Add SwarmUI settings management and portrait generation enhancements

- Introduced new API endpoints for managing SwarmUI settings, including fetching and saving presets and age rules.
- Updated the portrait generation logic to utilize the new settings structure, allowing for dynamic preset selection based on age.
- Enhanced UI components to support SwarmUI settings, including localization for new strings and improved styling for settings sections.
- Added tests to verify the functionality of new settings endpoints and portrait generation behavior.

This commit lays the groundwork for more flexible and user-friendly portrait generation options.
This commit is contained in:
Leonid Pershin
2026-08-20 06:06:45 +03:00
parent e0b7122f3b
commit 5a400be792
32 changed files with 2178 additions and 184 deletions
+78 -2
View File
@@ -11,6 +11,44 @@ const ru = {
schoolsTitle: 'Школы',
createSchool: 'Создать школу',
settings: 'Настройки',
save: 'Сохранить',
settingsTitle: 'SwarmUI — пресеты портретов',
settingsActivePreset: 'Пресет по умолчанию',
settingsEditPreset: 'Редактируемый пресет',
settingsAddPreset: 'Добавить пресет',
settingsPresetLabel: 'Название пресета',
settingsModel: 'Модель',
settingsSteps: 'Steps',
settingsCfg: 'CFG scale',
settingsClipSkip: 'CLIP skip',
settingsSampler: 'Sampler',
settingsScheduler: 'Scheduler',
settingsSeed: 'Seed',
settingsPositive: 'Базовый positive',
settingsNegative: 'Negative',
settingsPositiveLoras: 'Positive LoRA',
settingsNegativeLoras: 'Negative LoRA',
settingsAddLora: 'Добавить LoRA',
settingsAvatarPreset: 'Аватар',
settingsCustomPreset: 'Свой промпт (размеры)',
settingsFullBodyPreset: 'В полный рост',
settingsWidth: 'Ширина',
settingsHeight: 'Высота',
settingsKindPositive: 'Positive для вида',
settingsAgeRules: 'Правила по возрасту',
settingsAgeMin: 'От',
settingsAgeMax: 'До',
settingsAgePreset: 'Пресет',
settingsAddAgeRule: 'Добавить правило',
settingsRemoveRule: 'Удалить',
settingsRefreshLists: 'Обновить списки из SwarmUI',
settingsSwarmReady: 'SwarmUI подключён — списки моделей и семплеров доступны.',
settingsSwarmOffline: 'SwarmUI недоступен — поля можно заполнить вручную.',
settingsSwarmNotConfigured: 'SwarmUI не настроен на сервере (SwarmUi:BaseUrl).',
settingsLoadFailed: 'Не удалось загрузить настройки.',
settingsSaveFailed: 'Не удалось сохранить настройки.',
settingsDiscoveryFailed: 'Не удалось получить списки из SwarmUI.',
emptySchools: 'Пока ни одной школы. Создайте первую.',
loadSchoolsFailed: 'Не удалось загрузить список школ. Проверьте соединение с сервером.',
createDisabledTitle: 'Удалите одну из школ, чтобы создать новую',
@@ -152,7 +190,6 @@ const ru = {
peopleLogEvent: 'Событие',
peopleLogEmpty: 'Сегодня записей нет.',
peopleTabOverview: 'Обзор',
peopleTabPortrait: 'Портрет',
peoplePortraitAvatar: 'Аватар',
peoplePortraitFull: 'В полный рост',
@@ -178,6 +215,7 @@ const ru = {
peoplePortraitPromptNegative: 'Negative',
peoplePortraitPromptLoading: 'Сборка промпта…',
peoplePortraitPromptFailed: 'Не удалось получить промпт.',
peoplePortraitPromptPreset: 'Пресет: {label}',
modeOverview: 'Обзор',
modeManage: 'Управление',
@@ -277,6 +315,44 @@ const en: Messages = {
schoolsTitle: 'Schools',
createSchool: 'Create school',
settings: 'Settings',
save: 'Save',
settingsTitle: 'SwarmUI portrait presets',
settingsActivePreset: 'Default preset',
settingsEditPreset: 'Preset to edit',
settingsAddPreset: 'Add preset',
settingsPresetLabel: 'Preset name',
settingsModel: 'Model',
settingsSteps: 'Steps',
settingsCfg: 'CFG scale',
settingsClipSkip: 'CLIP skip',
settingsSampler: 'Sampler',
settingsScheduler: 'Scheduler',
settingsSeed: 'Seed',
settingsPositive: 'Base positive',
settingsNegative: 'Negative',
settingsPositiveLoras: 'Positive LoRA',
settingsNegativeLoras: 'Negative LoRA',
settingsAddLora: 'Add LoRA',
settingsAvatarPreset: 'Avatar',
settingsCustomPreset: 'Custom prompt (size)',
settingsFullBodyPreset: 'Full body',
settingsWidth: 'Width',
settingsHeight: 'Height',
settingsKindPositive: 'Kind positive',
settingsAgeRules: 'Age rules',
settingsAgeMin: 'From',
settingsAgeMax: 'To',
settingsAgePreset: 'Preset',
settingsAddAgeRule: 'Add rule',
settingsRemoveRule: 'Remove',
settingsRefreshLists: 'Refresh lists from SwarmUI',
settingsSwarmReady: 'SwarmUI connected — model and sampler lists are available.',
settingsSwarmOffline: 'SwarmUI unreachable — you can still edit fields manually.',
settingsSwarmNotConfigured: 'SwarmUI is not configured on the server (SwarmUi:BaseUrl).',
settingsLoadFailed: 'Could not load settings.',
settingsSaveFailed: 'Could not save settings.',
settingsDiscoveryFailed: 'Could not fetch lists from SwarmUI.',
emptySchools: 'No schools yet. Create the first one.',
loadSchoolsFailed: 'Could not load the school list. Check the connection to the server.',
createDisabledTitle: 'Delete a school to create a new one',
@@ -418,7 +494,6 @@ const en: Messages = {
peopleLogEvent: 'Event',
peopleLogEmpty: 'Nothing logged today.',
peopleTabOverview: 'Overview',
peopleTabPortrait: 'Portrait',
peoplePortraitAvatar: 'Avatar',
peoplePortraitFull: 'Full body',
@@ -444,6 +519,7 @@ const en: Messages = {
peoplePortraitPromptNegative: 'Negative',
peoplePortraitPromptLoading: 'Building prompt…',
peoplePortraitPromptFailed: 'Could not load the prompt.',
peoplePortraitPromptPreset: 'Preset: {label}',
modeOverview: 'Overview',
modeManage: 'Management',
+68
View File
@@ -402,6 +402,72 @@ export async function fetchGameStatus(): Promise<GameStatus> {
return request<GameStatus>('/api/status');
}
export interface SwarmUiKindPreset {
width: number;
height: number;
positive: string;
}
export interface SwarmUiLoraEntry {
name: string;
weight: number;
}
export interface SwarmUiPresetDefinition {
id: string;
label: string;
model: string;
steps: number;
cfgScale: number;
clipSkip: number;
sampler: string;
scheduler: string;
seed: number;
positive: string;
negative: string;
positiveLoras: SwarmUiLoraEntry[];
negativeLoras: SwarmUiLoraEntry[];
avatar: SwarmUiKindPreset;
custom: SwarmUiKindPreset;
fullBody: SwarmUiKindPreset;
}
export interface SwarmUiAgeRule {
minAge: number;
maxAge: number;
presetId: string;
}
export interface SwarmUiSettingsFile {
activePresetId: string;
presets: SwarmUiPresetDefinition[];
ageRules: SwarmUiAgeRule[];
}
export interface SwarmUiDiscovery {
connected: boolean;
models: readonly string[];
loras: readonly string[];
samplers: readonly string[];
schedulers: readonly string[];
}
export async function fetchSwarmUiSettings(): Promise<SwarmUiSettingsFile> {
return request<SwarmUiSettingsFile>('/api/settings/swarmui');
}
export async function saveSwarmUiSettings(settings: SwarmUiSettingsFile): Promise<SwarmUiSettingsFile> {
return request<SwarmUiSettingsFile>('/api/settings/swarmui', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(settings),
});
}
export async function fetchSwarmUiDiscovery(): Promise<SwarmUiDiscovery> {
return request<SwarmUiDiscovery>('/api/settings/swarmui/discovery');
}
export type PortraitKind = 'avatar' | 'full' | 'custom';
export interface PortraitResult {
@@ -430,6 +496,8 @@ export interface PortraitPrompt {
readonly positive: string;
readonly negative: string;
readonly promptExtra: string | null;
readonly presetId: string;
readonly presetLabel: string;
}
export async function fetchPortraitPrompt(
+36 -1
View File
@@ -683,10 +683,45 @@ body {
overflow-x: auto;
}
.people__portrait-prompt-text--muted {
.form--settings {
max-height: min(90vh, 960px);
overflow: auto;
}
.settings-section-title {
margin: 20px 0 8px;
font-size: 15px;
}
.settings-subtitle {
margin: 16px 0 8px;
font-size: 14px;
}
.settings-age-rule {
align-items: end;
margin-bottom: 8px;
}
.settings-lora-row {
align-items: end;
margin-bottom: 8px;
}
.settings-lora-row .field {
flex: 1;
}
.people__portrait-prompt-meta {
margin: 0 0 8px;
font-size: 13px;
color: var(--text-muted, #666);
}
.field--grow {
flex: 1;
}
.people__swarm-status {
margin: 0 0 12px;
font-size: 13px;
+8 -1
View File
@@ -11,6 +11,7 @@ import { schoolWord, t } from '../i18n/strings.ts';
import { el } from './dom.ts';
import { confirmDialog } from './confirmDialog.ts';
import { createSchoolDialog } from './createSchoolDialog.ts';
import { swarmUiSettingsDialog } from './swarmUiSettingsDialog.ts';
import { SchoolCard } from './schoolCard.ts';
interface MainMenuOptions {
@@ -35,6 +36,10 @@ export class MainMenu {
class: 'button button--primary',
type: 'button',
});
private readonly settingsButton = el('button', {
class: 'button',
type: 'button',
});
private readonly limitHint = el('p', { class: 'hint' });
private readonly status = el('p', { class: 'hint hint--error' });
@@ -47,6 +52,7 @@ export class MainMenu {
constructor(private readonly options: MainMenuOptions) {
this.createButton.addEventListener('click', () => void this.openCreateDialog());
this.settingsButton.addEventListener('click', () => void swarmUiSettingsDialog());
this.status.hidden = true;
this.root.append(
@@ -54,7 +60,7 @@ export class MainMenu {
'header',
{ class: 'screen__header' },
this.title,
el('div', { class: 'screen__actions' }, this.createButton),
el('div', { class: 'screen__actions' }, this.settingsButton, this.createButton),
),
this.limitHint,
this.status,
@@ -73,6 +79,7 @@ export class MainMenu {
localize(): void {
this.title.textContent = t('schoolsTitle');
this.createButton.textContent = t('createSchool');
this.settingsButton.textContent = t('settings');
this.emptyHint.textContent = t('emptySchools');
for (const card of this.cards.values()) {
+1
View File
@@ -489,6 +489,7 @@ function portraitPromptView(
{ class: 'people__portrait-prompt-wrap' },
toggle,
el('div', { class: 'people__portrait-prompt-view' },
el('p', { class: 'people__portrait-prompt-meta', text: t('peoplePortraitPromptPreset', { label: prompt.presetLabel || prompt.presetId }) }),
el('p', { class: 'people__label', text: t('peoplePortraitPromptPositive') }),
el('pre', { class: 'people__portrait-prompt-text', text: prompt.positive }),
el('p', { class: 'people__label', text: t('peoplePortraitPromptNegative') }),
@@ -0,0 +1,435 @@
import {
ApiError,
fetchGameStatus,
fetchSwarmUiDiscovery,
fetchSwarmUiSettings,
saveSwarmUiSettings,
type SwarmUiDiscovery,
type SwarmUiLoraEntry,
type SwarmUiPresetDefinition,
type SwarmUiSettingsFile,
} from '../net/api.ts';
import { t } from '../i18n/strings.ts';
import { el } from './dom.ts';
import { Modal } from './modal.ts';
export function swarmUiSettingsDialog(): Promise<boolean> {
const modal = new Modal<boolean>(false);
const error = el('p', { class: 'dialog__error' });
error.hidden = true;
const statusLine = el('p', { class: 'hint' });
const editPresetSelect = el('select', { class: 'input' });
const activePresetSelect = el('select', { class: 'input' });
const formHost = el('div', { class: 'settings-form' });
const ageRulesHost = el('div', { class: 'settings-age-rules' });
let config: SwarmUiSettingsFile | null = null;
let discovery: SwarmUiDiscovery = { connected: false, models: [], loras: [], samplers: [], schedulers: [] };
let editingPresetId = '';
const cancelButton = el('button', { class: 'button', type: 'button', onClick: () => modal.close(false) });
const saveButton = el('button', { class: 'button button--primary', type: 'submit' });
const addPresetButton = el('button', { class: 'button button--small', type: 'button' });
const addAgeRuleButton = el('button', { class: 'button button--small', type: 'button' });
const refreshDiscoveryButton = el('button', { class: 'button button--small', type: 'button' });
const form = el(
'form',
{ class: 'form form--settings' },
el('h2', { class: 'dialog__title' }),
statusLine,
el('div', { class: 'field__row' }, refreshDiscoveryButton),
el('label', { class: 'field' }, el('span', { class: 'field__label' }), activePresetSelect),
el(
'div',
{ class: 'field field__row' },
el('label', { class: 'field field--grow' }, el('span', { class: 'field__label' }), editPresetSelect),
addPresetButton,
),
formHost,
el('h3', { class: 'settings-section-title' }),
ageRulesHost,
el('div', { class: 'field__row' }, addAgeRuleButton),
error,
el('div', { class: 'dialog__actions' }, cancelButton, saveButton),
);
form.addEventListener('submit', (event) => {
event.preventDefault();
void submit();
});
addPresetButton.addEventListener('click', () => {
if (config === null) {
return;
}
const id = `preset-${config.presets.length + 1}`;
const source = currentPreset() ?? config.presets[0];
config.presets.push({
...structuredClone(source),
id,
label: id,
});
editingPresetId = id;
paintPresetSelectors();
paintPresetForm();
paintAgeRules();
});
addAgeRuleButton.addEventListener('click', () => {
if (config === null) {
return;
}
config.ageRules.push({
minAge: 6,
maxAge: 11,
presetId: config.activePresetId,
});
paintAgeRules();
});
refreshDiscoveryButton.addEventListener('click', () => void reloadDiscovery());
editPresetSelect.addEventListener('change', () => {
editingPresetId = editPresetSelect.value;
paintPresetForm();
});
activePresetSelect.addEventListener('change', () => {
if (config !== null) {
config.activePresetId = activePresetSelect.value;
}
paintAgeRules();
});
const dialog = modal.element;
dialog.classList.add('dialog--screen');
dialog.append(form);
void init();
return modal.open(saveButton);
async function init(): Promise<void> {
localize();
try {
const [settings, gameStatus, lists] = await Promise.all([
fetchSwarmUiSettings(),
fetchGameStatus(),
fetchSwarmUiDiscovery(),
]);
config = settings;
discovery = lists;
editingPresetId = settings.presets[0]?.id ?? '';
paintStatus(gameStatus.swarmUiConfigured, gameStatus.swarmUiConnected, lists.connected);
paintPresetSelectors();
paintPresetForm();
paintAgeRules();
} catch {
showError(t('settingsLoadFailed'));
}
}
async function reloadDiscovery(): Promise<void> {
refreshDiscoveryButton.disabled = true;
try {
discovery = await fetchSwarmUiDiscovery();
paintStatus(true, discovery.connected, discovery.connected);
paintPresetForm();
} catch {
showError(t('settingsDiscoveryFailed'));
} finally {
refreshDiscoveryButton.disabled = false;
}
}
async function submit(): Promise<void> {
if (config === null) {
return;
}
syncActivePresetFromForm();
saveButton.disabled = true;
error.hidden = true;
try {
await saveSwarmUiSettings(config);
modal.close(true);
} catch (err) {
showError(err instanceof ApiError ? err.message : t('settingsSaveFailed'));
} finally {
saveButton.disabled = false;
}
}
function showError(message: string): void {
error.textContent = message;
error.hidden = false;
}
function paintStatus(configured: boolean, connected: boolean | null, discoveryConnected: boolean): void {
if (!configured) {
statusLine.textContent = t('settingsSwarmNotConfigured');
return;
}
if (connected === true && discoveryConnected) {
statusLine.textContent = t('settingsSwarmReady');
return;
}
statusLine.textContent = t('settingsSwarmOffline');
}
function paintPresetSelectors(): void {
if (config === null) {
return;
}
editPresetSelect.replaceChildren(
...config.presets.map((preset) => el('option', { value: preset.id, text: preset.label || preset.id })),
);
editPresetSelect.value = editingPresetId;
activePresetSelect.replaceChildren(
...config.presets.map((preset) => el('option', { value: preset.id, text: preset.label || preset.id })),
);
activePresetSelect.value = config.activePresetId;
}
function currentPreset(): SwarmUiPresetDefinition | undefined {
return config?.presets.find((preset) => preset.id === editingPresetId);
}
function paintPresetForm(): void {
formHost.replaceChildren();
const preset = currentPreset();
if (preset === null || preset === undefined) {
return;
}
formHost.append(
textField(t('settingsPresetLabel'), preset.label, (value) => {
preset.label = value;
paintPresetSelectors();
}),
choiceField(t('settingsModel'), preset.model, discovery.models, (value) => {
preset.model = value;
}),
numberField(t('settingsSteps'), preset.steps, (value) => {
preset.steps = value;
}),
numberField(t('settingsCfg'), preset.cfgScale, (value) => {
preset.cfgScale = value;
}, 0.1),
numberField(t('settingsClipSkip'), preset.clipSkip, (value) => {
preset.clipSkip = value;
}),
choiceField(t('settingsSampler'), preset.sampler, discovery.samplers, (value) => {
preset.sampler = value;
}),
choiceField(t('settingsScheduler'), preset.scheduler, discovery.schedulers, (value) => {
preset.scheduler = value;
}),
numberField(t('settingsSeed'), preset.seed, (value) => {
preset.seed = value;
}),
textareaField(t('settingsPositive'), preset.positive, (value) => {
preset.positive = value;
}),
textareaField(t('settingsNegative'), preset.negative, (value) => {
preset.negative = value;
}),
loraSection(t('settingsPositiveLoras'), preset.positiveLoras),
loraSection(t('settingsNegativeLoras'), preset.negativeLoras),
kindSection(t('settingsAvatarPreset'), preset.avatar),
kindSection(t('settingsCustomPreset'), preset.custom),
kindSection(t('settingsFullBodyPreset'), preset.fullBody),
);
}
function syncActivePresetFromForm(): void {
// Values are bound live through closures; nothing extra to scrape from DOM.
}
function paintAgeRules(): void {
ageRulesHost.replaceChildren();
if (config === null) {
return;
}
for (const rule of config.ageRules) {
const minInput = el('input', { class: 'input', type: 'number', value: String(rule.minAge) });
minInput.min = '0';
minInput.max = '120';
minInput.addEventListener('input', () => {
rule.minAge = Number(minInput.value);
});
const maxInput = el('input', { class: 'input', type: 'number', value: String(rule.maxAge) });
maxInput.min = '0';
maxInput.max = '120';
maxInput.addEventListener('input', () => {
rule.maxAge = Number(maxInput.value);
});
const presetSelect = el(
'select',
{ class: 'input' },
...config.presets.map((preset) => el('option', { value: preset.id, text: preset.label || preset.id })),
);
presetSelect.value = rule.presetId;
presetSelect.addEventListener('change', () => {
rule.presetId = presetSelect.value;
});
const removeButton = el('button', {
class: 'button button--small button--danger',
type: 'button',
text: t('settingsRemoveRule'),
onClick: () => {
config!.ageRules = config!.ageRules.filter((entry) => entry !== rule);
paintAgeRules();
},
});
ageRulesHost.append(
el(
'div',
{ class: 'settings-age-rule field__row' },
el('label', { class: 'field' }, el('span', { class: 'field__label', text: t('settingsAgeMin') }), minInput),
el('label', { class: 'field' }, el('span', { class: 'field__label', text: t('settingsAgeMax') }), maxInput),
el('label', { class: 'field field--grow' }, el('span', { class: 'field__label', text: t('settingsAgePreset') }), presetSelect),
removeButton,
),
);
}
}
function loraSection(title: string, loras: SwarmUiLoraEntry[]): HTMLElement {
const host = el('div', { class: 'settings-loras' });
const heading = el('h4', { class: 'settings-subtitle', text: title });
const rows = el('div', { class: 'settings-lora-rows' });
const paintRows = (): void => {
rows.replaceChildren();
for (const lora of loras) {
const nameField = choiceField('', lora.name, discovery.loras, (value) => {
lora.name = value;
});
const weightInput = el('input', { class: 'input', type: 'number', value: String(lora.weight) });
weightInput.step = '0.05';
weightInput.min = '-4';
weightInput.max = '4';
weightInput.addEventListener('input', () => {
lora.weight = Number(weightInput.value);
});
const remove = el('button', {
class: 'button button--small button--danger',
type: 'button',
text: '×',
onClick: () => {
const index = loras.indexOf(lora);
if (index >= 0) {
loras.splice(index, 1);
}
paintRows();
},
});
rows.append(el('div', { class: 'field__row settings-lora-row' }, nameField, weightInput, remove));
}
};
paintRows();
const add = el('button', {
class: 'button button--small',
type: 'button',
text: t('settingsAddLora'),
onClick: () => {
loras.push({ name: discovery.loras[0] ?? '', weight: 1 });
paintRows();
},
});
host.append(heading, rows, add);
return host;
}
function kindSection(title: string, preset: SwarmUiPresetDefinition['avatar']): HTMLElement {
return el(
'div',
{ class: 'settings-kind' },
el('h4', { class: 'settings-subtitle', text: title }),
numberField(t('settingsWidth'), preset.width, (value) => {
preset.width = value;
}),
numberField(t('settingsHeight'), preset.height, (value) => {
preset.height = value;
}),
textareaField(t('settingsKindPositive'), preset.positive, (value) => {
preset.positive = value;
}),
);
}
function localize(): void {
form.querySelector('.dialog__title')!.textContent = t('settingsTitle');
form.querySelectorAll('.field__label')[0]!.textContent = t('settingsActivePreset');
form.querySelectorAll('.field__label')[1]!.textContent = t('settingsEditPreset');
form.querySelector('.settings-section-title')!.textContent = t('settingsAgeRules');
cancelButton.textContent = t('cancel');
saveButton.textContent = t('save');
addPresetButton.textContent = t('settingsAddPreset');
addAgeRuleButton.textContent = t('settingsAddAgeRule');
refreshDiscoveryButton.textContent = t('settingsRefreshLists');
}
}
function textField(label: string, value: string, onChange: (value: string) => void): HTMLElement {
const input = el('input', { class: 'input', type: 'text', value });
input.addEventListener('input', () => onChange(input.value));
return el('label', { class: 'field' }, el('span', { class: 'field__label', text: label }), input);
}
function numberField(
label: string,
value: number,
onChange: (value: number) => void,
step = 1,
): HTMLElement {
const input = el('input', { class: 'input', type: 'number', value: String(value) });
input.step = String(step);
input.addEventListener('input', () => onChange(Number(input.value)));
return el('label', { class: 'field' }, el('span', { class: 'field__label', text: label }), input);
}
function textareaField(label: string, value: string, onChange: (value: string) => void): HTMLElement {
const input = el('textarea', { class: 'input', rows: 3, value });
input.addEventListener('input', () => onChange(input.value));
return el('label', { class: 'field' }, el('span', { class: 'field__label', text: label }), input);
}
function choiceField(
label: string,
value: string,
options: readonly string[],
onChange: (value: string) => void,
): HTMLElement {
const values = options.includes(value) ? options : value.length > 0 ? [value, ...options] : options;
if (values.length === 0) {
const input = el('input', { class: 'input', type: 'text', value });
input.addEventListener('input', () => onChange(input.value));
return el('label', { class: 'field' }, el('span', { class: 'field__label', text: label }), input);
}
const select = el(
'select',
{ class: 'input' },
...values.map((entry) => el('option', { value: entry, text: entry })),
);
select.value = value;
select.addEventListener('change', () => onChange(select.value));
return el('label', { class: 'field' }, el('span', { class: 'field__label', text: label }), select);
}