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.

feat(enhancer): rewrite the prompt with the loaded text encoder before generating

Gabriele Lozupone989ad0550660
diff --git a/crates/qls-core/src/config.rs b/crates/qls-core/src/config.rs
index 30b6d94..93e68ff 100644
--- a/crates/qls-core/src/config.rs
+++ b/crates/qls-core/src/config.rs
@@ -334,6 +334,10 @@ pub struct AppConfig {
/// 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,
+ /// System prompts of the prompt enhancer for text-to-image and for edits; "" = the
+ /// built-in ones (`enhancer::T2I_SYSTEM_PROMPT`, `enhancer::EDIT_SYSTEM_PROMPT`).
+ pub enhancer_t2i_prompt: String,
+ pub enhancer_edit_prompt: String,
/// Opaque UI preferences (last quality, resolution mode, aspect...).
pub ui: serde_json::Value,
}
@@ -369,6 +373,8 @@ impl Default for AppConfig {
setup_complete: false,
hardware_preset: crate::catalog::DEFAULT_PRESET.into(),
vram_override_mib: 0,
+ enhancer_t2i_prompt: String::new(),
+ enhancer_edit_prompt: String::new(),
ui: serde_json::json!({}),
}
}
@@ -544,6 +550,12 @@ impl AppConfig {
/// the official files of the configured folder and preset (its tuning is kept), every
/// other profile is the user's, and the active profile exists.
pub fn normalize(&mut self) {
+ // A prompt equal to the built-in one is saved as "" so it follows future defaults.
+ for (custom, default) in [(&mut self.enhancer_t2i_prompt, crate::enhancer::T2I_SYSTEM_PROMPT), (&mut self.enhancer_edit_prompt, crate::enhancer::EDIT_SYSTEM_PROMPT)] {
+ if custom.trim().is_empty() || custom.trim() == default {
+ custom.clear();
+ }
+ }
for p in &mut self.profiles {
p.source = if p.id == OFFICIAL_PROFILE_ID { ProfileSource::Official } else { ProfileSource::User };
if p.model.trim().is_empty() {
@@ -770,6 +782,10 @@ impl AppConfig {
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)."));
}
+ let max = crate::enhancer::MAX_SYSTEM_PROMPT_CHARS;
+ if self.enhancer_t2i_prompt.chars().count() > max || self.enhancer_edit_prompt.chars().count() > max {
+ return Err(AppError::new(ErrorCode::InvalidConfig, format!("Prompt enhancer instructions can be at most {max} characters.")));
+ }
Ok(())
}
}
@@ -802,6 +818,25 @@ mod tests {
ModelProfile::user(m.join("diffusion_models").join("turbo_int8.safetensors"), m.join("vae").join("vae.safetensors"), m.join("text_encoders").join("qwen3vl_fused.safetensors"), None)
}
+ #[test]
+ fn enhancer_prompts_default_blank_and_are_capped() {
+ let mut c = AppConfig::default();
+ assert!(c.enhancer_t2i_prompt.is_empty() && c.enhancer_edit_prompt.is_empty(), "built-in by default");
+ // Older settings files have no such keys.
+ let old: AppConfig = serde_json::from_str(r#"{"schemaVersion":9}"#).unwrap();
+ assert!(old.enhancer_edit_prompt.is_empty());
+ // A restored default is saved blank, so it follows future defaults; a custom one stays.
+ c.enhancer_t2i_prompt = format!("{}\n", crate::enhancer::T2I_SYSTEM_PROMPT);
+ c.enhancer_edit_prompt = "Retouch jewelry only.".into();
+ c.normalize();
+ assert_eq!((c.enhancer_t2i_prompt.as_str(), c.enhancer_edit_prompt.as_str()), ("", "Retouch jewelry only."));
+ let v = serde_json::to_value(&c).unwrap();
+ assert_eq!(v["enhancerEditPrompt"], "Retouch jewelry only.");
+ assert!(c.validate().is_ok());
+ c.enhancer_edit_prompt = "x".repeat(crate::enhancer::MAX_SYSTEM_PROMPT_CHARS + 1);
+ assert!(c.validate().is_err());
+ }
+
#[test]
fn hand_edited_official_paths_move_to_the_user_profile() {
let dir = tempfile::tempdir().unwrap();
diff --git a/crates/qls-core/src/engine.rs b/crates/qls-core/src/engine.rs
index d222f7b..c4929fa 100644
--- a/crates/qls-core/src/engine.rs
+++ b/crates/qls-core/src/engine.rs
@@ -13,6 +13,7 @@ use tokio::sync::{Notify, broadcast};
use crate::config::AppConfig;
use crate::diagnostics::{GpuInfo, query_gpus};
+use crate::enhancer;
use crate::error::{AppError, AppResult, ErrorCode, translate_generation_failure};
use crate::geometry::Size;
use crate::imaging::{self, LoadedImage};
@@ -20,7 +21,7 @@ use crate::paths;
use crate::pipeline;
use crate::planner::{self, GenerationRequest, Mode, OutputFormat, Plan, PlanInputs, ResolutionMode, ResolvedMode};
use crate::process::{BackendProgress, BackendStage, ProgressParser, ServerManager, ServerState};
-use crate::sdcpp::{BackendJobStatus, CancelOutcome, SdcppClient, UpscaleRequest};
+use crate::sdcpp::{BackendJobStatus, CancelOutcome, Capabilities, SdcppClient, UpscaleRequest};
use crate::store::{GenerationRecord, InputRecord, PipelineRecord, ReferenceRecord, Store, new_id, now_rfc3339};
pub const APP_VERSION: &str = env!("CARGO_PKG_VERSION");
@@ -31,6 +32,8 @@ pub enum JobStatus {
Queued,
StartingBackend,
Preparing,
+ /// The prompt enhancer is writing the prompt (`JobView::enhanced_prompt` grows).
+ EnhancingPrompt,
Running,
Saving,
Done,
@@ -58,6 +61,9 @@ pub struct JobView {
pub started_at: Option<String>,
pub finished_at: Option<String>,
pub prompt: String,
+ /// The prompt enhancer's text: partial while `EnhancingPrompt`, then the prompt the image
+ /// is made from (`prompt` stays the user's). None when the enhancer did not run or failed.
+ pub enhanced_prompt: Option<String>,
pub client: Option<String>,
pub plan: Option<Plan>,
pub seed: Option<i64>,
@@ -74,6 +80,8 @@ struct Job {
cancel: bool,
retried_oom: bool,
workspace: Option<PathBuf>,
+ /// The prompt enhancer's finished text, kept for a retry (out of memory).
+ enhanced: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
@@ -473,6 +481,7 @@ impl Engine {
started_at: None,
finished_at: None,
prompt: if upscale && request.prompt.trim().is_empty() { "Upscale".into() } else { request.prompt.clone() },
+ enhanced_prompt: None,
client: request.client.clone(),
plan: None,
seed: request.seed,
@@ -483,7 +492,7 @@ impl Engine {
};
{
let mut jobs = self.jobs.lock().unwrap();
- jobs.insert(id.clone(), Job { view, request, cancel: false, retried_oom: false, workspace });
+ jobs.insert(id.clone(), Job { view, request, cancel: false, retried_oom: false, workspace, enhanced: None });
let mut order = self.order.lock().unwrap();
order.push_back(id.clone());
// Keep memory bounded: drop the oldest finished jobs.
@@ -667,6 +676,7 @@ impl Engine {
created_at: now_rfc3339(),
mode: "lut".into(),
prompt: String::new(),
+ original_prompt: None,
negative_prompt: String::new(),
seed: parent.as_ref().map(|p| p.seed).unwrap_or(0),
width: out.width(),
@@ -828,6 +838,7 @@ impl Engine {
}
let quick_upscale = plan.upscale.is_some();
let icc = images.first().and_then(|i| i.icc_profile.clone());
+ let mut enhanced: Option<String> = None;
let (contents, post) = if quick_upscale {
// No diffusion: the source itself is enlarged.
@@ -852,7 +863,16 @@ impl Engine {
let prepared = tokio::task::spawn_blocking(move || pipeline::prepare(&plan2, &prompt, seed, &images, mask_img.as_ref(), &opts))
.await
.map_err(AppError::internal)??;
- let pipeline::PreparedJob { request: sd_req, post } = prepared;
+ let pipeline::PreparedJob { request: mut sd_req, post } = prepared;
+
+ // 4b. Prompt enhancer: rewrites the user's prompt, looking at the references
+ // exactly as the image model gets them.
+ if request.enhance && enhancer::applies(plan.mode) {
+ enhanced = self.enhance_prompt(id, &client, &caps, &cfg, plan.mode, &request.prompt, &sd_req.ref_images, seed).await?;
+ if let Some(text) = &enhanced {
+ sd_req.prompt = pipeline::enhanced_prompt(&request.prompt, text);
+ }
+ }
// 5. Submit and follow.
let mut lines = self.server.subscribe_lines();
@@ -987,12 +1007,12 @@ impl Engine {
if let Some(j) = self.job(id) {
plan3.notes = j.notes;
}
- let (p, req3, inputs3, mask3, icc3, ws) = (post.clone(), request.clone(), inputs_meta.clone(), mask_rec.clone(), icc.clone(), workspace.clone());
+ let (p, req3, inputs3, mask3, icc3, ws, enh3) = (post.clone(), request.clone(), inputs_meta.clone(), mask_rec.clone(), icc.clone(), workspace.clone(), enhanced.clone());
let rec = blocking(move || {
let final_img = pipeline::finish(content, &p)?;
let duration_ms = duration_start.elapsed().as_millis() as u64;
let pipeline = (pipeline_rec != PipelineRecord::default()).then_some(pipeline_rec);
- this.save_result(&final_img, &req3, &plan3, seed + i as i64, &inputs3, mask3.as_ref(), icc3.as_deref(), duration_ms, ws.as_deref(), i, pipeline, original.as_ref())
+ 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(), enh3)
})
.await?;
if !request.private {
@@ -1009,6 +1029,75 @@ impl Engine {
Ok(())
}
+ /// Runs the prompt enhancer for job `id` and streams its text into the job. Returns the
+ /// new prompt, or None when the job keeps the user's prompt: the engine cannot write text,
+ /// or the enhancer failed (both noted on the job). Errors only for a cancel or a crash.
+ #[allow(clippy::too_many_arguments)]
+ async fn enhance_prompt(&self, id: &str, client: &SdcppClient, caps: &Capabilities, cfg: &AppConfig, mode: ResolvedMode, prompt: &str, images: &[String], seed: i64) -> AppResult<Option<String>> {
+ // A retry after running out of memory keeps the first prompt.
+ if let Some(done) = self.jobs.lock().unwrap().get(id).and_then(|j| j.enhanced.clone()) {
+ return Ok(Some(done));
+ }
+ if !caps.text_generation {
+ self.update(id, |j| j.view.notes.push("This inference engine has no prompt enhancer (update it in Setup); your prompt was used as written.".into()));
+ return Ok(None);
+ }
+ self.update(id, |j| {
+ j.view.status = JobStatus::EnhancingPrompt;
+ j.view.stage = None;
+ j.view.enhanced_prompt = Some(String::new());
+ });
+ let req = enhancer::request(cfg, mode, prompt, images.to_vec(), seed);
+ let started = Instant::now();
+ let mut text = String::new();
+ let mut last_emit = Instant::now();
+ let on_delta = |d: &str| {
+ text.push_str(d);
+ // The UI follows the text at ~10 updates a second.
+ if last_emit.elapsed() >= Duration::from_millis(100) {
+ last_emit = Instant::now();
+ let partial = text.clone();
+ self.update(id, |j| j.view.enhanced_prompt = Some(partial));
+ }
+ };
+ let r = client.text_gen(&req, Duration::from_secs(300), on_delta, || self.is_cancelled(id)).await;
+ let failure = match r {
+ Ok(done) => match enhancer::clean(&done.text) {
+ Some(t) => {
+ tracing::info!("prompt enhancer: {} tokens in {:.1} s ({}, seed {})", done.usage.completion_tokens, started.elapsed().as_secs_f32(), done.finish_reason, done.seed);
+ let cut = done.finish_reason == "length";
+ self.update(id, |j| {
+ j.view.enhanced_prompt = Some(t.clone());
+ j.enhanced = Some(t.clone());
+ if cut {
+ j.view.notes.push("The prompt enhancer reached its length limit; its prompt may end abruptly.".into());
+ }
+ });
+ return Ok(Some(t));
+ }
+ None => "it wrote nothing".to_string(),
+ },
+ Err(e) if e.code == ErrorCode::Cancelled => return Err(e),
+ Err(e) => {
+ if self.server.owned_alive() == Some(false) {
+ let tail = self.server.log.tail(30).join("\n");
+ self.server.mark_lost(AppError::new(ErrorCode::ServerCrashed, "The inference server stopped unexpectedly."));
+ self.emit_server();
+ return Err(AppError::new(ErrorCode::ServerCrashed, "The inference server stopped while writing the prompt.")
+ .suggest("It will restart automatically on the next job. Turn the prompt enhancer off if it happens again.")
+ .detail(tail));
+ }
+ tracing::warn!("prompt enhancer failed: {} {:?}", e.message, e.detail);
+ e.detail.clone().map(|d| format!("{} {d}", e.message)).unwrap_or(e.message)
+ }
+ };
+ self.update(id, |j| {
+ j.view.enhanced_prompt = None;
+ j.view.notes.push(format!("The prompt enhancer failed ({}); your prompt was used as written.", failure.trim_end_matches('.')));
+ });
+ Ok(None)
+ }
+
/// Label of an upscale request that has no prompt: the source's own prompt, if any.
fn upscale_prompt(&self, req: &GenerationRequest) -> String {
let source = req.images.first().and_then(|s| s.strip_prefix("gen:")).and_then(|g| self.gen_store(g).get_generation(g).ok());
@@ -1163,6 +1252,7 @@ impl Engine {
index: usize,
mut pipeline: Option<PipelineRecord>,
original: Option<&image::RgbaImage>,
+ enhanced_prompt: Option<String>,
) -> AppResult<GenerationRecord> {
let cfg = self.config();
let id = new_id();
@@ -1204,7 +1294,9 @@ impl Engine {
id: id.clone(),
created_at: now_rfc3339(),
mode: mode.into(),
- prompt: req.prompt.clone(),
+ // An enhanced job records the prompt the image was made from, and the user's.
+ original_prompt: enhanced_prompt.is_some().then(|| req.prompt.clone()),
+ prompt: enhanced_prompt.unwrap_or_else(|| req.prompt.clone()),
negative_prompt: plan.negative_prompt.clone(),
seed,
width: img.width(),
@@ -1457,6 +1549,85 @@ mod tests {
assert_eq!(e.job(&mcp.id).unwrap().status, JobStatus::Queued);
}
+ #[tokio::test]
+ async fn prompt_enhancer_streams_falls_back_and_is_kept_for_retries() {
+ use crate::sdcpp::{fake_server, sse_answer};
+ let dir = tempfile::tempdir().unwrap();
+ // SAFETY: test-only env override, single-threaded setup.
+ unsafe { std::env::set_var("QLS_CONFIG_DIR", dir.path().join("cfg")) };
+ let mut cfg = AppConfig::default();
+ cfg.sdcpp_dir = dir.path().join("sdcpp");
+ cfg.normalize();
+ std::fs::create_dir_all(cfg.engine_dir()).unwrap();
+ std::fs::write(cfg.server_exe(), b"").unwrap();
+ for (_, p, _) in cfg.profile().files() {
+ std::fs::create_dir_all(p.parent().unwrap()).unwrap();
+ std::fs::write(p, b"").unwrap();
+ }
+ let e = Engine::new(cfg.clone(), dir.path()).unwrap();
+ let caps = Capabilities { text_generation: true, ..Default::default() };
+ let submit = || e.submit(GenerationRequest { prompt: "rendi il gatto nero".into(), enhance: true, ..Default::default() }, None).unwrap().id;
+ let images = vec!["PNG1".to_string()];
+
+ // Streams into the job (~10 updates a second) and keeps the finished text.
+ let id = submit();
+ let mut events = e.events.subscribe();
+ let (port, body) = fake_server(200, "text/event-stream", sse_answer(&["Change the cat's", " fur to black."], "stop"), Duration::from_millis(150)).await;
+ let out = e.enhance_prompt(&id, &SdcppClient::new(port), &caps, &cfg, ResolvedMode::Edit, "rendi il gatto nero", &images, 42).await.unwrap();
+ assert_eq!(out.as_deref(), Some("Change the cat's fur to black."));
+ let mut partial = false;
+ while let Ok(ev) = events.try_recv() {
+ if let Event::Job { job } = ev {
+ partial |= job.status == JobStatus::EnhancingPrompt && job.enhanced_prompt.as_deref() == Some("Change the cat's");
+ }
+ }
+ assert!(partial, "the job shows the text while it is written");
+ let v = e.job(&id).unwrap();
+ assert_eq!((v.enhanced_prompt.as_deref(), v.prompt.as_str()), (Some("Change the cat's fur to black."), "rendi il gatto nero"));
+ let sent: serde_json::Value = serde_json::from_str(&body.await.unwrap()).unwrap();
+ assert_eq!((sent["images"][0].as_str(), sent["sampling"]["seed"].as_i64()), (Some("PNG1"), Some(42)), "the references and the job's seed");
+ assert_eq!(sent["system_prompt"], enhancer::EDIT_SYSTEM_PROMPT);
+ // A retry (out of memory) keeps that prompt without asking the server again.
+ let again = e.enhance_prompt(&id, &SdcppClient::new(1), &caps, &cfg, ResolvedMode::Edit, "rendi il gatto nero", &images, 43).await.unwrap();
+ assert_eq!(again, out);
+
+ // A failure keeps the user's prompt, with a note.
+ let id = submit();
+ let chunks = vec!["event: delta\ndata: {\"text\":\"Chan\"}\n\n".into(), "event: error\ndata: {\"error\":\"out of memory\"}\n\n".into()];
+ let (port, _) = fake_server(200, "text/event-stream", chunks, Duration::from_millis(1)).await;
+ assert_eq!(e.enhance_prompt(&id, &SdcppClient::new(port), &caps, &cfg, ResolvedMode::Generate, "un gatto", &[], 1).await.unwrap(), None);
+ let v = e.job(&id).unwrap();
+ assert_eq!(v.enhanced_prompt, None);
+ assert!(v.notes.last().is_some_and(|n| n.contains("prompt enhancer failed") && n.contains("out of memory") && n.ends_with("used as written.")), "{:?}", v.notes);
+ // An empty answer too.
+ let id = submit();
+ let (port, _) = fake_server(200, "text/event-stream", sse_answer(&[" "], "stop"), Duration::ZERO).await;
+ assert_eq!(e.enhance_prompt(&id, &SdcppClient::new(port), &caps, &cfg, ResolvedMode::Generate, "un gatto", &[], 1).await.unwrap(), None);
+ assert!(e.job(&id).unwrap().notes.last().unwrap().contains("wrote nothing"));
+ // A cut-off answer is used, with a note.
+ let id = submit();
+ let (port, _) = fake_server(200, "text/event-stream", sse_answer(&["A cat on a"], "length"), Duration::ZERO).await;
+ assert_eq!(e.enhance_prompt(&id, &SdcppClient::new(port), &caps, &cfg, ResolvedMode::Generate, "un gatto", &[], 1).await.unwrap().as_deref(), Some("A cat on a"));
+ assert!(e.job(&id).unwrap().notes.last().unwrap().contains("length limit"));
+
+ // An engine without text generation (official builds): note, no request.
+ let id = submit();
+ assert_eq!(e.enhance_prompt(&id, &SdcppClient::new(1), &Capabilities::default(), &cfg, ResolvedMode::Generate, "un gatto", &[], 1).await.unwrap(), None);
+ assert!(e.job(&id).unwrap().notes.last().unwrap().contains("no prompt enhancer"));
+ assert_eq!(e.job(&id).unwrap().status, JobStatus::Queued, "status untouched");
+
+ // Cancel while the enhancer is writing: the job stops.
+ let id = submit();
+ let (port, _) = fake_server(200, "text/event-stream", sse_answer(&["slow"], "stop"), Duration::from_secs(30)).await;
+ let (e2, id2) = (e.clone(), id.clone());
+ tokio::spawn(async move {
+ tokio::time::sleep(Duration::from_millis(300)).await;
+ e2.cancel(&id2).unwrap();
+ });
+ let err = e.enhance_prompt(&id, &SdcppClient::new(port), &caps, &cfg, ResolvedMode::Generate, "un gatto", &[], 1).await.unwrap_err();
+ assert_eq!(err.code, ErrorCode::Cancelled);
+ }
+
#[test]
fn private_results_stay_out_of_the_gallery() {
let dir = tempfile::tempdir().unwrap();
diff --git a/crates/qls-core/src/enhancer.rs b/crates/qls-core/src/enhancer.rs
new file mode 100644
index 0000000..1a78734
--- /dev/null
+++ b/crates/qls-core/src/enhancer.rs
@@ -0,0 +1,130 @@
+//! Prompt enhancer: the Qwen3-VL 8B that Qwen-Image 2.1 already loads as its text encoder
+//! rewrites the user's short instruction into a full English prompt (looking at the input
+//! images for edits) before the image is generated. Runs on Kokon's engine builds only
+//! (`Capabilities::text_generation`, `POST /sdcpp/v1/text_gen`); the server has no built-in
+//! system prompt, so Kokon always sends one: the user's from Settings or the defaults below.
+//! Design and the A/B behind these texts: docs/prompt-enhancer.md.
+
+use crate::config::AppConfig;
+use crate::planner::ResolvedMode;
+use crate::sdcpp::{TextGenRequest, TextSampling};
+
+/// Built-in system prompt for text-to-image (docs/prompt-enhancer.md, decided 2026-10-18).
+pub const T2I_SYSTEM_PROMPT: &str = r#"You write prompts for an image generation model. Expand the user's request into one detailed English paragraph that describes the finished image: subject, setting, composition, lighting and style.
+- Keep everything the user specified (objects, counts, colours, positions, style) and never contradict it. If the request is already detailed, keep all of it and only add what is missing.
+- Text that must appear in the image: copy it exactly, in its original language and script, inside double quotes, and say where it is and how it looks. Do not add any text the user did not ask for.
+- Name the medium and style near the start (photograph, watercolour, poster, 3D render, ...).
+- Always describe the light: its source, direction and quality.
+- Be concrete: colours with a modifier (deep navy, pale cream), materials, where things are in the frame. Never write vague words like "various items".
+- People: only what is visible (life stage, expression, pose, hair, clothing). No brand names unless the user gave them.
+- No quality tags such as "masterpiece", "8K" or "highly detailed", and no resolution or aspect ratio.
+- Write in English whatever language the user writes in, about 80 to 150 words, in the present tense, as a description of the image, not as instructions.
+Output only the prompt."#;
+
+/// Built-in system prompt for image-grounded edits and combines.
+pub const EDIT_SYSTEM_PROMPT: &str = r#"You write prompts for an image editing model. You see the input image and the user's instruction. Rewrite the instruction as one precise English editing instruction.
+- Start with the operation (Change, Replace, Remove, Add, Turn, ...) and say exactly what changes, where it is in the image and what it becomes. Make the change complete and clearly visible, not faint.
+- Describe in detail only what changes. For everything else end with one sentence such as "Keep everything else in the image unchanged." Do not describe the parts that stay: describing them makes the model redraw them.
+- People keep their face and identity, and the image keeps its medium (photo, painting, illustration), unless the user asks to change them.
+- Base every detail on what is visible in the image and do not invent objects. Do only what the user asked: no extra fixes or additions.
+- When something is removed or moved, say briefly what fills the empty area so the result looks natural.
+- Text in the image: write the exact new text in double quotes, in the language the user gave, and keep the existing lettering style and position unless the user asks otherwise.
+- For a style or mood change (painting, season, night, ...), apply it fully to the whole image and keep the composition and the subjects.
+- With several input images, refer to them as <image1>, <image2>, ... and say what is taken from each.
+- Write in English whatever language the user writes in, as one paragraph of about 20 to 60 words, with no resolution or aspect ratio.
+Output only the instruction."#;
+
+/// Longest custom system prompt accepted in Settings (characters).
+pub const MAX_SYSTEM_PROMPT_CHARS: usize = 20_000;
+
+/// The built-in prompts ask for ≤ 150 words (~200 tokens); the cap only stops a model that
+/// does not end its turn.
+pub const MAX_TOKENS: u32 = 512;
+
+/// Qwen's recommended sampling for Qwen3-VL (vision-language), used for both prompts.
+pub const SAMPLING: TextSampling = TextSampling { temperature: 0.7, top_p: 0.8, top_k: 20, presence_penalty: 1.5, seed: -1 };
+
+/// Text-to-image, edits and combines get the enhancer. Inpaint and outpaint wrap the prompt
+/// in their own instructions, and upscales have no prompt.
+pub fn applies(mode: ResolvedMode) -> bool {
+ matches!(mode, ResolvedMode::Generate | ResolvedMode::Edit | ResolvedMode::MultiReference)
+}
+
+/// The system prompt for `mode`: the one saved in Settings, or the built-in one.
+pub fn system_prompt(cfg: &AppConfig, mode: ResolvedMode) -> String {
+ let (custom, default) = if mode == ResolvedMode::Generate { (&cfg.enhancer_t2i_prompt, T2I_SYSTEM_PROMPT) } else { (&cfg.enhancer_edit_prompt, EDIT_SYSTEM_PROMPT) };
+ if custom.trim().is_empty() { default.to_string() } else { custom.trim().to_string() }
+}
+
+/// The `text_gen` request for a job: its seed (so the same seed writes the same prompt, and
+/// Regenerate writes a new one) and, for edits, the references as the image model gets them.
+pub fn request(cfg: &AppConfig, mode: ResolvedMode, prompt: &str, images: Vec<String>, seed: i64) -> TextGenRequest {
+ TextGenRequest {
+ prompt: prompt.trim().to_string(),
+ system_prompt: system_prompt(cfg, mode),
+ images: if mode == ResolvedMode::Generate { Vec::new() } else { images },
+ max_tokens: MAX_TOKENS,
+ sampling: TextSampling { seed, ..SAMPLING },
+ stream: true,
+ }
+}
+
+/// The model's answer as a prompt: trimmed, without a "Prompt:" label or quotes around the
+/// whole text. None when nothing usable is left.
+pub fn clean(text: &str) -> Option<String> {
+ let mut t = text.trim();
+ for label in ["Prompt:", "Instruction:", "Editing instruction:"] {
+ if t.get(..label.len()).is_some_and(|head| head.eq_ignore_ascii_case(label)) {
+ t = t[label.len()..].trim_start();
+ }
+ }
+ // Quotes around everything, but not quoted text inside (text to render in the image).
+ if t.len() >= 2 && t.starts_with('"') && t.ends_with('"') && !t[1..t.len() - 1].contains('"') {
+ t = t[1..t.len() - 1].trim();
+ }
+ (!t.is_empty()).then(|| t.to_string())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn modes_and_prompts() {
+ assert!(applies(ResolvedMode::Generate) && applies(ResolvedMode::Edit) && applies(ResolvedMode::MultiReference));
+ assert!(!applies(ResolvedMode::Inpaint) && !applies(ResolvedMode::Outpaint) && !applies(ResolvedMode::Upscale));
+ let mut cfg = AppConfig::default();
+ assert_eq!(system_prompt(&cfg, ResolvedMode::Generate), T2I_SYSTEM_PROMPT);
+ assert_eq!(system_prompt(&cfg, ResolvedMode::Edit), EDIT_SYSTEM_PROMPT);
+ assert_eq!(system_prompt(&cfg, ResolvedMode::MultiReference), EDIT_SYSTEM_PROMPT);
+ cfg.enhancer_edit_prompt = " Jewelry retouch rules.\n".into();
+ cfg.enhancer_t2i_prompt = " \n ".into();
+ assert_eq!(system_prompt(&cfg, ResolvedMode::Edit), "Jewelry retouch rules.");
+ assert_eq!(system_prompt(&cfg, ResolvedMode::Generate), T2I_SYSTEM_PROMPT, "blank = built-in");
+ assert!(T2I_SYSTEM_PROMPT.ends_with("Output only the prompt.") && EDIT_SYSTEM_PROMPT.contains("<image1>, <image2>"));
+ }
+
+ #[test]
+ fn request_uses_job_seed_and_images_only_for_edits() {
+ let cfg = AppConfig::default();
+ let r = request(&cfg, ResolvedMode::Edit, " rendi la macchina nera ", vec!["PNG".into()], 1234);
+ assert_eq!((r.prompt.as_str(), r.images.len(), r.sampling.seed, r.max_tokens), ("rendi la macchina nera", 1, 1234, MAX_TOKENS));
+ assert_eq!((r.sampling.temperature, r.sampling.top_p, r.sampling.top_k, r.sampling.presence_penalty), (0.7, 0.8, 20, 1.5));
+ assert!(r.stream);
+ let r = request(&cfg, ResolvedMode::Generate, "un gatto", vec!["PNG".into()], 1);
+ assert!(r.images.is_empty() && r.system_prompt == T2I_SYSTEM_PROMPT);
+ }
+
+ #[test]
+ fn cleaning() {
+ assert_eq!(clean(" A watercolour fox.\n").as_deref(), Some("A watercolour fox."));
+ assert_eq!(clean("Prompt: A fox.").as_deref(), Some("A fox."));
+ assert_eq!(clean("\"A fox in snow.\"").as_deref(), Some("A fox in snow."));
+ let sign = "A shop sign reading \"CAFÉ\" above the door, lit by \"warm\" lamps.";
+ assert_eq!(clean(sign).as_deref(), Some(sign), "inner quotes are text to render");
+ assert_eq!(clean("\"OPEN\" glows in red neon above a \"BAR\"").as_deref(), Some("\"OPEN\" glows in red neon above a \"BAR\""));
+ assert_eq!(clean(" \n "), None);
+ assert_eq!(clean("Prompt:"), None);
+ assert_eq!(clean("Ünïcode first").as_deref(), Some("Ünïcode first"), "no slicing inside a character");
+ }
+}
diff --git a/crates/qls-core/src/examples.rs b/crates/qls-core/src/examples.rs
index 00b2a4d..f1dc106 100644
--- a/crates/qls-core/src/examples.rs
+++ b/crates/qls-core/src/examples.rs
@@ -143,6 +143,7 @@ impl Engine {
created_at: format!("2026-10-10T09:{:02}:{:02}.000Z", pi * 5, si * 10),
mode,
prompt: s.prompt.into(),
+ original_prompt: None,
negative_prompt: String::new(),
seed: s.seed,
width: img.width(),
diff --git a/crates/qls-core/src/lib.rs b/crates/qls-core/src/lib.rs
index cdd3098..859d975 100644
--- a/crates/qls-core/src/lib.rs
+++ b/crates/qls-core/src/lib.rs
@@ -2,6 +2,7 @@ pub mod catalog;
pub mod config;
pub mod diagnostics;
pub mod engine;
+pub mod enhancer;
pub mod engine_manifest;
pub mod error;
pub mod examples;
diff --git a/crates/qls-core/src/pipeline.rs b/crates/qls-core/src/pipeline.rs
index 0d67c3a..5c63046 100644
--- a/crates/qls-core/src/pipeline.rs
+++ b/crates/qls-core/src/pipeline.rs
@@ -157,6 +157,17 @@ pub fn effective_prompt(plan: &Plan, prompt: &str) -> String {
}
}
+/// The prompt sent for an enhanced job (text-to-image, edit, combine): the enhancer's text,
+/// wrapped for transparency when the user's own words asked for it (not the rewrite's, which
+/// may mention "transparent glass").
+pub fn enhanced_prompt(original: &str, enhanced: &str) -> String {
+ let p = enhanced.trim();
+ if wants_transparency(original) && !p.starts_with(RGBA_PREFIX) {
+ return format!("{RGBA_PREFIX} {}. {RGBA_SUFFIX}", p.trim_end_matches('.'));
+ }
+ p.to_string()
+}
+
pub fn prepare(plan: &Plan, prompt: &str, seed: i64, images: &[LoadedImage], mask: Option<&GrayImage>, opts: &BackendOptions) -> AppResult<PreparedJob> {
let first = plan.working;
let mut req = ImgGenRequest {
@@ -527,6 +538,15 @@ pub fn tile_png_b64(input: &RgbaImage, tile: &Tile) -> AppResult<String> {
mod tests {
use super::*;
+ #[test]
+ fn enhanced_prompt_follows_the_users_words_for_transparency() {
+ assert_eq!(enhanced_prompt("un gatto", " A tabby cat on a sill.\n"), "A tabby cat on a sill.");
+ assert_eq!(enhanced_prompt("a vase", "A transparent glass vase on oak."), "A transparent glass vase on oak.", "the rewrite's words do not ask for alpha");
+ let p = enhanced_prompt("a logo with transparent background", "A flat fox logo.");
+ assert_eq!(p, format!("{RGBA_PREFIX} A flat fox logo. {RGBA_SUFFIX}"));
+ assert_eq!(enhanced_prompt("transparent", &p), p, "not wrapped twice");
+ }
+
#[test]
fn prescale_and_blend() {
let c = Size::new(1448, 1448);
diff --git a/crates/qls-core/src/planner.rs b/crates/qls-core/src/planner.rs
index e9f00b4..5c49a70 100644
--- a/crates/qls-core/src/planner.rs
+++ b/crates/qls-core/src/planner.rs
@@ -271,6 +271,10 @@ pub struct GenerationRequest {
/// output folder) that is deleted when private mode ends or the service exits.
#[serde(default)]
pub private: bool,
+ /// Prompt enhancer: the text encoder's LLM rewrites `prompt` into a full prompt before
+ /// generating (text-to-image, edits, combines; engines with text generation only).
+ #[serde(default)]
+ pub enhance: bool,
}
// ---------------------------------------------------------------------------------------
diff --git a/crates/qls-core/src/sdcpp.rs b/crates/qls-core/src/sdcpp.rs
index 6f46f5e..679318d 100644
--- a/crates/qls-core/src/sdcpp.rs
+++ b/crates/qls-core/src/sdcpp.rs
@@ -7,6 +7,7 @@
//! GET /sdcpp/v1/jobs/{id} -> {status: queued|generating|completed|failed|cancelled, ...}
//! POST /sdcpp/v1/jobs/{id}/cancel -> 200, or 409 while generating (not interruptible)
//! POST /sdcpp/v1/upscale -> 200 {images, upscaler, scale, width, height} (sync ESRGAN)
+//! POST /sdcpp/v1/text_gen -> SSE delta/done/error (Kokon's engine: prompt enhancer)
//!
//! Request objects are merged field by field over the server's launch defaults
//! (`SDGenerationParams::from_json_str`), so omitted fields keep the CLI values.
@@ -190,6 +191,9 @@ pub struct Capabilities {
/// Whether any RGB ESRGAN model is available for `/sdcpp/v1/upscale`.
#[serde(default)]
pub upscale: bool,
+ /// Whether `/sdcpp/v1/text_gen` works with the loaded model (Kokon's engine builds only).
+ #[serde(default)]
+ pub text_generation: bool,
}
impl Capabilities {
@@ -295,6 +299,88 @@ pub struct UpscaleResponse {
pub height: u32,
}
+/// Sampling of `POST /sdcpp/v1/text_gen` (`temperature` 0 = greedy).
+#[derive(Debug, Clone, Copy, Serialize, PartialEq)]
+pub struct TextSampling {
+ pub temperature: f32,
+ pub top_p: f32,
+ pub top_k: u32,
+ pub presence_penalty: f32,
+ /// Negative = the server picks one.
+ pub seed: i64,
+}
+
+/// Body of `POST /sdcpp/v1/text_gen`: one chat turn for the LLM the model uses as its text
+/// encoder.
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct TextGenRequest {
+ pub prompt: String,
+ /// Always sent; "" means no system turn (the server has no built-in prompt).
+ pub system_prompt: String,
+ /// Base64 images shown before the prompt (`<image1>`, `<image2>`, ... when several).
+ #[serde(skip_serializing_if = "Vec::is_empty")]
+ pub images: Vec<String>,
+ pub max_tokens: u32,
+ pub sampling: TextSampling,
+ pub stream: bool,
+}
+
+#[derive(Debug, Clone, Deserialize, Default, PartialEq)]
+pub struct TextUsage {
+ #[serde(default)]
+ pub prompt_tokens: u32,
+ #[serde(default)]
+ pub completion_tokens: u32,
+}
+
+/// The `done` event of `text_gen` (the whole reply with `stream: false`).
+#[derive(Debug, Clone, Deserialize, Default)]
+pub struct TextGenDone {
+ #[serde(default)]
+ pub text: String,
+ /// "stop", "length" or "cancelled".
+ #[serde(default)]
+ pub finish_reason: String,
+ #[serde(default)]
+ pub seed: i64,
+ #[serde(default)]
+ pub usage: TextUsage,
+ /// Seconds: prepare_s, image_s, prefill_s, decode_s.
+ #[serde(default)]
+ pub timings: serde_json::Value,
+}
+
+/// Splits a `text/event-stream` body into (event, data) pairs. Bytes are buffered until the
+/// blank line that ends an event, so a chunk may end inside a line or a UTF-8 character.
+/// Comment lines (": waiting for the model") are skipped.
+#[derive(Default)]
+pub struct SseParser {
+ buf: Vec<u8>,
+}
+
+impl SseParser {
+ pub fn push(&mut self, chunk: &[u8]) -> Vec<(String, String)> {
+ self.buf.extend(chunk.iter().filter(|&&b| b != b'\r'));
+ let mut events = Vec::new();
+ while let Some(end) = self.buf.windows(2).position(|w| w == b"\n\n") {
+ let block: Vec<u8> = self.buf.drain(..end + 2).collect();
+ let text = String::from_utf8_lossy(&block[..end]);
+ let (mut event, mut data) = (String::new(), Vec::new());
+ for line in text.lines() {
+ if let Some(v) = line.strip_prefix("event:") {
+ event = v.trim().to_string();
+ } else if let Some(v) = line.strip_prefix("data:") {
+ data.push(v.strip_prefix(' ').unwrap_or(v));
+ }
+ }
+ if !data.is_empty() || !event.is_empty() {
+ events.push((if event.is_empty() { "message".into() } else { event }, data.join("\n")));
+ }
+ }
+ events
+ }
+}
+
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CancelOutcome {
Cancelled,
@@ -396,6 +482,78 @@ impl SdcppClient {
}
}
+ /// Streams `POST /sdcpp/v1/text_gen`: `on_delta` gets each piece of text as it is written.
+ /// `cancelled` is checked a few times a second; returning true drops the connection, which
+ /// stops the generation on the server. `idle` limits the wait for the next chunk (the
+ /// server first waits for a running generation, then reads the images).
+ pub async fn text_gen(&self, req: &TextGenRequest, idle: Duration, mut on_delta: impl FnMut(&str), cancelled: impl Fn() -> bool) -> Result<TextGenDone, AppError> {
+ use futures_util::StreamExt;
+ let cancel_err = || AppError::new(ErrorCode::Cancelled, "Cancelled.");
+ let failed = |detail: String| AppError::new(ErrorCode::GenerationFailed, "The prompt enhancer failed.").detail(detail);
+ let body = serde_json::to_vec(&TextGenRequest { stream: true, ..req.clone() }).map_err(AppError::internal)?;
+ let r = self
+ .http
+ .post(format!("{}/sdcpp/v1/text_gen", self.base))
+ .header("Content-Type", "application/json")
+ .header("Accept", "text/event-stream")
+ .body(body)
+ .send()
+ .await
+ .map_err(unavailable)?;
+ let status = r.status().as_u16();
+ if status != 200 {
+ let text = r.text().await.unwrap_or_default();
+ let msg = serde_json::from_str::<serde_json::Value>(&text).ok().and_then(|v| v["error"].as_str().map(str::to_owned)).unwrap_or(text);
+ return Err(match status {
+ 404 => AppError::new(ErrorCode::Unsupported, "This inference engine cannot write prompts.").detail(msg),
+ 400 => AppError::new(ErrorCode::MalformedRequest, "The inference server rejected the prompt request.").detail(msg),
+ _ => failed(format!("HTTP {status}: {msg}")),
+ });
+ }
+ let mut stream = r.bytes_stream();
+ let mut parser = SseParser::default();
+ let mut last_chunk = std::time::Instant::now();
+ loop {
+ let chunk = tokio::select! {
+ c = stream.next() => c,
+ _ = tokio::time::sleep(Duration::from_millis(200)) => {
+ if cancelled() {
+ return Err(cancel_err());
+ }
+ if last_chunk.elapsed() > idle {
+ return Err(failed(format!("no answer for {} s", idle.as_secs())));
+ }
+ continue;
+ }
+ };
+ let bytes = match chunk {
+ Some(Ok(b)) => b,
+ Some(Err(e)) => return Err(failed(format!("connection broke: {e}"))),
+ None => return Err(failed("the stream ended without an answer".into())),
+ };
+ last_chunk = std::time::Instant::now();
+ for (event, data) in parser.push(&bytes) {
+ let json = serde_json::from_str::<serde_json::Value>(&data).ok();
+ match event.as_str() {
+ "delta" => {
+ if let Some(t) = json.as_ref().and_then(|v| v["text"].as_str()) {
+ on_delta(t);
+ }
+ }
+ "done" => {
+ return serde_json::from_str(&data)
+ .map_err(|e| AppError::new(ErrorCode::Unsupported, "Unexpected reply from the prompt enhancer.").detail(format!("{e}: {data}")));
+ }
+ "error" => return Err(failed(json.as_ref().and_then(|v| v["error"].as_str().map(str::to_owned)).unwrap_or(data))),
+ _ => {}
+ }
+ }
+ if cancelled() {
+ return Err(cancel_err());
+ }
+ }
+ }
+
pub async fn job(&self, id: &str) -> Result<BackendJob, AppError> {
let r = self
.http
@@ -441,10 +599,114 @@ pub fn parse_version_banner(text: &str) -> Option<String> {
Some(line.trim().trim_start_matches("stable-diffusion.cpp").trim().to_string())
}
+/// A one-shot HTTP server on 127.0.0.1 for tests: answers the first request with `status`
+/// and `chunks` (sent `gap` apart, then the connection closes) and hands back the request body.
+#[cfg(test)]
+pub(crate) async fn fake_server(status: u16, content_type: &'static str, chunks: Vec<String>, gap: Duration) -> (u16, tokio::sync::oneshot::Receiver<String>) {
+ use tokio::io::{AsyncReadExt, AsyncWriteExt};
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let (tx, rx) = tokio::sync::oneshot::channel();
+ tokio::spawn(async move {
+ let (mut sock, _) = listener.accept().await.unwrap();
+ let mut req = Vec::new();
+ let mut buf = [0u8; 8192];
+ // Headers, then Content-Length bytes of body.
+ let body = loop {
+ let n = sock.read(&mut buf).await.unwrap();
+ req.extend_from_slice(&buf[..n]);
+ let text = String::from_utf8_lossy(&req).to_string();
+ if let Some(end) = text.find("\r\n\r\n") {
+ let len = text.lines().find_map(|l| l.to_ascii_lowercase().strip_prefix("content-length:").map(|v| v.trim().parse::<usize>().unwrap())).unwrap_or(0);
+ if req.len() >= end + 4 + len {
+ break String::from_utf8_lossy(&req[end + 4..end + 4 + len]).to_string();
+ }
+ }
+ };
+ let _ = tx.send(body);
+ let head = format!("HTTP/1.1 {status} X\r\nContent-Type: {content_type}\r\nConnection: close\r\n\r\n");
+ if sock.write_all(head.as_bytes()).await.is_err() {
+ return;
+ }
+ for c in chunks {
+ tokio::time::sleep(gap).await;
+ if sock.write_all(c.as_bytes()).await.is_err() {
+ return; // the client hung up (cancel)
+ }
+ }
+ });
+ (port, rx)
+}
+
+/// SSE chunks of a `text_gen` that writes `pieces` and ends with `done`.
+#[cfg(test)]
+pub(crate) fn sse_answer(pieces: &[&str], finish: &str) -> Vec<String> {
+ let mut v = vec![": waiting for the model\n\n".to_string()];
+ for p in pieces {
+ v.push(format!("event: delta\ndata: {}\n\n", serde_json::json!({ "text": p })));
+ }
+ let done = serde_json::json!({ "text": pieces.concat(), "finish_reason": finish, "seed": 7, "usage": { "prompt_tokens": 60, "completion_tokens": pieces.len() } });
+ v.push(format!("event: done\ndata: {done}\n\n"));
+ v
+}
+
#[cfg(test)]
mod tests {
use super::*;
+ fn text_req() -> TextGenRequest {
+ TextGenRequest {
+ prompt: "un gatto".into(),
+ system_prompt: "sys".into(),
+ images: vec![],
+ max_tokens: 64,
+ sampling: TextSampling { temperature: 0.7, top_p: 0.8, top_k: 20, presence_penalty: 1.5, seed: 7 },
+ stream: false,
+ }
+ }
+
+ #[tokio::test]
+ async fn text_gen_streams_deltas_and_returns_done() {
+ let (port, body) = fake_server(200, "text/event-stream", sse_answer(&["A tabby", " cat on", " a sill."], "stop"), Duration::from_millis(5)).await;
+ let mut seen = Vec::new();
+ let done = SdcppClient::new(port).text_gen(&text_req(), Duration::from_secs(10), |d| seen.push(d.to_string()), || false).await.unwrap();
+ assert_eq!(seen, ["A tabby", " cat on", " a sill."]);
+ assert_eq!((done.text.as_str(), done.finish_reason.as_str(), done.seed, done.usage.completion_tokens), ("A tabby cat on a sill.", "stop", 7, 3));
+ let sent: serde_json::Value = serde_json::from_str(&body.await.unwrap()).unwrap();
+ assert_eq!(sent["stream"], true, "always streamed");
+ assert_eq!((sent["prompt"].as_str(), sent["system_prompt"].as_str()), (Some("un gatto"), Some("sys")));
+ }
+
+ #[tokio::test]
+ async fn text_gen_errors_and_cancel() {
+ // A failure after the stream started.
+ let chunks = vec!["event: delta\ndata: {\"text\":\"A\"}\n\n".into(), "event: error\ndata: {\"error\":\"out of memory\"}\n\n".into()];
+ let (port, _) = fake_server(200, "text/event-stream", chunks, Duration::from_millis(1)).await;
+ let e = SdcppClient::new(port).text_gen(&text_req(), Duration::from_secs(10), |_| {}, || false).await.unwrap_err();
+ assert_eq!(e.code, ErrorCode::GenerationFailed);
+ assert_eq!(e.detail.as_deref(), Some("out of memory"));
+ // An engine without the endpoint, and a model without text generation.
+ let (port, _) = fake_server(404, "text/plain", vec!["Not Found".into()], Duration::ZERO).await;
+ assert_eq!(SdcppClient::new(port).text_gen(&text_req(), Duration::from_secs(10), |_| {}, || false).await.unwrap_err().code, ErrorCode::Unsupported);
+ let (port, _) = fake_server(400, "application/json", vec!["{\"error\":\"model has no text generation\"}".into()], Duration::ZERO).await;
+ let e = SdcppClient::new(port).text_gen(&text_req(), Duration::from_secs(10), |_| {}, || false).await.unwrap_err();
+ assert_eq!((e.code, e.detail.as_deref()), (ErrorCode::MalformedRequest, Some("model has no text generation")));
+ // The stream ends without `done`.
+ let (port, _) = fake_server(200, "text/event-stream", vec!["event: delta\ndata: {\"text\":\"A\"}\n\n".into()], Duration::ZERO).await;
+ assert_eq!(SdcppClient::new(port).text_gen(&text_req(), Duration::from_secs(10), |_| {}, || false).await.unwrap_err().code, ErrorCode::GenerationFailed);
+ // Cancel while the server is silent (waiting for the model).
+ let (port, _) = fake_server(200, "text/event-stream", sse_answer(&["late"], "stop"), Duration::from_secs(30)).await;
+ let t = std::time::Instant::now();
+ let cancel_at = t + Duration::from_millis(300);
+ let e = SdcppClient::new(port).text_gen(&text_req(), Duration::from_secs(60), |_| {}, || std::time::Instant::now() > cancel_at).await.unwrap_err();
+ assert_eq!(e.code, ErrorCode::Cancelled);
+ assert!(t.elapsed() < Duration::from_secs(3), "{:?}", t.elapsed());
+ // No answer within `idle`.
+ let (port, _) = fake_server(200, "text/event-stream", sse_answer(&["late"], "stop"), Duration::from_secs(30)).await;
+ let e = SdcppClient::new(port).text_gen(&text_req(), Duration::from_millis(400), |_| {}, || false).await.unwrap_err();
+ assert!(e.code == ErrorCode::GenerationFailed && e.detail.unwrap().contains("no answer"));
+ }
+
#[test]
fn request_serialization_matches_native_schema() {
let req = ImgGenRequest {
@@ -572,6 +834,9 @@ mod tests {
assert!(!caps.model_matches(std::path::Path::new(r"C:\AI\sdcpp\models\other.gguf")));
assert_eq!(caps.limits.max_width, 4096);
assert!(!caps.upscale && caps.upscalers.is_empty(), "older servers: no upscaler fields");
+ assert!(!caps.text_generation, "official engines: no text endpoint");
+ let caps: Capabilities = serde_json::from_str(r#"{"text_generation":true}"#).unwrap();
+ assert!(caps.text_generation);
let caps: Capabilities = serde_json::from_str(
r#"{"upscale":true,"upscalers":[{"name":"Lanczos","model":false,"image_upscale":false},
@@ -584,6 +849,50 @@ mod tests {
assert!(!caps.has_upscaler("Lanczos", false), "built-in filters are not models");
}
+ #[test]
+ fn text_gen_request_matches_api() {
+ let r = TextGenRequest {
+ prompt: "un gatto".into(),
+ system_prompt: String::new(),
+ images: vec![],
+ max_tokens: 512,
+ sampling: TextSampling { temperature: 0.7, top_p: 0.8, top_k: 20, presence_penalty: 1.5, seed: 42 },
+ stream: true,
+ };
+ let v = serde_json::to_value(&r).unwrap();
+ assert_eq!(v["system_prompt"], "", "always sent: the server has no built-in prompt");
+ assert!(v.get("images").is_none());
+ assert_eq!((v["max_tokens"].as_u64(), v["sampling"]["top_k"].as_u64(), v["sampling"]["seed"].as_i64()), (Some(512), Some(20), Some(42)));
+ assert!((v["sampling"]["presence_penalty"].as_f64().unwrap() - 1.5).abs() < 1e-6);
+ let v = serde_json::to_value(TextGenRequest { images: vec!["AAA".into()], ..r }).unwrap();
+ assert_eq!(v["images"][0], "AAA");
+ }
+
+ #[test]
+ fn sse_parser_splits_events_across_chunks() {
+ // The documented stream, cut at awkward places: inside a line, inside "é", in "\r\n".
+ let body = ": waiting for the model\r\n\r\nevent: delta\r\ndata: {\"text\":\"A caf\u{e9}\"}\r\n\r\nevent: delta\ndata: {\"text\":\" at night\"}\n\nevent: done\ndata: {\"text\":\"A caf\u{e9} at night\",\"finish_reason\":\"stop\",\"seed\":7,\"usage\":{\"prompt_tokens\":96,\"completion_tokens\":4},\"timings\":{\"decode_s\":0.1}}\n\n";
+ let bytes = body.as_bytes();
+ let e_acute = body.find('\u{e9}').unwrap();
+ let cuts = [5, 24, 30, e_acute + 1, e_acute + 2, 90, bytes.len()];
+ let mut p = SseParser::default();
+ let mut events = Vec::new();
+ let mut start = 0;
+ for &c in &cuts {
+ events.extend(p.push(&bytes[start..c]));
+ start = c;
+ }
+ assert_eq!(events.len(), 3, "{events:?}");
+ assert_eq!(events[0], ("delta".to_string(), "{\"text\":\"A caf\u{e9}\"}".to_string()));
+ assert_eq!(events[1].0, "delta");
+ let done: TextGenDone = serde_json::from_str(&events[2].1).unwrap();
+ assert_eq!((done.text.as_str(), done.finish_reason.as_str(), done.seed), ("A caf\u{e9} at night", "stop", 7));
+ assert_eq!(done.usage, TextUsage { prompt_tokens: 96, completion_tokens: 4 });
+ // An event without an `event:` line, and the error event.
+ assert_eq!(p.push(b"data: x\n\nevent: error\ndata: {\"error\":\"boom\"}\n\n"), vec![("message".into(), "x".into()), ("error".into(), "{\"error\":\"boom\"}".into())]);
+ assert!(p.push(b"event: delta\ndata: {\"te").is_empty(), "incomplete event waits");
+ }
+
#[test]
fn base64_roundtrip_and_data_urls() {
let data = vec![0u8, 1, 2, 250];
diff --git a/crates/qls-core/src/store.rs b/crates/qls-core/src/store.rs
index a5659d3..5bb8119 100644
--- a/crates/qls-core/src/store.rs
+++ b/crates/qls-core/src/store.rs
@@ -51,7 +51,11 @@ pub struct GenerationRecord {
pub id: String,
pub created_at: String,
pub mode: String,
+ /// The prompt the image was made from (the prompt enhancer's when it ran).
pub prompt: String,
+ /// The user's own prompt, when the prompt enhancer rewrote it.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub original_prompt: Option<String>,
pub negative_prompt: String,
pub seed: i64,
pub width: u32,
@@ -436,6 +440,7 @@ mod tests {
id: id.into(),
created_at: created.into(),
mode: "generate".into(),
+ original_prompt: None,
prompt: prompt.into(),
negative_prompt: "blurry".into(),
seed: 1234,
diff --git a/crates/qls-service/src/api.rs b/crates/qls-service/src/api.rs
index 4ca33ab..71caa1e 100644
--- a/crates/qls-service/src/api.rs
+++ b/crates/qls-service/src/api.rs
@@ -74,6 +74,7 @@ pub fn router(state: Arc<AppState>) -> Router {
.route("/upscalers", get(list_upscalers))
.route("/upscalers/{name}/download", post(download_upscaler))
.route("/config", get(get_config).put(put_config))
+ .route("/enhancer/defaults", get(enhancer_defaults))
.route("/backend/start", post(backend_start))
.route("/backend/stop", post(backend_stop))
.route("/backend/restart", post(backend_restart))
@@ -209,6 +210,7 @@ async fn status(State(s): St) -> Json<Value> {
"samplers": srv.capabilities.as_ref().map(|c| c.samplers.clone()).unwrap_or_default(),
"schedulers": srv.capabilities.as_ref().map(|c| c.schedulers.clone()).unwrap_or_default(),
"upscale": srv.capabilities.as_ref().map(|c| c.upscale),
+ "text_generation": srv.capabilities.as_ref().map(|c| c.text_generation),
},
"upscaler": { "model": cfg.upscaler().map(|u| u.0).unwrap_or_else(|| cfg.upscaler_model.clone()), "available": cfg.upscaler_file().is_some() },
"engine": { "release": catalog::engine_tag(), "update_needed": engine_update },
@@ -469,6 +471,12 @@ async fn get_config(State(s): St) -> Json<AppConfig> {
Json(s.engine.config())
}
+/// The prompt enhancer's built-in system prompts (Settings shows them for "" and restores them).
+async fn enhancer_defaults() -> Json<Value> {
+ use qls_core::enhancer;
+ Json(json!({ "t2i": enhancer::T2I_SYSTEM_PROMPT, "edit": enhancer::EDIT_SYSTEM_PROMPT, "max_chars": enhancer::MAX_SYSTEM_PROMPT_CHARS }))
+}
+
async fn put_config(State(s): St, Json(cfg): Json<AppConfig>) -> ApiResult<Json<Value>> {
let restart = s.engine.set_config(cfg)?;
let st = s.engine.server.status();