Skip to content

Commit c69c5f7

Browse files
committed
fix(cookbook): harden local llama-server launch commands
1 parent 3df0eab commit c69c5f7

6 files changed

Lines changed: 81 additions & 17 deletions

File tree

routes/cookbook_routes.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1386,6 +1386,10 @@ async def model_serve(request: Request, req: ServeRequest):
13861386
# shell resolves the bundled python3/hf, mirroring the download flow.
13871387
if not remote:
13881388
runner_lines.append(_local_tooling_path_export(sys.executable))
1389+
if local_windows:
1390+
# Detached Git Bash runs do not always inherit recently edited
1391+
# user PATH entries from the already-running Odysseus process.
1392+
runner_lines.append('export PATH="$HOME/bin:$HOME/llama.cpp/build-cuda/bin/Release:$HOME/llama.cpp/build/bin/Release:$HOME/llama.cpp/build/bin/Debug:$HOME/llama.cpp/build/bin:$PATH"')
13891393
runner_lines.append("export FLASHINFER_DISABLE_VERSION_CHECK=1")
13901394
if req.hf_token:
13911395
runner_lines.append(f"export HF_TOKEN='{_bash_squote(req.hf_token)}'")

static/js/cookbook.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2111,14 +2111,14 @@ function _renderRecipes() {
21112111
const isLocal = !s.host || s.host.toLowerCase() === 'local';
21122112
if (isLocal) {
21132113
s.host = '';
2114-
s.platform = _envState.hostPlatform || _envState.platform || '';
2114+
s.platform = _envState.hostPlatform || '';
21152115
if (_localSeen) return false;
21162116
_localSeen = true;
21172117
}
21182118
return true;
21192119
});
21202120
if (!_localSeen) {
2121-
_es.servers.unshift({ host: '', env: _es.env || 'none', envPath: _es.envPath || '', modelDir: '~/.cache/huggingface/hub', platform: _envState.hostPlatform || _envState.platform || '' });
2121+
_es.servers.unshift({ host: '', env: _es.env || 'none', envPath: _es.envPath || '', modelDir: '~/.cache/huggingface/hub', platform: _envState.hostPlatform || '' });
21222122
}
21232123
if (_es.remoteHost && !_es.servers.some(s => s.host === _es.remoteHost)) {
21242124
_es.servers.push({ host: _es.remoteHost, env: _es.env || 'none', envPath: _es.envPath || '', modelDir: '~/.cache/huggingface/hub' });

static/js/cookbookRunning.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1522,7 +1522,7 @@ export async function _launchServeTask(shortName, repo, cmd, fields, hostOverrid
15221522
const _host = (hostOverride !== undefined) ? (hostOverride || '') : (_envState.remoteHost || '');
15231523
const _hsrv = _serverByVal(_envState.remoteServerKey || _host)
15241524
|| _envState.servers.find(s => s.host === _host) || {};
1525-
const _hplatform = _host ? (_hsrv.platform || '') : (_envState.platform || '');
1525+
const _hplatform = _host ? (_hsrv.platform || '') : (_envState.hostPlatform || '');
15261526

15271527
// Replace any serve already targeting this same host:port — you can't run two
15281528
// servers on one port, so re-serving (or retrying) should stop & remove the

static/js/cookbookServe.js

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ function _selectedServeTarget(panel) {
119119
port: host ? (server?.port || _getPort(host) || '') : '',
120120
env: server?.env || '',
121121
venv,
122-
platform: server?.platform || _envState.platform || '',
122+
platform: host ? (server?.platform || '') : (_envState.hostPlatform || ''),
123123
label,
124124
};
125125
}
@@ -240,6 +240,12 @@ function _runnableGgufFiles(model) {
240240
return primary.length ? primary : files;
241241
}
242242

243+
function _projectorGgufFiles(model) {
244+
return _ggufFilesForModel(model)
245+
.filter(f => (f.role || '') === 'projector' || /(^|\/)mmproj[^/]*\.gguf$/i.test(f.rel_path || f.name || ''))
246+
.sort((a, b) => String(a.rel_path || a.name || '').localeCompare(String(b.rel_path || b.name || '')));
247+
}
248+
243249
function _ggufFileLabel(file) {
244250
const base = (file.name || file.rel_path || '').split('/').pop();
245251
const size = _formatGgufSize(file.size_bytes);
@@ -621,6 +627,7 @@ function _rerenderCachedModels() {
621627
: `This model's download isn't complete yet (${esc(m.size || 'partial')}). The serve will start but is likely to crash on a missing shard. Wait for the download to finish, or relaunch after it's done.`;
622628
panelHtml += `<div class="hwfit-serve-warn" style="margin:0 0 8px;padding:6px 10px;border-radius:5px;font-size:11px;background:color-mix(in srgb, var(--color-warning, #f0ad4e) 14%, transparent);border:1px solid color-mix(in srgb, var(--color-warning, #f0ad4e) 40%, transparent);color:var(--color-warning, #f0ad4e);display:flex;gap:6px;align-items:flex-start;line-height:1.4;"><span aria-hidden="true">⚠</span><span>${_warnText}</span></div>`;
623629
}
630+
panelHtml += `<div class="hwfit-serve-vision-warn" style="display:none;margin:0 0 8px;padding:6px 10px;border-radius:5px;font-size:11px;background:color-mix(in srgb, var(--color-warning, #f0ad4e) 14%, transparent);border:1px solid color-mix(in srgb, var(--color-warning, #f0ad4e) 40%, transparent);color:var(--color-warning, #f0ad4e);gap:6px;align-items:flex-start;line-height:1.4;"><span aria-hidden="true">⚠</span><span>Vision is enabled, but no mmproj GGUF projector was found in the cached model scan. Download an mmproj-*.gguf for this model, then refresh the cached model list before launching.</span></div>`;
624631
// Row 1: Backend + Server + Env
625632
panelHtml += `<div class="hwfit-serve-row">`;
626633
const backendOpts = _backendChoices.map(([v,l]) => `<option value="${v}"${defaultBackend===v?' selected':''}>${l}</option>`).join('');
@@ -896,18 +903,22 @@ function _rerenderCachedModels() {
896903
: m.is_local_dir && m.path
897904
? `$({ find ${_ldir} -name '*-00001-of-*.gguf' 2>/dev/null | sort; find ${_ldir} -name '*.gguf' 2>/dev/null | sort; } | head -1)`
898905
: `$({ find ${dir} -name '*-00001-of-*.gguf' 2>/dev/null | sort; find ${dir} -name '*.gguf' 2>/dev/null | sort; } | head -1)`;
899-
// Vision: auto-find the mmproj (CLIP/projector) file in the same dir.
900-
// Resolved at runtime so the toggle just works if an mmproj-*.gguf is
901-
// present (downloaded alongside the model). Empty if none → cmd omits it.
902-
const _vsearchdir = (m.is_local_dir && m.path) ? _ldir : dir;
903-
f._mmproj_path = `$(find ${_vsearchdir} -iname 'mmproj*.gguf' 2>/dev/null | sort | head -1)`;
906+
// Vision: use the scanned projector (CLIP/mmproj) file when present.
907+
// Keeping this as a printf path avoids generating a command substitution
908+
// that the backend serve-command validator must reject as unsafe.
909+
const selectedProjector = _projectorGgufFiles(m)[0];
910+
f._mmproj_path = selectedProjector ? _selectedGgufExpr(m, repo, selectedProjector.rel_path) : '';
904911
}
905912
if (f.reasoning_parser) {
906913
const _rpEl2 = panel.querySelector('[data-field="reasoning_parser"]');
907914
f._reasoning_parser_value = _rpEl2?.dataset?.parser || 'qwen3';
908915
}
909916
let cmd = _buildServeCmd(f, serveModel, backend);
910917
if (f.extra && f.extra.trim()) cmd += ' ' + f.extra.trim();
918+
const missingVisionProjector = backend === 'llamacpp' && !!f.vision && !f._mmproj_path;
919+
panel._visionMissingProjector = missingVisionProjector;
920+
const _visionWarn = panel.querySelector('.hwfit-serve-vision-warn');
921+
if (_visionWarn) _visionWarn.style.display = missingVisionProjector ? 'flex' : 'none';
911922
const _ce2 = panel.querySelector('.hwfit-serve-cmd'); _ce2.value = cmd; _ce2.style.height = 'auto'; _ce2.style.height = _ce2.scrollHeight + 'px';
912923
panel._cmd = cmd;
913924
panel._host = f.host || '';
@@ -1982,12 +1993,16 @@ function _rerenderCachedModels() {
19821993
});
19831994
serveState.backend = serveState.backend || (_detectBackend(m).backend) || 'vllm';
19841995
const launchTarget = _selectedServeTarget(panel);
1996+
if (serveState.backend === 'llamacpp' && serveState.vision && !/(?:^|\s)(?:--mmproj|--clip_model_path)\b/.test(launchCmd)) {
1997+
_restoreLaunchBtn();
1998+
uiModule.showToast('Vision is checked, but no mmproj projector is in the launch command. Refresh cached models after downloading mmproj, or add --mmproj manually.', 8000);
1999+
return;
2000+
}
19852001
if (serveState.backend === 'diffusers' && _remoteWindowsDiffusersUnsupported(launchTarget)) {
19862002
_restoreLaunchBtn();
19872003
uiModule.showToast('Diffusers serving is not supported on remote Windows servers yet. Use local Windows or a Linux server.', 9000);
19882004
return;
19892005
}
1990-
19912006
// Pre-launch: check our own task list for a serve already running
19922007
// on this host. Offer to stop+launch as the default action — the
19932008
// SSH-based port probe below is more thorough but it can miss

tests/test_cookbook_cpu_only_serve.py

Lines changed: 39 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,13 +67,27 @@ def test_local_windows_platform_comes_from_backend_host_state():
6767
assert "hostOrTask === 'local'" in text
6868
assert "if (hostOrTask === 'local') return _envState.hostPlatform || '';" in text
6969
assert "return _envState.hostPlatform || _envState.platform || ''" not in text
70+
assert "s.platform = _envState.hostPlatform || '';" in text
71+
assert "platform: _envState.hostPlatform || ''" in text
72+
assert "s.platform = _envState.hostPlatform || _envState.platform || '';" not in text
73+
assert "platform: _envState.hostPlatform || _envState.platform || ''" not in text
7074
assert 'return "windows" if IS_WINDOWS else ""' in routes
7175
assert 'env["hostPlatform"] = _client_host_platform()' in routes
7276
assert "return _state_for_client({})" in routes
7377
assert 'env.pop("hostPlatform", None)' in routes
7478
assert "delete env.hostPlatform;" in running
7579

7680

81+
def test_local_serve_payload_ignores_stale_env_platform():
82+
serve = SERVE_SRC.read_text(encoding="utf-8")
83+
running = (SRC.parent / "cookbookRunning.js").read_text(encoding="utf-8")
84+
85+
assert "platform: host ? (server?.platform || '') : (_envState.hostPlatform || '')," in serve
86+
assert "platform: server?.platform || _envState.platform || ''" not in serve
87+
assert "const _hplatform = _host ? (_hsrv.platform || '') : (_envState.hostPlatform || '');" in running
88+
assert "const _hplatform = _host ? (_hsrv.platform || '') : (_envState.platform || '');" not in running
89+
90+
7791
def test_local_windows_llamacpp_prefers_native_llama_server():
7892
text = SRC.read_text(encoding="utf-8")
7993
helpers = (ROOT / "routes/cookbook_helpers.py").read_text(encoding="utf-8")
@@ -90,4 +104,28 @@ def test_local_windows_llama_server_skips_source_bootstrap():
90104
routes = (ROOT / "routes/cookbook_routes.py").read_text(encoding="utf-8")
91105

92106
assert 'local_windows_llama_cmd = local_windows and ("llama_cpp" in req.cmd or "llama-server" in req.cmd)' in routes
93-
assert 'if ("llama_cpp" in req.cmd or "llama-server" in req.cmd) and not local_windows_llama_cmd:' in routes
107+
assert 'if ("llama_cpp" in req.cmd or "llama-server" in req.cmd) and not local_windows_llama_cmd:' in routes
108+
109+
110+
def test_local_windows_llama_server_path_includes_user_wrapper_and_cuda_builds():
111+
routes = (ROOT / "routes/cookbook_routes.py").read_text(encoding="utf-8")
112+
113+
assert 'if local_windows:' in routes
114+
assert (
115+
'export PATH="$HOME/bin:$HOME/llama.cpp/build-cuda/bin/Release:'
116+
'$HOME/llama.cpp/build/bin/Release:$HOME/llama.cpp/build/bin/Debug:'
117+
'$HOME/llama.cpp/build/bin:$PATH"'
118+
) in routes
119+
120+
121+
def test_llamacpp_vision_uses_scanned_projector_instead_of_runtime_find():
122+
text = SERVE_SRC.read_text(encoding="utf-8")
123+
124+
assert "function _projectorGgufFiles(model)" in text
125+
assert "const selectedProjector = _projectorGgufFiles(m)[0];" in text
126+
assert "f._mmproj_path = selectedProjector ? _selectedGgufExpr(m, repo, selectedProjector.rel_path) : '';" in text
127+
assert "const missingVisionProjector = backend === 'llamacpp' && !!f.vision && !f._mmproj_path;" in text
128+
assert "hwfit-serve-vision-warn" in text
129+
assert "!/(?:^|\\s)(?:--mmproj|--clip_model_path)\\b/.test(launchCmd)" in text
130+
assert "no mmproj projector is in the launch command" in text
131+
assert "find ${_vsearchdir} -iname 'mmproj*.gguf'" not in text

tests/test_cookbook_helpers.py

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -419,8 +419,6 @@ def test_pip_install_attempt_failure_propagates_real_exit_code():
419419
"""Run the generated snippet against a deliberately broken pip install
420420
to confirm the subshell exits with pip's non-zero status."""
421421
snippet = _pip_install_attempt("python3 -m pip install __nonexistent_package_12345__")
422-
if sys.platform == "win32":
423-
snippet = snippet.replace("$", "\\$")
424422
result = subprocess.run(
425423
["bash", "-c", snippet],
426424
capture_output=True,
@@ -433,8 +431,6 @@ def test_pip_install_attempt_failure_propagates_real_exit_code():
433431
def test_pip_install_attempt_success_exits_zero():
434432
"""When pip succeeds, the subshell should exit 0."""
435433
snippet = _pip_install_attempt("python3 -c 'pass'")
436-
if sys.platform == "win32":
437-
snippet = snippet.replace("$", "\\$")
438434
result = subprocess.run(
439435
["bash", "-c", snippet],
440436
capture_output=True,
@@ -447,8 +443,6 @@ def test_pip_install_attempt_success_exits_zero():
447443
def test_pip_install_attempt_surfaces_stderr_on_failure():
448444
"""On failure, the last 5 lines of pip output should appear in stdout."""
449445
snippet = _pip_install_attempt("python3 -m pip install __nonexistent_package_12345__")
450-
if sys.platform == "win32":
451-
snippet = snippet.replace("$", "\\$")
452446
result = subprocess.run(
453447
["bash", "-c", snippet],
454448
capture_output=True,
@@ -557,6 +551,19 @@ def test_validate_serve_cmd_accepts_windows_printf_format():
557551
assert _validate_serve_cmd(cmd) == cmd
558552

559553

554+
def test_validate_serve_cmd_accepts_llama_mmproj_printf_format():
555+
cmd = (
556+
"CUDA_VISIBLE_DEVICES=0 llama-server --model "
557+
"\"$(printf %s ${HOME}'/.cache/huggingface/hub/models--unsloth--Qwen3.6-35B-A3B-GGUF/snapshots/abc/Qwen3.6-35B-A3B-UD-Q4_K_M.gguf')\" "
558+
"--host 0.0.0.0 --port 8000 -ngl 99 -c 20000 "
559+
"--cache-type-k q4_0 --cache-type-v q4_0 --mmproj "
560+
"\"$(printf %s ${HOME}'/.cache/huggingface/hub/models--unsloth--Qwen3.6-35B-A3B-GGUF/snapshots/abc/mmproj-BF16.gguf')\" "
561+
"--image-max-tokens 1024"
562+
)
563+
564+
assert _validate_serve_cmd(cmd) == cmd
565+
566+
560567
def test_normalize_llama_cpp_python_cache_types_for_stale_client_cmd():
561568
cmd = (
562569
"python -m llama_cpp.server --model model.gguf --host 0.0.0.0 --port 8000 "

0 commit comments

Comments
 (0)