Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ Quant tags match whole tokens when identifying cached weights: `F16` does not se

`modelSelection` holds the chosen `selection` plus a `custom` object with the last Custom submission's fields; picking another entry leaves `custom` in place so Custom stays prefilled. `modelSettings` is a list of `{preset}` or `{hfRepo, hfFile}` entries with `ctx`, `ngl` and `extraArgs`, one per model, replaced on each submit of that model. A preset entry matches its preset; a repo entry matches by the weights it resolves to — the same cached file, or the same quant tag before download — so a Custom model keeps its settings once it shows up as a downloaded entry, and one that is a preset's quant counts as that preset. Stores from before `modelSettings` fall back to `modelSelection.custom`. The daemon reads neither, so they cannot disagree with `model` about what is actually running — at worst they prefill a form with a stale answer.

**A preset's repo is resolved at every start, never saved.** `main.ts` looks the preset up in `startos/actions/presets.ts` and serves its `hfRepo`, unless those weights are not cached and a repo in its `formerRepos` has them cached, in which case it serves that one. A preset whose upstream repo is withdrawn therefore moves to its replacement on the next start for everyone without the old weights, restores included, while a server that already downloaded it keeps using its copy: llama-server falls back to cached files when HuggingFace refuses the repo.
**A preset's repo is resolved at every start, never saved.** `main.ts` looks the preset up in `startos/actions/presets.ts` and serves its `hfRepo`, unless those weights are not cached and a repo in its `formerRepos` has them cached, in which case it serves that one. A preset whose upstream repo is withdrawn therefore moves to its replacement on the next start for everyone without the old weights, restores included, while a server that already downloaded it keeps using its copy: llama-server falls back to cached files when HuggingFace refuses the repo. Once the current repo is cached, `main.ts` deletes unused former repos' folders before starting; a folder that also holds another quant, or is the effective main or draft model's repo (including overrides in Extra arguments), is kept. A split model counts as cached only with every part on disk, so an interrupted download never displaces a complete copy.

**No configuration file reaches the application.** Two environment variables are set, both redirecting caches onto the volume so downloaded weights survive a container rebuild:

Expand Down Expand Up @@ -148,6 +148,8 @@ Chooses what the server runs — either a curated preset or a model of your own.
- **The form reopens on the running model**, which stays selectable: change its settings and submit to restart with them. Submitting it unchanged writes the same `model` and `settingsArgs` and does not restart. With nothing chosen yet the form falls back to the hardware-filtered default.
- **Presets are filtered to your hardware.** The form reads the accelerator's memory — VRAM on NVIDIA and ROCm, system memory otherwise — and disables any preset that would not fit, defaulting to the smallest that does. The field's help text lists every preset with the memory it needs. The estimate is the quantized weights plus roughly a quarter for the context cache.
- **Models already downloaded to the volume appear in the same list**, so a model you fetched before can be reselected without retyping its repo or re-downloading it. A downloaded file that is a preset's quant stays under that preset, while other quants of the same repo get their own entries. A downloaded entry is passed to `llama-server` as `-hf <org>/<repo> -hff <file>` so the exact cached quant is reused; a first-time downloaded entry defaults to an 8192-token context. When the entry is the running model, its repo and file arguments are kept as they were written.
- **The form shows how much disk downloaded models use**, under the model list.
- **Delete other downloaded models**, off by default, removes every cache entry except the selected model and its draft model after saving the selection, as Delete Model Cache would one at a time. A selected preset keeps all its cached copies until its next start removes the superseded ones.
- **Custom** takes a HuggingFace GGUF repo, optionally a specific file, a context size, a GPU-layer count, and extra server flags. Those extra flags are split on whitespace, so a quoted value with spaces will not survive.

### Set UI Password
Expand Down
2 changes: 1 addition & 1 deletion instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ curl -s -H "Authorization: Bearer <your-api-key>" <api-interface-url>/v1/chat/co

### Actions

- **Set Model** — switch to a different preset, a model you already downloaded, or a custom GGUF. The form opens on the model you are running, with its settings filled in, so you can change its context size or flags and submit; submitting without changes does not restart anything. Each model remembers its own settings, so switching away and back keeps them. The service restarts with the new weights; uncached models download on this restart.
- **Set Model** — switch to a different preset, a model you already downloaded, or a custom GGUF. The form opens on the model you are running, with its settings filled in, so you can change its context size or flags and submit; submitting without changes does not restart anything. Each model remembers its own settings, so switching away and back keeps them. The service restarts with the new weights; uncached models download on this restart. Models you switch away from stay downloaded so switching back is instant; the form shows how much disk they use, and turning on **Delete other downloaded models** removes all of them except the one you select.
- **Set UI Password** — generate a new web UI password (username stays `admin`). Use it for first-time setup or to rotate the password later; when rotating, it asks you to confirm, since saved logins stop working.
- **API Key** — show the key for the OpenAI-compatible API interface. Turn on **Generate a new key** to replace it; clients outside StartOS then need the new key, and StartOS apps pick it up when they restart.
- **Delete Model Cache** — pick a downloaded model from the list, with its size, and remove it to reclaim disk space. The model you are currently running can't be deleted; a selected preset protects its cached copies from both current and former publishers. Switch to another model with Set Model first. A deleted model will be re-downloaded if you select it again.
Expand Down
28 changes: 3 additions & 25 deletions startos/actions/deleteModelCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,38 +6,16 @@ import {
cacheDir,
entryLabel,
formatBytes,
isCached,
listCacheEntries,
listCachedModels,
repoFolderName,
} from '../modelCache'
import { sdk } from '../sdk'
import {
hfDraftRepoFlags,
hfRepoFlags,
lastOptionValue,
refTargets,
serveArgsOf,
} from '../utils'
import { cacheEntriesInUse } from '../utils'

const { InputSpec, Value } = sdk

// Cache folders of the configured main and draft models, last flag winning
// as in llama-server. It keeps them open, so deleting one would free nothing
// until a restart, which downloads it again.
async function inUseEntries(): Promise<Set<string>> {
const store = await storeJson.read().once()
const cached = await listCachedModels()
const serveArgs = serveArgsOf(store, cached) ?? []
const repos = [hfRepoFlags, hfDraftRepoFlags]
.map((flags) => lastOptionValue(serveArgs, flags)?.split(':')[0])
.filter((repo): repo is string => Boolean(repo))
// Cache changes must not make a running preset's repo deletable.
const candidates = refTargets(store?.model)
.filter((target) => isCached(target, cached))
.map((target) => target.repo)
return new Set([...repos, ...candidates].map(repoFolderName))
}
const inUseEntries = async () =>
cacheEntriesInUse(await storeJson.read().once(), await listCachedModels())

const inputSpec = InputSpec.of({
model: Value.dynamicSelect(async () => {
Expand Down
41 changes: 39 additions & 2 deletions startos/actions/setModel.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,26 @@
import { rm } from 'node:fs/promises'
import { join } from 'node:path'
import { T } from '@start9labs/start-sdk'
import { i18n } from '../i18n'
import { sdk } from '../sdk'
import { storeJson, type ModelRef } from '../fileModels/store.json'
import { detectHardware } from '../hardware'
import {
cacheDir,
formatBytes,
listCacheEntries,
listCachedModels,
parseTarget,
repoFolderName,
targetFile,
type CachedModel,
} from '../modelCache'
import { isGpuVariant, matchingPreset, sameRef } from '../utils'
import {
cacheEntriesInUse,
isGpuVariant,
matchingPreset,
sameRef,
} from '../utils'
import { models } from './presets'

const { InputSpec, Value, Variants } = sdk
Expand Down Expand Up @@ -139,6 +149,10 @@ const inputSpec = InputSpec.of({
// Anything already on disk can be selected again without re-downloading.
// Preset files are left out because their entry is already in the list.
const allCached = await listCachedModels()
const cacheBytes = (await listCacheEntries()).reduce(
(total, e) => total + e.bytes,
0,
)
const cached = allCached.filter((c) => !matchingPreset(c, allCached))
// Label by repo alone when it has one cached file; append the file only
// when a repo has several, where it is needed to tell them apart.
Expand Down Expand Up @@ -211,12 +225,27 @@ const inputSpec = InputSpec.of({
`- ${i18n(m.displayName)}: ${i18n('needs about ${memory} GB of memory', { memory: m.minMemoryGB })}`,
),
`- ${i18n('Custom')}: ${i18n('any HuggingFace GGUF model, with your own context size, GPU layers and server flags')}`,
...(cacheBytes > 0
? [
'',
i18n('Downloaded models use ${size} of disk.', {
size: formatBytes(cacheBytes),
}),
]
: []),
].join('\n'),
variants: Variants.of(variants),
default: defaultId as string,
disabled: disabledIds.length > 0 ? disabledIds : false,
}
}),
deleteOthers: Value.toggle({
name: i18n('Delete other downloaded models'),
description: i18n(
'Remove every downloaded model except the one selected here and its draft model, freeing their disk space. A deleted model downloads again if you select it later.',
),
default: false,
}),
})

// The settings as form values; the text field takes null, not undefined.
Expand Down Expand Up @@ -340,9 +369,10 @@ export const setModel = sdk.Action.withInput(
hfRepo: model.hfRepo,
hfFile: model.hfFile,
}
const settingsArgs = settingsArgsFor(settings)
await storeJson.merge(effects, {
model: modelRef,
settingsArgs: settingsArgsFor(settings),
settingsArgs,
modelSelection: {
selection: config.selection,
custom:
Expand All @@ -357,5 +387,12 @@ export const setModel = sdk.Action.withInput(
{ ...modelRef, ...settings },
],
})

if (input.deleteOthers) {
const keep = cacheEntriesInUse({ model: modelRef, settingsArgs }, cached)
for (const { name } of await listCacheEntries()) {
if (!keep.has(name)) await rm(join(cacheDir, name), { recursive: true })
}
}
},
)
4 changes: 4 additions & 0 deletions startos/i18n/dictionaries/default.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ export const DEFAULT_LANG = 'en_US'

const dict = {
// main.ts
'Removed ${model}, which the selected preset no longer uses.': 64,
'Starting llama.cpp!': 0,
'llama.cpp API': 1,
'The llama.cpp API is ready': 2,
Expand Down Expand Up @@ -34,6 +35,9 @@ const dict = {
'needs about ${memory} GB of memory': 47,
'any HuggingFace GGUF model, with your own context size, GPU layers and server flags': 48,
'That downloaded model is no longer in the cache.': 53,
'Delete other downloaded models': 61,
'Remove every downloaded model except the one selected here and its draft model, freeing their disk space. A deleted model downloads again if you select it later.': 62,
'Downloaded models use ${size} of disk.': 63,

// model preset labels
'Llama 3.2 1B Instruct': 22,
Expand Down
16 changes: 16 additions & 0 deletions startos/i18n/dictionaries/translations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,10 @@ export default {
58: 'Clave de API',
59: 'Muestra la clave de la interfaz API compatible con OpenAI o genera una nueva.',
60: 'Envíe esta clave como "Authorization: Bearer <clave>" a la interfaz API compatible con OpenAI. En la mayoría de los clientes, establezca la URL base en la dirección de esa interfaz con /v1 añadido y pegue esto como clave de API.',
61: 'Eliminar los demás modelos descargados',
62: 'Elimina todos los modelos descargados excepto el seleccionado aquí y su modelo borrador, liberando su espacio en disco. Un modelo eliminado se vuelve a descargar si lo selecciona más adelante.',
63: 'Los modelos descargados ocupan ${size} de disco.',
64: 'Se eliminó ${model}, que el preset seleccionado ya no usa.',
},
de_DE: {
0: 'Starte llama.cpp!',
Expand Down Expand Up @@ -126,6 +130,10 @@ export default {
58: 'API-Schlüssel',
59: 'Zeigt den Schlüssel für die OpenAI-kompatible API-Schnittstelle an oder erzeugt einen neuen.',
60: 'Senden Sie diesen Schlüssel als „Authorization: Bearer <Schlüssel>“ an die OpenAI-kompatible API-Schnittstelle. In den meisten Clients setzen Sie die Basis-URL auf die Adresse dieser Schnittstelle mit angehängtem /v1 und fügen dies als API-Schlüssel ein.',
61: 'Andere heruntergeladene Modelle löschen',
62: 'Entfernt alle heruntergeladenen Modelle außer dem hier ausgewählten und seinem Entwurfsmodell und gibt ihren Speicherplatz frei. Ein gelöschtes Modell wird erneut heruntergeladen, wenn Sie es später auswählen.',
63: 'Heruntergeladene Modelle belegen ${size} Speicherplatz.',
64: '${model} wurde entfernt, da das ausgewählte Preset es nicht mehr verwendet.',
},
pl_PL: {
0: 'Uruchamianie llama.cpp!',
Expand Down Expand Up @@ -189,6 +197,10 @@ export default {
58: 'Klucz API',
59: 'Pokazuje klucz do interfejsu API zgodnego z OpenAI lub generuje nowy.',
60: 'Wysyłaj ten klucz jako „Authorization: Bearer <klucz>” do interfejsu API zgodnego z OpenAI. W większości klientów ustaw bazowy URL na adres tego interfejsu z dopisanym /v1 i wklej to jako klucz API.',
61: 'Usuń pozostałe pobrane modele',
62: 'Usuwa wszystkie pobrane modele oprócz wybranego tutaj i jego modelu szkicowego, zwalniając miejsce na dysku. Usunięty model zostanie pobrany ponownie, jeśli wybierzesz go później.',
63: 'Pobrane modele zajmują ${size} na dysku.',
64: 'Usunięto ${model}, którego wybrany preset już nie używa.',
},
fr_FR: {
0: 'Démarrage de llama.cpp !',
Expand Down Expand Up @@ -252,5 +264,9 @@ export default {
58: 'Clé d’API',
59: 'Affiche la clé de l’interface API compatible OpenAI, ou en génère une nouvelle.',
60: 'Envoyez cette clé sous la forme « Authorization: Bearer <clé> » à l’interface API compatible OpenAI. Dans la plupart des clients, définissez l’URL de base sur l’adresse de cette interface suivie de /v1 et collez ceci comme clé d’API.',
61: 'Supprimer les autres modèles téléchargés',
62: 'Supprime tous les modèles téléchargés sauf celui sélectionné ici et son modèle brouillon, libérant leur espace disque. Un modèle supprimé est retéléchargé si vous le sélectionnez plus tard.',
63: 'Les modèles téléchargés occupent ${size} d’espace disque.',
64: '${model} a été supprimé, car le préréglage sélectionné ne l’utilise plus.',
},
} satisfies Record<string, LangDict>
32 changes: 24 additions & 8 deletions startos/main.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,34 @@
import { i18n } from './i18n'
import { sdk } from './sdk'
import { storeJson } from './fileModels/store.json'
import { listCachedModels } from './modelCache'
import { apiPort, serveArgsOf } from './utils'
import { rm } from 'node:fs/promises'
import { join } from 'node:path'
import {
cacheDir,
entryLabel,
listCachedModels,
readdirSafe,
} from './modelCache'
import { apiPort, serveArgsOf, supersededCopies } from './utils'

export const main = sdk.setupMain(async ({ effects }) => {
console.info(i18n('Starting llama.cpp!'))

const serveArgs = serveArgsOf(
await storeJson
.read((s) => ({ model: s?.model, settingsArgs: s?.settingsArgs }))
.const(effects),
await listCachedModels(),
)
const store = await storeJson
.read((s) => ({ model: s?.model, settingsArgs: s?.settingsArgs }))
.const(effects)
const cached = await listCachedModels()
const onDisk = await readdirSafe(cacheDir)
for (const name of supersededCopies(store, cached)) {
if (!onDisk.includes(name)) continue
await rm(join(cacheDir, name), { recursive: true })
console.info(
i18n('Removed ${model}, which the selected preset no longer uses.', {
model: entryLabel(name),
}),
)
}
const serveArgs = serveArgsOf(store, cached)

const subcontainer = sdk.SubContainer.of(
effects,
Expand Down
36 changes: 25 additions & 11 deletions startos/modelCache.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { lstat, readdir, stat } from 'node:fs/promises'
import { basename, join } from 'node:path'
import { basename, dirname, join } from 'node:path'
import { sdk } from './sdk'

// llama-server's LLAMA_CACHE (see main.ts), as seen from the action.
Expand Down Expand Up @@ -119,6 +119,28 @@ function isModelStart(file: string): boolean {
return !split || Number(split[2]) <= 1 || Number(split[1]) === 1
}

const isFile = (path: string) =>
stat(path).then(
(info) => info.isFile(),
(e: NodeJS.ErrnoException) => {
if (e.code === 'ENOENT') return false
throw e
},
)

// A split model counts only with every part on disk: an interrupted download
// leaves the first part without the rest.
async function isComplete(path: string) {
const split = basename(path).match(/^(.+-)00001-of-([0-9]{5})(\.gguf)$/i)
if (!split) return isFile(path)
const [, stem, total, ext] = split
for (let part = 1; part <= Number(total); part++) {
const name = `${stem}${String(part).padStart(5, '0')}-of-${total}${ext}`
if (!(await isFile(join(dirname(path), name)))) return false
}
return true
}

async function snapshotFiles(
path: string,
files: Set<string>,
Expand All @@ -131,16 +153,8 @@ async function snapshotFiles(
const info = await lstat(child)
if (info.isDirectory()) {
await snapshotFiles(child, files, file)
} else if (isModelStart(file)) {
if (info.isFile()) {
files.add(file)
} else if (info.isSymbolicLink()) {
try {
if ((await stat(child)).isFile()) files.add(file)
} catch (e: any) {
if (e.code !== 'ENOENT') throw e
}
}
} else if (isModelStart(file) && (await isComplete(child))) {
files.add(file)
}
}
}
Expand Down
Loading