Skip to content

AI media harness for planning, generating, and editing locally

TypeScript

Show CUDA setup guidance at startup

Bitti2c12c7e51b0f
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 888c5ae..13506a1 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -29,7 +29,7 @@ reqwest = { version = "0.12", default-features = false, features = ["blocking",
jpeg-encoder = "0.6"
[target.'cfg(windows)'.dependencies]
-windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_Storage_FileSystem"] }
+windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_Storage_FileSystem", "Win32_UI_Shell"] }
[dev-dependencies]
tempfile = "3"
diff --git a/src-tauri/src/cuda_support.rs b/src-tauri/src/cuda_support.rs
new file mode 100644
index 0000000..525cec0
--- /dev/null
+++ b/src-tauri/src/cuda_support.rs
@@ -0,0 +1,51 @@
+const CUDA_DOWNLOADS: &str = "https://developer.nvidia.com/cuda-downloads";
+const CUDA_12_8_DOWNLOADS: &str = "https://developer.nvidia.com/cuda-12-8-0-download-archive";
+
+fn download_url(version: &str) -> Result<&'static str, String> {
+ match version {
+ "latest" => Ok(CUDA_DOWNLOADS),
+ "12.8" => Ok(CUDA_12_8_DOWNLOADS),
+ _ => Err("Unsupported CUDA download version.".into()),
+ }
+}
+
+#[tauri::command]
+pub fn open_cuda_download(version: String) -> Result<(), String> {
+ // Only these two download pages can be opened by this command.
+ let url = download_url(&version)?;
+ #[cfg(windows)]
+ {
+ use windows_sys::Win32::UI::Shell::ShellExecuteW;
+ let operation: Vec<u16> = "open\0".encode_utf16().collect();
+ let target: Vec<u16> = url.encode_utf16().chain(Some(0)).collect();
+ // Both strings are NUL-terminated and remain alive for the shell call.
+ let result = unsafe {
+ ShellExecuteW(std::ptr::null_mut(), operation.as_ptr(), target.as_ptr(),
+ std::ptr::null(), std::ptr::null(), 1)
+ };
+ if result as isize <= 32 {
+ return Err("Could not open the browser. Copy the download link into your browser.".into());
+ }
+ Ok(())
+ }
+ #[cfg(not(windows))]
+ {
+ let program = if cfg!(target_os = "macos") { "open" } else { "xdg-open" };
+ std::process::Command::new(program).arg(url).spawn()
+ .map(|_| ())
+ .map_err(|error| format!("Could not open the browser: {error}"))
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn only_opens_the_requested_nvidia_download_pages() {
+ assert_eq!(download_url("latest").unwrap(), CUDA_DOWNLOADS);
+ assert_eq!(download_url("12.8").unwrap(), CUDA_12_8_DOWNLOADS);
+ assert!(download_url("https://example.com").is_err());
+ assert!(download_url("file:///C:/Windows").is_err());
+ }
+}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 801e18b..49756eb 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -10,6 +10,7 @@ use tauri_plugin_dialog::DialogExt;
mod agent;
mod agent_commands;
+mod cuda_support;
mod diagnostics;
mod export;
mod reference_icons;
@@ -2799,6 +2800,7 @@ pub fn run() {
.plugin(tauri_plugin_process::init())
.invoke_handler(tauri::generate_handler![
app_updater_enabled,
+ cuda_support::open_cuda_download,
write_diagnostic_log,
diagnostic_log_info,
reveal_diagnostic_log,
diff --git a/src-tauri/src/slopfab.rs b/src-tauri/src/slopfab.rs
index 4ddd039..35f573a 100644
--- a/src-tauri/src/slopfab.rs
+++ b/src-tauri/src/slopfab.rs
@@ -87,6 +87,7 @@ pub struct SlopfabStatus {
pub version: Option<String>,
pub platform: Option<&'static str>,
pub cuda_available: bool,
+ pub cuda_device_names: Vec<String>,
pub detail: String,
pub models: Vec<ModelStatus>,
}
@@ -495,6 +496,7 @@ pub fn status(settings: &BTreeMap<String, ProviderSetting>) -> SlopfabStatus {
version: Some(version),
platform: Some(platform.label()),
cuda_available: detected != ComputePlatform::Vulkan,
+ cuda_device_names: ffi::cuda_device_names(),
detail: if missing == 0 {
"Runtime and required model paths are available.".into()
} else {
@@ -509,6 +511,7 @@ pub fn status(settings: &BTreeMap<String, ProviderSetting>) -> SlopfabStatus {
version: None,
platform: None,
cuda_available: false,
+ cuda_device_names: Vec::new(),
detail: error,
models,
},
@@ -519,6 +522,7 @@ pub fn status(settings: &BTreeMap<String, ProviderSetting>) -> SlopfabStatus {
version: None,
platform: None,
cuda_available: false,
+ cuda_device_names: Vec::new(),
detail: format!("slopfab is unavailable: {error}. Editing remains available."),
models,
},
@@ -1017,6 +1021,35 @@ mod ffi {
init(0) == 0 && count(&mut devices) == 0 && devices > 0
}
}
+ pub fn cuda_device_names() -> Vec<String> {
+ // The display driver's API is available without the CUDA toolkit.
+ // Keep the library and fixed-size name buffer alive for every call.
+ unsafe {
+ #[cfg(windows)]
+ let driver = libloading::os::windows::Library::load_with_flags(
+ "nvcuda.dll", 0x00000800, // LOAD_LIBRARY_SEARCH_SYSTEM32
+ ).map(Library::from);
+ #[cfg(not(windows))]
+ let driver = Library::new("libcuda.so.1");
+ let Ok(library) = driver else { return Vec::new() };
+ let Ok(init) = library.get::<unsafe extern "system" fn(u32) -> i32>(b"cuInit\0") else { return Vec::new() };
+ let Ok(count) = library.get::<unsafe extern "system" fn(*mut i32) -> i32>(b"cuDeviceGetCount\0") else { return Vec::new() };
+ let Ok(get) = library.get::<unsafe extern "system" fn(*mut i32, i32) -> i32>(b"cuDeviceGet\0") else { return Vec::new() };
+ let Ok(name) = library.get::<unsafe extern "system" fn(*mut c_char, i32, i32) -> i32>(b"cuDeviceGetName\0") else { return Vec::new() };
+ let mut count_value = 0;
+ if init(0) != 0 || count(&mut count_value) != 0 { return Vec::new() }
+ (0..count_value).filter_map(|ordinal| {
+ let mut device = 0;
+ let mut buffer = [0u8; 256];
+ if get(&mut device, ordinal) != 0 || name(buffer.as_mut_ptr().cast(), buffer.len() as i32, device) != 0 {
+ return None;
+ }
+ let end = buffer.iter().position(|byte| *byte == 0).unwrap_or(buffer.len());
+ Some(String::from_utf8_lossy(&buffer[..end]).into_owned())
+ }).collect()
+ }
+ }
+
pub enum Generation {}
#[repr(C)]
#[derive(Clone, Copy)]
diff --git a/src/App.cuda.test.tsx b/src/App.cuda.test.tsx
new file mode 100644
index 0000000..8305c22
--- /dev/null
+++ b/src/App.cuda.test.tsx
@@ -0,0 +1,74 @@
+// @vitest-environment jsdom
+import "@testing-library/jest-dom/vitest";
+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { invoke } from "@tauri-apps/api/core";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+import App from "./App";
+import { getRuntimeStatus, type RuntimeStatus } from "./lib/runtime";
+
+vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn(async () => undefined) }));
+vi.mock("@tauri-apps/api/event", () => ({ listen: vi.fn(async () => () => undefined) }));
+vi.mock("./lib/persistence", async (original) => ({
+ ...await original<typeof import("./lib/persistence")>(),
+ isTauri: () => true,
+ listRecentProjects: async () => ({ projects: [], unreadable: [] }),
+}));
+vi.mock("./lib/runtime", async (original) => ({
+ ...await original<typeof import("./lib/runtime")>(), getRuntimeStatus: vi.fn(),
+}));
+
+const detected: RuntimeStatus = {
+ providers: [],
+ slopfab: { state: "modelsMissing", dllPath: "slopfab.dll", version: "1.4.0", platform: "Vulkan", cudaAvailable: false, cudaDeviceNames: ["NVIDIA GeForce RTX 5090"], detail: "Missing models", models: [] },
+};
+
+beforeEach(() => {
+ localStorage.clear();
+ vi.clearAllMocks();
+ vi.mocked(invoke).mockResolvedValue(undefined);
+ vi.mocked(getRuntimeStatus).mockResolvedValue(detected);
+});
+afterEach(cleanup);
+
+it("shows startup guidance, opens NVIDIA in the browser, and stays dismissed after checking settings", async () => {
+ render(<App />);
+ const dialog = await screen.findByRole("dialog", { name: "Install CUDA for faster generation" });
+ expect(within(dialog).getByText(/Vulkan fallback backend, with longer generation times/)).toBeInTheDocument();
+ const proceed = within(dialog).getByRole("button", { name: "Continue with Vulkan" });
+ expect(proceed).toHaveFocus();
+ const download = within(dialog).getByRole("link", { name: "Download CUDA from NVIDIA" });
+ expect(download).toHaveAttribute("href", "https://developer.nvidia.com/cuda-downloads");
+ fireEvent.keyDown(proceed, { key: "Tab" });
+ expect(download).toHaveFocus();
+ fireEvent.keyDown(download, { key: "Tab", shiftKey: true });
+ expect(proceed).toHaveFocus();
+ fireEvent.click(download);
+ await waitFor(() => expect(invoke).toHaveBeenCalledWith("open_cuda_download", { version: "latest" }));
+ fireEvent.click(proceed);
+ expect(screen.queryByRole("dialog", { name: "Install CUDA for faster generation" })).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "Settings" }));
+ fireEvent.keyDown(window, { key: "Escape" });
+ await waitFor(() => expect(getRuntimeStatus).toHaveBeenCalledTimes(2));
+ expect(screen.queryByRole("dialog", { name: "Install CUDA for faster generation" })).toBeNull();
+});
+
+it("offers the CUDA 12.8 archive for older RTX cards and allows Escape to proceed after a browser error", async () => {
+ vi.mocked(getRuntimeStatus).mockResolvedValue({ ...detected, slopfab: { ...detected.slopfab, cudaDeviceNames: ["NVIDIA GeForce RTX 3080"] } });
+ render(<App />);
+ const dialog = await screen.findByRole("dialog", { name: "Install CUDA for faster generation" });
+ const download = within(dialog).getByRole("link", { name: "Download CUDA 12.8 from NVIDIA" });
+ expect(download).toHaveAttribute("href", "https://developer.nvidia.com/cuda-12-8-0-download-archive");
+ vi.mocked(invoke).mockRejectedValueOnce(new Error("Browser unavailable"));
+ fireEvent.click(download);
+ expect(await within(dialog).findByRole("alert")).toHaveTextContent("Browser unavailable");
+ expect(invoke).toHaveBeenCalledWith("open_cuda_download", { version: "12.8" });
+ fireEvent.keyDown(window, { key: "Escape" });
+ expect(screen.queryByRole("dialog", { name: "Install CUDA for faster generation" })).toBeNull();
+});
+
+it("does not show the popup when CUDA is usable but Vulkan is selected", async () => {
+ vi.mocked(getRuntimeStatus).mockResolvedValue({ ...detected, slopfab: { ...detected.slopfab, cudaAvailable: true } });
+ render(<App />);
+ await screen.findByText("No projects yet");
+ expect(screen.queryByRole("dialog", { name: "Install CUDA for faster generation" })).toBeNull();
+});
diff --git a/src/App.tsx b/src/App.tsx
index 9a2aa95..4d964f1 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -1,6 +1,8 @@
import { WorkQueue, isWorkActive, projectQueueKey } from "./lib/workQueue";
import { WorkQueuePanel } from "./components/WorkQueuePanel";
import { ReferenceIconGenerationDialog } from "./components/ReferenceIconGenerationDialog";
+import { CudaSetupDialog } from "./components/CudaSetupDialog";
+import { missingCudaDownload } from "./lib/cudaSupport";
import { invoke } from "@tauri-apps/api/core";
import { listen } from "@tauri-apps/api/event";
import { FolderOpen, Grid2X2, List, ListTodo, Plus, Search, Settings } from "lucide-react";
@@ -80,6 +82,8 @@ function App() {
which is seconds of work, and the answer is the same for every project.
Null means the probe has not landed yet — never "nothing is installed". */
const [runtime, setRuntime] = useState<RuntimeStatus | null>(null);
+ const [cudaNoticeDismissed, setCudaNoticeDismissed] = useState(false);
+ const cudaDownload = !cudaNoticeDismissed && isTauri() ? missingCudaDownload(runtime?.slopfab) : null;
const searchInput = useRef<HTMLInputElement>(null);
/* ── Exit guard: the window's close button ───────────────────────────────
@@ -243,7 +247,9 @@ function App() {
<ListTodo size={22} aria-hidden="true" />{ongoingGenerations.length > 0 && <b>{ongoingGenerations.length}</b>}
</button>;
const queuePanel = workQueueOpen ? <WorkQueuePanel queue={workQueue} items={workItems} onClose={() => setWorkQueueOpen(false)} /> : null;
- const iconConfirmation = iconConfirmationCount > 0 && !settingsOpen && !workQueueOpen && !closeRequested && !projectToDelete && !newProjectOpen
+ const cudaNotice = cudaDownload && !settingsOpen && !workQueueOpen && !closeRequested && !projectToDelete && !newProjectOpen
+ ? <CudaSetupDialog download={cudaDownload} onContinue={() => setCudaNoticeDismissed(true)} /> : null;
+ const iconConfirmation = iconConfirmationCount > 0 && !cudaNotice && !settingsOpen && !workQueueOpen && !closeRequested && !projectToDelete && !newProjectOpen
? <ReferenceIconGenerationDialog count={iconConfirmationCount} onAnswer={workQueue.answerIconConfirmation} /> : null;
if (activeProject) {
@@ -256,6 +262,7 @@ function App() {
{updateNotice}
<UpdateProgress updater={updater} />
{iconConfirmation}
+ {cudaNotice}
{exitGuard}
</>;
}
@@ -313,6 +320,7 @@ function App() {
<UpdateProgress updater={updater} />
{projectToDelete && <DeleteProjectDialog project={projectToDelete} deleting={deletingProject} onConfirm={() => void confirmProjectDeletion()} onCancel={() => setProjectToDelete(null)} />}
{iconConfirmation}
+ {cudaNotice}
{exitGuard}
{error && <div className="toast" role="alert"><strong>{error.title}</strong><span>{error.detail}</span><button onClick={() => setError(null)}>Dismiss</button></div>}
</div>
diff --git a/src/components/CudaSetupDialog.tsx b/src/components/CudaSetupDialog.tsx
new file mode 100644
index 0000000..bfdba76
--- /dev/null
+++ b/src/components/CudaSetupDialog.tsx
@@ -0,0 +1,67 @@
+import { invoke } from "@tauri-apps/api/core";
+import { Info } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import type { CudaDownload } from "../lib/cudaSupport";
+
+export function CudaSetupDialog({ download, onContinue }: { download: CudaDownload; onContinue: () => void }) {
+ const dialog = useRef<HTMLDivElement>(null);
+ const proceed = useRef<HTMLButtonElement>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ const opener = document.activeElement as HTMLElement | null;
+ proceed.current?.focus();
+ return () => opener?.focus?.();
+ }, []);
+
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "Escape") {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ onContinue();
+ }
+ if (event.key !== "Tab" || !dialog.current) return;
+ const stops = Array.from(dialog.current.querySelectorAll<HTMLElement>("a[href], button"));
+ const first = stops[0], last = stops[stops.length - 1];
+ const active = document.activeElement as HTMLElement | null;
+ if (!event.shiftKey && (active === last || !dialog.current.contains(active))) {
+ event.preventDefault();
+ first.focus();
+ } else if (event.shiftKey && (active === first || !dialog.current.contains(active))) {
+ event.preventDefault();
+ last.focus();
+ }
+ };
+ window.addEventListener("keydown", onKeyDown, true);
+ return () => window.removeEventListener("keydown", onKeyDown, true);
+ }, [onContinue]);
+
+ const openDownload = async () => {
+ setError(null);
+ try {
+ await invoke("open_cuda_download", { version: download.version });
+ } catch (reason) {
+ setError(reason instanceof Error ? reason.message : String(reason));
+ }
+ };
+
+ return <div className="exit-guard-backdrop">
+ <div className="exit-guard" ref={dialog} role="dialog" aria-modal="true" aria-labelledby="cuda-setup-title" aria-describedby="cuda-setup-description">
+ <div className="exit-guard__head">
+ <span className="exit-guard__mark" aria-hidden="true"><Info size={20} /></span>
+ <h2 id="cuda-setup-title">Install CUDA for faster generation</h2>
+ </div>
+ <div className="exit-guard__body" id="cuda-setup-description">
+ <p>Slopus detected your {download.gpuName}, but could not find a usable CUDA installation.</p>
+ <p>You can continue using the Vulkan fallback backend, with longer generation times.</p>
+ <p>For faster generation, install {download.version === "12.8" ? "CUDA 12.8" : "CUDA"} and restart Slopus.</p>
+ <p><a className="cuda-setup-download" href={download.url} target="_blank" rel="noreferrer" onClick={(event) => { event.preventDefault(); void openDownload(); }}>Download {download.version === "12.8" ? "CUDA 12.8" : "CUDA"} from NVIDIA</a></p>
+ {error && <p role="alert">{error}</p>}
+ </div>
+ <div className="exit-guard__actions">
+ <button className="primary-button" type="button" ref={proceed} onClick={onContinue}>Continue with Vulkan</button>
+ </div>
+ </div>
+ </div>;
+}
diff --git a/src/lib/cudaSupport.test.ts b/src/lib/cudaSupport.test.ts
new file mode 100644
index 0000000..4d60832
--- /dev/null
+++ b/src/lib/cudaSupport.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from "vitest";
+import { missingCudaDownload } from "./cudaSupport";
+import type { SlopfabStatus } from "./runtime";
+
+const status = (names: string[], extra: Partial<SlopfabStatus> = {}): SlopfabStatus => ({
+ state: "modelsMissing", dllPath: "slopfab.dll", version: "1.4.0", platform: "Vulkan",
+ cudaAvailable: false, cudaDeviceNames: names, detail: "Missing models", models: [], ...extra,
+});
+
+describe("CUDA download recommendations", () => {
+ it.each(["NVIDIA GeForce RTX 5090", "NVIDIA GeForce RTX 5080 Laptop GPU", "RTX 5060 Ti"])("offers current CUDA for %s", (name) => {
+ expect(missingCudaDownload(status([name]))).toEqual({
+ gpuName: name, version: "latest", url: "https://developer.nvidia.com/cuda-downloads",
+ });
+ });
+
+ it.each(["NVIDIA GeForce RTX 4090", "RTX 4070 Ti SUPER", "NVIDIA GeForce RTX 3090", "RTX 3050 Laptop GPU"])("offers CUDA 12.8 for %s", (name) => {
+ expect(missingCudaDownload(status([name]))).toEqual({
+ gpuName: name, version: "12.8", url: "https://developer.nvidia.com/cuda-12-8-0-download-archive",
+ });
+ });
+
+ it.each(["NVIDIA GeForce RTX 2080 Ti", "NVIDIA RTX 5000 Ada Generation", "NVIDIA RTX 4000", "NVIDIA RTX A3000", "AMD Radeon RX 7900 XTX", "Intel Arc A770"])("does not recommend a toolkit for other GPU families: %s", (name) => {
+ expect(missingCudaDownload(status([name]))).toBeNull();
+ });
+
+ it("does not confuse a Vulkan preference, unknown detection, or a broken engine with missing CUDA", () => {
+ for (const extra of [{ cudaAvailable: true }, { cudaAvailable: undefined }, { state: "runtimeMissing" as const }, { state: "incompatible" as const }]) {
+ expect(missingCudaDownload(status(["RTX 5090"], extra))).toBeNull();
+ }
+ expect(missingCudaDownload(null)).toBeNull();
+ expect(missingCudaDownload(status([]))).toBeNull();
+ });
+
+ it("uses the current download when a 50-series card is present alongside older cards", () => {
+ expect(missingCudaDownload(status(["RTX 3080", "RTX 5090"]))?.version).toBe("latest");
+ });
+});
diff --git a/src/lib/cudaSupport.ts b/src/lib/cudaSupport.ts
new file mode 100644
index 0000000..dc9d3d3
--- /dev/null
+++ b/src/lib/cudaSupport.ts
@@ -0,0 +1,26 @@
+import type { SlopfabStatus } from "./runtime";
+
+export interface CudaDownload {
+ gpuName: string;
+ version: "latest" | "12.8";
+ url: string;
+}
+
+export function missingCudaDownload(status: SlopfabStatus | null | undefined): CudaDownload | null {
+ if (!status || status.cudaAvailable !== false || !["ready", "modelsMissing"].includes(status.state)) return null;
+ const devices = (status.cudaDeviceNames ?? []).flatMap((gpuName) => {
+ // Match GeForce model numbers, including Ti/SUPER/laptop variants. Exclude
+ // workstation names such as RTX 4000 Ada and RTX 5000, which use other chips.
+ const series = /\bRTX\s+(30|40|50)([1-9]\d)\b/i.exec(gpuName)?.[1];
+ return series ? [{ gpuName, series }] : [];
+ });
+ const gpu = devices.find((device) => device.series === "50") ?? devices[0];
+ if (!gpu) return null;
+ return {
+ gpuName: gpu.gpuName,
+ version: gpu.series === "50" ? "latest" : "12.8",
+ url: gpu.series === "50"
+ ? "https://developer.nvidia.com/cuda-downloads"
+ : "https://developer.nvidia.com/cuda-12-8-0-download-archive",
+ };
+}
diff --git a/src/lib/runtime.ts b/src/lib/runtime.ts
index ffbb9fb..84e0eed 100644
--- a/src/lib/runtime.ts
+++ b/src/lib/runtime.ts
@@ -31,6 +31,7 @@ export interface SlopfabStatus {
version: string | null;
platform: string | null;
cudaAvailable?: boolean;
+ cudaDeviceNames?: string[];
detail: string;
models: ModelStatus[];
}
diff --git a/src/styles/exit-guard.css b/src/styles/exit-guard.css
index 5887df2..87eb147 100644
--- a/src/styles/exit-guard.css
+++ b/src/styles/exit-guard.css
@@ -80,6 +80,11 @@
font-weight: var(--weight-semibold);
}
+.cuda-setup-download {
+ color: var(--accent-bright);
+ text-underline-offset: 3px;
+}
+
.exit-guard__jobs {
max-height: 40vh;
overflow-y: auto;