XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Text.Json.Nodes;
using XFEExtension.NetCore.XUnit.Assertions;
using XFEExtension.NetCore.XUnit.Attributes;
using XFEWorkflow.Plugins.AgentBrowser;

namespace XFEWorkflow.Test;

[TestFixture]
public class AgentSessionTests
{
    [Test]
    public async Task BrowserTabsSelectionAndProfilesPersistWithoutStealingAnotherActiveSession()
    {
        await using var workspace = new TestWorkspace(); var store = new AgentSessionStore(workspace.Paths.Root);
        var first = new AgentSession { BrowserUrl = "https://example.test/legacy", UseLegacyBrowserProfile = true }; first.EnsureBrowserTabs();
        var original = first.BrowserTabs[0].Id; var other = Guid.NewGuid().ToString("N");
        first.BrowserTabs.Add(new(other, "https://example.test/second", "第二个标签 😀")); first.ActiveBrowserTabId = other;
        first.EnsureBrowserTabs(); await store.SaveAsync(first.Snapshot());
        var second = new AgentSession(); second.EnsureBrowserTabs(); await store.SaveAsync(second.Snapshot());
        first.BrowserTabs[0] = first.BrowserTabs[0] with { Title = "后台标签" }; await store.SaveAsync(first.Snapshot(), activate: false);
        var reopened = new AgentSessionStore(workspace.Paths.Root);
        Assert.Equal(second.Id, (await reopened.ListAsync()).ActiveSessionId);
        var restored = await reopened.LoadAsync(first.Id);
        Assert.Equal(2, restored.BrowserTabs.Count); Assert.Equal(other, restored.ActiveBrowserTabId); Assert.True(restored.UseLegacyBrowserProfile);
        Assert.Equal("https://example.test/legacy", restored.BrowserTabs.Single(x => x.Id == original).Url);
        Assert.Equal("第二个标签 😀", restored.BrowserTabs.Single(x => x.Id == other).Title);
        var independent = await reopened.LoadAsync(second.Id); Assert.Equal(1, independent.BrowserTabs.Count);
        Assert.False(independent.UseLegacyBrowserProfile); Assert.True(independent.BrowserTabs[0].Id != original);
    }
    [Test]
    public void BrowserTabMigrationNormalizesMissingSelectionDuplicateIdsAndUnsafeUrls()
    {
        var legacy = new AgentSession { BrowserUrl = "https://example.test/old" }; legacy.EnsureBrowserTabs();
        Assert.Equal("https://example.test/old", legacy.BrowserTabs.Single().Url); Assert.Equal(legacy.BrowserTabs[0].Id, legacy.ActiveBrowserTabId);
        var id = Guid.NewGuid().ToString("N");
        var invalid = new AgentSession { BrowserTabs = [new("../bad", "https://example.test"), new(id, "file:///C:/test.txt"), new(id, "https://example.test")], ActiveBrowserTabId = "missing" };
        invalid.EnsureBrowserTabs(); Assert.Equal(1, invalid.BrowserTabs.Count); Assert.Equal("about:blank", invalid.BrowserTabs[0].Url);
        invalid.BrowserTabs.Clear(); invalid.EnsureBrowserTabs(); Assert.Equal(1, invalid.BrowserTabs.Count);
    }
    [Test]
    public async Task MultipleSessionsPersistSelectionDraftsAvatarsAndIndependentContextAcrossRestart()
    {
        await using var workspace = new TestWorkspace(); var store = new AgentSessionStore(workspace.Paths.Root);
        var first = new AgentSession { Draft = "下次继续 😀", BrowserUrl = "https://example.test/", ContextKey = AgentSession.Key(new()) };
        first.AddUser("u1", "联系人列表 😀", new("account-1", "测试作者", "data:image/png;base64,ZmFrZQ=="));
        first.Record(new("assistant_start", "a1", "", MessageId: "turn-1"));
        first.Record(new("assistant_delta", "reply-1", "你好", MessageId: "turn-1"));
        first.Record(new("assistant_delta", "reply-1", " 😀", MessageId: "turn-1"));
        first.Context = new(new JsonObject { ["role"] = "user", ["content"] = "联系人列表 😀" }, new JsonObject { ["role"] = "assistant", ["content"] = "你好 😀" });
        await store.SaveAsync(first.Snapshot());
        var second = new AgentSession { Title = "另一个任务", TitleEdited = true }; second.AddUser("u2", "第二个任务", new("account-2", "另一作者"));
        await store.SaveAsync(second.Snapshot()); await store.SaveAsync(first.Snapshot());
        var reopened = new AgentSessionStore(workspace.Paths.Root); var catalog = await reopened.ListAsync();
        Assert.Equal(2, catalog.Sessions.Count); Assert.Equal(first.Id, catalog.ActiveSessionId);
        var restored = await reopened.LoadAsync(first.Id);
        Assert.Equal("下次继续 😀", restored.Draft); Assert.Equal("https://example.test/", restored.BrowserUrl);
        Assert.Equal("测试作者", restored.Users["account-1"].DisplayName); Assert.True(restored.Users["account-1"].AvatarDataUri.StartsWith("data:image/png"));
        Assert.Equal("你好 😀", restored.Records.Single(x => x.Type == "message_done").Text);
        Assert.Equal(2, restored.Context.Count); Assert.Equal(0, (await reopened.LoadAsync(second.Id)).Context.Count);
        var json = await File.ReadAllTextAsync(Path.Combine(workspace.Paths.Root, "ChatSessions", first.Id + ".json"));
        Assert.True(json.Contains("联系人列表")); Assert.True(json.Contains("😀"));
    }
    [Test]
    public void TranscriptCombinesStreamFragmentsAndPreservesToolInputsOutputsAndRoundIdentity()
    {
        var session = new AgentSession(); session.AddUser("user", string.Concat(Enumerable.Repeat("😀", 40)), new("u", "用户"));
        Assert.Equal(33, session.Title.EnumerateRunes().Count());
        session.Record(new("assistant_start", "group", "", MessageId: "group"));
        session.Record(new("tool_start", "tool-1", "{\"code\":\"return page.title()\"}", "browser_execute", MessageId: "group"));
        session.Record(new("tool_result", "tool-1", "网页标题", "browser_execute", MessageId: "group"), "Conversations/shot.png");
        session.Record(new("assistant_delta", "response", "结果", MessageId: "group"));
        session.Record(new("assistant_delta", "response", "已确认", MessageId: "group"));
        session.Record(new("message_done", "response", "结果已确认。", MessageId: "group"));
        var tool = session.Records.Single(x => x.Id == "tool-1");
        Assert.Equal("tool_result", tool.Type); Assert.True(tool.Input!.Contains("page.title")); Assert.Equal("网页标题", tool.Text);
        Assert.Equal("Conversations/shot.png", tool.ImagePath); Assert.Equal("group", tool.MessageId);
        Assert.Equal("结果已确认。", session.Records.Single(x => x.Id == "response").Text);
        Assert.Equal(4, session.Records.Count);
    }
    [Test]
    public async Task InterruptedTurnIsMarkedWithoutReplayingToolsAndKeepsOnlyCompletedContext()
    {
        await using var workspace = new TestWorkspace(); var store = new AgentSessionStore(workspace.Paths.Root);
        var session = new AgentSession { TurnInProgress = true, Context = new(new JsonObject { ["role"] = "user", ["content"] = "此前任务" }, new JsonObject { ["role"] = "assistant", ["content"] = "此前完成" }) };
        session.Record(new("tool_start", "pending", "click()", "browser_execute", MessageId: "turn"));
        await store.SaveAsync(session.Snapshot());
        var recovered = await new AgentSessionStore(workspace.Paths.Root).LoadAsync(session.Id);
        Assert.False(recovered.TurnInProgress); Assert.Equal(2, recovered.Context.Count);
        Assert.Equal("tool_error", recovered.Records[0].Type); Assert.True(recovered.Records[0].Text.Contains("未自动重新执行"));
        Assert.Equal(1, recovered.Records.Count(x => x.Type == "error"));
        var again = await new AgentSessionStore(workspace.Paths.Root).LoadAsync(session.Id);
        Assert.Equal(recovered.Records.Count, again.Records.Count);
        using var http = new HttpClient(); new AgentConversation(http).RestoreHistory(again.Context);
    }
    [Test]
    public async Task CorruptPrimaryFallsBackToBackupAndRebuildsCatalogWithoutDeletingFiles()
    {
        await using var workspace = new TestWorkspace(); var store = new AgentSessionStore(workspace.Paths.Root);
        var session = new AgentSession { Title = "可靠备份" }; await store.SaveAsync(session.Snapshot());
        session.Title = "最新版本"; await store.SaveAsync(session.Snapshot());
        var directory = Path.Combine(workspace.Paths.Root, "ChatSessions");
        await File.WriteAllTextAsync(Path.Combine(directory, session.Id + ".json"), "{");
        await File.WriteAllTextAsync(Path.Combine(directory, "catalog.json"), "{");
        await File.WriteAllTextAsync(Path.Combine(directory, "catalog.json.bak"), "{");
        var reopened = new AgentSessionStore(workspace.Paths.Root); var catalog = await reopened.ListAsync();
        Assert.Equal(1, catalog.Sessions.Count); Assert.Equal("可靠备份", (await reopened.LoadAsync(session.Id)).Title);
        Assert.True(reopened.Warnings.Count > 0); Assert.True(File.Exists(Path.Combine(directory, session.Id + ".json")));
        await Assert.ThrowsAsync<ArgumentException>(() => reopened.LoadAsync("../outside"));
        await Assert.ThrowsAsync<ArgumentException>(() => reopened.DeleteAsync("../outside"));
    }
    [Test]
    public async Task SessionDeletionRenameAndCancellationPreserveOtherHistory()
    {
        await using var workspace = new TestWorkspace(); var store = new AgentSessionStore(workspace.Paths.Root);
        var first = new AgentSession(); var second = new AgentSession { Title = "保留任务" };
        await Task.WhenAll(store.SaveAsync(first.Snapshot()), store.SaveAsync(second.Snapshot()));
        first.Title = "我的会话"; first.TitleEdited = true; await store.SaveAsync(first.Snapshot());
        using var cancelled = new CancellationTokenSource(); cancelled.Cancel();
        await Assert.ThrowsAsync<OperationCanceledException>(() => store.SaveAsync(new() { Title = "不应保存" }, cancelled.Token));
        await store.DeleteAsync(first.Id); var reopened = new AgentSessionStore(workspace.Paths.Root);
        var catalog = await reopened.ListAsync(); Assert.Equal(1, catalog.Sessions.Count); Assert.Equal(second.Id, catalog.ActiveSessionId);
        Assert.Equal("保留任务", (await reopened.LoadAsync(second.Id)).Title);
        Assert.False(File.Exists(Path.Combine(workspace.Paths.Root, "ChatSessions", first.Id + ".json.bak")));
    }
    [Test]
    public async Task ScreenshotReferencesStayInsidePluginDataAndMissingFilesUseFallback()
    {
        await using var workspace = new TestWorkspace(); var data = Path.Combine(workspace.Paths.Root, "AgentData"); Directory.CreateDirectory(data);
        var store = new AgentSessionStore(data); var outside = Path.Combine(workspace.Paths.Root, "outside.png"); await File.WriteAllBytesAsync(outside, [1]);
        var inside = Path.Combine(data, "shot.png"); await File.WriteAllBytesAsync(inside, [1]);
        Assert.Equal("shot.png", store.RelativeImage(inside)); Assert.Equal(inside, store.ImagePath("shot.png"));
        Assert.True(store.ImagePath("../outside.png") is null); Assert.True(store.ImagePath(outside) is null); Assert.True(store.RelativeImage(outside) is null);
        File.Delete(inside); Assert.True(store.ImagePath("shot.png") is null);
    }
}