Compare commits

..

No commits in common. "main" and "v2.0.0" have entirely different histories.
main ... v2.0.0

57 changed files with 462 additions and 8216 deletions

8
.gitignore vendored
View file

@ -7,12 +7,8 @@ dist/
# Electron packaged installers
release/
# Local database and assets (Portable Data).
# Leading slash ANCHORS this to the repo root. Unanchored, `data/` matches a
# directory named "data" at ANY depth — which silently excluded the whole
# thirdparty/skintokens/src/data package from the repo, so a fresh clone could
# not import rig.py at all ("No module named 'src.data'").
/data/
# Local database and assets (Portable Data)
data/
# Wiki author mode — presence of this file unlocks editing the Wiki.
# Kept local (never synced) so the published docs are read-only for end users.

View file

@ -19,9 +19,6 @@
| Date | Description |
| --- | --- |
| **2026-07-28** | Fixed Desktop App on Linux<br>ComfyUI: Added Enums<br>Wireframe mode in Mesh Previewer |
| **2026-07-27** | ComfyUI: Custom models folder<br>Mesh Export: Save last output folder<br>DB: Fixed assets linked to a project<br>Kanban: Can add more meshes and images from any column<br>Desktop App: Fixed Graph page slowness |
| **2026-07-23** | Added Brainstorming Boards |
| **2026-07-20** | MCP Server<br>Graph Page: Added Reorganize button<br>Graph Page: Save the last position and zoom level<br>Graph Page: Simplified Image Node Actions<br>Desktop App: Fixed Wiki<br>Desktop App: Auto-start python services in Settings<br>3D Mesh: Thumbnail is now generated by mesh-tools (python) |
| **2026-07-16** | Mesh Preview: FBX Export (Unity, Unreal Engine)<br>Graph Page: Can import a mesh directly from the computer<br>Kanban board: Added Rigging column |
| **2026-07-15** | MeshEditor: Auto Rig with Skintokens<br>Fixed Desktop App Setup |
@ -212,7 +209,7 @@ Open the application and configure your services in the settings area:
## Documentation
A complete Wiki is included with the application.
You will find some documentation here: https://github.com/visualbruno/3DGenStudio/tree/main/docs
---
@ -222,7 +219,6 @@ A complete Wiki is included with the application.
- [**SkinTokens**](https://github.com/VAST-AI-Research/SkinTokens) — used in **Auto Rig** for AI-powered skeleton generation and skinning.
- [**mesh2motion-app**](https://github.com/Mesh2Motion/mesh2motion-app) — used in **Auto Rig** for skeleton/animation reference.
- [**excalidraw**](https://github.com/excalidraw/excalidraw) — used for Brainstorming Boards.
---

View file

@ -41,9 +41,6 @@ files:
- package.json
- dist/**/*
- electron/**/*
# App icon shown on the splash/setup windows (electron/splash.html loads it
# from disk, so it must ship even though dist/ has its own copy).
- public/favicon.png
- comfyui_workflows/**/*
- setup/**/*
- tools/**/*

View file

@ -10,10 +10,7 @@
// - Mesh Tools (python-server): always provisioned. CPU only.
// - Rigging (skintokens): opt-in. Heavy (torch + flash-attn + model) and needs
// an NVIDIA GPU; the setup reuses the service's own Python helpers
// (select_flash_attn.py / download_wheel.py / download.py). Windows and Linux
// only — flash-attn comes from a prebuilt wheel curated PER PLATFORM
// (flash_attention_windows.txt / flash_attention_linux.txt) because building
// it from source takes ~an hour either way. macOS has no CUDA and is refused.
// (select_flash_attn.py / download_wheel.py / download.py).
//
// Everything is async and streams output to an onProgress callback; nothing
// blocks the Electron main-process event loop.
@ -24,7 +21,6 @@ const os = require('node:os');
const { spawn, spawnSync } = require('node:child_process');
const IS_WIN = process.platform === 'win32';
const IS_MAC = process.platform === 'darwin';
const PYVER = '3.13';
const UV_EXE = IS_WIN ? 'uv.exe' : 'uv';
@ -196,11 +192,6 @@ async function setupPythonServer({ uv, serviceDir, venvDir, onProgress }) {
// downloaded there; rig_server.py chdirs to this same dir at launch (via
// RIGTOOLS_DATA_DIR) so its relative weight lookups resolve here.
async function setupSkintokens({ uv, serviceDir, venvDir, dataDir, onProgress }) {
// Rigging needs an NVIDIA GPU. Say so up front rather than failing several GB
// into a torch install that has no macOS CUDA build to find.
if (IS_MAC) {
throw new Error('Rigging (Auto Rig) needs an NVIDIA GPU (CUDA), which macOS does not provide. The rest of the app works normally.');
}
const vp = venvPython(venvDir);
const env = process.env;
const modelDir = dataDir || serviceDir;
@ -223,9 +214,6 @@ async function setupSkintokens({ uv, serviceDir, venvDir, dataDir, onProgress })
], (e) => onProgress(scaled(e, 0, 0.4)));
// Select the flash-attn wheel + matching torch for this machine's CUDA.
// select_flash_attn.py picks the table for THIS platform (win_amd64 wheels from
// flash_attention_windows.txt, linux_x86_64 from flash_attention_linux.txt) —
// a wheel from the wrong table is rejected outright by uv at install time.
onProgress({ kind: 'phase', phase: 'Selecting CUDA build', pct: 0.4 });
const sel = await runStream(vp, ['select_flash_attn.py'], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
let wheel = null, torchArgs = null;
@ -234,39 +222,29 @@ async function setupSkintokens({ uv, serviceDir, venvDir, dataDir, onProgress })
else if (line.startsWith('TORCHARGS=')) torchArgs = line.slice(10).trim();
}
// No match -> no rigging. Bail BEFORE the torch download: flash-attn is a hard
// requirement (src/model/tokenrig.py imports it unguarded, so the service cannot
// even load without it), and building it from source takes ~an hour on every
// platform. Pulling multi-GB of torch on the way to a certain failure is waste.
if (!wheel || !torchArgs) {
throw new Error('No prebuilt flash-attn wheel matched this GPU/CUDA (see details). Rigging is unavailable on this machine.');
}
// Install torch with the curated per-wheel command, ABI-matched to the wheel.
// Install torch (curated per-wheel command, or a sane default).
onProgress({ kind: 'phase', phase: 'Installing PyTorch', pct: 0.45 });
const torchInstall = torchArgs
? torchArgs.split(/\s+/)
: ['torch==2.7.0', 'torchvision==0.22.0', 'torchaudio==2.7.0', '--index-url', 'https://download.pytorch.org/whl/cu128'];
{
const r = await runStream(uv, ['pip', 'install', '--python', vp, ...torchArgs.split(/\s+/)], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
const r = await runStream(uv, ['pip', 'install', '--python', vp, ...torchInstall], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
if (r.code !== 0) throw new Error(`PyTorch install failed (exit ${r.code}).`);
}
// flash-attn — download the prebuilt wheel first (Hugging Face Xet URLs 403 for
// pip and need the HF client; GitHub release assets are plain URLs), install it,
// then PROVE it loads: a wheel built against a different torch ABI installs
// cleanly and only dies at `import flash_attn` with `undefined symbol: _ZN3c10…`.
// Catching that here beats surfacing it after the multi-GB checkpoint download.
onProgress({ kind: 'phase', phase: 'Installing flash-attn', pct: 0.6 });
{
// flash-attn — download the prebuilt wheel via the HF client, then install it.
if (wheel) {
onProgress({ kind: 'phase', phase: 'Installing flash-attn', pct: 0.65 });
const dl = await runStream(vp, ['download_wheel.py', wheel], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
const localWheel = dl.stdout.split(/\r?\n/).map((s) => s.trim()).filter(Boolean).pop();
if (dl.code !== 0 || !localWheel) throw new Error('flash-attn download failed. Rigging cannot start without it.');
const r = await runStream(uv, ['pip', 'install', '--python', vp, localWheel], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
if (r.code !== 0) throw new Error('flash-attn install failed. Rigging cannot start without it.');
}
onProgress({ kind: 'phase', phase: 'Verifying flash-attn', pct: 0.72 });
{
const probe = 'import torch, flash_attn; print("flash_attn", flash_attn.__version__, "/ torch", torch.__version__)';
const r = await runStream(vp, ['-c', probe], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
if (r.code !== 0) throw new Error('flash-attn installed but will not import — most likely a torch ABI mismatch with the selected wheel (see details). Rigging cannot start.');
if (dl.code === 0 && localWheel) {
const r = await runStream(uv, ['pip', 'install', '--python', vp, localWheel], { cwd: serviceDir, env, onLine: (t) => onProgress({ kind: 'log', text: t }) });
if (r.code !== 0) throw new Error('flash-attn install failed. Rigging cannot start without it.');
} else {
throw new Error('flash-attn download failed. Rigging cannot start without it.');
}
} else {
throw new Error('No prebuilt flash-attn wheel matched this GPU/CUDA. Rigging is unavailable.');
}
// Model checkpoints (large; downloaded into the WRITABLE data dir).

View file

@ -83,7 +83,7 @@
<span class="svc__name">Rigging (Auto Rig)</span>
<span class="svc__tag">optional · NVIDIA GPU, large download</span>
</div>
<label class="opt"><input type="checkbox" id="opt-rigging" /> Install the AI rigging service (needs an NVIDIA GPU ≥14 GB with a recent driver — CUDA 12.8+; downloads several GB)</label>
<label class="opt"><input type="checkbox" id="opt-rigging" /> Install the AI rigging service (needs an NVIDIA GPU ≥14 GB; downloads several GB)</label>
<div class="svc__phase" style="display:none"></div>
<div class="bar" style="display:none"><i></i></div>
</div>
@ -109,13 +109,6 @@
const logEl = $('#log');
const errEl = $('#err');
// Rigging needs CUDA, so it exists on Windows and Linux only. Hide the option on
// macOS rather than offering an install that cannot succeed. (An unchecked box
// reads as false in runInstall, so nothing else needs to know.)
if ((window.genStudioDesktop && window.genStudioDesktop.platform) === 'darwin') {
$('#svc-rigging').style.display = 'none';
}
function setRow(service, { state, phase, pct }) {
const row = rows[service];
if (!row) return;

View file

@ -52,13 +52,6 @@
box-shadow: 0 0 22px rgba(124,92,255,0.55);
display: flex; align-items: center; justify-content: center;
font-size: 22px;
overflow: hidden;
}
/* App icon fills the orb; if the file is missing the emoji underneath shows. */
.orb img {
position: absolute; inset: 0; width: 100%; height: 100%;
object-fit: cover; border-radius: 50%;
-webkit-user-drag: none;
}
.title {
font-size: 26px; font-weight: 700; letter-spacing: .3px;
@ -75,7 +68,7 @@
<div class="glow"></div>
<div class="mark">
<div class="ring"></div>
<div class="orb">🌌<img src="../public/favicon.png" alt="" onerror="this.remove()" /></div>
<div class="orb">🌌</div>
</div>
<div class="title">3D Gen Studio</div>
<div class="status">Starting local services<span class="dots"></span></div>

View file

@ -49,15 +49,10 @@ export function registerAssetTools(server, { api, notifyMutation }) {
server.registerTool('list_assets', {
title: 'List project assets',
description: 'List a project\'s assets (images, meshes, workflows) with their version/edit trees and direct download URLs.',
inputSchema: {
projectId: z.number().int(),
includeChildren: z.boolean().optional().describe('Also return every project-linked edit/version as a top-level entry, not only nested under its root.')
},
inputSchema: { projectId: z.number().int() },
annotations: { readOnlyHint: true }
}, toolHandler(async ({ projectId, includeChildren }) => {
const assets = await api.apiJson('GET', '/assets', {
query: { projectId, ...(includeChildren ? { includeChildren: 'true' } : {}) }
});
}, toolHandler(async ({ projectId }) => {
const assets = await api.apiJson('GET', '/assets', { query: { projectId } });
return (Array.isArray(assets) ? assets : []).map(asset => withAssetUrls(api, asset));
}));
@ -106,48 +101,22 @@ export function registerAssetTools(server, { api, notifyMutation }) {
server.registerTool('link_asset', {
title: 'Link existing asset',
description: 'Attach an existing asset to a project. Pass assetId to link an asset that is already in the database — this works for a root asset AND for an image edit or mesh version (use the child id from list_assets). Pass filename instead to link a stored file from the asset library.',
description: 'Attach an already-stored asset file (by its stored filename) to a project — creates the card/link without re-uploading.',
inputSchema: {
projectId: z.number().int(),
assetId: z.number().int().optional().describe('Asset id to link — root, image edit or mesh version. Preferred over filename.'),
filename: z.string().min(1).optional().describe('Stored asset filename (from list_library_assets). Used when assetId is not given.'),
filename: z.string().min(1).describe('Stored asset filename (from list_library_assets)'),
type: z.enum(['image', 'mesh']).default('image'),
name: z.string().optional(),
metadata: z.record(z.string(), z.any()).optional(),
cascadeChildren: z.boolean().optional().describe('With assetId: also link every edit/version of that asset.')
metadata: z.record(z.string(), z.any()).optional()
}
}, toolHandler(async ({ projectId, assetId, filename, type, name, metadata, cascadeChildren }) => {
if (assetId === undefined && !filename) {
throw new Error('Pass either assetId or filename.');
}
const asset = assetId !== undefined
? await api.apiJson('POST', `/projects/${projectId}/assets`, {
body: { assetId, ...(cascadeChildren ? { cascadeChildren: true } : {}) }
})
: await api.apiJson('POST', '/assets/link', {
body: { projectId, filename, type, ...(name ? { name } : {}), ...(metadata ? { metadata } : {}) }
});
}, toolHandler(async ({ projectId, filename, type, name, metadata }) => {
const asset = await api.apiJson('POST', '/assets/link', {
body: { projectId, filename, type, ...(name ? { name } : {}), ...(metadata ? { metadata } : {}) }
});
notifyMutation(projectId);
return withAssetUrls(api, asset);
}));
server.registerTool('unlink_asset', {
title: 'Unlink asset from project',
description: 'Remove an asset from a project without deleting the file or the library record. Also removes it from any card/node it sits on in that project.',
inputSchema: {
projectId: z.number().int(),
assetId: z.number().int().describe('Asset id — root, image edit or mesh version'),
cascadeChildren: z.boolean().default(true).describe('Also unlink every edit/version of that asset.')
}
}, toolHandler(async ({ projectId, assetId, cascadeChildren }) => {
const query = cascadeChildren === false ? { cascadeChildren: 'false' } : {};
const result = await api.apiJson('DELETE', `/projects/${projectId}/assets/${assetId}`, { query });
notifyMutation(projectId);
return result;
}));
server.registerTool('view_asset', {
title: 'View asset (image)',
description: 'SEE a project asset: returns the actual image so it can be visually inspected. For image assets returns the image itself; for meshes returns the thumbnail preview when one exists. Use this after generating images to check the results. For raw file access use download_asset.',

View file

@ -31,7 +31,7 @@ async function resolveWorkflowJson({ workflowJson, filePath }) {
export function registerWorkflowTools(server, { api, notifyMutation }) {
server.registerTool('list_workflows', {
title: 'List ComfyUI workflows',
description: 'List the ComfyUI workflows saved in the library, with their configured parameters (inputs the caller can set, each with id/name/valueType/defaultValue, plus enums when the parameter only accepts a fixed list of values) and output nodes.',
description: 'List the ComfyUI workflows saved in the library, with their configured parameters (inputs the caller can set, each with id/name/valueType/defaultValue) and output nodes.',
annotations: { readOnlyHint: true }
}, toolHandler(async () => {
const workflows = await api.apiJson('GET', '/library/comfy-workflows');
@ -58,7 +58,7 @@ export function registerWorkflowTools(server, { api, notifyMutation }) {
server.registerTool('import_workflow', {
title: 'Import ComfyUI workflow',
description: 'Save a ComfyUI workflow into the library. parameters selects which inspected inputs become runtime parameters ({id, name?, valueType?: image|mesh|video|string|number|boolean, enums?: allowed values for a string/number parameter}); outputs selects which terminal nodes\' results are saved ({nodeId, name?}). At least one output is required. When importing a .3dgw share bundle via filePath, the bundled parameter/output configuration is used automatically unless overridden.',
description: 'Save a ComfyUI workflow into the library. parameters selects which inspected inputs become runtime parameters ({id, name?, valueType?: image|mesh|video|string|number|boolean}); outputs selects which terminal nodes\' results are saved ({nodeId, name?}). At least one output is required. When importing a .3dgw share bundle via filePath, the bundled parameter/output configuration is used automatically unless overridden.',
inputSchema: {
name: z.string().min(1).describe('Workflow name in the library'),
workflowJson: z.any().optional().describe('ComfyUI API-format graph JSON (object or string)'),
@ -66,9 +66,7 @@ export function registerWorkflowTools(server, { api, notifyMutation }) {
parameters: z.array(z.object({
id: z.string(),
name: z.string().optional(),
valueType: z.string().optional(),
enums: z.array(z.union([z.string(), z.number()])).optional()
.describe('Allowed values for a string/number parameter — the app renders it as a dropdown limited to this list. Ignored for other value types.')
valueType: z.string().optional()
})).optional().describe('Inputs to expose as parameters (ids from inspect_workflow)'),
outputs: z.array(z.object({
nodeId: z.string(),

2457
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,7 +1,7 @@
{
"name": "app",
"private": true,
"version": "2.1.2",
"version": "2.0.0",
"type": "module",
"main": "electron/main.cjs",
"description": "AI-powered 3D mesh production studio — image generation, mesh generation, UV unwrapping, and texturing pipelines.",
@ -27,7 +27,6 @@
"dist:dir": "npm run build && electron-builder --dir"
},
"dependencies": {
"@excalidraw/excalidraw": "^0.18.1",
"@modelcontextprotocol/sdk": "^1.29.0",
"@react-three/drei": "^10.7.7",
"@react-three/fiber": "^9.5.0",

344
server.js
View file

@ -45,12 +45,6 @@ import {
deleteAssetById,
deleteProjectConnection,
deleteProjectNode,
deleteBoard,
listProjectBoards,
getBoardById,
createBoard,
updateBoard,
resolveEditableSourceReference,
deleteLibraryAssetByFilePath,
deleteProjectById,
findLibraryAssetByFilePath,
@ -65,8 +59,6 @@ import {
getWorkflowRecordById,
initializeStorage,
listLibraryAssetsByType,
linkExistingAssetToProject,
unlinkAssetFromProjectById,
listProjectAssets,
listProjectTasks,
listProjects,
@ -374,13 +366,10 @@ app.post('/api/library/comfy-workflows', async (req, res) => {
throw new Error(`Unknown workflow parameter: ${parameter.id}`);
}
const valueType = normalizeComfyValueType(parameter.valueType, getDefaultComfyValueType(sourceParameter));
return {
...sourceParameter,
name: sanitizeDisplayName(parameter.name || sourceParameter.name, sourceParameter.name),
valueType,
enums: normalizeComfyEnums(parameter.enums, valueType)
valueType: normalizeComfyValueType(parameter.valueType, getDefaultComfyValueType(sourceParameter))
};
});
@ -458,20 +447,10 @@ app.put('/api/library/comfy-workflows/:id', async (req, res) => {
defaultValue = cloneSerializable(sourceParameter.defaultValue);
}
const valueType = normalizeComfyValueType(parameter.valueType, getDefaultComfyValueType(sourceParameter));
// Same rule as defaultValue: an incoming list wins (including an empty one,
// which clears the enums), otherwise keep whatever was stored — callers such
// as "Set as default" send a minimal parameter list and must not wipe it.
const enums = Object.prototype.hasOwnProperty.call(parameter, 'enums')
? normalizeComfyEnums(parameter.enums, valueType)
: normalizeComfyEnums(storedParameter?.enums, valueType);
return {
...sourceParameter,
name: sanitizeDisplayName(parameter.name || sourceParameter.name, sourceParameter.name),
valueType,
enums,
valueType: normalizeComfyValueType(parameter.valueType, getDefaultComfyValueType(sourceParameter)),
defaultValue
};
});
@ -878,33 +857,6 @@ function normalizeComfyValueType(value, fallback = 'string') {
return ['string', 'number', 'boolean', 'image', 'video', 'mesh'].includes(value) ? value : fallback;
}
// Enums restrict a String / Number parameter to a fixed list of allowed values,
// which the UI renders as a dropdown. Entries are coerced to the parameter's value
// type and de-duplicated; a non-String/Number parameter never keeps a list.
// Returns undefined when there is nothing to store (JSON.stringify drops the key).
function normalizeComfyEnums(rawEnums, valueType) {
if (!Array.isArray(rawEnums) || !['string', 'number'].includes(valueType)) return undefined;
const values = [];
for (const entry of rawEnums) {
if (entry === null || entry === undefined || typeof entry === 'boolean' || typeof entry === 'object') continue;
if (valueType === 'number') {
const numericValue = Number(entry);
if (!Number.isFinite(numericValue) || values.includes(numericValue)) continue;
values.push(numericValue);
continue;
}
const textValue = String(entry).trim();
if (!textValue || values.includes(textValue)) continue;
values.push(textValue);
}
return values.length > 0 ? values : undefined;
}
function getComfyNodeLabel(nodeId, node = {}) {
return sanitizeDisplayName(node._meta?.title || node.title || node.class_type || `Node ${nodeId}`, `Node ${nodeId}`);
}
@ -1481,7 +1433,7 @@ async function sleep(ms) {
async function queueComfyPrompt(baseUrl, workflowJson, identifiers = {}) {
const clientId = String(identifiers?.clientId || '').trim() || randomUUID();
const promptId = randomUUID(); // patched 2026-07-30: ComfyUI now enforces UUID prompt_id, client-supplied ids can be non-UUID and get rejected
const promptId = String(identifiers?.promptId || '').trim() || randomUUID();
const response = await fetch(`${baseUrl}/prompt`, {
method: 'POST',
headers: {
@ -2846,7 +2798,7 @@ async function saveGeneratedMeshAssets({
// When the mesh was edited from a connected mesh, save it as a version (child)
// of that mesh instead of creating a new root asset.
savedAssets.push(normalizedParentAssetId
? await createAssetVersion({ assetId: normalizedParentAssetId, ...assetPayload, thumbnailPath: thumbnailFilename, inheritThumbnail: false, projectId: Number(projectId) })
? await createAssetVersion({ assetId: normalizedParentAssetId, ...assetPayload, thumbnailPath: thumbnailFilename, inheritThumbnail: false })
: await createProjectAsset({ projectId: Number(projectId), ...assetPayload, thumbnailPath: thumbnailFilename }));
}
@ -3605,9 +3557,6 @@ app.post('/api/comfyui/workflows/run', workflowExecutionUpload.any(), async (req
const inputValues = JSON.parse(req.body.inputValues || '{}');
const persistProcessingCard = String(req.body.persistProcessingCard || '').toLowerCase() !== 'false';
const persistGeneratedAssets = String(req.body.persistGeneratedAssets || '').toLowerCase() !== 'false';
// Brainstorming Board generations link assets to the project without creating
// a visible Kanban card (an Assets_Projects row and no Cards_Assets row).
const persistAssetsDetached = String(req.body.detachedAsset || '').toLowerCase() === 'true';
// Default ON: when no explicit parentAssetId is given, save each output under
// the resolved input asset of the same type — a mesh output becomes a version of
// the input mesh, an image output an edit of the input image. This means MCP
@ -3884,7 +3833,7 @@ app.post('/api/comfyui/workflows/run', workflowExecutionUpload.any(), async (req
// of the source image. Otherwise it's a new root asset.
const outputParentId = resolveOutputParentId(inferredAssetType);
const persistedAsset = (outputParentId && inferredAssetType === 'mesh')
? await createAssetVersion({ assetId: outputParentId, ...generatedAssetPayload, thumbnailPath: meshThumbnailFilename, inheritThumbnail: false, projectId: hasProjectId ? normalizedProjectId : null })
? await createAssetVersion({ assetId: outputParentId, ...generatedAssetPayload, thumbnailPath: meshThumbnailFilename, inheritThumbnail: false })
: (outputParentId && inferredAssetType === 'image')
? {
...(await createAssetEditRecord({
@ -3894,12 +3843,11 @@ app.post('/api/comfyui/workflows/run', workflowExecutionUpload.any(), async (req
filePath: storedFilePath,
width: dimensions.width,
height: dimensions.height,
projectId: hasProjectId ? normalizedProjectId : null,
createdAt: generatedAssetPayload.createdAt
})),
type: 'image'
}
: await createProjectAsset({ ...generatedAssetPayload, thumbnailPath: meshThumbnailFilename, detached: persistAssetsDetached });
: await createProjectAsset({ ...generatedAssetPayload, thumbnailPath: meshThumbnailFilename });
generatedAssets.push({
...persistedAsset,
url: `${getRequestBaseUrl(req)}/assets/${encodeURI(toAssetUrlPath(storedFilePath))}`,
@ -4433,7 +4381,7 @@ app.post('/api/meshes/generate', async (req, res) => {
// When a mesh was connected to the node and used to edit it, save the
// result as a version (child) of that mesh instead of a new root asset.
const savedAsset = normalizedParentAssetId
? await createAssetVersion({ assetId: normalizedParentAssetId, ...meshAssetPayload, inheritThumbnail: false, projectId: Number(projectId) })
? await createAssetVersion({ assetId: normalizedParentAssetId, ...meshAssetPayload, inheritThumbnail: false })
: await createProjectAsset({ projectId: Number(projectId), ...meshAssetPayload });
await clearCardProcessingState(processingProjectId, processingCardId, {
@ -5248,50 +5196,6 @@ app.delete('/api/projects/:id', async (req, res) => {
}
});
// Project <-> asset membership (Assets_Projects). An asset belongs to a project
// on its own, with no card required: any asset id works, root or edit/version.
app.post('/api/projects/:id/assets', async (req, res) => {
try {
const assetId = Number(req.body?.assetId);
if (!Number.isFinite(assetId)) {
return res.status(400).json({ error: 'assetId is required' });
}
const linked = await linkExistingAssetToProject(Number(req.params.id), assetId, {
cascadeChildren: req.body?.cascadeChildren === true
});
res.status(201).json(linked);
} catch (err) {
if (err.message === 'Asset not found') {
return res.status(404).json({ error: 'Asset not found' });
}
if (err.message?.startsWith('Project not found:')) {
return res.status(404).json({ error: 'Project not found' });
}
console.error('Failed to link asset to project:', err);
res.status(500).json({ error: 'Failed to link asset to project' });
}
});
app.delete('/api/projects/:id/assets/:assetId', async (req, res) => {
try {
const result = await unlinkAssetFromProjectById(Number(req.params.id), Number(req.params.assetId), {
cascadeChildren: req.query.cascadeChildren !== 'false'
});
if (result.status === 'not-found') {
return res.status(404).json({ error: 'Asset not found' });
}
res.json(result);
} catch (err) {
console.error('Failed to unlink asset from project:', err);
res.status(500).json({ error: 'Failed to unlink asset from project' });
}
});
// Turn a filesystem-unsafe name into a folder base name (letters, digits,
// spaces, dot, dash, underscore) so it can name the export folder + .3dgp file.
function sanitizeProjectExportName(name, fallback = 'project') {
@ -5403,12 +5307,8 @@ app.post('/api/projects/import', async (req, res) => {
});
app.get('/api/assets', async (req, res) => {
const { projectId, includeChildren } = req.query;
// includeChildren returns every project-linked edit/version as a row of its
// own, on top of the copies nested in each root's `children` array.
res.json(await listProjectAssets(projectId ? Number(projectId) : null, {
includeChildren: String(includeChildren || '').toLowerCase() === 'true'
}));
const { projectId } = req.query;
res.json(await listProjectAssets(projectId ? Number(projectId) : null));
});
app.get('/api/cards', async (req, res) => {
@ -5580,86 +5480,6 @@ app.delete('/api/graph/connections', async (req, res) => {
}
});
// ---------------------------------------------------------------------------
// Brainstorming Boards
// ---------------------------------------------------------------------------
app.get('/api/boards', async (req, res) => {
try {
const { projectId } = req.query;
if (!projectId) {
return res.status(400).json({ error: 'projectId is required' });
}
res.json(await listProjectBoards(Number(projectId)));
} catch (err) {
console.error('Failed to list boards:', err);
res.status(500).json({ error: err.message || 'Failed to list boards' });
}
});
app.post('/api/boards', async (req, res) => {
try {
const { projectId, name } = req.body;
if (!projectId) {
return res.status(400).json({ error: 'projectId is required' });
}
res.status(201).json(await createBoard({ projectId: Number(projectId), name }));
} catch (err) {
console.error('Failed to create board:', err);
res.status(500).json({ error: err.message || 'Failed to create board' });
}
});
app.get('/api/boards/:id', async (req, res) => {
try {
const board = await getBoardById(Number(req.params.id));
if (!board) {
return res.status(404).json({ error: 'Board not found' });
}
res.json(board);
} catch (err) {
console.error('Failed to get board:', err);
res.status(500).json({ error: err.message || 'Failed to get board' });
}
});
app.put('/api/boards/:id', async (req, res) => {
try {
const { name, state, position, thumbnailPath } = req.body;
const board = await updateBoard(Number(req.params.id), { name, state, position, thumbnailPath });
if (!board) {
return res.status(404).json({ error: 'Board not found' });
}
res.json(board);
} catch (err) {
console.error('Failed to update board:', err);
res.status(500).json({ error: err.message || 'Failed to update board' });
}
});
app.delete('/api/boards/:id', async (req, res) => {
try {
const result = await deleteBoard(Number(req.params.id));
if (result.status === 'not-found') {
return res.status(404).json({ error: 'Board not found' });
}
res.status(204).end();
} catch (err) {
console.error('Failed to delete board:', err);
res.status(500).json({ error: err.message || 'Failed to delete board' });
}
});
app.get('/api/assets/library', async (req, res) => {
try {
const [images, meshes, brushes] = await Promise.all([
@ -6637,59 +6457,12 @@ app.post('/api/assets/image-editor/save', multer({ storage: multer.memoryStorage
}
});
// Resolve a chosen file (served filename or stored path) to a workflow source
// reference that parents edits to the root ancestor. Used by the board panel.
app.get('/api/assets/resolve-source', async (req, res) => {
try {
const { projectId, type = 'image', filePath } = req.query;
if (!projectId || !filePath) {
return res.status(400).json({ error: 'projectId and filePath are required' });
}
res.json(await resolveEditableSourceReference(Number(projectId), type, filePath));
} catch (err) {
console.error('Failed to resolve asset source:', err);
res.status(500).json({ error: err.message || 'Failed to resolve asset source' });
}
});
app.post('/api/assets/link', async (req, res) => {
try {
const { projectId, assetId, filename, type = 'image', name, metadata, detached } = req.body;
const { projectId, filename, type = 'image', name, metadata } = req.body;
if (!projectId) {
return res.status(400).json({ error: 'projectId is required' });
}
// Link an EXISTING asset by id — works for a root asset as well as for an
// image edit or a mesh version, which have no file of their own to look up
// in the library and previously could not be attached to a project at all.
if (assetId !== undefined && assetId !== null && assetId !== '') {
const numericAssetId = Number(assetId);
if (!Number.isFinite(numericAssetId)) {
return res.status(400).json({ error: 'assetId must be a number' });
}
try {
const linked = await linkExistingAssetToProject(Number(projectId), numericAssetId, {
cascadeChildren: req.body.cascadeChildren === true
});
return res.status(201).json(linked);
} catch (linkErr) {
if (linkErr.message === 'Asset not found') {
return res.status(404).json({ error: 'Asset not found' });
}
if (linkErr.message?.startsWith('Project not found:')) {
return res.status(404).json({ error: 'Project not found' });
}
throw linkErr;
}
}
if (!filename) {
return res.status(400).json({ error: 'assetId or filename is required' });
if (!projectId || !filename) {
return res.status(400).json({ error: 'projectId and filename are required' });
}
const assetType = type || inferAssetTypeFromFilename(filename);
@ -6720,8 +6493,7 @@ app.post('/api/assets/link', async (req, res) => {
format: path.extname(storedFilePath).replace('.', '').toUpperCase() || assetType.toUpperCase(),
source: 'ASSET LIB'
},
createdAt: Date.now(),
detached: detached === true || String(detached).toLowerCase() === 'true'
createdAt: Date.now()
});
res.status(201).json(newAsset);
@ -6734,10 +6506,7 @@ app.post('/api/assets/link', async (req, res) => {
app.delete('/api/assets/:id', async (req, res) => {
try {
const assetId = Number(req.params.id);
// With ?projectId= the asset is detached from that project only; without it,
// from every project (and deleted outright when it belonged to none).
const projectId = req.query.projectId ? Number(req.query.projectId) : null;
const result = await deleteAssetById(assetId, { projectId });
const result = await deleteAssetById(assetId);
if (result.status === 'not-found') {
return res.status(404).json({ error: 'Asset card not found' });
@ -7315,9 +7084,6 @@ app.post('/api/images/generate', async (req, res) => {
try {
const { projectId, selectedApi, prompt, name, cardId } = req.body;
const trimmedName = String(name || '').trim();
// Brainstorming Board generations link the asset to the project without a
// visible Kanban card, so skip the processing-card snapshot entirely.
const detachedAsset = String(req.body.detachedAsset || '').toLowerCase() === 'true';
if (!projectId || !selectedApi || !prompt?.trim() || !trimmedName) {
return res.status(400).json({ error: 'projectId, selectedApi, prompt and name are required' });
@ -7326,23 +7092,21 @@ app.post('/api/images/generate', async (req, res) => {
const settings = await getSettings();
const trimmedPrompt = prompt.trim();
processingProjectId = Number(projectId);
processingCardId = detachedAsset ? null : (cardId || randomUUID());
processingCardId = cardId || randomUUID();
processingCardName = trimmedName;
processingStartedAt = Date.now();
if (!detachedAsset) {
await updateCardProcessingSnapshot(processingProjectId, processingCardId, {
columnName: 'Images',
name: processingCardName,
status: 'processing',
progressPercent: null,
detail: 'Submitting image generation request',
currentNodeLabel: 'Waiting for API response',
source: 'API',
operationType: 'image-generation',
startedAt: processingStartedAt
});
}
await updateCardProcessingSnapshot(processingProjectId, processingCardId, {
columnName: 'Images',
name: processingCardName,
status: 'processing',
progressPercent: null,
detail: 'Submitting image generation request',
currentNodeLabel: 'Waiting for API response',
source: 'API',
operationType: 'image-generation',
startedAt: processingStartedAt
});
const googleSettings = settings?.apis?.google;
const googleGenerationSettings = googleSettings?.imageGeneration;
@ -7484,17 +7248,14 @@ app.post('/api/images/generate', async (req, res) => {
mimeType: inlineData.mimeType,
responseId,
usage: responseBody?.usage || responseBody?.usageMetadata || null,
...(processingCardId ? { cardId: processingCardId } : {})
cardId: processingCardId
},
createdAt: Date.now(),
detached: detachedAsset
createdAt: Date.now()
});
if (!detachedAsset) {
await clearCardProcessingState(processingProjectId, processingCardId, {
name: processingCardName
});
}
await clearCardProcessingState(processingProjectId, processingCardId, {
name: processingCardName
});
res.status(201).json(newAsset);
} catch (err) {
@ -7721,14 +7482,8 @@ async function fileSizeOrNull(targetPath) {
}
}
function resolveComfySubPath(comfyPath, relativePath, modelsPath) {
function resolveComfySubPath(comfyPath, relativePath) {
const normalizedRelative = String(relativePath || '').replace(/^[/\\]+/, '');
if (modelsPath) {
const afterModels = normalizedRelative.replace(/^models[/\\]?/, '');
if (afterModels !== normalizedRelative) {
return path.join(modelsPath, afterModels);
}
}
return path.join(comfyPath, normalizedRelative);
}
@ -7768,7 +7523,7 @@ async function downloadFileWithProgress(url, destinationPath, onChunk) {
return { receivedBytes, totalBytes };
}
async function runSetupDownloads(jobId, comfyPath, files, modelsPath) {
async function runSetupDownloads(jobId, comfyPath, files) {
const totalExpectedBytes = files.reduce((sum, file) => sum + (Number(file.expectedBytes) || 0), 0);
let cumulativeCompletedBytes = 0;
@ -7785,7 +7540,7 @@ async function runSetupDownloads(jobId, comfyPath, files, modelsPath) {
for (let index = 0; index < files.length; index += 1) {
const file = files[index];
const destinationPath = resolveComfySubPath(comfyPath, path.join(file.relativeDir, file.fileName), modelsPath);
const destinationPath = resolveComfySubPath(comfyPath, path.join(file.relativeDir, file.fileName));
try {
await fs.mkdir(path.dirname(destinationPath), { recursive: true });
@ -7903,13 +7658,10 @@ async function installSetupWorkflow(workflowConfig, diffusionModelFileName = '')
if (!sourceParameter) {
throw new Error(`Workflow "${workflowConfig.Name}": input ${parameterId} not found`);
}
const valueType = normalizeComfyValueType(SETUP_TYPE_TO_VALUE_TYPE[inputCfg.Type], getDefaultComfyValueType(sourceParameter));
parameters.push({
...sourceParameter,
name: sanitizeDisplayName(inputCfg.Name || sourceParameter.name, sourceParameter.name),
valueType,
// Optional "Enums": [...] in setup.json turns the field into a dropdown.
enums: normalizeComfyEnums(inputCfg.Enums, valueType)
valueType: normalizeComfyValueType(SETUP_TYPE_TO_VALUE_TYPE[inputCfg.Type], getDefaultComfyValueType(sourceParameter))
});
}
@ -8025,7 +7777,6 @@ app.get('/api/setup/config', async (req, res) => {
app.post('/api/setup/check-comfy-path', async (req, res) => {
try {
const comfyPath = String(req.body?.path || '').trim();
const modelsPath = String(req.body?.modelsPath || '').trim();
if (!comfyPath) {
return res.status(400).json({ error: 'A ComfyUI folder path is required' });
}
@ -8035,30 +7786,23 @@ app.post('/api/setup/check-comfy-path', async (req, res) => {
return res.status(400).json({ error: `Folder does not exist: ${comfyPath}` });
}
if (modelsPath) {
const modelsPathExists = await pathExists(modelsPath);
if (!modelsPathExists) {
return res.status(400).json({ error: `Models folder does not exist: ${modelsPath}` });
}
} else {
const modelsDir = path.join(comfyPath, 'models');
const modelsExist = await pathExists(modelsDir);
if (!modelsExist) {
return res.status(400).json({ error: `This does not look like a ComfyUI folder (missing "models" subfolder): ${comfyPath}` });
}
const modelsDir = path.join(comfyPath, 'models');
const modelsExist = await pathExists(modelsDir);
if (!modelsExist) {
return res.status(400).json({ error: `This does not look like a ComfyUI folder (missing "models" subfolder): ${comfyPath}` });
}
const config = await loadSetupConfig();
const created = [];
for (const relativePath of Object.values(config.ComfyUIPaths || {})) {
const target = resolveComfySubPath(comfyPath, relativePath, modelsPath);
const target = resolveComfySubPath(comfyPath, relativePath);
if (!(await pathExists(target))) {
await fs.mkdir(target, { recursive: true });
created.push(relativePath);
}
}
res.json({ ok: true, comfyPath, modelsPath, createdSubfolders: created });
res.json({ ok: true, comfyPath, createdSubfolders: created });
} catch (err) {
console.error('Failed to validate ComfyUI path:', err);
res.status(500).json({ error: err.message || 'Failed to validate ComfyUI path' });
@ -8068,7 +7812,6 @@ app.post('/api/setup/check-comfy-path', async (req, res) => {
app.post('/api/setup/check-files', async (req, res) => {
try {
const comfyPath = String(req.body?.comfyPath || '').trim();
const modelsPath = String(req.body?.modelsPath || '').trim();
const files = Array.isArray(req.body?.files) ? req.body.files : [];
if (!comfyPath) {
@ -8077,7 +7820,7 @@ app.post('/api/setup/check-files', async (req, res) => {
const results = [];
for (const file of files) {
const absPath = resolveComfySubPath(comfyPath, path.join(file.relativeDir || '', file.fileName || ''), modelsPath);
const absPath = resolveComfySubPath(comfyPath, path.join(file.relativeDir || '', file.fileName || ''));
const size = await fileSizeOrNull(absPath);
results.push({
relativeDir: file.relativeDir || '',
@ -8097,7 +7840,6 @@ app.post('/api/setup/check-files', async (req, res) => {
app.post('/api/setup/download', async (req, res) => {
try {
const comfyPath = String(req.body?.comfyPath || '').trim();
const modelsPath = String(req.body?.modelsPath || '').trim();
const files = Array.isArray(req.body?.files) ? req.body.files : [];
if (!comfyPath) {
@ -8113,7 +7855,7 @@ app.post('/api/setup/download', async (req, res) => {
const jobId = randomUUID();
getSetupDownloadJob(jobId);
runSetupDownloads(jobId, comfyPath, files, modelsPath).catch(err => {
runSetupDownloads(jobId, comfyPath, files).catch(err => {
console.error('[setup] download job crashed:', err);
publishSetupDownloadProgress(jobId, { status: 'error', error: err.message || String(err) });
});

View file

@ -1,37 +0,0 @@
{
"1": {
"inputs": {
"model_name": "Qwen3-VL-4B-Instruct",
"quantization": "None (FP16)",
"attention_mode": "auto",
"use_torch_compile": false,
"device": "auto",
"prompt_text": "",
"enhancement_style": "📝 Enhance",
"custom_system_prompt": "",
"max_tokens": 1024,
"temperature": 0.7,
"top_p": 0.9,
"repetition_penalty": 1.1,
"keep_model_loaded": false,
"seed": 12345
},
"class_type": "AILab_QwenVL_PromptEnhancer",
"_meta": {
"title": "QwenVL Prompt Enhancer"
}
},
"2": {
"inputs": {
"output": "",
"source": [
"1",
0
]
},
"class_type": "Display Any (rgthree)",
"_meta": {
"title": "Display Any (rgthree)"
}
}
}

View file

@ -181,8 +181,7 @@
"Inputs": [
{ "Node": "112", "Input": "text", "Name": "Prompt", "Type": "String" },
{ "Node": "116", "Input": "seed", "Name": "Seed", "Type": "Number" },
{ "Node": "116", "Input": "steps", "Name": "Steps", "Type": "Number" },
{ "Node": "114", "Input": "batch_size", "Name": "Number of Images to Generate", "Type": "Number" }
{ "Node": "116", "Input": "steps", "Name": "Steps", "Type": "Number" }
],
"Outputs": [
{ "Node": "90", "Name": "Save Image", "Type": "Image" }
@ -295,8 +294,7 @@
"Inputs": [
{ "Node": "34:27", "Input": "text", "Name": "Prompt", "Type": "String" },
{ "Node": "34:3", "Input": "seed", "Name": "Seed", "Type": "Number" },
{ "Node": "34:3", "Input": "steps", "Name": "Steps", "Type": "Number" },
{ "Node": "34:13", "Input": "batch_size", "Name": "Number of Images to Generate", "Type": "Number" }
{ "Node": "34:3", "Input": "steps", "Name": "Steps", "Type": "Number" }
],
"Outputs": [
{ "Node": "43", "Name": "Save Image", "Type": "Image" }
@ -329,8 +327,7 @@
{ "Node": "6", "Input": "text", "Name": "Prompt", "Type": "String" },
{ "Node": "7", "Input": "noise_seed", "Name": "Seed", "Type": "Number" },
{ "Node": "8:17", "Input": "steps", "Name": "Steps", "Type": "Number" },
{ "Node": "65", "Input": "value", "Name": "Image Resolution", "Type": "Number" },
{ "Node": "8:18", "Input": "batch_size", "Name": "Number of Images to Generate", "Type": "Number" }
{ "Node": "65", "Input": "value", "Name": "Image Resolution", "Type": "Number" }
],
"Outputs": [
{ "Node": "63", "Name": "Save Image", "Type": "Image" }
@ -392,8 +389,7 @@
{ "Node": "6", "Input": "text", "Name": "Prompt", "Type": "String" },
{ "Node": "7", "Input": "noise_seed", "Name": "Seed", "Type": "Number" },
{ "Node": "8:17", "Input": "steps", "Name": "Steps", "Type": "Number" },
{ "Node": "65", "Input": "value", "Name": "Image Resolution", "Type": "Number" },
{ "Node": "8:18", "Input": "batch_size", "Name": "Number of Images to Generate", "Type": "Number" }
{ "Node": "65", "Input": "value", "Name": "Image Resolution", "Type": "Number" }
],
"Outputs": [
{ "Node": "63", "Name": "Save Image", "Type": "Image" }
@ -477,8 +473,7 @@
{ "Node": "6", "Input": "text", "Name": "Prompt", "Type": "String" },
{ "Node": "2", "Input": "seed", "Name": "Seed", "Type": "Number" },
{ "Node": "2", "Input": "steps", "Name": "Steps", "Type": "Number" },
{ "Node": "31", "Input": "value", "Name": "Image Resolution", "Type": "Number" },
{ "Node": "10", "Input": "batch_size", "Name": "Number of Images to Generate", "Type": "Number" }
{ "Node": "31", "Input": "value", "Name": "Image Resolution", "Type": "Number" }
],
"Outputs": [
{ "Node": "22", "Name": "Save Image", "Type": "Image" }
@ -503,8 +498,7 @@
{ "Node": "23", "Input": "text", "Name": "Prompt", "Type": "String" },
{ "Node": "3", "Input": "seed", "Name": "Seed", "Type": "Number" },
{ "Node": "3", "Input": "steps", "Name": "Steps", "Type": "Number" },
{ "Node": "46", "Input": "value", "Name": "Image Resolution", "Type": "Number" },
{ "Node": "43", "Input": "batch_size", "Name": "Number of Images to Generate", "Type": "Number" }
{ "Node": "46", "Input": "value", "Name": "Image Resolution", "Type": "Number" }
],
"Outputs": [
{ "Node": "47", "Name": "Save Image", "Type": "Image" }
@ -559,7 +553,7 @@
{ "Node": "6", "Input": "image", "Name": "Source Image", "Type": "Image" },
{ "Node": "209", "Input": "value", "Name": "Target Face Number", "Type": "Number" },
{ "Node": "214", "Input": "seed", "Name": "Seed", "Type": "Number" },
{ "Node": "258", "Input": "to_resolution", "Name": "Cascade Resolution", "Type": "Number", "Enums":[1024,1536] }
{ "Node": "258", "Input": "to_resolution", "Name": "Cascade Resolution (1024 or 1536)", "Type": "Number" }
],
"Outputs": [
{ "Node": "232", "Name": "Save Mesh", "Type": "Mesh" }
@ -572,7 +566,7 @@
{ "Node": "6", "Input": "image", "Name": "Source Image", "Type": "Image" },
{ "Node": "209", "Input": "value", "Name": "Target Face Number", "Type": "Number" },
{ "Node": "214", "Input": "seed", "Name": "Seed", "Type": "Number" },
{ "Node": "258", "Input": "to_resolution", "Name": "Cascade Resolution", "Type": "Number", "Enums":[1024,1536] },
{ "Node": "258", "Input": "to_resolution", "Name": "Cascade Resolution (1024 or 1536)", "Type": "Number" },
{ "Node": "261", "Input": "texture_size", "Name": "Texture Size", "Type": "Number" }
],
"Outputs": [
@ -585,7 +579,7 @@
"Inputs": [
{ "Node": "1", "Input": "glb_path", "Name": "Source Mesh", "Type": "Mesh" },
{ "Node": "3", "Input": "target_face_num", "Name": "Target Face Number", "Type": "Number" },
{ "Node": "3", "Input": "method", "Name": "Method", "Type": "String", "Enums":["Cumesh","Meshlib"] }
{ "Node": "3", "Input": "method", "Name": "Method (Cumesh or Meshlib)", "Type": "String" }
],
"Outputs": [
{ "Node": "5", "Name": "Save Mesh", "Type": "Mesh" }
@ -598,7 +592,7 @@
{ "Node": "1", "Input": "image", "Name": "Source Image", "Type": "Image" },
{ "Node": "8", "Input": "glb_path", "Name": "Source Mesh", "Type": "Mesh" },
{ "Node": "3", "Input": "texture_size", "Name": "Texture Size", "Type": "Number" },
{ "Node": "3", "Input": "resolution", "Name": "Resolution", "Type": "Number", "Enums":[1024,1536] }
{ "Node": "3", "Input": "resolution", "Name": "Resolution (1024 or 1536)", "Type": "Number" }
],
"Outputs": [
{ "Node": "12", "Name": "Output Mesh", "Type": "Mesh" }
@ -625,7 +619,7 @@
{ "Node": "2", "Input": "image", "Name": "Source Image", "Type": "Image" },
{ "Node": "28", "Input": "value", "Name": "Target Face Number", "Type": "Number" },
{ "Node": "4", "Input": "seed", "Name": "Seed", "Type": "Number" },
{ "Node": "4", "Input": "resolution", "Name": "Resolution", "Type": "Number", "Enums":[1024,1536] }
{ "Node": "4", "Input": "resolution", "Name": "Resolution (1024 or 1536)", "Type": "Number" }
],
"Outputs": [
{ "Node": "7", "Name": "Save Mesh", "Type": "Mesh" }
@ -689,19 +683,6 @@
"Outputs": [
{ "Node": "10", "Name": "Save Mesh", "Type": "Mesh" }
]
},
{
"Name": "Prompt Enhancer",
"File": "setup/Prompt Enhancer.json",
"Inputs": [
{ "Node": "1", "Input": "prompt_text", "Name": "Source Prompt", "Type": "String" },
{ "Node": "1", "Input": "max_tokens", "Name": "Max Tokens", "Type": "Number" },
{ "Node": "1", "Input": "keep_model_loaded", "Name": "Keep Model Loaded", "Type": "Boolean" },
{ "Node": "1", "Input": "seed", "Name": "Seed", "Type": "Number" }
],
"Outputs": [
{ "Node": "2", "Name": "Enhanced Prompt", "Type": "String" }
]
}
]
}

View file

@ -8,7 +8,6 @@ import ProjectWorkspacePage from './pages/ProjectWorkspacePage'
import AssetsPage from './pages/AssetsPage'
import MeshEditorPage from './pages/MeshEditorPage'
import ImageEditorPage from './pages/ImageEditorPage'
import BoardPage from './pages/BoardPage'
import WikiPage from './pages/WikiPage'
function AppRoutes() {
@ -20,7 +19,6 @@ function AppRoutes() {
<Route path="/assets" element={<AssetsPage />} />
<Route path="/mesh-editor" element={<MeshEditorPage />} />
<Route path="/image-editor" element={<ImageEditorPage />} />
<Route path="/board" element={<BoardPage />} />
<Route path="/wiki" element={<WikiPage />} />
<Route path="/wiki/:pageId" element={<WikiPage />} />
<Route path="/library" element={<Navigate to="/assets" replace />} />

View file

@ -1,8 +1,7 @@
import { useEffect, useState } from 'react'
import { useState } from 'react'
import FolderBrowserDialog from './FolderBrowserDialog'
import {
EXPORT_FORMATS,
browseFolders,
exportObject3D,
isGlbUrl,
loadObject3DFromUrl,
@ -12,8 +11,6 @@ import {
import { convertMesh, ensureDesktopService } from '../utils/meshTools'
import './ExportMeshDialog.css'
const LAST_OUTPUT_FOLDER_KEY = 'exportMeshDialog:lastOutputFolder'
// Reusable export popup. Provide either `getObject3D` (an async function that
// returns the in-memory THREE.Object3D to export) or `meshUrl` (a mesh URL the
// dialog loads itself). `defaultName` seeds the output file name.
@ -34,15 +31,6 @@ export default function ExportMeshDialog({ getObject3D, meshUrl, defaultName = '
const formats = getObject3D ? EXPORT_FORMATS.filter(entry => entry.kind === 'local') : EXPORT_FORMATS
const selectedFormat = formats.find(entry => entry.value === format) || formats[0]
// Recall the last folder used, but drop it silently if it no longer exists.
useEffect(() => {
const saved = localStorage.getItem(LAST_OUTPUT_FOLDER_KEY)
if (!saved) return
browseFolders(saved)
.then(() => setOutputFolder(saved))
.catch(() => localStorage.removeItem(LAST_OUTPUT_FOLDER_KEY))
}, [])
// Source GLB for the preset paths. When the asset is already a .glb, use its
// original bytes (perfect fidelity — skin weights, clips and textures
// untouched); otherwise serialize through three.js, which now carries the
@ -115,7 +103,6 @@ export default function ExportMeshDialog({ getObject3D, meshUrl, defaultName = '
setProgress({ frac: 0.97, message: 'Writing files…' })
const result = await writeExportedFiles(folder, files)
localStorage.setItem(LAST_OUTPUT_FOLDER_KEY, folder)
const writtenNames = (result?.written || files.map(file => file.filename)).join(', ')
setSuccess(`Exported ${files.length} file${files.length === 1 ? '' : 's'}: ${writtenNames}${convertNote}`)
} catch (err) {

View file

@ -55,7 +55,7 @@ function getNotificationIcon(tone) {
return 'info'
}
export default function Header({ showSearch = false, showCreateNew = false, onSettingsClick, title = '', centerTitle = false, searchValue = '', onSearchChange, searchPlaceholder = 'Search Assets', projectId = null }) {
export default function Header({ showSearch = false, showCreateNew = false, onSettingsClick, title = '', centerTitle = false, searchValue = '', onSearchChange, searchPlaceholder = 'Search Assets' }) {
const location = useLocation()
const navigate = useNavigate()
const { notifications, clearNotifications, removeNotification } = useNotifications()
@ -182,20 +182,6 @@ export default function Header({ showSearch = false, showCreateNew = false, onSe
)
)}
{projectId && (
isActive('/board') ? (
<Link to={`/projects/${projectId}`} className="header__search-btn" title="Back to workspace">
<span className="material-symbols-outlined" style={{ fontSize: '16px' }}>arrow_back</span>
<span className="header__search-text">Workspace</span>
</Link>
) : (
<Link to={`/board?projectId=${projectId}`} className="header__search-btn" title="Open brainstorming boards">
<span className="material-symbols-outlined" style={{ fontSize: '16px' }}>dashboard</span>
<span className="header__search-text">Boards</span>
</Link>
)
)}
<div className="header__actions">
<button
className={`header__icon-btn ${hasUnreadNotifications ? 'header__icon-btn--update' : ''}`}

View file

@ -8,7 +8,6 @@ export default function MeshPreviewDialog({ asset, titleId = 'mesh-preview-dialo
const [showGrid, setShowGrid] = useState(true)
const [showShadows, setShowShadows] = useState(false)
const [showAlbedo, setShowAlbedo] = useState(false)
const [showWireframe, setShowWireframe] = useState(false)
const [showLightSlider, setShowLightSlider] = useState(false)
const [lightIntensity, setLightIntensity] = useState(2.2)
const [showExport, setShowExport] = useState(false)
@ -47,15 +46,6 @@ export default function MeshPreviewDialog({ asset, titleId = 'mesh-preview-dialo
>
A
</button>
<button
type="button"
className={`mesh-preview-dialog__tool ${showWireframe ? 'mesh-preview-dialog__tool--active' : ''}`}
onClick={() => setShowWireframe(current => !current)}
aria-pressed={showWireframe}
title="Toggle wireframe"
>
W
</button>
<button
type="button"
className={`mesh-preview-dialog__tool ${showGrid ? 'mesh-preview-dialog__tool--active' : ''}`}
@ -103,7 +93,6 @@ export default function MeshPreviewDialog({ asset, titleId = 'mesh-preview-dialo
showGrid={showGrid}
showShadows={showShadows}
showAlbedo={showAlbedo}
showWireframe={showWireframe}
lightIntensity={lightIntensity}
fitMode="center"
/>

View file

@ -1,6 +1,5 @@
import { useState, useEffect } from 'react'
import { useSettings } from '../context/SettingsContext.shared'
import { API_BASE } from '../config'
import './SettingsModal.css'
const CUSTOM_API_TYPE_OPTIONS = [
@ -183,48 +182,6 @@ function RiggingInstaller() {
)
}
// Desktop-only-friendly folder browse button: calls the backend's native folder
// picker (Windows) and reports the chosen path back to the caller.
function BrowseFolderButton({ description, initialPath, onPick }) {
const [busy, setBusy] = useState(false)
const [error, setError] = useState('')
const handleClick = async () => {
setError(''); setBusy(true)
try {
const res = await fetch(`${API_BASE}/setup/pick-folder`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ description, initialPath })
})
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Folder picker failed')
if (data.path) onPick(data.path)
} catch (err) {
setError(err.message || String(err))
} finally {
setBusy(false)
}
}
return (
<>
<button
type="button"
className="kanban-sidebar__new-asset"
style={{ margin: 0, padding: '0.5rem 0.9rem', whiteSpace: 'nowrap' }}
onClick={handleClick}
disabled={busy}
title={description}
>
<span className="material-symbols-outlined" style={{ fontSize: '16px', verticalAlign: 'middle' }}>folder_open</span>
{busy ? '…' : 'Browse'}
</button>
{error && <p className="settings-helper-text" style={{ color: '#f87171' }}>{error}</p>}
</>
)
}
export default function SettingsModal({ onClose }) {
const { settings, updateSettings, addCustomApi } = useSettings()
const [localSettings, setLocalSettings] = useState(settings)
@ -579,65 +536,21 @@ export default function SettingsModal({ onClose }) {
<div className="settings-input-group">
<label className="settings-label">Path</label>
<div style={{ display: 'flex', gap: '0.5em', alignItems: 'flex-start' }}>
<input
className="settings-input"
style={{ flex: 1 }}
placeholder="C:\\ComfyUI"
value={localSettings?.apis?.comfyui?.path || ''}
onChange={e => setLocalSettings(prev => ({
...prev,
apis: {
...prev?.apis,
comfyui: {
...prev?.apis?.comfyui,
path: e.target.value
}
<input
className="settings-input"
placeholder="C:\\ComfyUI"
value={localSettings?.apis?.comfyui?.path || ''}
onChange={e => setLocalSettings(prev => ({
...prev,
apis: {
...prev?.apis,
comfyui: {
...prev?.apis?.comfyui,
path: e.target.value
}
}))}
/>
<BrowseFolderButton
description="Select your ComfyUI folder"
initialPath={localSettings?.apis?.comfyui?.path || ''}
onPick={picked => setLocalSettings(prev => ({
...prev,
apis: { ...prev?.apis, comfyui: { ...prev?.apis?.comfyui, path: picked } }
}))}
/>
</div>
</div>
<div className="settings-input-group">
<label className="settings-label">Models Path <span style={{ opacity: 0.6, fontWeight: 400 }}>(optional)</span></label>
<div style={{ display: 'flex', gap: '0.5em', alignItems: 'flex-start' }}>
<input
className="settings-input"
style={{ flex: 1 }}
placeholder="Defaults to {ComfyUI path}\models"
value={localSettings?.apis?.comfyui?.modelsPath || ''}
onChange={e => setLocalSettings(prev => ({
...prev,
apis: {
...prev?.apis,
comfyui: {
...prev?.apis?.comfyui,
modelsPath: e.target.value
}
}
}))}
/>
<BrowseFolderButton
description="Select your ComfyUI models folder"
initialPath={localSettings?.apis?.comfyui?.modelsPath || localSettings?.apis?.comfyui?.path || ''}
onPick={picked => setLocalSettings(prev => ({
...prev,
apis: { ...prev?.apis, comfyui: { ...prev?.apis?.comfyui, modelsPath: picked } }
}))}
/>
</div>
<p className="settings-helper-text">
Set this only if your models live somewhere other than <code>{'{ComfyUI path}'}\models</code> (e.g. shared across multiple ComfyUI installs).
</p>
}
}))}
/>
</div>
<div className="settings-grid settings-grid--triple">

View file

@ -74,11 +74,9 @@ export default function SetupWizardModal({ onComplete, onClose }) {
const [loadError, setLoadError] = useState('')
const [comfyPath, setComfyPath] = useState('')
const [modelsPath, setModelsPath] = useState('')
const [pathBusy, setPathBusy] = useState(false)
const [pathError, setPathError] = useState('')
const [browseBusy, setBrowseBusy] = useState(false)
const [browseModelsBusy, setBrowseModelsBusy] = useState(false)
const [selectionByName, setSelectionByName] = useState({})
const [existingFileKeys, setExistingFileKeys] = useState(new Set())
@ -119,10 +117,6 @@ export default function SetupWizardModal({ onComplete, onClose }) {
setComfyPath(settings?.apis?.comfyui?.path || '')
}, [settings?.apis?.comfyui?.path])
useEffect(() => {
setModelsPath(settings?.apis?.comfyui?.modelsPath || '')
}, [settings?.apis?.comfyui?.modelsPath])
useEffect(() => () => {
eventSourceRef.current?.close()
}, [])
@ -137,10 +131,9 @@ export default function SetupWizardModal({ onComplete, onClose }) {
return buildFileList(config, allSelections, paths)
}, [config])
const refreshFileExistence = useCallback(async (pathOverride, modelsPathOverride) => {
const refreshFileExistence = useCallback(async (pathOverride) => {
if (!config) return
const effectivePath = pathOverride ?? comfyPath
const effectiveModelsPath = modelsPathOverride ?? modelsPath
if (!effectivePath) return
setCheckingFiles(true)
@ -148,7 +141,7 @@ export default function SetupWizardModal({ onComplete, onClose }) {
const res = await fetch(`${API_BASE}/setup/check-files`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ comfyPath: effectivePath, modelsPath: effectiveModelsPath, files: allCandidateFiles })
body: JSON.stringify({ comfyPath: effectivePath, files: allCandidateFiles })
})
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Failed to check files')
@ -163,7 +156,7 @@ export default function SetupWizardModal({ onComplete, onClose }) {
} finally {
setCheckingFiles(false)
}
}, [allCandidateFiles, comfyPath, modelsPath, config])
}, [allCandidateFiles, comfyPath, config])
const selections = useMemo(
() => Object.entries(selectionByName).map(([diffusionName, modelQuality]) => ({ diffusionName, modelQuality })),
@ -262,35 +255,15 @@ export default function SetupWizardModal({ onComplete, onClose }) {
}
}
const handleBrowseModelsFolder = async () => {
setPathError('')
setBrowseModelsBusy(true)
try {
const res = await fetch(`${API_BASE}/setup/pick-folder`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ description: 'Select your ComfyUI models folder', initialPath: modelsPath || comfyPath })
})
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Folder picker failed')
if (data.path) setModelsPath(data.path)
} catch (err) {
setPathError(err.message || String(err))
} finally {
setBrowseModelsBusy(false)
}
}
const handleValidatePath = async () => {
setPathError('')
setPathBusy(true)
try {
const trimmed = comfyPath.trim()
const trimmedModelsPath = modelsPath.trim()
const res = await fetch(`${API_BASE}/setup/check-comfy-path`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ path: trimmed, modelsPath: trimmedModelsPath })
body: JSON.stringify({ path: trimmed })
})
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Invalid ComfyUI path')
@ -299,11 +272,11 @@ export default function SetupWizardModal({ onComplete, onClose }) {
...settings,
apis: {
...(settings?.apis || {}),
comfyui: { ...(settings?.apis?.comfyui || {}), path: trimmed, modelsPath: trimmedModelsPath }
comfyui: { ...(settings?.apis?.comfyui || {}), path: trimmed }
}
})
await refreshFileExistence(trimmed, trimmedModelsPath)
await refreshFileExistence(trimmed)
setStepId('models')
} catch (err) {
setPathError(err.message || String(err))
@ -325,7 +298,7 @@ export default function SetupWizardModal({ onComplete, onClose }) {
const res = await fetch(`${API_BASE}/setup/download`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ comfyPath, modelsPath, files: filesToDownload })
body: JSON.stringify({ comfyPath, files: filesToDownload })
})
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Failed to start downloads')
@ -467,36 +440,7 @@ export default function SetupWizardModal({ onComplete, onClose }) {
</button>
</div>
<p className="setup-wizard__hint">
{modelsPath.trim()
? 'Missing model-type subfolders will be created inside your models folder below.'
: <>The folder must contain a <code>models</code> subfolder. Missing model-type subfolders will be created.</>}
</p>
<label className="projects-page__label font-label" htmlFor="setup-models-path" style={{ marginTop: '1em' }}>
Models Folder <span style={{ opacity: 0.6, fontWeight: 400 }}>(optional)</span>
</label>
<div className="setup-wizard__path-row">
<input
id="setup-models-path"
type="text"
className="projects-page__input setup-wizard__path-input"
placeholder="Defaults to {ComfyUI folder}\models"
value={modelsPath}
onChange={(e) => setModelsPath(e.target.value)}
/>
<button
type="button"
className="setup-wizard__browse-btn"
onClick={handleBrowseModelsFolder}
disabled={browseModelsBusy}
title="Browse for models folder"
>
<span className="material-symbols-outlined" style={{ fontSize: '18px' }}>folder_open</span>
{browseModelsBusy ? '…' : 'Browse'}
</button>
</div>
<p className="setup-wizard__hint">
Set this only if your models live somewhere other than <code>{'{ComfyUI folder}'}\models</code> (e.g. shared across multiple ComfyUI installs).
The folder must contain a <code>models</code> subfolder. Missing model-type subfolders will be created.
</p>
{pathError && <div className="setup-wizard__error">{pathError}</div>}

View file

@ -184,36 +184,6 @@ function applyDisplayMaterial(object, showNormals, showShadows, showAlbedo) {
})
}
function applyWireframeOverlay(object, showWireframe) {
if (!showWireframe || !object) {
return
}
const meshes = []
object.traverse(child => {
if (child.isMesh && child.geometry) {
meshes.push(child)
}
})
meshes.forEach(mesh => {
const overlay = new THREE.Mesh(
mesh.geometry,
new THREE.MeshBasicMaterial({
color: '#ffffff',
wireframe: true,
transparent: true,
opacity: 0.36,
depthWrite: false
})
)
overlay.castShadow = false
overlay.receiveShadow = false
overlay.userData.isWireframeOverlay = true
mesh.add(overlay)
})
}
async function loadModelFromUrl(url, fitMode = 'ground') {
const extension = getExtensionFromUrl(url)
@ -279,7 +249,6 @@ export default function Viewer({
showGrid = true,
showShadows = true,
showAlbedo = false,
showWireframe = false,
lightIntensity = 2.2,
fitMode = 'ground'
}) {
@ -325,9 +294,8 @@ export default function Viewer({
const modelClone = modelState.object.clone(true)
applyDisplayMaterial(modelClone, showNormals, showShadows, showAlbedo)
applyWireframeOverlay(modelClone, showWireframe)
return modelClone
}, [modelState, modelUrl, showNormals, showShadows, showAlbedo, showWireframe])
}, [modelState, modelUrl, showNormals, showShadows, showAlbedo])
const cameraTarget = modelState?.modelUrl === modelUrl ? modelState.target : new THREE.Vector3(0, 0.75, 0)
const cameraPosition = modelState?.modelUrl === modelUrl ? modelState.cameraPosition : new THREE.Vector3(3, 3, 5)

View file

@ -1,465 +0,0 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { useProjects } from '../../context/ProjectContext'
import { useSettings } from '../../context/SettingsContext.shared'
import { useNotifications } from '../../context/NotificationContext'
import { useWorkflowJobs } from '../../context/WorkflowJobsContext'
import {
IMAGE_API_LIST,
normalizeCustomApiType,
filterImageGenerationWorkflows,
filterImageEditWorkflows,
getWorkflowParameterValueType,
isFileWorkflowValueType,
getWorkflowFileInputAccept,
createComfyExecutionId
} from '../../utils/graphHelpers'
import { getComfyDraftFromWorkflow } from '../../utils/kanbanHelpers'
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
import AssetSelectorModal from '../AssetSelectorModal'
// An image/file input value chosen from the Assets library (vs an uploaded File).
function isAssetReferenceValue(value) {
return value && typeof value === 'object' && !(value instanceof File) && typeof value.source === 'string'
}
function describeFileValue(value, valueType) {
if (value instanceof File) return value.name
if (isAssetReferenceValue(value)) return value.name || 'Selected asset'
return `Choose ${valueType} file`
}
// Merge image-generation + image-edit workflows, de-duplicated by id and
// sorted alphabetically by name.
function collectImageWorkflows(workflows = []) {
const seen = new Set()
const result = []
for (const wf of [...filterImageGenerationWorkflows(workflows), ...filterImageEditWorkflows(workflows)]) {
if (seen.has(wf.id)) continue
seen.add(wf.id)
result.push(wf)
}
return result.sort((a, b) =>
String(a.name || '').localeCompare(String(b.name || ''), undefined, { sensitivity: 'base' })
)
}
export default function BoardAiPanel({ projectId, projectName, boardId, onImageGenerated, getSelectedBoardImage }) {
const { getComfyWorkflows, runComfyWorkflow, generateImage, resolveAssetSourceReference } = useProjects()
const { settings } = useSettings()
const { addNotification } = useNotifications()
const { registerJob, completeJob } = useWorkflowJobs()
const [tab, setTab] = useState('comfy')
const [workflows, setWorkflows] = useState([])
const [selectedWorkflowId, setSelectedWorkflowId] = useState('')
const [comfyInputs, setComfyInputs] = useState({})
const [comfyName, setComfyName] = useState('')
const [selectedApi, setSelectedApi] = useState('')
const [apiPrompt, setApiPrompt] = useState('')
const [apiName, setApiName] = useState('')
const [running, setRunning] = useState(false)
const [status, setStatus] = useState(null)
const [assetPickerParam, setAssetPickerParam] = useState(null) // { paramId, valueType }
const fileInputsRef = useRef({})
const customApis = useMemo(() => settings?.apis?.custom || [], [settings])
const imageApis = useMemo(() => ([
...IMAGE_API_LIST,
...customApis
.filter(api => normalizeCustomApiType(api?.type) === 'image-generation')
.map(api => ({ id: `custom_${api.id}`, name: api.name }))
]), [customApis])
useEffect(() => {
let cancelled = false
getComfyWorkflows()
.then(list => { if (!cancelled) setWorkflows(collectImageWorkflows(list || [])) })
.catch(err => console.error('Failed to load ComfyUI workflows', err))
return () => { cancelled = true }
}, [getComfyWorkflows])
useEffect(() => {
if (imageApis.length && !selectedApi) setSelectedApi(imageApis[0].id)
}, [imageApis, selectedApi])
// Workflow ids are numeric but <select> values are strings — match loosely
// (same approach as GraphAssetNode) so the selected workflow resolves.
const selectedWorkflow = useMemo(
() => workflows.find(wf => String(wf.id) === String(selectedWorkflowId)) || null,
[workflows, selectedWorkflowId]
)
const handleSelectWorkflow = (id) => {
setSelectedWorkflowId(id)
const wf = workflows.find(w => String(w.id) === String(id))
setComfyInputs(wf ? getComfyDraftFromWorkflow(wf).inputs : {})
}
const setInputValue = (paramId, value) => {
setComfyInputs(prev => ({ ...prev, [paramId]: value }))
}
const flash = (message, tone = 'info') => setStatus({ message, tone })
// Resolve a chosen file to a source reference (edit: for edits so the output
// nests under the root ancestor; asset: for roots) and bind it to a parameter.
const bindSourceForParam = async (paramId, valueType, filePath, fallbackName) => {
const { sourceReference } = await resolveAssetSourceReference(
projectId,
valueType === 'mesh' ? 'mesh' : 'image',
filePath
)
setInputValue(paramId, { source: sourceReference, name: fallbackName || 'Selected asset' })
}
const handleUseSelectedImage = async (paramId, valueType) => {
const selected = getSelectedBoardImage?.()
if (!selected?.filename) {
flash('Select an image on the board first.', 'error')
return
}
try {
await bindSourceForParam(paramId, valueType, selected.filename, 'Selected board image')
} catch (err) {
console.error('Failed to use selected board image', err)
flash(err.message || 'Failed to use the selected image.', 'error')
}
}
const runComfy = async () => {
if (!selectedWorkflow) { flash('Select a workflow first.', 'error'); return }
// Validate required file/string params (numbers/booleans always have a value).
for (const parameter of selectedWorkflow.parameters || []) {
const valueType = getWorkflowParameterValueType(parameter)
const value = comfyInputs[parameter.id]
if (isFileWorkflowValueType(valueType) && !(value instanceof File) && !isAssetReferenceValue(value)) {
flash(`Select a ${valueType} for ${parameter.name}.`, 'error')
return
}
if (valueType === 'string' && parameter.required && !String(value ?? '').trim()) {
flash(`Enter a value for ${parameter.name}.`, 'error')
return
}
}
const promptId = createComfyExecutionId('comfy-prompt')
const clientId = createComfyExecutionId('comfy-client')
setRunning(true)
flash('Running ComfyUI workflow…')
registerJob({
id: promptId,
projectId,
projectName,
page: 'board',
targetId: boardId,
kind: 'image',
label: selectedWorkflow.name
})
try {
const assets = await runComfyWorkflow(projectId, {
workflowId: selectedWorkflow.id,
inputs: comfyInputs,
name: comfyName.trim() || undefined,
clientId,
promptId,
persistProcessingCard: false,
// Detached: image-generation outputs (no image input) become root project
// assets with no Kanban card. autoParentFromInputs: when an image input is
// an asset, the output is saved as an Edit of that source image instead.
detachedAsset: true,
autoParentFromInputs: true
})
const imageAssets = (Array.isArray(assets) ? assets : [assets]).filter(
a => a && (a.type ? a.type === 'image' : true)
)
for (const asset of imageAssets) {
await onImageGenerated(asset)
}
completeJob(promptId, { status: 'completed' })
flash(`Added ${imageAssets.length} image${imageAssets.length === 1 ? '' : 's'} to the board.`, 'success')
} catch (err) {
console.error('ComfyUI board generation failed', err)
completeJob(promptId, { status: 'error', error: err.message })
flash(err.message || 'ComfyUI workflow failed.', 'error')
addNotification({ title: 'Board generation failed', message: err.message || 'ComfyUI workflow failed', tone: 'error', source: selectedWorkflow.name, projectId })
} finally {
setRunning(false)
}
}
const runApi = async () => {
if (!selectedApi) { flash('Select an API.', 'error'); return }
if (!apiPrompt.trim()) { flash('Enter a prompt.', 'error'); return }
const name = apiName.trim()
if (!name) { flash('Enter a name for the image.', 'error'); return }
setRunning(true)
flash('Generating image…')
try {
const asset = await generateImage(projectId, { selectedApi, prompt: apiPrompt.trim(), name, detachedAsset: true })
await onImageGenerated(asset)
flash('Image added to the board.', 'success')
} catch (err) {
console.error('API board generation failed', err)
flash(err.message || 'Image generation failed.', 'error')
addNotification({ title: 'Board generation failed', message: err.message || 'Image generation failed', tone: 'error', source: imageApis.find(a => a.id === selectedApi)?.name || 'Image API', projectId })
} finally {
setRunning(false)
}
}
const renderParameterField = (parameter) => {
const valueType = getWorkflowParameterValueType(parameter)
const value = comfyInputs[parameter.id]
const label = parameter.label || parameter.name || parameter.id
if (isFileWorkflowValueType(valueType)) {
const hasValue = value instanceof File || isAssetReferenceValue(value)
return (
<div className="board-ai-panel__field" key={parameter.id}>
<span className="board-ai-panel__label">{label}</span>
<button
type="button"
className={`board-ai-panel__file-btn ${hasValue ? 'board-ai-panel__file-btn--set' : ''}`}
onClick={() => fileInputsRef.current[parameter.id]?.click()}
>
<span className="material-symbols-outlined" style={{ fontSize: '16px' }}>upload</span>
{describeFileValue(value, valueType)}
</button>
<div className="board-ai-panel__file-actions">
<button
type="button"
className="board-ai-panel__link-btn"
onClick={() => fileInputsRef.current[parameter.id]?.click()}
>
From computer
</button>
<button
type="button"
className="board-ai-panel__link-btn"
onClick={() => setAssetPickerParam({ paramId: parameter.id, valueType })}
>
From Assets
</button>
{valueType === 'image' && (
<button
type="button"
className="board-ai-panel__link-btn"
onClick={() => handleUseSelectedImage(parameter.id, valueType)}
title="Use the image currently selected on the board"
>
Selected image
</button>
)}
</div>
<input
ref={(el) => { fileInputsRef.current[parameter.id] = el }}
type="file"
accept={getWorkflowFileInputAccept(valueType)}
style={{ display: 'none' }}
onChange={(e) => setInputValue(parameter.id, e.target.files?.[0] || null)}
/>
</div>
)
}
if (valueType === 'boolean') {
return (
<label className="board-ai-panel__field" key={parameter.id} style={{ flexDirection: 'row', alignItems: 'center', gap: '0.5rem' }}>
<input
type="checkbox"
checked={Boolean(value)}
onChange={(e) => setInputValue(parameter.id, e.target.checked)}
/>
<span className="board-ai-panel__label" style={{ margin: 0 }}>{label}</span>
</label>
)
}
const enumOptions = getWorkflowEnumOptions(parameter, value)
if (enumOptions) {
return (
<div className="board-ai-panel__field" key={parameter.id}>
<span className="board-ai-panel__label">{label}</span>
<select
className="board-ai-panel__select"
value={value == null ? '' : String(value)}
onChange={(e) => setInputValue(parameter.id, resolveWorkflowEnumValue(parameter, e.target.value))}
>
{enumOptions.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
</div>
)
}
if (valueType === 'number') {
return (
<div className="board-ai-panel__field" key={parameter.id}>
<span className="board-ai-panel__label">{label}</span>
<input
className="board-ai-panel__input"
type="number"
value={value ?? ''}
onChange={(e) => setInputValue(parameter.id, e.target.value === '' ? '' : Number(e.target.value))}
/>
</div>
)
}
// string / json / anything else — multiline like the Graph Image node.
return (
<div className="board-ai-panel__field" key={parameter.id}>
<span className="board-ai-panel__label">{label}</span>
<textarea
className="board-ai-panel__textarea"
value={typeof value === 'string' ? value : (value == null ? '' : JSON.stringify(value, null, 2))}
onChange={(e) => setInputValue(parameter.id, e.target.value)}
/>
</div>
)
}
return (
<aside className="board-ai-panel">
<div className="board-ai-panel__head">
<div className="board-ai-panel__title">Generate images</div>
<div className="board-ai-panel__subtitle">Saved to Assets and placed on the board</div>
</div>
<div className="board-ai-panel__body">
<div className="board-ai-panel__tabs">
<button
type="button"
className={`board-ai-panel__tab ${tab === 'comfy' ? 'board-ai-panel__tab--active' : ''}`}
onClick={() => setTab('comfy')}
>
ComfyUI
</button>
<button
type="button"
className={`board-ai-panel__tab ${tab === 'api' ? 'board-ai-panel__tab--active' : ''}`}
onClick={() => setTab('api')}
>
External API
</button>
</div>
{tab === 'comfy' ? (
<>
<div className="board-ai-panel__field">
<span className="board-ai-panel__label">Workflow</span>
<select
className="board-ai-panel__select"
value={selectedWorkflowId}
onChange={(e) => handleSelectWorkflow(e.target.value)}
>
<option value="">Select a workflow…</option>
{workflows.map(wf => (
<option key={wf.id} value={wf.id}>{wf.name}</option>
))}
</select>
{workflows.length === 0 && (
<span className="board-ai-panel__hint" style={{ marginTop: '0.3rem' }}>
No image workflows found. Import one from the Assets library.
</span>
)}
</div>
{selectedWorkflow && (
<>
<div className="board-ai-panel__field">
<span className="board-ai-panel__label">Image name (optional)</span>
<input
className="board-ai-panel__input"
value={comfyName}
onChange={(e) => setComfyName(e.target.value)}
placeholder={selectedWorkflow.name}
/>
</div>
{(selectedWorkflow.parameters || []).map(renderParameterField)}
</>
)}
<button className="board-ai-panel__run" onClick={runComfy} disabled={running || !selectedWorkflow}>
{running ? 'Working…' : 'Run workflow'}
</button>
</>
) : (
<>
<div className="board-ai-panel__field">
<span className="board-ai-panel__label">API</span>
<select
className="board-ai-panel__select"
value={selectedApi}
onChange={(e) => setSelectedApi(e.target.value)}
>
{imageApis.map(api => (
<option key={api.id} value={api.id}>{api.name}</option>
))}
</select>
</div>
<div className="board-ai-panel__field">
<span className="board-ai-panel__label">Image name</span>
<input
className="board-ai-panel__input"
value={apiName}
onChange={(e) => setApiName(e.target.value)}
placeholder="Concept sketch"
/>
</div>
<div className="board-ai-panel__field">
<span className="board-ai-panel__label">Prompt</span>
<textarea
className="board-ai-panel__textarea"
value={apiPrompt}
onChange={(e) => setApiPrompt(e.target.value)}
placeholder="Describe the image to generate…"
/>
</div>
<button className="board-ai-panel__run" onClick={runApi} disabled={running}>
{running ? 'Working…' : 'Generate image'}
</button>
</>
)}
{status && (
<div className={`board-ai-panel__status ${status.tone === 'error' ? 'board-ai-panel__status--error' : ''}`}>
{status.message}
</div>
)}
</div>
{assetPickerParam && (
<AssetSelectorModal
assetType={assetPickerParam.valueType === 'mesh' ? 'mesh' : 'image'}
showEdits
onSelect={async (asset) => {
const picker = assetPickerParam
setAssetPickerParam(null)
if (!asset) return
try {
// Resolve to the right reference: edits nest under the root ancestor;
// roots reuse the project asset or attach a library file if needed.
await bindSourceForParam(
picker.paramId,
picker.valueType,
asset.filename || asset.filePath,
asset.name
)
} catch (err) {
console.error('Failed to use selected asset for board input', err)
flash(err.message || 'Failed to use the selected asset.', 'error')
}
}}
onClose={() => setAssetPickerParam(null)}
/>
)}
</aside>
)
}

View file

@ -1,158 +0,0 @@
import { useEffect, useRef, useState } from 'react'
export default function BoardSwitcher({
projectId,
boards = [],
currentBoard,
onBoardsChanged,
createBoard,
updateBoard,
deleteBoard,
onSelect
}) {
const [open, setOpen] = useState(false)
const [renamingId, setRenamingId] = useState(null)
const [renameValue, setRenameValue] = useState('')
const [busy, setBusy] = useState(false)
const rootRef = useRef(null)
useEffect(() => {
if (!open) return undefined
const onPointerDown = (event) => {
if (rootRef.current && !rootRef.current.contains(event.target)) {
setOpen(false)
setRenamingId(null)
}
}
document.addEventListener('mousedown', onPointerDown)
return () => document.removeEventListener('mousedown', onPointerDown)
}, [open])
const handleCreate = async () => {
if (busy) return
setBusy(true)
try {
const name = `Board ${boards.length + 1}`
const created = await createBoard(projectId, name)
onBoardsChanged()
setOpen(false)
onSelect(created.id)
} catch (err) {
console.error('Failed to create board', err)
} finally {
setBusy(false)
}
}
const startRename = (board) => {
setRenamingId(board.id)
setRenameValue(board.name)
}
const commitRename = async (board) => {
const name = renameValue.trim()
setRenamingId(null)
if (!name || name === board.name) return
try {
await updateBoard(board.id, { name })
onBoardsChanged()
} catch (err) {
console.error('Failed to rename board', err)
}
}
const handleDelete = async (board) => {
if (boards.length <= 1) {
window.alert('A project must keep at least one board.')
return
}
if (!window.confirm(`Delete board "${board.name}"? This cannot be undone.`)) return
try {
await deleteBoard(board.id)
const remaining = boards.filter(b => String(b.id) !== String(board.id))
onBoardsChanged()
if (String(board.id) === String(currentBoard?.id) && remaining[0]) {
onSelect(remaining[0].id)
}
} catch (err) {
console.error('Failed to delete board', err)
}
}
return (
<div className="board-switcher" ref={rootRef}>
<button
type="button"
className="board-switcher__current"
onClick={() => setOpen(o => !o)}
title="Switch board"
>
<span className="material-symbols-outlined" style={{ fontSize: '18px' }}>dashboard</span>
<span className="board-switcher__name">{currentBoard?.name || 'Select board'}</span>
<span className="material-symbols-outlined" style={{ fontSize: '18px' }}>expand_more</span>
</button>
<button type="button" className="board-switcher__btn" onClick={handleCreate} disabled={busy}>
<span className="material-symbols-outlined" style={{ fontSize: '16px' }}>add</span>
New
</button>
{open && (
<div className="board-switcher__menu" role="menu">
{boards.map(board => {
const isActive = String(board.id) === String(currentBoard?.id)
const isRenaming = renamingId === board.id
return (
<div
key={board.id}
className={`board-switcher__item ${isActive ? 'board-switcher__item--active' : ''}`}
onClick={() => {
if (isRenaming) return
setOpen(false)
onSelect(board.id)
}}
>
{isRenaming ? (
<input
className="board-switcher__input"
value={renameValue}
autoFocus
onClick={(e) => e.stopPropagation()}
onChange={(e) => setRenameValue(e.target.value)}
onBlur={() => commitRename(board)}
onKeyDown={(e) => {
if (e.key === 'Enter') commitRename(board)
if (e.key === 'Escape') setRenamingId(null)
}}
/>
) : (
<>
<span className="board-switcher__name">{board.name}</span>
<span className="board-switcher__item-actions">
<button
type="button"
className="board-switcher__icon-btn"
title="Rename board"
onClick={(e) => { e.stopPropagation(); startRename(board) }}
>
<span className="material-symbols-outlined" style={{ fontSize: '16px' }}>edit</span>
</button>
<button
type="button"
className="board-switcher__icon-btn"
title="Delete board"
onClick={(e) => { e.stopPropagation(); handleDelete(board) }}
>
<span className="material-symbols-outlined" style={{ fontSize: '16px' }}>delete</span>
</button>
</span>
</>
)}
</div>
)
})}
</div>
)}
</div>
)
}

View file

@ -13,7 +13,6 @@ import {
createComfyExecutionId
} from '../../utils/graphHelpers'
import { getComfyDraftFromWorkflow } from '../../utils/kanbanHelpers'
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
import { buildAssetUrl } from '../../utils/meshTexturing'
import './ComfyTextGenModal.css'
@ -325,24 +324,6 @@ export default function ComfyTextGenModal({ open, onClose, onResult }) {
)
}
const enumOptions = getWorkflowEnumOptions(parameter, value)
if (enumOptions) {
return (
<div key={parameter.id} className="comfy-tg-field">
<label className="comfy-tg-label">{parameter.name} • {valueType.toUpperCase()}</label>
<select
className="comfy-tg-input"
value={value == null ? '' : String(value)}
onChange={event => handleInputChange(parameter, resolveWorkflowEnumValue(parameter, event.target.value))}
>
{enumOptions.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
</div>
)
}
if (valueType === 'number') {
return (
<div key={parameter.id} className="comfy-tg-field">

View file

@ -42,7 +42,6 @@ import {
resolveImageSourceOption,
resolveSelectedInputSource
} from '../../utils/graphHelpers'
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
import ComfyTextButton from '../comfy/ComfyTextButton'
import LastActionInfo from './LastActionInfo'
@ -179,21 +178,6 @@ const GraphAssetNode = memo(function GraphAssetNode({ data }) {
)
}
const enumOptions = getWorkflowEnumOptions(parameter, currentValue)
if (enumOptions) {
return (
<select
className="params-card__select nodrag"
value={currentValue === undefined || currentValue === null ? '' : String(currentValue)}
onChange={event => data.onDraftInputChange?.(data.id, parameter, resolveWorkflowEnumValue(parameter, event.target.value))}
>
{enumOptions.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
)
}
if (valueType === 'string' || parameter.type === 'json') {
return (
<div className="comfy-textfield-wrap nodrag">

View file

@ -14,7 +14,6 @@ import {
isFileWorkflowValueType,
resolveSelectedInputSource
} from '../../utils/graphHelpers'
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
import ComfyTextButton from '../comfy/ComfyTextButton'
import LastActionInfo from './LastActionInfo'
@ -78,21 +77,6 @@ const GraphValueNode = memo(function GraphValueNode({ data }) {
)
}
const enumOptions = getWorkflowEnumOptions(parameter, currentValue)
if (enumOptions) {
return (
<select
className="params-card__select nodrag"
value={currentValue === undefined || currentValue === null ? '' : String(currentValue)}
onChange={event => data.onDraftInputChange?.(data.id, parameter, resolveWorkflowEnumValue(parameter, event.target.value))}
>
{enumOptions.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
)
}
if (valueType === 'string' || parameter.type === 'json') {
return (
<div className="comfy-textfield-wrap nodrag">

View file

@ -1,29 +1,10 @@
// Renders a single non-image ComfyUI workflow parameter (boolean checkbox or
// text/number input). Shared by the AI control panels. Presentational.
import { getValueType } from '../../../utils/imageEditorCanvas'
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../../utils/workflowEnums'
import ComfyTextButton from '../../comfy/ComfyTextButton'
export default function WorkflowParameterField({ parameter, value, onChange }) {
const valueType = getValueType(parameter)
const enumOptions = getWorkflowEnumOptions(parameter, value)
if (enumOptions) {
return (
<label className="image-editor-label">
{parameter.name}
<select
className="image-editor-input"
value={value == null ? '' : String(value)}
onChange={event => onChange(parameter.id, resolveWorkflowEnumValue(parameter, event.target.value))}
>
{enumOptions.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
</label>
)
}
if (valueType === 'boolean') {
return (

View file

@ -11,7 +11,6 @@ import {
isTencentMeshGenerationApi,
isTripoMeshGenerationApi
} from '../../utils/kanbanHelpers'
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
// A single Kanban board card (image / image-edit / mesh-gen / mesh-edit / texturing).
// Presentational: all board state, derived selectors, and handlers are passed in
@ -52,7 +51,6 @@ export default function KanbanImageCard({
handleCardDragStart,
handleCardDragEnd,
openImageSourceMenu,
openMeshSourceMenu,
handleRemoveImageCard,
openMeshPreview,
handleRemoveImage,
@ -88,12 +86,9 @@ export default function KanbanImageCard({
const isMeshWorkflowCard = isMeshGenCard || isMeshEditCard || isTexturingCard || isRiggingCard
const carouselItems = getCardPreviewItems(card, showAttributes)
const useAssetCarousel = carouselItems.length > 0
const previewAssets = useAssetCarousel
? card.assets
: isMeshWorkflowCard && (card.meshAssets?.length || 0) > 0
? card.meshAssets
// Images column: meshes attached via "Add more meshes" sit alongside the images.
: (card.allAssets?.length ? card.allAssets : card.assets)
const previewAssets = isMeshWorkflowCard && (card.meshAssets?.length || 0) > 0 && !useAssetCarousel
? card.meshAssets
: card.assets
const totalPages = useAssetCarousel
? Math.max(1, carouselItems.length)
: Math.max(1, Math.ceil(previewAssets.length / 4))
@ -119,28 +114,19 @@ export default function KanbanImageCard({
onDragEnd={handleCardDragEnd}
>
<div className="image-card__actions">
<button
className="image-card__action-btn"
disabled={cardLocked}
onClick={(e) => {
e.stopPropagation()
openMeshSourceMenu(card.id)
}}
title="Add more meshes"
>
<span className="material-symbols-outlined" style={{ fontSize: '16px' }}>deployed_code</span>
</button>
<button
className="image-card__action-btn"
disabled={cardLocked}
onClick={(e) => {
e.stopPropagation()
openImageSourceMenu(card.id)
}}
title="Add more images"
>
<span className="material-symbols-outlined" style={{ fontSize: '16px' }}>add_photo_alternate</span>
</button>
{!showAttributes && (
<button
className="image-card__action-btn"
disabled={cardLocked}
onClick={(e) => {
e.stopPropagation()
openImageSourceMenu(card.id)
}}
title="Add more images"
>
<span className="material-symbols-outlined" style={{ fontSize: '16px' }}>add_photo_alternate</span>
</button>
)}
<button
className="image-card__action-btn image-card__delete"
disabled={cardLocked}
@ -162,12 +148,9 @@ export default function KanbanImageCard({
? Math.min(imageEditPreviewIndexes[asset.id] || 0, Math.max(0, displayItems.length - 1))
: 0
const previewItem = showAttributes ? (displayItems[previewIndex] || displayItems[0]) : asset
// Meshes rendered outside the carousel carry their thumbnail on
// `thumbnail`; the carousel pre-resolves it into `previewFilename`.
const meshThumbnail = useAssetCarousel ? asset.previewFilename : (asset.type === 'mesh' ? asset.thumbnail : null)
const previewFilename = useAssetCarousel
? (asset.previewFilename || asset.filename)
: (showAttributes ? previewItem?.filename : (meshThumbnail || asset.filename))
: (showAttributes ? previewItem?.filename : asset.filename)
const previewName = useAssetCarousel
? asset.name
: (showAttributes ? previewItem?.name : asset.name)
@ -198,7 +181,7 @@ export default function KanbanImageCard({
} : undefined}
>
{previewType === 'mesh' && previewUrl ? (
meshThumbnail ? (
asset.previewFilename ? (
<img
src={previewUrl}
alt={previewName}
@ -230,13 +213,13 @@ export default function KanbanImageCard({
e.stopPropagation()
handleRemoveImage(asset.id)
}}
title={previewType === 'mesh' ? 'Remove mesh' : 'Remove image'}
title="Remove image"
>
<span className="material-symbols-outlined" style={{ fontSize: '14px' }}>close</span>
</button>
)}
{useAssetCarousel && previewType === 'mesh' && sourceAsset?.id && (
{previewType === 'mesh' && sourceAsset?.id && (
<button
className="image-card__thumb-remove image-card__thumb-remove--left"
disabled={cardLocked}
@ -604,12 +587,6 @@ export default function KanbanImageCard({
}
const sourceOptions = getAttributeOptionsForCard(card.id, valueType === 'number' ? 'Number' : 'Text')
// An attribute-bound value is shown read-only, so the dropdown
// reflects whichever value is actually in play.
const enumSelectValue = binding.source === 'custom'
? (binding.customValue == null ? '' : String(binding.customValue))
: String(resolvedValue ?? '')
const enumOptions = getWorkflowEnumOptions(parameter, enumSelectValue)
return (
<div key={parameter.id} className="params-card__field">
@ -623,18 +600,7 @@ export default function KanbanImageCard({
<option key={option.id} value={option.id}>{option.label}</option>
))}
</select>
{enumOptions ? (
<select
className="image-card__attribute-select"
value={enumSelectValue}
onChange={event => handleImageEditParameterValueChange(card, parameter, resolveWorkflowEnumValue(parameter, event.target.value))}
disabled={binding.source !== 'custom'}
>
{enumOptions.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
) : valueType === 'string' ? (
{valueType === 'string' ? (
<div className="comfy-textfield-wrap">
<textarea
className="gen-prompt-input image-card__param-textarea"

View file

@ -1,5 +1,4 @@
import { getWorkflowValueType } from '../../utils/meshTexturing'
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
import ComfyTextButton from '../comfy/ComfyTextButton'
// Projection-mode left panel (projection setup, AI workflow + image-input
@ -190,26 +189,11 @@ export default function ProjectionToolsPanel({
{projectionWorkflowParameters.map(parameter => {
const valueType = getWorkflowValueType(parameter)
const currentValue = projectionWorkflowInputs?.[parameter.id]
const enumOptions = getWorkflowEnumOptions(parameter, currentValue)
return (
<label key={parameter.id} className="mesh-editor-workflow-field">
<span>{parameter.name}</span>
{enumOptions ? (
<select
className="mesh-editor-panel__input"
value={currentValue == null ? '' : String(currentValue)}
onChange={event => setProjectionWorkflowInputs(current => ({
...current,
[parameter.id]: resolveWorkflowEnumValue(parameter, event.target.value)
}))}
disabled={!!texturingUnavailableReason || projecting || projectionRebuilding}
>
{enumOptions.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
) : valueType === 'boolean' ? (
{valueType === 'boolean' ? (
<button
type="button"
className={`mesh-editor-toggle ${currentValue ? 'mesh-editor-toggle--active' : ''}`}

View file

@ -1,5 +1,4 @@
import { getWorkflowValueType } from '../../utils/meshTexturing'
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../../utils/workflowEnums'
import ComfyTextButton from '../comfy/ComfyTextButton'
// Texturing-mode left panel (brush/crop/feather, AI workflow + image-input
@ -163,23 +162,11 @@ export default function TexturingToolsPanel({
{textureWorkflowParameters.map(parameter => {
const valueType = getWorkflowValueType(parameter)
const currentValue = textureWorkflowInputs?.[parameter.id]
const enumOptions = getWorkflowEnumOptions(parameter, currentValue)
return (
<label key={parameter.id} className="mesh-editor-workflow-field">
<span>{parameter.name}</span>
{enumOptions ? (
<select
className="mesh-editor-panel__input"
value={currentValue == null ? '' : String(currentValue)}
onChange={event => handleTextureWorkflowInputChange(parameter, resolveWorkflowEnumValue(parameter, event.target.value))}
disabled={!!texturingUnavailableReason || !!pendingPatch}
>
{enumOptions.map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
) : valueType === 'boolean' ? (
{valueType === 'boolean' ? (
<button
type="button"
className={`mesh-editor-toggle ${currentValue ? 'mesh-editor-toggle--active' : ''}`}

View file

@ -500,69 +500,6 @@ export function ProjectProvider({ children }) {
await fetchProjects()
}
// ---- Brainstorming Boards ------------------------------------------------
const getProjectBoards = async (projectId) => {
const res = await fetch(`${API_BASE}/boards?projectId=${projectId}`)
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Failed to load boards')
return data
}
const getBoard = async (boardId) => {
const res = await fetch(`${API_BASE}/boards/${boardId}`)
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Failed to load board')
return data
}
const createBoard = async (projectId, name = 'Untitled Board') => {
const res = await fetch(`${API_BASE}/boards`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ projectId, name })
})
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Failed to create board')
return data
}
const updateBoard = async (boardId, patch) => {
const res = await fetch(`${API_BASE}/boards/${boardId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(patch)
})
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Failed to update board')
return data
}
// Save used by the board's debounced autosave. Never throws into the render
// path (mirrors saveGraphViewport); returns true on success so the UI can
// surface a save indicator.
const saveBoardState = async (boardId, state) => {
try {
const res = await fetch(`${API_BASE}/boards/${boardId}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ state })
})
return res.ok
} catch (err) {
console.error('Failed to save board state:', err)
return false
}
}
const deleteBoard = async (boardId) => {
const res = await fetch(`${API_BASE}/boards/${boardId}`, { method: 'DELETE' })
if (!res.ok && res.status !== 204) {
const data = await res.json().catch(() => ({}))
throw new Error(data?.error || 'Failed to delete board')
}
}
const exportProject = async (id, { folder, name }) => {
const res = await fetch(`${API_BASE}/projects/${id}/export`, {
method: 'POST',
@ -590,9 +527,8 @@ export function ProjectProvider({ children }) {
return data
}
const getProjectAssets = async (projectId, { includeChildren = false } = {}) => {
const query = includeChildren ? '&includeChildren=true' : ''
const res = await fetch(`${API_BASE}/assets?projectId=${projectId}${query}`)
const getProjectAssets = async (projectId) => {
const res = await fetch(`${API_BASE}/assets?projectId=${projectId}`)
return await res.json()
}
@ -853,16 +789,6 @@ export function ProjectProvider({ children }) {
return await res.json();
}
// Resolve a file (served filename or stored path) to a workflow source
// reference (edit: for edits, asset: for roots) so board edits nest correctly.
const resolveAssetSourceReference = async (projectId, type, filePath) => {
const params = new URLSearchParams({ projectId: String(projectId), type: type || 'image', filePath })
const res = await fetch(`${API_BASE}/assets/resolve-source?${params.toString()}`)
const data = await res.json()
if (!res.ok) throw new Error(data?.error || 'Failed to resolve asset source')
return data
}
const attachExistingAsset = async (projectId, assetData) => {
const res = await fetch(`${API_BASE}/assets/link`, {
method: 'POST',
@ -879,39 +805,6 @@ export function ProjectProvider({ children }) {
return data
}
// Attach any EXISTING asset — a root, an image edit or a mesh version — to a
// project. Membership lives in Assets_Projects, so this needs no card.
const linkAssetToProject = async (projectId, assetId, { cascadeChildren = false } = {}) => {
const res = await fetch(`${API_BASE}/projects/${projectId}/assets`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ assetId, cascadeChildren })
})
const data = await res.json().catch(() => ({}))
if (!res.ok) {
throw new Error(data?.error || 'Failed to link asset to project')
}
return data
}
const unlinkAssetFromProject = async (projectId, assetId, { cascadeChildren = true } = {}) => {
const query = cascadeChildren ? '' : '?cascadeChildren=false'
const res = await fetch(`${API_BASE}/projects/${projectId}/assets/${assetId}${query}`, {
method: 'DELETE'
})
const data = await res.json().catch(() => ({}))
if (!res.ok) {
throw new Error(data?.error || 'Failed to unlink asset from project')
}
return data
}
const deleteLibraryAsset = async ({ type, filename, force = false }) => {
const params = new URLSearchParams({ type, filename })
if (force) {
@ -937,9 +830,8 @@ export function ProjectProvider({ children }) {
return data
}
const deleteAsset = async (assetId, { projectId = null } = {}) => {
const query = projectId ? `?projectId=${projectId}` : ''
const res = await fetch(`${API_BASE}/assets/${assetId}${query}`, { method: 'DELETE' })
const deleteAsset = async (assetId) => {
const res = await fetch(`${API_BASE}/assets/${assetId}`, { method: 'DELETE' })
if (!res.ok) {
const data = await res.json().catch(() => ({}))
@ -1113,9 +1005,6 @@ export function ProjectProvider({ children }) {
if (workflowData.persistGeneratedAssets === false) {
formData.append('persistGeneratedAssets', 'false')
}
if (workflowData.detachedAsset === true) {
formData.append('detachedAsset', 'true')
}
// The app manages its own edit/version saving (e.g. image edits via
// /image-edits/comfy, mesh versions via an explicit parentAssetId), and its
// generate flows must create new root assets — so opt out of the server's
@ -1328,12 +1217,6 @@ export function ProjectProvider({ children }) {
deleteProject,
exportProject,
importProject,
getProjectBoards,
getBoard,
createBoard,
updateBoard,
saveBoardState,
deleteBoard,
getProjectAssets,
getProjectCards,
getProjectNodes,
@ -1353,9 +1236,6 @@ export function ProjectProvider({ children }) {
getPaintDocument,
savePaintDocument,
attachExistingAsset,
linkAssetToProject,
unlinkAssetFromProject,
resolveAssetSourceReference,
deleteAsset,
moveKanbanCard,
deleteCard,

View file

@ -151,7 +151,6 @@ export function SettingsProvider({ children }) {
},
comfyui: {
path: '',
modelsPath: '',
url: 'http://127.0.0.1',
port: '8188'
},

View file

@ -519,23 +519,6 @@
color: var(--on-surface);
}
.library-textarea {
resize: vertical;
min-height: 4.5rem;
font-family: inherit;
line-height: 1.4;
}
/* Enum editor: label + textarea + hint sit tighter than a top-level form field. */
.library-selected-item .library-field {
gap: 0.35rem;
}
.library-hint {
font-size: 0.72rem;
color: var(--on-surface-variant);
}
.library-config-fields,
.library-config-actions,
.library-workflow-card__actions,

View file

@ -8,11 +8,6 @@ import { useProjects } from '../context/ProjectContext'
import { createMeshThumbnailFile, isMeshFile } from '../utils/meshThumbnail'
import { parseAbrFile } from '../utils/brushAbr'
import { downloadShareableWorkflow, isShareableWorkflow } from '../utils/workflowShare'
import {
formatWorkflowEnumsInput,
isEnumWorkflowValueType,
parseWorkflowEnumsInput
} from '../utils/workflowEnums'
import './AssetsPage.css'
const ASSETS_PER_PAGE = 20
@ -79,8 +74,7 @@ function createSelectionMap(items, getLabel, isOutput = false, selected = false)
{
selected,
name: getLabel(item),
valueType: getDefaultValueType(item, isOutput),
enumsText: formatWorkflowEnumsInput(item?.enums)
valueType: getDefaultValueType(item, isOutput)
}
])
)
@ -98,8 +92,7 @@ function hydrateWorkflowSelection(workflow) {
{
selected: Boolean(selectedParameter),
name: selectedParameter?.name || input.name,
valueType: getDefaultValueType(selectedParameter || input),
enumsText: formatWorkflowEnumsInput(selectedParameter?.enums)
valueType: getDefaultValueType(selectedParameter || input)
}
]
})
@ -134,8 +127,7 @@ function selectWorkflowItem(setter, key, name, valueType) {
[key]: {
selected: true,
name: prev[key]?.name || name,
valueType: prev[key]?.valueType || valueType,
enumsText: prev[key]?.enumsText || ''
valueType: prev[key]?.valueType || valueType
}
}))
}
@ -462,15 +454,8 @@ export default function AssetsPage() {
// An asset can be linked to multiple projects, so resolve every project key it
// belongs to (falling back to the single projectId, then "Unassigned").
// Edits/versions carry their own project links, and an asset shown here is a
// root — so a root also counts as belonging to every project one of its
// children was attached to, otherwise attaching an edit would show nothing.
const getAssetProjectKeys = useCallback((asset) => {
const ids = [
...(Array.isArray(asset?.projectIds) ? asset.projectIds : []),
...(Array.isArray(asset?.children) ? asset.children : [])
.flatMap(child => (Array.isArray(child?.projectIds) ? child.projectIds : []))
]
const ids = Array.isArray(asset?.projectIds) ? asset.projectIds : []
const keys = [...new Set(
ids.filter(id => id !== null && id !== undefined).map(id => String(id))
)]
@ -1112,17 +1097,11 @@ export default function AssetsPage() {
const buildWorkflowPayload = () => {
const parameters = (inspectedWorkflow?.inputs || [])
.filter(input => selectedInputs[input.id]?.selected)
.map(input => {
const valueType = selectedInputs[input.id]?.valueType || getDefaultValueType(input)
return {
id: input.id,
name: selectedInputs[input.id]?.name || input.name,
valueType,
// Always sent so emptying the field clears a previously saved list.
enums: parseWorkflowEnumsInput(selectedInputs[input.id]?.enumsText, valueType)
}
})
.map(input => ({
id: input.id,
name: selectedInputs[input.id]?.name || input.name,
valueType: selectedInputs[input.id]?.valueType || getDefaultValueType(input)
}))
const outputs = (inspectedWorkflow?.outputs || [])
.filter(output => selectedOutputs[output.nodeId]?.selected)
@ -1685,30 +1664,6 @@ export default function AssetsPage() {
))}
</select>
</div>
{/* JSON inputs resolve to the String value type but are parsed as
JSON at run time, so they never get an allowed-value list. */}
{input.type !== 'json' && isEnumWorkflowValueType(selectedInputs[input.id]?.valueType || getDefaultValueType(input)) && (
<div className="library-field">
<label className="library-label">Allowed Values (optional)</label>
<textarea
className="library-input library-textarea"
rows={3}
value={selectedInputs[input.id]?.enumsText || ''}
onChange={event => setSelectedInputs(prev => ({
...prev,
[input.id]: {
...prev[input.id],
enumsText: event.target.value
}
}))}
placeholder={'1024\n1536'}
/>
<span className="library-hint">
One value per line. Leave empty for a free-form field; two or more values turn it into a dropdown everywhere the workflow is used.
</span>
</div>
)}
</div>
))}
</div>

View file

@ -1,357 +0,0 @@
.board-page {
display: flex;
flex-direction: column;
height: 100vh;
background: var(--background);
color: var(--on-surface);
overflow: hidden;
}
.board-page__bar {
display: flex;
align-items: center;
gap: 0.75rem;
padding: 0.5rem 1rem;
border-bottom: 1px solid var(--outline-variant);
background: var(--surface-container-low);
flex: 0 0 auto;
}
.board-page__save {
font-size: 0.78rem;
font-family: var(--font-label);
color: var(--on-surface-variant);
margin-left: 0.25rem;
}
.board-page__save--saving { color: var(--primary-dim); }
.board-page__save--saved { color: var(--on-surface-variant); }
.board-page__save--error { color: var(--error); }
.board-page__body {
flex: 1 1 auto;
display: flex;
min-height: 0;
}
.board-page__canvas {
position: relative;
flex: 1 1 auto;
min-width: 0;
height: 100%;
}
/* Excalidraw needs an explicitly sized host. */
.board-page__canvas .excalidraw {
height: 100%;
width: 100%;
}
.board-page__loading,
.board-page__empty,
.board-page__error {
display: grid;
place-items: center;
height: 100%;
color: var(--on-surface-variant);
font-family: var(--font-body);
}
.board-page__error {
height: auto;
padding: 0.5rem 1rem;
color: var(--on-error-container);
background: var(--error-container);
place-items: start;
}
/* ── Board switcher ──────────────────────────────────────── */
.board-switcher {
display: flex;
align-items: center;
gap: 0.5rem;
position: relative;
}
.board-switcher__current {
display: inline-flex;
align-items: center;
gap: 0.4rem;
padding: 0.35rem 0.7rem;
border: 1px solid var(--outline-variant);
border-radius: var(--radius-md);
background: var(--surface-container);
color: var(--on-surface);
font-family: var(--font-label);
font-size: 0.9rem;
cursor: pointer;
max-width: 260px;
}
.board-switcher__current:hover {
border-color: var(--outline);
}
.board-switcher__name {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.board-switcher__menu {
position: absolute;
top: calc(100% + 4px);
left: 0;
z-index: 40;
min-width: 240px;
max-height: 340px;
overflow-y: auto;
padding: 0.35rem;
border: 1px solid var(--outline-variant);
border-radius: var(--radius-md);
background: var(--surface-container-high);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
}
.board-switcher__item {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.5rem;
padding: 0.4rem 0.5rem;
border-radius: var(--radius-sm);
cursor: pointer;
color: var(--on-surface);
font-size: 0.88rem;
}
.board-switcher__item:hover {
background: var(--surface-container-highest);
}
.board-switcher__item--active {
background: var(--surface-variant);
}
.board-switcher__item-actions {
display: flex;
gap: 0.15rem;
opacity: 0;
}
.board-switcher__item:hover .board-switcher__item-actions {
opacity: 1;
}
.board-switcher__icon-btn,
.board-switcher__btn {
display: inline-flex;
align-items: center;
gap: 0.3rem;
border: 1px solid var(--outline-variant);
border-radius: var(--radius-sm);
background: var(--surface-container);
color: var(--on-surface);
cursor: pointer;
font-family: var(--font-label);
}
.board-switcher__icon-btn {
padding: 0.25rem;
border-color: transparent;
background: transparent;
color: var(--on-surface-variant);
}
.board-switcher__icon-btn:hover {
color: var(--on-surface);
background: var(--surface-container-lowest);
}
.board-switcher__btn {
padding: 0.35rem 0.6rem;
font-size: 0.85rem;
}
.board-switcher__btn:hover {
border-color: var(--outline);
}
.board-switcher__input {
flex: 1;
padding: 0.3rem 0.4rem;
border: 1px solid var(--outline);
border-radius: var(--radius-sm);
background: var(--surface-container-lowest);
color: var(--on-surface);
font-size: 0.85rem;
}
/* ── AI panel ────────────────────────────────────────────── */
.board-ai-panel {
flex: 0 0 320px;
width: 320px;
height: 100%;
display: flex;
flex-direction: column;
border-left: 1px solid var(--outline-variant);
background: var(--surface-container-low);
overflow-y: auto;
}
.board-ai-panel__head {
padding: 0.75rem 1rem;
border-bottom: 1px solid var(--outline-variant);
}
.board-ai-panel__title {
font-family: var(--font-headline);
font-size: 1rem;
color: var(--on-surface);
}
.board-ai-panel__subtitle {
font-size: 0.75rem;
color: var(--on-surface-variant);
margin-top: 0.15rem;
}
.board-ai-panel__body {
padding: 0.85rem 1rem;
display: flex;
flex-direction: column;
gap: 0.75rem;
}
.board-ai-panel__tabs {
display: flex;
gap: 0.35rem;
}
.board-ai-panel__tab {
flex: 1;
padding: 0.4rem;
border: 1px solid var(--outline-variant);
border-radius: var(--radius-md);
background: var(--surface-container);
color: var(--on-surface-variant);
font-family: var(--font-label);
font-size: 0.8rem;
cursor: pointer;
}
.board-ai-panel__tab--active {
border-color: var(--primary);
color: var(--on-surface);
background: var(--surface-variant);
}
.board-ai-panel__label {
display: block;
font-size: 0.72rem;
text-transform: uppercase;
letter-spacing: 0.04em;
color: var(--on-surface-variant);
margin-bottom: 0.3rem;
font-family: var(--font-label);
}
.board-ai-panel__field {
display: flex;
flex-direction: column;
}
.board-ai-panel__select,
.board-ai-panel__input,
.board-ai-panel__textarea {
width: 100%;
padding: 0.45rem 0.55rem;
border: 1px solid var(--outline-variant);
border-radius: var(--radius-md);
background: var(--surface-container-lowest);
color: var(--on-surface);
font-size: 0.85rem;
font-family: var(--font-body);
}
.board-ai-panel__textarea {
resize: vertical;
min-height: 76px;
}
.board-ai-panel__file-btn {
display: inline-flex;
align-items: center;
gap: 0.35rem;
padding: 0.4rem 0.55rem;
border: 1px dashed var(--outline);
border-radius: var(--radius-md);
background: var(--surface-container-lowest);
color: var(--on-surface-variant);
font-size: 0.8rem;
cursor: pointer;
width: 100%;
}
.board-ai-panel__file-btn--set {
border-style: solid;
color: var(--on-surface);
}
.board-ai-panel__file-actions {
display: flex;
flex-wrap: wrap;
gap: 0.6rem;
margin-top: 0.3rem;
}
.board-ai-panel__link-btn {
background: none;
border: none;
padding: 0;
color: var(--primary);
font-size: 0.75rem;
font-family: var(--font-label);
cursor: pointer;
text-decoration: underline;
}
.board-ai-panel__link-btn:hover {
color: var(--primary-dim);
}
.board-ai-panel__run {
margin-top: 0.25rem;
padding: 0.6rem;
border: none;
border-radius: var(--radius-md);
background: var(--primary);
color: var(--on-primary);
font-family: var(--font-label);
font-weight: 600;
font-size: 0.9rem;
cursor: pointer;
}
.board-ai-panel__run:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.board-ai-panel__status {
font-size: 0.8rem;
color: var(--on-surface-variant);
padding: 0.5rem 0.6rem;
border-radius: var(--radius-md);
background: var(--surface-container);
}
.board-ai-panel__status--error {
color: var(--on-error-container);
background: var(--error-container);
}
.board-ai-panel__hint {
font-size: 0.72rem;
color: var(--on-surface-variant);
}

View file

@ -1,396 +0,0 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useSearchParams } from 'react-router-dom'
import { Excalidraw, convertToExcalidrawElements } from '@excalidraw/excalidraw'
import '@excalidraw/excalidraw/index.css'
import Header from '../components/Header'
import Footer from '../components/Footer'
import SettingsModal from '../components/SettingsModal'
import BoardSwitcher from '../components/board/BoardSwitcher'
import BoardAiPanel from '../components/board/BoardAiPanel'
import { useProjects } from '../context/ProjectContext'
import { assetUrl } from '../config'
import {
sanitizeBoardAppState,
boardStateSignature,
urlToDataURL,
dataURLToFile,
measureImage,
mimeFromName,
extFromMime,
toServedAssetPath
} from '../utils/boardHelpers'
import './BoardPage.css'
const AUTOSAVE_DELAY = 800
export default function BoardPage() {
const [searchParams, setSearchParams] = useSearchParams()
const projectId = searchParams.get('projectId')
const boardId = searchParams.get('boardId')
const {
getProject,
getProjectBoards,
getBoard,
createBoard,
deleteBoard,
updateBoard,
saveBoardState,
uploadAsset
} = useProjects()
const [project, setProject] = useState(null)
const [boards, setBoards] = useState([])
const [board, setBoard] = useState(null)
const [initialData, setInitialData] = useState(null)
const [loadError, setLoadError] = useState('')
const [showSettings, setShowSettings] = useState(false)
const [saveStatus, setSaveStatus] = useState('idle') // 'idle' | 'saving' | 'saved' | 'error'
const excalidrawApiRef = useRef(null)
const bootstrappingRef = useRef(null) // projectId currently being bootstrapped (guards StrictMode double-run)
const imageRefsRef = useRef({}) // excalidraw fileId -> asset filename (url path)
const uploadingRef = useRef(new Set())
const lastSavedSigRef = useRef('')
const saveTimerRef = useRef(null)
const latestSceneRef = useRef(null) // latest { elements, appState } from onChange
const boardIdRef = useRef(null) // current boardId, so async saves target the right board
const selectedImageRef = useRef(null) // { fileId, filename } of the selected asset-backed image, or null
// ---- Load the project (name for the header) ------------------------------
useEffect(() => {
let cancelled = false
if (!projectId) return undefined
getProject(projectId)
.then(data => { if (!cancelled) setProject(data) })
.catch(() => { if (!cancelled) setProject(null) })
return () => { cancelled = true }
}, [projectId, getProject])
// ---- Load the project's boards + bootstrap a default when empty ----------
const refreshBoards = useCallback(async () => {
if (!projectId) return []
const list = await getProjectBoards(projectId)
setBoards(list)
return list
}, [projectId, getProjectBoards])
useEffect(() => {
let cancelled = false
if (!projectId) return undefined
;(async () => {
try {
let list = await getProjectBoards(projectId)
if (cancelled) return
// No board selected in the URL: open the first, or create one.
if (!boardId) {
if (list.length === 0) {
// Guard against StrictMode's double effect run creating two boards.
if (bootstrappingRef.current === projectId) return
bootstrappingRef.current = projectId
const created = await createBoard(projectId, 'Board 1')
list = [created]
}
if (cancelled) return
setBoards(list)
setSearchParams({ projectId, boardId: String(list[0].id) }, { replace: true })
return
}
setBoards(list)
} catch (err) {
if (!cancelled) setLoadError(err.message || 'Failed to load boards')
}
})()
return () => { cancelled = true }
}, [projectId, boardId, getProjectBoards, createBoard, setSearchParams])
// ---- Load the selected board + build Excalidraw initialData --------------
useEffect(() => {
let cancelled = false
if (!boardId) return undefined
setInitialData(null)
setSaveStatus('idle')
imageRefsRef.current = {}
uploadingRef.current = new Set()
latestSceneRef.current = null
boardIdRef.current = boardId
;(async () => {
try {
const data = await getBoard(boardId)
if (cancelled) return
setBoard(data)
const state = data?.state || {}
const elements = Array.isArray(state.elements) ? state.elements : []
const appState = sanitizeBoardAppState(state.appState || {})
const imageRefs = state.imageRefs && typeof state.imageRefs === 'object' ? state.imageRefs : {}
imageRefsRef.current = { ...imageRefs }
// Re-hydrate image binaries from their backing assets on disk.
const files = {}
await Promise.all(Object.entries(imageRefs).map(async ([fileId, filename]) => {
try {
const dataURL = await urlToDataURL(assetUrl(filename))
files[fileId] = { id: fileId, dataURL, mimeType: mimeFromName(filename), created: Date.now() }
} catch (err) {
console.error('Failed to load board image', filename, err)
}
}))
if (cancelled) return
lastSavedSigRef.current = boardStateSignature(elements, appState)
setInitialData({ elements, appState, files, scrollToContent: true })
} catch (err) {
if (!cancelled) setLoadError(err.message || 'Failed to load board')
}
})()
return () => { cancelled = true }
}, [boardId, getBoard])
// ---- Persist board state (debounced) -------------------------------------
// Saves from the latest onChange snapshot (falling back to the API) so it
// never silently no-ops if the API ref hasn't populated yet.
const persistNow = useCallback(async () => {
const targetBoardId = boardIdRef.current
if (!targetBoardId) return
let elements = latestSceneRef.current?.elements
let appState = latestSceneRef.current?.appState
if (!elements) {
const api = excalidrawApiRef.current
if (!api) return
elements = api.getSceneElements()
appState = api.getAppState()
}
elements = (elements || []).filter(el => !el.isDeleted)
appState = sanitizeBoardAppState(appState || {})
// Prune image refs whose element no longer exists on the canvas.
const liveFileIds = new Set(
elements.filter(el => el.type === 'image' && el.fileId).map(el => el.fileId)
)
const imageRefs = {}
for (const [fileId, filename] of Object.entries(imageRefsRef.current)) {
if (liveFileIds.has(fileId)) imageRefs[fileId] = filename
}
imageRefsRef.current = imageRefs
setSaveStatus('saving')
const ok = await saveBoardState(targetBoardId, { elements, appState, imageRefs })
setSaveStatus(ok ? 'saved' : 'error')
}, [saveBoardState])
const scheduleSave = useCallback(() => {
if (saveTimerRef.current) clearTimeout(saveTimerRef.current)
saveTimerRef.current = setTimeout(() => { saveTimerRef.current = null; persistNow() }, AUTOSAVE_DELAY)
}, [persistNow])
// ---- Upload pasted/dropped local images so they persist as assets --------
const backfillLocalImages = useCallback(async (elements, files) => {
if (!projectId || !files) return
const imageElements = elements.filter(el => el.type === 'image' && !el.isDeleted && el.fileId)
for (const el of imageElements) {
const fileId = el.fileId
if (imageRefsRef.current[fileId] || uploadingRef.current.has(fileId)) continue
const file = files[fileId]
if (!file?.dataURL) continue
uploadingRef.current.add(fileId)
try {
const ext = extFromMime(file.mimeType || 'image/png')
const uploadFile = dataURLToFile(file.dataURL, `board-${fileId}.${ext}`)
const asset = await uploadAsset(projectId, uploadFile, 'image', { source: 'board-upload' })
if (asset?.filename) {
imageRefsRef.current[fileId] = asset.filename
scheduleSave()
}
} catch (err) {
console.error('Failed to persist board image upload', err)
} finally {
uploadingRef.current.delete(fileId)
}
}
}, [projectId, uploadAsset, scheduleSave])
const handleChange = useCallback((elements, appState, files) => {
latestSceneRef.current = { elements, appState }
// Track the currently-selected asset-backed image (used by the AI panel's
// "Selected image" input option). Runs before the save early-return because
// selection changes don't alter the board-state signature.
const selectedIds = appState?.selectedElementIds || {}
const selectedImage = elements.find(el =>
el.type === 'image' && !el.isDeleted && el.fileId && selectedIds[el.id] && imageRefsRef.current[el.fileId]
)
selectedImageRef.current = selectedImage
? { fileId: selectedImage.fileId, filename: imageRefsRef.current[selectedImage.fileId] }
: null
const sig = boardStateSignature(elements, appState)
if (sig === lastSavedSigRef.current) return
lastSavedSigRef.current = sig
scheduleSave()
backfillLocalImages(elements, files)
}, [scheduleSave, backfillLocalImages])
const getSelectedBoardImage = useCallback(() => selectedImageRef.current, [])
// Flush a pending save on unmount / board switch.
useEffect(() => () => {
if (saveTimerRef.current) {
clearTimeout(saveTimerRef.current)
saveTimerRef.current = null
persistNow()
}
}, [persistNow])
// Flush on tab hide / close so in-flight edits aren't lost.
useEffect(() => {
const flush = () => {
if (saveTimerRef.current) {
clearTimeout(saveTimerRef.current)
saveTimerRef.current = null
persistNow()
}
}
window.addEventListener('pagehide', flush)
document.addEventListener('visibilitychange', flush)
return () => {
window.removeEventListener('pagehide', flush)
document.removeEventListener('visibilitychange', flush)
}
}, [persistNow])
// ---- Place an AI-generated (already-saved) asset onto the canvas ---------
const placeAssetImage = useCallback(async (asset) => {
const api = excalidrawApiRef.current
if (!api || !asset) return
// Edits return a stored filePath (with data/assets/ prefix) and no filename;
// normalize either to the served path so reload URLs resolve correctly.
const refPath = asset.filename || (asset.filePath ? toServedAssetPath(asset.filePath) : null)
try {
// ComfyUI results carry an absolute `url`; external-API/persisted assets
// resolve from their served filename. Either way we render from a data URL.
const src = (typeof asset.url === 'string' && /^(https?:|data:)/i.test(asset.url))
? asset.url
: (refPath ? assetUrl(refPath) : null)
if (!src) return
const dataURL = src.startsWith('data:') ? src : await urlToDataURL(src)
const fileId = `board-asset-${asset.id || Date.now()}`
api.addFiles([{ id: fileId, dataURL, mimeType: mimeFromName(refPath || 'image.png'), created: Date.now() }])
// Cap on-canvas size to a usable footprint regardless of render size.
const { width, height } = await measureImage(dataURL)
const st = api.getAppState()
const zoom = st.zoom?.value || 1
const centerX = (st.width / 2) / zoom - st.scrollX
const centerY = (st.height / 2) / zoom - st.scrollY
const skeleton = {
type: 'image',
x: centerX - width / 2,
y: centerY - height / 2,
width,
height,
fileId
}
const newElements = convertToExcalidrawElements([skeleton])
api.updateScene({ elements: [...api.getSceneElements(), ...newElements] })
// Only persist a ref when the image is backed by a served asset file
// (so it re-hydrates on reload); pure data-URL results won't be.
if (refPath) imageRefsRef.current[fileId] = refPath
// updateScene triggers onChange → scheduleSave; nudge it explicitly too.
scheduleSave()
} catch (err) {
console.error('Failed to place generated image on board', err)
}
}, [scheduleSave])
const handleBoardsChanged = useCallback((nextBoards) => {
if (Array.isArray(nextBoards)) setBoards(nextBoards)
else refreshBoards()
}, [refreshBoards])
const currentBoard = useMemo(
() => boards.find(b => String(b.id) === String(boardId)) || board,
[boards, boardId, board]
)
if (!projectId) {
return (
<div className="board-page">
<Header onSettingsClick={() => setShowSettings(true)} title="Boards" centerTitle />
<div className="board-page__empty">No project selected.</div>
<Footer />
</div>
)
}
return (
<div className="board-page">
<Header
onSettingsClick={() => setShowSettings(true)}
projectId={projectId}
title={project?.name || 'Boards'}
centerTitle
/>
{showSettings && <SettingsModal onClose={() => setShowSettings(false)} />}
<div className="board-page__bar">
<BoardSwitcher
projectId={projectId}
boards={boards}
currentBoard={currentBoard}
onBoardsChanged={handleBoardsChanged}
createBoard={createBoard}
updateBoard={updateBoard}
deleteBoard={deleteBoard}
onSelect={(id) => setSearchParams({ projectId, boardId: String(id) })}
/>
<span className={`board-page__save board-page__save--${saveStatus}`}>
{saveStatus === 'saving' && 'Saving…'}
{saveStatus === 'saved' && 'All changes saved'}
{saveStatus === 'error' && 'Save failed — retrying on next edit'}
</span>
</div>
{loadError && <div className="board-page__error">{loadError}</div>}
<div className="board-page__body">
<div className="board-page__canvas">
{initialData ? (
<Excalidraw
key={boardId}
excalidrawAPI={(api) => { excalidrawApiRef.current = api }}
initialData={initialData}
onChange={handleChange}
theme="dark"
name={currentBoard?.name || 'Board'}
/>
) : (
<div className="board-page__loading">Loading board…</div>
)}
</div>
<BoardAiPanel
projectId={projectId}
projectName={project?.name || ''}
boardId={boardId}
onImageGenerated={placeAssetImage}
getSelectedBoardImage={getSelectedBoardImage}
/>
</div>
</div>
)
}

View file

@ -785,11 +785,7 @@
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
/* A flat fill instead of backdrop-filter: blur(). Every blurred element inside
the React Flow viewport costs a backdrop readback per frame, and with 3-4
badges per node (70+ on screen at low zoom) that collapsed dragging to
~2 fps in the desktop app (Electron/Chromium 130) while browsers coped. */
background: rgba(12, 14, 16, 0.55);
backdrop-filter: blur(10px);
pointer-events: none;
}

View file

@ -3226,7 +3226,6 @@ export default function GraphPage({ project }) {
onSettingsClick={() => setShowSettings(true)}
title={project?.name || 'Workspace'}
centerTitle
projectId={project?.id}
/>
{showSettings && <SettingsModal onClose={() => setShowSettings(false)} />}

View file

@ -55,7 +55,6 @@ import {
normalizeCustomApiType
} from '../utils/kanbanHelpers'
import { saveWorkflowDefaults } from '../utils/workflowDefaults'
import { getWorkflowEnumOptions, resolveWorkflowEnumValue } from '../utils/workflowEnums'
// Database id of the "Mesh Gen" kanban column (see IMAGE_CARD_COLUMNS).
const MESH_GEN_COLUMN_ID = 3
@ -139,7 +138,7 @@ export default function KanbanPage() {
const fileInputRef = useRef(null)
const fileUploadContextRef = useRef({ cardId: null, closeDraft: true })
const meshFileInputRef = useRef(null)
const meshUploadContextRef = useRef({ cardId: null, closeDraft: true })
const meshUploadContextRef = useRef({ closeDraft: true })
const pendingMeshProgressSubscriptionRef = useRef(null)
const pendingComfyProgressSubscriptionRef = useRef(null)
const imageEditProgressSubscriptionsRef = useRef(new Map())
@ -148,11 +147,11 @@ export default function KanbanPage() {
const [assetSelectorOpen, setAssetSelectorOpen] = useState(false);
const [pendingAssetCardId, setPendingAssetCardId] = useState(null);
const [assetSelectorType, setAssetSelectorType] = useState('image'); // 'image' | 'mesh'
const [assetSelectorType, setAssetSelectorType] = useState('image'); // only 'image' for now
const handleOpenAssetSelector = (cardId, type = 'image') => {
const handleOpenAssetSelector = (cardId) => {
setPendingAssetCardId(cardId);
setAssetSelectorType(type);
setAssetSelectorType('image');
setAssetSelectorOpen(true);
};
@ -238,7 +237,6 @@ export default function KanbanPage() {
}
const openImageSourceMenu = (cardId = null) => {
setMeshDraft(null)
setImageDraft({ mode: 'select', cardId })
}
@ -499,9 +497,7 @@ export default function KanbanPage() {
const handleRemoveImage = async (assetId) => {
try {
// Scope the removal to THIS project — an asset shared with another project
// must keep its membership there.
await deleteAsset(assetId, { projectId })
await deleteAsset(assetId)
await Promise.all([refreshProjectAssets(), refreshCardAttributes()])
} catch (err) {
console.error('Failed to remove image:', err)
@ -512,7 +508,7 @@ export default function KanbanPage() {
const handleRemoveImageCard = async (cardId, cardAssets) => {
try {
for (const asset of cardAssets) {
await deleteAsset(asset.id, { projectId })
await deleteAsset(asset.id)
}
if (cardId) {
@ -651,13 +647,8 @@ export default function KanbanPage() {
}
}
// Assets on column-less "detached" container cards (Brainstorming Board
// generations) have kanbanColumnId === null. They belong to the project (and
// are returned by listProjectAssets for MCP/clients) but must NOT appear on
// the Kanban board, so exclude them from the columns entirely.
const kanbanAssets = assets.filter(a => a.kanbanColumnId !== null && a.kanbanColumnId !== undefined)
const images = kanbanAssets.filter(a => a.type === 'image')
const meshes = kanbanAssets.filter(a => a.type === 'mesh')
const images = assets.filter(a => a.type === 'image')
const meshes = assets.filter(a => a.type === 'mesh')
const meshAssetsByCardId = useMemo(() => {
return meshes.reduce((accumulator, asset) => {
@ -713,10 +704,7 @@ export default function KanbanPage() {
}
});
if (isMesh) {
// Only a freshly created card needs relocating — an existing card keeps its column.
if (!pendingAssetCardId) {
await moveCardToMeshGen(cardId);
}
await moveCardToMeshGen(cardId);
await ensureGeneratedMeshThumbnails(attachedAsset);
}
await refreshProjectAssets();
@ -1046,15 +1034,12 @@ export default function KanbanPage() {
// ---- "Add New Mesh" (Mesh Gen column) ----------------------------------
const selectedMeshComfyWorkflow = meshGenWorkflows.find(workflow => workflow.id == meshDraft?.workflowId) || null
// `cardId` targets an existing card ("Add more meshes" on any card); null
// creates a brand new Mesh Gen card ("ADD NEW MESH" at the bottom of the column).
const openMeshSourceMenu = (cardId = null) => {
setImageDraft(null)
setMeshDraft({ mode: 'select', cardId })
const openMeshSourceMenu = () => {
setMeshDraft({ mode: 'select' })
}
const openMeshLocalFilePicker = (cardId = meshDraft?.cardId || null) => {
meshUploadContextRef.current = { cardId, closeDraft: true }
const openMeshLocalFilePicker = () => {
meshUploadContextRef.current = { closeDraft: true }
if (meshFileInputRef.current) {
meshFileInputRef.current.value = ''
@ -1066,8 +1051,8 @@ export default function KanbanPage() {
const files = Array.from(e.target.files || [])
if (files.length === 0) return
const { cardId: targetCardId, closeDraft } = meshUploadContextRef.current
const cardId = targetCardId || createImageCardId()
const { closeDraft } = meshUploadContextRef.current
const cardId = createImageCardId()
try {
setLoading(true)
@ -1083,10 +1068,7 @@ export default function KanbanPage() {
uploadedAssets.push(uploaded)
}
// Only a freshly created card needs relocating — an existing card keeps its column.
if (!targetCardId) {
await moveCardToMeshGen(cardId)
}
await moveCardToMeshGen(cardId)
await ensureGeneratedMeshThumbnails(uploadedAssets)
await refreshProjectAssets()
@ -1099,21 +1081,23 @@ export default function KanbanPage() {
} finally {
setLoading(false)
e.target.value = ''
meshUploadContextRef.current = { cardId: null, closeDraft: true }
meshUploadContextRef.current = { closeDraft: true }
}
}
const openMeshAssetLibrary = async (cardId = meshDraft?.cardId || null) => {
const openMeshAssetLibrary = async () => {
try {
await getLibraryAssets() // preload library if needed
handleOpenAssetSelector(cardId, 'mesh')
setPendingAssetCardId(null)
setAssetSelectorType('mesh')
setAssetSelectorOpen(true)
} catch (err) {
console.error('Failed to load mesh library:', err)
showStatusMessage(err.message || 'Failed to load meshes library', 'error')
}
}
const openMeshComfyDraft = (cardId = meshDraft?.cardId || null) => {
const openMeshComfyDraft = () => {
if (meshGenWorkflows.length === 0) {
showStatusMessage('No compatible ComfyUI workflows available. Import a workflow with at least one mesh output.', 'error')
return
@ -1121,16 +1105,16 @@ export default function KanbanPage() {
setMeshDraft({
...getComfyDraftFromWorkflow(meshGenWorkflows[0]),
cardId
cardId: null
})
}
const handleMeshComfyWorkflowChange = (workflowId) => {
const workflow = meshGenWorkflows.find(item => item.id == workflowId)
setMeshDraft(prev => ({
setMeshDraft({
...getComfyDraftFromWorkflow(workflow),
cardId: prev?.cardId || null
}))
cardId: null
})
}
const handleMeshComfyInputChange = (parameter, rawValue) => {
@ -1192,8 +1176,7 @@ export default function KanbanPage() {
detail: 'Preparing ComfyUI workflow',
progressPercent: 0,
currentNodeLabel: 'Waiting for ComfyUI execution to start',
promptId,
cardId: draft.cardId || null
promptId
})
setMeshDraft(null)
setLoading(true)
@ -1221,10 +1204,7 @@ export default function KanbanPage() {
currentNodeLabel: 'Generated mesh received'
} : prev)
await persistWorkflowDefaultsIfRequested(draft, workflow)
// Only a freshly created card needs relocating — an existing card keeps its column.
if (!draft.cardId) {
await moveCardToMeshGen(cardId)
}
await moveCardToMeshGen(cardId)
await ensureGeneratedMeshThumbnails(generatedMeshes)
await refreshProjectAssets()
completeJob(promptId, { status: 'completed' })
@ -1259,16 +1239,16 @@ export default function KanbanPage() {
}
const prompt = draft.prompt.trim()
const cardId = draft.cardId || createImageCardId()
const cardId = createImageCardId()
const isTencentMeshApi = isTencentMeshGenerationApi(draft.selectedApi)
const isTripoMeshApi = isTripoMeshGenerationApi(draft.selectedApi)
const isHitemMeshApi = isHitemMeshGenerationApi(draft.selectedApi)
const isTripoP1Model = isTripoMeshApi && (draft.modelVersion || 'v2.5-20250123') === 'P1-20260311'
// Hitem3D is image-to-3D only; the mesh source draft has no image source, so
// it must be run from a card that already holds an image, via its Action menu.
// Hitem3D is image-to-3D only; the "Add New Mesh" draft has no image source,
// so it must be run from a Mesh Gen card that has an image dragged into it.
if (isHitemMeshApi) {
showStatusMessage('Hitem3D needs an image source. Add an image to a card and run it from the card Action menu.', 'error')
showStatusMessage('Hitem3D needs an image source. Drag an image into the Mesh Gen column and run it from the card.', 'error')
return
}
@ -1283,8 +1263,7 @@ export default function KanbanPage() {
selectedApi: draft.selectedApi,
title: name,
source: providerLabel,
detail: 'Submitting mesh generation request',
cardId: draft.cardId || null
detail: 'Submitting mesh generation request'
})
setMeshDraft(null)
setLoading(true)
@ -1672,9 +1651,7 @@ export default function KanbanPage() {
const getCardPreviewItems = (card, showAttributes = false) => {
const hasMeshAssets = (card.meshAssets?.length || 0) > 0
// Image Edit (2) is included so a mesh attached there via "Add more meshes"
// stays visible instead of being dropped from the preview.
const useMixedAssetCarousel = showAttributes && [2, 3, 4, 5, 6].includes(card.kanbanColumnId) && hasMeshAssets
const useMixedAssetCarousel = showAttributes && [3, 4, 5, 6].includes(card.kanbanColumnId) && hasMeshAssets
if (!useMixedAssetCarousel) {
return []
@ -3011,18 +2988,9 @@ export default function KanbanPage() {
)
}
// Image / mesh source drafts render inside the column of the card they target
// ("Add more images" / "Add more meshes"), and default to their own column when
// they are creating a brand new card.
const resolveDraftColumnId = (cardId, fallbackColumnId) => (
cardId
? imageCards.find(card => card.id === cardId)?.kanbanColumnId || fallbackColumnId
: fallbackColumnId
)
const draftColumnId = resolveDraftColumnId(imageDraft?.cardId, IMAGE_CARD_COLUMNS[0].dbId)
const meshDraftColumnId = resolveDraftColumnId(meshDraft?.cardId, MESH_GEN_COLUMN_ID)
const pendingMeshColumnId = resolveDraftColumnId(pendingMeshGeneration?.cardId, MESH_GEN_COLUMN_ID)
const draftColumnId = imageDraft?.cardId
? imageCards.find(card => card.id === imageDraft.cardId)?.kanbanColumnId || IMAGE_CARD_COLUMNS[0].dbId
: IMAGE_CARD_COLUMNS[0].dbId
const renderDropZone = (columnId, position, isEmpty = false) => {
const isActive = dropTarget?.columnId === columnId && dropTarget?.position === position
@ -3035,11 +3003,7 @@ export default function KanbanPage() {
onDragOver={event => handleCardDragOver(event, columnId, position)}
onDrop={event => handleCardDrop(event, columnId, position)}
>
{isEmpty
&& !(imageDraft && draftColumnId === columnId)
&& !(pendingImageGeneration && columnId === IMAGE_CARD_COLUMNS[0].dbId)
&& !(meshDraft && meshDraftColumnId === columnId)
&& !(pendingMeshGeneration && pendingMeshColumnId === columnId) && (
{isEmpty && !imageDraft && !pendingImageGeneration && !(columnId === MESH_GEN_COLUMN_ID && (meshDraft || pendingMeshGeneration)) && (
<span className="kanban-drop-zone__label font-label">
{column?.emptyLabel || 'Drop image cards here'}
</span>
@ -3078,7 +3042,6 @@ export default function KanbanPage() {
handleCardDragStart,
handleCardDragEnd,
openImageSourceMenu,
openMeshSourceMenu,
handleRemoveImageCard,
openMeshPreview,
handleRemoveImage,
@ -3219,16 +3182,6 @@ export default function KanbanPage() {
</div>
<span>{parameter.label || 'Toggle value'}</span>
</label>
) : getWorkflowEnumOptions(parameter, imageDraft.inputs?.[parameter.id]) ? (
<select
className="params-card__select"
value={imageDraft.inputs?.[parameter.id] == null ? '' : String(imageDraft.inputs[parameter.id])}
onChange={e => handleComfyInputChange(parameter, resolveWorkflowEnumValue(parameter, e.target.value))}
>
{getWorkflowEnumOptions(parameter, imageDraft.inputs?.[parameter.id]).map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
) : getWorkflowParameterValueType(parameter) === 'string' ? (
<div className="comfy-textfield-wrap">
<textarea
@ -3374,33 +3327,44 @@ export default function KanbanPage() {
</div>
)}
{column.dbId === IMAGE_CARD_COLUMNS[0].dbId
&& !(imageDraft && draftColumnId === column.dbId)
&& !pendingImageGeneration && (
<button className="kanban-col__add-btn" id="add-image-btn" onClick={() => openImageSourceMenu()}>
<span className="material-symbols-outlined">add_photo_alternate</span>
<span className="font-label">ADD NEW IMAGE</span>
</button>
{column.dbId === IMAGE_CARD_COLUMNS[0].dbId && (
<>
<input
type="file"
accept="image/*"
multiple
style={{ display: 'none' }}
onChange={handleFileUpload}
ref={fileInputRef}
/>
{!imageDraft && !pendingImageGeneration && (
<button className="kanban-col__add-btn" id="add-image-btn" onClick={() => openImageSourceMenu()}>
<span className="material-symbols-outlined">add_photo_alternate</span>
<span className="font-label">ADD NEW IMAGE</span>
</button>
)}
</>
)}
{meshDraft && meshDraftColumnId === column.dbId && (
{meshDraft && column.dbId === MESH_GEN_COLUMN_ID && (
<div className="image-card image-card--draft">
{meshDraft.mode === 'select' && (
<div className="image-card__options">
<span className="font-label" style={{ fontSize: '0.65rem', color: 'var(--primary)', marginBottom: '0.5rem' }}>MESH SOURCE</span>
<button className="option-btn" onClick={() => openMeshLocalFilePicker(meshDraft?.cardId || null)}>
<button className="option-btn" onClick={() => openMeshLocalFilePicker()}>
<span className="material-symbols-outlined">computer</span>
Local Computer
</button>
<button className="option-btn" onClick={() => openMeshAssetLibrary(meshDraft?.cardId || null)}>
<button className="option-btn" onClick={() => openMeshAssetLibrary()}>
<span className="material-symbols-outlined">folder_open</span>
From Assets
</button>
<button className="option-btn" onClick={() => openMeshComfyDraft(meshDraft?.cardId || null)}>
<button className="option-btn" onClick={() => openMeshComfyDraft()}>
<span className="material-symbols-outlined">account_tree</span>
ComfyUI Workflow
</button>
<button className="option-btn" onClick={() => setMeshDraft({ mode: 'api', selectedApi: meshGenerationApis[0]?.id || '', prompt: '', name: '', ...getMeshGenApiDefaults(), cardId: meshDraft?.cardId || null })}>
<button className="option-btn" onClick={() => setMeshDraft({ mode: 'api', selectedApi: meshGenerationApis[0]?.id || '', prompt: '', name: '', ...getMeshGenApiDefaults() })}>
<span className="material-symbols-outlined">api</span>
Remote API
</button>
@ -3463,16 +3427,6 @@ export default function KanbanPage() {
</div>
<span>{parameter.label || 'Toggle value'}</span>
</label>
) : getWorkflowEnumOptions(parameter, meshDraft.inputs?.[parameter.id]) ? (
<select
className="params-card__select"
value={meshDraft.inputs?.[parameter.id] == null ? '' : String(meshDraft.inputs[parameter.id])}
onChange={e => handleMeshComfyInputChange(parameter, resolveWorkflowEnumValue(parameter, e.target.value))}
>
{getWorkflowEnumOptions(parameter, meshDraft.inputs?.[parameter.id]).map(option => (
<option key={option.value} value={option.value}>{option.label}</option>
))}
</select>
) : getWorkflowParameterValueType(parameter) === 'string' ? (
<textarea
className="gen-prompt-input image-card__param-textarea"
@ -3530,7 +3484,7 @@ export default function KanbanPage() {
<span>No mesh workflows available. Open the Library page to import one.</span>
</div>
)}
<button className="kanban-sidebar__nav-item" onClick={() => openMeshSourceMenu(meshDraft?.cardId || null)} style={{ justifyContent: 'center' }}>BACK</button>
<button className="kanban-sidebar__nav-item" onClick={() => openMeshSourceMenu()} style={{ justifyContent: 'center' }}>BACK</button>
</div>
)}
@ -3588,13 +3542,13 @@ export default function KanbanPage() {
<span>No mesh generation APIs available. Configure one in Settings.</span>
</div>
)}
<button className="kanban-sidebar__nav-item" onClick={() => openMeshSourceMenu(meshDraft?.cardId || null)} style={{ justifyContent: 'center' }}>BACK</button>
<button className="kanban-sidebar__nav-item" onClick={() => openMeshSourceMenu()} style={{ justifyContent: 'center' }}>BACK</button>
</div>
)}
</div>
)}
{pendingMeshGeneration && pendingMeshColumnId === column.dbId && (
{pendingMeshGeneration && column.dbId === MESH_GEN_COLUMN_ID && (
<div className="image-card image-card--loading" id="mesh-card-loading">
<div className="image-card__thumb image-card__thumb--loading">
<div className="image-card__loading-state">
@ -3623,13 +3577,24 @@ export default function KanbanPage() {
</div>
)}
{column.dbId === MESH_GEN_COLUMN_ID
&& !(meshDraft && meshDraftColumnId === column.dbId)
&& !(pendingMeshGeneration && pendingMeshColumnId === column.dbId) && (
<button className="kanban-col__add-btn" id="add-mesh-btn" onClick={() => openMeshSourceMenu()}>
<span className="material-symbols-outlined">deployed_code</span>
<span className="font-label">ADD NEW MESH</span>
</button>
{column.dbId === MESH_GEN_COLUMN_ID && (
<>
<input
type="file"
accept={getWorkflowFileInputAccept('mesh')}
multiple
style={{ display: 'none' }}
onChange={handleMeshFileUpload}
ref={meshFileInputRef}
/>
{!meshDraft && !pendingMeshGeneration && (
<button className="kanban-col__add-btn" id="add-mesh-btn" onClick={() => openMeshSourceMenu()}>
<span className="material-symbols-outlined">deployed_code</span>
<span className="font-label">ADD NEW MESH</span>
</button>
)}
</>
)}
</div>
</div>
@ -3642,7 +3607,6 @@ export default function KanbanPage() {
onSettingsClick={() => setShowSettings(true)}
title={project?.name || 'Workspace'}
centerTitle
projectId={projectId}
/>
{statusMessage && (
@ -3656,25 +3620,6 @@ export default function KanbanPage() {
{showSettings && <SettingsModal onClose={() => setShowSettings(false)} />}
{/* Rendered once at page level: "Add more images"/"Add more meshes" can be
triggered from a card in any column, not just Images / Mesh Gen. */}
<input
type="file"
accept="image/*"
multiple
style={{ display: 'none' }}
onChange={handleFileUpload}
ref={fileInputRef}
/>
<input
type="file"
accept={getWorkflowFileInputAccept('mesh')}
multiple
style={{ display: 'none' }}
onChange={handleMeshFileUpload}
ref={meshFileInputRef}
/>
{meshPreviewAsset && <MeshPreviewDialog asset={meshPreviewAsset} titleId="kanban-mesh-preview-dialog-title" onClose={() => setMeshPreviewAsset(null)} />}
{assetSelectorOpen && (

View file

@ -23,34 +23,6 @@ const PRESETS = [
]
const CHANGE_LOG_ENTRIES = [
{
version: 'v2.1.2',
date: '2026-07-28',
items: [
'Fixed Desktop App on Linux',
'ComfyUI: Added Enums',
'Wireframe mode in Mesh Previewer'
],
},
{
version: 'v2.1.1',
date: '2026-07-27',
items: [
'ComfyUI: Custom models folder',
'Mesh Export: Save last output folder',
'DB: Fixed assets linked to a project',
'Kanban: Can add more meshes and images from any column',
'Desktop App: Fixed Graph page slowness'
],
},
{
version: 'v2.1.0',
date: '2026-07-23',
items: [
'Added Brainstorming Boards',
'MCP: Fixed Optimize tool'
],
},
{
version: 'v2.0.0',
date: '2026-07-20',

View file

@ -1,96 +0,0 @@
// Pure helpers for the Brainstorming Board (BoardPage). No React state.
// Fields of Excalidraw's appState that are safe + useful to persist. We
// deliberately drop transient/unserializable ones (collaborators, selection,
// cursor, etc.) so re-hydrating via initialData never crashes.
export function sanitizeBoardAppState(appState = {}) {
const { viewBackgroundColor, scrollX, scrollY, zoom, gridSize } = appState
return {
viewBackgroundColor: viewBackgroundColor ?? '#0d0e10',
scrollX: Number.isFinite(scrollX) ? scrollX : 0,
scrollY: Number.isFinite(scrollY) ? scrollY : 0,
zoom: zoom && Number.isFinite(zoom.value) ? { value: zoom.value } : { value: 1 },
gridSize: gridSize ?? null
}
}
// A cheap change signature so the debounced autosave skips redundant writes
// (e.g. the initial onChange that echoes the data we just loaded, or pure
// selection changes which live in appState we don't include here).
export function boardStateSignature(elements = [], appState = {}) {
const sanitized = sanitizeBoardAppState(appState)
const elementSig = elements.map(el => `${el.id}:${el.version}`).join(',')
return JSON.stringify({ e: elementSig, a: sanitized })
}
// Normalize an asset path to the served (url) form assetUrl() expects. Assets
// created as edits return a stored filePath ("data/assets/images/x.png") with no
// filename field; the served mount strips the "data/assets/" prefix.
export function toServedAssetPath(pathOrFilename) {
return String(pathOrFilename || '').replace(/\\/g, '/').replace(/^data\/assets\//, '')
}
export function mimeFromName(name = '') {
const ext = String(name).split('.').pop().toLowerCase()
if (ext === 'jpg' || ext === 'jpeg') return 'image/jpeg'
if (ext === 'webp') return 'image/webp'
if (ext === 'gif') return 'image/gif'
if (ext === 'svg') return 'image/svg+xml'
return 'image/png'
}
export function extFromMime(mime = '') {
if (mime.includes('jpeg')) return 'jpg'
if (mime.includes('webp')) return 'webp'
if (mime.includes('gif')) return 'gif'
if (mime.includes('svg')) return 'svg'
return 'png'
}
// Fetch a served asset URL and return it as a data URL (Excalidraw renders
// images from data URLs in its `files` map).
export async function urlToDataURL(url) {
const res = await fetch(url)
if (!res.ok) throw new Error(`Failed to fetch image: ${res.status}`)
const blob = await res.blob()
return await blobToDataURL(blob)
}
export function blobToDataURL(blob) {
return new Promise((resolve, reject) => {
const reader = new FileReader()
reader.onload = () => resolve(reader.result)
reader.onerror = () => reject(new Error('Failed to read image blob'))
reader.readAsDataURL(blob)
})
}
export function dataURLToFile(dataURL, filename) {
const [meta, b64] = String(dataURL).split(',')
const mime = /data:(.*?)(;|$)/.exec(meta)?.[1] || 'image/png'
const binary = atob(b64)
const bytes = new Uint8Array(binary.length)
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i)
return new File([bytes], filename, { type: mime })
}
// Natural pixel size of a data URL, capped so huge renders land at a usable
// size on the canvas while preserving aspect ratio.
export function measureImage(dataURL, maxDimension = 720) {
return new Promise((resolve) => {
const img = new Image()
img.onload = () => {
let { naturalWidth: w, naturalHeight: h } = img
if (!w || !h) { resolve({ width: 512, height: 512 }); return }
const largest = Math.max(w, h)
if (largest > maxDimension) {
const scale = maxDimension / largest
w = Math.round(w * scale)
h = Math.round(h * scale)
}
resolve({ width: w, height: h })
}
img.onerror = () => resolve({ width: 512, height: 512 })
img.src = dataURL
})
}

View file

@ -21,11 +21,7 @@ export function buildWorkflowDefaultsPayload(workflow, values = {}) {
const base = {
id: parameter.id,
name: parameter.name,
valueType,
// Echo the allowed-value list back so saving defaults never drops it.
...(Array.isArray(parameter.enums) && parameter.enums.length > 0
? { enums: [...parameter.enums] }
: {})
valueType
}
// Only String / Number / Boolean fields are saved as defaults. File-type params

View file

@ -1,75 +0,0 @@
// Enum support for ComfyUI workflow parameters.
//
// A String or Number parameter can carry an `enums` array that restricts it to a
// fixed list of allowed values. Every AI panel renders such a parameter as a
// dropdown instead of a free-form field, so the value can only ever be one the
// workflow actually accepts.
//
// Values keep their real type in storage (numbers stay numbers) while <select>
// values are always strings — hence resolveWorkflowEnumValue, which maps a picked
// option back to its typed entry.
const ENUM_VALUE_TYPES = ['string', 'number']
// The allowed values of a parameter, or null when it isn't an enum parameter.
export function getWorkflowParameterEnums(parameter) {
if (!Array.isArray(parameter?.enums)) return null
const values = parameter.enums.filter(value => typeof value === 'string' || typeof value === 'number')
return values.length > 0 ? values : null
}
export function isEnumWorkflowValueType(valueType) {
return ENUM_VALUE_TYPES.includes(valueType)
}
// Options for a <select>, or null when the parameter has no enums. A current
// value outside the list is kept as an extra option so an older saved value is
// never silently rewritten.
export function getWorkflowEnumOptions(parameter, currentValue) {
const enums = getWorkflowParameterEnums(parameter)
if (!enums) return null
const options = enums.map(value => ({ value: String(value), label: String(value) }))
if (currentValue !== undefined && currentValue !== null && currentValue !== ''
&& !options.some(option => option.value === String(currentValue))) {
options.unshift({ value: String(currentValue), label: `${currentValue} (custom)` })
}
return options
}
// Map a <select> value (always a string) back to the typed enum entry.
export function resolveWorkflowEnumValue(parameter, rawValue) {
const enums = getWorkflowParameterEnums(parameter)
const match = enums?.find(value => String(value) === String(rawValue))
return match === undefined ? rawValue : match
}
// Parse the workflow editor's enum field (one value per line) into stored values.
export function parseWorkflowEnumsInput(text, valueType) {
if (!isEnumWorkflowValueType(valueType)) return []
const values = []
for (const line of String(text || '').split('\n')) {
const trimmed = line.trim()
if (!trimmed) continue
if (valueType === 'number') {
const numeric = Number(trimmed)
if (!Number.isFinite(numeric) || values.includes(numeric)) continue
values.push(numeric)
continue
}
if (!values.includes(trimmed)) values.push(trimmed)
}
return values
}
// Render stored enums back into the editor field (one value per line).
export function formatWorkflowEnumsInput(enums) {
return Array.isArray(enums) ? enums.join('\n') : ''
}

View file

@ -26,12 +26,7 @@ export function buildShareableWorkflow(workflow) {
parameters: (workflow?.parameters || []).map(parameter => ({
id: parameter.id,
name: parameter.name,
valueType: parameter.valueType,
// Only String/Number parameters carry an allowed-value list; omit the key
// entirely for the rest so bundles stay as small as they were.
...(Array.isArray(parameter.enums) && parameter.enums.length > 0
? { enums: [...parameter.enums] }
: {})
valueType: parameter.valueType
})),
outputs: (workflow?.outputs || []).map(output => ({
nodeId: output.nodeId,

File diff suppressed because it is too large Load diff

View file

@ -14,9 +14,7 @@ exits non-zero on failure so the caller can skip the install.
"""
from __future__ import annotations
import os
import re
import shutil
import sys
import tempfile
import urllib.parse
@ -42,21 +40,13 @@ def download(url: str) -> str:
return hf_hub_download(repo_id=repo_id, filename=filename)
# Plain HTTP(S) download (e.g. GitHub release assets).
#
# The original basename MUST be preserved. pip/uv read the distribution name,
# version and compatibility tags out of the wheel FILENAME, so a mkstemp name
# like "flash_attn_t5eu90p9.whl" is rejected before the file is even opened:
# error: The wheel filename "flash_attn_t5eu90p9.whl" is invalid: Must have a version
# So download into a temp DIRECTORY and keep the name the server gave us.
name = os.path.basename(urllib.parse.unquote(urllib.parse.urlparse(url).path))
if not name.endswith(".whl"):
raise ValueError(f"URL does not name a .whl file: {url}")
path = os.path.join(tempfile.mkdtemp(prefix="flash_attn_"), name)
fd, path = tempfile.mkstemp(suffix=".whl", prefix="flash_attn_")
import os
os.close(fd)
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
# copyfileobj streams: these wheels are a few hundred MB and don't need to be
# held in memory in one piece.
with urllib.request.urlopen(req) as resp, open(path, "wb") as out:
shutil.copyfileobj(resp, out)
out.write(resp.read())
return path

View file

@ -1,3 +0,0 @@
Torch;Cuda;Link;PyTorchLink
2.13.0;12.6.0;https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.47/flash_attn-2.8.3+cu126torch2.13-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl;pip3 install torch~=2.13.0 torchvision --index-url https://download.pytorch.org/whl/cu126
2.13.0;13.0.0;https://github.com/mjun0812/flash-attention-prebuild-wheels/releases/download/v0.9.47/flash_attn-2.8.3+cu130torch2.13-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl;pip3 install torch~=2.13.0 torchvision

View file

@ -6,18 +6,12 @@
#
# On first run it uses `uv` to provision a pinned standalone Python (see
# .python-version -> 3.13) and installs the SkinTokens requirements, torch, a
# flash-attn wheel, and the model checkpoints. Like Windows, Linux installs
# flash-attn from a curated prebuilt wheel (flash_attention_linux.txt) rather than
# `pip install flash-attn`, which compiles from source and takes about an hour.
# uv is auto-installed if absent.
# flash-attn wheel, and the model checkpoints. Unlike Windows (which needs the
# curated flash_attention_windows.txt wheels), Linux gets flash-attn straight
# from pip, which resolves a prebuilt wheel for the installed torch/CUDA/Python
# (or builds it — needs the CUDA toolkit + ninja). uv is auto-installed if absent.
#
# Env overrides:
# RIGTOOLS_PORT / RIGTOOLS_HOST bind address
# RIGTOOLS_CUDA=12.6 force the CUDA build to target (skip nvidia-smi)
# RIGTOOLS_SKIP_FLASH=1 don't install flash-attn
# RIGTOOLS_BUILD_FLASH=1 if no curated wheel matches, build from source
# instead of giving up (~1 hour, needs nvcc+ninja)
# RIGTOOLS_SKIP_MODEL=1 don't download the model checkpoints
# Env overrides: RIGTOOLS_PORT/HOST, RIGTOOLS_SKIP_FLASH=1, RIGTOOLS_SKIP_MODEL=1.
set -euo pipefail
cd "$(dirname "$0")"
PYVER=3.13
@ -48,70 +42,22 @@ if [ ! -x ".venv/bin/python" ]; then
# shellcheck disable=SC1091
source .venv/bin/activate
# --- Pick a prebuilt flash-attn wheel + its matching torch install ----------
# select_flash_attn.py picks the table for this platform (flash_attention_linux.txt
# here) and, on a CUDA match, prints:
# WHEEL=<flash-attn wheel url>
# TORCHARGS=<torch~=.. torchvision .. [--index-url ..]>
# Prints nothing on no match. Python is pinned to 3.13 by uv, so the wheels (all
# cp313) always fit; only CUDA has to be matched.
echo
echo "Detecting CUDA to select a flash-attn wheel..."
WHEEL=""
TORCHARGS=""
while IFS= read -r line; do
case "$line" in
WHEEL=*) WHEEL="${line#WHEEL=}" ;;
TORCHARGS=*) TORCHARGS="${line#TORCHARGS=}" ;;
esac
done < <(python select_flash_attn.py)
echo
echo "Installing SkinTokens requirements..."
"$UV" pip install -r requirements.txt
# torch AFTER requirements so it overrides the torch `lightning` pulls in. The
# curated TORCHARGS pins torch to the version the flash-attn wheel was built
# against, so the ABI matches. On Linux the PyPI torch wheels bundle CUDA, so a
# row may legitimately carry no --index-url.
# torch AFTER requirements so it overrides the torch `lightning` pulls in. On
# Linux the default PyPI torch wheels bundle CUDA, so no custom index is needed.
echo
if [ -n "$TORCHARGS" ]; then
echo "Installing torch: $TORCHARGS"
# shellcheck disable=SC2086 -- curated arg list; word-splitting is intended
"$UV" pip install $TORCHARGS
else
echo "No matching prebuilt flash-attn wheel -- installing default torch (CUDA build from PyPI)..."
"$UV" pip install torch torchvision
fi
echo "Installing torch (CUDA build)..."
"$UV" pip install torch torchvision torchaudio
# --- flash-attn -------------------------------------------------------------
echo
if [ -n "${RIGTOOLS_SKIP_FLASH:-}" ]; then
echo "RIGTOOLS_SKIP_FLASH set -- skipping flash-attn."
elif [ -n "$WHEEL" ]; then
echo "Downloading + installing prebuilt flash-attn wheel..."
# Fetch to a local path first: `pip install <hf-url>` 403s on Hugging Face
# Xet-backed files. GitHub release assets go over plain urllib.
if FA_WHEEL="$(python download_wheel.py "$WHEEL" | tail -n 1)" && [ -n "$FA_WHEEL" ]; then
"$UV" pip install "$FA_WHEEL" || echo "[warn] flash-attn install failed; continuing without it."
else
echo "[warn] flash-attn download failed; continuing without it."
fi
elif [ -n "${RIGTOOLS_BUILD_FLASH:-}" ]; then
echo "No curated wheel matched -- building flash-attn from source (this takes ~an hour)..."
"$UV" pip install flash-attn --no-build-isolation || echo "[warn] flash-attn build failed; continuing without it."
else
echo "[warn] No prebuilt flash-attn wheel matched this CUDA; flash-attn was NOT installed."
echo " rig_server.py cannot import without it. Either add a row for your"
echo " CUDA/torch to flash_attention_linux.txt, or build from source with:"
echo " RIGTOOLS_BUILD_FLASH=1 ./run_server.sh # ~1 hour, needs nvcc + ninja"
fi
# A wheel built against a different torch ABI installs cleanly and only fails at
# import ("undefined symbol: _ZN3c10..."), so check now rather than mid-rig.
if [ -z "${RIGTOOLS_SKIP_FLASH:-}" ]; then
python -c 'import torch, flash_attn; print("flash_attn", flash_attn.__version__, "/ torch", torch.__version__)' \
|| echo "[warn] flash-attn does not import -- likely a torch ABI mismatch with the selected wheel."
echo "Installing flash-attn (prebuilt wheel if available, else builds from source)..."
"$UV" pip install flash-attn --no-build-isolation || echo "[warn] flash-attn install failed; continuing without it."
fi
echo

View file

@ -1,63 +1,50 @@
"""Pick the prebuilt flash-attn wheel + matching torch install for this machine.
Building flash-attn from source takes ~an hour on BOTH Windows and Linux, so we
always prefer a precompiled wheel. There is one curated table per platform —
``flash_attention_windows.txt`` (win_amd64 wheels) and
``flash_attention_linux.txt`` (linux_x86_64 wheels) — and this script picks the
table matching the host. Each lists, per row:
Building flash-attn from source on Windows takes ages, so we prefer a
precompiled wheel. ``flash_attention_windows.txt`` lists, per row:
Torch;Cuda;Link;PyTorchLink
│ │ │ └ the exact `pip install torch... [--index-url ...]` command
│ │ │ └ the exact `pip install torch... --index-url ...` command
│ │ │ that pairs with this flash-attn wheel (ABI-matched)
│ │ └ flash-attn wheel URL
│ └ CUDA build the wheel targets (match key against the driver;
│ "13.0" and "13.0.0" both work — only major.minor is compared)
│ └ CUDA build the wheel targets (match key against the driver)
└ torch version (informational; also encoded in the wheel + PyTorchLink)
Python is pinned to 3.13 by uv (see .python-version) so it is no longer a match
key — every wheel in both tables is cp313. We just pick the newest CUDA build
the driver can run and hand the caller both pieces to install.
key — every wheel here is cp313. We just pick the newest CUDA build the driver
can run and hand the caller both pieces to install.
On a match it prints two `KEY=value` lines to stdout:
WHEEL=https://.../flash_attn-...cp313-win_amd64.whl
TORCHARGS=torch==2.12.0 torchvision==0.27.0 --index-url https://download.pytorch.org/whl/cu130
(``TORCHARGS`` is column 4 with the leading ``pip install`` / ``pip3 install``
stripped, so the caller can run it with ``uv pip install``.) On no match — no
NVIDIA driver, an unsupported platform/arch, or a driver older than every listed
CUDA build — it prints nothing and exits 0; the caller decides what that means.
(``TORCHARGS`` is column 4 with the leading ``pip install`` stripped, so the
caller can run it with ``uv pip install``.) On no match it prints nothing.
Diagnostics go to stderr. Standard library + nvidia-smi only.
macOS has no CUDA, so rigging is unavailable there and this prints nothing.
Override CUDA detection with RIGTOOLS_CUDA (e.g. "12.8").
"""
from __future__ import annotations
import os
import platform
import re
import shutil
import subprocess
import sys
from pathlib import Path
_HERE = Path(__file__).resolve().parent
# Wheels are platform-tagged: a win_amd64 wheel is rejected outright by pip/uv on
# Linux ("wheel is compatible with Windows, but you're on Linux"), so the table
# MUST follow the host rather than being a single shared list.
WHEELS_FILE = _HERE / ("flash_attention_windows.txt" if sys.platform == "win32"
else "flash_attention_linux.txt")
WHEELS_FILE = Path(__file__).resolve().parent / "flash_attention_windows.txt"
def driver_cuda() -> float | None:
"""Max CUDA version the NVIDIA driver supports (from nvidia-smi), or None."""
override = os.environ.get("RIGTOOLS_CUDA")
if override:
forced = cuda_key(override)
if forced is not None:
return forced
try:
return float(override)
except ValueError:
pass
exe = shutil.which("nvidia-smi")
if not exe:
return None
@ -69,17 +56,6 @@ def driver_cuda() -> float | None:
return float(f"{m.group(1)}.{m.group(2)}") if m else None
def cuda_key(text: str) -> float | None:
"""Normalise a CUDA column to a comparable major.minor float.
Accepts "13", "13.0" and "13.0.0" — the Linux table quotes three-part CUDA
versions, and a bare float() on those raises, which would silently drop the
row and look identical to "no GPU".
"""
m = re.match(r"\s*(\d+)(?:\.(\d+))?", text)
return float(f"{m.group(1)}.{m.group(2) or 0}") if m else None
def parse_rows():
"""Yield (torch_ver, cuda: float, wheel_url, torch_args) from the wheels file."""
rows = []
@ -91,37 +67,19 @@ def parse_rows():
if len(parts) < 4:
continue
torch_ver, cuda, link, pytorch_cmd = parts[0], parts[1], parts[2], parts[3]
cuda_f = cuda_key(cuda)
if cuda_f is None:
try:
cuda_f = float(cuda)
except ValueError:
continue
# Strip the leading "pip install" / "pip3 install" (or the "uv "-prefixed
# forms) so the caller can run it via `uv pip install <args>`.
args = re.sub(r"^\s*(uv\s+)?pip3?\s+install\s+", "", pytorch_cmd).strip()
# Strip the leading "pip install" (or "uv pip install") so the caller can
# run it via `uv pip install <args>`.
args = re.sub(r"^\s*(uv\s+)?pip\s+install\s+", "", pytorch_cmd).strip()
rows.append((torch_ver, cuda_f, link, args))
return rows
def main() -> None:
py = f"{sys.version_info.major}.{sys.version_info.minor}"
# Platform/arch gates first: both tables ship x86_64 wheels for a CUDA GPU, so
# anywhere else there is nothing to pick and saying so beats letting the caller
# download multi-GB of torch on the way to an unavoidable failure.
if sys.platform == "darwin":
print("[flash-attn] macOS has no CUDA; rigging is unavailable here.", file=sys.stderr)
return
if sys.platform not in ("win32", "linux"):
print(f"[flash-attn] Unsupported platform {sys.platform!r}; no prebuilt wheels listed.", file=sys.stderr)
return
arch = platform.machine().lower()
if arch not in ("x86_64", "amd64"):
print(f"[flash-attn] Unsupported CPU architecture {arch!r} — the listed wheels are "
f"x86_64 only.", file=sys.stderr)
return
if not WHEELS_FILE.exists():
print(f"[flash-attn] Missing wheel table {WHEELS_FILE.name}.", file=sys.stderr)
return
cuda = driver_cuda()
if cuda is None:
print("[flash-attn] No NVIDIA GPU / CUDA detected; skipping prebuilt wheel.", file=sys.stderr)
@ -129,7 +87,7 @@ def main() -> None:
rows = parse_rows()
if not rows:
print(f"[flash-attn] No usable rows in {WHEELS_FILE.name}.", file=sys.stderr)
print("[flash-attn] No usable rows in flash_attention_windows.txt.", file=sys.stderr)
return
# Rows whose CUDA build the driver can run (wheel_cuda <= driver_cuda),
@ -145,8 +103,8 @@ def main() -> None:
if py != "3.13":
print(f"[flash-attn] WARNING: running Python {py}, but the wheels are cp313. "
f"Expect an install failure unless the venv is Python 3.13.", file=sys.stderr)
print(f"[flash-attn] {WHEELS_FILE.name}: driver CUDA {cuda} -> wheel CUDA {wheel_cuda}, "
f"torch {torch_ver}.", file=sys.stderr)
print(f"[flash-attn] driver CUDA {cuda} -> wheel CUDA {wheel_cuda}, torch {torch_ver}.",
file=sys.stderr)
print(f"WHEEL={link}")
print(f"TORCHARGS={torch_args}")

View file

@ -1,706 +0,0 @@
from copy import deepcopy
from dataclasses import dataclass
from typing import Tuple, Union, List, Optional, Dict
from numpy import ndarray
from abc import ABC, abstractmethod
from scipy.spatial.transform import Rotation as R
import numpy as np
import random
from .spec import ConfigSpec
from ..rig_package.utils import axis_angle_to_matrix
from ..rig_package.info.asset import Asset
@dataclass(frozen=True)
class Augment(ConfigSpec):
@classmethod
@abstractmethod
def parse(cls, **kwags) -> 'Augment':
pass
@abstractmethod
def transform(self, asset: Asset, **kwargs):
pass
@dataclass(frozen=True)
class AugmentTrim(Augment):
"""randomly delete joints and vertices"""
@classmethod
def parse(cls, **kwargs) -> 'AugmentTrim':
cls.check_keys(kwargs)
return AugmentTrim()
def transform(self, asset: Asset, **kwargs):
asset.trim_skeleton()
@dataclass(frozen=True)
class AugmentDelete(Augment):
"""randomly delete joints and vertices"""
# probability
p: float
# how much to keep
rate: float
@classmethod
def parse(cls, **kwargs) -> 'AugmentDelete':
cls.check_keys(kwargs)
return AugmentDelete(
p=kwargs.get('p', 0.),
rate=kwargs.get('rate', 0.5),
)
def transform(self, asset: Asset, **kwargs):
if asset.skin is None:
raise ValueError("do not have skin")
if asset.parents is None:
raise ValueError("do not have parents")
asset.normalize_skin()
def select_k(arr: List, k: int):
if len(arr) <= k:
return arr
else:
rest_indices = list(range(1, len(arr)))
selected_indices = sorted(random.sample(rest_indices, k))
return [arr[i] for i in selected_indices]
if np.random.rand() >= self.p:
return
ids = select_k([i for i in range(asset.J)], max(int(asset.J * (1 - np.random.rand() * self.rate)), 1))
if len(ids) == 0:
return
# keep bones with no skin
keep = {}
for id in ids:
keep[id] = True
for id in range(asset.J):
if np.all(asset.skin[:, id] < 0.1):
keep[id] = True
keep[asset.root] = True
vertices_to_delete = np.zeros(asset.N, dtype=bool)
for id in range(asset.J):
if id not in keep:
dominant = asset.skin.argmax(axis=1) == id
x = (asset.skin[:, id] > 0.1) & dominant
if np.all(~x) or x.sum() * asset.J < asset.N: # avoid collapsing
keep[id] = 1
continue
vertices_to_delete[x] = True
if np.all(vertices_to_delete):
return
if asset.faces is not None:
indices = np.where(~vertices_to_delete)[0]
face_mask = np.all(np.isin(asset.faces, indices), axis=1)
if np.all(~face_mask):
return
joints_to_delete: List[int|str] = [i for i in range(asset.J) if i not in keep]
asset.delete_joints(joints_to_delete)
asset.delete_vertices(np.arange(asset.N)[vertices_to_delete])
@dataclass(frozen=True)
class AugmentDropPart(Augment):
"""randomly drop subtrees and their vertices"""
# probability
p: float
# drop rate
rate: float
@classmethod
def parse(cls, **kwargs) -> 'AugmentDropPart':
cls.check_keys(kwargs)
return AugmentDropPart(
p=kwargs.get('p', 0.),
rate=kwargs.get('rate', 0.5),
)
def transform(self, asset: Asset, **kwargs):
if np.random.rand() >= self.p:
return
if asset.parents is None:
raise ValueError("do not have parents")
if asset.skin is None:
raise ValueError("do not have skin")
keep = []
for id in range(asset.J):
if np.random.rand() < self.rate:
keep.append(id)
if len(keep) == 0:
return
for id in reversed(asset.dfs_order):
p = asset.parents[id]
if p == -1:
continue
if id in keep and p not in keep:
keep.append(p)
mask = np.zeros(asset.N, dtype=bool)
for id in keep:
mask[asset.skin[:, id] > 1e-5] = True
vertices_to_delete = ~mask
if np.all(vertices_to_delete):
return
if asset.faces is not None:
indices = np.where(~vertices_to_delete)[0]
face_mask = np.all(np.isin(asset.faces, indices), axis=1)
if np.all(~face_mask):
return
joints_to_delete: List[int|str] = [i for i in range(asset.J) if i not in keep]
asset.delete_joints(joints_to_delete)
asset.delete_vertices(np.arange(asset.N)[vertices_to_delete])
def inverse(self, asset: Asset):
pass
@dataclass(frozen=True)
class AugmentCollapse(Augment):
"""randomly merge joints"""
# collapse the skeleton with probability p
p: float
# probability to merge the bone
rate: float
# max bones
max_bones: int
@classmethod
def parse(cls, **kwargs) -> 'AugmentCollapse':
cls.check_keys(kwargs)
return AugmentCollapse(
p=kwargs.get('p', 0.),
rate=kwargs.get('rate', 0.),
max_bones=kwargs.get('max_bones', 2147483647),
)
def transform(self, asset: Asset, **kwargs):
def select_k(arr: List, k: int):
if len(arr) <= k:
return arr
else:
rest_indices = list(range(1, len(arr)))
selected_indices = sorted(random.sample(rest_indices, k))
return [arr[i] for i in selected_indices]
root = asset.root
if np.random.rand() < self.p:
ids = []
for id in range(asset.J):
if np.random.rand() >= self.rate:
ids.append(id)
if root not in ids:
ids.append(root)
keep: List[int|str] = select_k([i for i in range(asset.J) if i in ids], self.max_bones)
if root not in keep:
keep[0] = root
asset.set_order(new_orders=keep)
elif asset.J > self.max_bones:
ids = select_k([i for i in range(asset.J)], k=self.max_bones)
if root not in ids:
ids[0] = root
keep: List[int|str] = [i for i in range(asset.J) if i in ids]
asset.set_order(new_orders=keep)
@dataclass(frozen=True)
class AugmentJointDiscrete(Augment):
# perturb the skeleton with probability p
p: float
# num of discretized coord
discrete: int
# continuous range
continuous_range: Tuple[float, float]
@classmethod
def parse(cls, **kwargs) -> 'AugmentJointDiscrete':
cls.check_keys(kwargs)
return AugmentJointDiscrete(
p=kwargs.get('p', 0.),
discrete=kwargs.get('discrete', 256),
continuous_range=kwargs.get('continuous_range', [-1., 1.]),
)
def _discretize(
self,
t: ndarray,
continuous_range: Tuple[float, float],
num_discrete: int,
) -> ndarray:
lo, hi = continuous_range
assert hi >= lo
t = (t - lo) / (hi - lo)
t *= num_discrete
return np.clip(t.round(), 0, num_discrete - 1).astype(np.int64)
def _undiscretize(
self,
t: ndarray,
continuous_range: Tuple[float, float],
num_discrete: int,
) -> ndarray:
lo, hi = continuous_range
assert hi >= lo
t = t.astype(np.float32) + 0.5
t /= num_discrete
return t * (hi - lo) + lo
def transform(self, asset: Asset, **kwargs):
if np.random.rand() < self.p:
joints = asset.joints
if joints is not None and asset.matrix_local is not None:
joints = self._undiscretize(self._discretize(
joints,
self.continuous_range,
self.discrete,
),
self.continuous_range,
self.discrete,
)
asset.matrix_local[:, :3, 3] = joints
@dataclass(frozen=True)
class AugmentJointPerturb(Augment):
# perturb the skeleton with probability p
p: float
# jitter sigma on joints
sigma: float
# jitter clip on joints
clip: float
@classmethod
def parse(cls, **kwargs) -> 'AugmentJointPerturb':
cls.check_keys(kwargs)
return AugmentJointPerturb(
p=kwargs.get('p', 0.),
sigma=kwargs.get('sigma', 0.),
clip=kwargs.get('clip', 0.),
)
def transform(self, asset: Asset, **kwargs):
if np.random.rand() < self.p and asset.matrix_local is not None:
asset.matrix_local[:, :3] += np.clip(
np.random.normal(0, self.sigma, (asset.J, 3)),
-self.clip,
self.clip,
)
@dataclass(frozen=True)
class AugmentLBS(Augment):
# apply a random pose with probability p
random_pose_p: float
# random pose angle range
random_pose_angle: float
# random scale
random_scale_range: Tuple[float, float]
@classmethod
def parse(cls, **kwargs) -> 'AugmentLBS':
cls.check_keys(kwargs)
return AugmentLBS(
random_pose_p=kwargs.get('random_pose_p', 0.),
random_pose_angle=kwargs.get('random_pose_angle', 0.),
random_scale_range=kwargs.get('random_scale_range', (1., 1.)),
)
def _apply(self, v: ndarray, trans: ndarray) -> ndarray:
return np.matmul(v, trans[:3, :3].transpose()) + trans[:3, 3]
def transform(self, asset: Asset, **kwargs):
def get_matrix_basis(angle: float):
matrix = axis_angle_to_matrix((np.random.rand(asset.J, 3) - 0.5) * angle / 180 * np.pi * 2).astype(np.float32)
return matrix
if np.random.rand() < self.random_pose_p and asset.joints is not None:
matrix_basis = get_matrix_basis(self.random_pose_angle)
max_offset = (asset.joints.max(axis=0) - asset.joints.min(axis=0)).max()
matrix_basis[:, :3, :3] *= np.tile(np.random.uniform(low=self.random_scale_range[0], high=self.random_scale_range[1], size=(asset.J, 1, 1)), (1, 3, 3))
asset.vertices_with_pose(matrix_basis=matrix_basis, inplace=True)
@dataclass(frozen=True)
class AugmentLinear(Augment):
# apply random rotation with probability p
random_rotate_p: float
# random rotation angle(degree)
random_rotate_angle: float
# swap x with probability p
random_flip_x_p: float
# swap y with probability p
random_flip_y_p: float
# swap z with probability p
random_flip_z_p: float
# probability to pick an angle in static_rotate_x
static_rotate_x_p: float
# rotate around x axis among given angles(degrees)
static_rotate_x: List[float]
# probability to pick an angle in static_rotate_y
static_rotate_y_p: float
# rotate around y axis among given angles(degrees)
static_rotate_y: List[float]
# probability to pick an angle in static_rotate_z
static_rotate_z_p: float
# rotate around z axis among given angles(degrees)
static_rotate_z: List[float]
# apply random scaling with probability p
random_scale_p: float
# random scaling xyz axis
random_scale: Tuple[float, float]
# randomly change xyz orientation
random_transpose: float
@classmethod
def parse(cls, **kwargs) -> 'AugmentLinear':
if kwargs.get('random_flip_x_p', 0) > 0 or kwargs.get('random_flip_y_p', 0) > 0 or kwargs.get('random_flip_z_p', 0) > 0:
print("\033[31mWARNING: random flip is enabled and is very likely to confuse ar model !\033[0m")
cls.check_keys(kwargs)
return AugmentLinear(
random_rotate_p=kwargs.get('random_rotate_p', 0.),
random_rotate_angle=kwargs.get('random_rotate_angle', 0.),
random_flip_x_p=kwargs.get('random_flip_x_p', 0.),
random_flip_y_p=kwargs.get('random_flip_y_p', 0.),
random_flip_z_p=kwargs.get('random_flip_z_p', 0.),
static_rotate_x_p=kwargs.get('static_rotate_x_p', 0.),
static_rotate_x=kwargs.get('static_rotate_x', []),
static_rotate_y_p=kwargs.get('static_rotate_y_p', 0.),
static_rotate_y=kwargs.get('static_rotate_y', []),
static_rotate_z_p=kwargs.get('static_rotate_z_p', 0.),
static_rotate_z=kwargs.get('static_rotate_z', []),
random_scale_p=kwargs.get('random_scale_p', 0.),
random_scale=kwargs.get('random_scale', [1.0, 1.0]),
random_transpose=kwargs.get('random_transpose', 0.),
)
def _apply(self, v: ndarray, trans: ndarray) -> ndarray:
return np.matmul(v, trans[:3, :3].transpose()) + trans[:3, 3]
def transform(self, asset: Asset, **kwargs):
trans_vertex = np.eye(4, dtype=np.float32)
r = np.eye(4, dtype=np.float32)
if np.random.rand() < self.random_rotate_p:
angle = self.random_rotate_angle
axis_angle = (np.random.rand(3) - 0.5) * angle / 180 * np.pi * 2
r = R.from_rotvec(axis_angle).as_matrix()
r = np.pad(r, ((0, 1), (0, 1)), 'constant', constant_values=0.)
r[3, 3] = 1.
if np.random.uniform(0, 1) < self.random_flip_x_p:
r @= np.array([
[-1.0, 0.0, 0.0, 0.0],
[ 0.0, 1.0, 0.0, 0.0],
[ 0.0, 0.0, 1.0, 0.0],
[ 0.0, 0.0, 0.0, 1.0],
])
if np.random.uniform(0, 1) < self.random_flip_y_p:
r @= np.array([
[1.0, 0.0, 0.0, 0.0],
[0.0, -1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
])
if np.random.uniform(0, 1) < self.random_flip_z_p:
r @= np.array([
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, -1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
])
if np.random.uniform(0, 1) < self.static_rotate_x_p:
assert len(self.static_rotate_x) > 0, "static rotation of x is enabled, but static_rotate_x is empty"
angle = np.random.choice(self.static_rotate_x) / 180 * np.pi
c = np.cos(angle)
s = np.sin(angle)
r @= np.array([
[ 1.0, 0.0, 0.0, 0.0],
[ 0.0, c, s, 0.0],
[ 0.0, -s, c, 0.0],
[ 0.0, 0.0, 0.0, 1.0],
])
if np.random.uniform(0, 1) < self.static_rotate_y_p:
assert len(self.static_rotate_y) > 0, "static rotation of y is enabled, but static_rotate_y is empty"
angle = np.random.choice(self.static_rotate_y) / 180 * np.pi
c = np.cos(angle)
s = np.sin(angle)
r @= np.array([
[ c, 0.0, -s, 0.0],
[ 0.0, 1.0, 0.0, 0.0],
[ s, 0.0, c, 0.0],
[ 0.0, 0.0, 0.0, 1.0],
])
if np.random.uniform(0, 1) < self.static_rotate_z_p:
assert len(self.static_rotate_z) > 0, "static rotation of z is enabled, but static_rotate_z is empty"
angle = np.random.choice(self.static_rotate_z) / 180 * np.pi
c = np.cos(angle)
s = np.sin(angle)
r @= np.array([
[ c, s, 0.0, 0.0],
[ -s, c, 0.0, 0.0],
[ 0.0, 0.0, 1.0, 0.0],
[ 0.0, 0.0, 0.0, 1.0],
])
if np.random.uniform(0, 1) < self.random_scale_p:
scale_x = np.random.uniform(self.random_scale[0], self.random_scale[1])
scale_y = np.random.uniform(self.random_scale[0], self.random_scale[1])
scale_z = np.random.uniform(self.random_scale[0], self.random_scale[1])
r @= np.array([
[scale_x, 0.0, 0.0, 0.0],
[0.0, scale_y, 0.0, 0.0],
[0.0, 0.0, scale_z, 0.0],
[0.0, 0.0, 0.0, 1.0],
])
if np.random.uniform(0, 1) < self.random_transpose:
permutations = [
(0, 1, 2), # x, y, z
(0, 2, 1), # x, z, y
(1, 0, 2), # y, x, z
(1, 2, 0), # y, z, x
(2, 0, 1), # z, x, y
(2, 1, 0), # z, y, x
]
direction_signs = [
(1, 1, 1),
(1, 1, -1),
(1, -1, 1),
(1, -1, -1),
(-1, 1, 1),
(-1, 1, -1),
(-1, -1, 1),
(-1, -1, -1),
]
perm = permutations[np.random.randint(0, 6)]
sign = direction_signs[np.random.randint(0, 8)]
m = np.zeros((4, 4))
for i in range(3):
m[i, perm[i]] = sign[i]
m[3, 3] = 1.0
r = m @ r
trans_vertex = r @ trans_vertex
# apply transform here
asset.transform(trans=trans_vertex)
@dataclass(frozen=True)
class AugmentAffine(Augment):
# final normalization cube
normalize_into: Tuple[float, float]
# randomly scale coordinates with probability p
random_scale_p: float
# scale range (lower, upper)
random_scale: Tuple[float, float]
# randomly shift coordinates with probability p
random_shift_p: float
# shift range (lower, upper)
random_shift: Tuple[float, float]
@classmethod
def parse(cls, **kwargs) -> 'AugmentAffine':
cls.check_keys(kwargs)
return AugmentAffine(
normalize_into=kwargs.get('normalize_into', [-1.0, 1.0]),
random_scale_p=kwargs.get('random_scale_p', 0.),
random_scale=kwargs.get('random_scale', [1., 1.]),
random_shift_p=kwargs.get('random_shift_p', 0.),
random_shift=kwargs.get('random_shift', [0., 0.]),
)
def transform(self, asset: Asset, **kwargs):
if asset.vertices is None:
raise ValueError("do not have vertices")
bound_min = asset.vertices.min(axis=0)
bound_max = asset.vertices.max(axis=0)
if asset.joints is not None:
joints_bound_min = asset.joints.min(axis=0)
joints_bound_max = asset.joints.max(axis=0)
bound_min = np.minimum(bound_min, joints_bound_min)
bound_max = np.maximum(bound_max, joints_bound_max)
trans_vertex = np.eye(4, dtype=np.float32)
trans_vertex = _trans_to_m(-(bound_max + bound_min)/2) @ trans_vertex
if self.normalize_into is not None:
# scale into the cube
normalize_into = self.normalize_into
scale = np.max((bound_max - bound_min) / (normalize_into[1] - normalize_into[0]))
trans_vertex = _scale_to_m(1. / scale) @ trans_vertex
bias = (normalize_into[0] + normalize_into[1]) / 2
trans_vertex = _trans_to_m(np.array([bias, bias, bias], dtype=np.float32)) @ trans_vertex
if np.random.rand() < self.random_scale_p:
scale = _scale_to_m(np.random.uniform(self.random_scale[0], self.random_scale[1]))
trans_vertex = scale @ trans_vertex
if np.random.rand() < self.random_shift_p:
l, r = self.random_shift
shift_vals = np.array([
np.random.uniform(l, r),
np.random.uniform(l, r),
np.random.uniform(l, r),
], dtype=np.float32)
if self.normalize_into is not None:
def _apply(v: ndarray, trans: ndarray) -> ndarray:
return np.matmul(v, trans[:3, :3].transpose()) + trans[:3, 3]
lo, hi = self.normalize_into
pts_min = _apply(bound_min[None, :], trans_vertex)[0]
pts_max = _apply(bound_max[None, :], trans_vertex)[0]
low_allowed = lo - pts_min
high_allowed = hi - pts_max
shift_vals = np.array([
np.random.uniform(low_allowed[0], high_allowed[0]),
np.random.uniform(low_allowed[1], high_allowed[1]),
np.random.uniform(low_allowed[2], high_allowed[2]),
], dtype=np.float32)
shift = _trans_to_m(shift_vals.astype(np.float32))
trans_vertex = shift @ trans_vertex
asset.transform(trans=trans_vertex)
@dataclass(frozen=True)
class AugmentJitter(Augment):
# probability
p: float
# jitter sigma on vertices
vertex_sigma: float
# jitter clip on vertices
vertex_clip: float
# jitter sigma on normals
normal_sigma: float
# jitter clip on normals
normal_clip: float
@classmethod
def parse(cls, **kwargs) -> 'AugmentJitter':
cls.check_keys(kwargs)
return AugmentJitter(
p=kwargs.get('p', 0.5),
vertex_sigma=kwargs.get('vertex_sigma', 0.),
vertex_clip=kwargs.get('vertex_clip', 0.),
normal_sigma=kwargs.get('normal_sigma', 0.),
normal_clip=kwargs.get('normal_clip', 0.),
)
def transform(self, asset: Asset, **kwargs):
vertex_sigma = self.vertex_sigma
vertex_clip = self.vertex_clip
normal_sigma = self.normal_sigma
normal_clip = self.normal_clip
if np.random.rand() < self.p:
scale = np.random.rand() + 1e-6
vertex_sigma *= scale
vertex_clip *= scale
scale = np.random.rand() + 1e-6
normal_sigma *= scale
normal_clip *= scale
if vertex_sigma > 0 and asset.vertices is not None:
noise = np.clip(np.random.randn(*asset.vertices.shape) * vertex_sigma, -vertex_clip, vertex_clip).astype(np.float32)
asset.vertices += noise
if normal_sigma > 0:
if asset.vertex_normals is not None:
noise = np.clip(np.random.randn(*asset.vertex_normals.shape) * normal_sigma, -normal_clip, normal_clip).astype(np.float32)
asset.vertex_normals += noise
if asset.face_normals is not None:
noise = np.clip(np.random.randn(*asset.face_normals.shape) * normal_sigma, -normal_clip, normal_clip).astype(np.float32)
asset.face_normals += noise
@dataclass(frozen=True)
class AugmentNormalize(Augment):
@classmethod
def parse(cls, **kwargs) -> 'AugmentNormalize':
cls.check_keys(kwargs)
return AugmentNormalize()
def transform(self, asset: Asset, **kwargs):
epsilon = 1e-10
if asset.vertex_normals is not None:
vertex_norms = np.linalg.norm(asset.vertex_normals, axis=1, keepdims=True)
vertex_norms = np.maximum(vertex_norms, epsilon)
asset.vertex_normals = asset.vertex_normals / vertex_norms
asset.vertex_normals = np.nan_to_num(asset.vertex_normals, nan=0., posinf=0., neginf=0.) # type: ignore
if asset.face_normals is not None:
face_norms = np.linalg.norm(asset.face_normals, axis=1, keepdims=True)
face_norms = np.maximum(face_norms, epsilon)
asset.face_normals = asset.face_normals / face_norms
asset.face_normals = np.nan_to_num(asset.face_normals, nan=0., posinf=0., neginf=0.) # type: ignore
def _trans_to_m(v: ndarray):
m = np.eye(4, dtype=np.float32)
m[0:3, 3] = v
return m
def _scale_to_m(r: ndarray|float):
m = np.zeros((4, 4), dtype=np.float32)
m[0, 0] = r
m[1, 1] = r
m[2, 2] = r
m[3, 3] = 1.
return m
def get_augments(*args) -> List[Augment]:
MAP = {
'trim': AugmentTrim,
'delete': AugmentDelete,
'drop_part': AugmentDropPart,
'collapse': AugmentCollapse,
'lbs': AugmentLBS,
'linear': AugmentLinear,
'affine': AugmentAffine,
'jitter': AugmentJitter,
'joint_perturb': AugmentJointPerturb,
'joint_discrete': AugmentJointDiscrete,
'normalize': AugmentNormalize,
}
MAP: Dict[str, type[Augment]]
augments = []
for (i, config) in enumerate(args):
__target__ = config.get('__target__')
assert __target__ is not None, f"do not find `__target__` in augment of position {i}"
c = deepcopy(config)
del c['__target__']
augments.append(MAP[__target__].parse(**c))
return augments

View file

@ -1,344 +0,0 @@
from abc import abstractmethod, ABC
from collections import defaultdict
from dataclasses import dataclass, field
from numpy import ndarray
from random import shuffle
from typing import Dict, List, Optional
import numpy as np
import requests
import os
from ..rig_package.info.asset import Asset
from ..server.spec import BPY_SERVER, bytes_to_object, object_to_bytes
from .spec import ConfigSpec
@dataclass
class LazyAsset(ABC):
"""store datapath and load upon requiring"""
path: str
cls: Optional[str]=None
@abstractmethod
def load(self) -> 'Asset':
raise NotImplementedError()
@dataclass
class BpyLazyAsset(LazyAsset):
def load(self) -> 'Asset':
from ..rig_package.parser.bpy import BpyParser
asset = BpyParser.load(filepath=self.path)
asset.cls = self.cls
asset.path = self.path
return asset
@dataclass
class BpyServerLazyAsset(LazyAsset):
"""workaround while bpy is working in multiple threads"""
def load(self) -> 'Asset':
try:
asset = bytes_to_object(requests.get(f"{BPY_SERVER}/load", data=object_to_bytes(self.path)).content)
if isinstance(asset, str):
raise RuntimeError(f"bpy server failed: {asset}")
assert isinstance(asset, Asset)
asset.cls = self.cls
asset.path = self.path
return asset
except Exception as e:
raise RuntimeError(f"bpy server failed: {str(e)}")
@dataclass
class NpzLazyAsset(LazyAsset):
def load(self) -> 'Asset':
d = np.load(self.path, allow_pickle=True)
asset = Asset(
vertices=d['vertices'],
faces=d['faces'],
mesh_names=d.get('mesh_names', None),
joint_names=d.get('joint_names', None),
parents=d.get('parents', None),
lengths=d.get('lengths', None),
matrix_world=d.get('matrix_world', None),
matrix_local=d.get('matrix_local', None),
armature_name=d.get('armature_name', None),
skin=d.get('skin', None),
cls=self.cls,
path=self.path
)
asset.cls = self.cls
asset.path = self.path
return asset
@dataclass
class UniRigLazyAsset(LazyAsset):
"""map unirig's data correctly"""
def load(self) -> 'Asset':
def bn(x):
if isinstance(x, ndarray) and x.ndim==0:
return x.item()
return x
d = np.load(self.path, allow_pickle=True)
parents = bn(d.get('parents', None))
if parents is not None:
parents = [-1 if x is None else x for x in parents]
parents = np.array(parents)
matrix_local = bn(d.get('matrix_local', None))
joints = bn(d.get('joints', None))
if matrix_local is not None and matrix_local.ndim != 3 and joints is not None:
matrix_local = np.zeros((joints.shape[0], 4, 4))
matrix_local[...] = np.eye(4)
matrix_local[:, :3, 3] = joints
asset = Asset(
vertices=d['vertices'],
faces=d['faces'],
joint_names=bn(d.get('names', None)),
parents=parents, # type: ignore
lengths=bn(d.get('lengths', None)),
matrix_world=bn(d.get('matrix_world', None)),
matrix_local=matrix_local,
armature_name=bn(d.get('armature_name', None)),
skin=bn(d.get('skin', None)),
cls=self.cls,
path=self.path
).change_dtype(float_dtype=np.float32, int_dtype=np.int32)
asset.cls = self.cls
asset.path = self.path
return asset
@dataclass
class Datapath(ConfigSpec):
"""handle input data paths"""
# all filepaths
filepaths: List[str]
# root to add to prefix
input_dataset_dir: str=''
# name of class
cls_name: Optional[List[str]]=None
# bias in a single class
cls_bias: Optional[List[int]]=None
# num of files in a single class
cls_length: Optional[List[int]]=None
# how many files to return when using data sampling
num_files: Optional[int]=None
# use proportion data sampling
use_prob: bool=False
# weight
cls_weight: Optional[List[float]]=None
# use bpy loader
loader: type[LazyAsset]=BpyLazyAsset
# data name
data_name: Optional[str]=None
# check if path exists
ignore_check: bool=False
#################################################################
# other vertex groups
vertex_groups: Dict[str, ndarray]=field(default_factory=dict)
# sampled vertices
sampled_vertices: Optional[ndarray]=None
# sampled normals
sampled_normals: Optional[ndarray]=None
# sampled vertex groups
sampled_vertex_groups: Optional[Dict[str, ndarray]]=None
@classmethod
def parse(cls, **kwargs) -> 'Datapath':
MAP = {
None: BpyLazyAsset,
'bpy': BpyLazyAsset,
'bpy_server': BpyServerLazyAsset,
'npz': NpzLazyAsset,
'unirig': UniRigLazyAsset,
}
input_dataset_dir = kwargs.get('input_dataset_dir', '')
num_files = kwargs.get('num_files', None)
use_prob = kwargs.get('use_prob', False)
data_name = kwargs.get('data_name', 'raw_data.npz')
data_path = kwargs.get('data_path', None)
loader_cls = MAP[kwargs.get('loader', None)]
ignore_check = kwargs.get('ignore_check', False)
if data_path is not None:
filepaths = []
if isinstance(data_path, dict):
cls_name = []
cls_bias = []
cls_length = []
cls_weight = []
for name, v in data_path.items():
assert isinstance(v, list), "items in the dict must be a list of data list paths"
for item in v:
if isinstance(item, str):
datalist_path = item
weight = 1.0
else:
datalist_path = item[0]
weight = item[1]
cls_name.append(name)
lines = [x.strip() for x in open(datalist_path, "r").readlines()]
ok_lines = []
missing = 0
for line in lines:
if ignore_check:
ok_lines.append(line)
elif os.path.exists(os.path.join(input_dataset_dir, line, data_name)):
ok_lines.append(line)
else:
missing += 1
if missing != 0:
print(f"\033[31m{datalist_path}: {missing} missing files\033[0m")
cls_bias.append(len(filepaths))
cls_length.append(len(ok_lines))
cls_weight.append(weight)
filepaths.extend(ok_lines)
else:
raise NotImplementedError()
else:
_filepaths = kwargs['filepaths']
if isinstance(_filepaths, list):
filepaths = _filepaths
cls_name = None
cls_bias = None
cls_length = None
cls_weight = None
elif isinstance(_filepaths, dict):
filepaths = []
cls_name = []
cls_bias = []
cls_length = []
cls_weight = []
for k, v in _filepaths.items():
assert isinstance(v, list), "items in the dict must be a list of paths"
cls_name.append(k)
cls_bias.append(len(filepaths))
cls_length.append(len(v))
cls_weight.append(1.0)
filepaths.extend(v)
else:
raise NotImplementedError()
if cls_weight is not None:
total = sum(cls_weight)
cls_weight = [x/total for x in cls_weight]
return Datapath(
filepaths=filepaths,
input_dataset_dir=input_dataset_dir,
cls_name=cls_name,
cls_bias=cls_bias,
cls_length=cls_length,
num_files=num_files,
use_prob=use_prob,
cls_weight=cls_weight,
loader=loader_cls,
data_name=data_name,
ignore_check=ignore_check,
)
def make(self, path: str, cls: str|None) -> LazyAsset:
return self.loader(path=path, cls=cls)
def __getitem__(self, index: int) -> LazyAsset:
if self.use_prob and self.cls_weight is not None:
if self.cls_bias is None:
raise ValueError("do not have cls_bias")
if self.cls_length is None:
raise ValueError("do not have cls_length")
if not hasattr(self, "perms"):
self.perms = []
self.current_bias = []
for i in range(len(self.cls_weight)):
self.perms.append([x for x in range(self.cls_length[i])])
self.current_bias.append(0)
idx = np.random.choice(len(self.cls_weight), p=self.cls_weight)
i = self.perms[idx][self.current_bias[idx]]
self.current_bias[idx] += 1
if self.current_bias[idx] >= self.cls_length[idx]:
shuffle(self.perms[idx])
self.current_bias[idx] = 0
if self.cls_name is None:
name = None
else:
name = self.cls_name[idx]
path = os.path.join(self.input_dataset_dir, self.filepaths[i+self.cls_bias[idx]])
if self.data_name is not None:
path = os.path.join(path, self.data_name)
return self.make(path=path, cls=name)
else:
if self.cls_name is None or self.cls_bias is None or self.cls_length is None:
name = None
else:
name = None
for i in range(len(self.cls_bias)):
start = self.cls_bias[i]
end = start + self.cls_length[i]
if start <= index < end:
name = self.cls_name[i]
break
path = os.path.join(self.input_dataset_dir, self.filepaths[index])
if self.data_name is not None:
path = os.path.join(path, self.data_name)
return self.make(path=path, cls=name)
def get_data(self) -> List[LazyAsset]:
return [self[i] for i in range(len(self))]
def split_by_cls(self) -> Dict[str|None, 'Datapath']:
res: Dict[str|None, Datapath] = {}
if self.cls_name is None:
res[None] = self
return res
if self.cls_bias is None:
raise ValueError("do not have cls_bias")
if self.cls_length is None:
raise ValueError("do not have cls_length")
d_filepaths = defaultdict(list)
d_length = defaultdict(int)
d_weight = defaultdict(list)
for (i, cls) in enumerate(self.cls_name):
s = slice(self.cls_bias[i], self.cls_bias[i]+self.cls_length[i])
d_filepaths[cls].extend(self.filepaths[s].copy())
d_length[cls] += self.cls_length[i]
if self.cls_weight is not None:
d_weight[cls].append(self.cls_weight[i])
for cls in d_filepaths:
cls_weight = None if self.cls_weight is None else d_weight[cls]
if cls_weight is not None:
total = sum(cls_weight)
cls_weight = [x/total for x in cls_weight]
res[cls] = Datapath(
filepaths=d_filepaths[cls],
input_dataset_dir=self.input_dataset_dir,
cls_name=[cls],
cls_bias=[0],
cls_length=[len(d_filepaths[cls])],
num_files=self.num_files,
use_prob=self.use_prob,
cls_weight=cls_weight,
loader=self.loader,
data_name=self.data_name,
)
return res
def __len__(self):
if self.use_prob:
assert self.num_files is not None, 'num_files is not specified'
return self.num_files
return len(self.filepaths)

View file

@ -1,319 +0,0 @@
from copy import deepcopy
from dataclasses import dataclass
from lightning.pytorch.utilities.types import EVAL_DATALOADERS, TRAIN_DATALOADERS
from numpy import ndarray
from torch import Tensor
from torch.utils import data
from torch.utils.data import DataLoader, Dataset
from typing import Dict, List, Tuple, Callable, Optional
import os
import lightning.pytorch as pl
import numpy as np
import torch
from .datapath import Datapath, LazyAsset
from .spec import ConfigSpec
from .transform import Transform
from ..model.spec import ModelInput
from ..rig_package.info.asset import Asset
from ..tokenizer.spec import Tokenizer, TokenizeInput
@dataclass
class DatasetConfig(ConfigSpec):
shuffle: bool
batch_size: int
num_workers: int
datapath: Datapath
pin_memory: bool=True
persistent_workers: bool=True
@classmethod
def parse(cls, **kwargs) -> 'DatasetConfig':
cls.check_keys(kwargs)
return DatasetConfig(
shuffle=kwargs.get('shuffle', False),
batch_size=kwargs.get('batch_size', 1),
num_workers=kwargs.get('num_workers', 1),
pin_memory=kwargs.get('pin_memory', True),
persistent_workers=kwargs.get('persistent_workers', True),
datapath=Datapath.parse(**kwargs.get('datapath')),
)
def split_by_cls(self) -> Dict[str|None, 'DatasetConfig']:
res: Dict[str|None, DatasetConfig] = {}
datapath_dict = self.datapath.split_by_cls()
for cls, v in datapath_dict.items():
res[cls] = DatasetConfig(
shuffle=self.shuffle,
batch_size=self.batch_size,
num_workers=self.num_workers,
datapath=v,
pin_memory=self.pin_memory,
persistent_workers=self.persistent_workers,
)
return res
class RigDatasetModule(pl.LightningDataModule):
def __init__(
self,
process_fn: Optional[Callable[[List[ModelInput]], List[Dict]]]=None,
train_dataset_config: Optional[DatasetConfig]=None,
validate_dataset_config: Optional[Dict[str|None, DatasetConfig]]=None,
predict_dataset_config: Optional[Dict[str|None, DatasetConfig]]=None,
train_transform: Optional[Transform]=None,
validate_transform: Optional[Transform]=None,
predict_transform: Optional[Transform]=None,
tokenizer: Optional[Tokenizer]=None,
debug: bool=False,
):
super().__init__()
self.process_fn = process_fn
self.train_dataset_config = train_dataset_config
self.validate_dataset_config = validate_dataset_config
self.predict_dataset_config = predict_dataset_config
self.train_transform = train_transform
self.validate_transform = validate_transform
self.predict_transform = predict_transform
self.tokenizer = tokenizer
self.debug = debug
if debug:
print("\033[31mWARNING: debug mode, dataloader will be extremely slow !!!\033[0m")
# build train datapath
if self.train_dataset_config is not None:
self.train_datapath = self.train_dataset_config.datapath
else:
self.train_datapath = None
# build validate datapath
if self.validate_dataset_config is not None:
self.validate_datapath = {
cls: self.validate_dataset_config[cls].datapath
for cls in self.validate_dataset_config
}
else:
self.validate_datapath = None
# build predict datapath
if self.predict_dataset_config is not None:
self.predict_datapath = {
cls: self.predict_dataset_config[cls].datapath
for cls in self.predict_dataset_config
}
else:
self.predict_datapath = None
self.tokenizer = tokenizer
def prepare_data(self):
pass
def train_dataloader(self) -> TRAIN_DATALOADERS:
if self.train_dataset_config is None:
raise ValueError("do not have train_dataset_config")
if self.train_transform is None:
raise ValueError("do not have train_transform")
if self.train_datapath is not None:
self._train_ds = RigDataset(
process_fn=self.process_fn,
data=self.train_datapath.get_data(),
name="train",
tokenizer=self.tokenizer,
transform=self.train_transform,
debug=self.debug,
)
else:
return None
return self._create_dataloader(
dataset=self._train_ds,
config=self.train_dataset_config,
is_train=True,
drop_last=False,
)
def val_dataloader(self) -> EVAL_DATALOADERS:
if self.validate_dataset_config is None:
raise ValueError("do not have validate_dataset_config")
if self.validate_transform is None:
raise ValueError("do not have validate_transform")
if self.validate_datapath is not None:
self._validation_ds = {}
for cls in self.validate_datapath:
self._validation_ds[cls] = RigDataset(
process_fn=self.process_fn,
data=self.validate_datapath[cls].get_data(),
name=f"validate-{cls}",
tokenizer=self.tokenizer,
transform=self.validate_transform,
debug=self.debug,
)
else:
return None
return self._create_dataloader(
dataset=self._validation_ds,
config=self.validate_dataset_config,
is_train=False,
drop_last=False,
)
def predict_dataloader(self):
if self.predict_dataset_config is None:
raise ValueError("do not have predict_dataset_config")
if self.predict_transform is None:
raise ValueError("do not have predict_transform")
if self.predict_datapath is not None:
self._predict_ds = {}
for cls in self.predict_datapath:
self._predict_ds[cls] = RigDataset(
process_fn=self.process_fn,
data=self.predict_datapath[cls].get_data(),
name=f"predict-{cls}",
tokenizer=self.tokenizer,
transform=self.predict_transform,
debug=self.debug,
)
else:
return None
return self._create_dataloader(
dataset=self._predict_ds,
config=self.predict_dataset_config,
is_train=False,
drop_last=False,
)
def _create_dataloader(
self,
dataset: Dataset|Dict[str, Dataset],
config: DatasetConfig|Dict[str|None, DatasetConfig],
is_train: bool,
**kwargs,
) -> DataLoader|Dict[str, DataLoader]:
def create_single_dataloader(dataset, config: DatasetConfig, **kwargs):
return DataLoader(
dataset,
batch_size=config.batch_size,
shuffle=config.shuffle,
num_workers=config.num_workers,
pin_memory=config.pin_memory,
persistent_workers=config.persistent_workers,
collate_fn=dataset.collate_fn,
**kwargs,
)
if isinstance(dataset, Dict):
assert isinstance(config, dict)
return {k: create_single_dataloader(v, config[k], **kwargs) for k, v in dataset.items()}
else:
assert isinstance(config, DatasetConfig)
return create_single_dataloader(dataset, config, **kwargs)
class RigDataset(Dataset):
def __init__(
self,
data: List[LazyAsset],
transform: Transform,
name: Optional[str]=None,
process_fn: Optional[Callable[[List[ModelInput]], List[Dict]]]=None,
tokenizer: Optional[Tokenizer]=None,
debug: bool=False,
) -> None:
super().__init__()
self.data = data
self.name = name
self.process_fn = process_fn
self.tokenizer = tokenizer
self.transform = transform
self.debug = debug
if not debug:
assert self.process_fn is not None, 'missing data processing function'
def __len__(self) -> int:
return len(self.data)
def __getitem__(self, idx) -> ModelInput:
lazy_asset = self.data[idx]
asset = lazy_asset.load()
self.transform.apply(asset=asset)
if self.tokenizer is not None and asset.parents is not None:
x = TokenizeInput(
joints=asset.joints,
parents=asset.parents,
cls=asset.cls,
joint_names=asset.joint_names,
)
tokens = self.tokenizer.tokenize(input=x)
else:
tokens = None
return ModelInput(asset=asset, tokens=tokens)
def _collate_fn_debug(self, batch):
return batch
def _collate_fn(self, batch):
processed_batch = self.process_fn(batch) # type: ignore
processed_batch: List[Dict]
tensors_stack = {}
tensors_cat = {}
non_tensors = {}
vis = {}
def check(x):
assert x not in vis, f"multiple keys found: {x}"
vis[x] = True
for k, v in processed_batch[0].items():
if k == "cat":
assert isinstance(v, dict)
for k1 in v.keys():
check(k1)
tensors_cat[k1] = []
for i in range(len(processed_batch)):
v1 = processed_batch[i]['cat'][k1]
if isinstance(v1, ndarray):
v1 = torch.from_numpy(v1)
elif isinstance(v1, Tensor):
v1 = v1
else:
raise ValueError(f"cannot concatenate non-tensor type of key {k1}, type: {type(v1)}")
tensors_cat[k1].append(v1)
elif k == "non":
assert isinstance(v, dict)
for k1 in v.keys():
check(k1)
non_tensors[k1] = []
for i in range(len(processed_batch)):
v1 = processed_batch[i]['non'][k1]
if isinstance(v1, ndarray):
v1 = torch.from_numpy(v1)
non_tensors[k1].append(v1)
else:
check(k)
tensors_stack[k] = []
for i in range(len(processed_batch)):
v1 = processed_batch[i][k]
if isinstance(v1, ndarray):
v1 = torch.from_numpy(v1)
elif isinstance(v1, Tensor):
v1 = v1
else:
raise ValueError(f"cannot stack type of key {k}, type: {type(v1)}")
tensors_stack[k].append(v1)
collated_stack = {k: torch.stack(v) for k, v in tensors_stack.items()}
collated_cat = {k: torch.concat(v, dim=1) for k, v in tensors_cat.items()}
collated_batch = {
**collated_stack,
**collated_cat,
**non_tensors,
}
return collated_batch
def collate_fn(self, batch):
if self.debug:
return self._collate_fn_debug(batch)
return self._collate_fn(batch)

View file

@ -1,132 +0,0 @@
from collections import defaultdict
from dataclasses import dataclass
from numpy import ndarray
from omegaconf import OmegaConf
from typing import Dict, List, Tuple, Optional
from .spec import ConfigSpec
@dataclass
class Order(ConfigSpec):
# {part_name: [bone_name_1, bone_name_2, ...]}
parts: Dict[str, Dict[str, List[str]]]
# parts of bones to be arranged in [part_name_1, part_name_2, ...]
parts_order: Dict[str, List[str]]
# {skeleton_name: path}
skeleton_path: Optional[Dict[str, str]]=None
sort_by_xyz: bool=False
@classmethod
def parse(cls, **kwargs) -> 'Order':
cls.check_keys(kwargs)
skeleton_path = kwargs.get('skeleton_path', None)
if skeleton_path is not None:
parts = {}
parts_order = {}
for (cls, path) in skeleton_path.items():
assert cls not in parts, 'cls conflicts'
d = OmegaConf.load(path)
parts[cls] = d.parts
parts_order[cls] = d.parts_order
else:
parts = kwargs.get('parts')
parts_order = kwargs.get('parts_order')
assert parts is not None
assert parts_order is not None
return Order(
skeleton_path=skeleton_path,
parts=parts,
parts_order=parts_order,
sort_by_xyz=kwargs.get('sort_by_xyz', False),
)
def part_exists(self, cls: str, part: str, names: List[str]) -> bool:
'''
Check if part exists.
'''
if part not in self.parts[cls]:
return False
for name in self.parts[cls][part]:
if name not in names:
return False
return True
def make_names(self, cls: str|None, parts: List[str|None], num_bones: int) -> List[str]:
'''
Get names for specified cls.
'''
names = []
for part in parts:
if part is None: # spring
continue
if cls in self.parts and part in self.parts[cls]:
names.extend(self.parts[cls][part])
assert len(names) <= num_bones, "number of bones in required skeleton is more than existing bones"
for i in range(len(names), num_bones):
names.append(f"bone_{i}")
return names
def arrange_names(self, cls: str|None, names: List[str], parents: List[int], joints: Optional[ndarray]=None) -> Tuple[List[str], Dict[int, str|None]]:
'''
Arrange names according to required parts order.
'''
def sort_by_xyz(joints):
return sorted(joints, key=lambda joint: (joint[1][2], joint[1][0], joint[1][1]))
if self.sort_by_xyz:
assert joints is not None
new_names = []
root = -1
son = defaultdict(list)
not_root = {}
for (i, p) in enumerate(parents):
if p != -1:
son[p].append(i)
not_root[i] = True
for i in range(len(parents)):
if not_root.get(i, False) == False:
root = i
break
Q = [root]
while Q:
u = Q.pop(0)
new_names.append(names[u])
wait = []
for v in son[u]:
wait.append((v, joints[v]))
wait_sorted = sort_by_xyz(wait)
new_wait = [v for v, _ in wait_sorted]
Q = new_wait + Q
return new_names, {}
if cls not in self.parts_order:
return names, {0: None} # add a spring token
vis = defaultdict(bool)
name_to_id = {name: i for (i, name) in enumerate(names)}
new_names = []
parts_bias = {}
for part in self.parts_order[cls]:
if self.part_exists(cls=cls, part=part, names=names):
for name in self.parts[cls][part]:
vis[name] = True
flag = False
for name in self.parts[cls][part]:
pid = parents[name_to_id[name]]
if pid==-1:
continue
if not vis[names[pid]]:
flag = True
break
if flag: # incorrect parts order and should immediately add a spring token
break
parts_bias[len(new_names)] = part
new_names.extend(self.parts[cls][part])
parts_bias[len(new_names)] = None # add a spring token
for name in names:
if name not in new_names:
new_names.append(name)
return new_names, parts_bias

View file

@ -1,189 +0,0 @@
from dataclasses import dataclass
from abc import ABC, abstractmethod
from numpy import ndarray
from scipy.spatial import cKDTree # type: ignore
from typing import Dict, Optional
import numpy as np
import random
from ..rig_package.info.asset import Asset
from ..rig_package.utils import sample_vertex_groups
from .spec import ConfigSpec
@dataclass
class SamplerResult():
sampled_vertices: Optional[ndarray]=None
sampled_normals: Optional[ndarray]=None
sampled_vertex_groups: Optional[Dict[str, ndarray]]=None
# number of sampled skin
skin_samples: Optional[int]=None
class Sampler(ABC):
@abstractmethod
def sample(
self,
asset: Asset,
) -> SamplerResult:
'''
Return sampled vertices, sampled normals and vertex groups.
'''
pass
@classmethod
@abstractmethod
def parse(cls, **kwargs) -> 'Sampler':
pass
@dataclass
class SamplerMix(Sampler, ConfigSpec):
num_samples: int
num_vertex_samples: int
num_skin_samples: Optional[int]=None
replace: bool=True
all_skeleton: Optional[bool]=None
max_distance: float=0.1
rate_distance: float=0.1
@classmethod
def parse(cls, **kwargs) -> 'SamplerMix':
cls.check_keys(kwargs)
return SamplerMix(
num_samples=kwargs.get('num_samples', 0),
num_vertex_samples=kwargs.get('num_vertex_samples', 0),
num_skin_samples=kwargs.get('num_skin_samples', None),
replace=kwargs.get('replace', True),
all_skeleton=kwargs.get('all_skeleton', None),
max_distance=kwargs.get('max_distance', 0.1),
rate_distance=kwargs.get('rate_distance', 0.1),
)
def sample_on_skin(
self,
skin: ndarray,
vertices: ndarray,
faces: ndarray,
):
face_has_skin = np.any(skin[faces] > 0, axis=-1)
if face_has_skin.sum() == 0:
face_has_skin = np.ones_like(face_has_skin)
elif self.max_distance < 1e-5:
return face_has_skin
else:
# sample near points
p = np.unique(faces[face_has_skin].reshape(-1))
tree = cKDTree(vertices[p])
dis, _ = tree.query(vertices, k=1)
dis_skin = np.sqrt(((np.max(vertices[p], axis=0) - np.min(vertices[p], axis=0))**2).sum())
mask_face_near = np.any(dis[faces] < min(self.max_distance, dis_skin * self.rate_distance), axis=-1)
face_has_skin |= mask_face_near
return face_has_skin
def sample(
self,
asset: Asset,
) -> SamplerResult:
if asset.vertices is None:
raise ValueError("do not have vertices")
if asset.faces is None:
raise ValueError("do not have faces")
vertex_groups = []
mapping = {}
tot = 0
for k, v in asset.vertex_groups.items():
if v.ndim == 1:
v = v[:, None]
elif v.ndim != 2:
raise ValueError(f"ndim of key {k} is {v.ndim}")
s = tot
e = tot + v.shape[1]
mapping[k] = slice(s,e)
vertex_groups.append(v)
if len(vertex_groups) > 0:
vertex_groups = np.concatenate(vertex_groups, axis=1)
else:
vertex_groups = None
final_sampled_vertices, final_sampled_normals, sampled_vertex_groups = sample_vertex_groups(
vertices=asset.vertices,
faces=asset.faces,
num_samples=self.num_samples,
vertex_normals=asset.vertex_normals,
face_normals=asset.face_normals,
vertex_groups=vertex_groups,
face_mask=None,
shuffle=True,
same=True,
)
if vertex_groups is not None:
final_sampled_vertices = final_sampled_vertices[:, 0]
if final_sampled_normals is not None:
final_sampled_normals = final_sampled_normals[:, 0]
final_sampled_vertex_groups = {}
if sampled_vertex_groups is not None:
for k, s in mapping.items():
final_sampled_vertex_groups[k] = sampled_vertex_groups[:, s] # (N, k)
if vertex_groups is not None and self.num_skin_samples is not None:
dense_vertices = []
dense_normals = []
dense_skin = []
if 'skin' not in mapping:
raise ValueError("do not have skin")
if self.all_skeleton:
dense_indices = [i for i in range(asset.J)]
else:
dense_indices = [random.randint(0, asset.J-1)]
for indice in dense_indices:
_s = asset.vertex_groups['skin'][:, indice]
face_has_skin = self.sample_on_skin(
skin=_s,
vertices=asset.vertices,
faces=asset.faces,
)
sampled_vertices, sampled_normals, sampled_skin = sample_vertex_groups(
vertices=asset.vertices,
faces=asset.faces,
vertex_normals=asset.vertex_normals,
face_normals=asset.face_normals,
vertex_groups=_s,
num_samples=self.num_skin_samples,
num_vertex_samples=self.num_vertex_samples,
face_mask=face_has_skin,
shuffle=True,
same=True,
)
assert sampled_skin is not None
assert sampled_skin.ndim == 2
dense_vertices.append(sampled_vertices[:, 0])
if sampled_normals is not None:
dense_normals.append(sampled_normals[:, 0])
dense_skin.append(sampled_skin[:, 0])
dense_vertices = np.stack(dense_vertices, axis=0) # (J, m, 3)
if len(dense_normals) > 0:
dense_normals = np.stack(dense_normals, axis=0) # (J, m, 3)
else:
dense_normals = None
dense_skin = np.stack(dense_skin, axis=0) # (J, m, 1)
final_sampled_vertex_groups['skin'] = final_sampled_vertex_groups['skin'][:, dense_indices]
if asset.meta is None:
asset.meta = {}
asset.meta['dense_vertices'] = dense_vertices
asset.meta['dense_normals'] = dense_normals
asset.meta['dense_skin'] = dense_skin
asset.meta['dense_indices'] = dense_indices
return SamplerResult(
sampled_vertices=final_sampled_vertices,
sampled_normals=final_sampled_normals if final_sampled_normals is not None else None,
sampled_vertex_groups=final_sampled_vertex_groups,
skin_samples=self.num_skin_samples,
)
def get_sampler(**kwargs) -> Sampler:
__target__ = kwargs.get('__target__')
assert __target__ is not None
del kwargs['__target__']
if __target__ == 'mix':
sampler = SamplerMix.parse(**kwargs)
else:
raise ValueError(f"sampler method {__target__} not supported")
return sampler

View file

@ -1,16 +0,0 @@
from abc import ABC, abstractmethod
from dataclasses import fields
class ConfigSpec(ABC):
@classmethod
def check_keys(cls, config, expect=None):
if expect is None:
expect = [field.name for field in fields(cls)] # type: ignore
for key in config.keys():
if key not in expect:
raise ValueError(f"expect names {expect} in {cls.__name__}, found {key}")
@classmethod
@abstractmethod
def parse(cls, **kwargs) -> 'ConfigSpec':
raise NotImplementedError()

View file

@ -1,70 +0,0 @@
from dataclasses import dataclass
from typing import List, Optional
from ..rig_package.info.asset import Asset
from .augment import Augment, get_augments
from .order import Order
from .sampler import Sampler, get_sampler
from .spec import ConfigSpec
from .vertex_group import VertexGroup, get_vertex_groups
@dataclass
class Transform(ConfigSpec):
order: Optional[Order]=None
vertex_groups: Optional[List[VertexGroup]]=None
augments: Optional[List[Augment]]=None
sampler: Optional[Sampler]=None
@classmethod
def parse(cls, **kwargs) -> 'Transform':
cls.check_keys(kwargs)
order_config = kwargs.get('order')
vertex_groups_config = kwargs.get('vertex_groups')
augments_config = kwargs.get('augments')
sampler_config = kwargs.get('sampler')
d = {}
if order_config is not None:
d['order'] = Order.parse(**order_config)
if vertex_groups_config is not None:
d['vertex_groups'] = get_vertex_groups(*vertex_groups_config)
if augments_config is not None:
d['augments'] = get_augments(*augments_config)
if sampler_config is not None:
d['sampler'] = get_sampler(**sampler_config)
return Transform(**d)
def apply(self, asset: Asset, **kwargs):
# 1. arrange bones
if self.order is not None:
if asset.joint_names is not None and asset.parents is not None:
new_names, _ = self.order.arrange_names(cls=asset.cls, names=asset.joint_names, parents=asset.parents.tolist())
asset.set_order(new_orders=new_names) # type: ignore
# 2. collapse must perform first
if self.augments is not None:
kwargs = {}
for augment in self.augments:
augment.transform(asset=asset, **kwargs)
# 3. get vertex groups
if self.vertex_groups is not None:
d = {}
for v in self.vertex_groups:
d.update(v.get_vertex_group(asset=asset))
asset.vertex_groups = d
else:
asset.vertex_groups = {}
# 4. sample
if self.sampler is not None:
res = self.sampler.sample(asset=asset)
asset.sampled_vertices = res.sampled_vertices
asset.sampled_normals = res.sampled_normals
asset.sampled_vertex_groups = res.sampled_vertex_groups
asset.skin_samples = res.skin_samples

View file

@ -1,257 +0,0 @@
from abc import ABC, abstractmethod
from collections import defaultdict
from copy import deepcopy
from dataclasses import dataclass
from numpy import ndarray
from scipy.spatial import cKDTree # type: ignore
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import shortest_path, connected_components
from typing import Dict, List, Optional, Literal
import numpy as np
from ..rig_package.info.asset import Asset
@dataclass(frozen=True)
class VertexGroup(ABC):
@classmethod
@abstractmethod
def parse(cls, **kwargs) -> 'VertexGroup':
pass
@abstractmethod
def get_vertex_group(self, asset: Asset) -> Dict[str, ndarray]:
pass
@dataclass(frozen=True)
class VertexGroupSkin(VertexGroup):
"""capture skin"""
normalize: bool=True
@classmethod
def parse(cls, **kwargs) -> 'VertexGroupSkin':
return VertexGroupSkin(normalize=kwargs.get('normalize', True))
def get_vertex_group(self, asset: Asset) -> Dict[str, ndarray]:
if asset.skin is None:
raise ValueError("do not have skin")
if self.normalize:
asset.normalize_skin()
return {'skin': asset.skin.copy()}
@dataclass(frozen=True)
class VertexGroupVoxelSkin(VertexGroup):
"""capture voxel skin"""
grid: int
alpha: float
link_dis: float
grid_query: int
vertex_query: int
grid_weight: float
mode: Literal['square', 'exp']
@classmethod
def parse(cls, **kwargs) -> 'VertexGroupVoxelSkin':
return VertexGroupVoxelSkin(
grid=kwargs.get('grid', 64),
alpha=kwargs.get('alpha', 0.5),
link_dis=kwargs.get('link_dis', 0.00001),
grid_query=kwargs.get('grid_query', 27),
vertex_query=kwargs.get('vertex_query', 27),
grid_weight=kwargs.get('grid_weight', 3.0),
mode=kwargs.get('mode', 'square'),
)
def get_vertex_group(self, asset: Asset) -> Dict[str, ndarray]:
if asset.vertices is None:
raise ValueError("do not have vertices")
if asset.faces is None:
raise ValueError("do not have faces")
if asset.joints is None:
raise ValueError("do not have joints")
# normalize into [-1, 1] first
min_vals = np.min(asset.vertices, axis=0)
max_vals = np.max(asset.vertices, axis=0)
center = (min_vals + max_vals) / 2
scale = np.max(max_vals - min_vals) / 2
normalized_vertices = (asset.vertices - center) / scale
normalized_joints = (asset.joints - center) / scale
grid_coords = asset.voxel().coords
skin = voxel_skin(
grid=self.grid,
grid_coords=grid_coords,
joints=normalized_joints,
vertices=normalized_vertices,
faces=asset.faces,
alpha=self.alpha,
link_dis=self.link_dis,
grid_query=self.grid_query,
vertex_query=self.vertex_query,
grid_weight=self.grid_weight,
mode=self.mode,
)
skin = np.nan_to_num(skin, nan=0., posinf=0., neginf=0.)
return {'voxel_skin': skin,}
def voxel_skin(
grid: int,
grid_coords: ndarray, # (M, 3)
joints: ndarray, # (J, 3)
vertices: ndarray, # (N, 3)
faces: ndarray, # (F, 3)
alpha: float=0.5,
link_dis: float=0.00001,
grid_query: int=27,
vertex_query: int=27,
grid_weight: float=3.0,
voxel_size: Optional[float]=None,
mode: str='square',
parents: Optional[ndarray]=None,
):
# modified from https://dl.acm.org/doi/pdf/10.1145/2485895.2485919
assert mode in ['square', 'exp']
J = joints.shape[0]
M = grid_coords.shape[0]
N = vertices.shape[0]
if voxel_size is None:
_range = 2/grid*1.74
else:
_range = voxel_size*1.74
grid_tree = cKDTree(grid_coords)
vertex_tree = cKDTree(vertices)
if parents is not None:
son = defaultdict(list)
for i, p in enumerate(parents):
if i == -1:
continue
son[p].append(i)
divide_joints = []
joints_map = []
for u in range(len(parents)):
if len(son[u]) != 1:
divide_joints.append(joints[u])
joints_map.append(u)
else:
pu = joints[u]
pv = joints[son[u][0]]
seg = 10
for i in range(seg+1):
p = (pu*i + pv*(seg-i)) / seg
divide_joints.append(p)
joints_map.append(u)
divide_joints = np.stack(divide_joints)
joints_map = np.array(joints_map)
else:
divide_joints = joints
joints_map = np.arange(joints.shape[0])
joint_tree = cKDTree(divide_joints)
# make combined vertices
# 0 ~ N-1: mesh vertices
# N ~ N+M-1: grid vertices
combined_vertices = np.concatenate([vertices, grid_coords], axis=0)
# link adjacent grids
dist, idx = grid_tree.query(grid_coords, grid_query) # 3*3*3
dist = dist[:, 1:]
idx = idx[:, 1:]
mask = (0 < dist) & (dist < _range)
source_grid2grid = np.repeat(np.arange(M), grid_query-1)[mask.ravel()] + N
to_grid2grid = idx[mask] + N
weight_grid2grid = dist[mask] * grid_weight
# link very close vertices
dist, idx = vertex_tree.query(vertices, 4)
dist = dist[:, 1:]
idx = idx[:, 1:]
mask = (0 < dist) & (dist < link_dis)
source_close = np.repeat(np.arange(N), 3)[mask.ravel()]
to_close = idx[mask]
weight_close = dist[mask]
# link grids to mesh vertices
dist, idx = vertex_tree.query(grid_coords, vertex_query)
mask = (0 < dist) & (dist < _range) # sqrt(3)
source_grid2vertex = np.repeat(np.arange(M), vertex_query)[mask.ravel()] + N
to_grid2vertex = idx[mask]
weight_grid2vertex = dist[mask]
# build combined vertices tree
combined_tree = cKDTree(combined_vertices)
# link bones to the neartest vertices
_, joint_indices = combined_tree.query(divide_joints)
# build graph
source_vertex2vertex = np.concatenate([faces[:, 0], faces[:, 1], faces[:, 2]], axis=0)
to_vertex2vertex = np.concatenate([faces[:, 1], faces[:, 2], faces[:, 0]], axis=0)
weight_vertex2vertex = np.sqrt(((vertices[source_vertex2vertex] - vertices[to_vertex2vertex])**2).sum(axis=-1))
graph = csr_matrix(
(np.concatenate([weight_close, weight_vertex2vertex, weight_grid2grid, weight_grid2vertex]),
(
np.concatenate([source_close, source_vertex2vertex, source_grid2grid, source_grid2vertex], axis=0),
np.concatenate([to_close, to_vertex2vertex, to_grid2grid, to_grid2vertex], axis=0)),
),
shape=(N+M, N+M),
)
# get shortest path (J, N+M)
dist_matrix = shortest_path(graph, method='D', directed=False, indices=joint_indices)
# (sum_J, N)
dis_vertex2bone = dist_matrix[:, :N]
unreachable = np.isinf(dis_vertex2bone).all(axis=0)
k = min(J, 3)
dist, idx = joint_tree.query(vertices[unreachable], k)
# make sure at least one value in dis is not inf
unreachable_indices = np.where(unreachable)[0]
row_indices = idx
col_indices = np.repeat(unreachable_indices, k).reshape(-1, k)
dis_vertex2bone[row_indices, col_indices] = dist
finite_vals = dis_vertex2bone[np.isfinite(dis_vertex2bone)]
max_dis = np.max(finite_vals)
dis_vertex2bone = np.nan_to_num(dis_vertex2bone, nan=max_dis, posinf=max_dis, neginf=max_dis)
dis_vertex2bone = np.maximum(dis_vertex2bone, 1e-6)
# turn dis2bone to dis2vertex
dis_vertex2joint = np.full((joints.shape[0], vertices.shape[0]), max_dis)
for i in range(len(dis_vertex2bone)):
dis_vertex2joint[joints_map[i]] = np.minimum(dis_vertex2bone[i], dis_vertex2joint[joints_map[i]])
# (J, N)
if mode == 'exp':
skin = np.exp(-dis_vertex2joint / max_dis * 20.0)
elif mode == 'square':
skin = (1./((1-alpha)*dis_vertex2joint + alpha*dis_vertex2joint**2))**2
else:
assert False, f'invalid mode: {mode}'
skin = skin / skin.sum(axis=0)
# (N, J)
skin = skin.transpose()
return skin
def get_vertex_groups(*args) -> List[VertexGroup]:
vertex_groups = []
MAP = {
'skin': VertexGroupSkin,
'voxel_skin': VertexGroupVoxelSkin,
}
MAP: Dict[str, type[VertexGroup]]
for (i, c) in enumerate(args):
__target__ = c.get('__target__')
assert __target__ is not None, f"do not find `__target__` in config of vertex_groups of position {i}"
assert __target__ in MAP, f"expect: [{','.join(MAP.keys())}], found: {__target__}"
c = deepcopy(c)
del c['__target__']
vertex_groups.append(MAP[__target__].parse(**c))
return vertex_groups

View file

@ -1,4 +1,4 @@
{
"version": "2.1.2",
"message": "Fixed Desktop App on Linux - ComfyUI: Added Enums - Wireframe in Mesh Previewer"
"version": "2.0.0",
"message": "MCP Server + Improved Graph Page"
}