using System.Text.Encodings.Web;
using System.Text.Json;
using System.Text;
using XFEWorkflow.Abstractions;
namespace XFEWorkflow.Plugins.AgentBrowser;
/// Serialized atomic local writes. The catalog stays small; each conversation has its own document and backup.
public sealed class AgentSessionStore(string dataDirectory)
{
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web) { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
private readonly string root = Path.GetFullPath(dataDirectory);
private readonly string directory = Path.Combine(Path.GetFullPath(dataDirectory), "ChatSessions");
private readonly SemaphoreSlim gate = new(1);
private AgentSessionCatalog? catalog;
public List Warnings { get; } = [];
public async Task ListAsync(CancellationToken ct = default)
{
await gate.WaitAsync(ct).ConfigureAwait(false);
try { return await Task.Run(async () => Copy(await CatalogAsync(ct)), ct).ConfigureAwait(false); }
finally { gate.Release(); }
}
public async Task LoadAsync(string id, CancellationToken ct = default)
{
var path = SessionPath(id);
await gate.WaitAsync(ct).ConfigureAwait(false);
try
{
return await Task.Run(async () =>
{
var value = await ReadAsync(path, ct) ?? throw new FileNotFoundException("会话文件不存在", path);
Validate(value, id);
if (value.RecoverInterruptedTurn()) await SaveCoreAsync(value, ct);
return value;
}, ct).ConfigureAwait(false);
}
finally { gate.Release(); }
}
public async Task SaveAsync(AgentSession snapshot, CancellationToken ct = default, bool activate = true)
{
Validate(snapshot, snapshot.Id);
await gate.WaitAsync(ct).ConfigureAwait(false);
try { await Task.Run(() => SaveCoreAsync(snapshot, ct, activate), ct).ConfigureAwait(false); }
finally { gate.Release(); }
}
public async Task DeleteAsync(string id, CancellationToken ct = default)
{
var path = SessionPath(id);
await gate.WaitAsync(ct).ConfigureAwait(false);
try
{
await Task.Run(async () =>
{
var list = await CatalogAsync(ct);
list.Sessions.RemoveAll(x => x.Id == id);
if (list.ActiveSessionId == id) list.ActiveSessionId = list.Sessions.FirstOrDefault()?.Id ?? "";
await WriteAsync(Path.Combine(directory, "catalog.json"), list, ct);
File.Delete(path); File.Delete(path + ".bak");
}, ct).ConfigureAwait(false);
}
finally { gate.Release(); }
}
public string? RelativeImage(string path)
{
var absolute = Path.GetFullPath(path);
return absolute.StartsWith(root.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)
? Path.GetRelativePath(root, absolute) : null;
}
public string? ImagePath(string? relative)
{
if (string.IsNullOrWhiteSpace(relative) || Path.IsPathRooted(relative)) return null;
try
{
var path = Path.GetFullPath(Path.Combine(root, relative));
return RelativeImage(path) is not null && File.Exists(path) && new FileInfo(path).Length <= 8 * 1024 * 1024 ? path : null;
}
catch (Exception ex) when (ex is ArgumentException or IOException or UnauthorizedAccessException) { return null; }
}
private async Task SaveCoreAsync(AgentSession value, CancellationToken ct, bool activate = true)
{
var list = await CatalogAsync(ct);
await WriteAsync(SessionPath(value.Id), value, ct);
list.Sessions.RemoveAll(x => x.Id == value.Id); list.Sessions.Add(value.Summary());
list.Sessions = list.Sessions.OrderByDescending(x => x.UpdatedAt).ToList();
if (activate) list.ActiveSessionId = value.Id;
await WriteAsync(Path.Combine(directory, "catalog.json"), list, ct);
}
private async Task CatalogAsync(CancellationToken ct)
{
if (catalog is not null) return catalog;
Directory.CreateDirectory(directory);
AgentSessionCatalog? value;
try { value = await ReadAsync(Path.Combine(directory, "catalog.json"), ct); }
catch (InvalidDataException) { Warnings.Add("历史会话目录损坏,已从单独的会话文件恢复列表。"); value = null; }
if (value?.SchemaVersion != 1) value = new();
value.Sessions = value.Sessions.Where(x => ValidId(x.Id) && (File.Exists(SessionPath(x.Id)) || File.Exists(SessionPath(x.Id) + ".bak")))
.DistinctBy(x => x.Id).ToList();
foreach (var path in Directory.EnumerateFiles(directory, "*.json"))
{
var id = Path.GetFileNameWithoutExtension(path);
if (!ValidId(id) || value.Sessions.Any(x => x.Id == id)) continue;
try
{
var session = await ReadAsync(path, ct);
if (session is null) continue;
Validate(session, id); value.Sessions.Add(session.Summary());
}
catch (InvalidDataException) { Warnings.Add("一份历史会话无法读取,原文件已保留:" + id); }
}
value.Sessions = value.Sessions.OrderByDescending(x => x.UpdatedAt).ToList();
if (!value.Sessions.Any(x => x.Id == value.ActiveSessionId)) value.ActiveSessionId = value.Sessions.FirstOrDefault()?.Id ?? "";
return catalog = value;
}
private async Task ReadAsync(string path, CancellationToken ct) where T : class
{
var found = false;
foreach (var candidate in new[] { path, path + ".bak" })
{
if (!File.Exists(candidate)) continue;
found = true;
try
{
await using var stream = new FileStream(candidate, FileMode.Open, FileAccess.Read, FileShare.Read, 8192, true);
var result = await JsonSerializer.DeserializeAsync(stream, Json, ct) ?? throw new JsonException("会话为空");
if (candidate != path) Warnings.Add("已从备份恢复会话文件:" + Path.GetFileName(path));
return result;
}
catch (JsonException) { }
}
if (found) throw new InvalidDataException("会话文件和备份无法读取:" + Path.GetFileName(path));
return null;
}
private static async Task WriteAsync(string path, T value, CancellationToken ct)
{
Directory.CreateDirectory(Path.GetDirectoryName(path)!);
var temporary = path + "." + Guid.NewGuid().ToString("N") + ".tmp";
try
{
await File.WriteAllTextAsync(temporary, WorkflowJson.SerializeDisplay(value), new UTF8Encoding(false), ct);
ct.ThrowIfCancellationRequested();
if (File.Exists(path)) File.Copy(path, path + ".bak", true);
File.Move(temporary, path, true);
}
finally { File.Delete(temporary); }
}
private string SessionPath(string id) => ValidId(id) ? Path.Combine(directory, id + ".json") : throw new ArgumentException("会话 ID 无效");
private static bool ValidId(string id) => Guid.TryParseExact(id, "N", out _);
private static void Validate(AgentSession value, string id)
{
if (value.SchemaVersion != 1 || value.Id != id || !ValidId(id) || value.Records is null || value.Context is null || value.Users is null || string.IsNullOrWhiteSpace(value.Title))
throw new InvalidDataException("会话内容格式无效");
}
private static AgentSessionCatalog Copy(AgentSessionCatalog value) => new() { SchemaVersion = value.SchemaVersion, ActiveSessionId = value.ActiveSessionId, Sessions = [.. value.Sessions] };
}