using System.Text.Json.Nodes; using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Markup; namespace XFEWorkflow.Plugins.AgentBrowser.WinUI; public sealed partial class AgentBrowserPage { private readonly ComboBox sessionPicker = new() { HorizontalAlignment = HorizontalAlignment.Stretch, PlaceholderText = "选择历史会话", MinWidth = 0 }; private readonly Button sessionMore = new() { Content = new FontIcon { Glyph = "\uE712" } }; private readonly DispatcherTimer saveTimer = new() { Interval = TimeSpan.FromMilliseconds(700) }; private readonly List sessions = []; private AgentSessionStore? sessionStore; private AgentSession session = new(); private readonly Dictionary documents = []; private readonly Dictionary pendingSaves = []; private readonly HashSet dirtySessions = []; private Task savePump = Task.CompletedTask; private Exception? saveError; private bool changingSession, updatingPicker; private Grid CreateSessionsBar() { var bar = new Grid { ColumnSpacing = 6 }; bar.ColumnDefinitions.Add(new() { Width = new(1, GridUnitType.Star) }); bar.ColumnDefinitions.Add(new() { Width = GridLength.Auto }); sessionPicker.ItemTemplate = (DataTemplate)XamlReader.Load(""" """); sessionPicker.SelectionChanged += async (_, _) => { if (!updatingPicker && sessionPicker.SelectedItem is AgentSessionSummary selected && selected.Id != session.Id) await GuardAsync(() => SwitchSessionAsync(selected.Id)); }; var menu = new MenuFlyout(); var rename = new MenuFlyoutItem { Text = "重命名会话", Icon = new FontIcon { Glyph = "\uE70F" } }; var delete = new MenuFlyoutItem { Text = "删除当前会话", Icon = new FontIcon { Glyph = "\uE74D" } }; rename.Click += async (_, _) => await GuardAsync(RenameSessionAsync); delete.Click += async (_, _) => await GuardAsync(DeleteSessionAsync); menu.Items.Add(rename); menu.Items.Add(delete); sessionMore.Flyout = menu; bar.Children.Add(sessionPicker); bar.Children.Add(sessionMore); Grid.SetColumn(sessionMore, 1); AutomationId(sessionPicker, "AgentSessionPicker"); AutomationId(sessionMore, "AgentSessionMore"); AutomationId(rename, "AgentSessionRename"); AutomationId(delete, "AgentSessionDelete"); ToolTipService.SetToolTip(sessionPicker, "切换对话及该会话的浏览器标签页"); ToolTipService.SetToolTip(sessionMore, "管理当前会话"); saveTimer.Tick += (_, _) => { saveTimer.Stop(); QueueSave(); }; return bar; } private async Task InitializeSessionsAsync(CancellationToken ct) { sessionStore = new(host.DataDirectory); var catalog = await sessionStore.ListAsync(ct); sessions.AddRange(catalog.Sessions); AgentSession? restored = null; foreach (var candidate in catalog.Sessions.OrderByDescending(x => x.Id == catalog.ActiveSessionId)) { try { restored = await sessionStore.LoadAsync(candidate.Id, ct); break; } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { ShowError(ex.Message); } } if (restored is { BrowserTabs.Count: 0 } && Directory.Exists(Path.Combine(host.DataDirectory, "BrowserProfile"))) restored.UseLegacyBrowserProfile = true; ApplySession(restored ?? new()); await FlushSessionAsync(); if (sessionStore.Warnings.Count > 0) ShowError(string.Join("\n", sessionStore.Warnings)); SetBusy(false); } private void ApplySession(AgentSession value) { if (documents.TryGetValue(value.Id, out var cached)) value = cached; try { var key = AgentSession.Key(options); if (value.ContextKey.Length > 0 && value.ContextKey != key && !(options.MigrationContextKey == key && options.MigratedContextKeys.Contains(value.ContextKey))) { value.Context = []; value.Record(new("error", Guid.NewGuid().ToString("N"), "模型或技能配置已变化,先前记录已保留,本次使用新的模型上下文。")); } value.ContextKey = key; } catch (ArgumentException) { } try { conversation!.RestoreHistory(value.Context); } catch (InvalidDataException) { value.Context = []; conversation!.Clear(); value.Record(new("error", Guid.NewGuid().ToString("N"), "此前模型上下文无效,聊天记录已保留。请确认网页后继续。")); } documents[value.Id] = value; session = value; changingSession = true; try { composer.Text = session.Draft; RefreshSessionPicker(); } finally { changingSession = false; } } private void RefreshSessionPicker() { sessions.RemoveAll(x => x.Id == session.Id); sessions.Add(session.Summary()); sessions.Sort((x, y) => y.UpdatedAt.CompareTo(x.UpdatedAt)); updatingPicker = true; try { sessionPicker.ItemsSource = sessions.ToArray(); sessionPicker.SelectedItem = sessions.Single(x => x.Id == session.Id); } finally { updatingPicker = false; } } private void ScheduleSave(string? sessionId = null) { dirtySessions.Add(sessionId ?? session.Id); if (disposed || changingSession || sessionStore is null || saveTimer.IsEnabled) return; saveTimer.Start(); } private void QueueSave() { if (sessionStore is null) return; session.Draft = composer.Text; foreach (var view in workspaces.Values) view.Capture(); dirtySessions.Add(session.Id); foreach (var id in dirtySessions) if (documents.TryGetValue(id, out var value)) pendingSaves[id] = value.Snapshot(); dirtySessions.Clear(); if (savePump.IsCompleted) savePump = SaveLoopAsync(); } private async Task SaveLoopAsync() { while (pendingSaves.Count > 0) { var (id, value) = pendingSaves.First(); pendingSaves.Remove(id); try { await sessionStore!.SaveAsync(value, activate: id == session.Id); saveError = null; } catch (Exception ex) { saveError = ex; ShowError("会话保存失败,请检查工作区权限或磁盘空间:" + ex.Message); host.Log("Agent 会话保存失败:" + ex.Message, true); break; } } } private async Task FlushSessionAsync() { saveTimer.Stop(); QueueSave(); await savePump; if (saveError is not null) throw new IOException("会话未能保存,请检查工作区后重试", saveError); } private void RecordNotice(string type, string text) { var item = new AgentEvent(type, Guid.NewGuid().ToString("N"), text); session.Record(item); Post(new { type, id = item.Id, text }); ScheduleSave(); } private async Task RenderSessionAsync() { Post(new { type = "clear" }); var batch = new List(); foreach (var record in session.Records) { object View(string type, string text, string? image = null) => new { type, id = record.Id, text, name = record.Name, messageId = record.MessageId, image, user = record.UserId is { } userId ? session.Users.GetValueOrDefault(userId) : null }; if (record.Type is "tool_result" or "tool_error" && !string.IsNullOrEmpty(record.Input)) batch.Add(View("tool_start", record.Input)); string? image = null; if (sessionStore?.ImagePath(record.ImagePath) is { } path) { try { image = "data:image/png;base64," + Convert.ToBase64String(await File.ReadAllBytesAsync(path, lifetime.Token)); } catch (IOException) { } } batch.Add(View(record.Type, record.Type == "tool_start" ? record.Input ?? "" : record.Text, image)); if (batch.Count >= 30 || image is not null) { Post(new { type = "restore_batch", entries = batch.ToArray() }); batch.Clear(); await Task.Yield(); } } if (batch.Count > 0) Post(new { type = "restore_batch", entries = batch.ToArray() }); Post(new { type = "restored", sessionId = session.Id }); } private async Task NewSessionAsync() { if (active is not null || changingSession || !chatReady) return; changingSession = true; SetBusy(false); try { await FlushSessionAsync(); ApplySession(new()); changingSession = true; await ShowWorkspaceAsync(); await RenderSessionAsync(); await FlushSessionAsync(); error.IsOpen = false; status.Text = "新会话 · 历史记录已保存"; } finally { changingSession = false; SetBusy(false); } } private async Task SwitchSessionAsync(string id) { if (active is not null || changingSession || !chatReady) return; changingSession = true; SetBusy(false); try { await FlushSessionAsync(); var loaded = await sessionStore!.LoadAsync(id, lifetime.Token); ApplySession(loaded); changingSession = true; await ShowWorkspaceAsync(); await RenderSessionAsync(); await FlushSessionAsync(); error.IsOpen = false; status.Text = "已恢复会话 · 可以继续对话"; } finally { changingSession = false; RefreshSessionPicker(); SetBusy(false); } } private async Task RenameSessionAsync() { if (active is not null || changingSession) return; var title = new TextBox { Header = "会话名称", Text = session.Title, MaxLength = 100 }; AutomationId(title, "AgentSessionTitle"); var dialog = new ContentDialog { Title = "重命名会话", Content = title, PrimaryButtonText = "保存", CloseButtonText = "取消", DefaultButton = ContentDialogButton.Primary, XamlRoot = root.XamlRoot, RequestedTheme = root.ActualTheme }; if (await dialog.ShowAsync() != ContentDialogResult.Primary || string.IsNullOrWhiteSpace(title.Text)) return; session.Title = title.Text.Trim(); session.TitleEdited = true; session.Touch(); RefreshSessionPicker(); await FlushSessionAsync(); } private async Task DeleteSessionAsync() { if (active is not null || changingSession) return; var dialog = new ContentDialog { Title = "删除当前会话?", Content = $"将删除“{session.Title}”的聊天记录和上下文。浏览器登录与技能产物会保留。", PrimaryButtonText = "删除", CloseButtonText = "取消", XamlRoot = root.XamlRoot, RequestedTheme = root.ActualTheme }; if (await dialog.ShowAsync() != ContentDialogResult.Primary) return; changingSession = true; SetBusy(false); try { await FlushSessionAsync(); var id = session.Id; if (workspaces.Remove(id, out var view)) view.Dispose(); documents.Remove(id); dirtySessions.Remove(id); pendingSaves.Remove(id); await sessionStore!.DeleteAsync(id, lifetime.Token); sessions.RemoveAll(x => x.Id == id); var catalog = await sessionStore.ListAsync(lifetime.Token); ApplySession(catalog.ActiveSessionId.Length > 0 ? await sessionStore.LoadAsync(catalog.ActiveSessionId, lifetime.Token) : new()); changingSession = true; await ShowWorkspaceAsync(); await RenderSessionAsync(); await FlushSessionAsync(); status.Text = "会话已删除"; } finally { changingSession = false; RefreshSessionPicker(); SetBusy(false); } } }