Skip to content

The agent that grows with you

feat(local-runtime): one-click quickstart — engine, recommended model, default

emozillab1ef72786d0c
diff --git a/apps/desktop/src/api/local-models.ts b/apps/desktop/src/api/local-models.ts
index f3b5f35566d..d2cbce5f2c8 100644
--- a/apps/desktop/src/api/local-models.ts
+++ b/apps/desktop/src/api/local-models.ts
@@ -40,6 +40,24 @@ export function installLocalRuntime(backend?: string): Promise<{ backend: string
})
}
+export interface QuickstartResponse {
+ display_name: string
+ download_bytes: number
+ job_id: string
+ model_id: string
+ needs_download: boolean
+ needs_runtime: boolean
+}
+
+export function quickstartLocalModels(modelId?: string): Promise<QuickstartResponse> {
+ return hermesApi<QuickstartResponse>({
+ ...profileScoped(),
+ body: { model_id: modelId ?? null },
+ method: 'POST',
+ path: '/api/local-models/quickstart'
+ })
+}
+
export function downloadLocalModel(modelId: string): Promise<{ already_downloaded?: boolean; job_id: null | string }> {
return hermesApi<{ already_downloaded?: boolean; job_id: null | string }>({
...profileScoped(),
diff --git a/apps/desktop/src/app/settings/local-models-settings.test.tsx b/apps/desktop/src/app/settings/local-models-settings.test.tsx
index 5114eff925a..a118a21a511 100644
--- a/apps/desktop/src/app/settings/local-models-settings.test.tsx
+++ b/apps/desktop/src/app/settings/local-models-settings.test.tsx
@@ -22,6 +22,7 @@ vi.mock('@/hermes', () => ({
getLocalRuntimeJob: vi.fn(),
installLocalRuntime: vi.fn(),
listHFRepoFiles: vi.fn(),
+ quickstartLocalModels: vi.fn(),
searchHFModels: vi.fn(),
sideloadLocalModel: vi.fn()
}))
@@ -107,6 +108,18 @@ function renderPane() {
)
}
+// The fresh-machine states these tests exercise now lead with the
+// quickstart card; the full pane (runtime rows, model list, browser)
+// is one 'Configure…' click away. Render and click through.
+async function renderFullPane() {
+ const result = renderPane()
+ const configure = await screen.findByRole('button', { name: /configure/i })
+
+ fireEvent.click(configure)
+
+ return result
+}
+
beforeEach(() => {
mocked.getLocalModelsStatus.mockResolvedValue(BASE_STATUS)
mocked.getLocalHardware.mockResolvedValue(BASE_HARDWARE)
@@ -122,7 +135,7 @@ afterEach(() => {
describe('LocalModelsSettings', () => {
it('offers the runtime install with a plain-language explanation', async () => {
- renderPane()
+ await renderFullPane()
expect(await screen.findByText('Install the local runtime')).toBeTruthy()
expect(screen.getByText(/runs? entirely on this machine/i)).toBeTruthy()
@@ -130,7 +143,7 @@ describe('LocalModelsSettings', () => {
})
it('shows every catalog model with fit pills; unaffordable ones stay visible with the reason', async () => {
- renderPane()
+ await renderFullPane()
expect(await screen.findByText('Qwen3.6 27B')).toBeTruthy()
// The fitting model reads as pills, not prose: green memory pill +
@@ -162,7 +175,7 @@ describe('LocalModelsSettings', () => {
runtime_installed: true,
runtime_backend: 'cuda'
})
- renderPane()
+ await renderFullPane()
await screen.findByText('Qwen3.6 27B')
const [fittingButton] = screen.getAllByRole('button', { name: /download · 17\.6 GB/i })
@@ -170,7 +183,7 @@ describe('LocalModelsSettings', () => {
})
it('shows hardware facts after backfill', async () => {
- renderPane()
+ await renderFullPane()
expect(await screen.findByText('NVIDIA GeForce RTX 5090')).toBeTruthy()
expect(screen.getByText(/32\.0 GB GPU memory/)).toBeTruthy()
@@ -203,7 +216,7 @@ describe('LocalModelsSettings', () => {
.mockResolvedValueOnce({ jobs: [running] })
.mockResolvedValue({ jobs: [{ ...running, status: 'done', phase: 'done', done_bytes: 100, percent: 100 }] })
- renderPane()
+ await renderFullPane()
await screen.findByText('Qwen3.6 27B')
const [download] = screen.getAllByRole('button', { name: /download · 17\.6 GB/i })
@@ -241,7 +254,7 @@ describe('LocalModelsSettings', () => {
}
])
- renderPane()
+ await renderFullPane()
await screen.findByText('Qwen3.6 27B')
// The fitting row shows byte progress; the remaining download
@@ -273,13 +286,74 @@ describe('LocalModelsSettings', () => {
}
])
- renderPane()
+ await renderFullPane()
await screen.findByText('Qwen3.6 27B')
expect(await screen.findByText(/integrity check/)).toBeTruthy()
})
})
+describe('quickstart', () => {
+ it('leads with one button on a fresh machine and fires the quickstart job', async () => {
+ mocked.quickstartLocalModels.mockResolvedValue({
+ display_name: 'Qwen3.6 27B',
+ download_bytes: FITTING_MODEL.size_bytes,
+ job_id: 'q1',
+ model_id: 'qwen3.6-27b',
+ needs_download: true,
+ needs_runtime: true
+ })
+ renderPane()
+
+ // The card names the recommended model and the one-click action; the
+ // runtime/model machinery is NOT on screen.
+ expect(await screen.findByRole('button', { name: /set up for me/i })).toBeTruthy()
+ expect(screen.queryByText('Install the local runtime')).toBeNull()
+
+ fireEvent.click(screen.getByRole('button', { name: /set up for me/i }))
+ await waitFor(() => {
+ expect(mocked.quickstartLocalModels).toHaveBeenCalled()
+ })
+ })
+
+ it('pins the quickstart progress view while the job runs', async () => {
+ $localRuntimeJobs.set([
+ {
+ job_id: 'q1',
+ kind: 'quickstart',
+ target: 'Qwen3.6 27B',
+ model_id: 'qwen3.6-27b',
+ status: 'running',
+ phase: 'downloading',
+ detail: 'Qwen3.6 27B — 17.6 GB',
+ total_bytes: 100,
+ done_bytes: 30,
+ percent: 30,
+ error: null
+ }
+ ])
+ renderPane()
+
+ expect(await screen.findByText('Qwen3.6 27B — 17.6 GB')).toBeTruthy()
+ // One job, one view: no Set up / Configure buttons while it runs.
+ expect(screen.queryByRole('button', { name: /set up for me/i })).toBeNull()
+ })
+
+ it('skips the card entirely once a model is staged', async () => {
+ mocked.getLocalModelsStatus.mockResolvedValue({
+ ...BASE_STATUS,
+ runtime_installed: true,
+ runtime_backend: 'cuda',
+ models: [{ id: 'Qwen3.6-27B-UD-Q4_K_XL', size_bytes: 17 * 2 ** 30, size_label: '17.6 GB' }]
+ })
+ renderPane()
+
+ // Straight to the full pane — no quickstart hero for a working setup.
+ expect(await screen.findByText('Qwen3.6 27B')).toBeTruthy()
+ expect(screen.queryByRole('button', { name: /set up for me/i })).toBeNull()
+ })
+})
+
describe('BrowseSection', () => {
it('searches HF after a pause and shows fit-priced files on demand', async () => {
vi.useFakeTimers()
@@ -302,6 +376,8 @@ describe('BrowseSection', () => {
await act(async () => {
await vi.runOnlyPendingTimersAsync()
})
+ // Fresh machine leads with the quickstart card — enter the full pane.
+ fireEvent.click(screen.getByRole('button', { name: /configure/i }))
const box = screen.getByPlaceholderText(/search models/i)
fireEvent.change(box, { target: { value: 'qwen' } })
diff --git a/apps/desktop/src/app/settings/local-models-settings.tsx b/apps/desktop/src/app/settings/local-models-settings.tsx
index 279c5952b08..bc5a42b0e91 100644
--- a/apps/desktop/src/app/settings/local-models-settings.tsx
+++ b/apps/desktop/src/app/settings/local-models-settings.tsx
@@ -16,6 +16,7 @@ import {
type HFSearchHit,
installLocalRuntime,
listHFRepoFiles,
+ quickstartLocalModels,
searchHFModels,
setLocalServer,
sideloadLocalModel
@@ -59,8 +60,11 @@ export function LocalModelsSettings() {
const [status, setStatus] = useState<LocalModelsStatus | null>(null)
const [hardware, setHardware] = useState<LocalHardware | null>(null)
const [catalog, setCatalog] = useState<LocalCatalogModel[] | null>(null)
- const [deleting, setDeleting] = useState<string | null>(null)
+ const [deleting, setDeleting] = useState<null | string>(null)
const [serverBusy, setServerBusy] = useState(false)
+ // Quickstart escape hatch: true once the user asks for the full pane
+ // (model list, HF browser) instead of the one-button setup card.
+ const [configure, setConfigure] = useState(false)
// Jobs live in the app-level store (they must survive this pane
// unmounting); the pane just renders the slice it cares about.
const jobs = useStore($localRuntimeJobs)
@@ -137,6 +141,15 @@ export function LocalModelsSettings() {
}
}
+ async function handleQuickstart() {
+ try {
+ await quickstartLocalModels()
+ watchLocalRuntimeJobs()
+ } catch (err) {
+ notifyError(err, copy.quickstartFailed)
+ }
+ }
+
async function handleDownload(model: LocalCatalogModel) {
try {
const res = await downloadLocalModel(model.id)
@@ -220,6 +233,60 @@ export function LocalModelsSettings() {
const rJob = runningRuntimeInstall(jobs)
const lastError = jobs.find(j => j.status === 'error')
+ // ── Quickstart: the dummy-proof front door ──
+ // Until something is servable (runtime + at least one model), the pane
+ // leads with one button that does everything; the full pane stays one
+ // 'Configure…' click away. A running quickstart pins this view so its
+ // progress has a home even after a remount.
+ const qJob = jobs.find(j => j.kind === 'quickstart' && j.status === 'running') ?? null
+ const needsSetup = !status.runtime_installed || status.models.length === 0
+ const heroModel = catalog.find(c => c.recommended && c.fits) ?? catalog.find(c => c.fits) ?? null
+
+ if (qJob || (needsSetup && !configure && heroModel)) {
+ return (
+ <SettingsContent>
+ <SettingsSection icon={Zap} title={copy.quickstartTitle}>
+ {qJob ? (
+ <ListRow
+ below={<ProgressBar percent={qJob.percent} />}
+ description={qJob.detail || copy.installing}
+ title={
+ <span className="inline-flex items-center gap-2">
+ <Loader2 className="size-3.5 animate-spin" />
+ {qJob.target}
+ </span>
+ }
+ />
+ ) : heroModel ? (
+ <ListRow
+ action={
+ <div className="flex items-center gap-2">
+ <Button onClick={() => setConfigure(true)} size="sm" variant="outline">
+ {copy.quickstartConfigure}
+ </Button>
+ <Button onClick={() => void handleQuickstart()} size="sm">
+ <Zap />
+ {copy.quickstartAction}
+ </Button>
+ </div>
+ }
+ description={
+ heroModel.downloaded
+ ? copy.quickstartDetailReady(heroModel.display_name)
+ : copy.quickstartDetail(heroModel.display_name, heroModel.size_label)
+ }
+ title={heroModel.display_name}
+ />
+ ) : null}
+
+ {lastError?.kind === 'quickstart' && (
+ <p className="text-[0.75rem] text-destructive">{lastError.error}</p>
+ )}
+ </SettingsSection>
+ </SettingsContent>
+ )
+ }
+
// Up to date = the authority (status) says the configured tag is what's
// serving. Shown whenever true — not only right after an update.
const updateApplied =
diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.ts
index ca325a32f25..637a4b49ca2 100644
--- a/apps/desktop/src/i18n/en.ts
+++ b/apps/desktop/src/i18n/en.ts
@@ -1104,6 +1104,14 @@ export const en: Translations = {
downloadProgress: (done, total) => `${done} of ${total}`,
downloadDoneToast: model => `${model} is ready.`,
installDoneToast: 'Local runtime installed and ready.',
+ quickstartTitle: 'Run a model on this machine',
+ quickstartDetail: (model, size) =>
+ `One click sets everything up: the local engine, ${model} (${size} download), and your default for new chats. Nothing leaves this computer.`,
+ quickstartDetailReady: model => `One click makes ${model} your default for new chats. Everything runs on this machine.`,
+ quickstartAction: 'Set up for me',
+ quickstartConfigure: 'Configure…',
+ quickstartDoneToast: model => `${model} is set up — new chats run on this machine.`,
+ quickstartFailed: 'Local model setup failed',
useAction: 'Use',
activePill: 'Default',
updateTitle: 'Engine update available',
diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.ts
index 90674b9d988..d787e7ae2a0 100644
--- a/apps/desktop/src/i18n/types.ts
+++ b/apps/desktop/src/i18n/types.ts
@@ -954,6 +954,13 @@ export interface Translations {
downloadProgress: (done: string, total: string) => string
downloadDoneToast: (model: string) => string
installDoneToast: string
+ quickstartTitle: string
+ quickstartDetail: (model: string, size: string) => string
+ quickstartDetailReady: (model: string) => string
+ quickstartAction: string
+ quickstartConfigure: string
+ quickstartDoneToast: (model: string) => string
+ quickstartFailed: string
useAction: string
activePill: string
updateTitle: string
diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.ts
index dc299ee341f..8ea3fdedb8b 100644
--- a/apps/desktop/src/i18n/zh.ts
+++ b/apps/desktop/src/i18n/zh.ts
@@ -1286,6 +1286,14 @@ export const zh: Translations = {
installAction: '安装运行时',
installing: '正在安装运行时…',
installFailed: '运行时安装失败',
+ quickstartTitle: '在本机运行模型',
+ quickstartDetail: (model, size) =>
+ `一键完成所有设置:本地引擎、${model}(需下载 ${size}),并设为新会话的默认模型。数据不会离开这台电脑。`,
+ quickstartDetailReady: model => `一键将 ${model} 设为新会话的默认模型。所有内容都在本机运行。`,
+ quickstartAction: '为我设置',
+ quickstartConfigure: '自定义…',
+ quickstartDoneToast: model => `${model} 已就绪——新会话将在本机运行。`,
+ quickstartFailed: '本地模型设置失败',
hardwareTitle: '本机配置',
hardwareLoading: '正在检测硬件…',
vram: label => `${label} 显存`,
diff --git a/apps/desktop/src/store/local-runtime-jobs.ts b/apps/desktop/src/store/local-runtime-jobs.ts
index 7ec47da9df4..d7829d2b802 100644
--- a/apps/desktop/src/store/local-runtime-jobs.ts
+++ b/apps/desktop/src/store/local-runtime-jobs.ts
@@ -57,7 +57,9 @@ function notifySettled(previous: readonly LocalRuntimeJob[], next: readonly Loca
? translateNow('settings.localModels.downloadDoneToast', job.target)
: job.kind === 'model-activate'
? translateNow('settings.localModels.activateDoneToast', job.target)
- : translateNow('settings.localModels.installDoneToast')
+ : job.kind === 'quickstart'
+ ? translateNow('settings.localModels.quickstartDoneToast', job.target)
+ : translateNow('settings.localModels.installDoneToast')
})
} else {
notifyError(
@@ -66,7 +68,9 @@ function notifySettled(previous: readonly LocalRuntimeJob[], next: readonly Loca
? translateNow('settings.localModels.downloadFailed', job.target)
: job.kind === 'model-activate'
? translateNow('settings.localModels.activateFailed', job.target)
- : translateNow('settings.localModels.installFailed')
+ : job.kind === 'quickstart'
+ ? translateNow('settings.localModels.quickstartFailed')
+ : translateNow('settings.localModels.installFailed')
)
}
}
diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.ts
index c412354796f..632b89ed6fd 100644
--- a/apps/desktop/src/types/hermes.ts
+++ b/apps/desktop/src/types/hermes.ts
@@ -1283,7 +1283,7 @@ export interface LocalCatalogModel {
export interface LocalRuntimeJob {
job_id: string
- kind: 'runtime-install' | 'model-download' | 'model-activate'
+ kind: 'model-activate' | 'model-download' | 'quickstart' | 'runtime-install'
target: string
model_id: string | null
status: 'running' | 'done' | 'error'
diff --git a/hermes_cli/web_routers/local_models.py b/hermes_cli/web_routers/local_models.py
index be9965b8a8d..43117874374 100644
--- a/hermes_cli/web_routers/local_models.py
+++ b/hermes_cli/web_routers/local_models.py
@@ -811,6 +811,169 @@ class ServerActionBody(BaseModel):
action: str # "stop" | "start"
+# ── quickstart: one click from nothing to a working default ──
+
+
+class QuickstartBody(BaseModel):
+ model_id: str | None = None # default: the catalog's recommended entry
+
+
[email protected]("/api/local-models/quickstart")
+async def local_models_quickstart(body: QuickstartBody):
+ """The dummy-proof path: one job that installs the runtime (if
+ missing), downloads this machine's build of the recommended model
+ (if missing), and makes it the default for new chats. Each leg is
+ the same code the individual routes run — this route only sequences
+ them, so 'Configure' (the existing pane) and quickstart can never
+ disagree about what gets installed.
+
+ Preflight rejects (no servable entry, engine too old) fail the POST
+ synchronously so the button can explain itself; everything slow runs
+ in the job with the usual phase/byte progress.
+ """
+ from hermes_cli.local_runtime.binaries import (
+ default_tag,
+ installed_tags,
+ resolve_assets,
+ select_backend,
+ )
+ from hermes_cli.local_runtime.bootstrap import (
+ _detect_gpu_vendor,
+ assets_dir,
+ staged_model_ids,
+ )
+ from hermes_cli.local_runtime.catalog import CATALOG, catalog_by_id, select_variant
+ from hermes_cli.local_runtime.hardware import probe_budget
+
+ # Resolve the target entry: explicit id, else recommended, else the
+ # first catalog entry this machine can serve.
+ budget = probe_budget(planning=True)
+ entry = None
+ if body.model_id:
+ entry = catalog_by_id().get(body.model_id)
+ if entry is None:
+ raise HTTPException(status_code=404,
+ detail=f"unknown model {body.model_id}")
+ candidates = [entry]
+ else:
+ candidates = sorted(CATALOG, key=lambda e: not e.recommended)
+ chosen = None
+ for candidate in candidates:
+ choice = select_variant(candidate, budget)
+ if choice is not None and not _engine_too_old(candidate.min_engine):
+ chosen = (candidate, choice.variant)
+ break
+ if chosen is None:
+ raise HTTPException(
+ status_code=409,
+ detail="no catalog model fits this machine — open Local Models "
+ "to browse for a smaller build")
+ entry, variant = chosen
+
+ section = _runtime_section()
+ tag = section.get("tag") or default_tag()
+ backend = section.get("backend", "auto")
+ if backend == "auto":
+ backend = select_backend(_detect_gpu_vendor())
+ need_runtime = not installed_tags()
+ if need_runtime:
+ # Same preflight as /runtime/install: impossible combos fail the POST.
+ try:
+ resolve_assets(tag, backend)
+ except Exception as exc: # noqa: BLE001
+ raise HTTPException(status_code=400, detail=str(exc))
+
+ need_download = variant.model_id not in staged_model_ids()
+ download_plan = [] # (url, dest, bytes)
+ if need_download:
+ for asset in variant.files:
+ download_plan.append(
+ (f"https://huggingface.co/{entry.repo}/resolve/main/{asset.path}",
+ _models_dir() / asset.local_name, asset.size_bytes))
+ for asset in (entry.mmproj, entry.draft):
+ if asset is not None:
+ download_plan.append(
+ (f"https://huggingface.co/{entry.repo}/resolve/main/{asset.path}",
+ assets_dir() / asset.local_name, asset.size_bytes))
+
+ job = _job("quickstart", entry.display_name, model_id=entry.id)
+ job["total_bytes"] = sum(p[2] for p in download_plan) or None
+
+ def _run():
+ try:
+ if need_runtime:
+ from hermes_cli.local_runtime.binaries import ensure_runtime_installed
+
+ job["phase"] = "installing-runtime"
+ job["detail"] = "Installing the local engine"
+ ensure_runtime_installed(tag, backend)
+
+ if need_download:
+ job["phase"] = "downloading"
+ total = sum(p[2] for p in download_plan)
+ job["detail"] = f"{entry.display_name} — {_human_gb(total)}"
+ done_before = 0
+ for url, dest, size in download_plan:
+ if dest.exists():
+ done_before += size
+ job["done_bytes"] = done_before
+ continue
+ download_file(url, dest, job,
+ base_done=done_before, keep_totals=True)
+ job["phase"] = "downloading"
+ done_before += size
+ job["done_bytes"] = done_before
+
+ # Activate: same sequence as /activate's job body.
+ from hermes_cli.config import load_config, save_config
+ from hermes_cli.local_runtime.bootstrap import (
+ ensure_local_runtime,
+ refresh_local_runtime,
+ )
+
+ job["phase"] = "starting-server"
+ job["detail"] = "Starting the local server"
+ config = load_config()
+ config.setdefault("local_runtime", {})["enabled"] = True
+ save_config(config)
+ sup = ensure_local_runtime(config, force=True)
+ if sup is None and _state_endpoint() is None:
+ raise RuntimeError(
+ "The local server could not start — open Local Models for details")
+ if sup is not None:
+ try:
+ if variant.model_id not in sup.models():
+ job["detail"] = "Refreshing the local server"
+ refresh_local_runtime()
+ except Exception: # noqa: BLE001
+ logger.debug("quickstart rescan check skipped", exc_info=True)
+
+ job["phase"] = "setting-default"
+ job["detail"] = "Making it your default"
+ from hermes_cli.web_deps import late
+
+ late("_apply_model_assignment_sync")(
+ "main", "llamacpp", variant.model_id, "", "", "")
+
+ job["phase"] = "done"
+ job["status"] = "done"
+ job["detail"] = f"{entry.display_name} is ready — new chats use it"
+ except Exception as exc: # noqa: BLE001
+ logger.warning("quickstart failed: %s", exc)
+ job["status"] = "error"
+ job["error"] = str(exc)
+
+ threading.Thread(target=_run, daemon=True, name="lr-quickstart").start()
+ return {
+ "job_id": job["job_id"],
+ "model_id": entry.id,
+ "display_name": entry.display_name,
+ "needs_runtime": need_runtime,
+ "needs_download": need_download,
+ "download_bytes": sum(p[2] for p in download_plan),
+ }
+
+
@router.post("/api/local-models/server")
async def local_models_server(body: ServerActionBody):
"""Turn the local engine off (stop the server, free ALL GPU memory,
diff --git a/tests/hermes_cli/test_local_quickstart.py b/tests/hermes_cli/test_local_quickstart.py
new file mode 100644
index 00000000000..15d18b047f9
--- /dev/null
+++ b/tests/hermes_cli/test_local_quickstart.py
@@ -0,0 +1,152 @@
+"""Quickstart route: one POST from nothing to a working local default.
+
+Contract, not implementation: the route must (a) preflight-fail
+synchronously when nothing fits, (b) report which legs the job will run
+(runtime install / model download), skipping legs already satisfied,
+and (c) run install -> download -> activate through the same code paths
+the individual routes use. The slow legs are stubbed at their module
+boundaries; the sequencing and job bookkeeping are real.
+"""
+
+from __future__ import annotations
+
+import time
+from pathlib import Path
+
+import pytest
+from fastapi.testclient import TestClient
+
+
+def client(tmp_path, monkeypatch):
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))
+ from hermes_cli import web_server
+
+ test_client = TestClient(web_server.app)
+ test_client.headers[web_server._SESSION_HEADER_NAME] = web_server._SESSION_TOKEN
+ return test_client
+
+
+def _wait_job(client, job_id: str, timeout: float = 10.0) -> dict:
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ job = client.get(f"/api/local-models/jobs/{job_id}").json()
+ if job["status"] != "running":
+ return job
+ time.sleep(0.05)
+ raise AssertionError(f"job {job_id} still running after {timeout}s")
+
+
+def test_quickstart_unknown_model_404s(client):
+ r = client.post("/api/local-models/quickstart", json={"model_id": "no-such"})
+ assert r.status_code == 404
+
+
+def test_quickstart_refuses_when_nothing_fits(client, monkeypatch):
+ """Preflight is synchronous: a machine no catalog entry fits gets a 409
+ with guidance, not a doomed background job."""
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.catalog.select_variant", lambda *a, **k: None)
+ r = client.post("/api/local-models/quickstart", json={})
+ assert r.status_code == 409
+ assert "Local Models" in r.json()["detail"]
+
+
+def test_quickstart_runs_all_three_legs(client, monkeypatch, tmp_path):
+ """Fresh machine: install runtime -> download recommended -> activate.
+ Each leg is asserted by its observable call, in order."""
+ calls: list[str] = []
+
+ # Leg 1: no runtime installed yet; install is the stubbed binaries call.
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.binaries.installed_tags", lambda: [])
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.binaries.ensure_runtime_installed",
+ lambda tag, backend: calls.append("install"))
+
+ # Leg 2: nothing staged; the download writes the files the plan names.
+ def _fake_download(url, dest, job, *, base_done=0, keep_totals=False):
+ Path(dest).parent.mkdir(parents=True, exist_ok=True)
+ Path(dest).write_bytes(b"GGUF\x00")
+ calls.append("download")
+
+ monkeypatch.setattr(
+ "hermes_cli.web_routers.local_models.download_file", _fake_download)
+
+ # Leg 3: activation — stub the server start and the model assignment.
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.bootstrap.ensure_local_runtime",
+ lambda config, force=False: calls.append("server") or None)
+ monkeypatch.setattr(
+ "hermes_cli.web_routers.local_models._state_endpoint",
+ lambda: {"base_url": "http://127.0.0.1:1/v1", "api_key": "k"})
+ from hermes_cli import web_deps
+
+ monkeypatch.setattr(
+ web_deps, "late",
+ lambda name: (lambda *a, **k: calls.append("assign")))
+
+ r = client.post("/api/local-models/quickstart", json={})
+ assert r.status_code == 200
+ body = r.json()
+ assert body["needs_runtime"] is True
+ assert body["needs_download"] is True
+ assert body["download_bytes"] > 0
+
+ job = _wait_job(client, body["job_id"])
+ assert job["status"] == "done", job["error"]
+ assert job["kind"] == "quickstart"
+ # Order is the contract: engine, weights, server, default.
+ assert calls[0] == "install"
+ assert "download" in calls
+ assert calls.index("install") < calls.index("download") < calls.index("assign")
+
+ # Durable effect: the runtime is enabled in config.
+ from hermes_cli.config import load_config
+
+ assert load_config()["local_runtime"]["enabled"] is True
+
+
+def test_quickstart_skips_satisfied_legs(client, monkeypatch):
+ """Runtime present and model already staged: the response says so and
+ the job goes straight to activation."""
+ calls: list[str] = []
+
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.binaries.installed_tags", lambda: ["b10362"])
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.binaries.ensure_runtime_installed",
+ lambda tag, backend: calls.append("install"))
+
+ # Every catalog variant reads as staged.
+ from hermes_cli.local_runtime.catalog import CATALOG
+
+ all_ids = {v.model_id for e in CATALOG for v in e.variants}
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.bootstrap.staged_model_ids", lambda: all_ids)
+ monkeypatch.setattr(
+ "hermes_cli.web_routers.local_models.download_file",
+ lambda *a, **k: calls.append("download"))
+ monkeypatch.setattr(
+ "hermes_cli.local_runtime.bootstrap.ensure_local_runtime",
+ lambda config, force=False: None)
+ monkeypatch.setattr(
+ "hermes_cli.web_routers.local_models._state_endpoint",
+ lambda: {"base_url": "http://127.0.0.1:1/v1", "api_key": "k"})
+ from hermes_cli import web_deps
+
+ monkeypatch.setattr(
+ web_deps, "late",
+ lambda name: (lambda *a, **k: calls.append("assign")))
+
+ r = client.post("/api/local-models/quickstart", json={})
+ assert r.status_code == 200
+ body = r.json()
+ assert body["needs_runtime"] is False
+ assert body["needs_download"] is False
+ assert body["download_bytes"] == 0
+
+ job = _wait_job(client, body["job_id"])
+ assert job["status"] == "done", job["error"]
+ assert "install" not in calls and "download" not in calls
+ assert calls == ["assign"] or calls[-1] == "assign"