Merge branch 'main' into feature/token-count-from-usage

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-09-23 17:18:06 +02:00
commit ae10bb4809
69 files changed
+4129 -336

No files matched your search

@@ -1,6 +1,7 @@
using System.Globalization;
using AIStudio.Dialogs;
using AIStudio.Tools.PluginSystem.Assistants;
using AIStudio.Tools.ToolCallingSystem;
using Microsoft.AspNetCore.Components;
using DialogOptions = AIStudio.Dialogs.DialogOptions;
@@ -30,7 +31,9 @@ public partial class AssistantPluginSecurityCard : MSGComponentBase
/// should see that beforehand, which is why the count sits in the header next to the audit
/// level and the tools themselves are named in the details.
/// </remarks>
private IReadOnlyList<string> PluginToolIds => this.Plugin?.AssistantToolIds ?? this.Plugin?.ChatLaunchConfiguration?.ToolIds ?? [];
private IReadOnlyList<string> PluginToolIds => ToolSelectionRules.NormalizeSelection(this.Plugin?.AssistantToolIds ?? this.Plugin?.ChatLaunchConfiguration?.ToolIds ?? [])
.OrderBy(x => x, StringComparer.Ordinal)
.ToList();
private CultureInfo currentCultureInfo = CultureInfo.InvariantCulture;
private bool showSecurityCard;
@@ -21,11 +21,14 @@
Type="@block.ContentType"
Time="@block.Time"
Content="@block.Content"
ExportFileName="@this.ChatThread.Name"
RemoveBlockFunc="@this.RemoveBlock"
IsLastContentBlock="@isLastBlock"
IsSecondToLastBlock="@isSecondLastBlock"
RegenerateFunc="@this.RegenerateBlock"
RegenerateEnabled="@(() => this.IsProviderSelected && this.ChatThread.IsLLMProviderAllowed(this.Provider))"
RollbackFunc="@this.RollbackBlock"
RollbackEnabled="@(() => !this.IsCurrentChatStreaming)"
EditLastBlockFunc="@this.EditLastBlock"
EditLastUserBlockFunc="@this.EditLastUserBlock"/>
}
@@ -92,7 +95,7 @@
@if (this.SettingsManager.ConfigurationData.Workspace.StorageBehavior is WorkspaceStorageBehavior.STORE_CHATS_AUTOMATICALLY)
{
<MudTooltip Text="@T("Delete this chat & start a new one.")" Placement="@TOOLBAR_TOOLTIP_PLACEMENT">
<MudIconButton Icon="@Icons.Material.Filled.Refresh" OnClick="@(() => this.StartNewChat(useSameWorkspace: true, deletePreviousChat: true))" Disabled="@(!this.CanThreadBeSaved || this.IsCurrentChatStreaming)"/>
<MudIconButton Icon="@Icons.Material.Filled.DeleteSweep" Color="Color.Error" OnClick="@(() => this.StartNewChat(useSameWorkspace: true, deletePreviousChat: true))" Disabled="@(!this.CanThreadBeSaved || this.IsCurrentChatStreaming)"/>
</MudTooltip>
}
@@ -101,6 +104,10 @@
<MudTooltip Text="@T("Move the chat to a workspace, or to another if it is already in one.")" Placement="@TOOLBAR_TOOLTIP_PLACEMENT">
<MudIconButton Icon="@Icons.Material.Filled.MoveToInbox" Disabled="@(!this.CanThreadBeSaved || this.IsCurrentChatStreaming)" OnClick="@this.MoveChatToWorkspace"/>
</MudTooltip>
<MudTooltip Text="@T("Copy this chat & continue in the copy.")" Placement="@TOOLBAR_TOOLTIP_PLACEMENT">
<MudIconButton Icon="@Icons.Material.Filled.ContentCopy" Disabled="@(!this.CanThreadBeCopied)" OnClick="@this.CopyCurrentChat"/>
</MudTooltip>
}
<AttachDocuments Name="File Attachments" DocumentPaths="@this.ComposerState.FileAttachments" DocumentPathsChanged="@this.ComposerAttachmentsChanged" CatchAllDocuments="true" UseSmallForm="true" ShowMediaStatus="false" Provider="@this.Provider" OwnerChat="@this.ChatThread" EnsureOwnerChatAsync="@this.EnsureMediaImportChatAsync" Disabled="@this.MediaTranscriptionService.IsBusy(this.CurrentMediaImportOwner)"/>
@@ -74,7 +74,7 @@ public partial class ChatComponent : MSGComponentBase
private DataSourceSelection? dataSourceSelectionComponent;
private DataSourceOptions earlyDataSourceOptions = new();
private DataSourceOptions lastAppliedStandardDataSourceOptions = new();
private DataSourceOptions lastAppliedAutomaticDataSourceOptions = new();
private Profile currentProfile = Profile.NO_PROFILE;
private ChatTemplate currentChatTemplate = ChatTemplate.NO_CHAT_TEMPLATE;
private bool hasUnsavedChanges;
@@ -264,9 +264,9 @@ public partial class ChatComponent : MSGComponentBase
this.currentChatTemplate = this.SettingsManager.GetPreselectedChatTemplate(Tools.Components.CHAT);
if (!this.ComposerState.HasUserDraft && !this.ComposerState.HasComposerContent)
this.ComposerState.ApplyTemplate(this.currentChatTemplate);
this.selectedToolIds = ToolSelectionRules.NormalizeSelection(this.SettingsManager.GetDefaultToolIds(Tools.Components.CHAT));
this.lastAppliedStandardDataSourceOptions = this.SettingsManager.ConfigurationData.Chat.PreselectedDataSourceOptions.CreateCopy();
await this.ApplyChatTemplateToolSelectionAsync();
this.lastAppliedAutomaticDataSourceOptions = this.GetAutomaticDataSourceOptions();
var deferredInput = MessageBus.INSTANCE.TakeDeferredMessages<string>(Event.SEND_TO_CHAT_INPUT).LastOrDefault();
if (!string.IsNullOrWhiteSpace(deferredInput))
@@ -354,7 +354,7 @@ public partial class ChatComponent : MSGComponentBase
//
// No, the user did not send an assistant result to the chat.
//
this.ApplyStandardDataSourceOptions();
this.ApplyAutomaticDataSourceOptions();
}
//
@@ -660,7 +660,9 @@ public partial class ChatComponent : MSGComponentBase
}
private bool CanThreadBeSaved => this.ChatThread is not null && this.ChatThread.Blocks.Any(b => !b.HideFromUser);
private bool CanThreadBeCopied => this.CanThreadBeSaved && !this.IsCurrentChatStreaming && !this.MediaTranscriptionService.IsBusy(this.CurrentMediaImportOwner);
private string TooltipAddChatToWorkspace => string.Format(T("Start new chat in workspace '{0}'"), this.currentWorkspaceName);
private string UserInputStyle => this.SettingsManager.ConfigurationData.Confidence.ShowProviderConfidence ? this.Provider.UsedLLMProvider.GetConfidence(this.SettingsManager).SetColorStyle(this.SettingsManager) : string.Empty;
@@ -705,35 +707,75 @@ public partial class ChatComponent : MSGComponentBase
}
}
private void ApplyStandardDataSourceOptions()
/// <summary>
/// Picks the tools a chat starts with: those of its chat template, or the chat defaults.
/// </summary>
/// <remarks>
/// A preselection, not a limit — the user changes it in the chat as usual. A template without a
/// tool selection says nothing about tools and therefore leaves the chat default in place,
/// which is a different statement from a template that selects no tool at all.
/// </remarks>
private async Task ApplyChatTemplateToolSelectionAsync()
{
var chatDefaultOptions = this.SettingsManager.ConfigurationData.Chat.PreselectedDataSourceOptions.CreateCopy();
this.lastAppliedStandardDataSourceOptions = chatDefaultOptions.CreateCopy();
this.earlyDataSourceOptions = chatDefaultOptions;
if(this.ChatThread is not null)
this.ChatThread.DataSourceOptions = chatDefaultOptions;
this.dataSourceSelectionComponent?.ChangeOptionWithoutSaving(chatDefaultOptions);
}
private async Task ApplyUpdatedStandardDataSourceOptionsAfterConfigurationChange()
{
var updatedStandardOptions = this.SettingsManager.ConfigurationData.Chat.PreselectedDataSourceOptions.CreateCopy();
var previousStandardOptions = this.lastAppliedStandardDataSourceOptions;
this.lastAppliedStandardDataSourceOptions = updatedStandardOptions.CreateCopy();
if (this.ChatThread is null)
if (this.currentChatTemplate.ToolIds is not { } templateToolIds)
{
this.earlyDataSourceOptions = updatedStandardOptions;
this.dataSourceSelectionComponent?.ChangeOptionWithoutSaving(updatedStandardOptions);
this.selectedToolIds = ToolSelectionRules.NormalizeSelection(this.SettingsManager.GetDefaultToolIds(Tools.Components.CHAT));
return;
}
if (!DataSourceOptionsAreEqual(this.ChatThread.DataSourceOptions, previousStandardOptions))
//
// Only the tools the user could have switched on themselves: a template may name one whose
// settings are incomplete — an unconfigured web search, say — and starting with it enabled
// would show a state the user cannot produce by hand and cannot fix from the chat.
//
this.selectedToolIds = await this.ToolRegistry.FilterSelectableToolIdsAsync(Tools.Components.CHAT, templateToolIds);
}
/// <summary>
/// The data source options a chat starts with: those of its chat template, or the chat defaults.
/// </summary>
/// <remarks>
/// As with the tools, a template which carries no options says nothing and leaves the chat
/// defaults in place. A template which carries them answers more than which sources to search:
/// whether data sources are used at all, and whether an agent picks them for each message.
/// </remarks>
private DataSourceOptions GetAutomaticDataSourceOptions() =>
this.currentChatTemplate.DataSourceOptions?.CreateCopy() ?? this.SettingsManager.ConfigurationData.Chat.PreselectedDataSourceOptions.CreateCopy();
private void ApplyAutomaticDataSourceOptions()
{
var automaticOptions = this.GetAutomaticDataSourceOptions();
this.lastAppliedAutomaticDataSourceOptions = automaticOptions.CreateCopy();
this.earlyDataSourceOptions = automaticOptions;
if(this.ChatThread is not null)
this.ChatThread.DataSourceOptions = automaticOptions;
this.dataSourceSelectionComponent?.ChangeOptionWithoutSaving(automaticOptions);
}
private async Task ApplyUpdatedAutomaticDataSourceOptionsAfterConfigurationChange()
{
//
// What a chat would start with right now. The chat template is asked first, so that editing
// the template of the current chat reaches it — a change of the chat defaults it does not
// use would say nothing about it.
//
var updatedAutomaticOptions = this.GetAutomaticDataSourceOptions();
var previousAutomaticOptions = this.lastAppliedAutomaticDataSourceOptions;
this.lastAppliedAutomaticDataSourceOptions = updatedAutomaticOptions.CreateCopy();
if (this.ChatThread is null)
{
this.earlyDataSourceOptions = updatedAutomaticOptions;
this.dataSourceSelectionComponent?.ChangeOptionWithoutSaving(updatedAutomaticOptions);
return;
}
if (!DataSourceOptionsAreEqual(this.ChatThread.DataSourceOptions, previousAutomaticOptions))
return;
await this.SetCurrentDataSourceOptions(updatedStandardOptions);
this.dataSourceSelectionComponent?.ChangeOptionWithoutSaving(updatedStandardOptions, this.ChatThread.AISelectedDataSources);
await this.SetCurrentDataSourceOptions(updatedAutomaticOptions);
this.dataSourceSelectionComponent?.ChangeOptionWithoutSaving(updatedAutomaticOptions, this.ChatThread.AISelectedDataSources);
await this.ChatThreadChanged.InvokeAsync(this.ChatThread);
}
@@ -793,7 +835,18 @@ public partial class ChatComponent : MSGComponentBase
this.ComposerState.ReplaceFileAttachments(this.currentChatTemplate.FileAttachments);
if (this.ChatThread is not null)
{
// Starting the new chat is what hands the selection of the new template to it:
await this.StartNewChat(true);
return;
}
//
// Without a thread there is nothing to start anew, so the selection of the new template is
// applied right here. It travels into the thread which the first message creates.
//
await this.ApplyChatTemplateToolSelectionAsync();
this.ApplyAutomaticDataSourceOptions();
}
private void RefreshCurrentProfileAndChatTemplate()
@@ -830,7 +883,7 @@ public partial class ChatComponent : MSGComponentBase
if (!this.ComposerState.HasUserDraft && previousChatTemplate != this.currentChatTemplate)
this.ComposerState.ApplyTemplate(this.currentChatTemplate);
await this.ApplyUpdatedStandardDataSourceOptionsAfterConfigurationChange();
await this.ApplyUpdatedAutomaticDataSourceOptionsAfterConfigurationChange();
}
private IReadOnlyList<DataSourceAgentSelected> GetAgentSelectedDataSources()
@@ -1164,10 +1217,10 @@ public partial class ChatComponent : MSGComponentBase
{
var dialogParameters = new DialogParameters<ConfirmDialog>
{
{ x => x.Message, "Are you sure you want to start a new chat? All unsaved changes will be lost." },
{ x => x.Message, T("Are you sure you want to start a new chat? All unsaved changes will be lost.") },
};
var dialogReference = await this.DialogService.ShowAsync<ConfirmDialog>("Delete Chat", dialogParameters, DialogOptions.FULLSCREEN);
var dialogReference = await this.DialogService.ShowAsync<ConfirmDialog>(T("Start New Chat"), dialogParameters, DialogOptions.FULLSCREEN);
var dialogResult = await dialogReference.Result;
if (dialogResult is null || dialogResult.Canceled)
return;
@@ -1178,16 +1231,27 @@ public partial class ChatComponent : MSGComponentBase
//
if (this.ChatThread is not null && deletePreviousChat)
{
string chatPath;
if (this.ChatThread.WorkspaceId == Guid.Empty)
chatPath = Path.Join(SettingsManager.DataDirectory, "tempChats", this.ChatThread.ChatId.ToString());
//
// A deleted chat cannot be restored, and the check above never covers this path: it
// exists only while chats are stored automatically, while that check runs only while
// they are stored manually. So we let the deletion itself ask, with the question the
// chat list asks. When it reports the chat is still there, the user declined or the
// chat is busy, and we stop before the reset below takes it out of view:
//
bool chatIsGone;
if (this.Workspaces is null)
chatIsGone = await WorkspaceBehaviour.DeleteChatAsync(this.DialogService, this.ChatThread.WorkspaceId, this.ChatThread.ChatId);
else
chatPath = Path.Join(SettingsManager.DataDirectory, "workspaces", this.ChatThread.WorkspaceId.ToString(), this.ChatThread.ChatId.ToString());
{
var chatPath = this.ChatThread.WorkspaceId == Guid.Empty
? Path.Join(SettingsManager.DataDirectory, "tempChats", this.ChatThread.ChatId.ToString())
: Path.Join(SettingsManager.DataDirectory, "workspaces", this.ChatThread.WorkspaceId.ToString(), this.ChatThread.ChatId.ToString());
if(this.Workspaces is null)
await WorkspaceBehaviour.DeleteChatAsync(this.DialogService, this.ChatThread.WorkspaceId, this.ChatThread.ChatId, askForConfirmation: false);
else
await this.Workspaces.DeleteChatAsync(chatPath, askForConfirmation: false, unloadChat: true);
chatIsGone = await this.Workspaces.DeleteChatAsync(chatPath, unloadChat: true);
}
if (!chatIsGone)
return;
}
//
@@ -1195,7 +1259,6 @@ public partial class ChatComponent : MSGComponentBase
//
this.hasUnsavedChanges = false;
this.ComposerState.Clear();
this.selectedToolIds = ToolSelectionRules.NormalizeSelection(this.SettingsManager.GetDefaultToolIds(Tools.Components.CHAT));
this.RefreshCurrentProfileAndChatTemplate();
//
@@ -1244,9 +1307,11 @@ public partial class ChatComponent : MSGComponentBase
this.ComposerState.ApplyTemplate(this.currentChatTemplate);
// Now, we have to reset the data source options as well:
this.ApplyStandardDataSourceOptions();
// Now, the chat starts with what its template asks for, and with the chat defaults wherever
// that template says nothing:
await this.ApplyChatTemplateToolSelectionAsync();
this.ApplyAutomaticDataSourceOptions();
// Notify the parent component about the change:
await this.SyncForegroundChatAsync();
this.MarkCurrentChatAsLoadedParameter();
@@ -1265,7 +1330,7 @@ public partial class ChatComponent : MSGComponentBase
{ x => x.Message, T("Are you sure you want to move this chat? All unsaved changes will be lost.") },
};
var confirmationDialogReference = await this.DialogService.ShowAsync<ConfirmDialog>("Unsaved Changes", confirmationDialogParameters, DialogOptions.FULLSCREEN);
var confirmationDialogReference = await this.DialogService.ShowAsync<ConfirmDialog>(T("Unsaved Changes"), confirmationDialogParameters, DialogOptions.FULLSCREEN);
var confirmationDialogResult = await confirmationDialogReference.Result;
if (confirmationDialogResult is null || confirmationDialogResult.Canceled)
return;
@@ -1292,7 +1357,48 @@ public partial class ChatComponent : MSGComponentBase
await this.SyncWorkspaceHeaderWithChatThreadAsync();
}
/// <summary>
/// Copies the open chat and continues in the copy.
/// </summary>
/// <remarks>
/// Copied is the chat as it stands on the screen, not the state which was stored last. That is
/// why nothing is asked about unsaved changes here, unlike everywhere else a chat is left
/// behind: none of them are lost, they move into the copy, while the original keeps what was
/// stored.<br/><br/>
///
/// The same holds for the message being written. The copy is marked as loaded right away,
/// because the parameter update which follows would otherwise take it for another chat being
/// opened and clear the composer. Only the transcripts attached to that message are exchanged:
/// those of the original live in its directory, and the copy got copies of its own.
/// </remarks>
private async Task CopyCurrentChat()
{
if (this.ChatThread is null || !this.CanThreadBeCopied)
return;
var sourceChat = this.ChatThread;
var copy = this.Workspaces is null
? await WorkspaceBehaviour.CopyChatAsync(this.DialogService, sourceChat)
: await this.Workspaces.CopyChatAsync(sourceChat);
if (copy is null)
return;
var transcriptsOfTheOriginal = sourceChat.PendingMediaTranscripts.Select(transcript => transcript.FilePath).ToHashSet(StringComparer.Ordinal);
this.ComposerState.FileAttachments.RemoveWhere(attachment => transcriptsOfTheOriginal.Contains(attachment.FilePath));
foreach (var transcript in copy.PendingMediaTranscripts)
this.ComposerState.FileAttachments.Add(transcript);
this.ChatThread = copy;
this.hasUnsavedChanges = false;
await this.SyncForegroundChatAsync();
this.MarkCurrentChatAsLoadedParameter();
await this.SyncWorkspaceHeaderWithChatThreadAsync();
await this.ChatThreadChanged.InvokeAsync(this.ChatThread);
}
private async Task LoadedChatChanged(bool notifyParent = true)
{
this.hasUnsavedChanges = false;
@@ -1317,9 +1423,9 @@ public partial class ChatComponent : MSGComponentBase
this.loadedParameterWorkspaceId = Guid.Empty;
this.ClearWorkspaceHeaderState();
await this.SyncForegroundChatAsync();
this.ApplyStandardDataSourceOptions();
this.ApplyAutomaticDataSourceOptions();
}
await this.SelectProviderWhenLoadingChat();
if (this.SettingsManager.ConfigurationData.Chat.ShowLatestMessageAfterLoading)
{
@@ -1352,7 +1458,7 @@ public partial class ChatComponent : MSGComponentBase
this.ChatThread = null;
this.MarkCurrentChatAsLoadedParameter();
await this.SyncForegroundChatAsync();
this.ApplyStandardDataSourceOptions();
this.ApplyAutomaticDataSourceOptions();
await this.ChatThreadChanged.InvokeAsync(this.ChatThread);
}
@@ -1405,6 +1511,24 @@ public partial class ChatComponent : MSGComponentBase
await this.SendMessage(reuseLastUserPrompt: true);
}
private async Task RollbackBlock(IContent aiBlock)
{
if (this.ChatThread is null || this.IsCurrentChatStreaming)
return;
// Which parts of the thread a rollback resets and which it keeps is documented at RollBackTo:
if (!this.ChatThread.RollBackTo(aiBlock))
return;
// The rollback reset the AI-selected data sources, which the data source selection still shows:
this.dataSourceSelectionComponent?.ChangeOptionWithoutSaving(this.ChatThread.DataSourceOptions, this.ChatThread.AISelectedDataSources);
this.hasUnsavedChanges = true;
await this.SaveThread();
this.tokenTracker?.Nudge();
this.StateHasChanged();
await this.inputField.FocusAsync();
}
private Task EditLastUserBlock(IContent block)
{
@@ -179,13 +179,13 @@ else if (this.SelectionMode is DataSourceSelectionMode.CONFIGURATION_MODE)
</MudText>
}
<MudTextSwitch Label="@T("Are data sources enabled?")" Value="@this.areDataSourcesEnabled" LabelOn="@T("Yes, I want to use data sources.")" LabelOff="@T("No, I don't want to use data sources.")" ValueChanged="@this.EnabledChanged" Disabled="@this.IsPreselectedDataSourcesDisabledLocked()"/>
<MudTextSwitch Label="@T("Are data sources enabled?")" Value="@this.areDataSourcesEnabled" LabelOn="@T("Yes, I want to use data sources.")" LabelOff="@T("No, I don't want to use data sources.")" ValueChanged="@this.EnabledChanged" Disabled="@(this.ReadOnly || this.IsPreselectedDataSourcesDisabledLocked())"/>
@if (this.areDataSourcesEnabled)
{
<MudTextSwitch Label="@T("AI-based data source selection")" Value="@this.aiBasedSourceSelection" LabelOn="@T("Yes, let the AI decide which data sources are needed.")" LabelOff="@T("No, I manually decide which data source to use.")" ValueChanged="@this.AutoModeChanged" Disabled="@this.IsPreselectedDataSourcesAutomaticSelectionLocked()"/>
<MudTextSwitch Label="@T("AI-based data validation")" Value="@this.aiBasedValidation" LabelOn="@T("Yes, let the AI validate & filter the retrieved data.")" LabelOff="@T("No, use all data retrieved from the data sources.")" ValueChanged="@this.ValidationModeChanged" Disabled="@this.IsPreselectedDataSourcesAutomaticValidationLocked()"/>
<MudField Label="@T("Available Data Sources")" Variant="Variant.Outlined" Class="mb-3" Disabled="@(this.aiBasedSourceSelection || this.IsPreselectedDataSourceIdsLocked())">
<MudList T="IDataSource" Dense="@true" Class="data-source-rows" SelectionMode="@this.GetListSelectionMode()" @bind-SelectedValues:get="@this.selectedDataSources" @bind-SelectedValues:set="@(x => this.SelectionChanged(x))" ReadOnly="@this.IsPreselectedDataSourceIdsLocked()">
<MudTextSwitch Label="@T("AI-based data source selection")" Value="@this.aiBasedSourceSelection" LabelOn="@T("Yes, let the AI decide which data sources are needed.")" LabelOff="@T("No, I manually decide which data source to use.")" ValueChanged="@this.AutoModeChanged" Disabled="@(this.ReadOnly || this.IsPreselectedDataSourcesAutomaticSelectionLocked())"/>
<MudTextSwitch Label="@T("AI-based data validation")" Value="@this.aiBasedValidation" LabelOn="@T("Yes, let the AI validate & filter the retrieved data.")" LabelOff="@T("No, use all data retrieved from the data sources.")" ValueChanged="@this.ValidationModeChanged" Disabled="@(this.ReadOnly || this.IsPreselectedDataSourcesAutomaticValidationLocked())"/>
<MudField Label="@T("Available Data Sources")" Variant="Variant.Outlined" Class="mb-3" Disabled="@(this.ReadOnly || this.aiBasedSourceSelection || this.IsPreselectedDataSourceIdsLocked())">
<MudList T="IDataSource" Dense="@true" Class="data-source-rows" SelectionMode="@this.GetListSelectionMode()" @bind-SelectedValues:get="@this.selectedDataSources" @bind-SelectedValues:set="@(x => this.SelectionChanged(x))" ReadOnly="@(this.ReadOnly || this.IsPreselectedDataSourceIdsLocked())">
@*
The configuration mode lists what was configured, without filtering it, so no
row here is ever waiting for an index.
@@ -38,7 +38,28 @@ public partial class DataSourceSelection : MSGComponentBase
[Parameter]
public bool AutoSaveAppSettings { get; set; }
/// <summary>
/// Shows the options without letting the user change them.
/// </summary>
/// <remarks>
/// For options somebody else decided on, such as those of a chat template an organization
/// rolled out. Seeing which data such a chat will search is the point; changing it here is not.
/// </remarks>
[Parameter]
public bool ReadOnly { get; set; }
/// <summary>
/// Whether the options edited here are the data source defaults of the chat.
/// </summary>
/// <remarks>
/// Those defaults can be locked by a configuration plugin, and this component reads the locks
/// from the chat settings. Wherever the same options belong to something else — to a chat
/// template, say — the locks of the chat defaults have nothing to say about them.
/// </remarks>
[Parameter]
public bool ConfiguresChatDefaults { get; set; } = true;
[Inject]
private DataSourceService DataSourceService { get; init; } = null!;
@@ -334,6 +355,7 @@ public partial class DataSourceSelection : MSGComponentBase
private bool IsPreselectedDataSourcesDisabledLocked()
{
return this.SelectionMode is DataSourceSelectionMode.CONFIGURATION_MODE
&& this.ConfiguresChatDefaults
&& ManagedConfiguration.TryGet(x => x.Chat, x => x.PreselectedDataSourcesDisabled, out var meta)
&& meta.IsLocked;
}
@@ -341,6 +363,7 @@ public partial class DataSourceSelection : MSGComponentBase
private bool IsPreselectedDataSourcesAutomaticSelectionLocked()
{
return this.SelectionMode is DataSourceSelectionMode.CONFIGURATION_MODE
&& this.ConfiguresChatDefaults
&& ManagedConfiguration.TryGet(x => x.Chat, x => x.PreselectedDataSourcesAutomaticSelection, out var meta)
&& meta.IsLocked;
}
@@ -348,6 +371,7 @@ public partial class DataSourceSelection : MSGComponentBase
private bool IsPreselectedDataSourcesAutomaticValidationLocked()
{
return this.SelectionMode is DataSourceSelectionMode.CONFIGURATION_MODE
&& this.ConfiguresChatDefaults
&& ManagedConfiguration.TryGet(x => x.Chat, x => x.PreselectedDataSourcesAutomaticValidation, out var meta)
&& meta.IsLocked;
}
@@ -355,6 +379,7 @@ public partial class DataSourceSelection : MSGComponentBase
private bool IsPreselectedDataSourceIdsLocked()
{
return this.SelectionMode is DataSourceSelectionMode.CONFIGURATION_MODE
&& this.ConfiguresChatDefaults
&& ManagedConfiguration.TryGet(x => x.Chat, x => x.PreselectedDataSourceIds, out var meta)
&& meta.IsLocked;
}
@@ -51,4 +51,20 @@
}
</MudSelect>
<ToolSelectionField Component="Components.CHAT" SelectedToolIds="@this.ToolIds" SelectedToolIdsChanged="@this.SetToolIds" Label="@T("Tools (Optional)")" Help="@T("These tools are preselected when the chat opens. Users can change the selection in the chat, and every tool has to meet the confidence requirements of the provider in use.")"/>
@* A chat template wins over what is chosen here, so the form says so before somebody picks
something which would never take effect: *@
@if (this.SelectedChatTemplate.DataSourceOptions is not null)
{
<MudText Typo="Typo.body2" Class="mud-text-secondary mb-3">
@T("The chosen chat template brings data sources of its own, and those win over a selection made here. Only a template can also leave the choice of sources to the AI, which is why it decides this on its own.")
</MudText>
}
<ToolSelectionField Component="Components.CHAT" SelectedToolIds="@this.ToolIds" SelectedToolIdsChanged="@this.SetToolIds" Label="@T("Tools (Optional)")" Help="@T("These tools are preselected when the chat opens. Users can change the selection in the chat, and every tool has to meet the confidence requirements of the provider in use.")"/>
@if (this.SelectedChatTemplate.ToolIds is not null)
{
<MudText Typo="Typo.body2" Class="mud-text-secondary">
@T("The chosen chat template brings tools of its own, and those win over a selection made here.")
</MudText>
}
@@ -1,3 +1,5 @@
using AIStudio.Settings;
using Microsoft.AspNetCore.Components;
namespace AIStudio.Components;
@@ -81,6 +83,19 @@ public partial class DirectChatLauncherForm : MSGComponentBase
/// </summary>
private bool OpensTemporaryChat => string.IsNullOrWhiteSpace(this.WorkspaceName);
/// <summary>
/// The chat template the launcher would open its chat with, as far as it is known here.
/// </summary>
/// <remarks>
/// With "use chat default" chosen, this is whichever template the chat options name right now,
/// and that may well be another one by the time somebody opens the launcher. The form therefore
/// only says what such a template brings along instead of disabling the fields below it: a field
/// which locks itself behind the user's back is worse than a sentence explaining the situation.
/// </remarks>
private ChatTemplate SelectedChatTemplate => string.IsNullOrWhiteSpace(this.ChatTemplateId)
? this.SettingsManager.GetPreselectedChatTemplate(Tools.Components.CHAT)
: this.SettingsManager.GetChatTemplateById(this.ChatTemplateId);
private IReadOnlyList<WorkspaceTreeWorkspace> availableWorkspaces = [];
private static readonly Dictionary<string, object?> USER_INPUT_ATTRIBUTES = new();
@@ -44,8 +44,7 @@
@foreach (var item in this.catalog)
{
var isSelected = this.SelectedToolIds.Contains(item.Definition.Id);
var isConfigured = item.ConfigurationState.IsConfigured;
var providerConfidenceHint = this.GetProviderConfidenceHint(item);
var warningText = this.GetWarningText(item);
<div class="tool-selection-row">
<MudStack Row="true" AlignItems="AlignItems.Center" Justify="Justify.SpaceBetween" Spacing="1">
@*
@@ -81,17 +80,13 @@
</MudButton>
<MudIconButton Icon="@Icons.Material.Filled.Settings" Size="Size.Small" OnClick="@(async () => await this.OpenSettings(item.Definition.Id))" />
</MudStack>
@if (!isConfigured)
@if (!string.IsNullOrWhiteSpace(warningText))
{
<MudText Typo="Typo.caption" Color="Color.Warning" Class="ml-2">@(string.IsNullOrWhiteSpace(item.ConfigurationState.Message) ? T("Required settings are missing. Configure this tool before enabling it.") : item.ConfigurationState.Message)</MudText>
}
@if (!item.IsActive)
{
<MudText Typo="Typo.caption" Color="Color.Warning" Class="ml-2">@T("This tool has been disabled by your organization.")</MudText>
}
@if (!string.IsNullOrWhiteSpace(providerConfidenceHint))
{
<MudText Typo="Typo.caption" Color="Color.Warning" Class="ml-2">@providerConfidenceHint</MudText>
@*
A caption renders as an inline span by default, and an inline element
cannot be justified. The div makes it a block of its own.
*@
<MudJustifiedText Typo="Typo.caption" HtmlTag="div" Color="Color.Warning" Class="ml-2">@warningText</MudJustifiedText>
}
</div>
}
@@ -104,4 +99,4 @@
</MudCardActions>
</MudCard>
</MudPopover>
</div>
</div>
@@ -129,6 +129,29 @@ public partial class ToolSelection : MSGComponentBase
this.ProviderConfidence.GetName());
}
/// <summary>
/// Every reason why this tool is out of reach right now, as one text.
/// </summary>
/// <remarks>
/// Several reasons can apply at once, such as a missing setting and a provider without the
/// confidence the tool needs. One justified paragraph reads better than a stack of short lines.
/// </remarks>
private string GetWarningText(ToolCatalogItem item)
{
var warnings = new List<string>(3);
if (!item.ConfigurationState.IsConfigured)
warnings.Add(string.IsNullOrWhiteSpace(item.ConfigurationState.Message) ? T("Required settings are missing. Configure this tool before enabling it.") : item.ConfigurationState.Message);
if (!item.IsActive)
warnings.Add(T("This tool has been disabled by your organization."));
var providerConfidenceHint = this.GetProviderConfidenceHint(item);
if (!string.IsNullOrWhiteSpace(providerConfidenceHint))
warnings.Add(providerConfidenceHint);
return string.Join(' ', warnings);
}
private async Task OpenSettings(string toolId)
{
var parameters = new DialogParameters<ToolSettingsDialog>
@@ -49,6 +49,14 @@ public partial class ToolSelectionField : MSGComponentBase
private List<ConfigurationSelectData<string>> availableTools = [];
protected override void OnParametersSet()
{
// Like ToolSelection, the field shows the tools which will actually run, also when the
// selection is read-only. See ToolSelectionRules.NormalizeSelection:
this.SelectedToolIds = ToolSelectionRules.NormalizeSelection(this.SelectedToolIds);
base.OnParametersSet();
}
protected override async Task OnInitializedAsync()
{
this.availableTools = (await this.ToolRegistry.GetCatalogAsync(this.Component))
@@ -80,4 +88,4 @@ public partial class ToolSelectionField : MSGComponentBase
break;
}
}
}
}
@@ -81,6 +81,10 @@ else
<MudIconButton Icon="@Icons.Material.Filled.MoveToInbox" Size="Size.Medium" Color="Color.Inherit" Disabled="@this.IsChatTreeItemBusy(treeItem)" OnClick="@(() => this.MoveChatAsync(treeItem.Path))"/>
</MudTooltip>
<MudTooltip Text="@T("Copy chat")" Placement="@WORKSPACE_ITEM_TOOLTIP_PLACEMENT">
<MudIconButton Icon="@Icons.Material.Filled.ContentCopy" Size="Size.Medium" Color="Color.Inherit" Disabled="@this.IsChatTreeItemBusy(treeItem)" OnClick="@(() => this.CopyChatFromTreeAsync(treeItem.Path))"/>
</MudTooltip>
<MudTooltip Text="@T("Rename")" Placement="@WORKSPACE_ITEM_TOOLTIP_PLACEMENT">
<MudIconButton Icon="@Icons.Material.Filled.Edit" Size="Size.Medium" Color="Color.Inherit" Disabled="@this.IsChatTreeItemBusy(treeItem)" OnClick="@(() => this.RenameChatAsync(treeItem.Path))"/>
</MudTooltip>
@@ -660,6 +660,24 @@ public partial class Workspaces : MSGComponentBase
await this.LoadTreeItemsAsync(startPrefetch: false);
}
/// <summary>
/// Copies the given chat, after asking the user for the name of the copy, and shows the copy in the tree.
/// </summary>
/// <param name="sourceChat">The chat to copy, as it stands in memory.</param>
/// <returns>The persisted copy. Null when the user canceled the question, in which case nothing was copied.</returns>
/// <remarks>
/// Neither asks about unsaved changes nor opens the copy: which of both a caller needs depends
/// on where the copy was asked for.
/// </remarks>
public async Task<ChatThread?> CopyChatAsync(ChatThread sourceChat)
{
var copy = await WorkspaceBehaviour.CopyChatAsync(this.DialogService, sourceChat);
if (copy is not null)
await this.LoadTreeItemsAsync(startPrefetch: false);
return copy;
}
private async Task<ChatThread?> LoadChatAsync(string? chatPath, bool switchToChat)
{
if (string.IsNullOrWhiteSpace(chatPath))
@@ -704,37 +722,35 @@ public partial class Workspaces : MSGComponentBase
return null;
}
public async Task DeleteChatAsync(string? chatPath, bool askForConfirmation = true, bool unloadChat = true)
/// <summary>Deletes the given chat and updates the tree, asking the user to confirm that beforehand.</summary>
/// <param name="chatPath">Path of the chat to delete.</param>
/// <param name="askForConfirmation">False skips the question. Only for callers who already asked.</param>
/// <param name="unloadChat">Whether to take the chat out of the view when it is the one being shown.</param>
/// <returns>True when the chat is gone, which includes it never having been there. False when it is still there.</returns>
/// <remarks>
/// The question itself comes from the workspace behaviour, so that it is worded in one place only.
/// Callers who do more than deleting have to honor the return value: a chat that is busy is not
/// deleted either, and then nothing about it may be reset.
/// </remarks>
public async Task<bool> DeleteChatAsync(string? chatPath, bool askForConfirmation = true, bool unloadChat = true)
{
var chat = await this.LoadChatAsync(chatPath, false);
// There is nothing left to delete, so the caller may go on:
if (chat is null)
return;
return true;
//
// Deleting a chat while it is being worked on would pull the ground from under that work.
// We check before asking: nobody should confirm something that cannot happen anyway.
//
var mediaOwner = MediaImportOwner.ForChat(chat.ChatId);
if (this.AIJobService.IsChatGenerationActive(chat.ChatId) || this.MediaTranscriptionService.IsBusy(mediaOwner))
return;
return false;
if (askForConfirmation)
{
var workspaceName = await WorkspaceBehaviour.LoadWorkspaceNameAsync(chat.WorkspaceId);
var dialogParameters = new DialogParameters<ConfirmDialog>
{
{
x => x.Message, (chat.WorkspaceId == Guid.Empty) switch
{
true => string.Format(T("Are you sure you want to delete the temporary chat '{0}'?"), chat.Name),
false => string.Format(T("Are you sure you want to delete the chat '{0}' in the workspace '{1}'?"), chat.Name, workspaceName),
}
},
};
if (!await WorkspaceBehaviour.DeleteChatAsync(this.DialogService, chat.WorkspaceId, chat.ChatId, askForConfirmation))
return false;
var dialogReference = await this.DialogService.ShowAsync<ConfirmDialog>(T("Delete Chat"), dialogParameters, DialogOptions.FULLSCREEN);
var dialogResult = await dialogReference.Result;
if (dialogResult is null || dialogResult.Canceled)
return;
}
await WorkspaceBehaviour.DeleteChatAsync(this.DialogService, chat.WorkspaceId, chat.ChatId, askForConfirmation: false);
this.MediaTranscriptionService.ClearOwnerState(mediaOwner);
await this.LoadTreeItemsAsync(startPrefetch: false);
@@ -743,6 +759,8 @@ public partial class Workspaces : MSGComponentBase
this.CurrentChatThread = null;
await this.CurrentChatThreadChanged.InvokeAsync(this.CurrentChatThread);
}
return true;
}
private async Task RenameChatAsync(string? chatPath)
@@ -781,6 +799,62 @@ public partial class Workspaces : MSGComponentBase
await this.LoadTreeItemsAsync(startPrefetch: false);
}
/// <summary>
/// Copies the chat behind the copy button of a tree item and opens the copy.
/// </summary>
/// <param name="chatPath">The directory of the chat to copy.</param>
/// <remarks>
/// The copy itself is done by CopyChatAsync, which the chat toolbar uses as well. What this
/// handler adds is what only the tree needs: it finds the chat by its directory, and because it
/// opens the copy afterward, it asks first when the chat open right now has unsaved changes.
/// The chat toolbar asks nothing, since it copies the chat on the screen and keeps working in it.
/// </remarks>
private async Task CopyChatFromTreeAsync(string? chatPath)
{
var chat = await this.LoadChatAsync(chatPath, false);
if (chat is null)
return;
var mediaOwner = MediaImportOwner.ForChat(chat.ChatId);
if (this.AIJobService.IsChatGenerationActive(chat.ChatId) || this.MediaTranscriptionService.IsBusy(mediaOwner))
return;
//
// Copying the chat which is open right now takes its in-memory state, so whatever the user
// has not saved yet ends up in the copy while the original keeps the state it was stored
// with. Copying any other chat replaces the open one, so its unsaved changes are gone.
// Both outcomes are surprising enough to deserve their own wording.
//
var openChat = this.CurrentChatThread;
var isCopyOfOpenChat = openChat is not null && openChat.ChatId == chat.ChatId;
if (await MessageBus.INSTANCE.SendMessageUseFirstResult<bool, bool>(this, Event.HAS_CHAT_UNSAVED_CHANGES))
{
var dialogParameters = new DialogParameters<ConfirmDialog>
{
{
x => x.Message, isCopyOfOpenChat switch
{
true => T("Do you want to copy this chat? Your unsaved changes move into the copy, and the original chat keeps the state it was last saved with."),
false => T("Do you want to copy this chat? The copy is opened afterwards, so all unsaved changes of the chat you have open right now will be lost."),
}
},
};
var dialogReference = await this.DialogService.ShowAsync<ConfirmDialog>(T("Copy Chat"), dialogParameters, DialogOptions.FULLSCREEN);
var dialogResult = await dialogReference.Result;
if (dialogResult is null || dialogResult.Canceled)
return;
}
var sourceChat = isCopyOfOpenChat ? openChat! : chat;
var copy = await this.CopyChatAsync(sourceChat);
if (copy is null)
return;
this.CurrentChatThread = copy;
await this.CurrentChatThreadChanged.InvokeAsync(this.CurrentChatThread);
}
private async Task RenameWorkspaceAsync(string? workspacePath)
{
if (workspacePath is null)