Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
202 lines
14 KiB
C#
202 lines
14 KiB
C#
using Avalonia;
|
|
using Avalonia.Controls;
|
|
using Avalonia.Layout;
|
|
using Avalonia.Media;
|
|
using Avalonia.Platform.Storage;
|
|
using System.Text.Json.Nodes;
|
|
|
|
namespace Strata.Desktop;
|
|
|
|
public sealed class MainWindow : Window
|
|
{
|
|
private static readonly IBrush Accent = Brush.Parse("#82DFCB");
|
|
private static readonly IBrush Muted = Brush.Parse("#9DABB9");
|
|
private readonly StackPanel hardwareCards = new() { Spacing = 12 };
|
|
private readonly StackPanel planCards = new() { Spacing = 12 };
|
|
private readonly TextBlock status = Text("Підключення до gRPC-вузла…", 13, Muted);
|
|
private readonly TextBlock connectionStatus = Text("Вузол: підключення…", 13, Muted);
|
|
private readonly TextBlock details = Text("", 13, Muted);
|
|
private readonly Button refresh = Action("Оновити обладнання");
|
|
private readonly Button import = Action("Відкрити профіль…");
|
|
private readonly Button example = Action("Приклад оцінки");
|
|
private readonly WorkerController worker = new(CoreClient.WorkerRpc());
|
|
private readonly TextBlock workerStatus = Text("Модель: перевірка вузла…", 14, Muted);
|
|
private readonly Button startWorker = Action("Запустити модель");
|
|
private readonly Button stopWorker = Action("Зупинити модель");
|
|
private readonly CancellationTokenSource lifetime = new();
|
|
|
|
public MainWindow()
|
|
{
|
|
Title = "Strata · " + CoreClient.SourceLabel;
|
|
Width = 1200; Height = 840; MinWidth = 900; MinHeight = 650;
|
|
Background = Brush.Parse("#10151C");
|
|
var root = new Grid { ColumnDefinitions = new ColumnDefinitions("220,*") };
|
|
var sidebar = new StackPanel { Margin = new Thickness(24, 32), Spacing = 24 };
|
|
sidebar.Children.Add(Text("strata", 34, Accent, FontWeight.Bold));
|
|
sidebar.Children.Add(Text("ЛОКАЛЬНИЙ ІНТЕЛЕКТ", 10, Muted));
|
|
sidebar.Children.Add(new Border { Background = Brush.Parse("#243830"), CornerRadius = new CornerRadius(8),
|
|
Padding = new Thickness(14, 12), Child = Text(CoreClient.SourceLabel, 15, Accent, FontWeight.SemiBold) });
|
|
sidebar.Children.Add(Text("Моделі та підготовка\nНаступний етап", 13, Muted));
|
|
sidebar.Children.Add(Text("Автопідбір\nНаступний етап", 13, Muted));
|
|
sidebar.Children.Add(new Border { Height = 1, Background = Brush.Parse("#303B46") });
|
|
sidebar.Children.Add(Text("DESKTOP PREVIEW", 10, Accent));
|
|
sidebar.Children.Add(Text("Спільний інтерфейс.\nОкреме Rust-ядро.\nДані на вашому пристрої.", 12, Muted));
|
|
root.Children.Add(new Border { Background = Brush.Parse("#161E27"), Child = sidebar });
|
|
var page = new StackPanel { Margin = new Thickness(34, 30), Spacing = 20 };
|
|
page.Children.Add(Text("Рушій починається з вашого заліза", 27, Brushes.White, FontWeight.SemiBold));
|
|
page.Children.Add(Text("Визначте ресурси. Перевірте бюджет пам’яті. Оберіть наступний крок.", 14, Muted));
|
|
var toolbar = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10 };
|
|
toolbar.Children.Add(refresh); toolbar.Children.Add(import); toolbar.Children.Add(example);
|
|
page.Children.Add(toolbar);
|
|
page.Children.Add(status);
|
|
page.Children.Add(connectionStatus);
|
|
page.Children.Add(workerStatus);
|
|
var workerActions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10 };
|
|
startWorker.IsEnabled = stopWorker.IsEnabled = false;
|
|
workerActions.Children.Add(startWorker); workerActions.Children.Add(stopWorker);
|
|
page.Children.Add(workerActions);
|
|
startWorker.Click += async (_, _) => await WorkerCommand(true);
|
|
stopWorker.Click += async (_, _) => await WorkerCommand(false);
|
|
var columns = new Grid { ColumnDefinitions = new ColumnDefinitions("*,24,*") };
|
|
var left = new StackPanel { Spacing = 14 };
|
|
left.Children.Add(Text("ОБЛАДНАННЯ", 11, Accent, FontWeight.SemiBold));
|
|
left.Children.Add(hardwareCards); left.Children.Add(details);
|
|
columns.Children.Add(left);
|
|
var right = new StackPanel { Spacing = 14 };
|
|
right.Children.Add(Text("ПЛАН РОЗМІЩЕННЯ", 11, Accent, FontWeight.SemiBold));
|
|
right.Children.Add(planCards); Grid.SetColumn(right, 2); columns.Children.Add(right);
|
|
page.Children.Add(columns);
|
|
var scroll = new ScrollViewer { Content = page, HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled };
|
|
Grid.SetColumn(scroll, 1); root.Children.Add(scroll); Content = root;
|
|
planCards.Children.Add(Card("Спочатку — вимоги моделі", "Відкрийте JSON-профіль із runtime-розмірами ваг, KV і буферів. Або перегляньте явно позначений синтетичний приклад."));
|
|
planCards.Children.Add(Card("Що вже працює", "Локальне визначення обладнання та оцінка пам’яті. Керування встановленою моделлю доступне на налаштованому керованому вузлі. Завантаження моделей і автоматичні бенчмарки ще попереду."));
|
|
refresh.Click += async (_, _) => await Busy(RefreshHardware);
|
|
import.Click += async (_, _) => await PickProfile();
|
|
example.Click += async (_, _) => await Busy(() => LoadPlan(Path.Combine(AppContext.BaseDirectory, "example-requirements.json")));
|
|
Opened += async (_, _) => {
|
|
_ = ObserveWorker();
|
|
await Busy(RefreshHardware);
|
|
_ = Task.Run(() => CoreClient.Observe(state => Avalonia.Threading.Dispatcher.UIThread.Post(() => {
|
|
connectionStatus.Text = state.Phase switch {
|
|
"ready" => $"Вузол підключений · активних запитів: {state.ActiveResponses}",
|
|
"auth_error" => "Вузол: перевірте credential підключення",
|
|
"protocol_error" => "Вузол: несумісний протокол",
|
|
"configuration_error" => "Вузол: перевірте налаштування підключення",
|
|
"connecting" => "Вузол: підключення…",
|
|
_ => "Зв’язок із вузлом втрачено · відновлення…"
|
|
};
|
|
connectionStatus.Foreground = state.Phase == "ready" ? Accent : Muted;
|
|
}), lifetime.Token));
|
|
};
|
|
Closed += (_, _) => lifetime.Cancel();
|
|
}
|
|
|
|
private void RenderWorker()
|
|
{
|
|
var w = worker.View;
|
|
string label = w.Phase switch {
|
|
"ready" => "Модель готова", "stopped" => "Модель зупинена",
|
|
"starting" => "Завантаження моделі…", "draining" => "Завершення активних запитів…",
|
|
"failed" => "Помилка моделі", "unmanaged" => "На цьому вузлі немає профілю запуску моделі",
|
|
"auth_error" => "Перевірте доступ до вузла", "reconcile" => "Потрібна звірка стану",
|
|
_ => "Стан моделі недоступний · відновлення зв’язку…"
|
|
};
|
|
workerStatus.Text = label + (w.Model.Length > 0 ? " · " + w.Model : "")
|
|
+ (w.Detail.Length > 0 ? "\n" + w.Detail : "")
|
|
+ (w.OperationId.Length > 0 ? "\nОперація: " + w.OperationId : "");
|
|
startWorker.IsEnabled = w.CanStart; stopWorker.IsEnabled = w.CanStop;
|
|
}
|
|
private async Task ObserveWorker()
|
|
{
|
|
try {
|
|
while (!lifetime.IsCancellationRequested) {
|
|
await worker.Refresh(lifetime.Token); RenderWorker();
|
|
await Task.Delay(1000, lifetime.Token);
|
|
}
|
|
} catch (OperationCanceledException) {}
|
|
}
|
|
private async Task WorkerCommand(bool start)
|
|
{
|
|
startWorker.IsEnabled = stopWorker.IsEnabled = false;
|
|
try { await worker.Command(start, lifetime.Token); RenderWorker(); }
|
|
catch (OperationCanceledException) {}
|
|
}
|
|
|
|
private async Task Busy(Func<Task> action)
|
|
{
|
|
refresh.IsEnabled = import.IsEnabled = example.IsEnabled = false;
|
|
status.Text = "Зчитування ресурсів вузла…"; status.Foreground = Muted;
|
|
try { await action(); status.Text = "Готово · дані вузла · жодних inference-запитів"; }
|
|
catch (OperationCanceledException) { status.Text = "Зчитування скасовано або перевищено час очікування."; }
|
|
catch (Exception e) { status.Text = e.Message; status.Foreground = Brush.Parse("#FFBF87"); }
|
|
finally { refresh.IsEnabled = import.IsEnabled = example.IsEnabled = true; }
|
|
}
|
|
|
|
private async Task RefreshHardware()
|
|
{
|
|
var h = await CoreClient.Run(lifetime.Token, "hardware");
|
|
hardwareCards.Children.Clear();
|
|
hardwareCards.Children.Add(Card(S(h, "cpu_name"), $"{S(h, "os")} / {S(h, "architecture")} · {h["logical_cpus"]} потоків\n" +
|
|
string.Join(" · ", h["cpu_features"]!.AsArray().Select(v => v!.GetValue<string>()))));
|
|
hardwareCards.Children.Add(Card("Оперативна пам’ять", $"{Memory(h["memory"]?["available_bytes"])} доступно\n{Memory(h["memory"]?["total_bytes"])} загалом"));
|
|
foreach (var g in h["accelerators"]!.AsArray().OfType<JsonObject>())
|
|
{
|
|
var shared = S(g, "memory_kind") == "shared";
|
|
hardwareCards.Children.Add(Card(S(g, "name"), shared
|
|
? "Спільна пам’ять із CPU\nЛіміт GPU ще не визначено"
|
|
: $"{Memory(g["memory"]?["available_bytes"])} доступно з {Memory(g["memory"]?["total_bytes"])}\nДрайвер: {S(g, "driver")}"));
|
|
}
|
|
if (h["accelerators"]!.AsArray().Count == 0)
|
|
hardwareCards.Children.Add(Card("GPU не визначено", "Це не підтверджує відсутність GPU. Перевірте доступність драйвера й підтримку probe."));
|
|
details.Text = "NPU та сумісність inference-рушіїв перевірятимуться окремо.";
|
|
if (h["warnings"] is JsonArray warnings && warnings.Count > 0)
|
|
details.Text += "\n\n" + string.Join("\n", warnings.Select(v => v!.GetValue<string>()));
|
|
}
|
|
|
|
private async Task PickProfile()
|
|
{
|
|
await Busy(async () => {
|
|
var files = await StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions {
|
|
Title = "Профіль вимог моделі (JSON)", AllowMultiple = false,
|
|
// macOS type associations can hide valid JSON; the core validates contents.
|
|
FileTypeFilter = [FilePickerFileTypes.All]
|
|
});
|
|
if (files.Count == 0) return;
|
|
var path = files[0].TryGetLocalPath() ?? throw new InvalidOperationException("Потрібен локальний JSON-файл.");
|
|
await LoadPlan(path);
|
|
});
|
|
}
|
|
|
|
private async Task LoadPlan(string path)
|
|
{
|
|
var p = await CoreClient.Run(lifetime.Token, "plan", path);
|
|
planCards.Children.Clear();
|
|
planCards.Children.Add(Card(S(p, "model"), $"Контекст {p["context_tokens"]} · запитів {p["concurrent_requests"]}\nОцінка пам’яті; швидкість і сумісність ще не перевірені."));
|
|
foreach (var c in p["candidates"]!.AsArray().OfType<JsonObject>())
|
|
{
|
|
var fit = S(c, "fit");
|
|
var label = fit switch { "fits_estimate" => "Вкладається за оцінкою", "insufficient" => "Недостатньо пам’яті", _ => "Потрібні додаткові дані" };
|
|
var message = $"{label}\nПік RAM: {Memory(c["host_peak_bytes"])} · бюджет {Memory(c["host_budget_bytes"])}";
|
|
if (S(c, "device") != "cpu") message += $"\nПік GPU: {Memory(c["device_peak_bytes"])} · бюджет {Memory(c["device_budget_bytes"])}\nВаг на GPU: {c["device_weight_percent"]}%";
|
|
message += "\n" + string.Join("\n", c["reasons"]!.AsArray().Select(v => v!.GetValue<string>()));
|
|
planCards.Children.Add(Card($"{S(c, "device")} · {S(c, "placement")}", message.Trim(), fit == "fits_estimate"));
|
|
}
|
|
}
|
|
|
|
private static string S(JsonNode n, string key) => n[key]?.GetValue<string>() ?? "невідомо";
|
|
private static string Memory(JsonNode? n) => n is null ? "невідомо" : $"{n.GetValue<ulong>() / 1073741824.0:0.0} GiB";
|
|
private static Button Action(string text) => new() { Content = text, Padding = new Thickness(14, 10), CornerRadius = new CornerRadius(7) };
|
|
private static TextBlock Text(string text, double size, IBrush brush, FontWeight? weight = null) => new() {
|
|
Text = text, FontSize = size, Foreground = brush, FontWeight = weight ?? FontWeight.Normal,
|
|
TextWrapping = TextWrapping.Wrap
|
|
};
|
|
private static Border Card(string title, string body, bool positive = false)
|
|
{
|
|
var content = new StackPanel { Spacing = 9 };
|
|
content.Children.Add(Text(title, 17, positive ? Accent : Brushes.White, FontWeight.SemiBold));
|
|
content.Children.Add(Text(body, 13, Muted));
|
|
return new Border { Background = Brush.Parse("#1A2430"), BorderBrush = Brush.Parse(positive ? "#3D6D61" : "#2C3947"),
|
|
BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(12), Padding = new Thickness(20), Child = content };
|
|
}
|
|
}
|