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.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat: Tauri production backend — standalone .exe with all features
PurpleDoubleDd660b9de7cfd
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 62bad412..2c49d986 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -338,6 +338,16 @@ dependencies = ["version_check",]+[[package]]+name = "core-foundation"+version = "0.9.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f"+dependencies = [+ "core-foundation-sys",+ "libc",+]+[[package]]name = "core-foundation"version = "0.10.1"@@ -361,9 +371,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97"dependencies = ["bitflags 2.11.0",- "core-foundation",+ "core-foundation 0.10.1","core-graphics-types",- "foreign-types",+ "foreign-types 0.5.0","libc",]@@ -374,7 +384,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"dependencies = ["bitflags 2.11.0",- "core-foundation",+ "core-foundation 0.10.1","libc",]@@ -697,6 +707,15 @@ version = "1.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"+[[package]]+name = "encoding_rs"+version = "0.8.35"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"+dependencies = [+ "cfg-if",+]+[[package]]name = "equivalent"version = "1.0.2"@@ -714,6 +733,16 @@ dependencies = ["typeid",]+[[package]]+name = "errno"+version = "0.3.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]+[[package]]name = "fastrand"version = "2.3.0"@@ -773,6 +802,15 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"+[[package]]+name = "foreign-types"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"+dependencies = [+ "foreign-types-shared 0.1.1",+]+[[package]]name = "foreign-types"version = "0.5.0"@@ -780,7 +818,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"dependencies = ["foreign-types-macros",- "foreign-types-shared",+ "foreign-types-shared 0.3.1",][[package]]@@ -794,6 +832,12 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "foreign-types-shared"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"+[[package]]name = "foreign-types-shared"version = "0.3.1"@@ -826,6 +870,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"dependencies = ["futures-core",+ "futures-sink",][[package]]@@ -1203,6 +1248,25 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "h2"+version = "0.4.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2f44da3a8150a6703ed5d34e164b875fd14c2cdab9af1252a9a1020bde2bdc54"+dependencies = [+ "atomic-waker",+ "bytes",+ "fnv",+ "futures-core",+ "futures-sink",+ "http",+ "indexmap 2.13.0",+ "slab",+ "tokio",+ "tokio-util",+ "tracing",+]+[[package]]name = "hashbrown"version = "0.12.3"@@ -1313,6 +1377,7 @@ dependencies = ["bytes","futures-channel","futures-core",+ "h2","http","http-body","httparse",@@ -1324,6 +1389,38 @@ dependencies = ["want",]+[[package]]+name = "hyper-rustls"+version = "0.27.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e3c93eb611681b207e1fe55d5a71ecf91572ec8a6705cdb6857f7d8d5242cf58"+dependencies = [+ "http",+ "hyper",+ "hyper-util",+ "rustls",+ "rustls-pki-types",+ "tokio",+ "tokio-rustls",+ "tower-service",+]++[[package]]+name = "hyper-tls"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0"+dependencies = [+ "bytes",+ "http-body-util",+ "hyper",+ "hyper-util",+ "native-tls",+ "tokio",+ "tokio-native-tls",+ "tower-service",+]+[[package]]name = "hyper-util"version = "0.1.20"@@ -1342,9 +1439,11 @@ dependencies = ["percent-encoding","pin-project-lite","socket2",+ "system-configuration","tokio","tower-service","tracing",+ "windows-registry",][[package]]@@ -1543,6 +1642,25 @@ dependencies = ["serde",]+[[package]]+name = "is-docker"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3"+dependencies = [+ "once_cell",+]++[[package]]+name = "is-wsl"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5"+dependencies = [+ "is-docker",+ "once_cell",+]+[[package]]name = "itoa"version = "1.0.18"@@ -1728,6 +1846,12 @@ dependencies = ["libc",]+[[package]]+name = "linux-raw-sys"+version = "0.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"+[[package]]name = "litemap"version = "0.8.1"@@ -1736,12 +1860,21 @@ checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77"[[package]]name = "locally-uncensored"-version = "1.2.0"+version = "1.2.1"dependencies = [+ "base64 0.22.1",+ "dirs",+ "futures-util",+ "regex",+ "reqwest 0.12.28","serde","serde_json","tauri","tauri-build",+ "tauri-plugin-shell",+ "tempfile",+ "tokio",+ "urlencoding",][[package]]@@ -1870,6 +2003,23 @@ dependencies = ["windows-sys 0.60.2",]+[[package]]+name = "native-tls"+version = "0.2.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2"+dependencies = [+ "libc",+ "log",+ "openssl",+ "openssl-probe",+ "openssl-sys",+ "schannel",+ "security-framework",+ "security-framework-sys",+ "tempfile",+]+[[package]]name = "ndk"version = "0.9.0"@@ -2078,12 +2228,78 @@ version = "1.21.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"+[[package]]+name = "open"+version = "5.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "43bb73a7fa3799b198970490a51174027ba0d4ec504b03cd08caf513d40024bc"+dependencies = [+ "dunce",+ "is-wsl",+ "libc",+ "pathdiff",+]++[[package]]+name = "openssl"+version = "0.10.76"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "951c002c75e16ea2c65b8c7e4d3d51d5530d8dfa7d060b4776828c88cfb18ecf"+dependencies = [+ "bitflags 2.11.0",+ "cfg-if",+ "foreign-types 0.3.2",+ "libc",+ "once_cell",+ "openssl-macros",+ "openssl-sys",+]++[[package]]+name = "openssl-macros"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]++[[package]]+name = "openssl-probe"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"++[[package]]+name = "openssl-sys"+version = "0.9.112"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "57d55af3b3e226502be1526dfdba67ab0e9c96fc293004e79576b2b9edb0dbdb"+dependencies = [+ "cc",+ "libc",+ "pkg-config",+ "vcpkg",+]+[[package]]name = "option-ext"version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"+[[package]]+name = "os_pipe"+version = "1.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967"+dependencies = [+ "libc",+ "windows-sys 0.61.2",+]+[[package]]name = "pango"version = "0.18.3"@@ -2132,6 +2348,12 @@ dependencies = ["windows-link 0.2.1",]+[[package]]+name = "pathdiff"+version = "0.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3"+[[package]]name = "percent-encoding"version = "2.3.2"@@ -2663,6 +2885,50 @@ version = "0.8.10"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"+[[package]]+name = "reqwest"+version = "0.12.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"+dependencies = [+ "base64 0.22.1",+ "bytes",+ "encoding_rs",+ "futures-channel",+ "futures-core",+ "futures-util",+ "h2",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-rustls",+ "hyper-tls",+ "hyper-util",+ "js-sys",+ "log",+ "mime",+ "native-tls",+ "percent-encoding",+ "pin-project-lite",+ "rustls-pki-types",+ "serde",+ "serde_json",+ "serde_urlencoded",+ "sync_wrapper",+ "tokio",+ "tokio-native-tls",+ "tokio-util",+ "tower",+ "tower-http",+ "tower-service",+ "url",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "wasm-streams 0.4.2",+ "web-sys",+]+[[package]]name = "reqwest"version = "0.13.2"@@ -2693,10 +2959,24 @@ dependencies = ["url","wasm-bindgen","wasm-bindgen-futures",- "wasm-streams",+ "wasm-streams 0.5.0","web-sys",]+[[package]]+name = "ring"+version = "0.17.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"+dependencies = [+ "cc",+ "cfg-if",+ "getrandom 0.2.17",+ "libc",+ "untrusted",+ "windows-sys 0.52.0",+]+[[package]]name = "rustc-hash"version = "2.1.2"@@ -2712,12 +2992,64 @@ dependencies = ["semver",]+[[package]]+name = "rustix"+version = "1.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"+dependencies = [+ "bitflags 2.11.0",+ "errno",+ "libc",+ "linux-raw-sys",+ "windows-sys 0.61.2",+]++[[package]]+name = "rustls"+version = "0.23.37"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "758025cb5fccfd3bc2fd74708fd4682be41d99e5dff73c377c0646c6012c73a4"+dependencies = [+ "once_cell",+ "rustls-pki-types",+ "rustls-webpki",+ "subtle",+ "zeroize",+]++[[package]]+name = "rustls-pki-types"+version = "1.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd"+dependencies = [+ "zeroize",+]++[[package]]+name = "rustls-webpki"+version = "0.103.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df33b2b81ac578cabaf06b89b0631153a3f416b0a886e8a7a1707fb51abbd1ef"+dependencies = [+ "ring",+ "rustls-pki-types",+ "untrusted",+]+[[package]]name = "rustversion"version = "1.0.22"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"+[[package]]+name = "ryu"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"+[[package]]name = "same-file"version = "1.0.6"@@ -2727,6 +3059,15 @@ dependencies = ["winapi-util",]+[[package]]+name = "schannel"+version = "0.1.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"+dependencies = [+ "windows-sys 0.61.2",+]+[[package]]name = "schemars"version = "0.8.22"@@ -2784,6 +3125,29 @@ version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"+[[package]]+name = "security-framework"+version = "3.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"+dependencies = [+ "bitflags 2.11.0",+ "core-foundation 0.10.1",+ "core-foundation-sys",+ "libc",+ "security-framework-sys",+]++[[package]]+name = "security-framework-sys"+version = "2.17.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"+dependencies = [+ "core-foundation-sys",+ "libc",+]+[[package]]name = "selectors"version = "0.24.0"@@ -2926,6 +3290,18 @@ dependencies = ["serde_core",]+[[package]]+name = "serde_urlencoded"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"+dependencies = [+ "form_urlencoded",+ "itoa",+ "ryu",+ "serde",+]+[[package]]name = "serde_with"version = "3.18.0"@@ -3009,12 +3385,54 @@ dependencies = ["digest",]+[[package]]+name = "shared_child"+version = "1.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e362d9935bc50f019969e2f9ecd66786612daae13e8f277be7bfb66e8bed3f7"+dependencies = [+ "libc",+ "sigchld",+ "windows-sys 0.60.2",+]+[[package]]name = "shlex"version = "1.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"+[[package]]+name = "sigchld"+version = "0.2.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47106eded3c154e70176fc83df9737335c94ce22f821c32d17ed1db1f83badb1"+dependencies = [+ "libc",+ "os_pipe",+ "signal-hook",+]++[[package]]+name = "signal-hook"+version = "0.3.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"+dependencies = [+ "libc",+ "signal-hook-registry",+]++[[package]]+name = "signal-hook-registry"+version = "1.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b"+dependencies = [+ "errno",+ "libc",+]+[[package]]name = "simd-adler32"version = "0.3.9"@@ -3164,6 +3582,12 @@ version = "0.11.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"+[[package]]+name = "subtle"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"+[[package]]name = "swift-rs"version = "1.0.7"@@ -3217,6 +3641,27 @@ dependencies = ["syn 2.0.117",]+[[package]]+name = "system-configuration"+version = "0.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"+dependencies = [+ "bitflags 2.11.0",+ "core-foundation 0.9.4",+ "system-configuration-sys",+]++[[package]]+name = "system-configuration-sys"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e1d1b10ced5ca923a1fcb8d03e96b8d3268065d724548c0211415ff6ac6bac4"+dependencies = [+ "core-foundation-sys",+ "libc",+]+[[package]]name = "system-deps"version = "6.2.2"@@ -3238,7 +3683,7 @@ checksum = "9103edf55f2da3c82aea4c7fab7c4241032bfeea0e71fa557d98e00e7ce7cc20"dependencies = ["bitflags 2.11.0","block2",- "core-foundation",+ "core-foundation 0.10.1","core-graphics","crossbeam-channel","dispatch2",@@ -3315,7 +3760,7 @@ dependencies = ["percent-encoding","plist","raw-window-handle",- "reqwest",+ "reqwest 0.13.2","serde","serde_json","serde_repr",@@ -3399,6 +3844,44 @@ dependencies = ["tauri-utils",]+[[package]]+name = "tauri-plugin"+version = "2.5.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddde7d51c907b940fb573006cdda9a642d6a7c8153657e88f8a5c3c9290cd4aa"+dependencies = [+ "anyhow",+ "glob",+ "plist",+ "schemars 0.8.22",+ "serde",+ "serde_json",+ "tauri-utils",+ "toml 0.9.12+spec-1.1.0",+ "walkdir",+]++[[package]]+name = "tauri-plugin-shell"+version = "2.3.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8457dbf9e2bab1edd8df22bb2c20857a59a9868e79cb3eac5ed639eec4d0c73b"+dependencies = [+ "encoding_rs",+ "log",+ "open",+ "os_pipe",+ "regex",+ "schemars 0.8.22",+ "serde",+ "serde_json",+ "shared_child",+ "tauri",+ "tauri-plugin",+ "thiserror 2.0.18",+ "tokio",+]+[[package]]name = "tauri-runtime"version = "2.10.1"@@ -3499,6 +3982,19 @@ dependencies = ["toml 0.9.12+spec-1.1.0",]+[[package]]+name = "tempfile"+version = "3.27.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"+dependencies = [+ "fastrand",+ "getrandom 0.4.2",+ "once_cell",+ "rustix",+ "windows-sys 0.61.2",+]+[[package]]name = "tendril"version = "0.4.3"@@ -3610,11 +4106,45 @@ dependencies = ["bytes","libc","mio",+ "parking_lot","pin-project-lite",+ "signal-hook-registry","socket2",+ "tokio-macros","windows-sys 0.61.2",]+[[package]]+name = "tokio-macros"+version = "2.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c55a2eff8b69ce66c84f85e1da1c233edc36ceb85a2058d11b0d6a3c7e7569c"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.117",+]++[[package]]+name = "tokio-native-tls"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2"+dependencies = [+ "native-tls",+ "tokio",+]++[[package]]+name = "tokio-rustls"+version = "0.26.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"+dependencies = [+ "rustls",+ "tokio",+]+[[package]]name = "tokio-util"version = "0.7.18"@@ -3896,6 +4426,12 @@ version = "0.2.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"+[[package]]+name = "untrusted"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"+[[package]]name = "url"version = "2.5.8"@@ -3909,6 +4445,12 @@ dependencies = ["serde_derive",]+[[package]]+name = "urlencoding"+version = "2.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"+[[package]]name = "urlpattern"version = "0.3.0"@@ -3945,6 +4487,12 @@ dependencies = ["wasm-bindgen",]+[[package]]+name = "vcpkg"+version = "0.2.15"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"+[[package]]name = "version-compare"version = "0.2.1"@@ -4103,6 +4651,19 @@ dependencies = ["wasmparser",]+[[package]]+name = "wasm-streams"+version = "0.4.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65"+dependencies = [+ "futures-util",+ "js-sys",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "web-sys",+]+[[package]]name = "wasm-streams"version = "0.5.0"@@ -4379,6 +4940,17 @@ dependencies = ["windows-link 0.1.3",]+[[package]]+name = "windows-registry"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"+dependencies = [+ "windows-link 0.2.1",+ "windows-result 0.4.1",+ "windows-strings 0.5.1",+]+[[package]]name = "windows-result"version = "0.3.4"@@ -4424,6 +4996,15 @@ dependencies = ["windows-targets 0.42.2",]+[[package]]+name = "windows-sys"+version = "0.52.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"+dependencies = [+ "windows-targets 0.52.6",+]+[[package]]name = "windows-sys"version = "0.59.0"@@ -4912,6 +5493,12 @@ dependencies = ["synstructure",]+[[package]]+name = "zeroize"+version = "1.8.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"+[[package]]name = "zerotrie"version = "0.2.3"diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 1a3e2062..d8eb3a80 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -10,8 +10,17 @@ tauri-build = { version = "2", features = [] }[dependencies]tauri = { version = "2", features = [] }+tauri-plugin-shell = "2"serde = { version = "1", features = ["derive"] }serde_json = "1"+tokio = { version = "1", features = ["full"] }+reqwest = { version = "0.12", features = ["stream", "blocking", "json"] }+dirs = "6"+regex = "1"+base64 = "0.22"+tempfile = "3"+futures-util = "0.3"+urlencoding = "2"[profile.release]panic = "abort"diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.jsonindex f9de4480..1540db67 100644--- a/src-tauri/capabilities/default.json+++ b/src-tauri/capabilities/default.json@@ -6,6 +6,9 @@"permissions": ["core:default","core:window:default",- "core:webview:default"+ "core:webview:default",+ "shell:allow-spawn",+ "shell:allow-stdin-write",+ "shell:allow-kill"]}diff --git a/src-tauri/resources/whisper_server.py b/src-tauri/resources/whisper_server.pynew file mode 100644index 00000000..5f8508aa--- /dev/null+++ b/src-tauri/resources/whisper_server.py@@ -0,0 +1,88 @@+"""+Persistent faster-whisper server for Locally Uncensored.+Communicates via stdin/stdout with line-based JSON protocol.++Input (one JSON per line on stdin):+ {"action": "transcribe", "path": "/tmp/audio.wav"}+ {"action": "status"}+ {"action": "quit"}++Output (one JSON per line on stdout):+ {"status": "ready", "backend": "faster-whisper"}+ {"transcript": "hello world", "language": "en"}+ {"error": "..."}+"""++import sys+import json+import os++def main():+ # Unbuffered stdout for real-time communication with Node.js+ sys.stdout.reconfigure(line_buffering=True)+ sys.stderr.reconfigure(line_buffering=True)++ print("Loading faster-whisper model...", file=sys.stderr, flush=True)++ try:+ from faster_whisper import WhisperModel+ except ImportError:+ respond({"status": "error", "error": "faster-whisper not installed"})+ sys.exit(1)++ # Load model once — this is the slow part (~170s on some systems)+ try:+ model = WhisperModel("base", device="cpu", compute_type="int8")+ print("Model loaded, ready for transcription.", file=sys.stderr, flush=True)+ except Exception as e:+ respond({"status": "error", "error": f"Model load failed: {e}"})+ sys.exit(1)++ # Signal readiness+ respond({"status": "ready", "backend": "faster-whisper"})++ # Main loop: read commands from stdin+ for line in sys.stdin:+ line = line.strip()+ if not line:+ continue++ try:+ cmd = json.loads(line)+ except json.JSONDecodeError:+ respond({"error": "Invalid JSON"})+ continue++ action = cmd.get("action", "")++ if action == "status":+ respond({"status": "ready", "backend": "faster-whisper"})++ elif action == "transcribe":+ audio_path = cmd.get("path", "")+ if not audio_path or not os.path.exists(audio_path):+ respond({"error": f"File not found: {audio_path}", "transcript": ""})+ continue++ try:+ segments, info = model.transcribe(audio_path)+ text = " ".join([s.text for s in segments]).strip()+ respond({"transcript": text, "language": info.language})+ except Exception as e:+ respond({"error": str(e), "transcript": ""})++ elif action == "quit":+ respond({"status": "stopped"})+ break++ else:+ respond({"error": f"Unknown action: {action}"})+++def respond(data: dict):+ """Write a JSON response line to stdout."""+ print(json.dumps(data), flush=True)+++if __name__ == "__main__":+ main()diff --git a/src-tauri/src/commands/agent.rs b/src-tauri/src/commands/agent.rsnew file mode 100644index 00000000..dfec8442--- /dev/null+++ b/src-tauri/src/commands/agent.rs@@ -0,0 +1,117 @@+use std::fs;+use std::io::Read;+use std::path::PathBuf;+use std::process::{Command, Stdio};++use tauri::State;++use crate::state::AppState;++fn agent_workspace() -> PathBuf {+ dirs::home_dir().unwrap_or_default().join("agent-workspace")+}++fn validate_path(path: &str) -> Result<PathBuf, String> {+ if path.contains("..") {+ return Err("Path traversal not allowed".to_string());+ }+ let workspace = agent_workspace();+ let full = workspace.join(path);+ if !full.starts_with(&workspace) {+ return Err("Path outside workspace".to_string());+ }+ Ok(full)+}++#[tauri::command]+pub fn execute_code(+ code: String,+ timeout: Option<u64>,+ state: State<'_, AppState>,+) -> Result<serde_json::Value, String> {+ let timeout_ms = timeout.unwrap_or(30000);++ let tmp_dir = std::env::temp_dir();+ let script_path = tmp_dir.join(format!("agent-code-{}.py", std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH).unwrap().as_millis()));++ fs::write(&script_path, &code)+ .map_err(|e| format!("Write temp script: {}", e))?;++ let workspace = agent_workspace();+ let _ = fs::create_dir_all(&workspace);++ let mut child = Command::new(&state.python_bin)+ .arg(&script_path)+ .current_dir(&workspace)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .map_err(|e| format!("Spawn Python: {}", e))?;++ // Poll-based timeout since std::process::Child has no wait_timeout+ let start = std::time::Instant::now();+ let timeout_dur = std::time::Duration::from_millis(timeout_ms);++ loop {+ match child.try_wait() {+ Ok(Some(status)) => {+ let mut stdout_str = String::new();+ let mut stderr_str = String::new();+ if let Some(mut stdout) = child.stdout.take() {+ let _ = stdout.read_to_string(&mut stdout_str);+ }+ if let Some(mut stderr) = child.stderr.take() {+ let _ = stderr.read_to_string(&mut stderr_str);+ }++ let _ = fs::remove_file(&script_path);+ return Ok(serde_json::json!({+ "stdout": stdout_str,+ "stderr": stderr_str,+ "exitCode": status.code().unwrap_or(-1),+ "timedOut": false,+ }));+ }+ Ok(None) => {+ if start.elapsed() > timeout_dur {+ let _ = child.kill();+ let _ = fs::remove_file(&script_path);+ return Ok(serde_json::json!({+ "stdout": "",+ "stderr": format!("Execution timed out after {}ms", timeout_ms),+ "exitCode": -1,+ "timedOut": true,+ }));+ }+ std::thread::sleep(std::time::Duration::from_millis(50));+ }+ Err(e) => {+ let _ = fs::remove_file(&script_path);+ return Err(format!("Wait error: {}", e));+ }+ }+ }+}++#[tauri::command]+pub fn file_read(path: String) -> Result<serde_json::Value, String> {+ let full_path = validate_path(&path)?;+ if !full_path.exists() {+ return Err(format!("File not found: {}", path));+ }+ let content = fs::read_to_string(&full_path)+ .map_err(|e| format!("Read error: {}", e))?;+ Ok(serde_json::json!({"content": content}))+}++#[tauri::command]+pub fn file_write(path: String, content: String) -> Result<serde_json::Value, String> {+ let full_path = validate_path(&path)?;+ if let Some(parent) = full_path.parent() {+ fs::create_dir_all(parent).map_err(|e| format!("Create dir: {}", e))?;+ }+ fs::write(&full_path, &content).map_err(|e| format!("Write error: {}", e))?;+ Ok(serde_json::json!({"status": "saved", "path": full_path.to_string_lossy()}))+}diff --git a/src-tauri/src/commands/download.rs b/src-tauri/src/commands/download.rsnew file mode 100644index 00000000..041bf240--- /dev/null+++ b/src-tauri/src/commands/download.rs@@ -0,0 +1,123 @@+use std::fs;+use std::path::PathBuf;+use std::time::Instant;++use futures_util::StreamExt;+use tauri::State;++use crate::state::{AppState, DownloadProgress};++fn models_dir(comfy_path: &Option<String>, subfolder: &str) -> Result<PathBuf, String> {+ let base = comfy_path.as_ref().ok_or("ComfyUI path not set")?;+ let dir = PathBuf::from(base).join("models").join(subfolder);+ fs::create_dir_all(&dir).map_err(|e| format!("Create models dir: {}", e))?;+ Ok(dir)+}++#[tauri::command]+pub async fn download_model(+ url: String,+ subfolder: String,+ filename: String,+ state: State<'_, AppState>,+) -> Result<serde_json::Value, String> {+ let comfy_path = {+ let p = state.comfy_path.lock().unwrap();+ p.clone()+ };++ let dest_dir = models_dir(&comfy_path, &subfolder)?;+ let dest_file = dest_dir.join(&filename);++ if dest_file.exists() {+ return Ok(serde_json::json!({"status": "exists", "path": dest_file.to_string_lossy()}));+ }++ let id = format!("{}-{}", subfolder, filename);++ // Initialize progress+ {+ let mut downloads = state.downloads.lock().unwrap();+ downloads.insert(id.clone(), DownloadProgress {+ progress: 0,+ total: 0,+ speed: 0.0,+ filename: filename.clone(),+ status: "connecting".to_string(),+ error: None,+ });+ }++ let id_clone = id.clone();+ let filename_clone = filename.clone();++ tokio::spawn(async move {+ match do_download(&url, &dest_file).await {+ Ok(_) => println!("[Download] Complete: {}", filename_clone),+ Err(e) => println!("[Download] Failed: {} - {}", filename_clone, e),+ }+ });++ Ok(serde_json::json!({"status": "started", "id": id}))+}++async fn do_download(url: &str, dest: &PathBuf) -> Result<(), String> {+ let client = reqwest::Client::builder()+ .user_agent("LocallyUncensored/1.3")+ .redirect(reqwest::redirect::Policy::limited(10))+ .build()+ .map_err(|e| e.to_string())?;++ let response = client.get(url)+ .send()+ .await+ .map_err(|e| format!("Request failed: {}", e))?;++ if !response.status().is_success() {+ return Err(format!("HTTP {}", response.status()));+ }++ let total = response.content_length().unwrap_or(0);++ let tmp_path = dest.with_extension("download");+ let mut file = tokio::fs::File::create(&tmp_path)+ .await+ .map_err(|e| format!("Create file: {}", e))?;++ let mut stream = response.bytes_stream();+ let mut downloaded: u64 = 0;+ let start = Instant::now();++ use tokio::io::AsyncWriteExt;+ while let Some(chunk) = stream.next().await {+ let chunk = chunk.map_err(|e| format!("Stream error: {}", e))?;+ file.write_all(&chunk).await.map_err(|e| format!("Write: {}", e))?;+ downloaded += chunk.len() as u64;++ // Log progress every ~1MB+ if downloaded % (1024 * 1024) < chunk.len() as u64 {+ let elapsed = start.elapsed().as_secs_f64();+ let speed = if elapsed > 0.0 { downloaded as f64 / elapsed } else { 0.0 };+ println!("[Download] {:.1} MB / {:.1} MB ({:.1} MB/s)",+ downloaded as f64 / 1048576.0,+ total as f64 / 1048576.0,+ speed / 1048576.0);+ }+ }++ file.flush().await.map_err(|e| format!("Flush: {}", e))?;+ drop(file);++ tokio::fs::rename(&tmp_path, dest)+ .await+ .map_err(|e| format!("Rename: {}", e))?;++ Ok(())+}++#[tauri::command]+pub fn download_progress(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let downloads = state.downloads.lock().unwrap();+ let map: std::collections::HashMap<String, DownloadProgress> = downloads.clone();+ Ok(serde_json::to_value(map).unwrap_or_default())+}diff --git a/src-tauri/src/commands/install.rs b/src-tauri/src/commands/install.rsnew file mode 100644index 00000000..03e671f5--- /dev/null+++ b/src-tauri/src/commands/install.rs@@ -0,0 +1,111 @@+use std::fs;+use std::path::PathBuf;+use std::process::{Command, Stdio};++use tauri::State;++use crate::state::AppState;++#[tauri::command]+pub fn install_comfyui(+ install_path: Option<String>,+ state: State<'_, AppState>,+) -> Result<serde_json::Value, String> {+ let mut install = state.install_status.lock().unwrap();+ if install.status == "installing" {+ return Ok(serde_json::json!({"status": "already_installing"}));+ }++ install.status = "installing".to_string();+ install.logs.clear();+ install.logs.push("Starting ComfyUI installation...".to_string());+ drop(install);++ let target_dir = install_path+ .map(PathBuf::from)+ .unwrap_or_else(|| dirs::home_dir().unwrap_or_default().join("ComfyUI"));++ let python_bin = state.python_bin.clone();++ std::thread::spawn(move || {+ // Step 1: Git clone+ println!("[Install] Cloning ComfyUI to {:?}", target_dir);+ let clone = Command::new("git")+ .args(["clone", "https://github.com/comfyanonymous/ComfyUI.git"])+ .arg(&target_dir)+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .output();++ match clone {+ Ok(output) if output.status.success() => {+ println!("[Install] Git clone successful");+ }+ Ok(output) => {+ let stderr = String::from_utf8_lossy(&output.stderr);+ // Directory might already exist+ if stderr.contains("already exists") {+ println!("[Install] ComfyUI directory already exists, updating...");+ let _ = Command::new("git")+ .args(["pull"])+ .current_dir(&target_dir)+ .output();+ } else {+ println!("[Install] Git clone failed: {}", stderr);+ return;+ }+ }+ Err(e) => {+ println!("[Install] Git not available: {}", e);+ return;+ }+ }++ // Step 2: Detect GPU and install PyTorch+ let has_nvidia = Command::new("nvidia-smi")+ .output()+ .map(|o| o.status.success())+ .unwrap_or(false);++ println!("[Install] GPU detected: {}", if has_nvidia { "NVIDIA CUDA" } else { "CPU only" });++ let torch_args = if has_nvidia {+ vec!["-m", "pip", "install", "torch", "torchvision", "torchaudio",+ "--index-url", "https://download.pytorch.org/whl/cu121"]+ } else {+ vec!["-m", "pip", "install", "torch", "torchvision", "torchaudio"]+ };++ println!("[Install] Installing PyTorch...");+ let _ = Command::new(&python_bin)+ .args(&torch_args)+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .output();++ // Step 3: Install ComfyUI requirements+ println!("[Install] Installing ComfyUI requirements...");+ let reqs = target_dir.join("requirements.txt");+ if reqs.exists() {+ let _ = Command::new(&python_bin)+ .args(["-m", "pip", "install", "-r"])+ .arg(&reqs)+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .output();+ }++ println!("[Install] ComfyUI installation complete");+ });++ Ok(serde_json::json!({"status": "installing"}))+}++#[tauri::command]+pub fn install_comfyui_status(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let install = state.install_status.lock().unwrap();+ Ok(serde_json::json!({+ "status": install.status,+ "logs": install.logs,+ }))+}diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsnew file mode 100644index 00000000..ce7b9bbe--- /dev/null+++ b/src-tauri/src/commands/mod.rs@@ -0,0 +1,7 @@+pub mod agent;+pub mod download;+pub mod install;+pub mod process;+pub mod proxy;+pub mod search;+pub mod whisper;diff --git a/src-tauri/src/commands/process.rs b/src-tauri/src/commands/process.rsnew file mode 100644index 00000000..29e6219d--- /dev/null+++ b/src-tauri/src/commands/process.rs@@ -0,0 +1,335 @@+use std::fs;+use std::path::{Path, PathBuf};+use std::process::{Command, Stdio};+use tauri::State;++use crate::state::AppState;++/// Skip these directories during ComfyUI search+const SKIP_DIRS: &[&str] = &[+ "node_modules", ".git", "__pycache__", "venv", ".venv", "site-packages",+ "Windows", "Program Files", "Program Files (x86)", "$Recycle.Bin", "AppData",+];++fn scan_for_comfyui(dir: &Path, depth: u32) -> Option<PathBuf> {+ if depth == 0 {+ return None;+ }+ let entries = fs::read_dir(dir).ok()?;+ for entry in entries.flatten() {+ let file_type = entry.file_type().ok()?;+ if !file_type.is_dir() {+ continue;+ }+ let name = entry.file_name();+ let name_str = name.to_string_lossy();+ if name_str.starts_with('.') || SKIP_DIRS.contains(&name_str.as_ref()) {+ continue;+ }+ let full = entry.path();+ // Check if this directory IS ComfyUI+ if name_str.eq_ignore_ascii_case("comfyui") && full.join("main.py").exists() {+ return Some(full);+ }+ // Recurse deeper+ if let Some(found) = scan_for_comfyui(&full, depth - 1) {+ return Some(found);+ }+ }+ None+}++pub fn find_comfyui_path() -> Option<String> {+ // 1. Check environment variable+ if let Ok(env_path) = std::env::var("COMFYUI_PATH") {+ if Path::new(&env_path).join("main.py").exists() {+ return Some(env_path);+ }+ }++ // 2. Read from app config+ if let Some(config_dir) = dirs::config_dir() {+ let config_file = config_dir.join("locally-uncensored").join("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) {+ if let Some(path) = config.get("comfyui_path").and_then(|v| v.as_str()) {+ if Path::new(path).join("main.py").exists() {+ return Some(path.to_string());+ }+ }+ }+ }+ }+ }++ let home = dirs::home_dir().unwrap_or_default();++ // 3. Check common fixed locations+ let fixed = [+ home.join("ComfyUI"),+ home.join("Desktop").join("ComfyUI"),+ home.join("Documents").join("ComfyUI"),+ PathBuf::from("C:\\ComfyUI"),+ ];+ for p in &fixed {+ if p.join("main.py").exists() {+ return Some(p.to_string_lossy().to_string());+ }+ }++ // 4. Recursive scan of Desktop, Documents, Downloads, and drive roots+ let mut scan_roots: Vec<PathBuf> = vec![+ home.join("Desktop"),+ home.join("Documents"),+ home.join("Downloads"),+ ];+ if cfg!(target_os = "windows") {+ scan_roots.push(PathBuf::from("C:\\"));+ scan_roots.push(PathBuf::from("D:\\"));+ } else {+ scan_roots.push(PathBuf::from("/opt"));+ scan_roots.push(PathBuf::from("/usr/local"));+ }++ for root in &scan_roots {+ if root.exists() {+ if let Some(found) = scan_for_comfyui(root, 4) {+ return Some(found.to_string_lossy().to_string());+ }+ }+ }++ None+}++fn is_comfyui_running() -> bool {+ reqwest::blocking::get("http://localhost:8188/system_stats")+ .map(|r| r.status().is_success())+ .unwrap_or(false)+}++#[tauri::command]+pub fn start_ollama(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ // Check if already running+ if let Ok(output) = Command::new("tasklist")+ .args(["/FI", "IMAGENAME eq ollama.exe"])+ .output()+ {+ let stdout = String::from_utf8_lossy(&output.stdout);+ if stdout.contains("ollama.exe") {+ println!("[Ollama] Already running");+ return Ok(serde_json::json!({"status": "already_running"}));+ }+ }++ println!("[Ollama] Starting...");+ let result = Command::new("ollama")+ .arg("serve")+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn();++ match result {+ Ok(_) => {+ println!("[Ollama] Started");+ Ok(serde_json::json!({"status": "started"}))+ }+ Err(e) => {+ println!("[Ollama] Failed to start: {}", e);+ Ok(serde_json::json!({"status": "error", "error": e.to_string()}))+ }+ }+}++#[tauri::command]+pub fn start_comfyui(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ if is_comfyui_running() {+ return Ok(serde_json::json!({"status": "already_running"}));+ }++ let comfy_path = {+ let path = state.comfy_path.lock().unwrap();+ path.clone()+ };++ let comfy_path = comfy_path+ .or_else(|| find_comfyui_path())+ .ok_or_else(|| "ComfyUI not found".to_string())?;++ // Store the path for future use+ {+ let mut path = state.comfy_path.lock().unwrap();+ *path = Some(comfy_path.clone());+ }++ println!("[ComfyUI] Starting from: {}", comfy_path);++ let child = Command::new(&state.python_bin)+ .args(["main.py", "--listen", "127.0.0.1", "--port", "8188"])+ .current_dir(&comfy_path)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .map_err(|e| format!("Failed to start ComfyUI: {}", e))?;++ // Store process+ {+ let mut proc = state.comfy_process.lock().unwrap();+ *proc = Some(child);+ }++ println!("[ComfyUI] Started");+ Ok(serde_json::json!({"status": "started", "path": comfy_path}))+}++#[tauri::command]+pub fn stop_comfyui(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let mut proc = state.comfy_process.lock().unwrap();+ if let Some(ref mut child) = *proc {+ let pid = child.id();+ if cfg!(target_os = "windows") {+ let _ = Command::new("taskkill")+ .args(["/pid", &pid.to_string(), "/T", "/F"])+ .output();+ } else {+ let _ = child.kill();+ }+ *proc = None;+ println!("[ComfyUI] Stopped");+ Ok(serde_json::json!({"status": "stopped"}))+ } else {+ Ok(serde_json::json!({"status": "not_running"}))+ }+}++#[tauri::command]+pub async fn comfyui_status(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let running = reqwest::get("http://localhost:8188/system_stats")+ .await+ .map(|r| r.status().is_success())+ .unwrap_or(false);++ let process_alive = {+ let proc = state.comfy_process.lock().unwrap();+ proc.is_some()+ };++ let path = {+ let p = state.comfy_path.lock().unwrap();+ p.clone()+ };++ let found = path.is_some() || find_comfyui_path().is_some();++ Ok(serde_json::json!({+ "running": running,+ "starting": process_alive && !running,+ "found": found,+ "path": path,+ "processAlive": process_alive,+ }))+}++#[tauri::command]+pub fn find_comfyui() -> Result<serde_json::Value, String> {+ match find_comfyui_path() {+ Some(path) => Ok(serde_json::json!({"found": true, "path": path})),+ None => Ok(serde_json::json!({"found": false, "path": null})),+ }+}++#[tauri::command]+pub fn set_comfyui_path(path: String, state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let main_py = Path::new(&path).join("main.py");+ if !main_py.exists() {+ return Err(format!("main.py not found in {}", path));+ }++ // Store in memory+ {+ let mut p = state.comfy_path.lock().unwrap();+ *p = Some(path.clone());+ }++ // Persist to config file+ if let Some(config_dir) = dirs::config_dir() {+ let app_config = config_dir.join("locally-uncensored");+ let _ = fs::create_dir_all(&app_config);+ let config_file = app_config.join("config.json");++ let mut config: serde_json::Value = if config_file.exists() {+ fs::read_to_string(&config_file)+ .ok()+ .and_then(|s| serde_json::from_str(&s).ok())+ .unwrap_or_else(|| serde_json::json!({}))+ } else {+ serde_json::json!({})+ };++ config["comfyui_path"] = serde_json::json!(path);+ let _ = fs::write(&config_file, serde_json::to_string_pretty(&config).unwrap());+ }++ Ok(serde_json::json!({"status": "saved", "path": path}))+}++/// Auto-start Ollama on app launch (called from setup)+pub fn auto_start_ollama(state: &AppState) {+ // Check if already running+ if let Ok(output) = Command::new("tasklist")+ .args(["/FI", "IMAGENAME eq ollama.exe"])+ .output()+ {+ let stdout = String::from_utf8_lossy(&output.stdout);+ if stdout.contains("ollama.exe") {+ println!("[Ollama] Already running");+ return;+ }+ }++ println!("[Ollama] Starting...");+ match Command::new("ollama")+ .arg("serve")+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ {+ Ok(_) => println!("[Ollama] Started"),+ Err(e) => println!("[Ollama] Failed to start: {}", e),+ }+}++/// Auto-start ComfyUI on app launch (called from setup)+pub fn auto_start_comfyui(state: &AppState) {+ if is_comfyui_running() {+ println!("[ComfyUI] Already running on port 8188");+ return;+ }++ match find_comfyui_path() {+ Some(path) => {+ println!("[ComfyUI] Auto-starting from: {}", path);+ *state.comfy_path.lock().unwrap() = Some(path.clone());++ match Command::new(&state.python_bin)+ .args(["main.py", "--listen", "127.0.0.1", "--port", "8188"])+ .current_dir(&path)+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ {+ Ok(child) => {+ *state.comfy_process.lock().unwrap() = Some(child);+ println!("[ComfyUI] Started");+ }+ Err(e) => println!("[ComfyUI] Failed to start: {}", e),+ }+ }+ None => println!("[ComfyUI] Not found. Install ComfyUI or set path in settings."),+ }+}diff --git a/src-tauri/src/commands/proxy.rs b/src-tauri/src/commands/proxy.rsnew file mode 100644index 00000000..8208bdc8--- /dev/null+++ b/src-tauri/src/commands/proxy.rs@@ -0,0 +1,28 @@+/// Proxy search requests to ollama.com (needed because frontend can't CORS to ollama.com)+#[tauri::command]+pub async fn ollama_search(query: String) -> Result<serde_json::Value, String> {+ let url = format!(+ "https://ollama.com/search?q={}&p=1",+ urlencoding::encode(&query)+ );++ let client = reqwest::Client::builder()+ .user_agent("LocallyUncensored/1.3")+ .timeout(std::time::Duration::from_secs(10))+ .build()+ .map_err(|e| e.to_string())?;++ let resp = client.get(&url)+ .header("Accept", "application/json")+ .send()+ .await+ .map_err(|e| format!("Ollama search: {}", e))?;++ let text = resp.text().await.map_err(|e| e.to_string())?;++ // Try to parse as JSON; if it's HTML, return empty results+ match serde_json::from_str::<serde_json::Value>(&text) {+ Ok(json) => Ok(json),+ Err(_) => Ok(serde_json::json!({"models": []})),+ }+}diff --git a/src-tauri/src/commands/search.rs b/src-tauri/src/commands/search.rsnew file mode 100644index 00000000..fcd0e80f--- /dev/null+++ b/src-tauri/src/commands/search.rs@@ -0,0 +1,233 @@+use std::sync::atomic::Ordering;+use tauri::State;++use crate::state::AppState;++#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]+pub struct SearchResult {+ pub title: String,+ pub url: String,+ pub snippet: String,+}++async fn try_searxng(query: &str, count: usize) -> Result<Vec<SearchResult>, String> {+ let url = format!(+ "http://localhost:8888/search?q={}&format=json&engines=google,duckduckgo,brave&categories=general",+ urlencoding::encode(query)+ );++ let client = reqwest::Client::builder()+ .timeout(std::time::Duration::from_secs(5))+ .build()+ .map_err(|e| e.to_string())?;++ let resp = client.get(&url)+ .send()+ .await+ .map_err(|e| format!("SearXNG: {}", e))?;++ let json: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?;++ let results = json.get("results")+ .and_then(|r| r.as_array())+ .map(|arr| {+ arr.iter()+ .take(count)+ .filter_map(|r| {+ Some(SearchResult {+ title: r.get("title")?.as_str()?.to_string(),+ url: r.get("url")?.as_str()?.to_string(),+ snippet: r.get("content").and_then(|c| c.as_str()).unwrap_or("").to_string(),+ })+ })+ .collect()+ })+ .unwrap_or_default();++ Ok(results)+}++async fn try_ddg(query: &str, count: usize) -> Result<Vec<SearchResult>, String> {+ let client = reqwest::Client::builder()+ .timeout(std::time::Duration::from_secs(10))+ .user_agent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36")+ .build()+ .map_err(|e| e.to_string())?;++ let resp = client.post("https://html.duckduckgo.com/html/")+ .form(&[("q", query)])+ .send()+ .await+ .map_err(|e| format!("DDG: {}", e))?;++ let html = resp.text().await.map_err(|e| e.to_string())?;++ // Parse results from HTML using regex+ let title_re = regex::Regex::new(r#"class="result__a"[^>]*>([^<]+)</a>"#).unwrap();+ let url_re = regex::Regex::new(r#"class="result__url"[^>]*href="([^"]+)">"#).unwrap();+ let snippet_re = regex::Regex::new(r#"class="result__snippet"[^>]*>([^<]+)"#).unwrap();++ let titles: Vec<String> = title_re.captures_iter(&html).map(|c| c[1].to_string()).collect();+ let urls: Vec<String> = url_re.captures_iter(&html).map(|c| c[1].to_string()).collect();+ let snippets: Vec<String> = snippet_re.captures_iter(&html).map(|c| c[1].to_string()).collect();++ let mut results = Vec::new();+ for i in 0..titles.len().min(count) {+ results.push(SearchResult {+ title: html_decode(&titles[i]),+ url: urls.get(i).cloned().unwrap_or_default(),+ snippet: snippets.get(i).map(|s| html_decode(s)).unwrap_or_default(),+ });+ }++ if results.is_empty() {+ Err("No DDG results".to_string())+ } else {+ Ok(results)+ }+}++async fn try_wikipedia(query: &str, count: usize) -> Result<Vec<SearchResult>, String> {+ let url = format!(+ "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch={}&format=json&srlimit={}",+ urlencoding::encode(query), count+ );++ let resp = reqwest::get(&url)+ .await+ .map_err(|e| format!("Wikipedia: {}", e))?;++ let json: serde_json::Value = resp.json().await.map_err(|e| e.to_string())?;++ let results: Vec<SearchResult> = json.pointer("/query/search")+ .and_then(|s| s.as_array())+ .map(|arr| {+ arr.iter()+ .filter_map(|r| {+ let title = r.get("title")?.as_str()?;+ Some(SearchResult {+ title: title.to_string(),+ url: format!("https://en.wikipedia.org/wiki/{}", urlencoding::encode(title)),+ snippet: r.get("snippet").and_then(|s| s.as_str())+ .map(|s| html_decode(&strip_html(s)))+ .unwrap_or_default(),+ })+ })+ .collect()+ })+ .unwrap_or_default();++ if results.is_empty() {+ Err("No Wikipedia results".to_string())+ } else {+ Ok(results)+ }+}++fn html_decode(s: &str) -> String {+ s.replace("&", "&")+ .replace("<", "<")+ .replace(">", ">")+ .replace(""", "\"")+ .replace("'", "'")+ .replace("'", "'")+}++fn strip_html(s: &str) -> String {+ let re = regex::Regex::new(r"<[^>]+>").unwrap();+ re.replace_all(s, "").to_string()+}++#[tauri::command]+pub async fn web_search(+ query: String,+ count: Option<usize>,+ state: State<'_, AppState>,+) -> Result<serde_json::Value, String> {+ let count = count.unwrap_or(5);++ // Try SearXNG first+ if state.searxng_available.load(Ordering::Relaxed) {+ if let Ok(results) = try_searxng(&query, count).await {+ return Ok(serde_json::json!({"results": results}));+ }+ }++ // Fallback to DuckDuckGo+ if let Ok(results) = try_ddg(&query, count).await {+ return Ok(serde_json::json!({"results": results}));+ }++ // Fallback to Wikipedia+ if let Ok(results) = try_wikipedia(&query, count).await {+ return Ok(serde_json::json!({"results": results}));+ }++ Ok(serde_json::json!({"results": [], "error": "All search tiers failed"}))+}++#[tauri::command]+pub async fn search_status(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let client = reqwest::Client::builder()+ .timeout(std::time::Duration::from_secs(3))+ .build()+ .map_err(|e| e.to_string())?;++ let available = client.get("http://localhost:8888")+ .send()+ .await+ .map(|r| r.status().is_success())+ .unwrap_or(false);++ state.searxng_available.store(available, Ordering::Relaxed);++ Ok(serde_json::json!({"searxng": available}))+}++#[tauri::command]+pub fn install_searxng(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let mut install = state.searxng_install.lock().unwrap();+ if install.status == "installing" {+ return Ok(serde_json::json!({"status": "already_installing"}));+ }++ install.status = "installing".to_string();+ install.logs.clear();+ install.logs.push("Pulling SearXNG Docker image...".to_string());+ drop(install);++ // Run docker pull + run in background+ std::thread::spawn(move || {+ let pull = std::process::Command::new("docker")+ .args(["pull", "searxng/searxng"])+ .output();++ match pull {+ Ok(output) if output.status.success() => {+ let _ = std::process::Command::new("docker")+ .args([+ "run", "-d", "--name", "searxng",+ "-p", "8888:8080",+ "-e", "INSTANCE_NAME=locally-uncensored",+ "searxng/searxng",+ ])+ .output();+ println!("[SearXNG] Installed and running on port 8888");+ }+ _ => {+ println!("[SearXNG] Docker pull failed. Is Docker installed?");+ }+ }+ });++ Ok(serde_json::json!({"status": "installing"}))+}++#[tauri::command]+pub fn searxng_status(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let install = state.searxng_install.lock().unwrap();+ Ok(serde_json::json!({+ "status": install.status,+ "logs": install.logs,+ }))+}diff --git a/src-tauri/src/commands/whisper.rs b/src-tauri/src/commands/whisper.rsnew file mode 100644index 00000000..3ed01780--- /dev/null+++ b/src-tauri/src/commands/whisper.rs@@ -0,0 +1,250 @@+use std::io::{BufRead, BufReader, Write};+use std::process::{Child, Command, Stdio};+use std::sync::mpsc;+use std::path::PathBuf;++use base64::Engine;+use tauri::{Manager, State};++use crate::state::AppState;++pub struct WhisperServer {+ process: Option<Child>,+ stdin_tx: Option<std::io::BufWriter<std::process::ChildStdin>>,+ response_rx: Option<mpsc::Receiver<serde_json::Value>>,+ pub ready: bool,+ pub backend: Option<String>,+}++impl WhisperServer {+ pub fn new() -> Self {+ Self {+ process: None,+ stdin_tx: None,+ response_rx: None,+ ready: false,+ backend: None,+ }+ }++ pub fn start(&mut self, python_bin: &str, script_path: &str) -> Result<(), String> {+ if self.process.is_some() {+ return Ok(());+ }++ println!("[Whisper] Starting persistent server: {} {}", python_bin, script_path);++ let mut child = Command::new(python_bin)+ .arg(script_path)+ .stdin(Stdio::piped())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .spawn()+ .map_err(|e| format!("Failed to start whisper server: {}", e))?;++ let stdin = child.stdin.take().ok_or("Failed to get stdin")?;+ let stdout = child.stdout.take().ok_or("Failed to get stdout")?;+ let stderr = child.stderr.take().ok_or("Failed to get stderr")?;++ self.stdin_tx = Some(std::io::BufWriter::new(stdin));++ // Channel for passing responses from reader thread to callers+ let (tx, rx) = mpsc::channel();+ self.response_rx = Some(rx);++ // Stdout reader thread — parses JSON lines from whisper_server.py+ let tx_clone = tx.clone();+ std::thread::spawn(move || {+ let reader = BufReader::new(stdout);+ for line in reader.lines() {+ if let Ok(line) = line {+ let trimmed = line.trim();+ if trimmed.is_empty() {+ continue;+ }+ if let Ok(json) = serde_json::from_str::<serde_json::Value>(trimmed) {+ let _ = tx_clone.send(json);+ }+ }+ }+ });++ // Stderr reader thread — log Python output+ std::thread::spawn(move || {+ let reader = BufReader::new(stderr);+ for line in reader.lines() {+ if let Ok(line) = line {+ if !line.trim().is_empty() {+ println!("[Whisper] {}", line.trim());+ }+ }+ }+ });++ self.process = Some(child);++ // Wait for the "ready" signal (up to 5 minutes for model loading)+ if let Some(ref rx) = self.response_rx {+ match rx.recv_timeout(std::time::Duration::from_secs(300)) {+ Ok(msg) => {+ if msg.get("status").and_then(|s| s.as_str()) == Some("ready") {+ self.ready = true;+ self.backend = msg.get("backend").and_then(|b| b.as_str()).map(|s| s.to_string());+ println!("[Whisper] Server ready (backend: {})", self.backend.as_deref().unwrap_or("unknown"));+ } else if msg.get("status").and_then(|s| s.as_str()) == Some("error") {+ let err = msg.get("error").and_then(|e| e.as_str()).unwrap_or("unknown");+ return Err(format!("Whisper server error: {}", err));+ }+ }+ Err(_) => {+ return Err("Whisper server did not become ready within 5 minutes".to_string());+ }+ }+ }++ Ok(())+ }++ pub fn send_command(&mut self, cmd: &serde_json::Value) -> Result<serde_json::Value, String> {+ if !self.ready {+ return Err("Whisper server not ready".to_string());+ }++ let stdin = self.stdin_tx.as_mut().ok_or("No stdin connection")?;+ let json_str = serde_json::to_string(cmd).map_err(|e| e.to_string())?;++ stdin.write_all(json_str.as_bytes()).map_err(|e| format!("stdin write: {}", e))?;+ stdin.write_all(b"\n").map_err(|e| format!("stdin newline: {}", e))?;+ stdin.flush().map_err(|e| format!("stdin flush: {}", e))?;++ // Wait for response (60s timeout for transcription)+ let rx = self.response_rx.as_ref().ok_or("No response channel")?;+ rx.recv_timeout(std::time::Duration::from_secs(60))+ .map_err(|_| "Whisper transcription timed out".to_string())+ }++ pub fn stop(&mut self) {+ if let Some(ref mut stdin) = self.stdin_tx {+ let _ = stdin.write_all(b"{\"action\":\"quit\"}\n");+ let _ = stdin.flush();+ }+ if let Some(ref mut child) = self.process {+ let _ = child.kill();+ }+ self.process = None;+ self.stdin_tx = None;+ self.response_rx = None;+ self.ready = false;+ println!("[Whisper] Server stopped");+ }+}++#[tauri::command]+pub fn whisper_status(state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let whisper = state.whisper.lock().unwrap();+ Ok(serde_json::json!({+ "available": whisper.process.is_some(),+ "backend": whisper.backend,+ "loading": whisper.process.is_some() && !whisper.ready,+ }))+}++#[tauri::command]+pub fn transcribe(audio_base64: String, content_type: String, state: State<'_, AppState>) -> Result<serde_json::Value, String> {+ let audio_bytes = base64::engine::general_purpose::STANDARD+ .decode(&audio_base64)+ .map_err(|e| format!("base64 decode: {}", e))?;++ if audio_bytes.is_empty() {+ return Err("Empty audio data".to_string());+ }++ // Determine file extension+ let ext = if content_type.contains("wav") { ".wav" }+ else if content_type.contains("mp3") || content_type.contains("mpeg") { ".mp3" }+ else if content_type.contains("ogg") { ".ogg" }+ else if content_type.contains("mp4") || content_type.contains("m4a") { ".m4a" }+ else { ".webm" };++ // Write to temp file+ let tmp_dir = std::env::temp_dir();+ let tmp_file = tmp_dir.join(format!("whisper-{}{}", std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH).unwrap().as_millis(), ext));++ std::fs::write(&tmp_file, &audio_bytes)+ .map_err(|e| format!("Write temp file: {}", e))?;++ let audio_path = tmp_file.to_string_lossy().replace('\\', "/");+ println!("[Whisper] Transcribing: {} ({:.1} KB)", audio_path, audio_bytes.len() as f64 / 1024.0);++ // Send to persistent whisper server+ let result = {+ let mut whisper = state.whisper.lock().unwrap();+ whisper.send_command(&serde_json::json!({+ "action": "transcribe",+ "path": audio_path,+ }))+ };++ // Clean up temp file+ let _ = std::fs::remove_file(&tmp_file);++ match result {+ Ok(response) => {+ if let Some(transcript) = response.get("transcript").and_then(|t| t.as_str()) {+ println!("[Whisper] Transcribed: \"{}\" (lang: {})",+ &transcript[..transcript.len().min(80)],+ response.get("language").and_then(|l| l.as_str()).unwrap_or("?"));+ }+ Ok(response)+ }+ Err(e) => Err(e),+ }+}++/// Auto-start whisper server on app launch+pub fn auto_start_whisper(app: &tauri::AppHandle, state: &AppState) {+ // Check if faster-whisper is installed+ let check = Command::new(&state.python_bin)+ .args(["-c", "import faster_whisper"])+ .output();++ match check {+ Ok(output) if output.status.success() => {+ println!("[Whisper] faster-whisper found, starting persistent server...");+ }+ _ => {+ println!("[Whisper] faster-whisper not installed — STT disabled");+ return;+ }+ }++ // Resolve whisper_server.py path from bundled resources+ let script_path: Option<PathBuf> = app.path()+ .resource_dir()+ .ok()+ .map(|d: PathBuf| d.join("resources").join("whisper_server.py"))+ .filter(|p: &PathBuf| p.exists())+ // Fallback: check public/ for dev mode+ .or_else(|| {+ let dev_path = PathBuf::from("public").join("whisper_server.py");+ if dev_path.exists() { Some(dev_path) } else { None }+ });++ match script_path {+ Some(path) => {+ let path_str: String = path.to_string_lossy().to_string();+ let python_bin = state.python_bin.clone();++ // Start synchronously — the model loading blocks but that's OK+ // since Tauri setup runs before the window is shown+ let mut ws = state.whisper.lock().unwrap();+ if let Err(e) = ws.start(&python_bin, &path_str) {+ println!("[Whisper] Failed to start: {}", e);+ }+ }+ None => {+ println!("[Whisper] whisper_server.py not found");+ }+ }+}diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rsindex e6ad770c..0d186365 100644--- a/src-tauri/src/main.rs+++ b/src-tauri/src/main.rs@@ -1,8 +1,62 @@// Prevents additional console window on Windows in release, DO NOT REMOVE!!#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]+mod commands;+mod python;+mod state;++use state::AppState;+use tauri::Manager;+fn main() {+ let app_state = AppState::new();+tauri::Builder::default()+ .plugin(tauri_plugin_shell::init())+ .manage(app_state)+ .invoke_handler(tauri::generate_handler![+ // Process management+ commands::process::start_ollama,+ commands::process::start_comfyui,+ commands::process::stop_comfyui,+ commands::process::comfyui_status,+ commands::process::find_comfyui,+ commands::process::set_comfyui_path,+ // Installation+ commands::install::install_comfyui,+ commands::install::install_comfyui_status,+ // Whisper STT+ commands::whisper::whisper_status,+ commands::whisper::transcribe,+ // Agent tools+ commands::agent::execute_code,+ commands::agent::file_read,+ commands::agent::file_write,+ // Downloads+ commands::download::download_model,+ commands::download::download_progress,+ // Web search+ commands::search::web_search,+ commands::search::search_status,+ commands::search::install_searxng,+ commands::search::searxng_status,+ // Proxy+ commands::proxy::ollama_search,+ ])+ .setup(|app| {+ let state = app.state::<AppState>();++ // Auto-start Ollama+ commands::process::auto_start_ollama(&state);++ // Auto-start ComfyUI+ commands::process::auto_start_comfyui(&state);++ // Start Whisper server (background — model loading takes minutes)+ commands::whisper::auto_start_whisper(app.handle(), &state);++ Ok(())+ }).run(tauri::generate_context!()).expect("error while running tauri application");}diff --git a/src-tauri/src/python.rs b/src-tauri/src/python.rsnew file mode 100644index 00000000..d355c746--- /dev/null+++ b/src-tauri/src/python.rs@@ -0,0 +1,25 @@+use std::process::Command;++/// Resolve the real Python binary path, filtering out Windows Store alias.+pub fn get_python_bin() -> String {+ if cfg!(not(target_os = "windows")) {+ return "python3".to_string();+ }++ if let Ok(output) = Command::new("where")+ .arg("python")+ .output()+ {+ if output.status.success() {+ let stdout = String::from_utf8_lossy(&output.stdout);+ for line in stdout.lines() {+ let path = line.trim();+ if !path.is_empty() && !path.contains("WindowsApps") {+ return path.to_string();+ }+ }+ }+ }++ "python".to_string()+}diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rsnew file mode 100644index 00000000..b92296c8--- /dev/null+++ b/src-tauri/src/state.rs@@ -0,0 +1,90 @@+use std::collections::HashMap;+use std::process::Child;+use std::sync::atomic::AtomicBool;+use std::sync::Mutex;++use crate::commands::whisper::WhisperServer;+use crate::python::get_python_bin;++#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]+pub struct DownloadProgress {+ pub progress: u64,+ pub total: u64,+ pub speed: f64,+ pub filename: String,+ pub status: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub error: Option<String>,+}++#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]+pub struct InstallState {+ pub status: String,+ pub logs: Vec<String>,+}++impl Default for InstallState {+ fn default() -> Self {+ Self {+ status: "idle".to_string(),+ logs: Vec::new(),+ }+ }+}++pub struct AppState {+ pub comfy_process: Mutex<Option<Child>>,+ pub comfy_logs: Mutex<Vec<String>>,+ pub comfy_path: Mutex<Option<String>>,+ pub whisper: Mutex<WhisperServer>,+ pub downloads: Mutex<HashMap<String, DownloadProgress>>,+ pub install_status: Mutex<InstallState>,+ pub searxng_install: Mutex<InstallState>,+ pub searxng_available: AtomicBool,+ pub python_bin: String,+}++impl AppState {+ pub fn new() -> Self {+ let python_bin = get_python_bin();+ println!("[Python] Resolved: {}", python_bin);++ Self {+ comfy_process: Mutex::new(None),+ comfy_logs: Mutex::new(Vec::new()),+ comfy_path: Mutex::new(None),+ whisper: Mutex::new(WhisperServer::new()),+ downloads: Mutex::new(HashMap::new()),+ install_status: Mutex::new(InstallState::default()),+ searxng_install: Mutex::new(InstallState::default()),+ searxng_available: AtomicBool::new(false),+ python_bin,+ }+ }+}++impl Drop for AppState {+ fn drop(&mut self) {+ // Kill ComfyUI process tree+ if let Ok(mut proc) = self.comfy_process.lock() {+ if let Some(ref mut child) = *proc {+ {+ let pid = child.id();+ if cfg!(target_os = "windows") {+ let _ = std::process::Command::new("taskkill")+ .args(["/pid", &pid.to_string(), "/T", "/F"])+ .output();+ } else {+ let _ = child.kill();+ }+ }+ println!("[ComfyUI] Stopped");+ }+ }++ // Stop Whisper server+ if let Ok(mut whisper) = self.whisper.lock() {+ whisper.stop();+ }+ }+}diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.jsonindex bc918ffc..0ed0b053 100644--- a/src-tauri/tauri.conf.json+++ b/src-tauri/tauri.conf.json@@ -27,6 +27,7 @@"bundle": {"active": true,"targets": "all",+ "resources": ["resources/whisper_server.py"],"icon": ["icons/32x32.png","icons/128x128.png",diff --git a/src/api/agents.ts b/src/api/agents.tsindex 857436d1..2a6615fb 100644--- a/src/api/agents.ts+++ b/src/api/agents.ts@@ -1,4 +1,5 @@import type { Tool, ToolName, ToolCall, AgentLogEntry } from "../types/agents";+import { backendCall, ollamaUrl } from "./backend";export const AGENT_TOOLS: Tool[] = [{@@ -260,52 +261,28 @@ export async function executeTool(): Promise<string> {switch (tool) {case "code_execute": {- const res = await fetch("/local-api/execute-code", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- code: args.code,- language: args.language || "python",- }),+ const data = await backendCall("execute_code", {+ code: args.code,+ timeout: 30000,});- if (!res.ok) throw new Error(`code_execute failed: ${res.statusText}`);- const data = await res.json();return `Exit code: ${data.exitCode ?? 0}\nStdout:\n${data.stdout || ""}\nStderr:\n${data.stderr || ""}`;}case "file_read": {- const res = await fetch("/local-api/file-read", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ path: args.path }),- });- if (!res.ok) throw new Error(`file_read failed: ${res.statusText}`);- const data = await res.json();+ const data = await backendCall("file_read", { path: args.path });return data.content || "";}case "file_write": {- const res = await fetch("/local-api/file-write", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ path: args.path, content: args.content }),- });- if (!res.ok) throw new Error(`file_write failed: ${res.statusText}`);- const data = await res.json();+ const data = await backendCall("file_write", { path: args.path, content: args.content });return data.message || "File written successfully";}case "web_search": {- const res = await fetch("/local-api/web-search", {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({- query: args.query,- maxResults: args.maxResults || 5,- }),+ const data = await backendCall("web_search", {+ query: args.query,+ count: args.maxResults || 5,});- if (!res.ok) throw new Error(`web_search failed: ${res.statusText}`);- const data = await res.json();if (Array.isArray(data.results)) {return data.results.map(@@ -330,7 +307,7 @@ export async function chatNonStreaming(model: string,messages: { role: string; content: string }[]): Promise<string> {- const res = await fetch("/api/chat", {+ const res = await fetch(ollamaUrl("/chat"), {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({diff --git a/src/api/backend.ts b/src/api/backend.tsnew file mode 100644index 00000000..63624224--- /dev/null+++ b/src/api/backend.ts@@ -0,0 +1,112 @@+/**+ * Backend abstraction layer for Locally Uncensored.+ *+ * - DEV MODE (npm run dev): Routes to Vite middleware via fetch("/local-api/...")+ * - PRODUCTION (Tauri .exe): Routes to Rust backend via invoke()+ *+ * Ollama/ComfyUI calls go directly to localhost in production (CSP allows it).+ */++let _invoke: ((cmd: string, args?: Record<string, unknown>) => Promise<unknown>) | null = null;++/** True when running inside a Tauri WebView (.exe), false in browser dev mode */+export function isTauri(): boolean {+ return !!(window as any).__TAURI__;+}++async function getInvoke() {+ if (!_invoke) {+ const { invoke } = await import("@tauri-apps/api/core");+ _invoke = invoke;+ }+ return _invoke;+}++/**+ * Call a backend command. Routes to Tauri invoke() or Vite fetch() automatically.+ */+export async function backendCall<T = any>(+ command: string,+ args?: Record<string, unknown>,+ options?: { method?: string; body?: any; headers?: Record<string, string> }+): Promise<T> {+ if (isTauri()) {+ const invoke = await getInvoke();+ return invoke(command, args || {}) as Promise<T>;+ }++ // Dev mode: map command to /local-api/ endpoint+ const endpointMap: Record<string, { path: string; method?: string }> = {+ start_comfyui: { path: "/local-api/start-comfyui", method: "POST" },+ stop_comfyui: { path: "/local-api/stop-comfyui", method: "POST" },+ comfyui_status: { path: "/local-api/comfyui-status" },+ find_comfyui: { path: "/local-api/find-comfyui" },+ set_comfyui_path: { path: "/local-api/set-comfyui-path", method: "POST" },+ install_comfyui: { path: "/local-api/install-comfyui", method: "POST" },+ install_comfyui_status: { path: "/local-api/install-comfyui" },+ whisper_status: { path: "/local-api/transcribe-status" },+ transcribe: { path: "/local-api/transcribe", method: "POST" },+ execute_code: { path: "/local-api/execute-code", method: "POST" },+ file_read: { path: "/local-api/file-read", method: "POST" },+ file_write: { path: "/local-api/file-write", method: "POST" },+ download_model: { path: "/local-api/download-model", method: "POST" },+ download_progress: { path: "/local-api/download-progress" },+ web_search: { path: "/local-api/web-search", method: "POST" },+ search_status: { path: "/local-api/search-status" },+ install_searxng: { path: "/local-api/install-searxng", method: "POST" },+ searxng_status: { path: "/local-api/install-searxng" },+ ollama_search: { path: "/ollama-search" },+ };++ const endpoint = endpointMap[command];+ if (!endpoint) {+ throw new Error(`Unknown backend command: ${command}`);+ }++ const method = options?.method || endpoint.method || "GET";+ const fetchOptions: RequestInit = { method };++ if (options?.body) {+ fetchOptions.body = options.body;+ if (options.headers) {+ fetchOptions.headers = options.headers;+ }+ } else if (args && method !== "GET") {+ fetchOptions.headers = { "Content-Type": "application/json" };+ fetchOptions.body = JSON.stringify(args);+ }++ // For GET with args, append as query params+ let url = endpoint.path;+ if (args && method === "GET") {+ const params = new URLSearchParams();+ for (const [key, value] of Object.entries(args)) {+ params.set(key, String(value));+ }+ url += `?${params.toString()}`;+ }++ const res = await fetch(url, fetchOptions);+ return res.json();+}++/** Get the base URL for Ollama API calls */+export function ollamaUrl(path: string): string {+ if (isTauri()) {+ return `http://localhost:11434${path}`;+ }+ return `/api${path}`;+}++/** Get the base URL for ComfyUI API calls */+export function comfyuiUrl(path: string): string {+ if (isTauri()) {+ return `http://localhost:8188${path}`;+ }+ return `/comfyui${path}`;+}++/** Get the WebSocket URL for ComfyUI */+export function comfyuiWsUrl(): string {+ return "ws://localhost:8188/ws";+}diff --git a/src/api/comfyui.ts b/src/api/comfyui.tsindex 313e4b97..7f312699 100644--- a/src/api/comfyui.ts+++ b/src/api/comfyui.ts@@ -1,3 +1,5 @@+import { comfyuiUrl } from "./backend"+// ─── Types ───export interface GenerateParams {@@ -59,7 +61,7 @@ function isVideoModelType(type: ModelType): boolean {export async function checkComfyConnection(): Promise<boolean> {try {- const res = await fetch('/comfyui/system_stats', { signal: AbortSignal.timeout(5000) })+ const res = await fetch(comfyuiUrl('/system_stats'), { signal: AbortSignal.timeout(5000) })return res.ok} catch {return false@@ -69,7 +71,7 @@ export async function checkComfyConnection(): Promise<boolean> {// Check if a specific node exists in ComfyUI (lightweight, single node check)async function nodeExists(nodeName: string): Promise<boolean> {try {- const res = await fetch(`/comfyui/object_info/${nodeName}`, { signal: AbortSignal.timeout(3000) })+ const res = await fetch(comfyuiUrl(`/object_info/${nodeName}`), { signal: AbortSignal.timeout(3000) })if (!res.ok) return falseconst data = await res.json()return !!(data && data[nodeName])@@ -80,7 +82,7 @@ async function nodeExists(nodeName: string): Promise<boolean> {export async function getCheckpoints(): Promise<string[]> {try {- const res = await fetch('/comfyui/object_info/CheckpointLoaderSimple')+ const res = await fetch(comfyuiUrl('/object_info/CheckpointLoaderSimple'))if (!res.ok) return []const data = await res.json()return data?.CheckpointLoaderSimple?.input?.required?.ckpt_name?.[0] ?? []@@ -92,7 +94,7 @@ export async function getCheckpoints(): Promise<string[]> {export async function getDiffusionModels(): Promise<string[]> {try {- const res = await fetch('/comfyui/object_info/UNETLoader')+ const res = await fetch(comfyuiUrl('/object_info/UNETLoader'))if (!res.ok) return []const data = await res.json()return data?.UNETLoader?.input?.required?.unet_name?.[0] ?? []@@ -104,7 +106,7 @@ export async function getDiffusionModels(): Promise<string[]> {export async function getVAEModels(): Promise<string[]> {try {- const res = await fetch('/comfyui/object_info/VAELoader')+ const res = await fetch(comfyuiUrl('/object_info/VAELoader'))if (!res.ok) return []const data = await res.json()return data?.VAELoader?.input?.required?.vae_name?.[0] ?? []@@ -116,7 +118,7 @@ export async function getVAEModels(): Promise<string[]> {export async function getCLIPModels(): Promise<string[]> {try {- const res = await fetch('/comfyui/object_info/CLIPLoader')+ const res = await fetch(comfyuiUrl('/object_info/CLIPLoader'))if (!res.ok) return []const data = await res.json()return data?.CLIPLoader?.input?.required?.clip_name?.[0] ?? []@@ -128,7 +130,7 @@ export async function getCLIPModels(): Promise<string[]> {export async function getSamplers(): Promise<string[]> {try {- const res = await fetch('/comfyui/object_info/KSampler')+ const res = await fetch(comfyuiUrl('/object_info/KSampler'))if (!res.ok) throw new Error('Failed')const data = await res.json()return data?.KSampler?.input?.required?.sampler_name?.[0] ?? []@@ -139,7 +141,7 @@ export async function getSamplers(): Promise<string[]> {export async function getSchedulers(): Promise<string[]> {try {- const res = await fetch('/comfyui/object_info/KSampler')+ const res = await fetch(comfyuiUrl('/object_info/KSampler'))if (!res.ok) throw new Error('Failed')const data = await res.json()return data?.KSampler?.input?.required?.scheduler?.[0] ?? []@@ -150,7 +152,7 @@ export async function getSchedulers(): Promise<string[]> {export async function getAnimateDiffModels(): Promise<string[]> {try {- const res = await fetch('/comfyui/object_info/ADE_LoadAnimateDiffModel')+ const res = await fetch(comfyuiUrl('/object_info/ADE_LoadAnimateDiffModel'))if (!res.ok) return []const data = await res.json()return data?.ADE_LoadAnimateDiffModel?.input?.required?.model_name?.[0] ?? []@@ -277,7 +279,7 @@ async function findAnimateDiffModel(): Promise<string> {// ─── Workflow Submission ───export async function submitWorkflow(workflow: Record<string, any>): Promise<string> {- const res = await fetch('/comfyui/prompt', {+ const res = await fetch(comfyuiUrl('/prompt'), {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ prompt: workflow }),@@ -292,13 +294,13 @@ export async function submitWorkflow(workflow: Record<string, any>): Promise<strexport async function cancelGeneration(): Promise<void> {try {- await fetch('/comfyui/interrupt', { method: 'POST' })+ await fetch(comfyuiUrl('/interrupt'), { method: 'POST' })} catch { /* best effort */ }}export async function getHistory(promptId: string): Promise<any> {try {- const res = await fetch(`/comfyui/history/${promptId}`)+ const res = await fetch(comfyuiUrl(`/history/${promptId}`))if (!res.ok) return nullconst data = await res.json()return data[promptId] ?? null@@ -308,7 +310,7 @@ export async function getHistory(promptId: string): Promise<any> {}export function getImageUrl(filename: string, subfolder: string = '', type: string = 'output'): string {- return `/comfyui/view?filename=${encodeURIComponent(filename)}&subfolder=${encodeURIComponent(subfolder)}&type=${type}&t=${Date.now()}`+ return comfyuiUrl(`/view?filename=${encodeURIComponent(filename)}&subfolder=${encodeURIComponent(subfolder)}&type=${type}&t=${Date.now()}`)}// ─── Validate params ───diff --git a/src/api/discover.ts b/src/api/discover.tsindex 9b621711..d98ba494 100644--- a/src/api/discover.ts+++ b/src/api/discover.ts@@ -1,3 +1,5 @@+import { backendCall } from "./backend"+export interface DiscoverModel {name: stringdescription: string@@ -24,18 +26,12 @@ export interface DownloadProgress {// ─── Download API ───export async function startModelDownload(url: string, subfolder: string, filename: string): Promise<{ status: string; id: string; error?: string }> {- const res = await fetch('/local-api/download-model', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ url, subfolder, filename }),- })- return res.json()+ return backendCall("download_model", { url, subfolder, filename })}export async function getDownloadProgress(): Promise<Record<string, DownloadProgress>> {try {- const res = await fetch('/local-api/download-progress')- return res.json()+ return await backendCall("download_progress")} catch {return {}}@@ -45,6 +41,12 @@ export async function getDownloadProgress(): Promise<Record<string, DownloadProgexport async function fetchAbliteratedModels(): Promise<DiscoverModel[]> {try {+ // In Tauri production mode, we can't proxy to ollama.com — fall back to curated list+ const { isTauri } = await import("./backend")+ if (isTauri()) {+ return getCuratedTextModels()+ }+const res = await fetch('/ollama-search?q=abliterated&p=1')const html = await res.text()diff --git a/src/api/ollama.ts b/src/api/ollama.tsindex 6309b2e7..e262ee36 100644--- a/src/api/ollama.ts+++ b/src/api/ollama.ts@@ -1,14 +1,15 @@import type { OllamaModel } from "../types/models"+import { ollamaUrl } from "./backend"export async function listModels(): Promise<OllamaModel[]> {- const res = await fetch("/api/tags")+ const res = await fetch(ollamaUrl("/tags"))if (!res.ok) throw new Error("Failed to fetch models")const data = await res.json()return (data.models || []).map((m: any) => ({ ...m, type: "text" as const }))}export async function showModel(name: string) {- const res = await fetch("/api/show", {+ const res = await fetch(ollamaUrl("/show"), {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ name }),@@ -36,7 +37,7 @@ export async function chatStream(options: { temperature?: number; top_p?: number; top_k?: number; num_predict?: number } = {},signal?: AbortSignal): Promise<Response> {- const res = await fetch("/api/chat", {+ const res = await fetch(ollamaUrl("/chat"), {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ model, messages, options, stream: true }),@@ -47,7 +48,7 @@ export async function chatStream(}export async function pullModel(name: string, signal?: AbortSignal): Promise<Response> {- const res = await fetch("/api/pull", {+ const res = await fetch(ollamaUrl("/pull"), {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ name, stream: true }),@@ -58,7 +59,7 @@ export async function pullModel(name: string, signal?: AbortSignal): Promise<Res}export async function deleteModel(name: string): Promise<void> {- const res = await fetch("/api/delete", {+ const res = await fetch(ollamaUrl("/delete"), {method: "DELETE",headers: { "Content-Type": "application/json" },body: JSON.stringify({ name }),@@ -68,7 +69,7 @@ export async function deleteModel(name: string): Promise<void> {export async function checkConnection(): Promise<boolean> {try {- await fetch("/api/tags")+ await fetch(ollamaUrl("/tags"))return true} catch {return falsediff --git a/src/api/rag.ts b/src/api/rag.tsindex 55f2d8ef..2b60f6c3 100644--- a/src/api/rag.ts+++ b/src/api/rag.ts@@ -1,5 +1,6 @@import { v4 as uuid } from "uuid"import type { DocumentMeta, TextChunk, RAGContext, VectorSearchResult } from "../types/rag"+import { ollamaUrl } from "./backend"export async function extractText(file: File): Promise<string> {const ext = file.name.split(".").pop()?.toLowerCase()@@ -56,7 +57,7 @@ export async function generateEmbeddings(texts: string[],model = "nomic-embed-text"): Promise<number[][]> {- const res = await fetch("/api/embed", {+ const res = await fetch(ollamaUrl("/embed"), {method: "POST",headers: { "Content-Type": "application/json" },body: JSON.stringify({ model, input: texts }),diff --git a/src/api/voice.ts b/src/api/voice.tsindex 5e7aae45..28965211 100644--- a/src/api/voice.ts+++ b/src/api/voice.ts@@ -1,3 +1,5 @@+import { backendCall, isTauri } from "./backend";+/*** Voice API — 100% local* STT: Local Whisper (faster-whisper or openai-whisper) via /local-api/transcribe@@ -139,9 +141,13 @@ export function stopSpeaking(): void {export async function checkWhisperAvailable(): Promise<{available: boolean;backend: string | null;+ loading?: boolean;error?: string;}> {try {+ if (isTauri()) {+ return await backendCall("whisper_status");+ }const res = await fetch("/local-api/transcribe-status");return res.json();} catch {@@ -150,6 +156,23 @@ export async function checkWhisperAvailable(): Promise<{}export async function transcribeAudio(audioBlob: Blob): Promise<string> {+ if (isTauri()) {+ // Convert blob to base64 for Tauri invoke+ const buffer = await audioBlob.arrayBuffer();+ const bytes = new Uint8Array(buffer);+ let binary = "";+ for (let i = 0; i < bytes.length; i++) {+ binary += String.fromCharCode(bytes[i]);+ }+ const audioBase64 = btoa(binary);+ const data = await backendCall("transcribe", {+ audio_base64: audioBase64,+ content_type: audioBlob.type || "audio/webm",+ });+ if (data.error) throw new Error(data.error);+ return data.transcript || "";+ }+const res = await fetch("/local-api/transcribe", {method: "POST",headers: { "Content-Type": audioBlob.type || "audio/webm" },diff --git a/src/components/agents/AgentView.tsx b/src/components/agents/AgentView.tsxindex 0a208c1b..f6dccf14 100644--- a/src/components/agents/AgentView.tsx+++ b/src/components/agents/AgentView.tsx@@ -1,4 +1,5 @@import { useState, useEffect } from 'react'+import { backendCall } from '../../api/backend'import { motion, AnimatePresence } from 'framer-motion'import { Bot, Play, Square, Trash2, Clock, Download, Loader2, CircleCheck, CircleAlert } from 'lucide-react'import { GlowButton } from '../ui/GlowButton'@@ -45,8 +46,7 @@ export function AgentView() {const checkSearxngStatus = async () => {try {- const res = await fetch('/local-api/install-searxng')- const data = await res.json()+ const data = await backendCall('searxng_status')setSearxngStatus({ installed: data.installed, running: data.running, dockerAvailable: data.dockerAvailable })} catch {setSearxngStatus({ installed: false, running: false, dockerAvailable: false })@@ -57,8 +57,7 @@ export function AgentView() {setSearxngInstalling(true)setSearxngMsg('Starting...')try {- const res = await fetch('/local-api/install-searxng', { method: 'POST' })- const data = await res.json()+ const data = await backendCall('install_searxng')if (data.error) {setSearxngMsg(data.error)setSearxngInstalling(false)@@ -72,8 +71,7 @@ export function AgentView() {}const poll = setInterval(async () => {try {- const statusRes = await fetch('/local-api/install-searxng')- const statusData = await statusRes.json()+ const statusData = await backendCall('searxng_status')const lastLog = statusData.logs?.length ? statusData.logs[statusData.logs.length - 1] : ''setSearxngMsg(lastLog || statusData.status)if (statusData.status === 'complete') {diff --git a/src/components/create/CreateView.tsx b/src/components/create/CreateView.tsxindex 970fbecb..a9ccab79 100644--- a/src/components/create/CreateView.tsx+++ b/src/components/create/CreateView.tsx@@ -1,5 +1,6 @@import { useEffect, useState, useCallback, useRef } from 'react'import { Image, Video, WifiOff, Loader2, CheckCircle, AlertTriangle, RefreshCw, Settings, FolderOpen, ExternalLink, Copy } from 'lucide-react'+import { backendCall } from '../../api/backend'import { useCreate } from '../../hooks/useCreate'import { useCreateStore } from '../../stores/createStore'import { PromptInput } from './PromptInput'@@ -39,8 +40,7 @@ export function CreateView() {const pollStatus = useCallback(async () => {try {- const res = await fetch('/local-api/comfyui-status', { signal: AbortSignal.timeout(3000) })- const data: ComfyStatus = await res.json()+ const data: ComfyStatus = await backendCall('comfyui_status')setStatus(data)if (data.logs?.length > 0) setStartupLogs(data.logs)@@ -86,7 +86,7 @@ export function CreateView() {const retryConnect = async () => {setRetrying(true)- try { await fetch('/local-api/start-comfyui') } catch { /* ignore */ }+ try { await backendCall('start_comfyui') } catch { /* ignore */ }// Single poll attemptsetTimeout(async () => {await pollStatus()@@ -118,12 +118,11 @@ export function CreateView() {setInstallError('')setInstallLogs([])try {- await fetch('/local-api/install-comfyui', { method: 'POST' })+ await backendCall('install_comfyui')// Poll install progressinstallPollRef.current = setInterval(async () => {try {- const res = await fetch('/local-api/install-comfyui')- const data = await res.json()+ const data = await backendCall('install_comfyui_status')setInstallLogs(data.logs || [])if (data.status === 'complete') {if (installPollRef.current) clearInterval(installPollRef.current)@@ -169,12 +168,7 @@ export function CreateView() {setPathSaving(true)setPathError('')try {- const res = await fetch('/local-api/set-comfyui-path', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ path: comfyPathInput.trim() }),- })- const data = await res.json()+ const data = await backendCall('set_comfyui_path', { path: comfyPathInput.trim() })if (data.status === 'ok') {setTimeout(() => pollStatus(), 2000)} else {