Skip to content

AI, fully local on your computer.

7.2 KB
Raw Blame
import type { ModelInfo } from '@shared/types'
import { isModelInstalled, isModelOnDrive, isModelRunnableHere } from './modelAvailability'
import { foldCase } from '@shared/text-fold'

export type ModelTask = 'chat' | 'documents' | 'translation' | 'vision' | 'transcriber'
export type LibraryView = 'installed' | 'browse'

/** The task a model serves; null for a model for a newer HilbertRaum (#847), which serves none here. */
export function modelTask(model: ModelInfo): ModelTask | null {
  if (model.role === 'unknown') return null
  return model.role === 'embeddings' || model.role === 'reranker' ? 'documents' : model.role
}

/**
 * #313 — the view half of `ModelsScreen`'s `visibleModels` filter, extracted so the screen and
 * `availableFamilies` below read the SAME rule and can never disagree about which view a model
 * belongs to. "On this drive" lists a model whose state is known-usable or repairable
 * (`isModelOnDrive`); Browse imposes no view restriction at all. A model for a newer HilbertRaum
 * (#847) is never a library row: `newerAppRows` lists it apart.
 */
export function matchesLibraryView(model: ModelInfo, view: LibraryView): boolean {
  if (model.role === 'unknown') return false
  return view !== 'installed' || isModelOnDrive(model)
}

/**
 * #847 — the rows of the screen's trailing "Needs a newer HilbertRaum" section: the models for a newer
 * HilbertRaum (`role: 'unknown'`) the current view and filters yield. "On this drive" lists one whose
 * declared files are all present — `filesPresent`, the main process's existence check and the only presence
 * contract this view reads beyond `isModelOnDrive` (design-guidelines §15) — and Browse lists every one. They
 * serve no task and offer no family option, so a task or family filter hides them; search applies as to every
 * row.
 */
export function newerAppRows(
  models: ModelInfo[],
  opts: { view: LibraryView; task: ModelTask | 'all'; family: string; query: string }
): ModelInfo[] {
  if (opts.task !== 'all' || opts.family !== 'all') return []
  return models.filter(
    (m) =>
      m.role === 'unknown' &&
      (opts.view !== 'installed' || m.filesPresent === true) &&
      matchesModelSearch(m, opts.query)
  )
}

/**
 * #313 — the family options the `<select>` can coherently offer: the sorted set of families
 * among the rows the CURRENT view and task filters can yield, excluding the pinned active chat
 * model (the same exclusion `visibleModels` applies). Deliberately does NOT apply search or the
 * family filter itself — search narrows within a family, it does not decide which families are
 * offered, and applying the family filter here would make every family but the selected one
 * disappear. See `docs/design-guidelines.md` §15 "Search + task + family filters".
 */
export function availableFamilies(
  models: ModelInfo[],
  opts: { activeChat: ModelInfo | null; view: LibraryView; task: ModelTask | 'all' }
): string[] {
  const rows = models.filter(
    (m) =>
      m !== opts.activeChat &&
      matchesLibraryView(m, opts.view) &&
      (opts.task === 'all' || modelTask(m) === opts.task)
  )
  return [...new Set(rows.map((m) => m.family))].sort()
}

/** Only remove a recognized terminal quantization label. Keep size, generation,
 * instruction revision and QAT identity intact; unknown naming stays separate.
 * This is presentation grouping, never a new runtime/model identifier. */
export function modelVariantName(model: ModelInfo): string {
  return model.displayName.replace(/\s+\(?(?:UD-)?(?:I?Q\d[\w-]*|BF16|F16|F32)\)?$/i, '').trim()
}

export interface ModelVariantGroup {
  key: string
  name: string
  models: ModelInfo[]
}

/** Input is already ordered by availability/recommendation; retain that order in
 * both groups and their variants (the collapsed FACE is a presentation exception —
 * `variantGroupFace`). Never combine different roles or runtimes. */
export function groupModelVariants(models: ModelInfo[]): ModelVariantGroup[] {
  const groups = new Map<string, ModelVariantGroup>()
  for (const model of models) {
    const name = modelVariantName(model)
    const key = JSON.stringify([model.role, model.family, model.runtime, name])
    const group = groups.get(key)
    if (group) group.models.push(model)
    else groups.set(key, { key, name, models: [model] })
  }
  return [...groups.values()]
}

/**
 * The three ordering keys of `orderPickerModels`, as a comparable tuple. Members that tie on
 * all three are interchangeable to the sort — only their catalog order separates them.
 */
function priorityKeys(m: ModelInfo): [boolean, boolean, boolean] {
  return [isModelInstalled(m), m.recommended === true, isModelRunnableHere(m)]
}

/**
 * Can the user act on this variant right now — either it is already on the drive, or its
 * manifest still offers a download that has not been withdrawn (#196)? A manual/local entry with
 * no `download` block is NOT obtainable from inside the app, so it never wins the face.
 */
function isObtainable(m: ModelInfo): boolean {
  return isModelInstalled(m) || (m.download != null && m.download.withdrawn == null)
}

/**
 * F5 (#196) — which variant a COLLAPSED group shows. The catalog's six Qwen3.8 27B quants tie on
 * all three ordering keys on a 16 GB machine (none installed, none recommended, none runnable),
 * so stable sort left alphabetical catalog order in charge and the group fronted a variant whose
 * upstream file was withdrawn: the one card the user sees offered nothing to do.
 *
 * The rule is deliberately narrow. Only the LEADING COHORT is considered — the run of members
 * from the front whose `priorityKeys` equal the first member's — so obtainability can never lift
 * a variant across an installed / recommended / runnable boundary (an installed-but-withdrawn
 * weight keeps the face; a lower-priority downloadable sibling does not steal it). Within that
 * cohort the first obtainable member wins; if none is obtainable the original leader stays, so a
 * group of purely withdrawn or manual variants is unchanged.
 *
 * Presentation only: group membership, the global sort and `group.models` itself are untouched.
 * Expects a nonempty group (`groupModelVariants` never produces an empty one).
 */
export function variantGroupFace(group: ModelVariantGroup): ModelInfo {
  const first = group.models[0]
  const lead = priorityKeys(first)
  for (const m of group.models) {
    const keys = priorityKeys(m)
    if (keys[0] !== lead[0] || keys[1] !== lead[1] || keys[2] !== lead[2]) break
    if (isObtainable(m)) return m
  }
  return first
}

/**
 * Render order for a group: the face first, then every OTHER member exactly once in its original
 * relative order. Never mutates `group.models`. Expects a nonempty group, like `variantGroupFace`.
 */
export function variantGroupOrder(group: ModelVariantGroup): ModelInfo[] {
  const face = variantGroupFace(group)
  return [face, ...group.models.filter((m) => m !== face)]
}

/** Every word of `query` is a substring of the model's name, id or family, both sides folded with
 *  the shared `foldCase` (so a Turkish keyboard's "ı" or "İ" finds an "i"). */
export function matchesModelSearch(model: ModelInfo, query: string): boolean {
  const haystack = foldCase(`${model.displayName} ${model.id} ${model.family}`)
  return foldCase(query).trim().split(/\s+/).every((word) => haystack.includes(word))
}