feat(autocomplete): search loras within active filters of LoRA Manager page

Add /af and /noaf toggle commands (plus /activefilters aliases) to the
loras autocomplete widget. When enabled (default off), suggestions are
matched within the active filters (folder, base model, tags, auto-tags,
license, tag logic) persisted by the LoRA Manager page in localStorage,
keeping the match pool consistent with the list endpoint, including the
global show_only_sfw setting.

Backend: /lm/{prefix}/relative-paths accepts the filter query params and
pre-filters the scanner cache with ModelFilterSet. The presence of the
recursive param signals the filter pipeline to run even without concrete
filters so global settings stay in parity with the list endpoint.
This commit is contained in:
Will Miao
2026-08-07 20:07:34 +08:00
parent 5ab06c4aae
commit 56acefbd6c
6 changed files with 1025 additions and 20 deletions

View File

@@ -14,6 +14,7 @@ import {
getAutocompleteAppendCommaPreference,
getAutocompleteAutoFormatPreference,
getAutocompleteAcceptKeyPreference,
getLoraActiveFiltersAutocompletePreference,
getPromptTagAutocompletePreference,
getTagSpaceReplacementPreference,
} from "./settings.js";
@@ -48,6 +49,47 @@ const TAG_COMMANDS = {
},
};
// Command definitions for LoRA active-filters search
// Aliases (/activefilters, /noactivefilters) mirror /emb ↔ /embedding
const LORAS_COMMANDS = {
'/af': {
type: 'toggle_setting',
settingId: 'loramanager.lora_active_filters_autocomplete',
value: true,
label: 'Active Filters: ON',
feedbackSummary: 'Active Filters Search: ON',
feedbackDetail: 'LoRA autocomplete now searches within the active filters of the LoRA Manager page.',
condition: () => !getLoraActiveFiltersAutocompletePreference()
},
'/noaf': {
type: 'toggle_setting',
settingId: 'loramanager.lora_active_filters_autocomplete',
value: false,
label: 'Active Filters: OFF',
feedbackSummary: 'Active Filters Search: OFF',
feedbackDetail: 'LoRA autocomplete searches the full library again.',
condition: () => getLoraActiveFiltersAutocompletePreference()
},
'/activefilters': {
type: 'toggle_setting',
settingId: 'loramanager.lora_active_filters_autocomplete',
value: true,
label: 'Active Filters: ON',
feedbackSummary: 'Active Filters Search: ON',
feedbackDetail: 'LoRA autocomplete now searches within the active filters of the LoRA Manager page.',
condition: () => !getLoraActiveFiltersAutocompletePreference()
},
'/noactivefilters': {
type: 'toggle_setting',
settingId: 'loramanager.lora_active_filters_autocomplete',
value: false,
label: 'Active Filters: OFF',
feedbackSummary: 'Active Filters Search: OFF',
feedbackDetail: 'LoRA autocomplete searches the full library again.',
condition: () => getLoraActiveFiltersAutocompletePreference()
},
};
// Category display information
const CATEGORY_INFO = {
0: { bg: 'rgba(0, 155, 230, 0.2)', text: '#4bb4ff', label: 'General' },
@@ -719,6 +761,36 @@ class AutoComplete {
searchTerm = (match[1] || '').trim();
}
// For loras model type, check if we're in command mode (/af, /noaf)
if (this.modelType === 'loras') {
const commandResult = this._parseCommandInput(rawSearchTerm);
if (commandResult.showCommands) {
// Show command list dropdown
this.showingCommands = true;
this.activeCommand = null;
this.searchType = 'commands';
this._showCommandList(commandResult.commandFilter);
return;
} else if (commandResult.command?.type === 'toggle_setting') {
// Handle toggle setting command (/af, /noaf)
this._handleToggleSettingCommand(commandResult.command);
return;
} else if (commandResult.command) {
// Command is active, use filtered search
this.showingCommands = false;
this.activeCommand = null;
this.searchType = null;
searchTerm = commandResult.searchTerm || rawSearchTerm;
} else {
// No command - regular lora search
this.showingCommands = false;
this.activeCommand = null;
this.searchType = null;
searchTerm = rawSearchTerm;
}
}
// For prompt model type, check if we're searching embeddings, commands, or tags
if (this.modelType === 'prompt') {
const match = rawSearchTerm.match(/^emb:(.*)$/i);
@@ -1095,7 +1167,11 @@ class AutoComplete {
}
_isSelectableInfoItem(item) {
return isWildcardInfoItem(item);
if (isWildcardInfoItem(item)) {
return true;
}
// Command items are not model paths — never show preview for them
return item && typeof item === 'object' && 'command' in item;
}
/**
@@ -1159,6 +1235,11 @@ class AutoComplete {
return (match?.[1] || '').trim();
}
if (this.modelType === 'loras') {
const commandResult = this._parseCommandInput(rawSearchTerm);
return commandResult.searchTerm ?? rawSearchTerm;
}
if (this.modelType === 'prompt') {
const embeddingMatch = rawSearchTerm.match(/^emb:(.*)$/i);
if (embeddingMatch) {
@@ -1245,6 +1326,91 @@ class AutoComplete {
return this._getPreferredSelectedIndex(searchTerm);
}
/**
* Build a URL-encoded query string from the LoRA Manager page's active
* filters in localStorage, or null when not applicable.
*/
_getActiveLoraFilters() {
if (this.modelType !== 'loras' || !getLoraActiveFiltersAutocompletePreference()) {
return null;
}
try {
const params = new URLSearchParams();
const folder = localStorage.getItem('lora_manager_loras_activeFolder');
const recursiveRaw = localStorage.getItem('lora_manager_loras_recursiveSearch');
const recursive = recursiveRaw === null ? true : recursiveRaw.toLowerCase() === 'true';
if (folder && folder !== 'null') {
params.append('folder', folder);
} else if (!recursive) {
// Root folder with recursion disabled mirrors the page list,
// which matches only root-level files via folder=''.
params.append('folder', '');
}
const raw = localStorage.getItem('lora_manager_loras_filters');
if (raw) {
const filters = JSON.parse(raw);
if (Array.isArray(filters.baseModel)) {
filters.baseModel.forEach((m) => m && params.append('base_model', m));
}
if (filters.tags && typeof filters.tags === 'object') {
Object.entries(filters.tags).forEach(([tag, state]) => {
if (state === 'include') {
params.append('tag_include', tag);
} else if (state === 'exclude') {
params.append('tag_exclude', tag);
}
});
}
if (filters.autoTags && typeof filters.autoTags === 'object') {
Object.entries(filters.autoTags).forEach(([tag, state]) => {
if (state === 'include') {
params.append('auto_tag_include', tag);
} else if (state === 'exclude') {
params.append('auto_tag_exclude', tag);
}
});
}
if (Array.isArray(filters.modelTypes)) {
filters.modelTypes.forEach((t) => t && params.append('model_type', t));
}
if (filters.tagLogic) {
params.append('tag_logic', filters.tagLogic);
}
if (filters.license) {
if (filters.license.noCredit === 'include') {
params.append('credit_required', 'false');
} else if (filters.license.noCredit === 'exclude') {
params.append('credit_required', 'true');
}
if (filters.license.allowSelling === 'include') {
params.append('allow_selling_generated_content', 'true');
} else if (filters.license.allowSelling === 'exclude') {
params.append('allow_selling_generated_content', 'false');
}
}
}
// Always send recursive in filter mode — its presence also signals
// the backend to run the filter pipeline (e.g. show_only_sfw) even
// when no concrete filter is set, matching the list endpoint.
params.append('recursive', String(recursive));
return params.toString();
} catch (error) {
console.warn('[Lora Manager] Failed to read active filters for autocomplete:', error);
return null;
}
}
async search(term = '', endpoint = null) {
try {
this.currentSearchTerm = term;
@@ -1262,6 +1428,10 @@ class AutoComplete {
endpoint = `/lm/${this.modelType}/relative-paths`;
}
// Active-filter query params for loras (null when setting off or
// model type is not loras, so appending is safe for all types)
const activeFiltersQuery = this._getActiveLoraFilters();
// Generate multiple query variations for better matching, but avoid
// sending duplicate-equivalent requests that normalize to the same
// backend search term.
@@ -1281,9 +1451,10 @@ class AutoComplete {
const url = endpoint.includes('?')
? `${endpoint}&search=${encodeURIComponent(query)}&limit=${this.options.maxItems}`
: `${endpoint}?search=${encodeURIComponent(query)}&limit=${this.options.maxItems}`;
const finalUrl = activeFiltersQuery ? `${url}&${activeFiltersQuery}` : url;
try {
const response = await api.fetchApi(url);
const response = await api.fetchApi(finalUrl);
const data = await response.json();
return {
items: data.success ? (data.relative_paths || data.words || []) : [],
@@ -1358,6 +1529,15 @@ class AutoComplete {
}
}
/**
* Return the command map for the current model type.
* Lora model types get the active-filters toggle commands, all others
* keep the prompt tag commands.
*/
_getCommands() {
return this.modelType === 'loras' ? LORAS_COMMANDS : TAG_COMMANDS;
}
/**
* Parse command input to detect command mode
* @param {string} rawInput - Raw input text
@@ -1379,8 +1559,8 @@ class AutoComplete {
const partialCommand = trimmed.toLowerCase();
// Check for exact command match
if (TAG_COMMANDS[partialCommand]) {
const cmd = TAG_COMMANDS[partialCommand];
if (this._getCommands()[partialCommand]) {
const cmd = this._getCommands()[partialCommand];
// Filter out toggle commands that don't meet their condition
if (cmd.type === 'toggle_setting' && cmd.condition && !cmd.condition()) {
return { showCommands: false, command: null, searchTerm: '' };
@@ -1405,8 +1585,8 @@ class AutoComplete {
const commandPart = trimmed.slice(0, spaceIndex).toLowerCase();
const searchPart = trimmed.slice(spaceIndex + 1).trim();
if (TAG_COMMANDS[commandPart]) {
const cmd = TAG_COMMANDS[commandPart];
if (this._getCommands()[commandPart]) {
const cmd = this._getCommands()[commandPart];
// Filter out toggle commands that don't meet their condition
if (cmd.type === 'toggle_setting' && cmd.condition && !cmd.condition()) {
return { showCommands: false, command: null, searchTerm: trimmed };
@@ -1437,7 +1617,7 @@ class AutoComplete {
const commands = [];
for (const [cmd, info] of Object.entries(TAG_COMMANDS)) {
for (const [cmd, info] of Object.entries(this._getCommands())) {
// Filter out toggle commands that don't meet their condition
if (info.type === 'toggle_setting' && info.condition) {
if (!info.condition()) continue;
@@ -1902,7 +2082,8 @@ class AutoComplete {
showPreviewForItem(relativePath, itemElement) {
if (!this.options.showPreview || !this.previewTooltip) return;
if (typeof relativePath !== 'string' || !relativePath) return;
// Extract filename without extension for preview
const fileName = relativePath.split(/[/\\]/).pop();
const loraName = fileName.replace(/\.(safetensors|ckpt|pt|bin)$/i, '');
@@ -1984,14 +2165,18 @@ class AutoComplete {
const queriesToExecute = this._getQueriesToExecute(this.currentSearchTerm);
const offset = this.items.length;
// Active-filter query params for loras (null when setting off)
const activeFiltersQuery = this._getActiveLoraFilters();
// Execute all queries in parallel with offset
const searchPromises = queriesToExecute.map(async (query) => {
const url = endpoint.includes('?')
? `${endpoint}&search=${encodeURIComponent(query)}&limit=${this.options.pageSize}&offset=${offset}`
: `${endpoint}?search=${encodeURIComponent(query)}&limit=${this.options.pageSize}&offset=${offset}`;
const finalUrl = activeFiltersQuery ? `${url}&${activeFiltersQuery}` : url;
try {
const response = await api.fetchApi(url);
const response = await api.fetchApi(finalUrl);
const data = await response.json();
return data.success ? (data.relative_paths || data.words || []) : [];
} catch (error) {
@@ -2692,14 +2877,14 @@ class AutoComplete {
const settingManager = app?.extensionManager?.setting;
if (settingManager && typeof settingManager.set === 'function') {
await settingManager.set(settingId, value);
this._showToggleFeedback(value);
this._showToggleFeedback(command, value);
this._clearCurrentToken();
} else {
// Fallback: use legacy settings API
const setting = app.ui.settings.settingsById?.[settingId];
if (setting) {
app.ui.settings.setSettingValue(settingId, value);
this._showToggleFeedback(value);
this._showToggleFeedback(command, value);
this._clearCurrentToken();
}
}
@@ -2718,15 +2903,16 @@ class AutoComplete {
/**
* Show visual feedback for toggle action using toast
* @param {Object} command - The toggle command that was executed
* @param {boolean} enabled - New autocomplete state
*/
_showToggleFeedback(enabled) {
_showToggleFeedback(command, enabled) {
showToast({
severity: enabled ? 'success' : 'secondary',
summary: enabled ? 'Autocomplete Enabled' : 'Autocomplete Disabled',
detail: enabled
? 'Tag autocomplete is now ON. Type to see suggestions.'
: 'Tag autocomplete is now OFF. Use /ac to re-enable.',
summary: command.feedbackSummary || (enabled ? 'Autocomplete Enabled' : 'Autocomplete Disabled'),
detail: command.feedbackDetail || (enabled
? 'Tag autocomplete is now ON. Type to see suggestions.'
: 'Tag autocomplete is now OFF. Use /ac to re-enable.'),
life: 3000
});
}