Simplified Image Node Actions in Graph Page + Fixed MCP

This commit is contained in:
Bruno Fargnoli 2026-07-19 17:12:59 +02:00
parent 27645c4e0f
commit d4ef8f8b1b
8 changed files with 317 additions and 42 deletions

View file

@ -76,6 +76,12 @@ Connect with transport "Streamable HTTP" to `http://localhost:3001/mcp`.
In graph projects, pass `nodeId` to `run_workflow`, `generate_image`, `edit_image`, or `generate_mesh` to display the results on that node — the first result becomes the node's asset, and additional results become new nodes stacked below it (wired to the same inputs). Without `nodeId` the generated assets are saved to the project but no node displays them.
`run_workflow` saves its output **under the source it was derived from, automatically** — you normally never set `parentAssetId`. It picks the workflow's image/mesh input matching the output type (whether that input was wired from the target node or passed in `inputs`): an image output becomes an edit of that source image, a mesh output a version of that source mesh (matching the graph UI). So a re-texture (image + mesh in → mesh out) becomes a version of the input mesh, and a background-removal (image in → image out) an edit of the input image, with nothing extra to pass. Set `parentAssetId` only to override the inferred parent; a parent whose type doesn't match the output type is ignored and a new root asset is created. (`edit_image` likewise saves an edit of its `imageSource`, and `run_mesh_tool` a version of its `assetId`.)
The target node's connected input assets also **auto-fill the workflow's image/mesh parameters**, matched by type (each connected asset used once). A node wired to an image and a mesh feeds a workflow that needs a Source Image + a mesh input without any manual mapping — so for a wired node you should **not** pass `inputs` for file (image/mesh/video) parameters and never need to guess their parameter ids. Set an `inputs` entry for a file parameter only to override a wired input or when nothing is connected; use `inputs` otherwise just for string/number/boolean parameters. Explicit `inputs`/`fileInputs` always take precedence over an auto-filled value.
**Connect the input nodes _before_ you run.** `run_workflow`, `edit_image`, and `generate_mesh` read a node's connected input at the moment they execute — the input feeds the workflow/API and determines whether the result is saved as an edit/version. So the correct order is always: (1) `create_node` for the target, (2) `connect_nodes` to wire its input asset(s), then (3) run the workflow or API on that node. Running first and connecting afterwards is wrong: the run sees no input, so it can't use the source image/mesh and saves a stray new root asset instead of an edit/version — and the late connection does **not** re-run or re-parent it. If you ran in the wrong order, delete the stray result, connect the inputs, and run again.
### Parameter-heavy mesh tools
Auto UV and Auto Retopo have many tuning parameters (14 and 20 respectively) that materially change the output. Use the dedicated `auto_uv_mesh` and `auto_retopo_mesh` tools rather than `run_mesh_tool` for these: each declares every parameter in its schema with type, range, default, and description (mirroring the Python service's models), so a client can set exactly what it needs and see the valid bounds. Any subset of options may be set; unset keys fall back to the documented default. For Auto Retopo, the `shell_*` options apply only when `watertight` is `true`. `run_mesh_tool` still accepts `auto_uv`/`auto_retopo` (options ride along as a free-form object) for backward compatibility.

View file

@ -34,7 +34,10 @@ const SERVER_INSTRUCTIONS = `3D Gen Studio automation server.
Typical flows:
- New pipeline: create_project (preset "graph") -> create_node / connect_nodes to lay out the pipeline -> run_workflow or generate_image / generate_mesh to produce assets.
- IMPORTANT (graph projects): always pass nodeId to run_workflow / generate_image / edit_image / generate_mesh so the results are DISPLAYED on that node. Without nodeId the assets are saved but no node shows them. The first result becomes the node's image/mesh; extra results become new nodes stacked below it.
- IMPORTANT ordering: connect_nodes to wire a node's input asset(s) BEFORE you run_workflow / edit_image / generate_mesh on it. The run reads the node's connected input at execution time — it feeds the workflow/API and decides whether the result is saved as an edit of the connected image / a version of the connected mesh. Running first and connecting afterwards is wrong: the run sees no input, so it uses none and saves a stray new root asset, and the late connection does not re-run or re-parent it. If you got the order wrong, delete the stray result, connect the inputs, then run again.
- ComfyUI: list_workflows for saved workflows and their parameters; import_workflow to add new ones (inspect_workflow first to discover inputs/outputs). run_workflow blocks with progress until the assets are ready. ComfyUI itself must be running (URL in get_settings).
- ComfyUI image/mesh (file) parameters are filled AUTOMATICALLY from the target node's wired inputs (matched by type) — so for a node whose inputs are connected, do NOT pass inputs for file parameters (no need to guess their ids); just connect_nodes then run_workflow with nodeId. Only set a file-parameter input to override a wired input or when nothing is connected. Set inputs only for non-file parameters (string/number/boolean) you want to change.
- Parent linkage is AUTOMATIC — do NOT manage parentAssetId yourself. run_workflow saves its output under the source it was derived from (the image/mesh input matching the output type, wired or passed in inputs): an image output becomes an edit of that image, a mesh output a version of that mesh. edit_image already saves an edit of its imageSource, and run_mesh_tool saves a version of its assetId. So a re-texture (image+mesh in, mesh out) versions the input mesh, and a background-removal (image in, image out) edits the input image, with no parentAssetId needed. Only pass parentAssetId to override the inferred parent.
- Mesh processing: run_mesh_tool (auto_uv / auto_retopo / repair / auto_rig / optimize / convert_fbx) works on mesh assets; results save as asset versions.
- Seeing results: use view_asset to LOOK at a generated image (returns the actual image; for meshes it returns the thumbnail when available). Use download_asset to save any asset file to a local folder. Assets also carry direct download URLs in every response.

View file

@ -7,6 +7,70 @@
const VERTICAL_STEP = 580; // collapsed node card height (~480px) + gap
const NODE_TYPE_BY_ASSET_TYPE = { image: 'Image', mesh: 'Mesh' };
// Decide where a generated result should land. Graph nodes are filled via
// `nodeId` (→ attachResultsToNode → the node's own asset); kanban cards via
// `cardId`. Clients sometimes pass a graph node id as `cardId`, which the kanban
// path can't attach to a node (and worse, silently creates an orphaned card), so
// promote such an id to a node target here. Returns the resolved target; a node
// target never also carries a kanban cardId.
//
// Safe because graph nodes and kanban cards are unique rows in one `Cards` table:
// an id that matches a graph node IS that node, not a card.
export async function resolveNodeTarget(api, projectId, { nodeId, cardId } = {}) {
if (nodeId !== undefined && nodeId !== null && nodeId !== '') {
return { nodeId: Number(nodeId), cardId: undefined };
}
if (cardId !== undefined && cardId !== null && cardId !== '' && projectId) {
const numeric = Number(cardId);
if (Number.isInteger(numeric)) {
const nodes = await api.apiJson('GET', '/graph/nodes', { query: { projectId } }).catch(() => []);
const isGraphNode = (Array.isArray(nodes) ? nodes : []).some(node => Number(node?.id) === numeric);
if (isGraphNode) {
return { nodeId: numeric, cardId: undefined };
}
}
}
return { nodeId: undefined, cardId };
}
// List the assets feeding a node's inputs: for each incoming edge whose source
// node holds an asset, the asset id + type (ordered by input connector so the
// result is deterministic). Lets a workflow run fill its image/mesh parameters
// from what the node is wired to — mirroring the GraphPage, which binds each
// file parameter to the connected input of the matching type — and pick the
// parent asset (image edit / mesh version) by matching the output type.
export async function resolveNodeInputAssets(api, projectId, nodeId) {
if (!nodeId || projectId === undefined || projectId === null) {
return [];
}
const [nodes, connections] = await Promise.all([
api.apiJson('GET', '/graph/nodes', { query: { projectId } }).catch(() => []),
api.apiJson('GET', '/graph/connections', { query: { projectId } }).catch(() => [])
]);
const nodeList = Array.isArray(nodes) ? nodes : [];
const incomingEdges = (Array.isArray(connections) ? connections : [])
.filter(connection => Number(connection?.targetNodeId) === Number(nodeId))
.sort((a, b) => String(a?.inputId || '').localeCompare(String(b?.inputId || '')));
const inputs = [];
for (const edge of incomingEdges) {
const sourceNode = nodeList.find(node => Number(node?.id) === Number(edge.sourceNodeId));
const assetId = sourceNode?.assetId ?? sourceNode?.asset?.id ?? null;
if (assetId) {
inputs.push({
assetId: Number(assetId),
type: String(sourceNode?.asset?.type || '').toLowerCase() || null,
connectorId: edge.inputId || null
});
}
}
return inputs;
}
export async function attachResultsToNode(api, { projectId, nodeId, assets, metadata = {} }) {
const usable = (Array.isArray(assets) ? assets : [assets]).filter(asset =>
asset?.id && NODE_TYPE_BY_ASSET_TYPE[String(asset.type || '').toLowerCase()]

View file

@ -1,6 +1,6 @@
import { z } from 'zod';
import { toolHandler, createProgressReporter } from '../client.js';
import { attachResultsToNode } from '../nodeResults.js';
import { attachResultsToNode, resolveNodeTarget } from '../nodeResults.js';
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
@ -125,12 +125,16 @@ async function runMeshGeneration(api, notifyMutation, args, extra) {
} = args;
const reportProgress = createProgressReporter(extra);
// Route a graph-node target to the node; never send a node id as a kanban
// cardId. targetNodeId gets the final mesh attached (via pollMeshResult).
const { nodeId: targetNodeId, cardId: kanbanCardId } = await resolveNodeTarget(api, projectId, { nodeId, cardId });
const submit = await api.apiJson('POST', '/meshes/generate', {
body: {
projectId, selectedApi, name,
...(prompt ? { prompt } : {}),
...(imageSource !== undefined ? { imageSource } : {}),
...(cardId !== undefined ? { cardId } : {}),
...(kanbanCardId !== undefined && kanbanCardId !== null ? { cardId: kanbanCardId } : {}),
...(parentAssetId !== undefined ? { parentAssetId } : {}),
...options
}
@ -141,7 +145,7 @@ async function runMeshGeneration(api, notifyMutation, args, extra) {
projectId,
name,
prompt: prompt || '',
cardId: submit?.cardId ?? cardId ?? null,
cardId: submit?.cardId ?? kanbanCardId ?? null,
selectedApi,
parentAssetId: parentAssetId ?? null
});
@ -155,7 +159,7 @@ async function runMeshGeneration(api, notifyMutation, args, extra) {
pollRequest,
providerLabel: submit.provider,
projectId,
nodeId,
nodeId: targetNodeId,
selectedApi,
timeoutSeconds,
pollIntervalSeconds
@ -164,13 +168,16 @@ async function runMeshGeneration(api, notifyMutation, args, extra) {
if (outcome.status === 'running') {
// Timed out with the job still on the provider. The mesh is NOT saved until a
// result poll sees completion, so hand back the job ids for get_mesh_result.
// Surface the resolved node target so a follow-up get_mesh_result can pass
// nodeId and still land the mesh on the intended node.
return {
status: 'running',
note: `Still processing after ${timeoutSeconds}s. The provider keeps working, but the mesh is only saved once a result poll sees it finish — call get_mesh_result with the ids below to retrieve it when ready. Do NOT re-run generation (that starts a new job).`,
note: `Still processing after ${timeoutSeconds}s. The provider keeps working, but the mesh is only saved once a result poll sees it finish — call get_mesh_result with the ids below to retrieve it when ready${targetNodeId ? ' (pass nodeId to attach it to the graph node)' : ''}. Do NOT re-run generation (that starts a new job).`,
provider: submit.provider,
selectedApi,
projectId,
name,
...(targetNodeId ? { nodeId: targetNodeId } : {}),
...(submit.jobId ? { jobId: submit.jobId } : {}),
...(submit.taskId ? { taskId: submit.taskId } : {}),
...(submit.region ? { region: submit.region } : {}),
@ -184,7 +191,7 @@ async function runMeshGeneration(api, notifyMutation, args, extra) {
export function registerActionTools(server, { api, notifyMutation }) {
server.registerTool('generate_image', {
title: 'Generate image',
description: 'Generate an image with an external AI provider and save it as a project asset. selectedApi identifies the provider/model configured in Settings (e.g. Google/OpenAI image APIs or a custom_* API) — check get_settings for what is configured. In graph projects pass nodeId so the result is displayed on that node.',
description: 'Generate an image with an external AI provider and save it as a project asset. selectedApi identifies the provider/model configured in Settings (e.g. Google/OpenAI image APIs or a custom_* API) — check get_settings for what is configured. In graph projects pass nodeId so the result is displayed on that node (cardId is for kanban cards; a graph node id passed as cardId is auto-routed to that node).',
inputSchema: {
projectId: z.number().int(),
selectedApi: z.string().min(1).describe('Provider/model id from Settings (e.g. "google_gemini", "openai_gpt_image", or a custom_* id)'),
@ -194,12 +201,15 @@ export function registerActionTools(server, { api, notifyMutation }) {
cardId: z.union([z.number().int(), z.string()]).optional().describe('Existing kanban card to attach the result to')
}
}, toolHandler(async ({ projectId, nodeId, ...body }) => {
const result = await api.apiJson('POST', '/images/generate', { body: { projectId, ...body } });
// A graph node id may arrive as nodeId or (mistakenly) as cardId — route it
// to the node and keep only a real kanban cardId in the request body.
const { nodeId: targetNodeId, cardId: kanbanCardId } = await resolveNodeTarget(api, projectId, { nodeId, cardId: body.cardId });
const result = await api.apiJson('POST', '/images/generate', { body: { projectId, ...body, cardId: kanbanCardId } });
let nodeAttachment = null;
if (nodeId) {
if (targetNodeId) {
nodeAttachment = await attachResultsToNode(api, {
projectId,
nodeId,
nodeId: targetNodeId,
assets: [{ ...result, type: result?.type || 'image' }],
metadata: { lastAction: 'image-api' }
});
@ -210,7 +220,7 @@ export function registerActionTools(server, { api, notifyMutation }) {
server.registerTool('edit_image', {
title: 'Edit image (AI)',
description: 'Edit an existing project image with an external AI provider (prompt-based edit). The result is saved as an edit of the source asset. In graph projects pass nodeId so the result is displayed on that node. For ComfyUI-based edits use run_workflow instead.',
description: 'Edit an existing project image with an external AI provider (prompt-based edit). The result is saved as an edit of the source asset. In graph projects pass nodeId so the result is displayed on that node (cardId is for kanban cards; a graph node id passed as cardId is auto-routed to that node). For ComfyUI-based edits use run_workflow instead.',
inputSchema: {
projectId: z.number().int(),
selectedApi: z.string().min(1),
@ -221,13 +231,14 @@ export function registerActionTools(server, { api, notifyMutation }) {
cardId: z.union([z.number().int(), z.string()]).optional()
}
}, toolHandler(async ({ projectId, nodeId, ...body }) => {
const result = await api.apiJson('POST', '/image-edits/api', { body: { projectId, ...body } });
const { nodeId: targetNodeId, cardId: kanbanCardId } = await resolveNodeTarget(api, projectId, { nodeId, cardId: body.cardId });
const result = await api.apiJson('POST', '/image-edits/api', { body: { projectId, ...body, cardId: kanbanCardId } });
let nodeAttachment = null;
const savedEdits = Array.isArray(result?.savedEdits) ? result.savedEdits : [];
if (nodeId && savedEdits.length > 0) {
if (targetNodeId && savedEdits.length > 0) {
nodeAttachment = await attachResultsToNode(api, {
projectId,
nodeId,
nodeId: targetNodeId,
assets: savedEdits.map(edit => ({ id: edit.id, name: edit.name || body.name, type: 'image' })),
metadata: { lastAction: 'image-edit-api' }
});
@ -238,14 +249,14 @@ export function registerActionTools(server, { api, notifyMutation }) {
server.registerTool('generate_mesh', {
title: 'Generate 3D mesh',
description: 'Generate a 3D mesh from an image and/or prompt using Tencent Hunyuan, Tripo AI, or Hitem3D (selectedApi from Settings). Submits the job and polls the provider until the mesh is ready (streams MCP progress), then returns the saved mesh assets. Takes minutes — on timeout returns the job info so it can be re-polled by calling this tool\'s sibling get-result flow or checking list_assets later.',
description: 'Generate a 3D mesh from an image and/or prompt using Tencent Hunyuan, Tripo AI, or Hitem3D (selectedApi from Settings). Submits the job and polls the provider until the mesh is ready (streams MCP progress), then returns the saved mesh assets. In graph projects pass nodeId so the mesh is displayed on that node (cardId is for kanban cards; a graph node id passed as cardId is auto-routed to that node). Takes minutes — on timeout returns the job info so it can be re-polled by calling this tool\'s sibling get-result flow or checking list_assets later.',
inputSchema: {
projectId: z.number().int(),
selectedApi: z.string().min(1).describe('Mesh provider id from Settings (Tencent / Tripo / Hitem3D / custom_*)'),
name: z.string().min(1),
prompt: z.string().optional().describe('Text prompt (Tencent/Tripo support text-to-3D)'),
imageSource: z.union([z.number().int(), z.string()]).optional().describe('Source image: asset id or stored filePath (required for Hitem3D)'),
nodeId: z.number().int().optional().describe('Graph node to attach the generated mesh to (graph projects)'),
nodeId: z.number().int().optional().describe('Graph node to attach the generated mesh to (graph projects). The correct way to fill a node; a graph node id passed as cardId is auto-routed here.'),
cardId: z.union([z.number().int(), z.string()]).optional(),
parentAssetId: z.number().int().optional(),
options: z.record(z.string(), z.any()).default({}).describe('Provider options, e.g. Tencent: region, modelVersion, enablePBR, faceCount, generationType, polygonType; Tripo: modelVersion, texture, pbr, quad, faceLimit, …. Prefer the dedicated generate_mesh_tencent / generate_mesh_tripo / generate_mesh_hitem tools, which document and validate every option.'),
@ -263,7 +274,7 @@ export function registerActionTools(server, { api, notifyMutation }) {
prompt: z.string().optional().describe('Text prompt (text-to-3D). Provide this OR imageSource.'),
imageSource: z.union([z.number().int(), z.string()]).optional().describe('Source image: asset id or stored filePath (image-to-3D). Provide this OR prompt.'),
options: z.object(TENCENT_MESH_OPTIONS).describe('Tencent Hunyuan3D parameters (region is required).'),
nodeId: z.number().int().optional().describe('Graph node to attach the generated mesh to (graph projects)'),
nodeId: z.number().int().optional().describe('Graph node to attach the generated mesh to (graph projects). The correct way to fill a node; a graph node id passed as cardId is auto-routed here.'),
cardId: z.union([z.number().int(), z.string()]).optional(),
parentAssetId: z.number().int().optional(),
timeoutSeconds: z.number().int().min(30).max(3600).default(1200),
@ -280,7 +291,7 @@ export function registerActionTools(server, { api, notifyMutation }) {
prompt: z.string().optional().describe('Text prompt (text-to-3D). Provide this OR imageSource.'),
imageSource: z.union([z.number().int(), z.string()]).optional().describe('Source image: asset id or stored filePath (image-to-3D). Provide this OR prompt.'),
options: z.object(TRIPO_MESH_OPTIONS).default({}).describe('Tripo AI parameters (all optional; unset keys use their default).'),
nodeId: z.number().int().optional().describe('Graph node to attach the generated mesh to (graph projects)'),
nodeId: z.number().int().optional().describe('Graph node to attach the generated mesh to (graph projects). The correct way to fill a node; a graph node id passed as cardId is auto-routed here.'),
cardId: z.union([z.number().int(), z.string()]).optional(),
parentAssetId: z.number().int().optional(),
timeoutSeconds: z.number().int().min(30).max(3600).default(1200),
@ -296,7 +307,7 @@ export function registerActionTools(server, { api, notifyMutation }) {
name: z.string().min(1),
imageSource: z.union([z.number().int(), z.string()]).describe('Source image: asset id or stored filePath — REQUIRED.'),
options: z.object(HITEM_MESH_OPTIONS).default({}).describe('Hitem3D parameters (all optional; unset keys use their default).'),
nodeId: z.number().int().optional().describe('Graph node to attach the generated mesh to (graph projects)'),
nodeId: z.number().int().optional().describe('Graph node to attach the generated mesh to (graph projects). The correct way to fill a node; a graph node id passed as cardId is auto-routed here.'),
cardId: z.union([z.number().int(), z.string()]).optional(),
parentAssetId: z.number().int().optional(),
timeoutSeconds: z.number().int().min(30).max(3600).default(1200),

View file

@ -3,7 +3,27 @@ import { randomUUID } from 'node:crypto';
import fs from 'node:fs/promises';
import path from 'node:path';
import { toolHandler, createProgressReporter } from '../client.js';
import { attachResultsToNode } from '../nodeResults.js';
import { attachResultsToNode, resolveNodeTarget, resolveNodeInputAssets } from '../nodeResults.js';
const FILE_PARAM_TYPES = ['image', 'mesh', 'video'];
// Pull a project asset id out of a file-parameter value (number, "asset:<id>",
// numeric string, or {assetId|source|filePath}). Returns null for uploaded local
// files and stored file paths — there's no project asset to parent to.
function extractAssetIdFromInput(value) {
if (value === null || value === undefined) return null;
if (typeof value === 'number') return Number.isInteger(value) && value > 0 ? value : null;
if (typeof value === 'string') {
const raw = value.startsWith('asset:') ? value.slice(6) : value;
const numeric = Number(raw);
return Number.isInteger(numeric) && numeric > 0 ? numeric : null;
}
if (typeof value === 'object') {
if (value.__fileField) return null;
return extractAssetIdFromInput(value.assetId ?? value.source ?? value.filePath ?? null);
}
return null;
}
// Strip the raw graph JSON from workflow records so list responses stay small.
function summarizeWorkflow(workflow) {
@ -104,16 +124,16 @@ export function registerWorkflowTools(server, { api, notifyMutation }) {
server.registerTool('run_workflow', {
title: 'Run ComfyUI workflow',
description: 'Execute a saved ComfyUI workflow and wait for the generated assets (streams MCP progress notifications). inputs maps parameter id -> value; for image/mesh parameters pass a project asset id (number) as the value, or use fileInputs to upload a local file. IMPORTANT for graph projects: pass nodeId (a graph node from get_graph/create_node) so the results are displayed on that node — the first result becomes the node\'s asset, additional results become new nodes stacked below it. Requires ComfyUI to be running (configured in Settings). On timeout returns {status:"running", promptId} — poll with get_run_status.',
description: 'Execute a saved ComfyUI workflow and wait for the generated assets (streams MCP progress notifications). inputs maps parameter id -> value; for image/mesh parameters pass a project asset id (number) as the value, or use fileInputs to upload a local file. IMPORTANT for graph projects: pass nodeId (a graph node from get_graph/create_node) so the results are displayed on that node — the first result becomes the node\'s asset, additional results become new nodes stacked below it. nodeId is the ONLY way to fill a graph node; cardId is for kanban cards. (If you pass a graph node id as cardId it is auto-attached to that node, not turned into a card.) Wiring: the target node\'s connected input assets automatically fill the workflow\'s image/mesh parameters (matched by type), so you normally do NOT set inputs for file parameters — just connect_nodes to wire the source image/mesh, then run with nodeId. Only pass inputs for file parameters to override a wired input or when the node has no connection. Requires ComfyUI to be running (configured in Settings). On timeout returns {status:"running", promptId} — poll with get_run_status.',
inputSchema: {
workflowId: z.number().int().describe('Saved workflow id (from list_workflows)'),
projectId: z.number().int().optional().describe('Project to attach results to (required unless persistGeneratedAssets=false)'),
inputs: z.record(z.string(), z.any()).default({}).describe('Parameter id -> value. Image/mesh parameters accept a project assetId (number) or stored filePath (string).'),
fileInputs: z.record(z.string(), z.string()).optional().describe('Parameter id -> absolute local file path to upload for image/mesh/video parameters'),
nodeId: z.number().int().optional().describe('Graph node to attach the results to (graph projects) — without it the generated assets are saved but no node displays them'),
cardId: z.union([z.number().int(), z.string()]).optional().describe('Existing kanban card to attach the run to (its status updates live in the UI)'),
nodeId: z.number().int().optional().describe('Graph node to attach the results to (graph projects) — the correct way to fill a node; without it the generated assets are saved but no node displays them'),
cardId: z.union([z.number().int(), z.string()]).optional().describe('Existing KANBAN card to attach the run to (kanban projects). For graph nodes use nodeId — a graph node id passed here is auto-routed to that node'),
name: z.string().optional().describe('Name for the generated asset(s)'),
parentAssetId: z.number().int().optional().describe('Save results as versions of this asset'),
parentAssetId: z.number().int().optional().describe('Save results under this asset: a mesh output becomes a version of it, an image output an edit of it (the parent must match the output type, else a new root asset is created). USUALLY LEAVE UNSET — it is inferred automatically from the source the output was derived from: the workflow file (image/mesh) input matching the output type, whether that input came from the target node\'s wiring or was passed in `inputs`. Set this only to override that inference (e.g. attach to a different asset).'),
persistProcessingCard: z.boolean().optional(),
persistGeneratedAssets: z.boolean().optional(),
timeoutSeconds: z.number().int().min(5).max(3600).default(600)
@ -126,6 +146,66 @@ export function registerWorkflowTools(server, { api, notifyMutation }) {
const reportProgress = createProgressReporter(extra);
const promptId = randomUUID();
// Route a graph-node target to the node (via nodeId), even if the caller
// passed the node id as cardId. targetNodeId gets the result attached;
// kanbanCardId is only forwarded to the server when it's a real kanban card.
const { nodeId: targetNodeId, cardId: kanbanCardId } = await resolveNodeTarget(api, projectId, { nodeId, cardId });
// Mirror the GraphPage: use what the target node is wired to. Its connected
// input assets fill the workflow's image/mesh parameters (by matching type) so
// the caller doesn't have to hand-map parameter ids, and — when the caller
// didn't pin one — set the parent so the output is saved as an edit of a
// connected image / a version of a connected mesh (parent matches output type).
const nodeInputAssets = (targetNodeId && projectId)
? await resolveNodeInputAssets(api, projectId, targetNodeId)
: [];
// Fetch the workflow definition to know its file parameters and output type.
const workflowDef = (await api.apiJson('GET', '/library/comfy-workflows').catch(() => []))
.find?.(item => Number(item?.id) === Number(workflowId)) || null;
const fileParams = (workflowDef?.parameters || [])
.map(parameter => ({ id: parameter.id, type: String(parameter.valueType || '').toLowerCase() }))
.filter(parameter => FILE_PARAM_TYPES.includes(parameter.type));
// Auto-fill each unset image/mesh/video parameter from a connected input of
// the matching type (each connected asset used at most once). Explicit `inputs`
// and `fileInputs` always win over an auto-filled value.
const autoInputs = {};
if (nodeInputAssets.length > 0 && fileParams.length > 0) {
const available = nodeInputAssets.map(asset => ({ ...asset, used: false }));
for (const parameter of fileParams) {
const explicitlySet = (inputs[parameter.id] !== undefined && inputs[parameter.id] !== null)
|| (fileInputs && fileInputs[parameter.id]);
if (explicitlySet) continue;
const match = available.find(asset => !asset.used && asset.type === parameter.type);
if (match) {
autoInputs[parameter.id] = `asset:${match.assetId}`;
match.used = true;
}
}
}
// Save the output under the source asset it was derived from, unless the caller
// pinned a parent explicitly. Pick the file-parameter input (auto-filled from
// wiring OR passed in `inputs`) whose type matches the produced output: an image
// output becomes an edit of its source image, a mesh output a version of its
// source mesh. Inferring from the reused input — not just node wiring — means a
// caller that reuses a source assetId as an input doesn't have to remember
// parentAssetId. Pass parentAssetId explicitly to override the inferred parent.
let effectiveParentAssetId = parentAssetId;
if (effectiveParentAssetId === undefined || effectiveParentAssetId === null) {
const outputTypes = (workflowDef?.outputs || []).map(output => String(output?.valueType || 'image').toLowerCase());
const primaryOutputType = outputTypes.includes('mesh')
? 'mesh'
: (outputTypes.includes('image') ? 'image' : (outputTypes[0] || null));
const matchingParam = primaryOutputType
? fileParams.find(parameter => parameter.type === primaryOutputType)
: null;
if (matchingParam) {
effectiveParentAssetId = extractAssetIdFromInput(inputs[matchingParam.id] ?? autoInputs[matchingParam.id]);
}
}
// Subscribe to the single-job progress stream BEFORE submitting so the
// terminal event can't be missed (the endpoint also replays the latest
// snapshot on connect).
@ -153,13 +233,13 @@ export function registerWorkflowTools(server, { api, notifyMutation }) {
if (projectId !== undefined && projectId !== null) form.append('projectId', String(projectId));
form.append('workflowId', String(workflowId));
form.append('promptId', promptId);
if (cardId !== undefined && cardId !== null) form.append('cardId', String(cardId));
if (kanbanCardId !== undefined && kanbanCardId !== null) form.append('cardId', String(kanbanCardId));
if (name) form.append('name', name);
if (parentAssetId !== undefined && parentAssetId !== null) form.append('parentAssetId', String(parentAssetId));
if (effectiveParentAssetId !== undefined && effectiveParentAssetId !== null) form.append('parentAssetId', String(effectiveParentAssetId));
if (persistProcessingCard === false) form.append('persistProcessingCard', 'false');
if (persistGeneratedAssets === false) form.append('persistGeneratedAssets', 'false');
const inputValues = { ...inputs };
const inputValues = { ...autoInputs, ...inputs };
for (const [key, localPath] of Object.entries(fileInputs || {})) {
const fieldName = `comfyFile:${key}`;
const buffer = await fs.readFile(localPath);
@ -194,10 +274,10 @@ export function registerWorkflowTools(server, { api, notifyMutation }) {
// the GraphPage does after a run — without this the assets exist but no
// node shows them).
let nodeAttachment = null;
if (nodeId && projectId) {
if (targetNodeId && projectId) {
nodeAttachment = await attachResultsToNode(api, {
projectId,
nodeId,
nodeId: targetNodeId,
assets,
metadata: { lastAction: 'comfy-workflow', promptId }
});

View file

@ -3719,6 +3719,13 @@ app.post('/api/comfyui/workflows/run', workflowExecutionUpload.any(), async (req
const baseTimestamp = Date.now();
const generatedAssets = [];
// When results are saved under a parent asset, they become an image edit or a
// mesh version of it — but only when the parent's type matches the produced
// output type (a mismatched parent falls back to a new root asset).
const parentAsset = normalizedParentAssetId ? await getAssetRecordById(normalizedParentAssetId) : null;
const parentAssetType = parentAsset ? String(parentAsset.assetTypeName || '').toLowerCase() : null;
const workflowEditId = randomUUID();
for (const [index, workflowText] of workflowTexts.entries()) {
generatedAssets.push({
type: 'text',
@ -3794,11 +3801,26 @@ app.post('/api/comfyui/workflows/run', workflowExecutionUpload.any(), async (req
? await renderMeshThumbnailViaService(downloadedFile.buffer, generatedAssetPayload.name)
: null;
// When a mesh output was edited from a connected mesh, store it as a
// version (child) of that mesh instead of creating a new root asset.
const persistedAsset = (normalizedParentAssetId && inferredAssetType === 'mesh')
// When the output was produced from a connected input asset, store it as a
// child of that asset instead of a new root: a mesh output becomes a version
// of the connected mesh, an image output becomes an edit of the connected
// image. A parent whose type doesn't match the output falls back to a root.
const persistedAsset = (normalizedParentAssetId && parentAssetType === 'mesh' && inferredAssetType === 'mesh')
? await createAssetVersion({ assetId: normalizedParentAssetId, ...generatedAssetPayload, thumbnailPath: meshThumbnailFilename, inheritThumbnail: false })
: await createProjectAsset({ ...generatedAssetPayload, thumbnailPath: meshThumbnailFilename });
: (normalizedParentAssetId && parentAssetType === 'image' && inferredAssetType === 'image')
? {
...(await createAssetEditRecord({
assetId: normalizedParentAssetId,
editId: workflowEditId,
name: generatedAssetPayload.name,
filePath: storedFilePath,
width: dimensions.width,
height: dimensions.height,
createdAt: generatedAssetPayload.createdAt
})),
type: 'image'
}
: await createProjectAsset({ ...generatedAssetPayload, thumbnailPath: meshThumbnailFilename });
generatedAssets.push({
...persistedAsset,
url: `${getRequestBaseUrl(req)}/assets/${encodeURI(toAssetUrlPath(storedFilePath))}`,

View file

@ -476,16 +476,10 @@ const GraphAssetNode = memo(function GraphAssetNode({ data }) {
From Assets
</button>
<button className="image-card__edit-action-option nodrag" onClick={() => data.onImageModeSelect?.(data.id, 'comfy')}>
Generate · ComfyUI Workflow
ComfyUI Workflow
</button>
<button className="image-card__edit-action-option nodrag" onClick={() => data.onImageModeSelect?.(data.id, 'api')}>
Generate · Remote API
</button>
<button className="image-card__edit-action-option nodrag" onClick={() => data.onImageEditModeSelect?.(data.id, 'edit-api')}>
Edit · API
</button>
<button className="image-card__edit-action-option nodrag" onClick={() => data.onImageEditModeSelect?.(data.id, 'edit-comfy')}>
Edit · ComfyUI Workflow
API
</button>
</>
)}

View file

@ -1449,6 +1449,54 @@ export default function GraphPage({ project }) {
return
}
// With an image attached to the node, an API run edits that image and
// saves the result as an edit of it; otherwise it's a plain generation.
const connectedInputAsset = getConnectedInputAssetFrom(nodes, edges, targetNodeId)
const editSourceReference = getAssetSourceReference(connectedInputAsset)
if (editSourceReference) {
await setProcessingState('processing', null, { processingSource: 'API', inputSource: editSourceReference })
try {
const response = await runImageEditApi(project.id, {
imageSource: editSourceReference,
name: targetDraft.name.trim(),
selectedApi: targetDraft.selectedApi,
prompt: targetDraft.prompt.trim()
})
const savedEdits = response?.savedEdits || []
if (savedEdits.length === 0) {
throw new Error('Image edit did not return any saved image')
}
await applyNodeResult({ id: savedEdits[0].id, name: savedEdits[0].name || targetDraft.name.trim() }, {
lastAction: 'image-edit-api',
inputSource: editSourceReference,
lastActionParams: buildLastActionParams({
source: 'API',
label: imageGenerationApis.find(api => api.id === targetDraft.selectedApi)?.name || targetDraft.selectedApi,
params: [
{ label: 'Prompt', type: 'string', value: targetDraft.prompt.trim() },
{ label: 'Image source', type: 'image', value: editSourceReference }
]
})
})
if (savedEdits.length > 1) {
await spawnAdditionalResultNodes('Image', savedEdits.slice(1).map(edit => ({
id: edit.id,
name: edit.name || targetDraft.name.trim()
})))
}
setActionDraftsByNodeId({})
} catch (err) {
await setProcessingState('error', null, { error: err.message || 'Image edit failed', inputSource: editSourceReference })
pushExternalApiFailureNotification(
'Image edit failed',
err.message || 'Image edit failed',
imageGenerationApis.find(api => api.id === targetDraft.selectedApi)?.name || 'Image edit API'
)
}
return
}
await setProcessingState('processing', null, { processingSource: 'API' })
try {
const generatedAsset = await generateImage(project.id, {
@ -1517,6 +1565,13 @@ export default function GraphPage({ project }) {
inputValues[parameter.id] = inputValue
}
// With an image attached to the node, the workflow output is saved as
// an edit of that image instead of as a brand-new asset — but only when
// the workflow exposes an image input to receive it. A pure text-to-image
// workflow can't edit the attached image, so it falls back to generation.
const connectedInputAsset = getConnectedInputAssetFrom(nodes, edges, targetNodeId)
const workflowAcceptsImageInput = (workflow.parameters || []).some(parameter => getWorkflowParameterValueType(parameter) === 'image')
const saveAsEdit = Boolean(connectedInputAsset && workflowAcceptsImageInput)
const promptId = createComfyExecutionId('graph-image-prompt')
const clientId = createComfyExecutionId('graph-image-client')
setActionDraftsByNodeId({})
@ -1526,15 +1581,55 @@ export default function GraphPage({ project }) {
projectName: project.name,
page: 'graph',
targetId: targetNodeId,
kind: 'image',
kind: saveAsEdit ? 'imageEdit' : 'image',
label: targetDraft.name.trim() || workflow.name
})
await setProcessingState('processing', 0, { processingSource: 'ComfyUI', promptId }, {
progressDetail: 'Preparing ComfyUI workflow',
progressDetail: saveAsEdit ? 'Preparing ComfyUI image edit' : 'Preparing ComfyUI workflow',
currentNodeLabel: 'Waiting for ComfyUI execution to start'
})
try {
if (saveAsEdit) {
const response = await runImageEditComfy(project.id, {
assetId: connectedInputAsset.id,
workflowId: Number(targetDraft.workflowId),
name: targetDraft.name.trim(),
inputValues,
promptId,
clientId
})
const savedEdits = response?.savedEdits || []
if (savedEdits.length === 0) {
throw new Error('ComfyUI image edit did not return any saved image')
}
setNodeTransientData(targetNodeId, {
status: 'processing',
progress: 100,
progressDetail: 'Saving edited image',
currentNodeLabel: 'ComfyUI image edit completed'
})
await applyNodeResult({ id: savedEdits[0].id, name: savedEdits[0].name || targetDraft.name.trim() }, {
lastAction: 'image-edit-comfy',
promptId,
inputSource: JSON.stringify(inputValues),
lastActionParams: buildLastActionParams({
source: 'ComfyUI',
label: workflow.name,
params: describeWorkflowParams(workflow, inputValues, targetDraft, targetInputSources)
})
})
if (savedEdits.length > 1) {
await spawnAdditionalResultNodes('Image', savedEdits.slice(1).map(edit => ({
id: edit.id,
name: edit.name || targetDraft.name.trim()
})))
}
await persistWorkflowDefaultsIfRequested(targetDraft, workflow, inputValues)
completeJob(promptId, { status: 'completed' })
return
}
const generatedAssets = await runComfyWorkflow(project.id, {
workflowId: Number(targetDraft.workflowId),
name: targetDraft.name.trim(),