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.

feat(webv2): pure workflow model-requirement extraction and resolution

joshistoast47fdc3cbd3ed
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.test.ts b/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.test.ts
new file mode 100644
index 0000000000..a3f0fbce8e
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.test.ts
@@ -0,0 +1,396 @@
+import { describe, expect, it } from 'vitest';
+
+import type {
+ FieldInputTemplate,
+ InvocationTemplate,
+ InvocationTemplates,
+ ProjectGraphState,
+ WorkflowEdge,
+ WorkflowInvocationNode,
+} from './types';
+
+import {
+ extractWorkflowModelRequirements,
+ resolveWorkflowModelRequirements,
+ type InstalledModelSummary,
+ type StarterCatalogEntry,
+ type WorkflowModelRequirement,
+} from './modelRequirements';
+
+/**
+ * Fixture helpers mirror `graphToDocument.test.ts`: minimal templates and
+ * documents built inline rather than mocking the module under test.
+ */
+
+const fieldInput = (name: string, overrides: Partial<FieldInputTemplate> = {}): FieldInputTemplate => ({
+ default: undefined,
+ description: '',
+ exclusiveMaximum: null,
+ exclusiveMinimum: null,
+ input: 'any',
+ maximum: null,
+ minimum: null,
+ multipleOf: null,
+ name,
+ options: null,
+ required: false,
+ title: name,
+ type: { batch: false, cardinality: 'SINGLE', name: 'ModelIdentifierField' },
+ uiChoiceLabels: null,
+ uiComponent: null,
+ uiHidden: false,
+ uiModelBase: null,
+ uiModelFormat: null,
+ uiModelType: null,
+ uiOrder: null,
+ ...overrides,
+});
+
+const invocationTemplate = (type: string, inputs: Record<string, FieldInputTemplate>): InvocationTemplate => ({
+ category: 'test',
+ classification: 'stable',
+ description: '',
+ inputs,
+ nodePack: 'invokeai',
+ outputs: {},
+ outputType: `${type}_output`,
+ tags: [],
+ title: type,
+ type,
+ useCache: true,
+ version: '1.0.0',
+});
+
+const invocationNode = (id: string, type: string, inputs: Record<string, unknown> = {}): WorkflowInvocationNode => ({
+ data: {
+ inputs: Object.fromEntries(Object.entries(inputs).map(([name, value]) => [name, { label: '', name, value }])),
+ isIntermediate: false,
+ isOpen: true,
+ label: '',
+ nodePack: 'invokeai',
+ notes: '',
+ type,
+ useCache: true,
+ version: '1.0.0',
+ },
+ id,
+ position: { x: 0, y: 0 },
+ type: 'invocation',
+});
+
+const graphDocument = (nodes: WorkflowInvocationNode[], edges: WorkflowEdge[] = []): ProjectGraphState => ({
+ author: '',
+ contact: '',
+ description: '',
+ edges,
+ form: { elements: {}, rootElementId: 'root' },
+ id: 'doc',
+ name: 'doc',
+ nodes,
+ notes: '',
+ tags: '',
+ updatedAt: '2024-01-01T00:00:00.000Z',
+ version: 2,
+ workflowVersion: '1.0.0',
+});
+
+describe('extractWorkflowModelRequirements', () => {
+ it('extracts an exact requirement when a model field value duck-types a model identifier', () => {
+ const templates: InvocationTemplates = {
+ main_model_loader: invocationTemplate('main_model_loader', {
+ model: fieldInput('model', { required: true }),
+ }),
+ };
+ const document = graphDocument([
+ invocationNode('loader', 'main_model_loader', {
+ model: { base: 'sdxl', hash: 'hash-1', key: 'model-key-1', name: 'My Model', type: 'main' },
+ }),
+ ]);
+
+ const { requirements } = extractWorkflowModelRequirements(document, templates);
+
+ expect(requirements).toEqual([
+ {
+ identifier: { base: 'sdxl', hash: 'hash-1', key: 'model-key-1', name: 'My Model', type: 'main' },
+ kind: 'exact',
+ label: 'My Model',
+ },
+ ]);
+ });
+
+ it('skips inputs that are fed by a connection', () => {
+ const templates: InvocationTemplates = {
+ main_model_loader: invocationTemplate('main_model_loader', {
+ model: fieldInput('model', { required: true, uiModelBase: ['sdxl'], uiModelType: ['main'] }),
+ }),
+ upstream: invocationTemplate('upstream', {}),
+ };
+ const document = graphDocument(
+ [invocationNode('upstream', 'upstream'), invocationNode('loader', 'main_model_loader', {})],
+ [
+ {
+ id: 'e1',
+ source: 'upstream',
+ sourceHandle: 'model',
+ target: 'loader',
+ targetHandle: 'model',
+ type: 'default',
+ },
+ ]
+ );
+
+ const { requirements } = extractWorkflowModelRequirements(document, templates);
+
+ expect(requirements).toEqual([]);
+ });
+
+ it('dedupes exact requirements that share a key', () => {
+ const templates: InvocationTemplates = {
+ loader: invocationTemplate('loader', { model: fieldInput('model', { required: true }) }),
+ };
+ const document = graphDocument([
+ invocationNode('a', 'loader', { model: { key: 'shared-key', name: 'Shared' } }),
+ invocationNode('b', 'loader', { model: { key: 'shared-key', name: 'Shared' } }),
+ ]);
+
+ const { requirements } = extractWorkflowModelRequirements(document, templates);
+
+ expect(requirements).toHaveLength(1);
+ });
+
+ it('extracts a slot requirement for an empty required model field, labeled from uiModelBase/uiModelType', () => {
+ const templates: InvocationTemplates = {
+ main_model_loader: invocationTemplate('main_model_loader', {
+ model: fieldInput('model', { required: true, title: 'Model', uiModelBase: ['sdxl'], uiModelType: ['main'] }),
+ }),
+ };
+ const document = graphDocument([invocationNode('loader', 'main_model_loader', {})]);
+
+ const { requirements } = extractWorkflowModelRequirements(document, templates);
+
+ expect(requirements).toEqual([{ base: 'sdxl', kind: 'slot', label: 'SDXL checkpoint', modelType: 'main' }]);
+ });
+
+ it('does not extract a slot requirement for an empty optional model field', () => {
+ const templates: InvocationTemplates = {
+ main_model_loader: invocationTemplate('main_model_loader', {
+ model: fieldInput('model', { required: false, uiModelBase: ['sdxl'], uiModelType: ['main'] }),
+ }),
+ };
+ const document = graphDocument([invocationNode('loader', 'main_model_loader', {})]);
+
+ const { requirements } = extractWorkflowModelRequirements(document, templates);
+
+ expect(requirements).toEqual([]);
+ });
+
+ it('prefers the most frequent main-type base for primaryBase over a more frequent non-main base', () => {
+ const templates: InvocationTemplates = {
+ loader: invocationTemplate('loader', { model: fieldInput('model', { required: true }) }),
+ vae_loader: invocationTemplate('vae_loader', { vae_model: fieldInput('vae_model', { required: true }) }),
+ };
+ const document = graphDocument([
+ invocationNode('a', 'loader', { model: { base: 'sd-1', key: 'k1', type: 'main' } }),
+ invocationNode('b', 'loader', { model: { base: 'sdxl', key: 'k2', type: 'main' } }),
+ invocationNode('c', 'loader', { model: { base: 'sdxl', key: 'k3', type: 'main' } }),
+ invocationNode('d', 'vae_loader', { vae_model: { base: 'sd-1', key: 'k4', type: 'vae' } }),
+ invocationNode('e', 'vae_loader', { vae_model: { base: 'sd-1', key: 'k5', type: 'vae' } }),
+ ]);
+
+ const { primaryBase } = extractWorkflowModelRequirements(document, templates);
+
+ expect(primaryBase).toBe('sdxl');
+ });
+
+ it('falls back to the most frequent base overall when no exact main-type identifier is present', () => {
+ const templates: InvocationTemplates = {
+ vae_loader: invocationTemplate('vae_loader', {
+ vae_model: fieldInput('vae_model', { required: true, uiModelBase: ['flux'], uiModelType: ['vae'] }),
+ }),
+ };
+ const document = graphDocument([invocationNode('a', 'vae_loader', {})]);
+
+ const { primaryBase } = extractWorkflowModelRequirements(document, templates);
+
+ expect(primaryBase).toBe('flux');
+ });
+
+ it('returns a null primaryBase when there are no requirements with a known base', () => {
+ const document = graphDocument([]);
+
+ const { primaryBase, requirements } = extractWorkflowModelRequirements(document, {});
+
+ expect(requirements).toEqual([]);
+ expect(primaryBase).toBeNull();
+ });
+});
+
+describe('resolveWorkflowModelRequirements', () => {
+ it('resolves an exact requirement as installed via a plain key hit', () => {
+ const requirement: WorkflowModelRequirement = {
+ identifier: { key: 'model-key-1', name: 'My Model' },
+ kind: 'exact',
+ label: 'My Model',
+ };
+ const installedModels: InstalledModelSummary[] = [
+ { base: 'sdxl', hash: 'hash-1', key: 'model-key-1', name: 'My Model', type: 'main' },
+ ];
+
+ const [resolved] = resolveWorkflowModelRequirements([requirement], {
+ activeInstallSources: new Set(),
+ installedModels,
+ starterModels: [],
+ });
+
+ expect(resolved).toMatchObject({ matchedModelName: 'My Model', starterMatch: null, status: 'installed' });
+ });
+
+ it('falls back to a hash match when the key does not hit', () => {
+ const requirement: WorkflowModelRequirement = {
+ identifier: { base: 'sdxl', hash: 'hash-1', key: 'unknown-key', name: 'My Model', type: 'main' },
+ kind: 'exact',
+ label: 'My Model',
+ };
+ const installedModels: InstalledModelSummary[] = [
+ { base: 'sdxl', hash: 'hash-1', key: 'installed-key', name: 'My Model', type: 'main' },
+ ];
+
+ const [resolved] = resolveWorkflowModelRequirements([requirement], {
+ activeInstallSources: new Set(),
+ installedModels,
+ starterModels: [],
+ });
+
+ expect(resolved).toMatchObject({ matchedModelName: 'My Model', status: 'installed' });
+ });
+
+ it('falls back to a name+base+type match when key and hash both miss', () => {
+ const requirement: WorkflowModelRequirement = {
+ identifier: { base: 'sdxl', hash: 'unknown-hash', key: 'unknown-key', name: 'My Model', type: 'main' },
+ kind: 'exact',
+ label: 'My Model',
+ };
+ const installedModels: InstalledModelSummary[] = [
+ { base: 'sdxl', hash: 'different-hash', key: 'installed-key', name: 'My Model', type: 'main' },
+ ];
+
+ const [resolved] = resolveWorkflowModelRequirements([requirement], {
+ activeInstallSources: new Set(),
+ installedModels,
+ starterModels: [],
+ });
+
+ expect(resolved).toMatchObject({ matchedModelName: 'My Model', status: 'installed' });
+ });
+
+ it('resolves a slot requirement as installed when any installed model matches the base (+ type)', () => {
+ const requirement: WorkflowModelRequirement = {
+ base: 'sdxl',
+ kind: 'slot',
+ label: 'SDXL checkpoint',
+ modelType: 'main',
+ };
+ const installedModels: InstalledModelSummary[] = [
+ { base: 'sdxl', hash: 'h', key: 'k', name: 'Some SDXL Checkpoint', type: 'main' },
+ ];
+
+ const [resolved] = resolveWorkflowModelRequirements([requirement], {
+ activeInstallSources: new Set(),
+ installedModels,
+ starterModels: [],
+ });
+
+ expect(resolved).toMatchObject({ matchedModelName: 'Some SDXL Checkpoint', status: 'installed' });
+ });
+
+ it('matches a starter catalog entry via previous_names, case-insensitively', () => {
+ const requirement: WorkflowModelRequirement = {
+ identifier: { base: 'sdxl', key: 'missing-key', name: 'old name', type: 'main' },
+ kind: 'exact',
+ label: 'old name',
+ };
+ const starterModels: StarterCatalogEntry[] = [
+ {
+ base: 'sdxl',
+ is_installed: false,
+ name: 'New Name',
+ previous_names: ['Old Name'],
+ source: 'hf/some-model',
+ type: 'main',
+ },
+ ];
+
+ const [resolved] = resolveWorkflowModelRequirements([requirement], {
+ activeInstallSources: new Set(),
+ installedModels: [],
+ starterModels,
+ });
+
+ expect(resolved?.status).toBe('installable');
+ expect(resolved?.starterMatch?.name).toBe('New Name');
+ });
+
+ it('is installing when the matched starter source is in activeInstallSources', () => {
+ const requirement: WorkflowModelRequirement = {
+ base: 'sdxl',
+ kind: 'slot',
+ label: 'SDXL checkpoint',
+ modelType: 'main',
+ };
+ const starterModels: StarterCatalogEntry[] = [
+ { base: 'sdxl', is_installed: false, name: 'Some SDXL Checkpoint', source: 'hf/some-model', type: 'main' },
+ ];
+
+ const [resolved] = resolveWorkflowModelRequirements([requirement], {
+ activeInstallSources: new Set(['hf/some-model']),
+ installedModels: [],
+ starterModels,
+ });
+
+ expect(resolved?.status).toBe('installing');
+ });
+
+ it('is installing when a dependency source of the matched starter is in activeInstallSources', () => {
+ const requirement: WorkflowModelRequirement = {
+ base: 'sdxl',
+ kind: 'slot',
+ label: 'SDXL checkpoint',
+ modelType: 'main',
+ };
+ const starterModels: StarterCatalogEntry[] = [
+ {
+ base: 'sdxl',
+ dependencies: [{ is_installed: false, source: 'hf/dependency' }],
+ is_installed: false,
+ name: 'Some SDXL Checkpoint',
+ source: 'hf/some-model',
+ type: 'main',
+ },
+ ];
+
+ const [resolved] = resolveWorkflowModelRequirements([requirement], {
+ activeInstallSources: new Set(['hf/dependency']),
+ installedModels: [],
+ starterModels,
+ });
+
+ expect(resolved?.status).toBe('installing');
+ });
+
+ it('is unresolvable when nothing installed or in the starter catalog matches', () => {
+ const requirement: WorkflowModelRequirement = {
+ base: 'flux',
+ kind: 'slot',
+ label: 'FLUX checkpoint',
+ modelType: 'main',
+ };
+
+ const [resolved] = resolveWorkflowModelRequirements([requirement], {
+ activeInstallSources: new Set(),
+ installedModels: [],
+ starterModels: [],
+ });
+
+ expect(resolved).toMatchObject({ matchedModelName: null, starterMatch: null, status: 'unresolvable' });
+ });
+});
diff --git a/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.ts b/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.ts
new file mode 100644
index 0000000000..83c947e9f0
--- /dev/null
+++ b/invokeai/frontend/webv2/src/features/workflow/core/modelRequirements.ts
@@ -0,0 +1,454 @@
+import type { FieldInputTemplate, InvocationTemplates, ProjectGraphState } from './types';
+
+import { isModelFieldType } from './fields';
+import { isInvocationNode } from './types';
+
+/**
+ * "Which models does this workflow need, and are they installed?" — pure
+ * extraction from a project graph document plus template metadata, and pure
+ * resolution against injected installed/starter-catalog data. 28 of the 29
+ * shipped default workflows ship with *blank* model fields: the template's
+ * `uiModelBase` / `uiModelType` hints on an empty required input (the "slot"
+ * requirement) are how those workflows say what they need, so slot handling
+ * is not a fallback path — it's the common case.
+ */
+
+export interface WorkflowModelIdentifier {
+ key: string;
+ hash?: string;
+ name?: string;
+ base?: string;
+ type?: string;
+}
+
+export type WorkflowModelRequirement =
+ | { kind: 'exact'; identifier: WorkflowModelIdentifier; label: string }
+ | { kind: 'slot'; base: string | null; modelType: string | null; label: string };
+
+export interface WorkflowModelRequirementSet {
+ requirements: readonly WorkflowModelRequirement[];
+ primaryBase: string | null;
+}
+
+// #region Labeling
+
+/** Display labels for known model bases. Unknown bases fall back to a humanized form. */
+const BASE_LABELS: Record<string, string> = {
+ any: 'Any',
+ anima: 'Anima',
+ cogview4: 'CogView4',
+ external: 'External',
+ flux: 'FLUX',
+ flux2: 'FLUX.2',
+ 'ideogram-4': 'Ideogram 4',
+ 'krea-2': 'Krea-2',
+ 'qwen-image': 'Qwen Image',
+ 'sd-1': 'SD 1.x',
+ 'sd-2': 'SD 2.x',
+ 'sd-3': 'SD 3.x',
+ sdxl: 'SDXL',
+ 'sdxl-refiner': 'SDXL Refiner',
+ unknown: 'Unknown',
+ wan: 'Wan 2.2',
+ 'z-image': 'Z-Image',
+};
+
+/** Display labels for known model taxonomy types. Unknown types fall back to a humanized form. */
+const MODEL_TYPE_LABELS: Record<string, string> = {
+ clip_embed: 'CLIP embed',
+ clip_vision: 'CLIP Vision',
+ control_lora: 'Control LoRA',
+ controlnet: 'ControlNet',
+ embedding: 'embedding',
+ external_image_generator: 'external image generator',
+ flux_redux: 'FLUX Redux',
+ gemma2_encoder: 'Gemma2 encoder',
+ ip_adapter: 'IP Adapter',
+ llava_onevision: 'LLaVA OneVision',
+ lora: 'LoRA',
+ main: 'checkpoint',
+ mistral_encoder: 'Mistral encoder',
+ onnx: 'ONNX model',
+ pid_decoder: 'PID decoder',
+ qwen3_encoder: 'Qwen3 encoder',
+ qwen3_vl_encoder: 'Qwen3 VL encoder',
+ qwen_vl_encoder: 'Qwen VL encoder',
+ siglip: 'SigLIP',
+ spandrel_image_to_image: 'upscaler',
+ t2i_adapter: 'T2I Adapter',
+ t5_encoder: 'T5 encoder',
+ text_llm: 'text LLM',
+ unknown: 'model',
+ vae: 'VAE',
+ wan_t5_encoder: 'Wan T5 encoder',
+};
+
+const humanize = (value: string): string => value.replaceAll(/[_-]+/g, ' ');
+
+const getBaseLabel = (base: string): string => BASE_LABELS[base] ?? humanize(base);
+
+const getModelTypeLabel = (modelType: string): string => MODEL_TYPE_LABELS[modelType] ?? humanize(modelType);
+
+const capitalize = (value: string): string => (value.length === 0 ? value : value[0]?.toUpperCase() + value.slice(1));
+
+const buildSlotLabel = (fieldTemplate: FieldInputTemplate, base: string | null, modelType: string | null): string => {
+ const baseLabel = base ? getBaseLabel(base) : null;
+ const typeLabel = modelType ? getModelTypeLabel(modelType) : null;
+
+ if (baseLabel && typeLabel) {
+ return `${baseLabel} ${typeLabel}`;
+ }
+
+ if (baseLabel) {
+ return `${baseLabel} model`;
+ }
+
+ if (typeLabel) {
+ return capitalize(typeLabel);
+ }
+
+ return fieldTemplate.title || fieldTemplate.name;
+};
+
+// #endregion
+
+// #region Extraction
+
+interface DuckTypedModelValue {
+ key: string;
+ hash?: unknown;
+ name?: unknown;
+ base?: unknown;
+ type?: unknown;
+}
+
+const isDuckTypedModelValue = (value: unknown): value is DuckTypedModelValue =>
+ typeof value === 'object' &&
+ value !== null &&
+ typeof (value as Record<string, unknown>).key === 'string' &&
+ ((value as Record<string, unknown>).key as string).trim().length > 0;
+
+const buildIdentifier = (value: DuckTypedModelValue): WorkflowModelIdentifier => {
+ const identifier: WorkflowModelIdentifier = { key: value.key };
+
+ if (typeof value.hash === 'string') {
+ identifier.hash = value.hash;
+ }
+
+ if (typeof value.name === 'string') {
+ identifier.name = value.name;
+ }
+
+ if (typeof value.base === 'string') {
+ identifier.base = value.base;
+ }
+
+ if (typeof value.type === 'string') {
+ identifier.type = value.type;
+ }
+
+ return identifier;
+};
+
+const mostFrequentBase = (counts: Map<string, number>): string | null => {
+ let best: string | null = null;
+ let bestCount = 0;
+
+ for (const [base, count] of counts) {
+ if (count > bestCount) {
+ best = base;
+ bestCount = count;
+ }
+ }
+
+ return best;
+};
+
+const computePrimaryBase = (requirements: readonly WorkflowModelRequirement[]): string | null => {
+ const mainBaseCounts = new Map<string, number>();
+ const allBaseCounts = new Map<string, number>();
+
+ const bump = (counts: Map<string, number>, base: string): void => {
+ counts.set(base, (counts.get(base) ?? 0) + 1);
+ };
+
+ for (const requirement of requirements) {
+ if (requirement.kind === 'exact') {
+ if (requirement.identifier.base) {
+ bump(allBaseCounts, requirement.identifier.base);
+
+ if (requirement.identifier.type === 'main') {
+ bump(mainBaseCounts, requirement.identifier.base);
+ }
+ }
+ } else if (requirement.base) {
+ bump(allBaseCounts, requirement.base);
+ }
+ }
+
+ return mostFrequentBase(mainBaseCounts) ?? mostFrequentBase(allBaseCounts);
+};
+
+/**
+ * Walks invocation nodes' model-typed inputs and classifies each as an
+ * `exact` requirement (a concrete `{ key }` value) or a `slot` requirement
+ * (an empty *required* field, described by its template's `uiModelBase` /
+ * `uiModelType` hints). Connection-fed inputs are skipped entirely — the
+ * upstream node is what actually needs a model, not this pass-through.
+ */
+export const extractWorkflowModelRequirements = (
+ document: ProjectGraphState,
+ templates: InvocationTemplates
+): WorkflowModelRequirementSet => {
+ const connectionTargets = new Set(document.edges.map((edge) => `${edge.target}::${edge.targetHandle}`));
+
+ const requirements: WorkflowModelRequirement[] = [];
+ const exactKeyHashes = new Map<string, string | undefined>();
+ const seenExactDedupeKeys = new Set<string>();
+ const seenSlotSignatures = new Set<string>();
+
+ for (const node of document.nodes) {
+ if (!isInvocationNode(node)) {
+ continue;
+ }
+
+ const template = templates[node.data.type];
+
+ if (!template) {
+ continue;
+ }
+
+ for (const fieldTemplate of Object.values(template.inputs)) {
+ if (!isModelFieldType(fieldTemplate.type)) {
+ continue;
+ }
+
+ if (connectionTargets.has(`${node.id}::${fieldTemplate.name}`)) {
+ continue;
+ }
+
+ const value = node.data.inputs[fieldTemplate.name]?.value;
+
+ if (isDuckTypedModelValue(value)) {
+ const identifier = buildIdentifier(value);
+
+ let dedupeKey = identifier.key;
+
+ if (exactKeyHashes.has(identifier.key)) {
+ const existingHash = exactKeyHashes.get(identifier.key);
+
+ if (identifier.hash !== undefined && existingHash !== undefined && existingHash !== identifier.hash) {
+ dedupeKey = `${identifier.key}::${identifier.hash}`;
+ }
+ } else {
+ exactKeyHashes.set(identifier.key, identifier.hash);
+ }
+
+ if (seenExactDedupeKeys.has(dedupeKey)) {
+ continue;
+ }
+
+ seenExactDedupeKeys.add(dedupeKey);
+ requirements.push({ identifier, kind: 'exact', label: identifier.name ?? identifier.key });
+ continue;
+ }
+
+ if (!fieldTemplate.required) {
+ continue;
+ }
+
+ const base = fieldTemplate.uiModelBase?.[0] ?? null;
+ const modelType = fieldTemplate.uiModelType?.[0] ?? null;
+ const signature = `${base ?? ''}::${modelType ?? ''}`;
+
+ if (seenSlotSignatures.has(signature)) {
+ continue;
+ }
+
+ seenSlotSignatures.add(signature);
+ requirements.push({ base, kind: 'slot', label: buildSlotLabel(fieldTemplate, base, modelType), modelType });
+ }
+ }
+
+ return { primaryBase: computePrimaryBase(requirements), requirements };
+};
+
+// #endregion
+
+// #region Resolution
+
+export interface InstalledModelSummary {
+ key: string;
+ hash: string;
+ name: string;
+ base: string;
+ type: string;
+}
+
+export interface StarterCatalogEntry {
+ name: string;
+ previous_names?: string[] | null;
+ base: string;
+ type: string;
+ source: string;
+ is_installed: boolean;
+ dependencies?: readonly { source: string; is_installed: boolean }[] | null;
+}
+
+export type ModelRequirementStatus = 'installed' | 'installing' | 'installable' | 'unresolvable';
+
+export interface ResolvedModelRequirement {
+ requirement: WorkflowModelRequirement;
+ status: ModelRequirementStatus;
+ matchedModelName: string | null;
+ starterMatch: StarterCatalogEntry | null;
+}
+
+interface ResolutionDeps {
+ installedModels: readonly InstalledModelSummary[];
+ starterModels: readonly StarterCatalogEntry[];
+ activeInstallSources: ReadonlySet<string>;
+}
+
+const findInstalledForExact = (
+ identifier: WorkflowModelIdentifier,
+ installedModels: readonly InstalledModelSummary[]
+): InstalledModelSummary | null => {
+ const byKey = installedModels.find((model) => model.key === identifier.key);
+
+ if (byKey) {
+ return byKey;
+ }
+
+ if (identifier.hash) {
+ const byHash = installedModels.find((model) => model.hash === identifier.hash);
+
+ if (byHash) {
+ return byHash;
+ }
+ }
+
+ if (identifier.name && identifier.base && identifier.type) {
+ const byNameBaseType = installedModels.find(
+ (model) => model.name === identifier.name && model.base === identifier.base && model.type === identifier.type
+ );
+
+ if (byNameBaseType) {
+ return byNameBaseType;
+ }
+ }
+
+ return null;
+};
+
+const findInstalledForSlot = (
+ base: string | null,
+ modelType: string | null,
+ installedModels: readonly InstalledModelSummary[]
+): InstalledModelSummary | null =>
+ installedModels.find(
+ (model) => (base === null || model.base === base) && (modelType === null || model.type === modelType)
+ ) ?? null;
+
+const matchesStarterName = (starter: StarterCatalogEntry, name: string): boolean => {
+ const target = name.toLowerCase();
+
+ if (starter.name.toLowerCase() === target) {
+ return true;
+ }
+
+ return (starter.previous_names ?? []).some((previousName) => previousName.toLowerCase() === target);
+};
+
+const findStarterForExact = (
+ identifier: WorkflowModelIdentifier,
+ starterModels: readonly StarterCatalogEntry[]
+): StarterCatalogEntry | null => {
+ if (!identifier.name || !identifier.base || !identifier.type) {
+ return null;
+ }
+
+ return (
+ starterModels.find(
+ (starter) =>
+ matchesStarterName(starter, identifier.name as string) &&
+ starter.base === identifier.base &&
+ starter.type === identifier.type
+ ) ?? null
+ );
+};
+
+const findStarterForSlot = (
+ base: string | null,
+ modelType: string | null,
+ starterModels: readonly StarterCatalogEntry[]
+): StarterCatalogEntry | null =>
+ starterModels.find(
+ (starter) => (base === null || starter.base === base) && (modelType === null || starter.type === modelType)
+ ) ?? null;
+
+const isStarterActivelyInstalling = (
+ starter: StarterCatalogEntry,
+ activeInstallSources: ReadonlySet<string>
+): boolean =>
+ activeInstallSources.has(starter.source) ||
+ (starter.dependencies ?? []).some((dependency) => activeInstallSources.has(dependency.source));
+
+const resolveFromStarter = (
+ requirement: WorkflowModelRequirement,
+ starter: StarterCatalogEntry | null,
+ activeInstallSources: ReadonlySet<string>
+): ResolvedModelRequirement => {
+ if (!starter) {
+ return { matchedModelName: null, requirement, starterMatch: null, status: 'unresolvable' };
+ }
+
+ return {
+ matchedModelName: null,
+ requirement,
+ starterMatch: starter,
+ status: isStarterActivelyInstalling(starter, activeInstallSources) ? 'installing' : 'installable',
+ };
+};
+
+/**
+ * Resolves each requirement against injected installed/starter-catalog data.
+ * `exact` requirements match installed models by key, then hash, then
+ * name+base+type; `slot` requirements match by base (and type, when the
+ * slot names one). Unmatched requirements fall through to a starter-catalog
+ * lookup, which reports `installing` when its (or a dependency's) source is
+ * already being installed.
+ */
+export const resolveWorkflowModelRequirements = (
+ requirements: readonly WorkflowModelRequirement[],
+ deps: ResolutionDeps
+): ResolvedModelRequirement[] =>
+ requirements.map((requirement) => {
+ if (requirement.kind === 'exact') {
+ const installed = findInstalledForExact(requirement.identifier, deps.installedModels);
+
+ if (installed) {
+ return { matchedModelName: installed.name, requirement, starterMatch: null, status: 'installed' };
+ }
+
+ return resolveFromStarter(
+ requirement,
+ findStarterForExact(requirement.identifier, deps.starterModels),
+ deps.activeInstallSources
+ );
+ }
+
+ const installed = findInstalledForSlot(requirement.base, requirement.modelType, deps.installedModels);
+
+ if (installed) {
+ return { matchedModelName: installed.name, requirement, starterMatch: null, status: 'installed' };
+ }
+
+ return resolveFromStarter(
+ requirement,
+ findStarterForSlot(requirement.base, requirement.modelType, deps.starterModels),
+ deps.activeInstallSources
+ );
+ });
+
+// #endregion