Skip to content

The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.

fix(isolation): der Experiment-Build hat ein eigenes Datenverzeichnis

David1936b84e1d47
diff --git a/scripts/app-identity.mjs b/scripts/app-identity.mjs
new file mode 100644
index 00000000..8f353cb3
--- /dev/null
+++ b/scripts/app-identity.mjs
@@ -0,0 +1,34 @@
+/**
+ * Verzeichnisnamen dieses Builds für die Node-Skripte (Smoke-Harnesse).
+ *
+ * Kein dritter Ort mit denselben Strings: die Namen werden aus
+ * `src/lib/app-identity.ts` GELESEN, das seinerseits gegen
+ * `src-tauri/src/app_identity.rs` getestet wird
+ * (`src/lib/__tests__/app-identity.test.ts`).
+ *
+ * Hintergrund: dieser Branch (`experiment/audits-komplett`) hat bewusst eigene
+ * Datenverzeichnisse, weil der Experiment-Build am 2026-08-31 in das
+ * Verzeichnis der ECHTEN App geschrieben hat. Die Zusicherungen in den
+ * Smoke-Skripten ("der Pfad liegt NICHT im Standard-Sandkasten") wären mit
+ * einem fest verdrahteten `agent-workspace` still immer erfüllt und würden
+ * nichts mehr fangen.
+ */
+
+import { readFileSync } from 'node:fs'
+import { fileURLToPath } from 'node:url'
+import { dirname, resolve } from 'node:path'
+
+const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), '..')
+const src = readFileSync(resolve(repoRoot, 'src/lib/app-identity.ts'), 'utf8')
+
+function readConst(name) {
+ const m = new RegExp(`export const ${name} = '([^']+)'`).exec(src)
+ if (!m) throw new Error(`${name} nicht in src/lib/app-identity.ts gefunden`)
+ return m[1]
+}
+
+/** Sandkasten-Wurzel der Agenten unter `$HOME` (ohne Home-Präfix). */
+export const AGENT_WORKSPACE_DIR = readConst('AGENT_WORKSPACE_DIR')
+
+/** Der Ordner, in den ein Remote-Aufruf OHNE gewählten Projektordner fiele. */
+export const REMOTE_FALLBACK_DIR = `${AGENT_WORKSPACE_DIR}/__remote__`
diff --git a/scripts/remote-all-tools-e2e.mjs b/scripts/remote-all-tools-e2e.mjs
index bccd2360..733f8f1f 100644
--- a/scripts/remote-all-tools-e2e.mjs
+++ b/scripts/remote-all-tools-e2e.mjs
@@ -16,6 +16,9 @@
*/
import { argv, exit } from 'node:process'
+// Siehe scripts/app-identity.mjs — der Sandkasten-Name trägt auf diesem Branch
+// einen Suffix, ein festes Literal würde hier nichts mehr fangen.
+import { REMOTE_FALLBACK_DIR } from './app-identity.mjs'
function parseArgs() {
const out = { base: null, code: null, chatId: 'all-tools-e2e' }
@@ -55,7 +58,7 @@ function check(label, ok, detail) {
else { console.error(` ✗ ${label}\n ${detail}`); fail++ }
}
-const NOT_REMOTE = (s) => !String(s || '').replaceAll('\\', '/').includes('agent-workspace/__remote__')
+const NOT_REMOTE = (s) => !String(s || '').replaceAll('\\', '/').includes(REMOTE_FALLBACK_DIR)
async function step(label, fn) {
console.log(`\n━━ ${label} ━━`)
diff --git a/scripts/remote-smoke.mjs b/scripts/remote-smoke.mjs
index 6815cf91..a25cba7f 100644
--- a/scripts/remote-smoke.mjs
+++ b/scripts/remote-smoke.mjs
@@ -26,6 +26,10 @@
import { argv, exit } from 'node:process'
import { join } from 'node:path'
+// Der Sandkasten-Name kommt aus app-identity. Dieser Branch hängt einen Suffix
+// an; eine fest verdrahtete Zusicherung wäre danach immer erfüllt und würde
+// eine echte Regression nicht mehr fangen.
+import { REMOTE_FALLBACK_DIR } from './app-identity.mjs'
function parseArgs() {
const out = { base: null, code: null, chatId: 'remote-smoke' }
@@ -109,7 +113,7 @@ async function main() {
const writePath = writeRes?.path || ''
console.log(` wrote to: ${writePath}`)
check('file_write path is NOT ~/agent-workspace/__remote__/',
- !writePath.replaceAll('\\', '/').includes('agent-workspace/__remote__/'),
+ !writePath.replaceAll('\\', '/').includes(REMOTE_FALLBACK_DIR + '/'),
`path was ${writePath} — bug 1 still present`)
// 2) file_list — same relative folder. Should return one entry (hello.txt).
@@ -156,7 +160,7 @@ async function main() {
if (typeof shellRes?.stdout === 'string') {
console.log(` cwd seen by shell: ${shellRes.stdout.trim()}`)
check('shell_execute cwd is NOT ~/agent-workspace/__remote__/',
- !shellRes.stdout.replaceAll('\\', '/').includes('agent-workspace/__remote__'),
+ !shellRes.stdout.replaceAll('\\', '/').includes(REMOTE_FALLBACK_DIR),
`stdout was ${shellRes.stdout}`)
}
@@ -170,7 +174,7 @@ async function main() {
console.log(` cwd: ${shellRel.stdout.trim()}`)
check('shell_execute resolved relative cwd into override folder',
shellRel.stdout.includes('remote-smoke') &&
- !shellRel.stdout.replaceAll('\\', '/').includes('agent-workspace/__remote__'),
+ !shellRel.stdout.replaceAll('\\', '/').includes(REMOTE_FALLBACK_DIR),
`stdout was ${shellRel.stdout}`)
} else {
check('shell_execute (relative cwd) returned stdout', false, JSON.stringify(shellRel))
@@ -194,7 +198,7 @@ async function main() {
check('file_search found the marker we just wrote', !!hit,
JSON.stringify(searchRes?.results))
check('file_search hit file path is NOT under agent-workspace/__remote__/',
- hit ? !String(hit.file).replaceAll('\\', '/').includes('agent-workspace/__remote__') : false,
+ hit ? !String(hit.file).replaceAll('\\', '/').includes(REMOTE_FALLBACK_DIR) : false,
`hit was ${JSON.stringify(hit)}`)
// 8) file_list with recursive=true → should include both files we wrote
@@ -228,7 +232,7 @@ async function main() {
if (typeof pyRes?.stdout === 'string') {
console.log(` python cwd: ${pyRes.stdout.trim()}`)
check('code_execute cwd is NOT ~/agent-workspace/__remote__/',
- !pyRes.stdout.replaceAll('\\', '/').includes('agent-workspace/__remote__'),
+ !pyRes.stdout.replaceAll('\\', '/').includes(REMOTE_FALLBACK_DIR),
`stdout was ${pyRes.stdout}`)
}
// Confirm via file_read that python's relative write landed in the override
@@ -281,7 +285,7 @@ async function main() {
JSON.stringify(deep))
check('deep file_write path is NOT under agent-workspace/__remote__/',
typeof deep?.path === 'string' &&
- !deep.path.replaceAll('\\', '/').includes('agent-workspace/__remote__'),
+ !deep.path.replaceAll('\\', '/').includes(REMOTE_FALLBACK_DIR),
`path was ${deep?.path}`)
// 14) Wrong-arg shape → should come back as a clean {error} (graceful 200),
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 55ccc85a..021e46bc 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -2542,7 +2542,22 @@ dependencies = [
]
[[package]]
-name = "locally-uncensored"
+name = "lock_api"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
+dependencies = [
+ "scopeguard",
+]
+
+[[package]]
+name = "log"
+version = "0.4.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
+
+[[package]]
+name = "lu-experiment"
version = "2.6.7"
dependencies = [
"axum",
@@ -2592,21 +2607,6 @@ dependencies = [
"zip 2.4.2",
]
-[[package]]
-name = "lock_api"
-version = "0.4.14"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
-dependencies = [
- "scopeguard",
-]
-
-[[package]]
-name = "log"
-version = "0.4.29"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
-
[[package]]
name = "lzma-rs"
version = "0.3.0"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 3c28951c..cb57b2d4 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,5 +1,28 @@
[package]
-name = "locally-uncensored"
+# ACHTUNG, Branch `experiment/audits-komplett`: der Paketname ist hier BEWUSST
+# nicht `locally-uncensored`.
+#
+# Unter macOS bestimmt im `tauri dev`-Modus der Name der laufenden Datei das
+# WebKit-Verzeichnis: ein nicht gebündeltes Programm hat keine Bundle-ID
+# (`[[NSBundle mainBundle] bundleIdentifier]` ist nil), also fällt WebKit auf
+# `[[NSProcessInfo processInfo] processName]` zurück — den Dateinamen der
+# ausführbaren Datei — und legt localStorage/IndexedDB unter
+# `~/Library/WebKit/<Dateiname>/` ab. `cargo run` benennt die Datei nach
+# diesem Feld.
+#
+# Mit `locally-uncensored` teilte der Experiment-Build deshalb
+# `~/Library/WebKit/locally-uncensored/` mit JEDEM `npm run tauri dev` aus dem
+# echten Repo — inklusive `chat-conversations` und `lu-providers`. Genau von
+# dort stammt der `lu-cloud: false`-Zustand, der am 2026-08-31 in das
+# Store-Backup der echten App geschrieben wurde.
+#
+# Die `identifier` in `tauri.conf.json` hilft hier nicht: sie landet nur in
+# der Info.plist eines GEBÜNDELTEN Builds. `bundle.mainBinaryName` hilft
+# ebenfalls nicht — laut tauri-utils benennt tauri-cli die Datei erst in
+# `tauri build` um, nicht in `tauri dev`.
+#
+# In der echten App gehört hier `locally-uncensored` hin.
+name = "lu-experiment"
version = "2.6.7"
description = "Private, local AI chat & image/video generation"
authors = ["purpledoubled"]
diff --git a/src-tauri/src/app_identity.rs b/src-tauri/src/app_identity.rs
new file mode 100644
index 00000000..6ce4d989
--- /dev/null
+++ b/src-tauri/src/app_identity.rs
@@ -0,0 +1,311 @@
+//! Die Namen der app-eigenen Verzeichnisse — an EINER Stelle.
+//!
+//! ## Warum es diese Datei gibt
+//!
+//! Dieser Branch (`experiment/audits-komplett`) hat **bewusst ein eigenes
+//! Datenverzeichnis** und teilt nichts mit der installierten echten App.
+//!
+//! Am 2026-08-31 hat der erste echte Start des Experiment-Builds
+//! (`npm run tauri dev`) in `~/Library/Application Support/lu-labs/`
+//! geschrieben — dem Datenverzeichnis der ECHTEN App. Dabei wurde
+//! `stores/store_backup.json` überschrieben und `lu-providers` auf einen
+//! Zustand aus einem fremden Lauf zurückgesetzt (`lu-cloud` von `enabled:
+//! true` auf `false`). Dass die 6,7 MB echter Chats überlebt haben, lag
+//! allein an der Merge-Rettung in `commands::system` (`keys_lost` /
+//! `merged_backup`) — das ist ein Sicherheitsnetz, keine Isolation.
+//!
+//! Die Ursache: der Verzeichnisname wird auf der Rust-Seite **nicht** aus der
+//! Tauri-`identifier` abgeleitet, sondern war als String an acht Stellen
+//! hartkodiert. Ein eigener `identifier` in `tauri.conf.json` trennt daher
+//! WebView-Speicher und Single-Instance-Socket, aber eben nicht die Pfade, die
+//! sich aus `dirs::*` und einem angehängten Literal zusammensetzen.
+//!
+//! ## Wie es jetzt läuft
+//!
+//! [`branch_dir_suffix!`] ist der einzige Schalter. Er hängt an jeden Namen,
+//! den diese App auf der Platte (und im Schlüsselbund) besitzt. Für die
+//! **echte App gehört hier `""` hin** — `lu-labs`, `locally-uncensored`,
+//! `Locally Uncensored` und `agent-workspace` sind dort die richtigen Namen
+//! und dürfen sich nicht ändern. Nur dieser Branch setzt einen Suffix.
+//!
+//! Wer den Suffix auf `""` zurückdreht, fällt in
+//! [`tests::keiner_der_namen_ist_der_name_der_echten_app`] und
+//! [`tests::kein_abgeleiteter_pfad_zeigt_in_ein_verzeichnis_der_echten_app`]
+//! durch. Das ist Absicht.
+//!
+//! ## Was hier NICHT drin steht
+//!
+//! * Die Tauri-`identifier` (`tauri.conf.json`) — sie steuert
+//! `app_data_dir()`/`app_config_dir()`, den Single-Instance-Socket und den
+//! WebView-Speicher **gebündelter** Builds; die ist bereits getrennt.
+//! * Der Binärname (`Cargo.toml`, `[package] name`) — er steuert unter macOS
+//! im `tauri dev`-Modus das WebKit-Verzeichnis (`~/Library/WebKit/<Name>`).
+//! Die ausführliche Begründung steht als Kommentar in `Cargo.toml`;
+//! festgenagelt wird er von
+//! [`tests::der_binaername_ist_nicht_der_der_echten_app`].
+
+/// **Der einzige Schalter.** Suffix an jedem app-eigenen Verzeichnisnamen.
+///
+/// * Echte App / upstream: `""`
+/// * Branch `experiment/audits-komplett`: `"-experiment"`
+///
+/// Ein Makro (und nicht eine `const`), weil `concat!` nur Literale
+/// zusammensetzen kann — so bleibt jeder Name unten eine echte
+/// Compile-Zeit-Konstante statt eines `format!` zur Laufzeit.
+macro_rules! branch_dir_suffix {
+ () => {
+ "-experiment"
+ };
+}
+
+/// Haupt-Datenverzeichnis dieser App unter `data_local_dir()`, `cache_dir()`
+/// und `config_dir()`.
+///
+/// * macOS: `~/Library/Application Support/<APP_DIR>`
+/// * Windows: `%LOCALAPPDATA%\<APP_DIR>`
+/// * Linux: `~/.local/share/<APP_DIR>`, `~/.cache/<APP_DIR>`,
+/// `~/.config/<APP_DIR>`
+pub const APP_DIR: &str = concat!("lu-labs", branch_dir_suffix!());
+
+/// Älterer Ordner unter `config_dir()` bzw. `data_local_dir()`: hält
+/// `config.json` (ComfyUI-Pfad/-Port, Ollama-Basis, Trainer-Root) und
+/// `bin/cloudflared`.
+pub const APP_CONFIG_DIR: &str = concat!("locally-uncensored", branch_dir_suffix!());
+
+/// Die Anzeige-Schreibweise desselben Namens. Zwei Verwendungen:
+/// `%APPDATA%\<APP_DISPLAY_DIR>` (Store-Backups + Onboarding-Marker, Windows)
+/// und `<data_dir>/<APP_DISPLAY_DIR>/models` (Modelle der eingebauten Engine).
+pub const APP_DISPLAY_DIR: &str = concat!("Locally Uncensored", branch_dir_suffix!());
+
+/// Sandkasten-Wurzel der Agenten unter `$HOME`. Pro Chat entsteht darin ein
+/// Unterordner; der Agent darf nichts außerhalb anfassen.
+pub const AGENT_WORKSPACE_DIR: &str = concat!("agent-workspace", branch_dir_suffix!());
+
+/// Service-Name im OS-Schlüsselbund (macOS Keychain / Windows Credential
+/// Manager) für Provider-Schlüssel und die Cloud-Sitzung.
+///
+/// Gehört hierher, obwohl es kein Pfad ist: der Name war ebenfalls
+/// hartkodiert, und ohne Suffix läse und **überschriebe** der
+/// Experiment-Build die echten API-Schlüssel des Nutzers. In der echten App
+/// muss er stabil bleiben — ein geänderter Service-Name verwaist die dort
+/// gespeicherten Schlüssel.
+pub const KEYCHAIN_SERVICE: &str =
+ concat!("com.locallyuncensored.providerkeys", branch_dir_suffix!());
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::path::{Component, Path};
+
+ /// Die Namen, die der ECHTEN App gehören.
+ ///
+ /// Bewusst als eigene Literale wiederholt und **nicht** aus den
+ /// Konstanten oben abgeleitet: ein Test, der seine Erwartung aus dem
+ /// prüft, was er absichern soll, prüft nichts.
+ const NAMEN_DER_ECHTEN_APP: [&str; 4] = [
+ "lu-labs",
+ "locally-uncensored",
+ "Locally Uncensored",
+ "agent-workspace",
+ ];
+
+ /// Mutationsprobe: `branch_dir_suffix!()` auf `""` zurückdrehen lässt
+ /// genau diesen Test rot werden.
+ #[test]
+ fn keiner_der_namen_ist_der_name_der_echten_app() {
+ for name in [
+ APP_DIR,
+ APP_CONFIG_DIR,
+ APP_DISPLAY_DIR,
+ AGENT_WORKSPACE_DIR,
+ ] {
+ assert!(
+ !NAMEN_DER_ECHTEN_APP.contains(&name),
+ "'{name}' ist der Verzeichnisname der ECHTEN App — dieser Build \
+ würde in die Daten des Nutzers schreiben. branch_dir_suffix!() prüfen."
+ );
+ }
+ assert_ne!(
+ KEYCHAIN_SERVICE, "com.locallyuncensored.providerkeys",
+ "der Experiment-Build teilte sonst den Schlüsselbund-Eintrag der echten App"
+ );
+ }
+
+ /// Der WebView-Speicher hängt unter macOS im `tauri dev`-Modus NICHT an
+ /// der Tauri-`identifier`, sondern am Namen der laufenden Datei: ein nicht
+ /// gebündeltes Programm hat keine Bundle-ID, also nimmt WebKit
+ /// `processName` (= Dateiname) und legt localStorage/IndexedDB unter
+ /// `~/Library/WebKit/<Dateiname>/` ab. `cargo run` benennt die Datei nach
+ /// `[package] name`.
+ ///
+ /// Solange der `locally-uncensored` hieß, teilte dieser Build denselben
+ /// localStorage mit jedem `tauri dev` aus dem echten Repo. Deshalb steht
+ /// der Name hier unter Test — er ist Isolation, nicht Kosmetik.
+ #[test]
+ fn der_binaername_ist_nicht_der_der_echten_app() {
+ assert_ne!(
+ env!("CARGO_PKG_NAME"),
+ "locally-uncensored",
+ "der Dateiname der ausführbaren Datei bestimmt unter macOS das \
+ WebKit-Verzeichnis im dev-Modus — mit diesem Namen teilt der \
+ Experiment-Build localStorage mit dem echten Repo"
+ );
+ if let Some(bin) = option_env!("CARGO_BIN_NAME") {
+ assert_ne!(bin, "locally-uncensored");
+ }
+ }
+
+ /// Der Suffix muss auch wirklich trennen und nicht nur anders aussehen.
+ #[test]
+ fn suffix_ist_nicht_leer_und_haengt_an_jedem_namen() {
+ let suffix = branch_dir_suffix!();
+ assert!(!suffix.is_empty(), "ohne Suffix gibt es keine Trennung");
+ for name in [
+ APP_DIR,
+ APP_CONFIG_DIR,
+ APP_DISPLAY_DIR,
+ AGENT_WORKSPACE_DIR,
+ KEYCHAIN_SERVICE,
+ ] {
+ assert!(
+ name.ends_with(suffix),
+ "'{name}' trägt den Branch-Suffix nicht"
+ );
+ }
+ }
+
+ /// Ein Pfadbestandteil, der einem Verzeichnis der echten App entspricht.
+ ///
+ /// Verglichen wird **komponentenweise und exakt**, nicht mit `starts_with`
+ /// auf dem ganzen Pfad: `lu-labs-experiment` ist erlaubt, `lu-labs` nicht,
+ /// und ein Präfix-Vergleich könnte die beiden nicht auseinanderhalten.
+ /// Zusätzlich case-insensitiv, weil macOS (APFS) und Windows
+ /// Groß-/Kleinschreibung in Pfaden nicht unterscheiden — `LU-LABS` wäre
+ /// dort dasselbe Verzeichnis.
+ fn kollidierende_komponente(pfad: &Path) -> Option<String> {
+ for c in pfad.components() {
+ if let Component::Normal(os) = c {
+ let s = os.to_string_lossy();
+ if let Some(hit) = NAMEN_DER_ECHTEN_APP
+ .iter()
+ .find(|n| n.eq_ignore_ascii_case(&s))
+ {
+ return Some((*hit).to_string());
+ }
+ }
+ }
+ None
+ }
+
+ /// Jeder Pfad, den dieser Build sich selbst zusammenbaut — einmal
+ /// aufgezählt, einmal geprüft. Kommt eine neue Ableitung dazu, gehört sie
+ /// hier hinein.
+ fn alle_abgeleiteten_pfade() -> Vec<(&'static str, std::path::PathBuf)> {
+ use crate::os_paths as p;
+ vec![
+ ("data_dir", p::data_dir()),
+ ("cache_dir", p::cache_dir()),
+ ("config_root", p::config_root()),
+ ("log_dir", p::log_dir()),
+ ("app_config_dir", p::app_config_dir()),
+ ("app_config_json", p::app_config_json()),
+ ("tools_bin_dir", p::tools_bin_dir()),
+ ("builtin_models_dir", p::builtin_models_dir()),
+ ("agent_workspace_root", p::agent_workspace_root()),
+ ("default_comfyui_dir", p::default_comfyui_dir()),
+ ("mlx_root", p::data_dir().join("mlx")),
+ ("stores_dir", p::data_dir().join("stores")),
+ ("crash_log", crate::crash_report::crash_log_path()),
+ ("images_root", crate::commands::mlx::images_root()),
+ ("video_models_root", crate::commands::video::models_root()),
+ ("video_outputs_root", crate::commands::video::outputs_root()),
+ (
+ "persistent_dir",
+ crate::commands::system::persistent_dir().expect("persistent_dir"),
+ ),
+ ]
+ }
+
+ /// Mutationsprobe: `branch_dir_suffix!()` auf `""` zurückdrehen lässt auch
+ /// diesen Test rot werden — und zwar für jeden einzelnen Pfad.
+ #[test]
+ fn kein_abgeleiteter_pfad_zeigt_in_ein_verzeichnis_der_echten_app() {
+ // Alle Verstöße sammeln statt beim ersten abzubrechen: wer den Suffix
+ // zurückdreht, soll die ganze Liste sehen und nicht einen Pfad nach
+ // dem anderen.
+ let mut verstoesse: Vec<String> = Vec::new();
+ for (name, pfad) in alle_abgeleiteten_pfade() {
+ if let Some(treffer) = kollidierende_komponente(&pfad) {
+ verstoesse.push(format!("{name} = {} (via '{treffer}')", pfad.display()));
+ }
+ }
+ assert!(
+ verstoesse.is_empty(),
+ "diese Pfade zeigen in ein Verzeichnis der ECHTEN App — dieser Build \
+ darf dort weder lesen noch schreiben:\n {}",
+ verstoesse.join("\n ")
+ );
+ }
+
+ /// Gegenprobe zur Prüfmethode selbst: sie muss einen Treffer auch finden.
+ /// Ohne das wäre ein immer-`None` liefernder Prüfer ein grüner Test.
+ #[test]
+ fn die_pruefung_erkennt_einen_echten_treffer() {
+ let echt = Path::new("/Users/x/Library/Application Support/lu-labs/stores");
+ assert_eq!(kollidierende_komponente(echt).as_deref(), Some("lu-labs"));
+
+ let gross = Path::new("/Users/x/AppData/Local/LU-LABS/logs");
+ assert_eq!(kollidierende_komponente(gross).as_deref(), Some("lu-labs"));
+
+ // …und ein Suffix-Name ist ausdrücklich KEIN Treffer.
+ let unser = Path::new("/Users/x/Library/Application Support/lu-labs-experiment/stores");
+ assert_eq!(kollidierende_komponente(unser), None);
+ }
+
+ /// Die Präfix-Falle: `lu-labs-experiment` fängt mit `lu-labs` an. Sobald
+ /// irgendwo im Code ein Präfix-Vergleich oder ein Glob auf dem nackten
+ /// Namen steht, erwischt das beide Verzeichnisse und die Trennung ist
+ /// wieder weg. Genauso wandert ein neu angehängtes Literal an der
+ /// Konstante vorbei.
+ ///
+ /// Deshalb scannt dieser Test die eigenen Quellen. Die Nadeln werden zur
+ /// Laufzeit gebaut, damit der Test sich nicht selbst findet.
+ #[test]
+ fn keine_quelldatei_baut_einen_pfad_der_echten_app_von_hand() {
+ let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
+ let mut funde: Vec<String> = Vec::new();
+
+ for eintrag in walkdir::WalkDir::new(&src)
+ .into_iter()
+ .filter_map(Result::ok)
+ .filter(|e| e.path().extension().is_some_and(|x| x == "rs"))
+ {
+ let Ok(inhalt) = std::fs::read_to_string(eintrag.path()) else {
+ continue;
+ };
+ for name in NAMEN_DER_ECHTEN_APP {
+ for nadel in [
+ format!(".join(\"{name}\")"),
+ format!("starts_with(\"{name}\")"),
+ format!("\"{name}*\""),
+ format!("\"{name}/"),
+ format!("\"{name}\\\\"),
+ ] {
+ if inhalt.contains(&nadel) {
+ funde.push(format!(
+ "{}: {nadel}",
+ eintrag.path().strip_prefix(&src).unwrap_or(eintrag.path()).display()
+ ));
+ }
+ }
+ }
+ }
+
+ assert!(
+ funde.is_empty(),
+ "Pfade der ECHTEN App im Quelltext zusammengebaut — jeder dieser Namen \
+ gehört über die Konstanten in app_identity abgeleitet:\n {}",
+ funde.join("\n ")
+ );
+ }
+}
diff --git a/src-tauri/src/commands/agent.rs b/src-tauri/src/commands/agent.rs
index 668f74ab..0977b194 100644
--- a/src-tauri/src/commands/agent.rs
+++ b/src-tauri/src/commands/agent.rs
@@ -16,7 +16,7 @@ const CREATE_NO_WINDOW: u32 = 0x08000000;
/// Base directory for all agent workspaces. Per-chat subfolders are
/// created lazily by `agent_workspace(chat_id)` on the first write.
fn agent_workspace_root() -> PathBuf {
- dirs::home_dir().unwrap_or_default().join("agent-workspace")
+ crate::os_paths::agent_workspace_root()
}
/// Per-chat workspace directory. Each LU chat / Remote chat / Codex chat
diff --git a/src-tauri/src/commands/engine.rs b/src-tauri/src/commands/engine.rs
index 0d649cac..39b7c9c0 100644
--- a/src-tauri/src/commands/engine.rs
+++ b/src-tauri/src/commands/engine.rs
@@ -440,8 +440,8 @@ fn scan_gguf_dir(
/// download / scan just works on a fresh box. This is the same path
/// `detect_model_path("builtin")` returns.
pub fn builtin_models_dir() -> Result<PathBuf, String> {
- let base = dirs::data_dir().ok_or("Cannot resolve app data directory")?;
- let dir = base.join("Locally Uncensored").join("models");
+ dirs::data_dir().ok_or("Cannot resolve app data directory")?;
+ let dir = crate::os_paths::builtin_models_dir();
std::fs::create_dir_all(&dir)
.map_err(|e| format!("Create built-in models dir: {}", os_error::english(&e)))?;
Ok(dir)
diff --git a/src-tauri/src/commands/filesystem.rs b/src-tauri/src/commands/filesystem.rs
index a6960593..990ade68 100644
--- a/src-tauri/src/commands/filesystem.rs
+++ b/src-tauri/src/commands/filesystem.rs
@@ -189,7 +189,7 @@ pub(crate) fn workspace_root(chat_id: Option<&str>, working_dir: Option<&str>) -
return PathBuf::from(wd);
}
let slug = crate::commands::agent::sanitize_chat_slug(chat_id.unwrap_or("default"));
- dirs::home_dir().unwrap_or_default().join("agent-workspace").join(slug)
+ crate::os_paths::agent_workspace_root().join(slug)
}
/// THE ALLOWLIST: folders the user chose in a native folder dialog.
@@ -285,7 +285,7 @@ pub(crate) fn remember_picked_root(root: &Path) -> Result<(), String> {
/// app derives them itself (`workspace_root`), so the allowlist has to know
/// them or a plain sandbox chat could not read its own files.
fn is_app_work_dir(norm: &Path) -> bool {
- let base = lexical_normalize(&dirs::home_dir().unwrap_or_default().join("agent-workspace"));
+ let base = lexical_normalize(&crate::os_paths::agent_workspace_root());
is_within(&base, norm)
}
@@ -1038,14 +1038,18 @@ mod tests {
fn relative_path_without_working_dir_uses_sandbox() {
let got = resolve_path("notes.md", Some("chat-1"), None).unwrap();
let s = got.to_string_lossy().replace('\\', "/");
- assert!(s.contains("agent-workspace/chat-1/notes.md"), "got: {}", s);
+ // Der Ordnername kommt aus app_identity, damit diese Zusicherung den
+ // Branch-Suffix nicht gegen sich selbst ausspielt.
+ let erwartet = format!("{}/chat-1/notes.md", crate::app_identity::AGENT_WORKSPACE_DIR);
+ assert!(s.contains(&erwartet), "got: {}", s);
}
#[test]
fn blank_working_dir_falls_back_to_sandbox() {
let got = resolve_path("a.txt", Some("c"), Some(" ")).unwrap();
let s = got.to_string_lossy().replace('\\', "/");
- assert!(s.contains("agent-workspace/c/a.txt"), "got: {}", s);
+ let erwartet = format!("{}/c/a.txt", crate::app_identity::AGENT_WORKSPACE_DIR);
+ assert!(s.contains(&erwartet), "got: {}", s);
}
// ── Path-jail (security): absolute paths are allowed only inside the root ──
@@ -1306,7 +1310,7 @@ mod workspace_root_guard_tests {
let home = dirs::home_dir().unwrap_or_default();
assert_eq!(
workspace_root(Some(".."), None),
- home.join("agent-workspace").join("__"),
+ crate::os_paths::agent_workspace_root().join("__"),
);
for id in ["..", ".", "../.."] {
let target = home.join(".ssh").join("id_rsa");
diff --git a/src-tauri/src/commands/install.rs b/src-tauri/src/commands/install.rs
index 5bfdbb7c..506fd4ae 100644
--- a/src-tauri/src/commands/install.rs
+++ b/src-tauri/src/commands/install.rs
@@ -1438,8 +1438,8 @@ pub fn install_comfyui(
let mut p = comfy_path_slot.lock().unwrap();
*p = Some(dir_str.clone());
}
- if let Some(config_dir) = dirs::config_dir() {
- let app_config = config_dir.join("locally-uncensored");
+ {
+ let app_config = crate::os_paths::app_config_dir();
let _ = std::fs::create_dir_all(&app_config);
let config_file = app_config.join("config.json");
let mut config: serde_json::Value = std::fs::read_to_string(&config_file)
diff --git a/src-tauri/src/commands/mlx.rs b/src-tauri/src/commands/mlx.rs
index ca244c17..7eb579c8 100644
--- a/src-tauri/src/commands/mlx.rs
+++ b/src-tauri/src/commands/mlx.rs
@@ -1,7 +1,8 @@
//! MLX-Stable-Diffusion image provider for macOS (Apple Silicon
//! recommended image stack).
//!
-//! Layout under `~/Library/Application Support/lu-labs/mlx/`:
+//! Layout under `<os_paths::data_dir()>/mlx/` (macOS: `~/Library/Application
+//! Support/<APP_DIR>/mlx/`; der Verzeichnisname kommt aus `app_identity`):
//! venv/ — dedicated Python venv we own
//! server.py — FastAPI sidecar (embedded via include_str!)
//! requirements.txt — pip dependencies (embedded via include_str!)
@@ -802,10 +803,7 @@ pub async fn mlx_generate(_state: &AppState, args: &Value) -> CmdResult {
/// Where generated stills live. Sibling of the video lane's outputs root and
/// covered by the same read_media_file allow-list.
pub(crate) fn images_root() -> PathBuf {
- dirs::config_dir()
- .unwrap_or_else(|| PathBuf::from("."))
- .join("lu-labs")
- .join("images")
+ crate::os_paths::config_root().join("images")
}
fn write_generated_png(b64: &str) -> Result<PathBuf, String> {
diff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rs
index 1ffc3efa..bcf91c09 100644
--- a/src-tauri/src/commands/process.rs
+++ b/src-tauri/src/commands/process.rs
@@ -692,8 +692,8 @@ pub fn find_comfyui_path() -> Option<String> {
}
// 2. Read from app config
- if let Some(config_dir) = dirs::config_dir() {
- let config_file = config_dir.join("locally-uncensored").join("config.json");
+ {
+ let config_file = crate::os_paths::app_config_json();
if config_file.exists() {
if let Ok(content) = fs::read_to_string(&config_file) {
if let Ok(config) = serde_json::from_str::<serde_json::Value>(&content) {
@@ -875,8 +875,8 @@ fn detect_all_comfyui_installs_sync() -> Vec<ComfyUIInstall> {
}
// 2. app config.json
- if let Some(config_dir) = dirs::config_dir() {
- let config_file = config_dir.join("locally-uncensored").join("config.json");
+ {
+ let config_file = crate::os_paths::app_config_json();
if let Ok(content) = fs::read_to_string(&config_file) {
if let Ok(config) = serde_json::from_str::<serde_json::Value>(&content) {
if let Some(path) = config.get("comfyui_path").and_then(|v| v.as_str()) {
@@ -1952,8 +1952,8 @@ pub fn set_comfyui_path(path: String, state: State<'_, AppState>) -> Result<serd
}
// Persist to config file
- if let Some(config_dir) = dirs::config_dir() {
- let app_config = config_dir.join("locally-uncensored");
+ {
+ let app_config = crate::os_paths::app_config_dir();
let _ = fs::create_dir_all(&app_config);
let config_file = app_config.join("config.json");
@@ -2017,8 +2017,8 @@ pub fn set_comfyui_host(host: String, state: State<'_, AppState>) -> Result<serd
}
// Persist to config file
- if let Some(config_dir) = dirs::config_dir() {
- let app_config = config_dir.join("locally-uncensored");
+ {
+ let app_config = crate::os_paths::app_config_dir();
let _ = fs::create_dir_all(&app_config);
let config_file = app_config.join("config.json");
@@ -2055,8 +2055,8 @@ pub fn set_comfyui_port(port: u16, state: State<'_, AppState>) -> Result<serde_j
}
// Persist to config file
- if let Some(config_dir) = dirs::config_dir() {
- let app_config = config_dir.join("locally-uncensored");
+ {
+ let app_config = crate::os_paths::app_config_dir();
let _ = fs::create_dir_all(&app_config);
let config_file = app_config.join("config.json");
@@ -2112,8 +2112,8 @@ pub fn set_ollama_host(host: String, state: State<'_, AppState>) -> Result<serde
// Persist to config file under ollama_base — next startup will pick it
// up via load_ollama_base() before any request fires.
- if let Some(config_dir) = dirs::config_dir() {
- let app_config = config_dir.join("locally-uncensored");
+ {
+ let app_config = crate::os_paths::app_config_dir();
let _ = fs::create_dir_all(&app_config);
let config_file = app_config.join("config.json");
diff --git a/src-tauri/src/commands/proxy.rs b/src-tauri/src/commands/proxy.rs
index bad017f8..56daa961 100644
--- a/src-tauri/src/commands/proxy.rs
+++ b/src-tauri/src/commands/proxy.rs
@@ -1358,7 +1358,7 @@ mod tests {
/// Live proof over a real socket against the strict aiohttp parser, the
/// one that rejected every 2.6.0 Create submit. Start the stub first
/// (scratchpad/strict-comfy-stub.py, AIOHTTP_NO_EXTENSIONS=1), then:
- /// cargo test --bin locally-uncensored live_strict -- --ignored --nocapture
+ /// cargo test --bin lu-experiment live_strict -- --ignored --nocapture
#[test]
#[ignore]
fn live_strict_aiohttp_takes_the_fixed_request_and_refuses_the_old_one() {
diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rs
index 629f814f..1c0ee09c 100644
--- a/src-tauri/src/commands/remote.rs
+++ b/src-tauri/src/commands/remote.rs
@@ -5826,10 +5826,7 @@ pub async fn set_remote_permissions(
/// Download cloudflared binary if not present, return its path
fn get_cloudflared_path() -> std::path::PathBuf {
- let dir = dirs::data_local_dir()
- .unwrap_or_else(|| std::path::PathBuf::from("."))
- .join("locally-uncensored")
- .join("bin");
+ let dir = crate::os_paths::tools_bin_dir();
let exe_name = if cfg!(windows) { "cloudflared.exe" } else { "cloudflared" };
dir.join(exe_name)
}
@@ -6309,7 +6306,11 @@ mod remote_path_tests {
let state = AppState::new();
let resolved = resolve_remote_path("client/public", Some("__remote__"), &state).unwrap();
let s = resolved.replace('\\', "/");
- assert!(s.contains("agent-workspace/__remote__/client/public"), "got: {}", s);
+ let erwartet = format!(
+ "{}/__remote__/client/public",
+ crate::app_identity::AGENT_WORKSPACE_DIR
+ );
+ assert!(s.contains(&erwartet), "got: {}", s);
}
/// Override set → relative paths land inside it.
diff --git a/src-tauri/src/commands/secret.rs b/src-tauri/src/commands/secret.rs
index a0031749..6522e522 100644
--- a/src-tauri/src/commands/secret.rs
+++ b/src-tauri/src/commands/secret.rs
@@ -24,8 +24,14 @@
/// Keychain service name. The "account" is the provider id (ollama / openai /
/// anthropic). Keep this stable — changing it would orphan stored keys.
+///
+/// Der Name ist KEIN Pfad, gehört aber zur selben Trennung: ohne eigenen
+/// Service-Namen läse der Experiment-Build die echten API-Schlüssel des
+/// Nutzers aus dem Schlüsselbund und überschriebe sie beim nächsten Speichern.
+/// Deshalb kommt er aus `crate::app_identity` und trägt auf diesem Branch
+/// denselben Suffix wie die Verzeichnisse.
#[cfg(any(target_os = "windows", target_os = "macos"))]
-const SERVICE: &str = "com.locallyuncensored.providerkeys";
+const SERVICE: &str = crate::app_identity::KEYCHAIN_SERVICE;
#[cfg(any(target_os = "windows", target_os = "macos"))]
mod chunked {
diff --git a/src-tauri/src/commands/shell.rs b/src-tauri/src/commands/shell.rs
index 3a8bc744..857c4e20 100644
--- a/src-tauri/src/commands/shell.rs
+++ b/src-tauri/src/commands/shell.rs
@@ -23,9 +23,7 @@ use std::path::{Path, PathBuf};
/// resolved to `~/agent-workspace/..` == `$HOME` and the shell tool ran (and
/// created directories) straight in the user's home (audit IPC-1).
fn workspace_cwd(chat_id: Option<&str>) -> PathBuf {
- dirs::home_dir()
- .unwrap_or_default()
- .join("agent-workspace")
+ crate::os_paths::agent_workspace_root()
.join(crate::commands::agent::sanitize_chat_slug(chat_id.unwrap_or("default")))
}
@@ -488,7 +486,7 @@ mod tests {
/// from that chat ran there (audit IPC-1, fixed in agent.rs only).
#[test]
fn a_dotted_chat_id_cannot_walk_the_cwd_out_of_the_workspace() {
- let root = dirs::home_dir().unwrap_or_default().join("agent-workspace");
+ let root = crate::os_paths::agent_workspace_root();
for id in ["..", ".", "../..", "a.b"] {
let cwd = workspace_cwd(Some(id));
assert!(cwd.starts_with(&root), "id {id:?} escaped to {cwd:?}");
diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rs
index c903c2a8..5df7e7db 100644
--- a/src-tauri/src/commands/system.rs
+++ b/src-tauri/src/commands/system.rs
@@ -267,15 +267,20 @@ pub fn exit_app(app: tauri::AppHandle) {
}
/// Get the persistent settings dir — outside the (NSIS) install dir so it
-/// survives updates. On Windows this stays `%APPDATA%/Locally Uncensored` (the
+/// survives updates. On Windows this stays `%APPDATA%/<APP_DISPLAY_DIR>` (the
/// path existing installs already back up to). `APPDATA` is Windows-only, so on
/// macOS/Linux the whole backup/restore + onboarding-marker cluster used to
/// hard-error; there we use the shared app data dir instead.
-fn persistent_dir() -> Result<std::path::PathBuf, String> {
+///
+/// `<APP_DISPLAY_DIR>` ist `Locally Uncensored` in der echten App; auf diesem
+/// Branch trägt der Name einen Suffix (`crate::app_identity`). Genau diese
+/// Datei — `store_backup.json` — hat der Experiment-Build am 2026-08-31 im
+/// Verzeichnis der echten App überschrieben.
+pub(crate) fn persistent_dir() -> Result<std::path::PathBuf, String> {
#[cfg(target_os = "windows")]
{
let appdata = std::env::var("APPDATA").map_err(|_| "APPDATA not set".to_string())?;
- Ok(std::path::PathBuf::from(appdata).join("Locally Uncensored"))
+ Ok(std::path::PathBuf::from(appdata).join(crate::app_identity::APP_DISPLAY_DIR))
}
#[cfg(not(target_os = "windows"))]
{
diff --git a/src-tauri/src/commands/trainer.rs b/src-tauri/src/commands/trainer.rs
index b8a0634c..5ad8c608 100644
--- a/src-tauri/src/commands/trainer.rs
+++ b/src-tauri/src/commands/trainer.rs
@@ -82,7 +82,7 @@ fn free_stem(dir: &Path, base: &str, ext: &str, bytes: &[u8]) -> String {
}
fn config_json_path() -> Option<PathBuf> {
- dirs::config_dir().map(|d| d.join("locally-uncensored").join("config.json"))
+ dirs::config_dir().map(|_| crate::os_paths::app_config_json())
}
fn read_config_value(key: &str) -> Option<String> {
diff --git a/src-tauri/src/commands/video.rs b/src-tauri/src/commands/video.rs
index e0855066..d5895cfb 100644
--- a/src-tauri/src/commands/video.rs
+++ b/src-tauri/src/commands/video.rs
@@ -5,9 +5,12 @@
//! with an arch check so Windows/Linux clients hitting these commands by
//! accident get a clear 400 instead of a hung subprocess.
//!
-//! Models are downloaded into `~/.cache/lu-labs/mlx-video/<id>/` (the
-//! `--model-dir` argument passed to `mlx_video.<family>.generate`).
-//! Generated videos land in `~/.config/lu-labs/videos/<job_id>.mp4`.
+//! Models are downloaded into `<os_paths::cache_dir()>/mlx-video/<id>/` (the
+//! `--model-dir` argument passed to `mlx_video.<family>.generate`), Linux also
+//! `~/.cache/<APP_DIR>/mlx-video/<id>/`.
+//! Generated videos land in `<os_paths::config_root()>/videos/<job_id>.mp4`.
+//! `<APP_DIR>` kommt aus `app_identity` und trägt auf diesem Branch einen
+//! eigenen Suffix.
use crate::os_error;
use crate::commands::{bad_request, internal, CmdResult};
@@ -178,18 +181,12 @@ fn catalog_lookup(id: &str) -> Option<&'static CatalogEntry> {
// ── Filesystem layout ─────────────────────────────────────────────────
-fn models_root() -> PathBuf {
- dirs::cache_dir()
- .unwrap_or_else(|| PathBuf::from("."))
- .join("lu-labs")
- .join("mlx-video")
+pub(crate) fn models_root() -> PathBuf {
+ crate::os_paths::cache_dir().join("mlx-video")
}
pub(crate) fn outputs_root() -> PathBuf {
- dirs::config_dir()
- .unwrap_or_else(|| PathBuf::from("."))
- .join("lu-labs")
- .join("videos")
+ crate::os_paths::config_root().join("videos")
}
fn model_dir(id: &str) -> PathBuf {
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
index 775e6e3a..227381e5 100644
--- a/src-tauri/src/main.rs
+++ b/src-tauri/src/main.rs
@@ -1,6 +1,7 @@
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
+mod app_identity;
mod commands;
mod crash_report;
mod install_state;
@@ -110,7 +111,7 @@ fn file_log_writer() -> Option<(tracing_appender::non_blocking::NonBlocking, tra
/// because most desktop users just want a readable terminal.
///
/// `RUST_LOG` is honored as the filter — common values are `info`,
-/// `locally_uncensored=debug`, or a per-module spec.
+/// `lu_experiment=debug` (der Crate-Name, siehe Cargo.toml), or a per-module spec.
///
/// Audit finding #01: until now this was the stdout layer and nothing else,
/// and a shipped desktop app has no stdout. On Windows the release binary is
diff --git a/src-tauri/src/os_paths.rs b/src-tauri/src/os_paths.rs
index 344ccdb1..d05480d9 100644
--- a/src-tauri/src/os_paths.rs
+++ b/src-tauri/src/os_paths.rs
@@ -1,7 +1,13 @@
//! Cross-platform path helpers — Python lookup, LM Studio CLI, common
//! install destinations. Mirrors the path-resolution logic from the old
//! Locally Uncensored Tauri binary.
+//!
+//! Jeder app-eigene Verzeichnisname kommt aus [`crate::app_identity`] und wird
+//! hier NICHT noch einmal als Literal geschrieben. Auf diesem Branch trägt er
+//! einen Suffix, damit der Experiment-Build die Daten der echten App weder
+//! liest noch überschreibt — die Begründung steht in `app_identity`.
+use crate::app_identity::{AGENT_WORKSPACE_DIR, APP_CONFIG_DIR, APP_DIR, APP_DISPLAY_DIR};
use std::path::PathBuf;
pub fn home() -> PathBuf {
@@ -12,13 +18,61 @@ pub fn data_dir() -> PathBuf {
dirs::data_local_dir()
.or_else(dirs::data_dir)
.unwrap_or_else(|| PathBuf::from("."))
- .join("lu-labs")
+ .join(APP_DIR)
}
pub fn cache_dir() -> PathBuf {
dirs::cache_dir()
.unwrap_or_else(|| PathBuf::from("."))
- .join("lu-labs")
+ .join(APP_DIR)
+}
+
+/// `config_dir()`-Zweig desselben Verzeichnisses. Unter macOS/Windows fällt er
+/// mit [`data_dir`] zusammen, unter Linux ist es `~/.config/<APP_DIR>` — dort
+/// liegen die erzeugten Bilder (`commands::mlx`) und Videos
+/// (`commands::video`).
+pub fn config_root() -> PathBuf {
+ dirs::config_dir()
+ .unwrap_or_else(|| PathBuf::from("."))
+ .join(APP_DIR)
+}
+
+/// Ordner der `config.json` (ComfyUI-Pfad/-Port, Ollama-Basis, Trainer-Root).
+/// Historisch ein anderer Name als [`data_dir`] — deshalb eine eigene
+/// Konstante statt eines zweiten Literals.
+pub fn app_config_dir() -> PathBuf {
+ dirs::config_dir()
+ .unwrap_or_else(|| PathBuf::from("."))
+ .join(APP_CONFIG_DIR)
+}
+
+/// Die `config.json` selbst.
+pub fn app_config_json() -> PathBuf {
+ app_config_dir().join("config.json")
+}
+
+/// Ablage für Hilfsbinaries, die die App selbst herunterlädt (`cloudflared`).
+pub fn tools_bin_dir() -> PathBuf {
+ dirs::data_local_dir()
+ .unwrap_or_else(|| PathBuf::from("."))
+ .join(APP_CONFIG_DIR)
+ .join("bin")
+}
+
+/// Modellordner der eingebauten Engine. Bewusst `dirs::data_dir()` (unter
+/// Windows also `%APPDATA%`, nicht `%LOCALAPPDATA%`) — das ist der Pfad, den
+/// `detect_model_path("builtin")` seit jeher zurückgibt.
+pub fn builtin_models_dir() -> PathBuf {
+ dirs::data_dir()
+ .unwrap_or_else(|| PathBuf::from("."))
+ .join(APP_DISPLAY_DIR)
+ .join("models")
+}
+
+/// Sandkasten-Wurzel der Agenten. Pro Chat entsteht darin ein Unterordner;
+/// `commands::filesystem::contain_within` lässt nichts darüber hinaus.
+pub fn agent_workspace_root() -> PathBuf {
+ home().join(AGENT_WORKSPACE_DIR)
}
/// Where the rolling application log is written (`init_tracing` in main.rs,
@@ -37,9 +91,12 @@ pub fn cache_dir() -> PathBuf {
/// every artefact a support request needs, instead of the panic record and
/// the log being two unrelated places on three different operating systems.
///
-/// macOS: ~/Library/Application Support/lu-labs/logs
-/// Windows: %LOCALAPPDATA%\lu-labs\logs
-/// Linux: ~/.local/share/lu-labs/logs
+/// macOS: ~/Library/Application Support/<APP_DIR>/logs
+/// Windows: %LOCALAPPDATA%\<APP_DIR>\logs
+/// Linux: ~/.local/share/<APP_DIR>/logs
+///
+/// `<APP_DIR>` ist `lu-labs` in der echten App und trägt auf diesem Branch
+/// einen Suffix — siehe [`crate::app_identity`].
pub fn log_dir() -> PathBuf {
data_dir().join("logs")
}
diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs
index 4c70f4dc..49709b7a 100644
--- a/src-tauri/src/state.rs
+++ b/src-tauri/src/state.rs
@@ -78,15 +78,16 @@ impl Default for InstallState {
}
}
-/// Read persisted ComfyUI port + host from %APPDATA%/locally-uncensored/config.json.
+/// Read persisted ComfyUI port + host from `os_paths::app_config_json()`
+/// (Windows: `%APPDATA%\\<APP_CONFIG_DIR>\\config.json`).
/// Returns (port, host) with sensible defaults (8188, "localhost") on any error.
/// Called at startup so user-configured values survive app restarts.
pub(crate) fn load_comfy_config_values() -> (u16, String) {
let mut port = 8188u16;
let mut host = "localhost".to_string();
- if let Some(config_dir) = dirs::config_dir() {
- let config_file = config_dir.join("locally-uncensored").join("config.json");
+ {
+ let config_file = crate::os_paths::app_config_json();
if let Ok(raw) = std::fs::read_to_string(&config_file) {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&raw) {
if let Some(p) = v.get("comfyui_port").and_then(|x| x.as_u64()) {
@@ -128,8 +129,8 @@ pub(crate) fn load_ollama_base() -> String {
};
// Priority 1: config.json override (GUI takes precedence)
- if let Some(config_dir) = dirs::config_dir() {
- let config_file = config_dir.join("locally-uncensored").join("config.json");
+ {
+ let config_file = crate::os_paths::app_config_json();
if let Ok(raw) = std::fs::read_to_string(&config_file) {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(&raw) {
if let Some(b) = v.get("ollama_base").and_then(|x| x.as_str()) {
diff --git a/src/lib/__tests__/app-identity.test.ts b/src/lib/__tests__/app-identity.test.ts
new file mode 100644
index 00000000..92fe4c90
--- /dev/null
+++ b/src/lib/__tests__/app-identity.test.ts
@@ -0,0 +1,77 @@
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import {
+ AGENT_WORKSPACE_DIR,
+ APP_CONFIG_DIR,
+ APP_DIR,
+ APP_DISPLAY_DIR,
+} from '../app-identity'
+
+/**
+ * Dieser Branch (`experiment/audits-komplett`) hat bewusst eigene
+ * Datenverzeichnisse: der Experiment-Build hat am 2026-08-31 in
+ * `~/Library/Application Support/lu-labs/` — dem Verzeichnis der ECHTEN App —
+ * geschrieben und dabei ein Store-Backup überschrieben.
+ *
+ * Die Namen stehen an zwei Stellen (Rust für die Tauri-App, TypeScript für die
+ * vite-Middlewares von `npm run dev`). Diese Datei ist die Klammer: sie liest
+ * die Rust-Konstanten und vergleicht sie mit den TS-Konstanten, damit die
+ * beiden Seiten nicht auseinander laufen können.
+ */
+describe('Verzeichnisnamen dieses Builds', () => {
+ const rust = readFileSync(
+ resolve(process.cwd(), 'src-tauri/src/app_identity.rs'),
+ 'utf8',
+ )
+
+ /** `pub const NAME: &str = concat!("basis", branch_dir_suffix!());` auflösen. */
+ function rustConst(name: string): string {
+ const suffix = /macro_rules!\s+branch_dir_suffix\s*\{\s*\(\)\s*=>\s*\{\s*"([^"]*)"/.exec(rust)
+ expect(suffix, 'branch_dir_suffix!() nicht in app_identity.rs gefunden').not.toBeNull()
+ const re = new RegExp(
+ `pub const ${name}: &str =\\s*concat!\\("([^"]*)",\\s*branch_dir_suffix!\\(\\)\\);`,
+ )
+ const m = re.exec(rust)
+ expect(m, `${name} nicht in app_identity.rs gefunden`).not.toBeNull()
+ return `${m![1]}${suffix![1]}`
+ }
+
+ it('stimmen mit der Rust-Seite überein', () => {
+ // Ein Jail, das anders rechnet als der Ordner, in den geschrieben wird,
+ // lehnt jeden Zugriff ab — die beiden Seiten MÜSSEN identisch sein.
+ expect(AGENT_WORKSPACE_DIR).toBe(rustConst('AGENT_WORKSPACE_DIR'))
+ expect(APP_CONFIG_DIR).toBe(rustConst('APP_CONFIG_DIR'))
+ expect(APP_DIR).toBe(rustConst('APP_DIR'))
+ expect(APP_DISPLAY_DIR).toBe(rustConst('APP_DISPLAY_DIR'))
+ })
+
+ it('sind keine Verzeichnisnamen der echten App', () => {
+ // Bewusst eigene Literale: ein Test, der seine Erwartung aus dem ableitet,
+ // was er absichern soll, prüft nichts.
+ const echt = ['lu-labs', 'locally-uncensored', 'Locally Uncensored', 'agent-workspace']
+ for (const name of [AGENT_WORKSPACE_DIR, APP_CONFIG_DIR, APP_DIR, APP_DISPLAY_DIR]) {
+ expect(echt, `'${name}' ist der Verzeichnisname der ECHTEN App`).not.toContain(name)
+ }
+ })
+
+ it('werden im vite-Dev-Server nicht von Hand zusammengebaut', () => {
+ // Die Präfix-/Literal-Falle auf der TS-Seite: `lu-labs-experiment` fängt
+ // mit `lu-labs` an, und ein neu hingeschriebenes Literal wandert an
+ // app-identity.ts vorbei. vite.config.ts bedient den `npm run dev`-Pfad
+ // und schreibt mit echten Node-fs-Aufrufen auf die Platte.
+ const vite = readFileSync(resolve(process.cwd(), 'vite.config.ts'), 'utf8')
+ const jail = readFileSync(resolve(process.cwd(), 'src/lib/dev-fs-jail.ts'), 'utf8')
+ for (const name of ['lu-labs', 'locally-uncensored', 'Locally Uncensored', 'agent-workspace']) {
+ for (const quelle of [
+ ['vite.config.ts', vite],
+ ['src/lib/dev-fs-jail.ts', jail],
+ ] as const) {
+ expect(quelle[1], `${quelle[0]}: '${name}' als Pfadbestandteil hartkodiert`)
+ .not.toContain(`'${name}'`)
+ expect(quelle[1], `${quelle[0]}: '${name}/' als Pfadbestandteil hartkodiert`)
+ .not.toContain(`/${name}/`)
+ }
+ }
+ })
+})
diff --git a/src/lib/__tests__/dev-fs-jail.test.ts b/src/lib/__tests__/dev-fs-jail.test.ts
index c07637c8..7494f34b 100644
--- a/src/lib/__tests__/dev-fs-jail.test.ts
+++ b/src/lib/__tests__/dev-fs-jail.test.ts
@@ -27,6 +27,9 @@ import {
DEV_READ_BYTES_CAP,
JailEscapeError,
} from '../dev-fs-jail'
+// Der Ordnername kommt aus app-identity (dieser Branch hängt einen Suffix an),
+// damit die Zusicherungen den Namen nicht gegen sich selbst ausspielen.
+import { AGENT_WORKSPACE_DIR as WS } from '../app-identity'
const HOME = '/Users/dev'
const ROOT = '/Users/dev/projects/lu'
@@ -37,18 +40,18 @@ describe('devWorkspaceRoot', () => {
})
it('falls back to the per-chat sandbox', () => {
- expect(devWorkspaceRoot(HOME, 'chat-1', '')).toBe('/Users/dev/agent-workspace/chat-1')
- expect(devWorkspaceRoot(HOME, null, null)).toBe('/Users/dev/agent-workspace/default')
+ expect(devWorkspaceRoot(HOME, 'chat-1', '')).toBe(`/Users/dev/${WS}/chat-1`)
+ expect(devWorkspaceRoot(HOME, null, null)).toBe(`/Users/dev/${WS}/default`)
})
it('sanitises the chat id the way the Rust side does', () => {
- expect(devWorkspaceRoot(HOME, '../../etc', null)).toBe('/Users/dev/agent-workspace/.._.._etc')
- expect(devWorkspaceRoot(HOME, 'a/b c', null)).toBe('/Users/dev/agent-workspace/a_b_c')
+ expect(devWorkspaceRoot(HOME, '../../etc', null)).toBe(`/Users/dev/${WS}/.._.._etc`)
+ expect(devWorkspaceRoot(HOME, 'a/b c', null)).toBe(`/Users/dev/${WS}/a_b_c`)
})
it('caps the chat id at 64 chars', () => {
const long = 'a'.repeat(200)
- expect(devWorkspaceRoot(HOME, long, null)).toBe(`/Users/dev/agent-workspace/${'a'.repeat(64)}`)
+ expect(devWorkspaceRoot(HOME, long, null)).toBe(`/Users/dev/${WS}/${'a'.repeat(64)}`)
})
})
@@ -86,7 +89,7 @@ describe('the jail', () => {
it('jails the per-chat sandbox too, not just a picked folder', () => {
expect(devResolveWithinJail({ path: 'note.txt', homeDir: HOME, chatId: 'c1' })).toBe(
- '/Users/dev/agent-workspace/c1/note.txt',
+ `/Users/dev/${WS}/c1/note.txt`,
)
expect(() =>
devResolveWithinJail({ path: '../c2/note.txt', homeDir: HOME, chatId: 'c1' }),
diff --git a/src/lib/app-identity.ts b/src/lib/app-identity.ts
new file mode 100644
index 00000000..bc4fbb02
--- /dev/null
+++ b/src/lib/app-identity.ts
@@ -0,0 +1,47 @@
+/**
+ * Die Namen der app-eigenen Verzeichnisse — TypeScript-Seite.
+ *
+ * Spiegel von `src-tauri/src/app_identity.rs`. Die ausführliche Begründung
+ * steht dort; kurz: dieser Branch (`experiment/audits-komplett`) hat BEWUSST
+ * eigene Verzeichnisse, weil der Experiment-Build am 2026-08-31 in das
+ * Datenverzeichnis der ECHTEN App geschrieben und dort ein Store-Backup
+ * überschrieben hat.
+ *
+ * Zwei Sprachen, zwei Dateien — unvermeidlich, aber nicht unbeaufsichtigt:
+ * `__tests__/app-identity.test.ts` liest die Rust-Konstanten aus
+ * `app_identity.rs` und schlägt fehl, sobald die beiden Seiten auseinander
+ * laufen. Sie MÜSSEN übereinstimmen: die Rust-Seite (Tauri-App) und die
+ * TS-Seite (`npm run dev` im Browser, vite-Middlewares) legen dieselben
+ * Dateien an, und ein Jail, das anders rechnet als der Ordner, in den
+ * geschrieben wird, lehnt jeden Zugriff ab.
+ *
+ * In der echten App gehört hier der Name OHNE Suffix hin.
+ */
+
+/**
+ * Sandkasten-Wurzel der Agenten unter `$HOME`.
+ * Rust: `app_identity::AGENT_WORKSPACE_DIR`.
+ */
+export const AGENT_WORKSPACE_DIR = 'agent-workspace-experiment'
+
+/**
+ * Ordner der `config.json` (ComfyUI-Pfad/-Port, Ollama-Basis).
+ * Rust: `app_identity::APP_CONFIG_DIR`.
+ */
+export const APP_CONFIG_DIR = 'locally-uncensored-experiment'
+
+/**
+ * Haupt-Datenverzeichnis (Daten, Cache, Config).
+ * Rust: `app_identity::APP_DIR`.
+ *
+ * Auf der TS-Seite bisher nur zur Vollständigkeit — sobald eine
+ * vite-Middleware dorthin greift, kommt der Name von hier.
+ */
+export const APP_DIR = 'lu-labs-experiment'
+
+/**
+ * Anzeige-Schreibweise (Modellordner der eingebauten Engine,
+ * `%APPDATA%`-Ordner der Store-Backups).
+ * Rust: `app_identity::APP_DISPLAY_DIR`.
+ */
+export const APP_DISPLAY_DIR = 'Locally Uncensored-experiment'
diff --git a/src/lib/dev-fs-jail.ts b/src/lib/dev-fs-jail.ts
index 55b9211f..dc626f72 100644
--- a/src/lib/dev-fs-jail.ts
+++ b/src/lib/dev-fs-jail.ts
@@ -6,7 +6,7 @@
* `contain_within` refuses anything that escapes it. `npm run dev` in a browser
* has no Rust, so each `/local-api/fs-*` middleware is on its own. This module
* is the port of that boundary: same root rule (a configured workingDirectory
- * wins, otherwise `~/agent-workspace/<chatId>`), same containment rule
+ * wins, otherwise `~/<AGENT_WORKSPACE_DIR>/<chatId>`), same containment rule
* (relative paths resolve inside the root, absolute paths are accepted only
* when they already fall inside it), same lexical `..` normalization so a path
* that does not exist yet can still be judged.
@@ -17,6 +17,8 @@
* runs on Windows.
*/
+import { AGENT_WORKSPACE_DIR } from './app-identity'
+
/** Read cap for one dev byte-read, mirroring READ_BYTES_CAP in filesystem.rs. */
export const DEV_READ_BYTES_CAP = 16 * 1024 * 1024
@@ -86,7 +88,7 @@ function compareKey(normalized: string): string {
/**
* The jail root for a dev file op — port of `workspace_root`. A non-empty
* `workingDirectory` (the folder the user picked) wins; otherwise the per-chat
- * sandbox `<homeDir>/agent-workspace/<chatId>`, with the id sanitised to
+ * sandbox `<homeDir>/<AGENT_WORKSPACE_DIR>/<chatId>`, with the id sanitised to
* `[A-Za-z0-9_.-]` and capped at 64 chars exactly like the Rust side.
*/
export function devWorkspaceRoot(
@@ -100,7 +102,7 @@ export function devWorkspaceRoot(
const safe = id
.slice(0, 64)
.replace(/[^A-Za-z0-9_.-]/g, '_')
- return lexicalNormalize(`${homeDir}/agent-workspace/${safe || 'default'}`)
+ return lexicalNormalize(`${homeDir}/${AGENT_WORKSPACE_DIR}/${safe || 'default'}`)
}
/** Thrown for any path that leaves the workspace root. */
diff --git a/vite.config.ts b/vite.config.ts
index 9224633a..4b166471 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -13,6 +13,10 @@ import os from 'os'
import dns from 'node:dns'
import net from 'node:net'
import { devResolveWithinJail, effectiveByteCap, JailEscapeError } from './src/lib/dev-fs-jail'
+// Verzeichnisnamen dieses Builds. Dieser Branch schreibt BEWUSST nicht in die
+// Ordner der echten App — siehe src/lib/app-identity.ts und
+// src-tauri/src/app_identity.rs.
+import { AGENT_WORKSPACE_DIR, APP_CONFIG_DIR } from './src/lib/app-identity'
import { postContentTypeAllowed, postContentTypeError } from './src/lib/local-api-guard'
// The port the dev server binds and the only port the /local-api origin check
@@ -903,7 +907,7 @@ function comfyLauncher(): Plugin {
res.end(JSON.stringify(found))
} else {
// Fallback: create LU models directory (same as Rust backend)
- const fallback = join(home, 'locally-uncensored', 'models')
+ const fallback = join(home, APP_CONFIG_DIR, 'models')
try { mkdirSync(fallback, { recursive: true }) } catch {}
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify(fallback))
@@ -933,7 +937,7 @@ function comfyLauncher(): Plugin {
// (konata-session 2026-06-07).
let comfyPath = ''
try {
- const cfgPath = join(process.env.APPDATA || join(home, 'AppData', 'Roaming'), 'locally-uncensored', 'config.json')
+ const cfgPath = join(process.env.APPDATA || join(home, 'AppData', 'Roaming'), APP_CONFIG_DIR, 'config.json')
if (existsSync(cfgPath)) {
const cfg = JSON.parse(require('fs').readFileSync(cfgPath, 'utf8'))
if (cfg.comfyui_path && existsSync(cfg.comfyui_path)) comfyPath = cfg.comfyui_path
@@ -1410,7 +1414,7 @@ function comfyLauncher(): Plugin {
const os = require('os')
const fs = require('fs')
- const workspaceDir = join(os.homedir(), 'agent-workspace')
+ const workspaceDir = join(os.homedir(), AGENT_WORKSPACE_DIR)
if (!existsSync(workspaceDir)) mkdirSync(workspaceDir, { recursive: true })
const resolvedPath = join(workspaceDir, filePath)
@@ -1450,7 +1454,7 @@ function comfyLauncher(): Plugin {
const os = require('os')
const fs = require('fs')
- const workspaceDir = join(os.homedir(), 'agent-workspace')
+ const workspaceDir = join(os.homedir(), AGENT_WORKSPACE_DIR)
const resolvedPath = join(workspaceDir, filePath)
const parentDir = resolve(resolvedPath, '..')
if (!existsSync(parentDir)) mkdirSync(parentDir, { recursive: true })
@@ -1542,7 +1546,7 @@ function comfyLauncher(): Plugin {
const { path: filePath } = JSON.parse(body)
const os = require('os')
const fs = require('fs')
- const resolved = require('path').isAbsolute(filePath) ? filePath : join(os.homedir(), 'agent-workspace', filePath)
+ const resolved = require('path').isAbsolute(filePath) ? filePath : join(os.homedir(), AGENT_WORKSPACE_DIR, filePath)
const content = fs.readFileSync(resolved, 'utf8')
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ content, encoding: 'utf8' }))
@@ -1610,7 +1614,7 @@ function comfyLauncher(): Plugin {
const { path: filePath, content } = JSON.parse(body)
const os = require('os')
const fs = require('fs')
- const resolved = require('path').isAbsolute(filePath) ? filePath : join(os.homedir(), 'agent-workspace', filePath)
+ const resolved = require('path').isAbsolute(filePath) ? filePath : join(os.homedir(), AGENT_WORKSPACE_DIR, filePath)
const parentDir = resolve(resolved, '..')
if (!existsSync(parentDir)) mkdirSync(parentDir, { recursive: true })
fs.writeFileSync(resolved, content, 'utf8')
@@ -1631,7 +1635,7 @@ function comfyLauncher(): Plugin {
req.on('end', () => {
try {
const { path: dirPath, recursive } = JSON.parse(body)
- const resolved = isAbsolute(dirPath) ? dirPath : join(os.homedir(), 'agent-workspace', dirPath)
+ const resolved = isAbsolute(dirPath) ? dirPath : join(os.homedir(), AGENT_WORKSPACE_DIR, dirPath)
const entries: Array<{ name: string; path: string; size: number; isDir: boolean; modified: number }> = []
// `recursive` arrived from the caller (file_list passes the model's
// flag straight through) and was then ignored, so in dev mode a
@@ -1676,7 +1680,7 @@ function comfyLauncher(): Plugin {
const { path: dirPath, pattern, max_results } = JSON.parse(body)
const os = require('os')
const fs = require('fs')
- const resolved = require('path').isAbsolute(dirPath) ? dirPath : join(os.homedir(), 'agent-workspace', dirPath)
+ const resolved = require('path').isAbsolute(dirPath) ? dirPath : join(os.homedir(), AGENT_WORKSPACE_DIR, dirPath)
const re = new RegExp(pattern)
const results: any[] = []
const max = max_results || 50
@@ -1725,7 +1729,7 @@ function comfyLauncher(): Plugin {
const { path: filePath } = JSON.parse(body)
const os = require('os')
const fs = require('fs')
- const resolved = require('path').isAbsolute(filePath) ? filePath : join(os.homedir(), 'agent-workspace', filePath)
+ const resolved = require('path').isAbsolute(filePath) ? filePath : join(os.homedir(), AGENT_WORKSPACE_DIR, filePath)
const stat = fs.statSync(resolved)
res.writeHead(200, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({