mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-12-04 21:44:35 +00:00
Kept the inputs of assistants when you leave them (#1209)
Co-authored-by: Thorsten Sommer <SommerEngineering@users.noreply.github.com>
This commit is contained in:
1 parent
1fbc1f4796
commit
7e2f83b19b
83 files changed
+1924
-347
No files matched your search
@@ -150,7 +150,7 @@ public sealed class TextContentCleaningProviderTests
|
||||
private static AIOperationProviderChoice Choose(SettingsManager settingsManager, AIStudio.Settings.Provider assistantProvider)
|
||||
{
|
||||
var resolver = new AIOperationProviderResolver(settingsManager, NullLogger<AIOperationProviderResolver>.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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Checks the drafts of assistant plugins, whose whole form lives in one AssistantState.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
[TestFixture]
|
||||
public sealed class AssistantPluginDraftTests
|
||||
{
|
||||
private static readonly AssistantSessionStateKey<AssistantState> 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<string, IAssistantSessionSnapshotField> Capture(AssistantState form)
|
||||
{
|
||||
var state = new AssistantSessionStateWriter();
|
||||
state.Set(ASSISTANT_STATE_KEY, form.Clone());
|
||||
return state.ToDictionary();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Checks the drafts which keep what an assistant holds while the user is elsewhere in AI Studio.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
[TestFixture]
|
||||
public sealed class AssistantSessionDraftTests
|
||||
{
|
||||
private static readonly AssistantSessionStateKey<string> TEXT_KEY = new("Text");
|
||||
private static readonly AssistantSessionStateKey<bool> IS_READING_KEY = new("IsReading", isKeptOutOfDrafts: true);
|
||||
|
||||
private static readonly AssistantSessionStateKey<bool> 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<bool>(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<bool>(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.");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Keys whose name reads like a flag of work in progress but is none.
|
||||
/// </summary>
|
||||
private static readonly HashSet<string> 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<string, IAssistantSessionSnapshotField> 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;
|
||||
}
|
||||
}
|
||||
@@ -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<MediaTranscriptionService>.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");
|
||||
|
||||
/// <summary>
|
||||
/// Stores a transcript next to the recording and looks it up, both as the Batch Processing assistant does.
|
||||
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Checks the bookkeeping of the imports of web content, which go on while the user is elsewhere.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
[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<ImportOwner>();
|
||||
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!;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The stand-in imports need none of the services which load a real page.
|
||||
/// </summary>
|
||||
private static WebContentImportService CreateService() => new(null!, null!, null!, null!, null!, NullLogger<WebContentImportService>.Instance);
|
||||
|
||||
private static TaskCompletionSource NewSignal() => new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
}
|
||||
Reference in new issue
Block a user