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.

CLA for contributors; example gallery, tour, installer hooks

Gabriele Lozuponecba3a0a0bad1
diff --git a/.github/workflows/cla.yml b/.github/workflows/cla.yml
new file mode 100644
index 0000000..e6ceaa4
--- /dev/null
+++ b/.github/workflows/cla.yml
@@ -0,0 +1,30 @@
+# Asks first-time contributors to sign CLA.md with a comment on their pull request.
+# Signatures are stored in signatures/cla.json on the `cla-signatures` branch.
+name: CLA
+
+on:
+ issue_comment:
+ types: [created]
+ pull_request_target:
+ types: [opened, closed, synchronize]
+
+permissions:
+ actions: write
+ contents: write
+ pull-requests: write
+ statuses: write
+
+jobs:
+ cla:
+ runs-on: ubuntu-latest
+ steps:
+ - name: CLA check
+ if: (github.event.comment.body == 'recheck' || github.event.comment.body == 'I have read the CLA Document and I hereby sign the CLA') || github.event_name == 'pull_request_target'
+ uses: contributor-assistant/[email protected]
+ env:
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ with:
+ path-to-signatures: signatures/cla.json
+ path-to-document: https://github.com/GabrieleLozupone/kokon/blob/master/CLA.md
+ branch: cla-signatures
+ allowlist: GabrieleLozupone,dependabot[bot]
diff --git a/CLA.md b/CLA.md
new file mode 100644
index 0000000..cc8ad10
--- /dev/null
+++ b/CLA.md
@@ -0,0 +1,48 @@
+# Kokon Contributor License Agreement
+
+Thank you for contributing to Kokon. This agreement is between you ("You") and Gabriele
+Lozupone, the maintainer and copyright holder of Kokon ("the Maintainer"). It applies to every
+contribution You submit to the Kokon project (https://github.com/GabrieleLozupone/kokon), such
+as code, documentation, images or translations ("Contributions").
+
+You sign it by posting the comment requested by the CLA bot on your pull request. You sign once;
+it covers all your future Contributions.
+
+## 1. You keep your copyright
+
+You keep the copyright on your Contributions. This agreement only grants the licenses below.
+
+## 2. Copyright license
+
+You grant the Maintainer, and anyone who receives software from the Maintainer, a perpetual,
+worldwide, non-exclusive, royalty-free, irrevocable license to use, reproduce, modify, prepare
+derivative works of, publicly display, publicly perform, distribute and sublicense Your
+Contributions and such derivative works, under any license terms, including the GNU AGPL-3.0
+and commercial or proprietary licenses.
+
+## 3. Patent license
+
+You grant the Maintainer, and anyone who receives software from the Maintainer, a perpetual,
+worldwide, non-exclusive, royalty-free, irrevocable patent license to make, use, sell, offer to
+sell, import and otherwise transfer Your Contributions, alone or combined with Kokon, for any
+patent claims You can license that Your Contributions would otherwise infringe.
+
+## 4. The project stays open source
+
+Every Contribution that the Maintainer includes in Kokon will also stay available under the GNU
+AGPL-3.0 or a later version of that license.
+
+## 5. What You confirm
+
+- Each Contribution is Your original work, or You have the right to submit it under this
+ agreement. If it includes third-party material, You say so in the pull request and give its
+ license.
+- If Your employer or school has rights over what You create, You have permission to make the
+ Contribution under this agreement, or they have waived those rights.
+- You will tell the Maintainer if any of this stops being true.
+
+## 6. No obligation, no warranty
+
+The Maintainer does not have to use Your Contributions. You provide them "as is", without
+warranties or conditions of any kind, unless You agree otherwise in writing. You do not have to
+provide support for them.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index c3d757d..602bbb0 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -91,8 +91,11 @@ picked to be approachable. Also welcome:
## Licenses
-By contributing, you agree that your contribution is licensed under the
-[GNU Affero General Public License v3.0](LICENSE) (AGPL-3.0-only), like the rest of Kokon's code.
+Kokon's code is licensed under the [GNU AGPL-3.0](LICENSE). Before your first pull request is
+merged, a bot asks you to sign the [Contributor License Agreement](CLA.md) with a one-line
+comment. You keep the copyright on your work; the CLA lets the project ship it under the
+AGPL and, if needed, under a commercial license too. Contributions are always also available
+under the AGPL.
Model weights are not part of this repository. Kokon downloads them from their authors, and
they keep their own licenses (see [NOTICE](NOTICE)). Please don't commit model files or other
diff --git a/NOTICE b/NOTICE
index b56f2f3..62e4e98 100644
--- a/NOTICE
+++ b/NOTICE
@@ -1,7 +1,9 @@
Kokon
Copyright 2026 Gabriele Lozupone
-This product is licensed under the GNU Affero General Public License, version 3 only (AGPL-3.0-only, see LICENSE).
+This product is licensed under the GNU Affero General Public License, version 3 only
+(AGPL-3.0-only, see LICENSE). Commercial licenses for uses the AGPL does not allow are
+available from the copyright holder (see the README).
Model weights and the upscaler that Kokon downloads at setup are not part of this product;
they come from their authors under their own licenses (see the README).
diff --git a/README.md b/README.md
index b9833ad..8a5ac4d 100644
--- a/README.md
+++ b/README.md
@@ -504,8 +504,8 @@ with a plain resize instead.
<summary><b>How do I uninstall it?</b></summary>
<br>
-**Windows:** Settings → Apps → Installed apps → Kokon → Uninstall. To free the model space too,
-delete `%LOCALAPPDATA%\KokonData`.
+**Windows:** Settings → Apps → Installed apps → Kokon → Uninstall. The uninstaller asks whether to
+delete the downloaded models and app data too (`%LOCALAPPDATA%\KokonData`).
**Mac:** drag Kokon from Applications to the Trash. To free the model space too, delete
`~/Library/Application Support/KokonData`.
@@ -609,9 +609,17 @@ images of someone without their consent. You are responsible for what you create
## License
-Kokon's source code is released under the [GNU Affero General Public License v3.0](LICENSE) (AGPL-3.0-only). Model weights and the
-upscaler are downloaded from their authors and keep their own licenses (see the
-[FAQ](#faq)).
+Kokon's source code is released under the [GNU Affero General Public License v3.0](LICENSE)
+(AGPL-3.0-only). You can use, study, change and share it freely. If you distribute a modified
+version, or offer one as a network service, you must publish its source under the same
+license. The license covers the code, not the images you make with it.
+
+Want to ship Kokon inside a closed-source product or service? A commercial license is
+available: open a [discussion](https://github.com/GabrieleLozupone/kokon/discussions) or
+contact the author.
+
+Model weights and the upscaler are downloaded from their authors and keep their own licenses
+(see the [FAQ](#faq)).
Kokon builds on [stable-diffusion.cpp](https://github.com/leejet/stable-diffusion.cpp) by
leejet, [Qwen-Image 2.1](https://huggingface.co/Qwen/Qwen-Image-2.1) and its Turbo model by the
diff --git a/assets/examples/bakery-text.jpg b/assets/examples/bakery-text.jpg
new file mode 100644
index 0000000..05d2050
Binary files /dev/null and b/assets/examples/bakery-text.jpg differ
diff --git a/assets/examples/bakery.jpg b/assets/examples/bakery.jpg
new file mode 100644
index 0000000..e85618f
Binary files /dev/null and b/assets/examples/bakery.jpg differ
diff --git a/assets/examples/cabin-winter.jpg b/assets/examples/cabin-winter.jpg
new file mode 100644
index 0000000..931fbba
Binary files /dev/null and b/assets/examples/cabin-winter.jpg differ
diff --git a/assets/examples/cabin.jpg b/assets/examples/cabin.jpg
new file mode 100644
index 0000000..6a30a02
Binary files /dev/null and b/assets/examples/cabin.jpg differ
diff --git a/assets/examples/lighthouse-wide.jpg b/assets/examples/lighthouse-wide.jpg
new file mode 100644
index 0000000..becf5f9
Binary files /dev/null and b/assets/examples/lighthouse-wide.jpg differ
diff --git a/assets/examples/lighthouse.jpg b/assets/examples/lighthouse.jpg
new file mode 100644
index 0000000..0b1a2d5
Binary files /dev/null and b/assets/examples/lighthouse.jpg differ
diff --git a/assets/examples/potter-watercolor.jpg b/assets/examples/potter-watercolor.jpg
new file mode 100644
index 0000000..a1327ea
Binary files /dev/null and b/assets/examples/potter-watercolor.jpg differ
diff --git a/assets/examples/potter.jpg b/assets/examples/potter.jpg
new file mode 100644
index 0000000..d06103d
Binary files /dev/null and b/assets/examples/potter.jpg differ
diff --git a/assets/examples/street-add-mask.png b/assets/examples/street-add-mask.png
new file mode 100644
index 0000000..0215966
Binary files /dev/null and b/assets/examples/street-add-mask.png differ
diff --git a/assets/examples/street-cat.jpg b/assets/examples/street-cat.jpg
new file mode 100644
index 0000000..9262560
Binary files /dev/null and b/assets/examples/street-cat.jpg differ
diff --git a/assets/examples/street-mask.png b/assets/examples/street-mask.png
new file mode 100644
index 0000000..9ee490f
Binary files /dev/null and b/assets/examples/street-mask.png differ
diff --git a/assets/examples/street-removed.jpg b/assets/examples/street-removed.jpg
new file mode 100644
index 0000000..24b3522
Binary files /dev/null and b/assets/examples/street-removed.jpg differ
diff --git a/assets/examples/street.jpg b/assets/examples/street.jpg
new file mode 100644
index 0000000..1322aef
Binary files /dev/null and b/assets/examples/street.jpg differ
diff --git a/crates/qls-core/Cargo.toml b/crates/qls-core/Cargo.toml
index 4702a60..fde5dab 100644
--- a/crates/qls-core/Cargo.toml
+++ b/crates/qls-core/Cargo.toml
@@ -1,6 +1,7 @@
[package]
name = "qls-core"
version.workspace = true
+license.workspace = true
edition.workspace = true
[dependencies]
diff --git a/crates/qls-core/src/engine.rs b/crates/qls-core/src/engine.rs
index dcd6236..2861ab8 100644
--- a/crates/qls-core/src/engine.rs
+++ b/crates/qls-core/src/engine.rs
@@ -694,7 +694,11 @@ impl Engine {
let mut records = Vec::with_capacity(contents.len());
for (i, content) in contents.into_iter().enumerate() {
let before = Size::new(content.width(), content.height());
- let (content, enlarged_with) = self.enlarge(id, &client, content, pipeline::enlarge_target(&post), esrgan.as_deref()).await?;
+ let target = pipeline::enlarge_target(&post);
+ // Kept when the upscaler enlarges it, so the user can still see and save it.
+ let original = target.map(|_| content.clone());
+ let (content, enlarged_with) = self.enlarge(id, &client, content, target, esrgan.as_deref()).await?;
+ let original = original.filter(|_| enlarged_with.is_some());
self.update(id, |j| {
j.view.status = JobStatus::Saving;
j.view.stage = None;
@@ -708,6 +712,7 @@ impl Engine {
cache_threshold: None,
enlarged_from: enlarged_with.is_some().then_some(before),
enlarged_with,
+ original_path: None, // set when the original is saved
};
let this = self.clone();
let mut plan3 = plan.clone();
@@ -720,7 +725,7 @@ impl Engine {
let final_img = pipeline::finish(content, &p)?;
let duration_ms = duration_start.elapsed().as_millis() as u64;
let pipeline = (pipeline_rec != PipelineRecord::default()).then_some(pipeline_rec);
- this.save_result(&final_img, &req3, &plan3, seed + i as i64, &inputs3, mask3.as_ref(), icc3.as_deref(), duration_ms, ws.as_deref(), i, pipeline)
+ 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, original.as_ref())
})
.await?;
if !request.private {
@@ -879,7 +884,8 @@ impl Engine {
duration_ms: u64,
workspace: Option<&Path>,
index: usize,
- pipeline: Option<PipelineRecord>,
+ mut pipeline: Option<PipelineRecord>,
+ original: Option<&image::RgbaImage>,
) -> AppResult<GenerationRecord> {
let cfg = self.config();
let id = new_id();
@@ -894,6 +900,21 @@ impl Engine {
let format = if hdr.is_some() { OutputFormat::Jpeg } else { plan.output_format };
let file = paths::unique_path(dir.join(format!("{stem}.{}", format.ext())), &[]);
+ if let Some(o) = original {
+ let path = store.original_path(&id);
+ let saved = (|| {
+ if let Some(d) = path.parent() {
+ std::fs::create_dir_all(d).map_err(|e| AppError::io("create the originals folder", d, e))?;
+ }
+ write_atomic(&path, &imaging::encode_png(o, &[], icc, true)?)
+ })();
+ match (saved, pipeline.as_mut()) {
+ (Ok(()), Some(p)) => p.original_path = Some(path.to_string_lossy().into_owned()),
+ (Err(e), _) => tracing::warn!("could not keep the pre-upscale image of {id}: {} {:?}", e.message, e.detail),
+ _ => {}
+ }
+ }
+
let mode = match plan.mode {
ResolvedMode::Generate => "generate",
ResolvedMode::Edit => "edit",
diff --git a/crates/qls-core/src/examples.rs b/crates/qls-core/src/examples.rs
new file mode 100644
index 0000000..00b2a4d
--- /dev/null
+++ b/crates/qls-core/src/examples.rs
@@ -0,0 +1,217 @@
+//! Example projects added on the first launch: real results made by Kokon (see
+//! `marketing/showcase/PROMPTS.md`, resized by `scripts/make-examples.py`), stored as
+//! ordinary generations so they open, compare and edit like the user's own work.
+
+use std::path::Path;
+
+use serde::Serialize;
+
+use crate::engine::{APP_VERSION, Engine};
+use crate::error::{AppError, AppResult};
+use crate::geometry::Expansion;
+use crate::imaging;
+use crate::planner::{GenerationRequest, InpaintAction, Mode, OutpaintSpec, Quality};
+use crate::store::{GenerationRecord, InputRecord, ReferenceRecord};
+
+/// One version of an example: made from the previous step of its project (none for the first).
+struct Step {
+ name: &'static str,
+ image: &'static [u8],
+ mode: Mode,
+ prompt: &'static str,
+ seed: i64,
+ quality: Quality,
+ seconds: u64,
+ inpaint: Option<(InpaintAction, &'static [u8])>,
+ /// Outpaint: expansion in pixels of the previous step.
+ expand: Option<Expansion>,
+}
+
+struct Project {
+ title: &'static str,
+ steps: &'static [Step],
+}
+
+macro_rules! asset {
+ ($f:literal) => {
+ include_bytes!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../assets/examples/", $f))
+ };
+}
+
+const fn step(name: &'static str, image: &'static [u8], mode: Mode, prompt: &'static str, seed: i64, quality: Quality, seconds: u64) -> Step {
+ Step { name, image, mode, prompt, seed, quality, seconds, inpaint: None, expand: None }
+}
+
+/// The first project is the one the tour walks through.
+static PROJECTS: &[Project] = &[
+ Project {
+ title: "Italian street café",
+ steps: &[
+ step("street", asset!("street.jpg"), Mode::Generate, "Editorial photograph of a sunny cobblestone street in a small Italian coastal town, a pastel yellow café with outdoor wooden tables and potted lemon trees, a red vintage scooter parked in front of the café, warm late-morning light, 35mm, shallow depth of field, highly detailed, realistic", 1101, Quality::Quality, 46),
+ Step { inpaint: Some((InpaintAction::Remove, asset!("street-mask.png"))), ..step("street-removed", asset!("street-removed.jpg"), Mode::Inpaint, "the red scooter", 7, Quality::Quality, 33) },
+ Step { inpaint: Some((InpaintAction::Add, asset!("street-add-mask.png"))), ..step("street-cat", asset!("street-cat.jpg"), Mode::Inpaint, "a ginger cat sitting on the cobblestones, looking at the camera", 13, Quality::Quality, 31) },
+ ],
+ },
+ Project {
+ title: "Lake cabin, summer to winter",
+ steps: &[
+ step("cabin", asset!("cabin.jpg"), Mode::Generate, "Photograph of a small wooden cabin with a stone chimney on the shore of a calm alpine lake, pine forest and tall mountains behind, clear summer midday, crisp reflections on the water, wide angle, highly detailed, realistic landscape photography", 2202, Quality::Quality, 39),
+ step("cabin-winter", asset!("cabin-winter.jpg"), Mode::Edit, "Make it a snowy winter night: snow on the roof, trees and shore, the lake partly frozen, warm golden light glowing from the cabin windows, stars in the sky. Keep the composition unchanged.", 3, Quality::Quality, 53),
+ ],
+ },
+ Project {
+ title: "Paris bakery sign",
+ steps: &[
+ step("bakery", asset!("bakery.jpg"), Mode::Generate, "Photograph of a charming bakery storefront in Paris, dark green painted wooden facade, large gold lettering sign above the window that reads \"BOULANGERIE\", window display full of croissants and baguettes, flower boxes, soft morning light, realistic, highly detailed", 3303, Quality::Quality, 39),
+ step("bakery-text", asset!("bakery-text.jpg"), Mode::Edit, "Change the gold sign text to \"KOKON CAFÉ\" in the same gold lettering style. Keep everything else unchanged.", 5, Quality::Quality, 54),
+ ],
+ },
+ Project {
+ title: "Lighthouse, wider",
+ steps: &[
+ step("lighthouse", asset!("lighthouse.jpg"), Mode::Generate, "Photograph of a white and red lighthouse on a rocky cliff above a turquoise sea, golden sunset light, gentle waves, a few seagulls, realistic, highly detailed, coastal landscape photography", 6606, Quality::Balanced, 22),
+ Step { expand: Some(Expansion { left: 355, right: 356, top: 0, bottom: 0 }), ..step("lighthouse-wide", asset!("lighthouse-wide.jpg"), Mode::Outpaint, "continue the rocky coastline and the turquoise sea at golden sunset", 9, Quality::Balanced, 55) },
+ ],
+ },
+ Project {
+ title: "Potter, as a watercolor",
+ steps: &[
+ step("potter", asset!("potter.jpg"), Mode::Generate, "Portrait photograph of a young ceramic artist in her sunlit studio, holding a freshly glazed blue bowl, shelves of handmade pottery behind her, linen apron, natural window light, warm and friendly expression, 85mm lens, realistic, highly detailed", 4404, Quality::Quality, 38),
+ step("potter-watercolor", asset!("potter-watercolor.jpg"), Mode::Edit, "Turn it into a hand-painted watercolor illustration with soft ink outlines and visible paper texture. Keep the person, pose and composition the same.", 11, Quality::Quality, 55),
+ ],
+ },
+];
+
+/// An example project as the desktop app stores it: a title and its versions, oldest first.
+#[derive(Debug, Clone, Serialize)]
+pub struct ExampleProject {
+ pub title: String,
+ pub generations: Vec<String>,
+}
+
+impl Engine {
+ /// Adds the example projects to the gallery (again, if they were deleted) and returns
+ /// them. Ids are fixed, so calling this twice does not duplicate anything.
+ pub fn install_examples(&self) -> AppResult<Vec<ExampleProject>> {
+ let store = &self.store;
+ let dir = store.examples_dir();
+ std::fs::create_dir_all(&dir).map_err(|e| AppError::io("create the examples folder", &dir, e))?;
+ let model = self.config().profile().model_name();
+ let mut out = Vec::new();
+ for (pi, project) in PROJECTS.iter().enumerate() {
+ let mut prev: Option<GenerationRecord> = None;
+ let mut ids = Vec::new();
+ for (si, s) in project.steps.iter().enumerate() {
+ let id = format!("example-{}", s.name);
+ if let Ok(g) = store.get_generation(&id)
+ && Path::new(&g.file_path).is_file()
+ {
+ ids.push(id);
+ prev = Some(g);
+ continue;
+ }
+ let file = dir.join(format!("{}.jpg", s.name));
+ std::fs::write(&file, s.image).map_err(|e| AppError::io("store the example", &file, e))?;
+ let img = imaging::decode_image(s.image)?.pixels;
+ // The previous version as this one's reference, the way an edit records it.
+ let reference: Option<InputRecord> = match &prev {
+ Some(p) => Some(store.put_input(&std::fs::read(&p.file_path).map_err(|e| AppError::io("read the example", Path::new(&p.file_path), e))?, Some(&format!("{}.jpg", p.id)), Some(&p.file_path))?),
+ None => None,
+ };
+ let mask = match s.inpaint {
+ Some((_, png)) => Some(store.put_input(png, Some("mask.png"), None)?),
+ None => None,
+ };
+ let request = GenerationRequest {
+ prompt: s.prompt.into(),
+ mode: s.mode,
+ images: prev.iter().map(|p| format!("gen:{}", p.id)).collect(),
+ mask: mask.as_ref().map(|m| format!("input:{}", m.id)),
+ inpaint_action: s.inpaint.map(|(a, _)| a).unwrap_or_default(),
+ outpaint: s.expand.map(|e| OutpaintSpec { left: e.left as f64, right: e.right as f64, top: e.top as f64, bottom: e.bottom as f64, ..Default::default() }),
+ quality: s.quality,
+ seed: Some(s.seed),
+ client: Some("example".into()),
+ parent_id: prev.as_ref().map(|p| p.id.clone()),
+ preserve_dimensions: true,
+ ..Default::default()
+ };
+ let mode = serde_json::to_value(s.mode).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or_default();
+ let rec = GenerationRecord {
+ id: id.clone(),
+ // Older than anything the user makes, in project order.
+ created_at: format!("2026-10-10T09:{:02}:{:02}.000Z", pi * 5, si * 10),
+ mode,
+ prompt: s.prompt.into(),
+ negative_prompt: String::new(),
+ seed: s.seed,
+ width: img.width(),
+ height: img.height(),
+ working_width: img.width(),
+ working_height: img.height(),
+ model: model.clone(),
+ sampler: "euler".into(),
+ scheduler: None,
+ steps: 8,
+ cfg: 1.0,
+ strength: None,
+ quality: serde_json::to_value(s.quality).ok().and_then(|v| v.as_str().map(str::to_owned)).unwrap_or_default(),
+ resolution: "auto".into(),
+ references: reference
+ .iter()
+ .map(|r| ReferenceRecord { index: 0, input_id: r.id.clone(), original_path: r.original_path.clone(), width: r.width, height: r.height })
+ .collect(),
+ mask_input_id: mask.map(|m| m.id),
+ outpaint: s.expand,
+ file_path: file.to_string_lossy().into_owned(),
+ extra_paths: vec![],
+ favorite: false,
+ parent_id: prev.as_ref().map(|p| p.id.clone()),
+ duration_ms: s.seconds * 1000,
+ notes: vec!["Example made by Kokon, resized for the installer.".into()],
+ app_version: APP_VERSION.into(),
+ backend_version: None,
+ client: Some("example".into()),
+ request: serde_json::to_value(&request).unwrap_or_default(),
+ pipeline: None,
+ };
+ if let Ok(j) = imaging::encode_jpeg(&imaging::thumbnail(&img, 512), 85) {
+ let _ = std::fs::write(store.thumb_path(&id), j);
+ }
+ store.insert_generation(&rec)?;
+ ids.push(id);
+ prev = Some(rec);
+ }
+ out.push(ExampleProject { title: project.title.into(), generations: ids });
+ }
+ Ok(out)
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn example_assets_match_their_chains() {
+ for p in PROJECTS {
+ let mut prev: Option<(u32, u32)> = None;
+ for s in p.steps {
+ let im = imaging::decode_image(s.image).unwrap().pixels;
+ let size = (im.width(), im.height());
+ if let Some((_, mask)) = s.inpaint {
+ let m = imaging::decode_image(mask).unwrap().pixels;
+ assert_eq!((m.width(), m.height()), prev.unwrap(), "{}: mask fits the image it was painted on", s.name);
+ }
+ if let Some(e) = s.expand {
+ let (w, h) = prev.unwrap();
+ assert_eq!(size, (w + e.left + e.right, h + e.top + e.bottom), "{}: expansion adds up", s.name);
+ }
+ if matches!(s.mode, Mode::Edit | Mode::Inpaint) {
+ assert_eq!(Some(size), prev, "{}: edits keep the size", s.name);
+ }
+ prev = Some(size);
+ }
+ }
+ }
+}
diff --git a/crates/qls-core/src/lib.rs b/crates/qls-core/src/lib.rs
index 730a26c..4c39f35 100644
--- a/crates/qls-core/src/lib.rs
+++ b/crates/qls-core/src/lib.rs
@@ -3,6 +3,7 @@ pub mod config;
pub mod diagnostics;
pub mod engine;
pub mod error;
+pub mod examples;
pub mod geometry;
pub mod hdr;
pub mod heif;
diff --git a/crates/qls-core/src/store.rs b/crates/qls-core/src/store.rs
index 6fd6447..c4b6e9d 100644
--- a/crates/qls-core/src/store.rs
+++ b/crates/qls-core/src/store.rs
@@ -40,6 +40,10 @@ pub struct PipelineRecord {
pub enlarged_with: Option<String>,
/// Size the content had before the final enlargement.
pub enlarged_from: Option<Size>,
+ /// The diffusion output before that enlargement (PNG in the store's `originals`), kept
+ /// so the result can be compared with it or saved without the upscaler.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub original_path: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
@@ -123,6 +127,9 @@ impl GenerationRecord {
pub fn png_text(&self) -> Vec<(&'static str, String)> {
let mut slim = self.clone();
slim.request = serde_json::Value::Null;
+ if let Some(p) = slim.pipeline.as_mut() {
+ p.original_path = None;
+ }
vec![
("parameters", self.parameters_text()),
("qls:generation", serde_json::to_string(&slim).unwrap_or_default()),
@@ -230,6 +237,16 @@ impl Store {
self.data_dir.join("thumbs").join(format!("{id}.jpg"))
}
+ /// The bundled example projects' images ([`crate::examples`]).
+ pub fn examples_dir(&self) -> PathBuf {
+ self.data_dir.join("examples")
+ }
+
+ /// Where a result's pre-enlargement image is kept ([`PipelineRecord::original_path`]).
+ pub fn original_path(&self, id: &str) -> PathBuf {
+ self.data_dir.join("originals").join(format!("{id}.png"))
+ }
+
pub fn insert_generation(&self, r: &GenerationRecord) -> AppResult<()> {
let json = serde_json::to_string(r).map_err(AppError::internal)?;
self.conn
@@ -306,15 +323,17 @@ impl Store {
Ok(())
}
- /// Removes the record, its image file (only if inside the app output folder) and thumbnail.
+ /// Removes the record, its image file (only if inside the app output folder, or an
+ /// example's), thumbnail and pre-upscale original.
pub fn delete_generation(&self, id: &str, output_root: &Path) -> AppResult<()> {
let rec = self.get_generation(id)?;
self.conn.lock().unwrap().execute("DELETE FROM generations WHERE id = ?1", [id]).map_err(db_err)?;
let f = PathBuf::from(&rec.file_path);
- if crate::paths::is_within(&f, &[output_root.to_path_buf()]) {
+ if crate::paths::is_within(&f, &[output_root.to_path_buf(), self.examples_dir()]) {
let _ = std::fs::remove_file(&f);
}
let _ = std::fs::remove_file(self.thumb_path(id));
+ let _ = std::fs::remove_file(self.original_path(id));
Ok(())
}
@@ -458,6 +477,7 @@ mod tests {
cache_threshold: Some(0.2),
enlarged_with: Some("RealESRGAN_x4plus".into()),
enlarged_from: Some(Size::new(2048, 1152)),
+ original_path: None,
});
let text = r.png_text();
let params_ = &text.iter().find(|(k, _)| *k == "parameters").unwrap().1;
diff --git a/crates/qls-service/Cargo.toml b/crates/qls-service/Cargo.toml
index 08f2e0c..9704d34 100644
--- a/crates/qls-service/Cargo.toml
+++ b/crates/qls-service/Cargo.toml
@@ -1,6 +1,7 @@
[package]
name = "qls-service"
version.workspace = true
+license.workspace = true
edition.workspace = true
# The executable users see (Task Manager, the install folder) carries the product name.
diff --git a/crates/qls-service/src/api.rs b/crates/qls-service/src/api.rs
index 01947b5..3f376c7 100644
--- a/crates/qls-service/src/api.rs
+++ b/crates/qls-service/src/api.rs
@@ -87,8 +87,10 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/gallery/{id}", get(gallery_get).patch(gallery_patch).delete(gallery_delete))
.route("/gallery/{id}/image", get(gallery_image))
.route("/gallery/{id}/thumb", get(gallery_thumb))
+ .route("/gallery/{id}/original", get(gallery_original))
.route("/gallery/{id}/export", post(gallery_export))
.route("/image-info", post(image_info))
+ .route("/examples", post(install_examples))
.route("/session/heartbeat", post(heartbeat))
.route("/session/release", post(release))
.route("/shutdown", post(shutdown))
@@ -154,7 +156,8 @@ async fn auth(State(s): St, req: Request, next: Next) -> Response {
if !ok {
return ApiError(AppError::new(ErrorCode::Unauthorized, "Missing or invalid API token (see service.json).")).into_response();
}
- s.engine.touch();
+ // No `touch()` here: heartbeats and status polls are not work, and counting them kept
+ // the model loaded for as long as an MCP client stayed connected.
next.run(req).await
}
@@ -765,6 +768,13 @@ async fn gallery_image(State(s): St, AxPath(id): AxPath<String>) -> ApiResult<Re
serve_file(Path::new(&r.file_path), None).await
}
+/// The result before the upscaler enlarged it, when it was kept.
+async fn gallery_original(State(s): St, AxPath(id): AxPath<String>) -> ApiResult<Response> {
+ let r = s.engine.gen_store(&id).get_generation(&id)?;
+ let p = r.pipeline.and_then(|p| p.original_path).ok_or_else(|| AppError::new(ErrorCode::NotFound, "This image has no pre-upscale original."))?;
+ serve_file(Path::new(&p), Some("image/png")).await
+}
+
async fn gallery_thumb(State(s): St, AxPath(id): AxPath<String>) -> ApiResult<Response> {
let store = s.engine.gen_store(&id);
let p = store.thumb_path(&id);
@@ -780,6 +790,9 @@ struct ExportBody {
path: String,
#[serde(default)]
overwrite: bool,
+ /// Save the pre-upscale original instead of the result.
+ #[serde(default)]
+ original: bool,
}
/// "Save as" from the desktop app (path chosen in the native dialog, which already
@@ -798,13 +811,18 @@ async fn gallery_export(State(s): St, AxPath(id): AxPath<String>, Json(b): Json<
qls_core::planner::OutputFormat::Png
}
};
- if Path::new(&rec.file_path) == target {
+ let source = if b.original {
+ rec.pipeline.as_ref().and_then(|p| p.original_path.clone()).ok_or_else(|| AppError::new(ErrorCode::NotFound, "This image has no pre-upscale original."))?
+ } else {
+ rec.file_path.clone()
+ };
+ if Path::new(&source) == target {
return Ok(target);
}
if !b.overwrite {
target = paths::unique_path(target, &[]);
}
- let img = imaging::load_image(Path::new(&rec.file_path))?;
+ let img = imaging::load_image(Path::new(&source))?;
let bytes = qls_core::engine::encode_output(&img.pixels, fmt, &rec, img.icc_profile.as_deref())?;
qls_core::engine::write_atomic(&target, &bytes)?;
Ok(target)
@@ -814,6 +832,13 @@ async fn gallery_export(State(s): St, AxPath(id): AxPath<String>, Json(b): Json<
Ok(Json(json!({ "path": saved })))
}
+/// Adds the bundled example projects (first launch, or Settings) and lists them.
+async fn install_examples(State(s): St) -> ApiResult<Json<Value>> {
+ let engine = s.engine.clone();
+ let projects = tokio::task::spawn_blocking(move || engine.install_examples()).await.map_err(AppError::internal)??;
+ Ok(Json(json!({ "projects": projects })))
+}
+
async fn image_info(Json(b): Json<PathBody>) -> ApiResult<Json<Value>> {
let v = tokio::task::spawn_blocking(move || -> Result<Value, AppError> {
let p = paths::validate_input_image(&b.path, None, &[])?;
diff --git a/crates/qls-service/src/main.rs b/crates/qls-service/src/main.rs
index e12ac86..510b0a0 100644
--- a/crates/qls-service/src/main.rs
+++ b/crates/qls-service/src/main.rs
@@ -32,7 +32,8 @@ pub struct ServiceInfo {
pub struct Lease {
pub kind: String,
pub last_seen: Instant,
- /// Client process id; a dead process drops its lease at once (app killed or crashed).
+ /// Client process id. A dead process drops its lease at once (app killed or crashed); a
+ /// live one keeps it however late its heartbeat is (see [`lease_alive`]).
pub pid: Option<u32>,
}
@@ -52,6 +53,17 @@ pub struct AppState {
pub const LEASE_TTL: Duration = Duration::from_secs(45);
+/// Whether a client still holds its lease. Clients that sent their pid (the desktop app, the
+/// MCP server) hold it while that process runs: after the computer sleeps their heartbeat is
+/// minutes late, and dropping them then cancelled the window's jobs and unloaded the model.
+/// The heartbeat timeout only applies to clients without a pid.
+fn lease_alive(l: &Lease) -> bool {
+ match l.pid {
+ Some(pid) => qls_core::process::pid_alive(pid),
+ None => l.last_seen.elapsed() < LEASE_TTL,
+ }
+}
+
fn load_or_create_token(dir: &std::path::Path) -> String {
let p = dir.join("service-token");
if let Ok(t) = std::fs::read_to_string(&p) {
@@ -169,13 +181,25 @@ async fn main() {
/// Exits when no client holds a lease, no job is pending, and the grace period passed.
/// Also unloads the model after long idle periods when no desktop window is attached.
async fn lifecycle(state: Arc<AppState>) {
+ let mut last_tick = Instant::now();
loop {
tokio::time::sleep(Duration::from_secs(2)).await;
+ // A long gap between two 2 s ticks: the computer slept. Give every client a fresh
+ // timeout to check in again before deciding it is gone.
+ let gap = last_tick.elapsed();
+ last_tick = Instant::now();
+ let resumed = gap > Duration::from_secs(20);
+ if resumed {
+ tracing::info!("resumed after {} s (computer asleep?): waiting for clients to check in", gap.as_secs());
+ }
let (n_leases, has_ui, lost) = {
let mut leases = state.leases.lock().unwrap();
+ if resumed {
+ leases.values_mut().for_each(|l| l.last_seen = Instant::now());
+ }
let mut lost = Vec::new();
leases.retain(|id, l| {
- let alive = l.last_seen.elapsed() < LEASE_TTL && l.pid.map(qls_core::process::pid_alive).unwrap_or(true);
+ let alive = lease_alive(l);
if !alive {
lost.push((id.clone(), l.kind.clone()));
}
diff --git a/marketing/release-notes-0.9.0.md b/marketing/release-notes-0.9.0.md
index d476fc7..b9efc98 100644
--- a/marketing/release-notes-0.9.0.md
+++ b/marketing/release-notes-0.9.0.md
@@ -39,7 +39,7 @@ On first launch Kokon detects your graphics card (or your Mac's chip and memory)
## Model licenses
-Kokon's code is Apache 2.0. The models are downloaded from their authors and keep their own licenses: Qwen-Image 2.1 Turbo has the same license as [Qwen-Image 2.1](https://huggingface.co/Qwen/Qwen-Image-2.1) (see the [Turbo model page](https://huggingface.co/Qwen/Qwen-Image-2.1-Turbo)), the Qwen3-VL text encoder is from [Qwen/Qwen3-VL-8B-Instruct-GGUF](https://huggingface.co/Qwen/Qwen3-VL-8B-Instruct-GGUF), and the optional 4x-UltraSharp upscaler is CC BY-NC-SA 4.0 (non-commercial only). Check them before commercial use. Details in [NOTICE](https://github.com/GabrieleLozupone/kokon/blob/master/NOTICE).
+Kokon's code is open source under the GNU AGPL-3.0. The models are downloaded from their authors and keep their own licenses: Qwen-Image 2.1 Turbo has the same license as [Qwen-Image 2.1](https://huggingface.co/Qwen/Qwen-Image-2.1) (see the [Turbo model page](https://huggingface.co/Qwen/Qwen-Image-2.1-Turbo)), the Qwen3-VL text encoder is from [Qwen/Qwen3-VL-8B-Instruct-GGUF](https://huggingface.co/Qwen/Qwen3-VL-8B-Instruct-GGUF), and the optional 4x-UltraSharp upscaler is CC BY-NC-SA 4.0 (non-commercial only). Check them before commercial use. Details in [NOTICE](https://github.com/GabrieleLozupone/kokon/blob/master/NOTICE).
## First launch
diff --git a/mcp/package.json b/mcp/package.json
index 13c18c0..f44b811 100644
--- a/mcp/package.json
+++ b/mcp/package.json
@@ -1,6 +1,7 @@
{
"name": "kokon-mcp",
"version": "0.9.0",
+ "license": "AGPL-3.0-only",
"private": true,
"description": "MCP server for Kokon (local image generation and editing)",
"type": "module",
diff --git a/package.json b/package.json
index b62daf2..a904891 100644
--- a/package.json
+++ b/package.json
@@ -2,6 +2,7 @@
"name": "kokon",
"private": true,
"version": "0.9.0",
+ "license": "AGPL-3.0-only",
"type": "module",
"scripts": {
"dev": "vite",
diff --git a/scripts/make-examples.py b/scripts/make-examples.py
new file mode 100644
index 0000000..b822179
--- /dev/null
+++ b/scripts/make-examples.py
@@ -0,0 +1,33 @@
+"""Builds the example projects bundled with Kokon (assets/examples) from the full-size
+showcase originals (made by Kokon, see marketing/showcase/PROMPTS.md).
+
+ python scripts/make-examples.py [originals folder] # default: ~/Pictures/Kokon/marketing
+"""
+import os
+import sys
+from PIL import Image
+
+SRC = sys.argv[1] if len(sys.argv) > 1 else os.path.join(os.path.expanduser("~"), "Pictures", "Kokon", "marketing")
+OUT = os.path.join(os.path.dirname(__file__), "..", "assets", "examples")
+LONG = 1600
+# Chains share one scale so masks and expansions keep matching their images.
+GROUPS = {
+ "street": ["street", "street-removed", "street-cat", "street-mask", "street-add-mask"],
+ "cabin": ["cabin", "cabin-winter"],
+ "bakery": ["bakery", "bakery-text"],
+ "lighthouse": ["lighthouse", "lighthouse-wide"],
+ "potter": ["potter", "potter-watercolor"],
+}
+
+os.makedirs(OUT, exist_ok=True)
+for names in GROUPS.values():
+ ims = {n: Image.open(os.path.join(SRC, n + ".png")) for n in names}
+ k = min(1.0, LONG / max(max(im.size) for im in ims.values()))
+ for n, im in ims.items():
+ size = (round(im.width * k), round(im.height * k))
+ im = im.resize(size, Image.LANCZOS)
+ if im.mode == "L":
+ im.point(lambda v: 255 if v >= 128 else 0).save(os.path.join(OUT, n + ".png"), optimize=True)
+ else:
+ im.convert("RGB").save(os.path.join(OUT, n + ".jpg"), quality=86, optimize=True, progressive=True)
+ print(n, size)
diff --git a/site/index.html b/site/index.html
index ec473ca..4767376 100644
--- a/site/index.html
+++ b/site/index.html
@@ -97,7 +97,7 @@
"name": "Is it really free?",
"acceptedAnswer": {
"@type": "Answer",
- "text": "Yes. Kokon is open source under the AGPL-3.0 license. No account, no credits, no subscription. It uses your own GPU, so there is nothing to pay for."
+ "text": "Yes. Kokon is open source under the GNU AGPL-3.0 license. No account, no credits, no subscription. It uses your own GPU, so there is nothing to pay for."
}
},
{
@@ -153,7 +153,7 @@
"name": "Can I use the images commercially?",
"acceptedAnswer": {
"@type": "Answer",
- "text": "The app's code is AGPL-3.0. The model weights have their own licenses: read the Qwen-Image model page before commercial use. The optional upscaler is non-commercial (CC BY-NC-SA 4.0)."
+ "text": "The app is open source (AGPL-3.0); that covers the code, not the images you make. The model weights have their own licenses: read the Qwen-Image model page before commercial use. The optional upscaler is non-commercial (CC BY-NC-SA 4.0)."
}
},
{
@@ -428,14 +428,14 @@
<p class="kicker rv">FAQ</p>
<h2 class="rv d1">Questions.</h2>
<div class="faq rv d2">
- <details><summary>Is it really free?</summary><p>Yes. Kokon is open source under the AGPL-3.0 license. No account, no credits, no subscription. It uses your own GPU, so there is nothing to pay for.</p></details>
+ <details><summary>Is it really free?</summary><p>Yes. Kokon is open source under the GNU AGPL-3.0 license. No account, no credits, no subscription. It uses your own GPU, so there is nothing to pay for.</p></details>
<details><summary>How do I run Qwen-Image 2.1 locally without ComfyUI?</summary><p>Install Kokon and let its setup download the model. Kokon runs Qwen-Image 2.1 through stable-diffusion.cpp, a native engine, so there is no Python, no ComfyUI and no workflow to build. The step-by-step guide is at kokon.app/qwen-image-2-1-local.</p></details>
<details><summary>Which model does it use?</summary><p>Qwen-Image 2.1 Turbo, the official 8-step version of Qwen&#x27;s image model, which both creates and edits images and leads the open-weights image-editing rankings.</p></details>
<details><summary>Does it work on AMD or Intel GPUs?</summary><p>Yes, in beta, through the Vulkan engine on Windows with 12 GB of VRAM or more. On NVIDIA it uses CUDA; on Apple Silicon Macs it uses Metal.</p></details>
<details><summary>My GPU has 8 GB. Will it work?</summary><p>Not well today. 12 GB is the smallest size that gives good results with this model. On a Mac, 16 GB of unified memory works but slowly; 32 GB is recommended.</p></details>
<details><summary>Can Claude Code or Cursor generate images with it?</summary><p>Yes. Kokon ships an MCP server: register it once and any MCP client can create, edit, inpaint, expand and upscale images on your GPU, for free and without an API key.</p></details>
<details><summary>Is it an alternative to Photoshop Generative Fill?</summary><p>For many edits, yes: paint an area and describe what should be there, or remove, replace and add objects. It runs offline and costs nothing, but it is an AI editor, not a full layer-based image editor.</p></details>
- <details><summary>Can I use the images commercially?</summary><p>The app's code is AGPL-3.0. The model weights have their own licenses: read the Qwen-Image model page before commercial use. The optional upscaler is non-commercial (CC BY-NC-SA 4.0).</p></details>
+ <details><summary>Can I use the images commercially?</summary><p>The app is open source (AGPL-3.0); that covers the code, not the images you make. The model weights have their own licenses: read the Qwen-Image model page before commercial use. The optional upscaler is non-commercial (CC BY-NC-SA 4.0).</p></details>
<details><summary>Windows says the app is unrecognized. Is it safe?</summary><p>The beta installer is not code-signed yet, so SmartScreen warns about it. Click &quot;More info&quot; and then &quot;Run anyway&quot;. The code is public and every download the app makes is checked against a pinned hash.</p></details>
<details><summary>Does it work offline?</summary><p>Yes. After setup has downloaded the models, everything runs offline.</p></details>
</div>
diff --git a/site/qwen-image-2-1-local/index.html b/site/qwen-image-2-1-local/index.html
index edb7507..667c8e9 100644
--- a/site/qwen-image-2-1-local/index.html
+++ b/site/qwen-image-2-1-local/index.html
@@ -164,7 +164,7 @@
<p>Kokon includes an MCP server, so Claude Code, Cursor or any MCP client can create and edit images on your GPU without an API key. See <a href="../mcp-image-generation/">free local image generation for Claude Code and MCP</a>.</p>
<h2>License notes</h2>
- <p>Kokon's code is AGPL-3.0. The model weights have their own licenses; read the Qwen-Image model page before commercial use. Kokon is an independent project, not affiliated with Alibaba.</p>
+ <p>Kokon is open source (AGPL-3.0). The model weights have their own licenses; read the Qwen-Image model page before commercial use. Kokon is an independent project, not affiliated with Alibaba.</p>
<div class="cta-box">
<h2>Try it</h2>
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 794f1f4..d64f373 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,6 +1,7 @@
[package]
name = "kokon"
version.workspace = true
+license.workspace = true
edition.workspace = true
description = "Kokon"
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 06f96b3..7f520f9 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -53,6 +53,7 @@
"installerIcon": "icons/icon.ico",
"uninstallerIcon": "icons/icon.ico",
"installMode": "currentUser",
+ "installerHooks": "windows/hooks.nsh",
"displayLanguageSelector": false
}
},
diff --git a/src-tauri/windows/hooks.nsh b/src-tauri/windows/hooks.nsh
new file mode 100644
index 0000000..e48a15d
--- /dev/null
+++ b/src-tauri/windows/hooks.nsh
@@ -0,0 +1,58 @@
+; Kokon's additions to Tauri's NSIS installer (bundle > windows > nsis > installerHooks).
+; - Before installing, updating or uninstalling: stop the background processes (MCP servers,
+; kokon-service, sd-server) that keep Kokon's files locked. Tauri itself only closes Kokon.exe.
+; - After uninstalling: offer to delete the downloaded models and app data. Images in the
+; output folder (Pictures\Kokon) are never touched.
+
+; This folder, captured now (inside a macro, __FILEDIR__ is the file that uses it).
+!define KOKON_HOOKS_DIR "${__FILEDIR__}"
+
+!macro KOKON_STOP_PROCESSES
+ Push $0
+ Push $1
+ InitPluginsDir
+ File "/oname=$PLUGINSDIR\kokon-stop.ps1" "${KOKON_HOOKS_DIR}\kokon-stop.ps1"
+ ; 64-bit PowerShell from the 32-bit installer (Sysnative), the plain path otherwise.
+ StrCpy $1 "$WINDIR\Sysnative\WindowsPowerShell\v1.0\powershell.exe"
+ ${IfNot} ${FileExists} "$1"
+ StrCpy $1 "$SYSDIR\WindowsPowerShell\v1.0\powershell.exe"
+ ${EndIf}
+ DetailPrint "Stopping Kokon's background processes..."
+ nsExec::Exec '"$1" -NoProfile -NonInteractive -ExecutionPolicy Bypass -File "$PLUGINSDIR\kokon-stop.ps1" -InstDir "$INSTDIR"'
+ Pop $0
+ Pop $1
+ Pop $0
+!macroend
+
+!macro NSIS_HOOK_PREINSTALL
+ !insertmacro KOKON_STOP_PROCESSES
+!macroend
+
+!macro NSIS_HOOK_PREUNINSTALL
+ !insertmacro KOKON_STOP_PROCESSES
+!macroend
+
+!macro NSIS_HOOK_POSTUNINSTALL
+ ; Never during an update or a silent/passive uninstall: only when a person uninstalls.
+ ${If} $UpdateMode <> 1
+ ${AndIf} $PassiveMode <> 1
+ ${AndIfNot} ${Silent}
+ SetShellVarContext current
+ ${If} ${FileExists} "$LOCALAPPDATA\KokonData\*.*"
+ ${GetSize} "$LOCALAPPDATA\KokonData" "/S=0M /G=1" $0 $1 $2
+ IntOp $1 $0 / 1024
+ IntOp $2 $0 % 1024
+ IntOp $2 $2 * 10
+ IntOp $2 $2 / 1024
+ MessageBox MB_YESNO|MB_ICONQUESTION|MB_DEFBUTTON2 "Also delete the AI models Kokon downloaded and its app data ($1.$2 GB)?$\r$\n$\r$\nThis frees the disk space. If you install Kokon again, it downloads the models again.$\r$\n$\r$\nYour images in the Kokon output folder (Pictures\Kokon by default) are kept either way.$\r$\n$\r$\nChoose No if you are reinstalling or updating Kokon." IDNO kokon_keep_data
+ DetailPrint "Deleting Kokon's models and data..."
+ RMDir /r "$LOCALAPPDATA\KokonData"
+ RMDir /r "$LOCALAPPDATA\QwenLocalStudio"
+ RMDir /r "$APPDATA\Kokon"
+ ${If} ${FileExists} "$LOCALAPPDATA\KokonData\*.*"
+ MessageBox MB_OK|MB_ICONEXCLAMATION "Some files could not be deleted. You can delete this folder yourself:$\r$\n$LOCALAPPDATA\KokonData"
+ ${EndIf}
+ kokon_keep_data:
+ ${EndIf}
+ ${EndIf}
+!macroend
diff --git a/src-tauri/windows/kokon-stop.ps1 b/src-tauri/windows/kokon-stop.ps1
new file mode 100644
index 0000000..809c386
--- /dev/null
+++ b/src-tauri/windows/kokon-stop.ps1
@@ -0,0 +1,46 @@
+# Stops Kokon's background processes so the installer can replace (or the uninstaller remove)
+# their files. Run by hooks.nsh before installing, updating and uninstalling.
+# -InstDir Kokon's install folder: only executables inside it (and the inference server in
+# Kokon's data folder) are stopped, never another copy of sd-server.
+# -DryRun List what would be stopped.
+param([Parameter(Mandatory = $true)][string]$InstDir, [switch]$DryRun)
+
+$ErrorActionPreference = 'SilentlyContinue'
+$data = Join-Path $env:LOCALAPPDATA 'KokonData'
+$roots = @($InstDir.TrimEnd('\') + '\')
+
+# Win32_Process gives the path even across 32/64-bit (the installer itself is 32-bit).
+function Find([string[]]$names, [string[]]$under) {
+ Get-CimInstance Win32_Process | Where-Object {
+ $p = $_
+ ($names -contains $p.Name) -and $p.ExecutablePath -and ($under | Where-Object { $p.ExecutablePath.StartsWith($_, [StringComparison]::OrdinalIgnoreCase) })
+ }
+}
+
+function Stop([object[]]$procs) {
+ foreach ($p in $procs) {
+ if ($DryRun) { Write-Output "would stop $($p.ProcessId) $($p.ExecutablePath)" }
+ else { Stop-Process -Id $p.ProcessId -Force }
+ }
+}
+
+$services = @('kokon-service.exe', 'qls-service.exe')
+
+# 1. The MCP servers (Claude and other agents) first: they would start the service again.
+Stop (Find @('kokon-mcp.exe', 'qls-mcp.exe') $roots)
+
+# 2. Ask the service to exit, so it unloads the model the normal way.
+$running = Find $services $roots
+if ($running -and -not $DryRun) {
+ $info = Get-Content (Join-Path $data 'service.json') -Raw | ConvertFrom-Json
+ if ($info -and ($running.ProcessId -contains $info.pid)) {
+ Invoke-RestMethod -Method Post -Uri "http://127.0.0.1:$($info.port)/api/v1/shutdown" -Headers @{ Authorization = "Bearer $($info.token)" } -TimeoutSec 3 | Out-Null
+ $deadline = (Get-Date).AddSeconds(8)
+ while ((Find $services $roots) -and (Get-Date) -lt $deadline) { Start-Sleep -Milliseconds 250 }
+ }
+}
+
+# 3. Whatever is still running.
+Stop (Find $services $roots)
+Stop (Find @('sd-server.exe') @($data.TrimEnd('\') + '\'))
+exit 0
diff --git a/src/App.tsx b/src/App.tsx
index 16bd111..0b279b0 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -1,10 +1,10 @@
import { getCurrentWebview } from "@tauri-apps/api/webview";
import { ArrowDownToLine, EyeOff, PanelLeft, Redo2, Settings, SquarePen, Undo2, X } from "lucide-react";
-import { useEffect, useState } from "react";
+import { useEffect, useRef, useState } from "react";
import { api, configure } from "./lib/api";
import { native } from "./lib/native";
import {
- addInputs, dismissToast, getState, newProject, redoVersion, refreshStatus, selectItem, setPrivateMode, setState, startEvents, submitComposer, toastError, toastInfo, undoKey, undoVersion, useStore,
+ addExampleProjects, addInputs, dismissToast, getState, newProject, redoVersion, refreshStatus, selectItem, setPrivateMode, setState, startEvents, startTour, submitComposer, toastError, toastInfo, undoKey, undoVersion, useStore,
} from "./lib/store";
import { Composer, importPaths } from "./components/Composer";
import { ExpandEditor } from "./components/ExpandEditor";
@@ -14,6 +14,7 @@ import { Settings as SettingsDialog } from "./components/Settings";
import { Setup } from "./components/Setup";
import { ProjectTitle, Sidebar } from "./components/Sidebar";
import { Stage } from "./components/Stage";
+import { Tour } from "./components/Tour";
import { IconButton } from "./components/ui";
import { shortcut } from "./lib/platform";
import { KokonMark, Welcome } from "./components/Welcome";
@@ -178,6 +179,14 @@ export default function App() {
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);
+ // First launch: the tour starts once the main window is free (after welcome and setup).
+ const tourPending = useRef(false);
+ const tourDue = boot === "ok" && !needsSetup && !overlay;
+ useEffect(() => {
+ if (!tourDue || !tourPending.current) return;
+ tourPending.current = false;
+ startTour();
+ }, [tourDue]);
// Connect to (or start) the local service.
useEffect(() => {
@@ -191,7 +200,13 @@ export default function App() {
const cfg = await api.config();
const st = await refreshStatus();
// First launch: the welcome screen, once (Settings → General shows it again).
- const welcomeSeen = !!(cfg.ui as Record<string, unknown> | null)?.welcomeSeen;
+ const ui = (cfg.ui ?? {}) as Record<string, unknown>;
+ const welcomeSeen = !!ui.welcomeSeen;
+ // ...with example projects to look at, and the tour through the first one.
+ if (!welcomeSeen && !ui.tourSeen) {
+ tourPending.current = true;
+ addExampleProjects().catch(() => {});
+ }
setState({ needsSetup: !cfg.setupComplete, ...(welcomeSeen ? {} : { overlay: "welcome" }) });
setBoot("ok");
autoCheckForUpdate();
@@ -340,6 +355,7 @@ export default function App() {
</div>
{overlay === "settings" && <SettingsDialog />}
{overlay === "welcome" && <Welcome />}
+ <Tour />
<Toasts />
</div>
);
diff --git a/src/components/Composer.tsx b/src/components/Composer.tsx
index f9107fa..2cf9422 100644
--- a/src/components/Composer.tsx
+++ b/src/components/Composer.tsx
@@ -181,7 +181,7 @@ function TargetBar() {
</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">
+ <button className={`tool ${c.mask ? "on" : ""}`} data-tour="paint" 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 && (
diff --git a/src/components/Settings.tsx b/src/components/Settings.tsx
index a778b1d..a5a1741 100644
--- a/src/components/Settings.tsx
+++ b/src/components/Settings.tsx
@@ -3,7 +3,7 @@ import { useEffect, useState } from "react";
import { writeText } from "@tauri-apps/plugin-clipboard-manager";
import { api } from "../lib/api";
import { native } from "../lib/native";
-import { getState, refreshStatus, setState, toastError, toastInfo } from "../lib/store";
+import { getState, refreshStatus, setState, startTour, toastError, toastInfo } from "../lib/store";
import { UPSCALERS } from "../lib/logic";
import type { AppConfig, Check, ModelProfile, SetupReport, TextEncoderPlacement } from "../lib/types";
import { IconButton, Seg, Switch } from "./ui";
@@ -193,6 +193,12 @@ export function Settings() {
Show
</button>
</div>
+ <div className="field-row">
+ <span>Tour: a short walk through an example project (adds the examples again if you removed them)</span>
+ <button className="btn" onClick={startTour}>
+ Start
+ </button>
+ </div>
</>
)}
diff --git a/src/components/Stage.tsx b/src/components/Stage.tsx
index 94ab3ac..65e0fc8 100644
--- a/src/components/Stage.tsx
+++ b/src/components/Stage.tsx
@@ -271,7 +271,9 @@ function MoreMenu({ item, path }: { item: SessionItem; path: string | null }) {
);
}
-function GenActions({ item, g }: { item: SessionItem; g: GenerationRecord }) {
+function GenActions({ item, g, showOriginal }: { item: SessionItem; g: GenerationRecord; showOriginal: boolean }) {
+ // Save, copy and "show in folder" act on the image on screen: the result or its pre-upscale original.
+ const shownPath = (showOriginal && g.pipeline?.original_path) || g.file_path;
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 (
@@ -312,13 +314,13 @@ function GenActions({ item, g }: { item: SessionItem; g: GenerationRecord }) {
<Heart size={17} fill={fav ? "currentColor" : "none"} />
</IconButton>
<IconButton
- title="Save as…"
+ title={showOriginal ? "Save the original (before upscaling) as…" : "Save as…"}
onClick={async () => {
const name = g.file_path.split(/[\\/]/).pop() ?? "image.png";
- const path = await native.saveAs(name);
+ const path = await native.saveAs(showOriginal ? name.replace(/(\.\w+)?$/, "-original.png") : name);
if (!path) return;
try {
- const r = await api.exportGeneration(g.id, path);
+ const r = await api.exportGeneration(g.id, path, showOriginal);
toastInfo(`Saved ${r.path.split(/[\\/]/).pop()}`);
} catch (e) {
toastError(e);
@@ -328,10 +330,10 @@ function GenActions({ item, g }: { item: SessionItem; g: GenerationRecord }) {
<Download size={17} />
</IconButton>
<IconButton
- title="Copy image"
+ title={showOriginal ? "Copy the original (before upscaling)" : "Copy image"}
onClick={async () => {
try {
- await native.copyImage(g.file_path);
+ await native.copyImage(shownPath);
toastInfo("Image copied");
} catch (e) {
toastError(e);
@@ -350,7 +352,7 @@ function GenActions({ item, g }: { item: SessionItem; g: GenerationRecord }) {
>
{() => <InfoPanel g={g} />}
</Popover>
- <MoreMenu item={item} path={g.file_path} />
+ <MoreMenu item={item} path={shownPath} />
</div>
);
}
@@ -382,10 +384,11 @@ function PlainFrame({ src, alt, w, h }: { src: string; alt: string; w: number; h
}
/** Under the image: which image this is and what made it, then what you can do with it. */
-function StageBar({ item, label }: { item: SessionItem; label: string }) {
+function StageBar({ item, label, showOriginal, setShowOriginal }: { item: SessionItem; label: string; showOriginal: boolean; setShowOriginal: (on: boolean) => void }) {
const g = item.gen;
const w = g?.width ?? item.input!.width;
const h = g?.height ?? item.input!.height;
+ const from = g?.pipeline?.original_path ? g.pipeline.enlarged_from : null;
const name = item.input?.original_name ? safeDecode(item.input.original_name) : "Imported image";
return (
<div className="stage-bar">
@@ -395,11 +398,22 @@ function StageBar({ item, label }: { item: SessionItem; label: string }) {
<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>
+ {from ? (
+ <span className="seg dims-seg" role="radiogroup" aria-label="Which image to show">
+ <button className={showOriginal ? "" : "on"} role="radio" aria-checked={!showOriginal} onClick={() => setShowOriginal(false)} title={`The result, enlarged by ${upscalerLabel(g!.pipeline!.enlarged_with)}`}>
+ Upscaled {w}×{h}
+ </button>
+ <button className={showOriginal ? "on" : ""} role="radio" aria-checked={showOriginal} onClick={() => setShowOriginal(true)} title="What the model made, before the upscaler enlarged it">
+ Original {from.width}×{from.height}
+ </button>
+ </span>
+ ) : (
+ <span className="dims">
+ {w}×{h}
+ </span>
+ )}
</div>
- {g ? <GenActions key={`actions-${g.id}`} item={item} g={g} /> : <InputActions item={item} />}
+ {g ? <GenActions key={`actions-${g.id}`} item={item} g={g} showOriginal={showOriginal} /> : <InputActions item={item} />}
</div>
);
}
@@ -461,6 +475,29 @@ function Timeline({ labels }: { labels: Record<string, string> }) {
boxRef.current?.querySelector(".frame.sel")?.scrollIntoView({ block: "nearest", inline: "nearest" });
}, [selected, session.length]);
+ // A timeline wider than the stage scrolls: a thin bar under it, and the mouse wheel moves
+ // it sideways (a touchpad's own sideways swipe keeps working).
+ const [overflow, setOverflow] = useState(false);
+ useEffect(() => {
+ const box = boxRef.current;
+ if (!box) return;
+ const measure = () => setOverflow(box.scrollWidth > box.clientWidth + 1);
+ const ro = new ResizeObserver(measure);
+ ro.observe(box);
+ if (trackRef.current) ro.observe(trackRef.current);
+ const wheel = (e: WheelEvent) => {
+ if (box.scrollWidth <= box.clientWidth || Math.abs(e.deltaX) > Math.abs(e.deltaY)) return;
+ e.preventDefault();
+ box.scrollLeft += e.deltaMode === 1 ? e.deltaY * 32 : e.deltaY;
+ };
+ box.addEventListener("wheel", wheel, { passive: false });
+ measure();
+ return () => {
+ ro.disconnect();
+ box.removeEventListener("wheel", wheel);
+ };
+ }, [session.length > 0]);
+
// Thumbnail centres, for the arcs.
useLayoutEffect(() => {
const out: Record<string, number> = {};
@@ -491,7 +528,7 @@ function Timeline({ labels }: { labels: Record<string, string> }) {
};
return (
- <div className="timeline" ref={boxRef} aria-label="Versions">
+ <div className={`timeline ${overflow ? "overflow" : ""}`} ref={boxRef} aria-label="Versions">
{/* Room for the selection outline even when there are no arcs (the scroll box clips). */}
<div className="track" ref={trackRef} style={{ paddingTop: Math.max(band, 6) }} onMouseLeave={() => setHovered(null)}>
{arcs.length > 0 && (
@@ -606,6 +643,8 @@ export function Stage() {
const session = useStore((s) => s.session);
const job = useStore((s) => (item?.jobId ? s.jobs[item.jobId] : undefined));
const labels = useMemo(() => sessionLabels(session), [session]);
+ // The result whose pre-upscale original is on screen instead of it.
+ const [originalOf, setOriginalOf] = useState<string | null>(null);
if (!item) {
return (
@@ -632,14 +671,19 @@ export function Stage() {
const w = item.gen?.width ?? item.input!.width;
const h = item.gen?.height ?? item.input!.height;
const base = item.gen ? compareBase(item.gen) : null;
+ const g = item.gen;
+ const from = g?.pipeline?.original_path ? g.pipeline.enlarged_from : null;
+ const showOriginal = !!(g && from && originalOf === g.id);
view = (
<>
- {item.gen && base ? (
+ {g && from && showOriginal ? (
+ <PlainFrame key={`original-${g.id}`} src={urls.genOriginal(g.id)} alt={`${g.prompt} (before upscaling)`} w={from.width} h={from.height} />
+ ) : 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]} />
+ <StageBar item={item} label={labels[item.key]} showOriginal={showOriginal} setShowOriginal={(on) => setOriginalOf(on && g ? g.id : null)} />
</>
);
}
diff --git a/src/components/Tour.tsx b/src/components/Tour.tsx
new file mode 100644
index 0000000..0b16a4b
--- /dev/null
+++ b/src/components/Tour.tsx
@@ -0,0 +1,168 @@
+// First-run tour: a few cards pointing at the parts of the window, walked through on the
+// first example project (store.startTour). Steps whose target is not on screen are skipped.
+
+import { X } from "lucide-react";
+import { useEffect, useLayoutEffect, useState } from "react";
+import { endTour, setState, useStore } from "../lib/store";
+
+interface Step {
+ target: string;
+ title: string;
+ text: string;
+}
+
+const STEPS: Step[] = [
+ {
+ target: ".stage-frame",
+ title: "An example project",
+ text: "Kokon made these images on a PC like yours, about half a minute each. This project is yours to look around in, edit further or delete.",
+ },
+ {
+ target: ".timeline",
+ title: "Every version is kept",
+ text: "A sentence made the first image. Painting an area then removed the scooter and added the cat. Click any version to go back to it and continue from there.",
+ },
+ {
+ target: ".compare-bar",
+ title: "Before and after",
+ text: "Press and hold the image (or hold B) to see the version it was made from. Slider, Flicker and Changes compare the two in other ways.",
+ },
+ {
+ target: ".composer",
+ title: "Describe a change",
+ text: "Type what should change in plain words, like “make it a rainy evening”, and press Enter. New image starts from a sentence instead of a picture.",
+ },
+ {
+ target: '[data-tour="paint"]',
+ title: "Change just one area",
+ text: "Paint area: brush over part of the image and only that part changes. Remove, replace, add or change what is there.",
+ },
+ {
+ target: ".side-list",
+ title: "Your projects",
+ text: "More examples are here. Start your own with New image, or drop or paste a photo anywhere in the window.",
+ },
+];
+
+const PAD = 6;
+const CARD_W = 320;
+const GAP = 14;
+
+type Box = { x: number; y: number; w: number; h: number };
+
+function find(step: number): Box | null {
+ const el = document.querySelector(STEPS[step].target);
+ if (!el) return null;
+ const r = el.getBoundingClientRect();
+ return r.width && r.height ? { x: r.left - PAD, y: r.top - PAD, w: r.width + PAD * 2, h: r.height + PAD * 2 } : null;
+}
+
+/** The next step (in direction `d`) whose target is on screen; null past the ends. */
+function nextShown(from: number, d: 1 | -1): number | null {
+ for (let i = from; i >= 0 && i < STEPS.length; i += d) if (find(i)) return i;
+ return null;
+}
+
+export function Tour() {
+ const step = useStore((s) => s.tour);
+ const overlay = useStore((s) => s.overlay);
+ const [box, setBox] = useState<Box | null>(null);
+
+ // Follow the target while the window resizes or the layout settles.
+ useLayoutEffect(() => {
+ if (step === null) return;
+ const measure = () => setBox(find(step));
+ measure();
+ const t = window.setInterval(measure, 250);
+ window.addEventListener("resize", measure);
+ return () => {
+ window.clearInterval(t);
+ window.removeEventListener("resize", measure);
+ };
+ }, [step]);
+
+ const go = (d: 1 | -1) => {
+ if (step === null) return;
+ const n = nextShown(step + d, d);
+ if (n === null) {
+ if (d === 1) endTour();
+ } else setState({ tour: n });
+ };
+
+ useEffect(() => {
+ if (step === null) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") endTour();
+ else if (e.key === "ArrowRight" || e.key === "Enter") go(1);
+ else if (e.key === "ArrowLeft") go(-1);
+ else return;
+ e.preventDefault();
+ e.stopImmediatePropagation();
+ };
+ window.addEventListener("keydown", onKey, true);
+ return () => window.removeEventListener("keydown", onKey, true);
+ }, [step]);
+
+ // A step whose target is gone (sidebar hidden, nothing to compare) moves on by itself.
+ useEffect(() => {
+ if (step === null || box) return;
+ const t = window.setTimeout(() => {
+ if (!find(step)) go(1);
+ }, 400);
+ return () => window.clearTimeout(t);
+ }, [step, box]);
+
+ if (step === null || overlay) return null;
+ const s = STEPS[step];
+ const shown = STEPS.map((_, i) => i).filter((i) => i === step || find(i));
+ const last = nextShown(step + 1, 1) === null;
+ const vw = window.innerWidth;
+ const vh = window.innerHeight;
+ // Below the target when it fits, otherwise above; beside it for tall targets (the sidebar).
+ let left = 0;
+ let top = 0;
+ if (box) {
+ const tall = box.h > vh * 0.5;
+ if (tall) {
+ left = box.x + box.w + GAP + CARD_W < vw ? box.x + box.w + GAP : box.x - GAP - CARD_W;
+ top = box.y + 24;
+ } else {
+ left = box.x + box.w / 2 - CARD_W / 2;
+ top = box.y + box.h + GAP + 190 < vh ? box.y + box.h + GAP : box.y - GAP - 190;
+ }
+ left = Math.max(16, Math.min(vw - CARD_W - 16, left));
+ top = Math.max(16, Math.min(vh - 206, top));
+ }
+
+ return (
+ <div className="tour" role="dialog" aria-label="Tour">
+ {box ? <div className="tour-hole" style={{ left: box.x, top: box.y, width: box.w, height: box.h }} /> : <div className="tour-dim" />}
+ {box && (
+ <div className="tour-card" style={{ left, top, width: CARD_W }}>
+ <div className="tour-head">
+ <strong>{s.title}</strong>
+ <button className="tour-x" onClick={endTour} title="Close the tour (Esc)" aria-label="Close the tour">
+ <X size={15} />
+ </button>
+ </div>
+ <p>{s.text}</p>
+ <div className="tour-foot">
+ <span className="tour-dots" aria-hidden>
+ {shown.map((i) => (
+ <i key={i} className={i === step ? "on" : ""} />
+ ))}
+ </span>
+ {shown[0] !== step && (
+ <button className="btn" onClick={() => go(-1)}>
+ Back
+ </button>
+ )}
+ <button className="btn primary" onClick={() => go(1)}>
+ {last ? "Start creating" : "Next"}
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/lib/api.ts b/src/lib/api.ts
index f9d66b1..3af9869 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -85,7 +85,9 @@ export const api = {
generation: (id: string) => call<GenerationRecord>(`/gallery/${id}`),
setFavorite: (id: string, favorite: boolean) => call<GenerationRecord>(`/gallery/${id}`, { method: "PATCH", body: json({ favorite }) }),
deleteGeneration: (id: string) => call<{ deleted: string }>(`/gallery/${id}`, { method: "DELETE" }),
- exportGeneration: (id: string, path: string) => call<{ path: string }>(`/gallery/${id}/export`, { method: "POST", body: json({ path, overwrite: true }) }),
+ /** Adds the bundled example projects to the gallery (idempotent) and lists them. */
+ installExamples: () => call<{ projects: { title: string; generations: string[] }[] }>("/examples", { method: "POST" }),
+ exportGeneration: (id: string, path: string, original = false) => call<{ path: string }>(`/gallery/${id}/export`, { method: "POST", body: json({ path, overwrite: true, original }) }),
};
export const urls = {
@@ -93,6 +95,8 @@ 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}`,
+ /** The result before the upscaler enlarged it (`pipeline.original_path`). */
+ genOriginal: (id: string) => `${base}/gallery/${id}/original?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))),
diff --git a/src/lib/store.ts b/src/lib/store.ts
index d093f9c..d758bb3 100644
--- a/src/lib/store.ts
+++ b/src/lib/store.ts
@@ -79,6 +79,8 @@ export interface State {
privateMode: boolean;
/** Versions left with Undo, most recent last (Redo walks back through them). */
redo: string[];
+ /** Step of the first-run tour on screen (components/Tour.tsx), or null. */
+ tour: number | null;
}
const PREFS_KEY = "qls.prefs.v1";
@@ -280,6 +282,7 @@ let state: State = {
flickerMs: 500,
privateMode: false,
redo: [],
+ tour: null,
};
const listeners = new Set<() => void>();
@@ -473,6 +476,53 @@ export async function switchProject(id: string, selectKey?: string) {
setState((s) => ({ projectId: id, session, selected, overlay: null, redo: [], composer: composerFor(s.composer, session, selected) }));
}
+/** Adds the example projects that ship with Kokon (made by Kokon itself), except the ones
+ * already in the list, below the user's own work. Returns the first one (the tour's). */
+export async function addExampleProjects(): Promise<string | null> {
+ const { projects: examples } = await api.installExamples();
+ const now = Date.now();
+ let first: string | null = null;
+ examples.forEach((ex, i) => {
+ const have = Object.values(projects).find((p) => p.items.some((it) => it.genId === ex.generations[0]));
+ if (have) {
+ first ??= have.meta.id;
+ return;
+ }
+ const id = newKey();
+ const items: StoredItem[] = ex.generations.map((g) => ({ key: newKey(), kind: "gen", genId: g }));
+ const updatedAt = now - 60_000 - i * 1000;
+ projects[id] = { meta: { id, title: ex.title, named: true, updatedAt, cover: lastCover(items), count: items.length }, items, selected: items[items.length - 1].key };
+ first ??= id;
+ });
+ persistProjects();
+ setState({ projects: projectList() });
+ return first;
+}
+
+/** Opens the first example project on its last version and starts the tour. */
+export async function startTour() {
+ try {
+ const id = await addExampleProjects();
+ if (!id) return;
+ await switchProject(id, projects[id]?.items.at(-1)?.key);
+ setState({ tour: 0, overlay: null, sidebar: true });
+ } catch (e) {
+ toastError(e);
+ }
+}
+
+/** Closes the tour and remembers that it was seen. */
+export async function endTour() {
+ setState({ tour: null });
+ try {
+ const cfg = await api.config();
+ const ui = (cfg.ui ?? {}) as Record<string, unknown>;
+ if (!ui.tourSeen) await api.saveConfig({ ...cfg, ui: { ...ui, tourSeen: true } });
+ } catch {
+ /* shown again next time */
+ }
+}
+
/** 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);
diff --git a/src/lib/types.ts b/src/lib/types.ts
index 29cb5c4..eb55770 100644
--- a/src/lib/types.ts
+++ b/src/lib/types.ts
@@ -95,6 +95,8 @@ export interface PipelineRecord {
cache_threshold: number | null;
enlarged_with: string | null;
enlarged_from: Size | null;
+ /** The result before that enlargement, kept by the service (absent on older results). */
+ original_path?: string | null;
}
export interface GenerationRecord {
diff --git a/src/styles.css b/src/styles.css
index 4853a2b..eec62d9 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -122,6 +122,8 @@ svg { display: block; 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: 0 1 auto; min-width: 0; color: var(--text-2); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.stage-meta .dims { flex: none; }
+.stage-meta .dims-seg { flex: none; padding: 2px; border-radius: 8px; }
+.stage-meta .dims-seg button { height: 20px; border-radius: 6px; font-size: 11.5px; padding: 0 7px; }
.actions { display: flex; gap: 2px; flex: none; }
.actions .sep { width: 1px; background: var(--border); margin: 6px 4px; }
@@ -156,8 +158,10 @@ svg { display: block; flex: none; }
/* version timeline: a line per image and the versions made from it; arcs join versions made
from earlier ones or from several */
-.timeline { flex: none; display: flex; max-width: 100%; overflow-x: auto; padding: 0 8px 4px; margin: 14px 0 10px; scrollbar-width: none; }
-.timeline::-webkit-scrollbar { display: none; }
+.timeline { flex: none; display: flex; max-width: 100%; overflow-x: auto; padding: 0 8px 4px; margin: 14px 0 10px; scrollbar-width: thin; scrollbar-color: transparent transparent; transition: scrollbar-color 0.2s; }
+/* A thin bar under a timeline wider than the stage, clearer on hover. */
+.timeline.overflow { padding-bottom: 8px; margin-bottom: 6px; scrollbar-color: var(--surface-3) transparent; }
+.timeline.overflow:hover { scrollbar-color: var(--text-3) transparent; }
.track { position: relative; display: flex; align-items: flex-start; width: max-content; }
.arcs { position: absolute; left: 0; top: 0; width: 100%; overflow: visible; pointer-events: none; }
.arcs path { fill: none; stroke: var(--text-3); stroke-opacity: 0.45; stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; transition: stroke-opacity 0.15s; }
@@ -495,3 +499,19 @@ pre.diag { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font
@media (prefers-reduced-motion: reduce) { .boot-splash .kokon-mark { animation: none; } }
.welcome-check { display: inline-flex; align-items: center; gap: 8px; font-size: 13px; color: var(--text-2); cursor: pointer; }
.welcome-check input { width: 15px; height: 15px; accent-color: var(--text); margin: 0; }
+
+/* first-run tour: the target stays lit, a card explains it */
+.tour { position: fixed; inset: 0; z-index: 45; pointer-events: none; }
+.tour-hole { position: fixed; border-radius: 14px; box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.5); outline: 2px solid var(--text); outline-offset: 0; transition: left 0.25s, top 0.25s, width 0.25s, height 0.25s; }
+.tour-dim { position: fixed; inset: 0; background: rgba(0, 0, 0, 0.5); }
+.tour-card { position: fixed; pointer-events: auto; background: var(--bg); color: var(--text); border-radius: var(--radius); box-shadow: var(--shadow); border: 1px solid var(--border); padding: 14px 16px; display: flex; flex-direction: column; gap: 8px; transition: left 0.25s, top 0.25s; }
+.tour-head { display: flex; align-items: center; gap: 8px; }
+.tour-head strong { flex: 1; font-size: 14px; }
+.tour-x { width: 26px; height: 26px; border-radius: 8px; display: grid; place-items: center; color: var(--text-3); }
+.tour-x:hover { background: var(--surface); color: var(--text); }
+.tour-card p { margin: 0; font-size: 13px; line-height: 1.45; color: var(--text-2); }
+.tour-foot { display: flex; align-items: center; gap: 8px; margin-top: 4px; }
+.tour-dots { flex: 1; display: flex; gap: 5px; }
+.tour-dots i { width: 6px; height: 6px; border-radius: 50%; background: var(--surface-3); }
+.tour-dots i.on { background: var(--text); }
+@media (prefers-reduced-motion: reduce) { .tour-hole, .tour-card { transition: none; } }