mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-12-04 22:44:35 +00:00
Kept the inputs of assistants when you leave them (#1209)
Co-authored-by: Thorsten Sommer <SommerEngineering@users.noreply.github.com>
This commit is contained in:
1 parent
1fbc1f4796
commit
7e2f83b19b
83 files changed
+1924
-347
No files matched your search
@@ -1,9 +1,11 @@
|
||||
using AIStudio.Dialogs.Settings;
|
||||
using AIStudio.Settings.DataModel;
|
||||
using AIStudio.Tools.AssistantSessions;
|
||||
using AIStudio.Tools.Imports;
|
||||
using AIStudio.Tools.Media;
|
||||
using AIStudio.Tools.PluginSystem;
|
||||
using AIStudio.Tools.Services;
|
||||
using AIStudio.Tools.Web;
|
||||
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using DialogOptions = AIStudio.Dialogs.DialogOptions;
|
||||
@@ -79,7 +81,10 @@ public partial class AssistantBlock<TSettings> : MSGComponentBase, IAssistantCat
|
||||
|
||||
[Inject]
|
||||
private MediaTranscriptionService MediaTranscriptionService { get; init; } = null!;
|
||||
|
||||
|
||||
[Inject]
|
||||
private WebContentImportService WebContentImportService { get; init; } = null!;
|
||||
|
||||
private async Task OpenSettingsDialog()
|
||||
{
|
||||
if (!this.HasSettingsPanel)
|
||||
@@ -90,7 +95,7 @@ public partial class AssistantBlock<TSettings> : MSGComponentBase, IAssistantCat
|
||||
await this.DialogService.ShowAsync<TSettings>(T("Open Settings"), dialogParameters, DialogOptions.FULLSCREEN);
|
||||
}
|
||||
|
||||
private string BorderColor => this.AssistantSessionSnapshot?.IsActive is true || this.MediaImportSnapshot?.IsBusy is true ? this.ColorTheme.GetActivityIndicatorColor(this.SettingsManager) : this.SettingsManager.IsDarkMode switch
|
||||
private string BorderColor => this.AssistantSessionSnapshot?.IsActive is true || this.MediaImportSnapshot?.IsBusy is true || this.HasRunningWebContentImport ?this.ColorTheme.GetActivityIndicatorColor(this.SettingsManager) : this.SettingsManager.IsDarkMode switch
|
||||
{
|
||||
true => this.ColorTheme.GetCurrentPalette(this.SettingsManager).GrayDefault,
|
||||
false => this.ColorTheme.GetCurrentPalette(this.SettingsManager).GrayDefault,
|
||||
@@ -112,30 +117,30 @@ public partial class AssistantBlock<TSettings> : MSGComponentBase, IAssistantCat
|
||||
? this.AssistantSessionService.GetSnapshots().FirstOrDefault(snapshot => snapshot.Key.Component == this.Component)
|
||||
: this.AssistantSessionService.GetSnapshots().FirstOrDefault(snapshot => snapshot.Key.InstanceId == this.AssistantSessionInstanceId);
|
||||
|
||||
private MediaImportOwner CurrentMediaImportOwner => MediaImportOwner.ForAssistant(new AssistantSessionKey(this.Component, this.AssistantSessionInstanceId));
|
||||
private ImportOwner CurrentImportOwner => ImportOwner.ForAssistant(new AssistantSessionKey(this.Component, this.AssistantSessionInstanceId));
|
||||
|
||||
private MediaImportSnapshot? MediaImportSnapshot => this.MediaTranscriptionService.GetSnapshots()
|
||||
.FirstOrDefault(snapshot => this.OwnedByThisBlock(snapshot.Owner));
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether a media-import owner belongs to the assistant represented by this block.
|
||||
/// Gets whether an import owner belongs to the assistant represented by this block.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Owners that persist their own sources are keyed by the stored document rather than by an
|
||||
/// assistant session, so this block aggregates all of them for its component. Without a session
|
||||
/// instance we aggregate every owner of the component, otherwise we match the exact owner.
|
||||
/// </remarks>
|
||||
/// <param name="owner">The media-import owner to test.</param>
|
||||
/// <param name="owner">The import owner to test.</param>
|
||||
/// <returns><c>true</c> when this block represents the owner.</returns>
|
||||
private bool OwnedByThisBlock(MediaImportOwner owner)
|
||||
private bool OwnedByThisBlock(ImportOwner owner)
|
||||
{
|
||||
if (owner.Kind.PersistsOwnSources)
|
||||
return owner.Kind == this.Component.MediaOwnerKind;
|
||||
return owner.Kind == this.Component.ImportOwnerKind;
|
||||
|
||||
if (string.IsNullOrWhiteSpace(this.AssistantSessionInstanceId))
|
||||
return owner.Kind is MediaImportOwnerKind.ASSISTANT && owner.Id.StartsWith($"{this.Component}:", StringComparison.Ordinal);
|
||||
return owner.Kind is ImportOwnerKind.ASSISTANT && owner.Id.StartsWith($"{this.Component}:", StringComparison.Ordinal);
|
||||
|
||||
return owner == this.CurrentMediaImportOwner;
|
||||
return owner == this.CurrentImportOwner;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -152,18 +157,30 @@ public partial class AssistantBlock<TSettings> : MSGComponentBase, IAssistantCat
|
||||
_ => this.AssistantSessionIndicatorWithoutMedia,
|
||||
};
|
||||
|
||||
private AssistantSessionIndicatorData? AssistantSessionIndicatorWithoutMedia => this.AssistantSessionSnapshot?.Status switch
|
||||
/// <summary>
|
||||
/// Gets the indicator of the assistant session, unless web content for the assistant is still loading, which counts
|
||||
/// as running as well.
|
||||
/// </summary>
|
||||
private AssistantSessionIndicatorData? AssistantSessionIndicatorWithoutMedia => this.HasRunningWebContentImport ? this.RunningIndicator : this.AssistantSessionSnapshot?.Status switch
|
||||
{
|
||||
AssistantSessionStatus.RUNNING or AssistantSessionStatus.CANCELING => new(AppIcons.RUNNING, Color.Info, this.T("Assistant is still running.")),
|
||||
AssistantSessionStatus.RUNNING or AssistantSessionStatus.CANCELING => this.RunningIndicator,
|
||||
AssistantSessionStatus.COMPLETED => new(AppIcons.SUCCESS, Color.Success, this.T("The result is ready.")),
|
||||
AssistantSessionStatus.FAILED => new(AppIcons.ERROR, Color.Error, this.TA("Assistant failed. Open it to review the result.")),
|
||||
AssistantSessionStatus.CANCELED => new(AppIcons.CANCELED, Color.Warning, this.TA("Assistant was canceled. Open it to review the result.")),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
private AssistantSessionIndicatorData RunningIndicator => new(AppIcons.RUNNING, Color.Info, this.T("Assistant is still running."));
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether one of the web content readers of the assistant is loading a page, see WebContentImportService.
|
||||
/// </summary>
|
||||
private bool HasRunningWebContentImport => this.WebContentImportService.GetSnapshots().Any(snapshot => this.OwnedByThisBlock(snapshot.Target.Owner));
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
this.MediaTranscriptionService.StateChanged += this.OnMediaImportStateChanged;
|
||||
this.MediaTranscriptionService.StateChanged += this.OnImportStateChanged;
|
||||
this.WebContentImportService.StateChanged += this.OnImportStateChanged;
|
||||
this.CategoryBlock?.RegisterAssistant(this);
|
||||
this.WarnAboutAnotherCategory();
|
||||
await base.OnInitializedAsync();
|
||||
@@ -188,15 +205,20 @@ public partial class AssistantBlock<TSettings> : MSGComponentBase, IAssistantCat
|
||||
this.Logger.LogError("The assistants page shows the assistant '{Component}' under the category '{PageCategory}', but its category is '{Category}'. Please move it into the section of its category.", this.Component, this.CategoryBlock.Category.Category, category);
|
||||
}
|
||||
|
||||
private void OnMediaImportStateChanged(MediaImportOwner owner)
|
||||
/// <summary>
|
||||
/// Renders the block again when an import of its assistant changed, the transcription of a media file or the
|
||||
/// loading of web content.
|
||||
/// </summary>
|
||||
private void OnImportStateChanged(ImportOwner owner)
|
||||
{
|
||||
if (this.OwnedByThisBlock(owner))
|
||||
this.InvokeAsync(this.StateHasChanged).Observe($"{nameof(AssistantBlock<>)}: rendering a media import change");
|
||||
this.InvokeAsync(this.StateHasChanged).Observe($"{nameof(AssistantBlock<>)}: rendering an import change");
|
||||
}
|
||||
|
||||
protected override void DisposeResources()
|
||||
{
|
||||
this.MediaTranscriptionService.StateChanged -= this.OnMediaImportStateChanged;
|
||||
this.MediaTranscriptionService.StateChanged -= this.OnImportStateChanged;
|
||||
this.WebContentImportService.StateChanged -= this.OnImportStateChanged;
|
||||
this.CategoryBlock?.UnregisterAssistant(this);
|
||||
base.DisposeResources();
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@
|
||||
</PathDropZone>
|
||||
@if (this.ShowMediaStatus)
|
||||
{
|
||||
<MediaTranscriptionStatus Owner="@this.EffectiveImportOwner" TargetId="@this.EffectiveMediaImportTarget.TargetId" Compact="true"/>
|
||||
<MediaTranscriptionStatus Owner="@this.EffectiveImportOwner" TargetId="@this.EffectiveImportTarget.TargetId" Compact="true"/>
|
||||
}
|
||||
</MudStack>
|
||||
}
|
||||
@@ -85,7 +85,7 @@ else
|
||||
}
|
||||
@if (this.ShowMediaStatus)
|
||||
{
|
||||
<MediaTranscriptionStatus Owner="@this.EffectiveImportOwner" TargetId="@this.EffectiveMediaImportTarget.TargetId"/>
|
||||
<MediaTranscriptionStatus Owner="@this.EffectiveImportOwner" TargetId="@this.EffectiveImportTarget.TargetId"/>
|
||||
}
|
||||
<PathDropZone IdPrefix="attach-documents"
|
||||
Class="pa-4 mt-4 mud-height-full"
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
using AIStudio.Chat;
|
||||
using AIStudio.Dialogs;
|
||||
using AIStudio.Tools.Imports;
|
||||
using AIStudio.Tools.Media;
|
||||
using AIStudio.Tools.PluginSystem;
|
||||
using AIStudio.Tools.Rust;
|
||||
@@ -14,10 +15,10 @@ using DialogOptions = Dialogs.DialogOptions;
|
||||
|
||||
public partial class AttachDocuments : MSGComponentBase
|
||||
{
|
||||
private readonly MediaImportOwner fallbackMediaImportOwner = new(MediaImportOwnerKind.CHAT, $"attachments:{Guid.NewGuid():N}");
|
||||
private readonly ImportOwner fallbackImportOwner = new(ImportOwnerKind.CHAT, $"attachments:{Guid.NewGuid():N}");
|
||||
|
||||
[CascadingParameter]
|
||||
private MediaImportOwner? ImportOwner { get; set; }
|
||||
private ImportOwner? ImportOwner { get; set; }
|
||||
|
||||
private static string TB(string fallbackEN) => I18N.I.T(fallbackEN, typeof(AttachDocuments).Namespace, nameof(AttachDocuments));
|
||||
|
||||
@@ -122,11 +123,11 @@ public partial class AttachDocuments : MSGComponentBase
|
||||
private static readonly string DROP_FILES_HERE_TEXT = TB("Drop files here to attach them.");
|
||||
|
||||
private bool isFileDialogOpen;
|
||||
private MediaImportOwner EffectiveImportOwner => this.OwnerChat is not null
|
||||
? MediaImportOwner.ForChat(this.OwnerChat.ChatId)
|
||||
: this.ImportOwner ?? this.fallbackMediaImportOwner;
|
||||
private ImportOwner EffectiveImportOwner => this.OwnerChat is not null
|
||||
? Tools.Imports.ImportOwner.ForChat(this.OwnerChat.ChatId)
|
||||
: this.ImportOwner ?? this.fallbackImportOwner;
|
||||
|
||||
private MediaImportTarget EffectiveMediaImportTarget => new(this.EffectiveImportOwner, string.IsNullOrWhiteSpace(this.Name) ? "attachments" : this.Name);
|
||||
private ImportTarget EffectiveImportTarget => new(this.EffectiveImportOwner, string.IsNullOrWhiteSpace(this.Name) ? "attachments" : this.Name);
|
||||
|
||||
private bool IsUnavailable => this.Disabled || this.isFileDialogOpen || this.MediaTranscriptionService.IsBusy(this.EffectiveImportOwner);
|
||||
|
||||
@@ -148,7 +149,7 @@ public partial class AttachDocuments : MSGComponentBase
|
||||
}
|
||||
|
||||
/// <summary>Refreshes disabled controls when the shared import lane changes.</summary>
|
||||
private void OnMediaImportStateChanged(MediaImportOwner owner)
|
||||
private void OnMediaImportStateChanged(ImportOwner owner)
|
||||
{
|
||||
if (owner == this.EffectiveImportOwner)
|
||||
this.InvokeAsync(async () =>
|
||||
@@ -194,7 +195,7 @@ public partial class AttachDocuments : MSGComponentBase
|
||||
/// <summary>Reattaches completed owner results after progress updates or navigation.</summary>
|
||||
private async Task SyncCompletedMediaAttachmentsAsync()
|
||||
{
|
||||
var delivery = this.MediaTranscriptionService.GetPendingDelivery(this.EffectiveMediaImportTarget);
|
||||
var delivery = this.MediaTranscriptionService.GetPendingDelivery(this.EffectiveImportTarget);
|
||||
// Owners that persist their own sources have already taken the media over when the batch
|
||||
// started, so re-adding the delivered transcripts here would duplicate them.
|
||||
var completed = this.EffectiveImportOwner.Kind.PersistsOwnSources
|
||||
@@ -463,7 +464,7 @@ public partial class AttachDocuments : MSGComponentBase
|
||||
await this.OnChange(this.DocumentPaths);
|
||||
}
|
||||
|
||||
this.MediaTranscriptionService.TryStartAttachmentBatch(mediaPaths, this.EffectiveMediaImportTarget, this.OwnerChat);
|
||||
this.MediaTranscriptionService.TryStartAttachmentBatch(mediaPaths, this.EffectiveImportTarget, this.OwnerChat);
|
||||
return attached;
|
||||
}
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
}
|
||||
</ChildContent>
|
||||
<FooterContent>
|
||||
<MediaTranscriptionStatus Owner="@this.CurrentMediaImportOwner"/>
|
||||
<MediaTranscriptionStatus Owner="@this.CurrentImportOwner"/>
|
||||
<MudElement Style="flex: 0 0 auto;">
|
||||
<MudTextField
|
||||
T="string"
|
||||
@@ -52,7 +52,7 @@
|
||||
Label="@this.InputLabel"
|
||||
Placeholder="@this.ProviderPlaceholder"
|
||||
Adornment="Adornment.End"
|
||||
AdornmentIcon="@(this.MediaTranscriptionService.IsBusy(this.CurrentMediaImportOwner) ? AppIcons.PENDING : AppIcons.SEND)"
|
||||
AdornmentIcon="@(this.MediaTranscriptionService.IsBusy(this.CurrentImportOwner) ? AppIcons.PENDING : AppIcons.SEND)"
|
||||
OnAdornmentClick="() => this.SendMessage()"
|
||||
Disabled="@this.IsInputForbidden()"
|
||||
Immediate="@true"
|
||||
|
||||
@@ -13,6 +13,7 @@ using AIStudio.Tools.Databases.ProvenanceStore;
|
||||
using AIStudio.Tools.ToolCallingSystem;
|
||||
using AIStudio.Tools.AIJobs;
|
||||
using AIStudio.Tools.AssistantLaunch;
|
||||
using AIStudio.Tools.Imports;
|
||||
using AIStudio.Tools.Media;
|
||||
using AIStudio.Tools.Services;
|
||||
|
||||
@@ -302,7 +303,7 @@ public partial class ChatComponent : MSGComponentBase
|
||||
this.currentCulture = CommonTools.DeriveActiveCultureOrInvariant(activeLanguagePlugin.IETFTag);
|
||||
}
|
||||
|
||||
private MediaImportOwner CurrentMediaImportOwner => MediaImportOwner.ForChat(this.ChatThread?.ChatId ?? this.draftMediaOwnerId);
|
||||
private ImportOwner CurrentImportOwner => ImportOwner.ForChat(this.ChatThread?.ChatId ?? this.draftMediaOwnerId);
|
||||
|
||||
// Unfortunately, we need the input field reference to blur the focus away. Without
|
||||
// this, we cannot clear the input field.
|
||||
@@ -531,9 +532,9 @@ public partial class ChatComponent : MSGComponentBase
|
||||
}
|
||||
|
||||
/// <summary>Refreshes send and attachment controls when the media import lane changes.</summary>
|
||||
private void OnMediaImportStateChanged(MediaImportOwner owner)
|
||||
private void OnMediaImportStateChanged(ImportOwner owner)
|
||||
{
|
||||
if (owner == this.CurrentMediaImportOwner)
|
||||
if (owner == this.CurrentImportOwner)
|
||||
this.InvokeAsync(async () =>
|
||||
{
|
||||
await this.ConsumeMediaOutcomeAsync();
|
||||
@@ -544,7 +545,7 @@ public partial class ChatComponent : MSGComponentBase
|
||||
/// <summary>Consumes a terminal media notification when its chat is visible.</summary>
|
||||
private async Task ConsumeMediaOutcomeAsync()
|
||||
{
|
||||
var outcome = this.MediaTranscriptionService.TryConsumeOutcome(this.CurrentMediaImportOwner);
|
||||
var outcome = this.MediaTranscriptionService.TryConsumeOutcome(this.CurrentImportOwner);
|
||||
if (outcome is null)
|
||||
return;
|
||||
|
||||
@@ -822,7 +823,7 @@ 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 bool CanThreadBeCopied => this.CanThreadBeSaved && !this.IsCurrentChatStreaming && !this.MediaTranscriptionService.IsBusy(this.CurrentImportOwner);
|
||||
|
||||
/// <summary>
|
||||
/// Whether the open chat can be compressed into a new chat.
|
||||
@@ -924,7 +925,7 @@ public partial class ChatComponent : MSGComponentBase
|
||||
/// Not while an answer is being written, just like the text of the message, and not while the
|
||||
/// audio or video files of the chat are being transcribed.
|
||||
/// </remarks>
|
||||
private bool CanAttachFiles => !this.IsCurrentChatStreaming && !this.MediaTranscriptionService.IsBusy(this.CurrentMediaImportOwner);
|
||||
private bool CanAttachFiles => !this.IsCurrentChatStreaming && !this.MediaTranscriptionService.IsBusy(this.CurrentImportOwner);
|
||||
|
||||
// The chat template locks the profile for good, an answer being written only until it is complete:
|
||||
private string ProfileDisabledText => this.currentChatTemplate.AllowProfileUsage
|
||||
@@ -943,7 +944,7 @@ public partial class ChatComponent : MSGComponentBase
|
||||
/// </remarks>
|
||||
private bool CanThreadBeMoved => this.ChatThread is not null
|
||||
&& !this.IsCurrentChatStreaming
|
||||
&& !this.MediaTranscriptionService.IsBusy(this.CurrentMediaImportOwner)
|
||||
&& !this.MediaTranscriptionService.IsBusy(this.CurrentImportOwner)
|
||||
&& WorkspaceBehaviour.IsChatExisting(new LoadChat(this.ChatThread.WorkspaceId, this.ChatThread.ChatId));
|
||||
|
||||
private bool HasSentFileAttachments => this.ChatThread?.HasSentFileAttachments() ?? false;
|
||||
@@ -1501,7 +1502,7 @@ public partial class ChatComponent : MSGComponentBase
|
||||
this.ComposerState.Clear();
|
||||
chat.WorkspaceId = await this.ResolveWorkspaceOfFirstThreadAsync();
|
||||
}
|
||||
else if (unstoredChatBeingLeft is not null && (!unstoredChatBeingLeft.Draft.IsEmpty || this.MediaTranscriptionService.IsBusy(MediaImportOwner.ForChat(unstoredChatBeingLeft.ChatId))))
|
||||
else if (unstoredChatBeingLeft is not null && (!unstoredChatBeingLeft.Draft.IsEmpty || this.MediaTranscriptionService.IsBusy(ImportOwner.ForChat(unstoredChatBeingLeft.ChatId))))
|
||||
{
|
||||
// Deleting the workspace took the chat along. Storing it would bring the workspace back, as an unnamed one:
|
||||
if (!WorkspaceBehaviour.IsWorkspaceExisting(unstoredChatBeingLeft.WorkspaceId))
|
||||
@@ -1724,7 +1725,7 @@ public partial class ChatComponent : MSGComponentBase
|
||||
if (this.IsCurrentChatStreaming || this.isCompressing)
|
||||
return;
|
||||
|
||||
if (this.MediaTranscriptionService.IsBusy(this.CurrentMediaImportOwner))
|
||||
if (this.MediaTranscriptionService.IsBusy(this.CurrentImportOwner))
|
||||
return;
|
||||
|
||||
await this.RefreshProviderSelectionFromConfigurationAsync();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
@inherits MudComponentBase
|
||||
|
||||
@* Bound by its value, the field checks itself only once touched. Bound by its text, it would check its first text, too, and show an issue as soon as it appears, e.g., when a switch shows it later: *@
|
||||
<MudTextField T="string" Disabled="@this.Disabled" Value="@this.text" ValueChanged="@this.OnTextChanged" Validation="@this.ValidationFunc" Label="@this.Label" Variant="Variant.Outlined" Lines="@this.Lines" MaxLines="@this.MaxLines" Sizing="@(this.MaxLines > this.Lines ? InputSizing.Auto : InputSizing.Fixed)" Margin="Margin.Dense" UserAttributes="@this.Attributes" HelperText="@this.HelpText" Placeholder="@this.Placeholder" Class="mb-3" Immediate="true" Adornment="Adornment.Start" AdornmentIcon="@this.Icon"/>
|
||||
<MudTextField T="string" Disabled="@this.Disabled" Value="@this.text" ValueChanged="@this.OnTextChanged" OnBlur="@this.OnBlur" Validation="@this.ValidationFunc" Label="@this.Label" Variant="Variant.Outlined" Lines="@this.Lines" MaxLines="@this.MaxLines" Sizing="@(this.MaxLines > this.Lines ? InputSizing.Auto : InputSizing.Fixed)" Margin="Margin.Dense" UserAttributes="@this.Attributes" HelperText="@this.HelpText" Placeholder="@this.Placeholder" Class="mb-3" Immediate="true" Adornment="Adornment.Start" AdornmentIcon="@this.Icon"/>
|
||||
@@ -1,4 +1,5 @@
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using Microsoft.AspNetCore.Components.Web;
|
||||
|
||||
using Timer = System.Timers.Timer;
|
||||
|
||||
@@ -64,14 +65,7 @@ public partial class DebouncedTextField : MudComponentBase, IDisposable
|
||||
this.debounceTimer.Elapsed += (_, _) =>
|
||||
{
|
||||
this.debounceTimer.Stop();
|
||||
this.InvokeAsync(async () =>
|
||||
{
|
||||
// The parent hands this text back with its next render, which is no change of its own, cf. OnParametersSetAsync:
|
||||
this.lastParameterText = this.text;
|
||||
await this.TextChanged.InvokeAsync(this.text);
|
||||
}).Observe($"{nameof(DebouncedTextField)}: notifying about changed text");
|
||||
this.InvokeAsync(async () => await this.WhenTextChangedAsync(this.text)).Observe($"{nameof(DebouncedTextField)}: handling changed text asynchronously");
|
||||
this.InvokeAsync(() => this.WhenTextCanged(this.text)).Observe($"{nameof(DebouncedTextField)}: handling changed text");
|
||||
this.HandOnText();
|
||||
};
|
||||
|
||||
this.isInitialized = true;
|
||||
@@ -117,6 +111,38 @@ public partial class DebouncedTextField : MudComponentBase, IDisposable
|
||||
this.debounceTimer.Start();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Hands a text which still waits for the debounce time on at once, as soon as the user leaves the field.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A click elsewhere, e.g., into the navigation, takes the focus first. So the parent gets the last characters
|
||||
/// typed before it goes away, e.g., an assistant which keeps its inputs as a draft when the user leaves it.
|
||||
/// Otherwise, they would be lost together with this field.
|
||||
/// </remarks>
|
||||
private void OnBlur(FocusEventArgs _)
|
||||
{
|
||||
if (!this.debounceTimer.Enabled)
|
||||
return;
|
||||
|
||||
this.debounceTimer.Stop();
|
||||
this.HandOnText();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Hands the text on to the parent and to the handlers of a changed text.
|
||||
/// </summary>
|
||||
private void HandOnText()
|
||||
{
|
||||
this.InvokeAsync(async () =>
|
||||
{
|
||||
// The parent hands this text back with its next render, which is no change of its own, cf. OnParametersSetAsync:
|
||||
this.lastParameterText = this.text;
|
||||
await this.TextChanged.InvokeAsync(this.text);
|
||||
}).Observe($"{nameof(DebouncedTextField)}: notifying about changed text");
|
||||
this.InvokeAsync(async () => await this.WhenTextChangedAsync(this.text)).Observe($"{nameof(DebouncedTextField)}: handling changed text asynchronously");
|
||||
this.InvokeAsync(() => this.WhenTextCanged(this.text)).Observe($"{nameof(DebouncedTextField)}: handling changed text");
|
||||
}
|
||||
|
||||
#region IDisposable
|
||||
|
||||
public void Dispose()
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
using AIStudio.Tools.Imports;
|
||||
using AIStudio.Tools.Media;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
|
||||
@@ -7,7 +8,7 @@ public partial class MediaTranscriptionStatus
|
||||
{
|
||||
/// <summary>The surface owner whose operation is rendered.</summary>
|
||||
[Parameter]
|
||||
public MediaImportOwner Owner { get; set; }
|
||||
public ImportOwner Owner { get; set; }
|
||||
|
||||
/// <summary>Optional target filter used by embedded file controls.</summary>
|
||||
[Parameter]
|
||||
@@ -58,7 +59,7 @@ public partial class MediaTranscriptionStatus
|
||||
}
|
||||
|
||||
/// <summary>Schedules a render after an import state transition.</summary>
|
||||
private void OnStateChanged(MediaImportOwner owner)
|
||||
private void OnStateChanged(ImportOwner owner)
|
||||
{
|
||||
if (owner == this.Owner)
|
||||
this.InvokeAsync(this.StateHasChanged).Observe($"{nameof(MediaTranscriptionStatus)}: rendering an import state transition");
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
using AIStudio.Dialogs;
|
||||
using AIStudio.Tools.Media;
|
||||
using AIStudio.Tools.Imports;
|
||||
using AIStudio.Tools.PluginSystem;
|
||||
using AIStudio.Tools.Services;
|
||||
|
||||
@@ -168,9 +168,9 @@ public partial class PluginDeleteAction : MSGComponentBase
|
||||
return await dialog.Result is { Canceled: false };
|
||||
}
|
||||
|
||||
private void OnMediaTranscriptionStateChanged(MediaImportOwner owner)
|
||||
private void OnMediaTranscriptionStateChanged(ImportOwner owner)
|
||||
{
|
||||
if (owner.Kind is MediaImportOwnerKind.ASSISTANT && owner.Id.EndsWith($":{this.Plugin.Id}", StringComparison.Ordinal))
|
||||
if (owner.Kind is ImportOwnerKind.ASSISTANT && owner.Id.EndsWith($":{this.Plugin.Id}", StringComparison.Ordinal))
|
||||
this.InvokeAsync(this.StateHasChanged).Observe($"{nameof(PluginDeleteAction)}: rendering a transcription state change");
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@
|
||||
|
||||
@if (this.IsCurrentTargetBusy)
|
||||
{
|
||||
<MediaTranscriptionStatus Owner="@this.EffectiveImportOwner" TargetId="@this.EffectiveMediaImportTarget.TargetId" Compact="true"/>
|
||||
<MediaTranscriptionStatus Owner="@this.EffectiveImportOwner" TargetId="@this.EffectiveImportTarget.TargetId" Compact="true"/>
|
||||
}
|
||||
else
|
||||
{
|
||||
@@ -57,6 +57,6 @@ else
|
||||
</MudButton>
|
||||
}
|
||||
|
||||
<MediaTranscriptionStatus Owner="@this.EffectiveImportOwner" TargetId="@this.EffectiveMediaImportTarget.TargetId" Compact="true"/>
|
||||
<MediaTranscriptionStatus Owner="@this.EffectiveImportOwner" TargetId="@this.EffectiveImportTarget.TargetId" Compact="true"/>
|
||||
</MudStack>
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
using AIStudio.Dialogs;
|
||||
using AIStudio.Tools.Imports;
|
||||
using AIStudio.Tools.Media;
|
||||
using AIStudio.Tools.Rust;
|
||||
using AIStudio.Tools.Services;
|
||||
@@ -10,13 +11,13 @@ namespace AIStudio.Components;
|
||||
|
||||
public partial class ReadFileContent : MSGComponentBase
|
||||
{
|
||||
private readonly MediaImportOwner fallbackMediaImportOwner = new(MediaImportOwnerKind.ASSISTANT, $"read-file-content:{Guid.NewGuid():N}");
|
||||
private readonly ImportOwner fallbackImportOwner = new(ImportOwnerKind.ASSISTANT, $"read-file-content:{Guid.NewGuid():N}");
|
||||
|
||||
[CascadingParameter]
|
||||
private MediaImportOwner? ImportOwner { get; set; }
|
||||
private ImportOwner? ImportOwner { get; set; }
|
||||
|
||||
[Parameter]
|
||||
public string MediaImportTargetId { get; set; } = string.Empty;
|
||||
public string ImportTargetId { get; set; } = string.Empty;
|
||||
|
||||
[Parameter]
|
||||
public string Text { get; set; } = string.Empty;
|
||||
@@ -85,17 +86,17 @@ public partial class ReadFileContent : MSGComponentBase
|
||||
private string loadedFileName = string.Empty;
|
||||
|
||||
private bool IsCurrentTargetBusy => this.MediaTranscriptionService.GetSnapshot(this.EffectiveImportOwner) is { IsBusy: true } snapshot
|
||||
&& snapshot.Target == this.EffectiveMediaImportTarget;
|
||||
&& snapshot.Target == this.EffectiveImportTarget;
|
||||
|
||||
private bool IsUnavailable => this.Disabled || this.isFileDialogOpen || this.MediaTranscriptionService.IsBusy(this.EffectiveImportOwner);
|
||||
|
||||
private MediaImportOwner EffectiveImportOwner => this.ImportOwner ?? this.fallbackMediaImportOwner;
|
||||
private ImportOwner EffectiveImportOwner => this.ImportOwner ?? this.fallbackImportOwner;
|
||||
|
||||
private string EffectiveMediaImportTargetId => string.IsNullOrWhiteSpace(this.MediaImportTargetId)
|
||||
private string EffectiveImportTargetId => string.IsNullOrWhiteSpace(this.ImportTargetId)
|
||||
? string.IsNullOrWhiteSpace(this.Text) ? "primary" : this.Text
|
||||
: this.MediaImportTargetId;
|
||||
: this.ImportTargetId;
|
||||
|
||||
private MediaImportTarget EffectiveMediaImportTarget => new(this.EffectiveImportOwner, this.EffectiveMediaImportTargetId);
|
||||
private ImportTarget EffectiveImportTarget => new(this.EffectiveImportOwner, this.EffectiveImportTargetId);
|
||||
|
||||
#region Overrides of MSGComponentBase
|
||||
|
||||
@@ -120,7 +121,7 @@ public partial class ReadFileContent : MSGComponentBase
|
||||
}
|
||||
|
||||
/// <summary>Refreshes disabled controls when the shared import lane changes.</summary>
|
||||
private void OnMediaImportStateChanged(MediaImportOwner owner)
|
||||
private void OnMediaImportStateChanged(ImportOwner owner)
|
||||
{
|
||||
if (owner == this.EffectiveImportOwner)
|
||||
this.InvokeAsync(async () =>
|
||||
@@ -167,12 +168,12 @@ public partial class ReadFileContent : MSGComponentBase
|
||||
/// <remarks>The transcript arrives filtered for prompt injections, cf. MediaTranscriptionService.</remarks>
|
||||
private async Task SyncCompletedMediaTextAsync()
|
||||
{
|
||||
var delivery = this.MediaTranscriptionService.GetPendingDelivery(this.EffectiveMediaImportTarget);
|
||||
var delivery = this.MediaTranscriptionService.GetPendingDelivery(this.EffectiveImportTarget);
|
||||
if (delivery is null || delivery.Text is not { } text)
|
||||
return;
|
||||
|
||||
var fileName = this.MediaTranscriptionService.GetSnapshot(this.EffectiveImportOwner) is { Target: var target } snapshot
|
||||
&& target == this.EffectiveMediaImportTarget
|
||||
&& target == this.EffectiveImportTarget
|
||||
? snapshot.CurrentFileName
|
||||
: string.Empty;
|
||||
await this.ApplyFileContentAsync(text, fileName);
|
||||
@@ -319,7 +320,7 @@ public partial class ReadFileContent : MSGComponentBase
|
||||
|
||||
return this.MediaTranscriptionService.TryStartTextImport(
|
||||
filePath,
|
||||
this.EffectiveMediaImportTarget);
|
||||
this.EffectiveImportTarget);
|
||||
}
|
||||
|
||||
private string FileLoadedTooltip()
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
@inherits MSGComponentBase
|
||||
<MudPaper Class="pa-3 mb-3 border-dashed border rounded-lg">
|
||||
<MudTextSwitch Label="@T("Read content from web?")" Disabled="@this.CleanerIsRunning" Value="@this.Preselect" ValueChanged="@this.ShowWebContentReaderChanged" LabelOn="@T("Show web content options")" LabelOff="@T("Hide web content options")" />
|
||||
<MudTextSwitch Label="@T("Read content from web?")" Disabled="@this.IsImporting" Value="@this.Preselect" ValueChanged="@this.ShowWebContentReaderChanged" LabelOn="@T("Show web content options")" LabelOff="@T("Hide web content options")" />
|
||||
@if (this.Preselect)
|
||||
{
|
||||
<MudTextSwitch Label="@T("Clean up the content with AI?")" Value="@this.PreselectContentCleaner" ValueChanged="@this.UseContentCleanerChanged" Disabled="@this.CleanerIsRunning" LabelOn="@T("The text content cleaner, an AI task, extracts the main content, tries to remove advertisements and other clutter, and tries to turn relative links into absolute ones, so that they work.")" LabelOff="@T("No content cleaning")" />
|
||||
<MudTextSwitch Label="@T("Clean up the content with AI?")" Value="@this.PreselectContentCleaner" ValueChanged="@this.UseContentCleanerChanged" Disabled="@this.IsImporting" LabelOn="@T("The text content cleaner, an AI task, extracts the main content, tries to remove advertisements and other clutter, and tries to turn relative links into absolute ones, so that they work.")" LabelOff="@T("No content cleaning")" />
|
||||
@if (this.ContentCleanerHint is { } contentCleanerHint)
|
||||
{
|
||||
<MudText Typo="Typo.body2" Color="Color.Error" Class="mb-3">
|
||||
@@ -11,14 +11,14 @@
|
||||
</MudText>
|
||||
}
|
||||
<MudStack Row="@true" AlignItems="@AlignItems.Baseline" Class="mb-3">
|
||||
<MudTextField T="string" Label="@T("URL from which to load the content")" Value="@this.URL" ValueChanged="@this.URLValueChanged" Validation="@this.ValidateURL" Adornment="Adornment.Start" AdornmentIcon="@AppIcons.LINK" Placeholder="https://..." HelperText="@TA("Loads the content from your URL. Does not work when the content is hidden behind a paywall.")" Variant="Variant.Outlined" Immediate="@true" Disabled="@this.CleanerIsRunning"/>
|
||||
<MudButton Disabled="@(!this.IsReady || this.CleanerIsRunning)" Variant="Variant.Filled" Size="Size.Large" Color="Color.Primary" StartIcon="@AppIcons.DOWNLOAD" OnClick="@this.LoadFromWeb">
|
||||
<MudTextField T="string" Label="@T("URL from which to load the content")" Value="@this.URL" ValueChanged="@this.URLValueChanged" Validation="@this.ValidateURL" Adornment="Adornment.Start" AdornmentIcon="@AppIcons.LINK" Placeholder="https://..." HelperText="@TA("Loads the content from your URL. Does not work when the content is hidden behind a paywall.")" Variant="Variant.Outlined" Immediate="@true" Disabled="@this.IsImporting"/>
|
||||
<MudButton Disabled="@(!this.IsReady || this.IsImporting)"Variant="Variant.Filled" Size="Size.Large" Color="Color.Primary" StartIcon="@AppIcons.DOWNLOAD" OnClick="@this.LoadFromWeb">
|
||||
@T("Fetch")
|
||||
</MudButton>
|
||||
</MudStack>
|
||||
@if (this.CleanerIsRunning)
|
||||
@if (this.IsImporting)
|
||||
{
|
||||
<ProcessComponent T="ReadWebContentSteps" StepValue="@this.processStep" ShowProgressAnimation="@true"/>
|
||||
<ProcessComponent T="ReadWebContentSteps" StepValue="@this.ProcessStep" ShowProgressAnimation="@true"/>
|
||||
}
|
||||
}
|
||||
</MudPaper>
|
||||
@@ -1,39 +1,48 @@
|
||||
using AIStudio.AIOperations;
|
||||
using AIStudio.AIOperations.TextContentCleaning;
|
||||
using AIStudio.Provider;
|
||||
using AIStudio.Settings;
|
||||
using AIStudio.Tools.Security;
|
||||
using AIStudio.Tools.Imports;
|
||||
using AIStudio.Tools.Web;
|
||||
|
||||
using Microsoft.AspNetCore.Components;
|
||||
|
||||
namespace AIStudio.Components;
|
||||
|
||||
/// <summary>
|
||||
/// Loads the content of a web page into a text field of an assistant.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The loading itself runs in WebContentImportService, so that it goes on while the user is elsewhere: this
|
||||
/// reader goes away together with its assistant. The reader starts the import, shows its progress, and takes
|
||||
/// its result, also when it is new and the import ran while the user was away.
|
||||
/// </remarks>
|
||||
public partial class ReadWebContent : MSGComponentBase
|
||||
{
|
||||
/// <summary>
|
||||
/// How long loading one page may take.
|
||||
/// The owner of the imports of a reader outside an assistant, which cascades no owner.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The user is watching a progress indicator while this runs, so it is shorter than what the
|
||||
/// tools allow themselves for a page fetched in the background.
|
||||
/// </remarks>
|
||||
private const int TIMEOUT_SECONDS = 60;
|
||||
private readonly ImportOwner fallbackImportOwner = new(ImportOwnerKind.ASSISTANT, $"read-web-content:{Guid.NewGuid():N}");
|
||||
|
||||
[Inject]
|
||||
private WebPageRetrievalService WebPageRetrievalService { get; init; } = null!;
|
||||
|
||||
[Inject]
|
||||
private ILogger<ReadWebContent> Logger { get; init; } = null!;
|
||||
|
||||
[Inject]
|
||||
private TextContentCleaningOperation TextContentCleaning { get; init; } = null!;
|
||||
private WebContentImportService WebContentImportService { get; init; } = null!;
|
||||
|
||||
[Inject]
|
||||
private AIOperationProviderResolver ProviderResolver { get; init; } = null!;
|
||||
|
||||
[Inject]
|
||||
private PromptInjectionGuardService PromptInjectionGuardService { get; init; } = null!;
|
||||
/// <summary>
|
||||
/// The assistant around this reader, which owns its imports.
|
||||
/// </summary>
|
||||
[CascadingParameter]
|
||||
private ImportOwner? ImportOwner { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Tells the readers of one assistant apart, e.g., by the name of the component of an assistant plugin.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// An assistant with a single reader keeps the default.
|
||||
/// </remarks>
|
||||
[Parameter]
|
||||
public string ImportTargetId { get; set; } = "primary";
|
||||
|
||||
[Parameter]
|
||||
public string Content { get; set; } = string.Empty;
|
||||
@@ -76,7 +85,6 @@ public partial class ReadWebContent : MSGComponentBase
|
||||
public EventCallback<bool> PreselectContentCleanerChanged { get; set; }
|
||||
|
||||
private readonly Process<ReadWebContentSteps> process = Process<ReadWebContentSteps>.INSTANCE;
|
||||
private ProcessStepValue processStep;
|
||||
|
||||
/// <summary>
|
||||
/// The model the content cleaner would run with, and why others were not chosen.
|
||||
@@ -93,10 +101,12 @@ public partial class ReadWebContent : MSGComponentBase
|
||||
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
this.WebContentImportService.StateChanged += this.OnImportStateChanged;
|
||||
this.ApplyFilters([], [ Event.CONFIGURATION_CHANGED ]);
|
||||
this.ResolveProvider();
|
||||
|
||||
await base.OnInitializedAsync();
|
||||
await this.SyncWithImportAsync();
|
||||
}
|
||||
|
||||
protected override async Task OnParametersSetAsync()
|
||||
@@ -125,6 +135,15 @@ public partial class ReadWebContent : MSGComponentBase
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stops following the imports. An import keeps running, and its result waits for the next reader of this field.
|
||||
/// </summary>
|
||||
protected override void DisposeResources()
|
||||
{
|
||||
this.WebContentImportService.StateChanged -= this.OnImportStateChanged;
|
||||
base.DisposeResources();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
@@ -135,106 +154,130 @@ public partial class ReadWebContent : MSGComponentBase
|
||||
/// parameter, and a parameter arrives whenever the parent renders. Resolving only once would
|
||||
/// leave the cleaner with whatever was set the first time this component was built.
|
||||
/// </remarks>
|
||||
private void ResolveProvider() => this.cleanerChoice = this.ProviderResolver.Preview(TextContentCleaningOperation.GetProviderSettings(this.SettingsManager), ConfidenceLevel.NONE, GetCleanerProviderOptions(this.SettingsManager, this.ProviderSettings));
|
||||
private void ResolveProvider() => this.cleanerChoice = this.ProviderResolver.Preview(TextContentCleaningOperation.GetProviderSettings(this.SettingsManager), ConfidenceLevel.NONE, WebContentImportService.GetCleanerProviderOptions(this.SettingsManager, this.ProviderSettings));
|
||||
|
||||
private ImportOwner EffectiveImportOwner => this.ImportOwner ?? this.fallbackImportOwner;
|
||||
|
||||
private ImportTarget EffectiveImportTarget => new(this.EffectiveImportOwner, this.ImportTargetId);
|
||||
|
||||
/// <summary>
|
||||
/// What the reader adds to the choice of the provider for the content cleaner.
|
||||
/// The import which fills this field, while it runs.
|
||||
/// </summary>
|
||||
private WebContentImportSnapshot? CurrentImport => this.WebContentImportService.GetSnapshot(this.EffectiveImportTarget);
|
||||
|
||||
/// <summary>
|
||||
/// Whether the content of this field is being loaded. The controls of the reader wait for the whole import,
|
||||
/// from loading the page to cleaning it.
|
||||
/// </summary>
|
||||
private bool IsImporting => this.CurrentImport is not null;
|
||||
|
||||
private ProcessStepValue ProcessStep => this.process[this.CurrentImport?.Step ?? ReadWebContentSteps.START];
|
||||
|
||||
private void LoadFromWeb()
|
||||
{
|
||||
if(!this.IsReady || this.IsImporting)
|
||||
return;
|
||||
|
||||
this.WebContentImportService.TryStart(this.EffectiveImportTarget, new(this.URL, this.PreselectContentCleaner, this.ProviderSettings));
|
||||
}
|
||||
|
||||
private void OnImportStateChanged(ImportOwner owner)
|
||||
{
|
||||
if (owner == this.EffectiveImportOwner)
|
||||
this.InvokeAsync(async () =>
|
||||
{
|
||||
await this.SyncWithImportAsync();
|
||||
this.StateHasChanged();
|
||||
}).Observe($"{nameof(ReadWebContent)}: following the web content import");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes over what the import of this field reached: its options while it runs, its result once it ended, and
|
||||
/// whether it cleans.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Without a model of its own, the cleaner falls back on the model of the assistant, and then on
|
||||
/// the app-wide default. Its minimum confidence applies to both of them: a model somebody picked
|
||||
/// for the assistant has to clear the bar of the cleaner before the cleaner uses it.
|
||||
/// This runs when the reader starts, too: the user may have left the assistant while the import ran. The
|
||||
/// assistant restores its draft in OnInitializedAsync, before its first render creates this reader, so the
|
||||
/// result lands on the draft and not under it, as the transcripts of ReadFileContent do. The assistant hears
|
||||
/// about the cleaning only, as before, e.g., to lock its input field while the cleaner prepares the text
|
||||
/// which replaces it.
|
||||
/// </remarks>
|
||||
/// <param name="settingsManager">The settings, for the app-wide default.</param>
|
||||
/// <param name="assistantProvider">The model of the assistant around the reader.</param>
|
||||
/// <returns>The options for the provider resolver.</returns>
|
||||
internal static AIOperationProviderOptions GetCleanerProviderOptions(SettingsManager settingsManager, AIStudio.Settings.Provider assistantProvider) => new()
|
||||
private async Task SyncWithImportAsync()
|
||||
{
|
||||
FallbackProviderIds = [assistantProvider.Id, settingsManager.AppDefaultProviderId],
|
||||
OwnMinimumConfidenceAppliesToFallbacks = true,
|
||||
};
|
||||
var result = this.WebContentImportService.TryTakeResult(this.EffectiveImportTarget);
|
||||
var currentImport = this.CurrentImport;
|
||||
if (currentImport is not null)
|
||||
await this.ShowRunningImportAsync(currentImport);
|
||||
|
||||
private async Task LoadFromWeb()
|
||||
{
|
||||
if(!this.IsReady)
|
||||
return;
|
||||
|
||||
var markdown = string.Empty;
|
||||
try
|
||||
var isCleaning = currentImport?.Step is ReadWebContentSteps.CLEANING;
|
||||
if (isCleaning != this.CleanerIsRunning)
|
||||
{
|
||||
this.processStep = this.process[ReadWebContentSteps.LOADING];
|
||||
this.StateHasChanged();
|
||||
|
||||
//
|
||||
// The same retrieval the read web page tool uses, so a page is fetched and read one
|
||||
// way throughout AI Studio. The difference is the target policy: here the user typed
|
||||
// the URL, so their own network is not off limits.
|
||||
//
|
||||
var retrievedPage = await this.WebPageRetrievalService.RetrieveAsync(
|
||||
new Uri(this.URL),
|
||||
new WebPageRetrievalOptions
|
||||
{
|
||||
TimeoutSeconds = TIMEOUT_SECONDS,
|
||||
TargetChosenByUser = true,
|
||||
});
|
||||
|
||||
this.processStep = this.process[ReadWebContentSteps.PARSING];
|
||||
this.StateHasChanged();
|
||||
markdown = retrievedPage.ExtractedPage.Markdown;
|
||||
markdown = await this.PromptInjectionGuardService.SanitizeAsync(markdown, PromptInjectionSource.WebContent(this.URL));
|
||||
|
||||
if (this.PreselectContentCleaner)
|
||||
{
|
||||
var request = new TextContentCleaningRequest(markdown, this.URL);
|
||||
var choice = this.ProviderResolver.Resolve(this.TextContentCleaning, request, TextContentCleaningOperation.GetProviderSettings(this.SettingsManager), GetCleanerProviderOptions(this.SettingsManager, this.ProviderSettings));
|
||||
if (!choice.HasProvider)
|
||||
{
|
||||
//
|
||||
// Say that the cleaning did not happen. The user asked for it, the page arrives,
|
||||
// and without a word they would take the raw markdown -- navigation, cookie banner
|
||||
// and advertising included -- for the cleaned result.
|
||||
//
|
||||
await this.MessageBus.SendError(new(AppIcons.AI_OPERATION, T("The content was loaded, but not cleaned: no model is available for the content cleaner.")));
|
||||
}
|
||||
else
|
||||
{
|
||||
this.processStep = this.process[ReadWebContentSteps.CLEANING];
|
||||
this.CleanerIsRunning = true;
|
||||
await this.CleanerIsRunningChanged.InvokeAsync(this.CleanerIsRunning);
|
||||
this.StateHasChanged();
|
||||
|
||||
var result = await this.TextContentCleaning.RunAsync(request, new(choice.Provider));
|
||||
markdown = result.Markdown;
|
||||
if (!result.IsCleaned)
|
||||
await this.MessageBus.SendWarning(new(AppIcons.AI_OPERATION, T("The content was loaded, but not cleaned: the model of the content cleaner gave no answer.")));
|
||||
|
||||
this.processStep = this.process[ReadWebContentSteps.DONE];
|
||||
this.CleanerIsRunning = false;
|
||||
await this.CleanerIsRunningChanged.InvokeAsync(this.CleanerIsRunning);
|
||||
this.StateHasChanged();
|
||||
}
|
||||
}
|
||||
this.CleanerIsRunning = isCleaning;
|
||||
await this.CleanerIsRunningChanged.InvokeAsync(this.CleanerIsRunning);
|
||||
}
|
||||
catch (Exception exception)
|
||||
|
||||
if (result is not null)
|
||||
await this.ApplyResultAsync(result);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Shows the options with which the import of this field runs: the reader expanded, the address it loads,
|
||||
/// and whether it cleans the page.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// An assistant which starts anew when the user comes back, see AssistantInputsWhenLeaving.DISCARD_INPUTS,
|
||||
/// holds its preselected values instead. The reader would then stay collapsed, with its switch locked and
|
||||
/// the progress of the import hidden. The options belong to the assistant, so they go there as well.
|
||||
/// </remarks>
|
||||
private async Task ShowRunningImportAsync(WebContentImportSnapshot import)
|
||||
{
|
||||
if (!this.Preselect)
|
||||
{
|
||||
if (this.CleanerIsRunning)
|
||||
{
|
||||
this.processStep = this.process[ReadWebContentSteps.START];
|
||||
this.CleanerIsRunning = false;
|
||||
await this.CleanerIsRunningChanged.InvokeAsync(this.CleanerIsRunning);
|
||||
this.StateHasChanged();
|
||||
}
|
||||
this.Preselect = true;
|
||||
await this.PreselectChanged.InvokeAsync(this.Preselect);
|
||||
}
|
||||
|
||||
if (this.URL != import.Url)
|
||||
{
|
||||
this.URL = import.Url;
|
||||
await this.URLChanged.InvokeAsync(this.URL);
|
||||
}
|
||||
|
||||
if (this.PreselectContentCleaner != import.CleanContent)
|
||||
{
|
||||
this.PreselectContentCleaner = import.CleanContent;
|
||||
await this.PreselectContentCleanerChanged.InvokeAsync(this.PreselectContentCleaner);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ApplyResultAsync(WebContentImportResult result)
|
||||
{
|
||||
switch (result.Issue)
|
||||
{
|
||||
//
|
||||
// Say that the cleaning did not happen. The user asked for it, the page arrives,
|
||||
// and without a word they would take the raw markdown -- navigation, cookie banner
|
||||
// and advertising included -- for the cleaned result.
|
||||
//
|
||||
case WebContentImportIssue.NOT_CLEANED_NO_MODEL:
|
||||
await this.MessageBus.SendError(new(AppIcons.AI_OPERATION, T("The content was loaded, but not cleaned: no model is available for the content cleaner.")));
|
||||
break;
|
||||
|
||||
case WebContentImportIssue.NOT_CLEANED_NO_ANSWER:
|
||||
await this.MessageBus.SendWarning(new(AppIcons.AI_OPERATION, T("The content was loaded, but not cleaned: the model of the content cleaner gave no answer.")));
|
||||
break;
|
||||
|
||||
//
|
||||
// Say why nothing was loaded. An empty text field looks like a page without content,
|
||||
// and the reasons a page cannot be read are things the user can act on: a link to a
|
||||
// PDF rather than a page, a host that does not answer, a server refusing the request.
|
||||
//
|
||||
this.Logger.LogWarning(exception, "Could not load the web content from '{ProvidedUrl}'.", this.URL);
|
||||
await this.MessageBus.SendError(new(AppIcons.PROVIDER_ERROR, string.Format(this.T("The content of '{0}' could not be loaded: {1}"), this.URL, exception.Message)));
|
||||
case WebContentImportIssue.LOAD_FAILED:
|
||||
await this.MessageBus.SendError(new(AppIcons.PROVIDER_ERROR, string.Format(T("The content of '{0}' could not be loaded: {1}"), result.Url, result.ErrorMessage)));
|
||||
break;
|
||||
}
|
||||
|
||||
this.Content = markdown;
|
||||
this.Content = result.Markdown;
|
||||
await this.ContentChanged.InvokeAsync(this.Content);
|
||||
}
|
||||
|
||||
|
||||
@@ -5,6 +5,7 @@ using AIStudio.Chat;
|
||||
using AIStudio.Dialogs;
|
||||
using AIStudio.Settings.DataModel;
|
||||
using AIStudio.Tools.AIJobs;
|
||||
using AIStudio.Tools.Imports;
|
||||
using AIStudio.Tools.Media;
|
||||
using AIStudio.Tools.Services;
|
||||
|
||||
@@ -403,11 +404,11 @@ public partial class Workspaces : MSGComponentBase
|
||||
/// Whether an answer is being written for the given chat, or a transcript is being made for it.
|
||||
/// </summary>
|
||||
/// <param name="chatId">The chat to check.</param>
|
||||
private bool IsChatBusy(Guid chatId) => this.AIJobService.IsChatGenerationActive(chatId) || this.MediaTranscriptionService.IsBusy(MediaImportOwner.ForChat(chatId));
|
||||
private bool IsChatBusy(Guid chatId) => this.AIJobService.IsChatGenerationActive(chatId) || this.MediaTranscriptionService.IsBusy(ImportOwner.ForChat(chatId));
|
||||
|
||||
private string GetChatTreeItemTextStyle(TreeItemData treeItem)
|
||||
{
|
||||
var status = this.MediaTranscriptionService.GetSnapshot(MediaImportOwner.ForChat(treeItem.ChatId))?.Status;
|
||||
var status = this.MediaTranscriptionService.GetSnapshot(ImportOwner.ForChat(treeItem.ChatId))?.Status;
|
||||
var color = status switch
|
||||
{
|
||||
MediaImportStatus.QUEUED or MediaImportStatus.RUNNING or MediaImportStatus.CANCELING => " color: var(--mud-palette-info);",
|
||||
@@ -432,7 +433,7 @@ public partial class Workspaces : MSGComponentBase
|
||||
|
||||
private string GetChatTreeIcon(Guid chatId, string defaultIcon)
|
||||
{
|
||||
var mediaStatus = this.MediaTranscriptionService.GetSnapshot(MediaImportOwner.ForChat(chatId))?.Status;
|
||||
var mediaStatus = this.MediaTranscriptionService.GetSnapshot(ImportOwner.ForChat(chatId))?.Status;
|
||||
if (mediaStatus is not null)
|
||||
{
|
||||
return mediaStatus switch
|
||||
@@ -464,13 +465,13 @@ public partial class Workspaces : MSGComponentBase
|
||||
/// Colors the icon of a chat red when its media transcription failed, like every other error icon.
|
||||
/// </summary>
|
||||
/// <param name="treeItem">The chat in the tree.</param>
|
||||
private Color GetChatTreeIconColor(TreeItemData treeItem) => this.MediaTranscriptionService.GetSnapshot(MediaImportOwner.ForChat(treeItem.ChatId))?.Status is MediaImportStatus.FAILED
|
||||
private Color GetChatTreeIconColor(TreeItemData treeItem) => this.MediaTranscriptionService.GetSnapshot(ImportOwner.ForChat(treeItem.ChatId))?.Status is MediaImportStatus.FAILED
|
||||
? Color.Error
|
||||
: Color.Default;
|
||||
|
||||
private void OnMediaImportStateChanged(MediaImportOwner owner)
|
||||
private void OnMediaImportStateChanged(ImportOwner owner)
|
||||
{
|
||||
if (owner.Kind is MediaImportOwnerKind.CHAT)
|
||||
if (owner.Kind is ImportOwnerKind.CHAT)
|
||||
this.SafeStateHasChanged().Observe($"{nameof(Workspaces)}: rendering a media import change");
|
||||
}
|
||||
|
||||
@@ -788,7 +789,7 @@ public partial class Workspaces : MSGComponentBase
|
||||
// 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);
|
||||
var mediaOwner = ImportOwner.ForChat(chat.ChatId);
|
||||
if (this.AIJobService.IsChatGenerationActive(chat.ChatId) || this.MediaTranscriptionService.IsBusy(mediaOwner))
|
||||
return false;
|
||||
|
||||
@@ -859,7 +860,7 @@ public partial class Workspaces : MSGComponentBase
|
||||
if (chat is null)
|
||||
return;
|
||||
|
||||
var mediaOwner = MediaImportOwner.ForChat(chat.ChatId);
|
||||
var mediaOwner = ImportOwner.ForChat(chat.ChatId);
|
||||
if (this.AIJobService.IsChatGenerationActive(chat.ChatId) || this.MediaTranscriptionService.IsBusy(mediaOwner))
|
||||
return;
|
||||
|
||||
@@ -996,7 +997,7 @@ public partial class Workspaces : MSGComponentBase
|
||||
}
|
||||
|
||||
foreach (var chatId in chatIds)
|
||||
this.MediaTranscriptionService.ClearOwnerState(MediaImportOwner.ForChat(chatId));
|
||||
this.MediaTranscriptionService.ClearOwnerState(ImportOwner.ForChat(chatId));
|
||||
|
||||
await this.LoadTreeItemsAsync(startPrefetch: false);
|
||||
|
||||
|
||||
Reference in new issue
Block a user