mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-12-04 22:44:35 +00:00
Kept the inputs of assistants when you leave them (#1209)
Co-authored-by: Thorsten Sommer <SommerEngineering@users.noreply.github.com>
This commit is contained in:
1 parent
1fbc1f4796
commit
7e2f83b19b
83 files changed
+1924
-347
No files matched your search
@@ -88,6 +88,11 @@ public sealed class AssistantSessionService(MessageBus messageBus)
|
||||
/// </summary>
|
||||
private readonly ConcurrentDictionary<AssistantSessionKey, AssistantSessionState> sessions = new();
|
||||
|
||||
/// <summary>
|
||||
/// Stores one draft per session key, see <see cref="SaveDraft"/>.
|
||||
/// </summary>
|
||||
private readonly ConcurrentDictionary<AssistantSessionKey, AssistantSessionSnapshot> drafts = new();
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether at least one assistant session is still active.
|
||||
/// </summary>
|
||||
@@ -142,6 +147,47 @@ public sealed class AssistantSessionService(MessageBus messageBus)
|
||||
return ((ICollection<KeyValuePair<AssistantSessionKey, AssistantSessionState>>)this.sessions).Remove(new(key, session)) ? snapshot : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stores what an assistant holds when the user leaves it, so that it is there again when the user comes back.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A draft is not a run: neither <see cref="GetSnapshots"/> nor <see cref="HasActiveSessions"/> 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.
|
||||
/// </remarks>
|
||||
/// <param name="key">The assistant session key.</param>
|
||||
/// <param name="title">The user-visible assistant title.</param>
|
||||
/// <param name="chatThread">The assistant chat thread, if one exists.</param>
|
||||
/// <param name="state">The assistant component state.</param>
|
||||
public void SaveDraft(AssistantSessionKey key, string title, ChatThread? chatThread, Dictionary<string, IAssistantSessionSnapshotField> 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<string, IAssistantSessionSnapshotField>(state, StringComparer.Ordinal),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tries to get and remove the draft of an assistant.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
/// <param name="key">The assistant session key to look up and remove.</param>
|
||||
/// <returns>The removed draft, or <c>null</c> when there is none.</returns>
|
||||
public AssistantSessionSnapshot? TryTakeDraft(AssistantSessionKey key) => this.drafts.TryRemove(key, out var draft) ? draft : null;
|
||||
|
||||
/// <summary>
|
||||
/// Starts a new assistant session when no active session exists for the key.
|
||||
/// </summary>
|
||||
@@ -279,11 +325,12 @@ public sealed class AssistantSessionService(MessageBus messageBus)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears an inactive assistant session.
|
||||
/// Clears an inactive assistant session and the draft of the assistant.
|
||||
/// </summary>
|
||||
/// <param name="key">The assistant session key to clear.</param>
|
||||
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)
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears all inactive sessions for a component.
|
||||
/// Clears all inactive sessions and all drafts for a component.
|
||||
/// </summary>
|
||||
/// <param name="component">The component whose inactive sessions should be cleared.</param>
|
||||
/// <param name="component">The component whose inactive sessions and drafts should be cleared.</param>
|
||||
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)
|
||||
|
||||
@@ -13,9 +13,11 @@ public sealed record AssistantSessionSnapshotField<T> : IAssistantSessionSnapsho
|
||||
/// Initializes a new typed snapshot field.
|
||||
/// </summary>
|
||||
/// <param name="value">The captured value.</param>
|
||||
public AssistantSessionSnapshotField(T value)
|
||||
/// <param name="countsAsChange">Whether another value of this field means that the assistant changed, see CountsAsChange.</param>
|
||||
public AssistantSessionSnapshotField(T value, bool countsAsChange = true)
|
||||
{
|
||||
this.Value = value;
|
||||
this.CountsAsChange = countsAsChange;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -26,6 +28,9 @@ public sealed record AssistantSessionSnapshotField<T> : IAssistantSessionSnapsho
|
||||
/// <inheritdoc />
|
||||
public Type ValueType => typeof(T);
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool CountsAsChange { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool TryRead<TValue>(out TValue? value)
|
||||
{
|
||||
@@ -56,6 +61,10 @@ public sealed record AssistantSessionSnapshotField<T> : 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);
|
||||
|
||||
@@ -10,9 +10,13 @@ public readonly record struct AssistantSessionStateKey<T>
|
||||
/// Initializes a new assistant session state key.
|
||||
/// </summary>
|
||||
/// <param name="name">The stable dictionary name used in assistant session snapshots.</param>
|
||||
public AssistantSessionStateKey(string name)
|
||||
/// <param name="isKeptOutOfDrafts">Whether a draft leaves the value out, see <see cref="IsKeptOutOfDrafts"/>.</param>
|
||||
/// <param name="isDerived">Whether the value follows from other values, see IsDerived.</param>
|
||||
public AssistantSessionStateKey(string name, bool isKeptOutOfDrafts = false, bool isDerived = false)
|
||||
{
|
||||
this.Name = name;
|
||||
this.IsKeptOutOfDrafts = isKeptOutOfDrafts;
|
||||
this.IsDerived = isDerived;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -20,6 +24,28 @@ public readonly record struct AssistantSessionStateKey<T>
|
||||
/// </summary>
|
||||
public string Name { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether an assistant restores the value from a run only, never from a draft.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
public bool IsKeptOutOfDrafts { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the value follows from other values, such as whether the form is valid, or is a cache.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
public bool IsDerived { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Returns the stable dictionary name.
|
||||
/// </summary>
|
||||
|
||||
@@ -7,10 +7,21 @@ namespace AIStudio.Tools.AssistantSessions;
|
||||
/// </summary>
|
||||
/// <param name="fields">The captured snapshot fields.</param>
|
||||
/// <param name="assistantTitle">The user-visible assistant title.</param>
|
||||
public sealed class AssistantSessionStateReader(IReadOnlyDictionary<string, IAssistantSessionSnapshotField> fields, string assistantTitle)
|
||||
/// <param name="isDraft">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 <see cref="AssistantSessionStateKey{T}.IsKeptOutOfDrafts"/>.</param>
|
||||
public sealed class AssistantSessionStateReader(IReadOnlyDictionary<string, IAssistantSessionSnapshotField> fields, string assistantTitle, bool isDraft = false)
|
||||
{
|
||||
private static readonly ILogger<AssistantSessionStateReader> LOG = Program.LOGGER_FACTORY.CreateLogger<AssistantSessionStateReader>();
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether the fields come from a draft rather than from a run.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
public bool IsDraft => isDraft;
|
||||
|
||||
/// <summary>
|
||||
/// Restores a typed value when it exists in the snapshot.
|
||||
/// </summary>
|
||||
@@ -94,6 +105,9 @@ public sealed class AssistantSessionStateReader(IReadOnlyDictionary<string, IAss
|
||||
private bool TryRead<T>(AssistantSessionStateKey<T> key, out T? value)
|
||||
{
|
||||
value = default;
|
||||
if (isDraft && key.IsKeptOutOfDrafts)
|
||||
return false;
|
||||
|
||||
if (!fields.TryGetValue(key.Name, out var field))
|
||||
return false;
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ public sealed class AssistantSessionStateWriter
|
||||
/// <param name="value">The captured value.</param>
|
||||
public void Set<T>(AssistantSessionStateKey<T> key, T value)
|
||||
{
|
||||
this.fields[key.Name] = new AssistantSessionSnapshotField<T>(value);
|
||||
this.fields[key.Name] = new AssistantSessionSnapshotField<T>(value, countsAsChange: !key.IsDerived && !key.IsKeptOutOfDrafts);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -10,6 +10,16 @@ public interface IAssistantSessionSnapshotField
|
||||
/// </summary>
|
||||
Type ValueType { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Gets whether another value of this field means that the assistant changed.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
bool CountsAsChange { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Tries to read the captured value as the requested type.
|
||||
/// </summary>
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace AIStudio.Tools.AssistantSessions;
|
||||
|
||||
/// <summary>
|
||||
/// A value of an assistant session which tells by itself whether another value holds the same.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
public interface IAssistantSessionValue
|
||||
{
|
||||
/// <summary>
|
||||
/// Tells whether another value holds the same content as this one.
|
||||
/// </summary>
|
||||
/// <param name="other">The value to compare with.</param>
|
||||
/// <returns><c>true</c> when both values hold the same content; otherwise, <c>false</c>.</returns>
|
||||
bool HasSameValueAs(object other);
|
||||
}
|
||||
@@ -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
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 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.
|
||||
/// </summary>
|
||||
/// <value>The media-import owner kind.</value>
|
||||
public MediaImportOwnerKind MediaOwnerKind => component switch
|
||||
/// <value>The import owner kind.</value>
|
||||
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
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
using AIStudio.Tools.AssistantSessions;
|
||||
|
||||
namespace AIStudio.Tools.Imports;
|
||||
|
||||
/// <summary>Identifies the chat, assistant, or visual briefing that owns an import, e.g., the transcription of a media file.</summary>
|
||||
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());
|
||||
|
||||
/// <summary>
|
||||
/// Creates a persistent import owner for a visual briefing.
|
||||
/// </summary>
|
||||
/// <param name="briefingId">The stable briefing identifier.</param>
|
||||
/// <returns>The import owner.</returns>
|
||||
public static ImportOwner ForVisualBriefing(Guid briefingId) => new(ImportOwnerKind.VISUAL_BRIEFING, briefingId.ToString("D"));
|
||||
}
|
||||
+4
-4
@@ -1,7 +1,7 @@
|
||||
namespace AIStudio.Tools.Media;
|
||||
namespace AIStudio.Tools.Imports;
|
||||
|
||||
/// <summary>Supported persistent media-operation owners.</summary>
|
||||
public enum MediaImportOwnerKind
|
||||
/// <summary>The kinds of owners of an import, see ImportOwner.</summary>
|
||||
public enum ImportOwnerKind
|
||||
{
|
||||
CHAT,
|
||||
ASSISTANT,
|
||||
@@ -13,7 +13,7 @@ public enum MediaImportOwnerKind
|
||||
/// A visual briefing cannot use <see cref="ASSISTANT"/>: 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 <see cref="MediaImportOwner.ForVisualBriefing"/>.
|
||||
/// therefore keyed by the briefing ID, see <see cref="ImportOwner.ForVisualBriefing"/>.
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
+6
-6
@@ -1,22 +1,22 @@
|
||||
namespace AIStudio.Tools.Media;
|
||||
namespace AIStudio.Tools.Imports;
|
||||
|
||||
/// <summary>Capabilities of a media-import owner kind.</summary>
|
||||
public static class MediaImportOwnerKindExtensions
|
||||
/// <summary>Capabilities of an import owner kind.</summary>
|
||||
public static class ImportOwnerKindExtensions
|
||||
{
|
||||
/// <param name="kind">The owner kind to look up.</param>
|
||||
extension(MediaImportOwnerKind kind)
|
||||
extension(ImportOwnerKind kind)
|
||||
{
|
||||
/// <summary>
|
||||
/// Gets whether the owner stores its own source list and transcripts.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Owners that persist their own sources take the attached media over immediately and keep it
|
||||
/// next to the stored document, see <see cref="MediaImportOwnerKind.VISUAL_BRIEFING"/>. The
|
||||
/// next to the stored document, see <see cref="ImportOwnerKind.VISUAL_BRIEFING"/>. 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.
|
||||
/// </remarks>
|
||||
/// <value><c>true</c> when the owner persists its own sources.</value>
|
||||
public bool PersistsOwnSources => kind is MediaImportOwnerKind.VISUAL_BRIEFING;
|
||||
public bool PersistsOwnSources => kind is ImportOwnerKind.VISUAL_BRIEFING;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
namespace AIStudio.Tools.Imports;
|
||||
|
||||
/// <summary>Identifies the concrete field inside an owner which an import fills, e.g., an attachment list or a file-content field.</summary>
|
||||
public readonly record struct ImportTarget(ImportOwner Owner, string TargetId);
|
||||
@@ -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
|
||||
{
|
||||
/// <summary>
|
||||
/// Determines whether this storage handles the specified media-import owner.
|
||||
/// Determines whether this storage handles the specified import owner.
|
||||
/// </summary>
|
||||
/// <param name="owner">The feature-specific media-import owner.</param>
|
||||
/// <param name="owner">The feature-specific import owner.</param>
|
||||
/// <returns><see langword="true"/> when the transcript can be stored.</returns>
|
||||
bool CanStore(MediaImportOwner owner);
|
||||
bool CanStore(ImportOwner owner);
|
||||
|
||||
/// <summary>
|
||||
/// Persists a completed transcript and returns the attachment exposed to the calling workflow.
|
||||
/// </summary>
|
||||
/// <param name="target">The stable media-import target.</param>
|
||||
/// <param name="target">The stable import target.</param>
|
||||
/// <param name="originalMediaPath">The original media path.</param>
|
||||
/// <param name="transcript">The completed transcript text.</param>
|
||||
/// <param name="token">The cancellation token.</param>
|
||||
/// <returns>The attachment representing the persisted transcript.</returns>
|
||||
Task<FileAttachment> StoreAsync(
|
||||
MediaImportTarget target,
|
||||
ImportTarget target,
|
||||
string originalMediaPath,
|
||||
string transcript,
|
||||
CancellationToken token);
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
using AIStudio.Chat;
|
||||
using AIStudio.Tools.Imports;
|
||||
|
||||
namespace AIStudio.Tools.Media;
|
||||
|
||||
/// <summary>Pending media results waiting for one concrete UI target.</summary>
|
||||
public sealed record MediaImportDelivery
|
||||
{
|
||||
public required MediaImportTarget Target { get; init; }
|
||||
public required ImportTarget Target { get; init; }
|
||||
|
||||
public IReadOnlyList<FileAttachment> Attachments { get; init; } = [];
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
using AIStudio.Tools.Imports;
|
||||
|
||||
namespace AIStudio.Tools.Media;
|
||||
|
||||
/// <summary>Terminal batch outcome retained until its owner is displayed.</summary>
|
||||
public sealed record MediaImportOutcome
|
||||
{
|
||||
public required MediaImportOwner Owner { get; init; }
|
||||
public required ImportOwner Owner { get; init; }
|
||||
|
||||
public required MediaImportStatus Status { get; init; }
|
||||
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
using AIStudio.Tools.AssistantSessions;
|
||||
|
||||
namespace AIStudio.Tools.Media;
|
||||
|
||||
/// <summary>Identifies the chat or assistant that owns a media import.</summary>
|
||||
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());
|
||||
|
||||
/// <summary>
|
||||
/// Creates a persistent media-import owner for a visual briefing.
|
||||
/// </summary>
|
||||
/// <param name="briefingId">The stable briefing identifier.</param>
|
||||
/// <returns>The media-import owner.</returns>
|
||||
public static MediaImportOwner ForVisualBriefing(Guid briefingId) => new(MediaImportOwnerKind.VISUAL_BRIEFING, briefingId.ToString("D"));
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
using AIStudio.Tools.Imports;
|
||||
|
||||
namespace AIStudio.Tools.Media;
|
||||
|
||||
/// <summary>Copied owner-specific state suitable for rendering after navigation.</summary>
|
||||
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; }
|
||||
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
namespace AIStudio.Tools.Media;
|
||||
|
||||
/// <summary>Identifies the concrete attachment or file-content field inside an owner.</summary>
|
||||
public readonly record struct MediaImportTarget(MediaImportOwner Owner, string TargetId);
|
||||
@@ -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<string, string> Text = new(StringComparer.Ordinal);
|
||||
public readonly Dictionary<string, string> SingleSelect = new(StringComparer.Ordinal);
|
||||
@@ -36,17 +38,22 @@ public sealed class AssistantState
|
||||
/// <summary>
|
||||
/// Copies all dynamic assistant state values from another state instance.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
/// <param name="other">The state instance to copy from.</param>
|
||||
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<string>(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;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears the flags of work in progress, such as a content cleaner which runs for a web page.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
public void ClearFlagsOfWorkInProgress()
|
||||
{
|
||||
foreach (var webContent in this.WebContent.Values)
|
||||
webContent.CleanerIsRunning = false;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
/// <remarks>
|
||||
/// Compares the values of all fields. Whether a web content cleaner runs is not an input and does not count,
|
||||
/// see WebContentState.HasSameInputsAs.
|
||||
/// </remarks>
|
||||
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);
|
||||
|
||||
/// <summary>
|
||||
/// Copies all entries from one dictionary into another dictionary.
|
||||
/// </summary>
|
||||
@@ -71,12 +111,25 @@ public sealed class AssistantState
|
||||
/// <typeparam name="TValue">The dictionary value type.</typeparam>
|
||||
/// <param name="source">The source dictionary.</param>
|
||||
/// <param name="target">The target dictionary.</param>
|
||||
private static void CopyDictionary<TKey, TValue>(Dictionary<TKey, TValue> source, Dictionary<TKey, TValue> target) where TKey : notnull
|
||||
/// <param name="copyValue">Copies a value which the form changes in place; null for a value nobody can change, such as a string.</param>
|
||||
private static void CopyDictionary<TKey, TValue>(Dictionary<TKey, TValue> source, Dictionary<TKey, TValue> target, Func<TValue, TValue>? copyValue = null) where TKey : notnull
|
||||
{
|
||||
foreach (var (key, value) in source)
|
||||
target[key] = value;
|
||||
target[key] = copyValue is null ? value : copyValue(value);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tells whether two dictionaries hold the same keys with the same values.
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue">The dictionary value type.</typeparam>
|
||||
/// <param name="first">The first dictionary.</param>
|
||||
/// <param name="second">The second dictionary.</param>
|
||||
/// <param name="isSame">Tells whether two values are the same.</param>
|
||||
/// <returns><c>true</c> when both dictionaries hold the same entries; otherwise, <c>false</c>.</returns>
|
||||
private static bool HaveSameEntries<TValue>(Dictionary<string, TValue> first, Dictionary<string, TValue> second, Func<TValue, TValue, bool> 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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -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<MediaOperation> operations = [];
|
||||
|
||||
/// <summary>The active or queued import operation for each owner.</summary>
|
||||
private readonly Dictionary<MediaImportOwner, MediaOperation> currentImports = [];
|
||||
private readonly Dictionary<ImportOwner, MediaOperation> currentImports = [];
|
||||
|
||||
/// <summary>The latest active or unacknowledged terminal state for each owner.</summary>
|
||||
private readonly Dictionary<MediaImportOwner, MediaImportSnapshot> snapshots = [];
|
||||
private readonly Dictionary<ImportOwner, MediaImportSnapshot> snapshots = [];
|
||||
|
||||
/// <summary>Successful results waiting for their concrete UI target.</summary>
|
||||
private readonly Dictionary<MediaImportTarget, PendingDelivery> pendingDeliveries = [];
|
||||
private readonly Dictionary<ImportTarget, PendingDelivery> pendingDeliveries = [];
|
||||
|
||||
/// <summary>Terminal notifications waiting for their owner surface to be displayed.</summary>
|
||||
private readonly Dictionary<MediaImportOwner, MediaImportOutcome> outcomes = [];
|
||||
private readonly Dictionary<ImportOwner, MediaImportOutcome> outcomes = [];
|
||||
|
||||
/// <summary>Owners whose complete file batches are managed by this service.</summary>
|
||||
private readonly HashSet<MediaImportOwner> activeBatches = [];
|
||||
private readonly HashSet<ImportOwner> activeBatches = [];
|
||||
|
||||
/// <summary>Batch-level cancellation keeps Stop effective between two files.</summary>
|
||||
private readonly Dictionary<MediaImportOwner, CancellationTokenSource> batchCancellations = [];
|
||||
private readonly Dictionary<ImportOwner, CancellationTokenSource> batchCancellations = [];
|
||||
|
||||
/// <summary>Prevents new work after disposal.</summary>
|
||||
private bool disposed;
|
||||
|
||||
/// <summary>Raised only with the owner whose copied state changed.</summary>
|
||||
public event Action<MediaImportOwner>? StateChanged;
|
||||
public event Action<ImportOwner>? StateChanged;
|
||||
|
||||
/// <summary>Gets whether one owner has queued, running, or canceling media work.</summary>
|
||||
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;
|
||||
|
||||
/// <summary>Gets the last retained state for one owner.</summary>
|
||||
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(
|
||||
}
|
||||
|
||||
/// <summary>Gets copied results that have not yet been applied by one target.</summary>
|
||||
public MediaImportDelivery? GetPendingDelivery(MediaImportTarget target)
|
||||
public MediaImportDelivery? GetPendingDelivery(ImportTarget target)
|
||||
{
|
||||
lock (this.stateLock)
|
||||
{
|
||||
@@ -118,7 +119,7 @@ public sealed class MediaTranscriptionService(
|
||||
}
|
||||
|
||||
/// <summary>Consumes one terminal notification when its owner surface is displayed.</summary>
|
||||
public MediaImportOutcome? TryConsumeOutcome(MediaImportOwner owner)
|
||||
public MediaImportOutcome? TryConsumeOutcome(ImportOwner owner)
|
||||
{
|
||||
MediaImportOutcome? outcome;
|
||||
lock (this.stateLock)
|
||||
@@ -135,7 +136,7 @@ public sealed class MediaTranscriptionService(
|
||||
}
|
||||
|
||||
/// <summary>Discards retained inactive state and deletes unclaimed managed transcript files.</summary>
|
||||
public void ClearOwnerState(MediaImportOwner owner)
|
||||
public void ClearOwnerState(ImportOwner owner)
|
||||
{
|
||||
List<FileAttachment> discardedAttachments = [];
|
||||
lock (this.stateLock)
|
||||
@@ -160,7 +161,7 @@ public sealed class MediaTranscriptionService(
|
||||
}
|
||||
|
||||
/// <summary>Starts an owner-managed attachment batch and returns without holding the UI event handler.</summary>
|
||||
public bool TryStartAttachmentBatch(IReadOnlyList<string> mediaPaths, MediaImportTarget target, ChatThread? ownerChat = null)
|
||||
public bool TryStartAttachmentBatch(IReadOnlyList<string> mediaPaths, ImportTarget target, ChatThread? ownerChat = null)
|
||||
{
|
||||
this.ThrowIfDisposed();
|
||||
if (mediaPaths.Count is 0)
|
||||
@@ -181,7 +182,7 @@ public sealed class MediaTranscriptionService(
|
||||
}
|
||||
|
||||
/// <summary>Starts a reattachable file-content import for one stable assistant field.</summary>
|
||||
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(
|
||||
}
|
||||
|
||||
/// <summary>Completes a field import independently of the originating Blazor component.</summary>
|
||||
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(
|
||||
/// <param name="target">The field which receives the transcript.</param>
|
||||
/// <param name="mediaPath">The recording the transcript belongs to.</param>
|
||||
/// <param name="transcript">The transcript as the provider returned it.</param>
|
||||
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(
|
||||
}
|
||||
|
||||
/// <summary>Serially transcribes a complete owner batch while retaining every successful result.</summary>
|
||||
private async Task RunAttachmentBatchAsync(IReadOnlyList<string> mediaPaths, MediaImportTarget target, ChatThread? ownerChat)
|
||||
private async Task RunAttachmentBatchAsync(IReadOnlyList<string> mediaPaths, ImportTarget target, ChatThread? ownerChat)
|
||||
{
|
||||
CancellationToken batchToken;
|
||||
lock (this.stateLock)
|
||||
@@ -364,7 +365,7 @@ public sealed class MediaTranscriptionService(
|
||||
}
|
||||
|
||||
/// <summary>Adds a successful partial result to the retained owner snapshot.</summary>
|
||||
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(
|
||||
/// <param name="target">Media import target.</param>
|
||||
/// <param name="token">Caller cancellation token.</param>
|
||||
/// <returns>A typed terminal result.</returns>
|
||||
private async Task<MediaTranscriptionResult> TranscribeImportAsync(string mediaPath, MediaImportTarget target, CancellationToken token = default)
|
||||
private async Task<MediaTranscriptionResult> 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<MediaTranscriptionResult> TranscribeVoiceAsync(string mediaPath, CancellationToken token = default) => this.TranscribeAsync(mediaPath, token);
|
||||
|
||||
/// <summary>Cancels only the queued or active operation belonging to one owner.</summary>
|
||||
public async Task StopAsync(MediaImportOwner owner)
|
||||
public async Task StopAsync(ImportOwner owner)
|
||||
{
|
||||
MediaOperation? operation;
|
||||
MediaImportSnapshot? snapshot;
|
||||
@@ -798,7 +799,7 @@ public sealed class MediaTranscriptionService(
|
||||
/// <param name="target">Optional visible media import target.</param>
|
||||
/// <param name="token">Caller token linked to the operation.</param>
|
||||
/// <returns>The registered operation.</returns>
|
||||
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(
|
||||
}
|
||||
|
||||
/// <summary>Updates and publishes copied state for exactly one owner.</summary>
|
||||
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(
|
||||
|
||||
/// <summary>Publishes one retained terminal result after an entire target batch ended.</summary>
|
||||
private void CompleteImport(
|
||||
MediaImportTarget target,
|
||||
ImportTarget target,
|
||||
string fileName,
|
||||
MediaImportStatus status,
|
||||
IReadOnlyList<MediaImportFailure> failures,
|
||||
@@ -869,14 +870,14 @@ public sealed class MediaTranscriptionService(
|
||||
}
|
||||
|
||||
/// <summary>Publishes state changes without allowing one stale UI subscriber to fault a worker.</summary>
|
||||
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<MediaImportOwner>)@delegate;
|
||||
var handler = (Action<ImportOwner>)@delegate;
|
||||
|
||||
try
|
||||
{
|
||||
@@ -984,14 +985,14 @@ public sealed class MediaTranscriptionService(
|
||||
/// <summary>Creates operation state linked to a caller token.</summary>
|
||||
/// <param name="target">Optional visible media import target.</param>
|
||||
/// <param name="token">Caller cancellation token.</param>
|
||||
public MediaOperation(MediaImportTarget? target, CancellationToken token)
|
||||
public MediaOperation(ImportTarget? target, CancellationToken token)
|
||||
{
|
||||
this.Target = target;
|
||||
this.Cancellation = CancellationTokenSource.CreateLinkedTokenSource(token);
|
||||
}
|
||||
|
||||
/// <summary>Gets the optional visible import target; voice operations have none.</summary>
|
||||
public MediaImportTarget? Target { get; }
|
||||
public ImportTarget? Target { get; }
|
||||
|
||||
/// <summary>Gets the unique temporary-path identifier.</summary>
|
||||
public Guid Id { get; } = Guid.NewGuid();
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
namespace AIStudio.Tools.Web;
|
||||
|
||||
/// <summary>
|
||||
/// What went wrong while loading web content, so that the reader can tell the user, see WebContentImportResult.
|
||||
/// </summary>
|
||||
public enum WebContentImportIssue
|
||||
{
|
||||
/// <summary>
|
||||
/// The content arrived as asked for.
|
||||
/// </summary>
|
||||
NONE,
|
||||
|
||||
/// <summary>
|
||||
/// The content arrived, but uncleaned, since no model is available for the content cleaner.
|
||||
/// </summary>
|
||||
NOT_CLEANED_NO_MODEL,
|
||||
|
||||
/// <summary>
|
||||
/// The content arrived, but uncleaned, since the model of the content cleaner gave no answer.
|
||||
/// </summary>
|
||||
NOT_CLEANED_NO_ANSWER,
|
||||
|
||||
/// <summary>
|
||||
/// The content could not be loaded, see WebContentImportResult.ErrorMessage.
|
||||
/// </summary>
|
||||
LOAD_FAILED,
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
namespace AIStudio.Tools.Web;
|
||||
|
||||
/// <summary>
|
||||
/// What the web content reader of an assistant asks the WebContentImportService to load.
|
||||
/// </summary>
|
||||
/// <param name="Url">The address the user typed.</param>
|
||||
/// <param name="CleanContent">Whether the text content cleaner, an AI task, cleans the page.</param>
|
||||
/// <param name="AssistantProvider">The model of the assistant around the reader, which the cleaner falls back on, see WebContentImportService.GetCleanerProviderOptions.</param>
|
||||
public sealed record WebContentImportRequest(string Url, bool CleanContent, AIStudio.Settings.Provider AssistantProvider);
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace AIStudio.Tools.Web;
|
||||
|
||||
/// <summary>
|
||||
/// What loading web content brought, waiting for the reader of its field, see WebContentImportService.TryTakeResult.
|
||||
/// </summary>
|
||||
/// <param name="Url">The address the content was loaded from.</param>
|
||||
/// <param name="Markdown">The content, filtered for prompt injections. It is what arrived before an error, which may be nothing.</param>
|
||||
/// <param name="Issue">What went wrong, if anything.</param>
|
||||
/// <param name="ErrorMessage">Why the content could not be loaded, for <see cref="WebContentImportIssue.LOAD_FAILED"/>; null otherwise.</param>
|
||||
public sealed record WebContentImportResult(string Url, string Markdown, WebContentImportIssue Issue = WebContentImportIssue.NONE, string? ErrorMessage = null);
|
||||
@@ -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;
|
||||
|
||||
/// <summary>
|
||||
/// Loads web content for the web content readers of assistants, in the background.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
public sealed class WebContentImportService(
|
||||
WebPageRetrievalService webPageRetrievalService,
|
||||
PromptInjectionGuardService promptInjectionGuardService,
|
||||
TextContentCleaningOperation textContentCleaning,
|
||||
AIOperationProviderResolver providerResolver,
|
||||
SettingsManager settingsManager,
|
||||
ILogger<WebContentImportService> logger)
|
||||
{
|
||||
/// <summary>
|
||||
/// How long loading one page may take.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The user waits for this text, so it is shorter than what the tools allow themselves for the
|
||||
/// pages they fetch.
|
||||
/// </remarks>
|
||||
private const int TIMEOUT_SECONDS = 60;
|
||||
|
||||
/// <summary>Protects the running imports and the waiting results.</summary>
|
||||
private readonly Lock stateLock = new();
|
||||
|
||||
/// <summary>The state of each running import.</summary>
|
||||
private readonly Dictionary<ImportTarget, WebContentImportSnapshot> runningImports = [];
|
||||
|
||||
/// <summary>Results waiting for the reader of their field.</summary>
|
||||
private readonly Dictionary<ImportTarget, WebContentImportResult> results = [];
|
||||
|
||||
/// <summary>Raised with the owner whose imports changed: one started, went on to its next step, or ended.</summary>
|
||||
public event Action<ImportOwner>? StateChanged;
|
||||
|
||||
/// <summary>
|
||||
/// What the reader adds to the choice of the provider for the content cleaner.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Without a model of its own, the cleaner falls back on the model of the assistant, and then on
|
||||
/// the app-wide default. Its minimum confidence applies to both of them: a model somebody picked
|
||||
/// for the assistant has to clear the bar of the cleaner before the cleaner uses it.
|
||||
/// </remarks>
|
||||
/// <param name="settingsManager">The settings, for the app-wide default.</param>
|
||||
/// <param name="assistantProvider">The model of the assistant around the reader.</param>
|
||||
/// <returns>The options for the provider resolver.</returns>
|
||||
internal static AIOperationProviderOptions GetCleanerProviderOptions(SettingsManager settingsManager, AIStudio.Settings.Provider assistantProvider) => new()
|
||||
{
|
||||
FallbackProviderIds = [assistantProvider.Id, settingsManager.AppDefaultProviderId],
|
||||
OwnMinimumConfidenceAppliesToFallbacks = true,
|
||||
};
|
||||
|
||||
/// <summary>Gets whether one of the fields of an owner is loading web content.</summary>
|
||||
/// <param name="owner">The owner, e.g., an assistant.</param>
|
||||
/// <returns><c>true</c> while an import of the owner runs.</returns>
|
||||
public bool IsBusy(ImportOwner owner)
|
||||
{
|
||||
lock (this.stateLock)
|
||||
return this.runningImports.Keys.Any(target => target.Owner == owner);
|
||||
}
|
||||
|
||||
/// <summary>Gets the state of the import which fills a field, while it runs.</summary>
|
||||
/// <param name="target">The field.</param>
|
||||
/// <returns>A copy of the state, or <c>null</c> when no import of the field runs.</returns>
|
||||
public WebContentImportSnapshot? GetSnapshot(ImportTarget target)
|
||||
{
|
||||
lock (this.stateLock)
|
||||
return this.runningImports.GetValueOrDefault(target);
|
||||
}
|
||||
|
||||
/// <summary>Gets copies of the states of all running imports, e.g., for the navigation.</summary>
|
||||
public IReadOnlyCollection<WebContentImportSnapshot> GetSnapshots()
|
||||
{
|
||||
lock (this.stateLock)
|
||||
return [.. this.runningImports.Values];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts loading web content into a field, unless an import of that field still runs.
|
||||
/// </summary>
|
||||
/// <param name="target">The field to fill.</param>
|
||||
/// <param name="request">What to load.</param>
|
||||
/// <returns><c>true</c> when the import started.</returns>
|
||||
public bool TryStart(ImportTarget target, WebContentImportRequest request) => this.Start(target, request, reportStep => this.ImportAsync(request, reportStep)) is not null;
|
||||
|
||||
/// <summary>
|
||||
/// Starts an import into a field, unless an import of that field still runs.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// 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.
|
||||
/// </remarks>
|
||||
/// <param name="target">The field to fill.</param>
|
||||
/// <param name="request">What the import loads, for its state and for the result of an import which failed unexpectedly.</param>
|
||||
/// <param name="import">The work, which reports each step it reaches.</param>
|
||||
/// <returns>The running import, or <c>null</c> when an import of the field still runs.</returns>
|
||||
internal Task? Start(ImportTarget target, WebContentImportRequest request, Func<Action<ReadWebContentSteps>, Task<WebContentImportResult>> 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));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes the result which waits for a field, so that it is delivered exactly once.
|
||||
/// </summary>
|
||||
/// <param name="target">The field.</param>
|
||||
/// <returns>The result, or <c>null</c> when none waits.</returns>
|
||||
public WebContentImportResult? TryTakeResult(ImportTarget target)
|
||||
{
|
||||
lock (this.stateLock)
|
||||
return this.results.Remove(target, out var result) ? result : null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Discards the results which wait for the fields of an owner, e.g., when the user resets the assistant.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A running import is left alone, as with media files: the assistant does not reset while one runs.
|
||||
/// </remarks>
|
||||
/// <param name="owner">The owner.</param>
|
||||
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<Action<ReadWebContentSteps>, Task<WebContentImportResult>> 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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Loads a page, filters it for prompt injections, and cleans it if asked to.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Never throws: the content which arrived before an error goes into the result, together with the error.
|
||||
/// </remarks>
|
||||
private async Task<WebContentImportResult> ImportAsync(WebContentImportRequest request, Action<ReadWebContentSteps> 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);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tells every handler about a change, so that a handler which throws keeps none of the others from hearing about it.
|
||||
/// </summary>
|
||||
private void NotifyStateChanged(ImportOwner owner)
|
||||
{
|
||||
if (this.StateChanged is not { } stateChanged)
|
||||
return;
|
||||
|
||||
foreach (var @delegate in stateChanged.GetInvocationList())
|
||||
{
|
||||
try
|
||||
{
|
||||
((Action<ImportOwner>)@delegate)(owner);
|
||||
}
|
||||
catch (Exception exception)
|
||||
{
|
||||
logger.LogError(exception, "A handler failed while it was told about a changed web content import.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
using AIStudio.Components;
|
||||
using AIStudio.Tools.Imports;
|
||||
|
||||
namespace AIStudio.Tools.Web;
|
||||
|
||||
/// <summary>
|
||||
/// A copy of the state of a running web content import, see WebContentImportService.GetSnapshot.
|
||||
/// </summary>
|
||||
/// <param name="Target">The field the import fills.</param>
|
||||
/// <param name="Url">The address the import loads.</param>
|
||||
/// <param name="CleanContent">Whether the import cleans the page.</param>
|
||||
/// <param name="Step">The step the import is at: loading, parsing, or cleaning.</param>
|
||||
public sealed record WebContentImportSnapshot(ImportTarget Target, string Url, bool CleanContent, ReadWebContentSteps Step);
|
||||
Reference in new issue
Block a user