Fixed assets linked to a project

This commit is contained in:
Bruno Fargnoli 2026-07-27 10:35:35 +02:00
parent 21312811e5
commit 22c6badff1
6 changed files with 783 additions and 238 deletions

View file

@ -49,10 +49,15 @@ 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() },
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.')
},
annotations: { readOnlyHint: true }
}, toolHandler(async ({ projectId }) => {
const assets = await api.apiJson('GET', '/assets', { query: { projectId } });
}, toolHandler(async ({ projectId, includeChildren }) => {
const assets = await api.apiJson('GET', '/assets', {
query: { projectId, ...(includeChildren ? { includeChildren: 'true' } : {}) }
});
return (Array.isArray(assets) ? assets : []).map(asset => withAssetUrls(api, asset));
}));
@ -101,22 +106,48 @@ export function registerAssetTools(server, { api, notifyMutation }) {
server.registerTool('link_asset', {
title: 'Link existing asset',
description: 'Attach an already-stored asset file (by its stored filename) to a project — creates the card/link without re-uploading.',
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.',
inputSchema: {
projectId: z.number().int(),
filename: z.string().min(1).describe('Stored asset filename (from list_library_assets)'),
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.'),
type: z.enum(['image', 'mesh']).default('image'),
name: z.string().optional(),
metadata: z.record(z.string(), z.any()).optional()
metadata: z.record(z.string(), z.any()).optional(),
cascadeChildren: z.boolean().optional().describe('With assetId: also link every edit/version of that asset.')
}
}, toolHandler(async ({ projectId, filename, type, name, metadata }) => {
const asset = await api.apiJson('POST', '/assets/link', {
}, 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 } : {}) }
});
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.',

104
server.js
View file

@ -65,6 +65,8 @@ import {
getWorkflowRecordById,
initializeStorage,
listLibraryAssetsByType,
linkExistingAssetToProject,
unlinkAssetFromProjectById,
listProjectAssets,
listProjectTasks,
listProjects,
@ -2804,7 +2806,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 })
? await createAssetVersion({ assetId: normalizedParentAssetId, ...assetPayload, thumbnailPath: thumbnailFilename, inheritThumbnail: false, projectId: Number(projectId) })
: await createProjectAsset({ projectId: Number(projectId), ...assetPayload, thumbnailPath: thumbnailFilename }));
}
@ -3564,7 +3566,7 @@ app.post('/api/comfyui/workflows/run', workflowExecutionUpload.any(), async (req
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 (see ensureDetachedCard).
// 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
@ -3842,7 +3844,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 })
? await createAssetVersion({ assetId: outputParentId, ...generatedAssetPayload, thumbnailPath: meshThumbnailFilename, inheritThumbnail: false, projectId: hasProjectId ? normalizedProjectId : null })
: (outputParentId && inferredAssetType === 'image')
? {
...(await createAssetEditRecord({
@ -3852,6 +3854,7 @@ 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'
@ -4390,7 +4393,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 })
? await createAssetVersion({ assetId: normalizedParentAssetId, ...meshAssetPayload, inheritThumbnail: false, projectId: Number(projectId) })
: await createProjectAsset({ projectId: Number(projectId), ...meshAssetPayload });
await clearCardProcessingState(processingProjectId, processingCardId, {
@ -5205,6 +5208,50 @@ 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') {
@ -5316,8 +5363,12 @@ app.post('/api/projects/import', async (req, res) => {
});
app.get('/api/assets', async (req, res) => {
const { projectId } = req.query;
res.json(await listProjectAssets(projectId ? Number(projectId) : null));
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'
}));
});
app.get('/api/cards', async (req, res) => {
@ -6565,10 +6616,40 @@ app.get('/api/assets/resolve-source', async (req, res) => {
app.post('/api/assets/link', async (req, res) => {
try {
const { projectId, filename, type = 'image', name, metadata, detached } = req.body;
const { projectId, assetId, filename, type = 'image', name, metadata, detached } = req.body;
if (!projectId || !filename) {
return res.status(400).json({ error: 'projectId and filename are required' });
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' });
}
const assetType = type || inferAssetTypeFromFilename(filename);
@ -6613,7 +6694,10 @@ app.post('/api/assets/link', async (req, res) => {
app.delete('/api/assets/:id', async (req, res) => {
try {
const assetId = Number(req.params.id);
const result = await deleteAssetById(assetId);
// 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 });
if (result.status === 'not-found') {
return res.status(404).json({ error: 'Asset card not found' });

View file

@ -590,8 +590,9 @@ export function ProjectProvider({ children }) {
return data
}
const getProjectAssets = async (projectId) => {
const res = await fetch(`${API_BASE}/assets?projectId=${projectId}`)
const getProjectAssets = async (projectId, { includeChildren = false } = {}) => {
const query = includeChildren ? '&includeChildren=true' : ''
const res = await fetch(`${API_BASE}/assets?projectId=${projectId}${query}`)
return await res.json()
}
@ -878,6 +879,39 @@ 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) {
@ -903,8 +937,9 @@ export function ProjectProvider({ children }) {
return data
}
const deleteAsset = async (assetId) => {
const res = await fetch(`${API_BASE}/assets/${assetId}`, { method: 'DELETE' })
const deleteAsset = async (assetId, { projectId = null } = {}) => {
const query = projectId ? `?projectId=${projectId}` : ''
const res = await fetch(`${API_BASE}/assets/${assetId}${query}`, { method: 'DELETE' })
if (!res.ok) {
const data = await res.json().catch(() => ({}))
@ -1318,6 +1353,8 @@ export function ProjectProvider({ children }) {
getPaintDocument,
savePaintDocument,
attachExistingAsset,
linkAssetToProject,
unlinkAssetFromProject,
resolveAssetSourceReference,
deleteAsset,
moveKanbanCard,

View file

@ -454,8 +454,15 @@ 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 : []
const ids = [
...(Array.isArray(asset?.projectIds) ? asset.projectIds : []),
...(Array.isArray(asset?.children) ? asset.children : [])
.flatMap(child => (Array.isArray(child?.projectIds) ? child.projectIds : []))
]
const keys = [...new Set(
ids.filter(id => id !== null && id !== undefined).map(id => String(id))
)]

View file

@ -497,7 +497,9 @@ export default function KanbanPage() {
const handleRemoveImage = async (assetId) => {
try {
await deleteAsset(assetId)
// Scope the removal to THIS project — an asset shared with another project
// must keep its membership there.
await deleteAsset(assetId, { projectId })
await Promise.all([refreshProjectAssets(), refreshCardAttributes()])
} catch (err) {
console.error('Failed to remove image:', err)
@ -508,7 +510,7 @@ export default function KanbanPage() {
const handleRemoveImageCard = async (cardId, cardAssets) => {
try {
for (const asset of cardAssets) {
await deleteAsset(asset.id)
await deleteAsset(asset.id, { projectId })
}
if (cardId) {

File diff suppressed because it is too large Load diff