mirror of
https://github.com/mudler/LocalAI.git
synced 2026-08-04 12:22:22 -04:00
* feat(ui): rename the Install Models nav entry to Discover "Install Models" named the action rather than the destination, and it was the only multi-word entry in a rail of one-word ones (Home, Chat, Studio, Talk, Build, Operate). A bare "Models" was the obvious fix but it collides with the installed-models view under Host, which is a different page for a different job. "Discover" keeps the rhythm and says what the page is for. The icon moves from a download arrow to a compass for the same reason: the page is browsed before it is installed from. Translated in all seven locales rather than left to fall back, so a locale switch does not leave the entry in English. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-5 [Claude Code] * feat(ui): replace the gallery table with a rail and a detail pane The eight-column table was not the real problem; the click-to-expand row underneath it was. Variants, files and a VRAM estimate never fitted inside a <tr>, so they were pushed into a drawer that could hold one model at a time, could not be linked to, and had no room to say anything useful. The gallery is now a rail to scan and a pane that answers. The pane has two states and no third: with nothing selected it is the discovery page, and with a model selected it is that model's detail. Selection lives in the URL, so a model is linkable and Back steps out of the detail instead of off the page. The rail groups by capability while browsing and flattens to results the moment a term is typed. That is a rule rather than a toggle: once someone has said what they are looking for, the buckets are between them and the answer, and making the user choose would be handing them our problem. The detail pane plots VRAM against context length with the host's own limit drawn across it. This is new information, not a restyle. A single number invites "so will it run?", and the honest answer is usually "yes, up to a 32k context", which is a shape rather than a number. The estimates were already fetched for every context size, so it costs no new request. Backends that take no context length say so instead of being given a meaningless chart, and a host with no GPU gets no chart at all rather than bars with nothing to compare against. The split-button variant menu goes with the actions column. The pane lists every build with its backend, quantization, size, fit and a details disclosure, each installable, which is what the dropdown was a cramped substitute for. Its tests move onto that list; the three contracts it alone carried (fetch-once caching, the loading state, an unfit build staying installable) are backfilled against the pane. RecommendedModels moves inside the pane, where it has the width to argue for a model instead of listing one, and keeps its own dismissal and collapse. Rail entries carry no description. Two lines is the budget and the second is better spent on whether the thing will run; the stripped-Markdown contract moves to the pane's lede, tooltip included. e2e: 123 passing across models-gallery, navigation, recommended-panel, model-artifact-operation, operations-strip and page-render-smoke. Inline styles in Models.jsx drop from 82 to 41. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-5 [Claude Code] * refactor(ui): extract the split view into shared components Discover shipped its rail, pane and detail header as private functions inside Models.jsx. Backends and Host have the same defect and want the same shape, so leaving them there guarantees three rails that drift. SplitView, EntityRail, DetailHeader and StatGrid now live under components/split/. EntityRail is deliberately data-driven: a surface maps its own entity onto { id, name, icon, meta, stripe, groupId } and keeps its vocabulary to itself, which is what stops the rail learning about models, backends and loaded state all at once. The CSS moves with it. What was .discover__rail is .entity-rail, .discover__ pane is .split-view__pane and so on, because a class named after one page is a lie on the next two. Only what is genuinely Discover's stays behind the old prefix: the shelves, the hero and the VRAM-by-context chart. Two additions the shared rail needs and Discover did not: a state stripe, for surfaces read by condition before they are read by name, and an empty label. Discover passes neither. No behaviour change. e2e 100 passing across models-gallery, navigation and models-recommended-panel. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-5 [Claude Code] * feat(ui): put the backend gallery on the split view Same defect as the model gallery, so the same shape: a seven-column table over a click-to-expand row that was the only place the repository, licence, tags and links could go. The rail groups backends by the use case they serve, sharing Discover's taxonomy on purpose: a backend is the runtime a use case needs, so "vision" ought to mean the same thing one level down. It flattens on a query for the same reason it does on Discover. The zero state is the one real departure. A backend's fitness is not free memory, it is the accelerator and platform it was built for, so the pane leads with what this host is, then what is not installed yet, then whether anything installed has gone stale. The table listed 37 runtimes and left "which of these can even run here" entirely to the reader. Distribution moves into the pane, which is the one thing a row could never carry: which nodes hold a copy and which do not, with the install-on-more control next to it rather than squeezed against a chip. The distributed and target-node action logic is unchanged, including the guard that keeps a hardware-specific build off the fan-out path. The split-button popover loses its per-row anchoring because there are no rows; one pane, one anchor. Selection lives in ?backend=, preserving the ?target= scope rather than clobbering it. e2e: 139 passing across models-gallery, navigation, backends-management, models-recommended-panel, nodes-per-node-backend-actions, page-render-smoke, operations-strip and model-artifact-operation. The backends spec gains six split-view tests; its three description-cell tests move onto the pane lede. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-5 [Claude Code] * feat(ui): put the Host inventory on the split view The last of the three surfaces, and the one that is not a catalog. Both tabs had the same click-to-expand row, so the shell transfers; what does not transfer is the zero state, because there is nothing to discover in your own inventory. With nothing selected the pane reports what is happening: how many models are loaded, what failed, what has an update, and which models are holding VRAM right now. Every number was already on the page. None of them had been assembled into one statement, so "what is going on" was a question the tabs could not answer however long you looked at them. The rail buckets by state rather than capability - Running, Idle, Disabled for models; Update available, Installed for backends - which is the opposite of the galleries and deliberately so: nobody opens Host wondering which of their models does vision. Entries carry a state stripe for the same reason. Load and Stop are promoted out of the kebab, because that is what an operator came for; the rest stays behind the menu rather than diluting it. Adopted, pinned and alias badges follow the model into the pane: they are facts about the thing, not about its state, and the rail line is spent on state. Deliberately NOT done: folding the two tabs into one rail, as the mock had it. It costs five URL parameters, the manage-tab localStorage key and the stat-card shortcuts, all of which are live deep-links today. The tabs stay as the group selector; merging them is a follow-up with its own migration. e2e: full suite 355 passing. New host-split-view spec; alias-template, manage-logs-link, manage-action-menu-position and model-editor-back-nav move off `.table` and the row kebab onto the rail and the pane. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-5 [Claude Code] * polish(ui): accessibility and consistency pass over the three split views Findings from a pass over what the previous four commits actually shipped, rather than what they were supposed to. The rail was not a listbox. ARIA lets a listbox contain options and groups, and nothing else, but each group's collapse control is a button that has to sit inside the scroller with the entries it folds. It is now a labelled group of buttons, which is the honest description; selection is announced with aria-current and the arrow keys are unaffected. Every entry was its own tab stop, so tabbing past a forty-entry rail to reach the pane took forty keystrokes. Roving tabindex makes the rail one stop, and arrowing now moves focus with the selection instead of leaving it behind on an entry Tab can no longer reach. The rail rounds its corners with overflow:hidden, which was clipping the focus ring off the first and last entries entirely. Inset outlines fix it. A 30px row is fine under a mouse and too small under a thumb, so coarse pointers get a 44px target without costing density on a desktop. One slot said three different things: "9 models loaded" on Discover, "12 loaded" on Backends, "3 of 9" on Host. All three lists are a page of a larger set, so all three now say so the same way. Also removed: an emptyLabel prop on EntityRail that nothing passed, its dead CSS rule, and MODELS_COLSPAN and ResourceRowDesc, which died with the tables. e2e: full suite 355 passing. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-5 [Claude Code] * fix(ui): correct three defects only a real gallery exposed Running the branch against a live instance with 1,595 models and 1,017 backends, rather than against mocked fixtures, surfaced three things the e2e suite could not. Grouping did nothing. The rails matched on the use-case keys the filter chips send (`chat`, `tts`, `transcript`), but those are a server-side vocabulary the handler maps onto entries. What entries actually carry is free-form and inconsistent: models come back tagged `llm`, `gguf`, `vision`, `coding`, and backends `LLM`, `text-to-text`, `audio-transcription`. Nothing matched, so every model landed in "Everything else" and the feature was decorative. Grouping now lives in utils/entityGroups.js, shared by both galleries, matching case-insensitively against the vocabulary the API really uses, with the entry's backend as a fallback signal - a backend named `whisper` is a speech backend whatever its tags say. Order is specific before general and that is load-bearing: a vision model is tagged `llm` too, so testing text first would swallow it. The zero state claimed GPU memory on a machine with no GPU. The resources endpoint reports system RAM in the same field when gpu_count is 0, so the hero read "84.4 GB of GPU memory" next to the recommendations panel correctly saying "No GPU detected". The number was never wrong, only its label; it now says system memory unless a GPU is actually present. The page title still said "Install Models" under a nav entry saying Discover. Also: the keyboard test named the model it expected to arrive at, which made it a hostage of the grouping table and broke the moment the buckets were fixed. It now asserts that the selection moves and returns. e2e: full suite 355 passing. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-5 [Claude Code] * fix(ui): the filters and the rail were fighting over the same job Four things you find odd on Discover, and they turn out to be one mistake seen from four sides. The rail grouped the current page. The listing is paginated at nine rows, so those bucket headers described nine entries out of 1,595, and turning a page reshuffled the sections under the reader. The structure was never stable because it was computed over the wrong set. The chips were redundant for the same reason, seen from the other side. They send tag= and filter all 1,595 server-side. The rail grouped nine of them client-side by the same axis. Two controls for one job, and the weaker one was the one this branch added, so it goes. Grouping stays only on Host, where the list is complete, local, and bucketed by state rather than capability. The search bar felt odd because it sat in a full-width band while the thing it narrowed was a 290px rail below and to the left. The whole band now lives in the rail column: search, backend, use cases, refinements, then the list it narrows. One column to say what you want, one to show what you got. Nineteen chips do not fit at that width, so they fold into a disclosure that states the selection. A disclosure and not a popover, deliberately: picking use cases is multi-select and interleaves with the backend select and the toggles below, and a popover dismisses itself the moment you touch either. The header held two counts and two buttons at arm's length from all of it. The counts were the third statement of the same number on one screen, after the rail's "9 of 1,247" and the pane's own headline, so they go. The buttons move into the pane's zero state, which is the surface that answers "what do I do here". Also: the two first-run empty states wore .loading-center, which is display:flex in the default row direction because it exists to centre one spinner. With four children that put the icon, the heading, the sentence and the buttons on a single line with no gap. They are now a proper full-height empty state. e2e: full suite 353 passing. Grouping tests are replaced by ones asserting the rail stays flat; chip tests open the disclosure first; two filter-layout tests that asserted the old three-band arrangement now assert the column. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-5 [Claude Code] * polish(ui): make Discover a full-height view, group the chips, name the refinements Four things, all of them the same complaint: the page read as a document with controls scattered on it rather than as one view. The header is fused. A title block with its own padding, a subtitle and two counts made the split view look like an attachment to a document that happened to sit below it. It is now a slim bar carrying the title, the count and the two page-level actions, and the split fills the rest of the window. Rail and pane scroll independently, so the filters and the pane's headline stay put while a long list moves under them. The chips group. Nineteen in a flat row is a lot to scan even behind a disclosure, and they already belong to the four families the rest of the UI speaks, so they are bucketed by those. "All" sits on its own above them without a heading, because it is a reset rather than a use case. The refinements stop looking dumped. When the band became a column they were three controls left where they landed; they now read as a named section with one control per row. The zero state suggests again. It had decayed into a "Browsing / 9 of 1,247 / select a model" line that restated the count for the third time on one screen. It now offers the four use cases as tiles that set the filter, which is the shelf idea from the mock without inventing curation or paying for a second fetch. Two bugs found by looking at it rather than at the tests: the disclosure was clamped to 190px, which cut it off partway through its third section so two of the five never appeared at all; and the creation actions rendered twice, once in the new bar and once in the pane hero a few pixels away. e2e: full suite 353 passing. The chip-row test now holds its contract across the per-family rows rather than a single one, and additionally asserts every family is present and non-empty. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-5 [Claude Code] * fix(ui): pin the split view's height so a long detail scrolls the pane Selecting a model with a long description grew the whole page and dragged the rail down with it, which is the opposite of what "full height" was supposed to buy. The flex chain was right and the ceiling was missing. .app-layout and .main-content are min-height:100dvh, which is a floor: flex distributes free space but nothing caps growth, so a pane taller than the viewport expanded the column, the document scrolled, and the rail stretched to match. height:100% on the pane then resolved against an auto-height parent and did nothing. The chat route already solves this by pinning .main-content to 100dvh. The same treatment now applies to any route containing a .page--app, selected with :has() so the shell does not have to learn which pages happen to be split views. Below the stacking breakpoint the pin is lifted, because two stacked halves in two short scrollers is worse than a page that scrolls. Measured on a live instance: document height stays at the viewport across selection (950px either side) and the pane overflows internally instead. Adds discover-height.spec.js, which asserts the page height and the rail height are unchanged by selection and that the pane is the thing that scrolls. The existing specs could not have caught this: they mock short descriptions, and the bug only appears when the pane has more content than the viewport holds. e2e: full suite 355 passing. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-5 [Claude Code] * feat(ui): give Backends and Host the full-height view, and fix the Update button Backends now matches Discover: the header fuses into a slim bar carrying the title, the count and the page-level actions, the filters move into the rail column where they narrow the rail and nothing else, and the split fills the window. Its seven chips fit at rail width, so unlike Discover's nineteen they need no disclosure. Host gets the bar and the height; its resource monitor, summary cards and tabs stay above the split, because those are read once while the rail and the pane are worked in. Two things the height change surfaced. The console layout is a flex row with align-items:flex-start, so its body sizes to content. Right for the pages it was built for, wrong for a split view, which needs a ceiling to scroll inside: without it the Backends rail ran past the viewport and over the footer. Pinned with :has() so only split-view routes are affected. The filters vanished when nothing matched. Both galleries swapped the whole shell for an empty state, which took the search box and the chips with it, so the page said "try adjusting your search or filters" while offering neither. The shell now stays and the empty state moves into the pane. Also fixes the Update control on Host, which had no className at all and rendered as bare text, next to a status span that had picked up btn classes and two copies of `fas` and so rendered as a button you cannot press. They have swapped appearances back. e2e: full suite 355 passing. The render-smoke selector learns .view-bar__title, since the pages it checks no longer all use PageHeader. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-5 [Claude Code] * fix(ui): keep the view mounted while searching, and bring rail grouping back Searching replaced the whole view with a loader. The search box lives in the rail column, so every debounced refetch unmounted the field being typed into and dropped its focus with it. The list, the filters and the pane went too. The shell now stays and the rail says it is busy: a sweep bar under its header and the stale list dimmed, so the eye knows the answer is being replaced without losing its place. A cold start still gets the skeleton, because there is nothing to keep. The condition for that is "nothing has loaded yet", not "the list is empty". Those differ exactly when someone is editing a query that matched nothing, and getting it wrong there would unmount the view on the keystroke after a no-results search - the worst possible moment. Grouping comes back on both galleries. It was removed because nine rows could not fill five buckets, so a page turn rebuilt the rail's whole structure. That was a symptom of the page size rather than of grouping: the rail now asks for 30 rows instead of 9 (Backends 60 instead of 21), which is enough for the sections to read as structure and turns five times fewer pages. The order of the sections is fixed, so what changes between pages is membership, not arrangement. Grouped while browsing, flat while searching, as before: once a term is typed the buckets stand between the reader and the answer. Also gives GalleryLoader a class and a testid instead of six inline style declarations on a bare div, which is why nothing could select it. e2e: full suite 359 passing, including a new spec asserting the search box keeps its focus and its value across a refetch, and that a cold start still shows the skeleton. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-5 [Claude Code] * perf(gallery): stop invalidating the VRAM estimate caches on every request Searching or turning a page felt slow. It was not the search and not the listing: /api/models answers in 3-9ms. It was the VRAM estimate, which the gallery asks for once per row, and which took ~2.3s every single time however often the same model was asked about. pkg/vram already caches what makes that expensive - the remote content-length probes, the GGUF metadata reads and the HF repo sizes. Those caches key on a gallery generation counter, and AvailableGalleryModelsCached triggered a background refresh on every call, with each refresh bumping the counter. One page view is one listing request plus thirty estimate requests, each of which re-read the gallery and started another refresh, so the generation moved constantly and every cache entry was stale before it could ever be read. The caches were dead in production. Three changes, each doing one thing: A refresh interval. The cached list is still served immediately; this only decides how often re-fetching from upstream is worth starting. Five minutes, as a package variable so tests can drive it without waiting. A generation bump only when the gallery actually changed. An unchanged gallery re-fetched on schedule must not throw away work that is still valid, which is the difference between an estimate costing nothing and costing a network round trip. A separate "loaded" flag. The cache engaged on `cached != nil`, so a gallery that legitimately holds nothing read as never-loaded and took the blocking path on every call, bumping the generation each time. Found by the test for the interval, which could not pass while this was true. Measured against a live instance with 1,595 models: one estimate, repeated 2.3s -> 2ms a page of 30, in parallel 10s -> 0.04s A first, genuinely unseen model still costs its remote probe. That is inherent; what changed is that it is now paid once per model per gallery version rather than once per request. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-5 [Claude Code] * perf(gallery): warm VRAM estimates at startup, and stop the UI waiting on them Two halves of the same complaint: the gallery stalls on VRAM estimation. Server side, the estimates are now warmed in the background at startup. Estimating an entry nobody has asked about costs a remote probe of its weight files, and the gallery needs one per row, so the first visitor was paying for the whole page. The warm-up walks the gallery in the order the UI lists it, so the first page is ready before anyone reaches it. It is bounded and it never blocks: 300 entries at 4 at a time by default, on its own goroutine, stopping with the server's context. Warming the whole gallery would be thousands of probes on every boot, which is rude to the upstream and slow to finish; warming nothing leaves the first page paying two seconds a row. Anything past the limit still warms itself on first view. LOCALAI_VRAM_WARM_LIMIT=0 turns it off for an air-gapped host, LOCALAI_VRAM_WARM_CONCURRENCY=1 slows it for a metered link. Client side, the page no longer waits on estimates it does not need yet. It fired one request per row at once; a browser allows about six connections per host, so thirty estimates took every slot and the request behind a click - the variant list, an install - queued behind work nobody asked for. That is the freeze: the list was already usable, and the UI was busy fetching sizes. Four at a time leaves room for the interactive request to overtake, and a row whose estimate is still in flight says "sizing…" rather than leaving a blank where a number will appear. buildEstimateInput moves to core/gallery as EstimateInput, since the handler and the warmer both need it. Measured against 1,595 models, from a cold boot: page 1, 30 estimates in parallel 10s -> 0.04s full warm-up (299 of 300 entries) 3m, in the background Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-5 [Claude Code] * chore: untrack data/.local_user_id and ignore the runtime data dir `local-ai run` writes its instance state under ./data when started from the repo root, which is exactly what a contributor testing a build does. The identity file ended up committed on this branch by a `git add -A` while verifying the gallery changes against a live instance. Anchored, so it matches the runtime directory at the repo root and not a `data` directory nested inside some package. Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Assisted-by: Claude:claude-opus-5 [Claude Code] --------- Signed-off-by: Ettore Di Giacinto <mudler@localai.io> Co-authored-by: Ettore Di Giacinto <mudler@localai.io>
640 lines
20 KiB
Go
640 lines
20 KiB
Go
package gallery
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"path/filepath"
|
|
"slices"
|
|
"strings"
|
|
"sync"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/lithammer/fuzzysearch/fuzzy"
|
|
"github.com/mudler/LocalAI/core/config"
|
|
"github.com/mudler/LocalAI/pkg/downloader"
|
|
"github.com/mudler/LocalAI/pkg/system"
|
|
"github.com/mudler/LocalAI/pkg/utils"
|
|
"github.com/mudler/LocalAI/pkg/xsync"
|
|
"github.com/mudler/xlog"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
// validateGalleryConfigURL guards the gallery config fetch against SSRF. A
|
|
// gallery config URL can be attacker-controlled (e.g. POST /models/apply with
|
|
// an empty id fetches it directly), so a plain http(s) URL must not be allowed
|
|
// to reach private, loopback, link-local or cloud-metadata addresses. Other
|
|
// schemes (huggingface://, github:, oci://, ollama://, file://) resolve to
|
|
// fixed public services or local files and are not a network-SSRF vector, so
|
|
// they are left untouched.
|
|
// See https://github.com/mudler/LocalAI/issues/10665
|
|
func validateGalleryConfigURL(rawURL string) error {
|
|
lower := strings.ToLower(strings.TrimSpace(rawURL))
|
|
if strings.HasPrefix(lower, "http://") || strings.HasPrefix(lower, "https://") {
|
|
return utils.ValidateExternalURL(rawURL)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func GetGalleryConfigFromURL[T any](url string, basePath string) (T, error) {
|
|
var config T
|
|
if err := validateGalleryConfigURL(url); err != nil {
|
|
xlog.Error("refusing to fetch gallery config", "error", err, "url", url)
|
|
return config, err
|
|
}
|
|
uri := downloader.URI(url)
|
|
err := uri.ReadWithCallback(basePath, func(url string, d []byte) error {
|
|
return yaml.Unmarshal(d, &config)
|
|
})
|
|
if err != nil {
|
|
xlog.Error("failed to get gallery config for url", "error", err, "url", url)
|
|
return config, err
|
|
}
|
|
return config, nil
|
|
}
|
|
|
|
func GetGalleryConfigFromURLWithContext[T any](ctx context.Context, url string, basePath string) (T, error) {
|
|
var config T
|
|
if err := validateGalleryConfigURL(url); err != nil {
|
|
xlog.Error("refusing to fetch gallery config", "error", err, "url", url)
|
|
return config, err
|
|
}
|
|
uri := downloader.URI(url)
|
|
err := uri.ReadWithAuthorizationAndCallback(ctx, basePath, "", func(url string, d []byte) error {
|
|
return yaml.Unmarshal(d, &config)
|
|
})
|
|
if err != nil {
|
|
xlog.Error("failed to get gallery config for url", "error", err, "url", url)
|
|
return config, err
|
|
}
|
|
return config, nil
|
|
}
|
|
|
|
func ReadConfigFile[T any](filePath string) (*T, error) {
|
|
// Read the YAML file
|
|
yamlFile, err := os.ReadFile(filePath)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to read YAML file: %v", err)
|
|
}
|
|
|
|
// Unmarshal YAML data into a Config struct
|
|
var config T
|
|
err = yaml.Unmarshal(yamlFile, &config)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to unmarshal YAML: %v", err)
|
|
}
|
|
|
|
return &config, nil
|
|
}
|
|
|
|
type GalleryElement interface {
|
|
SetGallery(gallery config.Gallery)
|
|
SetInstalled(installed bool)
|
|
GetName() string
|
|
GetDescription() string
|
|
GetTags() []string
|
|
GetInstalled() bool
|
|
GetLicense() string
|
|
GetGallery() config.Gallery
|
|
}
|
|
|
|
type GalleryElements[T GalleryElement] []T
|
|
|
|
func (gm GalleryElements[T]) Search(term string) GalleryElements[T] {
|
|
var filteredModels GalleryElements[T]
|
|
term = strings.ToLower(term)
|
|
for _, m := range gm {
|
|
if fuzzy.Match(term, strings.ToLower(m.GetName())) ||
|
|
fuzzy.Match(term, strings.ToLower(m.GetGallery().Name)) ||
|
|
strings.Contains(strings.ToLower(m.GetName()), term) ||
|
|
strings.Contains(strings.ToLower(m.GetDescription()), term) ||
|
|
strings.Contains(strings.ToLower(m.GetGallery().Name), term) ||
|
|
strings.Contains(strings.ToLower(strings.Join(m.GetTags(), ",")), term) {
|
|
filteredModels = append(filteredModels, m)
|
|
}
|
|
}
|
|
|
|
return filteredModels
|
|
}
|
|
|
|
// FilterGalleryModelsByUsecase returns models whose known_usecases include all
|
|
// the bits set in usecase. For example, passing FLAG_CHAT matches any model
|
|
// with the chat usecase; passing FLAG_CHAT|FLAG_VISION matches only models
|
|
// that have both.
|
|
func FilterGalleryModelsByUsecase(models GalleryElements[*GalleryModel], usecase config.ModelConfigUsecase) GalleryElements[*GalleryModel] {
|
|
var filtered GalleryElements[*GalleryModel]
|
|
for _, m := range models {
|
|
u := m.GetKnownUsecases()
|
|
if u != nil && (*u&usecase) == usecase {
|
|
filtered = append(filtered, m)
|
|
}
|
|
}
|
|
return filtered
|
|
}
|
|
|
|
// FilterGalleryModelsByMultimodal returns models whose known_usecases span two
|
|
// or more orthogonal modality groups (e.g. chat+vision, tts+transcript).
|
|
func FilterGalleryModelsByMultimodal(models GalleryElements[*GalleryModel]) GalleryElements[*GalleryModel] {
|
|
var filtered GalleryElements[*GalleryModel]
|
|
for _, m := range models {
|
|
u := m.GetKnownUsecases()
|
|
if u != nil && config.IsMultimodal(*u) {
|
|
filtered = append(filtered, m)
|
|
}
|
|
}
|
|
return filtered
|
|
}
|
|
|
|
func (gm GalleryElements[T]) FilterByTag(tag string) GalleryElements[T] {
|
|
var filtered GalleryElements[T]
|
|
for _, m := range gm {
|
|
for _, t := range m.GetTags() {
|
|
if strings.EqualFold(t, tag) {
|
|
filtered = append(filtered, m)
|
|
break
|
|
}
|
|
}
|
|
}
|
|
return filtered
|
|
}
|
|
|
|
func (gm GalleryElements[T]) SortByName(sortOrder string) GalleryElements[T] {
|
|
slices.SortFunc(gm, func(a, b T) int {
|
|
r := strings.Compare(strings.ToLower(a.GetName()), strings.ToLower(b.GetName()))
|
|
if sortOrder == "desc" {
|
|
return -r
|
|
}
|
|
return r
|
|
})
|
|
return gm
|
|
}
|
|
|
|
func (gm GalleryElements[T]) SortByRepository(sortOrder string) GalleryElements[T] {
|
|
slices.SortFunc(gm, func(a, b T) int {
|
|
r := strings.Compare(strings.ToLower(a.GetGallery().Name), strings.ToLower(b.GetGallery().Name))
|
|
if sortOrder == "desc" {
|
|
return -r
|
|
}
|
|
return r
|
|
})
|
|
return gm
|
|
}
|
|
|
|
func (gm GalleryElements[T]) SortByLicense(sortOrder string) GalleryElements[T] {
|
|
slices.SortFunc(gm, func(a, b T) int {
|
|
licenseA := a.GetLicense()
|
|
licenseB := b.GetLicense()
|
|
var r int
|
|
if licenseA == "" && licenseB != "" {
|
|
r = 1
|
|
} else if licenseA != "" && licenseB == "" {
|
|
r = -1
|
|
} else {
|
|
r = strings.Compare(strings.ToLower(licenseA), strings.ToLower(licenseB))
|
|
}
|
|
if sortOrder == "desc" {
|
|
return -r
|
|
}
|
|
return r
|
|
})
|
|
return gm
|
|
}
|
|
|
|
func (gm GalleryElements[T]) SortByInstalled(sortOrder string) GalleryElements[T] {
|
|
slices.SortFunc(gm, func(a, b T) int {
|
|
var r int
|
|
// Sort by installed status: installed items first (true > false)
|
|
if a.GetInstalled() != b.GetInstalled() {
|
|
if a.GetInstalled() {
|
|
r = -1
|
|
} else {
|
|
r = 1
|
|
}
|
|
} else {
|
|
r = strings.Compare(strings.ToLower(a.GetName()), strings.ToLower(b.GetName()))
|
|
}
|
|
if sortOrder == "desc" {
|
|
return -r
|
|
}
|
|
return r
|
|
})
|
|
return gm
|
|
}
|
|
|
|
func (gm GalleryElements[T]) FindByName(name string) T {
|
|
for _, m := range gm {
|
|
if strings.EqualFold(m.GetName(), name) {
|
|
return m
|
|
}
|
|
}
|
|
var zero T
|
|
return zero
|
|
}
|
|
|
|
func (gm GalleryElements[T]) Paginate(pageNum int, itemsNum int) GalleryElements[T] {
|
|
start := (pageNum - 1) * itemsNum
|
|
end := start + itemsNum
|
|
if start > len(gm) {
|
|
start = len(gm)
|
|
}
|
|
if end > len(gm) {
|
|
end = len(gm)
|
|
}
|
|
return gm[start:end]
|
|
}
|
|
|
|
func FindGalleryElement[T GalleryElement](models []T, name string) T {
|
|
var model T
|
|
name = strings.ReplaceAll(name, string(os.PathSeparator), "__")
|
|
|
|
if !strings.Contains(name, "@") {
|
|
for _, m := range models {
|
|
if strings.EqualFold(strings.ToLower(m.GetName()), strings.ToLower(name)) {
|
|
model = m
|
|
break
|
|
}
|
|
}
|
|
|
|
} else {
|
|
for _, m := range models {
|
|
if strings.EqualFold(strings.ToLower(name), strings.ToLower(fmt.Sprintf("%s@%s", m.GetGallery().Name, m.GetName()))) {
|
|
model = m
|
|
break
|
|
}
|
|
}
|
|
}
|
|
|
|
return model
|
|
}
|
|
|
|
// List available models
|
|
// Models galleries are a list of yaml files that are hosted on a remote server (for example github).
|
|
// Each yaml file contains a list of models that can be downloaded and optionally overrides to define a new model setting.
|
|
func AvailableGalleryModels(galleries []config.Gallery, systemState *system.SystemState) (GalleryElements[*GalleryModel], error) {
|
|
var models []*GalleryModel
|
|
|
|
// Get models from galleries
|
|
for _, gallery := range galleries {
|
|
galleryModels, err := getGalleryElements(gallery, systemState.Model.ModelsPath, func(model *GalleryModel) bool {
|
|
if _, err := os.Stat(filepath.Join(systemState.Model.ModelsPath, fmt.Sprintf("%s.yaml", model.GetName()))); err == nil {
|
|
return true
|
|
}
|
|
return false
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Resolve model URLs locally (for local galleries) and collect unique
|
|
// URLs that need fetching for backend resolution.
|
|
uniqueURLs := map[string]struct{}{}
|
|
for _, m := range galleryModels {
|
|
if m.URL != "" {
|
|
m.URL = resolveModelURLLocally(m.URL, gallery.URL)
|
|
}
|
|
if m.Backend == "" && m.URL != "" {
|
|
uniqueURLs[m.URL] = struct{}{}
|
|
}
|
|
}
|
|
|
|
// Pre-warm cache with parallel fetches to avoid sequential HTTP
|
|
// requests on cold start (~50 unique gallery config files).
|
|
if len(uniqueURLs) > 0 {
|
|
urls := make([]string, 0, len(uniqueURLs))
|
|
for u := range uniqueURLs {
|
|
urls = append(urls, u)
|
|
}
|
|
prefetchModelConfigs(urls, systemState.Model.ModelsPath)
|
|
}
|
|
|
|
// Resolve backends from warm cache.
|
|
for _, m := range galleryModels {
|
|
if m.Backend == "" {
|
|
m.Backend = resolveBackend(m, systemState.Model.ModelsPath)
|
|
}
|
|
}
|
|
|
|
models = append(models, galleryModels...)
|
|
}
|
|
|
|
return models, nil
|
|
}
|
|
|
|
var (
|
|
availableModelsMu sync.RWMutex
|
|
availableModelsCache GalleryElements[*GalleryModel]
|
|
// Whether a load has happened, tracked apart from the slice itself. A
|
|
// gallery that legitimately holds nothing caches as an empty (often nil)
|
|
// slice, and testing the slice for nil read that as "never loaded": every
|
|
// call then took the blocking path and bumped the generation, which is the
|
|
// same cache-defeating loop the refresh interval exists to stop.
|
|
availableModelsLoaded bool
|
|
refreshing atomic.Bool
|
|
galleryGeneration atomic.Uint64
|
|
lastRefreshUnixNano atomic.Int64
|
|
)
|
|
|
|
// How often the cached model list may be refreshed from upstream.
|
|
//
|
|
// This is a floor on refresh frequency, not a TTL: the cache is served
|
|
// regardless, and this only decides how often a background re-fetch is worth
|
|
// starting. It matters far more than it looks, because a refresh bumps
|
|
// galleryGeneration, and that invalidates every VRAM estimate cache in
|
|
// pkg/vram. Refreshing on every call therefore kept those caches permanently
|
|
// cold: the gallery listing is one request but the UI asks for one VRAM
|
|
// estimate per row, so a single page view triggered dozens of refreshes and
|
|
// every estimate paid full price for a remote probe it had already made.
|
|
//
|
|
// A package variable rather than a constant so tests can drive refreshes
|
|
// without waiting.
|
|
var GalleryRefreshInterval = 5 * time.Minute
|
|
|
|
// GalleryGeneration returns a counter that increments each time the gallery
|
|
// model list is refreshed from upstream. VRAM estimation caches use this to
|
|
// invalidate entries when the gallery data changes.
|
|
func GalleryGeneration() uint64 { return galleryGeneration.Load() }
|
|
|
|
// ResetGalleryModelCache drops the cached model list, once any background
|
|
// refresh already in flight has finished writing to it.
|
|
//
|
|
// It exists for tests. The cache is a package global keyed by nothing, which is
|
|
// right for a process serving one gallery configuration and wrong for a suite
|
|
// where each spec stands up its own: a refresh one spec triggered can land in
|
|
// the middle of the next and answer it with the previous spec's entries, so
|
|
// whichever assertion happens to straddle it fails at random.
|
|
//
|
|
// Waiting for the in-flight refresh rather than only clearing is the point. The
|
|
// refresh publishes its result after this call would otherwise have returned,
|
|
// so clearing without waiting just narrows the window.
|
|
func ResetGalleryModelCache() {
|
|
for refreshing.Load() {
|
|
time.Sleep(time.Millisecond)
|
|
}
|
|
availableModelsMu.Lock()
|
|
availableModelsCache = nil
|
|
availableModelsLoaded = false
|
|
availableModelsMu.Unlock()
|
|
// Also clear the refresh stamp, or a suite that reset the cache would find
|
|
// the next refresh throttled by the previous spec's clock.
|
|
lastRefreshUnixNano.Store(0)
|
|
}
|
|
|
|
// AvailableGalleryModelsCached returns gallery models from an in-memory cache.
|
|
// Local-only fields (installed status) are refreshed on every call. A background
|
|
// goroutine is triggered to re-fetch the full model list (including network
|
|
// calls) so subsequent requests pick up changes without blocking the caller.
|
|
// The first call with an empty cache blocks until the initial load completes.
|
|
func AvailableGalleryModelsCached(galleries []config.Gallery, systemState *system.SystemState) (GalleryElements[*GalleryModel], error) {
|
|
availableModelsMu.RLock()
|
|
cached := availableModelsCache
|
|
loaded := availableModelsLoaded
|
|
availableModelsMu.RUnlock()
|
|
|
|
if loaded {
|
|
// Refresh installed status under write lock to avoid races with
|
|
// concurrent readers and the background refresh goroutine.
|
|
availableModelsMu.Lock()
|
|
for _, m := range cached {
|
|
_, err := os.Stat(filepath.Join(systemState.Model.ModelsPath, fmt.Sprintf("%s.yaml", m.GetName())))
|
|
m.SetInstalled(err == nil)
|
|
}
|
|
availableModelsMu.Unlock()
|
|
// Trigger a background refresh if one is not already running.
|
|
triggerGalleryRefresh(galleries, systemState)
|
|
return cached, nil
|
|
}
|
|
|
|
// No cache yet — must do a blocking load.
|
|
models, err := AvailableGalleryModels(galleries, systemState)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
availableModelsMu.Lock()
|
|
availableModelsCache = models
|
|
availableModelsLoaded = true
|
|
galleryGeneration.Add(1)
|
|
availableModelsMu.Unlock()
|
|
lastRefreshUnixNano.Store(time.Now().UnixNano())
|
|
|
|
return models, nil
|
|
}
|
|
|
|
// triggerGalleryRefresh starts a background goroutine that refreshes the
|
|
// gallery model cache. Only one refresh runs at a time; concurrent calls
|
|
// are no-ops.
|
|
func triggerGalleryRefresh(galleries []config.Gallery, systemState *system.SystemState) {
|
|
if GalleryRefreshInterval > 0 {
|
|
last := lastRefreshUnixNano.Load()
|
|
if last != 0 && time.Since(time.Unix(0, last)) < GalleryRefreshInterval {
|
|
return
|
|
}
|
|
}
|
|
if !refreshing.CompareAndSwap(false, true) {
|
|
return
|
|
}
|
|
// Stamped before the fetch rather than after, so a slow upstream cannot
|
|
// let a queue of callers each start their own refresh behind this one.
|
|
lastRefreshUnixNano.Store(time.Now().UnixNano())
|
|
go func() {
|
|
defer refreshing.Store(false)
|
|
models, err := AvailableGalleryModels(galleries, systemState)
|
|
if err != nil {
|
|
xlog.Error("background gallery refresh failed", "error", err)
|
|
return
|
|
}
|
|
availableModelsMu.Lock()
|
|
changed := !sameModelSet(availableModelsCache, models)
|
|
availableModelsCache = models
|
|
availableModelsLoaded = true
|
|
// Only a real change invalidates the VRAM caches. An unchanged gallery
|
|
// re-fetched on schedule must not throw away work that is still valid,
|
|
// which is the difference between an estimate costing nothing and
|
|
// costing a network round trip.
|
|
if changed {
|
|
galleryGeneration.Add(1)
|
|
}
|
|
availableModelsMu.Unlock()
|
|
}()
|
|
}
|
|
|
|
// sameModelSet reports whether two model lists describe the same gallery, for
|
|
// the purpose of deciding whether derived caches are still valid. Names and
|
|
// order are enough: a change to an entry's files or size arrives with a new
|
|
// gallery index, and comparing every field on every entry would cost more than
|
|
// the caches save.
|
|
func sameModelSet(a, b GalleryElements[*GalleryModel]) bool {
|
|
if len(a) != len(b) {
|
|
return false
|
|
}
|
|
for i := range a {
|
|
if a[i].GetName() != b[i].GetName() {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|
|
|
|
// List available backends
|
|
func AvailableBackends(galleries []config.Gallery, systemState *system.SystemState) (GalleryElements[*GalleryBackend], error) {
|
|
return availableBackendsWithFilter(galleries, systemState, func(backend *GalleryBackend) bool {
|
|
return backend.IsCompatibleWith(systemState)
|
|
})
|
|
}
|
|
|
|
// AvailableBackendsUnfiltered returns all available backends without filtering by system capability.
|
|
func AvailableBackendsUnfiltered(galleries []config.Gallery, systemState *system.SystemState) (GalleryElements[*GalleryBackend], error) {
|
|
return availableBackendsWithFilter(galleries, systemState, nil)
|
|
}
|
|
|
|
// AvailableBackendsForCapabilities lists backends runnable on the local system
|
|
// OR on any remote host reporting one of the supplied capabilities.
|
|
//
|
|
// In a distributed deployment the host serving this listing (the controller)
|
|
// is usually a GPU-less pod while the GPUs live on worker nodes. Filtering
|
|
// only against the controller hid every GPU-only meta backend from admins even
|
|
// though installing it by name on a worker worked fine, so compatibility is
|
|
// evaluated as a union over the cluster. An empty capabilities slice reproduces
|
|
// AvailableBackends exactly, keeping single-node behavior untouched.
|
|
func AvailableBackendsForCapabilities(galleries []config.Gallery, systemState *system.SystemState, capabilities []string) (GalleryElements[*GalleryBackend], error) {
|
|
if len(capabilities) == 0 {
|
|
return AvailableBackends(galleries, systemState)
|
|
}
|
|
|
|
// Each remote capability is evaluated through a state pinned to that exact
|
|
// capability, so the controller's own detection (and any forced capability
|
|
// on the controller image) cannot leak into the worker's verdict. Backend
|
|
// paths still come from the controller's state because that is where the
|
|
// gallery metadata is read from.
|
|
nodeStates := make([]*system.SystemState, 0, len(capabilities))
|
|
for _, capability := range capabilities {
|
|
nodeStates = append(nodeStates, system.NewCapabilityState(capability,
|
|
system.WithBackendPath(systemState.Backend.BackendsPath)))
|
|
}
|
|
|
|
return availableBackendsWithFilter(galleries, systemState, func(backend *GalleryBackend) bool {
|
|
if backend.IsCompatibleWith(systemState) {
|
|
return true
|
|
}
|
|
for _, nodeState := range nodeStates {
|
|
if backend.IsCompatibleWith(nodeState) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
})
|
|
}
|
|
|
|
// availableBackendsWithFilter lists available backends, keeping only those
|
|
// accepted by compatible. A nil compatible keeps everything.
|
|
func availableBackendsWithFilter(galleries []config.Gallery, systemState *system.SystemState, compatible func(*GalleryBackend) bool) (GalleryElements[*GalleryBackend], error) {
|
|
var backends []*GalleryBackend
|
|
|
|
systemBackends, err := ListSystemBackends(systemState)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
// Get backends from galleries
|
|
for _, gallery := range galleries {
|
|
galleryBackends, err := getGalleryElements(gallery, systemState.Backend.BackendsPath, func(backend *GalleryBackend) bool {
|
|
return systemBackends.Exists(backend.GetName())
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if compatible == nil {
|
|
backends = append(backends, galleryBackends...)
|
|
continue
|
|
}
|
|
|
|
for _, backend := range galleryBackends {
|
|
if compatible(backend) {
|
|
backends = append(backends, backend)
|
|
}
|
|
}
|
|
}
|
|
|
|
return backends, nil
|
|
}
|
|
|
|
func findGalleryURLFromReferenceURL(url string, basePath string) (string, error) {
|
|
var refFile string
|
|
uri := downloader.URI(url)
|
|
err := uri.ReadWithCallback(basePath, func(url string, d []byte) error {
|
|
refFile = string(d)
|
|
if len(refFile) == 0 {
|
|
return fmt.Errorf("invalid reference file at url %s: %s", url, d)
|
|
}
|
|
cutPoint := strings.LastIndex(url, "/")
|
|
refFile = url[:cutPoint+1] + refFile
|
|
return nil
|
|
})
|
|
return refFile, err
|
|
}
|
|
|
|
type galleryCacheEntry struct {
|
|
yamlEntry []byte
|
|
lastUpdated time.Time
|
|
}
|
|
|
|
func (entry galleryCacheEntry) hasExpired() bool {
|
|
return entry.lastUpdated.Before(time.Now().Add(-1 * time.Hour))
|
|
}
|
|
|
|
var galleryCache = xsync.NewSyncedMap[string, galleryCacheEntry]()
|
|
|
|
func getGalleryElements[T GalleryElement](gallery config.Gallery, basePath string, isInstalledCallback func(T) bool) ([]T, error) {
|
|
var models []T = []T{}
|
|
|
|
if strings.HasSuffix(gallery.URL, ".ref") {
|
|
var err error
|
|
gallery.URL, err = findGalleryURLFromReferenceURL(gallery.URL, basePath)
|
|
if err != nil {
|
|
return models, err
|
|
}
|
|
}
|
|
|
|
cacheKey := fmt.Sprintf("%s-%s", gallery.Name, gallery.URL)
|
|
if galleryCache.Exists(cacheKey) {
|
|
entry := galleryCache.Get(cacheKey)
|
|
// refresh if last updated is more than 1 hour ago
|
|
if !entry.hasExpired() {
|
|
err := yaml.Unmarshal(entry.yamlEntry, &models)
|
|
if err != nil {
|
|
return models, err
|
|
}
|
|
} else {
|
|
galleryCache.Delete(cacheKey)
|
|
}
|
|
}
|
|
|
|
uri := downloader.URI(gallery.URL)
|
|
|
|
if len(models) == 0 {
|
|
err := uri.ReadWithCallback(basePath, func(url string, d []byte) error {
|
|
galleryCache.Set(cacheKey, galleryCacheEntry{
|
|
yamlEntry: d,
|
|
lastUpdated: time.Now(),
|
|
})
|
|
return yaml.Unmarshal(d, &models)
|
|
})
|
|
if err != nil {
|
|
if yamlErr, ok := err.(*yaml.TypeError); ok {
|
|
xlog.Debug("YAML errors", "errors", strings.Join(yamlErr.Errors, "\n"), "models", models)
|
|
}
|
|
return models, fmt.Errorf("failed to read gallery elements: %w", err)
|
|
}
|
|
}
|
|
|
|
// Add gallery to models
|
|
for _, model := range models {
|
|
model.SetGallery(gallery)
|
|
model.SetInstalled(isInstalledCallback(model))
|
|
}
|
|
return models, nil
|
|
}
|