fix: исправить навигацию клавиатуры в TUI через GlobalKeyboardService
- Добавить GlobalKeyboardService — выделенный поток с блокирующим Console.ReadKey, единственный источник клавишных событий для TUI - Убрать FocusManager из App.razor: перехватывал Tab до компонентов - Удалить @onkeydown с <Select>: RazorConsole не пробрасывает Tab/стрелки через этот механизм - Использовать FocusedValue вместо Value в Select для корректной подсветки - Обновить CLAUDE.md и AGENTS.md: архитектура TUI, RazorConsole gotchas - Добавить docs/tui_log.md: разбор проблемы и справочник по RazorConsole Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -4,6 +4,7 @@
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UseAppHost>false</UseAppHost>
|
||||
<!-- Включаем Razor-компоненты (Blazor-стиль) без MVC -->
|
||||
<AddRazorSupportForMvc>false</AddRazorSupportForMvc>
|
||||
</PropertyGroup>
|
||||
|
||||
@@ -2,40 +2,87 @@ using LazyBear.MCP.Services.Confluence;
|
||||
using LazyBear.MCP.Services.Jira;
|
||||
using LazyBear.MCP.Services.Kubernetes;
|
||||
using LazyBear.MCP.Services.Logging;
|
||||
using LazyBear.MCP.Services.Mcp;
|
||||
using LazyBear.MCP.Services.ToolRegistry;
|
||||
using LazyBear.MCP.TUI;
|
||||
using LazyBear.MCP.TUI.Components;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using RazorConsole.Core;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
|
||||
// ── InMemoryLogSink: регистрируем Singleton и кастомный логгер ───────────────
|
||||
// ── Общий логгер и один DI-контейнер для TUI + MCP ──────────────────────────
|
||||
var logSink = new InMemoryLogSink();
|
||||
builder.Services.AddSingleton(logSink);
|
||||
builder.Logging.AddProvider(new InMemoryLoggerProvider(logSink));
|
||||
|
||||
// ── MCP-провайдеры ───────────────────────────────────────────────────────────
|
||||
builder.Services.AddSingleton<K8sClientProvider>();
|
||||
builder.Services.AddSingleton<JiraClientProvider>();
|
||||
builder.Services.AddSingleton<ConfluenceClientProvider>();
|
||||
var host = Host.CreateDefaultBuilder(args)
|
||||
.ConfigureServices(services =>
|
||||
{
|
||||
services.AddSingleton(logSink);
|
||||
services.AddSingleton<ToolRegistryService>();
|
||||
|
||||
// ── ToolRegistry ─────────────────────────────────────────────────────────────
|
||||
builder.Services.AddSingleton<ToolRegistryService>();
|
||||
// MCP-провайдеры
|
||||
services.AddSingleton<K8sClientProvider>();
|
||||
services.AddSingleton<JiraClientProvider>();
|
||||
services.AddSingleton<ConfluenceClientProvider>();
|
||||
|
||||
// ── Модули инструментов (generic: добавь новый IToolModule — он появится в TUI)
|
||||
builder.Services.AddSingleton<IToolModule, JiraToolModule>();
|
||||
builder.Services.AddSingleton<IToolModule, KubernetesToolModule>();
|
||||
builder.Services.AddSingleton<IToolModule, ConfluenceToolModule>();
|
||||
// Модули инструментов (добавь новый IToolModule — он появится в TUI)
|
||||
services.AddSingleton<IToolModule, JiraToolModule>();
|
||||
services.AddSingleton<IToolModule, KubernetesToolModule>();
|
||||
services.AddSingleton<IToolModule, ConfluenceToolModule>();
|
||||
|
||||
// ── MCP-сервер ───────────────────────────────────────────────────────────────
|
||||
builder.Services.AddMcpServer()
|
||||
.WithHttpTransport()
|
||||
.WithToolsFromAssembly();
|
||||
// HTTP MCP endpoint запускаем в фоне, чтобы TUI оставался владельцем консоли
|
||||
services.AddHostedService<McpWebHostedService>();
|
||||
|
||||
// ── TUI как фоновый сервис ───────────────────────────────────────────────────
|
||||
builder.Services.AddHostedService<TuiHostedService>();
|
||||
// Глобальный читатель клавиш — единственный источник клавишных событий для TUI
|
||||
services.AddSingleton<GlobalKeyboardService>();
|
||||
services.AddHostedService(sp => sp.GetRequiredService<GlobalKeyboardService>());
|
||||
})
|
||||
.ConfigureLogging(logging =>
|
||||
{
|
||||
logging.ClearProviders();
|
||||
logging.AddProvider(new InMemoryLoggerProvider(logSink));
|
||||
})
|
||||
.UseRazorConsole<App>(hostBuilder =>
|
||||
{
|
||||
hostBuilder.ConfigureServices(services =>
|
||||
{
|
||||
services.Configure<ConsoleAppOptions>(options =>
|
||||
{
|
||||
options.AutoClearConsole = true;
|
||||
options.EnableTerminalResizing = true;
|
||||
options.AfterRenderAsync = (_, _, _) =>
|
||||
{
|
||||
try
|
||||
{
|
||||
Console.CursorVisible = false;
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ignore terminals that do not support CursorVisible.
|
||||
}
|
||||
|
||||
var app = builder.Build();
|
||||
try
|
||||
{
|
||||
Console.Write("\u001b[?25l");
|
||||
Console.Out.Flush();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Ignore terminals that do not support ANSI cursor control.
|
||||
}
|
||||
|
||||
app.MapMcp();
|
||||
return Task.CompletedTask;
|
||||
};
|
||||
});
|
||||
});
|
||||
})
|
||||
.Build();
|
||||
|
||||
var urls = Environment.GetEnvironmentVariable("ASPNETCORE_URLS") ?? "http://localhost:5000";
|
||||
app.Run(urls);
|
||||
// ── Регистрируем модули один раз до старта TUI и web host ───────────────────
|
||||
var registry = host.Services.GetRequiredService<ToolRegistryService>();
|
||||
foreach (var module in host.Services.GetServices<IToolModule>())
|
||||
{
|
||||
registry.RegisterModule(module);
|
||||
}
|
||||
|
||||
await host.RunAsync();
|
||||
|
||||
66
LazyBear.MCP/Services/Mcp/McpWebHostedService.cs
Normal file
66
LazyBear.MCP/Services/Mcp/McpWebHostedService.cs
Normal file
@@ -0,0 +1,66 @@
|
||||
using LazyBear.MCP.Services.Confluence;
|
||||
using LazyBear.MCP.Services.Jira;
|
||||
using LazyBear.MCP.Services.Kubernetes;
|
||||
using LazyBear.MCP.Services.Logging;
|
||||
using LazyBear.MCP.Services.ToolRegistry;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
namespace LazyBear.MCP.Services.Mcp;
|
||||
|
||||
/// <summary>
|
||||
/// Поднимает HTTP MCP endpoint в фоне, не вмешиваясь в основной TUI event loop.
|
||||
/// Использует общие singleton-экземпляры из root host.
|
||||
/// </summary>
|
||||
public sealed class McpWebHostedService(
|
||||
IServiceProvider rootServices,
|
||||
IConfiguration configuration,
|
||||
ILogger<McpWebHostedService> logger) : IHostedService
|
||||
{
|
||||
private WebApplication? _webApp;
|
||||
|
||||
public async Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
var builder = WebApplication.CreateBuilder();
|
||||
var urls = Environment.GetEnvironmentVariable("ASPNETCORE_URLS") ?? "http://localhost:5000";
|
||||
|
||||
builder.WebHost.UseUrls(urls);
|
||||
|
||||
// Используем тот же IConfiguration и те же singleton-сервисы, что и в TUI host.
|
||||
builder.Services.AddSingleton(configuration);
|
||||
builder.Services.AddSingleton(rootServices.GetRequiredService<InMemoryLogSink>());
|
||||
builder.Services.AddSingleton(rootServices.GetRequiredService<ToolRegistryService>());
|
||||
builder.Services.AddSingleton(rootServices.GetRequiredService<K8sClientProvider>());
|
||||
builder.Services.AddSingleton(rootServices.GetRequiredService<JiraClientProvider>());
|
||||
builder.Services.AddSingleton(rootServices.GetRequiredService<ConfluenceClientProvider>());
|
||||
|
||||
foreach (var module in rootServices.GetServices<IToolModule>())
|
||||
{
|
||||
builder.Services.AddSingleton(module);
|
||||
builder.Services.AddSingleton(typeof(IToolModule), module);
|
||||
}
|
||||
|
||||
builder.Services.AddMcpServer()
|
||||
.WithHttpTransport()
|
||||
.WithToolsFromAssembly();
|
||||
|
||||
_webApp = builder.Build();
|
||||
_webApp.MapMcp();
|
||||
|
||||
await _webApp.StartAsync(cancellationToken);
|
||||
logger.LogInformation("HTTP MCP endpoint запущен на {Urls}", urls);
|
||||
}
|
||||
|
||||
public async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_webApp is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
await _webApp.StopAsync(cancellationToken);
|
||||
await _webApp.DisposeAsync();
|
||||
_webApp = null;
|
||||
}
|
||||
}
|
||||
@@ -49,9 +49,12 @@ public sealed class ToolRegistryService
|
||||
public bool IsModuleEnabled(string moduleName) =>
|
||||
_moduleEnabled.GetValueOrDefault(moduleName, true);
|
||||
|
||||
public bool IsToolConfiguredEnabled(string moduleName, string toolName) =>
|
||||
_toolEnabled.GetValueOrDefault(MakeKey(moduleName, toolName), true);
|
||||
|
||||
public bool IsToolEnabled(string moduleName, string toolName) =>
|
||||
IsModuleEnabled(moduleName) &&
|
||||
_toolEnabled.GetValueOrDefault(MakeKey(moduleName, toolName), true);
|
||||
IsToolConfiguredEnabled(moduleName, toolName);
|
||||
|
||||
// ── Переключение ─────────────────────────────────────────────────────────
|
||||
|
||||
@@ -71,7 +74,7 @@ public sealed class ToolRegistryService
|
||||
SetModuleEnabled(moduleName, !IsModuleEnabled(moduleName));
|
||||
|
||||
public void ToggleTool(string moduleName, string toolName) =>
|
||||
SetToolEnabled(moduleName, toolName, !IsToolEnabled(moduleName, toolName));
|
||||
SetToolEnabled(moduleName, toolName, !IsToolConfiguredEnabled(moduleName, toolName));
|
||||
|
||||
// ── Счётчики для Overview ─────────────────────────────────────────────────
|
||||
|
||||
@@ -90,6 +93,21 @@ public sealed class ToolRegistryService
|
||||
}
|
||||
}
|
||||
|
||||
public (int Enabled, int Total) GetConfiguredToolCounts(string moduleName)
|
||||
{
|
||||
lock (_modulesLock)
|
||||
{
|
||||
var module = _modules.FirstOrDefault(m =>
|
||||
string.Equals(m.ModuleName, moduleName, StringComparison.OrdinalIgnoreCase));
|
||||
|
||||
if (module is null) return (0, 0);
|
||||
|
||||
var total = module.ToolNames.Count;
|
||||
var enabled = module.ToolNames.Count(t => IsToolConfiguredEnabled(moduleName, t));
|
||||
return (enabled, total);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────
|
||||
|
||||
private static string MakeKey(string module, string tool) => $"{module}::{tool}";
|
||||
|
||||
@@ -2,80 +2,542 @@
|
||||
@using LazyBear.MCP.Services.ToolRegistry
|
||||
@inject ToolRegistryService Registry
|
||||
@inject InMemoryLogSink LogSink
|
||||
@inject GlobalKeyboardService KeyboardService
|
||||
|
||||
@implements IDisposable
|
||||
|
||||
<Rows>
|
||||
<Panel Title="LazyBear MCP" BorderColor="@Spectre.Console.Color.Gold1" Expand="true">
|
||||
<Rows>
|
||||
@* Таб-навигация *@
|
||||
<Rows Expand="true">
|
||||
<Panel Title="LazyBear MCP"
|
||||
TitleColor="@UiPalette.Accent"
|
||||
BorderColor="@UiPalette.Frame"
|
||||
Expand="true"
|
||||
Height="@GetPanelHeight()"
|
||||
Padding="@(new Spectre.Console.Padding(1, 0, 1, 0))">
|
||||
<Rows Expand="true">
|
||||
<Markup Content="Tab: switch tabs | Arrows: navigate | Space: toggle | Enter: open" Foreground="@UiPalette.TextMuted" />
|
||||
<Markup Content=" " />
|
||||
|
||||
<Columns>
|
||||
<TextButton Content="[1] Overview"
|
||||
OnClick="@(() => SetTab(Tab.Overview))"
|
||||
BackgroundColor="@(_activeTab == Tab.Overview ? Spectre.Console.Color.DarkBlue : Spectre.Console.Color.Grey23)"
|
||||
FocusedColor="@Spectre.Console.Color.Blue"
|
||||
FocusOrder="1" />
|
||||
<TextButton Content="[2] Logs"
|
||||
OnClick="@(() => SetTab(Tab.Logs))"
|
||||
BackgroundColor="@(_activeTab == Tab.Logs ? Spectre.Console.Color.DarkBlue : Spectre.Console.Color.Grey23)"
|
||||
FocusedColor="@Spectre.Console.Color.Blue"
|
||||
FocusOrder="2" />
|
||||
<TextButton Content="[3] Settings"
|
||||
OnClick="@(() => SetTab(Tab.Settings))"
|
||||
BackgroundColor="@(_activeTab == Tab.Settings ? Spectre.Console.Color.DarkBlue : Spectre.Console.Color.Grey23)"
|
||||
FocusedColor="@Spectre.Console.Color.Blue"
|
||||
FocusOrder="3" />
|
||||
@foreach (var tab in _tabs)
|
||||
{
|
||||
var isActive = _activeTab == tab;
|
||||
<Markup Content="@($" {GetTabLabel(tab)} ")"
|
||||
Foreground="@(isActive ? UiPalette.SelectionForeground : UiPalette.Text)"
|
||||
Background="@(isActive ? UiPalette.Accent : UiPalette.SurfaceMuted)"
|
||||
Decoration="@(isActive ? Spectre.Console.Decoration.Bold : Spectre.Console.Decoration.None)" />
|
||||
<Markup Content=" " />
|
||||
}
|
||||
</Columns>
|
||||
|
||||
@* Контент таба *@
|
||||
<Markup Content=" " />
|
||||
|
||||
@if (_activeTab == Tab.Overview)
|
||||
{
|
||||
<OverviewTab />
|
||||
<OverviewTab Rows="@GetOverviewRows()"
|
||||
SelectedIndex="@_overviewSelection"
|
||||
SelectedIndexChanged="@OnOverviewSelectionChanged"
|
||||
ViewportRows="@GetOverviewViewportRows()" />
|
||||
}
|
||||
else if (_activeTab == Tab.Logs)
|
||||
{
|
||||
<LogsTab />
|
||||
<LogsTab Entries="@GetFilteredLogEntries()"
|
||||
SelectedIndex="@_logSelection"
|
||||
SelectedIndexChanged="@OnLogSelectionChanged"
|
||||
SelectedFilter="@_logFilters[_logFilterIndex]"
|
||||
ViewportRows="@GetLogsViewportRows()"
|
||||
IsStickyToBottom="@_logsStickToBottom" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<SettingsTab />
|
||||
<SettingsTab Entries="@GetSettingsEntries()"
|
||||
SelectedIndex="@_settingsSelection"
|
||||
SelectedIndexChanged="@OnSettingsSelectionChanged"
|
||||
ViewportRows="@GetSettingsViewportRows()" />
|
||||
}
|
||||
</Rows>
|
||||
</Panel>
|
||||
</Rows>
|
||||
|
||||
@code {
|
||||
private enum Tab { Overview, Logs, Settings }
|
||||
private enum Tab
|
||||
{
|
||||
Overview,
|
||||
Logs,
|
||||
Settings
|
||||
}
|
||||
|
||||
private static readonly Tab[] _tabs = [Tab.Overview, Tab.Logs, Tab.Settings];
|
||||
private static readonly string[] _logFilters = ["All", "Info", "Warn", "Error"];
|
||||
private readonly HashSet<string> _expandedModules = new(StringComparer.Ordinal);
|
||||
|
||||
private Tab _activeTab = Tab.Overview;
|
||||
private int _overviewSelection;
|
||||
private int _logFilterIndex;
|
||||
private int _logSelection;
|
||||
private int _settingsSelection;
|
||||
private bool _logsStickToBottom = true;
|
||||
|
||||
private static int GetPanelHeight() => Math.Max(Console.WindowHeight - 2, 10);
|
||||
private static int GetOverviewViewportRows() => Math.Max(Console.WindowHeight - 11, 3);
|
||||
private static int GetLogsViewportRows() => Math.Max(Console.WindowHeight - 16, 5);
|
||||
private static int GetSettingsViewportRows() => Math.Max(Console.WindowHeight - 13, 5);
|
||||
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
Registry.StateChanged += OnStateChanged;
|
||||
Registry.StateChanged += OnRegistryChanged;
|
||||
LogSink.OnLog += OnNewLog;
|
||||
KeyboardService.OnKeyPressed += OnConsoleKeyPressed;
|
||||
}
|
||||
|
||||
private void SetTab(Tab tab)
|
||||
// Конвертация ConsoleKeyInfo → KeyboardEventArgs для переиспользования существующей логики
|
||||
private static KeyboardEventArgs ConvertKey(ConsoleKeyInfo key)
|
||||
{
|
||||
_activeTab = tab;
|
||||
StateHasChanged();
|
||||
}
|
||||
|
||||
private void OnStateChanged()
|
||||
{
|
||||
InvokeAsync(StateHasChanged);
|
||||
}
|
||||
|
||||
private void OnNewLog(LogEntry _)
|
||||
{
|
||||
if (_activeTab == Tab.Logs)
|
||||
var name = key.Key switch
|
||||
{
|
||||
InvokeAsync(StateHasChanged);
|
||||
ConsoleKey.UpArrow => "ArrowUp",
|
||||
ConsoleKey.DownArrow => "ArrowDown",
|
||||
ConsoleKey.LeftArrow => "ArrowLeft",
|
||||
ConsoleKey.RightArrow => "ArrowRight",
|
||||
ConsoleKey.Enter => "Enter",
|
||||
ConsoleKey.Spacebar => " ",
|
||||
ConsoleKey.Home => "Home",
|
||||
ConsoleKey.End => "End",
|
||||
ConsoleKey.PageUp => "PageUp",
|
||||
ConsoleKey.PageDown => "PageDown",
|
||||
ConsoleKey.Tab => "Tab",
|
||||
_ => key.KeyChar == '\0' ? string.Empty : key.KeyChar.ToString()
|
||||
};
|
||||
|
||||
return new KeyboardEventArgs
|
||||
{
|
||||
Key = name,
|
||||
ShiftKey = (key.Modifiers & ConsoleModifiers.Shift) != 0
|
||||
};
|
||||
}
|
||||
|
||||
private void OnConsoleKeyPressed(ConsoleKeyInfo key)
|
||||
{
|
||||
var args = ConvertKey(key);
|
||||
if (string.IsNullOrEmpty(args.Key))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
InvokeAsync(() =>
|
||||
{
|
||||
HandleKeyDown(args);
|
||||
StateHasChanged();
|
||||
});
|
||||
}
|
||||
|
||||
private void HandleKeyDown(KeyboardEventArgs args)
|
||||
{
|
||||
if (string.Equals(args.Key, "Tab", StringComparison.Ordinal))
|
||||
{
|
||||
ChangeTab(args.ShiftKey ? -1 : 1);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (_activeTab)
|
||||
{
|
||||
case Tab.Overview:
|
||||
HandleOverviewKey(args);
|
||||
break;
|
||||
case Tab.Logs:
|
||||
HandleLogsKey(args);
|
||||
break;
|
||||
case Tab.Settings:
|
||||
HandleSettingsKey(args);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private Task OnOverviewSelectionChanged(int value)
|
||||
{
|
||||
var rows = GetOverviewRows();
|
||||
_overviewSelection = rows.Count == 0 ? 0 : Math.Clamp(value, 0, rows.Count - 1);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task OnLogSelectionChanged(int value)
|
||||
{
|
||||
var entries = GetFilteredLogEntries();
|
||||
_logSelection = entries.Count == 0 ? 0 : Math.Clamp(value, 0, entries.Count - 1);
|
||||
_logsStickToBottom = entries.Count == 0 || _logSelection >= entries.Count - 1;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private Task OnSettingsSelectionChanged(int value)
|
||||
{
|
||||
var entries = GetSettingsEntries();
|
||||
_settingsSelection = entries.Count == 0 ? 0 : Math.Clamp(value, 0, entries.Count - 1);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void ChangeTab(int step)
|
||||
{
|
||||
var currentIndex = Array.IndexOf(_tabs, _activeTab);
|
||||
if (currentIndex < 0)
|
||||
{
|
||||
currentIndex = 0;
|
||||
}
|
||||
|
||||
var nextIndex = (currentIndex + step + _tabs.Length) % _tabs.Length;
|
||||
_activeTab = _tabs[nextIndex];
|
||||
ClampSelections();
|
||||
}
|
||||
|
||||
private void HandleOverviewKey(KeyboardEventArgs args)
|
||||
{
|
||||
var rows = GetOverviewRows();
|
||||
if (rows.Count == 0)
|
||||
{
|
||||
_overviewSelection = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
_overviewSelection = Math.Clamp(_overviewSelection, 0, rows.Count - 1);
|
||||
|
||||
switch (args.Key)
|
||||
{
|
||||
case "ArrowUp":
|
||||
_overviewSelection = Math.Max(0, _overviewSelection - 1);
|
||||
break;
|
||||
case "ArrowDown":
|
||||
_overviewSelection = Math.Min(rows.Count - 1, _overviewSelection + 1);
|
||||
break;
|
||||
case "Home":
|
||||
_overviewSelection = 0;
|
||||
break;
|
||||
case "End":
|
||||
_overviewSelection = rows.Count - 1;
|
||||
break;
|
||||
case "Enter":
|
||||
_activeTab = Tab.Settings;
|
||||
SelectSettingsModule(rows[_overviewSelection].ModuleName);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleLogsKey(KeyboardEventArgs args)
|
||||
{
|
||||
switch (args.Key)
|
||||
{
|
||||
case "ArrowLeft":
|
||||
_logFilterIndex = (_logFilterIndex - 1 + _logFilters.Length) % _logFilters.Length;
|
||||
ResetLogsSelectionToBottom();
|
||||
return;
|
||||
case "ArrowRight":
|
||||
_logFilterIndex = (_logFilterIndex + 1) % _logFilters.Length;
|
||||
ResetLogsSelectionToBottom();
|
||||
return;
|
||||
}
|
||||
|
||||
var entries = GetFilteredLogEntries();
|
||||
if (entries.Count == 0)
|
||||
{
|
||||
_logSelection = 0;
|
||||
_logsStickToBottom = true;
|
||||
return;
|
||||
}
|
||||
|
||||
_logSelection = Math.Clamp(_logSelection, 0, entries.Count - 1);
|
||||
var page = Math.Max(GetLogsViewportRows() - 1, 1);
|
||||
|
||||
switch (args.Key)
|
||||
{
|
||||
case "ArrowUp":
|
||||
_logSelection = Math.Max(0, _logSelection - 1);
|
||||
break;
|
||||
case "ArrowDown":
|
||||
_logSelection = Math.Min(entries.Count - 1, _logSelection + 1);
|
||||
break;
|
||||
case "PageUp":
|
||||
_logSelection = Math.Max(0, _logSelection - page);
|
||||
break;
|
||||
case "PageDown":
|
||||
case " ":
|
||||
case "Spacebar":
|
||||
_logSelection = Math.Min(entries.Count - 1, _logSelection + page);
|
||||
break;
|
||||
case "Home":
|
||||
_logSelection = 0;
|
||||
break;
|
||||
case "End":
|
||||
_logSelection = entries.Count - 1;
|
||||
break;
|
||||
}
|
||||
|
||||
_logsStickToBottom = _logSelection >= entries.Count - 1;
|
||||
}
|
||||
|
||||
private void HandleSettingsKey(KeyboardEventArgs args)
|
||||
{
|
||||
var entries = GetSettingsEntries();
|
||||
if (entries.Count == 0)
|
||||
{
|
||||
_settingsSelection = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
_settingsSelection = Math.Clamp(_settingsSelection, 0, entries.Count - 1);
|
||||
var selected = entries[_settingsSelection];
|
||||
var page = Math.Max(GetSettingsViewportRows() - 1, 1);
|
||||
|
||||
switch (args.Key)
|
||||
{
|
||||
case "ArrowUp":
|
||||
_settingsSelection = Math.Max(0, _settingsSelection - 1);
|
||||
return;
|
||||
case "ArrowDown":
|
||||
_settingsSelection = Math.Min(entries.Count - 1, _settingsSelection + 1);
|
||||
return;
|
||||
case "PageUp":
|
||||
_settingsSelection = Math.Max(0, _settingsSelection - page);
|
||||
return;
|
||||
case "PageDown":
|
||||
_settingsSelection = Math.Min(entries.Count - 1, _settingsSelection + page);
|
||||
return;
|
||||
case "Home":
|
||||
_settingsSelection = 0;
|
||||
return;
|
||||
case "End":
|
||||
_settingsSelection = entries.Count - 1;
|
||||
return;
|
||||
case "ArrowRight":
|
||||
ExpandModule(selected);
|
||||
return;
|
||||
case "ArrowLeft":
|
||||
CollapseModuleOrFocusParent(selected);
|
||||
return;
|
||||
case "Enter":
|
||||
ToggleExpansion(selected);
|
||||
return;
|
||||
case " ":
|
||||
case "Spacebar":
|
||||
ToggleSetting(selected);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
private void ExpandModule(SettingsEntry entry)
|
||||
{
|
||||
if (entry.Kind != SettingsEntryKind.Module || entry.IsExpanded)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_expandedModules.Add(entry.ModuleName);
|
||||
ClampSelections();
|
||||
}
|
||||
|
||||
private void CollapseModuleOrFocusParent(SettingsEntry entry)
|
||||
{
|
||||
if (entry.Kind == SettingsEntryKind.Module)
|
||||
{
|
||||
if (_expandedModules.Remove(entry.ModuleName))
|
||||
{
|
||||
ClampSelections();
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
_expandedModules.Remove(entry.ModuleName);
|
||||
SelectSettingsModule(entry.ModuleName);
|
||||
}
|
||||
|
||||
private void ToggleExpansion(SettingsEntry entry)
|
||||
{
|
||||
if (entry.Kind != SettingsEntryKind.Module)
|
||||
{
|
||||
ToggleSetting(entry);
|
||||
return;
|
||||
}
|
||||
|
||||
if (_expandedModules.Contains(entry.ModuleName))
|
||||
{
|
||||
_expandedModules.Remove(entry.ModuleName);
|
||||
}
|
||||
else
|
||||
{
|
||||
_expandedModules.Add(entry.ModuleName);
|
||||
}
|
||||
|
||||
SelectSettingsModule(entry.ModuleName);
|
||||
}
|
||||
|
||||
private void ToggleSetting(SettingsEntry entry)
|
||||
{
|
||||
if (entry.Kind == SettingsEntryKind.Module)
|
||||
{
|
||||
Registry.ToggleModule(entry.ModuleName);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(entry.ToolName))
|
||||
{
|
||||
Registry.ToggleTool(entry.ModuleName, entry.ToolName);
|
||||
}
|
||||
}
|
||||
|
||||
private void SelectSettingsModule(string moduleName)
|
||||
{
|
||||
var entries = GetSettingsEntries();
|
||||
var index = entries.FindIndex(entry =>
|
||||
entry.Kind == SettingsEntryKind.Module &&
|
||||
string.Equals(entry.ModuleName, moduleName, StringComparison.Ordinal));
|
||||
|
||||
_settingsSelection = index >= 0 ? index : 0;
|
||||
}
|
||||
|
||||
private void ResetLogsSelectionToBottom()
|
||||
{
|
||||
var entries = GetFilteredLogEntries();
|
||||
_logSelection = Math.Max(entries.Count - 1, 0);
|
||||
_logsStickToBottom = true;
|
||||
}
|
||||
|
||||
private List<OverviewRow> GetOverviewRows() =>
|
||||
Registry.GetModules()
|
||||
.Select(module =>
|
||||
{
|
||||
var (configuredTools, totalTools) = Registry.GetConfiguredToolCounts(module.ModuleName);
|
||||
return new OverviewRow(
|
||||
module.ModuleName,
|
||||
module.Description,
|
||||
Registry.IsModuleEnabled(module.ModuleName),
|
||||
configuredTools,
|
||||
totalTools);
|
||||
})
|
||||
.ToList();
|
||||
|
||||
private List<SettingsEntry> GetSettingsEntries()
|
||||
{
|
||||
var entries = new List<SettingsEntry>();
|
||||
|
||||
foreach (var module in Registry.GetModules())
|
||||
{
|
||||
var isModuleEnabled = Registry.IsModuleEnabled(module.ModuleName);
|
||||
var isExpanded = _expandedModules.Contains(module.ModuleName);
|
||||
|
||||
entries.Add(new SettingsEntry(
|
||||
SettingsEntryKind.Module,
|
||||
module.ModuleName,
|
||||
null,
|
||||
module.ModuleName,
|
||||
module.Description,
|
||||
isModuleEnabled,
|
||||
isModuleEnabled,
|
||||
isExpanded,
|
||||
0));
|
||||
|
||||
if (!isExpanded)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
foreach (var toolName in module.ToolNames)
|
||||
{
|
||||
var isConfigured = Registry.IsToolConfiguredEnabled(module.ModuleName, toolName);
|
||||
entries.Add(new SettingsEntry(
|
||||
SettingsEntryKind.Tool,
|
||||
module.ModuleName,
|
||||
toolName,
|
||||
toolName,
|
||||
isModuleEnabled
|
||||
? $"{module.ModuleName} / {toolName}"
|
||||
: $"{module.ModuleName} / {toolName} (module is OFF, tool state is preserved)",
|
||||
isConfigured,
|
||||
isModuleEnabled,
|
||||
false,
|
||||
1));
|
||||
}
|
||||
}
|
||||
|
||||
return entries;
|
||||
}
|
||||
|
||||
private List<LogEntry> GetFilteredLogEntries()
|
||||
{
|
||||
var entries = LogSink.GetEntries();
|
||||
return _logFilters[_logFilterIndex] switch
|
||||
{
|
||||
"Info" => entries.Where(IsInfoLevel).ToList(),
|
||||
"Warn" => entries.Where(entry => entry.Level == LogLevel.Warning).ToList(),
|
||||
"Error" => entries.Where(entry => entry.Level is LogLevel.Error or LogLevel.Critical).ToList(),
|
||||
_ => entries.ToList()
|
||||
};
|
||||
}
|
||||
|
||||
private void ClampSelections()
|
||||
{
|
||||
var overviewRows = GetOverviewRows();
|
||||
_overviewSelection = overviewRows.Count == 0
|
||||
? 0
|
||||
: Math.Clamp(_overviewSelection, 0, overviewRows.Count - 1);
|
||||
|
||||
var logEntries = GetFilteredLogEntries();
|
||||
_logSelection = logEntries.Count == 0
|
||||
? 0
|
||||
: Math.Clamp(_logSelection, 0, logEntries.Count - 1);
|
||||
|
||||
var settingsEntries = GetSettingsEntries();
|
||||
_settingsSelection = settingsEntries.Count == 0
|
||||
? 0
|
||||
: Math.Clamp(_settingsSelection, 0, settingsEntries.Count - 1);
|
||||
}
|
||||
|
||||
private void OnRegistryChanged()
|
||||
{
|
||||
InvokeAsync(() =>
|
||||
{
|
||||
ClampSelections();
|
||||
StateHasChanged();
|
||||
});
|
||||
}
|
||||
|
||||
private void OnNewLog(LogEntry entry)
|
||||
{
|
||||
InvokeAsync(() =>
|
||||
{
|
||||
if (_logsStickToBottom && MatchesCurrentLogFilter(entry))
|
||||
{
|
||||
var filteredEntries = GetFilteredLogEntries();
|
||||
_logSelection = Math.Max(filteredEntries.Count - 1, 0);
|
||||
}
|
||||
else
|
||||
{
|
||||
ClampSelections();
|
||||
}
|
||||
|
||||
StateHasChanged();
|
||||
});
|
||||
}
|
||||
|
||||
private bool MatchesCurrentLogFilter(LogEntry entry) =>
|
||||
_logFilters[_logFilterIndex] switch
|
||||
{
|
||||
"Info" => IsInfoLevel(entry),
|
||||
"Warn" => entry.Level == LogLevel.Warning,
|
||||
"Error" => entry.Level is LogLevel.Error or LogLevel.Critical,
|
||||
_ => true
|
||||
};
|
||||
|
||||
private static bool IsInfoLevel(LogEntry entry) =>
|
||||
entry.Level is LogLevel.Information or LogLevel.Debug or LogLevel.Trace;
|
||||
|
||||
private static string GetTabLabel(Tab tab) => tab switch
|
||||
{
|
||||
Tab.Overview => "Overview",
|
||||
Tab.Logs => "Logs",
|
||||
_ => "Settings"
|
||||
};
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
Registry.StateChanged -= OnStateChanged;
|
||||
Registry.StateChanged -= OnRegistryChanged;
|
||||
LogSink.OnLog -= OnNewLog;
|
||||
KeyboardService.OnKeyPressed -= OnConsoleKeyPressed;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,119 +1,131 @@
|
||||
@using LazyBear.MCP.Services.Logging
|
||||
@inject InMemoryLogSink LogSink
|
||||
|
||||
@implements IDisposable
|
||||
|
||||
<Rows>
|
||||
<Markup Content="Runtime Logs" Foreground="@UiPalette.Text" Decoration="@Spectre.Console.Decoration.Bold" />
|
||||
<Markup Content="Left/Right change level. Up/Down move. PageUp/PageDown/Home/End scroll." Foreground="@UiPalette.TextMuted" />
|
||||
<Markup Content=" " />
|
||||
|
||||
@* Фильтр по модулю *@
|
||||
<Columns>
|
||||
<Markup Content="Filter: " />
|
||||
<Select TItem="string"
|
||||
Options="@_filterOptions"
|
||||
Value="@_selectedFilter"
|
||||
ValueChanged="@OnFilterChanged"
|
||||
FocusOrder="10" />
|
||||
@foreach (var filter in Filters)
|
||||
{
|
||||
var isActive = string.Equals(filter, SelectedFilter, StringComparison.Ordinal);
|
||||
<Markup Content="@($" {filter} ")"
|
||||
Foreground="@(isActive ? UiPalette.SelectionForeground : UiPalette.Text)"
|
||||
Background="@(isActive ? UiPalette.AccentSoft : UiPalette.SurfaceMuted)"
|
||||
Decoration="@(isActive ? Spectre.Console.Decoration.Bold : Spectre.Console.Decoration.None)" />
|
||||
<Markup Content=" " />
|
||||
}
|
||||
</Columns>
|
||||
|
||||
<Markup Content=" " />
|
||||
|
||||
@{
|
||||
var entries = GetFilteredEntries();
|
||||
}
|
||||
|
||||
@if (entries.Count == 0)
|
||||
@if (Entries.Count == 0)
|
||||
{
|
||||
<Markup Content="[grey]No log entries yet...[/]" />
|
||||
<Border BorderColor="@UiPalette.Frame" BoxBorder="@Spectre.Console.BoxBorder.Rounded" Padding="@(new Spectre.Console.Padding(0, 0, 0, 0))">
|
||||
<Markup Content="No log entries yet." Foreground="@UiPalette.TextDim" />
|
||||
</Border>
|
||||
}
|
||||
else
|
||||
{
|
||||
@* Показываем последние 20 строк с прокруткой *@
|
||||
<ViewHeightScrollable LinesToRender="20"
|
||||
ScrollOffset="@_scrollOffset"
|
||||
ScrollOffsetChanged="@(v => { _scrollOffset = v; })" >
|
||||
<Rows>
|
||||
@foreach (var entry in entries)
|
||||
{
|
||||
var levelColor = entry.Level switch
|
||||
{
|
||||
LogLevel.Error or LogLevel.Critical => Spectre.Console.Color.Red,
|
||||
LogLevel.Warning => Spectre.Console.Color.Yellow,
|
||||
LogLevel.Information => Spectre.Console.Color.White,
|
||||
_ => Spectre.Console.Color.Grey
|
||||
};
|
||||
|
||||
var levelTag = entry.Level switch
|
||||
{
|
||||
LogLevel.Error => "ERR",
|
||||
LogLevel.Critical => "CRT",
|
||||
LogLevel.Warning => "WRN",
|
||||
LogLevel.Information => "INF",
|
||||
LogLevel.Debug => "DBG",
|
||||
_ => "TRC"
|
||||
};
|
||||
|
||||
var time = entry.Timestamp.ToString("HH:mm:ss");
|
||||
var cat = entry.ShortCategory.Length > 18
|
||||
? entry.ShortCategory[..18]
|
||||
: entry.ShortCategory.PadRight(18);
|
||||
var msg = entry.Message.Length > 80
|
||||
? entry.Message[..80] + "..."
|
||||
: entry.Message;
|
||||
|
||||
<Columns>
|
||||
<Markup Content="@($"[grey]{time}[/]")" />
|
||||
<Markup Content="@($" {levelTag} ")" Foreground="@levelColor" />
|
||||
<Markup Content="@($"[grey]{cat}[/]")" />
|
||||
<Markup Content="@($" {msg}")" />
|
||||
</Columns>
|
||||
}
|
||||
</Rows>
|
||||
</ViewHeightScrollable>
|
||||
<Select TItem="int"
|
||||
Options="@GetOptions()"
|
||||
Value="@GetNormalizedIndex()"
|
||||
FocusedValue="@GetNormalizedIndex()"
|
||||
Formatter="@FormatEntry"
|
||||
Expand="true"
|
||||
BorderStyle="@Spectre.Console.BoxBorder.Rounded"
|
||||
SelectedIndicator="@('>')" />
|
||||
}
|
||||
|
||||
<Markup Content=" " />
|
||||
<Markup Content="@GetDetailsHeader()" Foreground="@UiPalette.TextMuted" />
|
||||
<Markup Content="@GetDetailsText()" Foreground="@UiPalette.Text" />
|
||||
</Rows>
|
||||
|
||||
@code {
|
||||
private string _selectedFilter = "All";
|
||||
private int _scrollOffset = 0;
|
||||
private static readonly string[] Filters = ["All", "Info", "Warn", "Error"];
|
||||
|
||||
private string[] _filterOptions = ["All", "Jira", "Kubernetes", "Confluence", "MCP", "System"];
|
||||
[Parameter, EditorRequired] public IReadOnlyList<LogEntry> Entries { get; set; } = Array.Empty<LogEntry>();
|
||||
[Parameter] public int SelectedIndex { get; set; }
|
||||
[Parameter] public EventCallback<int> SelectedIndexChanged { get; set; }
|
||||
[Parameter] public string SelectedFilter { get; set; } = "All";
|
||||
[Parameter] public int ViewportRows { get; set; } = 5;
|
||||
[Parameter] public bool IsStickyToBottom { get; set; }
|
||||
|
||||
private static readonly Dictionary<string, string?> FilterPrefixes = new()
|
||||
private int[] GetOptions() => Enumerable.Range(0, Entries.Count).ToArray();
|
||||
|
||||
private int GetNormalizedIndex() => Entries.Count == 0 ? 0 : Math.Clamp(SelectedIndex, 0, Entries.Count - 1);
|
||||
|
||||
private string GetDetailsHeader()
|
||||
{
|
||||
["All"] = null,
|
||||
["Jira"] = "LazyBear.MCP.Services.Jira",
|
||||
["Kubernetes"] = "LazyBear.MCP.Services.Kubernetes",
|
||||
["Confluence"] = "LazyBear.MCP.Services.Confluence",
|
||||
["MCP"] = "ModelContextProtocol",
|
||||
["System"] = "Microsoft"
|
||||
if (Entries.Count == 0)
|
||||
{
|
||||
return $"Filter: {SelectedFilter}";
|
||||
}
|
||||
|
||||
var selected = Entries[Math.Clamp(SelectedIndex, 0, Entries.Count - 1)];
|
||||
var position = Math.Clamp(SelectedIndex, 0, Entries.Count - 1) + 1;
|
||||
var sticky = IsStickyToBottom ? "sticky" : "manual";
|
||||
return $"{position}/{Entries.Count} | {selected.Timestamp:HH:mm:ss} | {selected.Level} | {selected.ShortCategory} | {sticky}";
|
||||
}
|
||||
|
||||
private string GetDetailsText()
|
||||
{
|
||||
if (Entries.Count == 0)
|
||||
{
|
||||
return "Incoming log entries will appear here.";
|
||||
}
|
||||
|
||||
var selected = Entries[Math.Clamp(SelectedIndex, 0, Entries.Count - 1)];
|
||||
var details = string.IsNullOrWhiteSpace(selected.Exception)
|
||||
? selected.Message
|
||||
: $"{selected.Message} | {selected.Exception}";
|
||||
|
||||
return Fit(details, Math.Max(Console.WindowWidth - 12, 32));
|
||||
}
|
||||
|
||||
private static Spectre.Console.Color GetLevelColor(LogEntry entry) => entry.Level switch
|
||||
{
|
||||
LogLevel.Error or LogLevel.Critical => UiPalette.Danger,
|
||||
LogLevel.Warning => UiPalette.Warning,
|
||||
LogLevel.Information => UiPalette.Text,
|
||||
_ => UiPalette.TextMuted
|
||||
};
|
||||
|
||||
private IReadOnlyList<LogEntry> GetFilteredEntries()
|
||||
private string FormatEntry(int index)
|
||||
{
|
||||
FilterPrefixes.TryGetValue(_selectedFilter, out var prefix);
|
||||
return LogSink.GetEntries(prefix);
|
||||
var entry = Entries[index];
|
||||
var level = entry.Level switch
|
||||
{
|
||||
LogLevel.Error => "ERR",
|
||||
LogLevel.Critical => "CRT",
|
||||
LogLevel.Warning => "WRN",
|
||||
LogLevel.Information => "INF",
|
||||
LogLevel.Debug => "DBG",
|
||||
_ => "TRC"
|
||||
};
|
||||
|
||||
var text = $"{entry.Timestamp:HH:mm:ss} {level,-3} {entry.ShortCategory,-18} {entry.Message}";
|
||||
return Fit(text, Math.Max(Console.WindowWidth - 12, 32));
|
||||
}
|
||||
|
||||
private void OnFilterChanged(string value)
|
||||
private static string Fit(string text, int width)
|
||||
{
|
||||
_selectedFilter = value;
|
||||
_scrollOffset = 0;
|
||||
StateHasChanged();
|
||||
}
|
||||
if (width <= 0)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
protected override void OnInitialized()
|
||||
{
|
||||
LogSink.OnLog += HandleNewLog;
|
||||
}
|
||||
if (text.Length <= width)
|
||||
{
|
||||
return text.PadRight(width);
|
||||
}
|
||||
|
||||
private void HandleNewLog(LogEntry _)
|
||||
{
|
||||
InvokeAsync(StateHasChanged);
|
||||
}
|
||||
if (width <= 3)
|
||||
{
|
||||
return text[..width];
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
LogSink.OnLog -= HandleNewLog;
|
||||
return text[..(width - 3)] + "...";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,39 +1,80 @@
|
||||
@using LazyBear.MCP.Services.ToolRegistry
|
||||
@inject ToolRegistryService Registry
|
||||
|
||||
<Rows>
|
||||
<Markup Content="Module Overview" Foreground="@UiPalette.Text" Decoration="@Spectre.Console.Decoration.Bold" />
|
||||
<Markup Content="Up/Down select a module. Enter opens its settings." Foreground="@UiPalette.TextMuted" />
|
||||
<Markup Content=" " />
|
||||
@foreach (var module in Registry.GetModules())
|
||||
{
|
||||
var (active, total) = Registry.GetToolCounts(module.ModuleName);
|
||||
var isEnabled = Registry.IsModuleEnabled(module.ModuleName);
|
||||
var statusColor = isEnabled ? Spectre.Console.Color.Green : Spectre.Console.Color.Red;
|
||||
var statusText = isEnabled ? "ENABLED" : "DISABLED";
|
||||
var activeColor = active == total
|
||||
? Spectre.Console.Color.Green
|
||||
: (active == 0 ? Spectre.Console.Color.Red : Spectre.Console.Color.Yellow);
|
||||
|
||||
<Panel Title="@module.ModuleName"
|
||||
BorderColor="@(isEnabled ? Spectre.Console.Color.Green3 : Spectre.Console.Color.Grey46)"
|
||||
Expand="true">
|
||||
<Columns>
|
||||
<Rows>
|
||||
<Columns>
|
||||
<Markup Content="Status: " />
|
||||
<Markup Content="@statusText" Foreground="@statusColor" />
|
||||
</Columns>
|
||||
<Columns>
|
||||
<Markup Content="Tools: " />
|
||||
<Markup Content="@($"{active}/{total} active")" Foreground="@activeColor" />
|
||||
</Columns>
|
||||
<Markup Content="@module.Description" Foreground="@Spectre.Console.Color.Grey" />
|
||||
</Rows>
|
||||
</Columns>
|
||||
</Panel>
|
||||
@if (Rows.Count == 0)
|
||||
{
|
||||
<Border BorderColor="@UiPalette.Frame" BoxBorder="@Spectre.Console.BoxBorder.Rounded" Padding="@(new Spectre.Console.Padding(0, 0, 0, 0))">
|
||||
<Markup Content="No modules registered." Foreground="@UiPalette.TextDim" />
|
||||
</Border>
|
||||
}
|
||||
else
|
||||
{
|
||||
<Select TItem="int"
|
||||
Options="@GetOptions()"
|
||||
Value="@GetNormalizedIndex()"
|
||||
FocusedValue="@GetNormalizedIndex()"
|
||||
Formatter="@FormatRow"
|
||||
Expand="true"
|
||||
BorderStyle="@Spectre.Console.BoxBorder.Rounded"
|
||||
SelectedIndicator="@('>')" />
|
||||
}
|
||||
|
||||
<Markup Content=" " />
|
||||
<Markup Content="[grey]Go to Settings tab to toggle modules and tools[/]" />
|
||||
<Markup Content="@GetFooterText()" Foreground="@UiPalette.TextMuted" />
|
||||
</Rows>
|
||||
|
||||
@code {
|
||||
[Parameter, EditorRequired] public IReadOnlyList<OverviewRow> Rows { get; set; } = Array.Empty<OverviewRow>();
|
||||
[Parameter] public int SelectedIndex { get; set; }
|
||||
[Parameter] public EventCallback<int> SelectedIndexChanged { get; set; }
|
||||
[Parameter] public int ViewportRows { get; set; } = 3;
|
||||
|
||||
private int[] GetOptions() => Enumerable.Range(0, Rows.Count).ToArray();
|
||||
|
||||
private int GetNormalizedIndex() => Rows.Count == 0 ? 0 : Math.Clamp(SelectedIndex, 0, Rows.Count - 1);
|
||||
|
||||
private string GetFooterText()
|
||||
{
|
||||
if (Rows.Count == 0)
|
||||
{
|
||||
return "No integration modules available.";
|
||||
}
|
||||
|
||||
var selected = Rows[Math.Clamp(SelectedIndex, 0, Rows.Count - 1)];
|
||||
var state = selected.IsModuleEnabled ? "ON" : "OFF";
|
||||
return $"{selected.ModuleName}: {selected.Description} | Module {state} | Tools {selected.ConfiguredTools}/{selected.TotalTools}";
|
||||
}
|
||||
|
||||
private static Spectre.Console.Color GetRowForeground(OverviewRow row) =>
|
||||
row.IsModuleEnabled ? UiPalette.Text : UiPalette.TextMuted;
|
||||
|
||||
private string FormatRow(int index)
|
||||
{
|
||||
var row = Rows[index];
|
||||
var status = row.IsModuleEnabled ? "[ON] " : "[OFF]";
|
||||
var text = $"{row.ModuleName,-12} {status} {row.ConfiguredTools,2}/{row.TotalTools,-2} {row.Description}";
|
||||
return Fit(text, Math.Max(Console.WindowWidth - 12, 32));
|
||||
}
|
||||
|
||||
private static string Fit(string text, int width)
|
||||
{
|
||||
if (width <= 0)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
if (text.Length <= width)
|
||||
{
|
||||
return text.PadRight(width);
|
||||
}
|
||||
|
||||
if (width <= 3)
|
||||
{
|
||||
return text[..width];
|
||||
}
|
||||
|
||||
return text[..(width - 3)] + "...";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,42 +1,89 @@
|
||||
@using LazyBear.MCP.Services.ToolRegistry
|
||||
@inject ToolRegistryService Registry
|
||||
|
||||
<Rows>
|
||||
<Markup Content=" " />
|
||||
<Markup Content="[bold]Tool Registry — runtime enable/disable[/]" />
|
||||
<Markup Content="[grey]Changes take effect immediately without restart[/]" />
|
||||
<Markup Content="Tool Registry" Foreground="@UiPalette.Text" Decoration="@Spectre.Console.Decoration.Bold" />
|
||||
<Markup Content="Up/Down select. Left/Right collapse or expand. Space toggles state." Foreground="@UiPalette.TextMuted" />
|
||||
<Markup Content=" " />
|
||||
|
||||
@{
|
||||
int focusIdx = 20;
|
||||
}
|
||||
|
||||
@foreach (var module in Registry.GetModules())
|
||||
@if (Entries.Count == 0)
|
||||
{
|
||||
var moduleEnabled = Registry.IsModuleEnabled(module.ModuleName);
|
||||
var moduleColor = moduleEnabled ? Spectre.Console.Color.Green : Spectre.Console.Color.Red;
|
||||
var moduleName = module.ModuleName;
|
||||
var capturedFocus = focusIdx++;
|
||||
|
||||
<Panel Title="@module.ModuleName" BorderColor="@moduleColor" Expand="true">
|
||||
<Rows>
|
||||
<Columns>
|
||||
<TextButton Content="@(moduleEnabled ? "[green]■ MODULE ENABLED[/]" : "[red]□ MODULE DISABLED[/]")"
|
||||
OnClick="@(() => Registry.ToggleModule(moduleName))"
|
||||
BackgroundColor="@(moduleEnabled ? Spectre.Console.Color.DarkGreen : Spectre.Console.Color.DarkRed)"
|
||||
FocusedColor="@Spectre.Console.Color.Yellow"
|
||||
FocusOrder="@capturedFocus" />
|
||||
<Markup Content="@($" {module.Description}")" Foreground="@Spectre.Console.Color.Grey" />
|
||||
</Columns>
|
||||
<Markup Content=" " />
|
||||
<ToolButtonList Module="@module" StartFocusIdx="@focusIdx" />
|
||||
</Rows>
|
||||
</Panel>
|
||||
|
||||
focusIdx += module.ToolNames.Count;
|
||||
<Markup Content=" " />
|
||||
<Border BorderColor="@UiPalette.Frame" BoxBorder="@Spectre.Console.BoxBorder.Rounded" Padding="@(new Spectre.Console.Padding(0, 0, 0, 0))">
|
||||
<Markup Content="No modules available." Foreground="@UiPalette.TextDim" />
|
||||
</Border>
|
||||
}
|
||||
else
|
||||
{
|
||||
<Select TItem="int"
|
||||
Options="@GetOptions()"
|
||||
Value="@GetNormalizedIndex()"
|
||||
FocusedValue="@GetNormalizedIndex()"
|
||||
Formatter="@FormatEntry"
|
||||
Expand="true"
|
||||
BorderStyle="@Spectre.Console.BoxBorder.Rounded"
|
||||
SelectedIndicator="@('>')" />
|
||||
}
|
||||
|
||||
<Markup Content=" " />
|
||||
<Markup Content="@GetSelectedDescription()" Foreground="@UiPalette.TextMuted" />
|
||||
</Rows>
|
||||
|
||||
@code {
|
||||
[Parameter, EditorRequired] public IReadOnlyList<SettingsEntry> Entries { get; set; } = Array.Empty<SettingsEntry>();
|
||||
[Parameter] public int SelectedIndex { get; set; }
|
||||
[Parameter] public EventCallback<int> SelectedIndexChanged { get; set; }
|
||||
[Parameter] public int ViewportRows { get; set; } = 5;
|
||||
|
||||
private int[] GetOptions() => Enumerable.Range(0, Entries.Count).ToArray();
|
||||
|
||||
private int GetNormalizedIndex() => Entries.Count == 0 ? 0 : Math.Clamp(SelectedIndex, 0, Entries.Count - 1);
|
||||
|
||||
private string GetSelectedDescription()
|
||||
{
|
||||
if (Entries.Count == 0)
|
||||
{
|
||||
return "Runtime enable/disable settings are unavailable.";
|
||||
}
|
||||
|
||||
var selected = Entries[Math.Clamp(SelectedIndex, 0, Entries.Count - 1)];
|
||||
return selected.Description;
|
||||
}
|
||||
|
||||
private string FormatEntry(int index)
|
||||
{
|
||||
var entry = Entries[index];
|
||||
var indent = new string(' ', entry.Depth * 4);
|
||||
var checkbox = entry.IsChecked ? "[x]" : "[ ]";
|
||||
var disabledSuffix = entry.Kind == SettingsEntryKind.Tool && !entry.IsModuleEnabled ? " (module off)" : string.Empty;
|
||||
|
||||
string text;
|
||||
if (entry.Kind == SettingsEntryKind.Module)
|
||||
{
|
||||
var expander = entry.IsExpanded ? "[-]" : "[+]";
|
||||
text = $"{expander} {checkbox} {entry.Label}";
|
||||
}
|
||||
else
|
||||
{
|
||||
text = $"{indent}{checkbox} {entry.Label}{disabledSuffix}";
|
||||
}
|
||||
|
||||
return Fit(text, Math.Max(Console.WindowWidth - 12, 32));
|
||||
}
|
||||
|
||||
private static string Fit(string text, int width)
|
||||
{
|
||||
if (width <= 0)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
if (text.Length <= width)
|
||||
{
|
||||
return text.PadRight(width);
|
||||
}
|
||||
|
||||
if (width <= 3)
|
||||
{
|
||||
return text[..width];
|
||||
}
|
||||
|
||||
return text[..(width - 3)] + "...";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,9 @@
|
||||
var moduleName = Module.ModuleName;
|
||||
var fo = StartFocusIdx + idx;
|
||||
|
||||
<TextButton Content="@(toolEnabled ? $"[green]✓[/] {toolName}" : $"[grey]✗[/] {toolName}")"
|
||||
<TextButton Content="@(toolEnabled ? $"✓ {toolName}" : $"✗ {toolName}")"
|
||||
OnClick="@(() => Registry.ToggleTool(moduleName, toolName))"
|
||||
BackgroundColor="@(toolEnabled ? Spectre.Console.Color.Grey19 : Spectre.Console.Color.Grey7)"
|
||||
BackgroundColor="@(toolEnabled ? Spectre.Console.Color.DarkGreen : Spectre.Console.Color.Grey11)"
|
||||
FocusedColor="@Spectre.Console.Color.Yellow"
|
||||
FocusOrder="@fo" />
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
@using Microsoft.AspNetCore.Components
|
||||
@using Microsoft.AspNetCore.Components.Web
|
||||
@using RazorConsole.Components
|
||||
@using RazorConsole.Core
|
||||
@using RazorConsole.Core.Rendering
|
||||
@using LazyBear.MCP.TUI
|
||||
@using LazyBear.MCP.TUI.Models
|
||||
@using LazyBear.MCP.TUI.Components
|
||||
|
||||
74
LazyBear.MCP/TUI/GlobalKeyboardService.cs
Normal file
74
LazyBear.MCP/TUI/GlobalKeyboardService.cs
Normal file
@@ -0,0 +1,74 @@
|
||||
using Microsoft.Extensions.Hosting;
|
||||
|
||||
namespace LazyBear.MCP.TUI;
|
||||
|
||||
/// <summary>
|
||||
/// Фоновый сервис для глобального чтения клавиш консоли.
|
||||
/// Единственный источник клавишных событий для всего TUI.
|
||||
///
|
||||
/// Использует выделенный поток с блокирующим Console.ReadKey — никакого
|
||||
/// polling-а, нет обращений к Console.KeyAvailable, которые захватывают
|
||||
/// консольный mutex и мешают рендерингу RazorConsole.
|
||||
/// </summary>
|
||||
public sealed class GlobalKeyboardService : IHostedService, IDisposable
|
||||
{
|
||||
public event Action<ConsoleKeyInfo>? OnKeyPressed;
|
||||
|
||||
private Thread? _thread;
|
||||
private volatile bool _stopping;
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (Console.IsInputRedirected)
|
||||
{
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
_thread = new Thread(ReadLoop)
|
||||
{
|
||||
IsBackground = true,
|
||||
Name = "KeyboardReader"
|
||||
};
|
||||
_thread.Start();
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_stopping = true;
|
||||
// Console.ReadKey не поддерживает CancellationToken — поток
|
||||
// завершится сам при выходе приложения (IsBackground = true).
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void ReadLoop()
|
||||
{
|
||||
while (!_stopping)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Блокирующий вызов: не нагружает CPU и не трогает консольный
|
||||
// mutex в паузах между нажатиями — рендеринг не страдает.
|
||||
var key = Console.ReadKey(intercept: true);
|
||||
if (!_stopping)
|
||||
{
|
||||
OnKeyPressed?.Invoke(key);
|
||||
}
|
||||
}
|
||||
catch (InvalidOperationException)
|
||||
{
|
||||
// stdin стал недоступен (перенаправление и т.п.)
|
||||
break;
|
||||
}
|
||||
catch
|
||||
{
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_stopping = true;
|
||||
}
|
||||
}
|
||||
8
LazyBear.MCP/TUI/Models/OverviewRow.cs
Normal file
8
LazyBear.MCP/TUI/Models/OverviewRow.cs
Normal file
@@ -0,0 +1,8 @@
|
||||
namespace LazyBear.MCP.TUI.Models;
|
||||
|
||||
public sealed record OverviewRow(
|
||||
string ModuleName,
|
||||
string Description,
|
||||
bool IsModuleEnabled,
|
||||
int ConfiguredTools,
|
||||
int TotalTools);
|
||||
18
LazyBear.MCP/TUI/Models/SettingsEntry.cs
Normal file
18
LazyBear.MCP/TUI/Models/SettingsEntry.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
namespace LazyBear.MCP.TUI.Models;
|
||||
|
||||
public enum SettingsEntryKind
|
||||
{
|
||||
Module,
|
||||
Tool
|
||||
}
|
||||
|
||||
public sealed record SettingsEntry(
|
||||
SettingsEntryKind Kind,
|
||||
string ModuleName,
|
||||
string? ToolName,
|
||||
string Label,
|
||||
string Description,
|
||||
bool IsChecked,
|
||||
bool IsModuleEnabled,
|
||||
bool IsExpanded,
|
||||
int Depth);
|
||||
@@ -1,69 +0,0 @@
|
||||
using LazyBear.MCP.Services.ToolRegistry;
|
||||
using LazyBear.MCP.TUI.Components;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using RazorConsole.Core;
|
||||
|
||||
namespace LazyBear.MCP.TUI;
|
||||
|
||||
/// <summary>
|
||||
/// Запускает RazorConsole TUI как IHostedService в отдельном потоке,
|
||||
/// чтобы не блокировать ASP.NET Core pipeline.
|
||||
/// </summary>
|
||||
public sealed class TuiHostedService(IServiceProvider services, ILogger<TuiHostedService> logger) : IHostedService
|
||||
{
|
||||
private Thread? _tuiThread;
|
||||
private CancellationTokenSource? _cts;
|
||||
|
||||
public Task StartAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_cts = new CancellationTokenSource();
|
||||
|
||||
// Регистрируем все IToolModule-модули в ToolRegistryService
|
||||
var registry = services.GetRequiredService<ToolRegistryService>();
|
||||
foreach (var module in services.GetServices<IToolModule>())
|
||||
{
|
||||
registry.RegisterModule(module);
|
||||
}
|
||||
|
||||
_tuiThread = new Thread(RunTui)
|
||||
{
|
||||
IsBackground = true,
|
||||
Name = "RazorConsole-TUI"
|
||||
};
|
||||
_tuiThread.Start();
|
||||
|
||||
logger.LogInformation("TUI запущен в фоновом потоке");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
public Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
_cts?.Cancel();
|
||||
logger.LogInformation("TUI остановлен");
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
private void RunTui()
|
||||
{
|
||||
try
|
||||
{
|
||||
var host = Host.CreateDefaultBuilder()
|
||||
.UseRazorConsole<App>(configure: configure =>
|
||||
{
|
||||
configure.ConfigureServices((_, svc) =>
|
||||
{
|
||||
// Пробрасываем ключевые Singleton из основного DI-контейнера в TUI-контейнер
|
||||
svc.AddSingleton(services.GetRequiredService<ToolRegistryService>());
|
||||
svc.AddSingleton(services.GetRequiredService<Services.Logging.InMemoryLogSink>());
|
||||
});
|
||||
})
|
||||
.Build();
|
||||
|
||||
host.Run();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "Ошибка в потоке TUI");
|
||||
}
|
||||
}
|
||||
}
|
||||
21
LazyBear.MCP/TUI/UiPalette.cs
Normal file
21
LazyBear.MCP/TUI/UiPalette.cs
Normal file
@@ -0,0 +1,21 @@
|
||||
using Spectre.Console;
|
||||
|
||||
namespace LazyBear.MCP.TUI;
|
||||
|
||||
internal static class UiPalette
|
||||
{
|
||||
public static readonly Color Frame = new(26, 44, 64);
|
||||
public static readonly Color Surface = new(12, 21, 34);
|
||||
public static readonly Color SurfaceAlt = new(18, 29, 44);
|
||||
public static readonly Color SurfaceMuted = new(28, 40, 56);
|
||||
public static readonly Color Accent = Color.Cyan1;
|
||||
public static readonly Color AccentSoft = Color.DeepSkyBlue1;
|
||||
public static readonly Color Text = Color.Grey93;
|
||||
public static readonly Color TextMuted = Color.Grey62;
|
||||
public static readonly Color TextDim = Color.Grey46;
|
||||
public static readonly Color Success = Color.Green3;
|
||||
public static readonly Color Warning = Color.Yellow3;
|
||||
public static readonly Color Danger = Color.Red3;
|
||||
public static readonly Color SelectionBackground = new(24, 152, 181);
|
||||
public static readonly Color SelectionForeground = new(7, 18, 31);
|
||||
}
|
||||
Reference in New Issue
Block a user