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.
TypeScript ai-photo-editorcomfyui-alternativegenerative-fillimage-editingimage-generationinpaintinglinuxlocal-aimacosmcpmcp-servernano-banana-alternativeofflinephoto-editorprivacyqwen-imageqwen-image-2-1stable-diffusion-cppvulkanwindows
Mac engine inside Kokon.app, offered once at start on Macs
Gabriele Lozupone3be71413bbfd
diff --git a/.gitignore b/.gitignoreindex 9f94f1c..f064ed0 100644--- a/.gitignore+++ b/.gitignore@@ -7,6 +7,7 @@ node_modules/src-tauri/binaries/*.exe# Model files bundled with the app, fetched at build time (scripts/release/fetch-bundled.mjs)/src-tauri/resources/*.pth+/src-tauri/resources/engine-mac/*.log/.test-data/dist-releasediff --git a/crates/qls-core/src/config.rs b/crates/qls-core/src/config.rsindex 55ae845..d4144ea 100644--- a/crates/qls-core/src/config.rs+++ b/crates/qls-core/src/config.rs@@ -794,11 +794,18 @@ impl AppConfig {pub fn server_exe(&self) -> PathBuf {if self.uses_mac_engine() {- return self.sdcpp_dir.join(MAC_ENGINE_DIR).join(MAC_ENGINE_EXE);+ return self.mac_engine_exe();}self.engine_dir().join(if cfg!(windows) { "sd-server.exe" } else { "sd-server" })}+ /// Kokon's Mac engine, on or off: the copy inside the app (next to kokon-service; `tauri dev` puts one there too),+ /// else the one `engine-mac/tools/install-dev.sh` puts in the stable-diffusion.cpp folder.+ pub fn mac_engine_exe(&self) -> PathBuf {+ let here = std::env::current_exe().ok().and_then(|e| e.parent().map(Path::to_path_buf));+ mac_engine_in(here.as_deref(), &self.sdcpp_dir)+ }+/// Kokon's Mac engine runs instead of sd-server: chosen in Settings, on the Metal backend only.pub fn uses_mac_engine(&self) -> bool {self.mac_engine && self.gpu_backend == GpuBackend::Metal@@ -925,10 +932,26 @@ fn extra_weights_mib(diffusion: u64, text_encoder: u64, unified: bool) -> u64 {extra >> 20}+/// See [`AppConfig::mac_engine_exe`]: `app_dir` is kokon-service's folder.+fn mac_engine_in(app_dir: Option<&Path>, sdcpp_dir: &Path) -> PathBuf {+ app_dir.map(|d| d.join(MAC_ENGINE_EXE)).filter(|p| p.is_file()).unwrap_or_else(|| sdcpp_dir.join(MAC_ENGINE_DIR).join(MAC_ENGINE_EXE))+}+#[cfg(test)]mod tests {use super::*;+ #[test]+ fn mac_engine_inside_the_app_first() {+ let app = tempfile::tempdir().unwrap();+ let sdcpp = tempfile::tempdir().unwrap();+ let dev = sdcpp.path().join(MAC_ENGINE_DIR).join(MAC_ENGINE_EXE);+ assert_eq!(mac_engine_in(Some(app.path()), sdcpp.path()), dev);+ assert_eq!(mac_engine_in(None, sdcpp.path()), dev);+ std::fs::write(app.path().join(MAC_ENGINE_EXE), b"").unwrap();+ assert_eq!(mac_engine_in(Some(app.path()), sdcpp.path()), app.path().join(MAC_ENGINE_EXE));+ }+/// Empty files at every path of `p`.fn touch_files(p: &ModelProfile) {for (_, f, _) in p.files() {diff --git a/crates/qls-service/src/api.rs b/crates/qls-service/src/api.rsindex f576ed9..94e56d7 100644--- a/crates/qls-service/src/api.rs+++ b/crates/qls-service/src/api.rs@@ -267,6 +267,8 @@ async fn status(State(s): St) -> Json<Value> {"active_job": s.engine.active_job(),"queue": { "queued": queued, "jobs": jobs.iter().filter(|j| !j.status.is_terminal()).collect::<Vec<_>>() },"setup_complete": cfg.setup_complete,+ // Kokon's Mac engine: installed (inside the app or by hand) and switched on.+ "mac_engine": { "available": cfg.gpu_backend == GpuBackend::Metal && cfg.mac_engine_exe().is_file(), "on": cfg.uses_mac_engine() },}))}diff --git a/docs/STATUS.md b/docs/STATUS.mdindex 6ac01c1..4ff08c0 100644--- a/docs/STATUS.md+++ b/docs/STATUS.md@@ -29,7 +29,8 @@ Windows, macOS (Apple Silicon, 15+) and Linux (`.deb`, `.rpm`). Installed copiesextending an image, about 64–67 s for 1 MP text to image and ~106 s for a 1 MP edit on the same Mac (peak memory 5 GB),as an experimental switch in Settings → Performance (off by default). Since then (2026-10-26, not yet re-measured aswhole images): one denoising step ~5 % faster, the decoder ~1 s faster per image, an edit's image reading 2.6 → 1.7 s. LoRAs and the upscaler still need the standard- engine (not planned for its first release). A "Benchmark this Mac" button in Settings → Performance runs the engine's+ engine (not planned for its first release). On the branch it now ships inside Kokon.app (1.7 MB) and Kokon offers it once at start+ on Macs with 16 GB or more (planned for 0.11.1, with rollback in Settings). A "Benchmark this Mac" button in Settings → Performance runs the engine'sbench from the app (~10 min) and gives the report to paste in[Discussion #43](https://github.com/GabrieleLozupone/kokon/discussions/43).- The Windows installer is not code-signed: SmartScreen or Smart App Control may block it (README FAQ: Unblock).diff --git a/engine-mac/README.md b/engine-mac/README.mdindex a345689..9e6303b 100644--- a/engine-mac/README.md+++ b/engine-mac/README.md@@ -24,9 +24,13 @@ bash tools/ab.sh snapshot base; bash tools/ab.sh run 2 "base|base|X=1" "new|new|# alternated A/B of build snapshots and settings (steps, page-ins)```-In the app: `bash tools/install-dev.sh` puts the build where Kokon looks for it, then Settings → Performance →-"Kokon's Mac engine (experimental)". Off by default; sd.cpp stays the default, the fallback, and the engine on-Windows and Linux.+In the app: Kokon.app carries the engine (1.7 MB: `Contents/MacOS/kokon-engine-mac`, the kernels in+`Contents/Resources/engine-mac/`; `tools/stage-app.sh`, called by `scripts/dev/mac-dev.sh` and+`scripts/build-release-mac.sh`), and Settings → Performance → "Kokon's Mac engine (experimental)" turns it on. Off by+default; at the first start on a Mac with 16 GB or more Kokon offers it once, before the model loads. sd.cpp stays the+default, the fallback, and the engine on Windows and Linux. Without the app's copy (a service run with `cargo run`),+`bash tools/install-dev.sh` puts the build in the stable-diffusion.cpp folder; `kokon-engine-mac kernels` prints where+the kernels were found.## What is herediff --git a/engine-mac/Sources/KokonEngine/EngineBundle.swift b/engine-mac/Sources/KokonEngine/EngineBundle.swiftnew file mode 100644index 0000000..8cd1968--- /dev/null+++ b/engine-mac/Sources/KokonEngine/EngineBundle.swift@@ -0,0 +1,28 @@+import Foundation++/// **Where the kernels' source is**: SwiftPM's resource bundle, found by its folder rather than `Bundle.module`, which+/// looks at the root of an app bundle when the engine runs from `Kokon.app/Contents/MacOS` (and stops the process when+/// nothing is there). Places, in order: next to the executable (`swift build`, `install-dev.sh`), `engine-mac/` next+/// to it (`tauri dev` copies the app's resources there), `../Resources/engine-mac/` (inside Kokon.app).+public enum EngineBundle {+ static let name = "KokonEngineMac_KokonEngine.bundle"++ static let resources: Bundle = {+ let executable = URL(fileURLWithPath: CommandLine.arguments[0]).resolvingSymlinksInPath()+ let candidates = places(executable: Bundle.main.executableURL ?? executable)+ if let found = candidates.lazy.compactMap({ FileManager.default.fileExists(atPath: $0.path) ? Bundle(url: $0) : nil }).first {+ return found+ }+ return Bundle.module+ }()++ /// The bundle's possible places for an engine at `executable`.+ static func places(executable: URL) -> [URL] {+ let dir = executable.deletingLastPathComponent()+ return [dir.appendingPathComponent(name), dir.appendingPathComponent("engine-mac/" + name),+ dir.deletingLastPathComponent().appendingPathComponent("Resources/engine-mac/" + name)]+ }++ /// The `Kernels` folder of `resources`.+ public static var kernels: URL? { resources.url(forResource: "Kernels", withExtension: nil) }+}diff --git a/engine-mac/Sources/KokonEngine/MetalContext.swift b/engine-mac/Sources/KokonEngine/MetalContext.swiftindex 9036961..b0e374e 100644--- a/engine-mac/Sources/KokonEngine/MetalContext.swift+++ b/engine-mac/Sources/KokonEngine/MetalContext.swift@@ -32,7 +32,7 @@ public final class MetalContext: @unchecked Sendable {}self.device = deviceself.queue = queue- guard let directory = Bundle.module.url(forResource: "Kernels", withExtension: nil) else {+ guard let directory = EngineBundle.kernels else {throw Failure.noKernelSource}let files = try FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)diff --git a/engine-mac/Sources/KokonEngine/NeuralAccelerators.swift b/engine-mac/Sources/KokonEngine/NeuralAccelerators.swiftindex cd84dca..875bbb0 100644--- a/engine-mac/Sources/KokonEngine/NeuralAccelerators.swift+++ b/engine-mac/Sources/KokonEngine/NeuralAccelerators.swift@@ -25,7 +25,7 @@ public final class NeuralAccelerators: @unchecked Sendable {return nil}do {- guard let url = Bundle.module.url(forResource: "Kernels", withExtension: nil)?+ guard let url = EngineBundle.kernels?.appendingPathComponent("metal4/na_matmul.metal") else { throw MetalContext.Failure.noKernelSource }let options = MTLCompileOptions()options.languageVersion = .version4_0diff --git a/engine-mac/Sources/kokon-engine-mac/main.swift b/engine-mac/Sources/kokon-engine-mac/main.swiftindex 0fec545..0d93f46 100644--- a/engine-mac/Sources/kokon-engine-mac/main.swift+++ b/engine-mac/Sources/kokon-engine-mac/main.swift@@ -198,6 +198,9 @@ do {guard arguments.count >= 6 else { fail(usage) }try Bench.child(mode: arguments[1], encoder: arguments[2], dit: arguments[3], vae: arguments[4], prefix: arguments[5],quick: arguments.contains("--quick"))+ case "kernels":+ // Where the kernels' source was found (diagnostics: Kokon.app, tauri dev, swift build).+ print(EngineBundle.kernels?.path ?? "not found")case "check-ane8":try Checks.aneInt8()case "check-na":diff --git a/engine-mac/Tests/KokonEngineTests/EngineBundleTests.swift b/engine-mac/Tests/KokonEngineTests/EngineBundleTests.swiftnew file mode 100644index 0000000..f4052cb--- /dev/null+++ b/engine-mac/Tests/KokonEngineTests/EngineBundleTests.swift@@ -0,0 +1,19 @@+import XCTest+@testable import KokonEngine++/// The kernels are found from `swift build`'s folder, and the places include Kokon.app's layout.+final class EngineBundleTests: XCTestCase {+ func testFindsTheKernels() throws {+ let kernels = try XCTUnwrap(EngineBundle.kernels)+ XCTAssertTrue(FileManager.default.fileExists(atPath: kernels.appendingPathComponent("dit.metal").path))+ }++ func testPlacesInsideTheApp() {+ let places = EngineBundle.places(executable: URL(fileURLWithPath: "/Applications/Kokon.app/Contents/MacOS/kokon-engine-mac"))+ XCTAssertEqual(places.map(\.path), [+ "/Applications/Kokon.app/Contents/MacOS/KokonEngineMac_KokonEngine.bundle",+ "/Applications/Kokon.app/Contents/MacOS/engine-mac/KokonEngineMac_KokonEngine.bundle",+ "/Applications/Kokon.app/Contents/Resources/engine-mac/KokonEngineMac_KokonEngine.bundle",+ ])+ }+}diff --git a/engine-mac/tools/install-dev.sh b/engine-mac/tools/install-dev.shindex 8792ca0..564f59d 100755--- a/engine-mac/tools/install-dev.sh+++ b/engine-mac/tools/install-dev.sh@@ -1,7 +1,8 @@#!/bin/bash# Builds kokon-engine-mac and puts it where Kokon looks for it when "Kokon's Mac engine" is on (Settings →-# Performance): <stable-diffusion.cpp folder>/engine-mac/, beside sd.cpp's engine-metal. The kernels and resources-# are the KokonEngineMac_KokonEngine.bundle next to the executable.+# Performance) and the app has no copy of its own (Kokon.app and `tauri dev` have one, see stage-app.sh):+# <stable-diffusion.cpp folder>/engine-mac/, beside sd.cpp's engine-metal. The kernels and resources are the+# KokonEngineMac_KokonEngine.bundle next to the executable.## bash engine-mac/tools/install-dev.sh [stable-diffusion.cpp folder]set -euo pipefaildiff --git a/engine-mac/tools/stage-app.sh b/engine-mac/tools/stage-app.shnew file mode 100755index 0000000..6b54f00--- /dev/null+++ b/engine-mac/tools/stage-app.sh@@ -0,0 +1,13 @@+#!/bin/bash+# Builds kokon-engine-mac and puts it where Tauri packs it into Kokon.app (scripts/dev/mac-dev.sh and+# scripts/build-release-mac.sh call it): the executable as a sidecar next to kokon-service+# (src-tauri/binaries, Contents/MacOS in the app), its kernels as a resource (Contents/Resources/engine-mac).+#+# bash engine-mac/tools/stage-app.sh+set -euo pipefail+root="$(cd "$(dirname "$0")/../.." && pwd)"+(cd "$root/engine-mac" && swift build -c release 2>&1 | tail -1)+mkdir -p "$root/src-tauri/binaries"+cp "$root/engine-mac/.build/release/kokon-engine-mac" "$root/src-tauri/binaries/kokon-engine-mac-aarch64-apple-darwin"+rm -rf "$root/src-tauri/resources/engine-mac" && mkdir -p "$root/src-tauri/resources/engine-mac"+cp -R "$root/engine-mac/.build/release/KokonEngineMac_KokonEngine.bundle" "$root/src-tauri/resources/engine-mac/"diff --git a/scripts/build-release-mac.sh b/scripts/build-release-mac.shindex 7737f2e..fa76c1f 100755--- a/scripts/build-release-mac.sh+++ b/scripts/build-release-mac.sh@@ -1,5 +1,5 @@#!/usr/bin/env bash-# Builds the macOS release on an Apple Silicon Mac: kokon-service, kokon-mcp, Kokon.app and+# Builds the macOS release on an Apple Silicon Mac: kokon-service, kokon-mcp, kokon-engine-mac, Kokon.app and# the disk image ("Kokon_<version>_aarch64.dmg"), copied to dist-release/.## bash scripts/build-release-mac.sh@@ -30,6 +30,9 @@ echo "3/5 kokon-service (release)"cargo build -p qls-service --releasemkdir -p src-tauri/binariescp target/release/kokon-service "src-tauri/binaries/kokon-service-$TRIPLE"+# Kokon's Mac engine: its tests compile and run the kernels on this Mac's GPU (~15 s), then it goes into the app.+(cd engine-mac && swift test 2>&1 | grep -E "Executed [0-9]+ tests" | tail -1)+bash engine-mac/tools/stage-app.shecho "4/5 kokon-mcp + MCP tests (they drive the bundle and the service built above)"(cd mcp && npm run build:exe && npx vitest run)diff --git a/scripts/dev/mac-dev.sh b/scripts/dev/mac-dev.shindex 7525b5e..2d68f20 100755--- a/scripts/dev/mac-dev.sh+++ b/scripts/dev/mac-dev.sh@@ -45,5 +45,8 @@ exec node "$ROOT/mcp/build/kokon-mcp.cjs" "\$@"EOFchmod +x "src-tauri/binaries/kokon-mcp-$TRIPLE"+echo "→ Kokon's Mac engine (Swift)"+bash engine-mac/tools/stage-app.sh+echo "→ Starting Kokon (close the window to stop)"npx tauri devdiff --git a/src-tauri/tauri.macos.conf.json b/src-tauri/tauri.macos.conf.jsonindex 56368b1..dbf6591 100644--- a/src-tauri/tauri.macos.conf.json+++ b/src-tauri/tauri.macos.conf.json@@ -22,6 +22,14 @@]},"bundle": {+ "externalBin": [+ "binaries/kokon-service",+ "binaries/kokon-mcp",+ "binaries/kokon-engine-mac"+ ],+ "resources": {+ "resources/engine-mac/": "engine-mac/"+ },"targets": ["app","dmg"diff --git a/src/App.tsx b/src/App.tsxindex 805cad6..c08083c 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -4,6 +4,7 @@ import { useEffect, useRef, useState } from "react";import { api, ApiError, configure, setSignedOutHandler } from "./lib/api";import { native } from "./lib/native";import { inBrowser, isNarrow, useNarrow } from "./lib/platform";+import { macEngineOfferDue } from "./lib/logic";import {addExampleProjects, closeStarPrompt, loadProjects, dismissToast, getState, initStarPrompt, redoVersion, refreshLoras, refreshStatus, selectItem, setState, startEvents, startTour, submitComposer, toastError, toastInfo, undoVersion, useStore,} from "./lib/store";@@ -20,6 +21,7 @@ import { Tour } from "./components/Tour";import { PromptTips } from "./components/PromptTips";import { Shortcuts } from "./components/Shortcuts";import { WhatsNew, whatsNewDue } from "./components/WhatsNew";+import { MacEngineOffer } from "./components/MacEngineOffer";import { UpscalerCompare } from "./components/Upscalers";import { KokonMark, Welcome } from "./components/Welcome";import { PhoneApp } from "./components/PhoneApp";@@ -168,7 +170,9 @@ export default function App() {// newer one (it can be postponed there; offered again only for another release).const whatsNew = cfg.setupComplete && whatsNewDue(ui, st?.engine);const engineUpdate = whatsNew && !!st?.engine?.update_needed;- setState({ needsSetup: !cfg.setupComplete, ...(!welcomeSeen ? { overlay: "welcome" } : whatsNew ? { overlay: "whats-new" } : {}) });+ // Otherwise, once on a Mac: Kokon's Mac engine (before the model loads, on the engine chosen).+ const macOffer = !inBrowser && welcomeSeen && !whatsNew && macEngineOfferDue(st, ui, cfg.setupComplete);+ setState({ needsSetup: !cfg.setupComplete, ...(!welcomeSeen ? { overlay: "welcome" } : whatsNew ? { overlay: "whats-new" } : macOffer ? { overlay: "mac-engine" } : {}) });setBoot("ok");if (!inBrowser) autoCheckForUpdate();// Own model files that run but don't suit Kokon's 8 steps (the base model instead of Turbo).@@ -178,7 +182,7 @@ export default function App() {if (w) toastError(new ApiError({ code: "model_warning", message: w, suggestion: "Settings → Models: download the official files, or use other files of your own." }, 200));}, () => {});// Preload the model so the first generation starts immediately (not an engine about to be replaced).- if (cfg.setupComplete && !engineUpdate && st && st.server.state === "stopped") api.startBackend().then(refreshStatus, () => refreshStatus());+ if (cfg.setupComplete && !engineUpdate && !macOffer && st && st.server.state === "stopped") api.startBackend().then(refreshStatus, () => refreshStatus());} catch (e) {setBoot(String(e));}@@ -346,6 +350,7 @@ export default function App() {{overlay === "settings" && <SettingsDialog />}{overlay === "welcome" && <Welcome />}{overlay === "whats-new" && <WhatsNew />}+ {overlay === "mac-engine" && <MacEngineOffer />}{overlay === "prompt-tips" && <PromptTips />}{overlay === "shortcuts" && <Shortcuts />}{compareUpscalers && <UpscalerCompare />}diff --git a/src/components/MacEngineOffer.tsx b/src/components/MacEngineOffer.tsxnew file mode 100644index 0000000..3500029--- /dev/null+++ b/src/components/MacEngineOffer.tsx@@ -0,0 +1,72 @@+import { Activity, RotateCcw, Zap } from "lucide-react";+import { useEffect } from "react";+import { api } from "../lib/api";+import { refreshStatus, setState, toastError, toastInfo } from "../lib/store";+import { KokonMark } from "./Welcome";++const POINTS = [+ {+ icon: Zap,+ title: "About 4 times faster",+ text: "The GPU, the CPU's matrix unit and the Neural Engine work together: a new 1024 × 1024 image takes about a minute on an M2 Pro instead of four. Edits, brushed edits, extending and Prompt+ work too.",+ },+ {+ icon: RotateCcw,+ title: "Switch back any time",+ text: "Settings → Performance → Kokon's Mac engine. LoRAs and the upscaler model still need the standard engine.",+ },+ {+ icon: Activity,+ title: "Help us tune it",+ text: "Settings → Performance → Benchmark this Mac measures it in about 10 minutes and gives a report to paste on GitHub. Reports from M1, M3, M4 and M5 Macs help most.",+ },+];++/** Once, at start on a Mac (after Setup or What's new): Kokon's own engine, experimental and off by default. The+ * model loads after the answer, on the engine chosen. */+export function MacEngineOffer() {+ const answer = async (on: boolean) => {+ setState({ overlay: null });+ try {+ const cfg = await api.config();+ const ui = { ...((cfg.ui ?? {}) as Record<string, unknown>), macEngineOffered: true };+ await api.saveConfig({ ...cfg, macEngine: on || !!cfg.macEngine, ui });+ if (on) toastInfo("Kokon's Mac engine is on. Switch back any time in Settings → Performance.");+ } catch (e) {+ toastError(e);+ }+ api.startBackend().then(refreshStatus, () => refreshStatus());+ };+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => e.key === "Escape" && answer(false);+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, []);+ return (+ <div className="modal-scrim">+ <div className="welcome" role="dialog" aria-label="Try Kokon's Mac engine">+ <KokonMark size={44} />+ <h1>Try Kokon's Mac engine</h1>+ <p className="welcome-lead">Kokon now has its own engine for Apple Silicon. It's experimental, so it stays off until you turn it on.</p>+ <div className="welcome-grid">+ {POINTS.map(({ icon: Icon, title, text }) => (+ <div className="welcome-item" key={title}>+ <Icon size={20} />+ <strong>{title}</strong>+ <span>{text}</span>+ </div>+ ))}+ </div>+ <div style={{ display: "flex", gap: 10, justifyContent: "center", flexWrap: "wrap" }}>+ <button className="btn primary big" onClick={() => answer(true)}>+ Try it+ </button>+ <button className="btn big" onClick={() => answer(false)}>+ Not now+ </button>+ </div>+ <span className="muted welcome-foot">Your images, models and settings stay as they are.</span>+ </div>+ </div>+ );+}diff --git a/src/components/Setup.tsx b/src/components/Setup.tsxindex db38075..17b3666 100644--- a/src/components/Setup.tsx+++ b/src/components/Setup.tsx@@ -4,7 +4,7 @@ import { api } from "../lib/api";import { formatBytes, installItemShort, installProgress, installStep, installTimeLeft } from "../lib/logic";import { native } from "../lib/native";import { inBrowser } from "../lib/platform";-import { refreshStatus, setState, toastError, toastInfo, useStore } from "../lib/store";+import { afterStartScreens, refreshStatus, setState, toastError, toastInfo, useStore } from "../lib/store";import type { GpuBackend, HardwareReport, InstallItem, InstallStatus, ModelScan, ModelSlot, ModelsStatus, SetupReport } from "../lib/types";import { OwnModels } from "./OwnModels";import { Seg } from "./ui";@@ -318,8 +318,8 @@ export function Setup() {if (st?.engine?.update_needed) ui.engineUpdateSkipped = st.engine.release;await api.saveConfig({ ...cfg, setupComplete: true, ui });setState({ needsSetup: false, setupMode: null });- // Load the model in the background; the status indicator shows progress.- api.startBackend().then(refreshStatus, toastError);+ // On a Mac, the Mac engine offer first; then the model loads in the background (the status indicator shows it).+ afterStartScreens();refreshStatus();} catch (e) {toastError(e);diff --git a/src/components/WhatsNew.tsx b/src/components/WhatsNew.tsxindex 6504a81..4386367 100644--- a/src/components/WhatsNew.tsx+++ b/src/components/WhatsNew.tsx@@ -2,7 +2,7 @@ import { CircleAlert, Container, FolderSync, ShieldCheck, Smartphone, TabletSmarimport { useEffect, useState } from "react";import { api } from "../lib/api";import { formatBytes, installProgress, installStep, installTimeLeft } from "../lib/logic";-import { refreshStatus, setState, toastError, useStore } from "../lib/store";+import { afterStartScreens, refreshStatus, setState, toastError, useStore } from "../lib/store";import type { GpuBackend, InstallItem, InstallStatus, ModelsStatus } from "../lib/types";import { KokonMark } from "./Welcome";@@ -155,7 +155,7 @@ export function WhatsNew() {setState({ overlay: null });markSeen(postponed && engine && needsEngine ? engine.release : null);refreshStatus();- api.startBackend().then(refreshStatus, () => refreshStatus());+ afterStartScreens();};return (diff --git a/src/lib/logic.test.ts b/src/lib/logic.test.tsindex fe56993..af0a91f 100644--- a/src/lib/logic.test.ts+++ b/src/lib/logic.test.ts@@ -1,5 +1,6 @@import { describe, expect, it } from "vitest";import {+ macEngineOfferDue,macBenchProgress,activeLoras, activeOverrides, buildRequest, composing, editing, reviewRequest, wantsPromptReview, 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,@@ -627,3 +628,19 @@ describe("macBenchProgress", () => {expect(macBenchProgress({ state: "done", report: "r", finished_at: started_at, quick: false }, t0)).toBeNull();});});++describe("macEngineOfferDue", () => {+ const gpu = (gb: number) => ({ name: "Apple M2 Pro", vendor: "apple", unified: true, memory_total_mib: gb * 1024, memory_used_mib: 0, memory_free_mib: 0, driver_version: "" });+ const st = (available: boolean, on: boolean, gb = 16) => ({ gpu: gpu(gb), mac_engine: { available, on } });+ it("offers it once on a set-up Mac with the engine in the app", () => {+ expect(macEngineOfferDue(st(true, false), {}, true)).toBe(true);+ expect(macEngineOfferDue(st(true, false), { macEngineOffered: true }, true)).toBe(false);+ });+ it("not before setup, without the engine, when it is on, or below 16 GB", () => {+ expect(macEngineOfferDue(st(true, false), {}, false)).toBe(false);+ expect(macEngineOfferDue(st(false, false), {}, true)).toBe(false);+ expect(macEngineOfferDue(st(true, true), {}, true)).toBe(false);+ expect(macEngineOfferDue(st(true, false, 8), {}, true)).toBe(false);+ expect(macEngineOfferDue({ gpu: null, mac_engine: undefined }, {}, true)).toBe(false);+ });+});diff --git a/src/lib/logic.ts b/src/lib/logic.tsindex 7558e04..346f984 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, LoraItem, LutInfo, MacBenchState, Mode, OutpaintSpec, Plan, Quality, ResolutionMode, Size } from "./types";+import type { Advanced, GenerationRecord, GenerationRequest, InpaintAction, InputRecord, InstallItem, JobView, LoraItem, LutInfo, MacBenchState, Mode, StatusResponse, OutpaintSpec, Plan, Quality, ResolutionMode, Size } from "./types";export interface Ref {key: string;@@ -642,6 +642,13 @@ export function formatBytes(n: number): string {return `${Math.max(0, Math.round(n / 1e3))} KB`;}+/** Offer Kokon's Mac engine once, at start: set up, the engine in the app, off, never asked. Not below 16 GB: the+ * engine peaks at ~9 GB during a 1024² decode (M2 Pro, Benchmark button 2026-10-26) and was never run on 8 GB. */+export function macEngineOfferDue(st: Pick<StatusResponse, "gpu" | "mac_engine"> | null, ui: Record<string, unknown>, setupComplete: boolean): boolean {+ const engine = st?.mac_engine;+ return setupComplete && !!engine?.available && !engine.on && !ui.macEngineOffered && (st?.gpu?.memory_total_mib ?? 0) >= 15 * 1024;+}+/** Benchmark this Mac while it runs: the bar's fill and the line under it ("Step 2 of 7 · Default: accuracy at* 512² · 3 min"). The engine names a run by the setting it changes; its first run is the default paths. */export function macBenchProgress(b: MacBenchState, now: number): { frac: number; text: string } | null {diff --git a/src/lib/store.ts b/src/lib/store.tsindex 8abd1c5..63ed9a1 100644--- a/src/lib/store.ts+++ b/src/lib/store.ts@@ -9,10 +9,10 @@ import { inBrowser, isNarrow } from "./platform";import { useSyncExternalStore } from "react";import { markFresh } from "../components/Cocoon";import { api, ApiError, setPrivateInputs, subscribe, urls } from "./api";-import { activeLoras, buildRequest, composing, emptyComposer, goneVersions, needsPrompt, newKey, pageOutdated, persistentAdvanced, refFromGen, refFromInput, reviewRequest, stageFitsPreview, starPromptDue, timelineLinks, undoTarget, versionLabels, wantsPromptReview, type CompareMode, type Composer, type Ref } from "./logic";+import { activeLoras, buildRequest, composing, emptyComposer, goneVersions, macEngineOfferDue, needsPrompt, newKey, pageOutdated, persistentAdvanced, refFromGen, refFromInput, reviewRequest, stageFitsPreview, starPromptDue, timelineLinks, undoTarget, versionLabels, wantsPromptReview, type CompareMode, type Composer, type Ref } from "./logic";import type { AppErrorBody, GenerationRecord, GenerationRequest, InputRecord, JobView, LoraItem, MacBenchState, ServerState, StatusResponse } from "./types";-export type Overlay = null | "gallery" | "settings" | "inpaint" | "expand" | "welcome" | "whats-new" | "prompt-tips" | "shortcuts";+export type Overlay = null | "gallery" | "settings" | "inpaint" | "expand" | "welcome" | "whats-new" | "mac-engine" | "prompt-tips" | "shortcuts";export interface SessionItem {key: string;@@ -495,6 +495,21 @@ export function dismissToast(id: string) {let unsub: (() => void) | null = null;+/** After Setup or What's new: the Mac engine offer when it is due (the answer decides which engine loads), else the+ * model loads in the background so the first image starts at once. */+export async function afterStartScreens() {+ try {+ const [cfg, st] = await Promise.all([api.config(), api.status()]);+ if (!inBrowser && macEngineOfferDue(st, (cfg.ui ?? {}) as Record<string, unknown>, cfg.setupComplete)) {+ setState({ overlay: "mac-engine" });+ return;+ }+ } catch {+ // The offer can wait for the next start; the model still loads.+ }+ api.startBackend().then(refreshStatus, () => refreshStatus());+}+export async function refreshStatus() {try {const st = await api.status();diff --git a/src/lib/types.ts b/src/lib/types.tsindex 322ff44..94eefdc 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -241,6 +241,8 @@ export interface StatusResponse {/** The installed engine predates `release` (needed for the upscaler): Setup updates it. */engine?: { release: string; update_needed: boolean };setup_complete: boolean;+ /** Kokon's Mac engine: installed (inside the app or by hand) and switched on. */+ mac_engine?: { available: boolean; on: boolean };}export interface Check { id: string; label: string; ok: boolean; detail: string }