Skip to content

armgit / kokon

Public Imported from GitHub
0

Edit photos by describing the change, on your own GPU. A free, open-source alternative to Nano Banana and ChatGPT image editing: photos stay on your computer, no daily limit. One installer for Windows, Mac and Linux sets up the best open model (Qwen-Image 2.1). MCP server for AI agents.

Snapshot before UX redesign

Gabriele Lozupone7210c18d090b
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..89a4d87
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,11 @@
+/target
+node_modules
+/dist
+/mcp/dist
+/mcp/build
+/src-tauri/target
+/src-tauri/binaries/*.exe
+*.log
+/.test-data
+/dist-release
+/src-tauri/gen
diff --git a/Cargo.lock b/Cargo.lock
new file mode 100644
index 0000000..1de57ce
--- /dev/null
+++ b/Cargo.lock
@@ -0,0 +1,5862 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "adler2"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+
+[[package]]
+name = "aho-corasick"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "alloc-no-stdlib"
+version = "3.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"
+
+[[package]]
+name = "alloc-stdlib"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"
+dependencies = [
+ "alloc-no-stdlib",
+]
+
+[[package]]
+name = "android_system_properties"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+
+[[package]]
+name = "arboard"
+version = "3.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0348a1c054491f4bfe6ab86a7b6ab1e44e45d899005de92f58b3df180b36ddaf"
+dependencies = [
+ "clipboard-win",
+ "image",
+ "log",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-foundation",
+ "parking_lot",
+ "percent-encoding",
+ "windows-sys 0.60.2",
+ "wl-clipboard-rs",
+ "x11rb",
+]
+
+[[package]]
+name = "async-broadcast"
+version = "0.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532"
+dependencies = [
+ "event-listener",
+ "event-listener-strategy",
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-channel"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2"
+dependencies = [
+ "concurrent-queue",
+ "event-listener-strategy",
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-executor"
+version = "1.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a"
+dependencies = [
+ "async-task",
+ "concurrent-queue",
+ "fastrand",
+ "futures-lite",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
+name = "async-io"
+version = "2.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc"
+dependencies = [
+ "autocfg",
+ "cfg-if",
+ "concurrent-queue",
+ "futures-io",
+ "futures-lite",
+ "parking",
+ "polling",
+ "rustix",
+ "slab",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "async-lock"
+version = "3.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311"
+dependencies = [
+ "event-listener",
+ "event-listener-strategy",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "async-process"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75"
+dependencies = [
+ "async-channel",
+ "async-io",
+ "async-lock",
+ "async-signal",
+ "async-task",
+ "blocking",
+ "cfg-if",
+ "event-listener",
+ "futures-lite",
+ "rustix",
+]
+
+[[package]]
+name = "async-recursion"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "async-signal"
+version = "0.2.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485"
+dependencies = [
+ "async-io",
+ "async-lock",
+ "atomic-waker",
+ "cfg-if",
+ "futures-core",
+ "futures-io",
+ "rustix",
+ "signal-hook-registry",
+ "slab",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "async-task"
+version = "4.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"
+
+[[package]]
+name = "async-trait"
+version = "0.1.92"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "atk"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b"
+dependencies = [
+ "atk-sys",
+ "glib",
+ "libc",
+]
+
+[[package]]
+name = "atk-sys"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086"
+dependencies = [
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "atomic-waker"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+
+[[package]]
+name = "axum"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
+dependencies = [
+ "axum-core",
+ "bytes",
+ "form_urlencoded",
+ "futures-util",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-util",
+ "itoa",
+ "matchit",
+ "memchr",
+ "mime",
+ "percent-encoding",
+ "pin-project-lite",
+ "serde_core",
+ "serde_json",
+ "serde_path_to_error",
+ "serde_urlencoded",
+ "sync_wrapper",
+ "tokio",
+ "tower",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "axum-core"
+version = "0.5.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "http-body-util",
+ "mime",
+ "pin-project-lite",
+ "sync_wrapper",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "base64"
+version = "0.21.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"
+
+[[package]]
+name = "base64"
+version = "0.22.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
+
+[[package]]
+name = "base64"
+version = "0.23.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
+
+[[package]]
+name = "bit-set"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"
+dependencies = [
+ "bit-vec",
+]
+
+[[package]]
+name = "bit-vec"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"
+
+[[package]]
+name = "bitflags"
+version = "1.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
+
+[[package]]
+name = "bitflags"
+version = "2.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "block-buffer"
+version = "0.10.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
+dependencies = [
+ "generic-array",
+]
+
+[[package]]
+name = "block-buffer"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "block2"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
+dependencies = [
+ "objc2",
+]
+
+[[package]]
+name = "blocking"
+version = "1.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa"
+dependencies = [
+ "async-channel",
+ "async-task",
+ "futures-io",
+ "futures-lite",
+ "piper",
+]
+
+[[package]]
+name = "brotli"
+version = "9.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8b851b75c23ca7873623d612fe49bd1989aeb03d08fb9432187eb253d3d4c6b"
+dependencies = [
+ "alloc-no-stdlib",
+ "alloc-stdlib",
+ "brotli-decompressor",
+]
+
+[[package]]
+name = "brotli-decompressor"
+version = "6.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "941cd9bd4ddab83cb46fa5a2d428f1c857b24ac78cb876cf7beb710840934bd7"
+dependencies = [
+ "alloc-no-stdlib",
+ "alloc-stdlib",
+]
+
+[[package]]
+name = "bs58"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4"
+dependencies = [
+ "tinyvec",
+]
+
+[[package]]
+name = "bumpalo"
+version = "3.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
+
+[[package]]
+name = "bytemuck"
+version = "1.25.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
+
+[[package]]
+name = "byteorder"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
+
+[[package]]
+name = "byteorder-lite"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
+
+[[package]]
+name = "bytes"
+version = "1.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "cairo-rs"
+version = "0.18.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2"
+dependencies = [
+ "bitflags 2.13.2",
+ "cairo-sys-rs",
+ "glib",
+ "libc",
+ "once_cell",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "cairo-sys-rs"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51"
+dependencies = [
+ "glib-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "camino"
+version = "1.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "cargo-platform"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "cargo_metadata"
+version = "0.19.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba"
+dependencies = [
+ "camino",
+ "cargo-platform",
+ "semver",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "cargo_toml"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9"
+dependencies = [
+ "semver",
+ "serde",
+ "toml 1.1.6+spec-1.1.0",
+]
+
+[[package]]
+name = "cc"
+version = "1.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f74872d07caf508b30a21f6836e7d7016a2eaf7d9ff4f48deaa58cd8a0407630"
+dependencies = [
+ "find-msvc-tools",
+ "shlex",
+]
+
+[[package]]
+name = "cesu8"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c"
+
+[[package]]
+name = "cfb"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a347dcabdae9c31b0825fd6a8bed285ec9c2acb89c47827126d52fa4f59cece3"
+dependencies = [
+ "fnv",
+ "uuid",
+ "web-time",
+]
+
+[[package]]
+name = "cfg-expr"
+version = "0.15.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02"
+dependencies = [
+ "smallvec",
+ "target-lexicon",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+
+[[package]]
+name = "chrono"
+version = "0.4.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
+dependencies = [
+ "iana-time-zone",
+ "js-sys",
+ "num-traits",
+ "serde",
+ "wasm-bindgen",
+ "windows-link",
+]
+
+[[package]]
+name = "clipboard-win"
+version = "5.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4"
+dependencies = [
+ "error-code",
+]
+
+[[package]]
+name = "color_quant"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
+
+[[package]]
+name = "combine"
+version = "4.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfc320937d09e6de266b31b9afb480f197d7a861be86be7cb2ea7e5d1bfffc5e"
+dependencies = [
+ "bytes",
+ "memchr",
+]
+
+[[package]]
+name = "concurrent-queue"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "const-oid"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
+
+[[package]]
+name = "cookie"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"
+dependencies = [
+ "time",
+ "version_check",
+]
+
+[[package]]
+name = "core-foundation"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
+[[package]]
+name = "core-foundation-sys"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+
+[[package]]
+name = "core-graphics"
+version = "0.25.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97"
+dependencies = [
+ "bitflags 2.13.2",
+ "core-foundation",
+ "core-graphics-types",
+ "foreign-types",
+ "libc",
+]
+
+[[package]]
+name = "core-graphics-types"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"
+dependencies = [
+ "bitflags 2.13.2",
+ "core-foundation",
+ "libc",
+]
+
+[[package]]
+name = "cpufeatures"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "cpufeatures"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crc32fast"
+version = "1.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "crossbeam-channel"
+version = "0.5.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1"
+dependencies = [
+ "crossbeam-utils",
+]
+
+[[package]]
+name = "crossbeam-utils"
+version = "0.8.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
+
+[[package]]
+name = "crunchy"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+
+[[package]]
+name = "crypto-common"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
+dependencies = [
+ "generic-array",
+ "typenum",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "cssparser"
+version = "0.37.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98"
+dependencies = [
+ "cssparser-macros",
+ "dtoa-short",
+ "itoa",
+ "phf",
+ "smallvec",
+]
+
+[[package]]
+name = "cssparser-macros"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a"
+dependencies = [
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "ctor"
+version = "1.0.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d"
+
+[[package]]
+name = "darling"
+version = "0.24.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"
+dependencies = [
+ "darling_core",
+ "darling_macro",
+]
+
+[[package]]
+name = "darling_core"
+version = "0.24.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"
+dependencies = [
+ "ident_case",
+ "proc-macro2",
+ "quote",
+ "strsim",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "darling_macro"
+version = "0.24.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"
+dependencies = [
+ "darling_core",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "dbus"
+version = "0.9.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e"
+dependencies = [
+ "libc",
+ "libdbus-sys",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "defmt"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e2953bfe4f93bbd20cc71198842756f77d161884c99ebbabc41d80231ded88d1"
+dependencies = [
+ "bitflags 1.3.2",
+ "defmt-macros",
+]
+
+[[package]]
+name = "defmt-macros"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bad9c72e7ca2137e0dc3813245a0d282fd6daad32fd800af018306a9169b5fe8"
+dependencies = [
+ "defmt-parser",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "defmt-parser"
+version = "1.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10d60334b3b2e7c9d91ef8150abfb6fa4c1c39ebbcf4a81c2e346aad939fee3e"
+dependencies = [
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "deranged"
+version = "0.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "derive_more"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134"
+dependencies = [
+ "derive_more-impl",
+]
+
+[[package]]
+name = "derive_more-impl"
+version = "2.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "rustc_version",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "digest"
+version = "0.10.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
+dependencies = [
+ "block-buffer 0.10.4",
+ "crypto-common 0.1.7",
+]
+
+[[package]]
+name = "digest"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
+dependencies = [
+ "block-buffer 0.12.1",
+ "const-oid",
+ "crypto-common 0.2.2",
+]
+
+[[package]]
+name = "dirs"
+version = "7.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f"
+dependencies = [
+ "dirs-sys",
+]
+
+[[package]]
+name = "dirs-sys"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
+dependencies = [
+ "libc",
+ "option-ext",
+ "redox_users",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "dispatch2"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2",
+ "libc",
+ "objc2",
+]
+
+[[package]]
+name = "displaydoc"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "dlopen2"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e2c5bd4158e66d1e215c49b837e11d62f3267b30c92f1d171c4d3105e3dc4d4"
+dependencies = [
+ "dlopen2_derive",
+ "libc",
+ "once_cell",
+ "winapi",
+]
+
+[[package]]
+name = "dlopen2_derive"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fbbb781877580993a8707ec48672673ec7b81eeba04cfd2310bd28c08e47c8f"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "dom_query"
+version = "0.28.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc"
+dependencies = [
+ "bit-set",
+ "cssparser",
+ "foldhash 0.2.0",
+ "html5ever",
+ "precomputed-hash",
+ "selectors",
+ "tendril",
+]
+
+[[package]]
+name = "downcast-rs"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2"
+
+[[package]]
+name = "dpi"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "dtoa"
+version = "1.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590"
+
+[[package]]
+name = "dtoa-short"
+version = "0.3.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87"
+dependencies = [
+ "dtoa",
+]
+
+[[package]]
+name = "dunce"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
+
+[[package]]
+name = "dyn-clone"
+version = "1.0.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"
+
+[[package]]
+name = "embed-resource"
+version = "3.0.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f"
+dependencies = [
+ "cc",
+ "memchr",
+ "rustc_version",
+ "toml 1.1.6+spec-1.1.0",
+ "vswhom",
+ "winreg",
+]
+
+[[package]]
+name = "embed_plist"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"
+
+[[package]]
+name = "endi"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
+
+[[package]]
+name = "enumflags2"
+version = "0.7.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef"
+dependencies = [
+ "enumflags2_derive",
+ "serde",
+]
+
+[[package]]
+name = "enumflags2_derive"
+version = "0.7.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "erased-serde"
+version = "0.4.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2add8a07dd6a8d93ff627029c51de145e12686fbc36ecb298ac22e74cf02dec"
+dependencies = [
+ "serde",
+ "serde_core",
+ "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 = "error-code"
+version = "3.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7"
+
+[[package]]
+name = "event-listener"
+version = "5.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2"
+dependencies = [
+ "parking",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "event-listener-strategy"
+version = "0.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93"
+dependencies = [
+ "event-listener",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "fallible-iterator"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
+
+[[package]]
+name = "fallible-streaming-iterator"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
+
+[[package]]
+name = "fastrand"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"
+
+[[package]]
+name = "fax"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a"
+
+[[package]]
+name = "fdeflate"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
+dependencies = [
+ "simd-adler32",
+]
+
+[[package]]
+name = "field-offset"
+version = "0.3.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f"
+dependencies = [
+ "memoffset",
+ "rustc_version",
+]
+
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
+
+[[package]]
+name = "fixedbitset"
+version = "0.5.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99"
+
+[[package]]
+name = "flate2"
+version = "1.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
+dependencies = [
+ "crc32fast",
+ "miniz_oxide 0.9.1",
+ "zlib-rs",
+]
+
+[[package]]
+name = "fnv"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1"
+
+[[package]]
+name = "foldhash"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+
+[[package]]
+name = "foldhash"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+
+[[package]]
+name = "foreign-types"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"
+dependencies = [
+ "foreign-types-macros",
+ "foreign-types-shared",
+]
+
+[[package]]
+name = "foreign-types-macros"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "foreign-types-shared"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"
+
+[[package]]
+name = "form_urlencoded"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
+dependencies = [
+ "percent-encoding",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
+
+[[package]]
+name = "futures-executor"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-io"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed"
+
+[[package]]
+name = "futures-lite"
+version = "2.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad"
+dependencies = [
+ "fastrand",
+ "futures-core",
+ "futures-io",
+ "parking",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "futures-macro"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "futures-sink"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d"
+
+[[package]]
+name = "futures-task"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
+
+[[package]]
+name = "futures-util"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
+dependencies = [
+ "futures-core",
+ "futures-io",
+ "futures-macro",
+ "futures-sink",
+ "futures-task",
+ "memchr",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
+name = "gdk"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691"
+dependencies = [
+ "cairo-rs",
+ "gdk-pixbuf",
+ "gdk-sys",
+ "gio",
+ "glib",
+ "libc",
+ "pango",
+]
+
+[[package]]
+name = "gdk-pixbuf"
+version = "0.18.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec"
+dependencies = [
+ "gdk-pixbuf-sys",
+ "gio",
+ "glib",
+ "libc",
+ "once_cell",
+]
+
+[[package]]
+name = "gdk-pixbuf-sys"
+version = "0.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7"
+dependencies = [
+ "gio-sys",
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "gdk-sys"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7"
+dependencies = [
+ "cairo-sys-rs",
+ "gdk-pixbuf-sys",
+ "gio-sys",
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "pango-sys",
+ "pkg-config",
+ "system-deps",
+]
+
+[[package]]
+name = "gdkwayland-sys"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69"
+dependencies = [
+ "gdk-sys",
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "pkg-config",
+ "system-deps",
+]
+
+[[package]]
+name = "gdkx11"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3caa00e14351bebbc8183b3c36690327eb77c49abc2268dd4bd36b856db3fbfe"
+dependencies = [
+ "gdk",
+ "gdkx11-sys",
+ "gio",
+ "glib",
+ "libc",
+ "x11",
+]
+
+[[package]]
+name = "gdkx11-sys"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d"
+dependencies = [
+ "gdk-sys",
+ "glib-sys",
+ "libc",
+ "system-deps",
+ "x11",
+]
+
+[[package]]
+name = "generic-array"
+version = "0.14.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
+dependencies = [
+ "typenum",
+ "version_check",
+]
+
+[[package]]
+name = "gethostname"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8"
+dependencies = [
+ "rustix",
+ "windows-link",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi 5.3.0",
+ "wasip2",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi 6.0.0",
+]
+
+[[package]]
+name = "gif"
+version = "0.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"
+dependencies = [
+ "color_quant",
+ "weezl",
+]
+
+[[package]]
+name = "gio"
+version = "0.18.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-io",
+ "futures-util",
+ "gio-sys",
+ "glib",
+ "libc",
+ "once_cell",
+ "pin-project-lite",
+ "smallvec",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "gio-sys"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2"
+dependencies = [
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "system-deps",
+ "winapi",
+]
+
+[[package]]
+name = "glib"
+version = "0.18.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5"
+dependencies = [
+ "bitflags 2.13.2",
+ "futures-channel",
+ "futures-core",
+ "futures-executor",
+ "futures-task",
+ "futures-util",
+ "gio-sys",
+ "glib-macros",
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "memchr",
+ "once_cell",
+ "smallvec",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "glib-macros"
+version = "0.18.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc"
+dependencies = [
+ "heck 0.4.1",
+ "proc-macro-crate 2.0.2",
+ "proc-macro-error",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "glib-sys"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898"
+dependencies = [
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "glob"
+version = "0.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"
+
+[[package]]
+name = "gobject-sys"
+version = "0.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44"
+dependencies = [
+ "glib-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "gtk"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a"
+dependencies = [
+ "atk",
+ "cairo-rs",
+ "field-offset",
+ "futures-channel",
+ "gdk",
+ "gdk-pixbuf",
+ "gio",
+ "glib",
+ "gtk-sys",
+ "gtk3-macros",
+ "libc",
+ "pango",
+ "pkg-config",
+]
+
+[[package]]
+name = "gtk-sys"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414"
+dependencies = [
+ "atk-sys",
+ "cairo-sys-rs",
+ "gdk-pixbuf-sys",
+ "gdk-sys",
+ "gio-sys",
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "pango-sys",
+ "system-deps",
+]
+
+[[package]]
+name = "gtk3-macros"
+version = "0.18.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d"
+dependencies = [
+ "proc-macro-crate 1.3.1",
+ "proc-macro-error",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "half"
+version = "2.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
+dependencies = [
+ "cfg-if",
+ "crunchy",
+ "zerocopy",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
+
+[[package]]
+name = "hashbrown"
+version = "0.15.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
+dependencies = [
+ "foldhash 0.1.5",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+dependencies = [
+ "foldhash 0.2.0",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+dependencies = [
+ "foldhash 0.2.0",
+]
+
+[[package]]
+name = "hashlink"
+version = "0.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb"
+dependencies = [
+ "hashbrown 0.17.1",
+]
+
+[[package]]
+name = "heck"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "hermit-abi"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284"
+
+[[package]]
+name = "hex"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+
+[[package]]
+name = "html5ever"
+version = "0.39.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8"
+dependencies = [
+ "log",
+ "markup5ever",
+]
+
+[[package]]
+name = "http"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
+dependencies = [
+ "bytes",
+ "itoa",
+]
+
+[[package]]
+name = "http-body"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
+dependencies = [
+ "bytes",
+ "http",
+]
+
+[[package]]
+name = "http-body-util"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "httparse"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+
+[[package]]
+name = "httpdate"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
+
+[[package]]
+name = "hybrid-array"
+version = "0.4.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
+dependencies = [
+ "typenum",
+]
+
+[[package]]
+name = "hyper"
+version = "1.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "futures-channel",
+ "futures-core",
+ "http",
+ "http-body",
+ "httparse",
+ "httpdate",
+ "itoa",
+ "pin-project-lite",
+ "smallvec",
+ "tokio",
+ "want",
+]
+
+[[package]]
+name = "hyper-util"
+version = "0.1.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff"
+dependencies = [
+ "base64 0.23.1",
+ "bytes",
+ "futures-channel",
+ "futures-util",
+ "http",
+ "http-body",
+ "httparse",
+ "hyper",
+ "ipnet",
+ "libc",
+ "percent-encoding",
+ "pin-project-lite",
+ "socket2",
+ "tokio",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "iana-time-zone"
+version = "0.1.65"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
+dependencies = [
+ "android_system_properties",
+ "core-foundation-sys",
+ "iana-time-zone-haiku",
+ "js-sys",
+ "log",
+ "wasm-bindgen",
+ "windows-core",
+]
+
+[[package]]
+name = "iana-time-zone-haiku"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
+dependencies = [
+ "cc",
+]
+
+[[package]]
+name = "ico"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3e795dff5605e0f04bff85ca41b51a96b83e80b281e96231bcaaf1ac35103371"
+dependencies = [
+ "byteorder",
+ "png 0.17.16",
+]
+
+[[package]]
+name = "icu_collections"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"
+dependencies = [
+ "displaydoc",
+ "potential_utf",
+ "utf8_iter",
+ "yoke",
+ "zerofrom",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locale_core"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
+dependencies = [
+ "displaydoc",
+ "litemap",
+ "tinystr",
+ "writeable",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"
+dependencies = [
+ "icu_collections",
+ "icu_normalizer_data",
+ "icu_properties",
+ "icu_provider",
+ "smallvec",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"
+
+[[package]]
+name = "icu_properties"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"
+dependencies = [
+ "displaydoc",
+ "icu_collections",
+ "icu_locale_core",
+ "icu_properties_data",
+ "icu_provider",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_properties_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"
+
+[[package]]
+name = "icu_provider"
+version = "2.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
+dependencies = [
+ "displaydoc",
+ "icu_locale_core",
+ "writeable",
+ "yoke",
+ "zerofrom",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "ident_case"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39"
+
+[[package]]
+name = "idna"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
+dependencies = [
+ "idna_adapter",
+ "smallvec",
+ "utf8_iter",
+]
+
+[[package]]
+name = "idna_adapter"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
+dependencies = [
+ "icu_normalizer",
+ "icu_properties",
+]
+
+[[package]]
+name = "image"
+version = "0.25.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
+dependencies = [
+ "bytemuck",
+ "byteorder-lite",
+ "color_quant",
+ "gif",
+ "image-webp",
+ "moxcms",
+ "num-traits",
+ "png 0.18.1",
+ "tiff",
+ "zune-core",
+ "zune-jpeg",
+]
+
+[[package]]
+name = "image-webp"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
+dependencies = [
+ "byteorder-lite",
+ "quick-error",
+]
+
+[[package]]
+name = "indexmap"
+version = "1.9.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"
+dependencies = [
+ "autocfg",
+ "hashbrown 0.12.3",
+ "serde",
+]
+
+[[package]]
+name = "indexmap"
+version = "2.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.17.1",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "infer"
+version = "0.22.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4"
+dependencies = [
+ "cfb",
+]
+
+[[package]]
+name = "ipnet"
+version = "2.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
+
+[[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"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "javascriptcore-rs"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc"
+dependencies = [
+ "bitflags 1.3.2",
+ "glib",
+ "javascriptcore-rs-sys",
+]
+
+[[package]]
+name = "javascriptcore-rs-sys"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124"
+dependencies = [
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "jiff"
+version = "0.2.37"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ab1baf72f08796de0260609515130699b890ac25f30e610ad894bc5856cafdb"
+dependencies = [
+ "defmt",
+ "jiff-core",
+ "jiff-static",
+ "jiff-tzdb-platform",
+ "log",
+ "portable-atomic",
+ "portable-atomic-util",
+ "serde_core",
+ "windows-link",
+]
+
+[[package]]
+name = "jiff-core"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e52fe76043ccecc9005d2305ebaadf7d7fc0cc89ca6baa10a94d6bc68c7128c"
+dependencies = [
+ "defmt",
+ "log",
+]
+
+[[package]]
+name = "jiff-static"
+version = "0.2.37"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "378268a1116ad67ae6228701118ac9f491d78fda38a40a1f1a9e1348de6f7212"
+dependencies = [
+ "jiff-core",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "jiff-tzdb"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "142bd39932ad231f10513df9ab62661fead8719872150b7ad02a2df79f4e141e"
+
+[[package]]
+name = "jiff-tzdb-platform"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8"
+dependencies = [
+ "jiff-tzdb",
+]
+
+[[package]]
+name = "jni"
+version = "0.21.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97"
+dependencies = [
+ "cesu8",
+ "cfg-if",
+ "combine",
+ "jni-sys 0.3.1",
+ "log",
+ "thiserror 1.0.69",
+ "walkdir",
+ "windows-sys 0.45.0",
+]
+
+[[package]]
+name = "jni-sys"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258"
+dependencies = [
+ "jni-sys 0.4.1",
+]
+
+[[package]]
+name = "jni-sys"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
+dependencies = [
+ "jni-sys-macros",
+]
+
+[[package]]
+name = "jni-sys-macros"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
+dependencies = [
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "js-sys"
+version = "0.3.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"
+dependencies = [
+ "cfg-if",
+ "futures-util",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "json-patch"
+version = "4.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72"
+dependencies = [
+ "jsonptr",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "jsonptr"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a5a3cc660ba5d72bce0b3bb295bf20847ccbb40fd423f3f05b61273672e561fe"
+dependencies = [
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "keyboard-types"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d"
+dependencies = [
+ "bitflags 2.13.2",
+ "serde",
+]
+
+[[package]]
+name = "lazy_static"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb"
+
+[[package]]
+name = "libappindicator"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a"
+dependencies = [
+ "glib",
+ "gtk",
+ "gtk-sys",
+ "libappindicator-sys",
+ "log",
+]
+
+[[package]]
+name = "libappindicator-sys"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf"
+dependencies = [
+ "gtk-sys",
+ "libloading",
+ "once_cell",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.190"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
+
+[[package]]
+name = "libdbus-sys"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043"
+dependencies = [
+ "pkg-config",
+]
+
+[[package]]
+name = "libloading"
+version = "0.7.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f"
+dependencies = [
+ "cfg-if",
+ "winapi",
+]
+
+[[package]]
+name = "libredox"
+version = "0.1.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "libsqlite3-sys"
+version = "0.38.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1d20bef17f513b9b3004532233187769cd072d790971f4e4da0e346eb6401e8"
+dependencies = [
+ "cc",
+ "pkg-config",
+ "vcpkg",
+]
+
+[[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.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
+
+[[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.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
+
+[[package]]
+name = "markup5ever"
+version = "0.39.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de"
+dependencies = [
+ "log",
+ "tendril",
+ "web_atoms",
+]
+
+[[package]]
+name = "matchers"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
+dependencies = [
+ "regex-automata",
+]
+
+[[package]]
+name = "matchit"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "memoffset"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "mime"
+version = "0.3.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
+
+[[package]]
+name = "miniz_oxide"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "miniz_oxide"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "mio"
+version = "1.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
+dependencies = [
+ "libc",
+ "wasi",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "moxcms"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
+dependencies = [
+ "num-traits",
+ "pxfm",
+]
+
+[[package]]
+name = "muda"
+version = "0.20.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cca139e57da4383727f189e43e66e84fa372347027fc996f9f1a007ec0a37996"
+dependencies = [
+ "crossbeam-channel",
+ "dpi",
+ "gtk",
+ "keyboard-types",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-core-foundation",
+ "objc2-foundation",
+ "once_cell",
+ "png 0.18.1",
+ "serde",
+ "thiserror 2.0.21",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "ndk"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"
+dependencies = [
+ "bitflags 2.13.2",
+ "jni-sys 0.3.1",
+ "log",
+ "ndk-sys",
+ "num_enum",
+ "raw-window-handle",
+ "thiserror 1.0.69",
+]
+
+[[package]]
+name = "ndk-context"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b"
+
+[[package]]
+name = "ndk-sys"
+version = "0.6.0+11769913"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873"
+dependencies = [
+ "jni-sys 0.3.1",
+]
+
+[[package]]
+name = "new_debug_unreachable"
+version = "1.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"
+
+[[package]]
+name = "nom"
+version = "8.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "ntapi"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae"
+dependencies = [
+ "winapi",
+]
+
+[[package]]
+name = "nu-ansi-term"
+version = "0.50.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "num-conv"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "num_enum"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26"
+dependencies = [
+ "num_enum_derive",
+ "rustversion",
+]
+
+[[package]]
+name = "num_enum_derive"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8"
+dependencies = [
+ "proc-macro-crate 3.5.0",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "objc2"
+version = "0.6.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
+dependencies = [
+ "objc2-encode",
+ "objc2-exception-helper",
+]
+
+[[package]]
+name = "objc2-app-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-foundation",
+ "objc2-quartz-core",
+]
+
+[[package]]
+name = "objc2-cloud-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c"
+dependencies = [
+ "bitflags 2.13.2",
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-core-data"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa"
+dependencies = [
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-core-foundation"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
+dependencies = [
+ "bitflags 2.13.2",
+ "dispatch2",
+ "objc2",
+]
+
+[[package]]
+name = "objc2-core-graphics"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"
+dependencies = [
+ "bitflags 2.13.2",
+ "dispatch2",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-io-surface",
+]
+
+[[package]]
+name = "objc2-core-image"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006"
+dependencies = [
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-core-location"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009"
+dependencies = [
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-core-text"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"
+dependencies = [
+ "bitflags 2.13.2",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+]
+
+[[package]]
+name = "objc2-encode"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
+
+[[package]]
+name = "objc2-exception-helper"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c7a1c5fbb72d7735b076bb47b578523aedc40f3c439bea6dfd595c089d79d98a"
+dependencies = [
+ "cc",
+]
+
+[[package]]
+name = "objc2-foundation"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2",
+ "libc",
+ "objc2",
+ "objc2-core-foundation",
+]
+
+[[package]]
+name = "objc2-io-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15"
+dependencies = [
+ "libc",
+ "objc2-core-foundation",
+]
+
+[[package]]
+name = "objc2-io-surface"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"
+dependencies = [
+ "bitflags 2.13.2",
+ "objc2",
+ "objc2-core-foundation",
+]
+
+[[package]]
+name = "objc2-open-directory"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb82bed227edf5201dfedf072bba4015a33d3d4a98519837295a90f0a23f676d"
+dependencies = [
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-quartz-core"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"
+dependencies = [
+ "bitflags 2.13.2",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-ui-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2",
+ "objc2",
+ "objc2-cloud-kit",
+ "objc2-core-data",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-core-image",
+ "objc2-core-location",
+ "objc2-core-text",
+ "objc2-foundation",
+ "objc2-quartz-core",
+ "objc2-user-notifications",
+]
+
+[[package]]
+name = "objc2-user-notifications"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e"
+dependencies = [
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-web-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-core-foundation",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "open"
+version = "5.4.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aa576c76302b7b808eecc68061e67336c47833ef9d22caa74dda10fa9675eebc"
+dependencies = [
+ "dunce",
+ "is-wsl",
+ "libc",
+]
+
+[[package]]
+name = "option-ext"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
+
+[[package]]
+name = "ordered-stream"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50"
+dependencies = [
+ "futures-core",
+ "pin-project-lite",
+]
+
+[[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"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4"
+dependencies = [
+ "gio",
+ "glib",
+ "libc",
+ "once_cell",
+ "pango-sys",
+]
+
+[[package]]
+name = "pango-sys"
+version = "0.18.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5"
+dependencies = [
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "parking"
+version = "2.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
+
+[[package]]
+name = "parking_lot"
+version = "0.12.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
+dependencies = [
+ "lock_api",
+ "parking_lot_core",
+]
+
+[[package]]
+name = "parking_lot_core"
+version = "0.9.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall",
+ "smallvec",
+ "windows-link",
+]
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+
+[[package]]
+name = "petgraph"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455"
+dependencies = [
+ "fixedbitset",
+ "hashbrown 0.15.5",
+ "indexmap 2.14.2",
+]
+
+[[package]]
+name = "phf"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"
+dependencies = [
+ "phf_macros",
+ "phf_shared",
+ "serde",
+]
+
+[[package]]
+name = "phf_codegen"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1"
+dependencies = [
+ "phf_generator",
+ "phf_shared",
+]
+
+[[package]]
+name = "phf_generator"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"
+dependencies = [
+ "fastrand",
+ "phf_shared",
+]
+
+[[package]]
+name = "phf_macros"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"
+dependencies = [
+ "phf_generator",
+ "phf_shared",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "phf_shared"
+version = "0.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"
+dependencies = [
+ "siphasher",
+]
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
+
+[[package]]
+name = "piper"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1"
+dependencies = [
+ "atomic-waker",
+ "fastrand",
+ "futures-io",
+]
+
+[[package]]
+name = "pkg-config"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
+
+[[package]]
+name = "plist"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2896bade328c13f7042a297ea5ac5b0951f6cf989dea5f32c2fd98da398195cb"
+dependencies = [
+ "base64 0.23.1",
+ "indexmap 2.14.2",
+ "quick-xml 0.42.0",
+ "serde",
+ "time",
+]
+
+[[package]]
+name = "png"
+version = "0.17.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"
+dependencies = [
+ "bitflags 1.3.2",
+ "crc32fast",
+ "fdeflate",
+ "flate2",
+ "miniz_oxide 0.8.9",
+]
+
+[[package]]
+name = "png"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
+dependencies = [
+ "bitflags 2.13.2",
+ "crc32fast",
+ "fdeflate",
+ "flate2",
+ "miniz_oxide 0.8.9",
+]
+
+[[package]]
+name = "polling"
+version = "3.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218"
+dependencies = [
+ "cfg-if",
+ "concurrent-queue",
+ "hermit-abi",
+ "pin-project-lite",
+ "rustix",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "portable-atomic"
+version = "1.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"
+
+[[package]]
+name = "portable-atomic-util"
+version = "0.2.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"
+dependencies = [
+ "portable-atomic",
+]
+
+[[package]]
+name = "potential_utf"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
+dependencies = [
+ "zerovec",
+]
+
+[[package]]
+name = "powerfmt"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958"
+
+[[package]]
+name = "precomputed-hash"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c"
+
+[[package]]
+name = "proc-macro-crate"
+version = "1.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919"
+dependencies = [
+ "once_cell",
+ "toml_edit 0.19.15",
+]
+
+[[package]]
+name = "proc-macro-crate"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24"
+dependencies = [
+ "toml_datetime 0.6.3",
+ "toml_edit 0.20.2",
+]
+
+[[package]]
+name = "proc-macro-crate"
+version = "3.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"
+dependencies = [
+ "toml_edit 0.25.15+spec-1.1.0",
+]
+
+[[package]]
+name = "proc-macro-error"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c"
+dependencies = [
+ "proc-macro-error-attr",
+ "proc-macro2",
+ "quote",
+ "syn 1.0.109",
+ "version_check",
+]
+
+[[package]]
+name = "proc-macro-error-attr"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "version_check",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "pxfm"
+version = "0.1.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
+
+[[package]]
+name = "qls-core"
+version = "1.0.0"
+dependencies = [
+ "anyhow",
+ "base64 0.23.1",
+ "chrono",
+ "dirs",
+ "hex",
+ "image",
+ "png 0.18.1",
+ "regex",
+ "reqwest",
+ "rusqlite",
+ "serde",
+ "serde_json",
+ "sha2 0.11.0",
+ "sysinfo",
+ "tempfile",
+ "thiserror 2.0.21",
+ "tokio",
+ "tracing",
+ "uuid",
+ "windows",
+]
+
+[[package]]
+name = "qls-service"
+version = "1.0.0"
+dependencies = [
+ "axum",
+ "futures-util",
+ "qls-core",
+ "serde",
+ "serde_json",
+ "tokio",
+ "tokio-stream",
+ "tower-http 0.7.1",
+ "tracing",
+ "tracing-appender",
+ "tracing-subscriber",
+ "uuid",
+]
+
+[[package]]
+name = "quick-error"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
+
+[[package]]
+name = "quick-xml"
+version = "0.41.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "quick-xml"
+version = "0.42.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "qwen-local-studio"
+version = "1.0.0"
+dependencies = [
+ "dirs",
+ "image",
+ "reqwest",
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-build",
+ "tauri-plugin-clipboard-manager",
+ "tauri-plugin-dialog",
+ "tauri-plugin-opener",
+ "tauri-plugin-single-instance",
+]
+
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "raw-window-handle"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"
+
+[[package]]
+name = "redox_syscall"
+version = "0.5.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
+dependencies = [
+ "bitflags 2.13.2",
+]
+
+[[package]]
+name = "redox_users"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0"
+dependencies = [
+ "libredox",
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "ref-cast"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3"
+dependencies = [
+ "ref-cast-impl",
+]
+
+[[package]]
+name = "ref-cast-impl"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "regex"
+version = "1.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
+
+[[package]]
+name = "reqwest"
+version = "0.13.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029"
+dependencies = [
+ "base64 0.23.1",
+ "bytes",
+ "futures-channel",
+ "futures-core",
+ "futures-util",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-util",
+ "js-sys",
+ "log",
+ "percent-encoding",
+ "pin-project-lite",
+ "serde",
+ "serde_json",
+ "sync_wrapper",
+ "tokio",
+ "tokio-util",
+ "tower",
+ "tower-http 0.6.11",
+ "tower-service",
+ "url",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "wasm-streams",
+ "web-sys",
+]
+
+[[package]]
+name = "rfd"
+version = "0.16.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a15ad77d9e70a92437d8f74c35d99b4e4691128df018833e99f90bcd36152672"
+dependencies = [
+ "block2",
+ "dispatch2",
+ "glib-sys",
+ "gobject-sys",
+ "gtk-sys",
+ "js-sys",
+ "log",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-core-foundation",
+ "objc2-foundation",
+ "raw-window-handle",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+ "windows-sys 0.60.2",
+]
+
+[[package]]
+name = "rsqlite-vfs"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c"
+dependencies = [
+ "hashbrown 0.16.1",
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "rusqlite"
+version = "0.40.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3"
+dependencies = [
+ "bitflags 2.13.2",
+ "fallible-iterator",
+ "fallible-streaming-iterator",
+ "hashlink",
+ "libsqlite3-sys",
+ "smallvec",
+ "sqlite-wasm-rs",
+]
+
+[[package]]
+name = "rustc-hash"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"
+
+[[package]]
+name = "rustc_version"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92"
+dependencies = [
+ "semver",
+]
+
+[[package]]
+name = "rustix"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d"
+dependencies = [
+ "bitflags 2.13.2",
+ "errno",
+ "libc",
+ "linux-raw-sys",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustversion"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+
+[[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"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "schemars"
+version = "0.8.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615"
+dependencies = [
+ "dyn-clone",
+ "indexmap 1.9.3",
+ "schemars_derive",
+ "serde",
+ "serde_json",
+ "url",
+ "uuid",
+]
+
+[[package]]
+name = "schemars"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f"
+dependencies = [
+ "dyn-clone",
+ "ref-cast",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "schemars"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "687274d293b6cdc6e73e0fee520bf2049650090d7164f87672d212a3c530cf4a"
+dependencies = [
+ "dyn-clone",
+ "ref-cast",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "schemars_derive"
+version = "0.8.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "serde_derive_internals",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
+[[package]]
+name = "selectors"
+version = "0.38.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d"
+dependencies = [
+ "bitflags 2.13.2",
+ "cssparser",
+ "derive_more",
+ "log",
+ "new_debug_unreachable",
+ "phf",
+ "phf_codegen",
+ "precomputed-hash",
+ "rustc-hash",
+ "servo_arc",
+ "smallvec",
+]
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+dependencies = [
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde-untagged"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058"
+dependencies = [
+ "erased-serde",
+ "serde",
+ "serde_core",
+ "typeid",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "serde_derive_internals"
+version = "0.29.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.151"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "serde_path_to_error"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
+dependencies = [
+ "itoa",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "serde_repr"
+version = "0.1.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "serde_spanned"
+version = "0.6.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "serde_spanned"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"
+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.24.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df9adc193c780ef8f159aee8b61e2d5801aaa555e6eb0947fe45530ec506296f"
+dependencies = [
+ "base64 0.23.1",
+ "bs58",
+ "chrono",
+ "hex",
+ "indexmap 1.9.3",
+ "indexmap 2.14.2",
+ "jiff",
+ "schemars 0.9.0",
+ "schemars 1.2.2",
+ "serde_core",
+ "serde_json",
+ "serde_with_macros",
+ "time",
+]
+
+[[package]]
+name = "serde_with_macros"
+version = "3.24.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3e17bbc68e28663bbbb90df47e058aa7eda4fb445b89fe70457bb94fbccf6e49"
+dependencies = [
+ "darling",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "serialize-to-javascript"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04f3666a07a197cdb77cdf306c32be9b7f598d7060d50cfd4d5aa04bfd92f6c5"
+dependencies = [
+ "serde",
+ "serde_json",
+ "serialize-to-javascript-impl",
+]
+
+[[package]]
+name = "serialize-to-javascript-impl"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "772ee033c0916d670af7860b6e1ef7d658a4629a6d0b4c8c3e67f09b3765b75d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "servo_arc"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930"
+dependencies = [
+ "stable_deref_trait",
+]
+
+[[package]]
+name = "sha2"
+version = "0.10.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.2.17",
+ "digest 0.10.7",
+]
+
+[[package]]
+name = "sha2"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
+dependencies = [
+ "cfg-if",
+ "cpufeatures 0.3.1",
+ "digest 0.11.3",
+]
+
+[[package]]
+name = "sharded-slab"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
+dependencies = [
+ "lazy_static",
+]
+
+[[package]]
+name = "shlex"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+
+[[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.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
+
+[[package]]
+name = "siphasher"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"
+
+[[package]]
+name = "slab"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+
+[[package]]
+name = "smallvec"
+version = "1.16.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e"
+
+[[package]]
+name = "socket2"
+version = "0.6.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
+dependencies = [
+ "libc",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "softbuffer"
+version = "0.4.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3"
+dependencies = [
+ "bytemuck",
+ "js-sys",
+ "ndk",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-foundation",
+ "objc2-quartz-core",
+ "raw-window-handle",
+ "redox_syscall",
+ "tracing",
+ "wasm-bindgen",
+ "web-sys",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "soup3"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f"
+dependencies = [
+ "futures-channel",
+ "gio",
+ "glib",
+ "libc",
+ "soup3-sys",
+]
+
+[[package]]
+name = "soup3-sys"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27"
+dependencies = [
+ "gio-sys",
+ "glib-sys",
+ "gobject-sys",
+ "libc",
+ "system-deps",
+]
+
+[[package]]
+name = "sqlite-wasm-rs"
+version = "0.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75"
+dependencies = [
+ "cc",
+ "js-sys",
+ "rsqlite-vfs",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+
+[[package]]
+name = "string_cache"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901"
+dependencies = [
+ "new_debug_unreachable",
+ "parking_lot",
+ "phf_shared",
+ "precomputed-hash",
+]
+
+[[package]]
+name = "string_cache_codegen"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69"
+dependencies = [
+ "phf_generator",
+ "phf_shared",
+ "proc-macro2",
+ "quote",
+]
+
+[[package]]
+name = "strsim"
+version = "0.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
+
+[[package]]
+name = "swift-rs"
+version = "1.0.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e45c444e496845d3f2a351146bff59aae4975b2280238df1dfaa0c7d1846f38e"
+dependencies = [
+ "base64 0.21.7",
+ "serde",
+ "serde_json",
+]
+
+[[package]]
+name = "symlink"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a7973cce6668464ea31f176d85b13c7ab3bba2cb3b77a2ed26abd7801688010a"
+
+[[package]]
+name = "syn"
+version = "1.0.109"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
+dependencies = [
+ "proc-macro2",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "sync_wrapper"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "synstructure"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "sysinfo"
+version = "0.39.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2071df9448915b71c4fe6d25deaf1c22f12bd234f01540b77312bb8e41361e6"
+dependencies = [
+ "libc",
+ "memchr",
+ "ntapi",
+ "objc2-core-foundation",
+ "objc2-io-kit",
+ "objc2-open-directory",
+ "windows",
+]
+
+[[package]]
+name = "system-deps"
+version = "6.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349"
+dependencies = [
+ "cfg-expr",
+ "heck 0.5.0",
+ "pkg-config",
+ "toml 0.8.2",
+ "version-compare",
+]
+
+[[package]]
+name = "tao"
+version = "0.37.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f37f381f4e048e6cdf038b5705f8cf14ad108279d46eb968140a7b291aba9400"
+dependencies = [
+ "bitflags 2.13.2",
+ "block2",
+ "core-foundation",
+ "core-graphics",
+ "crossbeam-channel",
+ "dbus",
+ "dispatch2",
+ "dlopen2",
+ "dpi",
+ "gdkwayland-sys",
+ "gdkx11-sys",
+ "gtk",
+ "jni",
+ "libc",
+ "log",
+ "ndk",
+ "ndk-context",
+ "ndk-sys",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-foundation",
+ "objc2-ui-kit",
+ "parking_lot",
+ "percent-encoding",
+ "raw-window-handle",
+ "tao-macros",
+ "unicode-segmentation",
+ "url",
+ "windows",
+ "windows-core",
+ "windows-version",
+ "x11-dl",
+]
+
+[[package]]
+name = "tao-macros"
+version = "0.1.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f7eeb6d99155545da6150a1795945f16ac9c178deb2a5f2e74d776107bd5849"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "target-lexicon"
+version = "0.12.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"
+
+[[package]]
+name = "tauri"
+version = "2.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed99ee9694a2deb776d91cae48ac7411ddfc89ecae2f9b5041111d8c88f2ace9"
+dependencies = [
+ "anyhow",
+ "bytes",
+ "cookie",
+ "dirs",
+ "dunce",
+ "embed_plist",
+ "getrandom 0.3.4",
+ "glob",
+ "gtk",
+ "heck 0.5.0",
+ "http",
+ "jni",
+ "libc",
+ "log",
+ "mime",
+ "muda",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-foundation",
+ "objc2-ui-kit",
+ "objc2-web-kit",
+ "percent-encoding",
+ "plist",
+ "raw-window-handle",
+ "reqwest",
+ "serde",
+ "serde_json",
+ "serde_repr",
+ "serialize-to-javascript",
+ "swift-rs",
+ "tauri-build",
+ "tauri-macros",
+ "tauri-runtime",
+ "tauri-runtime-wry",
+ "tauri-utils",
+ "thiserror 2.0.21",
+ "tokio",
+ "tray-icon",
+ "url",
+ "webkit2gtk",
+ "webview2-com",
+ "window-vibrancy",
+ "windows",
+]
+
+[[package]]
+name = "tauri-build"
+version = "2.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "59563ca5b331fd97f27ee9672ec8d36d33bb3c9e2c9f6710a1a5687256052e45"
+dependencies = [
+ "anyhow",
+ "cargo_toml",
+ "dirs",
+ "glob",
+ "heck 0.5.0",
+ "json-patch",
+ "schemars 0.8.22",
+ "semver",
+ "serde",
+ "serde_json",
+ "tauri-utils",
+ "tauri-winres",
+ "walkdir",
+]
+
+[[package]]
+name = "tauri-codegen"
+version = "2.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e50213e463086ecc283d7e9f51c30cc0fd304ad457425158018be26dbf0d0a80"
+dependencies = [
+ "base64 0.22.1",
+ "brotli",
+ "ico",
+ "json-patch",
+ "plist",
+ "png 0.18.1",
+ "proc-macro2",
+ "quote",
+ "semver",
+ "serde",
+ "serde_json",
+ "sha2 0.10.9",
+ "syn 2.0.119",
+ "tauri-utils",
+ "thiserror 2.0.21",
+ "time",
+ "url",
+ "uuid",
+ "walkdir",
+]
+
+[[package]]
+name = "tauri-macros"
+version = "2.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8129fb43bb6e0d6b73ad3315cd172beaab17cd28899c594b1b32c80edbbfd99c"
+dependencies = [
+ "heck 0.5.0",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+ "tauri-codegen",
+ "tauri-utils",
+]
+
+[[package]]
+name = "tauri-plugin"
+version = "2.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1140cf34a3b3b836a13103dcab17f18831d5cc3534cbd435dc01a5c6daa65aa2"
+dependencies = [
+ "anyhow",
+ "glob",
+ "plist",
+ "schemars 0.8.22",
+ "serde",
+ "serde_json",
+ "tauri-utils",
+ "walkdir",
+]
+
+[[package]]
+name = "tauri-plugin-clipboard-manager"
+version = "2.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "333d3b6beeb1c2c7fc040233d4ea7b6c03a9f8f039592b7400833c43fb5b568a"
+dependencies = [
+ "arboard",
+ "log",
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+ "thiserror 2.0.21",
+]
+
+[[package]]
+name = "tauri-plugin-dialog"
+version = "2.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "daf9a5c92e39bdd84f22f6be9230e39d0c4e140345f71ffe6058dca4f71127cf"
+dependencies = [
+ "log",
+ "raw-window-handle",
+ "rfd",
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+ "tauri-plugin-fs",
+ "thiserror 2.0.21",
+ "url",
+]
+
+[[package]]
+name = "tauri-plugin-fs"
+version = "2.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "466eb32466fe5021b6728b06862f9ff14a9f7e1af890047654e03a96d7c0e1bb"
+dependencies = [
+ "anyhow",
+ "dunce",
+ "glob",
+ "log",
+ "objc2-foundation",
+ "percent-encoding",
+ "schemars 0.8.22",
+ "serde",
+ "serde_json",
+ "serde_repr",
+ "tauri",
+ "tauri-plugin",
+ "tauri-utils",
+ "thiserror 2.0.21",
+ "toml 1.1.6+spec-1.1.0",
+ "url",
+]
+
+[[package]]
+name = "tauri-plugin-opener"
+version = "2.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d39404b2572927e0d3ed30a7ca226037f7508d22e79c96ee6ef0d42b6a4b3345"
+dependencies = [
+ "dunce",
+ "glob",
+ "objc2-app-kit",
+ "objc2-foundation",
+ "open",
+ "schemars 0.8.22",
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+ "thiserror 2.0.21",
+ "url",
+ "windows",
+ "zbus",
+]
+
+[[package]]
+name = "tauri-plugin-single-instance"
+version = "2.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee2c8fe2d6b75caed0153f91eda30ea1dea3bfb6710d5adb80456d2c035a569d"
+dependencies = [
+ "serde",
+ "serde_json",
+ "tauri",
+ "thiserror 2.0.21",
+ "tokio",
+ "tracing",
+ "windows-sys 0.61.2",
+ "zbus",
+]
+
+[[package]]
+name = "tauri-runtime"
+version = "2.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a57a2a9b8c8b7fc00d35b510fe808ded7f9f1b44fc1cdda6aee38632ea5413"
+dependencies = [
+ "cookie",
+ "dpi",
+ "gtk",
+ "http",
+ "jni",
+ "objc2",
+ "objc2-ui-kit",
+ "objc2-web-kit",
+ "raw-window-handle",
+ "serde",
+ "serde_json",
+ "tauri-utils",
+ "thiserror 2.0.21",
+ "url",
+ "webkit2gtk",
+ "webview2-com",
+ "windows",
+]
+
+[[package]]
+name = "tauri-runtime-wry"
+version = "2.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f9e7e0c9f80a5130773cfabb6df4dc924518fb1b2c923726966804634b57d22"
+dependencies = [
+ "gtk",
+ "http",
+ "jni",
+ "log",
+ "objc2",
+ "objc2-app-kit",
+ "once_cell",
+ "percent-encoding",
+ "raw-window-handle",
+ "softbuffer",
+ "tao",
+ "tauri-runtime",
+ "tauri-utils",
+ "url",
+ "webkit2gtk",
+ "webview2-com",
+ "windows",
+ "wry",
+]
+
+[[package]]
+name = "tauri-utils"
+version = "2.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2ff55a614843b9a3f010f211df637c94df2607175b8d0f6e0f4a7c19e18621ee"
+dependencies = [
+ "anyhow",
+ "brotli",
+ "cargo_metadata",
+ "ctor",
+ "dom_query",
+ "dunce",
+ "glob",
+ "http",
+ "infer",
+ "json-patch",
+ "log",
+ "memchr",
+ "phf",
+ "plist",
+ "proc-macro2",
+ "quote",
+ "regex",
+ "schemars 0.8.22",
+ "semver",
+ "serde",
+ "serde-untagged",
+ "serde_json",
+ "serde_with",
+ "swift-rs",
+ "thiserror 2.0.21",
+ "toml 1.1.6+spec-1.1.0",
+ "url",
+ "urlpattern",
+ "uuid",
+ "walkdir",
+]
+
+[[package]]
+name = "tauri-winres"
+version = "0.3.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cc65d45c68858bfe420dd29e834b5d15dbecf8a07a8a16cf4d532c7b1f69d4b6"
+dependencies = [
+ "dunce",
+ "embed-resource",
+ "toml 1.1.6+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.3",
+ "once_cell",
+ "rustix",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "tendril"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08"
+dependencies = [
+ "new_debug_unreachable",
+]
+
+[[package]]
+name = "thiserror"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
+dependencies = [
+ "thiserror-impl 1.0.69",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
+dependencies = [
+ "thiserror-impl 2.0.21",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "1.0.69"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "thread_local"
+version = "1.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "tiff"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52"
+dependencies = [
+ "fax",
+ "flate2",
+ "half",
+ "quick-error",
+ "weezl",
+ "zune-jpeg",
+]
+
+[[package]]
+name = "time"
+version = "0.3.55"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"
+dependencies = [
+ "deranged",
+ "num-conv",
+ "powerfmt",
+ "serde_core",
+ "time-core",
+ "time-macros",
+]
+
+[[package]]
+name = "time-core"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
+
+[[package]]
+name = "time-macros"
+version = "0.2.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
+dependencies = [
+ "num-conv",
+ "time-core",
+]
+
+[[package]]
+name = "tinystr"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"
+dependencies = [
+ "displaydoc",
+ "zerovec",
+]
+
+[[package]]
+name = "tinyvec"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
+
+[[package]]
+name = "tokio"
+version = "1.53.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044"
+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.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "tokio-stream"
+version = "0.1.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b"
+dependencies = [
+ "futures-core",
+ "pin-project-lite",
+ "tokio",
+ "tokio-util",
+]
+
+[[package]]
+name = "tokio-util"
+version = "0.7.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "futures-sink",
+ "pin-project-lite",
+ "tokio",
+]
+
+[[package]]
+name = "toml"
+version = "0.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d"
+dependencies = [
+ "serde",
+ "serde_spanned 0.6.9",
+ "toml_datetime 0.6.3",
+ "toml_edit 0.20.2",
+]
+
+[[package]]
+name = "toml"
+version = "1.1.6+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "920602543f0911ab71da12c50d59701da54c196d1a2bf5cb4b75667f137a406a"
+dependencies = [
+ "indexmap 2.14.2",
+ "serde_core",
+ "serde_spanned 1.1.1",
+ "toml_datetime 1.1.1+spec-1.1.0",
+ "toml_parser",
+ "toml_writer",
+ "winnow 1.0.4",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "0.6.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "1.1.1+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.19.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421"
+dependencies = [
+ "indexmap 2.14.2",
+ "toml_datetime 0.6.3",
+ "winnow 0.5.40",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.20.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338"
+dependencies = [
+ "indexmap 2.14.2",
+ "serde",
+ "serde_spanned 0.6.9",
+ "toml_datetime 0.6.3",
+ "winnow 0.5.40",
+]
+
+[[package]]
+name = "toml_edit"
+version = "0.25.15+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1340ea94a5856333492c9064b02c778b191dd2c853778d9609debdcdfea3a614"
+dependencies = [
+ "indexmap 2.14.2",
+ "toml_datetime 1.1.1+spec-1.1.0",
+ "toml_parser",
+ "winnow 1.0.4",
+]
+
+[[package]]
+name = "toml_parser"
+version = "1.1.3+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1d38ac1cf9b95face32296c0a3ede1fdc270627c9d9c02a7274dd6d960dc4d56"
+dependencies = [
+ "winnow 1.0.4",
+]
+
+[[package]]
+name = "toml_writer"
+version = "1.1.2+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
+
+[[package]]
+name = "tower"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
+dependencies = [
+ "futures-core",
+ "futures-util",
+ "pin-project-lite",
+ "sync_wrapper",
+ "tokio",
+ "tower-layer",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "tower-http"
+version = "0.6.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
+dependencies = [
+ "bitflags 2.13.2",
+ "bytes",
+ "futures-util",
+ "http",
+ "http-body",
+ "pin-project-lite",
+ "tower",
+ "tower-layer",
+ "tower-service",
+ "url",
+]
+
+[[package]]
+name = "tower-http"
+version = "0.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08a05a66a4fdd61cbbe0a1d755ffe0ca6aba159dd4820936a0ff8a8278245b9c"
+dependencies = [
+ "bitflags 2.13.2",
+ "bytes",
+ "http",
+ "http-body",
+ "http-body-util",
+ "percent-encoding",
+ "pin-project-lite",
+ "tower-layer",
+ "tower-service",
+]
+
+[[package]]
+name = "tower-layer"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
+
+[[package]]
+name = "tower-service"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
+
+[[package]]
+name = "tracing"
+version = "0.1.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
+dependencies = [
+ "log",
+ "pin-project-lite",
+ "tracing-attributes",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-appender"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "050686193eb999b4bb3bc2acfa891a13da00f79734704c4b8b4ef1a10b368a3c"
+dependencies = [
+ "crossbeam-channel",
+ "symlink",
+ "thiserror 2.0.21",
+ "time",
+ "tracing-subscriber",
+]
+
+[[package]]
+name = "tracing-attributes"
+version = "0.1.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
+dependencies = [
+ "once_cell",
+ "valuable",
+]
+
+[[package]]
+name = "tracing-log"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
+dependencies = [
+ "log",
+ "once_cell",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-subscriber"
+version = "0.3.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319"
+dependencies = [
+ "matchers",
+ "nu-ansi-term",
+ "once_cell",
+ "regex-automata",
+ "sharded-slab",
+ "smallvec",
+ "thread_local",
+ "tracing",
+ "tracing-core",
+ "tracing-log",
+]
+
+[[package]]
+name = "tray-icon"
+version = "0.25.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72"
+dependencies = [
+ "crossbeam-channel",
+ "dirs",
+ "libappindicator",
+ "muda",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-foundation",
+ "once_cell",
+ "png 0.18.1",
+ "serde",
+ "thiserror 2.0.21",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "tree_magic_mini"
+version = "3.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6"
+dependencies = [
+ "memchr",
+ "nom",
+ "petgraph",
+]
+
+[[package]]
+name = "try-lock"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+
+[[package]]
+name = "typeid"
+version = "1.0.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "uds_windows"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e"
+dependencies = [
+ "memoffset",
+ "tempfile",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
+
+[[package]]
+name = "unicode-segmentation"
+version = "1.13.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
+
+[[package]]
+name = "url"
+version = "2.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
+dependencies = [
+ "form_urlencoded",
+ "idna",
+ "percent-encoding",
+ "serde",
+ "serde_derive",
+]
+
+[[package]]
+name = "urlpattern"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "df16f50ef4cc145211879a3867ba757076b25dfee812040dcb0658bd9ae7904b"
+dependencies = [
+ "icu_properties",
+ "regex",
+ "serde",
+ "url",
+]
+
+[[package]]
+name = "utf8_iter"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
+
+[[package]]
+name = "uuid"
+version = "1.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97277d36b9c3ace13e58fa6e753f8b0bbbf302a18dd193240d70f9e29681059a"
+dependencies = [
+ "getrandom 0.4.3",
+ "js-sys",
+ "serde_core",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "valuable"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
+
+[[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"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e"
+
+[[package]]
+name = "version_check"
+version = "0.9.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
+
+[[package]]
+name = "vswhom"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b"
+dependencies = [
+ "libc",
+ "vswhom-sys",
+]
+
+[[package]]
+name = "vswhom-sys"
+version = "0.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150"
+dependencies = [
+ "cc",
+ "libc",
+]
+
+[[package]]
+name = "walkdir"
+version = "2.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
+dependencies = [
+ "same-file",
+ "winapi-util",
+]
+
+[[package]]
+name = "want"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b"
+dependencies = [
+ "try-lock",
+]
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "wasip2"
+version = "1.0.4+wasi-0.2.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
+dependencies = [
+ "wit-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "rustversion",
+ "wasm-bindgen-macro",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-futures"
+version = "0.4.79"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e"
+dependencies = [
+ "js-sys",
+ "tokio",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"
+dependencies = [
+ "bumpalo",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "wasm-streams"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb"
+dependencies = [
+ "futures-util",
+ "js-sys",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+]
+
+[[package]]
+name = "wayland-backend"
+version = "0.3.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078"
+dependencies = [
+ "cc",
+ "downcast-rs",
+ "rustix",
+ "smallvec",
+ "wayland-sys",
+]
+
+[[package]]
+name = "wayland-client"
+version = "0.31.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073"
+dependencies = [
+ "bitflags 2.13.2",
+ "rustix",
+ "wayland-backend",
+ "wayland-scanner",
+]
+
+[[package]]
+name = "wayland-protocols"
+version = "0.32.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6"
+dependencies = [
+ "bitflags 2.13.2",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-scanner",
+]
+
+[[package]]
+name = "wayland-protocols-wlr"
+version = "0.3.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234"
+dependencies = [
+ "bitflags 2.13.2",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-protocols",
+ "wayland-scanner",
+]
+
+[[package]]
+name = "wayland-scanner"
+version = "0.31.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"
+dependencies = [
+ "proc-macro2",
+ "quick-xml 0.41.0",
+ "quote",
+]
+
+[[package]]
+name = "wayland-sys"
+version = "0.31.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be"
+dependencies = [
+ "pkg-config",
+]
+
+[[package]]
+name = "web-sys"
+version = "0.3.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "web-time"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "web_atoms"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ba8b815c1b593dc0baf78dd0f4fc8fdb2de53198fb1163738093e9a311c33fb3"
+dependencies = [
+ "phf",
+ "phf_codegen",
+ "string_cache",
+ "string_cache_codegen",
+]
+
+[[package]]
+name = "webkit2gtk"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1027150013530fb2eaf806408df88461ae4815a45c541c8975e61d6f2fc4793"
+dependencies = [
+ "bitflags 1.3.2",
+ "cairo-rs",
+ "gdk",
+ "gdk-sys",
+ "gio",
+ "gio-sys",
+ "glib",
+ "glib-sys",
+ "gobject-sys",
+ "gtk",
+ "gtk-sys",
+ "javascriptcore-rs",
+ "libc",
+ "once_cell",
+ "soup3",
+ "webkit2gtk-sys",
+]
+
+[[package]]
+name = "webkit2gtk-sys"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "916a5f65c2ef0dfe12fff695960a2ec3d4565359fdbb2e9943c974e06c734ea5"
+dependencies = [
+ "bitflags 1.3.2",
+ "cairo-sys-rs",
+ "gdk-sys",
+ "gio-sys",
+ "glib-sys",
+ "gobject-sys",
+ "gtk-sys",
+ "javascriptcore-rs-sys",
+ "libc",
+ "pkg-config",
+ "soup3-sys",
+ "system-deps",
+]
+
+[[package]]
+name = "webview2-com"
+version = "0.39.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f89fca7a704cee10dcb3654c1dbb8941d1783132f1917358af75bec37a7d7e6"
+dependencies = [
+ "webview2-com-macros",
+ "webview2-com-sys",
+ "windows",
+ "windows-core",
+]
+
+[[package]]
+name = "webview2-com-macros"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "webview2-com-sys"
+version = "0.39.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b3a07132775117d6065853d9d1178157b8c90e228de47129d6bce2c7edebedfb"
+dependencies = [
+ "thiserror 2.0.21",
+ "windows",
+ "windows-core",
+]
+
+[[package]]
+name = "weezl"
+version = "0.1.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
+
+[[package]]
+name = "winapi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
+[[package]]
+name = "winapi-util"
+version = "0.1.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
+[[package]]
+name = "window-vibrancy"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "111e51caca442cafd9bab396628ac4d814880eaea4e63dfd76a12e9f342b5580"
+dependencies = [
+ "objc2",
+ "objc2-app-kit",
+ "objc2-core-foundation",
+ "objc2-foundation",
+ "objc2-quartz-core",
+ "raw-window-handle",
+ "windows-sys 0.61.2",
+ "windows-version",
+]
+
+[[package]]
+name = "windows"
+version = "0.62.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
+dependencies = [
+ "windows-collections",
+ "windows-core",
+ "windows-future",
+ "windows-numerics",
+]
+
+[[package]]
+name = "windows-collections"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
+dependencies = [
+ "windows-core",
+]
+
+[[package]]
+name = "windows-core"
+version = "0.62.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
+dependencies = [
+ "windows-implement",
+ "windows-interface",
+ "windows-link",
+ "windows-result",
+ "windows-strings",
+]
+
+[[package]]
+name = "windows-future"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
+dependencies = [
+ "windows-core",
+ "windows-link",
+ "windows-threading",
+]
+
+[[package]]
+name = "windows-implement"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "windows-interface"
+version = "0.59.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-numerics"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
+dependencies = [
+ "windows-core",
+ "windows-link",
+]
+
+[[package]]
+name = "windows-result"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-strings"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.45.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"
+dependencies = [
+ "windows-targets 0.42.2",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
+dependencies = [
+ "windows-targets 0.53.5",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"
+dependencies = [
+ "windows_aarch64_gnullvm 0.42.2",
+ "windows_aarch64_msvc 0.42.2",
+ "windows_i686_gnu 0.42.2",
+ "windows_i686_msvc 0.42.2",
+ "windows_x86_64_gnu 0.42.2",
+ "windows_x86_64_gnullvm 0.42.2",
+ "windows_x86_64_msvc 0.42.2",
+]
+
+[[package]]
+name = "windows-targets"
+version = "0.53.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
+dependencies = [
+ "windows-link",
+ "windows_aarch64_gnullvm 0.53.1",
+ "windows_aarch64_msvc 0.53.1",
+ "windows_i686_gnu 0.53.1",
+ "windows_i686_gnullvm",
+ "windows_i686_msvc 0.53.1",
+ "windows_x86_64_gnu 0.53.1",
+ "windows_x86_64_gnullvm 0.53.1",
+ "windows_x86_64_msvc 0.53.1",
+]
+
+[[package]]
+name = "windows-threading"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-version"
+version = "0.1.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8"
+
+[[package]]
+name = "windows_aarch64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"
+
+[[package]]
+name = "windows_aarch64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f"
+
+[[package]]
+name = "windows_i686_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
+
+[[package]]
+name = "windows_i686_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"
+
+[[package]]
+name = "windows_i686_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36"
+
+[[package]]
+name = "windows_x86_64_gnu"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"
+
+[[package]]
+name = "windows_x86_64_gnullvm"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.42.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"
+
+[[package]]
+name = "windows_x86_64_msvc"
+version = "0.53.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
+
+[[package]]
+name = "winnow"
+version = "0.5.40"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "winnow"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "winreg"
+version = "0.56.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10"
+dependencies = [
+ "cfg-if",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "wit-bindgen"
+version = "0.57.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
+
+[[package]]
+name = "wl-clipboard-rs"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4d7888ccd4896447b2d14d3a9350a85df2aeb6f181e2e7a31349d104ac46cac1"
+dependencies = [
+ "libc",
+ "log",
+ "os_pipe",
+ "rustix",
+ "thiserror 2.0.21",
+ "tree_magic_mini",
+ "wayland-backend",
+ "wayland-client",
+ "wayland-protocols",
+ "wayland-protocols-wlr",
+]
+
+[[package]]
+name = "writeable"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
+
+[[package]]
+name = "wry"
+version = "0.57.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a819957a01b3119af85e638a38d242af76dbc87d130dca67bfd0441072e21ff0"
+dependencies = [
+ "base64 0.22.1",
+ "block2",
+ "cookie",
+ "crossbeam-channel",
+ "dirs",
+ "dom_query",
+ "dpi",
+ "dunce",
+ "gdkx11",
+ "gtk",
+ "http",
+ "javascriptcore-rs",
+ "jni",
+ "libc",
+ "ndk",
+ "objc2",
+ "objc2-app-kit",
+ "objc2-core-foundation",
+ "objc2-foundation",
+ "objc2-ui-kit",
+ "objc2-web-kit",
+ "once_cell",
+ "percent-encoding",
+ "raw-window-handle",
+ "sha2 0.10.9",
+ "soup3",
+ "tao-macros",
+ "thiserror 2.0.21",
+ "url",
+ "webkit2gtk",
+ "webkit2gtk-sys",
+ "webview2-com",
+ "windows",
+ "windows-core",
+ "windows-version",
+ "x11-dl",
+]
+
+[[package]]
+name = "x11"
+version = "2.21.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e"
+dependencies = [
+ "libc",
+ "pkg-config",
+]
+
+[[package]]
+name = "x11-dl"
+version = "2.21.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f"
+dependencies = [
+ "libc",
+ "once_cell",
+ "pkg-config",
+]
+
+[[package]]
+name = "x11rb"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414"
+dependencies = [
+ "gethostname",
+ "rustix",
+ "x11rb-protocol",
+]
+
+[[package]]
+name = "x11rb-protocol"
+version = "0.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd"
+
+[[package]]
+name = "yoke"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
+dependencies = [
+ "stable_deref_trait",
+ "yoke-derive",
+ "zerofrom",
+]
+
+[[package]]
+name = "yoke-derive"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+ "synstructure",
+]
+
+[[package]]
+name = "zbus"
+version = "5.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907"
+dependencies = [
+ "async-broadcast",
+ "async-executor",
+ "async-io",
+ "async-lock",
+ "async-process",
+ "async-recursion",
+ "async-task",
+ "async-trait",
+ "blocking",
+ "enumflags2",
+ "event-listener",
+ "futures-core",
+ "futures-lite",
+ "hex",
+ "libc",
+ "ordered-stream",
+ "rustix",
+ "serde",
+ "serde_repr",
+ "tracing",
+ "uds_windows",
+ "uuid",
+ "windows-sys 0.61.2",
+ "winnow 1.0.4",
+ "zbus_macros",
+ "zbus_names",
+ "zvariant",
+]
+
+[[package]]
+name = "zbus_macros"
+version = "5.19.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40"
+dependencies = [
+ "proc-macro-crate 3.5.0",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+ "zbus_names",
+ "zvariant",
+ "zvariant_utils",
+]
+
+[[package]]
+name = "zbus_names"
+version = "4.3.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e"
+dependencies = [
+ "serde",
+ "winnow 1.0.4",
+ "zvariant",
+]
+
+[[package]]
+name = "zcheapstr"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473"
+dependencies = [
+ "serde",
+]
+
+[[package]]
+name = "zerocopy"
+version = "0.8.60"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6400fc4bb7426f6faac3fb07566122bb18622e3022bd2c36426a92ed489b1dbe"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.60"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "99c27cc7525bad4df59a45e073c45b2c2aa820efb588234cc23a547ec69a34db"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "zerofrom"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
+dependencies = [
+ "zerofrom-derive",
+]
+
+[[package]]
+name = "zerofrom-derive"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+ "synstructure",
+]
+
+[[package]]
+name = "zerotrie"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
+dependencies = [
+ "displaydoc",
+ "yoke",
+ "zerofrom",
+]
+
+[[package]]
+name = "zerovec"
+version = "0.11.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"
+dependencies = [
+ "yoke",
+ "zerofrom",
+ "zerovec-derive",
+]
+
+[[package]]
+name = "zerovec-derive"
+version = "0.11.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "zlib-rs"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+
+[[package]]
+name = "zune-core"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
+
+[[package]]
+name = "zune-jpeg"
+version = "0.5.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
+dependencies = [
+ "zune-core",
+]
+
+[[package]]
+name = "zvariant"
+version = "5.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c1d34c27cc6cdd1f458427519dd6b8612f7b7e3f7b9a0b2355d041dda9869147"
+dependencies = [
+ "endi",
+ "enumflags2",
+ "serde",
+ "winnow 1.0.4",
+ "zcheapstr",
+ "zvariant_derive",
+ "zvariant_utils",
+]
+
+[[package]]
+name = "zvariant_derive"
+version = "5.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "864155e69b4352db0c7f374917bf45d1e0c8d17659c8b3dbf9795f3673f8c497"
+dependencies = [
+ "proc-macro-crate 3.5.0",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+ "zvariant_utils",
+]
+
+[[package]]
+name = "zvariant_utils"
+version = "4.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "serde",
+ "syn 3.0.6",
+ "winnow 1.0.4",
+]
diff --git a/Cargo.toml b/Cargo.toml
new file mode 100644
index 0000000..96e11c4
--- /dev/null
+++ b/Cargo.toml
@@ -0,0 +1,20 @@
+[workspace]
+resolver = "3"
+members = ["crates/qls-core", "crates/qls-service", "src-tauri"]
+
+[workspace.package]
+version = "1.0.0"
+edition = "2024"
+license = "AGPL-3.0-only"
+
+[profile.release]
+opt-level = 3
+lto = "thin"
+codegen-units = 4
+strip = true
+
+# Image processing is far too slow unoptimized; keep deps optimized in dev/test.
+[profile.dev.package."*"]
+opt-level = 3
+[profile.dev]
+opt-level = 1
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..e5bedd2
--- /dev/null
+++ b/README.md
@@ -0,0 +1,237 @@
+# Qwen Local Studio
+
+Local image generation and editing for Windows, built on
+[stable-diffusion.cpp](https://github.com/leejet/stable-diffusion.cpp) and Qwen-Image 2.1.
+Everything runs on this PC: no telemetry, no uploads, no cloud calls. All services
+listen on `127.0.0.1` only.
+
+- Text to image, edit, multi-reference, inpaint, outpaint (expand), upscale
+- One diffusion pass per image, then ESRGAN (UltraSharp by default) instead of plain
+ resizing whenever the result is enlarged to its final size
+- Automatic mode, resolution and memory decisions; advanced controls stay hidden
+- Persistent local gallery with metadata (also embedded in the PNGs)
+- MCP server for Claude Code and other MCP hosts, plus a stable local HTTP API
+
+## Architecture
+
+```
+Qwen Local Studio.exe (Tauri 2 + React) qls-mcp.exe (MCP, stdio) scripts
+ │ loopback HTTP + SSE, token │ │
+ └──────────────────────────────┬────────────┴────────────────────────┘
+ ▼
+ qls-service.exe — stable API http://127.0.0.1:39151/api/v1
+ (engine: planner · preprocessing · job queue · gallery)
+ │ native async API /sdcpp/v1/*
+ ▼
+ sd-server.exe (stable-diffusion.cpp) 127.0.0.1:39150
+```
+
+| Crate / package | Responsibility |
+| --- | --- |
+| `crates/qls-core/src/geometry.rs` | Pure dimension math: 32-alignment, working canvas, outpaint/inpaint geometry |
+| `imaging.rs` | EXIF orientation, alpha-safe resize, padding, masks, compositing, PNG metadata/ICC |
+| `planner.rs` | Mode detection, resolution policy, upscale targets, VRAM budget |
+| `pipeline.rs` | Builds backend requests, post-processes results (crop back, ESRGAN tiling, composite) |
+| `sdcpp.rs` | Inference adapter — the only code that knows sd-server's schema |
+| `process.rs` | sd-server launch/reuse/stop, log capture, truthful progress parsing |
+| `engine.rs` | Async job queue, cancellation, OOM retry, saving |
+| `store.rs` | SQLite gallery + content-addressed inputs |
+| `paths.rs` | Path validation (no UNC/device/ADS/traversal, never overwrite) |
+| `crates/qls-service` | Headless service and stable HTTP API; single instance; lifecycle |
+| `src-tauri`, `src/` | Desktop shell (Rust) and UI (React + TypeScript) |
+| `mcp/` | MCP server (TypeScript, official SDK) |
+
+### Verified backend facts (stable-diffusion.cpp commit `3f8527a`)
+
+- Native async API: `POST /sdcpp/v1/img_gen` → `GET /sdcpp/v1/jobs/{id}`; cancel works only for
+ queued jobs (`cancel_generating: false`). Cancelling a running job therefore restarts the
+ server when this app launched it.
+- Qwen-Image 2.1 editing uses `ref_images` (labelled `<image1>`, `<image2>`… in order);
+ references and canvas must be multiples of 32. Inpainting uses `init_image` + binary
+ `mask_image` (white = regenerate).
+- Recommended settings follow the official Qwen-Image 2.1 release (QwenLM/Qwen-Image-2.1
+ README, diffusers `QwenImage21Pipeline`): `euler`, **no CFG** (1.0, "meant to be sampled
+ without guidance"), 40 steps, native 2K sizes; sd-server picks the same resolution-dependent
+ flow schedule (exponential shift 0.5–0.9, terminal 0.02). sd.cpp's own docs use CFG 6, which
+ runs a second, unconditional model pass every step; the app used that until 2026-10-07.
+ At CFG 1 the negative prompt is ignored.
+ Presets: Fast 20 steps at ~1 MP (a shortcut, not official); Balanced 40 steps at ~1 MP;
+ Quality 40 steps at the official 2K buckets (2048², 2752×1536…; edits share that budget
+ with their reference images, so they land near 2 MP on 16 GB).
+- Default launch: `--backend cuda0 --params-backend te=cpu --fa --sage-attn --vae-tiling
+ --vae-tile-size 768 --vae-tile-overlap 0.125 --max-vram -1` plus `--hires-upscalers-dir`
+ when the upscalers folder exists (text-encoder weights in RAM, computed on the GPU). Measured
+ on an RTX 5070 Ti: running the text encoder fully on the CPU made a one-image edit take 240 s
+ versus 61 s; SageAttention makes 2K steps ~32 % faster; untiled 2K VAE decodes OOM and fall
+ back to 256 px tiles (~22 s), 768 px tiles take ~4 s.
+- Request objects are merged field by field over the server's launch options, so omitted
+ fields keep the CLI values (per-request VAE tiling is only sent to turn it off).
+- `img_gen` accepts a `hires` object (second pass: upscale with a built-in filter or an ESRGAN
+ model from `--hires-upscalers-dir`, then re-sample at `denoising_strength`); reference
+ latents and inpaint masks are carried into that pass. `cache_mode`/`cache_option`
+ (e.g. `easycache`, `threshold=0.2`) work per request. `POST /sdcpp/v1/upscale`
+ (`{image, upscaler}`) runs ESRGAN synchronously, up to 8192 px per side.
+- Qwen-Image 2.1 always decodes an alpha channel (≈1 % of pixels at alpha 247–254 on opaque
+ images); outputs are made opaque unless transparency is requested.
+
+## Using the app
+
+Drop, paste (Ctrl+V) or add images, describe the result, press Enter.
+
+- **No image** → text to image (aspect from the prompt or the aspect menu)
+- **One image** → edit; the original size and aspect ratio are kept
+- **Several images** → combine; refer to them as image 1, image 2… (drag to reorder)
+- **Brush** → paint a mask, then describe what goes there (inpainting)
+- **Expand** → drag the edges or type pixel/percent values (outpainting)
+
+Results offer Edit, Variation, Use as reference, Inpaint, Expand, Upscale, Favorite, Save, Copy
+and Show in Explorer. The gallery (grid icon) reopens any previous generation with its recipe.
+
+### Large images and upscaling
+
+Every job runs a single diffusion pass at the working size (Auto: ~1 MP for Fast/Balanced,
+native 2K for Quality; or the 1K/1.5K/2K/Source/Custom choice), capped by the VRAM token budget
+that the target shares with its reference images. The earlier two-pass mode (≈1 MP render →
+ESRGAN → low-denoise refine at 2K) was removed on 2026-10-06: in A/B tests the refine made
+edits look worse than a single pass.
+
+Whenever a result is larger than what the model rendered (edits restored to the source size,
+outpaint, sizes above the VRAM budget) it is enlarged with ESRGAN ×4 and then resized down to the exact
+size; Lanczos is only used for shrinking or factors below 1.1×.
+
+The **Upscale** button (on results and inputs) offers 2×, 4K, the original source size or a
+custom width, with two methods:
+
+- **Quick**: ESRGAN only, a few seconds; adds no new content.
+- **Detailed**: re-renders fine detail with a low-denoise (0.3) img2img pass at about 2K, then
+ ESRGAN to the target. About a minute.
+
+The result is saved as a new gallery item linked to its source. The Details panel shows the
+pipeline (e.g. `1376×768 → 5120×2880 (UltraSharp)`).
+
+**HEIC and HDR.** HEIC/HEIF photos can be opened like any other image (picker, drag & drop);
+they are decoded by Windows' HEIF codec, so Microsoft's "HEIF Image Extensions" and "HEVC Video
+Extensions" must be installed. iPhone photos with an HDR gain map (ISO 21496-1, iOS 18+) show a
+**Keep HDR** switch in Advanced (on by default): edits, inpainting and upscales of such a photo are
+saved as an **Ultra HDR JPEG** (SDR image + gain map), which Chrome/Edge, Android and recent
+Apple systems show in HDR and every other viewer as a normal JPEG. The model itself works in SDR;
+the source's gain map is reused and faded out where the edit changed brightness by more than
+~¼ stop (gone at 1 stop). Reading the gain map needs `ffmpeg` (7.1+) on PATH; without it, or
+when the result's framing differs from the source (outpaint, other aspect ratios), the result is
+saved in SDR and the job's notes say why.
+
+**Upscaler model.** Settings → Models offers two ESRGAN models (64 MB each), used for
+enlarging results and for the Upscale button: **UltraSharp** (default,
+`4x-UltraSharp.pth`) and **Superscale-SP** (`4x_NMKD-Superscale-SP_178000_G.pth`). Both keep
+fine texture that RealESRGAN_x4plus smooths away. Put them in
+`<stable-diffusion.cpp folder>\models\upscalers\`. The app does not download models: get them
+from <https://huggingface.co/uwg/upscaler/tree/main/ESRGAN>. UltraSharp is licensed
+CC BY-NC-SA 4.0 (non-commercial). Without the selected model everything still works, with
+Lanczos instead of ESRGAN; the setup screen reports whether the model was found.
+
+Data locations:
+
+| What | Where |
+| --- | --- |
+| Images | `%USERPROFILE%\Pictures\Qwen Local Studio\<date>\` (configurable) |
+| Settings | `%APPDATA%\Qwen Local Studio\config.json` |
+| Gallery DB, inputs, thumbnails, logs | `%LOCALAPPDATA%\QwenLocalStudio\` |
+| API port + token | `%LOCALAPPDATA%\QwenLocalStudio\service.json` |
+
+## MCP (Claude Code)
+
+The installer places `qls-mcp.exe` next to the app. Register it once (user scope, available in
+every project):
+
+```powershell
+claude mcp add --scope user qwen-local -- "$env:LOCALAPPDATA\Qwen Local Studio\qls-mcp.exe"
+```
+
+Equivalent JSON form:
+
+```powershell
+claude mcp add-json --scope user qwen-local '{"type":"stdio","command":"C:\\Users\\<you>\\AppData\\Local\\Qwen Local Studio\\qls-mcp.exe","args":[]}'
+```
+
+Project-scoped `.mcp.json` example:
+
+```json
+{
+ "mcpServers": {
+ "qwen-local": {
+ "type": "stdio",
+ "command": "C:\\Users\\<you>\\AppData\\Local\\Qwen Local Studio\\qls-mcp.exe",
+ "args": []
+ }
+ }
+}
+```
+
+Tools: `generate_image`, `edit_image`, `edit_images`, `outpaint_image`, `inpaint_image`,
+`upscale_image`, `get_image_info`, `get_generator_status`. Every result includes the absolute
+path of the saved file, its size, seed and generation metadata (including the
+ESRGAN pipeline when used). `upscale_image` takes `scale` (default 2) or `width`/`height`
+(up to 8192 px) and `method` (`quick` | `detailed`).
+
+Notes:
+
+- The app does not need to be open. The MCP server starts the service, which starts or reuses
+ sd-server (first call ≈ 1 min to load the model). Without the desktop window, the model is
+ unloaded after 15 idle minutes (Settings → General).
+- Paths may be absolute or relative to the project (`CLAUDE_PROJECT_DIR`). Reads and writes
+ are limited to the project folder, the app's output folder, and folders listed in
+ `QLS_MCP_ALLOWED_DIRS` (semicolon-separated). Existing files are never overwritten.
+- Images are **not** returned to the model by default (they stay local). Pass
+ `include_preview: true` to include a small JPEG preview.
+- Claude Code's default stdio tool timeout is 30 minutes (`MCP_TOOL_TIMEOUT`). Progress is
+ reported through MCP progress notifications.
+
+## Stable local API
+
+Base URL: `http://127.0.0.1:39151/api/v1`. Every call except `/ping` needs
+`Authorization: Bearer <token>`, where the token comes from `service.json`. Requests carrying a
+browser `Origin` header are refused.
+
+| Method | Path | Purpose |
+| --- | --- | --- |
+| GET | `/ping` | Liveness (no auth) |
+| GET | `/status` | Server state, model, GPU/VRAM, active job, queue |
+| POST | `/generate`, `/edit`, `/inpaint`, `/outpaint`, `/upscale` | Simple operations; wait for the result unless `?wait=false` |
+| POST | `/jobs` | Full request (see `GenerationRequest` in `planner.rs`) |
+| GET | `/jobs/{id}`, `/jobs/{id}/wait?timeout=60` | Job status / long-poll |
+| POST | `/jobs/{id}/cancel` | Cancel |
+| POST | `/plan` | Dry run: resolved mode, working/output size, notes |
+| GET | `/events` | Server-sent events (jobs, server, gallery) |
+| GET | `/gallery`, `/gallery/{id}`, `/gallery/{id}/image` | Gallery |
+| POST | `/image-info` | Size, aspect, type, embedded generation metadata |
+
+Example (PowerShell):
+
+```powershell
+$i = Get-Content "$env:LOCALAPPDATA\QwenLocalStudio\service.json" | ConvertFrom-Json
+$h = @{ Authorization = "Bearer $($i.token)" }
+Invoke-RestMethod -Method Post "http://127.0.0.1:$($i.port)/api/v1/generate" -Headers $h `
+ -ContentType 'application/json' -Body '{"prompt":"a lighthouse at dusk, 16:9","quality":"fast"}'
+```
+
+Simple-operation fields: `prompt`, `image` / `images[]`, `mask`, `width`, `height`,
+`aspect_ratio`, `quality` (`fast|balanced|quality`), `seed`, `output_path`,
+`preserve_dimensions`, `left/right/top/bottom` + `units` (`pixels|percent`) for outpainting,
+`scale` and `method` (`quick|detailed`) for upscaling. Full requests (`/jobs`) also accept
+`"mode": "upscale"` with `"upscale": {"method", "scale" | "width"/"height"}` and
+`"advanced": {"refine": "fast|best"}` (effort of a Detailed upscale).
+
+New settings in `config.json`: `refineMode` (`fast|best`, Detailed upscale effort; `off` is legacy), `upscalersDir` (null = default
+folder), `upscalerModel` (`4x-UltraSharp`; configs on the old `RealESRGAN_x4plus` default move to it), `upscaleTileSize` (0 = backend default 128).
+
+## Building
+
+Requirements: Rust (stable, MSVC), Node 22+, VS Build Tools, WebView2.
+
+```powershell
+cargo test -p qls-core # core unit tests
+npx vitest run # UI logic tests
+cd mcp; npx vitest run; cd .. # MCP tests (includes a stdio protocol test)
+npx tauri dev # run the desktop app in development
+powershell -ExecutionPolicy Bypass -File scripts\build-release.ps1 # installer
+```
diff --git a/assets/icon.svg b/assets/icon.svg
new file mode 100644
index 0000000..aeddc80
--- /dev/null
+++ b/assets/icon.svg
@@ -0,0 +1,5 @@
+<svg xmlns="http://www.w3.org/2000/svg" width="1024" height="1024" viewBox="0 0 1024 1024">
+ <rect x="64" y="64" width="896" height="896" rx="208" fill="#0a0a0a"/>
+ <circle cx="512" cy="512" r="250" fill="none" stroke="#ffffff" stroke-width="64"/>
+ <path d="M512 382 C522 470 554 502 642 512 C554 522 522 554 512 642 C502 554 470 522 382 512 C470 502 502 470 512 382 Z" fill="#ffffff"/>
+</svg>
diff --git a/crates/qls-core/Cargo.lock b/crates/qls-core/Cargo.lock
new file mode 100644
index 0000000..d53a7d1
--- /dev/null
+++ b/crates/qls-core/Cargo.lock
@@ -0,0 +1,1844 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "adler2"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
+
+[[package]]
+name = "aho-corasick"
+version = "1.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba"
+dependencies = [
+ "memchr",
+]
+
+[[package]]
+name = "android_system_properties"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.104"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"
+
+[[package]]
+name = "atomic-waker"
+version = "1.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
+
+[[package]]
+name = "autocfg"
+version = "1.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
+
+[[package]]
+name = "base64"
+version = "0.23.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"
+
+[[package]]
+name = "bitflags"
+version = "2.13.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
+
+[[package]]
+name = "block-buffer"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "bumpalo"
+version = "3.20.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
+
+[[package]]
+name = "bytemuck"
+version = "1.25.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"
+
+[[package]]
+name = "byteorder-lite"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"
+
+[[package]]
+name = "bytes"
+version = "1.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"
+
+[[package]]
+name = "cc"
+version = "1.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f74872d07caf508b30a21f6836e7d7016a2eaf7d9ff4f48deaa58cd8a0407630"
+dependencies = [
+ "find-msvc-tools",
+ "shlex",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
+
+[[package]]
+name = "chacha20"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "rand_core",
+]
+
+[[package]]
+name = "chrono"
+version = "0.4.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
+dependencies = [
+ "iana-time-zone",
+ "js-sys",
+ "num-traits",
+ "wasm-bindgen",
+ "windows-link",
+]
+
+[[package]]
+name = "color_quant"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b"
+
+[[package]]
+name = "const-oid"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
+
+[[package]]
+name = "core-foundation-sys"
+version = "0.8.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b"
+
+[[package]]
+name = "cpufeatures"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crc32fast"
+version = "1.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78"
+dependencies = [
+ "cfg-if",
+]
+
+[[package]]
+name = "crunchy"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+
+[[package]]
+name = "crypto-common"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "digest"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
+dependencies = [
+ "block-buffer",
+ "const-oid",
+ "crypto-common",
+]
+
+[[package]]
+name = "dirs"
+version = "7.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f"
+dependencies = [
+ "dirs-sys",
+]
+
+[[package]]
+name = "dirs-sys"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab"
+dependencies = [
+ "libc",
+ "option-ext",
+ "redox_users",
+ "windows-sys",
+]
+
+[[package]]
+name = "dispatch2"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
+dependencies = [
+ "bitflags",
+ "objc2",
+]
+
+[[package]]
+name = "displaydoc"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "errno"
+version = "0.3.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
+dependencies = [
+ "libc",
+ "windows-sys",
+]
+
+[[package]]
+name = "fallible-iterator"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2acce4a10f12dc2fb14a218589d4f1f62ef011b2d0cc4b3cb1bba8e94da14649"
+
+[[package]]
+name = "fallible-streaming-iterator"
+version = "0.1.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7360491ce676a36bf9bb3c56c1aa791658183a54d2744120f27285738d90465a"
+
+[[package]]
+name = "fax"
+version = "0.2.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a"
+
+[[package]]
+name = "fdeflate"
+version = "0.3.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
+dependencies = [
+ "simd-adler32",
+]
+
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484"
+
+[[package]]
+name = "flate2"
+version = "1.1.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb"
+dependencies = [
+ "crc32fast",
+ "miniz_oxide 0.9.1",
+ "zlib-rs",
+]
+
+[[package]]
+name = "foldhash"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+
+[[package]]
+name = "form_urlencoded"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
+dependencies = [
+ "percent-encoding",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e"
+
+[[package]]
+name = "futures-task"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd"
+
+[[package]]
+name = "futures-util"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc"
+dependencies = [
+ "futures-core",
+ "futures-task",
+ "pin-project-lite",
+ "slab",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+ "rand_core",
+]
+
+[[package]]
+name = "gif"
+version = "0.14.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159"
+dependencies = [
+ "color_quant",
+ "weezl",
+]
+
+[[package]]
+name = "half"
+version = "2.7.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
+dependencies = [
+ "cfg-if",
+ "crunchy",
+ "zerocopy",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+dependencies = [
+ "foldhash",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+dependencies = [
+ "foldhash",
+]
+
+[[package]]
+name = "hashlink"
+version = "0.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a596f1b20ed2cc5ecac41a164aaebc7258057060f06c0cf7a2ba3991ee7990fb"
+dependencies = [
+ "hashbrown 0.17.1",
+]
+
+[[package]]
+name = "hex"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+
+[[package]]
+name = "http"
+version = "1.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0"
+dependencies = [
+ "bytes",
+ "itoa",
+]
+
+[[package]]
+name = "http-body"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"
+dependencies = [
+ "bytes",
+ "http",
+]
+
+[[package]]
+name = "http-body-util"
+version = "0.1.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c"
+dependencies = [
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "httparse"
+version = "1.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
+
+[[package]]
+name = "hybrid-array"
+version = "0.4.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17"
+dependencies = [
+ "typenum",
+]
+
+[[package]]
+name = "hyper"
+version = "1.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43"
+dependencies = [
+ "atomic-waker",
+ "bytes",
+ "futures-channel",
+ "futures-core",
+ "http",
+ "http-body",
+ "httparse",
+ "itoa",
+ "pin-project-lite",
+ "smallvec",
+ "tokio",
+ "want",
+]
+
+[[package]]
+name = "hyper-util"
+version = "0.1.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff"
+dependencies = [
+ "base64",
+ "bytes",
+ "futures-channel",
+ "futures-util",
+ "http",
+ "http-body",
+ "httparse",
+ "hyper",
+ "ipnet",
+ "libc",
+ "percent-encoding",
+ "pin-project-lite",
+ "socket2",
+ "tokio",
+ "tower-service",
+ "tracing",
+]
+
+[[package]]
+name = "iana-time-zone"
+version = "0.1.65"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
+dependencies = [
+ "android_system_properties",
+ "core-foundation-sys",
+ "iana-time-zone-haiku",
+ "js-sys",
+ "log",
+ "wasm-bindgen",
+ "windows-core",
+]
+
+[[package]]
+name = "iana-time-zone-haiku"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
+dependencies = [
+ "cc",
+]
+
+[[package]]
+name = "icu_collections"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fa68d21081c4a05d5a901a1c62add574c77048b6a1c67be3b50ce0b60d4ca513"
+dependencies = [
+ "displaydoc",
+ "potential_utf",
+ "utf8_iter",
+ "yoke",
+ "zerofrom",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_locale_core"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d56e28588da92eee5c3201a6eff33fabdd49b62269c8938d4ff050ce4d900deb"
+dependencies = [
+ "displaydoc",
+ "litemap",
+ "tinystr",
+ "writeable",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "12f9cf5f235641ed274641dd81c3f28d870e276763d0797aeeab72317b1c646f"
+dependencies = [
+ "icu_collections",
+ "icu_normalizer_data",
+ "icu_properties",
+ "icu_provider",
+ "smallvec",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_normalizer_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1563da1ed3e0b3bf3d74c9b85917ac9c56464d2f57242270c09c9e752f8021a0"
+
+[[package]]
+name = "icu_properties"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7e7ca276ad3145661a65914e6daf131ca5120cd3dcee8f8f3214b8875184a148"
+dependencies = [
+ "displaydoc",
+ "icu_collections",
+ "icu_locale_core",
+ "icu_properties_data",
+ "icu_provider",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "icu_properties_data"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e590f038c1464a96894fd6d10127e90a8be4509f56ff7ecef851b15cee0b7caa"
+
+[[package]]
+name = "icu_provider"
+version = "2.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d27bbb9d3abbefac45d55f647c9de1d44aafcd1186eb91879afef17c396c3e73"
+dependencies = [
+ "displaydoc",
+ "icu_locale_core",
+ "writeable",
+ "yoke",
+ "zerofrom",
+ "zerotrie",
+ "zerovec",
+]
+
+[[package]]
+name = "idna"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
+dependencies = [
+ "idna_adapter",
+ "smallvec",
+ "utf8_iter",
+]
+
+[[package]]
+name = "idna_adapter"
+version = "1.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
+dependencies = [
+ "icu_normalizer",
+ "icu_properties",
+]
+
+[[package]]
+name = "image"
+version = "0.25.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104"
+dependencies = [
+ "bytemuck",
+ "byteorder-lite",
+ "color_quant",
+ "gif",
+ "image-webp",
+ "moxcms",
+ "num-traits",
+ "png",
+ "tiff",
+ "zune-core",
+ "zune-jpeg",
+]
+
+[[package]]
+name = "image-webp"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3"
+dependencies = [
+ "byteorder-lite",
+ "quick-error",
+]
+
+[[package]]
+name = "ipnet"
+version = "2.12.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "js-sys"
+version = "0.3.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5"
+dependencies = [
+ "cfg-if",
+ "futures-util",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.190"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78"
+
+[[package]]
+name = "libredox"
+version = "0.1.25"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "libsqlite3-sys"
+version = "0.38.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1d20bef17f513b9b3004532233187769cd072d790971f4e4da0e346eb6401e8"
+dependencies = [
+ "cc",
+ "pkg-config",
+ "vcpkg",
+]
+
+[[package]]
+name = "litemap"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"
+
+[[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.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6"
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "miniz_oxide"
+version = "0.8.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "miniz_oxide"
+version = "0.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
+dependencies = [
+ "adler2",
+ "simd-adler32",
+]
+
+[[package]]
+name = "mio"
+version = "1.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee"
+dependencies = [
+ "libc",
+ "wasi",
+ "windows-sys",
+]
+
+[[package]]
+name = "moxcms"
+version = "0.8.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b"
+dependencies = [
+ "num-traits",
+ "pxfm",
+]
+
+[[package]]
+name = "ntapi"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae"
+dependencies = [
+ "winapi",
+]
+
+[[package]]
+name = "num-traits"
+version = "0.2.19"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
+dependencies = [
+ "autocfg",
+]
+
+[[package]]
+name = "objc2"
+version = "0.6.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8"
+dependencies = [
+ "objc2-encode",
+]
+
+[[package]]
+name = "objc2-core-foundation"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
+dependencies = [
+ "bitflags",
+ "dispatch2",
+ "objc2",
+]
+
+[[package]]
+name = "objc2-encode"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
+
+[[package]]
+name = "objc2-foundation"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
+dependencies = [
+ "bitflags",
+ "objc2",
+]
+
+[[package]]
+name = "objc2-io-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15"
+dependencies = [
+ "libc",
+ "objc2-core-foundation",
+]
+
+[[package]]
+name = "objc2-open-directory"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb82bed227edf5201dfedf072bba4015a33d3d4a98519837295a90f0a23f676d"
+dependencies = [
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "once_cell"
+version = "1.21.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
+
+[[package]]
+name = "option-ext"
+version = "0.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
+
+[[package]]
+name = "parking_lot"
+version = "0.12.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
+dependencies = [
+ "lock_api",
+ "parking_lot_core",
+]
+
+[[package]]
+name = "parking_lot_core"
+version = "0.9.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "redox_syscall",
+ "smallvec",
+ "windows-link",
+]
+
+[[package]]
+name = "percent-encoding"
+version = "2.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
+
+[[package]]
+name = "pkg-config"
+version = "0.3.34"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"
+
+[[package]]
+name = "png"
+version = "0.18.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
+dependencies = [
+ "bitflags",
+ "crc32fast",
+ "fdeflate",
+ "flate2",
+ "miniz_oxide 0.8.9",
+]
+
+[[package]]
+name = "potential_utf"
+version = "0.1.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661"
+dependencies = [
+ "zerovec",
+]
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.107"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "pxfm"
+version = "0.1.30"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"
+
+[[package]]
+name = "qls-core"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "base64",
+ "chrono",
+ "dirs",
+ "hex",
+ "image",
+ "png",
+ "rand",
+ "regex",
+ "reqwest",
+ "rusqlite",
+ "serde",
+ "serde_json",
+ "sha2",
+ "sysinfo",
+ "thiserror",
+ "tokio",
+ "tracing",
+ "uuid",
+]
+
+[[package]]
+name = "quick-error"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"
+
+[[package]]
+name = "quote"
+version = "1.0.47"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rand"
+version = "0.10.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af"
+dependencies = [
+ "chacha20",
+ "getrandom",
+ "rand_core",
+]
+
+[[package]]
+name = "rand_core"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+
+[[package]]
+name = "redox_syscall"
+version = "0.5.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
+dependencies = [
+ "bitflags",
+]
+
+[[package]]
+name = "redox_users"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0"
+dependencies = [
+ "libredox",
+ "thiserror",
+]
+
+[[package]]
+name = "regex"
+version = "1.13.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-automata",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-automata"
+version = "0.4.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"
+dependencies = [
+ "aho-corasick",
+ "memchr",
+ "regex-syntax",
+]
+
+[[package]]
+name = "regex-syntax"
+version = "0.8.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
+
+[[package]]
+name = "reqwest"
+version = "0.13.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029"
+dependencies = [
+ "base64",
+ "bytes",
+ "futures-core",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-util",
+ "js-sys",
+ "log",
+ "percent-encoding",
+ "pin-project-lite",
+ "serde",
+ "serde_json",
+ "sync_wrapper",
+ "tokio",
+ "tower",
+ "tower-http",
+ "tower-service",
+ "url",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+]
+
+[[package]]
+name = "rsqlite-vfs"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c51c9ae4df8a7fba42103df5c621fa3c37eccf3a3c650879e90fc48b11cc192c"
+dependencies = [
+ "hashbrown 0.16.1",
+ "thiserror",
+]
+
+[[package]]
+name = "rusqlite"
+version = "0.40.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23f2a97da3e3873c73cb2a2e71b35c40ff95e0b1eefa8d72d8499a6928c3b5b3"
+dependencies = [
+ "bitflags",
+ "fallible-iterator",
+ "fallible-streaming-iterator",
+ "hashlink",
+ "libsqlite3-sys",
+ "smallvec",
+ "sqlite-wasm-rs",
+]
+
+[[package]]
+name = "rustversion"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+
+[[package]]
+name = "scopeguard"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+
+[[package]]
+name = "serde"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.229"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.151"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "sha2"
+version = "0.11.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "digest",
+]
+
+[[package]]
+name = "shlex"
+version = "2.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
+
+[[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.10"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
+
+[[package]]
+name = "slab"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
+
+[[package]]
+name = "smallvec"
+version = "1.16.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e"
+
+[[package]]
+name = "socket2"
+version = "0.6.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"
+dependencies = [
+ "libc",
+ "windows-sys",
+]
+
+[[package]]
+name = "sqlite-wasm-rs"
+version = "0.5.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dc3efc0da82635d7e1ced0053bbbfa8c7ab9645d0bf36ceb4f7127bb85315d75"
+dependencies = [
+ "cc",
+ "js-sys",
+ "rsqlite-vfs",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "sync_wrapper"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
+dependencies = [
+ "futures-core",
+]
+
+[[package]]
+name = "synstructure"
+version = "0.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "sysinfo"
+version = "0.39.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2071df9448915b71c4fe6d25deaf1c22f12bd234f01540b77312bb8e41361e6"
+dependencies = [
+ "libc",
+ "memchr",
+ "ntapi",
+ "objc2-core-foundation",
+ "objc2-io-kit",
+ "objc2-open-directory",
+ "windows",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "tiff"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52"
+dependencies = [
+ "fax",
+ "flate2",
+ "half",
+ "quick-error",
+ "weezl",
+ "zune-jpeg",
+]
+
+[[package]]
+name = "tinystr"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b1e27c91459209c2986af3dcf603a5a74a4368754ce37414f59acc971167f643"
+dependencies = [
+ "displaydoc",
+ "zerovec",
+]
+
+[[package]]
+name = "tokio"
+version = "1.53.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e95f91fcc7a621e8b030f6aa23c71fe9838ae2fb4d8118b75602a328f5144044"
+dependencies = [
+ "bytes",
+ "libc",
+ "mio",
+ "parking_lot",
+ "pin-project-lite",
+ "signal-hook-registry",
+ "socket2",
+ "tokio-macros",
+ "windows-sys",
+]
+
+[[package]]
+name = "tokio-macros"
+version = "2.7.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "tower"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
+dependencies = [
+ "futures-core",
+ "futures-util",
+ "pin-project-lite",
+ "sync_wrapper",
+ "tokio",
+ "tower-layer",
+ "tower-service",
+]
+
+[[package]]
+name = "tower-http"
+version = "0.6.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
+dependencies = [
+ "bitflags",
+ "bytes",
+ "futures-util",
+ "http",
+ "http-body",
+ "pin-project-lite",
+ "tower",
+ "tower-layer",
+ "tower-service",
+ "url",
+]
+
+[[package]]
+name = "tower-layer"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
+
+[[package]]
+name = "tower-service"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
+
+[[package]]
+name = "tracing"
+version = "0.1.44"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
+dependencies = [
+ "pin-project-lite",
+ "tracing-attributes",
+ "tracing-core",
+]
+
+[[package]]
+name = "tracing-attributes"
+version = "0.1.31"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "tracing-core"
+version = "0.1.36"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
+dependencies = [
+ "once_cell",
+]
+
+[[package]]
+name = "try-lock"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954"
+
+[[package]]
+name = "url"
+version = "2.5.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
+dependencies = [
+ "form_urlencoded",
+ "idna",
+ "percent-encoding",
+ "serde",
+]
+
+[[package]]
+name = "utf8_iter"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
+
+[[package]]
+name = "uuid"
+version = "1.27.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "97277d36b9c3ace13e58fa6e753f8b0bbbf302a18dd193240d70f9e29681059a"
+dependencies = [
+ "getrandom",
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "vcpkg"
+version = "0.2.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
+
+[[package]]
+name = "want"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b"
+dependencies = [
+ "try-lock",
+]
+
+[[package]]
+name = "wasi"
+version = "0.11.1+wasi-snapshot-preview1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409"
+dependencies = [
+ "cfg-if",
+ "once_cell",
+ "rustversion",
+ "wasm-bindgen-macro",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-futures"
+version = "0.4.79"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e"
+dependencies = [
+ "js-sys",
+ "tokio",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen-macro"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535"
+dependencies = [
+ "quote",
+ "wasm-bindgen-macro-support",
+]
+
+[[package]]
+name = "wasm-bindgen-macro-support"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7"
+dependencies = [
+ "bumpalo",
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+ "wasm-bindgen-shared",
+]
+
+[[package]]
+name = "wasm-bindgen-shared"
+version = "0.2.129"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "web-sys"
+version = "0.3.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4"
+dependencies = [
+ "js-sys",
+ "wasm-bindgen",
+]
+
+[[package]]
+name = "weezl"
+version = "0.1.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88"
+
+[[package]]
+name = "winapi"
+version = "0.3.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"
+dependencies = [
+ "winapi-i686-pc-windows-gnu",
+ "winapi-x86_64-pc-windows-gnu",
+]
+
+[[package]]
+name = "winapi-i686-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
+
+[[package]]
+name = "winapi-x86_64-pc-windows-gnu"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+
+[[package]]
+name = "windows"
+version = "0.62.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"
+dependencies = [
+ "windows-collections",
+ "windows-core",
+ "windows-future",
+ "windows-numerics",
+]
+
+[[package]]
+name = "windows-collections"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"
+dependencies = [
+ "windows-core",
+]
+
+[[package]]
+name = "windows-core"
+version = "0.62.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
+dependencies = [
+ "windows-implement",
+ "windows-interface",
+ "windows-link",
+ "windows-result",
+ "windows-strings",
+]
+
+[[package]]
+name = "windows-future"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"
+dependencies = [
+ "windows-core",
+ "windows-link",
+ "windows-threading",
+]
+
+[[package]]
+name = "windows-implement"
+version = "0.60.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "windows-interface"
+version = "0.59.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-numerics"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"
+dependencies = [
+ "windows-core",
+ "windows-link",
+]
+
+[[package]]
+name = "windows-result"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-strings"
+version = "0.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "windows-threading"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "writeable"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc"
+
+[[package]]
+name = "yoke"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
+dependencies = [
+ "stable_deref_trait",
+ "yoke-derive",
+ "zerofrom",
+]
+
+[[package]]
+name = "yoke-derive"
+version = "0.8.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+ "synstructure",
+]
+
+[[package]]
+name = "zerocopy"
+version = "0.8.60"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6400fc4bb7426f6faac3fb07566122bb18622e3022bd2c36426a92ed489b1dbe"
+dependencies = [
+ "zerocopy-derive",
+]
+
+[[package]]
+name = "zerocopy-derive"
+version = "0.8.60"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "99c27cc7525bad4df59a45e073c45b2c2aa820efb588234cc23a547ec69a34db"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "zerofrom"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
+dependencies = [
+ "zerofrom-derive",
+]
+
+[[package]]
+name = "zerofrom-derive"
+version = "0.1.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+ "synstructure",
+]
+
+[[package]]
+name = "zerotrie"
+version = "0.2.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"
+dependencies = [
+ "displaydoc",
+ "yoke",
+ "zerofrom",
+]
+
+[[package]]
+name = "zerovec"
+version = "0.11.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb0464e17806c1d976d5cba29399c7f08e516e279e2ba493f63123b5fca67dd8"
+dependencies = [
+ "yoke",
+ "zerofrom",
+ "zerovec-derive",
+]
+
+[[package]]
+name = "zerovec-derive"
+version = "0.11.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "34df6fc39dbd26ddc9c10e6a2984476e13acce22e64e4487636ef494369225da"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 3.0.6",
+]
+
+[[package]]
+name = "zlib-rs"
+version = "0.6.8"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+
+[[package]]
+name = "zune-core"
+version = "0.5.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
+
+[[package]]
+name = "zune-jpeg"
+version = "0.5.15"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
+dependencies = [
+ "zune-core",
+]
diff --git a/crates/qls-core/Cargo.toml b/crates/qls-core/Cargo.toml
new file mode 100644
index 0000000..dba5589
--- /dev/null
+++ b/crates/qls-core/Cargo.toml
@@ -0,0 +1,31 @@
+[package]
+name = "qls-core"
+version.workspace = true
+edition.workspace = true
+
+[dependencies]
+anyhow = "1.0.104"
+base64 = "0.23.1"
+chrono = { version = "0.4.45", features = ["serde"] }
+dirs = "7.0.0"
+hex = "0.4.3"
+image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "webp", "bmp", "gif", "tiff"] }
+png = "0.18.1"
+
+regex = "1.13.1"
+reqwest = { version = "0.13.5", default-features = false, features = ["json"] }
+rusqlite = { version = "0.40.2", features = ["bundled"] }
+serde = { version = "1.0.229", features = ["derive"] }
+serde_json = "1.0.151"
+sha2 = "0.11.0"
+sysinfo = "0.39.6"
+thiserror = "2.0.21"
+tokio = { version = "1.53.2", features = ["full"] }
+tracing = "0.1.44"
+uuid = { version = "1.27.0", features = ["v4"] }
+
+[target.'cfg(windows)'.dependencies]
+windows = { version = "0.62", features = ["Win32_Graphics_Imaging", "Win32_System_Com"] }
+
+[dev-dependencies]
+tempfile = "3"
diff --git a/crates/qls-core/src/config.rs b/crates/qls-core/src/config.rs
new file mode 100644
index 0000000..e5a5c56
--- /dev/null
+++ b/crates/qls-core/src/config.rs
@@ -0,0 +1,547 @@
+//! Persistent configuration and model profiles. Stored as JSON in
+//! `%APPDATA%\Qwen Local Studio\config.json`; every field has a default so older or
+//! partial files keep loading.
+
+use std::path::{Path, PathBuf};
+
+use serde::{Deserialize, Serialize};
+
+use crate::error::{AppError, ErrorCode};
+
+pub const APP_NAME: &str = "Qwen Local Studio";
+pub const DEFAULT_SDCPP_DIR: &str = r"C:\AI\sdcpp";
+pub const DEFAULT_SERVER_PORT: u16 = 39150;
+pub const DEFAULT_SERVICE_PORT: u16 = 39151;
+/// ESRGAN models offered in Settings: (file stem, label, download URL). Chosen by visual A/B on
+/// a Qwen edit (2026-10-06): both keep fine texture that RealESRGAN_x4plus smooths away.
+pub const UPSCALER_CHOICES: &[(&str, &str, &str)] = &[
+ ("4x-UltraSharp", "UltraSharp", "https://huggingface.co/uwg/upscaler/resolve/main/ESRGAN/4x-UltraSharp.pth"),
+ ("4x_NMKD-Superscale-SP_178000_G", "Superscale-SP", "https://huggingface.co/uwg/upscaler/resolve/main/ESRGAN/4x_NMKD-Superscale-SP_178000_G.pth"),
+];
+pub const DEFAULT_UPSCALER: &str = UPSCALER_CHOICES[0].0;
+/// Default before schema 2; configs still on it are moved to [`DEFAULT_UPSCALER`].
+const OLD_DEFAULT_UPSCALER: &str = "RealESRGAN_x4plus";
+const SCHEMA_VERSION: u32 = 4;
+
+/// Where to download `name`, if it is one of [`UPSCALER_CHOICES`].
+pub fn upscaler_download_url(name: &str) -> Option<&'static str> {
+ UPSCALER_CHOICES.iter().find(|(n, _, _)| *n == name).map(|(_, _, u)| *u)
+}
+/// Extensions sd-server accepts for model-backed upscalers (common.cpp, commit 3f8527a).
+pub const UPSCALER_EXTENSIONS: &[&str] = &["pth", "safetensors", "gguf", "pt"];
+
+/// Where the text encoder's weights live. Compute always runs on the selected GPU except
+/// for `Cpu`, which also computes on the CPU (slow for image editing, measured ~35×).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "snake_case")]
+pub enum TextEncoderPlacement {
+ /// Weights in system RAM, compute on GPU (`--params-backend te=cpu`). Recommended.
+ #[default]
+ Ram,
+ /// Weights and compute on GPU (fastest prompt encoding, slower sampling on 16 GB).
+ Gpu,
+ /// Weights and compute on CPU (`--backend te=cpu`). Lowest VRAM, slow editing.
+ Cpu,
+ /// Let stable-diffusion.cpp's auto-fit decide.
+ Auto,
+}
+
+/// Effort of a Detailed upscale (low-denoise re-render at ~2K before the upscaler model).
+/// Generation itself always runs in one pass (two-pass refine removed 2026-10-06).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "snake_case")]
+pub enum RefineMode {
+ /// Kept for old configs; behaves like Fast.
+ Off,
+ /// Fewer refine steps + EasyCache.
+ #[default]
+ Fast,
+ /// More refine steps, no cache.
+ Best,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct RecommendedSettings {
+ pub sampler: String,
+ pub scheduler: Option<String>,
+ /// 1.0 = no classifier-free guidance: one model pass per step, negative prompt unused.
+ pub cfg: f32,
+ /// CFG for modes that start from an image (edit, multi-reference, inpaint, outpaint,
+ /// Detailed upscale).
+ pub cfg_edit: f32,
+ pub steps_fast: u32,
+ pub steps_balanced: u32,
+ pub steps_quality: u32,
+ /// Pixel area used by Auto resolution at each quality level.
+ pub area_fast: u64,
+ pub area_balanced: u64,
+ pub area_quality: u64,
+ pub align: u32,
+ pub max_side: u32,
+ pub max_references: u32,
+ pub negative_prompt: String,
+ /// Detailed upscale: largest re-render area and effective steps per effort.
+ pub hires_max_area: u64,
+ pub hires_steps_fast: u32,
+ pub hires_steps_best: u32,
+ /// EasyCache reuse threshold of a Fast Detailed upscale.
+ pub easycache_threshold: f32,
+}
+
+impl Default for RecommendedSettings {
+ fn default() -> Self {
+ // Official Qwen-Image 2.1 settings (QwenLM/Qwen-Image-2.1 README, diffusers
+ // QwenImage21Pipeline): no CFG ("meant to be sampled without guidance"), 40 steps,
+ // native 2K buckets; flow-matching Euler, whose resolution-dependent schedule
+ // sd-server selects automatically. Fast halves the steps for speed (not official).
+ Self {
+ sampler: "euler".into(),
+ scheduler: None,
+ cfg: 1.0,
+ cfg_edit: 1.0,
+ steps_fast: 20,
+ steps_balanced: 40,
+ steps_quality: 40,
+ area_fast: 1024 * 1024,
+ area_balanced: 1024 * 1024,
+ area_quality: 2048 * 2048,
+ align: 32,
+ max_side: 4096,
+ max_references: 10,
+ negative_prompt: String::new(),
+ hires_max_area: 2048 * 1152,
+ hires_steps_fast: 6,
+ hires_steps_best: 8,
+ easycache_threshold: 0.2,
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(default)]
+pub struct ProfileCapabilities {
+ pub text_to_image: bool,
+ pub edit: bool,
+ pub multi_reference: bool,
+ pub inpaint: bool,
+ pub outpaint: bool,
+ pub alpha: bool,
+}
+
+impl Default for ProfileCapabilities {
+ fn default() -> Self {
+ Self { text_to_image: true, edit: true, multi_reference: true, inpaint: true, outpaint: true, alpha: true }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct ModelProfile {
+ pub id: String,
+ pub display_name: String,
+ pub diffusion_model: PathBuf,
+ pub vae: PathBuf,
+ pub text_encoder: PathBuf,
+ pub vision_projector: Option<PathBuf>,
+ /// Extra sd-server arguments specific to this model.
+ pub backend_args: Vec<String>,
+ pub recommended_settings: RecommendedSettings,
+ pub capabilities: ProfileCapabilities,
+}
+
+impl Default for ModelProfile {
+ fn default() -> Self {
+ Self::qwen_image_21_q4(Path::new(DEFAULT_SDCPP_DIR))
+ }
+}
+
+impl ModelProfile {
+ pub fn qwen_image_21_q4(sdcpp_dir: &Path) -> Self {
+ let m = sdcpp_dir.join("models").join("qwen21");
+ Self {
+ id: "qwen-image-2.1-uc-q4km".into(),
+ display_name: "Qwen Image 2.1 UC Q4_K_M".into(),
+ diffusion_model: m.join("qwen-image-2.1-UC-Q4_K_M.gguf"),
+ vae: m.join("qwen_image_2.1_vae_bf16.safetensors"),
+ text_encoder: m.join("Qwen3VL-8B-Instruct-Q4_K_M.gguf"),
+ vision_projector: Some(m.join("mmproj-Qwen3VL-8B-Instruct-F16.gguf")),
+ backend_args: vec![],
+ recommended_settings: RecommendedSettings::default(),
+ capabilities: ProfileCapabilities::default(),
+ }
+ }
+
+ /// (label, path, required) for every model file.
+ pub fn files(&self) -> Vec<(&'static str, &Path, bool)> {
+ let mut v = vec![
+ ("Diffusion model", self.diffusion_model.as_path(), true),
+ ("VAE", self.vae.as_path(), true),
+ ("Text encoder (Qwen3-VL)", self.text_encoder.as_path(), true),
+ ];
+ if let Some(p) = &self.vision_projector {
+ v.push(("Vision projector (mmproj)", p.as_path(), true));
+ }
+ v
+ }
+
+ pub fn model_name(&self) -> String {
+ self.diffusion_model.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| self.display_name.clone())
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(default, rename_all = "camelCase")]
+pub struct AppConfig {
+ pub schema_version: u32,
+ pub sdcpp_dir: PathBuf,
+ pub server_port: u16,
+ pub service_port: u16,
+ pub active_profile: String,
+ pub profiles: Vec<ModelProfile>,
+ /// ggml device name for diffusion + VAE, e.g. "cuda0" (see `sd-server --list-devices`).
+ pub device: String,
+ pub text_encoder_placement: TextEncoderPlacement,
+ /// VRAM kept free, in GiB (passed as a negative `--max-vram`).
+ pub vram_reserve_gib: f32,
+ pub flash_attention: bool,
+ /// Native CUDA SageAttention in the diffusion model (`--sage-attn`); ~1.5x faster
+ /// steps at 2K on an RTX 5070 Ti with near-identical output.
+ pub sage_attention: bool,
+ /// VAE tile size in pixels (`--vae-tiling --vae-tile-size N`); 0 disables tiling.
+ /// Untiled 2K decodes need ~18 GB, OOM and retry with 256px tiles (~22 s); 768px
+ /// tiles decode 2K in ~4 s on a 16 GB card.
+ pub vae_tile_size: u32,
+ /// Storage type of the Qwen 2.1 prefix cache (text + reference K/V reused across steps,
+ /// `--model-args qwen_image_2_1_prefix_cache_type=...`). "auto" picks FP32 whenever
+ /// SageAttention is on: ~8 GiB for a 2 MP reference, which never fits on 16 GB, so every
+ /// edit fell back to the full sequence. "q8_0" (~2.2 GiB at 2 MP) fits; "f16" halves FP32;
+ /// "off" disables the cache.
+ pub prefix_cache_type: String,
+ /// Load all weights when the server starts (`--eager-load`) instead of on the first
+ /// step of the first job (~7 s of per-segment loading).
+ pub eager_load: bool,
+ /// Folder with ESRGAN models (`--hires-upscalers-dir`); None = `<sdcpp>\models\upscalers`.
+ pub upscalers_dir: Option<PathBuf>,
+ /// ESRGAN model name (file stem) used to enlarge results and for upscales.
+ pub upscaler_model: String,
+ /// ESRGAN tile size in pixels; 0 = backend default (128).
+ pub upscale_tile_size: u32,
+ /// Default effort of a Detailed upscale.
+ pub refine_mode: RefineMode,
+ pub extra_server_args: Vec<String>,
+ pub output_dir: PathBuf,
+ pub keep_server_running: bool,
+ /// When no desktop window is attached (e.g. MCP only), unload the model after this
+ /// many idle minutes. 0 disables.
+ pub idle_unload_minutes: u32,
+ pub setup_complete: bool,
+ /// Opaque UI preferences (last quality, resolution mode, aspect...).
+ pub ui: serde_json::Value,
+}
+
+impl Default for AppConfig {
+ fn default() -> Self {
+ let sdcpp = PathBuf::from(DEFAULT_SDCPP_DIR);
+ Self {
+ schema_version: SCHEMA_VERSION,
+ profiles: vec![ModelProfile::qwen_image_21_q4(&sdcpp)],
+ active_profile: "qwen-image-2.1-uc-q4km".into(),
+ sdcpp_dir: sdcpp,
+ server_port: DEFAULT_SERVER_PORT,
+ service_port: DEFAULT_SERVICE_PORT,
+ device: "cuda0".into(),
+ text_encoder_placement: TextEncoderPlacement::Ram,
+ vram_reserve_gib: 1.0,
+ flash_attention: true,
+ sage_attention: true,
+ vae_tile_size: 768,
+ prefix_cache_type: "q8_0".into(),
+ eager_load: true,
+ upscalers_dir: None,
+ upscaler_model: DEFAULT_UPSCALER.into(),
+ upscale_tile_size: 0,
+ refine_mode: RefineMode::Fast,
+ extra_server_args: vec![],
+ output_dir: default_output_dir(),
+ keep_server_running: false,
+ idle_unload_minutes: 15,
+ setup_complete: false,
+ ui: serde_json::json!({}),
+ }
+ }
+}
+
+pub fn default_output_dir() -> PathBuf {
+ dirs::picture_dir()
+ .or_else(|| dirs::home_dir().map(|h| h.join("Pictures")))
+ .unwrap_or_else(|| PathBuf::from("."))
+ .join(APP_NAME)
+}
+
+/// `%APPDATA%\Qwen Local Studio` (roaming) — configuration.
+pub fn config_dir() -> PathBuf {
+ if let Ok(p) = std::env::var("QLS_CONFIG_DIR") {
+ return PathBuf::from(p);
+ }
+ dirs::config_dir().unwrap_or_else(std::env::temp_dir).join(APP_NAME)
+}
+
+/// `%LOCALAPPDATA%\QwenLocalStudio` — gallery database, inputs, thumbnails, logs.
+/// Deliberately distinct from the installer's `%LOCALAPPDATA%\Qwen Local Studio`.
+pub fn data_dir() -> PathBuf {
+ if let Ok(p) = std::env::var("QLS_DATA_DIR") {
+ return PathBuf::from(p);
+ }
+ dirs::data_local_dir().unwrap_or_else(std::env::temp_dir).join("QwenLocalStudio")
+}
+
+impl AppConfig {
+ pub fn path() -> PathBuf {
+ config_dir().join("config.json")
+ }
+
+ pub fn load() -> Self {
+ Self::load_from(&Self::path())
+ }
+
+ pub fn load_from(path: &Path) -> Self {
+ match std::fs::read_to_string(path) {
+ // Windows PowerShell 5.1 writes UTF-8 with a BOM; accept it.
+ Ok(s) => match serde_json::from_str::<AppConfig>(s.trim_start_matches('\u{feff}')) {
+ Ok(mut c) => {
+ if c.profiles.is_empty() {
+ c.profiles.push(ModelProfile::qwen_image_21_q4(&c.sdcpp_dir));
+ }
+ if c.schema_version < 2 && c.upscaler_model.trim() == OLD_DEFAULT_UPSCALER {
+ c.upscaler_model = DEFAULT_UPSCALER.into();
+ }
+ if c.schema_version < 3 {
+ // Presets saved with the old defaults move to the new ones; edited values stay.
+ for p in &mut c.profiles {
+ let r = &mut p.recommended_settings;
+ if r.steps_balanced == 30 {
+ r.steps_balanced = 20;
+ }
+ if r.steps_quality == 40 {
+ r.steps_quality = 20;
+ }
+ if r.area_quality == 1536 * 1536 {
+ r.area_quality = 2_000_000;
+ }
+ }
+ }
+ if c.schema_version < 4 {
+ // Old defaults came from sd.cpp's example (CFG 6, edits 4, 20 steps);
+ // move them to the official settings. Edited values stay.
+ for p in &mut c.profiles {
+ let r = &mut p.recommended_settings;
+ if r.cfg == 6.0 {
+ r.cfg = 1.0;
+ }
+ if r.cfg_edit == 4.0 {
+ r.cfg_edit = 1.0;
+ }
+ if r.steps_balanced == 20 {
+ r.steps_balanced = 40;
+ }
+ if r.steps_quality == 20 {
+ r.steps_quality = 40;
+ }
+ if r.area_quality == 2_000_000 {
+ r.area_quality = 2048 * 2048;
+ }
+ }
+ }
+ c.schema_version = c.schema_version.max(SCHEMA_VERSION);
+ c
+ }
+ Err(e) => {
+ tracing::warn!("config at {} is invalid ({e}); using defaults", path.display());
+ let _ = std::fs::copy(path, path.with_extension("json.invalid"));
+ Self::default()
+ }
+ },
+ Err(_) => Self::default(),
+ }
+ }
+
+ pub fn save(&self) -> Result<(), AppError> {
+ self.save_to(&Self::path())
+ }
+
+ /// Atomic write: temp file + rename.
+ pub fn save_to(&self, path: &Path) -> Result<(), AppError> {
+ if let Some(dir) = path.parent() {
+ std::fs::create_dir_all(dir).map_err(|e| AppError::io("create the settings folder", dir, e))?;
+ }
+ let tmp = path.with_extension("json.tmp");
+ let json = serde_json::to_string_pretty(self).map_err(AppError::internal)?;
+ std::fs::write(&tmp, json).map_err(|e| AppError::io("write settings", &tmp, e))?;
+ std::fs::rename(&tmp, path).map_err(|e| AppError::io("save settings", path, e))?;
+ Ok(())
+ }
+
+ pub fn profile(&self) -> &ModelProfile {
+ self.profiles.iter().find(|p| p.id == self.active_profile).unwrap_or(&self.profiles[0])
+ }
+
+ pub fn server_exe(&self) -> PathBuf {
+ self.sdcpp_dir.join("sd-server.exe")
+ }
+
+ pub fn upscalers_dir(&self) -> PathBuf {
+ match &self.upscalers_dir {
+ Some(d) if !d.as_os_str().is_empty() => d.clone(),
+ _ => self.sdcpp_dir.join("models").join("upscalers"),
+ }
+ }
+
+ /// The configured ESRGAN model file, if present. sd-server resolves names the same
+ /// way: `<dir>/<name>.<ext>`, top level only.
+ pub fn upscaler_file(&self) -> Option<PathBuf> {
+ let name = self.upscaler_model.trim();
+ if name.is_empty() {
+ return None;
+ }
+ let dir = self.upscalers_dir();
+ UPSCALER_EXTENSIONS.iter().map(|e| dir.join(format!("{name}.{e}"))).find(|p| p.is_file())
+ }
+
+ pub fn validate(&self) -> Result<(), AppError> {
+ if self.server_port == self.service_port {
+ return Err(AppError::new(ErrorCode::InvalidConfig, "The inference server and the app service cannot use the same port."));
+ }
+ if self.server_port < 1024 || self.service_port < 1024 {
+ return Err(AppError::new(ErrorCode::InvalidConfig, "Ports must be 1024 or higher."));
+ }
+ if !(0.0..=64.0).contains(&self.vram_reserve_gib) {
+ return Err(AppError::new(ErrorCode::InvalidConfig, "VRAM reserve must be between 0 and 64 GiB."));
+ }
+ if self.device.trim().is_empty() || !self.device.chars().all(|c| c.is_ascii_alphanumeric()) {
+ return Err(AppError::new(ErrorCode::InvalidConfig, "Device must be a backend name such as cuda0."));
+ }
+ if self.prefix_cache_type.is_empty() || !self.prefix_cache_type.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') {
+ return Err(AppError::new(ErrorCode::InvalidConfig, "Prefix cache type must be auto, off, or a weight type such as q8_0 or f16."));
+ }
+ if self.profiles.is_empty() {
+ return Err(AppError::new(ErrorCode::InvalidConfig, "No model profile configured."));
+ }
+ Ok(())
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn defaults_match_spec() {
+ let c = AppConfig::default();
+ let p = c.profile();
+ assert_eq!(p.display_name, "Qwen Image 2.1 UC Q4_K_M");
+ assert!(p.diffusion_model.ends_with("qwen-image-2.1-UC-Q4_K_M.gguf"));
+ assert_eq!(c.device, "cuda0");
+ assert_eq!(c.vram_reserve_gib, 1.0);
+ assert!(c.flash_attention);
+ assert!(!c.keep_server_running);
+ assert!(c.validate().is_ok());
+ assert_eq!(p.files().len(), 4);
+ assert_eq!(c.refine_mode, RefineMode::Fast);
+ assert_eq!(c.upscaler_model, "4x-UltraSharp");
+ assert_eq!(c.upscalers_dir(), PathBuf::from(r"C:\AI\sdcpp\models\upscalers"));
+ }
+
+ #[test]
+ fn old_default_upscaler_is_migrated() {
+ let dir = tempfile::tempdir().unwrap();
+ let p = dir.path().join("config.json");
+ std::fs::write(&p, r#"{"schemaVersion":1,"upscalerModel":"RealESRGAN_x4plus"}"#).unwrap();
+ let c = AppConfig::load_from(&p);
+ assert_eq!(c.upscaler_model, DEFAULT_UPSCALER);
+ assert_eq!(c.schema_version, SCHEMA_VERSION);
+ // A choice made after the change is kept.
+ std::fs::write(&p, r#"{"schemaVersion":2,"upscalerModel":"RealESRGAN_x4plus"}"#).unwrap();
+ assert_eq!(AppConfig::load_from(&p).upscaler_model, "RealESRGAN_x4plus");
+ std::fs::write(&p, r#"{"schemaVersion":1,"upscalerModel":"4x_NMKD-Superscale-SP_178000_G"}"#).unwrap();
+ assert_eq!(AppConfig::load_from(&p).upscaler_model, "4x_NMKD-Superscale-SP_178000_G");
+ }
+
+ #[test]
+ fn old_quality_presets_are_migrated() {
+ let dir = tempfile::tempdir().unwrap();
+ let p = dir.path().join("config.json");
+ let old = r#"{"schemaVersion":2,"profiles":[{"id":"a","recommendedSettings":{"steps_balanced":30,"steps_quality":40,"area_quality":2359296}}]}"#;
+ std::fs::write(&p, old).unwrap();
+ let r = AppConfig::load_from(&p).profiles[0].recommended_settings.clone();
+ // Schema 3 then schema 4 run in sequence and end on the official settings.
+ assert_eq!((r.steps_balanced, r.steps_quality, r.area_quality, r.cfg_edit), (40, 40, 2048 * 2048, 1.0));
+ // Values the user changed are kept.
+ let custom = r#"{"schemaVersion":2,"profiles":[{"id":"a","recommendedSettings":{"steps_balanced":25,"steps_quality":50}}]}"#;
+ std::fs::write(&p, custom).unwrap();
+ let r = AppConfig::load_from(&p).profiles[0].recommended_settings.clone();
+ assert_eq!((r.steps_balanced, r.steps_quality), (25, 50));
+ }
+
+ #[test]
+ fn sdcpp_example_settings_move_to_official() {
+ let dir = tempfile::tempdir().unwrap();
+ let p = dir.path().join("config.json");
+ let old = r#"{"schemaVersion":3,"profiles":[{"id":"a","recommendedSettings":{"cfg":6.0,"cfg_edit":4.0,"steps_fast":20,"steps_balanced":20,"steps_quality":20,"area_quality":2000000}}]}"#;
+ std::fs::write(&p, old).unwrap();
+ let r = AppConfig::load_from(&p).profiles[0].recommended_settings.clone();
+ assert_eq!((r.cfg, r.cfg_edit), (1.0, 1.0));
+ assert_eq!((r.steps_fast, r.steps_balanced, r.steps_quality, r.area_quality), (20, 40, 40, 2048 * 2048));
+ assert_eq!(r, RecommendedSettings::default());
+ let custom = r#"{"schemaVersion":3,"profiles":[{"id":"a","recommendedSettings":{"cfg":3.0,"cfg_edit":2.5,"steps_balanced":28}}]}"#;
+ std::fs::write(&p, custom).unwrap();
+ let r = AppConfig::load_from(&p).profiles[0].recommended_settings.clone();
+ assert_eq!((r.cfg, r.cfg_edit, r.steps_balanced), (3.0, 2.5, 28));
+ }
+
+ #[test]
+ fn upscaler_file_lookup() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut c = AppConfig::default();
+ c.upscalers_dir = Some(dir.path().to_path_buf());
+ assert!(c.upscaler_file().is_none());
+ std::fs::write(dir.path().join("4x-UltraSharp.pth"), b"x").unwrap();
+ assert_eq!(c.upscaler_file().unwrap(), dir.path().join("4x-UltraSharp.pth"));
+ c.upscaler_model = " ".into();
+ assert!(c.upscaler_file().is_none());
+ // Older config files without the new fields keep loading with defaults.
+ let old: AppConfig = serde_json::from_str(r#"{"serverPort": 41000, "vaeTileSize": 512}"#).unwrap();
+ assert_eq!(old.refine_mode, RefineMode::Fast);
+ assert_eq!(old.profile().recommended_settings.hires_max_area, 2048 * 1152);
+ }
+
+ #[test]
+ fn roundtrip_and_partial_files() {
+ let dir = tempfile::tempdir().unwrap();
+ let path = dir.path().join("config.json");
+ let mut c = AppConfig::default();
+ c.server_port = 40000;
+ c.ui = serde_json::json!({"quality": "fast"});
+ c.save_to(&path).unwrap();
+ assert_eq!(AppConfig::load_from(&path), c);
+ std::fs::write(&path, r#"{"serverPort": 41000}"#).unwrap();
+ let p = AppConfig::load_from(&path);
+ assert_eq!(p.server_port, 41000);
+ assert_eq!(p.profiles.len(), 1);
+ std::fs::write(&path, "\u{feff}{\"serverPort\": 42000}").unwrap();
+ assert_eq!(AppConfig::load_from(&path).server_port, 42000, "UTF-8 BOM accepted");
+ std::fs::write(&path, "{ broken").unwrap();
+ assert_eq!(AppConfig::load_from(&path), AppConfig::default());
+ assert!(path.with_extension("json.invalid").exists());
+ }
+
+ #[test]
+ fn validation() {
+ let mut c = AppConfig::default();
+ c.service_port = c.server_port;
+ assert!(c.validate().is_err());
+ let mut c = AppConfig::default();
+ c.device = "cuda0; rm".into();
+ assert!(c.validate().is_err());
+ }
+}
diff --git a/crates/qls-core/src/diagnostics.rs b/crates/qls-core/src/diagnostics.rs
new file mode 100644
index 0000000..3fa9727
--- /dev/null
+++ b/crates/qls-core/src/diagnostics.rs
@@ -0,0 +1,191 @@
+//! Environment inspection: GPU, sd-server version/devices, first-launch readiness checks
+//! and the copyable diagnostics report.
+
+use std::path::Path;
+use std::time::Duration;
+
+use serde::Serialize;
+
+use crate::config::AppConfig;
+use crate::process::{parse_device_list, run_server_probe};
+
+#[derive(Debug, Clone, Serialize, Default)]
+pub struct GpuInfo {
+ pub name: String,
+ pub memory_total_mib: u64,
+ pub memory_used_mib: u64,
+ pub memory_free_mib: u64,
+ pub driver_version: String,
+}
+
+/// Queries NVIDIA GPUs through nvidia-smi (ships with the driver). None if unavailable.
+pub fn query_gpus() -> Option<Vec<GpuInfo>> {
+ let mut cmd = std::process::Command::new("nvidia-smi");
+ cmd.args(["--query-gpu=name,memory.total,memory.used,memory.free,driver_version", "--format=csv,noheader,nounits"]);
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ cmd.creation_flags(0x0800_0000);
+ }
+ let out = cmd.output().ok()?;
+ if !out.status.success() {
+ return None;
+ }
+ let text = String::from_utf8_lossy(&out.stdout);
+ let gpus: Vec<GpuInfo> = text.lines().filter_map(parse_gpu_line).collect();
+ (!gpus.is_empty()).then_some(gpus)
+}
+
+pub fn parse_gpu_line(line: &str) -> Option<GpuInfo> {
+ let f: Vec<&str> = line.split(',').map(str::trim).collect();
+ if f.len() < 5 {
+ return None;
+ }
+ Some(GpuInfo {
+ name: f[0].to_string(),
+ memory_total_mib: f[1].parse().ok()?,
+ memory_used_mib: f[2].parse().ok()?,
+ memory_free_mib: f[3].parse().ok()?,
+ driver_version: f[4].to_string(),
+ })
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct Check {
+ pub id: &'static str,
+ pub label: String,
+ pub ok: bool,
+ pub detail: String,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct SetupReport {
+ pub ready: bool,
+ pub checks: Vec<Check>,
+ pub devices: Vec<(String, String)>,
+ pub backend_version: Option<String>,
+}
+
+pub fn backend_version(exe: &Path) -> Option<String> {
+ run_server_probe(exe, &["--help"], Duration::from_secs(20)).and_then(|t| crate::sdcpp::parse_version_banner(&t))
+}
+
+pub fn list_devices(exe: &Path) -> Vec<(String, String)> {
+ run_server_probe(exe, &["--list-devices"], Duration::from_secs(30)).map(|t| parse_device_list(&t)).unwrap_or_default()
+}
+
+fn fmt_size(bytes: u64) -> String {
+ if bytes >= 1 << 30 { format!("{:.2} GB", bytes as f64 / (1u64 << 30) as f64) } else { format!("{:.0} MB", bytes as f64 / (1u64 << 20) as f64) }
+}
+
+/// First-launch / settings checks. `server_ok` is the live health result if known.
+pub fn setup_checks(cfg: &AppConfig, server_ok: Option<bool>) -> SetupReport {
+ let mut checks = Vec::new();
+ let dir_ok = cfg.sdcpp_dir.is_dir();
+ checks.push(Check { id: "sdcpp_dir", label: "stable-diffusion.cpp folder".into(), ok: dir_ok, detail: cfg.sdcpp_dir.display().to_string() });
+ let exe = cfg.server_exe();
+ let exe_ok = exe.is_file();
+ checks.push(Check { id: "server_exe", label: "sd-server.exe".into(), ok: exe_ok, detail: exe.display().to_string() });
+ for (label, path, _required) in cfg.profile().files() {
+ let meta = std::fs::metadata(path).ok().filter(|m| m.is_file());
+ checks.push(Check {
+ id: "model_file",
+ label: label.to_string(),
+ ok: meta.is_some(),
+ detail: match &meta {
+ Some(m) => format!("{} ({})", path.display(), fmt_size(m.len())),
+ None => format!("Missing: {}", path.display()),
+ },
+ });
+ }
+ let devices = if exe_ok { list_devices(&exe) } else { vec![] };
+ let wanted = cfg.device.to_ascii_lowercase();
+ let dev = devices.iter().find(|(n, _)| n.to_ascii_lowercase() == wanted);
+ let gpu_ok = dev.is_some();
+ checks.push(Check {
+ id: "device",
+ label: "GPU device".into(),
+ ok: gpu_ok,
+ detail: match dev {
+ Some((n, d)) => format!("{n} — {d}"),
+ None if devices.is_empty() => "No devices reported by sd-server".into(),
+ None => format!("{} not found. Available: {}", cfg.device, devices.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>().join(", ")),
+ },
+ });
+ if let Some(running) = server_ok {
+ // Informational: the server is started on demand, so "not running" is not a problem.
+ checks.push(Check {
+ id: "server",
+ label: "Inference server".into(),
+ ok: true,
+ detail: if running { "Running".into() } else { "Not running yet — starts automatically".into() },
+ });
+ }
+ checks.push(upscaler_check(cfg));
+ let backend_version = if exe_ok { backend_version(&exe) } else { None };
+ // The server and the ESRGAN model are optional: neither blocks starting.
+ let ready = checks.iter().filter(|c| c.id != "server" && c.id != "upscaler").all(|c| c.ok);
+ SetupReport { ready, checks, devices, backend_version }
+}
+
+/// ESRGAN model for sharper enlargements. Optional: without it Lanczos is used. The app
+/// never downloads models, so the check explains where to get it.
+pub fn upscaler_check(cfg: &AppConfig) -> Check {
+ let dir = cfg.upscalers_dir();
+ match cfg.upscaler_file() {
+ Some(p) => {
+ let size = std::fs::metadata(&p).map(|m| fmt_size(m.len())).unwrap_or_default();
+ Check { id: "upscaler", label: "ESRGAN upscaler (optional)".into(), ok: true, detail: format!("{} ({size})", p.display()) }
+ }
+ None => Check {
+ id: "upscaler",
+ label: "ESRGAN upscaler (optional)".into(),
+ ok: false,
+ detail: {
+ let name = cfg.upscaler_model.trim();
+ let get = crate::config::upscaler_download_url(name)
+ .map(|u| format!(" Download {u} (64 MB) into that folder for sharper results."))
+ .unwrap_or_default();
+ format!("Not found: {}\\{name}.pth — enlargements use Lanczos.{get}", dir.display())
+ },
+ },
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn gpu_line_parsing() {
+ let g = parse_gpu_line("NVIDIA GeForce RTX 5070 Ti, 16303, 2312, 13991, 617.14").unwrap();
+ assert_eq!(g.name, "NVIDIA GeForce RTX 5070 Ti");
+ assert_eq!((g.memory_total_mib, g.memory_used_mib, g.memory_free_mib), (16303, 2312, 13991));
+ assert_eq!(g.driver_version, "617.14");
+ assert!(parse_gpu_line("garbage").is_none());
+ }
+
+ #[test]
+ fn checks_flag_missing_files() {
+ let mut cfg = AppConfig::default();
+ cfg.sdcpp_dir = std::env::temp_dir().join("qls-does-not-exist");
+ cfg.profiles = vec![crate::config::ModelProfile::qwen_image_21_q4(&cfg.sdcpp_dir)];
+ let r = setup_checks(&cfg, None);
+ assert!(!r.ready);
+ assert!(r.checks.iter().any(|c| c.id == "server_exe" && !c.ok));
+ assert_eq!(r.checks.iter().filter(|c| c.id == "model_file").count(), 4);
+ let up = r.checks.iter().find(|c| c.id == "upscaler").unwrap();
+ assert!(!up.ok && up.detail.contains("4x-UltraSharp.pth") && up.detail.contains("huggingface.co/uwg/upscaler"));
+ }
+
+ #[test]
+ fn upscaler_check_is_optional() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut cfg = AppConfig::default();
+ cfg.upscalers_dir = Some(dir.path().to_path_buf());
+ assert!(!upscaler_check(&cfg).ok);
+ std::fs::write(dir.path().join("4x-UltraSharp.pth"), vec![0u8; 2048]).unwrap();
+ let c = upscaler_check(&cfg);
+ assert!(c.ok && c.detail.contains("4x-UltraSharp.pth"));
+ }
+}
diff --git a/crates/qls-core/src/engine.rs b/crates/qls-core/src/engine.rs
new file mode 100644
index 0000000..061708b
--- /dev/null
+++ b/crates/qls-core/src/engine.rs
@@ -0,0 +1,1111 @@
+//! The application engine shared by every front end (desktop UI, HTTP API, MCP):
+//! a queue of generation jobs executed one at a time against sd-server, with truthful
+//! progress, cancellation, automatic VRAM mitigation, and gallery persistence.
+
+use std::collections::{HashMap, VecDeque};
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex, RwLock};
+use std::time::{Duration, Instant};
+
+use image::GrayImage;
+use serde::Serialize;
+use tokio::sync::{Notify, broadcast};
+
+use crate::config::AppConfig;
+use crate::diagnostics::{GpuInfo, query_gpus};
+use crate::error::{AppError, AppResult, ErrorCode, translate_generation_failure};
+use crate::geometry::Size;
+use crate::imaging::{self, LoadedImage};
+use crate::paths;
+use crate::pipeline;
+use crate::planner::{self, GenerationRequest, Mode, OutputFormat, Plan, PlanInputs, ResolutionMode, ResolvedMode, UpscaleMethod};
+use crate::process::{BackendProgress, BackendStage, ProgressParser, ServerManager, ServerState};
+use crate::sdcpp::{BackendJobStatus, CancelOutcome, SdcppClient, UpscaleRequest};
+use crate::store::{GenerationRecord, InputRecord, PipelineRecord, ReferenceRecord, Store, new_id, now_rfc3339};
+
+pub const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum JobStatus {
+ Queued,
+ StartingBackend,
+ Preparing,
+ Running,
+ Saving,
+ Done,
+ Failed,
+ Cancelled,
+}
+
+impl JobStatus {
+ pub fn is_terminal(&self) -> bool {
+ matches!(self, Self::Done | Self::Failed | Self::Cancelled)
+ }
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct JobView {
+ pub id: String,
+ pub status: JobStatus,
+ /// Backend-reported stage while running (None if the backend gives no detail).
+ pub stage: Option<BackendStage>,
+ pub step: Option<(u32, u32)>,
+ pub image: Option<(u32, u32)>,
+ pub seconds_per_step: Option<f32>,
+ pub queue_position: usize,
+ pub created_at: String,
+ pub started_at: Option<String>,
+ pub finished_at: Option<String>,
+ pub prompt: String,
+ pub client: Option<String>,
+ pub plan: Option<Plan>,
+ pub seed: Option<i64>,
+ pub results: Vec<GenerationRecord>,
+ pub error: Option<AppError>,
+ pub notes: Vec<String>,
+ /// True when progress comes from the server log (we launched it).
+ pub detailed_progress: bool,
+}
+
+struct Job {
+ view: JobView,
+ request: GenerationRequest,
+ cancel: bool,
+ retried_oom: bool,
+ workspace: Option<PathBuf>,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(tag = "type", rename_all = "snake_case")]
+pub enum Event {
+ Job { job: Box<JobView> },
+ Server { state: ServerState, owned: bool, error: Option<AppError> },
+ Gallery { id: String, change: &'static str },
+}
+
+pub struct Engine {
+ cfg: RwLock<AppConfig>,
+ pub server: Arc<ServerManager>,
+ pub store: Arc<Store>,
+ jobs: Mutex<HashMap<String, Job>>,
+ order: Mutex<VecDeque<String>>,
+ active: Mutex<Option<String>>,
+ wake: Notify,
+ pub events: broadcast::Sender<Event>,
+ gpu: Mutex<(Option<Instant>, Option<GpuInfo>)>,
+ backend_version: Mutex<Option<String>>,
+ last_activity: Mutex<Instant>,
+}
+
+fn random_seed() -> i64 {
+ let b = uuid::Uuid::new_v4();
+ let v = u32::from_le_bytes(b.as_bytes()[..4].try_into().unwrap());
+ (v & 0x7fff_ffff) as i64
+}
+
+/// Runs CPU-heavy image work off the async runtime.
+async fn blocking<T: Send + 'static>(f: impl FnOnce() -> AppResult<T> + Send + 'static) -> AppResult<T> {
+ tokio::task::spawn_blocking(f).await.map_err(AppError::internal)?
+}
+
+/// Planner inputs from the configuration and measured facts.
+pub fn plan_inputs(cfg: &AppConfig, image_sizes: Vec<Size>, mask: Option<(Size, Option<crate::geometry::Rect>, f64)>, vram_total_mib: Option<u64>) -> PlanInputs {
+ PlanInputs {
+ image_sizes,
+ mask,
+ vram_total_mib,
+ upscaler: cfg.upscaler_file().map(|_| cfg.upscaler_model.trim().to_string()),
+ refine: cfg.refine_mode,
+ server_vae_tiling: cfg.vae_tile_size > 0,
+ sage_attention: cfg.sage_attention,
+ }
+}
+
+impl Engine {
+ pub fn new(cfg: AppConfig, data_dir: &Path) -> AppResult<Arc<Self>> {
+ let store = Arc::new(Store::open(data_dir)?);
+ let (events, _) = broadcast::channel(512);
+ Ok(Arc::new(Self {
+ cfg: RwLock::new(cfg),
+ server: ServerManager::new(data_dir.to_path_buf()),
+ store,
+ jobs: Mutex::new(HashMap::new()),
+ order: Mutex::new(VecDeque::new()),
+ active: Mutex::new(None),
+ wake: Notify::new(),
+ events,
+ gpu: Mutex::new((None, None)),
+ backend_version: Mutex::new(None),
+ last_activity: Mutex::new(Instant::now()),
+ }))
+ }
+
+ pub fn config(&self) -> AppConfig {
+ self.cfg.read().unwrap().clone()
+ }
+
+ /// Replaces the configuration. Returns true when the backend must restart.
+ pub fn set_config(&self, new: AppConfig) -> AppResult<bool> {
+ new.validate()?;
+ new.save()?;
+ let mut g = self.cfg.write().unwrap();
+ let restart = crate::process::build_server_args(&g, g.profile()) != crate::process::build_server_args(&new, new.profile())
+ || g.sdcpp_dir != new.sdcpp_dir;
+ *g = new;
+ *self.backend_version.lock().unwrap() = None;
+ Ok(restart)
+ }
+
+ pub fn touch(&self) {
+ *self.last_activity.lock().unwrap() = Instant::now();
+ }
+
+ pub fn idle_for(&self) -> Duration {
+ self.last_activity.lock().unwrap().elapsed()
+ }
+
+ pub fn has_pending_work(&self) -> bool {
+ self.active.lock().unwrap().is_some() || self.jobs.lock().unwrap().values().any(|j| !j.view.status.is_terminal())
+ }
+
+ pub fn gpu(&self) -> Option<GpuInfo> {
+ let mut g = self.gpu.lock().unwrap();
+ if g.0.map(|t| t.elapsed() < Duration::from_secs(3)).unwrap_or(false) {
+ return g.1.clone();
+ }
+ let info = query_gpus().and_then(|v| v.into_iter().next());
+ *g = (Some(Instant::now()), info.clone());
+ info
+ }
+
+ pub fn backend_version(&self) -> Option<String> {
+ if let Some(v) = self.backend_version.lock().unwrap().clone() {
+ return Some(v);
+ }
+ let v = crate::diagnostics::backend_version(&self.config().server_exe());
+ *self.backend_version.lock().unwrap() = v.clone();
+ v
+ }
+
+ fn emit_job(&self, id: &str) {
+ if let Some(v) = self.job(id) {
+ let _ = self.events.send(Event::Job { job: Box::new(v) });
+ }
+ }
+
+ pub fn emit_server(&self) {
+ let s = self.server.status();
+ let _ = self.events.send(Event::Server { state: s.state, owned: s.owned, error: s.error });
+ }
+
+ fn update(&self, id: &str, f: impl FnOnce(&mut Job)) {
+ {
+ let mut jobs = self.jobs.lock().unwrap();
+ if let Some(j) = jobs.get_mut(id) {
+ f(j);
+ }
+ }
+ self.emit_job(id);
+ }
+
+ fn queue_positions(&self) {
+ let order = self.order.lock().unwrap();
+ let mut jobs = self.jobs.lock().unwrap();
+ let mut pos = 0;
+ for id in order.iter() {
+ if let Some(j) = jobs.get_mut(id)
+ && j.view.status == JobStatus::Queued
+ {
+ pos += 1;
+ j.view.queue_position = pos;
+ }
+ }
+ }
+
+ pub fn job(&self, id: &str) -> Option<JobView> {
+ self.jobs.lock().unwrap().get(id).map(|j| j.view.clone())
+ }
+
+ pub fn jobs(&self) -> Vec<JobView> {
+ let order = self.order.lock().unwrap();
+ let jobs = self.jobs.lock().unwrap();
+ order.iter().filter_map(|id| jobs.get(id).map(|j| j.view.clone())).collect()
+ }
+
+ pub fn active_job(&self) -> Option<JobView> {
+ let id = self.active.lock().unwrap().clone()?;
+ self.job(&id)
+ }
+
+ /// Validates cheaply and enqueues. `workspace` is the caller's project folder (MCP),
+ /// used to resolve relative paths and as an allowed output root.
+ pub fn submit(&self, mut request: GenerationRequest, workspace: Option<PathBuf>) -> AppResult<JobView> {
+ self.touch();
+ let upscale = request.mode == Mode::Upscale;
+ if request.prompt.trim().is_empty() && !upscale {
+ return Err(AppError::invalid("Describe what to generate or change."));
+ }
+ if upscale && request.images.is_empty() {
+ return Err(AppError::invalid("Choose an image to upscale."));
+ }
+ if request.images.len() > 16 {
+ return Err(AppError::invalid("Too many images."));
+ }
+ if let Some(seed) = request.seed
+ && seed < 0
+ {
+ request.seed = None;
+ }
+ let id = format!("job_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
+ let view = JobView {
+ id: id.clone(),
+ status: JobStatus::Queued,
+ stage: None,
+ step: None,
+ image: None,
+ seconds_per_step: None,
+ queue_position: 0,
+ created_at: now_rfc3339(),
+ started_at: None,
+ finished_at: None,
+ prompt: if upscale && request.prompt.trim().is_empty() {
+ match request.upscale.map(|u| u.method).unwrap_or_default() {
+ UpscaleMethod::Quick => "Upscale (Quick)".into(),
+ UpscaleMethod::Detailed => "Upscale (Detailed)".into(),
+ }
+ } else {
+ request.prompt.clone()
+ },
+ client: request.client.clone(),
+ plan: None,
+ seed: request.seed,
+ results: vec![],
+ error: None,
+ notes: vec![],
+ detailed_progress: false,
+ };
+ {
+ let mut jobs = self.jobs.lock().unwrap();
+ jobs.insert(id.clone(), Job { view, request, cancel: false, retried_oom: false, workspace });
+ let mut order = self.order.lock().unwrap();
+ order.push_back(id.clone());
+ // Keep memory bounded: drop the oldest finished jobs.
+ while order.len() > 300 {
+ let Some(pos) = order.iter().position(|i| jobs.get(i).map(|j| j.view.status.is_terminal()).unwrap_or(true)) else { break };
+ if let Some(old) = order.remove(pos) {
+ jobs.remove(&old);
+ }
+ }
+ }
+ self.queue_positions();
+ self.emit_job(&id);
+ self.wake.notify_one();
+ Ok(self.job(&id).unwrap())
+ }
+
+ /// Requests cancellation. Queued jobs stop immediately; a running job is stopped as
+ /// soon as the backend allows (see `run_job`).
+ pub fn cancel(&self, id: &str) -> AppResult<JobView> {
+ let status = self.job(id).ok_or_else(|| AppError::new(ErrorCode::NotFound, "Unknown job."))?.status;
+ if status.is_terminal() {
+ return Ok(self.job(id).unwrap());
+ }
+ self.update(id, |j| {
+ j.cancel = true;
+ if j.view.status == JobStatus::Queued {
+ j.view.status = JobStatus::Cancelled;
+ j.view.finished_at = Some(now_rfc3339());
+ }
+ });
+ self.queue_positions();
+ Ok(self.job(id).unwrap())
+ }
+
+ /// Cancels every unfinished job submitted by `client` (e.g. "ui" when the desktop app
+ /// closes). A running job stops the owned server, which frees the GPU right away.
+ pub fn cancel_client_jobs(&self, client: &str) -> usize {
+ let ids: Vec<String> = {
+ let jobs = self.jobs.lock().unwrap();
+ jobs.values().filter(|j| !j.view.status.is_terminal() && j.view.client.as_deref() == Some(client)).map(|j| j.view.id.clone()).collect()
+ };
+ for id in &ids {
+ let _ = self.cancel(id);
+ }
+ ids.len()
+ }
+
+ fn next_queued(&self) -> Option<String> {
+ let order = self.order.lock().unwrap();
+ let jobs = self.jobs.lock().unwrap();
+ order.iter().find(|id| jobs.get(*id).map(|j| j.view.status == JobStatus::Queued).unwrap_or(false)).cloned()
+ }
+
+ /// Worker loop: one job at a time (the GPU is the bottleneck); the queue keeps order.
+ pub async fn run_worker(self: Arc<Self>) {
+ loop {
+ let Some(id) = self.next_queued() else {
+ self.wake.notified().await;
+ continue;
+ };
+ *self.active.lock().unwrap() = Some(id.clone());
+ self.queue_positions();
+ let r = self.clone().run_job(&id).await;
+ if let Err(e) = r {
+ let cancelled = self.jobs.lock().unwrap().get(&id).map(|j| j.cancel).unwrap_or(false);
+ self.update(&id, |j| {
+ if cancelled || e.code == ErrorCode::Cancelled {
+ j.view.status = JobStatus::Cancelled;
+ } else {
+ j.view.status = JobStatus::Failed;
+ j.view.error = Some(e.clone());
+ }
+ j.view.finished_at = Some(now_rfc3339());
+ j.view.stage = None;
+ });
+ if !cancelled {
+ tracing::warn!("job {id} failed: {} {:?}", e.message, e.detail);
+ }
+ }
+ *self.active.lock().unwrap() = None;
+ self.touch();
+ }
+ }
+
+ fn is_cancelled(&self, id: &str) -> bool {
+ self.jobs.lock().unwrap().get(id).map(|j| j.cancel).unwrap_or(true)
+ }
+
+ fn check_cancel(&self, id: &str) -> AppResult<()> {
+ if self.is_cancelled(id) { Err(AppError::new(ErrorCode::Cancelled, "Cancelled.")) } else { Ok(()) }
+ }
+
+ /// Loads one image source: "input:<id>", "gen:<id>" or an absolute path.
+ pub fn resolve_source(&self, src: &str, workspace: Option<&Path>) -> AppResult<(LoadedImage, InputRecord)> {
+ let (bytes, original_path, name) = if let Some(id) = src.strip_prefix("input:") {
+ let rec = self.store.get_input(id)?;
+ let b = std::fs::read(&rec.path).map_err(|e| AppError::io("read the stored image", Path::new(&rec.path), e))?;
+ (b, rec.original_path.clone(), rec.original_name.clone())
+ } else if let Some(id) = src.strip_prefix("gen:") {
+ let rec = self.store.get_generation(id)?;
+ let p = PathBuf::from(&rec.file_path);
+ let b = std::fs::read(&p).map_err(|e| AppError::io("read the generated image", &p, e))?;
+ (b, Some(rec.file_path.clone()), p.file_name().map(|n| n.to_string_lossy().into_owned()))
+ } else {
+ let p = paths::validate_input_image(src, workspace, &[])?;
+ let b = std::fs::read(&p).map_err(|e| AppError::io("read the image", &p, e))?;
+ (b, Some(p.to_string_lossy().into_owned()), p.file_name().map(|n| n.to_string_lossy().into_owned()))
+ };
+ let rec = self.store.put_input(&bytes, name.as_deref(), original_path.as_deref())?;
+ let img = imaging::decode_image(&bytes)?;
+ Ok((img, rec))
+ }
+
+ /// Dry run: the plan a request would get (used by the UI to show working sizes).
+ pub fn preview_plan(&self, req: &GenerationRequest, sizes: Vec<Size>, mask: Option<(Size, Option<crate::geometry::Rect>, f64)>) -> AppResult<Plan> {
+ let cfg = self.config();
+ let vram = self.gpu().map(|g| g.memory_total_mib);
+ planner::plan(req, &plan_inputs(&cfg, sizes, mask, vram), &cfg.profile().recommended_settings)
+ }
+
+ async fn run_job(self: Arc<Self>, id: &str) -> AppResult<()> {
+ let started = Instant::now();
+ let (request, workspace) = {
+ let jobs = self.jobs.lock().unwrap();
+ let j = jobs.get(id).ok_or_else(|| AppError::internal("job vanished"))?;
+ (j.request.clone(), j.workspace.clone())
+ };
+ self.update(id, |j| {
+ j.view.status = JobStatus::Preparing;
+ j.view.started_at = Some(now_rfc3339());
+ j.view.queue_position = 0;
+ });
+
+ // 1. Load inputs (off the async runtime: decoding large photos is CPU work).
+ let this = self.clone();
+ let req2 = request.clone();
+ let ws = workspace.clone();
+ let (images, inputs_meta, mask) = tokio::task::spawn_blocking(move || -> AppResult<_> {
+ let mut images = Vec::new();
+ let mut metas = Vec::new();
+ for s in &req2.images {
+ let (img, rec) = this.resolve_source(s, ws.as_deref())?;
+ images.push(img);
+ metas.push(rec);
+ }
+ let mask = match &req2.mask {
+ Some(m) => {
+ let (img, rec) = this.resolve_source(m, ws.as_deref())?;
+ Some((imaging::mask_from_image(&img), rec))
+ }
+ None => None,
+ };
+ Ok((images, metas, mask))
+ })
+ .await
+ .map_err(AppError::internal)??;
+ self.check_cancel(id)?;
+
+ // 2. Plan.
+ let cfg = self.config();
+ let profile = cfg.profile().clone();
+ let vram = self.gpu().map(|g| g.memory_total_mib);
+ let mask_info = mask.as_ref().map(|(m, _)| (Size::new(m.width(), m.height()), imaging::mask_bbox(m, 16), imaging::mask_coverage(m, 16)));
+ let plan_inputs = plan_inputs(&cfg, images.iter().map(|i| i.size()).collect(), mask_info, vram);
+ let plan = planner::plan(&request, &plan_inputs, &profile.recommended_settings)?;
+ let seed = request.seed.unwrap_or_else(random_seed);
+ let mut request = request;
+ if plan.mode == ResolvedMode::Upscale && request.prompt.trim().is_empty() {
+ request.prompt = self.upscale_prompt(&request, plan.steps == 0);
+ }
+ self.update(id, |j| {
+ j.view.plan = Some(plan.clone());
+ j.view.seed = Some(seed);
+ j.view.notes = plan.notes.clone();
+ });
+
+ // 3. Backend.
+ if self.server.status().state != ServerState::Ready || self.server.owned_alive() == Some(false) {
+ self.update(id, |j| j.view.status = JobStatus::StartingBackend);
+ self.emit_server();
+ let r = self.server.ensure_ready(&cfg).await;
+ self.emit_server();
+ r?;
+ }
+ self.check_cancel(id)?;
+ self.update(id, |j| j.view.status = JobStatus::Preparing);
+
+ // Which upscalers the running server really has (an external server may lack
+ // --hires-upscalers-dir): enlargements fall back to Lanczos.
+ // Fresh, because the server rescans the upscalers folder on every request.
+ let client = SdcppClient::new(cfg.server_port);
+ let caps = client.capabilities(Duration::from_secs(5)).await.ok().or_else(|| self.server.capabilities()).unwrap_or_default();
+ let esrgan = plan.upscaler.clone().filter(|n| caps.has_upscaler(n, true));
+ let needs_esrgan = plan.upscale.is_some() || plan.output.area() as f64 > plan.content.area() as f64 * 1.21;
+ if needs_esrgan && plan.upscaler.is_some() && esrgan.is_none() {
+ let name = plan.upscaler.clone().unwrap_or_default();
+ self.update(id, |j| j.view.notes.push(format!("The inference server did not list the upscaler model {name}; Lanczos was used instead.")));
+ } else if plan.upscaler.is_none() && plan.upscale.is_some() {
+ self.update(id, |j| {
+ j.view.notes.push(format!("Upscaler model {} not found; enlarged with Lanczos. Put {}.pth in the upscalers folder for sharper results.", cfg.upscaler_model, cfg.upscaler_model))
+ });
+ }
+ let quick_upscale = plan.upscale.map(|u| u.method == UpscaleMethod::Quick).unwrap_or(false);
+ let icc = images.first().and_then(|i| i.icc_profile.clone());
+
+ let (contents, post) = if quick_upscale {
+ // No diffusion: the source itself is enlarged.
+ let src = images.into_iter().next().ok_or_else(|| AppError::invalid("Choose an image to upscale."))?;
+ let size = src.size();
+ let post = pipeline::PostProcess {
+ kind: pipeline::PostKind::Plain,
+ keep_alpha: true,
+ working: size,
+ content: crate::geometry::Rect::new(0, 0, size.width, size.height),
+ output: plan.output,
+ mode: plan.mode,
+ outpaint: None,
+ };
+ (vec![src.pixels], post)
+ } else {
+ let mut images = images;
+ if plan.upscale.is_some() {
+ // Detailed: bring the source to the refine size first (ESRGAN when enlarging).
+ let target = Size::new(plan.content.width, plan.content.height);
+ let src = std::mem::replace(&mut images[0].pixels, image::RgbaImage::new(1, 1));
+ let (enlarged, _) = self.enlarge(id, &client, src, Some(target), esrgan.as_deref()).await?;
+ images[0].pixels = enlarged;
+ self.update(id, |j| {
+ j.view.status = JobStatus::Preparing;
+ j.view.stage = None;
+ });
+ }
+
+ // 4. Build the request (CPU work).
+ let plan2 = plan.clone();
+ let prompt = request.prompt.clone();
+ let mask_img: Option<GrayImage> = mask.as_ref().map(|(m, _)| m.clone());
+ let opts = pipeline::BackendOptions { server_vae_tile_size: cfg.vae_tile_size };
+ let prepared = tokio::task::spawn_blocking(move || pipeline::prepare(&plan2, &prompt, seed, &images, mask_img.as_ref(), &opts))
+ .await
+ .map_err(AppError::internal)??;
+ let pipeline::PreparedJob { request: sd_req, post } = prepared;
+
+ // 5. Submit and follow.
+ let mut lines = self.server.subscribe_lines();
+ let detailed = self.server.status().owned;
+ let accepted = client.submit(&sd_req).await?;
+ drop(sd_req); // release the base64 payloads
+ self.update(id, |j| {
+ j.view.status = JobStatus::Running;
+ j.view.detailed_progress = detailed;
+ });
+ let mut parser = ProgressParser::default();
+ let mut job_log: Vec<String> = Vec::new();
+ let mut last_poll = Instant::now() - Duration::from_secs(10);
+ let backend_job = loop {
+ // Drain log lines -> truthful stage/step.
+ loop {
+ match lines.try_recv() {
+ Ok(l) => {
+ if job_log.len() < 4000 {
+ job_log.push(l.clone());
+ }
+ if let Some(p) = parser.feed(&l) {
+ self.apply_progress(id, p);
+ }
+ }
+ Err(broadcast::error::TryRecvError::Lagged(_)) => continue,
+ Err(_) => break,
+ }
+ }
+ if self.is_cancelled(id) {
+ return self.cancel_running(id, &client, &accepted.id, &cfg).await;
+ }
+ if last_poll.elapsed() >= Duration::from_millis(500) {
+ last_poll = Instant::now();
+ match client.job(&accepted.id).await {
+ Ok(bj) => match bj.status {
+ BackendJobStatus::Completed | BackendJobStatus::Failed | BackendJobStatus::Cancelled => break bj,
+ BackendJobStatus::Queued if !detailed => self.update(id, |j| j.view.stage = None),
+ BackendJobStatus::Generating if !detailed => self.update(id, |j| j.view.stage = Some(BackendStage::Generating)),
+ _ => {}
+ },
+ Err(e) => {
+ if self.server.owned_alive() == Some(false) {
+ let tail = self.server.log.tail(30).join("\n");
+ self.server.mark_lost(AppError::new(ErrorCode::ServerCrashed, "The inference server stopped unexpectedly."));
+ self.emit_server();
+ let mut err = translate_generation_failure("server process exited", &tail, (plan.working.width, plan.working.height), None);
+ if err.code == ErrorCode::GenerationFailed {
+ err = AppError::new(ErrorCode::ServerCrashed, "The inference server stopped unexpectedly.")
+ .suggest("It will restart automatically on the next job.")
+ .detail(tail);
+ }
+ return self.maybe_retry_oom(id, err).await;
+ }
+ if e.code == ErrorCode::NotFound {
+ return Err(AppError::new(ErrorCode::GenerationFailed, "The inference server lost track of the job (it may have restarted)."));
+ }
+ }
+ }
+ }
+ tokio::time::sleep(Duration::from_millis(120)).await;
+ };
+
+ match backend_job.status {
+ BackendJobStatus::Completed => {}
+ BackendJobStatus::Cancelled => return Err(AppError::new(ErrorCode::Cancelled, "Cancelled.")),
+ _ => {
+ let msg = backend_job.error.map(|e| format!("{}: {}", e.code, e.message)).unwrap_or_default();
+ let smaller = Size::new(((plan.working.width as f64) * 0.75) as u32 / 32 * 32, ((plan.working.height as f64) * 0.75) as u32 / 32 * 32);
+ let err = translate_generation_failure(&msg, &job_log.join("\n"), (plan.working.width, plan.working.height), Some((smaller.width, smaller.height)));
+ return self.maybe_retry_oom(id, err).await;
+ }
+ }
+ let result = backend_job.result.unwrap_or_default();
+ if result.images.is_empty() {
+ return Err(AppError::new(ErrorCode::GenerationFailed, "The inference server returned no image."));
+ }
+ let post = Arc::new(post);
+ let mut contents = Vec::with_capacity(result.images.len());
+ for im in result.images {
+ let p = post.clone();
+ contents.push(
+ blocking(move || {
+ let raw = imaging::decode_image(&crate::sdcpp::b64_decode(&im.b64_json)?)?.pixels;
+ Ok(pipeline::crop_content(raw, &p))
+ })
+ .await?,
+ );
+ }
+ (contents, Arc::try_unwrap(post).map_err(|_| AppError::internal("post-process still shared"))?)
+ };
+
+ // 6. Enlarge (ESRGAN), post-process and save.
+ let post = Arc::new(post);
+ let duration_start = started;
+ let mask_rec = mask.map(|(_, r)| r);
+ let mut records = Vec::with_capacity(contents.len());
+ for (i, content) in contents.into_iter().enumerate() {
+ let before = Size::new(content.width(), content.height());
+ let (content, enlarged_with) = self.enlarge(id, &client, content, pipeline::enlarge_target(&post), esrgan.as_deref()).await?;
+ self.update(id, |j| {
+ j.view.status = JobStatus::Saving;
+ j.view.stage = None;
+ });
+ let pipeline_rec = PipelineRecord {
+ base: None,
+ refine: None,
+ refine_steps: None,
+ refine_denoise: None,
+ hires_upscaler: None,
+ cache_threshold: plan.cache_threshold,
+ enlarged_from: enlarged_with.is_some().then_some(before),
+ enlarged_with,
+ };
+ let this = self.clone();
+ let mut plan3 = plan.clone();
+ // Notes added while running (fallbacks, retries) belong in the record too.
+ if let Some(j) = self.job(id) {
+ plan3.notes = j.notes;
+ }
+ let (p, req3, inputs3, mask3, icc3, ws) = (post.clone(), request.clone(), inputs_meta.clone(), mask_rec.clone(), icc.clone(), workspace.clone());
+ let rec = blocking(move || {
+ let final_img = pipeline::finish(content, &p)?;
+ let duration_ms = duration_start.elapsed().as_millis() as u64;
+ let pipeline = (pipeline_rec != PipelineRecord::default()).then_some(pipeline_rec);
+ this.save_result(&final_img, &req3, &plan3, seed + i as i64, &inputs3, mask3.as_ref(), icc3.as_deref(), duration_ms, ws.as_deref(), i, pipeline)
+ })
+ .await?;
+ let _ = self.events.send(Event::Gallery { id: rec.id.clone(), change: "added" });
+ records.push(rec);
+ }
+ self.update(id, |j| {
+ j.view.status = JobStatus::Done;
+ j.view.results = records;
+ j.view.finished_at = Some(now_rfc3339());
+ j.view.stage = None;
+ });
+ Ok(())
+ }
+
+ /// Prompt for an upscale request that has none: the source's own prompt for
+ /// text-to-image results, otherwise a neutral description (an edit instruction such
+ /// as "make it darker" would keep pushing the image during the refine).
+ fn upscale_prompt(&self, req: &GenerationRequest, quick: bool) -> String {
+ let source = req.images.first().and_then(|s| s.strip_prefix("gen:")).and_then(|g| self.store.get_generation(g).ok());
+ match source {
+ Some(g) if g.mode == "generate" || (quick && !g.prompt.trim().is_empty()) => g.prompt,
+ _ if quick => "Upscaled image".into(),
+ _ => planner::UPSCALE_PROMPT.into(),
+ }
+ }
+
+ /// Enlarges `content` with ESRGAN when [`pipeline::finish`] would resize it up to
+ /// `target` by more than ~1.1x. Returns the (possibly larger) content and how the
+ /// enlargement is done; ESRGAN failures fall back to Lanczos with a note.
+ async fn enlarge(&self, id: &str, client: &SdcppClient, content: image::RgbaImage, target: Option<Size>, esrgan: Option<&str>) -> AppResult<(image::RgbaImage, Option<String>)> {
+ let Some(target) = target else { return Ok((content, None)) };
+ let size = Size::new(content.width(), content.height());
+ let factor = (target.width as f64 / size.width as f64).max(target.height as f64 / size.height as f64);
+ if factor <= pipeline::ESRGAN_MIN_FACTOR {
+ return Ok((content, None));
+ }
+ let Some(name) = esrgan else { return Ok((content, Some("Lanczos".into()))) };
+ self.update(id, |j| {
+ j.view.status = JobStatus::Running;
+ j.view.stage = Some(BackendStage::Upscaling);
+ j.view.step = None;
+ });
+ let content = Arc::new(content);
+ let r = self.esrgan_enlarge(id, client, content.clone(), target, name).await;
+ let content = Arc::try_unwrap(content).unwrap_or_else(|a| (*a).clone());
+ match r {
+ Ok(Some(img)) => Ok((img, Some(name.to_string()))),
+ Ok(None) => Ok((content, None)),
+ Err(e) if e.code == ErrorCode::Cancelled => Err(e),
+ Err(e) => {
+ tracing::warn!("ESRGAN upscale failed, using Lanczos: {} {:?}", e.message, e.detail);
+ self.update(id, |j| j.view.notes.push(format!("Upscaler model failed ({}); enlarged with Lanczos.", e.message)));
+ Ok((content, Some("Lanczos".into())))
+ }
+ }
+ }
+
+ async fn esrgan_enlarge(&self, id: &str, client: &SdcppClient, content: Arc<image::RgbaImage>, target: Size, upscaler: &str) -> AppResult<Option<image::RgbaImage>> {
+ // Tiles are sized for an x4 model, the common case (an x2 model just gets smaller results).
+ let Some(ep) = pipeline::esrgan_plan(Size::new(content.width(), content.height()), target, 4) else { return Ok(None) };
+ let c = content.clone();
+ let input = Arc::new(blocking(move || Ok(imaging::resize(&c, ep.input.width, ep.input.height))).await?);
+ let mut stitcher = pipeline::Stitcher::new(ep.input);
+ for tile in &ep.tiles {
+ self.check_cancel(id)?;
+ let (inp, t) = (input.clone(), *tile);
+ let png = blocking(move || pipeline::tile_png_b64(&inp, &t)).await?;
+ let resp = client.upscale(&UpscaleRequest { image: png, upscaler: Some(upscaler.to_string()), tile_size: None, output_format: "png".into() }).await?;
+ let up = blocking(move || Ok(imaging::decode_image(&crate::sdcpp::b64_decode(&resp.images[0].b64_json)?)?.pixels)).await?;
+ stitcher.add(tile, &up)?;
+ }
+ Ok(Some(blocking(move || stitcher.finish(&content)).await?))
+ }
+
+ fn apply_progress(&self, id: &str, p: BackendProgress) {
+ self.update(id, |j| {
+ j.view.stage = Some(p.stage);
+ j.view.step = p.step;
+ j.view.image = p.image;
+ j.view.seconds_per_step = p.seconds_per_step;
+ });
+ }
+
+ async fn cancel_running(&self, id: &str, client: &SdcppClient, backend_id: &str, cfg: &AppConfig) -> AppResult<()> {
+ match client.cancel(backend_id).await {
+ Ok(CancelOutcome::Cancelled) | Ok(CancelOutcome::AlreadyFinished) | Ok(CancelOutcome::NotFound) => {}
+ Ok(CancelOutcome::NotInterruptible) | Err(_) => {
+ // This sd-server build cannot interrupt a running job. If we own the
+ // process, restart it to free the GPU now; otherwise the result is discarded.
+ if self.server.status().owned {
+ self.update(id, |j| j.view.notes.push("Stopping the inference server to cancel immediately.".into()));
+ self.server.stop().await;
+ self.emit_server();
+ let this_cfg = cfg.clone();
+ let srv = self.server.clone();
+ let has_more = self.next_queued().is_some();
+ if has_more {
+ tokio::spawn(async move {
+ let _ = srv.ensure_ready(&this_cfg).await;
+ });
+ }
+ } else {
+ self.update(id, |j| j.view.notes.push("The external server will finish this image; the result is discarded.".into()));
+ }
+ }
+ }
+ Err(AppError::new(ErrorCode::Cancelled, "Cancelled."))
+ }
+
+ /// One automatic retry for out-of-memory: enable VAE tiling, then lower resolution.
+ async fn maybe_retry_oom(&self, id: &str, err: AppError) -> AppResult<()> {
+ let can_retry = err.code == ErrorCode::OutOfMemory && !self.jobs.lock().unwrap().get(id).map(|j| j.retried_oom).unwrap_or(true);
+ if !can_retry {
+ return Err(err);
+ }
+ self.update(id, |j| {
+ j.retried_oom = true;
+ let tiled = j.view.plan.as_ref().map(|p| p.vae_tiling).unwrap_or(false);
+ j.request.advanced.vae_tiling = Some(true);
+ if tiled {
+ j.request.resolution = match j.request.resolution {
+ ResolutionMode::K2 | ResolutionMode::Source | ResolutionMode::Custom => ResolutionMode::K15,
+ _ => ResolutionMode::K1,
+ };
+ j.request.width = None;
+ j.request.height = None;
+ j.view.notes.push("Ran out of VRAM; retrying at a lower resolution.".into());
+ } else {
+ j.view.notes.push("Ran out of VRAM; retrying with memory optimization.".into());
+ }
+ j.view.status = JobStatus::Queued;
+ j.view.stage = None;
+ j.view.step = None;
+ });
+ // Re-queue at the front.
+ {
+ let mut order = self.order.lock().unwrap();
+ if let Some(pos) = order.iter().position(|x| x == id) {
+ order.remove(pos);
+ }
+ order.push_front(id.to_string());
+ }
+ self.wake.notify_one();
+ Ok(())
+ }
+
+ #[allow(clippy::too_many_arguments)]
+ fn save_result(
+ &self,
+ img: &image::RgbaImage,
+ req: &GenerationRequest,
+ plan: &Plan,
+ seed: i64,
+ inputs: &[InputRecord],
+ mask: Option<&InputRecord>,
+ icc: Option<&[u8]>,
+ duration_ms: u64,
+ workspace: Option<&Path>,
+ index: usize,
+ pipeline: Option<PipelineRecord>,
+ ) -> AppResult<GenerationRecord> {
+ let cfg = self.config();
+ let id = new_id();
+ let now = chrono::Local::now();
+ let dir = cfg.output_dir.join(now.format("%Y-%m-%d").to_string());
+ std::fs::create_dir_all(&dir).map_err(|e| AppError::io("create the output folder", &dir, e))?;
+ let words: Vec<&str> = req.prompt.split_whitespace().take(6).collect();
+ let stem = format!("{}-{}-{seed}", now.format("%H%M%S"), paths::sanitize_file_stem(&words.join(" ")));
+ // HDR from a HEIC source forces an Ultra HDR JPEG; otherwise the requested format.
+ let (hdr, hdr_note) = hdr_for(img, req, plan, inputs);
+ let format = if hdr.is_some() { OutputFormat::Jpeg } else { plan.output_format };
+ let file = paths::unique_path(dir.join(format!("{stem}.{}", format.ext())), &[]);
+
+ let mode = match plan.mode {
+ ResolvedMode::Generate => "generate",
+ ResolvedMode::Edit => "edit",
+ ResolvedMode::Inpaint => "inpaint",
+ ResolvedMode::Outpaint => "outpaint",
+ ResolvedMode::MultiReference => "multi_reference",
+ ResolvedMode::Upscale => "upscale",
+ };
+ let mut rec = GenerationRecord {
+ id: id.clone(),
+ created_at: now_rfc3339(),
+ mode: mode.into(),
+ prompt: req.prompt.clone(),
+ negative_prompt: plan.negative_prompt.clone(),
+ seed,
+ width: img.width(),
+ height: img.height(),
+ working_width: plan.working.width,
+ working_height: plan.working.height,
+ model: cfg.profile().model_name(),
+ sampler: plan.sampler.clone(),
+ scheduler: plan.scheduler.clone(),
+ steps: plan.steps,
+ cfg: plan.cfg,
+ strength: plan.strength,
+ quality: serde_json::to_value(plan.quality).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or_default(),
+ resolution: serde_json::to_value(plan.resolution).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or_default(),
+ references: inputs
+ .iter()
+ .enumerate()
+ .map(|(i, r)| ReferenceRecord { index: i, input_id: r.id.clone(), original_path: r.original_path.clone(), width: r.width, height: r.height })
+ .collect(),
+ mask_input_id: mask.map(|m| m.id.clone()),
+ outpaint: plan.outpaint.map(|o| o.expansion),
+ file_path: file.to_string_lossy().into_owned(),
+ extra_paths: vec![],
+ favorite: false,
+ parent_id: req.parent_id.clone(),
+ duration_ms,
+ notes: plan.notes.clone(),
+ app_version: APP_VERSION.into(),
+ backend_version: self.backend_version.lock().unwrap().clone(),
+ client: req.client.clone(),
+ request: serde_json::to_value(req).unwrap_or_default(),
+ pipeline,
+ };
+ rec.notes.extend(hdr_note);
+ let bytes = match &hdr {
+ Some(gm) => crate::hdr::encode_ultra_hdr(img, icc, gm, 95).map_err(|e| AppError::new(ErrorCode::Internal, "Failed to encode the HDR JPEG.").detail(e))?,
+ None => encode_output(img, format, &rec, icc)?,
+ };
+ write_atomic(&file, &bytes)?;
+
+ // Optional copy to a caller-chosen path (MCP / API), validated and never overwriting.
+ if let Some(out) = &req.output_path {
+ let mut roots = vec![cfg.output_dir.clone()];
+ if let Some(w) = workspace {
+ roots.push(w.to_path_buf());
+ }
+ let input_paths: Vec<PathBuf> = inputs.iter().filter_map(|r| r.original_path.as_ref().map(PathBuf::from)).collect();
+ let raw = if index == 0 { out.clone() } else { numbered(out, index) };
+ let target = paths::resolve_output_path(&raw, workspace, &roots, &input_paths)?;
+ if let Some(d) = target.parent() {
+ std::fs::create_dir_all(d).map_err(|e| AppError::io("create the output folder", d, e))?;
+ }
+ let ext = target.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
+ let fmt = match ext.as_str() {
+ "jpg" | "jpeg" => OutputFormat::Jpeg,
+ "webp" => OutputFormat::Webp,
+ _ => OutputFormat::Png,
+ };
+ let data = if fmt == format { bytes.clone() } else { encode_output(img, fmt, &rec, icc)? };
+ write_atomic(&target, &data)?;
+ rec.extra_paths.push(target.to_string_lossy().into_owned());
+ }
+ drop(bytes);
+ let thumb = imaging::thumbnail(img, 512);
+ if let Ok(j) = imaging::encode_jpeg(&thumb, 85) {
+ let _ = std::fs::write(self.store.thumb_path(&id), j);
+ }
+ self.store.insert_generation(&rec)?;
+ Ok(rec)
+ }
+}
+
+/// The gain map to attach when the source is an HDR HEIC and the user kept HDR on
+/// (`advanced.hdr`, default on), plus a note saying what happened. Only for results that
+/// keep the source's framing (edit, inpaint, upscale); every failure falls back to SDR.
+fn hdr_for(img: &image::RgbaImage, req: &GenerationRequest, plan: &Plan, inputs: &[InputRecord]) -> (Option<crate::hdr::GainMap>, Option<String>) {
+ let Some(src) = inputs.first().filter(|r| r.format == "heic" && r.hdr) else { return (None, None) };
+ if req.advanced.hdr == Some(false) {
+ return (None, None);
+ }
+ if !matches!(plan.mode, ResolvedMode::Edit | ResolvedMode::Inpaint | ResolvedMode::Upscale) {
+ return (None, Some("HDR not kept: only edits, inpainting and upscales keep the source's framing.".into()));
+ }
+ if !crate::hdr::same_framing((src.width, src.height), img.dimensions()) {
+ return (None, Some("HDR not kept: the result's framing differs from the HEIC source.".into()));
+ }
+ let Some(ffmpeg) = crate::hdr::find_ffmpeg() else {
+ return (None, Some("HDR not kept: ffmpeg was not found on PATH (needed to read the HEIC gain map).".into()));
+ };
+ let attempt = || -> Result<(crate::hdr::GainMap, f32), String> {
+ let path = Path::new(&src.path);
+ let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
+ let info = crate::heif::gain_map(&bytes).ok_or("no ISO 21496-1 gain map")?;
+ let gm = crate::hdr::read_heic_gain_map(&ffmpeg, path, &info)?;
+ let base = imaging::decode_image(&bytes).map_err(|e| e.message)?.pixels;
+ if !crate::hdr::same_framing(base.dimensions(), gm.image.dimensions()) {
+ return Err("gain map and image disagree on orientation".into());
+ }
+ Ok(crate::hdr::adapt_gain_map(&gm, &base, img))
+ };
+ match attempt() {
+ Ok((gm, kept)) => {
+ let note = format!("HDR kept from the HEIC source (Ultra HDR JPEG); the HDR boost was kept on {:.0}% of the image and faded where the edit changed brightness.", kept * 100.0);
+ (Some(gm), Some(note))
+ }
+ Err(e) => {
+ tracing::warn!("HDR gain map failed: {e}");
+ (None, Some(format!("HDR not kept: {e}.")))
+ }
+ }
+}
+
+fn numbered(path: &str, i: usize) -> String {
+ let p = Path::new(path);
+ let stem = p.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "image".into());
+ let ext = p.extension().map(|s| format!(".{}", s.to_string_lossy())).unwrap_or_default();
+ p.with_file_name(format!("{stem}-{}{ext}", i + 1)).to_string_lossy().into_owned()
+}
+
+pub fn encode_output(img: &image::RgbaImage, format: OutputFormat, rec: &GenerationRecord, icc: Option<&[u8]>) -> AppResult<Vec<u8>> {
+ match format {
+ OutputFormat::Png => {
+ let text = rec.png_text();
+ let pairs: Vec<(&str, &str)> = text.iter().map(|(k, v)| (*k, v.as_str())).collect();
+ imaging::encode_png(img, &pairs, icc, false)
+ }
+ OutputFormat::Jpeg => imaging::encode_jpeg(img, 95),
+ OutputFormat::Webp => imaging::encode_webp_lossless(img),
+ }
+}
+
+pub fn write_atomic(path: &Path, bytes: &[u8]) -> AppResult<()> {
+ let tmp = path.with_extension(format!("{}.part", path.extension().map(|e| e.to_string_lossy().into_owned()).unwrap_or_default()));
+ std::fs::write(&tmp, bytes).map_err(|e| AppError::io("write the image", &tmp, e))?;
+ std::fs::rename(&tmp, path).map_err(|e| {
+ let _ = std::fs::remove_file(&tmp);
+ AppError::io("save the image", path, e)
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::config::RefineMode;
+
+ /// End to end on a real iPhone HEIC (QLS_TEST_HEIC, ffmpeg on PATH): import, simulated
+ /// edit (left half 2 stops darker), HDR decision and Ultra HDR file. QLS_TEST_OUT keeps it.
+ #[test]
+ fn heic_edit_keeps_hdr() {
+ let Ok(p) = std::env::var("QLS_TEST_HEIC") else { return };
+ if crate::hdr::find_ffmpeg().is_none() {
+ return;
+ }
+ let dir = tempfile::tempdir().unwrap();
+ let store = crate::store::Store::open(dir.path()).unwrap();
+ let bytes = std::fs::read(&p).unwrap();
+ let input = store.put_input(&bytes, Some("IMG.HEIC"), Some(&p)).unwrap();
+ assert_eq!(input.format, "heic");
+ assert!(input.hdr);
+ assert!(store.input_display_path(&input.id).is_file());
+
+ let mut edited = imaging::decode_image(&bytes).unwrap().pixels;
+ let w = edited.width();
+ for (x, _, px) in edited.enumerate_pixels_mut() {
+ if x < w / 2 {
+ for c in 0..3 {
+ px.0[c] /= 3;
+ }
+ }
+ }
+ let mut req = GenerationRequest { prompt: "darker".into(), images: vec![format!("input:{}", input.id)], preserve_dimensions: true, ..Default::default() };
+ let pi = crate::planner::PlanInputs { image_sizes: vec![Size::new(input.width, input.height)], vram_total_mib: Some(16303), ..Default::default() };
+ let plan = crate::planner::plan(&req, &pi, &crate::config::RecommendedSettings::default()).unwrap();
+ assert_eq!(plan.mode, ResolvedMode::Edit);
+
+ let (gm, note) = hdr_for(&edited, &req, &plan, std::slice::from_ref(&input));
+ let gm = gm.expect("HDR kept");
+ let note = note.unwrap();
+ assert!(note.contains("HDR kept"), "{note}");
+ // Roughly the right half keeps its boost.
+ let share: f64 = note.split("kept on ").nth(1).unwrap().split('%').next().unwrap().parse().unwrap();
+ assert!((35.0..65.0).contains(&share), "{note}");
+ let icc = crate::heif::primary_icc(&bytes);
+ let out = crate::hdr::encode_ultra_hdr(&edited, icc.as_deref(), &gm, 95).unwrap();
+ if let Ok(d) = std::env::var("QLS_TEST_OUT") {
+ std::fs::write(Path::new(&d).join("edit_ultrahdr.jpg"), &out).unwrap();
+ }
+
+ req.advanced.hdr = Some(false);
+ assert!(hdr_for(&edited, &req, &plan, std::slice::from_ref(&input)).0.is_none(), "toggle off");
+ let cropped = image::imageops::crop_imm(&edited, 0, 0, w, w).to_image();
+ let (none, why) = hdr_for(&cropped, &GenerationRequest { advanced: Default::default(), ..req.clone() }, &plan, std::slice::from_ref(&input));
+ assert!(none.is_none() && why.unwrap().contains("framing"));
+ }
+
+ #[test]
+ fn numbered_paths() {
+ assert_eq!(numbered(r"C:\a\hero.png", 1), r"C:\a\hero-2.png");
+ assert_eq!(numbered("x", 2), "x-3");
+ }
+
+ #[tokio::test]
+ async fn submit_validate_and_cancel_queued() {
+ let dir = tempfile::tempdir().unwrap();
+ // SAFETY: test-only env override, single-threaded setup.
+ unsafe { std::env::set_var("QLS_CONFIG_DIR", dir.path().join("cfg")) };
+ let e = Engine::new(AppConfig::default(), dir.path()).unwrap();
+ assert!(e.submit(GenerationRequest { prompt: " ".into(), ..Default::default() }, None).is_err());
+ let j = e.submit(GenerationRequest { prompt: "a fox".into(), seed: Some(-1), ..Default::default() }, None).unwrap();
+ assert_eq!(j.status, JobStatus::Queued);
+ assert_eq!(j.seed, None, "negative seed means random");
+ let j2 = e.submit(GenerationRequest { prompt: "a cat".into(), ..Default::default() }, None).unwrap();
+ assert_eq!(e.job(&j2.id).unwrap().queue_position, 2);
+ let c = e.cancel(&j.id).unwrap();
+ assert_eq!(c.status, JobStatus::Cancelled);
+ assert_eq!(e.job(&j2.id).unwrap().queue_position, 1);
+ assert_eq!(e.next_queued().as_deref(), Some(j2.id.as_str()));
+ assert!(e.cancel("nope").is_err());
+ // Upscales need an image but no prompt; the job gets a readable label.
+ let up = GenerationRequest { mode: Mode::Upscale, ..Default::default() };
+ assert!(e.submit(up.clone(), None).is_err());
+ let j3 = e.submit(GenerationRequest { images: vec!["gen:x".into()], ..up }, None).unwrap();
+ assert_eq!(j3.prompt, "Upscale (Quick)");
+ // Closing the desktop app cancels only its own jobs.
+ let ui = e.submit(GenerationRequest { prompt: "ui job".into(), client: Some("ui".into()), ..Default::default() }, None).unwrap();
+ let mcp = e.submit(GenerationRequest { prompt: "mcp job".into(), client: Some("mcp".into()), ..Default::default() }, None).unwrap();
+ assert_eq!(e.cancel_client_jobs("ui"), 1);
+ assert_eq!(e.job(&ui.id).unwrap().status, JobStatus::Cancelled);
+ assert_eq!(e.job(&mcp.id).unwrap().status, JobStatus::Queued);
+ }
+
+ #[test]
+ fn plan_inputs_follow_config() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut cfg = AppConfig::default();
+ cfg.upscalers_dir = Some(dir.path().to_path_buf());
+ let i = plan_inputs(&cfg, vec![], None, Some(16303));
+ assert_eq!(i.upscaler, None, "no model file -> Lanczos");
+ assert!(i.server_vae_tiling && i.sage_attention);
+ assert_eq!(i.refine, RefineMode::Fast);
+ std::fs::write(dir.path().join("4x-UltraSharp.pth"), b"x").unwrap();
+ cfg.vae_tile_size = 0;
+ cfg.refine_mode = RefineMode::Best;
+ let i = plan_inputs(&cfg, vec![], None, None);
+ assert_eq!(i.upscaler.as_deref(), Some("4x-UltraSharp"));
+ assert!(!i.server_vae_tiling);
+ assert_eq!(i.refine, RefineMode::Best);
+ }
+
+ #[test]
+ fn output_encoding_formats() {
+ let img = image::RgbaImage::from_pixel(8, 8, image::Rgba([1, 2, 3, 255]));
+ let rec: GenerationRecord = serde_json::from_value(serde_json::json!({
+ "id":"x","created_at":"t","mode":"generate","prompt":"p","negative_prompt":"","seed":1,"width":8,"height":8,
+ "working_width":32,"working_height":32,"model":"m","sampler":"euler","scheduler":null,"steps":1,"cfg":6.0,"strength":null,
+ "quality":"fast","resolution":"auto","references":[],"mask_input_id":null,"outpaint":null,"file_path":"f","favorite":false,
+ "parent_id":null,"duration_ms":1,"notes":[],"app_version":"1","backend_version":null,"client":null
+ }))
+ .unwrap();
+ let png = encode_output(&img, OutputFormat::Png, &rec, None).unwrap();
+ assert!(imaging::read_png_text(&png).iter().any(|(k, _)| k == "qls:generation"));
+ let jpg = encode_output(&img, OutputFormat::Jpeg, &rec, None).unwrap();
+ assert_eq!(&jpg[..2], &[0xFF, 0xD8]);
+ let webp = encode_output(&img, OutputFormat::Webp, &rec, None).unwrap();
+ assert_eq!(&webp[..4], b"RIFF");
+ }
+}
diff --git a/crates/qls-core/src/error.rs b/crates/qls-core/src/error.rs
new file mode 100644
index 0000000..24fbf8b
--- /dev/null
+++ b/crates/qls-core/src/error.rs
@@ -0,0 +1,209 @@
+//! Application-level errors: a stable code, a short human message, optional suggestion,
+//! and the raw technical detail (kept for Diagnostics, never shown by default).
+
+use serde::{Deserialize, Serialize};
+use std::fmt;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ErrorCode {
+ OutOfMemory,
+ MissingModel,
+ InvalidConfig,
+ ServerUnavailable,
+ ServerStartFailed,
+ ServerCrashed,
+ MalformedRequest,
+ Unsupported,
+ ImageDecode,
+ Filesystem,
+ InvalidPath,
+ InvalidInput,
+ NotFound,
+ QueueFull,
+ Cancelled,
+ GenerationFailed,
+ Unauthorized,
+ Internal,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct AppError {
+ pub code: ErrorCode,
+ pub message: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub suggestion: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub detail: Option<String>,
+}
+
+impl AppError {
+ pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
+ Self { code, message: message.into(), suggestion: None, detail: None }
+ }
+ pub fn detail(mut self, d: impl Into<String>) -> Self {
+ self.detail = Some(d.into());
+ self
+ }
+ pub fn suggest(mut self, s: impl Into<String>) -> Self {
+ self.suggestion = Some(s.into());
+ self
+ }
+ pub fn invalid(message: impl Into<String>) -> Self {
+ Self::new(ErrorCode::InvalidInput, message)
+ }
+ pub fn internal(e: impl fmt::Display) -> Self {
+ Self::new(ErrorCode::Internal, "Something went wrong inside the app.").detail(e.to_string())
+ }
+ pub fn io(action: &str, path: &std::path::Path, e: std::io::Error) -> Self {
+ let msg = match e.kind() {
+ std::io::ErrorKind::NotFound => format!("File not found: {}", path.display()),
+ std::io::ErrorKind::PermissionDenied => format!("Permission denied: {}", path.display()),
+ _ => format!("Could not {action}: {}", path.display()),
+ };
+ Self::new(ErrorCode::Filesystem, msg).detail(e.to_string())
+ }
+ /// HTTP status used by the stable API.
+ pub fn http_status(&self) -> u16 {
+ match self.code {
+ ErrorCode::InvalidInput | ErrorCode::InvalidPath | ErrorCode::MalformedRequest | ErrorCode::ImageDecode => 400,
+ ErrorCode::Unauthorized => 401,
+ ErrorCode::NotFound => 404,
+ ErrorCode::QueueFull => 429,
+ ErrorCode::Unsupported => 422,
+ ErrorCode::ServerUnavailable | ErrorCode::ServerStartFailed | ErrorCode::ServerCrashed => 503,
+ _ => 500,
+ }
+ }
+}
+
+impl fmt::Display for AppError {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "{}", self.message)?;
+ if let Some(s) = &self.suggestion {
+ write!(f, " {s}")?;
+ }
+ Ok(())
+ }
+}
+
+impl std::error::Error for AppError {}
+
+impl From<std::io::Error> for AppError {
+ fn from(e: std::io::Error) -> Self {
+ AppError::new(ErrorCode::Filesystem, "A file operation failed.").detail(e.to_string())
+ }
+}
+
+pub type AppResult<T> = Result<T, AppError>;
+
+const OOM_PATTERNS: &[&str] = &[
+ "out of memory",
+ "cudamalloc failed",
+ "cuda error: out of memory",
+ "failed to allocate",
+ "ggml_backend_cuda_buffer_type_alloc_buffer",
+ "not enough memory",
+ "cudaerrormemoryallocation",
+ "failed during weight preparation",
+];
+
+pub fn looks_like_oom(text: &str) -> bool {
+ let t = text.to_ascii_lowercase();
+ OOM_PATTERNS.iter().any(|p| t.contains(p))
+}
+
+/// Translates a failed backend job (its error message plus the server log lines written
+/// while it ran) into an application error. `size` is the working resolution and
+/// `smaller` a suggested safer resolution.
+pub fn translate_generation_failure(backend_message: &str, log_tail: &str, size: (u32, u32), smaller: Option<(u32, u32)>) -> AppError {
+ let combined = format!("{backend_message}\n{log_tail}");
+ let lc = combined.to_ascii_lowercase();
+ if looks_like_oom(&combined) {
+ let mut e = AppError::new(ErrorCode::OutOfMemory, format!("Not enough VRAM for {}×{}.", size.0, size.1));
+ e = match smaller {
+ Some((w, h)) => e.suggest(format!("Try {w}×{h}, fewer reference images, or the Fast preset.")),
+ None => e.suggest("Try a smaller resolution or fewer reference images."),
+ };
+ return e.detail(combined);
+ }
+ if lc.contains("requires qwen3-vl vision weights") || lc.contains("llm_vision") {
+ return AppError::new(ErrorCode::InvalidConfig, "Image editing needs the vision projector (mmproj) model.")
+ .suggest("Set the vision projector file in Settings.")
+ .detail(combined);
+ }
+ if lc.contains("multiples of 32") {
+ return AppError::new(ErrorCode::MalformedRequest, "The image size was not compatible with the model.").detail(combined);
+ }
+ if lc.contains("invalid") && lc.contains("request") {
+ return AppError::new(ErrorCode::MalformedRequest, "The inference server rejected the request.").detail(combined);
+ }
+ AppError::new(ErrorCode::GenerationFailed, "Generation failed.").suggest("See Diagnostics for details.").detail(combined)
+}
+
+/// Translates sd-server startup output (process exited before becoming ready).
+pub fn translate_startup_failure(log_tail: &str) -> AppError {
+ let lc = log_tail.to_ascii_lowercase();
+ if lc.contains("failed to open") || lc.contains("no such file") || lc.contains("does not exist") || lc.contains("file not found") {
+ return AppError::new(ErrorCode::MissingModel, "A model file could not be opened.")
+ .suggest("Check the model paths in Settings.")
+ .detail(log_tail.to_string());
+ }
+ if looks_like_oom(log_tail) {
+ return AppError::new(ErrorCode::OutOfMemory, "Not enough VRAM to load the model.")
+ .suggest("Close other GPU applications, or store the text encoder in RAM (Settings).")
+ .detail(log_tail.to_string());
+ }
+ if lc.contains("address already in use") || lc.contains("bind") && lc.contains("fail") {
+ return AppError::new(ErrorCode::ServerStartFailed, "The inference server port is already in use.")
+ .suggest("Choose another port in Settings.")
+ .detail(log_tail.to_string());
+ }
+ if lc.contains("cuda") && (lc.contains("no cuda") || lc.contains("cuda error") || lc.contains("no devices")) {
+ return AppError::new(ErrorCode::ServerStartFailed, "CUDA is not available.")
+ .suggest("Update the NVIDIA driver or select another device in Settings.")
+ .detail(log_tail.to_string());
+ }
+ if lc.contains("unknown argument") || lc.contains("invalid argument") || lc.contains("unknown option") {
+ return AppError::new(ErrorCode::InvalidConfig, "The inference server did not accept its launch options.")
+ .suggest("Your stable-diffusion.cpp build may be older or newer than expected. See Diagnostics.")
+ .detail(log_tail.to_string());
+ }
+ AppError::new(ErrorCode::ServerStartFailed, "The inference server failed to start.")
+ .suggest("See Diagnostics for the server log.")
+ .detail(log_tail.to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn oom_is_translated_with_suggestion() {
+ let e = translate_generation_failure("generate_image returned empty results", "[ERROR] cudaMalloc failed: out of memory", (2048, 2048), Some((1536, 1536)));
+ assert_eq!(e.code, ErrorCode::OutOfMemory);
+ assert_eq!(e.message, "Not enough VRAM for 2048×2048.");
+ assert!(e.suggestion.unwrap().contains("1536×1536"));
+ assert!(e.detail.unwrap().contains("cudaMalloc"));
+ }
+
+ #[test]
+ fn generic_failure() {
+ let e = translate_generation_failure("boom", "", (1024, 1024), None);
+ assert_eq!(e.code, ErrorCode::GenerationFailed);
+ }
+
+ #[test]
+ fn startup_failures() {
+ assert_eq!(translate_startup_failure("failed to open 'x.gguf'").code, ErrorCode::MissingModel);
+ assert_eq!(translate_startup_failure("ggml_backend_cuda_buffer_type_alloc_buffer: allocating").code, ErrorCode::OutOfMemory);
+ assert_eq!(translate_startup_failure("error: unknown argument: --foo").code, ErrorCode::InvalidConfig);
+ assert_eq!(translate_startup_failure("weird").code, ErrorCode::ServerStartFailed);
+ }
+
+ #[test]
+ fn statuses() {
+ assert_eq!(AppError::invalid("x").http_status(), 400);
+ assert_eq!(AppError::new(ErrorCode::NotFound, "x").http_status(), 404);
+ }
+}
diff --git a/crates/qls-core/src/geometry.rs b/crates/qls-core/src/geometry.rs
new file mode 100644
index 0000000..0aeaef0
--- /dev/null
+++ b/crates/qls-core/src/geometry.rs
@@ -0,0 +1,581 @@
+//! Pure dimension math: alignment, aspect ratios, working canvases, outpaint and
+//! inpaint geometry. Nothing here touches pixels, so everything is unit-testable.
+
+use serde::{Deserialize, Serialize};
+
+/// Qwen-Image 2.1 requires every canvas and reference dimension to be a multiple of 32.
+pub const MODEL_ALIGN: u32 = 32;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Size {
+ pub width: u32,
+ pub height: u32,
+}
+
+impl Size {
+ pub const fn new(width: u32, height: u32) -> Self {
+ Self { width, height }
+ }
+ pub fn area(&self) -> u64 {
+ self.width as u64 * self.height as u64
+ }
+ pub fn aspect(&self) -> f64 {
+ self.width as f64 / self.height.max(1) as f64
+ }
+ pub fn is_aligned(&self, align: u32) -> bool {
+ self.width % align == 0 && self.height % align == 0
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+pub struct Rect {
+ pub x: u32,
+ pub y: u32,
+ pub width: u32,
+ pub height: u32,
+}
+
+impl Rect {
+ pub const fn new(x: u32, y: u32, width: u32, height: u32) -> Self {
+ Self { x, y, width, height }
+ }
+ pub fn size(&self) -> Size {
+ Size::new(self.width, self.height)
+ }
+ pub fn right(&self) -> u32 {
+ self.x + self.width
+ }
+ pub fn bottom(&self) -> u32 {
+ self.y + self.height
+ }
+ pub fn area(&self) -> u64 {
+ self.width as u64 * self.height as u64
+ }
+}
+
+pub fn align_up(v: u32, align: u32) -> u32 {
+ v.div_ceil(align) * align
+}
+
+pub fn align_down(v: u32, align: u32) -> u32 {
+ ((v / align) * align).max(align)
+}
+
+/// Nearest multiple of `align`, never below `align`.
+pub fn align_nearest(v: u32, align: u32) -> u32 {
+ let n = ((v as f64) / align as f64).round() as u32;
+ (n * align).max(align)
+}
+
+fn gcd(a: u32, b: u32) -> u32 {
+ if b == 0 { a } else { gcd(b, a % b) }
+}
+
+/// Human-friendly aspect label: exact reduced ratio when small ("16:9"), otherwise the
+/// closest common ratio within 1% ("≈ 4:3"), otherwise a decimal ("1.85:1").
+pub fn aspect_label(size: Size) -> String {
+ if size.width == 0 || size.height == 0 {
+ return "0:0".into();
+ }
+ let g = gcd(size.width, size.height);
+ let (w, h) = (size.width / g, size.height / g);
+ if w <= 32 && h <= 32 {
+ return format!("{w}:{h}");
+ }
+ let a = size.aspect();
+ for (cw, ch) in COMMON_RATIOS {
+ let r = *cw as f64 / *ch as f64;
+ if (a / r - 1.0).abs() < 0.01 {
+ return format!("≈{cw}:{ch}");
+ }
+ }
+ if a >= 1.0 { format!("{:.2}:1", a) } else { format!("1:{:.2}", 1.0 / a) }
+}
+
+const COMMON_RATIOS: &[(u32, u32)] = &[
+ (1, 1), (4, 3), (3, 4), (3, 2), (2, 3), (16, 9), (9, 16), (5, 4), (4, 5), (21, 9), (9, 21), (2, 1), (1, 2),
+];
+
+/// Aligned dimensions closest to `aspect` with area close to `area`, clamped to `max_side`.
+pub fn dims_for_area(aspect: f64, area: f64, align: u32, min_side: u32, max_side: u32) -> Size {
+ let aspect = aspect.clamp(1.0 / 8.0, 8.0);
+ let mut w = (area * aspect).sqrt();
+ let mut h = w / aspect;
+ let max_side_f = max_side as f64;
+ if w > max_side_f {
+ w = max_side_f;
+ h = w / aspect;
+ }
+ if h > max_side_f {
+ h = max_side_f;
+ w = h * aspect;
+ }
+ let w = align_nearest(w.round() as u32, align).clamp(align_up(min_side, align), align_down(max_side, align));
+ let h = align_nearest(h.round() as u32, align).clamp(align_up(min_side, align), align_down(max_side, align));
+ Size::new(w, h)
+}
+
+/// How a source region is mapped onto the model's working canvas.
+///
+/// The source is uniformly scaled (never stretched) to `content`, then placed at
+/// `content_offset` inside the aligned `canvas`. The remaining border (< align on each
+/// axis) is padding that is cropped away after generation.
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
+pub struct WorkingCanvas {
+ pub source: Size,
+ pub content: Size,
+ pub canvas: Size,
+ pub content_offset: (u32, u32),
+ pub scale: f64,
+}
+
+impl WorkingCanvas {
+ pub fn content_rect(&self) -> Rect {
+ Rect::new(self.content_offset.0, self.content_offset.1, self.content.width, self.content.height)
+ }
+ pub fn is_identity(&self) -> bool {
+ self.source == self.canvas && self.content == self.source
+ }
+ pub fn padding(&self) -> (u32, u32) {
+ (self.canvas.width - self.content.width, self.canvas.height - self.content.height)
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
+pub struct CanvasLimits {
+ /// Maximum canvas area in pixels.
+ pub max_area: u64,
+ /// When the source is smaller than this area it is scaled *up* towards it (used for
+ /// inpaint crops, where more pixels on the masked detail improves quality).
+ pub upscale_to_area: Option<u64>,
+ pub max_upscale: f64,
+ pub min_side: u32,
+ pub max_side: u32,
+ pub align: u32,
+}
+
+impl Default for CanvasLimits {
+ fn default() -> Self {
+ Self { max_area: 1024 * 1024, upscale_to_area: None, max_upscale: 1.0, min_side: 256, max_side: 4096, align: MODEL_ALIGN }
+ }
+}
+
+/// Robust working-resolution calculation. Preserves aspect ratio exactly up to integer
+/// rounding of the content size; alignment is achieved with minimal centered padding.
+pub fn plan_working_canvas(source: Size, limits: &CanvasLimits) -> WorkingCanvas {
+ assert!(source.width > 0 && source.height > 0, "empty source");
+ let area = source.area() as f64;
+ let mut scale = 1.0f64;
+ // Sources within 8% of the budget keep their native size: shrinking by a few
+ // percent costs detail and saves almost nothing.
+ if area > limits.max_area as f64 * 1.08 {
+ scale = (limits.max_area as f64 / area).sqrt();
+ } else if let Some(target) = limits.upscale_to_area
+ && area < target as f64
+ {
+ let target = (target.min(limits.max_area)) as f64;
+ scale = (target / area).sqrt().min(limits.max_upscale.max(1.0));
+ }
+ // Fit max_side after alignment padding.
+ let max_content = (limits.max_side - limits.align + 1) as f64;
+ let longest = source.width.max(source.height) as f64;
+ if longest * scale > max_content {
+ scale = max_content / longest;
+ }
+ // Small images: the shortest side must reach min_side once aligned.
+ let shortest = source.width.min(source.height) as f64;
+ if shortest * scale < limits.min_side as f64 && longest * (limits.min_side as f64 / shortest) <= max_content {
+ scale = limits.min_side as f64 / shortest;
+ }
+ let cw = ((source.width as f64 * scale).round() as u32).max(1);
+ let ch = ((source.height as f64 * scale).round() as u32).max(1);
+ let canvas = Size::new(
+ align_up(cw, limits.align).max(align_up(limits.min_side.min(cw), limits.align)),
+ align_up(ch, limits.align).max(align_up(limits.min_side.min(ch), limits.align)),
+ );
+ let offset = ((canvas.width - cw) / 2, (canvas.height - ch) / 2);
+ WorkingCanvas { source, content: Size::new(cw, ch), canvas, content_offset: offset, scale }
+}
+
+/// Scale `src` to fit entirely within `bounds` (letterbox). Returns scaled size and the
+/// centered offset.
+pub fn contain(src: Size, bounds: Size) -> (Size, (u32, u32)) {
+ let s = (bounds.width as f64 / src.width as f64).min(bounds.height as f64 / src.height as f64);
+ let w = ((src.width as f64 * s).round() as u32).clamp(1, bounds.width);
+ let h = ((src.height as f64 * s).round() as u32).clamp(1, bounds.height);
+ (Size::new(w, h), ((bounds.width - w) / 2, (bounds.height - h) / 2))
+}
+
+/// Scale `src` to fully cover `bounds`. Returns the scaled size and the centered crop
+/// rectangle (in scaled coordinates) that equals `bounds`.
+pub fn cover(src: Size, bounds: Size) -> (Size, Rect) {
+ let s = (bounds.width as f64 / src.width as f64).max(bounds.height as f64 / src.height as f64);
+ let w = ((src.width as f64 * s).round() as u32).max(bounds.width);
+ let h = ((src.height as f64 * s).round() as u32).max(bounds.height);
+ (Size::new(w, h), Rect::new((w - bounds.width) / 2, (h - bounds.height) / 2, bounds.width, bounds.height))
+}
+
+// ---------------------------------------------------------------------------------------
+// Outpainting
+// ---------------------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
+pub struct Expansion {
+ pub left: u32,
+ pub right: u32,
+ pub top: u32,
+ pub bottom: u32,
+}
+
+impl Expansion {
+ pub fn is_zero(&self) -> bool {
+ self.left == 0 && self.right == 0 && self.top == 0 && self.bottom == 0
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "lowercase")]
+pub enum ExpansionUnits {
+ #[default]
+ Pixels,
+ Percent,
+}
+
+/// Converts user-facing expansion values to source pixels. Percentages are relative to
+/// the source width (left/right) or height (top/bottom).
+pub fn expansion_to_pixels(source: Size, left: f64, right: f64, top: f64, bottom: f64, units: ExpansionUnits) -> Expansion {
+ let conv = |v: f64, base: u32| -> u32 {
+ let v = if v.is_finite() { v.max(0.0) } else { 0.0 };
+ match units {
+ ExpansionUnits::Pixels => v.round() as u32,
+ ExpansionUnits::Percent => (base as f64 * v / 100.0).round() as u32,
+ }
+ };
+ Expansion {
+ left: conv(left, source.width),
+ right: conv(right, source.width),
+ top: conv(top, source.height),
+ bottom: conv(bottom, source.height),
+ }
+}
+
+/// Expansion needed to reach a target aspect ratio by growing only the short dimension,
+/// split evenly on both sides. Returns zero expansion if already at (or beyond) target.
+pub fn expansion_for_aspect(source: Size, target_aspect: f64) -> Expansion {
+ let a = source.aspect();
+ if (a / target_aspect - 1.0).abs() < 0.005 {
+ return Expansion::default();
+ }
+ if target_aspect > a {
+ let new_w = (source.height as f64 * target_aspect).round() as u32;
+ let extra = new_w.saturating_sub(source.width);
+ Expansion { left: extra / 2, right: extra - extra / 2, top: 0, bottom: 0 }
+ } else {
+ let new_h = (source.width as f64 / target_aspect).round() as u32;
+ let extra = new_h.saturating_sub(source.height);
+ Expansion { left: 0, right: 0, top: extra / 2, bottom: extra - extra / 2 }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
+pub struct OutpaintPlan {
+ pub source: Size,
+ pub expansion: Expansion,
+ /// Final output size at source pixel density.
+ pub final_size: Size,
+ /// Where the original image sits in the final output.
+ pub source_rect_final: Rect,
+ /// Working canvas for the whole final image.
+ pub working: WorkingCanvas,
+ /// Where the (scaled) original sits inside the working canvas.
+ pub source_rect_working: Rect,
+ /// Pixels (working space) on each expanded edge where the original is also regenerated
+ /// so seams blend. Zero on edges that were not expanded.
+ pub overlap_working: Expansion,
+}
+
+pub const MAX_FINAL_SIDE: u32 = 16384;
+
+pub fn plan_outpaint(source: Size, expansion: Expansion, limits: &CanvasLimits, overlap_px: u32) -> Result<OutpaintPlan, String> {
+ if expansion.is_zero() {
+ return Err("Choose at least one side to expand.".into());
+ }
+ let final_size = Size::new(source.width + expansion.left + expansion.right, source.height + expansion.top + expansion.bottom);
+ if final_size.width > MAX_FINAL_SIDE || final_size.height > MAX_FINAL_SIDE {
+ return Err(format!("The expanded image would be {}×{}, larger than the {} px limit.", final_size.width, final_size.height, MAX_FINAL_SIDE));
+ }
+ let working = plan_working_canvas(final_size, limits);
+ let s = working.scale;
+ let ox = working.content_offset.0;
+ let oy = working.content_offset.1;
+ // Map source rect into working space, rounding edges (not sizes) so adjacent regions tile.
+ let x0 = (expansion.left as f64 * s).round() as u32;
+ let y0 = (expansion.top as f64 * s).round() as u32;
+ let x1 = (((expansion.left + source.width) as f64) * s).round() as u32;
+ let y1 = (((expansion.top + source.height) as f64) * s).round() as u32;
+ let x1 = x1.min(working.content.width).max(x0 + 1);
+ let y1 = y1.min(working.content.height).max(y0 + 1);
+ let source_rect_working = Rect::new(ox + x0, oy + y0, x1 - x0, y1 - y0);
+ let ov = |expanded: u32, room: u32| if expanded > 0 { overlap_px.min(room / 4) } else { 0 };
+ let overlap_working = Expansion {
+ left: ov(expansion.left, source_rect_working.width),
+ right: ov(expansion.right, source_rect_working.width),
+ top: ov(expansion.top, source_rect_working.height),
+ bottom: ov(expansion.bottom, source_rect_working.height),
+ };
+ Ok(OutpaintPlan {
+ source,
+ expansion,
+ final_size,
+ source_rect_final: Rect::new(expansion.left, expansion.top, source.width, source.height),
+ working,
+ source_rect_working,
+ overlap_working,
+ })
+}
+
+// ---------------------------------------------------------------------------------------
+// Inpainting
+// ---------------------------------------------------------------------------------------
+
+/// Region of the source to send to the model for an inpaint. Small masks on large images
+/// get a context crop (higher detail, faster); large masks use the whole image.
+pub fn inpaint_region(source: Size, mask_bbox: Rect, min_context: u32, whole_image_threshold: f64) -> Rect {
+ let whole = Rect::new(0, 0, source.width, source.height);
+ if mask_bbox.width == 0 || mask_bbox.height == 0 {
+ return whole;
+ }
+ let pad = (mask_bbox.width.max(mask_bbox.height) as f64 * 0.5).round() as u32;
+ let pad = pad.max(64);
+ let mut x0 = mask_bbox.x.saturating_sub(pad);
+ let mut y0 = mask_bbox.y.saturating_sub(pad);
+ let mut x1 = (mask_bbox.right() + pad).min(source.width);
+ let mut y1 = (mask_bbox.bottom() + pad).min(source.height);
+ // Grow to at least min_context per side (when the image allows), keeping centered.
+ let grow = |a0: &mut u32, a1: &mut u32, limit: u32| {
+ let len = *a1 - *a0;
+ let want = min_context.min(limit);
+ if len < want {
+ let extra = want - len;
+ let before = (extra / 2).min(*a0);
+ *a0 -= before;
+ *a1 = (*a1 + (extra - before)).min(limit);
+ let len = *a1 - *a0;
+ if len < want {
+ *a0 = a0.saturating_sub(want - len);
+ }
+ }
+ };
+ grow(&mut x0, &mut x1, source.width);
+ grow(&mut y0, &mut y1, source.height);
+ let region = Rect::new(x0, y0, x1 - x0, y1 - y0);
+ if region.area() as f64 >= whole.area() as f64 * whole_image_threshold {
+ whole
+ } else {
+ region
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn limits(max_area: u64) -> CanvasLimits {
+ CanvasLimits { max_area, ..Default::default() }
+ }
+
+ #[test]
+ fn alignment_helpers() {
+ assert_eq!(align_up(1080, 32), 1088);
+ assert_eq!(align_up(1024, 32), 1024);
+ assert_eq!(align_up(1, 32), 32);
+ assert_eq!(align_down(1080, 32), 1056);
+ assert_eq!(align_down(10, 32), 32);
+ assert_eq!(align_nearest(1080, 32), 1088);
+ assert_eq!(align_nearest(1071, 32), 1056);
+ assert_eq!(align_nearest(1537, 32), 1536);
+ assert_eq!(align_nearest(3, 32), 32);
+ }
+
+ #[test]
+ fn aspect_labels() {
+ assert_eq!(aspect_label(Size::new(1920, 1080)), "16:9");
+ assert_eq!(aspect_label(Size::new(1080, 1920)), "9:16");
+ assert_eq!(aspect_label(Size::new(1024, 1024)), "1:1");
+ assert_eq!(aspect_label(Size::new(4032, 3024)), "4:3");
+ assert_eq!(aspect_label(Size::new(1537, 1025)), "≈3:2");
+ assert_eq!(aspect_label(Size::new(1850, 1000)), "1.85:1");
+ assert_eq!(aspect_label(Size::new(1000, 1850)), "1:1.85");
+ }
+
+ #[test]
+ fn source_1536x1024_is_identity() {
+ let w = plan_working_canvas(Size::new(1536, 1024), &limits(4_200_000));
+ assert!(w.is_identity());
+ assert_eq!(w.canvas, Size::new(1536, 1024));
+ }
+
+ #[test]
+ fn source_1920x1080_pads_to_1088() {
+ let w = plan_working_canvas(Size::new(1920, 1080), &limits(4_200_000));
+ assert_eq!(w.content, Size::new(1920, 1080));
+ assert_eq!(w.canvas, Size::new(1920, 1088));
+ assert_eq!(w.content_offset, (0, 4));
+ assert_eq!(w.scale, 1.0);
+ }
+
+ #[test]
+ fn portrait_1080x1920() {
+ let w = plan_working_canvas(Size::new(1080, 1920), &limits(4_200_000));
+ assert_eq!(w.canvas, Size::new(1088, 1920));
+ assert_eq!(w.content, Size::new(1080, 1920));
+ }
+
+ #[test]
+ fn square_1024() {
+ let w = plan_working_canvas(Size::new(1024, 1024), &limits(1024 * 1024));
+ assert!(w.is_identity());
+ }
+
+ #[test]
+ fn large_photo_4032x3024_scales_preserving_aspect() {
+ let w = plan_working_canvas(Size::new(4032, 3024), &limits(2_359_296));
+ assert!(w.canvas.area() <= 2_359_296 + 32 * 2000);
+ assert!(w.canvas.is_aligned(32));
+ let src_aspect = 4032.0 / 3024.0;
+ let content_aspect = w.content.width as f64 / w.content.height as f64;
+ assert!((content_aspect / src_aspect - 1.0).abs() < 0.002, "aspect drift {content_aspect}");
+ assert!(w.padding().0 < 32 && w.padding().1 < 32);
+ }
+
+ #[test]
+ fn odd_1537x1025() {
+ let w = plan_working_canvas(Size::new(1537, 1025), &limits(4_200_000));
+ assert_eq!(w.content, Size::new(1537, 1025));
+ assert_eq!(w.canvas, Size::new(1568, 1056));
+ assert_eq!(w.content_offset, (15, 15));
+ }
+
+ #[test]
+ fn aspect_always_preserved_property() {
+ let sizes = [(1920, 1080), (1080, 1920), (1024, 1024), (4032, 3024), (1537, 1025), (333, 777), (6000, 400), (64, 64), (8000, 8000)];
+ for (w, h) in sizes {
+ for area in [1_048_576u64, 2_359_296, 4_194_304] {
+ let p = plan_working_canvas(Size::new(w, h), &limits(area));
+ assert!(p.canvas.is_aligned(32), "{w}x{h}");
+ assert!(p.canvas.width <= 4096 && p.canvas.height <= 4096, "{w}x{h} -> {:?}", p.canvas);
+ assert!(p.content.width <= p.canvas.width && p.content.height <= p.canvas.height);
+ let drift = (p.content.aspect() / Size::new(w, h).aspect() - 1.0).abs();
+ // Rounding a side to an integer can only shift aspect by < 1px.
+ let tol = 1.0 / p.content.width.min(p.content.height) as f64 + 1e-9;
+ assert!(drift <= tol, "{w}x{h} area {area}: drift {drift} > {tol}");
+ }
+ }
+ }
+
+ #[test]
+ fn tiny_image_scaled_up_to_min_side() {
+ let p = plan_working_canvas(Size::new(100, 50), &limits(1_048_576));
+ assert!(p.content.height >= 256);
+ assert_eq!(p.content.width, 512);
+ }
+
+ #[test]
+ fn upscale_for_inpaint_crops() {
+ let l = CanvasLimits { max_area: 2_000_000, upscale_to_area: Some(1_048_576), max_upscale: 4.0, ..Default::default() };
+ let p = plan_working_canvas(Size::new(300, 200), &l);
+ assert!(p.scale > 3.0 && p.scale <= 4.0);
+ let l2 = CanvasLimits { max_upscale: 2.0, ..l };
+ assert_eq!(plan_working_canvas(Size::new(300, 200), &l2).scale, 2.0);
+ }
+
+ #[test]
+ fn dims_for_area_matches_official_buckets_roughly() {
+ let d = dims_for_area(1.0, 1024.0 * 1024.0, 32, 256, 4096);
+ assert_eq!(d, Size::new(1024, 1024));
+ let d = dims_for_area(16.0 / 9.0, 1024.0 * 1024.0, 32, 256, 4096);
+ assert_eq!(d, Size::new(1376, 768));
+ let d = dims_for_area(9.0 / 16.0, 2048.0 * 2048.0, 32, 256, 4096);
+ assert_eq!(d, Size::new(1536, 2720));
+ assert!(d.is_aligned(32));
+ }
+
+ #[test]
+ fn contain_and_cover() {
+ let (s, off) = contain(Size::new(1920, 1080), Size::new(1024, 1024));
+ assert_eq!(s, Size::new(1024, 576));
+ assert_eq!(off, (0, 224));
+ let (s, crop) = cover(Size::new(1920, 1080), Size::new(1024, 1024));
+ assert_eq!(s, Size::new(1820, 1024));
+ assert_eq!(crop, Rect::new(398, 0, 1024, 1024));
+ }
+
+ #[test]
+ fn expansion_units() {
+ let e = expansion_to_pixels(Size::new(1000, 500), 25.0, 0.0, 10.0, 0.0, ExpansionUnits::Percent);
+ assert_eq!(e, Expansion { left: 250, right: 0, top: 50, bottom: 0 });
+ let e = expansion_to_pixels(Size::new(1000, 500), 256.0, 256.0, -5.0, f64::NAN, ExpansionUnits::Pixels);
+ assert_eq!(e, Expansion { left: 256, right: 256, top: 0, bottom: 0 });
+ }
+
+ #[test]
+ fn expansion_targets() {
+ let e = expansion_for_aspect(Size::new(1024, 1024), 16.0 / 9.0);
+ assert_eq!(e.left + e.right + 1024, 1820);
+ assert_eq!((e.top, e.bottom), (0, 0));
+ let e = expansion_for_aspect(Size::new(1920, 1080), 1.0);
+ assert_eq!(e.top + e.bottom + 1080, 1920);
+ let e = expansion_for_aspect(Size::new(1080, 1920), 9.0 / 16.0);
+ assert!(e.is_zero());
+ }
+
+ #[test]
+ fn outpaint_geometry_right_256() {
+ let src = Size::new(1024, 1024);
+ let p = plan_outpaint(src, Expansion { left: 0, right: 256, top: 0, bottom: 0 }, &limits(4_200_000), 32).unwrap();
+ assert_eq!(p.final_size, Size::new(1280, 1024));
+ assert_eq!(p.working.canvas, Size::new(1280, 1024));
+ assert_eq!(p.source_rect_working, Rect::new(0, 0, 1024, 1024));
+ assert_eq!(p.source_rect_final, Rect::new(0, 0, 1024, 1024));
+ assert_eq!(p.overlap_working, Expansion { left: 0, right: 32, top: 0, bottom: 0 });
+ }
+
+ #[test]
+ fn outpaint_geometry_scaled_and_all_sides() {
+ let src = Size::new(1920, 1080);
+ let e = Expansion { left: 256, right: 256, top: 128, bottom: 128 };
+ let p = plan_outpaint(src, e, &limits(1_048_576), 24).unwrap();
+ assert_eq!(p.final_size, Size::new(2432, 1336));
+ assert!(p.working.canvas.is_aligned(32));
+ assert!(p.working.canvas.area() <= 1_048_576 + 32 * 1400);
+ let r = p.source_rect_working;
+ // Source occupies the same fractional position in working space.
+ let fx = (r.x - p.working.content_offset.0) as f64 / p.working.content.width as f64;
+ assert!((fx - 256.0 / 2432.0).abs() < 0.002);
+ let fw = r.width as f64 / p.working.content.width as f64;
+ assert!((fw - 1920.0 / 2432.0).abs() < 0.002);
+ assert!(r.right() <= p.working.canvas.width && r.bottom() <= p.working.canvas.height);
+ }
+
+ #[test]
+ fn outpaint_rejects_zero_and_huge() {
+ assert!(plan_outpaint(Size::new(100, 100), Expansion::default(), &limits(1 << 20), 16).is_err());
+ assert!(plan_outpaint(Size::new(100, 100), Expansion { left: 20000, ..Default::default() }, &limits(1 << 20), 16).is_err());
+ }
+
+ #[test]
+ fn inpaint_region_crop_and_whole() {
+ let src = Size::new(4032, 3024);
+ let r = inpaint_region(src, Rect::new(2000, 1500, 100, 80), 768, 0.6);
+ assert!(r.x <= 2000 && r.y <= 1500 && r.right() >= 2100 && r.bottom() >= 1580);
+ assert!(r.width >= 768 && r.height >= 768);
+ assert!(r.right() <= 4032 && r.bottom() <= 3024);
+ // A large mask uses the whole image.
+ let r = inpaint_region(Size::new(1024, 1024), Rect::new(100, 100, 800, 800), 768, 0.6);
+ assert_eq!(r, Rect::new(0, 0, 1024, 1024));
+ // Near the corner, crop stays inside.
+ let r = inpaint_region(src, Rect::new(0, 0, 50, 50), 768, 0.6);
+ assert_eq!((r.x, r.y), (0, 0));
+ assert!(r.width >= 768);
+ }
+}
diff --git a/crates/qls-core/src/hdr.rs b/crates/qls-core/src/hdr.rs
new file mode 100644
index 0000000..5a8059c
--- /dev/null
+++ b/crates/qls-core/src/hdr.rs
@@ -0,0 +1,359 @@
+//! HDR for HEIC sources: read the source's gain map (via ffmpeg), adapt it to the edited
+//! image and write an Ultra HDR JPEG (SDR JPEG + gain map JPEG, with Google/Adobe `hdrgm` XMP
+//! and ISO 21496-1 metadata, joined by an MPF index).
+//!
+//! The model only sees and produces SDR. The source's gain map says how much brighter each
+//! point of the *original* scene is in HDR; where the edit changed brightness or content
+//! that boost no longer fits, so the gain is faded towards none (plain SDR) there.
+
+use std::path::{Path, PathBuf};
+use std::process::Command;
+
+use image::{DynamicImage, GrayImage, ImageEncoder, Luma, RgbaImage, imageops};
+
+use crate::heif::{GainMapMetadata, HeifGainMap};
+
+/// Brightness change (in stops) below which the source gain is kept as is, and above which
+/// it is dropped entirely; linear in between.
+const KEEP_STOPS: f32 = 0.25;
+const DROP_STOPS: f32 = 1.0;
+
+/// A gain map ready to be attached to an SDR image of the same framing.
+pub struct GainMap {
+ pub image: GrayImage,
+ pub metadata: GainMapMetadata,
+}
+
+/// `ffmpeg.exe` on PATH (winget, scoop, manual installs), if any.
+pub fn find_ffmpeg() -> Option<PathBuf> {
+ let exe = if cfg!(windows) { "ffmpeg.exe" } else { "ffmpeg" };
+ std::env::split_paths(&std::env::var_os("PATH")?).map(|d| d.join(exe)).find(|p| p.is_file())
+}
+
+/// Reads the gain map of a HEIC file. `source` is the file on disk (ffmpeg needs to seek).
+/// The result has the same orientation as the decoded base image (both apply `irot`/`imir`).
+pub fn read_heic_gain_map(ffmpeg: &Path, source: &Path, info: &HeifGainMap) -> Result<GainMap, String> {
+ let map = if info.is_grid {
+ // Grids are stream groups; ffmpeg's filter label takes the group *index*.
+ let ffprobe = ffmpeg.with_file_name(if cfg!(windows) { "ffprobe.exe" } else { "ffprobe" });
+ let out = run(Command::new(&ffprobe).args(["-v", "error", "-show_entries", "stream_group=index,id", "-of", "csv=p=0"]).arg(source))?;
+ let text = String::from_utf8_lossy(&out);
+ let index = text
+ .lines()
+ .filter_map(|l| {
+ // "index,id," (ffprobe adds empty columns for nested sections).
+ let mut f = l.trim().split(',');
+ Some((f.next()?.trim().to_string(), parse_id(f.next()?)?))
+ })
+ .find(|(_, id)| *id == info.item_id)
+ .map(|(i, _)| i)
+ .ok_or_else(|| format!("ffprobe did not list the gain map (item {})", info.item_id))?;
+ format!("[0:g:{index}]")
+ } else {
+ format!("0:#{}", info.item_id)
+ };
+ let png = run(Command::new(ffmpeg)
+ .args(["-v", "error", "-i"])
+ .arg(source)
+ .args(["-map", &map, "-frames:v", "1", "-f", "image2pipe", "-c:v", "png", "-pix_fmt", "gray", "-"]))?;
+ let image = image::load_from_memory(&png).map_err(|e| format!("gain map decode: {e}"))?.into_luma8();
+ Ok(GainMap { image, metadata: info.metadata.clone() })
+}
+
+fn parse_id(s: &str) -> Option<u32> {
+ let s = s.trim();
+ match s.strip_prefix("0x") {
+ Some(h) => u32::from_str_radix(h, 16).ok(),
+ None => s.parse().ok(),
+ }
+}
+
+fn run(cmd: &mut Command) -> Result<Vec<u8>, String> {
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ cmd.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
+ }
+ let out = cmd.output().map_err(|e| format!("could not run ffmpeg: {e}"))?;
+ if !out.status.success() || out.stdout.is_empty() {
+ let err = String::from_utf8_lossy(&out.stderr);
+ return Err(format!("ffmpeg failed: {}", err.lines().last().unwrap_or("no output")));
+ }
+ Ok(out.stdout)
+}
+
+/// True when `out` shows the same framing as `source` (same aspect ratio within 1%), so the
+/// source's gain map can be stretched onto it.
+pub fn same_framing(source: (u32, u32), out: (u32, u32)) -> bool {
+ let a = source.0 as f64 / source.1 as f64;
+ let b = out.0 as f64 / out.1 as f64;
+ (a / b - 1.0).abs() < 0.01
+}
+
+/// Fits the source gain map to the edited image: same relative resolution as in the source,
+/// and the gain faded out where the edit changed brightness (see [`KEEP_STOPS`]).
+/// Returns the adapted map and the share of the image that kept (most of) its HDR boost.
+pub fn adapt_gain_map(gm: &GainMap, source_sdr: &RgbaImage, edited: &RgbaImage) -> (GainMap, f32) {
+ let (ew, eh) = edited.dimensions();
+ let scale = gm.image.width() as f64 / source_sdr.width() as f64;
+ let w = ((ew as f64 * scale).round() as u32).clamp(1, ew);
+ let h = ((eh as f64 * scale).round() as u32).clamp(1, eh);
+ let gain = imageops::resize(&gm.image, w, h, imageops::FilterType::Triangle);
+ let ys = luma_linear(&imageops::resize(source_sdr, w, h, imageops::FilterType::Triangle));
+ let ye = luma_linear(&imageops::resize(edited, w, h, imageops::FilterType::Triangle));
+
+ // Per-pixel keep weight from the brightness change, smoothed so the fade has no edges.
+ let mut keep = GrayImage::new(w, h);
+ for (i, p) in keep.pixels_mut().enumerate() {
+ let stops = ((ye[i] + 1e-3) / (ys[i] + 1e-3)).log2().abs();
+ let k = 1.0 - ((stops - KEEP_STOPS) / (DROP_STOPS - KEEP_STOPS)).clamp(0.0, 1.0);
+ p.0 = [(k * 255.0).round() as u8];
+ }
+ let keep = imageops::blur(&keep, (w.max(h) as f32 / 400.0).max(1.0));
+
+ let m = &gm.metadata;
+ let (lo, hi, gamma) = (m.gain_map_min[0], m.gain_map_max[0], m.gamma[0]);
+ let mut out = GrayImage::new(w, h);
+ let mut kept = 0usize;
+ for (o, (g, k)) in out.pixels_mut().zip(gain.pixels().zip(keep.pixels())) {
+ let k = k.0[0] as f64 / 255.0;
+ if k > 0.5 {
+ kept += 1;
+ }
+ // ISO 21496-1: log2 gain = lerp(min, max, encoded^(1/gamma)); fade it towards 0 (no boost).
+ let e = g.0[0] as f64 / 255.0;
+ let log_gain = lo + (hi - lo) * e.powf(1.0 / gamma);
+ let faded = log_gain * k;
+ let enc = if hi > lo { ((faded - lo) / (hi - lo)).clamp(0.0, 1.0).powf(gamma) } else { 0.0 };
+ *o = Luma([(enc * 255.0).round() as u8]);
+ }
+ let share = kept as f32 / (w * h) as f32;
+ (GainMap { image: out, metadata: m.clone() }, share)
+}
+
+/// Relative linear luminance per pixel (sRGB transfer, Rec.709 weights).
+fn luma_linear(img: &RgbaImage) -> Vec<f32> {
+ let lin: Vec<f32> = (0..256)
+ .map(|v| {
+ let c = v as f32 / 255.0;
+ if c <= 0.04045 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
+ })
+ .collect();
+ img.pixels().map(|p| 0.2126 * lin[p.0[0] as usize] + 0.7152 * lin[p.0[1] as usize] + 0.0722 * lin[p.0[2] as usize]).collect()
+}
+
+const XMP_NS: &[u8] = b"http://ns.adobe.com/xap/1.0/\0";
+const ISO_NS: &[u8] = b"urn:iso:std:iso:ts:21496:-1\0";
+
+/// Encodes an Ultra HDR JPEG: `sdr` as the primary image (with `icc`), `gm` as the gain map.
+pub fn encode_ultra_hdr(sdr: &RgbaImage, icc: Option<&[u8]>, gm: &GainMap, quality: u8) -> Result<Vec<u8>, String> {
+ let primary = jpeg(&DynamicImage::ImageRgba8(sdr.clone()).into_rgb8(), icc, quality)?;
+ let gain = jpeg(&gm.image, None, quality.min(90))?;
+
+ let mut gain_segments = app(1, &[XMP_NS, gain_map_xmp(&gm.metadata).as_bytes()].concat());
+ gain_segments.extend(app(2, &[ISO_NS, &gm.metadata.to_iso()].concat()));
+ let gain_file = insert_after_soi(&gain, &gain_segments);
+
+ // Primary: XMP directory + ISO version marker + MPF index, then the encoder's own segments.
+ let mut head = app(1, &[XMP_NS, primary_xmp(gain_file.len()).as_bytes()].concat());
+ head.extend(app(2, &[ISO_NS, &[0, 0, 0, 0]].concat()));
+ let mpf_at = 2 + head.len() + 4 + 4; // SOI + segments + APP2 marker/length + "MPF\0"
+ let mpf_len = app(2, &mpf(0, 0, 0)).len();
+ let primary_len = primary.len() + head.len() + mpf_len;
+ head.extend(app(2, &mpf(primary_len as u32, gain_file.len() as u32, (primary_len - mpf_at) as u32)));
+ let mut out = insert_after_soi(&primary, &head);
+ debug_assert_eq!(out.len(), primary_len);
+ out.extend_from_slice(&gain_file);
+ Ok(out)
+}
+
+fn jpeg<P: image::PixelWithColorType + image::Pixel<Subpixel = u8>>(img: &image::ImageBuffer<P, Vec<u8>>, icc: Option<&[u8]>, quality: u8) -> Result<Vec<u8>, String> {
+ let mut out = Vec::new();
+ let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality.clamp(1, 100));
+ if let Some(icc) = icc {
+ let _ = enc.set_icc_profile(icc.to_vec());
+ }
+ enc.write_image(img.as_raw(), img.width(), img.height(), P::COLOR_TYPE).map_err(|e| format!("JPEG encode: {e}"))?;
+ Ok(out)
+}
+
+/// One APPn segment (marker, big-endian length including itself, payload).
+fn app(n: u8, payload: &[u8]) -> Vec<u8> {
+ let mut v = vec![0xFF, 0xE0 + n];
+ v.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes());
+ v.extend_from_slice(payload);
+ v
+}
+
+fn insert_after_soi(jpeg: &[u8], segments: &[u8]) -> Vec<u8> {
+ let mut v = Vec::with_capacity(jpeg.len() + segments.len());
+ v.extend_from_slice(&jpeg[..2]);
+ v.extend_from_slice(segments);
+ v.extend_from_slice(&jpeg[2..]);
+ v
+}
+
+/// MPF APP2 payload: two images, offsets relative to the TIFF header right after "MPF\0".
+fn mpf(primary_len: u32, gain_len: u32, gain_offset: u32) -> Vec<u8> {
+ let mut v = b"MPF\0MM\0\x2a\0\0\0\x08".to_vec();
+ v.extend_from_slice(&3u16.to_be_bytes());
+ let entry = |v: &mut Vec<u8>, tag: u16, typ: u16, count: u32, value: [u8; 4]| {
+ v.extend_from_slice(&tag.to_be_bytes());
+ v.extend_from_slice(&typ.to_be_bytes());
+ v.extend_from_slice(&count.to_be_bytes());
+ v.extend_from_slice(&value);
+ };
+ entry(&mut v, 0xB000, 7, 4, *b"0100");
+ entry(&mut v, 0xB001, 4, 1, 2u32.to_be_bytes());
+ entry(&mut v, 0xB002, 7, 32, 50u32.to_be_bytes()); // 8 (header) + 2 + 3*12 + 4
+ v.extend_from_slice(&0u32.to_be_bytes());
+ for (attr, size, off) in [(0x0003_0000u32, primary_len, 0u32), (0, gain_len, gain_offset)] {
+ v.extend_from_slice(&attr.to_be_bytes());
+ v.extend_from_slice(&size.to_be_bytes());
+ v.extend_from_slice(&off.to_be_bytes());
+ v.extend_from_slice(&[0, 0, 0, 0]);
+ }
+ v
+}
+
+fn primary_xmp(gain_len: usize) -> String {
+ format!(
+ r#"<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Qwen Local Studio"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description xmlns:Container="http://ns.google.com/photos/1.0/container/" xmlns:Item="http://ns.google.com/photos/1.0/container/item/" xmlns:hdrgm="http://ns.adobe.com/hdr-gain-map/1.0/" hdrgm:Version="1.0"><Container:Directory><rdf:Seq><rdf:li rdf:parseType="Resource"><Container:Item Item:Semantic="Primary" Item:Mime="image/jpeg"/></rdf:li><rdf:li rdf:parseType="Resource"><Container:Item Item:Semantic="GainMap" Item:Mime="image/jpeg" Item:Length="{gain_len}"/></rdf:li></rdf:Seq></Container:Directory></rdf:Description></rdf:RDF></x:xmpmeta>"#
+ )
+}
+
+fn gain_map_xmp(m: &GainMapMetadata) -> String {
+ let f = |a: &[f64; 3]| {
+ if m.multichannel {
+ format!("<rdf:Seq><rdf:li>{:.6}</rdf:li><rdf:li>{:.6}</rdf:li><rdf:li>{:.6}</rdf:li></rdf:Seq>", a[0], a[1], a[2])
+ } else {
+ format!("{:.6}", a[0])
+ }
+ };
+ let (attrs, elems): (Vec<String>, Vec<String>) = [
+ ("GainMapMin", f(&m.gain_map_min)),
+ ("GainMapMax", f(&m.gain_map_max)),
+ ("Gamma", f(&m.gamma)),
+ ("OffsetSDR", f(&m.base_offset)),
+ ("OffsetHDR", f(&m.alternate_offset)),
+ ]
+ .into_iter()
+ .partition_map_like(m.multichannel);
+ format!(
+ r#"<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Qwen Local Studio"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description xmlns:hdrgm="http://ns.adobe.com/hdr-gain-map/1.0/" hdrgm:Version="1.0" {} hdrgm:HDRCapacityMin="{:.6}" hdrgm:HDRCapacityMax="{:.6}" hdrgm:BaseRenditionIsHDR="False">{}</rdf:Description></rdf:RDF></x:xmpmeta>"#,
+ attrs.join(" "),
+ m.base_hdr_headroom.max(0.0),
+ m.alternate_hdr_headroom,
+ elems.join("")
+ )
+}
+
+/// Single-channel values go in attributes, per-channel sequences in elements.
+trait PartitionLike {
+ fn partition_map_like(self, multichannel: bool) -> (Vec<String>, Vec<String>);
+}
+
+impl<I: Iterator<Item = (&'static str, String)>> PartitionLike for I {
+ fn partition_map_like(self, multichannel: bool) -> (Vec<String>, Vec<String>) {
+ let mut attrs = vec![];
+ let mut elems = vec![];
+ for (k, v) in self {
+ if multichannel {
+ elems.push(format!("<hdrgm:{k}>{v}</hdrgm:{k}>"));
+ } else {
+ attrs.push(format!("hdrgm:{k}=\"{v}\""));
+ }
+ }
+ (attrs, elems)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn meta() -> GainMapMetadata {
+ GainMapMetadata {
+ gain_map_min: [-0.05; 3],
+ gain_map_max: [1.85; 3],
+ gamma: [0.66; 3],
+ base_offset: [1e-5; 3],
+ alternate_offset: [1e-5; 3],
+ base_hdr_headroom: 0.0,
+ alternate_hdr_headroom: 1.85,
+ multichannel: false,
+ use_base_colour_space: true,
+ }
+ }
+
+ fn decode_log_gain(m: &GainMapMetadata, v: u8) -> f64 {
+ let (lo, hi) = (m.gain_map_min[0], m.gain_map_max[0]);
+ lo + (hi - lo) * (v as f64 / 255.0).powf(1.0 / m.gamma[0])
+ }
+
+ #[test]
+ fn unchanged_edit_keeps_the_gain_and_a_changed_one_drops_it() {
+ let src = RgbaImage::from_pixel(64, 48, image::Rgba([120, 110, 100, 255]));
+ let gm = GainMap { image: GrayImage::from_pixel(32, 24, Luma([200])), metadata: meta() };
+ let (same, share) = adapt_gain_map(&gm, &src, &src);
+ assert_eq!(same.image.dimensions(), (32, 24));
+ assert!(share > 0.99);
+ assert!((decode_log_gain(&gm.metadata, same.image.get_pixel(10, 10).0[0]) - decode_log_gain(&gm.metadata, 200)).abs() < 0.02);
+
+ // The edit is 3 stops darker everywhere: no boost left (log gain ~0).
+ let dark = RgbaImage::from_pixel(128, 96, image::Rgba([40, 36, 33, 255]));
+ let (faded, share) = adapt_gain_map(&gm, &src, &dark);
+ assert_eq!(faded.image.dimensions(), (64, 48), "same relative resolution on a 2x larger result");
+ assert!(share < 0.01);
+ assert!(decode_log_gain(&gm.metadata, faded.image.get_pixel(30, 20).0[0]).abs() < 0.02);
+ }
+
+ #[test]
+ fn ultra_hdr_layout() {
+ let sdr = RgbaImage::from_pixel(64, 32, image::Rgba([200, 30, 30, 255]));
+ let gm = GainMap { image: GrayImage::from_pixel(32, 16, Luma([128])), metadata: meta() };
+ let icc = vec![7u8; 600];
+ let out = encode_ultra_hdr(&sdr, Some(&icc), &gm, 90).unwrap();
+
+ // Find the MPF segment and check that its second entry points at a JPEG with gain map XMP.
+ let pos = out.windows(4).position(|w| w == b"MPF\0").unwrap();
+ let tiff = pos + 4;
+ let e2 = tiff + 50 + 16;
+ let size = u32::from_be_bytes(out[e2 + 4..e2 + 8].try_into().unwrap()) as usize;
+ let off = u32::from_be_bytes(out[e2 + 8..e2 + 12].try_into().unwrap()) as usize;
+ let primary_size = u32::from_be_bytes(out[tiff + 50 + 4..tiff + 50 + 8].try_into().unwrap()) as usize;
+ assert_eq!(tiff + off, primary_size, "gain map starts right after the primary image");
+ assert_eq!(primary_size + size, out.len());
+ let gain = &out[tiff + off..];
+ assert_eq!(&gain[..2], &[0xFF, 0xD8]);
+ let g = String::from_utf8_lossy(gain);
+ assert!(g.contains("hdrgm:GainMapMax=\"1.850000\"") && g.contains("urn:iso:std:iso:ts:21496:-1"));
+ let p = String::from_utf8_lossy(&out[..primary_size]);
+ assert!(p.contains(&format!("Item:Length=\"{size}\"")));
+ assert_eq!(&out[primary_size - 2..primary_size], &[0xFF, 0xD9], "primary ends with EOI");
+
+ // Both images decode; the primary keeps its ICC profile.
+ assert_eq!(image::load_from_memory(&out).unwrap().width(), 64);
+ assert_eq!(image::load_from_memory(gain).unwrap().width(), 32);
+ let mut dec = image::codecs::jpeg::JpegDecoder::new(std::io::Cursor::new(&out[..primary_size])).unwrap();
+ use image::ImageDecoder;
+ assert_eq!(dec.icc_profile().unwrap().unwrap(), icc);
+ }
+
+ /// Run with QLS_TEST_HEIC=<iPhone .HEIC with HDR> and ffmpeg on PATH.
+ #[test]
+ fn real_heic_gain_map_matches_base() {
+ let Ok(p) = std::env::var("QLS_TEST_HEIC") else { return };
+ let Some(ff) = find_ffmpeg() else { return };
+ let bytes = std::fs::read(&p).unwrap();
+ let info = crate::heif::gain_map(&bytes).unwrap();
+ let gm = read_heic_gain_map(&ff, Path::new(&p), &info).unwrap();
+ let base = crate::wic::decode(&bytes).unwrap().pixels;
+ println!("base {:?} gain map {:?}", base.dimensions(), gm.image.dimensions());
+ assert!(same_framing(base.dimensions(), gm.image.dimensions()), "gain map oriented like the base");
+ let out = encode_ultra_hdr(&base, crate::heif::primary_icc(&bytes).as_deref(), &adapt_gain_map(&gm, &base, &base).0, 92).unwrap();
+ if let Ok(dir) = std::env::var("QLS_TEST_OUT") {
+ std::fs::write(Path::new(&dir).join("ultrahdr_test.jpg"), &out).unwrap();
+ }
+ }
+}
diff --git a/crates/qls-core/src/heif.rs b/crates/qls-core/src/heif.rs
new file mode 100644
index 0000000..cefc2de
--- /dev/null
+++ b/crates/qls-core/src/heif.rs
@@ -0,0 +1,436 @@
+//! Minimal HEIF (ISO/IEC 23008-12) container reader: just enough to find an HDR gain map.
+//!
+//! Pixels are decoded elsewhere (Windows' HEIF codec for the base image, ffmpeg for the gain
+//! map); this module only reads item metadata: item types, `auxC` types, references and the
+//! ISO 21496-1 `tmap` item that says which item is the gain map and how to apply it.
+
+use std::collections::HashMap;
+
+/// True for HEIF/HEIC/AVIF-family files (`ftyp` with a HEIF brand).
+pub fn is_heif(b: &[u8]) -> bool {
+ if b.len() < 16 || &b[4..8] != b"ftyp" {
+ return false;
+ }
+ let size = (u32::from_be_bytes([b[0], b[1], b[2], b[3]]) as usize).clamp(16, b.len().min(256));
+ let (compatible, _) = b[16..size].as_chunks::<4>();
+ let mut brands = std::iter::once(&b[8..12]).chain(compatible.iter().map(|c| c.as_slice()));
+ brands.any(|br| matches!(br, b"heic" | b"heix" | b"heim" | b"heis" | b"hevc" | b"hevx" | b"mif1" | b"msf1" | b"mif2"))
+}
+
+/// ISO 21496-1 gain map metadata. Values are in log2 space (as stored), single channel
+/// or per RGB channel.
+#[derive(Debug, Clone, PartialEq)]
+pub struct GainMapMetadata {
+ pub gain_map_min: [f64; 3],
+ pub gain_map_max: [f64; 3],
+ pub gamma: [f64; 3],
+ pub base_offset: [f64; 3],
+ pub alternate_offset: [f64; 3],
+ pub base_hdr_headroom: f64,
+ pub alternate_hdr_headroom: f64,
+ pub multichannel: bool,
+ pub use_base_colour_space: bool,
+}
+
+impl GainMapMetadata {
+ /// Parses the payload of a `tmap` item (a version byte, then the ISO 21496-1 structure).
+ pub fn parse_tmap(d: &[u8]) -> Option<Self> {
+ let mut r = Reader { b: d, p: 0 };
+ if r.u8()? != 0 {
+ return None;
+ }
+ Self::parse_iso(&d[1..])
+ }
+
+ /// Parses the bare ISO 21496-1 metadata (as in a JPEG APP2 segment after its URN).
+ pub fn parse_iso(d: &[u8]) -> Option<Self> {
+ let mut r = Reader { b: d, p: 0 };
+ let min_version = r.u16()?;
+ let _writer = r.u16()?;
+ if min_version != 0 {
+ return None;
+ }
+ let flags = r.u8()?;
+ let multichannel = flags & 0x80 != 0;
+ let use_base_colour_space = flags & 0x40 != 0;
+ let ch = if multichannel { 3 } else { 1 };
+ let mut m = Self {
+ gain_map_min: [0.0; 3],
+ gain_map_max: [0.0; 3],
+ gamma: [1.0; 3],
+ base_offset: [0.0; 3],
+ alternate_offset: [0.0; 3],
+ base_hdr_headroom: 0.0,
+ alternate_hdr_headroom: 0.0,
+ multichannel,
+ use_base_colour_space,
+ };
+ let frac = |n: f64, d: u32| if d == 0 { None } else { Some(n / d as f64) };
+ if flags & 0x08 != 0 {
+ let den = r.u32()?;
+ m.base_hdr_headroom = frac(r.u32()? as f64, den)?;
+ m.alternate_hdr_headroom = frac(r.u32()? as f64, den)?;
+ for c in 0..ch {
+ m.gain_map_min[c] = frac(r.i32()? as f64, den)?;
+ m.gain_map_max[c] = frac(r.i32()? as f64, den)?;
+ m.gamma[c] = frac(r.u32()? as f64, den)?;
+ m.base_offset[c] = frac(r.i32()? as f64, den)?;
+ m.alternate_offset[c] = frac(r.i32()? as f64, den)?;
+ }
+ } else {
+ m.base_hdr_headroom = frac(r.u32()? as f64, r.u32()?)?;
+ m.alternate_hdr_headroom = frac(r.u32()? as f64, r.u32()?)?;
+ for c in 0..ch {
+ m.gain_map_min[c] = frac(r.i32()? as f64, r.u32()?)?;
+ m.gain_map_max[c] = frac(r.i32()? as f64, r.u32()?)?;
+ m.gamma[c] = frac(r.u32()? as f64, r.u32()?)?;
+ m.base_offset[c] = frac(r.i32()? as f64, r.u32()?)?;
+ m.alternate_offset[c] = frac(r.i32()? as f64, r.u32()?)?;
+ }
+ }
+ if !multichannel {
+ for a in [&mut m.gain_map_min, &mut m.gain_map_max, &mut m.gamma, &mut m.base_offset, &mut m.alternate_offset] {
+ a[1] = a[0];
+ a[2] = a[0];
+ }
+ }
+ let sane = (0..ch).all(|c| m.gain_map_max[c] >= m.gain_map_min[c] && m.gamma[c] > 0.0)
+ && m.alternate_hdr_headroom.is_finite()
+ && m.alternate_hdr_headroom != m.base_hdr_headroom;
+ sane.then_some(m)
+ }
+
+ /// Serializes as ISO 21496-1 (no leading version byte), fractions over 1,000,000.
+ pub fn to_iso(&self) -> Vec<u8> {
+ const DEN: f64 = 1_000_000.0;
+ let mut o = Vec::with_capacity(64);
+ o.extend_from_slice(&0u16.to_be_bytes()); // minimum_version
+ o.extend_from_slice(&0u16.to_be_bytes()); // writer_version
+ let mut flags = 0x08u8; // common denominator
+ if self.multichannel {
+ flags |= 0x80;
+ }
+ if self.use_base_colour_space {
+ flags |= 0x40;
+ }
+ o.push(flags);
+ let u = |v: f64| ((v * DEN).round().clamp(0.0, u32::MAX as f64) as u32).to_be_bytes();
+ let s = |v: f64| ((v * DEN).round().clamp(i32::MIN as f64, i32::MAX as f64) as i32).to_be_bytes();
+ o.extend_from_slice(&(DEN as u32).to_be_bytes());
+ o.extend_from_slice(&u(self.base_hdr_headroom));
+ o.extend_from_slice(&u(self.alternate_hdr_headroom));
+ for c in 0..if self.multichannel { 3 } else { 1 } {
+ o.extend_from_slice(&s(self.gain_map_min[c]));
+ o.extend_from_slice(&s(self.gain_map_max[c]));
+ o.extend_from_slice(&u(self.gamma[c]));
+ o.extend_from_slice(&s(self.base_offset[c]));
+ o.extend_from_slice(&s(self.alternate_offset[c]));
+ }
+ o
+ }
+}
+
+/// What a HEIF file says about its HDR gain map.
+#[derive(Debug, Clone)]
+pub struct HeifGainMap {
+ /// Item id of the gain map (ffmpeg uses it as the stream / stream-group id).
+ pub item_id: u32,
+ /// True when the gain map is a `grid` of tiles (ffmpeg exposes it as a stream group).
+ pub is_grid: bool,
+ pub metadata: GainMapMetadata,
+}
+
+#[derive(Debug, Default, Clone)]
+struct Item {
+ typ: [u8; 4],
+ aux: Option<String>,
+ icc: Option<(usize, usize)>,
+ refs: Vec<([u8; 4], Vec<u32>)>,
+ /// (construction_method, extents as (offset, length)).
+ loc: Option<(u8, Vec<(u64, u64)>)>,
+}
+
+/// Finds the gain map of a HEIF file through its ISO 21496-1 `tmap` item. Files with only
+/// Apple's older proprietary gain map (no `tmap`) return None: their headroom lives in Apple
+/// maker notes, which we don't interpret.
+pub fn gain_map(b: &[u8]) -> Option<HeifGainMap> {
+ let (items, primary, idat) = parse(b)?;
+ for it in items.values().filter(|i| &i.typ == b"tmap") {
+ let dimg = it.refs.iter().find(|(t, _)| t == b"dimg").map(|(_, to)| to)?;
+ if dimg.len() != 2 || dimg[0] != primary {
+ continue;
+ }
+ let (cm, ext) = it.loc.as_ref()?;
+ let data = read_extents(b, idat, *cm, ext)?;
+ let metadata = GainMapMetadata::parse_tmap(&data)?;
+ let gm = items.get(&dimg[1])?;
+ return Some(HeifGainMap { item_id: dimg[1], is_grid: &gm.typ == b"grid", metadata });
+ }
+ None
+}
+
+/// The ICC profile of the primary image (`colr` box of type `prof`), if any. Windows' HEIF
+/// codec doesn't expose it, and iPhone photos are Display P3.
+pub fn primary_icc(b: &[u8]) -> Option<Vec<u8>> {
+ let (items, primary, _) = parse(b)?;
+ let it = items.get(&primary)?;
+ // A grid usually carries the profile itself; otherwise take its first tile's.
+ let range = it.icc.or_else(|| {
+ let tiles = it.refs.iter().find(|(t, _)| t == b"dimg").map(|(_, to)| to)?;
+ items.get(tiles.first()?)?.icc
+ })?;
+ Some(b[range.0..range.1].to_vec())
+}
+
+/// Item type and `auxC` type of every item, for diagnostics and tests.
+pub fn describe(b: &[u8]) -> Vec<(u32, String, Option<String>)> {
+ let Some((items, _, _)) = parse(b) else { return vec![] };
+ let mut v: Vec<_> = items.into_iter().map(|(id, i)| (id, String::from_utf8_lossy(&i.typ).into_owned(), i.aux)).collect();
+ v.sort_by_key(|x| x.0);
+ v
+}
+
+fn read_extents(b: &[u8], idat: Option<(usize, usize)>, cm: u8, ext: &[(u64, u64)]) -> Option<Vec<u8>> {
+ let base = match cm {
+ 0 => (0usize, b.len()),
+ 1 => idat?,
+ _ => return None,
+ };
+ let mut out = Vec::new();
+ for &(off, len) in ext {
+ let s = base.0.checked_add(off as usize)?;
+ let e = s.checked_add(len as usize)?;
+ if e > base.1 || len > 1 << 20 {
+ return None;
+ }
+ out.extend_from_slice(&b[s..e]);
+ }
+ Some(out)
+}
+
+type Parsed = (HashMap<u32, Item>, u32, Option<(usize, usize)>);
+
+fn parse(b: &[u8]) -> Option<Parsed> {
+ if !is_heif(b) {
+ return None;
+ }
+ let (ms, me) = boxes(b, 0, b.len()).find(|x| &x.0 == b"meta").map(|x| (x.1 + 4, x.2))?;
+ let meta: HashMap<[u8; 4], (usize, usize)> = boxes(b, ms, me).map(|(t, s, e)| (t, (s, e))).collect();
+ let mut items: HashMap<u32, Item> = HashMap::new();
+
+ // iinf: item ids and types (infe version 2/3).
+ let (s, e) = *meta.get(b"iinf")?;
+ let mut r = Reader { b: &b[..e], p: s };
+ let ver = r.u8()?;
+ r.skip(3)?;
+ if ver == 0 { r.u16()? as u32 } else { r.u32()? };
+ for (t, cs, ce) in boxes(b, r.p, e) {
+ if &t != b"infe" {
+ continue;
+ }
+ let mut r = Reader { b: &b[..ce], p: cs };
+ let v = r.u8()?;
+ r.skip(3)?;
+ if v < 2 {
+ continue;
+ }
+ let id = if v == 2 { r.u16()? as u32 } else { r.u32()? };
+ r.skip(2)?;
+ let typ: [u8; 4] = r.take(4)?.try_into().ok()?;
+ items.entry(id).or_default().typ = typ;
+ }
+
+ // iloc: where each item's bytes are.
+ let (s, e) = *meta.get(b"iloc")?;
+ let mut r = Reader { b: &b[..e], p: s };
+ let ver = r.u8()?;
+ r.skip(3)?;
+ let (a, c) = (r.u8()?, r.u8()?);
+ let (osz, lsz, bsz) = (a >> 4, a & 15, c >> 4);
+ let isz = if ver == 1 || ver == 2 { c & 15 } else { 0 };
+ let count = if ver < 2 { r.u16()? as u32 } else { r.u32()? };
+ for _ in 0..count.min(1 << 16) {
+ let id = if ver < 2 { r.u16()? as u32 } else { r.u32()? };
+ let cm = if ver == 1 || ver == 2 { (r.u16()? & 15) as u8 } else { 0 };
+ r.skip(2)?;
+ let base = r.uint(bsz)?;
+ let n = r.u16()?;
+ let mut ext = Vec::with_capacity(n as usize);
+ for _ in 0..n {
+ if isz > 0 {
+ r.uint(isz)?;
+ }
+ let off = r.uint(osz)?;
+ let len = r.uint(lsz)?;
+ ext.push((base + off, len));
+ }
+ items.entry(id).or_default().loc = Some((cm, ext));
+ }
+
+ // iref: dimg / auxl / cdsc ... references.
+ if let Some(&(s, e)) = meta.get(b"iref") {
+ let ver = *b.get(s)?;
+ for (t, cs, ce) in boxes(b, s + 4, e) {
+ let mut r = Reader { b: &b[..ce], p: cs };
+ let from = if ver == 0 { r.u16()? as u32 } else { r.u32()? };
+ let n = r.u16()?;
+ let to = (0..n).map(|_| if ver == 0 { r.u16().map(u32::from) } else { r.u32() }).collect::<Option<Vec<_>>>()?;
+ items.entry(from).or_default().refs.push((t, to));
+ }
+ }
+
+ // iprp/ipco + ipma: the auxC type of each item.
+ if let Some(&(s, e)) = meta.get(b"iprp") {
+ let iprp: HashMap<[u8; 4], (usize, usize)> = boxes(b, s, e).map(|(t, s, e)| (t, (s, e))).collect();
+ if let (Some(&(cs, ce)), Some(&(ms, me))) = (iprp.get(b"ipco"), iprp.get(b"ipma")) {
+ let props: Vec<_> = boxes(b, cs, ce).collect();
+ let mut r = Reader { b: &b[..me], p: ms };
+ let ver = r.u8()?;
+ let flags = (r.u8()? as u32) << 16 | r.u16()? as u32;
+ let n = r.u32()?;
+ for _ in 0..n.min(1 << 16) {
+ let id = if ver < 1 { r.u16()? as u32 } else { r.u32()? };
+ let k = r.u8()?;
+ for _ in 0..k {
+ let idx = if flags & 1 != 0 { (r.u16()? & 0x7fff) as usize } else { (r.u8()? & 0x7f) as usize };
+ if idx == 0 {
+ continue;
+ }
+ if let Some(&(t, ps, pe)) = props.get(idx - 1) {
+ if &t == b"colr" && pe > ps + 132 && &b[ps..ps + 4] == b"prof" {
+ items.entry(id).or_default().icc = Some((ps + 4, pe));
+ }
+ if &t == b"auxC" && pe > ps + 4 {
+ let urn = &b[ps + 4..pe];
+ let urn = urn.split(|&x| x == 0).next().unwrap_or_default();
+ items.entry(id).or_default().aux = Some(String::from_utf8_lossy(urn).into_owned());
+ }
+ }
+ }
+ }
+ }
+ }
+
+ let (ps, _) = *meta.get(b"pitm")?;
+ let mut r = Reader { b, p: ps };
+ let primary = if r.u8()? == 0 {
+ r.skip(3)?;
+ r.u16()? as u32
+ } else {
+ r.skip(3)?;
+ r.u32()?
+ };
+ let idat = meta.get(b"idat").copied();
+ Some((items, primary, idat))
+}
+
+/// Child boxes in `b[start..end]` as (type, body start, box end).
+fn boxes(b: &[u8], start: usize, end: usize) -> impl Iterator<Item = ([u8; 4], usize, usize)> + '_ {
+ let end = end.min(b.len());
+ let mut off = start;
+ std::iter::from_fn(move || {
+ if off + 8 > end {
+ return None;
+ }
+ let size = u32::from_be_bytes(b[off..off + 4].try_into().ok()?) as u64;
+ let typ: [u8; 4] = b[off + 4..off + 8].try_into().ok()?;
+ let (size, hdr) = match size {
+ 0 => ((end - off) as u64, 8),
+ 1 if off + 16 <= end => (u64::from_be_bytes(b[off + 8..off + 16].try_into().ok()?), 16),
+ 1 => return None,
+ s => (s, 8),
+ };
+ if size < hdr as u64 || off as u64 + size > end as u64 {
+ return None;
+ }
+ let item = (typ, off + hdr, off + size as usize);
+ off += size as usize;
+ Some(item)
+ })
+}
+
+struct Reader<'a> {
+ b: &'a [u8],
+ p: usize,
+}
+
+impl Reader<'_> {
+ fn take(&mut self, n: usize) -> Option<&[u8]> {
+ let s = self.b.get(self.p..self.p.checked_add(n)?)?;
+ self.p += n;
+ Some(s)
+ }
+ fn skip(&mut self, n: usize) -> Option<()> {
+ self.take(n).map(|_| ())
+ }
+ fn u8(&mut self) -> Option<u8> {
+ self.take(1).map(|s| s[0])
+ }
+ fn u16(&mut self) -> Option<u16> {
+ self.take(2).map(|s| u16::from_be_bytes([s[0], s[1]]))
+ }
+ fn u32(&mut self) -> Option<u32> {
+ self.take(4).map(|s| u32::from_be_bytes([s[0], s[1], s[2], s[3]]))
+ }
+ fn i32(&mut self) -> Option<i32> {
+ self.u32().map(|v| v as i32)
+ }
+ fn uint(&mut self, size: u8) -> Option<u64> {
+ match size {
+ 0 => Some(0),
+ 4 => self.u32().map(u64::from),
+ 8 => self.take(8).map(|s| u64::from_be_bytes(s.try_into().unwrap())),
+ _ => None,
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ /// The `tmap` payload of an iPhone 15 photo (iOS 18), read with an independent parser.
+ const IPHONE_TMAP: &str = "00000000004000000000000f4240001c5683000f4240ffff23b4000f4240001c5683000f4240000a23e7000f42400000000a000f42400000000a000f4240";
+
+ #[test]
+ fn parses_iphone_tmap() {
+ let m = GainMapMetadata::parse_tmap(&hex::decode(IPHONE_TMAP).unwrap()).unwrap();
+ assert!(!m.multichannel && m.use_base_colour_space);
+ assert_eq!(m.base_hdr_headroom, 0.0);
+ assert!((m.alternate_hdr_headroom - 1.857155).abs() < 1e-6);
+ assert!((m.gain_map_min[0] + 0.056396).abs() < 1e-6 && (m.gain_map_max[2] - 1.857155).abs() < 1e-6);
+ assert!((m.gamma[0] - 0.664551).abs() < 1e-6);
+ }
+
+ #[test]
+ fn iso_round_trip() {
+ let m = GainMapMetadata::parse_tmap(&hex::decode(IPHONE_TMAP).unwrap()).unwrap();
+ let back = GainMapMetadata::parse_iso(&m.to_iso()).unwrap();
+ assert!((back.alternate_hdr_headroom - m.alternate_hdr_headroom).abs() < 1e-6);
+ assert!((back.gain_map_min[0] - m.gain_map_min[0]).abs() < 1e-6 && (back.gamma[1] - m.gamma[1]).abs() < 1e-6);
+ }
+
+ #[test]
+ fn rejects_garbage() {
+ assert!(!is_heif(b"\x89PNG\r\n\x1a\n0000"));
+ assert!(gain_map(b"not a heif file at all").is_none());
+ assert!(GainMapMetadata::parse_tmap(&[0, 0, 0]).is_none());
+ let mut fake = vec![0, 0, 0, 24];
+ fake.extend_from_slice(b"ftypheic\0\0\0\0mif1heic");
+ assert!(is_heif(&fake));
+ assert!(gain_map(&fake).is_none(), "no meta box");
+ }
+
+ /// Run with QLS_TEST_HEIC=<iPhone .HEIC with HDR> to check a real file.
+ #[test]
+ fn real_file_gain_map() {
+ let Ok(p) = std::env::var("QLS_TEST_HEIC") else { return };
+ let b = std::fs::read(p).unwrap();
+ let g = gain_map(&b).expect("gain map");
+ assert!(g.metadata.alternate_hdr_headroom > 0.5);
+ let icc = primary_icc(&b).expect("iPhone photos carry an ICC profile");
+ assert_eq!(&icc[36..40], b"acsp", "valid ICC header");
+ let d = describe(&b);
+ assert!(d.iter().any(|(id, _, aux)| *id == g.item_id && aux.as_deref().is_some_and(|a| a.contains("hdrgainmap"))), "{d:?}");
+ }
+}
diff --git a/crates/qls-core/src/imaging.rs b/crates/qls-core/src/imaging.rs
new file mode 100644
index 0000000..44938ab
--- /dev/null
+++ b/crates/qls-core/src/imaging.rs
@@ -0,0 +1,646 @@
+//! Pixel-level preprocessing. All functions are pure (input buffers in, new buffers out)
+//! and independently testable. Images are handled as 8-bit RGBA so alpha is never lost;
+//! colors are never converted (ICC profiles are carried through untouched).
+
+use std::io::Cursor;
+
+use image::{
+ DynamicImage, GrayImage, ImageDecoder, ImageFormat, ImageReader, Luma, Rgba, RgbaImage,
+ imageops::{self, FilterType},
+ metadata::Orientation,
+};
+
+use crate::error::{AppError, ErrorCode};
+use crate::geometry::{Rect, Size};
+
+/// Upper bound on decoded input size, to fail fast on decompression bombs.
+pub const MAX_INPUT_PIXELS: u64 = 64_000_000;
+
+#[derive(Debug, Clone)]
+pub struct LoadedImage {
+ /// Pixels with EXIF orientation already applied (i.e. as a viewer displays them).
+ pub pixels: RgbaImage,
+ pub format: &'static str,
+ /// EXIF orientation value that was applied (1 = none).
+ pub exif_orientation: u8,
+ pub icc_profile: Option<Vec<u8>>,
+ /// True when at least one pixel is not fully opaque.
+ pub has_transparency: bool,
+ /// PNG text chunks (keyword, text), if any.
+ pub text: Vec<(String, String)>,
+}
+
+impl LoadedImage {
+ pub fn size(&self) -> Size {
+ Size::new(self.pixels.width(), self.pixels.height())
+ }
+}
+
+fn format_name(f: ImageFormat) -> &'static str {
+ match f {
+ ImageFormat::Png => "png",
+ ImageFormat::Jpeg => "jpeg",
+ ImageFormat::WebP => "webp",
+ ImageFormat::Bmp => "bmp",
+ ImageFormat::Gif => "gif",
+ ImageFormat::Tiff => "tiff",
+ _ => "other",
+ }
+}
+
+fn orientation_code(o: Orientation) -> u8 {
+ match o {
+ Orientation::NoTransforms => 1,
+ Orientation::FlipHorizontal => 2,
+ Orientation::Rotate180 => 3,
+ Orientation::FlipVertical => 4,
+ Orientation::Rotate90FlipH => 5,
+ Orientation::Rotate90 => 6,
+ Orientation::Rotate270FlipH => 7,
+ Orientation::Rotate270 => 8,
+ }
+}
+
+pub fn decode_image(bytes: &[u8]) -> Result<LoadedImage, AppError> {
+ if crate::heif::is_heif(bytes) {
+ return decode_heic(bytes);
+ }
+ let reader = ImageReader::new(Cursor::new(bytes))
+ .with_guessed_format()
+ .map_err(|e| AppError::new(ErrorCode::ImageDecode, "This file could not be read as an image.").detail(e.to_string()))?;
+ let format = reader.format().ok_or_else(|| {
+ AppError::new(ErrorCode::ImageDecode, "Unsupported image format. Use PNG, JPEG, WebP, BMP, GIF, TIFF or HEIC.")
+ })?;
+ let mut decoder = reader
+ .into_decoder()
+ .map_err(|e| AppError::new(ErrorCode::ImageDecode, "This image could not be decoded.").detail(e.to_string()))?;
+ let (w, h) = decoder.dimensions();
+ if w == 0 || h == 0 || (w as u64 * h as u64) > MAX_INPUT_PIXELS {
+ return Err(AppError::new(ErrorCode::ImageDecode, format!("Image is too large ({w}×{h}). The limit is 64 megapixels.")));
+ }
+ let orientation = decoder.orientation().unwrap_or(Orientation::NoTransforms);
+ let icc_profile = decoder.icc_profile().ok().flatten();
+ let mut dynimg = DynamicImage::from_decoder(decoder)
+ .map_err(|e| AppError::new(ErrorCode::ImageDecode, "This image could not be decoded.").detail(e.to_string()))?;
+ dynimg.apply_orientation(orientation);
+ let text = if format == ImageFormat::Png { read_png_text(bytes) } else { Vec::new() };
+ let pixels = dynimg.into_rgba8();
+ let has_transparency = pixels.pixels().any(|p| p[3] != 255);
+ Ok(LoadedImage {
+ pixels,
+ format: format_name(format),
+ exif_orientation: orientation_code(orientation),
+ icc_profile,
+ has_transparency,
+ text,
+ })
+}
+
+/// HEIC/HEIF through Windows' HEIF codec, which already applies the file's rotation/mirror.
+/// The SDR base image only; an HDR gain map is read separately (see `crate::hdr`).
+fn decode_heic(bytes: &[u8]) -> Result<LoadedImage, AppError> {
+ let img = crate::wic::decode(bytes).map_err(|e| AppError::new(ErrorCode::ImageDecode, "This HEIC image could not be decoded.").detail(e))?;
+ let pixels = img.pixels;
+ let has_transparency = pixels.pixels().any(|p| p[3] != 255);
+ Ok(LoadedImage {
+ pixels,
+ format: "heic",
+ exif_orientation: 1,
+ icc_profile: crate::heif::primary_icc(bytes).or(img.icc_profile),
+ has_transparency,
+ text: Vec::new(),
+ })
+}
+
+pub fn load_image(path: &std::path::Path) -> Result<LoadedImage, AppError> {
+ let bytes = std::fs::read(path).map_err(|e| AppError::io("read the image", path, e))?;
+ decode_image(&bytes)
+}
+
+/// Reads tEXt / zTXt / iTXt chunks from PNG bytes. Never fails; returns what it can.
+pub fn read_png_text(bytes: &[u8]) -> Vec<(String, String)> {
+ let decoder = png::Decoder::new(Cursor::new(bytes));
+ let Ok(reader) = decoder.read_info() else { return Vec::new() };
+ let info = reader.info();
+ let mut out: Vec<(String, String)> =
+ info.uncompressed_latin1_text.iter().map(|c| (c.keyword.clone(), c.text.clone())).collect();
+ for c in &info.compressed_latin1_text {
+ if let Ok(t) = c.get_text() {
+ out.push((c.keyword.clone(), t));
+ }
+ }
+ for c in &info.utf8_text {
+ if let Ok(t) = c.get_text() {
+ out.push((c.keyword.clone(), t));
+ }
+ }
+ out
+}
+
+/// Encodes PNG with optional UTF-8 text chunks and ICC profile. Writes RGB when the image
+/// is fully opaque (smaller files), RGBA otherwise.
+pub fn encode_png(img: &RgbaImage, text: &[(&str, &str)], icc: Option<&[u8]>, fast: bool) -> Result<Vec<u8>, AppError> {
+ let opaque = img.pixels().all(|p| p[3] == 255);
+ let mut info = png::Info::with_size(img.width(), img.height());
+ info.color_type = if opaque { png::ColorType::Rgb } else { png::ColorType::Rgba };
+ info.bit_depth = png::BitDepth::Eight;
+ if let Some(icc) = icc {
+ info.icc_profile = Some(std::borrow::Cow::Owned(icc.to_vec()));
+ }
+ let mut out = Vec::with_capacity(img.as_raw().len() / 2);
+ {
+ let mut enc = png::Encoder::with_info(&mut out, info).map_err(png_err)?;
+ enc.set_compression(if fast { png::Compression::Fastest } else { png::Compression::Balanced });
+ for (k, v) in text {
+ enc.add_itxt_chunk((*k).to_string(), (*v).to_string()).map_err(png_err)?;
+ }
+ let mut writer = enc.write_header().map_err(png_err)?;
+ if opaque {
+ let rgb: Vec<u8> = img.as_raw().chunks_exact(4).flat_map(|p| [p[0], p[1], p[2]]).collect();
+ writer.write_image_data(&rgb).map_err(png_err)?;
+ } else {
+ writer.write_image_data(img.as_raw()).map_err(png_err)?;
+ }
+ writer.finish().map_err(png_err)?;
+ }
+ Ok(out)
+}
+
+fn png_err(e: png::EncodingError) -> AppError {
+ AppError::new(ErrorCode::Internal, "Failed to encode PNG.").detail(e.to_string())
+}
+
+pub fn encode_jpeg(img: &RgbaImage, quality: u8) -> Result<Vec<u8>, AppError> {
+ let rgb = DynamicImage::ImageRgba8(img.clone()).into_rgb8();
+ let mut out = Vec::new();
+ let enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, quality.clamp(1, 100));
+ rgb.write_with_encoder(enc).map_err(|e| AppError::new(ErrorCode::Internal, "Failed to encode JPEG.").detail(e.to_string()))?;
+ Ok(out)
+}
+
+pub fn encode_webp_lossless(img: &RgbaImage) -> Result<Vec<u8>, AppError> {
+ let mut out = Vec::new();
+ let enc = image::codecs::webp::WebPEncoder::new_lossless(&mut out);
+ img.write_with_encoder(enc).map_err(|e| AppError::new(ErrorCode::Internal, "Failed to encode WebP.").detail(e.to_string()))?;
+ Ok(out)
+}
+
+// ---------------------------------------------------------------------------------------
+// Geometry operations
+// ---------------------------------------------------------------------------------------
+
+/// High-quality resize (Lanczos3). Transparent images are resized in premultiplied
+/// alpha so fully transparent pixels do not bleed color into edges.
+pub fn resize(img: &RgbaImage, width: u32, height: u32) -> RgbaImage {
+ if img.width() == width && img.height() == height {
+ return img.clone();
+ }
+ let transparent = img.pixels().any(|p| p[3] != 255);
+ if !transparent {
+ return imageops::resize(img, width, height, FilterType::Lanczos3);
+ }
+ let mut pre = img.clone();
+ for p in pre.pixels_mut() {
+ let a = p[3] as u32;
+ for c in 0..3 {
+ p[c] = ((p[c] as u32 * a + 127) / 255) as u8;
+ }
+ }
+ let mut out = imageops::resize(&pre, width, height, FilterType::Lanczos3);
+ for p in out.pixels_mut() {
+ let a = p[3] as u32;
+ if a == 0 {
+ p[0] = 0;
+ p[1] = 0;
+ p[2] = 0;
+ } else if a < 255 {
+ for c in 0..3 {
+ p[c] = ((p[c] as u32 * 255 + a / 2) / a).min(255) as u8;
+ }
+ }
+ }
+ out
+}
+
+pub fn resize_mask(mask: &GrayImage, width: u32, height: u32) -> GrayImage {
+ if mask.width() == width && mask.height() == height {
+ return mask.clone();
+ }
+ imageops::resize(mask, width, height, FilterType::Triangle)
+}
+
+pub fn crop(img: &RgbaImage, r: Rect) -> RgbaImage {
+ imageops::crop_imm(img, r.x, r.y, r.width, r.height).to_image()
+}
+
+pub fn crop_mask(mask: &GrayImage, r: Rect) -> GrayImage {
+ imageops::crop_imm(mask, r.x, r.y, r.width, r.height).to_image()
+}
+
+/// Places `img` at `offset` on a `canvas`-sized image and fills everything outside it by
+/// replicating the nearest edge pixel. Used for 32-alignment padding and as the neutral
+/// fill for outpaint regions (which are fully regenerated anyway).
+pub fn pad_edge(img: &RgbaImage, canvas: Size, offset: (u32, u32)) -> RgbaImage {
+ assert!(offset.0 + img.width() <= canvas.width && offset.1 + img.height() <= canvas.height);
+ if canvas.width == img.width() && canvas.height == img.height() {
+ return img.clone();
+ }
+ let (ox, oy) = (offset.0 as i64, offset.1 as i64);
+ let (iw, ih) = (img.width() as i64, img.height() as i64);
+ RgbaImage::from_fn(canvas.width, canvas.height, |x, y| {
+ let sx = (x as i64 - ox).clamp(0, iw - 1) as u32;
+ let sy = (y as i64 - oy).clamp(0, ih - 1) as u32;
+ *img.get_pixel(sx, sy)
+ })
+}
+
+/// Places `img` at `offset` on a canvas filled with `fill`.
+pub fn pad_solid(img: &RgbaImage, canvas: Size, offset: (u32, u32), fill: Rgba<u8>) -> RgbaImage {
+ let mut out = RgbaImage::from_pixel(canvas.width, canvas.height, fill);
+ imageops::replace(&mut out, img, offset.0 as i64, offset.1 as i64);
+ out
+}
+
+// ---------------------------------------------------------------------------------------
+// Masks — convention: 255 = regenerate, 0 = keep.
+// ---------------------------------------------------------------------------------------
+
+/// Converts a user-supplied mask image to a single-channel mask. Masks painted on a
+/// transparent layer use alpha; opaque masks use luminance (white = edit).
+pub fn mask_from_image(img: &LoadedImage) -> GrayImage {
+ let p = &img.pixels;
+ if img.has_transparency {
+ GrayImage::from_fn(p.width(), p.height(), |x, y| Luma([p.get_pixel(x, y)[3]]))
+ } else {
+ GrayImage::from_fn(p.width(), p.height(), |x, y| {
+ let q = p.get_pixel(x, y);
+ Luma([((q[0] as u32 * 299 + q[1] as u32 * 587 + q[2] as u32 * 114) / 1000) as u8])
+ })
+ }
+}
+
+pub fn mask_rect(size: Size, inside: Rect, inside_value: u8, outside_value: u8) -> GrayImage {
+ GrayImage::from_fn(size.width, size.height, |x, y| {
+ if x >= inside.x && x < inside.right() && y >= inside.y && y < inside.bottom() {
+ Luma([inside_value])
+ } else {
+ Luma([outside_value])
+ }
+ })
+}
+
+pub fn invert_mask(mask: &GrayImage) -> GrayImage {
+ GrayImage::from_fn(mask.width(), mask.height(), |x, y| Luma([255 - mask.get_pixel(x, y)[0]]))
+}
+
+pub fn binarize(mask: &GrayImage, threshold: u8) -> GrayImage {
+ GrayImage::from_fn(mask.width(), mask.height(), |x, y| Luma([if mask.get_pixel(x, y)[0] > threshold { 255 } else { 0 }]))
+}
+
+/// Bounding box of pixels above `threshold`, or None for an empty mask.
+pub fn mask_bbox(mask: &GrayImage, threshold: u8) -> Option<Rect> {
+ let (mut x0, mut y0, mut x1, mut y1) = (u32::MAX, u32::MAX, 0u32, 0u32);
+ for (x, y, p) in mask.enumerate_pixels() {
+ if p[0] > threshold {
+ x0 = x0.min(x);
+ y0 = y0.min(y);
+ x1 = x1.max(x);
+ y1 = y1.max(y);
+ }
+ }
+ (x0 != u32::MAX).then(|| Rect::new(x0, y0, x1 - x0 + 1, y1 - y0 + 1))
+}
+
+pub fn mask_coverage(mask: &GrayImage, threshold: u8) -> f64 {
+ let n = mask.pixels().filter(|p| p[0] > threshold).count();
+ n as f64 / (mask.width() as f64 * mask.height() as f64).max(1.0)
+}
+
+/// Separable sliding-window max/min/mean over rows then columns.
+fn separable(mask: &GrayImage, radius: u32, op: fn(&[u8]) -> u8) -> GrayImage {
+ if radius == 0 {
+ return mask.clone();
+ }
+ let (w, h) = (mask.width() as usize, mask.height() as usize);
+ let r = radius as usize;
+ let src = mask.as_raw();
+ let mut tmp = vec![0u8; w * h];
+ let mut buf = Vec::with_capacity(2 * r + 1);
+ for y in 0..h {
+ let row = &src[y * w..(y + 1) * w];
+ for x in 0..w {
+ buf.clear();
+ buf.extend_from_slice(&row[x.saturating_sub(r)..(x + r + 1).min(w)]);
+ tmp[y * w + x] = op(&buf);
+ }
+ }
+ let mut out = vec![0u8; w * h];
+ for x in 0..w {
+ for y in 0..h {
+ buf.clear();
+ for yy in y.saturating_sub(r)..(y + r + 1).min(h) {
+ buf.push(tmp[yy * w + x]);
+ }
+ out[y * w + x] = op(&buf);
+ }
+ }
+ GrayImage::from_raw(w as u32, h as u32, out).expect("size")
+}
+
+pub fn dilate(mask: &GrayImage, radius: u32) -> GrayImage {
+ separable(mask, radius, |s| *s.iter().max().unwrap())
+}
+
+pub fn erode(mask: &GrayImage, radius: u32) -> GrayImage {
+ separable(mask, radius, |s| *s.iter().min().unwrap())
+}
+
+/// Soft edge: three box-blur passes approximate a Gaussian with sigma ≈ radius/√3·√3.
+pub fn feather(mask: &GrayImage, radius: u32) -> GrayImage {
+ if radius == 0 {
+ return mask.clone();
+ }
+ let r = (radius / 3).max(1);
+ let mean = |s: &[u8]| -> u8 { (s.iter().map(|&v| v as u32).sum::<u32>() as f32 / s.len() as f32).round() as u8 };
+ let mut m = separable(mask, r, mean);
+ m = separable(&m, r, mean);
+ separable(&m, r, mean)
+}
+
+/// The mask sent to the backend must be binary and must fully cover the feathered
+/// region, so the soft blend in [`composite`] never reveals unedited pixels.
+pub fn backend_mask(user_mask: &GrayImage, grow: u32) -> GrayImage {
+ binarize(&dilate(user_mask, grow), 8)
+}
+
+/// Blends `top` over `base` at `at` using `mask` (same size as `top`): out = base·(1−m) + top·m.
+/// Alpha is blended the same way, so transparency of untouched regions is preserved exactly.
+pub fn composite(base: &mut RgbaImage, top: &RgbaImage, mask: &GrayImage, at: (u32, u32)) {
+ assert_eq!((top.width(), top.height()), (mask.width(), mask.height()));
+ for (x, y, tp) in top.enumerate_pixels() {
+ let bx = at.0 + x;
+ let by = at.1 + y;
+ if bx >= base.width() || by >= base.height() {
+ continue;
+ }
+ let m = mask.get_pixel(x, y)[0] as u32;
+ if m == 0 {
+ continue;
+ }
+ let bp = base.get_pixel_mut(bx, by);
+ if m == 255 {
+ *bp = *tp;
+ continue;
+ }
+ for c in 0..4 {
+ bp[c] = ((bp[c] as u32 * (255 - m) + tp[c] as u32 * m + 127) / 255) as u8;
+ }
+ }
+}
+
+/// Mask (in `size`) that is 255 everywhere except `keep`, which is 0, with the keep
+/// area shrunk by `overlap` on selected sides so seams are regenerated.
+pub fn outpaint_mask(size: Size, keep: Rect, overlap: crate::geometry::Expansion) -> GrayImage {
+ let inner = Rect::new(
+ keep.x + overlap.left,
+ keep.y + overlap.top,
+ keep.width.saturating_sub(overlap.left + overlap.right).max(1),
+ keep.height.saturating_sub(overlap.top + overlap.bottom).max(1),
+ );
+ mask_rect(size, inner, 0, 255)
+}
+
+/// Mask used to paste the original back into an outpainted result: 255 inside the
+/// original, ramping to 0 across `feather_px` on edges that were expanded.
+pub fn paste_back_mask(size: Size, expanded: crate::geometry::Expansion, feather_px: u32) -> GrayImage {
+ let f = feather_px.max(1) as f32;
+ GrayImage::from_fn(size.width, size.height, |x, y| {
+ let mut v = 1.0f32;
+ let ramp = |d: u32| ((d as f32 + 0.5) / f).min(1.0);
+ if expanded.left > 0 {
+ v = v.min(ramp(x));
+ }
+ if expanded.right > 0 {
+ v = v.min(ramp(size.width - 1 - x));
+ }
+ if expanded.top > 0 {
+ v = v.min(ramp(y));
+ }
+ if expanded.bottom > 0 {
+ v = v.min(ramp(size.height - 1 - y));
+ }
+ Luma([(v * 255.0).round() as u8])
+ })
+}
+
+pub fn thumbnail(img: &RgbaImage, max_side: u32) -> RgbaImage {
+ let (w, h) = (img.width(), img.height());
+ if w.max(h) <= max_side {
+ return img.clone();
+ }
+ let s = max_side as f64 / w.max(h) as f64;
+ let (tw, th) = (((w as f64 * s).round() as u32).max(1), ((h as f64 * s).round() as u32).max(1));
+ imageops::thumbnail(img, tw, th)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::geometry::Expansion;
+
+ fn gradient(w: u32, h: u32) -> RgbaImage {
+ RgbaImage::from_fn(w, h, |x, y| Rgba([(x * 255 / w.max(1)) as u8, (y * 255 / h.max(1)) as u8, 77, 255]))
+ }
+
+ /// Builds a JPEG with an EXIF APP1 segment carrying the given orientation.
+ fn jpeg_with_orientation(img: &RgbaImage, orientation: u16) -> Vec<u8> {
+ let jpeg = encode_jpeg(img, 95).unwrap();
+ // Minimal little-endian TIFF with a single IFD0 entry: Orientation (0x0112), SHORT.
+ let mut tiff = vec![b'I', b'I', 0x2A, 0x00, 0x08, 0x00, 0x00, 0x00, 0x01, 0x00];
+ tiff.extend_from_slice(&0x0112u16.to_le_bytes());
+ tiff.extend_from_slice(&3u16.to_le_bytes());
+ tiff.extend_from_slice(&1u32.to_le_bytes());
+ tiff.extend_from_slice(&orientation.to_le_bytes());
+ tiff.extend_from_slice(&[0, 0, 0, 0, 0, 0]);
+ let mut payload = b"Exif\0\0".to_vec();
+ payload.extend_from_slice(&tiff);
+ let mut out = vec![0xFF, 0xD8, 0xFF, 0xE1];
+ out.extend_from_slice(&((payload.len() + 2) as u16).to_be_bytes());
+ out.extend_from_slice(&payload);
+ out.extend_from_slice(&jpeg[2..]);
+ out
+ }
+
+ #[test]
+ fn exif_rotation_is_applied() {
+ let img = gradient(120, 80);
+ let rotated = decode_image(&jpeg_with_orientation(&img, 6)).unwrap();
+ assert_eq!(rotated.exif_orientation, 6);
+ assert_eq!(rotated.size(), Size::new(80, 120));
+ let plain = decode_image(&jpeg_with_orientation(&img, 1)).unwrap();
+ assert_eq!(plain.size(), Size::new(120, 80));
+ let r8 = decode_image(&jpeg_with_orientation(&img, 8)).unwrap();
+ assert_eq!(r8.size(), Size::new(80, 120));
+ // Rotate 90 CW: the original top-left (dark red channel) lands at top-right.
+ let tl = rotated.pixels.get_pixel(79, 0);
+ assert!(tl[0] < 40 && tl[1] < 40, "{tl:?}");
+ }
+
+ #[test]
+ fn png_roundtrip_preserves_pixels_alpha_text_and_icc() {
+ let mut img = gradient(64, 48);
+ img.put_pixel(3, 3, Rgba([10, 20, 30, 0]));
+ img.put_pixel(4, 3, Rgba([10, 20, 30, 128]));
+ let icc = vec![1u8, 2, 3, 4, 5];
+ let bytes = encode_png(&img, &[("parameters", "a cat, Steps: 30"), ("qls", "{\"seed\":1}")], Some(&icc), false).unwrap();
+ let back = decode_image(&bytes).unwrap();
+ assert_eq!(back.pixels, img);
+ assert!(back.has_transparency);
+ assert_eq!(back.icc_profile.as_deref(), Some(&icc[..]));
+ assert!(back.text.iter().any(|(k, v)| k == "parameters" && v == "a cat, Steps: 30"));
+ assert!(back.text.iter().any(|(k, _)| k == "qls"));
+ }
+
+ #[test]
+ fn opaque_png_written_as_rgb_but_identical() {
+ let img = gradient(33, 17);
+ let bytes = encode_png(&img, &[], None, true).unwrap();
+ let back = decode_image(&bytes).unwrap();
+ assert!(!back.has_transparency);
+ assert_eq!(back.pixels, img);
+ }
+
+ #[test]
+ fn unicode_text_roundtrip() {
+ let img = gradient(8, 8);
+ let bytes = encode_png(&img, &[("parameters", "caffè, 東京 ✓")], None, true).unwrap();
+ assert_eq!(read_png_text(&bytes)[0].1, "caffè, 東京 ✓");
+ }
+
+ #[test]
+ fn pad_edge_preserves_content_and_replicates() {
+ let img = gradient(1920 / 8, 1080 / 8);
+ let canvas = Size::new(240, 136);
+ let out = pad_edge(&img, canvas, (0, 1));
+ assert_eq!(out.dimensions(), (240, 136));
+ assert_eq!(crop(&out, Rect::new(0, 1, 240, 135)), img);
+ assert_eq!(out.get_pixel(5, 0), img.get_pixel(5, 0));
+ assert_eq!(out.get_pixel(5, 135), img.get_pixel(5, 134));
+ }
+
+ #[test]
+ fn pad_then_crop_back_is_lossless() {
+ let img = gradient(1537 / 4, 1025 / 4);
+ let w = crate::geometry::plan_working_canvas(Size::new(img.width(), img.height()), &crate::geometry::CanvasLimits { min_side: 32, ..Default::default() });
+ let padded = pad_edge(&img, w.canvas, w.content_offset);
+ assert!(w.canvas.is_aligned(32));
+ assert_eq!(crop(&padded, w.content_rect()), img);
+ }
+
+ #[test]
+ fn resize_preserves_transparent_edges() {
+ // Opaque white square on fully transparent *red* background: premultiplied resize
+ // must not produce reddish fringe pixels.
+ let img = RgbaImage::from_fn(64, 64, |x, y| {
+ if (16..48).contains(&x) && (16..48).contains(&y) { Rgba([255, 255, 255, 255]) } else { Rgba([255, 0, 0, 0]) }
+ });
+ let out = resize(&img, 37, 37);
+ for p in out.pixels() {
+ if p[3] > 16 {
+ assert!(p[1] > 200 && p[2] > 200, "fringe {p:?}");
+ }
+ }
+ assert!(out.pixels().any(|p| p[3] == 0));
+ }
+
+ #[test]
+ fn resize_identity_returns_same() {
+ let img = gradient(50, 40);
+ assert_eq!(resize(&img, 50, 40), img);
+ }
+
+ #[test]
+ fn mask_ops() {
+ let size = Size::new(100, 80);
+ let m = mask_rect(size, Rect::new(40, 30, 10, 10), 255, 0);
+ assert_eq!(mask_bbox(&m, 127), Some(Rect::new(40, 30, 10, 10)));
+ let d = dilate(&m, 5);
+ assert_eq!(mask_bbox(&d, 127), Some(Rect::new(35, 25, 20, 20)));
+ let e = erode(&d, 5);
+ assert_eq!(mask_bbox(&e, 127), Some(Rect::new(40, 30, 10, 10)));
+ let inv = invert_mask(&m);
+ assert_eq!(inv.get_pixel(0, 0)[0], 255);
+ assert_eq!(inv.get_pixel(45, 35)[0], 0);
+ let big = mask_rect(size, Rect::new(30, 20, 40, 40), 255, 0);
+ let f = feather(&big, 6);
+ assert_eq!(f.get_pixel(50, 40)[0], 255);
+ assert_eq!(f.get_pixel(0, 0)[0], 0);
+ let edge = f.get_pixel(30, 40)[0];
+ assert!(edge > 0 && edge < 255, "edge {edge}");
+ assert!(mask_bbox(&GrayImage::new(10, 10), 0).is_none());
+ assert!((mask_coverage(&m, 127) - 100.0 / 8000.0).abs() < 1e-9);
+ }
+
+ #[test]
+ fn backend_mask_covers_feather() {
+ let size = Size::new(64, 64);
+ let m = feather(&mask_rect(size, Rect::new(20, 20, 24, 24), 255, 0), 6);
+ let b = backend_mask(&m, 4);
+ for (x, y, p) in m.enumerate_pixels() {
+ if p[0] > 0 {
+ assert_eq!(b.get_pixel(x, y)[0], 255, "uncovered at {x},{y}");
+ }
+ }
+ assert!(b.pixels().all(|p| p[0] == 0 || p[0] == 255));
+ }
+
+ #[test]
+ fn mask_from_alpha_layer_and_from_luma() {
+ let mut layer = RgbaImage::from_pixel(10, 10, Rgba([0, 0, 0, 0]));
+ layer.put_pixel(2, 2, Rgba([0, 0, 0, 255]));
+ let li = LoadedImage { pixels: layer, format: "png", exif_orientation: 1, icc_profile: None, has_transparency: true, text: vec![] };
+ let m = mask_from_image(&li);
+ assert_eq!(m.get_pixel(2, 2)[0], 255);
+ assert_eq!(m.get_pixel(3, 3)[0], 0);
+ let bw = RgbaImage::from_fn(10, 10, |x, _| if x < 5 { Rgba([255, 255, 255, 255]) } else { Rgba([0, 0, 0, 255]) });
+ let li = LoadedImage { pixels: bw, format: "png", exif_orientation: 1, icc_profile: None, has_transparency: false, text: vec![] };
+ let m = mask_from_image(&li);
+ assert_eq!((m.get_pixel(1, 1)[0], m.get_pixel(8, 1)[0]), (255, 0));
+ }
+
+ #[test]
+ fn composite_keeps_unmasked_pixels_exactly_including_alpha() {
+ let mut base = RgbaImage::from_fn(50, 50, |x, y| Rgba([x as u8, y as u8, 9, (x * 5) as u8]));
+ let orig = base.clone();
+ let top = RgbaImage::from_pixel(20, 20, Rgba([200, 200, 200, 255]));
+ let mask = feather(&mask_rect(Size::new(20, 20), Rect::new(5, 5, 10, 10), 255, 0), 3);
+ composite(&mut base, &top, &mask, (10, 10));
+ for (x, y, p) in base.enumerate_pixels() {
+ let inside_top = (10..30).contains(&x) && (10..30).contains(&y);
+ if !inside_top || mask.get_pixel(x - 10, y - 10)[0] == 0 {
+ assert_eq!(p, orig.get_pixel(x, y));
+ }
+ }
+ assert_eq!(base.get_pixel(20, 20), &Rgba([200, 200, 200, 255]));
+ }
+
+ #[test]
+ fn outpaint_masks() {
+ let size = Size::new(128, 64);
+ let keep = Rect::new(0, 0, 96, 64);
+ let m = outpaint_mask(size, keep, Expansion { right: 8, ..Default::default() });
+ assert_eq!(m.get_pixel(10, 10)[0], 0);
+ assert_eq!(m.get_pixel(90, 10)[0], 255); // overlap band regenerated
+ assert_eq!(m.get_pixel(120, 10)[0], 255);
+ let p = paste_back_mask(Size::new(96, 64), Expansion { right: 32, ..Default::default() }, 8);
+ assert_eq!(p.get_pixel(0, 10)[0], 255); // left edge not expanded: no ramp
+ assert_eq!(p.get_pixel(50, 10)[0], 255);
+ assert!(p.get_pixel(95, 10)[0] < 40);
+ }
+
+ #[test]
+ fn decode_failure_is_friendly() {
+ let e = decode_image(b"not an image at all").unwrap_err();
+ assert_eq!(e.code, ErrorCode::ImageDecode);
+ }
+}
diff --git a/crates/qls-core/src/lib.rs b/crates/qls-core/src/lib.rs
new file mode 100644
index 0000000..7ada249
--- /dev/null
+++ b/crates/qls-core/src/lib.rs
@@ -0,0 +1,15 @@
+pub mod config;
+pub mod diagnostics;
+pub mod engine;
+pub mod error;
+pub mod geometry;
+pub mod hdr;
+pub mod heif;
+pub mod imaging;
+pub mod paths;
+pub mod pipeline;
+pub mod planner;
+pub mod process;
+pub mod sdcpp;
+pub mod store;
+pub mod wic;
diff --git a/crates/qls-core/src/paths.rs b/crates/qls-core/src/paths.rs
new file mode 100644
index 0000000..ddabb0e
--- /dev/null
+++ b/crates/qls-core/src/paths.rs
@@ -0,0 +1,291 @@
+//! Validation of filesystem paths received through MCP / HTTP. Rules:
+//! - absolute local drive paths only (no UNC, device namespaces, or alternate streams);
+//! - no `..` escaping an allowed root; symlinked parents are resolved before checking;
+//! - only image extensions; size-limited inputs;
+//! - outputs never overwrite existing files or any input file (a numbered suffix is added).
+
+use std::path::{Component, Path, PathBuf};
+
+use crate::error::{AppError, AppResult, ErrorCode};
+
+pub const INPUT_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "webp", "bmp", "gif", "tif", "tiff", "heic", "heif"];
+pub const OUTPUT_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "webp"];
+pub const MAX_INPUT_BYTES: u64 = 200 * 1024 * 1024;
+
+fn bad(msg: impl Into<String>) -> AppError {
+ AppError::new(ErrorCode::InvalidPath, msg)
+}
+
+const RESERVED: &[&str] = &[
+ "con", "prn", "aux", "nul", "com1", "com2", "com3", "com4", "com5", "com6", "com7", "com8", "com9", "lpt1", "lpt2", "lpt3", "lpt4",
+ "lpt5", "lpt6", "lpt7", "lpt8", "lpt9",
+];
+
+/// Lexically normalizes an absolute path (resolving `.` and `..`) after rejecting
+/// dangerous forms. Relative paths are joined to `base` when given.
+pub fn normalize(raw: &str, base: Option<&Path>) -> AppResult<PathBuf> {
+ let s = raw.trim();
+ if s.is_empty() {
+ return Err(bad("The path is empty."));
+ }
+ if s.contains('\0') || s.chars().any(|c| (c as u32) < 0x20) {
+ return Err(bad("The path contains invalid characters."));
+ }
+ if s.starts_with(r"\\") || s.starts_with("//") {
+ return Err(bad("Network and device paths are not allowed."));
+ }
+ let p = Path::new(s);
+ let joined: PathBuf = if p.is_absolute() {
+ p.to_path_buf()
+ } else {
+ match base {
+ Some(b) if !s.contains(':') => b.join(p),
+ _ => return Err(bad("Use an absolute path (for example C:\\Images\\photo.png).")),
+ }
+ };
+ let mut out = PathBuf::new();
+ for c in joined.components() {
+ match c {
+ Component::Prefix(pre) => {
+ use std::path::Prefix;
+ match pre.kind() {
+ Prefix::Disk(_) => out.push(pre.as_os_str()),
+ _ => return Err(bad("Network and device paths are not allowed.")),
+ }
+ }
+ Component::RootDir => out.push(std::path::MAIN_SEPARATOR_STR),
+ Component::CurDir => {}
+ Component::ParentDir => {
+ if !out.pop() || out.parent().is_none() {
+ return Err(bad("The path escapes its folder."));
+ }
+ }
+ Component::Normal(n) => {
+ let name = n.to_string_lossy();
+ if name.contains(':') {
+ return Err(bad("Alternate data streams are not allowed."));
+ }
+ let stem = name.split('.').next().unwrap_or("").to_ascii_lowercase();
+ if RESERVED.contains(&stem.trim_end().as_ref()) {
+ return Err(bad(format!("'{name}' is a reserved Windows name.")));
+ }
+ if name.ends_with(' ') || (name.ends_with('.') && name != "." && name != "..") {
+ return Err(bad("File names cannot end with a space or a dot."));
+ }
+ out.push(n);
+ }
+ }
+ }
+ Ok(out)
+}
+
+fn ext_of(p: &Path) -> Option<String> {
+ p.extension().map(|e| e.to_string_lossy().to_ascii_lowercase())
+}
+
+/// Resolves symlinks/junctions on the deepest existing ancestor, then re-appends the rest.
+fn resolve_existing_prefix(p: &Path) -> PathBuf {
+ let mut existing = p.to_path_buf();
+ let mut rest = Vec::new();
+ while !existing.exists() {
+ match (existing.file_name().map(|s| s.to_os_string()), existing.parent()) {
+ (Some(n), Some(parent)) => {
+ rest.push(n);
+ existing = parent.to_path_buf();
+ }
+ _ => return p.to_path_buf(),
+ }
+ }
+ let mut resolved = dunce_canonical(&existing).unwrap_or(existing);
+ for n in rest.into_iter().rev() {
+ resolved.push(n);
+ }
+ resolved
+}
+
+/// `std::fs::canonicalize` returns `\\?\C:\...` on Windows; strip it for comparisons.
+pub fn dunce_canonical(p: &Path) -> std::io::Result<PathBuf> {
+ let c = std::fs::canonicalize(p)?;
+ let s = c.to_string_lossy();
+ Ok(match s.strip_prefix(r"\\?\") {
+ Some(rest) if !rest.starts_with("UNC") => PathBuf::from(rest),
+ _ => c,
+ })
+}
+
+fn starts_with_ci(p: &Path, root: &Path) -> bool {
+ let a = p.to_string_lossy().to_ascii_lowercase().replace('/', "\\");
+ let mut b = root.to_string_lossy().to_ascii_lowercase().replace('/', "\\");
+ if !b.ends_with('\\') {
+ b.push('\\');
+ }
+ a == b.trim_end_matches('\\') || a.starts_with(&b)
+}
+
+pub fn is_within(p: &Path, roots: &[PathBuf]) -> bool {
+ let rp = resolve_existing_prefix(p);
+ roots.iter().any(|r| {
+ let rr = resolve_existing_prefix(r);
+ starts_with_ci(&rp, &rr)
+ })
+}
+
+/// Validates an input image path. `roots`: when non-empty, the file must be inside one.
+pub fn validate_input_image(raw: &str, base: Option<&Path>, roots: &[PathBuf]) -> AppResult<PathBuf> {
+ let p = normalize(raw, base)?;
+ match ext_of(&p) {
+ Some(e) if INPUT_EXTENSIONS.contains(&e.as_str()) => {}
+ _ => return Err(bad("Only PNG, JPEG, WebP, BMP, GIF, TIFF and HEIC images are supported.")),
+ }
+ if !roots.is_empty() && !is_within(&p, roots) {
+ return Err(bad(format!("{} is outside the allowed folders.", p.display())));
+ }
+ let meta = std::fs::metadata(&p).map_err(|e| AppError::io("read the image", &p, e))?;
+ if !meta.is_file() {
+ return Err(bad(format!("{} is not a file.", p.display())));
+ }
+ if meta.len() > MAX_INPUT_BYTES {
+ return Err(bad("The image file is larger than 200 MB."));
+ }
+ Ok(p)
+}
+
+pub fn sanitize_file_stem(s: &str) -> String {
+ let cleaned: String = s
+ .chars()
+ .map(|c| if c.is_alphanumeric() || c == '-' || c == '_' { c } else { '-' })
+ .collect();
+ let mut out = String::new();
+ for c in cleaned.chars() {
+ if c == '-' && out.ends_with('-') {
+ continue;
+ }
+ out.push(c);
+ }
+ let out = out.trim_matches('-').chars().take(60).collect::<String>().to_lowercase();
+ if out.is_empty() { "image".into() } else { out }
+}
+
+/// Resolves where to write an output. Adds `.png` if no extension; requires an allowed
+/// root; never returns an existing path or one of `inputs` (adds -1, -2, ...).
+pub fn resolve_output_path(raw: &str, base: Option<&Path>, roots: &[PathBuf], inputs: &[PathBuf]) -> AppResult<PathBuf> {
+ let mut p = normalize(raw, base)?;
+ match ext_of(&p) {
+ None => {
+ p.set_extension("png");
+ }
+ Some(e) if OUTPUT_EXTENSIONS.contains(&e.as_str()) => {}
+ Some(_) => return Err(bad("Output files must end in .png, .jpg or .webp.")),
+ }
+ if !is_within(&p, roots) {
+ return Err(bad(format!("{} is outside the allowed output folders.", p.display())));
+ }
+ Ok(unique_path(p, inputs))
+}
+
+pub fn unique_path(p: PathBuf, avoid: &[PathBuf]) -> PathBuf {
+ let collides = |c: &Path| c.exists() || avoid.iter().any(|a| a.to_string_lossy().eq_ignore_ascii_case(&c.to_string_lossy()));
+ if !collides(&p) {
+ return p;
+ }
+ let stem = p.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "image".into());
+ let ext = p.extension().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "png".into());
+ let dir = p.parent().map(|d| d.to_path_buf()).unwrap_or_default();
+ for i in 1..10_000 {
+ let c = dir.join(format!("{stem}-{i}.{ext}"));
+ if !collides(&c) {
+ return c;
+ }
+ }
+ dir.join(format!("{stem}-{}.{ext}", uuid::Uuid::new_v4().simple()))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn normalize_rejects_dangerous_forms() {
+ for bad_path in [
+ r"\\server\share\a.png",
+ r"\\?\C:\a.png",
+ r"\\.\PhysicalDrive0",
+ "//server/x.png",
+ r"C:\images\a.png:stream",
+ r"C:\images\CON.png",
+ r"C:\images\nul",
+ "",
+ "a\0b",
+ r"C:\..\..\Windows",
+ ] {
+ assert!(normalize(bad_path, None).is_err(), "{bad_path:?} accepted");
+ }
+ assert!(normalize("relative.png", None).is_err());
+ assert!(normalize(r"C:relative.png", Some(Path::new(r"C:\base"))).is_err(), "drive-relative");
+ }
+
+ #[test]
+ fn normalize_resolves_dots() {
+ assert_eq!(normalize(r"C:\a\b\..\c\.\d.png", None).unwrap(), PathBuf::from(r"C:\a\c\d.png"));
+ assert_eq!(normalize(r"assets\hero.png", Some(Path::new(r"C:\proj"))).unwrap(), PathBuf::from(r"C:\proj\assets\hero.png"));
+ assert_eq!(normalize("C:/a/b.png", None).unwrap(), PathBuf::from(r"C:\a\b.png"));
+ }
+
+ #[test]
+ fn traversal_outside_root_is_rejected() {
+ let dir = tempfile::tempdir().unwrap();
+ let root = dir.path().join("proj");
+ std::fs::create_dir_all(root.join("assets")).unwrap();
+ let roots = vec![root.clone()];
+ let ok = resolve_output_path(r"assets\hero.png", Some(&root), &roots, &[]).unwrap();
+ assert!(ok.ends_with("hero.png"));
+ let escape = resolve_output_path(r"..\outside.png", Some(&root), &roots, &[]);
+ assert!(escape.is_err());
+ let sneaky = resolve_output_path(r"assets\..\..\proj2\x.png", Some(&root), &roots, &[]);
+ assert!(sneaky.is_err());
+ // Prefix trick: C:\...\proj2 must not count as inside C:\...\proj
+ let sibling = dir.path().join("proj2").join("x.png");
+ assert!(!is_within(&sibling, &roots));
+ }
+
+ #[test]
+ fn outputs_never_overwrite() {
+ let dir = tempfile::tempdir().unwrap();
+ let roots = vec![dir.path().to_path_buf()];
+ let existing = dir.path().join("a.png");
+ std::fs::write(&existing, b"x").unwrap();
+ let p = resolve_output_path(&existing.to_string_lossy(), None, &roots, &[]).unwrap();
+ assert_eq!(p.file_name().unwrap(), "a-1.png");
+ let input = dir.path().join("b.png");
+ let p = resolve_output_path(&input.to_string_lossy(), None, &roots, std::slice::from_ref(&input)).unwrap();
+ assert_eq!(p.file_name().unwrap(), "b-1.png");
+ let p = resolve_output_path(&dir.path().join("noext").to_string_lossy(), None, &roots, &[]).unwrap();
+ assert_eq!(p.extension().unwrap(), "png");
+ assert!(resolve_output_path(&dir.path().join("x.exe").to_string_lossy(), None, &roots, &[]).is_err());
+ }
+
+ #[test]
+ fn input_validation() {
+ let dir = tempfile::tempdir().unwrap();
+ let img = dir.path().join("in.png");
+ std::fs::write(&img, b"fake").unwrap();
+ let roots = vec![dir.path().to_path_buf()];
+ assert!(validate_input_image(&img.to_string_lossy(), None, &roots).is_ok());
+ assert!(validate_input_image(&img.to_string_lossy(), None, &[]).is_ok());
+ assert!(validate_input_image(&dir.path().join("missing.png").to_string_lossy(), None, &roots).is_err());
+ let txt = dir.path().join("a.txt");
+ std::fs::write(&txt, b"x").unwrap();
+ assert!(validate_input_image(&txt.to_string_lossy(), None, &roots).is_err());
+ let other = tempfile::tempdir().unwrap();
+ let outside = other.path().join("o.png");
+ std::fs::write(&outside, b"x").unwrap();
+ assert!(validate_input_image(&outside.to_string_lossy(), None, &roots).is_err());
+ }
+
+ #[test]
+ fn stems() {
+ assert_eq!(sanitize_file_stem("A hero image: sunset / city!"), "a-hero-image-sunset-city");
+ assert_eq!(sanitize_file_stem("../../etc"), "etc");
+ assert_eq!(sanitize_file_stem("???"), "image");
+ }
+}
diff --git a/crates/qls-core/src/pipeline.rs b/crates/qls-core/src/pipeline.rs
new file mode 100644
index 0000000..3987f6d
--- /dev/null
+++ b/crates/qls-core/src/pipeline.rs
@@ -0,0 +1,790 @@
+//! Executes a [`Plan`] at the pixel level: builds the backend request (exact working
+//! geometry, binary masks) and post-processes results (crop alignment padding, restore
+//! dimensions, composite inpaint/outpaint so untouched pixels stay bit-identical).
+//! Enlargements go through ESRGAN when the engine has it: [`crop_content`], then
+//! [`enlarge_target`] / [`esrgan_plan`] + [`Stitcher`], then [`finish`].
+
+use image::{GrayImage, Luma, Rgba, RgbaImage};
+
+use crate::error::{AppError, AppResult, ErrorCode};
+use crate::geometry::{Rect, Size};
+use crate::imaging::{self, LoadedImage};
+use crate::planner::{Plan, ResolvedMode};
+use crate::sdcpp::{Guidance, ImgGenRequest, SampleParams, VaeTilingParams, b64};
+
+/// Server-side facts that shape the request but are not part of the plan.
+#[derive(Debug, Clone)]
+pub struct BackendOptions {
+ /// `--vae-tile-size` the server was launched with (0 = no server-side tiling).
+ pub server_vae_tile_size: u32,
+}
+
+impl Default for BackendOptions {
+ fn default() -> Self {
+ Self { server_vae_tile_size: 0 }
+ }
+}
+
+/// Tile size used when the server has no tiling configured (2K decode: ~4 s vs ~22 s at 256 px).
+pub const DEFAULT_VAE_TILE: u32 = 768;
+
+/// Per-request VAE tiling. The request is merged over the server's launch defaults, so
+/// when the server already tiles (`--vae-tiling --vae-tile-size N`) nothing is sent —
+/// sending `tile_size 0` would silently select 256 px tiles. Only an explicit "off"
+/// overrides it.
+pub fn vae_tiling_params(tiling: bool, server_tile: u32) -> Option<VaeTilingParams> {
+ match (tiling, server_tile > 0) {
+ (true, true) | (false, false) => None,
+ (false, true) => Some(VaeTilingParams { enabled: false, ..Default::default() }),
+ (true, false) => Some(VaeTilingParams { enabled: true, tile_size_w: Some(DEFAULT_VAE_TILE), tile_size_h: Some(DEFAULT_VAE_TILE), target_overlap: Some(0.125) }),
+ }
+}
+
+pub struct PreparedJob {
+ pub request: ImgGenRequest,
+ pub post: PostProcess,
+}
+
+pub enum PostKind {
+ Plain,
+ Inpaint { source: RgbaImage, region: Rect, blend: GrayImage },
+ Outpaint { source: RgbaImage, feather: u32 },
+}
+
+pub struct PostProcess {
+ pub kind: PostKind,
+ /// Qwen-Image 2.1 always decodes an alpha channel; on opaque content ~1% of pixels
+ /// come back at alpha 247–254. When transparency is not intended, force opaque.
+ pub keep_alpha: bool,
+ pub working: Size,
+ pub content: Rect,
+ pub output: Size,
+ pub mode: ResolvedMode,
+ pub outpaint: Option<crate::geometry::OutpaintPlan>,
+}
+
+fn png_b64(img: &RgbaImage) -> AppResult<String> {
+ Ok(b64(&imaging::encode_png(img, &[], None, true)?))
+}
+
+fn gray_png_b64(m: &GrayImage) -> AppResult<String> {
+ let mut out = Vec::new();
+ image::DynamicImage::ImageLuma8(m.clone())
+ .write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png)
+ .map_err(|e| AppError::internal(e))?;
+ Ok(b64(&out))
+}
+
+/// Places `img` (resized to the canvas content) on the plan's padded canvas.
+fn to_canvas(img: &RgbaImage, c: &crate::geometry::WorkingCanvas) -> RgbaImage {
+ let resized = imaging::resize(img, c.content.width, c.content.height);
+ imaging::pad_edge(&resized, c.canvas, c.content_offset)
+}
+
+fn mean_color(img: &RgbaImage) -> Rgba<u8> {
+ let (mut r, mut g, mut b, mut n) = (0u64, 0u64, 0u64, 0u64);
+ let step = ((img.width() as u64 * img.height() as u64) / 65_536).max(1) as usize;
+ for p in img.pixels().step_by(step) {
+ r += p[0] as u64;
+ g += p[1] as u64;
+ b += p[2] as u64;
+ n += 1;
+ }
+ let n = n.max(1);
+ Rgba([(r / n) as u8, (g / n) as u8, (b / n) as u8, 255])
+}
+
+fn is_binary(m: &GrayImage) -> bool {
+ m.pixels().all(|p| p[0] == 0 || p[0] == 255)
+}
+
+const RGBA_PREFIX: &str = "This is an RGBA image with transparency.";
+const RGBA_SUFFIX: &str = "The image has alpha channel and the background is transparent.";
+
+/// True when the prompt asks for transparency (e.g. "transparent background", "remove the background").
+pub fn wants_transparency(prompt: &str) -> bool {
+ let p = prompt.to_lowercase();
+ ["transparent", "transparency", "alpha channel", "rgba", "no background", "without background", "remove the background", "remove background", "cut out", "cutout"]
+ .iter()
+ .any(|k| p.contains(k))
+}
+
+/// Prompt sent to the model. Transparency requests use the prompt format recommended for
+/// Qwen-Image 2.1 RGBA output; outpainting gets an instruction prefix so short prompts
+/// like "extend left" still describe the task.
+pub fn effective_prompt(plan: &Plan, prompt: &str) -> String {
+ let p = prompt.trim();
+ if wants_transparency(p) && !p.starts_with(RGBA_PREFIX) {
+ let body = p.trim_end_matches('.');
+ return format!("{RGBA_PREFIX} {body}. {RGBA_SUFFIX}");
+ }
+ match plan.mode {
+ ResolvedMode::Outpaint => format!(
+ "Extend the image naturally into the empty border areas, continuing the scene with matching perspective, lighting and style. {}",
+ prompt.trim()
+ ),
+ _ => prompt.trim().to_string(),
+ }
+}
+
+pub fn prepare(plan: &Plan, prompt: &str, seed: i64, images: &[LoadedImage], mask: Option<&GrayImage>, opts: &BackendOptions) -> AppResult<PreparedJob> {
+ let first = plan.working;
+ let mut req = ImgGenRequest {
+ prompt: effective_prompt(plan, prompt),
+ negative_prompt: plan.negative_prompt.clone(),
+ width: first.width,
+ height: first.height,
+ seed,
+ batch_count: plan.batch_count,
+ strength: None,
+ init_image: None,
+ mask_image: None,
+ ref_images: Vec::new(),
+ image_preprocess: Vec::new(),
+ sample_params: SampleParams {
+ sample_method: Some(plan.sampler.clone()),
+ scheduler: plan.scheduler.clone(),
+ sample_steps: plan.steps,
+ flow_shift: plan.flow_shift,
+ guidance: Guidance { txt_cfg: plan.cfg, img_cfg: None },
+ },
+ vae_tiling_params: vae_tiling_params(plan.vae_tiling, opts.server_vae_tile_size),
+ hires: None,
+ cache_mode: plan.cache_threshold.map(|_| "easycache".to_string()),
+ cache_option: plan.cache_threshold.map(|t| format!("threshold={t}")),
+ output_format: "png".into(),
+ embed_image_metadata: false,
+ };
+ let mut kind = PostKind::Plain;
+ let keep_alpha = wants_transparency(prompt) || images.iter().any(|i| i.has_transparency);
+ let need_images = |n: usize| -> AppResult<()> {
+ if images.len() < n {
+ Err(AppError::new(ErrorCode::InvalidInput, "An input image is missing."))
+ } else {
+ Ok(())
+ }
+ };
+
+ match plan.mode {
+ ResolvedMode::Generate => {}
+ ResolvedMode::Edit | ResolvedMode::MultiReference => {
+ need_images(plan.references.len())?;
+ for r in &plan.references {
+ let img = &images[r.index].pixels;
+ req.ref_images.push(png_b64(&to_canvas(img, &r.canvas))?);
+ }
+ req.image_preprocess.push("target=ref,mode=none".into());
+ if let Some(s) = plan.strength {
+ req.strength = Some(s);
+ }
+ }
+ ResolvedMode::Inpaint => {
+ need_images(1)?;
+ let src = &images[0].pixels;
+ let src_size = Size::new(src.width(), src.height());
+ let user_mask = mask.ok_or_else(|| AppError::invalid("A mask is required for inpainting."))?;
+ let user_mask = imaging::resize_mask(user_mask, src_size.width, src_size.height);
+ let region = plan.inpaint_region.unwrap_or(Rect::new(0, 0, src_size.width, src_size.height));
+ let wc = plan.references[0].canvas;
+ let crop = imaging::crop(src, region);
+ let canvas = to_canvas(&crop, &wc);
+ let canvas_b64 = png_b64(&canvas)?;
+ drop(canvas);
+
+ // Blend mask (source resolution): soft edges so the patch merges invisibly.
+ let mut blend = imaging::crop_mask(&user_mask, region);
+ if is_binary(&blend) {
+ let r = ((region.width.max(region.height) as f64) * 0.006).round().max(3.0) as u32;
+ blend = imaging::feather(&imaging::dilate(&blend, r / 2), r);
+ }
+ // Backend mask (working resolution): binary, grown to cover the soft edge.
+ let m_work = imaging::resize_mask(&blend, wc.content.width, wc.content.height);
+ let grow = ((wc.scale * 4.0).round() as u32).clamp(4, 24);
+ let m_work = imaging::backend_mask(&m_work, grow);
+ let mut m_canvas = GrayImage::from_pixel(wc.canvas.width, wc.canvas.height, Luma([0]));
+ image::imageops::replace(&mut m_canvas, &m_work, wc.content_offset.0 as i64, wc.content_offset.1 as i64);
+
+ req.init_image = Some(canvas_b64.clone());
+ req.ref_images.push(canvas_b64);
+ req.mask_image = Some(gray_png_b64(&m_canvas)?);
+ req.strength = plan.strength;
+ req.image_preprocess = vec!["target=init,mode=none".into(), "target=mask,mode=none,filter=nearest-exact".into(), "target=ref,mode=none".into()];
+ kind = PostKind::Inpaint { source: src.clone(), region, blend };
+ }
+ ResolvedMode::Outpaint => {
+ need_images(1)?;
+ let src = &images[0].pixels;
+ let op = plan.outpaint.ok_or_else(|| AppError::internal("missing outpaint plan"))?;
+ let r = op.source_rect_working;
+ let scaled = imaging::resize(src, r.width, r.height);
+ // Unknown areas get the image's mean color: neutral, no edge streaks.
+ let canvas = imaging::pad_solid(&scaled, op.working.canvas, (r.x, r.y), mean_color(src));
+ let mask = imaging::outpaint_mask(op.working.canvas, r, op.overlap_working);
+ req.init_image = Some(png_b64(&canvas)?);
+ req.mask_image = Some(gray_png_b64(&mask)?);
+ req.ref_images.push(png_b64(&to_canvas(src, &plan.references[0].canvas))?);
+ req.strength = plan.strength;
+ req.image_preprocess = vec!["target=init,mode=none".into(), "target=mask,mode=none,filter=nearest-exact".into(), "target=ref,mode=none".into()];
+ let feather_final = ((op.overlap_working.left.max(op.overlap_working.right).max(op.overlap_working.top).max(op.overlap_working.bottom)) as f64
+ / op.working.scale)
+ .round() as u32;
+ kind = PostKind::Outpaint { source: src.clone(), feather: feather_final.max(2) };
+ }
+ ResolvedMode::Upscale => {
+ // Detailed upscale: plain img2img over the (already enlarged) image.
+ need_images(1)?;
+ if plan.steps == 0 {
+ return Err(AppError::internal("a quick upscale has no diffusion request"));
+ }
+ let canvas = to_canvas(&images[0].pixels, &plan.references[0].canvas);
+ req.init_image = Some(png_b64(&canvas)?);
+ req.strength = plan.strength;
+ req.image_preprocess = vec!["target=init,mode=none".into()];
+ }
+ }
+
+ Ok(PreparedJob {
+ request: req,
+ post: PostProcess { kind, keep_alpha, working: plan.working, content: plan.content, output: plan.output, mode: plan.mode, outpaint: plan.outpaint },
+ })
+}
+
+/// Turns one backend output image into the delivered image (Lanczos for any resize).
+pub fn postprocess(raw: RgbaImage, post: &PostProcess) -> AppResult<RgbaImage> {
+ finish(crop_content(raw, post), post)
+}
+
+/// Step 1: the meaningful part of a backend image (alignment padding removed).
+pub fn crop_content(raw: RgbaImage, post: &PostProcess) -> RgbaImage {
+ let raw = if raw.width() != post.working.width || raw.height() != post.working.height {
+ tracing::warn!("backend returned {}x{}, expected {:?}", raw.width(), raw.height(), post.working);
+ imaging::resize(&raw, post.working.width, post.working.height)
+ } else {
+ raw
+ };
+ let mut content = imaging::crop(&raw, post.content);
+ drop(raw);
+ if !post.keep_alpha {
+ for p in content.pixels_mut() {
+ p[3] = 255;
+ }
+ }
+ content
+}
+
+/// Size the content is resized to in [`finish`], when ESRGAN may help. Inpaint patches
+/// are generated near native size and keep the plain path.
+pub fn enlarge_target(post: &PostProcess) -> Option<Size> {
+ match &post.kind {
+ PostKind::Plain => Some(post.output),
+ PostKind::Outpaint { .. } => post.outpaint.map(|o| o.final_size),
+ PostKind::Inpaint { .. } => None,
+ }
+}
+
+/// Step 3: resize (now usually *down* from an ESRGAN result) and composite. `content`
+/// is the output of [`crop_content`], optionally enlarged in between.
+pub fn finish(content: RgbaImage, post: &PostProcess) -> AppResult<RgbaImage> {
+ Ok(match &post.kind {
+ PostKind::Plain => imaging::resize(&content, post.output.width, post.output.height),
+ PostKind::Inpaint { source, region, blend } => {
+ let patch = imaging::resize(&content, region.width, region.height);
+ let mut out = source.clone();
+ imaging::composite(&mut out, &patch, blend, (region.x, region.y));
+ out
+ }
+ PostKind::Outpaint { source, feather } => {
+ let op = post.outpaint.as_ref().ok_or_else(|| AppError::internal("missing outpaint plan"))?;
+ let mut out = imaging::resize(&content, op.final_size.width, op.final_size.height);
+ let paste = imaging::paste_back_mask(Size::new(source.width(), source.height()), op.expansion, *feather);
+ imaging::composite(&mut out, source, &paste, (op.source_rect_final.x, op.source_rect_final.y));
+ out
+ }
+ })
+}
+
+// ---------------------------------------------------------------------------------------
+// ESRGAN enlargement (POST /sdcpp/v1/upscale)
+// ---------------------------------------------------------------------------------------
+
+/// Results per side of one `/sdcpp/v1/upscale` call (server limit, routes_sdcpp.cpp).
+pub const ESRGAN_MAX_OUTPUT_SIDE: u32 = 8192;
+/// Context shared by neighbouring tiles; ESRGAN's receptive field is far smaller.
+pub const ESRGAN_TILE_OVERLAP: u32 = 32;
+/// Cap on the intermediate x4 image (~400 MB RGBA); larger inputs are shrunk first.
+pub const ESRGAN_MAX_OUTPUT_AREA: u64 = 100_000_000;
+/// Below this linear factor Lanczos is as good and much cheaper.
+pub const ESRGAN_MIN_FACTOR: f64 = 1.1;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Tile {
+ /// Region sent to the upscaler (input coordinates).
+ pub rect: Rect,
+ /// Part of the tile kept in the stitched result; cores cover the image without gaps.
+ pub core: Rect,
+}
+
+#[derive(Debug, Clone, PartialEq)]
+pub struct EsrganPlan {
+ /// Size the content is resized to before upscaling (usually unchanged).
+ pub input: Size,
+ pub tiles: Vec<Tile>,
+}
+
+fn axis_tiles(len: u32, max: u32, overlap: u32) -> Vec<(u32, u32, u32, u32)> {
+ if len <= max {
+ return vec![(0, len, 0, len)];
+ }
+ let n = (len - overlap).div_ceil(max - overlap);
+ let tile = (len + (n - 1) * overlap).div_ceil(n).min(max);
+ let mut out = Vec::with_capacity(n as usize);
+ for i in 0..n {
+ let start = (i * (tile - overlap)).min(len - tile);
+ let end = start + tile;
+ let core_start = if i == 0 { 0 } else { start + overlap / 2 };
+ let core_end = if i == n - 1 { len } else { end - overlap / 2 };
+ out.push((start, end, core_start, core_end));
+ }
+ out
+}
+
+/// Overlapping tiles no larger than `max` per side.
+pub fn tile_grid(size: Size, max: u32, overlap: u32) -> Vec<Tile> {
+ let xs = axis_tiles(size.width, max, overlap);
+ let ys = axis_tiles(size.height, max, overlap);
+ let mut tiles = Vec::with_capacity(xs.len() * ys.len());
+ for &(y0, y1, cy0, cy1) in &ys {
+ for &(x0, x1, cx0, cx1) in &xs {
+ tiles.push(Tile { rect: Rect::new(x0, y0, x1 - x0, y1 - y0), core: Rect::new(cx0, cy0, cx1 - cx0, cy1 - cy0) });
+ }
+ }
+ tiles
+}
+
+/// How to enlarge `content` to `target` with an x`scale` ESRGAN model; None when the
+/// factor is small enough for Lanczos.
+pub fn esrgan_plan(content: Size, target: Size, scale: u32) -> Option<EsrganPlan> {
+ let factor = (target.width as f64 / content.width as f64).max(target.height as f64 / content.height as f64);
+ if factor <= ESRGAN_MIN_FACTOR || scale < 2 {
+ return None;
+ }
+ let s2 = (scale * scale) as u64;
+ let input = if content.area() * s2 > ESRGAN_MAX_OUTPUT_AREA {
+ let k = (ESRGAN_MAX_OUTPUT_AREA as f64 / (content.area() * s2) as f64).sqrt();
+ Size::new(((content.width as f64 * k).floor() as u32).max(1), ((content.height as f64 * k).floor() as u32).max(1))
+ } else {
+ content
+ };
+ Some(EsrganPlan { input, tiles: tile_grid(input, ESRGAN_MAX_OUTPUT_SIDE / scale, ESRGAN_TILE_OVERLAP) })
+}
+
+/// Assembles upscaled tiles. The model's real factor comes from the first result.
+pub struct Stitcher {
+ input: Size,
+ out: Option<RgbaImage>,
+ scale: u32,
+}
+
+impl Stitcher {
+ pub fn new(input: Size) -> Self {
+ Self { input, out: None, scale: 0 }
+ }
+
+ pub fn add(&mut self, tile: &Tile, up: &RgbaImage) -> AppResult<()> {
+ let scale = up.width() / tile.rect.width.max(1);
+ if scale < 1 || up.width() != tile.rect.width * scale || up.height() != tile.rect.height * scale {
+ return Err(AppError::new(ErrorCode::GenerationFailed, "The upscaler returned an unexpected size.")
+ .detail(format!("tile {:?} -> {}x{}", tile.rect, up.width(), up.height())));
+ }
+ if self.out.is_none() {
+ self.scale = scale;
+ self.out = Some(RgbaImage::new(self.input.width * scale, self.input.height * scale));
+ } else if scale != self.scale {
+ return Err(AppError::new(ErrorCode::GenerationFailed, "The upscaler changed its scale between tiles."));
+ }
+ let c = tile.core;
+ let piece = image::imageops::crop_imm(up, (c.x - tile.rect.x) * scale, (c.y - tile.rect.y) * scale, c.width * scale, c.height * scale).to_image();
+ image::imageops::replace(self.out.as_mut().unwrap(), &piece, (c.x * scale) as i64, (c.y * scale) as i64);
+ Ok(())
+ }
+
+ /// The stitched image. ESRGAN models are RGB-only, so `alpha_from`'s alpha channel
+ /// (if it has any transparency) is resized onto the result.
+ pub fn finish(self, alpha_from: &RgbaImage) -> AppResult<RgbaImage> {
+ let mut out = self.out.ok_or_else(|| AppError::internal("no upscaled tiles"))?;
+ if alpha_from.pixels().any(|p| p[3] != 255) {
+ let a = image::imageops::resize(alpha_from, out.width(), out.height(), image::imageops::FilterType::Lanczos3);
+ for (o, s) in out.pixels_mut().zip(a.pixels()) {
+ o[3] = s[3];
+ }
+ } else {
+ for p in out.pixels_mut() {
+ p[3] = 255;
+ }
+ }
+ Ok(out)
+ }
+}
+
+/// PNG (base64) of one tile for the upscale endpoint (alpha is dropped by the server).
+pub fn tile_png_b64(input: &RgbaImage, tile: &Tile) -> AppResult<String> {
+ png_b64(&imaging::crop(input, tile.rect))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::config::RecommendedSettings;
+ use crate::geometry::ExpansionUnits;
+ use crate::config::RefineMode;
+ use crate::planner::{GenerationRequest, Mode, OutpaintSpec, PlanInputs, Quality, ResolutionMode, UpscaleMethod, UpscaleSpec, plan};
+ use crate::sdcpp::b64_decode;
+
+ fn env(sizes: Vec<Size>) -> PlanInputs {
+ PlanInputs { image_sizes: sizes, vram_total_mib: Some(16303), upscaler: Some("RealESRGAN_x4plus".into()), ..Default::default() }
+ }
+ fn esrgan_opts() -> BackendOptions {
+ BackendOptions { server_vae_tile_size: 768 }
+ }
+
+ #[test]
+ fn vae_tiling_never_overrides_the_server_tile_size() {
+ assert_eq!(vae_tiling_params(true, 768), None, "server already tiles with its own size");
+ assert_eq!(vae_tiling_params(false, 0), None);
+ assert_eq!(vae_tiling_params(false, 768), Some(VaeTilingParams { enabled: false, ..Default::default() }));
+ let p = vae_tiling_params(true, 0).unwrap();
+ assert_eq!((p.enabled, p.tile_size_w, p.tile_size_h, p.target_overlap), (true, Some(768), Some(768), Some(0.125)));
+ // Regression: a planned-tiled 2K job sent tile_size 0, i.e. 256 px tiles.
+ let mut r = req("a cabin");
+ r.aspect_ratio = Some("16:9".into());
+ r.resolution = ResolutionMode::K2;
+ let i = PlanInputs { server_vae_tiling: true, ..env(vec![]) };
+ let p = plan(&r, &i, &RecommendedSettings::default()).unwrap();
+ assert!(p.vae_tiling);
+ let j = prepare(&p, &r.prompt, 1, &[], None, &esrgan_opts()).unwrap();
+ assert!(serde_json::to_value(&j.request).unwrap().get("vae_tiling_params").is_none());
+ }
+
+ #[test]
+ fn quality_generate_request_is_one_pass() {
+ let mut r = req("a cozy mountain cabin");
+ r.aspect_ratio = Some("16:9".into());
+ r.quality = Quality::Quality;
+ r.advanced.refine = Some(RefineMode::Best);
+ let p = plan(&r, &env(vec![]), &RecommendedSettings::default()).unwrap();
+ let j = prepare(&p, &r.prompt, 42, &[], None, &esrgan_opts()).unwrap();
+ let v = serde_json::to_value(&j.request).unwrap();
+ assert_eq!((v["width"].as_u64(), v["height"].as_u64()), (Some(p.working.width as u64), Some(p.working.height as u64)));
+ assert!(v.get("hires").map(|h| h.is_null()).unwrap_or(true), "no second pass");
+ assert!(v.get("cache_mode").map(|c| c.is_null()).unwrap_or(true));
+ assert_eq!(v["sample_params"]["sample_steps"], 40);
+ assert_eq!(v["sample_params"]["guidance"]["txt_cfg"], 1.0, "official: no CFG");
+ assert!(p.working.area() > 2_500_000, "Quality renders toward native 2K: {:?}", p.working);
+ }
+
+ #[test]
+ fn large_edit_is_one_pass_then_enlarged() {
+ let img = photo(2560, 1440);
+ let mut r = req("make it a dark version");
+ r.resolution = ResolutionMode::Source;
+ let p = plan(&r, &env(vec![img.size()]), &RecommendedSettings::default()).unwrap();
+ let j = prepare(&p, &r.prompt, 3, std::slice::from_ref(&img), None, &esrgan_opts()).unwrap();
+ assert!(j.request.hires.is_none());
+ assert_eq!((j.request.width, j.request.height), (p.working.width, p.working.height));
+ assert_eq!(decode(&j.request.ref_images[0]).dimensions(), (p.working.width, p.working.height), "reference matches the canvas");
+ // The single-pass result is enlarged to the 2560x1440 source size with ESRGAN.
+ let content = crop_content(fake_backend(p.working.width, p.working.height), &j.post);
+ let target = enlarge_target(&j.post).unwrap();
+ assert_eq!(target, Size::new(2560, 1440));
+ let ep = esrgan_plan(Size::new(content.width(), content.height()), target, 4).unwrap();
+ assert_eq!(ep.tiles.len(), 1, "fits one upscale call");
+ let out = finish(content, &j.post).unwrap();
+ assert_eq!(out.dimensions(), (2560, 1440));
+ }
+
+ #[test]
+ fn detailed_upscale_is_img2img_at_2k() {
+ let img = photo(1376, 768);
+ let r = GenerationRequest {
+ mode: Mode::Upscale,
+ upscale: Some(UpscaleSpec { method: UpscaleMethod::Detailed, width: Some(5120), height: Some(2880), scale: None }),
+ preserve_dimensions: true,
+ ..Default::default()
+ };
+ let p = plan(&r, &env(vec![img.size()]), &RecommendedSettings::default()).unwrap();
+ let j = prepare(&p, crate::planner::UPSCALE_PROMPT, 9, std::slice::from_ref(&img), None, &esrgan_opts()).unwrap();
+ assert_eq!((j.request.width, j.request.height), (2048, 1152));
+ assert_eq!(decode(j.request.init_image.as_ref().unwrap()).dimensions(), (2048, 1152));
+ assert!(j.request.ref_images.is_empty() && j.request.mask_image.is_none() && j.request.hires.is_none());
+ assert_eq!(j.request.strength, Some(0.3));
+ assert_eq!(j.request.image_preprocess, vec!["target=init,mode=none".to_string()]);
+ assert_eq!(enlarge_target(&j.post), Some(Size::new(5120, 2880)));
+
+ let quick = GenerationRequest { upscale: Some(UpscaleSpec::default()), ..r };
+ let p = plan(&quick, &env(vec![img.size()]), &RecommendedSettings::default()).unwrap();
+ assert!(prepare(&p, "", 9, std::slice::from_ref(&img), None, &esrgan_opts()).is_err(), "quick upscales never reach img_gen");
+ }
+
+ #[test]
+ fn enlarge_targets_by_kind() {
+ let img = photo(800, 600);
+ let mut r = req("more beach");
+ r.outpaint = Some(OutpaintSpec { left: 0.0, right: 50.0, top: 0.0, bottom: 0.0, units: ExpansionUnits::Percent });
+ let p = plan(&r, &env(vec![img.size()]), &RecommendedSettings::default()).unwrap();
+ let j = prepare(&p, &r.prompt, 1, std::slice::from_ref(&img), None, &esrgan_opts()).unwrap();
+ assert_eq!(enlarge_target(&j.post), Some(Size::new(1200, 600)));
+ let mut m = GrayImage::new(800, 600);
+ m.put_pixel(400, 300, Luma([255]));
+ let mut r = req("remove it");
+ r.mask = Some("m".into());
+ let i = PlanInputs { mask: Some((Size::new(800, 600), imaging::mask_bbox(&m, 127), 0.01)), ..env(vec![img.size()]) };
+ let p = plan(&r, &i, &RecommendedSettings::default()).unwrap();
+ let j = prepare(&p, &r.prompt, 1, std::slice::from_ref(&img), Some(&m), &esrgan_opts()).unwrap();
+ assert_eq!(enlarge_target(&j.post), None, "inpaint keeps its own path");
+ }
+
+ #[test]
+ fn esrgan_vs_lanczos_choice() {
+ let c = Size::new(1376, 768);
+ assert!(esrgan_plan(c, Size::new(1500, 837), 4).is_none(), "1.09x: Lanczos");
+ assert!(esrgan_plan(c, Size::new(1376, 768), 4).is_none());
+ assert!(esrgan_plan(c, Size::new(1000, 558), 4).is_none(), "shrinking: Lanczos");
+ let ep = esrgan_plan(c, Size::new(5120, 2880), 4).unwrap();
+ assert_eq!(ep.input, c);
+ assert_eq!(ep.tiles, vec![Tile { rect: Rect::new(0, 0, 1376, 768), core: Rect::new(0, 0, 1376, 768) }]);
+ assert!(esrgan_plan(c, Size::new(5120, 2880), 1).is_none(), "not an enlarging model");
+ }
+
+ #[test]
+ fn large_inputs_are_tiled_and_capped() {
+ let ep = esrgan_plan(Size::new(3000, 1700), Size::new(6000, 3400), 4).unwrap();
+ assert_eq!(ep.input, Size::new(3000, 1700), "an 82 MP intermediate is under the cap");
+ assert_eq!(ep.tiles.len(), 2);
+ for t in &ep.tiles {
+ assert!(t.rect.width <= 2048 && t.rect.height <= 2048);
+ }
+ // Cores tile the image exactly once.
+ let mut hits = vec![0u8; 3000 * 1700];
+ for t in &ep.tiles {
+ assert!(t.core.x >= t.rect.x && t.core.right() <= t.rect.right() && t.core.y >= t.rect.y && t.core.bottom() <= t.rect.bottom());
+ for y in t.core.y..t.core.bottom() {
+ for x in t.core.x..t.core.right() {
+ hits[(y * 3000 + x) as usize] += 1;
+ }
+ }
+ }
+ assert!(hits.iter().all(|h| *h == 1));
+ let ep = esrgan_plan(Size::new(4000, 3000), Size::new(8000, 6000), 4).unwrap();
+ assert!(ep.input.area() * 16 <= ESRGAN_MAX_OUTPUT_AREA, "{:?}", ep.input);
+ assert!(ep.input.width * 4 >= 8000 && ep.input.height * 4 >= 6000, "still covers the target");
+ assert!(tile_grid(Size::new(5000, 300), 2048, 32).iter().all(|t| t.rect.width <= 2048));
+ }
+
+ #[test]
+ fn stitched_tiles_match_a_whole_image_upscale() {
+ // A nearest-neighbour "model" is exact per pixel, so any seam would show.
+ let x4 = |img: &RgbaImage| image::imageops::resize(img, img.width() * 4, img.height() * 4, image::imageops::FilterType::Nearest);
+ let src = photo(300, 170).pixels;
+ let tiles = tile_grid(Size::new(300, 170), 128, 16);
+ assert!(tiles.len() > 4);
+ let mut st = Stitcher::new(Size::new(300, 170));
+ for t in &tiles {
+ let png = tile_png_b64(&src, t).unwrap();
+ st.add(t, &x4(&decode(&png))).unwrap();
+ }
+ let out = st.finish(&src).unwrap();
+ assert_eq!(out, x4(&src));
+ let mut bad = Stitcher::new(Size::new(300, 170));
+ assert!(bad.add(&tiles[0], &RgbaImage::new(7, 7)).is_err());
+ }
+
+ #[test]
+ fn stitched_result_keeps_source_alpha() {
+ let mut src = photo(64, 64).pixels;
+ for y in 0..32 {
+ for x in 0..64 {
+ src.get_pixel_mut(x, y)[3] = 0;
+ }
+ }
+ let t = tile_grid(Size::new(64, 64), 2048, 32)[0];
+ let mut st = Stitcher::new(Size::new(64, 64));
+ let mut up = image::imageops::resize(&src, 256, 256, image::imageops::FilterType::Nearest);
+ for p in up.pixels_mut() {
+ p[3] = 255; // ESRGAN output is RGB
+ }
+ st.add(&t, &up).unwrap();
+ let out = st.finish(&src).unwrap();
+ assert_eq!(out.get_pixel(10, 10)[3], 0);
+ assert_eq!(out.get_pixel(10, 250)[3], 255);
+ }
+
+ fn photo(w: u32, h: u32) -> LoadedImage {
+ let pixels = RgbaImage::from_fn(w, h, |x, y| Rgba([(x % 256) as u8, (y % 256) as u8, ((x + y) % 256) as u8, 255]));
+ LoadedImage { pixels, format: "png", exif_orientation: 1, icc_profile: None, has_transparency: false, text: vec![] }
+ }
+ fn req(p: &str) -> GenerationRequest {
+ GenerationRequest { prompt: p.into(), preserve_dimensions: true, ..Default::default() }
+ }
+ fn decode(b: &str) -> RgbaImage {
+ imaging::decode_image(&b64_decode(b).unwrap()).unwrap().pixels
+ }
+ fn fake_backend(w: u32, h: u32) -> RgbaImage {
+ RgbaImage::from_pixel(w, h, Rgba([9, 99, 199, 255]))
+ }
+
+ #[test]
+ fn edit_request_and_restore_1920x1080() {
+ let img = photo(1920, 1080);
+ let mut r = req("make it night");
+ r.resolution = ResolutionMode::Source;
+ r.advanced.refine = Some(RefineMode::Off);
+ let p = plan(&r, &PlanInputs { image_sizes: vec![img.size()], vram_total_mib: Some(16303), ..Default::default() }, &RecommendedSettings::default()).unwrap();
+ let j = prepare(&p, &r.prompt, 7, std::slice::from_ref(&img), None, &BackendOptions::default()).unwrap();
+ assert_eq!((j.request.width, j.request.height), (1920, 1088));
+ assert_eq!(j.request.ref_images.len(), 1);
+ assert!(j.request.init_image.is_none() && j.request.mask_image.is_none());
+ let sent = decode(&j.request.ref_images[0]);
+ assert_eq!(sent.dimensions(), (1920, 1088));
+ // Original content is intact inside the padded reference.
+ assert_eq!(imaging::crop(&sent, Rect::new(0, 4, 1920, 1080)), img.pixels);
+ let out = postprocess(fake_backend(1920, 1088), &j.post).unwrap();
+ assert_eq!(out.dimensions(), (1920, 1080));
+ }
+
+ #[test]
+ fn multi_reference_order_preserved_in_request() {
+ let imgs = vec![photo(640, 960), photo(800, 800), photo(1200, 600)];
+ let r = req("person from image 1, clothes from image 2, light from image 3");
+ let p = plan(&r, &PlanInputs { image_sizes: imgs.iter().map(|i| i.size()).collect(), vram_total_mib: Some(16303), ..Default::default() }, &RecommendedSettings::default()).unwrap();
+ let j = prepare(&p, &r.prompt, 1, &imgs, None, &BackendOptions::default()).unwrap();
+ assert_eq!(j.request.ref_images.len(), 3);
+ let dims: Vec<(u32, u32)> = j.request.ref_images.iter().map(|b| decode(b).dimensions()).collect();
+ assert!(dims[0].1 > dims[0].0, "first is portrait");
+ assert_eq!(dims[1].0, dims[1].1, "second is square");
+ assert!(dims[2].0 > dims[2].1, "third is landscape");
+ for (w, h) in dims {
+ assert!(w % 32 == 0 && h % 32 == 0);
+ assert!((w as u64 * h as u64) <= (j.request.width as u64 * j.request.height as u64));
+ }
+ }
+
+ #[test]
+ fn inpaint_preserves_unmasked_pixels_exactly() {
+ let img = photo(900, 700);
+ let mut m = GrayImage::new(900, 700);
+ for y in 300..360 {
+ for x in 400..480 {
+ m.put_pixel(x, y, Luma([255]));
+ }
+ }
+ let mut r = req("remove it");
+ r.mask = Some("input:m".into());
+ let inputs = PlanInputs {
+ image_sizes: vec![img.size()],
+ mask: Some((Size::new(900, 700), imaging::mask_bbox(&m, 127), imaging::mask_coverage(&m, 127))),
+ vram_total_mib: Some(16303),
+ ..Default::default()
+ };
+ let p = plan(&r, &inputs, &RecommendedSettings::default()).unwrap();
+ let j = prepare(&p, &r.prompt, 1, std::slice::from_ref(&img), Some(&m), &BackendOptions::default()).unwrap();
+ assert!(j.request.init_image.is_some() && j.request.mask_image.is_some());
+ assert_eq!(j.request.strength, Some(1.0));
+ let bm = imaging::decode_image(&b64_decode(j.request.mask_image.as_ref().unwrap()).unwrap()).unwrap().pixels;
+ assert_eq!(bm.dimensions(), (j.request.width, j.request.height));
+ assert!(bm.pixels().all(|p| p[0] == 0 || p[0] == 255), "backend mask is binary");
+ let out = postprocess(fake_backend(p.working.width, p.working.height), &j.post).unwrap();
+ assert_eq!(out.dimensions(), (900, 700));
+ let PostKind::Inpaint { blend, region, .. } = &j.post.kind else { panic!() };
+ let mut changed_inside = false;
+ for (x, y, px) in out.enumerate_pixels() {
+ let inside = x >= region.x && x < region.right() && y >= region.y && y < region.bottom();
+ let b = if inside { blend.get_pixel(x - region.x, y - region.y)[0] } else { 0 };
+ if b == 0 {
+ assert_eq!(px, img.pixels.get_pixel(x, y), "pixel {x},{y} changed outside mask");
+ } else if b == 255 {
+ changed_inside |= px != img.pixels.get_pixel(x, y);
+ }
+ }
+ assert!(changed_inside);
+ }
+
+ #[test]
+ fn outpaint_preserves_original_region() {
+ let img = photo(800, 600);
+ let mut r = req("more beach");
+ r.outpaint = Some(OutpaintSpec { left: 0.0, right: 50.0, top: 0.0, bottom: 0.0, units: ExpansionUnits::Percent });
+ let p = plan(&r, &PlanInputs { image_sizes: vec![img.size()], vram_total_mib: Some(16303), ..Default::default() }, &RecommendedSettings::default()).unwrap();
+ assert_eq!(p.output, Size::new(1200, 600));
+ let j = prepare(&p, &r.prompt, 1, std::slice::from_ref(&img), None, &BackendOptions::default()).unwrap();
+ assert!(j.request.prompt.contains("more beach"));
+ let mask = imaging::decode_image(&b64_decode(j.request.mask_image.as_ref().unwrap()).unwrap()).unwrap().pixels;
+ let op = p.outpaint.unwrap();
+ let r0 = op.source_rect_working;
+ assert_eq!(mask.get_pixel(r0.x + 5, r0.y + 5)[0], 0, "original area kept");
+ assert_eq!(mask.get_pixel(op.working.canvas.width - 2, 10)[0], 255, "new area generated");
+ let out = postprocess(fake_backend(p.working.width, p.working.height), &j.post).unwrap();
+ assert_eq!(out.dimensions(), (1200, 600));
+ // Everything left of the feather band equals the source exactly.
+ let PostKind::Outpaint { feather, .. } = j.post.kind else { panic!() };
+ for y in 0..600 {
+ for x in 0..(800 - feather) {
+ assert_eq!(out.get_pixel(x, y), img.pixels.get_pixel(x, y));
+ }
+ }
+ assert_eq!(out.get_pixel(1150, 300), &Rgba([9, 99, 199, 255]));
+ }
+
+ #[test]
+ fn alpha_noise_is_flattened_unless_transparency_intended() {
+ let r = req("a red fox");
+ let p = plan(&r, &PlanInputs { vram_total_mib: Some(16303), ..Default::default() }, &RecommendedSettings::default()).unwrap();
+ let j = prepare(&p, &r.prompt, 5, &[], None, &BackendOptions::default()).unwrap();
+ let mut noisy = fake_backend(1024, 1024);
+ noisy.put_pixel(3, 3, Rgba([1, 2, 3, 250]));
+ let out = postprocess(noisy.clone(), &j.post).unwrap();
+ assert!(out.pixels().all(|p| p[3] == 255));
+ let r = req("a red fox on a transparent background");
+ let j = prepare(&p, &r.prompt, 5, &[], None, &BackendOptions::default()).unwrap();
+ assert!(j.request.prompt.starts_with("This is an RGBA image with transparency. a red fox on a transparent background."));
+ assert!(j.request.prompt.ends_with("the background is transparent."));
+ let out = postprocess(noisy, &j.post).unwrap();
+ assert_eq!(out.get_pixel(3, 3)[3], 250);
+ }
+
+ #[test]
+ fn generate_request_has_no_images() {
+ let r = req("a red fox");
+ let p = plan(&r, &PlanInputs { vram_total_mib: Some(16303), ..Default::default() }, &RecommendedSettings::default()).unwrap();
+ let j = prepare(&p, &r.prompt, 5, &[], None, &BackendOptions::default()).unwrap();
+ let v = serde_json::to_value(&j.request).unwrap();
+ assert!(v.get("ref_images").is_none() && v.get("init_image").is_none());
+ assert_eq!(v["seed"], 5);
+ assert_eq!(v["width"], 1024);
+ let out = postprocess(fake_backend(1024, 1024), &j.post).unwrap();
+ assert_eq!(out.dimensions(), (1024, 1024));
+ }
+
+ #[test]
+ fn transparent_source_alpha_survives_inpaint() {
+ let mut img = photo(400, 400);
+ for y in 0..50 {
+ for x in 0..50 {
+ img.pixels.put_pixel(x, y, Rgba([0, 0, 0, 0]));
+ }
+ }
+ img.has_transparency = true;
+ let mut m = GrayImage::new(400, 400);
+ for y in 200..260 {
+ for x in 200..260 {
+ m.put_pixel(x, y, Luma([255]));
+ }
+ }
+ let mut r = req("add a star");
+ r.mask = Some("m".into());
+ let inputs = PlanInputs { image_sizes: vec![img.size()], mask: Some((Size::new(400, 400), imaging::mask_bbox(&m, 127), 0.02)), vram_total_mib: Some(16303), ..Default::default() };
+ let p = plan(&r, &inputs, &RecommendedSettings::default()).unwrap();
+ let j = prepare(&p, &r.prompt, 1, std::slice::from_ref(&img), Some(&m), &BackendOptions::default()).unwrap();
+ let out = postprocess(fake_backend(p.working.width, p.working.height), &j.post).unwrap();
+ assert_eq!(out.get_pixel(10, 10)[3], 0, "transparent corner untouched");
+ }
+}
diff --git a/crates/qls-core/src/planner.rs b/crates/qls-core/src/planner.rs
new file mode 100644
index 0000000..de0d2cd
--- /dev/null
+++ b/crates/qls-core/src/planner.rs
@@ -0,0 +1,1370 @@
+//! Turns a user-level request ("change the car to black", one image, Balanced) into a
+//! concrete generation plan: mode, working resolution, steps/CFG, memory mitigations.
+//! Pure functions only — image sizes are passed in — so behavior is fully testable.
+
+use std::sync::LazyLock;
+
+use regex::Regex;
+use serde::{Deserialize, Serialize};
+
+use crate::config::{RecommendedSettings, RefineMode};
+use crate::error::{AppError, ErrorCode};
+use crate::geometry::{
+ self, CanvasLimits, Expansion, ExpansionUnits, OutpaintPlan, Rect, Size, WorkingCanvas, aspect_label, dims_for_area,
+ expansion_for_aspect, expansion_to_pixels, plan_outpaint, plan_working_canvas,
+};
+
+// ---------------------------------------------------------------------------------------
+// Request (stable, user-level)
+// ---------------------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "snake_case")]
+pub enum Mode {
+ #[default]
+ Auto,
+ Generate,
+ Edit,
+ Inpaint,
+ Outpaint,
+ MultiReference,
+ Upscale,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ResolvedMode {
+ Generate,
+ Edit,
+ Inpaint,
+ Outpaint,
+ MultiReference,
+ Upscale,
+}
+
+impl ResolvedMode {
+ pub fn label(&self) -> &'static str {
+ match self {
+ Self::Generate => "Text to Image",
+ Self::Edit => "Edit Image",
+ Self::Inpaint => "Inpainting",
+ Self::Outpaint => "Outpainting",
+ Self::MultiReference => "Multi-reference",
+ Self::Upscale => "Upscale",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "snake_case")]
+pub enum UpscaleMethod {
+ /// ESRGAN only (seconds).
+ #[default]
+ Quick,
+ /// Low-denoise img2img refine at up to ~2K, then ESRGAN to the target.
+ Detailed,
+}
+
+/// Target of an upscale job. Exact `width`+`height` win, then one side (aspect kept),
+/// then `scale`; the default is 2x.
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
+pub struct UpscaleSpec {
+ #[serde(default)]
+ pub method: UpscaleMethod,
+ #[serde(default)]
+ pub scale: Option<f64>,
+ #[serde(default)]
+ pub width: Option<u32>,
+ #[serde(default)]
+ pub height: Option<u32>,
+}
+
+/// Largest upscale result: 8192 px per side (the ESRGAN endpoint's limit) and ~40 MP.
+pub const MAX_UPSCALE_SIDE: u32 = 8192;
+pub const MAX_UPSCALE_AREA: u64 = 40_000_000;
+/// Denoise of the Detailed upscale refine (img2img).
+pub const DETAILED_DENOISE: f32 = 0.3;
+/// Prompt for refining images that have no usable description (inputs, edit results).
+pub const UPSCALE_PROMPT: &str = "A sharp, highly detailed, high-quality image with clean fine textures.";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "snake_case")]
+pub enum Quality {
+ Fast,
+ #[default]
+ Balanced,
+ Quality,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
+pub enum ResolutionMode {
+ #[default]
+ #[serde(rename = "auto")]
+ Auto,
+ #[serde(rename = "source")]
+ Source,
+ #[serde(rename = "1k")]
+ K1,
+ #[serde(rename = "1.5k")]
+ K15,
+ #[serde(rename = "2k")]
+ K2,
+ #[serde(rename = "custom")]
+ Custom,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "lowercase")]
+pub enum OutputFormat {
+ #[default]
+ Png,
+ Jpeg,
+ Webp,
+}
+
+impl OutputFormat {
+ pub fn ext(&self) -> &'static str {
+ match self {
+ Self::Png => "png",
+ Self::Jpeg => "jpg",
+ Self::Webp => "webp",
+ }
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize, Default)]
+pub struct OutpaintSpec {
+ #[serde(default)]
+ pub left: f64,
+ #[serde(default)]
+ pub right: f64,
+ #[serde(default)]
+ pub top: f64,
+ #[serde(default)]
+ pub bottom: f64,
+ #[serde(default)]
+ pub units: ExpansionUnits,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
+#[serde(default)]
+pub struct AdvancedOptions {
+ pub steps: Option<u32>,
+ pub cfg: Option<f32>,
+ pub sampler: Option<String>,
+ pub scheduler: Option<String>,
+ /// Edit/inpaint denoising strength (0..1).
+ pub strength: Option<f32>,
+ pub batch_count: Option<u32>,
+ pub output_format: Option<OutputFormat>,
+ /// None = automatic.
+ pub vae_tiling: Option<bool>,
+ pub flow_shift: Option<f32>,
+ /// Effort of a Detailed upscale (Fast or Best); None = the app setting.
+ pub refine: Option<RefineMode>,
+ /// Keep the HDR gain map of a HEIC source (Ultra HDR JPEG output); None = on.
+ pub hdr: Option<bool>,
+}
+
+fn default_true() -> bool {
+ true
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
+pub struct GenerationRequest {
+ pub prompt: String,
+ #[serde(default)]
+ pub negative_prompt: Option<String>,
+ #[serde(default)]
+ pub mode: Mode,
+ /// Ordered image sources: "input:<id>", "gen:<id>" or an absolute file path.
+ #[serde(default)]
+ pub images: Vec<String>,
+ #[serde(default)]
+ pub mask: Option<String>,
+ #[serde(default)]
+ pub outpaint: Option<OutpaintSpec>,
+ #[serde(default)]
+ pub quality: Quality,
+ #[serde(default)]
+ pub resolution: ResolutionMode,
+ /// "auto", "1:1", "16:9", ... (text-to-image, edit, multi-reference; image 1's shape when unset).
+ #[serde(default)]
+ pub aspect_ratio: Option<String>,
+ #[serde(default)]
+ pub width: Option<u32>,
+ #[serde(default)]
+ pub height: Option<u32>,
+ #[serde(default)]
+ pub seed: Option<i64>,
+ #[serde(default = "default_true")]
+ pub preserve_dimensions: bool,
+ #[serde(default)]
+ pub advanced: AdvancedOptions,
+ #[serde(default)]
+ pub output_path: Option<String>,
+ #[serde(default)]
+ pub client: Option<String>,
+ #[serde(default)]
+ pub parent_id: Option<String>,
+ /// Target for `mode: upscale`.
+ #[serde(default)]
+ pub upscale: Option<UpscaleSpec>,
+}
+
+// ---------------------------------------------------------------------------------------
+// Plan
+// ---------------------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct RefPlan {
+ pub index: usize,
+ pub source: Size,
+ pub canvas: WorkingCanvas,
+}
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
+pub struct UpscalePlan {
+ pub method: UpscaleMethod,
+ pub source: Size,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct Plan {
+ pub mode: ResolvedMode,
+ pub auto_mode: bool,
+ pub mode_reason: String,
+ /// Delivered image size.
+ pub output: Size,
+ /// Model canvas size (multiple of 32).
+ pub working: Size,
+ /// Content area inside `working` that maps to the output (rest is alignment padding).
+ pub content: Rect,
+ pub steps: u32,
+ pub cfg: f32,
+ pub sampler: String,
+ pub scheduler: Option<String>,
+ pub strength: Option<f32>,
+ pub batch_count: u32,
+ pub flow_shift: Option<f32>,
+ pub vae_tiling: bool,
+ pub output_format: OutputFormat,
+ pub negative_prompt: String,
+ pub references: Vec<RefPlan>,
+ pub outpaint: Option<OutpaintPlan>,
+ /// Region of the source sent to the model for inpainting.
+ pub inpaint_region: Option<Rect>,
+ pub quality: Quality,
+ pub resolution: ResolutionMode,
+ pub aspect_label: String,
+ /// User-visible notes such as "Optimized for available VRAM".
+ pub notes: Vec<String>,
+ pub optimized_for_vram: bool,
+ pub estimated_seconds: f32,
+ /// EasyCache threshold (Detailed upscale only); None = off.
+ #[serde(default)]
+ pub cache_threshold: Option<f32>,
+ /// ESRGAN model used to enlarge the result; None = Lanczos.
+ #[serde(default)]
+ pub upscaler: Option<String>,
+ #[serde(default)]
+ pub upscale: Option<UpscalePlan>,
+}
+
+/// Facts about inputs and the environment, measured before planning.
+#[derive(Debug, Clone, Default)]
+pub struct PlanInputs {
+ pub image_sizes: Vec<Size>,
+ /// (mask size, bounding box of painted area, coverage 0..1)
+ pub mask: Option<(Size, Option<Rect>, f64)>,
+ pub vram_total_mib: Option<u64>,
+ /// ESRGAN model available to the server (`AppConfig::upscaler_file`).
+ pub upscaler: Option<String>,
+ /// App default effort of a Detailed upscale (per-job override in `AdvancedOptions::refine`).
+ pub refine: RefineMode,
+ /// The server was launched with `--vae-tiling` (tiles every decode by default).
+ pub server_vae_tiling: bool,
+ /// SageAttention is enabled (faster steps; used for estimates only).
+ pub sage_attention: bool,
+}
+
+// ---------------------------------------------------------------------------------------
+// Prompt understanding (deliberately small and predictable)
+// ---------------------------------------------------------------------------------------
+
+static RATIO_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\b(\d{1,2})\s*:\s*(\d{1,2})\b").unwrap());
+static DIMS_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\b(\d{3,4})\s*[x×]\s*(\d{3,4})\b").unwrap());
+static OUTPAINT_RE: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"(?i)\b(extend|expand|outpaint|uncrop|zoom(?:ed)? out|widen|make (?:it|the image) (?:wider|taller))\b").unwrap());
+static AMOUNT_PCT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)\b(\d{1,3})\s*(%|percent)").unwrap());
+static AMOUNT_PX_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)\b(\d{2,4})\s*(px|pixels?)\b").unwrap());
+
+#[derive(Debug, Clone, PartialEq)]
+pub enum AspectHint {
+ Ratio(f64, String),
+ Dimensions(u32, u32),
+}
+
+/// Aspect ratio implied by a text prompt, if any.
+pub fn aspect_hint(prompt: &str) -> Option<AspectHint> {
+ if let Some(c) = DIMS_RE.captures(prompt) {
+ let (w, h): (u32, u32) = (c[1].parse().ok()?, c[2].parse().ok()?);
+ if (64..=4096).contains(&w) && (64..=4096).contains(&h) {
+ return Some(AspectHint::Dimensions(w, h));
+ }
+ }
+ // Only well-known ratios, so times like "10:30" are not mistaken for aspect ratios.
+ const KNOWN: &[(u32, u32)] = &[(1, 1), (4, 3), (3, 4), (3, 2), (2, 3), (16, 9), (9, 16), (21, 9), (9, 21), (5, 4), (4, 5), (2, 1), (1, 2), (16, 10), (10, 16)];
+ for c in RATIO_RE.captures_iter(prompt) {
+ let (a, b): (u32, u32) = (c[1].parse().ok()?, c[2].parse().ok()?);
+ if KNOWN.contains(&(a, b)) {
+ return Some(AspectHint::Ratio(a as f64 / b as f64, format!("{a}:{b}")));
+ }
+ }
+ let p = prompt.to_lowercase();
+ let has = |words: &[&str]| words.iter().any(|w| p.contains(w));
+ if has(&["panorama", "panoramic", "ultrawide", "ultra-wide", "cinematic banner"]) {
+ return Some(AspectHint::Ratio(21.0 / 9.0, "21:9".into()));
+ }
+ if has(&["hero image", "hero banner", "banner", "landscape", "widescreen", "wide shot", "desktop wallpaper", "youtube thumbnail", "cinematic"]) {
+ return Some(AspectHint::Ratio(16.0 / 9.0, "16:9".into()));
+ }
+ if has(&["phone wallpaper", "mobile wallpaper", "instagram story", "story format", "vertical video", "tiktok", "smartphone wallpaper"]) {
+ return Some(AspectHint::Ratio(9.0 / 16.0, "9:16".into()));
+ }
+ if has(&["portrait", "poster", "full-body", "full body", "book cover", "vertical"]) {
+ return Some(AspectHint::Ratio(3.0 / 4.0, "3:4".into()));
+ }
+ if has(&["square", "profile picture", "avatar", "app icon", "icon", "logo", "instagram post"]) {
+ return Some(AspectHint::Ratio(1.0, "1:1".into()));
+ }
+ None
+}
+
+pub fn parse_aspect(s: &str) -> Option<(f64, String)> {
+ let s = s.trim();
+ if s.eq_ignore_ascii_case("auto") || s.is_empty() {
+ return None;
+ }
+ let (a, b) = s.split_once([':', 'x', '/'])?;
+ let (a, b): (f64, f64) = (a.trim().parse().ok()?, b.trim().parse().ok()?);
+ (a > 0.0 && b > 0.0 && (a / b) > 0.124 && (a / b) < 8.1).then(|| (a / b, s.to_string()))
+}
+
+/// Outpaint intent expressed in words ("extend to the left", "make it 16:9 landscape").
+pub fn outpaint_intent(prompt: &str, source: Size) -> Option<Expansion> {
+ if !OUTPAINT_RE.is_match(prompt) {
+ return None;
+ }
+ let p = prompt.to_lowercase();
+ let amount_pct = AMOUNT_PCT_RE.captures(&p).and_then(|c| c[1].parse::<f64>().ok()).filter(|v| *v > 0.0 && *v <= 200.0);
+ let amount_px = AMOUNT_PX_RE.captures(&p).and_then(|c| c[1].parse::<f64>().ok());
+ let side = |pct_base: u32| -> u32 {
+ if let Some(px) = amount_px {
+ return px as u32;
+ }
+ (pct_base as f64 * amount_pct.unwrap_or(25.0) / 100.0).round() as u32
+ };
+ let word = |w: &str| Regex::new(&format!(r"\b{w}\b")).map(|r| r.is_match(&p)).unwrap_or(false);
+ let mut e = Expansion::default();
+ if word("left") {
+ e.left = side(source.width);
+ }
+ if word("right") {
+ e.right = side(source.width);
+ }
+ if word("top") || word("up") || word("upwards") || word("above") || word("sky") {
+ e.top = side(source.height);
+ }
+ if word("bottom") || word("down") || word("downwards") || word("below") {
+ e.bottom = side(source.height);
+ }
+ if word("sides") || word("horizontally") || word("wider") || word("widen") {
+ e.left = side(source.width);
+ e.right = side(source.width);
+ }
+ if word("vertically") || word("taller") {
+ e.top = side(source.height);
+ e.bottom = side(source.height);
+ }
+ if e.is_zero() {
+ if let Some(AspectHint::Ratio(r, _)) = aspect_hint(prompt) {
+ let x = expansion_for_aspect(source, r);
+ if !x.is_zero() {
+ return Some(x);
+ }
+ }
+ if p.contains("landscape") {
+ return Some(expansion_for_aspect(source, 16.0 / 9.0)).filter(|x| !x.is_zero());
+ }
+ if p.contains("portrait") {
+ return Some(expansion_for_aspect(source, 9.0 / 16.0)).filter(|x| !x.is_zero());
+ }
+ // "zoom out" / "expand the image": every side.
+ let h = side(source.width);
+ let v = side(source.height);
+ e = Expansion { left: h, right: h, top: v, bottom: v };
+ }
+ Some(e)
+}
+
+// ---------------------------------------------------------------------------------------
+// Resolution and memory policy
+// ---------------------------------------------------------------------------------------
+
+/// Official Qwen-Image 2.1 native 2K buckets (model card).
+const OFFICIAL_2K: &[(f64, u32, u32)] = &[
+ (1.0, 2048, 2048),
+ (4.0 / 3.0, 2400, 1792),
+ (3.0 / 4.0, 1792, 2400),
+ (3.0 / 2.0, 2528, 1696),
+ (2.0 / 3.0, 1696, 2528),
+ (16.0 / 9.0, 2752, 1536),
+ (9.0 / 16.0, 1536, 2752),
+];
+
+/// Output size for an aspect ratio and pixel area: the official 2K bucket when one matches,
+/// else the closest aligned size.
+fn size_for_aspect(aspect: f64, area: u64, rec: &RecommendedSettings) -> Size {
+ match OFFICIAL_2K.iter().find(|(a, w, h)| (a / aspect - 1.0).abs() < 0.01 && (*w as u64 * *h as u64) as f64 <= area as f64 * 1.02 && area >= 2048 * 2048) {
+ Some((_, w, h)) => Size::new(*w, *h),
+ None => dims_for_area(aspect, area as f64, rec.align, 256, rec.max_side),
+ }
+}
+
+pub fn resolution_area(mode: ResolutionMode, quality: Quality, rec: &RecommendedSettings) -> Option<u64> {
+ match mode {
+ ResolutionMode::Auto => Some(match quality {
+ Quality::Fast => rec.area_fast,
+ Quality::Balanced => rec.area_balanced,
+ Quality::Quality => rec.area_quality,
+ }),
+ ResolutionMode::K1 => Some(1024 * 1024),
+ ResolutionMode::K15 => Some(1536 * 1536),
+ ResolutionMode::K2 => Some(2048 * 2048),
+ ResolutionMode::Source | ResolutionMode::Custom => None,
+ }
+}
+
+/// Transformer token budget for the whole sequence (target + references), from total
+/// VRAM. 16384 tokens = one 2048² image, verified to run on a 16 GB card.
+pub fn token_budget(vram_total_mib: Option<u64>) -> u64 {
+ let Some(mib) = vram_total_mib else { return 12_288 };
+ let gib = mib as f64 / 1024.0;
+ // Anchored on measurement: a 16 GB card (≈15.9 GiB reported) runs 2048² text-to-image.
+ let tokens = if gib < 15.0 {
+ (gib - 2.0) / 13.0 * 16_384.0
+ } else if gib <= 20.0 {
+ 16_384.0
+ } else {
+ 16_384.0 + (gib - 20.0) * 1_024.0
+ };
+ tokens.clamp(4_096.0, 24_576.0) as u64
+}
+
+pub const PIXELS_PER_TOKEN: u64 = 256; // 8x VAE downscale, 2x2 patches
+
+/// Seconds per sampling step, from RTX 5070 Ti measurements at CFG 6 (two model passes per
+/// step): 1 MP ≈ 2.0 s (1.63 s with SageAttention), 2048x1152 ≈ 5.6 s (3.8 s with
+/// SageAttention). CFG 1 runs one pass, so half of that (to re-measure).
+fn step_seconds(tokens: f32, ref_tokens: f32, sage: bool, cfg: f32) -> f32 {
+ let x = tokens / 4096.0;
+ let base = if sage { 1.6 * x.powf(1.1) } else { 2.0 * x.powf(1.4) };
+ let passes = if uses_guidance(cfg) { 1.0 } else { 0.5 };
+ base * passes * (1.0 + 0.12 * ref_tokens / tokens.max(1.0))
+}
+
+/// sd-server runs the unconditional pass whenever CFG differs from 1 (diffusion_engine.cpp,
+/// commit 3f8527a); only then is the negative prompt used.
+pub fn uses_guidance(cfg: f32) -> bool {
+ (cfg - 1.0).abs() > 1e-4
+}
+
+/// One ESRGAN x4 pass over `input` pixels (~10 s per MP incl. model load, measured).
+pub fn esrgan_seconds(input: u64) -> f32 {
+ 1.0 + 9.0 * input as f32 / 1_048_576.0
+}
+
+/// VAE decode with 768 px tiles: ~1.3 s at 1 MP, ~3.9 s at 2048x1152.
+fn decode_seconds(area: u64) -> f32 {
+ 1.0 + 1.25 * area as f32 / 1_048_576.0
+}
+
+/// Rough wall-clock estimate of one diffusion job (single pass), excluding enlargement.
+pub fn estimate_seconds(working: Size, refs: &[RefPlan], steps: u32, batch: u32, cache: bool, sage: bool, cfg: f32) -> f32 {
+ let tokens = |s: Size| (s.area() / PIXELS_PER_TOKEN) as f32;
+ let ref_tokens: f32 = refs.iter().map(|r| tokens(r.canvas.canvas)).sum();
+ let encode = 4.0 + ref_tokens / 4096.0 * 3.0;
+ // EasyCache skipped ~1/3 of the refine steps in the 2K bench.
+ let cache_factor = if cache { 0.7 } else { 1.0 };
+ let t = encode + step_seconds(tokens(working), ref_tokens, sage, cfg) * steps as f32 * cache_factor;
+ (t + decode_seconds(working.area())) * batch as f32
+}
+
+fn steps_for(q: Quality, rec: &RecommendedSettings) -> u32 {
+ match q {
+ Quality::Fast => rec.steps_fast,
+ Quality::Balanced => rec.steps_balanced,
+ Quality::Quality => rec.steps_quality,
+ }
+}
+
+fn limits(max_area: u64, rec: &RecommendedSettings) -> CanvasLimits {
+ CanvasLimits { max_area, align: rec.align, max_side: rec.max_side, ..Default::default() }
+}
+
+/// Exact upscale target for a source size.
+pub fn upscale_target(src: Size, spec: &UpscaleSpec) -> Result<Size, AppError> {
+ let aspect = src.aspect();
+ let t = match (spec.width, spec.height) {
+ (Some(w), Some(h)) => Size::new(w, h),
+ (Some(w), None) => Size::new(w, ((w as f64 / aspect).round() as u32).max(1)),
+ (None, Some(h)) => Size::new(((h as f64 * aspect).round() as u32).max(1), h),
+ (None, None) => {
+ let s = spec.scale.unwrap_or(2.0);
+ if !(s.is_finite() && s > 0.0) {
+ return Err(AppError::invalid("The upscale factor must be a positive number."));
+ }
+ Size::new(((src.width as f64 * s).round() as u32).max(1), ((src.height as f64 * s).round() as u32).max(1))
+ }
+ };
+ if t.width < 64 || t.height < 64 || t.width > MAX_UPSCALE_SIDE || t.height > MAX_UPSCALE_SIDE {
+ return Err(AppError::invalid(format!("The upscaled size must be between 64 and {MAX_UPSCALE_SIDE} pixels per side.")));
+ }
+ if t.area() > MAX_UPSCALE_AREA {
+ return Err(AppError::invalid(format!("{}×{} is too large; the limit is about 40 megapixels.", t.width, t.height)));
+ }
+ Ok(t)
+}
+
+fn detect_mode(req: &GenerationRequest, inputs: &PlanInputs) -> Result<(ResolvedMode, bool, String), AppError> {
+ let n = inputs.image_sizes.len();
+ let has_mask = req.mask.is_some() && inputs.mask.as_ref().map(|m| m.2 > 0.0).unwrap_or(false);
+ let has_outpaint = req.outpaint.map(|o| o.left > 0.0 || o.right > 0.0 || o.top > 0.0 || o.bottom > 0.0).unwrap_or(false);
+ let need = |ok: bool, msg: &str| if ok { Ok(()) } else { Err(AppError::invalid(msg)) };
+ let explicit = |m: ResolvedMode, why: &str| Ok((m, false, why.to_string()));
+ match req.mode {
+ Mode::Generate => explicit(ResolvedMode::Generate, "Selected"),
+ Mode::Edit => {
+ need(n >= 1, "Add an image to edit.")?;
+ if n >= 2 { explicit(ResolvedMode::MultiReference, "Selected (several images)") } else { explicit(ResolvedMode::Edit, "Selected") }
+ }
+ Mode::MultiReference => {
+ need(n >= 1, "Add at least one reference image.")?;
+ explicit(ResolvedMode::MultiReference, "Selected")
+ }
+ Mode::Inpaint => {
+ need(n >= 1, "Add an image to inpaint.")?;
+ need(has_mask, "Paint the area to change first.")?;
+ explicit(ResolvedMode::Inpaint, "Selected")
+ }
+ Mode::Outpaint => {
+ need(n >= 1, "Add an image to expand.")?;
+ explicit(ResolvedMode::Outpaint, "Selected")
+ }
+ Mode::Upscale => {
+ need(n >= 1, "Choose an image to upscale.")?;
+ explicit(ResolvedMode::Upscale, "Selected")
+ }
+ Mode::Auto => {
+ if n == 0 {
+ return Ok((ResolvedMode::Generate, true, "No image provided".into()));
+ }
+ if has_mask {
+ return Ok((ResolvedMode::Inpaint, true, "A mask was painted".into()));
+ }
+ if has_outpaint {
+ return Ok((ResolvedMode::Outpaint, true, "Expansion requested".into()));
+ }
+ if n >= 2 {
+ return Ok((ResolvedMode::MultiReference, true, format!("{n} reference images")));
+ }
+ if outpaint_intent(&req.prompt, inputs.image_sizes[0]).is_some() {
+ return Ok((ResolvedMode::Outpaint, true, "The prompt asks to extend the image".into()));
+ }
+ Ok((ResolvedMode::Edit, true, "An image was provided".into()))
+ }
+ }
+}
+
+/// Reference canvas whose aligned area never exceeds `max_canvas_area`: the backend
+/// resizes any reference larger than the output area (by area, with rounding that can
+/// slightly distort aspect), so staying at or below it keeps references untouched.
+fn ref_canvas(src: Size, max_canvas_area: u64, rec: &RecommendedSettings) -> WorkingCanvas {
+ let mut area = src.area().min(max_canvas_area);
+ loop {
+ let c = plan_working_canvas(src, &CanvasLimits { min_side: 64, ..limits(area, rec) });
+ if c.canvas.area() <= max_canvas_area || area < 64 * 64 {
+ return c;
+ }
+ area = (area as f64 * 0.97) as u64;
+ }
+}
+
+/// Produces the generation plan. `rec` comes from the active model profile.
+pub fn plan(req: &GenerationRequest, inputs: &PlanInputs, rec: &RecommendedSettings) -> Result<Plan, AppError> {
+ if req.prompt.trim().is_empty() && req.mode != Mode::Upscale {
+ return Err(AppError::invalid("Describe what to generate or change."));
+ }
+ if req.prompt.len() > 8000 {
+ return Err(AppError::invalid("The prompt is too long (8000 characters max)."));
+ }
+ if inputs.image_sizes.len() > rec.max_references as usize {
+ return Err(AppError::invalid(format!("Use at most {} reference images.", rec.max_references)));
+ }
+ let (mode, auto_mode, mode_reason) = detect_mode(req, inputs)?;
+ let default_cfg = if mode == ResolvedMode::Generate { rec.cfg } else { rec.cfg_edit };
+ let cfg = req.advanced.cfg.unwrap_or(default_cfg).clamp(0.0, 30.0);
+ let mut notes = Vec::new();
+ let budget_tokens = token_budget(inputs.vram_total_mib);
+ let budget_area = budget_tokens * PIXELS_PER_TOKEN;
+ let tier_area = resolution_area(req.resolution, req.quality, rec);
+ let adv = &req.advanced;
+ let mut steps = adv.steps.unwrap_or_else(|| steps_for(req.quality, rec)).clamp(1, 150);
+ let batch_count = if mode == ResolvedMode::Upscale { 1 } else { adv.batch_count.unwrap_or(1).clamp(1, 8) };
+ let mut optimized = false;
+ // Diffusion always runs in one pass; larger outputs are enlarged with the upscaler
+ // model (user A/B test, 2026-10-06: the two-pass refine made results worse).
+ // `refine` only sets the effort of a Detailed upscale.
+ let refine = adv.refine.unwrap_or(inputs.refine);
+ let mut upscale = None;
+
+ // Shared: cap an area by the VRAM budget given n reference images of similar size.
+ let mut cap_for_refs = |wanted: u64, n_refs: usize, notes: &mut Vec<String>| -> u64 {
+ let allowed = budget_area / (1 + n_refs as u64);
+ if wanted > allowed {
+ optimized = true;
+ notes.push("Resolution reduced to fit available VRAM.".into());
+ allowed
+ } else {
+ wanted
+ }
+ };
+
+ // Edit/combine: largest area `a <= wanted` with `a + Σ min(ref_i, a)` within the budget.
+ let cap_for_sources = |wanted: u64, refs: &[Size], notes: &mut Vec<String>| -> u64 {
+ let fits = |a: u64| a + refs.iter().map(|r| r.area().min(a)).sum::<u64>() <= budget_area;
+ if fits(wanted) {
+ return wanted;
+ }
+ let (mut lo, mut hi) = (budget_area / (1 + refs.len() as u64), wanted);
+ while hi - lo > 1024 {
+ let mid = (lo + hi) / 2;
+ if fits(mid) { lo = mid } else { hi = mid }
+ }
+ notes.push("Resolution reduced to fit available VRAM.".into());
+ lo
+ };
+
+ let mut sources_reduced = false;
+ let mut references = Vec::new();
+ let mut outpaint = None;
+ let mut inpaint_region = None;
+ let mut strength = None;
+ let output: Size;
+ let working: WorkingCanvas;
+
+ match mode {
+ ResolvedMode::Generate => {
+ let explicit_dims = match (req.width, req.height) {
+ (Some(w), Some(h)) => Some((w, h)),
+ _ => match req.aspect_ratio.as_deref().and_then(parse_aspect) {
+ Some(_) => None,
+ None => match aspect_hint(&req.prompt) {
+ Some(AspectHint::Dimensions(w, h)) if req.aspect_ratio.as_deref().map(|a| a == "auto").unwrap_or(true) => Some((w, h)),
+ _ => None,
+ },
+ },
+ };
+ if let Some((w, h)) = explicit_dims {
+ if !(64..=rec.max_side).contains(&w) || !(64..=rec.max_side).contains(&h) {
+ return Err(AppError::invalid(format!("Width and height must be between 64 and {}.", rec.max_side)));
+ }
+ let src = Size::new(w, h);
+ // Above the VRAM budget: render smaller, then enlarge to the exact size.
+ let area = cap_for_refs(src.area(), 0, &mut notes);
+ working = plan_working_canvas(src, &CanvasLimits { min_side: 64, ..limits(area, rec) });
+ output = src;
+ } else {
+ let (aspect, _label) = req
+ .aspect_ratio
+ .as_deref()
+ .and_then(parse_aspect)
+ .or_else(|| match aspect_hint(&req.prompt) {
+ Some(AspectHint::Ratio(r, l)) => Some((r, l)),
+ _ => None,
+ })
+ .unwrap_or((1.0, "1:1".into()));
+ let wanted = tier_area.unwrap_or(rec.area_balanced);
+ let area = cap_for_refs(wanted, 0, &mut notes);
+ let size = size_for_aspect(aspect, area, rec);
+ working = plan_working_canvas(size, &limits(size.area(), rec));
+ output = size;
+ }
+ }
+ ResolvedMode::Edit | ResolvedMode::MultiReference => {
+ let first = inputs.image_sizes[0];
+ // Output shape: the chosen aspect ratio, else image 1's.
+ let chosen_aspect = req.aspect_ratio.as_deref().and_then(parse_aspect).map(|(a, _)| a);
+ let aspect = chosen_aspect.unwrap_or(first.width as f64 / first.height as f64);
+ let tier = matches!(req.resolution, ResolutionMode::K1 | ResolutionMode::K15 | ResolutionMode::K2);
+ let target = match (req.width, req.height) {
+ (Some(w), Some(h)) => {
+ if !(64..=rec.max_side).contains(&w) || !(64..=rec.max_side).contains(&h) {
+ return Err(AppError::invalid(format!("Width and height must be between 64 and {}.", rec.max_side)));
+ }
+ Size::new(w, h)
+ }
+ // An explicit 1K/1.5K/2K sets the output size whatever the sources' sizes, so a
+ // small photo can be edited into a larger image.
+ _ if tier => size_for_aspect(aspect, tier_area.unwrap(), rec),
+ _ => match chosen_aspect {
+ Some(a) => dims_for_area(a, first.area() as f64, 1, 64, 16384),
+ None => first,
+ },
+ };
+ // Auto renders at most the quality tier (enlarging larger outputs afterwards);
+ // explicit sizes ask for the whole output.
+ let wanted = match req.resolution {
+ ResolutionMode::Auto => tier_area.unwrap().min(target.area().max(256 * 256)),
+ _ => target.area(),
+ };
+ // Target and references share the token budget; a reference never takes more
+ // than the target's area (see `ref_canvas`), so small references leave room.
+ let area = cap_for_sources(wanted, &inputs.image_sizes, &mut notes);
+ sources_reduced = area < wanted;
+ working = plan_working_canvas(target, &limits(area, rec));
+ for (i, s) in inputs.image_sizes.iter().enumerate() {
+ let c = if i == 0 && *s == target { working } else { ref_canvas(*s, working.canvas.area(), rec) };
+ references.push(RefPlan { index: i, source: *s, canvas: c });
+ }
+ output = if req.preserve_dimensions || tier || chosen_aspect.is_some() { target } else { working.content };
+ strength = adv.strength.map(|s| s.clamp(0.0, 1.0));
+ }
+ ResolvedMode::Upscale => {
+ let src = inputs.image_sizes[0];
+ let spec = req.upscale.unwrap_or_default();
+ output = upscale_target(src, &spec)?;
+ upscale = Some(UpscalePlan { method: spec.method, source: src });
+ match spec.method {
+ UpscaleMethod::Quick => {
+ // No diffusion: the "working" image is the source itself.
+ working = WorkingCanvas { source: src, content: src, canvas: src, content_offset: (0, 0), scale: 1.0 };
+ steps = 0;
+ }
+ UpscaleMethod::Detailed => {
+ // img2img at up to ~2K in the target's shape; the server trims the
+ // schedule by `strength`, so `steps` = effective steps / strength.
+ working = plan_working_canvas(output, &CanvasLimits { min_side: 64, ..limits(rec.hires_max_area.min(budget_area), rec) });
+ let s = adv.strength.unwrap_or(DETAILED_DENOISE).clamp(0.05, 1.0);
+ let effective = if refine == RefineMode::Best { rec.hires_steps_best } else { rec.hires_steps_fast };
+ steps = adv.steps.unwrap_or_else(|| (effective as f32 / s).ceil() as u32).clamp(1, 150);
+ strength = Some(s);
+ references.push(RefPlan { index: 0, source: src, canvas: working });
+ }
+ }
+ }
+ ResolvedMode::Inpaint => {
+ let src = inputs.image_sizes[0];
+ let (mask_size, bbox, _) = inputs.mask.ok_or_else(|| AppError::invalid("Paint the area to change first."))?;
+ if mask_size != src {
+ notes.push("The mask was resized to match the image.".into());
+ }
+ let bbox = bbox.ok_or_else(|| AppError::invalid("The mask is empty. Paint the area to change."))?;
+ let sx = src.width as f64 / mask_size.width as f64;
+ let sy = src.height as f64 / mask_size.height as f64;
+ let bbox = Rect::new(
+ (bbox.x as f64 * sx) as u32,
+ (bbox.y as f64 * sy) as u32,
+ ((bbox.width as f64 * sx).ceil() as u32).max(1),
+ ((bbox.height as f64 * sy).ceil() as u32).max(1),
+ );
+ let area = cap_for_refs(tier_area.unwrap_or(src.area()), 1, &mut notes);
+ let min_ctx = ((area as f64).sqrt() * 0.75) as u32;
+ let region = geometry::inpaint_region(src, bbox, min_ctx, 0.55);
+ let l = CanvasLimits { upscale_to_area: Some(area), max_upscale: 4.0, ..limits(area, rec) };
+ working = plan_working_canvas(region.size(), &l);
+ if region.size() != src {
+ notes.push(format!("Focused on a {}×{} area around the mask.", region.width, region.height));
+ }
+ inpaint_region = Some(region);
+ output = src;
+ references.push(RefPlan { index: 0, source: region.size(), canvas: working });
+ strength = Some(adv.strength.unwrap_or(1.0).clamp(0.05, 1.0));
+ }
+ ResolvedMode::Outpaint => {
+ let src = inputs.image_sizes[0];
+ let exp = match req.outpaint {
+ Some(o) if o.left > 0.0 || o.right > 0.0 || o.top > 0.0 || o.bottom > 0.0 => {
+ expansion_to_pixels(src, o.left, o.right, o.top, o.bottom, o.units)
+ }
+ _ => outpaint_intent(&req.prompt, src).ok_or_else(|| AppError::invalid("Choose how far to expand the image."))?,
+ };
+ let final_area = Size::new(src.width + exp.left + exp.right, src.height + exp.top + exp.bottom).area();
+ let wanted = match req.resolution {
+ ResolutionMode::Source | ResolutionMode::Custom => final_area,
+ _ => tier_area.unwrap().min(final_area.max(256 * 256)),
+ };
+ let area = cap_for_refs(wanted, 1, &mut notes);
+ let p = plan_outpaint(src, exp, &limits(area, rec), 32).map_err(AppError::invalid)?;
+ working = p.working;
+ output = p.final_size;
+ references.push(RefPlan { index: 0, source: src, canvas: ref_canvas(src, p.working.canvas.area(), rec) });
+ outpaint = Some(p);
+ strength = Some(adv.strength.unwrap_or(1.0).clamp(0.05, 1.0));
+ }
+ }
+
+ optimized |= sources_reduced;
+ let quick_upscale = upscale.map(|u| u.method == UpscaleMethod::Quick).unwrap_or(false);
+ if !quick_upscale && !working.canvas.is_aligned(rec.align) {
+ return Err(AppError::new(ErrorCode::Internal, "Working size is not aligned.").detail(format!("{:?}", working.canvas)));
+ }
+ let ref_tokens: u64 = references.iter().map(|r| r.canvas.canvas.area() / PIXELS_PER_TOKEN).sum();
+ let total_area = working.canvas.area();
+ // Untiled decodes above ~1.5 MP OOM on 16 GB with the DiT resident (2K needs ~18 GB)
+ // and the backend's 256 px retry costs ~22 s.
+ let auto_tiling = total_area > 1_600_000 || (ref_tokens * PIXELS_PER_TOKEN + total_area) > 6_000_000;
+ let vae_tiling = adv.vae_tiling.unwrap_or(inputs.server_vae_tiling || auto_tiling);
+ if vae_tiling && adv.vae_tiling.is_none() && !inputs.server_vae_tiling && !quick_upscale {
+ optimized = true;
+ notes.push("Memory optimization enabled for this size.".into());
+ }
+ if (working.content.area() as f64) < output.area() as f64 * 0.98 && matches!(mode, ResolvedMode::Generate | ResolvedMode::Edit | ResolvedMode::MultiReference) {
+ notes.push(format!(
+ "Rendered at {}×{}, then enlarged to {}×{} with {}.",
+ working.content.width,
+ working.content.height,
+ output.width,
+ output.height,
+ inputs.upscaler.as_deref().unwrap_or("Lanczos")
+ ));
+ }
+ let detailed_upscale = upscale.map(|u| u.method == UpscaleMethod::Detailed).unwrap_or(false);
+ let cache_threshold = (detailed_upscale && refine != RefineMode::Best).then_some(rec.easycache_threshold);
+ // Results are enlarged with ESRGAN when the model exists (Lanczos otherwise).
+ let enlarge = output.area() as f64 > working.content.area() as f64 * 1.21;
+ // img2img only runs the last `strength` share of the schedule.
+ let sampled_steps = if detailed_upscale { (steps as f32 * strength.unwrap_or(1.0)).ceil() as u32 } else { steps };
+ let mut estimated_seconds = if quick_upscale {
+ 2.0
+ } else {
+ estimate_seconds(working.canvas, &references, sampled_steps, batch_count, cache_threshold.is_some(), inputs.sage_attention, cfg)
+ };
+ if inputs.upscaler.is_some() {
+ if enlarge || quick_upscale {
+ estimated_seconds += esrgan_seconds(working.content.area()) * batch_count as f32;
+ }
+ if detailed_upscale && working.content.area() as f64 > inputs.image_sizes[0].area() as f64 * 1.21 {
+ estimated_seconds += esrgan_seconds(inputs.image_sizes[0].area());
+ }
+ }
+ let negative_prompt = req.negative_prompt.clone().unwrap_or_else(|| rec.negative_prompt.clone());
+ if !negative_prompt.trim().is_empty() && !uses_guidance(cfg) && !quick_upscale {
+ notes.push("The negative prompt is ignored at CFG 1; raise CFG in Advanced to use it.".into());
+ }
+ Ok(Plan {
+ mode,
+ auto_mode,
+ mode_reason,
+ aspect_label: aspect_label(output),
+ output,
+ working: working.canvas,
+ content: working.content_rect(),
+ steps,
+ cfg,
+ sampler: adv.sampler.clone().filter(|s| !s.is_empty()).unwrap_or_else(|| rec.sampler.clone()),
+ scheduler: adv.scheduler.clone().filter(|s| !s.is_empty() && s != "default").or_else(|| rec.scheduler.clone()),
+ strength,
+ batch_count,
+ flow_shift: adv.flow_shift,
+ vae_tiling,
+ output_format: adv.output_format.unwrap_or_default(),
+ negative_prompt,
+ references,
+ outpaint,
+ inpaint_region,
+ quality: req.quality,
+ resolution: req.resolution,
+ notes,
+ optimized_for_vram: optimized,
+ estimated_seconds,
+ cache_threshold,
+ upscaler: inputs.upscaler.clone(),
+ upscale,
+ })
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn rec() -> RecommendedSettings {
+ RecommendedSettings::default()
+ }
+ fn req(prompt: &str) -> GenerationRequest {
+ GenerationRequest { prompt: prompt.into(), preserve_dimensions: true, ..Default::default() }
+ }
+ fn inputs(sizes: &[(u32, u32)]) -> PlanInputs {
+ PlanInputs { image_sizes: sizes.iter().map(|(w, h)| Size::new(*w, *h)).collect(), mask: None, vram_total_mib: Some(16303), ..Default::default() }
+ }
+
+ #[test]
+ fn text_to_image_defaults() {
+ let p = plan(&req("a lighthouse at dusk"), &inputs(&[]), &rec()).unwrap();
+ assert_eq!(p.mode, ResolvedMode::Generate);
+ assert!(p.auto_mode);
+ assert_eq!(p.output, Size::new(1024, 1024));
+ assert_eq!(p.working, Size::new(1024, 1024));
+ assert_eq!((p.steps, p.cfg, p.sampler.as_str()), (40, 1.0, "euler"), "official: 40 steps, no CFG");
+ assert!(!p.vae_tiling);
+ assert!(p.references.is_empty());
+ }
+
+ #[test]
+ fn negative_prompt_needs_cfg() {
+ let mut r = req("a lighthouse at dusk");
+ r.negative_prompt = Some("blurry".into());
+ let p = plan(&r, &inputs(&[]), &rec()).unwrap();
+ assert_eq!(p.negative_prompt, "blurry", "still sent; the server ignores it at CFG 1");
+ assert!(p.notes.iter().any(|n| n.contains("negative prompt is ignored")));
+ r.advanced.cfg = Some(4.0);
+ let p = plan(&r, &inputs(&[]), &rec()).unwrap();
+ assert!(!p.notes.iter().any(|n| n.contains("negative prompt")));
+ assert!(p.estimated_seconds > plan(&req("a lighthouse at dusk"), &inputs(&[]), &rec()).unwrap().estimated_seconds * 1.6, "CFG > 1 doubles the steps' cost");
+ }
+
+ #[test]
+ fn prompt_implies_aspect() {
+ let p = plan(&req("Generate a hero image for the landing page, 16:9"), &inputs(&[]), &rec()).unwrap();
+ assert_eq!(p.output, Size::new(1376, 768));
+ let p = plan(&req("a phone wallpaper of mountains"), &inputs(&[]), &rec()).unwrap();
+ assert!(p.output.height > p.output.width);
+ let p = plan(&req("a poster, 1280x720"), &inputs(&[]), &rec()).unwrap();
+ assert_eq!(p.output, Size::new(1280, 720));
+ assert_eq!(p.working, Size::new(1280, 736));
+ }
+
+ #[test]
+ fn explicit_aspect_and_quality_tiers() {
+ let mut r = req("a cat");
+ r.aspect_ratio = Some("16:9".into());
+ r.resolution = ResolutionMode::K2;
+ let p = plan(&r, &inputs(&[]), &rec()).unwrap();
+ assert_eq!(p.output, Size::new(2752, 1536), "official 2K bucket");
+ assert!(p.vae_tiling, "large decode gets tiling");
+ assert!(p.optimized_for_vram);
+ r.resolution = ResolutionMode::Auto;
+ r.quality = Quality::Fast;
+ let p = plan(&r, &inputs(&[]), &rec()).unwrap();
+ assert_eq!(p.steps, 20, "Fast halves the official 40 steps");
+ assert!(p.output.area() <= 1_100_000);
+ r.quality = Quality::Balanced;
+ assert_eq!(plan(&r, &inputs(&[]), &rec()).unwrap().steps, 40);
+ r.quality = Quality::Quality;
+ let p = plan(&r, &inputs(&[]), &rec()).unwrap();
+ assert_eq!(p.steps, 40);
+ assert_eq!(p.working, Size::new(2752, 1536), "Quality = official native 2K bucket");
+ assert_eq!(p.output, p.working);
+ }
+
+ #[test]
+ fn single_image_means_edit_and_preserves_dimensions() {
+ let p = plan(&req("change the red car to a black Porsche"), &inputs(&[(1920, 1080)]), &rec()).unwrap();
+ assert_eq!(p.mode, ResolvedMode::Edit);
+ assert_eq!(p.output, Size::new(1920, 1080));
+ assert!(p.working.is_aligned(32));
+ let a = p.content.width as f64 / p.content.height as f64;
+ assert!((a / (1920.0 / 1080.0) - 1.0).abs() < 0.01);
+ assert_eq!(p.references.len(), 1);
+ assert_eq!(p.references[0].canvas.canvas, p.working, "ref matches canvas so the backend never resizes it");
+ assert!(p.strength.is_none());
+ assert_eq!(p.cfg, 1.0, "official: edits run without CFG too");
+ }
+
+ #[test]
+ fn near_budget_source_is_not_rescaled() {
+ // Regression: a 1376x768 result (0.7% over the 1 MP Balanced budget) was shrunk by 0.4% and padded.
+ let p = plan(&req("make it nighttime"), &inputs(&[(1376, 768)]), &rec()).unwrap();
+ assert_eq!(p.working, Size::new(1376, 768));
+ assert_eq!(p.content, Rect::new(0, 0, 1376, 768));
+ assert!(p.notes.is_empty(), "{:?}", p.notes);
+ }
+
+ #[test]
+ fn source_mode_works_at_full_resolution() {
+ let mut r = req("make it night");
+ r.resolution = ResolutionMode::Source;
+ let p = plan(&r, &inputs(&[(1536, 1024)]), &rec()).unwrap();
+ assert_eq!(p.working, Size::new(1536, 1024));
+ assert_eq!(p.output, Size::new(1536, 1024));
+ let p = plan(&r, &inputs(&[(1920, 1080)]), &rec()).unwrap();
+ assert_eq!(p.working, Size::new(1920, 1088));
+ assert_eq!(p.content, Rect::new(0, 4, 1920, 1080));
+ }
+
+ #[test]
+ fn huge_photo_is_reduced_for_vram_and_restored() {
+ let mut r = req("make it autumn");
+ r.resolution = ResolutionMode::Source;
+ let p = plan(&r, &inputs(&[(4032, 3024)]), &rec()).unwrap();
+ assert!(p.optimized_for_vram);
+ assert_eq!(p.references[0].canvas.canvas, p.working);
+ assert!((p.working.area() * 2) as f64 <= (token_budget(Some(16303)) * 256) as f64 * 1.05, "target + reference share the budget");
+ assert_eq!(p.output, Size::new(4032, 3024));
+ assert!(p.notes.iter().any(|n| n.contains("enlarged to 4032×3024")));
+ }
+
+ fn env(upscaler: bool, refine: RefineMode) -> PlanInputs {
+ PlanInputs { upscaler: upscaler.then(|| "RealESRGAN_x4plus".to_string()), refine, sage_attention: true, ..inputs(&[]) }
+ }
+
+ #[test]
+ fn generation_is_always_one_pass() {
+ // Any refine setting, any size: one diffusion pass, no cache.
+ for refine in [RefineMode::Off, RefineMode::Fast, RefineMode::Best] {
+ for (res, aspect) in [(ResolutionMode::Auto, "16:9"), (ResolutionMode::K15, "1:1"), (ResolutionMode::K2, "9:16")] {
+ for q in [Quality::Fast, Quality::Balanced, Quality::Quality] {
+ let mut r = req("a cozy mountain cabin");
+ r.aspect_ratio = Some(aspect.into());
+ r.resolution = res;
+ r.quality = q;
+ r.advanced.refine = Some(refine);
+ let p = plan(&r, &env(true, refine), &rec()).unwrap();
+ assert_eq!(p.cache_threshold, None, "{res:?} {aspect} {q:?}");
+ assert!(!p.notes.iter().any(|n| n.contains("Two passes")));
+ assert!(p.working.is_aligned(32));
+ assert!(p.working.area() as f64 <= (token_budget(Some(16303)) * 256) as f64 * 1.02, "{:?}", p.working);
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn large_text_to_image_renders_within_budget_then_enlarges() {
+ // Official 2K bucket fits the budget: rendered natively.
+ let mut r = req("a city at night");
+ r.aspect_ratio = Some("16:9".into());
+ r.resolution = ResolutionMode::K2;
+ let p = plan(&r, &env(true, RefineMode::Fast), &rec()).unwrap();
+ assert_eq!(p.output, Size::new(2752, 1536));
+ assert!(p.vae_tiling, "large decode is tiled");
+
+ // A custom 4K: rendered at the budget, delivered at the exact size with the upscaler.
+ let mut r = req("a city at night");
+ r.resolution = ResolutionMode::Custom;
+ r.width = Some(3840);
+ r.height = Some(2160);
+ let p = plan(&r, &env(true, RefineMode::Fast), &rec()).unwrap();
+ assert_eq!(p.output, Size::new(3840, 2160), "exact requested size is delivered");
+ assert!(p.working.area() as f64 <= (token_budget(Some(16303)) * 256) as f64 * 1.02, "alignment padding only");
+ assert!((p.content.width as f64 / p.content.height as f64 / (3840.0 / 2160.0) - 1.0).abs() < 0.01);
+ assert!(p.notes.iter().any(|n| n.contains("enlarged to 3840×2160 with RealESRGAN_x4plus")), "{:?}", p.notes);
+ }
+
+ #[test]
+ fn edits_are_one_pass_and_enlarged_to_the_source() {
+ let i = PlanInputs { image_sizes: vec![Size::new(5120, 2880)], ..env(true, RefineMode::Fast) };
+ let mut r = req("make it a dark version");
+ r.quality = Quality::Balanced;
+ let p = plan(&r, &i, &rec()).unwrap();
+ assert_eq!(p.mode, ResolvedMode::Edit);
+ assert_eq!(p.working, Size::new(1376, 768));
+ assert_eq!(p.references[0].canvas.canvas, p.working);
+ assert_eq!(p.output, Size::new(5120, 2880));
+ assert_eq!((p.steps, p.cfg), (40, 1.0));
+ let esrgan = p.estimated_seconds;
+ let p2 = plan(&r, &PlanInputs { upscaler: None, ..i.clone() }, &rec()).unwrap();
+ assert!(esrgan > p2.estimated_seconds, "the enlargement is included in the estimate");
+ assert!(p2.notes.iter().any(|n| n.ends_with("with Lanczos.")));
+ }
+
+ #[test]
+ fn quality_edit_shares_the_2k_budget_with_its_reference() {
+ let mut r = req("remove the people");
+ r.quality = Quality::Quality;
+ let i = PlanInputs { image_sizes: vec![Size::new(5712, 4284)], ..env(true, RefineMode::Best) };
+ let p = plan(&r, &i, &rec()).unwrap();
+ assert_eq!((p.steps, p.cfg, p.cache_threshold), (40, 1.0, None));
+ // Native 2K plus a 2K reference exceeds 16 GB: both get half the budget (~2 MP each).
+ // Each side rounds to 32 px, so allow the same 5 % slack as many_references_share_the_budget.
+ assert!((1_850_000..=2_202_010).contains(&p.working.area()), "{:?}", p.working);
+ assert_eq!(p.references[0].canvas.canvas, p.working, "the model sees the source at ~2 MP");
+ assert!(p.notes.iter().any(|n| n.contains("Resolution reduced")));
+ assert!((p.working.area() + p.references[0].canvas.canvas.area()) as f64 <= (token_budget(Some(16303)) * PIXELS_PER_TOKEN) as f64 * 1.05);
+ assert_eq!(p.output, Size::new(5712, 4284));
+ }
+
+ #[test]
+ fn tiers_set_the_output_size_of_edits_and_combines() {
+ // Regression: 1K/1.5K/2K were capped by the smallest source, so 800x800 refs always gave 800x800.
+ let budget = (token_budget(Some(16303)) * PIXELS_PER_TOKEN) as f64 * 1.05;
+ let mut r = req("put both people in a kitchen");
+ r.resolution = ResolutionMode::K15;
+ let p = plan(&r, &inputs(&[(800, 800), (800, 800)]), &rec()).unwrap();
+ assert_eq!(p.mode, ResolvedMode::MultiReference);
+ assert_eq!(p.output, Size::new(1536, 1536));
+ assert!(p.working.area() > 1_500_000, "small references leave room for the target: {:?}", p.working);
+ assert!((p.working.area() + p.references.iter().map(|r| r.canvas.canvas.area()).sum::<u64>()) as f64 <= budget);
+ r.resolution = ResolutionMode::K2;
+ r.aspect_ratio = Some("16:9".into());
+ let p = plan(&r, &inputs(&[(800, 800), (600, 900)]), &rec()).unwrap();
+ assert_eq!(p.output, Size::new(2752, 1536), "official 2K bucket");
+ assert!((p.working.area() + p.references.iter().map(|r| r.canvas.canvas.area()).sum::<u64>()) as f64 <= budget);
+ let a = p.content.width as f64 / p.content.height as f64;
+ assert!((a / (16.0 / 9.0) - 1.0).abs() < 0.02);
+ // A single small photo edited at 1K.
+ let mut r = req("make it a watercolor");
+ r.resolution = ResolutionMode::K1;
+ let p = plan(&r, &inputs(&[(640, 480)]), &rec()).unwrap();
+ assert_eq!(p.mode, ResolvedMode::Edit);
+ assert!((1_000_000..=1_100_000).contains(&p.output.area()), "{:?}", p.output);
+ assert!((p.output.width as f64 / p.output.height as f64 / (4.0 / 3.0) - 1.0).abs() < 0.02);
+ }
+
+ #[test]
+ fn edit_aspect_and_custom_size() {
+ let mut r = req("turn it into a wide cinematic shot");
+ r.aspect_ratio = Some("16:9".into());
+ let p = plan(&r, &inputs(&[(1024, 1024)]), &rec()).unwrap();
+ assert_eq!(p.mode, ResolvedMode::Edit);
+ assert!(p.output.width > p.output.height);
+ assert!((p.output.area() as f64 / (1024.0 * 1024.0) - 1.0).abs() < 0.05, "Auto keeps the source's pixel count");
+ let mut r = req("same scene, poster");
+ r.resolution = ResolutionMode::Custom;
+ (r.width, r.height) = (Some(1200), Some(1800));
+ let p = plan(&r, &inputs(&[(800, 800)]), &rec()).unwrap();
+ assert_eq!(p.output, Size::new(1200, 1800));
+ r.width = Some(9000);
+ assert!(plan(&r, &inputs(&[(800, 800)]), &rec()).is_err());
+ }
+
+ #[test]
+ fn many_references_share_the_budget() {
+ let mut r = req("combine");
+ r.resolution = ResolutionMode::Source;
+ let i = PlanInputs { image_sizes: vec![Size::new(3000, 2000), Size::new(2000, 2000), Size::new(2000, 2000)], ..env(true, RefineMode::Fast) };
+ let p = plan(&r, &i, &rec()).unwrap();
+ assert!(p.optimized_for_vram);
+ let total: u64 = p.working.area() + p.references.iter().map(|r| r.canvas.canvas.area()).sum::<u64>();
+ assert!(total as f64 <= (token_budget(Some(16303)) * 256) as f64 * 1.05, "{total}");
+ }
+
+ #[test]
+ fn upscale_targets() {
+ let src = Size::new(1376, 768);
+ let t = |spec: UpscaleSpec| upscale_target(src, &spec);
+ assert_eq!(t(UpscaleSpec::default()).unwrap(), Size::new(2752, 1536), "default 2x");
+ assert_eq!(t(UpscaleSpec { scale: Some(4.0), ..Default::default() }).unwrap(), Size::new(5504, 3072));
+ assert_eq!(t(UpscaleSpec { width: Some(3840), ..Default::default() }).unwrap(), Size::new(3840, 2143));
+ assert_eq!(t(UpscaleSpec { height: Some(2880), ..Default::default() }).unwrap(), Size::new(5160, 2880));
+ assert_eq!(t(UpscaleSpec { width: Some(5120), height: Some(2880), ..Default::default() }).unwrap(), Size::new(5120, 2880));
+ assert!(t(UpscaleSpec { scale: Some(8.0), ..Default::default() }).is_err(), "over 8192 px");
+ assert!(t(UpscaleSpec { width: Some(8000), height: Some(8000), ..Default::default() }).is_err(), "over 40 MP");
+ assert!(t(UpscaleSpec { scale: Some(-1.0), ..Default::default() }).is_err());
+ }
+
+ #[test]
+ fn upscale_plans() {
+ let mut r = GenerationRequest { mode: Mode::Upscale, upscale: Some(UpscaleSpec { scale: Some(2.0), ..Default::default() }), ..Default::default() };
+ let i = PlanInputs { image_sizes: vec![Size::new(1376, 768)], ..env(true, RefineMode::Fast) };
+ let p = plan(&r, &i, &rec()).unwrap();
+ assert_eq!(p.mode, ResolvedMode::Upscale);
+ assert_eq!(p.output, Size::new(2752, 1536));
+ assert_eq!(p.steps, 0, "Quick runs no diffusion");
+ assert_eq!(p.working, Size::new(1376, 768));
+ assert!(p.cache_threshold.is_none());
+ assert!(p.estimated_seconds < 20.0, "{}", p.estimated_seconds);
+
+ r.upscale = Some(UpscaleSpec { method: UpscaleMethod::Detailed, width: Some(5120), height: Some(2880), ..Default::default() });
+ let p = plan(&r, &i, &rec()).unwrap();
+ assert_eq!(p.output, Size::new(5120, 2880));
+ assert_eq!(p.working, Size::new(2048, 1152), "refine at ~2K in the target's shape");
+ assert_eq!(p.strength, Some(DETAILED_DENOISE));
+ assert_eq!(p.steps, 20, "6 effective steps at denoise 0.3");
+ assert_eq!(p.cfg, 1.0);
+ assert_eq!(p.cache_threshold, Some(0.2));
+ assert_eq!(p.batch_count, 1);
+ assert_eq!(p.references.len(), 1);
+
+ r.advanced.refine = Some(RefineMode::Best);
+ let p = plan(&r, &i, &rec()).unwrap();
+ assert_eq!((p.steps, p.cache_threshold), (27, None));
+
+ r.mode = Mode::Upscale;
+ assert!(plan(&r, &env(true, RefineMode::Fast), &rec()).is_err(), "needs an image");
+ }
+
+ #[test]
+ fn server_vae_tiling_is_reflected_in_the_plan() {
+ let i = PlanInputs { server_vae_tiling: true, ..inputs(&[]) };
+ let p = plan(&req("a fox"), &i, &rec()).unwrap();
+ assert!(p.vae_tiling, "the server tiles every decode");
+ assert!(!p.notes.iter().any(|n| n.contains("Memory optimization")), "nothing to announce");
+ let mut r = req("a fox");
+ r.advanced.vae_tiling = Some(false);
+ assert!(!plan(&r, &i, &rec()).unwrap().vae_tiling, "explicit off wins");
+ }
+
+ #[test]
+ fn multi_reference_keeps_order_and_budget() {
+ let p = plan(
+ &req("Use the person from image 1, the clothing from image 2, and the lighting style from image 3."),
+ &inputs(&[(1080, 1920), (1024, 1024), (4032, 3024)]),
+ &rec(),
+ )
+ .unwrap();
+ assert_eq!(p.mode, ResolvedMode::MultiReference);
+ let idx: Vec<usize> = p.references.iter().map(|r| r.index).collect();
+ assert_eq!(idx, vec![0, 1, 2]);
+ assert_eq!(p.references[0].source, Size::new(1080, 1920));
+ assert_eq!(p.references[2].source, Size::new(4032, 3024));
+ assert!(p.output.height > p.output.width, "image 1 defines the output shape");
+ for r in &p.references {
+ assert!(r.canvas.canvas.is_aligned(32));
+ assert!(r.canvas.canvas.area() <= p.working.area());
+ }
+ }
+
+ #[test]
+ fn too_many_references() {
+ let sizes: Vec<(u32, u32)> = (0..11).map(|_| (512, 512)).collect();
+ assert!(plan(&req("x"), &inputs(&sizes), &rec()).is_err());
+ }
+
+ #[test]
+ fn empty_prompt_rejected() {
+ assert_eq!(plan(&req(" "), &inputs(&[]), &rec()).unwrap_err().code, ErrorCode::InvalidInput);
+ }
+
+ #[test]
+ fn mode_override() {
+ let mut r = req("a new scene");
+ r.mode = Mode::Generate;
+ let p = plan(&r, &inputs(&[(800, 600)]), &rec()).unwrap();
+ assert_eq!(p.mode, ResolvedMode::Generate);
+ assert!(!p.auto_mode);
+ r.mode = Mode::Inpaint;
+ assert!(plan(&r, &inputs(&[(800, 600)]), &rec()).is_err(), "inpaint needs a mask");
+ r.mode = Mode::Edit;
+ assert!(plan(&r, &inputs(&[]), &rec()).is_err());
+ }
+
+ #[test]
+ fn inpaint_plan_crops_around_mask() {
+ let mut r = req("remove the sign");
+ r.mask = Some("input:m".into());
+ let mut i = inputs(&[(4032, 3024)]);
+ i.mask = Some((Size::new(4032, 3024), Some(Rect::new(2000, 1500, 120, 90)), 0.001));
+ let p = plan(&r, &i, &rec()).unwrap();
+ assert_eq!(p.mode, ResolvedMode::Inpaint);
+ let reg = p.inpaint_region.unwrap();
+ assert!(reg.x <= 2000 && reg.right() >= 2120);
+ assert!(reg.width < 4032);
+ assert_eq!(p.output, Size::new(4032, 3024));
+ assert_eq!(p.strength, Some(1.0));
+ assert!(p.working.is_aligned(32));
+ }
+
+ #[test]
+ fn inpaint_with_empty_mask_falls_back_to_edit_in_auto() {
+ let mut r = req("make it sunny");
+ r.mask = Some("input:m".into());
+ let mut i = inputs(&[(1024, 768)]);
+ i.mask = Some((Size::new(1024, 768), None, 0.0));
+ assert_eq!(plan(&r, &i, &rec()).unwrap().mode, ResolvedMode::Edit);
+ }
+
+ #[test]
+ fn outpaint_from_numbers_and_from_words() {
+ let mut r = req("continue the beach");
+ r.outpaint = Some(OutpaintSpec { left: 256.0, right: 256.0, top: 0.0, bottom: 0.0, units: ExpansionUnits::Pixels });
+ let p = plan(&r, &inputs(&[(1024, 1024)]), &rec()).unwrap();
+ assert_eq!(p.mode, ResolvedMode::Outpaint);
+ assert_eq!(p.output, Size::new(1536, 1024));
+ let op = p.outpaint.unwrap();
+ assert_eq!(op.source_rect_final, Rect::new(256, 0, 1024, 1024));
+
+ let p = plan(&req("extend the image to the left by 50%"), &inputs(&[(1000, 800)]), &rec()).unwrap();
+ assert_eq!(p.mode, ResolvedMode::Outpaint);
+ assert_eq!(p.output, Size::new(1500, 800));
+
+ let p = plan(&req("expand it to 16:9 landscape"), &inputs(&[(1024, 1024)]), &rec()).unwrap();
+ assert_eq!(p.output, Size::new(1820, 1024));
+
+ let mut r = req("more sky");
+ r.outpaint = Some(OutpaintSpec { top: 25.0, units: ExpansionUnits::Percent, ..Default::default() });
+ let p = plan(&r, &inputs(&[(1920, 1080)]), &rec()).unwrap();
+ assert_eq!(p.output, Size::new(1920, 1350));
+ }
+
+ #[test]
+ fn outpaint_intent_parsing() {
+ let s = Size::new(1000, 1000);
+ assert_eq!(outpaint_intent("change the car color", s), None);
+ assert_eq!(outpaint_intent("extend right", s), Some(Expansion { right: 250, ..Default::default() }));
+ assert_eq!(outpaint_intent("expand upwards by 400 px", s), Some(Expansion { top: 400, ..Default::default() }));
+ assert_eq!(outpaint_intent("zoom out", s), Some(Expansion { left: 250, right: 250, top: 250, bottom: 250 }));
+ assert_eq!(outpaint_intent("make it wider", s), Some(Expansion { left: 250, right: 250, ..Default::default() }));
+ }
+
+ #[test]
+ fn aspect_hints() {
+ assert_eq!(aspect_hint("a 16:9 banner"), Some(AspectHint::Ratio(16.0 / 9.0, "16:9".into())));
+ assert_eq!(aspect_hint("logo for a cafe"), Some(AspectHint::Ratio(1.0, "1:1".into())));
+ assert_eq!(aspect_hint("a street at 10:30 in the morning"), None);
+ assert_eq!(aspect_hint("a cat"), None);
+ assert_eq!(parse_aspect("4:3").unwrap().0, 4.0 / 3.0);
+ assert!(parse_aspect("auto").is_none());
+ assert!(parse_aspect("100:1").is_none());
+ }
+
+ #[test]
+ fn budget_scales_with_vram() {
+ assert_eq!(token_budget(Some(16303)), 16_384);
+ assert!(token_budget(Some(8192)) < token_budget(Some(16303)));
+ assert!(token_budget(Some(24576)) > token_budget(Some(16303)));
+ assert_eq!(token_budget(None), 12_288);
+ }
+
+ #[test]
+ fn estimate_matches_benchmarks_roughly() {
+ // Benchmarks ran at CFG 6.
+ let s = estimate_seconds(Size::new(1024, 1024), &[], 20, 1, false, false, 6.0);
+ assert!((40.0..55.0).contains(&s), "{s}");
+ let s = estimate_seconds(Size::new(2048, 2048), &[], 3, 1, false, false, 6.0);
+ assert!((40.0..60.0).contains(&s), "{s}");
+ // 2K bench (sd-cli incl. ~3 s load): sage single pass 104 s.
+ let s = estimate_seconds(Size::new(2048, 1152), &[], 20, 1, false, true, 6.0);
+ assert!((80.0..105.0).contains(&s), "native {s}");
+ // CFG 1 runs one model pass per step: 40 steps cost about what 20 did at CFG 6.
+ let one = estimate_seconds(Size::new(1024, 1024), &[], 40, 1, false, true, 1.0);
+ let two = estimate_seconds(Size::new(1024, 1024), &[], 20, 1, false, true, 6.0);
+ assert!((one - two).abs() < 1.0, "{one} vs {two}");
+ }
+
+ #[test]
+ fn request_json_contract() {
+ let r: GenerationRequest = serde_json::from_str(
+ r#"{"prompt":"x","mode":"multi_reference","images":["C:\\a.png","input:abc"],"quality":"fast","resolution":"1.5k",
+ "outpaint":{"left":10,"units":"percent"},"advanced":{"steps":12,"output_format":"webp"}}"#,
+ )
+ .unwrap();
+ assert_eq!(r.mode, Mode::MultiReference);
+ assert_eq!(r.resolution, ResolutionMode::K15);
+ assert_eq!(r.quality, Quality::Fast);
+ assert!(r.preserve_dimensions);
+ assert_eq!(r.outpaint.unwrap().units, ExpansionUnits::Percent);
+ assert_eq!(r.advanced.output_format, Some(OutputFormat::Webp));
+ assert!(r.upscale.is_none() && r.advanced.refine.is_none());
+
+ let r: GenerationRequest = serde_json::from_str(
+ r#"{"prompt":"","mode":"upscale","images":["gen:abc"],"upscale":{"method":"detailed","width":3840},"advanced":{"refine":"best"}}"#,
+ )
+ .unwrap();
+ assert_eq!(r.mode, Mode::Upscale);
+ assert_eq!(r.upscale.unwrap().method, UpscaleMethod::Detailed);
+ assert_eq!(r.upscale.unwrap().width, Some(3840));
+ assert_eq!(r.advanced.refine, Some(RefineMode::Best));
+ }
+}
diff --git a/crates/qls-core/src/process.rs b/crates/qls-core/src/process.rs
new file mode 100644
index 0000000..98bdf38
--- /dev/null
+++ b/crates/qls-core/src/process.rs
@@ -0,0 +1,891 @@
+//! sd-server process management: launch arguments, reuse/spawn/stop, log capture and
+//! truthful progress parsing from the server's own log output.
+
+use std::collections::VecDeque;
+use std::io::{Read, Seek, SeekFrom};
+use std::path::{Path, PathBuf};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use serde::{Deserialize, Serialize};
+use tokio::sync::broadcast;
+
+use crate::config::{AppConfig, ModelProfile, TextEncoderPlacement};
+use crate::error::{AppError, ErrorCode, translate_startup_failure};
+use crate::sdcpp::{Capabilities, SdcppClient};
+
+// ---------------------------------------------------------------------------------------
+// Launch arguments
+// ---------------------------------------------------------------------------------------
+
+pub fn build_server_args(cfg: &AppConfig, profile: &ModelProfile) -> Vec<String> {
+ let p = |p: &Path| p.to_string_lossy().into_owned();
+ let mut a: Vec<String> = vec![
+ "--listen-ip".into(),
+ "127.0.0.1".into(),
+ "--listen-port".into(),
+ cfg.server_port.to_string(),
+ "--diffusion-model".into(),
+ p(&profile.diffusion_model),
+ "--vae".into(),
+ p(&profile.vae),
+ "--llm".into(),
+ p(&profile.text_encoder),
+ ];
+ if let Some(v) = &profile.vision_projector {
+ a.push("--llm_vision".into());
+ a.push(p(v));
+ }
+ let dev = cfg.device.to_ascii_lowercase();
+ match cfg.text_encoder_placement {
+ TextEncoderPlacement::Ram => {
+ // Weights in RAM, compute on the GPU. Explicit --params-backend disables
+ // auto-fit, so DiT/VAE weights live on their compute device.
+ a.extend(["--backend".into(), dev.clone(), "--params-backend".into(), "te=cpu".into()]);
+ }
+ TextEncoderPlacement::Gpu => a.extend(["--backend".into(), dev.clone()]),
+ TextEncoderPlacement::Cpu => a.extend(["--backend".into(), format!("diffusion={dev},vae={dev},te=cpu")]),
+ TextEncoderPlacement::Auto => a.extend(["--backend".into(), format!("diffusion={dev},vae={dev}"), "--auto-fit".into(), "on".into()]),
+ }
+ if cfg.flash_attention {
+ a.push("--fa".into());
+ }
+ if cfg.sage_attention {
+ // Falls back to flash/default attention for layers it can't handle.
+ a.push("--sage-attn".into());
+ }
+ if cfg.vae_tile_size > 0 {
+ a.extend([
+ "--vae-tiling".into(),
+ "--vae-tile-size".into(),
+ cfg.vae_tile_size.to_string(),
+ "--vae-tile-overlap".into(),
+ "0.125".into(),
+ ]);
+ }
+ match cfg.prefix_cache_type.as_str() {
+ "auto" => {}
+ "off" => a.extend(["--model-args".into(), "qwen_image_2_1_prefix_cache=false".into()]),
+ t => a.extend(["--model-args".into(), format!("qwen_image_2_1_prefix_cache_type={t}")]),
+ }
+ if cfg.eager_load {
+ a.push("--eager-load".into());
+ }
+ // ESRGAN models for the hires refine and `/sdcpp/v1/upscale`; the server scans the
+ // folder lazily, so a model added later is picked up without a restart.
+ let up_dir = cfg.upscalers_dir();
+ if up_dir.is_dir() {
+ a.push("--hires-upscalers-dir".into());
+ a.push(p(&up_dir));
+ }
+ if cfg.upscale_tile_size > 0 {
+ let t = cfg.upscale_tile_size.to_string();
+ a.extend(["--upscale-tile-size".into(), t.clone(), "--hires-upscale-tile-size".into(), t]);
+ }
+ if cfg.vram_reserve_gib > 0.0 {
+ // A negative --max-vram reserves that much free VRAM (sd-server --help).
+ a.push("--max-vram".into());
+ a.push(format!("-{}", trim_float(cfg.vram_reserve_gib)));
+ }
+ a.extend(profile.backend_args.iter().cloned());
+ a.extend(cfg.extra_server_args.iter().cloned());
+ a
+}
+
+fn trim_float(v: f32) -> String {
+ let s = format!("{v:.2}");
+ s.trim_end_matches('0').trim_end_matches('.').to_string()
+}
+
+// ---------------------------------------------------------------------------------------
+// Progress parsing (only what the backend actually prints)
+// ---------------------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum BackendStage {
+ Preparing,
+ EncodingImages,
+ EncodingPrompt,
+ Generating,
+ /// Hires fix: decoding the first pass, ESRGAN, re-encoding at the target size.
+ Upscaling,
+ /// Hires fix: second sampling pass at the target size.
+ Refining,
+ Decoding,
+ Finishing,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
+pub struct BackendProgress {
+ pub stage: BackendStage,
+ /// (current, total) sampling step, when the sampler's progress bar reports it.
+ pub step: Option<(u32, u32)>,
+ /// (current, total) image in a batch.
+ pub image: Option<(u32, u32)>,
+ pub seconds_per_step: Option<f32>,
+}
+
+#[derive(Debug, Default)]
+pub struct ProgressParser {
+ current: Option<BackendProgress>,
+}
+
+impl ProgressParser {
+ pub fn reset(&mut self) {
+ self.current = None;
+ }
+
+ /// Feeds one log line (already split on \n / \r). sd-server erases progress bars with
+ /// ESC[K and may print the next log line right after it, so ESC[K also separates
+ /// lines. Returns the latest update when the state changes.
+ pub fn feed(&mut self, raw: &str) -> Option<BackendProgress> {
+ let mut last = None;
+ for seg in raw.split("\u{1b}[K") {
+ if let Some(p) = self.feed_segment(seg) {
+ last = Some(p);
+ }
+ }
+ last
+ }
+
+ fn feed_segment(&mut self, raw: &str) -> Option<BackendProgress> {
+ let line = raw.trim();
+ if line.is_empty() {
+ return None;
+ }
+ let set = |s: &mut Self, stage: BackendStage| -> Option<BackendProgress> {
+ let image = s.current.and_then(|c| c.image);
+ let p = BackendProgress { stage, step: None, image, seconds_per_step: None };
+ s.current = Some(p);
+ Some(p)
+ };
+ if line.contains("generate_image ") && !line.contains("completed") {
+ self.current = None;
+ return set(self, BackendStage::Preparing);
+ }
+ self.current?;
+ let stage = self.current.map(|c| c.stage).unwrap();
+ if line.contains("generate_image completed") {
+ return set(self, BackendStage::Finishing);
+ }
+ if line.contains("EDIT mode") || line.contains("IMG2IMG") {
+ return set(self, BackendStage::EncodingImages);
+ }
+ if line.contains("sampling using") && stage == BackendStage::Preparing {
+ return set(self, BackendStage::EncodingPrompt);
+ }
+ if line.contains("encode_first_stage completed") {
+ return set(self, BackendStage::EncodingPrompt);
+ }
+ if let Some(rest) = line.split("generating image:").nth(1) {
+ // "generating image: 1/1 - seed 7"
+ let frac = rest.trim().split_whitespace().next().unwrap_or("");
+ let image = parse_fraction(frac);
+ let p = BackendProgress { stage: BackendStage::Generating, step: None, image, seconds_per_step: None };
+ self.current = Some(p);
+ return Some(p);
+ }
+ if line.contains("hires fix: upscaling to") {
+ return set(self, BackendStage::Upscaling);
+ }
+ // The upscaling stage prints VAE and ESRGAN tile bars that look like step bars
+ // (the VAE encode can even report "6/6"); sampling starts when the diffusion
+ // model builds its graph or EasyCache announces itself.
+ if stage == BackendStage::Upscaling
+ && (line.contains("EasyCache enabled")
+ || (line.contains("build cached graph cut plan") && !line.contains("vae") && !line.contains("esrgan")))
+ {
+ return set(self, BackendStage::Refining);
+ }
+ if line.contains("decoding") && line.contains("latent") && !line.contains("completed") {
+ return set(self, BackendStage::Decoding);
+ }
+ if matches!(stage, BackendStage::Generating | BackendStage::Refining)
+ && let Some((cur, total, spi)) = parse_step_bar(line)
+ {
+ let mut p = self.current.unwrap();
+ if p.step != Some((cur, total)) {
+ p.step = Some((cur, total));
+ p.seconds_per_step = spi;
+ self.current = Some(p);
+ return Some(p);
+ }
+ }
+ None
+ }
+}
+
+fn parse_fraction(s: &str) -> Option<(u32, u32)> {
+ let (a, b) = s.split_once('/')?;
+ Some((a.trim().parse().ok()?, b.trim().parse().ok()?))
+}
+
+/// Parses a sampler bar such as `|=====> | 2/20 - 1.99s/it`. Tensor-loading bars
+/// (`98/397 - 3.76GB/s`) are rejected because they report bytes, not iterations.
+pub fn parse_step_bar(line: &str) -> Option<(u32, u32, Option<f32>)> {
+ let after = line.rsplit('|').next()?.trim();
+ let (frac, rate) = after.split_once(" - ")?;
+ let rate = rate.trim();
+ let spi = if let Some(v) = rate.strip_suffix("s/it") {
+ v.trim().parse::<f32>().ok()
+ } else if let Some(v) = rate.strip_suffix("it/s") {
+ v.trim().parse::<f32>().ok().filter(|x| *x > 0.0).map(|x| 1.0 / x)
+ } else {
+ return None;
+ };
+ let (cur, total) = parse_fraction(frac)?;
+ (total > 0 && cur <= total).then_some((cur, total, spi))
+}
+
+// ---------------------------------------------------------------------------------------
+// Server manager
+// ---------------------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ServerState {
+ Stopped,
+ Starting,
+ Ready,
+ Error,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct ServerStatus {
+ pub state: ServerState,
+ /// True when this app launched the process (and may stop it).
+ pub owned: bool,
+ pub pid: Option<u32>,
+ pub port: u16,
+ pub model: Option<String>,
+ pub started_at: Option<chrono::DateTime<chrono::Utc>>,
+ pub error: Option<AppError>,
+ pub capabilities: Option<Capabilities>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+struct OwnedRecord {
+ pid: u32,
+ port: u16,
+ model: String,
+ log: PathBuf,
+}
+
+pub struct LogBuffer {
+ lines: Mutex<VecDeque<String>>,
+ cap: usize,
+}
+
+impl LogBuffer {
+ fn new(cap: usize) -> Self {
+ Self { lines: Mutex::new(VecDeque::with_capacity(cap)), cap }
+ }
+ fn push(&self, l: String) {
+ let mut g = self.lines.lock().unwrap();
+ if g.len() == self.cap {
+ g.pop_front();
+ }
+ g.push_back(l);
+ }
+ pub fn tail(&self, n: usize) -> Vec<String> {
+ let g = self.lines.lock().unwrap();
+ g.iter().skip(g.len().saturating_sub(n)).cloned().collect()
+ }
+}
+
+struct Inner {
+ state: ServerState,
+ owned: bool,
+ pid: Option<u32>,
+ port: u16,
+ model: Option<String>,
+ started_at: Option<chrono::DateTime<chrono::Utc>>,
+ error: Option<AppError>,
+ caps: Option<Capabilities>,
+ tail_stop: Option<Arc<std::sync::atomic::AtomicBool>>,
+}
+
+pub struct ServerManager {
+ inner: Mutex<Inner>,
+ start_lock: tokio::sync::Mutex<()>,
+ data_dir: PathBuf,
+ pub log: Arc<LogBuffer>,
+ lines_tx: broadcast::Sender<String>,
+}
+
+const CREATE_NO_WINDOW: u32 = 0x0800_0000;
+const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;
+
+impl ServerManager {
+ pub fn new(data_dir: PathBuf) -> Arc<Self> {
+ let (lines_tx, _) = broadcast::channel(4096);
+ Arc::new(Self {
+ inner: Mutex::new(Inner {
+ state: ServerState::Stopped,
+ owned: false,
+ pid: None,
+ port: 0,
+ model: None,
+ started_at: None,
+ error: None,
+ caps: None,
+ tail_stop: None,
+ }),
+ start_lock: tokio::sync::Mutex::new(()),
+ data_dir,
+ log: Arc::new(LogBuffer::new(4000)),
+ lines_tx,
+ })
+ }
+
+ /// Live stream of server log lines (only available for servers this app launched).
+ pub fn subscribe_lines(&self) -> broadcast::Receiver<String> {
+ self.lines_tx.subscribe()
+ }
+
+ pub fn status(&self) -> ServerStatus {
+ let g = self.inner.lock().unwrap();
+ ServerStatus {
+ state: g.state,
+ owned: g.owned,
+ pid: g.pid,
+ port: g.port,
+ model: g.model.clone(),
+ started_at: g.started_at,
+ error: g.error.clone(),
+ capabilities: g.caps.clone(),
+ }
+ }
+
+ pub fn capabilities(&self) -> Option<Capabilities> {
+ self.inner.lock().unwrap().caps.clone()
+ }
+
+ fn record_path(&self) -> PathBuf {
+ self.data_dir.join("sd-server.owned.json")
+ }
+
+ fn log_path(&self) -> PathBuf {
+ self.data_dir.join("logs").join("sd-server.log")
+ }
+
+ fn read_record(&self) -> Option<OwnedRecord> {
+ serde_json::from_str(&std::fs::read_to_string(self.record_path()).ok()?).ok()
+ }
+
+ fn set_state(&self, f: impl FnOnce(&mut Inner)) {
+ let mut g = self.inner.lock().unwrap();
+ f(&mut g);
+ }
+
+ /// Mark the server as gone (e.g. the process exited unexpectedly).
+ pub fn mark_lost(&self, err: AppError) {
+ self.set_state(|g| {
+ g.state = ServerState::Error;
+ g.error = Some(err);
+ g.caps = None;
+ });
+ }
+
+ /// Ensures a compatible sd-server is reachable: reuses a running one, otherwise
+ /// launches it. Serialized so concurrent callers never start two instances.
+ pub async fn ensure_ready(&self, cfg: &AppConfig) -> Result<Capabilities, AppError> {
+ let _guard = self.start_lock.lock().await;
+ let profile = cfg.profile().clone();
+ let client = SdcppClient::new(cfg.server_port);
+
+ if let Ok(caps) = client.capabilities(Duration::from_secs(3)).await {
+ let rec = self.read_record().filter(|r| r.port == cfg.server_port && process_alive(r.pid));
+ if caps.model_matches(&profile.diffusion_model) && caps.supports_img_gen() {
+ let owned = rec.is_some();
+ if let Some(r) = &rec
+ && self.inner.lock().unwrap().tail_stop.is_none()
+ {
+ self.start_tail(&r.log, true);
+ }
+ self.set_state(|g| {
+ g.state = ServerState::Ready;
+ g.owned = owned;
+ g.pid = rec.as_ref().map(|r| r.pid);
+ g.port = cfg.server_port;
+ g.model = Some(caps.model.name.clone());
+ g.error = None;
+ g.caps = Some(caps.clone());
+ if g.started_at.is_none() {
+ g.started_at = Some(chrono::Utc::now());
+ }
+ });
+ return Ok(caps);
+ }
+ // Wrong model on our port.
+ if let Some(r) = rec {
+ tracing::info!("restarting owned sd-server (pid {}) for a different model", r.pid);
+ kill_pid(r.pid);
+ let _ = std::fs::remove_file(self.record_path());
+ wait_port_free(&client, Duration::from_secs(15)).await;
+ } else {
+ let e = AppError::new(
+ ErrorCode::ServerStartFailed,
+ format!("Port {} is used by another stable-diffusion.cpp server with a different model ({}).", cfg.server_port, caps.model.name),
+ )
+ .suggest("Stop that server or choose another port in Settings.");
+ self.set_state(|g| {
+ g.state = ServerState::Error;
+ g.error = Some(e.clone());
+ });
+ return Err(e);
+ }
+ }
+
+ self.spawn_and_wait(cfg, &profile, &client).await
+ }
+
+ async fn spawn_and_wait(&self, cfg: &AppConfig, profile: &ModelProfile, client: &SdcppClient) -> Result<Capabilities, AppError> {
+ let fail = |e: AppError| {
+ self.set_state(|g| {
+ g.state = ServerState::Error;
+ g.error = Some(e.clone());
+ g.caps = None;
+ });
+ e
+ };
+ let exe = cfg.server_exe();
+ if !exe.is_file() {
+ return Err(fail(
+ AppError::new(ErrorCode::MissingModel, format!("sd-server.exe was not found in {}.", cfg.sdcpp_dir.display()))
+ .suggest("Set the stable-diffusion.cpp folder in Settings."),
+ ));
+ }
+ for (label, path, required) in profile.files() {
+ if required && !path.is_file() {
+ return Err(fail(
+ AppError::new(ErrorCode::MissingModel, format!("{label} not found: {}", path.display())).suggest("Fix the model path in Settings."),
+ ));
+ }
+ }
+ let log_path = self.log_path();
+ if let Some(d) = log_path.parent() {
+ std::fs::create_dir_all(d).map_err(|e| fail(AppError::io("create the log folder", d, e)))?;
+ }
+ if log_path.exists() {
+ let _ = std::fs::rename(&log_path, log_path.with_extension("prev.log"));
+ }
+ let file = std::fs::File::create(&log_path).map_err(|e| fail(AppError::io("create the server log", &log_path, e)))?;
+ let args = build_server_args(cfg, profile);
+ tracing::info!("starting {} {}", exe.display(), args.join(" "));
+
+ let mut cmd = std::process::Command::new(&exe);
+ cmd.args(&args)
+ .current_dir(&cfg.sdcpp_dir)
+ .stdin(std::process::Stdio::null())
+ .stdout(file.try_clone().map_err(|e| fail(e.into()))?)
+ .stderr(file);
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ cmd.creation_flags(CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP);
+ }
+ let mut child = cmd.spawn().map_err(|e| {
+ fail(AppError::new(ErrorCode::ServerStartFailed, "Could not launch sd-server.exe.").detail(e.to_string()))
+ })?;
+ let pid = child.id();
+ let rec = OwnedRecord { pid, port: cfg.server_port, model: profile.model_name(), log: log_path.clone() };
+ let _ = std::fs::write(self.record_path(), serde_json::to_string(&rec).unwrap_or_default());
+ self.set_state(|g| {
+ g.state = ServerState::Starting;
+ g.owned = true;
+ g.pid = Some(pid);
+ g.port = cfg.server_port;
+ g.error = None;
+ g.caps = None;
+ g.started_at = Some(chrono::Utc::now());
+ });
+ self.start_tail(&log_path, false);
+
+ let started = Instant::now();
+ loop {
+ if let Ok(Some(status)) = child.try_wait() {
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ let tail = self.log.tail(40).join("\n");
+ let _ = std::fs::remove_file(self.record_path());
+ return Err(fail(translate_startup_failure(&format!("{tail}\n(exit status {status})"))));
+ }
+ if let Ok(caps) = client.capabilities(Duration::from_secs(2)).await {
+ self.set_state(|g| {
+ g.state = ServerState::Ready;
+ g.model = Some(caps.model.name.clone());
+ g.caps = Some(caps.clone());
+ });
+ // The Child handle is dropped; the process keeps running and is tracked by pid.
+ return Ok(caps);
+ }
+ if started.elapsed() > Duration::from_secs(900) {
+ kill_pid(pid);
+ return Err(fail(
+ AppError::new(ErrorCode::ServerStartFailed, "The inference server took too long to start.").detail(self.log.tail(40).join("\n")),
+ ));
+ }
+ tokio::time::sleep(Duration::from_millis(750)).await;
+ }
+ }
+
+ /// Stops the server if this app owns it. Never touches servers it did not start.
+ pub async fn stop(&self) -> bool {
+ let _guard = self.start_lock.lock().await;
+ let (owned, pid) = {
+ let g = self.inner.lock().unwrap();
+ (g.owned, g.pid.or_else(|| self.read_record().map(|r| r.pid)))
+ };
+ let pid = if owned { pid } else { self.read_record().map(|r| r.pid) };
+ let stopped = match pid {
+ Some(pid) if process_alive(pid) => {
+ kill_pid(pid);
+ true
+ }
+ _ => false,
+ };
+ let _ = std::fs::remove_file(self.record_path());
+ self.set_state(|g| {
+ if let Some(s) = g.tail_stop.take() {
+ s.store(true, std::sync::atomic::Ordering::Relaxed);
+ }
+ g.state = ServerState::Stopped;
+ g.owned = false;
+ g.pid = None;
+ g.caps = None;
+ g.started_at = None;
+ });
+ stopped
+ }
+
+ /// Whether the owned process is still alive (false for external servers).
+ pub fn owned_alive(&self) -> Option<bool> {
+ let g = self.inner.lock().unwrap();
+ if !g.owned {
+ return None;
+ }
+ g.pid.map(process_alive)
+ }
+
+ fn start_tail(&self, path: &Path, from_end: bool) {
+ let stop = Arc::new(std::sync::atomic::AtomicBool::new(false));
+ if let Some(old) = self.inner.lock().unwrap().tail_stop.replace(stop.clone()) {
+ old.store(true, std::sync::atomic::Ordering::Relaxed);
+ }
+ let path = path.to_path_buf();
+ let log = self.log.clone();
+ let tx = self.lines_tx.clone();
+ std::thread::Builder::new()
+ .name("sd-server-log".into())
+ .spawn(move || tail_file(&path, from_end, &stop, |line| {
+ log.push(line.clone());
+ let _ = tx.send(line);
+ }))
+ .ok();
+ }
+}
+
+/// Follows a growing file, splitting on \n and \r (progress bars use carriage returns).
+fn tail_file(path: &Path, from_end: bool, stop: &std::sync::atomic::AtomicBool, mut on_line: impl FnMut(String)) {
+ let mut pos: u64 = 0;
+ let mut opened = false;
+ let mut partial = Vec::<u8>::new();
+ let mut buf = vec![0u8; 64 * 1024];
+ while !stop.load(std::sync::atomic::Ordering::Relaxed) {
+ if let Ok(mut f) = std::fs::OpenOptions::new().read(true).open(path) {
+ let len = f.metadata().map(|m| m.len()).unwrap_or(0);
+ if !opened {
+ pos = if from_end { len } else { 0 };
+ opened = true;
+ }
+ if len < pos {
+ pos = 0; // truncated / replaced
+ }
+ if len > pos && f.seek(SeekFrom::Start(pos)).is_ok() {
+ while let Ok(n) = f.read(&mut buf) {
+ if n == 0 {
+ break;
+ }
+ pos += n as u64;
+ for &b in &buf[..n] {
+ if b == b'\n' || b == b'\r' {
+ if !partial.is_empty() {
+ on_line(String::from_utf8_lossy(&partial).into_owned());
+ partial.clear();
+ }
+ } else {
+ partial.push(b);
+ }
+ }
+ }
+ }
+ }
+ std::thread::sleep(Duration::from_millis(200));
+ }
+}
+
+async fn wait_port_free(client: &SdcppClient, timeout: Duration) {
+ let t = Instant::now();
+ while t.elapsed() < timeout && client.capabilities(Duration::from_millis(500)).await.is_ok() {
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ }
+}
+
+pub fn process_alive(pid: u32) -> bool {
+ use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System};
+ let mut sys = System::new();
+ let pid = Pid::from_u32(pid);
+ sys.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), true, ProcessRefreshKind::nothing());
+ sys.process(pid)
+ .map(|p| p.name().to_string_lossy().to_ascii_lowercase().starts_with("sd-server"))
+ .unwrap_or(false)
+}
+
+/// Whether any process with this pid exists (used for client liveness, not sd-server).
+pub fn pid_alive(pid: u32) -> bool {
+ use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System};
+ let mut sys = System::new();
+ let pid = Pid::from_u32(pid);
+ sys.refresh_processes_specifics(ProcessesToUpdate::Some(&[pid]), true, ProcessRefreshKind::nothing());
+ sys.process(pid).is_some()
+}
+
+fn kill_pid(pid: u32) {
+ use sysinfo::{Pid, ProcessRefreshKind, ProcessesToUpdate, System};
+ let mut sys = System::new();
+ let p = Pid::from_u32(pid);
+ sys.refresh_processes_specifics(ProcessesToUpdate::Some(&[p]), true, ProcessRefreshKind::nothing());
+ if let Some(proc_) = sys.process(p)
+ && proc_.name().to_string_lossy().to_ascii_lowercase().starts_with("sd-server")
+ {
+ proc_.kill();
+ let _ = proc_.wait();
+ }
+}
+
+/// Runs a short-lived sd-server command (e.g. `--help`, `--list-devices`) and returns output.
+pub fn run_server_probe(exe: &Path, args: &[&str], timeout: Duration) -> Option<String> {
+ let mut cmd = std::process::Command::new(exe);
+ cmd.args(args).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped());
+ if let Some(d) = exe.parent() {
+ cmd.current_dir(d);
+ }
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ cmd.creation_flags(CREATE_NO_WINDOW);
+ }
+ let child = cmd.spawn().ok()?;
+ let (tx, rx) = std::sync::mpsc::channel();
+ std::thread::spawn(move || {
+ let _ = tx.send(child.wait_with_output());
+ });
+ let out = rx.recv_timeout(timeout).ok()?.ok()?;
+ let mut s = String::from_utf8_lossy(&out.stdout).into_owned();
+ s.push('\n');
+ s.push_str(&String::from_utf8_lossy(&out.stderr));
+ Some(s)
+}
+
+/// Parses `--list-devices` output: `NAME<TAB>description` lines.
+pub fn parse_device_list(text: &str) -> Vec<(String, String)> {
+ text.lines()
+ .filter_map(|l| {
+ let (n, d) = l.split_once('\t')?;
+ let n = n.trim();
+ (!n.is_empty() && !n.contains(' ') && n.chars().all(|c| c.is_ascii_alphanumeric())).then(|| (n.to_string(), d.trim().to_string()))
+ })
+ .collect()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn default_launch_args() {
+ let mut cfg = AppConfig::default();
+ cfg.upscalers_dir = Some(std::env::temp_dir().join("qls-no-upscalers-here"));
+ let a = build_server_args(&cfg, cfg.profile());
+ let s = a.join(" ");
+ assert!(s.starts_with("--listen-ip 127.0.0.1 --listen-port 39150"));
+ assert!(s.contains(r"--diffusion-model C:\AI\sdcpp\models\qwen21\qwen-image-2.1-UC-Q4_K_M.gguf"));
+ assert!(s.contains(r"--vae C:\AI\sdcpp\models\qwen21\qwen_image_2.1_vae_bf16.safetensors"));
+ assert!(s.contains(r"--llm C:\AI\sdcpp\models\qwen21\Qwen3VL-8B-Instruct-Q4_K_M.gguf"));
+ assert!(s.contains(r"--llm_vision C:\AI\sdcpp\models\qwen21\mmproj-Qwen3VL-8B-Instruct-F16.gguf"));
+ assert!(s.contains("--backend cuda0 --params-backend te=cpu"));
+ assert!(s.contains("--fa --sage-attn --vae-tiling --vae-tile-size 768 --vae-tile-overlap 0.125"));
+ assert!(s.contains("--model-args qwen_image_2_1_prefix_cache_type=q8_0 --eager-load"));
+ assert!(s.ends_with("--max-vram -1"));
+ assert!(!s.contains("0.0.0.0"));
+ assert!(!s.contains("--hires-upscalers-dir"), "missing folder is not passed");
+ assert!(!s.contains("upscale-tile-size"));
+ }
+
+ #[test]
+ fn upscaler_args() {
+ let dir = tempfile::tempdir().unwrap();
+ let mut cfg = AppConfig::default();
+ cfg.upscalers_dir = Some(dir.path().to_path_buf());
+ cfg.upscale_tile_size = 256;
+ let a = build_server_args(&cfg, cfg.profile());
+ let i = a.iter().position(|x| x == "--hires-upscalers-dir").unwrap();
+ assert_eq!(a[i + 1], dir.path().to_string_lossy());
+ assert!(a.join(" ").contains("--upscale-tile-size 256 --hires-upscale-tile-size 256"));
+ }
+
+ /// Captured from sd-cli 3f8527a (bench hires_fast: 1376x768 -> ESRGAN -> 2048x1152,
+ /// 6 refine steps, EasyCache, 1024px VAE tiles). sd-server prints the same lines.
+ const HIRES_LOG: &str = "[INFO ] image.cpp:814 - generate_image 1376x768
+[INFO ] request.cpp:420 - sampling using Euler method
+[INFO ] image.cpp:529 - get_learned_condition completed, taking 1.14s
+[INFO ] image.cpp:866 - generating image: 1/1 - seed 42
+[INFO ] sample-cache.cpp:66 - EasyCache enabled - threshold: 0.200, start: 0.15, end: 0.95
+ |==> | 1/20 - 2.66s/it\u{1b}[K[INFO ] ggml_graph_cut.cpp:1034 - qwen_image_2_1 build cached graph cut plan done (taking 2 ms)
+ |==================================================| 20/20 - 1.63s/it\u{1b}[K
+[INFO ] image.cpp:899 - sampling completed, taking 17.40s
+[INFO ] image.cpp:924 - hires fix: upscaling to 2048x1152
+[INFO ] image.cpp:932 - hires fix: loading model upscaler from 'C:\\AI\\sdcpp\\models\\upscalers\\RealESRGAN_x4plus.pth'
+[INFO ] image.cpp:960 - hires fix: scheduler_steps=17, denoising_strength=0.35, sigma_sched_size=7
+[INFO ] ggml_graph_cut.cpp:1034 - wan_vae build cached graph cut plan done (taking 0 ms)
+ |##################################################| 128/128 - 2.23GB/s\u{1b}[K
+ |=========================> | 1/2 - 1.12s/it\u{1b}[K
+ |==================================================| 2/2 - 1.27it/s\u{1b}[K
+[INFO ] ggml_graph_cut.cpp:1034 - esrgan build cached graph cut plan done (taking 2 ms)
+ |> | 1/112 - 2.88it/s\u{1b}[K
+ |==================================================| 112/112 - 10.87it/s\u{1b}[K
+[INFO ] ggml_graph_cut.cpp:1034 - wan_vae build cached graph cut plan done (taking 0 ms)
+ |========> | 1/6 - 1.86it/s\u{1b}[K
+ |==================================================| 6/6 - 3.42it/s\u{1b}[K
+[INFO ] sample-cache.cpp:66 - EasyCache enabled - threshold: 0.200, start: 0.15, end: 0.95
+[INFO ] ggml_graph_cut.cpp:1034 - qwen_image_2_1 build cached graph cut plan done (taking 3 ms)
+ |========> | 1/6 - 4.02s/it\u{1b}[K[INFO ] ggml_graph_cut.cpp:1034 - qwen_image_2_1 build cached graph cut plan done (taking 3 ms)
+ |================> | 2/6 - 3.81s/it\u{1b}[K
+ |==================================================| 6/6 - 3.80s/it\u{1b}[K
+[INFO ] image.cpp:1024 - hires sampling 1/1 completed, taking 15.46s
+[INFO ] image.cpp:1036 - hires fix completed, taking 30.73s
+[INFO ] image.cpp:554 - decoding 1 latents
+ |========> | 1/6 - 1.07s/it\u{1b}[K
+[INFO ] image.cpp:620 - latent 1 decoded, taking 6.18s
+[INFO ] image.cpp:1050 - generate_image completed in 55.52s";
+
+ #[test]
+ fn progress_through_hires_refine() {
+ let mut p = ProgressParser::default();
+ let updates: Vec<BackendProgress> = HIRES_LOG.split(['\n', '\r']).filter_map(|l| p.feed(l)).collect();
+ let stages: Vec<BackendStage> = updates.iter().map(|u| u.stage).collect();
+ let pos = |s: BackendStage| stages.iter().position(|x| *x == s).unwrap_or_else(|| panic!("missing {s:?} in {stages:?}"));
+ assert!(pos(BackendStage::Generating) < pos(BackendStage::Upscaling));
+ assert!(pos(BackendStage::Upscaling) < pos(BackendStage::Refining));
+ assert!(pos(BackendStage::Refining) < pos(BackendStage::Decoding));
+ let base: Vec<(u32, u32)> = updates.iter().filter(|u| u.stage == BackendStage::Generating).filter_map(|u| u.step).collect();
+ assert_eq!(base, vec![(1, 20), (20, 20)]);
+ // VAE/ESRGAN tile bars (2, 112 and the 6-tile encode) never count as refine steps.
+ let refine: Vec<(u32, u32, Option<f32>)> =
+ updates.iter().filter(|u| u.stage == BackendStage::Refining).filter_map(|u| u.step.map(|s| (s.0, s.1, u.seconds_per_step))).collect();
+ assert_eq!(refine.iter().map(|r| (r.0, r.1)).collect::<Vec<_>>(), vec![(1, 6), (2, 6), (6, 6)]);
+ assert_eq!(refine[0].2, Some(4.02), "the 1.86it/s VAE tile bar was not taken");
+ assert!(updates.iter().filter(|u| u.stage == BackendStage::Upscaling).all(|u| u.step.is_none()));
+ assert_eq!(stages.last(), Some(&BackendStage::Finishing));
+ }
+
+ #[test]
+ fn placement_variants_and_reserve() {
+ let mut cfg = AppConfig::default();
+ cfg.text_encoder_placement = TextEncoderPlacement::Cpu;
+ cfg.vram_reserve_gib = 1.5;
+ cfg.flash_attention = false;
+ cfg.sage_attention = false;
+ cfg.vae_tile_size = 0;
+ cfg.extra_server_args = vec!["--vae-conv-direct".into()];
+ cfg.prefix_cache_type = "off".into();
+ cfg.eager_load = false;
+ let s = build_server_args(&cfg, cfg.profile()).join(" ");
+ assert!(s.contains("--model-args qwen_image_2_1_prefix_cache=false"));
+ assert!(!s.contains("--eager-load"));
+ assert!(s.contains("--backend diffusion=cuda0,vae=cuda0,te=cpu"));
+ assert!(s.contains("--max-vram -1.5"));
+ assert!(!s.contains("--fa"));
+ assert!(!s.contains("--sage-attn"));
+ assert!(!s.contains("--vae-tiling"));
+ assert!(s.ends_with("--vae-conv-direct"));
+ cfg.text_encoder_placement = TextEncoderPlacement::Auto;
+ cfg.vram_reserve_gib = 0.0;
+ cfg.prefix_cache_type = "auto".into();
+ let s = build_server_args(&cfg, cfg.profile()).join(" ");
+ assert!(!s.contains("--model-args"));
+ assert!(s.contains("--auto-fit on"));
+ assert!(!s.contains("--max-vram"));
+ }
+
+ #[test]
+ fn step_bar_parsing() {
+ assert_eq!(parse_step_bar(" |=====> | 2/20 - 1.99s/it"), Some((2, 20, Some(1.99))));
+ assert_eq!(parse_step_bar("|====| 4/8 - 2.00it/s"), Some((4, 8, Some(0.5))));
+ assert_eq!(parse_step_bar(" |############# | 98/397 - 3.76GB/s"), None);
+ assert_eq!(parse_step_bar("random text"), None);
+ }
+
+ /// Real log excerpt captured from sd-server 3f8527a during an edit job.
+ const EDIT_LOG: &str = "[INFO ] image.cpp:814 - generate_image 1024x1024
+[INFO ] diffusion_engine.cpp:3012 - Using 'qwen' preset for reference images
+[INFO ] request.cpp:420 - sampling using Euler method
+[INFO ] image.cpp:274 - EDIT mode
+ |##################################################| 98/98 - 728.50MB/s\u{1b}[K
+[INFO ] image.cpp:398 - encode_first_stage completed, taking 0.99s
+[INFO ] image.cpp:529 - get_learned_condition completed, taking 4.30s
+[INFO ] image.cpp:866 - generating image: 1/1 - seed 3
+ |==> | 1/20 - 12.44s/it\u{1b}[K\r |=====> | 2/20 - 2.57s/it\u{1b}[K\r |=======> | 3/20 - 2.47s/it
+[INFO ] image.cpp:899 - sampling completed, taking 53.57s
+[INFO ] image.cpp:554 - decoding 1 latents
+ |######################## | 59/128 - 931.44MB/s
+[INFO ] image.cpp:620 - latent 1 decoded, taking 1.15s
+[INFO ] image.cpp:1050 - generate_image completed in 61.38s";
+
+ #[test]
+ fn progress_from_real_log() {
+ let mut p = ProgressParser::default();
+ let updates: Vec<BackendProgress> = EDIT_LOG.split(['\n', '\r']).filter_map(|l| p.feed(l)).collect();
+ let stages: Vec<BackendStage> = updates.iter().map(|u| u.stage).collect();
+ assert_eq!(stages.first(), Some(&BackendStage::Preparing));
+ assert!(stages.contains(&BackendStage::EncodingImages));
+ assert!(stages.contains(&BackendStage::EncodingPrompt));
+ assert!(stages.contains(&BackendStage::Decoding));
+ assert_eq!(stages.last(), Some(&BackendStage::Finishing));
+ let steps: Vec<(u32, u32)> = updates.iter().filter_map(|u| u.step).collect();
+ assert_eq!(steps, vec![(1, 20), (2, 20), (3, 20)]);
+ let gen_ = updates.iter().find(|u| u.stage == BackendStage::Generating).unwrap();
+ assert_eq!(gen_.image, Some((1, 1)));
+ // The tensor-loading bar during decode must not be mistaken for steps.
+ assert!(updates.iter().all(|u| u.step.map(|s| s.1) != Some(128)));
+ }
+
+ #[test]
+ fn step_bar_followed_by_log_line_on_same_line() {
+ // Captured from sd-server 3f8527a: the step bar is immediately followed by a log line.
+ let mut p = ProgressParser::default();
+ p.feed("[INFO ] image.cpp:814 - generate_image 1376x768");
+ p.feed("[INFO ] image.cpp:866 - generating image: 1/1 - seed 7");
+ let u = p.feed(" |==> | 1/20 - 4.05s/it\u{1b}[K[INFO ] ggml_graph_cut.cpp:1034 - qwen_image_2_1 build cached graph cut plan done").unwrap();
+ assert_eq!(u.step, Some((1, 20)));
+ let u = p.feed(" |=====> | 20/20 - 2.01s/it\u{1b}[K[INFO ] image.cpp:899 - sampling completed, taking 41.67s").unwrap();
+ assert_eq!(u.step, Some((20, 20)));
+ }
+
+ #[test]
+ fn parser_ignores_lines_before_a_job() {
+ let mut p = ProgressParser::default();
+ assert!(p.feed(" |==> | 1/20 - 2.0s/it").is_none());
+ assert!(p.feed("[INFO] listening on: http://127.0.0.1:39150").is_none());
+ }
+
+ #[test]
+ fn device_list() {
+ let out = "ggml_cuda_init: found 1 CUDA devices:\n Device 0: NVIDIA GeForce RTX 5070 Ti, compute capability 12.0\nCUDA0\tNVIDIA GeForce RTX 5070 Ti\nCPU\tAMD Ryzen 7 7700 8-Core Processor \n";
+ assert_eq!(
+ parse_device_list(out),
+ vec![("CUDA0".into(), "NVIDIA GeForce RTX 5070 Ti".into()), ("CPU".into(), "AMD Ryzen 7 7700 8-Core Processor".into())]
+ );
+ }
+}
diff --git a/crates/qls-core/src/sdcpp.rs b/crates/qls-core/src/sdcpp.rs
new file mode 100644
index 0000000..03b86c2
--- /dev/null
+++ b/crates/qls-core/src/sdcpp.rs
@@ -0,0 +1,586 @@
+//! Inference adapter for stable-diffusion.cpp's native async API (`/sdcpp/v1/*`).
+//!
+//! This is the only module that knows the sd-server wire format. Schemas were verified
+//! against examples/server (api.md, routes_sdcpp.cpp, async_jobs.h) at commit 3f8527a:
+//! GET /sdcpp/v1/capabilities
+//! POST /sdcpp/v1/img_gen -> 202 {id, kind, status, created, poll_url}
+//! GET /sdcpp/v1/jobs/{id} -> {status: queued|generating|completed|failed|cancelled, ...}
+//! POST /sdcpp/v1/jobs/{id}/cancel -> 200, or 409 while generating (not interruptible)
+//! POST /sdcpp/v1/upscale -> 200 {images, upscaler, scale, width, height} (sync ESRGAN)
+//!
+//! Request objects are merged field by field over the server's launch defaults
+//! (`SDGenerationParams::from_json_str`), so omitted fields keep the CLI values.
+
+use std::time::Duration;
+
+use base64::Engine;
+use serde::{Deserialize, Serialize};
+
+use crate::error::{AppError, ErrorCode};
+
+// ---------------------------------------------------------------------------------------
+// Request
+// ---------------------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Default, Serialize, PartialEq)]
+pub struct Guidance {
+ pub txt_cfg: f32,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub img_cfg: Option<f32>,
+}
+
+#[derive(Debug, Clone, Default, Serialize, PartialEq)]
+pub struct SampleParams {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub sample_method: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub scheduler: Option<String>,
+ pub sample_steps: u32,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub flow_shift: Option<f32>,
+ pub guidance: Guidance,
+}
+
+#[derive(Debug, Clone, Default, Serialize, PartialEq)]
+pub struct VaeTilingParams {
+ pub enabled: bool,
+ /// Image pixels; 0 = backend default (256).
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub tile_size_w: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub tile_size_h: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub target_overlap: Option<f32>,
+}
+
+/// Second pass of `img_gen` (`hires`): the first result is upscaled to the target size
+/// (`upscaler` = built-in filter or an ESRGAN model stem from `--hires-upscalers-dir`)
+/// and re-sampled with `denoising_strength`. Reference latents and the inpaint mask are
+/// carried into the second pass (src/pipeline/image.cpp, commit 3f8527a).
+#[derive(Debug, Clone, Default, Serialize, PartialEq)]
+pub struct HiresParams {
+ pub enabled: bool,
+ pub upscaler: String,
+ pub target_width: u32,
+ pub target_height: u32,
+ /// Effective refine steps (the server scales the schedule by the denoise strength).
+ pub steps: u32,
+ pub denoising_strength: f32,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub upscale_tile_size: Option<u32>,
+}
+
+/// Body of `POST /sdcpp/v1/img_gen`. Images are base64 PNG strings.
+#[derive(Debug, Clone, Default, Serialize, PartialEq)]
+pub struct ImgGenRequest {
+ pub prompt: String,
+ pub negative_prompt: String,
+ pub width: u32,
+ pub height: u32,
+ pub seed: i64,
+ pub batch_count: u32,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub strength: Option<f32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub init_image: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub mask_image: Option<String>,
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub ref_images: Vec<String>,
+ /// Our images already arrive at exact working geometry, so input transforms are
+ /// disabled (`mode=none`) to guarantee no crop/stretch happens server-side.
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub image_preprocess: Vec<String>,
+ pub sample_params: SampleParams,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub vae_tiling_params: Option<VaeTilingParams>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub hires: Option<HiresParams>,
+ /// e.g. "easycache"; applies to both passes. Omitted = server default.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cache_mode: Option<String>,
+ /// e.g. "threshold=0.2".
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub cache_option: Option<String>,
+ pub output_format: String,
+ /// We write our own metadata after post-processing.
+ pub embed_image_metadata: bool,
+}
+
+pub fn b64(bytes: &[u8]) -> String {
+ base64::engine::general_purpose::STANDARD.encode(bytes)
+}
+
+pub fn b64_decode(s: &str) -> Result<Vec<u8>, AppError> {
+ let s = s.split_once(";base64,").map(|(_, d)| d).unwrap_or(s);
+ base64::engine::general_purpose::STANDARD
+ .decode(s.trim())
+ .map_err(|e| AppError::new(ErrorCode::GenerationFailed, "The inference server returned an unreadable image.").detail(e.to_string()))
+}
+
+// ---------------------------------------------------------------------------------------
+// Responses
+// ---------------------------------------------------------------------------------------
+
+#[derive(Debug, Clone, Deserialize, Serialize, Default)]
+pub struct CapModel {
+ #[serde(default)]
+ pub name: String,
+ #[serde(default)]
+ pub stem: String,
+ #[serde(default)]
+ pub path: String,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize, Default)]
+pub struct CapLimits {
+ #[serde(default)]
+ pub min_width: u32,
+ #[serde(default)]
+ pub max_width: u32,
+ #[serde(default)]
+ pub min_height: u32,
+ #[serde(default)]
+ pub max_height: u32,
+ #[serde(default)]
+ pub max_batch_count: u32,
+ #[serde(default)]
+ pub max_queue_size: u32,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize, Default, PartialEq)]
+pub struct CapUpscaler {
+ #[serde(default)]
+ pub name: String,
+ /// True for a model-backed upscaler (false for built-in filters).
+ #[serde(default)]
+ pub model: bool,
+ /// Usable with `POST /sdcpp/v1/upscale` (RGB ESRGAN models).
+ #[serde(default)]
+ pub image_upscale: bool,
+}
+
+#[derive(Debug, Clone, Deserialize, Serialize, Default)]
+pub struct Capabilities {
+ #[serde(default)]
+ pub model: CapModel,
+ #[serde(default)]
+ pub supported_modes: Vec<String>,
+ #[serde(default)]
+ pub samplers: Vec<String>,
+ #[serde(default)]
+ pub schedulers: Vec<String>,
+ #[serde(default)]
+ pub output_formats: Vec<String>,
+ #[serde(default)]
+ pub limits: CapLimits,
+ #[serde(default)]
+ pub features_by_mode: serde_json::Value,
+ #[serde(default)]
+ pub defaults_by_mode: serde_json::Value,
+ #[serde(default)]
+ pub upscalers: Vec<CapUpscaler>,
+ /// Whether any RGB ESRGAN model is available for `/sdcpp/v1/upscale`.
+ #[serde(default)]
+ pub upscale: bool,
+}
+
+impl Capabilities {
+ pub fn img_feature(&self, name: &str) -> bool {
+ self.features_by_mode.get("img_gen").and_then(|f| f.get(name)).and_then(|v| v.as_bool()).unwrap_or(false)
+ }
+ pub fn supports_img_gen(&self) -> bool {
+ self.supported_modes.iter().any(|m| m == "img_gen")
+ }
+ /// True when `name` is a model-backed upscaler the server can load (hires and,
+ /// if `image` is set, the standalone upscale endpoint).
+ pub fn has_upscaler(&self, name: &str, image: bool) -> bool {
+ self.upscalers.iter().any(|u| u.model && u.name == name && (!image || u.image_upscale))
+ }
+ /// True when the loaded diffusion model is the file we expect (path compare is
+ /// case/slash-insensitive, since Windows paths come back with forward slashes).
+ pub fn model_matches(&self, expected: &std::path::Path) -> bool {
+ let norm = |s: &str| s.replace('\\', "/").to_ascii_lowercase();
+ let want = norm(&expected.to_string_lossy());
+ let got = norm(&self.model.path);
+ if !got.is_empty() {
+ return got == want || want.ends_with(&got) || got.ends_with(&want);
+ }
+ let file = expected.file_name().map(|f| f.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
+ self.model.name.to_ascii_lowercase() == file
+ }
+}
+
+#[derive(Debug, Clone, Deserialize)]
+pub struct JobAccepted {
+ pub id: String,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum BackendJobStatus {
+ Queued,
+ Generating,
+ Completed,
+ Failed,
+ Cancelled,
+ #[serde(other)]
+ Unknown,
+}
+
+#[derive(Debug, Clone, Deserialize, Default)]
+pub struct JobError {
+ #[serde(default)]
+ pub code: String,
+ #[serde(default)]
+ pub message: String,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+pub struct JobImage {
+ #[serde(default)]
+ pub index: u32,
+ pub b64_json: String,
+}
+
+#[derive(Debug, Clone, Deserialize, Default)]
+pub struct JobResult {
+ #[serde(default)]
+ pub images: Vec<JobImage>,
+ #[serde(default)]
+ pub output_format: String,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+pub struct BackendJob {
+ pub id: String,
+ pub status: BackendJobStatus,
+ #[serde(default)]
+ pub queue_position: u32,
+ #[serde(default)]
+ pub result: Option<JobResult>,
+ #[serde(default)]
+ pub error: Option<JobError>,
+}
+
+/// Body of `POST /sdcpp/v1/upscale`.
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct UpscaleRequest {
+ pub image: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub upscaler: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub tile_size: Option<u32>,
+ pub output_format: String,
+}
+
+#[derive(Debug, Clone, Deserialize)]
+pub struct UpscaleResponse {
+ #[serde(default)]
+ pub images: Vec<JobImage>,
+ #[serde(default)]
+ pub upscaler: String,
+ #[serde(default)]
+ pub scale: u32,
+ #[serde(default)]
+ pub width: u32,
+ #[serde(default)]
+ pub height: u32,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum CancelOutcome {
+ Cancelled,
+ /// The backend cannot interrupt a job that is already generating.
+ NotInterruptible,
+ AlreadyFinished,
+ NotFound,
+}
+
+// ---------------------------------------------------------------------------------------
+// Client
+// ---------------------------------------------------------------------------------------
+
+#[derive(Clone)]
+pub struct SdcppClient {
+ base: String,
+ http: reqwest::Client,
+}
+
+fn unavailable(e: impl std::fmt::Display) -> AppError {
+ AppError::new(ErrorCode::ServerUnavailable, "The inference server is not reachable.").detail(e.to_string())
+}
+
+impl SdcppClient {
+ pub fn new(port: u16) -> Self {
+ let http = reqwest::Client::builder()
+ .no_proxy()
+ .connect_timeout(Duration::from_secs(3))
+ .build()
+ .expect("http client");
+ Self { base: format!("http://127.0.0.1:{port}"), http }
+ }
+
+ pub fn base_url(&self) -> &str {
+ &self.base
+ }
+
+ pub async fn capabilities(&self, timeout: Duration) -> Result<Capabilities, AppError> {
+ let r = self.http.get(format!("{}/sdcpp/v1/capabilities", self.base)).timeout(timeout).send().await.map_err(unavailable)?;
+ if !r.status().is_success() {
+ return Err(AppError::new(ErrorCode::ServerUnavailable, "The inference server did not report its capabilities.")
+ .detail(format!("HTTP {}", r.status())));
+ }
+ r.json::<Capabilities>().await.map_err(|e| {
+ AppError::new(ErrorCode::Unsupported, "The program on the inference port does not look like stable-diffusion.cpp.").detail(e.to_string())
+ })
+ }
+
+ pub async fn submit(&self, req: &ImgGenRequest) -> Result<JobAccepted, AppError> {
+ let body = serde_json::to_vec(req).map_err(AppError::internal)?;
+ let r = self
+ .http
+ .post(format!("{}/sdcpp/v1/img_gen", self.base))
+ .header("Content-Type", "application/json")
+ .body(body)
+ .timeout(Duration::from_secs(120))
+ .send()
+ .await
+ .map_err(unavailable)?;
+ let status = r.status().as_u16();
+ let text = r.text().await.unwrap_or_default();
+ match status {
+ 200 | 202 => serde_json::from_str(&text)
+ .map_err(|e| AppError::new(ErrorCode::Unsupported, "Unexpected reply from the inference server.").detail(format!("{e}: {text}"))),
+ 429 => Err(AppError::new(ErrorCode::QueueFull, "The inference server queue is full.").detail(text)),
+ 400 => Err(AppError::new(ErrorCode::MalformedRequest, "The inference server rejected the request.").detail(text)),
+ _ => Err(AppError::new(ErrorCode::GenerationFailed, "The inference server returned an error.").detail(format!("HTTP {status}: {text}"))),
+ }
+ }
+
+ /// Synchronous ESRGAN pass. It waits for the server's generation lock, so the
+ /// timeout covers a job that might still be finishing.
+ pub async fn upscale(&self, req: &UpscaleRequest) -> Result<UpscaleResponse, AppError> {
+ let body = serde_json::to_vec(req).map_err(AppError::internal)?;
+ let r = self
+ .http
+ .post(format!("{}/sdcpp/v1/upscale", self.base))
+ .header("Content-Type", "application/json")
+ .body(body)
+ .timeout(Duration::from_secs(600))
+ .send()
+ .await
+ .map_err(unavailable)?;
+ let status = r.status().as_u16();
+ let text = r.text().await.unwrap_or_default();
+ let server_error = || serde_json::from_str::<serde_json::Value>(&text).ok().and_then(|v| v["error"].as_str().map(str::to_owned)).unwrap_or_else(|| text.clone());
+ match status {
+ 200 => {
+ let resp: UpscaleResponse = serde_json::from_str(&text)
+ .map_err(|e| AppError::new(ErrorCode::Unsupported, "Unexpected reply from the upscaler.").detail(format!("{e}: {}", &text[..text.len().min(300)])))?;
+ if resp.images.is_empty() {
+ return Err(AppError::new(ErrorCode::GenerationFailed, "The upscaler returned no image."));
+ }
+ Ok(resp)
+ }
+ 404 => Err(AppError::new(ErrorCode::Unsupported, "This sd-server build has no upscale endpoint.").detail(text)),
+ 400 => Err(AppError::new(ErrorCode::MalformedRequest, "The upscaler rejected the image.").detail(server_error())),
+ _ => Err(AppError::new(ErrorCode::GenerationFailed, "The upscaler failed.").detail(format!("HTTP {status}: {}", server_error()))),
+ }
+ }
+
+ pub async fn job(&self, id: &str) -> Result<BackendJob, AppError> {
+ let r = self
+ .http
+ .get(format!("{}/sdcpp/v1/jobs/{}", self.base, id))
+ .timeout(Duration::from_secs(60))
+ .send()
+ .await
+ .map_err(unavailable)?;
+ match r.status().as_u16() {
+ 200 => r.json().await.map_err(|e| AppError::new(ErrorCode::Unsupported, "Unexpected job status format.").detail(e.to_string())),
+ 404 | 410 => Err(AppError::new(ErrorCode::NotFound, "The inference job is no longer known to the server.")),
+ s => Err(AppError::new(ErrorCode::GenerationFailed, "Could not read job status.").detail(format!("HTTP {s}"))),
+ }
+ }
+
+ pub async fn cancel(&self, id: &str) -> Result<CancelOutcome, AppError> {
+ let r = self
+ .http
+ .post(format!("{}/sdcpp/v1/jobs/{}/cancel", self.base, id))
+ .timeout(Duration::from_secs(10))
+ .send()
+ .await
+ .map_err(unavailable)?;
+ let status = r.status().as_u16();
+ Ok(match status {
+ 200 => {
+ let job: Option<BackendJob> = r.json().await.ok();
+ match job.map(|j| j.status) {
+ Some(BackendJobStatus::Cancelled) | None => CancelOutcome::Cancelled,
+ _ => CancelOutcome::AlreadyFinished,
+ }
+ }
+ 409 => CancelOutcome::NotInterruptible,
+ 404 | 410 => CancelOutcome::NotFound,
+ _ => CancelOutcome::NotInterruptible,
+ })
+ }
+}
+
+/// Parses `stable-diffusion.cpp version X, commit abc123` from `--help` output.
+pub fn parse_version_banner(text: &str) -> Option<String> {
+ let line = text.lines().find(|l| l.contains("stable-diffusion.cpp version"))?;
+ Some(line.trim().trim_start_matches("stable-diffusion.cpp").trim().to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn request_serialization_matches_native_schema() {
+ let req = ImgGenRequest {
+ prompt: "change the red car to a black Porsche".into(),
+ negative_prompt: String::new(),
+ width: 1920,
+ height: 1088,
+ seed: 42,
+ batch_count: 1,
+ strength: None,
+ init_image: None,
+ mask_image: None,
+ ref_images: vec!["AAA".into(), "BBB".into()],
+ image_preprocess: vec!["target=ref,mode=none".into()],
+ sample_params: SampleParams {
+ sample_method: Some("euler".into()),
+ scheduler: None,
+ sample_steps: 30,
+ flow_shift: None,
+ guidance: Guidance { txt_cfg: 6.0, img_cfg: None },
+ },
+ vae_tiling_params: None,
+ hires: None,
+ cache_mode: None,
+ cache_option: None,
+ output_format: "png".into(),
+ embed_image_metadata: false,
+ };
+ let v: serde_json::Value = serde_json::to_value(&req).unwrap();
+ assert_eq!(v["width"], 1920);
+ assert_eq!(v["height"], 1088);
+ assert_eq!(v["sample_params"]["sample_method"], "euler");
+ assert_eq!(v["sample_params"]["sample_steps"], 30);
+ assert_eq!(v["sample_params"]["guidance"]["txt_cfg"], 6.0);
+ assert!(v["sample_params"].get("scheduler").is_none(), "omitted -> backend default");
+ assert!(v["sample_params"]["guidance"].get("img_cfg").is_none());
+ assert_eq!(v["ref_images"][0], "AAA");
+ assert_eq!(v["ref_images"][1], "BBB", "reference order preserved");
+ assert!(v.get("init_image").is_none());
+ assert!(v.get("mask_image").is_none());
+ assert!(v.get("strength").is_none());
+ assert!(v.get("vae_tiling_params").is_none());
+ assert_eq!(v["embed_image_metadata"], false);
+ assert_eq!(v["image_preprocess"][0], "target=ref,mode=none");
+ assert!(v.get("hires").is_none() && v.get("cache_mode").is_none() && v.get("cache_option").is_none(), "server defaults apply");
+ }
+
+ #[test]
+ fn hires_cache_and_tiling_serialization() {
+ let req = ImgGenRequest {
+ prompt: "a cabin".into(),
+ width: 1376,
+ height: 768,
+ hires: Some(HiresParams {
+ enabled: true,
+ upscaler: "RealESRGAN_x4plus".into(),
+ target_width: 2048,
+ target_height: 1152,
+ steps: 6,
+ denoising_strength: 0.35,
+ upscale_tile_size: None,
+ }),
+ cache_mode: Some("easycache".into()),
+ cache_option: Some("threshold=0.2".into()),
+ vae_tiling_params: Some(VaeTilingParams { enabled: false, ..Default::default() }),
+ ..Default::default()
+ };
+ let v = serde_json::to_value(&req).unwrap();
+ assert_eq!(v["hires"]["enabled"], true);
+ assert_eq!(v["hires"]["upscaler"], "RealESRGAN_x4plus");
+ assert_eq!((v["hires"]["target_width"].as_u64(), v["hires"]["target_height"].as_u64()), (Some(2048), Some(1152)));
+ assert_eq!(v["hires"]["steps"], 6);
+ assert!((v["hires"]["denoising_strength"].as_f64().unwrap() - 0.35).abs() < 1e-6);
+ assert!(v["hires"].get("upscale_tile_size").is_none());
+ assert!(v["hires"].get("scale").is_none(), "target size wins over scale");
+ assert_eq!(v["cache_mode"], "easycache");
+ assert_eq!(v["cache_option"], "threshold=0.2");
+ // Only `enabled` is sent, so the server keeps its configured tile size.
+ assert_eq!(v["vae_tiling_params"], serde_json::json!({"enabled": false}));
+ }
+
+ #[test]
+ fn upscale_request_and_response() {
+ let r = UpscaleRequest { image: "AAA".into(), upscaler: Some("RealESRGAN_x4plus".into()), tile_size: None, output_format: "png".into() };
+ assert_eq!(serde_json::to_value(&r).unwrap(), serde_json::json!({"image": "AAA", "upscaler": "RealESRGAN_x4plus", "output_format": "png"}));
+ let resp: UpscaleResponse = serde_json::from_str(
+ r#"{"images":[{"index":0,"b64_json":"iVBOR"}],"upscaler":"RealESRGAN_x4plus","scale":4,"repeats":1,"width":5504,"height":3072,"output_format":"png"}"#,
+ )
+ .unwrap();
+ assert_eq!((resp.scale, resp.width, resp.height), (4, 5504, 3072));
+ assert_eq!(resp.images[0].b64_json, "iVBOR");
+ }
+
+ #[test]
+ fn job_status_parsing() {
+ let done = r#"{"completed":1791295347,"created":1791295301,"error":null,"id":"job_1","kind":"img_gen","queue_position":0,
+ "result":{"images":[{"b64_json":"iVBORw0K","index":0}],"output_format":"png"},"started":1791295302,"status":"completed"}"#;
+ let j: BackendJob = serde_json::from_str(done).unwrap();
+ assert_eq!(j.status, BackendJobStatus::Completed);
+ assert_eq!(j.result.unwrap().images[0].b64_json, "iVBORw0K");
+ let failed = r#"{"id":"job_2","status":"failed","error":{"code":"generation_failed","message":"generate_image returned empty results"}}"#;
+ let j: BackendJob = serde_json::from_str(failed).unwrap();
+ assert_eq!(j.status, BackendJobStatus::Failed);
+ assert_eq!(j.error.unwrap().code, "generation_failed");
+ let weird: BackendJob = serde_json::from_str(r#"{"id":"x","status":"paused"}"#).unwrap();
+ assert_eq!(weird.status, BackendJobStatus::Unknown);
+ }
+
+ #[test]
+ fn capabilities_parsing_and_model_match() {
+ let caps: Capabilities = serde_json::from_str(r#"{"model":{"name":"qwen-image-2.1-UC-Q4_K_M.gguf","path":"C:/AI/sdcpp/models/qwen21/qwen-image-2.1-UC-Q4_K_M.gguf","stem":"x"},
+ "supported_modes":["img_gen"],"features_by_mode":{"img_gen":{"cancel_generating":false,"ref_images":true}},
+ "limits":{"max_width":4096,"max_height":4096,"min_width":64,"min_height":64,"max_batch_count":8,"max_queue_size":64}}"#).unwrap();
+ assert!(caps.supports_img_gen());
+ assert!(caps.img_feature("ref_images"));
+ assert!(!caps.img_feature("cancel_generating"));
+ assert!(caps.model_matches(std::path::Path::new(r"C:\AI\sdcpp\models\qwen21\qwen-image-2.1-UC-Q4_K_M.gguf")));
+ assert!(!caps.model_matches(std::path::Path::new(r"C:\AI\sdcpp\models\other.gguf")));
+ assert_eq!(caps.limits.max_width, 4096);
+ assert!(!caps.upscale && caps.upscalers.is_empty(), "older servers: no upscaler fields");
+
+ let caps: Capabilities = serde_json::from_str(
+ r#"{"upscale":true,"upscalers":[{"name":"Lanczos","model":false,"image_upscale":false},
+ {"name":"RealESRGAN_x4plus","model":true,"image_upscale":true},{"name":"ltx_latent","model":true,"image_upscale":false}]}"#,
+ )
+ .unwrap();
+ assert!(caps.upscale);
+ assert!(caps.has_upscaler("RealESRGAN_x4plus", true));
+ assert!(caps.has_upscaler("ltx_latent", false) && !caps.has_upscaler("ltx_latent", true));
+ assert!(!caps.has_upscaler("Lanczos", false), "built-in filters are not models");
+ }
+
+ #[test]
+ fn base64_roundtrip_and_data_urls() {
+ let data = vec![0u8, 1, 2, 250];
+ assert_eq!(b64_decode(&b64(&data)).unwrap(), data);
+ assert_eq!(b64_decode(&format!("data:image/png;base64,{}", b64(&data))).unwrap(), data);
+ assert!(b64_decode("!!!").is_err());
+ }
+
+ #[test]
+ fn version_banner() {
+ assert_eq!(parse_version_banner("stable-diffusion.cpp version unknown, commit 3f8527a\nUsage: ...").unwrap(), "version unknown, commit 3f8527a");
+ assert!(parse_version_banner("nothing").is_none());
+ }
+}
diff --git a/crates/qls-core/src/store.rs b/crates/qls-core/src/store.rs
new file mode 100644
index 0000000..3fb122f
--- /dev/null
+++ b/crates/qls-core/src/store.rs
@@ -0,0 +1,520 @@
+//! Local persistence: SQLite gallery of generations, content-addressed input images,
+//! and the metadata written into PNG files. Nothing leaves the machine.
+
+use std::path::{Path, PathBuf};
+use std::sync::Mutex;
+
+use rusqlite::{Connection, OptionalExtension, params};
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+
+use crate::config::RefineMode;
+use crate::error::{AppError, AppResult, ErrorCode};
+use crate::geometry::{Expansion, Size};
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct ReferenceRecord {
+ pub index: usize,
+ /// Content-addressed copy of the reference (always available for reopening).
+ pub input_id: String,
+ #[serde(default)]
+ pub original_path: Option<String>,
+ pub width: u32,
+ pub height: u32,
+}
+
+/// How the pixels were produced beyond a single diffusion pass (Details panel).
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
+#[serde(default)]
+pub struct PipelineRecord {
+ /// First pass of a two-pass job (the refine ran at `working_*`).
+ pub base: Option<Size>,
+ pub refine: Option<RefineMode>,
+ pub refine_steps: Option<u32>,
+ pub refine_denoise: Option<f32>,
+ /// Upscaler between the passes ("RealESRGAN_x4plus" or "Lanczos").
+ pub hires_upscaler: Option<String>,
+ /// EasyCache threshold used for sampling.
+ pub cache_threshold: Option<f32>,
+ /// How the result was enlarged to its final size, when it was ("RealESRGAN_x4plus" or "Lanczos").
+ pub enlarged_with: Option<String>,
+ /// Size the content had before the final enlargement.
+ pub enlarged_from: Option<Size>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct GenerationRecord {
+ pub id: String,
+ pub created_at: String,
+ pub mode: String,
+ pub prompt: String,
+ pub negative_prompt: String,
+ pub seed: i64,
+ pub width: u32,
+ pub height: u32,
+ pub working_width: u32,
+ pub working_height: u32,
+ pub model: String,
+ pub sampler: String,
+ pub scheduler: Option<String>,
+ pub steps: u32,
+ pub cfg: f32,
+ pub strength: Option<f32>,
+ pub quality: String,
+ pub resolution: String,
+ pub references: Vec<ReferenceRecord>,
+ pub mask_input_id: Option<String>,
+ pub outpaint: Option<Expansion>,
+ pub file_path: String,
+ #[serde(default)]
+ pub extra_paths: Vec<String>,
+ pub favorite: bool,
+ pub parent_id: Option<String>,
+ pub duration_ms: u64,
+ pub notes: Vec<String>,
+ pub app_version: String,
+ pub backend_version: Option<String>,
+ pub client: Option<String>,
+ /// Full original request, for exact "reopen".
+ #[serde(default)]
+ pub request: serde_json::Value,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub pipeline: Option<PipelineRecord>,
+}
+
+impl GenerationRecord {
+ /// AUTOMATIC1111-style "parameters" text understood by many image tools.
+ pub fn parameters_text(&self) -> String {
+ let mut s = self.prompt.clone();
+ if !self.negative_prompt.is_empty() {
+ s.push_str(&format!("\nNegative prompt: {}", self.negative_prompt));
+ }
+ s.push_str(&format!(
+ "\nSteps: {}, Sampler: {}, Schedule type: {}, CFG scale: {}, Seed: {}, Size: {}x{}, Model: {}",
+ self.steps,
+ self.sampler,
+ self.scheduler.as_deref().unwrap_or("default"),
+ self.cfg,
+ self.seed,
+ self.width,
+ self.height,
+ self.model
+ ));
+ if let Some(st) = self.strength {
+ s.push_str(&format!(", Denoising strength: {st}"));
+ }
+ if let Some(p) = &self.pipeline
+ && let Some(base) = p.base
+ {
+ let factor = self.working_width as f64 / base.width.max(1) as f64;
+ s.push_str(&format!(
+ ", Hires upscale: {factor:.2}, Hires steps: {}, Hires upscaler: {}",
+ p.refine_steps.unwrap_or(0),
+ p.hires_upscaler.as_deref().unwrap_or("Lanczos")
+ ));
+ if let Some(d) = p.refine_denoise {
+ s.push_str(&format!(", Hires denoising strength: {d}"));
+ }
+ }
+ s.push_str(&format!(", Mode: {}, Version: Qwen Local Studio {}", self.mode, self.app_version));
+ s
+ }
+
+ pub fn png_text(&self) -> Vec<(&'static str, String)> {
+ let mut slim = self.clone();
+ slim.request = serde_json::Value::Null;
+ vec![
+ ("parameters", self.parameters_text()),
+ ("qls:generation", serde_json::to_string(&slim).unwrap_or_default()),
+ ("Software", format!("Qwen Local Studio {}", self.app_version)),
+ ]
+ }
+
+ pub fn from_png_text(text: &[(String, String)]) -> Option<Self> {
+ text.iter().find(|(k, _)| k == "qls:generation").and_then(|(_, v)| serde_json::from_str(v).ok())
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct InputRecord {
+ pub id: String,
+ pub path: String,
+ pub original_name: Option<String>,
+ pub original_path: Option<String>,
+ pub width: u32,
+ pub height: u32,
+ pub format: String,
+ pub has_alpha: bool,
+ pub created_at: String,
+ /// HEIC with an ISO 21496-1 HDR gain map.
+ #[serde(default)]
+ pub hdr: bool,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Default)]
+pub struct ListQuery {
+ #[serde(default)]
+ pub q: Option<String>,
+ #[serde(default)]
+ pub favorites: bool,
+ #[serde(default)]
+ pub limit: Option<u32>,
+ #[serde(default)]
+ pub offset: Option<u32>,
+ /// "recent" (default) or "oldest".
+ #[serde(default)]
+ pub sort: Option<String>,
+}
+
+pub struct Store {
+ conn: Mutex<Connection>,
+ pub data_dir: PathBuf,
+}
+
+fn db_err(e: rusqlite::Error) -> AppError {
+ AppError::new(ErrorCode::Internal, "The local gallery database reported an error.").detail(e.to_string())
+}
+
+pub fn now_rfc3339() -> String {
+ chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true)
+}
+
+pub fn new_id() -> String {
+ // Time-ordered prefix keeps file listings chronological.
+ format!("{}{}", chrono::Utc::now().format("%Y%m%d%H%M%S"), &uuid::Uuid::new_v4().simple().to_string()[..8])
+}
+
+impl Store {
+ pub fn open(data_dir: &Path) -> AppResult<Self> {
+ std::fs::create_dir_all(data_dir.join("inputs")).map_err(|e| AppError::io("create the data folder", data_dir, e))?;
+ std::fs::create_dir_all(data_dir.join("thumbs")).map_err(|e| AppError::io("create the data folder", data_dir, e))?;
+ let conn = Connection::open(data_dir.join("gallery.db")).map_err(db_err)?;
+ Self::init(conn, data_dir)
+ }
+
+ pub fn open_in_memory(data_dir: &Path) -> AppResult<Self> {
+ Self::init(Connection::open_in_memory().map_err(db_err)?, data_dir)
+ }
+
+ fn init(conn: Connection, data_dir: &Path) -> AppResult<Self> {
+ conn.execute_batch(
+ "PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA foreign_keys=ON;
+ CREATE TABLE IF NOT EXISTS generations (
+ id TEXT PRIMARY KEY,
+ created_at TEXT NOT NULL,
+ prompt TEXT NOT NULL,
+ mode TEXT NOT NULL,
+ favorite INTEGER NOT NULL DEFAULT 0,
+ file_path TEXT NOT NULL,
+ record TEXT NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS gen_created ON generations(created_at);
+ CREATE INDEX IF NOT EXISTS gen_fav ON generations(favorite);
+ CREATE TABLE IF NOT EXISTS inputs (
+ id TEXT PRIMARY KEY,
+ created_at TEXT NOT NULL,
+ record TEXT NOT NULL
+ );",
+ )
+ .map_err(db_err)?;
+ conn.pragma_update(None, "user_version", 1).map_err(db_err)?;
+ Ok(Self { conn: Mutex::new(conn), data_dir: data_dir.to_path_buf() })
+ }
+
+ pub fn thumb_path(&self, id: &str) -> PathBuf {
+ self.data_dir.join("thumbs").join(format!("{id}.jpg"))
+ }
+
+ pub fn insert_generation(&self, r: &GenerationRecord) -> AppResult<()> {
+ let json = serde_json::to_string(r).map_err(AppError::internal)?;
+ self.conn
+ .lock()
+ .unwrap()
+ .execute(
+ "INSERT OR REPLACE INTO generations (id, created_at, prompt, mode, favorite, file_path, record) VALUES (?1,?2,?3,?4,?5,?6,?7)",
+ params![r.id, r.created_at, r.prompt, r.mode, r.favorite as i32, r.file_path, json],
+ )
+ .map_err(db_err)?;
+ Ok(())
+ }
+
+ pub fn get_generation(&self, id: &str) -> AppResult<GenerationRecord> {
+ let json: Option<String> = self
+ .conn
+ .lock()
+ .unwrap()
+ .query_row("SELECT record FROM generations WHERE id = ?1", [id], |r| r.get(0))
+ .optional()
+ .map_err(db_err)?;
+ let json = json.ok_or_else(|| AppError::new(ErrorCode::NotFound, "That image is no longer in the gallery."))?;
+ let mut rec: GenerationRecord = serde_json::from_str(&json).map_err(AppError::internal)?;
+ rec.favorite = self.is_favorite(id)?;
+ Ok(rec)
+ }
+
+ fn is_favorite(&self, id: &str) -> AppResult<bool> {
+ let v: Option<i32> = self
+ .conn
+ .lock()
+ .unwrap()
+ .query_row("SELECT favorite FROM generations WHERE id = ?1", [id], |r| r.get(0))
+ .optional()
+ .map_err(db_err)?;
+ Ok(v.unwrap_or(0) != 0)
+ }
+
+ pub fn list_generations(&self, q: &ListQuery) -> AppResult<(Vec<GenerationRecord>, u64)> {
+ let limit = q.limit.unwrap_or(60).clamp(1, 500);
+ let offset = q.offset.unwrap_or(0);
+ let order = if q.sort.as_deref() == Some("oldest") { "ASC" } else { "DESC" };
+ let pattern = q.q.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(|s| {
+ let esc = s.replace('\\', "\\\\").replace('%', "\\%").replace('_', "\\_");
+ format!("%{esc}%")
+ });
+ let where_ = "WHERE (?1 IS NULL OR prompt LIKE ?1 ESCAPE '\\' OR mode LIKE ?1 ESCAPE '\\') AND (?2 = 0 OR favorite = 1)";
+ let conn = self.conn.lock().unwrap();
+ let total: i64 = conn
+ .query_row(&format!("SELECT COUNT(*) FROM generations {where_}"), params![pattern, q.favorites as i32], |r| r.get(0))
+ .map_err(db_err)?;
+ let mut stmt = conn
+ .prepare(&format!("SELECT record, favorite FROM generations {where_} ORDER BY created_at {order}, id {order} LIMIT ?3 OFFSET ?4"))
+ .map_err(db_err)?;
+ let rows = stmt
+ .query_map(params![pattern, q.favorites as i32, limit, offset], |r| Ok((r.get::<_, String>(0)?, r.get::<_, i32>(1)?)))
+ .map_err(db_err)?;
+ let mut out = Vec::new();
+ for row in rows {
+ let (json, fav) = row.map_err(db_err)?;
+ if let Ok(mut rec) = serde_json::from_str::<GenerationRecord>(&json) {
+ rec.favorite = fav != 0;
+ out.push(rec);
+ }
+ }
+ Ok((out, total.max(0) as u64))
+ }
+
+ pub fn set_favorite(&self, id: &str, fav: bool) -> AppResult<()> {
+ let n = self.conn.lock().unwrap().execute("UPDATE generations SET favorite = ?2 WHERE id = ?1", params![id, fav as i32]).map_err(db_err)?;
+ if n == 0 {
+ return Err(AppError::new(ErrorCode::NotFound, "That image is no longer in the gallery."));
+ }
+ Ok(())
+ }
+
+ /// Removes the record, its image file (only if inside the app output folder) and thumbnail.
+ pub fn delete_generation(&self, id: &str, output_root: &Path) -> AppResult<()> {
+ let rec = self.get_generation(id)?;
+ self.conn.lock().unwrap().execute("DELETE FROM generations WHERE id = ?1", [id]).map_err(db_err)?;
+ let f = PathBuf::from(&rec.file_path);
+ if crate::paths::is_within(&f, &[output_root.to_path_buf()]) {
+ let _ = std::fs::remove_file(&f);
+ }
+ let _ = std::fs::remove_file(self.thumb_path(id));
+ Ok(())
+ }
+
+ // ---- inputs -----------------------------------------------------------------------
+
+ /// Stores input bytes content-addressed (deduplicated). Original bytes are kept so
+ /// EXIF/ICC survive for reopening.
+ pub fn put_input(&self, bytes: &[u8], original_name: Option<&str>, original_path: Option<&str>) -> AppResult<InputRecord> {
+ let img = crate::imaging::decode_image(bytes)?;
+ let hash = hex::encode(Sha256::digest(bytes));
+ let id = hash[..24].to_string();
+ if let Ok(existing) = self.get_input(&id)
+ && Path::new(&existing.path).is_file()
+ {
+ return Ok(existing);
+ }
+ let ext = match img.format {
+ "jpeg" => "jpg",
+ f => f,
+ };
+ let path = self.data_dir.join("inputs").join(format!("{id}.{ext}"));
+ std::fs::write(&path, bytes).map_err(|e| AppError::io("store the image", &path, e))?;
+ let thumb = crate::imaging::thumbnail(&img.pixels, 384);
+ if let Ok(j) = crate::imaging::encode_jpeg(&thumb, 85) {
+ let _ = std::fs::write(self.data_dir.join("inputs").join(format!("{id}.thumb.jpg")), j);
+ }
+ if img.format == "heic" {
+ // The UI's WebView cannot show HEIC: keep a full-size JPEG to display instead.
+ let j = crate::imaging::encode_jpeg(&img.pixels, 92)?;
+ std::fs::write(self.input_display_path(&id), j).map_err(|e| AppError::io("store the image", &path, e))?;
+ }
+ let rec = InputRecord {
+ id: id.clone(),
+ path: path.to_string_lossy().into_owned(),
+ original_name: original_name.map(str::to_owned),
+ original_path: original_path.map(str::to_owned),
+ width: img.pixels.width(),
+ height: img.pixels.height(),
+ format: img.format.to_string(),
+ has_alpha: img.has_transparency,
+ created_at: now_rfc3339(),
+ hdr: img.format == "heic" && crate::heif::gain_map(bytes).is_some(),
+ };
+ let json = serde_json::to_string(&rec).map_err(AppError::internal)?;
+ self.conn
+ .lock()
+ .unwrap()
+ .execute("INSERT OR REPLACE INTO inputs (id, created_at, record) VALUES (?1,?2,?3)", params![id, rec.created_at, json])
+ .map_err(db_err)?;
+ Ok(rec)
+ }
+
+ pub fn get_input(&self, id: &str) -> AppResult<InputRecord> {
+ if !id.chars().all(|c| c.is_ascii_hexdigit()) {
+ return Err(AppError::new(ErrorCode::NotFound, "Unknown input image."));
+ }
+ let json: Option<String> = self
+ .conn
+ .lock()
+ .unwrap()
+ .query_row("SELECT record FROM inputs WHERE id = ?1", [id], |r| r.get(0))
+ .optional()
+ .map_err(db_err)?;
+ let json = json.ok_or_else(|| AppError::new(ErrorCode::NotFound, "Unknown input image."))?;
+ serde_json::from_str(&json).map_err(AppError::internal)
+ }
+
+ pub fn input_thumb_path(&self, id: &str) -> PathBuf {
+ self.data_dir.join("inputs").join(format!("{id}.thumb.jpg"))
+ }
+
+ /// Full-size JPEG shown in the UI for inputs the WebView cannot display (HEIC).
+ pub fn input_display_path(&self, id: &str) -> PathBuf {
+ self.data_dir.join("inputs").join(format!("{id}.display.jpg"))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn rec(id: &str, prompt: &str, created: &str) -> GenerationRecord {
+ GenerationRecord {
+ id: id.into(),
+ created_at: created.into(),
+ mode: "generate".into(),
+ prompt: prompt.into(),
+ negative_prompt: "blurry".into(),
+ seed: 1234,
+ width: 1024,
+ height: 1024,
+ working_width: 1024,
+ working_height: 1024,
+ model: "qwen-image-2.1-UC-Q4_K_M".into(),
+ sampler: "euler".into(),
+ scheduler: None,
+ steps: 30,
+ cfg: 6.0,
+ strength: None,
+ quality: "balanced".into(),
+ resolution: "auto".into(),
+ references: vec![ReferenceRecord { index: 0, input_id: "abc".into(), original_path: Some(r"C:\a.png".into()), width: 10, height: 20 }],
+ mask_input_id: None,
+ outpaint: Some(Expansion { left: 1, right: 2, top: 3, bottom: 4 }),
+ file_path: r"C:\out\x.png".into(),
+ extra_paths: vec![],
+ favorite: false,
+ parent_id: None,
+ duration_ms: 5000,
+ notes: vec!["n".into()],
+ app_version: "1.0.0".into(),
+ backend_version: Some("commit 3f8527a".into()),
+ client: Some("ui".into()),
+ request: serde_json::json!({"prompt": prompt}),
+ pipeline: None,
+ }
+ }
+
+ #[test]
+ fn pipeline_metadata_roundtrip_and_parameters() {
+ let mut r = rec("g2", "a cabin", "2026-10-06T10:00:00.000Z");
+ r.working_width = 2048;
+ r.working_height = 1152;
+ r.pipeline = Some(PipelineRecord {
+ base: Some(Size::new(1376, 768)),
+ refine: Some(RefineMode::Fast),
+ refine_steps: Some(6),
+ refine_denoise: Some(0.35),
+ hires_upscaler: Some("RealESRGAN_x4plus".into()),
+ cache_threshold: Some(0.2),
+ enlarged_with: Some("RealESRGAN_x4plus".into()),
+ enlarged_from: Some(Size::new(2048, 1152)),
+ });
+ let text = r.png_text();
+ let params_ = &text.iter().find(|(k, _)| *k == "parameters").unwrap().1;
+ assert!(params_.contains("Hires upscale: 1.49, Hires steps: 6, Hires upscaler: RealESRGAN_x4plus, Hires denoising strength: 0.35"), "{params_}");
+ let owned: Vec<(String, String)> = text.into_iter().map(|(k, v)| (k.to_string(), v)).collect();
+ let back = GenerationRecord::from_png_text(&owned).unwrap();
+ assert_eq!(back.pipeline, r.pipeline);
+ // Records written before this field existed still load.
+ let mut v = serde_json::to_value(rec("g3", "x", "t")).unwrap();
+ v.as_object_mut().unwrap().remove("pipeline");
+ assert_eq!(serde_json::from_value::<GenerationRecord>(v).unwrap().pipeline, None);
+ }
+
+ #[test]
+ fn metadata_serialization_roundtrip_via_png() {
+ let r = rec("g1", "a red fox in snow", "2026-10-06T10:00:00.000Z");
+ let img = image::RgbaImage::from_pixel(4, 4, image::Rgba([1, 2, 3, 255]));
+ let text = r.png_text();
+ let pairs: Vec<(&str, &str)> = text.iter().map(|(k, v)| (*k, v.as_str())).collect();
+ let png = crate::imaging::encode_png(&img, &pairs, None, true).unwrap();
+ let back = crate::imaging::decode_image(&png).unwrap();
+ let parsed = GenerationRecord::from_png_text(&back.text).unwrap();
+ let mut expected = r.clone();
+ expected.request = serde_json::Value::Null;
+ assert_eq!(parsed, expected);
+ let params_ = back.text.iter().find(|(k, _)| k == "parameters").unwrap().1.clone();
+ assert!(params_.starts_with("a red fox in snow\nNegative prompt: blurry\nSteps: 30, Sampler: euler"));
+ assert!(params_.contains("Seed: 1234, Size: 1024x1024"));
+ }
+
+ #[test]
+ fn gallery_crud_search_favorites_sort() {
+ let dir = tempfile::tempdir().unwrap();
+ let s = Store::open(dir.path()).unwrap();
+ s.insert_generation(&rec("a", "a red fox", "2026-10-06T10:00:00.000Z")).unwrap();
+ s.insert_generation(&rec("b", "blue whale 100%", "2026-10-06T11:00:00.000Z")).unwrap();
+ s.insert_generation(&rec("c", "red car", "2026-10-06T12:00:00.000Z")).unwrap();
+ let (all, total) = s.list_generations(&ListQuery::default()).unwrap();
+ assert_eq!(total, 3);
+ assert_eq!(all.iter().map(|r| r.id.as_str()).collect::<Vec<_>>(), vec!["c", "b", "a"]);
+ let (red, _) = s.list_generations(&ListQuery { q: Some("red".into()), ..Default::default() }).unwrap();
+ assert_eq!(red.len(), 2);
+ let (pct, _) = s.list_generations(&ListQuery { q: Some("100%".into()), ..Default::default() }).unwrap();
+ assert_eq!(pct.len(), 1, "LIKE wildcards are escaped");
+ s.set_favorite("a", true).unwrap();
+ let (fav, n) = s.list_generations(&ListQuery { favorites: true, ..Default::default() }).unwrap();
+ assert_eq!((fav.len(), n, fav[0].favorite), (1, 1, true));
+ let (old, _) = s.list_generations(&ListQuery { sort: Some("oldest".into()), limit: Some(1), ..Default::default() }).unwrap();
+ assert_eq!(old[0].id, "a");
+ assert!(s.get_generation("a").unwrap().favorite);
+ s.delete_generation("a", dir.path()).unwrap();
+ assert_eq!(s.get_generation("a").unwrap_err().code, ErrorCode::NotFound);
+ assert!(s.set_favorite("zzz", true).is_err());
+ // Reopen persists.
+ drop(s);
+ let s = Store::open(dir.path()).unwrap();
+ assert_eq!(s.list_generations(&ListQuery::default()).unwrap().1, 2);
+ assert_eq!(s.get_generation("c").unwrap().references[0].input_id, "abc");
+ }
+
+ #[test]
+ fn inputs_are_deduplicated() {
+ let dir = tempfile::tempdir().unwrap();
+ let s = Store::open(dir.path()).unwrap();
+ let img = image::RgbaImage::from_pixel(30, 20, image::Rgba([5, 6, 7, 255]));
+ let png = crate::imaging::encode_png(&img, &[], None, true).unwrap();
+ let a = s.put_input(&png, Some("x.png"), None).unwrap();
+ let b = s.put_input(&png, Some("y.png"), None).unwrap();
+ assert_eq!(a.id, b.id);
+ assert_eq!((a.width, a.height), (30, 20));
+ assert!(Path::new(&a.path).is_file());
+ assert!(s.input_thumb_path(&a.id).is_file());
+ assert!(s.get_input("../../etc").is_err());
+ assert!(s.put_input(b"garbage", None, None).is_err());
+ }
+}
diff --git a/crates/qls-core/src/wic.rs b/crates/qls-core/src/wic.rs
new file mode 100644
index 0000000..8edf1ed
--- /dev/null
+++ b/crates/qls-core/src/wic.rs
@@ -0,0 +1,103 @@
+//! Decoding through Windows Imaging Component, for formats the `image` crate lacks (HEIC).
+//! HEIC needs Microsoft's "HEIF Image Extensions" + "HEVC Video Extensions" (Store).
+
+use image::RgbaImage;
+
+/// Pixels (orientation as the codec presents them) and the embedded ICC profile.
+pub struct WicImage {
+ pub pixels: RgbaImage,
+ pub icc_profile: Option<Vec<u8>>,
+}
+
+#[cfg(windows)]
+pub fn decode(bytes: &[u8]) -> Result<WicImage, String> {
+ use windows::Win32::Graphics::Imaging::*;
+ use windows::Win32::System::Com::*;
+ use windows::core::GUID;
+
+ // COM per call: the caller may be any tokio blocking thread. S_FALSE (already
+ // initialised) is fine; RPC_E_CHANGED_MODE means an STA thread, which also works.
+ let init = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) };
+ let _guard = init.is_ok().then_some(ComGuard);
+
+ let codec = |e: windows::core::Error| {
+ format!("Windows could not decode the image ({e}). For HEIC photos install \"HEIF Image Extensions\" and \"HEVC Video Extensions\" from the Microsoft Store.")
+ };
+ unsafe {
+ let factory: IWICImagingFactory = CoCreateInstance(&CLSID_WICImagingFactory, None, CLSCTX_INPROC_SERVER).map_err(|e| e.to_string())?;
+ let stream = factory.CreateStream().map_err(|e| e.to_string())?;
+ stream.InitializeFromMemory(bytes).map_err(|e| e.to_string())?;
+ let decoder = factory.CreateDecoderFromStream(&stream, std::ptr::null(), WICDecodeMetadataCacheOnDemand).map_err(codec)?;
+ let frame = decoder.GetFrame(0).map_err(codec)?;
+ let (mut w, mut h) = (0u32, 0u32);
+ frame.GetSize(&mut w, &mut h).map_err(codec)?;
+ if w == 0 || h == 0 || (w as u64 * h as u64) > crate::imaging::MAX_INPUT_PIXELS {
+ return Err(format!("Image too large ({w}×{h})."));
+ }
+
+ let converter = factory.CreateFormatConverter().map_err(|e| e.to_string())?;
+ let rgba: GUID = GUID_WICPixelFormat32bppRGBA;
+ converter.Initialize(&frame, &rgba, WICBitmapDitherTypeNone, None, 0.0, WICBitmapPaletteTypeCustom).map_err(codec)?;
+ let mut buf = vec![0u8; w as usize * h as usize * 4];
+ converter.CopyPixels(std::ptr::null(), w * 4, &mut buf).map_err(codec)?;
+ let pixels = RgbaImage::from_raw(w, h, buf).ok_or("pixel buffer size mismatch")?;
+
+ Ok(WicImage { pixels, icc_profile: icc_profile(&factory, &frame) })
+ }
+}
+
+#[cfg(windows)]
+unsafe fn icc_profile(factory: &windows::Win32::Graphics::Imaging::IWICImagingFactory, frame: &windows::Win32::Graphics::Imaging::IWICBitmapFrameDecode) -> Option<Vec<u8>> {
+ use windows::Win32::Graphics::Imaging::*;
+ unsafe {
+ let mut n = 0u32;
+ frame.GetColorContexts(&mut [], &mut n).ok()?;
+ if n == 0 {
+ return None;
+ }
+ let ctx: Vec<IWICColorContext> = (0..n).filter_map(|_| factory.CreateColorContext().ok()).collect();
+ let mut slots: Vec<Option<IWICColorContext>> = ctx.iter().cloned().map(Some).collect();
+ frame.GetColorContexts(&mut slots, &mut n).ok()?;
+ for c in ctx.iter().take(n as usize) {
+ if c.GetType().ok()? != WICColorContextProfile {
+ continue;
+ }
+ let mut len = 0u32;
+ c.GetProfileBytes(&mut [], &mut len).ok()?;
+ let mut v = vec![0u8; len as usize];
+ c.GetProfileBytes(&mut v, &mut len).ok()?;
+ if len > 128 {
+ v.truncate(len as usize);
+ return Some(v);
+ }
+ }
+ None
+ }
+}
+
+#[cfg(windows)]
+struct ComGuard;
+
+#[cfg(windows)]
+impl Drop for ComGuard {
+ fn drop(&mut self) {
+ unsafe { windows::Win32::System::Com::CoUninitialize() }
+ }
+}
+
+#[cfg(not(windows))]
+pub fn decode(_bytes: &[u8]) -> Result<WicImage, String> {
+ Err("HEIC images can only be opened on Windows.".into())
+}
+
+#[cfg(test)]
+mod tests {
+ /// Run with QLS_TEST_HEIC=<path to a .HEIC> (needs the Store HEIF/HEVC extensions).
+ #[test]
+ fn decodes_real_heic() {
+ let Ok(p) = std::env::var("QLS_TEST_HEIC") else { return };
+ let img = super::decode(&std::fs::read(p).unwrap()).unwrap();
+ println!("WIC: {}x{}, icc {:?} bytes", img.pixels.width(), img.pixels.height(), img.icc_profile.as_ref().map(|v| v.len()));
+ assert!(img.pixels.width() > 0);
+ }
+}
diff --git a/crates/qls-service/Cargo.toml b/crates/qls-service/Cargo.toml
new file mode 100644
index 0000000..30837d1
--- /dev/null
+++ b/crates/qls-service/Cargo.toml
@@ -0,0 +1,18 @@
+[package]
+name = "qls-service"
+version.workspace = true
+edition.workspace = true
+
+[dependencies]
+axum = "0.8.9"
+futures-util = "0.3.34"
+qls-core = { version = "1.0.0", path = "../qls-core" }
+serde = { version = "1.0.229", features = ["derive"] }
+serde_json = "1.0.151"
+tokio = { version = "1.53.2", features = ["full"] }
+tokio-stream = { version = "0.1.19", features = ["sync"] }
+tower-http = { version = "0.7.1", features = ["cors", "limit"] }
+tracing = "0.1.44"
+tracing-appender = "0.2.5"
+tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
+uuid = { version = "1.27.0", features = ["v4"] }
diff --git a/crates/qls-service/src/api.rs b/crates/qls-service/src/api.rs
new file mode 100644
index 0000000..ac2a364
--- /dev/null
+++ b/crates/qls-service/src/api.rs
@@ -0,0 +1,752 @@
+//! Stable local API, versioned under /api/v1. Loopback-only, token-protected, and
+//! independent of sd-server's own schema (the engine adapts between the two).
+
+use std::convert::Infallible;
+use std::path::{Path, PathBuf};
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+use axum::{
+ Json, Router,
+ body::{Body, Bytes},
+ extract::{DefaultBodyLimit, Path as AxPath, Query, Request, State},
+ http::{HeaderMap, HeaderValue, Method, StatusCode, header},
+ middleware::{self, Next},
+ response::{IntoResponse, Response, Sse, sse::Event as SseEvent},
+ routing::{get, post},
+};
+use futures_util::stream::Stream;
+use qls_core::{
+ config::AppConfig,
+ diagnostics,
+ engine::{APP_VERSION, JobView},
+ error::{AppError, ErrorCode},
+ geometry::{ExpansionUnits, Size, aspect_label},
+ imaging, paths,
+ planner::{GenerationRequest, Mode, OutpaintSpec, Quality, UpscaleMethod, UpscaleSpec},
+ store::{GenerationRecord, ListQuery},
+};
+use serde::Deserialize;
+use serde_json::{Value, json};
+use tokio_stream::StreamExt;
+
+use crate::{AppState, Lease};
+
+type St = State<Arc<AppState>>;
+
+struct ApiError(AppError);
+
+impl From<AppError> for ApiError {
+ fn from(e: AppError) -> Self {
+ Self(e)
+ }
+}
+
+impl IntoResponse for ApiError {
+ fn into_response(self) -> Response {
+ let status = StatusCode::from_u16(self.0.http_status()).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
+ (status, Json(json!({ "error": self.0 }))).into_response()
+ }
+}
+
+type ApiResult<T> = Result<T, ApiError>;
+
+const ALLOWED_ORIGINS: &[&str] = &["http://tauri.localhost", "https://tauri.localhost", "tauri://localhost", "http://localhost:1420"];
+
+pub fn router(state: Arc<AppState>) -> Router {
+ let api = Router::new()
+ .route("/status", get(status))
+ .route("/setup", get(setup))
+ .route("/config", get(get_config).put(put_config))
+ .route("/backend/start", post(backend_start))
+ .route("/backend/stop", post(backend_stop))
+ .route("/backend/restart", post(backend_restart))
+ .route("/diagnostics", get(diagnostics_json))
+ .route("/logs", get(logs))
+ .route("/plan", post(plan))
+ .route("/jobs", get(list_jobs).post(create_job))
+ .route("/jobs/{id}", get(get_job))
+ .route("/jobs/{id}/cancel", post(cancel_job))
+ .route("/jobs/{id}/wait", get(wait_job))
+ .route("/generate", post(op_generate))
+ .route("/edit", post(op_edit))
+ .route("/inpaint", post(op_inpaint))
+ .route("/outpaint", post(op_outpaint))
+ .route("/upscale", post(op_upscale))
+ .route("/events", get(events))
+ .route("/inputs/import", post(import_input))
+ .route("/inputs/{id}", get(get_input))
+ .route("/inputs/{id}/image", get(input_image))
+ .route("/inputs/{id}/thumb", get(input_thumb))
+ .route("/gallery", get(gallery_list))
+ .route("/gallery/{id}", get(gallery_get).patch(gallery_patch).delete(gallery_delete))
+ .route("/gallery/{id}/image", get(gallery_image))
+ .route("/gallery/{id}/thumb", get(gallery_thumb))
+ .route("/gallery/{id}/export", post(gallery_export))
+ .route("/image-info", post(image_info))
+ .route("/session/heartbeat", post(heartbeat))
+ .route("/session/release", post(release))
+ .route("/shutdown", post(shutdown))
+ .layer(middleware::from_fn_with_state(state.clone(), auth))
+ .layer(DefaultBodyLimit::max(4 * 1024 * 1024));
+ let uploads = Router::new().route("/inputs", post(upload_input)).layer(DefaultBodyLimit::max(210 * 1024 * 1024));
+ Router::new()
+ .route("/api/v1/ping", get(ping))
+ .nest("/api/v1", api.merge(uploads.layer(middleware::from_fn_with_state(state.clone(), auth))))
+ .layer(middleware::from_fn(cors))
+ .with_state(state)
+}
+
+/// CORS for the desktop webview origins only; everything else gets no CORS headers.
+async fn cors(req: Request, next: Next) -> Response {
+ let origin = req.headers().get(header::ORIGIN).and_then(|o| o.to_str().ok()).map(str::to_owned);
+ let allowed = origin.as_deref().filter(|o| ALLOWED_ORIGINS.contains(o)).map(str::to_owned);
+ if req.method() == Method::OPTIONS {
+ let mut r = StatusCode::NO_CONTENT.into_response();
+ if let Some(o) = allowed {
+ set_cors(r.headers_mut(), &o);
+ }
+ return r;
+ }
+ let mut r = next.run(req).await;
+ // Windows PowerShell 5.1 decodes JSON without an explicit charset as Latin-1.
+ if r.headers().get(header::CONTENT_TYPE).map(|v| v == "application/json").unwrap_or(false) {
+ r.headers_mut().insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json; charset=utf-8"));
+ }
+ if let Some(o) = allowed {
+ set_cors(r.headers_mut(), &o);
+ }
+ // Responses differ by Origin (CORS headers), so caches must not reuse one for the other.
+ r.headers_mut().insert(header::VARY, HeaderValue::from_static("Origin"));
+ r
+}
+
+fn set_cors(h: &mut HeaderMap, origin: &str) {
+ if let Ok(v) = HeaderValue::from_str(origin) {
+ h.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, v);
+ }
+ h.insert(header::ACCESS_CONTROL_ALLOW_METHODS, HeaderValue::from_static("GET, POST, PUT, PATCH, DELETE, OPTIONS"));
+ h.insert(header::ACCESS_CONTROL_ALLOW_HEADERS, HeaderValue::from_static("authorization, content-type, x-filename"));
+ h.insert(header::VARY, HeaderValue::from_static("Origin"));
+}
+
+/// Bearer token (or `?token=` for <img>/EventSource), and a foreign-Origin block so web
+/// pages open in a browser cannot drive the local API.
+async fn auth(State(s): St, req: Request, next: Next) -> Response {
+ if let Some(o) = req.headers().get(header::ORIGIN).and_then(|o| o.to_str().ok())
+ && !ALLOWED_ORIGINS.contains(&o)
+ {
+ return ApiError(AppError::new(ErrorCode::Unauthorized, "Requests from web pages are not allowed.")).into_response();
+ }
+ let header_tok = req
+ .headers()
+ .get(header::AUTHORIZATION)
+ .and_then(|v| v.to_str().ok())
+ .and_then(|v| v.strip_prefix("Bearer "))
+ .map(str::to_owned);
+ let query_tok = req.uri().query().and_then(|q| q.split('&').find_map(|kv| kv.strip_prefix("token=")).map(str::to_owned));
+ let ok = header_tok.or(query_tok).map(|t| constant_eq(t.as_bytes(), s.token.as_bytes())).unwrap_or(false);
+ if !ok {
+ return ApiError(AppError::new(ErrorCode::Unauthorized, "Missing or invalid API token (see service.json).")).into_response();
+ }
+ s.engine.touch();
+ next.run(req).await
+}
+
+fn constant_eq(a: &[u8], b: &[u8]) -> bool {
+ a.len() == b.len() && a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
+}
+
+async fn ping() -> Json<Value> {
+ Json(json!({ "service": "qwen-local-studio", "version": APP_VERSION }))
+}
+
+// ---------------------------------------------------------------------------------------
+// Status, setup, config, backend
+// ---------------------------------------------------------------------------------------
+
+async fn status(State(s): St) -> Json<Value> {
+ let e = s.engine.clone();
+ let gpu = tokio::task::spawn_blocking(move || e.gpu()).await.ok().flatten();
+ let srv = s.engine.server.status();
+ let jobs = s.engine.jobs();
+ let queued = jobs.iter().filter(|j| j.status == qls_core::engine::JobStatus::Queued).count();
+ let cfg = s.engine.config();
+ Json(json!({
+ "service": { "version": APP_VERSION, "pid": std::process::id(), "uptime_s": s.started.elapsed().as_secs() },
+ "server": {
+ "state": srv.state, "owned": srv.owned, "pid": srv.pid, "port": cfg.server_port,
+ "model": srv.model, "model_loaded": srv.state == qls_core::process::ServerState::Ready,
+ "error": srv.error,
+ "cancel_generating": srv.capabilities.as_ref().map(|c| c.img_feature("cancel_generating")),
+ "samplers": srv.capabilities.as_ref().map(|c| c.samplers.clone()).unwrap_or_default(),
+ "schedulers": srv.capabilities.as_ref().map(|c| c.schedulers.clone()).unwrap_or_default(),
+ "upscale": srv.capabilities.as_ref().map(|c| c.upscale),
+ },
+ "upscaler": { "model": cfg.upscaler_model, "available": cfg.upscaler_file().is_some(), "refine_mode": cfg.refine_mode },
+ "profile": { "id": cfg.profile().id, "display_name": cfg.profile().display_name },
+ "gpu": gpu,
+ "active_job": s.engine.active_job(),
+ "queue": { "queued": queued, "jobs": jobs.iter().filter(|j| !j.status.is_terminal()).collect::<Vec<_>>() },
+ "setup_complete": cfg.setup_complete,
+ }))
+}
+
+async fn setup(State(s): St) -> ApiResult<Json<Value>> {
+ let cfg = s.engine.config();
+ let srv_ok = s.engine.server.status().state == qls_core::process::ServerState::Ready;
+ let report = tokio::task::spawn_blocking(move || diagnostics::setup_checks(&cfg, Some(srv_ok))).await.map_err(AppError::internal)?;
+ Ok(Json(serde_json::to_value(report).unwrap()))
+}
+
+async fn get_config(State(s): St) -> Json<AppConfig> {
+ Json(s.engine.config())
+}
+
+async fn put_config(State(s): St, Json(cfg): Json<AppConfig>) -> ApiResult<Json<Value>> {
+ let restart = s.engine.set_config(cfg)?;
+ let st = s.engine.server.status();
+ if restart && st.owned && st.state == qls_core::process::ServerState::Ready && !s.engine.has_pending_work() {
+ s.engine.server.stop().await;
+ s.engine.emit_server();
+ }
+ Ok(Json(json!({ "saved": true, "backend_restart_needed": restart })))
+}
+
+async fn backend_start(State(s): St) -> ApiResult<Json<Value>> {
+ let cfg = s.engine.config();
+ let engine = s.engine.clone();
+ engine.emit_server();
+ let r = engine.server.ensure_ready(&cfg).await;
+ engine.emit_server();
+ let caps = r?;
+ Ok(Json(json!({ "ready": true, "model": caps.model.name })))
+}
+
+async fn backend_stop(State(s): St) -> Json<Value> {
+ let stopped = s.engine.server.stop().await;
+ s.engine.emit_server();
+ Json(json!({ "stopped": stopped }))
+}
+
+async fn backend_restart(State(s): St) -> ApiResult<Json<Value>> {
+ s.engine.server.stop().await;
+ backend_start(State(s)).await
+}
+
+async fn diagnostics_json(State(s): St) -> ApiResult<Json<Value>> {
+ let engine = s.engine.clone();
+ let v = tokio::task::spawn_blocking(move || {
+ let cfg = engine.config();
+ let gpus = diagnostics::query_gpus();
+ let srv = engine.server.status();
+ let version = engine.backend_version();
+ let devices = diagnostics::list_devices(&cfg.server_exe());
+ let log = engine.server.log.tail(300);
+ let args = qls_core::process::build_server_args(&cfg, cfg.profile());
+ let mut text = String::new();
+ use std::fmt::Write;
+ let _ = writeln!(text, "Qwen Local Studio {APP_VERSION} — diagnostics ({})", qls_core::store::now_rfc3339());
+ let _ = writeln!(text, "\n[GPU]");
+ match &gpus {
+ Some(g) => {
+ for x in g {
+ let _ = writeln!(text, "{} — {} MiB total, {} MiB used, {} MiB free, driver {}", x.name, x.memory_total_mib, x.memory_used_mib, x.memory_free_mib, x.driver_version);
+ }
+ }
+ None => {
+ let _ = writeln!(text, "nvidia-smi not available");
+ }
+ }
+ let _ = writeln!(text, "Backend devices: {}", devices.iter().map(|(n, d)| format!("{n} ({d})")).collect::<Vec<_>>().join(", "));
+ let cuda = devices.iter().any(|(n, _)| n.to_ascii_lowercase().starts_with("cuda"));
+ let _ = writeln!(text, "CUDA backend: {}", if cuda { "available" } else { "NOT available" });
+ let _ = writeln!(text, "\n[Inference server]");
+ let _ = writeln!(text, "stable-diffusion.cpp: {}", version.clone().unwrap_or_else(|| "unknown".into()));
+ let _ = writeln!(text, "State: {:?}, owned: {}, pid: {:?}, port: {}", srv.state, srv.owned, srv.pid, cfg.server_port);
+ if let Some(e) = &srv.error {
+ let _ = writeln!(text, "Last error: {} {}", e.message, e.detail.clone().unwrap_or_default());
+ }
+ let _ = writeln!(text, "Launch: sd-server.exe {}", args.join(" "));
+ if let Some(c) = &srv.capabilities {
+ let _ = writeln!(text, "Model: {} ({})", c.model.name, c.model.path);
+ let _ = writeln!(text, "Modes: {:?}; limits {}..{} px; features {}", c.supported_modes, c.limits.min_width, c.limits.max_width, c.features_by_mode);
+ let models: Vec<&str> = c.upscalers.iter().filter(|u| u.model).map(|u| u.name.as_str()).collect();
+ let _ = writeln!(text, "Upscalers: {} (image upscale: {})", if models.is_empty() { "none".into() } else { models.join(", ") }, c.upscale);
+ }
+ let _ = writeln!(text, "\n[Configuration]");
+ let _ = writeln!(text, "sdcpp dir: {}", cfg.sdcpp_dir.display());
+ for (label, p, _) in cfg.profile().files() {
+ let _ = writeln!(text, "{label}: {} ({})", p.display(), if p.is_file() { "ok" } else { "MISSING" });
+ }
+ let _ = writeln!(text, "Device: {}, text encoder: {:?}, VRAM reserve: {} GiB, flash attention: {}, sage attention: {}", cfg.device, cfg.text_encoder_placement, cfg.vram_reserve_gib, cfg.flash_attention, cfg.sage_attention);
+ let _ = writeln!(text, "VAE tile size: {}, refine: {:?}, upscale tile size: {}", cfg.vae_tile_size, cfg.refine_mode, cfg.upscale_tile_size);
+ let up = diagnostics::upscaler_check(&cfg);
+ let _ = writeln!(text, "ESRGAN upscaler: {}", up.detail);
+ let _ = writeln!(text, "Ports: server {}, service {}", cfg.server_port, cfg.service_port);
+ let _ = writeln!(text, "Output: {}", cfg.output_dir.display());
+ let _ = writeln!(text, "Data: {}", qls_core::config::data_dir().display());
+ let _ = writeln!(text, "\n[Server log — last {} lines]", log.len());
+ for l in &log {
+ let _ = writeln!(text, "{l}");
+ }
+ json!({
+ "gpus": gpus, "devices": devices, "cuda_available": cuda, "backend_version": version,
+ "server": srv, "launch_args": args, "config": cfg, "log": log, "text": text,
+ })
+ })
+ .await
+ .map_err(AppError::internal)?;
+ Ok(Json(v))
+}
+
+#[derive(Deserialize)]
+struct LinesQ {
+ lines: Option<usize>,
+}
+
+async fn logs(State(s): St, Query(q): Query<LinesQ>) -> Json<Value> {
+ Json(json!({ "lines": s.engine.server.log.tail(q.lines.unwrap_or(200).min(4000)) }))
+}
+
+// ---------------------------------------------------------------------------------------
+// Jobs
+// ---------------------------------------------------------------------------------------
+
+#[derive(Deserialize)]
+struct JobBody {
+ #[serde(flatten)]
+ request: GenerationRequest,
+ /// Caller's project folder (MCP): relative paths resolve here; allowed output root.
+ #[serde(default)]
+ workspace: Option<String>,
+}
+
+fn workspace_path(w: Option<&str>) -> Result<Option<PathBuf>, AppError> {
+ match w {
+ Some(w) if !w.trim().is_empty() => {
+ let p = paths::normalize(w, None)?;
+ if !p.is_dir() {
+ return Err(AppError::new(ErrorCode::InvalidPath, format!("Workspace folder not found: {}", p.display())));
+ }
+ Ok(Some(p))
+ }
+ _ => Ok(None),
+ }
+}
+
+async fn create_job(State(s): St, Json(b): Json<JobBody>) -> ApiResult<(StatusCode, Json<JobView>)> {
+ let ws = workspace_path(b.workspace.as_deref())?;
+ let j = s.engine.submit(b.request, ws)?;
+ Ok((StatusCode::ACCEPTED, Json(j)))
+}
+
+async fn list_jobs(State(s): St) -> Json<Vec<JobView>> {
+ Json(s.engine.jobs())
+}
+
+async fn get_job(State(s): St, AxPath(id): AxPath<String>) -> ApiResult<Json<JobView>> {
+ Ok(Json(s.engine.job(&id).ok_or_else(|| AppError::new(ErrorCode::NotFound, "Unknown job."))?))
+}
+
+async fn cancel_job(State(s): St, AxPath(id): AxPath<String>) -> ApiResult<Json<JobView>> {
+ Ok(Json(s.engine.cancel(&id)?))
+}
+
+#[derive(Deserialize)]
+struct WaitQ {
+ timeout: Option<u64>,
+}
+
+async fn wait_for(s: &AppState, id: &str, timeout: Duration) -> Result<JobView, AppError> {
+ let mut rx = s.engine.events.subscribe();
+ let deadline = Instant::now() + timeout;
+ loop {
+ let j = s.engine.job(id).ok_or_else(|| AppError::new(ErrorCode::NotFound, "Unknown job."))?;
+ if j.status.is_terminal() || Instant::now() >= deadline {
+ return Ok(j);
+ }
+ let _ = tokio::time::timeout(Duration::from_millis(1000).min(deadline - Instant::now()), rx.recv()).await;
+ }
+}
+
+/// Long-poll until the job finishes or `timeout` seconds pass (default 60, max 600).
+async fn wait_job(State(s): St, AxPath(id): AxPath<String>, Query(q): Query<WaitQ>) -> ApiResult<Json<JobView>> {
+ Ok(Json(wait_for(&s, &id, Duration::from_secs(q.timeout.unwrap_or(60).min(600))).await?))
+}
+
+/// Stable convenience endpoints. Body is a simplified request; `?wait=false` returns the
+/// queued job immediately, otherwise the call returns when the job finishes.
+#[derive(Deserialize, Default)]
+#[serde(default)]
+struct SimpleOp {
+ prompt: String,
+ negative_prompt: Option<String>,
+ image: Option<String>,
+ images: Vec<String>,
+ mask: Option<String>,
+ width: Option<u32>,
+ height: Option<u32>,
+ aspect_ratio: Option<String>,
+ quality: Option<Quality>,
+ seed: Option<i64>,
+ output_path: Option<String>,
+ preserve_dimensions: Option<bool>,
+ left: f64,
+ right: f64,
+ top: f64,
+ bottom: f64,
+ units: Option<ExpansionUnits>,
+ workspace: Option<String>,
+ client: Option<String>,
+ /// Upscale: factor (default 2), or a target `width`/`height`.
+ scale: Option<f64>,
+ method: Option<UpscaleMethod>,
+}
+
+#[derive(Deserialize)]
+struct OpQ {
+ wait: Option<bool>,
+}
+
+async fn run_simple(s: Arc<AppState>, mode: Mode, op: SimpleOp, wait: bool) -> ApiResult<Json<JobView>> {
+ let mut images = op.images.clone();
+ if let Some(i) = op.image.clone() {
+ images.insert(0, i);
+ }
+ let req = GenerationRequest {
+ prompt: op.prompt,
+ negative_prompt: op.negative_prompt,
+ mode,
+ images,
+ mask: op.mask,
+ outpaint: (mode == Mode::Outpaint).then_some(OutpaintSpec { left: op.left, right: op.right, top: op.top, bottom: op.bottom, units: op.units.unwrap_or_default() }),
+ quality: op.quality.unwrap_or_default(),
+ aspect_ratio: op.aspect_ratio,
+ width: op.width,
+ height: op.height,
+ seed: op.seed,
+ preserve_dimensions: op.preserve_dimensions.unwrap_or(true),
+ output_path: op.output_path,
+ client: op.client.or(Some("api".into())),
+ upscale: (mode == Mode::Upscale).then_some(UpscaleSpec { method: op.method.unwrap_or_default(), scale: op.scale, width: op.width, height: op.height }),
+ ..Default::default()
+ };
+ let ws = workspace_path(op.workspace.as_deref())?;
+ let j = s.engine.submit(req, ws)?;
+ if !wait {
+ return Ok(Json(j));
+ }
+ Ok(Json(wait_for(&s, &j.id, Duration::from_secs(3600)).await?))
+}
+
+async fn op_generate(State(s): St, Query(q): Query<OpQ>, Json(op): Json<SimpleOp>) -> ApiResult<Json<JobView>> {
+ run_simple(s, Mode::Generate, op, q.wait.unwrap_or(true)).await
+}
+async fn op_edit(State(s): St, Query(q): Query<OpQ>, Json(op): Json<SimpleOp>) -> ApiResult<Json<JobView>> {
+ let mode = if op.images.len() + op.image.is_some() as usize > 1 { Mode::MultiReference } else { Mode::Edit };
+ run_simple(s, mode, op, q.wait.unwrap_or(true)).await
+}
+async fn op_inpaint(State(s): St, Query(q): Query<OpQ>, Json(op): Json<SimpleOp>) -> ApiResult<Json<JobView>> {
+ run_simple(s, Mode::Inpaint, op, q.wait.unwrap_or(true)).await
+}
+async fn op_outpaint(State(s): St, Query(q): Query<OpQ>, Json(op): Json<SimpleOp>) -> ApiResult<Json<JobView>> {
+ run_simple(s, Mode::Outpaint, op, q.wait.unwrap_or(true)).await
+}
+/// `{"image": "...", "scale": 2 | "width"/"height", "method": "quick"|"detailed", "prompt"?}`
+async fn op_upscale(State(s): St, Query(q): Query<OpQ>, Json(op): Json<SimpleOp>) -> ApiResult<Json<JobView>> {
+ run_simple(s, Mode::Upscale, op, q.wait.unwrap_or(true)).await
+}
+
+#[derive(Deserialize)]
+struct PlanBody {
+ #[serde(flatten)]
+ request: GenerationRequest,
+ #[serde(default)]
+ workspace: Option<String>,
+}
+
+/// Dry run: resolved mode, working/output size and notes for the current inputs.
+async fn plan(State(s): St, Json(b): Json<PlanBody>) -> ApiResult<Json<Value>> {
+ let engine = s.engine.clone();
+ let ws = workspace_path(b.workspace.as_deref())?;
+ let v = tokio::task::spawn_blocking(move || -> Result<Value, AppError> {
+ let mut sizes = Vec::new();
+ for src in &b.request.images {
+ sizes.push(source_size(&engine, src, ws.as_deref())?);
+ }
+ let mask = match &b.request.mask {
+ Some(m) => {
+ let (img, _) = engine.resolve_source(m, ws.as_deref())?;
+ let mm = imaging::mask_from_image(&img);
+ Some((Size::new(mm.width(), mm.height()), imaging::mask_bbox(&mm, 16), imaging::mask_coverage(&mm, 16)))
+ }
+ None => None,
+ };
+ let p = engine.preview_plan(&b.request, sizes, mask)?;
+ Ok(serde_json::to_value(p).unwrap())
+ })
+ .await
+ .map_err(AppError::internal)??;
+ Ok(Json(v))
+}
+
+fn source_size(engine: &qls_core::engine::Engine, src: &str, ws: Option<&Path>) -> Result<Size, AppError> {
+ if let Some(id) = src.strip_prefix("input:") {
+ let r = engine.store.get_input(id)?;
+ return Ok(Size::new(r.width, r.height));
+ }
+ if let Some(id) = src.strip_prefix("gen:") {
+ let r = engine.store.get_generation(id)?;
+ return Ok(Size::new(r.width, r.height));
+ }
+ let (img, _) = engine.resolve_source(src, ws)?;
+ Ok(img.size())
+}
+
+// ---------------------------------------------------------------------------------------
+// Events (SSE)
+// ---------------------------------------------------------------------------------------
+
+async fn events(State(s): St) -> Sse<impl Stream<Item = Result<SseEvent, Infallible>>> {
+ let rx = s.engine.events.subscribe();
+ let stream = tokio_stream::wrappers::BroadcastStream::new(rx).filter_map(|r| r.ok()).map(|ev| Ok(SseEvent::default().json_data(ev).unwrap_or_default()));
+ Sse::new(stream).keep_alive(axum::response::sse::KeepAlive::new().interval(Duration::from_secs(15)))
+}
+
+// ---------------------------------------------------------------------------------------
+// Inputs
+// ---------------------------------------------------------------------------------------
+
+async fn upload_input(State(s): St, headers: HeaderMap, body: Bytes) -> ApiResult<Json<Value>> {
+ if body.is_empty() {
+ return Err(AppError::invalid("The upload was empty.").into());
+ }
+ let name = headers.get("x-filename").and_then(|v| v.to_str().ok()).map(|n| percent_decode(n).chars().take(200).collect::<String>());
+ let store = s.engine.store.clone();
+ let rec = tokio::task::spawn_blocking(move || store.put_input(&body, name.as_deref(), None)).await.map_err(AppError::internal)??;
+ Ok(Json(serde_json::to_value(rec).unwrap()))
+}
+
+#[derive(Deserialize)]
+struct PathBody {
+ path: String,
+}
+
+async fn import_input(State(s): St, Json(b): Json<PathBody>) -> ApiResult<Json<Value>> {
+ let store = s.engine.store.clone();
+ let rec = tokio::task::spawn_blocking(move || -> Result<_, AppError> {
+ let p = paths::validate_input_image(&b.path, None, &[])?;
+ let bytes = std::fs::read(&p).map_err(|e| AppError::io("read the image", &p, e))?;
+ let name = p.file_name().map(|n| n.to_string_lossy().into_owned());
+ store.put_input(&bytes, name.as_deref(), Some(&p.to_string_lossy()))
+ })
+ .await
+ .map_err(AppError::internal)??;
+ Ok(Json(serde_json::to_value(rec).unwrap()))
+}
+
+async fn get_input(State(s): St, AxPath(id): AxPath<String>) -> ApiResult<Json<Value>> {
+ Ok(Json(serde_json::to_value(s.engine.store.get_input(&id)?).unwrap()))
+}
+
+async fn serve_file(path: &Path, content_type: Option<&str>) -> ApiResult<Response> {
+ let bytes = tokio::fs::read(path).await.map_err(|e| AppError::io("read the image", path, e))?;
+ let ct = content_type.map(str::to_owned).unwrap_or_else(|| {
+ match path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).as_deref() {
+ Some("png") => "image/png",
+ Some("jpg") | Some("jpeg") => "image/jpeg",
+ Some("webp") => "image/webp",
+ Some("gif") => "image/gif",
+ Some("bmp") => "image/bmp",
+ Some("tif") | Some("tiff") => "image/tiff",
+ _ => "application/octet-stream",
+ }
+ .to_string()
+ });
+ Ok(Response::builder()
+ .header(header::CONTENT_TYPE, ct)
+ .header(header::CACHE_CONTROL, "private, max-age=31536000, immutable")
+ .body(Body::from(bytes))
+ .unwrap())
+}
+
+async fn input_image(State(s): St, AxPath(id): AxPath<String>) -> ApiResult<Response> {
+ let r = s.engine.store.get_input(&id)?;
+ if r.format == "heic" {
+ return serve_file(&s.engine.store.input_display_path(&id), Some("image/jpeg")).await;
+ }
+ serve_file(Path::new(&r.path), None).await
+}
+
+async fn input_thumb(State(s): St, AxPath(id): AxPath<String>) -> ApiResult<Response> {
+ s.engine.store.get_input(&id)?;
+ serve_file(&s.engine.store.input_thumb_path(&id), Some("image/jpeg")).await
+}
+
+// ---------------------------------------------------------------------------------------
+// Gallery
+// ---------------------------------------------------------------------------------------
+
+async fn gallery_list(State(s): St, Query(q): Query<ListQuery>) -> ApiResult<Json<Value>> {
+ let (items, total) = s.engine.store.list_generations(&q)?;
+ Ok(Json(json!({ "items": items, "total": total })))
+}
+
+async fn gallery_get(State(s): St, AxPath(id): AxPath<String>) -> ApiResult<Json<GenerationRecord>> {
+ Ok(Json(s.engine.store.get_generation(&id)?))
+}
+
+#[derive(Deserialize)]
+struct PatchBody {
+ favorite: Option<bool>,
+}
+
+async fn gallery_patch(State(s): St, AxPath(id): AxPath<String>, Json(b): Json<PatchBody>) -> ApiResult<Json<GenerationRecord>> {
+ if let Some(f) = b.favorite {
+ s.engine.store.set_favorite(&id, f)?;
+ let _ = s.engine.events.send(qls_core::engine::Event::Gallery { id: id.clone(), change: "updated" });
+ }
+ Ok(Json(s.engine.store.get_generation(&id)?))
+}
+
+async fn gallery_delete(State(s): St, AxPath(id): AxPath<String>) -> ApiResult<Json<Value>> {
+ let out = s.engine.config().output_dir;
+ s.engine.store.delete_generation(&id, &out)?;
+ let _ = s.engine.events.send(qls_core::engine::Event::Gallery { id: id.clone(), change: "deleted" });
+ Ok(Json(json!({ "deleted": id })))
+}
+
+async fn gallery_image(State(s): St, AxPath(id): AxPath<String>) -> ApiResult<Response> {
+ let r = s.engine.store.get_generation(&id)?;
+ serve_file(Path::new(&r.file_path), None).await
+}
+
+async fn gallery_thumb(State(s): St, AxPath(id): AxPath<String>) -> ApiResult<Response> {
+ let p = s.engine.store.thumb_path(&id);
+ if !p.is_file() {
+ let r = s.engine.store.get_generation(&id)?;
+ return serve_file(Path::new(&r.file_path), None).await;
+ }
+ serve_file(&p, Some("image/jpeg")).await
+}
+
+#[derive(Deserialize)]
+struct ExportBody {
+ path: String,
+ #[serde(default)]
+ overwrite: bool,
+}
+
+/// "Save as" from the desktop app (path chosen in the native dialog, which already
+/// confirmed any overwrite). Format follows the extension.
+async fn gallery_export(State(s): St, AxPath(id): AxPath<String>, Json(b): Json<ExportBody>) -> ApiResult<Json<Value>> {
+ let rec = s.engine.store.get_generation(&id)?;
+ let saved = tokio::task::spawn_blocking(move || -> Result<PathBuf, AppError> {
+ let mut target = paths::normalize(&b.path, None)?;
+ let ext = target.extension().map(|e| e.to_string_lossy().to_ascii_lowercase());
+ let fmt = match ext.as_deref() {
+ Some("jpg") | Some("jpeg") => qls_core::planner::OutputFormat::Jpeg,
+ Some("webp") => qls_core::planner::OutputFormat::Webp,
+ Some("png") => qls_core::planner::OutputFormat::Png,
+ _ => {
+ target.set_extension("png");
+ qls_core::planner::OutputFormat::Png
+ }
+ };
+ if Path::new(&rec.file_path) == target {
+ return Ok(target);
+ }
+ if !b.overwrite {
+ target = paths::unique_path(target, &[]);
+ }
+ let img = imaging::load_image(Path::new(&rec.file_path))?;
+ let bytes = qls_core::engine::encode_output(&img.pixels, fmt, &rec, img.icc_profile.as_deref())?;
+ qls_core::engine::write_atomic(&target, &bytes)?;
+ Ok(target)
+ })
+ .await
+ .map_err(AppError::internal)??;
+ Ok(Json(json!({ "path": saved })))
+}
+
+async fn image_info(Json(b): Json<PathBody>) -> ApiResult<Json<Value>> {
+ let v = tokio::task::spawn_blocking(move || -> Result<Value, AppError> {
+ let p = paths::validate_input_image(&b.path, None, &[])?;
+ let bytes = std::fs::read(&p).map_err(|e| AppError::io("read the image", &p, e))?;
+ let img = imaging::decode_image(&bytes)?;
+ let size = img.size();
+ let meta = GenerationRecord::from_png_text(&img.text);
+ let parameters = img.text.iter().find(|(k, _)| k == "parameters").map(|(_, v)| v.clone());
+ Ok(json!({
+ "path": p, "width": size.width, "height": size.height, "aspect_ratio": aspect_label(size),
+ "aspect_value": (size.width as f64 / size.height as f64 * 10000.0).round() / 10000.0,
+ "file_type": img.format, "file_size": bytes.len(), "exif_orientation": img.exif_orientation,
+ "has_transparency": img.has_transparency, "has_icc_profile": img.icc_profile.is_some(),
+ "generation": meta, "parameters": parameters,
+ }))
+ })
+ .await
+ .map_err(AppError::internal)??;
+ Ok(Json(v))
+}
+
+// ---------------------------------------------------------------------------------------
+// Sessions / lifecycle
+// ---------------------------------------------------------------------------------------
+
+#[derive(Deserialize)]
+struct HeartbeatBody {
+ client_id: String,
+ #[serde(default)]
+ kind: Option<String>,
+ #[serde(default)]
+ pid: Option<u32>,
+}
+
+async fn heartbeat(State(s): St, Json(b): Json<HeartbeatBody>) -> Json<Value> {
+ let kind = b.kind.unwrap_or_else(|| "client".into());
+ s.leases.lock().unwrap().insert(b.client_id.chars().take(80).collect(), Lease { kind, last_seen: Instant::now(), pid: b.pid });
+ *s.exit_deadline.lock().unwrap() = None;
+ s.quick_exit.store(false, std::sync::atomic::Ordering::Relaxed);
+ Json(json!({ "ok": true, "ttl_s": crate::LEASE_TTL.as_secs() }))
+}
+
+async fn release(State(s): St, Json(b): Json<HeartbeatBody>) -> Json<Value> {
+ let (removed, remaining, ui_remaining) = {
+ let mut l = s.leases.lock().unwrap();
+ let removed = l.remove(&b.client_id);
+ (removed, l.len(), l.values().any(|l| l.kind == "ui"))
+ };
+ if let Some(lease) = removed {
+ tracing::info!("client {} ({}) released", b.client_id, lease.kind);
+ // The desktop app closed: cancel its jobs and exit promptly instead of finishing
+ // them and waiting out the idle grace with the model still in VRAM.
+ crate::client_left(&s, &lease.kind, ui_remaining, remaining);
+ }
+ Json(json!({ "ok": true, "remaining_clients": remaining }))
+}
+
+async fn shutdown(State(s): St) -> Json<Value> {
+ s.shutdown.notify_waiters();
+ Json(json!({ "ok": true }))
+}
+
+/// Decodes %XX escapes (file names are sent URI-encoded in a header).
+fn percent_decode(s: &str) -> String {
+ let b = s.as_bytes();
+ let mut out = Vec::with_capacity(b.len());
+ let mut i = 0;
+ while i < b.len() {
+ if b[i] == b'%' && i + 2 < b.len() {
+ if let Ok(v) = u8::from_str_radix(&s[i + 1..i + 3], 16) {
+ out.push(v);
+ i += 3;
+ continue;
+ }
+ }
+ out.push(b[i]);
+ i += 1;
+ }
+ String::from_utf8_lossy(&out).into_owned()
+}
diff --git a/crates/qls-service/src/main.rs b/crates/qls-service/src/main.rs
new file mode 100644
index 0000000..3ed8c48
--- /dev/null
+++ b/crates/qls-service/src/main.rs
@@ -0,0 +1,257 @@
+//! qls-service — the headless Qwen Local Studio service.
+//!
+//! Owns the generation engine and the sd-server process, and exposes the stable local API
+//! (`http://127.0.0.1:<port>/api/v1/...`) used by the desktop app, the MCP server and
+//! scripts. Exactly one instance runs (the port bind is the lock). It exits by itself when
+//! no client holds a lease and no work is pending, stopping sd-server unless the user
+//! chose to keep it running.
+
+#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
+
+mod api;
+
+use std::collections::HashMap;
+use std::net::SocketAddr;
+use std::path::PathBuf;
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use qls_core::config::{AppConfig, data_dir};
+use qls_core::engine::{APP_VERSION, Engine};
+use qls_core::process::ServerState;
+use serde::{Deserialize, Serialize};
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ServiceInfo {
+ pub port: u16,
+ pub token: String,
+ pub pid: u32,
+ pub version: String,
+}
+
+pub struct Lease {
+ pub kind: String,
+ pub last_seen: Instant,
+ /// Client process id; a dead process drops its lease at once (app killed or crashed).
+ pub pid: Option<u32>,
+}
+
+pub struct AppState {
+ pub engine: Arc<Engine>,
+ pub token: String,
+ pub leases: Mutex<HashMap<String, Lease>>,
+ /// When the last lease went away and how long to wait before exiting.
+ pub exit_deadline: Mutex<Option<Instant>>,
+ pub persistent: bool,
+ /// The last client left on purpose (or died): exit right after the work stops instead
+ /// of waiting out the idle grace. Cleared by any heartbeat.
+ pub quick_exit: std::sync::atomic::AtomicBool,
+ pub shutdown: tokio::sync::Notify,
+ pub started: Instant,
+}
+
+pub const LEASE_TTL: Duration = Duration::from_secs(45);
+
+fn load_or_create_token(dir: &std::path::Path) -> String {
+ let p = dir.join("service-token");
+ if let Ok(t) = std::fs::read_to_string(&p) {
+ let t = t.trim().to_string();
+ if t.len() >= 32 && t.chars().all(|c| c.is_ascii_hexdigit()) {
+ return t;
+ }
+ }
+ let t = format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple());
+ let _ = std::fs::write(&p, &t);
+ t
+}
+
+pub fn service_info_path() -> PathBuf {
+ data_dir().join("service.json")
+}
+
+fn init_logging(dir: &std::path::Path) -> tracing_appender::non_blocking::WorkerGuard {
+ let logs = dir.join("logs");
+ let _ = std::fs::create_dir_all(&logs);
+ let file = tracing_appender::rolling::never(&logs, "service.log");
+ let (nb, guard) = tracing_appender::non_blocking(file);
+ tracing_subscriber::fmt()
+ .with_writer(nb)
+ .with_ansi(false)
+ .with_env_filter(tracing_subscriber::EnvFilter::try_from_env("QLS_LOG").unwrap_or_else(|_| "info".into()))
+ .init();
+ guard
+}
+
+#[tokio::main(flavor = "multi_thread", worker_threads = 4)]
+async fn main() {
+ let args: Vec<String> = std::env::args().collect();
+ let persistent = args.iter().any(|a| a == "--persistent");
+ let dir = data_dir();
+ let _ = std::fs::create_dir_all(&dir);
+ // Rotate the service log at startup (keep one previous).
+ let log_file = dir.join("logs").join("service.log");
+ if std::fs::metadata(&log_file).map(|m| m.len() > 5_000_000).unwrap_or(false) {
+ let _ = std::fs::rename(&log_file, dir.join("logs").join("service.prev.log"));
+ }
+ let _guard = init_logging(&dir);
+
+ let cfg = AppConfig::load();
+ let port = args
+ .iter()
+ .position(|a| a == "--port")
+ .and_then(|i| args.get(i + 1))
+ .and_then(|p| p.parse().ok())
+ .unwrap_or(cfg.service_port);
+
+ // Single instance: binding the port is the lock. Loopback only.
+ let addr = SocketAddr::from(([127, 0, 0, 1], port));
+ let listener = match tokio::net::TcpListener::bind(addr).await {
+ Ok(l) => l,
+ Err(e) => {
+ tracing::info!("port {port} busy ({e}); another qls-service is probably running — exiting");
+ return;
+ }
+ };
+
+ let engine = match Engine::new(cfg, &dir) {
+ Ok(e) => e,
+ Err(e) => {
+ tracing::error!("cannot start engine: {e} {:?}", e.detail);
+ return;
+ }
+ };
+ let token = load_or_create_token(&dir);
+ let info = ServiceInfo { port, token: token.clone(), pid: std::process::id(), version: APP_VERSION.into() };
+ let _ = std::fs::write(service_info_path(), serde_json::to_string_pretty(&info).unwrap());
+ tracing::info!("qls-service {APP_VERSION} listening on http://{addr} (pid {})", info.pid);
+
+ let state = Arc::new(AppState {
+ engine: engine.clone(),
+ token,
+ leases: Mutex::new(HashMap::new()),
+ exit_deadline: Mutex::new(Some(Instant::now() + Duration::from_secs(90))),
+ persistent,
+ quick_exit: std::sync::atomic::AtomicBool::new(false),
+ shutdown: tokio::sync::Notify::new(),
+ started: Instant::now(),
+ });
+
+ tokio::spawn(engine.clone().run_worker());
+ tokio::spawn(lifecycle(state.clone()));
+ tokio::spawn(server_watch(state.clone()));
+
+ let app = api::router(state.clone());
+ let st = state.clone();
+ let serve = axum::serve(listener, app).with_graceful_shutdown(async move { st.shutdown.notified().await });
+ if let Err(e) = serve.await {
+ tracing::error!("http server error: {e}");
+ }
+
+ // Shutdown: stop sd-server unless the user wants it kept loaded.
+ let cfg = engine.config();
+ if !cfg.keep_server_running {
+ if engine.server.stop().await {
+ tracing::info!("stopped sd-server on exit");
+ }
+ } else {
+ tracing::info!("leaving sd-server running (keep_server_running)");
+ }
+ if let Ok(s) = std::fs::read_to_string(service_info_path())
+ && let Ok(i) = serde_json::from_str::<ServiceInfo>(&s)
+ && i.pid == std::process::id()
+ {
+ let _ = std::fs::remove_file(service_info_path());
+ }
+ tracing::info!("qls-service exited");
+}
+
+/// Exits when no client holds a lease, no job is pending, and the grace period passed.
+/// Also unloads the model after long idle periods when no desktop window is attached.
+async fn lifecycle(state: Arc<AppState>) {
+ loop {
+ tokio::time::sleep(Duration::from_secs(2)).await;
+ let (n_leases, has_ui, lost) = {
+ let mut leases = state.leases.lock().unwrap();
+ let mut lost = Vec::new();
+ leases.retain(|id, l| {
+ let alive = l.last_seen.elapsed() < LEASE_TTL && l.pid.map(qls_core::process::pid_alive).unwrap_or(true);
+ if !alive {
+ lost.push((id.clone(), l.kind.clone()));
+ }
+ alive
+ });
+ (leases.len(), leases.values().any(|l| l.kind == "ui"), lost)
+ };
+ for (id, kind) in &lost {
+ tracing::info!("client {id} ({kind}) is gone");
+ client_left(&state, kind, has_ui, n_leases);
+ }
+ let busy = state.engine.has_pending_work();
+ if n_leases > 0 || busy {
+ *state.exit_deadline.lock().unwrap() = None;
+ } else if !state.persistent {
+ // Nobody is left to use the model: free the GPU now, exit after the grace.
+ let st = state.engine.server.status();
+ if st.owned && st.state != ServerState::Stopped && !state.engine.config().keep_server_running {
+ tracing::info!("no clients — unloading model");
+ state.engine.server.stop().await;
+ state.engine.emit_server();
+ }
+ let grace = if state.quick_exit.load(std::sync::atomic::Ordering::Relaxed) { 3 } else { 60 };
+ let mut d = state.exit_deadline.lock().unwrap();
+ match *d {
+ None => *d = Some(Instant::now() + Duration::from_secs(grace)),
+ Some(t) if Instant::now() >= t => {
+ tracing::info!("no clients and no work — shutting down");
+ state.shutdown.notify_waiters();
+ return;
+ }
+ _ => {}
+ }
+ }
+ // Idle unload (MCP-only or scripted use): free VRAM after N idle minutes.
+ let cfg = state.engine.config();
+ let st = state.engine.server.status();
+ if !has_ui
+ && !busy
+ && cfg.idle_unload_minutes > 0
+ && st.state == ServerState::Ready
+ && st.owned
+ && state.engine.idle_for() > Duration::from_secs(cfg.idle_unload_minutes as u64 * 60)
+ {
+ tracing::info!("idle for {} min without the desktop app — unloading model", cfg.idle_unload_minutes);
+ state.engine.server.stop().await;
+ state.engine.emit_server();
+ }
+ }
+}
+
+/// A client released its lease or died. When the last desktop window goes, its unfinished
+/// jobs are cancelled (MCP jobs keep running); when the last client goes, the service exits
+/// as soon as the work stops.
+pub fn client_left(state: &AppState, kind: &str, ui_remaining: bool, remaining: usize) {
+ if kind == "ui" && !ui_remaining {
+ let n = state.engine.cancel_client_jobs("ui");
+ if n > 0 {
+ tracing::info!("desktop app closed — cancelled {n} job(s)");
+ }
+ }
+ if remaining == 0 {
+ state.quick_exit.store(true, std::sync::atomic::Ordering::Relaxed);
+ }
+}
+
+/// Detects an owned sd-server that died between jobs, so the UI shows the right state.
+async fn server_watch(state: Arc<AppState>) {
+ loop {
+ tokio::time::sleep(Duration::from_secs(3)).await;
+ let st = state.engine.server.status();
+ if st.state == ServerState::Ready && st.owned && state.engine.server.owned_alive() == Some(false) {
+ state.engine.server.mark_lost(qls_core::error::AppError::new(
+ qls_core::error::ErrorCode::ServerCrashed,
+ "The inference server stopped unexpectedly.",
+ ));
+ state.engine.emit_server();
+ }
+ }
+}
diff --git a/docs/upscale-plan.md b/docs/upscale-plan.md
new file mode 100644
index 0000000..dc7bb0c
--- /dev/null
+++ b/docs/upscale-plan.md
@@ -0,0 +1,251 @@
+# Speed & upscaling: results log and implementation plan
+
+Status as of 2026-10-06. Hardware: RTX 5070 Ti 16 GB, sd-server/sd-cli in `C:\AI\sdcpp`
+(stable-diffusion.cpp commit 3f8527a), Qwen Image 2.1 UC Q4_K_M + Qwen3VL-8B Q4_K_M TE.
+Benchmark script: `C:\AI\sdcpp\bench\bench-2k.ps1` (`-Only a,b`), outputs + logs in `C:\AI\sdcpp\bench\out`.
+
+## 1. Results so far
+
+### 1.1 Text-to-image 2048x1152, 20 steps, cfg 6, euler, seed 42 (sd-cli, incl. model load)
+
+| Variant | Total | s/step | Notes |
+|---|---|---|---|
+| `base` (`--fa`) | 139 s | 5.63 | Over-sharpened / "oil painting" look at native 2K |
+| `sage` (+`--sage-attn`) | 104 s | 3.81 | Near-identical image to base |
+| `easycache` (threshold=0.2) | 90 s | 5.57 | Skips 10/20 steps |
+| `sage_ec` | 64 s | 3.80 | Same composition, slightly softer |
+| `hires` (1024x576 → x2 latent, 10 steps, denoise 0.5) | 87 s | 3.86 | Different, more photographic |
+| `hires_esrgan` (1376x768 → ESRGAN → 2048x1152, 8 steps, denoise 0.35) | 104 s | — | Best look; but decode wasted 22.8 s |
+| `hires_vt768` (same + `--vae-tiling --vae-tile-size 768 --vae-tile-overlap 0.125`) | **86.8 s** | — | Best quality/time |
+| `hires_vt1024` (tile 1024) | 88.8 s | — | Decode 6.1 s (768: 3.9 s) |
+| `hires_fast` (tile 1024 + EasyCache + 6 refine steps) | **57.5 s** | — | Very close to vt768, slightly softer fine detail |
+
+Breakdown `hires_vt768`: base 20 steps @1376x768 33.5 s (1.63 s/it with sage) · hires prep
+(decode + ESRGAN + re-encode) ~16 s · 8 refine steps @2K 30.8 s (3.8 s/it) · decode 3.9 s.
+Breakdown `hires_fast`: base 17.4 s (EasyCache skipped 10/20) · refine 15.5 s (skipped 2/6) · prep ~15 s · decode 6.2 s.
+
+### 1.2 Key findings
+
+- **SageAttention** (`--sage-attn`): ~32% faster steps at 2K, no visible quality cost. Works on Blackwell (sm_120).
+- **VAE decode at 2K always OOMs** untiled (needs ~18 GB with DiT weights resident), then the backend
+ retries with 256 px tiles → ~22 s per 2K image. 768 px tiles + overlap 0.125 → ~4 s. `--vae-tiling`
+ alone keeps 256 px tiles and also slows encode (+8 s), so the tile size matters.
+- **ESRGAN (RealESRGAN_x4plus.pth)** via `sd-cli -M upscale`: 1376x768 → 5504x3072 in 13 s *including*
+ process start + model load; output clearly sharper/cleaner than Lanczos (slightly "painted" fine texture).
+ Model at `C:\AI\sdcpp\models\upscalers\RealESRGAN_x4plus.pth`; as a hires upscaler its name is the
+ file stem (`--hires-upscaler RealESRGAN_x4plus` with `--hires-upscalers-dir`). Verified working.
+- **Native 2K looks over-processed**; 1 MP base + 2K low-denoise refine looks natural. The model is best near 1 MP.
+- **Edit CFG**: at cfg 6 edits can collapse to near-black (Spider-Man "dark version" test); user A/B
+ showed detail increases monotonically as cfg drops 6 → 4 → 2. Clear, explicit edit prompts help.
+- **Steps**: 10 steps + cfg 6 produced an almost blank flat-vector logo (L range 245–255). Keep ≥20.
+- **Current upscaling in the app = none**: everything renders at working size; `pipeline::postprocess`
+ Lanczos-resizes to output. Edits at Balanced work at ~1 MP and are stretched back (5120x2880 source
+ → worked at 1376x768 → 3.7x Lanczos stretch = soft).
+
+### 1.3 sd-server capabilities found in the binary (strings, not yet exercised over HTTP)
+
+- `POST /sdcpp/v1/upscale` — ESRGAN upscale endpoint; needs RGB ESRGAN models in `--hires-upscalers-dir`
+ ("no RGB ESRGAN upscaler models are available; start the server with --hires-upscalers-dir"),
+ max 8192x8192, errors: "image is required", "no compatible image upscaler called …". Capabilities
+ JSON has `upscalers`, `max_upscale_width/height`, feature `image_upscale`. Request field names are
+ unknown — inspect via `GET /sdcpp/v1/capabilities` and trial requests.
+- `img_gen` request has a `hires` object: `enabled, upscaler, model_path, scale, target_width,
+ target_height, steps, denoising_strength, upscale_tile_size, custom_sigmas`.
+- `img_gen` also has `vae_tiling_params` (already in `sdcpp.rs`) and strings `cache_mode`,
+ `cache_option`, `cache_params` (per-request EasyCache plausible, unverified).
+
+## 2. Already implemented (not yet in a release build — run `scripts\build-release.ps1`)
+
+- `AppConfig.sage_attention` (default true) → `--sage-attn`; Settings switch.
+- `AppConfig.vae_tile_size` (default 768, 0 = off) → `--vae-tiling --vae-tile-size N --vae-tile-overlap 0.125`; Settings field.
+- `RecommendedSettings.cfg_edit` (default 4.0) used for every non-Generate mode; t2i stays at `cfg` 6.0.
+- All 92 qls-core tests pass; UI typechecks.
+
+**Known bug to fix first:** `planner.rs` sets `vae_tiling` automatically for areas > 2.7 MP and
+`pipeline.rs:120` then sends `VaeTilingParams { tile_size_w: 0, tile_size_h: 0, target_overlap: 0.5 }`,
+which probably overrides the server's 768 px default with 256 px tiles. Send the configured tile size
+(768, overlap 0.125) or omit the field when the server flag already applies.
+
+## 3. Implementation plan
+
+### Phase 0 — verify over HTTP (short, before coding the client)
+1. Start sd-server with the app's args + `--hires-upscalers-dir C:\AI\sdcpp\models\upscalers`; dump
+ `GET /sdcpp/v1/capabilities` (look for `upscalers`, `image_upscale`, hires/cache features).
+2. Find the `/sdcpp/v1/upscale` body schema (try `{image, upscaler, scale|width/height}`; read error messages).
+3. Confirm `hires` works in `img_gen` for t2i **and** for edits with `ref_images` (does the refine pass keep refs?).
+4. Check whether `cache_mode`/`cache_option` are accepted per request.
+Long runs (model loads, 2K jobs) are executed by the user: give copy-paste commands and wait for output.
+
+### Phase 1 — backend plumbing (qls-core)
+- `config.rs`: `upscalers_dir` (default `<sdcpp>\models\upscalers`), `upscaler_model` (default
+ `RealESRGAN_x4plus`); pass `--hires-upscalers-dir` in `process.rs` when the dir exists.
+- `sdcpp.rs`: `HiresParams` on `ImgGenRequest` (skip when None); `upscale()` client for `/sdcpp/v1/upscale`;
+ parse `upscalers` from capabilities; optional per-request cache params if Phase 0 confirms.
+- Diagnostics/setup: report whether an ESRGAN model is present, with the download URL
+ `https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth` (64 MB).
+ The app does not download models itself (Setup.tsx says so) — keep that, show instructions.
+- Fix the per-request VAE tiling bug above.
+
+### Phase 2 — two-pass Quality for text-to-image (planner + pipeline)
+- When the target area is > ~1.3 MP (Quality / 2K / custom large): base pass at ~1 MP with the same
+ aspect (aligned to 32), `hires` to the target size with the ESRGAN upscaler, denoise 0.35.
+- Two settings: **Best** = 8 refine steps, no cache (~86 s at 2K) · **Fast** = 6 refine steps + EasyCache
+ threshold 0.2 (~55 s). Expose as a preference (default Fast?) and in Advanced.
+- Targets above 2K (e.g. 4K): two-pass to 2K, then ESRGAN to the final size (Phase 3 path), never a
+ single diffusion pass > ~2.4 MP.
+- Update `estimate_seconds` to model base + refine + ESRGAN + decode; record `working_*` and hires
+ info in the gallery metadata and the Details panel ("rendered 1376x768 → refined 2048x1152 → upscaled …").
+
+### Phase 3 — ESRGAN instead of Lanczos when enlarging
+- `pipeline::postprocess`: when output is larger than the working content by > ~1.1x (edits with
+ preserve_dimensions, outpaint final size, any custom large size), upscale with `/sdcpp/v1/upscale`
+ (x4) and then Lanczos *down* to the exact size. Lanczos only for shrinking or tiny factors.
+- Inpaint composites keep their current path (patch is generated near native size).
+
+### Phase 4 — Upscale action in the UI
+- New toolbar button on any image: **Quick** (ESRGAN only, seconds) and **Detailed** (img2img refine at
+ ~2K with denoise ~0.3, cfg_edit, then ESRGAN to the target) with target presets 2x / 4K / original
+ source size / custom; result saved as a child of the source (parent_id).
+- For the 3.7x edit case: edit at ~1 MP → (Detailed) refine at 2048x1152 → ESRGAN x4 → downscale to
+ 5120x2880. Expected ~70–80 s total (unmeasured).
+- MCP server (`mcp/`): expose the upscale action too.
+
+### Phase 5 — validation
+- Unit tests: planner two-pass sizes/aspect, hires request JSON, postprocess choosing ESRGAN vs Lanczos.
+- User-run benchmarks via `bench-2k.ps1` / the app: 2K Fast vs Best timings, 4K t2i, the Spider-Man
+ 5120x2880 edit, a flat logo (thin lines) to check ESRGAN doesn't smear text.
+- Update `README.md` (upscaler model requirement, new settings).
+
+## 4. Relevant code
+- `crates/qls-core/src/config.rs` — AppConfig, RecommendedSettings (cfg, cfg_edit, steps, areas)
+- `crates/qls-core/src/process.rs` — `build_server_args`, log progress parser (add hires stage parsing:
+ "hires fix: upscaling to", "hires sampling 1/1 completed")
+- `crates/qls-core/src/planner.rs` — mode detection, working/output sizes (~L510-628), auto VAE tiling (~L633), estimates (~L395)
+- `crates/qls-core/src/pipeline.rs` — request building (~L100-125), `postprocess` resize (~L207)
+- `crates/qls-core/src/sdcpp.rs` — native API client and request structs
+- `crates/qls-core/src/imaging.rs` — Lanczos resize
+- `src/components/Settings.tsx`, `Advanced.tsx`, `Stage.tsx` (toolbar), `src/lib/types.ts`
+
+## 5. Implementation status (2026-10-06)
+
+All phases are implemented; real-hardware validation is pending (scripts below).
+
+### Phase 0 — answered from the server source at commit 3f8527a (`examples/server`, `src/pipeline/image.cpp`)
+- Requests start from the server's launch defaults and are merged **field by field**
+ (`SDGenerationParams::from_json_str`). Consequence: the old per-request
+ `vae_tiling_params {tile_size_w: 0}` really did override the 768 px server tiles with 256 px.
+- `POST /sdcpp/v1/upscale` body: `{image, upscaler?, repeats? (1-4), tile_size?, output_format?}` →
+ `{images[{b64_json}], upscaler, scale, width, height}`; synchronous, holds the GPU lock, loads
+ the ESRGAN model per call, output ≤ 8192 px per axis (so ≤ 2048 px input for x4), RGB only.
+- Capabilities: `upscale` (bool) and `upscalers[] {name, model, image_upscale}`; `features_by_mode.img_gen.hires/cache`.
+- `hires` in `img_gen`: `{enabled, upscaler, target_width, target_height, steps, denoising_strength, ...}`;
+ the refine pass reuses `ref_latents`, `ref_image_params` and an interpolated inpaint mask, so
+ edits keep their references. `hires.steps` = effective steps (schedule scaled by 1/denoise).
+- `cache_mode` / `cache_option` are honored per request (`initialize_cache_params` runs on each
+ request) and apply to both passes.
+- Model-backed upscaler names resolve as `<dir>/<name>.{gguf,safetensors,pt,pth}`.
+
+### What was built
+- VAE tiling fix: nothing is sent when the server already tiles; only an explicit "off" is sent
+ (`pipeline::vae_tiling_params`). Auto tiling threshold lowered to 1.6 MP.
+- Config: `refineMode` (fast default | best | off), `upscalersDir`, `upscalerModel`, `upscaleTileSize`;
+ `--hires-upscalers-dir` passed when the folder exists; setup check (optional) with download URL.
+- Planner: two-pass when the working area would exceed 1.3 MP — t2i and edit/multi-ref (refs at
+ the base size); refine canvas ≤ 2048×1152; larger outputs delivered at the exact size via ESRGAN.
+ `Mode::Upscale` (Quick / Detailed). Estimates calibrated on the bench (Best ≈ 87 s, Fast ≈ 57 s).
+- Engine: ESRGAN enlargement whenever the result is enlarged > 1.1× (client-side tiling for
+ the 8192 px limit, alpha preserved, Lanczos fallback with a note); runtime check of the server's
+ upscaler list; Upscaling/Refining progress stages; OOM retry drops two-pass to one 1 MP pass.
+- Gallery `pipeline` metadata (+ A1111 "Hires upscale/steps/upscaler" parameters), Details panel row.
+- UI: Upscale button (2×, 4K, source size, custom; Quick/Detailed), refine selector in Advanced
+ and Settings. MCP `upscale_image`; API `POST /upscale`.
+
+### Validation (run by the user; close the app first)
+```powershell
+# Raw sd-server checks + ESRGAN tile size (128/256/512) timing, ~6 min:
+powershell -ExecutionPolicy Bypass -File C:\AI\sdcpp\bench\validate-sdserver.ps1
+# Through the app engine (2K Fast/Best, 4K, 5120x2880 edit, Quick/Detailed upscale, logo), ~15 min:
+cd C:\AI\qwen-local-studio; cargo build -p qls-service
+powershell -ExecutionPolicy Bypass -File scripts\dev\validate-upscale.ps1
+```
+
+## 6. Upscaling quality review (2026-10-06, after first real use)
+
+### Findings
+- **ESRGAN smooths real texture.** Spider-Man "dark version" edit, Balanced (rendered at 1365×768, restored to
+ 5120×2880): RealESRGAN_x4plus gives crisper edges (+46 % Laplacian energy) but erases the suit's fine
+ mesh and invents painterly "crinkle" strokes; the old Lanczos stretch keeps the mesh (soft). It also cost
+ +39 s (58.7 s → 98.0 s). Cause: x4plus is trained to remove blur/noise/JPEG from degraded photos, and a
+ 1–2 px pattern on a clean AI render looks like noise to it. The Best/Fast refine was not involved
+ (Balanced is below the 1.3 MP two-pass threshold).
+- **sd.cpp's ESRGAN loader** (3f8527a) accepts any RRDBNet with 64 features / 32 growth channels, any block
+ count, x1/x2/x4, in both RealESRGAN and old-ESRGAN key formats. Community models trained for clean
+ inputs (4x NMKD Siax — WTFPL; 4x Remacri, 4x UltraSharp — non-commercial) should load. Not tested.
+- **Guided detail transfer from the source** (prototype, fast guided filter: local affine color model fitted at
+ low res, applied to the full-res original): recovers the original's mesh/grain, 5 s on CPU, 40 dB
+ consistency with the edit; ghost outlines where the model moved content (chest emblem). **User judged
+ plain Lanczos better.**
+- **SeedVR2** (ByteDance, ICLR 2026, one-step diffusion SR): best-regarded diffusion upscaler, but users report
+ over-generated detail/oversharpening on clean AI-generated inputs (our case), plastic skin, halos, tile
+ seams; needs a PyTorch sidecar and can't share 16 GB with Qwen. SUPIR: SDXL-based, slow, strays further.
+
+### Decisions
+| Option | Decision |
+| --- | --- |
+| ESRGAN for automatic enlargement (edits restored to source size, outpaint, > 2K) | **Drop** — back to Lanczos by default |
+| Guided transfer from source | **Drop** (visually worse to the user) |
+| SeedVR2 / SUPIR | **Not now** (risk of the same over-detail, new runtime, VRAM) |
+| Two-pass hires with ESRGAN *between* passes (> 1.3 MP) | **Keep** (bench: best 2K look; Qwen redraws detail after it) |
+| **Lanczos upscale + Qwen low-denoise refine** (whole image at 2K, or ~1 MP tiles at full res) | **Pursue** — measure first |
+| Better ESRGAN model (Siax/Remacri) for the Quick upscale | Optional, after `compare-upscalers.ps1` |
+
+### To do
+1. Add an "enlarge results with" setting (Lanczos | ESRGAN), default **Lanczos**; ESRGAN stays available in
+ the Upscale button's Quick mode.
+2. Run `python C:\AI\sdcpp\bench\tiled_refine_test.py` (~10–15 min; user runs it). It compares
+ `refine2k`, `tiles_cfg4`, `tiles_cfg1`, `tiles_cfg1_ec`, `tiles_s020` (24 tiles of 960×832 for 5120×2880,
+ denoise 0.3 = 6 of 20 steps, neutral prompt) and logs time per stage. Speed levers to evaluate:
+ CFG 1 (one model pass per step, ~2×), EasyCache, lower denoise, tile size, keeping 3 jobs queued
+ (the server caches the prompt encoding across tiles).
+3. Pick the quality/time trade-off; implement it as the Upscale **Detailed** mode (replacing the current
+ 2K img2img + ESRGAN) and, if fast enough, as an option for large edits.
+4. Optional: `compare-upscalers.ps1` with Siax/Remacri; consider also Lanczos as the hires upscaler between passes.
+5. Still pending from section 5: `validate-sdserver.ps1` and `scripts\dev\validate-upscale.ps1`.
+
+### Update 2026-10-06 (evening): GAN model choice
+- A/B of 9 ESRGAN-family models on the Spider-Man edit (`C:\AI\sdcpp\bench\gan_compare.py`, sheets in
+ `bench\out\gan\`): **4x-UltraSharp** and **4x_NMKD-Superscale-SP** keep the fine texture; x4plus/esrnet
+ smooth it, Valar crushes shadows. BSRGAN and RealisticRescaler don't load in sd.cpp.
+- Texture transfer from the original (A, `gan_methods.py`) and Qwen tiled refine over the GAN (B,
+ `gan-qwen-refine.ps1`) were **rejected** by the user.
+- **Implemented:** Settings → Models offers UltraSharp (default) and Superscale-SP for every ESRGAN use
+ (hires pass, enlargement, Upscale button); configs on the old x4plus default migrate (schema 2).
+
+
+## 7. Settings corrected to the official Qwen-Image 2.1 release (2026-10-07)
+
+Every measurement and A/B test above ran at **CFG 6 (edits 4) with 20 steps**, taken from the
+example command in sd.cpp's `docs/qwen_image_2.1.md`. The official release does not use
+guidance: diffusers `QwenImage21Pipeline` defaults to `true_cfg_scale=1.0` ("Qwen-Image 2.1 is
+meant to be sampled without guidance") with 40 steps, and the README's sizes are native 2K
+(2048², 2752×1536…). sd-server runs a second, unconditional model pass whenever CFG ≠ 1, so the
+old settings doubled the cost of each step and over-guided the model. That may explain the
+over-sharpened 2K look, the edits that collapsed to near-black, and the canvas texture. sd-server's
+default Qwen 2.1 schedule already matches the official one (exponential shift, mu 0.5→0.9 over
+256→8192 tokens, terminal 0.02), so no schedule change is needed.
+
+New defaults (config schema 4 migrates configs still on the old values):
+
+| Preset | Before | Now |
+| --- | --- | --- |
+| Fast | ~1 MP, 20 steps, CFG 6 | ~1 MP, 20 steps, CFG 1 (shortcut, ~2× faster than before) |
+| Balanced | ~1 MP, 20 steps, CFG 6 | ~1 MP, 40 steps, CFG 1 (official) |
+| Quality | ~2 MP, 20 steps, CFG 6 | native 2K bucket, 40 steps, CFG 1 (official) |
+| Edits / inpaint / outpaint / Detailed upscale | CFG 4 | CFG 1 |
+
+Time estimates halve the CFG-6 step times for CFG 1. They need re-measuring. The quality
+conclusions above (ESRGAN choice, single pass vs refine, edit CFG) were drawn at CFG 6 and
+should be re-checked. Bench scripts now default to the official settings: `turbo_test.py`
+writes to `out/turbo_official`, `nude_turbo_bench.py` to `out/nude_official`.
+`validate-sdserver.ps1`, `bench-2k.ps1` and `tiled_refine_test.py` still test the old CFG-6
+two-pass flow and are kept only as a historical record.
diff --git a/index.html b/index.html
new file mode 100644
index 0000000..1977a6b
--- /dev/null
+++ b/index.html
@@ -0,0 +1,12 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Qwen Local Studio</title>
+ </head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/src/main.tsx"></script>
+ </body>
+</html>
diff --git a/mcp/package-lock.json b/mcp/package-lock.json
new file mode 100644
index 0000000..2d05d76
--- /dev/null
+++ b/mcp/package-lock.json
@@ -0,0 +1,3217 @@
+{
+ "name": "qls-mcp",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "qls-mcp",
+ "version": "1.0.0",
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.32.1",
+ "zod": "^4.6.5"
+ },
+ "devDependencies": {
+ "@types/node": "^26.6.4",
+ "esbuild": "^0.28.2",
+ "postject": "^1.0.0-alpha.6",
+ "typescript": "^7.0.2",
+ "vitest": "^5.0.3"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
+ "integrity": "sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.28.2.tgz",
+ "integrity": "sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.28.2.tgz",
+ "integrity": "sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.28.2.tgz",
+ "integrity": "sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.28.2.tgz",
+ "integrity": "sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.28.2.tgz",
+ "integrity": "sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.28.2.tgz",
+ "integrity": "sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.28.2.tgz",
+ "integrity": "sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.28.2.tgz",
+ "integrity": "sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.28.2.tgz",
+ "integrity": "sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.28.2.tgz",
+ "integrity": "sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.28.2.tgz",
+ "integrity": "sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.28.2.tgz",
+ "integrity": "sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.28.2.tgz",
+ "integrity": "sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.28.2.tgz",
+ "integrity": "sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.28.2.tgz",
+ "integrity": "sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.28.2.tgz",
+ "integrity": "sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.28.2.tgz",
+ "integrity": "sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.28.2.tgz",
+ "integrity": "sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.28.2.tgz",
+ "integrity": "sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.28.2.tgz",
+ "integrity": "sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/openharmony-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.28.2.tgz",
+ "integrity": "sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.28.2.tgz",
+ "integrity": "sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.28.2.tgz",
+ "integrity": "sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.28.2.tgz",
+ "integrity": "sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.28.2.tgz",
+ "integrity": "sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@hono/node-server": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.3.tgz",
+ "integrity": "sha512-TA//nWMqPhbfdfneACk6t5a9eqbS9lABEPyKn0/xZTah3H3U2XaVg85rJFl0/Fyit0I552YDHgXGVSf3GwqbUw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=20"
+ },
+ "peerDependencies": {
+ "hono": "^4"
+ }
+ },
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.31",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.1.0",
+ "@jridgewell/sourcemap-codec": "^1.4.14"
+ }
+ },
+ "node_modules/@modelcontextprotocol/sdk": {
+ "version": "1.32.1",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.32.1.tgz",
+ "integrity": "sha512-2DdE+SJDtzLEEWzY1ZjY7Q+VcPhcV1KisD3zI4u0XZyktsjHum1mwbMI+JaulUBi2OZk+KJAi2uPXzxichPkdw==",
+ "license": "MIT",
+ "dependencies": {
+ "@hono/node-server": "^1.19.9 || ^2.0.5",
+ "ajv": "^8.17.1",
+ "ajv-formats": "^3.0.1",
+ "content-type": "^1.0.5",
+ "cors": "^2.8.5",
+ "cross-spawn": "^7.0.5",
+ "eventsource": "^3.0.2",
+ "eventsource-parser": "^3.0.0",
+ "express": "^5.2.1",
+ "express-rate-limit": "^8.2.1",
+ "hono": "^4.11.4",
+ "jose": "^6.1.3",
+ "json-schema-typed": "^8.0.2",
+ "pkce-challenge": "^5.0.0",
+ "raw-body": "^3.0.0",
+ "zod": "^3.25 || ^4.0",
+ "zod-to-json-schema": "^3.25.1"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "peerDependencies": {
+ "@cfworker/json-schema": "^4.1.1",
+ "zod": "^3.25 || ^4.0"
+ },
+ "peerDependenciesMeta": {
+ "@cfworker/json-schema": {
+ "optional": true
+ },
+ "zod": {
+ "optional": false
+ }
+ }
+ },
+ "node_modules/@oxc-project/types": {
+ "version": "0.152.0",
+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.152.0.tgz",
+ "integrity": "sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "funding": {
+ "url": "https://github.com/sponsors/oxc-project"
+ }
+ },
+ "node_modules/@rolldown/binding-android-arm-eabi": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.12.tgz",
+ "integrity": "sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "peer": true,
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-android-arm64": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.12.tgz",
+ "integrity": "sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "peer": true,
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-arm64": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.12.tgz",
+ "integrity": "sha512-3YIhqHD96nA5SaYNRBR16HnGv4oavZvXfD/ayHM+oYZ0WD/8lBAtf6zQua4kEyAvpqrluKXl0lnOBoiNby7x9w==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "peer": true,
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-x64": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.12.tgz",
+ "integrity": "sha512-UuuJ35MFw4gmFOrE9pEqIV+K3syIKveph+Qc1/ljHZVdoDW4pz/JHR/eMVom+TZGl/5OOvGJOWaOCVt3ZfqhxA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "peer": true,
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-freebsd-x64": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.12.tgz",
+ "integrity": "sha512-uMvssit0a4W+/7D8CbHUvG719mH3R2jwXAlh/XcPvuHTE0g++LymF88DCGNX0HM2rBOn0xrzgXktIB6fLSJBTQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "peer": true,
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm-gnueabihf": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.12.tgz",
+ "integrity": "sha512-XcFu0R0xWnwzSf4IQgFH1rJIckPN1pLy2R+4r9IDB7Yfu/ys9cVqfa4pBrMHj7a3gl8mIR4nRNPg0e5IvEVs6g==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "peer": true,
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-gnu": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.12.tgz",
+ "integrity": "sha512-260UrKgn8tz39ak+SMDOirKzr7V04M9dWPw5llW00SwBivCZoWcRBKV1d8cXnRkUmSZA3BdiUmBHWk7734Ulpw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "peer": true,
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-musl": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.12.tgz",
+ "integrity": "sha512-5YK1I9SqDkbPgc1IA8BgDl34suqUS2q0KWnBrirm0E51YjOs6eo6dV6jbQfNE/argHRSvd0QUGgtpIoYx+WWpw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "peer": true,
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.12.tgz",
+ "integrity": "sha512-Rkcrmp7eFRg74yL5fXEU91JEWbdEPLevWwGtXpmhbjlD1StScbWTmO94Bhly+Mo+ketKYkdmM1vNUKeWSlx8cQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "peer": true,
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-s390x-gnu": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.12.tgz",
+ "integrity": "sha512-qvK4DuAsQc2BSjlx+Xr+IzOIvvxbGZqxFwdWfG6F518Erj0GGISyQbJ6pIappnOxlNPzNHvo/L0BwB30GZ+zVw==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "peer": true,
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-gnu": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.12.tgz",
+ "integrity": "sha512-Q9uLBO53Xd4QIq1WOycVQyPP1O4HhraEV2qqb3uTrnVw6QZih9duY4vNXOivL1xoUS1/z+W8eF4NMfl2a8Sdjw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "peer": true,
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-musl": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.12.tgz",
+ "integrity": "sha512-3IBxWFMjbOZskDPKv8Lf9BCnahlKuHthWkYnyIxOH/QcJrFcS4EmcenthApkwr/5+nEqZlLzeYbxeMaX7A5u4g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "peer": true,
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-openharmony-arm64": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.12.tgz",
+ "integrity": "sha512-xtX61xg4LKPkPWilZU1ynKClz5Gj4bf74LML4r3eVLWumKnGjoEr1OSHQhMdbBDoYTi+yjrujvpZe2pUnqCrrA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "peer": true,
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-arm64-msvc": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.12.tgz",
+ "integrity": "sha512-At7fPB6PCaIjzgIhEZFxuT+BBFqiQibJDT4d3PhiR3f4E7bbMZF4aKblbFfEM3sETRDd1YiQx/+U/g/B/ou5Ew==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "peer": true,
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-x64-msvc": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.12.tgz",
+ "integrity": "sha512-WIw2haVKwjuYdXkHaoC0mF8Le71TuCBxjrdKqLbJGctbBABj+ClfmNvtbOnzpq3RokNo5+V1qhtSzJyXorsklQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "peer": true,
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/pluginutils": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
+ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true
+ },
+ "node_modules/@types/chai": {
+ "version": "5.2.3",
+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/deep-eql": "*",
+ "assertion-error": "^2.0.1"
+ }
+ },
+ "node_modules/@types/deep-eql": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/node": {
+ "version": "26.6.4",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.4.tgz",
+ "integrity": "sha512-ldVPDCzj7fsaGZrLB0NuHuTvJcsNasysBAqMolr/cgxrLd1xbqxIr3XJiPnHHJUCxj5sNF1vnRj9aWnrVh5Jcg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "undici-types": "~8.9.0"
+ }
+ },
+ "node_modules/@typescript/typescript-aix-ppc64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
+ "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-darwin-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz",
+ "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-darwin-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz",
+ "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-freebsd-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz",
+ "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-freebsd-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz",
+ "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-arm": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz",
+ "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz",
+ "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-loong64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz",
+ "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-mips64el": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz",
+ "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-ppc64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz",
+ "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-riscv64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz",
+ "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-s390x": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz",
+ "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz",
+ "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-netbsd-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz",
+ "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-netbsd-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz",
+ "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-openbsd-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz",
+ "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-openbsd-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz",
+ "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-sunos-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz",
+ "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-win32-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz",
+ "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-win32-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz",
+ "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@vitest/mocker": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.3.tgz",
+ "integrity": "sha512-T8sWAIbkSyAjkwTcaEc3Iu0o9A27X1/kdXrizhZkGuSKScRQtRzclfAMpOTcGdXCsqxeWlpGy3XjqaW8CpLORg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/trace-mapping": "0.3.31",
+ "@vitest/spy": "5.0.3",
+ "estree-walker": "^3.0.3",
+ "magic-string": "^1.2.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "msw": "^2.4.9",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "msw": {
+ "optional": true
+ },
+ "vite": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@vitest/spy": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.3.tgz",
+ "integrity": "sha512-XhFysQTB8AZ+P4gMi+Lpo99vg2AZi0qKpaB9yXQl37+CaMEAPO3iH/wGVnSyL5MPERiLezpqTVtrR6UZH5GCXg==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/accepts": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
+ "integrity": "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-types": "^3.0.0",
+ "negotiator": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/ajv": {
+ "version": "8.20.0",
+ "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz",
+ "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==",
+ "license": "MIT",
+ "dependencies": {
+ "fast-deep-equal": "^3.1.3",
+ "fast-uri": "^3.0.1",
+ "json-schema-traverse": "^1.0.0",
+ "require-from-string": "^2.0.2"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/epoberezkin"
+ }
+ },
+ "node_modules/ajv-formats": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/ajv-formats/-/ajv-formats-3.0.1.tgz",
+ "integrity": "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ==",
+ "license": "MIT",
+ "dependencies": {
+ "ajv": "^8.0.0"
+ },
+ "peerDependencies": {
+ "ajv": "^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "ajv": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/assertion-error": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/body-parser": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",
+ "integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==",
+ "license": "MIT",
+ "dependencies": {
+ "bytes": "^3.1.2",
+ "content-type": "^2.0.0",
+ "debug": "^4.4.3",
+ "http-errors": "^2.0.1",
+ "iconv-lite": "^0.7.2",
+ "on-finished": "^2.4.1",
+ "qs": "^6.15.2",
+ "raw-body": "^3.0.2",
+ "type-is": "^2.1.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/body-parser/node_modules/content-type": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz",
+ "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/bytes": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
+ "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/call-bind-apply-helpers": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/call-bound": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz",
+ "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "get-intrinsic": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/chai": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz",
+ "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/commander": {
+ "version": "9.5.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-9.5.0.tgz",
+ "integrity": "sha512-KRs7WVDKg86PWiuAqhDrAQnTXZKraVcCc6vFdL14qrZ/DcWwuRo7VoiYXalXO7S5GKpqYiVEwCbgFDfxNHKJBQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^12.20.0 || >=14"
+ }
+ },
+ "node_modules/content-disposition": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-1.1.0.tgz",
+ "integrity": "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/content-type": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
+ "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/cookie": {
+ "version": "0.7.2",
+ "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
+ "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/cookie-signature": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",
+ "integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.6.0"
+ }
+ },
+ "node_modules/cors": {
+ "version": "2.8.6",
+ "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.6.tgz",
+ "integrity": "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==",
+ "license": "MIT",
+ "dependencies": {
+ "object-assign": "^4",
+ "vary": "^1"
+ },
+ "engines": {
+ "node": ">= 0.10"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/cross-spawn": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
+ "license": "MIT",
+ "dependencies": {
+ "path-key": "^3.1.0",
+ "shebang-command": "^2.0.0",
+ "which": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/depd": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/detect-libc": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "peer": true,
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/dunder-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "gopd": "^1.2.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/ee-first": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz",
+ "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==",
+ "license": "MIT"
+ },
+ "node_modules/encodeurl": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz",
+ "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/es-define-property": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",
+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-errors": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-module-lexer": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz",
+ "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/es-object-atoms": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.2.tgz",
+ "integrity": "sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/esbuild": {
+ "version": "0.28.2",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.2.tgz",
+ "integrity": "sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.28.2",
+ "@esbuild/android-arm": "0.28.2",
+ "@esbuild/android-arm64": "0.28.2",
+ "@esbuild/android-x64": "0.28.2",
+ "@esbuild/darwin-arm64": "0.28.2",
+ "@esbuild/darwin-x64": "0.28.2",
+ "@esbuild/freebsd-arm64": "0.28.2",
+ "@esbuild/freebsd-x64": "0.28.2",
+ "@esbuild/linux-arm": "0.28.2",
+ "@esbuild/linux-arm64": "0.28.2",
+ "@esbuild/linux-ia32": "0.28.2",
+ "@esbuild/linux-loong64": "0.28.2",
+ "@esbuild/linux-mips64el": "0.28.2",
+ "@esbuild/linux-ppc64": "0.28.2",
+ "@esbuild/linux-riscv64": "0.28.2",
+ "@esbuild/linux-s390x": "0.28.2",
+ "@esbuild/linux-x64": "0.28.2",
+ "@esbuild/netbsd-arm64": "0.28.2",
+ "@esbuild/netbsd-x64": "0.28.2",
+ "@esbuild/openbsd-arm64": "0.28.2",
+ "@esbuild/openbsd-x64": "0.28.2",
+ "@esbuild/openharmony-arm64": "0.28.2",
+ "@esbuild/sunos-x64": "0.28.2",
+ "@esbuild/win32-arm64": "0.28.2",
+ "@esbuild/win32-ia32": "0.28.2",
+ "@esbuild/win32-x64": "0.28.2"
+ }
+ },
+ "node_modules/escape-html": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz",
+ "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==",
+ "license": "MIT"
+ },
+ "node_modules/estree-walker": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0"
+ }
+ },
+ "node_modules/etag": {
+ "version": "1.8.1",
+ "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz",
+ "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/eventsource": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",
+ "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",
+ "license": "MIT",
+ "dependencies": {
+ "eventsource-parser": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/eventsource-parser": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.1.1.tgz",
+ "integrity": "sha512-EKN1vKAMcZ8MlYMpaNuxN6R9yakzH6uajHcHVTqWJzvu5pWw9DyhbP35HH8MVBQ+dZjAfDxk+A8NiR9KWaXiyQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
+ "node_modules/expect-type": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
+ "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
+ "node_modules/express": {
+ "version": "5.2.1",
+ "resolved": "https://registry.npmjs.org/express/-/express-5.2.1.tgz",
+ "integrity": "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw==",
+ "license": "MIT",
+ "dependencies": {
+ "accepts": "^2.0.0",
+ "body-parser": "^2.2.1",
+ "content-disposition": "^1.0.0",
+ "content-type": "^1.0.5",
+ "cookie": "^0.7.1",
+ "cookie-signature": "^1.2.1",
+ "debug": "^4.4.0",
+ "depd": "^2.0.0",
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "etag": "^1.8.1",
+ "finalhandler": "^2.1.0",
+ "fresh": "^2.0.0",
+ "http-errors": "^2.0.0",
+ "merge-descriptors": "^2.0.0",
+ "mime-types": "^3.0.0",
+ "on-finished": "^2.4.1",
+ "once": "^1.4.0",
+ "parseurl": "^1.3.3",
+ "proxy-addr": "^2.0.7",
+ "qs": "^6.14.0",
+ "range-parser": "^1.2.1",
+ "router": "^2.2.0",
+ "send": "^1.1.0",
+ "serve-static": "^2.2.0",
+ "statuses": "^2.0.1",
+ "type-is": "^2.0.1",
+ "vary": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/express-rate-limit": {
+ "version": "8.7.1",
+ "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.7.1.tgz",
+ "integrity": "sha512-2FXbqkygil3mZiXzEtM0IjE/UBmBNot0J1GEVrJT4JbrvwOSoEtqtO+wHbiMQELWe1eNvHoYRg2dkjOid+6JkA==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.3",
+ "ip-address": "^10.2.0"
+ },
+ "engines": {
+ "node": ">= 16"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/express-rate-limit"
+ },
+ "peerDependencies": {
+ "express": ">= 4.11"
+ }
+ },
+ "node_modules/fast-deep-equal": {
+ "version": "3.1.3",
+ "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
+ "license": "MIT"
+ },
+ "node_modules/fast-uri": {
+ "version": "3.1.8",
+ "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz",
+ "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/finalhandler": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-2.1.1.tgz",
+ "integrity": "sha512-S8KoZgRZN+a5rNwqTxlZZePjT/4cnm0ROV70LedRHZ0p8u9fRID0hJUZQpkKLzro8LfmC8sx23bY6tVNxv8pQA==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.0",
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "on-finished": "^2.4.1",
+ "parseurl": "^1.3.3",
+ "statuses": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 18.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/forwarded": {
+ "version": "0.2.0",
+ "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz",
+ "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/fresh": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/fresh/-/fresh-2.0.0.tgz",
+ "integrity": "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "peer": true,
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/function-bind": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-intrinsic": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bind-apply-helpers": "^1.0.2",
+ "es-define-property": "^1.0.1",
+ "es-errors": "^1.3.0",
+ "es-object-atoms": "^1.1.1",
+ "function-bind": "^1.1.2",
+ "get-proto": "^1.0.1",
+ "gopd": "^1.2.0",
+ "has-symbols": "^1.1.0",
+ "hasown": "^2.0.2",
+ "math-intrinsics": "^1.1.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-proto": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",
+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
+ "license": "MIT",
+ "dependencies": {
+ "dunder-proto": "^1.0.1",
+ "es-object-atoms": "^1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/gopd": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/has-symbols": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",
+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/hasown": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
+ "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
+ "license": "MIT",
+ "dependencies": {
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/hono": {
+ "version": "4.13.13",
+ "resolved": "https://registry.npmjs.org/hono/-/hono-4.13.13.tgz",
+ "integrity": "sha512-CQ46U0ZkAGmbT/4UxdzzGJpacP2IeKgY4a5/tOI9AABbpOMfK739wfDXmv1usCk+3RkKj1hQy4/fjhiwa2xlrA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=16.9.0"
+ }
+ },
+ "node_modules/http-errors": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz",
+ "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==",
+ "license": "MIT",
+ "dependencies": {
+ "depd": "~2.0.0",
+ "inherits": "~2.0.4",
+ "setprototypeof": "~1.2.0",
+ "statuses": "~2.0.2",
+ "toidentifier": "~1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/iconv-lite": {
+ "version": "0.7.3",
+ "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",
+ "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==",
+ "license": "MIT",
+ "dependencies": {
+ "safer-buffer": ">= 2.1.2 < 3.0.0"
+ },
+ "engines": {
+ "node": ">=0.10.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/inherits": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz",
+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",
+ "license": "ISC"
+ },
+ "node_modules/ip-address": {
+ "version": "10.7.3",
+ "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.3.tgz",
+ "integrity": "sha512-A1kdq/tSb5QjvKvAMgIoEvDBIgL7qaqVP/jkvSwYYRZ9iEzvPpopxp2wQfu3SuZRHtpHNxMn8Fs0bS+gf5Xmwg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 12"
+ }
+ },
+ "node_modules/ipaddr.js": {
+ "version": "1.9.1",
+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz",
+ "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/is-promise": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/is-promise/-/is-promise-4.0.0.tgz",
+ "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
+ "license": "MIT"
+ },
+ "node_modules/isexe": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
+ "license": "ISC"
+ },
+ "node_modules/jose": {
+ "version": "6.2.12",
+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.12.tgz",
+ "integrity": "sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/panva"
+ }
+ },
+ "node_modules/json-schema-traverse": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz",
+ "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==",
+ "license": "MIT"
+ },
+ "node_modules/json-schema-typed": {
+ "version": "8.0.2",
+ "resolved": "https://registry.npmjs.org/json-schema-typed/-/json-schema-typed-8.0.2.tgz",
+ "integrity": "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA==",
+ "license": "BSD-2-Clause"
+ },
+ "node_modules/lightningcss": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
+ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",
+ "dev": true,
+ "license": "MPL-2.0",
+ "peer": true,
+ "dependencies": {
+ "detect-libc": "^2.0.3"
+ },
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ },
+ "optionalDependencies": {
+ "lightningcss-android-arm64": "1.33.0",
+ "lightningcss-darwin-arm64": "1.33.0",
+ "lightningcss-darwin-x64": "1.33.0",
+ "lightningcss-freebsd-x64": "1.33.0",
+ "lightningcss-linux-arm-gnueabihf": "1.33.0",
+ "lightningcss-linux-arm64-gnu": "1.33.0",
+ "lightningcss-linux-arm64-musl": "1.33.0",
+ "lightningcss-linux-x64-gnu": "1.33.0",
+ "lightningcss-linux-x64-musl": "1.33.0",
+ "lightningcss-win32-arm64-msvc": "1.33.0",
+ "lightningcss-win32-x64-msvc": "1.33.0"
+ }
+ },
+ "node_modules/lightningcss-android-arm64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz",
+ "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "peer": true,
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-arm64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz",
+ "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "peer": true,
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-x64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz",
+ "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "peer": true,
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-freebsd-x64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz",
+ "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "peer": true,
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm-gnueabihf": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz",
+ "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "peer": true,
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-gnu": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz",
+ "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "peer": true,
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-musl": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz",
+ "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "peer": true,
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-gnu": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",
+ "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "peer": true,
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-musl": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz",
+ "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "peer": true,
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-arm64-msvc": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz",
+ "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "peer": true,
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-x64-msvc": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz",
+ "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "peer": true,
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/magic-string": {
+ "version": "1.4.3",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.3.tgz",
+ "integrity": "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.6.0"
+ }
+ },
+ "node_modules/math-intrinsics": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/media-typer": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-1.1.1.tgz",
+ "integrity": "sha512-yz3xRaG20c6/BOzvYoDaGtPmGscs7YivItZEEqe6GbwNfHuxu9YNmvnEkMzKldAGY4/80pRcQRZSEnhquk9XuQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/merge-descriptors": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-2.0.0.tgz",
+ "integrity": "sha512-Snk314V5ayFLhp3fkUREub6WtjBfPdCPY1Ln8/8munuLuiYhsABgBVWsozAG+MWMbVEvcdcpbi9R7ww22l9Q3g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/sindresorhus"
+ }
+ },
+ "node_modules/mime-db": {
+ "version": "1.54.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz",
+ "integrity": "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/mime-types": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-3.0.2.tgz",
+ "integrity": "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A==",
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": "^1.54.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "license": "MIT"
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.20",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
+ "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "peer": true,
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/negotiator": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.1.0.tgz",
+ "integrity": "sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg==",
+ "license": "MIT",
+ "dependencies": {
+ "content-type": "^2.1.0"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/negotiator/node_modules/content-type": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz",
+ "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/object-assign": {
+ "version": "4.1.1",
+ "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
+ "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/object-inspect": {
+ "version": "1.13.4",
+ "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
+ "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/obug": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz",
+ "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==",
+ "dev": true,
+ "funding": [
+ "https://github.com/sponsors/sxzz",
+ "https://opencollective.com/debug"
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/on-finished": {
+ "version": "2.4.1",
+ "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz",
+ "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==",
+ "license": "MIT",
+ "dependencies": {
+ "ee-first": "1.1.1"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/once": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
+ "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
+ "license": "ISC",
+ "dependencies": {
+ "wrappy": "1"
+ }
+ },
+ "node_modules/parseurl": {
+ "version": "1.3.3",
+ "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz",
+ "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/path-key": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/path-to-regexp": {
+ "version": "8.4.2",
+ "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",
+ "integrity": "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC",
+ "peer": true
+ },
+ "node_modules/picomatch": {
+ "version": "4.0.7",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/pkce-challenge": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",
+ "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.29",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz",
+ "integrity": "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "nanoid": "^3.3.19",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.2"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/postject": {
+ "version": "1.0.0-alpha.6",
+ "resolved": "https://registry.npmjs.org/postject/-/postject-1.0.0-alpha.6.tgz",
+ "integrity": "sha512-b9Eb8h2eVqNE8edvKdwqkrY6O7kAwmI8kcnBv1NScolYJbo59XUF0noFq+lxbC1yN20bmC0WBEbDC5H/7ASb0A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "commander": "^9.4.0"
+ },
+ "bin": {
+ "postject": "dist/cli.js"
+ },
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/proxy-addr": {
+ "version": "2.0.8",
+ "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.8.tgz",
+ "integrity": "sha512-5nnx0yGyVUcY6t9RnWcARWtwT9F1D8O9rt08htPvnd49W1IgZtmLkhu9WfMzQj1cFxjHIO6connUNVW5k7AVyQ==",
+ "license": "MIT",
+ "dependencies": {
+ "forwarded": "0.2.0",
+ "ipaddr.js": "1.9.1"
+ },
+ "engines": {
+ "node": ">= 0.10"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/qs": {
+ "version": "6.16.0",
+ "resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz",
+ "integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "es-define-property": "^1.0.1",
+ "side-channel": "^1.1.1"
+ },
+ "engines": {
+ "node": ">=0.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/range-parser": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.3.0.tgz",
+ "integrity": "sha512-hek2mFQpPuI4E1BBKrSto+BU3e3x4xuarsbiwr3+lf7p44juvFMV0XFWQAP3xUyqXA4RrXLIoaSUGbSt056ZMw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/raw-body": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-3.0.2.tgz",
+ "integrity": "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA==",
+ "license": "MIT",
+ "dependencies": {
+ "bytes": "~3.1.2",
+ "http-errors": "~2.0.1",
+ "iconv-lite": "~0.7.0",
+ "unpipe": "~1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.10"
+ }
+ },
+ "node_modules/require-from-string": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/rolldown": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.12.tgz",
+ "integrity": "sha512-8wafseiaG80xmXSfqidUNqZcylTlhmPZZt+za2m+js2sFZ8dTNlhIOV2WcbIPx2hgwPBJpEUGFAMZ9bgBBLTSQ==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "@oxc-project/types": "=0.152.0",
+ "@rolldown/pluginutils": "^1.0.0"
+ },
+ "bin": {
+ "rolldown": "bin/cli.mjs"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "optionalDependencies": {
+ "@rolldown/binding-android-arm-eabi": "1.2.12",
+ "@rolldown/binding-android-arm64": "1.2.12",
+ "@rolldown/binding-darwin-arm64": "1.2.12",
+ "@rolldown/binding-darwin-x64": "1.2.12",
+ "@rolldown/binding-freebsd-x64": "1.2.12",
+ "@rolldown/binding-linux-arm-gnueabihf": "1.2.12",
+ "@rolldown/binding-linux-arm64-gnu": "1.2.12",
+ "@rolldown/binding-linux-arm64-musl": "1.2.12",
+ "@rolldown/binding-linux-ppc64-gnu": "1.2.12",
+ "@rolldown/binding-linux-s390x-gnu": "1.2.12",
+ "@rolldown/binding-linux-x64-gnu": "1.2.12",
+ "@rolldown/binding-linux-x64-musl": "1.2.12",
+ "@rolldown/binding-openharmony-arm64": "1.2.12",
+ "@rolldown/binding-win32-arm64-msvc": "1.2.12",
+ "@rolldown/binding-win32-x64-msvc": "1.2.12"
+ }
+ },
+ "node_modules/router": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/router/-/router-2.2.0.tgz",
+ "integrity": "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.0",
+ "depd": "^2.0.0",
+ "is-promise": "^4.0.0",
+ "parseurl": "^1.3.3",
+ "path-to-regexp": "^8.0.0"
+ },
+ "engines": {
+ "node": ">= 18"
+ }
+ },
+ "node_modules/safer-buffer": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
+ "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
+ "license": "MIT"
+ },
+ "node_modules/send": {
+ "version": "1.2.1",
+ "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz",
+ "integrity": "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ==",
+ "license": "MIT",
+ "dependencies": {
+ "debug": "^4.4.3",
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "etag": "^1.8.1",
+ "fresh": "^2.0.0",
+ "http-errors": "^2.0.1",
+ "mime-types": "^3.0.2",
+ "ms": "^2.1.3",
+ "on-finished": "^2.4.1",
+ "range-parser": "^1.2.1",
+ "statuses": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/serve-static": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.1.tgz",
+ "integrity": "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw==",
+ "license": "MIT",
+ "dependencies": {
+ "encodeurl": "^2.0.0",
+ "escape-html": "^1.0.3",
+ "parseurl": "^1.3.3",
+ "send": "^1.2.0"
+ },
+ "engines": {
+ "node": ">= 18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/setprototypeof": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
+ "license": "ISC"
+ },
+ "node_modules/shebang-command": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
+ "license": "MIT",
+ "dependencies": {
+ "shebang-regex": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/shebang-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/side-channel": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz",
+ "integrity": "sha512-6x6dK6zJdpTzF4sQeNYxwtvBzf6Eg4GtlesS94HOvTudUeyK2WXAaIfmDgsyslYrRBeFIlsi54AYsFGUuhmvrQ==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "object-inspect": "^1.13.4",
+ "side-channel-list": "^1.0.1",
+ "side-channel-map": "^1.0.1",
+ "side-channel-weakmap": "^1.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-list": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz",
+ "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==",
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "object-inspect": "^1.13.4"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-map": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz",
+ "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.5",
+ "object-inspect": "^1.13.3"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/side-channel-weakmap": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz",
+ "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==",
+ "license": "MIT",
+ "dependencies": {
+ "call-bound": "^1.0.2",
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.5",
+ "object-inspect": "^1.13.3",
+ "side-channel-map": "^1.0.1"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
+ "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "peer": true,
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/statuses": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz",
+ "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/std-env": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz",
+ "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinybench": {
+ "version": "6.2.0",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.0.tgz",
+ "integrity": "sha512-78U2TlB2CnVenajOFzf3BKSm0J6oz5L0NV7g32LCPccvYc0lbWvys4d3uUUCS2B1N8PAf2+aekR8i1KbC3HO7Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/tinyexec": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz",
+ "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.17",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.4"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/toidentifier": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz",
+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.6"
+ }
+ },
+ "node_modules/type-is": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",
+ "integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==",
+ "license": "MIT",
+ "dependencies": {
+ "content-type": "^2.0.0",
+ "media-typer": "^1.1.0",
+ "mime-types": "^3.0.0"
+ },
+ "engines": {
+ "node": ">= 18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/type-is/node_modules/content-type": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz",
+ "integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/express"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz",
+ "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc"
+ },
+ "engines": {
+ "node": ">=16.20.0"
+ },
+ "optionalDependencies": {
+ "@typescript/typescript-aix-ppc64": "7.0.2",
+ "@typescript/typescript-darwin-arm64": "7.0.2",
+ "@typescript/typescript-darwin-x64": "7.0.2",
+ "@typescript/typescript-freebsd-arm64": "7.0.2",
+ "@typescript/typescript-freebsd-x64": "7.0.2",
+ "@typescript/typescript-linux-arm": "7.0.2",
+ "@typescript/typescript-linux-arm64": "7.0.2",
+ "@typescript/typescript-linux-loong64": "7.0.2",
+ "@typescript/typescript-linux-mips64el": "7.0.2",
+ "@typescript/typescript-linux-ppc64": "7.0.2",
+ "@typescript/typescript-linux-riscv64": "7.0.2",
+ "@typescript/typescript-linux-s390x": "7.0.2",
+ "@typescript/typescript-linux-x64": "7.0.2",
+ "@typescript/typescript-netbsd-arm64": "7.0.2",
+ "@typescript/typescript-netbsd-x64": "7.0.2",
+ "@typescript/typescript-openbsd-arm64": "7.0.2",
+ "@typescript/typescript-openbsd-x64": "7.0.2",
+ "@typescript/typescript-sunos-x64": "7.0.2",
+ "@typescript/typescript-win32-arm64": "7.0.2",
+ "@typescript/typescript-win32-x64": "7.0.2"
+ }
+ },
+ "node_modules/undici-types": {
+ "version": "8.9.0",
+ "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz",
+ "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/unpipe": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz",
+ "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/vary": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz",
+ "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
+ "node_modules/vite": {
+ "version": "8.3.3",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.3.tgz",
+ "integrity": "sha512-cTAldKPImjg6c+gk48U19POPn3GCBzZwpdsN8ZMEEcbpes+6/wvfqUd0C2y3qYY4wsj8PwgFwrZ/1jBPVttMSg==",
+ "dev": true,
+ "license": "MIT",
+ "peer": true,
+ "dependencies": {
+ "lightningcss": "^1.33.0",
+ "picomatch": "^4.0.7",
+ "postcss": "^8.5.28",
+ "rolldown": "~1.2.11",
+ "tinyglobby": "^0.2.17"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^20.19.0 || >=22.12.0",
+ "@vitejs/devtools": "^0.7.1",
+ "esbuild": "^0.27.0 || ^0.28.0",
+ "jiti": ">=1.21.0",
+ "less": "^4.0.0",
+ "sass": "^1.70.0",
+ "sass-embedded": "^1.70.0",
+ "stylus": ">=0.54.8",
+ "sugarss": "^5.0.0",
+ "terser": "^5.16.0",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "@vitejs/devtools": {
+ "optional": true
+ },
+ "esbuild": {
+ "optional": true
+ },
+ "jiti": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vitest": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.3.tgz",
+ "integrity": "sha512-xMw97S3rjdtj5dkVat7jCsqWBpvchs3RlpQctUqwJD0KkERk40vz2fJ77lDwW/Vzh/pk18eItYAzkodhSes3jQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/chai": "^5.2.2",
+ "@vitest/mocker": "5.0.3",
+ "chai": "^6.2.2",
+ "es-module-lexer": "^2.3.2",
+ "expect-type": "^1.4.0",
+ "magic-string": "^1.2.3",
+ "obug": "^2.1.4",
+ "picomatch": "^4.0.7",
+ "std-env": "^4.2.0",
+ "tinybench": "^6.1.4",
+ "tinyexec": "^1.3.0",
+ "tinyglobby": "^0.2.17",
+ "why-is-node-running": "3.2.1"
+ },
+ "bin": {
+ "vitest": "vitest.mjs"
+ },
+ "engines": {
+ "node": "^22.12.0 || ^24.0.0 || >=26.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "@edge-runtime/vm": "*",
+ "@opentelemetry/api": "^1.9.0",
+ "@types/node": "^22.0.0 || >=24.0.0",
+ "@vitest/browser-playwright": "5.0.3",
+ "@vitest/browser-preview": "5.0.3",
+ "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0",
+ "@vitest/coverage-istanbul": "5.0.3",
+ "@vitest/coverage-v8": "5.0.3",
+ "@vitest/ui": "5.0.3",
+ "happy-dom": "*",
+ "jsdom": "*",
+ "vite": "^6.4.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@edge-runtime/vm": {
+ "optional": true
+ },
+ "@opentelemetry/api": {
+ "optional": true
+ },
+ "@types/node": {
+ "optional": true
+ },
+ "@vitest/browser-playwright": {
+ "optional": true
+ },
+ "@vitest/browser-preview": {
+ "optional": true
+ },
+ "@vitest/browser-webdriverio": {
+ "optional": true
+ },
+ "@vitest/coverage-istanbul": {
+ "optional": true
+ },
+ "@vitest/coverage-v8": {
+ "optional": true
+ },
+ "@vitest/ui": {
+ "optional": true
+ },
+ "happy-dom": {
+ "optional": true
+ },
+ "jsdom": {
+ "optional": true
+ },
+ "vite": {
+ "optional": false
+ }
+ }
+ },
+ "node_modules/which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "license": "ISC",
+ "dependencies": {
+ "isexe": "^2.0.0"
+ },
+ "bin": {
+ "node-which": "bin/node-which"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/why-is-node-running": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz",
+ "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "why-is-node-running": "cli.js"
+ },
+ "engines": {
+ "node": ">=20.11"
+ }
+ },
+ "node_modules/wrappy": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
+ "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
+ "license": "ISC"
+ },
+ "node_modules/zod": {
+ "version": "4.6.5",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz",
+ "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ },
+ "node_modules/zod-to-json-schema": {
+ "version": "3.25.2",
+ "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz",
+ "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==",
+ "license": "ISC",
+ "peerDependencies": {
+ "zod": "^3.25.28 || ^4"
+ }
+ }
+ }
+}
diff --git a/mcp/package.json b/mcp/package.json
new file mode 100644
index 0000000..07dc940
--- /dev/null
+++ b/mcp/package.json
@@ -0,0 +1,24 @@
+{
+ "name": "qls-mcp",
+ "version": "1.0.0",
+ "private": true,
+ "description": "MCP server for Qwen Local Studio (local image generation)",
+ "type": "module",
+ "scripts": {
+ "build": "esbuild src/index.ts --bundle --platform=node --target=node22 --format=cjs --outfile=build/qls-mcp.cjs",
+ "test": "vitest run",
+ "typecheck": "tsc --noEmit",
+ "build:exe": "node scripts/build-exe.mjs"
+ },
+ "dependencies": {
+ "@modelcontextprotocol/sdk": "^1.32.1",
+ "zod": "^4.6.5"
+ },
+ "devDependencies": {
+ "@types/node": "^26.6.4",
+ "esbuild": "^0.28.2",
+ "postject": "^1.0.0-alpha.6",
+ "typescript": "^7.0.2",
+ "vitest": "^5.0.3"
+ }
+}
diff --git a/mcp/scripts/build-exe.mjs b/mcp/scripts/build-exe.mjs
new file mode 100644
index 0000000..b9c3da8
--- /dev/null
+++ b/mcp/scripts/build-exe.mjs
@@ -0,0 +1,25 @@
+// Builds build/qls-mcp.exe: the bundled server injected into a copy of node.exe
+// (Node "single executable application"). No separate Node install is needed to run it.
+import { execFileSync } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const root = path.resolve(here, "..");
+const build = path.join(root, "build");
+const run = (cmd, args) => execFileSync(cmd, args, { cwd: root, stdio: "inherit", shell: process.platform === "win32" && cmd === "npx" });
+
+run("npx", ["esbuild", "src/index.ts", "--bundle", "--platform=node", "--target=node22", "--format=cjs", "--outfile=build/qls-mcp.cjs", "--minify"]);
+fs.writeFileSync(
+ path.join(build, "sea-config.json"),
+ JSON.stringify({ main: "build/qls-mcp.cjs", output: "build/sea-prep.blob", disableExperimentalSEAWarning: true, useSnapshot: false, useCodeCache: true }),
+);
+run(process.execPath, ["--experimental-sea-config", "build/sea-config.json"]);
+const exe = path.join(build, "qls-mcp.exe");
+fs.copyFileSync(process.execPath, exe);
+run("npx", ["postject", exe, "NODE_SEA_BLOB", path.join(build, "sea-prep.blob"), "--sentinel-fuse", "NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2"]);
+
+const sidecar = path.resolve(root, "..", "src-tauri", "binaries", "qls-mcp-x86_64-pc-windows-msvc.exe");
+fs.copyFileSync(exe, sidecar);
+console.log(`built ${exe} (${(fs.statSync(exe).size / 1e6).toFixed(1)} MB) -> ${sidecar}`);
diff --git a/mcp/src/index.ts b/mcp/src/index.ts
new file mode 100644
index 0000000..43aa695
--- /dev/null
+++ b/mcp/src/index.ts
@@ -0,0 +1,115 @@
+// qls-mcp — MCP server (stdio) for Qwen Local Studio. Uses the same local service and
+// generation engine as the desktop app. Works when the app is closed: the service and
+// the inference server are started on demand. Everything stays on 127.0.0.1.
+
+import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
+import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
+import { handlers, schemas, toErrorResult, type ToolContext, type ToolResult } from "./tools.js";
+import { ServiceClient } from "./service.js";
+
+const VERSION = "1.0.0";
+
+const DESCRIPTIONS: Record<keyof typeof schemas, { title: string; description: string }> = {
+ generate_image: {
+ title: "Generate image",
+ description:
+ "Generate an image from a text prompt with the local Qwen-Image 2.1 model. Dimensions are chosen automatically (aspect ratio can be inferred from the prompt, e.g. '16:9 hero image') unless width/height or aspect_ratio are given. Returns the absolute path of the saved PNG. Runs fully offline; typically 45 s–4 min.",
+ },
+ edit_image: {
+ title: "Edit image",
+ description:
+ "Edit an existing image with a natural-language instruction (e.g. 'make the background nighttime, keep the foreground unchanged'). Preserves the input's width, height and aspect ratio by default. The input file is never overwritten.",
+ },
+ edit_images: {
+ title: "Edit with multiple references",
+ description:
+ "Create an image from several reference images (up to 10) and an instruction. Order matters: refer to them as image 1, image 2, ... in the prompt. The output follows image 1's aspect ratio unless width/height or aspect_ratio are given.",
+ },
+ outpaint_image: {
+ title: "Expand image (outpaint)",
+ description:
+ "Extend an image beyond its borders. Give the expansion per side in pixels or percent; the canvas, mask and model-aligned sizes are built automatically and the original pixels are preserved exactly.",
+ },
+ inpaint_image: {
+ title: "Inpaint image",
+ description: "Regenerate only the masked area of an image (mask: white = change, black = keep). Pixels outside the mask are preserved exactly.",
+ },
+ upscale_image: {
+ title: "Upscale image",
+ description:
+ "Enlarge an image (default 2x, or to a width/height up to 8192 px). method 'quick' runs the configured ESRGAN upscaler model only (UltraSharp by default; seconds, no new content); 'detailed' first re-renders fine detail at about 2K with a low-denoise refine, then the upscaler model (about a minute). Saves a new file; the input is never overwritten.",
+ },
+ get_image_info: {
+ title: "Image info",
+ description: "Width, height, aspect ratio, file type and, for images made by Qwen Local Studio, the generation metadata (prompt, seed, model, steps...).",
+ },
+ get_generator_status: {
+ title: "Generator status",
+ description: "Whether the local inference server is running and the model loaded, GPU and VRAM, the active job and the queue.",
+ },
+};
+
+const client = new ServiceClient();
+const server = new McpServer({ name: "qwen-local-studio", version: VERSION }, { capabilities: { tools: {} } });
+
+function toMcp(r: ToolResult) {
+ const content: ({ type: "text"; text: string } | { type: "image"; data: string; mimeType: string })[] = [{ type: "text", text: r.text }];
+ if (r.previewJpeg) content.push({ type: "image", data: r.previewJpeg.toString("base64"), mimeType: "image/jpeg" });
+ return { content, structuredContent: r.structured, isError: r.isError ?? false };
+}
+
+for (const name of Object.keys(schemas) as (keyof typeof schemas)[]) {
+ const d = DESCRIPTIONS[name];
+ server.registerTool(
+ name,
+ {
+ title: d.title,
+ description: d.description,
+ inputSchema: schemas[name],
+ annotations: { readOnlyHint: name.startsWith("get_"), openWorldHint: false, destructiveHint: false, idempotentHint: name.startsWith("get_") },
+ },
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ async (args: any, extra: any) => {
+ const token = extra?._meta?.progressToken;
+ let n = 0;
+ const ctx: ToolContext = {
+ client,
+ // Claude Code sets CLAUDE_PROJECT_DIR for MCP servers; otherwise use the working directory.
+ cwd: process.env.CLAUDE_PROJECT_DIR || process.cwd(),
+ signal: extra?.signal,
+ progress: (message) => {
+ if (token === undefined) return;
+ n += 1;
+ extra.sendNotification({ method: "notifications/progress", params: { progressToken: token, progress: n, message } }).catch(() => {});
+ },
+ };
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ return toMcp(await (handlers[name] as any)(args, ctx));
+ } catch (e) {
+ return toMcp(toErrorResult(e));
+ }
+ },
+ );
+}
+
+async function main() {
+ if (process.argv.includes("--version")) {
+ process.stdout.write(`qls-mcp ${VERSION}\n`);
+ return;
+ }
+ const transport = new StdioServerTransport();
+ await server.connect(transport);
+ const shutdown = async () => {
+ await client.release();
+ process.exit(0);
+ };
+ process.stdin.on("close", shutdown);
+ process.on("SIGINT", shutdown);
+ process.on("SIGTERM", shutdown);
+}
+
+main().catch((e) => {
+ process.stderr.write(`qls-mcp failed: ${e instanceof Error ? e.stack : String(e)}\n`);
+ process.exit(1);
+});
diff --git a/mcp/src/paths.ts b/mcp/src/paths.ts
new file mode 100644
index 0000000..08053ca
--- /dev/null
+++ b/mcp/src/paths.ts
@@ -0,0 +1,88 @@
+// Path policy for MCP clients. An agent may only read images from — and write images
+// to — the project folder (MCP working directory), the app's output folder, and any
+// folders listed in QLS_MCP_ALLOWED_DIRS (semicolon separated). The service validates
+// again on its side (UNC/device paths, traversal, no overwrite).
+
+import fs from "node:fs";
+import path from "node:path";
+
+const p = path.win32;
+
+export const INPUT_EXT = [".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif", ".tif", ".tiff", ".heic", ".heif"];
+export const OUTPUT_EXT = [".png", ".jpg", ".jpeg", ".webp"];
+export const MAX_INPUT_BYTES = 200 * 1024 * 1024;
+
+export class PathError extends Error {}
+
+function realish(target: string): string {
+ // Resolve symlinks/junctions on the deepest existing ancestor.
+ let cur = target;
+ const rest: string[] = [];
+ while (!fs.existsSync(cur)) {
+ const parent = p.dirname(cur);
+ if (parent === cur) return target;
+ rest.unshift(p.basename(cur));
+ cur = parent;
+ }
+ let real = cur;
+ try {
+ real = fs.realpathSync.native(cur);
+ } catch {
+ /* keep lexical */
+ }
+ return p.join(real, ...rest);
+}
+
+export function isWithin(target: string, root: string): boolean {
+ const t = realish(p.resolve(target)).toLowerCase();
+ const r = realish(p.resolve(root)).toLowerCase().replace(/\\+$/, "");
+ return t === r || t.startsWith(r + "\\");
+}
+
+/** Lexical checks shared by inputs and outputs; returns an absolute normalized path. */
+export function normalize(raw: string, cwd: string): string {
+ const s = (raw ?? "").trim();
+ if (!s) throw new PathError("The path is empty.");
+ if (/[\u0000-\u001f]/.test(s)) throw new PathError("The path contains invalid characters.");
+ if (s.startsWith("\\\\") || s.startsWith("//")) throw new PathError("Network and device paths are not allowed.");
+ if (/^[a-zA-Z]:(?![\\/])/.test(s)) throw new PathError("Drive-relative paths (like C:file.png) are not allowed.");
+ const abs = p.resolve(cwd, s.replace(/\//g, "\\"));
+ const parts = abs.slice(3).split("\\");
+ for (const part of parts) {
+ if (part.includes(":")) throw new PathError("Alternate data streams are not allowed.");
+ if (/^(con|prn|aux|nul|com\d|lpt\d)(\..*)?$/i.test(part)) throw new PathError(`'${part}' is a reserved Windows name.`);
+ }
+ return abs;
+}
+
+export function checkInput(raw: string, cwd: string, roots: string[]): string {
+ const abs = normalize(raw, cwd);
+ if (!INPUT_EXT.includes(p.extname(abs).toLowerCase())) throw new PathError("Only PNG, JPEG, WebP, BMP, GIF, TIFF and HEIC images are supported.");
+ if (!roots.some((r) => isWithin(abs, r))) throw new PathError(`${abs} is outside the allowed folders (${roots.join("; ")}).`);
+ let st: fs.Stats;
+ try {
+ st = fs.statSync(abs);
+ } catch {
+ throw new PathError(`File not found: ${abs}`);
+ }
+ if (!st.isFile()) throw new PathError(`${abs} is not a file.`);
+ if (st.size > MAX_INPUT_BYTES) throw new PathError("The image file is larger than 200 MB.");
+ return abs;
+}
+
+export function checkOutput(raw: string, cwd: string, roots: string[]): string {
+ let abs = normalize(raw, cwd);
+ const ext = p.extname(abs).toLowerCase();
+ if (!ext) abs += ".png";
+ else if (!OUTPUT_EXT.includes(ext)) throw new PathError("output_path must end in .png, .jpg or .webp.");
+ if (!roots.some((r) => isWithin(abs, r))) throw new PathError(`${abs} is outside the allowed output folders (${roots.join("; ")}).`);
+ return abs;
+}
+
+export function allowedRoots(cwd: string, outputDir: string | null): string[] {
+ const extra = (process.env.QLS_MCP_ALLOWED_DIRS ?? "")
+ .split(";")
+ .map((x) => x.trim())
+ .filter(Boolean);
+ return [cwd, ...(outputDir ? [outputDir] : []), ...extra].map((r) => p.resolve(r));
+}
diff --git a/mcp/src/service.ts b/mcp/src/service.ts
new file mode 100644
index 0000000..3ca7865
--- /dev/null
+++ b/mcp/src/service.ts
@@ -0,0 +1,150 @@
+// Client for the local qls-service. Finds it via service.json, starts it if needed
+// (the service in turn starts/reuses sd-server), and holds an "mcp" lease while alive.
+
+import { spawn } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+
+export interface ServiceInfo {
+ port: number;
+ token: string;
+ pid: number;
+ version: string;
+}
+
+export class ServiceError extends Error {
+ constructor(
+ message: string,
+ public code = "service_error",
+ public suggestion?: string,
+ public detail?: string,
+ ) {
+ super(message);
+ }
+}
+
+export function dataDir(): string {
+ return process.env.QLS_DATA_DIR ?? path.join(process.env.LOCALAPPDATA ?? path.join(process.env.USERPROFILE ?? "C:\\", "AppData", "Local"), "QwenLocalStudio");
+}
+
+function readInfo(): ServiceInfo | null {
+ try {
+ return JSON.parse(fs.readFileSync(path.join(dataDir(), "service.json"), "utf8"));
+ } catch {
+ return null;
+ }
+}
+
+async function ping(port: number): Promise<boolean> {
+ try {
+ const r = await fetch(`http://127.0.0.1:${port}/api/v1/ping`, { signal: AbortSignal.timeout(1500) });
+ return r.ok;
+ } catch {
+ return false;
+ }
+}
+
+export function findServiceExe(): string | null {
+ const local = process.env.LOCALAPPDATA ?? "";
+ const candidates = [
+ process.env.QLS_SERVICE_EXE,
+ path.join(path.dirname(process.execPath), "qls-service.exe"),
+ path.join(local, "Qwen Local Studio", "qls-service.exe"),
+ path.join(process.env.ProgramFiles ?? "C:\\Program Files", "Qwen Local Studio", "qls-service.exe"),
+ // Development checkout (mcp/build -> target/...)
+ path.resolve(__dirname, "..", "..", "target", "release", "qls-service.exe"),
+ path.resolve(__dirname, "..", "..", "target", "debug", "qls-service.exe"),
+ ];
+ for (const c of candidates) {
+ if (c && fs.existsSync(c)) return c;
+ }
+ return null;
+}
+
+export class ServiceClient {
+ private info: ServiceInfo | null = null;
+ private starting: Promise<ServiceInfo> | null = null;
+ private heartbeat: NodeJS.Timeout | null = null;
+ readonly clientId = `mcp-${process.pid}`;
+
+ async ensure(): Promise<ServiceInfo> {
+ if (this.info && (await ping(this.info.port))) return this.info;
+ if (!this.starting) {
+ this.starting = this.start().finally(() => (this.starting = null));
+ }
+ this.info = await this.starting;
+ this.startHeartbeat();
+ return this.info;
+ }
+
+ private async start(): Promise<ServiceInfo> {
+ const existing = readInfo();
+ if (existing && (await ping(existing.port))) return existing;
+ const exe = findServiceExe();
+ if (!exe) {
+ throw new ServiceError(
+ "Qwen Local Studio is not installed (qls-service.exe not found).",
+ "not_installed",
+ "Install Qwen Local Studio, or set QLS_SERVICE_EXE to the path of qls-service.exe.",
+ );
+ }
+ // Detached: the service outlives this MCP process and exits on its own when idle.
+ const child = spawn(exe, [], { detached: true, stdio: "ignore", windowsHide: true });
+ child.unref();
+ const deadline = Date.now() + 30_000;
+ while (Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, 300));
+ const i = readInfo();
+ if (i && (await ping(i.port))) return i;
+ }
+ throw new ServiceError("The Qwen Local Studio service did not start.", "service_unavailable", `See ${path.join(dataDir(), "logs", "service.log")}`);
+ }
+
+ private startHeartbeat() {
+ if (this.heartbeat) return;
+ const beat = () => this.call("POST", "/session/heartbeat", { client_id: this.clientId, kind: "mcp", pid: process.pid }).catch(() => {});
+ beat();
+ this.heartbeat = setInterval(beat, 15_000);
+ this.heartbeat.unref();
+ }
+
+ async release() {
+ if (this.heartbeat) clearInterval(this.heartbeat);
+ if (!this.info) return;
+ try {
+ await fetch(`http://127.0.0.1:${this.info.port}/api/v1/session/release`, {
+ method: "POST",
+ headers: { Authorization: `Bearer ${this.info.token}`, "Content-Type": "application/json" },
+ body: JSON.stringify({ client_id: this.clientId }),
+ signal: AbortSignal.timeout(2000),
+ });
+ } catch {
+ /* service already gone */
+ }
+ }
+
+ async call<T = unknown>(method: string, route: string, body?: unknown, retry = true): Promise<T> {
+ const info = await this.ensure();
+ let res: Response;
+ try {
+ res = await fetch(`http://127.0.0.1:${info.port}/api/v1${route}`, {
+ method,
+ headers: { Authorization: `Bearer ${info.token}`, ...(body !== undefined ? { "Content-Type": "application/json" } : {}) },
+ body: body !== undefined ? JSON.stringify(body) : undefined,
+ });
+ } catch (e) {
+ if (retry) {
+ this.info = null;
+ return this.call(method, route, body, false);
+ }
+ throw new ServiceError("The Qwen Local Studio service is not reachable.", "service_unavailable", undefined, String(e));
+ }
+ const text = await res.text();
+ const data = text ? JSON.parse(text) : null;
+ if (!res.ok) {
+ const err = data?.error ?? {};
+ throw new ServiceError(err.message ?? `HTTP ${res.status}`, err.code ?? "error", err.suggestion, err.detail);
+ }
+ return data as T;
+ }
+}
diff --git a/mcp/src/tools.ts b/mcp/src/tools.ts
new file mode 100644
index 0000000..73f9050
--- /dev/null
+++ b/mcp/src/tools.ts
@@ -0,0 +1,397 @@
+// Tool schemas and handlers. Handlers are framework-free (testable): they receive a
+// context with the service client, the project folder and a progress callback.
+
+import { z } from "zod";
+import { allowedRoots, checkInput, checkOutput, PathError } from "./paths.js";
+import { ServiceClient, ServiceError } from "./service.js";
+
+const quality = z.enum(["fast", "balanced", "quality"]).describe("fast = ~1 MP, 20 steps; balanced = ~1 MP, 40 steps (the default); quality = native 2K, 40 steps (slower; edits share 2K with their references)");
+const seed = z.number().int().min(-1).max(2_147_483_647).describe("Seed for reproducible results; omit or -1 for random");
+const dim = z.number().int().min(64).max(4096);
+const aspect = z
+ .string()
+ .regex(/^(auto|\d{1,2}:\d{1,2})$/, "Use a ratio like 16:9 or 'auto'")
+ .describe("Aspect ratio such as 1:1, 4:3, 3:4, 16:9, 9:16, or auto (inferred from the prompt)");
+const prompt = z.string().trim().min(1, "prompt must not be empty").max(8000);
+const outputPath = z
+ .string()
+ .min(1)
+ .describe("Optional destination (absolute, or relative to the project). Must be inside the project or the app output folder. Existing files are never overwritten; a numbered name is used instead.");
+const preview = z.boolean().describe("Also return a small JPEG preview in the tool result. Default false: images stay local and are not sent to the model.");
+
+export const schemas = {
+ generate_image: {
+ prompt: prompt.describe("What to generate, in natural language"),
+ negative_prompt: z.string().max(2000).optional(),
+ width: dim.optional().describe("Output width in pixels (needs height too). Omit to choose automatically."),
+ height: dim.optional().describe("Output height in pixels (needs width too)."),
+ aspect_ratio: aspect.optional(),
+ quality: quality.optional(),
+ seed: seed.optional(),
+ output_path: outputPath.optional(),
+ include_preview: preview.optional(),
+ },
+ edit_image: {
+ image_path: z.string().min(1).describe("Image to edit (absolute, or relative to the project)"),
+ prompt: prompt.describe("The change to make, e.g. 'make the background nighttime, keep the foreground unchanged'"),
+ output_path: outputPath.optional(),
+ quality: quality.optional(),
+ preserve_dimensions: z.boolean().optional().describe("Keep the input's exact width/height (default true)"),
+ seed: seed.optional(),
+ negative_prompt: z.string().max(2000).optional(),
+ include_preview: preview.optional(),
+ },
+ edit_images: {
+ image_paths: z.array(z.string().min(1)).min(1).max(10).describe("Reference images in order; refer to them as image 1, image 2, ... in the prompt"),
+ prompt: prompt.describe("e.g. 'Use the person from image 1, the clothing from image 2 and the lighting of image 3'"),
+ width: dim.optional(),
+ height: dim.optional(),
+ aspect_ratio: aspect.optional(),
+ quality: quality.optional(),
+ seed: seed.optional(),
+ output_path: outputPath.optional(),
+ include_preview: preview.optional(),
+ },
+ outpaint_image: {
+ image_path: z.string().min(1),
+ prompt: prompt.describe("What the extended area should contain"),
+ left: z.number().min(0).max(16384).default(0),
+ right: z.number().min(0).max(16384).default(0),
+ top: z.number().min(0).max(16384).default(0),
+ bottom: z.number().min(0).max(16384).default(0),
+ units: z.enum(["pixels", "percent"]).default("pixels").describe("Units for left/right/top/bottom; percent is relative to the image width (left/right) or height (top/bottom)"),
+ seed: seed.optional(),
+ quality: quality.optional(),
+ output_path: outputPath.optional(),
+ include_preview: preview.optional(),
+ },
+ inpaint_image: {
+ image_path: z.string().min(1),
+ mask_path: z.string().min(1).describe("Mask image: white = area to change, black = keep (or opaque strokes on a transparent layer)"),
+ prompt: prompt.describe("What should appear in the masked area"),
+ seed: seed.optional(),
+ quality: quality.optional(),
+ output_path: outputPath.optional(),
+ include_preview: preview.optional(),
+ },
+ upscale_image: {
+ image_path: z.string().min(1).describe("Image to upscale (absolute, or relative to the project)"),
+ scale: z.number().gt(1).max(8).optional().describe("Enlargement factor, e.g. 2 (default 2 when no width/height is given)"),
+ width: z.number().int().min(64).max(8192).optional().describe("Target width in pixels; height follows the aspect ratio unless also given"),
+ height: z.number().int().min(64).max(8192).optional().describe("Target height in pixels; width follows the aspect ratio unless also given"),
+ method: z
+ .enum(["quick", "detailed"])
+ .optional()
+ .describe("quick = the configured ESRGAN upscaler model only (UltraSharp by default; seconds, adds no new content, default); detailed = re-render fine detail at ~2K with low denoise, then the upscaler model (about a minute)"),
+ prompt: z.string().max(8000).optional().describe("Optional description used by the detailed refine (defaults to the image's own prompt or a neutral one)"),
+ output_path: outputPath.optional(),
+ include_preview: preview.optional(),
+ },
+ get_image_info: {
+ image_path: z.string().min(1),
+ },
+ get_generator_status: {},
+} as const;
+
+export interface ToolContext {
+ client: ServiceClient;
+ cwd: string;
+ progress: (message: string) => void;
+ signal?: AbortSignal;
+}
+
+export interface ToolResult {
+ text: string;
+ structured: Record<string, unknown>;
+ previewJpeg?: Buffer;
+ isError?: boolean;
+}
+
+type Args<K extends keyof typeof schemas> = z.infer<z.ZodObject<(typeof schemas)[K]>>;
+
+interface JobView {
+ id: string;
+ status: string;
+ stage: string | null;
+ step: [number, number] | null;
+ queue_position: number;
+ plan: { mode: string; working: { width: number; height: number }; notes: string[] } | null;
+ results: Record<string, unknown>[];
+ error: { code: string; message: string; suggestion?: string; detail?: string } | null;
+ notes: string[];
+}
+
+let outputDirCache: string | null = null;
+async function outputDir(client: ServiceClient): Promise<string | null> {
+ if (outputDirCache) return outputDirCache;
+ try {
+ const cfg = await client.call<{ outputDir: string }>("GET", "/config");
+ outputDirCache = cfg.outputDir;
+ } catch {
+ /* fall back to project only */
+ }
+ return outputDirCache;
+}
+
+export function label(j: JobView): string {
+ switch (j.status) {
+ case "queued":
+ return j.queue_position > 1 ? `Queued (position ${j.queue_position})` : "Queued";
+ case "starting_backend":
+ return "Loading the model";
+ case "preparing":
+ return "Preparing";
+ case "saving":
+ return "Saving";
+ case "running":
+ if (j.stage === "generating" && j.step) return `Generating step ${j.step[0]}/${j.step[1]}`;
+ if (j.stage === "refining" && j.step) return `Refining step ${j.step[0]}/${j.step[1]}`;
+ return (
+ {
+ encoding_images: "Encoding reference images",
+ encoding_prompt: "Reading the prompt",
+ decoding: "Decoding",
+ finishing: "Finishing",
+ generating: "Generating",
+ upscaling: "Upscaling",
+ refining: "Refining",
+ }[j.stage ?? ""] ?? "Working"
+ );
+ default:
+ return j.status;
+ }
+}
+
+async function runJob(ctx: ToolContext, body: Record<string, unknown>, includePreview: boolean): Promise<ToolResult> {
+ const job = await ctx.client.call<JobView>("POST", "/jobs", { ...body, workspace: ctx.cwd, client: "mcp" });
+ let last = "";
+ let cancelled = false;
+ const onAbort = () => {
+ cancelled = true;
+ ctx.client.call("POST", `/jobs/${job.id}/cancel`).catch(() => {});
+ };
+ ctx.signal?.addEventListener("abort", onAbort, { once: true });
+ try {
+ for (;;) {
+ const j = await ctx.client.call<JobView>("GET", `/jobs/${job.id}`);
+ const l = label(j);
+ if (l !== last) {
+ last = l;
+ ctx.progress(l);
+ }
+ if (j.status === "done") return formatDone(ctx, j, includePreview);
+ if (j.status === "failed" || j.status === "cancelled") {
+ const e = j.error ?? { code: "cancelled", message: cancelled ? "Cancelled." : "The job was cancelled." };
+ return errorResult(e.message, e.code, e.suggestion, e.detail);
+ }
+ await new Promise((r) => setTimeout(r, 700));
+ }
+ } finally {
+ ctx.signal?.removeEventListener("abort", onAbort);
+ }
+}
+
+async function formatDone(ctx: ToolContext, j: JobView, includePreview: boolean): Promise<ToolResult> {
+ const images = j.results.map((r) => {
+ const extra = (r.extra_paths as string[]) ?? [];
+ return {
+ path: extra[0] ?? (r.file_path as string),
+ library_path: r.file_path,
+ id: r.id,
+ width: r.width,
+ height: r.height,
+ seed: r.seed,
+ };
+ });
+ const r0 = j.results[0];
+ const structured: Record<string, unknown> = {
+ ...images[0],
+ images: images.length > 1 ? images : undefined,
+ mode: r0.mode,
+ prompt: r0.prompt,
+ model: r0.model,
+ steps: r0.steps,
+ cfg: r0.cfg,
+ sampler: r0.sampler,
+ quality: r0.quality,
+ working_size: `${r0.working_width}x${r0.working_height}`,
+ pipeline: r0.pipeline ?? undefined,
+ duration_seconds: Math.round(((r0.duration_ms as number) ?? 0) / 100) / 10,
+ notes: [...new Set([...(j.notes ?? []), ...((r0.notes as string[]) ?? [])])],
+ };
+ let previewJpeg: Buffer | undefined;
+ if (includePreview) {
+ const info = await ctx.client.ensure();
+ const res = await fetch(`http://127.0.0.1:${info.port}/api/v1/gallery/${r0.id}/thumb?token=${info.token}`);
+ if (res.ok) previewJpeg = Buffer.from(await res.arrayBuffer());
+ }
+ const lines = [`Saved ${images.map((i) => i.path).join(", ")} (${images[0].width}x${images[0].height}, seed ${images[0].seed}).`];
+ if (structured.notes && (structured.notes as string[]).length) lines.push(`Notes: ${(structured.notes as string[]).join(" ")}`);
+ return { text: lines.join("\n") + "\n" + JSON.stringify(structured, null, 2), structured, previewJpeg };
+}
+
+export function errorResult(message: string, code = "error", suggestion?: string, detail?: string): ToolResult {
+ const structured = { error: { code, message, suggestion, detail: detail?.slice(0, 2000) } };
+ return { text: [message, suggestion].filter(Boolean).join(" "), structured, isError: true };
+}
+
+async function roots(ctx: ToolContext) {
+ return allowedRoots(ctx.cwd, await outputDir(ctx.client));
+}
+
+function validateDims(w?: number, h?: number) {
+ if ((w == null) !== (h == null)) throw new PathError("Provide both width and height, or neither.");
+}
+
+export const handlers = {
+ async generate_image(a: Args<"generate_image">, ctx: ToolContext) {
+ validateDims(a.width, a.height);
+ const out = a.output_path ? checkOutput(a.output_path, ctx.cwd, await roots(ctx)) : undefined;
+ return runJob(
+ ctx,
+ {
+ prompt: a.prompt,
+ negative_prompt: a.negative_prompt,
+ mode: "generate",
+ images: [],
+ width: a.width,
+ height: a.height,
+ resolution: a.width ? "custom" : "auto",
+ aspect_ratio: a.aspect_ratio,
+ quality: a.quality ?? "balanced",
+ seed: a.seed,
+ output_path: out,
+ advanced: {},
+ },
+ !!a.include_preview,
+ );
+ },
+
+ async edit_image(a: Args<"edit_image">, ctx: ToolContext) {
+ const r = await roots(ctx);
+ const img = checkInput(a.image_path, ctx.cwd, r);
+ const out = a.output_path ? checkOutput(a.output_path, ctx.cwd, r) : undefined;
+ return runJob(
+ ctx,
+ { prompt: a.prompt, negative_prompt: a.negative_prompt, mode: "edit", images: [img], quality: a.quality ?? "balanced", seed: a.seed, preserve_dimensions: a.preserve_dimensions ?? true, output_path: out, advanced: {} },
+ !!a.include_preview,
+ );
+ },
+
+ async edit_images(a: Args<"edit_images">, ctx: ToolContext) {
+ validateDims(a.width, a.height);
+ const r = await roots(ctx);
+ const imgs = a.image_paths.map((x) => checkInput(x, ctx.cwd, r));
+ const out = a.output_path ? checkOutput(a.output_path, ctx.cwd, r) : undefined;
+ return runJob(
+ ctx,
+ {
+ prompt: a.prompt,
+ mode: imgs.length > 1 ? "multi_reference" : "edit",
+ images: imgs,
+ width: a.width,
+ height: a.height,
+ resolution: a.width ? "custom" : "auto",
+ aspect_ratio: a.aspect_ratio,
+ quality: a.quality ?? "balanced",
+ seed: a.seed,
+ output_path: out,
+ advanced: {},
+ },
+ !!a.include_preview,
+ );
+ },
+
+ async outpaint_image(a: Args<"outpaint_image">, ctx: ToolContext) {
+ if (!(a.left > 0 || a.right > 0 || a.top > 0 || a.bottom > 0)) throw new PathError("Set at least one of left, right, top or bottom.");
+ const r = await roots(ctx);
+ const img = checkInput(a.image_path, ctx.cwd, r);
+ const out = a.output_path ? checkOutput(a.output_path, ctx.cwd, r) : undefined;
+ return runJob(
+ ctx,
+ {
+ prompt: a.prompt,
+ mode: "outpaint",
+ images: [img],
+ outpaint: { left: a.left, right: a.right, top: a.top, bottom: a.bottom, units: a.units },
+ quality: a.quality ?? "balanced",
+ seed: a.seed,
+ output_path: out,
+ advanced: {},
+ },
+ !!a.include_preview,
+ );
+ },
+
+ async inpaint_image(a: Args<"inpaint_image">, ctx: ToolContext) {
+ const r = await roots(ctx);
+ const img = checkInput(a.image_path, ctx.cwd, r);
+ const mask = checkInput(a.mask_path, ctx.cwd, r);
+ const out = a.output_path ? checkOutput(a.output_path, ctx.cwd, r) : undefined;
+ return runJob(ctx, { prompt: a.prompt, mode: "inpaint", images: [img], mask, quality: a.quality ?? "balanced", seed: a.seed, output_path: out, advanced: {} }, !!a.include_preview);
+ },
+
+ async upscale_image(a: Args<"upscale_image">, ctx: ToolContext) {
+ if (a.scale != null && (a.width != null || a.height != null)) throw new PathError("Give either scale or width/height, not both.");
+ const r = await roots(ctx);
+ const img = checkInput(a.image_path, ctx.cwd, r);
+ const out = a.output_path ? checkOutput(a.output_path, ctx.cwd, r) : undefined;
+ return runJob(
+ ctx,
+ {
+ prompt: a.prompt ?? "",
+ mode: "upscale",
+ images: [img],
+ upscale: { method: a.method ?? "quick", scale: a.scale, width: a.width, height: a.height },
+ output_path: out,
+ advanced: {},
+ },
+ !!a.include_preview,
+ );
+ },
+
+ async get_image_info(a: Args<"get_image_info">, ctx: ToolContext) {
+ const img = checkInput(a.image_path, ctx.cwd, await roots(ctx));
+ const info = await ctx.client.call<Record<string, unknown>>("POST", "/image-info", { path: img });
+ const g = info.generation as Record<string, unknown> | null;
+ const structured = {
+ path: info.path,
+ width: info.width,
+ height: info.height,
+ aspect_ratio: info.aspect_ratio,
+ file_type: info.file_type,
+ file_size: info.file_size,
+ has_transparency: info.has_transparency,
+ exif_orientation: info.exif_orientation,
+ generation: g
+ ? { prompt: g.prompt, negative_prompt: g.negative_prompt, seed: g.seed, mode: g.mode, model: g.model, steps: g.steps, cfg: g.cfg, sampler: g.sampler, created_at: g.created_at }
+ : info.parameters ?? null,
+ };
+ return { text: JSON.stringify(structured, null, 2), structured } as ToolResult;
+ },
+
+ async get_generator_status(_a: Args<"get_generator_status">, ctx: ToolContext) {
+ const st = await ctx.client.call<Record<string, any>>("GET", "/status");
+ const active = st.active_job as JobView | null;
+ const structured = {
+ server_running: st.server.state === "ready" || st.server.state === "starting",
+ model_loaded: !!st.server.model_loaded,
+ server_state: st.server.state,
+ model: st.server.model ?? st.profile?.display_name,
+ gpu: st.gpu?.name ?? null,
+ vram_total_mib: st.gpu?.memory_total_mib ?? null,
+ vram_free_mib: st.gpu?.memory_free_mib ?? null,
+ active_job: active ? { id: active.id, status: active.status, progress: label(active) } : null,
+ queued_jobs: st.queue?.queued ?? 0,
+ service_version: st.service?.version,
+ };
+ return { text: JSON.stringify(structured, null, 2), structured } as ToolResult;
+ },
+};
+
+export function toErrorResult(e: unknown): ToolResult {
+ if (e instanceof PathError) return errorResult(e.message, "invalid_path");
+ if (e instanceof ServiceError) return errorResult(e.message, e.code, e.suggestion, e.detail);
+ if (e instanceof z.ZodError) return errorResult(e.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; "), "invalid_input");
+ return errorResult(e instanceof Error ? e.message : String(e), "internal");
+}
diff --git a/mcp/test/paths.test.ts b/mcp/test/paths.test.ts
new file mode 100644
index 0000000..dd4940e
--- /dev/null
+++ b/mcp/test/paths.test.ts
@@ -0,0 +1,49 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import { checkInput, checkOutput, isWithin, normalize, PathError } from "../src/paths";
+
+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "qls-mcp-"));
+const proj = path.join(tmp, "proj");
+fs.mkdirSync(path.join(proj, "assets"), { recursive: true });
+fs.writeFileSync(path.join(proj, "assets", "header.png"), "x");
+fs.writeFileSync(path.join(proj, "notes.txt"), "x");
+const outside = path.join(tmp, "proj2");
+fs.mkdirSync(outside);
+fs.writeFileSync(path.join(outside, "x.png"), "x");
+const roots = [proj];
+
+describe("normalize", () => {
+ it.each([["\\\\server\\share\\a.png"], ["\\\\?\\C:\\a.png"], ["//server/a.png"], ["C:\\a.png:ads"], ["C:\\x\\CON.png"], ["C:rel.png"], [""], ["a\u0000b"]])("rejects %s", (p) => {
+ expect(() => normalize(p, proj)).toThrow(PathError);
+ });
+ it("resolves relative paths against the project", () => {
+ expect(normalize("assets/header.png", proj)).toBe(path.join(proj, "assets", "header.png"));
+ });
+});
+
+describe("inputs", () => {
+ it("accepts a relative image in the project", () => {
+ expect(checkInput("assets\\header.png", proj, roots)).toBe(path.join(proj, "assets", "header.png"));
+ });
+ it("rejects traversal outside the project", () => {
+ expect(() => checkInput("..\\proj2\\x.png", proj, roots)).toThrow(/outside/);
+ expect(() => checkInput(path.join(outside, "x.png"), proj, roots)).toThrow(/outside/);
+ });
+ it("rejects non-images and missing files", () => {
+ expect(() => checkInput("notes.txt", proj, roots)).toThrow(/Only PNG/);
+ expect(() => checkInput("missing.png", proj, roots)).toThrow(/not found/);
+ });
+ it("sibling prefix is not inside", () => {
+ expect(isWithin(path.join(outside, "x.png"), proj)).toBe(false);
+ });
+});
+
+describe("outputs", () => {
+ it("adds .png and stays inside roots", () => {
+ expect(checkOutput("assets/hero", proj, roots)).toBe(path.join(proj, "assets", "hero.png"));
+ expect(() => checkOutput("../escape.png", proj, roots)).toThrow(/outside/);
+ expect(() => checkOutput("x.exe", proj, roots)).toThrow(/png/);
+ });
+});
diff --git a/mcp/test/protocol.test.ts b/mcp/test/protocol.test.ts
new file mode 100644
index 0000000..08d329c
--- /dev/null
+++ b/mcp/test/protocol.test.ts
@@ -0,0 +1,79 @@
+// End-to-end over stdio with the official MCP client. Starts qls-service on demand
+// (no generation, so no GPU work) using an isolated data/config folder and ports.
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
+import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+const root = path.resolve(__dirname, "..", "..");
+const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "qls-mcp-proto-"));
+const env = {
+ ...process.env,
+ QLS_DATA_DIR: path.join(tmp, "data"),
+ QLS_CONFIG_DIR: path.join(tmp, "config"),
+ QLS_SERVICE_EXE: path.join(root, "target", "debug", "qls-service.exe"),
+} as Record<string, string>;
+delete env.CLAUDE_PROJECT_DIR;
+fs.mkdirSync(env.QLS_CONFIG_DIR, { recursive: true });
+fs.writeFileSync(path.join(env.QLS_CONFIG_DIR, "config.json"), JSON.stringify({ servicePort: 39181, serverPort: 39180, outputDir: path.join(tmp, "out") }));
+const proj = path.join(tmp, "project");
+fs.mkdirSync(proj);
+// 1x1 PNG
+fs.writeFileSync(path.join(proj, "dot.png"), Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "base64"));
+
+let client: Client;
+
+beforeAll(async () => {
+ client = new Client({ name: "qls-test", version: "1.0.0" });
+ const exe = process.env.QLS_MCP_EXE;
+ await client.connect(new StdioClientTransport({ command: exe ?? process.execPath, args: exe ? [] : [path.join(root, "mcp", "build", "qls-mcp.cjs")], env, cwd: proj, stderr: "pipe" }));
+}, 30_000);
+
+afterAll(async () => {
+ await client?.close();
+ try {
+ const info = JSON.parse(fs.readFileSync(path.join(env.QLS_DATA_DIR, "service.json"), "utf8"));
+ await fetch(`http://127.0.0.1:${info.port}/api/v1/shutdown`, { method: "POST", headers: { Authorization: `Bearer ${info.token}` } });
+ } catch {
+ /* not started */
+ }
+});
+
+describe("MCP protocol", () => {
+ it("lists the seven tools with schemas", async () => {
+ const { tools } = await client.listTools();
+ expect(tools.map((t) => t.name).sort()).toEqual(["edit_image", "edit_images", "generate_image", "get_generator_status", "get_image_info", "inpaint_image", "outpaint_image"]);
+ const gen = tools.find((t) => t.name === "generate_image")!;
+ expect(gen.inputSchema.required).toEqual(["prompt"]);
+ });
+
+ it("rejects invalid arguments", async () => {
+ const r = await client.callTool({ name: "generate_image", arguments: { prompt: "" } }).catch((e) => ({ isError: true, content: [{ type: "text", text: String(e) }] }));
+ expect(r.isError).toBe(true);
+ });
+
+ it("starts the service on demand and reports status", async () => {
+ const r = await client.callTool({ name: "get_generator_status", arguments: {} });
+ expect(r.isError).toBe(false);
+ const s = r.structuredContent as Record<string, unknown>;
+ expect(s).toHaveProperty("server_running");
+ expect(s).toHaveProperty("model_loaded");
+ expect(s.service_version).toBe("1.0.0");
+ }, 60_000);
+
+ it("get_image_info reads a project image and blocks paths outside", async () => {
+ const ok = await client.callTool({ name: "get_image_info", arguments: { image_path: "dot.png" } });
+ expect(ok.isError).toBe(false);
+ expect(ok.structuredContent).toMatchObject({ width: 1, height: 1, file_type: "png" });
+ const bad = await client.callTool({ name: "get_image_info", arguments: { image_path: "C:\\Windows\\System32\\cmd.png" } });
+ expect(bad.isError).toBe(true);
+ expect((bad.structuredContent as { error: { code: string } }).error.code).toBe("invalid_path");
+ }, 60_000);
+
+ it("edit_image refuses traversal before contacting the generator", async () => {
+ const r = await client.callTool({ name: "edit_image", arguments: { image_path: "..\\..\\secret.png", prompt: "x" } });
+ expect(r.isError).toBe(true);
+ });
+});
diff --git a/mcp/test/tools.test.ts b/mcp/test/tools.test.ts
new file mode 100644
index 0000000..414e807
--- /dev/null
+++ b/mcp/test/tools.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from "vitest";
+import { z } from "zod";
+import { handlers, label, schemas, toErrorResult } from "../src/tools";
+
+const obj = <K extends keyof typeof schemas>(k: K) => z.object(schemas[k]);
+
+describe("input validation", () => {
+ it("prompt is required and trimmed", () => {
+ expect(obj("generate_image").safeParse({ prompt: " " }).success).toBe(false);
+ expect(obj("generate_image").safeParse({ prompt: " a fox " }).data?.prompt).toBe("a fox");
+ });
+ it("dimensions, aspect, quality, seed", () => {
+ expect(obj("generate_image").safeParse({ prompt: "x", width: 32, height: 512 }).success).toBe(false);
+ expect(obj("generate_image").safeParse({ prompt: "x", width: 5000, height: 512 }).success).toBe(false);
+ expect(obj("generate_image").safeParse({ prompt: "x", aspect_ratio: "16:9" }).success).toBe(true);
+ expect(obj("generate_image").safeParse({ prompt: "x", aspect_ratio: "wide" }).success).toBe(false);
+ expect(obj("generate_image").safeParse({ prompt: "x", quality: "ultra" }).success).toBe(false);
+ expect(obj("generate_image").safeParse({ prompt: "x", seed: -2 }).success).toBe(false);
+ });
+ it("edit_images limits and order", () => {
+ expect(obj("edit_images").safeParse({ prompt: "x", image_paths: [] }).success).toBe(false);
+ expect(obj("edit_images").safeParse({ prompt: "x", image_paths: Array(11).fill("a.png") }).success).toBe(false);
+ expect(obj("edit_images").safeParse({ prompt: "x", image_paths: ["b.png", "a.png"] }).data?.image_paths).toEqual(["b.png", "a.png"]);
+ });
+ it("outpaint defaults", () => {
+ const r = obj("outpaint_image").parse({ image_path: "a.png", prompt: "x", left: 256 });
+ expect(r).toMatchObject({ left: 256, right: 0, top: 0, bottom: 0, units: "pixels" });
+ });
+ it("width without height is rejected before any service call", async () => {
+ const ctx = { client: {} as never, cwd: process.cwd(), progress: () => {} };
+ const res = await handlers.generate_image({ prompt: "x", width: 512 } as never, ctx).catch(toErrorResult);
+ expect(res.isError).toBe(true);
+ expect(res.text).toMatch(/both width and height/);
+ });
+});
+
+describe("upscale_image", () => {
+ it("validates factor, size and method", () => {
+ expect(obj("upscale_image").safeParse({ image_path: "a.png" }).success).toBe(true);
+ expect(obj("upscale_image").safeParse({ image_path: "a.png", scale: 1 }).success).toBe(false);
+ expect(obj("upscale_image").safeParse({ image_path: "a.png", scale: 2, method: "detailed" }).success).toBe(true);
+ expect(obj("upscale_image").safeParse({ image_path: "a.png", width: 9000 }).success).toBe(false);
+ expect(obj("upscale_image").safeParse({ image_path: "a.png", method: "ultra" }).success).toBe(false);
+ });
+ it("scale and width together are rejected before any service call", async () => {
+ const ctx = { client: {} as never, cwd: process.cwd(), progress: () => {} };
+ const res = await handlers.upscale_image({ image_path: "a.png", scale: 2, width: 4000 } as never, ctx).catch(toErrorResult);
+ expect(res.isError).toBe(true);
+ expect(res.text).toMatch(/either scale or width/);
+ });
+});
+
+describe("progress labels are truthful", () => {
+ const j = { id: "j", status: "running", stage: "generating", step: [3, 30] as [number, number], queue_position: 0, plan: null, results: [], error: null, notes: [] };
+ it("only shows steps when reported", () => {
+ expect(label(j)).toBe("Generating step 3/30");
+ expect(label({ ...j, step: null })).toBe("Generating");
+ expect(label({ ...j, status: "starting_backend" })).toBe("Loading the model");
+ expect(label({ ...j, stage: "upscaling", step: null })).toBe("Upscaling");
+ expect(label({ ...j, stage: "refining", step: [2, 6] })).toBe("Refining step 2/6");
+ });
+});
diff --git a/mcp/tsconfig.json b/mcp/tsconfig.json
new file mode 100644
index 0000000..f067b92
--- /dev/null
+++ b/mcp/tsconfig.json
@@ -0,0 +1,12 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "NodeNext",
+ "moduleResolution": "NodeNext",
+ "strict": true,
+ "skipLibCheck": true,
+ "noEmit": true,
+ "types": ["node"]
+ },
+ "include": ["src"]
+}
diff --git a/mcp/vitest.config.ts b/mcp/vitest.config.ts
new file mode 100644
index 0000000..8f488fc
--- /dev/null
+++ b/mcp/vitest.config.ts
@@ -0,0 +1,2 @@
+import { defineConfig } from "vitest/config";
+export default defineConfig({ test: { include: ["test/**/*.test.ts"], testTimeout: 20000, fileParallelism: false } });
diff --git a/package-lock.json b/package-lock.json
new file mode 100644
index 0000000..3594e62
--- /dev/null
+++ b/package-lock.json
@@ -0,0 +1,2369 @@
+{
+ "name": "qwen-local-studio",
+ "version": "1.0.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "qwen-local-studio",
+ "version": "1.0.0",
+ "dependencies": {
+ "@fontsource-variable/inter": "^5.3.0",
+ "@tauri-apps/api": "^2.12.1",
+ "@tauri-apps/plugin-clipboard-manager": "^2.4.1",
+ "@tauri-apps/plugin-dialog": "^2.8.1",
+ "@tauri-apps/plugin-opener": "^2.7.0",
+ "lucide-react": "^1.52.0",
+ "react": "^19.3.0",
+ "react-dom": "^19.3.0"
+ },
+ "devDependencies": {
+ "@tauri-apps/cli": "^2.12.1",
+ "@types/react": "^19.3.0",
+ "@types/react-dom": "^19.3.0",
+ "@vitejs/plugin-react": "^6.1.2",
+ "jsdom": "^29.1.1",
+ "typescript": "^7.0.2",
+ "vite": "^8.3.3",
+ "vitest": "^5.0.3"
+ }
+ },
+ "node_modules/@asamuzakjp/css-color": {
+ "version": "5.1.11",
+ "resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-5.1.11.tgz",
+ "integrity": "sha512-KVw6qIiCTUQhByfTd78h2yD1/00waTmm9uy/R7Ck/ctUyAPj+AEDLkQIdJW0T8+qGgj3j5bpNKK7Q3G+LedJWg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@asamuzakjp/generational-cache": "^1.0.1",
+ "@csstools/css-calc": "^3.2.0",
+ "@csstools/css-color-parser": "^4.1.0",
+ "@csstools/css-parser-algorithms": "^4.0.0",
+ "@csstools/css-tokenizer": "^4.0.0"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ }
+ },
+ "node_modules/@asamuzakjp/dom-selector": {
+ "version": "7.1.1",
+ "resolved": "https://registry.npmjs.org/@asamuzakjp/dom-selector/-/dom-selector-7.1.1.tgz",
+ "integrity": "sha512-67RZDnYRc8H/8MLDgQCDE//zoqVFwajkepHZgmXrbwybzXOEwOWGPYGmALYl9J2DOLfFPPs6kKCqmbzV895hTQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@asamuzakjp/generational-cache": "^1.0.1",
+ "@asamuzakjp/nwsapi": "^2.3.9",
+ "bidi-js": "^1.0.3",
+ "css-tree": "^3.2.1",
+ "is-potential-custom-element-name": "^1.0.1"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ }
+ },
+ "node_modules/@asamuzakjp/generational-cache": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@asamuzakjp/generational-cache/-/generational-cache-1.0.1.tgz",
+ "integrity": "sha512-wajfB8KqzMCN2KGNFdLkReeHncd0AslUSrvHVvvYWuU8ghncRJoA50kT3zP9MVL0+9g4/67H+cdvBskj9THPzg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ }
+ },
+ "node_modules/@asamuzakjp/nwsapi": {
+ "version": "2.3.9",
+ "resolved": "https://registry.npmjs.org/@asamuzakjp/nwsapi/-/nwsapi-2.3.9.tgz",
+ "integrity": "sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@bramus/specificity": {
+ "version": "2.4.3",
+ "resolved": "https://registry.npmjs.org/@bramus/specificity/-/specificity-2.4.3.tgz",
+ "integrity": "sha512-0GEz8qJWokkUVYQYRukmkSHIFNoBH8QTreeHrAFbvz1XFYc3Y+puhMs8PQ5x8GNugiC2l5jvDBXKLbBIByeSBw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "css-tree": "^3.2.1"
+ },
+ "bin": {
+ "specificity": "bin/cli.js"
+ }
+ },
+ "node_modules/@csstools/color-helpers": {
+ "version": "6.1.2",
+ "resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-6.1.2.tgz",
+ "integrity": "sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT-0",
+ "engines": {
+ "node": ">=20.19.0"
+ }
+ },
+ "node_modules/@csstools/css-calc": {
+ "version": "3.4.3",
+ "resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-3.4.3.tgz",
+ "integrity": "sha512-iex20d8CHVkyvg6B7UKV7uHnI2Bqo9g+EFfT9E0y+GvTvhZ/DwONJ+9aKb1dlqm0ZiGsL5RXjp0fCoJYnkeDjA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "peerDependencies": {
+ "@csstools/css-parser-algorithms": "^4.0.2",
+ "@csstools/css-tokenizer": "^4.0.2"
+ }
+ },
+ "node_modules/@csstools/css-color-parser": {
+ "version": "4.2.6",
+ "resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-4.2.6.tgz",
+ "integrity": "sha512-iiPQ3iRWwnJkeEn6RIu6SJPr7hYrLz6XZ9s/QZl+2/LI5KQVjpl2fdmDSZKuD4xP6GMmMPgHFFXg6k1Wkz0Trg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "@csstools/color-helpers": "^6.1.2",
+ "@csstools/css-calc": "^3.4.3"
+ },
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "peerDependencies": {
+ "@csstools/css-parser-algorithms": "^4.0.2",
+ "@csstools/css-tokenizer": "^4.0.2"
+ }
+ },
+ "node_modules/@csstools/css-parser-algorithms": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-4.0.2.tgz",
+ "integrity": "sha512-40cSKyMvK+tq4qz6Awrlye2WGuOKt3FwPgtGg6KTfbHOWNw+Rk1rzbAtZnZ6IBhsY491HLRnDXwoyBAijmmILA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "peerDependencies": {
+ "@csstools/css-tokenizer": "^4.0.2"
+ }
+ },
+ "node_modules/@csstools/css-syntax-patches-for-csstree": {
+ "version": "1.1.15",
+ "resolved": "https://registry.npmjs.org/@csstools/css-syntax-patches-for-csstree/-/css-syntax-patches-for-csstree-1.1.15.tgz",
+ "integrity": "sha512-J0u7HkVl2nzSlhsiTOp4AmwcUQ3D+mGEEKfBy/7To5/y7F2OHwyLrXfrhR0SMgr4p5Lo+eaMVSeai24zUcBIxA==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT-0",
+ "peerDependencies": {
+ "css-tree": "^3.2.1"
+ },
+ "peerDependenciesMeta": {
+ "css-tree": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@csstools/css-tokenizer": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-4.0.2.tgz",
+ "integrity": "sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/csstools"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/csstools"
+ }
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.19.0"
+ }
+ },
+ "node_modules/@exodus/bytes": {
+ "version": "1.16.0",
+ "resolved": "https://registry.npmjs.org/@exodus/bytes/-/bytes-1.16.0.tgz",
+ "integrity": "sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ },
+ "peerDependencies": {
+ "@noble/hashes": "^1.8.0 || ^2.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@noble/hashes": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@fontsource-variable/inter": {
+ "version": "5.3.0",
+ "resolved": "https://registry.npmjs.org/@fontsource-variable/inter/-/inter-5.3.0.tgz",
+ "integrity": "sha512-OupL48va4JNofb97w6NYeF9S7W/kHNKM0Er8Dem5nqi4jeOLrVJDoE8tZEpnMJmtkvNbB1EIPPwHcdkF6b1oUA==",
+ "license": "OFL-1.1",
+ "funding": {
+ "url": "https://github.com/sponsors/ayuhito"
+ }
+ },
+ "node_modules/@jridgewell/resolve-uri": {
+ "version": "3.1.2",
+ "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz",
+ "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6.0.0"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@jridgewell/trace-mapping": {
+ "version": "0.3.31",
+ "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz",
+ "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/resolve-uri": "^3.1.0",
+ "@jridgewell/sourcemap-codec": "^1.4.14"
+ }
+ },
+ "node_modules/@oxc-project/types": {
+ "version": "0.152.0",
+ "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.152.0.tgz",
+ "integrity": "sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/oxc-project"
+ }
+ },
+ "node_modules/@rolldown/binding-android-arm-eabi": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.12.tgz",
+ "integrity": "sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-android-arm64": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.2.12.tgz",
+ "integrity": "sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-arm64": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.2.12.tgz",
+ "integrity": "sha512-3YIhqHD96nA5SaYNRBR16HnGv4oavZvXfD/ayHM+oYZ0WD/8lBAtf6zQua4kEyAvpqrluKXl0lnOBoiNby7x9w==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-darwin-x64": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.2.12.tgz",
+ "integrity": "sha512-UuuJ35MFw4gmFOrE9pEqIV+K3syIKveph+Qc1/ljHZVdoDW4pz/JHR/eMVom+TZGl/5OOvGJOWaOCVt3ZfqhxA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-freebsd-x64": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.2.12.tgz",
+ "integrity": "sha512-uMvssit0a4W+/7D8CbHUvG719mH3R2jwXAlh/XcPvuHTE0g++LymF88DCGNX0HM2rBOn0xrzgXktIB6fLSJBTQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm-gnueabihf": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.2.12.tgz",
+ "integrity": "sha512-XcFu0R0xWnwzSf4IQgFH1rJIckPN1pLy2R+4r9IDB7Yfu/ys9cVqfa4pBrMHj7a3gl8mIR4nRNPg0e5IvEVs6g==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-gnu": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.2.12.tgz",
+ "integrity": "sha512-260UrKgn8tz39ak+SMDOirKzr7V04M9dWPw5llW00SwBivCZoWcRBKV1d8cXnRkUmSZA3BdiUmBHWk7734Ulpw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-arm64-musl": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.2.12.tgz",
+ "integrity": "sha512-5YK1I9SqDkbPgc1IA8BgDl34suqUS2q0KWnBrirm0E51YjOs6eo6dV6jbQfNE/argHRSvd0QUGgtpIoYx+WWpw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-ppc64-gnu": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.2.12.tgz",
+ "integrity": "sha512-Rkcrmp7eFRg74yL5fXEU91JEWbdEPLevWwGtXpmhbjlD1StScbWTmO94Bhly+Mo+ketKYkdmM1vNUKeWSlx8cQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-s390x-gnu": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.2.12.tgz",
+ "integrity": "sha512-qvK4DuAsQc2BSjlx+Xr+IzOIvvxbGZqxFwdWfG6F518Erj0GGISyQbJ6pIappnOxlNPzNHvo/L0BwB30GZ+zVw==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-gnu": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.2.12.tgz",
+ "integrity": "sha512-Q9uLBO53Xd4QIq1WOycVQyPP1O4HhraEV2qqb3uTrnVw6QZih9duY4vNXOivL1xoUS1/z+W8eF4NMfl2a8Sdjw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-linux-x64-musl": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.2.12.tgz",
+ "integrity": "sha512-3IBxWFMjbOZskDPKv8Lf9BCnahlKuHthWkYnyIxOH/QcJrFcS4EmcenthApkwr/5+nEqZlLzeYbxeMaX7A5u4g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-openharmony-arm64": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.2.12.tgz",
+ "integrity": "sha512-xtX61xg4LKPkPWilZU1ynKClz5Gj4bf74LML4r3eVLWumKnGjoEr1OSHQhMdbBDoYTi+yjrujvpZe2pUnqCrrA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-arm64-msvc": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.2.12.tgz",
+ "integrity": "sha512-At7fPB6PCaIjzgIhEZFxuT+BBFqiQibJDT4d3PhiR3f4E7bbMZF4aKblbFfEM3sETRDd1YiQx/+U/g/B/ou5Ew==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/binding-win32-x64-msvc": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.2.12.tgz",
+ "integrity": "sha512-WIw2haVKwjuYdXkHaoC0mF8Le71TuCBxjrdKqLbJGctbBABj+ClfmNvtbOnzpq3RokNo5+V1qhtSzJyXorsklQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ }
+ },
+ "node_modules/@rolldown/pluginutils": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz",
+ "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@tauri-apps/api": {
+ "version": "2.12.1",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.12.1.tgz",
+ "integrity": "sha512-DeyFHa3wynpyoqTDikDEDGTJIq4LQ5USfolQGRmGIWT6JMADyxZBTDa5cAdT3tDg73rUXufPaCwN7aXBos4OnQ==",
+ "license": "Apache-2.0 OR MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/tauri"
+ }
+ },
+ "node_modules/@tauri-apps/cli": {
+ "version": "2.12.1",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.12.1.tgz",
+ "integrity": "sha512-kEDEiGzG+yAc5FeLxtXpES/VN+F2C8H0r4gDVtfRLKxT9np9101d9REG/Kgo2lr0hKi0IpDsODiHnU3+naOmLg==",
+ "dev": true,
+ "license": "Apache-2.0 OR MIT",
+ "bin": {
+ "tauri": "tauri.js"
+ },
+ "engines": {
+ "node": ">= 10"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/tauri"
+ },
+ "optionalDependencies": {
+ "@tauri-apps/cli-darwin-arm64": "2.12.1",
+ "@tauri-apps/cli-darwin-x64": "2.12.1",
+ "@tauri-apps/cli-linux-arm-gnueabihf": "2.12.1",
+ "@tauri-apps/cli-linux-arm64-gnu": "2.12.1",
+ "@tauri-apps/cli-linux-arm64-musl": "2.12.1",
+ "@tauri-apps/cli-linux-riscv64-gnu": "2.12.1",
+ "@tauri-apps/cli-linux-x64-gnu": "2.12.1",
+ "@tauri-apps/cli-linux-x64-musl": "2.12.1",
+ "@tauri-apps/cli-win32-arm64-msvc": "2.12.1",
+ "@tauri-apps/cli-win32-ia32-msvc": "2.12.1",
+ "@tauri-apps/cli-win32-x64-msvc": "2.12.1"
+ }
+ },
+ "node_modules/@tauri-apps/cli-darwin-arm64": {
+ "version": "2.12.1",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.12.1.tgz",
+ "integrity": "sha512-8bMnbpJ2jKO/ufrOPL65EMHC3ptw7fzeraoQkwibyfGLqIl+UCWsC0152kmNbW6r9NvVQduXqAZF5mH1QgTWhw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 OR MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@tauri-apps/cli-darwin-x64": {
+ "version": "2.12.1",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.12.1.tgz",
+ "integrity": "sha512-G+2qte8GNqNlEZ9ftd21rbu/APVkl3r/nzNDI7LVxEoqJWVNe9GbEgQUMH1r4PHT20Z2UxR3KjCkltIb0e/Wjg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 OR MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@tauri-apps/cli-linux-arm-gnueabihf": {
+ "version": "2.12.1",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.12.1.tgz",
+ "integrity": "sha512-5b3n4DaTW+A1Zntnh4Yn44VyLrlPEpB8kMOBRfWkzNnzolBk+AYhKIfKjCLmoC8Mob3ETodxAEOMkE2YPKEWzQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 OR MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@tauri-apps/cli-linux-arm64-gnu": {
+ "version": "2.12.1",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.12.1.tgz",
+ "integrity": "sha512-APArHhDu+8pXSCkCQmvaz1nD3d8WTmlCoSS/oG475TJ6AATBvyQOAmf5qELgsQ4s2+8MOsop0Zd699RKELF1Cw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 OR MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@tauri-apps/cli-linux-arm64-musl": {
+ "version": "2.12.1",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.12.1.tgz",
+ "integrity": "sha512-JaCxcLoV0oGtllVkLr4UAHWG/wTfkEunnUqnsEsGYOp0VRxnUwHg63wFBD0jU2ul5eFfSLIDS4RF2gfzsSo5Jg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 OR MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@tauri-apps/cli-linux-riscv64-gnu": {
+ "version": "2.12.1",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.12.1.tgz",
+ "integrity": "sha512-K5+VXM7+SGVDwZleA2+lMgvbTVuA5e1tkiVEawu1Yxj26ZyEfO8h8xTC1rBdRX2xgJDSwCk6vPUBCS6i+Z5slQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 OR MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@tauri-apps/cli-linux-x64-gnu": {
+ "version": "2.12.1",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.12.1.tgz",
+ "integrity": "sha512-Z1QGPr49HJZMktu+Spu6Q1b/f9ANadXvqZZZt2645ua1x1ev6prOgp85eiGv2jRzohFEMLo6aJyaLjLUX5KIvA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 OR MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@tauri-apps/cli-linux-x64-musl": {
+ "version": "2.12.1",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.12.1.tgz",
+ "integrity": "sha512-nHuEhRPOMSJ/8RRhtMRxB9B9lVr7xxpe4DapBz8x1GIau3vdzjHHJ1hAfmw+PyayPLZ6XoaVIHPgI17rX6ii8w==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 OR MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@tauri-apps/cli-win32-arm64-msvc": {
+ "version": "2.12.1",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.12.1.tgz",
+ "integrity": "sha512-I0oPk2uGh86R8dAs2X5OxSP+/GqSc8jh1Px3l8EqrocSNivsRHDTh2k3PVOqdv163dlV6PIVvmhZAbH/lPfZrA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 OR MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@tauri-apps/cli-win32-ia32-msvc": {
+ "version": "2.12.1",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.12.1.tgz",
+ "integrity": "sha512-baNZRBfepAJ5qNFRMwzgBk94xQmkcmTZrNDjZjnzrq2vAaTC3NAhallb/zo3hyoCGQlMS13sdovktrg46NZz6Q==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 OR MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@tauri-apps/cli-win32-x64-msvc": {
+ "version": "2.12.1",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.12.1.tgz",
+ "integrity": "sha512-dIFaKslrzcbesb+bBh+E1R9km241pHyj32w6D9FPtvQeYpRUFbiCLEa/2S+S0UnIytfxepp4P+X8IerGqnXeYg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0 OR MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 10"
+ }
+ },
+ "node_modules/@tauri-apps/plugin-clipboard-manager": {
+ "version": "2.4.1",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-clipboard-manager/-/plugin-clipboard-manager-2.4.1.tgz",
+ "integrity": "sha512-5Q9hWWnsE7UF1xABWHpRwqGiyORrP9o/rJift/7V8woP/kSVF21W+bP9G7ch8Qd7pneDWUMk6hkfpLpjcC/4Ag==",
+ "license": "MIT OR Apache-2.0",
+ "dependencies": {
+ "@tauri-apps/api": "^2.12.0"
+ }
+ },
+ "node_modules/@tauri-apps/plugin-dialog": {
+ "version": "2.8.1",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-dialog/-/plugin-dialog-2.8.1.tgz",
+ "integrity": "sha512-/DtE3B62JgpYuWFL5ATXM6KOXUq7pca7cJWOgSqULhZsgyjLk0PWKek1dbRDvhNBW6flNsOfWphsKnb+738Dmw==",
+ "license": "MIT OR Apache-2.0",
+ "dependencies": {
+ "@tauri-apps/api": "^2.12.0"
+ }
+ },
+ "node_modules/@tauri-apps/plugin-opener": {
+ "version": "2.7.0",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/plugin-opener/-/plugin-opener-2.7.0.tgz",
+ "integrity": "sha512-mBorYfVKh9Lt7s4ZFtKbMUTxBw+Y/sVmSlKCtkkoBgMTC/DIbt/kaPm67L/2djAUqDI1wbixy5OHHVmipjuGMw==",
+ "license": "MIT OR Apache-2.0",
+ "dependencies": {
+ "@tauri-apps/api": "^2.12.0"
+ }
+ },
+ "node_modules/@types/chai": {
+ "version": "5.2.3",
+ "resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
+ "integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/deep-eql": "*",
+ "assertion-error": "^2.0.1"
+ }
+ },
+ "node_modules/@types/deep-eql": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
+ "integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@types/react": {
+ "version": "19.3.0",
+ "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz",
+ "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==",
+ "devOptional": true,
+ "license": "MIT",
+ "dependencies": {
+ "csstype": "^3.2.2"
+ }
+ },
+ "node_modules/@types/react-dom": {
+ "version": "19.3.0",
+ "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.3.0.tgz",
+ "integrity": "sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "@types/react": "^19.3.0"
+ }
+ },
+ "node_modules/@typescript/typescript-aix-ppc64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz",
+ "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-darwin-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz",
+ "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-darwin-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz",
+ "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-freebsd-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz",
+ "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-freebsd-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz",
+ "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-arm": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz",
+ "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz",
+ "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-loong64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz",
+ "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-mips64el": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz",
+ "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-ppc64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz",
+ "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-riscv64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz",
+ "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-s390x": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz",
+ "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-linux-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz",
+ "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-netbsd-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz",
+ "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-netbsd-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz",
+ "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-openbsd-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz",
+ "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-openbsd-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz",
+ "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-sunos-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz",
+ "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-win32-arm64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz",
+ "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@typescript/typescript-win32-x64": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz",
+ "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "Apache-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
+ "node_modules/@vitejs/plugin-react": {
+ "version": "6.1.2",
+ "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.1.2.tgz",
+ "integrity": "sha512-fhJNGUdscQa4HkI0xFxwonWyhnVReCPDbXI7FH7jmzpnVCrFQI7PRrhWecO263610vOrs9tr2Y4xcf8uAdFxbw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@rolldown/pluginutils": "^1.0.1"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "peerDependencies": {
+ "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0",
+ "babel-plugin-react-compiler": "^1.0.0",
+ "oxc-transform-react": "^0.152.0",
+ "vite": "^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@rolldown/plugin-babel": {
+ "optional": true
+ },
+ "babel-plugin-react-compiler": {
+ "optional": true
+ },
+ "oxc-transform-react": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@vitest/mocker": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-5.0.3.tgz",
+ "integrity": "sha512-T8sWAIbkSyAjkwTcaEc3Iu0o9A27X1/kdXrizhZkGuSKScRQtRzclfAMpOTcGdXCsqxeWlpGy3XjqaW8CpLORg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/trace-mapping": "0.3.31",
+ "@vitest/spy": "5.0.3",
+ "estree-walker": "^3.0.3",
+ "magic-string": "^1.2.3"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "msw": "^2.4.9",
+ "vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "msw": {
+ "optional": true
+ },
+ "vite": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@vitest/spy": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-5.0.3.tgz",
+ "integrity": "sha512-XhFysQTB8AZ+P4gMi+Lpo99vg2AZi0qKpaB9yXQl37+CaMEAPO3iH/wGVnSyL5MPERiLezpqTVtrR6UZH5GCXg==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/assertion-error": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/bidi-js": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.1.0.tgz",
+ "integrity": "sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "require-from-string": "^2.0.2"
+ }
+ },
+ "node_modules/chai": {
+ "version": "6.3.0",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-6.3.0.tgz",
+ "integrity": "sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/css-tree": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.2.1.tgz",
+ "integrity": "sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "mdn-data": "2.27.1",
+ "source-map-js": "^1.2.1"
+ },
+ "engines": {
+ "node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0"
+ }
+ },
+ "node_modules/csstype": {
+ "version": "3.2.3",
+ "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
+ "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
+ "devOptional": true,
+ "license": "MIT"
+ },
+ "node_modules/data-urls": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/data-urls/-/data-urls-7.0.0.tgz",
+ "integrity": "sha512-23XHcCF+coGYevirZceTVD7NdJOqVn+49IHyxgszm+JIiHLoB2TkmPtsYkNWT1pvRSGkc35L6NHs0yHkN2SumA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "whatwg-mimetype": "^5.0.0",
+ "whatwg-url": "^16.0.0"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ }
+ },
+ "node_modules/decimal.js": {
+ "version": "10.6.0",
+ "resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.6.0.tgz",
+ "integrity": "sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/detect-libc": {
+ "version": "2.1.2",
+ "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz",
+ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/entities": {
+ "version": "8.1.0",
+ "resolved": "https://registry.npmjs.org/entities/-/entities-8.1.0.tgz",
+ "integrity": "sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=20.19.0"
+ },
+ "funding": {
+ "url": "https://github.com/fb55/entities?sponsor=1"
+ }
+ },
+ "node_modules/es-module-lexer": {
+ "version": "2.3.2",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz",
+ "integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/estree-walker": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0"
+ }
+ },
+ "node_modules/expect-type": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
+ "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/html-encoding-sniffer": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-6.0.0.tgz",
+ "integrity": "sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@exodus/bytes": "^1.6.0"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ }
+ },
+ "node_modules/is-potential-custom-element-name": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
+ "integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/jsdom": {
+ "version": "29.1.1",
+ "resolved": "https://registry.npmjs.org/jsdom/-/jsdom-29.1.1.tgz",
+ "integrity": "sha512-ECi4Fi2f7BdJtUKTflYRTiaMxIB0O6zfR1fX0GXpUrf6flp8QIYn1UT20YQqdSOfk2dfkCwS8LAFoJDEppNK5Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@asamuzakjp/css-color": "^5.1.11",
+ "@asamuzakjp/dom-selector": "^7.1.1",
+ "@bramus/specificity": "^2.4.2",
+ "@csstools/css-syntax-patches-for-csstree": "^1.1.3",
+ "@exodus/bytes": "^1.15.0",
+ "css-tree": "^3.2.1",
+ "data-urls": "^7.0.0",
+ "decimal.js": "^10.6.0",
+ "html-encoding-sniffer": "^6.0.0",
+ "is-potential-custom-element-name": "^1.0.1",
+ "lru-cache": "^11.3.5",
+ "parse5": "^8.0.1",
+ "saxes": "^6.0.0",
+ "symbol-tree": "^3.2.4",
+ "tough-cookie": "^6.0.1",
+ "undici": "^7.25.0",
+ "w3c-xmlserializer": "^5.0.0",
+ "webidl-conversions": "^8.0.1",
+ "whatwg-mimetype": "^5.0.0",
+ "whatwg-url": "^16.0.1",
+ "xml-name-validator": "^5.0.0"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=24.0.0"
+ },
+ "peerDependencies": {
+ "canvas": "^3.0.0"
+ },
+ "peerDependenciesMeta": {
+ "canvas": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/lightningcss": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz",
+ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==",
+ "dev": true,
+ "license": "MPL-2.0",
+ "dependencies": {
+ "detect-libc": "^2.0.3"
+ },
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ },
+ "optionalDependencies": {
+ "lightningcss-android-arm64": "1.33.0",
+ "lightningcss-darwin-arm64": "1.33.0",
+ "lightningcss-darwin-x64": "1.33.0",
+ "lightningcss-freebsd-x64": "1.33.0",
+ "lightningcss-linux-arm-gnueabihf": "1.33.0",
+ "lightningcss-linux-arm64-gnu": "1.33.0",
+ "lightningcss-linux-arm64-musl": "1.33.0",
+ "lightningcss-linux-x64-gnu": "1.33.0",
+ "lightningcss-linux-x64-musl": "1.33.0",
+ "lightningcss-win32-arm64-msvc": "1.33.0",
+ "lightningcss-win32-x64-msvc": "1.33.0"
+ }
+ },
+ "node_modules/lightningcss-android-arm64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz",
+ "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-arm64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz",
+ "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-darwin-x64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz",
+ "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-freebsd-x64": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz",
+ "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm-gnueabihf": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz",
+ "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-gnu": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz",
+ "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-arm64-musl": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz",
+ "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-gnu": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz",
+ "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-linux-x64-musl": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz",
+ "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-arm64-msvc": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz",
+ "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lightningcss-win32-x64-msvc": {
+ "version": "1.33.0",
+ "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz",
+ "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MPL-2.0",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">= 12.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/parcel"
+ }
+ },
+ "node_modules/lru-cache": {
+ "version": "11.5.3",
+ "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz",
+ "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==",
+ "dev": true,
+ "license": "BlueOak-1.0.0",
+ "engines": {
+ "node": "20 || >=22"
+ }
+ },
+ "node_modules/lucide-react": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-1.52.0.tgz",
+ "integrity": "sha512-TUgPtl5ZI9WgxOcbu4ckaC5B3l1qxPQrCMgb6OfUB9owx/OvSJfcf93SMgUWAxRw5/1XDfh9uI5F5iNGXCcGDQ==",
+ "license": "ISC",
+ "peerDependencies": {
+ "@types/react": "*",
+ "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/magic-string": {
+ "version": "1.4.3",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.3.tgz",
+ "integrity": "sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.6.0"
+ }
+ },
+ "node_modules/mdn-data": {
+ "version": "2.27.1",
+ "resolved": "https://registry.npmjs.org/mdn-data/-/mdn-data-2.27.1.tgz",
+ "integrity": "sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==",
+ "dev": true,
+ "license": "CC0-1.0"
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.20",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
+ "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/obug": {
+ "version": "2.2.1",
+ "resolved": "https://registry.npmjs.org/obug/-/obug-2.2.1.tgz",
+ "integrity": "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==",
+ "dev": true,
+ "funding": [
+ "https://github.com/sponsors/sxzz",
+ "https://opencollective.com/debug"
+ ],
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.20.0"
+ }
+ },
+ "node_modules/parse5": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/parse5/-/parse5-8.0.1.tgz",
+ "integrity": "sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "entities": "^8.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/inikulin/parse5?sponsor=1"
+ }
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "4.0.7",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.29",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz",
+ "integrity": "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.19",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.2"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/punycode": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
+ "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/react": {
+ "version": "19.3.0",
+ "resolved": "https://registry.npmjs.org/react/-/react-19.3.0.tgz",
+ "integrity": "sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/react-dom": {
+ "version": "19.3.0",
+ "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.3.0.tgz",
+ "integrity": "sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==",
+ "license": "MIT",
+ "dependencies": {
+ "scheduler": "^0.28.0"
+ },
+ "peerDependencies": {
+ "react": "^19.3.0"
+ }
+ },
+ "node_modules/require-from-string": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
+ "integrity": "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/rolldown": {
+ "version": "1.2.12",
+ "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.2.12.tgz",
+ "integrity": "sha512-8wafseiaG80xmXSfqidUNqZcylTlhmPZZt+za2m+js2sFZ8dTNlhIOV2WcbIPx2hgwPBJpEUGFAMZ9bgBBLTSQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@oxc-project/types": "=0.152.0",
+ "@rolldown/pluginutils": "^1.0.0"
+ },
+ "bin": {
+ "rolldown": "bin/cli.mjs"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "optionalDependencies": {
+ "@rolldown/binding-android-arm-eabi": "1.2.12",
+ "@rolldown/binding-android-arm64": "1.2.12",
+ "@rolldown/binding-darwin-arm64": "1.2.12",
+ "@rolldown/binding-darwin-x64": "1.2.12",
+ "@rolldown/binding-freebsd-x64": "1.2.12",
+ "@rolldown/binding-linux-arm-gnueabihf": "1.2.12",
+ "@rolldown/binding-linux-arm64-gnu": "1.2.12",
+ "@rolldown/binding-linux-arm64-musl": "1.2.12",
+ "@rolldown/binding-linux-ppc64-gnu": "1.2.12",
+ "@rolldown/binding-linux-s390x-gnu": "1.2.12",
+ "@rolldown/binding-linux-x64-gnu": "1.2.12",
+ "@rolldown/binding-linux-x64-musl": "1.2.12",
+ "@rolldown/binding-openharmony-arm64": "1.2.12",
+ "@rolldown/binding-win32-arm64-msvc": "1.2.12",
+ "@rolldown/binding-win32-x64-msvc": "1.2.12"
+ }
+ },
+ "node_modules/saxes": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
+ "integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "xmlchars": "^2.2.0"
+ },
+ "engines": {
+ "node": ">=v12.22.7"
+ }
+ },
+ "node_modules/scheduler": {
+ "version": "0.28.0",
+ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.28.0.tgz",
+ "integrity": "sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==",
+ "license": "MIT"
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
+ "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/std-env": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-4.3.0.tgz",
+ "integrity": "sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/symbol-tree": {
+ "version": "3.2.4",
+ "resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
+ "integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinybench": {
+ "version": "6.2.0",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-6.2.0.tgz",
+ "integrity": "sha512-78U2TlB2CnVenajOFzf3BKSm0J6oz5L0NV7g32LCPccvYc0lbWvys4d3uUUCS2B1N8PAf2+aekR8i1KbC3HO7Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/tinyexec": {
+ "version": "1.3.1",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.1.tgz",
+ "integrity": "sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.17",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.4"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/tldts": {
+ "version": "7.4.16",
+ "resolved": "https://registry.npmjs.org/tldts/-/tldts-7.4.16.tgz",
+ "integrity": "sha512-QwBER5KMR86IIjpIiO7H/Z3IMJPsZ1A6RKPAqzTTgOyUQUSt9FdnKcqhTaJmkY6HVrgouZHZR0ncK5QxvmnQeg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tldts-core": "^7.4.16"
+ },
+ "bin": {
+ "tldts": "bin/cli.js"
+ }
+ },
+ "node_modules/tldts-core": {
+ "version": "7.4.16",
+ "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-7.4.16.tgz",
+ "integrity": "sha512-MDolfaSJtlSK5Y0A1xl3277ekubZwobpBjugknDizI9O5Rm60a1m8k4ICK+MRsCDzPygT81mp3BBf5RKDlFRfA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tough-cookie": {
+ "version": "6.0.2",
+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-6.0.2.tgz",
+ "integrity": "sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "tldts": "^7.0.5"
+ },
+ "engines": {
+ "node": ">=16"
+ }
+ },
+ "node_modules/tr46": {
+ "version": "6.0.0",
+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-6.0.0.tgz",
+ "integrity": "sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "punycode": "^2.3.1"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/typescript": {
+ "version": "7.0.2",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz",
+ "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc"
+ },
+ "engines": {
+ "node": ">=16.20.0"
+ },
+ "optionalDependencies": {
+ "@typescript/typescript-aix-ppc64": "7.0.2",
+ "@typescript/typescript-darwin-arm64": "7.0.2",
+ "@typescript/typescript-darwin-x64": "7.0.2",
+ "@typescript/typescript-freebsd-arm64": "7.0.2",
+ "@typescript/typescript-freebsd-x64": "7.0.2",
+ "@typescript/typescript-linux-arm": "7.0.2",
+ "@typescript/typescript-linux-arm64": "7.0.2",
+ "@typescript/typescript-linux-loong64": "7.0.2",
+ "@typescript/typescript-linux-mips64el": "7.0.2",
+ "@typescript/typescript-linux-ppc64": "7.0.2",
+ "@typescript/typescript-linux-riscv64": "7.0.2",
+ "@typescript/typescript-linux-s390x": "7.0.2",
+ "@typescript/typescript-linux-x64": "7.0.2",
+ "@typescript/typescript-netbsd-arm64": "7.0.2",
+ "@typescript/typescript-netbsd-x64": "7.0.2",
+ "@typescript/typescript-openbsd-arm64": "7.0.2",
+ "@typescript/typescript-openbsd-x64": "7.0.2",
+ "@typescript/typescript-sunos-x64": "7.0.2",
+ "@typescript/typescript-win32-arm64": "7.0.2",
+ "@typescript/typescript-win32-x64": "7.0.2"
+ }
+ },
+ "node_modules/undici": {
+ "version": "7.30.0",
+ "resolved": "https://registry.npmjs.org/undici/-/undici-7.30.0.tgz",
+ "integrity": "sha512-dkrQXeHSaoamnItlYbmzG0wFYrM0ZwDxCIg0A7aKjTyyhh9svRzCNFEzV+Vm05/yehjCzjDZ31KXfGEjYSztDQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=20.18.1"
+ }
+ },
+ "node_modules/vite": {
+ "version": "8.3.3",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-8.3.3.tgz",
+ "integrity": "sha512-cTAldKPImjg6c+gk48U19POPn3GCBzZwpdsN8ZMEEcbpes+6/wvfqUd0C2y3qYY4wsj8PwgFwrZ/1jBPVttMSg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "lightningcss": "^1.33.0",
+ "picomatch": "^4.0.7",
+ "postcss": "^8.5.28",
+ "rolldown": "~1.2.11",
+ "tinyglobby": "^0.2.17"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^20.19.0 || >=22.12.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^20.19.0 || >=22.12.0",
+ "@vitejs/devtools": "^0.7.1",
+ "esbuild": "^0.27.0 || ^0.28.0",
+ "jiti": ">=1.21.0",
+ "less": "^4.0.0",
+ "sass": "^1.70.0",
+ "sass-embedded": "^1.70.0",
+ "stylus": ">=0.54.8",
+ "sugarss": "^5.0.0",
+ "terser": "^5.16.0",
+ "tsx": "^4.8.1",
+ "yaml": "^2.4.2"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "@vitejs/devtools": {
+ "optional": true
+ },
+ "esbuild": {
+ "optional": true
+ },
+ "jiti": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ },
+ "tsx": {
+ "optional": true
+ },
+ "yaml": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vitest": {
+ "version": "5.0.3",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-5.0.3.tgz",
+ "integrity": "sha512-xMw97S3rjdtj5dkVat7jCsqWBpvchs3RlpQctUqwJD0KkERk40vz2fJ77lDwW/Vzh/pk18eItYAzkodhSes3jQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/chai": "^5.2.2",
+ "@vitest/mocker": "5.0.3",
+ "chai": "^6.2.2",
+ "es-module-lexer": "^2.3.2",
+ "expect-type": "^1.4.0",
+ "magic-string": "^1.2.3",
+ "obug": "^2.1.4",
+ "picomatch": "^4.0.7",
+ "std-env": "^4.2.0",
+ "tinybench": "^6.1.4",
+ "tinyexec": "^1.3.0",
+ "tinyglobby": "^0.2.17",
+ "why-is-node-running": "3.2.1"
+ },
+ "bin": {
+ "vitest": "vitest.mjs"
+ },
+ "engines": {
+ "node": "^22.12.0 || ^24.0.0 || >=26.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "@edge-runtime/vm": "*",
+ "@opentelemetry/api": "^1.9.0",
+ "@types/node": "^22.0.0 || >=24.0.0",
+ "@vitest/browser-playwright": "5.0.3",
+ "@vitest/browser-preview": "5.0.3",
+ "@vitest/browser-webdriverio": "^5.0.0-beta.5 || >=5.0.0",
+ "@vitest/coverage-istanbul": "5.0.3",
+ "@vitest/coverage-v8": "5.0.3",
+ "@vitest/ui": "5.0.3",
+ "happy-dom": "*",
+ "jsdom": "*",
+ "vite": "^6.4.0 || ^7.0.0 || ^8.0.0"
+ },
+ "peerDependenciesMeta": {
+ "@edge-runtime/vm": {
+ "optional": true
+ },
+ "@opentelemetry/api": {
+ "optional": true
+ },
+ "@types/node": {
+ "optional": true
+ },
+ "@vitest/browser-playwright": {
+ "optional": true
+ },
+ "@vitest/browser-preview": {
+ "optional": true
+ },
+ "@vitest/browser-webdriverio": {
+ "optional": true
+ },
+ "@vitest/coverage-istanbul": {
+ "optional": true
+ },
+ "@vitest/coverage-v8": {
+ "optional": true
+ },
+ "@vitest/ui": {
+ "optional": true
+ },
+ "happy-dom": {
+ "optional": true
+ },
+ "jsdom": {
+ "optional": true
+ },
+ "vite": {
+ "optional": false
+ }
+ }
+ },
+ "node_modules/w3c-xmlserializer": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
+ "integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "xml-name-validator": "^5.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/webidl-conversions": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-8.0.1.tgz",
+ "integrity": "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==",
+ "dev": true,
+ "license": "BSD-2-Clause",
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/whatwg-mimetype": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-5.0.0.tgz",
+ "integrity": "sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/whatwg-url": {
+ "version": "16.0.1",
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-16.0.1.tgz",
+ "integrity": "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@exodus/bytes": "^1.11.0",
+ "tr46": "^6.0.0",
+ "webidl-conversions": "^8.0.1"
+ },
+ "engines": {
+ "node": "^20.19.0 || ^22.12.0 || >=24.0.0"
+ }
+ },
+ "node_modules/why-is-node-running": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-3.2.1.tgz",
+ "integrity": "sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==",
+ "dev": true,
+ "license": "MIT",
+ "bin": {
+ "why-is-node-running": "cli.js"
+ },
+ "engines": {
+ "node": ">=20.11"
+ }
+ },
+ "node_modules/xml-name-validator": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
+ "integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/xmlchars": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
+ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
+ "dev": true,
+ "license": "MIT"
+ }
+ }
+}
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..47e77b6
--- /dev/null
+++ b/package.json
@@ -0,0 +1,32 @@
+{
+ "name": "qwen-local-studio",
+ "private": true,
+ "version": "1.0.0",
+ "type": "module",
+ "scripts": {
+ "dev": "vite",
+ "build": "tsc --noEmit && vite build",
+ "test": "vitest run",
+ "tauri": "tauri"
+ },
+ "dependencies": {
+ "@fontsource-variable/inter": "^5.3.0",
+ "@tauri-apps/api": "^2.12.1",
+ "@tauri-apps/plugin-clipboard-manager": "^2.4.1",
+ "@tauri-apps/plugin-dialog": "^2.8.1",
+ "@tauri-apps/plugin-opener": "^2.7.0",
+ "lucide-react": "^1.52.0",
+ "react": "^19.3.0",
+ "react-dom": "^19.3.0"
+ },
+ "devDependencies": {
+ "@tauri-apps/cli": "^2.12.1",
+ "@types/react": "^19.3.0",
+ "@types/react-dom": "^19.3.0",
+ "@vitejs/plugin-react": "^6.1.2",
+ "jsdom": "^29.1.1",
+ "typescript": "^7.0.2",
+ "vite": "^8.3.3",
+ "vitest": "^5.0.3"
+ }
+}
diff --git a/scripts/build-release.ps1 b/scripts/build-release.ps1
new file mode 100644
index 0000000..dde8178
--- /dev/null
+++ b/scripts/build-release.ps1
@@ -0,0 +1,43 @@
+# Builds the Windows release: qls-service.exe, qls-mcp.exe, the desktop app and the
+# NSIS installer ("Qwen Local Studio_<version>_x64-setup.exe").
+#
+# powershell -ExecutionPolicy Bypass -File scripts\build-release.ps1
+#
+# Takes ~5-15 minutes on first run (optimized Rust build). CPU only.
+
+$ErrorActionPreference = 'Stop'
+$root = Resolve-Path "$PSScriptRoot\.."
+Set-Location $root
+$env:Path = "$env:USERPROFILE\.cargo\bin;$env:Path"
+
+Write-Host "1/5 Tests (Rust core + frontend + MCP)" -ForegroundColor Cyan
+cargo test -p qls-core --release --quiet
+if ($LASTEXITCODE) { throw "Rust tests failed" }
+npx vitest run
+if ($LASTEXITCODE) { throw "Frontend tests failed" }
+Push-Location mcp; npx vitest run; $rc = $LASTEXITCODE; Pop-Location
+if ($rc) { throw "MCP tests failed" }
+
+Write-Host "2/5 qls-service (release)" -ForegroundColor Cyan
+cargo build -p qls-service --release
+if ($LASTEXITCODE) { throw "service build failed" }
+Copy-Item target\release\qls-service.exe src-tauri\binaries\qls-service-x86_64-pc-windows-msvc.exe -Force
+
+Write-Host "3/5 qls-mcp.exe" -ForegroundColor Cyan
+Push-Location mcp; npm run build:exe; $rc = $LASTEXITCODE; Pop-Location
+if ($rc) { throw "MCP build failed" }
+
+Write-Host "4/5 Desktop app + NSIS installer" -ForegroundColor Cyan
+npx tauri build
+if ($LASTEXITCODE) { throw "tauri build failed" }
+
+Write-Host "5/5 Artifacts" -ForegroundColor Cyan
+$exe = Get-Item "target\release\qwen-local-studio.exe"
+$setup = Get-ChildItem "target\release\bundle\nsis\*.exe" | Sort-Object LastWriteTime -Descending | Select-Object -First 1
+New-Item -ItemType Directory -Force dist-release | Out-Null
+Copy-Item $exe.FullName "dist-release\Qwen Local Studio.exe" -Force
+Copy-Item $setup.FullName "dist-release\Qwen Local Studio Setup.exe" -Force
+Copy-Item target\release\qls-service.exe dist-release\ -Force
+Copy-Item mcp\build\qls-mcp.exe dist-release\ -Force
+Get-ChildItem dist-release | Format-Table Name, @{n = 'MB'; e = { [math]::Round($_.Length / 1MB, 1) } } -AutoSize
+Write-Host "Installer: $root\dist-release\Qwen Local Studio Setup.exe" -ForegroundColor Green
diff --git a/scripts/dev/m1-backend-test.ps1 b/scripts/dev/m1-backend-test.ps1
new file mode 100644
index 0000000..7adf2cb
--- /dev/null
+++ b/scripts/dev/m1-backend-test.ps1
@@ -0,0 +1,71 @@
+# Milestone 1 — backend foundation, real inference.
+# Starts qls-service (debug build) with isolated test data, which launches sd-server,
+# then runs text-to-image and an edit, printing truthful progress from the backend.
+#
+# powershell -ExecutionPolicy Bypass -File scripts\dev\m1-backend-test.ps1
+#
+# Takes ~3-5 minutes (model load + two Fast generations).
+
+$ErrorActionPreference = 'Stop'
+$root = Resolve-Path "$PSScriptRoot\..\.."
+$test = Join-Path $root '.test-data'
+$env:QLS_DATA_DIR = Join-Path $test 'data'
+$env:QLS_CONFIG_DIR = Join-Path $test 'config'
+$out = Join-Path $test 'output'
+New-Item -ItemType Directory -Force $env:QLS_CONFIG_DIR, $out | Out-Null
+$port = 39171
+# Test config: real models, isolated output folder and ports.
+@{ outputDir = $out; serverPort = 39170; servicePort = $port } | ConvertTo-Json | Set-Content (Join-Path $env:QLS_CONFIG_DIR 'config.json') -Encoding utf8
+
+$exe = Join-Path $root 'target\debug\qls-service.exe'
+if (-not (Test-Path $exe)) { throw "Build first: cargo build -p qls-service" }
+$svc = Start-Process $exe -ArgumentList '--port', $port -PassThru -WindowStyle Hidden
+Start-Sleep 2
+$info = Get-Content (Join-Path $env:QLS_DATA_DIR 'service.json') | ConvertFrom-Json
+$H = @{ Authorization = "Bearer $($info.token)" }
+$B = "http://127.0.0.1:$port/api/v1"
+
+function Invoke-Job($path, $body) {
+ $json = $body | ConvertTo-Json -Depth 6
+ $job = Invoke-RestMethod -Method Post -Uri "$B/$path`?wait=false" -Headers $H -ContentType 'application/json' -Body ([Text.Encoding]::UTF8.GetBytes($json))
+ $sw = [Diagnostics.Stopwatch]::StartNew(); $last = ''
+ while ($true) {
+ $j = Invoke-RestMethod -Uri "$B/jobs/$($job.id)" -Headers $H
+ $step = if ($j.step) { " $($j.step[0])/$($j.step[1])" } else { '' }
+ $line = "$($j.status) $($j.stage)$step"
+ if ($line -ne $last) { Write-Host (" [{0,5:N1}s] {1}" -f $sw.Elapsed.TotalSeconds, $line); $last = $line }
+ if ($j.status -in 'done', 'failed', 'cancelled') { break }
+ Start-Sleep -Milliseconds 400
+ }
+ if ($j.status -ne 'done') { Write-Host " ERROR: $($j.error | ConvertTo-Json -Depth 4)" -ForegroundColor Red; return $null }
+ $r = $j.results[0]
+ Write-Host " plan: $($j.plan.mode) working $($j.plan.working.width)x$($j.plan.working.height) -> output $($r.width)x$($r.height), steps $($j.plan.steps), cfg $($j.plan.cfg), seed $($r.seed)"
+ if ($j.plan.notes) { Write-Host " notes: $($j.plan.notes -join ' | ')" }
+ Write-Host " file: $($r.file_path)" -ForegroundColor Green
+ return $r
+}
+
+try {
+ Write-Host "1) Text to image (16:9 from the prompt, Fast)" -ForegroundColor Cyan
+ $t2i = Invoke-Job 'generate' @{ prompt = 'A hero image for a coffee roastery landing page, warm morning light, 16:9'; quality = 'fast' }
+
+ if ($t2i) {
+ Write-Host "2) Edit the result (dimensions must be preserved)" -ForegroundColor Cyan
+ $ed = Invoke-Job 'edit' @{ image = $t2i.file_path; prompt = 'make it nighttime with warm window lights'; quality = 'fast' }
+ if ($ed) {
+ $same = ($ed.width -eq $t2i.width) -and ($ed.height -eq $t2i.height)
+ Write-Host (" dimensions preserved: {0}" -f $same) -ForegroundColor ($(if ($same) { 'Green' } else { 'Red' }))
+ }
+ }
+ $st = Invoke-RestMethod -Uri "$B/status" -Headers $H
+ Write-Host "Server: $($st.server.state), owned=$($st.server.owned), pid=$($st.server.pid), model=$($st.server.model)"
+}
+finally {
+ Write-Host "3) Shutdown (sd-server must stop)" -ForegroundColor Cyan
+ try { Invoke-RestMethod -Method Post -Uri "$B/shutdown" -Headers $H | Out-Null } catch {}
+ Start-Sleep 4
+ $left = Get-Process sd-server -ErrorAction SilentlyContinue
+ if ($left) { Write-Host " sd-server still running: $($left.Id -join ', ')" -ForegroundColor Red } else { Write-Host " sd-server stopped" -ForegroundColor Green }
+ Write-Host "Service log: $env:QLS_DATA_DIR\logs\service.log"
+ Write-Host "Server log: $env:QLS_DATA_DIR\logs\sd-server.log"
+}
diff --git a/scripts/dev/validate-upscale.ps1 b/scripts/dev/validate-upscale.ps1
new file mode 100644
index 0000000..de9cac2
--- /dev/null
+++ b/scripts/dev/validate-upscale.ps1
@@ -0,0 +1,129 @@
+# Speed & upscaling validation through the real app engine (planner, two-pass refine,
+# ESRGAN enlargement, Upscale action). Starts qls-service (debug build) with isolated
+# test data and ports, which launches sd-server.
+#
+# cargo build -p qls-service
+# powershell -ExecutionPolicy Bypass -File scripts\dev\validate-upscale.ps1 [-Only fast,best,4k,edit,upscale,logo] [-EditImage C:\path\photo.png]
+#
+# Close Qwen Local Studio first (GPU). Takes ~12-15 minutes for everything.
+# Without -EditImage, a 5120x2880 test photo is made by upscaling the 2K result.
+param([string[]]$Only, [string]$EditImage)
+
+$ErrorActionPreference = 'Stop'
+$Only = @($Only | ForEach-Object { $_ -split ',' } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
+if ($Only.Count -eq 0) { $Only = $null }
+function Want($n) { return (-not $Only) -or ($n -in $Only) }
+
+$root = Resolve-Path "$PSScriptRoot\..\.."
+$test = Join-Path $root '.test-data'
+$env:QLS_DATA_DIR = Join-Path $test 'data'
+$env:QLS_CONFIG_DIR = Join-Path $test 'config'
+$out = Join-Path $test 'output'
+New-Item -ItemType Directory -Force $env:QLS_CONFIG_DIR, $out | Out-Null
+$port = 39181
+# Test config: real models, defaults for everything new (refineMode fast, ESRGAN from
+# <sdcpp>\models\upscalers), isolated output folder and ports.
+@{ outputDir = $out; serverPort = 39180; servicePort = $port; setupComplete = $true } | ConvertTo-Json | Set-Content (Join-Path $env:QLS_CONFIG_DIR 'config.json') -Encoding utf8
+
+$exe = Join-Path $root 'target\debug\qls-service.exe'
+if (-not (Test-Path $exe)) { throw "Build first: cargo build -p qls-service" }
+$svc = Start-Process $exe -ArgumentList '--port', $port -PassThru -WindowStyle Hidden
+Start-Sleep 2
+$info = Get-Content (Join-Path $env:QLS_DATA_DIR 'service.json') | ConvertFrom-Json
+$H = @{ Authorization = "Bearer $($info.token)" }
+$B = "http://127.0.0.1:$port/api/v1"
+$results = @()
+
+function Dims($s) { if ($s) { return "$($s.width)x$($s.height)" } return '?' }
+function Pipeline($g) {
+ $p = $g.pipeline
+ if (-not $p) { return 'single pass' }
+ $parts = @()
+ if ($p.base) { $parts += "$(Dims $p.base) -> refine $($g.working_width)x$($g.working_height) ($($p.refine), $($p.refine_steps) steps, $($p.hires_upscaler))" }
+ if ($p.enlarged_with) {
+ if (-not $parts) { $parts += (Dims $p.enlarged_from) }
+ $parts += "$($g.width)x$($g.height) ($($p.enlarged_with))"
+ }
+ return ($parts -join ' -> ')
+}
+
+function Run($name, $body) {
+ $json = $body | ConvertTo-Json -Depth 6
+ $job = Invoke-RestMethod -Method Post -Uri "$B/jobs" -Headers $H -ContentType 'application/json' -Body ([Text.Encoding]::UTF8.GetBytes($json))
+ Write-Host "== $name (plan: estimate $([math]::Round($job.plan.estimated_seconds))s)" -ForegroundColor Cyan
+ $sw = [Diagnostics.Stopwatch]::StartNew(); $last = ''
+ while ($true) {
+ $j = Invoke-RestMethod -Uri "$B/jobs/$($job.id)" -Headers $H
+ $step = if ($j.step) { " $($j.step[0])/$($j.step[1])" } else { '' }
+ $line = "$($j.status) $($j.stage)$step"
+ if ($line -ne $last) { Write-Host (" [{0,5:N1}s] {1}" -f $sw.Elapsed.TotalSeconds, $line); $last = $line }
+ if ($j.status -in 'done', 'failed', 'cancelled') { break }
+ Start-Sleep -Milliseconds 400
+ }
+ $secs = [math]::Round($sw.Elapsed.TotalSeconds, 1)
+ if ($j.status -ne 'done') {
+ Write-Host " ERROR: $($j.error | ConvertTo-Json -Depth 4)" -ForegroundColor Red
+ $script:results += [pscustomobject]@{ Test = $name; Seconds = $secs; Estimate = [math]::Round($j.plan.estimated_seconds); Size = ''; Pipeline = "FAILED: $($j.error.message)"; File = '' }
+ return $null
+ }
+ $g = $j.results[0]
+ Write-Host " $($g.width)x$($g.height) in $secs s - $(Pipeline $g)" -ForegroundColor Green
+ if ($j.notes) { Write-Host " notes: $($j.notes -join ' ')" -ForegroundColor DarkGray }
+ $script:results += [pscustomobject]@{ Test = $name; Seconds = $secs; Estimate = [math]::Round($j.plan.estimated_seconds); Size = "$($g.width)x$($g.height)"; Pipeline = (Pipeline $g); File = $g.file_path }
+ return $g
+}
+
+$prompt = 'a cozy mountain cabin at golden hour, snowy peaks, warm light in the windows, highly detailed photo'
+# 20 base steps like the 2K bench (C:\AI\sdcpp\bench\bench-2k.ps1) so timings compare.
+$gen2k = @{ prompt = $prompt; mode = 'generate'; images = @(); aspect_ratio = '16:9'; quality = 'quality'; resolution = 'auto'; seed = 42; advanced = @{ steps = 20 } }
+
+try {
+ Write-Host 'Loading the model (first job includes ~1 min of model load)...' -ForegroundColor Cyan
+ Invoke-RestMethod -Method Post -Uri "$B/backend/start" -Headers $H -TimeoutSec 900 | Out-Null
+ $st = Invoke-RestMethod -Uri "$B/status" -Headers $H
+ Write-Host "Upscaler: $($st.upscaler | ConvertTo-Json -Compress); server image upscale: $($st.server.upscale)"
+
+ $fast = $null
+ if (Want 'fast') { $fast = Run 'gen2k_fast' $gen2k }
+ if (Want 'best') {
+ $b = $gen2k.Clone(); $b.advanced = @{ steps = 20; refine = 'best' }
+ Run 'gen2k_best' $b | Out-Null
+ }
+ if (Want '4k') {
+ $k = $gen2k.Clone(); $k.resolution = 'custom'; $k.width = 3840; $k.height = 2160; $k.Remove('aspect_ratio')
+ Run 'gen4k_fast' $k | Out-Null
+ }
+ if (Want 'edit') {
+ $src = $EditImage
+ if (-not $src) {
+ if (-not $fast) { $fast = Run 'gen2k_fast' $gen2k }
+ $big = Run 'make_5120' @{ prompt = ''; mode = 'upscale'; images = @("gen:$($fast.id)"); upscale = @{ method = 'quick'; width = 5120; height = 2880 }; advanced = @{} }
+ $src = "gen:$($big.id)"
+ }
+ $edit = @{ prompt = 'make it a dark version: night, moonlight, keep everything else unchanged'; mode = 'edit'; images = @($src); quality = 'balanced'; resolution = 'auto'; seed = 3; advanced = @{} }
+ Run 'edit_balanced' $edit | Out-Null # ~1 MP, ESRGAN back to the source size
+ $e2 = $edit.Clone(); $e2.resolution = 'source'
+ Run 'edit_source_2pass' $e2 | Out-Null # base ~1 MP + refine 2048x1152, ESRGAN to the source size
+ }
+ if (Want 'upscale') {
+ if (-not $fast) { $fast = Run 'gen2k_fast' $gen2k }
+ Run 'upscale_quick_2x' @{ prompt = ''; mode = 'upscale'; images = @("gen:$($fast.id)"); upscale = @{ method = 'quick'; scale = 2 }; advanced = @{} } | Out-Null
+ $small = Run 'gen1mp' @{ prompt = $prompt; mode = 'generate'; images = @(); aspect_ratio = '16:9'; quality = 'fast'; resolution = 'auto'; seed = 5; advanced = @{} }
+ if ($small) {
+ Run 'upscale_detailed_4k' @{ prompt = ''; mode = 'upscale'; images = @("gen:$($small.id)"); upscale = @{ method = 'detailed'; width = 3840 }; advanced = @{} } | Out-Null
+ Run 'upscale_quick_4k' @{ prompt = ''; mode = 'upscale'; images = @("gen:$($small.id)"); upscale = @{ method = 'quick'; width = 3840 }; advanced = @{} } | Out-Null
+ }
+ }
+ if (Want 'logo') {
+ $logo = Run 'logo_1mp' @{ prompt = "flat vector logo for a coffee shop called 'BEAN THERE', thin black line art and lettering on a plain white background"; mode = 'generate'; images = @(); aspect_ratio = '1:1'; quality = 'fast'; resolution = 'auto'; seed = 11; advanced = @{} }
+ if ($logo) { Run 'logo_quick_4x' @{ prompt = ''; mode = 'upscale'; images = @("gen:$($logo.id)"); upscale = @{ method = 'quick'; scale = 4 }; advanced = @{} } | Out-Null }
+ }
+} finally {
+ Write-Host ''
+ $results | Format-Table Test, Seconds, Estimate, Size, Pipeline -AutoSize -Wrap
+ $results | ConvertTo-Json -Depth 4 | Set-Content -Encoding utf8 (Join-Path $out 'validate-results.json')
+ Write-Host "Images in $out (results: validate-results.json)."
+ Invoke-RestMethod -Method Post -Uri "$B/shutdown" -Headers $H -ErrorAction SilentlyContinue | Out-Null
+ Start-Sleep 2
+ if (-not $svc.HasExited) { Stop-Process -Id $svc.Id -Force }
+}
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
new file mode 100644
index 0000000..3dfb733
--- /dev/null
+++ b/src-tauri/Cargo.toml
@@ -0,0 +1,24 @@
+[package]
+name = "qwen-local-studio"
+version.workspace = true
+edition.workspace = true
+description = "Qwen Local Studio"
+
+[lib]
+name = "qls_app"
+crate-type = ["staticlib", "cdylib", "rlib"]
+
+[build-dependencies]
+tauri-build = { version = "2", features = [] }
+
+[dependencies]
+dirs = "7.0.0"
+image = { version = "0.25.10", default-features = false, features = ["png", "jpeg", "webp", "bmp", "gif", "tiff"] }
+reqwest = { version = "0.13.5", default-features = false, features = ["json", "blocking"] }
+serde = { version = "1.0.229", features = ["derive"] }
+serde_json = "1.0.151"
+tauri = { version = "2", features = [] }
+tauri-plugin-clipboard-manager = "2"
+tauri-plugin-dialog = "2"
+tauri-plugin-opener = "2"
+tauri-plugin-single-instance = "2"
diff --git a/src-tauri/build.rs b/src-tauri/build.rs
new file mode 100644
index 0000000..2846c57
--- /dev/null
+++ b/src-tauri/build.rs
@@ -0,0 +1 @@
+fn main() { tauri_build::build() }
diff --git a/src-tauri/capabilities/default.json b/src-tauri/capabilities/default.json
new file mode 100644
index 0000000..d1879c4
--- /dev/null
+++ b/src-tauri/capabilities/default.json
@@ -0,0 +1,16 @@
+{
+ "$schema": "../gen/schemas/desktop-schema.json",
+ "identifier": "default",
+ "description": "Main window: dialogs, clipboard text, window events, full-screen image viewer.",
+ "windows": ["main"],
+ "permissions": [
+ "core:default",
+ "core:window:allow-set-fullscreen",
+ "core:window:allow-is-fullscreen",
+ "dialog:allow-open",
+ "dialog:allow-save",
+ "dialog:allow-message",
+ "dialog:allow-ask",
+ "clipboard-manager:allow-write-text"
+ ]
+}
diff --git a/src-tauri/icons/128x128.png b/src-tauri/icons/128x128.png
new file mode 100644
index 0000000..e5ebad9
Binary files /dev/null and b/src-tauri/icons/128x128.png differ
diff --git a/src-tauri/icons/[email protected] b/src-tauri/icons/[email protected]
new file mode 100644
index 0000000..9e047d7
Binary files /dev/null and b/src-tauri/icons/[email protected] differ
diff --git a/src-tauri/icons/32x32.png b/src-tauri/icons/32x32.png
new file mode 100644
index 0000000..d549a4e
Binary files /dev/null and b/src-tauri/icons/32x32.png differ
diff --git a/src-tauri/icons/64x64.png b/src-tauri/icons/64x64.png
new file mode 100644
index 0000000..6090c7e
Binary files /dev/null and b/src-tauri/icons/64x64.png differ
diff --git a/src-tauri/icons/Square107x107Logo.png b/src-tauri/icons/Square107x107Logo.png
new file mode 100644
index 0000000..fdb2fc4
Binary files /dev/null and b/src-tauri/icons/Square107x107Logo.png differ
diff --git a/src-tauri/icons/Square142x142Logo.png b/src-tauri/icons/Square142x142Logo.png
new file mode 100644
index 0000000..2998dd5
Binary files /dev/null and b/src-tauri/icons/Square142x142Logo.png differ
diff --git a/src-tauri/icons/Square150x150Logo.png b/src-tauri/icons/Square150x150Logo.png
new file mode 100644
index 0000000..4fa1524
Binary files /dev/null and b/src-tauri/icons/Square150x150Logo.png differ
diff --git a/src-tauri/icons/Square284x284Logo.png b/src-tauri/icons/Square284x284Logo.png
new file mode 100644
index 0000000..39972bd
Binary files /dev/null and b/src-tauri/icons/Square284x284Logo.png differ
diff --git a/src-tauri/icons/Square30x30Logo.png b/src-tauri/icons/Square30x30Logo.png
new file mode 100644
index 0000000..e3bd4e1
Binary files /dev/null and b/src-tauri/icons/Square30x30Logo.png differ
diff --git a/src-tauri/icons/Square310x310Logo.png b/src-tauri/icons/Square310x310Logo.png
new file mode 100644
index 0000000..91a08e8
Binary files /dev/null and b/src-tauri/icons/Square310x310Logo.png differ
diff --git a/src-tauri/icons/Square44x44Logo.png b/src-tauri/icons/Square44x44Logo.png
new file mode 100644
index 0000000..d1e8045
Binary files /dev/null and b/src-tauri/icons/Square44x44Logo.png differ
diff --git a/src-tauri/icons/Square71x71Logo.png b/src-tauri/icons/Square71x71Logo.png
new file mode 100644
index 0000000..dbf3128
Binary files /dev/null and b/src-tauri/icons/Square71x71Logo.png differ
diff --git a/src-tauri/icons/Square89x89Logo.png b/src-tauri/icons/Square89x89Logo.png
new file mode 100644
index 0000000..56951ac
Binary files /dev/null and b/src-tauri/icons/Square89x89Logo.png differ
diff --git a/src-tauri/icons/StoreLogo.png b/src-tauri/icons/StoreLogo.png
new file mode 100644
index 0000000..a1c5bb3
Binary files /dev/null and b/src-tauri/icons/StoreLogo.png differ
diff --git a/src-tauri/icons/icon.icns b/src-tauri/icons/icon.icns
new file mode 100644
index 0000000..c976f55
Binary files /dev/null and b/src-tauri/icons/icon.icns differ
diff --git a/src-tauri/icons/icon.ico b/src-tauri/icons/icon.ico
new file mode 100644
index 0000000..ac731c0
Binary files /dev/null and b/src-tauri/icons/icon.ico differ
diff --git a/src-tauri/icons/icon.png b/src-tauri/icons/icon.png
new file mode 100644
index 0000000..f3b167a
Binary files /dev/null and b/src-tauri/icons/icon.png differ
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
new file mode 100644
index 0000000..b5c05a0
--- /dev/null
+++ b/src-tauri/src/lib.rs
@@ -0,0 +1,238 @@
+//! Desktop shell. The UI talks to qls-service over loopback HTTP; this shell only
+//! ensures the service is running, keeps a "ui" lease alive while the window is open,
+//! and provides native integrations (clipboard images, Explorer).
+
+use std::path::PathBuf;
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use serde::{Deserialize, Serialize};
+use tauri::{Manager, RunEvent};
+use tauri_plugin_clipboard_manager::ClipboardExt;
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+struct ServiceInfo {
+ port: u16,
+ token: String,
+ pid: u32,
+ version: String,
+}
+
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+struct Connection {
+ base_url: String,
+ token: String,
+ version: String,
+}
+
+#[derive(Default)]
+struct Shared {
+ info: Mutex<Option<ServiceInfo>>,
+ heartbeat_started: Mutex<bool>,
+ connect_lock: Mutex<()>,
+}
+
+fn client_id() -> String {
+ format!("ui-{}", std::process::id())
+}
+
+fn data_dir() -> PathBuf {
+ if let Ok(p) = std::env::var("QLS_DATA_DIR") {
+ return PathBuf::from(p);
+ }
+ dirs::data_local_dir().unwrap_or_else(std::env::temp_dir).join("QwenLocalStudio")
+}
+
+fn http() -> reqwest::blocking::Client {
+ reqwest::blocking::Client::builder().no_proxy().timeout(Duration::from_secs(5)).build().expect("http")
+}
+
+fn read_info() -> Option<ServiceInfo> {
+ serde_json::from_str(&std::fs::read_to_string(data_dir().join("service.json")).ok()?).ok()
+}
+
+fn ping(port: u16) -> bool {
+ http()
+ .get(format!("http://127.0.0.1:{port}/api/v1/ping"))
+ .timeout(Duration::from_millis(1500))
+ .send()
+ .map(|r| r.status().is_success())
+ .unwrap_or(false)
+}
+
+fn service_exe() -> Option<PathBuf> {
+ let me = std::env::current_exe().ok()?;
+ let dir = me.parent()?;
+ for name in ["qls-service.exe", "qls-service-x86_64-pc-windows-msvc.exe"] {
+ let p = dir.join(name);
+ if p.is_file() {
+ return Some(p);
+ }
+ }
+ None
+}
+
+fn spawn_service() -> Result<(), String> {
+ let exe = service_exe().ok_or("qls-service.exe was not found next to the application.")?;
+ let mut cmd = std::process::Command::new(exe);
+ cmd.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
+ #[cfg(windows)]
+ {
+ use std::os::windows::process::CommandExt;
+ // CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP: survives independently of this window.
+ cmd.creation_flags(0x0800_0000 | 0x0000_0200);
+ }
+ cmd.spawn().map_err(|e| format!("Could not start the Qwen Local Studio service: {e}"))?;
+ Ok(())
+}
+
+fn ensure_service(shared: &Shared) -> Result<ServiceInfo, String> {
+ let _g = shared.connect_lock.lock().unwrap();
+ if let Some(i) = read_info()
+ && ping(i.port)
+ {
+ return Ok(i);
+ }
+ spawn_service()?;
+ let start = Instant::now();
+ while start.elapsed() < Duration::from_secs(20) {
+ std::thread::sleep(Duration::from_millis(250));
+ if let Some(i) = read_info()
+ && ping(i.port)
+ {
+ return Ok(i);
+ }
+ }
+ Err("The Qwen Local Studio service did not start. See %LOCALAPPDATA%\\QwenLocalStudio\\logs\\service.log.".into())
+}
+
+fn heartbeat(info: &ServiceInfo) -> bool {
+ http()
+ .post(format!("http://127.0.0.1:{}/api/v1/session/heartbeat", info.port))
+ .bearer_auth(&info.token)
+ .json(&serde_json::json!({ "client_id": client_id(), "kind": "ui", "pid": std::process::id() }))
+ .send()
+ .map(|r| r.status().is_success())
+ .unwrap_or(false)
+}
+
+fn start_heartbeat(shared: Arc<Shared>) {
+ {
+ let mut started = shared.heartbeat_started.lock().unwrap();
+ if *started {
+ return;
+ }
+ *started = true;
+ }
+ std::thread::spawn(move || {
+ loop {
+ let info = shared.info.lock().unwrap().clone();
+ if let Some(i) = info
+ && !heartbeat(&i)
+ {
+ // Service gone (crash or manual stop): bring it back.
+ if let Ok(n) = ensure_service(&shared) {
+ heartbeat(&n);
+ *shared.info.lock().unwrap() = Some(n);
+ }
+ }
+ std::thread::sleep(Duration::from_secs(15));
+ }
+ });
+}
+
+#[tauri::command]
+async fn connect(state: tauri::State<'_, Arc<Shared>>) -> Result<Connection, String> {
+ let shared = state.inner().clone();
+ tauri::async_runtime::spawn_blocking(move || {
+ let info = ensure_service(&shared)?;
+ heartbeat(&info);
+ *shared.info.lock().unwrap() = Some(info.clone());
+ start_heartbeat(shared.clone());
+ Ok(Connection { base_url: format!("http://127.0.0.1:{}/api/v1", info.port), token: info.token, version: info.version })
+ })
+ .await
+ .map_err(|e| e.to_string())?
+}
+
+#[tauri::command]
+async fn copy_image(app: tauri::AppHandle, path: String) -> Result<(), String> {
+ let img = tauri::async_runtime::spawn_blocking(move || image::open(&path).map(|i| i.into_rgba8()))
+ .await
+ .map_err(|e| e.to_string())?
+ .map_err(|e| format!("Could not read the image: {e}"))?;
+ let (w, h) = img.dimensions();
+ app.clipboard().write_image(&tauri::image::Image::new_owned(img.into_raw(), w, h)).map_err(|e| e.to_string())
+}
+
+/// Returns the clipboard image as PNG bytes (empty if the clipboard holds no image).
+#[tauri::command]
+async fn read_clipboard_image(app: tauri::AppHandle) -> Result<tauri::ipc::Response, String> {
+ let Ok(img) = app.clipboard().read_image() else { return Ok(tauri::ipc::Response::new(Vec::<u8>::new())) };
+ let (w, h, rgba) = (img.width(), img.height(), img.rgba().to_vec());
+ let png = tauri::async_runtime::spawn_blocking(move || -> Result<Vec<u8>, String> {
+ let buf = image::RgbaImage::from_raw(w, h, rgba).ok_or("bad clipboard image")?;
+ let mut out = Vec::new();
+ image::DynamicImage::ImageRgba8(buf).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).map_err(|e| e.to_string())?;
+ Ok(out)
+ })
+ .await
+ .map_err(|e| e.to_string())??;
+ Ok(tauri::ipc::Response::new(png))
+}
+
+#[tauri::command]
+fn reveal(path: String) -> Result<(), String> {
+ tauri_plugin_opener::reveal_item_in_dir(&path).map_err(|e| e.to_string())
+}
+
+#[tauri::command]
+fn open_folder(app: tauri::AppHandle, path: String) -> Result<(), String> {
+ use tauri_plugin_opener::OpenerExt;
+ let p = PathBuf::from(&path);
+ if !p.is_dir() {
+ return Err("Folder not found.".into());
+ }
+ app.opener().open_path(path, None::<&str>).map_err(|e| e.to_string())
+}
+
+#[tauri::command]
+fn data_folder() -> String {
+ data_dir().to_string_lossy().into_owned()
+}
+
+fn release(shared: &Shared) {
+ if let Some(i) = shared.info.lock().unwrap().clone() {
+ let _ = http()
+ .post(format!("http://127.0.0.1:{}/api/v1/session/release", i.port))
+ .bearer_auth(&i.token)
+ .timeout(Duration::from_secs(2))
+ .json(&serde_json::json!({ "client_id": client_id(), "kind": "ui" }))
+ .send();
+ }
+}
+
+#[cfg_attr(mobile, tauri::mobile_entry_point)]
+pub fn run() {
+ let shared = Arc::new(Shared::default());
+ let app = tauri::Builder::default()
+ .plugin(tauri_plugin_single_instance::init(|app, _args, _cwd| {
+ if let Some(w) = app.get_webview_window("main") {
+ let _ = w.unminimize();
+ let _ = w.set_focus();
+ }
+ }))
+ .plugin(tauri_plugin_dialog::init())
+ .plugin(tauri_plugin_opener::init())
+ .plugin(tauri_plugin_clipboard_manager::init())
+ .manage(shared.clone())
+ .invoke_handler(tauri::generate_handler![connect, copy_image, read_clipboard_image, reveal, open_folder, data_folder])
+ .build(tauri::generate_context!())
+ .expect("error while building Qwen Local Studio");
+ app.run(move |_handle, event| {
+ if let RunEvent::Exit = event {
+ release(&shared);
+ }
+ });
+}
diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs
new file mode 100644
index 0000000..4673065
--- /dev/null
+++ b/src-tauri/src/main.rs
@@ -0,0 +1,6 @@
+// Prevents an extra console window on Windows in release.
+#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
+
+fn main() {
+ qls_app::run()
+}
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
new file mode 100644
index 0000000..70759a9
--- /dev/null
+++ b/src-tauri/tauri.conf.json
@@ -0,0 +1,46 @@
+{
+ "$schema": "https://schema.tauri.app/config/2",
+ "productName": "Qwen Local Studio",
+ "version": "1.0.0",
+ "identifier": "app.qwenlocalstudio.desktop",
+ "build": {
+ "beforeDevCommand": "npm run dev",
+ "devUrl": "http://localhost:1420",
+ "beforeBuildCommand": "npm run build",
+ "frontendDist": "../dist"
+ },
+ "app": {
+ "withGlobalTauri": false,
+ "windows": [
+ {
+ "label": "main",
+ "title": "Qwen Local Studio",
+ "width": 1320,
+ "height": 880,
+ "minWidth": 880,
+ "minHeight": 620,
+ "center": true,
+ "dragDropEnabled": true
+ }
+ ],
+ "security": {
+ "csp": "default-src 'self'; img-src 'self' data: blob: http://127.0.0.1:*; connect-src 'self' ipc: http://ipc.localhost http://127.0.0.1:*; style-src 'self' 'unsafe-inline'; font-src 'self' data:; script-src 'self'"
+ }
+ },
+ "bundle": {
+ "active": true,
+ "targets": ["nsis"],
+ "publisher": "Qwen Local Studio",
+ "shortDescription": "Local AI image generation and editing",
+ "longDescription": "Local text-to-image and image editing with Qwen-Image 2.1 via stable-diffusion.cpp. Everything runs on this PC.",
+ "category": "Graphics and Design",
+ "icon": ["icons/32x32.png", "icons/128x128.png", "icons/[email protected]", "icons/icon.ico"],
+ "externalBin": ["binaries/qls-service", "binaries/qls-mcp"],
+ "windows": {
+ "nsis": {
+ "installMode": "currentUser",
+ "displayLanguageSelector": false
+ }
+ }
+ }
+}
diff --git a/src/App.tsx b/src/App.tsx
new file mode 100644
index 0000000..aab8d38
--- /dev/null
+++ b/src/App.tsx
@@ -0,0 +1,258 @@
+import { getCurrentWebview } from "@tauri-apps/api/webview";
+import { Images, Loader2, Settings, SquarePen, X } from "lucide-react";
+import { useEffect, useState } from "react";
+import { api, configure } from "./lib/api";
+import { emptyComposer } from "./lib/logic";
+import { native } from "./lib/native";
+import {
+ addInputs, dismissToast, getState, refreshStatus, setState, startEvents, submitComposer, toastError, toastInfo, useStore,
+} from "./lib/store";
+import { Composer, importPaths } from "./components/Composer";
+import { ExpandEditor } from "./components/ExpandEditor";
+import { Gallery } from "./components/Gallery";
+import { InpaintEditor } from "./components/InpaintEditor";
+import { Settings as SettingsDialog } from "./components/Settings";
+import { Setup } from "./components/Setup";
+import { HistoryRail, Stage } from "./components/Stage";
+import { IconButton } from "./components/ui";
+
+const IMAGE_EXT = /\.(png|jpe?g|webp|bmp|gif|tiff?|heic|heif)$/i;
+
+function StatusIndicator() {
+ const connected = useStore((s) => s.connected);
+ const server = useStore((s) => s.server);
+ const busy = useStore((s) => Object.values(s.jobs).some((j) => !["done", "failed", "cancelled"].includes(j.status)));
+ let cls = "dot";
+ let text = "Connecting";
+ let title = "";
+ if (connected) {
+ switch (server.state) {
+ case "ready":
+ cls = "dot ready";
+ text = busy ? "Working" : "Ready";
+ title = server.owned ? "Model loaded" : "Using an inference server that was already running";
+ break;
+ case "starting":
+ cls = "dot busy";
+ text = "Loading model";
+ break;
+ case "error":
+ cls = "dot error";
+ text = server.error?.message ?? "Inference server error";
+ title = "Open Diagnostics";
+ break;
+ default:
+ text = "Model not loaded";
+ title = "Click to load the model now";
+ }
+ }
+ return (
+ <button
+ className="status"
+ title={title}
+ onClick={() => {
+ if (server.state === "error") setState({ overlay: "settings" });
+ else if (server.state === "stopped" && connected) api.startBackend().then(refreshStatus, toastError);
+ }}
+ >
+ <span className={cls} />
+ <span style={{ maxWidth: 360, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{text}</span>
+ </button>
+ );
+}
+
+function Toasts() {
+ const toasts = useStore((s) => s.toasts);
+ const [open, setOpen] = useState<string | null>(null);
+ return (
+ <div className="toasts" role="status">
+ {toasts.map((t) => (
+ <div key={t.id} className="toast">
+ <div className="body">
+ <div>{t.message}</div>
+ {t.suggestion && <div className="sugg">{t.suggestion}</div>}
+ {t.detail && (
+ <button onClick={() => setOpen(open === t.id ? null : t.id)} style={{ marginTop: 4 }}>
+ {open === t.id ? "Hide details" : "Details"}
+ </button>
+ )}
+ {open === t.id && <pre>{t.detail}</pre>}
+ </div>
+ <button onClick={() => dismissToast(t.id)} aria-label="Dismiss">
+ <X size={14} />
+ </button>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+async function uploadBlobs(files: File[]) {
+ const recs = [];
+ for (const f of files) {
+ try {
+ recs.push(await api.upload(f, f.name || "pasted.png"));
+ } catch (e) {
+ toastError(e);
+ }
+ }
+ addInputs(recs);
+}
+
+export default function App() {
+ const overlay = useStore((s) => s.overlay);
+ const needsSetup = useStore((s) => s.needsSetup);
+ const [boot, setBoot] = useState<"connecting" | "ok" | string>("connecting");
+ const [dragging, setDragging] = useState(false);
+
+ // Connect to (or start) the local service.
+ useEffect(() => {
+ let cancelled = false;
+ (async () => {
+ try {
+ const conn = await native.connect();
+ if (cancelled) return;
+ configure(conn.baseUrl, conn.token);
+ startEvents();
+ const cfg = await api.config();
+ const st = await refreshStatus();
+ setState({ needsSetup: !cfg.setupComplete });
+ setBoot("ok");
+ // Preload the model so the first generation starts immediately.
+ if (cfg.setupComplete && st && st.server.state === "stopped") api.startBackend().then(refreshStatus, () => refreshStatus());
+ } catch (e) {
+ setBoot(String(e));
+ }
+ })();
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ // Native file drops (paths) — efficient: the service reads the files itself.
+ useEffect(() => {
+ let un: (() => void) | undefined;
+ getCurrentWebview()
+ .onDragDropEvent((ev) => {
+ const p = ev.payload;
+ if (p.type === "enter" || p.type === "over") setDragging(true);
+ else if (p.type === "leave") setDragging(false);
+ else if (p.type === "drop") {
+ setDragging(false);
+ const paths = p.paths.filter((x) => IMAGE_EXT.test(x));
+ if (paths.length) importPaths(paths);
+ else if (p.paths.length) toastInfo("Only image files can be added.");
+ }
+ })
+ .then((u) => (un = u))
+ .catch(() => {});
+ return () => un?.();
+ }, []);
+
+ // Clipboard paste: browser image data first, native clipboard as a fallback.
+ useEffect(() => {
+ const onPaste = async (e: ClipboardEvent) => {
+ if (getState().overlay) return;
+ const files = Array.from(e.clipboardData?.files ?? []).filter((f) => f.type.startsWith("image/"));
+ if (files.length) {
+ e.preventDefault();
+ uploadBlobs(files);
+ return;
+ }
+ if (e.clipboardData?.getData("text")) return;
+ try {
+ const png = await native.readClipboardImage();
+ if (png) uploadBlobs([new File([png as BlobPart], "pasted.png", { type: "image/png" })]);
+ } catch {
+ /* nothing to paste */
+ }
+ };
+ window.addEventListener("paste", onPaste);
+ return () => window.removeEventListener("paste", onPaste);
+ }, []);
+
+ // Keyboard: arrows browse the session, Ctrl+Enter generates.
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ const typing = (e.target as HTMLElement)?.closest("input, textarea, select");
+ const s = getState();
+ if (s.overlay) return;
+ if ((e.ctrlKey || e.metaKey) && e.key === "Enter") {
+ e.preventDefault();
+ submitComposer();
+ return;
+ }
+ if (typing) return;
+ if (e.key === "ArrowLeft" || e.key === "ArrowRight" || e.key === "ArrowUp" || e.key === "ArrowDown") {
+ const i = s.session.findIndex((x) => x.key === s.selected);
+ const d = e.key === "ArrowLeft" || e.key === "ArrowUp" ? -1 : 1;
+ const n = s.session[Math.max(0, Math.min(s.session.length - 1, i + d))];
+ if (n) setState({ selected: n.key });
+ }
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, []);
+
+ if (boot !== "ok") {
+ return (
+ <div className="app" style={{ display: "grid", placeItems: "center" }}>
+ {boot === "connecting" ? (
+ <Loader2 className="spin" size={22} />
+ ) : (
+ <div className="failed">
+ <strong>Could not start the local service</strong>
+ <span>{boot}</span>
+ <button className="btn" onClick={() => location.reload()}>
+ Try again
+ </button>
+ </div>
+ )}
+ </div>
+ );
+ }
+
+ return (
+ <div className="app">
+ <div className="topbar">
+ <div className="brand">
+ <StatusIndicator />
+ </div>
+ <div className="toolbar">
+ <IconButton
+ title="New"
+ onClick={() => {
+ const c = getState().composer;
+ setState({ composer: emptyComposer(c), selected: null });
+ }}
+ >
+ <SquarePen size={18} />
+ </IconButton>
+ <IconButton title="Gallery" active={overlay === "gallery"} onClick={() => setState({ overlay: overlay === "gallery" ? null : "gallery" })}>
+ <Images size={18} />
+ </IconButton>
+ <IconButton title="Settings" onClick={() => setState({ overlay: "settings" })}>
+ <Settings size={18} />
+ </IconButton>
+ </div>
+ </div>
+ <div className="main">
+ {needsSetup ? (
+ <Setup />
+ ) : (
+ <>
+ <Stage />
+ <HistoryRail />
+ </>
+ )}
+ {overlay === "gallery" && <Gallery />}
+ {overlay === "inpaint" && <InpaintEditor />}
+ {overlay === "expand" && <ExpandEditor />}
+ {dragging && <div className="drop-hint">Drop images to add them</div>}
+ </div>
+ {!needsSetup && overlay !== "inpaint" && overlay !== "expand" && overlay !== "gallery" && <Composer />}
+ {overlay === "settings" && <SettingsDialog />}
+ <Toasts />
+ </div>
+ );
+}
diff --git a/src/components/Advanced.tsx b/src/components/Advanced.tsx
new file mode 100644
index 0000000..ba75bf2
--- /dev/null
+++ b/src/components/Advanced.tsx
@@ -0,0 +1,158 @@
+import { Dices, RotateCcw } from "lucide-react";
+import { planPipeline } from "../lib/logic";
+import { updateComposer, useStore } from "../lib/store";
+import type { Advanced, OutputFormat, Plan, ResolutionMode } from "../lib/types";
+import { Seg, Switch } from "./ui";
+
+// Verified against sd-server 3f8527a capabilities; replaced by the live list when loaded.
+const FALLBACK_SAMPLERS = ["euler", "euler_a", "heun", "dpm2", "dpm++2s_a", "dpm++2m", "dpm++2mv2", "ipndm", "ipndm_v", "lcm", "ddim_trailing", "tcd", "res_multistep", "res_2s", "er_sde"];
+const FALLBACK_SCHEDULERS = ["discrete", "karras", "exponential", "ays", "gits", "sgm_uniform", "simple", "smoothstep", "kl_optimal", "lcm", "beta", "flux"];
+
+const RESOLUTIONS: { value: ResolutionMode; label: string }[] = [
+ { value: "auto", label: "Auto" },
+ { value: "source", label: "Source" },
+ { value: "1k", label: "1K" },
+ { value: "1.5k", label: "1.5K" },
+ { value: "2k", label: "2K" },
+ { value: "custom", label: "Custom" },
+];
+
+function NumField(props: { label: string; value: number | null | undefined; placeholder: string; min: number; max: number; step?: number; onChange: (v: number | null) => void }) {
+ return (
+ <label className="field-row">
+ <span>{props.label}</span>
+ <input
+ className="input"
+ style={{ width: 110 }}
+ type="number"
+ min={props.min}
+ max={props.max}
+ step={props.step ?? 1}
+ placeholder={props.placeholder}
+ value={props.value ?? ""}
+ onChange={(e) => {
+ const v = e.target.value === "" ? null : Number(e.target.value);
+ props.onChange(v === null || Number.isNaN(v) ? null : Math.min(props.max, Math.max(props.min, v)));
+ }}
+ />
+ </label>
+ );
+}
+
+export function AdvancedPanel({ plan }: { plan: Plan | null }) {
+ const c = useStore((s) => s.composer);
+ const samplers = useStore((s) => (s.status?.server as { samplers?: string[] } | undefined)?.samplers);
+ const schedulers = useStore((s) => (s.status?.server as { schedulers?: string[] } | undefined)?.schedulers);
+ const a = c.advanced;
+ const setA = (patch: Partial<Advanced>) => updateComposer({ advanced: { ...a, ...patch } });
+ const editLike = plan && (plan.mode === "inpaint" || plan.mode === "outpaint" || plan.mode === "edit");
+
+ return (
+ <>
+ <div className="field">
+ <span>Resolution</span>
+ <Seg value={c.resolution} options={RESOLUTIONS} onChange={(v) => updateComposer({ resolution: v })} />
+ {c.resolution === "custom" && (
+ <div style={{ display: "flex", gap: 8, alignItems: "center" }}>
+ <input className="input" type="number" min={64} max={4096} value={c.customWidth} onChange={(e) => updateComposer({ customWidth: Math.max(64, Math.min(4096, Number(e.target.value) || 64)) })} style={{ width: 90 }} />
+ <span className="muted">×</span>
+ <input className="input" type="number" min={64} max={4096} value={c.customHeight} onChange={(e) => updateComposer({ customHeight: Math.max(64, Math.min(4096, Number(e.target.value) || 64)) })} style={{ width: 90 }} />
+ </div>
+ )}
+ {plan && <span className="muted">{planPipeline(plan)}</span>}
+ </div>
+
+ <label className="field-row">
+ <span>Seed</span>
+ <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
+ <input
+ className="input"
+ style={{ width: 120 }}
+ type="number"
+ placeholder="Random"
+ value={c.seed ?? ""}
+ onChange={(e) => updateComposer({ seed: e.target.value === "" ? null : Math.max(0, Math.floor(Number(e.target.value))) })}
+ />
+ <button className="icon-btn sm" title="Random seed" onClick={() => updateComposer({ seed: null })}>
+ <Dices size={15} />
+ </button>
+ </div>
+ </label>
+
+ <NumField label="Steps" value={a.steps} placeholder={String(plan?.steps ?? "Auto")} min={1} max={150} onChange={(v) => setA({ steps: v })} />
+ <NumField label="CFG" value={a.cfg} placeholder={String(plan?.cfg ?? "Auto")} min={0} max={30} step={0.5} onChange={(v) => setA({ cfg: v })} />
+
+ <label className="field-row">
+ <span>Sampler</span>
+ <select className="select" value={a.sampler ?? ""} onChange={(e) => setA({ sampler: e.target.value || null })}>
+ <option value="">Default ({plan?.sampler ?? "euler"})</option>
+ {(samplers?.length ? samplers : FALLBACK_SAMPLERS).map((s) => (
+ <option key={s} value={s}>
+ {s}
+ </option>
+ ))}
+ </select>
+ </label>
+ <label className="field-row">
+ <span>Scheduler</span>
+ <select className="select" value={a.scheduler ?? ""} onChange={(e) => setA({ scheduler: e.target.value || null })}>
+ <option value="">Default (model)</option>
+ {(schedulers?.length ? schedulers : FALLBACK_SCHEDULERS).map((s) => (
+ <option key={s} value={s}>
+ {s}
+ </option>
+ ))}
+ </select>
+ </label>
+
+ {editLike && (
+ <label className="field">
+ <span>
+ Edit strength {a.strength != null ? a.strength.toFixed(2) : plan?.strength != null ? `(auto ${plan.strength})` : "(auto)"}
+ </span>
+ <input type="range" min={0.05} max={1} step={0.05} value={a.strength ?? plan?.strength ?? 1} onChange={(e) => setA({ strength: Number(e.target.value) })} />
+ </label>
+ )}
+
+ <NumField label="Images per run" value={a.batch_count} placeholder="1" min={1} max={4} onChange={(v) => setA({ batch_count: v })} />
+
+ <div className="field">
+ <span>Format</span>
+ <Seg<OutputFormat>
+ value={a.output_format ?? "png"}
+ options={[
+ { value: "png", label: "PNG" },
+ { value: "jpeg", label: "JPEG" },
+ { value: "webp", label: "WebP" },
+ ]}
+ onChange={(v) => setA({ output_format: v })}
+ />
+ </div>
+
+ {c.refs[0]?.hdr && (
+ <div className="field-row">
+ <span title="The HEIC source has an HDR gain map. The result is saved as an Ultra HDR JPEG; the HDR boost fades where the edit changed brightness.">
+ Keep HDR (Ultra HDR JPEG)
+ </span>
+ <Switch on={a.hdr ?? true} onChange={(v) => setA({ hdr: v })} label="Keep HDR" />
+ </div>
+ )}
+
+ <div className="field-row">
+ <span>
+ VAE tiling {a.vae_tiling == null ? `(auto: ${plan?.vae_tiling ? "on" : "off"})` : ""}
+ </span>
+ <Switch on={a.vae_tiling ?? plan?.vae_tiling ?? false} onChange={(v) => setA({ vae_tiling: v })} label="VAE tiling" />
+ </div>
+
+ <label className="field">
+ <span>Negative prompt</span>
+ <textarea className="input" rows={2} value={c.negative} placeholder="Optional; used only when CFG is above 1" onChange={(e) => updateComposer({ negative: e.target.value })} />
+ </label>
+
+ <button className="btn" onClick={() => updateComposer({ advanced: {}, seed: null, negative: "", resolution: "auto" })}>
+ <RotateCcw size={14} /> Reset to automatic
+ </button>
+ </>
+ );
+}
diff --git a/src/components/Compare.tsx b/src/components/Compare.tsx
new file mode 100644
index 0000000..c115d39
--- /dev/null
+++ b/src/components/Compare.tsx
@@ -0,0 +1,205 @@
+// Before / after views for results made from another image (edit, inpaint, expand, upscale).
+
+import { useEffect, useRef, useState } from "react";
+import { urls } from "../lib/api";
+import { diffPixels, type CompareBase, type CompareMode } from "../lib/logic";
+import { setState, useStore } from "../lib/store";
+import type { GenerationRecord } from "../lib/types";
+import { Seg, useFit } from "./ui";
+import { FullscreenButton } from "./Viewer";
+
+const MODES: { value: CompareMode; label: string }[] = [
+ { value: "off", label: "Result" },
+ { value: "slider", label: "Slider" },
+ { value: "flicker", label: "Flicker" },
+ { value: "diff", label: "Changes" },
+];
+const SPEEDS: { value: string; label: string }[] = [
+ { value: "250", label: "Fast" },
+ { value: "500", label: "Normal" },
+ { value: "1000", label: "Slow" },
+];
+/** Long side of the difference map; downscaling also averages out the VAE re-encode noise. */
+const DIFF_SIDE = 1024;
+
+const isTyping = (t: EventTarget | null) => t instanceof HTMLElement && (t.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(t.tagName));
+
+/** The result with the selected comparison view, sized to fit the stage (or the screen). */
+export function CompareFrame({ g, base, fullscreen = false }: { g: GenerationRecord; base: CompareBase; fullscreen?: boolean }) {
+ const mode = useStore((s) => s.compare);
+ const flickerMs = useStore((s) => s.flickerMs);
+ const { ref, box } = useFit(g.width / g.height);
+ const [split, setSplit] = useState(0.5);
+ const [holding, setHolding] = useState(false);
+ const [phase, setPhase] = useState<"before" | "after">("after");
+ const dragging = useRef(false);
+ const after = urls.gen(g.id);
+ const before = urls.input(base.inputId);
+
+ useEffect(() => {
+ if (mode !== "flicker") return;
+ setPhase("before");
+ const t = window.setInterval(() => setPhase((p) => (p === "before" ? "after" : "before")), flickerMs);
+ return () => window.clearInterval(t);
+ }, [mode, flickerMs, g.id]);
+
+ // Hold B to peek at the original from any view.
+ useEffect(() => {
+ const down = (e: KeyboardEvent) => {
+ if (e.key.toLowerCase() === "b" && !e.repeat && !e.ctrlKey && !e.metaKey && !e.altKey && !isTyping(e.target)) setHolding(true);
+ };
+ const up = (e: KeyboardEvent) => e.key.toLowerCase() === "b" && setHolding(false);
+ const blur = () => setHolding(false);
+ window.addEventListener("keydown", down);
+ window.addEventListener("keyup", up);
+ window.addEventListener("blur", blur);
+ return () => {
+ window.removeEventListener("keydown", down);
+ window.removeEventListener("keyup", up);
+ window.removeEventListener("blur", blur);
+ };
+ }, []);
+
+ const setFromPointer = (e: React.PointerEvent<HTMLDivElement>) => {
+ const r = e.currentTarget.getBoundingClientRect();
+ setSplit(Math.min(1, Math.max(0, (e.clientX - r.left) / r.width)));
+ };
+
+ const showBefore = holding || (mode === "flicker" && phase === "before");
+ const label = holding || mode === "flicker" ? (showBefore ? "Before" : "After") : null;
+ const pct = (v: number) => `${v * 100}%`;
+ const { x, y, w, h } = base.rect;
+
+ return (
+ <div className={fullscreen ? "viewer-frame" : "stage-frame"} ref={ref}>
+ <div
+ className={`compare-box ${mode === "slider" ? "slider" : ""}`}
+ style={{ width: box.w, height: box.h }}
+ onPointerDown={(e) => {
+ if (e.button !== 0) return;
+ e.currentTarget.setPointerCapture(e.pointerId);
+ if (mode === "slider") {
+ dragging.current = true;
+ setFromPointer(e);
+ } else if (mode === "off") setHolding(true);
+ }}
+ onPointerMove={(e) => dragging.current && setFromPointer(e)}
+ onPointerUp={() => {
+ dragging.current = false;
+ if (mode === "off") setHolding(false);
+ }}
+ onPointerCancel={() => {
+ dragging.current = false;
+ setHolding(false);
+ }}
+ onDoubleClick={() => setState({ overlay: null })}
+ title={mode === "off" ? "Press and hold (or hold B) to see the original" : undefined}
+ >
+ <img className="compare-img" src={after} alt={g.prompt} draggable={false} />
+ {mode === "diff" && !holding && <DiffCanvas after={after} before={before} rect={base.rect} />}
+ {/* The original stays mounted (hidden) so switching is instant. */}
+ <div
+ className="compare-before"
+ style={{
+ visibility: showBefore || mode === "slider" ? "visible" : "hidden",
+ clipPath: mode === "slider" && !holding ? `inset(0 ${pct(1 - split)} 0 0)` : undefined,
+ }}
+ >
+ <img src={before} alt="Original" draggable={false} style={{ left: pct(x), top: pct(y), width: pct(w), height: pct(h) }} />
+ </div>
+ {mode === "slider" && !holding && (
+ <>
+ <div className="compare-handle" style={{ left: pct(split) }}>
+ <span />
+ </div>
+ <span className="compare-tag left">Before</span>
+ <span className="compare-tag right">After</span>
+ </>
+ )}
+ {label && <span className="compare-tag left">{label}</span>}
+ {!fullscreen && (
+ <FullscreenButton
+ hint="Hold B for the original"
+ content={
+ <>
+ <CompareFrame g={g} base={base} fullscreen />
+ <div className="viewer-compare-bar">
+ <CompareBar />
+ </div>
+ </>
+ }
+ />
+ )}
+ </div>
+ </div>
+ );
+}
+
+/** Highlights what changed: dimmed result, changed pixels in red. */
+function DiffCanvas({ after, before, rect }: { after: string; before: string; rect: CompareBase["rect"] }) {
+ const ref = useRef<HTMLCanvasElement>(null);
+ const [share, setShare] = useState<number | null>(null);
+ const [error, setError] = useState(false);
+
+ useEffect(() => {
+ let alive = true;
+ setShare(null);
+ setError(false);
+ const load = (src: string) =>
+ new Promise<HTMLImageElement>((ok, fail) => {
+ const im = new Image();
+ im.crossOrigin = "anonymous";
+ im.onload = () => ok(im);
+ im.onerror = fail;
+ // A separate URL: the displayed <img> loads without CORS, and reusing that cached
+ // response for a CORS request would fail.
+ im.src = `${src}&cors=1`;
+ });
+ Promise.all([load(after), load(before)])
+ .then(([a, b]) => {
+ const cv = ref.current;
+ if (!alive || !cv) return;
+ const k = Math.min(1, DIFF_SIDE / Math.max(a.naturalWidth, a.naturalHeight));
+ const W = Math.max(1, Math.round(a.naturalWidth * k));
+ const H = Math.max(1, Math.round(a.naturalHeight * k));
+ cv.width = W;
+ cv.height = H;
+ const ctx = cv.getContext("2d", { willReadFrequently: true })!;
+ ctx.imageSmoothingQuality = "high";
+ ctx.drawImage(a, 0, 0, W, H);
+ const A = ctx.getImageData(0, 0, W, H);
+ ctx.clearRect(0, 0, W, H);
+ ctx.drawImage(b, rect.x * W, rect.y * H, rect.w * W, rect.h * H);
+ const B = ctx.getImageData(0, 0, W, H);
+ const out = ctx.createImageData(W, H);
+ const s = diffPixels(A.data, B.data, out.data);
+ ctx.putImageData(out, 0, 0);
+ setShare(s);
+ })
+ .catch(() => alive && setError(true));
+ return () => {
+ alive = false;
+ };
+ }, [after, before, rect.x, rect.y, rect.w, rect.h]);
+
+ return (
+ <>
+ <canvas ref={ref} className="compare-diff" />
+ <span className="compare-tag left">
+ {error ? "Could not compare the images" : share === null ? "Comparing…" : share < 0.001 ? "No visible change" : `≈${share < 0.01 ? "<1" : Math.round(share * 100)}% of the image changed`}
+ </span>
+ </>
+ );
+}
+
+/** View switch shown under a result that has an original to compare with. */
+export function CompareBar() {
+ const mode = useStore((s) => s.compare);
+ const flickerMs = useStore((s) => s.flickerMs);
+ return (
+ <div className="compare-bar">
+ <Seg value={mode} options={MODES} onChange={(v) => setState({ compare: v })} />
+ {mode === "flicker" && <Seg value={String(flickerMs)} options={SPEEDS} onChange={(v) => setState({ flickerMs: Number(v) })} />}
+ </div>
+ );
+}
diff --git a/src/components/Composer.tsx b/src/components/Composer.tsx
new file mode 100644
index 0000000..a20ca59
--- /dev/null
+++ b/src/components/Composer.tsx
@@ -0,0 +1,360 @@
+import {
+ ArrowUp, Brush, ChevronDown, Combine, Expand, Gauge, ImagePlus, Pencil, RectangleHorizontal, RectangleVertical, SlidersHorizontal, Sparkles, Square, Wand2, X, ZoomIn,
+} from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { api, urls } from "../lib/api";
+import { activeOverrides, buildRequest, expansionPixels, formatDuration, hasOutpaint, MODE_LABEL, moveRef, type Ref } from "../lib/logic";
+import { native } from "../lib/native";
+import { addInputs, getState, setState, submitComposer, toastError, updateComposer, useStore } from "../lib/store";
+import type { Mode, Plan, Quality } from "../lib/types";
+import { AdvancedPanel } from "./Advanced";
+import { Option, Popover } from "./ui";
+
+const thumbUrl = (r: Ref) => (r.source.startsWith("gen:") ? urls.genThumb(r.source.slice(4)) : urls.inputThumb(r.source.slice(6)));
+
+const MODE_ICON: Record<Mode, React.ReactNode> = {
+ auto: <Sparkles size={15} />,
+ generate: <Wand2 size={15} />,
+ edit: <Pencil size={15} />,
+ multi_reference: <Combine size={15} />,
+ inpaint: <Brush size={15} />,
+ outpaint: <Expand size={15} />,
+ upscale: <ZoomIn size={15} />,
+};
+
+const QUALITY: { value: Quality; label: string; sub: string }[] = [
+ { value: "fast", label: "Fast", sub: "~1 MP, 20 steps" },
+ { value: "balanced", label: "Balanced", sub: "~1 MP, 40 steps · recommended" },
+ { value: "quality", label: "Quality", sub: "native 2K, 40 steps · slower" },
+];
+
+const ASPECT_ICON: Record<string, React.ReactNode> = {
+ "1:1": <Square size={15} />,
+ "4:3": <RectangleHorizontal size={15} />,
+ "16:9": <RectangleHorizontal size={15} />,
+ "3:4": <RectangleVertical size={15} />,
+ "9:16": <RectangleVertical size={15} />,
+};
+
+export async function importPaths(paths: string[]) {
+ const recs = [];
+ for (const p of paths) {
+ try {
+ recs.push(await api.importPath(p));
+ } catch (e) {
+ toastError(e);
+ }
+ }
+ addInputs(recs);
+}
+
+function RefStrip() {
+ const refs = useStore((s) => s.composer.refs);
+ const mask = useStore((s) => s.composer.mask);
+ const [drag, setDrag] = useState<{ from: number; to: number; active: boolean } | null>(null);
+ const boxRef = useRef<HTMLDivElement>(null);
+ const start = useRef<{ x: number; idx: number } | null>(null);
+
+ const indexAt = (clientX: number) => {
+ const els = Array.from(boxRef.current?.querySelectorAll<HTMLElement>(".ref") ?? []);
+ for (let i = 0; i < els.length; i++) {
+ const r = els[i].getBoundingClientRect();
+ if (clientX < r.left + r.width / 2) return i;
+ }
+ return els.length;
+ };
+
+ if (!refs.length) return null;
+ return (
+ <div
+ className="refs"
+ ref={boxRef}
+ onPointerMove={(e) => {
+ if (!start.current) return;
+ if (!drag?.active && Math.abs(e.clientX - start.current.x) < 5) return;
+ setDrag({ from: start.current.idx, to: indexAt(e.clientX), active: true });
+ }}
+ onPointerUp={() => {
+ if (drag?.active) {
+ const to = drag.to > drag.from ? drag.to - 1 : drag.to;
+ updateComposer({ refs: moveRef(getState().composer.refs, drag.from, to) });
+ }
+ start.current = null;
+ setDrag(null);
+ }}
+ onPointerLeave={() => {
+ start.current = null;
+ setDrag(null);
+ }}
+ >
+ {refs.map((r, i) => (
+ <div
+ key={r.key}
+ className={`ref ${drag?.active && drag.from === i ? "dragging" : ""} ${drag?.active && drag.to === i && drag.from !== i ? "drop-before" : ""}`}
+ title={`Image ${i + 1} · ${r.width}×${r.height}${refs.length > 1 ? " — drag to reorder" : ""}`}
+ onPointerDown={(e) => {
+ if ((e.target as HTMLElement).closest(".rm")) return;
+ (e.currentTarget.parentElement as HTMLElement).setPointerCapture?.(e.pointerId);
+ start.current = { x: e.clientX, idx: i };
+ }}
+ >
+ <img src={thumbUrl(r)} alt="" draggable={false} />
+ {refs.length > 1 && <span className="num">{i + 1}</span>}
+ {mask && mask.refKey === r.key && (
+ <span className="badge" title="Mask painted">
+ <Brush size={11} />
+ </span>
+ )}
+ <button
+ className="rm"
+ title="Remove"
+ aria-label={`Remove image ${i + 1}`}
+ onClick={() => {
+ const c = getState().composer;
+ updateComposer({ refs: c.refs.filter((x) => x.key !== r.key), mask: c.mask?.refKey === r.key ? null : c.mask, outpaint: i === 0 ? null : c.outpaint });
+ }}
+ >
+ <X size={12} />
+ </button>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+function usePlanPreview(): { plan: Plan | null; error: string | null } {
+ const c = useStore((s) => s.composer);
+ const connected = useStore((s) => s.connected);
+ const [res, setRes] = useState<{ plan: Plan | null; error: string | null }>({ plan: null, error: null });
+ useEffect(() => {
+ if (!connected) return;
+ const prompt = c.prompt.trim() || "image";
+ const req = { ...buildRequest(c), prompt };
+ let cancelled = false;
+ const t = window.setTimeout(() => {
+ api.plan(req).then(
+ (p) => !cancelled && setRes({ plan: p, error: null }),
+ (e) => !cancelled && setRes({ plan: null, error: e?.message ?? null }),
+ );
+ }, 350);
+ return () => {
+ cancelled = true;
+ window.clearTimeout(t);
+ };
+ }, [connected, c.prompt, c.refs, c.mode, c.quality, c.resolution, c.aspect, c.outpaint, c.mask, c.customWidth, c.customHeight, c.advanced]);
+ return res;
+}
+
+export function Composer() {
+ const c = useStore((s) => s.composer);
+ const { plan, error } = usePlanPreview();
+ const taRef = useRef<HTMLTextAreaElement>(null);
+ const hasImages = c.refs.length > 0;
+ const overrides = activeOverrides(c.advanced);
+
+ useEffect(() => {
+ const ta = taRef.current;
+ if (!ta) return;
+ ta.style.height = "auto";
+ ta.style.height = Math.min(200, ta.scrollHeight) + "px";
+ }, [c.prompt]);
+
+ const detected = plan ? (plan.mode as Mode) : null;
+ const modeShown: Mode = c.mode === "auto" ? detected ?? "auto" : c.mode;
+ const outPx = hasOutpaint(c.outpaint) && c.refs[0] ? expansionPixels(c.outpaint!, c.refs[0].width, c.refs[0].height) : null;
+
+ const placeholder = !hasImages
+ ? "Describe an image…"
+ : c.refs.length > 1
+ ? "Describe how to combine image 1, image 2…"
+ : c.mask
+ ? "Describe what goes in the painted area…"
+ : outPx
+ ? "Describe the extended scene (optional details)…"
+ : "Describe the change…";
+
+ const openEditor = (overlay: "inpaint" | "expand") => {
+ const first = getState().composer.refs[0];
+ if (!first) return;
+ setState({ overlay });
+ };
+
+ const hint = (() => {
+ if (error) return error;
+ if (!plan) return "";
+ const parts = [`${plan.output.width}×${plan.output.height}`];
+ if (plan.working.width !== plan.output.width || plan.working.height !== plan.output.height) parts.push(`works at ${plan.working.width}×${plan.working.height}`);
+ parts.push(`~${formatDuration(plan.estimated_seconds)}`);
+ if (plan.optimized_for_vram) parts.push("optimized for VRAM");
+ return parts.join(" · ");
+ })();
+
+ return (
+ <div className="composer-wrap">
+ <div className="composer">
+ <RefStrip />
+ {(outPx || c.mask) && (
+ <div style={{ display: "flex", gap: 6, paddingBottom: 6 }}>
+ {outPx && (
+ <span className="chip">
+ <Expand size={13} /> Expand {outPx.left ? `←${outPx.left} ` : ""}
+ {outPx.right ? `→${outPx.right} ` : ""}
+ {outPx.top ? `↑${outPx.top} ` : ""}
+ {outPx.bottom ? `↓${outPx.bottom}` : ""}
+ <button onClick={() => openEditor("expand")} title="Adjust">
+ <Pencil size={12} />
+ </button>
+ <button onClick={() => updateComposer({ outpaint: null })} title="Remove expansion">
+ <X size={13} />
+ </button>
+ </span>
+ )}
+ {c.mask && (
+ <span className="chip">
+ <Brush size={13} /> Mask on image 1
+ <button onClick={() => openEditor("inpaint")} title="Edit mask">
+ <Pencil size={12} />
+ </button>
+ <button onClick={() => updateComposer({ mask: null })} title="Remove mask">
+ <X size={13} />
+ </button>
+ </span>
+ )}
+ </div>
+ )}
+ <textarea
+ id="prompt"
+ ref={taRef}
+ className="prompt"
+ rows={1}
+ value={c.prompt}
+ placeholder={placeholder}
+ onChange={(e) => updateComposer({ prompt: e.target.value })}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ submitComposer();
+ }
+ }}
+ spellCheck
+ />
+ <div className="controls">
+ <button
+ className="icon-btn"
+ title="Add images (or drop / paste)"
+ aria-label="Add images"
+ onClick={async () => importPaths(await native.pickImages())}
+ >
+ <ImagePlus size={19} />
+ </button>
+
+ <Popover
+ trigger={(open, toggle) => (
+ <button className={`pill ${open ? "on" : ""}`} onClick={toggle} title={plan?.mode_reason ? `Auto: ${plan.mode_reason}` : "Mode"}>
+ {MODE_ICON[modeShown]}
+ {c.mode === "auto" ? (detected ? MODE_LABEL[detected] : "Auto") : MODE_LABEL[c.mode]}
+ <ChevronDown size={13} />
+ </button>
+ )}
+ >
+ {(close) => (
+ <>
+ <Option selected={c.mode === "auto"} label="Auto" sub={detected ? MODE_LABEL[detected] : undefined} icon={MODE_ICON.auto} onClick={() => (updateComposer({ mode: "auto" }), close())} />
+ <Option selected={c.mode === "generate"} label="Create" sub="New image from text" icon={MODE_ICON.generate} onClick={() => (updateComposer({ mode: "generate" }), close())} />
+ {hasImages && <Option selected={c.mode === "edit"} label="Edit" sub="Change the image" icon={MODE_ICON.edit} onClick={() => (updateComposer({ mode: "edit" }), close())} />}
+ {c.refs.length > 1 && <Option selected={c.mode === "multi_reference"} label="Combine" sub="Use several images" icon={MODE_ICON.multi_reference} onClick={() => (updateComposer({ mode: "multi_reference" }), close())} />}
+ {hasImages && (
+ <Option
+ selected={c.mode === "inpaint"}
+ label="Inpaint"
+ sub="Paint an area"
+ icon={MODE_ICON.inpaint}
+ onClick={() => {
+ close();
+ updateComposer({ mode: "auto" });
+ openEditor("inpaint");
+ }}
+ />
+ )}
+ {hasImages && (
+ <Option
+ selected={c.mode === "outpaint"}
+ label="Expand"
+ sub="Extend the borders"
+ icon={MODE_ICON.outpaint}
+ onClick={() => {
+ close();
+ updateComposer({ mode: "auto" });
+ openEditor("expand");
+ }}
+ />
+ )}
+ </>
+ )}
+ </Popover>
+
+ {c.resolution !== "custom" && !c.mask && !outPx && (!hasImages || modeShown === "generate" || modeShown === "edit" || modeShown === "multi_reference" || modeShown === "auto") && (
+ <Popover
+ trigger={(open, toggle) => (
+ <button className={`pill ${open ? "on" : ""}`} onClick={toggle} title="Aspect ratio">
+ {ASPECT_ICON[c.aspect] ?? <RectangleHorizontal size={15} />}
+ {c.aspect === "auto" ? (plan && (modeShown === "generate" || hasImages) ? plan.aspect_label : "Auto") : c.aspect}
+ <ChevronDown size={13} />
+ </button>
+ )}
+ >
+ {(close) => (
+ <>
+ {["auto", "1:1", "4:3", "3:4", "16:9", "9:16"].map((a) => (
+ <Option key={a} selected={c.aspect === a} label={a === "auto" ? "Auto" : a} sub={a === "auto" ? (hasImages && c.mode !== "generate" ? "Same as image 1" : "From the prompt") : undefined} icon={ASPECT_ICON[a]} onClick={() => (updateComposer({ aspect: a }), close())} />
+ ))}
+ <Option label="Custom size…" icon={<SlidersHorizontal size={15} />} onClick={() => (updateComposer({ resolution: "custom" }), close())} />
+ </>
+ )}
+ </Popover>
+ )}
+
+ <Popover
+ trigger={(open, toggle) => (
+ <button className={`pill ${open ? "on" : ""}`} onClick={toggle} title="Quality">
+ <Gauge size={15} />
+ {QUALITY.find((q) => q.value === c.quality)?.label}
+ <ChevronDown size={13} />
+ </button>
+ )}
+ >
+ {(close) =>
+ QUALITY.map((q) => <Option key={q.value} selected={c.quality === q.value} label={q.label} sub={q.sub} onClick={() => (updateComposer({ quality: q.value }), close())} />)
+ }
+ </Popover>
+
+ <Popover
+ placement="top-start"
+ className="panel"
+ trigger={(open, toggle) => (
+ <button
+ className={`icon-btn has-badge ${open ? "active" : ""}`}
+ onClick={toggle}
+ title={overrides.length ? `Advanced: overriding the preset (${overrides.join(", ")})` : "Advanced"}
+ aria-label={overrides.length ? `Advanced settings, ${overrides.length} overrides active` : "Advanced settings"}
+ >
+ <SlidersHorizontal size={17} />
+ {overrides.length > 0 && <span className="override-dot" />}
+ </button>
+ )}
+ >
+ {() => <AdvancedPanel plan={plan} />}
+ </Popover>
+
+ <span className="spacer" />
+ <span className="plan-hint" title={plan?.notes.join("\n") || plan?.mode_reason || ""}>
+ {hint}
+ </span>
+ <button className="send" title="Generate (Enter)" aria-label="Generate" disabled={!c.prompt.trim()} onClick={() => submitComposer()}>
+ <ArrowUp size={18} strokeWidth={2.4} />
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/ExpandEditor.tsx b/src/components/ExpandEditor.tsx
new file mode 100644
index 0000000..76a0758
--- /dev/null
+++ b/src/components/ExpandEditor.tsx
@@ -0,0 +1,183 @@
+import { ArrowDown, ArrowLeft, ArrowRight, ArrowUp, Check, RectangleHorizontal, RectangleVertical, RotateCcw, Square, X } from "lucide-react";
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
+import { urls } from "../lib/api";
+import { expansionPixels, expansionPreset } from "../lib/logic";
+import { focusPrompt, setState, updateComposer, useStore } from "../lib/store";
+import type { OutpaintSpec, Units } from "../lib/types";
+import { IconButton, Seg } from "./ui";
+
+type Side = "left" | "right" | "top" | "bottom";
+const MAX_FINAL = 16384;
+
+export function ExpandEditor() {
+ const ref0 = useStore((s) => s.composer.refs[0]);
+ const initial = useStore((s) => s.composer.outpaint);
+ const [spec, setSpec] = useState<OutpaintSpec>(initial ?? { left: 0, right: 0, top: 0, bottom: 0, units: "pixels" });
+ const stageRef = useRef<HTMLDivElement>(null);
+ const [stage, setStage] = useState({ w: 800, h: 600 });
+ const [frozenScale, setFrozenScale] = useState<number | null>(null);
+ const drag = useRef<{ side: Side; start: number; startVal: number } | null>(null);
+
+ useLayoutEffect(() => {
+ const el = stageRef.current;
+ if (!el) return;
+ const ro = new ResizeObserver(() => setStage({ w: el.clientWidth - 64, h: el.clientHeight - 48 }));
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, []);
+
+ useEffect(() => {
+ if (!ref0) setState({ overlay: null });
+ }, [ref0]);
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => e.key === "Escape" && setState({ overlay: null });
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, []);
+ if (!ref0) return null;
+
+ const W = ref0.width;
+ const H = ref0.height;
+ const px = expansionPixels(spec, W, H);
+ const finalW = W + px.left + px.right;
+ const finalH = H + px.top + px.bottom;
+ const fitScale = Math.min(stage.w / finalW, stage.h / finalH, 1.5);
+ const scale = frozenScale ?? fitScale;
+ const src = ref0.source.startsWith("gen:") ? urls.gen(ref0.source.slice(4)) : urls.input(ref0.source.slice(6));
+
+ const toUnits = (pixels: number, side: Side) => {
+ if (spec.units === "pixels") return Math.max(0, Math.round(pixels));
+ const base = side === "left" || side === "right" ? W : H;
+ return Math.max(0, Math.round((pixels / base) * 1000) / 10);
+ };
+ const setSide = (side: Side, v: number) => setSpec((s) => ({ ...s, [side]: Math.max(0, Number.isFinite(v) ? v : 0) }));
+
+ const onHandleDown = (side: Side) => (e: React.PointerEvent) => {
+ (e.target as HTMLElement).setPointerCapture(e.pointerId);
+ setFrozenScale(scale);
+ drag.current = { side, start: side === "left" || side === "right" ? e.clientX : e.clientY, startVal: px[side] };
+ };
+ const onHandleMove = (e: React.PointerEvent) => {
+ const d = drag.current;
+ if (!d) return;
+ const pos = d.side === "left" || d.side === "right" ? e.clientX : e.clientY;
+ const delta = (pos - d.start) / (frozenScale ?? scale);
+ const outward = d.side === "left" || d.side === "top" ? -delta : delta;
+ // Snap to 8 px for tidy numbers.
+ const pixels = Math.max(0, Math.round((d.startVal + outward) / 8) * 8);
+ setSide(d.side, toUnits(pixels, d.side));
+ };
+ const onHandleUp = () => {
+ drag.current = null;
+ setFrozenScale(null);
+ };
+
+ const preset = (k: Parameters<typeof expansionPreset>[0]) => {
+ const cur = { ...px, units: "pixels" as Units };
+ const next = expansionPreset(k, W, H, cur);
+ if (spec.units === "percent") {
+ setSpec({ left: toPct(next.left, W), right: toPct(next.right, W), top: toPct(next.top, H), bottom: toPct(next.bottom, H), units: "percent" });
+ } else setSpec(next);
+ };
+ const toPct = (p: number, b: number) => Math.round((p / b) * 1000) / 10;
+
+ const switchUnits = (u: Units) => {
+ if (u === spec.units) return;
+ if (u === "percent") setSpec({ left: toPct(px.left, W), right: toPct(px.right, W), top: toPct(px.top, H), bottom: toPct(px.bottom, H), units: "percent" });
+ else setSpec({ ...px, units: "pixels" });
+ };
+
+ const tooBig = finalW > MAX_FINAL || finalH > MAX_FINAL;
+ const any = px.left + px.right + px.top + px.bottom > 0;
+ const cw = finalW * scale;
+ const ch = finalH * scale;
+
+ return (
+ <div className="overlay">
+ <div className="overlay-head">
+ <h2>Expand the image</h2>
+ <span className="muted">
+ {W}×{H} → {finalW}×{finalH}
+ </span>
+ <span className="spacer" />
+ <IconButton title="Cancel (Esc)" onClick={() => setState({ overlay: null })}>
+ <X size={18} />
+ </IconButton>
+ </div>
+ <div className="editor-stage" ref={stageRef} onPointerMove={onHandleMove} onPointerUp={onHandleUp}>
+ <div className="expand-area" style={{ width: cw, height: ch }}>
+ <div className="expand-canvas" style={{ left: 0, top: 0, width: cw, height: ch }} />
+ <div className="expand-src" style={{ left: px.left * scale, top: px.top * scale, width: W * scale, height: H * scale }}>
+ <img src={src} alt="" draggable={false} />
+ </div>
+ <div className="handle h" style={{ left: 0, top: ch / 2 }} onPointerDown={onHandleDown("left")} title="Drag to extend left" />
+ <div className="handle h" style={{ left: cw, top: ch / 2 }} onPointerDown={onHandleDown("right")} title="Drag to extend right" />
+ <div className="handle v" style={{ left: cw / 2, top: 0 }} onPointerDown={onHandleDown("top")} title="Drag to extend up" />
+ <div className="handle v" style={{ left: cw / 2, top: ch }} onPointerDown={onHandleDown("bottom")} title="Drag to extend down" />
+ </div>
+ </div>
+ <div className="editor-tools" style={{ flexDirection: "column", gap: 10 }}>
+ <div style={{ display: "flex", gap: 6, flexWrap: "wrap", justifyContent: "center" }}>
+ <div className="group">
+ <IconButton title="Extend left" onClick={() => preset("left")}>
+ <ArrowLeft size={17} />
+ </IconButton>
+ <IconButton title="Extend right" onClick={() => preset("right")}>
+ <ArrowRight size={17} />
+ </IconButton>
+ <IconButton title="Extend up" onClick={() => preset("top")}>
+ <ArrowUp size={17} />
+ </IconButton>
+ <IconButton title="Extend down" onClick={() => preset("bottom")}>
+ <ArrowDown size={17} />
+ </IconButton>
+ </div>
+ <div className="group">
+ <IconButton title="Landscape 16:9" onClick={() => preset("landscape")}>
+ <RectangleHorizontal size={17} />
+ </IconButton>
+ <IconButton title="Portrait 9:16" onClick={() => preset("portrait")}>
+ <RectangleVertical size={17} />
+ </IconButton>
+ <IconButton title="Square" onClick={() => preset("square")}>
+ <Square size={17} />
+ </IconButton>
+ <IconButton title="Reset" onClick={() => setSpec({ left: 0, right: 0, top: 0, bottom: 0, units: spec.units })}>
+ <RotateCcw size={17} />
+ </IconButton>
+ </div>
+ </div>
+ <div className="expand-fields">
+ {(["left", "right", "top", "bottom"] as Side[]).map((s) => (
+ <label key={s}>
+ {s[0].toUpperCase() + s.slice(1)}
+ <input className="num-input" type="number" min={0} step={spec.units === "pixels" ? 8 : 1} value={spec[s]} onChange={(e) => setSide(s, Number(e.target.value))} />
+ </label>
+ ))}
+ <div style={{ width: 120 }}>
+ <Seg<Units>
+ value={spec.units}
+ options={[
+ { value: "pixels", label: "px" },
+ { value: "percent", label: "%" },
+ ]}
+ onChange={switchUnits}
+ />
+ </div>
+ <button
+ className="btn primary"
+ disabled={!any || tooBig}
+ title={tooBig ? `Max ${MAX_FINAL}px per side` : undefined}
+ onClick={() => {
+ updateComposer({ outpaint: spec, mask: null, mode: "auto" });
+ setState({ overlay: null });
+ focusPrompt();
+ }}
+ >
+ <Check size={15} /> Done
+ </button>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/Gallery.tsx b/src/components/Gallery.tsx
new file mode 100644
index 0000000..eba5632
--- /dev/null
+++ b/src/components/Gallery.tsx
@@ -0,0 +1,145 @@
+import { ArrowLeft, Heart, Loader2, Search, Trash2 } from "lucide-react";
+import { useCallback, useEffect, useRef, useState } from "react";
+import { api, urls } from "../lib/api";
+import { composerFromRecord, newKey } from "../lib/logic";
+import { native } from "../lib/native";
+import { getState, setState, toastError, useStore } from "../lib/store";
+import type { GenerationRecord } from "../lib/types";
+import { IconButton, Seg } from "./ui";
+
+const PAGE = 60;
+
+export function Gallery() {
+ const version = useStore((s) => s.galleryVersion);
+ const [q, setQ] = useState("");
+ const [favorites, setFavorites] = useState(false);
+ const [sort, setSort] = useState<"recent" | "oldest">("recent");
+ const [items, setItems] = useState<GenerationRecord[]>([]);
+ const [total, setTotal] = useState(0);
+ const [loading, setLoading] = useState(false);
+ const gridRef = useRef<HTMLDivElement>(null);
+
+ const load = useCallback(
+ async (offset: number) => {
+ setLoading(true);
+ try {
+ const r = await api.gallery({ q, favorites, sort, limit: PAGE, offset });
+ setItems((prev) => (offset === 0 ? r.items : [...prev, ...r.items]));
+ setTotal(r.total);
+ } catch (e) {
+ toastError(e);
+ } finally {
+ setLoading(false);
+ }
+ },
+ [q, favorites, sort],
+ );
+
+ useEffect(() => {
+ const t = window.setTimeout(() => load(0), q ? 250 : 0);
+ return () => window.clearTimeout(t);
+ }, [load, version, q]);
+
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => e.key === "Escape" && setState({ overlay: null });
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, []);
+
+ const reopen = (g: GenerationRecord) => {
+ const s = getState();
+ const existing = s.session.find((i) => i.gen?.id === g.id);
+ const item = existing ?? { key: newKey(), kind: "gen" as const, gen: g };
+ setState({
+ session: existing ? s.session : [...s.session, item],
+ selected: item.key,
+ composer: composerFromRecord(g, s.composer),
+ overlay: null,
+ });
+ };
+
+ const toggleFav = async (g: GenerationRecord) => {
+ try {
+ const r = await api.setFavorite(g.id, !g.favorite);
+ setItems((list) => (favorites && !r.favorite ? list.filter((x) => x.id !== g.id) : list.map((x) => (x.id === g.id ? r : x))));
+ } catch (e) {
+ toastError(e);
+ }
+ };
+
+ const remove = async (g: GenerationRecord) => {
+ try {
+ await api.deleteGeneration(g.id);
+ setItems((list) => list.filter((x) => x.id !== g.id));
+ setTotal((t) => t - 1);
+ setState((s) => ({ session: s.session.filter((i) => i.gen?.id !== g.id) }));
+ } catch (e) {
+ toastError(e);
+ }
+ };
+
+ return (
+ <div className="overlay">
+ <div className="overlay-head">
+ <IconButton title="Back (Esc)" onClick={() => setState({ overlay: null })}>
+ <ArrowLeft size={18} />
+ </IconButton>
+ <h2>Gallery</h2>
+ <span className="muted">{total}</span>
+ </div>
+ <div className="gallery-bar">
+ <label className="search">
+ <Search size={15} />
+ <input type="text" placeholder="Search prompts" value={q} onChange={(e) => setQ(e.target.value)} autoFocus />
+ </label>
+ <IconButton title={favorites ? "Show all" : "Favorites only"} active={favorites} onClick={() => setFavorites((f) => !f)}>
+ <Heart size={17} fill={favorites ? "currentColor" : "none"} />
+ </IconButton>
+ <div style={{ width: 170 }}>
+ <Seg
+ value={sort}
+ options={[
+ { value: "recent", label: "Recent" },
+ { value: "oldest", label: "Oldest" },
+ ]}
+ onChange={setSort}
+ />
+ </div>
+ </div>
+ <div
+ className="grid"
+ ref={gridRef}
+ onScroll={(e) => {
+ const el = e.currentTarget;
+ if (!loading && items.length < total && el.scrollTop + el.clientHeight > el.scrollHeight - 400) load(items.length);
+ }}
+ >
+ {items.map((g) => (
+ <div key={g.id} className="card" onClick={() => reopen(g)} title={g.prompt}>
+ <img src={urls.genThumb(g.id)} alt="" loading="lazy" draggable={false} />
+ <div className={`card-actions ${g.favorite ? "fav" : ""}`} onClick={(e) => e.stopPropagation()}>
+ <button title={g.favorite ? "Remove from favorites" : "Favorite"} onClick={() => toggleFav(g)}>
+ <Heart size={14} fill={g.favorite ? "currentColor" : "none"} />
+ </button>
+ <button
+ title="Delete"
+ onClick={async () => {
+ if (await native.confirm("Delete this image from the gallery and disk?", "Delete")) remove(g);
+ }}
+ >
+ <Trash2 size={14} />
+ </button>
+ </div>
+ <div className="card-meta">{g.prompt}</div>
+ </div>
+ ))}
+ {!loading && items.length === 0 && <div className="muted" style={{ gridColumn: "1/-1", textAlign: "center", padding: 48 }}>{q || favorites ? "Nothing matches." : "Your generations will appear here."}</div>}
+ {loading && (
+ <div style={{ gridColumn: "1/-1", display: "grid", placeItems: "center", padding: 24 }}>
+ <Loader2 className="spin" size={20} />
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/InpaintEditor.tsx b/src/components/InpaintEditor.tsx
new file mode 100644
index 0000000..b37afeb
--- /dev/null
+++ b/src/components/InpaintEditor.tsx
@@ -0,0 +1,307 @@
+import { Brush, Check, Contrast, Eraser, Redo2, Trash2, Undo2, X } from "lucide-react";
+import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
+import { api, urls } from "../lib/api";
+import { focusPrompt, getState, setState, toastError, updateComposer, useStore } from "../lib/store";
+import { IconButton } from "./ui";
+
+type Op =
+ | { kind: "stroke"; erase: boolean; size: number; points: [number, number][] }
+ | { kind: "invert" }
+ | { kind: "clear" };
+
+/** Mask canvas resolution cap (the backend resizes the mask to the source anyway). */
+const MAX_MASK_SIDE = 2048;
+
+export function InpaintEditor() {
+ const ref0 = useStore((s) => s.composer.refs[0]);
+ const existingMask = useStore((s) => s.composer.mask);
+ const [ops, setOps] = useState<Op[]>([]);
+ const [redo, setRedo] = useState<Op[]>([]);
+ const [erase, setErase] = useState(false);
+ const [brush, setBrush] = useState(48); // in screen px
+ const [feather, setFeather] = useState(8); // in mask px
+ const [busy, setBusy] = useState(false);
+ const [cursor, setCursor] = useState<{ x: number; y: number } | null>(null);
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ const imgRef = useRef<HTMLImageElement>(null);
+ const stageRef = useRef<HTMLDivElement>(null);
+ const current = useRef<Op | null>(null);
+ const [disp, setDisp] = useState({ w: 0, h: 0 });
+
+ const srcW = ref0?.width ?? 1;
+ const srcH = ref0?.height ?? 1;
+ const scale = Math.min(1, MAX_MASK_SIDE / Math.max(srcW, srcH));
+ const mw = Math.max(1, Math.round(srcW * scale));
+ const mh = Math.max(1, Math.round(srcH * scale));
+ const src = ref0 ? (ref0.source.startsWith("gen:") ? urls.gen(ref0.source.slice(4)) : urls.input(ref0.source.slice(6))) : "";
+
+ // Fit the image into the stage.
+ useLayoutEffect(() => {
+ const el = stageRef.current;
+ if (!el) return;
+ const ro = new ResizeObserver(() => {
+ const W = el.clientWidth - 48;
+ const H = el.clientHeight - 24;
+ const s = Math.min(W / srcW, H / srcH);
+ setDisp({ w: Math.floor(srcW * s), h: Math.floor(srcH * s) });
+ });
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, [srcW, srcH]);
+
+ // Load an existing mask for re-editing (as a base raster op).
+ const baseMask = useRef<HTMLImageElement | null>(null);
+ useEffect(() => {
+ if (!existingMask || !ref0 || existingMask.refKey !== ref0.key) return;
+ const img = new Image();
+ img.crossOrigin = "anonymous";
+ img.onload = () => {
+ baseMask.current = img;
+ redraw(ops);
+ };
+ img.src = urls.input(existingMask.inputId);
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, []);
+
+ /** Base mask (if re-editing) + every operation after the last "clear". */
+ const redraw = useCallback(
+ (list: Op[]) => {
+ const c = canvasRef.current;
+ if (!c) return;
+ const ctx = c.getContext("2d")!;
+ ctx.globalCompositeOperation = "source-over";
+ ctx.clearRect(0, 0, mw, mh);
+ const lastClear = list.map((o) => o.kind).lastIndexOf("clear");
+ if (baseMask.current && lastClear < 0) {
+ // Stored masks are grayscale (white = edit): convert luminance to alpha.
+ const tmp = document.createElement("canvas");
+ tmp.width = mw;
+ tmp.height = mh;
+ const t = tmp.getContext("2d")!;
+ t.drawImage(baseMask.current, 0, 0, mw, mh);
+ const d = t.getImageData(0, 0, mw, mh);
+ for (let i = 0; i < d.data.length; i += 4) {
+ const v = d.data[i];
+ d.data[i] = d.data[i + 1] = d.data[i + 2] = 255;
+ d.data[i + 3] = v;
+ }
+ t.putImageData(d, 0, 0);
+ ctx.drawImage(tmp, 0, 0);
+ }
+ for (const op of list.slice(lastClear + 1)) render2(ctx, op, mw, mh);
+ },
+ [mw, mh],
+ );
+
+ useEffect(() => redraw(ops), [ops, redraw]);
+
+ const toMask = (e: React.PointerEvent): [number, number] => {
+ const r = canvasRef.current!.getBoundingClientRect();
+ return [((e.clientX - r.left) / r.width) * mw, ((e.clientY - r.top) / r.height) * mh];
+ };
+ const maskBrush = () => (brush * mw) / Math.max(1, disp.w);
+
+ const onDown = (e: React.PointerEvent) => {
+ (e.target as HTMLElement).setPointerCapture(e.pointerId);
+ current.current = { kind: "stroke", erase: erase || e.button === 2, size: maskBrush(), points: [toMask(e)] };
+ const ctx = canvasRef.current!.getContext("2d")!;
+ render2(ctx, current.current, mw, mh);
+ };
+ const onMove = (e: React.PointerEvent) => {
+ const r = canvasRef.current!.getBoundingClientRect();
+ setCursor({ x: e.clientX - r.left, y: e.clientY - r.top });
+ const op = current.current;
+ if (!op || op.kind !== "stroke") return;
+ op.points.push(toMask(e));
+ const ctx = canvasRef.current!.getContext("2d")!;
+ render2(ctx, { ...op, points: op.points.slice(-2) }, mw, mh);
+ };
+ const onUp = () => {
+ if (current.current) {
+ const op = current.current;
+ current.current = null;
+ setOps((o) => [...o, op]);
+ setRedo([]);
+ }
+ };
+
+ const undo = () => {
+ setOps((o) => {
+ if (!o.length) return o;
+ setRedo((r) => [...r, o[o.length - 1]]);
+ return o.slice(0, -1);
+ });
+ };
+ const redoOp = () => {
+ setRedo((r) => {
+ if (!r.length) return r;
+ setOps((o) => [...o, r[r.length - 1]]);
+ return r.slice(0, -1);
+ });
+ };
+ const push = (op: Op) => {
+ setOps((o) => [...o, op]);
+ setRedo([]);
+ };
+
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "z") {
+ e.preventDefault();
+ e.shiftKey ? redoOp() : undo();
+ } else if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "y") {
+ e.preventDefault();
+ redoOp();
+ } else if (e.key === "Escape") setState({ overlay: null });
+ else if (e.key === "[") setBrush((b) => Math.max(4, b - 8));
+ else if (e.key === "]") setBrush((b) => Math.min(400, b + 8));
+ else if (e.key.toLowerCase() === "e") setErase((v) => !v);
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ });
+
+ const done = async () => {
+ const c = canvasRef.current;
+ if (!c || !ref0) return;
+ // Export: white = edit on black, feathered.
+ const out = document.createElement("canvas");
+ out.width = mw;
+ out.height = mh;
+ const ctx = out.getContext("2d")!;
+ ctx.fillStyle = "#000";
+ ctx.fillRect(0, 0, mw, mh);
+ if (feather > 0) ctx.filter = `blur(${feather / 2}px)`;
+ ctx.drawImage(c, 0, 0);
+ ctx.filter = "none";
+ // Detect empty mask.
+ const data = c.getContext("2d")!.getImageData(0, 0, mw, mh).data;
+ let any = false;
+ for (let i = 3; i < data.length; i += 16) {
+ if (data[i] > 16) {
+ any = true;
+ break;
+ }
+ }
+ if (!any) {
+ updateComposer({ mask: null });
+ setState({ overlay: null });
+ return;
+ }
+ setBusy(true);
+ try {
+ const blob: Blob = await new Promise((res, rej) => out.toBlob((b) => (b ? res(b) : rej(new Error("export failed"))), "image/png"));
+ const rec = await api.upload(blob, "mask.png");
+ const refKey = getState().composer.refs[0]?.key;
+ if (refKey) updateComposer({ mask: { inputId: rec.id, refKey }, outpaint: null, mode: "auto" });
+ setState({ overlay: null });
+ focusPrompt();
+ } catch (e) {
+ toastError(e);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ useEffect(() => {
+ if (!ref0) setState({ overlay: null });
+ }, [ref0]);
+ if (!ref0) return null;
+
+ return (
+ <div className="overlay">
+ <div className="overlay-head">
+ <h2>Paint the area to change</h2>
+ <span className="spacer" />
+ <IconButton title="Cancel (Esc)" onClick={() => setState({ overlay: null })}>
+ <X size={18} />
+ </IconButton>
+ </div>
+ <div className="editor-stage" ref={stageRef}>
+ <div className="mask-wrap" style={{ width: disp.w, height: disp.h }} onContextMenu={(e) => e.preventDefault()}>
+ <img ref={imgRef} src={src} alt="" draggable={false} style={{ width: disp.w, height: disp.h }} />
+ <canvas
+ ref={canvasRef}
+ width={mw}
+ height={mh}
+ onPointerDown={onDown}
+ onPointerMove={onMove}
+ onPointerUp={onUp}
+ onPointerCancel={onUp}
+ onPointerLeave={() => setCursor(null)}
+ />
+ {cursor && <div className="brush-cursor" style={{ left: cursor.x, top: cursor.y, width: brush, height: brush }} />}
+ </div>
+ </div>
+ <div className="editor-tools">
+ <div className="group">
+ <IconButton title="Brush" active={!erase} onClick={() => setErase(false)}>
+ <Brush size={17} />
+ </IconButton>
+ <IconButton title="Eraser (E)" active={erase} onClick={() => setErase(true)}>
+ <Eraser size={17} />
+ </IconButton>
+ </div>
+ <div className="group">
+ <label className="slider" title="Brush size ( [ and ] )">
+ Size
+ <input type="range" min={4} max={400} value={brush} onChange={(e) => setBrush(Number(e.target.value))} />
+ </label>
+ <label className="slider" title="Soft edge">
+ Feather
+ <input type="range" min={0} max={64} value={feather} onChange={(e) => setFeather(Number(e.target.value))} />
+ </label>
+ </div>
+ <div className="group">
+ <IconButton title="Undo (Ctrl+Z)" onClick={undo} disabled={!ops.length}>
+ <Undo2 size={17} />
+ </IconButton>
+ <IconButton title="Redo (Ctrl+Y)" onClick={redoOp} disabled={!redo.length}>
+ <Redo2 size={17} />
+ </IconButton>
+ <IconButton title="Invert mask" onClick={() => push({ kind: "invert" })}>
+ <Contrast size={17} />
+ </IconButton>
+ <IconButton title="Clear mask" onClick={() => push({ kind: "clear" })}>
+ <Trash2 size={17} />
+ </IconButton>
+ </div>
+ <button className="btn primary" onClick={done} disabled={busy}>
+ <Check size={15} /> Done
+ </button>
+ </div>
+ </div>
+ );
+}
+
+/** Draws a single operation incrementally (no clearing). */
+function render2(ctx: CanvasRenderingContext2D, op: Op, w: number, h: number) {
+ if (op.kind === "clear") {
+ ctx.clearRect(0, 0, w, h);
+ return;
+ }
+ if (op.kind === "invert") {
+ ctx.globalCompositeOperation = "xor";
+ ctx.fillStyle = "#fff";
+ ctx.fillRect(0, 0, w, h);
+ ctx.globalCompositeOperation = "source-over";
+ return;
+ }
+ ctx.globalCompositeOperation = op.erase ? "destination-out" : "source-over";
+ ctx.strokeStyle = "#fff";
+ ctx.fillStyle = "#fff";
+ ctx.lineWidth = op.size;
+ ctx.lineCap = "round";
+ ctx.lineJoin = "round";
+ const p = op.points;
+ ctx.beginPath();
+ if (p.length === 1) {
+ ctx.arc(p[0][0], p[0][1], op.size / 2, 0, Math.PI * 2);
+ ctx.fill();
+ } else {
+ ctx.moveTo(p[0][0], p[0][1]);
+ for (let i = 1; i < p.length; i++) ctx.lineTo(p[i][0], p[i][1]);
+ ctx.stroke();
+ }
+ ctx.globalCompositeOperation = "source-over";
+}
diff --git a/src/components/Settings.tsx b/src/components/Settings.tsx
new file mode 100644
index 0000000..e1bbb2f
--- /dev/null
+++ b/src/components/Settings.tsx
@@ -0,0 +1,317 @@
+import { Activity, Copy, Cpu, FolderOpen, HardDrive, RefreshCw, RotateCcw, Settings2, X } from "lucide-react";
+import { useEffect, useState } from "react";
+import { writeText } from "@tauri-apps/plugin-clipboard-manager";
+import { api } from "../lib/api";
+import { native } from "../lib/native";
+import { refreshStatus, setState, toastError, toastInfo } from "../lib/store";
+import { UPSCALERS } from "../lib/logic";
+import type { AppConfig, Check, ModelProfile, RefineMode, SetupReport, TextEncoderPlacement } from "../lib/types";
+import { IconButton, Seg, Switch } from "./ui";
+
+type Tab = "general" | "models" | "performance" | "diagnostics";
+
+export function defaultProfilePaths(dir: string, p: ModelProfile): ModelProfile {
+ const m = `${dir.replace(/[\\/]+$/, "")}\\models\\qwen21\\`;
+ return {
+ ...p,
+ diffusionModel: m + "qwen-image-2.1-UC-Q4_K_M.gguf",
+ vae: m + "qwen_image_2.1_vae_bf16.safetensors",
+ textEncoder: m + "Qwen3VL-8B-Instruct-Q4_K_M.gguf",
+ visionProjector: m + "mmproj-Qwen3VL-8B-Instruct-F16.gguf",
+ };
+}
+
+function PathField(props: { label: string; value: string; onChange: (v: string) => void; folder?: boolean; extensions?: string[] }) {
+ return (
+ <label className="field">
+ <span>{props.label}</span>
+ <div className="path-row">
+ <input className="input" type="text" value={props.value} onChange={(e) => props.onChange(e.target.value)} spellCheck={false} />
+ <button
+ className="btn"
+ onClick={async () => {
+ const p = props.folder ? await native.pickFolder(props.value) : await native.pickFile(props.extensions ?? ["gguf", "safetensors"], props.value);
+ if (p) props.onChange(p);
+ }}
+ >
+ Browse
+ </button>
+ </div>
+ </label>
+ );
+}
+
+function Diagnostics() {
+ const [text, setText] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const load = async () => {
+ setText(null);
+ try {
+ setText((await api.diagnostics()).text);
+ } catch (e) {
+ toastError(e);
+ setText("");
+ }
+ };
+ useEffect(() => {
+ load();
+ }, []);
+ return (
+ <>
+ <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
+ <button className="btn" disabled={!text} onClick={async () => (await writeText(text ?? ""), toastInfo("Diagnostics copied"))}>
+ <Copy size={14} /> Copy
+ </button>
+ <button className="btn" onClick={load}>
+ <RefreshCw size={14} /> Refresh
+ </button>
+ <button
+ className="btn"
+ disabled={busy}
+ onClick={async () => {
+ setBusy(true);
+ try {
+ await api.restartBackend();
+ toastInfo("Inference server restarted");
+ load();
+ } catch (e) {
+ toastError(e);
+ } finally {
+ setBusy(false);
+ refreshStatus();
+ }
+ }}
+ >
+ <RotateCcw size={14} /> {busy ? "Restarting…" : "Restart server"}
+ </button>
+ <button className="btn" onClick={async () => native.openFolder(`${await native.dataFolder()}\\logs`).catch(toastError)}>
+ <FolderOpen size={14} /> Logs
+ </button>
+ </div>
+ <pre className="diag">{text ?? "Collecting…"}</pre>
+ </>
+ );
+}
+
+export function Settings() {
+ const [tab, setTab] = useState<Tab>("general");
+ const [cfg, setCfg] = useState<AppConfig | null>(null);
+ const [devices, setDevices] = useState<[string, string][]>([]);
+ const [upscaler, setUpscaler] = useState<Check | null>(null);
+ const [dirty, setDirty] = useState(false);
+
+ useEffect(() => {
+ api.config().then(setCfg, toastError);
+ api.setup().then(
+ (r: SetupReport) => {
+ setDevices(r.devices);
+ setUpscaler(r.checks.find((c) => c.id === "upscaler") ?? null);
+ },
+ () => {},
+ );
+ }, []);
+
+ const close = () => setState({ overlay: null });
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => e.key === "Escape" && close();
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, []);
+
+ if (!cfg) return null;
+ const profile = cfg.profiles.find((p) => p.id === cfg.activeProfile) ?? cfg.profiles[0];
+ const set = (patch: Partial<AppConfig>) => {
+ setCfg({ ...cfg, ...patch });
+ setDirty(true);
+ };
+ const setProfile = (patch: Partial<ModelProfile>) => set({ profiles: cfg.profiles.map((p) => (p.id === profile.id ? { ...p, ...patch } : p)) });
+
+ const save = async () => {
+ try {
+ const r = await api.saveConfig(cfg);
+ setDirty(false);
+ api.setup().then((s: SetupReport) => setUpscaler(s.checks.find((c) => c.id === "upscaler") ?? null), () => {});
+ toastInfo(r.backend_restart_needed ? "Saved. The model reloads with the new settings on the next generation." : "Saved");
+ refreshStatus();
+ } catch (e) {
+ toastError(e);
+ }
+ };
+
+ const nav: [Tab, string, React.ReactNode][] = [
+ ["general", "General", <Settings2 size={16} key="g" />],
+ ["models", "Models", <HardDrive size={16} key="m" />],
+ ["performance", "Performance", <Cpu size={16} key="p" />],
+ ["diagnostics", "Diagnostics", <Activity size={16} key="d" />],
+ ];
+
+ return (
+ <div className="modal-scrim" onMouseDown={(e) => e.target === e.currentTarget && close()}>
+ <div className="modal" role="dialog" aria-label="Settings">
+ <div className="modal-nav">
+ {nav.map(([t, label, icon]) => (
+ <button key={t} className={tab === t ? "on" : ""} onClick={() => setTab(t)}>
+ {icon} {label}
+ </button>
+ ))}
+ <span style={{ flex: 1 }} />
+ {tab !== "diagnostics" && (
+ <button className="btn primary" style={{ justifyContent: "center" }} disabled={!dirty} onClick={save}>
+ Save
+ </button>
+ )}
+ </div>
+ <div className="modal-body">
+ <div style={{ display: "flex", alignItems: "center" }}>
+ <h3 style={{ flex: 1 }}>{nav.find((n) => n[0] === tab)?.[1]}</h3>
+ <IconButton title="Close" onClick={close}>
+ <X size={18} />
+ </IconButton>
+ </div>
+
+ {tab === "general" && (
+ <>
+ <PathField label="Save images to" value={cfg.outputDir} folder onChange={(v) => set({ outputDir: v })} />
+ <div className="field-row">
+ <span>Keep inference server running after closing the app</span>
+ <Switch on={cfg.keepServerRunning} onChange={(v) => set({ keepServerRunning: v })} />
+ </div>
+ <span className="muted" style={{ marginTop: -10 }}>Keeps the model in VRAM so the next start is instant.</span>
+ <label className="field-row">
+ <span>Unload the model after idle minutes (app closed)</span>
+ <input className="input" type="number" min={0} max={1440} style={{ width: 90 }} value={cfg.idleUnloadMinutes} onChange={(e) => set({ idleUnloadMinutes: Math.max(0, Number(e.target.value) || 0) })} />
+ </label>
+ <span className="muted" style={{ marginTop: -10 }}>Applies to MCP and API use without the desktop window. 0 keeps it loaded.</span>
+ </>
+ )}
+
+ {tab === "models" && (
+ <>
+ <PathField label="stable-diffusion.cpp folder" value={cfg.sdcppDir} folder onChange={(v) => set({ sdcppDir: v })} />
+ <button className="btn" style={{ alignSelf: "flex-start" }} onClick={() => setProfile(defaultProfilePaths(cfg.sdcppDir, profile))}>
+ Use default model paths in this folder
+ </button>
+ <span className="muted">Profile: {profile.displayName}</span>
+ <PathField label="Diffusion model" value={profile.diffusionModel} onChange={(v) => setProfile({ diffusionModel: v })} />
+ <PathField label="VAE" value={profile.vae} onChange={(v) => setProfile({ vae: v })} />
+ <PathField label="Text encoder (Qwen3-VL)" value={profile.textEncoder} onChange={(v) => setProfile({ textEncoder: v })} />
+ <PathField label="Vision projector (mmproj)" value={profile.visionProjector ?? ""} onChange={(v) => setProfile({ visionProjector: v || null })} />
+ <PathField label="Upscalers folder (ESRGAN)" value={cfg.upscalersDir ?? `${cfg.sdcppDir.replace(/[\\/]+$/, "")}\\models\\upscalers`} folder onChange={(v) => set({ upscalersDir: v || null })} />
+ <label className="field-row">
+ <span>Upscaler model (ESRGAN)</span>
+ <select className="select" value={cfg.upscalerModel} onChange={(e) => set({ upscalerModel: e.target.value })}>
+ {UPSCALERS.map(([name, label], i) => (
+ <option key={name} value={name}>
+ {label}
+ {i === 0 ? " (default)" : ""}
+ </option>
+ ))}
+ {!UPSCALERS.some(([n]) => n === cfg.upscalerModel) && <option value={cfg.upscalerModel}>{cfg.upscalerModel}</option>}
+ </select>
+ </label>
+ <span className="muted">Enlarges every result from the model's output to its final size, and runs the Upscale button.</span>
+ {upscaler && <span className="muted">{upscaler.ok ? `Found: ${upscaler.detail}` : upscaler.detail}</span>}
+ </>
+ )}
+
+ {tab === "performance" && (
+ <>
+ <label className="field-row">
+ <span>GPU device</span>
+ <select className="select" value={cfg.device} onChange={(e) => set({ device: e.target.value })}>
+ {(devices.length ? devices : [[cfg.device, ""] as [string, string]]).map(([n, d]) => (
+ <option key={n} value={n.toLowerCase()}>
+ {n}
+ {d ? ` — ${d}` : ""}
+ </option>
+ ))}
+ </select>
+ </label>
+ <div className="field">
+ <span>Text encoder weights</span>
+ <Seg<TextEncoderPlacement>
+ value={cfg.textEncoderPlacement}
+ options={[
+ { value: "ram", label: "RAM" },
+ { value: "gpu", label: "GPU" },
+ { value: "cpu", label: "CPU" },
+ { value: "auto", label: "Auto" },
+ ]}
+ onChange={(v) => set({ textEncoderPlacement: v })}
+ />
+ <span className="muted">
+ RAM (recommended): weights in system memory, computed on the GPU. CPU uses the least VRAM but makes image editing several times slower.
+ </span>
+ </div>
+ <label className="field-row">
+ <span>VRAM reserve (GiB)</span>
+ <input className="input" type="number" min={0} max={16} step={0.5} style={{ width: 90 }} value={cfg.vramReserveGib} onChange={(e) => set({ vramReserveGib: Math.max(0, Number(e.target.value) || 0) })} />
+ </label>
+ <div className="field-row">
+ <span>Flash attention</span>
+ <Switch on={cfg.flashAttention} onChange={(v) => set({ flashAttention: v })} />
+ </div>
+ <div className="field-row">
+ <span>SageAttention (faster sampling)</span>
+ <Switch on={cfg.sageAttention} onChange={(v) => set({ sageAttention: v })} />
+ </div>
+ <label className="field-row">
+ <span>VAE tile size (px, 0 = off)</span>
+ <input className="input" type="number" min={0} max={2048} step={128} style={{ width: 90 }} value={cfg.vaeTileSize} onChange={(e) => set({ vaeTileSize: Math.max(0, Math.round(Number(e.target.value) || 0)) })} />
+ </label>
+ <div className="field">
+ <span>Edit prefix cache</span>
+ <Seg<string>
+ value={cfg.prefixCacheType}
+ options={[
+ { value: "q8_0", label: "8-bit" },
+ { value: "f16", label: "FP16" },
+ { value: "auto", label: "Auto" },
+ { value: "off", label: "Off" },
+ ]}
+ onChange={(v) => set({ prefixCacheType: v })}
+ />
+ <span className="muted">
+ Reuses the reference image and prompt across steps so each step only computes the new image. 8-bit (recommended) fits a 2 MP edit on 16 GB; FP16 is more exact but needs twice the memory; Auto uses FP32 when SageAttention is on and usually does not fit.
+ </span>
+ </div>
+ <div className="field-row">
+ <span>Load all weights at startup</span>
+ <Switch on={cfg.eagerLoad} onChange={(v) => set({ eagerLoad: v })} />
+ </div>
+ <div className="field">
+ <span>Detailed upscale</span>
+ <Seg<RefineMode>
+ value={cfg.refineMode === "best" ? "best" : "fast"}
+ options={[
+ { value: "fast", label: "Fast" },
+ { value: "best", label: "Best" },
+ ]}
+ onChange={(v) => set({ refineMode: v })}
+ />
+ <span className="muted">
+ Only for Upscale → Detailed, which re-renders fine detail at about 2K before the upscaler model. Fast: 6 steps with caching. Best: 8 steps, no cache. Generation always renders in one pass and is then enlarged with the upscaler model.
+ </span>
+ </div>
+ <label className="field-row">
+ <span>ESRGAN tile size (px, 0 = default 128)</span>
+ <input className="input" type="number" min={0} max={1024} step={64} style={{ width: 90 }} value={cfg.upscaleTileSize} onChange={(e) => set({ upscaleTileSize: Math.max(0, Math.round(Number(e.target.value) || 0)) })} />
+ </label>
+ <label className="field-row">
+ <span>Inference server port</span>
+ <input className="input" type="number" min={1024} max={65535} style={{ width: 100 }} value={cfg.serverPort} onChange={(e) => set({ serverPort: Number(e.target.value) || cfg.serverPort })} />
+ </label>
+ <label className="field">
+ <span>Extra server arguments</span>
+ <input className="input" type="text" spellCheck={false} placeholder="e.g. --vae-conv-direct" value={cfg.extraServerArgs.join(" ")} onChange={(e) => set({ extraServerArgs: e.target.value.split(/\s+/).filter(Boolean) })} />
+ </label>
+ <span className="muted">The server always listens on 127.0.0.1 only.</span>
+ </>
+ )}
+
+ {tab === "diagnostics" && <Diagnostics />}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/Setup.tsx b/src/components/Setup.tsx
new file mode 100644
index 0000000..d502152
--- /dev/null
+++ b/src/components/Setup.tsx
@@ -0,0 +1,96 @@
+import { Check, CircleAlert, FolderOpen, Info, Loader2, RefreshCw, Settings2 } from "lucide-react";
+import { useEffect, useState } from "react";
+import { api } from "../lib/api";
+import { native } from "../lib/native";
+import { refreshStatus, setState, toastError } from "../lib/store";
+import type { SetupReport } from "../lib/types";
+import { defaultProfilePaths } from "./Settings";
+
+/** First launch: verify folder, executable, the four model files and CUDA. */
+export function Setup() {
+ const [report, setReport] = useState<SetupReport | null>(null);
+ const [checking, setChecking] = useState(false);
+
+ const run = async () => {
+ setChecking(true);
+ try {
+ setReport(await api.setup());
+ } catch (e) {
+ toastError(e);
+ } finally {
+ setChecking(false);
+ }
+ };
+ useEffect(() => {
+ run();
+ }, []);
+
+ const chooseFolder = async () => {
+ const dir = await native.pickFolder("C:\\AI\\sdcpp");
+ if (!dir) return;
+ try {
+ const cfg = await api.config();
+ const profiles = cfg.profiles.map((p) => (p.id === cfg.activeProfile ? defaultProfilePaths(dir, p) : p));
+ await api.saveConfig({ ...cfg, sdcppDir: dir, profiles });
+ run();
+ } catch (e) {
+ toastError(e);
+ }
+ };
+
+ const start = async () => {
+ try {
+ const cfg = await api.config();
+ await api.saveConfig({ ...cfg, setupComplete: true });
+ setState({ needsSetup: false });
+ // Load the model in the background; the status indicator shows progress.
+ api.startBackend().then(refreshStatus, toastError);
+ refreshStatus();
+ } catch (e) {
+ toastError(e);
+ }
+ };
+
+ return (
+ <div className="setup">
+ <div className="setup-inner">
+ <h1>Welcome</h1>
+ <p className="muted" style={{ fontSize: 14, margin: 0 }}>
+ Qwen Local Studio runs entirely on this PC using stable-diffusion.cpp. Checking your installation…
+ </p>
+ <div className="check-list">
+ {!report && (
+ <div className="check-item">
+ <Loader2 className="spin" size={18} /> <span className="what">Checking</span>
+ </div>
+ )}
+ {report?.checks.map((c, i) => (
+ <div className="check-item" key={i}>
+ {c.ok ? <Check size={18} /> : c.id === "upscaler" ? <Info size={18} /> : <CircleAlert size={18} />}
+ <div className="what">
+ <div>{c.label}</div>
+ <div className="detail">{c.detail}</div>
+ </div>
+ </div>
+ ))}
+ {report?.backend_version && <div className="muted" style={{ paddingTop: 8 }}>stable-diffusion.cpp {report.backend_version}</div>}
+ </div>
+ <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
+ <button className="btn primary" disabled={!report?.ready} onClick={start}>
+ Start
+ </button>
+ <button className="btn" onClick={chooseFolder}>
+ <FolderOpen size={15} /> Choose stable-diffusion.cpp folder
+ </button>
+ <button className="btn" onClick={() => setState({ overlay: "settings" })}>
+ <Settings2 size={15} /> Settings
+ </button>
+ <button className="btn" onClick={run} disabled={checking}>
+ <RefreshCw size={15} /> Check again
+ </button>
+ </div>
+ {report && !report.ready && <p className="muted">Fix the items marked above, then check again. Model files are not downloaded by this app.</p>}
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/Stage.tsx b/src/components/Stage.tsx
new file mode 100644
index 0000000..843b8e0
--- /dev/null
+++ b/src/components/Stage.tsx
@@ -0,0 +1,405 @@
+import {
+ Brush, Copy, Download, Expand, FolderOpen, Heart, ImagePlus, Info, Loader2, MousePointerClick, Pencil, RotateCcw, Shuffle, Square, X, ClipboardPaste, ZoomIn,
+} from "lucide-react";
+import { Fragment, useState } from "react";
+import { api, urls } from "../lib/api";
+import {
+ compareBase, formatDuration, jobFraction, jobLabel, MAX_UPSCALE_AREA, MAX_UPSCALE_SIDE, MODE_LABEL, pipelineSummary, remainingSeconds, sizeForWidth, upscaleRequest, upscalerLabel, upscaleTargets,
+ variationRequest,
+} from "../lib/logic";
+import { native } from "../lib/native";
+import {
+ addAsReference, cancelJob, editItem, openEditorFor, removeSessionItem, selectedItem, setState, submitRequest, toastError, toastInfo, useStore, type SessionItem,
+} from "../lib/store";
+import type { GenerationRecord, JobView, Size, UpscaleMethod } from "../lib/types";
+import { CompareBar, CompareFrame } from "./Compare";
+import { IconButton, Popover, Seg, useFit } from "./ui";
+import { FullscreenButton, ZoomImage } from "./Viewer";
+
+function Empty() {
+ return (
+ <div className="empty">
+ <h1>What should we make?</h1>
+ <p>Describe an image, or bring one to edit.</p>
+ <div className="hint">
+ <span>
+ <MousePointerClick size={14} /> Drop images here
+ </span>
+ <span>
+ <ClipboardPaste size={14} /> Paste with Ctrl+V
+ </span>
+ </div>
+ </div>
+ );
+}
+
+function Pending({ job, aspect }: { job: JobView; aspect: number }) {
+ const { ref, box } = useFit(aspect);
+ const frac = jobFraction(job);
+ const remain = remainingSeconds(job);
+ const canCancel = !["done", "failed", "cancelled"].includes(job.status);
+ return (
+ <div className="stage-frame" ref={ref}>
+ <div className="pending" style={{ width: box.w, height: box.h }}>
+ <div className="pending-info">
+ <span style={{ color: "var(--text)", fontWeight: 500 }}>{jobLabel(job)}</span>
+ <div className={`progress ${frac === null ? "indeterminate" : ""}`}>
+ <i style={frac !== null ? { width: `${Math.round(frac * 100)}%` } : undefined} />
+ </div>
+ <span className="muted">
+ {job.plan ? `${MODE_LABEL[job.plan.mode]} · ${job.plan.output.width}×${job.plan.output.height}` : ""}
+ {remain !== null ? ` · ${formatDuration(remain)} left` : ""}
+ </span>
+ {job.notes.length > 0 && <span className="notes">{job.notes.join(" ")}</span>}
+ {canCancel && (
+ <button className="btn" onClick={() => cancelJob(job.id)} title="Cancel">
+ <Square size={13} /> Stop
+ </button>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function Failed({ job, item }: { job: JobView; item: SessionItem }) {
+ const [details, setDetails] = useState(false);
+ const req = item.request;
+ return (
+ <div className="stage-frame">
+ <div className="failed">
+ <strong>{job.status === "cancelled" ? "Cancelled" : job.error?.message ?? "Generation failed"}</strong>
+ {job.error?.suggestion && <span>{job.error.suggestion}</span>}
+ <div style={{ display: "flex", gap: 8 }}>
+ {req && (
+ <button className="btn" onClick={() => (removeSessionItem(item.key), submitRequest(req))}>
+ <RotateCcw size={14} /> Try again
+ </button>
+ )}
+ <button className="btn" onClick={() => removeSessionItem(item.key)}>
+ <X size={14} /> Dismiss
+ </button>
+ {job.error?.detail && (
+ <button className="btn" onClick={() => setDetails((d) => !d)}>
+ <Info size={14} /> Details
+ </button>
+ )}
+ </div>
+ {details && <pre className="diag" style={{ maxHeight: 220, textAlign: "left", width: "100%" }}>{job.error?.detail}</pre>}
+ </div>
+ </div>
+ );
+}
+
+function InfoPanel({ g }: { g: GenerationRecord }) {
+ const pipeline = pipelineSummary(g);
+ const rows: [string, string][] = [
+ ["Mode", MODE_LABEL[g.mode]],
+ ["Size", `${g.width}×${g.height}${g.working_width !== g.width || g.working_height !== g.height ? ` (worked at ${g.working_width}×${g.working_height})` : ""}`],
+ ...(pipeline ? ([["Pipeline", pipeline]] as [string, string][]) : []),
+ ["Seed", String(g.seed)],
+ ["Steps", String(g.steps)],
+ ["CFG", String(g.cfg)],
+ ["Sampler", `${g.sampler}${g.scheduler ? ` / ${g.scheduler}` : ""}`],
+ ...(g.strength != null ? ([["Strength", String(g.strength)]] as [string, string][]) : []),
+ ["References", String(g.references.length)],
+ ["Model", g.model],
+ ["Time", formatDuration(g.duration_ms / 1000)],
+ ["Created", new Date(g.created_at).toLocaleString()],
+ ];
+ return (
+ <div style={{ width: 340, padding: 8, display: "flex", flexDirection: "column", gap: 6 }}>
+ <div style={{ fontSize: 13, userSelect: "text", maxHeight: 120, overflow: "auto" }}>{g.prompt}</div>
+ {g.negative_prompt && <div className="muted">Negative: {g.negative_prompt}</div>}
+ <div style={{ display: "grid", gridTemplateColumns: "auto 1fr", gap: "4px 12px", fontSize: 12 }}>
+ {rows.map(([k, v]) => (
+ <Fragment key={k}>
+ <span className="muted">{k}</span>
+ <span style={{ userSelect: "text", wordBreak: "break-all" }}>{v}</span>
+ </Fragment>
+ ))}
+ </div>
+ {g.notes.length > 0 && <div className="muted">{g.notes.join(" ")}</div>}
+ <div className="muted" style={{ wordBreak: "break-all", userSelect: "text" }}>{g.file_path}</div>
+ </div>
+ );
+}
+
+/** Upscale menu: Quick (upscaler model only) or Detailed (refine at ~2K, then the upscaler model). */
+function UpscaleMenu(props: { source: string; size: Size; original?: Size | null; parentId?: string | null; close: () => void }) {
+ const { width: w, height: h } = props.size;
+ const [method, setMethod] = useState<UpscaleMethod>("quick");
+ const up = useStore((s) => s.status?.upscaler);
+ const via = up?.available ? upscalerLabel(up.model) : "Lanczos";
+ const [customW, setCustomW] = useState(Math.min(MAX_UPSCALE_SIDE, w * 2));
+ const targets = upscaleTargets(w, h, props.original);
+ const custom = sizeForWidth(w, h, customW);
+ const customOk = custom.width > w && custom.width <= MAX_UPSCALE_SIDE && custom.height <= MAX_UPSCALE_SIDE && custom.width * custom.height <= MAX_UPSCALE_AREA;
+ const go = (t: Size) => {
+ submitRequest(upscaleRequest(props.source, t, method, props.parentId));
+ props.close();
+ };
+ return (
+ <div style={{ width: 300, padding: 8, display: "flex", flexDirection: "column", gap: 10 }}>
+ <Seg<UpscaleMethod>
+ value={method}
+ options={[
+ { value: "quick", label: "Quick" },
+ { value: "detailed", label: "Detailed" },
+ ]}
+ onChange={setMethod}
+ />
+ <span className="muted">
+ {method === "quick" ? `${via} only: a few seconds, adds no new content.` : `Re-renders fine detail at about 2K (low denoise), then ${via}. About a minute.`}
+ </span>
+ {targets.map((t) => (
+ <button key={t.key} className="btn" onClick={() => go(t)}>
+ {t.label} · {t.width}×{t.height}
+ </button>
+ ))}
+ <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
+ <input
+ className="input"
+ type="number"
+ min={w + 1}
+ max={MAX_UPSCALE_SIDE}
+ style={{ width: 90 }}
+ value={customW}
+ onChange={(e) => setCustomW(Math.max(64, Math.min(MAX_UPSCALE_SIDE, Math.round(Number(e.target.value) || 0))))}
+ aria-label="Custom width"
+ />
+ <span className="muted" style={{ flex: 1 }}>
+ × {custom.height}
+ </span>
+ <button className="btn" disabled={!customOk} onClick={() => go(custom)}>
+ Upscale
+ </button>
+ </div>
+ </div>
+ );
+}
+
+function UpscaleButton(props: { source: string; size: Size; original?: Size | null; parentId?: string | null }) {
+ return (
+ <Popover
+ placement="top-start"
+ trigger={(open, toggle) => (
+ <IconButton title="Upscale" onClick={toggle} active={open}>
+ <ZoomIn size={17} />
+ </IconButton>
+ )}
+ >
+ {(close) => <UpscaleMenu {...props} close={close} />}
+ </Popover>
+ );
+}
+
+function GenActions({ item, g }: { item: SessionItem; g: GenerationRecord }) {
+ const original = g.references[0] && g.mode !== "generate" && g.mode !== "upscale" ? { width: g.references[0].width, height: g.references[0].height } : null;
+ const [fav, setFav] = useState(g.favorite);
+ return (
+ <div className="actions">
+ <IconButton title="Edit" onClick={() => editItem(item)}>
+ <Pencil size={17} />
+ </IconButton>
+ <IconButton
+ title="Create variation"
+ onClick={() => {
+ const r = variationRequest(g);
+ if (r) submitRequest(r);
+ }}
+ >
+ <Shuffle size={17} />
+ </IconButton>
+ <IconButton title="Use as reference" onClick={() => addAsReference(item)}>
+ <ImagePlus size={17} />
+ </IconButton>
+ <IconButton title="Inpaint" onClick={() => openEditorFor(item, "inpaint")}>
+ <Brush size={17} />
+ </IconButton>
+ <IconButton title="Expand" onClick={() => openEditorFor(item, "expand")}>
+ <Expand size={17} />
+ </IconButton>
+ <UpscaleButton source={`gen:${g.id}`} size={{ width: g.width, height: g.height }} original={original} parentId={g.id} />
+ <span className="sep" />
+ <IconButton
+ title={fav ? "Remove from favorites" : "Favorite"}
+ active={fav}
+ onClick={async () => {
+ try {
+ await api.setFavorite(g.id, !fav);
+ setFav(!fav);
+ } catch (e) {
+ toastError(e);
+ }
+ }}
+ >
+ <Heart size={17} fill={fav ? "currentColor" : "none"} />
+ </IconButton>
+ <IconButton
+ title="Save as…"
+ onClick={async () => {
+ const name = g.file_path.split(/[\\/]/).pop() ?? "image.png";
+ const path = await native.saveAs(name);
+ if (!path) return;
+ try {
+ const r = await api.exportGeneration(g.id, path);
+ toastInfo(`Saved ${r.path.split(/[\\/]/).pop()}`);
+ } catch (e) {
+ toastError(e);
+ }
+ }}
+ >
+ <Download size={17} />
+ </IconButton>
+ <IconButton
+ title="Copy image"
+ onClick={async () => {
+ try {
+ await native.copyImage(g.file_path);
+ toastInfo("Image copied");
+ } catch (e) {
+ toastError(e);
+ }
+ }}
+ >
+ <Copy size={17} />
+ </IconButton>
+ <IconButton title="Show in Explorer" onClick={() => native.reveal(g.file_path).catch(toastError)}>
+ <FolderOpen size={17} />
+ </IconButton>
+ <Popover
+ placement="top-end"
+ trigger={(open, toggle) => (
+ <IconButton title="Details" onClick={toggle} active={open}>
+ <Info size={17} />
+ </IconButton>
+ )}
+ >
+ {() => <InfoPanel g={g} />}
+ </Popover>
+ </div>
+ );
+}
+
+function InputActions({ item }: { item: SessionItem }) {
+ return (
+ <div className="actions">
+ <IconButton title="Edit" onClick={() => editItem(item)}>
+ <Pencil size={17} />
+ </IconButton>
+ <IconButton title="Use as reference" onClick={() => addAsReference(item)}>
+ <ImagePlus size={17} />
+ </IconButton>
+ <IconButton title="Inpaint" onClick={() => openEditorFor(item, "inpaint")}>
+ <Brush size={17} />
+ </IconButton>
+ <IconButton title="Expand" onClick={() => openEditorFor(item, "expand")}>
+ <Expand size={17} />
+ </IconButton>
+ {item.input && <UpscaleButton source={`input:${item.input.id}`} size={{ width: item.input.width, height: item.input.height }} />}
+ <span className="sep" />
+ <IconButton title="Remove from session" onClick={() => removeSessionItem(item.key)}>
+ <X size={17} />
+ </IconButton>
+ </div>
+ );
+}
+
+/** A result or input fitted to the stage (never enlarged past its own size), with the
+ * full-screen button in its top-right corner. */
+function PlainFrame({ src, alt, w, h }: { src: string; alt: string; w: number; h: number }) {
+ const { ref, box } = useFit(w / h);
+ const bw = Math.min(box.w, w);
+ return (
+ <div className="stage-frame" ref={ref}>
+ <div className="image-box" style={{ width: bw, height: bw * (h / w) }}>
+ <img className="stage-img fill" src={src} alt={alt} draggable={false} onDoubleClick={() => setState({ overlay: null })} />
+ <FullscreenButton hint="Click to zoom to 100 %" content={<ZoomImage src={src} alt={alt} />} />
+ </div>
+ </div>
+ );
+}
+
+export function Stage() {
+ const item = useStore(selectedItem);
+ const job = useStore((s) => (item?.jobId ? s.jobs[item.jobId] : undefined));
+
+ if (!item) {
+ return (
+ <div className="stage">
+ <Empty />
+ </div>
+ );
+ }
+ if (item.kind === "job" && job) {
+ if (job.status === "failed" || job.status === "cancelled") {
+ return (
+ <div className="stage">
+ <Failed job={job} item={item} />
+ </div>
+ );
+ }
+ const o = job.plan?.output;
+ return (
+ <div className="stage">
+ <Pending job={job} aspect={o ? o.width / o.height : 1} />
+ <div className="stage-caption">
+ <span className="prompt">{job.prompt}</span>
+ </div>
+ </div>
+ );
+ }
+ if (item.kind === "job") {
+ return (
+ <div className="stage">
+ <Loader2 className="spin" size={22} />
+ </div>
+ );
+ }
+ const src = item.gen ? urls.gen(item.gen.id) : urls.input(item.input!.id);
+ const w = item.gen?.width ?? item.input!.width;
+ const h = item.gen?.height ?? item.input!.height;
+ const base = item.gen ? compareBase(item.gen) : null;
+ return (
+ <div className="stage">
+ {item.gen && base ? (
+ <CompareFrame key={`compare-${item.gen.id}`} g={item.gen} base={base} />
+ ) : (
+ <PlainFrame key={src} src={src} alt={item.gen?.prompt ?? item.input?.original_name ?? ""} w={w} h={h} />
+ )}
+ {base && <CompareBar />}
+ <div className="stage-caption">
+ {item.gen ? <span className="prompt" title={item.gen.prompt}>{item.gen.prompt}</span> : <span>{item.input?.original_name ? decodeURIComponent(item.input.original_name) : "Image"}</span>}
+ <span>
+ {w}×{h}
+ </span>
+ </div>
+ {item.gen ? <GenActions key={`actions-${item.gen.id}`} item={item} g={item.gen} /> : <InputActions item={item} />}
+ </div>
+ );
+}
+
+export function HistoryRail() {
+ const session = useStore((s) => s.session);
+ const selected = useStore((s) => s.selected);
+ const jobs = useStore((s) => s.jobs);
+ if (!session.length) return null;
+ return (
+ <div className="rail" aria-label="Session history">
+ {session.map((it) => {
+ const job = it.jobId ? jobs[it.jobId] : undefined;
+ const pending = it.kind === "job";
+ return (
+ <button key={it.key} className={`thumb ${selected === it.key ? "sel" : ""}`} onClick={() => setState({ selected: it.key })} title={it.gen?.prompt ?? (job ? jobLabel(job) : "Image")}>
+ {it.gen && <img src={urls.genThumb(it.gen.id)} alt="" draggable={false} />}
+ {it.input && <img src={urls.inputThumb(it.input.id)} alt="" draggable={false} />}
+ {pending && job && !["failed", "cancelled"].includes(job.status) && <Loader2 className="spin" size={18} />}
+ {pending && job && ["failed", "cancelled"].includes(job.status) && <X size={18} />}
+ {it.input && <span className="tag">in</span>}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
diff --git a/src/components/Viewer.tsx b/src/components/Viewer.tsx
new file mode 100644
index 0000000..8373b30
--- /dev/null
+++ b/src/components/Viewer.tsx
@@ -0,0 +1,147 @@
+// Full-screen viewing: a shell that takes the window full screen and shows any content
+// (the live before/after comparison, or a zoomable image).
+
+import { Maximize2, X } from "lucide-react";
+import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
+import { createPortal } from "react-dom";
+import { native } from "../lib/native";
+
+const isTyping = (t: EventTarget | null) => t instanceof HTMLElement && (t.isContentEditable || ["INPUT", "TEXTAREA", "SELECT"].includes(t.tagName));
+
+/** Button for the top-right corner of an image; F also opens it. `content` is what to show
+ * full screen; `hint` is shown next to the close button. */
+export function FullscreenButton({ content, hint }: { content: ReactNode; hint?: string }) {
+ const [open, setOpen] = useState(false);
+ useEffect(() => {
+ if (open) return;
+ const down = (e: KeyboardEvent) => {
+ if (e.key.toLowerCase() === "f" && !e.repeat && !e.ctrlKey && !e.metaKey && !e.altKey && !isTyping(e.target)) setOpen(true);
+ };
+ window.addEventListener("keydown", down);
+ return () => window.removeEventListener("keydown", down);
+ }, [open]);
+ return (
+ <>
+ <button
+ className="fullscreen-btn"
+ title="Full screen (F)"
+ aria-label="View full screen"
+ onPointerDown={(e) => e.stopPropagation()}
+ onClick={(e) => {
+ e.stopPropagation();
+ setOpen(true);
+ }}
+ onDoubleClick={(e) => e.stopPropagation()}
+ >
+ <Maximize2 size={15} />
+ </button>
+ {open &&
+ createPortal(
+ <FullscreenShell hint={hint} onClose={() => setOpen(false)}>
+ {content}
+ </FullscreenShell>,
+ document.body,
+ )}
+ </>
+ );
+}
+
+function FullscreenShell({ children, hint, onClose }: { children: ReactNode; hint?: string; onClose: () => void }) {
+ // Real full screen for the window while open; restored on close unless it already was.
+ useEffect(() => {
+ let wasFull = false;
+ let alive = true;
+ native
+ .isFullscreen()
+ .then((f) => {
+ wasFull = f;
+ if (alive && !f) return native.setFullscreen(true);
+ })
+ .catch(() => {});
+ return () => {
+ alive = false;
+ if (!wasFull) native.setFullscreen(false).catch(() => {});
+ };
+ }, []);
+
+ useEffect(() => {
+ const down = (e: KeyboardEvent) => {
+ if (isTyping(e.target)) return;
+ if (e.key === "Escape" || (e.key.toLowerCase() === "f" && !e.repeat && !e.ctrlKey && !e.metaKey && !e.altKey)) {
+ e.preventDefault();
+ e.stopPropagation();
+ onClose();
+ }
+ };
+ window.addEventListener("keydown", down, true);
+ return () => window.removeEventListener("keydown", down, true);
+ }, [onClose]);
+
+ return (
+ <div className="viewer" role="dialog" aria-label="Full screen">
+ {children}
+ <div className="viewer-bar">
+ <span className="viewer-hint">{hint ? `${hint} · ` : ""}Esc to exit</span>
+ <button className="viewer-close" title="Exit full screen (Esc)" aria-label="Exit full screen" onClick={onClose}>
+ <X size={18} />
+ </button>
+ </div>
+ </div>
+ );
+}
+
+/** Fit to screen; click for 100 % at that point, drag to pan, click again to fit. */
+export function ZoomImage({ src, alt }: { src: string; alt: string }) {
+ const scroller = useRef<HTMLDivElement>(null);
+ const [zoom, setZoom] = useState<{ fx: number; fy: number } | null>(null);
+ const [natural, setNatural] = useState<{ w: number; h: number } | null>(null);
+ const drag = useRef<{ x: number; y: number; sl: number; st: number; moved: boolean } | null>(null);
+
+ useLayoutEffect(() => {
+ const el = scroller.current;
+ if (!el || !zoom || !natural) return;
+ el.scrollLeft = zoom.fx * natural.w - el.clientWidth / 2;
+ el.scrollTop = zoom.fy * natural.h - el.clientHeight / 2;
+ }, [zoom, natural]);
+
+ const el = scroller.current;
+ const canZoom = !natural || !el || natural.w > el.clientWidth || natural.h > el.clientHeight;
+
+ return (
+ <div
+ ref={scroller}
+ className={`viewer-scroll ${zoom ? "zoomed" : ""}`}
+ onPointerDown={(e) => {
+ if (!zoom || e.button !== 0) return;
+ drag.current = { x: e.clientX, y: e.clientY, sl: e.currentTarget.scrollLeft, st: e.currentTarget.scrollTop, moved: false };
+ e.currentTarget.setPointerCapture(e.pointerId);
+ }}
+ onPointerMove={(e) => {
+ const d = drag.current;
+ if (!d) return;
+ if (Math.abs(e.clientX - d.x) + Math.abs(e.clientY - d.y) > 4) d.moved = true;
+ e.currentTarget.scrollLeft = d.sl - (e.clientX - d.x);
+ e.currentTarget.scrollTop = d.st - (e.clientY - d.y);
+ }}
+ onPointerUp={() => {
+ const d = drag.current;
+ drag.current = null;
+ if (zoom && d && !d.moved) setZoom(null);
+ }}
+ >
+ <img
+ className="viewer-img"
+ src={src}
+ alt={alt}
+ draggable={false}
+ style={zoom && natural ? { width: natural.w, height: natural.h, maxWidth: "none", maxHeight: "none", cursor: "inherit" } : { cursor: canZoom ? "zoom-in" : "default" }}
+ onLoad={(e) => setNatural({ w: e.currentTarget.naturalWidth, h: e.currentTarget.naturalHeight })}
+ onClick={(e) => {
+ if (zoom || !canZoom) return;
+ const r = e.currentTarget.getBoundingClientRect();
+ setZoom({ fx: (e.clientX - r.left) / r.width, fy: (e.clientY - r.top) / r.height });
+ }}
+ />
+ </div>
+ );
+}
diff --git a/src/components/ui.tsx b/src/components/ui.tsx
new file mode 100644
index 0000000..58018f2
--- /dev/null
+++ b/src/components/ui.tsx
@@ -0,0 +1,95 @@
+import { Check } from "lucide-react";
+import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
+
+/** Largest w×h box with the given aspect that fits the container. */
+export function useFit(aspect: number) {
+ const ref = useRef<HTMLDivElement>(null);
+ const [box, setBox] = useState({ w: 0, h: 0 });
+ useLayoutEffect(() => {
+ const el = ref.current;
+ if (!el) return;
+ const ro = new ResizeObserver(() => {
+ const W = el.clientWidth;
+ const H = el.clientHeight;
+ const w = Math.min(W, H * aspect);
+ setBox({ w, h: w / aspect });
+ });
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, [aspect]);
+ return { ref, box };
+}
+
+/** Button + anchored popover that closes on outside click / Escape. */
+export function Popover(props: {
+ trigger: (open: boolean, toggle: () => void) => ReactNode;
+ children: (close: () => void) => ReactNode;
+ placement?: "top-start" | "top-end" | "bottom-end" | "bottom-start";
+ className?: string;
+}) {
+ const [open, setOpen] = useState(false);
+ const ref = useRef<HTMLDivElement>(null);
+ useEffect(() => {
+ if (!open) return;
+ const onDown = (e: MouseEvent) => {
+ if (ref.current && !ref.current.contains(e.target as Node)) setOpen(false);
+ };
+ const onKey = (e: KeyboardEvent) => e.key === "Escape" && setOpen(false);
+ document.addEventListener("mousedown", onDown);
+ document.addEventListener("keydown", onKey);
+ return () => {
+ document.removeEventListener("mousedown", onDown);
+ document.removeEventListener("keydown", onKey);
+ };
+ }, [open]);
+ const pos: Record<string, React.CSSProperties> = {
+ "top-start": { bottom: "calc(100% + 8px)", left: 0 },
+ "top-end": { bottom: "calc(100% + 8px)", right: 0 },
+ "bottom-end": { top: "calc(100% + 6px)", right: 0 },
+ "bottom-start": { top: "calc(100% + 6px)", left: 0 },
+ };
+ return (
+ <div ref={ref} style={{ position: "relative" }}>
+ {props.trigger(open, () => setOpen((o) => !o))}
+ {open && (
+ <div className={`popover ${props.className ?? ""}`} style={pos[props.placement ?? "top-start"]}>
+ {props.children(() => setOpen(false))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+export function Option(props: { selected?: boolean; onClick: () => void; icon?: ReactNode; label: string; sub?: string }) {
+ return (
+ <button className="opt" onClick={props.onClick} role="menuitemradio" aria-checked={!!props.selected}>
+ <span className="check">{props.selected ? <Check size={15} /> : props.icon}</span>
+ <span>{props.label}</span>
+ {props.sub && <span className="sub">{props.sub}</span>}
+ </button>
+ );
+}
+
+export function Seg<T extends string>(props: { value: T; options: { value: T; label: string }[]; onChange: (v: T) => void }) {
+ return (
+ <div className="seg" role="radiogroup">
+ {props.options.map((o) => (
+ <button key={o.value} className={o.value === props.value ? "on" : ""} onClick={() => props.onChange(o.value)} role="radio" aria-checked={o.value === props.value}>
+ {o.label}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+export function Switch(props: { on: boolean; onChange: (v: boolean) => void; label?: string }) {
+ return <button className={`switch ${props.on ? "on" : ""}`} role="switch" aria-checked={props.on} aria-label={props.label} onClick={() => props.onChange(!props.on)} />;
+}
+
+export function IconButton(props: { title: string; onClick?: () => void; children: ReactNode; active?: boolean; disabled?: boolean; small?: boolean }) {
+ return (
+ <button className={`icon-btn ${props.small ? "sm" : ""} ${props.active ? "active" : ""}`} title={props.title} aria-label={props.title} onClick={props.onClick} disabled={props.disabled}>
+ {props.children}
+ </button>
+ );
+}
diff --git a/src/lib/api.ts b/src/lib/api.ts
new file mode 100644
index 0000000..c3f1cb4
--- /dev/null
+++ b/src/lib/api.ts
@@ -0,0 +1,111 @@
+// Thin client for the local qls-service API. Images are referenced by URL (with the
+// token as a query parameter) so the webview streams them directly — no base64 copies.
+
+import type {
+ AppConfig, AppErrorBody, GenerationRecord, GenerationRequest, InputRecord, JobView, Plan, ServiceEvent, SetupReport, StatusResponse,
+} from "./types";
+
+export class ApiError extends Error {
+ constructor(public body: AppErrorBody, public status: number) {
+ super(body.message);
+ }
+}
+
+let base = "";
+let token = "";
+
+export function configure(baseUrl: string, tok: string) {
+ base = baseUrl;
+ token = tok;
+}
+
+export const isConfigured = () => base !== "";
+
+async function call<T>(path: string, init: RequestInit = {}): Promise<T> {
+ let res: Response;
+ try {
+ res = await fetch(base + path, {
+ ...init,
+ headers: { Authorization: `Bearer ${token}`, ...(init.body && typeof init.body === "string" ? { "Content-Type": "application/json" } : {}), ...(init.headers || {}) },
+ });
+ } catch (e) {
+ throw new ApiError({ code: "server_unavailable", message: "The local service is not reachable.", detail: String(e) }, 0);
+ }
+ const text = await res.text();
+ const data = text ? JSON.parse(text) : null;
+ if (!res.ok) {
+ throw new ApiError(data?.error ?? { code: "internal", message: `HTTP ${res.status}` }, res.status);
+ }
+ return data as T;
+}
+
+const json = (body: unknown) => JSON.stringify(body);
+
+export const api = {
+ status: () => call<StatusResponse>("/status"),
+ setup: () => call<SetupReport>("/setup"),
+ config: () => call<AppConfig>("/config"),
+ saveConfig: (c: AppConfig) => call<{ saved: boolean; backend_restart_needed: boolean }>("/config", { method: "PUT", body: json(c) }),
+ startBackend: () => call<{ ready: boolean }>("/backend/start", { method: "POST" }),
+ stopBackend: () => call<{ stopped: boolean }>("/backend/stop", { method: "POST" }),
+ restartBackend: () => call<{ ready: boolean }>("/backend/restart", { method: "POST" }),
+ diagnostics: () => call<{ text: string }>("/diagnostics"),
+ plan: (r: GenerationRequest) => call<Plan>("/plan", { method: "POST", body: json(r) }),
+ submit: (r: GenerationRequest) => call<JobView>("/jobs", { method: "POST", body: json(r) }),
+ job: (id: string) => call<JobView>(`/jobs/${id}`),
+ jobs: () => call<JobView[]>("/jobs"),
+ cancel: (id: string) => call<JobView>(`/jobs/${id}/cancel`, { method: "POST" }),
+ upload: (bytes: Blob | ArrayBuffer | Uint8Array, name?: string) =>
+ call<InputRecord>("/inputs", { method: "POST", body: bytes as BodyInit, headers: { "Content-Type": "application/octet-stream", ...(name ? { "x-filename": encodeURIComponent(name) } : {}) } }),
+ importPath: (path: string) => call<InputRecord>("/inputs/import", { method: "POST", body: json({ path }) }),
+ input: (id: string) => call<InputRecord>(`/inputs/${id}`),
+ gallery: (q: { q?: string; favorites?: boolean; limit?: number; offset?: number; sort?: string }) => {
+ const p = new URLSearchParams();
+ if (q.q) p.set("q", q.q);
+ if (q.favorites) p.set("favorites", "true");
+ if (q.limit) p.set("limit", String(q.limit));
+ if (q.offset) p.set("offset", String(q.offset));
+ if (q.sort) p.set("sort", q.sort);
+ return call<{ items: GenerationRecord[]; total: number }>(`/gallery?${p}`);
+ },
+ generation: (id: string) => call<GenerationRecord>(`/gallery/${id}`),
+ setFavorite: (id: string, favorite: boolean) => call<GenerationRecord>(`/gallery/${id}`, { method: "PATCH", body: json({ favorite }) }),
+ deleteGeneration: (id: string) => call<{ deleted: string }>(`/gallery/${id}`, { method: "DELETE" }),
+ exportGeneration: (id: string, path: string) => call<{ path: string }>(`/gallery/${id}/export`, { method: "POST", body: json({ path, overwrite: true }) }),
+};
+
+export const urls = {
+ input: (id: string) => `${base}/inputs/${id}/image?token=${token}`,
+ inputThumb: (id: string) => `${base}/inputs/${id}/thumb?token=${token}`,
+ gen: (id: string) => `${base}/gallery/${id}/image?token=${token}`,
+ genThumb: (id: string) => `${base}/gallery/${id}/thumb?token=${token}`,
+};
+
+/** Server-sent events with automatic reconnect. Returns an unsubscribe function. */
+export function subscribe(onEvent: (e: ServiceEvent) => void, onState?: (connected: boolean) => void): () => void {
+ let es: EventSource | null = null;
+ let closed = false;
+ let retry: number | undefined;
+ const open = () => {
+ es = new EventSource(`${base}/events?token=${token}`);
+ es.onopen = () => onState?.(true);
+ es.onmessage = (m) => {
+ try {
+ onEvent(JSON.parse(m.data));
+ } catch {
+ /* ignore malformed */
+ }
+ };
+ es.onerror = () => {
+ onState?.(false);
+ es?.close();
+ if (!closed) retry = window.setTimeout(open, 1500);
+ };
+ };
+ open();
+ return () => {
+ closed = true;
+ window.clearTimeout(retry);
+ es?.close();
+ };
+}
diff --git a/src/lib/logic.test.ts b/src/lib/logic.test.ts
new file mode 100644
index 0000000..739a43c
--- /dev/null
+++ b/src/lib/logic.test.ts
@@ -0,0 +1,183 @@
+import { describe, expect, it } from "vitest";
+import {
+ activeOverrides, buildRequest, compareBase, diffPixels, emptyComposer, expansionPixels, expansionPreset, jobFraction, jobLabel, moveRef, persistentAdvanced, pipelineSummary,
+ planPipeline, remainingSeconds, sizeForWidth, upscaleRequest, upscaleTargets, type Ref,
+} from "./logic";
+import type { GenerationRecord, JobView, Plan } from "./types";
+
+const ref = (n: number): Ref => ({ key: `k${n}`, source: `input:${n}`, width: 100, height: 100, name: `r${n}` });
+
+describe("references", () => {
+ it("moves while preserving order of others", () => {
+ const refs = [ref(1), ref(2), ref(3)];
+ expect(moveRef(refs, 2, 0).map((r) => r.key)).toEqual(["k3", "k1", "k2"]);
+ expect(moveRef(refs, 0, 2).map((r) => r.key)).toEqual(["k2", "k3", "k1"]);
+ expect(moveRef(refs, 1, 1)).toBe(refs);
+ });
+});
+
+describe("advanced overrides", () => {
+ // What an older version saved after a CFG test (found in a real WebView profile).
+ const saved = { batch_count: null, cfg: 4, flow_shift: null, hdr: false, output_format: "png" as const, refine: null, sampler: null, scheduler: null, steps: 20, strength: 1, vae_tiling: null };
+
+ it("lists only the sampling overrides that are set", () => {
+ expect(activeOverrides(saved)).toEqual(["CFG 4", "Steps 20", "Strength 1"]);
+ expect(activeOverrides({ output_format: "webp", hdr: true, batch_count: 2 })).toEqual([]);
+ expect(activeOverrides({})).toEqual([]);
+ });
+
+ it("keeps preferences but never persists sampling overrides", () => {
+ expect(persistentAdvanced(saved)).toEqual({ hdr: false, output_format: "png" });
+ expect(persistentAdvanced(undefined)).toEqual({});
+ expect(emptyComposer({ advanced: persistentAdvanced(saved) }).advanced.cfg).toBeUndefined();
+ });
+});
+
+describe("buildRequest", () => {
+ it("text to image uses aspect, no images", () => {
+ const c = { ...emptyComposer(), prompt: " a fox ", aspect: "16:9" };
+ const r = buildRequest(c);
+ expect(r.prompt).toBe("a fox");
+ expect(r.images).toEqual([]);
+ expect(r.aspect_ratio).toBe("16:9");
+ expect(r.width).toBeNull();
+ });
+ it("keeps reference order and the chosen aspect for edits and combines", () => {
+ const c = { ...emptyComposer(), prompt: "combine", refs: [ref(3), ref(1), ref(2)], aspect: "16:9" };
+ const r = buildRequest(c);
+ expect(r.images).toEqual(["input:3", "input:1", "input:2"]);
+ expect(r.aspect_ratio).toBe("16:9");
+ });
+ it("inpaint and expand ignore the aspect", () => {
+ const masked = { ...emptyComposer(), prompt: "x", refs: [ref(1)], mask: { inputId: "m", refKey: "k1" }, aspect: "16:9" };
+ expect(buildRequest(masked).aspect_ratio).toBeNull();
+ const expanded = { ...emptyComposer(), prompt: "x", refs: [ref(1)], outpaint: { left: 10, right: 10, top: 0, bottom: 0, units: "percent" as const }, aspect: "16:9" };
+ expect(buildRequest(expanded).aspect_ratio).toBeNull();
+ });
+ it("mask only applies to the image it was painted on", () => {
+ const c = { ...emptyComposer(), prompt: "x", refs: [ref(1)], mask: { inputId: "m", refKey: "k1" } };
+ expect(buildRequest(c).mask).toBe("input:m");
+ const moved = { ...c, refs: [ref(2), ref(1)] };
+ expect(buildRequest(moved).mask).toBeNull();
+ });
+ it("custom resolution sends dimensions", () => {
+ const c = { ...emptyComposer(), prompt: "x", resolution: "custom" as const, customWidth: 1280, customHeight: 720 };
+ const r = buildRequest(c);
+ expect([r.width, r.height]).toEqual([1280, 720]);
+ });
+ it("forced Create mode ignores attached images", () => {
+ const c = { ...emptyComposer(), prompt: "x", refs: [ref(1)], mode: "generate" as const };
+ expect(buildRequest(c).images).toEqual([]);
+ });
+});
+
+describe("expansion", () => {
+ const zero = { left: 0, right: 0, top: 0, bottom: 0, units: "pixels" as const };
+ it("presets", () => {
+ expect(expansionPreset("right", 1000, 800, zero)).toMatchObject({ right: 250 });
+ const l = expansionPreset("landscape", 1024, 1024, zero);
+ expect(l.left + l.right + 1024).toBe(1820);
+ const s = expansionPreset("square", 1920, 1080, zero);
+ expect(s.top + s.bottom + 1080).toBe(1920);
+ });
+ it("percent to pixels", () => {
+ expect(expansionPixels({ left: 10, right: 0, top: 50, bottom: 0, units: "percent" }, 1000, 600)).toEqual({ left: 100, right: 0, top: 300, bottom: 0 });
+ });
+});
+
+describe("job labels are truthful", () => {
+ const base: JobView = {
+ id: "j", status: "running", stage: "generating", step: [12, 30], image: null, seconds_per_step: 2, queue_position: 0, created_at: "",
+ started_at: null, finished_at: null, prompt: "", plan: null, seed: 1, results: [], error: null, notes: [], detailed_progress: true,
+ };
+ it("shows steps only when reported", () => {
+ expect(jobLabel(base)).toBe("Generating · 12/30");
+ expect(jobFraction(base)).toBeCloseTo(0.4);
+ const noDetail = { ...base, step: null };
+ expect(jobLabel(noDetail)).toBe("Generating");
+ expect(jobFraction(noDetail)).toBeNull();
+ expect(jobLabel({ ...base, status: "queued", queue_position: 3 })).toBe("Queued · 3");
+ });
+
+ it("one pass fills the bar; enlarging is indeterminate", () => {
+ expect(remainingSeconds({ ...base, step: [10, 20] as [number, number] })).toBeCloseTo(10 * 2);
+ expect(jobLabel({ ...base, stage: "upscaling", step: null })).toBe("Upscaling");
+ expect(jobFraction({ ...base, stage: "upscaling", step: null })).toBeNull();
+ expect(jobFraction({ ...base, stage: "decoding", step: null })).toBe(1);
+ });
+});
+
+describe("upscaling", () => {
+ it("presets are real enlargements within limits", () => {
+ const t = upscaleTargets(1376, 768);
+ expect(t.map((x) => x.key)).toEqual(["2x", "4k"]);
+ expect(t[0]).toMatchObject({ width: 2752, height: 1536 });
+ expect(t[1]).toMatchObject({ width: 3840, height: 2143 });
+ // Portrait 4K uses the long side.
+ expect(upscaleTargets(768, 1376).find((x) => x.key === "4k")).toMatchObject({ width: 2143, height: 3840 });
+ // A 1 MP edit of a 5120x2880 photo can go back to the photo's size.
+ expect(upscaleTargets(1376, 768, { width: 5120, height: 2880 }).map((x) => x.key)).toEqual(["2x", "4k", "source"]);
+ expect(upscaleTargets(5120, 2880, { width: 5120, height: 2880 }).map((x) => x.key), "2x is over 40 MP; 4K and source are not larger").toEqual([]);
+ expect(upscaleTargets(4000, 4000).length).toBe(0);
+ });
+ it("custom width keeps the aspect", () => {
+ expect(sizeForWidth(1376, 768, 3000)).toEqual({ width: 3000, height: 1674 });
+ });
+ it("builds an upscale request without a prompt", () => {
+ const r = upscaleRequest("gen:abc", { width: 2752, height: 1536 }, "detailed", "abc");
+ expect(r).toMatchObject({ mode: "upscale", images: ["gen:abc"], prompt: "", parent_id: "abc", upscale: { method: "detailed", width: 2752, height: 1536 } });
+ });
+ it("summarises the pipeline for the details panel", () => {
+ const g = {
+ width: 2752, height: 1536, working_width: 2048, working_height: 1152,
+ pipeline: {
+ base: { width: 1376, height: 768 }, refine: "fast", refine_steps: 6, refine_denoise: 0.35, hires_upscaler: "4x-UltraSharp",
+ cache_threshold: 0.2, enlarged_with: "4x-UltraSharp", enlarged_from: { width: 2048, height: 1152 },
+ },
+ } as unknown as GenerationRecord;
+ expect(pipelineSummary(g)).toBe("1376×768 → refined 2048×1152 (Fast, 6 steps, UltraSharp) → 2752×1536 (UltraSharp)");
+ const edit = { ...g, width: 5120, height: 2880, pipeline: { ...g.pipeline!, base: null, enlarged_from: { width: 1376, height: 768 }, enlarged_with: "Lanczos" } } as GenerationRecord;
+ expect(pipelineSummary(edit)).toBe("1376×768 → 5120×2880 (Lanczos)");
+ expect(pipelineSummary({ ...g, pipeline: null } as GenerationRecord)).toBeNull();
+ });
+ it("describes plans", () => {
+ const p = {
+ output: { width: 2752, height: 1536 }, working: { width: 2080, height: 1152 }, content: { x: 12, y: 2, width: 2056, height: 1148 },
+ upscaler: "4x-UltraSharp", upscale: null,
+ } as unknown as Plan;
+ expect(planPipeline(p)).toBe("2080×1152 render → 2752×1536 output (UltraSharp)");
+ const quick = { ...p, upscaler: null, upscale: { method: "quick", source: { width: 1376, height: 768 } } } as Plan;
+ expect(planPipeline(quick)).toBe("1376×768 → 2752×1536 (Lanczos)");
+ });
+});
+
+describe("before / after comparison", () => {
+ const rec = (mode: string, extra: Partial<GenerationRecord> = {}) =>
+ ({ mode, references: [{ index: 0, input_id: "in1", width: 1000, height: 500 }], outpaint: null, ...extra }) as unknown as GenerationRecord;
+
+ it("edits, inpaints and upscales compare against the whole source", () => {
+ for (const m of ["edit", "inpaint", "upscale"]) expect(compareBase(rec(m))).toEqual({ inputId: "in1", rect: { x: 0, y: 0, w: 1, h: 1 } });
+ });
+
+ it("an expanded image places the source inside the larger result", () => {
+ const b = compareBase(rec("outpaint", { outpaint: { left: 500, right: 500, top: 0, bottom: 500 } }))!;
+ expect(b.rect).toEqual({ x: 0.25, y: 0, w: 0.5, h: 0.5 });
+ });
+
+ it("new images and multi-reference results have no before", () => {
+ expect(compareBase(rec("generate"))).toBeNull();
+ expect(compareBase(rec("multi_reference"))).toBeNull();
+ expect(compareBase(rec("edit", { references: [] }))).toBeNull();
+ });
+
+ it("marks only pixels that changed beyond the threshold, and uncovered pixels", () => {
+ const after = new Uint8ClampedArray([100, 100, 100, 255, 100, 100, 100, 255, 200, 0, 0, 255, 50, 50, 50, 255]);
+ const before = new Uint8ClampedArray([100, 100, 100, 255, 110, 100, 100, 255, 0, 0, 0, 255, 0, 0, 0, 0]);
+ const out = new Uint8ClampedArray(16);
+ expect(diffPixels(after, before, out)).toBe(0.5);
+ expect(out[0]).toBe(out[1]); // unchanged: grey
+ expect(out[4]).toBe(out[5]); // small change below the threshold: grey
+ expect(out[8]).toBeGreaterThan(out[9]); // big change: red
+ expect(out[12]).toBeGreaterThan(out[13]); // not covered by the source (expanded): red
+ });
+});
diff --git a/src/lib/logic.ts b/src/lib/logic.ts
new file mode 100644
index 0000000..b04507d
--- /dev/null
+++ b/src/lib/logic.ts
@@ -0,0 +1,402 @@
+// Pure UI logic (unit-tested in logic.test.ts).
+
+import type { Advanced, GenerationRecord, GenerationRequest, InputRecord, JobView, Mode, OutpaintSpec, Plan, Quality, ResolutionMode, Size, UpscaleMethod } from "./types";
+
+export interface Ref {
+ key: string;
+ /** "input:<id>" or "gen:<id>" */
+ source: string;
+ width: number;
+ height: number;
+ name: string;
+ /** HEIC source with an HDR gain map. */
+ hdr?: boolean;
+}
+
+export interface Composer {
+ prompt: string;
+ negative: string;
+ refs: Ref[];
+ /** Mask painted on refs[0] (input id of the mask PNG). */
+ mask: { inputId: string; refKey: string } | null;
+ outpaint: OutpaintSpec | null;
+ mode: Mode;
+ aspect: string;
+ quality: Quality;
+ resolution: ResolutionMode;
+ customWidth: number;
+ customHeight: number;
+ seed: number | null;
+ advanced: Advanced;
+}
+
+export const emptyComposer = (prefs?: Partial<Composer>): Composer => ({
+ prompt: "",
+ negative: "",
+ refs: [],
+ mask: null,
+ outpaint: null,
+ mode: "auto",
+ aspect: prefs?.aspect ?? "auto",
+ quality: prefs?.quality ?? "balanced",
+ resolution: prefs?.resolution ?? "auto",
+ customWidth: prefs?.customWidth ?? 1024,
+ customHeight: prefs?.customHeight ?? 1024,
+ seed: null,
+ advanced: prefs?.advanced ?? {},
+});
+
+let counter = 0;
+export const newKey = () => `k${Date.now().toString(36)}${(counter++).toString(36)}`;
+
+export const refFromInput = (r: InputRecord): Ref => ({ key: newKey(), source: `input:${r.id}`, width: r.width, height: r.height, name: r.original_name ? decodeSafe(r.original_name) : "Image", hdr: r.hdr || undefined });
+export const refFromGen = (g: GenerationRecord): Ref => ({ key: newKey(), source: `gen:${g.id}`, width: g.width, height: g.height, name: "Result" });
+
+function decodeSafe(s: string) {
+ try {
+ return decodeURIComponent(s);
+ } catch {
+ return s;
+ }
+}
+
+/** Moves a reference, keeping all others in order. */
+export function moveRef(refs: Ref[], from: number, to: number): Ref[] {
+ if (from === to || from < 0 || from >= refs.length) return refs;
+ const out = refs.slice();
+ const [r] = out.splice(from, 1);
+ out.splice(Math.max(0, Math.min(to, out.length)), 0, r);
+ return out;
+}
+
+export function hasOutpaint(o: OutpaintSpec | null): boolean {
+ return !!o && (o.left > 0 || o.right > 0 || o.top > 0 || o.bottom > 0);
+}
+
+/** Composer state -> stable service request. */
+export function buildRequest(c: Composer, parentId?: string | null): GenerationRequest {
+ const maskValid = c.mask && c.refs[0] && c.mask.refKey === c.refs[0].key;
+ const custom = c.resolution === "custom";
+ // Inpaint and expand keep the source's shape; create, edit and combine take the chosen ratio.
+ const shaped = !maskValid && !hasOutpaint(c.outpaint);
+ return {
+ prompt: c.prompt.trim(),
+ negative_prompt: c.negative.trim() || null,
+ mode: c.mode,
+ images: c.mode === "generate" ? [] : c.refs.map((r) => r.source),
+ mask: maskValid ? `input:${c.mask!.inputId}` : null,
+ outpaint: hasOutpaint(c.outpaint) ? c.outpaint : null,
+ quality: c.quality,
+ resolution: c.resolution,
+ aspect_ratio: shaped && c.aspect !== "auto" && !custom ? c.aspect : null,
+ width: custom ? c.customWidth : null,
+ height: custom ? c.customHeight : null,
+ seed: c.seed,
+ preserve_dimensions: true,
+ advanced: cleanAdvanced(c.advanced),
+ client: "ui",
+ parent_id: parentId ?? null,
+ };
+}
+
+/** Advanced fields that change how the model samples. They last for the session only: a value
+ * typed once (e.g. CFG 4 during a test) must not silently override the presets after a restart.
+ * `flow_shift` is no longer in the UI but may still sit in old saved preferences. */
+const SAMPLING_OVERRIDES = ["steps", "cfg", "sampler", "scheduler", "strength", "flow_shift"];
+
+/** Labels of the sampling overrides currently set, e.g. ["CFG 4", "Steps 20"]. */
+export function activeOverrides(a: Advanced): string[] {
+ const label: Record<string, string> = { steps: "Steps", cfg: "CFG", sampler: "Sampler", scheduler: "Scheduler", strength: "Strength", flow_shift: "Flow shift" };
+ return Object.entries(cleanAdvanced(a))
+ .filter(([k]) => SAMPLING_OVERRIDES.includes(k))
+ .map(([k, v]) => `${label[k]} ${v}`);
+}
+
+/** `a` without the session-only sampling overrides (what is kept in saved preferences). */
+export function persistentAdvanced(a: Advanced | undefined): Advanced {
+ const out = cleanAdvanced(a ?? {});
+ for (const k of SAMPLING_OVERRIDES) delete (out as Record<string, unknown>)[k];
+ return out;
+}
+
+function cleanAdvanced(a: Advanced): Advanced {
+ const out: Advanced = {};
+ for (const [k, v] of Object.entries(a)) {
+ if (v !== null && v !== undefined && v !== "") (out as Record<string, unknown>)[k] = v;
+ }
+ return out;
+}
+
+/** Restores composer fields from a stored generation (gallery "reopen"). */
+export function composerFromRecord(g: GenerationRecord, base: Composer): Composer {
+ const req = g.request;
+ const refs: Ref[] = g.references.map((r) => ({ key: newKey(), source: `input:${r.input_id}`, width: r.width, height: r.height, name: `Image ${r.index + 1}` }));
+ const c: Composer = {
+ ...base,
+ prompt: g.prompt,
+ negative: g.negative_prompt ?? "",
+ refs,
+ mask: g.mask_input_id && refs[0] ? { inputId: g.mask_input_id, refKey: refs[0].key } : null,
+ outpaint: g.outpaint ? { ...g.outpaint, units: "pixels" } : null,
+ // Upscales are started from the image toolbar, not the composer.
+ mode: req?.mode && req.mode !== "upscale" ? req.mode : "auto",
+ quality: g.quality ?? base.quality,
+ resolution: req?.resolution ?? base.resolution,
+ aspect: req?.aspect_ratio ?? "auto",
+ seed: null,
+ advanced: req?.advanced ?? {},
+ };
+ if (req?.width && req?.height) {
+ c.customWidth = req.width;
+ c.customHeight = req.height;
+ }
+ return c;
+}
+
+/** A variation: same recipe, new random seed. */
+export function variationRequest(g: GenerationRecord): GenerationRequest | null {
+ if (!g.request) return null;
+ return { ...g.request, seed: null, client: "ui", parent_id: g.id };
+}
+
+export const MODE_LABEL: Record<Mode, string> = {
+ auto: "Auto",
+ generate: "Create",
+ edit: "Edit",
+ inpaint: "Inpaint",
+ outpaint: "Expand",
+ multi_reference: "Combine",
+ upscale: "Upscale",
+};
+
+/** Short truthful status text for a job. */
+export function jobLabel(j: JobView): string {
+ switch (j.status) {
+ case "queued":
+ return j.queue_position > 1 ? `Queued · ${j.queue_position}` : "Queued";
+ case "starting_backend":
+ return "Loading model";
+ case "preparing":
+ return "Preparing";
+ case "saving":
+ return "Saving";
+ case "done":
+ return "Done";
+ case "failed":
+ return "Failed";
+ case "cancelled":
+ return "Cancelled";
+ case "running": {
+ const batch = j.image && j.image[1] > 1 ? ` · ${j.image[0]}/${j.image[1]}` : "";
+ switch (j.stage) {
+ case "preparing":
+ return "Preparing";
+ case "encoding_images":
+ return "Encoding references";
+ case "encoding_prompt":
+ return "Reading prompt";
+ case "generating":
+ return j.step ? `Generating · ${j.step[0]}/${j.step[1]}${batch}` : `Generating${batch}`;
+ case "upscaling":
+ return "Upscaling";
+ case "refining":
+ return j.step ? `Refining · ${j.step[0]}/${j.step[1]}${batch}` : `Refining${batch}`;
+ case "decoding":
+ return "Decoding";
+ case "finishing":
+ return "Finishing";
+ default:
+ return "Working";
+ }
+ }
+ }
+}
+
+/** 0..1 when the backend reports steps, else null (indeterminate). */
+export function jobFraction(j: JobView): number | null {
+ if (j.status !== "running") return null;
+ if (j.stage === "generating" && j.step) return j.step[0] / Math.max(1, j.step[1]);
+ if (j.stage === "decoding" || j.stage === "finishing") return 1;
+ return null;
+}
+
+export function remainingSeconds(j: JobView): number | null {
+ if (j.status !== "running" || !j.step || !j.seconds_per_step) return null;
+ if (j.stage !== "generating") return null;
+ return Math.max(0, (j.step[1] - j.step[0]) * j.seconds_per_step);
+}
+
+// ---------------------------------------------------------------------------------------
+// Upscaling
+// ---------------------------------------------------------------------------------------
+
+/** Server limits for upscale results (8192 px per side, ~40 MP). */
+export const MAX_UPSCALE_SIDE = 8192;
+export const MAX_UPSCALE_AREA = 40_000_000;
+
+export interface UpscaleTarget { key: string; label: string; width: number; height: number }
+
+const fits = (s: Size) => s.width >= 64 && s.height >= 64 && s.width <= MAX_UPSCALE_SIDE && s.height <= MAX_UPSCALE_SIDE && s.width * s.height <= MAX_UPSCALE_AREA;
+
+/** Size with the given width and the source's aspect ratio. */
+export function sizeForWidth(w: number, h: number, width: number): Size {
+ return { width: Math.round(width), height: Math.max(1, Math.round((width * h) / w)) };
+}
+
+/** Upscale presets for a w×h image: 2x, 4K (3840 long side) and the original source
+ * size of an edit, when each is a real enlargement within the limits. */
+export function upscaleTargets(w: number, h: number, source?: Size | null): UpscaleTarget[] {
+ const out: UpscaleTarget[] = [];
+ const add = (key: string, label: string, s: Size) => {
+ if (fits(s) && s.width * s.height > w * h * 1.05 && !out.some((o) => o.width === s.width && o.height === s.height)) out.push({ key, label, ...s });
+ };
+ add("2x", "2×", { width: w * 2, height: h * 2 });
+ const k4 = w >= h ? sizeForWidth(w, h, 3840) : { width: Math.round((3840 * w) / h), height: 3840 };
+ add("4k", "4K", k4);
+ if (source) add("source", "Source size", source);
+ return out;
+}
+
+export function upscaleRequest(source: string, target: Size, method: UpscaleMethod, parentId?: string | null): GenerationRequest {
+ return {
+ prompt: "",
+ mode: "upscale",
+ images: [source],
+ quality: "balanced",
+ resolution: "auto",
+ preserve_dimensions: true,
+ advanced: {},
+ client: "ui",
+ parent_id: parentId ?? null,
+ upscale: { method, width: target.width, height: target.height },
+ };
+}
+
+const dims = (s: Size) => `${s.width}×${s.height}`;
+/** ESRGAN models offered for enlargement: [file stem, label]. Mirrors UPSCALER_CHOICES in config.rs. */
+export const UPSCALERS: [string, string][] = [
+ ["4x-UltraSharp", "UltraSharp"],
+ ["4x_NMKD-Superscale-SP_178000_G", "Superscale-SP"],
+];
+
+/** Short name of the upscaler that ran or will run: "UltraSharp", "Superscale-SP", "Lanczos"... */
+export const upscalerLabel = (name: string | null | undefined) => (!name || name === "Lanczos" ? "Lanczos" : UPSCALERS.find(([n]) => n === name)?.[1] ?? name);
+
+/** "1376×768 → 5120×2880 (UltraSharp)" for the Details panel; two-pass records from
+ * older versions read "1376×768 → refined 2048×1152 (Fast, 6 steps, UltraSharp) → ...". */
+export function pipelineSummary(g: GenerationRecord): string | null {
+ const p = g.pipeline;
+ if (!p) return null;
+ const parts: string[] = [];
+ if (p.base) {
+ const mode = p.refine === "best" ? "Best" : "Fast";
+ parts.push(dims(p.base), `refined ${g.working_width}×${g.working_height} (${mode}, ${p.refine_steps ?? "?"} steps, ${upscalerLabel(p.hires_upscaler)})`);
+ }
+ if (p.enlarged_with && p.enlarged_from) {
+ if (!parts.length) parts.push(dims(p.enlarged_from));
+ parts.push(`${g.width}×${g.height} (${upscalerLabel(p.enlarged_with)})`);
+ }
+ return parts.length ? parts.join(" → ") : null;
+}
+
+/** Short description of what a plan will do, for the Advanced panel. */
+export function planPipeline(plan: Plan): string {
+ const out = dims(plan.output);
+ const enlarge = plan.output.width * plan.output.height > plan.content.width * plan.content.height * 1.21;
+ const via = upscalerLabel(plan.upscaler);
+ if (plan.upscale?.method === "quick") return `${dims(plan.upscale.source)} → ${out} (${via})`;
+ const work = dims(plan.working);
+ return enlarge ? `${work} render → ${out} output (${via})` : `${work} render → ${out} output`;
+}
+
+export function formatDuration(s: number): string {
+ if (s < 60) return `${Math.max(1, Math.round(s))}s`;
+ const m = Math.floor(s / 60);
+ const r = Math.round(s % 60);
+ return r ? `${m}m ${r}s` : `${m}m`;
+}
+
+export const ASPECTS = ["auto", "1:1", "4:3", "3:4", "16:9", "9:16", "custom"] as const;
+
+/** Expansion presets in source pixels. */
+export function expansionPreset(kind: "left" | "right" | "top" | "bottom" | "landscape" | "portrait" | "square", w: number, h: number, cur: OutpaintSpec): OutpaintSpec {
+ const base: OutpaintSpec = { left: cur.left, right: cur.right, top: cur.top, bottom: cur.bottom, units: "pixels" };
+ const qx = Math.round(w * 0.25);
+ const qy = Math.round(h * 0.25);
+ const toAspect = (a: number): OutpaintSpec => {
+ if (w / h < a) {
+ const extra = Math.max(0, Math.round(h * a) - w);
+ return { left: Math.floor(extra / 2), right: extra - Math.floor(extra / 2), top: 0, bottom: 0, units: "pixels" };
+ }
+ const extra = Math.max(0, Math.round(w / a) - h);
+ return { left: 0, right: 0, top: Math.floor(extra / 2), bottom: extra - Math.floor(extra / 2), units: "pixels" };
+ };
+ switch (kind) {
+ case "left":
+ return { ...base, left: base.left + qx };
+ case "right":
+ return { ...base, right: base.right + qx };
+ case "top":
+ return { ...base, top: base.top + qy };
+ case "bottom":
+ return { ...base, bottom: base.bottom + qy };
+ case "landscape":
+ return toAspect(16 / 9);
+ case "portrait":
+ return toAspect(9 / 16);
+ case "square":
+ return toAspect(1);
+ }
+}
+
+/** Expansion in pixels regardless of units. */
+export function expansionPixels(o: OutpaintSpec, w: number, h: number) {
+ const f = (v: number, b: number) => (o.units === "percent" ? Math.round((b * v) / 100) : Math.round(v));
+ return { left: f(o.left, w), right: f(o.right, w), top: f(o.top, h), bottom: f(o.bottom, h) };
+}
+
+// ---------------------------------------------------------------------------------------
+// Before / after comparison
+// ---------------------------------------------------------------------------------------
+
+export type CompareMode = "off" | "slider" | "flicker" | "diff";
+
+/** The image a result was made from and where it sits inside the result, as fractions of the
+ * result's width/height (an expanded image sits inside a larger canvas). */
+export interface CompareBase {
+ inputId: string;
+ rect: { x: number; y: number; w: number; h: number };
+}
+
+export function compareBase(g: GenerationRecord): CompareBase | null {
+ const r = g.references[0];
+ // A new image or a combination of several has no single "before".
+ if (!r || !["edit", "inpaint", "outpaint", "upscale"].includes(g.mode)) return null;
+ const o = g.outpaint;
+ if (g.mode === "outpaint" && o) {
+ // Expansion is in source pixels; the result is the source plus the expansion.
+ const W = r.width + o.left + o.right;
+ const H = r.height + o.top + o.bottom;
+ return { inputId: r.input_id, rect: { x: o.left / W, y: o.top / H, w: r.width / W, h: r.height / H } };
+ }
+ return { inputId: r.input_id, rect: { x: 0, y: 0, w: 1, h: 1 } };
+}
+
+/** Per-pixel change between two equally sized RGBA buffers: the dimmed result in grey with
+ * changed pixels in red (stronger = bigger change). Pixels the "before" does not cover
+ * (alpha 0, e.g. expanded areas) count as changed. Returns the changed share of the image. */
+export function diffPixels(after: Uint8ClampedArray, before: Uint8ClampedArray, out: Uint8ClampedArray, threshold = 24): number {
+ let changed = 0;
+ const n = after.length / 4;
+ for (let i = 0; i < after.length; i += 4) {
+ const grey = 0.3 * (0.299 * after[i] + 0.587 * after[i + 1] + 0.114 * after[i + 2]);
+ const d = before[i + 3] < 128 ? 255 : Math.max(Math.abs(after[i] - before[i]), Math.abs(after[i + 1] - before[i + 1]), Math.abs(after[i + 2] - before[i + 2]));
+ const a = d <= threshold ? 0 : Math.min(1, 0.35 + (d - threshold) / 96);
+ if (a > 0) changed++;
+ out[i] = grey + (255 - grey) * a;
+ out[i + 1] = grey + (64 - grey) * a;
+ out[i + 2] = grey + (64 - grey) * a;
+ out[i + 3] = 255;
+ }
+ return n ? changed / n : 0;
+}
diff --git a/src/lib/native.ts b/src/lib/native.ts
new file mode 100644
index 0000000..a5eea1a
--- /dev/null
+++ b/src/lib/native.ts
@@ -0,0 +1,45 @@
+// Native integrations through the Tauri shell.
+
+import { invoke } from "@tauri-apps/api/core";
+import { getCurrentWindow } from "@tauri-apps/api/window";
+import { ask, open, save } from "@tauri-apps/plugin-dialog";
+
+export interface Connection { baseUrl: string; token: string; version: string }
+
+export const native = {
+ connect: () => invoke<Connection>("connect"),
+ copyImage: (path: string) => invoke<void>("copy_image", { path }),
+ readClipboardImage: async (): Promise<Uint8Array | null> => {
+ const buf = await invoke<ArrayBuffer>("read_clipboard_image");
+ const bytes = new Uint8Array(buf);
+ return bytes.length ? bytes : null;
+ },
+ reveal: (path: string) => invoke<void>("reveal", { path }),
+ openFolder: (path: string) => invoke<void>("open_folder", { path }),
+ dataFolder: () => invoke<string>("data_folder"),
+ pickImages: async (): Promise<string[]> => {
+ const r = await open({ multiple: true, directory: false, filters: [{ name: "Images", extensions: ["png", "jpg", "jpeg", "webp", "bmp", "gif", "tif", "tiff", "heic", "heif"] }] });
+ if (!r) return [];
+ return Array.isArray(r) ? r : [r];
+ },
+ pickFile: async (extensions: string[], defaultPath?: string): Promise<string | null> => {
+ const r = await open({ multiple: false, directory: false, defaultPath, filters: [{ name: "Model", extensions }] });
+ return typeof r === "string" ? r : null;
+ },
+ pickFolder: async (defaultPath?: string): Promise<string | null> => {
+ const r = await open({ multiple: false, directory: true, defaultPath });
+ return typeof r === "string" ? r : null;
+ },
+ confirm: (message: string, title: string) => ask(message, { title, kind: "warning" }),
+ isFullscreen: () => getCurrentWindow().isFullscreen(),
+ setFullscreen: (on: boolean) => getCurrentWindow().setFullscreen(on),
+ saveAs: (defaultName: string) =>
+ save({
+ defaultPath: defaultName,
+ filters: [
+ { name: "PNG", extensions: ["png"] },
+ { name: "JPEG", extensions: ["jpg"] },
+ { name: "WebP", extensions: ["webp"] },
+ ],
+ }),
+};
diff --git a/src/lib/store.ts b/src/lib/store.ts
new file mode 100644
index 0000000..f74c173
--- /dev/null
+++ b/src/lib/store.ts
@@ -0,0 +1,285 @@
+// Minimal global store (useSyncExternalStore) — no extra dependencies.
+
+import { useSyncExternalStore } from "react";
+import { api, ApiError, subscribe } from "./api";
+import { buildRequest, emptyComposer, newKey, persistentAdvanced, refFromGen, refFromInput, type CompareMode, type Composer } from "./logic";
+import type { AppErrorBody, GenerationRecord, GenerationRequest, InputRecord, JobView, ServerState, StatusResponse } from "./types";
+
+export type Overlay = null | "gallery" | "settings" | "inpaint" | "expand";
+
+export interface SessionItem {
+ key: string;
+ kind: "gen" | "input" | "job";
+ gen?: GenerationRecord;
+ input?: InputRecord;
+ jobId?: string;
+ /** Request that produced a pending job (for "Try again"). */
+ request?: GenerationRequest;
+}
+
+export interface Toast {
+ id: string;
+ message: string;
+ suggestion?: string;
+ detail?: string;
+ kind: "error" | "info";
+}
+
+export interface State {
+ connected: boolean;
+ connectError: string | null;
+ server: { state: ServerState; owned: boolean; error: AppErrorBody | null };
+ status: StatusResponse | null;
+ session: SessionItem[];
+ selected: string | null;
+ jobs: Record<string, JobView>;
+ composer: Composer;
+ overlay: Overlay;
+ toasts: Toast[];
+ galleryVersion: number;
+ needsSetup: boolean;
+ /** Before/after view for results made from another image; kept while switching results. */
+ compare: CompareMode;
+ /** Flicker period in ms. */
+ flickerMs: number;
+}
+
+const PREFS_KEY = "qls.prefs.v1";
+
+function loadPrefs(): Partial<Composer> {
+ try {
+ const p: Partial<Composer> = JSON.parse(localStorage.getItem(PREFS_KEY) || "{}");
+ // Older versions also saved CFG/steps/strength, which then overrode every preset.
+ return { ...p, advanced: persistentAdvanced(p.advanced) };
+ } catch {
+ return {};
+ }
+}
+
+function savePrefs(c: Composer) {
+ try {
+ const { quality, resolution, aspect, customWidth, customHeight } = c;
+ const advanced = persistentAdvanced(c.advanced);
+ localStorage.setItem(PREFS_KEY, JSON.stringify({ quality, resolution, aspect, customWidth, customHeight, advanced }));
+ } catch {
+ /* storage unavailable */
+ }
+}
+
+let state: State = {
+ connected: false,
+ connectError: null,
+ server: { state: "stopped", owned: false, error: null },
+ status: null,
+ session: [],
+ selected: null,
+ jobs: {},
+ composer: emptyComposer(loadPrefs()),
+ overlay: null,
+ toasts: [],
+ galleryVersion: 0,
+ needsSetup: false,
+ compare: "off",
+ flickerMs: 500,
+};
+
+const listeners = new Set<() => void>();
+
+export function getState() {
+ return state;
+}
+
+export function setState(patch: Partial<State> | ((s: State) => Partial<State>)) {
+ const p = typeof patch === "function" ? patch(state) : patch;
+ state = { ...state, ...p };
+ if (p.composer) savePrefs(state.composer);
+ listeners.forEach((l) => l());
+}
+
+export function useStore<T>(sel: (s: State) => T): T {
+ return useSyncExternalStore(
+ (l) => {
+ listeners.add(l);
+ return () => listeners.delete(l);
+ },
+ () => sel(state),
+ );
+}
+
+export function updateComposer(patch: Partial<Composer>) {
+ setState((s) => ({ composer: { ...s.composer, ...patch } }));
+}
+
+// ---------------------------------------------------------------------------------------
+// Toasts
+// ---------------------------------------------------------------------------------------
+
+export function toastError(e: unknown) {
+ const body: AppErrorBody = e instanceof ApiError ? e.body : { code: "internal", message: e instanceof Error ? e.message : String(e) };
+ pushToast({ id: newKey(), message: body.message, suggestion: body.suggestion, detail: body.detail, kind: "error" });
+}
+
+export function toastInfo(message: string) {
+ pushToast({ id: newKey(), message, kind: "info" });
+}
+
+function pushToast(t: Toast) {
+ setState((s) => ({ toasts: [...s.toasts.slice(-3), t] }));
+ if (t.kind === "info") window.setTimeout(() => dismissToast(t.id), 3500);
+}
+
+export function dismissToast(id: string) {
+ setState((s) => ({ toasts: s.toasts.filter((t) => t.id !== id) }));
+}
+
+// ---------------------------------------------------------------------------------------
+// Connection and events
+// ---------------------------------------------------------------------------------------
+
+let unsub: (() => void) | null = null;
+
+export async function refreshStatus() {
+ try {
+ const st = await api.status();
+ setState({ status: st, server: { state: st.server.state, owned: st.server.owned, error: st.server.error } });
+ return st;
+ } catch {
+ return null;
+ }
+}
+
+export function startEvents() {
+ unsub?.();
+ unsub = subscribe(
+ (ev) => {
+ if (ev.type === "job") onJob(ev.job);
+ else if (ev.type === "server") setState({ server: { state: ev.state, owned: ev.owned, error: ev.error } });
+ else if (ev.type === "gallery") setState((s) => ({ galleryVersion: s.galleryVersion + 1 }));
+ },
+ (ok) => {
+ setState({ connected: ok });
+ if (ok) {
+ // Catch up on anything missed while disconnected.
+ api.jobs().then((js) => js.forEach(onJob)).catch(() => {});
+ refreshStatus();
+ }
+ },
+ );
+}
+
+function onJob(job: JobView) {
+ setState((s) => {
+ if (!s.session.some((i) => i.jobId === job.id) && !s.jobs[job.id]) {
+ // A job from another client (e.g. MCP): track it but do not add it to this session.
+ return { jobs: { ...s.jobs, [job.id]: job } };
+ }
+ const jobs = { ...s.jobs, [job.id]: job };
+ if (job.status !== "done") return { jobs };
+ // Replace the pending item with one item per result.
+ const idx = s.session.findIndex((i) => i.jobId === job.id && i.kind === "job");
+ if (idx < 0) return { jobs };
+ const results: SessionItem[] = job.results.map((g) => ({ key: newKey(), kind: "gen", gen: g, jobId: job.id }));
+ const session = [...s.session.slice(0, idx), ...results, ...s.session.slice(idx + 1)];
+ const wasSelected = s.selected === s.session[idx].key;
+ return { jobs, session, selected: wasSelected && results[0] ? results[0].key : s.selected };
+ });
+ if (job.status === "failed" && job.error) toastError(new ApiError(job.error, 500));
+}
+
+// ---------------------------------------------------------------------------------------
+// Actions
+// ---------------------------------------------------------------------------------------
+
+export function addSessionItem(item: SessionItem, select = true) {
+ setState((s) => ({ session: [...s.session, item], selected: select ? item.key : s.selected }));
+}
+
+export function addInputs(records: InputRecord[]) {
+ if (!records.length) return;
+ setState((s) => {
+ const refs = [...s.composer.refs, ...records.map(refFromInput)].slice(0, 10);
+ const items: SessionItem[] = records.map((r) => ({ key: newKey(), kind: "input", input: r }));
+ return {
+ // The first image sets the shape again (a ratio picked for text-to-image would distort it).
+ composer: { ...s.composer, refs, outpaint: null, aspect: s.composer.refs.length ? s.composer.aspect : "auto" },
+ session: [...s.session, ...items],
+ selected: items[items.length - 1].key,
+ };
+ });
+ if (getState().composer.refs.length >= 10) toastInfo("Up to 10 reference images are supported.");
+}
+
+export async function submitRequest(req: GenerationRequest, opts: { clearComposer?: boolean } = {}) {
+ try {
+ const job = await api.submit(req);
+ const item: SessionItem = { key: newKey(), kind: "job", jobId: job.id, request: req };
+ setState((s) => ({
+ jobs: { ...s.jobs, [job.id]: job },
+ session: [...s.session, item],
+ selected: item.key,
+ composer: opts.clearComposer ? { ...s.composer, seed: null } : s.composer,
+ }));
+ } catch (e) {
+ toastError(e);
+ }
+}
+
+export async function submitComposer() {
+ const s = getState();
+ const parent = s.session.find((i) => i.key === s.selected)?.gen?.id ?? null;
+ const req = buildRequest(s.composer, parent);
+ if (!req.prompt) {
+ toastInfo("Describe what to create or change.");
+ return;
+ }
+ await submitRequest(req, { clearComposer: true });
+}
+
+export async function cancelJob(jobId: string) {
+ try {
+ const j = await api.cancel(jobId);
+ onJob(j);
+ } catch (e) {
+ toastError(e);
+ }
+}
+
+/** Use a result or input as the (only) image to edit. */
+export function editItem(item: SessionItem) {
+ const ref = item.gen ? refFromGen(item.gen) : item.input ? refFromInput(item.input) : null;
+ if (!ref) return;
+ updateComposer({ refs: [ref], mask: null, outpaint: null, mode: "auto", aspect: "auto" });
+ focusPrompt();
+}
+
+/** Append as an additional reference. */
+export function addAsReference(item: SessionItem) {
+ const ref = item.gen ? refFromGen(item.gen) : item.input ? refFromInput(item.input) : null;
+ if (!ref) return;
+ setState((s) => ({ composer: { ...s.composer, refs: [...s.composer.refs, ref].slice(0, 10), outpaint: null, aspect: s.composer.refs.length ? s.composer.aspect : "auto" } }));
+ toastInfo(`Added as image ${Math.min(10, getState().composer.refs.length)}`);
+}
+
+/** Open the inpaint / expand editor on an item (it becomes image 1). */
+export function openEditorFor(item: SessionItem, overlay: "inpaint" | "expand") {
+ const s = getState();
+ const first = s.composer.refs[0];
+ const src = item.gen ? `gen:${item.gen.id}` : item.input ? `input:${item.input.id}` : null;
+ if (!first || first.source !== src) editItem(item);
+ setState({ overlay });
+}
+
+export function focusPrompt() {
+ window.setTimeout(() => document.getElementById("prompt")?.focus(), 30);
+}
+
+export function removeSessionItem(key: string) {
+ setState((s) => {
+ const session = s.session.filter((i) => i.key !== key);
+ return { session, selected: s.selected === key ? session[session.length - 1]?.key ?? null : s.selected };
+ });
+}
+
+export function selectedItem(s: State): SessionItem | null {
+ return s.session.find((i) => i.key === s.selected) ?? null;
+}
diff --git a/src/lib/types.ts b/src/lib/types.ts
new file mode 100644
index 0000000..af7d3fc
--- /dev/null
+++ b/src/lib/types.ts
@@ -0,0 +1,224 @@
+// Mirrors the qls-service JSON contract (crates/qls-core).
+
+export type Mode = "auto" | "generate" | "edit" | "inpaint" | "outpaint" | "multi_reference" | "upscale";
+export type ResolvedMode = Exclude<Mode, "auto">;
+export type Quality = "fast" | "balanced" | "quality";
+export type ResolutionMode = "auto" | "source" | "1k" | "1.5k" | "2k" | "custom";
+export type OutputFormat = "png" | "jpeg" | "webp";
+export type Units = "pixels" | "percent";
+/** Effort of a Detailed upscale ("off" is legacy and behaves like fast). */
+export type RefineMode = "off" | "fast" | "best";
+export type UpscaleMethod = "quick" | "detailed";
+
+export interface UpscaleSpec { method: UpscaleMethod; scale?: number | null; width?: number | null; height?: number | null }
+
+export interface Size { width: number; height: number }
+export interface Rect { x: number; y: number; width: number; height: number }
+
+export interface OutpaintSpec { left: number; right: number; top: number; bottom: number; units: Units }
+
+export interface Advanced {
+ steps?: number | null;
+ cfg?: number | null;
+ sampler?: string | null;
+ scheduler?: string | null;
+ strength?: number | null;
+ batch_count?: number | null;
+ output_format?: OutputFormat | null;
+ vae_tiling?: boolean | null;
+ refine?: RefineMode | null;
+ /** Keep a HEIC source's HDR gain map (Ultra HDR JPEG); null = on. */
+ hdr?: boolean | null;
+}
+
+export interface GenerationRequest {
+ prompt: string;
+ negative_prompt?: string | null;
+ mode: Mode;
+ images: string[];
+ mask?: string | null;
+ outpaint?: OutpaintSpec | null;
+ quality: Quality;
+ resolution: ResolutionMode;
+ aspect_ratio?: string | null;
+ width?: number | null;
+ height?: number | null;
+ seed?: number | null;
+ preserve_dimensions?: boolean;
+ advanced: Advanced;
+ client?: string;
+ parent_id?: string | null;
+ upscale?: UpscaleSpec | null;
+}
+
+export interface WorkingCanvas { source: Size; content: Size; canvas: Size; content_offset: [number, number]; scale: number }
+export interface RefPlan { index: number; source: Size; canvas: WorkingCanvas }
+
+export interface Plan {
+ mode: ResolvedMode;
+ auto_mode: boolean;
+ mode_reason: string;
+ output: Size;
+ working: Size;
+ content: Rect;
+ steps: number;
+ cfg: number;
+ sampler: string;
+ scheduler: string | null;
+ strength: number | null;
+ batch_count: number;
+ vae_tiling: boolean;
+ references: RefPlan[];
+ aspect_label: string;
+ notes: string[];
+ optimized_for_vram: boolean;
+ estimated_seconds: number;
+ cache_threshold: number | null;
+ upscaler: string | null;
+ upscale: { method: UpscaleMethod; source: Size } | null;
+}
+
+export interface AppErrorBody { code: string; message: string; suggestion?: string; detail?: string }
+
+export interface ReferenceRecord { index: number; input_id: string; original_path?: string | null; width: number; height: number }
+
+export interface PipelineRecord {
+ base: Size | null;
+ refine: RefineMode | null;
+ refine_steps: number | null;
+ refine_denoise: number | null;
+ hires_upscaler: string | null;
+ cache_threshold: number | null;
+ enlarged_with: string | null;
+ enlarged_from: Size | null;
+}
+
+export interface GenerationRecord {
+ id: string;
+ created_at: string;
+ mode: ResolvedMode;
+ prompt: string;
+ negative_prompt: string;
+ seed: number;
+ width: number;
+ height: number;
+ working_width: number;
+ working_height: number;
+ model: string;
+ sampler: string;
+ scheduler: string | null;
+ steps: number;
+ cfg: number;
+ strength: number | null;
+ quality: Quality;
+ resolution: ResolutionMode;
+ references: ReferenceRecord[];
+ mask_input_id: string | null;
+ outpaint: { left: number; right: number; top: number; bottom: number } | null;
+ file_path: string;
+ extra_paths: string[];
+ favorite: boolean;
+ parent_id: string | null;
+ duration_ms: number;
+ notes: string[];
+ request: GenerationRequest | null;
+ pipeline?: PipelineRecord | null;
+}
+
+export type JobStatus = "queued" | "starting_backend" | "preparing" | "running" | "saving" | "done" | "failed" | "cancelled";
+export type BackendStage = "preparing" | "encoding_images" | "encoding_prompt" | "generating" | "upscaling" | "refining" | "decoding" | "finishing";
+
+export interface JobView {
+ id: string;
+ status: JobStatus;
+ stage: BackendStage | null;
+ step: [number, number] | null;
+ image: [number, number] | null;
+ seconds_per_step: number | null;
+ queue_position: number;
+ created_at: string;
+ started_at: string | null;
+ finished_at: string | null;
+ prompt: string;
+ plan: Plan | null;
+ seed: number | null;
+ results: GenerationRecord[];
+ error: AppErrorBody | null;
+ notes: string[];
+ detailed_progress: boolean;
+}
+
+export interface InputRecord {
+ id: string;
+ path: string;
+ original_name: string | null;
+ original_path: string | null;
+ width: number;
+ height: number;
+ format: string;
+ has_alpha: boolean;
+ /** HEIC with an HDR gain map. */
+ hdr?: boolean;
+}
+
+export type ServerState = "stopped" | "starting" | "ready" | "error";
+
+export interface StatusResponse {
+ service: { version: string; pid: number; uptime_s: number };
+ server: { state: ServerState; owned: boolean; pid: number | null; port: number; model: string | null; model_loaded: boolean; error: AppErrorBody | null };
+ profile: { id: string; display_name: string };
+ gpu: { name: string; memory_total_mib: number; memory_used_mib: number; memory_free_mib: number; driver_version: string } | null;
+ active_job: JobView | null;
+ queue: { queued: number; jobs: JobView[] };
+ upscaler?: { model: string; available: boolean; refine_mode: RefineMode };
+ setup_complete: boolean;
+}
+
+export interface Check { id: string; label: string; ok: boolean; detail: string }
+export interface SetupReport { ready: boolean; checks: Check[]; devices: [string, string][]; backend_version: string | null }
+
+export type TextEncoderPlacement = "ram" | "gpu" | "cpu" | "auto";
+
+export interface ModelProfile {
+ id: string;
+ displayName: string;
+ diffusionModel: string;
+ vae: string;
+ textEncoder: string;
+ visionProjector: string | null;
+ backendArgs: string[];
+ recommendedSettings: Record<string, unknown>;
+ capabilities: Record<string, boolean>;
+}
+
+export interface AppConfig {
+ schemaVersion: number;
+ sdcppDir: string;
+ serverPort: number;
+ servicePort: number;
+ activeProfile: string;
+ profiles: ModelProfile[];
+ device: string;
+ textEncoderPlacement: TextEncoderPlacement;
+ vramReserveGib: number;
+ flashAttention: boolean;
+ sageAttention: boolean;
+ vaeTileSize: number;
+ prefixCacheType: string;
+ eagerLoad: boolean;
+ upscalersDir: string | null;
+ upscalerModel: string;
+ upscaleTileSize: number;
+ refineMode: RefineMode;
+ extraServerArgs: string[];
+ outputDir: string;
+ keepServerRunning: boolean;
+ idleUnloadMinutes: number;
+ setupComplete: boolean;
+ ui: Record<string, unknown>;
+}
+
+export type ServiceEvent =
+ | { type: "job"; job: JobView }
+ | { type: "server"; state: ServerState; owned: boolean; error: AppErrorBody | null }
+ | { type: "gallery"; id: string; change: "added" | "updated" | "deleted" };
diff --git a/src/main.tsx b/src/main.tsx
new file mode 100644
index 0000000..693ac2e
--- /dev/null
+++ b/src/main.tsx
@@ -0,0 +1,10 @@
+import { StrictMode } from "react";
+import { createRoot } from "react-dom/client";
+import App from "./App";
+import "./styles.css";
+
+createRoot(document.getElementById("root")!).render(
+ <StrictMode>
+ <App />
+ </StrictMode>,
+);
diff --git a/src/styles.css b/src/styles.css
new file mode 100644
index 0000000..7613cd8
--- /dev/null
+++ b/src/styles.css
@@ -0,0 +1,287 @@
+@import "@fontsource-variable/inter";
+
+:root {
+ --bg: #ffffff;
+ --surface: #f4f4f4;
+ --surface-2: #e9e9e9;
+ --surface-3: #dcdcdc;
+ --border: #e4e4e4;
+ --text: #0d0d0d;
+ --text-2: #5c5c5c;
+ --text-3: #8e8e8e;
+ --invert-bg: #0d0d0d;
+ --invert-text: #ffffff;
+ --scrim: rgba(255, 255, 255, 0.82);
+ --shadow: 0 1px 2px rgba(0, 0, 0, 0.04), 0 6px 24px rgba(0, 0, 0, 0.08);
+ --checker: #f0f0f0;
+ --radius: 14px;
+ --font: "Inter Variable", "Inter", "Segoe UI Variable Text", "Segoe UI", system-ui, sans-serif;
+ color-scheme: light;
+}
+
+@media (prefers-color-scheme: dark) {
+ :root {
+ --bg: #161616;
+ --surface: #222222;
+ --surface-2: #2c2c2c;
+ --surface-3: #383838;
+ --border: #2c2c2c;
+ --text: #ececec;
+ --text-2: #a3a3a3;
+ --text-3: #6f6f6f;
+ --invert-bg: #ececec;
+ --invert-text: #111111;
+ --scrim: rgba(22, 22, 22, 0.85);
+ --shadow: 0 1px 2px rgba(0, 0, 0, 0.3), 0 8px 28px rgba(0, 0, 0, 0.45);
+ --checker: #1f1f1f;
+ color-scheme: dark;
+ }
+}
+
+* { box-sizing: border-box; }
+html, body, #root { height: 100%; margin: 0; }
+body {
+ background: var(--bg);
+ color: var(--text);
+ font-family: var(--font);
+ font-size: 14px;
+ line-height: 1.45;
+ -webkit-font-smoothing: antialiased;
+ user-select: none;
+ overflow: hidden;
+}
+input, textarea, select, button { font: inherit; color: inherit; }
+textarea, input[type="text"], input[type="number"] { user-select: text; }
+button { cursor: pointer; background: none; border: 0; padding: 0; }
+button:disabled { cursor: default; opacity: 0.4; }
+:focus-visible { outline: 2px solid var(--text); outline-offset: 2px; }
+::selection { background: var(--surface-3); }
+svg { display: block; flex: none; }
+
+.app { display: flex; flex-direction: column; height: 100%; }
+
+/* ---------- top bar ---------- */
+.topbar { height: 48px; display: flex; align-items: center; justify-content: space-between; padding: 0 12px 0 16px; flex: none; }
+.brand { display: flex; align-items: center; gap: 10px; font-weight: 600; letter-spacing: -0.01em; }
+.status { display: flex; align-items: center; gap: 8px; color: var(--text-2); font-size: 13px; font-weight: 400; }
+.dot { width: 7px; height: 7px; border-radius: 50%; background: var(--text-3); }
+.dot.ready { background: var(--text); }
+.dot.busy { background: transparent; border: 1.5px solid var(--text); animation: pulse 1.2s ease-in-out infinite; }
+.dot.error { background: transparent; border: 1.5px solid var(--text-2); }
+@keyframes pulse { 50% { opacity: 0.3; } }
+.toolbar { display: flex; gap: 2px; }
+
+.icon-btn { width: 34px; height: 34px; border-radius: 10px; display: grid; place-items: center; color: var(--text-2); }
+.icon-btn:hover:not(:disabled) { background: var(--surface); color: var(--text); }
+.icon-btn.active { background: var(--surface-2); color: var(--text); }
+.icon-btn.sm { width: 28px; height: 28px; border-radius: 8px; }
+.icon-btn.has-badge { position: relative; }
+.override-dot { position: absolute; top: 5px; right: 5px; width: 7px; height: 7px; border-radius: 50%; background: var(--text); box-shadow: 0 0 0 2px var(--bg); }
+
+/* ---------- main ---------- */
+.main { flex: 1; display: flex; min-height: 0; position: relative; }
+.stage { flex: 1; min-width: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 8px 24px 12px; position: relative; }
+.stage-frame { position: relative; flex: 1; min-height: 0; width: 100%; display: flex; align-items: center; justify-content: center; }
+.stage-img { max-width: 100%; max-height: 100%; object-fit: contain; border-radius: 6px; background-image: conic-gradient(var(--checker) 25%, transparent 0 50%, var(--checker) 0 75%, transparent 0); background-size: 16px 16px; }
+.stage-caption { margin-top: 10px; color: var(--text-3); font-size: 12px; display: flex; gap: 12px; align-items: center; min-height: 18px; text-align: center; max-width: 720px; }
+.stage-caption .prompt { color: var(--text-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 520px; }
+
+.actions { display: flex; gap: 2px; margin-top: 8px; padding: 3px; border-radius: 12px; }
+.actions .sep { width: 1px; background: var(--border); margin: 6px 4px; }
+
+.empty { display: flex; flex-direction: column; align-items: center; gap: 14px; color: var(--text-3); text-align: center; }
+.empty h1 { font-size: 26px; font-weight: 600; letter-spacing: -0.02em; color: var(--text); margin: 0; }
+.empty p { margin: 0; font-size: 14px; }
+.empty .hint { display: flex; gap: 18px; font-size: 12px; margin-top: 4px; }
+.empty .hint span { display: flex; gap: 6px; align-items: center; }
+
+/* pending job */
+.pending { position: relative; max-width: 100%; max-height: 100%; border-radius: 6px; background: var(--surface); overflow: hidden; display: grid; place-items: center; }
+.pending::after { content: ""; position: absolute; inset: 0; background: linear-gradient(100deg, transparent 30%, rgba(127,127,127,0.08) 50%, transparent 70%); background-size: 200% 100%; animation: sheen 1.8s linear infinite; }
+@keyframes sheen { from { background-position: 150% 0; } to { background-position: -50% 0; } }
+.pending-info { position: relative; z-index: 1; display: flex; flex-direction: column; align-items: center; gap: 12px; color: var(--text-2); font-size: 13px; padding: 24px; text-align: center; }
+.progress { width: 220px; height: 3px; background: var(--surface-3); border-radius: 2px; overflow: hidden; position: relative; }
+.progress > i { position: absolute; inset: 0 auto 0 0; background: var(--text); border-radius: 2px; transition: width 0.3s; }
+.progress.indeterminate > i { width: 30%; animation: indet 1.3s ease-in-out infinite; }
+@keyframes indet { from { left: -30%; } to { left: 100%; } }
+.notes { color: var(--text-3); font-size: 12px; max-width: 360px; }
+.failed { display: flex; flex-direction: column; align-items: center; gap: 10px; max-width: 460px; text-align: center; color: var(--text-2); }
+.failed strong { color: var(--text); font-weight: 600; }
+
+/* history rail */
+.rail { width: 84px; flex: none; overflow-y: auto; padding: 8px 12px 12px 4px; display: flex; flex-direction: column; gap: 8px; scrollbar-width: none; }
+.rail::-webkit-scrollbar { display: none; }
+.thumb { width: 64px; height: 64px; border-radius: 10px; overflow: hidden; background: var(--surface); position: relative; flex: none; outline: 2px solid transparent; outline-offset: 2px; display: grid; place-items: center; color: var(--text-3); }
+.thumb img { width: 100%; height: 100%; object-fit: cover; }
+.thumb.sel { outline-color: var(--text); }
+.thumb .tag { position: absolute; left: 4px; bottom: 4px; font-size: 10px; background: var(--scrim); color: var(--text); padding: 0 5px; border-radius: 4px; }
+
+/* ---------- composer ---------- */
+.composer-wrap { flex: none; padding: 0 24px 18px; display: flex; justify-content: center; }
+.composer { width: 100%; max-width: 820px; background: var(--surface); border-radius: 22px; padding: 10px 10px 8px 14px; position: relative; }
+.composer.drag { outline: 2px dashed var(--text-2); outline-offset: 3px; }
+.refs { display: flex; gap: 8px; padding: 4px 0 8px; overflow-x: auto; scrollbar-width: none; }
+.ref { position: relative; width: 58px; height: 58px; border-radius: 10px; overflow: visible; flex: none; cursor: grab; }
+.ref img { width: 100%; height: 100%; object-fit: cover; border-radius: 10px; display: block; background: var(--surface-2); }
+.ref .num { position: absolute; left: 4px; top: 4px; min-width: 16px; height: 16px; padding: 0 4px; border-radius: 8px; background: var(--invert-bg); color: var(--invert-text); font-size: 10px; font-weight: 600; display: grid; place-items: center; }
+.ref .rm { position: absolute; right: -6px; top: -6px; width: 20px; height: 20px; border-radius: 50%; background: var(--bg); color: var(--text); box-shadow: var(--shadow); display: none; place-items: center; }
+.ref:hover .rm { display: grid; }
+.ref .badge { position: absolute; right: 4px; bottom: 4px; width: 18px; height: 18px; border-radius: 5px; background: var(--scrim); display: grid; place-items: center; }
+.ref.dragging { opacity: 0.35; }
+.ref.drop-before::before { content: ""; position: absolute; left: -5px; top: 4px; bottom: 4px; width: 2px; background: var(--text); border-radius: 1px; }
+.chip { display: inline-flex; align-items: center; gap: 6px; height: 28px; padding: 0 10px; border-radius: 14px; background: var(--surface-2); font-size: 12px; color: var(--text); }
+.chip button { color: var(--text-2); }
+
+.prompt { width: 100%; border: 0; outline: 0; resize: none; background: transparent; font-size: 15px; line-height: 1.5; padding: 4px 2px; max-height: 200px; min-height: 26px; }
+.prompt::placeholder { color: var(--text-3); }
+.controls { display: flex; align-items: center; gap: 4px; margin-top: 4px; }
+.controls .spacer { flex: 1; }
+.plan-hint { color: var(--text-3); font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-right: 6px; }
+.pill { height: 32px; padding: 0 10px; border-radius: 16px; display: inline-flex; align-items: center; gap: 6px; color: var(--text-2); font-size: 13px; white-space: nowrap; }
+.pill:hover { background: var(--surface-2); color: var(--text); }
+.pill.on { color: var(--text); }
+.send { width: 34px; height: 34px; border-radius: 50%; background: var(--invert-bg); color: var(--invert-text); display: grid; place-items: center; }
+.send:disabled { opacity: 0.25; }
+
+/* popovers */
+.popover { position: absolute; z-index: 40; min-width: 200px; background: var(--bg); border: 1px solid var(--border); border-radius: 14px; box-shadow: var(--shadow); padding: 6px; }
+.popover .opt { display: flex; align-items: center; gap: 10px; width: 100%; padding: 8px 10px; border-radius: 9px; text-align: left; font-size: 13px; }
+.popover .opt:hover { background: var(--surface); }
+.popover .opt .sub { color: var(--text-3); font-size: 12px; margin-left: auto; padding-left: 16px; }
+.popover .opt .check { width: 16px; }
+.popover .label { font-size: 11px; color: var(--text-3); padding: 6px 10px 2px; text-transform: uppercase; letter-spacing: 0.04em; }
+
+.panel { width: 360px; padding: 14px; display: flex; flex-direction: column; gap: 12px; max-height: 70vh; overflow-y: auto; }
+.field { display: flex; flex-direction: column; gap: 6px; }
+.field > span, .field-row > span { font-size: 12px; color: var(--text-2); }
+.field-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
+.input, .select { height: 32px; border-radius: 9px; border: 1px solid var(--border); background: var(--bg); padding: 0 10px; outline: none; min-width: 0; }
+.input:focus, .select:focus { border-color: var(--text-2); }
+textarea.input { height: auto; padding: 8px 10px; resize: vertical; min-height: 60px; }
+.seg { display: flex; background: var(--surface); border-radius: 10px; padding: 3px; gap: 2px; }
+.seg button { flex: 1; height: 28px; border-radius: 8px; font-size: 12px; color: var(--text-2); padding: 0 6px; white-space: nowrap; }
+.seg button.on { background: var(--bg); color: var(--text); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.08); }
+input[type="range"] { width: 100%; accent-color: var(--text); }
+.switch { width: 34px; height: 20px; border-radius: 10px; background: var(--surface-3); position: relative; flex: none; transition: background 0.15s; }
+.switch::after { content: ""; position: absolute; left: 3px; top: 3px; width: 14px; height: 14px; border-radius: 50%; background: var(--bg); transition: left 0.15s; }
+.switch.on { background: var(--text); }
+.switch.on::after { left: 17px; }
+.btn { height: 34px; padding: 0 14px; border-radius: 10px; background: var(--surface); display: inline-flex; align-items: center; gap: 8px; font-size: 13px; }
+.btn:hover:not(:disabled) { background: var(--surface-2); }
+.btn.primary { background: var(--invert-bg); color: var(--invert-text); }
+.btn.primary:hover:not(:disabled) { opacity: 0.88; background: var(--invert-bg); }
+.muted { color: var(--text-3); font-size: 12px; }
+
+/* ---------- overlays ---------- */
+.overlay { position: absolute; inset: 0; z-index: 30; background: var(--bg); display: flex; flex-direction: column; }
+.overlay-head { height: 52px; display: flex; align-items: center; gap: 10px; padding: 0 12px 0 16px; flex: none; }
+.overlay-head h2 { font-size: 15px; font-weight: 600; margin: 0; }
+.overlay-head .spacer { flex: 1; }
+.modal-scrim { position: fixed; inset: 0; z-index: 50; background: rgba(0, 0, 0, 0.35); display: grid; place-items: center; }
+.modal { width: min(760px, 92vw); height: min(640px, 88vh); background: var(--bg); border-radius: 18px; box-shadow: var(--shadow); display: flex; overflow: hidden; }
+.modal-nav { width: 190px; padding: 14px 8px; background: var(--surface); display: flex; flex-direction: column; gap: 2px; }
+.modal-nav button { text-align: left; padding: 8px 12px; border-radius: 9px; color: var(--text-2); display: flex; gap: 10px; align-items: center; }
+.modal-nav button.on { background: var(--surface-2); color: var(--text); }
+.modal-body { flex: 1; overflow-y: auto; padding: 20px 24px; display: flex; flex-direction: column; gap: 16px; }
+.modal-body h3 { margin: 0 0 2px; font-size: 15px; font-weight: 600; }
+.path-row { display: flex; gap: 6px; }
+.path-row .input { flex: 1; font-size: 12px; }
+pre.diag { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font-size: 11px; background: var(--surface); border-radius: 10px; padding: 12px; white-space: pre-wrap; word-break: break-all; user-select: text; margin: 0; flex: 1; overflow: auto; }
+.check-list { display: flex; flex-direction: column; gap: 2px; }
+.check-item { display: flex; gap: 10px; align-items: flex-start; padding: 8px 0; border-bottom: 1px solid var(--border); }
+.check-item .what { flex: 1; min-width: 0; }
+.check-item .detail { font-size: 12px; color: var(--text-3); word-break: break-all; }
+
+/* gallery */
+.gallery-bar { display: flex; gap: 8px; align-items: center; padding: 0 16px 12px; }
+.search { flex: 1; max-width: 420px; display: flex; align-items: center; gap: 8px; background: var(--surface); border-radius: 10px; padding: 0 10px; height: 34px; color: var(--text-3); }
+.search input { border: 0; outline: 0; background: transparent; flex: 1; color: var(--text); }
+.grid { flex: 1; overflow-y: auto; padding: 0 16px 24px; display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px; align-content: start;
+ /* Without this, Chromium/WebView2 squeezes the implicit rows to fit the scroll box when the
+ window is short (e.g. 150% display scaling) and the square cards overlap the next row. */
+ grid-auto-rows: max-content; }
+.card { position: relative; border-radius: 10px; overflow: hidden; background: var(--surface); aspect-ratio: 1; cursor: pointer; }
+.card img { width: 100%; height: 100%; object-fit: cover; display: block; }
+.card .card-actions { position: absolute; right: 6px; top: 6px; display: none; gap: 4px; }
+.card:hover .card-actions, .card .card-actions.fav { display: flex; }
+.card .card-actions button { width: 28px; height: 28px; border-radius: 8px; background: var(--scrim); display: grid; place-items: center; color: var(--text); }
+.card .card-meta { position: absolute; left: 0; right: 0; bottom: 0; padding: 18px 8px 6px; font-size: 11px; color: #fff; background: linear-gradient(transparent, rgba(0,0,0,0.6)); display: none; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.card:hover .card-meta { display: block; }
+
+/* editors */
+.editor-stage { flex: 1; min-height: 0; display: flex; align-items: center; justify-content: center; padding: 12px 24px; position: relative; overflow: hidden; }
+.editor-tools { flex: none; display: flex; align-items: center; justify-content: center; gap: 6px; padding: 10px 16px 18px; flex-wrap: wrap; }
+.editor-tools .group { display: flex; align-items: center; gap: 4px; background: var(--surface); border-radius: 12px; padding: 4px; }
+.editor-tools .slider { display: flex; align-items: center; gap: 8px; padding: 0 10px; font-size: 12px; color: var(--text-2); }
+.editor-tools .slider input { width: 110px; }
+.mask-wrap { position: relative; touch-action: none; }
+.mask-wrap img { display: block; max-width: 100%; max-height: 100%; user-select: none; -webkit-user-drag: none; }
+.mask-wrap canvas { position: absolute; inset: 0; width: 100%; height: 100%; mix-blend-mode: difference; opacity: 0.75; cursor: none; }
+.brush-cursor { position: absolute; pointer-events: none; border: 1.5px solid #fff; mix-blend-mode: difference; border-radius: 50%; transform: translate(-50%, -50%); }
+
+.expand-area { position: relative; }
+.expand-canvas { position: absolute; border: 1.5px dashed var(--text-2); border-radius: 4px; background-image: conic-gradient(var(--checker) 25%, transparent 0 50%, var(--checker) 0 75%, transparent 0); background-size: 16px 16px; }
+.expand-src { position: absolute; }
+.expand-src img { width: 100%; height: 100%; display: block; }
+.handle { position: absolute; background: var(--text); border-radius: 3px; z-index: 2; }
+.handle.h { width: 6px; height: 40px; cursor: ew-resize; transform: translate(-50%, -50%); }
+.handle.v { width: 40px; height: 6px; cursor: ns-resize; transform: translate(-50%, -50%); }
+.num-input { width: 74px; height: 30px; border-radius: 8px; border: 1px solid var(--border); background: var(--bg); padding: 0 8px; text-align: right; outline: none; }
+.expand-fields { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; justify-content: center; }
+.expand-fields label { display: flex; align-items: center; gap: 6px; font-size: 12px; color: var(--text-2); }
+
+/* toasts */
+.toasts { position: fixed; right: 16px; bottom: 16px; z-index: 60; display: flex; flex-direction: column; gap: 8px; max-width: 380px; }
+.toast { background: var(--invert-bg); color: var(--invert-text); border-radius: 12px; padding: 12px 14px; box-shadow: var(--shadow); font-size: 13px; display: flex; gap: 10px; align-items: flex-start; }
+.toast .body { flex: 1; min-width: 0; }
+.toast .sugg { opacity: 0.75; margin-top: 2px; }
+.toast pre { white-space: pre-wrap; word-break: break-all; font-size: 11px; max-height: 160px; overflow: auto; opacity: 0.8; margin: 8px 0 0; user-select: text; }
+.toast button { color: inherit; opacity: 0.7; font-size: 12px; }
+
+.drop-hint { position: absolute; inset: 12px; z-index: 35; border: 2px dashed var(--text-2); border-radius: 18px; display: grid; place-items: center; background: var(--scrim); pointer-events: none; font-size: 15px; color: var(--text); }
+.spin { animation: spin 0.9s linear infinite; }
+@keyframes spin { to { transform: rotate(360deg); } }
+.setup { flex: 1; display: flex; justify-content: center; overflow-y: auto; padding: 48px 24px; }
+.setup-inner { width: 100%; max-width: 620px; display: flex; flex-direction: column; gap: 18px; }
+.setup h1 { font-size: 24px; letter-spacing: -0.02em; margin: 0; }
+
+/* before / after comparison */
+.compare-bar { display: flex; gap: 8px; margin-top: 8px; align-items: center; }
+.compare-bar .seg { min-width: 300px; }
+.compare-box { position: relative; border-radius: 6px; overflow: hidden; touch-action: none; user-select: none; background-image: conic-gradient(var(--checker) 25%, transparent 0 50%, var(--checker) 0 75%, transparent 0); background-size: 16px 16px; }
+.compare-box.slider { cursor: ew-resize; }
+.compare-img, .compare-diff { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
+/* Areas the original did not cover (expanded edges) show the checkerboard. */
+.compare-before { position: absolute; inset: 0; background-color: var(--bg); background-image: conic-gradient(var(--checker) 25%, transparent 0 50%, var(--checker) 0 75%, transparent 0); background-size: 16px 16px; }
+.compare-before img { position: absolute; display: block; }
+.compare-handle { position: absolute; top: 0; bottom: 0; width: 2px; margin-left: -1px; background: #fff; box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.35); pointer-events: none; }
+.compare-handle span { position: absolute; top: 50%; left: 50%; width: 28px; height: 28px; margin: -14px 0 0 -14px; border-radius: 50%; background: #fff; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.4); }
+.compare-handle span::before, .compare-handle span::after { content: ""; position: absolute; top: 9px; border: 5px solid transparent; }
+.compare-handle span::before { left: 2px; border-right-color: #333; }
+.compare-handle span::after { right: 2px; border-left-color: #333; }
+.compare-tag { position: absolute; top: 8px; padding: 2px 8px; border-radius: 6px; font-size: 11px; color: #fff; background: rgba(0, 0, 0, 0.55); pointer-events: none; }
+.compare-tag.left { left: 8px; }
+.compare-tag.right { right: 8px; }
+
+/* image box + full-screen button */
+.image-box { position: relative; }
+.stage-img.fill { width: 100%; height: 100%; max-width: none; max-height: none; display: block; }
+.fullscreen-btn { position: absolute; top: 8px; right: 8px; z-index: 2; width: 30px; height: 30px; border-radius: 8px; display: grid; place-items: center; color: #fff; background: rgba(0, 0, 0, 0.5); opacity: 0.75; transition: opacity 0.15s; }
+.fullscreen-btn:hover, .fullscreen-btn:focus-visible { opacity: 1; background: rgba(0, 0, 0, 0.7); }
+.compare-tag.right { right: 46px; }
+
+/* full-screen viewer */
+.viewer { position: fixed; inset: 0; z-index: 200; background: #000; }
+.viewer-scroll { position: absolute; inset: 0; display: grid; place-items: center; overflow: hidden; }
+.viewer-scroll.zoomed { display: block; overflow: auto; cursor: grab; scrollbar-width: none; }
+.viewer-scroll.zoomed:active { cursor: grabbing; }
+.viewer-img { max-width: 100vw; max-height: 100vh; object-fit: contain; display: block; cursor: zoom-in; user-select: none; }
+/* comparison full screen: the frame leaves room for the view switch at the bottom */
+.viewer-frame { position: absolute; inset: 60px 12px 64px; display: flex; align-items: center; justify-content: center; }
+.viewer-compare-bar { position: absolute; left: 0; right: 0; bottom: 14px; display: flex; justify-content: center; }
+.viewer-compare-bar .compare-bar { margin: 0; padding: 4px; border-radius: 12px; background: rgba(20, 20, 20, 0.85); }
+.viewer-bar { position: absolute; top: 12px; right: 12px; display: flex; align-items: center; gap: 10px; }
+.viewer-hint, .viewer-tag { font-size: 12px; color: rgba(255, 255, 255, 0.8); background: rgba(0, 0, 0, 0.55); padding: 4px 10px; border-radius: 8px; }
+.viewer-tag { color: #fff; font-weight: 600; }
+.viewer-close { width: 36px; height: 36px; border-radius: 10px; display: grid; place-items: center; color: #fff; background: rgba(255, 255, 255, 0.12); }
+.viewer-close:hover { background: rgba(255, 255, 255, 0.22); }
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 0000000..97634fd
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,17 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "lib": ["ES2023", "DOM", "DOM.Iterable"],
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "jsx": "react-jsx",
+ "strict": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "skipLibCheck": true,
+ "isolatedModules": true,
+ "noEmit": true,
+ "types": ["vite/client"]
+ },
+ "include": ["src", "vite.config.ts"]
+}
diff --git a/vite.config.ts b/vite.config.ts
new file mode 100644
index 0000000..48f25b1
--- /dev/null
+++ b/vite.config.ts
@@ -0,0 +1,11 @@
+import { defineConfig } from "vitest/config";
+import react from "@vitejs/plugin-react";
+
+// Tauri expects a fixed dev port and no browser auto-open.
+export default defineConfig({
+ plugins: [react()],
+ clearScreen: false,
+ server: { port: 1420, strictPort: true, host: "127.0.0.1" },
+ build: { target: "es2022", sourcemap: false, chunkSizeWarningLimit: 1500 },
+ test: { environment: "jsdom" },
+});