diff --git a/AGENTS.md b/AGENTS.md index 3b928c6..51c9607 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -81,7 +81,7 @@ RDP frame presentation latency (regression fix, 2026-11-23): pure repaint-wave d ## Full Screen Connection Bar -`Views/FullScreenConnectionBar.axaml(.cs)` is the mstsc-style floating bar shown at the top centre of a full screen window. It is hosted by `Views/MainWindow.axaml` (bound to `MainWindowViewModel.IsTerminalFullScreen`, endpoint `SelectedTab.Session.Host`, quality `SelectedTab.Rdp.LinkQualityLevel`, `IsQualityVisible=SelectedTab.IsRdpSession`), `Views/DetachedTabWindow.axaml` (bound to the tab view model), and `Views/RdpMonitorWindow.axaml`. Hosts wire `MinimizeRequested` / `RestoreRequested` / `CloseRequested` / `PinnedChanged` (and workspace/multi-monitor events where applicable). +`Views/FullScreenConnectionBar.axaml(.cs)` is the mstsc-style floating bar shown at the top centre of a full screen window. It is hosted by `Views/MainWindow.axaml` (bound to `MainWindowViewModel.IsTerminalFullScreen`, endpoint `SelectedTab.Session.Host`, quality `SelectedTab.Rdp.LinkQualityLevel`, `IsQualityVisible=SelectedTab.IsRdpSession`), `Views/DetachedTabWindow.axaml` (bound to the tab view model), `Views/RdpWorkspaceWindow.axaml`, and `Views/RdpMonitorWindow.axaml`. Hosts wire `MinimizeRequested` / `RestoreRequested` / `CloseRequested` / `PinnedChanged` (and workspace/multi-monitor events where applicable). Behaviour that must not regress: @@ -92,7 +92,7 @@ Behaviour that must not regress: - The quality bars are an estimate, not an RDP capability: `RdpViewModel` times a bare TCP connect to the session endpoint every 10 s while connected and maps ≤50 ms/≤100 ms/≤200 ms/longer to 4/3/2/1 bars (`LinkQualityLevel`); 0 means unknown/disconnected. RDP exposes no signal strength, and a full reconnect probe must never be used. - Minimize from the bar leaves the full screen presentation, so the host must restore it when the window comes back: `MainWindow` uses `_restoreFullScreenAfterMinimize` plus `OnMainWindowPropertyChanged`; `DetachedTabWindow` needs `_restoreFullScreenAfterMinimize` / `_restoreKeepTaskbarAfterMinimize` and the `_suppressPresentationRestore` guard, because leaving the taskbar-visible mode changes `WindowState` and would otherwise look like a user restore. Close maps to `CloseTab(SelectedTab)` in the main window and `Close()` in a detached window - never to shutting down the application. - **Both full screen modes must hide the drawn chrome, not just the title bar.** `WindowState.FullScreen` only drops the native frame; AtomUI draws its title bar (`IsTitleBarVisible`) inside the client area. `Views/KeepTaskbarFullScreen.cs` owns that: `Enter()` hides the title bar before maximizing, the immersive path calls `HideTitleBar()`. -- **AtomUI 6.3.0's built-in full-screen title bar must stay disabled via `FullScreenTitleBarMode="Hidden"`.** AtomUI 6.3.0 removed `FullscreenHeaderFrame` from `WindowDrawnDecorationsTheme` and introduced `Window.FullScreenTitleBarMode` (default `AutoHide`) inside `WindowChromeLayer`. Every window hosting `FullScreenConnectionBar` (`MainWindow.axaml`, `DetachedTabWindow.axaml`, `RdpMonitorWindow.axaml`) must set `FullScreenTitleBarMode="Hidden"` so AtomUI never activates its built-in full-screen bar or moves `TitleBar` between `NormalSlotTitleBar` and `FullScreenSlotContent`. +- **AtomUI 6.3.0's built-in full-screen title bar must stay disabled via `FullScreenTitleBarMode="Hidden"`.** AtomUI 6.3.0 removed `FullscreenHeaderFrame` from `WindowDrawnDecorationsTheme` and introduced `Window.FullScreenTitleBarMode` (default `AutoHide`) inside `WindowChromeLayer`. Every window hosting `FullScreenConnectionBar` (`MainWindow.axaml`, `DetachedTabWindow.axaml`, `RdpWorkspaceWindow.axaml`, `RdpMonitorWindow.axaml`) must set `FullScreenTitleBarMode="Hidden"` so AtomUI never activates its built-in full-screen bar or moves `TitleBar` between `NormalSlotTitleBar` and `FullScreenSlotContent`. - **Keep `FullScreenConnectionBar` as a dedicated control rather than replacing it with `Window.FullScreenTitleBar`.** `Window.FullScreenTitleBar` only activates for `WindowState.FullScreen`, whereas CxShell needs the same bar in taskbar-visible maximized mode (`KeepTaskbarFullScreen`) and `RdpMonitorWindow` borderless mode, with the centred 8 px / 500 ms mstsc hot-zone, RDP link quality, pin persistence, multi-monitor popup lock, workspace tab switching, and drag-restore. - `KeepTaskbarFullScreen` owns `HideTitleBar`/`RestoreTitleBar` and `HideDecorations`/`RestoreDecorations` (`Window.WindowDecorations = None`, previous values saved once). Both helpers are idempotent so switching between "keep taskbar" and immersive full screen never loses the original state. Restore them on every exit path (after leaving full screen, never before), including an external takeover (window manager shortcut, native caption button): `MainWindow.OnMainWindowPropertyChanged` and `DetachedTabWindow.OnWindowPropertyChanged` restore the chrome whenever the window ends up outside full screen without `_keepTaskbarFullScreen.IsActive`. Never bind `IsTitleBarVisible` or `WindowDecorations` from XAML. diff --git a/Controls/DataGridSourceAdapter.cs b/Controls/DataGridSourceAdapter.cs index 0f7728a..9b7b639 100644 --- a/Controls/DataGridSourceAdapter.cs +++ b/Controls/DataGridSourceAdapter.cs @@ -1,9 +1,11 @@ using System.Collections; using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.CompilerServices; using AtomUI.Desktop.Controls; using Avalonia.Data; +using CxShell.Models; namespace CxShell.Controls; @@ -12,11 +14,15 @@ namespace CxShell.Controls; /// keeps the source's row keys mapped to the application's item instances. /// This is deliberately a data-source helper, not a replacement DataGrid. /// -public sealed class DataGridSourceAdapter : IDisposable +public sealed class DataGridSourceAdapter<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] T> : IDisposable { + private static readonly string[] NestedKeyPropertyNames = ["Session", "Entry", "Recording"]; + private static readonly string[] DirectKeyPropertyNames = ["Id", "Key", "FullPath", "Path", "Name"]; private static readonly IComparer ObjectComparer = Comparer.Create(CompareValues); private readonly IReadOnlyList _items; private readonly Dictionary _itemsByKey = new(); + private readonly (string Name, PropertyInfo Property)? _nestedKeyProperty; + private readonly (string Name, PropertyInfo Property)[] _directKeyProperties; private readonly DataGridLocalSource _source; private bool _disposed; @@ -26,14 +32,34 @@ public DataGridSourceAdapter(IReadOnlyList items, bool snapshot = false) _items = snapshot ? items.ToArray() : items; var descriptor = DataGridLocalSourceDescriptor.For(GetRowKey); + var propertiesByName = new Dictionary(StringComparer.Ordinal); foreach (var property in typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (property.GetMethod == null || property.GetIndexParameters().Length != 0) continue; + propertiesByName.TryAdd(property.Name, property); AddReflectedField(descriptor, property); } + foreach (var nestedName in NestedKeyPropertyNames) + { + if (propertiesByName.TryGetValue(nestedName, out var nestedProp)) + { + _nestedKeyProperty = (nestedName, nestedProp); + break; + } + } + + var directProps = new List<(string Name, PropertyInfo Property)>(DirectKeyPropertyNames.Length); + foreach (var keyName in DirectKeyPropertyNames) + { + if (propertiesByName.TryGetValue(keyName, out var directProp)) + directProps.Add((keyName, directProp)); + } + + _directKeyProperties = directProps.ToArray(); + _source = DataGridLocalSource.Create( _items, descriptor, @@ -257,28 +283,35 @@ private static bool SupportsScalar(Type type) _ => null }; - private static string GetStableKeyText(T item) + private string GetStableKeyText(T item) { if (item == null) return "null"; - var type = item.GetType(); - foreach (var nestedPropertyName in new[] { "Session", "Entry", "Recording" }) + var typeName = item.GetType().FullName; + if (_nestedKeyProperty is { } nestedProp) { - var nested = type.GetProperty(nestedPropertyName, BindingFlags.Public | BindingFlags.Instance)?.GetValue(item); - var nestedId = nested?.GetType().GetProperty("Id", BindingFlags.Public | BindingFlags.Instance)?.GetValue(nested); + var nested = nestedProp.Property.GetValue(item); + var nestedId = TryGetNestedId(nested); if (nestedId != null) - return $"{type.FullName}:{nestedPropertyName}:{nestedId}:{RuntimeHelpers.GetHashCode(item)}"; + return $"{typeName}:{nestedProp.Name}:{nestedId}:{RuntimeHelpers.GetHashCode(item)}"; } - foreach (var propertyName in new[] { "Id", "Key", "FullPath", "Path", "Name" }) + foreach (var (propertyName, property) in _directKeyProperties) { - var property = type.GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance); - var value = property?.GetValue(item); + var value = property.GetValue(item); if (value != null && !string.IsNullOrWhiteSpace(value.ToString())) - return $"{type.FullName}:{propertyName}:{value}:{RuntimeHelpers.GetHashCode(item)}"; + return $"{typeName}:{propertyName}:{value}:{RuntimeHelpers.GetHashCode(item)}"; } - return $"{type.FullName}:{RuntimeHelpers.GetHashCode(item)}"; + return $"{typeName}:{RuntimeHelpers.GetHashCode(item)}"; } + + private static object? TryGetNestedId(object? nested) => nested switch + { + SessionInfo session => session.Id, + ConnectionAuditEntry entry => entry.Id, + SessionRecording recording => recording.Id, + _ => null + }; } diff --git a/CxShell.Tests/AgentRuntimeTestJsonInitializer.cs b/CxShell.Tests/AgentRuntimeTestJsonInitializer.cs new file mode 100644 index 0000000..22bcd3b --- /dev/null +++ b/CxShell.Tests/AgentRuntimeTestJsonInitializer.cs @@ -0,0 +1,24 @@ +using System.Runtime.CompilerServices; +using System.Text.Json; +using System.Text.Json.Serialization.Metadata; +using CxShell.Services; + +namespace CxShell.Tests; + +internal static class AgentRuntimeTestJsonInitializer +{ + private static readonly JsonSerializerOptions CamelCaseTestOptions = new() + { + PropertyNamingPolicy = JsonNamingPolicy.CamelCase, + TypeInfoResolver = JsonTypeInfoResolver.Combine( + AppCamelCaseJsonContext.Default, + new DefaultJsonTypeInfoResolver()) + }; + + [ModuleInitializer] + internal static void Initialize() + { + AppJsonOptions.TestCamelCaseTypeInfoFallback = + static type => CamelCaseTestOptions.GetTypeInfo(type); + } +} diff --git a/CxShell.Tests/CxShell.Tests.csproj b/CxShell.Tests/CxShell.Tests.csproj index f7b5222..c4b0a4e 100644 --- a/CxShell.Tests/CxShell.Tests.csproj +++ b/CxShell.Tests/CxShell.Tests.csproj @@ -5,6 +5,7 @@ enable false true + true diff --git a/CxShell.Tests/SshNetX11ApiSurfaceTests.cs b/CxShell.Tests/SshNetX11ApiSurfaceTests.cs index 4cb2cab..15e2b8e 100644 --- a/CxShell.Tests/SshNetX11ApiSurfaceTests.cs +++ b/CxShell.Tests/SshNetX11ApiSurfaceTests.cs @@ -26,4 +26,52 @@ public void X11RequestIsNotExposedThroughSupportedSshClientApi() Assert.True(requestMethod!.IsPublic); Assert.False(publicClientHasX11EntryPoint); } + + [Fact] + public void ShellStreamAndDescriptorTargetsExistForAotAndAgentForwarding() + { + MethodInfo? changeWindowSize = typeof(ShellStream).GetMethod( + nameof(ShellStream.ChangeWindowSize), + BindingFlags.Public | BindingFlags.Instance, + binder: null, + types: [typeof(uint), typeof(uint), typeof(uint), typeof(uint)], + modifiers: null); + Assert.NotNull(changeWindowSize); + Assert.True(changeWindowSize!.IsPublic); + + FieldInfo? channelField = typeof(ShellStream).GetField( + "_channel", + BindingFlags.Instance | BindingFlags.NonPublic); + Assert.NotNull(channelField); + + Assembly sshNetAssembly = typeof(SshClient).Assembly; + Type? channelType = sshNetAssembly.GetType("Renci.SshNet.Channels.Channel"); + Assert.NotNull(channelType); + Assert.NotNull(channelType!.GetField("_session", BindingFlags.Instance | BindingFlags.NonPublic)); + Assert.NotNull(channelType.GetProperty("RemoteChannelNumber", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)); + + Type? sessionType = sshNetAssembly.GetType("Renci.SshNet.Session"); + Assert.NotNull(sessionType); + foreach (string eventName in new[] + { + "ChannelOpenReceived", + "ChannelDataReceived", + "ChannelEofReceived", + "ChannelCloseReceived" + }) + { + Assert.NotNull(sessionType!.GetEvent(eventName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)); + } + + MethodInfo? sendMessage = sessionType! + .GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) + .FirstOrDefault(method => + method.Name.EndsWith("SendMessage", StringComparison.Ordinal) && + method.GetParameters() is [{ ParameterType.Name: "Message" }]); + Assert.NotNull(sendMessage); + + Type? messageEventArgsType = sshNetAssembly.GetType("Renci.SshNet.MessageEventArgs`1"); + Assert.NotNull(messageEventArgsType); + Assert.NotNull(messageEventArgsType!.GetProperty("Message", BindingFlags.Instance | BindingFlags.Public)); + } } diff --git a/CxShell.Tests/WindowsVirtualFileDragDropServiceTests.cs b/CxShell.Tests/WindowsVirtualFileDragDropServiceTests.cs new file mode 100644 index 0000000..32d520a --- /dev/null +++ b/CxShell.Tests/WindowsVirtualFileDragDropServiceTests.cs @@ -0,0 +1,162 @@ +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.Marshalling; +using System.Runtime.Versioning; +using System.Text; +using CxShell.Services; + +namespace CxShell.Tests; + +public sealed class WindowsVirtualFileDragDropServiceTests +{ + [Fact] + public unsafe void NativeStructSizesMatchWin32Abi() + { + Assert.Equal(592, sizeof(WindowsVirtualFileDragDropService.NativeFileDescriptor)); + Assert.Equal(IntPtr.Size == 8 ? 32 : 20, sizeof(WindowsVirtualFileDragDropService.NativeFormatEtc)); + Assert.Equal(IntPtr.Size * 3, sizeof(WindowsVirtualFileDragDropService.NativeStgMedium)); + Assert.Equal(IntPtr.Size == 8 ? 80 : 72, sizeof(WindowsVirtualFileDragDropService.NativeStatStg)); + } + + [Fact] + public unsafe void GeneratedComWrappersExposeDataObjectAndStreamRoundTripOnWindows() + { + if (!OperatingSystem.IsWindows()) + return; + + TestGeneratedComRoundTrip(); + } + + [SupportedOSPlatform("windows")] + private static unsafe void TestGeneratedComRoundTrip() + { + var payload = "hello-virtual-drag"u8.ToArray(); + var file = new VirtualDragFile( + "remote-note.txt", + payload.Length, + new DateTime(2026, 11, 24, 8, 0, 0, DateTimeKind.Utc), + () => new MemoryStream(payload)); + + var dataObjectObj = WindowsVirtualFileDragDropService.CreateDataObjectForTest([file]); + var dropSourceObj = WindowsVirtualFileDragDropService.CreateDropSourceForTest(); + + var dataObjectPtr = WindowsVirtualFileDragDropService.ComWrappers.GetOrCreateComInterfaceForObject( + dataObjectObj, + CreateComInterfaceFlags.None); + var dropSourcePtr = WindowsVirtualFileDragDropService.ComWrappers.GetOrCreateComInterfaceForObject( + dropSourceObj, + CreateComInterfaceFlags.None); + + try + { + var dataObject = (WindowsVirtualFileDragDropService.INativeDataObject) + WindowsVirtualFileDragDropService.ComWrappers.GetOrCreateObjectForComInstance( + dataObjectPtr, + CreateObjectFlags.None); + var asyncOp = (WindowsVirtualFileDragDropService.IAsyncOperation)dataObject; + var dropSource = (WindowsVirtualFileDragDropService.IDropSource) + WindowsVirtualFileDragDropService.ComWrappers.GetOrCreateObjectForComInstance( + dropSourcePtr, + CreateObjectFlags.None); + + Assert.Equal(WindowsVirtualFileDragDropService.SOk, asyncOp.SetAsyncMode(true)); + Assert.Equal(WindowsVirtualFileDragDropService.SOk, asyncOp.GetAsyncMode(out var isAsync)); + Assert.True(isAsync); + + Assert.Equal( + WindowsVirtualFileDragDropService.DragDropSDrop, + dropSource.QueryContinueDrag(false, 0)); + Assert.Equal( + WindowsVirtualFileDragDropService.DragDropSCancel, + dropSource.QueryContinueDrag(true, WindowsVirtualFileDragDropService.MkLButton)); + Assert.Equal( + WindowsVirtualFileDragDropService.DragDropSUseDefaultCursors, + dropSource.GiveFeedback(WindowsVirtualFileDragDropService.DropEffectCopy)); + + Assert.Equal( + WindowsVirtualFileDragDropService.SOk, + dataObject.EnumFormatEtc(WindowsVirtualFileDragDropService.DataDirGet, out var enumFormats)); + Assert.NotNull(enumFormats); + + var formatArray = new WindowsVirtualFileDragDropService.NativeFormatEtc[2]; + fixed (WindowsVirtualFileDragDropService.NativeFormatEtc* pFormats = formatArray) + { + // Passing null for pceltFetched when celt == 1 is valid in OLE and used by Explorer. + Assert.Equal(WindowsVirtualFileDragDropService.SOk, enumFormats!.Next(1, pFormats, null)); + uint fetched = 0; + Assert.Equal(WindowsVirtualFileDragDropService.SOk, enumFormats.Next(1, pFormats + 1, &fetched)); + Assert.Equal(1u, fetched); + } + + Assert.Equal(WindowsVirtualFileDragDropService.SOk, dataObject.QueryGetData(in formatArray[0])); + Assert.Equal(WindowsVirtualFileDragDropService.SOk, dataObject.QueryGetData(in formatArray[1])); + + Assert.Equal( + WindowsVirtualFileDragDropService.SOk, + dataObject.GetData(in formatArray[0], out var descriptorMedium)); + try + { + Assert.Equal(WindowsVirtualFileDragDropService.TymedHGlobal, descriptorMedium.tymed); + Assert.NotEqual(IntPtr.Zero, descriptorMedium.unionmember); + + var count = *(uint*)descriptorMedium.unionmember; + Assert.Equal(1u, count); + var descriptor = *(WindowsVirtualFileDragDropService.NativeFileDescriptor*)((byte*)descriptorMedium.unionmember + sizeof(uint)); + Assert.Equal((uint)payload.Length, descriptor.nFileSizeLow); + var nameSpan = new ReadOnlySpan(descriptor.cFileName, 260); + var nullIndex = nameSpan.IndexOf('\0'); + Assert.Equal("remote-note.txt", new string(nameSpan[..nullIndex])); + } + finally + { + if (descriptorMedium.unionmember != IntPtr.Zero) + Marshal.FreeHGlobal(descriptorMedium.unionmember); + } + + var contentFormat = formatArray[1]; + contentFormat.lindex = 0; + Assert.Equal( + WindowsVirtualFileDragDropService.SOk, + dataObject.GetData(in contentFormat, out var streamMedium)); + try + { + Assert.Equal(WindowsVirtualFileDragDropService.TymedIStream, streamMedium.tymed); + Assert.NotEqual(IntPtr.Zero, streamMedium.unionmember); + + var stream = (WindowsVirtualFileDragDropService.INativeStream) + WindowsVirtualFileDragDropService.ComWrappers.GetOrCreateObjectForComInstance( + streamMedium.unionmember, + CreateObjectFlags.None); + + WindowsVirtualFileDragDropService.NativeStatStg stat = default; + Assert.Equal(WindowsVirtualFileDragDropService.SOk, stream.Stat(&stat, 0)); + Assert.Equal((ulong)payload.Length, stat.cbSize); + + var readBuffer = new byte[64]; + uint bytesRead = 0; + fixed (byte* pRead = readBuffer) + { + Assert.Equal( + WindowsVirtualFileDragDropService.SOk, + stream.Read(pRead, (uint)readBuffer.Length, &bytesRead)); + } + + Assert.Equal((uint)payload.Length, bytesRead); + Assert.Equal("hello-virtual-drag", Encoding.UTF8.GetString(readBuffer, 0, (int)bytesRead)); + + ulong newPos = 0; + Assert.Equal(WindowsVirtualFileDragDropService.SOk, stream.Seek(0, 0, &newPos)); + Assert.Equal(0UL, newPos); + } + finally + { + if (streamMedium.unionmember != IntPtr.Zero) + Marshal.Release(streamMedium.unionmember); + } + } + finally + { + Marshal.Release(dataObjectPtr); + Marshal.Release(dropSourcePtr); + } + } +} diff --git a/CxShell.csproj b/CxShell.csproj index e61fa14..b16b57a 100644 --- a/CxShell.csproj +++ b/CxShell.csproj @@ -20,6 +20,32 @@ true + + false + false + true + + + + + + + + + + + + + + + + + + + + + + @@ -93,11 +119,11 @@ - + - + diff --git a/ILLink.Descriptors.xml b/ILLink.Descriptors.xml new file mode 100644 index 0000000..beab0cc --- /dev/null +++ b/ILLink.Descriptors.xml @@ -0,0 +1,29 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Models/SessionInfo.cs b/Models/SessionInfo.cs index e08d924..fa28401 100644 --- a/Models/SessionInfo.cs +++ b/Models/SessionInfo.cs @@ -627,6 +627,20 @@ public int SshMonitorRefreshIntervalSeconds public string RdpColorQuality { get; set; } = "32"; /// Preferred RDP security mode: Auto, Negotiate, NLA, TLS or RDP. public string RdpSecurityMode { get; set; } = "Auto"; + /// RDP window mode: Default (main window tab), MultiTab (standalone multi-tab RDP window), or Standalone (detached single-session window with multi-monitor support). + public string RdpWindowMode { get; set; } = "Default"; + public bool RdpOpenInStandaloneWindow { get; set; } + + public string ResolveEffectiveRdpWindowMode() + { + if (string.Equals(RdpWindowMode, "MultiTab", StringComparison.OrdinalIgnoreCase)) + return "MultiTab"; + if (string.Equals(RdpWindowMode, "Standalone", StringComparison.OrdinalIgnoreCase)) + return "Standalone"; + if (string.Equals(RdpWindowMode, "Default", StringComparison.OrdinalIgnoreCase) && RdpOpenInStandaloneWindow) + return "MultiTab"; + return RdpOpenInStandaloneWindow ? "MultiTab" : "Default"; + } public bool RdpApplyKeyCombinations { get; set; } = true; public bool RdpSyncLockKeys { get; set; } = true; public bool RdpEnableClipboardLock { get; set; } = true; diff --git a/Services/Agent/AgentAuditLog.cs b/Services/Agent/AgentAuditLog.cs index a7333ff..3bba415 100644 --- a/Services/Agent/AgentAuditLog.cs +++ b/Services/Agent/AgentAuditLog.cs @@ -99,7 +99,7 @@ private void LoadFromStore() if (string.IsNullOrWhiteSpace(json)) return; - var entries = JsonSerializer.Deserialize>(json, CxShell.Services.AppJsonOptions.Default); + var entries = JsonSerializer.Deserialize(json, AppJsonContext.Default.ListAgentAuditEntry); if (entries == null) return; @@ -121,7 +121,7 @@ private void SaveToStoreLocked() return; try { - var json = JsonSerializer.Serialize(_entries.Take(MaximumEntries).ToArray(), CxShell.Services.AppJsonOptions.Default); + var json = JsonSerializer.Serialize(_entries.Take(MaximumEntries).ToArray(), AppJsonContext.Default.AgentAuditEntryArray); var encrypted = PasswordEncryptionService.Encrypt(json); _store.Write("agent_audit", "entries", encrypted); } @@ -139,7 +139,7 @@ private void SaveToStoreLocked() try { - return JsonSerializer.Deserialize>(json, CxShell.Services.AppJsonOptions.Default); + return JsonSerializer.Deserialize(json, AppJsonContext.Default.ListAgentAuditEntry); } catch (JsonException) { diff --git a/Services/Agent/AgentConversationHistoryStore.cs b/Services/Agent/AgentConversationHistoryStore.cs index 27e970e..0e512a2 100644 --- a/Services/Agent/AgentConversationHistoryStore.cs +++ b/Services/Agent/AgentConversationHistoryStore.cs @@ -72,8 +72,6 @@ public interface IAgentConversationHistoryStore /// internal static class LegacyAgentConversationHistoryReader { - private static readonly JsonSerializerOptions JsonOptions = AppJsonOptions.CamelCase; - public static bool TryLoad( string filePath, out IReadOnlyList conversations) @@ -88,7 +86,7 @@ public static bool TryLoad( if (string.IsNullOrWhiteSpace(json)) return false; - var parsed = JsonSerializer.Deserialize>(json, JsonOptions); + var parsed = JsonSerializer.Deserialize(json, AppCamelCaseJsonContext.Default.ListAgentConversationHistoryRecord); if (parsed == null) return false; diff --git a/Services/Agent/AgentRunCoordinator.cs b/Services/Agent/AgentRunCoordinator.cs index 349f8e9..d9101cb 100644 --- a/Services/Agent/AgentRunCoordinator.cs +++ b/Services/Agent/AgentRunCoordinator.cs @@ -1,5 +1,6 @@ using System.Collections.Concurrent; using System.Text.Json; +using System.Text.Json.Nodes; using System.Text; using CxShell.Models; using CxShell.Services.Agent.OpenCoworkRuntime; @@ -55,562 +56,443 @@ public sealed class AgentRunCoordinator : IAgentRunCoordinator, IDisposable public static readonly TimeSpan CredentialRequestLifetime = TimeSpan.FromMinutes(5); private const int MaximumCredentialCharacters = 4096; - private static readonly object OptionalSessionIdSchema = new - { - type = "string", - format = "uuid", - description = "Optional runtime sessionId from list_connected_sessions. When omitted, use the session selected for this Agent run." - }; - private static readonly object RemotePathSchema = new - { - type = "string", - minLength = 1, - maxLength = AgentReadOnlyToolCatalog.MaximumRemotePathLength, - description = "Remote path to inspect. Credential and private-key paths are blocked by CxShell." - }; + private static readonly JsonObject OptionalSessionIdSchema = CreateStringSchema( + format: "uuid", + description: "Optional runtime sessionId from list_connected_sessions. When omitted, use the session selected for this Agent run."); + private static readonly JsonObject RemotePathSchema = CreateStringSchema( + minLength: 1, + maxLength: AgentReadOnlyToolCatalog.MaximumRemotePathLength, + description: "Remote path to inspect. Credential and private-key paths are blocked by CxShell."); private static readonly AgentToolDefinition SessionCommandTool = new( SessionCommandToolName, "Send one safe shell command to the SSH session selected for this run. " + "The command is still checked by CxShell's permission policy.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new - { - sessionId = OptionalSessionIdSchema, - command = new - { - type = "string", - description = "The shell command to send to the remote SSH terminal." - }, - timeoutMs = new - { - type = "integer", - minimum = 100, - maximum = (int)AgentSessionGateway.MaximumCommandTimeout.TotalMilliseconds, - description = "Maximum time to wait while dispatching the command." - } + CreateObjectSchema( + props => + { + props["sessionId"] = OptionalSessionIdSchema.DeepClone(); + props["command"] = CreateStringSchema( + description: "The shell command to send to the remote SSH terminal."); + props["timeoutMs"] = CreateIntegerSchema( + 100, + (int)AgentSessionGateway.MaximumCommandTimeout.TotalMilliseconds, + description: "Maximum time to wait while dispatching the command."); }, - required = new[] { "command" }, - additionalProperties = false - })); + required: ["command"])); private static readonly AgentToolDefinition SessionInfoTool = new( SessionInfoToolName, "Read connection metadata for the selected SSH session. This does not run a remote command and never returns secrets.", - JsonSerializer.SerializeToElement(new + CreateObjectSchema(props => { - type = "object", - properties = new - { - sessionId = OptionalSessionIdSchema - }, - additionalProperties = false + props["sessionId"] = OptionalSessionIdSchema.DeepClone(); })); private static readonly AgentToolDefinition SearchTerminalTool = new( SearchTerminalToolName, "Search the captured text of the selected SSH terminal without sending a command. " + "Returns bounded matching lines and never changes the remote host.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new - { - sessionId = OptionalSessionIdSchema, - query = new - { - type = "string", - minLength = 1, - maxLength = 256, - description = "Case-insensitive text to find in terminal scrollback." - }, - maxResults = new - { - type = "integer", - minimum = 1, - maximum = 50, - @default = 20 - } + CreateObjectSchema( + props => + { + props["sessionId"] = OptionalSessionIdSchema.DeepClone(); + props["query"] = CreateStringSchema( + minLength: 1, + maxLength: 256, + description: "Case-insensitive text to find in terminal scrollback."); + props["maxResults"] = CreateIntegerSchema(1, 50, defaultValue: 20); }, - required = new[] { "query" }, - additionalProperties = false - })); + required: ["query"])); private static readonly AgentToolDefinition WorkingDirectoryTool = new( AgentReadOnlyToolCatalog.WorkingDirectoryToolName, "Read the remote shell working directory for the selected SSH session.", - JsonSerializer.SerializeToElement(new + CreateObjectSchema(props => { - type = "object", - properties = new { sessionId = OptionalSessionIdSchema }, - additionalProperties = false + props["sessionId"] = OptionalSessionIdSchema.DeepClone(); })); private static readonly AgentToolDefinition ListRemoteDirectoryTool = new( AgentReadOnlyToolCatalog.ListRemoteDirectoryToolName, "List a bounded remote directory through the SSH session's SFTP channel. This is read-only.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new - { - sessionId = OptionalSessionIdSchema, - path = RemotePathSchema, - maxEntries = new - { - type = "integer", - minimum = 1, - maximum = AgentReadOnlyToolCatalog.MaximumRemoteDirectoryEntries, - @default = 100 - } + CreateObjectSchema( + props => + { + props["sessionId"] = OptionalSessionIdSchema.DeepClone(); + props["path"] = RemotePathSchema.DeepClone(); + props["maxEntries"] = CreateIntegerSchema( + 1, + AgentReadOnlyToolCatalog.MaximumRemoteDirectoryEntries, + defaultValue: 100); }, - required = new[] { "path" }, - additionalProperties = false - })); + required: ["path"])); private static readonly AgentToolDefinition StatRemotePathTool = new( AgentReadOnlyToolCatalog.StatRemotePathToolName, "Read metadata for one remote file or directory. This is read-only and credential paths are blocked.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new + CreateObjectSchema( + props => { - sessionId = OptionalSessionIdSchema, - path = RemotePathSchema + props["sessionId"] = OptionalSessionIdSchema.DeepClone(); + props["path"] = RemotePathSchema.DeepClone(); }, - required = new[] { "path" }, - additionalProperties = false - })); + required: ["path"])); private static readonly AgentToolDefinition ReadRemoteFileTool = new( AgentReadOnlyToolCatalog.ReadRemoteFileToolName, "Read a bounded number of lines from one remote text file. Credential and private-key paths are blocked.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new - { - sessionId = OptionalSessionIdSchema, - path = RemotePathSchema, - lines = new - { - type = "integer", - minimum = 1, - maximum = AgentReadOnlyToolCatalog.MaximumRemoteFileLines, - @default = 120 - }, - maxCharacters = new - { - type = "integer", - minimum = 1, - maximum = AgentReadOnlyToolCatalog.MaximumRemoteFileCharacters, - description = "Maximum UTF-8 text characters to read when the SFTP channel is available." - } + CreateObjectSchema( + props => + { + props["sessionId"] = OptionalSessionIdSchema.DeepClone(); + props["path"] = RemotePathSchema.DeepClone(); + props["lines"] = CreateIntegerSchema( + 1, + AgentReadOnlyToolCatalog.MaximumRemoteFileLines, + defaultValue: 120); + props["maxCharacters"] = CreateIntegerSchema( + 1, + AgentReadOnlyToolCatalog.MaximumRemoteFileCharacters, + description: "Maximum UTF-8 text characters to read when the SFTP channel is available."); }, - required = new[] { "path" }, - additionalProperties = false - })); + required: ["path"])); private static readonly AgentToolDefinition TerminalWriteTool = new( TerminalWriteToolName, "Write input to the visible SSH terminal for interactive programs such as vim, top, or a shell prompt. " + "This does not capture command output and must not be used for ordinary shell commands.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new - { - sessionId = OptionalSessionIdSchema, - input = new + CreateObjectSchema( + props => + { + props["sessionId"] = OptionalSessionIdSchema.DeepClone(); + props["input"] = CreateStringSchema( + minLength: 1, + maxLength: AgentSessionGateway.MaximumCommandLength, + description: "Text or key sequence to write to the visible terminal."); + props["appendLineEnding"] = new JsonObject { - type = "string", - minLength = 1, - maxLength = AgentSessionGateway.MaximumCommandLength, - description = "Text or key sequence to write to the visible terminal." - }, - appendLineEnding = new - { - type = "boolean", - @default = false, - description = "Append the configured terminal line ending after the input." - } + ["type"] = "boolean", + ["default"] = false, + ["description"] = "Append the configured terminal line ending after the input." + }; }, - required = new[] { "input" }, - additionalProperties = false - })); + required: ["input"])); private static readonly AgentToolDefinition ConnectedSessionListTool = new( ConnectedSessionListToolName, "List currently connected SSH sessions and their runtime IDs. This never opens a new session or returns credentials.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new { }, - additionalProperties = false - })); + CreateObjectSchema(static _ => { })); private static readonly AgentToolDefinition RunOnSessionsTool = new( RunOnSessionsToolName, "Run one shell command on an explicit list of currently connected SSH sessions. " + "Each target is isolated and returns its own status, output, exit code, and duration. " + "The operation is capped and requires one approval when any target command needs approval.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new + CreateObjectSchema( + props => { - sessionIds = new - { - type = "array", - minItems = 1, - maxItems = 16, - items = new { type = "string", format = "uuid" }, - description = "Runtime session IDs returned by list_connected_sessions." - }, - command = new - { - type = "string", - minLength = 1, - maxLength = AgentSessionGateway.MaximumCommandLength - }, - timeoutMs = new + props["sessionIds"] = new JsonObject { - type = "integer", - minimum = 100, - maximum = (int)AgentSessionGateway.MaximumCommandTimeout.TotalMilliseconds - } + ["type"] = "array", + ["minItems"] = 1, + ["maxItems"] = 16, + ["items"] = new JsonObject + { + ["type"] = "string", + ["format"] = "uuid" + }, + ["description"] = "Runtime session IDs returned by list_connected_sessions." + }; + props["command"] = CreateStringSchema( + minLength: 1, + maxLength: AgentSessionGateway.MaximumCommandLength); + props["timeoutMs"] = CreateIntegerSchema( + 100, + (int)AgentSessionGateway.MaximumCommandTimeout.TotalMilliseconds); }, - required = new[] { "sessionIds", "command" }, - additionalProperties = false - })); + required: ["sessionIds", "command"])); private static readonly AgentToolDefinition SavedSessionListTool = new( SavedSessionListToolName, "List saved SSH connection configurations, including configurations that are not currently open. " + "This never returns passwords or private key material.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new { }, - additionalProperties = false - })); + CreateObjectSchema(static _ => { })); private static readonly AgentToolDefinition OpenSessionTool = new( OpenSessionToolName, "Open a saved SSH configuration as a user-visible tab. Only configurations already saved by the user are accepted. " + "The user must approve this operation and the host may ask for confirmation or credentials.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new - { - savedSessionId = new - { - type = "string", - format = "uuid", - description = "The savedSessionId returned by list_saved_sessions." - }, - reason = new - { - type = "string", - minLength = 1, - maxLength = 500, - description = "Why this saved SSH connection is needed. The user will see this text." - }, - reuseConnected = new + CreateObjectSchema( + props => + { + props["savedSessionId"] = CreateStringSchema( + format: "uuid", + description: "The savedSessionId returned by list_saved_sessions."); + props["reason"] = CreateStringSchema( + minLength: 1, + maxLength: 500, + description: "Why this saved SSH connection is needed. The user will see this text."); + props["reuseConnected"] = new JsonObject { - type = "boolean", - @default = true, - description = "Reuse an already-connected tab for the same saved configuration when possible." - } + ["type"] = "boolean", + ["default"] = true, + ["description"] = "Reuse an already-connected tab for the same saved configuration when possible." + }; }, - required = new[] { "savedSessionId", "reason" }, - additionalProperties = false - })); + required: ["savedSessionId", "reason"])); private static readonly AgentToolDefinition CloseSessionTool = new( CloseSessionToolName, "Close a user-visible SSH tab previously opened by this Agent run. User-created tabs cannot be closed by the Agent.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new + CreateObjectSchema( + props => { - sessionId = new - { - type = "string", - format = "uuid", - description = "The runtime sessionId returned by open_session." - } + props["sessionId"] = CreateStringSchema( + format: "uuid", + description: "The runtime sessionId returned by open_session."); }, - required = new[] { "sessionId" }, - additionalProperties = false - })); + required: ["sessionId"])); private static readonly AgentToolDefinition DiagnosticRunTool = new( DiagnosticRunToolName, "Run one fixed, read-only CxShell diagnostic on the selected SSH session. " + "Use this for system, disk, network, services, processes, or all. Do not use it to change the server.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new + CreateObjectSchema( + props => { - sessionId = OptionalSessionIdSchema, - scope = new - { - type = "string", - @enum = AgentDiagnosticCatalog.Scopes, - description = "The read-only diagnostic scope to collect." - } + props["sessionId"] = OptionalSessionIdSchema.DeepClone(); + props["scope"] = CreateStringSchema( + enumValues: AgentDiagnosticCatalog.Scopes, + description: "The read-only diagnostic scope to collect."); }, - required = new[] { "scope" }, - additionalProperties = false - })); + required: ["scope"])); private static readonly AgentToolDefinition RunbookRunTool = new( RunbookRunToolName, "Run one fixed, read-only CxShell troubleshooting workflow. Use ssh for SSH service and port checks, " + "rdp for Windows Remote Desktop checks, or health for a complete host overview.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new + CreateObjectSchema( + props => { - sessionId = OptionalSessionIdSchema, - scope = new - { - type = "string", - @enum = AgentDiagnosticRunbookCatalog.Runbooks, - description = "The fixed read-only troubleshooting workflow to run." - } + props["sessionId"] = OptionalSessionIdSchema.DeepClone(); + props["scope"] = CreateStringSchema( + enumValues: AgentDiagnosticRunbookCatalog.Runbooks, + description: "The fixed read-only troubleshooting workflow to run."); }, - required = new[] { "scope" }, - additionalProperties = false - })); + required: ["scope"])); private static readonly AgentToolDefinition FleetDiagnosticTool = new( FleetDiagnosticToolName, "Inspect all currently connected SSH sessions with one fixed, read-only diagnostic. " + "Use this for a multi-server disk, network, services, processes, system, or health check. " + "It never connects to saved sessions automatically.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new + CreateObjectSchema( + props => { - scope = new - { - type = "string", - @enum = AgentDiagnosticCatalog.Scopes, - description = "The fixed read-only diagnostic scope for every currently connected SSH session." - } + props["scope"] = CreateStringSchema( + enumValues: AgentDiagnosticCatalog.Scopes, + description: "The fixed read-only diagnostic scope for every currently connected SSH session."); }, - required = new[] { "scope" }, - additionalProperties = false - })); + required: ["scope"])); private static readonly AgentToolDefinition LogsTool = new( AgentReadOnlyToolCatalog.LogsToolName, "Read a bounded tail of a known system, application, or security log. This is read-only and the log source is validated by CxShell.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new - { - sessionId = OptionalSessionIdSchema, - source = new - { - type = "string", - @enum = AgentReadOnlyToolCatalog.LogSources, - description = "Known log source to inspect." - }, - lines = new - { - type = "integer", - minimum = 1, - maximum = 200, - description = "Maximum number of log lines." - } + CreateObjectSchema( + props => + { + props["sessionId"] = OptionalSessionIdSchema.DeepClone(); + props["source"] = CreateStringSchema( + enumValues: AgentReadOnlyToolCatalog.LogSources, + description: "Known log source to inspect."); + props["lines"] = CreateIntegerSchema( + 1, + 200, + description: "Maximum number of log lines."); }, - required = new[] { "source" }, - additionalProperties = false - })); + required: ["source"])); private static readonly AgentToolDefinition PortCheckTool = new( AgentReadOnlyToolCatalog.PortCheckToolName, "Check whether one TCP port is listening on the selected SSH host. This never changes remote state.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new - { - sessionId = OptionalSessionIdSchema, - port = new - { - type = "integer", - minimum = 1, - maximum = 65535, - description = "TCP port number." - } + CreateObjectSchema( + props => + { + props["sessionId"] = OptionalSessionIdSchema.DeepClone(); + props["port"] = CreateIntegerSchema( + 1, + 65535, + description: "TCP port number."); }, - required = new[] { "port" }, - additionalProperties = false - })); + required: ["port"])); private static readonly AgentToolDefinition ServiceDetailTool = new( AgentReadOnlyToolCatalog.ServiceDetailToolName, "Read details for one service using a validated service name. This is read-only.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new - { - sessionId = OptionalSessionIdSchema, - service = new - { - type = "string", - minLength = 1, - maxLength = 64, - description = "Service name; letters, numbers, '.', '@', ':', '_' and '-' are accepted." - } + CreateObjectSchema( + props => + { + props["sessionId"] = OptionalSessionIdSchema.DeepClone(); + props["service"] = CreateStringSchema( + minLength: 1, + maxLength: 64, + description: "Service name; letters, numbers, '.', '@', ':', '_' and '-' are accepted."); }, - required = new[] { "service" }, - additionalProperties = false - })); + required: ["service"])); private static readonly AgentToolDefinition FilePreviewTool = new( AgentReadOnlyToolCatalog.FilePreviewToolName, "Preview a bounded portion of one known configuration or log file. Arbitrary paths are not accepted.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new - { - sessionId = OptionalSessionIdSchema, - target = new - { - type = "string", - @enum = AgentReadOnlyToolCatalog.FileTargets, - description = "Known file target." - }, - lines = new - { - type = "integer", - minimum = 1, - maximum = 200, - description = "Maximum number of lines." - } + CreateObjectSchema( + props => + { + props["sessionId"] = OptionalSessionIdSchema.DeepClone(); + props["target"] = CreateStringSchema( + enumValues: AgentReadOnlyToolCatalog.FileTargets, + description: "Known file target."); + props["lines"] = CreateIntegerSchema( + 1, + 200, + description: "Maximum number of lines."); }, - required = new[] { "target" }, - additionalProperties = false - })); + required: ["target"])); private static readonly AgentToolDefinition PackageQueryTool = new( AgentReadOnlyToolCatalog.PackageQueryToolName, "Look up one installed package or executable without changing the selected SSH host. " + "The package name is validated and the platform-specific query is supplied by CxShell.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new - { - sessionId = OptionalSessionIdSchema, - name = new - { - type = "string", - minLength = 1, - maxLength = 100, - description = "Package or executable name to query." - } + CreateObjectSchema( + props => + { + props["sessionId"] = OptionalSessionIdSchema.DeepClone(); + props["name"] = CreateStringSchema( + minLength: 1, + maxLength: 100, + description: "Package or executable name to query."); }, - required = new[] { "name" }, - additionalProperties = false - })); + required: ["name"])); private static readonly AgentToolDefinition RuntimeCheckTool = new( AgentReadOnlyToolCatalog.RuntimeCheckToolName, "Check installed Java, Python, .NET, Node.js, or PowerShell runtime versions. " + "Use all to check every supported runtime; this is read-only.", - JsonSerializer.SerializeToElement(new + CreateObjectSchema(props => { - type = "object", - properties = new - { - sessionId = OptionalSessionIdSchema, - runtime = new - { - type = "string", - @enum = AgentReadOnlyToolCatalog.RuntimeNames, - @default = "all", - description = "Runtime to check, or all for the complete supported list." - } - }, - additionalProperties = false + props["sessionId"] = OptionalSessionIdSchema.DeepClone(); + props["runtime"] = CreateStringSchema( + enumValues: AgentReadOnlyToolCatalog.RuntimeNames, + defaultValue: "all", + description: "Runtime to check, or all for the complete supported list."); })); private static readonly AgentToolDefinition DiskCleanupAdviceTool = new( AgentReadOnlyToolCatalog.DiskCleanupAdviceToolName, "Analyze disk usage and likely log or temporary-file cleanup candidates without deleting anything. " + "Use summary, logs, temp, or all.", - JsonSerializer.SerializeToElement(new + CreateObjectSchema(props => { - type = "object", - properties = new - { - sessionId = OptionalSessionIdSchema, - scope = new - { - type = "string", - @enum = AgentReadOnlyToolCatalog.CleanupScopes, - @default = "all", - description = "Read-only analysis area." - } - }, - additionalProperties = false + props["sessionId"] = OptionalSessionIdSchema.DeepClone(); + props["scope"] = CreateStringSchema( + enumValues: AgentReadOnlyToolCatalog.CleanupScopes, + defaultValue: "all", + description: "Read-only analysis area."); })); private static readonly AgentToolDefinition WebSearchTool = new( "web_search", "Search the public web through the configured SearXNG instance. This is read-only and returns bounded results.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new + CreateObjectSchema( + props => { - query = new - { - type = "string", - minLength = 1, - maxLength = 500, - description = "The public web search query. Do not include passwords, tokens, or private host data." - } + props["query"] = CreateStringSchema( + minLength: 1, + maxLength: 500, + description: "The public web search query. Do not include passwords, tokens, or private host data."); }, - required = new[] { "query" }, - additionalProperties = false - })); + required: ["query"])); private static readonly AgentToolDefinition WebFetchTool = new( "web_fetch", "Fetch bounded text from one HTTP(S) URL. Redirects, binary content, and private addresses are blocked by default.", - JsonSerializer.SerializeToElement(new - { - type = "object", - properties = new + CreateObjectSchema( + props => { - url = new - { - type = "string", - maxLength = 2048, - description = "The HTTP(S) URL to read." - } + props["url"] = CreateStringSchema( + maxLength: 2048, + description: "The HTTP(S) URL to read."); }, - required = new[] { "url" }, - additionalProperties = false - })); + required: ["url"])); + + private static JsonObject CreateStringSchema( + string? format = null, + string? description = null, + int? minLength = null, + int? maxLength = null, + IReadOnlyList? enumValues = null, + string? defaultValue = null) + { + var schema = new JsonObject { ["type"] = "string" }; + if (format != null) + schema["format"] = format; + if (minLength.HasValue) + schema["minLength"] = minLength.Value; + if (maxLength.HasValue) + schema["maxLength"] = maxLength.Value; + if (enumValues != null) + { + var array = new JsonArray(); + foreach (var value in enumValues) + array.Add((JsonNode?)JsonValue.Create(value)); + schema["enum"] = array; + } + if (defaultValue != null) + schema["default"] = defaultValue; + if (description != null) + schema["description"] = description; + return schema; + } + + private static JsonObject CreateIntegerSchema( + int minimum, + int maximum, + int? defaultValue = null, + string? description = null) + { + var schema = new JsonObject + { + ["type"] = "integer", + ["minimum"] = minimum, + ["maximum"] = maximum + }; + if (defaultValue.HasValue) + schema["default"] = defaultValue.Value; + if (description != null) + schema["description"] = description; + return schema; + } + + private static JsonElement CreateObjectSchema( + Action configureProperties, + string[]? required = null) + { + var properties = new JsonObject(); + configureProperties(properties); + var schema = new JsonObject + { + ["type"] = "object", + ["properties"] = properties + }; + if (required is { Length: > 0 }) + { + var requiredArray = new JsonArray(); + foreach (var item in required) + requiredArray.Add((JsonNode?)JsonValue.Create(item)); + schema["required"] = requiredArray; + } + schema["additionalProperties"] = false; + return JsonSerializer.SerializeToElement(schema, AppCamelCaseJsonContext.Default.JsonObject); + } private readonly IAgentSessionGateway _gateway; private readonly Func _providerSettings; @@ -1320,12 +1202,12 @@ private async Task ExecuteAsync( var safeMessage = AgentSensitiveDataRedactor.Redact(TrimException(ex)); toolResult = new( false, - JsonSerializer.Serialize(new + new JsonObject { - message = "The tool failed before it returned a result.", - error = safeMessage, - errorType = "ToolExecutionException" - })); + ["message"] = "The tool failed before it returned a result.", + ["error"] = safeMessage, + ["errorType"] = "ToolExecutionException" + }.ToJsonString()); } finally { @@ -1901,23 +1783,23 @@ private async Task ExecuteToolAsync( if (string.Equals(toolCall.Name, ConnectedSessionListToolName, StringComparison.Ordinal)) { - return new( - true, - JsonSerializer.Serialize(new + var sessions = new JsonArray(); + foreach (var session in _gateway.GetSessions() + .Where(session => session.IsConnected && session.Protocol == SessionProtocol.SSH)) + { + sessions.Add((JsonNode)new JsonObject { - sessions = _gateway.GetSessions() - .Where(session => session.IsConnected && session.Protocol == SessionProtocol.SSH) - .Select(session => new - { - sessionId = session.SessionId.ToString("D"), - session.Name, - session.Host, - session.Port, - session.Username, - session.Platform, - session.IsConnected - }) - })); + ["sessionId"] = session.SessionId.ToString("D"), + ["Name"] = session.Name, + ["Host"] = session.Host, + ["Port"] = session.Port, + ["Username"] = session.Username, + ["Platform"] = session.Platform, + ["IsConnected"] = session.IsConnected + }); + } + + return new(true, new JsonObject { ["sessions"] = sessions }.ToJsonString()); } if (string.Equals(toolCall.Name, "web_search", StringComparison.Ordinal)) @@ -1953,18 +1835,20 @@ private async Task ExecuteToolAsync( if (!TryResolveToolSession(activeRun, toolCall.Arguments, out var session, out var sessionError)) return sessionError!; - return new(true, JsonSerializer.Serialize(new + return new( + true, + new JsonObject { - sessionId = session.SessionId.ToString("D"), - session.Name, - session.Protocol, - session.Host, - session.Port, - session.Username, - session.Platform, - session.IsConnected, - canExecuteCommands = session.CanExecuteCommands - })); + ["sessionId"] = session.SessionId.ToString("D"), + ["Name"] = session.Name, + ["Protocol"] = (int)session.Protocol, + ["Host"] = session.Host, + ["Port"] = session.Port, + ["Username"] = session.Username, + ["Platform"] = session.Platform, + ["IsConnected"] = session.IsConnected, + ["canExecuteCommands"] = session.CanExecuteCommands + }.ToJsonString()); } if (string.Equals(toolCall.Name, TerminalWriteToolName, StringComparison.Ordinal)) @@ -2138,23 +2022,24 @@ private async Task ExecuteSavedSessionListAsync( CancellationToken cancellationToken) { var sessions = await _gateway.ListSavedSessionsAsync(cancellationToken).ConfigureAwait(false); - return new( - true, - JsonSerializer.Serialize(new - { - sessions = sessions.Select(session => new - { - savedSessionId = session.SavedSessionId.ToString("D"), - session.Name, - session.Path, - session.Protocol, - session.Host, - session.Port, - session.Username, - session.IsOpen, - openSessionId = session.OpenSessionId?.ToString("D") - }) - })); + var sessionsArray = new JsonArray(); + foreach (var session in sessions) + { + sessionsArray.Add((JsonNode)new JsonObject + { + ["savedSessionId"] = session.SavedSessionId.ToString("D"), + ["Name"] = session.Name, + ["Path"] = session.Path, + ["Protocol"] = (int)session.Protocol, + ["Host"] = session.Host, + ["Port"] = session.Port, + ["Username"] = session.Username, + ["IsOpen"] = session.IsOpen, + ["openSessionId"] = session.OpenSessionId?.ToString("D") + }); + } + + return new(true, new JsonObject { ["sessions"] = sessionsArray }.ToJsonString()); } private AgentToolExecutionResult ExecuteSearchTerminal( @@ -2194,31 +2079,34 @@ private AgentToolExecutionResult ExecuteSearchTerminal( .Select((line, index) => new { Line = line, Number = index + 1 }) .Where(item => item.Line.Contains(query, StringComparison.OrdinalIgnoreCase)) .ToArray(); - var returnedMatches = matches - .Take(maxResults) - .Select(item => new + var matchesArray = new JsonArray(); + var returnedCount = 0; + foreach (var item in matches.Take(maxResults)) + { + matchesArray.Add((JsonNode)new JsonObject { - line = item.Number, - text = item.Line.Length <= 2048 ? item.Line : item.Line[..2048] + "..." - }) - .ToArray(); + ["line"] = item.Number, + ["text"] = item.Line.Length <= 2048 ? item.Line : item.Line[..2048] + "..." + }); + returnedCount++; + } return new( true, - JsonSerializer.Serialize(new - { - tool = SearchTerminalToolName, - sessionId = session.SessionId.ToString("D"), - query, - matchCount = matches.Length, - returnedCount = returnedMatches.Length, - hasMore = matches.Length > returnedMatches.Length, - textWasTruncated, - message = returnedMatches.Length == 0 + new JsonObject + { + ["tool"] = SearchTerminalToolName, + ["sessionId"] = session.SessionId.ToString("D"), + ["query"] = query, + ["matchCount"] = matches.Length, + ["returnedCount"] = returnedCount, + ["hasMore"] = matches.Length > returnedCount, + ["textWasTruncated"] = textWasTruncated, + ["message"] = returnedCount == 0 ? "No matching terminal lines were found." : $"Found {matches.Length} matching terminal line(s).", - matches = returnedMatches - })); + ["matches"] = matchesArray + }.ToJsonString()); } private async Task ExecuteCommandWithCredentialsAsync( @@ -2426,15 +2314,15 @@ private async Task ExecuteWebSearchAsync( var result = await _webAccess.SearchAsync(query, cancellationToken).ConfigureAwait(false); return new( result.Success, - JsonSerializer.Serialize(new - { - tool = "web_search", - success = result.Success, - query, - url = result.Url, - content = result.Success ? result.Content : null, - error = result.Error - })); + new JsonObject + { + ["tool"] = "web_search", + ["success"] = result.Success, + ["query"] = query, + ["url"] = result.Url, + ["content"] = result.Success ? result.Content : null, + ["error"] = result.Error + }.ToJsonString()); } private async Task ExecuteWebFetchAsync( @@ -2447,15 +2335,15 @@ private async Task ExecuteWebFetchAsync( var result = await _webAccess.FetchAsync(url, cancellationToken).ConfigureAwait(false); return new( result.Success, - JsonSerializer.Serialize(new - { - tool = "web_fetch", - success = result.Success, - url = result.Url, - content = result.Success ? result.Content : null, - error = result.Error, - statusCode = result.StatusCode - })); + new JsonObject + { + ["tool"] = "web_fetch", + ["success"] = result.Success, + ["url"] = result.Url, + ["content"] = result.Success ? result.Content : null, + ["error"] = result.Error, + ["statusCode"] = result.StatusCode + }.ToJsonString()); } private static bool TryReadStringToolArgument( @@ -2592,16 +2480,16 @@ commandRequest with return new( result.IsSuccess, - JsonSerializer.Serialize(new - { - tool = TerminalWriteToolName, - sessionId = request.SessionId.ToString("D"), - status = result.Status.ToString(), - executionState = result.ExecutionState.ToString(), - message = result.Message, - inputDelivered = result.IsSuccess, - durationMs = result.DurationMs - })); + new JsonObject + { + ["tool"] = TerminalWriteToolName, + ["sessionId"] = request.SessionId.ToString("D"), + ["status"] = result.Status.ToString(), + ["executionState"] = result.ExecutionState.ToString(), + ["message"] = result.Message, + ["inputDelivered"] = result.IsSuccess, + ["durationMs"] = result.DurationMs + }.ToJsonString()); } private async Task ExecuteRunOnSessionsAsync( @@ -2629,16 +2517,20 @@ private async Task ExecuteRunOnSessionsAsync( .ToArray(); if (missing.Length > 0) { + var unavailableIds = new JsonArray(); + foreach (var id in missing) + unavailableIds.Add((JsonNode?)JsonValue.Create(id.ToString("D"))); + return new( false, - JsonSerializer.Serialize(new + new JsonObject { - status = "rejected", - errorType = "SessionUnavailable", - message = "Every target must be a currently connected SSH session.", - unavailableSessionIds = missing.Select(id => id.ToString("D")), - retrySafe = true - })); + ["status"] = "rejected", + ["errorType"] = "SessionUnavailable", + ["message"] = "Every target must be a currently connected SSH session.", + ["unavailableSessionIds"] = unavailableIds, + ["retrySafe"] = true + }.ToJsonString()); } var targets = sessionIds @@ -2797,41 +2689,49 @@ firstRequest with : WithExecutionError(firstExecution.Result, firstExecution.Error), firstExecution.SensitiveInputs); - var orderedResults = targets - .Select(target => new - { - sessionId = target.SessionId.ToString("D"), - name = target.Name, - host = target.Host, - status = results[target.SessionId].Result.Status.ToString(), - executionState = results[target.SessionId].Result.ExecutionState.ToString(), - success = results[target.SessionId].Result.IsSuccess, - outcomeCertain = results[target.SessionId].Result.IsOutcomeCertain, - remoteCompletionConfirmed = results[target.SessionId].Result.RemoteCompletionConfirmed, - message = AgentSensitiveDataRedactor.Redact( - results[target.SessionId].Result.Message, - results[target.SessionId].SensitiveInputs), - output = LimitToolResultOutput(AgentSensitiveDataRedactor.Redact( - results[target.SessionId].Result.Output, - results[target.SessionId].SensitiveInputs)), - error = LimitToolResultOutput(AgentSensitiveDataRedactor.Redact( - results[target.SessionId].Result.Error, - results[target.SessionId].SensitiveInputs)), - exitCode = results[target.SessionId].Result.ExitCode, - durationMs = results[target.SessionId].Result.DurationMs - }) - .ToArray(); - var succeeded = orderedResults.Count(item => item.success); + var orderedResultsArray = new JsonArray(); + var succeeded = 0; + foreach (var target in targets) + { + var targetExecution = results[target.SessionId]; + var targetResult = targetExecution.Result; + if (targetResult.IsSuccess) + succeeded++; + + orderedResultsArray.Add((JsonNode)new JsonObject + { + ["sessionId"] = target.SessionId.ToString("D"), + ["name"] = target.Name, + ["host"] = target.Host, + ["status"] = targetResult.Status.ToString(), + ["executionState"] = targetResult.ExecutionState.ToString(), + ["success"] = targetResult.IsSuccess, + ["outcomeCertain"] = targetResult.IsOutcomeCertain, + ["remoteCompletionConfirmed"] = targetResult.RemoteCompletionConfirmed, + ["message"] = AgentSensitiveDataRedactor.Redact( + targetResult.Message, + targetExecution.SensitiveInputs), + ["output"] = LimitToolResultOutput(AgentSensitiveDataRedactor.Redact( + targetResult.Output, + targetExecution.SensitiveInputs)), + ["error"] = LimitToolResultOutput(AgentSensitiveDataRedactor.Redact( + targetResult.Error, + targetExecution.SensitiveInputs)), + ["exitCode"] = targetResult.ExitCode, + ["durationMs"] = targetResult.DurationMs + }); + } + return new( - succeeded == orderedResults.Length, - JsonSerializer.Serialize(new - { - command, - targetCount = orderedResults.Length, - succeeded, - failed = orderedResults.Length - succeeded, - results = orderedResults - })); + succeeded == targets.Length, + new JsonObject + { + ["command"] = command, + ["targetCount"] = targets.Length, + ["succeeded"] = succeeded, + ["failed"] = targets.Length - succeeded, + ["results"] = orderedResultsArray + }.ToJsonString()); } private async Task ExecuteBatchTargetWithCredentialsAsync( @@ -3117,16 +3017,18 @@ private async Task ExecuteOpenSessionAsync( } return new( result.Opened, - JsonSerializer.Serialize(new + new JsonObject { - savedSessionId = savedSessionId.ToString("D"), - status = result.Status.ToString(), - message = result.Opened + ["savedSessionId"] = savedSessionId.ToString("D"), + ["status"] = result.Status.ToString(), + ["message"] = result.Opened ? "The SSH session is open in a user-visible tab." : result.Error ?? "The SSH session could not be opened.", - agentOwned = result.AgentOwned, - session = result.Session - })); + ["agentOwned"] = result.AgentOwned, + ["session"] = result.Session == null + ? null + : JsonSerializer.SerializeToNode(result.Session, AppJsonContext.Default.AgentSessionSnapshot) + }.ToJsonString()); } finally { @@ -3169,14 +3071,14 @@ private async Task ExecuteCloseSessionAsync( .ConfigureAwait(false); return new( result.Closed, - JsonSerializer.Serialize(new + new JsonObject { - sessionId = sessionId.ToString("D"), - status = result.Status.ToString(), - message = result.Closed + ["sessionId"] = sessionId.ToString("D"), + ["status"] = result.Status.ToString(), + ["message"] = result.Closed ? "The Agent-created SSH session was closed." : result.Error ?? "The SSH session could not be closed." - })); + }.ToJsonString()); } private static bool TryGetCredentialRequirement( @@ -3388,20 +3290,20 @@ private static AgentToolExecutionResult CreateToolFailure( bool retrySafe = true) => new( false, - JsonSerializer.Serialize(new - { - success = false, - status = "failed", - executionState = "Failed", - outcomeCertain = false, - remoteCompletionConfirmed = false, - errorType, - message, - error = message, - sessionId = sessionId == Guid.Empty ? null : sessionId.ToString("D"), - retrySafe, - durationMs = 0 - })); + new JsonObject + { + ["success"] = false, + ["status"] = "failed", + ["executionState"] = "Failed", + ["outcomeCertain"] = false, + ["remoteCompletionConfirmed"] = false, + ["errorType"] = errorType, + ["message"] = message, + ["error"] = message, + ["sessionId"] = sessionId == Guid.Empty ? null : sessionId.ToString("D"), + ["retrySafe"] = retrySafe, + ["durationMs"] = 0 + }.ToJsonString()); private static bool TryValidateToolCall( AgentToolCall? toolCall, @@ -3566,30 +3468,30 @@ private async Task ExecuteDiagnosticAsync( { return new( false, - JsonSerializer.Serialize(new + new JsonObject { - diagnostic = plan.Scope, - platform = plan.Platform, - status = result.Status.ToString(), - message = "The diagnostic was blocked by the command permission policy.", - approvalRequired = true - })); + ["diagnostic"] = plan.Scope, + ["platform"] = plan.Platform, + ["status"] = result.Status.ToString(), + ["message"] = "The diagnostic was blocked by the command permission policy.", + ["approvalRequired"] = true + }.ToJsonString()); } return new( result.IsSuccess, - JsonSerializer.Serialize(new - { - diagnostic = plan.Scope, - platform = plan.Platform, - displayCommand = plan.DisplayCommand, - status = result.Status.ToString(), - message = result.Message, - requestId = result.RequestId.ToString("D"), - sessionId = request.SessionId.ToString("D"), - remoteCompletionConfirmed = result.RemoteCompletionConfirmed, - output = LimitToolResultOutput(result.Output) - })); + new JsonObject + { + ["diagnostic"] = plan.Scope, + ["platform"] = plan.Platform, + ["displayCommand"] = plan.DisplayCommand, + ["status"] = result.Status.ToString(), + ["message"] = result.Message, + ["requestId"] = result.RequestId.ToString("D"), + ["sessionId"] = request.SessionId.ToString("D"), + ["remoteCompletionConfirmed"] = result.RemoteCompletionConfirmed, + ["output"] = LimitToolResultOutput(result.Output) + }.ToJsonString()); } private async Task ExecuteReadOnlyToolAsync( @@ -3625,30 +3527,36 @@ private async Task ExecuteReadOnlyToolAsync( maxEntries, cancellationToken) .ConfigureAwait(false); + var entriesArray = new JsonArray(); + foreach (var entry in directory.Entries) + { + entriesArray.Add((JsonNode)new JsonObject + { + ["name"] = entry.Name, + ["fullPath"] = entry.FullPath, + ["isDirectory"] = entry.IsDirectory, + ["size"] = entry.Size, + ["lastModified"] = entry.LastModified, + ["permissions"] = entry.Permissions, + ["isSymbolicLink"] = entry.IsSymbolicLink + }); + } + return new( directory.Success, - JsonSerializer.Serialize(new + new JsonObject { - tool = toolCall.Name, - path = directory.Path, - success = directory.Success, - status = directory.Success ? "completed" : "failed", - sessionId = request.SessionId.ToString("D"), - toolCallId = toolCall.Id, - truncated = directory.Truncated, - errorCode = directory.ErrorCode, - error = directory.Error, - entries = directory.Entries.Select(entry => new - { - name = entry.Name, - fullPath = entry.FullPath, - isDirectory = entry.IsDirectory, - size = entry.Size, - lastModified = entry.LastModified, - permissions = entry.Permissions, - isSymbolicLink = entry.IsSymbolicLink - }) - })); + ["tool"] = toolCall.Name, + ["path"] = directory.Path, + ["success"] = directory.Success, + ["status"] = directory.Success ? "completed" : "failed", + ["sessionId"] = request.SessionId.ToString("D"), + ["toolCallId"] = toolCall.Id, + ["truncated"] = directory.Truncated, + ["errorCode"] = directory.ErrorCode, + ["error"] = directory.Error, + ["entries"] = entriesArray + }.ToJsonString()); } if (toolCall.Name == AgentReadOnlyToolCatalog.WorkingDirectoryToolName && @@ -3656,14 +3564,14 @@ private async Task ExecuteReadOnlyToolAsync( { return new( true, - JsonSerializer.Serialize(new + new JsonObject { - tool = toolCall.Name, - success = true, - sessionId = request.SessionId.ToString("D"), - workingDirectory = currentDirectory, - source = "terminal" - })); + ["tool"] = toolCall.Name, + ["success"] = true, + ["sessionId"] = request.SessionId.ToString("D"), + ["workingDirectory"] = currentDirectory, + ["source"] = "terminal" + }.ToJsonString()); } if (toolCall.Name == AgentReadOnlyToolCatalog.ReadRemoteFileToolName) @@ -3681,20 +3589,20 @@ private async Task ExecuteReadOnlyToolAsync( { return new( readResult.Success, - JsonSerializer.Serialize(new + new JsonObject { - tool = toolCall.Name, - path = readResult.Path, - success = readResult.Success, - status = readResult.Success ? "completed" : "failed", - sessionId = request.SessionId.ToString("D"), - toolCallId = toolCall.Id, - characters = readResult.Characters, - content = readResult.Content, - errorCode = readResult.ErrorCode, - error = readResult.Error, - source = "sftp" - })); + ["tool"] = toolCall.Name, + ["path"] = readResult.Path, + ["success"] = readResult.Success, + ["status"] = readResult.Success ? "completed" : "failed", + ["sessionId"] = request.SessionId.ToString("D"), + ["toolCallId"] = toolCall.Id, + ["characters"] = readResult.Characters, + ["content"] = readResult.Content, + ["errorCode"] = readResult.ErrorCode, + ["error"] = readResult.Error, + ["source"] = "sftp" + }.ToJsonString()); } } @@ -3713,28 +3621,30 @@ private async Task ExecuteReadOnlyToolAsync( var entry = statResult.Entry; return new( statResult.Success, - JsonSerializer.Serialize(new + new JsonObject { - tool = toolCall.Name, - path = statResult.Path, - success = statResult.Success, - status = statResult.Success ? "completed" : "failed", - sessionId = request.SessionId.ToString("D"), - toolCallId = toolCall.Id, - entry = entry == null ? null : new - { - name = entry.Name, - fullPath = entry.FullPath, - isDirectory = entry.IsDirectory, - size = entry.Size, - lastModified = entry.LastModified, - permissions = entry.Permissions, - isSymbolicLink = entry.IsSymbolicLink - }, - errorCode = statResult.ErrorCode, - error = statResult.Error, - source = "sftp" - })); + ["tool"] = toolCall.Name, + ["path"] = statResult.Path, + ["success"] = statResult.Success, + ["status"] = statResult.Success ? "completed" : "failed", + ["sessionId"] = request.SessionId.ToString("D"), + ["toolCallId"] = toolCall.Id, + ["entry"] = entry == null + ? null + : new JsonObject + { + ["name"] = entry.Name, + ["fullPath"] = entry.FullPath, + ["isDirectory"] = entry.IsDirectory, + ["size"] = entry.Size, + ["lastModified"] = entry.LastModified, + ["permissions"] = entry.Permissions, + ["isSymbolicLink"] = entry.IsSymbolicLink + }, + ["errorCode"] = statResult.ErrorCode, + ["error"] = statResult.Error, + ["source"] = "sftp" + }.ToJsonString()); } } @@ -3751,18 +3661,18 @@ private async Task ExecuteReadOnlyToolAsync( .ConfigureAwait(false); return new( result.IsSuccess, - JsonSerializer.Serialize(new - { - tool = toolCall.Name, - platform = plan.Platform, - displayCommand = plan.DisplayCommand, - status = result.Status.ToString(), - message = result.Message, - requestId = result.RequestId.ToString("D"), - sessionId = request.SessionId.ToString("D"), - remoteCompletionConfirmed = result.RemoteCompletionConfirmed, - output = LimitToolResultOutput(result.Output) - })); + new JsonObject + { + ["tool"] = toolCall.Name, + ["platform"] = plan.Platform, + ["displayCommand"] = plan.DisplayCommand, + ["status"] = result.Status.ToString(), + ["message"] = result.Message, + ["requestId"] = result.RequestId.ToString("D"), + ["sessionId"] = request.SessionId.ToString("D"), + ["remoteCompletionConfirmed"] = result.RemoteCompletionConfirmed, + ["output"] = LimitToolResultOutput(result.Output) + }.ToJsonString()); } private static bool TryReadRemotePathArgument( @@ -3917,18 +3827,18 @@ private async Task ExecuteRunbookAsync( return new( result.IsSuccess, - JsonSerializer.Serialize(new - { - runbook = plan.Scope, - platform = plan.Platform, - displayCommand = plan.DisplayCommand, - status = result.Status.ToString(), - message = result.Message, - requestId = result.RequestId.ToString("D"), - sessionId = request.SessionId.ToString("D"), - remoteCompletionConfirmed = result.RemoteCompletionConfirmed, - output = LimitToolResultOutput(result.Output) - })); + new JsonObject + { + ["runbook"] = plan.Scope, + ["platform"] = plan.Platform, + ["displayCommand"] = plan.DisplayCommand, + ["status"] = result.Status.ToString(), + ["message"] = result.Message, + ["requestId"] = result.RequestId.ToString("D"), + ["sessionId"] = request.SessionId.ToString("D"), + ["remoteCompletionConfirmed"] = result.RemoteCompletionConfirmed, + ["output"] = LimitToolResultOutput(result.Output) + }.ToJsonString()); } private async Task ExecuteFleetDiagnosticAsync( @@ -3949,27 +3859,33 @@ private async Task ExecuteFleetDiagnosticAsync( scope, cancellationToken) .ConfigureAwait(false); + var resultsArray = new JsonArray(); + foreach (var item in result.Results) + { + resultsArray.Add((JsonNode)new JsonObject + { + ["sessionId"] = item.SessionId.ToString("D"), + ["name"] = item.Name, + ["host"] = item.Host, + ["platform"] = item.Platform, + ["status"] = item.Status, + ["message"] = item.Message, + ["remoteCompletionConfirmed"] = item.RemoteCompletionConfirmed, + ["output"] = LimitFleetOutput(item.Output) + }); + } + return new( result.FailureCount == 0, - JsonSerializer.Serialize(new - { - fleet = true, - diagnostic = result.Scope, - targetCount = result.TargetCount, - successCount = result.SuccessCount, - failureCount = result.FailureCount, - results = result.Results.Select(item => new - { - sessionId = item.SessionId.ToString("D"), - name = item.Name, - host = item.Host, - platform = item.Platform, - status = item.Status, - message = item.Message, - remoteCompletionConfirmed = item.RemoteCompletionConfirmed, - output = LimitFleetOutput(item.Output) - }) - })); + new JsonObject + { + ["fleet"] = true, + ["diagnostic"] = result.Scope, + ["targetCount"] = result.TargetCount, + ["successCount"] = result.SuccessCount, + ["failureCount"] = result.FailureCount, + ["results"] = resultsArray + }.ToJsonString()); } private static string? LimitFleetOutput(string? output) @@ -3994,25 +3910,27 @@ private static string SerializeCommandResult( var output = AgentSensitiveDataRedactor.Redact(result.Output, sensitiveInputs); var error = AgentSensitiveDataRedactor.Redact(result.Error, sensitiveInputs); - return JsonSerializer.Serialize(new - { - status = result.Status.ToString(), - message, - requestId = result.RequestId.ToString("D"), - sessionId = (targetSessionId ?? activeRun.SessionId).ToString("D"), - remoteCompletionConfirmed = result.RemoteCompletionConfirmed, - risk = result.Risk.ToString(), - executionState = result.ExecutionState.ToString(), - outcomeCertain = result.IsOutcomeCertain, - retrySafe = result.IsRetrySafe, - errorType = result.ErrorType.ToString(), - durationMs = result.DurationMs, - verification = AgentCommandVerificationService.Evaluate(result), - output = LimitToolResultOutput(output), - error = LimitToolResultOutput(error), - exitCode = result.ExitCode, - agentGuidance - }); + return new JsonObject + { + ["status"] = result.Status.ToString(), + ["message"] = message, + ["requestId"] = result.RequestId.ToString("D"), + ["sessionId"] = (targetSessionId ?? activeRun.SessionId).ToString("D"), + ["remoteCompletionConfirmed"] = result.RemoteCompletionConfirmed, + ["risk"] = result.Risk.ToString(), + ["executionState"] = result.ExecutionState.ToString(), + ["outcomeCertain"] = result.IsOutcomeCertain, + ["retrySafe"] = result.IsRetrySafe, + ["errorType"] = result.ErrorType.ToString(), + ["durationMs"] = result.DurationMs, + ["verification"] = JsonSerializer.SerializeToNode( + AgentCommandVerificationService.Evaluate(result), + AppJsonContext.Default.AgentCommandVerification), + ["output"] = LimitToolResultOutput(output), + ["error"] = LimitToolResultOutput(error), + ["exitCode"] = result.ExitCode, + ["agentGuidance"] = agentGuidance + }.ToJsonString(); } private static AgentCommandVerification? TryExtractCommandVerification(string content) diff --git a/Services/Agent/AgentRunHistoryStore.cs b/Services/Agent/AgentRunHistoryStore.cs index e670d5e..e205650 100644 --- a/Services/Agent/AgentRunHistoryStore.cs +++ b/Services/Agent/AgentRunHistoryStore.cs @@ -19,8 +19,6 @@ void SaveRecoverable(IReadOnlyCollection runs) /// public sealed class SqliteAgentRunHistoryStore : IAgentRunHistoryStore { - private static readonly JsonSerializerOptions JsonOptions = AppJsonOptions.Indented; - private const string Collection = "agent_runs"; private readonly object _gate = new(); private readonly string _legacyHistoryPath; @@ -57,7 +55,7 @@ public IReadOnlyList Load() if (payload == null) return []; - return JsonSerializer.Deserialize>(payload, JsonOptions) + return JsonSerializer.Deserialize(payload, AppIndentedJsonContext.Default.ListAgentRuntimeRunSnapshot) ?.Where(IsCompleted) .ToList() ?? []; @@ -82,7 +80,7 @@ public void Save(IReadOnlyCollection runs) .ToArray(); try { - var json = JsonSerializer.Serialize(completed, JsonOptions); + var json = JsonSerializer.Serialize(completed, AppIndentedJsonContext.Default.AgentRuntimeRunSnapshotArray); _store.Write(Collection, "completed", json); } catch @@ -112,7 +110,7 @@ public IReadOnlyList LoadRecoverable() return []; var now = DateTimeOffset.UtcNow; - return JsonSerializer.Deserialize>(json, JsonOptions) + return JsonSerializer.Deserialize(json, AppIndentedJsonContext.Default.ListAgentRunRecoveryState) ?.Select(NormalizeRecovery) .Where(recovery => IsValidRecovery(recovery, now)) .OrderByDescending(run => run.Snapshot.StartedAtUtc) @@ -143,7 +141,7 @@ public void SaveRecoverable(IReadOnlyCollection runs) .ToArray(); try { - var json = JsonSerializer.Serialize(recoverable, JsonOptions); + var json = JsonSerializer.Serialize(recoverable, AppIndentedJsonContext.Default.AgentRunRecoveryStateArray); var encrypted = PasswordEncryptionService.Encrypt(json); _store.Write(Collection, "recovery", encrypted); } @@ -215,7 +213,7 @@ private static bool IsValidLegacyHistory(string json) { try { - return JsonSerializer.Deserialize>(json, JsonOptions) != null; + return JsonSerializer.Deserialize(json, AppIndentedJsonContext.Default.ListAgentRuntimeRunSnapshot) != null; } catch (JsonException) { @@ -231,7 +229,7 @@ private static bool IsValidLegacyRecoveryPayload(string stored) try { - return JsonSerializer.Deserialize>(json, JsonOptions) != null; + return JsonSerializer.Deserialize(json, AppIndentedJsonContext.Default.ListAgentRunRecoveryState) != null; } catch (JsonException) { diff --git a/Services/Agent/AgentRuntimeClient.cs b/Services/Agent/AgentRuntimeClient.cs index 72fb4b6..1fabd75 100644 --- a/Services/Agent/AgentRuntimeClient.cs +++ b/Services/Agent/AgentRuntimeClient.cs @@ -1,4 +1,5 @@ using System.Text.Json; +using System.Text.Json.Nodes; using System.Text.Json.Serialization; namespace CxShell.Services.Agent; @@ -46,8 +47,6 @@ Task CancelRequestAsync( public sealed class AgentRuntimeClient : IAgentRuntimeClient { - private static readonly JsonSerializerOptions JsonOptions = CxShell.Services.AppJsonOptions.CamelCase; - private readonly IAgentRuntimeTransport _transport; private long _generatedRequestId; @@ -62,9 +61,13 @@ public Task InitializeAsync( string? requestId = null, CancellationToken cancellationToken = default) { - object? parameters = protocol == null && protocolVersion == null + JsonObject? parameters = protocol == null && protocolVersion == null ? null - : new { protocol, protocolVersion }; + : new JsonObject + { + ["protocol"] = protocol, + ["protocolVersion"] = protocolVersion + }; return SendResultAsync( AgentRuntimeMethodNames.Initialize, @@ -91,7 +94,7 @@ public Task CheckCapabilityAsync( return SendResultAsync( AgentRuntimeMethodNames.CapabilitiesCheck, - new { capability }, + new JsonObject { ["capability"] = capability }, requestId, cancellationToken); } @@ -108,9 +111,11 @@ public async Task SendAsync( normalizedRequestId, normalizedMethod, parameters == null - ? JsonSerializer.SerializeToElement(new { }, JsonOptions) - : JsonSerializer.SerializeToElement(parameters, JsonOptions)); - var requestJson = JsonSerializer.Serialize(request, JsonOptions); + ? AppJsonOptions.EmptyObjectElement + : AppJsonOptions.SerializeCamelCaseToElement(parameters)); + var requestJson = JsonSerializer.Serialize( + request, + AppCamelCaseJsonContext.Default.AgentRuntimeClientRequestEnvelope); string responseJson; try @@ -128,7 +133,7 @@ public async Task SendAsync( AgentRuntimeResponse? response; try { - response = JsonSerializer.Deserialize(responseJson, JsonOptions); + response = JsonSerializer.Deserialize(responseJson, AppCamelCaseJsonContext.Default.AgentRuntimeResponse); } catch (JsonException exception) { @@ -167,7 +172,7 @@ public async Task SendResultAsync( try { - return result.Deserialize(JsonOptions) + return AppJsonOptions.DeserializeCamelCase(result) ?? throw new AgentRuntimeProtocolException( $"Runtime response '{response.RequestId}' contained a null result."); } @@ -190,7 +195,7 @@ public Task CancelRequestAsync( return SendResultAsync( AgentRuntimeMethodNames.RequestCancel, - new { requestId = normalizedRequestId }, + new JsonObject { ["requestId"] = normalizedRequestId }, cancellationRequestId, cancellationToken); } diff --git a/Services/Agent/AgentRuntimeHost.cs b/Services/Agent/AgentRuntimeHost.cs index bd2b663..b39fe14 100644 --- a/Services/Agent/AgentRuntimeHost.cs +++ b/Services/Agent/AgentRuntimeHost.cs @@ -492,7 +492,7 @@ private AgentRuntimeResponse CancelRequest(string requestId, JsonElement paramet cancelled, targetRequestId, cancelled ? null : "The target request was not found or has already completed."), - CxShell.Services.AppJsonOptions.CamelCase + AppCamelCaseJsonContext.Default.AgentRuntimeRequestCancelResult ) }; } diff --git a/Services/Agent/AgentRuntimeJsonEndpoint.cs b/Services/Agent/AgentRuntimeJsonEndpoint.cs index 9c85425..8706cb4 100644 --- a/Services/Agent/AgentRuntimeJsonEndpoint.cs +++ b/Services/Agent/AgentRuntimeJsonEndpoint.cs @@ -10,8 +10,6 @@ namespace CxShell.Services.Agent; /// public sealed class AgentRuntimeJsonEndpoint { - private static readonly JsonSerializerOptions JsonOptions = CxShell.Services.AppJsonOptions.CamelCase; - private readonly IAgentRuntimeHost _host; public AgentRuntimeJsonEndpoint(IAgentRuntimeHost host) @@ -46,7 +44,7 @@ public async Task DispatchAsync( ReadString(root, "method") ?? string.Empty, ReadParameters(root)); var response = await _host.DispatchAsync(request, cancellationToken).ConfigureAwait(false); - return JsonSerializer.Serialize(response, JsonOptions); + return JsonSerializer.Serialize(response, AppCamelCaseJsonContext.Default.AgentRuntimeResponse); } catch (JsonException) { @@ -98,7 +96,7 @@ private static string SerializeError(string requestId, string errorCode, string ErrorCode = errorCode, Error = error }, - JsonOptions); + AppCamelCaseJsonContext.Default.AgentRuntimeResponse); private static string TrimException(Exception exception) { diff --git a/Services/Agent/AgentRuntimeSessionAdapter.cs b/Services/Agent/AgentRuntimeSessionAdapter.cs index 87c45b8..5333163 100644 --- a/Services/Agent/AgentRuntimeSessionAdapter.cs +++ b/Services/Agent/AgentRuntimeSessionAdapter.cs @@ -16,8 +16,6 @@ public sealed class AgentRuntimeSessionAdapter : { public const string ModuleName = "session-gateway"; - private static readonly JsonSerializerOptions JsonOptions = CxShell.Services.AppJsonOptions.CamelCase; - private readonly IAgentSessionGateway _gateway; private readonly Func _providerSettings; private readonly Func _webSettings; @@ -1150,7 +1148,7 @@ private static AgentRuntimeResponse Success(string requestId, object result) { RequestId = requestId, Ok = true, - Result = JsonSerializer.SerializeToElement(result, JsonOptions) + Result = AppJsonOptions.SerializeCamelCaseToElement(result) }; private static AgentRuntimeResponse Error(string requestId, string errorCode, string error) diff --git a/Services/Agent/AgentRuntimeStreamTransport.cs b/Services/Agent/AgentRuntimeStreamTransport.cs index 5989af0..900e705 100644 --- a/Services/Agent/AgentRuntimeStreamTransport.cs +++ b/Services/Agent/AgentRuntimeStreamTransport.cs @@ -1,5 +1,6 @@ using System.Collections.Concurrent; using System.Text.Json; +using System.Text.Json.Nodes; using System.Text.Json.Serialization; namespace CxShell.Services.Agent; @@ -18,8 +19,6 @@ public sealed class AgentRuntimeStreamTransport : public const int MaximumPendingRequests = 64; private const int ReadBufferSize = 16 * 1024; - private static readonly JsonSerializerOptions JsonOptions = CxShell.Services.AppJsonOptions.CamelCase; - private readonly Stream _stream; private readonly bool _leaveOpen; private readonly SemaphoreSlim _writeGate = new(1, 1); @@ -118,8 +117,12 @@ public async Task RequestCancellationAsync( var cancellationRequest = new RuntimeRequestEnvelope( $"cxshell-cancel-{DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()}-{sequence}", AgentRuntimeMethodNames.RequestCancel, - JsonSerializer.SerializeToElement(new { requestId = normalizedRequestId }, JsonOptions)); - var requestJson = JsonSerializer.Serialize(cancellationRequest, JsonOptions); + JsonSerializer.SerializeToElement( + new JsonObject { ["requestId"] = normalizedRequestId }, + AppCamelCaseJsonContext.Default.JsonObject)); + var requestJson = JsonSerializer.Serialize( + cancellationRequest, + AppCamelCaseJsonContext.Default.AgentRuntimeStreamRequestEnvelope); await SendAsync(requestJson, cancellationToken).ConfigureAwait(false); } @@ -214,7 +217,7 @@ private void ProcessFrame(string json) type.ValueKind == JsonValueKind.String && string.Equals(type.GetString(), "event", StringComparison.Ordinal)) { - var @event = JsonSerializer.Deserialize(json, JsonOptions) + var @event = JsonSerializer.Deserialize(json, AppCamelCaseJsonContext.Default.AgentRuntimeEventEnvelope) ?? throw new AgentRuntimeProtocolException("Runtime event frame is invalid."); PublishEvent(@event); return; diff --git a/Services/Agent/AgentRuntimeTransport.cs b/Services/Agent/AgentRuntimeTransport.cs index eaaa99d..821924d 100644 --- a/Services/Agent/AgentRuntimeTransport.cs +++ b/Services/Agent/AgentRuntimeTransport.cs @@ -1,6 +1,7 @@ using System.Buffers.Binary; using System.Text; using System.Text.Json; +using System.Text.Json.Nodes; using System.Text.Json.Serialization; using System.Threading.Channels; @@ -31,8 +32,6 @@ Task RequestCancellationAsync( /// public sealed class InProcessAgentRuntimeTransport : IAgentRuntimeTransport, IAgentRuntimeEventTransport { - private static readonly JsonSerializerOptions JsonOptions = CxShell.Services.AppJsonOptions.CamelCase; - private readonly AgentRuntimeJsonEndpoint _endpoint; private readonly IAgentRuntimeHost _host; @@ -62,7 +61,7 @@ public IDisposable SubscribeEvents(Action observer) private static JsonElement? SerializePayload(object? payload) => payload == null ? null - : JsonSerializer.SerializeToElement(payload, JsonOptions); + : AppJsonOptions.SerializeCamelCaseToElement(payload); } public interface IAgentRuntimeFrameEndpoint @@ -381,9 +380,12 @@ private void TryEnqueueOverflow() "runtime", string.Empty, "runtime", - JsonSerializer.SerializeToElement(new { droppedEvents = dropped }, JsonOptions)); + JsonSerializer.SerializeToElement( + new JsonObject { ["droppedEvents"] = dropped }, + AppCamelCaseJsonContext.Default.JsonObject)); if (!_controlChannel.Writer.TryWrite(new( - AgentRuntimeFrameCodec.Encode(JsonSerializer.Serialize(overflow, JsonOptions)), + AgentRuntimeFrameCodec.Encode( + JsonSerializer.Serialize(overflow, AppCamelCaseJsonContext.Default.AgentRuntimeEventEnvelope)), true, true))) { @@ -420,8 +422,6 @@ public void Dispose() } } - private static readonly JsonSerializerOptions JsonOptions = CxShell.Services.AppJsonOptions.CamelCase; - private static string SerializeDefaultEvent(AgentRuntimeModuleEvent @event) { ArgumentNullException.ThrowIfNull(@event); @@ -433,8 +433,8 @@ private static string SerializeDefaultEvent(AgentRuntimeModuleEvent @event) @event.Method, @event.Payload == null ? null - : JsonSerializer.SerializeToElement(@event.Payload, JsonOptions)); - return JsonSerializer.Serialize(envelope, JsonOptions); + : AppJsonOptions.SerializeCamelCaseToElement(@event.Payload)); + return JsonSerializer.Serialize(envelope, AppCamelCaseJsonContext.Default.AgentRuntimeEventEnvelope); } } diff --git a/Services/Agent/AgentToolResultEnvelope.cs b/Services/Agent/AgentToolResultEnvelope.cs index 17c3883..48fbc34 100644 --- a/Services/Agent/AgentToolResultEnvelope.cs +++ b/Services/Agent/AgentToolResultEnvelope.cs @@ -11,8 +11,6 @@ namespace CxShell.Services.Agent; /// public sealed record AgentToolResultEnvelope { - private static readonly JsonSerializerOptions JsonOptions = CxShell.Services.AppJsonOptions.CamelCase; - public bool Success { get; init; } public string Status { get; init; } = string.Empty; public string ExecutionState { get; init; } = string.Empty; @@ -72,16 +70,17 @@ public static string Serialize( { ArgumentNullException.ThrowIfNull(result); - var node = JsonSerializer.SerializeToNode(result, JsonOptions) as JsonObject ?? new JsonObject(); + var node = JsonSerializer.SerializeToNode(result, AppCamelCaseJsonContext.Default.AgentToolResultEnvelope) as JsonObject + ?? new JsonObject(); foreach (var (name, value) in toolSpecificFields) { if (string.IsNullOrWhiteSpace(name)) continue; - node[name] = value == null ? null : JsonSerializer.SerializeToNode(value, JsonOptions); + node[name] = SerializeValueToNode(value); } - return node.ToJsonString(JsonOptions); + return node.ToJsonString(AppJsonOptions.CamelCase); } /// @@ -145,20 +144,66 @@ public static string Merge( : "The tool call failed.", false, null), - JsonOptions); + AppCamelCaseJsonContext.Default.AgentCommandVerification); } - return node.ToJsonString(JsonOptions); + return node.ToJsonString(AppJsonOptions.CamelCase); } private static void SetIfMissing(JsonObject node, string name, object? value) { if (!node.ContainsKey(name)) - node[name] = value == null ? null : JsonSerializer.SerializeToNode(value, JsonOptions); + node[name] = SerializeValueToNode(value); } private static void SetOrReplace(JsonObject node, string name, object? value) - => node[name] = value == null ? null : JsonSerializer.SerializeToNode(value, JsonOptions); + => node[name] = SerializeValueToNode(value); + + private static JsonNode? SerializeValueToNode(object? value) + { + switch (value) + { + case null: + return null; + case JsonNode node: + return node.DeepClone(); + case JsonElement element: + return JsonSerializer.SerializeToNode(element, AppCamelCaseJsonContext.Default.JsonElement); + case bool b: + return JsonValue.Create(b); + case string s: + return JsonValue.Create(s); + case int i: + return JsonValue.Create(i); + case long l: + return JsonValue.Create(l); + case uint u: + return JsonValue.Create(u); + case ulong ul: + return JsonValue.Create(ul); + case double d: + return JsonValue.Create(d); + case float f: + return JsonValue.Create(f); + case decimal dec: + return JsonValue.Create(dec); + case DateTimeOffset dto: + return JsonValue.Create(dto); + case DateTime dt: + return JsonValue.Create(dt); + case Guid g: + return JsonValue.Create(g); + case IEnumerable strings: + { + var array = new JsonArray(); + foreach (var item in strings) + array.Add((JsonNode?)JsonValue.Create(item)); + return array; + } + default: + return JsonSerializer.SerializeToNode(value, AppJsonOptions.ResolveCamelCaseTypeInfo(value.GetType())); + } + } private static string? ReadString(JsonObject node, string name) => node[name] is JsonValue value && value.TryGetValue(out var text) diff --git a/Services/Agent/AgentWebAccess.cs b/Services/Agent/AgentWebAccess.cs index bbb3560..ac449ac 100644 --- a/Services/Agent/AgentWebAccess.cs +++ b/Services/Agent/AgentWebAccess.cs @@ -14,6 +14,10 @@ public sealed record AgentWebSearchItem( string Url, string Snippet); +public sealed record AgentWebSearchPayload( + string Query, + IReadOnlyList Results); + public sealed record AgentWebResult( bool Success, string Content, @@ -81,11 +85,9 @@ public async Task SearchAsync( var items = ParseSearchResults(body, settings.MaxResults); return new( true, - JsonSerializer.Serialize(new - { - query = query.Trim(), - results = items - }), + JsonSerializer.Serialize( + new AgentWebSearchPayload(query.Trim(), items), + AppCamelCaseJsonContext.Default.AgentWebSearchPayload), endpoint.ToString()); } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) diff --git a/Services/Agent/OpenAiCompatibleAgentModelClient.cs b/Services/Agent/OpenAiCompatibleAgentModelClient.cs index 3bf1aa9..2d727b7 100644 --- a/Services/Agent/OpenAiCompatibleAgentModelClient.cs +++ b/Services/Agent/OpenAiCompatibleAgentModelClient.cs @@ -1,6 +1,7 @@ using System.Net.Http.Headers; using System.Text; using System.Text.Json; +using System.Text.Json.Nodes; using CxShell.Models; using CxShell.Services; @@ -51,17 +52,7 @@ public async Task CompleteAsync( .ConfigureAwait(false); } - var body = new - { - model = AgentProviderConfiguration.GetEffectiveModelId(provider, request.Model), - messages = request.Messages.Select(ToWireMessage), - stream = false, - temperature = request.Temperature, - max_tokens = request.MaxTokens, - reasoning_effort = ToWireReasoningEffort(request.ReasoningEffort), - tools = request.Tools?.Select(ToWireTool), - tool_choice = request.Tools is { Count: > 0 } ? "auto" : null - }; + var body = BuildChatRequestBody(provider, request, stream: false); using var httpRequest = new HttpRequestMessage( HttpMethod.Post, @@ -138,18 +129,7 @@ private async Task CompleteChatStreamingAsync( Action onChunk, CancellationToken cancellationToken) { - var body = new - { - model = AgentProviderConfiguration.GetEffectiveModelId(provider, request.Model), - messages = request.Messages.Select(ToWireMessage), - stream = true, - stream_options = new { include_usage = true }, - temperature = request.Temperature, - max_tokens = request.MaxTokens, - reasoning_effort = ToWireReasoningEffort(request.ReasoningEffort), - tools = request.Tools?.Select(ToWireTool), - tool_choice = request.Tools is { Count: > 0 } ? "auto" : null - }; + var body = BuildChatRequestBody(provider, request, stream: true); using var httpRequest = new HttpRequestMessage( HttpMethod.Post, @@ -224,18 +204,7 @@ private async Task CompleteResponsesStreamingAsync( Action onChunk, CancellationToken cancellationToken) { - var body = new - { - model = AgentProviderConfiguration.GetEffectiveModelId(provider, request.Model), - input = request.Messages.SelectMany(ToResponsesInput).ToList(), - stream = true, - store = false, - temperature = request.Temperature, - max_output_tokens = request.MaxTokens, - reasoning = BuildResponsesReasoning(request.ReasoningEffort), - tools = request.Tools?.Select(ToResponsesTool), - tool_choice = request.Tools is { Count: > 0 } ? "auto" : null - }; + var body = BuildResponsesRequestBody(provider, request, stream: true); using var httpRequest = new HttpRequestMessage( HttpMethod.Post, @@ -501,7 +470,7 @@ private async Task CompleteAnthropicStreamingAsync( private static HttpRequestMessage CreateAnthropicRequest( AgentProviderSettings provider, - object body, + JsonObject body, string accept) { var request = new HttpRequestMessage( @@ -519,7 +488,50 @@ private static HttpRequestMessage CreateAnthropicRequest( return request; } - private static object BuildAnthropicRequestBody( + private static JsonObject BuildChatRequestBody( + AgentProviderSettings provider, + AgentModelRequest request, + bool stream) + { + var body = new JsonObject + { + ["model"] = AgentProviderConfiguration.GetEffectiveModelId(provider, request.Model), + ["messages"] = ToJsonArray(request.Messages.Select(ToWireMessage)), + ["stream"] = stream + }; + if (stream) + body["stream_options"] = new JsonObject { ["include_usage"] = true }; + SetIfNotNull(body, "temperature", request.Temperature); + SetIfNotNull(body, "max_tokens", request.MaxTokens); + SetIfNotNull(body, "reasoning_effort", ToWireReasoningEffort(request.ReasoningEffort)); + SetIfNotNull(body, "tools", request.Tools == null ? null : ToJsonArray(request.Tools.Select(ToWireTool))); + if (request.Tools is { Count: > 0 }) + body["tool_choice"] = "auto"; + return body; + } + + private static JsonObject BuildResponsesRequestBody( + AgentProviderSettings provider, + AgentModelRequest request, + bool stream) + { + var body = new JsonObject + { + ["model"] = AgentProviderConfiguration.GetEffectiveModelId(provider, request.Model), + ["input"] = ToJsonArray(request.Messages.SelectMany(ToResponsesInput)), + ["stream"] = stream, + ["store"] = false + }; + SetIfNotNull(body, "temperature", request.Temperature); + SetIfNotNull(body, "max_output_tokens", request.MaxTokens); + SetIfNotNull(body, "reasoning", BuildResponsesReasoning(request.ReasoningEffort)); + SetIfNotNull(body, "tools", request.Tools == null ? null : ToJsonArray(request.Tools.Select(ToResponsesTool))); + if (request.Tools is { Count: > 0 }) + body["tool_choice"] = "auto"; + return body; + } + + private static JsonObject BuildAnthropicRequestBody( AgentProviderSettings provider, AgentModelRequest request, bool stream) @@ -529,20 +541,22 @@ private static object BuildAnthropicRequestBody( .Select(message => message.Content) .Where(content => !string.IsNullOrWhiteSpace(content)) .ToArray(); - return new - { - model = AgentProviderConfiguration.GetEffectiveModelId(provider, request.Model), - max_tokens = request.MaxTokens is > 0 ? request.MaxTokens.Value : 4096, - system = system.Length == 0 ? null : string.Join("\n\n", system), - messages = request.Messages - .Where(message => !string.Equals(message.Role, "system", StringComparison.OrdinalIgnoreCase)) - .Select(ToAnthropicMessage), - stream, - temperature = request.Temperature, - tools = request.Tools?.Select(ToAnthropicTool), - thinking = BuildAnthropicThinking(request.ReasoningEffort), - tool_choice = request.Tools is { Count: > 0 } ? new { type = "auto" } : null + var body = new JsonObject + { + ["model"] = AgentProviderConfiguration.GetEffectiveModelId(provider, request.Model), + ["max_tokens"] = request.MaxTokens is > 0 ? request.MaxTokens.Value : 4096 }; + SetIfNotNull(body, "system", system.Length == 0 ? null : string.Join("\n\n", system)); + body["messages"] = ToJsonArray(request.Messages + .Where(message => !string.Equals(message.Role, "system", StringComparison.OrdinalIgnoreCase)) + .Select(ToAnthropicMessage)); + body["stream"] = stream; + SetIfNotNull(body, "temperature", request.Temperature); + SetIfNotNull(body, "tools", request.Tools == null ? null : ToJsonArray(request.Tools.Select(ToAnthropicTool))); + SetIfNotNull(body, "thinking", BuildAnthropicThinking(request.ReasoningEffort)); + if (request.Tools is { Count: > 0 }) + body["tool_choice"] = new JsonObject { ["type"] = "auto" }; + return body; } private static string? ToWireReasoningEffort(AgentReasoningEffort effort) @@ -554,18 +568,18 @@ private static object BuildAnthropicRequestBody( _ => null }; - private static object? BuildResponsesReasoning(AgentReasoningEffort effort) + private static JsonObject? BuildResponsesReasoning(AgentReasoningEffort effort) => effort == AgentReasoningEffort.None ? null - : new { effort = ToWireReasoningEffort(effort) }; + : new JsonObject { ["effort"] = ToWireReasoningEffort(effort) }; - private static object? BuildAnthropicThinking(AgentReasoningEffort effort) + private static JsonObject? BuildAnthropicThinking(AgentReasoningEffort effort) => effort == AgentReasoningEffort.None ? null - : new + : new JsonObject { - type = "enabled", - budget_tokens = effort switch + ["type"] = "enabled", + ["budget_tokens"] = effort switch { AgentReasoningEffort.Low => 1024, AgentReasoningEffort.Medium => 4096, @@ -573,84 +587,86 @@ private static object BuildAnthropicRequestBody( } }; - private static object ToAnthropicMessage(AgentChatMessage message) + private static JsonObject ToAnthropicMessage(AgentChatMessage message) { var role = message.Role.Trim().ToLowerInvariant(); if (role == "tool") { - return new + var toolResult = new JsonObject { - role = "user", - content = new[] - { - new - { - type = "tool_result", - tool_use_id = message.ToolCallId, - content = message.Content - } - } + ["type"] = "tool_result" + }; + SetIfNotNull(toolResult, "tool_use_id", message.ToolCallId); + SetIfNotNull(toolResult, "content", message.Content); + return new JsonObject + { + ["role"] = "user", + ["content"] = new JsonArray(toolResult) }; } if (role == "assistant" && message.ToolCalls is { Count: > 0 }) { - var blocks = new List(); + var blocks = new JsonArray(); if (!string.IsNullOrWhiteSpace(message.Content)) - blocks.Add(new { type = "text", text = message.Content }); + blocks.Add((JsonNode)new JsonObject { ["type"] = "text", ["text"] = message.Content }); foreach (var call in message.ToolCalls) { - blocks.Add(new + var block = new JsonObject { - type = "tool_use", - id = call.Id, - name = call.Name, - input = ParseToolArguments(call.Arguments) - }); + ["type"] = "tool_use" + }; + SetIfNotNull(block, "id", call.Id); + SetIfNotNull(block, "name", call.Name); + block["input"] = ToJsonNode(ParseToolArguments(call.Arguments)); + blocks.Add((JsonNode)block); } - return new { role = "assistant", content = blocks }; + return new JsonObject { ["role"] = "assistant", ["content"] = blocks }; } if (message.ContentParts is { Count: > 0 }) { - var blocks = new List(); + var blocks = new JsonArray(); if (!string.IsNullOrWhiteSpace(message.Content)) - blocks.Add(new { type = "text", text = message.Content }); + blocks.Add((JsonNode)new JsonObject { ["type"] = "text", ["text"] = message.Content }); foreach (var part in message.ContentParts) { if (string.Equals(part.Type, "image", StringComparison.OrdinalIgnoreCase)) { - blocks.Add(new + var source = new JsonObject + { + ["type"] = "base64", + ["media_type"] = part.MediaType ?? "image/png" + }; + SetIfNotNull(source, "data", part.Data); + blocks.Add((JsonNode)new JsonObject { - type = "image", - source = new - { - type = "base64", - media_type = part.MediaType ?? "image/png", - data = part.Data - } + ["type"] = "image", + ["source"] = source }); } else { - blocks.Add(new { type = "text", text = FormatTextPart(part) }); + blocks.Add((JsonNode)new JsonObject { ["type"] = "text", ["text"] = FormatTextPart(part) }); } } - return new { role = role == "assistant" ? "assistant" : "user", content = blocks }; + return new JsonObject { ["role"] = role == "assistant" ? "assistant" : "user", ["content"] = blocks }; } - return new { role = role == "assistant" ? "assistant" : "user", content = message.Content }; + var plain = new JsonObject { ["role"] = role == "assistant" ? "assistant" : "user" }; + SetIfNotNull(plain, "content", message.Content); + return plain; } - private static object ToAnthropicTool(AgentToolDefinition tool) - => new - { - name = tool.Name, - description = tool.Description, - input_schema = tool.Parameters - }; + private static JsonObject ToAnthropicTool(AgentToolDefinition tool) + { + var obj = new JsonObject { ["name"] = tool.Name }; + SetIfNotNull(obj, "description", tool.Description); + obj["input_schema"] = ToJsonNode(tool.Parameters); + return obj; + } private static JsonElement ParseToolArguments(string arguments) { @@ -1199,18 +1215,7 @@ private async Task CompleteResponsesAsync( AgentModelRequest request, CancellationToken cancellationToken) { - var body = new - { - model = AgentProviderConfiguration.GetEffectiveModelId(provider, request.Model), - input = request.Messages.SelectMany(ToResponsesInput).ToList(), - stream = false, - store = false, - temperature = request.Temperature, - max_output_tokens = request.MaxTokens, - reasoning = BuildResponsesReasoning(request.ReasoningEffort), - tools = request.Tools?.Select(ToResponsesTool), - tool_choice = request.Tools is { Count: > 0 } ? "auto" : null - }; + var body = BuildResponsesRequestBody(provider, request, stream: false); using var httpRequest = new HttpRequestMessage( HttpMethod.Post, @@ -1420,123 +1425,119 @@ private static AgentModelResponse ParseResponse(string responseText, AgentProvid return new AgentModelResponse(text, model, provider.BuiltinId, inputTokens, outputTokens, toolCalls); } - private static object ToWireMessage(AgentChatMessage message) + private static JsonObject ToWireMessage(AgentChatMessage message) { var role = message.Role.Trim().ToLowerInvariant(); if (role == "assistant" && message.ToolCalls is { Count: > 0 }) { - return new + var obj = new JsonObject { ["role"] = role }; + if (!string.IsNullOrEmpty(message.Content)) + obj["content"] = message.Content; + obj["tool_calls"] = ToJsonArray(message.ToolCalls.Select(call => { - role, - content = string.IsNullOrEmpty(message.Content) ? null : message.Content, - tool_calls = message.ToolCalls.Select(call => new - { - id = call.Id, - type = "function", - function = new - { - name = call.Name, - arguments = call.Arguments - } - }) - }; + var callObj = new JsonObject(); + SetIfNotNull(callObj, "id", call.Id); + callObj["type"] = "function"; + var fnObj = new JsonObject(); + SetIfNotNull(fnObj, "name", call.Name); + SetIfNotNull(fnObj, "arguments", call.Arguments); + callObj["function"] = fnObj; + return callObj; + })); + return obj; } if (role == "assistant" && !string.IsNullOrWhiteSpace(message.ToolName)) { - return new + var callObj = new JsonObject(); + SetIfNotNull(callObj, "id", message.ToolCallId); + callObj["type"] = "function"; + callObj["function"] = new JsonObject { - role, - content = (string?)null, - tool_calls = new[] - { - new - { - id = message.ToolCallId, - type = "function", - function = new - { - name = message.ToolName, - arguments = message.ToolArguments ?? "{}" - } - } - } + ["name"] = message.ToolName, + ["arguments"] = message.ToolArguments ?? "{}" + }; + return new JsonObject + { + ["role"] = role, + ["tool_calls"] = new JsonArray(callObj) }; } if (role == "tool") { - return new - { - role, - tool_call_id = message.ToolCallId, - content = message.Content - }; + var toolMsg = new JsonObject { ["role"] = role }; + SetIfNotNull(toolMsg, "tool_call_id", message.ToolCallId); + SetIfNotNull(toolMsg, "content", message.Content); + return toolMsg; } if (message.ContentParts is { Count: > 0 }) { - return new + return new JsonObject { - role, - content = ToChatContentParts(message) + ["role"] = role, + ["content"] = ToJsonArray(ToChatContentParts(message)) }; } - return new { role, content = message.Content }; + var plain = new JsonObject { ["role"] = role }; + SetIfNotNull(plain, "content", message.Content); + return plain; } - private static IEnumerable ToChatContentParts(AgentChatMessage message) + private static IEnumerable ToChatContentParts(AgentChatMessage message) { if (!string.IsNullOrEmpty(message.Content)) - yield return new { type = "text", text = message.Content }; + yield return new JsonObject { ["type"] = "text", ["text"] = message.Content }; foreach (var part in message.ContentParts ?? []) { if (string.Equals(part.Type, "image", StringComparison.OrdinalIgnoreCase)) { - yield return new + yield return new JsonObject { - type = "image_url", - image_url = new { url = BuildImageDataUrl(part) } + ["type"] = "image_url", + ["image_url"] = new JsonObject { ["url"] = BuildImageDataUrl(part) } }; } else { - yield return new + yield return new JsonObject { - type = "text", - text = FormatTextPart(part) + ["type"] = "text", + ["text"] = FormatTextPart(part) }; } } } - private static object ToWireTool(AgentToolDefinition tool) - => new + private static JsonObject ToWireTool(AgentToolDefinition tool) + { + var fn = new JsonObject { ["name"] = tool.Name }; + SetIfNotNull(fn, "description", tool.Description); + fn["parameters"] = ToJsonNode(tool.Parameters); + return new JsonObject { - type = "function", - function = new - { - name = tool.Name, - description = tool.Description, - parameters = tool.Parameters - } + ["type"] = "function", + ["function"] = fn }; + } - private static IEnumerable ToResponsesInput(AgentChatMessage message) + private static IEnumerable ToResponsesInput(AgentChatMessage message) { var role = message.Role.Trim().ToLowerInvariant(); if (role == "tool") { if (!string.IsNullOrWhiteSpace(message.ToolCallId)) { - yield return new + var item = new JsonObject { - type = "function_call_output", - call_id = message.ToolCallId, - output = message.Content + ["type"] = "function_call_output", + ["call_id"] = message.ToolCallId }; + SetIfNotNull(item, "output", message.Content); + yield return item; } yield break; @@ -1545,17 +1546,15 @@ private static IEnumerable ToResponsesInput(AgentChatMessage message) if (role == "assistant" && message.ToolCalls is { Count: > 0 }) { if (!string.IsNullOrWhiteSpace(message.Content)) - yield return new { role, content = message.Content }; + yield return new JsonObject { ["role"] = role, ["content"] = message.Content }; foreach (var toolCall in message.ToolCalls) { - yield return new - { - type = "function_call", - call_id = toolCall.Id, - name = toolCall.Name, - arguments = toolCall.Arguments - }; + var callObj = new JsonObject { ["type"] = "function_call" }; + SetIfNotNull(callObj, "call_id", toolCall.Id); + SetIfNotNull(callObj, "name", toolCall.Name); + SetIfNotNull(callObj, "arguments", toolCall.Arguments); + yield return callObj; } yield break; @@ -1563,55 +1562,54 @@ private static IEnumerable ToResponsesInput(AgentChatMessage message) if (role == "assistant" && !string.IsNullOrWhiteSpace(message.ToolName)) { - yield return new - { - type = "function_call", - call_id = message.ToolCallId, - name = message.ToolName, - arguments = message.ToolArguments ?? "{}" - }; + var callObj = new JsonObject { ["type"] = "function_call" }; + SetIfNotNull(callObj, "call_id", message.ToolCallId); + callObj["name"] = message.ToolName; + callObj["arguments"] = message.ToolArguments ?? "{}"; + yield return callObj; yield break; } if (message.ContentParts is { Count: > 0 }) { - yield return new + yield return new JsonObject { - role = role is "system" or "user" or "assistant" ? role : "user", - content = ToResponsesContentParts(message) + ["role"] = role is "system" or "user" or "assistant" ? role : "user", + ["content"] = ToJsonArray(ToResponsesContentParts(message)) }; yield break; } - yield return new + var msg = new JsonObject { - role = role is "system" or "user" or "assistant" ? role : "user", - content = message.Content + ["role"] = role is "system" or "user" or "assistant" ? role : "user" }; + SetIfNotNull(msg, "content", message.Content); + yield return msg; } - private static IEnumerable ToResponsesContentParts(AgentChatMessage message) + private static IEnumerable ToResponsesContentParts(AgentChatMessage message) { if (!string.IsNullOrEmpty(message.Content)) - yield return new { type = "input_text", text = message.Content }; + yield return new JsonObject { ["type"] = "input_text", ["text"] = message.Content }; foreach (var part in message.ContentParts ?? []) { if (string.Equals(part.Type, "image", StringComparison.OrdinalIgnoreCase)) { - yield return new + yield return new JsonObject { - type = "input_image", - image_url = BuildImageDataUrl(part), - detail = "auto" + ["type"] = "input_image", + ["image_url"] = BuildImageDataUrl(part), + ["detail"] = "auto" }; } else { - yield return new + yield return new JsonObject { - type = "input_text", - text = FormatTextPart(part) + ["type"] = "input_text", + ["text"] = FormatTextPart(part) }; } } @@ -1633,14 +1631,17 @@ private static string FormatTextPart(AgentContentPart part) return filePrefix + (part.Text ?? string.Empty); } - private static object ToResponsesTool(AgentToolDefinition tool) - => new + private static JsonObject ToResponsesTool(AgentToolDefinition tool) + { + var obj = new JsonObject { - type = "function", - name = tool.Name, - description = tool.Description, - parameters = tool.Parameters + ["type"] = "function", + ["name"] = tool.Name }; + SetIfNotNull(obj, "description", tool.Description); + obj["parameters"] = ToJsonNode(tool.Parameters); + return obj; + } private static AgentModelResponse ParseResponsesResponse( string responseText, @@ -1810,14 +1811,9 @@ private static AgentToolCall CreateValidatedToolCall( return new AgentToolCall(id, name, normalizedArguments); } - private static string SerializeRequest(object body) + private static string SerializeRequest(JsonObject body) { - var json = JsonSerializer.Serialize( - body, - new JsonSerializerOptions - { - DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull - }); + var json = body.ToJsonString(); if (Encoding.UTF8.GetByteCount(json) > MaximumRequestBytes) { throw AgentProviderException.Request( @@ -1827,6 +1823,47 @@ private static string SerializeRequest(object body) return json; } + private static void SetIfNotNull(JsonObject target, string name, JsonNode? value) + { + if (value != null) + target[name] = value; + } + + private static void SetIfNotNull(JsonObject target, string name, string? value) + { + if (value != null) + target[name] = value; + } + + private static void SetIfNotNull(JsonObject target, string name, int? value) + { + if (value.HasValue) + target[name] = value.Value; + } + + private static void SetIfNotNull(JsonObject target, string name, double? value) + { + if (value.HasValue) + target[name] = value.Value; + } + + private static JsonArray ToJsonArray(IEnumerable items) + { + var array = new JsonArray(); + foreach (var item in items) + array.Add(item); + return array; + } + + private static JsonNode ToJsonNode(JsonElement element) + { + if (element.ValueKind is JsonValueKind.Undefined or JsonValueKind.Null) + return new JsonObject(); + + return JsonSerializer.SerializeToNode(element, AppCamelCaseJsonContext.Default.JsonElement) + ?? new JsonObject(); + } + private static async Task ReadResponseTextAsync( HttpResponseMessage response, CancellationToken cancellationToken) diff --git a/Services/Agent/SqliteAgentConversationHistoryStore.cs b/Services/Agent/SqliteAgentConversationHistoryStore.cs index 0c8dc35..f921dde 100644 --- a/Services/Agent/SqliteAgentConversationHistoryStore.cs +++ b/Services/Agent/SqliteAgentConversationHistoryStore.cs @@ -20,8 +20,6 @@ internal sealed record ConversationPayload( IReadOnlyList? ContextMessages, IReadOnlyList? Messages); - private static readonly JsonSerializerOptions JsonOptions = AppJsonOptions.CamelCase; - private readonly object _gate = new(); private readonly string _filePath; private readonly string _legacyFilePath; @@ -286,7 +284,7 @@ private static void AddRecordParameters( var payload = new ConversationPayload( conversation.ContextMessages, conversation.Messages); - var payloadJson = JsonSerializer.Serialize(payload, JsonOptions); + var payloadJson = JsonSerializer.Serialize(payload, AppCamelCaseJsonContext.Default.ConversationPayload); var encryptedPayload = PasswordEncryptionService.Encrypt(payloadJson); command.Parameters.AddWithValue("$conversation_id", conversation.ConversationId); @@ -308,7 +306,7 @@ private static void AddRecordParameters( try { var payloadJson = PasswordEncryptionService.Decrypt(reader.GetString(11)); - var payload = JsonSerializer.Deserialize(payloadJson, JsonOptions); + var payload = JsonSerializer.Deserialize(payloadJson, AppCamelCaseJsonContext.Default.ConversationPayload); if (payload?.Messages is not { Count: > 0 }) return null; diff --git a/Services/AppJsonContext.cs b/Services/AppJsonContext.cs index 699010c..0eb8e51 100644 --- a/Services/AppJsonContext.cs +++ b/Services/AppJsonContext.cs @@ -30,6 +30,9 @@ namespace CxShell.Services; [JsonSerializable(typeof(AgentRuntimeRunSnapshot[]))] [JsonSerializable(typeof(List))] [JsonSerializable(typeof(AgentRunRecoveryState[]))] +[JsonSerializable(typeof(Dictionary))] +[JsonSerializable(typeof(AgentSessionSnapshot))] +[JsonSerializable(typeof(AgentCommandVerification))] internal partial class AppJsonContext : JsonSerializerContext; [JsonSourceGenerationOptions(WriteIndented = true)] @@ -103,36 +106,73 @@ internal partial class AppIndentedJsonContext : JsonSerializerContext; [JsonSerializable(typeof(AgentCommandResult))] [JsonSerializable(typeof(AgentAuditEntry))] [JsonSerializable(typeof(AgentChatMessage))] +[JsonSerializable(typeof(List))] +[JsonSerializable(typeof(AgentChatMessage[]))] [JsonSerializable(typeof(AgentContentPart))] +[JsonSerializable(typeof(AgentWebSearchPayload))] [JsonSerializable(typeof(JsonElement))] [JsonSerializable(typeof(JsonObject))] +[JsonSerializable(typeof(JsonArray))] +[JsonSerializable(typeof(JsonValue))] [JsonSerializable(typeof(JsonNode))] [JsonSerializable(typeof(Dictionary))] [JsonSerializable(typeof(object[]))] +[JsonSerializable(typeof(string[]))] +[JsonSerializable(typeof(List))] +[JsonSerializable(typeof(string))] +[JsonSerializable(typeof(bool))] +[JsonSerializable(typeof(int))] +[JsonSerializable(typeof(long))] +[JsonSerializable(typeof(double))] +[JsonSerializable(typeof(AsciicastHeader))] internal partial class AppCamelCaseJsonContext : JsonSerializerContext; +internal sealed record AsciicastHeader(int Version, int Width, int Height, long Timestamp, string? Title); + internal static class AppJsonOptions { public static JsonSerializerOptions Default { get; } = new() { - TypeInfoResolver = JsonTypeInfoResolver.Combine( - AppJsonContext.Default, - new DefaultJsonTypeInfoResolver()) + TypeInfoResolver = AppJsonContext.Default }; public static JsonSerializerOptions Indented { get; } = new() { WriteIndented = true, - TypeInfoResolver = JsonTypeInfoResolver.Combine( - AppIndentedJsonContext.Default, - new DefaultJsonTypeInfoResolver()) + TypeInfoResolver = AppIndentedJsonContext.Default }; public static JsonSerializerOptions CamelCase { get; } = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase, - TypeInfoResolver = JsonTypeInfoResolver.Combine( - AppCamelCaseJsonContext.Default, - new DefaultJsonTypeInfoResolver()) + TypeInfoResolver = AppCamelCaseJsonContext.Default }; + + internal static Func? TestCamelCaseTypeInfoFallback { get; set; } + + internal static JsonElement EmptyObjectElement { get; } = + JsonDocument.Parse("{}").RootElement.Clone(); + + internal static JsonTypeInfo ResolveCamelCaseTypeInfo(Type type) + { + return AppCamelCaseJsonContext.Default.GetTypeInfo(type) + ?? TestCamelCaseTypeInfoFallback?.Invoke(type) + ?? throw new NotSupportedException( + $"Type '{type.FullName}' is not registered in AppCamelCaseJsonContext."); + } + + internal static JsonElement SerializeCamelCaseToElement(object value) + { + return value switch + { + JsonElement element => element.Clone(), + JsonNode node => JsonSerializer.SerializeToElement(node, AppCamelCaseJsonContext.Default.JsonNode), + _ => JsonSerializer.SerializeToElement(value, ResolveCamelCaseTypeInfo(value.GetType())) + }; + } + + internal static T? DeserializeCamelCase(JsonElement element) + { + return (T?)JsonSerializer.Deserialize(element, ResolveCamelCaseTypeInfo(typeof(T))); + } } diff --git a/Services/ApplicationSettingsStore.cs b/Services/ApplicationSettingsStore.cs index 91a394d..74512d6 100644 --- a/Services/ApplicationSettingsStore.cs +++ b/Services/ApplicationSettingsStore.cs @@ -11,7 +11,6 @@ namespace CxShell.Services; public sealed class ApplicationSettingsStore { private const string LegacyFileName = "application-settings.json"; - private static readonly JsonSerializerOptions ComparisonJsonOptions = AppJsonOptions.Default; private readonly string _directory; private readonly string _path; private readonly SqliteAppDataStore _store; @@ -48,16 +47,16 @@ public ApplicationSettings Load(ApplicationSettings? fallback = null) try { - var loaded = JsonSerializer.Deserialize(payload, AppJsonOptions.Default); + var loaded = JsonSerializer.Deserialize(payload, AppJsonContext.Default.ApplicationSettings); if (loaded == null) return Recover(fallback); using var document = JsonDocument.Parse(payload); var hasSchemaVersion = document.RootElement .TryGetProperty(nameof(ApplicationSettings.SchemaVersion), out _); - var beforeNormalization = JsonSerializer.Serialize(loaded, ComparisonJsonOptions); + var beforeNormalization = JsonSerializer.Serialize(loaded, AppJsonContext.Default.ApplicationSettings); Normalize(loaded); - var afterNormalization = JsonSerializer.Serialize(loaded, ComparisonJsonOptions); + var afterNormalization = JsonSerializer.Serialize(loaded, AppJsonContext.Default.ApplicationSettings); if (!hasSchemaVersion || !string.Equals( beforeNormalization, afterNormalization, @@ -81,7 +80,7 @@ public void Save(ApplicationSettings settings) ArgumentNullException.ThrowIfNull(settings); Normalize(settings); - var json = JsonSerializer.Serialize(settings, AppJsonOptions.Indented); + var json = JsonSerializer.Serialize(settings, AppIndentedJsonContext.Default.ApplicationSettings); _store.Write("application_settings", "default", json); } @@ -200,7 +199,7 @@ private static void NormalizeGlobalProxy(ProxySettings proxy) { try { - return JsonSerializer.Deserialize(json, AppJsonOptions.Default); + return JsonSerializer.Deserialize(json, AppJsonContext.Default.ApplicationSettings); } catch (JsonException) { diff --git a/Services/BastionTokenExchangeService.cs b/Services/BastionTokenExchangeService.cs index 90e6879..6f5db7e 100644 --- a/Services/BastionTokenExchangeService.cs +++ b/Services/BastionTokenExchangeService.cs @@ -51,7 +51,7 @@ private static HttpRequestMessage CreateRequest(string token, string endpoint) var request = new HttpRequestMessage(HttpMethod.Post, endpoint) { Content = new StringContent( - JsonSerializer.Serialize(new TokenExchangeRequest(token), AppJsonOptions.Default), + JsonSerializer.Serialize(new TokenExchangeRequest(token), AppJsonContext.Default.TokenExchangeRequest), Encoding.UTF8, "application/json") }; diff --git a/Services/ConnectionAuditService.cs b/Services/ConnectionAuditService.cs index 157ec42..b709809 100644 --- a/Services/ConnectionAuditService.cs +++ b/Services/ConnectionAuditService.cs @@ -168,7 +168,7 @@ public void Export(string path, IReadOnlyList? entries = n { ArgumentException.ThrowIfNullOrWhiteSpace(path); var exportEntries = entries ?? ReadRecent(); - var json = JsonSerializer.Serialize(exportEntries, AppJsonOptions.Indented); + var json = JsonSerializer.Serialize(exportEntries, AppIndentedJsonContext.Default.IReadOnlyListConnectionAuditEntry); File.WriteAllText(path, json, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true)); } @@ -197,14 +197,14 @@ private List GetEntriesUnsafe() private void SaveUnsafe(IReadOnlyList entries) { - _store.Write("connection_audit", "entries", JsonSerializer.Serialize(entries, AppJsonOptions.Default)); + _store.Write("connection_audit", "entries", JsonSerializer.Serialize(entries, AppJsonContext.Default.IReadOnlyListConnectionAuditEntry)); } private static List? TryDeserialize(string json) { try { - return JsonSerializer.Deserialize>(json, AppJsonOptions.Default); + return JsonSerializer.Deserialize(json, AppJsonContext.Default.ListConnectionAuditEntry); } catch (JsonException) { diff --git a/Services/LocalizationService.cs b/Services/LocalizationService.cs index d5b94b3..e9a1c6c 100644 --- a/Services/LocalizationService.cs +++ b/Services/LocalizationService.cs @@ -180,6 +180,7 @@ public sealed class LocalizationService : INotifyPropertyChanged ["FullScreenBar.Unpin"] = "Unpin the connection bar (auto hide)", ["FullScreenBar.Minimize"] = "Minimize", ["FullScreenBar.Restore"] = "Restore window", + ["FullScreenBar.ToggleFullScreen"] = "Toggle full screen (F11)", ["FullScreenBar.Close"] = "Close this session", ["FullScreenBar.Quality"] = "Link quality", ["FullScreenBar.QualityGood"] = "Good", @@ -541,6 +542,7 @@ public sealed class LocalizationService : INotifyPropertyChanged ["FullScreenBar.Unpin"] = "取消固定(自动隐藏)", ["FullScreenBar.Minimize"] = "最小化", ["FullScreenBar.Restore"] = "还原窗口", + ["FullScreenBar.ToggleFullScreen"] = "切换全屏 (F11)", ["FullScreenBar.Close"] = "关闭当前会话", ["FullScreenBar.Quality"] = "网络质量", ["FullScreenBar.QualityGood"] = "良好", @@ -2241,12 +2243,21 @@ private static void AddGeneratedTexts(Dictionary english, Dictio english["UiText.088"] = "Resize screen (C):"; english["UiText.089"] = "Color quality (Q):"; english["SessionEdit.RdpSecurityMode"] = "Security mode:"; + english["SessionEdit.RdpWindowModeSection"] = "Window Mode"; + english["SessionEdit.RdpWindowModeLabel"] = "Open Mode:"; + english["SessionEdit.RdpWindowMode.Default"] = "Default (Main window tab)"; + english["SessionEdit.RdpWindowMode.MultiTab"] = "Multi-tab window"; + english["SessionEdit.RdpWindowMode.Standalone"] = "Standalone window (Multi-monitor)"; + english["SessionEdit.RdpOpenInStandaloneWindow"] = "Open in standalone RDP multi-tab window"; english["SessionEdit.RdpSyncLockKeys"] = "Sync CapsLock / NumLock / ScrollLock state"; english["SessionEdit.RdpSyncLockKeysHint"] = "Automatically synchronize local lock key states to the remote session on connect or focus."; english["SessionEdit.RdpEnableClipboardLock"] = "Enable clipboard large file locking (LockClipboardData)"; english["SessionEdit.RdpEnableClipboardLockHint"] = "Lock clipboard file snapshots during large file transfers so copying other content does not abort transfers."; english["Rdp.MultiMonitor"] = "Multi-Monitor"; english["Rdp.MultiMonitorTip"] = "Multi-monitor / Virtual screen settings"; + english["Rdp.MoveToWorkspace"] = "Move to multi-tab RDP window (single monitor)"; + english["Rdp.OpenInWorkspace"] = "Open in multi-tab RDP window"; + english["Rdp.OpenInDetachedWindow"] = "Open in standalone window (multi-monitor)"; english["Rdp.MultiMonitorPrompt"] = "Monitors to use (switches live)"; english["Rdp.AddVirtualMonitor"] = "+ Add virtual screen (separate window)"; english["Rdp.UltrawideSection"] = "Ultrawide / split layout"; @@ -2525,12 +2536,21 @@ private static void AddGeneratedTexts(Dictionary english, Dictio chinese["UiText.088"] = "改变屏幕大小(C):"; chinese["UiText.089"] = "颜色质量(Q):"; chinese["SessionEdit.RdpSecurityMode"] = "安全模式:"; + chinese["SessionEdit.RdpWindowModeSection"] = "窗口模式"; + chinese["SessionEdit.RdpWindowModeLabel"] = "打开方式:"; + chinese["SessionEdit.RdpWindowMode.Default"] = "默认(主窗口标签页)"; + chinese["SessionEdit.RdpWindowMode.MultiTab"] = "多标签"; + chinese["SessionEdit.RdpWindowMode.Standalone"] = "独立窗体(支持多屏)"; + chinese["SessionEdit.RdpOpenInStandaloneWindow"] = "在独立的 RDP 多标签窗口中打开"; chinese["SessionEdit.RdpSyncLockKeys"] = "同步 CapsLock / NumLock / ScrollLock 锁定键状态"; chinese["SessionEdit.RdpSyncLockKeysHint"] = "连接或切入 RDP 窗口时自动将本地大小写与小键盘锁定状态同步到远端。"; chinese["SessionEdit.RdpEnableClipboardLock"] = "启用剪贴板大文件锁定 (LockClipboardData)"; chinese["SessionEdit.RdpEnableClipboardLockHint"] = "通过剪贴板传输大文件时锁定快照,防止中途复制其他内容导致传输中断。"; chinese["Rdp.MultiMonitor"] = "多显示器"; chinese["Rdp.MultiMonitorTip"] = "多显示器 / 虚拟屏幕设置"; + chinese["Rdp.MoveToWorkspace"] = "移入多标签 RDP 窗口(自动收敛为单屏)"; + chinese["Rdp.OpenInWorkspace"] = "在独立多标签窗口打开"; + chinese["Rdp.OpenInDetachedWindow"] = "在独立窗体打开(支持多屏)"; chinese["Rdp.MultiMonitorPrompt"] = "选择要启用的显示器(实时热切换)"; chinese["Rdp.AddVirtualMonitor"] = "+ 新增虚拟屏(独立窗体)"; chinese["Rdp.UltrawideSection"] = "带鱼屏 / 虚拟分屏模式"; diff --git a/Services/RdpSecurityProfileCache.cs b/Services/RdpSecurityProfileCache.cs index c600f4a..facbb1a 100644 --- a/Services/RdpSecurityProfileCache.cs +++ b/Services/RdpSecurityProfileCache.cs @@ -85,7 +85,7 @@ public static void Store(string host, int port, string profile) var directory = Path.GetDirectoryName(CachePath); if (!string.IsNullOrEmpty(directory)) Directory.CreateDirectory(directory); - File.WriteAllText(CachePath, JsonSerializer.Serialize(_profiles)); + File.WriteAllText(CachePath, JsonSerializer.Serialize(_profiles, AppJsonContext.Default.DictionaryStringString)); } catch { @@ -112,7 +112,7 @@ private static void EnsureLoaded() { if (File.Exists(CachePath)) { - var parsed = JsonSerializer.Deserialize>(File.ReadAllText(CachePath)); + var parsed = JsonSerializer.Deserialize(File.ReadAllText(CachePath), AppJsonContext.Default.DictionaryStringString); if (parsed != null) { foreach (var pair in parsed) diff --git a/Services/SessionRecordingStore.cs b/Services/SessionRecordingStore.cs index b9429df..eeb080d 100644 --- a/Services/SessionRecordingStore.cs +++ b/Services/SessionRecordingStore.cs @@ -11,7 +11,6 @@ public sealed class SessionRecordingStore private readonly string _storageDirectory; private readonly SqliteAppDataStore _metadataStore; private readonly SemaphoreSlim _gate = new(1, 1); - private readonly JsonSerializerOptions _jsonOptions = AppJsonOptions.Indented; public static SessionRecordingStore Shared { get; } = new( Path.Combine(SessionStorageService.GetStorageDirectory(), "recordings"), @@ -30,7 +29,7 @@ public async Task SaveAsync(SessionRecording recording, CancellationToken cancel try { Directory.CreateDirectory(_storageDirectory); - var json = JsonSerializer.Serialize(recording, _jsonOptions); + var json = JsonSerializer.Serialize(recording, AppIndentedJsonContext.Default.SessionRecording); _metadataStore.Write("session_recordings", recording.Id.ToString("N"), json); SqliteAppDataStore.ArchiveLegacyFile(GetMetadataPath(recording.Id)); } @@ -203,7 +202,7 @@ private void MigrateLegacyMetadataFiles(CancellationToken cancellationToken) { try { - return JsonSerializer.Deserialize(json, AppJsonOptions.Default); + return JsonSerializer.Deserialize(json, AppJsonContext.Default.SessionRecording); } catch (JsonException) { diff --git a/Services/SessionStorageService.cs b/Services/SessionStorageService.cs index f667500..acd1aee 100644 --- a/Services/SessionStorageService.cs +++ b/Services/SessionStorageService.cs @@ -70,7 +70,7 @@ public void Save(SessionData data) QuickSessionIds = data.QuickSessionIds, ExportedAt = data.ExportedAt }; - var json = System.Text.Json.JsonSerializer.Serialize(persisted, AppJsonOptions.Default); + var json = System.Text.Json.JsonSerializer.Serialize(persisted, AppJsonContext.Default.SessionData); _store.Write("sessions", "default", json); } @@ -78,7 +78,7 @@ public void Save(SessionData data) { try { - return System.Text.Json.JsonSerializer.Deserialize(json, AppJsonOptions.Default); + return System.Text.Json.JsonSerializer.Deserialize(json, AppJsonContext.Default.SessionData); } catch (System.Text.Json.JsonException) { diff --git a/Services/SessionTransferService.cs b/Services/SessionTransferService.cs index bfbdda7..c688d77 100644 --- a/Services/SessionTransferService.cs +++ b/Services/SessionTransferService.cs @@ -8,8 +8,6 @@ public static class SessionTransferService public const string StorageFormat = "CxShell.Session"; public const string Format = "CxShell.SessionExport"; - private static readonly JsonSerializerOptions JsonOptions = AppJsonOptions.Indented; - public static void Export(string path, IEnumerable groups, IEnumerable sessions) { var selectedSessions = sessions.ToList(); @@ -41,7 +39,7 @@ public static void Export(string path, IEnumerable groups, IEnumer QuickSessionIds = new List() }; - var json = JsonSerializer.Serialize(package, JsonOptions); + var json = JsonSerializer.Serialize(package, AppIndentedJsonContext.Default.SessionData); File.WriteAllText(path, json); } @@ -49,7 +47,7 @@ public static SessionData Load(string path) { var json = File.ReadAllText(path); - var package = JsonSerializer.Deserialize(json, AppJsonOptions.Default) + var package = JsonSerializer.Deserialize(json, AppJsonContext.Default.SessionData) ?? throw new InvalidDataException("The session export file is empty."); if ((!string.Equals(package.Format, Format, StringComparison.Ordinal) && @@ -116,8 +114,8 @@ private static SessionGroup CloneGroup(SessionGroup source) private static SessionInfo CloneSessionForExport(SessionInfo source) { - var json = JsonSerializer.Serialize(source, JsonOptions); - var clone = JsonSerializer.Deserialize(json, AppJsonOptions.Default) + var json = JsonSerializer.Serialize(source, AppIndentedJsonContext.Default.SessionInfo); + var clone = JsonSerializer.Deserialize(json, AppJsonContext.Default.SessionInfo) ?? throw new InvalidDataException("Failed to copy a session for export."); clone.Password = KeepEncryptedOrEmpty(clone.Password); diff --git a/Services/SftpTransferQueueStore.cs b/Services/SftpTransferQueueStore.cs index f668e23..d9eb3e4 100644 --- a/Services/SftpTransferQueueStore.cs +++ b/Services/SftpTransferQueueStore.cs @@ -84,7 +84,7 @@ private List LoadCore() if (payload == null) return []; - var data = JsonSerializer.Deserialize(payload, AppJsonOptions.Default); + var data = JsonSerializer.Deserialize(payload, AppJsonContext.Default.SftpTransferQueueData); if (data == null || !string.Equals(data.Format, "CxShell.SftpTransferQueue", StringComparison.Ordinal) || !string.Equals(data.Version, "1.0", StringComparison.Ordinal)) @@ -115,7 +115,7 @@ private void SaveCore(IEnumerable records) .Take(MaxRecords) .ToList() }; - _store.Write(Collection, ItemKey, JsonSerializer.Serialize(data, AppJsonOptions.Default)); + _store.Write(Collection, ItemKey, JsonSerializer.Serialize(data, AppJsonContext.Default.SftpTransferQueueData)); } catch { @@ -127,7 +127,7 @@ private static bool IsValidLegacyQueue(string json) { try { - var data = JsonSerializer.Deserialize(json, AppJsonOptions.Default); + var data = JsonSerializer.Deserialize(json, AppJsonContext.Default.SftpTransferQueueData); return data != null && string.Equals(data.Format, "CxShell.SftpTransferQueue", StringComparison.Ordinal) && string.Equals(data.Version, "1.0", StringComparison.Ordinal); diff --git a/Services/SingleInstanceChannel.cs b/Services/SingleInstanceChannel.cs index 6f02c42..35943ee 100644 --- a/Services/SingleInstanceChannel.cs +++ b/Services/SingleInstanceChannel.cs @@ -392,7 +392,7 @@ private static string EncodePayload(string[] args) { var json = JsonSerializer.SerializeToUtf8Bytes( new CommandLineHandoffService.HandoffPayload(args), - AppJsonOptions.Default); + AppJsonContext.Default.HandoffPayload); return Convert.ToBase64String(json); } @@ -405,9 +405,9 @@ private static bool TryDecodePayload(string? payload, out string[] args) try { var json = Convert.FromBase64String(payload.Trim()); - var decoded = JsonSerializer.Deserialize( + var decoded = JsonSerializer.Deserialize( json, - AppJsonOptions.Default); + AppJsonContext.Default.HandoffPayload); if (decoded == null) return false; diff --git a/Services/SshAgentForwardingService.cs b/Services/SshAgentForwardingService.cs index cf5fa93..019158d 100644 --- a/Services/SshAgentForwardingService.cs +++ b/Services/SshAgentForwardingService.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; @@ -297,6 +298,7 @@ private static void WriteString(Stream stream, byte[] value) stream.Write(value, 0, value.Length); } + [UnconditionalSuppressMessage("Trimming", "IL2075", Justification = "Renci.SshNet internal members are preserved via ILLink.Descriptors.xml.")] private void AttachSessionEvent(string eventName, string handlerName) { if (_session == null) @@ -312,6 +314,7 @@ private void AttachSessionEvent(string eventName, string handlerName) _eventHandlers.Add((eventInfo, handler)); } + [UnconditionalSuppressMessage("Trimming", "IL2075", Justification = "Renci.SshNet internal members are preserved via ILLink.Descriptors.xml.")] private void SendMessage(Message message) { if (_session == null) @@ -325,11 +328,13 @@ private void SendMessage(Message message) method?.Invoke(_session, [message]); } + [UnconditionalSuppressMessage("Trimming", "IL2075", Justification = "Renci.SshNet internal members are preserved via ILLink.Descriptors.xml.")] private static T? GetMessage(EventArgs args) where T : class { return args.GetType().GetProperty("Message")?.GetValue(args) as T; } + [UnconditionalSuppressMessage("Trimming", "IL2075", Justification = "Renci.SshNet internal members are preserved via ILLink.Descriptors.xml.")] private static object? GetPrivateField(object instance, string name) { return instance.GetType() @@ -337,6 +342,7 @@ private void SendMessage(Message message) ?.GetValue(instance); } + [UnconditionalSuppressMessage("Trimming", "IL2075", Justification = "Renci.SshNet internal members are preserved via ILLink.Descriptors.xml.")] private static uint GetUIntProperty(object instance, string name) { return (uint)(instance.GetType() diff --git a/Services/SshConnectionService.cs b/Services/SshConnectionService.cs index 774a30f..5c848e4 100644 --- a/Services/SshConnectionService.cs +++ b/Services/SshConnectionService.cs @@ -2,7 +2,6 @@ using System.Buffers; using System.Collections.Generic; using System.IO; -using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; @@ -1242,40 +1241,11 @@ public void ResizeTerminal(TerminalPtySize size) if (_shellStream == null) return; - // SSH.NET keeps the session channel private; send the PTY window-change - // request through that channel so remote readline/bash wrap at our width. - var channelField = typeof(ShellStream).GetField( - "_channel", - BindingFlags.Instance | BindingFlags.NonPublic); - var channel = channelField?.GetValue(_shellStream); - if (channel == null || channelField == null) - return; - - var method = channelField.FieldType.GetMethod( - "SendWindowChangeRequest", - BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, - binder: null, - types: new[] { typeof(uint), typeof(uint), typeof(uint), typeof(uint) }, - modifiers: null) - ?? channel.GetType().GetMethod( - "SendWindowChangeRequest", - BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, - binder: null, - types: new[] { typeof(uint), typeof(uint), typeof(uint), typeof(uint) }, - modifiers: null); - if (method == null) - { - ErrorOccurred?.Invoke("SSH terminal resize failed: SendWindowChangeRequest was not found."); - return; - } - - method.Invoke(channel, new object[] - { + _shellStream.ChangeWindowSize( (uint)Math.Max(1, size.Columns), (uint)Math.Max(1, size.Rows), (uint)Math.Max(0, size.PixelWidth), - (uint)Math.Max(0, size.PixelHeight) - }); + (uint)Math.Max(0, size.PixelHeight)); } catch (Exception ex) { diff --git a/Services/SshHostKeyTrustService.cs b/Services/SshHostKeyTrustService.cs index f9757f9..07aceeb 100644 --- a/Services/SshHostKeyTrustService.cs +++ b/Services/SshHostKeyTrustService.cs @@ -239,14 +239,14 @@ private void SaveFile(KnownHostsFile file) _store.Write( "ssh_host_keys", "trusted_hosts", - JsonSerializer.Serialize(file, AppJsonOptions.Default)); + JsonSerializer.Serialize(file, AppJsonContext.Default.KnownHostsFile)); } private static KnownHostsFile? TryDeserializeKnownHosts(string json) { try { - var file = JsonSerializer.Deserialize(json, AppJsonOptions.Default); + var file = JsonSerializer.Deserialize(json, AppJsonContext.Default.KnownHostsFile); if (file == null) return null; file.Hosts ??= []; diff --git a/Services/WindowsVirtualFileDragDropService.cs b/Services/WindowsVirtualFileDragDropService.cs index f04ffca..73a5d65 100644 --- a/Services/WindowsVirtualFileDragDropService.cs +++ b/Services/WindowsVirtualFileDragDropService.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; -using System.Runtime.InteropServices.ComTypes; +using System.Runtime.InteropServices.Marshalling; using System.Runtime.Versioning; using System.Threading; @@ -93,9 +93,11 @@ internal void RequestCancellation() } } -public static class WindowsVirtualFileDragDropService +public static partial class WindowsVirtualFileDragDropService { private static readonly object DebugLogSync = new(); + private static readonly Guid IidIStream = new("0000000C-0000-0000-C000-000000000046"); + internal static readonly StrategyBasedComWrappers ComWrappers = new(); public static bool IsSupported => OperatingSystem.IsWindows(); public static string DebugLogPath => Path.Combine(AppDataPaths.GetLogsDirectory(), "sftp-drag.log"); @@ -137,33 +139,46 @@ public static int DoDragDrop(IReadOnlyList files) } } - private const int DropEffectNone = 0; - private const int DropEffectCopy = 1; - private const int MkLButton = 0x0001; - private const int SOk = 0; - private const int DragDropSDrop = 0x00040100; - private const int DragDropSCancel = 0x00040101; - private const int DragDropSUseDefaultCursors = 0x00040102; - - [DllImport("ole32.dll", PreserveSig = true)] - private static extern int DoDragDrop( - IDataObject dataObject, + [SupportedOSPlatform("windows")] + internal static object CreateDataObjectForTest(IReadOnlyList files) + => new VirtualFileDataObject(files); + + [SupportedOSPlatform("windows")] + internal static object CreateDropSourceForTest() + => new DropSource(); + + internal const int DropEffectNone = 0; + internal const int DropEffectCopy = 1; + internal const int MkLButton = 0x0001; + internal const int SOk = 0; + internal const int SFalse = 1; + internal const int DragDropSDrop = 0x00040100; + internal const int DragDropSCancel = 0x00040101; + internal const int DragDropSUseDefaultCursors = 0x00040102; + internal const uint DvaspectContent = 1; + internal const uint TymedHGlobal = 1; + internal const uint TymedIStream = 4; + internal const uint DataDirGet = 1; + internal const int DvEFormatEtc = unchecked((int)0x80040064); + + [LibraryImport("ole32.dll")] + private static partial int DoDragDrop( + INativeDataObject dataObject, IDropSource dropSource, int okEffects, out int effect); - [DllImport("user32.dll", CharSet = CharSet.Unicode)] - private static extern ushort RegisterClipboardFormat(string format); + [LibraryImport("user32.dll", EntryPoint = "RegisterClipboardFormatW", StringMarshalling = StringMarshalling.Utf16)] + private static partial ushort RegisterClipboardFormat(string format); - private static int OleDoDragDrop(IDataObject dataObject, IDropSource dropSource, int okEffects, out int effect) + private static int OleDoDragDrop(INativeDataObject dataObject, IDropSource dropSource, int okEffects, out int effect) { return DoDragDrop(dataObject, dropSource, okEffects, out effect); } - [ComImport] + [GeneratedComInterface] [Guid("00000121-0000-0000-C000-000000000046")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - private interface IDropSource + internal partial interface IDropSource { [PreserveSig] int QueryContinueDrag([MarshalAs(UnmanagedType.Bool)] bool escapePressed, int keyState); @@ -172,10 +187,9 @@ private interface IDropSource int GiveFeedback(int effect); } - [ComImport] + [GeneratedComInterface] [Guid("3D8B0590-F691-11D2-8EA9-006097DF5BD4")] - [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - private interface IAsyncOperation + internal partial interface IAsyncOperation { [PreserveSig] int SetAsyncMode([MarshalAs(UnmanagedType.Bool)] bool doOperationAsync); @@ -193,7 +207,100 @@ private interface IAsyncOperation int EndOperation(int result, IntPtr reservedBindContext, int effects); } - private sealed class DropSource : IDropSource + [GeneratedComInterface] + [Guid("0000010E-0000-0000-C000-000000000046")] + internal partial interface INativeDataObject + { + [PreserveSig] + int GetData(in NativeFormatEtc format, out NativeStgMedium medium); + + [PreserveSig] + int GetDataHere(in NativeFormatEtc format, ref NativeStgMedium medium); + + [PreserveSig] + int QueryGetData(in NativeFormatEtc format); + + [PreserveSig] + int GetCanonicalFormatEtc(in NativeFormatEtc formatIn, out NativeFormatEtc formatOut); + + [PreserveSig] + int SetData(in NativeFormatEtc formatIn, in NativeStgMedium medium, [MarshalAs(UnmanagedType.Bool)] bool release); + + [PreserveSig] + int EnumFormatEtc(uint direction, out INativeEnumFormatEtc? enumFormatEtc); + + [PreserveSig] + int DAdvise(in NativeFormatEtc format, uint advf, IntPtr adviseSink, out uint connection); + + [PreserveSig] + int DUnadvise(uint connection); + + [PreserveSig] + int EnumDAdvise(out IntPtr enumAdvise); + } + + [GeneratedComInterface] + [Guid("00000103-0000-0000-C000-000000000046")] + internal unsafe partial interface INativeEnumFormatEtc + { + [PreserveSig] + int Next(uint celt, NativeFormatEtc* rgelt, uint* pceltFetched); + + [PreserveSig] + int Skip(uint celt); + + [PreserveSig] + int Reset(); + + [PreserveSig] + int Clone(out INativeEnumFormatEtc? newEnum); + } + + [GeneratedComInterface] + [Guid("0C733A30-2A1C-11CE-ADE5-00AA0044773D")] + internal unsafe partial interface INativeSequentialStream + { + [PreserveSig] + int Read(byte* pv, uint cb, uint* pcbRead); + + [PreserveSig] + int Write(byte* pv, uint cb, uint* pcbWritten); + } + + [GeneratedComInterface] + [Guid("0000000C-0000-0000-C000-000000000046")] + internal unsafe partial interface INativeStream : INativeSequentialStream + { + [PreserveSig] + int Seek(long dlibMove, uint dwOrigin, ulong* plibNewPosition); + + [PreserveSig] + int SetSize(ulong libNewSize); + + [PreserveSig] + int CopyTo(INativeStream? destination, ulong cb, ulong* pcbRead, ulong* pcbWritten); + + [PreserveSig] + int Commit(uint grfCommitFlags); + + [PreserveSig] + int Revert(); + + [PreserveSig] + int LockRegion(ulong libOffset, ulong cb, uint dwLockType); + + [PreserveSig] + int UnlockRegion(ulong libOffset, ulong cb, uint dwLockType); + + [PreserveSig] + int Stat(NativeStatStg* stat, uint grfStatFlag); + + [PreserveSig] + int Clone(out INativeStream? clone); + } + + [GeneratedComClass] + private sealed partial class DropSource : IDropSource { public int QueryContinueDrag(bool escapePressed, int keyState) { @@ -210,12 +317,13 @@ public int GiveFeedback(int effect) } [SupportedOSPlatform("windows")] - private sealed class VirtualFileDataObject : IDataObject, IAsyncOperation + [GeneratedComClass] + private sealed partial class VirtualFileDataObject : INativeDataObject, IAsyncOperation { private static readonly short FileGroupDescriptorW = unchecked((short)RegisterClipboardFormat("FileGroupDescriptorW")); private static readonly short FileContents = unchecked((short)RegisterClipboardFormat("FileContents")); private readonly IReadOnlyList _files; - private readonly FORMATETC[] _formats; + private readonly NativeFormatEtc[] _formats; private readonly object _streamSync = new(); private readonly List _openStreams = []; private bool _asyncMode; @@ -226,40 +334,40 @@ public VirtualFileDataObject(IReadOnlyList files) _files = files; _formats = [ - new FORMATETC + new NativeFormatEtc { cfFormat = FileGroupDescriptorW, - dwAspect = DVASPECT.DVASPECT_CONTENT, + dwAspect = DvaspectContent, lindex = -1, - tymed = TYMED.TYMED_HGLOBAL + tymed = TymedHGlobal }, - new FORMATETC + new NativeFormatEtc { cfFormat = FileContents, - dwAspect = DVASPECT.DVASPECT_CONTENT, + dwAspect = DvaspectContent, lindex = -1, - tymed = TYMED.TYMED_ISTREAM + tymed = TymedIStream } ]; } - public void GetData(ref FORMATETC format, out STGMEDIUM medium) + public int GetData(in NativeFormatEtc format, out NativeStgMedium medium) { medium = default; - if (format.cfFormat == FileGroupDescriptorW && Allows(format.tymed, TYMED.TYMED_HGLOBAL)) + if (format.cfFormat == FileGroupDescriptorW && Allows(format.tymed, TymedHGlobal)) { - medium.tymed = TYMED.TYMED_HGLOBAL; + medium.tymed = TymedHGlobal; medium.unionmember = CreateFileGroupDescriptor(_files); - medium.pUnkForRelease = null; - return; + medium.pUnkForRelease = IntPtr.Zero; + return SOk; } - if (format.cfFormat == FileContents && Allows(format.tymed, TYMED.TYMED_ISTREAM)) + if (format.cfFormat == FileContents && Allows(format.tymed, TymedIStream)) { var index = format.lindex < 0 ? 0 : format.lindex; if (index >= _files.Count) - ThrowHResult(DvEFormatEtc); + return DvEFormatEtc; var file = _files[index]; RemoteComReadStream stream; @@ -277,75 +385,91 @@ public void GetData(ref FORMATETC format, out STGMEDIUM medium) { DebugLog($"stream request cancelled index={index} file={file.FileName}"); file.NotifyCancelled(); - throw; + return EAbort; } catch (Exception ex) { DebugLog($"stream request failed index={index} file={file.FileName} type={ex.GetType().Name} message={ex.Message}"); file.NotifyFailed(ex); - throw; + return Marshal.GetHRForException(ex); } - medium.tymed = TYMED.TYMED_ISTREAM; - medium.unionmember = Marshal.GetComInterfaceForObject(stream, typeof(IStream)); - medium.pUnkForRelease = null; - return; + var unknownPtr = ComWrappers.GetOrCreateComInterfaceForObject(stream, CreateComInterfaceFlags.None); + try + { + var iid = IidIStream; + var qiHr = Marshal.QueryInterface(unknownPtr, in iid, out var streamPtr); + if (qiHr < 0) + return qiHr; + + medium.tymed = TymedIStream; + medium.unionmember = streamPtr; + medium.pUnkForRelease = IntPtr.Zero; + return SOk; + } + finally + { + Marshal.Release(unknownPtr); + } } - ThrowHResult(DvEFormatEtc); + return DvEFormatEtc; } - public void GetDataHere(ref FORMATETC format, ref STGMEDIUM medium) + public int GetDataHere(in NativeFormatEtc format, ref NativeStgMedium medium) { - ThrowHResult(DvEFormatEtc); + return DvEFormatEtc; } - public int QueryGetData(ref FORMATETC format) + public int QueryGetData(in NativeFormatEtc format) { - if (format.cfFormat == FileGroupDescriptorW && Allows(format.tymed, TYMED.TYMED_HGLOBAL)) + if (format.cfFormat == FileGroupDescriptorW && Allows(format.tymed, TymedHGlobal)) return SOk; - if (format.cfFormat == FileContents && Allows(format.tymed, TYMED.TYMED_ISTREAM)) + if (format.cfFormat == FileContents && Allows(format.tymed, TymedIStream)) return SOk; return DvEFormatEtc; } - public int GetCanonicalFormatEtc(ref FORMATETC formatIn, out FORMATETC formatOut) + public int GetCanonicalFormatEtc(in NativeFormatEtc formatIn, out NativeFormatEtc formatOut) { formatOut = formatIn; formatOut.ptd = IntPtr.Zero; return DataSUnableToRender; } - public void SetData(ref FORMATETC formatIn, ref STGMEDIUM medium, bool release) + public int SetData(in NativeFormatEtc formatIn, in NativeStgMedium medium, bool release) { - ThrowHResult(OleENotSupported); + return OleENotSupported; } - public IEnumFORMATETC EnumFormatEtc(DATADIR direction) + public int EnumFormatEtc(uint direction, out INativeEnumFormatEtc? enumFormatEtc) { - if (direction == DATADIR.DATADIR_GET) - return new FormatEtcEnumerator(_formats); + if (direction == DataDirGet) + { + enumFormatEtc = new FormatEtcEnumerator(_formats); + return SOk; + } - ThrowHResult(OleENotSupported); - return null!; + enumFormatEtc = null; + return OleENotSupported; } - public int DAdvise(ref FORMATETC pFormatetc, ADVF advf, IAdviseSink adviseSink, out int connection) + public int DAdvise(in NativeFormatEtc format, uint advf, IntPtr adviseSink, out uint connection) { connection = 0; return OleEAdviseNotSupported; } - public void DUnadvise(int connection) + public int DUnadvise(uint connection) { - ThrowHResult(OleEAdviseNotSupported); + return OleEAdviseNotSupported; } - public int EnumDAdvise(out IEnumSTATDATA enumAdvise) + public int EnumDAdvise(out IntPtr enumAdvise) { - enumAdvise = null!; + enumAdvise = IntPtr.Zero; return OleEAdviseNotSupported; } @@ -454,34 +578,40 @@ private void DisposeStreamsInBackground() stream.DisposeInBackground(); } - private static bool Allows(TYMED actual, TYMED expected) + private static bool Allows(uint actual, uint expected) { return (actual & expected) == expected; } - private static IntPtr CreateFileGroupDescriptor(IReadOnlyList files) + private static unsafe IntPtr CreateFileGroupDescriptor(IReadOnlyList files) { - var descriptorSize = Marshal.SizeOf(); + var descriptorSize = sizeof(NativeFileDescriptor); var totalSize = sizeof(uint) + descriptorSize * files.Count; var handle = Marshal.AllocHGlobal(totalSize); - Marshal.WriteInt32(handle, files.Count); + *(uint*)handle = (uint)files.Count; + var descriptors = (NativeFileDescriptor*)((byte*)handle + sizeof(uint)); for (var index = 0; index < files.Count; index++) { var file = files[index]; - var descriptor = new FileDescriptor + var descriptor = new NativeFileDescriptor { dwFlags = FileDescriptorFlags.FdAttributes | FileDescriptorFlags.FdFileSize | FileDescriptorFlags.FdWriteTime, dwFileAttributes = FileAttributeNormal, nFileSizeHigh = (uint)((ulong)file.Size >> 32), - nFileSizeLow = (uint)((ulong)file.Size & 0xffffffff), - cFileName = SanitizeShellFileName(file.FileName) + nFileSizeLow = (uint)((ulong)file.Size & 0xffffffff) }; var fileTime = file.LastModified.ToFileTimeUtc(); descriptor.ftLastWriteTime.dwLowDateTime = unchecked((int)(fileTime & 0xffffffff)); descriptor.ftLastWriteTime.dwHighDateTime = unchecked((int)(fileTime >> 32)); - Marshal.StructureToPtr(descriptor, IntPtr.Add(handle, sizeof(uint) + descriptorSize * index), false); + + var sanitized = SanitizeShellFileName(file.FileName); + var copyLength = Math.Min(sanitized.Length, 259); + sanitized.AsSpan(0, copyLength).CopyTo(new Span(descriptor.cFileName, 260)); + descriptor.cFileName[copyLength] = '\0'; + + descriptors[index] = descriptor; } return handle; @@ -501,7 +631,8 @@ private static string SanitizeShellFileName(string name) } } - private sealed class RemoteComReadStream : IStream + [GeneratedComClass] + private sealed unsafe partial class RemoteComReadStream : INativeStream { private Stream? _stream; private readonly VirtualDragFile _file; @@ -519,27 +650,27 @@ public RemoteComReadStream(Stream stream, VirtualDragFile file) DisposeInBackground(); } - public void Read(byte[] buffer, int count, IntPtr bytesRead) + public int Read(byte* pv, uint cb, uint* pcbRead) { + if (pcbRead != null) + *pcbRead = 0; + var stream = _stream; - if (stream == null) - { - if (bytesRead != IntPtr.Zero) - Marshal.WriteInt32(bytesRead, 0); - return; - } + if (stream == null || cb == 0 || pv == null) + return SOk; try { _file.CancellationToken.ThrowIfCancellationRequested(); - var read = stream.Read(buffer, 0, count); - if (bytesRead != IntPtr.Zero) - Marshal.WriteInt32(bytesRead, read); + var count = (int)Math.Min(cb, int.MaxValue); + var read = stream.Read(new Span(pv, count)); + if (pcbRead != null) + *pcbRead = (uint)read; if (read <= 0) { LogCompletion(); - return; + return SOk; } var position = stream.CanSeek @@ -550,76 +681,98 @@ public void Read(byte[] buffer, int count, IntPtr bytesRead) { LogCompletion(); } + + return SOk; } catch (OperationCanceledException) { _file.NotifyCancelled(); - throw; + return EAbort; } catch (Exception ex) { _file.NotifyFailed(ex); - throw; + return Marshal.GetHRForException(ex); } } - public void Write(byte[] buffer, int count, IntPtr bytesWritten) + public int Write(byte* pv, uint cb, uint* pcbWritten) { - ThrowHResult(StgEAccessDenied); + if (pcbWritten != null) + *pcbWritten = 0; + return StgEAccessDenied; } - public void Seek(long offset, int origin, IntPtr newPosition) + public int Seek(long dlibMove, uint dwOrigin, ulong* plibNewPosition) { + if (dwOrigin > 2) + return StgEInvalidFunction; + try { _file.CancellationToken.ThrowIfCancellationRequested(); var stream = _stream ?? throw new ObjectDisposedException(nameof(RemoteComReadStream)); - var position = stream.Seek(offset, (SeekOrigin)origin); - if (newPosition != IntPtr.Zero) - Marshal.WriteInt64(newPosition, position); + var position = stream.Seek(dlibMove, (SeekOrigin)dwOrigin); + if (plibNewPosition != null) + *plibNewPosition = (ulong)position; + return SOk; } catch (OperationCanceledException) { _file.NotifyCancelled(); - throw; + return EAbort; } catch (Exception ex) { _file.NotifyFailed(ex); - throw; + return Marshal.GetHRForException(ex); } } - public void SetSize(long value) + public int SetSize(ulong libNewSize) { - ThrowHResult(StgEAccessDenied); + return StgEAccessDenied; } - public void CopyTo(IStream destination, long count, IntPtr bytesRead, IntPtr bytesWritten) + public int CopyTo(INativeStream? destination, ulong cb, ulong* pcbRead, ulong* pcbWritten) { + if (pcbRead != null) + *pcbRead = 0; + if (pcbWritten != null) + *pcbWritten = 0; + if (destination == null) + return StgEInvalidPointer; + var buffer = new byte[64 * 1024]; - long totalRead = 0; - long totalWritten = 0; + ulong totalRead = 0; + ulong totalWritten = 0; try { - while (totalRead < count) + fixed (byte* bufferPtr = buffer) { - _file.CancellationToken.ThrowIfCancellationRequested(); - var toRead = (int)Math.Min(buffer.Length, count - totalRead); - var stream = _stream; - if (stream == null) - break; - - var read = stream.Read(buffer, 0, toRead); - if (read <= 0) - break; - - totalRead += read; - destination.Write(buffer, read, IntPtr.Zero); - totalWritten += read; - var position = stream.CanSeek ? stream.Position : totalRead; - _file.NotifyProgress(position); + while (totalRead < cb) + { + _file.CancellationToken.ThrowIfCancellationRequested(); + var toRead = (int)Math.Min((ulong)buffer.Length, cb - totalRead); + var stream = _stream; + if (stream == null) + break; + + var read = stream.Read(buffer, 0, toRead); + if (read <= 0) + break; + + totalRead += (ulong)read; + uint written = 0; + var writeHr = destination.Write(bufferPtr, (uint)read, &written); + if (writeHr < 0) + Marshal.ThrowExceptionForHR(writeHr); + + totalWritten += written; + var position = stream.CanSeek ? stream.Position : (long)totalRead; + _file.NotifyProgress(position); + } } LogCompletion(); @@ -627,53 +780,59 @@ public void CopyTo(IStream destination, long count, IntPtr bytesRead, IntPtr byt catch (OperationCanceledException) { _file.NotifyCancelled(); - throw; + return EAbort; } catch (Exception ex) { _file.NotifyFailed(ex); - throw; + return Marshal.GetHRForException(ex); } - if (bytesRead != IntPtr.Zero) - Marshal.WriteInt64(bytesRead, totalRead); - if (bytesWritten != IntPtr.Zero) - Marshal.WriteInt64(bytesWritten, totalWritten); + if (pcbRead != null) + *pcbRead = totalRead; + if (pcbWritten != null) + *pcbWritten = totalWritten; + return SOk; } - public void Commit(int flags) + public int Commit(uint grfCommitFlags) { + return SOk; } - public void Revert() + public int Revert() { - ThrowHResult(StgEReverted); + return StgEReverted; } - public void LockRegion(long offset, long count, int lockType) + public int LockRegion(ulong libOffset, ulong cb, uint dwLockType) { - ThrowHResult(StgEInvalidFunction); + return StgEInvalidFunction; } - public void UnlockRegion(long offset, long count, int lockType) + public int UnlockRegion(ulong libOffset, ulong cb, uint dwLockType) { - ThrowHResult(StgEInvalidFunction); + return StgEInvalidFunction; } - public void Stat(out STATSTG stat, int flags) + public int Stat(NativeStatStg* stat, uint grfStatFlag) { - stat = new STATSTG + if (stat == null) + return StgEInvalidPointer; + + *stat = new NativeStatStg { type = StgTypeStream, - cbSize = _file.Size + cbSize = (ulong)Math.Max(0, _file.Size) }; + return SOk; } - public void Clone(out IStream clone) + public int Clone(out INativeStream? clone) { - clone = null!; - ThrowHResult(StgENotImplemented); + clone = null; + return StgENotImplemented; } public void DisposeInBackground() @@ -702,33 +861,44 @@ private void LogCompletion() } } - private sealed class FormatEtcEnumerator : IEnumFORMATETC + [GeneratedComClass] + private sealed unsafe partial class FormatEtcEnumerator : INativeEnumFormatEtc { - private readonly FORMATETC[] _formats; + private readonly NativeFormatEtc[] _formats; private int _index; - public FormatEtcEnumerator(FORMATETC[] formats) + public FormatEtcEnumerator(NativeFormatEtc[] formats) { _formats = formats; } - public int Next(int count, FORMATETC[] formats, int[]? fetched) + public int Next(uint celt, NativeFormatEtc* rgelt, uint* pceltFetched) { - var copied = 0; - while (copied < count && _index < _formats.Length) + if (pceltFetched != null) + *pceltFetched = 0; + + if (celt == 0) + return SOk; + if (rgelt == null) + return EInvalidArg; + + uint copied = 0; + while (copied < celt && _index < _formats.Length) { - formats[copied++] = _formats[_index++]; + rgelt[copied++] = _formats[_index++]; } - if (fetched is { Length: > 0 }) - fetched[0] = copied; + if (pceltFetched != null) + *pceltFetched = copied; - return copied == count ? SOk : SFalse; + return copied == celt ? SOk : SFalse; } - public int Skip(int count) + public int Skip(uint celt) { - _index = Math.Min(_index + count, _formats.Length); + var remaining = (uint)Math.Max(0, _formats.Length - _index); + var step = (int)Math.Min(celt, remaining); + _index += step; return _index < _formats.Length ? SOk : SFalse; } @@ -738,46 +908,86 @@ public int Reset() return SOk; } - public void Clone(out IEnumFORMATETC newEnum) + public int Clone(out INativeEnumFormatEtc? newEnum) { newEnum = new FormatEtcEnumerator(_formats) { _index = _index }; + return SOk; } } + [StructLayout(LayoutKind.Sequential)] + internal struct NativeFileTime + { + public int dwLowDateTime; + public int dwHighDateTime; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct NativeFormatEtc + { + public short cfFormat; + public IntPtr ptd; + public uint dwAspect; + public int lindex; + public uint tymed; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct NativeStgMedium + { + public uint tymed; + public IntPtr unionmember; + public IntPtr pUnkForRelease; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct NativeStatStg + { + public IntPtr pwcsName; + public uint type; + public ulong cbSize; + public NativeFileTime mtime; + public NativeFileTime ctime; + public NativeFileTime atime; + public uint grfMode; + public uint grfLocksSupported; + public Guid clsid; + public uint grfStateBits; + public uint reserved; + } + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - private struct FileDescriptor + internal unsafe struct NativeFileDescriptor { public FileDescriptorFlags dwFlags; public Guid clsid; public SizeL sizel; public PointL pointl; public uint dwFileAttributes; - public FILETIME ftCreationTime; - public FILETIME ftLastAccessTime; - public FILETIME ftLastWriteTime; + public NativeFileTime ftCreationTime; + public NativeFileTime ftLastAccessTime; + public NativeFileTime ftLastWriteTime; public uint nFileSizeHigh; public uint nFileSizeLow; - - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] - public string cFileName; + public fixed char cFileName[260]; } [StructLayout(LayoutKind.Sequential)] - private struct SizeL + internal struct SizeL { public int cx; public int cy; } [StructLayout(LayoutKind.Sequential)] - private struct PointL + internal struct PointL { public int x; public int y; } [Flags] - private enum FileDescriptorFlags : uint + internal enum FileDescriptorFlags : uint { FdAttributes = 0x00000004, FdWriteTime = 0x00000020, @@ -785,22 +995,18 @@ private enum FileDescriptorFlags : uint } private const uint FileAttributeNormal = 0x00000080; - private const int StgTypeStream = 2; - private const int SFalse = 1; + private const uint StgTypeStream = 2; private const int DataSUnableToRender = 0x000401A0; + private const int EAbort = unchecked((int)0x80004004); + private const int EInvalidArg = unchecked((int)0x80070057); private const int OleENotSupported = unchecked((int)0x80040000); private const int OleEAdviseNotSupported = unchecked((int)0x80040003); - private const int DvEFormatEtc = unchecked((int)0x80040064); private const int StgEInvalidFunction = unchecked((int)0x80030001); private const int StgEAccessDenied = unchecked((int)0x80030005); + private const int StgEInvalidPointer = unchecked((int)0x80030009); private const int StgEReverted = unchecked((int)0x80030102); private const int StgENotImplemented = unchecked((int)0x80030201); - private static void ThrowHResult(int hresult) - { - Marshal.ThrowExceptionForHR(hresult); - } - private static void DebugLog(string message) { try diff --git a/ViewModels/AgentPanelViewModel.cs b/ViewModels/AgentPanelViewModel.cs index aa56d87..158e8d8 100644 --- a/ViewModels/AgentPanelViewModel.cs +++ b/ViewModels/AgentPanelViewModel.cs @@ -1,5 +1,6 @@ using System.Collections.ObjectModel; using System.Text.Json; +using System.Text.Json.Nodes; using System.Text.Json.Serialization; using AtomUI.Controls; using AtomUI.Controls.Primitives; @@ -41,8 +42,6 @@ public sealed partial class AgentPanelViewModel : ObservableObject, IDisposable "and open_session to establish a saved SSH connection before attempting terminal " + "operations."; - private static readonly JsonSerializerOptions RuntimeJsonOptions = CxShell.Services.AppJsonOptions.CamelCase; - private readonly IAgentRuntimeClient _runtimeClient; private readonly IAgentRuntimeStatusSource? _runtimeStatusSource; private readonly Func _providerSettings; @@ -721,7 +720,7 @@ private async Task RefreshRunHistoryAsync(long version) { result = await _runtimeClient.SendResultAsync( AgentRuntimeMethodNames.RunList, - new { limit = AgentRunCoordinator.MaximumRetainedRuns }, + new JsonObject { ["limit"] = AgentRunCoordinator.MaximumRetainedRuns }, requestId: $"agent-panel-history-{Guid.NewGuid():N}") .ConfigureAwait(false); } @@ -1357,10 +1356,10 @@ private async Task ToggleRunDetails(AgentPanelRunViewModel? run) { var result = await _runtimeClient.SendResultAsync( AgentRuntimeMethodNames.RunEvents, - new + new JsonObject { - runId = run.RunId, - limit = AgentRunCoordinator.MaximumEventReadLimit + ["runId"] = run.RunId, + ["limit"] = AgentRunCoordinator.MaximumEventReadLimit }, requestId: $"agent-panel-history-details-{Guid.NewGuid():N}") .ConfigureAwait(false); @@ -1439,7 +1438,7 @@ private async Task ContinueRun(AgentPanelRunViewModel? run) { var result = await _runtimeClient.SendResultAsync( AgentRuntimeMethodNames.RunResume, - new { runId = run.RunId }, + new JsonObject { ["runId"] = run.RunId }, requestId: $"agent-panel-resume-{Guid.NewGuid():N}") .ConfigureAwait(false); if (!result.Resumed) @@ -1657,16 +1656,16 @@ private async Task Run() { var result = await _runtimeClient.SendResultAsync( AgentRuntimeMethodNames.Run, - new + new JsonObject { - runId, - sessionId = runSessionId.ToString("D"), - mode = SelectedChatMode.ToString().ToLowerInvariant(), - model = SelectedModel, - reasoningEffort = SelectedReasoningEffort.ToString().ToLowerInvariant(), - permissionMode = SelectedPermissionMode, - messages = requestMessages, - timeoutMs = (int)timeout.TotalMilliseconds + ["runId"] = runId, + ["sessionId"] = runSessionId.ToString("D"), + ["mode"] = SelectedChatMode.ToString().ToLowerInvariant(), + ["model"] = SelectedModel, + ["reasoningEffort"] = SelectedReasoningEffort.ToString().ToLowerInvariant(), + ["permissionMode"] = SelectedPermissionMode, + ["messages"] = JsonSerializer.SerializeToNode(requestMessages, AppCamelCaseJsonContext.Default.ListAgentChatMessage), + ["timeoutMs"] = (int)timeout.TotalMilliseconds }, requestId: $"agent-panel-start-{Guid.NewGuid():N}"); if (!result.Started) @@ -1723,10 +1722,10 @@ private async Task Append() { var result = await _runtimeClient.SendResultAsync( AgentRuntimeMethodNames.RunAppend, - new + new JsonObject { - runId, - messages = new[] { userMessage } + ["runId"] = runId, + ["messages"] = JsonSerializer.SerializeToNode(new[] { userMessage }, AppCamelCaseJsonContext.Default.AgentChatMessageArray) }, requestId: $"agent-panel-append-{Guid.NewGuid():N}"); @@ -1778,7 +1777,7 @@ private async Task FocusRun(AgentPanelRunViewModel? run) { var result = await _runtimeClient.SendResultAsync( AgentRuntimeMethodNames.RunStatus, - new { runId }, + new JsonObject { ["runId"] = runId }, requestId: $"agent-panel-focus-{Guid.NewGuid():N}"); if (!result.Found || result.Run == null || !IsActiveRun(result.Run)) @@ -1832,7 +1831,7 @@ private async Task StopBackgroundRun(AgentPanelRunViewModel? run) { var result = await _runtimeClient.SendResultAsync( AgentRuntimeMethodNames.RunStop, - new { runId }, + new JsonObject { ["runId"] = runId }, requestId: $"agent-panel-background-stop-{Guid.NewGuid():N}"); StatusText = result.Requested ? StoppingText : result.Error ?? ErrorText; } @@ -1862,7 +1861,7 @@ private async Task CancelBackgroundRun(AgentPanelRunViewModel? run) { var result = await _runtimeClient.SendResultAsync( AgentRuntimeMethodNames.Cancel, - new { runId }, + new JsonObject { ["runId"] = runId }, requestId: $"agent-panel-background-cancel-{Guid.NewGuid():N}"); StatusText = result.Cancelled ? CancellingText : result.Error ?? ErrorText; } @@ -1891,7 +1890,7 @@ private async Task Stop() { var result = await _runtimeClient.SendResultAsync( AgentRuntimeMethodNames.RunStop, - new { runId }, + new JsonObject { ["runId"] = runId }, requestId: $"agent-panel-stop-{Guid.NewGuid():N}"); if (!string.Equals(_activeRunId, runId, StringComparison.Ordinal)) @@ -1935,7 +1934,7 @@ private async Task Cancel() { var result = await _runtimeClient.SendResultAsync( AgentRuntimeMethodNames.Cancel, - new { runId }, + new JsonObject { ["runId"] = runId }, requestId: $"agent-panel-cancel-{Guid.NewGuid():N}"); if (!string.Equals(_activeRunId, runId, StringComparison.Ordinal)) @@ -1977,7 +1976,7 @@ private void OnRuntimeEvent(AgentRuntimeEventEnvelope envelope) AgentRuntimeStreamEnvelope? stream; try { - stream = payload.Deserialize(RuntimeJsonOptions); + stream = payload.Deserialize(AppCamelCaseJsonContext.Default.AgentRuntimeStreamEnvelope); } catch (JsonException) { @@ -2124,11 +2123,11 @@ private async Task RecoverRunEventsAsync(string runId, long afterSequence) { var result = await _runtimeClient.SendResultAsync( AgentRuntimeMethodNames.RunEvents, - new + new JsonObject { - runId, - afterSequence = cursor, - limit = AgentRunCoordinator.MaximumEventReadLimit + ["runId"] = runId, + ["afterSequence"] = cursor, + ["limit"] = AgentRunCoordinator.MaximumEventReadLimit }, requestId: $"agent-panel-events-{Guid.NewGuid():N}") .ConfigureAwait(false); @@ -2527,7 +2526,7 @@ private async Task ApproveTool(string? toolCallId) { var result = await _runtimeClient.SendResultAsync( AgentRuntimeMethodNames.RunApprove, - new { runId = _activeRunId, toolCallId }, + new JsonObject { ["runId"] = _activeRunId, ["toolCallId"] = toolCallId }, requestId: $"agent-panel-approve-{Guid.NewGuid():N}"); if (_toolMessages.TryGetValue(toolCallId, out var message)) { @@ -2552,7 +2551,7 @@ private async Task DenyTool(string? toolCallId) { var result = await _runtimeClient.SendResultAsync( AgentRuntimeMethodNames.RunDeny, - new { runId = _activeRunId, toolCallId }, + new JsonObject { ["runId"] = _activeRunId, ["toolCallId"] = toolCallId }, requestId: $"agent-panel-deny-{Guid.NewGuid():N}"); if (_toolMessages.TryGetValue(toolCallId, out var message)) { @@ -2584,12 +2583,12 @@ private async Task SubmitCredential(AgentPanelMessageViewModel? message) { var result = await _runtimeClient.SendResultAsync( AgentRuntimeMethodNames.RunCredential, - new + new JsonObject { - runId = _activeRunId, - credentialRequestId = message.CredentialRequestId, - value, - rememberForRun = message.RememberCredential + ["runId"] = _activeRunId, + ["credentialRequestId"] = message.CredentialRequestId, + ["value"] = value, + ["rememberForRun"] = message.RememberCredential }, requestId: $"agent-panel-credential-{Guid.NewGuid():N}"); message.ClearCredentialValue(); @@ -2624,10 +2623,10 @@ private async Task DenyCredential(AgentPanelMessageViewModel? message) { var result = await _runtimeClient.SendResultAsync( AgentRuntimeMethodNames.RunCredentialDeny, - new + new JsonObject { - runId = _activeRunId, - credentialRequestId = message.CredentialRequestId + ["runId"] = _activeRunId, + ["credentialRequestId"] = message.CredentialRequestId }, requestId: $"agent-panel-credential-deny-{Guid.NewGuid():N}"); message.ClearCredentialValue(); @@ -3245,7 +3244,7 @@ public void Dispose() { _ = _runtimeClient.SendAsync( AgentRuntimeMethodNames.Cancel, - new { runId = _activeRunId }, + new JsonObject { ["runId"] = _activeRunId }, requestId: $"agent-panel-dispose-{Guid.NewGuid():N}"); } _activeRunId = null; diff --git a/ViewModels/MainWindowViewModel.cs b/ViewModels/MainWindowViewModel.cs index 92d5e04..4fa3e8f 100644 --- a/ViewModels/MainWindowViewModel.cs +++ b/ViewModels/MainWindowViewModel.cs @@ -2588,7 +2588,17 @@ public async Task ConnectSession(SessionInfo session, string? passwordOverride, } } - private async Task ConnectRdpSession(SessionInfo session, string? passwordOverride) + public Task OpenRdpInWorkspaceWindowAsync(SessionInfo session) => + ConnectRdpSession(session, null, openInWorkspace: true, openInDetached: false); + + public Task OpenRdpInDetachedWindowAsync(SessionInfo session) => + ConnectRdpSession(session, null, openInWorkspace: false, openInDetached: true); + + private async Task ConnectRdpSession( + SessionInfo session, + string? passwordOverride, + bool? openInWorkspace = null, + bool openInDetached = false) { var password = string.IsNullOrEmpty(passwordOverride) ? GetSavedPassword(session) @@ -2603,6 +2613,19 @@ private async Task ConnectRdpSession(SessionInfo session, string? passwordOverri var tab = new TerminalTabViewModel(session, rdp); RecordAudit(session, ConnectionAuditEventType.ConnectStarted); + var effectiveWindowMode = session.ResolveEffectiveRdpWindowMode(); + if (openInDetached || (openInWorkspace == null && string.Equals(effectiveWindowMode, "Standalone", StringComparison.OrdinalIgnoreCase))) + { + Views.DetachedTabWindow.ShowFor(tab); + return; + } + + if (openInWorkspace ?? string.Equals(effectiveWindowMode, "MultiTab", StringComparison.OrdinalIgnoreCase)) + { + Views.RdpWorkspaceWindow.OpenTab(tab); + return; + } + tab.CloseRequested += CloseTab; tab.PropertyChanged += OnTerminalTabPropertyChanged; AddTabToActiveGroup(tab); diff --git a/ViewModels/SessionEditViewModel.cs b/ViewModels/SessionEditViewModel.cs index 1684f2d..580b89e 100644 --- a/ViewModels/SessionEditViewModel.cs +++ b/ViewModels/SessionEditViewModel.cs @@ -331,6 +331,8 @@ public readonly record struct AppearanceColorPalette( [ObservableProperty] private string _rdpFrameStrategy = "Auto"; [ObservableProperty] private string _rdpColorQuality = "32"; [ObservableProperty] private string _rdpSecurityMode = "Auto"; + [ObservableProperty] private string _rdpWindowMode = "Default"; + [ObservableProperty] private bool _rdpOpenInStandaloneWindow; [ObservableProperty] private bool _rdpApplyKeyCombinations = true; [ObservableProperty] private bool _rdpSyncLockKeys = true; [ObservableProperty] private bool _rdpEnableClipboardLock = true; @@ -1048,6 +1050,12 @@ public bool IsNumericKeypadModeForceNormal new SelectOption { Header = "TLS", Content = "TLS" }, new SelectOption { Header = "Standard RDP", Content = "RDP" } ]; + public ObservableCollection RdpWindowModeOptions { get; } = + [ + new SelectOption { Header = LocalizationService.Shared.Text("SessionEdit.RdpWindowMode.Default"), Content = "Default" }, + new SelectOption { Header = LocalizationService.Shared.Text("SessionEdit.RdpWindowMode.MultiTab"), Content = "MultiTab" }, + new SelectOption { Header = LocalizationService.Shared.Text("SessionEdit.RdpWindowMode.Standalone"), Content = "Standalone" } + ]; public ObservableCollection RdpAudioModeOptions { get; } = [ new SelectOption { Header = "Play on this computer", Content = "PlayLocal" }, @@ -1547,6 +1555,8 @@ public SessionEditViewModel(SessionInfo session) RdpFrameStrategy = RdpFramePresentationModes.Normalize(session.RdpFrameStrategy); RdpColorQuality = string.IsNullOrWhiteSpace(session.RdpColorQuality) ? "32" : session.RdpColorQuality; RdpSecurityMode = string.IsNullOrWhiteSpace(session.RdpSecurityMode) ? "Auto" : session.RdpSecurityMode; + RdpWindowMode = session.ResolveEffectiveRdpWindowMode(); + RdpOpenInStandaloneWindow = session.RdpOpenInStandaloneWindow; RdpApplyKeyCombinations = session.RdpApplyKeyCombinations; RdpSyncLockKeys = session.RdpSyncLockKeys; RdpEnableClipboardLock = session.RdpEnableClipboardLock; @@ -1861,6 +1871,8 @@ private void Save() session.RdpFrameStrategy = RdpFramePresentationModes.Normalize(RdpFrameStrategy); session.RdpColorQuality = RdpColorQuality; session.RdpSecurityMode = string.IsNullOrWhiteSpace(RdpSecurityMode) ? "Auto" : RdpSecurityMode; + session.RdpWindowMode = string.IsNullOrWhiteSpace(RdpWindowMode) ? "Default" : RdpWindowMode; + session.RdpOpenInStandaloneWindow = string.Equals(session.RdpWindowMode, "MultiTab", StringComparison.OrdinalIgnoreCase); session.RdpApplyKeyCombinations = RdpApplyKeyCombinations; session.RdpSyncLockKeys = RdpSyncLockKeys; session.RdpEnableClipboardLock = RdpEnableClipboardLock; diff --git a/ViewModels/SessionRecordingViewModel.cs b/ViewModels/SessionRecordingViewModel.cs index 25c315f..db4aa41 100644 --- a/ViewModels/SessionRecordingViewModel.cs +++ b/ViewModels/SessionRecordingViewModel.cs @@ -1,3 +1,4 @@ +using System.Buffers; using System.Collections.ObjectModel; using System.Text; using System.Text.Json; @@ -255,22 +256,28 @@ public string BuildAsciicast() return string.Empty; var builder = new StringBuilder(); - builder.AppendLine(JsonSerializer.Serialize(new - { - version = 2, - width = recording.Columns, - height = recording.Rows, - timestamp = recording.StartedAtUtc.ToUnixTimeSeconds(), - title = SelectedRecording?.Label - })); + var header = new AsciicastHeader( + 2, + recording.Columns, + recording.Rows, + recording.StartedAtUtc.ToUnixTimeSeconds(), + SelectedRecording?.Label); + builder.AppendLine(JsonSerializer.Serialize(header, AppCamelCaseJsonContext.Default.AsciicastHeader)); + + var buffer = new ArrayBufferWriter(256); foreach (var chunk in _chunks) { - builder.AppendLine(JsonSerializer.Serialize(new object[] + buffer.Clear(); + using (var writer = new Utf8JsonWriter(buffer)) { - chunk.OffsetMilliseconds / 1000.0, - "o", - Encoding.UTF8.GetString(chunk.Data) - })); + writer.WriteStartArray(); + writer.WriteNumberValue(chunk.OffsetMilliseconds / 1000.0); + writer.WriteStringValue("o"); + writer.WriteStringValue(Encoding.UTF8.GetString(chunk.Data)); + writer.WriteEndArray(); + } + + builder.AppendLine(Encoding.UTF8.GetString(buffer.WrittenSpan)); } return builder.ToString(); diff --git a/ViewModels/SessionTreeViewModel.cs b/ViewModels/SessionTreeViewModel.cs index 5c5a40d..2557401 100644 --- a/ViewModels/SessionTreeViewModel.cs +++ b/ViewModels/SessionTreeViewModel.cs @@ -266,6 +266,8 @@ public static void CopySessionValues(SessionInfo target, SessionInfo source) target.RdpFrameStrategy = source.RdpFrameStrategy; target.RdpColorQuality = source.RdpColorQuality; target.RdpSecurityMode = source.RdpSecurityMode; + target.RdpWindowMode = source.RdpWindowMode; + target.RdpOpenInStandaloneWindow = source.RdpOpenInStandaloneWindow; target.RdpSyncLockKeys = source.RdpSyncLockKeys; target.RdpEnableClipboardLock = source.RdpEnableClipboardLock; target.RdpClipboardEnabled = source.RdpClipboardEnabled; @@ -1261,6 +1263,8 @@ private static SessionInfo CloneSession(SessionInfo source, string name) RdpFrameStrategy = source.RdpFrameStrategy, RdpColorQuality = source.RdpColorQuality, RdpSecurityMode = source.RdpSecurityMode, + RdpWindowMode = source.RdpWindowMode, + RdpOpenInStandaloneWindow = source.RdpOpenInStandaloneWindow, RdpApplyKeyCombinations = source.RdpApplyKeyCombinations, RdpSyncLockKeys = source.RdpSyncLockKeys, RdpEnableClipboardLock = source.RdpEnableClipboardLock, diff --git a/Views/AgentPanelView.axaml b/Views/AgentPanelView.axaml index 6d40437..3e1db19 100644 --- a/Views/AgentPanelView.axaml +++ b/Views/AgentPanelView.axaml @@ -4,6 +4,7 @@ xmlns:antdicons="https://atomui.net/icons/antdesign" xmlns:md="clr-namespace:LiveMarkdown.Avalonia;assembly=LiveMarkdown.Avalonia" xmlns:vm="using:CxShell.ViewModels" + xmlns:views="using:CxShell.Views" x:Class="CxShell.Views.AgentPanelView" x:DataType="vm:AgentPanelViewModel"> @@ -184,7 +185,7 @@ - + @@ -294,7 +295,7 @@ - + - + @@ -356,7 +357,7 @@ Content="{Binding ToolDetailsButtonText}" ButtonType="Text" Padding="5,1" - Command="{Binding $parent[UserControl].DataContext.ToggleToolDetailsCommand, x:CompileBindings=False}" + Command="{Binding $parent[views:AgentPanelView].((vm:AgentPanelViewModel)DataContext).ToggleToolDetailsCommand}" CommandParameter="{Binding}"/> @@ -444,12 +445,12 @@ @@ -492,7 +493,7 @@ Content="{Binding ToolDetailsButtonText}" ButtonType="Text" Padding="5,1" - Command="{Binding $parent[UserControl].DataContext.ToggleToolDetailsCommand, x:CompileBindings=False}" + Command="{Binding $parent[views:AgentPanelView].((vm:AgentPanelViewModel)DataContext).ToggleToolDetailsCommand}" CommandParameter="{Binding}"/> @@ -645,12 +646,12 @@ @@ -776,9 +777,9 @@ HorizontalAlignment="Right" VerticalAlignment="Top" Margin="2" - Command="{Binding $parent[UserControl].DataContext.RemoveAttachmentCommand, x:CompileBindings=False}" + Command="{Binding $parent[views:AgentPanelView].((vm:AgentPanelViewModel)DataContext).RemoveAttachmentCommand}" CommandParameter="{Binding}" - atom:ToolTip.Tip="{Binding $parent[UserControl].DataContext.RemoveAttachmentText, x:CompileBindings=False}"/> + atom:ToolTip.Tip="{Binding $parent[views:AgentPanelView].((vm:AgentPanelViewModel)DataContext).RemoveAttachmentText}"/> @@ -813,7 +814,7 @@ Padding="0" ButtonType="Text" Icon="{antdicons:AntDesignIconProvider Kind=CloseOutlined}" - Command="{Binding $parent[UserControl].DataContext.RemoveAnnotationCommand, x:CompileBindings=False}" + Command="{Binding $parent[views:AgentPanelView].((vm:AgentPanelViewModel)DataContext).RemoveAnnotationCommand}" CommandParameter="{Binding}" atom:ToolTip.Tip="{Binding RemoveText}"/> diff --git a/Views/ConnectionAuditPage.axaml b/Views/ConnectionAuditPage.axaml index 2e64bac..cf25081 100644 --- a/Views/ConnectionAuditPage.axaml +++ b/Views/ConnectionAuditPage.axaml @@ -4,6 +4,7 @@ xmlns:antdicons="https://atomui.net/icons/antdesign" xmlns:vm="using:CxShell.ViewModels" x:Class="CxShell.Views.ConnectionAuditPage" + x:Name="AuditPageRoot" x:DataType="vm:ConnectionAuditViewModel"> -