Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(llamacpp): load router.preset.ini from a non-ASCII path on Windows (#9418)

Thinh Le384c5ddab237
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
index 6aafc0f9e..8a904a4ff 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/build.rs
@@ -57,9 +57,35 @@ fn main() {
// `#[cfg(feature = ...)]` here would silently never fire.
if std::env::var_os("CARGO_FEATURE_ENGINE").is_some() {
engine::build();
+ embed_utf8_manifest();
}
}
+/// Makes the worker's narrow-string file APIs read UTF-8 instead of the ANSI
+/// code page. Upstream llama.cpp opens paths from the preset (the ini, the
+/// model, `slot-save-path`, templates) with `std::filesystem` and `ifstream`
+/// taking a `std::string`; on Windows that decodes with the ANSI code page, so
+/// any path holding a character outside it -- a Cyrillic user name is enough --
+/// reads as a file that does not exist. With this manifest the same calls
+/// decode UTF-8, which is what Jan writes. Only the worker needs it: the engine
+/// runs nowhere else. Windows before 1903 ignores the setting, which is what
+/// the shim's ini fallback is for.
+fn embed_utf8_manifest() {
+ let target_msvc = std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows")
+ && std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc");
+ if !target_msvc {
+ return;
+ }
+ let manifest = std::path::Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap())
+ .join("jan-llama-worker.manifest");
+ println!("cargo:rerun-if-changed={}", manifest.display());
+ println!("cargo:rustc-link-arg-bin=jan-llama-worker=/MANIFEST:EMBED");
+ println!(
+ "cargo:rustc-link-arg-bin=jan-llama-worker=/MANIFESTINPUT:{}",
+ manifest.display()
+ );
+}
+
mod engine {
use std::path::{Path, PathBuf};
use std::{env, fs, process::Command};
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/jan-llama-worker.manifest b/src-tauri/plugins/tauri-plugin-llamacpp/jan-llama-worker.manifest
new file mode 100644
index 000000000..f2fff698a
--- /dev/null
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/jan-llama-worker.manifest
@@ -0,0 +1,8 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
+ <application xmlns="urn:schemas-microsoft-com:asm.v3">
+ <windowsSettings>
+ <activeCodePage xmlns="http://schemas.microsoft.com/SMI/2019/WindowsSettings">UTF-8</activeCodePage>
+ </windowsSettings>
+ </application>
+</assembly>
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.cpp b/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.cpp
index f10c815eb..2725faba0 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.cpp
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/shim/jan_llama_shim.cpp
@@ -28,10 +28,104 @@
#include <thread>
#include <unordered_map>
+#ifdef _WIN32
+# ifndef WIN32_LEAN_AND_MEAN
+# define WIN32_LEAN_AND_MEAN
+# endif
+# ifndef NOMINMAX
+# define NOMINMAX
+# endif
+# include <windows.h>
+#endif
+
struct jan_llama_engine;
namespace {
+#ifdef _WIN32
+bool is_ascii(const std::wstring & s) {
+ for (wchar_t c : s) {
+ if (c >= 0x80) {
+ return false;
+ }
+ }
+ return true;
+}
+
+/// Restores the process working directory when it goes out of scope, so an
+/// exception from the loader cannot leave the engine in the wrong directory.
+struct cwd_guard {
+ std::wstring previous;
+ ~cwd_guard() {
+ SetCurrentDirectoryW(previous.c_str());
+ }
+};
+#endif
+
+/// `common_preset_context::load_from_ini` takes a narrow `std::string` and
+/// opens it with `std::filesystem::exists` and `std::ifstream`. On Windows
+/// both decode a narrow string with the ANSI code page, not UTF-8, so an ini
+/// whose path holds a non-ASCII character (a Cyrillic user name is enough)
+/// never resolves and the loader throws "preset file does not exist" for a
+/// file that is there. For such a path the process switches into the ini's
+/// directory for the duration of the load and hands upstream the bare
+/// file name, which every code page reads the same way. The directory is
+/// changed through the wide API, which does not depend on the code page; a
+/// `\\?\` prefix is dropped first because the working directory cannot be a
+/// verbatim path. The lock keeps two engine starts from interleaving their
+/// directory changes.
+///
+/// This only covers the ini. jan-llama-worker embeds a UTF-8 active-code-page
+/// manifest (build.rs), which makes every narrow path upstream opens -- model,
+/// `slot-save-path`, templates -- resolve too, so the working-directory switch
+/// is skipped when it is in effect and remains for Windows before 1903, which
+/// ignores the manifest.
+common_presets load_ini_presets(const common_preset_context & pctx, const char * ini_path, common_preset & global) {
+#ifdef _WIN32
+ static std::mutex cwd_mutex;
+
+ int wide_len = GetACP() == CP_UTF8
+ ? 0
+ : MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, ini_path, -1, nullptr, 0);
+ if (wide_len > 1) {
+ std::wstring wide(static_cast<size_t>(wide_len), L'\0');
+ MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, ini_path, -1, wide.data(), wide_len);
+ wide.resize(static_cast<size_t>(wide_len) - 1);
+
+ if (!is_ascii(wide)) {
+ if (wide.rfind(L"\\\\?\\UNC\\", 0) == 0) {
+ wide = L"\\\\" + wide.substr(8);
+ } else if (wide.rfind(L"\\\\?\\", 0) == 0) {
+ wide = wide.substr(4);
+ }
+
+ size_t sep = wide.find_last_of(L"\\/");
+ if (sep != std::wstring::npos && sep > 0) {
+ std::wstring dir = wide.substr(0, sep);
+ std::wstring file = wide.substr(sep + 1);
+ if (dir.size() == 2 && dir[1] == L':') {
+ dir += L'\\'; // "C:" alone means "the current directory on C:"
+ }
+ if (!file.empty() && is_ascii(file)) {
+ std::lock_guard<std::mutex> lock(cwd_mutex);
+ DWORD need = GetCurrentDirectoryW(0, nullptr);
+ if (need > 0) {
+ cwd_guard guard;
+ guard.previous.resize(need);
+ DWORD got = GetCurrentDirectoryW(need, guard.previous.data());
+ guard.previous.resize(got);
+ if (got > 0 && SetCurrentDirectoryW(dir.c_str())) {
+ return pctx.load_from_ini(std::string(file.begin(), file.end()), global);
+ }
+ }
+ }
+ }
+ }
+ }
+#endif
+ return pctx.load_from_ini(ini_path, global);
+}
+
/// Mirrors upstream's `ex_wrapper` (tools/server/server.cpp), which every route
/// is registered behind. `build_table` captures the *unwrapped* handler members,
/// so the two things that wrapper does have to be done here instead: map
@@ -356,7 +450,7 @@ jan_llama_engine * jan_llama_engine_start_from_preset(const char * ini_pat
engine->params = pctx.default_params;
common_preset global;
- common_presets presets = pctx.load_from_ini(ini_path, global);
+ common_presets presets = load_ini_presets(pctx, ini_path, global);
auto it = presets.find(preset_name);
if (it == presets.end()) {