using AIStudio.Chat;
using AIStudio.Chat.Embedded;
namespace AIStudio.Tests.Chat.Embedded;
///
/// Keeps embedded chats in memory, as they were when they were stored last.
///
public sealed class InMemoryEmbeddedChatStore : IEmbeddedChatStore
{
private readonly Dictionary threads = [];
///
/// Whether loading fails, as with a chat this version cannot open.
///
public bool CannotOpen { get; init; }
///
/// How often a chat was stored.
///
public int SaveCount { get; private set; }
///
/// Gets the blocks of a chat as they were stored last, or none.
///
/// The ID of the chat.
public IReadOnlyList StoredBlocks(Guid chatId) => this.threads.TryGetValue(chatId, out var thread) ? thread.Blocks : [];
///
public Task LoadThreadAsync(Guid chatId, CancellationToken token = default)
{
if (this.CannotOpen)
throw new InvalidDataException("A newer version stored this chat.");
return Task.FromResult(this.threads.TryGetValue(chatId, out var thread) ? thread : null);
}
///
public Task SaveThreadAsync(ChatThread thread, CancellationToken token = default)
{
// A copy of the list, so that what the chat adds later does not change what was stored:
this.threads[thread.ChatId] = thread with { Blocks = [.. thread.Blocks] };
this.SaveCount++;
return Task.CompletedTask;
}
}