Fixed Storage with images generated from a board

This commit is contained in:
Bruno Fargnoli 2026-07-20 16:43:25 +02:00
parent be0318c1d8
commit 1389d9c443
6 changed files with 150 additions and 19 deletions

View file

@ -50,6 +50,7 @@ import {
getBoardById,
createBoard,
updateBoard,
resolveEditableSourceReference,
deleteLibraryAssetByFilePath,
deleteProjectById,
findLibraryAssetByFilePath,
@ -6545,6 +6546,23 @@ 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, filename, type = 'image', name, metadata, detached } = req.body;

View file

@ -42,8 +42,8 @@ function collectImageWorkflows(workflows = []) {
)
}
export default function BoardAiPanel({ projectId, projectName, boardId, onImageGenerated }) {
const { getComfyWorkflows, runComfyWorkflow, generateImage, attachExistingAsset } = useProjects()
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()
@ -102,6 +102,31 @@ export default function BoardAiPanel({ projectId, projectName, boardId, onImageG
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 }
@ -219,6 +244,16 @@ export default function BoardAiPanel({ projectId, projectName, boardId, onImageG
>
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 }}
@ -390,22 +425,14 @@ export default function BoardAiPanel({ projectId, projectName, boardId, onImageG
setAssetPickerParam(null)
if (!asset) return
try {
// The selector lists library assets whose ids aren't project-scoped.
// Attach the file to this project (mirrors GraphPage) so the server
// can resolve it as a project image/mesh source for the workflow.
const attached = await attachExistingAsset(projectId, {
filename: asset.filename || asset.filePath,
type: picker.valueType === 'mesh' ? 'mesh' : 'image',
name: asset.name,
metadata: { source: 'ASSET LIB' },
// Link the source to the project without a Kanban card; the edit
// output is parented to it (see autoParentFromInputs below).
detached: true
})
setInputValue(picker.paramId, {
source: `asset:${attached.id}`,
name: attached.name || asset.name || 'Selected asset'
})
// 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')

View file

@ -852,6 +852,16 @@ 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',
@ -1308,6 +1318,7 @@ export function ProjectProvider({ children }) {
getPaintDocument,
savePaintDocument,
attachExistingAsset,
resolveAssetSourceReference,
deleteAsset,
moveKanbanCard,
deleteCard,

View file

@ -300,7 +300,8 @@
.board-ai-panel__file-actions {
display: flex;
gap: 0.75rem;
flex-wrap: wrap;
gap: 0.6rem;
margin-top: 0.3rem;
}

View file

@ -56,6 +56,7 @@ export default function BoardPage() {
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(() => {
@ -221,6 +222,18 @@ export default function BoardPage() {
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
@ -228,6 +241,8 @@ export default function BoardPage() {
backfillLocalImages(elements, files)
}, [scheduleSave, backfillLocalImages])
const getSelectedBoardImage = useCallback(() => selectedImageRef.current, [])
// Flush a pending save on unmount / board switch.
useEffect(() => () => {
if (saveTimerRef.current) {
@ -373,6 +388,7 @@ export default function BoardPage() {
projectName={project?.name || ''}
boardId={boardId}
onImageGenerated={placeAssetImage}
getSelectedBoardImage={getSelectedBoardImage}
/>
</div>
</div>

View file

@ -1810,6 +1810,64 @@ export async function resolveProjectImageSource(projectId, sourceReference) {
return await resolveProjectAssetSourceById(projectId, assetId, 'Image');
}
// Given a file (served filename or stored path) chosen as a workflow image/mesh
// input, produce the correct source reference so the OUTPUT is parented to the
// root ancestor and no bogus root asset is created:
// - an edit/child file -> "edit:<storedFilePath>" (server parents output to the root)
// - a root already in this project -> "asset:<id>"
// - a library root not in this project -> attach detached, then "asset:<newId>"
// This is what the Brainstorming Board uses for "From Assets" / "Selected image".
export async function resolveEditableSourceReference(projectId, type, filePathOrFilename) {
const normalizedProjectId = await ensureProjectExists(projectId);
const normalizedType = normalizeAssetTypeName(type); // 'Image' | 'Mesh'
const lowerType = normalizedType.toLowerCase();
const stored = toStoredAssetPath(lowerType, filePathOrFilename);
const db = await getDb();
// 1. The file belongs to an edit/version (child) → reference it as an edit.
const editRow = await get(
db,
`SELECT a.id FROM Assets a
JOIN AssetTypes at ON at.id = a.assetTypeId
WHERE a.filePath = ? AND a.parentId IS NOT NULL AND at.name = ?
LIMIT 1`,
[stored, normalizedType]
);
if (editRow) {
return { sourceReference: `edit:${stored}`, isEdit: true };
}
// 2. A root asset with this file already linked to the project → reference by id.
const projectRoot = await get(
db,
`SELECT a.id FROM Assets a
JOIN AssetTypes at ON at.id = a.assetTypeId
JOIN Cards_Assets ca ON ca.assetId = a.id
JOIN Cards c ON c.id = ca.cardId
WHERE a.filePath = ? AND a.parentId IS NULL AND at.name = ? AND c.projectId = ?
LIMIT 1`,
[stored, normalizedType, normalizedProjectId]
);
if (projectRoot) {
return { sourceReference: `asset:${projectRoot.id}`, isEdit: false };
}
// 3. Library root not in this project → attach it (detached, no Kanban card).
const libraryAsset = await findLibraryAssetByFilePath(lowerType, stored);
const attached = await createProjectAsset({
projectId: normalizedProjectId,
type: lowerType,
name: libraryAsset?.name || stored.split('/').pop(),
filePath: stored,
thumbnailPath: libraryAsset?.thumbnail || null,
width: libraryAsset?.width ?? 0,
height: libraryAsset?.height ?? 0,
metadata: { source: 'ASSET LIB' },
detached: true
});
return { sourceReference: `asset:${attached.id}`, isEdit: false, attached: true };
}
export async function resolveProjectMeshSource(projectId, sourceReference) {
const parsedReference = typeof sourceReference === 'string'
? sourceReference