Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

fix(models): restore the Date added sort in the Model Manager (#10390)

Josh Corbettedc43fbfbd6e
diff --git a/invokeai/frontend/webv2/public/locales/en.json b/invokeai/frontend/webv2/public/locales/en.json
index 253497c4cd..fbb817a260 100644
--- a/invokeai/frontend/webv2/public/locales/en.json
+++ b/invokeai/frontend/webv2/public/locales/en.json
@@ -1498,6 +1498,8 @@
"countToInstall": "{{count}} to install",
"customizeDefaultField": "Customize {{field}} for this model",
"customizedForThisModel": "Customized for this model",
+ "dateAddedUnavailable": "Couldn't sort by date added",
+ "dateAddedUnavailableDescription": "Models are listed by name. Choose Date added again to retry.",
"defaultFieldInherited": {
"cfgRescale": "App default: 0 (off)",
"cfgScale": "App default: 7",
@@ -1856,6 +1858,7 @@
"someCouldNotBeDeleted": "Some models could not be deleted",
"someCouldNotBeReidentified": "Some models could not be re-identified",
"sort": {
+ "added": "Date added",
"base": "Base",
"catalog": "Catalog order",
"default": "Default",
diff --git a/invokeai/frontend/webv2/src/features/models/README.md b/invokeai/frontend/webv2/src/features/models/README.md
index 4979e6c7f7..f5ebe8d77b 100644
--- a/invokeai/frontend/webv2/src/features/models/README.md
+++ b/invokeai/frontend/webv2/src/features/models/README.md
@@ -4,6 +4,8 @@ Paths are relative to the webv2 `src/` directory.
`features/models/data/modelsStore.ts` owns the shared catalog snapshot and by-key index. List refreshes are single-flight with at most one queued trailing read. Local model replacement, narrow patches (including optimistic rollback), deletion, and cover changes advance a mutation generation. A read started before that generation cannot replace the catalog or publish an obsolete error; it queues an authoritative trailing read so unrelated server changes remain visible. Cover URL versions remain local cache-busting state. Only successful mutation callers apply confirmed changes; a failed request alone does not supersede a valid read.
+The catalog keeps the server's order, because features read `models` and take the first match. Install order is a separate read of the same listing (`order_by=created_at`) into `dateAddedRanks`, a key-to-rank map. It starts once the library's Date added sort asks for it (`ensureDateAddedOrderLoaded`) and then runs inside each refresh, so the ranks and the catalog come from the same refresh; a failed order read keeps the previous ranks and is reported to whoever asked. A model the ranks do not list sorts as the newest, and until the ranks load that sort lists by name.
+
Account reset clears the catalog and flight state. Responses from an earlier account lifetime cannot update the current catalog or schedule reads for it.
## Architecture table
diff --git a/invokeai/frontend/webv2/src/features/models/core/library.test.ts b/invokeai/frontend/webv2/src/features/models/core/library.test.ts
index 4f24376430..4f3c054c25 100644
--- a/invokeai/frontend/webv2/src/features/models/core/library.test.ts
+++ b/invokeai/frontend/webv2/src/features/models/core/library.test.ts
@@ -318,4 +318,27 @@ describe('sort fields', () => {
expect(sorted).toEqual(['main', 'main', 'lora', 'vae']);
});
+
+ it('sorts by install order, newest for a model the order does not list, and by name until the order loads', () => {
+ const ranks = new Map([
+ ['c', 0],
+ ['a', 1],
+ ['d', 2],
+ ]);
+ const sortedKeys = (sortDirection: 'asc' | 'desc') =>
+ filterModels(library, { ...DEFAULT_LIBRARY_FILTERS, sortDirection, sortField: 'added' }, NO_MISSING, ranks).map(
+ (m) => m.key
+ );
+
+ expect(sortedKeys('asc')).toEqual(['c', 'a', 'd', 'b']);
+ expect(sortedKeys('desc')).toEqual(['b', 'd', 'a', 'c']);
+ expect(
+ filterModels(
+ library,
+ { ...DEFAULT_LIBRARY_FILTERS, sortDirection: 'desc', sortField: 'added' },
+ NO_MISSING,
+ null
+ ).map((m) => m.key)
+ ).toEqual(['c', 'b', 'a', 'd']);
+ });
});
diff --git a/invokeai/frontend/webv2/src/features/models/core/library.ts b/invokeai/frontend/webv2/src/features/models/core/library.ts
index 9618b18578..ee7288ca1c 100644
--- a/invokeai/frontend/webv2/src/features/models/core/library.ts
+++ b/invokeai/frontend/webv2/src/features/models/core/library.ts
@@ -3,7 +3,7 @@ import type { ModelConfig, ModelTaxonomyType } from './types';
import { getModelBaseLabel, KNOWN_MODEL_BASES } from './baseIdentity';
import { getModelCategoryRank, getModelTypePluralLabel } from './taxonomy';
-export type ModelSortField = 'default' | 'name' | 'base' | 'size' | 'format' | 'type' | 'path';
+export type ModelSortField = 'default' | 'name' | 'base' | 'size' | 'added' | 'format' | 'type' | 'path';
export interface ModelLibraryFilters {
searchTerm: string;
@@ -81,22 +81,33 @@ const matchesSearchTerms = (model: ModelConfig, terms: readonly string[]): boole
return terms.every((term) => haystack.includes(term));
};
-const compareBySortField = (a: ModelConfig, b: ModelConfig, field: ModelSortField): number => {
+const compareByName = (a: ModelConfig, b: ModelConfig): number =>
+ a.name.localeCompare(b.name, undefined, { sensitivity: 'base' });
+
+const compareBySortField = (
+ a: ModelConfig,
+ b: ModelConfig,
+ field: ModelSortField,
+ dateAddedRanks: ReadonlyMap<string, number> | null
+): number => {
switch (field) {
case 'name':
case 'default':
- return a.name.localeCompare(b.name, undefined, { sensitivity: 'base' });
+ return compareByName(a, b);
case 'base':
return getModelBaseLabel(a.base).localeCompare(getModelBaseLabel(b.base));
case 'size':
return a.file_size - b.file_size;
+ case 'added': {
+ // An unlisted model was installed after the order was read, so it is the newest.
+ const newest = dateAddedRanks?.size ?? 0;
+
+ return (dateAddedRanks?.get(a.key) ?? newest) - (dateAddedRanks?.get(b.key) ?? newest) || compareByName(a, b);
+ }
case 'format':
return String(a.format).localeCompare(String(b.format));
case 'type':
- return (
- getModelCategoryRank(a.type) - getModelCategoryRank(b.type) ||
- a.name.localeCompare(b.name, undefined, { sensitivity: 'base' })
- );
+ return getModelCategoryRank(a.type) - getModelCategoryRank(b.type) || compareByName(a, b);
case 'path':
return a.path.localeCompare(b.path);
}
@@ -105,11 +116,16 @@ const compareBySortField = (a: ModelConfig, b: ModelConfig, field: ModelSortFiel
export const filterModels = (
models: ModelConfig[],
filters: ModelLibraryFilters,
- missingModelKeys: ReadonlySet<string>
+ missingModelKeys: ReadonlySet<string>,
+ /** Install-order ranks for the `added` sort, oldest first; until they load that sort lists by name, ascending. */
+ dateAddedRanks: ReadonlyMap<string, number> | null = null
): ModelConfig[] => {
// Split once per pass, not once per model.
const terms = filters.searchTerm.trim().toLowerCase().split(/\s+/).filter(Boolean);
- const directionFactor = filters.sortDirection === 'desc' ? -1 : 1;
+ // The direction waits for the install order: applied to the name fallback, it would flip the list and then
+ // reorder it again when the ranks land.
+ const isDescending = filters.sortDirection === 'desc' && (filters.sortField !== 'added' || dateAddedRanks !== null);
+ const directionFactor = isDescending ? -1 : 1;
return models
.filter(
@@ -119,7 +135,7 @@ export const filterModels = (
(filters.baseFilter === null || model.base === filters.baseFilter) &&
matchesSearchTerms(model, terms)
)
- .sort((a, b) => compareBySortField(a, b, filters.sortField) * directionFactor);
+ .sort((a, b) => compareBySortField(a, b, filters.sortField, dateAddedRanks) * directionFactor);
};
/**
diff --git a/invokeai/frontend/webv2/src/features/models/core/starters.ts b/invokeai/frontend/webv2/src/features/models/core/starters.ts
index 4678612bd6..2718700ea9 100644
--- a/invokeai/frontend/webv2/src/features/models/core/starters.ts
+++ b/invokeai/frontend/webv2/src/features/models/core/starters.ts
@@ -5,8 +5,8 @@ import { getModelBaseLabel } from './baseIdentity';
/** Pure filter/sort for the starter-models catalog; the installed-library twin is `library.ts`. */
-/** The catalog has no file sizes or install paths, and its type facet is the filter, not a sort. */
-export type StarterSortField = Exclude<ModelSortField, 'size' | 'type' | 'path'>;
+/** The catalog has no file sizes, install dates or install paths, and its type facet is the filter, not a sort. */
+export type StarterSortField = Exclude<ModelSortField, 'size' | 'added' | 'type' | 'path'>;
export interface StarterModelFilters {
/** null = all types. */
diff --git a/invokeai/frontend/webv2/src/features/models/data/api.ts b/invokeai/frontend/webv2/src/features/models/data/api.ts
index 5acbbca988..39ee2c8dfa 100644
--- a/invokeai/frontend/webv2/src/features/models/data/api.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/api.ts
@@ -28,6 +28,15 @@ export const listModels = async (signal?: AbortSignal): Promise<ModelConfig[]> =
return body.models ?? [];
};
+/** Model keys in install order, oldest first. Records carry no timestamp, so this listing's order is the only source. */
+export const listModelKeysByDateAdded = async (signal?: AbortSignal): Promise<string[]> => {
+ const body = await requestJson<{ models?: Pick<ModelConfig, 'key'>[] }>(`${MODELS_BASE}/?order_by=created_at`, {
+ signal,
+ });
+
+ return (body.models ?? []).map((model) => model.key);
+};
+
/** Models whose database record points at a file that no longer exists. */
export const listMissingModels = async (signal?: AbortSignal): Promise<ModelConfig[]> => {
const body = await requestJson<{ models?: ModelConfig[] }>(`${MODELS_BASE}/missing`, { signal });
diff --git a/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.ts b/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.ts
index 6c3c63c621..fc12789730 100644
--- a/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/modelsStore.test.ts
@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
const api = vi.hoisted(() => ({
getModelsDir: vi.fn(),
listMissingModels: vi.fn(),
+ listModelKeysByDateAdded: vi.fn(),
listModels: vi.fn(),
}));
@@ -15,6 +16,7 @@ describe('models store loading', () => {
vi.resetModules();
api.getModelsDir.mockReset().mockResolvedValue('/models');
api.listMissingModels.mockReset().mockResolvedValue([]);
+ api.listModelKeysByDateAdded.mockReset();
api.listModels.mockReset();
});
@@ -102,6 +104,53 @@ describe('models store loading', () => {
expect(store.getModelsSnapshot().models.map((model) => model.key)).toEqual(['a']);
});
+ it('reads install order only once it is asked for, even mid-refresh, then with every refresh', async () => {
+ const a = { base: 'sdxl', key: 'a', name: 'A', type: 'main' };
+ const b = { base: 'sdxl', key: 'b', name: 'B', type: 'main' };
+ api.listModels.mockResolvedValue([a, b]);
+ api.listModelKeysByDateAdded
+ // Outlasts the refresh already in flight, so only waiting for the trailing read can answer true.
+ .mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ setTimeout(() => resolve(['b', 'a']));
+ })
+ )
+ .mockResolvedValueOnce(['a', 'b']);
+ const store = await import('./modelsStore');
+
+ await store.refreshModels();
+ expect(api.listModelKeysByDateAdded).not.toHaveBeenCalled();
+ expect(store.getModelsSnapshot().dateAddedRanks).toBeNull();
+
+ void store.refreshModels();
+ await expect(store.ensureDateAddedOrderLoaded()).resolves.toBe(true);
+ expect([...store.getModelsSnapshot().dateAddedRanks!]).toEqual([
+ ['b', 0],
+ ['a', 1],
+ ]);
+ expect(store.getModelsSnapshot().models.map((model) => model.key)).toEqual(['a', 'b']);
+
+ await store.refreshModels();
+ expect([...store.getModelsSnapshot().dateAddedRanks!]).toEqual([
+ ['a', 0],
+ ['b', 1],
+ ]);
+ });
+
+ it('reports a failed install-order read without failing the library, and retries when asked again', async () => {
+ api.listModels.mockResolvedValue([{ base: 'sdxl', key: 'a', name: 'A', type: 'main' }]);
+ api.listModelKeysByDateAdded.mockRejectedValueOnce(new Error('down')).mockResolvedValueOnce(['a']);
+ const store = await import('./modelsStore');
+
+ await expect(store.ensureDateAddedOrderLoaded()).resolves.toBe(false);
+ expect(store.getModelsSnapshot()).toMatchObject({ dateAddedRanks: null, error: null, status: 'loaded' });
+ expect(store.getModelsSnapshot().models.map((model) => model.key)).toEqual(['a']);
+
+ await expect(store.ensureDateAddedOrderLoaded()).resolves.toBe(true);
+ expect([...store.getModelsSnapshot().dateAddedRanks!]).toEqual([['a', 0]]);
+ });
+
it.each(['replace', 'patch', 'delete', 'cover'] as const)(
'fences an older list after a confirmed %s and reads unrelated changes on the trailing pass',
async (mutation) => {
diff --git a/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts b/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts
index 49a94b2030..bbb50b396b 100644
--- a/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts
+++ b/invokeai/frontend/webv2/src/features/models/data/modelsStore.ts
@@ -10,7 +10,7 @@ import { createExternalStore } from '@platform/state/externalStore';
import { createTrailingSingleFlight } from '@platform/state/singleFlight';
import { getApiErrorMessage } from '@platform/transport/http';
-import { getModelsDir, listMissingModels, listModels } from './api';
+import { getModelsDir, listMissingModels, listModelKeysByDateAdded, listModels } from './api';
/**
* Share backend-owned model state outside the workbench reducer; mutations patch snapshots or refresh to keep all
@@ -22,6 +22,8 @@ export interface ModelsSnapshot {
/** Same models keyed for point lookups; always derived from `models`. */
modelsByKey: ReadonlyMap<string, ModelConfig>;
missingModelKeys: ReadonlySet<string>;
+ /** Each model's position in install order, oldest first; null until the Date added sort asks for it. */
+ dateAddedRanks: ReadonlyMap<string, number> | null;
/** Bumped when a model's cover image changes; cache-busts thumbnail URLs. */
coverImageVersions: Readonly<Record<string, number>>;
/** Absolute server path of the models directory (resolves relative model paths). */
@@ -35,6 +37,7 @@ const EMPTY_MODELS_BY_KEY: ReadonlyMap<string, ModelConfig> = new Map<string, Mo
const EMPTY_MODELS_SNAPSHOT: ModelsSnapshot = {
coverImageVersions: {},
+ dateAddedRanks: null,
error: null,
missingModelKeys: EMPTY_MISSING_KEYS,
models: [],
@@ -52,10 +55,12 @@ const store = createExternalStore<ModelsSnapshot>(EMPTY_MODELS_SNAPSHOT);
const refreshFlight = createTrailingSingleFlight();
let mutationGeneration = 0;
+let dateAddedOrderWanted = false;
registerAccountOwnedResource({
clear: () => {
mutationGeneration = 0;
+ dateAddedOrderWanted = false;
refreshFlight.reset();
store.setSnapshot(EMPTY_MODELS_SNAPSHOT);
},
@@ -90,8 +95,10 @@ export const refreshModels = (owner: AccountScope = captureAccountScope()): Prom
listMissingModels(owner.signal).catch(() => [] as ModelConfig[]),
// Static server config: fetched once, best-effort.
store.getSnapshot().modelsDir ?? getModelsDir(owner.signal).catch(() => null),
+ // Read with the catalog so the ranks describe the same refresh as `models`; best-effort like the two above.
+ dateAddedOrderWanted ? listModelKeysByDateAdded(owner.signal).catch(() => null) : null,
])
- .then(([models, missingModels, modelsDir]) => {
+ .then(([models, missingModels, modelsDir, dateAddedKeys]) => {
if (!isAccountScopeCurrent(owner)) {
return;
}
@@ -106,6 +113,8 @@ export const refreshModels = (owner: AccountScope = captureAccountScope()): Prom
store.patchSnapshot({
...withModels(withMissingFlags(models, missingKeys)),
+ // A failed order read keeps the previous ranks.
+ ...(dateAddedKeys ? { dateAddedRanks: new Map(dateAddedKeys.map((key, index) => [key, index])) } : null),
error: null,
missingModelKeys: missingKeys,
modelsDir,
@@ -140,6 +149,27 @@ export const ensureModelsLoaded = (): Promise<void> => {
return refreshFlight.inflight() ?? Promise.resolve();
};
+/**
+ * Start reading install order with the catalog, from now until the account changes. Resolves whether the order is
+ * loaded once the read this call asked for has settled; after a failed read, calling again retries.
+ */
+export const ensureDateAddedOrderLoaded = async (): Promise<boolean> => {
+ if (store.getSnapshot().dateAddedRanks) {
+ return true;
+ }
+
+ dateAddedOrderWanted = true;
+ await refreshModels();
+
+ // A refresh already in flight when this was called did not read the order, and one a mutation fenced discarded
+ // it; each queues a rerun that reads it, so wait those out too.
+ while (!store.getSnapshot().dateAddedRanks && refreshFlight.inflight()) {
+ await refreshFlight.inflight();
+ }
+
+ return store.getSnapshot().dateAddedRanks !== null;
+};
+
export const getModelsSnapshot = (): ModelsSnapshot => store.getSnapshot();
/** Read-only subscription for App-owned cross-feature runtimes. */
diff --git a/invokeai/frontend/webv2/src/features/models/ui/ModelManagerDrafts.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/ModelManagerDrafts.browser.test.tsx
index 66d2d1505f..5117438e52 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/ModelManagerDrafts.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/ModelManagerDrafts.browser.test.tsx
@@ -20,6 +20,7 @@ const { api, pending } = vi.hoisted(() => ({
api: {
getModelsDir: vi.fn(() => Promise.resolve('/models')),
listMissingModels: vi.fn(() => Promise.resolve([])),
+ listModelKeysByDateAdded: vi.fn(),
deleteModel: vi.fn(),
listModels: vi.fn(),
updateModel: vi.fn(),
@@ -358,6 +359,64 @@ describe('model manager in a single pane', () => {
expect(api.deleteModel).toHaveBeenCalledWith(B.key, expect.anything());
});
});
+describe('model library sorted by date added', () => {
+ let host: HTMLDivElement;
+ let root: Root;
+
+ beforeEach(async () => {
+ api.listModels.mockReset().mockResolvedValue([A, B]);
+ api.listModelKeysByDateAdded.mockReset();
+ accountLifecycle.activate('model-library-sort-test', ':user:model-library-sort-test');
+ setModelsSnapshotForTests({ models: [A, B], status: 'loaded' });
+ host = document.createElement('div');
+ host.style.cssText = 'display:flex;height:900px;width:1200px;';
+ document.body.append(host);
+ root = createRoot(host);
+ await act(() =>
+ root.render(
+ <ChakraProvider value={system}>
+ <ModelManagerView />
+ </ChakraProvider>
+ )
+ );
+ });
+
+ afterEach(async () => {
+ await act(() => root.unmount());
+ host.remove();
+ accountLifecycle.invalidate();
+ });
+
+ it('reads the install order on the sort pick, not on a search keystroke, and lists the newest first', async () => {
+ let finishOrderRead!: (keys: string[]) => void;
+ api.listModelKeysByDateAdded.mockReturnValueOnce(
+ new Promise((resolve) => {
+ finishOrderRead = resolve;
+ })
+ );
+ const rowKeys = () =>
+ [...host.querySelectorAll('[data-list-row]')]
+ .map((row) => row.getAttribute('data-list-row')!)
+ .filter((key) => !key.startsWith('header:'));
+
+ expect(rowKeys()).toEqual([A.key, B.key]);
+
+ await page.getByRole('button', { name: 'models.filterAndSort', exact: true }).click();
+ await page.getByRole('menuitem', { name: /models\.sortBy/ }).click();
+ await page.getByRole('menuitemcheckbox', { name: 'models.sort.added' }).click();
+ expect(api.listModelKeysByDateAdded).toHaveBeenCalledOnce();
+
+ // Typed while the read is still open: a keystroke that asked again would queue a second read behind it.
+ await page.getByRole('textbox', { name: 'models.searchModels' }).fill('Lora');
+ await act(async () => {
+ finishOrderRead([A.key, B.key]);
+ await Promise.resolve();
+ });
+
+ await expect.poll(rowKeys).toEqual([B.key, A.key]);
+ expect(api.listModelKeysByDateAdded).toHaveBeenCalledOnce();
+ });
+});
const buttonContaining = (text: string) =>
[...document.querySelectorAll<HTMLButtonElement>('button')].find((button) => button.textContent.includes(text))!;
const saveChangesButton = () => buttonContaining('users.saveChanges');
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/CpuOnlySetting.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/CpuOnlySetting.browser.test.tsx
index 8d3d13f92f..dfb0ad1c2b 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/CpuOnlySetting.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/CpuOnlySetting.browser.test.tsx
@@ -14,6 +14,7 @@ import { CpuOnlySetting } from './CpuOnlySetting';
const api = vi.hoisted(() => ({
getModelsDir: vi.fn(),
listMissingModels: vi.fn(),
+ listModelKeysByDateAdded: vi.fn(),
listModels: vi.fn(),
updateModel: vi.fn(),
}));
diff --git a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelEditForm.browser.test.tsx b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelEditForm.browser.test.tsx
index 96743f73e2..dd24081862 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/detail/ModelEditForm.browser.test.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/detail/ModelEditForm.browser.test.tsx
@@ -14,6 +14,7 @@ import { ModelEditForm } from './ModelEditForm';
const api = vi.hoisted(() => ({
getModelsDir: vi.fn(),
listMissingModels: vi.fn(),
+ listModelKeysByDateAdded: vi.fn(),
listModels: vi.fn(),
updateModel: vi.fn(),
}));
diff --git a/invokeai/frontend/webv2/src/features/models/ui/library/ModelLibraryList.tsx b/invokeai/frontend/webv2/src/features/models/ui/library/ModelLibraryList.tsx
index d10e89078f..f11bcfcf4e 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/library/ModelLibraryList.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/library/ModelLibraryList.tsx
@@ -47,9 +47,10 @@ export const ModelLibraryList = ({
selectedKeys: ReadonlySet<string>;
}) => {
const { t } = useTranslation();
- const { coverImageVersions, error, missingModelKeys, models, status } = useModelsSelector(
+ const { coverImageVersions, dateAddedRanks, error, missingModelKeys, models, status } = useModelsSelector(
(snapshot) => ({
coverImageVersions: snapshot.coverImageVersions,
+ dateAddedRanks: snapshot.dateAddedRanks,
error: snapshot.error,
missingModelKeys: snapshot.missingModelKeys,
models: snapshot.models,
@@ -57,6 +58,7 @@ export const ModelLibraryList = ({
}),
(left, right) =>
left.coverImageVersions === right.coverImageVersions &&
+ left.dateAddedRanks === right.dateAddedRanks &&
left.error === right.error &&
left.missingModelKeys === right.missingModelKeys &&
left.models === right.models &&
@@ -82,16 +84,17 @@ export const ModelLibraryList = ({
const rows = useMemo(
() =>
listRowsFromSections(
- groupModelsByType(filterModels(models, deferredFilters, missingModelKeys), deferredFilters.typeFilter).map(
- (group) => ({
- items: group.entries,
- key: group.type,
- label: group.label,
- })
- ),
+ groupModelsByType(
+ filterModels(models, deferredFilters, missingModelKeys, dateAddedRanks),
+ deferredFilters.typeFilter
+ ).map((group) => ({
+ items: group.entries,
+ key: group.type,
+ label: group.label,
+ })),
getRowKey
),
- [deferredFilters, missingModelKeys, models]
+ [dateAddedRanks, deferredFilters, missingModelKeys, models]
);
// Persist the offset so switching tabs/regions and coming back lands here.
diff --git a/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsx b/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsx
index ca32a6d05c..56f74f825f 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/manager/LibraryColumn.tsx
@@ -2,7 +2,12 @@
import { Icon } from '@chakra-ui/react';
import { collectBases, collectTypes, filterModels } from '@features/models/core/library';
import { bulkDeleteModels, bulkReidentifyModels } from '@features/models/data/api';
-import { refreshModels, removeModelsFromStore, useModelsSelector } from '@features/models/data/modelsStore';
+import {
+ ensureDateAddedOrderLoaded,
+ refreshModels,
+ removeModelsFromStore,
+ useModelsSelector,
+} from '@features/models/data/modelsStore';
import { refreshStartersIfLoaded } from '@features/models/data/startersStore';
import { MaintenanceMenu } from '@features/models/ui/library/MaintenanceMenu';
import { ModelFilterBar } from '@features/models/ui/library/ModelFilterBar';
@@ -16,7 +21,11 @@ import {
} from '@features/models/ui/uiStore';
import { useNotify } from '@features/models/ui/useModelsNotify';
import { useScopedAction } from '@platform/react/useScopedAction';
-import { assertAccountScopeCurrent } from '@platform/state/accountLifecycle';
+import {
+ assertAccountScopeCurrent,
+ captureAccountScope,
+ isAccountScopeCurrent,
+} from '@platform/state/accountLifecycle';
import { Button, IconButton, ConfirmDialog } from '@platform/ui';
import { ListSelectionBar } from '@platform/ui/list/ListSelectionBar';
import { ManagerColumn, type ManagerAddAction } from '@platform/ui/ManagerLayout';
@@ -161,7 +170,23 @@ export const LibraryColumn = ({ addAction }: { addAction: ManagerAddAction }) =>
availableTypes={availableTypes}
filters={filters}
missingCount={missingCount}
- onChange={(nextFilters) => updateModelsUi({ filters: nextFilters })}
+ onChange={(nextFilters) => {
+ updateModelsUi({ filters: nextFilters });
+ // Only a sort pick asks: a search keystroke under this sort must not refresh the library while the order
+ // is still loading or failing. Re-picking flips the direction, which is the retry.
+ if (
+ nextFilters.sortField === 'added' &&
+ (nextFilters.sortField !== filters.sortField || nextFilters.sortDirection !== filters.sortDirection)
+ ) {
+ const owner = captureAccountScope();
+
+ void ensureDateAddedOrderLoaded().then((loaded) => {
+ if (!loaded && isAccountScopeCurrent(owner)) {
+ notify.error(t('models.dateAddedUnavailable'), t('models.dateAddedUnavailableDescription'));
+ }
+ });
+ }
+ }}
/>
<ListSelectionBar
diff --git a/invokeai/frontend/webv2/src/features/models/ui/shared/ModelFilterMenu.tsx b/invokeai/frontend/webv2/src/features/models/ui/shared/ModelFilterMenu.tsx
index 603753e508..ce90257e1b 100644
--- a/invokeai/frontend/webv2/src/features/models/ui/shared/ModelFilterMenu.tsx
+++ b/invokeai/frontend/webv2/src/features/models/ui/shared/ModelFilterMenu.tsx
@@ -18,6 +18,8 @@ const SUBMENU_POSITIONING = { placement: 'right-start' } as const;
export interface ModelFilterSortOption<Field extends ModelSortField = ModelSortField> {
field: Field;
+ /** Direction a first selection of this field sorts in; ascending when omitted. */
+ initialDirection?: 'asc' | 'desc';
labelKey: string;
}
@@ -28,6 +30,7 @@ export const SORT_FIELD_OPTIONS: readonly ModelFilterSortOption[] = [
{ field: 'base', labelKey: 'models.sort.base' },
{ field: 'type', labelKey: 'models.sort.type' },
{ field: 'size', labelKey: 'models.sort.size' },
+ { field: 'added', initialDirection: 'desc', labelKey: 'models.sort.added' },
{ field: 'format', labelKey: 'models.sort.format' },
{ field: 'path', labelKey: 'models.sort.path' },
];
@@ -132,10 +135,11 @@ export const ModelFilterMenu = <Field extends ModelSortField>({
</FilterSubMenu>
<Menu.Separator />
<FilterSubMenu icon={ArrowUpDownIcon} label={t('models.sortBy')} summary={sortSummary}>
- {sortFields.map(({ field, labelKey }) => (
+ {sortFields.map(({ field, initialDirection, labelKey }) => (
<SortFilterMenuItem
key={field}
field={field}
+ initialDirection={initialDirection}
labelKey={labelKey}
sortDirection={sortDirection}
sortField={sortField}
@@ -290,12 +294,14 @@ const BaseFilterMenuItem = memo(function BaseFilterMenuItem({
const SortFilterMenuItem = memo(function SortFilterMenuItem({
field,
+ initialDirection = 'asc',
labelKey,
sortDirection,
sortField,
onSortChange,
}: {
field: ModelSortField;
+ initialDirection?: 'asc' | 'desc';
labelKey: string;
sortDirection: 'asc' | 'desc';
sortField: ModelSortField;
@@ -308,7 +314,9 @@ const SortFilterMenuItem = memo(function SortFilterMenuItem({
isChecked={sortField === field}
label={t(labelKey)}
value={`sort-${field}`}
- onSelect={() => onSortChange(field, sortField === field ? (sortDirection === 'asc' ? 'desc' : 'asc') : 'asc')}
+ onSelect={() =>
+ onSortChange(field, sortField === field ? (sortDirection === 'asc' ? 'desc' : 'asc') : initialDirection)
+ }
trailing={sortField === field ? (sortDirection === 'asc' ? t('common.asc') : t('common.desc')) : undefined}
/>
);