Skip to content

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

refactor(image-gen): simplify after code review

Adam Eivy685a6af41c53
diff --git a/client/src/pages/CharacterSheet.jsx b/client/src/pages/CharacterSheet.jsx
index dfff5f74a3..bd41224aea 100644
--- a/client/src/pages/CharacterSheet.jsx
+++ b/client/src/pages/CharacterSheet.jsx
@@ -5,6 +5,7 @@ import {
} from 'lucide-react';
import toast from 'react-hot-toast';
import { timeAgo } from '../utils/formatters';
+import { generateAvatar } from '../services/api';
const request = async (endpoint, options = {}) => {
const response = await fetch(`/api/character${endpoint}`, {
@@ -191,19 +192,12 @@ export default function CharacterSheet() {
const handleGenerateAvatar = () => {
setGeneratingAvatar(true);
- fetch('/api/image-gen/avatar', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ name: char.name, characterClass: char.class })
- })
- .then(res => res.ok ? res.json() : res.json().then(e => Promise.reject(new Error(e.error))))
+ generateAvatar({ name: char.name, characterClass: char.class })
.then(result => {
- const updated = { ...char, avatarPath: result.path };
- setChar(updated);
+ setChar(prev => ({ ...prev, avatarPath: result.path }));
return put({ avatarPath: result.path });
})
- .then(() => toast.success('Avatar generated'))
- .catch(err => toast.error(err.message || 'Failed to generate avatar'))
+ .catch(() => {})
.finally(() => setGeneratingAvatar(false));
};
diff --git a/client/src/pages/Settings.jsx b/client/src/pages/Settings.jsx
index 1b5b22d6d2..924fc4d477 100644
--- a/client/src/pages/Settings.jsx
+++ b/client/src/pages/Settings.jsx
@@ -869,20 +869,21 @@ function GeneralTab() {
);
}
+const SDAPI_TOOL_ID = 'sdapi';
+
function ImageGenTab() {
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [sdapiUrl, setSdapiUrl] = useState('');
const [status, setStatus] = useState(null);
const [checking, setChecking] = useState(false);
- const [toolId, setToolId] = useState(null);
+ const [toolRegistered, setToolRegistered] = useState(false);
useEffect(() => {
Promise.all([getSettings(), getToolsList()])
.then(([settings, tools]) => {
setSdapiUrl(settings?.imageGen?.sdapiUrl || '');
- const sdTool = tools.find(t => t.category === 'image-generation' && t.name === 'Stable Diffusion');
- if (sdTool) setToolId(sdTool.id);
+ setToolRegistered(tools.some(t => t.id === SDAPI_TOOL_ID));
})
.catch(() => toast.error('Failed to load image gen settings'))
.finally(() => setLoading(false));
@@ -905,23 +906,20 @@ function ImageGenTab() {
.catch(() => toast.error('Failed to save settings'));
// Register or update the tool in the CoS tools registry
- if (url) {
- const toolData = {
- name: 'Stable Diffusion',
- category: 'image-generation',
- description: 'Generate images via Stable Diffusion API (AUTOMATIC1111 / Forge WebUI)',
- enabled: true,
- config: { sdapiUrl: url },
- promptHints: 'Use POST /api/image-gen/generate with { prompt, negativePrompt, width, height, steps, cfgScale }. Use POST /api/image-gen/avatar for character portraits.'
- };
- if (toolId) {
- await updateTool(toolId, toolData).catch(() => {});
- } else {
- const created = await registerTool({ id: 'sdapi', ...toolData }).catch(() => null);
- if (created) setToolId(created.id);
- }
- } else if (toolId) {
- await updateTool(toolId, { enabled: false }).catch(() => {});
+ const toolData = {
+ name: 'Stable Diffusion',
+ category: 'image-generation',
+ description: 'Generate images via Stable Diffusion API (AUTOMATIC1111 / Forge WebUI)',
+ enabled: !!url,
+ config: { sdapiUrl: url },
+ promptHints: 'Use POST /api/image-gen/generate with { prompt, negativePrompt, width, height, steps, cfgScale }. Use POST /api/image-gen/avatar for character portraits.'
+ };
+ if (toolRegistered) {
+ await updateTool(SDAPI_TOOL_ID, toolData).catch(() => {});
+ } else if (url) {
+ await registerTool({ id: SDAPI_TOOL_ID, ...toolData })
+ .then(() => setToolRegistered(true))
+ .catch(() => {});
}
setSaving(false);
@@ -983,10 +981,10 @@ function ImageGenTab() {
When configured, this tool is registered with the CoS tools registry. Agents can use it to generate
images for briefings, character avatars, and other visual content. Images are stored in <code className="text-gray-400">./data/images/</code>.
</p>
- {toolId && (
+ {toolRegistered && (
<div className="flex items-center gap-2 text-xs text-port-success">
<Wrench size={12} />
- Registered as CoS tool (ID: {toolId})
+ Registered as CoS tool
</div>
)}
</div>
diff --git a/server/services/imageGen.js b/server/services/imageGen.js
index 4dcc83a96f..7622a8d006 100644
--- a/server/services/imageGen.js
+++ b/server/services/imageGen.js
@@ -12,36 +12,50 @@ import { ensureDir, PATHS } from '../lib/fileUtils.js';
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';
import { getSettings } from './settings.js';
+const DEFAULT_NEGATIVE_PROMPT = 'blurry, low quality, distorted, deformed, ugly, watermark, text, signature';
+
+// Cache detected model to avoid extra HTTP round-trip per generation
+let cachedModel = { name: null, timestamp: 0 };
+const MODEL_CACHE_TTL = 5 * 60 * 1000; // 5 minutes
+
async function getSdApiUrl() {
const settings = await getSettings();
return settings.imageGen?.sdapiUrl || null;
}
+async function detectModel(baseUrl) {
+ if (cachedModel.name && Date.now() - cachedModel.timestamp < MODEL_CACHE_TTL) {
+ return cachedModel.name;
+ }
+ const res = await fetchWithTimeout(`${baseUrl}/sdapi/v1/options`, {}, 10000).catch(() => null);
+ if (!res?.ok) return 'unknown';
+ const options = await res.json().catch(() => null);
+ const model = options?.sd_model_checkpoint || 'unknown';
+ cachedModel = { name: model, timestamp: Date.now() };
+ return model;
+}
+
export async function checkConnection() {
const baseUrl = await getSdApiUrl();
if (!baseUrl) return { connected: false, reason: 'No SD API URL configured' };
- const res = await fetchWithTimeout(`${baseUrl}/sdapi/v1/options`, {}, 10000).catch(() => null);
- if (!res?.ok) return { connected: false, reason: 'SD API unreachable' };
-
- const options = await res.json().catch(() => null);
- return {
- connected: true,
- model: options?.sd_model_checkpoint || 'unknown'
- };
+ const model = await detectModel(baseUrl);
+ if (model === 'unknown' && !cachedModel.timestamp) {
+ return { connected: false, reason: 'SD API unreachable' };
+ }
+ return { connected: true, model };
}
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');
- // Auto-detect model for Flux-specific parameters
- const status = await checkConnection();
- const isFlux = status.model?.toLowerCase().includes('flux');
+ const model = await detectModel(baseUrl);
+ const isFlux = model?.toLowerCase().includes('flux');
const payload = {
prompt,
- negative_prompt: negativePrompt || 'blurry, low quality, distorted, deformed, ugly, watermark, text, signature',
+ negative_prompt: negativePrompt || DEFAULT_NEGATIVE_PROMPT,
steps: steps || (isFlux ? 15 : 25),
width: width || (isFlux ? 832 : 512),
height: height || (isFlux ? 1216 : 768),
@@ -61,7 +75,7 @@ export async function generateImage({ prompt, negativePrompt, width, height, ste
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
},
- 300000 // 5 min timeout for generation
+ 300000
);
if (!res.ok) {
@@ -72,11 +86,9 @@ export async function generateImage({ prompt, negativePrompt, width, height, ste
const data = await res.json();
if (!data.images?.length) throw new Error('SD API returned no images');
- // Save base64 image to disk
await ensureDir(PATHS.images);
const filename = `${randomUUID()}.png`;
- const filePath = join(PATHS.images, filename);
- await writeFile(filePath, Buffer.from(data.images[0], 'base64'));
+ await writeFile(join(PATHS.images, filename), Buffer.from(data.images[0], 'base64'));
console.log(`🖼️ Image saved: ${filename}`);
return { filename, path: `/data/images/${filename}` };
@@ -88,6 +100,6 @@ export async function generateAvatar({ name, characterClass, prompt }) {
prompt: prompt || defaultPrompt,
width: 512,
height: 512,
- negativePrompt: 'blurry, low quality, distorted, deformed, ugly, watermark, text, signature, nude, nsfw'
+ negativePrompt: `${DEFAULT_NEGATIVE_PROMPT}, nude, nsfw`
});
}
diff --git a/server/services/tools.js b/server/services/tools.js
index 1eb3563ff6..56cac41ba6 100644
--- a/server/services/tools.js
+++ b/server/services/tools.js
@@ -3,30 +3,39 @@
*
* Manages onboard tools (image generation, etc.) that CoS agents can discover and use.
* Tools are stored as individual JSON files in data/tools/.
+ * In-memory cache avoids disk I/O on hot paths (agent spawning).
*/
-import { readFile, writeFile, readdir, unlink } from 'fs/promises';
+import { writeFile, readdir, unlink } from 'fs/promises';
import { join } from 'path';
import { randomUUID } from 'crypto';
-import { ensureDir, PATHS } from '../lib/fileUtils.js';
+import { ensureDir, readJSONFile, PATHS } from '../lib/fileUtils.js';
const toolPath = (id) => join(PATHS.tools, `${id}.json`);
-export async function getTools() {
+let cache = null;
+
+async function loadAll() {
await ensureDir(PATHS.tools);
const files = await readdir(PATHS.tools);
const tools = [];
for (const f of files) {
if (!f.endsWith('.json')) continue;
- const raw = await readFile(join(PATHS.tools, f), 'utf-8').catch(() => null);
- if (raw) tools.push(JSON.parse(raw));
+ const data = await readJSONFile(join(PATHS.tools, f), null);
+ if (data) tools.push(data);
}
+ cache = tools;
return tools;
}
+function invalidateCache() { cache = null; }
+
+export async function getTools() {
+ return cache || loadAll();
+}
+
export async function getTool(id) {
- const raw = await readFile(toolPath(id), 'utf-8').catch(() => null);
- return raw ? JSON.parse(raw) : null;
+ return readJSONFile(toolPath(id), null);
}
export async function getEnabledTools() {
@@ -34,11 +43,6 @@ export async function getEnabledTools() {
return all.filter(t => t.enabled);
}
-export async function getToolsByCategory(category) {
- const all = await getTools();
- return all.filter(t => t.category === category);
-}
-
export async function registerTool(config) {
await ensureDir(PATHS.tools);
const now = new Date().toISOString();
@@ -54,6 +58,7 @@ export async function registerTool(config) {
updatedAt: now
};
await writeFile(toolPath(tool.id), JSON.stringify(tool, null, 2) + '\n');
+ invalidateCache();
console.log(`🔧 Tool registered: ${tool.name} (${tool.id})`);
return tool;
}
@@ -64,26 +69,27 @@ export async function updateTool(id, updates) {
const merged = {
...existing,
...updates,
- id, // prevent id override
+ id,
updatedAt: new Date().toISOString()
};
await writeFile(toolPath(id), JSON.stringify(merged, null, 2) + '\n');
+ invalidateCache();
console.log(`🔧 Tool updated: ${merged.name} (${id})`);
return merged;
}
export async function deleteTool(id) {
await unlink(toolPath(id)).catch(() => null);
+ invalidateCache();
console.log(`🗑️ Tool deleted: ${id}`);
}
-export function getToolsSummaryForPrompt() {
- return getEnabledTools().then(tools => {
- if (tools.length === 0) return '';
- const lines = tools.map(t => {
- const hint = t.promptHints ? ` — ${t.promptHints}` : '';
- return `- **${t.name}** (${t.category}): ${t.description}${hint}`;
- });
- return `## Available Tools\nThe following onboard tools are available for this instance:\n\n${lines.join('\n')}\n`;
+export async function getToolsSummaryForPrompt() {
+ const tools = await getEnabledTools();
+ if (tools.length === 0) return '';
+ const lines = tools.map(t => {
+ const hint = t.promptHints ? ` — ${t.promptHints}` : '';
+ return `- **${t.name}** (${t.category}): ${t.description}${hint}`;
});
+ return `## Available Tools\nThe following onboard tools are available for this instance:\n\n${lines.join('\n')}\n`;
}