Skip to content

Image Pipeline Playground

feat(frontend/workflows): refactor project management to workflows

Mohammad Rajaei3b40128292ad
diff --git a/frontend/src/app/App.tsx b/frontend/src/app/App.tsx
index 0969d2b..ae1c936 100644
--- a/frontend/src/app/App.tsx
+++ b/frontend/src/app/App.tsx
@@ -6,12 +6,12 @@ import { NodeInspector } from '../features/inspector/NodeInspector'
import { CodePanel } from '../features/code/CodePanel'
import { ExecutionLogPanel } from '../features/execution/ExecutionLogPanel'
import { PreviewGrid } from '../features/preview/PreviewGrid'
-import { ProjectsDialog } from '../features/projects/ProjectsDialog'
+import { RecentWorkflowsDialog } from '../features/workflows/RecentWorkflowsDialog'
+import { WorkflowNameDialog } from '../features/workflows/WorkflowNameDialog'
import { TemplateGallery } from '../features/templates/TemplateGallery'
import { useGraphStore } from '../store/graphStore'
import {
bindExecutionRunner,
- requestCodegen,
useExecutionSocket,
} from '../hooks/useExecutionSocket'
import { useWorkflowPersistence } from '../hooks/useWorkflowPersistence'
@@ -21,44 +21,34 @@ import { materializeSampleImages } from '../workflow/materializeSampleImages'
import {
confirmDiscardIfDirty,
loadExternalDocument,
-} from '../workflow/projectActions'
+ newWorkflow,
+ renameActiveWorkflow,
+ saveWorkflow,
+ saveWorkflowAs,
+} from '../workflow/workflowActions'
import type { WorkflowTemplate } from '../workflow/templates'
import { AppHeader } from './AppHeader'
+type NamePrompt = 'saveAs' | 'rename' | null
+
export default function App() {
- const setGeneratedCode = useGraphStore((s) => s.setGeneratedCode)
const toWorkflowDocument = useGraphStore((s) => s.toWorkflowDocument)
+ const workflowId = useGraphStore((s) => s.workflowId)
+ const workflowName = useGraphStore((s) => s.workflowName)
+ const workflowDescription = useGraphStore((s) => s.workflowDescription)
const nodeCatalog = useGraphStore((s) => s.nodeCatalog)
const selectedNodeId = useGraphStore((s) => s.selectedNodeId)
const isExecuting = useGraphStore((s) => s.isExecuting)
const { run, cancel } = useExecutionSocket()
const fileInputRef = useRef<HTMLInputElement>(null)
const [templatesOpen, setTemplatesOpen] = useState(false)
- const [projectsOpen, setProjectsOpen] = useState(false)
+ const [recentOpen, setRecentOpen] = useState(false)
+ const [namePrompt, setNamePrompt] = useState<NamePrompt>(null)
const [sideTab, setSideTab] = useState(0)
useEffect(() => bindExecutionRunner(run), [run])
useWorkflowPersistence()
- const onExportPython = async () => {
- try {
- const code = await requestCodegen()
- setGeneratedCode(code)
- notifySuccess('Python script exported')
- } catch (error) {
- notifyError(error instanceof Error ? error.message : 'Codegen failed')
- }
- }
-
- const onExportWorkflow = () => {
- try {
- downloadWorkflowJson(toWorkflowDocument())
- notifySuccess('Workflow exported')
- } catch (error) {
- notifyError(error instanceof Error ? error.message : 'Export failed')
- }
- }
-
const applyLoadedWorkflow = async (
text: string,
successMessage: string,
@@ -77,7 +67,34 @@ export default function App() {
}
}
- const onLoadWorkflowClick = () => {
+ const onNewWorkflow = () => {
+ if (!confirmDiscardIfDirty()) return
+ newWorkflow()
+ notifySuccess('New workflow')
+ }
+
+ const onSaveWorkflow = () => {
+ try {
+ if (!workflowId) {
+ setNamePrompt('saveAs')
+ return
+ }
+ saveWorkflow()
+ notifySuccess('Workflow saved')
+ } catch (error) {
+ notifyError(error instanceof Error ? error.message : 'Save failed')
+ }
+ }
+
+ const onSaveAsWorkflow = () => {
+ setNamePrompt('saveAs')
+ }
+
+ const onRenameWorkflow = () => {
+ setNamePrompt('rename')
+ }
+
+ const onImportWorkflow = () => {
if (nodeCatalog.length === 0) {
notifyError('Node catalog is still loading — try again in a moment')
return
@@ -91,10 +108,10 @@ export default function App() {
if (!file) return
try {
const text = await file.text()
- await applyLoadedWorkflow(text, 'Workflow loaded')
- setProjectsOpen(false)
+ await applyLoadedWorkflow(text, 'Workflow imported')
+ setRecentOpen(false)
} catch (error) {
- notifyError(error instanceof Error ? error.message : 'Load failed')
+ notifyError(error instanceof Error ? error.message : 'Import failed')
} finally {
if (fileInputRef.current) fileInputRef.current.value = ''
}
@@ -108,8 +125,27 @@ export default function App() {
setTemplatesOpen(true)
}
- const onOpenProjects = () => {
- setProjectsOpen(true)
+ const onOpenRecent = () => {
+ setRecentOpen(true)
+ }
+
+ const onConfirmNamePrompt = (meta: { name: string; description: string }) => {
+ try {
+ if (namePrompt === 'saveAs') {
+ const record = saveWorkflowAs(meta)
+ downloadWorkflowJson({
+ ...toWorkflowDocument(),
+ ...record,
+ })
+ notifySuccess(`Saved “${record.name}”`)
+ } else if (namePrompt === 'rename') {
+ renameActiveWorkflow(meta)
+ notifySuccess('Workflow renamed')
+ }
+ setNamePrompt(null)
+ } catch (error) {
+ notifyError(error instanceof Error ? error.message : 'Could not update workflow')
+ }
}
const onSelectTemplate = async (template: WorkflowTemplate) => {
@@ -146,16 +182,26 @@ export default function App() {
run({ targetNodeId: selectedNodeId })
}}
onCancel={cancel}
- onExportPython={() => void onExportPython()}
- onExportWorkflow={onExportWorkflow}
- onLoadWorkflow={onLoadWorkflowClick}
+ onNewWorkflow={onNewWorkflow}
+ onSaveWorkflow={onSaveWorkflow}
+ onSaveAsWorkflow={onSaveAsWorkflow}
+ onRenameWorkflow={onRenameWorkflow}
+ onImportWorkflow={onImportWorkflow}
onOpenTemplates={onOpenTemplates}
- onOpenProjects={onOpenProjects}
+ onOpenRecent={onOpenRecent}
+ />
+ <WorkflowNameDialog
+ open={namePrompt != null}
+ title={namePrompt === 'rename' ? 'Rename workflow' : 'Save as'}
+ confirmLabel={namePrompt === 'rename' ? 'Rename' : 'Save'}
+ initialName={workflowName}
+ initialDescription={workflowDescription}
+ onClose={() => setNamePrompt(null)}
+ onConfirm={onConfirmNamePrompt}
/>
- <ProjectsDialog
- open={projectsOpen}
- onClose={() => setProjectsOpen(false)}
- onImportFile={onLoadWorkflowClick}
+ <RecentWorkflowsDialog
+ open={recentOpen}
+ onClose={() => setRecentOpen(false)}
disabled={isExecuting}
/>
<TemplateGallery
diff --git a/frontend/src/app/AppHeader.tsx b/frontend/src/app/AppHeader.tsx
index 5b7a117..5e591b2 100644
--- a/frontend/src/app/AppHeader.tsx
+++ b/frontend/src/app/AppHeader.tsx
@@ -1,6 +1,7 @@
import {
Box,
Button,
+ Divider,
IconButton,
Menu,
MenuItem,
@@ -128,11 +129,13 @@ interface AppHeaderProps {
onRun: () => void
onRunToSelected: () => void
onCancel: () => void
- onExportPython: () => void
- onExportWorkflow: () => void
- onLoadWorkflow: () => void
+ onNewWorkflow: () => void
+ onSaveWorkflow: () => void
+ onSaveAsWorkflow: () => void
+ onRenameWorkflow: () => void
+ onImportWorkflow: () => void
onOpenTemplates: () => void
- onOpenProjects: () => void
+ onOpenRecent: () => void
}
const outlineBtnSx = {
@@ -153,15 +156,24 @@ const outlineBtnSx = {
},
} as const
+const menuItemSx = {
+ fontSize: 13,
+ fontWeight: 600,
+ py: 1,
+ '&:hover': { bgcolor: 'rgba(125,206,160,0.1)' },
+} as const
+
export function AppHeader({
onRun,
onRunToSelected,
onCancel,
- onExportPython,
- onExportWorkflow,
- onLoadWorkflow,
+ onNewWorkflow,
+ onSaveWorkflow,
+ onSaveAsWorkflow,
+ onRenameWorkflow,
+ onImportWorkflow,
onOpenTemplates,
- onOpenProjects,
+ onOpenRecent,
}: AppHeaderProps) {
const seed = useGraphStore((s) => s.seed)
const sampleCount = useGraphStore((s) => s.sampleCount)
@@ -171,13 +183,18 @@ export function AppHeader({
const selectedNodeId = useGraphStore((s) => s.selectedNodeId)
const nodeCount = useGraphStore((s) => s.nodes.length)
const edgeCount = useGraphStore((s) => s.edges.length)
- const projectName = useGraphStore((s) => s.projectName)
- const projectDirty = useGraphStore((s) => s.projectDirty)
+ const workflowName = useGraphStore((s) => s.workflowName)
+ const workflowDirty = useGraphStore((s) => s.workflowDirty)
const [infoOpen, setInfoOpen] = useState(false)
- const [exportAnchor, setExportAnchor] = useState<null | HTMLElement>(null)
- const exportMenuOpen = Boolean(exportAnchor)
+ const [workflowAnchor, setWorkflowAnchor] = useState<null | HTMLElement>(null)
+ const workflowMenuOpen = Boolean(workflowAnchor)
+
+ const closeWorkflowMenu = () => setWorkflowAnchor(null)
- const closeExportMenu = () => setExportAnchor(null)
+ const runMenuAction = (action: () => void) => {
+ closeWorkflowMenu()
+ action()
+ }
return (
<Box
@@ -289,10 +306,10 @@ export function AppHeader({
lineHeight: 1.2,
}}
>
- Project
+ Workflow
</Typography>
<Typography
- title={projectName}
+ title={workflowName}
sx={{
fontSize: 13,
fontWeight: 650,
@@ -303,8 +320,8 @@ export function AppHeader({
whiteSpace: 'nowrap',
}}
>
- {projectName}
- {projectDirty ? (
+ {workflowName}
+ {workflowDirty ? (
<Box component="span" sx={{ color: '#e67e22', ml: 0.35 }}>
*
</Box>
@@ -414,25 +431,6 @@ export function AppHeader({
}}
>
<Box sx={{ display: 'inline-flex', alignItems: 'center', gap: 1 }}>
- {isExecuting ? (
- <Box
- sx={{
- width: 8,
- height: 8,
- borderRadius: '50%',
- bgcolor: '#0f0f0f',
- animation: 'pulse 1s ease-in-out infinite',
- '@keyframes pulse': {
- '0%, 100%': { opacity: 0.35 },
- '50%': { opacity: 1 },
- },
- }}
- />
- ) : (
- <Box component="span" sx={{ fontSize: 11, lineHeight: 1 }}>
- ▶
- </Box>
- )}
{isExecuting ? 'Running…' : 'Run'}
</Box>
</Button>
@@ -459,53 +457,26 @@ export function AppHeader({
border: '1px solid rgba(255,255,255,0.06)',
}}
>
- <Button
- variant="outlined"
- disabled={isExecuting}
- onClick={onOpenProjects}
- sx={outlineBtnSx}
- >
- Projects
- </Button>
-
- <Button
- variant="outlined"
- disabled={isExecuting}
- onClick={onOpenTemplates}
- sx={outlineBtnSx}
- >
- Templates
- </Button>
-
- <Button
- variant="outlined"
- disabled={isExecuting}
- onClick={onLoadWorkflow}
- sx={outlineBtnSx}
- >
- Load
- </Button>
-
<Button
variant="outlined"
disabled={isExecuting}
aria-haspopup="menu"
- aria-expanded={exportMenuOpen ? 'true' : undefined}
- aria-controls={exportMenuOpen ? 'export-menu' : undefined}
- onClick={(event) => setExportAnchor(event.currentTarget)}
+ aria-expanded={workflowMenuOpen ? 'true' : undefined}
+ aria-controls={workflowMenuOpen ? 'workflow-menu' : undefined}
+ onClick={(event) => setWorkflowAnchor(event.currentTarget)}
sx={outlineBtnSx}
>
- Export
+ Workflow
<Box component="span" sx={{ ml: 0.75, fontSize: 10, opacity: 0.7, lineHeight: 1 }}>
▾
</Box>
</Button>
<Menu
- id="export-menu"
- anchorEl={exportAnchor}
- open={exportMenuOpen}
- onClose={closeExportMenu}
+ id="workflow-menu"
+ anchorEl={workflowAnchor}
+ open={workflowMenuOpen}
+ onClose={closeWorkflowMenu}
anchorOrigin={{ vertical: 'bottom', horizontal: 'right' }}
transformOrigin={{ vertical: 'top', horizontal: 'right' }}
slotProps={{
@@ -513,7 +484,7 @@ export function AppHeader({
elevation: 0,
sx: {
mt: 0.75,
- minWidth: 180,
+ minWidth: 200,
bgcolor: '#161616',
color: '#f4f1ea',
border: '1px solid rgba(255,255,255,0.1)',
@@ -529,33 +500,27 @@ export function AppHeader({
},
}}
>
- <MenuItem
- onClick={() => {
- closeExportMenu()
- onExportWorkflow()
- }}
- sx={{
- fontSize: 13,
- fontWeight: 600,
- py: 1,
- '&:hover': { bgcolor: 'rgba(125,206,160,0.1)' },
- }}
- >
- Workflow JSON
+ <MenuItem onClick={() => runMenuAction(onNewWorkflow)} sx={menuItemSx}>
+ New
</MenuItem>
- <MenuItem
- onClick={() => {
- closeExportMenu()
- onExportPython()
- }}
- sx={{
- fontSize: 13,
- fontWeight: 600,
- py: 1,
- '&:hover': { bgcolor: 'rgba(125,206,160,0.1)' },
- }}
- >
- Python script
+ <MenuItem onClick={() => runMenuAction(onSaveWorkflow)} sx={menuItemSx}>
+ Save
+ </MenuItem>
+ <MenuItem onClick={() => runMenuAction(onSaveAsWorkflow)} sx={menuItemSx}>
+ Save as…
+ </MenuItem>
+ <MenuItem onClick={() => runMenuAction(onRenameWorkflow)} sx={menuItemSx}>
+ Rename…
+ </MenuItem>
+ <Divider sx={{ borderColor: 'rgba(255,255,255,0.08)', my: 0.5 }} />
+ <MenuItem onClick={() => runMenuAction(onImportWorkflow)} sx={menuItemSx}>
+ Import…
+ </MenuItem>
+ <MenuItem onClick={() => runMenuAction(onOpenTemplates)} sx={menuItemSx}>
+ Templates…
+ </MenuItem>
+ <MenuItem onClick={() => runMenuAction(onOpenRecent)} sx={menuItemSx}>
+ Recent…
</MenuItem>
</Menu>
</Stack>
diff --git a/frontend/src/features/inspector/NodeInspector.tsx b/frontend/src/features/inspector/NodeInspector.tsx
index 55d924b..e04c77f 100644
--- a/frontend/src/features/inspector/NodeInspector.tsx
+++ b/frontend/src/features/inspector/NodeInspector.tsx
@@ -83,7 +83,7 @@ export function NodeInspector() {
>
<li>Connect matching port types (image, mask, bboxes, keypoints)</li>
<li>Press Run to execute with live previews</li>
- <li>Projects saves named pipelines; Export downloads JSON / Python</li>
+ <li>Workflow menu: save, import, templates, and recent pipelines</li>
</Box>
</Box>
)
diff --git a/frontend/src/features/projects/ProjectsDialog.tsx b/frontend/src/features/projects/ProjectsDialog.tsx
deleted file mode 100644
index 68d1bee..0000000
--- a/frontend/src/features/projects/ProjectsDialog.tsx
+++ /dev/null
@@ -1,535 +0,0 @@
-import { useState } from 'react'
-import {
- Box,
- Button,
- Dialog,
- DialogContent,
- IconButton,
- Stack,
- TextField,
- Typography,
-} from '@mui/material'
-import { useGraphStore } from '../../store/graphStore'
-import { notifyError, notifyInfo, notifySuccess } from '../../notify'
-import { downloadWorkflowJson } from '../../workflow/io'
-import {
- confirmDiscardIfDirty,
- deleteProjectById,
- listProjects,
- newProject,
- openProject,
- type ProjectRecord,
- renameActiveProject,
- saveProject,
- saveProjectAs,
-} from '../../workflow/projectActions'
-
-type ProjectsDialogProps = {
- open: boolean
- onClose: () => void
- onImportFile: () => void
- disabled?: boolean
-}
-
-type PromptMode = 'saveAs' | 'rename' | null
-
-const outlineBtnSx = {
- height: 34,
- px: 1.5,
- borderRadius: 1.25,
- textTransform: 'none',
- fontWeight: 650,
- color: '#f0ebe3',
- borderColor: 'rgba(255,255,255,0.16)',
- '&:hover': {
- borderColor: 'rgba(125,206,160,0.45)',
- bgcolor: 'rgba(125,206,160,0.08)',
- },
- '&.Mui-disabled': {
- color: 'rgba(255,255,255,0.3)',
- borderColor: 'rgba(255,255,255,0.08)',
- },
-} as const
-
-function formatUpdatedAt(value: string): string {
- try {
- return new Intl.DateTimeFormat(undefined, {
- dateStyle: 'medium',
- timeStyle: 'short',
- }).format(new Date(value))
- } catch {
- return value
- }
-}
-
-function ProjectRow({
- project,
- active,
- disabled,
- onOpen,
- onDelete,
-}: {
- project: ProjectRecord
- active: boolean
- disabled?: boolean
- onOpen: () => void
- onDelete: () => void
-}) {
- const nodeCount = project.graph.nodes.length
- return (
- <Box
- sx={{
- display: 'flex',
- alignItems: 'stretch',
- gap: 1,
- p: 1.5,
- borderRadius: 1.75,
- border: '1px solid',
- borderColor: active ? 'rgba(125,206,160,0.45)' : 'rgba(255,255,255,0.1)',
- bgcolor: active ? 'rgba(125,206,160,0.08)' : 'rgba(255,255,255,0.02)',
- }}
- >
- <Box sx={{ flex: 1, minWidth: 0 }}>
- <Typography
- sx={{
- fontFamily: '"Fraunces", Georgia, serif',
- fontWeight: 700,
- fontSize: 16,
- letterSpacing: '-0.02em',
- color: '#f4f1ea',
- lineHeight: 1.2,
- }}
- >
- {project.name}
- {active ? (
- <Box
- component="span"
- sx={{
- ml: 1,
- fontFamily: 'inherit',
- fontSize: 11,
- fontWeight: 700,
- letterSpacing: '0.06em',
- textTransform: 'uppercase',
- color: '#7dcea0',
- }}
- >
- Open
- </Box>
- ) : null}
- </Typography>
- {project.description ? (
- <Typography
- sx={{
- mt: 0.5,
- fontSize: 12.5,
- color: 'rgba(244,241,234,0.52)',
- lineHeight: 1.4,
- }}
- >
- {project.description}
- </Typography>
- ) : null}
- <Typography
- sx={{
- mt: 0.75,
- fontSize: 11,
- color: 'rgba(244,241,234,0.38)',
- fontVariantNumeric: 'tabular-nums',
- }}
- >
- {nodeCount} node{nodeCount === 1 ? '' : 's'} · Updated {formatUpdatedAt(project.updatedAt)}
- </Typography>
- </Box>
- <Stack spacing={0.75} sx={{ justifyContent: 'center' }}>
- <Button
- size="small"
- variant="outlined"
- disabled={disabled || active}
- onClick={onOpen}
- sx={{ ...outlineBtnSx, height: 30, px: 1.25, fontSize: 12 }}
- >
- Open
- </Button>
- <Button
- size="small"
- variant="outlined"
- disabled={disabled}
- onClick={onDelete}
- sx={{
- ...outlineBtnSx,
- height: 30,
- px: 1.25,
- fontSize: 12,
- color: '#ff8a80',
- borderColor: 'rgba(255,138,128,0.28)',
- '&:hover': {
- borderColor: 'rgba(255,138,128,0.55)',
- bgcolor: 'rgba(192,57,43,0.12)',
- },
- }}
- >
- Delete
- </Button>
- </Stack>
- </Box>
- )
-}
-
-export function ProjectsDialog({
- open,
- onClose,
- onImportFile,
- disabled,
-}: ProjectsDialogProps) {
- const projectId = useGraphStore((s) => s.projectId)
- const projectName = useGraphStore((s) => s.projectName)
- const projectDescription = useGraphStore((s) => s.projectDescription)
- const projectDirty = useGraphStore((s) => s.projectDirty)
- const toWorkflowDocument = useGraphStore((s) => s.toWorkflowDocument)
- const [projects, setProjects] = useState<ProjectRecord[]>([])
- const [promptMode, setPromptMode] = useState<PromptMode>(null)
- const [promptName, setPromptName] = useState('')
- const [promptDescription, setPromptDescription] = useState('')
-
- const refresh = () => setProjects(listProjects())
-
- const closePrompt = () => {
- setPromptMode(null)
- setPromptName('')
- setPromptDescription('')
- }
-
- const handleEnter = () => {
- refresh()
- closePrompt()
- }
-
- const handleClose = () => {
- closePrompt()
- onClose()
- }
-
- const onNew = () => {
- if (!confirmDiscardIfDirty()) return
- newProject()
- refresh()
- notifySuccess('New project')
- }
-
- const onOpen = (id: string) => {
- if (id === projectId && !projectDirty) {
- handleClose()
- return
- }
- if (!confirmDiscardIfDirty()) return
- try {
- const { skippedTypes } = openProject(id)
- refresh()
- if (skippedTypes.length > 0) {
- notifyInfo(`Opened project (skipped unknown nodes: ${skippedTypes.join(', ')})`)
- } else {
- notifySuccess('Project opened')
- }
- handleClose()
- } catch (error) {
- notifyError(error instanceof Error ? error.message : 'Could not open project')
- }
- }
-
- const onSave = () => {
- try {
- if (!projectId) {
- setPromptMode('saveAs')
- setPromptName(projectName)
- setPromptDescription(projectDescription)
- return
- }
- saveProject()
- refresh()
- notifySuccess('Project saved')
- } catch (error) {
- notifyError(error instanceof Error ? error.message : 'Save failed')
- }
- }
-
- const openSaveAs = () => {
- setPromptMode('saveAs')
- setPromptName(projectName)
- setPromptDescription(projectDescription)
- }
-
- const openRename = () => {
- setPromptMode('rename')
- setPromptName(projectName)
- setPromptDescription(projectDescription)
- }
-
- const submitPrompt = () => {
- const name = promptName.trim()
- if (!name) {
- notifyError('Enter a project name')
- return
- }
- try {
- if (promptMode === 'saveAs') {
- saveProjectAs({ name, description: promptDescription })
- refresh()
- notifySuccess(`Saved “${name}”`)
- } else if (promptMode === 'rename') {
- renameActiveProject({ name, description: promptDescription })
- refresh()
- notifySuccess('Project renamed')
- }
- closePrompt()
- } catch (error) {
- notifyError(error instanceof Error ? error.message : 'Could not update project')
- }
- }
-
- const onDelete = (id: string, name: string) => {
- if (!window.confirm(`Delete “${name}” from the library? This cannot be undone.`)) {
- return
- }
- deleteProjectById(id)
- refresh()
- notifySuccess('Project deleted')
- }
-
- const onExport = () => {
- try {
- downloadWorkflowJson(toWorkflowDocument())
- notifySuccess('Workflow exported')
- } catch (error) {
- notifyError(error instanceof Error ? error.message : 'Export failed')
- }
- }
-
- return (
- <Dialog
- open={open}
- onClose={handleClose}
- maxWidth="sm"
- fullWidth
- slotProps={{
- transition: {
- onEnter: handleEnter,
- },
- paper: {
- sx: {
- bgcolor: '#121212',
- color: '#f4f1ea',
- border: '1px solid rgba(255,255,255,0.1)',
- borderRadius: 2.5,
- overflow: 'hidden',
- backgroundImage: `
- radial-gradient(ellipse 70% 55% at 0% 0%, rgba(125,206,160,0.14), transparent 55%),
- radial-gradient(ellipse 55% 45% at 100% 0%, rgba(230,126,34,0.1), transparent 50%),
- linear-gradient(180deg, #161616 0%, #101010 100%)
- `,
- },
- },
- }}
- >
- <Box
- sx={{
- display: 'flex',
- alignItems: 'flex-start',
- justifyContent: 'space-between',
- gap: 2,
- px: 3,
- pt: 2.5,
- pb: 1.5,
- }}
- >
- <Box sx={{ minWidth: 0 }}>
- <Typography
- sx={{
- fontFamily: '"Fraunces", Georgia, serif',
- fontWeight: 700,
- fontSize: 24,
- letterSpacing: '-0.03em',
- lineHeight: 1.15,
- }}
- >
- Projects
- </Typography>
- <Typography sx={{ mt: 0.75, fontSize: 13, color: 'rgba(244,241,234,0.5)', maxWidth: 480 }}>
- Save named pipelines in this browser, or import and export JSON files.
- {projectDirty ? ' Current project has unsaved changes.' : ''}
- </Typography>
- </Box>
- <IconButton
- aria-label="Close projects"
- onClick={handleClose}
- size="small"
- sx={{
- color: 'rgba(244,241,234,0.55)',
- border: '1px solid rgba(255,255,255,0.1)',
- borderRadius: 1.25,
- '&:hover': { bgcolor: 'rgba(255,255,255,0.06)', color: '#f4f1ea' },
- }}
- >
- ×
- </IconButton>
- </Box>
-
- <DialogContent sx={{ px: 3, pt: 0.5, pb: 3 }}>
- <Stack
- direction="row"
- spacing={1}
- useFlexGap
- sx={{ mb: 2, flexWrap: 'wrap' }}
- >
- <Button variant="outlined" disabled={disabled} onClick={onNew} sx={outlineBtnSx}>
- New
- </Button>
- <Button variant="outlined" disabled={disabled} onClick={onSave} sx={outlineBtnSx}>
- Save
- </Button>
- <Button variant="outlined" disabled={disabled} onClick={openSaveAs} sx={outlineBtnSx}>
- Save As…
- </Button>
- <Button variant="outlined" disabled={disabled} onClick={openRename} sx={outlineBtnSx}>
- Rename…
- </Button>
- <Button
- variant="outlined"
- disabled={disabled}
- onClick={onImportFile}
- sx={outlineBtnSx}
- >
- Import file…
- </Button>
- <Button variant="outlined" disabled={disabled} onClick={onExport} sx={outlineBtnSx}>
- Export JSON
- </Button>
- </Stack>
-
- {promptMode ? (
- <Box
- sx={{
- mb: 2,
- p: 1.75,
- borderRadius: 1.75,
- border: '1px solid rgba(125,206,160,0.3)',
- bgcolor: 'rgba(0,0,0,0.28)',
- }}
- >
- <Typography
- sx={{
- mb: 1.25,
- fontSize: 12,
- fontWeight: 700,
- letterSpacing: '0.06em',
- textTransform: 'uppercase',
- color: 'rgba(125,206,160,0.9)',
- }}
- >
- {promptMode === 'saveAs' ? 'Save as' : 'Rename'}
- </Typography>
- <Stack spacing={1.25}>
- <TextField
- size="small"
- label="Name"
- value={promptName}
- autoFocus
- onChange={(event) => setPromptName(event.target.value)}
- onKeyDown={(event) => {
- if (event.key === 'Enter') submitPrompt()
- }}
- sx={{
- '& .MuiInputBase-root': {
- color: '#f0ebe3',
- bgcolor: '#0f0f0f',
- borderRadius: 1.25,
- },
- '& .MuiInputLabel-root': { color: 'rgba(244,241,234,0.45)' },
- '& .MuiOutlinedInput-notchedOutline': {
- borderColor: 'rgba(255,255,255,0.1)',
- },
- }}
- />
- <TextField
- size="small"
- label="Description (optional)"
- value={promptDescription}
- onChange={(event) => setPromptDescription(event.target.value)}
- sx={{
- '& .MuiInputBase-root': {
- color: '#f0ebe3',
- bgcolor: '#0f0f0f',
- borderRadius: 1.25,
- },
- '& .MuiInputLabel-root': { color: 'rgba(244,241,234,0.45)' },
- '& .MuiOutlinedInput-notchedOutline': {
- borderColor: 'rgba(255,255,255,0.1)',
- },
- }}
- />
- <Stack direction="row" spacing={1}>
- <Button
- variant="contained"
- onClick={submitPrompt}
- sx={{
- textTransform: 'none',
- fontWeight: 700,
- bgcolor: '#e67e22',
- color: '#0f0f0f',
- '&:hover': { bgcolor: '#f39c12' },
- }}
- >
- {promptMode === 'saveAs' ? 'Save' : 'Rename'}
- </Button>
- <Button variant="outlined" onClick={closePrompt} sx={outlineBtnSx}>
- Cancel
- </Button>
- </Stack>
- </Stack>
- </Box>
- ) : null}
-
- {projects.length === 0 ? (
- <Box
- sx={{
- py: 5,
- textAlign: 'center',
- border: '1px dashed rgba(255,255,255,0.12)',
- borderRadius: 2,
- color: 'rgba(244,241,234,0.45)',
- }}
- >
- <Typography sx={{ fontSize: 14 }}>No saved projects yet.</Typography>
- <Typography sx={{ mt: 0.75, fontSize: 12.5, color: 'rgba(244,241,234,0.35)' }}>
- Use Save As to keep the current canvas in this library.
- </Typography>
- </Box>
- ) : (
- <Stack spacing={1.25}>
- {projects.map((project) => (
- <ProjectRow
- key={project.id}
- project={project}
- active={project.id === projectId}
- disabled={disabled}
- onOpen={() => onOpen(project.id)}
- onDelete={() => onDelete(project.id, project.name)}
- />
- ))}
- </Stack>
- )}
-
- <Typography
- sx={{
- mt: 2,
- fontSize: 11,
- color: 'rgba(244,241,234,0.35)',
- letterSpacing: '0.02em',
- }}
- >
- {projects.length} project{projects.length === 1 ? '' : 's'} in this browser
- </Typography>
- </DialogContent>
- </Dialog>
- )
-}
diff --git a/frontend/src/features/workflows/RecentWorkflowsDialog.tsx b/frontend/src/features/workflows/RecentWorkflowsDialog.tsx
new file mode 100644
index 0000000..37625a1
--- /dev/null
+++ b/frontend/src/features/workflows/RecentWorkflowsDialog.tsx
@@ -0,0 +1,323 @@
+import { useState } from 'react'
+import {
+ Box,
+ Button,
+ Dialog,
+ DialogContent,
+ IconButton,
+ Stack,
+ Typography,
+} from '@mui/material'
+import { useGraphStore } from '../../store/graphStore'
+import { notifyError, notifyInfo, notifySuccess } from '../../notify'
+import {
+ confirmDiscardIfDirty,
+ deleteWorkflowById,
+ listWorkflows,
+ openWorkflow,
+ type WorkflowRecord,
+} from '../../workflow/workflowActions'
+
+type RecentWorkflowsDialogProps = {
+ open: boolean
+ onClose: () => void
+ disabled?: boolean
+}
+
+const outlineBtnSx = {
+ height: 30,
+ px: 1.25,
+ borderRadius: 1.25,
+ textTransform: 'none',
+ fontWeight: 650,
+ fontSize: 12,
+ color: '#f0ebe3',
+ borderColor: 'rgba(255,255,255,0.16)',
+ '&:hover': {
+ borderColor: 'rgba(125,206,160,0.45)',
+ bgcolor: 'rgba(125,206,160,0.08)',
+ },
+ '&.Mui-disabled': {
+ color: 'rgba(255,255,255,0.3)',
+ borderColor: 'rgba(255,255,255,0.08)',
+ },
+} as const
+
+function formatUpdatedAt(value: string): string {
+ try {
+ return new Intl.DateTimeFormat(undefined, {
+ dateStyle: 'medium',
+ timeStyle: 'short',
+ }).format(new Date(value))
+ } catch {
+ return value
+ }
+}
+
+function WorkflowRow({
+ workflow,
+ active,
+ disabled,
+ onOpen,
+ onDelete,
+}: {
+ workflow: WorkflowRecord
+ active: boolean
+ disabled?: boolean
+ onOpen: () => void
+ onDelete: () => void
+}) {
+ const nodeCount = workflow.graph.nodes.length
+ return (
+ <Box
+ sx={{
+ display: 'flex',
+ alignItems: 'stretch',
+ gap: 1,
+ p: 1.5,
+ borderRadius: 1.75,
+ border: '1px solid',
+ borderColor: active ? 'rgba(125,206,160,0.45)' : 'rgba(255,255,255,0.1)',
+ bgcolor: active ? 'rgba(125,206,160,0.08)' : 'rgba(255,255,255,0.02)',
+ }}
+ >
+ <Box sx={{ flex: 1, minWidth: 0 }}>
+ <Typography
+ sx={{
+ fontFamily: '"Fraunces", Georgia, serif',
+ fontWeight: 700,
+ fontSize: 16,
+ letterSpacing: '-0.02em',
+ color: '#f4f1ea',
+ lineHeight: 1.2,
+ }}
+ >
+ {workflow.name}
+ {active ? (
+ <Box
+ component="span"
+ sx={{
+ ml: 1,
+ fontSize: 11,
+ fontWeight: 700,
+ letterSpacing: '0.06em',
+ textTransform: 'uppercase',
+ color: '#7dcea0',
+ }}
+ >
+ Open
+ </Box>
+ ) : null}
+ </Typography>
+ {workflow.description ? (
+ <Typography
+ sx={{
+ mt: 0.5,
+ fontSize: 12.5,
+ color: 'rgba(244,241,234,0.52)',
+ lineHeight: 1.4,
+ }}
+ >
+ {workflow.description}
+ </Typography>
+ ) : null}
+ <Typography
+ sx={{
+ mt: 0.75,
+ fontSize: 11,
+ color: 'rgba(244,241,234,0.38)',
+ fontVariantNumeric: 'tabular-nums',
+ }}
+ >
+ {nodeCount} node{nodeCount === 1 ? '' : 's'} · Updated {formatUpdatedAt(workflow.updatedAt)}
+ </Typography>
+ </Box>
+ <Stack spacing={0.75} sx={{ justifyContent: 'center' }}>
+ <Button
+ size="small"
+ variant="outlined"
+ disabled={disabled || active}
+ onClick={onOpen}
+ sx={outlineBtnSx}
+ >
+ Open
+ </Button>
+ <Button
+ size="small"
+ variant="outlined"
+ disabled={disabled}
+ onClick={onDelete}
+ sx={{
+ ...outlineBtnSx,
+ color: '#ff8a80',
+ borderColor: 'rgba(255,138,128,0.28)',
+ '&:hover': {
+ borderColor: 'rgba(255,138,128,0.55)',
+ bgcolor: 'rgba(192,57,43,0.12)',
+ },
+ }}
+ >
+ Delete
+ </Button>
+ </Stack>
+ </Box>
+ )
+}
+
+export function RecentWorkflowsDialog({
+ open,
+ onClose,
+ disabled,
+}: RecentWorkflowsDialogProps) {
+ const workflowId = useGraphStore((s) => s.workflowId)
+ const workflowDirty = useGraphStore((s) => s.workflowDirty)
+ const [workflows, setWorkflows] = useState<WorkflowRecord[]>([])
+
+ const refresh = () => setWorkflows(listWorkflows())
+
+ const handleEnter = () => {
+ refresh()
+ }
+
+ const onOpen = (id: string) => {
+ if (id === workflowId && !workflowDirty) {
+ onClose()
+ return
+ }
+ if (!confirmDiscardIfDirty()) return
+ try {
+ const { skippedTypes } = openWorkflow(id)
+ refresh()
+ if (skippedTypes.length > 0) {
+ notifyInfo(`Opened workflow (skipped unknown nodes: ${skippedTypes.join(', ')})`)
+ } else {
+ notifySuccess('Workflow opened')
+ }
+ onClose()
+ } catch (error) {
+ notifyError(error instanceof Error ? error.message : 'Could not open workflow')
+ }
+ }
+
+ const onDelete = (id: string, name: string) => {
+ if (!window.confirm(`Delete “${name}” from recent workflows? This cannot be undone.`)) {
+ return
+ }
+ deleteWorkflowById(id)
+ refresh()
+ notifySuccess('Workflow deleted')
+ }
+
+ return (
+ <Dialog
+ open={open}
+ onClose={onClose}
+ maxWidth="sm"
+ fullWidth
+ slotProps={{
+ transition: {
+ onEnter: handleEnter,
+ },
+ paper: {
+ sx: {
+ bgcolor: '#121212',
+ color: '#f4f1ea',
+ border: '1px solid rgba(255,255,255,0.1)',
+ borderRadius: 2.5,
+ overflow: 'hidden',
+ backgroundImage: `
+ radial-gradient(ellipse 70% 55% at 0% 0%, rgba(125,206,160,0.14), transparent 55%),
+ radial-gradient(ellipse 55% 45% at 100% 0%, rgba(230,126,34,0.1), transparent 50%),
+ linear-gradient(180deg, #161616 0%, #101010 100%)
+ `,
+ },
+ },
+ }}
+ >
+ <Box
+ sx={{
+ display: 'flex',
+ alignItems: 'flex-start',
+ justifyContent: 'space-between',
+ gap: 2,
+ px: 3,
+ pt: 2.5,
+ pb: 1.5,
+ }}
+ >
+ <Box sx={{ minWidth: 0 }}>
+ <Typography
+ sx={{
+ fontFamily: '"Fraunces", Georgia, serif',
+ fontWeight: 700,
+ fontSize: 24,
+ letterSpacing: '-0.03em',
+ lineHeight: 1.15,
+ }}
+ >
+ Recent
+ </Typography>
+ <Typography sx={{ mt: 0.75, fontSize: 13, color: 'rgba(244,241,234,0.5)', maxWidth: 480 }}>
+ Open a workflow saved in this browser.
+ </Typography>
+ </Box>
+ <IconButton
+ aria-label="Close recent workflows"
+ onClick={onClose}
+ size="small"
+ sx={{
+ color: 'rgba(244,241,234,0.55)',
+ border: '1px solid rgba(255,255,255,0.1)',
+ borderRadius: 1.25,
+ '&:hover': { bgcolor: 'rgba(255,255,255,0.06)', color: '#f4f1ea' },
+ }}
+ >
+ ×
+ </IconButton>
+ </Box>
+
+ <DialogContent sx={{ px: 3, pt: 0.5, pb: 3 }}>
+ {workflows.length === 0 ? (
+ <Box
+ sx={{
+ py: 5,
+ textAlign: 'center',
+ border: '1px dashed rgba(255,255,255,0.12)',
+ borderRadius: 2,
+ color: 'rgba(244,241,234,0.45)',
+ }}
+ >
+ <Typography sx={{ fontSize: 14 }}>No saved workflows yet.</Typography>
+ <Typography sx={{ mt: 0.75, fontSize: 12.5, color: 'rgba(244,241,234,0.35)' }}>
+ Use Save or Save as… from the Workflow menu.
+ </Typography>
+ </Box>
+ ) : (
+ <Stack spacing={1.25}>
+ {workflows.map((workflow) => (
+ <WorkflowRow
+ key={workflow.id}
+ workflow={workflow}
+ active={workflow.id === workflowId}
+ disabled={disabled}
+ onOpen={() => onOpen(workflow.id)}
+ onDelete={() => onDelete(workflow.id, workflow.name)}
+ />
+ ))}
+ </Stack>
+ )}
+
+ <Typography
+ sx={{
+ mt: 2,
+ fontSize: 11,
+ color: 'rgba(244,241,234,0.35)',
+ letterSpacing: '0.02em',
+ }}
+ >
+ {workflows.length} workflow{workflows.length === 1 ? '' : 's'} in this browser
+ </Typography>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/frontend/src/features/workflows/WorkflowNameDialog.tsx b/frontend/src/features/workflows/WorkflowNameDialog.tsx
new file mode 100644
index 0000000..cc2838c
--- /dev/null
+++ b/frontend/src/features/workflows/WorkflowNameDialog.tsx
@@ -0,0 +1,154 @@
+import { useState } from 'react'
+import { Box, Button, Dialog, DialogContent, Stack, TextField, Typography } from '@mui/material'
+
+type WorkflowNameDialogProps = {
+ open: boolean
+ title: string
+ confirmLabel: string
+ initialName: string
+ initialDescription?: string
+ onClose: () => void
+ onConfirm: (meta: { name: string; description: string }) => void
+}
+
+const fieldSx = {
+ '& .MuiInputBase-root': {
+ color: '#f0ebe3',
+ bgcolor: '#0f0f0f',
+ borderRadius: 1.25,
+ },
+ '& .MuiInputLabel-root': { color: 'rgba(244,241,234,0.45)' },
+ '& .MuiOutlinedInput-notchedOutline': {
+ borderColor: 'rgba(255,255,255,0.1)',
+ },
+ '& .MuiInputBase-root:hover .MuiOutlinedInput-notchedOutline': {
+ borderColor: 'rgba(255,255,255,0.18)',
+ },
+ '& .MuiInputBase-root.Mui-focused .MuiOutlinedInput-notchedOutline': {
+ borderColor: 'rgba(125,206,160,0.5)',
+ },
+} as const
+
+function WorkflowNameForm({
+ title,
+ confirmLabel,
+ initialName,
+ initialDescription = '',
+ onClose,
+ onConfirm,
+}: Omit<WorkflowNameDialogProps, 'open'>) {
+ const [name, setName] = useState(initialName)
+ const [description, setDescription] = useState(initialDescription)
+
+ const submit = () => {
+ const trimmed = name.trim()
+ if (!trimmed) return
+ onConfirm({ name: trimmed, description: description.trim() })
+ }
+
+ return (
+ <DialogContent sx={{ pt: 2.5, pb: 2.5, px: 2.5 }}>
+ <Typography
+ sx={{
+ mb: 1.75,
+ fontFamily: '"Fraunces", Georgia, serif',
+ fontWeight: 700,
+ fontSize: 20,
+ letterSpacing: '-0.02em',
+ }}
+ >
+ {title}
+ </Typography>
+ <Stack spacing={1.5}>
+ <TextField
+ size="small"
+ label="Name"
+ value={name}
+ autoFocus
+ onChange={(event) => setName(event.target.value)}
+ onKeyDown={(event) => {
+ if (event.key === 'Enter') submit()
+ }}
+ sx={fieldSx}
+ />
+ <TextField
+ size="small"
+ label="Description (optional)"
+ value={description}
+ onChange={(event) => setDescription(event.target.value)}
+ sx={fieldSx}
+ />
+ <Box sx={{ display: 'flex', gap: 1, justifyContent: 'flex-end', pt: 0.5 }}>
+ <Button
+ variant="outlined"
+ onClick={onClose}
+ sx={{
+ textTransform: 'none',
+ fontWeight: 650,
+ color: '#f0ebe3',
+ borderColor: 'rgba(255,255,255,0.16)',
+ }}
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="contained"
+ disabled={!name.trim()}
+ onClick={submit}
+ sx={{
+ textTransform: 'none',
+ fontWeight: 700,
+ bgcolor: '#e67e22',
+ color: '#0f0f0f',
+ '&:hover': { bgcolor: '#f39c12' },
+ }}
+ >
+ {confirmLabel}
+ </Button>
+ </Box>
+ </Stack>
+ </DialogContent>
+ )
+}
+
+export function WorkflowNameDialog({
+ open,
+ title,
+ confirmLabel,
+ initialName,
+ initialDescription = '',
+ onClose,
+ onConfirm,
+}: WorkflowNameDialogProps) {
+ return (
+ <Dialog
+ open={open}
+ onClose={onClose}
+ maxWidth="xs"
+ fullWidth
+ slotProps={{
+ paper: {
+ sx: {
+ bgcolor: '#121212',
+ color: '#f4f1ea',
+ border: '1px solid rgba(255,255,255,0.1)',
+ borderRadius: 2,
+ backgroundImage: 'none',
+ },
+ },
+ }}
+ >
+ {open ? (
+ <WorkflowNameForm
+ key={`${title}:${initialName}:${initialDescription}`}
+ title={title}
+ confirmLabel={confirmLabel}
+ initialName={initialName}
+ initialDescription={initialDescription}
+ onClose={onClose}
+ onConfirm={onConfirm}
+ />
+ ) : null}
+ </Dialog>
+ )
+}
diff --git a/frontend/src/hooks/useWorkflowPersistence.ts b/frontend/src/hooks/useWorkflowPersistence.ts
index ea839f2..431d353 100644
--- a/frontend/src/hooks/useWorkflowPersistence.ts
+++ b/frontend/src/hooks/useWorkflowPersistence.ts
@@ -2,7 +2,7 @@ import { useEffect, useRef, useState } from 'react'
import { useGraphStore } from '../store/graphStore'
import { materializeSampleImages } from '../workflow/materializeSampleImages'
import { loadWorkflowSession, saveWorkflowSession } from '../workflow/persist'
-import { getProject } from '../workflow/projectLibrary'
+import { getWorkflow } from '../workflow/workflowLibrary'
const SAVE_DEBOUNCE_MS = 400
@@ -18,9 +18,9 @@ export function useWorkflowPersistence() {
const edges = useGraphStore((s) => s.edges)
const seed = useGraphStore((s) => s.seed)
const sampleCount = useGraphStore((s) => s.sampleCount)
- const projectId = useGraphStore((s) => s.projectId)
- const projectName = useGraphStore((s) => s.projectName)
- const projectDescription = useGraphStore((s) => s.projectDescription)
+ const workflowId = useGraphStore((s) => s.workflowId)
+ const workflowName = useGraphStore((s) => s.workflowName)
+ const workflowDescription = useGraphStore((s) => s.workflowDescription)
const [sessionReady, setSessionReady] = useState(false)
const restoredRef = useRef(false)
@@ -29,16 +29,16 @@ export function useWorkflowPersistence() {
restoredRef.current = true
const saved = loadWorkflowSession()
if (saved && saved.document.graph.nodes.length > 0) {
- const libraryProject =
- saved.activeProjectId != null ? getProject(saved.activeProjectId) : null
- const doc = libraryProject
+ const libraryWorkflow =
+ saved.activeWorkflowId != null ? getWorkflow(saved.activeWorkflowId) : null
+ const doc = libraryWorkflow
? {
...saved.document,
- id: libraryProject.id,
- name: libraryProject.name,
- description: libraryProject.description,
- createdAt: libraryProject.createdAt,
- updatedAt: libraryProject.updatedAt,
+ id: libraryWorkflow.id,
+ name: libraryWorkflow.name,
+ description: libraryWorkflow.description,
+ createdAt: libraryWorkflow.createdAt,
+ updatedAt: libraryWorkflow.updatedAt,
}
: {
...saved.document,
@@ -66,9 +66,9 @@ export function useWorkflowPersistence() {
edges,
seed,
sampleCount,
- projectId,
- projectName,
- projectDescription,
+ workflowId,
+ workflowName,
+ workflowDescription,
toWorkflowDocument,
])
diff --git a/frontend/src/store/graphStore.ts b/frontend/src/store/graphStore.ts
index 064ec4b..401c254 100644
--- a/frontend/src/store/graphStore.ts
+++ b/frontend/src/store/graphStore.ts
@@ -11,7 +11,7 @@ import {
import { create } from 'zustand'
import type { ExecutionPreview, GraphNodeData, NodeMetadata } from '../types'
import {
- DEFAULT_PROJECT_NAME,
+ DEFAULT_WORKFLOW_NAME,
type WorkflowDocument,
type WorkflowGraphPayload,
} from '../workflow/io'
@@ -58,12 +58,12 @@ interface GraphState {
sampleCount: number
/** Bumped on loadWorkflow so the canvas can refit the viewport. */
graphRevision: number
- projectId: string | null
- projectName: string
- projectDescription: string
- projectCreatedAt: string | null
- projectUpdatedAt: string | null
- projectDirty: boolean
+ workflowId: string | null
+ workflowName: string
+ workflowDescription: string
+ workflowCreatedAt: string | null
+ workflowUpdatedAt: string | null
+ workflowDirty: boolean
setNodeCatalog: (catalog: NodeMetadata[]) => void
onNodesChange: (changes: NodeChange<PipelineNode>[]) => void
onEdgesChange: (changes: EdgeChange[]) => void
@@ -90,16 +90,16 @@ interface GraphState {
setIsExecuting: (value: boolean) => void
setSeed: (seed: number) => void
setSampleCount: (count: number) => void
- setProjectMeta: (meta: { name?: string; description?: string }) => void
- markProjectDirty: () => void
- markProjectClean: (record?: {
+ setWorkflowMeta: (meta: { name?: string; description?: string }) => void
+ markworkflowDirty: () => void
+ markWorkflowClean: (record?: {
id: string
name: string
description?: string
createdAt?: string
updatedAt?: string
}) => void
- newProject: () => void
+ newWorkflow: () => void
getInputImages: (nodeId: string) => string[]
getResultImages: (nodeId: string) => string[]
toGraphPayload: () => WorkflowGraphPayload
@@ -167,12 +167,12 @@ export const useGraphStore = create<GraphState>((set, get) => ({
seed: 0,
sampleCount: 1,
graphRevision: 0,
- projectId: null,
- projectName: DEFAULT_PROJECT_NAME,
- projectDescription: '',
- projectCreatedAt: null,
- projectUpdatedAt: null,
- projectDirty: false,
+ workflowId: null,
+ workflowName: DEFAULT_WORKFLOW_NAME,
+ workflowDescription: '',
+ workflowCreatedAt: null,
+ workflowUpdatedAt: null,
+ workflowDirty: false,
setNodeCatalog: (catalog) => set({ nodeCatalog: catalog }),
@@ -186,7 +186,7 @@ export const useGraphStore = create<GraphState>((set, get) => ({
set((state) => {
const nodes = applyNodeChanges(changes, state.nodes)
- const dirtyPatch = structural && !state.projectDirty ? { projectDirty: true } : {}
+ const dirtyPatch = structural && !state.workflowDirty ? { workflowDirty: true } : {}
if (removedIds.length === 0) {
return { nodes, ...dirtyPatch }
}
@@ -221,7 +221,7 @@ export const useGraphStore = create<GraphState>((set, get) => ({
)
set((state) => ({
edges: applyEdgeChanges(changes, state.edges),
- ...(structural ? { projectDirty: true } : {}),
+ ...(structural ? { workflowDirty: true } : {}),
}))
},
@@ -248,7 +248,7 @@ export const useGraphStore = create<GraphState>((set, get) => ({
},
get().edges,
),
- projectDirty: true,
+ workflowDirty: true,
})
},
@@ -269,7 +269,7 @@ export const useGraphStore = create<GraphState>((set, get) => ({
selectable: true,
data: oldEdge.data ?? { waypoints: [] },
})
- set({ edges: next, projectDirty: true })
+ set({ edges: next, workflowDirty: true })
},
setEdgeWaypoints: (edgeId, waypoints) =>
@@ -285,7 +285,7 @@ export const useGraphStore = create<GraphState>((set, get) => ({
}
: edge,
),
- projectDirty: true,
+ workflowDirty: true,
}),
addNodeFromType: (meta, position) => {
@@ -304,7 +304,7 @@ export const useGraphStore = create<GraphState>((set, get) => ({
localPreviewUrls: [],
},
}
- set({ nodes: [...get().nodes, node], selectedNodeId: id, projectDirty: true })
+ set({ nodes: [...get().nodes, node], selectedNodeId: id, workflowDirty: true })
},
removeNode: (nodeId) => {
@@ -334,7 +334,7 @@ export const useGraphStore = create<GraphState>((set, get) => ({
set({
nodes: [...get().nodes.map((node) => ({ ...node, selected: false })), copy],
selectedNodeId: id,
- projectDirty: true,
+ workflowDirty: true,
})
},
@@ -347,7 +347,7 @@ export const useGraphStore = create<GraphState>((set, get) => ({
? { ...node, data: { ...node.data, params: { ...node.data.params, ...params } } }
: node,
),
- projectDirty: true,
+ workflowDirty: true,
}),
setLocalPreview: (nodeId, dataUrl) =>
@@ -364,7 +364,7 @@ export const useGraphStore = create<GraphState>((set, get) => ({
}
: node,
),
- projectDirty: true,
+ workflowDirty: true,
}),
setLocalPreviews: (nodeId, dataUrls, uploadedFiles = []) =>
@@ -381,7 +381,7 @@ export const useGraphStore = create<GraphState>((set, get) => ({
}
: node,
),
- projectDirty: true,
+ workflowDirty: true,
}),
removeLocalPreview: (nodeId, index) => {
@@ -420,7 +420,7 @@ export const useGraphStore = create<GraphState>((set, get) => ({
: item,
),
sampleCount: Math.max(1, previews.length),
- projectDirty: true,
+ workflowDirty: true,
})
return { file: removedFile, path: nextPath }
},
@@ -504,36 +504,36 @@ export const useGraphStore = create<GraphState>((set, get) => ({
}),
setGeneratedCode: (code) => set({ generatedCode: code }),
setIsExecuting: (value) => set({ isExecuting: value }),
- setSeed: (seed) => set({ seed, projectDirty: true }),
- setSampleCount: (count) => set({ sampleCount: Math.max(1, count), projectDirty: true }),
+ setSeed: (seed) => set({ seed, workflowDirty: true }),
+ setSampleCount: (count) => set({ sampleCount: Math.max(1, count), workflowDirty: true }),
- setProjectMeta: (meta) =>
+ setWorkflowMeta: (meta) =>
set((state) => ({
- projectName:
+ workflowName:
meta.name !== undefined
- ? meta.name.trim() || DEFAULT_PROJECT_NAME
- : state.projectName,
- projectDescription:
- meta.description !== undefined ? meta.description : state.projectDescription,
- projectDirty: true,
+ ? meta.name.trim() || DEFAULT_WORKFLOW_NAME
+ : state.workflowName,
+ workflowDescription:
+ meta.description !== undefined ? meta.description : state.workflowDescription,
+ workflowDirty: true,
})),
- markProjectDirty: () => set({ projectDirty: true }),
+ markworkflowDirty: () => set({ workflowDirty: true }),
- markProjectClean: (record) =>
+ markWorkflowClean: (record) =>
set((state) => ({
- projectDirty: false,
- projectId: record?.id ?? state.projectId,
- projectName: record?.name ?? state.projectName,
- projectDescription:
+ workflowDirty: false,
+ workflowId: record?.id ?? state.workflowId,
+ workflowName: record?.name ?? state.workflowName,
+ workflowDescription:
record?.description !== undefined
? record.description
- : state.projectDescription,
- projectCreatedAt: record?.createdAt ?? state.projectCreatedAt,
- projectUpdatedAt: record?.updatedAt ?? state.projectUpdatedAt,
+ : state.workflowDescription,
+ workflowCreatedAt: record?.createdAt ?? state.workflowCreatedAt,
+ workflowUpdatedAt: record?.updatedAt ?? state.workflowUpdatedAt,
})),
- newProject: () => {
+ newWorkflow: () => {
nodeCounter = 1
set({
nodes: [],
@@ -549,12 +549,12 @@ export const useGraphStore = create<GraphState>((set, get) => ({
seed: 0,
sampleCount: 1,
graphRevision: get().graphRevision + 1,
- projectId: null,
- projectName: DEFAULT_PROJECT_NAME,
- projectDescription: '',
- projectCreatedAt: null,
- projectUpdatedAt: null,
- projectDirty: false,
+ workflowId: null,
+ workflowName: DEFAULT_WORKFLOW_NAME,
+ workflowDescription: '',
+ workflowCreatedAt: null,
+ workflowUpdatedAt: null,
+ workflowDirty: false,
})
},
@@ -622,19 +622,19 @@ export const useGraphStore = create<GraphState>((set, get) => ({
const {
seed,
sampleCount,
- projectId,
- projectName,
- projectDescription,
- projectCreatedAt,
- projectUpdatedAt,
+ workflowId,
+ workflowName,
+ workflowDescription,
+ workflowCreatedAt,
+ workflowUpdatedAt,
} = get()
return {
version: 1 as const,
- ...(projectId ? { id: projectId } : {}),
- name: projectName || DEFAULT_PROJECT_NAME,
- ...(projectDescription.trim() ? { description: projectDescription.trim() } : {}),
- ...(projectCreatedAt ? { createdAt: projectCreatedAt } : {}),
- ...(projectUpdatedAt ? { updatedAt: projectUpdatedAt } : {}),
+ ...(workflowId ? { id: workflowId } : {}),
+ name: workflowName || DEFAULT_WORKFLOW_NAME,
+ ...(workflowDescription.trim() ? { description: workflowDescription.trim() } : {}),
+ ...(workflowCreatedAt ? { createdAt: workflowCreatedAt } : {}),
+ ...(workflowUpdatedAt ? { updatedAt: workflowUpdatedAt } : {}),
seed,
sampleCount,
graph: get().toGraphPayload(),
@@ -713,12 +713,12 @@ export const useGraphStore = create<GraphState>((set, get) => ({
seed: doc.seed,
sampleCount: Math.max(1, doc.sampleCount),
graphRevision: get().graphRevision + 1,
- projectId: doc.id ?? null,
- projectName: doc.name || DEFAULT_PROJECT_NAME,
- projectDescription: doc.description ?? '',
- projectCreatedAt: doc.createdAt ?? null,
- projectUpdatedAt: doc.updatedAt ?? null,
- projectDirty: false,
+ workflowId: doc.id ?? null,
+ workflowName: doc.name || DEFAULT_WORKFLOW_NAME,
+ workflowDescription: doc.description ?? '',
+ workflowCreatedAt: doc.createdAt ?? null,
+ workflowUpdatedAt: doc.updatedAt ?? null,
+ workflowDirty: false,
})
return { skippedTypes: [...skipped].sort() }
diff --git a/frontend/src/workflow/io.ts b/frontend/src/workflow/io.ts
index a6cac9c..d8cc5b8 100644
--- a/frontend/src/workflow/io.ts
+++ b/frontend/src/workflow/io.ts
@@ -1,6 +1,6 @@
/** Versioned workflow JSON for export / load. */
-export const DEFAULT_PROJECT_NAME = 'Untitled'
+export const DEFAULT_WORKFLOW_NAME = 'Untitled'
export interface WorkflowWaypoint {
x: number
@@ -128,7 +128,7 @@ export function coerceWorkflowDocument(value: unknown): WorkflowDocument {
)
}
- const name = readOptionalString(value.name) ?? DEFAULT_PROJECT_NAME
+ const name = readOptionalString(value.name) ?? DEFAULT_WORKFLOW_NAME
const description = readOptionalString(value.description)
const id = readOptionalString(value.id)
const createdAt = readOptionalString(value.createdAt)
@@ -166,7 +166,7 @@ export function parseWorkflowJson(text: string): WorkflowDocument {
return coerceWorkflowDocument(parsed)
}
-/** Sanitize a project name into a safe download filename stem. */
+/** Sanitize a workflow name into a safe download filename stem. */
export function workflowFilename(name: string, fallback = 'workflow'): string {
const stem = name
.trim()
diff --git a/frontend/src/workflow/persist.ts b/frontend/src/workflow/persist.ts
index 4e854a5..063f4f9 100644
--- a/frontend/src/workflow/persist.ts
+++ b/frontend/src/workflow/persist.ts
@@ -8,7 +8,7 @@ import {
export const WORKFLOW_SESSION_KEY = 'image-pipes.workflow.v1'
export interface WorkflowSession {
- activeProjectId: string | null
+ activeWorkflowId: string | null
document: WorkflowDocument
}
@@ -22,14 +22,16 @@ function readOptionalString(value: unknown): string | null {
return trimmed.length > 0 ? trimmed : null
}
-/** Accept the new session envelope or a legacy bare WorkflowDocument. */
+/** Accept the session envelope or a legacy bare WorkflowDocument. */
export function coerceWorkflowSession(value: unknown): WorkflowSession | null {
if (!isRecord(value)) return null
if (isRecord(value.document)) {
try {
return {
- activeProjectId: readOptionalString(value.activeProjectId),
+ activeWorkflowId:
+ readOptionalString(value.activeWorkflowId) ??
+ readOptionalString(value.activeProjectId),
document: coerceWorkflowDocument(value.document),
}
} catch {
@@ -39,7 +41,7 @@ export function coerceWorkflowSession(value: unknown): WorkflowSession | null {
try {
return {
- activeProjectId: null,
+ activeWorkflowId: null,
document: coerceWorkflowDocument(value),
}
} catch {
@@ -49,11 +51,11 @@ export function coerceWorkflowSession(value: unknown): WorkflowSession | null {
export function saveWorkflowSession(
doc: WorkflowDocument,
- activeProjectId: string | null = doc.id ?? null,
+ activeWorkflowId: string | null = doc.id ?? null,
): void {
try {
const session: WorkflowSession = {
- activeProjectId,
+ activeWorkflowId,
document: doc,
}
localStorage.setItem(WORKFLOW_SESSION_KEY, JSON.stringify(session))
diff --git a/frontend/src/workflow/projectActions.ts b/frontend/src/workflow/projectActions.ts
deleted file mode 100644
index 7d10906..0000000
--- a/frontend/src/workflow/projectActions.ts
+++ /dev/null
@@ -1,127 +0,0 @@
-/** Project library orchestration used by the Projects UI. */
-
-import { useGraphStore } from '../store/graphStore'
-import { DEFAULT_PROJECT_NAME, type WorkflowDocument } from './io'
-import { saveWorkflowSession } from './persist'
-import {
- createProjectId,
- deleteProject as deleteLibraryProject,
- getProject,
- listProjects,
- type ProjectRecord,
- renameProject as renameLibraryProject,
- upsertProject,
-} from './projectLibrary'
-
-export function confirmDiscardIfDirty(message?: string): boolean {
- const dirty = useGraphStore.getState().projectDirty
- if (!dirty) return true
- return window.confirm(
- message ?? 'You have unsaved changes. Discard them and continue?',
- )
-}
-
-export function flushSession(): void {
- const doc = useGraphStore.getState().toWorkflowDocument()
- saveWorkflowSession(doc, doc.id ?? null)
-}
-
-export function openProject(id: string): { skippedTypes: string[] } {
- const record = getProject(id)
- if (!record) {
- throw new Error('Project not found')
- }
- const result = useGraphStore.getState().loadWorkflow(record)
- flushSession()
- return result
-}
-
-export function newProject(): void {
- useGraphStore.getState().newProject()
- flushSession()
-}
-
-export function saveProject(): ProjectRecord {
- const state = useGraphStore.getState()
- if (!state.projectId) {
- throw new Error('No saved project — use Save As')
- }
- const record = upsertProject(state.toWorkflowDocument())
- state.markProjectClean(record)
- flushSession()
- return record
-}
-
-export function saveProjectAs(meta: {
- name: string
- description?: string
-}): ProjectRecord {
- const state = useGraphStore.getState()
- const name = meta.name.trim() || DEFAULT_PROJECT_NAME
- const description = meta.description?.trim() || undefined
- const record = upsertProject({
- ...state.toWorkflowDocument(),
- id: createProjectId(),
- name,
- ...(description ? { description } : { description: undefined }),
- createdAt: undefined,
- updatedAt: undefined,
- })
- state.markProjectClean(record)
- flushSession()
- return record
-}
-
-export function renameActiveProject(meta: {
- name: string
- description?: string
-}): ProjectRecord | null {
- const state = useGraphStore.getState()
- const name = meta.name.trim() || DEFAULT_PROJECT_NAME
- const description = meta.description?.trim() || undefined
- if (!state.projectId) {
- state.setProjectMeta({ name, description: description ?? '' })
- return null
- }
- const record = renameLibraryProject(state.projectId, { name, description })
- if (record) {
- state.markProjectClean(record)
- flushSession()
- } else {
- state.setProjectMeta({ name, description: description ?? '' })
- }
- return record
-}
-
-export function deleteProjectById(id: string): void {
- deleteLibraryProject(id)
- const state = useGraphStore.getState()
- if (state.projectId === id) {
- // Detach from library without clearing the canvas.
- useGraphStore.setState({
- projectId: null,
- projectCreatedAt: null,
- projectUpdatedAt: null,
- projectDirty: true,
- })
- flushSession()
- }
-}
-
-/** Load a document that is not yet a library entry (file / template). */
-export function loadExternalDocument(
- doc: WorkflowDocument,
- overrides?: { name?: string },
-): { skippedTypes: string[] } {
- const { id: _id, ...withoutId } = doc
- void _id
- const result = useGraphStore.getState().loadWorkflow({
- ...withoutId,
- name: overrides?.name?.trim() || doc.name || DEFAULT_PROJECT_NAME,
- })
- flushSession()
- return result
-}
-
-export { listProjects, getProject }
-export type { ProjectRecord }
diff --git a/frontend/src/workflow/projectLibrary.ts b/frontend/src/workflow/projectLibrary.ts
deleted file mode 100644
index eadd4a0..0000000
--- a/frontend/src/workflow/projectLibrary.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-/** Local multi-project library backed by localStorage. */
-
-import {
- coerceWorkflowDocument,
- DEFAULT_PROJECT_NAME,
- type WorkflowDocument,
-} from './io'
-
-export const PROJECTS_LIBRARY_KEY = 'image-pipes.projects.v1'
-
-export type ProjectRecord = WorkflowDocument & {
- id: string
- createdAt: string
- updatedAt: string
-}
-
-interface ProjectLibraryStore {
- version: 1
- projects: ProjectRecord[]
-}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
-}
-
-export function createProjectId(): string {
- if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
- return crypto.randomUUID()
- }
- return `proj-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
-}
-
-function emptyLibrary(): ProjectLibraryStore {
- return { version: 1, projects: [] }
-}
-
-function readLibrary(): ProjectLibraryStore {
- try {
- const raw = localStorage.getItem(PROJECTS_LIBRARY_KEY)
- if (!raw) return emptyLibrary()
- const parsed = JSON.parse(raw) as unknown
- if (!isRecord(parsed) || parsed.version !== 1 || !Array.isArray(parsed.projects)) {
- return emptyLibrary()
- }
- const projects: ProjectRecord[] = []
- for (const entry of parsed.projects) {
- try {
- const doc = coerceWorkflowDocument(entry)
- if (!doc.id) continue
- const now = new Date().toISOString()
- projects.push({
- ...doc,
- id: doc.id,
- name: doc.name || DEFAULT_PROJECT_NAME,
- createdAt: doc.createdAt ?? now,
- updatedAt: doc.updatedAt ?? now,
- })
- } catch {
- // Skip corrupt entries.
- }
- }
- return { version: 1, projects }
- } catch {
- return emptyLibrary()
- }
-}
-
-function writeLibrary(store: ProjectLibraryStore): void {
- try {
- localStorage.setItem(PROJECTS_LIBRARY_KEY, JSON.stringify(store))
- } catch {
- // Quota or private mode — ignore; export still works.
- }
-}
-
-export function listProjects(): ProjectRecord[] {
- return [...readLibrary().projects].sort((a, b) =>
- b.updatedAt.localeCompare(a.updatedAt),
- )
-}
-
-export function getProject(id: string): ProjectRecord | null {
- return readLibrary().projects.find((project) => project.id === id) ?? null
-}
-
-export function upsertProject(doc: WorkflowDocument): ProjectRecord {
- const now = new Date().toISOString()
- const id = doc.id?.trim() || createProjectId()
- const store = readLibrary()
- const existing = store.projects.find((project) => project.id === id)
- const record: ProjectRecord = {
- ...doc,
- id,
- name: doc.name.trim() || DEFAULT_PROJECT_NAME,
- createdAt: existing?.createdAt ?? doc.createdAt ?? now,
- updatedAt: now,
- }
- const next = store.projects.filter((project) => project.id !== id)
- next.push(record)
- writeLibrary({ version: 1, projects: next })
- return record
-}
-
-export function deleteProject(id: string): boolean {
- const store = readLibrary()
- const next = store.projects.filter((project) => project.id !== id)
- if (next.length === store.projects.length) return false
- writeLibrary({ version: 1, projects: next })
- return true
-}
-
-export function renameProject(
- id: string,
- meta: { name: string; description?: string },
-): ProjectRecord | null {
- const existing = getProject(id)
- if (!existing) return null
- return upsertProject({
- ...existing,
- name: meta.name.trim() || DEFAULT_PROJECT_NAME,
- description: meta.description?.trim() || undefined,
- })
-}
diff --git a/frontend/src/workflow/workflowActions.ts b/frontend/src/workflow/workflowActions.ts
new file mode 100644
index 0000000..11ed265
--- /dev/null
+++ b/frontend/src/workflow/workflowActions.ts
@@ -0,0 +1,127 @@
+/** Workflow library orchestration used by the Workflows UI. */
+
+import { useGraphStore } from '../store/graphStore'
+import { DEFAULT_WORKFLOW_NAME, type WorkflowDocument } from './io'
+import { saveWorkflowSession } from './persist'
+import {
+ createWorkflowId,
+ deleteWorkflow as deleteLibraryWorkflow,
+ getWorkflow,
+ listWorkflows,
+ type WorkflowRecord,
+ renameWorkflow as renameLibraryWorkflow,
+ upsertWorkflow,
+} from './workflowLibrary'
+
+export function confirmDiscardIfDirty(message?: string): boolean {
+ const dirty = useGraphStore.getState().workflowDirty
+ if (!dirty) return true
+ return window.confirm(
+ message ?? 'You have unsaved changes. Discard them and continue?',
+ )
+}
+
+export function flushSession(): void {
+ const doc = useGraphStore.getState().toWorkflowDocument()
+ saveWorkflowSession(doc, doc.id ?? null)
+}
+
+export function openWorkflow(id: string): { skippedTypes: string[] } {
+ const record = getWorkflow(id)
+ if (!record) {
+ throw new Error('Workflow not found')
+ }
+ const result = useGraphStore.getState().loadWorkflow(record)
+ flushSession()
+ return result
+}
+
+export function newWorkflow(): void {
+ useGraphStore.getState().newWorkflow()
+ flushSession()
+}
+
+export function saveWorkflow(): WorkflowRecord {
+ const state = useGraphStore.getState()
+ if (!state.workflowId) {
+ throw new Error('No saved workflow — use Save As')
+ }
+ const record = upsertWorkflow(state.toWorkflowDocument())
+ state.markWorkflowClean(record)
+ flushSession()
+ return record
+}
+
+export function saveWorkflowAs(meta: {
+ name: string
+ description?: string
+}): WorkflowRecord {
+ const state = useGraphStore.getState()
+ const name = meta.name.trim() || DEFAULT_WORKFLOW_NAME
+ const description = meta.description?.trim() || undefined
+ const record = upsertWorkflow({
+ ...state.toWorkflowDocument(),
+ id: createWorkflowId(),
+ name,
+ ...(description ? { description } : { description: undefined }),
+ createdAt: undefined,
+ updatedAt: undefined,
+ })
+ state.markWorkflowClean(record)
+ flushSession()
+ return record
+}
+
+export function renameActiveWorkflow(meta: {
+ name: string
+ description?: string
+}): WorkflowRecord | null {
+ const state = useGraphStore.getState()
+ const name = meta.name.trim() || DEFAULT_WORKFLOW_NAME
+ const description = meta.description?.trim() || undefined
+ if (!state.workflowId) {
+ state.setWorkflowMeta({ name, description: description ?? '' })
+ return null
+ }
+ const record = renameLibraryWorkflow(state.workflowId, { name, description })
+ if (record) {
+ state.markWorkflowClean(record)
+ flushSession()
+ } else {
+ state.setWorkflowMeta({ name, description: description ?? '' })
+ }
+ return record
+}
+
+export function deleteWorkflowById(id: string): void {
+ deleteLibraryWorkflow(id)
+ const state = useGraphStore.getState()
+ if (state.workflowId === id) {
+ // Detach from library without clearing the canvas.
+ useGraphStore.setState({
+ workflowId: null,
+ workflowCreatedAt: null,
+ workflowUpdatedAt: null,
+ workflowDirty: true,
+ })
+ flushSession()
+ }
+}
+
+/** Load a document that is not yet a library entry (file / template). */
+export function loadExternalDocument(
+ doc: WorkflowDocument,
+ overrides?: { name?: string },
+): { skippedTypes: string[] } {
+ const { id: _id, ...withoutId } = doc
+ void _id
+ const result = useGraphStore.getState().loadWorkflow({
+ ...withoutId,
+ name: overrides?.name?.trim() || doc.name || DEFAULT_WORKFLOW_NAME,
+ })
+ flushSession()
+ return result
+}
+
+export { listWorkflows, getWorkflow }
+export type { WorkflowRecord }
diff --git a/frontend/src/workflow/workflowLibrary.ts b/frontend/src/workflow/workflowLibrary.ts
new file mode 100644
index 0000000..6e3489b
--- /dev/null
+++ b/frontend/src/workflow/workflowLibrary.ts
@@ -0,0 +1,138 @@
+/** Local multi-workflow library backed by localStorage. */
+
+import {
+ coerceWorkflowDocument,
+ DEFAULT_WORKFLOW_NAME,
+ type WorkflowDocument,
+} from './io'
+
+export const WORKFLOWS_LIBRARY_KEY = 'image-pipes.workflows.v1'
+/** @deprecated Previous key; still read for migration. */
+const LEGACY_PROJECTS_LIBRARY_KEY = 'image-pipes.projects.v1'
+
+export type WorkflowRecord = WorkflowDocument & {
+ id: string
+ createdAt: string
+ updatedAt: string
+}
+
+interface WorkflowLibraryStore {
+ version: 1
+ workflows: WorkflowRecord[]
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value)
+}
+
+export function createWorkflowId(): string {
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
+ return crypto.randomUUID()
+ }
+ return `wf-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`
+}
+
+function emptyLibrary(): WorkflowLibraryStore {
+ return { version: 1, workflows: [] }
+}
+
+function parseLibraryEntries(entries: unknown[]): WorkflowRecord[] {
+ const workflows: WorkflowRecord[] = []
+ for (const entry of entries) {
+ try {
+ const doc = coerceWorkflowDocument(entry)
+ if (!doc.id) continue
+ const now = new Date().toISOString()
+ workflows.push({
+ ...doc,
+ id: doc.id,
+ name: doc.name || DEFAULT_WORKFLOW_NAME,
+ createdAt: doc.createdAt ?? now,
+ updatedAt: doc.updatedAt ?? now,
+ })
+ } catch {
+ // Skip corrupt entries.
+ }
+ }
+ return workflows
+}
+
+function readLibrary(): WorkflowLibraryStore {
+ try {
+ const raw =
+ localStorage.getItem(WORKFLOWS_LIBRARY_KEY) ??
+ localStorage.getItem(LEGACY_PROJECTS_LIBRARY_KEY)
+ if (!raw) return emptyLibrary()
+ const parsed = JSON.parse(raw) as unknown
+ if (!isRecord(parsed) || parsed.version !== 1) {
+ return emptyLibrary()
+ }
+ const entries = Array.isArray(parsed.workflows)
+ ? parsed.workflows
+ : Array.isArray(parsed.projects)
+ ? parsed.projects
+ : null
+ if (!entries) return emptyLibrary()
+ return { version: 1, workflows: parseLibraryEntries(entries) }
+ } catch {
+ return emptyLibrary()
+ }
+}
+
+function writeLibrary(store: WorkflowLibraryStore): void {
+ try {
+ localStorage.setItem(WORKFLOWS_LIBRARY_KEY, JSON.stringify(store))
+ localStorage.removeItem(LEGACY_PROJECTS_LIBRARY_KEY)
+ } catch {
+ // Quota or private mode — ignore; export still works.
+ }
+}
+
+export function listWorkflows(): WorkflowRecord[] {
+ return [...readLibrary().workflows].sort((a, b) =>
+ b.updatedAt.localeCompare(a.updatedAt),
+ )
+}
+
+export function getWorkflow(id: string): WorkflowRecord | null {
+ return readLibrary().workflows.find((workflow) => workflow.id === id) ?? null
+}
+
+export function upsertWorkflow(doc: WorkflowDocument): WorkflowRecord {
+ const now = new Date().toISOString()
+ const id = doc.id?.trim() || createWorkflowId()
+ const store = readLibrary()
+ const existing = store.workflows.find((workflow) => workflow.id === id)
+ const record: WorkflowRecord = {
+ ...doc,
+ id,
+ name: doc.name.trim() || DEFAULT_WORKFLOW_NAME,
+ createdAt: existing?.createdAt ?? doc.createdAt ?? now,
+ updatedAt: now,
+ }
+ const next = store.workflows.filter((workflow) => workflow.id !== id)
+ next.push(record)
+ writeLibrary({ version: 1, workflows: next })
+ return record
+}
+
+export function deleteWorkflow(id: string): boolean {
+ const store = readLibrary()
+ const next = store.workflows.filter((workflow) => workflow.id !== id)
+ if (next.length === store.workflows.length) return false
+ writeLibrary({ version: 1, workflows: next })
+ return true
+}
+
+export function renameWorkflow(
+ id: string,
+ meta: { name: string; description?: string },
+): WorkflowRecord | null {
+ const existing = getWorkflow(id)
+ if (!existing) return null
+ return upsertWorkflow({
+ ...existing,
+ name: meta.name.trim() || DEFAULT_WORKFLOW_NAME,
+ description: meta.description?.trim() || undefined,
+ })
+}