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.

Rename to Kokon; add setup wizard, fast downloads, undo and private mode

Gabriele Lozuponefb9bab4c1f07
diff --git a/.gitignore b/.gitignore
index 89a4d87..02bda81 100644
--- a/.gitignore
+++ b/.gitignore
@@ -9,3 +9,4 @@ node_modules
/.test-data
/dist-release
/src-tauri/gen
+__pycache__/
diff --git a/Cargo.lock b/Cargo.lock
index 1de57ce..233d45d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -637,7 +637,7 @@ dependencies = [
"bitflags 2.13.2",
"core-foundation",
"core-graphics-types",
- "foreign-types",
+ "foreign-types 0.5.0",
"libc",
]
@@ -1183,6 +1183,15 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+[[package]]
+name = "foreign-types"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
+dependencies = [
+ "foreign-types-shared 0.1.1",
+]
+
[[package]]
name = "foreign-types"
version = "0.5.0"
@@ -1190,7 +1199,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965"
dependencies = [
"foreign-types-macros",
- "foreign-types-shared",
+ "foreign-types-shared 0.3.1",
]
[[package]]
@@ -1204,6 +1213,12 @@ dependencies = [
"syn 3.0.6",
]
+[[package]]
+name = "foreign-types-shared"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
+
[[package]]
name = "foreign-types-shared"
version = "0.3.1"
@@ -1766,6 +1781,22 @@ dependencies = [
"want",
]
+[[package]]
+name = "hyper-tls"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "70206fc6890eaca9fde8a0bf71caa2ddfc9fe045ac9e5c70df101a7dbde866e0"
+dependencies = [
+ "bytes",
+ "http-body-util",
+ "hyper",
+ "hyper-util",
+ "native-tls",
+ "tokio",
+ "tokio-native-tls",
+ "tower-service",
+]
+
[[package]]
name = "hyper-util"
version = "0.1.21"
@@ -2190,6 +2221,23 @@ dependencies = [
"serde",
]
+[[package]]
+name = "kokon"
+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 = "lazy_static"
version = "1.5.1"
@@ -2401,6 +2449,23 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "native-tls"
+version = "0.2.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2"
+dependencies = [
+ "libc",
+ "log",
+ "openssl",
+ "openssl-probe",
+ "openssl-sys",
+ "schannel",
+ "security-framework",
+ "security-framework-sys",
+ "tempfile",
+]
+
[[package]]
name = "ndk"
version = "0.9.0"
@@ -2737,6 +2802,49 @@ dependencies = [
"libc",
]
+[[package]]
+name = "openssl"
+version = "0.10.81"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45"
+dependencies = [
+ "bitflags 2.13.2",
+ "cfg-if",
+ "foreign-types 0.3.2",
+ "libc",
+ "openssl-macros",
+ "openssl-sys",
+]
+
+[[package]]
+name = "openssl-macros"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "openssl-probe"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
+
+[[package]]
+name = "openssl-sys"
+version = "0.9.117"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"
+dependencies = [
+ "cc",
+ "libc",
+ "pkg-config",
+ "vcpkg",
+]
+
[[package]]
name = "option-ext"
version = "0.2.0"
@@ -3075,6 +3183,7 @@ dependencies = [
"base64 0.23.1",
"chrono",
"dirs",
+ "futures-util",
"hex",
"image",
"png 0.18.1",
@@ -3091,6 +3200,7 @@ dependencies = [
"tracing",
"uuid",
"windows",
+ "zip",
]
[[package]]
@@ -3102,6 +3212,7 @@ dependencies = [
"qls-core",
"serde",
"serde_json",
+ "sysinfo",
"tokio",
"tokio-stream",
"tower-http 0.7.1",
@@ -3144,23 +3255,6 @@ 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"
@@ -3262,15 +3356,19 @@ dependencies = [
"http-body",
"http-body-util",
"hyper",
+ "hyper-tls",
"hyper-util",
"js-sys",
"log",
+ "native-tls",
"percent-encoding",
"pin-project-lite",
+ "rustls-pki-types",
"serde",
"serde_json",
"sync_wrapper",
"tokio",
+ "tokio-native-tls",
"tokio-util",
"tower",
"tower-http 0.6.11",
@@ -3359,6 +3457,15 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "rustls-pki-types"
+version = "1.15.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"
+dependencies = [
+ "zeroize",
+]
+
[[package]]
name = "rustversion"
version = "1.0.23"
@@ -3380,6 +3487,15 @@ dependencies = [
"winapi-util",
]
+[[package]]
+name = "schannel"
+version = "0.1.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939"
+dependencies = [
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "schemars"
version = "0.8.22"
@@ -3437,6 +3553,29 @@ version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
+[[package]]
+name = "security-framework"
+version = "3.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"
+dependencies = [
+ "bitflags 2.13.2",
+ "core-foundation",
+ "core-foundation-sys",
+ "libc",
+ "security-framework-sys",
+]
+
+[[package]]
+name = "security-framework-sys"
+version = "2.17.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3"
+dependencies = [
+ "core-foundation-sys",
+ "libc",
+]
+
[[package]]
name = "selectors"
version = "0.38.0"
@@ -4462,6 +4601,16 @@ dependencies = [
"syn 3.0.6",
]
+[[package]]
+name = "tokio-native-tls"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bbae76ab933c85776efabc971569dd6119c580d8f5d448769dec1764bf796ef2"
+dependencies = [
+ "native-tls",
+ "tokio",
+]
+
[[package]]
name = "tokio-stream"
version = "0.1.19"
@@ -4760,6 +4909,12 @@ version = "0.2.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
+[[package]]
+name = "typed-path"
+version = "0.12.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8e28f89b80c87b8fb0cf04ab448d5dd0dd0ade2f8891bae878de66a75a28600e"
+
[[package]]
name = "typeid"
version = "1.0.3"
@@ -5760,6 +5915,12 @@ dependencies = [
"synstructure",
]
+[[package]]
+name = "zeroize"
+version = "1.9.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879"
+
[[package]]
name = "zerotrie"
version = "0.2.5"
@@ -5793,6 +5954,20 @@ dependencies = [
"syn 3.0.6",
]
+[[package]]
+name = "zip"
+version = "8.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2d04a6b5381502aa6087c94c669499eb1602eb9c5e8198e534de571f7154809b"
+dependencies = [
+ "crc32fast",
+ "flate2",
+ "indexmap 2.14.2",
+ "memchr",
+ "typed-path",
+ "zopfli",
+]
+
[[package]]
name = "zlib-rs"
version = "0.6.8"
@@ -5805,6 +5980,18 @@ version = "1.0.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
+[[package]]
+name = "zopfli"
+version = "0.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f05cd8797d63865425ff89b5c4a48804f35ba0ce8d125800027ad6017d2b5249"
+dependencies = [
+ "bumpalo",
+ "crc32fast",
+ "log",
+ "simd-adler32",
+]
+
[[package]]
name = "zune-core"
version = "0.5.3"
diff --git a/assets/brand/README.md b/assets/brand/README.md
new file mode 100644
index 0000000..91fa058
--- /dev/null
+++ b/assets/brand/README.md
@@ -0,0 +1,39 @@
+# Kokon brand assets
+
+Generated by `scripts/brand/kokon_brand.py` from one geometric definition of the mark
+(variant C, "cocoon + wings": a capsule stem, the cocoon, and two wings, the upper one larger,
+emerging from it). Edit the script, not the files, and rebuild:
+
+```
+python scripts/brand/kokon_brand.py build c # needs pillow numpy fonttools brotli skia-pathops
+python scripts/brand/kokon_brand.py preview # variant comparison sheet (explorations/)
+```
+
+## Colours
+
+| Name | Hex | Use |
+| --- | --- | --- |
+| Ink | `#0D0D0D` | mark, wordmark, dark tiles (same as the app's text colour) |
+| Paper | `#F7F6F2` | app icon tile, mark on dark backgrounds |
+
+The app UI itself is monochrome (see `src/styles.css`).
+
+## Files
+
+| Folder | What | Where to use it |
+| --- | --- | --- |
+| `icon/kokon-icon*` | light squircle tile with the black mark | desktop app (installed into `src-tauri/icons`) |
+| `icon/kokon-icon-inverse*` | black tile, light mark | website, social avatars, anywhere but the desktop app |
+| `icon/kokon-app.ico` | Windows icon, 16–256 px each drawn directly | copied to `src-tauri/icons/icon.ico` (app, installer, uninstaller) |
+| `mark/` | the mark alone on transparent, black and light | documents, slides, merch |
+| `logo/` | mark + "Kokon" (Inter SemiBold, outlined) | README header, website header; `-white` on dark backgrounds |
+| `web/` | favicon.ico/.svg, apple-touch-icon, 192/512 icons (inverse tile) | website |
+| `social/` | 1280×640 preview | GitHub social preview, link cards |
+
+## Rules
+
+- Keep clear space around the mark of at least the stem width on every side.
+- Do not recolour the parts separately, rotate, stretch or add effects.
+- Below 24 px use the icon tile, not the bare mark.
+
+`explorations/` holds the variants considered (A, B, C); C was chosen on 2026-10-08.
diff --git a/assets/brand/explorations/kokon-variants.png b/assets/brand/explorations/kokon-variants.png
new file mode 100644
index 0000000..322af58
Binary files /dev/null and b/assets/brand/explorations/kokon-variants.png differ
diff --git a/assets/brand/icon/kokon-app.ico b/assets/brand/icon/kokon-app.ico
new file mode 100644
index 0000000..16ffb7b
Binary files /dev/null and b/assets/brand/icon/kokon-app.ico differ
diff --git a/assets/brand/icon/kokon-icon-1024.png b/assets/brand/icon/kokon-icon-1024.png
new file mode 100644
index 0000000..f3c2f15
Binary files /dev/null and b/assets/brand/icon/kokon-icon-1024.png differ
diff --git a/assets/brand/icon/kokon-icon-256.png b/assets/brand/icon/kokon-icon-256.png
new file mode 100644
index 0000000..55b9880
Binary files /dev/null and b/assets/brand/icon/kokon-icon-256.png differ
diff --git a/assets/brand/icon/kokon-icon-512.png b/assets/brand/icon/kokon-icon-512.png
new file mode 100644
index 0000000..82184a5
Binary files /dev/null and b/assets/brand/icon/kokon-icon-512.png differ
diff --git a/assets/brand/icon/kokon-icon-inverse-1024.png b/assets/brand/icon/kokon-icon-inverse-1024.png
new file mode 100644
index 0000000..9f1f612
Binary files /dev/null and b/assets/brand/icon/kokon-icon-inverse-1024.png differ
diff --git a/assets/brand/icon/kokon-icon-inverse-256.png b/assets/brand/icon/kokon-icon-inverse-256.png
new file mode 100644
index 0000000..46adaa2
Binary files /dev/null and b/assets/brand/icon/kokon-icon-inverse-256.png differ
diff --git a/assets/brand/icon/kokon-icon-inverse-512.png b/assets/brand/icon/kokon-icon-inverse-512.png
new file mode 100644
index 0000000..10abbec
Binary files /dev/null and b/assets/brand/icon/kokon-icon-inverse-512.png differ
diff --git a/assets/brand/icon/kokon-icon-inverse.svg b/assets/brand/icon/kokon-icon-inverse.svg
new file mode 100644
index 0000000..5d55469
--- /dev/null
+++ b/assets/brand/icon/kokon-icon-inverse.svg
@@ -0,0 +1,4 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024">
+<path fill="#0D0D0D" d="M983.04 512.00 L983.03 582.70 L983.01 605.28 L982.98 621.70 L982.93 635.08 L982.86 646.56 L982.78 656.74 L982.69 665.93 L982.58 674.36 L982.46 682.18 L982.32 689.49 L982.17 696.37 L982.01 702.88 L981.83 709.06 L981.63 714.96 L981.42 720.61 L981.20 726.03 L980.96 731.25 L980.71 736.28 L980.45 741.14 L980.16 745.84 L979.87 750.40 L979.56 754.83 L979.23 759.13 L978.90 763.31 L978.54 767.38 L978.17 771.35 L977.79 775.23 L977.39 779.01 L976.98 782.71 L976.55 786.32 L976.11 789.85 L975.65 793.32 L975.18 796.70 L974.70 800.03 L974.20 803.28 L973.68 806.48 L973.15 809.61 L972.60 812.69 L972.04 815.71 L971.46 818.68 L970.87 821.59 L970.27 824.46 L969.65 827.27 L969.01 830.04 L968.36 832.77 L967.69 835.45 L967.01 838.09 L966.31 840.69 L965.59 843.24 L964.86 845.76 L964.12 848.24 L963.36 850.68 L962.58 853.09 L961.79 855.46 L960.98 857.80 L960.16 860.10 L959.32 862.37 L958.46 864.60 L957.59 866.81 L956.70 868.98 L955.80 871.12 L954.88 873.24 L953.94 875.32 L952.99 877.38 L952.02 879.40 L951.03 881.40 L950.03 883.38 L949.01 885.32 L947.97 887.24 L946.91 889.13 L945.84 891.00 L944.75 892.84 L943.65 894.66 L942.52 896.45 L941.38 898.22 L940.22 899.97 L939.05 901.69 L937.85 903.39 L936.64 905.06 L935.41 906.72 L934.16 908.35 L932.89 909.96 L931.60 911.54 L930.30 913.11 L928.98 914.65 L927.63 916.18 L926.27 917.68 L924.89 919.16 L923.49 920.62 L922.06 922.06 L920.62 923.49 L919.16 924.89 L917.68 926.27 L916.18 927.63 L914.65 928.98 L913.11 930.30 L911.54 931.60 L909.96 932.89 L908.35 934.16 L906.72 935.41 L905.06 936.64 L903.39 937.85 L901.69 939.05 L899.97 940.22 L898.22 941.38 L896.45 942.52 L894.66 943.65 L892.84 944.75 L891.00 945.84 L889.13 946.91 L887.24 947.97 L885.32 949.01 L883.38 950.03 L881.40 951.03 L879.40 952.02 L877.38 952.99 L875.32 953.94 L873.24 954.88 L871.12 955.80 L868.98 956.70 L866.81 957.59 L864.60 958.46 L862.37 959.32 L860.10 960.16 L857.80 960.98 L855.46 961.79 L853.09 962.58 L850.68 963.36 L848.24 964.12 L845.76 964.86 L843.24 965.59 L840.69 966.31 L838.09 967.01 L835.45 967.69 L832.77 968.36 L830.04 969.01 L827.27 969.65 L824.46 970.27 L821.59 970.87 L818.68 971.46 L815.71 972.04 L812.69 972.60 L809.61 973.15 L806.48 973.68 L803.28 974.20 L800.03 974.70 L796.70 975.18 L793.32 975.65 L789.85 976.11 L786.32 976.55 L782.71 976.98 L779.01 977.39 L775.23 977.79 L771.35 978.17 L767.38 978.54 L763.31 978.90 L759.13 979.23 L754.83 979.56 L750.40 979.87 L745.84 980.16 L741.14 980.45 L736.28 980.71 L731.25 980.96 L726.03 981.20 L720.61 981.42 L714.96 981.63 L709.06 981.83 L702.88 982.01 L696.37 982.17 L689.49 982.32 L682.18 982.46 L674.36 982.58 L665.93 982.69 L656.74 982.78 L646.56 982.86 L635.08 982.93 L621.70 982.98 L605.28 983.01 L582.70 983.03 L512.00 983.04 L441.30 983.03 L418.72 983.01 L402.30 982.98 L388.92 982.93 L377.44 982.86 L367.26 982.78 L358.07 982.69 L349.64 982.58 L341.82 982.46 L334.51 982.32 L327.63 982.17 L321.12 982.01 L314.94 981.83 L309.04 981.63 L303.39 981.42 L297.97 981.20 L292.75 980.96 L287.72 980.71 L282.86 980.45 L278.16 980.16 L273.60 979.87 L269.17 979.56 L264.87 979.23 L260.69 978.90 L256.62 978.54 L252.65 978.17 L248.77 977.79 L244.99 977.39 L241.29 976.98 L237.68 976.55 L234.15 976.11 L230.68 975.65 L227.30 975.18 L223.97 974.70 L220.72 974.20 L217.52 973.68 L214.39 973.15 L211.31 972.60 L208.29 972.04 L205.32 971.46 L202.41 970.87 L199.54 970.27 L196.73 969.65 L193.96 969.01 L191.23 968.36 L188.55 967.69 L185.91 967.01 L183.31 966.31 L180.76 965.59 L178.24 964.86 L175.76 964.12 L173.32 963.36 L170.91 962.58 L168.54 961.79 L166.20 960.98 L163.90 960.16 L161.63 959.32 L159.40 958.46 L157.19 957.59 L155.02 956.70 L152.88 955.80 L150.76 954.88 L148.68 953.94 L146.62 952.99 L144.60 952.02 L142.60 951.03 L140.62 950.03 L138.68 949.01 L136.76 947.97 L134.87 946.91 L133.00 945.84 L131.16 944.75 L129.34 943.65 L127.55 942.52 L125.78 941.38 L124.03 940.22 L122.31 939.05 L120.61 937.85 L118.94 936.64 L117.28 935.41 L115.65 934.16 L114.04 932.89 L112.46 931.60 L110.89 930.30 L109.35 928.98 L107.82 927.63 L106.32 926.27 L104.84 924.89 L103.38 923.49 L101.94 922.06 L100.51 920.62 L99.11 919.16 L97.73 917.68 L96.37 916.18 L95.02 914.65 L93.70 913.11 L92.40 911.54 L91.11 909.96 L89.84 908.35 L88.59 906.72 L87.36 905.06 L86.15 903.39 L84.95 901.69 L83.78 899.97 L82.62 898.22 L81.48 896.45 L80.35 894.66 L79.25 892.84 L78.16 891.00 L77.09 889.13 L76.03 887.24 L74.99 885.32 L73.97 883.38 L72.97 881.40 L71.98 879.40 L71.01 877.38 L70.06 875.32 L69.12 873.24 L68.20 871.12 L67.30 868.98 L66.41 866.81 L65.54 864.60 L64.68 862.37 L63.84 860.10 L63.02 857.80 L62.21 855.46 L61.42 853.09 L60.64 850.68 L59.88 848.24 L59.14 845.76 L58.41 843.24 L57.69 840.69 L56.99 838.09 L56.31 835.45 L55.64 832.77 L54.99 830.04 L54.35 827.27 L53.73 824.46 L53.13 821.59 L52.54 818.68 L51.96 815.71 L51.40 812.69 L50.85 809.61 L50.32 806.48 L49.80 803.28 L49.30 800.03 L48.82 796.70 L48.35 793.32 L47.89 789.85 L47.45 786.32 L47.02 782.71 L46.61 779.01 L46.21 775.23 L45.83 771.35 L45.46 767.38 L45.10 763.31 L44.77 759.13 L44.44 754.83 L44.13 750.40 L43.84 745.84 L43.55 741.14 L43.29 736.28 L43.04 731.25 L42.80 726.03 L42.58 720.61 L42.37 714.96 L42.17 709.06 L41.99 702.88 L41.83 696.37 L41.68 689.49 L41.54 682.18 L41.42 674.36 L41.31 665.93 L41.22 656.74 L41.14 646.56 L41.07 635.08 L41.02 621.70 L40.99 605.28 L40.97 582.70 L40.96 512.00 L40.97 441.30 L40.99 418.72 L41.02 402.30 L41.07 388.92 L41.14 377.44 L41.22 367.26 L41.31 358.07 L41.42 349.64 L41.54 341.82 L41.68 334.51 L41.83 327.63 L41.99 321.12 L42.17 314.94 L42.37 309.04 L42.58 303.39 L42.80 297.97 L43.04 292.75 L43.29 287.72 L43.55 282.86 L43.84 278.16 L44.13 273.60 L44.44 269.17 L44.77 264.87 L45.10 260.69 L45.46 256.62 L45.83 252.65 L46.21 248.77 L46.61 244.99 L47.02 241.29 L47.45 237.68 L47.89 234.15 L48.35 230.68 L48.82 227.30 L49.30 223.97 L49.80 220.72 L50.32 217.52 L50.85 214.39 L51.40 211.31 L51.96 208.29 L52.54 205.32 L53.13 202.41 L53.73 199.54 L54.35 196.73 L54.99 193.96 L55.64 191.23 L56.31 188.55 L56.99 185.91 L57.69 183.31 L58.41 180.76 L59.14 178.24 L59.88 175.76 L60.64 173.32 L61.42 170.91 L62.21 168.54 L63.02 166.20 L63.84 163.90 L64.68 161.63 L65.54 159.40 L66.41 157.19 L67.30 155.02 L68.20 152.88 L69.12 150.76 L70.06 148.68 L71.01 146.62 L71.98 144.60 L72.97 142.60 L73.97 140.62 L74.99 138.68 L76.03 136.76 L77.09 134.87 L78.16 133.00 L79.25 131.16 L80.35 129.34 L81.48 127.55 L82.62 125.78 L83.78 124.03 L84.95 122.31 L86.15 120.61 L87.36 118.94 L88.59 117.28 L89.84 115.65 L91.11 114.04 L92.40 112.46 L93.70 110.89 L95.02 109.35 L96.37 107.82 L97.73 106.32 L99.11 104.84 L100.51 103.38 L101.94 101.94 L103.38 100.51 L104.84 99.11 L106.32 97.73 L107.82 96.37 L109.35 95.02 L110.89 93.70 L112.46 92.40 L114.04 91.11 L115.65 89.84 L117.28 88.59 L118.94 87.36 L120.61 86.15 L122.31 84.95 L124.03 83.78 L125.78 82.62 L127.55 81.48 L129.34 80.35 L131.16 79.25 L133.00 78.16 L134.87 77.09 L136.76 76.03 L138.68 74.99 L140.62 73.97 L142.60 72.97 L144.60 71.98 L146.62 71.01 L148.68 70.06 L150.76 69.12 L152.88 68.20 L155.02 67.30 L157.19 66.41 L159.40 65.54 L161.63 64.68 L163.90 63.84 L166.20 63.02 L168.54 62.21 L170.91 61.42 L173.32 60.64 L175.76 59.88 L178.24 59.14 L180.76 58.41 L183.31 57.69 L185.91 56.99 L188.55 56.31 L191.23 55.64 L193.96 54.99 L196.73 54.35 L199.54 53.73 L202.41 53.13 L205.32 52.54 L208.29 51.96 L211.31 51.40 L214.39 50.85 L217.52 50.32 L220.72 49.80 L223.97 49.30 L227.30 48.82 L230.68 48.35 L234.15 47.89 L237.68 47.45 L241.29 47.02 L244.99 46.61 L248.77 46.21 L252.65 45.83 L256.62 45.46 L260.69 45.10 L264.87 44.77 L269.17 44.44 L273.60 44.13 L278.16 43.84 L282.86 43.55 L287.72 43.29 L292.75 43.04 L297.97 42.80 L303.39 42.58 L309.04 42.37 L314.94 42.17 L321.12 41.99 L327.63 41.83 L334.51 41.68 L341.82 41.54 L349.64 41.42 L358.07 41.31 L367.26 41.22 L377.44 41.14 L388.92 41.07 L402.30 41.02 L418.72 40.99 L441.30 40.97 L512.00 40.96 L582.70 40.97 L605.28 40.99 L621.70 41.02 L635.08 41.07 L646.56 41.14 L656.74 41.22 L665.93 41.31 L674.36 41.42 L682.18 41.54 L689.49 41.68 L696.37 41.83 L702.88 41.99 L709.06 42.17 L714.96 42.37 L720.61 42.58 L726.03 42.80 L731.25 43.04 L736.28 43.29 L741.14 43.55 L745.84 43.84 L750.40 44.13 L754.83 44.44 L759.13 44.77 L763.31 45.10 L767.38 45.46 L771.35 45.83 L775.23 46.21 L779.01 46.61 L782.71 47.02 L786.32 47.45 L789.85 47.89 L793.32 48.35 L796.70 48.82 L800.03 49.30 L803.28 49.80 L806.48 50.32 L809.61 50.85 L812.69 51.40 L815.71 51.96 L818.68 52.54 L821.59 53.13 L824.46 53.73 L827.27 54.35 L830.04 54.99 L832.77 55.64 L835.45 56.31 L838.09 56.99 L840.69 57.69 L843.24 58.41 L845.76 59.14 L848.24 59.88 L850.68 60.64 L853.09 61.42 L855.46 62.21 L857.80 63.02 L860.10 63.84 L862.37 64.68 L864.60 65.54 L866.81 66.41 L868.98 67.30 L871.12 68.20 L873.24 69.12 L875.32 70.06 L877.38 71.01 L879.40 71.98 L881.40 72.97 L883.38 73.97 L885.32 74.99 L887.24 76.03 L889.13 77.09 L891.00 78.16 L892.84 79.25 L894.66 80.35 L896.45 81.48 L898.22 82.62 L899.97 83.78 L901.69 84.95 L903.39 86.15 L905.06 87.36 L906.72 88.59 L908.35 89.84 L909.96 91.11 L911.54 92.40 L913.11 93.70 L914.65 95.02 L916.18 96.37 L917.68 97.73 L919.16 99.11 L920.62 100.51 L922.06 101.94 L923.49 103.38 L924.89 104.84 L926.27 106.32 L927.63 107.82 L928.98 109.35 L930.30 110.89 L931.60 112.46 L932.89 114.04 L934.16 115.65 L935.41 117.28 L936.64 118.94 L937.85 120.61 L939.05 122.31 L940.22 124.03 L941.38 125.78 L942.52 127.55 L943.65 129.34 L944.75 131.16 L945.84 133.00 L946.91 134.87 L947.97 136.76 L949.01 138.68 L950.03 140.62 L951.03 142.60 L952.02 144.60 L952.99 146.62 L953.94 148.68 L954.88 150.76 L955.80 152.88 L956.70 155.02 L957.59 157.19 L958.46 159.40 L959.32 161.63 L960.16 163.90 L960.98 166.20 L961.79 168.54 L962.58 170.91 L963.36 173.32 L964.12 175.76 L964.86 178.24 L965.59 180.76 L966.31 183.31 L967.01 185.91 L967.69 188.55 L968.36 191.23 L969.01 193.96 L969.65 196.73 L970.27 199.54 L970.87 202.41 L971.46 205.32 L972.04 208.29 L972.60 211.31 L973.15 214.39 L973.68 217.52 L974.20 220.72 L974.70 223.97 L975.18 227.30 L975.65 230.68 L976.11 234.15 L976.55 237.68 L976.98 241.29 L977.39 244.99 L977.79 248.77 L978.17 252.65 L978.54 256.62 L978.90 260.69 L979.23 264.87 L979.56 269.17 L979.87 273.60 L980.16 278.16 L980.45 282.86 L980.71 287.72 L980.96 292.75 L981.20 297.97 L981.42 303.39 L981.63 309.04 L981.83 314.94 L982.01 321.12 L982.17 327.63 L982.32 334.51 L982.46 341.82 L982.58 349.64 L982.69 358.07 L982.78 367.26 L982.86 377.44 L982.93 388.92 L982.98 402.30 L983.01 418.72 L983.03 441.30 Z"/>
+<path fill="#F7F6F2" d="M256.00 377.40 C256.00 312.08 291.12 268.54 343.79 268.54 C396.47 268.54 431.59 312.08 431.59 377.40 L431.59 646.60 C431.59 711.92 396.47 755.46 343.79 755.46 C291.12 755.46 256.00 711.92 256.00 646.60 Z M450.77 530.47 C450.77 381.17 587.18 268.54 768.00 268.54 C768.00 417.84 631.59 530.47 450.77 530.47 Z M450.77 549.65 C450.77 666.96 565.35 755.46 717.24 755.46 C717.24 638.15 602.65 549.65 450.77 549.65 Z"/>
+</svg>
diff --git a/assets/brand/icon/kokon-icon.svg b/assets/brand/icon/kokon-icon.svg
new file mode 100644
index 0000000..37c8cac
--- /dev/null
+++ b/assets/brand/icon/kokon-icon.svg
@@ -0,0 +1,5 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024">
+<path fill="#000000" fill-opacity="0.11" d="M985.04 512.00 L985.03 583.00 L985.01 605.68 L984.98 622.17 L984.92 635.60 L984.86 647.14 L984.78 657.35 L984.69 666.59 L984.58 675.05 L984.46 682.91 L984.32 690.24 L984.17 697.15 L984.00 703.69 L983.82 709.90 L983.63 715.82 L983.42 721.50 L983.19 726.94 L982.95 732.18 L982.70 737.23 L982.43 742.11 L982.15 746.84 L981.86 751.41 L981.54 755.86 L981.22 760.18 L980.88 764.38 L980.52 768.47 L980.15 772.46 L979.77 776.35 L979.37 780.14 L978.95 783.86 L978.53 787.48 L978.08 791.03 L977.62 794.51 L977.15 797.91 L976.66 801.25 L976.16 804.52 L975.64 807.73 L975.11 810.87 L974.56 813.96 L973.99 817.00 L973.42 819.98 L972.82 822.91 L972.21 825.78 L971.59 828.61 L970.95 831.39 L970.29 834.13 L969.62 836.82 L968.94 839.47 L968.24 842.08 L967.52 844.65 L966.79 847.18 L966.04 849.67 L965.28 852.12 L964.50 854.54 L963.70 856.92 L962.89 859.26 L962.06 861.58 L961.22 863.85 L960.36 866.10 L959.48 868.31 L958.59 870.50 L957.68 872.65 L956.76 874.77 L955.82 876.86 L954.86 878.93 L953.89 880.96 L952.89 882.97 L951.89 884.95 L950.86 886.91 L949.82 888.83 L948.76 890.73 L947.68 892.61 L946.59 894.46 L945.48 896.28 L944.35 898.09 L943.21 899.86 L942.04 901.61 L940.86 903.34 L939.66 905.05 L938.44 906.73 L937.21 908.39 L935.95 910.03 L934.68 911.65 L933.39 913.24 L932.08 914.81 L930.75 916.36 L929.40 917.89 L928.03 919.40 L926.64 920.89 L925.23 922.36 L923.81 923.81 L922.36 925.23 L920.89 926.64 L919.40 928.03 L917.89 929.40 L916.36 930.75 L914.81 932.08 L913.24 933.39 L911.65 934.68 L910.03 935.95 L908.39 937.21 L906.73 938.44 L905.05 939.66 L903.34 940.86 L901.61 942.04 L899.86 943.21 L898.09 944.35 L896.28 945.48 L894.46 946.59 L892.61 947.68 L890.73 948.76 L888.83 949.82 L886.91 950.86 L884.95 951.89 L882.97 952.89 L880.96 953.89 L878.93 954.86 L876.86 955.82 L874.77 956.76 L872.65 957.68 L870.50 958.59 L868.31 959.48 L866.10 960.36 L863.85 961.22 L861.58 962.06 L859.26 962.89 L856.92 963.70 L854.54 964.50 L852.12 965.28 L849.67 966.04 L847.18 966.79 L844.65 967.52 L842.08 968.24 L839.47 968.94 L836.82 969.62 L834.13 970.29 L831.39 970.95 L828.61 971.59 L825.78 972.21 L822.91 972.82 L819.98 973.42 L817.00 973.99 L813.96 974.56 L810.87 975.11 L807.73 975.64 L804.52 976.16 L801.25 976.66 L797.91 977.15 L794.51 977.62 L791.03 978.08 L787.48 978.53 L783.86 978.95 L780.14 979.37 L776.35 979.77 L772.46 980.15 L768.47 980.52 L764.38 980.88 L760.18 981.22 L755.86 981.54 L751.41 981.86 L746.84 982.15 L742.11 982.43 L737.23 982.70 L732.18 982.95 L726.94 983.19 L721.50 983.42 L715.82 983.63 L709.90 983.82 L703.69 984.00 L697.15 984.17 L690.24 984.32 L682.91 984.46 L675.05 984.58 L666.59 984.69 L657.35 984.78 L647.14 984.86 L635.60 984.92 L622.17 984.98 L605.68 985.01 L583.00 985.03 L512.00 985.04 L441.00 985.03 L418.32 985.01 L401.83 984.98 L388.40 984.92 L376.86 984.86 L366.65 984.78 L357.41 984.69 L348.95 984.58 L341.09 984.46 L333.76 984.32 L326.85 984.17 L320.31 984.00 L314.10 983.82 L308.18 983.63 L302.50 983.42 L297.06 983.19 L291.82 982.95 L286.77 982.70 L281.89 982.43 L277.16 982.15 L272.59 981.86 L268.14 981.54 L263.82 981.22 L259.62 980.88 L255.53 980.52 L251.54 980.15 L247.65 979.77 L243.86 979.37 L240.14 978.95 L236.52 978.53 L232.97 978.08 L229.49 977.62 L226.09 977.15 L222.75 976.66 L219.48 976.16 L216.27 975.64 L213.13 975.11 L210.04 974.56 L207.00 973.99 L204.02 973.42 L201.09 972.82 L198.22 972.21 L195.39 971.59 L192.61 970.95 L189.87 970.29 L187.18 969.62 L184.53 968.94 L181.92 968.24 L179.35 967.52 L176.82 966.79 L174.33 966.04 L171.88 965.28 L169.46 964.50 L167.08 963.70 L164.74 962.89 L162.42 962.06 L160.15 961.22 L157.90 960.36 L155.69 959.48 L153.50 958.59 L151.35 957.68 L149.23 956.76 L147.14 955.82 L145.07 954.86 L143.04 953.89 L141.03 952.89 L139.05 951.89 L137.09 950.86 L135.17 949.82 L133.27 948.76 L131.39 947.68 L129.54 946.59 L127.72 945.48 L125.91 944.35 L124.14 943.21 L122.39 942.04 L120.66 940.86 L118.95 939.66 L117.27 938.44 L115.61 937.21 L113.97 935.95 L112.35 934.68 L110.76 933.39 L109.19 932.08 L107.64 930.75 L106.11 929.40 L104.60 928.03 L103.11 926.64 L101.64 925.23 L100.19 923.81 L98.77 922.36 L97.36 920.89 L95.97 919.40 L94.60 917.89 L93.25 916.36 L91.92 914.81 L90.61 913.24 L89.32 911.65 L88.05 910.03 L86.79 908.39 L85.56 906.73 L84.34 905.05 L83.14 903.34 L81.96 901.61 L80.79 899.86 L79.65 898.09 L78.52 896.28 L77.41 894.46 L76.32 892.61 L75.24 890.73 L74.18 888.83 L73.14 886.91 L72.11 884.95 L71.11 882.97 L70.11 880.96 L69.14 878.93 L68.18 876.86 L67.24 874.77 L66.32 872.65 L65.41 870.50 L64.52 868.31 L63.64 866.10 L62.78 863.85 L61.94 861.58 L61.11 859.26 L60.30 856.92 L59.50 854.54 L58.72 852.12 L57.96 849.67 L57.21 847.18 L56.48 844.65 L55.76 842.08 L55.06 839.47 L54.38 836.82 L53.71 834.13 L53.05 831.39 L52.41 828.61 L51.79 825.78 L51.18 822.91 L50.58 819.98 L50.01 817.00 L49.44 813.96 L48.89 810.87 L48.36 807.73 L47.84 804.52 L47.34 801.25 L46.85 797.91 L46.38 794.51 L45.92 791.03 L45.47 787.48 L45.05 783.86 L44.63 780.14 L44.23 776.35 L43.85 772.46 L43.48 768.47 L43.12 764.38 L42.78 760.18 L42.46 755.86 L42.14 751.41 L41.85 746.84 L41.57 742.11 L41.30 737.23 L41.05 732.18 L40.81 726.94 L40.58 721.50 L40.37 715.82 L40.18 709.90 L40.00 703.69 L39.83 697.15 L39.68 690.24 L39.54 682.91 L39.42 675.05 L39.31 666.59 L39.22 657.35 L39.14 647.14 L39.08 635.60 L39.02 622.17 L38.99 605.68 L38.97 583.00 L38.96 512.00 L38.97 441.00 L38.99 418.32 L39.02 401.83 L39.08 388.40 L39.14 376.86 L39.22 366.65 L39.31 357.41 L39.42 348.95 L39.54 341.09 L39.68 333.76 L39.83 326.85 L40.00 320.31 L40.18 314.10 L40.37 308.18 L40.58 302.50 L40.81 297.06 L41.05 291.82 L41.30 286.77 L41.57 281.89 L41.85 277.16 L42.14 272.59 L42.46 268.14 L42.78 263.82 L43.12 259.62 L43.48 255.53 L43.85 251.54 L44.23 247.65 L44.63 243.86 L45.05 240.14 L45.47 236.52 L45.92 232.97 L46.38 229.49 L46.85 226.09 L47.34 222.75 L47.84 219.48 L48.36 216.27 L48.89 213.13 L49.44 210.04 L50.01 207.00 L50.58 204.02 L51.18 201.09 L51.79 198.22 L52.41 195.39 L53.05 192.61 L53.71 189.87 L54.38 187.18 L55.06 184.53 L55.76 181.92 L56.48 179.35 L57.21 176.82 L57.96 174.33 L58.72 171.88 L59.50 169.46 L60.30 167.08 L61.11 164.74 L61.94 162.42 L62.78 160.15 L63.64 157.90 L64.52 155.69 L65.41 153.50 L66.32 151.35 L67.24 149.23 L68.18 147.14 L69.14 145.07 L70.11 143.04 L71.11 141.03 L72.11 139.05 L73.14 137.09 L74.18 135.17 L75.24 133.27 L76.32 131.39 L77.41 129.54 L78.52 127.72 L79.65 125.91 L80.79 124.14 L81.96 122.39 L83.14 120.66 L84.34 118.95 L85.56 117.27 L86.79 115.61 L88.05 113.97 L89.32 112.35 L90.61 110.76 L91.92 109.19 L93.25 107.64 L94.60 106.11 L95.97 104.60 L97.36 103.11 L98.77 101.64 L100.19 100.19 L101.64 98.77 L103.11 97.36 L104.60 95.97 L106.11 94.60 L107.64 93.25 L109.19 91.92 L110.76 90.61 L112.35 89.32 L113.97 88.05 L115.61 86.79 L117.27 85.56 L118.95 84.34 L120.66 83.14 L122.39 81.96 L124.14 80.79 L125.91 79.65 L127.72 78.52 L129.54 77.41 L131.39 76.32 L133.27 75.24 L135.17 74.18 L137.09 73.14 L139.05 72.11 L141.03 71.11 L143.04 70.11 L145.07 69.14 L147.14 68.18 L149.23 67.24 L151.35 66.32 L153.50 65.41 L155.69 64.52 L157.90 63.64 L160.15 62.78 L162.42 61.94 L164.74 61.11 L167.08 60.30 L169.46 59.50 L171.88 58.72 L174.33 57.96 L176.82 57.21 L179.35 56.48 L181.92 55.76 L184.53 55.06 L187.18 54.38 L189.87 53.71 L192.61 53.05 L195.39 52.41 L198.22 51.79 L201.09 51.18 L204.02 50.58 L207.00 50.01 L210.04 49.44 L213.13 48.89 L216.27 48.36 L219.48 47.84 L222.75 47.34 L226.09 46.85 L229.49 46.38 L232.97 45.92 L236.52 45.47 L240.14 45.05 L243.86 44.63 L247.65 44.23 L251.54 43.85 L255.53 43.48 L259.62 43.12 L263.82 42.78 L268.14 42.46 L272.59 42.14 L277.16 41.85 L281.89 41.57 L286.77 41.30 L291.82 41.05 L297.06 40.81 L302.50 40.58 L308.18 40.37 L314.10 40.18 L320.31 40.00 L326.85 39.83 L333.76 39.68 L341.09 39.54 L348.95 39.42 L357.41 39.31 L366.65 39.22 L376.86 39.14 L388.40 39.08 L401.83 39.02 L418.32 38.99 L441.00 38.97 L512.00 38.96 L583.00 38.97 L605.68 38.99 L622.17 39.02 L635.60 39.08 L647.14 39.14 L657.35 39.22 L666.59 39.31 L675.05 39.42 L682.91 39.54 L690.24 39.68 L697.15 39.83 L703.69 40.00 L709.90 40.18 L715.82 40.37 L721.50 40.58 L726.94 40.81 L732.18 41.05 L737.23 41.30 L742.11 41.57 L746.84 41.85 L751.41 42.14 L755.86 42.46 L760.18 42.78 L764.38 43.12 L768.47 43.48 L772.46 43.85 L776.35 44.23 L780.14 44.63 L783.86 45.05 L787.48 45.47 L791.03 45.92 L794.51 46.38 L797.91 46.85 L801.25 47.34 L804.52 47.84 L807.73 48.36 L810.87 48.89 L813.96 49.44 L817.00 50.01 L819.98 50.58 L822.91 51.18 L825.78 51.79 L828.61 52.41 L831.39 53.05 L834.13 53.71 L836.82 54.38 L839.47 55.06 L842.08 55.76 L844.65 56.48 L847.18 57.21 L849.67 57.96 L852.12 58.72 L854.54 59.50 L856.92 60.30 L859.26 61.11 L861.58 61.94 L863.85 62.78 L866.10 63.64 L868.31 64.52 L870.50 65.41 L872.65 66.32 L874.77 67.24 L876.86 68.18 L878.93 69.14 L880.96 70.11 L882.97 71.11 L884.95 72.11 L886.91 73.14 L888.83 74.18 L890.73 75.24 L892.61 76.32 L894.46 77.41 L896.28 78.52 L898.09 79.65 L899.86 80.79 L901.61 81.96 L903.34 83.14 L905.05 84.34 L906.73 85.56 L908.39 86.79 L910.03 88.05 L911.65 89.32 L913.24 90.61 L914.81 91.92 L916.36 93.25 L917.89 94.60 L919.40 95.97 L920.89 97.36 L922.36 98.77 L923.81 100.19 L925.23 101.64 L926.64 103.11 L928.03 104.60 L929.40 106.11 L930.75 107.64 L932.08 109.19 L933.39 110.76 L934.68 112.35 L935.95 113.97 L937.21 115.61 L938.44 117.27 L939.66 118.95 L940.86 120.66 L942.04 122.39 L943.21 124.14 L944.35 125.91 L945.48 127.72 L946.59 129.54 L947.68 131.39 L948.76 133.27 L949.82 135.17 L950.86 137.09 L951.89 139.05 L952.89 141.03 L953.89 143.04 L954.86 145.07 L955.82 147.14 L956.76 149.23 L957.68 151.35 L958.59 153.50 L959.48 155.69 L960.36 157.90 L961.22 160.15 L962.06 162.42 L962.89 164.74 L963.70 167.08 L964.50 169.46 L965.28 171.88 L966.04 174.33 L966.79 176.82 L967.52 179.35 L968.24 181.92 L968.94 184.53 L969.62 187.18 L970.29 189.87 L970.95 192.61 L971.59 195.39 L972.21 198.22 L972.82 201.09 L973.42 204.02 L973.99 207.00 L974.56 210.04 L975.11 213.13 L975.64 216.27 L976.16 219.48 L976.66 222.75 L977.15 226.09 L977.62 229.49 L978.08 232.97 L978.53 236.52 L978.95 240.14 L979.37 243.86 L979.77 247.65 L980.15 251.54 L980.52 255.53 L980.88 259.62 L981.22 263.82 L981.54 268.14 L981.86 272.59 L982.15 277.16 L982.43 281.89 L982.70 286.77 L982.95 291.82 L983.19 297.06 L983.42 302.50 L983.63 308.18 L983.82 314.10 L984.00 320.31 L984.17 326.85 L984.32 333.76 L984.46 341.09 L984.58 348.95 L984.69 357.41 L984.78 366.65 L984.86 376.86 L984.92 388.40 L984.98 401.83 L985.01 418.32 L985.03 441.00 Z"/>
+<path fill="#F7F6F2" d="M983.04 512.00 L983.03 582.70 L983.01 605.28 L982.98 621.70 L982.93 635.08 L982.86 646.56 L982.78 656.74 L982.69 665.93 L982.58 674.36 L982.46 682.18 L982.32 689.49 L982.17 696.37 L982.01 702.88 L981.83 709.06 L981.63 714.96 L981.42 720.61 L981.20 726.03 L980.96 731.25 L980.71 736.28 L980.45 741.14 L980.16 745.84 L979.87 750.40 L979.56 754.83 L979.23 759.13 L978.90 763.31 L978.54 767.38 L978.17 771.35 L977.79 775.23 L977.39 779.01 L976.98 782.71 L976.55 786.32 L976.11 789.85 L975.65 793.32 L975.18 796.70 L974.70 800.03 L974.20 803.28 L973.68 806.48 L973.15 809.61 L972.60 812.69 L972.04 815.71 L971.46 818.68 L970.87 821.59 L970.27 824.46 L969.65 827.27 L969.01 830.04 L968.36 832.77 L967.69 835.45 L967.01 838.09 L966.31 840.69 L965.59 843.24 L964.86 845.76 L964.12 848.24 L963.36 850.68 L962.58 853.09 L961.79 855.46 L960.98 857.80 L960.16 860.10 L959.32 862.37 L958.46 864.60 L957.59 866.81 L956.70 868.98 L955.80 871.12 L954.88 873.24 L953.94 875.32 L952.99 877.38 L952.02 879.40 L951.03 881.40 L950.03 883.38 L949.01 885.32 L947.97 887.24 L946.91 889.13 L945.84 891.00 L944.75 892.84 L943.65 894.66 L942.52 896.45 L941.38 898.22 L940.22 899.97 L939.05 901.69 L937.85 903.39 L936.64 905.06 L935.41 906.72 L934.16 908.35 L932.89 909.96 L931.60 911.54 L930.30 913.11 L928.98 914.65 L927.63 916.18 L926.27 917.68 L924.89 919.16 L923.49 920.62 L922.06 922.06 L920.62 923.49 L919.16 924.89 L917.68 926.27 L916.18 927.63 L914.65 928.98 L913.11 930.30 L911.54 931.60 L909.96 932.89 L908.35 934.16 L906.72 935.41 L905.06 936.64 L903.39 937.85 L901.69 939.05 L899.97 940.22 L898.22 941.38 L896.45 942.52 L894.66 943.65 L892.84 944.75 L891.00 945.84 L889.13 946.91 L887.24 947.97 L885.32 949.01 L883.38 950.03 L881.40 951.03 L879.40 952.02 L877.38 952.99 L875.32 953.94 L873.24 954.88 L871.12 955.80 L868.98 956.70 L866.81 957.59 L864.60 958.46 L862.37 959.32 L860.10 960.16 L857.80 960.98 L855.46 961.79 L853.09 962.58 L850.68 963.36 L848.24 964.12 L845.76 964.86 L843.24 965.59 L840.69 966.31 L838.09 967.01 L835.45 967.69 L832.77 968.36 L830.04 969.01 L827.27 969.65 L824.46 970.27 L821.59 970.87 L818.68 971.46 L815.71 972.04 L812.69 972.60 L809.61 973.15 L806.48 973.68 L803.28 974.20 L800.03 974.70 L796.70 975.18 L793.32 975.65 L789.85 976.11 L786.32 976.55 L782.71 976.98 L779.01 977.39 L775.23 977.79 L771.35 978.17 L767.38 978.54 L763.31 978.90 L759.13 979.23 L754.83 979.56 L750.40 979.87 L745.84 980.16 L741.14 980.45 L736.28 980.71 L731.25 980.96 L726.03 981.20 L720.61 981.42 L714.96 981.63 L709.06 981.83 L702.88 982.01 L696.37 982.17 L689.49 982.32 L682.18 982.46 L674.36 982.58 L665.93 982.69 L656.74 982.78 L646.56 982.86 L635.08 982.93 L621.70 982.98 L605.28 983.01 L582.70 983.03 L512.00 983.04 L441.30 983.03 L418.72 983.01 L402.30 982.98 L388.92 982.93 L377.44 982.86 L367.26 982.78 L358.07 982.69 L349.64 982.58 L341.82 982.46 L334.51 982.32 L327.63 982.17 L321.12 982.01 L314.94 981.83 L309.04 981.63 L303.39 981.42 L297.97 981.20 L292.75 980.96 L287.72 980.71 L282.86 980.45 L278.16 980.16 L273.60 979.87 L269.17 979.56 L264.87 979.23 L260.69 978.90 L256.62 978.54 L252.65 978.17 L248.77 977.79 L244.99 977.39 L241.29 976.98 L237.68 976.55 L234.15 976.11 L230.68 975.65 L227.30 975.18 L223.97 974.70 L220.72 974.20 L217.52 973.68 L214.39 973.15 L211.31 972.60 L208.29 972.04 L205.32 971.46 L202.41 970.87 L199.54 970.27 L196.73 969.65 L193.96 969.01 L191.23 968.36 L188.55 967.69 L185.91 967.01 L183.31 966.31 L180.76 965.59 L178.24 964.86 L175.76 964.12 L173.32 963.36 L170.91 962.58 L168.54 961.79 L166.20 960.98 L163.90 960.16 L161.63 959.32 L159.40 958.46 L157.19 957.59 L155.02 956.70 L152.88 955.80 L150.76 954.88 L148.68 953.94 L146.62 952.99 L144.60 952.02 L142.60 951.03 L140.62 950.03 L138.68 949.01 L136.76 947.97 L134.87 946.91 L133.00 945.84 L131.16 944.75 L129.34 943.65 L127.55 942.52 L125.78 941.38 L124.03 940.22 L122.31 939.05 L120.61 937.85 L118.94 936.64 L117.28 935.41 L115.65 934.16 L114.04 932.89 L112.46 931.60 L110.89 930.30 L109.35 928.98 L107.82 927.63 L106.32 926.27 L104.84 924.89 L103.38 923.49 L101.94 922.06 L100.51 920.62 L99.11 919.16 L97.73 917.68 L96.37 916.18 L95.02 914.65 L93.70 913.11 L92.40 911.54 L91.11 909.96 L89.84 908.35 L88.59 906.72 L87.36 905.06 L86.15 903.39 L84.95 901.69 L83.78 899.97 L82.62 898.22 L81.48 896.45 L80.35 894.66 L79.25 892.84 L78.16 891.00 L77.09 889.13 L76.03 887.24 L74.99 885.32 L73.97 883.38 L72.97 881.40 L71.98 879.40 L71.01 877.38 L70.06 875.32 L69.12 873.24 L68.20 871.12 L67.30 868.98 L66.41 866.81 L65.54 864.60 L64.68 862.37 L63.84 860.10 L63.02 857.80 L62.21 855.46 L61.42 853.09 L60.64 850.68 L59.88 848.24 L59.14 845.76 L58.41 843.24 L57.69 840.69 L56.99 838.09 L56.31 835.45 L55.64 832.77 L54.99 830.04 L54.35 827.27 L53.73 824.46 L53.13 821.59 L52.54 818.68 L51.96 815.71 L51.40 812.69 L50.85 809.61 L50.32 806.48 L49.80 803.28 L49.30 800.03 L48.82 796.70 L48.35 793.32 L47.89 789.85 L47.45 786.32 L47.02 782.71 L46.61 779.01 L46.21 775.23 L45.83 771.35 L45.46 767.38 L45.10 763.31 L44.77 759.13 L44.44 754.83 L44.13 750.40 L43.84 745.84 L43.55 741.14 L43.29 736.28 L43.04 731.25 L42.80 726.03 L42.58 720.61 L42.37 714.96 L42.17 709.06 L41.99 702.88 L41.83 696.37 L41.68 689.49 L41.54 682.18 L41.42 674.36 L41.31 665.93 L41.22 656.74 L41.14 646.56 L41.07 635.08 L41.02 621.70 L40.99 605.28 L40.97 582.70 L40.96 512.00 L40.97 441.30 L40.99 418.72 L41.02 402.30 L41.07 388.92 L41.14 377.44 L41.22 367.26 L41.31 358.07 L41.42 349.64 L41.54 341.82 L41.68 334.51 L41.83 327.63 L41.99 321.12 L42.17 314.94 L42.37 309.04 L42.58 303.39 L42.80 297.97 L43.04 292.75 L43.29 287.72 L43.55 282.86 L43.84 278.16 L44.13 273.60 L44.44 269.17 L44.77 264.87 L45.10 260.69 L45.46 256.62 L45.83 252.65 L46.21 248.77 L46.61 244.99 L47.02 241.29 L47.45 237.68 L47.89 234.15 L48.35 230.68 L48.82 227.30 L49.30 223.97 L49.80 220.72 L50.32 217.52 L50.85 214.39 L51.40 211.31 L51.96 208.29 L52.54 205.32 L53.13 202.41 L53.73 199.54 L54.35 196.73 L54.99 193.96 L55.64 191.23 L56.31 188.55 L56.99 185.91 L57.69 183.31 L58.41 180.76 L59.14 178.24 L59.88 175.76 L60.64 173.32 L61.42 170.91 L62.21 168.54 L63.02 166.20 L63.84 163.90 L64.68 161.63 L65.54 159.40 L66.41 157.19 L67.30 155.02 L68.20 152.88 L69.12 150.76 L70.06 148.68 L71.01 146.62 L71.98 144.60 L72.97 142.60 L73.97 140.62 L74.99 138.68 L76.03 136.76 L77.09 134.87 L78.16 133.00 L79.25 131.16 L80.35 129.34 L81.48 127.55 L82.62 125.78 L83.78 124.03 L84.95 122.31 L86.15 120.61 L87.36 118.94 L88.59 117.28 L89.84 115.65 L91.11 114.04 L92.40 112.46 L93.70 110.89 L95.02 109.35 L96.37 107.82 L97.73 106.32 L99.11 104.84 L100.51 103.38 L101.94 101.94 L103.38 100.51 L104.84 99.11 L106.32 97.73 L107.82 96.37 L109.35 95.02 L110.89 93.70 L112.46 92.40 L114.04 91.11 L115.65 89.84 L117.28 88.59 L118.94 87.36 L120.61 86.15 L122.31 84.95 L124.03 83.78 L125.78 82.62 L127.55 81.48 L129.34 80.35 L131.16 79.25 L133.00 78.16 L134.87 77.09 L136.76 76.03 L138.68 74.99 L140.62 73.97 L142.60 72.97 L144.60 71.98 L146.62 71.01 L148.68 70.06 L150.76 69.12 L152.88 68.20 L155.02 67.30 L157.19 66.41 L159.40 65.54 L161.63 64.68 L163.90 63.84 L166.20 63.02 L168.54 62.21 L170.91 61.42 L173.32 60.64 L175.76 59.88 L178.24 59.14 L180.76 58.41 L183.31 57.69 L185.91 56.99 L188.55 56.31 L191.23 55.64 L193.96 54.99 L196.73 54.35 L199.54 53.73 L202.41 53.13 L205.32 52.54 L208.29 51.96 L211.31 51.40 L214.39 50.85 L217.52 50.32 L220.72 49.80 L223.97 49.30 L227.30 48.82 L230.68 48.35 L234.15 47.89 L237.68 47.45 L241.29 47.02 L244.99 46.61 L248.77 46.21 L252.65 45.83 L256.62 45.46 L260.69 45.10 L264.87 44.77 L269.17 44.44 L273.60 44.13 L278.16 43.84 L282.86 43.55 L287.72 43.29 L292.75 43.04 L297.97 42.80 L303.39 42.58 L309.04 42.37 L314.94 42.17 L321.12 41.99 L327.63 41.83 L334.51 41.68 L341.82 41.54 L349.64 41.42 L358.07 41.31 L367.26 41.22 L377.44 41.14 L388.92 41.07 L402.30 41.02 L418.72 40.99 L441.30 40.97 L512.00 40.96 L582.70 40.97 L605.28 40.99 L621.70 41.02 L635.08 41.07 L646.56 41.14 L656.74 41.22 L665.93 41.31 L674.36 41.42 L682.18 41.54 L689.49 41.68 L696.37 41.83 L702.88 41.99 L709.06 42.17 L714.96 42.37 L720.61 42.58 L726.03 42.80 L731.25 43.04 L736.28 43.29 L741.14 43.55 L745.84 43.84 L750.40 44.13 L754.83 44.44 L759.13 44.77 L763.31 45.10 L767.38 45.46 L771.35 45.83 L775.23 46.21 L779.01 46.61 L782.71 47.02 L786.32 47.45 L789.85 47.89 L793.32 48.35 L796.70 48.82 L800.03 49.30 L803.28 49.80 L806.48 50.32 L809.61 50.85 L812.69 51.40 L815.71 51.96 L818.68 52.54 L821.59 53.13 L824.46 53.73 L827.27 54.35 L830.04 54.99 L832.77 55.64 L835.45 56.31 L838.09 56.99 L840.69 57.69 L843.24 58.41 L845.76 59.14 L848.24 59.88 L850.68 60.64 L853.09 61.42 L855.46 62.21 L857.80 63.02 L860.10 63.84 L862.37 64.68 L864.60 65.54 L866.81 66.41 L868.98 67.30 L871.12 68.20 L873.24 69.12 L875.32 70.06 L877.38 71.01 L879.40 71.98 L881.40 72.97 L883.38 73.97 L885.32 74.99 L887.24 76.03 L889.13 77.09 L891.00 78.16 L892.84 79.25 L894.66 80.35 L896.45 81.48 L898.22 82.62 L899.97 83.78 L901.69 84.95 L903.39 86.15 L905.06 87.36 L906.72 88.59 L908.35 89.84 L909.96 91.11 L911.54 92.40 L913.11 93.70 L914.65 95.02 L916.18 96.37 L917.68 97.73 L919.16 99.11 L920.62 100.51 L922.06 101.94 L923.49 103.38 L924.89 104.84 L926.27 106.32 L927.63 107.82 L928.98 109.35 L930.30 110.89 L931.60 112.46 L932.89 114.04 L934.16 115.65 L935.41 117.28 L936.64 118.94 L937.85 120.61 L939.05 122.31 L940.22 124.03 L941.38 125.78 L942.52 127.55 L943.65 129.34 L944.75 131.16 L945.84 133.00 L946.91 134.87 L947.97 136.76 L949.01 138.68 L950.03 140.62 L951.03 142.60 L952.02 144.60 L952.99 146.62 L953.94 148.68 L954.88 150.76 L955.80 152.88 L956.70 155.02 L957.59 157.19 L958.46 159.40 L959.32 161.63 L960.16 163.90 L960.98 166.20 L961.79 168.54 L962.58 170.91 L963.36 173.32 L964.12 175.76 L964.86 178.24 L965.59 180.76 L966.31 183.31 L967.01 185.91 L967.69 188.55 L968.36 191.23 L969.01 193.96 L969.65 196.73 L970.27 199.54 L970.87 202.41 L971.46 205.32 L972.04 208.29 L972.60 211.31 L973.15 214.39 L973.68 217.52 L974.20 220.72 L974.70 223.97 L975.18 227.30 L975.65 230.68 L976.11 234.15 L976.55 237.68 L976.98 241.29 L977.39 244.99 L977.79 248.77 L978.17 252.65 L978.54 256.62 L978.90 260.69 L979.23 264.87 L979.56 269.17 L979.87 273.60 L980.16 278.16 L980.45 282.86 L980.71 287.72 L980.96 292.75 L981.20 297.97 L981.42 303.39 L981.63 309.04 L981.83 314.94 L982.01 321.12 L982.17 327.63 L982.32 334.51 L982.46 341.82 L982.58 349.64 L982.69 358.07 L982.78 367.26 L982.86 377.44 L982.93 388.92 L982.98 402.30 L983.01 418.72 L983.03 441.30 Z"/>
+<path fill="#0D0D0D" d="M256.00 377.40 C256.00 312.08 291.12 268.54 343.79 268.54 C396.47 268.54 431.59 312.08 431.59 377.40 L431.59 646.60 C431.59 711.92 396.47 755.46 343.79 755.46 C291.12 755.46 256.00 711.92 256.00 646.60 Z M450.77 530.47 C450.77 381.17 587.18 268.54 768.00 268.54 C768.00 417.84 631.59 530.47 450.77 530.47 Z M450.77 549.65 C450.77 666.96 565.35 755.46 717.24 755.46 C717.24 638.15 602.65 549.65 450.77 549.65 Z"/>
+</svg>
diff --git a/assets/brand/logo/kokon-logo-white.png b/assets/brand/logo/kokon-logo-white.png
new file mode 100644
index 0000000..5ddf572
Binary files /dev/null and b/assets/brand/logo/kokon-logo-white.png differ
diff --git a/assets/brand/logo/kokon-logo-white.svg b/assets/brand/logo/kokon-logo-white.svg
new file mode 100644
index 0000000..76b545b
--- /dev/null
+++ b/assets/brand/logo/kokon-logo-white.svg
@@ -0,0 +1,4 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1703 406" width="1703" height="406">
+<path fill="#F7F6F2" d="M40.00 112.82 C40.00 69.13 63.49 40.00 98.72 40.00 C133.96 40.00 157.45 69.13 157.45 112.82 L157.45 292.88 C157.45 336.57 133.96 365.70 98.72 365.70 C63.49 365.70 40.00 336.57 40.00 292.88 Z M170.28 215.20 C170.28 115.34 261.52 40.00 382.47 40.00 C382.47 139.87 291.23 215.20 170.28 215.20 Z M170.28 228.04 C170.28 306.50 246.93 365.70 348.52 365.70 C348.52 287.23 271.88 228.04 170.28 228.04 Z"/>
+<path fill="#F7F6F2" d="M509.48 348.25 L509.48 57.23 L561.63 57.23 L561.63 143.56 L560.85 205.87 C562.41 203.39 563.97 200.98 565.53 198.64 C571.65 189.65 578.13 180.80 584.97 172.08 C591.80 163.35 599.45 154.11 607.92 144.34 L684.28 57.23 L749.13 57.23 L637.41 183.21 L751.08 348.25 L689.56 348.25 L601.28 217.78 L561.63 260.94 L561.63 348.25 Z M875.11 352.74 C853.89 352.74 835.46 348.02 819.84 338.58 C804.21 329.14 792.14 315.99 783.61 299.13 C775.08 282.26 770.82 262.64 770.82 240.24 C770.82 217.58 775.08 197.76 783.61 180.77 C792.14 163.78 804.21 150.59 819.84 141.22 C835.46 131.84 853.89 127.15 875.11 127.15 C896.47 127.15 914.96 131.84 930.58 141.22 C946.21 150.59 958.28 163.78 966.81 180.77 C975.34 197.76 979.60 217.58 979.60 240.24 C979.60 262.64 975.34 282.26 966.81 299.13 C958.28 315.99 946.21 329.14 930.58 338.58 C914.96 348.02 896.47 352.74 875.11 352.74 Z M875.11 311.53 C886.96 311.53 896.83 308.34 904.70 301.96 C912.58 295.58 918.44 286.98 922.28 276.18 C926.12 265.37 928.04 253.33 928.04 240.04 C928.04 226.63 926.12 214.52 922.28 203.72 C918.44 192.91 912.58 184.32 904.70 177.94 C896.83 171.56 886.96 168.37 875.11 168.37 C863.26 168.37 853.47 171.56 845.72 177.94 C837.97 184.32 832.18 192.88 828.34 203.62 C824.49 214.36 822.57 226.50 822.57 240.04 C822.57 253.33 824.49 265.37 828.34 276.18 C832.18 286.98 837.97 295.58 845.72 301.96 C853.47 308.34 863.26 311.53 875.11 311.53 Z M1015.94 348.25 L1015.94 57.23 L1066.72 57.23 L1066.72 217.97 L1070.43 217.97 L1149.14 129.89 L1208.71 129.89 L1124.14 224.22 L1213.79 348.25 L1152.85 348.25 L1085.47 254.69 L1066.72 274.81 L1066.72 348.25 Z M1330.40 352.74 C1309.18 352.74 1290.75 348.02 1275.13 338.58 C1259.50 329.14 1247.43 315.99 1238.90 299.13 C1230.37 282.26 1226.10 262.64 1226.10 240.24 C1226.10 217.58 1230.37 197.76 1238.90 180.77 C1247.43 163.78 1259.50 150.59 1275.13 141.22 C1290.75 131.84 1309.18 127.15 1330.40 127.15 C1351.76 127.15 1370.25 131.84 1385.87 141.22 C1401.50 150.59 1413.57 163.78 1422.10 180.77 C1430.63 197.76 1434.89 217.58 1434.89 240.24 C1434.89 262.64 1430.63 282.26 1422.10 299.13 C1413.57 315.99 1401.50 329.14 1385.87 338.58 C1370.25 348.02 1351.76 352.74 1330.40 352.74 Z M1330.40 311.53 C1342.25 311.53 1352.11 308.34 1359.99 301.96 C1367.87 295.58 1373.73 286.98 1377.57 276.18 C1381.41 265.37 1383.33 253.33 1383.33 240.04 C1383.33 226.63 1381.41 214.52 1377.57 203.72 C1373.73 192.91 1367.87 184.32 1359.99 177.94 C1352.11 171.56 1342.25 168.37 1330.40 168.37 C1318.55 168.37 1308.75 171.56 1301.01 177.94 C1293.26 184.32 1287.47 192.88 1283.62 203.62 C1279.78 214.36 1277.86 226.50 1277.86 240.04 C1277.86 253.33 1279.78 265.37 1283.62 276.18 C1287.47 286.98 1293.26 295.58 1301.01 301.96 C1308.75 308.34 1318.55 311.53 1330.40 311.53 Z M1522.01 220.32 L1522.01 348.25 L1471.23 348.25 L1471.23 129.89 L1519.28 129.89 L1519.86 173.44 C1525.59 159.64 1533.27 148.96 1542.91 141.41 C1554.76 131.91 1569.60 127.15 1587.44 127.15 C1602.41 127.15 1615.50 130.34 1626.70 136.72 C1637.90 143.10 1646.59 152.41 1652.77 164.65 C1658.96 176.89 1662.05 191.80 1662.05 209.38 L1662.05 348.25 L1611.27 348.25 L1611.27 217.19 C1611.27 202.61 1607.49 191.15 1599.94 182.82 C1592.39 174.48 1581.97 170.32 1568.69 170.32 C1559.71 170.32 1551.70 172.27 1544.67 176.18 C1537.64 180.08 1532.10 185.78 1528.07 193.27 C1524.03 200.75 1522.01 209.77 1522.01 220.32 Z"/>
+</svg>
diff --git a/assets/brand/logo/kokon-logo.png b/assets/brand/logo/kokon-logo.png
new file mode 100644
index 0000000..3aac1ff
Binary files /dev/null and b/assets/brand/logo/kokon-logo.png differ
diff --git a/assets/brand/logo/kokon-logo.svg b/assets/brand/logo/kokon-logo.svg
new file mode 100644
index 0000000..a45654f
--- /dev/null
+++ b/assets/brand/logo/kokon-logo.svg
@@ -0,0 +1,4 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1703 406" width="1703" height="406">
+<path fill="#0D0D0D" d="M40.00 112.82 C40.00 69.13 63.49 40.00 98.72 40.00 C133.96 40.00 157.45 69.13 157.45 112.82 L157.45 292.88 C157.45 336.57 133.96 365.70 98.72 365.70 C63.49 365.70 40.00 336.57 40.00 292.88 Z M170.28 215.20 C170.28 115.34 261.52 40.00 382.47 40.00 C382.47 139.87 291.23 215.20 170.28 215.20 Z M170.28 228.04 C170.28 306.50 246.93 365.70 348.52 365.70 C348.52 287.23 271.88 228.04 170.28 228.04 Z"/>
+<path fill="#0D0D0D" d="M509.48 348.25 L509.48 57.23 L561.63 57.23 L561.63 143.56 L560.85 205.87 C562.41 203.39 563.97 200.98 565.53 198.64 C571.65 189.65 578.13 180.80 584.97 172.08 C591.80 163.35 599.45 154.11 607.92 144.34 L684.28 57.23 L749.13 57.23 L637.41 183.21 L751.08 348.25 L689.56 348.25 L601.28 217.78 L561.63 260.94 L561.63 348.25 Z M875.11 352.74 C853.89 352.74 835.46 348.02 819.84 338.58 C804.21 329.14 792.14 315.99 783.61 299.13 C775.08 282.26 770.82 262.64 770.82 240.24 C770.82 217.58 775.08 197.76 783.61 180.77 C792.14 163.78 804.21 150.59 819.84 141.22 C835.46 131.84 853.89 127.15 875.11 127.15 C896.47 127.15 914.96 131.84 930.58 141.22 C946.21 150.59 958.28 163.78 966.81 180.77 C975.34 197.76 979.60 217.58 979.60 240.24 C979.60 262.64 975.34 282.26 966.81 299.13 C958.28 315.99 946.21 329.14 930.58 338.58 C914.96 348.02 896.47 352.74 875.11 352.74 Z M875.11 311.53 C886.96 311.53 896.83 308.34 904.70 301.96 C912.58 295.58 918.44 286.98 922.28 276.18 C926.12 265.37 928.04 253.33 928.04 240.04 C928.04 226.63 926.12 214.52 922.28 203.72 C918.44 192.91 912.58 184.32 904.70 177.94 C896.83 171.56 886.96 168.37 875.11 168.37 C863.26 168.37 853.47 171.56 845.72 177.94 C837.97 184.32 832.18 192.88 828.34 203.62 C824.49 214.36 822.57 226.50 822.57 240.04 C822.57 253.33 824.49 265.37 828.34 276.18 C832.18 286.98 837.97 295.58 845.72 301.96 C853.47 308.34 863.26 311.53 875.11 311.53 Z M1015.94 348.25 L1015.94 57.23 L1066.72 57.23 L1066.72 217.97 L1070.43 217.97 L1149.14 129.89 L1208.71 129.89 L1124.14 224.22 L1213.79 348.25 L1152.85 348.25 L1085.47 254.69 L1066.72 274.81 L1066.72 348.25 Z M1330.40 352.74 C1309.18 352.74 1290.75 348.02 1275.13 338.58 C1259.50 329.14 1247.43 315.99 1238.90 299.13 C1230.37 282.26 1226.10 262.64 1226.10 240.24 C1226.10 217.58 1230.37 197.76 1238.90 180.77 C1247.43 163.78 1259.50 150.59 1275.13 141.22 C1290.75 131.84 1309.18 127.15 1330.40 127.15 C1351.76 127.15 1370.25 131.84 1385.87 141.22 C1401.50 150.59 1413.57 163.78 1422.10 180.77 C1430.63 197.76 1434.89 217.58 1434.89 240.24 C1434.89 262.64 1430.63 282.26 1422.10 299.13 C1413.57 315.99 1401.50 329.14 1385.87 338.58 C1370.25 348.02 1351.76 352.74 1330.40 352.74 Z M1330.40 311.53 C1342.25 311.53 1352.11 308.34 1359.99 301.96 C1367.87 295.58 1373.73 286.98 1377.57 276.18 C1381.41 265.37 1383.33 253.33 1383.33 240.04 C1383.33 226.63 1381.41 214.52 1377.57 203.72 C1373.73 192.91 1367.87 184.32 1359.99 177.94 C1352.11 171.56 1342.25 168.37 1330.40 168.37 C1318.55 168.37 1308.75 171.56 1301.01 177.94 C1293.26 184.32 1287.47 192.88 1283.62 203.62 C1279.78 214.36 1277.86 226.50 1277.86 240.04 C1277.86 253.33 1279.78 265.37 1283.62 276.18 C1287.47 286.98 1293.26 295.58 1301.01 301.96 C1308.75 308.34 1318.55 311.53 1330.40 311.53 Z M1522.01 220.32 L1522.01 348.25 L1471.23 348.25 L1471.23 129.89 L1519.28 129.89 L1519.86 173.44 C1525.59 159.64 1533.27 148.96 1542.91 141.41 C1554.76 131.91 1569.60 127.15 1587.44 127.15 C1602.41 127.15 1615.50 130.34 1626.70 136.72 C1637.90 143.10 1646.59 152.41 1652.77 164.65 C1658.96 176.89 1662.05 191.80 1662.05 209.38 L1662.05 348.25 L1611.27 348.25 L1611.27 217.19 C1611.27 202.61 1607.49 191.15 1599.94 182.82 C1592.39 174.48 1581.97 170.32 1568.69 170.32 C1559.71 170.32 1551.70 172.27 1544.67 176.18 C1537.64 180.08 1532.10 185.78 1528.07 193.27 C1524.03 200.75 1522.01 209.77 1522.01 220.32 Z"/>
+</svg>
diff --git a/assets/brand/mark/kokon-mark-1024.png b/assets/brand/mark/kokon-mark-1024.png
new file mode 100644
index 0000000..e0f7739
Binary files /dev/null and b/assets/brand/mark/kokon-mark-1024.png differ
diff --git a/assets/brand/mark/kokon-mark-white-1024.png b/assets/brand/mark/kokon-mark-white-1024.png
new file mode 100644
index 0000000..5d2aa71
Binary files /dev/null and b/assets/brand/mark/kokon-mark-white-1024.png differ
diff --git a/assets/brand/mark/kokon-mark-white.svg b/assets/brand/mark/kokon-mark-white.svg
new file mode 100644
index 0000000..a3c2223
--- /dev/null
+++ b/assets/brand/mark/kokon-mark-white.svg
@@ -0,0 +1,3 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024">
+<path fill="#F7F6F2" d="M0.00 242.81 C0.00 112.17 70.23 25.08 175.59 25.08 C280.94 25.08 351.17 112.17 351.17 242.81 L351.17 781.19 C351.17 911.83 280.94 998.92 175.59 998.92 C70.23 998.92 0.00 911.83 0.00 781.19 Z M389.53 548.95 C389.53 250.35 662.35 25.08 1024.00 25.08 C1024.00 323.68 751.18 548.95 389.53 548.95 Z M389.53 587.31 C389.53 821.93 618.71 998.92 922.49 998.92 C922.49 764.30 693.31 587.31 389.53 587.31 Z"/>
+</svg>
diff --git a/assets/brand/mark/kokon-mark.svg b/assets/brand/mark/kokon-mark.svg
new file mode 100644
index 0000000..47c1732
--- /dev/null
+++ b/assets/brand/mark/kokon-mark.svg
@@ -0,0 +1,3 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" width="1024" height="1024">
+<path fill="#0D0D0D" d="M0.00 242.81 C0.00 112.17 70.23 25.08 175.59 25.08 C280.94 25.08 351.17 112.17 351.17 242.81 L351.17 781.19 C351.17 911.83 280.94 998.92 175.59 998.92 C70.23 998.92 0.00 911.83 0.00 781.19 Z M389.53 548.95 C389.53 250.35 662.35 25.08 1024.00 25.08 C1024.00 323.68 751.18 548.95 389.53 548.95 Z M389.53 587.31 C389.53 821.93 618.71 998.92 922.49 998.92 C922.49 764.30 693.31 587.31 389.53 587.31 Z"/>
+</svg>
diff --git a/assets/brand/social/kokon-social-1280x640.png b/assets/brand/social/kokon-social-1280x640.png
new file mode 100644
index 0000000..3442e39
Binary files /dev/null and b/assets/brand/social/kokon-social-1280x640.png differ
diff --git a/assets/brand/web/apple-touch-icon.png b/assets/brand/web/apple-touch-icon.png
new file mode 100644
index 0000000..7b26358
Binary files /dev/null and b/assets/brand/web/apple-touch-icon.png differ
diff --git a/assets/brand/web/favicon.ico b/assets/brand/web/favicon.ico
new file mode 100644
index 0000000..75dfeae
Binary files /dev/null and b/assets/brand/web/favicon.ico differ
diff --git a/assets/brand/web/favicon.svg b/assets/brand/web/favicon.svg
new file mode 100644
index 0000000..997ec02
--- /dev/null
+++ b/assets/brand/web/favicon.svg
@@ -0,0 +1,4 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64">
+<path fill="#0D0D0D" d="M61.44 32.00 L61.44 36.42 L61.44 37.83 L61.44 38.86 L61.43 39.69 L61.43 40.41 L61.42 41.05 L61.42 41.62 L61.41 42.15 L61.40 42.64 L61.40 43.09 L61.39 43.52 L61.38 43.93 L61.36 44.32 L61.35 44.69 L61.34 45.04 L61.33 45.38 L61.31 45.70 L61.29 46.02 L61.28 46.32 L61.26 46.62 L61.24 46.90 L61.22 47.18 L61.20 47.45 L61.18 47.71 L61.16 47.96 L61.14 48.21 L61.11 48.45 L61.09 48.69 L61.06 48.92 L61.03 49.14 L61.01 49.37 L60.98 49.58 L60.95 49.79 L60.92 50.00 L60.89 50.21 L60.85 50.40 L60.82 50.60 L60.79 50.79 L60.75 50.98 L60.72 51.17 L60.68 51.35 L60.64 51.53 L60.60 51.70 L60.56 51.88 L60.52 52.05 L60.48 52.22 L60.44 52.38 L60.39 52.54 L60.35 52.70 L60.30 52.86 L60.26 53.02 L60.21 53.17 L60.16 53.32 L60.11 53.47 L60.06 53.61 L60.01 53.76 L59.96 53.90 L59.90 54.04 L59.85 54.18 L59.79 54.31 L59.74 54.45 L59.68 54.58 L59.62 54.71 L59.56 54.84 L59.50 54.96 L59.44 55.09 L59.38 55.21 L59.31 55.33 L59.25 55.45 L59.18 55.57 L59.12 55.69 L59.05 55.80 L58.98 55.92 L58.91 56.03 L58.84 56.14 L58.76 56.25 L58.69 56.36 L58.62 56.46 L58.54 56.57 L58.46 56.67 L58.38 56.77 L58.31 56.87 L58.23 56.97 L58.14 57.07 L58.06 57.17 L57.98 57.26 L57.89 57.35 L57.81 57.45 L57.72 57.54 L57.63 57.63 L57.54 57.72 L57.45 57.81 L57.35 57.89 L57.26 57.98 L57.17 58.06 L57.07 58.14 L56.97 58.23 L56.87 58.31 L56.77 58.38 L56.67 58.46 L56.57 58.54 L56.46 58.62 L56.36 58.69 L56.25 58.76 L56.14 58.84 L56.03 58.91 L55.92 58.98 L55.80 59.05 L55.69 59.12 L55.57 59.18 L55.45 59.25 L55.33 59.31 L55.21 59.38 L55.09 59.44 L54.96 59.50 L54.84 59.56 L54.71 59.62 L54.58 59.68 L54.45 59.74 L54.31 59.79 L54.18 59.85 L54.04 59.90 L53.90 59.96 L53.76 60.01 L53.61 60.06 L53.47 60.11 L53.32 60.16 L53.17 60.21 L53.02 60.26 L52.86 60.30 L52.70 60.35 L52.54 60.39 L52.38 60.44 L52.22 60.48 L52.05 60.52 L51.88 60.56 L51.70 60.60 L51.53 60.64 L51.35 60.68 L51.17 60.72 L50.98 60.75 L50.79 60.79 L50.60 60.82 L50.40 60.85 L50.21 60.89 L50.00 60.92 L49.79 60.95 L49.58 60.98 L49.37 61.01 L49.14 61.03 L48.92 61.06 L48.69 61.09 L48.45 61.11 L48.21 61.14 L47.96 61.16 L47.71 61.18 L47.45 61.20 L47.18 61.22 L46.90 61.24 L46.62 61.26 L46.32 61.28 L46.02 61.29 L45.70 61.31 L45.38 61.33 L45.04 61.34 L44.69 61.35 L44.32 61.36 L43.93 61.38 L43.52 61.39 L43.09 61.40 L42.64 61.40 L42.15 61.41 L41.62 61.42 L41.05 61.42 L40.41 61.43 L39.69 61.43 L38.86 61.44 L37.83 61.44 L36.42 61.44 L32.00 61.44 L27.58 61.44 L26.17 61.44 L25.14 61.44 L24.31 61.43 L23.59 61.43 L22.95 61.42 L22.38 61.42 L21.85 61.41 L21.36 61.40 L20.91 61.40 L20.48 61.39 L20.07 61.38 L19.68 61.36 L19.31 61.35 L18.96 61.34 L18.62 61.33 L18.30 61.31 L17.98 61.29 L17.68 61.28 L17.38 61.26 L17.10 61.24 L16.82 61.22 L16.55 61.20 L16.29 61.18 L16.04 61.16 L15.79 61.14 L15.55 61.11 L15.31 61.09 L15.08 61.06 L14.86 61.03 L14.63 61.01 L14.42 60.98 L14.21 60.95 L14.00 60.92 L13.79 60.89 L13.60 60.85 L13.40 60.82 L13.21 60.79 L13.02 60.75 L12.83 60.72 L12.65 60.68 L12.47 60.64 L12.30 60.60 L12.12 60.56 L11.95 60.52 L11.78 60.48 L11.62 60.44 L11.46 60.39 L11.30 60.35 L11.14 60.30 L10.98 60.26 L10.83 60.21 L10.68 60.16 L10.53 60.11 L10.39 60.06 L10.24 60.01 L10.10 59.96 L9.96 59.90 L9.82 59.85 L9.69 59.79 L9.55 59.74 L9.42 59.68 L9.29 59.62 L9.16 59.56 L9.04 59.50 L8.91 59.44 L8.79 59.38 L8.67 59.31 L8.55 59.25 L8.43 59.18 L8.31 59.12 L8.20 59.05 L8.08 58.98 L7.97 58.91 L7.86 58.84 L7.75 58.76 L7.64 58.69 L7.54 58.62 L7.43 58.54 L7.33 58.46 L7.23 58.38 L7.13 58.31 L7.03 58.23 L6.93 58.14 L6.83 58.06 L6.74 57.98 L6.65 57.89 L6.55 57.81 L6.46 57.72 L6.37 57.63 L6.28 57.54 L6.19 57.45 L6.11 57.35 L6.02 57.26 L5.94 57.17 L5.86 57.07 L5.77 56.97 L5.69 56.87 L5.62 56.77 L5.54 56.67 L5.46 56.57 L5.38 56.46 L5.31 56.36 L5.24 56.25 L5.16 56.14 L5.09 56.03 L5.02 55.92 L4.95 55.80 L4.88 55.69 L4.82 55.57 L4.75 55.45 L4.69 55.33 L4.62 55.21 L4.56 55.09 L4.50 54.96 L4.44 54.84 L4.38 54.71 L4.32 54.58 L4.26 54.45 L4.21 54.31 L4.15 54.18 L4.10 54.04 L4.04 53.90 L3.99 53.76 L3.94 53.61 L3.89 53.47 L3.84 53.32 L3.79 53.17 L3.74 53.02 L3.70 52.86 L3.65 52.70 L3.61 52.54 L3.56 52.38 L3.52 52.22 L3.48 52.05 L3.44 51.88 L3.40 51.70 L3.36 51.53 L3.32 51.35 L3.28 51.17 L3.25 50.98 L3.21 50.79 L3.18 50.60 L3.15 50.40 L3.11 50.21 L3.08 50.00 L3.05 49.79 L3.02 49.58 L2.99 49.37 L2.97 49.14 L2.94 48.92 L2.91 48.69 L2.89 48.45 L2.86 48.21 L2.84 47.96 L2.82 47.71 L2.80 47.45 L2.78 47.18 L2.76 46.90 L2.74 46.62 L2.72 46.32 L2.71 46.02 L2.69 45.70 L2.67 45.38 L2.66 45.04 L2.65 44.69 L2.64 44.32 L2.62 43.93 L2.61 43.52 L2.60 43.09 L2.60 42.64 L2.59 42.15 L2.58 41.62 L2.58 41.05 L2.57 40.41 L2.57 39.69 L2.56 38.86 L2.56 37.83 L2.56 36.42 L2.56 32.00 L2.56 27.58 L2.56 26.17 L2.56 25.14 L2.57 24.31 L2.57 23.59 L2.58 22.95 L2.58 22.38 L2.59 21.85 L2.60 21.36 L2.60 20.91 L2.61 20.48 L2.62 20.07 L2.64 19.68 L2.65 19.31 L2.66 18.96 L2.67 18.62 L2.69 18.30 L2.71 17.98 L2.72 17.68 L2.74 17.38 L2.76 17.10 L2.78 16.82 L2.80 16.55 L2.82 16.29 L2.84 16.04 L2.86 15.79 L2.89 15.55 L2.91 15.31 L2.94 15.08 L2.97 14.86 L2.99 14.63 L3.02 14.42 L3.05 14.21 L3.08 14.00 L3.11 13.79 L3.15 13.60 L3.18 13.40 L3.21 13.21 L3.25 13.02 L3.28 12.83 L3.32 12.65 L3.36 12.47 L3.40 12.30 L3.44 12.12 L3.48 11.95 L3.52 11.78 L3.56 11.62 L3.61 11.46 L3.65 11.30 L3.70 11.14 L3.74 10.98 L3.79 10.83 L3.84 10.68 L3.89 10.53 L3.94 10.39 L3.99 10.24 L4.04 10.10 L4.10 9.96 L4.15 9.82 L4.21 9.69 L4.26 9.55 L4.32 9.42 L4.38 9.29 L4.44 9.16 L4.50 9.04 L4.56 8.91 L4.62 8.79 L4.69 8.67 L4.75 8.55 L4.82 8.43 L4.88 8.31 L4.95 8.20 L5.02 8.08 L5.09 7.97 L5.16 7.86 L5.24 7.75 L5.31 7.64 L5.38 7.54 L5.46 7.43 L5.54 7.33 L5.62 7.23 L5.69 7.13 L5.77 7.03 L5.86 6.93 L5.94 6.83 L6.02 6.74 L6.11 6.65 L6.19 6.55 L6.28 6.46 L6.37 6.37 L6.46 6.28 L6.55 6.19 L6.65 6.11 L6.74 6.02 L6.83 5.94 L6.93 5.86 L7.03 5.77 L7.13 5.69 L7.23 5.62 L7.33 5.54 L7.43 5.46 L7.54 5.38 L7.64 5.31 L7.75 5.24 L7.86 5.16 L7.97 5.09 L8.08 5.02 L8.20 4.95 L8.31 4.88 L8.43 4.82 L8.55 4.75 L8.67 4.69 L8.79 4.62 L8.91 4.56 L9.04 4.50 L9.16 4.44 L9.29 4.38 L9.42 4.32 L9.55 4.26 L9.69 4.21 L9.82 4.15 L9.96 4.10 L10.10 4.04 L10.24 3.99 L10.39 3.94 L10.53 3.89 L10.68 3.84 L10.83 3.79 L10.98 3.74 L11.14 3.70 L11.30 3.65 L11.46 3.61 L11.62 3.56 L11.78 3.52 L11.95 3.48 L12.12 3.44 L12.30 3.40 L12.47 3.36 L12.65 3.32 L12.83 3.28 L13.02 3.25 L13.21 3.21 L13.40 3.18 L13.60 3.15 L13.79 3.11 L14.00 3.08 L14.21 3.05 L14.42 3.02 L14.63 2.99 L14.86 2.97 L15.08 2.94 L15.31 2.91 L15.55 2.89 L15.79 2.86 L16.04 2.84 L16.29 2.82 L16.55 2.80 L16.82 2.78 L17.10 2.76 L17.38 2.74 L17.68 2.72 L17.98 2.71 L18.30 2.69 L18.62 2.67 L18.96 2.66 L19.31 2.65 L19.68 2.64 L20.07 2.62 L20.48 2.61 L20.91 2.60 L21.36 2.60 L21.85 2.59 L22.38 2.58 L22.95 2.58 L23.59 2.57 L24.31 2.57 L25.14 2.56 L26.17 2.56 L27.58 2.56 L32.00 2.56 L36.42 2.56 L37.83 2.56 L38.86 2.56 L39.69 2.57 L40.41 2.57 L41.05 2.58 L41.62 2.58 L42.15 2.59 L42.64 2.60 L43.09 2.60 L43.52 2.61 L43.93 2.62 L44.32 2.64 L44.69 2.65 L45.04 2.66 L45.38 2.67 L45.70 2.69 L46.02 2.71 L46.32 2.72 L46.62 2.74 L46.90 2.76 L47.18 2.78 L47.45 2.80 L47.71 2.82 L47.96 2.84 L48.21 2.86 L48.45 2.89 L48.69 2.91 L48.92 2.94 L49.14 2.97 L49.37 2.99 L49.58 3.02 L49.79 3.05 L50.00 3.08 L50.21 3.11 L50.40 3.15 L50.60 3.18 L50.79 3.21 L50.98 3.25 L51.17 3.28 L51.35 3.32 L51.53 3.36 L51.70 3.40 L51.88 3.44 L52.05 3.48 L52.22 3.52 L52.38 3.56 L52.54 3.61 L52.70 3.65 L52.86 3.70 L53.02 3.74 L53.17 3.79 L53.32 3.84 L53.47 3.89 L53.61 3.94 L53.76 3.99 L53.90 4.04 L54.04 4.10 L54.18 4.15 L54.31 4.21 L54.45 4.26 L54.58 4.32 L54.71 4.38 L54.84 4.44 L54.96 4.50 L55.09 4.56 L55.21 4.62 L55.33 4.69 L55.45 4.75 L55.57 4.82 L55.69 4.88 L55.80 4.95 L55.92 5.02 L56.03 5.09 L56.14 5.16 L56.25 5.24 L56.36 5.31 L56.46 5.38 L56.57 5.46 L56.67 5.54 L56.77 5.62 L56.87 5.69 L56.97 5.77 L57.07 5.86 L57.17 5.94 L57.26 6.02 L57.35 6.11 L57.45 6.19 L57.54 6.28 L57.63 6.37 L57.72 6.46 L57.81 6.55 L57.89 6.65 L57.98 6.74 L58.06 6.83 L58.14 6.93 L58.23 7.03 L58.31 7.13 L58.38 7.23 L58.46 7.33 L58.54 7.43 L58.62 7.54 L58.69 7.64 L58.76 7.75 L58.84 7.86 L58.91 7.97 L58.98 8.08 L59.05 8.20 L59.12 8.31 L59.18 8.43 L59.25 8.55 L59.31 8.67 L59.38 8.79 L59.44 8.91 L59.50 9.04 L59.56 9.16 L59.62 9.29 L59.68 9.42 L59.74 9.55 L59.79 9.69 L59.85 9.82 L59.90 9.96 L59.96 10.10 L60.01 10.24 L60.06 10.39 L60.11 10.53 L60.16 10.68 L60.21 10.83 L60.26 10.98 L60.30 11.14 L60.35 11.30 L60.39 11.46 L60.44 11.62 L60.48 11.78 L60.52 11.95 L60.56 12.12 L60.60 12.30 L60.64 12.47 L60.68 12.65 L60.72 12.83 L60.75 13.02 L60.79 13.21 L60.82 13.40 L60.85 13.60 L60.89 13.79 L60.92 14.00 L60.95 14.21 L60.98 14.42 L61.01 14.63 L61.03 14.86 L61.06 15.08 L61.09 15.31 L61.11 15.55 L61.14 15.79 L61.16 16.04 L61.18 16.29 L61.20 16.55 L61.22 16.82 L61.24 17.10 L61.26 17.38 L61.28 17.68 L61.29 17.98 L61.31 18.30 L61.33 18.62 L61.34 18.96 L61.35 19.31 L61.36 19.68 L61.38 20.07 L61.39 20.48 L61.40 20.91 L61.40 21.36 L61.41 21.85 L61.42 22.38 L61.42 22.95 L61.43 23.59 L61.43 24.31 L61.44 25.14 L61.44 26.17 L61.44 27.58 Z"/>
+<path fill="#F7F6F2" d="M16.00 23.59 C16.00 19.51 18.19 16.78 21.49 16.78 C24.78 16.78 26.97 19.51 26.97 23.59 L26.97 40.41 C26.97 44.49 24.78 47.22 21.49 47.22 C18.19 47.22 16.00 44.49 16.00 40.41 Z M28.17 33.15 C28.17 23.82 36.70 16.78 48.00 16.78 C48.00 26.12 39.47 33.15 28.17 33.15 Z M28.17 34.35 C28.17 41.69 35.33 47.22 44.83 47.22 C44.83 39.88 37.67 34.35 28.17 34.35 Z"/>
+</svg>
diff --git a/assets/brand/web/icon-192.png b/assets/brand/web/icon-192.png
new file mode 100644
index 0000000..694c3ab
Binary files /dev/null and b/assets/brand/web/icon-192.png differ
diff --git a/assets/brand/web/icon-512.png b/assets/brand/web/icon-512.png
new file mode 100644
index 0000000..10abbec
Binary files /dev/null and b/assets/brand/web/icon-512.png differ
diff --git a/crates/qls-core/Cargo.toml b/crates/qls-core/Cargo.toml
index dba5589..d7ce493 100644
--- a/crates/qls-core/Cargo.toml
+++ b/crates/qls-core/Cargo.toml
@@ -8,12 +8,13 @@ anyhow = "1.0.104"
base64 = "0.23.1"
chrono = { version = "0.4.45", features = ["serde"] }
dirs = "7.0.0"
+futures-util = "0.3.34"
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"] }
+reqwest = { version = "0.13.5", default-features = false, features = ["json", "native-tls", "stream"] }
rusqlite = { version = "0.40.2", features = ["bundled"] }
serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.151"
@@ -23,6 +24,7 @@ thiserror = "2.0.21"
tokio = { version = "1.53.2", features = ["full"] }
tracing = "0.1.44"
uuid = { version = "1.27.0", features = ["v4"] }
+zip = { version = "8.6.0", default-features = false, features = ["deflate"] }
[target.'cfg(windows)'.dependencies]
windows = { version = "0.62", features = ["Win32_Graphics_Imaging", "Win32_System_Com"] }
diff --git a/crates/qls-core/examples/inpaint_preview.rs b/crates/qls-core/examples/inpaint_preview.rs
new file mode 100644
index 0000000..5a469ab
--- /dev/null
+++ b/crates/qls-core/examples/inpaint_preview.rs
@@ -0,0 +1,28 @@
+//! Writes the images an inpaint request would send (init/image 1, guide/image 2, mask) and
+//! prints the prompt, without running the model.
+//! `cargo run -p qls-core --example inpaint_preview -- <image> <mask> <out_dir> <action> [prompt]`
+
+use qls_core::geometry::Size;
+use qls_core::planner::{GenerationRequest, InpaintAction, Mode, Quality, plan};
+use qls_core::{config::AppConfig, engine, imaging, pipeline, sdcpp};
+
+fn main() {
+ let a: Vec<String> = std::env::args().collect();
+ let (img, mask, out) = (imaging::load_image(a[1].as_ref()).unwrap(), imaging::load_image(a[2].as_ref()).unwrap(), std::path::PathBuf::from(&a[3]));
+ let action: InpaintAction = serde_json::from_value(serde_json::json!(a[4])).unwrap();
+ let prompt = a.get(5).cloned().unwrap_or_default();
+ let m = imaging::mask_from_image(&mask);
+ let cfg = AppConfig::default();
+ let req = GenerationRequest { prompt: prompt.clone(), mode: Mode::Inpaint, mask: Some("m".into()), inpaint_action: action, quality: Quality::Quality, preserve_dimensions: true, ..Default::default() };
+ let info = (Size::new(m.width(), m.height()), imaging::mask_bbox(&m, 16), imaging::mask_coverage(&m, 16));
+ let p = plan(&req, &engine::plan_inputs(&cfg, vec![img.size()], Some(info), Some(16303)), &cfg.profile().recommended_settings).unwrap();
+ let j = pipeline::prepare(&p, &prompt, 1, std::slice::from_ref(&img), Some(&m), &Default::default()).unwrap();
+ std::fs::create_dir_all(&out).unwrap();
+ let save = |name: &str, b64: &str| std::fs::write(out.join(name), sdcpp::b64_decode(b64).unwrap()).unwrap();
+ save("init.png", j.request.init_image.as_ref().unwrap());
+ save("mask.png", j.request.mask_image.as_ref().unwrap());
+ for (i, r) in j.request.ref_images.iter().enumerate() {
+ save(&format!("ref{}.png", i + 1), r);
+ }
+ println!("working {:?} region {:?} refs {:?}\n{}", p.working, p.inpaint_region, p.references.iter().map(|r| r.canvas.canvas).collect::<Vec<_>>(), j.request.prompt);
+}
diff --git a/crates/qls-core/src/catalog.rs b/crates/qls-core/src/catalog.rs
new file mode 100644
index 0000000..c5218c2
--- /dev/null
+++ b/crates/qls-core/src/catalog.rs
@@ -0,0 +1,325 @@
+//! What the first-run wizard installs: the stable-diffusion.cpp build the app was verified
+//! with, the official Qwen-Image 2.1 weights, and the VRAM presets that choose between them.
+//!
+//! Every file is pinned by URL, size and SHA-256 (from the Hugging Face / GitHub APIs,
+//! 2026-10-08). If a link moves, the wizard reports it and asks the user to download the
+//! file by hand from `page` and to open an issue at [`ISSUES_URL`].
+
+use std::path::{Path, PathBuf};
+
+use serde::Serialize;
+
+use crate::config::TextEncoderPlacement;
+
+/// Where users report broken download links. Set before publishing the repository.
+pub const ISSUES_URL: &str = "https://github.com/OWNER/kokon/issues/new";
+
+/// Folder under the stable-diffusion.cpp folder that holds the Qwen weights.
+pub const MODEL_SUBDIR: &str = r"models\qwen21";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum FileKind {
+ /// stable-diffusion.cpp binaries (a zip extracted into the folder).
+ Engine,
+ Model,
+ /// Not needed to run (the ESRGAN upscaler; Lanczos is used without it).
+ Optional,
+}
+
+#[derive(Debug, Clone, Copy, Serialize)]
+pub struct Download {
+ pub id: &'static str,
+ pub label: &'static str,
+ pub kind: FileKind,
+ pub url: &'static str,
+ /// Page where the file can be downloaded by hand when `url` stops working.
+ pub page: &'static str,
+ pub size: u64,
+ pub sha256: &'static str,
+ /// Destination relative to the stable-diffusion.cpp folder (for a zip: the archive name,
+ /// extracted into the folder and then deleted).
+ pub dest: &'static str,
+ /// Files a zip provides; their presence means it is installed.
+ pub provides: &'static [&'static str],
+}
+
+impl Download {
+ pub fn is_zip(&self) -> bool {
+ !self.provides.is_empty()
+ }
+
+ pub fn path(&self, sdcpp_dir: &Path) -> PathBuf {
+ sdcpp_dir.join(self.dest)
+ }
+
+ /// Installed: a zip's files exist, or the file exists with the expected size. The hash is
+ /// checked after every download; a size match is enough for files already on disk.
+ pub fn is_present(&self, sdcpp_dir: &Path) -> bool {
+ if self.is_zip() {
+ return self.provides.iter().all(|f| sdcpp_dir.join(f).is_file());
+ }
+ std::fs::metadata(self.path(sdcpp_dir)).map(|m| m.is_file() && m.len() == self.size).unwrap_or(false)
+ }
+}
+
+const SDCPP_RELEASE: &str = "https://github.com/leejet/stable-diffusion.cpp/releases/tag/master-929-3f8527a";
+
+/// stable-diffusion.cpp commit 3f8527a (2026-09-27): the build every backend fact in the
+/// README was verified on. CUDA 12 build; it runs on RTX 20xx to RTX 50xx.
+pub const ENGINE_CUDA: Download = Download {
+ id: "engine_cuda",
+ label: "stable-diffusion.cpp (CUDA 12)",
+ kind: FileKind::Engine,
+ url: "https://github.com/leejet/stable-diffusion.cpp/releases/download/master-929-3f8527a/sd-master-3f8527a-bin-win-cuda12-x64.zip",
+ page: SDCPP_RELEASE,
+ size: 337_915_440,
+ sha256: "217d6dead9abd3f827fc338268555cc179234e7e6330ef21ecb1c985e19d2dc7",
+ dest: "sd-master-3f8527a-bin-win-cuda12-x64.zip",
+ provides: &["sd-server.exe", "stable-diffusion.dll", "ggml-cuda.dll"],
+};
+
+pub const CUDA_RUNTIME: Download = Download {
+ id: "cuda_runtime",
+ label: "CUDA 12 runtime (cuBLAS)",
+ kind: FileKind::Engine,
+ url: "https://github.com/leejet/stable-diffusion.cpp/releases/download/master-929-3f8527a/cudart-sd-bin-win-cu12-x64.zip",
+ page: SDCPP_RELEASE,
+ size: 563_452_046,
+ sha256: "fe20366827d357c00797eebb58244dddab7fd9a348d70090c3871004c320f38d",
+ dest: "cudart-sd-bin-win-cu12-x64.zip",
+ provides: &["cudart64_12.dll", "cublas64_12.dll", "cublasLt64_12.dll"],
+};
+
+const UNSLOTH: &str = "https://huggingface.co/unsloth/Qwen-Image-2.1-GGUF/tree/main";
+const QWEN_TE: &str = "https://huggingface.co/Qwen/Qwen3-VL-8B-Instruct-GGUF/tree/main";
+
+/// Official Qwen-Image 2.1 weights, 4-bit (Unsloth GGUF of Qwen/Qwen-Image-2.1).
+pub const DIFFUSION_Q4_K_M: Download = Download {
+ id: "diffusion_q4_k_m",
+ label: "Qwen-Image 2.1 Q4_K_M",
+ kind: FileKind::Model,
+ url: "https://huggingface.co/unsloth/Qwen-Image-2.1-GGUF/resolve/main/qwen-image-2.1-Q4_K_M.gguf",
+ page: UNSLOTH,
+ size: 4_199_565_024,
+ sha256: "631d532e7ca71e8d90a87c71d3699761a812039d22e3370e87498d87754660fe",
+ dest: r"models\qwen21\qwen-image-2.1-Q4_K_M.gguf",
+ provides: &[],
+};
+
+/// Official weights, 8-bit: closest to the original, for cards with room to spare.
+pub const DIFFUSION_Q8_0: Download = Download {
+ id: "diffusion_q8_0",
+ label: "Qwen-Image 2.1 Q8_0",
+ kind: FileKind::Model,
+ url: "https://huggingface.co/unsloth/Qwen-Image-2.1-GGUF/resolve/main/qwen-image-2.1-Q8_0.gguf",
+ page: UNSLOTH,
+ size: 7_640_860_384,
+ sha256: "c0ed4b2ffd56cbe9c3df1e4a4098045256484ebe94ba5a7e4338d35ec046baa5",
+ dest: r"models\qwen21\qwen-image-2.1-Q8_0.gguf",
+ provides: &[],
+};
+
+pub const VAE: Download = Download {
+ id: "vae",
+ label: "Qwen-Image 2.1 VAE",
+ kind: FileKind::Model,
+ url: "https://huggingface.co/Comfy-Org/Qwen-Image-2.1/resolve/main/vae/qwen_image_2.1_vae_bf16.safetensors",
+ page: "https://huggingface.co/Comfy-Org/Qwen-Image-2.1/tree/main/vae",
+ size: 675_509_688,
+ sha256: "bb21f7473051e1ac368515dd3f2e15cd44d7a11748ee8823e1ddca3e4876b7c9",
+ dest: r"models\qwen21\qwen_image_2.1_vae_bf16.safetensors",
+ provides: &[],
+};
+
+/// Text encoder from Qwen's own GGUF repository (the one sd.cpp's docs point to).
+pub const TEXT_ENCODER_Q4_K_M: Download = Download {
+ id: "text_encoder_q4_k_m",
+ label: "Qwen3-VL 8B text encoder Q4_K_M",
+ kind: FileKind::Model,
+ url: "https://huggingface.co/Qwen/Qwen3-VL-8B-Instruct-GGUF/resolve/main/Qwen3VL-8B-Instruct-Q4_K_M.gguf",
+ page: QWEN_TE,
+ size: 5_027_784_800,
+ sha256: "67d1659bfe71b89d50b45a4ad1a9e5b997e5bb16ce5da66a6a6167abd569e9e2",
+ dest: r"models\qwen21\Qwen3VL-8B-Instruct-Q4_K_M.gguf",
+ provides: &[],
+};
+
+pub const TEXT_ENCODER_Q8_0: Download = Download {
+ id: "text_encoder_q8_0",
+ label: "Qwen3-VL 8B text encoder Q8_0",
+ kind: FileKind::Model,
+ url: "https://huggingface.co/Qwen/Qwen3-VL-8B-Instruct-GGUF/resolve/main/Qwen3VL-8B-Instruct-Q8_0.gguf",
+ page: QWEN_TE,
+ size: 8_709_519_456,
+ sha256: "0d264b3941185d00a74f75c4245521dae088ff1efc90ab8d1754e83f5844adb0",
+ dest: r"models\qwen21\Qwen3VL-8B-Instruct-Q8_0.gguf",
+ provides: &[],
+};
+
+/// Vision projector: lets the text encoder see reference images (needed for editing).
+pub const VISION_PROJECTOR: Download = Download {
+ id: "vision_projector",
+ label: "Qwen3-VL vision projector",
+ kind: FileKind::Model,
+ url: "https://huggingface.co/Qwen/Qwen3-VL-8B-Instruct-GGUF/resolve/main/mmproj-Qwen3VL-8B-Instruct-F16.gguf",
+ page: QWEN_TE,
+ size: 1_159_029_824,
+ sha256: "ca524100ebf825c9a870db1c580d03879e0da0ab2541697e2458e64891cf9d38",
+ dest: r"models\qwen21\mmproj-Qwen3VL-8B-Instruct-F16.gguf",
+ provides: &[],
+};
+
+/// Default ESRGAN model (CC BY-NC-SA 4.0). Must match `config::UPSCALER_CHOICES[0]`.
+pub const UPSCALER: Download = Download {
+ id: "upscaler",
+ label: "4x-UltraSharp upscaler",
+ kind: FileKind::Optional,
+ url: "https://huggingface.co/uwg/upscaler/resolve/main/ESRGAN/4x-UltraSharp.pth",
+ page: "https://huggingface.co/uwg/upscaler/tree/main/ESRGAN",
+ size: 66_961_958,
+ sha256: "a5812231fc936b42af08a5edba784195495d303d5b3248c24489ef0c4021fe01",
+ dest: r"models\upscalers\4x-UltraSharp.pth",
+ provides: &[],
+};
+
+/// Hardware presets: which weights to download and how to run them, by VRAM.
+#[derive(Debug, Clone, Copy, Serialize)]
+pub struct Preset {
+ pub id: &'static str,
+ pub label: &'static str,
+ /// Smallest reported VRAM (MiB) this preset is recommended for.
+ pub min_vram_mib: u64,
+ pub diffusion: Download,
+ pub text_encoder: Download,
+ pub text_encoder_placement: TextEncoderPlacement,
+ /// Measured on real hardware of this class (otherwise only derived).
+ pub verified: bool,
+ pub summary: &'static str,
+}
+
+/// Ordered by VRAM. Cards report a bit less than their nominal size (16 GB → 16303 MiB),
+/// so thresholds sit between classes.
+pub const PRESETS: &[Preset] = &[
+ Preset {
+ id: "12gb",
+ label: "12 GB",
+ min_vram_mib: 0,
+ diffusion: DIFFUSION_Q4_K_M,
+ text_encoder: TEXT_ENCODER_Q4_K_M,
+ text_encoder_placement: TextEncoderPlacement::Ram,
+ verified: false,
+ summary: "4-bit model; text encoder in system RAM; smaller working sizes",
+ },
+ Preset {
+ id: "16gb",
+ label: "16 GB",
+ min_vram_mib: 14 * 1024,
+ diffusion: DIFFUSION_Q4_K_M,
+ text_encoder: TEXT_ENCODER_Q4_K_M,
+ text_encoder_placement: TextEncoderPlacement::Ram,
+ verified: true,
+ summary: "4-bit model; text encoder in system RAM; native 2K for Quality",
+ },
+ Preset {
+ id: "24gb",
+ label: "24 GB",
+ min_vram_mib: 20 * 1024,
+ diffusion: DIFFUSION_Q8_0,
+ text_encoder: TEXT_ENCODER_Q4_K_M,
+ text_encoder_placement: TextEncoderPlacement::Ram,
+ verified: false,
+ summary: "8-bit model (closest to the original); larger edits fit",
+ },
+ Preset {
+ id: "32gb",
+ label: "32 GB+",
+ min_vram_mib: 28 * 1024,
+ diffusion: DIFFUSION_Q8_0,
+ text_encoder: TEXT_ENCODER_Q8_0,
+ text_encoder_placement: TextEncoderPlacement::Ram,
+ verified: false,
+ summary: "8-bit model and 8-bit text encoder",
+ },
+];
+
+pub const DEFAULT_PRESET: &str = "16gb";
+
+pub fn preset(id: &str) -> Option<&'static Preset> {
+ PRESETS.iter().find(|p| p.id == id)
+}
+
+/// The preset for a card with `vram_mib` (None: unknown GPU → the 16 GB default).
+pub fn recommended_preset(vram_mib: Option<u64>) -> &'static Preset {
+ match vram_mib {
+ Some(v) => PRESETS.iter().rev().find(|p| v >= p.min_vram_mib).unwrap_or(&PRESETS[0]),
+ None => preset(DEFAULT_PRESET).unwrap(),
+ }
+}
+
+/// Everything a preset needs, in download order (small, essential files first).
+pub fn downloads_for(p: &Preset, with_upscaler: bool) -> Vec<Download> {
+ let mut v = vec![ENGINE_CUDA, CUDA_RUNTIME, VAE, VISION_PROJECTOR, p.text_encoder, p.diffusion];
+ if with_upscaler {
+ v.push(UPSCALER);
+ }
+ v
+}
+
+/// Message shown when a download keeps failing (moved link, changed file, server down).
+pub fn manual_download_hint(d: &Download, sdcpp_dir: &Path) -> String {
+ let target = if d.is_zip() { format!("extract it into {}", sdcpp_dir.display()) } else { format!("save it as {}", d.path(sdcpp_dir).display()) };
+ format!(
+ "Download {} by hand from {} and {target}, then press Check again. Please also open an issue at {ISSUES_URL} so the link can be fixed.",
+ d.label, d.page
+ )
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn presets_follow_vram() {
+ assert_eq!(recommended_preset(Some(12_288)).id, "12gb");
+ assert_eq!(recommended_preset(Some(11_264)).id, "12gb");
+ assert_eq!(recommended_preset(Some(8_192)).id, "12gb", "smaller cards get the lightest preset");
+ assert_eq!(recommended_preset(Some(16_303)).id, "16gb");
+ assert_eq!(recommended_preset(Some(24_564)).id, "24gb");
+ assert_eq!(recommended_preset(Some(32_607)).id, "32gb");
+ assert_eq!(recommended_preset(Some(49_140)).id, "32gb");
+ assert_eq!(recommended_preset(None).id, "16gb");
+ }
+
+ #[test]
+ fn catalog_is_well_formed() {
+ let all = [ENGINE_CUDA, CUDA_RUNTIME, DIFFUSION_Q4_K_M, DIFFUSION_Q8_0, VAE, TEXT_ENCODER_Q4_K_M, TEXT_ENCODER_Q8_0, VISION_PROJECTOR, UPSCALER];
+ for d in all {
+ assert!(d.url.starts_with("https://"), "{}", d.id);
+ assert_eq!(d.sha256.len(), 64, "{}", d.id);
+ assert!(d.sha256.chars().all(|c| c.is_ascii_hexdigit() && !c.is_ascii_uppercase()), "{}", d.id);
+ assert!(d.size > 0);
+ assert_eq!(d.is_zip(), d.kind == FileKind::Engine, "{}", d.id);
+ }
+ // The default upscaler matches the one Settings offers first.
+ assert!(UPSCALER.dest.ends_with(&format!("{}.pth", crate::config::DEFAULT_UPSCALER)));
+ for p in PRESETS {
+ assert_eq!(downloads_for(p, true).len(), 7);
+ }
+ }
+
+ #[test]
+ fn presence_checks() {
+ let dir = tempfile::tempdir().unwrap();
+ assert!(!VAE.is_present(dir.path()));
+ std::fs::create_dir_all(dir.path().join(MODEL_SUBDIR)).unwrap();
+ std::fs::write(VAE.path(dir.path()), b"short").unwrap();
+ assert!(!VAE.is_present(dir.path()), "a partial file is not installed");
+ for f in ENGINE_CUDA.provides {
+ std::fs::write(dir.path().join(f), b"x").unwrap();
+ }
+ assert!(ENGINE_CUDA.is_present(dir.path()));
+ let hint = manual_download_hint(&ENGINE_CUDA, dir.path());
+ assert!(hint.contains("extract it into") && hint.contains(ISSUES_URL));
+ }
+}
diff --git a/crates/qls-core/src/config.rs b/crates/qls-core/src/config.rs
index e5a5c56..0d27a4f 100644
--- a/crates/qls-core/src/config.rs
+++ b/crates/qls-core/src/config.rs
@@ -1,5 +1,5 @@
//! Persistent configuration and model profiles. Stored as JSON in
-//! `%APPDATA%\Qwen Local Studio\config.json`; every field has a default so older or
+//! `%APPDATA%\Kokon\config.json`; every field has a default so older or
//! partial files keep loading.
use std::path::{Path, PathBuf};
@@ -8,8 +8,13 @@ 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 APP_NAME: &str = "Kokon";
+/// Folder names before the app was renamed Kokon (2026-10-08); moved on first start.
+const LEGACY_CONFIG_DIR: &str = "Qwen Local Studio";
+const LEGACY_DATA_DIR: &str = "QwenLocalStudio";
+/// Distinct from the installer's program folder `%LOCALAPPDATA%\Kokon`, so uninstalling
+/// never touches the gallery or the models.
+pub const DATA_DIR_NAME: &str = "KokonData";
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
@@ -21,7 +26,9 @@ pub const UPSCALER_CHOICES: &[(&str, &str, &str)] = &[
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;
+const SCHEMA_VERSION: u32 = 5;
+/// Profile id of the official Qwen-Image 2.1 weights (the default since schema 5).
+pub const OFFICIAL_PROFILE_ID: &str = "qwen-image-2.1";
/// Where to download `name`, if it is one of [`UPSCALER_CHOICES`].
pub fn upscaler_download_url(name: &str) -> Option<&'static str> {
@@ -152,20 +159,23 @@ pub struct ModelProfile {
impl Default for ModelProfile {
fn default() -> Self {
- Self::qwen_image_21_q4(Path::new(DEFAULT_SDCPP_DIR))
+ Self::official(&default_sdcpp_dir(), crate::catalog::preset(crate::catalog::DEFAULT_PRESET).unwrap())
}
}
impl ModelProfile {
- pub fn qwen_image_21_q4(sdcpp_dir: &Path) -> Self {
- let m = sdcpp_dir.join("models").join("qwen21");
+ /// The official Qwen-Image 2.1 weights a hardware preset downloads (Unsloth GGUF of
+ /// Qwen/Qwen-Image-2.1, Qwen's own Qwen3-VL GGUF, the 2.1 VAE).
+ pub fn official(sdcpp_dir: &Path, preset: &crate::catalog::Preset) -> Self {
+ use crate::catalog::{VAE, VISION_PROJECTOR};
+ let quant = preset.diffusion.dest.rsplit('-').next().unwrap_or("").trim_end_matches(".gguf");
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")),
+ id: OFFICIAL_PROFILE_ID.into(),
+ display_name: format!("Qwen-Image 2.1 {quant} (official)"),
+ diffusion_model: preset.diffusion.path(sdcpp_dir),
+ vae: VAE.path(sdcpp_dir),
+ text_encoder: preset.text_encoder.path(sdcpp_dir),
+ vision_projector: Some(VISION_PROJECTOR.path(sdcpp_dir)),
backend_args: vec![],
recommended_settings: RecommendedSettings::default(),
capabilities: ProfileCapabilities::default(),
@@ -236,17 +246,22 @@ pub struct AppConfig {
/// many idle minutes. 0 disables.
pub idle_unload_minutes: u32,
pub setup_complete: bool,
+ /// Hardware preset chosen in the setup wizard (`catalog::PRESETS`).
+ pub hardware_preset: String,
+ /// Plan as if the GPU had this much VRAM (MiB); 0 = use the detected size. For testing
+ /// smaller cards on a larger one, together with a VRAM ballast (scripts/dev).
+ pub vram_override_mib: u64,
/// 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);
+ let sdcpp = 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(),
+ profiles: vec![ModelProfile::official(&sdcpp, crate::catalog::preset(crate::catalog::DEFAULT_PRESET).unwrap())],
+ active_profile: OFFICIAL_PROFILE_ID.into(),
sdcpp_dir: sdcpp,
server_port: DEFAULT_SERVER_PORT,
service_port: DEFAULT_SERVICE_PORT,
@@ -267,6 +282,8 @@ impl Default for AppConfig {
keep_server_running: false,
idle_unload_minutes: 15,
setup_complete: false,
+ hardware_preset: crate::catalog::DEFAULT_PRESET.into(),
+ vram_override_mib: 0,
ui: serde_json::json!({}),
}
}
@@ -279,21 +296,67 @@ pub fn default_output_dir() -> PathBuf {
.join(APP_NAME)
}
-/// `%APPDATA%\Qwen Local Studio` (roaming) — configuration.
+/// Where the setup wizard installs stable-diffusion.cpp and the models on a new install:
+/// `%LOCALAPPDATA%\KokonData\sdcpp`.
+pub fn default_sdcpp_dir() -> PathBuf {
+ data_dir().join("sdcpp")
+}
+
+/// `%APPDATA%\Kokon` (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)
+ migrate_dir(&dirs::config_dir().unwrap_or_else(std::env::temp_dir), LEGACY_CONFIG_DIR, APP_NAME)
}
-/// `%LOCALAPPDATA%\QwenLocalStudio` — gallery database, inputs, thumbnails, logs.
-/// Deliberately distinct from the installer's `%LOCALAPPDATA%\Qwen Local Studio`.
+/// `%LOCALAPPDATA%\KokonData` — gallery database, inputs, thumbnails, logs, models
+/// installed by the setup screen.
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")
+ migrate_dir(&dirs::data_local_dir().unwrap_or_else(std::env::temp_dir), LEGACY_DATA_DIR, DATA_DIR_NAME)
+}
+
+/// The data folder of the app's previous name (for relocating stored paths).
+fn legacy_data_dir() -> PathBuf {
+ dirs::data_local_dir().unwrap_or_else(std::env::temp_dir).join(LEGACY_DATA_DIR)
+}
+
+/// `base\new`, moving `base\old` there first if only the old folder exists (a rename on the
+/// same drive). If the move fails, e.g. while a service of the old version still holds its
+/// files, the old folder stays in use and the move is retried on the next start.
+pub fn migrate_dir(base: &Path, old: &str, new: &str) -> PathBuf {
+ let new_path = base.join(new);
+ let old_path = base.join(old);
+ // Unit tests must never move the real folders of this PC (tests call it with temp dirs).
+ if cfg!(test) && !base.starts_with(std::env::temp_dir()) {
+ return new_path;
+ }
+ if new_path.exists() || !old_path.is_dir() {
+ return new_path;
+ }
+ match std::fs::rename(&old_path, &new_path) {
+ Ok(()) => {
+ tracing::info!("moved {} to {}", old_path.display(), new_path.display());
+ new_path
+ }
+ Err(e) => {
+ tracing::warn!("could not move {} to {} ({e}); using the old folder", old_path.display(), new_path.display());
+ old_path
+ }
+ }
+}
+
+/// `p` inside the old data folder after that folder was moved: the same path in the new one.
+fn relocate(p: &mut PathBuf, old: &Path, new: &Path) {
+ if old.exists() || old == new {
+ return;
+ }
+ if let Ok(rest) = p.strip_prefix(old) {
+ *p = new.join(rest);
+ }
}
impl AppConfig {
@@ -311,7 +374,13 @@ impl AppConfig {
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));
+ c.profiles.push(ModelProfile::official(&c.sdcpp_dir, c.preset()));
+ c.active_profile = OFFICIAL_PROFILE_ID.into();
+ }
+ // A file without profiles got the default one, built for the default
+ // folder and preset: build it for the configured folder and preset.
+ if c.profiles.len() == 1 && c.profiles[0] == ModelProfile::default() {
+ c.profiles[0] = ModelProfile::official(&c.sdcpp_dir, c.preset());
}
if c.schema_version < 2 && c.upscaler_model.trim() == OLD_DEFAULT_UPSCALER {
c.upscaler_model = DEFAULT_UPSCALER.into();
@@ -353,6 +422,16 @@ impl AppConfig {
}
}
}
+ // Paths into the data folder of the app's old name (models installed by the
+ // setup screen) follow the folder to its new name.
+ if std::env::var("QLS_DATA_DIR").is_err() {
+ c.relocate_paths(&legacy_data_dir(), &data_dir());
+ }
+ if c.schema_version < 5 && !c.profiles.iter().any(|p| p.id == OFFICIAL_PROFILE_ID) {
+ // The official weights become available as a profile; the active one
+ // stays until the user downloads them (setup wizard) or switches.
+ c.profiles.push(ModelProfile::official(&c.sdcpp_dir, c.preset()));
+ }
c.schema_version = c.schema_version.max(SCHEMA_VERSION);
c
}
@@ -386,6 +465,46 @@ impl AppConfig {
self.profiles.iter().find(|p| p.id == self.active_profile).unwrap_or(&self.profiles[0])
}
+ pub fn relocate_paths(&mut self, old: &Path, new: &Path) {
+ relocate(&mut self.sdcpp_dir, old, new);
+ if let Some(d) = self.upscalers_dir.as_mut() {
+ relocate(d, old, new);
+ }
+ for p in &mut self.profiles {
+ for f in [&mut p.diffusion_model, &mut p.vae, &mut p.text_encoder] {
+ relocate(f, old, new);
+ }
+ if let Some(v) = p.vision_projector.as_mut() {
+ relocate(v, old, new);
+ }
+ }
+ }
+
+ pub fn preset(&self) -> &'static crate::catalog::Preset {
+ crate::catalog::preset(&self.hardware_preset).unwrap_or_else(|| crate::catalog::preset(crate::catalog::DEFAULT_PRESET).unwrap())
+ }
+
+ /// Switches to the official weights of `preset` (replacing an older official profile)
+ /// and its runtime settings. Used when the setup wizard finishes.
+ pub fn apply_preset(&mut self, preset: &crate::catalog::Preset) {
+ let mut profile = ModelProfile::official(&self.sdcpp_dir, preset);
+ if let Some(old) = self.profiles.iter().find(|p| p.id == OFFICIAL_PROFILE_ID) {
+ // Keep presets the user tuned on the official profile.
+ profile.recommended_settings = old.recommended_settings.clone();
+ profile.backend_args = old.backend_args.clone();
+ }
+ self.profiles.retain(|p| p.id != OFFICIAL_PROFILE_ID);
+ self.profiles.insert(0, profile);
+ self.active_profile = OFFICIAL_PROFILE_ID.into();
+ self.hardware_preset = preset.id.into();
+ self.text_encoder_placement = preset.text_encoder_placement;
+ }
+
+ /// VRAM the planner should assume: the override when set, otherwise the detected size.
+ pub fn planning_vram_mib(&self, detected: Option<u64>) -> Option<u64> {
+ if self.vram_override_mib > 0 { Some(self.vram_override_mib) } else { detected }
+ }
+
pub fn server_exe(&self) -> PathBuf {
self.sdcpp_dir.join("sd-server.exe")
}
@@ -427,6 +546,9 @@ impl AppConfig {
if self.profiles.is_empty() {
return Err(AppError::new(ErrorCode::InvalidConfig, "No model profile configured."));
}
+ if self.vram_override_mib != 0 && !(4096..=196_608).contains(&self.vram_override_mib) {
+ return Err(AppError::new(ErrorCode::InvalidConfig, "Simulated VRAM must be between 4096 and 196608 MiB (or 0 to detect it)."));
+ }
Ok(())
}
}
@@ -439,8 +561,12 @@ mod tests {
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!(p.id, OFFICIAL_PROFILE_ID);
+ assert_eq!(p.display_name, "Qwen-Image 2.1 Q4_K_M (official)");
+ assert!(p.diffusion_model.ends_with("qwen-image-2.1-Q4_K_M.gguf"));
+ assert!(p.diffusion_model.starts_with(default_sdcpp_dir()));
+ assert_eq!(c.hardware_preset, "16gb");
+ assert_eq!(c.planning_vram_mib(Some(16303)), Some(16303));
assert_eq!(c.device, "cuda0");
assert_eq!(c.vram_reserve_gib, 1.0);
assert!(c.flash_attention);
@@ -449,7 +575,67 @@ mod tests {
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"));
+ assert_eq!(c.upscalers_dir(), default_sdcpp_dir().join("models").join("upscalers"));
+ }
+
+ #[test]
+ fn official_profile_is_added_but_not_forced() {
+ let dir = tempfile::tempdir().unwrap();
+ let p = dir.path().join("config.json");
+ let old = r#"{"schemaVersion":4,"sdcppDir":"D:\\sd","activeProfile":"uc","profiles":[{"id":"uc","displayName":"UC","diffusionModel":"D:\\sd\\uc.gguf"}]}"#;
+ std::fs::write(&p, old).unwrap();
+ let c = AppConfig::load_from(&p);
+ assert_eq!(c.active_profile, "uc", "the user's choice stays active");
+ let off = c.profiles.iter().find(|p| p.id == OFFICIAL_PROFILE_ID).unwrap();
+ assert_eq!(off.diffusion_model, PathBuf::from(r"D:\sd\models\qwen21\qwen-image-2.1-Q4_K_M.gguf"));
+ // Saved again, nothing is added twice.
+ c.save_to(&p).unwrap();
+ assert_eq!(AppConfig::load_from(&p).profiles.len(), 2);
+ // A file without profiles uses its own folder and preset.
+ std::fs::write(&p, r#"{"sdcppDir":"D:\\sd","hardwarePreset":"24gb"}"#).unwrap();
+ let c = AppConfig::load_from(&p);
+ assert_eq!(c.profile().diffusion_model, PathBuf::from(r"D:\sd\models\qwen21\qwen-image-2.1-Q8_0.gguf"));
+ }
+
+ #[test]
+ fn old_folders_move_to_the_new_name() {
+ let base = tempfile::tempdir().unwrap();
+ std::fs::create_dir_all(base.path().join("QwenLocalStudio").join("inputs")).unwrap();
+ std::fs::write(base.path().join("QwenLocalStudio").join("gallery.db"), b"db").unwrap();
+ let d = migrate_dir(base.path(), "QwenLocalStudio", "KokonData");
+ assert_eq!(d, base.path().join("KokonData"));
+ assert!(d.join("gallery.db").is_file() && !base.path().join("QwenLocalStudio").exists());
+ // Once moved, nothing happens again; a fresh install just gets the new name.
+ assert_eq!(migrate_dir(base.path(), "QwenLocalStudio", "KokonData"), d);
+ assert_eq!(migrate_dir(base.path(), "Missing", "New"), base.path().join("New"));
+ // Model paths inside the moved folder follow it; others stay.
+ let (old, new) = (base.path().join("QwenLocalStudio"), d.clone());
+ let mut c = AppConfig::default();
+ c.sdcpp_dir = old.join("sdcpp");
+ c.apply_preset(crate::catalog::preset("16gb").unwrap());
+ c.profiles.push(ModelProfile { id: "mine".into(), diffusion_model: PathBuf::from(r"C:\AI\sdcpp\x.gguf"), ..ModelProfile::default() });
+ c.relocate_paths(&old, &new);
+ assert_eq!(c.sdcpp_dir, new.join("sdcpp"));
+ assert!(c.profile().diffusion_model.starts_with(new.join("sdcpp")));
+ assert_eq!(c.profiles[1].diffusion_model, PathBuf::from(r"C:\AI\sdcpp\x.gguf"));
+ }
+
+ #[test]
+ fn presets_switch_weights_and_keep_tuning() {
+ let mut c = AppConfig::default();
+ c.profiles[0].recommended_settings.steps_fast = 12;
+ c.apply_preset(crate::catalog::preset("32gb").unwrap());
+ let p = c.profile();
+ assert!(p.diffusion_model.ends_with("qwen-image-2.1-Q8_0.gguf"));
+ assert!(p.text_encoder.ends_with("Qwen3VL-8B-Instruct-Q8_0.gguf"));
+ assert_eq!(p.display_name, "Qwen-Image 2.1 Q8_0 (official)");
+ assert_eq!(p.recommended_settings.steps_fast, 12);
+ assert_eq!((c.hardware_preset.as_str(), c.profiles.len()), ("32gb", 1));
+ c.vram_override_mib = 12_288;
+ assert_eq!(c.planning_vram_mib(Some(16303)), Some(12_288));
+ assert!(c.validate().is_ok());
+ c.vram_override_mib = 100;
+ assert!(c.validate().is_err());
}
#[test]
diff --git a/crates/qls-core/src/diagnostics.rs b/crates/qls-core/src/diagnostics.rs
index 3fa9727..6ddf0c5 100644
--- a/crates/qls-core/src/diagnostics.rs
+++ b/crates/qls-core/src/diagnostics.rs
@@ -169,7 +169,7 @@ mod tests {
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)];
+ cfg.profiles = vec![crate::config::ModelProfile::official(&cfg.sdcpp_dir, cfg.preset())];
let r = setup_checks(&cfg, None);
assert!(!r.ready);
assert!(r.checks.iter().any(|c| c.id == "server_exe" && !c.ok));
diff --git a/crates/qls-core/src/engine.rs b/crates/qls-core/src/engine.rs
index 061708b..a3dd144 100644
--- a/crates/qls-core/src/engine.rs
+++ b/crates/qls-core/src/engine.rs
@@ -88,12 +88,18 @@ pub struct Engine {
cfg: RwLock<AppConfig>,
pub server: Arc<ServerManager>,
pub store: Arc<Store>,
+ /// Private mode: records in memory, files under `private_dir`; wiped by `clear_private`,
+ /// at start and at exit. Never listed in the gallery.
+ pub private_store: Arc<Store>,
+ private_dir: PathBuf,
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>)>,
+ /// First-run downloads (setup wizard).
+ pub installer: Arc<crate::installer::Installer>,
backend_version: Mutex<Option<String>>,
last_activity: Mutex<Instant>,
}
@@ -125,17 +131,27 @@ pub fn plan_inputs(cfg: &AppConfig, image_sizes: Vec<Size>, mask: Option<(Size,
impl Engine {
pub fn new(cfg: AppConfig, data_dir: &Path) -> AppResult<Arc<Self>> {
let store = Arc::new(Store::open(data_dir)?);
+ let private_dir = data_dir.join("private");
+ // Leftovers of a crash or forced exit while private mode was on.
+ let _ = std::fs::remove_dir_all(&private_dir);
+ for sub in ["inputs", "thumbs", "out"] {
+ std::fs::create_dir_all(private_dir.join(sub)).map_err(|e| AppError::io("create the data folder", &private_dir, e))?;
+ }
+ let private_store = Arc::new(Store::open_in_memory(&private_dir)?);
let (events, _) = broadcast::channel(512);
Ok(Arc::new(Self {
cfg: RwLock::new(cfg),
server: ServerManager::new(data_dir.to_path_buf()),
store,
+ private_store,
+ private_dir,
jobs: Mutex::new(HashMap::new()),
order: Mutex::new(VecDeque::new()),
active: Mutex::new(None),
wake: Notify::new(),
events,
gpu: Mutex::new((None, None)),
+ installer: crate::installer::Installer::new(),
backend_version: Mutex::new(None),
last_activity: Mutex::new(Instant::now()),
}))
@@ -157,6 +173,43 @@ impl Engine {
Ok(restart)
}
+ /// The store holding generation `id`: the gallery, or the private-mode store.
+ pub fn gen_store(&self, id: &str) -> &Arc<Store> {
+ if self.store.get_generation(id).is_err() && self.private_store.get_generation(id).is_ok() { &self.private_store } else { &self.store }
+ }
+
+ /// The store holding input `id` (see [`Self::gen_store`]).
+ pub fn input_store(&self, id: &str) -> &Arc<Store> {
+ if self.store.get_input(id).is_err() && self.private_store.get_input(id).is_ok() { &self.private_store } else { &self.store }
+ }
+
+ /// Where a generation's image file may be deleted from: the output folder, or the
+ /// private folder for private results.
+ pub fn output_root(&self, id: &str) -> PathBuf {
+ if Arc::ptr_eq(self.gen_store(id), &self.private_store) { self.private_dir.join("out") } else { self.config().output_dir }
+ }
+
+ /// Ends private mode: forgets every private record and deletes its files.
+ pub fn clear_private(&self) -> AppResult<usize> {
+ let (items, _) = self.private_store.list_generations(&crate::store::ListQuery { limit: Some(500), ..Default::default() })?;
+ self.private_store.clear()?;
+ let mut removed = 0;
+ for sub in ["inputs", "thumbs", "out"] {
+ let dir = self.private_dir.join(sub);
+ if let Ok(entries) = std::fs::read_dir(&dir) {
+ for e in entries.flatten() {
+ if std::fs::remove_file(e.path()).is_ok() {
+ removed += 1;
+ }
+ }
+ }
+ }
+ if !items.is_empty() {
+ tracing::info!("private mode cleared ({} results, {removed} files)", items.len());
+ }
+ Ok(items.len())
+ }
+
pub fn touch(&self) {
*self.last_activity.lock().unwrap() = Instant::now();
}
@@ -166,7 +219,7 @@ impl Engine {
}
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())
+ self.active.lock().unwrap().is_some() || self.jobs.lock().unwrap().values().any(|j| !j.view.status.is_terminal()) || self.installer.is_running()
}
pub fn gpu(&self) -> Option<GpuInfo> {
@@ -243,7 +296,9 @@ impl Engine {
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 {
+ // Removing a painted area needs no description (the planner writes the prompt).
+ let removal = request.mask.is_some() && request.inpaint_action == planner::InpaintAction::Remove;
+ if request.prompt.trim().is_empty() && !upscale && !removal {
return Err(AppError::invalid("Describe what to generate or change."));
}
if upscale && request.images.is_empty() {
@@ -380,14 +435,15 @@ impl Engine {
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)> {
+ /// Loads one image source: "input:<id>", "gen:<id>" or an absolute path. A private job
+ /// keeps its copy of the input in the private store.
+ pub fn resolve_source(&self, src: &str, workspace: Option<&Path>, private: bool) -> AppResult<(LoadedImage, InputRecord)> {
let (bytes, original_path, name) = if let Some(id) = src.strip_prefix("input:") {
- let rec = self.store.get_input(id)?;
+ let rec = self.input_store(id).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 rec = self.gen_store(id).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()))
@@ -396,7 +452,8 @@ impl Engine {
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 store = if private { &self.private_store } else { &self.store };
+ let rec = store.put_input(&bytes, name.as_deref(), original_path.as_deref())?;
let img = imaging::decode_image(&bytes)?;
Ok((img, rec))
}
@@ -404,7 +461,7 @@ impl Engine {
/// 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);
+ let vram = cfg.planning_vram_mib(self.gpu().map(|g| g.memory_total_mib));
planner::plan(req, &plan_inputs(&cfg, sizes, mask, vram), &cfg.profile().recommended_settings)
}
@@ -429,13 +486,13 @@ impl Engine {
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())?;
+ let (img, rec) = this.resolve_source(s, ws.as_deref(), req2.private)?;
images.push(img);
metas.push(rec);
}
let mask = match &req2.mask {
Some(m) => {
- let (img, rec) = this.resolve_source(m, ws.as_deref())?;
+ let (img, rec) = this.resolve_source(m, ws.as_deref(), req2.private)?;
Some((imaging::mask_from_image(&img), rec))
}
None => None,
@@ -449,7 +506,7 @@ impl Engine {
// 2. Plan.
let cfg = self.config();
let profile = cfg.profile().clone();
- let vram = self.gpu().map(|g| g.memory_total_mib);
+ let vram = cfg.planning_vram_mib(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)?;
@@ -658,7 +715,9 @@ impl Engine {
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" });
+ if !request.private {
+ let _ = self.events.send(Event::Gallery { id: rec.id.clone(), change: "added" });
+ }
records.push(rec);
}
self.update(id, |j| {
@@ -674,7 +733,7 @@ impl Engine {
/// 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());
+ let source = req.images.first().and_then(|s| s.strip_prefix("gen:")).and_then(|g| self.gen_store(g).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(),
@@ -820,7 +879,8 @@ impl Engine {
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());
+ let store = if req.private { &self.private_store } else { &self.store };
+ let dir = if req.private { self.private_dir.join("out") } else { 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(" ")));
@@ -907,9 +967,9 @@ impl Engine {
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);
+ let _ = std::fs::write(store.thumb_path(&id), j);
}
- self.store.insert_generation(&rec)?;
+ store.insert_generation(&rec)?;
Ok(rec)
}
}
@@ -1050,6 +1110,11 @@ mod tests {
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());
+ // Remove needs no prompt; other inpaint actions do.
+ let remove = GenerationRequest { images: vec!["gen:x".into()], mask: Some("input:m".into()), inpaint_action: planner::InpaintAction::Remove, ..Default::default() };
+ assert!(e.submit(GenerationRequest { inpaint_action: planner::InpaintAction::Replace, ..remove.clone() }, None).is_err());
+ let r = e.submit(remove, None).unwrap();
+ e.cancel(&r.id).unwrap();
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");
@@ -1073,6 +1138,32 @@ mod tests {
assert_eq!(e.job(&mcp.id).unwrap().status, JobStatus::Queued);
}
+ #[test]
+ fn private_results_stay_out_of_the_gallery() {
+ let dir = tempfile::tempdir().unwrap();
+ let e = Engine::new(AppConfig::default(), dir.path()).unwrap();
+ // A tiny PNG imported in private mode lives in the private store only.
+ let png = imaging::encode_png(&image::RgbaImage::from_pixel(8, 8, image::Rgba([200, 10, 10, 255])), &[], None, false).unwrap();
+ let input = e.private_store.put_input(&png, Some("secret.png"), None).unwrap();
+ assert!(e.store.get_input(&input.id).is_err());
+ assert!(Arc::ptr_eq(e.input_store(&input.id), &e.private_store));
+ assert!(Path::new(&input.path).starts_with(dir.path().join("private")));
+ let (_, rec) = e.resolve_source(&format!("input:{}", input.id), None, true).unwrap();
+ assert_eq!(rec.id, input.id);
+ assert!(e.store.get_input(&input.id).is_err(), "a private job does not copy its input into the gallery");
+ // Ending private mode deletes records and files.
+ assert_eq!(e.clear_private().unwrap(), 0);
+ assert!(e.private_store.get_input(&input.id).is_err());
+ assert!(!Path::new(&input.path).exists());
+ // A new engine wipes leftovers of a previous run.
+ std::fs::write(dir.path().join("private").join("out").join("left.png"), b"x").unwrap();
+ drop(e);
+ let _e = Engine::new(AppConfig::default(), dir.path()).unwrap();
+ assert!(!dir.path().join("private").join("out").join("left.png").exists());
+ let req: GenerationRequest = serde_json::from_str(r#"{"prompt":"x"}"#).unwrap();
+ assert!(!req.private, "off unless asked");
+ }
+
#[test]
fn plan_inputs_follow_config() {
let dir = tempfile::tempdir().unwrap();
diff --git a/crates/qls-core/src/hdr.rs b/crates/qls-core/src/hdr.rs
index 5a8059c..26a4a64 100644
--- a/crates/qls-core/src/hdr.rs
+++ b/crates/qls-core/src/hdr.rs
@@ -218,7 +218,7 @@ fn mpf(primary_len: u32, gain_len: u32, gain_offset: u32) -> Vec<u8> {
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>"#
+ r#"<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Kokon"><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>"#
)
}
@@ -240,7 +240,7 @@ fn gain_map_xmp(m: &GainMapMetadata) -> String {
.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>"#,
+ r#"<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Kokon"><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,
diff --git a/crates/qls-core/src/imaging.rs b/crates/qls-core/src/imaging.rs
index 44938ab..9fe0962 100644
--- a/crates/qls-core/src/imaging.rs
+++ b/crates/qls-core/src/imaging.rs
@@ -433,6 +433,163 @@ pub fn paste_back_mask(size: Size, expanded: crate::geometry::Expansion, feather
})
}
+/// Replaces the pixels where `mask` > 127 by a smooth continuation of the pixels around
+/// them (push-pull: weighted averages down a pyramid, then blended back up). Known pixels
+/// stay exact. Erases content before a removal so the model cannot copy it back.
+pub fn fill_masked(img: &RgbaImage, mask: &GrayImage) -> RgbaImage {
+ assert_eq!(img.dimensions(), mask.dimensions());
+ struct Level {
+ w: usize,
+ h: usize,
+ color: Vec<[f32; 4]>,
+ weight: Vec<f32>,
+ }
+ let (w, h) = (img.width() as usize, img.height() as usize);
+ let mut levels = vec![Level {
+ w,
+ h,
+ color: img.pixels().map(|p| [p[0] as f32, p[1] as f32, p[2] as f32, p[3] as f32]).collect(),
+ weight: mask.pixels().map(|m| if m[0] > 127 { 0.0 } else { 1.0 }).collect(),
+ }];
+ // Push: each coarser pixel is the weighted mean of its (up to) 4 children.
+ while levels.last().map(|l| l.w > 1 || l.h > 1).unwrap() {
+ let cur = levels.last().unwrap();
+ let (nw, nh) = (cur.w.div_ceil(2), cur.h.div_ceil(2));
+ let mut csum = vec![[0f32; 4]; nw * nh];
+ let mut wsum = vec![0f32; nw * nh];
+ for y in 0..cur.h {
+ for x in 0..cur.w {
+ let (i, j) = (y * cur.w + x, (y / 2) * nw + x / 2);
+ let wt = cur.weight[i];
+ for (s, v) in csum[j].iter_mut().zip(cur.color[i]) {
+ *s += v * wt;
+ }
+ wsum[j] += wt;
+ }
+ }
+ let color = csum.iter().zip(&wsum).map(|(c, &s)| if s > 0.0 { c.map(|v| v / s) } else { [128.0, 128.0, 128.0, 255.0] }).collect();
+ levels.push(Level { w: nw, h: nh, color, weight: wsum.iter().map(|s| s.min(1.0)).collect() });
+ }
+ // Pull: unknown (or partly known) pixels take the bilinearly upsampled coarser level.
+ for l in (0..levels.len() - 1).rev() {
+ let (fine, coarse) = levels.split_at_mut(l + 1);
+ let (f, c) = (&mut fine[l], &coarse[0]);
+ let sample = |x: usize, y: usize| -> [f32; 4] {
+ let fx = ((x as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (c.w - 1) as f32);
+ let fy = ((y as f32 + 0.5) / 2.0 - 0.5).clamp(0.0, (c.h - 1) as f32);
+ let (x0, y0) = (fx as usize, fy as usize);
+ let (x1, y1) = ((x0 + 1).min(c.w - 1), (y0 + 1).min(c.h - 1));
+ let (tx, ty) = (fx - x0 as f32, fy - y0 as f32);
+ let p = |x: usize, y: usize| c.color[y * c.w + x];
+ let (a, b, d, e) = (p(x0, y0), p(x1, y0), p(x0, y1), p(x1, y1));
+ std::array::from_fn(|k| (a[k] * (1.0 - tx) + b[k] * tx) * (1.0 - ty) + (d[k] * (1.0 - tx) + e[k] * tx) * ty)
+ };
+ for y in 0..f.h {
+ for x in 0..f.w {
+ let i = y * f.w + x;
+ let wt = f.weight[i];
+ if wt < 1.0 {
+ let up = sample(x, y);
+ f.color[i] = std::array::from_fn(|k| f.color[i][k] * wt + up[k] * (1.0 - wt));
+ }
+ }
+ }
+ }
+ let base = &levels[0];
+ let mut out = img.clone();
+ for (i, (p, m)) in out.pixels_mut().zip(mask.pixels()).enumerate() {
+ if m[0] > 127 {
+ *p = Rgba(base.color[i].map(|v| v.round().clamp(0.0, 255.0) as u8));
+ }
+ }
+ out
+}
+
+/// Colors for marking an area on a guide image, as named in the prompt.
+const HIGHLIGHTS: [(&str, [u8; 3]); 4] = [("red", [255, 0, 0]), ("green", [0, 230, 0]), ("blue", [0, 80, 255]), ("magenta", [255, 0, 255])];
+
+/// Highlight color for marking the area where `mask` > 127 on `img`: red (the usual choice)
+/// unless the area itself is largely reddish, else the color least present there.
+pub fn pick_highlight(img: &RgbaImage, mask: &GrayImage) -> (&'static str, [u8; 3]) {
+ assert_eq!(img.dimensions(), mask.dimensions());
+ let step = ((img.width() as usize * img.height() as usize) / 200_000).max(1);
+ let mut near = [0usize; HIGHLIGHTS.len()];
+ let mut n = 0usize;
+ for (p, m) in img.pixels().zip(mask.pixels()).step_by(step) {
+ if m[0] <= 127 {
+ continue;
+ }
+ n += 1;
+ for (k, (_, c)) in HIGHLIGHTS.iter().enumerate() {
+ let d: i32 = (0..3).map(|i| (p[i] as i32 - c[i] as i32).pow(2)).sum();
+ if d < 140 * 140 {
+ near[k] += 1;
+ }
+ }
+ }
+ if n == 0 || near[0] * 100 < n * 15 {
+ return HIGHLIGHTS[0];
+ }
+ let k = (0..HIGHLIGHTS.len()).min_by_key(|&k| near[k]).unwrap();
+ HIGHLIGHTS[k]
+}
+
+/// Guide image: `img` with the area where `mask` > 127 tinted with `color` and outlined,
+/// so a prompt can refer to "the area marked in red". Fully opaque.
+pub fn highlight(img: &RgbaImage, mask: &GrayImage, color: [u8; 3]) -> RgbaImage {
+ assert_eq!(img.dimensions(), mask.dimensions());
+ let inside = binarize(mask, 127);
+ let ring = dilate(&inside, (img.width().max(img.height()) / 200).max(2));
+ RgbaImage::from_fn(img.width(), img.height(), |x, y| {
+ let p = img.get_pixel(x, y);
+ if inside.get_pixel(x, y)[0] > 0 {
+ let tint = |i: usize| ((p[i] as u32 + color[i] as u32) / 2) as u8;
+ Rgba([tint(0), tint(1), tint(2), 255])
+ } else if ring.get_pixel(x, y)[0] > 0 {
+ Rgba([color[0], color[1], color[2], 255])
+ } else {
+ Rgba([p[0], p[1], p[2], 255])
+ }
+ })
+}
+
+#[cfg(test)]
+mod fill_tests {
+ use super::*;
+
+ #[test]
+ fn fill_masked_keeps_known_pixels_and_continues_colors() {
+ // Left half blue, right half green, a red square across the boundary.
+ let mut img = RgbaImage::from_fn(64, 32, |x, _| if x < 32 { Rgba([0, 0, 200, 255]) } else { Rgba([0, 200, 0, 255]) });
+ let mut m = GrayImage::new(64, 32);
+ for y in 8..24 {
+ for x in 20..44 {
+ img.put_pixel(x, y, Rgba([255, 0, 0, 255]));
+ m.put_pixel(x, y, Luma([255]));
+ }
+ }
+ let out = fill_masked(&img, &m);
+ for (x, y, p) in out.enumerate_pixels() {
+ if m.get_pixel(x, y)[0] == 0 {
+ assert_eq!(p, img.get_pixel(x, y));
+ } else {
+ assert!(p[0] < 40, "no red left at {x},{y}: {p:?}");
+ }
+ }
+ assert!(out.get_pixel(21, 16)[2] > out.get_pixel(21, 16)[1], "left side continues blue");
+ assert!(out.get_pixel(42, 16)[1] > out.get_pixel(42, 16)[2], "right side continues green");
+ }
+
+ #[test]
+ fn highlight_avoids_the_area_color() {
+ let red = RgbaImage::from_pixel(32, 32, Rgba([230, 20, 20, 255]));
+ let gray = RgbaImage::from_pixel(32, 32, Rgba([120, 120, 120, 255]));
+ let m = GrayImage::from_pixel(32, 32, Luma([255]));
+ assert_eq!(pick_highlight(&gray, &m).0, "red");
+ assert_ne!(pick_highlight(&red, &m).0, "red");
+ }
+}
+
pub fn thumbnail(img: &RgbaImage, max_side: u32) -> RgbaImage {
let (w, h) = (img.width(), img.height());
if w.max(h) <= max_side {
diff --git a/crates/qls-core/src/installer.rs b/crates/qls-core/src/installer.rs
new file mode 100644
index 0000000..e3f12f1
--- /dev/null
+++ b/crates/qls-core/src/installer.rs
@@ -0,0 +1,918 @@
+//! First-run installer: downloads what a hardware preset needs (see [`crate::catalog`])
+//! into the stable-diffusion.cpp folder, with progress, resume and SHA-256 checks.
+//!
+//! - Large files download over [`CONNECTIONS`] parallel connections, each fetching 16 MB
+//! segments with HTTP Range requests into `<file>.part`; finished segments are recorded in
+//! `<file>.part.segments`, so a pause or crash resumes where it stopped. GitHub's release CDN
+//! limits each connection (measured 2026-10-08: ~1 MB/s on one, 23 MB/s on eight).
+//! A server that ignores ranges gets one plain connection.
+//! - Every finished download is hashed; a mismatch deletes it and downloads once more.
+//! - A moved link (HTTP 404/403/410) or a second mismatch fails that file with instructions
+//! to download it by hand and to open an issue ([`crate::catalog::manual_download_hint`]).
+//! - Zips (the engine) are extracted into the folder and then deleted.
+//!
+//! Files already present (by size) are skipped. Network calls only go to the URLs in the
+//! catalog (GitHub releases and Hugging Face).
+
+use std::collections::VecDeque;
+use std::io::{Read, Write};
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::{Duration, Instant};
+
+use futures_util::StreamExt;
+use serde::{Deserialize, Serialize};
+use sha2::{Digest, Sha256};
+
+use crate::catalog::{Download, FileKind, manual_download_hint};
+use crate::error::{AppError, AppResult, ErrorCode};
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ItemState {
+ /// Already installed; nothing to do.
+ Present,
+ Pending,
+ Downloading,
+ Verifying,
+ Extracting,
+ Done,
+ Failed,
+ Cancelled,
+}
+
+#[derive(Debug, Clone, Serialize)]
+pub struct ItemStatus {
+ pub id: &'static str,
+ pub label: &'static str,
+ pub kind: FileKind,
+ pub size: u64,
+ pub received: u64,
+ pub state: ItemState,
+ pub error: Option<String>,
+ /// What to do by hand when the download cannot be fixed by retrying.
+ pub hint: Option<String>,
+ pub url: &'static str,
+ pub page: &'static str,
+ pub path: String,
+}
+
+#[derive(Debug, Clone, Serialize, Default)]
+pub struct InstallStatus {
+ pub running: bool,
+ /// Every item is installed.
+ pub complete: bool,
+ pub preset: Option<String>,
+ pub sdcpp_dir: Option<String>,
+ pub items: Vec<ItemStatus>,
+ pub bytes_per_sec: f64,
+ pub started_at: Option<String>,
+}
+
+#[derive(Default)]
+pub struct Installer {
+ status: Mutex<InstallStatus>,
+ cancel: AtomicBool,
+ /// Bytes received in this run (all files, all connections), for the speed estimate.
+ bytes: AtomicU64,
+}
+
+/// Called once when a run ends, with whether everything is installed.
+pub type OnFinish = Box<dyn FnOnce(bool) + Send>;
+
+const RETRIES: usize = 3;
+const CHUNK_TIMEOUT: Duration = Duration::from_secs(60);
+/// How often a connection waiting for data re-checks pause and "finished elsewhere".
+const POLL: Duration = Duration::from_millis(250);
+/// Parallel connections per file and the size of the pieces they fetch.
+pub const CONNECTIONS: usize = 8;
+const SEGMENT: u64 = 8 << 20;
+/// Endgame: a piece with less than this left is not worth a second connection.
+const RACE_MIN_LEFT: u64 = 512 << 10;
+const SEGMENT_RETRIES: u64 = 5;
+
+enum Failure {
+ /// Worth retrying (network error, server error, truncated stream).
+ Transient(String),
+ /// Retrying will not help (moved link, refused, file changed upstream).
+ Permanent(String),
+ Cancelled,
+ /// The server answered a range request with the whole file.
+ NoRanges,
+}
+
+impl Failure {
+ fn message(self) -> String {
+ match self {
+ Self::Transient(m) | Self::Permanent(m) => m,
+ Self::Cancelled => "Cancelled.".into(),
+ Self::NoRanges => "The server does not support partial downloads.".into(),
+ }
+ }
+}
+
+fn http_failure(status: reqwest::StatusCode, d: &Download) -> Failure {
+ match status.as_u16() {
+ 404 | 410 => Failure::Permanent(format!("The file is no longer at {} (HTTP {status}).", d.url)),
+ 401 | 403 => Failure::Permanent(format!("The server refused the download (HTTP {status}).")),
+ _ => Failure::Transient(format!("HTTP {status}")),
+ }
+}
+
+/// One file being fetched over several connections. When no piece is left to start, idle
+/// connections also fetch the piece with the most left ("endgame"): the bytes are identical,
+/// so both write them and the first to finish wins. One slow connection can then no longer
+/// hold up the end of a file.
+struct Segmented<'a> {
+ d: &'a Download,
+ client: &'a reqwest::Client,
+ part: &'a Path,
+ file: std::fs::File,
+ queue: Mutex<VecDeque<usize>>,
+ done: Vec<AtomicBool>,
+ /// Furthest point any connection reached inside each piece.
+ progress: Vec<AtomicU64>,
+ /// Connections working on each piece.
+ workers: Mutex<Vec<u8>>,
+ /// Serializes writes of the state file.
+ state_lock: Mutex<()>,
+ /// Another connection hit an error that ends this attempt.
+ stop: AtomicBool,
+}
+
+impl Segmented<'_> {
+ fn received(&self) -> u64 {
+ (0..self.done.len())
+ .map(|i| if self.done[i].load(Ordering::SeqCst) { segment_len(i, self.d.size) } else { self.progress[i].load(Ordering::SeqCst) })
+ .sum()
+ }
+
+ fn save_state(&self) {
+ let _g = self.state_lock.lock().unwrap();
+ let done: Vec<bool> = self.done.iter().map(|d| d.load(Ordering::SeqCst)).collect();
+ write_segment_state(self.part, self.d.size, &done);
+ }
+
+ /// The next piece: a queued one, or (endgame) the unfinished piece with the most left
+ /// that only one connection is fetching. The bool says whether it is a race.
+ fn next(&self) -> Option<(usize, bool)> {
+ let mut workers = self.workers.lock().unwrap();
+ let pick = if let Some(i) = self.queue.lock().unwrap().pop_front() {
+ Some((i, false))
+ } else {
+ (0..self.done.len())
+ .filter(|&i| workers[i] == 1 && !self.done[i].load(Ordering::SeqCst))
+ .map(|i| (i, segment_len(i, self.d.size).saturating_sub(self.progress[i].load(Ordering::SeqCst))))
+ .filter(|&(_, left)| left >= RACE_MIN_LEFT)
+ .max_by_key(|&(_, left)| left)
+ .map(|(i, _)| (i, true))
+ };
+ if let Some((i, _)) = pick {
+ workers[i] += 1;
+ }
+ pick
+ }
+}
+
+impl Installer {
+ pub fn new() -> Arc<Self> {
+ Arc::new(Self::default())
+ }
+
+ pub fn status(&self) -> InstallStatus {
+ self.status.lock().unwrap().clone()
+ }
+
+ pub fn is_running(&self) -> bool {
+ self.status.lock().unwrap().running
+ }
+
+ pub fn cancel(&self) {
+ self.cancel.store(true, Ordering::SeqCst);
+ }
+
+ /// Starts installing `downloads` into `dir` in the background.
+ pub fn start(self: &Arc<Self>, dir: PathBuf, preset: &str, downloads: Vec<Download>, on_finish: OnFinish) -> AppResult<()> {
+ {
+ let mut st = self.status.lock().unwrap();
+ if st.running {
+ return Err(AppError::new(ErrorCode::QueueFull, "An installation is already running."));
+ }
+ *st = InstallStatus {
+ running: true,
+ complete: false,
+ preset: Some(preset.to_string()),
+ sdcpp_dir: Some(dir.display().to_string()),
+ items: downloads.iter().map(|d| item_status(d, &dir)).collect(),
+ bytes_per_sec: 0.0,
+ started_at: Some(crate::store::now_rfc3339()),
+ };
+ }
+ self.cancel.store(false, Ordering::SeqCst);
+ self.bytes.store(0, Ordering::SeqCst);
+ // Smoothed overall speed, shown with the time left.
+ let meter = self.clone();
+ tokio::spawn(async move {
+ let mut last = (Instant::now(), 0u64);
+ loop {
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ let now = meter.bytes.load(Ordering::SeqCst);
+ let rate = (now - last.1) as f64 / last.0.elapsed().as_secs_f64();
+ last = (Instant::now(), now);
+ let mut st = meter.status.lock().unwrap();
+ if !st.running {
+ break;
+ }
+ st.bytes_per_sec = if st.bytes_per_sec > 0.0 { st.bytes_per_sec * 0.7 + rate * 0.3 } else { rate };
+ }
+ });
+ let this = self.clone();
+ tokio::spawn(async move {
+ let ok = this.run(&dir, &downloads).await;
+ let complete = ok && !this.cancel.load(Ordering::SeqCst);
+ {
+ let mut st = this.status.lock().unwrap();
+ st.running = false;
+ st.complete = complete;
+ st.bytes_per_sec = 0.0;
+ }
+ on_finish(complete);
+ });
+ Ok(())
+ }
+
+ fn set(&self, id: &str, f: impl FnOnce(&mut ItemStatus)) {
+ let mut st = self.status.lock().unwrap();
+ if let Some(it) = st.items.iter_mut().find(|i| i.id == id) {
+ f(it);
+ }
+ }
+
+ async fn run(&self, dir: &Path, downloads: &[Download]) -> bool {
+ if let Err(e) = std::fs::create_dir_all(dir) {
+ for d in downloads {
+ self.set(d.id, |i| {
+ i.state = ItemState::Failed;
+ i.error = Some(format!("Cannot create {}: {e}", dir.display()));
+ });
+ }
+ return false;
+ }
+ let client = match reqwest::Client::builder()
+ .user_agent(concat!("kokon/", env!("CARGO_PKG_VERSION")))
+ .connect_timeout(Duration::from_secs(20))
+ .build()
+ {
+ Ok(c) => c,
+ Err(e) => {
+ tracing::error!("HTTP client: {e}");
+ return false;
+ }
+ };
+ let mut all_ok = true;
+ for d in downloads {
+ if self.cancel.load(Ordering::SeqCst) {
+ self.set(d.id, |i| {
+ if i.state == ItemState::Pending {
+ i.state = ItemState::Cancelled;
+ }
+ });
+ all_ok = false;
+ continue;
+ }
+ if d.is_present(dir) {
+ self.set(d.id, |i| i.state = ItemState::Present);
+ continue;
+ }
+ match self.install_one(&client, d, dir).await {
+ Ok(()) => self.set(d.id, |i| {
+ i.state = ItemState::Done;
+ i.received = i.size;
+ }),
+ Err(Failure::Cancelled) => {
+ self.set(d.id, |i| i.state = ItemState::Cancelled);
+ all_ok = false;
+ }
+ Err(f) => {
+ let e = f.message();
+ tracing::warn!("install {} failed: {e}", d.id);
+ let hint = manual_download_hint(d, dir);
+ self.set(d.id, |i| {
+ i.state = ItemState::Failed;
+ i.error = Some(e);
+ i.hint = Some(hint);
+ });
+ // Optional files never block; keep going so other files still install.
+ if d.kind != FileKind::Optional {
+ all_ok = false;
+ }
+ }
+ }
+ }
+ all_ok
+ }
+
+ async fn install_one(&self, client: &reqwest::Client, d: &Download, dir: &Path) -> Result<(), Failure> {
+ let target = d.path(dir);
+ if let Some(parent) = target.parent() {
+ std::fs::create_dir_all(parent).map_err(|e| Failure::Permanent(format!("Cannot create {}: {e}", parent.display())))?;
+ }
+ let part = part_path(&target);
+ let mut mismatches = 0;
+ let mut attempt = 0;
+ loop {
+ attempt += 1;
+ match self.download(client, d, &part).await {
+ Ok(()) => {}
+ Err(Failure::Transient(e)) if attempt < RETRIES => {
+ tracing::info!("download {} interrupted ({e}); resuming", d.id);
+ tokio::time::sleep(Duration::from_secs(2 * attempt as u64)).await;
+ continue;
+ }
+ Err(e) => return Err(e),
+ }
+ self.set(d.id, |i| i.state = ItemState::Verifying);
+ let p = part.clone();
+ let hash = tokio::task::spawn_blocking(move || sha256_file(&p)).await.map_err(|e| Failure::Transient(e.to_string()))?;
+ let hash = hash.map_err(|e| Failure::Transient(format!("Cannot read the download: {e}")))?;
+ if hash == d.sha256 {
+ break;
+ }
+ remove_part(&part);
+ mismatches += 1;
+ if mismatches >= 2 {
+ return Err(Failure::Permanent(format!("The downloaded file does not match the expected checksum (got {}…). The file may have changed on the server.", &hash[..12])));
+ }
+ tracing::warn!("{}: checksum mismatch, downloading again", d.id);
+ attempt = 0;
+ }
+ if d.is_zip() {
+ self.set(d.id, |i| i.state = ItemState::Extracting);
+ let (p, out) = (part.clone(), dir.to_path_buf());
+ tokio::task::spawn_blocking(move || extract_zip(&p, &out))
+ .await
+ .map_err(|e| Failure::Transient(e.to_string()))?
+ .map_err(Failure::Permanent)?;
+ let _ = std::fs::remove_file(&part);
+ } else {
+ std::fs::rename(&part, &target).map_err(|e| Failure::Permanent(format!("Cannot save {}: {e}", target.display())))?;
+ }
+ Ok(())
+ }
+
+ /// Downloads (or resumes) `d` into `part` until it has `d.size` bytes.
+ async fn download(&self, client: &reqwest::Client, d: &Download, part: &Path) -> Result<(), Failure> {
+ if d.size >= 2 * SEGMENT {
+ match self.download_segmented(client, d, part).await {
+ Err(Failure::NoRanges) => {
+ tracing::info!("{}: the server ignores ranges; using one connection", d.id);
+ remove_part(part);
+ }
+ r => return r,
+ }
+ }
+ self.download_single(client, d, part).await
+ }
+
+ async fn download_segmented(&self, client: &reqwest::Client, d: &Download, part: &Path) -> Result<(), Failure> {
+ let done = done_segments(part, d.size);
+ let file = std::fs::OpenOptions::new()
+ .create(true)
+ .write(true)
+ .truncate(false)
+ .open(part)
+ .map_err(|e| Failure::Permanent(format!("Cannot write {}: {e}", part.display())))?;
+ file.set_len(d.size).map_err(|e| Failure::Permanent(format!("Cannot reserve {} for {}: {e} (is the disk full?)", human(d.size), part.display())))?;
+ write_segment_state(part, d.size, &done);
+ let s = Segmented {
+ d,
+ client,
+ part,
+ file,
+ queue: Mutex::new((0..done.len()).filter(|i| !done[*i]).collect()),
+ progress: (0..done.len()).map(|_| AtomicU64::new(0)).collect(),
+ workers: Mutex::new(vec![0; done.len()]),
+ done: done.into_iter().map(AtomicBool::new).collect(),
+ state_lock: Mutex::new(()),
+ stop: AtomicBool::new(false),
+ };
+ let have = s.received();
+ self.set(d.id, |i| {
+ i.state = ItemState::Downloading;
+ i.received = have;
+ i.error = None;
+ });
+ let finished = AtomicBool::new(false);
+ let work = async {
+ let r = futures_util::future::join_all((0..CONNECTIONS).map(|_| self.segment_worker(&s))).await;
+ finished.store(true, Ordering::SeqCst);
+ r
+ };
+ let progress = async {
+ while !finished.load(Ordering::SeqCst) {
+ tokio::time::sleep(Duration::from_millis(250)).await;
+ let r = s.received();
+ self.set(d.id, |i| i.received = r);
+ }
+ };
+ let (results, ()) = tokio::join!(work, progress);
+ // The most telling outcome wins: a dead link over a pause over a network hiccup.
+ let mut outcome = Ok(());
+ for r in results {
+ outcome = match (outcome, r) {
+ (Err(Failure::Permanent(m)), _) | (_, Err(Failure::Permanent(m))) => Err(Failure::Permanent(m)),
+ (Err(Failure::NoRanges), _) | (_, Err(Failure::NoRanges)) => Err(Failure::NoRanges),
+ (Err(Failure::Cancelled), _) | (_, Err(Failure::Cancelled)) => Err(Failure::Cancelled),
+ (Err(e), _) | (_, Err(e)) => Err(e),
+ (Ok(()), Ok(())) => Ok(()),
+ };
+ }
+ outcome?;
+ if s.done.iter().any(|x| !x.load(Ordering::SeqCst)) {
+ return Err(Failure::Transient("Some parts are still missing.".into()));
+ }
+ s.file.sync_all().map_err(|e| Failure::Transient(e.to_string()))?;
+ drop(s);
+ let _ = std::fs::remove_file(segments_path(part));
+ Ok(())
+ }
+
+ /// One connection: takes pieces until none is left, then helps with the slowest one.
+ async fn segment_worker(&self, s: &Segmented<'_>) -> Result<(), Failure> {
+ loop {
+ if self.cancel.load(Ordering::SeqCst) {
+ return Err(Failure::Cancelled);
+ }
+ if s.stop.load(Ordering::SeqCst) {
+ return Ok(());
+ }
+ let Some((i, race)) = s.next() else { return Ok(()) };
+ let mut attempt = 0;
+ let r = loop {
+ attempt += 1;
+ match self.fetch_segment(s, i).await {
+ Err(Failure::Transient(e)) if !race && attempt < SEGMENT_RETRIES => {
+ tracing::info!("{} part {i}: {e}; retrying", s.d.id);
+ tokio::time::sleep(Duration::from_secs(attempt)).await;
+ }
+ r => break r,
+ }
+ };
+ s.workers.lock().unwrap()[i] -= 1;
+ match r {
+ Ok(()) => {
+ if !s.done[i].swap(true, Ordering::SeqCst) {
+ s.save_state();
+ }
+ }
+ // A helper that failed leaves the piece to its first connection.
+ Err(Failure::Transient(_)) if race => {}
+ Err(e) => {
+ s.stop.store(true, Ordering::SeqCst);
+ return Err(e);
+ }
+ }
+ }
+ }
+
+ /// Fetches piece `i` into the file. Returns early (Ok) when another connection finished it.
+ async fn fetch_segment(&self, s: &Segmented<'_>, i: usize) -> Result<(), Failure> {
+ if s.done[i].load(Ordering::SeqCst) {
+ return Ok(());
+ }
+ let start = i as u64 * SEGMENT;
+ let end = start + segment_len(i, s.d.size); // exclusive
+ let resp = s.client.get(s.d.url).header(reqwest::header::RANGE, format!("bytes={start}-{}", end - 1)).send().await.map_err(|e| Failure::Transient(describe(&e)))?;
+ match resp.status().as_u16() {
+ 206 => {}
+ 200 => return Err(Failure::NoRanges),
+ _ => return Err(http_failure(resp.status(), s.d)),
+ }
+ if let Some(total) = content_range_total(resp.headers())
+ && total != s.d.size
+ {
+ return Err(Failure::Permanent(format!("The server offers {total} bytes, expected {}. The file may have changed on the server.", s.d.size)));
+ }
+ let mut pos = start;
+ let mut stream = resp.bytes_stream();
+ let mut idle = Duration::ZERO;
+ let r = loop {
+ if self.cancel.load(Ordering::SeqCst) {
+ break Err(Failure::Cancelled);
+ }
+ if s.stop.load(Ordering::SeqCst) {
+ break Err(Failure::Transient("Stopped.".into()));
+ }
+ if s.done[i].load(Ordering::SeqCst) {
+ return Ok(());
+ }
+ let chunk = match tokio::select! { c = stream.next() => Some(c), _ = tokio::time::sleep(POLL) => None } {
+ None => {
+ idle += POLL;
+ if idle >= CHUNK_TIMEOUT {
+ break Err(Failure::Transient("The download stalled.".into()));
+ }
+ continue;
+ }
+ Some(None) => break Ok(()),
+ Some(Some(Err(e))) => break Err(Failure::Transient(describe(&e))),
+ Some(Some(Ok(c))) => c,
+ };
+ idle = Duration::ZERO;
+ if pos + chunk.len() as u64 > end {
+ break Err(Failure::Transient("The server sent more than requested.".into()));
+ }
+ if let Err(e) = write_all_at(&s.file, &chunk, pos) {
+ break Err(Failure::Permanent(format!("Cannot write {}: {e} (is the disk full?)", s.part.display())));
+ }
+ pos += chunk.len() as u64;
+ s.progress[i].fetch_max(pos - start, Ordering::SeqCst);
+ self.bytes.fetch_add(chunk.len() as u64, Ordering::SeqCst);
+ };
+ let r = r.and_then(|()| if pos == end { Ok(()) } else { Err(Failure::Transient("A part ended early.".into())) });
+ if r.is_err() && s.workers.lock().unwrap()[i] <= 1 && !s.done[i].load(Ordering::SeqCst) {
+ // Nobody else is on this piece: it starts over, so its bytes no longer count.
+ s.progress[i].store(0, Ordering::SeqCst);
+ }
+ r
+ }
+
+ /// One plain connection, appending to `part` (small files, servers without ranges).
+ async fn download_single(&self, client: &reqwest::Client, d: &Download, part: &Path) -> Result<(), Failure> {
+ let mut have = std::fs::metadata(part).map(|m| m.len()).unwrap_or(0);
+ if have > d.size {
+ let _ = std::fs::remove_file(part);
+ have = 0;
+ }
+ if have == d.size {
+ return Ok(());
+ }
+ self.set(d.id, |i| {
+ i.state = ItemState::Downloading;
+ i.received = have;
+ i.error = None;
+ });
+ let mut req = client.get(d.url);
+ if have > 0 {
+ req = req.header(reqwest::header::RANGE, format!("bytes={have}-"));
+ }
+ let resp = req.send().await.map_err(|e| Failure::Transient(describe(&e)))?;
+ let status = resp.status();
+ let append = match status.as_u16() {
+ 206 => true,
+ 200 => false,
+ 416 => {
+ // The range starts at or past the end: start over.
+ let _ = std::fs::remove_file(part);
+ return Err(Failure::Transient("The partial download was not accepted; starting over.".into()));
+ }
+ _ => return Err(http_failure(status, d)),
+ };
+ if let Some(len) = resp.content_length() {
+ let total = if append { have + len } else { len };
+ if total != d.size {
+ return Err(Failure::Permanent(format!("The server offers {total} bytes, expected {}. The file may have changed on the server.", d.size)));
+ }
+ }
+ let mut file = std::fs::OpenOptions::new()
+ .create(true)
+ .write(true)
+ .append(append)
+ .truncate(!append)
+ .open(part)
+ .map_err(|e| Failure::Permanent(format!("Cannot write {}: {e}", part.display())))?;
+ let mut received = if append { have } else { 0 };
+ let mut stream = resp.bytes_stream();
+ let mut idle = Duration::ZERO;
+ loop {
+ if self.cancel.load(Ordering::SeqCst) {
+ return Err(Failure::Cancelled);
+ }
+ let chunk = match tokio::select! { c = stream.next() => Some(c), _ = tokio::time::sleep(POLL) => None } {
+ None => {
+ idle += POLL;
+ if idle >= CHUNK_TIMEOUT {
+ return Err(Failure::Transient("The download stalled.".into()));
+ }
+ continue;
+ }
+ Some(None) => break,
+ Some(Some(Err(e))) => return Err(Failure::Transient(describe(&e))),
+ Some(Some(Ok(c))) => c,
+ };
+ idle = Duration::ZERO;
+ file.write_all(&chunk).map_err(|e| Failure::Permanent(format!("Cannot write {}: {e} (is the disk full?)", part.display())))?;
+ received += chunk.len() as u64;
+ self.bytes.fetch_add(chunk.len() as u64, Ordering::SeqCst);
+ self.set(d.id, |i| i.received = received);
+ }
+ file.flush().map_err(|e| Failure::Permanent(e.to_string()))?;
+ if received != d.size {
+ return Err(Failure::Transient(format!("The download ended early ({received} of {} bytes).", d.size)));
+ }
+ Ok(())
+ }
+}
+
+fn item_status(d: &Download, dir: &Path) -> ItemStatus {
+ let present = d.is_present(dir);
+ ItemStatus {
+ id: d.id,
+ label: d.label,
+ kind: d.kind,
+ size: d.size,
+ received: if present { d.size } else { part_progress(&d.path(dir), d.size) },
+ state: if present { ItemState::Present } else { ItemState::Pending },
+ error: None,
+ hint: None,
+ url: d.url,
+ page: d.page,
+ path: if d.is_zip() { dir.display().to_string() } else { d.path(dir).display().to_string() },
+ }
+}
+
+/// The wizard's view of a preset before anything runs: which files are present.
+pub fn preview(dir: &Path, downloads: &[Download]) -> Vec<ItemStatus> {
+ downloads.iter().map(|d| item_status(d, dir)).collect()
+}
+
+/// Bytes still to download, and the disk space that needs (zips are also extracted).
+pub fn space_needed(dir: &Path, downloads: &[Download]) -> (u64, u64) {
+ let missing: Vec<&Download> = downloads.iter().filter(|d| !d.is_present(dir)).collect();
+ let download: u64 = missing.iter().map(|d| d.size - part_progress(&d.path(dir), d.size)).sum();
+ let disk: u64 = missing.iter().map(|d| if d.is_zip() { d.size * 5 / 2 } else { d.size }).sum();
+ (download, disk)
+}
+
+/// Free space on the drive that holds `dir` (or its nearest existing parent).
+pub fn free_space(dir: &Path) -> Option<u64> {
+ let mut p = dir.to_path_buf();
+ while !p.exists() {
+ p = p.parent()?.to_path_buf();
+ }
+ let p = crate::paths::dunce_canonical(&p).unwrap_or(p);
+ let disks = sysinfo::Disks::new_with_refreshed_list();
+ disks
+ .list()
+ .iter()
+ .filter(|d| p.starts_with(d.mount_point()))
+ .max_by_key(|d| d.mount_point().as_os_str().len())
+ .map(|d| d.available_space())
+}
+
+#[derive(Serialize, Deserialize)]
+struct SegmentState {
+ size: u64,
+ segment: u64,
+ done: Vec<usize>,
+}
+
+fn segments_path(part: &Path) -> PathBuf {
+ let mut s = part.as_os_str().to_os_string();
+ s.push(".segments");
+ PathBuf::from(s)
+}
+
+fn segment_len(i: usize, size: u64) -> u64 {
+ SEGMENT.min(size - i as u64 * SEGMENT)
+}
+
+fn write_segment_state(part: &Path, size: u64, done: &[bool]) {
+ let st = SegmentState { size, segment: SEGMENT, done: done.iter().enumerate().filter(|(_, d)| **d).map(|(i, _)| i).collect() };
+ let p = segments_path(part);
+ let tmp = p.with_extension("tmp");
+ if std::fs::write(&tmp, serde_json::to_vec(&st).unwrap_or_default()).is_ok() {
+ let _ = std::fs::rename(&tmp, &p);
+ }
+}
+
+/// Segments of a `size`-byte download already in `part`: from the state file, or, for a part
+/// written by one plain connection, every whole segment of its prefix.
+fn done_segments(part: &Path, size: u64) -> Vec<bool> {
+ let n = size.div_ceil(SEGMENT) as usize;
+ let mut done = vec![false; n];
+ let state_file = segments_path(part);
+ if state_file.exists() {
+ // A state file for another size or segment length (or a damaged one): start over.
+ let st = std::fs::read(&state_file).ok().and_then(|b| serde_json::from_slice::<SegmentState>(&b).ok());
+ if let Some(st) = st.filter(|st| st.size == size && st.segment == SEGMENT) {
+ for i in st.done.into_iter().filter(|i| *i < n) {
+ done[i] = true;
+ }
+ }
+ } else {
+ {
+ let have = std::fs::metadata(part).map(|m| m.len()).unwrap_or(0);
+ let whole = if have == size { n } else { (have.min(size) / SEGMENT) as usize };
+ done.iter_mut().take(whole).for_each(|d| *d = true);
+ }
+ }
+ done
+}
+
+/// Bytes of `target` already downloaded.
+fn part_progress(target: &Path, size: u64) -> u64 {
+ let part = part_path(target);
+ if !part.exists() {
+ return 0;
+ }
+ if size < 2 * SEGMENT {
+ return std::fs::metadata(&part).map(|m| m.len().min(size)).unwrap_or(0);
+ }
+ done_segments(&part, size).iter().enumerate().filter(|(_, d)| **d).map(|(i, _)| segment_len(i, size)).sum()
+}
+
+fn remove_part(part: &Path) {
+ let _ = std::fs::remove_file(part);
+ let _ = std::fs::remove_file(segments_path(part));
+}
+
+/// `Content-Range: bytes a-b/total` → total.
+fn content_range_total(h: &reqwest::header::HeaderMap) -> Option<u64> {
+ h.get(reqwest::header::CONTENT_RANGE)?.to_str().ok()?.rsplit('/').next()?.parse().ok()
+}
+
+fn write_all_at(f: &std::fs::File, mut buf: &[u8], mut pos: u64) -> std::io::Result<()> {
+ while !buf.is_empty() {
+ #[cfg(windows)]
+ let n = std::os::windows::fs::FileExt::seek_write(f, buf, pos)?;
+ #[cfg(unix)]
+ let n = std::os::unix::fs::FileExt::write_at(f, buf, pos)?;
+ if n == 0 {
+ return Err(std::io::ErrorKind::WriteZero.into());
+ }
+ buf = &buf[n..];
+ pos += n as u64;
+ }
+ Ok(())
+}
+
+pub(crate) fn human(n: u64) -> String {
+ format!("{:.1} GB", n as f64 / 1e9)
+}
+
+fn part_path(target: &Path) -> PathBuf {
+ let mut s = target.as_os_str().to_os_string();
+ s.push(".part");
+ PathBuf::from(s)
+}
+
+fn describe(e: &reqwest::Error) -> String {
+ if e.is_connect() {
+ "Could not connect (check the internet connection).".into()
+ } else if e.is_timeout() {
+ "The connection timed out.".into()
+ } else {
+ e.to_string()
+ }
+}
+
+pub fn sha256_file(path: &Path) -> std::io::Result<String> {
+ let mut f = std::fs::File::open(path)?;
+ let mut h = Sha256::new();
+ let mut buf = vec![0u8; 1 << 20];
+ loop {
+ let n = f.read(&mut buf)?;
+ if n == 0 {
+ break;
+ }
+ h.update(&buf[..n]);
+ }
+ Ok(hex::encode(h.finalize()))
+}
+
+/// Extracts every file of `zip` into `out` (flat or nested; no path may leave `out`).
+/// Existing files are replaced, e.g. when updating the engine.
+pub fn extract_zip(zip: &Path, out: &Path) -> Result<(), String> {
+ let f = std::fs::File::open(zip).map_err(|e| e.to_string())?;
+ let mut ar = zip::ZipArchive::new(f).map_err(|e| format!("The archive is damaged: {e}"))?;
+ for i in 0..ar.len() {
+ let mut entry = ar.by_index(i).map_err(|e| format!("The archive is damaged: {e}"))?;
+ let Some(rel) = entry.enclosed_name() else { return Err(format!("Unsafe path in the archive: {}", entry.name())) };
+ let dest = out.join(rel);
+ if entry.is_dir() {
+ std::fs::create_dir_all(&dest).map_err(|e| e.to_string())?;
+ continue;
+ }
+ if let Some(p) = dest.parent() {
+ std::fs::create_dir_all(p).map_err(|e| e.to_string())?;
+ }
+ let tmp = part_path(&dest);
+ let mut w = std::fs::File::create(&tmp).map_err(|e| format!("Cannot write {}: {e}", tmp.display()))?;
+ std::io::copy(&mut entry, &mut w).map_err(|e| format!("Cannot extract {}: {e}", dest.display()))?;
+ drop(w);
+ std::fs::rename(&tmp, &dest).map_err(|e| {
+ let _ = std::fs::remove_file(&tmp);
+ format!("Cannot replace {} (is stable-diffusion.cpp still running?): {e}", dest.display())
+ })?;
+ }
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn zip_extraction_is_contained() {
+ let dir = tempfile::tempdir().unwrap();
+ let zp = dir.path().join("a.zip");
+ {
+ let mut z = zip::ZipWriter::new(std::fs::File::create(&zp).unwrap());
+ let o = zip::write::SimpleFileOptions::default();
+ z.start_file("sd-server.exe", o).unwrap();
+ z.write_all(b"exe").unwrap();
+ z.start_file("sub/x.txt", o).unwrap();
+ z.write_all(b"x").unwrap();
+ z.finish().unwrap();
+ }
+ let out = dir.path().join("out");
+ std::fs::create_dir_all(&out).unwrap();
+ std::fs::write(out.join("sd-server.exe"), b"old").unwrap();
+ extract_zip(&zp, &out).unwrap();
+ assert_eq!(std::fs::read(out.join("sd-server.exe")).unwrap(), b"exe", "replaced");
+ assert!(out.join("sub").join("x.txt").is_file());
+
+ let evil = dir.path().join("evil.zip");
+ {
+ let mut z = zip::ZipWriter::new(std::fs::File::create(&evil).unwrap());
+ z.start_file("../escape.txt", zip::write::SimpleFileOptions::default()).unwrap();
+ z.write_all(b"x").unwrap();
+ z.finish().unwrap();
+ }
+ assert!(extract_zip(&evil, &out).is_err());
+ assert!(!dir.path().join("escape.txt").exists());
+ }
+
+ #[test]
+ fn hashing_and_space() {
+ let dir = tempfile::tempdir().unwrap();
+ let f = dir.path().join("f");
+ std::fs::write(&f, b"abc").unwrap();
+ assert_eq!(sha256_file(&f).unwrap(), "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
+ let p = crate::catalog::preset("16gb").unwrap();
+ let all = crate::catalog::downloads_for(p, false);
+ let (dl, disk) = space_needed(dir.path(), &all);
+ assert_eq!(dl, all.iter().map(|d| d.size).sum::<u64>());
+ assert!(disk > dl, "zips need room to extract");
+ // A partial download counts toward what is left.
+ let vae = crate::catalog::VAE;
+ std::fs::create_dir_all(vae.path(dir.path()).parent().unwrap()).unwrap();
+ std::fs::write(part_path(&vae.path(dir.path())), vec![0u8; (SEGMENT + 1000) as usize]).unwrap();
+ assert_eq!(space_needed(dir.path(), &all).0, dl - SEGMENT, "whole segments count");
+ assert!(free_space(dir.path()).unwrap_or(1) > 0);
+ assert!(preview(dir.path(), &all).iter().all(|i| i.state == ItemState::Pending));
+ }
+
+ #[test]
+ fn segment_bookkeeping() {
+ let dir = tempfile::tempdir().unwrap();
+ let target = dir.path().join("m.gguf");
+ let part = part_path(&target);
+ let size = 5 * SEGMENT + 123;
+ assert_eq!(part_progress(&target, size), 0);
+ // A prefix left by a single-connection download counts in whole segments.
+ std::fs::write(&part, vec![0u8; (2 * SEGMENT + 10) as usize]).unwrap();
+ assert_eq!(done_segments(&part, size), vec![true, true, false, false, false, false]);
+ // A segmented download records what is done, in any order (the file is preallocated).
+ std::fs::OpenOptions::new().write(true).open(&part).unwrap().set_len(size).unwrap();
+ write_segment_state(&part, size, &[true, false, false, false, false, true]);
+ assert_eq!(part_progress(&target, size), SEGMENT + 123);
+ assert_eq!(segment_len(5, size), 123);
+ // State from another file size is ignored.
+ write_segment_state(&part, size + 1, &[true; 6]);
+ assert_eq!(done_segments(&part, size).iter().filter(|d| **d).count(), 0, "full-size preallocation is not a finished prefix");
+ remove_part(&part);
+ assert!(!part.exists() && !segments_path(&part).exists());
+ let mut h = reqwest::header::HeaderMap::new();
+ h.insert(reqwest::header::CONTENT_RANGE, "bytes 0-99/337915440".parse().unwrap());
+ assert_eq!(content_range_total(&h), Some(337_915_440));
+ }
+
+ /// Real download of the smallest catalog file (QLS_TEST_DOWNLOAD=1; ~67 MB).
+ #[tokio::test]
+ async fn real_download_with_resume() {
+ if std::env::var("QLS_TEST_DOWNLOAD").is_err() {
+ return;
+ }
+ let dir = tempfile::tempdir().unwrap();
+ let d = crate::catalog::UPSCALER;
+ let target = d.path(dir.path());
+ std::fs::create_dir_all(target.parent().unwrap()).unwrap();
+ // Start from a fake partial file holding the first bytes, as after an interruption.
+ let inst = Installer::new();
+ let client = reqwest::Client::new();
+ {
+ let resp = client.get(d.url).header(reqwest::header::RANGE, "bytes=0-1048575").send().await.unwrap();
+ assert_eq!(resp.status().as_u16(), 206, "Hugging Face supports ranges");
+ std::fs::write(part_path(&target), resp.bytes().await.unwrap()).unwrap();
+ }
+ let (tx, rx) = std::sync::mpsc::channel();
+ inst.start(dir.path().to_path_buf(), "test", vec![d], Box::new(move |ok| tx.send(ok).unwrap())).unwrap();
+ let ok = tokio::task::spawn_blocking(move || rx.recv_timeout(Duration::from_secs(600)).unwrap()).await.unwrap();
+ assert!(ok, "{:?}", inst.status());
+ assert!(d.is_present(dir.path()));
+ assert_eq!(sha256_file(&target).unwrap(), d.sha256);
+ }
+}
diff --git a/crates/qls-core/src/lib.rs b/crates/qls-core/src/lib.rs
index 7ada249..98bdaf4 100644
--- a/crates/qls-core/src/lib.rs
+++ b/crates/qls-core/src/lib.rs
@@ -1,3 +1,4 @@
+pub mod catalog;
pub mod config;
pub mod diagnostics;
pub mod engine;
@@ -6,6 +7,7 @@ pub mod geometry;
pub mod hdr;
pub mod heif;
pub mod imaging;
+pub mod installer;
pub mod paths;
pub mod pipeline;
pub mod planner;
diff --git a/crates/qls-core/src/pipeline.rs b/crates/qls-core/src/pipeline.rs
index 3987f6d..e7a995e 100644
--- a/crates/qls-core/src/pipeline.rs
+++ b/crates/qls-core/src/pipeline.rs
@@ -9,7 +9,7 @@ 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::planner::{InpaintAction, Plan, ResolvedMode};
use crate::sdcpp::{Guidance, ImgGenRequest, SampleParams, VaeTilingParams, b64};
/// Server-side facts that shape the request but are not part of the plan.
@@ -109,6 +109,32 @@ pub fn wants_transparency(prompt: &str) -> bool {
.any(|k| p.contains(k))
}
+/// Inpaint instruction: `<image1>` is the region (blurred out where content is removed),
+/// `<image2>` the same region with the area marked in `color`. The wording follows the
+/// official Qwen-Image 2.1 edit prompt guide (refer to images as `<imageN>`; for removals,
+/// describe what fills the exposed area).
+pub fn inpaint_prompt(action: InpaintAction, prompt: &str, color: &str) -> String {
+ let area = format!("the area marked in {color} in <image2>");
+ let keep = "Keep everything outside the marked area exactly as it is.";
+ let what = action.subject(prompt);
+ match action {
+ InpaintAction::Edit => format!("In <image1>, change only {area}: {what}. Blend the change seamlessly into the surrounding scene. {keep}"),
+ InpaintAction::Remove => {
+ let (target, it) = if what.is_empty() { ("everything that was there".to_string(), "it") } else { (what.clone(), "the removed content") };
+ format!(
+ "In <image1>, {area} has been blurred out to remove {target}. Replace the blurred area with the background that would naturally be behind it, \
+ continuing the surrounding scene, textures, lighting and perspective, so that no trace, outline or shadow of {it} remains. {keep}"
+ )
+ }
+ InpaintAction::Replace => format!(
+ "In <image1>, replace what is inside {area} with {what}. Match the scene's lighting, perspective, scale and style so it looks naturally part of the image. {keep}"
+ ),
+ InpaintAction::Add => format!(
+ "In <image1>, add {what} inside {area}, fitting it naturally into the scene with matching lighting, perspective, scale and shadows. {keep}"
+ ),
+ }
+}
+
/// 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.
@@ -185,27 +211,46 @@ pub fn prepare(plan: &Plan, prompt: &str, seed: i64, images: &[LoadedImage], mas
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 action = plan.inpaint_action.unwrap_or_default();
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);
+ let content = imaging::resize(&crop, wc.content.width, wc.content.height);
+ drop(crop);
// Blend mask (source resolution): soft edges so the patch merges invisibly.
let mut blend = imaging::crop_mask(&user_mask, region);
+ if action == InpaintAction::Remove {
+ // Removals also take the halo and contact shadow just outside the stroke.
+ blend = imaging::dilate(&blend, ((region.width.max(region.height) as f64) * 0.01).round().max(4.0) as u32);
+ }
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 m_content = 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 m_work = imaging::backend_mask(&m_content, 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);
+ // Image 1: the region; for a removal with the content already blurred away, so
+ // the model rebuilds background instead of copying the object back.
+ let pad = |img: &RgbaImage| imaging::pad_edge(img, wc.canvas, wc.content_offset);
+ let image1 = if action == InpaintAction::Remove { imaging::fill_masked(&content, &m_work) } else { content.clone() };
+ // Image 2 (guide): the area marked in a color named in the prompt. The model gets
+ // no mask otherwise; the latent mask only discards changes outside it.
+ let gc = plan.references.get(1).map(|r| r.canvas).ok_or_else(|| AppError::internal("missing inpaint guide plan"))?;
+ let (color_name, color) = imaging::pick_highlight(&content, &m_content);
+ let guide_mask = imaging::resize_mask(&m_work, gc.content.width, gc.content.height);
+ let guide = imaging::highlight(&imaging::resize(&image1, gc.content.width, gc.content.height), &guide_mask, color);
+ drop(content);
+
+ let image1_b64 = png_b64(&pad(&image1))?;
+ req.init_image = Some(image1_b64.clone());
+ req.ref_images.push(image1_b64);
+ req.ref_images.push(png_b64(&imaging::pad_edge(&guide, gc.canvas, gc.content_offset))?);
+ req.prompt = inpaint_prompt(action, prompt, color_name);
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()];
@@ -708,6 +753,80 @@ mod tests {
assert!(changed_inside);
}
+ fn inpaint_job(prompt: &str, action: InpaintAction) -> (LoadedImage, GrayImage, PreparedJob) {
+ // A white box, painted over.
+ let mut 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]));
+ img.pixels.put_pixel(x, y, Rgba([255, 255, 255, 255]));
+ }
+ }
+ let mut r = req(prompt);
+ r.mask = Some("input:m".into());
+ r.inpaint_action = action;
+ 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();
+ (img, m, j)
+ }
+
+ #[test]
+ fn inpaint_sends_region_and_marked_guide() {
+ let (_, _, j) = inpaint_job("a red hat", InpaintAction::Add);
+ assert_eq!(j.request.ref_images.len(), 2, "region + guide");
+ let (r1, g) = (decode(&j.request.ref_images[0]), decode(&j.request.ref_images[1]));
+ assert_eq!(r1.dimensions(), (j.request.width, j.request.height));
+ assert_eq!(j.request.init_image.as_ref(), Some(&j.request.ref_images[0]));
+ assert!(g.width() % 32 == 0 && g.height() % 32 == 0);
+ assert!((g.width() as u64 * g.height() as u64) < (r1.width() as u64 * r1.height() as u64) / 2, "guide is small");
+ // The guide carries the highlight color (named in the prompt) where the mask is.
+ let marked = g.pixels().filter(|p| p[0] == 255 && p[1] == 0 && p[2] == 0).count();
+ assert!(marked > 0);
+ assert!(j.request.prompt.contains("<image1>") && j.request.prompt.contains("marked in red in <image2>"));
+ assert!(j.request.prompt.contains("add a red hat inside"), "{}", j.request.prompt);
+ }
+
+ #[test]
+ fn remove_blurs_content_out_of_image_1() {
+ let center = |j: &PreparedJob| {
+ let r1 = decode(&j.request.ref_images[0]);
+ let PostKind::Inpaint { region, .. } = &j.post.kind else { panic!() };
+ let s = r1.width() as f64 / region.width as f64;
+ *r1.get_pixel(((440 - region.x) as f64 * s) as u32, ((330 - region.y) as f64 * s) as u32)
+ };
+ let (_, _, edit) = inpaint_job("make it shiny", InpaintAction::Edit);
+ assert_eq!(center(&edit), Rgba([255, 255, 255, 255]), "edits show the content");
+ // The "remove ..." prompt turns a plain edit into a removal.
+ let (_, _, rm) = inpaint_job("Remove the box.", InpaintAction::Edit);
+ assert!(rm.request.prompt.contains("blurred out to remove the box"), "{}", rm.request.prompt);
+ assert!(center(&rm).0[..3].iter().any(|&c| c < 230), "box erased: {:?}", center(&rm));
+ assert_eq!(rm.request.init_image.as_ref(), Some(&rm.request.ref_images[0]));
+ }
+
+ #[test]
+ fn remove_needs_no_prompt() {
+ let (_, _, j) = inpaint_job("", InpaintAction::Remove);
+ assert!(j.request.prompt.contains("to remove everything that was there"));
+ }
+
+ #[test]
+ fn inpaint_action_subjects() {
+ assert_eq!(InpaintAction::Edit.resolve("please remove the girl"), InpaintAction::Remove);
+ assert_eq!(InpaintAction::Edit.resolve("make it red"), InpaintAction::Edit);
+ assert_eq!(InpaintAction::Add.resolve("remove it"), InpaintAction::Add);
+ assert_eq!(InpaintAction::Remove.subject("Remove the girl."), "the girl");
+ assert_eq!(InpaintAction::Replace.subject("replace it with a dog"), "a dog");
+ assert_eq!(InpaintAction::Add.subject("Add a cat"), "a cat");
+ assert_eq!(InpaintAction::Edit.subject("make it blue"), "make it blue");
+ }
+
#[test]
fn outpaint_preserves_original_region() {
let img = photo(800, 600);
diff --git a/crates/qls-core/src/planner.rs b/crates/qls-core/src/planner.rs
index de0d2cd..57ac25e 100644
--- a/crates/qls-core/src/planner.rs
+++ b/crates/qls-core/src/planner.rs
@@ -55,6 +55,47 @@ impl ResolvedMode {
}
}
+/// What an inpaint does in the painted area. Each action wraps the prompt in an instruction
+/// that points the model at the area (marked on a second reference image, see pipeline).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
+#[serde(rename_all = "snake_case")]
+pub enum InpaintAction {
+ /// The prompt describes the change.
+ #[default]
+ Edit,
+ /// Erase the painted content and fill with background; the prompt (what to remove) is optional.
+ Remove,
+ /// Put what the prompt describes in place of the painted content.
+ Replace,
+ /// Add what the prompt describes inside the painted area.
+ Add,
+}
+
+static REMOVE_RE: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"(?i)^\s*(?:please\s+)?(?:remove|erase|delete|get rid of|take out|clear away|clean up)\b\s*").unwrap());
+
+impl InpaintAction {
+ /// The action actually run: an Edit whose prompt asks to remove something is a Remove.
+ pub fn resolve(self, prompt: &str) -> Self {
+ if self == Self::Edit && REMOVE_RE.is_match(prompt) { Self::Remove } else { self }
+ }
+
+ /// The prompt without the action's own verb ("Remove the girl" → "the girl").
+ pub fn subject(self, prompt: &str) -> String {
+ static ADD_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)^\s*(?:please\s+)?(?:add|put|place|insert)\b\s*").unwrap());
+ static REPLACE_RE: LazyLock<Regex> =
+ LazyLock::new(|| Regex::new(r"(?i)^\s*(?:please\s+)?(?:replace(?:\s+(?:it|this|that|them))?\s+with|change(?:\s+(?:it|this|that))?\s+(?:in)?to|with)\b\s*").unwrap());
+ let p = prompt.trim();
+ let s = match self {
+ Self::Edit => p.into(),
+ Self::Remove => REMOVE_RE.replace(p, "").into_owned(),
+ Self::Add => ADD_RE.replace(p, "").into_owned(),
+ Self::Replace => REPLACE_RE.replace(p, "").into_owned(),
+ };
+ s.trim().trim_end_matches(['.', '!']).trim().to_string()
+ }
+}
+
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum UpscaleMethod {
@@ -182,6 +223,9 @@ pub struct GenerationRequest {
pub images: Vec<String>,
#[serde(default)]
pub mask: Option<String>,
+ /// What to do in the masked area (inpaint only).
+ #[serde(default)]
+ pub inpaint_action: InpaintAction,
#[serde(default)]
pub outpaint: Option<OutpaintSpec>,
#[serde(default)]
@@ -210,6 +254,10 @@ pub struct GenerationRequest {
/// Target for `mode: upscale`.
#[serde(default)]
pub upscale: Option<UpscaleSpec>,
+ /// Private mode: inputs and results go to a temporary store (not the gallery or the
+ /// output folder) that is deleted when private mode ends or the service exits.
+ #[serde(default)]
+ pub private: bool,
}
// ---------------------------------------------------------------------------------------
@@ -254,6 +302,9 @@ pub struct Plan {
pub outpaint: Option<OutpaintPlan>,
/// Region of the source sent to the model for inpainting.
pub inpaint_region: Option<Rect>,
+ /// Resolved inpaint action (see [`InpaintAction::resolve`]).
+ #[serde(default)]
+ pub inpaint_action: Option<InpaintAction>,
pub quality: Quality,
pub resolution: ResolutionMode,
pub aspect_label: String,
@@ -464,6 +515,10 @@ pub fn token_budget(vram_total_mib: Option<u64>) -> u64 {
pub const PIXELS_PER_TOKEN: u64 = 256; // 8x VAE downscale, 2x2 patches
+/// Area of the inpaint guide reference (the region with the painted area marked), as a
+/// share of the working canvas: enough to locate the area, cheap in tokens.
+pub const INPAINT_GUIDE_AREA: f64 = 0.25;
+
/// 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).
@@ -603,9 +658,6 @@ fn ref_canvas(src: Size, max_canvas_area: u64, rec: &RecommendedSettings) -> Wor
/// 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)."));
}
@@ -613,6 +665,12 @@ pub fn plan(req: &GenerationRequest, inputs: &PlanInputs, rec: &RecommendedSetti
return Err(AppError::invalid(format!("Use at most {} reference images.", rec.max_references)));
}
let (mode, auto_mode, mode_reason) = detect_mode(req, inputs)?;
+ let inpaint_action = (mode == ResolvedMode::Inpaint).then(|| req.inpaint_action.resolve(&req.prompt));
+ // Upscales and removals need no description.
+ let prompt_optional = mode == ResolvedMode::Upscale || inpaint_action == Some(InpaintAction::Remove);
+ if req.prompt.trim().is_empty() && !prompt_optional {
+ return Err(AppError::invalid("Describe what to generate or change."));
+ }
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();
@@ -629,9 +687,9 @@ pub fn plan(req: &GenerationRequest, inputs: &PlanInputs, rec: &RecommendedSetti
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);
+ // Shared: cap an area by the VRAM budget given references totalling `n_refs` times it.
+ let mut cap_for_refs = |wanted: u64, n_refs: f64, notes: &mut Vec<String>| -> u64 {
+ let allowed = (budget_area as f64 / (1.0 + n_refs)) as u64;
if wanted > allowed {
optimized = true;
notes.push("Resolution reduced to fit available VRAM.".into());
@@ -682,7 +740,7 @@ pub fn plan(req: &GenerationRequest, inputs: &PlanInputs, rec: &RecommendedSetti
}
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);
+ let area = cap_for_refs(src.area(), 0.0, &mut notes);
working = plan_working_canvas(src, &CanvasLimits { min_side: 64, ..limits(area, rec) });
output = src;
} else {
@@ -696,7 +754,7 @@ pub fn plan(req: &GenerationRequest, inputs: &PlanInputs, rec: &RecommendedSetti
})
.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 area = cap_for_refs(wanted, 0.0, &mut notes);
let size = size_for_aspect(aspect, area, rec);
working = plan_working_canvas(size, &limits(size.area(), rec));
output = size;
@@ -779,8 +837,10 @@ pub fn plan(req: &GenerationRequest, inputs: &PlanInputs, rec: &RecommendedSetti
((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;
+ // References: the region itself, plus a smaller copy with the area marked.
+ let area = cap_for_refs(tier_area.unwrap_or(src.area()), 1.0 + INPAINT_GUIDE_AREA, &mut notes);
+ // At least the working size of context around the mask, so the model sees the scene.
+ let min_ctx = (area as f64).sqrt() 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);
@@ -790,6 +850,8 @@ pub fn plan(req: &GenerationRequest, inputs: &PlanInputs, rec: &RecommendedSetti
inpaint_region = Some(region);
output = src;
references.push(RefPlan { index: 0, source: region.size(), canvas: working });
+ let guide_area = (working.canvas.area() as f64 * INPAINT_GUIDE_AREA) as u64;
+ references.push(RefPlan { index: 0, source: region.size(), canvas: ref_canvas(region.size(), guide_area, rec) });
strength = Some(adv.strength.unwrap_or(1.0).clamp(0.05, 1.0));
}
ResolvedMode::Outpaint => {
@@ -805,7 +867,7 @@ pub fn plan(req: &GenerationRequest, inputs: &PlanInputs, rec: &RecommendedSetti
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 area = cap_for_refs(wanted, 1.0, &mut notes);
let p = plan_outpaint(src, exp, &limits(area, rec), 32).map_err(AppError::invalid)?;
working = p.working;
output = p.final_size;
@@ -884,6 +946,7 @@ pub fn plan(req: &GenerationRequest, inputs: &PlanInputs, rec: &RecommendedSetti
references,
outpaint,
inpaint_region,
+ inpaint_action,
quality: req.quality,
resolution: req.resolution,
notes,
diff --git a/crates/qls-core/src/process.rs b/crates/qls-core/src/process.rs
index 98bdf38..aafabbd 100644
--- a/crates/qls-core/src/process.rs
+++ b/crates/qls-core/src/process.rs
@@ -706,11 +706,13 @@ mod tests {
#[test]
fn default_launch_args() {
let mut cfg = AppConfig::default();
+ cfg.sdcpp_dir = std::path::PathBuf::from(r"C:\AI\sdcpp");
+ cfg.apply_preset(crate::catalog::preset("16gb").unwrap());
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"--diffusion-model C:\AI\sdcpp\models\qwen21\qwen-image-2.1-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"));
diff --git a/crates/qls-core/src/store.rs b/crates/qls-core/src/store.rs
index 3fb122f..6fd6447 100644
--- a/crates/qls-core/src/store.rs
+++ b/crates/qls-core/src/store.rs
@@ -116,7 +116,7 @@ impl GenerationRecord {
s.push_str(&format!(", Hires denoising strength: {d}"));
}
}
- s.push_str(&format!(", Mode: {}, Version: Qwen Local Studio {}", self.mode, self.app_version));
+ s.push_str(&format!(", Mode: {}, Version: Kokon {}", self.mode, self.app_version));
s
}
@@ -126,7 +126,7 @@ impl GenerationRecord {
vec![
("parameters", self.parameters_text()),
("qls:generation", serde_json::to_string(&slim).unwrap_or_default()),
- ("Software", format!("Qwen Local Studio {}", self.app_version)),
+ ("Software", format!("Kokon {}", self.app_version)),
]
}
@@ -221,6 +221,11 @@ impl Store {
Ok(Self { conn: Mutex::new(conn), data_dir: data_dir.to_path_buf() })
}
+ /// Forgets every record (used for the temporary private-mode store).
+ pub fn clear(&self) -> AppResult<()> {
+ self.conn.lock().unwrap().execute_batch("DELETE FROM generations; DELETE FROM inputs;").map_err(db_err)
+ }
+
pub fn thumb_path(&self, id: &str) -> PathBuf {
self.data_dir.join("thumbs").join(format!("{id}.jpg"))
}
@@ -374,7 +379,18 @@ impl Store {
.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)
+ let mut rec: InputRecord = serde_json::from_str(&json).map_err(AppError::internal)?;
+ // Records keep absolute paths; after the data folder moved (app renamed, user moved
+ // it) the file is found by name in this store's inputs folder.
+ if !Path::new(&rec.path).is_file()
+ && let Some(name) = Path::new(&rec.path).file_name()
+ {
+ let here = self.data_dir.join("inputs").join(name);
+ if here.is_file() {
+ rec.path = here.to_string_lossy().into_owned();
+ }
+ }
+ Ok(rec)
}
pub fn input_thumb_path(&self, id: &str) -> PathBuf {
diff --git a/crates/qls-service/Cargo.toml b/crates/qls-service/Cargo.toml
index 30837d1..d313dea 100644
--- a/crates/qls-service/Cargo.toml
+++ b/crates/qls-service/Cargo.toml
@@ -3,12 +3,18 @@ name = "qls-service"
version.workspace = true
edition.workspace = true
+# The executable users see (Task Manager, the install folder) carries the product name.
+[[bin]]
+name = "kokon-service"
+path = "src/main.rs"
+
[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"
+sysinfo = "0.39.6"
tokio = { version = "1.53.2", features = ["full"] }
tokio-stream = { version = "0.1.19", features = ["sync"] }
tower-http = { version = "0.7.1", features = ["cors", "limit"] }
diff --git a/crates/qls-service/src/api.rs b/crates/qls-service/src/api.rs
index ac2a364..0c428b3 100644
--- a/crates/qls-service/src/api.rs
+++ b/crates/qls-service/src/api.rs
@@ -17,13 +17,14 @@ use axum::{
};
use futures_util::stream::Stream;
use qls_core::{
+ catalog,
config::AppConfig,
diagnostics,
engine::{APP_VERSION, JobView},
error::{AppError, ErrorCode},
geometry::{ExpansionUnits, Size, aspect_label},
- imaging, paths,
- planner::{GenerationRequest, Mode, OutpaintSpec, Quality, UpscaleMethod, UpscaleSpec},
+ imaging, installer, paths,
+ planner::{GenerationRequest, InpaintAction, Mode, OutpaintSpec, Quality, UpscaleMethod, UpscaleSpec},
store::{GenerationRecord, ListQuery},
};
use serde::Deserialize;
@@ -57,6 +58,9 @@ pub fn router(state: Arc<AppState>) -> Router {
let api = Router::new()
.route("/status", get(status))
.route("/setup", get(setup))
+ .route("/setup/hardware", get(setup_hardware))
+ .route("/setup/install", get(install_status).post(install_start))
+ .route("/setup/install/cancel", post(install_cancel))
.route("/config", get(get_config).put(put_config))
.route("/backend/start", post(backend_start))
.route("/backend/stop", post(backend_stop))
@@ -75,6 +79,7 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/upscale", post(op_upscale))
.route("/events", get(events))
.route("/inputs/import", post(import_input))
+ .route("/private/clear", post(private_clear))
.route("/inputs/{id}", get(get_input))
.route("/inputs/{id}/image", get(input_image))
.route("/inputs/{id}/thumb", get(input_thumb))
@@ -158,7 +163,7 @@ fn constant_eq(a: &[u8], b: &[u8]) -> bool {
}
async fn ping() -> Json<Value> {
- Json(json!({ "service": "qwen-local-studio", "version": APP_VERSION }))
+ Json(json!({ "service": "kokon", "version": APP_VERSION }))
}
// ---------------------------------------------------------------------------------------
@@ -199,6 +204,98 @@ async fn setup(State(s): St) -> ApiResult<Json<Value>> {
Ok(Json(serde_json::to_value(report).unwrap()))
}
+/// What the setup wizard shows: the GPU, the recommended preset and, per preset, which files
+/// are installed in the configured folder and how much is left to download.
+async fn setup_hardware(State(s): St) -> ApiResult<Json<Value>> {
+ let engine = s.engine.clone();
+ let v = tokio::task::spawn_blocking(move || {
+ let cfg = engine.config();
+ let gpu = engine.gpu();
+ let detected = gpu.as_ref().map(|g| g.memory_total_mib);
+ let vram = cfg.planning_vram_mib(detected);
+ let mut sys = sysinfo::System::new();
+ sys.refresh_memory();
+ let dir = cfg.sdcpp_dir.clone();
+ let presets: Vec<Value> = catalog::PRESETS
+ .iter()
+ .map(|p| {
+ let files = catalog::downloads_for(p, true);
+ let (download, disk) = installer::space_needed(&dir, &files);
+ json!({
+ "id": p.id, "label": p.label, "summary": p.summary, "verified": p.verified, "min_vram_mib": p.min_vram_mib,
+ "files": installer::preview(&dir, &files), "download_bytes": download, "disk_bytes": disk,
+ })
+ })
+ .collect();
+ json!({
+ "gpu": gpu,
+ "nvidia": gpu.is_some(),
+ "vram_mib": vram,
+ "vram_simulated": cfg.vram_override_mib > 0,
+ "ram_total_mib": sys.total_memory() / (1024 * 1024),
+ "recommended": catalog::recommended_preset(vram).id,
+ "current": cfg.hardware_preset,
+ "presets": presets,
+ "sdcpp_dir": dir,
+ "default_sdcpp_dir": qls_core::config::default_sdcpp_dir(),
+ "free_bytes": installer::free_space(&dir),
+ "issues_url": catalog::ISSUES_URL,
+ })
+ })
+ .await
+ .map_err(AppError::internal)?;
+ Ok(Json(v))
+}
+
+#[derive(Deserialize)]
+struct InstallBody {
+ preset: String,
+ #[serde(default = "yes")]
+ upscaler: bool,
+}
+
+fn yes() -> bool {
+ true
+}
+
+/// Starts downloading a preset into the configured folder. When every file is installed the
+/// official profile of that preset becomes active.
+async fn install_start(State(s): St, Json(b): Json<InstallBody>) -> ApiResult<Json<Value>> {
+ let preset = catalog::preset(&b.preset).ok_or_else(|| AppError::invalid(format!("Unknown preset {}.", b.preset)))?;
+ let cfg = s.engine.config();
+ // A running server keeps its DLLs open; the engine zip may need to replace them.
+ let st = s.engine.server.status();
+ if st.owned && st.state != qls_core::process::ServerState::Stopped {
+ if s.engine.has_pending_work() {
+ return Err(AppError::new(ErrorCode::QueueFull, "Wait for the current images to finish, then install.").into());
+ }
+ s.engine.server.stop().await;
+ s.engine.emit_server();
+ }
+ let engine = s.engine.clone();
+ let on_finish = Box::new(move |complete: bool| {
+ if !complete {
+ return;
+ }
+ let mut c = engine.config();
+ c.apply_preset(preset);
+ if let Err(e) = engine.set_config(c) {
+ tracing::error!("could not save the installed preset: {}", e.message);
+ }
+ });
+ s.engine.installer.start(cfg.sdcpp_dir.clone(), preset.id, catalog::downloads_for(preset, b.upscaler), on_finish)?;
+ Ok(Json(serde_json::to_value(s.engine.installer.status()).unwrap()))
+}
+
+async fn install_status(State(s): St) -> Json<Value> {
+ Json(serde_json::to_value(s.engine.installer.status()).unwrap())
+}
+
+async fn install_cancel(State(s): St) -> Json<Value> {
+ s.engine.installer.cancel();
+ Json(serde_json::to_value(s.engine.installer.status()).unwrap())
+}
+
async fn get_config(State(s): St) -> Json<AppConfig> {
Json(s.engine.config())
}
@@ -246,7 +343,7 @@ async fn diagnostics_json(State(s): St) -> ApiResult<Json<Value>> {
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, "Kokon {APP_VERSION} — diagnostics ({})", qls_core::store::now_rfc3339());
let _ = writeln!(text, "\n[GPU]");
match &gpus {
Some(g) => {
@@ -276,6 +373,10 @@ async fn diagnostics_json(State(s): St) -> ApiResult<Json<Value>> {
}
let _ = writeln!(text, "\n[Configuration]");
let _ = writeln!(text, "sdcpp dir: {}", cfg.sdcpp_dir.display());
+ let _ = writeln!(text, "Preset: {}, profile: {}", cfg.hardware_preset, cfg.profile().display_name);
+ if cfg.vram_override_mib > 0 {
+ let _ = writeln!(text, "Simulated VRAM for planning: {} MiB", cfg.vram_override_mib);
+ }
for (label, p, _) in cfg.profile().files() {
let _ = writeln!(text, "{label}: {} ({})", p.display(), if p.is_file() { "ok" } else { "MISSING" });
}
@@ -385,6 +486,8 @@ struct SimpleOp {
image: Option<String>,
images: Vec<String>,
mask: Option<String>,
+ /// Inpaint: `edit` (default), `remove`, `replace` or `add`.
+ action: Option<InpaintAction>,
width: Option<u32>,
height: Option<u32>,
aspect_ratio: Option<String>,
@@ -420,6 +523,7 @@ async fn run_simple(s: Arc<AppState>, mode: Mode, op: SimpleOp, wait: bool) -> A
mode,
images,
mask: op.mask,
+ inpaint_action: op.action.unwrap_or_default(),
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,
@@ -477,7 +581,7 @@ async fn plan(State(s): St, Json(b): Json<PlanBody>) -> ApiResult<Json<Value>> {
}
let mask = match &b.request.mask {
Some(m) => {
- let (img, _) = engine.resolve_source(m, ws.as_deref())?;
+ let (img, _) = engine.resolve_source(m, ws.as_deref(), b.request.private)?;
let mm = imaging::mask_from_image(&img);
Some((Size::new(mm.width(), mm.height()), imaging::mask_bbox(&mm, 16), imaging::mask_coverage(&mm, 16)))
}
@@ -493,14 +597,15 @@ async fn plan(State(s): St, Json(b): Json<PlanBody>) -> ApiResult<Json<Value>> {
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)?;
+ let r = engine.input_store(id).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)?;
+ let r = engine.gen_store(id).get_generation(id)?;
return Ok(Size::new(r.width, r.height));
}
- let (img, _) = engine.resolve_source(src, ws)?;
+ // Only sizes are needed: a file path is read into the private store, which is temporary.
+ let (img, _) = engine.resolve_source(src, ws, true)?;
Ok(img.size())
}
@@ -518,12 +623,18 @@ async fn events(State(s): St) -> Sse<impl Stream<Item = Result<SseEvent, Infalli
// Inputs
// ---------------------------------------------------------------------------------------
-async fn upload_input(State(s): St, headers: HeaderMap, body: Bytes) -> ApiResult<Json<Value>> {
+#[derive(Deserialize, Default)]
+struct PrivateQ {
+ #[serde(default)]
+ private: bool,
+}
+
+async fn upload_input(State(s): St, Query(q): Query<PrivateQ>, 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 store = if q.private { s.engine.private_store.clone() } else { 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()))
}
@@ -533,8 +644,8 @@ struct PathBody {
path: String,
}
-async fn import_input(State(s): St, Json(b): Json<PathBody>) -> ApiResult<Json<Value>> {
- let store = s.engine.store.clone();
+async fn import_input(State(s): St, Query(q): Query<PrivateQ>, Json(b): Json<PathBody>) -> ApiResult<Json<Value>> {
+ let store = if q.private { s.engine.private_store.clone() } else { 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))?;
@@ -547,7 +658,13 @@ async fn import_input(State(s): St, Json(b): Json<PathBody>) -> ApiResult<Json<V
}
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()))
+ Ok(Json(serde_json::to_value(s.engine.input_store(&id).get_input(&id)?).unwrap()))
+}
+
+/// Ends private mode: deletes every private input and result.
+async fn private_clear(State(s): St) -> ApiResult<Json<Value>> {
+ let n = s.engine.clear_private()?;
+ Ok(Json(json!({ "cleared": n })))
}
async fn serve_file(path: &Path, content_type: Option<&str>) -> ApiResult<Response> {
@@ -572,16 +689,18 @@ async fn serve_file(path: &Path, content_type: Option<&str>) -> ApiResult<Respon
}
async fn input_image(State(s): St, AxPath(id): AxPath<String>) -> ApiResult<Response> {
- let r = s.engine.store.get_input(&id)?;
+ let store = s.engine.input_store(&id);
+ let r = store.get_input(&id)?;
if r.format == "heic" {
- return serve_file(&s.engine.store.input_display_path(&id), Some("image/jpeg")).await;
+ return serve_file(&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
+ let store = s.engine.input_store(&id);
+ store.get_input(&id)?;
+ serve_file(&store.input_thumb_path(&id), Some("image/jpeg")).await
}
// ---------------------------------------------------------------------------------------
@@ -594,7 +713,7 @@ async fn gallery_list(State(s): St, Query(q): Query<ListQuery>) -> ApiResult<Jso
}
async fn gallery_get(State(s): St, AxPath(id): AxPath<String>) -> ApiResult<Json<GenerationRecord>> {
- Ok(Json(s.engine.store.get_generation(&id)?))
+ Ok(Json(s.engine.gen_store(&id).get_generation(&id)?))
}
#[derive(Deserialize)]
@@ -603,29 +722,31 @@ struct PatchBody {
}
async fn gallery_patch(State(s): St, AxPath(id): AxPath<String>, Json(b): Json<PatchBody>) -> ApiResult<Json<GenerationRecord>> {
+ let store = s.engine.gen_store(&id);
if let Some(f) = b.favorite {
- s.engine.store.set_favorite(&id, f)?;
+ 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)?))
+ Ok(Json(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 out = s.engine.output_root(&id);
+ s.engine.gen_store(&id).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)?;
+ let r = s.engine.gen_store(&id).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);
+ let store = s.engine.gen_store(&id);
+ let p = store.thumb_path(&id);
if !p.is_file() {
- let r = s.engine.store.get_generation(&id)?;
+ let r = store.get_generation(&id)?;
return serve_file(Path::new(&r.file_path), None).await;
}
serve_file(&p, Some("image/jpeg")).await
@@ -641,7 +762,7 @@ struct ExportBody {
/// "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 rec = s.engine.gen_store(&id).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());
diff --git a/crates/qls-service/src/main.rs b/crates/qls-service/src/main.rs
index 3ed8c48..e12ac86 100644
--- a/crates/qls-service/src/main.rs
+++ b/crates/qls-service/src/main.rs
@@ -1,4 +1,4 @@
-//! qls-service — the headless Qwen Local Studio service.
+//! kokon-service (crate qls-service) — the headless Kokon 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
@@ -108,7 +108,7 @@ async fn main() {
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");
+ tracing::info!("port {port} busy ({e}); another kokon-service is probably running — exiting");
return;
}
};
@@ -123,7 +123,7 @@ async fn main() {
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);
+ tracing::info!("kokon-service {APP_VERSION} listening on http://{addr} (pid {})", info.pid);
let state = Arc::new(AppState {
engine: engine.clone(),
@@ -147,6 +147,7 @@ async fn main() {
tracing::error!("http server error: {e}");
}
+ let _ = engine.clear_private();
// Shutdown: stop sd-server unless the user wants it kept loaded.
let cfg = engine.config();
if !cfg.keep_server_running {
@@ -162,7 +163,7 @@ async fn main() {
{
let _ = std::fs::remove_file(service_info_path());
}
- tracing::info!("qls-service exited");
+ tracing::info!("kokon-service exited");
}
/// Exits when no client holds a lease, no job is pending, and the grace period passed.
@@ -235,6 +236,8 @@ pub fn client_left(state: &AppState, kind: &str, ui_remaining: bool, remaining:
if n > 0 {
tracing::info!("desktop app closed — cancelled {n} job(s)");
}
+ // Private mode lasts as long as the window.
+ let _ = state.engine.clear_private();
}
if remaining == 0 {
state.quick_exit.store(true, std::sync::atomic::Ordering::Relaxed);
diff --git a/index.html b/index.html
index 1977a6b..9f50fdc 100644
--- a/index.html
+++ b/index.html
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>Qwen Local Studio</title>
+ <title>Kokon</title>
</head>
<body>
<div id="root"></div>
diff --git a/mcp/package.json b/mcp/package.json
index 07dc940..6aaee77 100644
--- a/mcp/package.json
+++ b/mcp/package.json
@@ -1,11 +1,11 @@
{
- "name": "qls-mcp",
+ "name": "kokon-mcp",
"version": "1.0.0",
"private": true,
- "description": "MCP server for Qwen Local Studio (local image generation)",
+ "description": "MCP server for Kokon (local image generation and editing)",
"type": "module",
"scripts": {
- "build": "esbuild src/index.ts --bundle --platform=node --target=node22 --format=cjs --outfile=build/qls-mcp.cjs",
+ "build": "esbuild src/index.ts --bundle --platform=node --target=node22 --format=cjs --outfile=build/kokon-mcp.cjs",
"test": "vitest run",
"typecheck": "tsc --noEmit",
"build:exe": "node scripts/build-exe.mjs"
diff --git a/mcp/scripts/build-exe.mjs b/mcp/scripts/build-exe.mjs
index b9c3da8..1bbc062 100644
--- a/mcp/scripts/build-exe.mjs
+++ b/mcp/scripts/build-exe.mjs
@@ -1,4 +1,4 @@
-// Builds build/qls-mcp.exe: the bundled server injected into a copy of node.exe
+// Builds build/kokon-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";
@@ -10,16 +10,16 @@ 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"]);
+run("npx", ["esbuild", "src/index.ts", "--bundle", "--platform=node", "--target=node22", "--format=cjs", "--outfile=build/kokon-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 }),
+ JSON.stringify({ main: "build/kokon-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");
+const exe = path.join(build, "kokon-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");
+const sidecar = path.resolve(root, "..", "src-tauri", "binaries", "kokon-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
index 43aa695..ff840a4 100644
--- a/mcp/src/index.ts
+++ b/mcp/src/index.ts
@@ -1,4 +1,4 @@
-// qls-mcp — MCP server (stdio) for Qwen Local Studio. Uses the same local service and
+// kokon-mcp — MCP server (stdio) for Kokon. 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.
@@ -32,7 +32,8 @@ const DESCRIPTIONS: Record<keyof typeof schemas, { title: string; description: s
},
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.",
+ description:
+ "Change only the masked area of an image (mask: white = change, black = keep): edit it, remove what is there, replace it, or add something inside it. The model is shown the area marked on a copy of the image; pixels outside the mask are preserved exactly.",
},
upscale_image: {
title: "Upscale image",
@@ -41,7 +42,7 @@ const DESCRIPTIONS: Record<keyof typeof schemas, { title: string; description: s
},
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...).",
+ description: "Width, height, aspect ratio, file type and, for images made by Kokon, the generation metadata (prompt, seed, model, steps...).",
},
get_generator_status: {
title: "Generator status",
@@ -50,7 +51,7 @@ const DESCRIPTIONS: Record<keyof typeof schemas, { title: string; description: s
};
const client = new ServiceClient();
-const server = new McpServer({ name: "qwen-local-studio", version: VERSION }, { capabilities: { tools: {} } });
+const server = new McpServer({ name: "kokon", 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 }];
@@ -95,7 +96,7 @@ for (const name of Object.keys(schemas) as (keyof typeof schemas)[]) {
async function main() {
if (process.argv.includes("--version")) {
- process.stdout.write(`qls-mcp ${VERSION}\n`);
+ process.stdout.write(`kokon-mcp ${VERSION}\n`);
return;
}
const transport = new StdioServerTransport();
@@ -110,6 +111,6 @@ async function main() {
}
main().catch((e) => {
- process.stderr.write(`qls-mcp failed: ${e instanceof Error ? e.stack : String(e)}\n`);
+ process.stderr.write(`kokon-mcp failed: ${e instanceof Error ? e.stack : String(e)}\n`);
process.exit(1);
});
diff --git a/mcp/src/service.ts b/mcp/src/service.ts
index 3ca7865..350bf4d 100644
--- a/mcp/src/service.ts
+++ b/mcp/src/service.ts
@@ -1,4 +1,4 @@
-// Client for the local qls-service. Finds it via service.json, starts it if needed
+// Client for the local kokon-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";
@@ -24,7 +24,12 @@ export class ServiceError extends Error {
}
export function dataDir(): string {
- return process.env.QLS_DATA_DIR ?? path.join(process.env.LOCALAPPDATA ?? path.join(process.env.USERPROFILE ?? "C:\\", "AppData", "Local"), "QwenLocalStudio");
+ if (process.env.QLS_DATA_DIR) return process.env.QLS_DATA_DIR;
+ const base = process.env.LOCALAPPDATA ?? path.join(process.env.USERPROFILE ?? "C:\\", "AppData", "Local");
+ // The service moves the folder of the app's old name (QwenLocalStudio) to KokonData on its
+ // first start; until then the old one is read.
+ const [next, old] = [path.join(base, "KokonData"), path.join(base, "QwenLocalStudio")];
+ return !fs.existsSync(next) && fs.existsSync(old) ? old : next;
}
function readInfo(): ServiceInfo | null {
@@ -48,12 +53,12 @@ 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"),
+ path.join(path.dirname(process.execPath), "kokon-service.exe"),
+ path.join(local, "Kokon", "kokon-service.exe"),
+ path.join(process.env.ProgramFiles ?? "C:\\Program Files", "Kokon", "kokon-service.exe"),
// Development checkout (mcp/build -> target/...)
- path.resolve(__dirname, "..", "..", "target", "release", "qls-service.exe"),
- path.resolve(__dirname, "..", "..", "target", "debug", "qls-service.exe"),
+ path.resolve(__dirname, "..", "..", "target", "release", "kokon-service.exe"),
+ path.resolve(__dirname, "..", "..", "target", "debug", "kokon-service.exe"),
];
for (const c of candidates) {
if (c && fs.existsSync(c)) return c;
@@ -83,9 +88,9 @@ export class ServiceClient {
const exe = findServiceExe();
if (!exe) {
throw new ServiceError(
- "Qwen Local Studio is not installed (qls-service.exe not found).",
+ "Kokon is not installed (kokon-service.exe not found).",
"not_installed",
- "Install Qwen Local Studio, or set QLS_SERVICE_EXE to the path of qls-service.exe.",
+ "Install Kokon, or set QLS_SERVICE_EXE to the path of kokon-service.exe.",
);
}
// Detached: the service outlives this MCP process and exits on its own when idle.
@@ -97,7 +102,7 @@ export class ServiceClient {
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")}`);
+ throw new ServiceError("The Kokon service did not start.", "service_unavailable", `See ${path.join(dataDir(), "logs", "service.log")}`);
}
private startHeartbeat() {
@@ -137,7 +142,7 @@ export class ServiceClient {
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));
+ throw new ServiceError("The Kokon service is not reachable.", "service_unavailable", undefined, String(e));
}
const text = await res.text();
const data = text ? JSON.parse(text) : null;
diff --git a/mcp/src/tools.ts b/mcp/src/tools.ts
index 73f9050..cf5933a 100644
--- a/mcp/src/tools.ts
+++ b/mcp/src/tools.ts
@@ -68,7 +68,11 @@ export const schemas = {
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"),
+ action: z
+ .enum(["edit", "remove", "replace", "add"])
+ .default("edit")
+ .describe("edit: change the area as the prompt says; remove: erase what is there and fill with background (prompt optional, e.g. 'the bin'); replace: put the prompt's subject in its place; add: add the prompt's subject inside the area"),
+ prompt: z.string().trim().max(8000).default("").describe("The change, or the subject to add/replace with; optional for remove"),
seed: seed.optional(),
quality: quality.optional(),
output_path: outputPath.optional(),
@@ -328,7 +332,12 @@ export const handlers = {
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);
+ if (!a.prompt && a.action !== "remove") throw new PathError("prompt must not be empty (only action 'remove' works without one).");
+ return runJob(
+ ctx,
+ { prompt: a.prompt, mode: "inpaint", inpaint_action: a.action, 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) {
diff --git a/mcp/test/protocol.test.ts b/mcp/test/protocol.test.ts
index 08d329c..f8f7948 100644
--- a/mcp/test/protocol.test.ts
+++ b/mcp/test/protocol.test.ts
@@ -1,4 +1,4 @@
-// End-to-end over stdio with the official MCP client. Starts qls-service on demand
+// End-to-end over stdio with the official MCP client. Starts kokon-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";
@@ -13,7 +13,7 @@ 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"),
+ QLS_SERVICE_EXE: path.join(root, "target", "debug", "kokon-service.exe"),
} as Record<string, string>;
delete env.CLAUDE_PROJECT_DIR;
fs.mkdirSync(env.QLS_CONFIG_DIR, { recursive: true });
@@ -28,7 +28,7 @@ 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" }));
+ await client.connect(new StdioClientTransport({ command: exe ?? process.execPath, args: exe ? [] : [path.join(root, "mcp", "build", "kokon-mcp.cjs")], env, cwd: proj, stderr: "pipe" }));
}, 30_000);
afterAll(async () => {
@@ -42,9 +42,9 @@ afterAll(async () => {
});
describe("MCP protocol", () => {
- it("lists the seven tools with schemas", async () => {
+ it("lists the eight 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"]);
+ expect(tools.map((t) => t.name).sort()).toEqual(["edit_image", "edit_images", "generate_image", "get_generator_status", "get_image_info", "inpaint_image", "outpaint_image", "upscale_image"]);
const gen = tools.find((t) => t.name === "generate_image")!;
expect(gen.inputSchema.required).toEqual(["prompt"]);
});
diff --git a/package.json b/package.json
index 47e77b6..3e4db34 100644
--- a/package.json
+++ b/package.json
@@ -1,5 +1,5 @@
{
- "name": "qwen-local-studio",
+ "name": "kokon",
"private": true,
"version": "1.0.0",
"type": "module",
diff --git a/scripts/brand/.inter-500-merged.ttf b/scripts/brand/.inter-500-merged.ttf
new file mode 100644
index 0000000..9917578
Binary files /dev/null and b/scripts/brand/.inter-500-merged.ttf differ
diff --git a/scripts/brand/.inter-600-merged.ttf b/scripts/brand/.inter-600-merged.ttf
new file mode 100644
index 0000000..fb9e826
Binary files /dev/null and b/scripts/brand/.inter-600-merged.ttf differ
diff --git a/scripts/brand/kokon_brand.py b/scripts/brand/kokon_brand.py
new file mode 100644
index 0000000..08a2bc9
--- /dev/null
+++ b/scripts/brand/kokon_brand.py
@@ -0,0 +1,478 @@
+"""Kokon brand assets: the mark is defined here as geometry (cubic Bézier curves) and
+rendered to SVG and PNG, so every size is generated from one source.
+
+ python scripts/brand/kokon_brand.py preview # variant comparison sheet
+ python scripts/brand/kokon_brand.py build <variant> # full asset set into assets/brand
+
+Needs Pillow + numpy; the wordmark also needs fontTools, brotli and skia-pathops (reads the Inter font the
+app already ships in node_modules/@fontsource-variable/inter).
+"""
+
+from __future__ import annotations
+
+import math
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+
+import numpy as np
+from PIL import Image, ImageDraw, ImageFont
+
+ROOT = Path(__file__).resolve().parents[2]
+OUT = ROOT / "assets" / "brand"
+
+INK = "#0D0D0D" # the app's text colour
+PAPER = "#F7F6F2" # warm off-white of the app icon
+INK_RGB = (13, 13, 13)
+PAPER_RGB = (247, 246, 242)
+
+
+# ---------------------------------------------------------------------------------------
+# Paths: one builder gives both the SVG path data and a polygon for rasterizing.
+# ---------------------------------------------------------------------------------------
+
+class PathB:
+ def __init__(self):
+ self.d: list[str] = []
+ self.pts: list[tuple[float, float]] = []
+ self.cur = (0.0, 0.0)
+
+ def move(self, p):
+ self.d.append(f"M{p[0]:.2f} {p[1]:.2f}")
+ self.pts.append(p)
+ self.cur = p
+ return self
+
+ def line(self, p):
+ self.d.append(f"L{p[0]:.2f} {p[1]:.2f}")
+ self.pts.append(p)
+ self.cur = p
+ return self
+
+ def curve(self, c1, c2, p, n=96):
+ self.d.append(f"C{c1[0]:.2f} {c1[1]:.2f} {c2[0]:.2f} {c2[1]:.2f} {p[0]:.2f} {p[1]:.2f}")
+ p0 = np.array(self.cur)
+ a, b, c = np.array(c1), np.array(c2), np.array(p)
+ for t in np.linspace(0, 1, n)[1:]:
+ q = (1 - t) ** 3 * p0 + 3 * (1 - t) ** 2 * t * a + 3 * (1 - t) * t * t * b + t ** 3 * c
+ self.pts.append((float(q[0]), float(q[1])))
+ self.cur = p
+ return self
+
+ def close(self):
+ self.d.append("Z")
+ return self
+
+ def transformed(self, s, dx, dy):
+ out = PathB()
+ out.pts = [(x * s + dx, y * s + dy) for x, y in self.pts]
+ # Re-emit SVG data with the transform applied.
+ res = []
+ for tok in self.d:
+ cmd, nums = tok[0], tok[1:].split()
+ vals = [float(v) for v in nums]
+ vals = [v * s + (dx if i % 2 == 0 else dy) for i, v in enumerate(vals)]
+ res.append(cmd + " ".join(f"{v:.2f}" for v in vals) if vals else cmd)
+ out.d = res
+ return out
+
+
+# ---------------------------------------------------------------------------------------
+# The mark
+# ---------------------------------------------------------------------------------------
+
+@dataclass(frozen=True)
+class Variant:
+ name: str
+ label: str
+ stem: str # "leaf": two opposite corners rounded; "cocoon": rounded capsule
+ wings: bool # False: equal leaves; True: upper leaf larger, like butterfly wings
+
+
+VARIANTS = {
+ "a": Variant("a", "A · Bozzolo", "cocoon", False),
+ "b": Variant("b", "B · Ali", "leaf", True),
+ "c": Variant("c", "C · Bozzolo + ali", "cocoon", True),
+}
+
+H = 660.0 # mark height (units)
+S = 238.0 # stem width
+GAP = 26.0 # space between stem and leaves, and between the leaves
+W = 430.0 # leaf width
+K_STEM = 0.68 # curve fullness fitted to the generated logo (1.0 = square, 0.55 = circle)
+K_LEAF = 0.57
+
+
+def stem_path(v: Variant) -> PathB:
+ p = PathB()
+ x0, x1, y0, y1 = 0.0, S, 0.0, H
+ if v.stem == "leaf":
+ ry, k = 245.0, K_STEM
+ p.move((x0, y0))
+ p.curve((x0 + k * S, y0), (x1, y0 + ry - k * ry), (x1, y0 + ry))
+ p.line((x1, y1))
+ p.curve((x1 - k * S, y1), (x0, y1 - ry + k * ry), (x0, y1 - ry))
+ return p.close()
+ # Cocoon: a capsule whose ends are a little taller than a half circle.
+ r, ry, k = S / 2, S * 0.62, 0.60
+ cx = S / 2
+ p.move((x0, y0 + ry))
+ p.curve((x0, y0 + ry - k * ry), (cx - k * r, y0), (cx, y0))
+ p.curve((cx + k * r, y0), (x1, y0 + ry - k * ry), (x1, y0 + ry))
+ p.line((x1, y1 - ry))
+ p.curve((x1, y1 - ry + k * ry), (cx + k * r, y1), (cx, y1))
+ p.curve((cx - k * r, y1), (x0, y1 - ry + k * ry), (x0, y1 - ry))
+ return p.close()
+
+
+def leaf_up(x0, y0, x1, y1, k=K_LEAF) -> PathB:
+ """Corner at bottom-left (x0, y1), tip at top-right (x1, y0)."""
+ w, h = x1 - x0, y1 - y0
+ p = PathB().move((x0, y1))
+ p.curve((x0, y1 - k * h), (x1 - k * w, y0), (x1, y0))
+ p.curve((x1, y0 + k * h), (x0 + k * w, y1), (x0, y1))
+ return p.close()
+
+
+def leaf_down(x0, y0, x1, y1, k=K_LEAF) -> PathB:
+ """Corner at top-left (x0, y0), tip at bottom-right (x1, y1)."""
+ w, h = x1 - x0, y1 - y0
+ p = PathB().move((x0, y0))
+ p.curve((x0, y0 + k * h), (x1 - k * w, y1), (x1, y1))
+ p.curve((x1, y1 - k * h), (x0 + k * w, y0), (x0, y0))
+ return p.close()
+
+
+def mark(v: Variant) -> list[PathB]:
+ lx = S + GAP
+ room = H - GAP
+ if v.wings:
+ hu, hl = room * 0.56, room * 0.44
+ wu, wl = W, W * 0.84
+ else:
+ hu = hl = room / 2
+ wu = wl = W
+ return [stem_path(v), leaf_up(lx, 0, lx + wu, hu), leaf_down(lx, hu + GAP, lx + wl, H)]
+
+
+def bbox(paths):
+ pts = np.array([p for path in paths for p in path.pts])
+ return pts[:, 0].min(), pts[:, 1].min(), pts[:, 0].max(), pts[:, 1].max()
+
+
+def placed(paths, box, align="center"):
+ """Scales and centres `paths` into box = (x, y, w, h)."""
+ x0, y0, x1, y1 = bbox(paths)
+ s = min(box[2] / (x1 - x0), box[3] / (y1 - y0))
+ dx = box[0] + (box[2] - (x1 - x0) * s) / 2 - x0 * s
+ dy = box[1] + (box[3] - (y1 - y0) * s) / 2 - y0 * s
+ if align == "left":
+ dx = box[0] - x0 * s
+ return [p.transformed(s, dx, dy) for p in paths], s
+
+
+# ---------------------------------------------------------------------------------------
+# App icon shape: a superellipse ("squircle"), like iOS and Windows 11 app tiles.
+# ---------------------------------------------------------------------------------------
+
+def squircle(cx, cy, r, n=5.0, steps=720) -> PathB:
+ p = PathB()
+ for i in range(steps):
+ t = 2 * math.pi * i / steps
+ c, s = math.cos(t), math.sin(t)
+ x = cx + r * math.copysign(abs(c) ** (2 / n), c)
+ y = cy + r * math.copysign(abs(s) ** (2 / n), s)
+ (p.move if i == 0 else p.line)((x, y))
+ return p.close()
+
+
+# ---------------------------------------------------------------------------------------
+# Rendering
+# ---------------------------------------------------------------------------------------
+
+SS = 4 # supersampling
+
+
+def raster(size, layers, bg=None):
+ """layers: list of (paths, rgba). Returns an RGBA image of `size` (w, h)."""
+ W_, H_ = size[0] * SS, size[1] * SS
+ img = Image.new("RGBA", (W_, H_), bg or (0, 0, 0, 0))
+ for paths, color in layers:
+ m = Image.new("L", (W_, H_), 0)
+ d = ImageDraw.Draw(m)
+ for p in paths:
+ d.polygon([(x * SS, y * SS) for x, y in p.pts], fill=255)
+ solid = Image.new("RGBA", (W_, H_), color)
+ img = Image.composite(solid, img, m) if color[3] == 255 else Image.alpha_composite(img, Image.composite(solid, Image.new("RGBA", (W_, H_), (0, 0, 0, 0)), m))
+ return img.resize(size, Image.LANCZOS)
+
+
+def svg(size, layers, bg=None) -> str:
+ parts = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {size[0]} {size[1]}" width="{size[0]}" height="{size[1]}">']
+ if bg:
+ parts.append(f'<rect width="{size[0]}" height="{size[1]}" fill="{bg}"/>')
+ for paths, fill, extra in layers:
+ parts.append(f'<path fill="{fill}" {extra}d="{" ".join(" ".join(p.d) for p in paths)}"/>')
+ parts.append("</svg>")
+ return "\n".join(parts) + "\n"
+
+
+def icon_layers(v: Variant, size: int, inverse=False, border=True):
+ """App icon: squircle tile with the mark inside. Returns (raster layers, svg layers)."""
+ r = size * 0.46
+ tile = squircle(size / 2, size / 2, r)
+ m = size * 0.50 # mark height
+ paths, _ = placed(mark(v), (size / 2 - m / 2, size / 2 - m / 2, m, m))
+ tile_rgb, mark_rgb = (INK_RGB, PAPER_RGB) if inverse else (PAPER_RGB, INK_RGB)
+ tile_hex, mark_hex = (INK, PAPER) if inverse else (PAPER, INK)
+ rl, sl = [], []
+ if border and not inverse:
+ # A hairline keeps a light tile visible on light backgrounds (Windows light theme).
+ edge = squircle(size / 2, size / 2, r + max(1.0, size / 512))
+ rl.append(([edge], (0, 0, 0, 28)))
+ sl.append(([edge], "#000000", 'fill-opacity="0.11" '))
+ rl += [([tile], tile_rgb + (255,)), (paths, mark_rgb + (255,))]
+ sl += [([tile], tile_hex, ""), (paths, mark_hex, "")]
+ return rl, sl
+
+
+# ---------------------------------------------------------------------------------------
+# Inter (wordmark): instance the variable font the app ships, as TTF for Pillow and paths.
+# ---------------------------------------------------------------------------------------
+
+def inter_ttf(weight=600) -> Path:
+ out = Path(__file__).with_name(f".inter-{weight}-merged.ttf")
+ if out.exists():
+ return out
+ from fontTools.ttLib import TTFont
+ from fontTools.varLib.instancer import OverlapMode, instantiateVariableFont
+
+ src = ROOT / "node_modules" / "@fontsource-variable" / "inter" / "files" / "inter-latin-wght-normal.woff2"
+ f = TTFont(src)
+ # Variable fonts keep overlapping and self-overlapping contours; merge them (skia-pathops)
+ # so the outlines fill correctly with any rule, in SVG and in raster.
+ inst = instantiateVariableFont(f, {"wght": weight}, overlap=OverlapMode.REMOVE)
+ inst.flavor = None
+ inst.save(out)
+ return out
+
+
+def text_paths(text, size_px, x, y_baseline, weight=600, tracking=-0.02) -> list[PathB]:
+ """Glyph outlines of `text` as PathB (y down), baseline at y_baseline."""
+ from fontTools.pens.basePen import BasePen
+ from fontTools.ttLib import TTFont
+
+ f = TTFont(inter_ttf(weight))
+ upm = f["head"].unitsPerEm
+ s = size_px / upm
+ cmap, gs, hmtx = f.getBestCmap(), f.getGlyphSet(), f["hmtx"]
+ paths: list[PathB] = []
+
+ class Pen(BasePen):
+ def __init__(self, ox):
+ super().__init__(gs)
+ self.ox = ox
+ self.p = None
+
+ def tr(self, pt):
+ return (self.ox + pt[0] * s, y_baseline - pt[1] * s)
+
+ def _moveTo(self, pt):
+ self.p = PathB().move(self.tr(pt))
+
+ def _lineTo(self, pt):
+ self.p.line(self.tr(pt))
+
+ def _curveToOne(self, a, b, c):
+ self.p.curve(self.tr(a), self.tr(b), self.tr(c), n=24)
+
+ def _closePath(self):
+ paths.append(self.p.close())
+
+ pen_x = x
+ for ch in text:
+ g = cmap[ord(ch)]
+ gs[g].draw(Pen(pen_x))
+ pen_x += hmtx[g][0] * s + tracking * size_px
+ return paths
+
+
+def signed_area(p: PathB) -> float:
+ pts = p.pts
+ return 0.5 * sum(x0 * y1 - x1 * y0 for (x0, y0), (x1, y1) in zip(pts, pts[1:] + pts[:1]))
+
+
+def raster_text(size, paths, color, bg=None):
+ """Non-zero fill like a font renderer: contours turning the same way as the largest one
+ are filled (overlapping parts of a glyph merge), the others are holes (the inside of o)."""
+ W_, H_ = size[0] * SS, size[1] * SS
+ outer_sign = math.copysign(1, max((signed_area(p) for p in paths), key=abs))
+ m = Image.new("L", (W_, H_), 0)
+ d = ImageDraw.Draw(m)
+ for hole in (False, True):
+ for p in paths:
+ if (math.copysign(1, signed_area(p)) != outer_sign) == hole:
+ d.polygon([(x * SS, y * SS) for x, y in p.pts], fill=0 if hole else 255)
+ return m
+
+
+# ---------------------------------------------------------------------------------------
+# Preview sheet
+# ---------------------------------------------------------------------------------------
+
+def preview():
+ font = ImageFont.truetype(str(inter_ttf(600)), 26)
+ small = ImageFont.truetype(str(inter_ttf(500)), 16)
+ col_w, sheet_h = 460, 900
+ sheet = Image.new("RGBA", (col_w * len(VARIANTS) + 40, sheet_h), (255, 255, 255, 255))
+ d = ImageDraw.Draw(sheet)
+ for i, v in enumerate(VARIANTS.values()):
+ x = 20 + i * col_w
+ d.text((x + 20, 20), v.label, fill=INK_RGB + (255,), font=font)
+ # Large mark.
+ paths, _ = placed(mark(v), (0, 0, 300, 300))
+ sheet.alpha_composite(raster((300, 300), [(paths, INK_RGB + (255,))]), (x + 60, 80))
+ # App icon on a light and on a dark background.
+ for j, bgc in enumerate([(232, 232, 232, 255), (32, 32, 32, 255)]):
+ box = Image.new("RGBA", (200, 200), bgc)
+ rl, _ = icon_layers(v, 180)
+ box.alpha_composite(raster((180, 180), rl), (10, 10))
+ sheet.alpha_composite(box, (x + 10 + j * 215, 420))
+ d.text((x + 20, 630), "Inverse (web)", fill=(90, 90, 90, 255), font=small)
+ rl, _ = icon_layers(v, 120, inverse=True)
+ sheet.alpha_composite(raster((120, 120), rl), (x + 20, 660))
+ # Real small sizes, shown at 1:1 and enlarged ×4 (nearest) to judge legibility.
+ d.text((x + 170, 630), "48 / 32 / 16 px", fill=(90, 90, 90, 255), font=small)
+ ox = x + 170
+ for sz in (48, 32, 16):
+ rl, _ = icon_layers(v, sz)
+ sheet.alpha_composite(raster((sz, sz), rl), (ox, 665))
+ ox += sz + 12
+ rl, _ = icon_layers(v, 16)
+ big = raster((16, 16), rl).resize((96, 96), Image.NEAREST)
+ sheet.alpha_composite(big, (x + 170, 740))
+ d.text((x + 275, 800), "16 px ×6", fill=(140, 140, 140, 255), font=small)
+ OUT.mkdir(parents=True, exist_ok=True)
+ f = OUT / "explorations" / "kokon-variants.png"
+ f.parent.mkdir(exist_ok=True)
+ sheet.convert("RGB").save(f)
+ print(f)
+
+
+# ---------------------------------------------------------------------------------------
+# Full asset set
+# ---------------------------------------------------------------------------------------
+
+def lockup(v: Variant, font_px: float, mark_rgb, text_hex_for_svg=None):
+ """Mark + "Kokon". Returns (size, mark paths, text paths)."""
+ cap = 0.727 * font_px # Inter cap height
+ mh = cap * 1.12
+ gap = mh * 0.30
+ pad = 0.0
+ m_paths, _ = placed(mark(v), (pad, 0, mh * 2, mh), align="left")
+ mx1 = bbox(m_paths)[2]
+ baseline = mh / 2 + cap / 2
+ t_paths = text_paths("Kokon", font_px, mx1 + gap, baseline)
+ x0, y0, x1, y1 = bbox(m_paths + t_paths)
+ w, h = math.ceil(x1 - min(0, x0)), math.ceil(max(y1, mh))
+ return (w, h), m_paths, t_paths
+
+
+def write_svg(path: Path, size, layers, bg=None):
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(svg(size, layers, bg), encoding="utf-8")
+
+
+def compose(size, mark_paths, text_paths_, rgb, bg=None):
+ """Raster of the mark and the text in one colour."""
+ img = raster(size, [(mark_paths, rgb + (255,))], bg)
+ if text_paths_:
+ m = raster_text(size, text_paths_, rgb).resize(size, Image.LANCZOS)
+ img.alpha_composite(Image.composite(Image.new("RGBA", size, rgb + (255,)), Image.new("RGBA", size, (0, 0, 0, 0)), m))
+ return img
+
+
+def build(v: Variant):
+ OUT.mkdir(parents=True, exist_ok=True)
+ made = []
+
+ def save(img, rel):
+ p = OUT / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ img.save(p)
+ made.append(p)
+
+ # 1. Mark alone (transparent): ink and white.
+ for name, rgb, hexc in [("kokon-mark", INK_RGB, INK), ("kokon-mark-white", PAPER_RGB, PAPER)]:
+ paths, _ = placed(mark(v), (0, 0, 1024, 1024))
+ x0, y0, x1, y1 = bbox(paths)
+ write_svg(OUT / "mark" / f"{name}.svg", (1024, 1024), [(paths, hexc, "")])
+ made.append(OUT / "mark" / f"{name}.svg")
+ save(raster((1024, 1024), [(paths, rgb + (255,))]), f"mark/{name}-1024.png")
+
+ # 2. App icon (light tile, desktop) and inverse tile (web, social, anywhere else).
+ for name, inv in [("kokon-icon", False), ("kokon-icon-inverse", True)]:
+ _, sl = icon_layers(v, 1024, inverse=inv)
+ write_svg(OUT / "icon" / f"{name}.svg", (1024, 1024), sl)
+ made.append(OUT / "icon" / f"{name}.svg")
+ for sz in (1024, 512, 256):
+ rl, _ = icon_layers(v, sz, inverse=inv)
+ save(raster((sz, sz), rl), f"icon/{name}-{sz}.png")
+
+ # 3. Horizontal logo (mark + wordmark), for light and for dark backgrounds.
+ size, mp, tp = lockup(v, 400, INK_RGB)
+ pad = 40
+ mp = [p.transformed(1, pad, pad) for p in mp]
+ tp = [p.transformed(1, pad, pad) for p in tp]
+ size = (size[0] + 2 * pad, size[1] + 2 * pad)
+ for name, rgb, hexc in [("kokon-logo", INK_RGB, INK), ("kokon-logo-white", PAPER_RGB, PAPER)]:
+ write_svg(OUT / "logo" / f"{name}.svg", size, [(mp, hexc, ""), (tp, hexc, "")])
+ made.append(OUT / "logo" / f"{name}.svg")
+ save(compose(size, mp, tp, rgb), f"logo/{name}.png")
+
+ # 4. Web: favicon (inverse tile reads best in browser tabs, light and dark), touch icons.
+ web_sizes = {}
+ for sz in (16, 32, 48, 180, 192, 512):
+ rl, _ = icon_layers(v, sz, inverse=True)
+ web_sizes[sz] = raster((sz, sz), rl)
+ save(web_sizes[180], "web/apple-touch-icon.png")
+ save(web_sizes[192], "web/icon-192.png")
+ save(web_sizes[512], "web/icon-512.png")
+ ico = OUT / "web" / "favicon.ico"
+ web_sizes[48].save(ico, sizes=[(16, 16), (32, 32), (48, 48)], append_images=[web_sizes[16], web_sizes[32]])
+ made.append(ico)
+ _, sl = icon_layers(v, 64, inverse=True)
+ write_svg(OUT / "web" / "favicon.svg", (64, 64), sl)
+ made.append(OUT / "web" / "favicon.svg")
+
+ # 5. Desktop app .ico, every size rendered directly (sharper than downscaling 1024).
+ ico_sizes = (16, 20, 24, 32, 40, 48, 64, 128, 256)
+ imgs = {sz: raster((sz, sz), icon_layers(v, sz)[0]) for sz in ico_sizes}
+ app_ico = OUT / "icon" / "kokon-app.ico"
+ imgs[256].save(app_ico, sizes=[(s, s) for s in ico_sizes], append_images=[imgs[s] for s in ico_sizes if s != 256])
+ made.append(app_ico)
+
+ # 6. Social preview (GitHub, links): dark, white logo, one line of copy.
+ W_, H_ = 1280, 640
+ size_l, mp, tp = lockup(v, 150, PAPER_RGB)
+ ox, oy = (W_ - size_l[0]) / 2, 225
+ mp = [p.transformed(1, ox, oy) for p in mp]
+ tp = [p.transformed(1, ox, oy) for p in tp]
+ img = compose((W_, H_), mp, tp, PAPER_RGB, bg=INK_RGB + (255,))
+ d = ImageDraw.Draw(img)
+ f = ImageFont.truetype(str(inter_ttf(500)), 30)
+ line = "Create and edit images by describing them. Privately, on your own GPU."
+ tw = d.textlength(line, font=f)
+ d.text(((W_ - tw) / 2, oy + size_l[1] + 70), line, font=f, fill=PAPER_RGB + (178,))
+ save(img.convert("RGB"), "social/kokon-social-1280x640.png")
+
+ for p in made:
+ print(p.relative_to(ROOT))
+
+
+if __name__ == "__main__":
+ cmd = sys.argv[1] if len(sys.argv) > 1 else "preview"
+ if cmd == "preview":
+ preview()
+ elif cmd == "build":
+ build(VARIANTS[sys.argv[2] if len(sys.argv) > 2 else "c"])
diff --git a/scripts/build-release.ps1 b/scripts/build-release.ps1
index dde8178..7168ac2 100644
--- a/scripts/build-release.ps1
+++ b/scripts/build-release.ps1
@@ -1,5 +1,5 @@
-# Builds the Windows release: qls-service.exe, qls-mcp.exe, the desktop app and the
-# NSIS installer ("Qwen Local Studio_<version>_x64-setup.exe").
+# Builds the Windows release: kokon-service.exe, kokon-mcp.exe, the desktop app and the
+# NSIS installer ("Kokon_<version>_x64-setup.exe").
#
# powershell -ExecutionPolicy Bypass -File scripts\build-release.ps1
#
@@ -18,12 +18,12 @@ 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
+Write-Host "2/5 kokon-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
+Copy-Item target\release\kokon-service.exe src-tauri\binaries\kokon-service-x86_64-pc-windows-msvc.exe -Force
-Write-Host "3/5 qls-mcp.exe" -ForegroundColor Cyan
+Write-Host "3/5 kokon-mcp.exe" -ForegroundColor Cyan
Push-Location mcp; npm run build:exe; $rc = $LASTEXITCODE; Pop-Location
if ($rc) { throw "MCP build failed" }
@@ -32,12 +32,12 @@ 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"
+$exe = Get-Item "target\release\Kokon.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
+Copy-Item $exe.FullName "dist-release\Kokon.exe" -Force
+Copy-Item $setup.FullName "dist-release\Kokon Setup.exe" -Force
+Copy-Item target\release\kokon-service.exe dist-release\ -Force
+Copy-Item mcp\build\kokon-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
+Write-Host "Installer: $root\dist-release\Kokon Setup.exe" -ForegroundColor Green
diff --git a/scripts/dev/m1-backend-test.ps1 b/scripts/dev/m1-backend-test.ps1
index 7adf2cb..a50a5a7 100644
--- a/scripts/dev/m1-backend-test.ps1
+++ b/scripts/dev/m1-backend-test.ps1
@@ -1,5 +1,5 @@
# Milestone 1 — backend foundation, real inference.
-# Starts qls-service (debug build) with isolated test data, which launches sd-server,
+# Starts kokon-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
@@ -17,7 +17,7 @@ $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'
+$exe = Join-Path $root 'target\debug\kokon-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
diff --git a/scripts/dev/test-12gb.ps1 b/scripts/dev/test-12gb.ps1
new file mode 100644
index 0000000..94ac8ef
--- /dev/null
+++ b/scripts/dev/test-12gb.ps1
@@ -0,0 +1,207 @@
+# 12 GB verification on a bigger card. Holds VRAM with vram-ballast.py so the GPU really has
+# what a 12 GB card has, tells the planner the card has 12 GB (vramOverrideMib), then runs
+# every kind of job through the real engine and records time, sizes, VRAM peaks, spills to
+# shared memory and out-of-memory retries.
+#
+# cargo build -p qls-service
+# powershell -ExecutionPolicy Bypass -File scripts\dev\test-12gb.ps1 [-Only t2i-fast,edit-balanced] [-Image C:\path\photo.jpg]
+#
+# Close Kokon first (the GPU must be free). About 20-30 minutes for everything.
+# Results: docs\test-results\12gb-<date>.md (paste it back in the chat).
+#
+# -CardMib total VRAM of the card to emulate, as nvidia-smi reports it (12 GB: 12282)
+# -SdcppDir stable-diffusion.cpp folder with the models (official Q4_K_M preferred)
+# -Image a large photo to edit (optional; otherwise only generated images are edited)
+param([string[]]$Only, [string]$Image, [int]$CardMib = 12282, [string]$SdcppDir = 'C:\AI\sdcpp', [switch]$NoBallast)
+
+$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\12gb'
+$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, $env:QLS_DATA_DIR | Out-Null
+
+$exe = Join-Path $root 'target\debug\kokon-service.exe'
+if (-not (Test-Path $exe)) { throw "Build first: cargo build -p qls-service" }
+if (Get-Process sd-server -ErrorAction SilentlyContinue) { throw "sd-server is running. Close Kokon (and any sd-server) first." }
+
+# Official weights when present; otherwise whatever Q4_K_M diffusion model is there.
+$m = Join-Path $SdcppDir 'models\qwen21'
+$diffusion = Join-Path $m 'qwen-image-2.1-Q4_K_M.gguf'
+if (-not (Test-Path $diffusion)) {
+ $diffusion = Join-Path $m 'qwen-image-2.1-UC-Q4_K_M.gguf'
+ Write-Host "Official qwen-image-2.1-Q4_K_M.gguf not found; testing with $diffusion (same size and architecture)." -ForegroundColor Yellow
+}
+$prof = @{
+ id = 'qwen-image-2.1'; displayName = 'test'; diffusionModel = $diffusion
+ vae = (Join-Path $m 'qwen_image_2.1_vae_bf16.safetensors')
+ textEncoder = (Join-Path $m 'Qwen3VL-8B-Instruct-Q4_K_M.gguf')
+ visionProjector = (Join-Path $m 'mmproj-Qwen3VL-8B-Instruct-F16.gguf')
+}
+@{
+ sdcppDir = $SdcppDir; serverPort = 39190; servicePort = 39191; outputDir = $out; setupComplete = $true
+ hardwarePreset = '12gb'; vramOverrideMib = $CardMib; activeProfile = 'qwen-image-2.1'; profiles = @($prof)
+} | ConvertTo-Json -Depth 5 | Set-Content (Join-Path $env:QLS_CONFIG_DIR 'config.json') -Encoding utf8
+
+# 1. Ballast: the memory a 12 GB card does not have.
+$ballast = $null
+if (-not $NoBallast) {
+ $blog = Join-Path $test 'ballast.log'
+ Remove-Item $blog -ErrorAction SilentlyContinue
+ $ballast = Start-Process python -ArgumentList '-I', "`"$root\scripts\dev\vram-ballast.py`"", '--card-mib', $CardMib, '--sdcpp', "`"$SdcppDir`"" `
+ -RedirectStandardOutput $blog -RedirectStandardError "$blog.err" -PassThru -WindowStyle Hidden
+ for ($i = 0; $i -lt 40 -and -not (Select-String -Path $blog -Pattern 'Holding' -Quiet -ErrorAction SilentlyContinue); $i++) { Start-Sleep -Milliseconds 250 }
+ if ($ballast.HasExited -or -not (Select-String -Path $blog -Pattern 'Holding' -Quiet)) { throw "Ballast failed: $(Get-Content "$blog.err" -Raw)" }
+ Write-Host (Get-Content $blog | Select-Object -First 1) -ForegroundColor Cyan
+}
+
+# 2. Service (isolated data, ports and output).
+$svc = Start-Process $exe -ArgumentList '--port', 39191 -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:39191/api/v1"
+
+# 3. VRAM sampler: whole-GPU dedicated use (nvidia-smi) and sd-server's shared (spilled) memory.
+$samples = Join-Path $test 'vram.csv'
+"t,used_mib,shared_mib" | Set-Content $samples
+$sampler = Start-Job -ArgumentList $samples -ScriptBlock {
+ param($file)
+ while ($true) {
+ $used = (& nvidia-smi --query-gpu=memory.used --format=csv,noheader,nounits | Select-Object -First 1).Trim()
+ $shared = 0
+ $p = Get-Process sd-server -ErrorAction SilentlyContinue | Select-Object -First 1
+ if ($p) {
+ try {
+ $c = Get-Counter "\GPU Process Memory(pid_$($p.Id)*)\Shared Usage" -ErrorAction Stop
+ $shared = [math]::Round((($c.CounterSamples | Measure-Object CookedValue -Sum).Sum) / 1MB)
+ } catch {}
+ }
+ "$([DateTimeOffset]::Now.ToUnixTimeMilliseconds()),$used,$shared" | Add-Content $file
+ Start-Sleep -Milliseconds 500
+ }
+}
+function Peaks($fromMs, $toMs) {
+ $rows = Import-Csv $samples | Where-Object { [int64]$_.t -ge $fromMs -and [int64]$_.t -le $toMs }
+ if (-not $rows) { return @('?', '?') }
+ $u = ($rows | ForEach-Object { [int]$_.used_mib } | Measure-Object -Maximum).Maximum
+ $s = ($rows | ForEach-Object { [int]$_.shared_mib } | Measure-Object -Maximum).Maximum
+ return @($u, $s)
+}
+
+$results = @()
+$gens = @{}
+$sw = [Diagnostics.Stopwatch]::StartNew()
+try {
+ Write-Host "== Loading the model" -ForegroundColor Cyan
+ $t0 = [DateTimeOffset]::Now.ToUnixTimeMilliseconds()
+ Invoke-RestMethod -Method Post "$B/backend/start" -Headers $H -TimeoutSec 900 | Out-Null
+ $pk = Peaks $t0 ([DateTimeOffset]::Now.ToUnixTimeMilliseconds())
+ $results += [pscustomobject]@{ Case = 'model load'; Status = 'done'; Seconds = [math]::Round(([DateTimeOffset]::Now.ToUnixTimeMilliseconds() - $t0) / 1000); Working = ''; Output = ''; SecPerStep = ''; PeakVramMiB = $pk[0]; PeakSharedMiB = $pk[1]; Notes = '' }
+
+ function Run($name, $body) {
+ if (-not (Want $name)) { return $null }
+ $body.seed = 42
+ $body.client = 'test-12gb'
+ $json = $body | ConvertTo-Json -Depth 6
+ $logBefore = (Invoke-RestMethod "$B/logs?lines=4000" -Headers $H).lines.Count
+ $t0 = [DateTimeOffset]::Now.ToUnixTimeMilliseconds()
+ $job = Invoke-RestMethod -Method Post -Uri "$B/jobs" -Headers $H -ContentType 'application/json' -Body ([Text.Encoding]::UTF8.GetBytes($json))
+ Write-Host "== $name" -ForegroundColor Cyan
+ $last = ''; $sps = 0
+ while ($true) {
+ $j = Invoke-RestMethod -Uri "$B/jobs/$($job.id)/wait?timeout=2" -Headers $H
+ if ($j.seconds_per_step -and $j.seconds_per_step -gt $sps) { $sps = $j.seconds_per_step }
+ $step = if ($j.step) { " $($j.step[0])/$($j.step[1])" } else { '' }
+ $line = "$($j.status) $($j.stage)$step"
+ if ($line -ne $last) { Write-Host (" [{0,6:N1}s] {1}" -f (([DateTimeOffset]::Now.ToUnixTimeMilliseconds() - $t0) / 1000), $line); $last = $line }
+ if ($j.status -in 'done', 'failed', 'cancelled') { break }
+ }
+ $t1 = [DateTimeOffset]::Now.ToUnixTimeMilliseconds()
+ $pk = Peaks $t0 $t1
+ $log = (Invoke-RestMethod "$B/logs?lines=4000" -Headers $H).lines | Select-Object -Skip ([math]::Max(0, $logBefore - 50))
+ $memLines = @($log | Where-Object { $_ -match 'out of memory|insufficient memory|retrying without|failed to allocate|OOM' } | Select-Object -Unique)
+ $notes = @($j.notes) + @($memLines | ForEach-Object { "log: $($_.Trim())" })
+ if ($j.error) { $notes += "error: $($j.error.message)" }
+ $g = $j.results | Select-Object -First 1
+ if ($g) { $gens[$name] = $g }
+ $p = $j.plan
+ $script:results += [pscustomobject]@{
+ Case = $name; Status = $j.status; Seconds = [math]::Round(($t1 - $t0) / 1000)
+ Working = if ($p) { "$($p.working.width)x$($p.working.height)" } else { '' }
+ Output = if ($g) { "$($g.width)x$($g.height)" } else { '' }
+ SecPerStep = if ($sps) { [math]::Round($sps, 2) } else { '' }
+ PeakVramMiB = $pk[0]; PeakSharedMiB = $pk[1]
+ Notes = ($notes | Where-Object { $_ } | Select-Object -Unique) -join ' | '
+ }
+ Write-Host (" {0} in {1}s, working {2}, peak {3} MiB, shared {4} MiB" -f $j.status, [math]::Round(($t1 - $t0) / 1000), $script:results[-1].Working, $pk[0], $pk[1])
+ return $g
+ }
+
+ $scene = 'a red vintage bicycle leaning against a sunlit brick wall in a quiet street, photo'
+ Run 't2i-fast' @{ prompt = $scene; mode = 'generate'; quality = 'fast' } | Out-Null
+ Run 't2i-balanced' @{ prompt = $scene; mode = 'generate'; quality = 'balanced'; aspect_ratio = '16:9' } | Out-Null
+ Run 't2i-quality' @{ prompt = $scene; mode = 'generate'; quality = 'quality' } | Out-Null
+ $src = if ($gens['t2i-balanced']) { "gen:$($gens['t2i-balanced'].id)" } elseif ($gens['t2i-fast']) { "gen:$($gens['t2i-fast'].id)" } else { $null }
+ if ($Image) { $photo = (Resolve-Path $Image).Path } else { $photo = $null }
+ if ($src) {
+ Run 'edit-balanced' @{ prompt = 'make it night, with warm street lights and wet pavement'; mode = 'edit'; images = @($src); quality = 'balanced' } | Out-Null
+ Run 'edit-quality' @{ prompt = 'make it night, with warm street lights and wet pavement'; mode = 'edit'; images = @($src); quality = 'quality' } | Out-Null
+ # Inpaint (Remove): a mask over the middle third of the image.
+ if (Want 'inpaint-remove') {
+ Add-Type -AssemblyName System.Drawing
+ $g0 = $gens['t2i-balanced']; if (-not $g0) { $g0 = $gens['t2i-fast'] }
+ $bmp = New-Object System.Drawing.Bitmap $g0.width, $g0.height
+ $gr = [System.Drawing.Graphics]::FromImage($bmp)
+ $gr.Clear([System.Drawing.Color]::Black)
+ $gr.FillEllipse([System.Drawing.Brushes]::White, [int]($g0.width / 3), [int]($g0.height / 4), [int]($g0.width / 3), [int]($g0.height / 2))
+ $mask = Join-Path $test 'mask.png'
+ $bmp.Save($mask, [System.Drawing.Imaging.ImageFormat]::Png); $gr.Dispose(); $bmp.Dispose()
+ Run 'inpaint-remove' @{ prompt = ''; mode = 'inpaint'; images = @($src); mask = $mask; inpaint_action = 'remove'; quality = 'balanced' } | Out-Null
+ }
+ Run 'outpaint' @{ prompt = 'continue the street'; mode = 'outpaint'; images = @($src); quality = 'balanced'; outpaint = @{ left = 25; right = 25; top = 0; bottom = 0; units = 'percent' } } | Out-Null
+ if ($gens['t2i-fast']) {
+ Run 'multi-ref' @{ prompt = 'put the bicycle from image 1 into the street of image 2, at night'; mode = 'multi_reference'; images = @("gen:$($gens['t2i-fast'].id)", $src); quality = 'balanced' } | Out-Null
+ }
+ Run 'upscale-detailed' @{ prompt = ''; mode = 'upscale'; images = @($src); upscale = @{ method = 'detailed'; scale = 2 } } | Out-Null
+ }
+ if ($photo) {
+ Run 'photo-edit-balanced' @{ prompt = 'replace the sky with a dramatic sunset'; mode = 'edit'; images = @($photo); quality = 'balanced' } | Out-Null
+ Run 'photo-edit-quality' @{ prompt = 'replace the sky with a dramatic sunset'; mode = 'edit'; images = @($photo); quality = 'quality' } | Out-Null
+ }
+}
+finally {
+ $status = $null
+ try { $status = Invoke-RestMethod "$B/status" -Headers $H } catch {}
+ try { Invoke-RestMethod -Method Post "$B/backend/stop" -Headers $H | Out-Null } catch {}
+ try { Invoke-RestMethod -Method Post "$B/shutdown" -Headers $H | Out-Null } catch {}
+ Stop-Job $sampler -ErrorAction SilentlyContinue; Remove-Job $sampler -Force -ErrorAction SilentlyContinue
+ if ($ballast -and -not $ballast.HasExited) { Stop-Process -Id $ballast.Id -Force }
+ Start-Sleep 1
+ if (-not $svc.HasExited) { Stop-Process -Id $svc.Id -Force -ErrorAction SilentlyContinue }
+
+ $gpu = (& nvidia-smi --query-gpu=name,memory.total,driver_version --format=csv,noheader | Select-Object -First 1)
+ $policy = 'unknown (NVIDIA Control Panel > Manage 3D settings > CUDA - Sysmem Fallback Policy)'
+ $md = @(
+ "# 12 GB verification - $(Get-Date -Format 'yyyy-MM-dd HH:mm')", '',
+ "- GPU: $gpu; emulated card: $CardMib MiB (ballast: $(if ($NoBallast) { 'off' } else { 'on' }), planner override: $CardMib MiB)",
+ "- Model: $diffusion", "- Sysmem fallback policy: $policy",
+ "- Total wall time: $([math]::Round($sw.Elapsed.TotalMinutes, 1)) min", '',
+ '| Case | Status | Seconds | Working | Output | s/step | Peak VRAM MiB (whole GPU, incl. ballast) | Peak shared MiB (sd-server) | Notes |',
+ '| --- | --- | --- | --- | --- | --- | --- | --- | --- |'
+ )
+ foreach ($r in $results) { $md += "| $($r.Case) | $($r.Status) | $($r.Seconds) | $($r.Working) | $($r.Output) | $($r.SecPerStep) | $($r.PeakVramMiB) | $($r.PeakSharedMiB) | $($r.Notes -replace '\|', '/') |" }
+ $md += '', "Peak VRAM includes the ballast; a real 12 GB card has $CardMib MiB in total. Shared MiB above a few hundred means sd-server spilled into system memory (slow, but no crash with the default fallback policy)."
+ $md += "Images: $out"
+ $dir = Join-Path $root 'docs\test-results'
+ New-Item -ItemType Directory -Force $dir | Out-Null
+ $file = Join-Path $dir "12gb-$(Get-Date -Format 'yyyy-MM-dd-HHmm').md"
+ $md | Set-Content $file -Encoding utf8
+ $results | Format-Table Case, Status, Seconds, Working, Output, SecPerStep, PeakVramMiB, PeakSharedMiB -AutoSize
+ Write-Host "Results: $file" -ForegroundColor Green
+}
diff --git a/scripts/dev/validate-upscale.ps1 b/scripts/dev/validate-upscale.ps1
index de9cac2..7270e6b 100644
--- a/scripts/dev/validate-upscale.ps1
+++ b/scripts/dev/validate-upscale.ps1
@@ -1,11 +1,11 @@
# Speed & upscaling validation through the real app engine (planner, two-pass refine,
-# ESRGAN enlargement, Upscale action). Starts qls-service (debug build) with isolated
+# ESRGAN enlargement, Upscale action). Starts kokon-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.
+# Close Kokon 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)
@@ -25,7 +25,7 @@ $port = 39181
# <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'
+$exe = Join-Path $root 'target\debug\kokon-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
diff --git a/scripts/dev/vram-ballast.py b/scripts/dev/vram-ballast.py
new file mode 100644
index 0000000..f1b0535
--- /dev/null
+++ b/scripts/dev/vram-ballast.py
@@ -0,0 +1,99 @@
+"""Holds GPU memory so a larger card behaves like a smaller one (e.g. a 16 GB RTX 5070 Ti
+like a 12 GB card) while Kokon runs. Uses only the CUDA runtime DLL that ships
+with stable-diffusion.cpp (no Python packages).
+
+ python scripts\\dev\\vram-ballast.py --card-mib 12282 # emulate a 12 GB card
+ python scripts\\dev\\vram-ballast.py --mib 4000 --seconds 5 # quick self-test
+
+--card-mib is the total a real card reports (12 GB cards: 12282 MiB in nvidia-smi); the
+ballast is this card's total minus that. Desktop and other apps keep using what they use, as
+they would on the smaller card. The memory is written every half second so Windows keeps it
+resident instead of paging it out to shared memory. Ctrl+C frees it.
+
+Limits of the emulation: memory bandwidth and compute stay those of the bigger card, so
+times are faster than on a real 12 GB card (an RTX 3060 has ~40 % of a 5070 Ti's bandwidth).
+"""
+
+import argparse
+import ctypes
+import os
+import sys
+import time
+
+MIB = 1024 * 1024
+CHUNK_MIB = 256
+
+
+def load_cudart(sdcpp_dir):
+ os.add_dll_directory(sdcpp_dir)
+ try:
+ return ctypes.CDLL(os.path.join(sdcpp_dir, "cudart64_12.dll"))
+ except OSError as e:
+ sys.exit(f"cudart64_12.dll not found in {sdcpp_dir} ({e}). Pass --sdcpp <stable-diffusion.cpp folder>.")
+
+
+def check(rt, code, what):
+ if code != 0:
+ rt.cudaGetErrorString.restype = ctypes.c_char_p
+ sys.exit(f"{what} failed: {rt.cudaGetErrorString(code).decode()} ({code})")
+
+
+def mem_info(rt):
+ free, total = ctypes.c_size_t(), ctypes.c_size_t()
+ check(rt, rt.cudaMemGetInfo(ctypes.byref(free), ctypes.byref(total)), "cudaMemGetInfo")
+ return free.value // MIB, total.value // MIB
+
+
+def main():
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ g = ap.add_mutually_exclusive_group(required=True)
+ g.add_argument("--card-mib", type=int, help="total VRAM of the card to emulate, as nvidia-smi reports it (12 GB: 12282)")
+ g.add_argument("--mib", type=int, help="hold exactly this many MiB")
+ ap.add_argument("--device", type=int, default=0)
+ ap.add_argument("--seconds", type=float, default=0, help="release after this long (0 = until Ctrl+C)")
+ ap.add_argument("--sdcpp", default=r"C:\AI\sdcpp", help="folder with cudart64_12.dll")
+ a = ap.parse_args()
+
+ rt = load_cudart(a.sdcpp)
+ rt.cudaMemset.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_size_t]
+ check(rt, rt.cudaSetDevice(a.device), "cudaSetDevice")
+ free, total = mem_info(rt)
+ want = a.mib if a.mib is not None else total - a.card_mib
+ if want <= 0:
+ sys.exit(f"Nothing to hold: the card has {total} MiB.")
+ if want > free - 256:
+ sys.exit(f"Only {free} MiB free of {total}; cannot hold {want} MiB. Close the app (stop sd-server) first.")
+
+ chunks = []
+ left = want
+ while left > 0:
+ n = min(CHUNK_MIB, left) * MIB
+ p = ctypes.c_void_p()
+ check(rt, rt.cudaMalloc(ctypes.byref(p), ctypes.c_size_t(n)), "cudaMalloc")
+ chunks.append((p, n))
+ left -= n // MIB
+ free_after, _ = mem_info(rt)
+ print(f"Holding {want} MiB on GPU {a.device} ({total} MiB card): {free_after} MiB free now "
+ f"(like a {total - want} MiB card). Ctrl+C to release.", flush=True)
+
+ start = time.time()
+ last_report = 0.0
+ try:
+ while a.seconds <= 0 or time.time() - start < a.seconds:
+ for p, n in chunks:
+ check(rt, rt.cudaMemset(p, 0, ctypes.c_size_t(n)), "cudaMemset")
+ check(rt, rt.cudaDeviceSynchronize(), "cudaDeviceSynchronize")
+ if time.time() - last_report > 30:
+ last_report = time.time()
+ f, _ = mem_info(rt)
+ print(time.strftime("%H:%M:%S"), f"free {f} MiB", flush=True)
+ time.sleep(0.5)
+ except KeyboardInterrupt:
+ pass
+ for p, _ in chunks:
+ rt.cudaFree(p)
+ print("Released.")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 3dfb733..6a5d81a 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,8 +1,8 @@
[package]
-name = "qwen-local-studio"
+name = "kokon"
version.workspace = true
edition.workspace = true
-description = "Qwen Local Studio"
+description = "Kokon"
[lib]
name = "qls_app"
diff --git a/src-tauri/icons/128x128.png b/src-tauri/icons/128x128.png
index e5ebad9..ce6b4eb 100644
Binary files a/src-tauri/icons/128x128.png and b/src-tauri/icons/128x128.png differ
diff --git a/src-tauri/icons/[email protected] b/src-tauri/icons/[email protected]
index 9e047d7..632ef77 100644
Binary files a/src-tauri/icons/[email protected] and b/src-tauri/icons/[email protected] differ
diff --git a/src-tauri/icons/32x32.png b/src-tauri/icons/32x32.png
index d549a4e..8a95bca 100644
Binary files a/src-tauri/icons/32x32.png and b/src-tauri/icons/32x32.png differ
diff --git a/src-tauri/icons/64x64.png b/src-tauri/icons/64x64.png
index 6090c7e..84d2ede 100644
Binary files a/src-tauri/icons/64x64.png and b/src-tauri/icons/64x64.png differ
diff --git a/src-tauri/icons/Square107x107Logo.png b/src-tauri/icons/Square107x107Logo.png
index fdb2fc4..6d53ebc 100644
Binary files a/src-tauri/icons/Square107x107Logo.png and b/src-tauri/icons/Square107x107Logo.png differ
diff --git a/src-tauri/icons/Square142x142Logo.png b/src-tauri/icons/Square142x142Logo.png
index 2998dd5..c50c6ec 100644
Binary files a/src-tauri/icons/Square142x142Logo.png and b/src-tauri/icons/Square142x142Logo.png differ
diff --git a/src-tauri/icons/Square150x150Logo.png b/src-tauri/icons/Square150x150Logo.png
index 4fa1524..78be7a3 100644
Binary files a/src-tauri/icons/Square150x150Logo.png and b/src-tauri/icons/Square150x150Logo.png differ
diff --git a/src-tauri/icons/Square284x284Logo.png b/src-tauri/icons/Square284x284Logo.png
index 39972bd..cdb7e1d 100644
Binary files a/src-tauri/icons/Square284x284Logo.png and b/src-tauri/icons/Square284x284Logo.png differ
diff --git a/src-tauri/icons/Square30x30Logo.png b/src-tauri/icons/Square30x30Logo.png
index e3bd4e1..99d2fe1 100644
Binary files a/src-tauri/icons/Square30x30Logo.png and b/src-tauri/icons/Square30x30Logo.png differ
diff --git a/src-tauri/icons/Square310x310Logo.png b/src-tauri/icons/Square310x310Logo.png
index 91a08e8..98c90a5 100644
Binary files a/src-tauri/icons/Square310x310Logo.png and b/src-tauri/icons/Square310x310Logo.png differ
diff --git a/src-tauri/icons/Square44x44Logo.png b/src-tauri/icons/Square44x44Logo.png
index d1e8045..8672524 100644
Binary files a/src-tauri/icons/Square44x44Logo.png and b/src-tauri/icons/Square44x44Logo.png differ
diff --git a/src-tauri/icons/Square71x71Logo.png b/src-tauri/icons/Square71x71Logo.png
index dbf3128..90a7e99 100644
Binary files a/src-tauri/icons/Square71x71Logo.png and b/src-tauri/icons/Square71x71Logo.png differ
diff --git a/src-tauri/icons/Square89x89Logo.png b/src-tauri/icons/Square89x89Logo.png
index 56951ac..932b828 100644
Binary files a/src-tauri/icons/Square89x89Logo.png and b/src-tauri/icons/Square89x89Logo.png differ
diff --git a/src-tauri/icons/StoreLogo.png b/src-tauri/icons/StoreLogo.png
index a1c5bb3..e6a3ccd 100644
Binary files a/src-tauri/icons/StoreLogo.png and b/src-tauri/icons/StoreLogo.png differ
diff --git a/src-tauri/icons/android/mipmap-anydpi-v26/ic_launcher.xml b/src-tauri/icons/android/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 0000000..2ffbf24
--- /dev/null
+++ b/src-tauri/icons/android/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1,5 @@
+<?xml version="1.0" encoding="utf-8"?>
+<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
+ <foreground android:drawable="@mipmap/ic_launcher_foreground"/>
+ <background android:drawable="@color/ic_launcher_background"/>
+</adaptive-icon>
\ No newline at end of file
diff --git a/src-tauri/icons/android/mipmap-hdpi/ic_launcher.png b/src-tauri/icons/android/mipmap-hdpi/ic_launcher.png
new file mode 100644
index 0000000..8549eef
Binary files /dev/null and b/src-tauri/icons/android/mipmap-hdpi/ic_launcher.png differ
diff --git a/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png b/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png
new file mode 100644
index 0000000..f17564b
Binary files /dev/null and b/src-tauri/icons/android/mipmap-hdpi/ic_launcher_foreground.png differ
diff --git a/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png b/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png
new file mode 100644
index 0000000..02a1a34
Binary files /dev/null and b/src-tauri/icons/android/mipmap-hdpi/ic_launcher_round.png differ
diff --git a/src-tauri/icons/android/mipmap-mdpi/ic_launcher.png b/src-tauri/icons/android/mipmap-mdpi/ic_launcher.png
new file mode 100644
index 0000000..56605d4
Binary files /dev/null and b/src-tauri/icons/android/mipmap-mdpi/ic_launcher.png differ
diff --git a/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png b/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png
new file mode 100644
index 0000000..f28b9b2
Binary files /dev/null and b/src-tauri/icons/android/mipmap-mdpi/ic_launcher_foreground.png differ
diff --git a/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png b/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png
new file mode 100644
index 0000000..95dc784
Binary files /dev/null and b/src-tauri/icons/android/mipmap-mdpi/ic_launcher_round.png differ
diff --git a/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png b/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png
new file mode 100644
index 0000000..0ed6962
Binary files /dev/null and b/src-tauri/icons/android/mipmap-xhdpi/ic_launcher.png differ
diff --git a/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png b/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png
new file mode 100644
index 0000000..f9804ef
Binary files /dev/null and b/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_foreground.png differ
diff --git a/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png b/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..30c21d9
Binary files /dev/null and b/src-tauri/icons/android/mipmap-xhdpi/ic_launcher_round.png differ
diff --git a/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png b/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png
new file mode 100644
index 0000000..6376aff
Binary files /dev/null and b/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher.png differ
diff --git a/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png b/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png
new file mode 100644
index 0000000..b36dd31
Binary files /dev/null and b/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_foreground.png differ
diff --git a/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png b/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..9fe9d07
Binary files /dev/null and b/src-tauri/icons/android/mipmap-xxhdpi/ic_launcher_round.png differ
diff --git a/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png b/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png
new file mode 100644
index 0000000..4cbfb2e
Binary files /dev/null and b/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher.png differ
diff --git a/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png b/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png
new file mode 100644
index 0000000..de8413b
Binary files /dev/null and b/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_foreground.png differ
diff --git a/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png b/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png
new file mode 100644
index 0000000..3d696f7
Binary files /dev/null and b/src-tauri/icons/android/mipmap-xxxhdpi/ic_launcher_round.png differ
diff --git a/src-tauri/icons/android/values/ic_launcher_background.xml b/src-tauri/icons/android/values/ic_launcher_background.xml
new file mode 100644
index 0000000..16cdd5a
--- /dev/null
+++ b/src-tauri/icons/android/values/ic_launcher_background.xml
@@ -0,0 +1,4 @@
+<?xml version="1.0" encoding="utf-8"?>
+<resources>
+ <color name="ic_launcher_background">#FFFFFF</color>
+</resources>
\ No newline at end of file
diff --git a/src-tauri/icons/icon.icns b/src-tauri/icons/icon.icns
index c976f55..b2e5be7 100644
Binary files a/src-tauri/icons/icon.icns and b/src-tauri/icons/icon.icns differ
diff --git a/src-tauri/icons/icon.ico b/src-tauri/icons/icon.ico
index ac731c0..16ffb7b 100644
Binary files a/src-tauri/icons/icon.ico and b/src-tauri/icons/icon.ico differ
diff --git a/src-tauri/icons/icon.png b/src-tauri/icons/icon.png
index f3b167a..cd532b4 100644
Binary files a/src-tauri/icons/icon.png and b/src-tauri/icons/icon.png differ
diff --git a/src-tauri/icons/ios/[email protected] b/src-tauri/icons/ios/[email protected]
new file mode 100644
index 0000000..c064140
Binary files /dev/null and b/src-tauri/icons/ios/[email protected] differ
diff --git a/src-tauri/icons/ios/[email protected] b/src-tauri/icons/ios/[email protected]
new file mode 100644
index 0000000..42a1820
Binary files /dev/null and b/src-tauri/icons/ios/[email protected] differ
diff --git a/src-tauri/icons/ios/[email protected] b/src-tauri/icons/ios/[email protected]
new file mode 100644
index 0000000..42a1820
Binary files /dev/null and b/src-tauri/icons/ios/[email protected] differ
diff --git a/src-tauri/icons/ios/[email protected] b/src-tauri/icons/ios/[email protected]
new file mode 100644
index 0000000..2e5c427
Binary files /dev/null and b/src-tauri/icons/ios/[email protected] differ
diff --git a/src-tauri/icons/ios/[email protected] b/src-tauri/icons/ios/[email protected]
new file mode 100644
index 0000000..fc02213
Binary files /dev/null and b/src-tauri/icons/ios/[email protected] differ
diff --git a/src-tauri/icons/ios/[email protected] b/src-tauri/icons/ios/[email protected]
new file mode 100644
index 0000000..87e0ebb
Binary files /dev/null and b/src-tauri/icons/ios/[email protected] differ
diff --git a/src-tauri/icons/ios/[email protected] b/src-tauri/icons/ios/[email protected]
new file mode 100644
index 0000000..87e0ebb
Binary files /dev/null and b/src-tauri/icons/ios/[email protected] differ
diff --git a/src-tauri/icons/ios/[email protected] b/src-tauri/icons/ios/[email protected]
new file mode 100644
index 0000000..a47a525
Binary files /dev/null and b/src-tauri/icons/ios/[email protected] differ
diff --git a/src-tauri/icons/ios/[email protected] b/src-tauri/icons/ios/[email protected]
new file mode 100644
index 0000000..42a1820
Binary files /dev/null and b/src-tauri/icons/ios/[email protected] differ
diff --git a/src-tauri/icons/ios/[email protected] b/src-tauri/icons/ios/[email protected]
new file mode 100644
index 0000000..18e2fe8
Binary files /dev/null and b/src-tauri/icons/ios/[email protected] differ
diff --git a/src-tauri/icons/ios/[email protected] b/src-tauri/icons/ios/[email protected]
new file mode 100644
index 0000000..18e2fe8
Binary files /dev/null and b/src-tauri/icons/ios/[email protected] differ
diff --git a/src-tauri/icons/ios/[email protected] b/src-tauri/icons/ios/[email protected]
new file mode 100644
index 0000000..c1a4455
Binary files /dev/null and b/src-tauri/icons/ios/[email protected] differ
diff --git a/src-tauri/icons/ios/[email protected] b/src-tauri/icons/ios/[email protected]
new file mode 100644
index 0000000..f006250
Binary files /dev/null and b/src-tauri/icons/ios/[email protected] differ
diff --git a/src-tauri/icons/ios/[email protected] b/src-tauri/icons/ios/[email protected]
new file mode 100644
index 0000000..c1a4455
Binary files /dev/null and b/src-tauri/icons/ios/[email protected] differ
diff --git a/src-tauri/icons/ios/[email protected] b/src-tauri/icons/ios/[email protected]
new file mode 100644
index 0000000..c9de894
Binary files /dev/null and b/src-tauri/icons/ios/[email protected] differ
diff --git a/src-tauri/icons/ios/[email protected] b/src-tauri/icons/ios/[email protected]
new file mode 100644
index 0000000..0b2e2ec
Binary files /dev/null and b/src-tauri/icons/ios/[email protected] differ
diff --git a/src-tauri/icons/ios/[email protected] b/src-tauri/icons/ios/[email protected]
new file mode 100644
index 0000000..b3d2404
Binary files /dev/null and b/src-tauri/icons/ios/[email protected] differ
diff --git a/src-tauri/icons/ios/[email protected] b/src-tauri/icons/ios/[email protected]
new file mode 100644
index 0000000..52d23ce
Binary files /dev/null and b/src-tauri/icons/ios/[email protected] differ
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index b5c05a0..3b4bf48 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -1,4 +1,4 @@
-//! Desktop shell. The UI talks to qls-service over loopback HTTP; this shell only
+//! Desktop shell. The UI talks to kokon-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).
@@ -37,11 +37,15 @@ fn client_id() -> String {
format!("ui-{}", std::process::id())
}
+/// The service's data folder. Until the service has moved the folder of the app's old name
+/// (QwenLocalStudio, renamed Kokon on 2026-10-08) to KokonData, the old one is read.
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")
+ let base = dirs::data_local_dir().unwrap_or_else(std::env::temp_dir);
+ let (new, old) = (base.join("KokonData"), base.join("QwenLocalStudio"));
+ if !new.exists() && old.is_dir() { old } else { new }
}
fn http() -> reqwest::blocking::Client {
@@ -64,7 +68,7 @@ fn ping(port: u16) -> bool {
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"] {
+ for name in ["kokon-service.exe", "kokon-service-x86_64-pc-windows-msvc.exe"] {
let p = dir.join(name);
if p.is_file() {
return Some(p);
@@ -74,7 +78,7 @@ fn service_exe() -> Option<PathBuf> {
}
fn spawn_service() -> Result<(), String> {
- let exe = service_exe().ok_or("qls-service.exe was not found next to the application.")?;
+ let exe = service_exe().ok_or("kokon-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)]
@@ -83,7 +87,7 @@ fn spawn_service() -> Result<(), String> {
// 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}"))?;
+ cmd.spawn().map_err(|e| format!("Could not start the Kokon service: {e}"))?;
Ok(())
}
@@ -104,7 +108,7 @@ fn ensure_service(shared: &Shared) -> Result<ServiceInfo, String> {
return Ok(i);
}
}
- Err("The Qwen Local Studio service did not start. See %LOCALAPPDATA%\\QwenLocalStudio\\logs\\service.log.".into())
+ Err("The Kokon service did not start. See %LOCALAPPDATA%\\KokonData\\logs\\service.log.".into())
}
fn heartbeat(info: &ServiceInfo) -> bool {
@@ -197,6 +201,18 @@ fn open_folder(app: tauri::AppHandle, path: String) -> Result<(), String> {
app.opener().open_path(path, None::<&str>).map_err(|e| e.to_string())
}
+/// Opens a download page or the issue tracker in the browser. Only https links to the hosts
+/// the setup wizard uses are allowed.
+#[tauri::command]
+fn open_link(app: tauri::AppHandle, url: String) -> Result<(), String> {
+ use tauri_plugin_opener::OpenerExt;
+ let allowed = ["https://github.com/", "https://huggingface.co/"];
+ if !allowed.iter().any(|p| url.starts_with(p)) || url.chars().any(|c| c.is_whitespace() || c == '"') {
+ return Err("This link cannot be opened from the app.".into());
+ }
+ app.opener().open_url(url, None::<&str>).map_err(|e| e.to_string())
+}
+
#[tauri::command]
fn data_folder() -> String {
data_dir().to_string_lossy().into_owned()
@@ -227,9 +243,9 @@ pub fn run() {
.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])
+ .invoke_handler(tauri::generate_handler![connect, copy_image, read_clipboard_image, reveal, open_folder, open_link, data_folder])
.build(tauri::generate_context!())
- .expect("error while building Qwen Local Studio");
+ .expect("error while building Kokon");
app.run(move |_handle, event| {
if let RunEvent::Exit = event {
release(&shared);
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 70759a9..aa87a59 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -1,8 +1,9 @@
{
"$schema": "https://schema.tauri.app/config/2",
- "productName": "Qwen Local Studio",
+ "productName": "Kokon",
+ "mainBinaryName": "Kokon",
"version": "1.0.0",
- "identifier": "app.qwenlocalstudio.desktop",
+ "identifier": "app.kokon.desktop",
"build": {
"beforeDevCommand": "npm run dev",
"devUrl": "http://localhost:1420",
@@ -14,7 +15,7 @@
"windows": [
{
"label": "main",
- "title": "Qwen Local Studio",
+ "title": "Kokon",
"width": 1320,
"height": 880,
"minWidth": 880,
@@ -30,14 +31,16 @@
"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.",
+ "publisher": "Kokon",
+ "shortDescription": "Create and edit images by describing them, on your own GPU",
+ "longDescription": "Kokon creates and edits images from a sentence, privately on your own GPU, 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"],
+ "externalBin": ["binaries/kokon-service", "binaries/kokon-mcp"],
"windows": {
"nsis": {
+ "installerIcon": "icons/icon.ico",
+ "uninstallerIcon": "icons/icon.ico",
"installMode": "currentUser",
"displayLanguageSelector": false
}
diff --git a/src/App.tsx b/src/App.tsx
index aab8d38..12baf72 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -1,11 +1,10 @@
import { getCurrentWebview } from "@tauri-apps/api/webview";
-import { Images, Loader2, Settings, SquarePen, X } from "lucide-react";
+import { EyeOff, Loader2, PanelLeft, Redo2, Settings, SquarePen, Undo2, 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,
+ addInputs, dismissToast, getState, newProject, redoVersion, refreshStatus, selectItem, setPrivateMode, setState, startEvents, submitComposer, toastError, toastInfo, undoKey, undoVersion, useStore,
} from "./lib/store";
import { Composer, importPaths } from "./components/Composer";
import { ExpandEditor } from "./components/ExpandEditor";
@@ -13,7 +12,8 @@ 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 { ProjectTitle, Sidebar } from "./components/Sidebar";
+import { Stage } from "./components/Stage";
import { IconButton } from "./components/ui";
const IMAGE_EXT = /\.(png|jpe?g|webp|bmp|gif|tiff?|heic|heif)$/i;
@@ -61,6 +61,37 @@ function StatusIndicator() {
);
}
+/** Undo / Redo between versions: back to the image the current one was made from. */
+function HistoryButtons() {
+ const canUndo = useStore((s) => undoKey(s) !== null);
+ const canRedo = useStore((s) => s.redo.length > 0);
+ if (!canUndo && !canRedo) return null;
+ return (
+ <>
+ <IconButton title="Undo: back to the previous version (Ctrl+Z)" onClick={undoVersion} disabled={!canUndo}>
+ <Undo2 size={18} />
+ </IconButton>
+ <IconButton title="Redo (Ctrl+Y)" onClick={redoVersion} disabled={!canRedo}>
+ <Redo2 size={18} />
+ </IconButton>
+ </>
+ );
+}
+
+function PrivateToggle() {
+ const on = useStore((s) => s.privateMode);
+ const toggle = () => setPrivateMode(!on, () => native.confirm("Turn off private mode? The images made in private mode will be deleted.", "Private mode"));
+ return on ? (
+ <button className="private-pill" onClick={toggle} title="Private mode is on: images are not saved and are deleted when you turn it off or close the app. Click to turn it off.">
+ <EyeOff size={15} /> Private
+ </button>
+ ) : (
+ <IconButton title="Private mode: nothing is saved to the gallery or your Pictures folder" onClick={toggle}>
+ <EyeOff size={18} />
+ </IconButton>
+ );
+}
+
function Toasts() {
const toasts = useStore((s) => s.toasts);
const [open, setOpen] = useState<string | null>(null);
@@ -102,6 +133,8 @@ async function uploadBlobs(files: File[]) {
export default function App() {
const overlay = useStore((s) => s.overlay);
const needsSetup = useStore((s) => s.needsSetup);
+ const sidebar = useStore((s) => s.sidebar);
+ const editing = useStore((s) => s.composer.refs.length > 0 && s.session.length > 0);
const [boot, setBoot] = useState<"connecting" | "ok" | string>("connecting");
const [dragging, setDragging] = useState(false);
@@ -183,11 +216,23 @@ export default function App() {
return;
}
if (typing) return;
+ // Undo / Redo between versions (the brush editor has its own while it is open).
+ if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "z") {
+ e.preventDefault();
+ if (e.shiftKey) redoVersion();
+ else undoVersion();
+ return;
+ }
+ if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "y") {
+ e.preventDefault();
+ redoVersion();
+ 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 });
+ if (n) selectItem(n.key);
}
};
window.addEventListener("keydown", onKey);
@@ -214,43 +259,40 @@ export default function App() {
return (
<div className="app">
- <div className="topbar">
- <div className="brand">
- <StatusIndicator />
+ {sidebar && !needsSetup && <Sidebar />}
+ <div className="workspace">
+ <div className="topbar">
+ <div className="brand">
+ {!sidebar && !needsSetup && (
+ <>
+ <IconButton title="Show sidebar" onClick={() => setState({ sidebar: true })}>
+ <PanelLeft size={18} />
+ </IconButton>
+ <IconButton title="New image" onClick={newProject}>
+ <SquarePen size={18} />
+ </IconButton>
+ </>
+ )}
+ {overlay === "gallery" ? <span className="project-title">All images</span> : !needsSetup && <ProjectTitle />}
+ </div>
+ <div className="toolbar">
+ {!needsSetup && <HistoryButtons />}
+ {!needsSetup && <PrivateToggle />}
+ <StatusIndicator />
+ <IconButton title="Settings" onClick={() => setState({ overlay: "settings" })}>
+ <Settings size={18} />
+ </IconButton>
+ </div>
</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 className="main">
+ {needsSetup ? <Setup /> : <Stage />}
+ {overlay === "gallery" && <Gallery />}
+ {overlay === "inpaint" && <InpaintEditor />}
+ {overlay === "expand" && <ExpandEditor />}
+ {dragging && <div className="drop-hint">{editing ? "Drop to add as a reference image" : "Drop an image to start editing it"}</div>}
</div>
+ {!needsSetup && overlay !== "inpaint" && overlay !== "expand" && overlay !== "gallery" && <Composer />}
</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/Composer.tsx b/src/components/Composer.tsx
index a20ca59..736674c 100644
--- a/src/components/Composer.tsx
+++ b/src/components/Composer.tsx
@@ -1,26 +1,14 @@
-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 { ArrowUp, Brush, ChevronDown, Expand, FolderOpen, Gauge, ImagePlus, RectangleHorizontal, RectangleVertical, SlidersHorizontal, Sparkles, Square, X } from "lucide-react";
+import { useEffect, useMemo, 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 { activeOverrides, buildRequest, expansionPixels, formatDuration, hasOutpaint, moveRef, needsPrompt, versionLabels, 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 {
+ addAsReference, addInputs, getState, itemSource, selectedItem, selectItem, setState, submitComposer, toastError, updateComposer, useStore, type SessionItem,
+} from "../lib/store";
+import type { InpaintAction, 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} />,
-};
+import { Option, Popover, Seg } from "./ui";
const QUALITY: { value: Quality; label: string; sub: string }[] = [
{ value: "fast", label: "Fast", sub: "~1 MP, 20 steps" },
@@ -28,6 +16,15 @@ const QUALITY: { value: Quality; label: string; sub: string }[] = [
{ value: "quality", label: "Quality", sub: "native 2K, 40 steps · slower" },
];
+const INPAINT_ACTIONS: { value: InpaintAction; label: string; placeholder: string }[] = [
+ { value: "edit", label: "Change", placeholder: "Describe the change in the painted area…" },
+ { value: "remove", label: "Remove", placeholder: "What to remove (optional)…" },
+ { value: "replace", label: "Replace", placeholder: "What to put there instead…" },
+ { value: "add", label: "Add", placeholder: "What to add in the painted area…" },
+];
+
+const INPAINT_VERB: Record<InpaintAction, string> = { edit: "Changing", remove: "Clearing", replace: "Replacing", add: "Adding to" };
+
const ASPECT_ICON: Record<string, React.ReactNode> = {
"1:1": <Square size={15} />,
"4:3": <RectangleHorizontal size={15} />,
@@ -48,9 +45,24 @@ export async function importPaths(paths: string[]) {
addInputs(recs);
}
+/** Version name of a reference when it is part of the project ("v2", "Original"). */
+function useRefNames() {
+ const session = useStore((s) => s.session);
+ return useMemo(() => {
+ const labels = versionLabels(session);
+ const bySource = new Map<string, string>();
+ for (const i of session) {
+ const s = itemSource(i);
+ if (s) bySource.set(s, labels[i.key]);
+ }
+ return (r: Ref) => bySource.get(r.source) ?? null;
+ }, [session]);
+}
+
+/** Thumbnails of the images the prompt works on; drag to reorder when there are several. */
function RefStrip() {
const refs = useStore((s) => s.composer.refs);
- const mask = useStore((s) => s.composer.mask);
+ const nameOf = useRefNames();
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);
@@ -64,7 +76,6 @@ function RefStrip() {
return els.length;
};
- if (!refs.length) return null;
return (
<div
className="refs"
@@ -77,7 +88,7 @@ function RefStrip() {
onPointerUp={() => {
if (drag?.active) {
const to = drag.to > drag.from ? drag.to - 1 : drag.to;
- updateComposer({ refs: moveRef(getState().composer.refs, drag.from, to) });
+ updateComposer({ refs: moveRef(getState().composer.refs, drag.from, to), mask: null, outpaint: null });
}
start.current = null;
setDrag(null);
@@ -91,30 +102,25 @@ function RefStrip() {
<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" : ""}`}
+ title={`${refs.length > 1 ? `Image ${i + 1}: ` : ""}${nameOf(r) ?? r.name} · ${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} />
+ <img src={urls.sourceThumb(r.source)} 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 });
+ updateComposer({ refs: c.refs.filter((x) => x.key !== r.key), mask: i === 0 ? null : c.mask, outpaint: i === 0 ? null : c.outpaint });
}}
>
- <X size={12} />
+ <X size={11} />
</button>
</div>
))}
@@ -122,6 +128,135 @@ function RefStrip() {
);
}
+/** Says, in words, what the prompt is going to do, and offers the tools for that image. */
+function TargetBar() {
+ const c = useStore((s) => s.composer);
+ const sel = useStore(selectedItem);
+ const session = useStore((s) => s.session);
+ const nameOf = useRefNames();
+
+ if (!c.refs.length) {
+ const img = sel && (sel.gen || sel.input) ? sel : [...session].reverse().find((i) => i.gen || i.input);
+ if (!img) return null;
+ return (
+ <div className="target create">
+ <span className="target-icon">
+ <Sparkles size={15} />
+ </span>
+ <span className="target-text">
+ <span className="what">New image</span>
+ <span className="sub">Made from the prompt alone</span>
+ </span>
+ <span className="spacer" />
+ <button className="tool" onClick={() => selectItem(img.key)}>
+ Edit {versionLabels(session)[img.key]} instead
+ </button>
+ </div>
+ );
+ }
+
+ const first = c.refs[0];
+ const name = nameOf(first) ?? (first.source.startsWith("gen:") ? "this result" : first.name);
+ const outPx = hasOutpaint(c.outpaint) ? expansionPixels(c.outpaint!, first.width, first.height) : null;
+ const what =
+ c.refs.length > 1 ? `Combining ${c.refs.length} images` : c.mask ? `${INPAINT_VERB[c.inpaintAction]} the painted area of ${name}` : outPx ? `Expanding ${name}` : `Editing ${name}`;
+ const sub =
+ c.refs.length > 1
+ ? "Refer to them as image 1, image 2… in the prompt"
+ : outPx
+ ? `${first.width}×${first.height} → ${first.width + outPx.left + outPx.right}×${first.height + outPx.top + outPx.bottom}`
+ : `${first.width}×${first.height}`;
+
+ return (
+ <div className="target">
+ <RefStrip />
+ <span className="target-text">
+ <span className="what">{what}</span>
+ <span className="sub">{sub}</span>
+ </span>
+ <span className="spacer" />
+ <span className="tool-group">
+ <button className={`tool ${c.mask ? "on" : ""}`} onClick={() => setState({ overlay: "inpaint" })} title="Paint the area to change; the rest stays as it is">
+ <Brush size={14} /> {c.mask ? "Area painted" : "Paint area"}
+ </button>
+ {c.mask && (
+ <button className="tool-x" title="Remove the painted area" onClick={() => updateComposer({ mask: null })}>
+ <X size={13} />
+ </button>
+ )}
+ </span>
+ <span className="tool-group">
+ <button className={`tool ${outPx ? "on" : ""}`} onClick={() => setState({ overlay: "expand" })} title="Extend the image beyond its borders">
+ <Expand size={14} /> {outPx ? "Expanded" : "Expand"}
+ </button>
+ {outPx && (
+ <button className="tool-x" title="Remove the expansion" onClick={() => updateComposer({ outpaint: null })}>
+ <X size={13} />
+ </button>
+ )}
+ </span>
+ <button className="tool" title="Create a new image from the prompt instead" onClick={() => updateComposer({ refs: [], mask: null, outpaint: null })}>
+ New image
+ </button>
+ </div>
+ );
+}
+
+/** Adds a reference: a version from this project, or files. */
+function AddImage() {
+ const session = useStore((s) => s.session);
+ const refs = useStore((s) => s.composer.refs);
+ const labels = useMemo(() => versionLabels(session), [session]);
+ const used = new Set(refs.map((r) => r.source));
+ const candidates = session.filter((i) => {
+ const s = itemSource(i);
+ return s && !used.has(s);
+ });
+ const browse = async () => importPaths(await native.pickImages());
+ const title = refs.length ? "Add a reference image" : "Add an image to edit";
+
+ if (!candidates.length) {
+ return (
+ <button className="icon-btn" title={`${title} (or drop / paste)`} aria-label={title} onClick={browse}>
+ <ImagePlus size={19} />
+ </button>
+ );
+ }
+ return (
+ <Popover
+ placement="top-start"
+ trigger={(open, toggle) => (
+ <button className={`icon-btn ${open ? "active" : ""}`} title={title} aria-label={title} onClick={toggle}>
+ <ImagePlus size={19} />
+ </button>
+ )}
+ >
+ {(close) => (
+ <div className="add-menu">
+ <div className="label">{refs.length ? "Add a version as reference" : "Edit a version"}</div>
+ <div className="add-grid">
+ {candidates.map((it: SessionItem) => (
+ <button key={it.key} title={it.gen?.prompt ?? labels[it.key]} onClick={() => (addAsReference(it), close())}>
+ <img src={urls.sourceThumb(itemSource(it)!)} alt="" draggable={false} />
+ <span>{labels[it.key]}</span>
+ </button>
+ ))}
+ </div>
+ <button className="opt" onClick={() => (close(), browse())}>
+ <span className="check">
+ <FolderOpen size={15} />
+ </span>
+ <span>Browse files…</span>
+ </button>
+ <div className="muted" style={{ padding: "2px 10px 6px" }}>
+ You can also drop or paste images.
+ </div>
+ </div>
+ )}
+ </Popover>
+ );
+}
+
function usePlanPreview(): { plan: Plan | null; error: string | null } {
const c = useStore((s) => s.composer);
const connected = useStore((s) => s.connected);
@@ -141,12 +276,13 @@ function usePlanPreview(): { plan: Plan | null; error: string | null } {
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]);
+ }, [connected, c.prompt, c.refs, c.mode, c.quality, c.resolution, c.aspect, c.outpaint, c.mask, c.inpaintAction, c.customWidth, c.customHeight, c.advanced]);
return res;
}
export function Composer() {
const c = useStore((s) => s.composer);
+ const hasProject = useStore((s) => s.session.length > 0);
const { plan, error } = usePlanPreview();
const taRef = useRef<HTMLTextAreaElement>(null);
const hasImages = c.refs.length > 0;
@@ -159,69 +295,40 @@ export function Composer() {
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…"
+ ? hasProject
+ ? "Describe a new image…"
+ : "Describe an image to create, or drop one in to edit it…"
: c.refs.length > 1
? "Describe how to combine image 1, image 2…"
: c.mask
- ? "Describe what goes in the painted area…"
+ ? INPAINT_ACTIONS.find((a) => a.value === c.inpaintAction)!.placeholder
: 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 `${plan.output.width}×${plan.output.height} · ~${formatDuration(plan.estimated_seconds)}`;
})();
+ const hintTitle = plan
+ ? [
+ plan.working.width !== plan.output.width || plan.working.height !== plan.output.height ? `Works at ${plan.working.width}×${plan.working.height}` : "",
+ plan.optimized_for_vram ? "Optimized for VRAM" : "",
+ ...plan.notes,
+ ]
+ .filter(Boolean)
+ .join("\n")
+ : "";
+ const shaped = c.resolution !== "custom" && !c.mask && !outPx;
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>
- )}
+ <TargetBar />
<textarea
id="prompt"
ref={taRef}
@@ -234,71 +341,29 @@ export function Composer() {
if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) {
e.preventDefault();
submitComposer();
+ } else if (e.key === "ArrowUp" && !c.prompt) {
+ const last = getState().lastPrompt;
+ if (last) {
+ e.preventDefault();
+ updateComposer({ prompt: last });
+ }
}
}}
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>
+ <AddImage />
- <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.mask && (
+ <Seg value={c.inpaintAction} options={INPAINT_ACTIONS} onChange={(v) => updateComposer({ inpaintAction: v })} />
+ )}
- {c.resolution !== "custom" && !c.mask && !outPx && (!hasImages || modeShown === "generate" || modeShown === "edit" || modeShown === "multi_reference" || modeShown === "auto") && (
+ {shaped && (
<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}
+ {c.aspect === "auto" ? (plan ? plan.aspect_label : "Auto") : c.aspect}
<ChevronDown size={13} />
</button>
)}
@@ -306,7 +371,7 @@ export function Composer() {
{(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 key={a} selected={c.aspect === a} label={a === "auto" ? "Auto" : a} sub={a === "auto" ? (hasImages ? "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())} />
</>
@@ -347,10 +412,10 @@ export function Composer() {
</Popover>
<span className="spacer" />
- <span className="plan-hint" title={plan?.notes.join("\n") || plan?.mode_reason || ""}>
+ <span className="plan-hint" title={hintTitle}>
{hint}
</span>
- <button className="send" title="Generate (Enter)" aria-label="Generate" disabled={!c.prompt.trim()} onClick={() => submitComposer()}>
+ <button className="send" title={hasImages ? "Apply (Enter)" : "Create (Enter)"} aria-label="Generate" disabled={!c.prompt.trim() && needsPrompt(c)} onClick={() => submitComposer()}>
<ArrowUp size={18} strokeWidth={2.4} />
</button>
</div>
diff --git a/src/components/Gallery.tsx b/src/components/Gallery.tsx
index eba5632..4e5562d 100644
--- a/src/components/Gallery.tsx
+++ b/src/components/Gallery.tsx
@@ -1,9 +1,8 @@
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 { forgetGeneration, openGeneration, setState, toastError, useStore } from "../lib/store";
import type { GenerationRecord } from "../lib/types";
import { IconButton, Seg } from "./ui";
@@ -46,17 +45,7 @@ export function Gallery() {
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 reopen = (g: GenerationRecord) => openGeneration(g).catch(toastError);
const toggleFav = async (g: GenerationRecord) => {
try {
@@ -72,7 +61,7 @@ export function Gallery() {
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) }));
+ forgetGeneration(g.id);
} catch (e) {
toastError(e);
}
diff --git a/src/components/Settings.tsx b/src/components/Settings.tsx
index e1bbb2f..dea89cb 100644
--- a/src/components/Settings.tsx
+++ b/src/components/Settings.tsx
@@ -1,4 +1,4 @@
-import { Activity, Copy, Cpu, FolderOpen, HardDrive, RefreshCw, RotateCcw, Settings2, X } from "lucide-react";
+import { Activity, Copy, Cpu, Download, 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";
@@ -10,17 +10,6 @@ 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">
@@ -187,11 +176,32 @@ export function Settings() {
{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
+ className="btn"
+ style={{ alignSelf: "flex-start" }}
+ onClick={() => {
+ if (dirty && !window.confirm("Discard the unsaved changes and open the model setup?")) return;
+ setState({ overlay: null, needsSetup: true });
+ }}
+ >
+ <Download size={14} /> Set up models…
</button>
- <span className="muted">Profile: {profile.displayName}</span>
+ <span className="muted" style={{ marginTop: -10 }}>Downloads the official Qwen-Image 2.1 weights for your graphics card, or switches between the 12, 16, 24 and 32 GB presets.</span>
+ <PathField label="stable-diffusion.cpp folder" value={cfg.sdcppDir} folder onChange={(v) => set({ sdcppDir: v })} />
+ {cfg.profiles.length > 1 ? (
+ <label className="field-row">
+ <span>Model</span>
+ <select className="select" value={profile.id} onChange={(e) => set({ activeProfile: e.target.value })}>
+ {cfg.profiles.map((p) => (
+ <option key={p.id} value={p.id}>
+ {p.displayName}
+ </option>
+ ))}
+ </select>
+ </label>
+ ) : (
+ <span className="muted">Model: {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 })} />
@@ -297,6 +307,13 @@ export function Settings() {
<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>Simulated VRAM for testing (MiB, 0 = detect)</span>
+ <input className="input" type="number" min={0} max={196608} step={1024} style={{ width: 100 }} value={cfg.vramOverrideMib} onChange={(e) => set({ vramOverrideMib: Math.max(0, Math.round(Number(e.target.value) || 0)) })} />
+ </label>
+ <span className="muted" style={{ marginTop: -10 }}>
+ Plans image sizes as if the card had this much memory (e.g. 12288 to test a 12 GB card). Combine with the VRAM ballast script in scripts/dev so the memory is really unavailable.
+ </span>
<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 })} />
diff --git a/src/components/Setup.tsx b/src/components/Setup.tsx
index d502152..c9fefda 100644
--- a/src/components/Setup.tsx
+++ b/src/components/Setup.tsx
@@ -1,20 +1,91 @@
-import { Check, CircleAlert, FolderOpen, Info, Loader2, RefreshCw, Settings2 } from "lucide-react";
-import { useEffect, useState } from "react";
+import { Bug, Check, ChevronDown, CircleAlert, Download, ExternalLink, FolderOpen, Info, Loader2, Pause, Play, RefreshCw, Settings2 } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
import { api } from "../lib/api";
+import { formatBytes, installItemShort, installProgress, installStep, installTimeLeft } from "../lib/logic";
import { native } from "../lib/native";
-import { refreshStatus, setState, toastError } from "../lib/store";
-import type { SetupReport } from "../lib/types";
-import { defaultProfilePaths } from "./Settings";
+import { refreshStatus, setState, toastError, useStore } from "../lib/store";
+import type { HardwareReport, InstallItem, InstallStatus, SetupReport } from "../lib/types";
+import { Seg, Switch } from "./ui";
-/** First launch: verify folder, executable, the four model files and CUDA. */
+const gb = (mib: number) => `${Math.round(mib / 1024)} GB`;
+
+function ItemIcon({ it }: { it: InstallItem }) {
+ switch (it.state) {
+ case "present":
+ case "done":
+ return <Check size={16} />;
+ case "failed":
+ return it.kind === "optional" ? <Info size={16} /> : <CircleAlert size={16} />;
+ case "downloading":
+ case "verifying":
+ case "extracting":
+ return <Loader2 className="spin" size={16} />;
+ default:
+ return <Download size={16} style={{ opacity: 0.4 }} />;
+ }
+}
+
+/** A file that could not be downloaded: what happened and how to get it by hand. */
+function Failure({ it, issuesUrl }: { it: InstallItem; issuesUrl: string }) {
+ const folder = it.kind === "engine" ? it.path : it.path.replace(/[\\/][^\\/]+$/, "");
+ return (
+ <div className="setup-failure">
+ <strong>{it.label}</strong>
+ <span>{it.error}</span>
+ <span>{it.hint}</span>
+ <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
+ <button className="btn" onClick={() => native.openLink(it.page).catch(toastError)}>
+ <ExternalLink size={14} /> Download page
+ </button>
+ <button className="btn" onClick={() => native.openFolder(folder).catch(toastError)}>
+ <FolderOpen size={14} /> Open folder
+ </button>
+ <button className="btn" onClick={() => native.openLink(issuesUrl).catch(toastError)}>
+ <Bug size={14} /> Report the problem
+ </button>
+ </div>
+ </div>
+ );
+}
+
+function FileList({ items }: { items: InstallItem[] }) {
+ return (
+ <div className="setup-files">
+ {items.map((it) => (
+ <div className={`setup-file ${it.state}`} key={it.id}>
+ <ItemIcon it={it} />
+ <span className="name">
+ {it.label}
+ {it.kind === "optional" ? <span className="muted"> · optional</span> : null}
+ </span>
+ <span className="state">{installItemShort(it)}</span>
+ </div>
+ ))}
+ </div>
+ );
+}
+
+/** First launch (and Settings → Models → Set up models): detect the GPU, pick a preset,
+ * download stable-diffusion.cpp and the official Qwen-Image 2.1 weights, then start. */
export function Setup() {
+ const [hw, setHw] = useState<HardwareReport | null>(null);
const [report, setReport] = useState<SetupReport | null>(null);
+ const [inst, setInst] = useState<InstallStatus | null>(null);
+ const [preset, setPreset] = useState<string | null>(null);
+ const [upscaler, setUpscaler] = useState(true);
+ const [showFiles, setShowFiles] = useState(false);
const [checking, setChecking] = useState(false);
+ const wasRunning = useRef(false);
+ const setupDone = useStore((s) => s.status?.setup_complete ?? false);
- const run = async () => {
+ const refresh = async () => {
setChecking(true);
try {
- setReport(await api.setup());
+ const [h, r, i] = await Promise.all([api.hardware(), api.setup(), api.installStatus()]);
+ setHw(h);
+ setReport(r);
+ setInst(i);
+ setPreset((p) => p ?? (i.running && i.preset ? i.preset : h.recommended));
} catch (e) {
toastError(e);
} finally {
@@ -22,17 +93,39 @@ export function Setup() {
}
};
useEffect(() => {
- run();
+ refresh();
}, []);
+ // Follow a running installation; re-check everything once it ends.
+ useEffect(() => {
+ if (!inst?.running) {
+ if (wasRunning.current) {
+ wasRunning.current = false;
+ refresh();
+ }
+ return;
+ }
+ wasRunning.current = true;
+ const t = window.setInterval(() => api.installStatus().then(setInst, () => {}), 500);
+ return () => window.clearInterval(t);
+ }, [inst?.running]);
+
const chooseFolder = async () => {
- const dir = await native.pickFolder("C:\\AI\\sdcpp");
+ const dir = await native.pickFolder(hw?.sdcpp_dir);
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();
+ await api.saveConfig({ ...cfg, sdcppDir: dir });
+ refresh();
+ } catch (e) {
+ toastError(e);
+ }
+ };
+
+ const install = async () => {
+ if (!preset) return;
+ try {
+ setInst(await api.install(preset, upscaler));
} catch (e) {
toastError(e);
}
@@ -51,45 +144,194 @@ export function Setup() {
}
};
+ const chosen = hw?.presets.find((p) => p.id === preset) ?? null;
+ const running = inst?.running ?? false;
+ // While (or after) installing this preset, show the live list; otherwise what is on disk.
+ const live = !!inst && inst.preset === preset && inst.items.length > 0 && (running || inst.items.some((i) => i.state !== "pending" && i.state !== "present"));
+ const items = (live ? inst!.items : chosen?.files ?? []).filter((i) => upscaler || i.kind !== "optional" || live);
+ const missing = items.filter((i) => i.state !== "present" && i.state !== "done");
+ const failed = items.filter((i) => i.state === "failed");
+ const paused = !running && items.some((i) => i.state === "cancelled" || (i.state === "pending" && i.received > 0));
+ const toDownload = missing.reduce((a, i) => a + Math.max(0, i.size - i.received), 0);
+ const prog = installProgress(items);
+ const lowSpace = hw?.free_bytes != null && chosen != null && hw.free_bytes < chosen.disk_bytes;
+ const presetInstalled = missing.filter((i) => i.kind !== "optional").length === 0;
+ const ready = !!report?.ready && !running;
+ const rate = inst?.bytes_per_sec ?? 0;
+ const vram = hw?.vram_mib ?? null;
+ const optionalMissing = chosen?.files.some((f) => f.kind === "optional" && f.state !== "present");
+
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>
+ <h1>{setupDone ? "Models" : "Welcome to Kokon"}</h1>
+ <p className="setup-lead">
+ Everything runs on this PC. Setup downloads the image model once ({chosen ? formatBytes(chosen.files.reduce((a, f) => a + f.size, 0)) : "about 12 GB"}); after that, nothing
+ leaves your computer.
+ </p>
+ </div>
+
+ {!hw ? (
+ <div className="setup-card">
+ <Loader2 className="spin" size={18} /> Checking this PC…
+ </div>
+ ) : (
+ <>
+ <div className="setup-card setup-gpu">
+ <strong>{hw.gpu ? hw.gpu.name : "No NVIDIA GPU found"}</strong>
+ <span className="muted">
+ {vram ? `${gb(vram)} VRAM${hw.vram_simulated ? " (simulated)" : ""} · ` : ""}
+ {gb(hw.ram_total_mib)} RAM{hw.gpu ? ` · driver ${hw.gpu.driver_version}` : ""}
+ </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>
+ {!hw.nvidia && (
+ <div className="setup-note">
+ This version needs an NVIDIA GPU (RTX 20 series or newer) with at least 12 GB of VRAM and a recent driver. Support for AMD and Intel cards (Vulkan) is planned.
+ </div>
+ )}
+ {vram !== null && vram < 11 * 1024 && <div className="setup-note">Your GPU has {gb(vram)} of VRAM. 12 GB is the smallest size this app is made for; it may fail or run slowly.</div>}
+ {hw.ram_total_mib < 15 * 1024 && <div className="setup-note">The text encoder runs from system RAM; with {gb(hw.ram_total_mib)} of RAM, 16 GB or more is recommended.</div>}
+
+ {running || paused ? (
+ <div className="muted">
+ {chosen?.label} preset · {hw.sdcpp_dir}
+ </div>
+ ) : (
+ <>
+ <div className="field">
+ <span>Preset for your graphics card</span>
+ <Seg<string> value={preset ?? hw.recommended} options={hw.presets.map((p) => ({ value: p.id, label: p.label }))} onChange={setPreset} />
+ {chosen && (
+ <span className="muted">
+ {chosen.summary}.{chosen.id === hw.recommended ? " Recommended for your GPU." : ""}
+ {chosen.verified ? "" : " Not yet tested on a real card of this size."}
+ </span>
+ )}
+ </div>
+ <div className="field">
+ <span>Install folder</span>
+ <div className="path-row">
+ <input className="input" type="text" value={hw.sdcpp_dir} readOnly spellCheck={false} />
+ <button className="btn" onClick={chooseFolder}>
+ Change
+ </button>
+ </div>
+ <span className="muted">
+ {hw.free_bytes != null ? `${formatBytes(hw.free_bytes)} free` : ""}
+ {chosen && chosen.disk_bytes > 0 ? ` · needs about ${formatBytes(chosen.disk_bytes)}` : ""}
+ {lowSpace ? " — not enough space on this drive; choose another folder." : ""}
+ </span>
+ </div>
+ </>
+ )}
+
+ {/* Progress panel while installing or paused. */}
+ {(running || paused) && (
+ <div className="setup-card setup-progress">
+ <div className="setup-progress-head">
+ <span className="pct">{Math.floor(prog.frac * 100)}%</span>
+ <span className="muted">
+ {formatBytes(prog.received)} of {formatBytes(prog.total)}
+ {running && rate > 0 ? ` · ${formatBytes(rate)}/s` : ""}
+ {running ? (installTimeLeft(prog.total - prog.received, rate) ? ` · ${installTimeLeft(prog.total - prog.received, rate)}` : "") : " · paused"}
+ </span>
+ </div>
+ <div className="progress thick">
+ <i style={{ width: `${prog.frac * 100}%` }} />
+ </div>
+ <span className="muted">{running ? installStep(items) ?? "Starting…" : "Downloads continue where they stopped, also after closing the app."}</span>
+ <div>
+ {running ? (
+ <button className="btn" onClick={() => api.cancelInstall().then(setInst, toastError)}>
+ <Pause size={14} /> Pause
+ </button>
+ ) : (
+ <button className="btn primary" onClick={install} disabled={lowSpace}>
+ <Play size={14} /> Resume
+ </button>
+ )}
+ </div>
</div>
+ )}
+
+ {failed.length > 0 && !running && (
+ <div className="setup-note">
+ <div style={{ marginBottom: 8 }}>
+ {failed.length === 1 ? "One file" : `${failed.length} files`} could not be downloaded. Try again, or get {failed.length === 1 ? "it" : "them"} by hand and press Check again.
+ Please report a broken link so it can be fixed for everyone.
+ </div>
+ {failed.map((it) => (
+ <Failure key={it.id} it={it} issuesUrl={hw.issues_url} />
+ ))}
+ </div>
+ )}
+
+ {presetInstalled && !running && (
+ <div className="setup-card setup-ready">
+ <Check size={18} />
+ <span>{hw.current === chosen?.id || !chosen ? "Everything is installed." : `The ${chosen.label} files are already here.`}</span>
+ </div>
+ )}
+
+ {/* What gets installed. */}
+ <div className="field">
+ <button className="setup-toggle" onClick={() => setShowFiles((v) => !v)} aria-expanded={showFiles || running}>
+ <ChevronDown size={14} style={{ transform: showFiles || running ? "none" : "rotate(-90deg)", transition: "transform 0.15s" }} />
+ {items.length} files · {missing.length ? `${formatBytes(toDownload)} to download` : "all installed"}
+ </button>
+ {(showFiles || running) && <FileList items={items} />}
+ {optionalMissing && !running && !paused && (
+ <div className="field-row" style={{ paddingTop: 4 }}>
+ <span>Include the 4x-UltraSharp upscaler for sharper enlargements (67 MB, CC BY-NC-SA 4.0, non-commercial)</span>
+ <Switch on={upscaler} onChange={setUpscaler} label="Include the upscaler" />
+ </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
+ </>
+ )}
+
+ <div className="setup-actions">
+ {hw && !running && !paused && !presetInstalled && (
+ <button className="btn primary big" disabled={!chosen || lowSpace} onClick={install}>
+ <Download size={16} /> {failed.length ? "Try again" : `Install · ${formatBytes(toDownload)}`}
+ </button>
+ )}
+ {hw && presetInstalled && !running && chosen && hw.current !== chosen.id && (
+ // Files of another preset are already here: switch to it without downloading.
+ <button className="btn" onClick={install}>
+ Use the {chosen.label} preset
+ </button>
+ )}
+ {(ready || presetInstalled) && !running && (
+ <button className={`btn big ${presetInstalled ? "primary" : ""}`} disabled={!ready} onClick={start}>
+ {setupDone ? "Done" : "Start"}
+ </button>
+ )}
+ <span style={{ flex: 1 }} />
+ <button className="btn ghost" onClick={() => setState({ overlay: "settings" })} disabled={running}>
+ <Settings2 size={14} /> Settings
</button>
- <button className="btn" onClick={run} disabled={checking}>
- <RefreshCw size={15} /> Check again
+ <button className="btn ghost" onClick={refresh} disabled={checking || running}>
+ <RefreshCw size={14} /> 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>}
+
+ {report && !report.ready && !running && !paused && missing.length === 0 && (
+ <div className="setup-note">
+ {report.checks
+ .filter((c) => !c.ok && c.id !== "upscaler")
+ .map((c, i) => (
+ <div key={i}>
+ <strong>{c.label}</strong>: {c.detail}
+ </div>
+ ))}
+ </div>
+ )}
+ <p className="muted setup-foot">
+ Qwen-Image 2.1 and Qwen3-VL are released by Alibaba's Qwen team under their own licenses; check them before commercial use. Downloads come only from GitHub
+ (stable-diffusion.cpp) and Hugging Face, and every file is verified with its SHA-256 checksum.
+ </p>
</div>
</div>
);
diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsx
new file mode 100644
index 0000000..820cbf8
--- /dev/null
+++ b/src/components/Sidebar.tsx
@@ -0,0 +1,102 @@
+import { Images, PanelLeftClose, Pencil, SquarePen, X } from "lucide-react";
+import { useState } from "react";
+import { urls } from "../lib/api";
+import { timeAgo } from "../lib/logic";
+import { deleteProject, newProject, renameProject, setState, switchProject, useStore } from "../lib/store";
+import { IconButton, NameField } from "./ui";
+
+/** Navigation: start something new, browse every image, or go back to a project. */
+export function Sidebar() {
+ const projects = useStore((s) => s.projects);
+ const current = useStore((s) => s.projectId);
+ const empty = useStore((s) => s.session.length === 0);
+ const overlay = useStore((s) => s.overlay);
+ const gallery = overlay === "gallery";
+ const [renaming, setRenaming] = useState<string | null>(null);
+
+ return (
+ <aside className="sidebar">
+ <div className="side-head">
+ <IconButton title="Hide sidebar" onClick={() => setState({ sidebar: false })}>
+ <PanelLeftClose size={18} />
+ </IconButton>
+ </div>
+ <nav className="side-nav">
+ <button className={`side-item ${empty && !gallery ? "on" : ""}`} onClick={newProject}>
+ <SquarePen size={16} /> New image
+ </button>
+ <button className={`side-item ${gallery ? "on" : ""}`} onClick={() => setState({ overlay: gallery ? null : "gallery" })}>
+ <Images size={16} /> All images
+ </button>
+ </nav>
+ {projects.length > 0 && <div className="side-label">Projects</div>}
+ <div className="side-list">
+ {projects.map((p) => (
+ <div
+ key={p.id}
+ role="button"
+ tabIndex={0}
+ className={`proj ${p.id === current && !gallery ? "on" : ""}`}
+ onClick={() => switchProject(p.id)}
+ onDoubleClick={() => setRenaming(p.id)}
+ onKeyDown={(e) => {
+ if (e.target !== e.currentTarget) return;
+ if (e.key === "Enter" || e.key === " ") switchProject(p.id);
+ else if (e.key === "F2") setRenaming(p.id);
+ }}
+ title={`${p.title}
+Double-click or F2 to rename`}
+ >
+ <span className="cover">{p.cover && <img src={urls.sourceThumb(p.cover)} alt="" draggable={false} loading="lazy" />}</span>
+ <span className="proj-text">
+ {renaming === p.id ? (
+ <NameField value={p.named ? p.title : ""} onSave={(v) => renameProject(p.id, v)} onDone={() => setRenaming(null)} />
+ ) : (
+ <span className="proj-title">{p.title}</span>
+ )}
+ <span className="proj-sub">
+ {p.count} {p.count === 1 ? "version" : "versions"} · {timeAgo(p.updatedAt)}
+ </span>
+ </span>
+ <button
+ className="proj-rm"
+ title="Rename"
+ aria-label="Rename project"
+ onClick={(e) => {
+ e.stopPropagation();
+ setRenaming(p.id);
+ }}
+ >
+ <Pencil size={13} />
+ </button>
+ <button
+ className="proj-rm"
+ title="Remove from list (images stay in All images)"
+ aria-label="Remove project"
+ onClick={(e) => {
+ e.stopPropagation();
+ deleteProject(p.id);
+ }}
+ >
+ <X size={14} />
+ </button>
+ </div>
+ ))}
+ </div>
+ </aside>
+ );
+}
+
+/** The open project's name in the top bar; click to rename (also before the first image). */
+export function ProjectTitle() {
+ const id = useStore((s) => s.projectId);
+ const meta = useStore((s) => s.projects.find((p) => p.id === s.projectId));
+ const [editing, setEditing] = useState(false);
+ if (editing) return <NameField className="title-field" value={meta?.named ? meta.title : ""} onSave={(v) => renameProject(id, v)} onDone={() => setEditing(false)} />;
+ return (
+ <button className={`project-title ${meta ? "" : "placeholder"}`} title="Rename project" onClick={() => setEditing(true)}>
+ {meta?.title ?? "Untitled project"}
+ <Pencil size={13} className="title-pencil" />
+ </button>
+ );
+}
diff --git a/src/components/Stage.tsx b/src/components/Stage.tsx
index 843b8e0..a8ea2a0 100644
--- a/src/components/Stage.tsx
+++ b/src/components/Stage.tsx
@@ -1,26 +1,46 @@
import {
- Brush, Copy, Download, Expand, FolderOpen, Heart, ImagePlus, Info, Loader2, MousePointerClick, Pencil, RotateCcw, Shuffle, Square, X, ClipboardPaste, ZoomIn,
+ Brush, ClipboardPaste, Combine, Copy, Download, Ellipsis, Expand, FolderOpen, Heart, Info, Loader2, MousePointerClick, Pencil, RotateCcw, Shuffle, Square, TextCursorInput, Trash2, Wand2, X, ZoomIn,
} from "lucide-react";
-import { Fragment, useState } from "react";
+import { Fragment, useEffect, useMemo, useRef, 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,
+ compareBase, composerFromRecord, formatDuration, jobFraction, jobLabel, MAX_UPSCALE_AREA, MAX_UPSCALE_SIDE, MODE_LABEL, pipelineSummary, remainingSeconds, sizeForWidth, upscaleRequest, upscalerLabel,
+ upscaleTargets, variationRequest, versionLabels,
} from "../lib/logic";
import { native } from "../lib/native";
import {
- addAsReference, cancelJob, editItem, openEditorFor, removeSessionItem, selectedItem, setState, submitRequest, toastError, toastInfo, useStore, type SessionItem,
+ cancelJob, focusPrompt, getState, itemSource, removeSessionItem, selectedItem, selectItem, setState, submitRequest, toastError, toastInfo, useStore, type SessionItem,
} from "../lib/store";
-import type { GenerationRecord, JobView, Size, UpscaleMethod } from "../lib/types";
+import type { GenerationRecord, JobView, Mode, Size, UpscaleMethod } from "../lib/types";
import { CompareBar, CompareFrame } from "./Compare";
import { IconButton, Popover, Seg, useFit } from "./ui";
import { FullscreenButton, ZoomImage } from "./Viewer";
+export const MODE_ICON: Record<Mode, React.ReactNode> = {
+ auto: <Wand2 size={11} />,
+ generate: <Wand2 size={11} />,
+ edit: <Pencil size={11} />,
+ multi_reference: <Combine size={11} />,
+ inpaint: <Brush size={11} />,
+ outpaint: <Expand size={11} />,
+ upscale: <ZoomIn size={11} />,
+};
+
+const MODE_DOING: Record<Mode, string> = {
+ auto: "Working",
+ generate: "Creating",
+ edit: "Editing",
+ multi_reference: "Combining images",
+ inpaint: "Inpainting",
+ outpaint: "Expanding",
+ upscale: "Upscaling",
+};
+
function Empty() {
return (
<div className="empty">
<h1>What should we make?</h1>
- <p>Describe an image, or bring one to edit.</p>
+ <p>Describe a new image below, or bring one in to edit it.</p>
<div className="hint">
<span>
<MousePointerClick size={14} /> Drop images here
@@ -33,21 +53,33 @@ function Empty() {
);
}
-function Pending({ job, aspect }: { job: JobView; aspect: number }) {
- const { ref, box } = useFit(aspect);
+/** A version in progress: the image it starts from, dimmed, with live progress on top. */
+function Pending({ job, item, labels }: { job: JobView; item: SessionItem; labels: Record<string, string> }) {
+ const o = job.plan?.output;
+ const { ref, box } = useFit(o ? o.width / o.height : 1);
+ const session = useStore((s) => s.session);
const frac = jobFraction(job);
const remain = remainingSeconds(job);
const canCancel = !["done", "failed", "cancelled"].includes(job.status);
+ const src = item.request?.mode === "generate" ? undefined : item.request?.images?.[0];
+ const from = src ? session.find((i) => itemSource(i) === src) : undefined;
+ const mode = job.plan?.mode;
+ // "v3 · Editing v2", "v1 · Creating"
+ const title = [labels[item.key], mode && `${MODE_DOING[mode]}${from && mode !== "multi_reference" ? ` ${labels[from.key]}` : ""}`].filter(Boolean).join(" · ");
+ // The source keeps its own shape inside an expansion; elsewhere it fills the frame.
+ const outpaint = item.request?.outpaint;
return (
<div className="stage-frame" ref={ref}>
<div className="pending" style={{ width: box.w, height: box.h }}>
+ {src && !outpaint && <img className="pending-src" src={urls.source(src)} alt="" draggable={false} />}
<div className="pending-info">
- <span style={{ color: "var(--text)", fontWeight: 500 }}>{jobLabel(job)}</span>
+ <span className="pending-title">{title}</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}` : ""}
+ <span>
+ {jobLabel(job)}
+ {o ? ` · ${o.width}×${o.height}` : ""}
{remain !== null ? ` · ${formatDuration(remain)} left` : ""}
</span>
{job.notes.length > 0 && <span className="notes">{job.notes.join(" ")}</span>}
@@ -182,7 +214,7 @@ function UpscaleMenu(props: { source: string; size: Size; original?: Size | null
function UpscaleButton(props: { source: string; size: Size; original?: Size | null; parentId?: string | null }) {
return (
<Popover
- placement="top-start"
+ placement="top-end"
trigger={(open, toggle) => (
<IconButton title="Upscale" onClick={toggle} active={open}>
<ZoomIn size={17} />
@@ -194,16 +226,62 @@ function UpscaleButton(props: { source: string; size: Size; original?: Size | nu
);
}
+function MoreMenu({ item, path }: { item: SessionItem; path: string | null }) {
+ const g = item.gen;
+ return (
+ <Popover
+ placement="top-end"
+ trigger={(open, toggle) => (
+ <IconButton title="More" onClick={toggle} active={open}>
+ <Ellipsis size={17} />
+ </IconButton>
+ )}
+ >
+ {(close) => (
+ <>
+ {g && (
+ <button
+ className="opt"
+ onClick={() => {
+ close();
+ const c = getState().composer;
+ setState({ composer: { ...composerFromRecord(g, c), mode: "auto" } });
+ focusPrompt();
+ }}
+ >
+ <span className="check">
+ <TextCursorInput size={15} />
+ </span>
+ <span>Reuse prompt and settings</span>
+ </button>
+ )}
+ {path && (
+ <button className="opt" onClick={() => (close(), native.reveal(path).catch(toastError))}>
+ <span className="check">
+ <FolderOpen size={15} />
+ </span>
+ <span>Show in Explorer</span>
+ </button>
+ )}
+ <button className="opt" onClick={() => (close(), removeSessionItem(item.key))}>
+ <span className="check">
+ <Trash2 size={15} />
+ </span>
+ <span>Remove from project</span>
+ </button>
+ </>
+ )}
+ </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"
+ title="Variation (same prompt, new seed)"
onClick={() => {
const r = variationRequest(g);
if (r) submitRequest(r);
@@ -211,15 +289,6 @@ function GenActions({ item, g }: { item: SessionItem; g: GenerationRecord }) {
>
<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
@@ -265,9 +334,6 @@ function GenActions({ item, g }: { item: SessionItem; g: GenerationRecord }) {
>
<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) => (
@@ -278,30 +344,18 @@ function GenActions({ item, g }: { item: SessionItem; g: GenerationRecord }) {
>
{() => <InfoPanel g={g} />}
</Popover>
+ <MoreMenu item={item} path={g.file_path} />
</div>
);
}
function InputActions({ item }: { item: SessionItem }) {
+ const input = item.input!;
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 }} />}
+ <UpscaleButton source={`input:${input.id}`} size={{ width: input.width, height: input.height }} />
<span className="sep" />
- <IconButton title="Remove from session" onClick={() => removeSessionItem(item.key)}>
- <X size={17} />
- </IconButton>
+ <MoreMenu item={item} path={input.original_path ?? input.path} />
</div>
);
}
@@ -314,92 +368,165 @@ function PlainFrame({ src, alt, w, h }: { src: string; alt: string; w: number; h
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 })} />
+ <img className="stage-img fill" src={src} alt={alt} draggable={false} />
<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;
+/** One line under the image: which version this is, what made it, and what you can do with it. */
+function StageBar({ item, label }: { item: SessionItem; label: string }) {
+ const g = item.gen;
+ const base = g ? compareBase(g) : null;
+ const w = g?.width ?? item.input!.width;
+ const h = g?.height ?? item.input!.height;
+ const name = item.input?.original_name ? safeDecode(item.input.original_name) : "Imported image";
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>
+ <div className="stage-bar">
+ <div className="stage-meta">
+ <span className="ver">{label}</span>
+ {g && <span className="mode">{MODE_LABEL[g.mode]}</span>}
+ <span className="stage-prompt" title={g?.prompt ?? name}>
+ {g ? g.prompt || (g.mode === "upscale" ? `${g.references[0]?.width ?? "?"}×${g.references[0]?.height ?? "?"} → ${w}×${h}` : "") : name}
+ </span>
+ <span className="dims">
{w}×{h}
</span>
</div>
- {item.gen ? <GenActions key={`actions-${item.gen.id}`} item={item} g={item.gen} /> : <InputActions item={item} />}
+ {base && <CompareBar />}
+ {g ? <GenActions key={`actions-${g.id}`} item={item} g={g} /> : <InputActions item={item} />}
</div>
);
}
-export function HistoryRail() {
+function safeDecode(s: string) {
+ try {
+ return decodeURIComponent(s);
+ } catch {
+ return s;
+ }
+}
+
+/** The project's versions in order: Original → v1 → v2 … The image the prompt edits carries a pencil. */
+function Timeline({ labels }: { labels: Record<string, string> }) {
const session = useStore((s) => s.session);
const selected = useStore((s) => s.selected);
const jobs = useStore((s) => s.jobs);
+ const target = useStore((s) => s.composer.refs[0]?.source);
+ const boxRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ boxRef.current?.querySelector(".frame.sel")?.scrollIntoView({ block: "nearest", inline: "nearest" });
+ }, [selected, session.length]);
+
if (!session.length) return null;
return (
- <div className="rail" aria-label="Session history">
- {session.map((it) => {
+ <div className="timeline" ref={boxRef} aria-label="Versions">
+ {session.map((it, i) => {
const job = it.jobId ? jobs[it.jobId] : undefined;
+ const src = itemSource(it);
const pending = it.kind === "job";
+ const failed = pending && job && ["failed", "cancelled"].includes(job.status);
+ const frac = pending && job ? jobFraction(job) : null;
+ const mode: Mode | undefined = it.gen?.mode ?? job?.plan?.mode;
+ const from = it.gen?.parent_id ? session.find((x) => x.gen?.id === it.gen!.parent_id) : undefined;
+ const pendingSrc = pending && it.request?.mode !== "generate" ? it.request?.images?.[0] : undefined;
+ const prompt = it.gen?.prompt || it.request?.prompt || "";
+ const tip = [labels[it.key], mode ? MODE_LABEL[mode] : it.input ? "Imported" : "", from && session[i - 1] !== from ? `from ${labels[from.key]}` : "", prompt ? `— ${prompt}` : ""].filter(Boolean).join(" ");
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>
+ <Fragment key={it.key}>
+ {i > 0 && <span className="link" />}
+ <button className={`frame ${selected === it.key ? "sel" : ""}`} onClick={() => selectItem(it.key)} title={tip}>
+ <span className="frame-img">
+ {src && <img src={urls.sourceThumb(src)} alt="" draggable={false} />}
+ {pendingSrc && <img className="dim" src={urls.sourceThumb(pendingSrc)} alt="" draggable={false} />}
+ {pending && !failed && (
+ <span className="frame-state">
+ {frac !== null ? <Ring frac={frac} /> : <Loader2 className="spin" size={16} />}
+ </span>
+ )}
+ {failed && (
+ <span className="frame-state">
+ <X size={16} />
+ </span>
+ )}
+ {src && src === target && (
+ <span className="frame-badge" title="The prompt edits this image">
+ <Pencil size={10} />
+ </span>
+ )}
+ </span>
+ <span className="frame-label">
+ {mode && MODE_ICON[mode]}
+ {labels[it.key]}
+ </span>
+ </button>
+ </Fragment>
);
})}
</div>
);
}
+
+function Ring({ frac }: { frac: number }) {
+ const r = 8;
+ const c = 2 * Math.PI * r;
+ return (
+ <svg width="20" height="20" viewBox="0 0 20 20" aria-hidden>
+ <circle cx="10" cy="10" r={r} fill="none" stroke="currentColor" strokeOpacity="0.25" strokeWidth="2.5" />
+ <circle cx="10" cy="10" r={r} fill="none" stroke="currentColor" strokeWidth="2.5" strokeDasharray={c} strokeDashoffset={c * (1 - frac)} strokeLinecap="round" transform="rotate(-90 10 10)" />
+ </svg>
+ );
+}
+
+export function Stage() {
+ const item = useStore(selectedItem);
+ const session = useStore((s) => s.session);
+ const job = useStore((s) => (item?.jobId ? s.jobs[item.jobId] : undefined));
+ const labels = useMemo(() => versionLabels(session), [session]);
+
+ if (!item) {
+ return (
+ <div className="stage">
+ <Empty />
+ <Timeline labels={labels} />
+ </div>
+ );
+ }
+
+ let view: React.ReactNode;
+ if (item.kind === "job") {
+ view = !job ? (
+ <div className="stage-frame">
+ <Loader2 className="spin" size={22} />
+ </div>
+ ) : job.status === "failed" || job.status === "cancelled" ? (
+ <Failed job={job} item={item} />
+ ) : (
+ <Pending job={job} item={item} labels={labels} />
+ );
+ } else {
+ 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;
+ view = (
+ <>
+ {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} />
+ )}
+ <StageBar item={item} label={labels[item.key]} />
+ </>
+ );
+ }
+
+ return (
+ <div className="stage">
+ {view}
+ <Timeline labels={labels} />
+ </div>
+ );
+}
diff --git a/src/components/Viewer.tsx b/src/components/Viewer.tsx
index 8373b30..c52abe2 100644
--- a/src/components/Viewer.tsx
+++ b/src/components/Viewer.tsx
@@ -77,8 +77,23 @@ function FullscreenShell({ children, hint, onClose }: { children: ReactNode; hin
return () => window.removeEventListener("keydown", down, true);
}, [onClose]);
+ // React events from a portal still bubble to its React parents: without this, a press
+ // anywhere here reaches the stage image underneath (which captures the pointer for the
+ // slider / press-to-compare) and the buttons in full screen never get their click.
+ const stop = (e: React.SyntheticEvent) => e.stopPropagation();
return (
- <div className="viewer" role="dialog" aria-label="Full screen">
+ <div
+ className="viewer"
+ role="dialog"
+ aria-label="Full screen"
+ onPointerDown={stop}
+ onPointerMove={stop}
+ onPointerUp={stop}
+ onPointerCancel={stop}
+ onClick={stop}
+ onDoubleClick={stop}
+ onContextMenu={stop}
+ >
{children}
<div className="viewer-bar">
<span className="viewer-hint">{hint ? `${hint} · ` : ""}Esc to exit</span>
diff --git a/src/components/ui.tsx b/src/components/ui.tsx
index 58018f2..7af9b84 100644
--- a/src/components/ui.tsx
+++ b/src/components/ui.tsx
@@ -86,6 +86,37 @@ export function Switch(props: { on: boolean; onChange: (v: boolean) => void; lab
return <button className={`switch ${props.on ? "on" : ""}`} role="switch" aria-checked={props.on} aria-label={props.label} onClick={() => props.onChange(!props.on)} />;
}
+/** Text that turns into a field while renaming: Enter or leaving saves, Escape cancels. */
+export function NameField(props: { value: string; onSave: (v: string) => void; onDone: () => void; className?: string }) {
+ const [v, setV] = useState(props.value);
+ const done = useRef(false);
+ const finish = (save: boolean) => {
+ if (done.current) return;
+ done.current = true;
+ if (save && v.trim() !== props.value) props.onSave(v);
+ props.onDone();
+ };
+ return (
+ <input
+ className={`name-field ${props.className ?? ""}`}
+ value={v}
+ autoFocus
+ onFocus={(e) => e.currentTarget.select()}
+ onChange={(e) => setV(e.target.value)}
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ if (e.key === "Enter") finish(true);
+ else if (e.key === "Escape") finish(false);
+ }}
+ onBlur={() => finish(true)}
+ maxLength={120}
+ spellCheck={false}
+ aria-label="Project name"
+ />
+ );
+}
+
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}>
diff --git a/src/lib/api.ts b/src/lib/api.ts
index c3f1cb4..01b62c5 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -1,8 +1,8 @@
-// Thin client for the local qls-service API. Images are referenced by URL (with the
+// Thin client for the local kokon-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,
+ AppConfig, AppErrorBody, GenerationRecord, GenerationRequest, HardwareReport, InputRecord, InstallStatus, JobView, Plan, ServiceEvent, SetupReport, StatusResponse,
} from "./types";
export class ApiError extends Error {
@@ -13,6 +13,14 @@ export class ApiError extends Error {
let base = "";
let token = "";
+/** Private mode: uploads and imports go to the service's temporary store. */
+let privateInputs = false;
+
+export function setPrivateInputs(on: boolean) {
+ privateInputs = on;
+}
+
+const privateQuery = () => (privateInputs ? "?private=true" : "");
export function configure(baseUrl: string, tok: string) {
base = baseUrl;
@@ -44,6 +52,10 @@ const json = (body: unknown) => JSON.stringify(body);
export const api = {
status: () => call<StatusResponse>("/status"),
setup: () => call<SetupReport>("/setup"),
+ hardware: () => call<HardwareReport>("/setup/hardware"),
+ install: (preset: string, upscaler: boolean) => call<InstallStatus>("/setup/install", { method: "POST", body: json({ preset, upscaler }) }),
+ installStatus: () => call<InstallStatus>("/setup/install"),
+ cancelInstall: () => call<InstallStatus>("/setup/install/cancel", { method: "POST" }),
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" }),
@@ -56,8 +68,9 @@ export const api = {
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 }) }),
+ call<InputRecord>(`/inputs${privateQuery()}`, { method: "POST", body: bytes as BodyInit, headers: { "Content-Type": "application/octet-stream", ...(name ? { "x-filename": encodeURIComponent(name) } : {}) } }),
+ importPath: (path: string) => call<InputRecord>(`/inputs/import${privateQuery()}`, { method: "POST", body: json({ path }) }),
+ clearPrivate: () => call<{ cleared: number }>("/private/clear", { method: "POST" }),
input: (id: string) => call<InputRecord>(`/inputs/${id}`),
gallery: (q: { q?: string; favorites?: boolean; limit?: number; offset?: number; sort?: string }) => {
const p = new URLSearchParams();
@@ -79,6 +92,9 @@ export const urls = {
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}`,
+ /** Full image for a "gen:<id>" / "input:<id>" source. */
+ source: (s: string) => (s.startsWith("gen:") ? urls.gen(s.slice(4)) : urls.input(s.slice(6))),
+ sourceThumb: (s: string) => (s.startsWith("gen:") ? urls.genThumb(s.slice(4)) : urls.inputThumb(s.slice(6))),
};
/** Server-sent events with automatic reconnect. Returns an unsubscribe function. */
diff --git a/src/lib/logic.test.ts b/src/lib/logic.test.ts
index 739a43c..9fc5975 100644
--- a/src/lib/logic.test.ts
+++ b/src/lib/logic.test.ts
@@ -1,9 +1,10 @@
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,
+ activeOverrides, buildRequest, compareBase, diffPixels, emptyComposer, expansionPixels, expansionPreset, jobFraction, jobLabel, moveRef, needsPrompt, persistentAdvanced, pipelineSummary,
+ planPipeline, remainingSeconds, sizeForWidth, timeAgo, upscaleRequest, upscaleTargets, versionLabels, type Ref,
+ formatBytes, installItemShort, installItemText, installProgress, installStep, installTimeLeft, undoTarget,
} from "./logic";
-import type { GenerationRecord, JobView, Plan } from "./types";
+import type { GenerationRecord, InstallItem, JobView, Plan } from "./types";
const ref = (n: number): Ref => ({ key: `k${n}`, source: `input:${n}`, width: 100, height: 100, name: `r${n}` });
@@ -60,6 +61,15 @@ describe("buildRequest", () => {
const moved = { ...c, refs: [ref(2), ref(1)] };
expect(buildRequest(moved).mask).toBeNull();
});
+ it("sends the inpaint action with a valid mask only; removal needs no prompt", () => {
+ const c = { ...emptyComposer(), prompt: "", refs: [ref(1)], mask: { inputId: "m", refKey: "k1" }, inpaintAction: "remove" as const };
+ expect(buildRequest(c).inpaint_action).toBe("remove");
+ expect(needsPrompt(c)).toBe(false);
+ expect(needsPrompt({ ...c, inpaintAction: "add" })).toBe(true);
+ const moved = { ...c, refs: [ref(2), ref(1)] };
+ expect("inpaint_action" in buildRequest(moved)).toBe(false);
+ expect(needsPrompt(moved)).toBe(true);
+ });
it("custom resolution sends dimensions", () => {
const c = { ...emptyComposer(), prompt: "x", resolution: "custom" as const, customWidth: 1280, customHeight: 720 };
const r = buildRequest(c);
@@ -181,3 +191,76 @@ describe("before / after comparison", () => {
expect(out[12]).toBeGreaterThan(out[13]); // not covered by the source (expanded): red
});
});
+
+describe("project versions", () => {
+ it("names imports Original and numbers results and pending jobs", () => {
+ const items = [
+ { key: "a", kind: "input" as const },
+ { key: "b", kind: "gen" as const },
+ { key: "c", kind: "job" as const },
+ { key: "d", kind: "input" as const },
+ { key: "e", kind: "gen" as const },
+ ];
+ expect(versionLabels(items)).toEqual({ a: "Original", b: "v1", c: "v2", d: "Original 2", e: "v3" });
+ });
+
+ it("formats project age", () => {
+ const now = 1_000_000_000_000;
+ expect(timeAgo(now - 5_000, now)).toBe("just now");
+ expect(timeAgo(now - 5 * 60_000, now)).toBe("5m ago");
+ expect(timeAgo(now - 3 * 3_600_000, now)).toBe("3h ago");
+ expect(timeAgo(now - 2 * 86_400_000, now)).toBe("2d ago");
+ });
+});
+
+describe("setup wizard", () => {
+ const item = (p: Partial<InstallItem>): InstallItem => ({
+ id: "x", label: "X", kind: "model", size: 4_199_565_024, received: 0, state: "pending", error: null, hint: null, url: "", page: "", path: "", ...p,
+ });
+ it("formats sizes like download pages", () => {
+ expect(formatBytes(4_199_565_024)).toBe("4.2 GB");
+ expect(formatBytes(14_230_275_808)).toBe("14 GB");
+ expect(formatBytes(66_961_958)).toBe("67 MB");
+ expect(formatBytes(512)).toBe("1 KB");
+ });
+ it("counts progress only over files still to install", () => {
+ const p = installProgress([item({ state: "present", received: 100, size: 100 }), item({ size: 200, received: 50, state: "downloading" })]);
+ expect(p).toEqual({ received: 50, total: 200, frac: 0.25 });
+ expect(installProgress([item({ state: "present" })]).frac).toBe(1);
+ });
+ it("summarizes the progress panel", () => {
+ expect(installItemShort(item({ state: "downloading", received: 2_099_782_512 }))).toBe("50%");
+ expect(installItemShort(item({ state: "cancelled", received: 4_000_000_000 }))).toBe("Paused · 200 MB left");
+ expect(installItemShort(item({ state: "present" }))).toBe("Installed");
+ expect(installStep([item({ state: "done" }), item({ label: "VAE", state: "verifying" })])).toBe("Checking VAE");
+ expect(installStep([item({ state: "pending" })])).toBeNull();
+ expect(installTimeLeft(12e9, 100e6)).toBe("about 2 min left");
+ expect(installTimeLeft(1e9, 100e6)).toBe("less than a minute left");
+ expect(installTimeLeft(1e9, 0)).toBeNull();
+ });
+ it("describes each file state", () => {
+ expect(installItemText(item({ state: "downloading", received: 1e9 }), 50e6)).toBe("1.0 GB of 4.2 GB · 50 MB/s · 1m 4s left");
+ expect(installItemText(item({}), 0)).toBe("To download · 4.2 GB");
+ expect(installItemText(item({ state: "failed", error: "HTTP 404" }), 0)).toBe("HTTP 404");
+ expect(installItemText(item({ state: "cancelled", received: 2e9 }), 0)).toContain("continues where it stopped");
+ });
+});
+
+describe("undo between versions", () => {
+ const items = [
+ { key: "orig", source: "input:a", from: null },
+ { key: "v1", source: "gen:1", from: "input:a" },
+ { key: "v2", source: "gen:2", from: "gen:1" },
+ { key: "v3", source: "gen:3", from: "input:a" }, // a second edit of the original
+ { key: "t2i", source: "gen:4", from: null },
+ ];
+ it("goes back to the image a version was made from", () => {
+ expect(undoTarget(items, "v2")).toBe("v1");
+ expect(undoTarget(items, "v3")).toBe("orig");
+ });
+ it("falls back to the previous version, and stops at the first", () => {
+ expect(undoTarget(items, "t2i")).toBe("v3");
+ expect(undoTarget(items, "orig")).toBeNull();
+ expect(undoTarget(items, "missing")).toBeNull();
+ });
+});
diff --git a/src/lib/logic.ts b/src/lib/logic.ts
index b04507d..a2c7c8e 100644
--- a/src/lib/logic.ts
+++ b/src/lib/logic.ts
@@ -1,6 +1,6 @@
// 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";
+import type { Advanced, GenerationRecord, GenerationRequest, InpaintAction, InputRecord, InstallItem, JobView, Mode, OutpaintSpec, Plan, Quality, ResolutionMode, Size, UpscaleMethod } from "./types";
export interface Ref {
key: string;
@@ -19,6 +19,8 @@ export interface Composer {
refs: Ref[];
/** Mask painted on refs[0] (input id of the mask PNG). */
mask: { inputId: string; refKey: string } | null;
+ /** What to do in the painted area. */
+ inpaintAction: InpaintAction;
outpaint: OutpaintSpec | null;
mode: Mode;
aspect: string;
@@ -35,6 +37,7 @@ export const emptyComposer = (prefs?: Partial<Composer>): Composer => ({
negative: "",
refs: [],
mask: null,
+ inpaintAction: "edit",
outpaint: null,
mode: "auto",
aspect: prefs?.aspect ?? "auto",
@@ -85,6 +88,7 @@ export function buildRequest(c: Composer, parentId?: string | null): GenerationR
mode: c.mode,
images: c.mode === "generate" ? [] : c.refs.map((r) => r.source),
mask: maskValid ? `input:${c.mask!.inputId}` : null,
+ ...(maskValid ? { inpaint_action: c.inpaintAction } : {}),
outpaint: hasOutpaint(c.outpaint) ? c.outpaint : null,
quality: c.quality,
resolution: c.resolution,
@@ -99,6 +103,12 @@ export function buildRequest(c: Composer, parentId?: string | null): GenerationR
};
}
+/** False only for a removal in a painted area, which needs no description. */
+export function needsPrompt(c: Composer): boolean {
+ const maskValid = c.mask && c.refs[0] && c.mask.refKey === c.refs[0].key;
+ return !(maskValid && c.inpaintAction === "remove");
+}
+
/** 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. */
@@ -137,6 +147,7 @@ export function composerFromRecord(g: GenerationRecord, base: Composer): Compose
negative: g.negative_prompt ?? "",
refs,
mask: g.mask_input_id && refs[0] ? { inputId: g.mask_input_id, refKey: refs[0].key } : null,
+ inpaintAction: req?.inpaint_action ?? "edit",
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",
@@ -169,6 +180,31 @@ export const MODE_LABEL: Record<Mode, string> = {
upscale: "Upscale",
};
+/** Version names within a project: imported images are "Original" ("Original 2", ...), and
+ * results and pending jobs are numbered v1, v2... in project order. */
+export function versionLabels(items: { key: string; kind: "gen" | "input" | "job" }[]): Record<string, string> {
+ const out: Record<string, string> = {};
+ let v = 0;
+ let inputs = 0;
+ for (const it of items) {
+ if (it.kind === "input") {
+ inputs++;
+ out[it.key] = inputs === 1 ? "Original" : `Original ${inputs}`;
+ } else out[it.key] = `v${++v}`;
+ }
+ return out;
+}
+
+/** "1m ago"-style age for the project list. */
+export function timeAgo(ms: number, now = Date.now()): string {
+ const s = Math.max(0, (now - ms) / 1000);
+ if (s < 60) return "just now";
+ if (s < 3600) return `${Math.floor(s / 60)}m ago`;
+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`;
+ if (s < 86400 * 7) return `${Math.floor(s / 86400)}d ago`;
+ return new Date(ms).toLocaleDateString();
+}
+
/** Short truthful status text for a job. */
export function jobLabel(j: JobView): string {
switch (j.status) {
@@ -316,6 +352,93 @@ export function formatDuration(s: number): string {
return r ? `${m}m ${r}s` : `${m}m`;
}
+/** Undo target for version `key`: the version it was made from (`from` is that image's
+ * "gen:<id>"/"input:<id>"), or the version before it when that one is not in the project. */
+export function undoTarget(items: { key: string; source: string | null; from: string | null }[], key: string): string | null {
+ const i = items.findIndex((x) => x.key === key);
+ if (i < 0) return null;
+ const from = items[i].from;
+ const parent = from ? items.find((x) => x.source === from && x.key !== key) : undefined;
+ if (parent) return parent.key;
+ return i > 0 ? items[i - 1].key : null;
+}
+
+/** 1.2 GB, 340 MB, 12 KB (decimal units, like download sizes on Hugging Face and GitHub). */
+export function formatBytes(n: number): string {
+ if (n >= 1e9) return `${(n / 1e9).toFixed(n >= 1e10 ? 0 : 1)} GB`;
+ if (n >= 1e6) return `${Math.round(n / 1e6)} MB`;
+ return `${Math.max(0, Math.round(n / 1e3))} KB`;
+}
+
+/** Overall download progress over the files that were not installed already. */
+export function installProgress(items: InstallItem[]): { received: number; total: number; frac: number } {
+ const todo = items.filter((i) => i.state !== "present");
+ const total = todo.reduce((a, i) => a + i.size, 0);
+ const received = todo.reduce((a, i) => a + Math.min(i.received, i.size), 0);
+ return { received, total, frac: total ? received / total : 1 };
+}
+
+/** One line under a file in the setup wizard. */
+export function installItemText(i: InstallItem, bytesPerSec: number): string {
+ switch (i.state) {
+ case "present":
+ case "done":
+ return `Installed · ${formatBytes(i.size)}`;
+ case "pending":
+ return `To download · ${formatBytes(i.size - i.received)}`;
+ case "downloading": {
+ const rate = bytesPerSec > 0 ? ` · ${formatBytes(bytesPerSec)}/s` : "";
+ const left = bytesPerSec > 0 ? ` · ${formatDuration((i.size - i.received) / bytesPerSec)} left` : "";
+ return `${formatBytes(i.received)} of ${formatBytes(i.size)}${rate}${left}`;
+ }
+ case "verifying":
+ return "Checking the file…";
+ case "extracting":
+ return "Extracting…";
+ case "cancelled":
+ return i.received ? `Paused at ${formatBytes(i.received)}; continues where it stopped` : "Cancelled";
+ case "failed":
+ return i.error ?? "Failed";
+ }
+}
+
+/** Right-hand status of a file in the setup list. */
+export function installItemShort(i: InstallItem): string {
+ switch (i.state) {
+ case "present":
+ case "done":
+ return "Installed";
+ case "downloading":
+ return `${Math.floor((i.received / i.size) * 100)}%`;
+ case "verifying":
+ return "Checking";
+ case "extracting":
+ return "Extracting";
+ case "failed":
+ return "Failed";
+ case "cancelled":
+ return i.received ? `Paused · ${formatBytes(i.size - i.received)} left` : formatBytes(i.size);
+ case "pending":
+ return formatBytes(i.size - i.received);
+ }
+}
+
+/** What the installer is doing right now, for the progress panel. */
+export function installStep(items: InstallItem[]): string | null {
+ const it = items.find((i) => i.state === "downloading" || i.state === "verifying" || i.state === "extracting");
+ if (!it) return null;
+ if (it.state === "verifying") return `Checking ${it.label}`;
+ if (it.state === "extracting") return `Unpacking ${it.label}`;
+ return `Downloading ${it.label}`;
+}
+
+/** "about 2 min left" once the speed is known. */
+export function installTimeLeft(remaining: number, bytesPerSec: number): string | null {
+ if (bytesPerSec < 100e3 || remaining <= 0) return null;
+ const s = remaining / bytesPerSec;
+ return s < 60 ? "less than a minute left" : `about ${Math.ceil(s / 60)} min left`;
+}
+
export const ASPECTS = ["auto", "1:1", "4:3", "3:4", "16:9", "9:16", "custom"] as const;
/** Expansion presets in source pixels. */
diff --git a/src/lib/native.ts b/src/lib/native.ts
index a5eea1a..8871de1 100644
--- a/src/lib/native.ts
+++ b/src/lib/native.ts
@@ -17,6 +17,8 @@ export const native = {
reveal: (path: string) => invoke<void>("reveal", { path }),
openFolder: (path: string) => invoke<void>("open_folder", { path }),
dataFolder: () => invoke<string>("data_folder"),
+ /** https links to github.com / huggingface.co only. */
+ openLink: (url: string) => invoke<void>("open_link", { url }),
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 [];
diff --git a/src/lib/store.ts b/src/lib/store.ts
index f74c173..caca228 100644
--- a/src/lib/store.ts
+++ b/src/lib/store.ts
@@ -1,8 +1,13 @@
// Minimal global store (useSyncExternalStore) — no extra dependencies.
+//
+// Work is organised in projects: each project is one line of work (an original or a first
+// result and every version made from it). The open project lives in `session`/`selected`;
+// every project is kept as ids in `projects` (persisted) and re-loaded from the service when
+// opened again.
import { useSyncExternalStore } from "react";
-import { api, ApiError, subscribe } from "./api";
-import { buildRequest, emptyComposer, newKey, persistentAdvanced, refFromGen, refFromInput, type CompareMode, type Composer } from "./logic";
+import { api, ApiError, setPrivateInputs, subscribe } from "./api";
+import { buildRequest, emptyComposer, needsPrompt, newKey, persistentAdvanced, refFromGen, refFromInput, undoTarget, type CompareMode, type Composer, type Ref } from "./logic";
import type { AppErrorBody, GenerationRecord, GenerationRequest, InputRecord, JobView, ServerState, StatusResponse } from "./types";
export type Overlay = null | "gallery" | "settings" | "inpaint" | "expand";
@@ -17,6 +22,17 @@ export interface SessionItem {
request?: GenerationRequest;
}
+export interface ProjectMeta {
+ id: string;
+ title: string;
+ /** The title was typed by the user (otherwise it follows the first prompt). */
+ named?: boolean;
+ updatedAt: number;
+ /** "gen:<id>" / "input:<id>" of the latest image. */
+ cover: string | null;
+ count: number;
+}
+
export interface Toast {
id: string;
message: string;
@@ -30,10 +46,17 @@ export interface State {
connectError: string | null;
server: { state: ServerState; owned: boolean; error: AppErrorBody | null };
status: StatusResponse | null;
+ /** Versions of the open project, in order. */
session: SessionItem[];
selected: string | null;
+ projectId: string;
+ /** Saved projects, most recent first (empty ones are left out). */
+ projects: ProjectMeta[];
+ sidebar: boolean;
jobs: Record<string, JobView>;
composer: Composer;
+ /** Last submitted prompt (Up arrow in an empty prompt brings it back). */
+ lastPrompt: string;
overlay: Overlay;
toasts: Toast[];
galleryVersion: number;
@@ -42,9 +65,15 @@ export interface State {
compare: CompareMode;
/** Flicker period in ms. */
flickerMs: number;
+ /** Private mode: nothing is saved to the gallery, the output folder or the project list. */
+ privateMode: boolean;
+ /** Versions left with Undo, most recent last (Redo walks back through them). */
+ redo: string[];
}
const PREFS_KEY = "qls.prefs.v1";
+const PROJECTS_KEY = "qls.projects.v1";
+const SIDEBAR_KEY = "qls.sidebar.v1";
function loadPrefs(): Partial<Composer> {
try {
@@ -66,6 +95,159 @@ function savePrefs(c: Composer) {
}
}
+// ---------------------------------------------------------------------------------------
+// Projects (persisted as ids; records are fetched from the service when a project opens)
+// ---------------------------------------------------------------------------------------
+
+interface StoredItem {
+ key: string;
+ kind: SessionItem["kind"];
+ genId?: string;
+ inputId?: string;
+ jobId?: string;
+ request?: GenerationRequest;
+}
+
+interface ProjectData {
+ meta: ProjectMeta;
+ items: StoredItem[];
+ selected: string | null;
+}
+
+const projects: Record<string, ProjectData> = (() => {
+ try {
+ const p = JSON.parse(localStorage.getItem(PROJECTS_KEY) || "{}");
+ return p && typeof p === "object" ? p : {};
+ } catch {
+ return {};
+ }
+})();
+
+const genCache = new Map<string, GenerationRecord>();
+const inputCache = new Map<string, InputRecord>();
+
+let saveTimer: number | undefined;
+function persistProjects() {
+ window.clearTimeout(saveTimer);
+ saveTimer = window.setTimeout(() => {
+ const keep: Record<string, ProjectData> = {};
+ for (const [id, p] of Object.entries(projects)) if (p.items.length || p.meta.named) keep[id] = p;
+ try {
+ localStorage.setItem(PROJECTS_KEY, JSON.stringify(keep));
+ } catch {
+ /* storage unavailable */
+ }
+ }, 300);
+}
+
+function projectList(): ProjectMeta[] {
+ return Object.values(projects)
+ .filter((p) => p.items.length || p.meta.named)
+ .map((p) => p.meta)
+ .sort((a, b) => b.updatedAt - a.updatedAt);
+}
+
+export const itemSource = (i: { gen?: GenerationRecord; input?: InputRecord }) => (i.gen ? `gen:${i.gen.id}` : i.input ? `input:${i.input.id}` : null);
+const storedSource = (i: StoredItem) => (i.genId ? `gen:${i.genId}` : i.inputId ? `input:${i.inputId}` : null);
+
+const toStored = (i: SessionItem): StoredItem => ({
+ key: i.key,
+ kind: i.kind,
+ genId: i.gen?.id,
+ inputId: i.input?.id,
+ jobId: i.jobId,
+ request: i.kind === "job" ? i.request : undefined,
+});
+
+function titleOf(items: SessionItem[]): string | null {
+ for (const i of items) {
+ const p = i.gen?.prompt || i.request?.prompt;
+ if (p) return p;
+ if (i.input) return i.input.original_name ? safeDecode(i.input.original_name) : "Imported image";
+ }
+ return null;
+}
+
+function safeDecode(s: string) {
+ try {
+ return decodeURIComponent(s);
+ } catch {
+ return s;
+ }
+}
+
+const lastCover = (items: StoredItem[]) => {
+ for (let k = items.length - 1; k >= 0; k--) {
+ const s = storedSource(items[k]);
+ if (s) return s;
+ }
+ return null;
+};
+const countOf = (items: StoredItem[]) => items.filter((i) => i.kind !== "job").length;
+
+/** Writes the open project back into `projects` after its versions or selection changed. */
+function syncProject(prev: State) {
+ // Private work is never written to the project list (titles come from prompts).
+ if (state.privateMode) return;
+ const id = state.projectId;
+ const old = projects[id];
+ const items = state.session.map(toStored);
+ for (const i of state.session) {
+ if (i.gen) genCache.set(i.gen.id, i.gen);
+ if (i.input) inputCache.set(i.input.id, i.input);
+ }
+ // Opening a project must not move it to the top; adding a version does.
+ const edited = id === prev.projectId && state.session !== prev.session;
+ projects[id] = {
+ meta: {
+ id,
+ title: old?.meta.named ? old.meta.title : titleOf(state.session) ?? old?.meta.title ?? "Untitled",
+ named: old?.meta.named,
+ updatedAt: edited || !old ? Date.now() : old.meta.updatedAt,
+ cover: lastCover(items),
+ count: countOf(items),
+ },
+ items,
+ selected: state.selected,
+ };
+ state = { ...state, projects: projectList() };
+ persistProjects();
+}
+
+/** Loads the records of a stored project. Versions deleted from the gallery are skipped. */
+async function hydrate(items: StoredItem[]): Promise<SessionItem[]> {
+ const out = await Promise.all(
+ items.map(async (it): Promise<SessionItem | null> => {
+ try {
+ if (it.kind === "gen" && it.genId) {
+ const g = genCache.get(it.genId) ?? (await api.generation(it.genId));
+ genCache.set(g.id, g);
+ return { key: it.key, kind: "gen", gen: g, jobId: it.jobId };
+ }
+ if (it.kind === "input" && it.inputId) {
+ const r = inputCache.get(it.inputId) ?? (await api.input(it.inputId));
+ inputCache.set(r.id, r);
+ return { key: it.key, kind: "input", input: r };
+ }
+ // A job is only shown while the service still knows it (e.g. not after a restart).
+ if (it.kind === "job" && it.jobId && state.jobs[it.jobId]) return { key: it.key, kind: "job", jobId: it.jobId, request: it.request };
+ } catch {
+ /* deleted */
+ }
+ return null;
+ }),
+ );
+ return out.filter((x): x is SessionItem => !!x);
+}
+
+const loadSidebar = () => {
+ try {
+ return localStorage.getItem(SIDEBAR_KEY) !== "0";
+ } catch {
+ return true;
+ }
+};
+
let state: State = {
connected: false,
connectError: null,
@@ -73,14 +255,20 @@ let state: State = {
status: null,
session: [],
selected: null,
+ projectId: newKey(),
+ projects: projectList(),
+ sidebar: loadSidebar(),
jobs: {},
composer: emptyComposer(loadPrefs()),
+ lastPrompt: "",
overlay: null,
toasts: [],
galleryVersion: 0,
needsSetup: false,
compare: "off",
flickerMs: 500,
+ privateMode: false,
+ redo: [],
};
const listeners = new Set<() => void>();
@@ -90,9 +278,18 @@ export function getState() {
}
export function setState(patch: Partial<State> | ((s: State) => Partial<State>)) {
+ const prev = state;
const p = typeof patch === "function" ? patch(state) : patch;
state = { ...state, ...p };
if (p.composer) savePrefs(state.composer);
+ if (state.session !== prev.session || state.selected !== prev.selected || state.projectId !== prev.projectId) syncProject(prev);
+ if (p.sidebar !== undefined) {
+ try {
+ localStorage.setItem(SIDEBAR_KEY, p.sidebar ? "1" : "0");
+ } catch {
+ /* storage unavailable */
+ }
+ }
listeners.forEach((l) => l());
}
@@ -169,70 +366,276 @@ export function startEvents() {
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 results = job.results.map((g): SessionItem => ({ key: newKey(), kind: "gen", gen: g, jobId: job.id }));
+ // Replace the pending version with one version 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 (idx >= 0) {
+ const pending = s.session[idx];
+ const session = [...s.session.slice(0, idx), ...results, ...s.session.slice(idx + 1)];
+ const wasSelected = s.selected === pending.key;
+ // Editing carries on from the new version; creating new images stays in create mode.
+ let composer = s.composer;
+ const src = pending.request?.images?.[0];
+ if (wasSelected && results[0]?.gen && src && composer.refs[0]?.source === src) {
+ composer = { ...composer, refs: [refFromGen(results[0].gen), ...composer.refs.slice(1)], mask: null, outpaint: null };
+ }
+ return { jobs, session, composer, selected: wasSelected && results[0] ? results[0].key : s.selected };
+ }
+ // A job of another (closed) project.
+ for (const p of Object.values(projects)) {
+ const k = p.items.findIndex((i) => i.jobId === job.id && i.kind === "job");
+ if (k < 0) continue;
+ const stored = results.map(toStored);
+ for (const g of job.results) genCache.set(g.id, g);
+ const wasSelected = p.selected === p.items[k].key;
+ p.items = [...p.items.slice(0, k), ...stored, ...p.items.slice(k + 1)];
+ if (wasSelected && stored[0]) p.selected = stored[0].key;
+ p.meta = { ...p.meta, cover: lastCover(p.items), count: countOf(p.items), updatedAt: Date.now() };
+ persistProjects();
+ return { jobs, projects: projectList() };
+ }
+ // A job from another client (e.g. MCP): track it but do not add it to a project.
+ return { jobs };
});
if (job.status === "failed" && job.error) toastError(new ApiError(job.error, 500));
}
+// ---------------------------------------------------------------------------------------
+// Projects
+// ---------------------------------------------------------------------------------------
+
+/** A fresh composer (keeping quality/size preferences) that edits `selected`, if it is an image. */
+function composerFor(c: Composer, session: SessionItem[], selected: string | null): Composer {
+ const it = session.find((i) => i.key === selected);
+ const ref = it?.gen ? refFromGen(it.gen) : it?.input ? refFromInput(it.input) : null;
+ return { ...emptyComposer(c), refs: ref ? [ref] : [] };
+}
+
+/** Starts a new project; the current one stays in the list. */
+export function newProject() {
+ setState((s) =>
+ s.session.length
+ ? { projectId: newKey(), session: [], selected: null, overlay: null, redo: [], composer: emptyComposer(s.composer) }
+ : { overlay: null, composer: { ...emptyComposer(s.composer), prompt: s.composer.prompt } },
+ );
+ focusPrompt();
+}
+
+/** Private mode on: a fresh project whose images stay out of the gallery, the output folder
+ * and the project list. Off: those images are deleted (after confirming). */
+export async function setPrivateMode(on: boolean, confirmDiscard: () => Promise<boolean>) {
+ const s = getState();
+ if (on === s.privateMode) return;
+ if (!on && s.session.length > 0 && !(await confirmDiscard())) return;
+ if (!on) {
+ try {
+ await api.clearPrivate();
+ } catch (e) {
+ toastError(e);
+ return;
+ }
+ }
+ setPrivateInputs(on);
+ // The project being left was saved already (normal mode) or is discarded (private mode).
+ setState((st) => ({ privateMode: on, projectId: newKey(), session: [], selected: null, overlay: null, redo: [], composer: emptyComposer(st.composer) }));
+ if (on) toastInfo("Private mode: images are not saved, and are deleted when you turn it off or close the app.");
+ focusPrompt();
+}
+
+let switching = 0;
+
+export async function switchProject(id: string, selectKey?: string) {
+ if (id === state.projectId) {
+ setState({ overlay: null });
+ if (selectKey) selectItem(selectKey);
+ return;
+ }
+ const data = projects[id];
+ if (!data) return;
+ const token = ++switching;
+ const session = await hydrate(data.items);
+ if (token !== switching) return;
+ const keep = (k: string | null | undefined) => (k && session.some((i) => i.key === k) ? k : null);
+ const selected = keep(selectKey) ?? keep(data.selected) ?? session[session.length - 1]?.key ?? null;
+ setState((s) => ({ projectId: id, session, selected, overlay: null, redo: [], composer: composerFor(s.composer, session, selected) }));
+}
+
+/** Gives a project a name; an empty name goes back to naming it after its first prompt. */
+export function renameProject(id: string, name: string) {
+ const title = name.trim().replace(/\s+/g, " ").slice(0, 120);
+ const p = projects[id] ?? { meta: { id, title: "", updatedAt: Date.now(), cover: null, count: 0 }, items: [], selected: null };
+ const auto = id === state.projectId ? titleOf(state.session) : null;
+ p.meta = title ? { ...p.meta, title, named: true } : { ...p.meta, title: auto ?? p.meta.title ?? "Untitled", named: false };
+ projects[id] = p;
+ persistProjects();
+ setState({ projects: projectList() });
+}
+
+/** Removes a project from the list; its images stay in the gallery. */
+export function deleteProject(id: string) {
+ delete projects[id];
+ persistProjects();
+ if (id === state.projectId) setState((s) => ({ projectId: newKey(), session: [], selected: null, composer: emptyComposer(s.composer) }));
+ else setState({ projects: projectList() });
+}
+
+/** Opens a gallery image: in the project that holds it, or in a new project with its ancestors. */
+export async function openGeneration(g: GenerationRecord) {
+ genCache.set(g.id, g);
+ const here = state.session.find((i) => i.gen?.id === g.id);
+ if (here) {
+ setState({ overlay: null });
+ selectItem(here.key);
+ return;
+ }
+ for (const [id, p] of Object.entries(projects)) {
+ const it = p.items.find((i) => i.genId === g.id);
+ if (it) return switchProject(id, it.key);
+ }
+ const chain = [g];
+ for (let pid = g.parent_id; pid && chain.length < 24; ) {
+ try {
+ const r = genCache.get(pid) ?? (await api.generation(pid));
+ genCache.set(r.id, r);
+ chain.unshift(r);
+ pid = r.parent_id;
+ } catch {
+ break;
+ }
+ }
+ const items: SessionItem[] = [];
+ const root = chain[0];
+ const ref = root.references[0];
+ if (ref && root.references.length === 1 && root.mode !== "generate") {
+ try {
+ const r = inputCache.get(ref.input_id) ?? (await api.input(ref.input_id));
+ items.push({ key: newKey(), kind: "input", input: r });
+ } catch {
+ /* original no longer stored */
+ }
+ }
+ items.push(...chain.map((r): SessionItem => ({ key: newKey(), kind: "gen", gen: r })));
+ const selected = items[items.length - 1].key;
+ setState((s) => ({ projectId: newKey(), session: items, selected, overlay: null, composer: composerFor(s.composer, items, selected) }));
+}
+
+/** A generation was deleted: drop it from every project. */
+export function forgetGeneration(id: string) {
+ genCache.delete(id);
+ for (const p of Object.values(projects)) {
+ if (!p.items.some((i) => i.genId === id)) continue;
+ p.items = p.items.filter((i) => i.genId !== id);
+ p.meta = { ...p.meta, cover: lastCover(p.items), count: countOf(p.items) };
+ }
+ persistProjects();
+ setState((s) => {
+ const session = s.session.filter((i) => i.gen?.id !== id);
+ const refs = s.composer.refs.filter((r) => r.source !== `gen:${id}`);
+ return {
+ session,
+ projects: projectList(),
+ selected: session.some((i) => i.key === s.selected) ? s.selected : session[session.length - 1]?.key ?? null,
+ composer: refs.length === s.composer.refs.length ? s.composer : { ...s.composer, refs, mask: null, outpaint: null },
+ };
+ });
+}
+
// ---------------------------------------------------------------------------------------
// Actions
// ---------------------------------------------------------------------------------------
-export function addSessionItem(item: SessionItem, select = true) {
- setState((s) => ({ session: [...s.session, item], selected: select ? item.key : s.selected }));
+/** Makes `ref` the image being edited (image 1); other references stay. */
+function retarget(c: Composer, ref: Ref): Composer {
+ if (c.refs[0]?.source === ref.source) return c;
+ const rest = c.refs.slice(1).filter((r) => r.source !== ref.source);
+ return { ...c, refs: [ref, ...rest], mask: null, outpaint: null, aspect: "auto" };
+}
+
+/** Shows a version; an image also becomes the one the prompt edits. Choosing a version
+ * by hand ends the current Undo/Redo walk. */
+export function selectItem(key: string, keepRedo = false) {
+ setState((s) => {
+ const it = s.session.find((i) => i.key === key);
+ if (!it) return {};
+ const ref = it.gen ? refFromGen(it.gen) : it.input ? refFromInput(it.input) : null;
+ return { selected: key, composer: ref ? retarget(s.composer, ref) : s.composer, ...(keepRedo ? {} : { redo: [] }) };
+ });
+}
+
+const undoItems = (session: SessionItem[]) =>
+ session.map((i) => ({ key: i.key, source: itemSource(i), from: (i.gen?.request?.images?.[0] ?? (i.gen?.parent_id ? `gen:${i.gen.parent_id}` : null)) ?? i.request?.images?.[0] ?? null }));
+
+/** The version Undo goes back to (what the selected one was made from), if any. */
+export function undoKey(s: State): string | null {
+ return s.selected ? undoTarget(undoItems(s.session), s.selected) : null;
+}
+
+/** Back to the version the selected one was made from; the next edit starts from there. */
+export function undoVersion() {
+ const s = getState();
+ const target = undoKey(s);
+ if (!target || !s.selected) return;
+ const redo = [...s.redo, s.selected];
+ selectItem(target, true);
+ setState({ redo });
+}
+
+/** Forward again to the version left with Undo. */
+export function redoVersion() {
+ const s = getState();
+ const key = s.redo[s.redo.length - 1];
+ if (!key) return;
+ const redo = s.redo.slice(0, -1);
+ if (s.session.some((i) => i.key === key)) selectItem(key, true);
+ setState({ redo });
}
+/** New images: into an empty project (or with nothing being edited) they become versions to
+ * work on; while editing they are added as extra references. */
export function addInputs(records: InputRecord[]) {
if (!records.length) return;
setState((s) => {
- const refs = [...s.composer.refs, ...records.map(refFromInput)].slice(0, 10);
+ const added = records.map(refFromInput);
+ if (s.composer.refs.length && s.session.length) {
+ return { composer: { ...s.composer, refs: [...s.composer.refs, ...added].slice(0, 10), outpaint: null } };
+ }
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" },
+ composer: { ...s.composer, refs: [...s.composer.refs, ...added].slice(0, 10), mask: null, outpaint: null, aspect: "auto" },
session: [...s.session, ...items],
- selected: items[items.length - 1].key,
+ selected: items[0].key,
};
});
if (getState().composer.refs.length >= 10) toastInfo("Up to 10 reference images are supported.");
}
-export async function submitRequest(req: GenerationRequest, opts: { clearComposer?: boolean } = {}) {
+export async function submitRequest(req: GenerationRequest) {
try {
+ if (getState().privateMode) req = { ...req, private: true };
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,
- }));
+ setState((s) => ({ jobs: { ...s.jobs, [job.id]: job }, session: [...s.session, item], selected: item.key, redo: [] }));
+ return true;
} catch (e) {
toastError(e);
+ return false;
}
}
export async function submitComposer() {
const s = getState();
- const parent = s.session.find((i) => i.key === s.selected)?.gen?.id ?? null;
+ const target = s.composer.refs[0]?.source;
+ const parent = target?.startsWith("gen:") ? target.slice(4) : null;
const req = buildRequest(s.composer, parent);
- if (!req.prompt) {
+ if (!req.prompt && needsPrompt(s.composer)) {
toastInfo("Describe what to create or change.");
return;
}
- await submitRequest(req, { clearComposer: true });
+ if (await submitRequest(req)) {
+ setState((st) => ({ lastPrompt: req.prompt, composer: { ...st.composer, prompt: st.composer.prompt.trim() === req.prompt ? "" : st.composer.prompt, seed: null } }));
+ }
}
export async function cancelJob(jobId: string) {
@@ -244,29 +647,11 @@ export async function cancelJob(jobId: string) {
}
}
-/** 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. */
+/** Adds a version as an extra reference (or as the image to edit when there is none). */
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() {
@@ -274,10 +659,17 @@ export function focusPrompt() {
}
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 };
- });
+ const s = getState();
+ const removed = s.session.find((i) => i.key === key);
+ const session = s.session.filter((i) => i.key !== key);
+ const src = removed ? itemSource(removed) : null;
+ const refs = src ? s.composer.refs.filter((r) => r.source !== src) : s.composer.refs;
+ setState({ session, composer: refs.length === s.composer.refs.length ? s.composer : { ...s.composer, refs, mask: null, outpaint: null } });
+ if (s.selected === key) {
+ const next = session[session.length - 1];
+ if (next) selectItem(next.key);
+ else setState({ selected: null });
+ }
}
export function selectedItem(s: State): SessionItem | null {
diff --git a/src/lib/types.ts b/src/lib/types.ts
index af7d3fc..57f7eb6 100644
--- a/src/lib/types.ts
+++ b/src/lib/types.ts
@@ -1,7 +1,9 @@
-// Mirrors the qls-service JSON contract (crates/qls-core).
+// Mirrors the kokon-service JSON contract (crates/qls-core).
export type Mode = "auto" | "generate" | "edit" | "inpaint" | "outpaint" | "multi_reference" | "upscale";
export type ResolvedMode = Exclude<Mode, "auto">;
+/** What an inpaint does in the painted area. */
+export type InpaintAction = "edit" | "remove" | "replace" | "add";
export type Quality = "fast" | "balanced" | "quality";
export type ResolutionMode = "auto" | "source" | "1k" | "1.5k" | "2k" | "custom";
export type OutputFormat = "png" | "jpeg" | "webp";
@@ -37,6 +39,7 @@ export interface GenerationRequest {
mode: Mode;
images: string[];
mask?: string | null;
+ inpaint_action?: InpaintAction;
outpaint?: OutpaintSpec | null;
quality: Quality;
resolution: ResolutionMode;
@@ -49,6 +52,8 @@ export interface GenerationRequest {
client?: string;
parent_id?: string | null;
upscale?: UpscaleSpec | null;
+ /** Private mode: kept out of the gallery and the output folder, deleted when it ends. */
+ private?: boolean;
}
export interface WorkingCanvas { source: Size; content: Size; canvas: Size; content_offset: [number, number]; scale: number }
@@ -56,6 +61,8 @@ export interface RefPlan { index: number; source: Size; canvas: WorkingCanvas }
export interface Plan {
mode: ResolvedMode;
+ /** Inpaint action actually run (a "remove ..." prompt makes an edit a removal). */
+ inpaint_action?: InpaintAction | null;
auto_mode: boolean;
mode_reason: string;
output: Size;
@@ -215,9 +222,64 @@ export interface AppConfig {
keepServerRunning: boolean;
idleUnloadMinutes: number;
setupComplete: boolean;
+ /** Hardware preset chosen in the setup wizard. */
+ hardwarePreset: string;
+ /** Plan as if the GPU had this much VRAM (MiB); 0 = detected. */
+ vramOverrideMib: number;
ui: Record<string, unknown>;
}
+export type InstallItemState = "present" | "pending" | "downloading" | "verifying" | "extracting" | "done" | "failed" | "cancelled";
+
+export interface InstallItem {
+ id: string;
+ label: string;
+ kind: "engine" | "model" | "optional";
+ size: number;
+ received: number;
+ state: InstallItemState;
+ error: string | null;
+ hint: string | null;
+ url: string;
+ page: string;
+ path: string;
+}
+
+export interface InstallStatus {
+ running: boolean;
+ complete: boolean;
+ preset: string | null;
+ sdcpp_dir: string | null;
+ items: InstallItem[];
+ bytes_per_sec: number;
+}
+
+export interface HardwarePreset {
+ id: string;
+ label: string;
+ summary: string;
+ verified: boolean;
+ min_vram_mib: number;
+ files: InstallItem[];
+ download_bytes: number;
+ disk_bytes: number;
+}
+
+export interface HardwareReport {
+ gpu: StatusResponse["gpu"];
+ nvidia: boolean;
+ vram_mib: number | null;
+ vram_simulated: boolean;
+ ram_total_mib: number;
+ recommended: string;
+ current: string;
+ presets: HardwarePreset[];
+ sdcpp_dir: string;
+ default_sdcpp_dir: string;
+ free_bytes: number | null;
+ issues_url: string;
+}
+
export type ServiceEvent =
| { type: "job"; job: JobView }
| { type: "server"; state: ServerState; owned: boolean; error: AppErrorBody | null }
diff --git a/src/styles.css b/src/styles.css
index 7613cd8..6496035 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -14,6 +14,7 @@
--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;
+ --sidebar: #f9f9f9;
--radius: 14px;
--font: "Inter Variable", "Inter", "Segoe UI Variable Text", "Segoe UI", system-ui, sans-serif;
color-scheme: light;
@@ -34,6 +35,7 @@
--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;
+ --sidebar: #1d1d1d;
color-scheme: dark;
}
}
@@ -58,10 +60,30 @@ button:disabled { cursor: default; opacity: 0.4; }
::selection { background: var(--surface-3); }
svg { display: block; flex: none; }
-.app { display: flex; flex-direction: column; height: 100%; }
+.app { display: flex; height: 100%; }
+.workspace { flex: 1; min-width: 0; display: flex; flex-direction: column; }
+
+/* ---------- sidebar: new / all images / projects ---------- */
+.sidebar { width: 260px; flex: none; background: var(--sidebar); display: flex; flex-direction: column; min-height: 0; }
+.side-head { height: 48px; display: flex; align-items: center; padding: 0 8px; flex: none; }
+.side-nav { display: flex; flex-direction: column; gap: 1px; padding: 0 8px 8px; }
+.side-item { display: flex; align-items: center; gap: 10px; height: 36px; padding: 0 10px; border-radius: 10px; color: var(--text); font-size: 14px; text-align: left; }
+.side-item:hover, .side-item.on { background: var(--surface-2); }
+.side-label { font-size: 12px; color: var(--text-3); padding: 12px 18px 6px; }
+.side-list { flex: 1; overflow-y: auto; padding: 0 8px 12px; display: flex; flex-direction: column; gap: 1px; scrollbar-width: thin; }
+.proj { display: flex; align-items: center; gap: 10px; padding: 6px; border-radius: 10px; cursor: pointer; position: relative; outline-offset: -2px; }
+.proj:hover, .proj.on { background: var(--surface-2); }
+.proj .cover { width: 40px; height: 40px; border-radius: 8px; overflow: hidden; background: var(--surface-3); flex: none; }
+.proj .cover img { width: 100%; height: 100%; object-fit: cover; display: block; }
+.proj-text { flex: 1; min-width: 0; display: flex; flex-direction: column; }
+.proj-title { font-size: 13px; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.proj-sub { font-size: 11px; color: var(--text-3); white-space: nowrap; }
+.proj-rm { width: 24px; height: 24px; border-radius: 7px; display: none; place-items: center; color: var(--text-2); flex: none; }
+.proj:hover .proj-rm { display: grid; }
+.proj-rm:hover { background: var(--surface-3); color: var(--text); }
/* ---------- top bar ---------- */
-.topbar { height: 48px; display: flex; align-items: center; justify-content: space-between; padding: 0 12px 0 16px; flex: none; }
+.topbar { height: 48px; display: flex; align-items: center; justify-content: space-between; gap: 12px; 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); }
@@ -69,7 +91,16 @@ svg { display: block; flex: none; }
.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; }
+.toolbar { display: flex; gap: 2px; align-items: center; flex: none; }
+.toolbar .status { margin-right: 8px; }
+.brand { min-width: 0; gap: 4px; }
+.brand .project-title { font-size: 14px; font-weight: 500; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; display: flex; align-items: center; gap: 6px; height: 32px; padding: 0 8px; border-radius: 8px; min-width: 0; max-width: 100%; }
+.brand button.project-title:hover { background: var(--surface); }
+.brand .project-title.placeholder { color: var(--text-3); font-weight: 400; }
+.project-title .title-pencil { opacity: 0; color: var(--text-3); }
+.project-title:hover .title-pencil { opacity: 1; }
+.name-field { font: inherit; font-size: 13px; color: var(--text); background: var(--bg); border: 1px solid var(--text-3); border-radius: 6px; padding: 2px 6px; outline: none; min-width: 0; width: 100%; user-select: text; }
+.name-field.title-field { font-size: 14px; font-weight: 500; height: 32px; padding: 0 8px; width: min(480px, 50vw); }
.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); }
@@ -83,10 +114,15 @@ svg { display: block; flex: none; }
.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; }
+/* the line under the image: version, what made it, compare, actions */
+.stage-bar { width: 100%; max-width: 820px; display: flex; align-items: center; gap: 10px; margin-top: 8px; min-height: 36px; }
+.stage-meta { flex: 1; min-width: 0; display: flex; align-items: center; gap: 8px; font-size: 12px; color: var(--text-3); }
+.stage-meta .ver { font-weight: 600; color: var(--text); font-size: 13px; flex: none; }
+.stage-meta .mode { flex: none; padding: 1px 7px; border-radius: 6px; background: var(--surface); color: var(--text-2); }
+.stage-meta .stage-prompt { flex: 1; min-width: 0; color: var(--text-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.stage-meta .dims { flex: none; }
-.actions { display: flex; gap: 2px; margin-top: 8px; padding: 3px; border-radius: 12px; }
+.actions { display: flex; gap: 2px; flex: none; }
.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; }
@@ -99,6 +135,8 @@ svg { display: block; flex: none; }
.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-src { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; opacity: 0.35; filter: blur(2px) saturate(0.6); }
+.pending-title { color: var(--text); font-weight: 600; font-size: 14px; }
.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; }
@@ -108,23 +146,43 @@ svg { display: block; flex: none; }
.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; }
+/* version timeline: Original -> v1 -> v2 ... */
+.timeline { flex: none; display: flex; align-items: flex-start; max-width: 100%; overflow-x: auto; padding: 12px 4px 2px; scrollbar-width: none; }
+.timeline::-webkit-scrollbar { display: none; }
+.timeline .link { flex: none; width: 14px; height: 1.5px; background: var(--surface-3); margin-top: 24px; }
+.frame { flex: none; display: flex; flex-direction: column; align-items: center; gap: 5px; padding: 0 2px; color: var(--text-3); }
+.frame-img { width: 48px; height: 48px; border-radius: 10px; overflow: hidden; background: var(--surface); position: relative; display: grid; place-items: center; outline: 2px solid transparent; outline-offset: 2px; }
+.frame-img img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
+.frame-img img.dim { opacity: 0.35; filter: blur(1px); }
+.frame-state { position: relative; color: var(--text); display: grid; place-items: center; }
+.frame:hover .frame-img { outline-color: var(--surface-3); }
+.frame.sel .frame-img { outline-color: var(--text); }
+.frame.sel { color: var(--text); }
+.frame-label { display: flex; align-items: center; gap: 3px; font-size: 11px; line-height: 1; white-space: nowrap; }
+.frame-badge { position: absolute; right: 3px; bottom: 3px; width: 17px; height: 17px; border-radius: 5px; background: var(--invert-bg); color: var(--invert-text); display: grid; place-items: center; }
/* ---------- 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; }
+/* what the prompt works on */
+.target { display: flex; align-items: center; gap: 10px; padding: 2px 0 10px; margin-bottom: 6px; border-bottom: 1px solid var(--border); min-width: 0; }
+.target .spacer { flex: 1; }
+.target-icon { width: 40px; height: 40px; border-radius: 10px; background: var(--surface-2); display: grid; place-items: center; color: var(--text-2); flex: none; }
+.target-text { display: flex; flex-direction: column; min-width: 0; }
+.target-text .what { font-size: 13px; font-weight: 600; color: var(--text); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.target-text .sub { font-size: 12px; color: var(--text-3); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.tool-group { display: inline-flex; align-items: center; flex: none; }
+.tool { height: 30px; padding: 0 10px; border-radius: 15px; display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: var(--text-2); white-space: nowrap; flex: none; }
+.tool:hover, .tool.on { background: var(--surface-2); color: var(--text); }
+.tool-group .tool.on { border-radius: 15px 0 0 15px; padding-right: 6px; }
+.tool-x { height: 30px; padding: 0 8px 0 4px; border-radius: 0 15px 15px 0; background: var(--surface-2); color: var(--text-2); display: grid; place-items: center; }
+.tool-x:hover { color: var(--text); }
+.refs { display: flex; gap: 6px; overflow-x: auto; scrollbar-width: none; flex: none; max-width: 45%; padding: 6px 6px 0 0; margin-top: -6px; }
+.ref { position: relative; width: 40px; height: 40px; 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 .num { position: absolute; left: 3px; top: 3px; 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: 18px; height: 18px; 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; }
@@ -149,6 +207,11 @@ svg { display: block; flex: none; }
.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; }
+.add-menu { width: 300px; }
+.add-grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; padding: 6px 8px 8px; max-height: 240px; overflow-y: auto; }
+.add-grid button { display: flex; flex-direction: column; align-items: center; gap: 3px; font-size: 11px; color: var(--text-2); }
+.add-grid img { width: 100%; aspect-ratio: 1; object-fit: cover; border-radius: 8px; background: var(--surface); outline: 2px solid transparent; outline-offset: 1px; }
+.add-grid button:hover img { outline-color: var(--text-2); }
.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; }
@@ -241,13 +304,41 @@ pre.diag { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font
.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; }
+.private-pill { display: inline-flex; align-items: center; gap: 6px; height: 30px; padding: 0 12px; border-radius: 999px; border: 0; background: var(--invert-bg); color: var(--invert-text); font: inherit; font-size: 13px; cursor: pointer; }
+.setup { flex: 1; display: flex; justify-content: center; overflow-y: auto; padding: 40px 24px 0; }
+/* Bottom room inside the scroller (padding on the scroller itself is dropped by Chromium). */
+.setup-inner { width: 100%; max-width: 640px; display: flex; flex-direction: column; gap: 20px; padding-bottom: 72px; height: fit-content; }
+.setup h1 { font-size: 26px; letter-spacing: -0.02em; margin: 0 0 6px; }
+.setup-lead { font-size: 14px; color: var(--text-2); margin: 0; line-height: 1.5; }
+.setup-card { display: flex; gap: 10px; align-items: center; padding: 14px 16px; background: var(--surface); border-radius: 12px; }
+.setup-gpu { flex-direction: column; align-items: flex-start; gap: 2px; }
+.setup-note { font-size: 13px; color: var(--text-2); padding: 12px 14px; border: 1px solid var(--border); border-radius: 12px; line-height: 1.45; }
+.setup-failure { display: flex; flex-direction: column; gap: 6px; padding-top: 10px; margin-top: 10px; border-top: 1px solid var(--border); font-size: 12px; word-break: break-word; }
+.setup-failure strong { color: var(--text); font-size: 13px; }
+.setup-progress { flex-direction: column; align-items: stretch; gap: 10px; padding: 18px 18px 16px; }
+.setup-progress-head { display: flex; align-items: baseline; gap: 12px; flex-wrap: wrap; }
+.setup-progress .pct { font-size: 30px; font-weight: 600; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }
+.setup-progress .muted { font-variant-numeric: tabular-nums; }
+.progress.thick { width: 100%; height: 6px; border-radius: 3px; }
+.progress.thick > i { border-radius: 3px; }
+.setup-ready { font-size: 14px; }
+.setup-toggle { display: inline-flex; align-items: center; gap: 6px; align-self: flex-start; font-size: 13px; color: var(--text-2); padding: 2px 0; background: none; border: 0; cursor: pointer; }
+.setup-toggle:hover { color: var(--text); }
+.setup-files { display: flex; flex-direction: column; border: 1px solid var(--border); border-radius: 12px; overflow: hidden; }
+.setup-file { display: grid; grid-template-columns: 16px 1fr auto; gap: 10px; align-items: center; padding: 9px 14px; font-size: 13px; border-top: 1px solid var(--border); }
+.setup-file:first-child { border-top: 0; }
+.setup-file .name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.setup-file .state { font-size: 12px; color: var(--text-3); font-variant-numeric: tabular-nums; }
+.setup-file.present, .setup-file.done { color: var(--text-2); }
+.setup-file.failed .state { color: var(--text); font-weight: 600; }
+.setup-actions { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
+.btn.big { height: 42px; padding: 0 20px; font-size: 14px; border-radius: 12px; }
+.btn.ghost { background: transparent; color: var(--text-2); }
+.setup-foot { margin: 0; line-height: 1.5; }
/* before / after comparison */
-.compare-bar { display: flex; gap: 8px; margin-top: 8px; align-items: center; }
-.compare-bar .seg { min-width: 300px; }
+.compare-bar { display: flex; gap: 8px; align-items: center; flex: none; }
+.compare-bar .seg { min-width: 260px; }
.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; }