Files
ComfyUI-Lora-Manager/static/js/utils/updateCheckHelpers.js
T
Will Miao e42d649df0 refactor(update)!: make obtainability a property of updates, not a surface
The owner could not tell from the UI what "Buzz Price Tracking" enabled, what the
"Price alert threshold" number meant, or what "Price Alerts" was alerting about.
That was not a copy problem: the implementation exposed our mechanism (a page
scrape) and our SQL predicates as the user's concepts. Two concrete defects came
from the same root:

- the alert population included versions the user already owns (neither the event
  generator nor the query filtered on is_in_library; in the owner's library 28 of
  52 gated versions were already downloaded, so most "alerts" were about files
  already on disk, which cannot become cheaper *for them*);
- a threshold-filtered state list lived in a notification surface, so an empty
  panel had three indistinguishable causes and read as a broken feature.

The information model is now the version plus ownership: cost is shown only where
a decision exists. Owned -> nothing. Not owned and free -> nothing. Not owned and
gated -> the price when it is known, `Paid` without a number when it is not, and
early access keeps its countdown because "free on <date>" decides between waiting
and paying. The numeric threshold has no place in that model: every decision is
categorical (wait / pay / skip), so the setting, the comparison and the whole
alert-state machine are gone.

- both alert-state columns are removed from the schema rather than left dead; a
  database created by an unreleased build has them dropped on open (native
  ALTER TABLE ... DROP COLUMN, guarded), which is a no-op for everyone else
- gate events are emitted only for versions the user does not have, and the
  price-drop event goes with the threshold it belonged to
- both alert endpoints, PriceAlertsHandler and the service-registry adapter field
  it needed are removed: events already reach the UI through the refresh response
- the bell tab, panel, CSS, both entry points, the unread watermark and their
  locales are removed; the setting keeps only the enable flag and the refresh
  interval and is framed as plumbing
- "Price unavailable" is replaced by `Paid`: the gate is certain from the public
  API, only the number is best-effort, and that is our plumbing, not the user's
  problem

Verified against a copy of the owner's real database: 52 gated versions ->
28 owned (now silent) + 24 the feature is actually about; the drop migration ran
and both removed endpoints 404.
2026-10-05 08:54:08 +08:00

358 lines
12 KiB
JavaScript

import { state } from '../state/index.js';
import { translate } from './i18nHelpers.js';
import { showToast } from './uiHelpers.js';
import { getCompleteApiConfig, getCurrentModelType } from '../api/apiConfig.js';
import { resetAndReload, getModelApiClient } from '../api/modelApiFactory.js';
import { getStorageItem, setStorageItem } from './storageHelpers.js';
import { modalManager } from '../managers/ModalManager.js';
const CHECK_UPDATES_CONFIRMATION_KEY = 'ack_check_updates_for_all_models';
/**
* Count the gate/price transitions reported by an update refresh.
* @param {Array} events - `events` array from the refresh response.
* @returns {{becameFree: number, newGate: number, priceDrop: number, total: number}}
*/
export function summarizeGateEvents(events) {
const list = Array.isArray(events) ? events : [];
return {
becameFree: list.filter((event) => event?.kind === 'became_free').length,
newGate: list.filter((event) => event?.kind === 'new_gate').length,
total: list.length
};
}
/**
* Toast the gate/price transitions of an update refresh, if any. Kept to a single
* toast so a large refresh cannot bury the user in notifications.
* @param {Array} events
*/
export function showGateEventsToast(events) {
const { becameFree, newGate } = summarizeGateEvents(events);
if (!becameFree && !newGate) {
return;
}
const parts = [];
if (becameFree) {
parts.push(
translate(
'globalContextMenu.checkModelUpdates.gateEvents.becameFree',
{ count: becameFree },
`${becameFree} version(s) became free`
)
);
}
if (newGate) {
parts.push(
translate(
'globalContextMenu.checkModelUpdates.gateEvents.newGate',
{ count: newGate },
`${newGate} version(s) are now paid`
)
);
}
showToast(parts.join(' · '), {}, becameFree ? 'success' : 'info');
}
/**
* Perform a model update check using the shared backend endpoint.
* @param {Object} [options]
* @param {Function} [options.onStart] - Callback invoked before the request is sent.
* @param {Function} [options.onComplete] - Callback invoked after the request settles.
* @returns {Promise<{status: 'success' | 'error' | 'unsupported', displayName: string, records: Array, error: Error | null}>}
*/
export async function performModelUpdateCheck({ onStart, onComplete } = {}) {
const modelType = getCurrentModelType();
const apiConfig = getCompleteApiConfig(modelType);
const apiClient = getModelApiClient(modelType);
const displayName = apiConfig?.config?.displayName ?? 'Model';
if (!apiConfig?.endpoints?.refreshUpdates) {
console.warn('Refresh updates endpoint not configured for model type:', modelType);
onComplete?.({ status: 'unsupported', displayName, records: [], error: null });
return { status: 'unsupported', displayName, records: [], error: null };
}
const proceed = await ensureCheckUpdatesConfirmation(displayName);
if (!proceed) {
onComplete?.({ status: 'cancelled', displayName, records: [], error: null });
return { status: 'cancelled', displayName, records: [], error: null };
}
const loadingMessage = translate(
'globalContextMenu.checkModelUpdates.loading',
{ type: displayName },
`Checking for ${displayName} updates...`
);
onStart?.({ displayName, loadingMessage });
state.loadingManager?.showSimpleLoading?.(loadingMessage);
const abortController = new AbortController();
state.loadingManager?.showCancelButton?.(() => {
apiClient.cancelTask();
abortController.abort();
});
let status = 'success';
let records = [];
let error = null;
try {
const response = await fetch(apiConfig.endpoints.refreshUpdates, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
signal: abortController.signal,
body: JSON.stringify({ force: false })
});
let payload = {};
try {
payload = await response.json();
} catch {
payload = {};
}
if (!response.ok || payload.success !== true) {
if (payload?.status === 'cancelled') {
showToast('toast.api.operationCancelled', {}, 'info');
return { status: 'cancelled', displayName, records: [], error: null };
}
const errorMessage = payload?.error || response.statusText || 'Unknown error';
throw new Error(errorMessage);
}
records = Array.isArray(payload.records) ? payload.records : [];
if (records.length > 0) {
showToast('globalContextMenu.checkModelUpdates.success', { count: records.length, type: displayName }, 'success');
} else {
showToast('globalContextMenu.checkModelUpdates.none', { type: displayName }, 'info');
}
showGateEventsToast(payload.events);
await resetAndReload(false);
} catch (err) {
if (err?.name === 'AbortError') {
showToast('toast.api.operationCancelled', {}, 'info');
status = 'cancelled';
return { status: 'cancelled', displayName, records: [], error: null };
}
status = 'error';
error = err instanceof Error ? err : new Error(String(err));
console.error('Error checking model updates:', error);
showToast(
'globalContextMenu.checkModelUpdates.error',
{ message: error?.message ?? 'Unknown error', type: displayName },
'error'
);
} finally {
state.loadingManager?.hide?.();
if (typeof state.loadingManager?.restoreProgressBar === 'function') {
state.loadingManager.restoreProgressBar();
}
onComplete?.({ status, displayName, records, error });
}
return { status, displayName, records, error };
}
/**
* Perform a model update check scoped to a specific folder.
* @param {string} folderPath - The relative folder path to check.
* @param {Object} [options]
* @param {Function} [options.onComplete] - Callback invoked after the request settles.
* @returns {Promise<{status: string, records: Array, error: Error | null}>}
*/
export async function performFolderUpdateCheck(folderPath, { onComplete } = {}) {
const modelType = getCurrentModelType();
const apiConfig = getCompleteApiConfig(modelType);
const apiClient = getModelApiClient(modelType);
const displayName = apiConfig?.config?.displayName ?? 'Model';
if (!apiConfig?.endpoints?.refreshUpdates) {
console.warn('Refresh updates endpoint not configured for model type:', modelType);
onComplete?.({ status: 'unsupported', records: [], error: null });
return { status: 'unsupported', records: [], error: null };
}
const loadingMessage = translate(
'sidebar.folderUpdateCheck.loading',
{ type: displayName },
`Checking ${displayName} updates for this folder...`
);
state.loadingManager?.showSimpleLoading?.(loadingMessage);
const abortController = new AbortController();
state.loadingManager?.showCancelButton?.(() => {
apiClient.cancelTask();
abortController.abort();
});
let status = 'success';
let records = [];
let error = null;
try {
const response = await fetch(apiConfig.endpoints.refreshUpdates, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
signal: abortController.signal,
body: JSON.stringify({ folder_path: folderPath, force: false })
});
let payload = {};
try {
payload = await response.json();
} catch {
payload = {};
}
if (!response.ok || payload.success !== true) {
if (payload?.status === 'cancelled') {
showToast('toast.api.operationCancelled', {}, 'info');
return { status: 'cancelled', records: [], error: null };
}
const errorMessage = payload?.error || response.statusText || 'Unknown error';
throw new Error(errorMessage);
}
records = Array.isArray(payload.records) ? payload.records : [];
if (records.length > 0) {
showToast('sidebar.folderUpdateCheck.success', { count: records.length, type: displayName }, 'success');
} else {
showToast('sidebar.folderUpdateCheck.none', { type: displayName }, 'info');
}
showGateEventsToast(payload.events);
await resetAndReload(false);
} catch (err) {
if (err?.name === 'AbortError') {
showToast('toast.api.operationCancelled', {}, 'info');
status = 'cancelled';
return { status: 'cancelled', records: [], error: null };
}
status = 'error';
error = err instanceof Error ? err : new Error(String(err));
console.error('Error checking folder model updates:', error);
showToast(
'sidebar.folderUpdateCheck.error',
{ message: error?.message ?? 'Unknown error', type: displayName },
'error'
);
} finally {
state.loadingManager?.hide?.();
if (typeof state.loadingManager?.restoreProgressBar === 'function') {
state.loadingManager.restoreProgressBar();
}
onComplete?.({ status, records, error });
}
return { status, records, error };
}
function getTypePlural(displayName) {
if (!displayName) {
return 'models';
}
const lower = displayName.toLowerCase();
if (lower.endsWith('s')) {
return displayName;
}
return `${displayName}s`;
}
async function ensureCheckUpdatesConfirmation(displayName) {
const hasConfirmed = getStorageItem(CHECK_UPDATES_CONFIRMATION_KEY, false);
if (hasConfirmed) {
return true;
}
const modalElement = document.getElementById('checkUpdatesConfirmModal');
if (!modalElement) {
return true;
}
const typePlural = getTypePlural(displayName);
const titleElement = modalElement.querySelector('[data-role="title"]');
if (titleElement) {
titleElement.textContent = translate(
'modals.checkUpdates.title',
{ type: displayName, typePlural },
`Check updates for all ${typePlural}?`
);
}
const messageElement = modalElement.querySelector('[data-role="message"]');
if (messageElement) {
messageElement.textContent = translate(
'modals.checkUpdates.message',
{ type: displayName, typePlural },
`This checks every ${typePlural} in your library for updates. Large collections may take a little longer.`
);
}
const tipElement = modalElement.querySelector('[data-role="tip"]');
if (tipElement) {
tipElement.textContent = translate(
'modals.checkUpdates.tip',
{ type: displayName, typePlural },
'To work in smaller batches, switch to bulk mode, pick the ones you need, then use "Check Updates for Selected".'
);
}
const confirmButton = modalElement.querySelector('[data-action="confirm-check-updates"]');
const cancelButton = modalElement.querySelector('[data-action="cancel-check-updates"]');
if (!confirmButton || !cancelButton) {
return true;
}
return new Promise((resolve) => {
let resolved = false;
const cleanup = () => {
confirmButton.removeEventListener('click', handleConfirm);
cancelButton.removeEventListener('click', handleCancel);
};
const finalize = (proceed) => {
if (resolved) {
return;
}
resolved = true;
cleanup();
resolve(proceed);
};
const handleConfirm = (event) => {
event.preventDefault();
setStorageItem(CHECK_UPDATES_CONFIRMATION_KEY, true);
finalize(true);
modalManager.closeModal('checkUpdatesConfirmModal');
};
const handleCancel = (event) => {
event.preventDefault();
finalize(false);
modalManager.closeModal('checkUpdatesConfirmModal');
};
confirmButton.addEventListener('click', handleConfirm);
cancelButton.addEventListener('click', handleCancel);
modalManager.showModal('checkUpdatesConfirmModal', null, () => finalize(false));
});
}