Added Brainstorming Boards

This commit is contained in:
Bruno Fargnoli 2026-07-20 13:41:58 +02:00
parent 5d1bb30044
commit 72455e8064
14 changed files with 4196 additions and 31 deletions

2455
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -27,6 +27,7 @@
"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",

132
server.js
View file

@ -45,6 +45,11 @@ import {
deleteAssetById,
deleteProjectConnection,
deleteProjectNode,
deleteBoard,
listProjectBoards,
getBoardById,
createBoard,
updateBoard,
deleteLibraryAssetByFilePath,
deleteProjectById,
findLibraryAssetByFilePath,
@ -3557,6 +3562,9 @@ 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 (see ensureDetachedCard).
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
@ -3847,7 +3855,7 @@ app.post('/api/comfyui/workflows/run', workflowExecutionUpload.any(), async (req
})),
type: 'image'
}
: await createProjectAsset({ ...generatedAssetPayload, thumbnailPath: meshThumbnailFilename });
: await createProjectAsset({ ...generatedAssetPayload, thumbnailPath: meshThumbnailFilename, detached: persistAssetsDetached });
generatedAssets.push({
...persistedAsset,
url: `${getRequestBaseUrl(req)}/assets/${encodeURI(toAssetUrlPath(storedFilePath))}`,
@ -5480,6 +5488,86 @@ 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([
@ -7084,6 +7172,9 @@ 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' });
@ -7092,21 +7183,23 @@ app.post('/api/images/generate', async (req, res) => {
const settings = await getSettings();
const trimmedPrompt = prompt.trim();
processingProjectId = Number(projectId);
processingCardId = cardId || randomUUID();
processingCardId = detachedAsset ? null : (cardId || randomUUID());
processingCardName = trimmedName;
processingStartedAt = Date.now();
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
});
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
});
}
const googleSettings = settings?.apis?.google;
const googleGenerationSettings = googleSettings?.imageGeneration;
@ -7248,14 +7341,17 @@ app.post('/api/images/generate', async (req, res) => {
mimeType: inlineData.mimeType,
responseId,
usage: responseBody?.usage || responseBody?.usageMetadata || null,
cardId: processingCardId
...(processingCardId ? { cardId: processingCardId } : {})
},
createdAt: Date.now()
createdAt: Date.now(),
detached: detachedAsset
});
await clearCardProcessingState(processingProjectId, processingCardId, {
name: processingCardName
});
if (!detachedAsset) {
await clearCardProcessingState(processingProjectId, processingCardId, {
name: processingCardName
});
}
res.status(201).json(newAsset);
} catch (err) {

View file

@ -8,6 +8,7 @@ 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() {
@ -19,6 +20,7 @@ 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

@ -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' }) {
export default function Header({ showSearch = false, showCreateNew = false, onSettingsClick, title = '', centerTitle = false, searchValue = '', onSearchChange, searchPlaceholder = 'Search Assets', projectId = null }) {
const location = useLocation()
const navigate = useNavigate()
const { notifications, clearNotifications, removeNotification } = useNotifications()
@ -182,6 +182,20 @@ 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

@ -0,0 +1,412 @@
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 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 }) {
const { getComfyWorkflows, runComfyWorkflow, generateImage, attachExistingAsset } = 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 })
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,
detachedAsset: 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>
</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>
)
}
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 {
// 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' }
})
setInputValue(picker.paramId, {
source: `asset:${attached.id}`,
name: attached.name || asset.name || 'Selected asset'
})
} 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

@ -0,0 +1,158 @@
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

@ -500,6 +500,69 @@ 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',
@ -1005,6 +1068,9 @@ 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
@ -1217,6 +1283,12 @@ export function ProjectProvider({ children }) {
deleteProject,
exportProject,
importProject,
getProjectBoards,
getBoard,
createBoard,
updateBoard,
saveBoardState,
deleteBoard,
getProjectAssets,
getProjectCards,
getProjectNodes,

356
src/pages/BoardPage.css Normal file
View file

@ -0,0 +1,356 @@
.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;
gap: 0.75rem;
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);
}

377
src/pages/BoardPage.jsx Normal file
View file

@ -0,0 +1,377 @@
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
} 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
// ---- 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 }
const sig = boardStateSignature(elements, appState)
if (sig === lastSavedSigRef.current) return
lastSavedSigRef.current = sig
scheduleSave()
backfillLocalImages(elements, files)
}, [scheduleSave, backfillLocalImages])
// 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
const refPath = asset.filename || 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}
/>
</div>
</div>
)
}

View file

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

View file

@ -3607,6 +3607,7 @@ export default function KanbanPage() {
onSettingsClick={() => setShowSettings(true)}
title={project?.name || 'Workspace'}
centerTitle
projectId={projectId}
/>
{statusMessage && (

89
src/utils/boardHelpers.js Normal file
View file

@ -0,0 +1,89 @@
// 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 })
}
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

@ -1065,10 +1065,26 @@ export async function initializeStorage() {
updatedAt INTEGER NOT NULL,
FOREIGN KEY(parentId) REFERENCES WikiPages(id) ON DELETE CASCADE
);
-- Brainstorming Boards: a Figma-like canvas. Many boards per project.
-- stateJson holds the Excalidraw document (elements + trimmed appState +
-- imageRefs); image binaries live as normal project Assets on disk.
CREATE TABLE IF NOT EXISTS Boards (
id INTEGER PRIMARY KEY AUTOINCREMENT,
projectId INTEGER NOT NULL,
name TEXT NOT NULL,
position INTEGER NOT NULL DEFAULT 0,
stateJson TEXT,
thumbnailPath TEXT,
createdAt INTEGER NOT NULL,
updatedAt INTEGER NOT NULL,
FOREIGN KEY(projectId) REFERENCES Projects(id) ON DELETE CASCADE
);
`
);
await run(db, 'CREATE INDEX IF NOT EXISTS idx_wikipages_parentId ON WikiPages(parentId)');
await run(db, 'CREATE INDEX IF NOT EXISTS idx_boards_projectId ON Boards(projectId)');
const assetColumns = await all(db, 'PRAGMA table_info(Assets)');
if (!assetColumns.some(column => column.name === 'thumbnail')) {
@ -2311,6 +2327,107 @@ export async function deleteProjectConnection(projectId, {
return { status: result.changes > 0 ? 'deleted' : 'not-found' };
}
// ---------------------------------------------------------------------------
// Brainstorming Boards
// ---------------------------------------------------------------------------
function mapBoardRow(row) {
return {
id: row.id,
projectId: row.projectId,
name: row.name,
position: row.position ?? 0,
state: parseJson(row.stateJson, null),
thumbnailPath: row.thumbnailPath || null,
createdAt: row.createdAt,
updatedAt: row.updatedAt
};
}
export async function listProjectBoards(projectId) {
const normalizedProjectId = await ensureProjectExists(projectId);
const db = await getDb();
const rows = await all(
db,
'SELECT * FROM Boards WHERE projectId = ? ORDER BY position ASC, id ASC',
[normalizedProjectId]
);
return rows.map(mapBoardRow);
}
export async function getBoardById(boardId) {
const db = await getDb();
const row = await get(db, 'SELECT * FROM Boards WHERE id = ?', [Number(boardId)]);
return row ? mapBoardRow(row) : null;
}
export async function createBoard({ projectId, name = 'Untitled Board', position = null } = {}) {
const normalizedProjectId = await ensureProjectExists(projectId);
const db = await getDb();
let nextPosition;
if (position === null || position === undefined || !Number.isFinite(Number(position))) {
const row = await get(
db,
'SELECT COALESCE(MAX(position), -1) + 1 AS nextPosition FROM Boards WHERE projectId = ?',
[normalizedProjectId]
);
nextPosition = row?.nextPosition ?? 0;
} else {
nextPosition = Number(position);
}
const now = Date.now();
const result = await run(
db,
'INSERT INTO Boards (projectId, name, position, stateJson, createdAt, updatedAt) VALUES (?, ?, ?, ?, ?, ?)',
[normalizedProjectId, String(name || '').trim() || 'Untitled Board', nextPosition, null, now, now]
);
return await getBoardById(result.lastID);
}
export async function updateBoard(boardId, updates = {}) {
const db = await getDb();
const existing = await get(db, 'SELECT * FROM Boards WHERE id = ?', [Number(boardId)]);
if (!existing) return null;
const fields = [];
const values = [];
if (updates.name !== undefined) {
fields.push('name = ?');
values.push(String(updates.name || '').trim() || 'Untitled Board');
}
if (updates.position !== undefined) {
fields.push('position = ?');
values.push(Number(updates.position) || 0);
}
if (updates.state !== undefined) {
fields.push('stateJson = ?');
values.push(updates.state === null ? null : JSON.stringify(updates.state));
}
if (updates.thumbnailPath !== undefined) {
fields.push('thumbnailPath = ?');
values.push(updates.thumbnailPath || null);
}
if (fields.length > 0) {
fields.push('updatedAt = ?');
values.push(Date.now());
values.push(Number(boardId));
await run(db, `UPDATE Boards SET ${fields.join(', ')} WHERE id = ?`, values);
}
return await getBoardById(boardId);
}
export async function deleteBoard(boardId) {
const db = await getDb();
const result = await run(db, 'DELETE FROM Boards WHERE id = ?', [Number(boardId)]);
return { status: result.changes > 0 ? 'deleted' : 'not-found' };
}
export async function setCardProcessingState(projectId, externalCardId, {
columnName = 'Images',
name = null,
@ -2811,10 +2928,40 @@ export async function moveCard(projectId, externalCardId, kanbanColumnId, positi
return await resolveProjectCard(projectId, externalCardId);
}
export async function createProjectAsset({ projectId, type, name, filePath, thumbnailPath = null, width = 0, height = 0, metadata = {}, createdAt = Date.now() }) {
const card = await ensureCard(projectId, 'Images', metadata.cardId, {
creationDate: createdAt
});
// A per-project "container" card that holds assets which must be linked to the
// project but must NOT appear on the Kanban board. It has no kanbanColumnId (so
// listProjectCards' INNER JOIN on Columns excludes it) and no nodeTypeId (so the
// graph node listing excludes it too) — yet the library listing still resolves
// the asset's project through it. Used for Brainstorming Board generations.
async function ensureDetachedCard(projectId, clientKey = 'board-assets') {
const normalizedProjectId = await ensureProjectExists(projectId);
const db = await getDb();
const existing = await get(
db,
'SELECT id, clientKey FROM Cards WHERE projectId = ? AND clientKey = ? AND kanbanColumnId IS NULL AND nodeTypeId IS NULL',
[normalizedProjectId, clientKey]
);
if (existing) {
return { id: existing.id, clientKey: existing.clientKey };
}
const result = await run(
db,
`INSERT INTO Cards (projectId, kanbanColumnId, nodeTypeId, clientKey, name, position, creationDate)
VALUES (?, NULL, NULL, ?, ?, NULL, ?)`,
[normalizedProjectId, clientKey, 'Board assets', Date.now()]
);
return { id: result.lastID, clientKey };
}
export async function createProjectAsset({ projectId, type, name, filePath, thumbnailPath = null, width = 0, height = 0, metadata = {}, createdAt = Date.now(), detached = false }) {
const card = detached
? await ensureDetachedCard(projectId)
: await ensureCard(projectId, 'Images', metadata.cardId, {
creationDate: createdAt
});
const assetId = await insertAsset({
name,
type,