Files
AI-Studio/app/MindWork AI Studio/Dialogs/AssistantPluginAuditDialog.razor.cs
T

558 lines
23 KiB
C#
Raw Normal View History

2026-04-09 10:01:24 +02:00
using System.Collections;
using System.Collections.Immutable;
using System.Globalization;
using System.Reflection;
using AIStudio.AIOperations;
using AIStudio.AIOperations.PluginAudit;
2026-04-09 10:01:24 +02:00
using AIStudio.Components;
using AIStudio.Provider;
using AIStudio.Settings.DataModel;
using AIStudio.Tools.PluginSystem;
using AIStudio.Tools.PluginSystem.Assistants;
using AIStudio.Tools.PluginSystem.Assistants.DataModel;
using Microsoft.AspNetCore.Components;
namespace AIStudio.Dialogs;
public partial class AssistantPluginAuditDialog : MSGComponentBase
{
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(AssistantPluginAuditDialog).Namespace, nameof(AssistantPluginAuditDialog));
[CascadingParameter]
private IMudDialogInstance MudDialog { get; set; } = null!;
[Inject]
private AssistantPluginAuditService AssistantPluginAuditService { get; init; } = null!;
[Inject]
private IDialogService DialogService { get; init; } = null!;
[Inject]
private AIOperationProviderResolver ProviderResolver { get; init; } = null!;
2026-04-09 10:01:24 +02:00
[Parameter] public Guid PluginId { get; set; }
private PluginAssistants? plugin;
private PluginAssistantAudit? audit;
private string promptPreview = string.Empty;
private string promptFallbackPreview = string.Empty;
private ImmutableDictionary<string, string> luaFiles = ImmutableDictionary.Create<string, string>();
private IReadOnlyCollection<TreeItemData<ITreeItem>> componentTreeItems = [];
private IReadOnlyCollection<TreeItemData<ITreeItem>> fileSystemTreeItems = [];
private CultureInfo currentCultureInfo = CultureInfo.InvariantCulture;
private bool isAuditing;
private PluginAssistantSecurityState securityState = new();
2026-04-09 10:01:24 +02:00
/// <summary>
/// The provider the user picks inside this dialog when nothing is configured for the audit.
/// </summary>
/// <remarks>
/// It lives and dies with this dialog and is never written to the settings: an audit is a one-off
/// job, and the choice made here says nothing about which model the next one should use.
/// </remarks>
private AIStudio.Settings.Provider auditProviderSelection = AIStudio.Settings.Provider.NONE;
/// <summary>
/// The provider an audit would run with without a choice in this dialog, and why others were not chosen.
/// </summary>
private AIOperationProviderChoice ConfiguredChoice => this.ProviderResolver.Preview(PluginAuditOperation.GetProviderSettings(this.SettingsManager), ConfidenceLevel.NONE, AssistantPluginAuditService.GetProviderOptions(this.SettingsManager, null));
2026-04-09 10:01:24 +02:00
/// <summary>
/// The provider this audit runs with: the configured one, or what the user picked here instead.
/// </summary>
/// <remarks>
/// Chosen as the audit service chooses, so that the dialog never names a provider the audit would refuse.
/// </remarks>
private AIStudio.Settings.Provider EffectiveProvider => this.ProviderResolver.Preview(PluginAuditOperation.GetProviderSettings(this.SettingsManager), ConfidenceLevel.NONE, AssistantPluginAuditService.GetProviderOptions(this.SettingsManager, this.auditProviderSelection)).Provider;
/// <summary>
/// Whether this dialog has to offer a provider, because neither the audit nor the app has a usable one.
/// </summary>
private bool NeedsProviderSelection => !this.ConfiguredChoice.HasProvider;
/// <summary>
/// Says why this dialog offers a provider: none is set, or the one set cannot be used.
/// </summary>
private string ProviderSelectionHint => AssistantPluginAuditService.GetRelevantIssue(this.ConfiguredChoice) switch
{
AIOperationProviderIssue.NOT_SET => TA("No model is set for security checks, neither for this AI task nor for the app as a whole. Choose one here to check this plugin. Your choice applies to this check only; you can set a permanent one in the app settings."),
AIOperationProviderIssue.MISSING => TA("The model set for security checks no longer exists. Choose one here to check this plugin. Your choice applies to this check only; you can set a permanent one in the app settings."),
AIOperationProviderIssue.PROHIBITED => TA("Your organization does not allow the model set for security checks. Choose one here to check this plugin. Your choice applies to this check only; you can set a permanent one in the app settings."),
_ => TA("The model set for security checks is not trusted enough for them. Choose one here to check this plugin. Your choice applies to this check only; you can set a permanent one in the app settings."),
};
private string ProviderLabel => this.EffectiveProvider == AIStudio.Settings.Provider.NONE
? T("No model configured")
: $"{this.EffectiveProvider.InstanceName} ({this.EffectiveProvider.UsedLLMProvider.Name})";
2026-04-09 10:01:24 +02:00
private DataAssistantPluginAudit AuditSettings => this.SettingsManager.ConfigurationData.AssistantPluginAudit;
private PluginAuditLevel MinimumLevel => this.SettingsManager.ConfigurationData.AssistantPluginAudit.MinimumLevel;
2026-04-09 10:01:24 +02:00
private string MinimumLevelLabel => this.MinimumLevel.Name;
2026-04-09 10:01:24 +02:00
private bool CanRunAudit => this.plugin is not null && this.EffectiveProvider != AIStudio.Settings.Provider.NONE && !this.isAuditing && !this.securityState.IsEnterpriseApproved;
2026-04-09 10:01:24 +02:00
/// <summary>
/// The audit result this dialog acts on: the one it has, unless that one concluded nothing.
/// </summary>
/// <remarks>
/// UNKNOWN is not a low audit level, it is the absence of a result: the model was unreachable,
/// the key was wrong, no provider was trusted enough. Everything which decides something has to
/// read it as no audit at all -- whether the plugin may be activated, and what this dialog hands
/// back to be stored. Otherwise a check which failed would unlock a plugin nobody has checked,
/// and storing it would replace the last result which did say something, because audits are kept
/// one per plugin. This is the rule PluginAssistantSecurityResolver already applies to the stored
/// audits. What the dialog shows the user still reads the raw result: a failed run is precisely
/// what they need to see.
/// </remarks>
private PluginAssistantAudit? ConclusiveAudit => this.audit is { Level: not PluginAuditLevel.UNKNOWN } ? this.audit : null;
2026-04-09 10:01:24 +02:00
private bool IsAuditBelowMinimum => this.ConclusiveAudit is not null && this.ConclusiveAudit.Level < this.MinimumLevel;
2026-04-09 10:01:24 +02:00
private bool IsActivationBlockedBySettings => this.AuditSettings.RequireAuditBeforeActivation && (this.ConclusiveAudit is null || this.IsAuditBelowMinimum && this.AuditSettings.BlockActivationBelowMinimum);
private bool RequiresActivationConfirmation => this.ConclusiveAudit is not null && this.IsAuditBelowMinimum && !this.IsActivationBlockedBySettings;
2026-04-09 10:01:24 +02:00
2026-07-05 17:48:00 +02:00
private bool CanEnablePlugin => this.plugin is not null && !this.isAuditing && !this.IsActivationBlockedBySettings;
2026-04-09 10:01:24 +02:00
private Color EnableButtonColor => this.RequiresActivationConfirmation ? Color.Warning : Color.Success;
/// <summary>
/// Whether this dialog has produced an audit result, which is why it offers no second run.
/// </summary>
/// <remarks>
/// A run which concluded nothing must not set this. It would leave the user in front of a plugin
/// they cannot check and cannot enable, with closing and reopening the dialog as the only way on
/// -- and a failed run is the one case where trying again is exactly the right thing to do.
/// </remarks>
2026-04-09 10:01:24 +02:00
private bool justAudited;
private const ushort BYTES_PER_KILOBYTE = 1024;
protected override async Task OnInitializedAsync()
{
var activeLanguagePlugin = await this.SettingsManager.GetActiveLanguagePlugin();
this.currentCultureInfo = CommonTools.DeriveActiveCultureOrInvariant(activeLanguagePlugin.IETFTag);
this.plugin = PluginFactory.RunningPlugins.OfType<PluginAssistants>()
.FirstOrDefault(x => x.Id == this.PluginId);
if (this.plugin is not null)
{
this.securityState = PluginAssistantSecurityResolver.Resolve(this.SettingsManager, this.plugin);
2026-04-09 10:01:24 +02:00
this.promptPreview = await this.plugin.BuildAuditPromptPreviewAsync();
this.promptFallbackPreview = this.plugin.BuildAuditPromptFallbackPreview();
this.plugin.CreateAuditComponentSummary();
this.componentTreeItems = this.CreateAuditTreeItems(this.plugin.RootComponent);
this.fileSystemTreeItems = this.CreatePluginFileSystemTreeItems(this.plugin.PluginPath);
this.luaFiles = this.plugin.ReadAllLuaFiles();
}
await base.OnInitializedAsync();
}
private async Task RunAudit()
{
if (this.plugin is null || this.isAuditing)
return;
this.isAuditing = true;
await this.InvokeAsync(this.StateHasChanged);
try
{
//
// The provider picked here is handed over as the fallback: the audit service uses it only
// when nothing is configured for the audit, so an organization-wide provider keeps
// its precedence.
//
this.audit = await this.AssistantPluginAuditService.RunAuditAsync(this.plugin, providerAtHand: this.auditProviderSelection);
this.securityState = PluginAssistantSecurityResolver.Resolve(this.SettingsManager, this.plugin);
2026-04-09 10:01:24 +02:00
}
finally
{
this.isAuditing = false;
this.justAudited = this.ConclusiveAudit is not null;
2026-04-09 10:01:24 +02:00
await this.InvokeAsync(this.StateHasChanged);
}
}
private string? ValidatingProvider(AIStudio.Settings.Provider provider)
{
if (provider.UsedLLMProvider == LLMProviders.NONE)
return TA("Please select a model.");
return null;
}
2026-04-09 10:01:24 +02:00
private void CloseWithoutActivation()
{
if (this.ConclusiveAudit is null)
2026-04-09 10:01:24 +02:00
{
this.MudDialog.Cancel();
return;
}
this.MudDialog.Close(DialogResult.Ok(new AssistantPluginAuditDialogResult(this.ConclusiveAudit, false)));
2026-04-09 10:01:24 +02:00
}
private async Task EnablePlugin()
{
2026-07-05 17:48:00 +02:00
if (this.plugin is null)
2026-04-09 10:01:24 +02:00
return;
if (this.IsActivationBlockedBySettings)
return;
if (this.RequiresActivationConfirmation && !await this.ConfirmActivationBelowMinimumAsync())
return;
this.MudDialog.Close(DialogResult.Ok(new AssistantPluginAuditDialogResult(this.ConclusiveAudit, true)));
2026-04-09 10:01:24 +02:00
}
private async Task<bool> ConfirmActivationBelowMinimumAsync()
{
var dialogParameters = new DialogParameters<ConfirmDialog>
{
{
x => x.Message,
string.Format(
TA("The assistant plugin '{0}' was audited with the level '{1}', which is below the required safety level '{2}'. Your current settings still allow activation, but this may be unsafe. Do you really want to enable this plugin?"),
2026-04-09 10:01:24 +02:00
this.plugin?.Name ?? T("Unknown plugin"),
this.audit?.Level.Name ?? T("Unknown"),
2026-04-09 10:01:24 +02:00
this.MinimumLevelLabel)
},
};
var dialogReference = await this.DialogService.ShowAsync<ConfirmDialog>(T("Potentially Dangerous Plugin"), dialogParameters, DialogOptions.FULLSCREEN);
var dialogResult = await dialogReference.Result;
return dialogResult is not null && !dialogResult.Canceled;
}
private Severity GetAuditResultSeverity() => this.audit?.Level switch
{
PluginAuditLevel.DANGEROUS => Severity.Error,
PluginAuditLevel.CAUTION => Severity.Warning,
PluginAuditLevel.SAFE => Severity.Success,
2026-04-09 10:01:24 +02:00
_ => Severity.Normal,
};
/// <summary>
/// Creates the full audit tree for the assistant component hierarchy.
/// The dialog owns this mapping because it is pure presentation logic for the audit UI.
/// </summary>
private IReadOnlyCollection<TreeItemData<ITreeItem>> CreateAuditTreeItems(IAssistantComponent? rootComponent)
{
if (rootComponent is null)
return [];
return [this.CreateComponentTreeItem(rootComponent, index: 0, depth: 0)];
}
/// <summary>
/// Maps one assistant component into a tree node and recursively appends its value, props and child components.
/// </summary>
private TreeItemData<ITreeItem> CreateComponentTreeItem(IAssistantComponent component, int index, int depth)
{
var children = new List<TreeItemData<ITreeItem>>();
if (component.Props.TryGetValue("Value", out var value))
children.Add(this.CreateValueTreeItem(TB("Value"), value, depth + 1));
if (component.Props.Count > 0)
children.Add(this.CreatePropsTreeItem(component.Props, depth + 1));
children.AddRange(component.Children.Select((child, childIndex) =>
this.CreateComponentTreeItem(child, childIndex, depth + 1)));
return new TreeItemData<ITreeItem>
{
Expanded = depth < 2,
Expandable = children.Count > 0,
Value = new AssistantAuditTreeItem
{
Text = this.GetComponentTreeItemText(component),
Caption = this.GetComponentTreeItemCaption(component, index),
Icon = component.Type.Icon,
2026-04-09 10:01:24 +02:00
Expandable = children.Count > 0,
},
Children = children,
};
}
/// <summary>
/// Groups all props of a component under a single "Props" branch to keep the component nodes compact.
/// </summary>
private TreeItemData<ITreeItem> CreatePropsTreeItem(IReadOnlyDictionary<string, object> props, int depth)
{
var children = props
.OrderBy(prop => prop.Key, StringComparer.Ordinal)
.Select(prop => this.CreateValueTreeItem(prop.Key, prop.Value, depth + 1))
.ToList();
return new TreeItemData<ITreeItem>
{
Expanded = depth < 2,
Expandable = children.Count > 0,
Value = new AssistantAuditTreeItem
{
Text = TB("Properties"),
Caption = string.Format(TB("Count: {0}"), props.Count),
Icon = AppIcons.COMPONENT_PROPERTIES,
2026-04-09 10:01:24 +02:00
Expandable = children.Count > 0,
IsComponent = false,
},
Children = children,
};
}
/// <summary>
/// Converts a scalar or structured prop value into a tree node.
/// Scalars stay on one line, while structured values recursively expose their children.
/// </summary>
private TreeItemData<ITreeItem> CreateValueTreeItem(string label, object? value, int depth)
{
var children = this.CreateValueChildren(value, depth + 1);
return new TreeItemData<ITreeItem>
{
Expanded = depth < 2,
Expandable = children.Count > 0,
Value = new AssistantAuditTreeItem
{
Text = label,
Caption = children.Count == 0 ? this.FormatScalarValue(value) : this.GetStructuredValueCaption(value),
Icon = this.GetValueIcon(value),
Expandable = children.Count > 0,
IsComponent = false,
},
Children = children,
};
}
/// <summary>
/// Recursively expands structured values for the tree.
/// Lists, dictionaries and known DTO-style assistant values become nested tree branches.
/// </summary>
private List<TreeItemData<ITreeItem>> CreateValueChildren(object? value, int depth)
{
if (value is null || IsScalarValue(value))
return [];
if (value is IDictionary dictionary)
return this.CreateDictionaryChildren(dictionary, depth);
if (value is IEnumerable enumerable and not string)
return this.CreateEnumerableChildren(enumerable, depth);
return this.CreateObjectChildren(value, depth);
}
private List<TreeItemData<ITreeItem>> CreateDictionaryChildren(IDictionary dictionary, int depth)
{
var children = new List<TreeItemData<ITreeItem>>();
foreach (DictionaryEntry entry in dictionary)
{
var keyText = entry.Key.ToString() ?? TB("Unknown key");
children.Add(this.CreateValueTreeItem(keyText, entry.Value, depth));
}
return children;
}
/// <summary>
/// Creates a tree for the plugin directory so the audit can show unexpected folders and files, while excluding irrelevant dependency folders.
/// </summary>
private IReadOnlyCollection<TreeItemData<ITreeItem>> CreatePluginFileSystemTreeItems(string pluginPath)
{
if (string.IsNullOrWhiteSpace(pluginPath) || !Directory.Exists(pluginPath))
return [];
return [this.CreateDirectoryTreeItem(pluginPath, pluginPath, depth: 0)];
}
private TreeItemData<ITreeItem> CreateDirectoryTreeItem(string directoryPath, string rootPath, int depth)
{
var childDirectories = Directory.EnumerateDirectories(directoryPath)
.OrderBy(path => path, StringComparer.Ordinal)
.Select(path => this.CreateDirectoryTreeItem(path, rootPath, depth + 1))
.ToList();
var childFiles = Directory.EnumerateFiles(directoryPath)
.OrderBy(path => path, StringComparer.Ordinal)
.Select(path => this.CreateFileTreeItem(path, depth + 1))
.ToList();
var children = new List<TreeItemData<ITreeItem>>(childDirectories.Count + childFiles.Count);
children.AddRange(childDirectories);
children.AddRange(childFiles);
var relativePath = Path.GetRelativePath(rootPath, directoryPath);
var displayName = depth == 0
? Path.GetFileName(directoryPath)
: relativePath.Split(Path.DirectorySeparatorChar).Last();
return new TreeItemData<ITreeItem>
{
Expanded = depth < 2,
Expandable = children.Count > 0,
Value = new AssistantAuditTreeItem
{
Text = string.IsNullOrWhiteSpace(displayName) ? directoryPath : displayName,
Caption = depth == 0 ? TB("Plugin root") : string.Format(TB("Items: {0}"), children.Count),
Icon = children.Count > 0 ? AppIcons.FOLDERS : AppIcons.FOLDER,
2026-04-09 10:01:24 +02:00
Expandable = children.Count > 0,
IsComponent = false,
},
Children = children,
};
}
private TreeItemData<ITreeItem> CreateFileTreeItem(string filePath, int depth) => new()
{
Expanded = depth < 2,
Expandable = false,
Value = new AssistantAuditTreeItem
{
Text = Path.GetFileName(filePath),
Caption = string.Empty,
Icon = GetFileIcon(filePath),
Expandable = false,
IsComponent = false,
},
};
private static string GetFileIcon(string filePath)
{
var extension = Path.GetExtension(filePath);
return extension.ToLowerInvariant() switch
{
".lua" => AppIcons.CODE,
".md" => AppIcons.DOCUMENT,
".json" => AppIcons.DATA_OBJECT,
".png" or ".jpg" or ".jpeg" or ".svg" or ".webp" => AppIcons.IMAGE,
_ => AppIcons.FILE,
2026-04-09 10:01:24 +02:00
};
}
private List<TreeItemData<ITreeItem>> CreateEnumerableChildren(IEnumerable enumerable, int depth)
{
var children = new List<TreeItemData<ITreeItem>>();
var index = 0;
foreach (var item in enumerable)
{
children.Add(this.CreateValueTreeItem($"[{index}]", item, depth));
index++;
}
return children;
}
/// <summary>
/// Falls back to public instance properties for simple DTO-style values such as dropdown items.
/// Getter failures are treated defensively, so the audit dialog never crashes because of a problematic property.
/// </summary>
private List<TreeItemData<ITreeItem>> CreateObjectChildren(object value, int depth)
{
var children = new List<TreeItemData<ITreeItem>>();
foreach (var property in value.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
if (!property.CanRead || property.GetIndexParameters().Length != 0)
continue;
object? propertyValue;
try
{
propertyValue = property.GetValue(value);
}
catch (Exception)
{
propertyValue = TB("Unavailable");
}
children.Add(this.CreateValueTreeItem(property.Name, propertyValue, depth));
}
return children;
}
private string GetComponentTreeItemText(IAssistantComponent component)
{
var type = component.Type.DisplayName;
2026-04-09 10:01:24 +02:00
if (component is INamedAssistantComponent named && !string.IsNullOrWhiteSpace(named.Name))
return $"{type}: {named.Name}";
return type;
}
private string GetComponentTreeItemCaption(IAssistantComponent component, int index)
{
var details = new List<string> { $"#{index + 1}" };
if (component is IStatefulAssistantComponent stateful)
details.Add(string.IsNullOrWhiteSpace(stateful.UserPrompt) ? TB("Prompt: empty") : TB("Prompt: set"));
if (component.Children.Count > 0)
details.Add(string.Format(TB("Children: {0}"), component.Children.Count));
return string.Join(" | ", details);
}
private static bool IsScalarValue(object value)
{
return value is string or bool or char or Enum
or byte or sbyte or short or ushort or int or uint or long or ulong
or float or double or decimal
or DateTime or DateTimeOffset or TimeSpan or Guid;
}
private string FormatScalarValue(object? value) => value switch
{
null => TB("null"),
string stringValue when string.IsNullOrWhiteSpace(stringValue) => TB("empty"),
string stringValue => stringValue,
bool boolValue => boolValue ? "true" : "false",
_ => Convert.ToString(value, CultureInfo.InvariantCulture) ?? string.Empty,
};
private string GetStructuredValueCaption(object? value) => value switch
{
null => TB("null"),
IDictionary dictionary => string.Format(TB("Entries: {0}"), dictionary.Count),
IEnumerable enumerable when value is not string => string.Format(TB("Items: {0}"),
enumerable.Cast<object?>().Count()),
_ => value.GetType().Name,
};
private string GetValueIcon(object? value) => value switch
{
null => AppIcons.VALUE_NULL,
bool => AppIcons.SWITCH,
string => AppIcons.VALUE_TEXT,
int => AppIcons.NUMBER,
Enum => AppIcons.ENUM_VALUE,
IDictionary => AppIcons.DATA_OBJECT,
IEnumerable when value is not string => AppIcons.VALUE_LIST,
_ => AppIcons.DATA_VALUE,
2026-04-09 10:01:24 +02:00
};
private string FormatFileTimestamp(DateTime timestamp) => CommonTools.FormatTimestampToGeneral(timestamp, this.currentCultureInfo);
private string FormatFileSize(long bytes)
{
if (bytes < BYTES_PER_KILOBYTE)
return string.Format(this.currentCultureInfo, TB("{0} B"), bytes);
var kilobyte = bytes / (double)BYTES_PER_KILOBYTE;
if (kilobyte < BYTES_PER_KILOBYTE)
return string.Format(this.currentCultureInfo, TB("{0:0.##} KB"), kilobyte);
var megabyte = kilobyte / BYTES_PER_KILOBYTE;
if (megabyte < BYTES_PER_KILOBYTE)
return string.Format(this.currentCultureInfo, TB("{0:0.##} MB"), megabyte);
var gigabyte = megabyte / BYTES_PER_KILOBYTE;
return string.Format(this.currentCultureInfo, TB("{0:0.##} GB"), gigabyte);
}
}