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(lora): Settings → LoRA tab and a LoRA badge per project

Gabriele Lozuponebf0be6c99a27
diff --git a/src/App.tsx b/src/App.tsx
index 352195d..9f770ac 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -4,7 +4,7 @@ import { useEffect, useRef, useState } from "react";
import { api, configure } from "./lib/api";
import { native } from "./lib/native";
import {
- addExampleProjects, addInputs, closeStarPrompt, dismissToast, getState, initStarPrompt, isMissingModel, newProject, openModelSetup, redoVersion, refreshStatus, selectItem, setPrivateMode, setState, startEvents, startTour, submitComposer, toastError, toastInfo, undoKey, undoVersion, useStore,
+ addExampleProjects, addInputs, closeStarPrompt, dismissToast, getState, initStarPrompt, isMissingModel, newProject, openModelSetup, redoVersion, refreshLoras, 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";
@@ -236,6 +236,7 @@ export default function App() {
startEvents();
const cfg = await api.config();
const st = await refreshStatus();
+ refreshLoras();
// First launch: the welcome screen, once (Settings → General shows it again).
const ui = (cfg.ui ?? {}) as Record<string, unknown>;
const welcomeSeen = !!ui.welcomeSeen;
diff --git a/src/components/Composer.tsx b/src/components/Composer.tsx
index 39b6d5c..fd1b96f 100644
--- a/src/components/Composer.tsx
+++ b/src/components/Composer.tsx
@@ -1,10 +1,10 @@
-import { ArrowUp, Brush, ChevronDown, Expand, FolderOpen, Gauge, ImagePlus, Lightbulb, Maximize, Pencil, SlidersHorizontal, Sparkles, WandSparkles, X } from "lucide-react";
+import { ArrowUp, Brush, Check, ChevronDown, Expand, FolderOpen, Gauge, ImagePlus, Layers, Lightbulb, Maximize, Pencil, Settings2, SlidersHorizontal, Sparkles, WandSparkles, X } from "lucide-react";
import { useEffect, useMemo, useRef, useState } from "react";
import { api, urls } from "../lib/api";
-import { activeOverrides, aspectLabel, buildRequest, enhancerApplies, expansionPixels, formatDuration, hasOutpaint, imageName, moveRef, needsPrompt, parseRatio, type Ref } from "../lib/logic";
+import { activeLoras, activeOverrides, aspectLabel, buildRequest, enhancerApplies, expansionPixels, formatDuration, hasOutpaint, imageName, MAX_LORAS, moveRef, needsPrompt, parseRatio, toggleLora, type Ref } from "../lib/logic";
import { native } from "../lib/native";
import {
- addAsReference, addInputs, editShownImage, enhancerAvailable, getState, itemSource, selectedItem, sessionLabels, setState, startNewImage, submitComposer, toastError, updateComposer, useStore, type SessionItem,
+ addAsReference, addInputs, editShownImage, enhancerAvailable, getState, itemSource, openSettings, selectedItem, sessionLabels, setProjectLoras, setState, startNewImage, submitComposer, toastError, updateComposer, useStore, type SessionItem,
} from "../lib/store";
import type { InpaintAction, Plan, Quality } from "../lib/types";
import { AdvancedPanel } from "./Advanced";
@@ -282,6 +282,79 @@ function usePlanPreview(): { plan: Plan | null; error: string | null } {
return res;
}
+const weightLabel = (w: number) => `${Math.round(w * 100)} %`;
+
+/** The project's LoRAs: shown once any LoRA is loaded in Settings. With one LoRA a click turns
+ * it on or off; with more, a list with one switch each. */
+function LoraBadge() {
+ const all = useStore((s) => s.loras);
+ const choice = useStore((s) => s.composer.loras);
+ if (all.length === 0) return null;
+ const on = activeLoras({ loras: choice }, all);
+ const names = all.filter((l) => on.includes(l.id)).map((l) => `${l.name} (${weightLabel(l.weight)})`);
+ const title = on.length ? `LoRA on in this project: ${names.join(", ")}` : "LoRA: none on in this project";
+ const label = on.length === 1 ? all.find((l) => l.id === on[0])?.name ?? "LoRA" : on.length > 1 ? `LoRA · ${on.length}` : "LoRA";
+ const toggle = (id: string) => setProjectLoras(toggleLora({ loras: choice }, all, id));
+ if (all.length === 1) {
+ const l = all[0];
+ return (
+ <button
+ className={`pill lora ${on.length ? "on" : ""}`}
+ role="switch"
+ aria-checked={on.length > 0}
+ disabled={!l.available}
+ onClick={() => toggle(l.id)}
+ title={l.available ? `${title}. Click to turn ${on.length ? "off" : "on"}.` : "This LoRA's file is missing: load it again in Settings → LoRA."}
+ >
+ <Layers size={15} />
+ <span className="lora-name">{label}</span>
+ </button>
+ );
+ }
+ return (
+ <Popover
+ trigger={(open, toggleOpen) => (
+ <button className={`pill lora ${on.length || open ? "on" : ""}`} onClick={toggleOpen} title={title}>
+ <Layers size={15} />
+ <span className="lora-name">{label}</span>
+ <ChevronDown size={13} />
+ </button>
+ )}
+ >
+ {(close) => (
+ <>
+ <div className="label">LoRA in this project · up to {MAX_LORAS}</div>
+ {all.map((l) => {
+ const active = on.includes(l.id);
+ const full = !active && on.length >= MAX_LORAS;
+ return (
+ <button
+ key={l.id}
+ className="opt"
+ role="menuitemcheckbox"
+ aria-checked={active}
+ disabled={!l.available || full}
+ onClick={() => toggle(l.id)}
+ title={!l.available ? "This LoRA's file is missing: load it again in Settings → LoRA." : full ? `At most ${MAX_LORAS} LoRAs at once.` : l.triggerWords ? `Adds: ${l.triggerWords}` : undefined}
+ >
+ <span className="check">{active && <Check size={15} />}</span>
+ <span className="lora-name">{l.name}</span>
+ <span className="sub">{l.available ? weightLabel(l.weight) : "missing"}</span>
+ </button>
+ );
+ })}
+ <button className="opt" onClick={() => (close(), openSettings("lora"))}>
+ <span className="check">
+ <Settings2 size={15} />
+ </span>
+ <span>Manage LoRAs…</span>
+ </button>
+ </>
+ )}
+ </Popover>
+ );
+}
+
export function Composer() {
const c = useStore((s) => s.composer);
const hasProject = useStore((s) => s.session.length > 0);
@@ -459,6 +532,8 @@ export function Composer() {
</button>
)}
+ <LoraBadge />
+
<button className="icon-btn" onClick={() => setState({ overlay: "prompt-tips" })} title="Prompt tips" aria-label="Prompt tips">
<Lightbulb size={17} />
</button>
diff --git a/src/components/LoraSettings.tsx b/src/components/LoraSettings.tsx
new file mode 100644
index 0000000..e2caa2d
--- /dev/null
+++ b/src/components/LoraSettings.tsx
@@ -0,0 +1,142 @@
+import { CircleAlert, Plus, Trash2 } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { api } from "../lib/api";
+import { formatBytes, MAX_LORAS } from "../lib/logic";
+import { native } from "../lib/native";
+import { refreshLoras, toastError, toastInfo, useStore } from "../lib/store";
+import type { LoraItem } from "../lib/types";
+import { Switch } from "./ui";
+
+type Patch = Parameters<typeof api.updateLora>[1];
+
+async function update(id: string, patch: Patch) {
+ try {
+ await api.updateLora(id, patch);
+ } catch (e) {
+ toastError(e);
+ }
+ refreshLoras();
+}
+
+/** A text field saved when it loses focus (or on Enter). */
+function BlurField(props: { value: string; placeholder?: string; label: string; onSave: (v: string) => void }) {
+ const [v, setV] = useState(props.value);
+ useEffect(() => setV(props.value), [props.value]);
+ return (
+ <input
+ className="input"
+ type="text"
+ spellCheck={false}
+ aria-label={props.label}
+ placeholder={props.placeholder}
+ value={v}
+ onChange={(e) => setV(e.target.value)}
+ onBlur={() => v !== props.value && props.onSave(v)}
+ onKeyDown={(e) => e.key === "Enter" && (e.target as HTMLInputElement).blur()}
+ />
+ );
+}
+
+function LoraRow({ l }: { l: LoraItem }) {
+ const [weight, setWeight] = useState(l.weight);
+ useEffect(() => setWeight(l.weight), [l.weight]);
+ const timer = useRef<number | undefined>(undefined);
+ const setStrength = (w: number) => {
+ setWeight(w);
+ window.clearTimeout(timer.current);
+ timer.current = window.setTimeout(() => update(l.id, { weight: w }), 400);
+ };
+ const remove = async () => {
+ if (!(await native.confirm(`Remove "${l.name}" from Kokon? Your own file stays where it is.`, "Remove LoRA"))) return;
+ try {
+ await api.removeLora(l.id);
+ } catch (e) {
+ toastError(e);
+ }
+ refreshLoras();
+ };
+ return (
+ <div className="lora-card">
+ <div className="lora-head">
+ <BlurField label="Name" value={l.name} onSave={(name) => update(l.id, { name })} />
+ <button className="icon-btn" onClick={remove} title="Remove" aria-label={`Remove ${l.name}`}>
+ <Trash2 size={16} />
+ </button>
+ </div>
+ {!l.available && (
+ <span className="lora-warn">
+ <CircleAlert size={13} /> Kokon's copy of this LoRA is missing. Remove it and load the file again.
+ </span>
+ )}
+ {l.warning && (
+ <span className="lora-warn">
+ <CircleAlert size={13} /> {l.warning}
+ </span>
+ )}
+ <label className="field-row">
+ <span>Strength</span>
+ <span className="lora-strength">
+ <input type="range" min={0} max={2} step={0.05} value={weight} onChange={(e) => setStrength(Number(e.target.value))} aria-label="Strength" />
+ <span className="muted">{Math.round(weight * 100)} %</span>
+ </span>
+ </label>
+ <label className="field">
+ <span>Trigger words (added in front of the prompt when the LoRA is on)</span>
+ <BlurField label="Trigger words" placeholder="none" value={l.triggerWords} onSave={(triggerWords) => update(l.id, { triggerWords })} />
+ </label>
+ <div className="field-row">
+ <span>On by default in new projects</span>
+ <Switch on={l.onByDefault} label="On by default" onChange={(onByDefault) => update(l.id, { onByDefault })} />
+ </div>
+ <span className="muted lora-meta">
+ {[...l.notes, `${formatBytes(l.size)} · from ${l.source}`].join(" ")}
+ </span>
+ </div>
+ );
+}
+
+/** Settings → LoRA: the user's own LoRA files. */
+export function LoraSettings() {
+ const loras = useStore((s) => s.loras);
+ const [busy, setBusy] = useState(false);
+ useEffect(() => {
+ refreshLoras();
+ }, []);
+ const add = async () => {
+ const path = await native.pickFile(["safetensors"], undefined, "LoRA");
+ if (!path) return;
+ setBusy(true);
+ try {
+ const l = await api.addLora(path);
+ toastInfo(l.warning ? `Loaded "${l.name}", with a warning` : `Loaded "${l.name}"`);
+ } catch (e) {
+ toastError(e);
+ } finally {
+ setBusy(false);
+ refreshLoras();
+ }
+ };
+ return (
+ <>
+ <div className="setting-card">
+ <div className="setting-card-text">
+ <strong>Your LoRA files</strong>
+ <span className="muted">
+ Load LoRAs made for Qwen-Image 2.1 (.safetensors). Kokon checks each file and keeps its own prepared copy; your file is not changed. Turn them on or off for each project with the
+ LoRA button next to the prompt, up to {MAX_LORAS} at a time.
+ </span>
+ </div>
+ <button className="btn primary" disabled={busy} onClick={add}>
+ <Plus size={15} /> {busy ? "Checking…" : "Load a LoRA…"}
+ </button>
+ </div>
+ <span className="muted">
+ Most LoRAs are trained on the full Qwen-Image 2.1 model, while Kokon runs the faster Turbo model. The popular ones we tested didn't improve on what Turbo does with a good prompt, so compare
+ with the LoRA on and off. A LoRA makes each image about 20 % slower.
+ </span>
+ {loras.map((l) => (
+ <LoraRow key={l.id} l={l} />
+ ))}
+ </>
+ );
+}
diff --git a/src/components/Settings.tsx b/src/components/Settings.tsx
index 4f48d89..0890c73 100644
--- a/src/components/Settings.tsx
+++ b/src/components/Settings.tsx
@@ -1,4 +1,4 @@
-import { Activity, Copy, Cpu, Download, FolderOpen, HardDrive, RefreshCw, RotateCcw, Settings2, Trash2, X } from "lucide-react";
+import { Activity, Copy, Cpu, Download, FolderOpen, HardDrive, Layers, RefreshCw, RotateCcw, Settings2, Trash2, X } from "lucide-react";
import { useEffect, useState } from "react";
import { writeText } from "@tauri-apps/plugin-clipboard-manager";
import { api } from "../lib/api";
@@ -6,13 +6,15 @@ import { native } from "../lib/native";
import { getState, openModelSetup, refreshStatus, setState, startTour, toastError, toastInfo, useStore } from "../lib/store";
import { formatBytes } from "../lib/logic";
import { setThemeChoice, themeChoice, type ThemeChoice } from "../lib/theme";
+import { LoraSettings } from "./LoraSettings";
import { UpscalerControls } from "./Upscalers";
import { WHATS_NEW_VERSION } from "./WhatsNew";
import type { AppConfig, Check, ModelProfile, ModelsStatus, SetupReport, TextEncoderPlacement } from "../lib/types";
import { IconButton, Seg, Switch } from "./ui";
import { autoCheckEnabled, checkForUpdate } from "../lib/updates";
-type Tab = "general" | "models" | "performance" | "diagnostics";
+type Tab = "general" | "models" | "lora" | "performance" | "diagnostics";
+const TABS: Tab[] = ["general", "models", "lora", "performance", "diagnostics"];
function PathField(props: { label: string; value: string; onChange: (v: string) => void; folder?: boolean; extensions?: string[] }) {
return (
@@ -114,7 +116,12 @@ function Diagnostics() {
}
export function Settings() {
- const [tab, setTab] = useState<Tab>("general");
+ // Opened on a tab by `openSettings` (e.g. the LoRA badge), else General.
+ const [tab, setTab] = useState<Tab>(() => {
+ const t = getState().settingsTab as Tab | null;
+ return t && TABS.includes(t) ? t : "general";
+ });
+ useEffect(() => setState({ settingsTab: null }), []);
const [cfg, setCfg] = useState<AppConfig | null>(null);
const [devices, setDevices] = useState<[string, string][]>([]);
const [upscaler, setUpscaler] = useState<Check | null>(null);
@@ -225,6 +232,7 @@ export function Settings() {
const nav: [Tab, string, React.ReactNode][] = [
["general", "General", <Settings2 size={16} key="g" />],
["models", "Models", <HardDrive size={16} key="m" />],
+ ["lora", "LoRA", <Layers size={16} key="l" />],
["performance", "Performance", <Cpu size={16} key="p" />],
["diagnostics", "Diagnostics", <Activity size={16} key="d" />],
];
@@ -239,7 +247,7 @@ export function Settings() {
</button>
))}
<span style={{ flex: 1 }} />
- {tab !== "diagnostics" && (
+ {tab !== "diagnostics" && tab !== "lora" && (
<button className="btn primary" style={{ justifyContent: "center" }} disabled={!dirty} onClick={save}>
Save
</button>
@@ -614,6 +622,7 @@ export function Settings() {
</>
)}
+ {tab === "lora" && <LoraSettings />}
{tab === "diagnostics" && <Diagnostics />}
</div>
</div>
diff --git a/src/components/Stage.tsx b/src/components/Stage.tsx
index f959032..097310f 100644
--- a/src/components/Stage.tsx
+++ b/src/components/Stage.tsx
@@ -350,6 +350,7 @@ function InfoPanel({ g }: { g: GenerationRecord }) {
["Sampler", `${g.sampler}${g.scheduler ? ` / ${g.scheduler}` : ""}`],
...(g.strength != null ? ([["Strength", String(g.strength)]] as [string, string][]) : []),
["References", String(g.references.length)],
+ ...(g.loras?.length ? ([["LoRA", g.loras.map((l) => `${l.name} (${Math.round(l.weight * 100)} %)`).join(", ")]] as [string, string][]) : []),
["Model", g.model],
["Time", formatDuration(g.duration_ms / 1000)],
["Created", new Date(g.created_at).toLocaleString()],
diff --git a/src/lib/api.ts b/src/lib/api.ts
index 0ef9a3f..613d8d2 100644
--- a/src/lib/api.ts
+++ b/src/lib/api.ts
@@ -3,7 +3,7 @@
import type {
GpuBackend,
- AppConfig, AppErrorBody, GenerationRecord, GenerationRequest, HardwareReport, InputRecord, InstallStatus, JobView, LutEntry, ModelFileInfo, ModelScan, ModelSlot, ModelsStatus, Plan,
+ AppConfig, AppErrorBody, GenerationRecord, GenerationRequest, HardwareReport, InputRecord, InstallStatus, JobView, LoraItem, LutEntry, ModelFileInfo, ModelScan, ModelSlot, ModelsStatus, Plan,
ServiceEvent, SetupReport, StatusResponse, UpscalerItem,
} from "./types";
@@ -120,6 +120,13 @@ export const api = {
deleteGeneration: (id: string) => call<{ deleted: string }>(`/gallery/${id}`, { method: "DELETE" }),
/** Adds the bundled example projects to the gallery (idempotent) and lists them. */
installExamples: () => call<{ projects: { title: string; generations: string[] }[] }>("/examples", { method: "POST" }),
+ loras: () => call<{ items: LoraItem[]; dir: string; max_active: number }>("/loras"),
+ /** Checks a LoRA file against the image model and loads Kokon's copy of it. */
+ addLora: (path: string) => call<LoraItem>("/loras", { method: "POST", body: json({ path }) }),
+ updateLora: (id: string, patch: Partial<Pick<LoraItem, "name" | "weight" | "triggerWords" | "onByDefault">>) =>
+ call<LoraItem>(`/loras/${encodeURIComponent(id)}`, { method: "PATCH", body: json(patch) }),
+ /** Removes the LoRA and Kokon's copy (the user's file stays). */
+ removeLora: (id: string) => call<{ removed: string }>(`/loras/${encodeURIComponent(id)}`, { method: "DELETE" }),
luts: () => call<{ items: LutEntry[] }>("/luts"),
/** Adds a .cube file to the list (copied into Kokon's data folder). */
importLut: (path: string) => call<LutEntry>("/luts/import", { method: "POST", body: json({ path }) }),
diff --git a/src/lib/logic.test.ts b/src/lib/logic.test.ts
index 89169b9..ec0c040 100644
--- a/src/lib/logic.test.ts
+++ b/src/lib/logic.test.ts
@@ -1,10 +1,10 @@
import { describe, expect, it } from "vitest";
import {
- activeOverrides, buildRequest, jobPercent, compareBase, composerFromRecord, enhancerApplies, diffPixels, emptyComposer, expansionPixels, expansionPreset, jobLabel, jobSecondsLeft, lutInfo, moveRef, needsPrompt, normalizeQuality, persistentAdvanced, pipelineSummary,
+ activeLoras, activeOverrides, buildRequest, toggleLora, MAX_LORAS, jobPercent, compareBase, composerFromRecord, enhancerApplies, diffPixels, emptyComposer, expansionPixels, expansionPreset, jobLabel, jobSecondsLeft, lutInfo, moveRef, needsPrompt, normalizeQuality, persistentAdvanced, pipelineSummary,
planPipeline, remainingSeconds, sizeForWidth, timeAgo, upscaleRequest, upscaleTargets, versionLabels, type JobClock, type Ref,
neighbourAfterRemoval, previewIndex, starPromptDue, STAR_PROMPT_AFTER, formatBytes, formatDuration, installItemShort, installItemText, installProgress, installStep, installTimeLeft, timelineLinks, undoTarget, aspectLabel, parseRatio, sizeForRatio, expandToRatio, expandToSize, arcLayout,
} from "./logic";
-import type { GenerationRecord, InstallItem, JobView, Plan } from "./types";
+import type { GenerationRecord, InstallItem, JobView, LoraItem, Plan } from "./types";
const ref = (n: number): Ref => ({ key: `k${n}`, source: `input:${n}`, width: 100, height: 100, name: `r${n}` });
@@ -119,6 +119,28 @@ describe("buildRequest", () => {
});
});
+describe("LoRA", () => {
+ const l = (id: string, onByDefault = false, available = true) => ({ id, name: id, onByDefault, available, weight: 1 }) as LoraItem;
+ const all = [l("film", true), l("angles"), l("gone", true, false), l("a"), l("b")];
+ it("a new project uses the ones on by default that are still there", () => {
+ expect(activeLoras({ loras: null }, all)).toEqual(["film"]);
+ expect(activeLoras({ loras: [] }, all)).toEqual([]);
+ expect(activeLoras({ loras: ["angles", "removed", "gone"] }, all)).toEqual(["angles"]);
+ });
+ it("switches one on or off, at most MAX_LORAS", () => {
+ expect(toggleLora({ loras: null }, all, "film")).toEqual([]);
+ expect(toggleLora({ loras: null }, all, "angles")).toEqual(["film", "angles"]);
+ const full = ["film", "angles", "a"];
+ expect(full.length).toBe(MAX_LORAS);
+ expect(toggleLora({ loras: full }, all, "b")).toEqual(full);
+ });
+ it("reusing settings brings back the LoRAs the image was made with", () => {
+ const g = { prompt: "x", references: [], mask_input_id: null, outpaint: null, quality: "fast", request: null, loras: [{ id: "film", name: "Film", weight: 0.7 }] } as unknown as GenerationRecord;
+ expect(composerFromRecord(g, emptyComposer()).loras).toEqual(["film"]);
+ expect(composerFromRecord({ ...g, loras: undefined }, { ...emptyComposer(), loras: ["a"] }).loras).toEqual([]);
+ });
+});
+
describe("expansion", () => {
const zero = { left: 0, right: 0, top: 0, bottom: 0, units: "pixels" as const };
it("presets", () => {
diff --git a/src/lib/logic.ts b/src/lib/logic.ts
index b5ae681..1b0818a 100644
--- a/src/lib/logic.ts
+++ b/src/lib/logic.ts
@@ -1,6 +1,6 @@
// Pure UI logic (unit-tested in logic.test.ts).
-import type { Advanced, GenerationRecord, GenerationRequest, InpaintAction, InputRecord, InstallItem, JobView, LutInfo, Mode, OutpaintSpec, Plan, Quality, ResolutionMode, Size } from "./types";
+import type { Advanced, GenerationRecord, GenerationRequest, InpaintAction, InputRecord, InstallItem, JobView, LoraItem, LutInfo, Mode, OutpaintSpec, Plan, Quality, ResolutionMode, Size } from "./types";
export interface Ref {
key: string;
@@ -31,6 +31,8 @@ export interface Composer {
advanced: Advanced;
/** Prompt enhancer on (remembered; used only where `enhancerApplies`). */
enhance: boolean;
+ /** LoRAs switched on in this project; null = the ones on by default (`activeLoras`). */
+ loras: string[] | null;
}
/** A preset name from any version: older ones also had "turbo" (now Fast) and "ultra" (now Quality). */
@@ -56,8 +58,27 @@ export const emptyComposer = (prefs?: Partial<Composer>): Composer => ({
seed: null,
advanced: newChatAdvanced(prefs?.advanced),
enhance: prefs?.enhance === true,
+ loras: null,
});
+/** LoRAs one image can use at once (`lora::MAX_ACTIVE`). */
+export const MAX_LORAS = 3;
+
+/** The LoRAs a request from this composer uses: the project's choice, else the ones on by
+ * default; only loaded ones whose copy is there, at most `MAX_LORAS`. */
+export function activeLoras(c: Pick<Composer, "loras">, all: LoraItem[]): string[] {
+ const usable = new Set(all.filter((l) => l.available).map((l) => l.id));
+ const chosen = c.loras ?? all.filter((l) => l.onByDefault).map((l) => l.id);
+ return chosen.filter((id) => usable.has(id)).slice(0, MAX_LORAS);
+}
+
+/** The project's LoRA choice after switching `id` on or off. */
+export function toggleLora(c: Pick<Composer, "loras">, all: LoraItem[], id: string): string[] {
+ const now = activeLoras(c, all);
+ if (now.includes(id)) return now.filter((x) => x !== id);
+ return now.length < MAX_LORAS ? [...now, id] : now;
+}
+
/** Advanced settings a new chat starts with: everything kept except Reference detail, which
* every chat starts at the standard 1 MP. */
function newChatAdvanced(a: Advanced | undefined): Advanced {
@@ -182,6 +203,8 @@ export function composerFromRecord(g: GenerationRecord, base: Composer): Compose
aspect: req?.aspect_ratio ?? "auto",
seed: null,
advanced: cleanAdvanced(req?.advanced ?? {}),
+ // The LoRAs it was made with (none for images made before LoRAs or without them).
+ loras: (g.loras ?? []).map((l) => l.id),
};
if (req?.width && req?.height) {
c.customWidth = req.width;
diff --git a/src/lib/store.ts b/src/lib/store.ts
index 96729a2..15da84d 100644
--- a/src/lib/store.ts
+++ b/src/lib/store.ts
@@ -8,8 +8,8 @@
import { useSyncExternalStore } from "react";
import { markFresh } from "../components/Cocoon";
import { api, ApiError, setPrivateInputs, subscribe } from "./api";
-import { buildRequest, emptyComposer, needsPrompt, newKey, persistentAdvanced, refFromGen, refFromInput, starPromptDue, timelineLinks, undoTarget, versionLabels, type CompareMode, type Composer, type Ref } from "./logic";
-import type { AppErrorBody, GenerationRecord, GenerationRequest, InputRecord, JobView, ServerState, StatusResponse } from "./types";
+import { activeLoras, buildRequest, emptyComposer, needsPrompt, newKey, persistentAdvanced, refFromGen, refFromInput, starPromptDue, timelineLinks, undoTarget, versionLabels, type CompareMode, type Composer, type Ref } from "./logic";
+import type { AppErrorBody, GenerationRecord, GenerationRequest, InputRecord, JobView, LoraItem, ServerState, StatusResponse } from "./types";
export type Overlay = null | "gallery" | "settings" | "inpaint" | "expand" | "welcome" | "whats-new" | "prompt-tips" | "shortcuts";
@@ -88,6 +88,10 @@ export interface State {
tour: number | null;
/** The one-time "star on GitHub" card is on screen (App.tsx). */
starPrompt: boolean;
+ /** The user's LoRAs (Settings → LoRA). */
+ loras: LoraItem[];
+ /** Tab Settings opens on (then cleared). */
+ settingsTab: string | null;
}
const PREFS_KEY = "qls.prefs.v1";
@@ -131,6 +135,8 @@ interface ProjectData {
meta: ProjectMeta;
items: StoredItem[];
selected: string | null;
+ /** LoRAs switched on in the project (absent = the ones on by default). */
+ loras?: string[];
}
const projects: Record<string, ProjectData> = (() => {
@@ -228,6 +234,7 @@ function syncProject(prev: State) {
},
items,
selected: state.selected,
+ loras: state.composer.loras ?? undefined,
};
state = { ...state, projects: projectList() };
persistProjects();
@@ -293,6 +300,8 @@ let state: State = {
redo: [],
tour: null,
starPrompt: false,
+ loras: [],
+ settingsTab: null,
};
const listeners = new Set<() => void>();
@@ -573,7 +582,32 @@ export async function switchProject(id: string, selectKey?: string) {
if (token !== switching) return;
const keep = (k: string | null | undefined) => (k && session.some((i) => i.key === k) ? k : null);
const selected = keep(selectKey) ?? keep(data.selected) ?? session[session.length - 1]?.key ?? null;
- setState((s) => ({ projectId: id, session, selected, overlay: null, redo: [], composer: composerFor(s.composer, session, selected) }));
+ setState((s) => ({ projectId: id, session, selected, overlay: null, redo: [], composer: { ...composerFor(s.composer, session, selected), loras: data.loras ?? null } }));
+}
+
+/** Switches the project's LoRAs (the composer's LoRA badge); new projects start with the ones
+ * on by default. */
+export function setProjectLoras(ids: string[]) {
+ setState((s) => ({ composer: { ...s.composer, loras: ids } }));
+ const p = projects[state.projectId];
+ if (p && !state.privateMode) {
+ p.loras = ids;
+ persistProjects();
+ }
+}
+
+/** Reloads the LoRA list from the service. */
+export async function refreshLoras() {
+ try {
+ setState({ loras: (await api.loras()).items });
+ } catch {
+ /* service not reachable: keep the last list */
+ }
+}
+
+/** Opens Settings on one of its tabs. */
+export function openSettings(tab: string) {
+ setState({ overlay: "settings", settingsTab: tab });
}
/** Adds the example projects that ship with Kokon (made by Kokon itself), except the ones
@@ -874,7 +908,7 @@ export async function submitComposer() {
const s = getState();
const target = s.composer.refs[0]?.source;
const parent = target?.startsWith("gen:") ? target.slice(4) : null;
- const req = buildRequest(s.composer, parent);
+ const req: GenerationRequest = { ...buildRequest(s.composer, parent), loras: activeLoras(s.composer, s.loras) };
if (!req.prompt && needsPrompt(s.composer)) {
toastInfo("Describe what to create or change.");
return;
diff --git a/src/lib/types.ts b/src/lib/types.ts
index 170b4c2..ad22ad6 100644
--- a/src/lib/types.ts
+++ b/src/lib/types.ts
@@ -61,6 +61,8 @@ export interface GenerationRequest {
private?: boolean;
/** Prompt enhancer: the model's language model rewrites the prompt first (new images, edits, combines). */
enhance?: boolean;
+ /** LoRA ids to use; omitted = the ones on by default. */
+ loras?: string[] | null;
}
export interface WorkingCanvas { source: Size; content: Size; canvas: Size; content_offset: [number, number]; scale: number }
@@ -123,6 +125,8 @@ export interface GenerationRecord {
prompt: string;
/** The user's own prompt, when the prompt enhancer rewrote it. */
original_prompt?: string | null;
+ /** LoRAs the image was made with. */
+ loras?: AppliedLora[];
negative_prompt: string;
seed: number;
width: number;
@@ -151,6 +155,26 @@ export interface GenerationRecord {
pipeline?: PipelineRecord | null;
}
+/** A LoRA as an image used it. */
+export interface AppliedLora { id: string; name: string; weight: number; trigger_words?: string }
+
+/** One of the user's LoRAs (Settings → LoRA); Kokon's prepared copy is `<dir>/<id>.safetensors`. */
+export interface LoraItem {
+ id: string;
+ name: string;
+ /** The file the user picked. */
+ source: string;
+ weight: number;
+ triggerWords: string;
+ onByDefault: boolean;
+ size: number;
+ warning: string | null;
+ notes: string[];
+ addedAt: string;
+ /** Kokon's copy is still in its LoRA folder. */
+ available: boolean;
+}
+
/** A .cube LUT in Kokon's list (the user's, most recently used first, then Kokon's presets). */
export interface LutEntry { name: string; title: string | null; kind: "1d" | "3d"; size: number; builtin: boolean }
/** How a "lut" result was made (in its `request`). */
diff --git a/src/styles.css b/src/styles.css
index 84d4e51..ba08c50 100644
--- a/src/styles.css
+++ b/src/styles.css
@@ -194,6 +194,9 @@ svg { display: block; flex: none; }
}
.stage-meta .enhanced-mark { flex: none; display: inline-flex; color: var(--text-2); }
.pill.enhance.on { background: var(--surface-2); }
+.pill.lora.on { background: var(--surface-2); }
+.lora-name { max-width: 160px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.popover .opt:disabled { opacity: 0.5; cursor: default; }
.failed { display: flex; flex-direction: column; align-items: center; gap: 10px; max-width: 460px; text-align: center; color: var(--text-2); }
.failed strong { color: var(--text); font-weight: 600; }
@@ -746,3 +749,14 @@ kbd { min-width: 22px; height: 22px; padding: 0 6px; border-radius: 6px; display
.repair-option .muted { font-size: 12px; overflow-wrap: anywhere; }
.model-files summary { cursor: pointer; font-size: 12px; color: var(--text-2); margin-top: 4px; }
.model-files span { display: block; font-size: 11px; color: var(--text-3); overflow-wrap: anywhere; }
+
+/* Settings → LoRA */
+.lora-card { display: flex; flex-direction: column; gap: 10px; padding: 12px; border: 1px solid var(--border); border-radius: 12px; }
+.lora-head { display: flex; gap: 8px; align-items: center; }
+.lora-head .input { flex: 1; font-weight: 600; }
+.lora-strength { display: flex; align-items: center; gap: 10px; }
+.lora-strength input[type="range"] { width: 180px; }
+.lora-strength .muted { width: 44px; text-align: right; font-variant-numeric: tabular-nums; }
+.lora-warn { display: flex; gap: 6px; align-items: flex-start; font-size: 12px; color: var(--text-2); }
+.lora-warn svg { flex: none; margin-top: 2px; }
+.lora-meta { font-size: 12px; word-break: break-all; }