Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(image-gen): stream diffusion progress during generation, fix dev proxy
Adam Eivy265b723acc07
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6ea96c4e26..e7294ec7d4 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -6,3 +6,8 @@- **CoS Tools Registry** — New onboard tools system (`data/tools/`) that lets CoS agents discover and use instance-specific capabilities like image generation. Tools are exposed in agent prompts via `getToolsSummaryForPrompt()`.- **Character Avatar Generation** — D&D Character Sheet now supports AI-generated avatars via the configured SD API. Hover over the avatar area to generate a new portrait.- **Image serving** — Generated images stored in `data/images/` and served via `/data/images/` static route.+- **Diffusion progress streaming** — Image generation now streams intermediate diffusion steps via Socket.IO. The character avatar shows a live preview of the image forming, a progress bar, and step counter during generation.++## Fixed++- **Avatar images broken in dev mode** — Added `/data` proxy to Vite dev config so generated images load correctly when running `npm run dev`.diff --git a/client/src/pages/CharacterSheet.jsx b/client/src/pages/CharacterSheet.jsxindex bd41224aea..f767643f82 100644--- a/client/src/pages/CharacterSheet.jsx+++ b/client/src/pages/CharacterSheet.jsx@@ -1,4 +1,4 @@-import { useState, useEffect, useCallback } from 'react';+import { useState, useEffect, useCallback, useRef } from 'react';import {Sword, Star, Moon, ScrollText, Shield, Heart,Sparkles, RefreshCw, Dices, X, ChevronDown, Zap, Image@@ -6,6 +6,7 @@ import {import toast from 'react-hot-toast';import { timeAgo } from '../utils/formatters';import { generateAvatar } from '../services/api';+import socket from '../services/socket';const request = async (endpoint, options = {}) => {const response = await fetch(`/api/character${endpoint}`, {@@ -74,6 +75,8 @@ export default function CharacterSheet() {const [classVal, setClassVal] = useState('');const [syncing, setSyncing] = useState(null);const [generatingAvatar, setGeneratingAvatar] = useState(false);+ const [diffusionProgress, setDiffusionProgress] = useState(null);+ const generatingRef = useRef(false);// Form statesconst [dmgDice, setDmgDice] = useState('1d6');@@ -104,6 +107,24 @@ export default function CharacterSheet() {useEffect(() => { load(); }, [load]);+ // Listen for diffusion progress events while generating+ useEffect(() => {+ const onProgress = (data) => {+ if (generatingRef.current) setDiffusionProgress(data);+ };+ const onDone = () => {+ if (generatingRef.current) setDiffusionProgress(null);+ };+ socket.on('image-gen:progress', onProgress);+ socket.on('image-gen:completed', onDone);+ socket.on('image-gen:failed', onDone);+ return () => {+ socket.off('image-gen:progress', onProgress);+ socket.off('image-gen:completed', onDone);+ socket.off('image-gen:failed', onDone);+ };+ }, []);+const toggleAction = (action) => {setActiveAction(prev => prev === action ? null : action);};@@ -192,13 +213,19 @@ export default function CharacterSheet() {const handleGenerateAvatar = () => {setGeneratingAvatar(true);+ setDiffusionProgress(null);+ generatingRef.current = true;generateAvatar({ name: char.name, characterClass: char.class }).then(result => {setChar(prev => ({ ...prev, avatarPath: result.path }));return put({ avatarPath: result.path });}).catch(() => {})- .finally(() => setGeneratingAvatar(false));+ .finally(() => {+ setGeneratingAvatar(false);+ setDiffusionProgress(null);+ generatingRef.current = false;+ });};if (loading) {@@ -250,22 +277,47 @@ export default function CharacterSheet() {{/* Avatar */}<div className="flex-shrink-0"><div className="relative group w-20 h-20 rounded-lg overflow-hidden border border-port-border bg-port-bg">- {char.avatarPath ? (+ {generatingAvatar && diffusionProgress?.currentImage ? (+ <img+ src={`data:image/png;base64,${diffusionProgress.currentImage}`}+ alt="Generating..."+ className="w-full h-full object-cover"+ />+ ) : char.avatarPath ? (<img src={char.avatarPath} alt={char.name} className="w-full h-full object-cover" />) : (<div className="w-full h-full flex items-center justify-center text-gray-600"><Shield className="w-8 h-8" /></div>)}+ {/* Progress bar overlay */}+ {generatingAvatar && (+ <div className="absolute bottom-0 left-0 right-0 h-1.5 bg-black/40">+ <div+ className="h-full bg-port-accent transition-all duration-300"+ style={{ width: `${(diffusionProgress?.progress ?? 0) * 100}%` }}+ />+ </div>+ )}<buttononClick={handleGenerateAvatar}disabled={generatingAvatar}- className="absolute inset-0 flex items-center justify-center bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity"+ className="absolute inset-0 flex items-center justify-center bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity disabled:opacity-0"title="Generate avatar">- {generatingAvatar ? <RefreshCw className="w-5 h-5 text-white animate-spin" /> : <Image className="w-5 h-5 text-white" />}+ <Image className="w-5 h-5 text-white" /></button>+ {generatingAvatar && !diffusionProgress?.currentImage && (+ <div className="absolute inset-0 flex items-center justify-center bg-black/40">+ <RefreshCw className="w-5 h-5 text-white animate-spin" />+ </div>+ )}</div>+ {generatingAvatar && diffusionProgress && (+ <div className="text-[10px] text-gray-500 text-center mt-1">+ {diffusionProgress.step ?? 0}/{diffusionProgress.totalSteps ?? '?'}+ </div>+ )}</div>{/* Name, Class, Level */}diff --git a/client/vite.config.js b/client/vite.config.jsindex 9a47a5c1f3..4d852c85c0 100644--- a/client/vite.config.js+++ b/client/vite.config.js@@ -24,6 +24,10 @@ export default defineConfig(({ mode }) => {target: API_TARGET,changeOrigin: true},+ '/data': {+ target: API_TARGET,+ changeOrigin: true+ },'/socket.io': {target: API_TARGET,changeOrigin: true,diff --git a/server/services/imageGen.js b/server/services/imageGen.jsindex 7622a8d006..c755a4ac96 100644--- a/server/services/imageGen.js+++ b/server/services/imageGen.js@@ -3,6 +3,7 @@** Handles communication with Stable Diffusion API (AUTOMATIC1111 / Forge WebUI).* Generated images are stored in data/images/.+ * Streams diffusion progress via Socket.IO during generation.*/import { writeFile } from 'fs/promises';@@ -11,6 +12,7 @@ import { randomUUID } from 'crypto';import { ensureDir, PATHS } from '../lib/fileUtils.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';import { getSettings } from './settings.js';+import { imageGenEvents } from './imageGenEvents.js';const DEFAULT_NEGATIVE_PROMPT = 'blurry, low quality, distorted, deformed, ugly, watermark, text, signature';@@ -18,6 +20,8 @@ const DEFAULT_NEGATIVE_PROMPT = 'blurry, low quality, distorted, deformed, ugly,let cachedModel = { name: null, timestamp: 0 };const MODEL_CACHE_TTL = 5 * 60 * 1000; // 5 minutes+const PROGRESS_POLL_INTERVAL = 500; // ms between progress polls+async function getSdApiUrl() {const settings = await getSettings();return settings.imageGen?.sdapiUrl || null;@@ -46,6 +50,32 @@ export async function checkConnection() {return { connected: true, model };}+function startProgressPolling(baseUrl, generationId) {+ let lastProgress = -1;+ const interval = setInterval(async () => {+ const res = await fetchWithTimeout(`${baseUrl}/sdapi/v1/progress`, {}, 5000).catch(() => null);+ if (!res?.ok) return;+ const data = await res.json().catch(() => null);+ if (!data) return;++ // Only emit if progress actually changed+ const progress = Math.round(data.progress * 100);+ if (progress === lastProgress) return;+ lastProgress = progress;++ imageGenEvents.emit('progress', {+ generationId,+ progress: data.progress,+ eta: data.eta_relative,+ step: data.state?.sampling_step,+ totalSteps: data.state?.sampling_steps,+ currentImage: data.current_image || null+ });+ }, PROGRESS_POLL_INTERVAL);++ return () => clearInterval(interval);+}+export async function generateImage({ prompt, negativePrompt, width, height, steps, cfgScale, seed }) {const baseUrl = await getSdApiUrl();if (!baseUrl) throw new Error('No SD API URL configured — set it in Settings > Image Gen');@@ -66,32 +96,54 @@ export async function generateImage({ prompt, negativePrompt, width, height, ste...(seed != null && seed >= 0 && { seed })};- console.log(`🎨 Generating image: ${prompt.slice(0, 80)}... (${payload.width}x${payload.height}, ${payload.steps} steps)`);+ const generationId = randomUUID();+ console.log(`🎨 Generating image [${generationId.slice(0, 8)}]: ${prompt.slice(0, 80)}... (${payload.width}x${payload.height}, ${payload.steps} steps)`);++ imageGenEvents.emit('started', {+ generationId,+ prompt: prompt.slice(0, 200),+ totalSteps: payload.steps+ });- const res = await fetchWithTimeout(- `${baseUrl}/sdapi/v1/txt2img`,- {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify(payload)- },- 300000- );+ // Start polling progress in background+ const stopPolling = startProgressPolling(baseUrl, generationId);++ let res;+ try {+ res = await fetchWithTimeout(+ `${baseUrl}/sdapi/v1/txt2img`,+ {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload)+ },+ 300000+ );+ } finally {+ stopPolling();+ }if (!res.ok) {const errBody = await res.text().catch(() => '');+ imageGenEvents.emit('failed', { generationId, error: `SD API error ${res.status}` });throw new Error(`SD API error ${res.status}: ${errBody.slice(0, 200)}`);}const data = await res.json();- if (!data.images?.length) throw new Error('SD API returned no images');+ if (!data.images?.length) {+ imageGenEvents.emit('failed', { generationId, error: 'No images returned' });+ throw new Error('SD API returned no images');+ }await ensureDir(PATHS.images);const filename = `${randomUUID()}.png`;await writeFile(join(PATHS.images, filename), Buffer.from(data.images[0], 'base64'));+ const path = `/data/images/${filename}`;console.log(`🖼️ Image saved: ${filename}`);- return { filename, path: `/data/images/${filename}` };++ imageGenEvents.emit('completed', { generationId, path, filename });+ return { generationId, filename, path };}export async function generateAvatar({ name, characterClass, prompt }) {diff --git a/server/services/imageGenEvents.js b/server/services/imageGenEvents.jsnew file mode 100644index 0000000000..2307c0dbd5--- /dev/null+++ b/server/services/imageGenEvents.js@@ -0,0 +1,3 @@+import { EventEmitter } from 'events';++export const imageGenEvents = new EventEmitter();diff --git a/server/services/socket.js b/server/services/socket.jsindex eb40b9d7c6..a48e8c0c03 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -18,6 +18,7 @@ import { queueEvents } from './moltworldQueue.js';import { instanceEvents } from './instanceEvents.js';import { reviewEvents } from './review.js';import { loopEvents } from './loops.js';+import { imageGenEvents } from './imageGenEvents.js';import * as shellService from './shell.js';import {validateSocketData,@@ -499,6 +500,9 @@ export function initSocket(io) {// Set up loop event forwardingsetupLoopEventForwarding();++ // Set up image generation event forwarding+ setupImageGenEventForwarding();}function cleanupStream(socketId) {@@ -756,3 +760,22 @@ function setupLoopEventForwarding() {loopEvents.on('iteration:error', (data) => broadcastToLoops('loop:iteration:error', data));loopEvents.on('output', (data) => broadcastToLoops('loop:output', data));}++// Set up image generation event forwarding — broadcast to all clients+let imageGenForwardingSetup = false;+function setupImageGenEventForwarding() {+ if (imageGenForwardingSetup) return;+ imageGenForwardingSetup = true;+ imageGenEvents.on('started', (data) => {+ if (ioInstance) ioInstance.emit('image-gen:started', data);+ });+ imageGenEvents.on('progress', (data) => {+ if (ioInstance) ioInstance.emit('image-gen:progress', data);+ });+ imageGenEvents.on('completed', (data) => {+ if (ioInstance) ioInstance.emit('image-gen:completed', data);+ });+ imageGenEvents.on('failed', (data) => {+ if (ioInstance) ioInstance.emit('image-gen:failed', data);+ });+}