From 7e2f83b19b664ba631b1ecd07700575f669e6ffc Mon Sep 17 00:00:00 2001 From: Peer Hogeterp Date: Sat, 28 Nov 2026 11:52:17 +0100 Subject: [PATCH] Kept the inputs of assistants when you leave them (#1209) Co-authored-by: Thorsten Sommer --- .../Assistants/AssistantBase.razor | 6 +- .../Assistants/AssistantBase.razor.cs | 128 ++++++++- .../Assistants/AssistantLowerBase.cs | 32 ++- .../AssistantBatchProcessing.razor.Session.cs | 2 +- .../Builder/AssistantBuilder.razor.cs | 10 +- .../DocumentAnalysisAssistant.razor.cs | 68 +++++ .../Assistants/Dynamic/AssistantDynamic.razor | 3 +- .../Dynamic/AssistantDynamic.razor.cs | 46 +++- .../Assistants/Dynamic/FileAttachmentState.cs | 13 + .../Assistants/Dynamic/FileContentState.cs | 13 + .../Assistants/Dynamic/WebContentState.cs | 26 ++ .../Assistants/ERI/AssistantERI.razor.cs | 26 +- .../Assistants/I18N/AssistantI18N.razor.cs | 2 +- .../Assistants/I18N/allTexts.lua | 18 ++ .../LegalCheck/AssistantLegalCheck.razor.cs | 2 +- .../AssistantModelComparison.razor.cs | 2 +- .../AssistantPromptOptimizer.razor.cs | 2 +- .../SWOTAnalysis/AssistantSWOTAnalysis.razor | 6 +- .../AssistantSWOTAnalysis.razor.cs | 8 +- .../AssistantTextSummarizer.razor.cs | 2 +- .../Translation/AssistantTranslation.razor.cs | 2 +- .../VisualBriefingAssistant.razor | 4 +- .../VisualBriefingAssistant.razor.Projects.cs | 4 +- .../VisualBriefingAssistant.razor.Sources.cs | 15 +- .../VisualBriefingTranscriptStorage.cs | 7 +- .../Components/AssistantBlock.razor.cs | 52 +++- .../Components/AttachDocuments.razor | 4 +- .../Components/AttachDocuments.razor.cs | 19 +- .../Components/ChatComponent.razor | 4 +- .../Components/ChatComponent.razor.cs | 19 +- .../Components/DebouncedTextField.razor | 2 +- .../Components/DebouncedTextField.razor.cs | 42 ++- .../MediaTranscriptionStatus.razor.cs | 5 +- .../Components/PluginDeleteAction.razor.cs | 6 +- .../Components/ReadFileContent.razor | 4 +- .../Components/ReadFileContent.razor.cs | 25 +- .../Components/ReadWebContent.razor | 12 +- .../Components/ReadWebContent.razor.cs | 243 ++++++++++------- .../Components/Workspaces.razor.cs | 19 +- .../SettingsDialogAssistantsPage.razor | 1 + .../SettingsDialogAssistantsPage.razor.cs | 4 +- .../Layout/MainLayout.razor.cs | 27 +- .../Plugins/configuration/plugin.lua | 11 + .../plugin.lua | 18 ++ .../plugin.lua | 18 ++ app/MindWork AI Studio/Program.cs | 1 + .../ConfigurationSelectDataFactory.cs | 6 + .../DataModel/AssistantInputsWhenLeaving.cs | 18 ++ .../Settings/DataModel/DataAssistantsPage.cs | 17 +- .../AssistantSessionService.cs | 56 +++- .../AssistantSessionSnapshotField.cs | 11 +- .../AssistantSessionStateKey.cs | 28 +- .../AssistantSessionStateReader.cs | 18 +- .../AssistantSessionStateWriter.cs | 2 +- .../IAssistantSessionSnapshotField.cs | 10 + .../IAssistantSessionValue.cs | 20 ++ .../Tools/ComponentsExtensions.cs | 12 +- .../Tools/Imports/ImportOwner.cs | 18 ++ .../ImportOwnerKind.cs} | 8 +- .../ImportOwnerKindExtensions.cs} | 12 +- .../Tools/Imports/ImportTarget.cs | 4 + .../Tools/Media/IMediaTranscriptStorage.cs | 11 +- .../Tools/Media/MediaImportDelivery.cs | 3 +- .../Tools/Media/MediaImportOutcome.cs | 4 +- .../Tools/Media/MediaImportOwner.cs | 18 -- .../Tools/Media/MediaImportSnapshot.cs | 6 +- .../Tools/Media/MediaImportTarget.cs | 4 - .../Assistants/DataModel/AssistantState.cs | 67 ++++- .../Tools/PluginSystem/PluginConfiguration.cs | 3 + .../Services/MediaTranscriptionService.cs | 55 ++-- .../Services/PluginInstallService.Delete.cs | 4 +- .../Tools/Web/WebContentImportIssue.cs | 27 ++ .../Tools/Web/WebContentImportRequest.cs | 9 + .../Tools/Web/WebContentImportResult.cs | 10 + .../Tools/Web/WebContentImportService.cs | 255 +++++++++++++++++ .../Tools/Web/WebContentImportSnapshot.cs | 13 + .../wwwroot/changelog/v26.11.2.md | 5 + .../TextContentCleaningProviderTests.cs | 2 +- .../AssistantCategoryPageSettingsTests.cs | 1 + .../AssistantPluginDraftTests.cs | 122 +++++++++ .../AssistantSessionDraftTests.cs | 256 ++++++++++++++++++ .../Media/TranscriptPromptInjectionTests.cs | 3 +- .../Tools/Web/WebContentImportServiceTests.cs | 170 ++++++++++++ 83 files changed, 1924 insertions(+), 347 deletions(-) create mode 100644 app/MindWork AI Studio/Settings/DataModel/AssistantInputsWhenLeaving.cs create mode 100644 app/MindWork AI Studio/Tools/AssistantSessions/IAssistantSessionValue.cs create mode 100644 app/MindWork AI Studio/Tools/Imports/ImportOwner.cs rename app/MindWork AI Studio/Tools/{Media/MediaImportOwnerKind.cs => Imports/ImportOwnerKind.cs} (74%) rename app/MindWork AI Studio/Tools/{Media/MediaImportOwnerKindExtensions.cs => Imports/ImportOwnerKindExtensions.cs} (65%) create mode 100644 app/MindWork AI Studio/Tools/Imports/ImportTarget.cs delete mode 100644 app/MindWork AI Studio/Tools/Media/MediaImportOwner.cs delete mode 100644 app/MindWork AI Studio/Tools/Media/MediaImportTarget.cs create mode 100644 app/MindWork AI Studio/Tools/Web/WebContentImportIssue.cs create mode 100644 app/MindWork AI Studio/Tools/Web/WebContentImportRequest.cs create mode 100644 app/MindWork AI Studio/Tools/Web/WebContentImportResult.cs create mode 100644 app/MindWork AI Studio/Tools/Web/WebContentImportService.cs create mode 100644 app/MindWork AI Studio/Tools/Web/WebContentImportSnapshot.cs create mode 100644 app/Tests/Tools/AssistantSessions/AssistantPluginDraftTests.cs create mode 100644 app/Tests/Tools/AssistantSessions/AssistantSessionDraftTests.cs create mode 100644 app/Tests/Tools/Web/WebContentImportServiceTests.cs diff --git a/app/MindWork AI Studio/Assistants/AssistantBase.razor b/app/MindWork AI Studio/Assistants/AssistantBase.razor index 57d58c532..ee2346711 100644 --- a/app/MindWork AI Studio/Assistants/AssistantBase.razor +++ b/app/MindWork AI Studio/Assistants/AssistantBase.razor @@ -33,7 +33,7 @@ @if (this.Body is not null) { - + @this.Body @@ -42,7 +42,7 @@ - + @this.SubmitText @if (this.IsProcessing) @@ -181,7 +181,7 @@ @if (this.ShowReset) { - + @TB("Reset") } diff --git a/app/MindWork AI Studio/Assistants/AssistantBase.razor.cs b/app/MindWork AI Studio/Assistants/AssistantBase.razor.cs index 3834fe27f..99f9476d7 100644 --- a/app/MindWork AI Studio/Assistants/AssistantBase.razor.cs +++ b/app/MindWork AI Studio/Assistants/AssistantBase.razor.cs @@ -8,9 +8,11 @@ using AIStudio.Dialogs.Settings; using AIStudio.Tools.AIJobs; using AIStudio.Tools.AssistantLaunch; using AIStudio.Tools.AssistantSessions; +using AIStudio.Tools.Imports; using AIStudio.Tools.Media; using AIStudio.Tools.Services; using AIStudio.Tools.ToolCallingSystem; +using AIStudio.Tools.Web; using Microsoft.AspNetCore.Components; @@ -65,7 +67,13 @@ public abstract partial class AssistantBase : AssistantLowerBase wher [Inject] protected MediaTranscriptionService MediaTranscriptionService { get; init; } = null!; - + + /// + /// Loads web content for the web content readers of this assistant, also while the user is elsewhere. + /// + [Inject] + private WebContentImportService WebContentImportService { get; init; } = null!; + protected abstract string Title { get; } protected abstract string Description { get; } @@ -266,7 +274,7 @@ public abstract partial class AssistantBase : AssistantLowerBase wher protected CancellationTokenSource? CancellationTokenSource; private bool isDisposed; private AssistantSessionKey assistantSessionKey; - private MediaImportOwner CurrentMediaImportOwner => MediaImportOwner.ForAssistant(this.assistantSessionKey); + private ImportOwner CurrentImportOwner => ImportOwner.ForAssistant(this.assistantSessionKey); private Guid? assistantSessionId; /// @@ -285,6 +293,21 @@ public abstract partial class AssistantBase : AssistantLowerBase wher private AssistantSessionSnapshot? pendingRenderedAssistantSessionSnapshot; private AssistantSessionSnapshot? lastAttachedAssistantSessionSnapshot; + /// + /// What this assistant holds once its defaults are applied, before the user changed anything; null until + /// then, e.g., for a hidden assistant which sends the user to the overview instead. + /// + /// + /// When the user leaves the assistant, it stores a draft only if its state differs from this one, see + /// SaveDraftIfChanged. A reset makes the state after the reset the new one. + /// + private Dictionary? stateWithDefaults; + + /// + /// Whether this assistant holds a text sent to it, which it keeps in a draft even when the user changed nothing else. + /// + private bool holdsSentText; + /// /// Gets whether the Blazor component instance has already been disposed. /// @@ -296,7 +319,7 @@ public abstract partial class AssistantBase : AssistantLowerBase wher protected bool HasAssistantSession => this.assistantSessionId is not null; /// Gets whether this assistant currently owns active media work. - protected bool IsMediaImportBusy => this.MediaTranscriptionService.IsBusy(this.CurrentMediaImportOwner); + protected bool IsMediaImportBusy => this.MediaTranscriptionService.IsBusy(this.CurrentImportOwner); /// /// Gets the assistant-specific identifier used to distinguish session slots. @@ -312,6 +335,7 @@ public abstract partial class AssistantBase : AssistantLowerBase wher { this.transferredRestrictions = textLaunchPayload.Restrictions; this.ApplyTextLaunchPayload(textLaunchPayload); + this.holdsSentText = true; } this.MediaTranscriptionService.StateChanged += this.OnMediaImportStateChanged; @@ -343,6 +367,7 @@ public abstract partial class AssistantBase : AssistantLowerBase wher this.SelectedToolIds = this.ToolRegistry.GetDefaultToolIds(this.Component); await this.OnDefaultsAppliedAsync(); this.assistantSessionKey = new(this.Component, this.AssistantSessionInstanceId); + this.stateWithDefaults = this.CaptureAssistantSessionState(); await this.AttachAssistantSessionIfAvailable(); await this.ConsumeMediaOutcomeAsync(); } @@ -412,7 +437,7 @@ public abstract partial class AssistantBase : AssistantLowerBase wher return; } - if (this.MediaTranscriptionService.IsBusy(this.CurrentMediaImportOwner)) + if (this.MediaTranscriptionService.IsBusy(this.CurrentImportOwner)) return; var activeSession = this.AssistantSessionService.TryGetSnapshot(this.assistantSessionKey); @@ -1095,11 +1120,13 @@ public abstract partial class AssistantBase : AssistantLowerBase wher private async Task InnerResetForm() { if ((this.AssistantSessionService.TryGetSnapshot(this.assistantSessionKey)?.IsActive ?? false) - || this.MediaTranscriptionService.IsBusy(this.CurrentMediaImportOwner)) + || this.MediaTranscriptionService.IsBusy(this.CurrentImportOwner) + || this.WebContentImportService.IsBusy(this.CurrentImportOwner)) return; await this.AssistantSessionService.ClearAsync(this.assistantSessionKey); - this.MediaTranscriptionService.ClearOwnerState(this.CurrentMediaImportOwner); + this.MediaTranscriptionService.ClearOwnerState(this.CurrentImportOwner); + this.WebContentImportService.ClearOwnerState(this.CurrentImportOwner); this.assistantSessionId = null; this.ClearConversationState(); @@ -1119,6 +1146,10 @@ public abstract partial class AssistantBase : AssistantLowerBase wher this.InputIsValid = false; this.InputIssues = []; + // The draft is gone with the reset, see ClearAsync above, and the form starts anew: + this.stateWithDefaults = this.CaptureAssistantSessionState(); + this.holdsSentText = false; + if (this.Form is not null) await this.Form.ResetValidationAsync(); @@ -1143,6 +1174,7 @@ public abstract partial class AssistantBase : AssistantLowerBase wher protected override void DisposeResources() { + this.SaveDraftIfChanged(); this.MediaTranscriptionService.StateChanged -= this.OnMediaImportStateChanged; this.isDisposed = true; try @@ -1159,9 +1191,9 @@ public abstract partial class AssistantBase : AssistantLowerBase wher } /// Refreshes assistant actions when the shared import lane changes. - private void OnMediaImportStateChanged(MediaImportOwner owner) + private void OnMediaImportStateChanged(ImportOwner owner) { - if (owner == this.CurrentMediaImportOwner) + if (owner == this.CurrentImportOwner) this.InvokeAsync(async () => { await this.ConsumeMediaOutcomeAsync(); @@ -1172,7 +1204,7 @@ public abstract partial class AssistantBase : AssistantLowerBase wher /// Consumes a terminal media notification when this assistant is visible. private async Task ConsumeMediaOutcomeAsync() { - var outcome = this.MediaTranscriptionService.TryConsumeOutcome(this.CurrentMediaImportOwner); + var outcome = this.MediaTranscriptionService.TryConsumeOutcome(this.CurrentImportOwner); if (outcome is null) return; @@ -1261,6 +1293,12 @@ public abstract partial class AssistantBase : AssistantLowerBase wher /// A task that completes after the session was attached. private async Task AttachAssistantSessionIfAvailable() { + // + // A draft gives way to a run, which is newer, and to a text sent here, which the user chose to work on. + // It is taken in any case, so that a draft from before the user chose to discard inputs is gone, too: + // + var draft = this.AssistantSessionService.TryTakeDraft(this.assistantSessionKey); + var snapshot = this.AssistantSessionService.TryGetSnapshot(this.assistantSessionKey); if (snapshot?.IsActive ?? false) { @@ -1269,10 +1307,73 @@ public abstract partial class AssistantBase : AssistantLowerBase wher } snapshot = this.AssistantSessionService.TryTakeInactiveSnapshot(this.assistantSessionKey); - if (snapshot is null) + if (snapshot is not null) + { + await this.AttachAssistantSession(snapshot, restoreClientOnlyContent: true); + return; + } + + if (draft is not null && !this.holdsSentText && this.KeepsInputsWhenLeaving) + await this.RestoreDraft(draft); + } + + /// + /// Restores what this assistant held when the user left it, see SaveDraftIfChanged. + /// + /// + /// A draft is not a run, so this component takes over no session ID and does not count as attached to a + /// session: an assistant such as the I18N one loads its data anew, as on any other start. Flags of work + /// in progress stay as they are, see AssistantSessionStateKey.IsKeptOutOfDrafts. + /// + /// The draft to restore. + /// A task that completes after the component was refreshed. + private async Task RestoreDraft(AssistantSessionSnapshot draft) + { + this.ImportAssistantSessionState(draft.State, isDraft: true); + await this.OnAssistantSessionAttachedAsync(draft); + this.pendingRenderedAssistantSessionSnapshot = draft; + await this.RefreshAssistantUIAsync(); + } + + /// + /// Gets whether assistants keep the inputs of the user when the user leaves them, as the user or the + /// organization chose on the assistants page, see DataAssistantsPage.InputsWhenLeaving. + /// + /// + /// When not, an assistant behaves as before v26.11.2: it stores no draft and starts anew. Runs are not + /// affected, since their sessions keep their state either way. + /// + private bool KeepsInputsWhenLeaving => this.SettingsManager.ConfigurationData.AssistantsPage.InputsWhenLeaving is AssistantInputsWhenLeaving.KEEP_INPUTS; + + /// + /// Stores what this assistant holds as a draft, so that it is there again when the user comes back. + /// + /// + /// While a run goes on, its session keeps the state, so there is no draft. Neither is there one while + /// the assistant holds just its defaults, see IsWorthADraft, nor when the user chose to discard the + /// inputs, see KeepsInputsWhenLeaving. This runs while the component is disposed, so it must neither + /// wait nor throw. + /// + private void SaveDraftIfChanged() + { + if (this.stateWithDefaults is null || !this.KeepsInputsWhenLeaving) return; - await this.AttachAssistantSession(snapshot, restoreClientOnlyContent: true); + try + { + if (this.AssistantSessionService.TryGetSnapshot(this.assistantSessionKey)?.IsActive ?? false) + return; + + var state = this.CaptureAssistantSessionState(); + if (!IsWorthADraft(state, this.stateWithDefaults, this.holdsSentText)) + return; + + this.AssistantSessionService.SaveDraft(this.assistantSessionKey, this.Title, this.ChatThread, state); + } + catch (Exception e) + { + this.Logger.LogError(e, "Could not store the draft of the assistant '{AssistantTitle}'.", this.Title); + } } /// @@ -1367,9 +1468,10 @@ public abstract partial class AssistantBase : AssistantLowerBase wher /// Restores the base assistant state and assistant-specific typed state values from a session snapshot. /// /// The captured assistant state to import. - private void ImportAssistantSessionState(IReadOnlyDictionary state) + /// Whether the state comes from a draft rather than from a run. + private void ImportAssistantSessionState(IReadOnlyDictionary state, bool isDraft = false) { - var reader = new AssistantSessionStateReader(state, this.Title); + var reader = new AssistantSessionStateReader(state, this.Title, isDraft); reader.Restore(PROVIDER_SETTINGS_STATE_KEY, value => this.ProviderSettings = value); reader.Restore(INPUT_IS_VALID_STATE_KEY, value => this.InputIsValid = value); reader.Restore(CURRENT_PROFILE_STATE_KEY, value => this.CurrentProfile = value); diff --git a/app/MindWork AI Studio/Assistants/AssistantLowerBase.cs b/app/MindWork AI Studio/Assistants/AssistantLowerBase.cs index ce7f14e9f..de7675e50 100644 --- a/app/MindWork AI Studio/Assistants/AssistantLowerBase.cs +++ b/app/MindWork AI Studio/Assistants/AssistantLowerBase.cs @@ -29,14 +29,14 @@ public abstract class AssistantLowerBase : MSGComponentBase private protected static readonly TimeSpan STREAMING_CHECKPOINT_MIN_TIME = TimeSpan.FromSeconds(3); protected static readonly AssistantSessionStateKey PROVIDER_SETTINGS_STATE_KEY = new(nameof(ProviderSettings)); - protected static readonly AssistantSessionStateKey INPUT_IS_VALID_STATE_KEY = new(nameof(InputIsValid)); + protected static readonly AssistantSessionStateKey INPUT_IS_VALID_STATE_KEY = new(nameof(InputIsValid), isDerived: true); protected static readonly AssistantSessionStateKey CURRENT_PROFILE_STATE_KEY = new(nameof(CurrentProfile)); protected static readonly AssistantSessionStateKey CURRENT_CHAT_TEMPLATE_STATE_KEY = new(nameof(CurrentChatTemplate)); protected static readonly AssistantSessionStateKey CHAT_THREAD_STATE_KEY = new(nameof(ChatThread)); protected static readonly AssistantSessionStateKey LAST_USER_PROMPT_STATE_KEY = new(nameof(LastUserPrompt)); protected static readonly AssistantSessionStateKey RESULTING_CONTENT_BLOCK_STATE_KEY = new(nameof(ResultingContentBlock)); - protected static readonly AssistantSessionStateKey INPUT_ISSUES_STATE_KEY = new(nameof(InputIssues)); - protected static readonly AssistantSessionStateKey IS_PROCESSING_STATE_KEY = new(nameof(IsProcessing)); + protected static readonly AssistantSessionStateKey INPUT_ISSUES_STATE_KEY = new(nameof(InputIssues), isDerived: true); + protected static readonly AssistantSessionStateKey IS_PROCESSING_STATE_KEY = new(nameof(IsProcessing), isKeptOutOfDrafts: true); protected static readonly AssistantSessionStateKey> SELECTED_TOOL_IDS_STATE_KEY = new("SelectedToolIds"); protected static readonly AssistantSessionStateKey TRANSFERRED_RESTRICTIONS_STATE_KEY = new("TransferredRestrictions"); protected static readonly AssistantSessionStateKey CUSTOM_CHAT_SYSTEM_PROMPT_STATE_KEY = new("CustomChatSystemPromptOfRun"); @@ -65,4 +65,30 @@ public abstract class AssistantLowerBase : MSGComponentBase this.LastUserPrompt = null; this.ResultingContentBlock = null; } + + /// + /// Decides whether an assistant which the user leaves stores what it holds as a draft. + /// + /// + /// A text sent to the assistant is kept in any case. Otherwise, a draft needs a change from the state + /// with the defaults: a draft of just the defaults would bring back old defaults after the user changed + /// them in the settings. Only fields which count as a change are compared, see + /// IAssistantSessionSnapshotField.CountsAsChange: whether the form is valid, for example, follows from + /// the inputs and does not count as a change on its own. + /// + /// The state the assistant holds now. + /// The state the assistant held once its defaults were applied. + /// Whether the assistant holds a text sent to it. + /// true when the assistant stores a draft; otherwise, false. + internal static bool IsWorthADraft(IReadOnlyDictionary state, IReadOnlyDictionary stateWithDefaults, bool holdsSentText) + { + if (holdsSentText) + return true; + + var changeableFields = state.Where(field => field.Value.CountsAsChange).ToList(); + var holdsSameValues = changeableFields.Count == stateWithDefaults.Count(field => field.Value.CountsAsChange) + && changeableFields.All(field => stateWithDefaults.TryGetValue(field.Key, out var otherField) && field.Value.HasSameValueAs(otherField)); + + return !holdsSameValues; + } } \ No newline at end of file diff --git a/app/MindWork AI Studio/Assistants/BatchProcessing/AssistantBatchProcessing.razor.Session.cs b/app/MindWork AI Studio/Assistants/BatchProcessing/AssistantBatchProcessing.razor.Session.cs index 29e5bb712..87301cc38 100644 --- a/app/MindWork AI Studio/Assistants/BatchProcessing/AssistantBatchProcessing.razor.Session.cs +++ b/app/MindWork AI Studio/Assistants/BatchProcessing/AssistantBatchProcessing.razor.Session.cs @@ -28,7 +28,7 @@ public partial class AssistantBatchProcessing private static readonly AssistantSessionStateKey MAXIMUM_DELAY_SECONDS_STATE_KEY = new(nameof(maximumDelaySeconds)); private static readonly AssistantSessionStateKey> FILE_RESULTS_STATE_KEY = new(nameof(fileResults)); private static readonly AssistantSessionStateKey> USED_RESULT_FILE_NAMES_STATE_KEY = new(nameof(usedResultFileNames)); - private static readonly AssistantSessionStateKey IS_PROCESSING_BATCH_STATE_KEY = new(nameof(isProcessingBatch)); + private static readonly AssistantSessionStateKey IS_PROCESSING_BATCH_STATE_KEY = new(nameof(isProcessingBatch), isKeptOutOfDrafts: true); private static readonly AssistantSessionStateKey HAS_REPORTED_WRITE_FAILURE_STATE_KEY = new(nameof(hasReportedWriteFailure)); private static readonly AssistantSessionStateKey NUM_PROCESSED_FILES_STATE_KEY = new(nameof(numProcessedFiles)); private static readonly AssistantSessionStateKey NUM_TOO_LARGE_FILES_STATE_KEY = new(nameof(numTooLargeFiles)); diff --git a/app/MindWork AI Studio/Assistants/Builder/AssistantBuilder.razor.cs b/app/MindWork AI Studio/Assistants/Builder/AssistantBuilder.razor.cs index 9980cdadf..bce28097b 100644 --- a/app/MindWork AI Studio/Assistants/Builder/AssistantBuilder.razor.cs +++ b/app/MindWork AI Studio/Assistants/Builder/AssistantBuilder.razor.cs @@ -129,11 +129,11 @@ public partial class AssistantBuilder : AssistantBaseCore STEP_STATE_KEY = new(nameof(step)); - private static readonly AssistantSessionStateKey IS_GENERATING_STATE_KEY = new(nameof(isGenerating)); - private static readonly AssistantSessionStateKey IS_CHECKING_PLUGIN_STATE_KEY = new(nameof(isCheckingPlugin)); - private static readonly AssistantSessionStateKey IS_INSTALLING_PLUGIN_STATE_KEY = new(nameof(isInstallingPlugin)); - private static readonly AssistantSessionStateKey IS_AUDITING_PLUGIN_STATE_KEY = new(nameof(isAuditingPlugin)); - private static readonly AssistantSessionStateKey IS_ENABLING_PLUGIN_STATE_KEY = new(nameof(isEnablingPlugin)); + private static readonly AssistantSessionStateKey IS_GENERATING_STATE_KEY = new(nameof(isGenerating), isKeptOutOfDrafts: true); + private static readonly AssistantSessionStateKey IS_CHECKING_PLUGIN_STATE_KEY = new(nameof(isCheckingPlugin), isKeptOutOfDrafts: true); + private static readonly AssistantSessionStateKey IS_INSTALLING_PLUGIN_STATE_KEY = new(nameof(isInstallingPlugin), isKeptOutOfDrafts: true); + private static readonly AssistantSessionStateKey IS_AUDITING_PLUGIN_STATE_KEY = new(nameof(isAuditingPlugin), isKeptOutOfDrafts: true); + private static readonly AssistantSessionStateKey IS_ENABLING_PLUGIN_STATE_KEY = new(nameof(isEnablingPlugin), isKeptOutOfDrafts: true); private static readonly AssistantSessionStateKey ASSISTANT_DESCRIPTION_STATE_KEY = new(nameof(assistantDescription)); private static readonly AssistantSessionStateKey SELECTED_CATEGORY_STATE_KEY = new(nameof(selectedCategory)); private static readonly AssistantSessionStateKey CUSTOM_CATEGORY_STATE_KEY = new(nameof(customCategory)); diff --git a/app/MindWork AI Studio/Assistants/DocumentAnalysis/DocumentAnalysisAssistant.razor.cs b/app/MindWork AI Studio/Assistants/DocumentAnalysis/DocumentAnalysisAssistant.razor.cs index 55866728f..549f18814 100644 --- a/app/MindWork AI Studio/Assistants/DocumentAnalysis/DocumentAnalysisAssistant.razor.cs +++ b/app/MindWork AI Studio/Assistants/DocumentAnalysis/DocumentAnalysisAssistant.razor.cs @@ -280,6 +280,30 @@ public partial class DocumentAnalysisAssistant : AssistantBaseCore POLICY_MINIMUM_PROVIDER_CONFIDENCE_STATE_KEY = new(nameof(policyMinimumProviderConfidence)); private static readonly AssistantSessionStateKey POLICY_PRESELECTED_PROVIDER_ID_STATE_KEY = new(nameof(policyPreselectedProviderId)); private static readonly AssistantSessionStateKey POLICY_PRESELECTED_PROFILE_STATE_KEY = new(nameof(policyPreselectedProfile)); + private static readonly AssistantSessionStateKey> POLICY_ALLOWED_TOOL_IDS_STATE_KEY = new(nameof(policyAllowedToolIds)); private static readonly AssistantSessionStateKey> LOADED_DOCUMENT_PATHS_STATE_KEY = new(nameof(loadedDocumentPaths)); private static readonly AssistantSessionStateKey ANALYZED_POLICY_NAME_STATE_KEY = new(nameof(analyzedPolicyName)); private static readonly AssistantSessionStateKey>> AVAILABLE_LLM_PROVIDERS_STATE_KEY = new(nameof(availableLLMProviders)); @@ -434,6 +459,7 @@ public partial class DocumentAnalysisAssistant : AssistantBaseCore protected override void RestoreCustomAssistantSessionState(AssistantSessionStateReader state) { + if (state.IsDraft) + { + this.RestoreDraftState(state); + return; + } + state.Restore(SELECTED_POLICY_STATE_KEY, value => this.selectedPolicy = value); state.Restore(POLICY_IS_PROTECTED_STATE_KEY, value => this.policyIsProtected = value); state.Restore(POLICY_HIDE_POLICY_DEFINITION_STATE_KEY, value => this.policyHidePolicyDefinition = value); @@ -457,10 +489,46 @@ public partial class DocumentAnalysisAssistant : AssistantBaseCore this.policyMinimumProviderConfidence = value); state.Restore(POLICY_PRESELECTED_PROVIDER_ID_STATE_KEY, value => this.policyPreselectedProviderId = value); state.Restore(POLICY_PRESELECTED_PROFILE_STATE_KEY, value => this.policyPreselectedProfile = value); + + // + // The tools belong to the policy as well. On opening, the form holds those of the first policy, + // which AutoSave would otherwise write into the restored one: + // + state.Restore(POLICY_ALLOWED_TOOL_IDS_STATE_KEY, value => this.policyAllowedToolIds = [..value]); state.RestoreHashSet(LOADED_DOCUMENT_PATHS_STATE_KEY, this.loadedDocumentPaths); state.Restore(ANALYZED_POLICY_NAME_STATE_KEY, value => this.analyzedPolicyName = value); state.RestoreList(AVAILABLE_LLM_PROVIDERS_STATE_KEY, this.availableLLMProviders); } + + /// + /// Restores from a draft which policy was selected and what the user entered besides the policy. + /// + /// + /// The policies live in the settings, and AutoSave writes every change of the form into them. While the + /// user was elsewhere, a policy may have changed nonetheless, e.g., through a configuration plugin of the + /// organization, or it may be gone. A draft therefore brings back none of the policy fields, which hold + /// a copy of the policy, among them its minimum provider confidence: the form takes the policy as it is + /// now. A policy which no longer exists leaves the one selected on opening. + /// + /// The reader of the draft. + private void RestoreDraftState(AssistantSessionStateReader draft) + { + DataDocumentAnalysisPolicy? policyOfDraft = null; + draft.Restore(SELECTED_POLICY_STATE_KEY, value => policyOfDraft = value); + if (policyOfDraft is not null && this.SettingsManager.ConfigurationData.DocumentAnalysis.Policies.FirstOrDefault(policy => policy.Id == policyOfDraft.Id) is { } currentPolicy) + { + this.selectedPolicy = currentPolicy; + this.MightPreselectValues(); + draft.Restore(POLICY_DEFINITION_EXPANDED_STATE_KEY, value => + { + this.policyDefinitionExpanded = value; + this.documentSelectionExpanded = !value; + }); + } + + draft.RestoreHashSet(LOADED_DOCUMENT_PATHS_STATE_KEY, this.loadedDocumentPaths); + draft.Restore(ANALYZED_POLICY_NAME_STATE_KEY, value => this.analyzedPolicyName = value); + } private bool IsNoPolicySelectedOrProtected => this.selectedPolicy is null || this.selectedPolicy.IsProtected; diff --git a/app/MindWork AI Studio/Assistants/Dynamic/AssistantDynamic.razor b/app/MindWork AI Studio/Assistants/Dynamic/AssistantDynamic.razor index b993db4ba..3637bac52 100644 --- a/app/MindWork AI Studio/Assistants/Dynamic/AssistantDynamic.razor +++ b/app/MindWork AI Studio/Assistants/Dynamic/AssistantDynamic.razor @@ -140,6 +140,7 @@ else var webState = this.assistantState.WebContent[webContent.Name];
- +
} break; diff --git a/app/MindWork AI Studio/Assistants/Dynamic/AssistantDynamic.razor.cs b/app/MindWork AI Studio/Assistants/Dynamic/AssistantDynamic.razor.cs index dfce3de54..35e06710a 100644 --- a/app/MindWork AI Studio/Assistants/Dynamic/AssistantDynamic.razor.cs +++ b/app/MindWork AI Studio/Assistants/Dynamic/AssistantDynamic.razor.cs @@ -88,9 +88,9 @@ public partial class AssistantDynamic : AssistantBaseCore private static readonly AssistantSessionStateKey?> ASSISTANT_TOOL_IDS_STATE_KEY = new(nameof(assistantToolIds)); private static readonly AssistantSessionStateKey ASSISTANT_PLUGIN_STATE_KEY = new(nameof(assistantPlugin)); private static readonly AssistantSessionStateKey ASSISTANT_STATE_STATE_KEY = new(nameof(assistantState)); - private static readonly AssistantSessionStateKey> IMAGE_CACHE_STATE_KEY = new(nameof(imageCache)); - private static readonly AssistantSessionStateKey> EXECUTING_BUTTON_ACTIONS_STATE_KEY = new(nameof(executingButtonActions)); - private static readonly AssistantSessionStateKey> EXECUTING_SWITCH_ACTIONS_STATE_KEY = new(nameof(executingSwitchActions)); + private static readonly AssistantSessionStateKey> IMAGE_CACHE_STATE_KEY = new(nameof(imageCache), isDerived: true); + private static readonly AssistantSessionStateKey> EXECUTING_BUTTON_ACTIONS_STATE_KEY = new(nameof(executingButtonActions), isKeptOutOfDrafts: true); + private static readonly AssistantSessionStateKey> EXECUTING_SWITCH_ACTIONS_STATE_KEY = new(nameof(executingSwitchActions), isKeptOutOfDrafts: true); private static readonly AssistantSessionStateKey PLUGIN_PATH_STATE_KEY = new(nameof(pluginPath)); private static readonly AssistantSessionStateKey AUDIT_STATE_KEY = new(nameof(audit)); private static readonly AssistantSessionStateKey SECURITY_MESSAGE_STATE_KEY = new(nameof(securityMessage)); @@ -124,6 +124,12 @@ public partial class AssistantDynamic : AssistantBaseCore /// protected override void RestoreCustomAssistantSessionState(AssistantSessionStateReader state) { + if (state.IsDraft) + { + this.RestoreDraftState(state); + return; + } + state.Restore(TITLE_STATE_KEY, value => this.title = value); state.Restore(DESCRIPTION_STATE_KEY, value => this.description = value); state.Restore(SYSTEM_PROMPT_STATE_KEY, value => this.systemPrompt = value); @@ -143,6 +149,40 @@ public partial class AssistantDynamic : AssistantBaseCore state.Restore(SHARES_ASSISTANT_NAME_STATE_KEY, value => this.sharesAssistantName = value); } + /// + /// Restores from a draft what the user entered into the form. + /// + /// + /// Everything else follows from the plugin as it is now, see OnInitialized: while the user was elsewhere, + /// the plugin may have changed, or the organization may have withdrawn its approval. A draft therefore + /// brings back neither the plugin, its audit, its security state, nor its system prompt, so that a + /// blocked assistant stays blocked. What the user entered comes back only into the same version of a + /// plugin which may start: the components of another version may differ, and a blocked assistant shows + /// no form. Flags of work in progress inside the form, such as a running content cleaner, stay cleared. + /// + /// The reader of the draft. + private void RestoreDraftState(AssistantSessionStateReader draft) + { + if (this.isSecurityBlocked || this.assistantPlugin is not { } currentPlugin) + return; + + PluginAssistants? pluginOfDraft = null; + draft.Restore(ASSISTANT_PLUGIN_STATE_KEY, value => pluginOfDraft = value); + if (pluginOfDraft is null || pluginOfDraft.Id != currentPlugin.Id) + return; + + if (!ReferenceEquals(pluginOfDraft, currentPlugin) && !string.Equals(pluginOfDraft.ComputeAuditHash(), currentPlugin.ComputeAuditHash(), StringComparison.Ordinal)) + return; + + draft.Restore(ASSISTANT_STATE_STATE_KEY, value => + { + this.assistantState.CopyFrom(value); + this.assistantState.ClearFlagsOfWorkInProgress(); + }); + + draft.RestoreDictionary(IMAGE_CACHE_STATE_KEY, this.imageCache); + } + #region Implementation of AssistantBase protected override void OnInitialized() diff --git a/app/MindWork AI Studio/Assistants/Dynamic/FileAttachmentState.cs b/app/MindWork AI Studio/Assistants/Dynamic/FileAttachmentState.cs index 9bda173e3..d21143e29 100644 --- a/app/MindWork AI Studio/Assistants/Dynamic/FileAttachmentState.cs +++ b/app/MindWork AI Studio/Assistants/Dynamic/FileAttachmentState.cs @@ -5,4 +5,17 @@ namespace AIStudio.Assistants.Dynamic; public sealed class FileAttachmentState { public HashSet DocumentPaths { get; set; } = []; + + /// + /// Creates a copy which shares nothing with this state. + /// + /// The copy. + public FileAttachmentState Copy() => new() { DocumentPaths = new HashSet(this.DocumentPaths, this.DocumentPaths.Comparer) }; + + /// + /// Tells whether another state holds the same files as this one. + /// + /// The state to compare with. + /// true when both states hold the same files; otherwise, false. + public bool HasSameInputsAs(FileAttachmentState other) => this.DocumentPaths.SetEquals(other.DocumentPaths); } diff --git a/app/MindWork AI Studio/Assistants/Dynamic/FileContentState.cs b/app/MindWork AI Studio/Assistants/Dynamic/FileContentState.cs index 7ea92bd23..a20374edc 100644 --- a/app/MindWork AI Studio/Assistants/Dynamic/FileContentState.cs +++ b/app/MindWork AI Studio/Assistants/Dynamic/FileContentState.cs @@ -3,4 +3,17 @@ namespace AIStudio.Assistants.Dynamic; public sealed class FileContentState { public string Content { get; set; } = string.Empty; + + /// + /// Creates a copy which shares nothing with this state. + /// + /// The copy. + public FileContentState Copy() => new() { Content = this.Content }; + + /// + /// Tells whether another state holds the same content as this one. + /// + /// The state to compare with. + /// true when both states hold the same content; otherwise, false. + public bool HasSameInputsAs(FileContentState other) => string.Equals(this.Content, other.Content, StringComparison.Ordinal); } diff --git a/app/MindWork AI Studio/Assistants/Dynamic/WebContentState.cs b/app/MindWork AI Studio/Assistants/Dynamic/WebContentState.cs index 490862594..d2bfa7853 100644 --- a/app/MindWork AI Studio/Assistants/Dynamic/WebContentState.cs +++ b/app/MindWork AI Studio/Assistants/Dynamic/WebContentState.cs @@ -7,4 +7,30 @@ public sealed class WebContentState public bool Preselect { get; set; } public bool PreselectContentCleaner { get; set; } public bool CleanerIsRunning { get; set; } + + /// + /// Creates a copy which shares nothing with this state. + /// + /// The copy. + public WebContentState Copy() => new() + { + Content = this.Content, + URL = this.URL, + Preselect = this.Preselect, + PreselectContentCleaner = this.PreselectContentCleaner, + CleanerIsRunning = this.CleanerIsRunning, + }; + + /// + /// Tells whether another state holds the same inputs as this one. + /// + /// + /// Whether the content cleaner runs is not an input: it is work in progress, which ends with the component that started it. + /// + /// The state to compare with. + /// true when both states hold the same inputs; otherwise, false. + public bool HasSameInputsAs(WebContentState other) => string.Equals(this.Content, other.Content, StringComparison.Ordinal) + && string.Equals(this.URL, other.URL, StringComparison.Ordinal) + && this.Preselect == other.Preselect + && this.PreselectContentCleaner == other.PreselectContentCleaner; } \ No newline at end of file diff --git a/app/MindWork AI Studio/Assistants/ERI/AssistantERI.razor.cs b/app/MindWork AI Studio/Assistants/ERI/AssistantERI.razor.cs index f44ce1f2a..9384d1103 100644 --- a/app/MindWork AI Studio/Assistants/ERI/AssistantERI.razor.cs +++ b/app/MindWork AI Studio/Assistants/ERI/AssistantERI.razor.cs @@ -282,9 +282,27 @@ public partial class AssistantERI : AssistantBaseCore } /// + /// + /// The lists of the form are those of the selected server, see MightPreselectValues, and on opening, that + /// is the first server. The restored lists therefore become lists of their own: filled into the lists of + /// the form, they would replace the lists of the first server with those of another one, and the next + /// time the settings are stored, the first server would lose its embeddings, retrieval processes, and + /// generated files. A server which no longer exists brings back nothing, so that its inputs do not end up + /// in the server selected on opening. + /// protected override void RestoreCustomAssistantSessionState(AssistantSessionStateReader state) { - state.Restore(SELECTED_ERI_SERVER_STATE_KEY, value => this.selectedERIServer = value); + var serverStillExists = true; + state.Restore(SELECTED_ERI_SERVER_STATE_KEY, value => + { + serverStillExists = value is null || this.SettingsManager.ConfigurationData.ERI.ERIServers.Contains(value); + if (serverStillExists) + this.selectedERIServer = value; + }); + + if (!serverStillExists) + return; + state.Restore(AUTO_SAVE_STATE_KEY, value => this.autoSave = value); state.Restore(SERVER_NAME_STATE_KEY, value => this.serverName = value); state.Restore(SERVER_DESCRIPTION_STATE_KEY, value => this.serverDescription = value); @@ -302,12 +320,12 @@ public partial class AssistantERI : AssistantBaseCore state.Restore(AUTH_DESCRIPTION_STATE_KEY, value => this.authDescription = value); state.Restore(SELECTED_OPERATING_SYSTEM_STATE_KEY, value => this.selectedOperatingSystem = value); state.Restore(ALLOWED_LLM_PROVIDERS_STATE_KEY, value => this.allowedLLMProviders = value); - state.RestoreList(EMBEDDINGS_STATE_KEY, this.embeddings); - state.RestoreList(RETRIEVAL_PROCESSES_STATE_KEY, this.retrievalProcesses); + state.Restore(EMBEDDINGS_STATE_KEY, value => this.embeddings = [..value]); + state.Restore(RETRIEVAL_PROCESSES_STATE_KEY, value => this.retrievalProcesses = [..value]); state.Restore(ADDITIONAL_LIBRARIES_STATE_KEY, value => this.additionalLibraries = value); state.Restore(WRITE_TO_FILESYSTEM_STATE_KEY, value => this.writeToFilesystem = value); state.Restore(BASE_DIRECTORY_STATE_KEY, value => this.baseDirectory = value); - state.RestoreList(PREVIOUSLY_GENERATED_FILES_STATE_KEY, this.previouslyGeneratedFiles); + state.Restore(PREVIOUSLY_GENERATED_FILES_STATE_KEY, value => this.previouslyGeneratedFiles = [..value]); } private bool AreServerPresetsBlocked => !this.SettingsManager.ConfigurationData.ERI.PreselectOptions; diff --git a/app/MindWork AI Studio/Assistants/I18N/AssistantI18N.razor.cs b/app/MindWork AI Studio/Assistants/I18N/AssistantI18N.razor.cs index 38ea6cd26..130821ff9 100644 --- a/app/MindWork AI Studio/Assistants/I18N/AssistantI18N.razor.cs +++ b/app/MindWork AI Studio/Assistants/I18N/AssistantI18N.razor.cs @@ -138,7 +138,7 @@ public partial class AssistantI18N : AssistantBaseCore private string? formalTranslationOfText; private static readonly AssistantSessionStateKey SELECTED_TARGET_LANGUAGE_STATE_KEY = new(nameof(selectedTargetLanguage)); private static readonly AssistantSessionStateKey CUSTOM_TARGET_LANGUAGE_STATE_KEY = new(nameof(customTargetLanguage)); - private static readonly AssistantSessionStateKey IS_LOADING_STATE_KEY = new(nameof(isLoading)); + private static readonly AssistantSessionStateKey IS_LOADING_STATE_KEY = new(nameof(isLoading), isKeptOutOfDrafts: true); private static readonly AssistantSessionStateKey LOADING_ISSUE_STATE_KEY = new(nameof(loadingIssue)); private static readonly AssistantSessionStateKey LOCALIZATION_POSSIBLE_STATE_KEY = new(nameof(localizationPossible)); private static readonly AssistantSessionStateKey SEARCH_STRING_STATE_KEY = new(nameof(searchString)); diff --git a/app/MindWork AI Studio/Assistants/I18N/allTexts.lua b/app/MindWork AI Studio/Assistants/I18N/allTexts.lua index 3afe97982..2b7a3e2e5 100644 --- a/app/MindWork AI Studio/Assistants/I18N/allTexts.lua +++ b/app/MindWork AI Studio/Assistants/I18N/allTexts.lua @@ -16009,6 +16009,12 @@ UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTBUILDER::T4 -- The language in which the assistants you build answer. UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTBUILDER::T42126731::INFORMAL"] = "The language in which the assistants you build answer." +-- When you switch to the chat or to another assistant and come back, an assistant can still show your inputs, your options, and its last result. AI Studio keeps them in memory only, never on disk, until you reset the assistant or quit AI Studio. A text which you send to the assistant from elsewhere replaces them. An assistant which is still working keeps working in the background either way. +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T2267376752"] = "When you switch to the chat or to another assistant and come back, an assistant can still show your inputs, your options, and its last result. AI Studio keeps them in memory only, never on disk, until you reset the assistant or quit AI Studio. A text which you send to the assistant from elsewhere replaces them. An assistant which is still working keeps working in the background either way." + +-- When you switch to the chat or to another assistant and come back, an assistant can still show your inputs, your options, and its last result. AI Studio keeps them in memory only, never on disk, until you reset the assistant or quit AI Studio. A text which you send to the assistant from elsewhere replaces them. An assistant which is still working keeps working in the background either way. +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T2267376752::INFORMAL"] = "When you switch to the chat or to another assistant and come back, an assistant can still show your inputs, your options, and its last result. AI Studio keeps them in memory only, never on disk, until you reset the assistant or quit AI Studio. A text which you send to the assistant from elsewhere replaces them. An assistant which is still working keeps working in the background either way." + -- There are no categories to show or hide right now. UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T2279201345"] = "There are no categories to show or hide right now." @@ -16045,6 +16051,12 @@ UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T403 -- Assistant Settings UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T4124037832"] = "Assistant Settings" +-- What should happen to your inputs when you leave an assistant? +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T700558677"] = "What should happen to your inputs when you leave an assistant?" + +-- What should happen to your inputs when you leave an assistant? +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T700558677::INFORMAL"] = "What should happen to your inputs when you leave an assistant?" + -- Collapsing a category keeps the assistants page tidy. Choose whether AI Studio keeps offering its assistants elsewhere, e.g., in the "Send to ..." menu. UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T786145170"] = "Collapsing a category keeps the assistants page tidy. Choose whether AI Studio keeps offering its assistants elsewhere, e.g., in the \"Send to ...\" menu." @@ -20200,6 +20212,9 @@ UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T1402851833 -- Welcome UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T1485461907"] = "Welcome" +-- Keep my inputs and the last result until I reset the assistant or quit AI Studio +UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T1488089083"] = "Keep my inputs and the last result until I reset the assistant or quit AI Studio" + -- Assistants UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T1614176092"] = "Assistants" @@ -20323,6 +20338,9 @@ UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T453866521" -- Chat UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T578410699"] = "Chat" +-- Reset the assistant, so that it starts anew next time +UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T715634053"] = "Reset the assistant, so that it starts anew next time" + -- When possible, use the LLM provider which was used for each chat in the first place UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T75376144"] = "When possible, use the LLM provider which was used for each chat in the first place" diff --git a/app/MindWork AI Studio/Assistants/LegalCheck/AssistantLegalCheck.razor.cs b/app/MindWork AI Studio/Assistants/LegalCheck/AssistantLegalCheck.razor.cs index 3a1797b6b..c6c981d23 100644 --- a/app/MindWork AI Studio/Assistants/LegalCheck/AssistantLegalCheck.razor.cs +++ b/app/MindWork AI Studio/Assistants/LegalCheck/AssistantLegalCheck.razor.cs @@ -68,7 +68,7 @@ public partial class AssistantLegalCheck : AssistantBaseCore SHOW_WEB_CONTENT_READER_STATE_KEY = new(nameof(showWebContentReader)); private static readonly AssistantSessionStateKey USE_CONTENT_CLEANER_STATE_KEY = new(nameof(useContentCleaner)); - private static readonly AssistantSessionStateKey IS_CLEANER_RUNNING_STATE_KEY = new(nameof(isCleanerRunning)); + private static readonly AssistantSessionStateKey IS_CLEANER_RUNNING_STATE_KEY = new(nameof(isCleanerRunning), isKeptOutOfDrafts: true); private static readonly AssistantSessionStateKey WEB_CONTENT_URL_STATE_KEY = new(nameof(webContentURL)); private static readonly AssistantSessionStateKey INPUT_LEGAL_DOCUMENT_STATE_KEY = new(nameof(inputLegalDocument)); private static readonly AssistantSessionStateKey INPUT_QUESTIONS_STATE_KEY = new(nameof(inputQuestions)); diff --git a/app/MindWork AI Studio/Assistants/ModelComparison/AssistantModelComparison.razor.cs b/app/MindWork AI Studio/Assistants/ModelComparison/AssistantModelComparison.razor.cs index 6d451a2fd..1a5bcc016 100644 --- a/app/MindWork AI Studio/Assistants/ModelComparison/AssistantModelComparison.razor.cs +++ b/app/MindWork AI Studio/Assistants/ModelComparison/AssistantModelComparison.razor.cs @@ -487,7 +487,7 @@ public partial class AssistantModelComparison : AssistantBaseCore INPUT_CONTEXT_STATE_KEY = new(nameof(inputContext)); private static readonly AssistantSessionStateKey INPUT_QUESTION_STATE_KEY = new(nameof(inputQuestion)); - private static readonly AssistantSessionStateKey IS_COMPARING_STATE_KEY = new(nameof(isComparing)); + private static readonly AssistantSessionStateKey IS_COMPARING_STATE_KEY = new(nameof(isComparing), isKeptOutOfDrafts: true); private static readonly AssistantSessionStateKey RUN_COUNT_STATE_KEY = new(nameof(runCount)); private static readonly AssistantSessionStateKey BATCH_STATE_KEY = new(nameof(batch)); private static readonly AssistantSessionStateKey SECOND_PROVIDER_STATE_KEY = new(nameof(secondProvider)); diff --git a/app/MindWork AI Studio/Assistants/PromptOptimizer/AssistantPromptOptimizer.razor.cs b/app/MindWork AI Studio/Assistants/PromptOptimizer/AssistantPromptOptimizer.razor.cs index 07c950d7d..cb3e54d31 100644 --- a/app/MindWork AI Studio/Assistants/PromptOptimizer/AssistantPromptOptimizer.razor.cs +++ b/app/MindWork AI Studio/Assistants/PromptOptimizer/AssistantPromptOptimizer.razor.cs @@ -253,7 +253,7 @@ public partial class AssistantPromptOptimizer : AssistantBaseCore> CUSTOM_PROMPT_GUIDE_FILES_STATE_KEY = new(nameof(customPromptGuideFiles)); private static readonly AssistantSessionStateKey CURRENT_CUSTOM_PROMPT_GUIDE_PATH_STATE_KEY = new(nameof(currentCustomPromptGuidePath)); private static readonly AssistantSessionStateKey CUSTOM_PROMPTING_GUIDELINE_CONTENT_STATE_KEY = new(nameof(customPromptingGuidelineContent)); - private static readonly AssistantSessionStateKey IS_LOADING_CUSTOM_PROMPT_GUIDE_STATE_KEY = new(nameof(isLoadingCustomPromptGuide)); + private static readonly AssistantSessionStateKey IS_LOADING_CUSTOM_PROMPT_GUIDE_STATE_KEY = new(nameof(isLoadingCustomPromptGuide), isKeptOutOfDrafts: true); private static readonly AssistantSessionStateKey HAS_UPDATED_DEFAULT_RECOMMENDATIONS_STATE_KEY = new(nameof(hasUpdatedDefaultRecommendations)); private static readonly AssistantSessionStateKey OPTIMIZED_PROMPT_STATE_KEY = new(nameof(optimizedPrompt)); private static readonly AssistantSessionStateKey REC_CLARITY_DIRECTNESS_STATE_KEY = new(nameof(recClarityDirectness)); diff --git a/app/MindWork AI Studio/Assistants/SWOTAnalysis/AssistantSWOTAnalysis.razor b/app/MindWork AI Studio/Assistants/SWOTAnalysis/AssistantSWOTAnalysis.razor index c25c7ac5b..bbafc7891 100644 --- a/app/MindWork AI Studio/Assistants/SWOTAnalysis/AssistantSWOTAnalysis.razor +++ b/app/MindWork AI Studio/Assistants/SWOTAnalysis/AssistantSWOTAnalysis.razor @@ -15,15 +15,15 @@ @T("Input") - + @T("Analysis Options") - + - + @T("Contextual Knowledge") diff --git a/app/MindWork AI Studio/Assistants/SWOTAnalysis/AssistantSWOTAnalysis.razor.cs b/app/MindWork AI Studio/Assistants/SWOTAnalysis/AssistantSWOTAnalysis.razor.cs index ea8992679..08a707dc7 100644 --- a/app/MindWork AI Studio/Assistants/SWOTAnalysis/AssistantSWOTAnalysis.razor.cs +++ b/app/MindWork AI Studio/Assistants/SWOTAnalysis/AssistantSWOTAnalysis.razor.cs @@ -109,14 +109,14 @@ public partial class AssistantSWOTAnalysis : AssistantBaseCore ANALYSIS_GOAL_STATE_KEY = new(nameof(analysisGoal)); private static readonly AssistantSessionStateKey IMPORTANT_ASPECTS_STATE_KEY = new(nameof(importantAspects)); private static readonly AssistantSessionStateKey> CONTEXT_MATERIALS_STATE_KEY = new(nameof(contextMaterials)); - private static readonly AssistantSessionStateKey IS_CLEANER_RUNNING_STATE_KEY = new(nameof(isCleanerRunning)); + private static readonly AssistantSessionStateKey IS_CLEANER_RUNNING_STATE_KEY = new(nameof(isCleanerRunning), isKeptOutOfDrafts: true); private static readonly AssistantSessionStateKey SELECTED_TARGET_LANGUAGE_STATE_KEY = new(nameof(selectedTargetLanguage)); private static readonly AssistantSessionStateKey CUSTOM_TARGET_LANGUAGE_STATE_KEY = new(nameof(customTargetLanguage)); private static readonly AssistantSessionStateKey ANALYSIS_RESULT_STATE_KEY = new(nameof(analysisResult)); private static readonly AssistantSessionStateKey> CATEGORY_ANALYSIS_PROGRESS_STATE_KEY = new(nameof(categoryAnalysisProgress)); - private static readonly AssistantSessionStateKey IS_GATHERING_SHARED_RESEARCH_STATE_KEY = new(nameof(isGatheringSharedResearch)); - private static readonly AssistantSessionStateKey IS_MODERATING_ANALYSIS_STATE_KEY = new(nameof(isModeratingAnalysis)); - private static readonly AssistantSessionStateKey IS_REPAIRING_MODERATION_STATE_KEY = new(nameof(isRepairingModeration)); + private static readonly AssistantSessionStateKey IS_GATHERING_SHARED_RESEARCH_STATE_KEY = new(nameof(isGatheringSharedResearch), isKeptOutOfDrafts: true); + private static readonly AssistantSessionStateKey IS_MODERATING_ANALYSIS_STATE_KEY = new(nameof(isModeratingAnalysis), isKeptOutOfDrafts: true); + private static readonly AssistantSessionStateKey IS_REPAIRING_MODERATION_STATE_KEY = new(nameof(isRepairingModeration), isKeptOutOfDrafts: true); private static readonly AssistantSessionStateKey SHARED_RESEARCH_CONTEXT_STATE_KEY = new(nameof(sharedResearchContext)); /// diff --git a/app/MindWork AI Studio/Assistants/TextSummarizer/AssistantTextSummarizer.razor.cs b/app/MindWork AI Studio/Assistants/TextSummarizer/AssistantTextSummarizer.razor.cs index d28b46f99..10c68fca1 100644 --- a/app/MindWork AI Studio/Assistants/TextSummarizer/AssistantTextSummarizer.razor.cs +++ b/app/MindWork AI Studio/Assistants/TextSummarizer/AssistantTextSummarizer.razor.cs @@ -101,7 +101,7 @@ public partial class AssistantTextSummarizer : AssistantBaseCore USE_CONTENT_CLEANER_STATE_KEY = new(nameof(useContentCleaner)); private static readonly AssistantSessionStateKey WEB_CONTENT_URL_STATE_KEY = new(nameof(webContentURL)); private static readonly AssistantSessionStateKey INPUT_TEXT_STATE_KEY = new(nameof(inputText)); - private static readonly AssistantSessionStateKey IS_CLEANER_RUNNING_STATE_KEY = new(nameof(isCleanerRunning)); + private static readonly AssistantSessionStateKey IS_CLEANER_RUNNING_STATE_KEY = new(nameof(isCleanerRunning), isKeptOutOfDrafts: true); private static readonly AssistantSessionStateKey SELECTED_TARGET_LANGUAGE_STATE_KEY = new(nameof(selectedTargetLanguage)); private static readonly AssistantSessionStateKey CUSTOM_TARGET_LANGUAGE_STATE_KEY = new(nameof(customTargetLanguage)); private static readonly AssistantSessionStateKey SELECTED_COMPLEXITY_STATE_KEY = new(nameof(selectedComplexity)); diff --git a/app/MindWork AI Studio/Assistants/Translation/AssistantTranslation.razor.cs b/app/MindWork AI Studio/Assistants/Translation/AssistantTranslation.razor.cs index ac06c41a7..dc837b63d 100644 --- a/app/MindWork AI Studio/Assistants/Translation/AssistantTranslation.razor.cs +++ b/app/MindWork AI Studio/Assistants/Translation/AssistantTranslation.razor.cs @@ -107,7 +107,7 @@ public partial class AssistantTranslation : AssistantBaseCore SHOW_WEB_CONTENT_READER_STATE_KEY = new(nameof(showWebContentReader)); private static readonly AssistantSessionStateKey USE_CONTENT_CLEANER_STATE_KEY = new(nameof(useContentCleaner)); private static readonly AssistantSessionStateKey LIVE_TRANSLATION_STATE_KEY = new(nameof(liveTranslation)); - private static readonly AssistantSessionStateKey IS_CLEANER_RUNNING_STATE_KEY = new(nameof(isCleanerRunning)); + private static readonly AssistantSessionStateKey IS_CLEANER_RUNNING_STATE_KEY = new(nameof(isCleanerRunning), isKeptOutOfDrafts: true); private static readonly AssistantSessionStateKey WEB_CONTENT_URL_STATE_KEY = new(nameof(webContentURL)); private static readonly AssistantSessionStateKey INPUT_TEXT_STATE_KEY = new(nameof(inputText)); private static readonly AssistantSessionStateKey INPUT_TEXT_LAST_TRANSLATION_STATE_KEY = new(nameof(inputTextLastTranslation)); diff --git a/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingAssistant.razor b/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingAssistant.razor index b7cfbc525..d4188e2d8 100644 --- a/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingAssistant.razor +++ b/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingAssistant.razor @@ -1,6 +1,6 @@ @attribute [Route(Routes.ASSISTANT_VISUAL_BRIEFING)] @using AIStudio.Assistants.SlideBuilder -@using AIStudio.Tools.Media +@using AIStudio.Tools.Imports @using AIStudio.Tools.Rust @inherits MSGComponentBase @@ -39,7 +39,7 @@ } @if (project.IsAvailable) { - + } diff --git a/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingAssistant.razor.Projects.cs b/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingAssistant.razor.Projects.cs index 7643d7df9..e77f00ac8 100644 --- a/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingAssistant.razor.Projects.cs +++ b/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingAssistant.razor.Projects.cs @@ -3,7 +3,7 @@ using System.Text.Json; using AIStudio.Chat; using AIStudio.Dialogs; using AIStudio.Provider; -using AIStudio.Tools.Media; +using AIStudio.Tools.Imports; using AIStudio.Tools.Rust; using DialogOptions = AIStudio.Dialogs.DialogOptions; @@ -142,7 +142,7 @@ public partial class VisualBriefingAssistant return; var id = this.selectedProject.BriefingId; - this.MediaTranscriptionService.ClearOwnerState(MediaImportOwner.ForVisualBriefing(id)); + this.MediaTranscriptionService.ClearOwnerState(ImportOwner.ForVisualBriefing(id)); await this.Store.DeleteAsync(id); await this.Store.ForgetSelectionAsync(id); diff --git a/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingAssistant.razor.Sources.cs b/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingAssistant.razor.Sources.cs index 25c9a018e..a81a31cea 100644 --- a/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingAssistant.razor.Sources.cs +++ b/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingAssistant.razor.Sources.cs @@ -1,5 +1,6 @@ using AIStudio.Chat; using AIStudio.Dialogs; +using AIStudio.Tools.Imports; using AIStudio.Tools.Media; using DialogOptions = AIStudio.Dialogs.DialogOptions; @@ -11,9 +12,9 @@ public partial class VisualBriefingAssistant /// /// Defines CurrentMediaOwner for the visual briefing feature. /// - private MediaImportOwner CurrentMediaOwner => this.selectedBriefing is null - ? new(MediaImportOwnerKind.VISUAL_BRIEFING, Guid.Empty.ToString("D")) - : MediaImportOwner.ForVisualBriefing(this.selectedBriefing.BriefingId); + private ImportOwner CurrentMediaOwner => this.selectedBriefing is null + ? new(ImportOwnerKind.VISUAL_BRIEFING, Guid.Empty.ToString("D")) + : ImportOwner.ForVisualBriefing(this.selectedBriefing.BriefingId); /// /// Keeps source material and visual assets mutually exclusive after either list changed. @@ -130,9 +131,9 @@ public partial class VisualBriefingAssistant /// /// Defines MediaStateChanged for the visual briefing feature. /// - private void MediaStateChanged(MediaImportOwner owner) + private void MediaStateChanged(ImportOwner owner) { - if (owner.Kind is not MediaImportOwnerKind.VISUAL_BRIEFING || + if (owner.Kind is not ImportOwnerKind.VISUAL_BRIEFING || !Guid.TryParse(owner.Id, out var briefingId)) return; @@ -167,7 +168,7 @@ public partial class VisualBriefingAssistant private async Task ConsumePendingMediaOutcomesAsync() { foreach (var project in this.projects) - await this.ConsumeMediaOutcomeAsync(MediaImportOwner.ForVisualBriefing(project.BriefingId)); + await this.ConsumeMediaOutcomeAsync(ImportOwner.ForVisualBriefing(project.BriefingId)); } /// @@ -181,7 +182,7 @@ public partial class VisualBriefingAssistant /// different briefing is open still gets reported. /// /// The briefing whose media import finished. - private async Task ConsumeMediaOutcomeAsync(MediaImportOwner owner) + private async Task ConsumeMediaOutcomeAsync(ImportOwner owner) { var outcome = this.MediaTranscriptionService.TryConsumeOutcome(owner); if (outcome is null) diff --git a/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingTranscriptStorage.cs b/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingTranscriptStorage.cs index b11fcebe2..4e988d956 100644 --- a/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingTranscriptStorage.cs +++ b/app/MindWork AI Studio/Assistants/VisualBriefing/VisualBriefingTranscriptStorage.cs @@ -1,4 +1,5 @@ using AIStudio.Chat; +using AIStudio.Tools.Imports; using AIStudio.Tools.Media; namespace AIStudio.Assistants.VisualBriefing; @@ -11,15 +12,15 @@ public sealed class VisualBriefingTranscriptStorage(VisualBriefingStore store) : /// /// Defines CanStore for the visual briefing feature. /// - public bool CanStore(MediaImportOwner owner) => - owner.Kind is MediaImportOwnerKind.VISUAL_BRIEFING && + public bool CanStore(ImportOwner owner) => + owner.Kind is ImportOwnerKind.VISUAL_BRIEFING && Guid.TryParse(owner.Id, out _); /// /// Defines StoreAsync for the visual briefing feature. /// public async Task StoreAsync( - MediaImportTarget target, + ImportTarget target, string originalMediaPath, string transcript, CancellationToken token) diff --git a/app/MindWork AI Studio/Components/AssistantBlock.razor.cs b/app/MindWork AI Studio/Components/AssistantBlock.razor.cs index 251b175bd..65e72a91d 100644 --- a/app/MindWork AI Studio/Components/AssistantBlock.razor.cs +++ b/app/MindWork AI Studio/Components/AssistantBlock.razor.cs @@ -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 : 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 : MSGComponentBase, IAssistantCat await this.DialogService.ShowAsync(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 : 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)); /// - /// 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. /// /// /// 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. /// - /// The media-import owner to test. + /// The import owner to test. /// true when this block represents the owner. - 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; } /// @@ -152,18 +157,30 @@ public partial class AssistantBlock : MSGComponentBase, IAssistantCat _ => this.AssistantSessionIndicatorWithoutMedia, }; - private AssistantSessionIndicatorData? AssistantSessionIndicatorWithoutMedia => this.AssistantSessionSnapshot?.Status switch + /// + /// Gets the indicator of the assistant session, unless web content for the assistant is still loading, which counts + /// as running as well. + /// + 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.")); + + /// + /// Gets whether one of the web content readers of the assistant is loading a page, see WebContentImportService. + /// + 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 : 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) + /// + /// Renders the block again when an import of its assistant changed, the transcription of a media file or the + /// loading of web content. + /// + 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(); } diff --git a/app/MindWork AI Studio/Components/AttachDocuments.razor b/app/MindWork AI Studio/Components/AttachDocuments.razor index 878a8d4bc..5cebcf7eb 100644 --- a/app/MindWork AI Studio/Components/AttachDocuments.razor +++ b/app/MindWork AI Studio/Components/AttachDocuments.razor @@ -60,7 +60,7 @@ @if (this.ShowMediaStatus) { - + } } @@ -85,7 +85,7 @@ else } @if (this.ShowMediaStatus) { - + } 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 } /// Refreshes disabled controls when the shared import lane changes. - 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 /// Reattaches completed owner results after progress updates or navigation. 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; } diff --git a/app/MindWork AI Studio/Components/ChatComponent.razor b/app/MindWork AI Studio/Components/ChatComponent.razor index 4897ed457..7b60bb261 100644 --- a/app/MindWork AI Studio/Components/ChatComponent.razor +++ b/app/MindWork AI Studio/Components/ChatComponent.razor @@ -39,7 +39,7 @@ } - + 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 } /// Refreshes send and attachment controls when the media import lane changes. - 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 /// Consumes a terminal media notification when its chat is visible. 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); /// /// 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. /// - 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 /// 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(); diff --git a/app/MindWork AI Studio/Components/DebouncedTextField.razor b/app/MindWork AI Studio/Components/DebouncedTextField.razor index 944bcf71a..fd731ed71 100644 --- a/app/MindWork AI Studio/Components/DebouncedTextField.razor +++ b/app/MindWork AI Studio/Components/DebouncedTextField.razor @@ -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: *@ - \ No newline at end of file + \ No newline at end of file diff --git a/app/MindWork AI Studio/Components/DebouncedTextField.razor.cs b/app/MindWork AI Studio/Components/DebouncedTextField.razor.cs index be5da73ca..7b157de4c 100644 --- a/app/MindWork AI Studio/Components/DebouncedTextField.razor.cs +++ b/app/MindWork AI Studio/Components/DebouncedTextField.razor.cs @@ -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(); } + /// + /// Hands a text which still waits for the debounce time on at once, as soon as the user leaves the field. + /// + /// + /// 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. + /// + private void OnBlur(FocusEventArgs _) + { + if (!this.debounceTimer.Enabled) + return; + + this.debounceTimer.Stop(); + this.HandOnText(); + } + + /// + /// Hands the text on to the parent and to the handlers of a changed text. + /// + 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() diff --git a/app/MindWork AI Studio/Components/MediaTranscriptionStatus.razor.cs b/app/MindWork AI Studio/Components/MediaTranscriptionStatus.razor.cs index bfec89f26..67ff08de5 100644 --- a/app/MindWork AI Studio/Components/MediaTranscriptionStatus.razor.cs +++ b/app/MindWork AI Studio/Components/MediaTranscriptionStatus.razor.cs @@ -1,3 +1,4 @@ +using AIStudio.Tools.Imports; using AIStudio.Tools.Media; using Microsoft.AspNetCore.Components; @@ -7,7 +8,7 @@ public partial class MediaTranscriptionStatus { /// The surface owner whose operation is rendered. [Parameter] - public MediaImportOwner Owner { get; set; } + public ImportOwner Owner { get; set; } /// Optional target filter used by embedded file controls. [Parameter] @@ -58,7 +59,7 @@ public partial class MediaTranscriptionStatus } /// Schedules a render after an import state transition. - 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"); diff --git a/app/MindWork AI Studio/Components/PluginDeleteAction.razor.cs b/app/MindWork AI Studio/Components/PluginDeleteAction.razor.cs index 837ae2d2f..4821082a4 100644 --- a/app/MindWork AI Studio/Components/PluginDeleteAction.razor.cs +++ b/app/MindWork AI Studio/Components/PluginDeleteAction.razor.cs @@ -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"); } } \ No newline at end of file diff --git a/app/MindWork AI Studio/Components/ReadFileContent.razor b/app/MindWork AI Studio/Components/ReadFileContent.razor index 7d50b284c..a0a46424b 100644 --- a/app/MindWork AI Studio/Components/ReadFileContent.razor +++ b/app/MindWork AI Studio/Components/ReadFileContent.razor @@ -26,7 +26,7 @@ @if (this.IsCurrentTargetBusy) { - + } else { @@ -57,6 +57,6 @@ else } - + } \ No newline at end of file diff --git a/app/MindWork AI Studio/Components/ReadFileContent.razor.cs b/app/MindWork AI Studio/Components/ReadFileContent.razor.cs index f35857bc9..8189721c2 100644 --- a/app/MindWork AI Studio/Components/ReadFileContent.razor.cs +++ b/app/MindWork AI Studio/Components/ReadFileContent.razor.cs @@ -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 } /// Refreshes disabled controls when the shared import lane changes. - 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 /// The transcript arrives filtered for prompt injections, cf. MediaTranscriptionService. 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() diff --git a/app/MindWork AI Studio/Components/ReadWebContent.razor b/app/MindWork AI Studio/Components/ReadWebContent.razor index 085abad07..5315f009d 100644 --- a/app/MindWork AI Studio/Components/ReadWebContent.razor +++ b/app/MindWork AI Studio/Components/ReadWebContent.razor @@ -1,9 +1,9 @@ @inherits MSGComponentBase - + @if (this.Preselect) { - + @if (this.ContentCleanerHint is { } contentCleanerHint) { @@ -11,14 +11,14 @@ } - - @if (this.CleanerIsRunning) + @if (this.IsImporting) { - + } } \ No newline at end of file diff --git a/app/MindWork AI Studio/Components/ReadWebContent.razor.cs b/app/MindWork AI Studio/Components/ReadWebContent.razor.cs index 46f7b08ea..f6b29552e 100644 --- a/app/MindWork AI Studio/Components/ReadWebContent.razor.cs +++ b/app/MindWork AI Studio/Components/ReadWebContent.razor.cs @@ -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; +/// +/// Loads the content of a web page into a text field of an assistant. +/// +/// +/// 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. +/// public partial class ReadWebContent : MSGComponentBase { /// - /// How long loading one page may take. + /// The owner of the imports of a reader outside an assistant, which cascades no owner. /// - /// - /// 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. - /// - 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 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!; + /// + /// The assistant around this reader, which owns its imports. + /// + [CascadingParameter] + private ImportOwner? ImportOwner { get; set; } + + /// + /// Tells the readers of one assistant apart, e.g., by the name of the component of an assistant plugin. + /// + /// + /// An assistant with a single reader keeps the default. + /// + [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 PreselectContentCleanerChanged { get; set; } private readonly Process process = Process.INSTANCE; - private ProcessStepValue processStep; /// /// 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; } + /// + /// Stops following the imports. An import keeps running, and its result waits for the next reader of this field. + /// + protected override void DisposeResources() + { + this.WebContentImportService.StateChanged -= this.OnImportStateChanged; + base.DisposeResources(); + } + #endregion /// @@ -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. /// - 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); /// - /// What the reader adds to the choice of the provider for the content cleaner. + /// The import which fills this field, while it runs. + /// + private WebContentImportSnapshot? CurrentImport => this.WebContentImportService.GetSnapshot(this.EffectiveImportTarget); + + /// + /// 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. + /// + 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"); + } + + /// + /// Takes over what the import of this field reached: its options while it runs, its result once it ended, and + /// whether it cleans. /// /// - /// 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. /// - /// The settings, for the app-wide default. - /// The model of the assistant around the reader. - /// The options for the provider resolver. - 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); + } + + /// + /// Shows the options with which the import of this field runs: the reader expanded, the address it loads, + /// and whether it cleans the page. + /// + /// + /// 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. + /// + 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); } diff --git a/app/MindWork AI Studio/Components/Workspaces.razor.cs b/app/MindWork AI Studio/Components/Workspaces.razor.cs index 9a37ad931..b238efacc 100644 --- a/app/MindWork AI Studio/Components/Workspaces.razor.cs +++ b/app/MindWork AI Studio/Components/Workspaces.razor.cs @@ -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. /// /// The chat to check. - 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. /// /// The chat in the tree. - 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); diff --git a/app/MindWork AI Studio/Dialogs/Settings/SettingsDialogAssistantsPage.razor b/app/MindWork AI Studio/Dialogs/Settings/SettingsDialogAssistantsPage.razor index 84c5e5fe3..ec379ca5d 100644 --- a/app/MindWork AI Studio/Dialogs/Settings/SettingsDialogAssistantsPage.razor +++ b/app/MindWork AI Studio/Dialogs/Settings/SettingsDialogAssistantsPage.razor @@ -11,6 +11,7 @@ + @T("Categories") diff --git a/app/MindWork AI Studio/Dialogs/Settings/SettingsDialogAssistantsPage.razor.cs b/app/MindWork AI Studio/Dialogs/Settings/SettingsDialogAssistantsPage.razor.cs index c7640dfc3..b35018c01 100644 --- a/app/MindWork AI Studio/Dialogs/Settings/SettingsDialogAssistantsPage.razor.cs +++ b/app/MindWork AI Studio/Dialogs/Settings/SettingsDialogAssistantsPage.razor.cs @@ -6,7 +6,7 @@ namespace AIStudio.Dialogs.Settings; /// /// The settings of the assistants page: what happens to the assistants of collapsed and hidden categories, -/// and which categories the page shows. +/// whether assistants keep your inputs when you leave them, and which categories the page shows. /// public partial class SettingsDialogAssistantsPage : SettingsDialogBase { @@ -23,4 +23,6 @@ public partial class SettingsDialogAssistantsPage : SettingsDialogBase private string CollapsedCategoriesHelp => TA("""Collapsing a category keeps the assistants page tidy. Choose whether AI Studio keeps offering its assistants elsewhere, e.g., in the "Send to ..." menu."""); private string HiddenCategoriesHelp => TA("""Hiding a category says that you do not need its assistants. Choose whether AI Studio still offers them elsewhere, e.g., in the "Send to ..." menu."""); + + private string InputsWhenLeavingHelp => TA("When you switch to the chat or to another assistant and come back, an assistant can still show your inputs, your options, and its last result. AI Studio keeps them in memory only, never on disk, until you reset the assistant or quit AI Studio. A text which you send to the assistant from elsewhere replaces them. An assistant which is still working keeps working in the background either way."); } \ No newline at end of file diff --git a/app/MindWork AI Studio/Layout/MainLayout.razor.cs b/app/MindWork AI Studio/Layout/MainLayout.razor.cs index c4cccbdb4..f5412769b 100644 --- a/app/MindWork AI Studio/Layout/MainLayout.razor.cs +++ b/app/MindWork AI Studio/Layout/MainLayout.razor.cs @@ -3,11 +3,12 @@ using AIStudio.Settings; using AIStudio.Settings.DataModel; using AIStudio.Tools.AIJobs; using AIStudio.Tools.AssistantSessions; -using AIStudio.Tools.Media; +using AIStudio.Tools.Imports; using AIStudio.Tools.PluginSystem; using AIStudio.Tools.Security; using AIStudio.Tools.Rust; using AIStudio.Tools.Services; +using AIStudio.Tools.Web; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Routing; @@ -42,7 +43,10 @@ public partial class MainLayout : LayoutComponentBase, IMessageBusReceiver, ILan [Inject] private MediaTranscriptionService MediaTranscriptionService { get; init; } = null!; - + + [Inject] + private WebContentImportService WebContentImportService { get; init; } = null!; + [Inject] private ISnackbar Snackbar { get; init; } = null!; @@ -99,7 +103,8 @@ public partial class MainLayout : LayoutComponentBase, IMessageBusReceiver, ILan protected override async Task OnInitializedAsync() { this.NavigationManager.RegisterLocationChangingHandler(this.OnLocationChanging); - this.MediaTranscriptionService.StateChanged += this.OnMediaImportStateChanged; + this.MediaTranscriptionService.StateChanged += this.OnImportStateChanged; + this.WebContentImportService.StateChanged += this.OnImportStateChanged; this.DataRestoreService.StateChanged += this.OnDataRestoreStateChanged; // @@ -481,14 +486,14 @@ public partial class MainLayout : LayoutComponentBase, IMessageBusReceiver, ILan this.navItems = new List(this.GetNavItems()); } - /// Refreshes navigation activity colors when a media import changes state. - private void OnMediaImportStateChanged(MediaImportOwner owner) + /// Refreshes navigation activity colors when an import changes state, the transcription of a media file or the loading of web content. + private void OnImportStateChanged(ImportOwner owner) { this.InvokeAsync(() => { this.LoadNavItems(); this.StateHasChanged(); - }).Observe($"{nameof(MainLayout)}: refreshing the navigation after a media import change"); + }).Observe($"{nameof(MainLayout)}: refreshing the navigation after an import change"); } private IEnumerable GetNavItems() @@ -499,10 +504,11 @@ public partial class MainLayout : LayoutComponentBase, IMessageBusReceiver, ILan var defaultLightColor = palette.DarkLighten; var defaultDarkColor = palette.GrayLight; var mediaSnapshots = this.MediaTranscriptionService.GetSnapshots(); - var hasActiveChatMedia = mediaSnapshots.Any(snapshot => snapshot is { IsBusy: true, Owner.Kind: MediaImportOwnerKind.CHAT }); - var hasActiveAssistantMedia = mediaSnapshots.Any(snapshot => snapshot is { IsBusy: true, Owner.Kind: MediaImportOwnerKind.ASSISTANT or MediaImportOwnerKind.VISUAL_BRIEFING }); + var hasActiveChatMedia = mediaSnapshots.Any(snapshot => snapshot is { IsBusy: true, Owner.Kind: ImportOwnerKind.CHAT }); + var hasActiveAssistantMedia = mediaSnapshots.Any(snapshot => snapshot is { IsBusy: true, Owner.Kind: ImportOwnerKind.ASSISTANT or ImportOwnerKind.VISUAL_BRIEFING }); var hasActiveChatWork = this.AIJobService.HasActiveJobs || hasActiveChatMedia; - var hasActiveAssistantWork = this.AssistantSessionService.HasActiveSessions || hasActiveAssistantMedia; + var hasActiveWebContentImport = this.WebContentImportService.GetSnapshots().Count > 0; + var hasActiveAssistantWork = this.AssistantSessionService.HasActiveSessions || hasActiveAssistantMedia || hasActiveWebContentImport; var chatLightColor = hasActiveChatWork ? activityIndicatorLightColor : defaultLightColor; var chatDarkColor = hasActiveChatWork ? activityIndicatorDarkColor : defaultDarkColor; var assistantsLightColor = hasActiveAssistantWork ? activityIndicatorLightColor : defaultLightColor; @@ -830,7 +836,8 @@ public partial class MainLayout : LayoutComponentBase, IMessageBusReceiver, ILan public void Dispose() { - this.MediaTranscriptionService.StateChanged -= this.OnMediaImportStateChanged; + this.MediaTranscriptionService.StateChanged -= this.OnImportStateChanged; + this.WebContentImportService.StateChanged -= this.OnImportStateChanged; this.DataRestoreService.StateChanged -= this.OnDataRestoreStateChanged; this.CircuitState.ConnectionRestored -= this.OnConnectionRestored; this.MessageBus.Unregister(this); diff --git a/app/MindWork AI Studio/Plugins/configuration/plugin.lua b/app/MindWork AI Studio/Plugins/configuration/plugin.lua index dea073e78..01cbadaa7 100644 --- a/app/MindWork AI Studio/Plugins/configuration/plugin.lua +++ b/app/MindWork AI Studio/Plugins/configuration/plugin.lua @@ -991,6 +991,17 @@ CONFIG["SETTINGS"] = {} -- CONFIG["SETTINGS"]["DataAssistantsPage.CollapsedCategoryAssistants.AllowUserOverride"] = true -- CONFIG["SETTINGS"]["DataAssistantsPage.HiddenCategoryAssistants.AllowUserOverride"] = true +-- When users switch to the chat or to another assistant and come back, assistants still show +-- their inputs, their options, and their last result. Assistants keep them in memory only, +-- until users reset the assistant or quit AI Studio. You can preset whether assistants do so. +-- Requires AI Studio v26.11.2 or newer. Allowed values are: +-- KEEP_INPUTS: assistants keep the inputs. This is the default. +-- DISCARD_INPUTS: assistants start anew whenever users open them again. +-- CONFIG["SETTINGS"]["DataAssistantsPage.InputsWhenLeaving"] = "DISCARD_INPUTS" +-- +-- Allow users to change this option even though your organization set it above: +-- CONFIG["SETTINGS"]["DataAssistantsPage.InputsWhenLeaving.AllowUserOverride"] = true + -- Configure organization defaults for the Visual Briefing Assistant. -- The assistant turns documents, images, audio, and video into a self-contained interactive -- briefing. All settings below are defaults for new briefings; users can change them per briefing. diff --git a/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua b/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua index 8fba4e85f..9c870fd0f 100644 --- a/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua +++ b/app/MindWork AI Studio/Plugins/languages/de-de-43065dbc-78d0-45b7-92be-f14c2926e2dc/plugin.lua @@ -16011,6 +16011,12 @@ UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTBUILDER::T4 -- The language in which the assistants you build answer. UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTBUILDER::T42126731::INFORMAL"] = "Die Sprache, in der die von dir erstellten Assistenten antworten." +-- When you switch to the chat or to another assistant and come back, an assistant can still show your inputs, your options, and its last result. AI Studio keeps them in memory only, never on disk, until you reset the assistant or quit AI Studio. A text which you send to the assistant from elsewhere replaces them. An assistant which is still working keeps working in the background either way. +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T2267376752"] = "Wenn Sie zum Chat oder zu einem anderen Assistenten wechseln und zurückkehren, kann ein Assistent Ihre Eingaben, Ihre Optionen und sein letztes Ergebnis weiterhin anzeigen. AI Studio behält diese Inhalte nur im Arbeitsspeicher, nie auf der Festplatte, bis Sie den Assistenten zurücksetzen oder AI Studio beenden. Ein Text, den Sie dem Assistenten von anderer Stelle aus senden, ersetzt diese Inhalte. Ein Assistent, der gerade arbeitet, arbeitet in beiden Fällen im Hintergrund weiter." + +-- When you switch to the chat or to another assistant and come back, an assistant can still show your inputs, your options, and its last result. AI Studio keeps them in memory only, never on disk, until you reset the assistant or quit AI Studio. A text which you send to the assistant from elsewhere replaces them. An assistant which is still working keeps working in the background either way. +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T2267376752::INFORMAL"] = "Wenn du zum Chat oder zu einem anderen Assistenten wechselst und zurückkehrst, kann ein Assistent deine Eingaben, deine Optionen und sein letztes Ergebnis weiterhin anzeigen. AI Studio behält diese Inhalte nur im Arbeitsspeicher, nie auf der Festplatte, bis du den Assistenten zurücksetzt oder AI Studio beendest. Ein Text, den du dem Assistenten von anderer Stelle aus sendest, ersetzt diese Inhalte. Ein Assistent, der gerade arbeitet, arbeitet in beiden Fällen im Hintergrund weiter." + -- There are no categories to show or hide right now. UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T2279201345"] = "Derzeit gibt es keine Kategorien zum Ein- oder Ausblenden." @@ -16047,6 +16053,12 @@ UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T403 -- Assistant Settings UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T4124037832"] = "Assistenten-Einstellungen" +-- What should happen to your inputs when you leave an assistant? +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T700558677"] = "Was soll mit Ihren Eingaben geschehen, wenn Sie einen Assistenten verlassen?" + +-- What should happen to your inputs when you leave an assistant? +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T700558677::INFORMAL"] = "Was soll mit deinen Eingaben geschehen, wenn du einen Assistenten verlässt?" + -- Collapsing a category keeps the assistants page tidy. Choose whether AI Studio keeps offering its assistants elsewhere, e.g., in the "Send to ..." menu. UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T786145170"] = "Durch das Einklappen einer Kategorie bleibt die Assistentenseite übersichtlich. Legen Sie fest, ob AI Studio ihre Assistenten weiterhin an anderer Stelle anbietet, z. B. im Menü „Senden an …“." @@ -20202,6 +20214,9 @@ UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T1402851833 -- Welcome UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T1485461907"] = "Willkommen" +-- Keep my inputs and the last result until I reset the assistant or quit AI Studio +UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T1488089083"] = "Behalte meine Eingaben und das letzte Ergebnis, bis ich den Assistenten zurücksetze oder AI Studio beende" + -- Assistants UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T1614176092"] = "Assistenten" @@ -20325,6 +20340,9 @@ UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T453866521" -- Chat UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T578410699"] = "Chat" +-- Reset the assistant, so that it starts anew next time +UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T715634053"] = "Setze den Assistenten zurück, damit er beim nächsten Mal von vorn beginnt" + -- When possible, use the LLM provider which was used for each chat in the first place UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T75376144"] = "Wenn möglich, den LLM-Anbieter verwenden, der ursprünglich für den jeweiligen Chat verwendet wurde" diff --git a/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua b/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua index bc1ee7dc8..e43a091fb 100644 --- a/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua +++ b/app/MindWork AI Studio/Plugins/languages/en-us-97dfb1ba-50c4-4440-8dfa-6575daf543c8/plugin.lua @@ -16011,6 +16011,12 @@ UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTBUILDER::T4 -- The language in which the assistants you build answer. UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTBUILDER::T42126731::INFORMAL"] = "The language in which the assistants you build answer." +-- When you switch to the chat or to another assistant and come back, an assistant can still show your inputs, your options, and its last result. AI Studio keeps them in memory only, never on disk, until you reset the assistant or quit AI Studio. A text which you send to the assistant from elsewhere replaces them. An assistant which is still working keeps working in the background either way. +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T2267376752"] = "When you switch to the chat or to another assistant and come back, an assistant can still show your inputs, your options, and its last result. AI Studio keeps them in memory only, never on disk, until you reset the assistant or quit AI Studio. A text which you send to the assistant from elsewhere replaces them. An assistant which is still working keeps working in the background either way." + +-- When you switch to the chat or to another assistant and come back, an assistant can still show your inputs, your options, and its last result. AI Studio keeps them in memory only, never on disk, until you reset the assistant or quit AI Studio. A text which you send to the assistant from elsewhere replaces them. An assistant which is still working keeps working in the background either way. +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T2267376752::INFORMAL"] = "When you switch to the chat or to another assistant and come back, an assistant can still show your inputs, your options, and its last result. AI Studio keeps them in memory only, never on disk, until you reset the assistant or quit AI Studio. A text which you send to the assistant from elsewhere replaces them. An assistant which is still working keeps working in the background either way." + -- There are no categories to show or hide right now. UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T2279201345"] = "There are no categories to show or hide right now." @@ -16047,6 +16053,12 @@ UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T403 -- Assistant Settings UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T4124037832"] = "Assistant Settings" +-- What should happen to your inputs when you leave an assistant? +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T700558677"] = "What should happen to your inputs when you leave an assistant?" + +-- What should happen to your inputs when you leave an assistant? +UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T700558677::INFORMAL"] = "What should happen to your inputs when you leave an assistant?" + -- Collapsing a category keeps the assistants page tidy. Choose whether AI Studio keeps offering its assistants elsewhere, e.g., in the "Send to ..." menu. UI_TEXT_CONTENT["AISTUDIO::DIALOGS::SETTINGS::SETTINGSDIALOGASSISTANTSPAGE::T786145170"] = "Collapsing a category keeps the assistants page tidy. Choose whether AI Studio keeps offering its assistants elsewhere, e.g., in the \"Send to ...\" menu." @@ -20202,6 +20214,9 @@ UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T1402851833 -- Welcome UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T1485461907"] = "Welcome" +-- Keep my inputs and the last result until I reset the assistant or quit AI Studio +UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T1488089083"] = "Keep my inputs and the last result until I reset the assistant or quit AI Studio" + -- Assistants UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T1614176092"] = "Assistants" @@ -20325,6 +20340,9 @@ UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T453866521" -- Chat UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T578410699"] = "Chat" +-- Reset the assistant, so that it starts anew next time +UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T715634053"] = "Reset the assistant, so that it starts anew next time" + -- When possible, use the LLM provider which was used for each chat in the first place UI_TEXT_CONTENT["AISTUDIO::SETTINGS::CONFIGURATIONSELECTDATAFACTORY::T75376144"] = "When possible, use the LLM provider which was used for each chat in the first place" diff --git a/app/MindWork AI Studio/Program.cs b/app/MindWork AI Studio/Program.cs index ba8a93081..8ac9d18b0 100644 --- a/app/MindWork AI Studio/Program.cs +++ b/app/MindWork AI Studio/Program.cs @@ -205,6 +205,7 @@ internal sealed class Program builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/app/MindWork AI Studio/Settings/ConfigurationSelectDataFactory.cs b/app/MindWork AI Studio/Settings/ConfigurationSelectDataFactory.cs index ba075efda..e37610197 100644 --- a/app/MindWork AI Studio/Settings/ConfigurationSelectDataFactory.cs +++ b/app/MindWork AI Studio/Settings/ConfigurationSelectDataFactory.cs @@ -45,6 +45,12 @@ public static class ConfigurationSelectDataFactory yield return new(TB("""Treat the assistants as if they did not exist, e.g., not in the "Send to ..." menu"""), AssistantOfferBehavior.TREAT_AS_ABSENT); } + public static IEnumerable> GetAssistantInputsWhenLeavingData() + { + yield return new(TB("Keep my inputs and the last result until I reset the assistant or quit AI Studio"), AssistantInputsWhenLeaving.KEEP_INPUTS); + yield return new(TB("Reset the assistant, so that it starts anew next time"), AssistantInputsWhenLeaving.DISCARD_INPUTS); + } + public static IEnumerable> GetLoadingChatProviderBehavior() { yield return new(TB("When possible, use the LLM provider which was used for each chat in the first place"), LoadingChatProviderBehavior.USE_CHAT_PROVIDER_IF_AVAILABLE); diff --git a/app/MindWork AI Studio/Settings/DataModel/AssistantInputsWhenLeaving.cs b/app/MindWork AI Studio/Settings/DataModel/AssistantInputsWhenLeaving.cs new file mode 100644 index 000000000..026dd27d5 --- /dev/null +++ b/app/MindWork AI Studio/Settings/DataModel/AssistantInputsWhenLeaving.cs @@ -0,0 +1,18 @@ +namespace AIStudio.Settings.DataModel; + +/// +/// What happens to the inputs of an assistant when the user leaves it, e.g., for the chat or for another assistant. +/// +public enum AssistantInputsWhenLeaving +{ + /// + /// The assistant keeps the inputs, the options, and its last result in memory until the user resets it, sends + /// a new text to it, or quits AI Studio. + /// + KEEP_INPUTS, + + /// + /// The assistant starts anew when the user opens it again. A run which goes on keeps its state all the same. + /// + DISCARD_INPUTS, +} \ No newline at end of file diff --git a/app/MindWork AI Studio/Settings/DataModel/DataAssistantsPage.cs b/app/MindWork AI Studio/Settings/DataModel/DataAssistantsPage.cs index dd5801a84..38ed55983 100644 --- a/app/MindWork AI Studio/Settings/DataModel/DataAssistantsPage.cs +++ b/app/MindWork AI Studio/Settings/DataModel/DataAssistantsPage.cs @@ -5,14 +5,15 @@ using AIStudio.Tools.PluginSystem; namespace AIStudio.Settings.DataModel; /// -/// The settings of the assistants page: the categories the user collapsed or hid, and what that means for -/// their assistants. +/// The settings of the assistants page: the categories the user collapsed or hid, what that means for their +/// assistants, and whether assistants keep the inputs of the user when the user leaves them. /// /// /// Collapsing and hiding are choices of the user alone and never managed: both only take something out of /// sight. Your organization disables categories elsewhere, see DataApp.DisabledAssistantCategories. It may, /// however, preset or lock the two options which decide whether AI Studio keeps offering the assistants of -/// collapsed and hidden categories, e.g., in the "Send to ..." menu.

+/// collapsed and hidden categories, e.g., in the "Send to ..." menu, and the option which decides whether +/// assistants keep the inputs of the user when the user leaves them.

/// Ask AssistantCategoryRules instead of reading the categories: CORE counts as COMMON there, and custom /// categories are compared without regard to case. ///
@@ -62,4 +63,14 @@ public sealed class DataAssistantsPage(Expression /// they did not exist by default. /// public AssistantOfferBehavior HiddenCategoryAssistants { get; set; } = ManagedConfiguration.Register(configSelection, n => n.HiddenCategoryAssistants, AssistantOfferBehavior.TREAT_AS_ABSENT); + + /// + /// What happens to the inputs of an assistant when the user leaves it, e.g., for the chat or for another assistant. + /// + /// + /// By default, an assistant keeps them in memory, so that a look into the chat loses nothing. Users and + /// organizations who prefer an assistant which starts anew whenever it opens, as before v26.11.2, choose + /// DISCARD_INPUTS. See AssistantBase.KeepsInputsWhenLeaving. + /// + public AssistantInputsWhenLeaving InputsWhenLeaving { get; set; } = ManagedConfiguration.Register(configSelection, n => n.InputsWhenLeaving, AssistantInputsWhenLeaving.KEEP_INPUTS); } \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionService.cs b/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionService.cs index 1644c33bd..8a488cd65 100644 --- a/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionService.cs +++ b/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionService.cs @@ -88,6 +88,11 @@ public sealed class AssistantSessionService(MessageBus messageBus) ///
private readonly ConcurrentDictionary sessions = new(); + /// + /// Stores one draft per session key, see . + /// + private readonly ConcurrentDictionary drafts = new(); + /// /// Gets whether at least one assistant session is still active. /// @@ -142,6 +147,47 @@ public sealed class AssistantSessionService(MessageBus messageBus) return ((ICollection>)this.sessions).Remove(new(key, session)) ? snapshot : null; } + /// + /// Stores what an assistant holds when the user leaves it, so that it is there again when the user comes back. + /// + /// + /// A draft is not a run: neither nor sees it, so + /// the assistant overview shows no status for it, and AI Studio may close without asking. It lives in + /// memory only, until AI Studio closes, the user resets the assistant, or a text is sent to it. A newer + /// draft replaces the older one. A draft holds everything its assistant captures, such as the chat + /// thread, attached files, or the results of a batch, so there is at most one per assistant. + /// + /// The assistant session key. + /// The user-visible assistant title. + /// The assistant chat thread, if one exists. + /// The assistant component state. + public void SaveDraft(AssistantSessionKey key, string title, ChatThread? chatThread, Dictionary state) + { + var now = DateTimeOffset.Now; + this.drafts[key] = new() + { + SessionId = Guid.NewGuid(), + Key = key, + Title = title, + Status = AssistantSessionStatus.NONE, + StartedAt = now, + UpdatedAt = now, + ChatThread = chatThread, + State = new Dictionary(state, StringComparer.Ordinal), + }; + } + + /// + /// Tries to get and remove the draft of an assistant. + /// + /// + /// The assistant takes its draft once it opens and keeps it until the user leaves it again, which + /// stores a new draft. So a draft never lives in two places. + /// + /// The assistant session key to look up and remove. + /// The removed draft, or null when there is none. + public AssistantSessionSnapshot? TryTakeDraft(AssistantSessionKey key) => this.drafts.TryRemove(key, out var draft) ? draft : null; + /// /// Starts a new assistant session when no active session exists for the key. /// @@ -279,11 +325,12 @@ public sealed class AssistantSessionService(MessageBus messageBus) } /// - /// Clears an inactive assistant session. + /// Clears an inactive assistant session and the draft of the assistant. /// /// The assistant session key to clear. public async Task ClearAsync(AssistantSessionKey key) { + this.drafts.TryRemove(key, out _); if (!this.sessions.TryGetValue(key, out var session)) return; @@ -304,11 +351,14 @@ public sealed class AssistantSessionService(MessageBus messageBus) } /// - /// Clears all inactive sessions for a component. + /// Clears all inactive sessions and all drafts for a component. /// - /// The component whose inactive sessions should be cleared. + /// The component whose inactive sessions and drafts should be cleared. public async Task ClearInactiveSessionsForComponentAsync(Components component) { + foreach (var draftKey in this.drafts.Keys.Where(key => key.Component == component)) + this.drafts.TryRemove(draftKey, out _); + var matchingKeys = this.sessions .Where(pair => pair.Key.Component == component && pair.Value.Status is not AssistantSessionStatus.RUNNING and not AssistantSessionStatus.CANCELING) .Select(pair => pair.Key) diff --git a/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionSnapshotField.cs b/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionSnapshotField.cs index 69ce9d51f..019f032eb 100644 --- a/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionSnapshotField.cs +++ b/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionSnapshotField.cs @@ -13,9 +13,11 @@ public sealed record AssistantSessionSnapshotField : IAssistantSessionSnapsho /// Initializes a new typed snapshot field. ///
/// The captured value. - public AssistantSessionSnapshotField(T value) + /// Whether another value of this field means that the assistant changed, see CountsAsChange. + public AssistantSessionSnapshotField(T value, bool countsAsChange = true) { this.Value = value; + this.CountsAsChange = countsAsChange; } /// @@ -26,6 +28,9 @@ public sealed record AssistantSessionSnapshotField : IAssistantSessionSnapsho /// public Type ValueType => typeof(T); + /// + public bool CountsAsChange { get; } + /// public bool TryRead(out TValue? value) { @@ -56,6 +61,10 @@ public sealed record AssistantSessionSnapshotField : IAssistantSessionSnapsho if (value is null || otherValue is null) return false; + // A value which a snapshot holds as a copy of its own, e.g., the state of an assistant plugin, compares its content itself: + if (value is IAssistantSessionValue sessionValue) + return sessionValue.HasSameValueAs(otherValue); + // Nobody can change a string or a copied value type behind our back: if (value is string || value.GetType().IsValueType) return value.Equals(otherValue); diff --git a/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionStateKey.cs b/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionStateKey.cs index 8cab0f0cf..8b93abc28 100644 --- a/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionStateKey.cs +++ b/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionStateKey.cs @@ -10,9 +10,13 @@ public readonly record struct AssistantSessionStateKey /// Initializes a new assistant session state key. /// /// The stable dictionary name used in assistant session snapshots. - public AssistantSessionStateKey(string name) + /// Whether a draft leaves the value out, see . + /// Whether the value follows from other values, see IsDerived. + public AssistantSessionStateKey(string name, bool isKeptOutOfDrafts = false, bool isDerived = false) { this.Name = name; + this.IsKeptOutOfDrafts = isKeptOutOfDrafts; + this.IsDerived = isDerived; } /// @@ -20,6 +24,28 @@ public readonly record struct AssistantSessionStateKey /// public string Name { get; } + /// + /// Gets whether an assistant restores the value from a run only, never from a draft. + /// + /// + /// This is meant for flags of work in progress, such as reading a web page. An assistant stores a draft + /// when the user leaves it while no run goes on, and work outside of a run ends with the component which + /// did it. A flag restored from a draft would therefore stay set and could keep the form locked. Left + /// out, it keeps the value which a freshly opened assistant starts with. + /// + public bool IsKeptOutOfDrafts { get; } + + /// + /// Gets whether the value follows from other values, such as whether the form is valid, or is a cache. + /// + /// + /// A draft restores such a value, but it does not count as a change of the assistant: when the user leaves an + /// assistant, it stores a draft only when something else changed, see AssistantLowerBase.IsWorthADraft. + /// A cache which fills while the assistant renders, e.g., the images of an assistant plugin, would + /// otherwise make every assistant look changed as soon as it was shown. + /// + public bool IsDerived { get; } + /// /// Returns the stable dictionary name. /// diff --git a/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionStateReader.cs b/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionStateReader.cs index 4b826ed69..83aa2c529 100644 --- a/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionStateReader.cs +++ b/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionStateReader.cs @@ -7,10 +7,21 @@ namespace AIStudio.Tools.AssistantSessions; ///
/// The captured snapshot fields. /// The user-visible assistant title. -public sealed class AssistantSessionStateReader(IReadOnlyDictionary fields, string assistantTitle) +/// Whether the fields come from a draft, which an assistant stored when the user left it, rather than from a run. A draft restores no field whose key is kept out of drafts, see . +public sealed class AssistantSessionStateReader(IReadOnlyDictionary fields, string assistantTitle, bool isDraft = false) { private static readonly ILogger LOG = Program.LOGGER_FACTORY.CreateLogger(); - + + /// + /// Gets whether the fields come from a draft rather than from a run. + /// + /// + /// An assistant whose state partly follows from something outside of it, such as a plugin or a policy in + /// the settings, asks this to restore from a draft only what the user entered: the rest may have changed + /// while the user was elsewhere. + /// + public bool IsDraft => isDraft; + /// /// Restores a typed value when it exists in the snapshot. /// @@ -94,6 +105,9 @@ public sealed class AssistantSessionStateReader(IReadOnlyDictionary(AssistantSessionStateKey key, out T? value) { value = default; + if (isDraft && key.IsKeptOutOfDrafts) + return false; + if (!fields.TryGetValue(key.Name, out var field)) return false; diff --git a/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionStateWriter.cs b/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionStateWriter.cs index e57d3c6cc..c15712e7e 100644 --- a/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionStateWriter.cs +++ b/app/MindWork AI Studio/Tools/AssistantSessions/AssistantSessionStateWriter.cs @@ -20,7 +20,7 @@ public sealed class AssistantSessionStateWriter /// The captured value. public void Set(AssistantSessionStateKey key, T value) { - this.fields[key.Name] = new AssistantSessionSnapshotField(value); + this.fields[key.Name] = new AssistantSessionSnapshotField(value, countsAsChange: !key.IsDerived && !key.IsKeptOutOfDrafts); } /// diff --git a/app/MindWork AI Studio/Tools/AssistantSessions/IAssistantSessionSnapshotField.cs b/app/MindWork AI Studio/Tools/AssistantSessions/IAssistantSessionSnapshotField.cs index 590834911..6f2158701 100644 --- a/app/MindWork AI Studio/Tools/AssistantSessions/IAssistantSessionSnapshotField.cs +++ b/app/MindWork AI Studio/Tools/AssistantSessions/IAssistantSessionSnapshotField.cs @@ -10,6 +10,16 @@ public interface IAssistantSessionSnapshotField /// Type ValueType { get; } + /// + /// Gets whether another value of this field means that the assistant changed. + /// + /// + /// Not so for a value which follows from other values or is a cache, see AssistantSessionStateKey.IsDerived, + /// nor for a flag of work in progress, see AssistantSessionStateKey.IsKeptOutOfDrafts: neither is a change + /// the user made. + /// + bool CountsAsChange { get; } + /// /// Tries to read the captured value as the requested type. /// diff --git a/app/MindWork AI Studio/Tools/AssistantSessions/IAssistantSessionValue.cs b/app/MindWork AI Studio/Tools/AssistantSessions/IAssistantSessionValue.cs new file mode 100644 index 000000000..ed5885421 --- /dev/null +++ b/app/MindWork AI Studio/Tools/AssistantSessions/IAssistantSessionValue.cs @@ -0,0 +1,20 @@ +namespace AIStudio.Tools.AssistantSessions; + +/// +/// A value of an assistant session which tells by itself whether another value holds the same. +/// +/// +/// A snapshot compares most values by their reference, since an object may change without getting a new +/// one, see IAssistantSessionSnapshotField.HasSameValueAs. A value which the assistant captures as a copy +/// of its own, such as the state of an assistant plugin, gets a new reference with every snapshot, though, +/// and would always count as changed. Such a value compares its content instead. +/// +public interface IAssistantSessionValue +{ + /// + /// Tells whether another value holds the same content as this one. + /// + /// The value to compare with. + /// true when both values hold the same content; otherwise, false. + bool HasSameValueAs(object other); +} \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/ComponentsExtensions.cs b/app/MindWork AI Studio/Tools/ComponentsExtensions.cs index 6931f7186..979e313d8 100644 --- a/app/MindWork AI Studio/Tools/ComponentsExtensions.cs +++ b/app/MindWork AI Studio/Tools/ComponentsExtensions.cs @@ -1,7 +1,7 @@ using AIStudio.Provider; using AIStudio.Settings; using AIStudio.Settings.DataModel; -using AIStudio.Tools.Media; +using AIStudio.Tools.Imports; using AIStudio.Tools.PluginSystem; namespace AIStudio.Tools; @@ -94,14 +94,14 @@ public static class ComponentsExtensions }; /// - /// Gets the kind of media-import owner a component creates for its attachments. + /// Gets the kind of import owner a component creates for its attachments. /// - /// The media-import owner kind. - public MediaImportOwnerKind MediaOwnerKind => component switch + /// The import owner kind. + public ImportOwnerKind ImportOwnerKind => component switch { - Components.VISUAL_BRIEFING_ASSISTANT => MediaImportOwnerKind.VISUAL_BRIEFING, + Components.VISUAL_BRIEFING_ASSISTANT => ImportOwnerKind.VISUAL_BRIEFING, - _ => MediaImportOwnerKind.ASSISTANT, + _ => ImportOwnerKind.ASSISTANT, }; public bool AllowSendTo => component switch diff --git a/app/MindWork AI Studio/Tools/Imports/ImportOwner.cs b/app/MindWork AI Studio/Tools/Imports/ImportOwner.cs new file mode 100644 index 000000000..b456b423e --- /dev/null +++ b/app/MindWork AI Studio/Tools/Imports/ImportOwner.cs @@ -0,0 +1,18 @@ +using AIStudio.Tools.AssistantSessions; + +namespace AIStudio.Tools.Imports; + +/// Identifies the chat, assistant, or visual briefing that owns an import, e.g., the transcription of a media file. +public readonly record struct ImportOwner(ImportOwnerKind Kind, string Id) +{ + public static ImportOwner ForChat(Guid chatId) => new(ImportOwnerKind.CHAT, chatId.ToString("N")); + + public static ImportOwner ForAssistant(AssistantSessionKey key) => new(ImportOwnerKind.ASSISTANT, key.ToString()); + + /// + /// Creates a persistent import owner for a visual briefing. + /// + /// The stable briefing identifier. + /// The import owner. + public static ImportOwner ForVisualBriefing(Guid briefingId) => new(ImportOwnerKind.VISUAL_BRIEFING, briefingId.ToString("D")); +} \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Media/MediaImportOwnerKind.cs b/app/MindWork AI Studio/Tools/Imports/ImportOwnerKind.cs similarity index 74% rename from app/MindWork AI Studio/Tools/Media/MediaImportOwnerKind.cs rename to app/MindWork AI Studio/Tools/Imports/ImportOwnerKind.cs index 781a1abab..007db5e24 100644 --- a/app/MindWork AI Studio/Tools/Media/MediaImportOwnerKind.cs +++ b/app/MindWork AI Studio/Tools/Imports/ImportOwnerKind.cs @@ -1,7 +1,7 @@ -namespace AIStudio.Tools.Media; +namespace AIStudio.Tools.Imports; -/// Supported persistent media-operation owners. -public enum MediaImportOwnerKind +/// The kinds of owners of an import, see ImportOwner. +public enum ImportOwnerKind { CHAT, ASSISTANT, @@ -13,7 +13,7 @@ public enum MediaImportOwnerKind /// A visual briefing cannot use : that kind is keyed by an assistant /// session, which ends when the user navigates away or closes the app. A briefing is a stored /// document that outlives both, and its transcripts are stored next to it. The owner is - /// therefore keyed by the briefing ID, see . + /// therefore keyed by the briefing ID, see . /// This is what lets AI Studio re-associate transcripts with the right briefing after a /// restart, and what lets the UI show a running import on the briefing it belongs to. /// diff --git a/app/MindWork AI Studio/Tools/Media/MediaImportOwnerKindExtensions.cs b/app/MindWork AI Studio/Tools/Imports/ImportOwnerKindExtensions.cs similarity index 65% rename from app/MindWork AI Studio/Tools/Media/MediaImportOwnerKindExtensions.cs rename to app/MindWork AI Studio/Tools/Imports/ImportOwnerKindExtensions.cs index f194417bf..3a3a67acb 100644 --- a/app/MindWork AI Studio/Tools/Media/MediaImportOwnerKindExtensions.cs +++ b/app/MindWork AI Studio/Tools/Imports/ImportOwnerKindExtensions.cs @@ -1,22 +1,22 @@ -namespace AIStudio.Tools.Media; +namespace AIStudio.Tools.Imports; -/// Capabilities of a media-import owner kind. -public static class MediaImportOwnerKindExtensions +/// Capabilities of an import owner kind. +public static class ImportOwnerKindExtensions { /// The owner kind to look up. - extension(MediaImportOwnerKind kind) + extension(ImportOwnerKind kind) { /// /// Gets whether the owner stores its own source list and transcripts. /// /// /// Owners that persist their own sources take the attached media over immediately and keep it - /// next to the stored document, see . The + /// next to the stored document, see . The /// attachment control must therefore neither wait for the transcription to finish before showing /// the file, nor deliver the completed transcripts back into its own list afterwards, because /// the owner already holds them. All other owners rely on that delivery instead. /// /// true when the owner persists its own sources. - public bool PersistsOwnSources => kind is MediaImportOwnerKind.VISUAL_BRIEFING; + public bool PersistsOwnSources => kind is ImportOwnerKind.VISUAL_BRIEFING; } } \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Imports/ImportTarget.cs b/app/MindWork AI Studio/Tools/Imports/ImportTarget.cs new file mode 100644 index 000000000..f25a318ff --- /dev/null +++ b/app/MindWork AI Studio/Tools/Imports/ImportTarget.cs @@ -0,0 +1,4 @@ +namespace AIStudio.Tools.Imports; + +/// Identifies the concrete field inside an owner which an import fills, e.g., an attachment list or a file-content field. +public readonly record struct ImportTarget(ImportOwner Owner, string TargetId); \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Media/IMediaTranscriptStorage.cs b/app/MindWork AI Studio/Tools/Media/IMediaTranscriptStorage.cs index 0bebe1fb0..7eddf2d7f 100644 --- a/app/MindWork AI Studio/Tools/Media/IMediaTranscriptStorage.cs +++ b/app/MindWork AI Studio/Tools/Media/IMediaTranscriptStorage.cs @@ -1,4 +1,5 @@ using AIStudio.Chat; +using AIStudio.Tools.Imports; namespace AIStudio.Tools.Media; @@ -8,22 +9,22 @@ namespace AIStudio.Tools.Media; public interface IMediaTranscriptStorage { /// - /// Determines whether this storage handles the specified media-import owner. + /// Determines whether this storage handles the specified import owner. /// - /// The feature-specific media-import owner. + /// The feature-specific import owner. /// when the transcript can be stored. - bool CanStore(MediaImportOwner owner); + bool CanStore(ImportOwner owner); /// /// Persists a completed transcript and returns the attachment exposed to the calling workflow. /// - /// The stable media-import target. + /// The stable import target. /// The original media path. /// The completed transcript text. /// The cancellation token. /// The attachment representing the persisted transcript. Task StoreAsync( - MediaImportTarget target, + ImportTarget target, string originalMediaPath, string transcript, CancellationToken token); diff --git a/app/MindWork AI Studio/Tools/Media/MediaImportDelivery.cs b/app/MindWork AI Studio/Tools/Media/MediaImportDelivery.cs index d2987776b..dda90f2b2 100644 --- a/app/MindWork AI Studio/Tools/Media/MediaImportDelivery.cs +++ b/app/MindWork AI Studio/Tools/Media/MediaImportDelivery.cs @@ -1,11 +1,12 @@ using AIStudio.Chat; +using AIStudio.Tools.Imports; namespace AIStudio.Tools.Media; /// Pending media results waiting for one concrete UI target. public sealed record MediaImportDelivery { - public required MediaImportTarget Target { get; init; } + public required ImportTarget Target { get; init; } public IReadOnlyList Attachments { get; init; } = []; diff --git a/app/MindWork AI Studio/Tools/Media/MediaImportOutcome.cs b/app/MindWork AI Studio/Tools/Media/MediaImportOutcome.cs index 33eeb1594..0768ef977 100644 --- a/app/MindWork AI Studio/Tools/Media/MediaImportOutcome.cs +++ b/app/MindWork AI Studio/Tools/Media/MediaImportOutcome.cs @@ -1,9 +1,11 @@ +using AIStudio.Tools.Imports; + namespace AIStudio.Tools.Media; /// Terminal batch outcome retained until its owner is displayed. public sealed record MediaImportOutcome { - public required MediaImportOwner Owner { get; init; } + public required ImportOwner Owner { get; init; } public required MediaImportStatus Status { get; init; } diff --git a/app/MindWork AI Studio/Tools/Media/MediaImportOwner.cs b/app/MindWork AI Studio/Tools/Media/MediaImportOwner.cs deleted file mode 100644 index 698928334..000000000 --- a/app/MindWork AI Studio/Tools/Media/MediaImportOwner.cs +++ /dev/null @@ -1,18 +0,0 @@ -using AIStudio.Tools.AssistantSessions; - -namespace AIStudio.Tools.Media; - -/// Identifies the chat or assistant that owns a media import. -public readonly record struct MediaImportOwner(MediaImportOwnerKind Kind, string Id) -{ - public static MediaImportOwner ForChat(Guid chatId) => new(MediaImportOwnerKind.CHAT, chatId.ToString("N")); - - public static MediaImportOwner ForAssistant(AssistantSessionKey key) => new(MediaImportOwnerKind.ASSISTANT, key.ToString()); - - /// - /// Creates a persistent media-import owner for a visual briefing. - /// - /// The stable briefing identifier. - /// The media-import owner. - public static MediaImportOwner ForVisualBriefing(Guid briefingId) => new(MediaImportOwnerKind.VISUAL_BRIEFING, briefingId.ToString("D")); -} \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Media/MediaImportSnapshot.cs b/app/MindWork AI Studio/Tools/Media/MediaImportSnapshot.cs index 92957d916..7def093a7 100644 --- a/app/MindWork AI Studio/Tools/Media/MediaImportSnapshot.cs +++ b/app/MindWork AI Studio/Tools/Media/MediaImportSnapshot.cs @@ -1,11 +1,13 @@ +using AIStudio.Tools.Imports; + namespace AIStudio.Tools.Media; /// Copied owner-specific state suitable for rendering after navigation. public sealed record MediaImportSnapshot { - public required MediaImportOwner Owner { get; init; } + public required ImportOwner Owner { get; init; } - public required MediaImportTarget Target { get; init; } + public required ImportTarget Target { get; init; } public required MediaTranscriptionPhase Phase { get; init; } diff --git a/app/MindWork AI Studio/Tools/Media/MediaImportTarget.cs b/app/MindWork AI Studio/Tools/Media/MediaImportTarget.cs deleted file mode 100644 index 9ea4e68c0..000000000 --- a/app/MindWork AI Studio/Tools/Media/MediaImportTarget.cs +++ /dev/null @@ -1,4 +0,0 @@ -namespace AIStudio.Tools.Media; - -/// Identifies the concrete attachment or file-content field inside an owner. -public readonly record struct MediaImportTarget(MediaImportOwner Owner, string TargetId); \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/PluginSystem/Assistants/DataModel/AssistantState.cs b/app/MindWork AI Studio/Tools/PluginSystem/Assistants/DataModel/AssistantState.cs index 9fd0b5f8a..351a95fda 100644 --- a/app/MindWork AI Studio/Tools/PluginSystem/Assistants/DataModel/AssistantState.cs +++ b/app/MindWork AI Studio/Tools/PluginSystem/Assistants/DataModel/AssistantState.cs @@ -1,10 +1,12 @@ using AIStudio.Assistants.Dynamic; using AIStudio.Chat; +using AIStudio.Tools.AssistantSessions; + using Lua; namespace AIStudio.Tools.PluginSystem.Assistants.DataModel; -public sealed class AssistantState +public sealed class AssistantState : IAssistantSessionValue { public readonly Dictionary Text = new(StringComparer.Ordinal); public readonly Dictionary SingleSelect = new(StringComparer.Ordinal); @@ -36,17 +38,22 @@ public sealed class AssistantState /// /// Copies all dynamic assistant state values from another state instance. /// + /// + /// The copy shares nothing with the other state, not even the states of web content, file content, or + /// attachments, which the form changes in place. A snapshot of an assistant session holds such a copy, and + /// it must neither change along with the form nor look unchanged when the form changed one of them. + /// /// The state instance to copy from. public void CopyFrom(AssistantState other) { this.Clear(); CopyDictionary(other.Text, this.Text); CopyDictionary(other.SingleSelect, this.SingleSelect); - CopyDictionary(other.MultiSelect, this.MultiSelect); + CopyDictionary(other.MultiSelect, this.MultiSelect, values => new HashSet(values, values.Comparer)); CopyDictionary(other.Booleans, this.Booleans); - CopyDictionary(other.WebContent, this.WebContent); - CopyDictionary(other.FileContent, this.FileContent); - CopyDictionary(other.FileAttachments, this.FileAttachments); + CopyDictionary(other.WebContent, this.WebContent, state => state.Copy()); + CopyDictionary(other.FileContent, this.FileContent, state => state.Copy()); + CopyDictionary(other.FileAttachments, this.FileAttachments, state => state.Copy()); CopyDictionary(other.Colors, this.Colors); CopyDictionary(other.Dates, this.Dates); CopyDictionary(other.DateRanges, this.DateRanges); @@ -64,6 +71,39 @@ public sealed class AssistantState return clone; } + /// + /// Clears the flags of work in progress, such as a content cleaner which runs for a web page. + /// + /// + /// Such work ends with the component which started it. A draft restores the whole state, though, and a + /// flag restored from it would stay set and keep its field locked for good. The built-in assistants keep + /// such flags out of drafts by their keys, see AssistantSessionStateKey.IsKeptOutOfDrafts; the flags of an + /// assistant plugin live inside this state instead. + /// + public void ClearFlagsOfWorkInProgress() + { + foreach (var webContent in this.WebContent.Values) + webContent.CleanerIsRunning = false; + } + + /// + /// + /// Compares the values of all fields. Whether a web content cleaner runs is not an input and does not count, + /// see WebContentState.HasSameInputsAs. + /// + public bool HasSameValueAs(object other) => other is AssistantState otherState + && HaveSameEntries(this.Text, otherState.Text, IsSameText) + && HaveSameEntries(this.SingleSelect, otherState.SingleSelect, IsSameText) + && HaveSameEntries(this.MultiSelect, otherState.MultiSelect, (first, second) => first.SetEquals(second)) + && HaveSameEntries(this.Booleans, otherState.Booleans, (first, second) => first == second) + && HaveSameEntries(this.WebContent, otherState.WebContent, (first, second) => first.HasSameInputsAs(second)) + && HaveSameEntries(this.FileContent, otherState.FileContent, (first, second) => first.HasSameInputsAs(second)) + && HaveSameEntries(this.FileAttachments, otherState.FileAttachments, (first, second) => first.HasSameInputsAs(second)) + && HaveSameEntries(this.Colors, otherState.Colors, IsSameText) + && HaveSameEntries(this.Dates, otherState.Dates, IsSameText) + && HaveSameEntries(this.DateRanges, otherState.DateRanges, IsSameText) + && HaveSameEntries(this.Times, otherState.Times, IsSameText); + /// /// Copies all entries from one dictionary into another dictionary. /// @@ -71,12 +111,25 @@ public sealed class AssistantState /// The dictionary value type. /// The source dictionary. /// The target dictionary. - private static void CopyDictionary(Dictionary source, Dictionary target) where TKey : notnull + /// Copies a value which the form changes in place; null for a value nobody can change, such as a string. + private static void CopyDictionary(Dictionary source, Dictionary target, Func? copyValue = null) where TKey : notnull { foreach (var (key, value) in source) - target[key] = value; + target[key] = copyValue is null ? value : copyValue(value); } + /// + /// Tells whether two dictionaries hold the same keys with the same values. + /// + /// The dictionary value type. + /// The first dictionary. + /// The second dictionary. + /// Tells whether two values are the same. + /// true when both dictionaries hold the same entries; otherwise, false. + private static bool HaveSameEntries(Dictionary first, Dictionary second, Func isSame) => first.Count == second.Count && first.All(entry => second.TryGetValue(entry.Key, out var otherValue) && isSame(entry.Value, otherValue)); + + private static bool IsSameText(string first, string second) => string.Equals(first, second, StringComparison.Ordinal); + public bool TryApplyValue(string fieldName, LuaValue value, out string expectedType) { expectedType = string.Empty; diff --git a/app/MindWork AI Studio/Tools/PluginSystem/PluginConfiguration.cs b/app/MindWork AI Studio/Tools/PluginSystem/PluginConfiguration.cs index 003303ee2..74912e9f6 100644 --- a/app/MindWork AI Studio/Tools/PluginSystem/PluginConfiguration.cs +++ b/app/MindWork AI Studio/Tools/PluginSystem/PluginConfiguration.cs @@ -346,6 +346,9 @@ public sealed class PluginConfiguration(bool isInternal, LuaState state, PluginT ManagedConfiguration.TryProcessConfiguration(x => x.AssistantsPage, x => x.CollapsedCategoryAssistants, this.Id, settingsTable, dryRun); ManagedConfiguration.TryProcessConfiguration(x => x.AssistantsPage, x => x.HiddenCategoryAssistants, this.Id, settingsTable, dryRun); + // Config: do assistants keep the inputs of users when they leave them? + ManagedConfiguration.TryProcessConfiguration(x => x.AssistantsPage, x => x.InputsWhenLeaving, this.Id, settingsTable, dryRun); + // Config: prohibit some providers? ManagedConfiguration.TryProcessConfiguration(x => x.App, x => x.ProhibitedProviders, this.Id, settingsTable, dryRun); diff --git a/app/MindWork AI Studio/Tools/Services/MediaTranscriptionService.cs b/app/MindWork AI Studio/Tools/Services/MediaTranscriptionService.cs index fd649990f..9e3e6bf96 100644 --- a/app/MindWork AI Studio/Tools/Services/MediaTranscriptionService.cs +++ b/app/MindWork AI Studio/Tools/Services/MediaTranscriptionService.cs @@ -2,6 +2,7 @@ using AIStudio.Chat; using AIStudio.Provider; using AIStudio.Settings; using AIStudio.Settings.DataModel; +using AIStudio.Tools.Imports; using AIStudio.Tools.Media; using AIStudio.Tools.PluginSystem; using AIStudio.Tools.Rust; @@ -34,31 +35,31 @@ public sealed class MediaTranscriptionService( private readonly HashSet operations = []; /// The active or queued import operation for each owner. - private readonly Dictionary currentImports = []; + private readonly Dictionary currentImports = []; /// The latest active or unacknowledged terminal state for each owner. - private readonly Dictionary snapshots = []; + private readonly Dictionary snapshots = []; /// Successful results waiting for their concrete UI target. - private readonly Dictionary pendingDeliveries = []; + private readonly Dictionary pendingDeliveries = []; /// Terminal notifications waiting for their owner surface to be displayed. - private readonly Dictionary outcomes = []; + private readonly Dictionary outcomes = []; /// Owners whose complete file batches are managed by this service. - private readonly HashSet activeBatches = []; + private readonly HashSet activeBatches = []; /// Batch-level cancellation keeps Stop effective between two files. - private readonly Dictionary batchCancellations = []; + private readonly Dictionary batchCancellations = []; /// Prevents new work after disposal. private bool disposed; /// Raised only with the owner whose copied state changed. - public event Action? StateChanged; + public event Action? StateChanged; /// Gets whether one owner has queued, running, or canceling media work. - public bool IsBusy(MediaImportOwner owner) + public bool IsBusy(ImportOwner owner) { lock (this.stateLock) return this.activeBatches.Contains(owner); @@ -68,7 +69,7 @@ public sealed class MediaTranscriptionService( public bool HasUsableTranscriptionProvider => this.GetUsableProvider() is not null; /// Gets the last retained state for one owner. - public MediaImportSnapshot? GetSnapshot(MediaImportOwner owner) + public MediaImportSnapshot? GetSnapshot(ImportOwner owner) { lock (this.stateLock) return this.snapshots.GetValueOrDefault(owner); @@ -82,7 +83,7 @@ public sealed class MediaTranscriptionService( } /// Gets copied results that have not yet been applied by one target. - public MediaImportDelivery? GetPendingDelivery(MediaImportTarget target) + public MediaImportDelivery? GetPendingDelivery(ImportTarget target) { lock (this.stateLock) { @@ -118,7 +119,7 @@ public sealed class MediaTranscriptionService( } /// Consumes one terminal notification when its owner surface is displayed. - public MediaImportOutcome? TryConsumeOutcome(MediaImportOwner owner) + public MediaImportOutcome? TryConsumeOutcome(ImportOwner owner) { MediaImportOutcome? outcome; lock (this.stateLock) @@ -135,7 +136,7 @@ public sealed class MediaTranscriptionService( } /// Discards retained inactive state and deletes unclaimed managed transcript files. - public void ClearOwnerState(MediaImportOwner owner) + public void ClearOwnerState(ImportOwner owner) { List discardedAttachments = []; lock (this.stateLock) @@ -160,7 +161,7 @@ public sealed class MediaTranscriptionService( } /// Starts an owner-managed attachment batch and returns without holding the UI event handler. - public bool TryStartAttachmentBatch(IReadOnlyList mediaPaths, MediaImportTarget target, ChatThread? ownerChat = null) + public bool TryStartAttachmentBatch(IReadOnlyList mediaPaths, ImportTarget target, ChatThread? ownerChat = null) { this.ThrowIfDisposed(); if (mediaPaths.Count is 0) @@ -181,7 +182,7 @@ public sealed class MediaTranscriptionService( } /// Starts a reattachable file-content import for one stable assistant field. - public bool TryStartTextImport(string mediaPath, MediaImportTarget target) + public bool TryStartTextImport(string mediaPath, ImportTarget target) { this.ThrowIfDisposed(); lock (this.stateLock) @@ -199,7 +200,7 @@ public sealed class MediaTranscriptionService( } /// Completes a field import independently of the originating Blazor component. - private async Task RunTextImportAsync(string mediaPath, MediaImportTarget target) + private async Task RunTextImportAsync(string mediaPath, ImportTarget target) { CancellationTokenSource cancellation; lock (this.stateLock) @@ -259,7 +260,7 @@ public sealed class MediaTranscriptionService( /// The field which receives the transcript. /// The recording the transcript belongs to. /// The transcript as the provider returned it. - internal async Task AddCompletedTextAsync(MediaImportTarget target, string mediaPath, string transcript) + internal async Task AddCompletedTextAsync(ImportTarget target, string mediaPath, string transcript) { var text = await promptInjectionGuardService.SanitizeAsync(transcript, PromptInjectionSource.FileContent(mediaPath), reportingScope: null); lock (this.stateLock) @@ -274,7 +275,7 @@ public sealed class MediaTranscriptionService( } /// Serially transcribes a complete owner batch while retaining every successful result. - private async Task RunAttachmentBatchAsync(IReadOnlyList mediaPaths, MediaImportTarget target, ChatThread? ownerChat) + private async Task RunAttachmentBatchAsync(IReadOnlyList mediaPaths, ImportTarget target, ChatThread? ownerChat) { CancellationToken batchToken; lock (this.stateLock) @@ -364,7 +365,7 @@ public sealed class MediaTranscriptionService( } /// Adds a successful partial result to the retained owner snapshot. - private void AddCompletedAttachment(MediaImportTarget target, FileAttachment attachment) + private void AddCompletedAttachment(ImportTarget target, FileAttachment attachment) { lock (this.stateLock) { @@ -385,7 +386,7 @@ public sealed class MediaTranscriptionService( /// Media import target. /// Caller cancellation token. /// A typed terminal result. - private async Task TranscribeImportAsync(string mediaPath, MediaImportTarget target, CancellationToken token = default) + private async Task TranscribeImportAsync(string mediaPath, ImportTarget target, CancellationToken token = default) { this.ThrowIfDisposed(); var operation = this.CreateOperation(target, token); @@ -470,7 +471,7 @@ public sealed class MediaTranscriptionService( public Task TranscribeVoiceAsync(string mediaPath, CancellationToken token = default) => this.TranscribeAsync(mediaPath, token); /// Cancels only the queued or active operation belonging to one owner. - public async Task StopAsync(MediaImportOwner owner) + public async Task StopAsync(ImportOwner owner) { MediaOperation? operation; MediaImportSnapshot? snapshot; @@ -798,7 +799,7 @@ public sealed class MediaTranscriptionService( /// Optional visible media import target. /// Caller token linked to the operation. /// The registered operation. - private MediaOperation CreateOperation(MediaImportTarget? target, CancellationToken token) + private MediaOperation CreateOperation(ImportTarget? target, CancellationToken token) { var operation = new MediaOperation(target, token); lock (this.stateLock) @@ -818,7 +819,7 @@ public sealed class MediaTranscriptionService( } /// Updates and publishes copied state for exactly one owner. - private void UpdateImportState(MediaImportTarget target, string fileName, MediaTranscriptionPhase phase, double? progress, MediaImportStatus status) + private void UpdateImportState(ImportTarget target, string fileName, MediaTranscriptionPhase phase, double? progress, MediaImportStatus status) { var snapshot = new MediaImportSnapshot { @@ -838,7 +839,7 @@ public sealed class MediaTranscriptionService( /// Publishes one retained terminal result after an entire target batch ended. private void CompleteImport( - MediaImportTarget target, + ImportTarget target, string fileName, MediaImportStatus status, IReadOnlyList failures, @@ -869,14 +870,14 @@ public sealed class MediaTranscriptionService( } /// Publishes state changes without allowing one stale UI subscriber to fault a worker. - private void NotifyStateChanged(MediaImportOwner owner) + private void NotifyStateChanged(ImportOwner owner) { if (this.StateChanged is not { } stateChanged) return; foreach (var @delegate in stateChanged.GetInvocationList()) { - var handler = (Action)@delegate; + var handler = (Action)@delegate; try { @@ -984,14 +985,14 @@ public sealed class MediaTranscriptionService( /// Creates operation state linked to a caller token. /// Optional visible media import target. /// Caller cancellation token. - public MediaOperation(MediaImportTarget? target, CancellationToken token) + public MediaOperation(ImportTarget? target, CancellationToken token) { this.Target = target; this.Cancellation = CancellationTokenSource.CreateLinkedTokenSource(token); } /// Gets the optional visible import target; voice operations have none. - public MediaImportTarget? Target { get; } + public ImportTarget? Target { get; } /// Gets the unique temporary-path identifier. public Guid Id { get; } = Guid.NewGuid(); diff --git a/app/MindWork AI Studio/Tools/Services/PluginInstallService.Delete.cs b/app/MindWork AI Studio/Tools/Services/PluginInstallService.Delete.cs index c3b420558..c725f0118 100644 --- a/app/MindWork AI Studio/Tools/Services/PluginInstallService.Delete.cs +++ b/app/MindWork AI Studio/Tools/Services/PluginInstallService.Delete.cs @@ -1,6 +1,6 @@ using AIStudio.Settings; using AIStudio.Settings.DataModel; -using AIStudio.Tools.Media; +using AIStudio.Tools.Imports; using AIStudio.Tools.PluginSystem; using AIStudio.Tools.PluginSystem.Assistants; @@ -72,7 +72,7 @@ public sealed partial class PluginInstallService var ownerIdSuffix = $":{instanceId}"; return this.mediaTranscriptionService.GetSnapshots().Any(snapshot => - snapshot is { IsBusy: true, Owner.Kind: MediaImportOwnerKind.ASSISTANT } && + snapshot is { IsBusy: true, Owner.Kind: ImportOwnerKind.ASSISTANT } && snapshot.Owner.Id.EndsWith(ownerIdSuffix, StringComparison.Ordinal)); } diff --git a/app/MindWork AI Studio/Tools/Web/WebContentImportIssue.cs b/app/MindWork AI Studio/Tools/Web/WebContentImportIssue.cs new file mode 100644 index 000000000..6b995a9ec --- /dev/null +++ b/app/MindWork AI Studio/Tools/Web/WebContentImportIssue.cs @@ -0,0 +1,27 @@ +namespace AIStudio.Tools.Web; + +/// +/// What went wrong while loading web content, so that the reader can tell the user, see WebContentImportResult. +/// +public enum WebContentImportIssue +{ + /// + /// The content arrived as asked for. + /// + NONE, + + /// + /// The content arrived, but uncleaned, since no model is available for the content cleaner. + /// + NOT_CLEANED_NO_MODEL, + + /// + /// The content arrived, but uncleaned, since the model of the content cleaner gave no answer. + /// + NOT_CLEANED_NO_ANSWER, + + /// + /// The content could not be loaded, see WebContentImportResult.ErrorMessage. + /// + LOAD_FAILED, +} \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Web/WebContentImportRequest.cs b/app/MindWork AI Studio/Tools/Web/WebContentImportRequest.cs new file mode 100644 index 000000000..27576b532 --- /dev/null +++ b/app/MindWork AI Studio/Tools/Web/WebContentImportRequest.cs @@ -0,0 +1,9 @@ +namespace AIStudio.Tools.Web; + +/// +/// What the web content reader of an assistant asks the WebContentImportService to load. +/// +/// The address the user typed. +/// Whether the text content cleaner, an AI task, cleans the page. +/// The model of the assistant around the reader, which the cleaner falls back on, see WebContentImportService.GetCleanerProviderOptions. +public sealed record WebContentImportRequest(string Url, bool CleanContent, AIStudio.Settings.Provider AssistantProvider); \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Web/WebContentImportResult.cs b/app/MindWork AI Studio/Tools/Web/WebContentImportResult.cs new file mode 100644 index 000000000..26e8fa698 --- /dev/null +++ b/app/MindWork AI Studio/Tools/Web/WebContentImportResult.cs @@ -0,0 +1,10 @@ +namespace AIStudio.Tools.Web; + +/// +/// What loading web content brought, waiting for the reader of its field, see WebContentImportService.TryTakeResult. +/// +/// The address the content was loaded from. +/// The content, filtered for prompt injections. It is what arrived before an error, which may be nothing. +/// What went wrong, if anything. +/// Why the content could not be loaded, for ; null otherwise. +public sealed record WebContentImportResult(string Url, string Markdown, WebContentImportIssue Issue = WebContentImportIssue.NONE, string? ErrorMessage = null); \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Web/WebContentImportService.cs b/app/MindWork AI Studio/Tools/Web/WebContentImportService.cs new file mode 100644 index 000000000..45401c982 --- /dev/null +++ b/app/MindWork AI Studio/Tools/Web/WebContentImportService.cs @@ -0,0 +1,255 @@ +using AIStudio.AIOperations; +using AIStudio.AIOperations.TextContentCleaning; +using AIStudio.Components; +using AIStudio.Settings; +using AIStudio.Tools.Imports; +using AIStudio.Tools.Security; + +namespace AIStudio.Tools.Web; + +/// +/// Loads web content for the web content readers of assistants, in the background. +/// +/// +/// A reader goes away with its assistant when the user leaves it, while loading and above all cleaning a page +/// can take a minute. So the work runs here, keyed by the field it fills, see ImportTarget, and its result +/// waits until the reader of that field is there again, see TryTakeResult. This follows the transcription of +/// media files, see MediaTranscriptionService, with one difference: there is no common queue. Each field has +/// its own import, so several assistants, or several readers of an assistant plugin, load at the same time. +/// Only the same field cannot start a second import while its first one runs. +/// +public sealed class WebContentImportService( + WebPageRetrievalService webPageRetrievalService, + PromptInjectionGuardService promptInjectionGuardService, + TextContentCleaningOperation textContentCleaning, + AIOperationProviderResolver providerResolver, + SettingsManager settingsManager, + ILogger logger) +{ + /// + /// How long loading one page may take. + /// + /// + /// The user waits for this text, so it is shorter than what the tools allow themselves for the + /// pages they fetch. + /// + private const int TIMEOUT_SECONDS = 60; + + /// Protects the running imports and the waiting results. + private readonly Lock stateLock = new(); + + /// The state of each running import. + private readonly Dictionary runningImports = []; + + /// Results waiting for the reader of their field. + private readonly Dictionary results = []; + + /// Raised with the owner whose imports changed: one started, went on to its next step, or ended. + public event Action? StateChanged; + + /// + /// What the reader adds to the choice of the provider for the content cleaner. + /// + /// + /// 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. + /// + /// The settings, for the app-wide default. + /// The model of the assistant around the reader. + /// The options for the provider resolver. + internal static AIOperationProviderOptions GetCleanerProviderOptions(SettingsManager settingsManager, AIStudio.Settings.Provider assistantProvider) => new() + { + FallbackProviderIds = [assistantProvider.Id, settingsManager.AppDefaultProviderId], + OwnMinimumConfidenceAppliesToFallbacks = true, + }; + + /// Gets whether one of the fields of an owner is loading web content. + /// The owner, e.g., an assistant. + /// true while an import of the owner runs. + public bool IsBusy(ImportOwner owner) + { + lock (this.stateLock) + return this.runningImports.Keys.Any(target => target.Owner == owner); + } + + /// Gets the state of the import which fills a field, while it runs. + /// The field. + /// A copy of the state, or null when no import of the field runs. + public WebContentImportSnapshot? GetSnapshot(ImportTarget target) + { + lock (this.stateLock) + return this.runningImports.GetValueOrDefault(target); + } + + /// Gets copies of the states of all running imports, e.g., for the navigation. + public IReadOnlyCollection GetSnapshots() + { + lock (this.stateLock) + return [.. this.runningImports.Values]; + } + + /// + /// Starts loading web content into a field, unless an import of that field still runs. + /// + /// The field to fill. + /// What to load. + /// true when the import started. + public bool TryStart(ImportTarget target, WebContentImportRequest request) => this.Start(target, request, reportStep => this.ImportAsync(request, reportStep)) is not null; + + /// + /// Starts an import into a field, unless an import of that field still runs. + /// + /// + /// The import runs on the thread pool, not on the circuit of the reader which started it: the reader may + /// go away any moment. A new import replaces a result which its reader did not take yet. Tests hand in an + /// import of their own. + /// + /// The field to fill. + /// What the import loads, for its state and for the result of an import which failed unexpectedly. + /// The work, which reports each step it reaches. + /// The running import, or null when an import of the field still runs. + internal Task? Start(ImportTarget target, WebContentImportRequest request, Func, Task> import) + { + lock (this.stateLock) + { + if (!this.runningImports.TryAdd(target, new(target, request.Url, request.CleanContent, ReadWebContentSteps.LOADING))) + return null; + + this.results.Remove(target); + } + + this.NotifyStateChanged(target.Owner); + return Task.Run(() => this.RunAsync(target, request.Url, import)); + } + + /// + /// Takes the result which waits for a field, so that it is delivered exactly once. + /// + /// The field. + /// The result, or null when none waits. + public WebContentImportResult? TryTakeResult(ImportTarget target) + { + lock (this.stateLock) + return this.results.Remove(target, out var result) ? result : null; + } + + /// + /// Discards the results which wait for the fields of an owner, e.g., when the user resets the assistant. + /// + /// + /// A running import is left alone, as with media files: the assistant does not reset while one runs. + /// + /// The owner. + public void ClearOwnerState(ImportOwner owner) + { + lock (this.stateLock) + { + foreach (var target in this.results.Keys.Where(target => target.Owner == owner).ToList()) + this.results.Remove(target); + } + + this.NotifyStateChanged(owner); + } + + private async Task RunAsync(ImportTarget target, string url, Func, Task> import) + { + WebContentImportResult result; + try + { + result = await import(step => this.ReportStep(target, step)); + } + catch (Exception exception) + { + logger.LogWarning(exception, "Could not load the web content from '{ProvidedUrl}'.", url); + result = new(url, string.Empty, WebContentImportIssue.LOAD_FAILED, exception.Message); + } + + lock (this.stateLock) + { + this.runningImports.Remove(target); + this.results[target] = result; + } + + this.NotifyStateChanged(target.Owner); + } + + private void ReportStep(ImportTarget target, ReadWebContentSteps step) + { + lock (this.stateLock) + { + if (!this.runningImports.TryGetValue(target, out var snapshot)) + return; + + this.runningImports[target] = snapshot with { Step = step }; + } + + this.NotifyStateChanged(target.Owner); + } + + /// + /// Loads a page, filters it for prompt injections, and cleans it if asked to. + /// + /// + /// Never throws: the content which arrived before an error goes into the result, together with the error. + /// + private async Task ImportAsync(WebContentImportRequest request, Action reportStep) + { + var markdown = string.Empty; + try + { + // + // 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 webPageRetrievalService.RetrieveAsync( + new Uri(request.Url), + new WebPageRetrievalOptions + { + TimeoutSeconds = TIMEOUT_SECONDS, + TargetChosenByUser = true, + }); + + reportStep(ReadWebContentSteps.PARSING); + markdown = await promptInjectionGuardService.SanitizeAsync(retrievedPage.ExtractedPage.Markdown, PromptInjectionSource.WebContent(request.Url)); + if (!request.CleanContent) + return new(request.Url, markdown); + + var cleaningRequest = new TextContentCleaningRequest(markdown, request.Url); + var choice = providerResolver.Resolve(textContentCleaning, cleaningRequest, TextContentCleaningOperation.GetProviderSettings(settingsManager), GetCleanerProviderOptions(settingsManager, request.AssistantProvider)); + if (!choice.HasProvider) + return new(request.Url, markdown, WebContentImportIssue.NOT_CLEANED_NO_MODEL); + + reportStep(ReadWebContentSteps.CLEANING); + var cleaningResult = await textContentCleaning.RunAsync(cleaningRequest, new(choice.Provider)); + return new(request.Url, cleaningResult.Markdown, cleaningResult.IsCleaned ? WebContentImportIssue.NONE : WebContentImportIssue.NOT_CLEANED_NO_ANSWER); + } + catch (Exception exception) + { + logger.LogWarning(exception, "Could not load the web content from '{ProvidedUrl}'.", request.Url); + return new(request.Url, markdown, WebContentImportIssue.LOAD_FAILED, exception.Message); + } + } + + /// + /// Tells every handler about a change, so that a handler which throws keeps none of the others from hearing about it. + /// + private void NotifyStateChanged(ImportOwner owner) + { + if (this.StateChanged is not { } stateChanged) + return; + + foreach (var @delegate in stateChanged.GetInvocationList()) + { + try + { + ((Action)@delegate)(owner); + } + catch (Exception exception) + { + logger.LogError(exception, "A handler failed while it was told about a changed web content import."); + } + } + } +} \ No newline at end of file diff --git a/app/MindWork AI Studio/Tools/Web/WebContentImportSnapshot.cs b/app/MindWork AI Studio/Tools/Web/WebContentImportSnapshot.cs new file mode 100644 index 000000000..d20962e4d --- /dev/null +++ b/app/MindWork AI Studio/Tools/Web/WebContentImportSnapshot.cs @@ -0,0 +1,13 @@ +using AIStudio.Components; +using AIStudio.Tools.Imports; + +namespace AIStudio.Tools.Web; + +/// +/// A copy of the state of a running web content import, see WebContentImportService.GetSnapshot. +/// +/// The field the import fills. +/// The address the import loads. +/// Whether the import cleans the page. +/// The step the import is at: loading, parsing, or cleaning. +public sealed record WebContentImportSnapshot(ImportTarget Target, string Url, bool CleanContent, ReadWebContentSteps Step); \ No newline at end of file diff --git a/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md b/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md index 4af3a43c4..eb9553d7b 100644 --- a/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md +++ b/app/MindWork AI Studio/wwwroot/changelog/v26.11.2.md @@ -12,6 +12,7 @@ - Added the settings of chat compression to configuration plugins, so that organizations can preset or lock, among other options, which model writes the summary, the minimum confidence of that model, and what happens when a chat fills the context window. - Added the password encoding to the mail servers which organizations offer through configuration plugins. Depending on its configuration, a mail server may expect usernames and passwords with characters beyond ASCII in another encoding than UTF-8. With this setting, every mailbox on such a server signs in with the encoding your organization names. - Added the maximum pause between files of the Batch Processing Assistant to configuration plugins, so that organizations can preset or lock it, like the minimum pause. +- Added the option for leaving assistants to configuration plugins, so that organizations can preset or lock whether assistants keep the inputs of their users until they reset the assistant or quit AI Studio. - Improved how well the AI remembers what it looked up in a chat: for its earlier answers, it now knows which web pages it read, which searches it ran, and which sources it used. When you ask a follow-up question, it can read the page again instead of claiming that it never read it. - Improved follow-up questions about web pages which a tool found, such as the results of a web search: the Read Web Page tool may read these pages again later in the same chat, also after you restart AI Studio and also when it may otherwise read only addresses which stand in the chat. - Improved the texts of AI Studio: we corrected grammar mistakes, missing words, and punctuation in many English texts and improved the wording of some German ones. A few texts which every language showed in English are now translated as well. @@ -26,6 +27,7 @@ - Improved the chat while you wait for an answer: AI Studio now tells you when it is processing your prompt and when the model is thinking, instead of showing an animation alone. - Improved the chat when it nearly fills the context window of the selected model: before sending your message, AI Studio tells you and offers to compress the chat or to send your message anyway. With the gear in that notice, you can let AI Studio compress automatically or send without asking from then on. When compressing would not help, for example, because your message alone is too long, AI Studio tells you why. For a self-hosted model, enter its context window under "Override Model Limits" in the settings of the provider. - Improved the assistants when a request nearly fills the context window of the selected model: before sending it, AI Studio tells you, so that you can attach fewer or smaller files, or send the request anyway. +- Improved the assistants: when you switch to the chat or to another assistant and come back, the assistant still shows your inputs, your options, and its last result, until you reset it or quit AI Studio. With the gear on the assistants page, you can have assistants start anew instead. - Improved the settings of the AI tasks, which AI Studio hands to a model on its own, such as the data source selection or the text content cleaner, formerly called agents: for each of them, you can now set the minimum confidence its provider needs, and the provider selection tells you which model AI Studio uses when you choose none. - Improved classic RAG: when the model you chose for selecting data sources or validating retrieval contexts may not see the data sources of your chat, AI Studio now uses the model of the chat for this step instead of skipping it. - Improved the page numbers in the sources of your own documents: when a document opens without the page you clicked, AI Studio now tells you on which page the passage is and why it could not open the document there. This happens, for example, when AI Studio runs as a Flatpak, whose sandbox lets no page through, or when the program which shows the document does not allow choosing a page. In the Flatpak, the tooltip of a page number says so already. @@ -59,6 +61,9 @@ - Fixed the Mathematics prototype getting stuck for a long time when it checked a result with a very large factorial or power. Meanwhile, no other calculation could run. - Fixed AI Studio ceasing to work when many files in a folder of a local data source changed within a short time, e.g., during a software build or while a sync tool updated the folder. - Fixed transcripts of audio and video files which could miss whole passages. Before a transcription, AI Studio converts the file into a compact format, and it stored a few pieces of the sound in a way that many programs could not read. They then skipped up to half a minute of the recording at a time, so that the transcript lacked what was said there. +- Fixed the ERI server assistant, which could replace the embeddings, retrieval processes, and generated files of your first server with those of another server when you came back to the assistant. +- Fixed the document analysis assistant, which could give your selected policy the allowed tools of your first policy when you came back to an analysis that had run while you were elsewhere. +- Fixed assistants losing a web page which was still loading or being cleaned up when you left them. Loading now goes on in the background, and the text is there when you come back. - Upgraded several libraries to improve security. - Upgraded Tauri to v2.12.7. - Upgraded MudBlazor to v9.14.0. diff --git a/app/Tests/AIOperations/TextContentCleaningProviderTests.cs b/app/Tests/AIOperations/TextContentCleaningProviderTests.cs index 88f7c6592..209931498 100644 --- a/app/Tests/AIOperations/TextContentCleaningProviderTests.cs +++ b/app/Tests/AIOperations/TextContentCleaningProviderTests.cs @@ -150,7 +150,7 @@ public sealed class TextContentCleaningProviderTests private static AIOperationProviderChoice Choose(SettingsManager settingsManager, AIStudio.Settings.Provider assistantProvider) { var resolver = new AIOperationProviderResolver(settingsManager, NullLogger.Instance); - return resolver.Preview(TextContentCleaningOperation.GetProviderSettings(settingsManager), ConfidenceLevel.NONE, AIStudio.Components.ReadWebContent.GetCleanerProviderOptions(settingsManager, assistantProvider)); + return resolver.Preview(TextContentCleaningOperation.GetProviderSettings(settingsManager), ConfidenceLevel.NONE, AIStudio.Tools.Web.WebContentImportService.GetCleanerProviderOptions(settingsManager, assistantProvider)); } /// diff --git a/app/Tests/Assistants/AssistantCategoryPageSettingsTests.cs b/app/Tests/Assistants/AssistantCategoryPageSettingsTests.cs index e3f07206b..1a42f8a5a 100644 --- a/app/Tests/Assistants/AssistantCategoryPageSettingsTests.cs +++ b/app/Tests/Assistants/AssistantCategoryPageSettingsTests.cs @@ -71,6 +71,7 @@ public sealed class AssistantCategoryPageSettingsTests { Assert.That(page.CollapsedCategoryAssistants, Is.EqualTo(AssistantOfferBehavior.KEEP_OFFERING)); Assert.That(page.HiddenCategoryAssistants, Is.EqualTo(AssistantOfferBehavior.TREAT_AS_ABSENT)); + Assert.That(page.InputsWhenLeaving, Is.EqualTo(AssistantInputsWhenLeaving.KEEP_INPUTS)); } } diff --git a/app/Tests/Tools/AssistantSessions/AssistantPluginDraftTests.cs b/app/Tests/Tools/AssistantSessions/AssistantPluginDraftTests.cs new file mode 100644 index 000000000..b18ed1f91 --- /dev/null +++ b/app/Tests/Tools/AssistantSessions/AssistantPluginDraftTests.cs @@ -0,0 +1,122 @@ +using AIStudio.Assistants; +using AIStudio.Assistants.Dynamic; +using AIStudio.Chat; +using AIStudio.Tools.AssistantSessions; +using AIStudio.Tools.PluginSystem.Assistants.DataModel; + +namespace AIStudio.Tests.Tools.AssistantSessions; + +/// +/// Checks the drafts of assistant plugins, whose whole form lives in one AssistantState. +/// +/// +/// The plugin assistant captures a copy of its state with every snapshot. Compared by reference, such a +/// copy always looked changed, so that every plugin which the user merely opened kept a draft and brought +/// back old defaults. Shared with the form, it changed along with it. +/// +[TestFixture] +public sealed class AssistantPluginDraftTests +{ + private static readonly AssistantSessionStateKey ASSISTANT_STATE_KEY = new("AssistantState"); + + [Test] + public void APluginWithJustItsDefaultsKeepsNoDraft() + { + var form = CreateForm(); + + Assert.That(AssistantLowerBase.IsWorthADraft(Capture(form), Capture(form), holdsSentText: false), Is.False, "Two copies of an unchanged form hold the same."); + } + + [Test] + public void AChangedTextOfAPluginIsWorthADraft() + { + var form = CreateForm(); + var stateWithDefaults = Capture(form); + + form.Text["topic"] = "Quarterly report"; + + Assert.That(AssistantLowerBase.IsWorthADraft(Capture(form), stateWithDefaults, holdsSentText: false), Is.True); + } + + [Test] + public void AChangedAddressOfAWebPageIsWorthADraft() + { + var form = CreateForm(); + var stateWithDefaults = Capture(form); + + // The form changes the state of the web content in place: + form.WebContent["page"].URL = "https://example.org"; + + Assert.That(AssistantLowerBase.IsWorthADraft(Capture(form), stateWithDefaults, holdsSentText: false), Is.True, "A copy which shared the state of the web content would have changed along with the form and hidden the change."); + } + + [Test] + public void ARunningContentCleanerAloneIsNoChange() + { + var form = CreateForm(); + var stateWithDefaults = Capture(form); + + form.WebContent["page"].CleanerIsRunning = true; + + Assert.That(AssistantLowerBase.IsWorthADraft(Capture(form), stateWithDefaults, holdsSentText: false), Is.False, "Work in progress is not a change the user made."); + } + + [Test] + public void ACopySharesNothingWithTheForm() + { + var form = CreateForm(); + var copy = form.Clone(); + + form.MultiSelect["formats"].Add("pdf"); + form.WebContent["page"].Content = "changed"; + form.FileContent["file"].Content = "changed"; + form.FileAttachments["files"].DocumentPaths.Add(new FileAttachment(FileAttachmentType.DOCUMENT, "report.pdf", "/tmp/report.pdf", 1)); + + Assert.Multiple(() => + { + Assert.That(copy.MultiSelect["formats"], Is.Empty); + Assert.That(copy.WebContent["page"].Content, Is.Empty); + Assert.That(copy.FileContent["file"].Content, Is.Empty); + Assert.That(copy.FileAttachments["files"].DocumentPaths, Is.Empty); + }); + } + + [Test] + public void ClearingTheFlagsOfWorkInProgressKeepsTheInputs() + { + var form = CreateForm(); + form.WebContent["page"].URL = "https://example.org"; + form.WebContent["page"].Content = "The page"; + form.WebContent["page"].CleanerIsRunning = true; + + var draft = form.Clone(); + draft.ClearFlagsOfWorkInProgress(); + + Assert.Multiple(() => + { + Assert.That(draft.WebContent["page"].CleanerIsRunning, Is.False, "The cleaner ended with the component which started it, so its flag would keep the field locked for good."); + Assert.That(draft.WebContent["page"].URL, Is.EqualTo("https://example.org")); + Assert.That(draft.WebContent["page"].Content, Is.EqualTo("The page")); + Assert.That(form.WebContent["page"].CleanerIsRunning, Is.True, "The draft is a copy; the form keeps its own flag."); + }); + } + + private static AssistantState CreateForm() + { + var form = new AssistantState(); + form.Text["topic"] = string.Empty; + form.MultiSelect["formats"] = []; + form.Booleans["formal"] = false; + form.WebContent["page"] = new WebContentState(); + form.FileContent["file"] = new FileContentState(); + form.FileAttachments["files"] = new FileAttachmentState(); + return form; + } + + private static Dictionary Capture(AssistantState form) + { + var state = new AssistantSessionStateWriter(); + state.Set(ASSISTANT_STATE_KEY, form.Clone()); + return state.ToDictionary(); + } +} \ No newline at end of file diff --git a/app/Tests/Tools/AssistantSessions/AssistantSessionDraftTests.cs b/app/Tests/Tools/AssistantSessions/AssistantSessionDraftTests.cs new file mode 100644 index 000000000..a762a0a81 --- /dev/null +++ b/app/Tests/Tools/AssistantSessions/AssistantSessionDraftTests.cs @@ -0,0 +1,256 @@ +using System.Reflection; + +using AIStudio.Assistants; +using AIStudio.Assistants.Dynamic; +using AIStudio.Tools; +using AIStudio.Tools.AssistantSessions; + +namespace AIStudio.Tests.Tools.AssistantSessions; + +/// +/// Checks the drafts which keep what an assistant holds while the user is elsewhere in AI Studio. +/// +/// +/// A draft is not a run: it must neither show up as one, e.g., as a status in the assistant overview, nor +/// outlive a reset of its assistant or a text sent to it, which would otherwise overwrite that text. +/// +[TestFixture] +public sealed class AssistantSessionDraftTests +{ + private static readonly AssistantSessionStateKey TEXT_KEY = new("Text"); + private static readonly AssistantSessionStateKey IS_READING_KEY = new("IsReading", isKeptOutOfDrafts: true); + + private static readonly AssistantSessionStateKey IS_VALID_KEY = new("IsValid", isDerived: true); + + private static readonly AssistantSessionKey TRANSLATION_KEY = new(AIStudio.Tools.Components.TRANSLATION_ASSISTANT, "translation"); + private static readonly AssistantSessionKey SUMMARIZER_KEY = new(AIStudio.Tools.Components.TEXT_SUMMARIZER_ASSISTANT, "summarizer"); + + private AssistantSessionService service = null!; + + [SetUp] + public void SetUp() => this.service = new AssistantSessionService(MessageBus.INSTANCE); + + [Test] + public void ADraftComesBackWithItsState() + { + this.service.SaveDraft(TRANSLATION_KEY, "Translation", null, StateWithText("hello")); + + var draft = this.service.TryTakeDraft(TRANSLATION_KEY); + + Assert.That(draft, Is.Not.Null); + Assert.That(draft!.Key, Is.EqualTo(TRANSLATION_KEY)); + Assert.That(draft.IsActive, Is.False, "A draft is not a run."); + Assert.That(TextOf(draft), Is.EqualTo("hello")); + } + + [Test] + public void ADraftIsTakenOnlyOnce() + { + this.service.SaveDraft(TRANSLATION_KEY, "Translation", null, StateWithText("hello")); + + _ = this.service.TryTakeDraft(TRANSLATION_KEY); + + Assert.That(this.service.TryTakeDraft(TRANSLATION_KEY), Is.Null, "The assistant which took the draft holds it now, so it must not come back a second time."); + } + + [Test] + public void ANewerDraftReplacesTheOlderOne() + { + this.service.SaveDraft(TRANSLATION_KEY, "Translation", null, StateWithText("first")); + this.service.SaveDraft(TRANSLATION_KEY, "Translation", null, StateWithText("second")); + + Assert.That(TextOf(this.service.TryTakeDraft(TRANSLATION_KEY)!), Is.EqualTo("second")); + } + + [Test] + public void ADraftKeepsItsStateWhenTheCapturedDictionaryChangesLater() + { + var state = StateWithText("hello"); + this.service.SaveDraft(TRANSLATION_KEY, "Translation", null, state); + + state.Clear(); + + Assert.That(TextOf(this.service.TryTakeDraft(TRANSLATION_KEY)!), Is.EqualTo("hello")); + } + + [Test] + public void ADraftIsNoSession() + { + this.service.SaveDraft(TRANSLATION_KEY, "Translation", null, StateWithText("hello")); + + Assert.Multiple(() => + { + Assert.That(this.service.GetSnapshots(), Is.Empty, "The assistant overview must show no status for a draft."); + Assert.That(this.service.TryGetSnapshot(TRANSLATION_KEY), Is.Null); + Assert.That(this.service.HasActiveSessions, Is.False, "A draft must not keep AI Studio from closing."); + }); + } + + [Test] + public async Task AResetRemovesTheDraft() + { + this.service.SaveDraft(TRANSLATION_KEY, "Translation", null, StateWithText("hello")); + + await this.service.ClearAsync(TRANSLATION_KEY); + + Assert.That(this.service.TryTakeDraft(TRANSLATION_KEY), Is.Null); + } + + [Test] + public async Task ATextSentToAnAssistantRemovesOnlyItsDraft() + { + this.service.SaveDraft(TRANSLATION_KEY, "Translation", null, StateWithText("hello")); + this.service.SaveDraft(SUMMARIZER_KEY, "Summarizer", null, StateWithText("long text")); + + await this.service.ClearInactiveSessionsForComponentAsync(AIStudio.Tools.Components.TRANSLATION_ASSISTANT); + + Assert.Multiple(() => + { + Assert.That(this.service.TryTakeDraft(TRANSLATION_KEY), Is.Null, "The text sent to the assistant replaces its draft."); + Assert.That(this.service.TryTakeDraft(SUMMARIZER_KEY), Is.Not.Null, "The drafts of other assistants stay."); + }); + } + + [Test] + public void ADraftRestoresNoFlagOfWorkInProgress() + { + var state = StateWithText("hello"); + state[IS_READING_KEY.Name] = new AssistantSessionSnapshotField(true); + + var isReading = false; + string? text = null; + var reader = new AssistantSessionStateReader(state, "Translation", isDraft: true); + reader.Restore(IS_READING_KEY, value => isReading = value); + reader.Restore(TEXT_KEY, value => text = value); + + Assert.Multiple(() => + { + Assert.That(isReading, Is.False, "The work ended with the component which did it, so its flag would keep the form locked for good."); + Assert.That(text, Is.EqualTo("hello"), "Everything else comes back from a draft."); + }); + } + + [Test] + public void ARunRestoresFlagsOfWorkInProgress() + { + var state = StateWithText("hello"); + state[IS_READING_KEY.Name] = new AssistantSessionSnapshotField(true); + + var isReading = false; + new AssistantSessionStateReader(state, "Translation").Restore(IS_READING_KEY, value => isReading = value); + + Assert.That(isReading, Is.True, "A run still goes on, so its flags hold."); + } + + /// + /// Keys whose name reads like a flag of work in progress but is none. + /// + private static readonly HashSet NO_FLAGS_OF_WORK_IN_PROGRESS = + [ + // Whether the meeting of the agenda assistant takes place online, which the user chooses: + "IS_MEETING_VIRTUAL_STATE_KEY", + ]; + + [Test] + public void EveryFlagOfWorkInProgressIsKeptOutOfDrafts() + { + var flags = typeof(AssistantLowerBase).Assembly.GetTypes() + .Where(type => !type.ContainsGenericParameters) + .SelectMany(type => type.GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) + .Where(field => field.FieldType.IsGenericType && field.FieldType.GetGenericTypeDefinition() == typeof(AssistantSessionStateKey<>)) + .Where(field => ReadsLikeAFlagOfWorkInProgress(field.Name) && !NO_FLAGS_OF_WORK_IN_PROGRESS.Contains(field.Name)) + .ToList(); + + Assert.That(flags.Select(field => field.Name), Does.Contain("IS_PROCESSING_STATE_KEY"), "The search must find the flags, or this test checks nothing."); + + var restoredFromDrafts = flags + .Where(field => field.FieldType.GetProperty(nameof(AssistantSessionStateKey<>.IsKeptOutOfDrafts))!.GetValue(field.GetValue(null)) is not true) + .Select(field => $"{field.DeclaringType!.Name}.{field.Name}") + .ToList(); + + Assert.That(restoredFromDrafts, Is.Empty, "Work outside of a run ends with the component which did it, so a flag restored from a draft stays set for good and may lock the form. Pass isKeptOutOfDrafts: true, or list a key which is not such a flag in NO_FLAGS_OF_WORK_IN_PROGRESS."); + } + + [Test] + public void AnAssistantWithJustItsDefaultsKeepsNoDraft() + { + Assert.That(AssistantLowerBase.IsWorthADraft(StateWithText(string.Empty), StateWithText(string.Empty), holdsSentText: false), Is.False); + } + + [Test] + public void AChangedInputIsWorthADraft() + { + Assert.That(AssistantLowerBase.IsWorthADraft(StateWithText("hello"), StateWithText(string.Empty), holdsSentText: false), Is.True); + } + + [Test] + public void ADerivedValueAloneIsNoChange() + { + var stateWithDefaults = new AssistantSessionStateWriter(); + stateWithDefaults.Set(TEXT_KEY, string.Empty); + stateWithDefaults.Set(IS_VALID_KEY, false); + + var state = new AssistantSessionStateWriter(); + state.Set(TEXT_KEY, string.Empty); + state.Set(IS_VALID_KEY, true); + + Assert.That(AssistantLowerBase.IsWorthADraft(state.ToDictionary(), stateWithDefaults.ToDictionary(), holdsSentText: false), Is.False, "A value which follows from the inputs, which did not change, is not a change on its own."); + } + + [Test] + public void AFlagOfWorkInProgressAloneIsNoChange() + { + var stateWithDefaults = new AssistantSessionStateWriter(); + stateWithDefaults.Set(TEXT_KEY, string.Empty); + stateWithDefaults.Set(IS_READING_KEY, false); + + var state = new AssistantSessionStateWriter(); + state.Set(TEXT_KEY, string.Empty); + state.Set(IS_READING_KEY, true); + + Assert.That(AssistantLowerBase.IsWorthADraft(state.ToDictionary(), stateWithDefaults.ToDictionary(), holdsSentText: false), Is.False, "Work in progress is not a change the user made."); + } + + [TestCase(typeof(AssistantLowerBase), "INPUT_IS_VALID_STATE_KEY")] + [TestCase(typeof(AssistantLowerBase), "INPUT_ISSUES_STATE_KEY")] + [TestCase(typeof(AssistantDynamic), "IMAGE_CACHE_STATE_KEY")] + public void ValuesWhichFollowFromOthersAreDerived(Type declaringType, string fieldName) + { + var field = declaringType.GetField(fieldName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); + Assert.That(field, Is.Not.Null, $"The key {fieldName} is gone; update this test."); + + var isDerived = field!.FieldType.GetProperty(nameof(AssistantSessionStateKey<>.IsDerived))!.GetValue(field.GetValue(null)); + Assert.That(isDerived, Is.True, "Whether the form is valid, and a cache which fills while the assistant renders, would otherwise make an assistant look changed although the user changed nothing."); + } + + [Test] + public void ATextSentToTheAssistantIsAlwaysWorthADraft() + { + Assert.That(AssistantLowerBase.IsWorthADraft(StateWithText(string.Empty), StateWithText(string.Empty), holdsSentText: true), Is.True, "The user chose to work on the text sent here, even before changing anything."); + } + + private static bool ReadsLikeAFlagOfWorkInProgress(string name) + { + var words = name.Split('_'); + return words[0] switch + { + "IS" => words.Skip(1).Any(word => word.EndsWith("ING", StringComparison.Ordinal)), + "EXECUTING" => true, + _ => false, + }; + } + + private static Dictionary StateWithText(string text) + { + var state = new AssistantSessionStateWriter(); + state.Set(TEXT_KEY, text); + return state.ToDictionary(); + } + + private static string? TextOf(AssistantSessionSnapshot snapshot) + { + string? text = null; + new AssistantSessionStateReader(snapshot.State, snapshot.Title).Restore(TEXT_KEY, value => text = value); + return text; + } +} \ No newline at end of file diff --git a/app/Tests/Tools/Media/TranscriptPromptInjectionTests.cs b/app/Tests/Tools/Media/TranscriptPromptInjectionTests.cs index a8e1a10e0..fc88d18f1 100644 --- a/app/Tests/Tools/Media/TranscriptPromptInjectionTests.cs +++ b/app/Tests/Tools/Media/TranscriptPromptInjectionTests.cs @@ -1,5 +1,6 @@ using AIStudio.Settings; using AIStudio.Tests.Tools.Security; +using AIStudio.Tools.Imports; using AIStudio.Tools.Media; using AIStudio.Tools.Security; using AIStudio.Tools.Services; @@ -133,7 +134,7 @@ public sealed class TranscriptPromptInjectionTests private MediaTranscriptionService CreateMediaTranscriptionService() => new(this.rustService, this.settingsManager, this.guardService, [], NullLogger.Instance); - private static MediaImportTarget NewFieldTarget() => new(new(MediaImportOwnerKind.ASSISTANT, $"test-{Guid.NewGuid():N}"), "primary"); + private static ImportTarget NewFieldTarget() => new(new(ImportOwnerKind.ASSISTANT, $"test-{Guid.NewGuid():N}"), "primary"); /// /// Stores a transcript next to the recording and looks it up, both as the Batch Processing assistant does. diff --git a/app/Tests/Tools/Web/WebContentImportServiceTests.cs b/app/Tests/Tools/Web/WebContentImportServiceTests.cs new file mode 100644 index 000000000..4248e0cf0 --- /dev/null +++ b/app/Tests/Tools/Web/WebContentImportServiceTests.cs @@ -0,0 +1,170 @@ +using System.Collections.Concurrent; + +using AIStudio.Components; +using AIStudio.Tools.Imports; +using AIStudio.Tools.Web; + +using Microsoft.Extensions.Logging.Abstractions; + +namespace AIStudio.Tests.Tools.Web; + +/// +/// Checks the bookkeeping of the imports of web content, which go on while the user is elsewhere. +/// +/// +/// The web content reader of an assistant goes away when the user leaves the assistant. While the reader +/// loaded and cleaned the page itself, its result went to the assistant which was already gone. The imports +/// here are stand-ins: the bookkeeping does not care how a page is loaded. +/// +[TestFixture] +public sealed class WebContentImportServiceTests +{ + private const string URL = "https://example.org/report"; + + private static readonly ImportOwner ASSISTANT = new(ImportOwnerKind.ASSISTANT, "TRANSLATION_ASSISTANT:test"); + + private static readonly ImportTarget FIELD = new(ASSISTANT, "primary"); + + private static readonly WebContentImportRequest REQUEST = new(URL, CleanContent: true, AIStudio.Settings.Provider.NONE); + + [Test] + public async Task AnImportIsBusyUntilItEndsAndShowsItsStep() + { + var service = CreateService(); + var cleaning = NewSignal(); + var finish = NewSignal(); + var running = service.Start(FIELD, REQUEST, async reportStep => + { + reportStep(ReadWebContentSteps.CLEANING); + cleaning.SetResult(); + await finish.Task; + return new(URL, "Cleaned text"); + }); + + Assert.That(running, Is.Not.Null); + await cleaning.Task; + using (Assert.EnterMultipleScope()) + { + Assert.That(service.IsBusy(ASSISTANT), Is.True); + Assert.That(service.GetSnapshot(FIELD)?.Step, Is.EqualTo(ReadWebContentSteps.CLEANING)); + Assert.That(service.GetSnapshot(FIELD)?.Url, Is.EqualTo(URL), "A reader which comes back shows the address being loaded."); + Assert.That(service.GetSnapshot(FIELD)?.CleanContent, Is.True, "A reader which comes back shows that the page is being cleaned."); + Assert.That(service.TryTakeResult(FIELD), Is.Null, "Nothing waits while the import runs."); + } + + finish.SetResult(); + await running!; + using (Assert.EnterMultipleScope()) + { + Assert.That(service.IsBusy(ASSISTANT), Is.False); + Assert.That(service.GetSnapshot(FIELD), Is.Null); + } + } + + [Test] + public async Task AFieldStartsNoSecondImportWhileOtherFieldsLoadAtTheSameTime() + { + var service = CreateService(); + var otherReader = new ImportTarget(ASSISTANT, "second-reader"); + var otherAssistant = new ImportTarget(new(ImportOwnerKind.ASSISTANT, "LEGAL_CHECK_ASSISTANT:test"), "primary"); + var finish = NewSignal(); + + var first = service.Start(FIELD, REQUEST, async _ => { await finish.Task; return new(URL, "First text"); }); + var second = service.Start(FIELD, REQUEST, _ => Task.FromResult(new WebContentImportResult(URL, "Second text"))); + var ofOtherReader = service.Start(otherReader, REQUEST, async _ => { await finish.Task; return new(URL, "Text of the other reader"); }); + var ofOtherAssistant = service.Start(otherAssistant, REQUEST, async _ => { await finish.Task; return new(URL, "Text of the other assistant"); }); + + using (Assert.EnterMultipleScope()) + { + Assert.That(first, Is.Not.Null); + Assert.That(second, Is.Null, "The field still loads its first page."); + Assert.That(ofOtherReader, Is.Not.Null, "Another reader of the same assistant loads at the same time."); + Assert.That(ofOtherAssistant, Is.Not.Null, "A reader of another assistant loads at the same time."); + Assert.That(service.GetSnapshots(), Has.Count.EqualTo(3)); + } + + finish.SetResult(); + await Task.WhenAll(first!, ofOtherReader!, ofOtherAssistant!); + Assert.That(service.TryTakeResult(FIELD)?.Markdown, Is.EqualTo("First text")); + } + + [Test] + public async Task TheResultWaitsForItsFieldAndArrivesOnce() + { + var service = CreateService(); + await service.Start(FIELD, REQUEST, _ => Task.FromResult(new WebContentImportResult(URL, "Loaded text")))!; + + using (Assert.EnterMultipleScope()) + { + Assert.That(service.TryTakeResult(new ImportTarget(ASSISTANT, "second-reader")), Is.Null, "Another field gets nothing."); + Assert.That(service.TryTakeResult(FIELD)?.Markdown, Is.EqualTo("Loaded text")); + Assert.That(service.TryTakeResult(FIELD), Is.Null, "The result arrives once."); + } + } + + [Test] + public async Task AResetDiscardsWaitingResultsButNoRunningImport() + { + var service = CreateService(); + var otherReader = new ImportTarget(ASSISTANT, "second-reader"); + await service.Start(FIELD, REQUEST, _ => Task.FromResult(new WebContentImportResult(URL, "Loaded text")))!; + var finish = NewSignal(); + var running = service.Start(otherReader, REQUEST, async _ => { await finish.Task; return new(URL, "Later text"); }); + + service.ClearOwnerState(ASSISTANT); + + using (Assert.EnterMultipleScope()) + { + Assert.That(service.TryTakeResult(FIELD), Is.Null, "The waiting result is gone."); + Assert.That(service.GetSnapshot(otherReader), Is.Not.Null, "The running import goes on."); + } + + finish.SetResult(); + await running!; + Assert.That(service.TryTakeResult(otherReader)?.Markdown, Is.EqualTo("Later text")); + } + + [Test] + public async Task TheOwnerHearsAboutTheStartEachStepAndTheEnd() + { + var service = CreateService(); + var owners = new ConcurrentQueue(); + service.StateChanged += owners.Enqueue; + + await service.Start(FIELD, REQUEST, reportStep => + { + reportStep(ReadWebContentSteps.PARSING); + reportStep(ReadWebContentSteps.CLEANING); + return Task.FromResult(new WebContentImportResult(URL, "Cleaned text")); + })!; + + Assert.That(owners, Has.Count.EqualTo(4).And.All.EqualTo(ASSISTANT), "The start, two steps, and the end."); + } + + [Test] + public async Task AnImportWhichFailsSaysWhyAndFreesItsField() + { + var service = CreateService(); + await service.Start(FIELD, REQUEST, _ => throw new HttpRequestException("The host does not answer."))!; + + var result = service.TryTakeResult(FIELD); + using (Assert.EnterMultipleScope()) + { + Assert.That(result?.Issue, Is.EqualTo(WebContentImportIssue.LOAD_FAILED)); + Assert.That(result?.ErrorMessage, Is.EqualTo("The host does not answer.")); + Assert.That(result?.Url, Is.EqualTo(URL)); + Assert.That(service.IsBusy(ASSISTANT), Is.False); + } + + var retry = service.Start(FIELD, REQUEST, _ => Task.FromResult(new WebContentImportResult(URL, "Loaded text"))); + Assert.That(retry, Is.Not.Null, "The field can load again."); + await retry!; + } + + /// + /// The stand-in imports need none of the services which load a real page. + /// + private static WebContentImportService CreateService() => new(null!, null!, null!, null!, null!, NullLogger.Instance); + + private static TaskCompletionSource NewSignal() => new(TaskCreationOptions.RunContinuationsAsynchronously); +} \ No newline at end of file