Browse Source

Merge branch 'dev' into inference-reference-controlnet

pull/629/head
Ionite 8 months ago committed by GitHub
parent
commit
8b0bd6acbc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 17
      CHANGELOG.md
  2. 3
      StabilityMatrix.Avalonia/App.axaml
  3. 3
      StabilityMatrix.Avalonia/App.axaml.cs
  4. 76
      StabilityMatrix.Avalonia/Controls/Inference/ControlNetCard.axaml
  5. 5
      StabilityMatrix.Avalonia/Controls/SelectableImageCard/SelectableImageButton.axaml
  6. 8
      StabilityMatrix.Avalonia/Controls/SelectableImageCard/SelectableImageButton.cs
  7. 23
      StabilityMatrix.Avalonia/DesignData/DesignData.cs
  8. 3
      StabilityMatrix.Avalonia/DesignData/MockInferenceClientManager.cs
  9. 9
      StabilityMatrix.Avalonia/FallbackRamCachedWebImageLoader.cs
  10. 135
      StabilityMatrix.Avalonia/Languages/Resources.Designer.cs
  11. 45
      StabilityMatrix.Avalonia/Languages/Resources.resx
  12. 5
      StabilityMatrix.Avalonia/Models/PackageOutputCategory.cs
  13. 1
      StabilityMatrix.Avalonia/Services/IInferenceClientManager.cs
  14. 20
      StabilityMatrix.Avalonia/Services/InferenceClientManager.cs
  15. 148
      StabilityMatrix.Avalonia/Services/RunningPackageService.cs
  16. 73
      StabilityMatrix.Avalonia/Styles/ButtonStyles.axaml
  17. 403
      StabilityMatrix.Avalonia/Styles/CommandBarButtonStyles.axaml
  18. 1
      StabilityMatrix.Avalonia/Styles/ThemeColors.axaml
  19. 105
      StabilityMatrix.Avalonia/ViewModels/Base/InferenceGenerationViewModelBase.cs
  20. 16
      StabilityMatrix.Avalonia/ViewModels/Base/InferenceTabViewModelBase.cs
  21. 3
      StabilityMatrix.Avalonia/ViewModels/CheckpointBrowserViewModel.cs
  22. 3
      StabilityMatrix.Avalonia/ViewModels/CheckpointsPageViewModel.cs
  23. 15
      StabilityMatrix.Avalonia/ViewModels/Dialogs/InferenceConnectionHelpViewModel.cs
  24. 9
      StabilityMatrix.Avalonia/ViewModels/FirstLaunchSetupViewModel.cs
  25. 84
      StabilityMatrix.Avalonia/ViewModels/Inference/ControlNetCardViewModel.cs
  26. 20
      StabilityMatrix.Avalonia/ViewModels/Inference/InferenceImageToImageViewModel.cs
  27. 5
      StabilityMatrix.Avalonia/ViewModels/Inference/InferenceImageToVideoViewModel.cs
  28. 15
      StabilityMatrix.Avalonia/ViewModels/Inference/InferenceImageUpscaleViewModel.cs
  29. 5
      StabilityMatrix.Avalonia/ViewModels/Inference/InferenceTextToImageViewModel.cs
  30. 23
      StabilityMatrix.Avalonia/ViewModels/Inference/Modules/ControlNetModule.cs
  31. 13
      StabilityMatrix.Avalonia/ViewModels/Inference/Modules/HiresFixModule.cs
  32. 16
      StabilityMatrix.Avalonia/ViewModels/Inference/SamplerCardViewModel.cs
  33. 112
      StabilityMatrix.Avalonia/ViewModels/InferenceViewModel.cs
  34. 8
      StabilityMatrix.Avalonia/ViewModels/MainWindowViewModel.cs
  35. 3
      StabilityMatrix.Avalonia/ViewModels/NewCheckpointsPageViewModel.cs
  36. 7
      StabilityMatrix.Avalonia/ViewModels/NewPackageManagerViewModel.cs
  37. 166
      StabilityMatrix.Avalonia/ViewModels/OutputsPageViewModel.cs
  38. 271
      StabilityMatrix.Avalonia/ViewModels/PackageManager/PackageCardViewModel.cs
  39. 2
      StabilityMatrix.Avalonia/ViewModels/PackageManager/PackageInstallDetailViewModel.cs
  40. 15
      StabilityMatrix.Avalonia/ViewModels/PackageManagerViewModel.cs
  41. 161
      StabilityMatrix.Avalonia/ViewModels/RunningPackageViewModel.cs
  42. 60
      StabilityMatrix.Avalonia/ViewModels/Settings/MainSettingsViewModel.cs
  43. 12
      StabilityMatrix.Avalonia/Views/CivitAiBrowserPage.axaml
  44. 93
      StabilityMatrix.Avalonia/Views/ConsoleOutputPage.axaml
  45. 54
      StabilityMatrix.Avalonia/Views/ConsoleOutputPage.axaml.cs
  46. 44
      StabilityMatrix.Avalonia/Views/MainWindow.axaml.cs
  47. 135
      StabilityMatrix.Avalonia/Views/OutputsPage.axaml
  48. 295
      StabilityMatrix.Avalonia/Views/PackageManagerPage.axaml
  49. 33
      StabilityMatrix.Avalonia/Views/PackageManagerPage.axaml.cs
  50. 6
      StabilityMatrix.Core/Attributes/TypedNodeOptionsAttribute.cs
  51. 8
      StabilityMatrix.Core/Helper/EventManager.cs
  52. 1
      StabilityMatrix.Core/Helper/Factory/IPackageFactory.cs
  53. 74
      StabilityMatrix.Core/Helper/Factory/PackageFactory.cs
  54. 16
      StabilityMatrix.Core/Inference/ComfyClient.cs
  55. 124
      StabilityMatrix.Core/Models/Api/Comfy/ComfyAuxPreprocessor.cs
  56. 15
      StabilityMatrix.Core/Models/Api/Comfy/ComfyInputInfo.cs
  57. 2
      StabilityMatrix.Core/Models/Api/Comfy/NodeTypes/ModelConnections.cs
  58. 23
      StabilityMatrix.Core/Models/Api/Comfy/Nodes/ComfyNodeBuilder.cs
  59. 13
      StabilityMatrix.Core/Models/Api/Comfy/Nodes/NodeDictionary.cs
  60. 3
      StabilityMatrix.Core/Models/DownloadPackageVersionOptions.cs
  61. 2
      StabilityMatrix.Core/Models/HybridModelFile.cs
  62. 14
      StabilityMatrix.Core/Models/InferenceRunCustomPromptEventArgs.cs
  63. 105
      StabilityMatrix.Core/Models/Packages/Extensions/ExtensionSpecifier.cs
  64. 25
      StabilityMatrix.Core/Models/Packages/Extensions/GitPackageExtensionManager.cs
  65. 7
      StabilityMatrix.Core/Models/Packages/Extensions/IPackageExtensionManager.cs
  66. 1
      StabilityMatrix.Core/Models/Settings/Settings.cs
  67. 1
      StabilityMatrix.Core/Models/Settings/TeachingTip.cs
  68. 7
      StabilityMatrix.Tests/Helper/PackageFactoryTests.cs

17
CHANGELOG.md

@ -5,6 +5,23 @@ All notable changes to Stability Matrix will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning 2.0](https://semver.org/spec/v2.0.0.html). and this project adheres to [Semantic Versioning 2.0](https://semver.org/spec/v2.0.0.html).
## v2.10.0-dev.2
### Changed
- Inference Primary Sampler Addons (i.e. ControlNet, FreeU) are now inherited by Hires Fix Samplers, this can be overriden from the Hires Fix module's settings menu by disabling the "Inherit Primary Sampler Addons" option.
- Revisited the way images are loaded on the outputs page, with improvements to loading speed & not freezing the UI while loading
### Fixed
- Fixed Outputs page not remembering where the user last was in the TreeView in certain circumstances
## v2.10.0-dev.1
### Added
- Inference ControlNet module now supports over 42 preprocessors, a new button next to the preprocessors dropdown allows previewing the output of the selected preprocessor on the image.
- Added resolution selection for Inference ControlNet module, this controls preprocessor resolution too.
### Changed
- Revamped the Packages page to enable running multiple packages at the same time
- Changed the Outputs Page to use a TreeView for the directory selection instead of a dropdown selector
### Removed
- Removed the main Launch page, as it is no longer needed with the new Packages page
## v2.9.1 ## v2.9.1
### Added ### Added
- Fixed [#498](https://github.com/LykosAI/StabilityMatrix/issues/498) Added "Pony" category to CivitAI Model Browser - Fixed [#498](https://github.com/LykosAI/StabilityMatrix/issues/498) Added "Pony" category to CivitAI Model Browser

3
StabilityMatrix.Avalonia/App.axaml

@ -4,6 +4,7 @@
xmlns:local="using:StabilityMatrix.Avalonia" xmlns:local="using:StabilityMatrix.Avalonia"
xmlns:idcr="using:Dock.Avalonia.Controls.Recycling" xmlns:idcr="using:Dock.Avalonia.Controls.Recycling"
xmlns:styling="clr-namespace:FluentAvalonia.Styling;assembly=FluentAvalonia" xmlns:styling="clr-namespace:FluentAvalonia.Styling;assembly=FluentAvalonia"
xmlns:controls="clr-namespace:Avalonia.Labs.Controls;assembly=Avalonia.Labs.Controls"
Name="Stability Matrix" Name="Stability Matrix"
RequestedThemeVariant="Dark"> RequestedThemeVariant="Dark">
<!-- "Default" ThemeVariant follows system theme variant. "Dark" or "Light" are other available options. --> <!-- "Default" ThemeVariant follows system theme variant. "Dark" or "Light" are other available options. -->
@ -54,6 +55,7 @@
<StyleInclude Source="Styles/DockStyles.axaml"/> <StyleInclude Source="Styles/DockStyles.axaml"/>
<StyleInclude Source="Styles/BorderStyles.axaml"/> <StyleInclude Source="Styles/BorderStyles.axaml"/>
<StyleInclude Source="Styles/TextBoxStyles.axaml"/> <StyleInclude Source="Styles/TextBoxStyles.axaml"/>
<StyleInclude Source="Styles/CommandBarButtonStyles.axaml"/>
<StyleInclude Source="Controls/AdvancedImageBox.axaml"/> <StyleInclude Source="Controls/AdvancedImageBox.axaml"/>
<StyleInclude Source="Controls/FrameCarousel.axaml"/> <StyleInclude Source="Controls/FrameCarousel.axaml"/>
<StyleInclude Source="Controls/CodeCompletion/CompletionWindow.axaml"/> <StyleInclude Source="Controls/CodeCompletion/CompletionWindow.axaml"/>
@ -79,6 +81,7 @@
<StyleInclude Source="Controls/Inference/FreeUCard.axaml"/> <StyleInclude Source="Controls/Inference/FreeUCard.axaml"/>
<StyleInclude Source="Controls/Inference/ControlNetCard.axaml"/> <StyleInclude Source="Controls/Inference/ControlNetCard.axaml"/>
<StyleInclude Source="Controls/Inference/PromptExpansionCard.axaml"/> <StyleInclude Source="Controls/Inference/PromptExpansionCard.axaml"/>
<controls:ControlThemes/>
<Style Selector="DockControl"> <Style Selector="DockControl">
<Setter Property="(DockProperties.ControlRecycling)" Value="{StaticResource ControlRecyclingKey}" /> <Setter Property="(DockProperties.ControlRecycling)" Value="{StaticResource ControlRecyclingKey}" />

3
StabilityMatrix.Avalonia/App.axaml.cs

@ -328,9 +328,8 @@ public sealed class App : Application
{ {
Pages = Pages =
{ {
provider.GetRequiredService<LaunchPageViewModel>(),
provider.GetRequiredService<InferenceViewModel>(),
provider.GetRequiredService<NewPackageManagerViewModel>(), provider.GetRequiredService<NewPackageManagerViewModel>(),
provider.GetRequiredService<InferenceViewModel>(),
provider.GetRequiredService<CheckpointsPageViewModel>(), provider.GetRequiredService<CheckpointsPageViewModel>(),
provider.GetRequiredService<CheckpointBrowserViewModel>(), provider.GetRequiredService<CheckpointBrowserViewModel>(),
provider.GetRequiredService<OutputsPageViewModel>() provider.GetRequiredService<OutputsPageViewModel>()

76
StabilityMatrix.Avalonia/Controls/Inference/ControlNetCard.axaml

@ -36,29 +36,46 @@
<sg:SpacedGrid <sg:SpacedGrid
ColumnDefinitions="0.34*,0.65*" ColumnDefinitions="0.34*,0.65*"
ColumnSpacing="8" ColumnSpacing="8"
RowDefinitions="Auto,Auto,Auto" RowDefinitions="Auto,Auto,Auto,Auto"
RowSpacing="4"> RowSpacing="4">
<!-- Image Select --> <!-- Image Select -->
<controls:SelectImageCard <controls:SelectImageCard
Grid.RowSpan="2" Grid.RowSpan="3"
Padding="6" Padding="6"
VerticalAlignment="Stretch" VerticalAlignment="Stretch"
DataContext="{Binding SelectImageCardViewModel}" DataContext="{Binding SelectImageCardViewModel}"
FontSize="13" /> FontSize="13" />
<!-- TODO: Preprocessor Model --> <!-- Preprocessor Model -->
<ui:FAComboBox <sg:SpacedGrid
Grid.Row="0" Grid.Row="0"
Grid.Column="1" Grid.Column="1"
ColumnDefinitions="*,Auto">
<ui:FAComboBox
Margin="0,0,0,4" Margin="0,0,0,4"
SelectedItem="{Binding SelectedPreprocessor}"
ItemsSource="{Binding ClientManager.Preprocessors}"
DisplayMemberBinding="{Binding DisplayName}"
HorizontalAlignment="Stretch" HorizontalAlignment="Stretch"
markupExtensions:ShowDisabledTooltipExtension.ShowOnDisabled="True" Header="{x:Static lang:Resources.Label_Preprocessor}"/>
Header="{x:Static lang:Resources.Label_Preprocessor}"
IsEnabled="False" <Button
Theme="{StaticResource FAComboBoxHybridModelTheme}" ToolTip.Tip="{x:Static lang:Resources.Action_PreviewPreprocessor}"
ToolTip.ShowDelay="1200" Padding="7"
ToolTip.Tip="{StaticResource WipFeatureToolTip}" /> VerticalAlignment="Center"
Margin="0,23,0,0"
Command="{Binding PreviewPreprocessorCommand}"
CommandParameter="{Binding SelectedPreprocessor}"
Grid.Column="1">
<fluentIcons:SymbolIcon
VerticalAlignment="Center"
FontSize="15"
IsFilled="True"
Symbol="Play" />
</Button>
</sg:SpacedGrid>
<!-- ControlNet Model --> <!-- ControlNet Model -->
<ui:FAComboBox <ui:FAComboBox
@ -102,6 +119,45 @@
</ui:FAComboBox> </ui:FAComboBox>
<!-- Dimensions -->
<Grid
Grid.Row="2"
Grid.Column="1"
Margin="0,4,0,0"
ColumnDefinitions="*,Auto,*"
RowDefinitions="Auto,*">
<TextBlock
Grid.Row="0"
Grid.Column="0"
Margin="0,0,4,4"
Text="{x:Static lang:Resources.Label_Width}"/>
<ui:NumberBox
Grid.Row="1"
Grid.Column="0"
Margin="0,0,4,0"
PlaceholderText="128"
SmallChange="128"
Value="{Binding Width}"
ValidationMode="InvalidInputOverwritten"
HorizontalAlignment="Stretch"
SpinButtonPlacementMode="Compact"/>
<TextBlock
Grid.Row="0"
Grid.Column="2"
Margin="4,0,0,4"
Text="{x:Static lang:Resources.Label_Height}"/>
<ui:NumberBox
Grid.Row="1"
Grid.Column="2"
Margin="4,0,0,0"
PlaceholderText="128"
SmallChange="128"
Value="{Binding Height}"
ValidationMode="InvalidInputOverwritten"
HorizontalAlignment="Stretch"
SpinButtonPlacementMode="Compact"/>
</Grid>
</sg:SpacedGrid> </sg:SpacedGrid>
<sg:SpacedGrid <sg:SpacedGrid
ColumnDefinitions="*,Auto,Auto" ColumnDefinitions="*,Auto,Auto"

5
StabilityMatrix.Avalonia/Controls/SelectableImageCard/SelectableImageButton.axaml

@ -1,7 +1,8 @@
<Styles xmlns="https://github.com/avaloniaui" <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:selectableImageCard="clr-namespace:StabilityMatrix.Avalonia.Controls.SelectableImageCard" xmlns:selectableImageCard="clr-namespace:StabilityMatrix.Avalonia.Controls.SelectableImageCard"
xmlns:controls="clr-namespace:StabilityMatrix.Avalonia.Controls"> xmlns:controls="clr-namespace:StabilityMatrix.Avalonia.Controls"
xmlns:controls1="clr-namespace:Avalonia.Labs.Controls;assembly=Avalonia.Labs.Controls">
<Design.PreviewWith> <Design.PreviewWith>
<Border Padding="20"> <Border Padding="20">
<!-- Add Controls for Previewer Here --> <!-- Add Controls for Previewer Here -->
@ -38,7 +39,7 @@
CornerRadius="12" CornerRadius="12"
Command="{TemplateBinding Command}" Command="{TemplateBinding Command}"
CommandParameter="{TemplateBinding CommandParameter}"> CommandParameter="{TemplateBinding CommandParameter}">
<controls:BetterAdvancedImage <controls1:AsyncImage
Stretch="UniformToFill" Stretch="UniformToFill"
CornerRadius="8" CornerRadius="8"
ContextFlyout="{TemplateBinding ContextFlyout}" ContextFlyout="{TemplateBinding ContextFlyout}"

8
StabilityMatrix.Avalonia/Controls/SelectableImageCard/SelectableImageButton.cs

@ -11,8 +11,10 @@ public class SelectableImageButton : Button
public static readonly StyledProperty<bool?> IsSelectedProperty = public static readonly StyledProperty<bool?> IsSelectedProperty =
ToggleButton.IsCheckedProperty.AddOwner<SelectableImageButton>(); ToggleButton.IsCheckedProperty.AddOwner<SelectableImageButton>();
public static readonly StyledProperty<string?> SourceProperty = public static readonly StyledProperty<Uri?> SourceProperty = AvaloniaProperty.Register<
AdvancedImage.SourceProperty.AddOwner<SelectableImageButton>(); SelectableImageButton,
Uri?
>("Source");
public static readonly StyledProperty<double> ImageWidthProperty = AvaloniaProperty.Register< public static readonly StyledProperty<double> ImageWidthProperty = AvaloniaProperty.Register<
SelectableImageButton, SelectableImageButton,
@ -48,7 +50,7 @@ public class SelectableImageButton : Button
set => SetValue(IsSelectedProperty, value); set => SetValue(IsSelectedProperty, value);
} }
public string? Source public Uri? Source
{ {
get => GetValue(SourceProperty); get => GetValue(SourceProperty);
set => SetValue(SourceProperty, value); set => SetValue(SourceProperty, value);

23
StabilityMatrix.Avalonia/DesignData/DesignData.cs

@ -98,6 +98,19 @@ public static class DesignData
}, },
LibraryPath = $"Packages{Path.DirectorySeparatorChar}example-webui", LibraryPath = $"Packages{Path.DirectorySeparatorChar}example-webui",
LastUpdateCheck = DateTimeOffset.Now LastUpdateCheck = DateTimeOffset.Now
},
new()
{
Id = Guid.NewGuid(),
DisplayName = "Running Comfy",
PackageName = "ComfyUI",
Version = new InstalledPackageVersion
{
InstalledBranch = "master",
InstalledCommitSha = "abc12uwu345568972abaedf7g7e679a98879e879f87ga8"
},
LibraryPath = $"Packages{Path.DirectorySeparatorChar}example-webui",
LastUpdateCheck = DateTimeOffset.Now
} }
}, },
ActiveInstalledPackageId = activePackageId ActiveInstalledPackageId = activePackageId
@ -507,6 +520,16 @@ public static class DesignData
} }
) )
}; };
vm.Categories = new ObservableCollectionExtended<PackageOutputCategory>
{
new()
{
Name = "Category 1",
Path = "path1",
SubDirectories = [new PackageOutputCategory { Name = "SubCategory 1", Path = "path3" }]
},
new() { Name = "Category 2", Path = "path2" }
};
return vm; return vm;
} }
} }

3
StabilityMatrix.Avalonia/DesignData/MockInferenceClientManager.cs

@ -41,6 +41,9 @@ public partial class MockInferenceClientManager : ObservableObject, IInferenceCl
public IObservableCollection<ComfyScheduler> Schedulers { get; } = public IObservableCollection<ComfyScheduler> Schedulers { get; } =
new ObservableCollectionExtended<ComfyScheduler>(ComfyScheduler.Defaults); new ObservableCollectionExtended<ComfyScheduler>(ComfyScheduler.Defaults);
public IObservableCollection<ComfyAuxPreprocessor> Preprocessors { get; } =
new ObservableCollectionExtended<ComfyAuxPreprocessor>(ComfyAuxPreprocessor.Defaults);
[ObservableProperty] [ObservableProperty]
[NotifyPropertyChangedFor(nameof(CanUserConnect))] [NotifyPropertyChangedFor(nameof(CanUserConnect))]
private bool isConnected; private bool isConnected;

9
StabilityMatrix.Avalonia/FallbackRamCachedWebImageLoader.cs

@ -103,4 +103,13 @@ public class FallbackRamCachedWebImageLoader : RamCachedWebImageLoader
} }
} }
} }
public void ClearCache()
{
var cache =
this.GetPrivateField<ConcurrentDictionary<string, Task<Bitmap?>>>("_memoryCache")
?? throw new NullReferenceException("Memory cache not found");
cache.Clear();
}
} }

135
StabilityMatrix.Avalonia/Languages/Resources.Designer.cs generated

@ -392,6 +392,15 @@ namespace StabilityMatrix.Avalonia.Languages {
} }
} }
/// <summary>
/// Looks up a localized string similar to Preview Preprocessor.
/// </summary>
public static string Action_PreviewPreprocessor {
get {
return ResourceManager.GetString("Action_PreviewPreprocessor", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to Quit. /// Looks up a localized string similar to Quit.
/// </summary> /// </summary>
@ -671,6 +680,15 @@ namespace StabilityMatrix.Avalonia.Languages {
} }
} }
/// <summary>
/// Looks up a localized string similar to This action cannot be undone..
/// </summary>
public static string Label_ActionCannotBeUndone {
get {
return ResourceManager.GetString("Label_ActionCannotBeUndone", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to Addons. /// Looks up a localized string similar to Addons.
/// </summary> /// </summary>
@ -743,6 +761,15 @@ namespace StabilityMatrix.Avalonia.Languages {
} }
} }
/// <summary>
/// Looks up a localized string similar to Are you sure you want to delete {0} images?.
/// </summary>
public static string Label_AreYouSureDeleteImages {
get {
return ResourceManager.GetString("Label_AreYouSureDeleteImages", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to Augmentation Level. /// Looks up a localized string similar to Augmentation Level.
/// </summary> /// </summary>
@ -851,6 +878,15 @@ namespace StabilityMatrix.Avalonia.Languages {
} }
} }
/// <summary>
/// Looks up a localized string similar to We&apos;re checking some hardware specifications to determine compatibility..
/// </summary>
public static string Label_CheckingHardware {
get {
return ResourceManager.GetString("Label_CheckingHardware", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to Checkpoint Manager. /// Looks up a localized string similar to Checkpoint Manager.
/// </summary> /// </summary>
@ -860,6 +896,15 @@ namespace StabilityMatrix.Avalonia.Languages {
} }
} }
/// <summary>
/// Looks up a localized string similar to Checkpoints.
/// </summary>
public static string Label_Checkpoints {
get {
return ResourceManager.GetString("Label_Checkpoints", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to CivitAI. /// Looks up a localized string similar to CivitAI.
/// </summary> /// </summary>
@ -959,6 +1004,24 @@ namespace StabilityMatrix.Avalonia.Languages {
} }
} }
/// <summary>
/// Looks up a localized string similar to Confirm Exit.
/// </summary>
public static string Label_ConfirmExit {
get {
return ResourceManager.GetString("Label_ConfirmExit", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Are you sure you want to exit? This will also close any currently running packages..
/// </summary>
public static string Label_ConfirmExitDetail {
get {
return ResourceManager.GetString("Label_ConfirmExitDetail", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to Confirm Password. /// Looks up a localized string similar to Confirm Password.
/// </summary> /// </summary>
@ -1004,6 +1067,15 @@ namespace StabilityMatrix.Avalonia.Languages {
} }
} }
/// <summary>
/// Looks up a localized string similar to Console.
/// </summary>
public static string Label_Console {
get {
return ResourceManager.GetString("Label_Console", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to This will move all generated images from the selected packages to the Consolidated directory of the shared outputs folder. This action cannot be undone.. /// Looks up a localized string similar to This will move all generated images from the selected packages to the Consolidated directory of the shared outputs folder. This action cannot be undone..
/// </summary> /// </summary>
@ -1229,6 +1301,15 @@ namespace StabilityMatrix.Avalonia.Languages {
} }
} }
/// <summary>
/// Looks up a localized string similar to Everything looks good!.
/// </summary>
public static string Label_EverythingLooksGood {
get {
return ResourceManager.GetString("Label_EverythingLooksGood", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to You may encounter errors when using a FAT32 or exFAT drive. Select a different drive for a smoother experience.. /// Looks up a localized string similar to You may encounter errors when using a FAT32 or exFAT drive. Select a different drive for a smoother experience..
/// </summary> /// </summary>
@ -1589,6 +1670,15 @@ namespace StabilityMatrix.Avalonia.Languages {
} }
} }
/// <summary>
/// Looks up a localized string similar to Model Browser.
/// </summary>
public static string Label_ModelBrowser {
get {
return ResourceManager.GetString("Label_ModelBrowser", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to Model Description. /// Looks up a localized string similar to Model Description.
/// </summary> /// </summary>
@ -1715,6 +1805,15 @@ namespace StabilityMatrix.Avalonia.Languages {
} }
} }
/// <summary>
/// Looks up a localized string similar to We recommend a GPU with CUDA support for the best experience. You can continue without one, but some packages may not work, and inference may be slower..
/// </summary>
public static string Label_NvidiaGpuRecommended {
get {
return ResourceManager.GetString("Label_NvidiaGpuRecommended", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to 1 image selected. /// Looks up a localized string similar to 1 image selected.
/// </summary> /// </summary>
@ -1778,6 +1877,15 @@ namespace StabilityMatrix.Avalonia.Languages {
} }
} }
/// <summary>
/// Looks up a localized string similar to Packages.
/// </summary>
public static string Label_Packages {
get {
return ResourceManager.GetString("Label_Packages", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to Package Type. /// Looks up a localized string similar to Package Type.
/// </summary> /// </summary>
@ -2246,6 +2354,15 @@ namespace StabilityMatrix.Avalonia.Languages {
} }
} }
/// <summary>
/// Looks up a localized string similar to Auto-Scroll to End.
/// </summary>
public static string Label_ToggleAutoScrolling {
get {
return ResourceManager.GetString("Label_ToggleAutoScrolling", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to Trigger words:. /// Looks up a localized string similar to Trigger words:.
/// </summary> /// </summary>
@ -2390,6 +2507,15 @@ namespace StabilityMatrix.Avalonia.Languages {
} }
} }
/// <summary>
/// Looks up a localized string similar to Web UI.
/// </summary>
public static string Label_WebUi {
get {
return ResourceManager.GetString("Label_WebUi", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to Width. /// Looks up a localized string similar to Width.
/// </summary> /// </summary>
@ -2534,6 +2660,15 @@ namespace StabilityMatrix.Avalonia.Languages {
} }
} }
/// <summary>
/// Looks up a localized string similar to The &apos;Open Web UI&apos; button has moved to the command bar.
/// </summary>
public static string TeachingTip_WebUiButtonMoved {
get {
return ResourceManager.GetString("TeachingTip_WebUiButtonMoved", resourceCulture);
}
}
/// <summary> /// <summary>
/// Looks up a localized string similar to The app will relaunch after updating. /// Looks up a localized string similar to The app will relaunch after updating.
/// </summary> /// </summary>

45
StabilityMatrix.Avalonia/Languages/Resources.resx

@ -975,4 +975,49 @@
<data name="Label_Config" xml:space="preserve"> <data name="Label_Config" xml:space="preserve">
<value>Config</value> <value>Config</value>
</data> </data>
<data name="Action_PreviewPreprocessor" xml:space="preserve">
<value>Preview Preprocessor</value>
</data>
<data name="Label_ToggleAutoScrolling" xml:space="preserve">
<value>Auto-Scroll to End</value>
</data>
<data name="Label_ConfirmExit" xml:space="preserve">
<value>Confirm Exit</value>
</data>
<data name="Label_ConfirmExitDetail" xml:space="preserve">
<value>Are you sure you want to exit? This will also close any currently running packages.</value>
</data>
<data name="Label_Console" xml:space="preserve">
<value>Console</value>
</data>
<data name="Label_WebUi" xml:space="preserve">
<value>Web UI</value>
</data>
<data name="Label_Packages" xml:space="preserve">
<value>Packages</value>
</data>
<data name="Label_ActionCannotBeUndone" xml:space="preserve">
<value>This action cannot be undone.</value>
</data>
<data name="Label_AreYouSureDeleteImages" xml:space="preserve">
<value>Are you sure you want to delete {0} images?</value>
</data>
<data name="Label_CheckingHardware" xml:space="preserve">
<value>We're checking some hardware specifications to determine compatibility.</value>
</data>
<data name="Label_EverythingLooksGood" xml:space="preserve">
<value>Everything looks good!</value>
</data>
<data name="Label_NvidiaGpuRecommended" xml:space="preserve">
<value>We recommend a GPU with CUDA support for the best experience. You can continue without one, but some packages may not work, and inference may be slower.</value>
</data>
<data name="Label_Checkpoints" xml:space="preserve">
<value>Checkpoints</value>
</data>
<data name="Label_ModelBrowser" xml:space="preserve">
<value>Model Browser</value>
</data>
<data name="TeachingTip_WebUiButtonMoved" xml:space="preserve">
<value>The 'Open Web UI' button has moved to the command bar</value>
</data>
</root> </root>

5
StabilityMatrix.Avalonia/Models/PackageOutputCategory.cs

@ -1,7 +1,10 @@
namespace StabilityMatrix.Avalonia.Models; using System.Collections.ObjectModel;
namespace StabilityMatrix.Avalonia.Models;
public class PackageOutputCategory public class PackageOutputCategory
{ {
public ObservableCollection<PackageOutputCategory> SubDirectories { get; set; } = new();
public required string Name { get; set; } public required string Name { get; set; }
public required string Path { get; set; } public required string Path { get; set; }
} }

1
StabilityMatrix.Avalonia/Services/IInferenceClientManager.cs

@ -44,6 +44,7 @@ public interface IInferenceClientManager : IDisposable, INotifyPropertyChanged,
IObservableCollection<ComfySampler> Samplers { get; } IObservableCollection<ComfySampler> Samplers { get; }
IObservableCollection<ComfyUpscaler> Upscalers { get; } IObservableCollection<ComfyUpscaler> Upscalers { get; }
IObservableCollection<ComfyScheduler> Schedulers { get; } IObservableCollection<ComfyScheduler> Schedulers { get; }
IObservableCollection<ComfyAuxPreprocessor> Preprocessors { get; }
Task CopyImageToInputAsync(FilePath imageFile, CancellationToken cancellationToken = default); Task CopyImageToInputAsync(FilePath imageFile, CancellationToken cancellationToken = default);

20
StabilityMatrix.Avalonia/Services/InferenceClientManager.cs

@ -14,6 +14,7 @@ using StabilityMatrix.Avalonia.Models;
using StabilityMatrix.Avalonia.Models.TagCompletion; using StabilityMatrix.Avalonia.Models.TagCompletion;
using StabilityMatrix.Core.Api; using StabilityMatrix.Core.Api;
using StabilityMatrix.Core.Attributes; using StabilityMatrix.Core.Attributes;
using StabilityMatrix.Core.Extensions;
using StabilityMatrix.Core.Helper; using StabilityMatrix.Core.Helper;
using StabilityMatrix.Core.Inference; using StabilityMatrix.Core.Inference;
using StabilityMatrix.Core.Models; using StabilityMatrix.Core.Models;
@ -101,6 +102,11 @@ public partial class InferenceClientManager : ObservableObject, IInferenceClient
public IObservableCollection<ComfyScheduler> Schedulers { get; } = public IObservableCollection<ComfyScheduler> Schedulers { get; } =
new ObservableCollectionExtended<ComfyScheduler>(); new ObservableCollectionExtended<ComfyScheduler>();
public IObservableCollection<ComfyAuxPreprocessor> Preprocessors { get; } =
new ObservableCollectionExtended<ComfyAuxPreprocessor>();
private readonly SourceCache<ComfyAuxPreprocessor, string> preprocessorsSource = new(p => p.Value);
public InferenceClientManager( public InferenceClientManager(
ILogger<InferenceClientManager> logger, ILogger<InferenceClientManager> logger,
IApiFactory apiFactory, IApiFactory apiFactory,
@ -166,6 +172,8 @@ public partial class InferenceClientManager : ObservableObject, IInferenceClient
schedulersSource.Connect().DeferUntilLoaded().Bind(Schedulers).Subscribe(); schedulersSource.Connect().DeferUntilLoaded().Bind(Schedulers).Subscribe();
preprocessorsSource.Connect().DeferUntilLoaded().Bind(Preprocessors).Subscribe();
settingsManager.RegisterOnLibraryDirSet(_ => settingsManager.RegisterOnLibraryDirSet(_ =>
{ {
Dispatcher.UIThread.Post(ResetSharedProperties, DispatcherPriority.Background); Dispatcher.UIThread.Post(ResetSharedProperties, DispatcherPriority.Background);
@ -270,6 +278,15 @@ public partial class InferenceClientManager : ObservableObject, IInferenceClient
}); });
logger.LogTrace("Loaded scheduler methods: {@Schedulers}", schedulerNames); logger.LogTrace("Loaded scheduler methods: {@Schedulers}", schedulerNames);
} }
// Add preprocessor names from Inference_Core_AIO_Preprocessor node (might not exist if no extension)
if (
await Client.GetOptionalNodeOptionNamesAsync("Inference_Core_AIO_Preprocessor", "preprocessor") is
{ } preprocessorNames
)
{
preprocessorsSource.EditDiff(preprocessorNames.Select(n => new ComfyAuxPreprocessor(n)));
}
} }
/// <summary> /// <summary>
@ -342,6 +359,9 @@ public partial class InferenceClientManager : ObservableObject, IInferenceClient
u => !modelUpscalersSource.Lookup(u.Name).HasValue u => !modelUpscalersSource.Lookup(u.Name).HasValue
); );
downloadableUpscalersSource.EditDiff(remoteUpscalers, ComfyUpscaler.Comparer); downloadableUpscalersSource.EditDiff(remoteUpscalers, ComfyUpscaler.Comparer);
// Default Preprocessors
preprocessorsSource.EditDiff(ComfyAuxPreprocessor.Defaults);
} }
/// <inheritdoc /> /// <inheritdoc />

148
StabilityMatrix.Avalonia/Services/RunningPackageService.cs

@ -0,0 +1,148 @@
using System;
using System.Collections.Immutable;
using System.Linq;
using System.Threading.Tasks;
using Avalonia.Controls.Notifications;
using CommunityToolkit.Mvvm.ComponentModel;
using Microsoft.Extensions.Logging;
using StabilityMatrix.Avalonia.Models;
using StabilityMatrix.Avalonia.ViewModels;
using StabilityMatrix.Core.Attributes;
using StabilityMatrix.Core.Extensions;
using StabilityMatrix.Core.Helper.Factory;
using StabilityMatrix.Core.Models;
using StabilityMatrix.Core.Models.FileInterfaces;
using StabilityMatrix.Core.Models.Packages;
using StabilityMatrix.Core.Python;
using StabilityMatrix.Core.Services;
namespace StabilityMatrix.Avalonia.Services;
[Singleton]
public partial class RunningPackageService(
ILogger<RunningPackageService> logger,
IPackageFactory packageFactory,
INotificationService notificationService,
ISettingsManager settingsManager,
IPyRunner pyRunner
) : ObservableObject
{
// 🤔 what if we put the ConsoleViewModel inside the BasePackage? 🤔
[ObservableProperty]
private ObservableDictionary<Guid, RunningPackageViewModel> runningPackages = [];
public async Task<PackagePair?> StartPackage(InstalledPackage installedPackage, string? command = null)
{
var activeInstallName = installedPackage.PackageName;
var basePackage = string.IsNullOrWhiteSpace(activeInstallName)
? null
: packageFactory.GetNewBasePackage(installedPackage);
if (basePackage == null)
{
logger.LogWarning(
"During launch, package name '{PackageName}' did not match a definition",
activeInstallName
);
notificationService.Show(
new Notification(
"Package name invalid",
"Install package name did not match a definition. Please reinstall and let us know about this issue.",
NotificationType.Error
)
);
return null;
}
// If this is the first launch (LaunchArgs is null),
// load and save a launch options dialog vm
// so that dynamic initial values are saved.
if (installedPackage.LaunchArgs == null)
{
var definitions = basePackage.LaunchOptions;
// Create config cards and save them
var cards = LaunchOptionCard
.FromDefinitions(definitions, Array.Empty<LaunchOption>())
.ToImmutableArray();
var args = cards.SelectMany(c => c.Options).ToList();
logger.LogDebug(
"Setting initial launch args: {Args}",
string.Join(", ", args.Select(o => o.ToArgString()?.ToRepr()))
);
settingsManager.SaveLaunchArgs(installedPackage.Id, args);
}
if (basePackage is not StableSwarm)
{
await pyRunner.Initialize();
}
// Get path from package
var packagePath = new DirectoryPath(settingsManager.LibraryDir, installedPackage.LibraryPath!);
if (basePackage is not StableSwarm)
{
// Unpack sitecustomize.py to venv
await UnpackSiteCustomize(packagePath.JoinDir("venv"));
}
// Clear console and start update processing
var console = new ConsoleViewModel();
console.StartUpdates();
// Update shared folder links (in case library paths changed)
await basePackage.UpdateModelFolders(
packagePath,
installedPackage.PreferredSharedFolderMethod ?? basePackage.RecommendedSharedFolderMethod
);
// Load user launch args from settings and convert to string
var userArgs = installedPackage.LaunchArgs ?? [];
var userArgsString = string.Join(" ", userArgs.Select(opt => opt.ToArgString()));
// Join with extras, if any
userArgsString = string.Join(" ", userArgsString, basePackage.ExtraLaunchArguments);
// Use input command if provided, otherwise use package launch command
command ??= basePackage.LaunchCommand;
await basePackage.RunPackage(packagePath, command, userArgsString, o => console.Post(o));
var runningPackage = new PackagePair(installedPackage, basePackage);
var viewModel = new RunningPackageViewModel(
settingsManager,
notificationService,
this,
runningPackage,
console
);
RunningPackages.Add(runningPackage.InstalledPackage.Id, viewModel);
return runningPackage;
}
public async Task StopPackage(Guid id)
{
if (RunningPackages.TryGetValue(id, out var vm))
{
var runningPackage = vm.RunningPackage;
await runningPackage.BasePackage.WaitForShutdown();
RunningPackages.Remove(id);
}
}
public RunningPackageViewModel? GetRunningPackageViewModel(Guid id) =>
RunningPackages.TryGetValue(id, out var vm) ? vm : null;
private static async Task UnpackSiteCustomize(DirectoryPath venvPath)
{
var sitePackages = venvPath.JoinDir(PyVenvRunner.RelativeSitePackagesPath);
var file = sitePackages.JoinFile("sitecustomize.py");
file.Directory?.Create();
await Assets.PyScriptSiteCustomize.ExtractTo(file, true);
}
}

73
StabilityMatrix.Avalonia/Styles/ButtonStyles.axaml

@ -99,6 +99,43 @@
</Style> </Style>
</Style> </Style>
<!-- Danger -->
<Style Selector="Button.borderless-danger">
<Style Selector="^ /template/ ui|FABorder#Root">
<Setter Property="Background" Value="{DynamicResource ThemeRedColor}" />
</Style>
<Style Selector="^ /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Foreground" Value="{DynamicResource ButtonForeground}" />
</Style>
<Style Selector="^:pointerover">
<Style Selector="^ /template/ ui|FABorder#Root">
<Setter Property="Background" Value="{DynamicResource ThemeDarkRedColor}"/>
</Style>
<Style Selector="^ /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundPointerOver}" />
</Style>
</Style>
<Style Selector="^:pressed">
<Style Selector="^ /template/ ui|FABorder#Root">
<Setter Property="Background" Value="{DynamicResource ThemeDarkDarkRedColor}" />
</Style>
<Style Selector="^ /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundPressed}" />
</Style>
</Style>
<Style Selector="^:disabled">
<Style Selector="^ /template/ ui|FABorder#Root">
<Setter Property="Background" Value="{DynamicResource ButtonBackgroundDisabled}" />
</Style>
<Style Selector="^ /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundDisabled}" />
</Style>
</Style>
</Style>
<!-- Info --> <!-- Info -->
<Style Selector="Button.info"> <Style Selector="Button.info">
<Style Selector="^ /template/ ui|FABorder#Root"> <Style Selector="^ /template/ ui|FABorder#Root">
@ -140,6 +177,42 @@
</Style> </Style>
</Style> </Style>
<Style Selector="Button.borderless-info">
<Style Selector="^ /template/ ui|FABorder#Root">
<Setter Property="Background" Value="{DynamicResource ThemeLightBlueColor}" />
</Style>
<Style Selector="^ /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Foreground" Value="{DynamicResource ButtonForeground}" />
</Style>
<Style Selector="^:pointerover">
<Style Selector="^ /template/ ui|FABorder#Root">
<Setter Property="Background" Value="{DynamicResource ThemeBlueColor}"/>
</Style>
<Style Selector="^ /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundPointerOver}" />
</Style>
</Style>
<Style Selector="^:pressed">
<Style Selector="^ /template/ ui|FABorder#Root">
<Setter Property="Background" Value="{DynamicResource ThemeDarkBlueColor}" />
</Style>
<Style Selector="^ /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundPressed}" />
</Style>
</Style>
<Style Selector="^:disabled">
<Style Selector="^ /template/ ui|FABorder#Root">
<Setter Property="Background" Value="{DynamicResource ButtonBackgroundDisabled}" />
</Style>
<Style Selector="^ /template/ ContentPresenter#PART_ContentPresenter">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundDisabled}" />
</Style>
</Style>
</Style>
<!--Accent Button--> <!--Accent Button-->
<Style Selector="Button.accent"> <Style Selector="Button.accent">
<Style Selector="^ /template/ ui|FABorder#Root"> <Style Selector="^ /template/ ui|FABorder#Root">

403
StabilityMatrix.Avalonia/Styles/CommandBarButtonStyles.axaml

@ -0,0 +1,403 @@
<Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ui="clr-namespace:FluentAvalonia.UI.Controls;assembly=FluentAvalonia">
<Design.PreviewWith>
<Border Padding="20">
<ui:CommandBar
Margin="8"
VerticalAlignment="Center"
VerticalContentAlignment="Center"
HorizontalAlignment="Left"
HorizontalContentAlignment="Left"
DefaultLabelPosition="Right">
<ui:CommandBar.PrimaryCommands>
<ui:CommandBarButton Classes="success" Label="Success Button" Margin="8"
HorizontalAlignment="Center" />
<ui:CommandBarButton Classes="accent" Label="FA Accent Button" Margin="8"
HorizontalAlignment="Center" />
<ui:CommandBarButton Classes="systemaccent" Label="System Accent Button" Margin="8"
HorizontalAlignment="Center" />
<ui:CommandBarButton Classes="danger" Label="Danger Button" Margin="8" HorizontalAlignment="Center" />
<ui:CommandBarButton Classes="info" Label="Info Button" Margin="8" HorizontalAlignment="Center" />
<ui:CommandBarButton Classes="transparent-info" Label="Semi-Transparent Info Button" Margin="8"
HorizontalAlignment="Center" />
<ui:CommandBarButton Classes="transparent" Label="Transparent Button" Margin="8"
HorizontalAlignment="Center" />
<ui:CommandBarButton Classes="transparent-full" Label="Transparent Button" Margin="8"
HorizontalAlignment="Center" />
<ui:CommandBarButton Label="Disabled Button" Margin="8" IsEnabled="False"
HorizontalAlignment="Center" />
</ui:CommandBar.PrimaryCommands>
</ui:CommandBar>
</Border>
</Design.PreviewWith>
<!-- Success -->
<Style Selector="ui|CommandBarButton.success">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ThemeGreenColor}" />
<Setter Property="BorderBrush" Value="{DynamicResource ThemeGreenColor}" />
</Style>
<Style Selector="^ /template/ TextBlock#TextLabel">
<Setter Property="Foreground" Value="{DynamicResource ButtonForeground}" />
</Style>
<Style Selector="^:pointerover">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ThemeDarkGreenColor}"/>
<Setter Property="BorderBrush" Value="{DynamicResource ThemeDarkGreenColor}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="Green" />
</Style>
</Style>
<Style Selector="^:pressed">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ThemeDarkDarkGreenColor}" />
<Setter Property="BorderBrush" Value="{DynamicResource ThemeDarkDarkGreenColor}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundPressed}" />
</Style>
</Style>
<Style Selector="^:disabled">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ButtonBackgroundDisabled}" />
<Setter Property="BorderBrush" Value="{DynamicResource ButtonBorderBrushDisabled}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundDisabled}" />
</Style>
</Style>
</Style>
<!-- Danger -->
<Style Selector="ui|CommandBarButton.danger">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ThemeRedColor}" />
<Setter Property="BorderBrush" Value="{DynamicResource ThemeRedColor}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForeground}" />
</Style>
<Style Selector="^:pointerover">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ThemeDarkRedColor}"/>
<Setter Property="BorderBrush" Value="{DynamicResource ThemeDarkRedColor}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundPointerOver}" />
</Style>
</Style>
<Style Selector="^:pressed">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ThemeDarkDarkRedColor}" />
<Setter Property="BorderBrush" Value="{DynamicResource ThemeDarkDarkRedColor}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundPressed}" />
</Style>
</Style>
<Style Selector="^:disabled">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ButtonBackgroundDisabled}" />
<Setter Property="BorderBrush" Value="{DynamicResource ButtonBorderBrushDisabled}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundDisabled}" />
</Style>
</Style>
</Style>
<!-- Info -->
<Style Selector="ui|CommandBarButton.info">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ThemeLightBlueColor}" />
<Setter Property="BorderBrush" Value="{DynamicResource ThemeLightBlueColor}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForeground}" />
</Style>
<Style Selector="^:pointerover">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ThemeBlueColor}"/>
<Setter Property="BorderBrush" Value="{DynamicResource ThemeBlueColor}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundPointerOver}" />
</Style>
</Style>
<Style Selector="^:pressed">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ThemeDarkBlueColor}" />
<Setter Property="BorderBrush" Value="{DynamicResource ThemeDarkBlueColor}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundPressed}" />
</Style>
</Style>
<Style Selector="^:disabled">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ButtonBackgroundDisabled}" />
<Setter Property="BorderBrush" Value="{DynamicResource ButtonBorderBrushDisabled}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundDisabled}" />
</Style>
</Style>
</Style>
<!--Accent Button-->
<Style Selector="ui|CommandBarButton.accent">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource AccentButtonBackground}" />
<Setter Property="BorderBrush" Value="{DynamicResource AccentButtonBorderBrush}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource AccentButtonForeground}" />
</Style>
<Style Selector="^:pointerover">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource AccentButtonBackgroundPointerOver}" />
<Setter Property="BorderBrush" Value="{DynamicResource AccentButtonBorderBrushPointerOver}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource AccentButtonForegroundPointerOver}" />
</Style>
</Style>
<Style Selector="^:pressed">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource AccentButtonBackgroundPressed}" />
<Setter Property="BorderBrush" Value="{DynamicResource AccentButtonBorderBrushPressed}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource AccentButtonForegroundPressed}" />
</Style>
</Style>
<Style Selector="^:disabled">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource AccentButtonBackgroundDisabled}" />
<Setter Property="BorderBrush" Value="{DynamicResource AccentButtonBorderBrushDisabled}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource AccentButtonForegroundDisabled}" />
</Style>
</Style>
</Style>
<!-- SystemAccent -->
<Style Selector="ui|CommandBarButton.systemaccent">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource SystemAccentColor}" />
<Setter Property="BorderBrush" Value="{DynamicResource SystemAccentColor}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForeground}" />
</Style>
<Style Selector="^:pointerover">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource SystemAccentColorDark1}"/>
<Setter Property="BorderBrush" Value="{DynamicResource SystemAccentColorDark1}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundPointerOver}" />
</Style>
</Style>
<Style Selector="^:pressed">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource SystemAccentColorDark2}" />
<Setter Property="BorderBrush" Value="{DynamicResource SystemAccentColorDark2}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundPressed}" />
</Style>
</Style>
<Style Selector="^:disabled">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ButtonBackgroundDisabled}" />
<Setter Property="BorderBrush" Value="{DynamicResource ButtonBorderBrushDisabled}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundDisabled}" />
</Style>
</Style>
</Style>
<!-- Transparent -->
<Style Selector="ui|CommandBarButton.transparent">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource SystemControlTransparentBrush}" />
<Setter Property="BorderBrush" Value="{DynamicResource ButtonBorderBrush}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForeground}" />
</Style>
<Style Selector="^:pointerover">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ButtonBackgroundDisabled}"/>
<Setter Property="BorderBrush" Value="{DynamicResource ButtonBackgroundDisabled}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundPointerOver}" />
</Style>
</Style>
<Style Selector="^:pressed">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ButtonBackgroundPressed}" />
<Setter Property="BorderBrush" Value="{DynamicResource ButtonBackgroundPressed}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundPressed}" />
</Style>
</Style>
<Style Selector="^:disabled">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ButtonBackgroundDisabled}" />
<Setter Property="BorderBrush" Value="{DynamicResource ButtonBorderBrushDisabled}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundDisabled}" />
</Style>
</Style>
</Style>
<!-- Semi-Transparent Info -->
<Style Selector="ui|CommandBarButton.transparent-info">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ThemeLightBlueColorTransparent}" />
<Setter Property="BorderBrush" Value="{DynamicResource ThemeLightBlueColorTransparent}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForeground}" />
</Style>
<Style Selector="^:pointerover">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ThemeBlueColorTransparent}"/>
<Setter Property="BorderBrush" Value="{DynamicResource ThemeBlueColorTransparent}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundPointerOver}" />
</Style>
</Style>
<Style Selector="^:pressed">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ThemeDarkBlueColorTransparent}" />
<Setter Property="BorderBrush" Value="{DynamicResource ThemeDarkBlueColorTransparent}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundPressed}" />
</Style>
</Style>
<Style Selector="^:disabled">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ButtonBackgroundDisabled}" />
<Setter Property="BorderBrush" Value="{DynamicResource ButtonBorderBrushDisabled}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundDisabled}" />
</Style>
</Style>
</Style>
<!-- Transparent red -->
<Style Selector="ui|CommandBarButton.transparent-red">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource SystemControlTransparentBrush}" />
<Setter Property="BorderBrush" Value="{DynamicResource ButtonBorderBrush}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForeground}" />
</Style>
<Style Selector="^:pointerover">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ThemeCoralRedColor}"/>
<Setter Property="BorderBrush" Value="{DynamicResource ThemeCoralRedColor}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundPointerOver}" />
</Style>
</Style>
<Style Selector="^:pressed">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ThemeDarkCoralRedColor}"/>
<Setter Property="BorderBrush" Value="{DynamicResource ThemeDarkCoralRedColor}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundPressed}" />
</Style>
</Style>
<Style Selector="^:disabled">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ButtonBackgroundDisabled}" />
<Setter Property="BorderBrush" Value="{DynamicResource ButtonBorderBrushDisabled}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundDisabled}" />
</Style>
</Style>
</Style>
<!-- Full Transparent -->
<Style Selector="ui|CommandBarButton.transparent-full">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource SystemControlTransparentBrush}" />
<Setter Property="BorderBrush" Value="{DynamicResource SystemControlTransparentBrush}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForeground}" />
</Style>
<Style Selector="^:pointerover">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ButtonBackgroundDisabled}"/>
<Setter Property="BorderBrush" Value="{DynamicResource ButtonBackgroundDisabled}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundPointerOver}" />
</Style>
</Style>
<Style Selector="^:pressed">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource ButtonBackgroundPressed}" />
<Setter Property="BorderBrush" Value="{DynamicResource ButtonBackgroundPressed}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundPressed}" />
</Style>
</Style>
<Style Selector="^:disabled">
<Style Selector="^ /template/ Border#AppBarButtonInnerBorder">
<Setter Property="Background" Value="{DynamicResource SystemControlTransparentBrush}" />
<Setter Property="BorderBrush" Value="{DynamicResource SystemControlTransparentBrush}" />
</Style>
<Style Selector="^">
<Setter Property="Foreground" Value="{DynamicResource ButtonForegroundDisabled}" />
</Style>
</Style>
</Style>
</Styles>

1
StabilityMatrix.Avalonia/Styles/ThemeColors.axaml

@ -21,6 +21,7 @@
<Color x:Key="ThemeCyanColor">#00BCD4</Color> <Color x:Key="ThemeCyanColor">#00BCD4</Color>
<Color x:Key="ThemeTealColor">#009688</Color> <Color x:Key="ThemeTealColor">#009688</Color>
<Color x:Key="ThemeDarkDarkGreenColor">#2C582C</Color> <Color x:Key="ThemeDarkDarkGreenColor">#2C582C</Color>
<SolidColorBrush x:Key="ThemeDarkDarkGreenColorBrush">#2C582C</SolidColorBrush>
<Color x:Key="ThemeDarkGreenColor">#3A783C</Color> <Color x:Key="ThemeDarkGreenColor">#3A783C</Color>
<Color x:Key="ThemeGreenColor">#4BA04F</Color> <Color x:Key="ThemeGreenColor">#4BA04F</Color>
<Color x:Key="ThemeGreenColorTransparent">#AA4BA04F</Color> <Color x:Key="ThemeGreenColorTransparent">#AA4BA04F</Color>

105
StabilityMatrix.Avalonia/ViewModels/Base/InferenceGenerationViewModelBase.cs

@ -17,9 +17,9 @@ using CommunityToolkit.Mvvm.Input;
using ExifLibrary; using ExifLibrary;
using FluentAvalonia.UI.Controls; using FluentAvalonia.UI.Controls;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Nito.Disposables.Internals;
using NLog; using NLog;
using Refit; using Refit;
using Semver;
using SkiaSharp; using SkiaSharp;
using StabilityMatrix.Avalonia.Extensions; using StabilityMatrix.Avalonia.Extensions;
using StabilityMatrix.Avalonia.Helpers; using StabilityMatrix.Avalonia.Helpers;
@ -59,6 +59,7 @@ public abstract partial class InferenceGenerationViewModelBase
private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private readonly ISettingsManager settingsManager; private readonly ISettingsManager settingsManager;
private readonly RunningPackageService runningPackageService;
private readonly INotificationService notificationService; private readonly INotificationService notificationService;
private readonly ServiceManager<ViewModelBase> vmFactory; private readonly ServiceManager<ViewModelBase> vmFactory;
@ -79,12 +80,14 @@ public abstract partial class InferenceGenerationViewModelBase
ServiceManager<ViewModelBase> vmFactory, ServiceManager<ViewModelBase> vmFactory,
IInferenceClientManager inferenceClientManager, IInferenceClientManager inferenceClientManager,
INotificationService notificationService, INotificationService notificationService,
ISettingsManager settingsManager ISettingsManager settingsManager,
RunningPackageService runningPackageService
) )
: base(notificationService) : base(notificationService)
{ {
this.notificationService = notificationService; this.notificationService = notificationService;
this.settingsManager = settingsManager; this.settingsManager = settingsManager;
this.runningPackageService = runningPackageService;
this.vmFactory = vmFactory; this.vmFactory = vmFactory;
ClientManager = inferenceClientManager; ClientManager = inferenceClientManager;
@ -259,6 +262,30 @@ public abstract partial class InferenceGenerationViewModelBase
} }
} }
public async Task RunCustomGeneration(
InferenceQueueCustomPromptEventArgs args,
CancellationToken cancellationToken = default
)
{
if (ClientManager.Client is not { } client)
{
throw new InvalidOperationException("Client is not connected");
}
var generationArgs = new ImageGenerationEventArgs
{
Client = client,
Nodes = args.Builder.ToNodeDictionary(),
OutputNodeNames = args.Builder.Connections.OutputNodeNames.ToArray(),
Project = InferenceProjectDocument.FromLoadable(this),
FilesToTransfer = args.FilesToTransfer,
Parameters = new GenerationParameters(),
ClearOutputImages = true
};
await RunGeneration(generationArgs, cancellationToken);
}
/// <summary> /// <summary>
/// Runs a generation task /// Runs a generation task
/// </summary> /// </summary>
@ -643,12 +670,10 @@ public abstract partial class InferenceGenerationViewModelBase
{ {
// Get prompt required extensions // Get prompt required extensions
// Just static for now but could do manifest lookup when we support custom workflows // Just static for now but could do manifest lookup when we support custom workflows
var requiredExtensions = nodeDictionary var requiredExtensionSpecifiers = nodeDictionary.RequiredExtensions.ToList();
.ClassTypeRequiredExtensions.Values.SelectMany(x => x)
.ToHashSet();
// Skip if no extensions required // Skip if no extensions required
if (requiredExtensions.Count == 0) if (requiredExtensionSpecifiers.Count == 0)
{ {
return true; return true;
} }
@ -661,20 +686,63 @@ public abstract partial class InferenceGenerationViewModelBase
await ((GitPackageExtensionManager)manager).GetInstalledExtensionsLiteAsync( await ((GitPackageExtensionManager)manager).GetInstalledExtensionsLiteAsync(
localPackagePair.InstalledPackage localPackagePair.InstalledPackage
) )
).ToImmutableArray(); ).ToList();
var localExtensionsByGitUrl = localExtensions
.Where(ext => ext.GitRepositoryUrl is not null)
.ToDictionary(ext => ext.GitRepositoryUrl!, ext => ext);
var missingExtensions = requiredExtensions var requiredExtensionReferences = requiredExtensionSpecifiers
.Except(localExtensions.Select(ext => ext.GitRepositoryUrl).WhereNotNull()) .Select(specifier => specifier.Name)
.ToImmutableArray(); .ToHashSet();
var missingExtensions = new List<ExtensionSpecifier>();
var outOfDateExtensions =
new List<(ExtensionSpecifier Specifier, InstalledPackageExtension Installed)>();
if (missingExtensions.Length == 0) // Check missing extensions and out of date extensions
foreach (var specifier in requiredExtensionSpecifiers)
{
if (!localExtensionsByGitUrl.TryGetValue(specifier.Name, out var localExtension))
{
missingExtensions.Add(specifier);
continue;
}
// Check if constraint is specified
if (specifier.Constraint is not null && specifier.TryGetSemVersionRange(out var semVersionRange))
{
// Get version to compare
localExtension = await manager.GetInstalledExtensionInfoAsync(localExtension);
// Try to parse local tag to semver
if (
localExtension.Version?.Tag is not null
&& SemVersion.TryParse(
localExtension.Version.Tag,
SemVersionStyles.AllowV,
out var localSemVersion
)
)
{
// Check if not satisfied
if (!semVersionRange.Contains(localSemVersion))
{
outOfDateExtensions.Add((specifier, localExtension));
}
}
}
}
if (missingExtensions.Count == 0 && outOfDateExtensions.Count == 0)
{ {
return true; return true;
} }
var dialog = DialogHelper.CreateMarkdownDialog( var dialog = DialogHelper.CreateMarkdownDialog(
$"#### The following extensions are required for this workflow:\n" $"#### The following extensions are required for this workflow:\n"
+ $"{string.Join("\n- ", missingExtensions)}", + $"{string.Join("\n- ", missingExtensions.Select(ext => ext.Name))}"
+ $"{string.Join("\n- ", outOfDateExtensions.Select(pair => $"{pair.Item1.Name} {pair.Specifier.Constraint} {pair.Specifier.Version} (Current Version: {pair.Installed.Version?.Tag})"))}",
"Install Required Extensions?" "Install Required Extensions?"
); );
@ -692,13 +760,13 @@ public abstract partial class InferenceGenerationViewModelBase
var steps = new List<IPackageStep>(); var steps = new List<IPackageStep>();
foreach (var missingExtensionUrl in missingExtensions) foreach (var missingExtension in missingExtensions)
{ {
if (!manifestExtensionsMap.TryGetValue(missingExtensionUrl, out var extension)) if (!manifestExtensionsMap.TryGetValue(missingExtension.Name, out var extension))
{ {
Logger.Warn( Logger.Warn(
"Extension {MissingExtensionUrl} not found in manifests", "Extension {MissingExtensionUrl} not found in manifests",
missingExtensionUrl missingExtension.Name
); );
continue; continue;
} }
@ -722,15 +790,12 @@ public abstract partial class InferenceGenerationViewModelBase
return; return;
// Restart Package // Restart Package
// TODO: This should be handled by some DI package manager service
var launchPage = App.Services.GetRequiredService<LaunchPageViewModel>();
try try
{ {
await Dispatcher.UIThread.InvokeAsync(async () => await Dispatcher.UIThread.InvokeAsync(async () =>
{ {
await launchPage.Stop(); await runningPackageService.StopPackage(localPackagePair.InstalledPackage.Id);
await launchPage.LaunchAsync(); await runningPackageService.StartPackage(localPackagePair.InstalledPackage);
}); });
} }
catch (Exception e) catch (Exception e)

16
StabilityMatrix.Avalonia/ViewModels/Base/InferenceTabViewModelBase.cs

@ -98,11 +98,7 @@ public abstract partial class InferenceTabViewModelBase
protected async Task<ViewState> SaveViewState() protected async Task<ViewState> SaveViewState()
{ {
var eventArgs = new SaveViewStateEventArgs(); var eventArgs = new SaveViewStateEventArgs();
saveViewStateRequestedEventManager?.RaiseEvent( saveViewStateRequestedEventManager?.RaiseEvent(this, eventArgs, nameof(SaveViewStateRequested));
this,
eventArgs,
nameof(SaveViewStateRequested)
);
if (eventArgs.StateTask is not { } stateTask) if (eventArgs.StateTask is not { } stateTask)
{ {
@ -128,7 +124,7 @@ public abstract partial class InferenceTabViewModelBase
// TODO: Dock reset not working, using this hack for now to get a new view // TODO: Dock reset not working, using this hack for now to get a new view
var navService = App.Services.GetRequiredService<INavigationService<MainWindowViewModel>>(); var navService = App.Services.GetRequiredService<INavigationService<MainWindowViewModel>>();
navService.NavigateTo<LaunchPageViewModel>(new SuppressNavigationTransitionInfo()); navService.NavigateTo<NewPackageManagerViewModel>(new SuppressNavigationTransitionInfo());
((IPersistentViewProvider)this).AttachedPersistentView = null; ((IPersistentViewProvider)this).AttachedPersistentView = null;
navService.NavigateTo<InferenceViewModel>(new BetterEntranceNavigationTransition()); navService.NavigateTo<InferenceViewModel>(new BetterEntranceNavigationTransition());
} }
@ -157,9 +153,7 @@ public abstract partial class InferenceTabViewModelBase
if (result == ContentDialogResult.Primary && textFields[0].Text is { } json) if (result == ContentDialogResult.Primary && textFields[0].Text is { } json)
{ {
LoadViewState( LoadViewState(new LoadViewStateEventArgs { State = new ViewState { DockLayout = json } });
new LoadViewStateEventArgs { State = new ViewState { DockLayout = json } }
);
} }
} }
@ -226,9 +220,7 @@ public abstract partial class InferenceTabViewModelBase
if (this is IParametersLoadableState paramsLoadableVm) if (this is IParametersLoadableState paramsLoadableVm)
{ {
Dispatcher.UIThread.Invoke( Dispatcher.UIThread.Invoke(() => paramsLoadableVm.LoadStateFromParameters(parameters));
() => paramsLoadableVm.LoadStateFromParameters(parameters)
);
} }
else else
{ {

3
StabilityMatrix.Avalonia/ViewModels/CheckpointBrowserViewModel.cs

@ -6,6 +6,7 @@ using Avalonia.Controls;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using FluentAvalonia.Core; using FluentAvalonia.Core;
using FluentAvalonia.UI.Controls; using FluentAvalonia.UI.Controls;
using StabilityMatrix.Avalonia.Languages;
using StabilityMatrix.Avalonia.ViewModels.Base; using StabilityMatrix.Avalonia.ViewModels.Base;
using StabilityMatrix.Avalonia.ViewModels.CheckpointBrowser; using StabilityMatrix.Avalonia.ViewModels.CheckpointBrowser;
using StabilityMatrix.Avalonia.Views; using StabilityMatrix.Avalonia.Views;
@ -20,7 +21,7 @@ namespace StabilityMatrix.Avalonia.ViewModels;
[Singleton] [Singleton]
public partial class CheckpointBrowserViewModel : PageViewModelBase public partial class CheckpointBrowserViewModel : PageViewModelBase
{ {
public override string Title => "Model Browser"; public override string Title => Resources.Label_ModelBrowser;
public override IconSource IconSource => public override IconSource IconSource =>
new SymbolIconSource { Symbol = Symbol.BrainCircuit, IsFilled = true }; new SymbolIconSource { Symbol = Symbol.BrainCircuit, IsFilled = true };

3
StabilityMatrix.Avalonia/ViewModels/CheckpointsPageViewModel.cs

@ -25,6 +25,7 @@ using StabilityMatrix.Core.Models.Api;
using StabilityMatrix.Core.Models.Progress; using StabilityMatrix.Core.Models.Progress;
using StabilityMatrix.Core.Processes; using StabilityMatrix.Core.Processes;
using StabilityMatrix.Core.Services; using StabilityMatrix.Core.Services;
using Resources = StabilityMatrix.Avalonia.Languages.Resources;
using Symbol = FluentIcons.Common.Symbol; using Symbol = FluentIcons.Common.Symbol;
using SymbolIconSource = FluentIcons.Avalonia.Fluent.SymbolIconSource; using SymbolIconSource = FluentIcons.Avalonia.Fluent.SymbolIconSource;
using TeachingTip = StabilityMatrix.Core.Models.Settings.TeachingTip; using TeachingTip = StabilityMatrix.Core.Models.Settings.TeachingTip;
@ -43,7 +44,7 @@ public partial class CheckpointsPageViewModel : PageViewModelBase
private readonly INotificationService notificationService; private readonly INotificationService notificationService;
private readonly IMetadataImportService metadataImportService; private readonly IMetadataImportService metadataImportService;
public override string Title => "Checkpoints"; public override string Title => Resources.Label_Checkpoints;
public override IconSource IconSource => public override IconSource IconSource =>
new SymbolIconSource { Symbol = Symbol.Notebook, IsFilled = true }; new SymbolIconSource { Symbol = Symbol.Notebook, IsFilled = true };

15
StabilityMatrix.Avalonia/ViewModels/Dialogs/InferenceConnectionHelpViewModel.cs

@ -2,6 +2,7 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.Immutable; using System.Collections.Immutable;
using System.Linq; using System.Linq;
using System.Threading.Tasks;
using Avalonia.Threading; using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
@ -30,6 +31,7 @@ public partial class InferenceConnectionHelpViewModel : ContentDialogViewModelBa
private readonly ISettingsManager settingsManager; private readonly ISettingsManager settingsManager;
private readonly INavigationService<MainWindowViewModel> navigationService; private readonly INavigationService<MainWindowViewModel> navigationService;
private readonly IPackageFactory packageFactory; private readonly IPackageFactory packageFactory;
private readonly RunningPackageService runningPackageService;
[ObservableProperty] [ObservableProperty]
private string title = "Hello"; private string title = "Hello";
@ -58,12 +60,14 @@ public partial class InferenceConnectionHelpViewModel : ContentDialogViewModelBa
public InferenceConnectionHelpViewModel( public InferenceConnectionHelpViewModel(
ISettingsManager settingsManager, ISettingsManager settingsManager,
INavigationService<MainWindowViewModel> navigationService, INavigationService<MainWindowViewModel> navigationService,
IPackageFactory packageFactory IPackageFactory packageFactory,
RunningPackageService runningPackageService
) )
{ {
this.settingsManager = settingsManager; this.settingsManager = settingsManager;
this.navigationService = navigationService; this.navigationService = navigationService;
this.packageFactory = packageFactory; this.packageFactory = packageFactory;
this.runningPackageService = runningPackageService;
// Get comfy type installed packages // Get comfy type installed packages
var comfyPackages = this.settingsManager.Settings.InstalledPackages.Where( var comfyPackages = this.settingsManager.Settings.InstalledPackages.Where(
@ -122,14 +126,11 @@ public partial class InferenceConnectionHelpViewModel : ContentDialogViewModelBa
/// Request launch of the selected package /// Request launch of the selected package
/// </summary> /// </summary>
[RelayCommand] [RelayCommand]
private void LaunchSelectedPackage() private async Task LaunchSelectedPackage()
{ {
if (SelectedPackage?.Id is { } id) if (SelectedPackage is not null)
{ {
Dispatcher.UIThread.Post(() => await runningPackageService.StartPackage(SelectedPackage);
{
EventManager.Instance.OnPackageLaunchRequested(id);
});
} }
} }

9
StabilityMatrix.Avalonia/ViewModels/FirstLaunchSetupViewModel.cs

@ -3,6 +3,7 @@ using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsyncAwaitBestPractices; using AsyncAwaitBestPractices;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using StabilityMatrix.Avalonia.Languages;
using StabilityMatrix.Avalonia.Styles; using StabilityMatrix.Avalonia.Styles;
using StabilityMatrix.Avalonia.ViewModels.Base; using StabilityMatrix.Avalonia.ViewModels.Base;
using StabilityMatrix.Avalonia.Views; using StabilityMatrix.Avalonia.Views;
@ -27,11 +28,9 @@ public partial class FirstLaunchSetupViewModel : ViewModelBase
private RefreshBadgeViewModel checkHardwareBadge = private RefreshBadgeViewModel checkHardwareBadge =
new() new()
{ {
WorkingToolTipText = "We're checking some hardware specifications to determine compatibility.", WorkingToolTipText = Resources.Label_CheckingHardware,
SuccessToolTipText = "Everything looks good!", SuccessToolTipText = Resources.Label_EverythingLooksGood,
FailToolTipText = FailToolTipText = Resources.Label_NvidiaGpuRecommended,
"We recommend a GPU with CUDA support for the best experience. "
+ "You can continue without one, but some packages may not work, and inference may be slower.",
FailColorBrush = ThemeColors.ThemeYellow, FailColorBrush = ThemeColors.ThemeYellow,
}; };

84
StabilityMatrix.Avalonia/ViewModels/Inference/ControlNetCardViewModel.cs

@ -1,19 +1,20 @@
using System; using System;
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks; using System.Threading.Tasks;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using DynamicData.Binding;
using FluentAvalonia.UI.Controls; using FluentAvalonia.UI.Controls;
using StabilityMatrix.Avalonia.Controls; using StabilityMatrix.Avalonia.Controls;
using StabilityMatrix.Avalonia.Services; using StabilityMatrix.Avalonia.Services;
using StabilityMatrix.Avalonia.ViewModels.Base; using StabilityMatrix.Avalonia.ViewModels.Base;
using StabilityMatrix.Avalonia.ViewModels.Dialogs; using StabilityMatrix.Avalonia.ViewModels.Dialogs;
using StabilityMatrix.Core.Attributes; using StabilityMatrix.Core.Attributes;
using StabilityMatrix.Core.Extensions;
using StabilityMatrix.Core.Helper; using StabilityMatrix.Core.Helper;
using StabilityMatrix.Core.Models; using StabilityMatrix.Core.Models;
using StabilityMatrix.Core.Models.FileInterfaces; using StabilityMatrix.Core.Models.Api.Comfy;
using StabilityMatrix.Core.Services; using StabilityMatrix.Core.Models.Api.Comfy.Nodes;
namespace StabilityMatrix.Avalonia.ViewModels.Inference; namespace StabilityMatrix.Avalonia.ViewModels.Inference;
@ -32,7 +33,17 @@ public partial class ControlNetCardViewModel : LoadableViewModelBase
[ObservableProperty] [ObservableProperty]
[Required] [Required]
private HybridModelFile? selectedPreprocessor; private ComfyAuxPreprocessor? selectedPreprocessor;
[ObservableProperty]
[Required]
[Range(0, 2048)]
private int width;
[ObservableProperty]
[Required]
[Range(0, 2048)]
private int height;
[ObservableProperty] [ObservableProperty]
[Required] [Required]
@ -62,6 +73,18 @@ public partial class ControlNetCardViewModel : LoadableViewModelBase
ClientManager = clientManager; ClientManager = clientManager;
SelectImageCardViewModel = vmFactory.Get<SelectImageCardViewModel>(); SelectImageCardViewModel = vmFactory.Get<SelectImageCardViewModel>();
// Update our width and height when the image changes
SelectImageCardViewModel
.WhenPropertyChanged(card => card.CurrentBitmapSize)
.Subscribe(propertyValue =>
{
if (!propertyValue.Value.IsEmpty)
{
Width = propertyValue.Value.Width;
Height = propertyValue.Value.Height;
}
});
} }
[RelayCommand] [RelayCommand]
@ -79,4 +102,57 @@ public partial class ControlNetCardViewModel : LoadableViewModelBase
confirmDialog.StartDownload(); confirmDialog.StartDownload();
} }
} }
[RelayCommand]
private async Task PreviewPreprocessor(ComfyAuxPreprocessor? preprocessor)
{
if (
preprocessor is null
|| SelectImageCardViewModel.ImageSource is not { } imageSource
|| SelectImageCardViewModel.IsImageFileNotFound
)
return;
var args = new InferenceQueueCustomPromptEventArgs();
var images = SelectImageCardViewModel.GetInputImages();
await ClientManager.UploadInputImageAsync(imageSource);
var image = args.Nodes.AddTypedNode(
new ComfyNodeBuilder.LoadImage
{
Name = args.Nodes.GetUniqueName("Preprocessor_LoadImage"),
Image =
SelectImageCardViewModel.ImageSource?.GetHashGuidFileNameCached("Inference")
?? throw new ValidationException("No ImageSource")
}
).Output1;
var aioPreprocessor = args.Nodes.AddTypedNode(
new ComfyNodeBuilder.AIOPreprocessor
{
Name = args.Nodes.GetUniqueName("Preprocessor"),
Image = image,
Preprocessor = preprocessor.ToString(),
Resolution = Width is <= 2048 and > 0 ? Width : 512
}
);
args.Builder.Connections.OutputNodes.Add(
args.Nodes.AddTypedNode(
new ComfyNodeBuilder.PreviewImage
{
Name = args.Nodes.GetUniqueName("Preprocessor_OutputImage"),
Images = aioPreprocessor.Output
}
)
);
// Queue
Dispatcher.UIThread.Post(() => EventManager.Instance.OnInferenceQueueCustomPrompt(args));
// We don't know when it's done so wait a bit?
await Task.Delay(1000);
}
} }

20
StabilityMatrix.Avalonia/ViewModels/Inference/InferenceImageToImageViewModel.cs

@ -27,9 +27,17 @@ public class InferenceImageToImageViewModel : InferenceTextToImageViewModel
IInferenceClientManager inferenceClientManager, IInferenceClientManager inferenceClientManager,
INotificationService notificationService, INotificationService notificationService,
ISettingsManager settingsManager, ISettingsManager settingsManager,
IModelIndexService modelIndexService IModelIndexService modelIndexService,
RunningPackageService runningPackageService
)
: base(
notificationService,
inferenceClientManager,
settingsManager,
vmFactory,
modelIndexService,
runningPackageService
) )
: base(notificationService, inferenceClientManager, settingsManager, vmFactory, modelIndexService)
{ {
SelectImageCardViewModel = vmFactory.Get<SelectImageCardViewModel>(); SelectImageCardViewModel = vmFactory.Get<SelectImageCardViewModel>();
@ -77,12 +85,12 @@ public class InferenceImageToImageViewModel : InferenceTextToImageViewModel
var mainImages = SelectImageCardViewModel.GetInputImages(); var mainImages = SelectImageCardViewModel.GetInputImages();
var samplerImages = SamplerCardViewModel var samplerImages = SamplerCardViewModel
.ModulesCardViewModel .ModulesCardViewModel.Cards.OfType<IInputImageProvider>()
.Cards
.OfType<IInputImageProvider>()
.SelectMany(m => m.GetInputImages()); .SelectMany(m => m.GetInputImages());
var moduleImages = ModulesCardViewModel.Cards.OfType<IInputImageProvider>().SelectMany(m => m.GetInputImages()); var moduleImages = ModulesCardViewModel
.Cards.OfType<IInputImageProvider>()
.SelectMany(m => m.GetInputImages());
return mainImages.Concat(samplerImages).Concat(moduleImages); return mainImages.Concat(samplerImages).Concat(moduleImages);
} }

5
StabilityMatrix.Avalonia/ViewModels/Inference/InferenceImageToVideoViewModel.cs

@ -65,9 +65,10 @@ public partial class InferenceImageToVideoViewModel
IInferenceClientManager inferenceClientManager, IInferenceClientManager inferenceClientManager,
ISettingsManager settingsManager, ISettingsManager settingsManager,
ServiceManager<ViewModelBase> vmFactory, ServiceManager<ViewModelBase> vmFactory,
IModelIndexService modelIndexService IModelIndexService modelIndexService,
RunningPackageService runningPackageService
) )
: base(vmFactory, inferenceClientManager, notificationService, settingsManager) : base(vmFactory, inferenceClientManager, notificationService, settingsManager, runningPackageService)
{ {
this.notificationService = notificationService; this.notificationService = notificationService;
this.modelIndexService = modelIndexService; this.modelIndexService = modelIndexService;

15
StabilityMatrix.Avalonia/ViewModels/Inference/InferenceImageUpscaleViewModel.cs

@ -59,9 +59,10 @@ public class InferenceImageUpscaleViewModel : InferenceGenerationViewModelBase
INotificationService notificationService, INotificationService notificationService,
IInferenceClientManager inferenceClientManager, IInferenceClientManager inferenceClientManager,
ISettingsManager settingsManager, ISettingsManager settingsManager,
ServiceManager<ViewModelBase> vmFactory ServiceManager<ViewModelBase> vmFactory,
RunningPackageService runningPackageService
) )
: base(vmFactory, inferenceClientManager, notificationService, settingsManager) : base(vmFactory, inferenceClientManager, notificationService, settingsManager, runningPackageService)
{ {
this.notificationService = notificationService; this.notificationService = notificationService;
@ -142,7 +143,10 @@ public class InferenceImageUpscaleViewModel : InferenceGenerationViewModelBase
} }
/// <inheritdoc /> /// <inheritdoc />
protected override async Task GenerateImageImpl(GenerateOverrides overrides, CancellationToken cancellationToken) protected override async Task GenerateImageImpl(
GenerateOverrides overrides,
CancellationToken cancellationToken
)
{ {
if (!ClientManager.IsConnected) if (!ClientManager.IsConnected)
{ {
@ -169,7 +173,10 @@ public class InferenceImageUpscaleViewModel : InferenceGenerationViewModelBase
Client = ClientManager.Client, Client = ClientManager.Client,
Nodes = buildPromptArgs.Builder.ToNodeDictionary(), Nodes = buildPromptArgs.Builder.ToNodeDictionary(),
OutputNodeNames = buildPromptArgs.Builder.Connections.OutputNodeNames.ToArray(), OutputNodeNames = buildPromptArgs.Builder.Connections.OutputNodeNames.ToArray(),
Parameters = new GenerationParameters { ModelName = UpscalerCardViewModel.SelectedUpscaler?.Name, }, Parameters = new GenerationParameters
{
ModelName = UpscalerCardViewModel.SelectedUpscaler?.Name,
},
Project = InferenceProjectDocument.FromLoadable(this) Project = InferenceProjectDocument.FromLoadable(this)
}; };

5
StabilityMatrix.Avalonia/ViewModels/Inference/InferenceTextToImageViewModel.cs

@ -59,9 +59,10 @@ public class InferenceTextToImageViewModel : InferenceGenerationViewModelBase, I
IInferenceClientManager inferenceClientManager, IInferenceClientManager inferenceClientManager,
ISettingsManager settingsManager, ISettingsManager settingsManager,
ServiceManager<ViewModelBase> vmFactory, ServiceManager<ViewModelBase> vmFactory,
IModelIndexService modelIndexService IModelIndexService modelIndexService,
RunningPackageService runningPackageService
) )
: base(vmFactory, inferenceClientManager, notificationService, settingsManager) : base(vmFactory, inferenceClientManager, notificationService, settingsManager, runningPackageService)
{ {
this.notificationService = notificationService; this.notificationService = notificationService;
this.modelIndexService = modelIndexService; this.modelIndexService = modelIndexService;

23
StabilityMatrix.Avalonia/ViewModels/Inference/Modules/ControlNetModule.cs

@ -6,6 +6,7 @@ using StabilityMatrix.Avalonia.Models.Inference;
using StabilityMatrix.Avalonia.Services; using StabilityMatrix.Avalonia.Services;
using StabilityMatrix.Avalonia.ViewModels.Base; using StabilityMatrix.Avalonia.ViewModels.Base;
using StabilityMatrix.Core.Attributes; using StabilityMatrix.Core.Attributes;
using StabilityMatrix.Core.Models.Api.Comfy;
using StabilityMatrix.Core.Models.Api.Comfy.Nodes; using StabilityMatrix.Core.Models.Api.Comfy.Nodes;
namespace StabilityMatrix.Avalonia.ViewModels.Inference.Modules; namespace StabilityMatrix.Avalonia.ViewModels.Inference.Modules;
@ -39,7 +40,7 @@ public class ControlNetModule : ModuleBase
{ {
var card = GetCard<ControlNetCardViewModel>(); var card = GetCard<ControlNetCardViewModel>();
var imageLoad = e.Nodes.AddTypedNode( var image = e.Nodes.AddTypedNode(
new ComfyNodeBuilder.LoadImage new ComfyNodeBuilder.LoadImage
{ {
Name = e.Nodes.GetUniqueName("ControlNet_LoadImage"), Name = e.Nodes.GetUniqueName("ControlNet_LoadImage"),
@ -47,8 +48,24 @@ public class ControlNetModule : ModuleBase
card.SelectImageCardViewModel.ImageSource?.GetHashGuidFileNameCached("Inference") card.SelectImageCardViewModel.ImageSource?.GetHashGuidFileNameCached("Inference")
?? throw new ValidationException("No ImageSource") ?? throw new ValidationException("No ImageSource")
} }
).Output1;
if (card.SelectedPreprocessor is { } preprocessor && preprocessor != ComfyAuxPreprocessor.None)
{
var aioPreprocessor = e.Nodes.AddTypedNode(
new ComfyNodeBuilder.AIOPreprocessor
{
Name = e.Nodes.GetUniqueName("ControlNet_Preprocessor"),
Image = image,
Preprocessor = preprocessor.ToString(),
// Use width if valid, else default of 512
Resolution = card.Width is <= 2048 and > 0 ? card.Width : 512
}
); );
image = aioPreprocessor.Output;
}
var controlNetLoader = e.Nodes.AddTypedNode( var controlNetLoader = e.Nodes.AddTypedNode(
new ComfyNodeBuilder.ControlNetLoader new ComfyNodeBuilder.ControlNetLoader
{ {
@ -62,7 +79,7 @@ public class ControlNetModule : ModuleBase
new ComfyNodeBuilder.ControlNetApplyAdvanced new ComfyNodeBuilder.ControlNetApplyAdvanced
{ {
Name = e.Nodes.GetUniqueName("ControlNetApply"), Name = e.Nodes.GetUniqueName("ControlNetApply"),
Image = imageLoad.Output1, Image = image,
ControlNet = controlNetLoader.Output, ControlNet = controlNetLoader.Output,
Positive = e.Temp.Conditioning?.Positive ?? throw new ArgumentException("No Conditioning"), Positive = e.Temp.Conditioning?.Positive ?? throw new ArgumentException("No Conditioning"),
Negative = e.Temp.Conditioning?.Negative ?? throw new ArgumentException("No Conditioning"), Negative = e.Temp.Conditioning?.Negative ?? throw new ArgumentException("No Conditioning"),
@ -81,7 +98,7 @@ public class ControlNetModule : ModuleBase
new ComfyNodeBuilder.ControlNetApplyAdvanced new ComfyNodeBuilder.ControlNetApplyAdvanced
{ {
Name = e.Nodes.GetUniqueName("Refiner_ControlNetApply"), Name = e.Nodes.GetUniqueName("Refiner_ControlNetApply"),
Image = imageLoad.Output1, Image = image,
ControlNet = controlNetLoader.Output, ControlNet = controlNetLoader.Output,
Positive = e.Temp.RefinerConditioning.Positive, Positive = e.Temp.RefinerConditioning.Positive,
Negative = e.Temp.RefinerConditioning.Negative, Negative = e.Temp.RefinerConditioning.Negative,

13
StabilityMatrix.Avalonia/ViewModels/Inference/Modules/HiresFixModule.cs

@ -78,9 +78,12 @@ public partial class HiresFixModule : ModuleBase
); );
} }
var hiresSampler = builder // Choose conditioning based on whether to inherit primary sampler addons
.Nodes var conditioning = samplerCard.InheritPrimarySamplerAddons
.AddTypedNode( ? builder.Connections.GetRefinerOrBasePrimarySamplerConditioning()
: builder.Connections.GetRefinerOrBaseConditioning();
var hiresSampler = builder.Nodes.AddTypedNode(
new ComfyNodeBuilder.KSampler new ComfyNodeBuilder.KSampler
{ {
Name = builder.Nodes.GetUniqueName("HiresFix_Sampler"), Name = builder.Nodes.GetUniqueName("HiresFix_Sampler"),
@ -96,8 +99,8 @@ public partial class HiresFixModule : ModuleBase
samplerCard.SelectedScheduler?.Name samplerCard.SelectedScheduler?.Name
?? e.Builder.Connections.PrimaryScheduler?.Name ?? e.Builder.Connections.PrimaryScheduler?.Name
?? throw new ArgumentException("No PrimaryScheduler"), ?? throw new ArgumentException("No PrimaryScheduler"),
Positive = builder.Connections.GetRefinerOrBaseConditioning().Positive, Positive = conditioning.Positive,
Negative = builder.Connections.GetRefinerOrBaseConditioning().Negative, Negative = conditioning.Negative,
LatentImage = builder.GetPrimaryAsLatent(), LatentImage = builder.GetPrimaryAsLatent(),
Denoise = samplerCard.DenoiseStrength Denoise = samplerCard.DenoiseStrength
} }

16
StabilityMatrix.Avalonia/ViewModels/Inference/SamplerCardViewModel.cs

@ -87,6 +87,11 @@ public partial class SamplerCardViewModel : LoadableViewModelBase, IParametersLo
[Required] [Required]
private ComfyScheduler? selectedScheduler = ComfyScheduler.Normal; private ComfyScheduler? selectedScheduler = ComfyScheduler.Normal;
[ObservableProperty]
[property: Category("Settings")]
[property: DisplayName("Inherit Primary Sampler Addons")]
private bool inheritPrimarySamplerAddons = true;
[JsonPropertyName("Modules")] [JsonPropertyName("Modules")]
public StackEditableCardViewModel ModulesCardViewModel { get; } public StackEditableCardViewModel ModulesCardViewModel { get; }
@ -142,10 +147,17 @@ public partial class SamplerCardViewModel : LoadableViewModelBase, IParametersLo
if (!e.Nodes.ContainsKey("Sampler")) if (!e.Nodes.ContainsKey("Sampler"))
{ {
ApplyStepsInitialSampler(e); ApplyStepsInitialSampler(e);
// Save temp conditioning for primary
e.Builder.Connections.Base.PrimarySamplerConditioning = e.Temp.Conditioning;
e.Builder.Connections.Refiner.PrimarySamplerConditioning = e.Temp.RefinerConditioning;
} }
else else
{ {
ApplyStepsAdditionalSampler(e); // Hires does its own sampling so just throw I guess
throw new InvalidOperationException(
"Sampler ApplyStep was called when Sampler node already exists"
);
} }
} }
@ -287,8 +299,6 @@ public partial class SamplerCardViewModel : LoadableViewModelBase, IParametersLo
} }
} }
private void ApplyStepsAdditionalSampler(ModuleApplyStepEventArgs e) { }
/// <summary> /// <summary>
/// Applies each step of our addons /// Applies each step of our addons
/// </summary> /// </summary>

112
StabilityMatrix.Avalonia/ViewModels/InferenceViewModel.cs

@ -1,6 +1,8 @@
using System; using System;
using System.Collections.Generic;
using System.Collections.Immutable; using System.Collections.Immutable;
using System.Collections.ObjectModel; using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq; using System.Linq;
using System.Reactive.Linq; using System.Reactive.Linq;
using System.Text.Json; using System.Text.Json;
@ -16,6 +18,7 @@ using CommunityToolkit.Mvvm.Input;
using FluentAvalonia.UI.Controls; using FluentAvalonia.UI.Controls;
using NLog; using NLog;
using StabilityMatrix.Avalonia.Extensions; using StabilityMatrix.Avalonia.Extensions;
using StabilityMatrix.Avalonia.Languages;
using StabilityMatrix.Avalonia.Models; using StabilityMatrix.Avalonia.Models;
using StabilityMatrix.Avalonia.Services; using StabilityMatrix.Avalonia.Services;
using StabilityMatrix.Avalonia.ViewModels.Base; using StabilityMatrix.Avalonia.ViewModels.Base;
@ -51,8 +54,10 @@ public partial class InferenceViewModel : PageViewModelBase, IAsyncDisposable
private readonly ServiceManager<ViewModelBase> vmFactory; private readonly ServiceManager<ViewModelBase> vmFactory;
private readonly IModelIndexService modelIndexService; private readonly IModelIndexService modelIndexService;
private readonly ILiteDbContext liteDbContext; private readonly ILiteDbContext liteDbContext;
private readonly RunningPackageService runningPackageService;
private Guid? selectedPackageId;
public override string Title => "Inference"; public override string Title => Resources.Label_Inference;
public override IconSource IconSource => public override IconSource IconSource =>
new SymbolIconSource { Symbol = Symbol.AppGeneric, IsFilled = true }; new SymbolIconSource { Symbol = Symbol.AppGeneric, IsFilled = true };
@ -62,7 +67,7 @@ public partial class InferenceViewModel : PageViewModelBase, IAsyncDisposable
State = ProgressState.Failed, State = ProgressState.Failed,
FailToolTipText = "Not connected", FailToolTipText = "Not connected",
FailIcon = FluentAvalonia.UI.Controls.Symbol.Refresh, FailIcon = FluentAvalonia.UI.Controls.Symbol.Refresh,
SuccessToolTipText = "Connected", SuccessToolTipText = Resources.Label_Connected,
}; };
public IInferenceClientManager ClientManager { get; } public IInferenceClientManager ClientManager { get; }
@ -86,6 +91,8 @@ public partial class InferenceViewModel : PageViewModelBase, IAsyncDisposable
public bool IsComfyRunning => RunningPackage?.BasePackage is ComfyUI; public bool IsComfyRunning => RunningPackage?.BasePackage is ComfyUI;
private IDisposable? onStartupComplete;
public InferenceViewModel( public InferenceViewModel(
ServiceManager<ViewModelBase> vmFactory, ServiceManager<ViewModelBase> vmFactory,
INotificationService notificationService, INotificationService notificationService,
@ -93,6 +100,7 @@ public partial class InferenceViewModel : PageViewModelBase, IAsyncDisposable
ISettingsManager settingsManager, ISettingsManager settingsManager,
IModelIndexService modelIndexService, IModelIndexService modelIndexService,
ILiteDbContext liteDbContext, ILiteDbContext liteDbContext,
RunningPackageService runningPackageService,
SharedState sharedState SharedState sharedState
) )
{ {
@ -101,12 +109,13 @@ public partial class InferenceViewModel : PageViewModelBase, IAsyncDisposable
this.settingsManager = settingsManager; this.settingsManager = settingsManager;
this.modelIndexService = modelIndexService; this.modelIndexService = modelIndexService;
this.liteDbContext = liteDbContext; this.liteDbContext = liteDbContext;
this.runningPackageService = runningPackageService;
ClientManager = inferenceClientManager; ClientManager = inferenceClientManager;
SharedState = sharedState; SharedState = sharedState;
// Keep RunningPackage updated with the current package pair // Keep RunningPackage updated with the current package pair
EventManager.Instance.RunningPackageStatusChanged += OnRunningPackageStatusChanged; runningPackageService.RunningPackages.CollectionChanged += RunningPackagesOnCollectionChanged;
// "Send to Inference" // "Send to Inference"
EventManager.Instance.InferenceTextToImageRequested += OnInferenceTextToImageRequested; EventManager.Instance.InferenceTextToImageRequested += OnInferenceTextToImageRequested;
@ -114,28 +123,69 @@ public partial class InferenceViewModel : PageViewModelBase, IAsyncDisposable
EventManager.Instance.InferenceImageToImageRequested += OnInferenceImageToImageRequested; EventManager.Instance.InferenceImageToImageRequested += OnInferenceImageToImageRequested;
EventManager.Instance.InferenceImageToVideoRequested += OnInferenceImageToVideoRequested; EventManager.Instance.InferenceImageToVideoRequested += OnInferenceImageToVideoRequested;
// Global requests for custom prompt queueing
EventManager.Instance.InferenceQueueCustomPrompt += OnInferenceQueueCustomPromptRequested;
MenuSaveAsCommand.WithConditionalNotificationErrorHandler(notificationService); MenuSaveAsCommand.WithConditionalNotificationErrorHandler(notificationService);
MenuOpenProjectCommand.WithConditionalNotificationErrorHandler(notificationService); MenuOpenProjectCommand.WithConditionalNotificationErrorHandler(notificationService);
} }
private void DisconnectFromComfy()
{
RunningPackage = null;
// Cancel any pending connection
if (ConnectCancelCommand.CanExecute(null))
{
ConnectCancelCommand.Execute(null);
}
onStartupComplete?.Dispose();
onStartupComplete = null;
IsWaitingForConnection = false;
// Disconnect
Logger.Trace("On package close - disconnecting");
DisconnectCommand.Execute(null);
}
/// <summary> /// <summary>
/// Updates the RunningPackage property when the running package changes. /// Updates the RunningPackage property when the running package changes.
/// Also starts a connection to the backend if a new ComfyUI package is running. /// Also starts a connection to the backend if a new ComfyUI package is running.
/// And disconnects if the package is closed. /// And disconnects if the package is closed.
/// </summary> /// </summary>
private void OnRunningPackageStatusChanged(object? sender, RunningPackageStatusChangedEventArgs e) private void RunningPackagesOnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
{
if (
e.NewItems?.OfType<KeyValuePair<Guid, RunningPackageViewModel>>().Select(x => x.Value)
is not { } newItems
)
{
if (RunningPackage != null)
{ {
RunningPackage = e.CurrentPackagePair; DisconnectFromComfy();
}
return;
}
IDisposable? onStartupComplete = null; var comfyViewModel = newItems.FirstOrDefault(
vm =>
vm.RunningPackage.InstalledPackage.Id == selectedPackageId
|| vm.RunningPackage.BasePackage is ComfyUI
);
Dispatcher.UIThread.Post(() => if (comfyViewModel is null && RunningPackage?.BasePackage is ComfyUI)
{ {
if (e.CurrentPackagePair?.BasePackage is ComfyUI package) DisconnectFromComfy();
}
else if (comfyViewModel != null && RunningPackage == null)
{ {
IsWaitingForConnection = true; IsWaitingForConnection = true;
RunningPackage = comfyViewModel.RunningPackage;
onStartupComplete = Observable onStartupComplete = Observable
.FromEventPattern<string>(package, nameof(package.StartupComplete)) .FromEventPattern<string>(
comfyViewModel.RunningPackage.BasePackage,
nameof(comfyViewModel.RunningPackage.BasePackage.StartupComplete)
)
.Take(1) .Take(1)
.Subscribe(_ => .Subscribe(_ =>
{ {
@ -146,26 +196,39 @@ public partial class InferenceViewModel : PageViewModelBase, IAsyncDisposable
Logger.Trace("On package launch - starting connection"); Logger.Trace("On package launch - starting connection");
ConnectCommand.Execute(null); ConnectCommand.Execute(null);
} }
IsWaitingForConnection = false; IsWaitingForConnection = false;
}); });
}); });
} }
else }
private void OnInferenceQueueCustomPromptRequested(object? sender, InferenceQueueCustomPromptEventArgs e)
{ {
// Cancel any pending connection // Get currently selected tab
if (ConnectCancelCommand.CanExecute(null)) var currentTab = SelectedTab;
if (currentTab is InferenceGenerationViewModelBase generationViewModel)
{ {
ConnectCancelCommand.Execute(null); Dispatcher
} .UIThread.InvokeAsync(async () =>
onStartupComplete?.Dispose(); {
onStartupComplete = null; await generationViewModel.RunCustomGeneration(e);
IsWaitingForConnection = false; })
.SafeFireAndForget(ex =>
{
Logger.Error(ex, "Failed to queue prompt");
// Disconnect Dispatcher.UIThread.Post(() =>
Logger.Trace("On package close - disconnecting"); {
DisconnectCommand.Execute(null); notificationService.ShowPersistent(
} "Failed to queue prompt",
$"{ex.GetType().Name}: {ex.Message}",
NotificationType.Error
);
}); });
});
}
} }
public override void OnLoaded() public override void OnLoaded()
@ -390,7 +453,12 @@ public partial class InferenceViewModel : PageViewModelBase, IAsyncDisposable
private async Task ShowConnectionHelp() private async Task ShowConnectionHelp()
{ {
var vm = vmFactory.Get<InferenceConnectionHelpViewModel>(); var vm = vmFactory.Get<InferenceConnectionHelpViewModel>();
await vm.CreateDialog().ShowAsync(); var result = await vm.CreateDialog().ShowAsync();
if (result != ContentDialogResult.Primary)
return;
selectedPackageId = vm.SelectedPackage?.Id;
} }
/// <summary> /// <summary>

8
StabilityMatrix.Avalonia/ViewModels/MainWindowViewModel.cs

@ -139,14 +139,6 @@ public partial class MainWindowViewModel : ViewModelBase
Content = new NewOneClickInstallDialog { DataContext = viewModel }, Content = new NewOneClickInstallDialog { DataContext = viewModel },
}; };
EventManager.Instance.OneClickInstallFinished += (_, skipped) =>
{
if (skipped)
return;
EventManager.Instance.OnTeachingTooltipNeeded();
};
var firstDialogResult = await dialog.ShowAsync(App.TopLevel); var firstDialogResult = await dialog.ShowAsync(App.TopLevel);
if (firstDialogResult != ContentDialogResult.Primary) if (firstDialogResult != ContentDialogResult.Primary)

3
StabilityMatrix.Avalonia/ViewModels/NewCheckpointsPageViewModel.cs

@ -14,6 +14,7 @@ using FluentAvalonia.UI.Controls;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using Refit; using Refit;
using StabilityMatrix.Avalonia.Controls; using StabilityMatrix.Avalonia.Controls;
using StabilityMatrix.Avalonia.Languages;
using StabilityMatrix.Avalonia.Services; using StabilityMatrix.Avalonia.Services;
using StabilityMatrix.Avalonia.ViewModels.Base; using StabilityMatrix.Avalonia.ViewModels.Base;
using StabilityMatrix.Avalonia.ViewModels.CheckpointManager; using StabilityMatrix.Avalonia.ViewModels.CheckpointManager;
@ -47,7 +48,7 @@ public partial class NewCheckpointsPageViewModel(
IMetadataImportService metadataImportService IMetadataImportService metadataImportService
) : PageViewModelBase ) : PageViewModelBase
{ {
public override string Title => "Checkpoint Manager"; public override string Title => Resources.Label_CheckpointManager;
public override IconSource IconSource => public override IconSource IconSource =>
new SymbolIconSource { Symbol = Symbol.Cellular5g, IsFilled = true }; new SymbolIconSource { Symbol = Symbol.Cellular5g, IsFilled = true };

7
StabilityMatrix.Avalonia/ViewModels/NewPackageManagerViewModel.cs

@ -3,6 +3,7 @@ using System.Collections.ObjectModel;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using DynamicData; using DynamicData;
using FluentAvalonia.UI.Controls; using FluentAvalonia.UI.Controls;
using StabilityMatrix.Avalonia.Languages;
using StabilityMatrix.Avalonia.Services; using StabilityMatrix.Avalonia.Services;
using StabilityMatrix.Avalonia.ViewModels.Base; using StabilityMatrix.Avalonia.ViewModels.Base;
using StabilityMatrix.Avalonia.ViewModels.Dialogs; using StabilityMatrix.Avalonia.ViewModels.Dialogs;
@ -18,7 +19,7 @@ namespace StabilityMatrix.Avalonia.ViewModels;
[Singleton] [Singleton]
public partial class NewPackageManagerViewModel : PageViewModelBase public partial class NewPackageManagerViewModel : PageViewModelBase
{ {
public override string Title => "Packages"; public override string Title => Resources.Label_Packages;
public override IconSource IconSource => new SymbolIconSource { Symbol = Symbol.Box, IsFilled = true }; public override IconSource IconSource => new SymbolIconSource { Symbol = Symbol.Box, IsFilled = true };
public IReadOnlyList<PageViewModelBase> SubPages { get; } public IReadOnlyList<PageViewModelBase> SubPages { get; }
@ -58,6 +59,10 @@ public partial class NewPackageManagerViewModel : PageViewModelBase
{ {
CurrentPagePath.Add(value); CurrentPagePath.Add(value);
} }
else if (value is RunningPackageViewModel)
{
CurrentPagePath.Add(value);
}
else else
{ {
CurrentPagePath.Clear(); CurrentPagePath.Clear();

166
StabilityMatrix.Avalonia/ViewModels/OutputsPageViewModel.cs

@ -5,6 +5,7 @@ using System.Diagnostics;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Reactive.Linq; using System.Reactive.Linq;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsyncAwaitBestPractices; using AsyncAwaitBestPractices;
using AsyncImageLoader; using AsyncImageLoader;
@ -28,8 +29,6 @@ using StabilityMatrix.Avalonia.ViewModels.Base;
using StabilityMatrix.Avalonia.ViewModels.Dialogs; using StabilityMatrix.Avalonia.ViewModels.Dialogs;
using StabilityMatrix.Avalonia.ViewModels.OutputsPage; using StabilityMatrix.Avalonia.ViewModels.OutputsPage;
using StabilityMatrix.Core.Attributes; using StabilityMatrix.Core.Attributes;
using StabilityMatrix.Core.Exceptions;
using StabilityMatrix.Core.Extensions;
using StabilityMatrix.Core.Helper; using StabilityMatrix.Core.Helper;
using StabilityMatrix.Core.Helper.Factory; using StabilityMatrix.Core.Helper.Factory;
using StabilityMatrix.Core.Models; using StabilityMatrix.Core.Models;
@ -52,19 +51,21 @@ public partial class OutputsPageViewModel : PageViewModelBase
private readonly INotificationService notificationService; private readonly INotificationService notificationService;
private readonly INavigationService<MainWindowViewModel> navigationService; private readonly INavigationService<MainWindowViewModel> navigationService;
private readonly ILogger<OutputsPageViewModel> logger; private readonly ILogger<OutputsPageViewModel> logger;
private readonly List<CancellationTokenSource> cancellationTokenSources = [];
public override string Title => Resources.Label_OutputsPageTitle; public override string Title => Resources.Label_OutputsPageTitle;
public override IconSource IconSource => new SymbolIconSource { Symbol = Symbol.Grid, IsFilled = true }; public override IconSource IconSource => new SymbolIconSource { Symbol = Symbol.Grid, IsFilled = true };
public SourceCache<LocalImageFile, string> OutputsCache { get; } = new(file => file.AbsolutePath); public SourceCache<LocalImageFile, string> OutputsCache { get; } = new(file => file.AbsolutePath);
private SourceCache<PackageOutputCategory, string> categoriesCache = new(category => category.Path);
public IObservableCollection<OutputImageViewModel> Outputs { get; set; } = public IObservableCollection<OutputImageViewModel> Outputs { get; set; } =
new ObservableCollectionExtended<OutputImageViewModel>(); new ObservableCollectionExtended<OutputImageViewModel>();
public IEnumerable<SharedOutputType> OutputTypes { get; } = Enum.GetValues<SharedOutputType>(); public IObservableCollection<PackageOutputCategory> Categories { get; set; } =
new ObservableCollectionExtended<PackageOutputCategory>();
[ObservableProperty]
private ObservableCollection<PackageOutputCategory> categories;
[ObservableProperty] [ObservableProperty]
[NotifyPropertyChangedFor(nameof(CanShowOutputTypes))] [NotifyPropertyChangedFor(nameof(CanShowOutputTypes))]
@ -86,6 +87,15 @@ public partial class OutputsPageViewModel : PageViewModelBase
[ObservableProperty] [ObservableProperty]
private bool isConsolidating; private bool isConsolidating;
[ObservableProperty]
private bool isLoading;
[ObservableProperty]
private bool showFolders;
[ObservableProperty]
private bool isChangingCategory;
public bool CanShowOutputTypes => SelectedCategory?.Name?.Equals("Shared Output Folder") ?? false; public bool CanShowOutputTypes => SelectedCategory?.Name?.Equals("Shared Output Folder") ?? false;
public string NumImagesSelected => public string NumImagesSelected =>
@ -95,6 +105,8 @@ public partial class OutputsPageViewModel : PageViewModelBase
private string[] allowedExtensions = [".png", ".webp"]; private string[] allowedExtensions = [".png", ".webp"];
private PackageOutputCategory? lastOutputCategory;
public OutputsPageViewModel( public OutputsPageViewModel(
ISettingsManager settingsManager, ISettingsManager settingsManager,
IPackageFactory packageFactory, IPackageFactory packageFactory,
@ -113,7 +125,7 @@ public partial class OutputsPageViewModel : PageViewModelBase
// Observable predicate from SearchQuery changes // Observable predicate from SearchQuery changes
var searchPredicate = this.WhenPropertyChanged(vm => vm.SearchQuery) var searchPredicate = this.WhenPropertyChanged(vm => vm.SearchQuery)
.Throttle(TimeSpan.FromMilliseconds(50))! .Throttle(TimeSpan.FromMilliseconds(100))!
.Select(property => searcher.GetPredicate(property.Value)) .Select(property => searcher.GetPredicate(property.Value))
.AsObservable(); .AsObservable();
@ -122,28 +134,37 @@ public partial class OutputsPageViewModel : PageViewModelBase
.DeferUntilLoaded() .DeferUntilLoaded()
.Filter(searchPredicate) .Filter(searchPredicate)
.Transform(file => new OutputImageViewModel(file)) .Transform(file => new OutputImageViewModel(file))
.SortBy(vm => vm.ImageFile.CreatedAt, SortDirection.Descending) .Sort(
SortExpressionComparer<OutputImageViewModel>
.Descending(vm => vm.ImageFile.CreatedAt)
.ThenByDescending(vm => vm.ImageFile.FileName)
)
.Bind(Outputs) .Bind(Outputs)
.WhenPropertyChanged(p => p.IsSelected) .WhenPropertyChanged(p => p.IsSelected)
.Throttle(TimeSpan.FromMilliseconds(50))
.Subscribe(_ => .Subscribe(_ =>
{ {
NumItemsSelected = Outputs.Count(o => o.IsSelected); NumItemsSelected = Outputs.Count(o => o.IsSelected);
}); });
categoriesCache.Connect().DeferUntilLoaded().Bind(Categories).Subscribe();
settingsManager.RelayPropertyFor( settingsManager.RelayPropertyFor(
this, this,
vm => vm.ImageSize, vm => vm.ImageSize,
settings => settings.OutputsImageSize, settings => settings.OutputsImageSize,
delay: TimeSpan.FromMilliseconds(250) delay: TimeSpan.FromMilliseconds(250)
); );
}
protected override void OnInitialLoaded() settingsManager.RelayPropertyFor(
{ this,
RefreshCategories(); vm => vm.ShowFolders,
settings => settings.IsOutputsTreeViewEnabled,
true
);
} }
public override void OnLoaded() protected override void OnInitialLoaded()
{ {
if (Design.IsDesignMode) if (Design.IsDesignMode)
return; return;
@ -151,14 +172,17 @@ public partial class OutputsPageViewModel : PageViewModelBase
if (!settingsManager.IsLibraryDirSet) if (!settingsManager.IsLibraryDirSet)
return; return;
base.OnLoaded();
Directory.CreateDirectory(settingsManager.ImagesDirectory); Directory.CreateDirectory(settingsManager.ImagesDirectory);
RefreshCategories();
SelectedCategory ??= Categories.First(); SelectedCategory ??= Categories.First();
SelectedOutputType ??= SharedOutputType.All; SelectedOutputType ??= SharedOutputType.All;
SearchQuery = string.Empty; SearchQuery = string.Empty;
ImageSize = settingsManager.Settings.OutputsImageSize; ImageSize = settingsManager.Settings.OutputsImageSize;
lastOutputCategory = SelectedCategory;
IsChangingCategory = true;
var path = var path =
CanShowOutputTypes && SelectedOutputType != SharedOutputType.All CanShowOutputTypes && SelectedOutputType != SharedOutputType.All
@ -169,7 +193,7 @@ public partial class OutputsPageViewModel : PageViewModelBase
partial void OnSelectedCategoryChanged(PackageOutputCategory? oldValue, PackageOutputCategory? newValue) partial void OnSelectedCategoryChanged(PackageOutputCategory? oldValue, PackageOutputCategory? newValue)
{ {
if (oldValue == newValue || newValue == null) if (oldValue == newValue || oldValue == null || newValue == null)
return; return;
var path = var path =
@ -177,11 +201,12 @@ public partial class OutputsPageViewModel : PageViewModelBase
? Path.Combine(newValue.Path, SelectedOutputType.ToString()) ? Path.Combine(newValue.Path, SelectedOutputType.ToString())
: SelectedCategory.Path; : SelectedCategory.Path;
GetOutputs(path); GetOutputs(path);
lastOutputCategory = newValue;
} }
partial void OnSelectedOutputTypeChanged(SharedOutputType? oldValue, SharedOutputType? newValue) partial void OnSelectedOutputTypeChanged(SharedOutputType? oldValue, SharedOutputType? newValue)
{ {
if (oldValue == newValue || newValue == null) if (oldValue == newValue || oldValue == null || newValue == null)
return; return;
var path = var path =
@ -262,8 +287,13 @@ public partial class OutputsPageViewModel : PageViewModelBase
public void Refresh() public void Refresh()
{ {
Dispatcher.UIThread.Post(() => RefreshCategories()); Dispatcher.UIThread.Post(RefreshCategories);
Dispatcher.UIThread.Post(OnLoaded);
var path =
CanShowOutputTypes && SelectedOutputType != SharedOutputType.All
? Path.Combine(SelectedCategory.Path, SelectedOutputType.ToString())
: SelectedCategory.Path;
GetOutputs(path);
} }
public async Task DeleteImage(OutputImageViewModel? item) public async Task DeleteImage(OutputImageViewModel? item)
@ -273,8 +303,8 @@ public partial class OutputsPageViewModel : PageViewModelBase
var confirmationDialog = new BetterContentDialog var confirmationDialog = new BetterContentDialog
{ {
Title = "Are you sure you want to delete this image?", Title = Resources.Label_AreYouSure,
Content = "This action cannot be undone.", Content = Resources.Label_ActionCannotBeUndone,
PrimaryButtonText = Resources.Action_Delete, PrimaryButtonText = Resources.Action_Delete,
SecondaryButtonText = Resources.Action_Cancel, SecondaryButtonText = Resources.Action_Cancel,
DefaultButton = ContentDialogButton.Primary, DefaultButton = ContentDialogButton.Primary,
@ -352,8 +382,8 @@ public partial class OutputsPageViewModel : PageViewModelBase
{ {
var confirmationDialog = new BetterContentDialog var confirmationDialog = new BetterContentDialog
{ {
Title = $"Are you sure you want to delete {NumItemsSelected} images?", Title = string.Format(Resources.Label_AreYouSureDeleteImages, NumItemsSelected),
Content = "This action cannot be undone.", Content = Resources.Label_ActionCannotBeUndone,
PrimaryButtonText = Resources.Action_Delete, PrimaryButtonText = Resources.Action_Delete,
SecondaryButtonText = Resources.Action_Cancel, SecondaryButtonText = Resources.Action_Cancel,
DefaultButton = ContentDialogButton.Primary, DefaultButton = ContentDialogButton.Primary,
@ -491,7 +521,7 @@ public partial class OutputsPageViewModel : PageViewModelBase
} }
} }
OnLoaded(); Refresh();
IsConsolidating = false; IsConsolidating = false;
} }
@ -517,20 +547,58 @@ public partial class OutputsPageViewModel : PageViewModelBase
return; return;
} }
if (lastOutputCategory?.Path.Equals(directory) is not true)
{
OutputsCache.Clear();
IsChangingCategory = true;
}
IsLoading = true;
cancellationTokenSources.ForEach(cts => cts.Cancel());
Task.Run(() =>
{
var getOutputsTokenSource = new CancellationTokenSource();
cancellationTokenSources.Add(getOutputsTokenSource);
if (getOutputsTokenSource.IsCancellationRequested)
{
cancellationTokenSources.Remove(getOutputsTokenSource);
return;
}
var files = Directory var files = Directory
.EnumerateFiles(directory, "*.*", SearchOption.AllDirectories) .EnumerateFiles(directory, "*.*", SearchOption.AllDirectories)
.Where(path => allowedExtensions.Contains(new FilePath(path).Extension)) .Where(file => allowedExtensions.Contains(new FilePath(file).Extension))
.Select(file => LocalImageFile.FromPath(file)) .Select(file => LocalImageFile.FromPath(file))
.ToList(); .ToList();
if (files.Count == 0) if (getOutputsTokenSource.IsCancellationRequested)
{ {
OutputsCache.Clear(); cancellationTokenSources.Remove(getOutputsTokenSource);
return;
} }
else
Dispatcher.UIThread.Post(() =>
{
if (files.Count == 0 && OutputsCache.Count == 0)
{ {
OutputsCache.EditDiff(files); IsLoading = false;
IsChangingCategory = false;
return;
} }
OutputsCache.EditDiff(
files,
(oldItem, newItem) => oldItem.AbsolutePath == newItem.AbsolutePath
);
IsLoading = false;
IsChangingCategory = false;
});
cancellationTokenSources.Remove(getOutputsTokenSource);
});
} }
private void RefreshCategories() private void RefreshCategories()
@ -559,7 +627,10 @@ public partial class OutputsPageViewModel : PageViewModelBase
pair.InstalledPackage.FullPath!, pair.InstalledPackage.FullPath!,
pair.BasePackage.OutputFolderName pair.BasePackage.OutputFolderName
), ),
Name = pair.InstalledPackage.DisplayName ?? "" Name = pair.InstalledPackage.DisplayName ?? "",
SubDirectories = GetSubfolders(
Path.Combine(pair.InstalledPackage.FullPath!, pair.BasePackage.OutputFolderName)
)
} }
) )
.ToList(); .ToList();
@ -569,18 +640,37 @@ public partial class OutputsPageViewModel : PageViewModelBase
new PackageOutputCategory new PackageOutputCategory
{ {
Path = settingsManager.ImagesDirectory, Path = settingsManager.ImagesDirectory,
Name = "Shared Output Folder" Name = "Shared Output Folder",
SubDirectories = GetSubfolders(settingsManager.ImagesDirectory)
} }
); );
packageCategories.Insert( categoriesCache.EditDiff(packageCategories, (a, b) => a.Path == b.Path);
1,
new PackageOutputCategory { Path = settingsManager.ImagesInferenceDirectory, Name = "Inference" } SelectedCategory = previouslySelectedCategory ?? Categories.First();
); }
private ObservableCollection<PackageOutputCategory> GetSubfolders(string strPath)
{
var subfolders = new ObservableCollection<PackageOutputCategory>();
Categories = new ObservableCollection<PackageOutputCategory>(packageCategories); if (!Directory.Exists(strPath))
return subfolders;
var directories = Directory.EnumerateDirectories(strPath, "*", SearchOption.TopDirectoryOnly);
foreach (var dir in directories)
{
var category = new PackageOutputCategory { Name = Path.GetFileName(dir), Path = dir };
if (Directory.GetDirectories(dir, "*", SearchOption.TopDirectoryOnly).Length > 0)
{
category.SubDirectories = GetSubfolders(dir);
}
subfolders.Add(category);
}
SelectedCategory = return subfolders;
Categories.FirstOrDefault(x => x.Name == previouslySelectedCategory?.Name) ?? Categories.First();
} }
} }

271
StabilityMatrix.Avalonia/ViewModels/PackageManager/PackageCardViewModel.cs

@ -1,11 +1,16 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Collections.Immutable;
using System.Collections.Specialized;
using System.Linq; using System.Linq;
using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsyncAwaitBestPractices;
using Avalonia; using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Controls.Notifications; using Avalonia.Controls.Notifications;
using Avalonia.Controls.Primitives; using Avalonia.Controls.Primitives;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using FluentAvalonia.UI.Controls; using FluentAvalonia.UI.Controls;
@ -26,7 +31,6 @@ using StabilityMatrix.Core.Models;
using StabilityMatrix.Core.Models.FileInterfaces; using StabilityMatrix.Core.Models.FileInterfaces;
using StabilityMatrix.Core.Models.PackageModification; using StabilityMatrix.Core.Models.PackageModification;
using StabilityMatrix.Core.Models.Packages; using StabilityMatrix.Core.Models.Packages;
using StabilityMatrix.Core.Models.Settings;
using StabilityMatrix.Core.Processes; using StabilityMatrix.Core.Processes;
using StabilityMatrix.Core.Services; using StabilityMatrix.Core.Services;
@ -34,14 +38,17 @@ namespace StabilityMatrix.Avalonia.ViewModels.PackageManager;
[ManagedService] [ManagedService]
[Transient] [Transient]
public partial class PackageCardViewModel : ProgressViewModel public partial class PackageCardViewModel(
ILogger<PackageCardViewModel> logger,
IPackageFactory packageFactory,
INotificationService notificationService,
ISettingsManager settingsManager,
INavigationService<NewPackageManagerViewModel> navigationService,
ServiceManager<ViewModelBase> vmFactory,
RunningPackageService runningPackageService
) : ProgressViewModel
{ {
private readonly ILogger<PackageCardViewModel> logger; private string webUiUrl = string.Empty;
private readonly IPackageFactory packageFactory;
private readonly INotificationService notificationService;
private readonly ISettingsManager settingsManager;
private readonly INavigationService<MainWindowViewModel> navigationService;
private readonly ServiceManager<ViewModelBase> vmFactory;
[ObservableProperty] [ObservableProperty]
private InstalledPackage? package; private InstalledPackage? package;
@ -82,21 +89,31 @@ public partial class PackageCardViewModel : ProgressViewModel
[ObservableProperty] [ObservableProperty]
private bool canUseExtensions; private bool canUseExtensions;
public PackageCardViewModel( [ObservableProperty]
ILogger<PackageCardViewModel> logger, private bool isRunning;
IPackageFactory packageFactory,
INotificationService notificationService, [ObservableProperty]
ISettingsManager settingsManager, private bool showWebUiButton;
INavigationService<MainWindowViewModel> navigationService,
ServiceManager<ViewModelBase> vmFactory private void RunningPackagesOnCollectionChanged(object? sender, NotifyCollectionChangedEventArgs e)
) {
if (runningPackageService.RunningPackages.Select(x => x.Value) is not { } runningPackages)
return;
var runningViewModel = runningPackages.FirstOrDefault(
x => x.RunningPackage.InstalledPackage.Id == Package?.Id
);
if (runningViewModel is not null)
{
IsRunning = true;
runningViewModel.RunningPackage.BasePackage.Exited += BasePackageOnExited;
runningViewModel.RunningPackage.BasePackage.StartupComplete += RunningPackageOnStartupComplete;
}
else if (runningViewModel is null && IsRunning)
{ {
this.logger = logger; IsRunning = false;
this.packageFactory = packageFactory; ShowWebUiButton = false;
this.notificationService = notificationService; }
this.settingsManager = settingsManager;
this.navigationService = navigationService;
this.vmFactory = vmFactory;
} }
partial void OnPackageChanged(InstalledPackage? value) partial void OnPackageChanged(InstalledPackage? value)
@ -127,11 +144,30 @@ public partial class PackageCardViewModel : ProgressViewModel
UseSharedOutput = Package?.UseSharedOutputFolder ?? false; UseSharedOutput = Package?.UseSharedOutputFolder ?? false;
CanUseSharedOutput = basePackage?.SharedOutputFolders != null; CanUseSharedOutput = basePackage?.SharedOutputFolders != null;
CanUseExtensions = basePackage?.SupportsExtensions ?? false; CanUseExtensions = basePackage?.SupportsExtensions ?? false;
runningPackageService.RunningPackages.CollectionChanged += RunningPackagesOnCollectionChanged;
EventManager.Instance.PackageRelaunchRequested += InstanceOnPackageRelaunchRequested;
} }
} }
private void InstanceOnPackageRelaunchRequested(object? sender, InstalledPackage e)
{
if (e.Id != Package?.Id)
return;
navigationService.GoBack();
Launch().SafeFireAndForget();
}
public override async Task OnLoadedAsync() public override async Task OnLoadedAsync()
{ {
if (Design.IsDesignMode && Package?.DisplayName == "Running Comfy")
{
IsRunning = true;
IsUpdateAvailable = true;
ShowWebUiButton = true;
}
if (Design.IsDesignMode || !settingsManager.IsLibraryDirSet || Package is not { } currentPackage) if (Design.IsDesignMode || !settingsManager.IsLibraryDirSet || Package is not { } currentPackage)
return; return;
@ -160,18 +196,122 @@ public partial class PackageCardViewModel : ProgressViewModel
} }
IsUpdateAvailable = await HasUpdate(); IsUpdateAvailable = await HasUpdate();
if (
Package != null
&& !IsRunning
&& runningPackageService.RunningPackages.TryGetValue(Package.Id, out var runningPackageVm)
)
{
IsRunning = true;
runningPackageVm.RunningPackage.BasePackage.Exited += BasePackageOnExited;
runningPackageVm.RunningPackage.BasePackage.StartupComplete +=
RunningPackageOnStartupComplete;
webUiUrl = runningPackageVm.WebUiUrl;
ShowWebUiButton = !string.IsNullOrWhiteSpace(webUiUrl);
}
}
}
public override void OnUnloaded()
{
EventManager.Instance.PackageRelaunchRequested -= InstanceOnPackageRelaunchRequested;
runningPackageService.RunningPackages.CollectionChanged -= RunningPackagesOnCollectionChanged;
}
public async Task Launch()
{
if (Package == null)
return;
var packagePair = await runningPackageService.StartPackage(Package);
if (packagePair != null)
{
IsRunning = true;
packagePair.BasePackage.Exited += BasePackageOnExited;
packagePair.BasePackage.StartupComplete += RunningPackageOnStartupComplete;
var vm = runningPackageService.GetRunningPackageViewModel(packagePair.InstalledPackage.Id);
if (vm != null)
{
navigationService.NavigateTo(vm, new BetterEntranceNavigationTransition());
} }
} }
public void Launch() // settingsManager.Transaction(s => s.ActiveInstalledPackageId = Package.Id);
//
// navigationService.NavigateTo<LaunchPageViewModel>(new BetterDrillInNavigationTransition());
// EventManager.Instance.OnPackageLaunchRequested(Package.Id);
}
public void NavToConsole()
{ {
if (Package == null) if (Package == null)
return; return;
settingsManager.Transaction(s => s.ActiveInstalledPackageId = Package.Id); var vm = runningPackageService.GetRunningPackageViewModel(Package.Id);
if (vm != null)
{
navigationService.NavigateTo(vm, new BetterEntranceNavigationTransition());
}
}
public void LaunchWebUi()
{
if (string.IsNullOrEmpty(webUiUrl))
return;
navigationService.NavigateTo<LaunchPageViewModel>(new BetterDrillInNavigationTransition()); notificationService.TryAsync(
EventManager.Instance.OnPackageLaunchRequested(Package.Id); Task.Run(() => ProcessRunner.OpenUrl(webUiUrl)),
"Failed to open URL",
$"{webUiUrl}"
);
}
private void BasePackageOnExited(object? sender, int exitCode)
{
Dispatcher
.UIThread.InvokeAsync(async () =>
{
logger.LogTrace("Process exited ({Code}) at {Time:g}", exitCode, DateTimeOffset.Now);
// Need to wait for streams to finish before detaching handlers
if (sender is BaseGitPackage { VenvRunner: not null } package)
{
var process = package.VenvRunner.Process;
if (process is not null)
{
// Max 5 seconds
var ct = new CancellationTokenSource(5000).Token;
try
{
await process.WaitUntilOutputEOF(ct);
}
catch (OperationCanceledException e)
{
logger.LogWarning("Waiting for process EOF timed out: {Message}", e.Message);
}
}
}
// Detach handlers
if (sender is BasePackage basePackage)
{
basePackage.Exited -= BasePackageOnExited;
basePackage.StartupComplete -= RunningPackageOnStartupComplete;
}
if (Package?.Id != null)
{
runningPackageService.RunningPackages.Remove(Package.Id);
}
IsRunning = false;
ShowWebUiButton = false;
})
.SafeFireAndForget();
} }
public async Task Uninstall() public async Task Uninstall()
@ -282,6 +422,21 @@ public partial class PackageCardViewModel : ProgressViewModel
versionOptions.CommitHash = latest.Sha; versionOptions.CommitHash = latest.Sha;
} }
var confirmationDialog = new BetterContentDialog
{
Title = Resources.Label_AreYouSure,
Content =
$"{Package.DisplayName} will be updated to the latest version ({versionOptions.GetReadableVersionString()})",
PrimaryButtonText = Resources.Action_Continue,
SecondaryButtonText = Resources.Action_Cancel,
DefaultButton = ContentDialogButton.Primary,
IsSecondaryButtonEnabled = true,
};
var dialogResult = await confirmationDialog.ShowAsync();
if (dialogResult != ContentDialogResult.Primary)
return;
var updatePackageStep = new UpdatePackageStep( var updatePackageStep = new UpdatePackageStep(
settingsManager, settingsManager,
Package, Package,
@ -435,6 +590,64 @@ public partial class PackageCardViewModel : ProgressViewModel
ProcessRunner.OpenUrl(basePackage.GithubUrl); ProcessRunner.OpenUrl(basePackage.GithubUrl);
} }
[RelayCommand]
private async Task Stop()
{
if (Package is null)
return;
await runningPackageService.StopPackage(Package.Id);
IsRunning = false;
ShowWebUiButton = false;
}
[RelayCommand]
private async Task Restart()
{
await Stop();
await Launch();
}
[RelayCommand]
private async Task ShowLaunchOptions()
{
var basePackage = packageFactory.FindPackageByName(Package?.PackageName);
if (basePackage == null)
{
logger.LogWarning("Package {Name} not found", Package?.PackageName);
return;
}
var viewModel = vmFactory.Get<LaunchOptionsViewModel>();
viewModel.Cards = LaunchOptionCard
.FromDefinitions(basePackage.LaunchOptions, Package?.LaunchArgs ?? [])
.ToImmutableArray();
logger.LogDebug("Launching config dialog with cards: {CardsCount}", viewModel.Cards.Count);
var dialog = new BetterContentDialog
{
ContentVerticalScrollBarVisibility = ScrollBarVisibility.Disabled,
IsPrimaryButtonEnabled = true,
PrimaryButtonText = Resources.Action_Save,
CloseButtonText = Resources.Action_Cancel,
FullSizeDesired = true,
DefaultButton = ContentDialogButton.Primary,
ContentMargin = new Thickness(32, 16),
Padding = new Thickness(0, 16),
Content = new LaunchOptionsDialog { DataContext = viewModel, }
};
var result = await dialog.ShowAsync();
if (result == ContentDialogResult.Primary && Package != null)
{
// Save config
var args = viewModel.AsLaunchArgs();
settingsManager.SaveLaunchArgs(Package.Id, args);
}
}
private async Task<bool> HasUpdate() private async Task<bool> HasUpdate()
{ {
if (Package == null || IsUnknownPackage || Design.IsDesignMode) if (Package == null || IsUnknownPackage || Design.IsDesignMode)
@ -565,4 +778,10 @@ public partial class PackageCardViewModel : ProgressViewModel
IsSharedModelConfig = false; IsSharedModelConfig = false;
} }
} }
private void RunningPackageOnStartupComplete(object? sender, string e)
{
webUiUrl = e.Replace("0.0.0.0", "127.0.0.1");
ShowWebUiButton = !string.IsNullOrWhiteSpace(webUiUrl);
}
} }

2
StabilityMatrix.Avalonia/ViewModels/PackageManager/PackageInstallDetailViewModel.cs

@ -281,7 +281,7 @@ public partial class PackageInstallDetailViewModel(
SelectedVersion = !IsReleaseMode SelectedVersion = !IsReleaseMode
? AvailableVersions?.FirstOrDefault(x => x.TagName == SelectedPackage.MainBranch) ? AvailableVersions?.FirstOrDefault(x => x.TagName == SelectedPackage.MainBranch)
?? AvailableVersions?.FirstOrDefault() ?? AvailableVersions?.FirstOrDefault()
: AvailableVersions?.FirstOrDefault(); : AvailableVersions?.FirstOrDefault(v => !v.IsPrerelease);
CanInstall = !ShowDuplicateWarning; CanInstall = !ShowDuplicateWarning;
} }

15
StabilityMatrix.Avalonia/ViewModels/PackageManagerViewModel.cs

@ -6,8 +6,6 @@ using System.Linq;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsyncAwaitBestPractices; using AsyncAwaitBestPractices;
using Avalonia.Controls; using Avalonia.Controls;
using Avalonia.Controls.Notifications;
using Avalonia.Controls.Primitives;
using Avalonia.Threading; using Avalonia.Threading;
using CommunityToolkit.Mvvm.Input; using CommunityToolkit.Mvvm.Input;
using DynamicData; using DynamicData;
@ -15,18 +13,15 @@ using DynamicData.Binding;
using FluentAvalonia.UI.Controls; using FluentAvalonia.UI.Controls;
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging;
using StabilityMatrix.Avalonia.Animations; using StabilityMatrix.Avalonia.Animations;
using StabilityMatrix.Avalonia.Controls; using StabilityMatrix.Avalonia.Languages;
using StabilityMatrix.Avalonia.Services; using StabilityMatrix.Avalonia.Services;
using StabilityMatrix.Avalonia.ViewModels.Base; using StabilityMatrix.Avalonia.ViewModels.Base;
using StabilityMatrix.Avalonia.ViewModels.Dialogs;
using StabilityMatrix.Avalonia.ViewModels.PackageManager; using StabilityMatrix.Avalonia.ViewModels.PackageManager;
using StabilityMatrix.Avalonia.Views; using StabilityMatrix.Avalonia.Views;
using StabilityMatrix.Avalonia.Views.Dialogs;
using StabilityMatrix.Core.Attributes; using StabilityMatrix.Core.Attributes;
using StabilityMatrix.Core.Helper; using StabilityMatrix.Core.Helper;
using StabilityMatrix.Core.Models; using StabilityMatrix.Core.Models;
using StabilityMatrix.Core.Models.FileInterfaces; using StabilityMatrix.Core.Models.FileInterfaces;
using StabilityMatrix.Core.Models.PackageModification;
using StabilityMatrix.Core.Models.Packages; using StabilityMatrix.Core.Models.Packages;
using StabilityMatrix.Core.Services; using StabilityMatrix.Core.Services;
using Symbol = FluentIcons.Common.Symbol; using Symbol = FluentIcons.Common.Symbol;
@ -48,7 +43,7 @@ public partial class PackageManagerViewModel : PageViewModelBase
private readonly INavigationService<NewPackageManagerViewModel> packageNavigationService; private readonly INavigationService<NewPackageManagerViewModel> packageNavigationService;
private readonly ILogger<PackageManagerViewModel> logger; private readonly ILogger<PackageManagerViewModel> logger;
public override string Title => "Packages"; public override string Title => Resources.Label_Packages;
public override IconSource IconSource => new SymbolIconSource { Symbol = Symbol.Box, IsFilled = true }; public override IconSource IconSource => new SymbolIconSource { Symbol = Symbol.Box, IsFilled = true };
/// <summary> /// <summary>
@ -84,6 +79,7 @@ public partial class PackageManagerViewModel : PageViewModelBase
this.logger = logger; this.logger = logger;
EventManager.Instance.InstalledPackagesChanged += OnInstalledPackagesChanged; EventManager.Instance.InstalledPackagesChanged += OnInstalledPackagesChanged;
EventManager.Instance.OneClickInstallFinished += OnOneClickInstallFinished;
var installed = installedPackages.Connect(); var installed = installedPackages.Connect();
var unknown = unknownInstalledPackages.Connect(); var unknown = unknownInstalledPackages.Connect();
@ -107,6 +103,11 @@ public partial class PackageManagerViewModel : PageViewModelBase
timer.Tick += async (_, _) => await CheckPackagesForUpdates(); timer.Tick += async (_, _) => await CheckPackagesForUpdates();
} }
private void OnOneClickInstallFinished(object? sender, bool e)
{
OnLoadedAsync().SafeFireAndForget();
}
public void SetPackages(IEnumerable<InstalledPackage> packages) public void SetPackages(IEnumerable<InstalledPackage> packages)
{ {
installedPackages.Edit(s => s.Load(packages)); installedPackages.Edit(s => s.Load(packages));

161
StabilityMatrix.Avalonia/ViewModels/RunningPackageViewModel.cs

@ -0,0 +1,161 @@
using System;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using FluentAvalonia.UI.Controls;
using StabilityMatrix.Avalonia.Services;
using StabilityMatrix.Avalonia.ViewModels.Base;
using StabilityMatrix.Avalonia.Views;
using StabilityMatrix.Core.Attributes;
using StabilityMatrix.Core.Helper;
using StabilityMatrix.Core.Models;
using StabilityMatrix.Core.Models.Packages;
using StabilityMatrix.Core.Processes;
using StabilityMatrix.Core.Services;
using SymbolIconSource = FluentIcons.Avalonia.Fluent.SymbolIconSource;
using TeachingTip = StabilityMatrix.Core.Models.Settings.TeachingTip;
namespace StabilityMatrix.Avalonia.ViewModels;
[View(typeof(ConsoleOutputPage))]
public partial class RunningPackageViewModel : PageViewModelBase, IDisposable, IAsyncDisposable
{
private readonly ISettingsManager settingsManager;
private readonly INotificationService notificationService;
private readonly RunningPackageService runningPackageService;
public PackagePair RunningPackage { get; }
public ConsoleViewModel Console { get; }
public override string Title => RunningPackage.InstalledPackage.PackageName ?? "Running Package";
public override IconSource IconSource => new SymbolIconSource();
[ObservableProperty]
private bool autoScrollToEnd;
[ObservableProperty]
private bool showWebUiButton;
[ObservableProperty]
private string webUiUrl = string.Empty;
[ObservableProperty]
private bool isRunning = true;
[ObservableProperty]
private string consoleInput = string.Empty;
[ObservableProperty]
private bool showWebUiTeachingTip;
/// <inheritdoc/>
public RunningPackageViewModel(
ISettingsManager settingsManager,
INotificationService notificationService,
RunningPackageService runningPackageService,
PackagePair runningPackage,
ConsoleViewModel console
)
{
this.settingsManager = settingsManager;
this.notificationService = notificationService;
this.runningPackageService = runningPackageService;
RunningPackage = runningPackage;
Console = console;
Console.Document.LineCountChanged += DocumentOnLineCountChanged;
RunningPackage.BasePackage.StartupComplete += BasePackageOnStartupComplete;
RunningPackage.BasePackage.Exited += BasePackageOnExited;
settingsManager.RelayPropertyFor(
this,
vm => vm.AutoScrollToEnd,
settings => settings.AutoScrollLaunchConsoleToEnd,
true
);
}
private void BasePackageOnExited(object? sender, int e)
{
IsRunning = false;
ShowWebUiButton = false;
Console.Document.LineCountChanged -= DocumentOnLineCountChanged;
RunningPackage.BasePackage.StartupComplete -= BasePackageOnStartupComplete;
RunningPackage.BasePackage.Exited -= BasePackageOnExited;
runningPackageService.RunningPackages.Remove(RunningPackage.InstalledPackage.Id);
}
private void BasePackageOnStartupComplete(object? sender, string url)
{
WebUiUrl = url.Replace("0.0.0.0", "127.0.0.1");
ShowWebUiButton = !string.IsNullOrWhiteSpace(WebUiUrl);
if (settingsManager.Settings.SeenTeachingTips.Contains(TeachingTip.WebUiButtonMovedTip))
return;
ShowWebUiTeachingTip = true;
settingsManager.Transaction(s => s.SeenTeachingTips.Add(TeachingTip.WebUiButtonMovedTip));
}
private void DocumentOnLineCountChanged(object? sender, EventArgs e)
{
if (AutoScrollToEnd)
{
EventManager.Instance.OnScrollToBottomRequested();
}
}
[RelayCommand]
private void LaunchPackage()
{
EventManager.Instance.OnPackageRelaunchRequested(RunningPackage.InstalledPackage);
}
[RelayCommand]
private async Task Stop()
{
await runningPackageService.StopPackage(RunningPackage.InstalledPackage.Id);
Console.PostLine($"{Environment.NewLine}Stopped process at {DateTimeOffset.Now}");
await Console.StopUpdatesAsync();
IsRunning = false;
}
[RelayCommand]
private void LaunchWebUi()
{
if (string.IsNullOrEmpty(WebUiUrl))
return;
notificationService.TryAsync(
Task.Run(() => ProcessRunner.OpenUrl(WebUiUrl)),
"Failed to open URL",
$"{WebUiUrl}"
);
}
[RelayCommand]
private async Task SendToConsole()
{
Console.PostLine(ConsoleInput);
if (RunningPackage?.BasePackage is BaseGitPackage gitPackage)
{
var venv = gitPackage.VenvRunner;
var process = venv?.Process;
if (process is not null)
{
await process.StandardInput.WriteLineAsync(ConsoleInput);
}
}
ConsoleInput = string.Empty;
}
public void Dispose()
{
Console.Dispose();
}
public async ValueTask DisposeAsync()
{
await Console.DisposeAsync();
}
}

60
StabilityMatrix.Avalonia/ViewModels/Settings/MainSettingsViewModel.cs

@ -14,6 +14,7 @@ using System.Text;
using System.Text.Json; using System.Text.Json;
using System.Threading.Tasks; using System.Threading.Tasks;
using AsyncAwaitBestPractices; using AsyncAwaitBestPractices;
using AsyncImageLoader;
using Avalonia; using Avalonia;
using Avalonia.Controls.Notifications; using Avalonia.Controls.Notifications;
using Avalonia.Controls.Primitives; using Avalonia.Controls.Primitives;
@ -774,7 +775,10 @@ public partial class MainSettingsViewModel : PageViewModelBase
[ [
new CommandItem(DebugFindLocalModelFromIndexCommand), new CommandItem(DebugFindLocalModelFromIndexCommand),
new CommandItem(DebugExtractDmgCommand), new CommandItem(DebugExtractDmgCommand),
new CommandItem(DebugShowNativeNotificationCommand) new CommandItem(DebugShowNativeNotificationCommand),
new CommandItem(DebugClearImageCacheCommand),
new CommandItem(DebugGCCollectCommand),
new CommandItem(DebugExtractImagePromptsToTxtCommand)
]; ];
[RelayCommand] [RelayCommand]
@ -889,6 +893,60 @@ public partial class MainSettingsViewModel : PageViewModelBase
); );
} }
[RelayCommand]
private void DebugClearImageCache()
{
if (ImageLoader.AsyncImageLoader is FallbackRamCachedWebImageLoader loader)
{
loader.ClearCache();
}
}
[RelayCommand]
private void DebugGCCollect()
{
GC.Collect();
}
[RelayCommand]
private async Task DebugExtractImagePromptsToTxt()
{
// Choose images
var provider = App.StorageProvider;
var files = await provider.OpenFilePickerAsync(new FilePickerOpenOptions { AllowMultiple = true });
if (files.Count == 0)
return;
var images = await Task.Run(
() => files.Select(f => LocalImageFile.FromPath(f.TryGetLocalPath()!)).ToList()
);
var successfulFiles = new List<LocalImageFile>();
foreach (var localImage in images)
{
var imageFile = new FilePath(localImage.AbsolutePath);
// Write a txt with the same name as the image
var txtFile = imageFile.WithName(imageFile.NameWithoutExtension + ".txt");
// Read metadata
if (localImage.GenerationParameters?.PositivePrompt is { } positivePrompt)
{
await File.WriteAllTextAsync(txtFile, positivePrompt);
successfulFiles.Add(localImage);
}
}
notificationService.Show(
"Extracted prompts",
$"Extracted prompts from {successfulFiles.Count}/{images.Count} images.",
NotificationType.Success
);
}
#endregion #endregion
#region Info Section #region Info Section

12
StabilityMatrix.Avalonia/Views/CivitAiBrowserPage.axaml

@ -15,6 +15,7 @@
xmlns:converters="clr-namespace:StabilityMatrix.Avalonia.Converters" xmlns:converters="clr-namespace:StabilityMatrix.Avalonia.Converters"
xmlns:asyncImageLoader="clr-namespace:AsyncImageLoader;assembly=AsyncImageLoader.Avalonia" xmlns:asyncImageLoader="clr-namespace:AsyncImageLoader;assembly=AsyncImageLoader.Avalonia"
xmlns:helpers="clr-namespace:StabilityMatrix.Avalonia.Helpers" xmlns:helpers="clr-namespace:StabilityMatrix.Avalonia.Helpers"
xmlns:controls1="clr-namespace:Avalonia.Labs.Controls;assembly=Avalonia.Labs.Controls"
d:DataContext="{x:Static designData:DesignData.CivitAiBrowserViewModel}" d:DataContext="{x:Static designData:DesignData.CivitAiBrowserViewModel}"
d:DesignHeight="700" d:DesignHeight="700"
d:DesignWidth="800" d:DesignWidth="800"
@ -100,7 +101,7 @@
CommandParameter="{Binding CivitModel}" CommandParameter="{Binding CivitModel}"
IsEnabled="{Binding !IsImporting}"> IsEnabled="{Binding !IsImporting}">
<Grid RowDefinitions="*, Auto"> <Grid RowDefinitions="*, Auto">
<controls:BetterAdvancedImage Grid.Row="0" <controls1:AsyncImage Grid.Row="0"
CornerRadius="8" CornerRadius="8"
VerticalAlignment="Top" VerticalAlignment="Top"
HorizontalAlignment="Center" HorizontalAlignment="Center"
@ -112,16 +113,15 @@
<!-- <controls:BetterAdvancedImage.RenderTransform> --> <!-- <controls:BetterAdvancedImage.RenderTransform> -->
<!-- <RotateTransform Angle="315"></RotateTransform> --> <!-- <RotateTransform Angle="315"></RotateTransform> -->
<!-- </controls:BetterAdvancedImage.RenderTransform> --> <!-- </controls:BetterAdvancedImage.RenderTransform> -->
</controls:BetterAdvancedImage> </controls1:AsyncImage>
<controls:BetterAdvancedImage <controls1:AsyncImage
Grid.Row="0" Grid.Row="0"
Grid.RowSpan="2" Grid.RowSpan="2"
CornerRadius="8" CornerRadius="8"
Width="330" Width="330"
Height="400" Height="400"
Source="{Binding CardImage}" Source="{Binding CardImage}"
Stretch="UniformToFill" Stretch="UniformToFill"/>
StretchDirection="Both"/>
<StackPanel <StackPanel
Grid.Row="0" Grid.Row="0"
@ -180,7 +180,7 @@
Classes="transparent" Classes="transparent"
Padding="10,4"> Padding="10,4">
<StackPanel Orientation="Horizontal" Spacing="6"> <StackPanel Orientation="Horizontal" Spacing="6">
<controls:BetterAdvancedImage <controls1:AsyncImage
Width="22" Width="22"
Height="22" Height="22"
Effect="{StaticResource ImageDropShadowEffect}" Effect="{StaticResource ImageDropShadowEffect}"

93
StabilityMatrix.Avalonia/Views/ConsoleOutputPage.axaml

@ -0,0 +1,93 @@
<controls:UserControlBase xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="clr-namespace:StabilityMatrix.Avalonia.Controls"
xmlns:avaloniaEdit="https://github.com/avaloniaui/avaloniaedit"
xmlns:viewModels="clr-namespace:StabilityMatrix.Avalonia.ViewModels"
xmlns:ui="clr-namespace:FluentAvalonia.UI.Controls;assembly=FluentAvalonia"
xmlns:lang="clr-namespace:StabilityMatrix.Avalonia.Languages"
xmlns:avalonia="https://github.com/projektanker/icons.avalonia"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450"
x:DataType="viewModels:RunningPackageViewModel"
x:Class="StabilityMatrix.Avalonia.Views.ConsoleOutputPage">
<Grid RowDefinitions="Auto, *, Auto">
<ui:CommandBar Grid.Row="0"
Margin="12,0,0,4"
VerticalAlignment="Center"
VerticalContentAlignment="Center"
HorizontalAlignment="Left"
HorizontalContentAlignment="Left"
DefaultLabelPosition="Right">
<ui:CommandBar.PrimaryCommands>
<ui:CommandBarButton
IconSource="Stop"
IsVisible="{Binding IsRunning}"
Classes="danger"
Command="{Binding StopCommand}"
VerticalAlignment="Center"
Label="{x:Static lang:Resources.Action_Stop}" />
<ui:CommandBarButton
IconSource="Play"
IsVisible="{Binding !IsRunning}"
Classes="success"
Command="{Binding LaunchPackageCommand}"
VerticalAlignment="Center"
Label="{x:Static lang:Resources.Action_Launch}" />
<ui:CommandBarSeparator Margin="6,0,4,0"/>
<ui:CommandBarToggleButton
VerticalAlignment="Center"
IsChecked="{Binding AutoScrollToEnd}"
Label="{x:Static lang:Resources.Label_ToggleAutoScrolling}"
ToolTip.Tip="{x:Static lang:Resources.Label_AutoScrollToEnd}">
<ui:CommandBarToggleButton.IconSource>
<controls:FASymbolIconSource Symbol="fa-solid fa-arrow-down-wide-short" />
</ui:CommandBarToggleButton.IconSource>
</ui:CommandBarToggleButton>
<ui:CommandBarButton
Command="{Binding LaunchWebUiCommand}"
IsVisible="{Binding ShowWebUiButton}"
VerticalAlignment="Center"
x:Name="OpenWebUiButton"
Label="{x:Static lang:Resources.Action_OpenWebUI}">
<ui:CommandBarButton.IconSource>
<controls:FASymbolIconSource Symbol="fa-solid fa-up-right-from-square"/>
</ui:CommandBarButton.IconSource>
</ui:CommandBarButton>
</ui:CommandBar.PrimaryCommands>
</ui:CommandBar>
<avaloniaEdit:TextEditor
Grid.Row="1"
x:Name="Console"
Margin="8,8,16,10"
DataContext="{Binding Console}"
Document="{Binding Document}"
FontFamily="Cascadia Code,Consolas,Menlo,Monospace"
IsReadOnly="True"
LineNumbersForeground="DarkSlateGray"
ShowLineNumbers="True"
VerticalScrollBarVisibility="Auto"
WordWrap="True" />
<Grid Grid.Row="2" ColumnDefinitions="*, Auto"
Margin="16,4,16,16">
<TextBox Grid.Column="0" Text="{Binding ConsoleInput, Mode=TwoWay}"
Margin="0,0,8,0"/>
<Button Grid.Column="1"
Classes="accent"
IsDefault="True"
Content="{x:Static lang:Resources.Action_Send}"
Command="{Binding SendToConsoleCommand}"/>
</Grid>
<ui:TeachingTip Grid.Row="0" Grid.Column="0" Name="TeachingTip1"
Target="{Binding #OpenWebUiButton}"
Title="{x:Static lang:Resources.TeachingTip_WebUiButtonMoved}"
PreferredPlacement="Bottom"
IsOpen="True"/>
</Grid>
</controls:UserControlBase>

54
StabilityMatrix.Avalonia/Views/ConsoleOutputPage.axaml.cs

@ -0,0 +1,54 @@
using System;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Interactivity;
using Avalonia.Threading;
using AvaloniaEdit;
using StabilityMatrix.Avalonia.Controls;
using StabilityMatrix.Avalonia.Helpers;
using StabilityMatrix.Avalonia.Models;
using StabilityMatrix.Core.Attributes;
using StabilityMatrix.Core.Helper;
namespace StabilityMatrix.Avalonia.Views;
[Transient]
public partial class ConsoleOutputPage : UserControlBase
{
private const int LineOffset = 5;
public ConsoleOutputPage()
{
InitializeComponent();
}
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
TextEditorConfigs.Configure(Console, TextEditorPreset.Console);
}
protected override void OnUnloaded(RoutedEventArgs e)
{
base.OnUnloaded(e);
EventManager.Instance.ScrollToBottomRequested -= OnScrollToBottomRequested;
}
protected override void OnLoaded(RoutedEventArgs e)
{
base.OnLoaded(e);
EventManager.Instance.ScrollToBottomRequested += OnScrollToBottomRequested;
}
private void OnScrollToBottomRequested(object? sender, EventArgs e)
{
Dispatcher.UIThread.Invoke(() =>
{
var editor = this.FindControl<TextEditor>("Console");
if (editor?.Document == null)
return;
var line = Math.Max(editor.Document.LineCount - LineOffset, 1);
editor.ScrollToLine(line);
});
}
}

44
StabilityMatrix.Avalonia/Views/MainWindow.axaml.cs

@ -6,6 +6,7 @@ using System.IO;
using System.Linq; using System.Linq;
using System.Reactive.Linq; using System.Reactive.Linq;
using System.Threading; using System.Threading;
using AsyncAwaitBestPractices;
using AsyncImageLoader; using AsyncImageLoader;
using Avalonia; using Avalonia;
using Avalonia.Controls; using Avalonia.Controls;
@ -193,13 +194,52 @@ public partial class MainWindow : AppWindowBase
protected override void OnClosing(WindowClosingEventArgs e) protected override void OnClosing(WindowClosingEventArgs e)
{ {
// Show confirmation if package running // Show confirmation if package running
var launchPageViewModel = App.Services.GetRequiredService<LaunchPageViewModel>(); var runningPackageService = App.Services.GetRequiredService<RunningPackageService>();
if (
runningPackageService.RunningPackages.Count > 0
&& e.CloseReason is WindowCloseReason.WindowClosing
)
{
e.Cancel = true;
launchPageViewModel.OnMainWindowClosing(e); var dialog = CreateExitConfirmDialog();
Dispatcher
.UIThread.InvokeAsync(async () =>
{
if (
(TaskDialogStandardResult)await dialog.ShowAsync(true) == TaskDialogStandardResult.Yes
)
{
App.Services.GetRequiredService<MainWindow>().Hide();
App.Shutdown();
}
})
.SafeFireAndForget();
}
base.OnClosing(e); base.OnClosing(e);
} }
private static TaskDialog CreateExitConfirmDialog()
{
var dialog = DialogHelper.CreateTaskDialog(
Languages.Resources.Label_ConfirmExit,
Languages.Resources.Label_ConfirmExitDetail
);
dialog.ShowProgressBar = false;
dialog.FooterVisibility = TaskDialogFooterVisibility.Never;
dialog.Buttons = new List<TaskDialogButton>
{
new("Exit", TaskDialogStandardResult.Yes),
TaskDialogButton.CancelButton
};
dialog.Buttons[0].IsDefault = true;
return dialog;
}
/// <inheritdoc /> /// <inheritdoc />
protected override void OnClosed(EventArgs e) protected override void OnClosed(EventArgs e)
{ {

135
StabilityMatrix.Avalonia/Views/OutputsPage.axaml

@ -2,15 +2,12 @@
x:Class="StabilityMatrix.Avalonia.Views.OutputsPage" x:Class="StabilityMatrix.Avalonia.Views.OutputsPage"
xmlns="https://github.com/avaloniaui" xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:avalonia="clr-namespace:Projektanker.Icons.Avalonia;assembly=Projektanker.Icons.Avalonia"
xmlns:avaloniaEdit="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:controls="clr-namespace:StabilityMatrix.Avalonia.Controls" xmlns:controls="clr-namespace:StabilityMatrix.Avalonia.Controls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:fluentAvalonia="clr-namespace:FluentIcons.Avalonia.Fluent;assembly=FluentIcons.Avalonia.Fluent" xmlns:fluentAvalonia="clr-namespace:FluentIcons.Avalonia.Fluent;assembly=FluentIcons.Avalonia.Fluent"
xmlns:lang="clr-namespace:StabilityMatrix.Avalonia.Languages" xmlns:lang="clr-namespace:StabilityMatrix.Avalonia.Languages"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:mocks="clr-namespace:StabilityMatrix.Avalonia.DesignData" xmlns:mocks="clr-namespace:StabilityMatrix.Avalonia.DesignData"
xmlns:models1="clr-namespace:StabilityMatrix.Avalonia.Models"
xmlns:outputsPage="clr-namespace:StabilityMatrix.Avalonia.ViewModels.OutputsPage" xmlns:outputsPage="clr-namespace:StabilityMatrix.Avalonia.ViewModels.OutputsPage"
xmlns:scroll="clr-namespace:StabilityMatrix.Avalonia.Controls.Scroll" xmlns:scroll="clr-namespace:StabilityMatrix.Avalonia.Controls.Scroll"
xmlns:selectableImageCard="clr-namespace:StabilityMatrix.Avalonia.Controls.SelectableImageCard" xmlns:selectableImageCard="clr-namespace:StabilityMatrix.Avalonia.Controls.SelectableImageCard"
@ -23,8 +20,28 @@
x:DataType="vm:OutputsPageViewModel" x:DataType="vm:OutputsPageViewModel"
Focusable="True" Focusable="True"
mc:Ignorable="d"> mc:Ignorable="d">
<Grid Margin="16" RowDefinitions="Auto,*"> <Grid Margin="16" RowDefinitions="Auto,*"
<Grid ColumnDefinitions="Auto, *">
<TreeView Grid.Row="1"
Grid.Column="0"
IsVisible="{Binding ShowFolders}"
Margin="0,0,12,0"
ItemsSource="{Binding Categories}"
SelectedItem="{Binding SelectedCategory}">
<TreeView.ItemTemplate>
<TreeDataTemplate ItemsSource="{Binding SubDirectories}">
<TextBlock Text="{Binding Name}"
MaxWidth="250"
TextWrapping="NoWrap"
TextTrimming="CharacterEllipsis"
ToolTip.Tip="{Binding Name}"/>
</TreeDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
<Grid Grid.Column="0"
Grid.ColumnSpan="2"
Grid.Row="0" Grid.Row="0"
Margin="0,0,0,16" Margin="0,0,0,16"
ColumnDefinitions="Auto,Auto,*,Auto" ColumnDefinitions="Auto,Auto,*,Auto"
@ -39,56 +56,6 @@
</Style> </Style>
</Grid.Styles> </Grid.Styles>
<TextBlock
Grid.Row="0"
Grid.Column="0"
Margin="4"
Text="{x:Static lang:Resources.Label_OutputFolder}" />
<ComboBox
Grid.Row="1"
Grid.Column="0"
MinWidth="150"
Margin="4,0"
VerticalAlignment="Center"
ItemsSource="{Binding Categories}"
SelectedItem="{Binding SelectedCategory}">
<ComboBox.Styles>
<Style Selector="ComboBox /template/ ContentControl#ContentPresenter &gt; StackPanel &gt; TextBlock:nth-child(2)">
<Setter Property="IsVisible" Value="False" />
</Style>
</ComboBox.Styles>
<ComboBox.ItemTemplate>
<DataTemplate DataType="{x:Type models1:PackageOutputCategory}">
<StackPanel>
<TextBlock Margin="0,4,0,4" Text="{Binding Name, Mode=OneWay}" />
<TextBlock Text="{Binding Path, Mode=OneWay}" />
</StackPanel>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<TextBlock
Grid.Row="0"
Grid.Column="1"
Margin="4"
IsVisible="{Binding CanShowOutputTypes}"
Text="{x:Static lang:Resources.Label_OutputType}" />
<ComboBox
Grid.Row="1"
Grid.Column="1"
MinWidth="150"
Margin="4,0"
VerticalAlignment="Center"
VerticalContentAlignment="Center"
IsVisible="{Binding CanShowOutputTypes}"
ItemsSource="{Binding OutputTypes}"
SelectedItem="{Binding SelectedOutputType}" />
<TextBlock
Grid.Row="0"
Grid.Column="2"
Margin="4"
Text="{x:Static lang:Resources.Action_Search}" />
<TextBox <TextBox
Grid.Row="1" Grid.Row="1"
Grid.Column="2" Grid.Column="2"
@ -115,13 +82,6 @@
</TextBox.InnerRightContent> </TextBox.InnerRightContent>
</TextBox> </TextBox>
<TextBlock
Grid.Row="0"
Grid.Column="3"
Margin="4"
IsVisible="{Binding !!NumItemsSelected}"
Text="{Binding NumImagesSelected}" />
<ui:CommandBar <ui:CommandBar
Grid.Row="1" Grid.Row="1"
Grid.Column="3" Grid.Column="3"
@ -131,25 +91,54 @@
DefaultLabelPosition="Right"> DefaultLabelPosition="Right">
<ui:CommandBar.PrimaryCommands> <ui:CommandBar.PrimaryCommands>
<ui:CommandBarElementContainer>
<TextBlock Text="{Binding NumImagesSelected}"
IsVisible="{Binding NumItemsSelected}"
VerticalAlignment="Center"/>
</ui:CommandBarElementContainer>
<ui:CommandBarButton <ui:CommandBarButton
IsEnabled="{Binding !!NumItemsSelected}" IsEnabled="{Binding NumItemsSelected}"
Command="{Binding DeleteAllSelected}" Command="{Binding DeleteAllSelected}"
IconSource="Delete" /> IconSource="Delete" />
<ui:CommandBarSeparator /> <ui:CommandBarSeparator />
<ui:CommandBarButton <ui:CommandBarButton
Command="{Binding SelectAll}" Command="{Binding SelectAll}"
IsEnabled="{Binding !IsLoading}"
IconSource="SelectAll" IconSource="SelectAll"
Label="{x:Static lang:Resources.Action_SelectAll}" /> Label="{x:Static lang:Resources.Action_SelectAll}" />
<ui:CommandBarButton <ui:CommandBarButton
Command="{Binding ClearSelection}" Command="{Binding ClearSelection}"
IconSource="ClearSelection" IconSource="ClearSelection"
IsEnabled="{Binding !!NumItemsSelected}" IsEnabled="{Binding NumItemsSelected}"
Label="{x:Static lang:Resources.Action_ClearSelection}" /> Label="{x:Static lang:Resources.Action_ClearSelection}" />
<ui:CommandBarSeparator /> <ui:CommandBarSeparator />
<ui:CommandBarButton <ui:CommandBarButton
IconSource="Refresh" IconSource="Refresh"
Classes.loading="{Binding IsLoading}"
Command="{Binding Refresh}" Command="{Binding Refresh}"
Label="{x:Static lang:Resources.Action_Refresh}" /> IsEnabled="{Binding !IsLoading}"
Label="{x:Static lang:Resources.Action_Refresh}">
<ui:CommandBarButton.Styles>
<Style Selector="ui|CommandBarButton:disabled.loading">
<Style Selector="^ ui|SymbolIcon">
<Style.Animations>
<Animation Duration="0:0:2" IterationCount="INFINITE">
<KeyFrame Cue="0%">
<Setter Property="RotateTransform.Angle" Value="0"/>
</KeyFrame>
<KeyFrame Cue="100%">
<Setter Property="RotateTransform.Angle" Value="360"/>
</KeyFrame>
</Animation>
</Style.Animations>
</Style>
</Style>
</ui:CommandBarButton.Styles>
</ui:CommandBarButton>
<ui:CommandBarToggleButton
IconSource="List"
IsChecked="{Binding ShowFolders}"
Label="Show Folders"/>
</ui:CommandBar.PrimaryCommands> </ui:CommandBar.PrimaryCommands>
<ui:CommandBar.SecondaryCommands> <ui:CommandBar.SecondaryCommands>
@ -161,10 +150,21 @@
</ui:CommandBar> </ui:CommandBar>
</Grid> </Grid>
<scroll:BetterScrollViewer Grid.Row="1" PointerWheelChanged="ScrollViewer_MouseWheelChanged"> <controls:ProgressRing Grid.Row="1"
Grid.Column="1"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Width="200"
Height="200"
IsIndeterminate="True"
IsVisible="{Binding IsChangingCategory}"/>
<scroll:BetterScrollViewer Grid.Column="1"
Grid.Row="1" PointerWheelChanged="ScrollViewer_MouseWheelChanged">
<ItemsRepeater <ItemsRepeater
x:Name="ImageRepeater" x:Name="ImageRepeater"
VerticalAlignment="Top" VerticalAlignment="Top"
HorizontalAlignment="Center"
ItemsSource="{Binding Outputs}"> ItemsSource="{Binding Outputs}">
<ItemsRepeater.Layout> <ItemsRepeater.Layout>
<UniformGridLayout MinColumnSpacing="8" MinRowSpacing="8" /> <UniformGridLayout MinColumnSpacing="8" MinRowSpacing="8" />
@ -206,7 +206,8 @@
IconSource="Delete" IconSource="Delete"
Text="{x:Static lang:Resources.Action_Delete}" /> Text="{x:Static lang:Resources.Action_Delete}" />
<ui:MenuFlyoutSeparator IsVisible="{Binding ImageFile.GenerationParameters, Converter={x:Static ObjectConverters.IsNotNull}}" /> <ui:MenuFlyoutSeparator
IsVisible="{Binding ImageFile.GenerationParameters, Converter={x:Static ObjectConverters.IsNotNull}}" />
<ui:MenuFlyoutSubItem <ui:MenuFlyoutSubItem
IconSource="Share" IconSource="Share"

295
StabilityMatrix.Avalonia/Views/PackageManagerPage.axaml

@ -10,15 +10,23 @@
xmlns:icons="clr-namespace:Projektanker.Icons.Avalonia;assembly=Projektanker.Icons.Avalonia" xmlns:icons="clr-namespace:Projektanker.Icons.Avalonia;assembly=Projektanker.Icons.Avalonia"
xmlns:lang="clr-namespace:StabilityMatrix.Avalonia.Languages" xmlns:lang="clr-namespace:StabilityMatrix.Avalonia.Languages"
xmlns:system="clr-namespace:System;assembly=System.Runtime" xmlns:system="clr-namespace:System;assembly=System.Runtime"
mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450" xmlns:converters="clr-namespace:StabilityMatrix.Avalonia.Converters"
xmlns:avalonia="clr-namespace:SpacedGridControl.Avalonia;assembly=SpacedGridControl.Avalonia"
xmlns:markupExtensions="clr-namespace:StabilityMatrix.Avalonia.MarkupExtensions"
mc:Ignorable="d" d:DesignWidth="1000" d:DesignHeight="450"
x:DataType="viewModels:PackageManagerViewModel" x:DataType="viewModels:PackageManagerViewModel"
x:CompileBindings="True" x:CompileBindings="True"
d:DataContext="{x:Static designData:DesignData.PackageManagerViewModel}" d:DataContext="{x:Static designData:DesignData.PackageManagerViewModel}"
x:Class="StabilityMatrix.Avalonia.Views.PackageManagerPage"> x:Class="StabilityMatrix.Avalonia.Views.PackageManagerPage">
<controls:UserControlBase.Resources>
<converters:BooleanChoiceMultiConverter x:Key="BoolChoiceMultiConverter" />
</controls:UserControlBase.Resources>
<Grid Margin="16" RowDefinitions="Auto,*,Auto"> <Grid Margin="16" RowDefinitions="Auto,*,Auto">
<ScrollViewer Grid.Row="1"> <ScrollViewer Grid.Row="1">
<ItemsRepeater <ItemsRepeater
x:Name="PackageCardsRepeater"
ItemsSource="{Binding PackageCards}"> ItemsSource="{Binding PackageCards}">
<ItemsRepeater.Layout> <ItemsRepeater.Layout>
<UniformGridLayout MinColumnSpacing="12" MinRowSpacing="12" /> <UniformGridLayout MinColumnSpacing="12" MinRowSpacing="12" />
@ -26,16 +34,64 @@
<ItemsRepeater.ItemTemplate> <ItemsRepeater.ItemTemplate>
<DataTemplate DataType="{x:Type packageManager:PackageCardViewModel}"> <DataTemplate DataType="{x:Type packageManager:PackageCardViewModel}">
<controls:Card Padding="8" <controls:Card Padding="8"
MinWidth="400"
CornerRadius="8"> CornerRadius="8">
<Grid RowDefinitions="Auto, Auto, Auto, Auto" <controls:Card.Background>
ColumnDefinitions="*,Auto"> <MultiBinding Converter="{StaticResource BoolChoiceMultiConverter}">
<Binding Path="IsRunning" />
<TextBlock Grid.Row="0" <DynamicResource ResourceKey="ThemeDarkDarkGreenColorBrush" />
<DynamicResource ResourceKey="ButtonBackground" />
</MultiBinding>
</controls:Card.Background>
<Grid ColumnDefinitions="Auto, *">
<controls:BetterAdvancedImage
Grid.Column="0"
Height="150"
Width="150"
Margin="4, 8"
CornerRadius="8"
HorizontalAlignment="Center"
VerticalContentAlignment="Top"
HorizontalContentAlignment="Center"
Source="{Binding CardImageSource}"
IsVisible="{Binding !IsUnknownPackage}"
Stretch="UniformToFill" />
<Border
Grid.Column="0" Grid.Column="0"
ToolTip.Tip="{Binding Package.DisplayName, FallbackValue=''}" Height="150"
Text="{Binding Package.DisplayName, FallbackValue=''}" Width="150"
TextTrimming="WordEllipsis" Margin="4, 8"
TextAlignment="Left" /> CornerRadius="8"
HorizontalAlignment="Center"
IsVisible="{Binding IsUnknownPackage}"
Background="#202020">
<TextBlock
TextAlignment="Center"
VerticalAlignment="Center"
FontSize="18"
TextWrapping="Wrap"
Text="{x:Static lang:Resources.Label_UnknownPackage}" />
</Border>
<Grid Grid.Column="1" RowDefinitions="Auto, Auto, Auto, *"
ColumnDefinitions="Auto, *">
<TextBlock Grid.Column="0"
Grid.Row="0"
Text="{Binding Package.DisplayName}"
Margin="8,0,8,0"
FontWeight="SemiBold"
MaxWidth="200"
TextWrapping="NoWrap"
TextTrimming="CharacterEllipsis"
ToolTip.Tip="{Binding Package.DisplayName}"
FontSize="16" />
<TextBlock Grid.Column="0"
Grid.Row="1"
FontSize="13"
Foreground="{DynamicResource TextControlPlaceholderForeground}"
Margin="8,0,8,0"
VerticalAlignment="Center"
Text="{Binding InstalledVersion}" />
<Button <Button
Grid.Row="0" Grid.Row="0"
Grid.Column="1" Grid.Column="1"
@ -43,7 +99,7 @@
HorizontalAlignment="Right" HorizontalAlignment="Right"
VerticalContentAlignment="Top" VerticalContentAlignment="Top"
VerticalAlignment="Top" VerticalAlignment="Top"
Padding="4,1" Padding="4"
Margin="4,0,0,0" Margin="4,0,0,0"
Classes="transparent" Classes="transparent"
Width="24" Width="24"
@ -98,7 +154,8 @@
<Separator IsVisible="{Binding CanUseSharedOutput}" /> <Separator IsVisible="{Binding CanUseSharedOutput}" />
<MenuItem Header="{x:Static lang:Resources.Label_SharedModelStrategyShort}" <MenuItem
Header="{x:Static lang:Resources.Label_SharedModelStrategyShort}"
IsVisible="{Binding !IsUnknownPackage}"> IsVisible="{Binding !IsUnknownPackage}">
<MenuItem.Icon> <MenuItem.Icon>
<ui:SymbolIcon Symbol="FolderLink" /> <ui:SymbolIcon Symbol="FolderLink" />
@ -173,61 +230,89 @@
</Button.Flyout> </Button.Flyout>
</Button> </Button>
<TextBlock Grid.Row="1" <StackPanel Grid.Row="2"
Grid.Column="0" Grid.Column="0"
Grid.ColumnSpan="2" Margin="0,4,0,0"
Margin="2,0,0,0" Orientation="Horizontal">
VerticalAlignment="Center" <Button Classes="transparent-full"
Text="{Binding InstalledVersion}" /> Margin="4,4,0,0"
Padding="4"
ToolTip.Tip="{x:Static lang:Resources.Action_CheckForUpdates}"
Command="{Binding OnLoadedAsync}"
>
<Button.IsVisible>
<MultiBinding Converter="{x:Static BoolConverters.And}">
<Binding Path="!IsUnknownPackage" />
<Binding Path="!IsUpdateAvailable" />
</MultiBinding>
</Button.IsVisible>
<ui:SymbolIcon Symbol="Refresh"
FontSize="20"/>
</Button>
<!-- Normal packages shows image --> <Button Classes="transparent-full"
<controls:BetterAdvancedImage Margin="4,4,0,0"
Grid.Row="2" Padding="4"
Grid.Column="0" IsEnabled="{Binding !IsRunning}"
Grid.ColumnSpan="2" ToolTip.Tip="{x:Static lang:Resources.Label_UpdateAvailable}"
Margin="0,8,0,8" markupExtensions:ShowDisabledTooltipExtension.ShowOnDisabled="True"
Height="180" Command="{Binding Update}">
Width="225" <Button.IsVisible>
CornerRadius="4" <MultiBinding Converter="{x:Static BoolConverters.And}">
HorizontalAlignment="Center" <Binding Path="!IsUnknownPackage" />
VerticalContentAlignment="Top" <Binding Path="IsUpdateAvailable" />
HorizontalContentAlignment="Center" </MultiBinding>
Source="{Binding CardImageSource}" </Button.IsVisible>
<ui:SymbolIcon Symbol="CloudDownload"
IsEnabled="{Binding !IsRunning}"
FontSize="24">
<ui:SymbolIcon.Styles>
<Style Selector="ui|SymbolIcon">
<Setter Property="Foreground" Value="Lime" />
</Style>
<Style Selector="ui|SymbolIcon:disabled">
<Setter Property="Foreground" Value="Gray" />
</Style>
</ui:SymbolIcon.Styles>
</ui:SymbolIcon>
</Button>
<Button Classes="transparent-full"
Margin="4,4,0,0"
Padding="4"
ToolTip.Tip="Launch Options"
IsVisible="{Binding !IsUnknownPackage}" IsVisible="{Binding !IsUnknownPackage}"
Stretch="UniformToFill" /> Command="{Binding ShowLaunchOptionsCommand}">
<ui:SymbolIcon Symbol="SettingsFilled"
<!-- Unknown packages panel --> FontSize="20"/>
<Border </Button>
Grid.Row="2" <Button Classes="transparent-full"
Grid.Column="0" Margin="6,2,0,0"
Grid.ColumnSpan="2" Padding="4"
Margin="0,8,0,8" ToolTip.Tip="Extensions"
Height="180" IsVisible="{Binding CanUseExtensions}"
Width="225" Command="{Binding OpenExtensionsDialogCommand}">
CornerRadius="4" <icons:Icon FontSize="18"
HorizontalAlignment="Center" HorizontalAlignment="Center"
IsVisible="{Binding IsUnknownPackage}"
Background="#202020">
<TextBlock
TextAlignment="Center"
VerticalAlignment="Center" VerticalAlignment="Center"
FontSize="18" Value="fa-solid fa-puzzle-piece" />
TextWrapping="Wrap" </Button>
Text="{x:Static lang:Resources.Label_UnknownPackage}" /> </StackPanel>
</Border> <UniformGrid Grid.Column="0"
<Grid
Grid.Row="3"
Grid.Column="0"
Grid.ColumnSpan="2" Grid.ColumnSpan="2"
IsVisible="{Binding IsUpdateAvailable}" Grid.Row="3"
ColumnDefinitions="*, *"> VerticalAlignment="Bottom"
<!-- Launch and update buttons --> Margin="8,8,8,0">
<Button Grid.Column="0" Classes="accent" <Button Classes="accent"
Name="LaunchButton"
VerticalAlignment="Bottom" VerticalAlignment="Bottom"
HorizontalAlignment="Stretch" HorizontalAlignment="Stretch"
Command="{Binding Launch}"> Command="{Binding Launch}">
<Button.IsVisible>
<MultiBinding Converter="{x:Static BoolConverters.And}">
<Binding Path="!IsRunning" />
<Binding Path="!IsUnknownPackage" />
</MultiBinding>
</Button.IsVisible>
<StackPanel Orientation="Horizontal" Margin="0,2,0,2"> <StackPanel Orientation="Horizontal" Margin="0,2,0,2">
<icons:Icon Value="fa-solid fa-rocket" <icons:Icon Value="fa-solid fa-rocket"
Margin="0,0,8,0" Margin="0,0,8,0"
@ -235,45 +320,59 @@
<TextBlock Text="{x:Static lang:Resources.Action_Launch}" /> <TextBlock Text="{x:Static lang:Resources.Action_Launch}" />
</StackPanel> </StackPanel>
</Button> </Button>
<Button Grid.Column="1" Classes="accent" <Button Classes="borderless-danger"
VerticalAlignment="Bottom" VerticalAlignment="Bottom"
HorizontalAlignment="Stretch" HorizontalAlignment="Stretch"
Command="{Binding Update}"> IsVisible="{Binding IsRunning}"
<StackPanel Orientation="Horizontal" Margin="0,2,0,2"> Command="{Binding StopCommand}">
<icons:Icon Value="fa-solid fa-download" <StackPanel Orientation="Horizontal"
Margin="0,2">
<icons:Icon Value="fa-solid fa-stop"
Margin="0,0,8,0" Margin="0,0,8,0"
FontSize="14" /> FontSize="14" />
<TextBlock Text="{x:Static lang:Resources.Action_Update}" /> <TextBlock Text="{x:Static lang:Resources.Action_Stop}" />
</StackPanel> </StackPanel>
</Button> </Button>
</Grid> <Button Classes="borderless-info"
BorderBrush="Transparent"
<!-- Big launch button -->
<Button
Grid.Row="3"
Grid.Column="0"
Grid.ColumnSpan="2"
Classes="accent"
VerticalAlignment="Bottom" VerticalAlignment="Bottom"
Command="{Binding Launch}" HorizontalAlignment="Stretch"
HorizontalAlignment="Stretch"> IsVisible="{Binding IsRunning}"
<Button.IsVisible> Command="{Binding RestartCommand}">
<MultiBinding Converter="{x:Static BoolConverters.And}"> <StackPanel Orientation="Horizontal"
<Binding Path="!IsUpdateAvailable" /> Margin="0,2">
<Binding Path="!IsUnknownPackage" /> <icons:Icon Value="fa-solid fa-arrow-rotate-left"
</MultiBinding>
</Button.IsVisible>
<StackPanel Orientation="Horizontal" Margin="0,2,0,2">
<icons:Icon Value="fa-solid fa-rocket"
Margin="0,0,8,0" Margin="0,0,8,0"
FontSize="14" /> FontSize="14" />
<TextBlock Text="{x:Static lang:Resources.Action_Launch}" /> <TextBlock Text="{x:Static lang:Resources.Action_Restart}" />
</StackPanel> </StackPanel>
</Button> </Button>
<Button Classes="accent"
<!-- Import button (for unknown) --> VerticalAlignment="Bottom"
<Button Grid.Row="3" Grid.Column="0" Classes="transparent-info" HorizontalAlignment="Stretch"
Grid.ColumnSpan="2" IsVisible="{Binding IsRunning}"
Command="{Binding NavToConsole}">
<StackPanel Orientation="Horizontal"
Margin="0,2,0,2">
<icons:Icon Value="fa-solid fa-terminal"
Margin="0,0,8,0"
FontSize="14" />
<TextBlock Text="{x:Static lang:Resources.Label_Console}" />
</StackPanel>
</Button>
<Button Classes="accent"
VerticalAlignment="Bottom"
HorizontalAlignment="Stretch"
IsVisible="{Binding ShowWebUiButton}"
Command="{Binding LaunchWebUi}">
<StackPanel Orientation="Horizontal" Margin="8,2,8,2">
<icons:Icon Value="fa-solid fa-up-right-from-square"
Margin="0,0,8,0"
FontSize="14" />
<TextBlock Text="{x:Static lang:Resources.Label_WebUi}" />
</StackPanel>
</Button>
<Button Classes="transparent-info"
VerticalAlignment="Bottom" VerticalAlignment="Bottom"
HorizontalAlignment="Stretch" HorizontalAlignment="Stretch"
Command="{Binding Import}" Command="{Binding Import}"
@ -285,29 +384,28 @@
<TextBlock Text="{x:Static lang:Resources.Action_Import}" /> <TextBlock Text="{x:Static lang:Resources.Action_Import}" />
</StackPanel> </StackPanel>
</Button> </Button>
</UniformGrid>
</Grid>
<!-- Update overlay --> <!-- Update overlay -->
<Border <Border
Grid.Row="0" Grid.RowSpan="4"
Grid.Column="0" Grid.Column="0"
Grid.ColumnSpan="2" Grid.ColumnSpan="2"
Background="#DD000000" Background="#DD000000"
CornerRadius="4" CornerRadius="8"
HorizontalAlignment="Stretch" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" VerticalAlignment="Stretch"
IsVisible="{Binding IsProgressVisible}"/> IsVisible="{Binding IsProgressVisible}"/>
<Grid Grid.Row="0" Grid.RowSpan="4" <Grid Grid.Column="0"
Grid.Column="0"
Grid.ColumnSpan="2" Grid.ColumnSpan="2"
HorizontalAlignment="Center" HorizontalAlignment="Center"
VerticalAlignment="Center" VerticalAlignment="Center"
RowDefinitions="Auto, *" IsVisible="{Binding IsProgressVisible}"
IsVisible="{Binding IsProgressVisible}"> RowDefinitions="Auto, *">
<controls:ProgressRing <controls:ProgressRing
HorizontalAlignment="Center" HorizontalAlignment="Center"
IsIndeterminate="{Binding IsIndeterminate}" IsIndeterminate="{Binding IsIndeterminate}"
Width="150" Width="120"
Height="150" Height="120"
StartAngle="90" StartAngle="90"
EndAngle="450" EndAngle="450"
Value="{Binding Value}" Value="{Binding Value}"
@ -335,6 +433,15 @@
PreferredPlacement="Top" PreferredPlacement="Top"
IsOpen="{Binding !Packages.Count}" /> IsOpen="{Binding !Packages.Count}" />
<ui:TeachingTip Grid.Row="0"
Name="LaunchTeachingTip"
MinWidth="100"
Title="{x:Static lang:Resources.TeachingTip_ClickLaunchToGetStarted}"
PreferredPlacement="Bottom"
Margin="8,0,0,0"
PlacementMargin="0,0,0,0"
TailVisibility="Auto"/>
<!-- Add Packages Button --> <!-- Add Packages Button -->
<Button Grid.Row="2" <Button Grid.Row="2"
Classes="transparent" Classes="transparent"

33
StabilityMatrix.Avalonia/Views/PackageManagerPage.axaml.cs

@ -1,12 +1,18 @@
using Avalonia.Interactivity; using System.Linq;
using System.Threading.Tasks;
using Avalonia.Controls;
using Avalonia.Controls.Primitives;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml; using Avalonia.Markup.Xaml;
using Avalonia.Threading; using Avalonia.Threading;
using Avalonia.VisualTree;
using FluentAvalonia.UI.Controls; using FluentAvalonia.UI.Controls;
using FluentAvalonia.UI.Navigation; using FluentAvalonia.UI.Navigation;
using StabilityMatrix.Avalonia.Controls; using StabilityMatrix.Avalonia.Controls;
using StabilityMatrix.Avalonia.Models; using StabilityMatrix.Avalonia.Models;
using StabilityMatrix.Avalonia.ViewModels; using StabilityMatrix.Avalonia.ViewModels;
using StabilityMatrix.Core.Attributes; using StabilityMatrix.Core.Attributes;
using StabilityMatrix.Core.Helper;
using StabilityMatrix.Core.Models.Packages; using StabilityMatrix.Core.Models.Packages;
namespace StabilityMatrix.Avalonia.Views; namespace StabilityMatrix.Avalonia.Views;
@ -19,6 +25,31 @@ public partial class PackageManagerPage : UserControlBase
InitializeComponent(); InitializeComponent();
AddHandler(Frame.NavigatedToEvent, OnNavigatedTo, RoutingStrategies.Direct); AddHandler(Frame.NavigatedToEvent, OnNavigatedTo, RoutingStrategies.Direct);
EventManager.Instance.OneClickInstallFinished += OnOneClickInstallFinished;
}
private void OnOneClickInstallFinished(object? sender, bool skipped)
{
if (skipped)
return;
Dispatcher.UIThread.Invoke(() =>
{
var target = this.FindDescendantOfType<UniformGrid>()
?.GetVisualChildren()
.OfType<Button>()
.FirstOrDefault(x => x is { Name: "LaunchButton" });
if (target == null)
return;
var teachingTip = this.FindControl<TeachingTip>("LaunchTeachingTip");
if (teachingTip == null)
return;
teachingTip.Target = target;
teachingTip.IsOpen = true;
});
} }
private void InitializeComponent() private void InitializeComponent()

6
StabilityMatrix.Core/Attributes/TypedNodeOptionsAttribute.cs

@ -1,4 +1,5 @@
using StabilityMatrix.Core.Models.Api.Comfy.Nodes; using StabilityMatrix.Core.Models.Api.Comfy.Nodes;
using StabilityMatrix.Core.Models.Packages.Extensions;
namespace StabilityMatrix.Core.Attributes; namespace StabilityMatrix.Core.Attributes;
@ -11,4 +12,9 @@ public class TypedNodeOptionsAttribute : Attribute
public string? Name { get; init; } public string? Name { get; init; }
public string[]? RequiredExtensions { get; init; } public string[]? RequiredExtensions { get; init; }
public IEnumerable<ExtensionSpecifier> GetRequiredExtensionSpecifiers()
{
return RequiredExtensions?.Select(ExtensionSpecifier.Parse) ?? Enumerable.Empty<ExtensionSpecifier>();
}
} }

8
StabilityMatrix.Core/Helper/EventManager.cs

@ -23,6 +23,7 @@ public class EventManager
public event EventHandler<bool>? DevModeSettingChanged; public event EventHandler<bool>? DevModeSettingChanged;
public event EventHandler<UpdateInfo>? UpdateAvailable; public event EventHandler<UpdateInfo>? UpdateAvailable;
public event EventHandler<Guid>? PackageLaunchRequested; public event EventHandler<Guid>? PackageLaunchRequested;
public event EventHandler<InstalledPackage>? PackageRelaunchRequested;
public event EventHandler? ScrollToBottomRequested; public event EventHandler? ScrollToBottomRequested;
public event EventHandler<ProgressItem>? ProgressChanged; public event EventHandler<ProgressItem>? ProgressChanged;
public event EventHandler<RunningPackageStatusChangedEventArgs>? RunningPackageStatusChanged; public event EventHandler<RunningPackageStatusChangedEventArgs>? RunningPackageStatusChanged;
@ -41,6 +42,7 @@ public class EventManager
public event EventHandler<LocalImageFile>? InferenceUpscaleRequested; public event EventHandler<LocalImageFile>? InferenceUpscaleRequested;
public event EventHandler<LocalImageFile>? InferenceImageToImageRequested; public event EventHandler<LocalImageFile>? InferenceImageToImageRequested;
public event EventHandler<LocalImageFile>? InferenceImageToVideoRequested; public event EventHandler<LocalImageFile>? InferenceImageToVideoRequested;
public event EventHandler<InferenceQueueCustomPromptEventArgs>? InferenceQueueCustomPrompt;
public event EventHandler<int>? NavigateAndFindCivitModelRequested; public event EventHandler<int>? NavigateAndFindCivitModelRequested;
public event EventHandler? DownloadsTeachingTipRequested; public event EventHandler? DownloadsTeachingTipRequested;
public event EventHandler? RecommendedModelsDialogClosed; public event EventHandler? RecommendedModelsDialogClosed;
@ -92,6 +94,9 @@ public class EventManager
public void OnInferenceImageToVideoRequested(LocalImageFile imageFile) => public void OnInferenceImageToVideoRequested(LocalImageFile imageFile) =>
InferenceImageToVideoRequested?.Invoke(this, imageFile); InferenceImageToVideoRequested?.Invoke(this, imageFile);
public void OnInferenceQueueCustomPrompt(InferenceQueueCustomPromptEventArgs e) =>
InferenceQueueCustomPrompt?.Invoke(this, e);
public void OnNavigateAndFindCivitModelRequested(int modelId) => public void OnNavigateAndFindCivitModelRequested(int modelId) =>
NavigateAndFindCivitModelRequested?.Invoke(this, modelId); NavigateAndFindCivitModelRequested?.Invoke(this, modelId);
@ -100,4 +105,7 @@ public class EventManager
public void OnRecommendedModelsDialogClosed() => public void OnRecommendedModelsDialogClosed() =>
RecommendedModelsDialogClosed?.Invoke(this, EventArgs.Empty); RecommendedModelsDialogClosed?.Invoke(this, EventArgs.Empty);
public void OnPackageRelaunchRequested(InstalledPackage package) =>
PackageRelaunchRequested?.Invoke(this, package);
} }

1
StabilityMatrix.Core/Helper/Factory/IPackageFactory.cs

@ -10,4 +10,5 @@ public interface IPackageFactory
BasePackage? this[string packageName] { get; } BasePackage? this[string packageName] { get; }
PackagePair? GetPackagePair(InstalledPackage? installedPackage); PackagePair? GetPackagePair(InstalledPackage? installedPackage);
IEnumerable<BasePackage> GetPackagesByType(PackageType packageType); IEnumerable<BasePackage> GetPackagesByType(PackageType packageType);
BasePackage GetNewBasePackage(InstalledPackage installedPackage);
} }

74
StabilityMatrix.Core/Helper/Factory/PackageFactory.cs

@ -1,22 +1,94 @@
using StabilityMatrix.Core.Attributes; using StabilityMatrix.Core.Attributes;
using StabilityMatrix.Core.Helper.Cache;
using StabilityMatrix.Core.Models; using StabilityMatrix.Core.Models;
using StabilityMatrix.Core.Models.Packages; using StabilityMatrix.Core.Models.Packages;
using StabilityMatrix.Core.Python;
using StabilityMatrix.Core.Services;
namespace StabilityMatrix.Core.Helper.Factory; namespace StabilityMatrix.Core.Helper.Factory;
[Singleton(typeof(IPackageFactory))] [Singleton(typeof(IPackageFactory))]
public class PackageFactory : IPackageFactory public class PackageFactory : IPackageFactory
{ {
private readonly IGithubApiCache githubApiCache;
private readonly ISettingsManager settingsManager;
private readonly IDownloadService downloadService;
private readonly IPrerequisiteHelper prerequisiteHelper;
private readonly IPyRunner pyRunner;
/// <summary> /// <summary>
/// Mapping of package.Name to package /// Mapping of package.Name to package
/// </summary> /// </summary>
private readonly Dictionary<string, BasePackage> basePackages; private readonly Dictionary<string, BasePackage> basePackages;
public PackageFactory(IEnumerable<BasePackage> basePackages) public PackageFactory(
IEnumerable<BasePackage> basePackages,
IGithubApiCache githubApiCache,
ISettingsManager settingsManager,
IDownloadService downloadService,
IPrerequisiteHelper prerequisiteHelper,
IPyRunner pyRunner
)
{ {
this.githubApiCache = githubApiCache;
this.settingsManager = settingsManager;
this.downloadService = downloadService;
this.prerequisiteHelper = prerequisiteHelper;
this.pyRunner = pyRunner;
this.basePackages = basePackages.ToDictionary(x => x.Name); this.basePackages = basePackages.ToDictionary(x => x.Name);
} }
public BasePackage GetNewBasePackage(InstalledPackage installedPackage)
{
return installedPackage.PackageName switch
{
"ComfyUI" => new ComfyUI(githubApiCache, settingsManager, downloadService, prerequisiteHelper),
"Fooocus" => new Fooocus(githubApiCache, settingsManager, downloadService, prerequisiteHelper),
"stable-diffusion-webui"
=> new A3WebUI(githubApiCache, settingsManager, downloadService, prerequisiteHelper),
"Fooocus-ControlNet-SDXL"
=> new FocusControlNet(githubApiCache, settingsManager, downloadService, prerequisiteHelper),
"Fooocus-MRE"
=> new FooocusMre(githubApiCache, settingsManager, downloadService, prerequisiteHelper),
"InvokeAI" => new InvokeAI(githubApiCache, settingsManager, downloadService, prerequisiteHelper),
"kohya_ss"
=> new KohyaSs(
githubApiCache,
settingsManager,
downloadService,
prerequisiteHelper,
pyRunner
),
"OneTrainer"
=> new OneTrainer(githubApiCache, settingsManager, downloadService, prerequisiteHelper),
"RuinedFooocus"
=> new RuinedFooocus(githubApiCache, settingsManager, downloadService, prerequisiteHelper),
"stable-diffusion-webui-forge"
=> new SDWebForge(githubApiCache, settingsManager, downloadService, prerequisiteHelper),
"stable-diffusion-webui-directml"
=> new StableDiffusionDirectMl(
githubApiCache,
settingsManager,
downloadService,
prerequisiteHelper
),
"stable-diffusion-webui-ux"
=> new StableDiffusionUx(
githubApiCache,
settingsManager,
downloadService,
prerequisiteHelper
),
"StableSwarmUI"
=> new StableSwarm(githubApiCache, settingsManager, downloadService, prerequisiteHelper),
"automatic"
=> new VladAutomatic(githubApiCache, settingsManager, downloadService, prerequisiteHelper),
"voltaML-fast-stable-diffusion"
=> new VoltaML(githubApiCache, settingsManager, downloadService, prerequisiteHelper),
_ => throw new ArgumentOutOfRangeException(nameof(installedPackage))
};
}
public IEnumerable<BasePackage> GetAllAvailablePackages() public IEnumerable<BasePackage> GetAllAvailablePackages()
{ {
return basePackages.Values.OrderBy(p => p.InstallerSortOrder).ThenBy(p => p.DisplayName); return basePackages.Values.OrderBy(p => p.InstallerSortOrder).ThenBy(p => p.DisplayName);

16
StabilityMatrix.Core/Inference/ComfyClient.cs

@ -460,6 +460,22 @@ public class ComfyClient : InferenceClientBase
return info.Input.GetRequiredValueAsNestedList(optionName); return info.Input.GetRequiredValueAsNestedList(optionName);
} }
/// <summary>
/// Get a list of strings representing available optional options of a given node
/// </summary>
public async Task<List<string>?> GetOptionalNodeOptionNamesAsync(
string nodeName,
string optionName,
CancellationToken cancellationToken = default
)
{
var response = await comfyApi.GetObjectInfo(nodeName, cancellationToken).ConfigureAwait(false);
var info = response.GetValueOrDefault(nodeName);
return info?.Input.GetOptionalValueAsNestedList(optionName);
}
protected override void Dispose(bool disposing) protected override void Dispose(bool disposing)
{ {
if (isDisposed) if (isDisposed)

124
StabilityMatrix.Core/Models/Api/Comfy/ComfyAuxPreprocessor.cs

@ -0,0 +1,124 @@
using System.Diagnostics.CodeAnalysis;
using JetBrains.Annotations;
namespace StabilityMatrix.Core.Models.Api.Comfy;
/// <summary>
/// Collection of preprocessors included in
/// </summary>
/// <param name="Value"></param>
[PublicAPI]
[SuppressMessage("ReSharper", "InconsistentNaming")]
public record ComfyAuxPreprocessor(string Value) : StringValue(Value)
{
public static ComfyAuxPreprocessor None { get; } = new("none");
public static ComfyAuxPreprocessor AnimeFaceSemSegPreprocessor { get; } =
new("AnimeFace_SemSegPreprocessor");
public static ComfyAuxPreprocessor BinaryPreprocessor { get; } = new("BinaryPreprocessor");
public static ComfyAuxPreprocessor CannyEdgePreprocessor { get; } = new("CannyEdgePreprocessor");
public static ComfyAuxPreprocessor ColorPreprocessor { get; } = new("ColorPreprocessor");
public static ComfyAuxPreprocessor DensePosePreprocessor { get; } = new("DensePosePreprocessor");
public static ComfyAuxPreprocessor DepthAnythingPreprocessor { get; } = new("DepthAnythingPreprocessor");
public static ComfyAuxPreprocessor ZoeDepthAnythingPreprocessor { get; } =
new("Zoe_DepthAnythingPreprocessor");
public static ComfyAuxPreprocessor DiffusionEdgePreprocessor { get; } = new("DiffusionEdge_Preprocessor");
public static ComfyAuxPreprocessor DWPreprocessor { get; } = new("DWPreprocessor");
public static ComfyAuxPreprocessor AnimalPosePreprocessor { get; } = new("AnimalPosePreprocessor");
public static ComfyAuxPreprocessor HEDPreprocessor { get; } = new("HEDPreprocessor");
public static ComfyAuxPreprocessor FakeScribblePreprocessor { get; } = new("FakeScribblePreprocessor");
public static ComfyAuxPreprocessor LeReSDepthMapPreprocessor { get; } = new("LeReS-DepthMapPreprocessor");
public static ComfyAuxPreprocessor LineArtPreprocessor { get; } = new("LineArtPreprocessor");
public static ComfyAuxPreprocessor AnimeLineArtPreprocessor { get; } = new("AnimeLineArtPreprocessor");
public static ComfyAuxPreprocessor LineartStandardPreprocessor { get; } =
new("LineartStandardPreprocessor");
public static ComfyAuxPreprocessor Manga2AnimeLineArtPreprocessor { get; } =
new("Manga2Anime_LineArt_Preprocessor");
public static ComfyAuxPreprocessor MediaPipeFaceMeshPreprocessor { get; } =
new("MediaPipe-FaceMeshPreprocessor");
public static ComfyAuxPreprocessor MeshGraphormerDepthMapPreprocessor { get; } =
new("MeshGraphormer-DepthMapPreprocessor");
public static ComfyAuxPreprocessor MiDaSNormalMapPreprocessor { get; } =
new("MiDaS-NormalMapPreprocessor");
public static ComfyAuxPreprocessor MiDaSDepthMapPreprocessor { get; } = new("MiDaS-DepthMapPreprocessor");
public static ComfyAuxPreprocessor MLSDPreprocessor { get; } = new("M-LSDPreprocessor");
public static ComfyAuxPreprocessor BAENormalMapPreprocessor { get; } = new("BAE-NormalMapPreprocessor");
public static ComfyAuxPreprocessor OneFormerCOCOSemSegPreprocessor { get; } =
new("OneFormer-COCO-SemSegPreprocessor");
public static ComfyAuxPreprocessor OneFormerADE20KSemSegPreprocessor { get; } =
new("OneFormer-ADE20K-SemSegPreprocessor");
public static ComfyAuxPreprocessor OpenposePreprocessor { get; } = new("OpenposePreprocessor");
public static ComfyAuxPreprocessor PiDiNetPreprocessor { get; } = new("PiDiNetPreprocessor");
public static ComfyAuxPreprocessor SavePoseKpsAsJsonFile { get; } = new("SavePoseKpsAsJsonFile");
public static ComfyAuxPreprocessor FacialPartColoringFromPoseKps { get; } =
new("FacialPartColoringFromPoseKps");
public static ComfyAuxPreprocessor ImageLuminanceDetector { get; } = new("ImageLuminanceDetector");
public static ComfyAuxPreprocessor ImageIntensityDetector { get; } = new("ImageIntensityDetector");
public static ComfyAuxPreprocessor ScribblePreprocessor { get; } = new("ScribblePreprocessor");
public static ComfyAuxPreprocessor ScribbleXDoGPreprocessor { get; } = new("Scribble_XDoG_Preprocessor");
public static ComfyAuxPreprocessor SAMPreprocessor { get; } = new("SAMPreprocessor");
public static ComfyAuxPreprocessor ShufflePreprocessor { get; } = new("ShufflePreprocessor");
public static ComfyAuxPreprocessor TEEDPreprocessor { get; } = new("TEEDPreprocessor");
public static ComfyAuxPreprocessor TilePreprocessor { get; } = new("TilePreprocessor");
public static ComfyAuxPreprocessor UniFormerSemSegPreprocessor { get; } =
new("UniFormer-SemSegPreprocessor");
public static ComfyAuxPreprocessor SemSegPreprocessor { get; } = new("SemSegPreprocessor");
public static ComfyAuxPreprocessor UnimatchOptFlowPreprocessor { get; } =
new("Unimatch_OptFlowPreprocessor");
public static ComfyAuxPreprocessor MaskOptFlow { get; } = new("MaskOptFlow");
public static ComfyAuxPreprocessor ZoeDepthMapPreprocessor { get; } = new("Zoe-DepthMapPreprocessor");
private static Dictionary<ComfyAuxPreprocessor, string> DisplayNamesMapping { get; } =
new()
{
[None] = "None",
[AnimeFaceSemSegPreprocessor] = "Anime Face SemSeg Preprocessor",
[BinaryPreprocessor] = "Binary Preprocessor",
[CannyEdgePreprocessor] = "Canny Edge Preprocessor",
[ColorPreprocessor] = "Color Preprocessor",
[DensePosePreprocessor] = "DensePose Preprocessor",
[DepthAnythingPreprocessor] = "Depth Anything Preprocessor",
[ZoeDepthAnythingPreprocessor] = "Zoe Depth Anything Preprocessor",
[DiffusionEdgePreprocessor] = "Diffusion Edge Preprocessor",
[DWPreprocessor] = "DW Preprocessor",
[AnimalPosePreprocessor] = "Animal Pose Preprocessor",
[HEDPreprocessor] = "HED Preprocessor",
[FakeScribblePreprocessor] = "Fake Scribble Preprocessor",
[LeReSDepthMapPreprocessor] = "LeReS-DepthMap Preprocessor",
[LineArtPreprocessor] = "LineArt Preprocessor",
[AnimeLineArtPreprocessor] = "Anime LineArt Preprocessor",
[LineartStandardPreprocessor] = "Lineart Standard Preprocessor",
[Manga2AnimeLineArtPreprocessor] = "Manga2Anime LineArt Preprocessor",
[MediaPipeFaceMeshPreprocessor] = "MediaPipe FaceMesh Preprocessor",
[MeshGraphormerDepthMapPreprocessor] = "MeshGraphormer DepthMap Preprocessor",
[MiDaSNormalMapPreprocessor] = "MiDaS NormalMap Preprocessor",
[MiDaSDepthMapPreprocessor] = "MiDaS DepthMap Preprocessor",
[MLSDPreprocessor] = "M-LSD Preprocessor",
[BAENormalMapPreprocessor] = "BAE NormalMap Preprocessor",
[OneFormerCOCOSemSegPreprocessor] = "OneFormer COCO SemSeg Preprocessor",
[OneFormerADE20KSemSegPreprocessor] = "OneFormer ADE20K SemSeg Preprocessor",
[OpenposePreprocessor] = "Openpose Preprocessor",
[PiDiNetPreprocessor] = "PiDiNet Preprocessor",
[SavePoseKpsAsJsonFile] = "Save Pose Kps As Json File",
[FacialPartColoringFromPoseKps] = "Facial Part Coloring From Pose Kps",
[ImageLuminanceDetector] = "Image Luminance Detector",
[ImageIntensityDetector] = "Image Intensity Detector",
[ScribblePreprocessor] = "Scribble Preprocessor",
[ScribbleXDoGPreprocessor] = "Scribble XDoG Preprocessor",
[SAMPreprocessor] = "SAM Preprocessor",
[ShufflePreprocessor] = "Shuffle Preprocessor",
[TEEDPreprocessor] = "TEED Preprocessor",
[TilePreprocessor] = "Tile Preprocessor",
[UniFormerSemSegPreprocessor] = "UniFormer SemSeg Preprocessor",
[SemSegPreprocessor] = "SemSeg Preprocessor",
[UnimatchOptFlowPreprocessor] = "Unimatch OptFlow Preprocessor",
[MaskOptFlow] = "Mask OptFlow",
[ZoeDepthMapPreprocessor] = "Zoe DepthMap Preprocessor"
};
public static IEnumerable<ComfyAuxPreprocessor> Defaults => DisplayNamesMapping.Keys;
public string DisplayName => DisplayNamesMapping.GetValueOrDefault(this, Value);
/// <inheritdoc />
public override string ToString() => Value;
}

15
StabilityMatrix.Core/Models/Api/Comfy/ComfyInputInfo.cs

@ -9,13 +9,24 @@ public class ComfyInputInfo
[JsonPropertyName("required")] [JsonPropertyName("required")]
public Dictionary<string, JsonValue>? Required { get; set; } public Dictionary<string, JsonValue>? Required { get; set; }
[JsonPropertyName("optional")]
public Dictionary<string, JsonValue>? Optional { get; set; }
public List<string>? GetRequiredValueAsNestedList(string key) public List<string>? GetRequiredValueAsNestedList(string key)
{ {
var value = Required?[key]; var value = Required?[key];
if (value is null) return null;
var nested = value.Deserialize<List<List<string>>>(); var nested = value?.Deserialize<List<List<string>>>();
return nested?.SelectMany(x => x).ToList(); return nested?.SelectMany(x => x).ToList();
} }
public List<string>? GetOptionalValueAsNestedList(string key)
{
var value = Optional?[key];
var nested = value?.Deserialize<JsonArray>()?[0].Deserialize<List<string>>();
return nested;
}
} }

2
StabilityMatrix.Core/Models/Api/Comfy/NodeTypes/ModelConnections.cs

@ -12,4 +12,6 @@ public record ModelConnections(string Name)
public ClipNodeConnection? Clip { get; set; } public ClipNodeConnection? Clip { get; set; }
public ConditioningConnections? Conditioning { get; set; } public ConditioningConnections? Conditioning { get; set; }
public ConditioningConnections? PrimarySamplerConditioning { get; set; }
} }

23
StabilityMatrix.Core/Models/Api/Comfy/Nodes/ComfyNodeBuilder.cs

@ -332,7 +332,7 @@ public class ComfyNodeBuilder
[TypedNodeOptions( [TypedNodeOptions(
Name = "Inference_Core_PromptExpansion", Name = "Inference_Core_PromptExpansion",
RequiredExtensions = ["https://github.com/LykosAI/ComfyUI-Inference-Core-Nodes"] RequiredExtensions = ["https://github.com/LykosAI/ComfyUI-Inference-Core-Nodes >= 0.2.0"]
)] )]
public record PromptExpansion : ComfyTypedNodeBase<StringNodeConnection> public record PromptExpansion : ComfyTypedNodeBase<StringNodeConnection>
{ {
@ -342,6 +342,20 @@ public class ComfyNodeBuilder
public bool LogPrompt { get; init; } public bool LogPrompt { get; init; }
} }
[TypedNodeOptions(
Name = "Inference_Core_AIO_Preprocessor",
RequiredExtensions = ["https://github.com/LykosAI/ComfyUI-Inference-Core-Nodes >= 0.2.0"]
)]
public record AIOPreprocessor : ComfyTypedNodeBase<ImageNodeConnection>
{
public required ImageNodeConnection Image { get; init; }
public required string Preprocessor { get; init; }
[Range(64, 2048)]
public int Resolution { get; init; } = 512;
}
public ImageNodeConnection Lambda_LatentToImage(LatentNodeConnection latent, VAENodeConnection vae) public ImageNodeConnection Lambda_LatentToImage(LatentNodeConnection latent, VAENodeConnection vae)
{ {
var name = GetUniqueName("VAEDecode"); var name = GetUniqueName("VAEDecode");
@ -843,6 +857,13 @@ public class ComfyNodeBuilder
?? throw new NullReferenceException("No Refiner or Base Conditioning"); ?? throw new NullReferenceException("No Refiner or Base Conditioning");
} }
public ConditioningConnections GetRefinerOrBasePrimarySamplerConditioning()
{
return Refiner.PrimarySamplerConditioning
?? Base.PrimarySamplerConditioning
?? throw new NullReferenceException("No Refiner or Base PrimarySampler Conditioning");
}
public VAENodeConnection GetDefaultVAE() public VAENodeConnection GetDefaultVAE()
{ {
return PrimaryVAE ?? Refiner.VAE ?? Base.VAE ?? throw new NullReferenceException("No VAE"); return PrimaryVAE ?? Refiner.VAE ?? Base.VAE ?? throw new NullReferenceException("No VAE");

13
StabilityMatrix.Core/Models/Api/Comfy/Nodes/NodeDictionary.cs

@ -1,10 +1,12 @@
using System.ComponentModel; using System.ComponentModel;
using System.Reflection; using System.Reflection;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
using KGySoft.CoreLibraries;
using OneOf; using OneOf;
using StabilityMatrix.Core.Attributes; using StabilityMatrix.Core.Attributes;
using StabilityMatrix.Core.Helper; using StabilityMatrix.Core.Helper;
using StabilityMatrix.Core.Models.Api.Comfy.NodeTypes; using StabilityMatrix.Core.Models.Api.Comfy.NodeTypes;
using StabilityMatrix.Core.Models.Packages.Extensions;
namespace StabilityMatrix.Core.Models.Api.Comfy.Nodes; namespace StabilityMatrix.Core.Models.Api.Comfy.Nodes;
@ -19,7 +21,10 @@ public class NodeDictionary : Dictionary<string, ComfyNode>
/// When inserting TypedNodes, this holds a mapping of ClassType to required extensions /// When inserting TypedNodes, this holds a mapping of ClassType to required extensions
/// </summary> /// </summary>
[JsonIgnore] [JsonIgnore]
public Dictionary<string, string[]> ClassTypeRequiredExtensions { get; } = new(); public Dictionary<string, ExtensionSpecifier[]> ClassTypeRequiredExtensions { get; } = new();
public IEnumerable<ExtensionSpecifier> RequiredExtensions =>
ClassTypeRequiredExtensions.Values.SelectMany(x => x);
/// <summary> /// <summary>
/// Finds a unique node name given a base name, by appending _2, _3, etc. /// Finds a unique node name given a base name, by appending _2, _3, etc.
@ -63,7 +68,11 @@ public class NodeDictionary : Dictionary<string, ComfyNode>
{ {
if (options.RequiredExtensions != null) if (options.RequiredExtensions != null)
{ {
ClassTypeRequiredExtensions[namedNode.ClassType] = options.RequiredExtensions; ClassTypeRequiredExtensions.AddOrUpdate(
namedNode.ClassType,
_ => options.GetRequiredExtensionSpecifiers().ToArray(),
(_, specifiers) => options.GetRequiredExtensionSpecifiers().Concat(specifiers).ToArray()
);
} }
} }

3
StabilityMatrix.Core/Models/DownloadPackageVersionOptions.cs

@ -7,4 +7,7 @@ public class DownloadPackageVersionOptions
public string? VersionTag { get; set; } public string? VersionTag { get; set; }
public bool IsLatest { get; set; } public bool IsLatest { get; set; }
public bool IsPrerelease { get; set; } public bool IsPrerelease { get; set; }
public string GetReadableVersionString() =>
!string.IsNullOrWhiteSpace(VersionTag) ? VersionTag : $"{BranchName}@{CommitHash?[..7]}";
} }

2
StabilityMatrix.Core/Models/HybridModelFile.cs

@ -20,7 +20,7 @@ public record HybridModelFile
/// </summary> /// </summary>
public static HybridModelFile None { get; } = FromRemote("@none"); public static HybridModelFile None { get; } = FromRemote("@none");
private string? RemoteName { get; init; } public string? RemoteName { get; init; }
public LocalModelFile? Local { get; init; } public LocalModelFile? Local { get; init; }

14
StabilityMatrix.Core/Models/InferenceRunCustomPromptEventArgs.cs

@ -0,0 +1,14 @@
using StabilityMatrix.Core.Models.Api.Comfy.Nodes;
namespace StabilityMatrix.Core.Models;
public class InferenceQueueCustomPromptEventArgs : EventArgs
{
public ComfyNodeBuilder Builder { get; } = new();
public NodeDictionary Nodes => Builder.Nodes;
public long? SeedOverride { get; init; }
public List<(string SourcePath, string DestinationRelativePath)> FilesToTransfer { get; init; } = [];
}

105
StabilityMatrix.Core/Models/Packages/Extensions/ExtensionSpecifier.cs

@ -0,0 +1,105 @@
using System.Diagnostics.CodeAnalysis;
using System.Text.RegularExpressions;
using JetBrains.Annotations;
using Semver;
using StabilityMatrix.Core.Processes;
namespace StabilityMatrix.Core.Models.Packages.Extensions;
/// <summary>
/// Extension specifier with optional version constraints.
/// </summary>
[PublicAPI]
public partial class ExtensionSpecifier
{
public required string Name { get; init; }
public string? Constraint { get; init; }
public string? Version { get; init; }
public string? VersionConstraint => Constraint is null || Version is null ? null : Constraint + Version;
public bool TryGetSemVersionRange([NotNullWhen(true)] out SemVersionRange? semVersionRange)
{
if (!string.IsNullOrEmpty(VersionConstraint))
{
return SemVersionRange.TryParse(
VersionConstraint,
SemVersionRangeOptions.Loose,
out semVersionRange
);
}
semVersionRange = null;
return false;
}
public static ExtensionSpecifier Parse(string value)
{
TryParse(value, true, out var packageSpecifier);
return packageSpecifier!;
}
public static bool TryParse(string value, [NotNullWhen(true)] out ExtensionSpecifier? extensionSpecifier)
{
return TryParse(value, false, out extensionSpecifier);
}
private static bool TryParse(
string value,
bool throwOnFailure,
[NotNullWhen(true)] out ExtensionSpecifier? packageSpecifier
)
{
var match = ExtensionSpecifierRegex().Match(value);
if (!match.Success)
{
if (throwOnFailure)
{
throw new ArgumentException($"Invalid extension specifier: {value}");
}
packageSpecifier = null;
return false;
}
packageSpecifier = new ExtensionSpecifier
{
Name = match.Groups["extension_name"].Value,
Constraint = match.Groups["version_constraint"].Value,
Version = match.Groups["version"].Value
};
return true;
}
/// <inheritdoc />
public override string ToString()
{
return Name + VersionConstraint;
}
public static implicit operator Argument(ExtensionSpecifier specifier)
{
return specifier.VersionConstraint is null
? new Argument(specifier.Name)
: new Argument((specifier.Name, specifier.VersionConstraint));
}
public static implicit operator ExtensionSpecifier(string specifier)
{
return Parse(specifier);
}
/// <summary>
/// Regex to match a pip package specifier.
/// </summary>
[GeneratedRegex(
@"(?<extension_name>\S+)\s*(?<version_constraint>==|>=|<=|>|<|~=|!=)?\s*(?<version>[a-zA-Z0-9_.]+)?",
RegexOptions.CultureInvariant,
5000
)]
private static partial Regex ExtensionSpecifierRegex();
}

25
StabilityMatrix.Core/Models/Packages/Extensions/GitPackageExtensionManager.cs

@ -201,6 +201,31 @@ public abstract partial class GitPackageExtensionManager(IPrerequisiteHelper pre
return extensions; return extensions;
} }
public virtual async Task<InstalledPackageExtension> GetInstalledExtensionInfoAsync(
InstalledPackageExtension installedExtension
)
{
if (installedExtension.PrimaryPath is not DirectoryPath extensionDirectory)
{
return installedExtension;
}
// Get git version
var version = await prerequisiteHelper
.GetGitRepositoryVersion(extensionDirectory)
.ConfigureAwait(false);
return installedExtension with
{
Version = new PackageExtensionVersion
{
Tag = version.Tag,
Branch = version.Branch,
CommitSha = version.CommitSha
}
};
}
/// <inheritdoc /> /// <inheritdoc />
public virtual async Task InstallExtensionAsync( public virtual async Task InstallExtensionAsync(
PackageExtension extension, PackageExtension extension,

7
StabilityMatrix.Core/Models/Packages/Extensions/IPackageExtensionManager.cs

@ -89,6 +89,13 @@ public interface IPackageExtensionManager
CancellationToken cancellationToken = default CancellationToken cancellationToken = default
); );
/// <summary>
/// Get updated info (version) for an installed extension.
/// </summary>
Task<InstalledPackageExtension> GetInstalledExtensionInfoAsync(
InstalledPackageExtension installedExtension
);
/// <summary> /// <summary>
/// Install an extension to the provided package. /// Install an extension to the provided package.
/// </summary> /// </summary>

1
StabilityMatrix.Core/Models/Settings/Settings.cs

@ -120,6 +120,7 @@ public class Settings
public Size InferenceImageSize { get; set; } = new(150, 190); public Size InferenceImageSize { get; set; } = new(150, 190);
public Size OutputsImageSize { get; set; } = new(300, 300); public Size OutputsImageSize { get; set; } = new(300, 300);
public HolidayMode HolidayModeSetting { get; set; } = HolidayMode.Automatic; public HolidayMode HolidayModeSetting { get; set; } = HolidayMode.Automatic;
public bool IsOutputsTreeViewEnabled { get; set; } = true;
[JsonIgnore] [JsonIgnore]
public bool IsHolidayModeActive => public bool IsHolidayModeActive =>

1
StabilityMatrix.Core/Models/Settings/TeachingTip.cs

@ -13,6 +13,7 @@ public record TeachingTip(string Value) : StringValue(Value)
public static TeachingTip CheckpointCategoriesTip => new("CheckpointCategoriesTip"); public static TeachingTip CheckpointCategoriesTip => new("CheckpointCategoriesTip");
public static TeachingTip PackageExtensionsInstallNotice => new("PackageExtensionsInstallNotice"); public static TeachingTip PackageExtensionsInstallNotice => new("PackageExtensionsInstallNotice");
public static TeachingTip DownloadsTip => new("DownloadsTip"); public static TeachingTip DownloadsTip => new("DownloadsTip");
public static TeachingTip WebUiButtonMovedTip => new("WebUiButtonMovedTip");
/// <inheritdoc /> /// <inheritdoc />
public override string ToString() public override string ToString()

7
StabilityMatrix.Tests/Helper/PackageFactoryTests.cs

@ -12,11 +12,8 @@ public class PackageFactoryTests
[TestInitialize] [TestInitialize]
public void Setup() public void Setup()
{ {
fakeBasePackages = new List<BasePackage> fakeBasePackages = new List<BasePackage> { new DankDiffusion(null!, null!, null!, null!) };
{ packageFactory = new PackageFactory(fakeBasePackages, null, null, null, null, null);
new DankDiffusion(null!, null!, null!, null!)
};
packageFactory = new PackageFactory(fakeBasePackages);
} }
[TestMethod] [TestMethod]

Loading…
Cancel
Save