Merge branch 'main' into fix/transcription-dialog-api-key-not-loaded

This commit is contained in:
Thorsten Sommer authored and GitHub committed 2026-09-16 10:44:53 +02:00
commit 6c5c982f92
400 files changed
+22787 -4290

No files matched your search

@@ -32,8 +32,7 @@
@bind-ProfileId="@this.profileId"
@bind-ChatTemplateId="@this.chatTemplateId"
@bind-DataSourceIds="@this.dataSourceIds"
@bind-ToolIds="@this.toolIds"
ValidateWorkspaceName="@this.ValidateWorkspaceName"/>
@bind-ToolIds="@this.toolIds"/>
</MudPaper>
</MudForm>
@@ -152,7 +152,9 @@ public partial class DirectChatLauncherSettingsDialog : MSGComponentBase
//
// An empty selection means "use the chat defaults" and is left out of the plugin, whereas
// the empty GUID explicitly selects no profile or no chat template:
// the empty GUID explicitly selects no profile or no chat template. Clearing the workspace
// name is a change of its own: the tile then opens a disappearing chat, and the writer
// switches the launch behavior accordingly.
//
return new(
this.workspaceName.Trim(),
@@ -248,8 +250,6 @@ public partial class DirectChatLauncherSettingsDialog : MSGComponentBase
private string? ValidateDescription(string value) => string.IsNullOrWhiteSpace(value) ? T("Please provide a description for this tile.") : null;
private string? ValidateWorkspaceName(string value) => string.IsNullOrWhiteSpace(value) ? T("Please select or enter a workspace name for this tile.") : null;
private void Cancel() => this.MudDialog.Cancel();
private static Guid? ParseOptionalGuid(string value) => Guid.TryParse(value, out var parsed) ? parsed : null;
@@ -3,20 +3,34 @@
<MudDialog>
<DialogContent>
@* A drop anywhere in this dialog belongs to the dialog, not to the page behind it: *@
<PathDropZone IsArea="@true">
<PathDropZone IsArea="@true"
IdPrefix="document-check"
OnPathsDropped="@this.DropCallback"
Disabled="@this.IsZoneDisabled"
Context="isDropTarget">
<MudJustifiedText Typo="Typo.body1" Class="mb-3">
@T("See how we load your file. Review the content before we process it further.")
</MudJustifiedText>
@if (this.Document is null)
@if (this.CanAttach)
{
<ReadFileContent Text="@T("Load file")" FileContent="@this.FileContent" FileContentChanged="@this.ApplyLoadedFileContent" EnableDragDrop="true" CatchAllDocuments="true"/>
<MudJustifiedText Typo="Typo.body1" Class="mb-3">
@T("You can drag another file into this window. We attach it right away and show it here.")
</MudJustifiedText>
}
@if (this.document is null)
{
<ReadFileContent Text="@T("Load file")" FileContent="@this.fileContent" FileContentChanged="@this.ApplyLoadedFileContent" EnableDragDrop="true" CatchAllDocuments="true"/>
}
else
{
@* Keys have to be unique among siblings, no matter the component: this field and the
tabs below both stand for the document and would otherwise collide on its path. *@
<MudTextField
@key="@($"file-path-{this.document.FilePath}")"
T="string"
Text="@this.Document.FilePath"
Text="@this.document.FilePath"
AdornmentIcon="@Icons.Material.Filled.FileOpen"
Adornment="Adornment.Start"
Immediate="@true"
@@ -29,7 +43,10 @@
/>
}
@if (!this.Document?.Exists ?? false)
@* The frame shows where a dropped file would land. It is drawn only while this dialog can
take one, and keeps its width in both states so that nothing jumps during a drag: *@
<div class="@this.PreviewAreaClass(isDropTarget)">
@if (!this.document?.Exists ?? false)
{
<MudAlert Severity="Severity.Error" Variant="Variant.Filled" Class="my-2">
@T("The specified file could not be found. The file have been moved, deleted, renamed, or is otherwise inaccessible.")
@@ -60,11 +77,13 @@
</MudAlert>
}
<MudTabs Elevation="0" Rounded="true" ApplyEffectsToContainer="true" Outlined="true" PanelClass="pa-2" Class="mb-2">
@if (this.Document?.IsImage ?? false)
@* Keyed by the document: a switch from an image to a text file changes which panels
exist, and a leftover active panel would point at one that is gone. *@
<MudTabs @key="@($"preview-tabs-{this.document?.FilePath}")" Elevation="0" Rounded="true" ApplyEffectsToContainer="true" Outlined="true" PanelClass="pa-2" Class="mb-2">
@if (this.document?.IsImage ?? false)
{
<MudTabPanel Text="@T("Image View")" Icon="@Icons.Material.Filled.Image">
<MudImage ObjectFit="ObjectFit.ScaleDown" Style="width: 100%;" Src="@this.Document.FilePathAsUrl"/>
<MudImage ObjectFit="ObjectFit.ScaleDown" Style="width: 100%;" Src="@this.document.FilePathAsUrl"/>
</MudTabPanel>
}
else
@@ -102,6 +121,7 @@
}
</MudTabs>
}
</div>
</PathDropZone>
</DialogContent>
<DialogActions>
@@ -21,6 +21,46 @@ public partial class DocumentCheckDialog : MSGComponentBase
[Parameter]
public string FileContent { get; set; } = string.Empty;
/// <summary>
/// Attaches the files the user drops onto this dialog, and answers which of them it attached.
/// </summary>
/// <remarks>
/// Null when our caller has no list of attachments to add to, which is the case for the prompt
/// guide preview of the Prompt Optimizer. This dialog then shows its document and nothing else,
/// exactly as it always did.
/// </remarks>
[Parameter]
public Func<List<string>, Task<IReadOnlyList<FileAttachment>>>? AttachPaths { get; set; }
/// <summary>
/// Decides, at the moment a drop arrives, whether attaching is possible right now.
/// </summary>
/// <remarks>
/// Asked rather than passed as a value, because the answer changes while this dialog is open:
/// dropping a media file starts a transcription, and nothing else may be attached until that
/// one is through.
/// </remarks>
[Parameter]
public Func<bool>? IsAttachingUnavailable { get; set; }
/// <summary>
/// The document we show right now. It starts out as the one we were opened with and changes
/// whenever the user drops another file onto this dialog.
/// </summary>
/// <remarks>
/// Kept in a field rather than read from the parameter: the dialog fragment is rendered again
/// with the parameters captured when it was opened, whenever something about the dialog stack
/// changes. That happens in the middle of a drop, because attaching may open the Pandoc dialog
/// or ask the user about a media file -- reading the parameter would undo the switch right
/// after it was made.
/// </remarks>
private FileAttachment? document;
/// <summary>
/// The content of the document we show, either handed to us by our caller or read by us.
/// </summary>
private string fileContent = string.Empty;
/// <summary>
/// How many characters we show at most. Rendering a huge document costs us a large Markdown
/// syntax tree and an equally large render tree. This dialog answers the question of how we
@@ -46,9 +86,20 @@ public partial class DocumentCheckDialog : MSGComponentBase
private int previewCutOffCharacters;
/// <summary>
/// Ends the extraction when this dialog is gone before the file was read completely.
/// Ends the extraction when this dialog is gone, or when another document took the place of
/// the one being read, before that file was read completely.
/// </summary>
private readonly CancellationTokenSource extractionCancellation = new();
private CancellationTokenSource extractionCancellation = new();
/// <summary>
/// Numbers the loads, so that a load can tell whether it still owns this dialog.
/// </summary>
/// <remarks>
/// Cancelling ends the waiting, not the code behind it: what follows every await of an
/// abandoned load runs regardless. Without this number, its final block would clear the loading
/// state of the load which replaced it, and the new document would never leave its skeletons.
/// </remarks>
private int loadGeneration;
/// <summary>
/// True once this dialog was disposed. The extraction runs across awaits, so it may return
@@ -73,75 +124,194 @@ public partial class DocumentCheckDialog : MSGComponentBase
protected override async Task OnInitializedAsync()
{
//
// Decide before the first render whether we have to read the file at all. Images are shown
// as they are, a missing file shows its own message, and content a caller already handed
// us is reused instead of being extracted a second time:
//
this.isLoadingContent =
this.Document is not null &&
!this.Document.IsImage &&
this.Document.Exists &&
string.IsNullOrWhiteSpace(this.FileContent);
this.document = this.Document;
this.fileContent = this.FileContent;
this.isLoadingContent = this.NeedsExtraction();
this.UpdatePreview();
await base.OnInitializedAsync();
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender && this.Document is not null)
if (!firstRender)
return;
if (this.document is null)
{
if (!this.isLoadingContent)
this.Logger.LogWarning("Document check dialog opened without a valid file path.");
return;
}
await this.LoadDocumentContentAsync();
}
/// <summary>
/// Whether the document we show has to be read before we can show anything of it. Images are
/// shown as they are, a missing file shows its own message, and content a caller already handed
/// us is reused instead of being extracted a second time.
/// </summary>
private bool NeedsExtraction() =>
this.document is not null &&
!this.document.IsImage &&
this.document.Exists &&
string.IsNullOrWhiteSpace(this.fileContent);
/// <summary>
/// Reads the content of the document we show and puts it into the preview.
/// </summary>
/// <remarks>
/// Runs after a render, so the user sees that we are working instead of an empty document. It
/// is called for the document this dialog was opened with, and again for every file the user
/// drops onto it.
/// </remarks>
private async Task LoadDocumentContentAsync()
{
if (this.document is null || !this.isLoadingContent)
return;
//
// A drop may arrive while we are still reading the file before it. We number this load and
// end the previous one, so that what is left of it recognizes that this dialog has moved on:
//
var generation = ++this.loadGeneration;
var documentToLoad = this.document;
var previousCancellation = this.extractionCancellation;
this.extractionCancellation = new();
var cancellationToken = this.extractionCancellation.Token;
await previousCancellation.CancelAsync();
previousCancellation.Dispose();
if (this.isDisposed || generation != this.loadGeneration)
return;
try
{
var extraction = await UserFile.LoadFileData(documentToLoad.FilePath, this.RustService, this.PandocAvailability, cancellationToken);
if (this.isDisposed || generation != this.loadGeneration)
return;
try
{
var extraction = await UserFile.LoadFileData(this.Document.FilePath, this.RustService, this.PandocAvailability, this.extractionCancellation.Token);
if (this.isDisposed)
return;
this.fileContent = extraction.Content;
this.FileContent = extraction.Content;
//
// This dialog exists so the user can check what we hand to the AI. Showing an
// empty document when reading the file failed would answer that question wrong.
//
if (!extraction.HasUsableContent)
this.loadFailureMessage = extraction.ToUserMessage(documentToLoad.FileName);
}
catch (OperationCanceledException)
{
// Either the user closed this dialog, or another document took the place of this one
// while we were reading it. Nothing left to do in both cases.
}
catch (Exception ex)
{
this.Logger.LogError(ex, "Failed to load file content from '{FilePath}'", documentToLoad.FilePath);
if (this.isDisposed || generation != this.loadGeneration)
return;
//
// This dialog exists so the user can check what we hand to the AI. Showing an
// empty document when reading the file failed would answer that question wrong.
//
if (!extraction.HasUsableContent)
this.loadFailureMessage = extraction.ToUserMessage(this.Document.FileName);
}
catch (OperationCanceledException)
this.fileContent = string.Empty;
this.loadFailureMessage = FileExtractionErrorCode.INTERNAL.ToUserMessage(documentToLoad.FileName);
}
finally
{
if (!this.isDisposed && generation == this.loadGeneration)
{
// The user closed this dialog while we were reading the file. Nothing left to do.
}
catch (Exception ex)
{
this.Logger.LogError(ex, "Failed to load file content from '{FilePath}'", this.Document);
this.FileContent = string.Empty;
this.loadFailureMessage = FileExtractionErrorCode.INTERNAL.ToUserMessage(this.Document.FileName);
}
finally
{
if (!this.isDisposed)
{
this.isLoadingContent = false;
this.UpdatePreview();
this.StateHasChanged();
}
this.isLoadingContent = false;
this.UpdatePreview();
this.StateHasChanged();
}
}
else if (firstRender)
this.Logger.LogWarning("Document check dialog opened without a valid file path.");
}
/// <summary>
/// Whether a dropped file can be both attached and shown here, which decides what this dialog
/// says and shows -- and whether it takes drops at all.
/// </summary>
/// <remarks>
/// Without a document, this dialog offers a file to be loaded instead, and that field is the
/// default target of this dialog. An area which reports a delegate claims that role for itself
/// and would take every drop away from the field, so we stay a plain marker in that case.
/// </remarks>
private bool CanAttach => this.AttachPaths is not null && this.document is not null;
private EventCallback<List<string>> DropCallback => this.CanAttach
? EventCallback.Factory.Create<List<string>>(this, this.PathsDropped)
: default;
private bool IsZoneDisabled() => this.IsAttachingUnavailable?.Invoke() ?? false;
/// <summary>
/// Marks the part of this dialog which shows the document while a file hovers over it, so it is
/// visible where that file would land. The frame keeps its width in both states; only its color
/// changes, or the content would jump by a few pixels with every drag.
/// </summary>
/// <param name="isDropTarget">Whether this dialog is the target of the drop being aimed right now.</param>
private string PreviewAreaClass(bool isDropTarget)
{
if (!this.CanAttach)
return string.Empty;
return isDropTarget && !this.IsZoneDisabled()
? "border-dashed border-2 rounded-lg pa-2 mud-border-primary"
: "border-dashed border-2 rounded-lg pa-2 mud-border-lines-default";
}
/// <summary>
/// Attaches what the user dropped onto this dialog and shows the first file of it.
/// </summary>
/// <param name="paths">The dropped paths, in the order the runtime delivered them.</param>
private async Task PathsDropped(List<string> paths)
{
if (this.AttachPaths is null)
return;
var attached = await this.AttachPaths(paths);
if (this.isDisposed)
return;
//
// Nothing came of the drop: the file is of a kind we do not take, Pandoc is missing, the
// validation refused it, or it is a media file whose transcript does not exist yet. The
// reason is already on its way to the user, and the document they were looking at stays.
//
if (attached.Count is 0)
return;
this.ShowDocument(attached[0]);
//
// Render before reading: the skeletons of the loading state are what tells the user that
// the preview switched at all, and reading a file may well take a moment.
//
this.StateHasChanged();
await this.LoadDocumentContentAsync();
}
/// <summary>
/// Shows another document, discarding everything that belonged to the previous one.
/// </summary>
/// <param name="attachment">The document to show from now on.</param>
private void ShowDocument(FileAttachment attachment)
{
this.document = attachment;
this.fileContent = string.Empty;
this.loadFailureMessage = null;
this.isLoadingContent = this.NeedsExtraction();
this.UpdatePreview();
}
/// <summary>
/// Called when the user loads a file through this dialog. We don't use a two-way binding here,
/// since we have to refresh the preview whenever the content changes.
/// </summary>
/// <param name="fileContent">The content of the file the user has loaded.</param>
private void ApplyLoadedFileContent(string fileContent)
/// <param name="loadedContent">The content of the file the user has loaded.</param>
private void ApplyLoadedFileContent(string loadedContent)
{
this.FileContent = fileContent;
this.fileContent = loadedContent;
this.UpdatePreview();
}
@@ -150,9 +320,9 @@ public partial class DocumentCheckDialog : MSGComponentBase
/// </summary>
private void UpdatePreview()
{
if (this.FileContent.Length <= PREVIEW_CHARACTER_LIMIT)
if (this.fileContent.Length <= PREVIEW_CHARACTER_LIMIT)
{
this.previewContent = this.FileContent;
this.previewContent = this.fileContent;
this.previewCutOffCharacters = 0;
return;
}
@@ -161,12 +331,12 @@ public partial class DocumentCheckDialog : MSGComponentBase
// We cut at the last line break before our limit. Otherwise, we might tear apart a Markdown
// construct like a table row or a code fence in the middle of a line:
//
var cutIndex = this.FileContent.LastIndexOf('\n', PREVIEW_CHARACTER_LIMIT - 1) + 1;
var cutIndex = this.fileContent.LastIndexOf('\n', PREVIEW_CHARACTER_LIMIT - 1) + 1;
if (cutIndex < 1)
cutIndex = PREVIEW_CHARACTER_LIMIT;
this.previewContent = this.FileContent[..cutIndex];
this.previewCutOffCharacters = this.FileContent.Length - cutIndex;
this.previewContent = this.fileContent[..cutIndex];
this.previewCutOffCharacters = this.fileContent.Length - cutIndex;
}
/// <summary>
@@ -177,6 +347,11 @@ public partial class DocumentCheckDialog : MSGComponentBase
protected override void DisposeResources()
{
this.isDisposed = true;
//
// Only the running load is left to end here: every load we replaced was ended and disposed
// the moment its successor started.
//
this.extractionCancellation.Cancel();
this.extractionCancellation.Dispose();
@@ -187,6 +187,7 @@
Disabled="@this.IsEnterpriseConfiguration"
Validation="@this.ValidateEmbeddingBatchSize"
HelperText="@T("How many chunks are sent to the embedding provider at once. The default is 1.")"/>
<TokenizerHint LLMProvider="@this.DataLLMProvider" Model="@this.DataModel"/>
<PathDropZone IdPrefix="tokenizer" Disabled="@(() => this.IsEnterpriseConfiguration)" OnPathsDropped="@this.OnTokenizerPathsDropped">
<MudStack Row="@true" Spacing="3" Class="mb-3" StretchItems="StretchItems.None" AlignItems="AlignItems.Center">
<MudTextField
@@ -242,6 +242,64 @@
</MudSelect>
</MudPaper>
</MudStack>
<MudText Typo="Typo.subtitle2" Class="mb-2">
@T("Override Model Limits")
</MudText>
<MudJustifiedText Typo="Typo.body2" Class="mb-4">
@T("Where the stored numbers do not match your installation, state yours here. This matters most for self-hosted models: they run with whatever their operator configured, which the model card cannot know.")
</MudJustifiedText>
<MudStack Class="mb-4" Spacing="2">
<MudPaper Outlined="@true" Class="pa-3">
<MudNumericField T="int?"
Value="@this.capabilityOverrides.ContextWindowTokens"
ValueChanged="@this.SetContextWindowOverride"
Label="@T("Context window in tokens")"
HelperText="@this.ContextWindowHelperText"
Placeholder="@this.AutomaticContextWindowPlaceholder"
Variant="Variant.Outlined"
Margin="Margin.Dense"
Min="1"
HideSpinButtons="@true"
Clearable="@true"
Disabled="@this.IsEnterpriseConfiguration"
Adornment="Adornment.Start"
AdornmentIcon="@Icons.Material.Filled.Straighten"
AdornmentColor="Color.Info" />
</MudPaper>
<MudPaper Outlined="@true" Class="pa-3">
<MudText Typo="Typo.body2">
@T("Images")
</MudText>
<MudText Typo="Typo.caption" Color="Color.Secondary">
@this.ImageLimitsEffectiveLabel
</MudText>
<MudStack Row="@true" Spacing="3" Wrap="Wrap.Wrap" Class="border-dashed border rounded-lg pa-3 mt-3">
<MudNumericField T="int?"
Value="@this.capabilityOverrides.MaxImagesPerMessage"
ValueChanged="@this.SetMaxImagesPerMessageOverride"
Label="@T("Per message")"
Placeholder="@this.AutomaticImageLimitPlaceholder(this.GetAutomaticModelProfile().Images.MaxPerMessage)"
Variant="Variant.Outlined"
Margin="Margin.Dense"
Min="0"
Clearable="@true"
Disabled="@this.IsEnterpriseConfiguration" />
<MudNumericField T="int?"
Value="@this.capabilityOverrides.MaxImagesPerRequest"
ValueChanged="@this.SetMaxImagesPerRequestOverride"
Label="@T("Per request")"
Placeholder="@this.AutomaticImageLimitPlaceholder(this.GetAutomaticModelProfile().Images.MaxPerRequest)"
Variant="Variant.Outlined"
Margin="Margin.Dense"
Min="0"
Clearable="@true"
Disabled="@this.IsEnterpriseConfiguration" />
</MudStack>
<MudText Typo="Typo.caption" Color="Color.Secondary" Class="mt-2">
@T("Vendors state one of the two, the other, or neither. Whichever is smaller decides how many images one message may carry; an empty field states nothing.")
</MudText>
</MudPaper>
</MudStack>
<MudJustifiedText Typo="Typo.body2" Class="mb-4">
@string.Format(T("The current model uses the {0}."), this.GetCurrentModelApiLabel())
</MudJustifiedText>
@@ -251,6 +309,7 @@
<MudJustifiedText Typo="Typo.body1" Class="mt-4 mb-3">
@T("For better token estimates, you can configure a custom tokenizer for this provider.")
</MudJustifiedText>
<TokenizerHint LLMProvider="@this.DataLLMProvider" Model="@this.DataModel"/>
<PathDropZone IdPrefix="tokenizer" Disabled="@(() => this.IsEnterpriseConfiguration)" OnPathsDropped="@this.OnTokenizerPathsDropped">
<MudStack Row="@true" Spacing="3" Class="mb-3" StretchItems="StretchItems.None" AlignItems="AlignItems.Center">
<MudTextField
@@ -1,7 +1,9 @@
using System.Globalization;
using System.Text;
using System.Text.Json;
using AIStudio.Components;
using AIStudio.Models;
using AIStudio.Provider;
using AIStudio.Provider.HuggingFace;
using AIStudio.Tools.Rust;
@@ -163,6 +165,16 @@ public partial class ProviderDialog : MSGComponentBase, ISecretId
private bool usesLegacySystemModelFallback;
private bool showExpertSettings;
private ProviderCapabilityOverrides capabilityOverrides = new();
/// <summary>
/// The culture the numbers of this dialog are written in.
/// </summary>
/// <remarks>
/// AI Studio's language is a setting of its own and does not move the thread's culture along
/// with it. Without this, a German who chose German would read a context window of 131,072
/// tokens as a number a thousand times smaller.
/// </remarks>
private CultureInfo currentCulture = CultureInfo.InvariantCulture;
// We get the form reference from Blazor code to validate it manually:
private MudForm form = null!;
@@ -226,7 +238,11 @@ public partial class ProviderDialog : MSGComponentBase, ISecretId
{
// Call the base initialization first so that the I18N is ready:
await base.OnInitializedAsync();
// The numbers of the expert settings are written the way the chosen language writes them:
var activeLanguagePlugin = await this.SettingsManager.GetActiveLanguagePlugin();
this.currentCulture = CommonTools.DeriveActiveCultureOrInvariant(activeLanguagePlugin.IETFTag);
// Configure the spellchecking for the instance name input:
this.SettingsManager.InjectSpellchecking(SPELLCHECK_ATTRIBUTES);
@@ -663,33 +679,29 @@ public partial class ProviderDialog : MSGComponentBase, ISecretId
if (alwaysReasoning is null && optionalReasoning is null && reasoningByDefault is null)
return ReasoningOverrideMode.AUTOMATIC;
var capabilities = this.GetCurrentModelCapabilities();
if (capabilities.Contains(Capability.ALWAYS_REASONING))
return ReasoningOverrideMode.ALWAYS_ON;
if (capabilities.Contains(Capability.REASONING_BY_DEFAULT))
return ReasoningOverrideMode.ON_BY_DEFAULT;
if (capabilities.Contains(Capability.OPTIONAL_REASONING))
return ReasoningOverrideMode.CAN_BE_ENABLED;
return ReasoningOverrideMode.NO_REASONING;
return ModeOf(this.GetCurrentModelProfile().Reasoning);
}
private ReasoningOverrideMode GetAutomaticReasoningOverrideMode()
private ReasoningOverrideMode GetAutomaticReasoningOverrideMode() => ModeOf(this.GetAutomaticModelProfile().Reasoning);
/// <summary>
/// Which of the choices in this dialog a reasoning state is.
/// </summary>
/// <remarks>
/// The five entries of the list were always this one answer, only written as three flags and
/// read back by asking for them in the right order. Now they are the same four words plus
/// "automatic", which is the absence of a statement rather than a state a model can be in.
/// </remarks>
/// <param name="reasoning">How the model reasons.</param>
/// <returns>The choice standing for it.</returns>
private static ReasoningOverrideMode ModeOf(ReasoningSupport reasoning) => reasoning switch
{
var capabilities = this.GetAutomaticModelCapabilities();
if (capabilities.Contains(Capability.ALWAYS_REASONING))
return ReasoningOverrideMode.ALWAYS_ON;
ReasoningSupport.ALWAYS => ReasoningOverrideMode.ALWAYS_ON,
ReasoningSupport.ON_BY_DEFAULT => ReasoningOverrideMode.ON_BY_DEFAULT,
ReasoningSupport.OPTIONAL => ReasoningOverrideMode.CAN_BE_ENABLED,
if (capabilities.Contains(Capability.REASONING_BY_DEFAULT))
return ReasoningOverrideMode.ON_BY_DEFAULT;
if (capabilities.Contains(Capability.OPTIONAL_REASONING))
return ReasoningOverrideMode.CAN_BE_ENABLED;
return ReasoningOverrideMode.NO_REASONING;
}
_ => ReasoningOverrideMode.NO_REASONING,
};
private void SetReasoningOverrideMode(ReasoningOverrideMode mode)
{
@@ -746,11 +758,7 @@ public partial class ProviderDialog : MSGComponentBase, ISecretId
private bool HasCapabilityOverride(Capability capability) => this.capabilityOverrides.GetOverride(capability) is not null;
private bool IsCapabilityEnabled(Capability capability)
{
var capabilities = this.GetCurrentModelCapabilities();
return capabilities.Contains(capability);
}
private bool IsCapabilityEnabled(Capability capability) => this.GetCurrentModelProfile().Has(capability);
private string GetCapabilityEffectiveLabel(Capability capability)
{
@@ -761,21 +769,107 @@ public partial class ProviderDialog : MSGComponentBase, ISecretId
return isEnabled ? T("Enabled (Auto)") : T("Disabled (Auto)");
}
private List<Capability> GetCurrentModelCapabilities()
/// <summary>
/// States how many tokens this installation reads and writes.
/// </summary>
/// <param name="tokens">The number of tokens, or null to go back to the automatic answer.</param>
private void SetContextWindowOverride(int? tokens) => this.capabilityOverrides = this.capabilityOverrides with { ContextWindowTokens = tokens };
/// <summary>
/// States how many images one message may carry here.
/// </summary>
/// <param name="images">The number of images, or null to go back to the automatic answer.</param>
private void SetMaxImagesPerMessageOverride(int? images) => this.capabilityOverrides = this.capabilityOverrides with { MaxImagesPerMessage = images };
/// <summary>
/// States how many images one request may carry here.
/// </summary>
/// <param name="images">The number of images, or null to go back to the automatic answer.</param>
private void SetMaxImagesPerRequestOverride(int? images) => this.capabilityOverrides = this.capabilityOverrides with { MaxImagesPerRequest = images };
/// <summary>
/// What an empty window field shows.
/// </summary>
/// <remarks>
/// Written without separators, unlike the number in the helper text next to it: this one stands
/// inside the field a person types into, and what they see there has to be what they may type.
/// </remarks>
private string AutomaticContextWindowPlaceholder
{
var currentProviderSettings = this.CreateProviderSettings();
return currentProviderSettings.GetModelCapabilities();
get
{
var context = this.GetAutomaticModelProfile().Context;
return context.IsKnown ? context.DefaultTokens.ToString(CultureInfo.InvariantCulture) : string.Empty;
}
}
private List<Capability> GetAutomaticModelCapabilities() => this.DataLLMProvider.GetModelCapabilities(this.GetSelectedModel());
/// <summary>
/// What an empty image field shows.
/// </summary>
/// <param name="limit">The limit the rules worked out, if any.</param>
/// <returns>The number, or nothing where nobody stated one.</returns>
private string AutomaticImageLimitPlaceholder(int? limit) => limit?.ToString(CultureInfo.InvariantCulture) ?? string.Empty;
/// <summary>
/// What the window field says below itself.
/// </summary>
/// <remarks>
/// It names the automatic answer rather than the one in effect, because the number in effect is
/// already in the field. What a person cannot otherwise see is what they would go back to.
/// </remarks>
private string ContextWindowHelperText
{
get
{
var context = this.GetAutomaticModelProfile().Context;
return context.IsKnown
? string.Format(T("Detected: {0} tokens. Leave the field empty to use that."), context.DefaultTokens.ToString("N0", this.currentCulture))
: T("Nobody has stated a window for this model. Left empty, the chat counts the tokens of a conversation without saying what they may grow to.");
}
}
/// <summary>
/// What the two image fields say above themselves.
/// </summary>
/// <remarks>
/// The number in effect, not the two the person typed: which of them decides is the one thing
/// two fields cannot show on their own, and it is the one the chat and the Visual Briefing go by.
/// </remarks>
private string ImageLimitsEffectiveLabel
{
get
{
var allowed = this.GetCurrentModelProfile().Images.MaxInOneMessage;
return allowed is { } count
? string.Format(T("At most {0} images at once."), count.ToString("N0", this.currentCulture))
: T("No limit known, so AI Studio does not stop anybody from attaching more.");
}
}
/// <summary>
/// What the model can do as this provider instance is configured, the person's own settings included.
/// </summary>
/// <returns>The profile.</returns>
private ModelProfile GetCurrentModelProfile() => this.CreateProviderSettings().GetModelProfile();
/// <summary>
/// What holds without anybody switching anything, which is what each field shows as its automatic answer.
/// </summary>
/// <remarks>
/// The rules, plus whatever the provider itself stated when the model list was loaded a moment
/// ago. A self-hosted engine is the case this matters for: it reports the window it was started
/// with, and that is the number a person gets by leaving the field below empty.
/// </remarks>
/// <returns>The profile.</returns>
private ModelProfile GetAutomaticModelProfile() => this.CreateProviderSettings().GetAutomaticModelProfile();
private string GetCurrentModelApiLabel()
{
var capabilities = this.GetCurrentModelCapabilities();
if (capabilities.Contains(Capability.RESPONSES_API))
var profile = this.GetCurrentModelProfile();
if (profile.Has(Capability.RESPONSES_API))
return "Responses API";
if (capabilities.Contains(Capability.CHAT_COMPLETION_API))
if (profile.Has(Capability.CHAT_COMPLETION_API))
return "Chat Completions API";
return "Unknown";
@@ -2,13 +2,26 @@
<MudDialog>
<DialogContent>
@* A drop anywhere in this dialog belongs to the dialog, not to the page behind it: *@
<PathDropZone IsArea="@true"
IdPrefix="review-attachments"
OnPathsDropped="@this.DropCallback"
Disabled="@this.IsZoneDisabled"
Context="isDropTarget">
<MudJustifiedText Typo="Typo.body1" Class="mb-3">
@T("Here you can see all attached files. Files that can no longer be found (deleted, renamed, or moved) are marked with a warning icon and a strikethrough name. You can remove any attachment using the trash can icon.")
</MudJustifiedText>
@if (this.CanAttach)
{
<MudJustifiedText Typo="Typo.body1" Class="mb-3">
@T("You can drag more files into this window to attach them right away.")
</MudJustifiedText>
}
<MudDivider Class="mt-3 mb-3"/>
<div style="max-height: 50vh; overflow-y: auto; overflow-x: hidden; padding-right: 8px;">
<div class="@this.AttachmentListClass(isDropTarget)" style="max-height: 50vh; overflow-y: auto; overflow-x: hidden;">
@if (!this.DocumentPaths.Any())
{
<MudJustifiedText Typo="Typo.body1" Class="mt-3">
@@ -18,7 +31,7 @@
@{
var currentFolder = string.Empty;
foreach (var fileAttachment in this.DocumentPaths)
foreach (var fileAttachment in this.OrderedAttachments)
{
var folderPath = Path.GetDirectoryName(fileAttachment.FilePath);
if (folderPath != currentFolder)
@@ -91,6 +104,7 @@
}
}
</div>
</PathDropZone>
</DialogContent>
<DialogActions>
<MudButton OnClick="@this.Close" Variant="Variant.Filled" Color="Color.Primary">
@@ -16,18 +16,123 @@ public partial class ReviewAttachmentsDialog : MSGComponentBase
[Parameter]
public HashSet<FileAttachment> DocumentPaths { get; set; } = new();
/// <summary>
/// Attaches the files the user drops onto this dialog, and answers which of them it attached.
/// </summary>
/// <remarks>
/// Null when this dialog only shows attachments, which is the case for a message that was
/// already sent: there is nothing left to attach to. Without this, the dialog behaves as it
/// always did and swallows every drop.
/// </remarks>
[Parameter]
public Func<List<string>, Task<IReadOnlyList<FileAttachment>>>? AttachPaths { get; set; }
/// <summary>
/// Decides, at the moment a drop arrives, whether attaching is possible right now.
/// </summary>
/// <remarks>
/// Asked rather than passed as a value, because the answer changes while this dialog is open:
/// dropping a media file here starts a transcription, and nothing else may be attached until
/// that one is through.
/// </remarks>
[Parameter]
public Func<bool>? IsAttachingUnavailable { get; set; }
[Inject]
private IDialogService DialogService { get; set; } = null!;
private void Close() => this.MudDialog.Close(DialogResult.Ok(this.DocumentPaths));
public static async Task<HashSet<FileAttachment>> OpenDialogAsync(IDialogService dialogService, params HashSet<FileAttachment> documentPaths)
/// <summary>Whether this dialog takes files at all, which decides what it says and shows.</summary>
private bool CanAttach => this.AttachPaths is not null;
private bool IsZoneDisabled() => this.IsAttachingUnavailable?.Invoke() ?? false;
/// <summary>
/// Binds the drop zone only when there is something to attach to. An area which reports a
/// delegate claims the role of its own default target, and claiming it without being able to
/// use it would swallow drops with no reason the user could see.
/// </summary>
private EventCallback<List<string>> DropCallback => this.AttachPaths is null
? default
: EventCallback.Factory.Create<List<string>>(this, this.PathsDropped);
/// <summary>
/// Marks the list of attachments while a file hovers over this dialog, so it is visible where
/// the file would land. The frame keeps its width in both states; only its color changes, or
/// the list would jump by a few pixels with every drag.
/// </summary>
/// <param name="isDropTarget">Whether this dialog is the target of the drop being aimed right now.</param>
private string AttachmentListClass(bool isDropTarget)
{
if (!this.CanAttach)
return "pa-2";
return isDropTarget && !this.IsZoneDisabled()
? "border-dashed border-2 rounded-lg pa-2 mud-border-primary"
: "border-dashed border-2 rounded-lg pa-2 mud-border-lines-default";
}
/// <summary>
/// The attachments, sorted by their folder and, within it, by their file name.
/// </summary>
/// <remarks>
/// The list below starts a new heading whenever the folder changes from one attachment to the
/// next, which names every folder exactly once -- but only as long as the attachments of a
/// folder arrive together. The set behind them keeps no order of its own to guarantee that:
/// removing one attachment already scrambles it, and one attached while this dialog is open
/// lands at its end, giving its folder a second heading further down. Sorting here is what that
/// list assumes anyway.
/// </remarks>
private IEnumerable<FileAttachment> OrderedAttachments => this.DocumentPaths
.OrderBy(attachment => Path.GetDirectoryName(attachment.FilePath) ?? string.Empty, StringComparer.OrdinalIgnoreCase)
.ThenBy(attachment => attachment.FileName, StringComparer.OrdinalIgnoreCase);
/// <summary>
/// Attaches what the user dropped onto this dialog and answers which files that became.
/// </summary>
/// <remarks>
/// Every drop takes this way, the ones aimed at the document preview above this dialog
/// included. That is why the list is refreshed here and nowhere else.
/// </remarks>
/// <param name="paths">The dropped paths, in the order the runtime delivered them.</param>
/// <returns>The files which were attached, in the order they were dropped.</returns>
private async Task<IReadOnlyList<FileAttachment>> AttachPathsAsync(List<string> paths)
{
if (this.AttachPaths is null)
return [];
var attached = await this.AttachPaths(paths);
this.StateHasChanged();
//
// The list scrolls, so a newly attached file may well sit outside the visible part of it.
// Saying so is cheaper than scrolling there, and the snackbar is skipped by the hit test,
// so it never gets in the way of the next drop.
//
if (attached.Count > 0)
await this.MessageBus.SendSuccess(new(Icons.Material.Filled.AttachFile, attached.Count is 1
? string.Format(T("Attached {0}."), attached[0].FileName)
: string.Format(T("Attached {0} files."), attached.Count)));
return attached;
}
private async Task PathsDropped(List<string> paths) => await this.AttachPathsAsync(paths);
public static async Task<HashSet<FileAttachment>> OpenDialogAsync(IDialogService dialogService, HashSet<FileAttachment> documentPaths, Func<List<string>, Task<IReadOnlyList<FileAttachment>>>? attachPaths = null, Func<bool>? isAttachingUnavailable = null)
{
var dialogParameters = new DialogParameters<ReviewAttachmentsDialog>
{
{ x => x.DocumentPaths, documentPaths }
};
if (attachPaths is not null)
dialogParameters.Add(x => x.AttachPaths, attachPaths);
if (isAttachingUnavailable is not null)
dialogParameters.Add(x => x.IsAttachingUnavailable, isAttachingUnavailable);
var dialogReference = await dialogService.ShowAsync<ReviewAttachmentsDialog>(TB("Your attached files"), dialogParameters, DialogOptions.FULLSCREEN);
var dialogResult = await dialogReference.Result;
if (dialogResult is null || dialogResult.Canceled)
@@ -58,6 +163,19 @@ public partial class ReviewAttachmentsDialog : MSGComponentBase
{ x => x.Document, fileAttachment },
};
//
// Give the preview our own way of attaching, so a file dropped onto it lands in this list
// as well. Not when we cannot attach anything ourselves: the preview would then claim every
// drop and do nothing with it.
//
if (this.CanAttach)
{
dialogParameters.Add(x => x.AttachPaths, this.AttachPathsAsync);
if (this.IsAttachingUnavailable is not null)
dialogParameters.Add(x => x.IsAttachingUnavailable, this.IsAttachingUnavailable);
}
await this.DialogService.ShowAsync<DocumentCheckDialog>(T("Document Preview"), dialogParameters, DialogOptions.FULLSCREEN);
}
}