Image Pipeline Playground
feat(frontend): add user script management and integration into the UI
Mohammad Rajaei6ba980480120
diff --git a/frontend/src/api/userScripts.ts b/frontend/src/api/userScripts.tsnew file mode 100644index 0000000..223fed3--- /dev/null+++ b/frontend/src/api/userScripts.ts@@ -0,0 +1,66 @@+/** Client for versioned reusable user scripts. */++export type UserScriptMeta = {+ id: string+ name: string+ current_version: number+ created_at: string+ updated_at: string+ node_type: string+}++export type UserScriptCode = {+ id: string+ version: number+ code: string+}++async function readError(response: Response): Promise<string> {+ try {+ const body = (await response.json()) as { detail?: unknown }+ if (typeof body.detail === 'string') return body.detail+ return JSON.stringify(body.detail ?? body)+ } catch {+ return response.statusText || 'Request failed'+ }+}++export async function listUserScripts(): Promise<UserScriptMeta[]> {+ const response = await fetch('/api/user-scripts')+ if (!response.ok) throw new Error(await readError(response))+ return response.json()+}++export async function createUserScript(name: string, code: string): Promise<UserScriptMeta> {+ const response = await fetch('/api/user-scripts', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name, code }),+ })+ if (!response.ok) throw new Error(await readError(response))+ return response.json()+}++export async function createUserScriptVersion(+ scriptId: string,+ code: string,+): Promise<UserScriptMeta> {+ const response = await fetch(`/api/user-scripts/${encodeURIComponent(scriptId)}/versions`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ code }),+ })+ if (!response.ok) throw new Error(await readError(response))+ return response.json()+}++export async function getUserScriptCode(+ scriptId: string,+ version: number,+): Promise<UserScriptCode> {+ const response = await fetch(+ `/api/user-scripts/${encodeURIComponent(scriptId)}/versions/${version}`,+ )+ if (!response.ok) throw new Error(await readError(response))+ return response.json()+}diff --git a/frontend/src/features/canvas/NodeMenu.tsx b/frontend/src/features/canvas/NodeMenu.tsxindex b6e741f..8c9127b 100644--- a/frontend/src/features/canvas/NodeMenu.tsx+++ b/frontend/src/features/canvas/NodeMenu.tsx@@ -266,7 +266,7 @@ export function useNodeMenu({lineHeight: 1.2,}}>- {category}+ {category === 'user_scripts' ? 'My Scripts' : category}</Typography><Typographysx={{diff --git a/frontend/src/features/canvas/PipelineCanvas.tsx b/frontend/src/features/canvas/PipelineCanvas.tsxindex b922041..5c64638 100644--- a/frontend/src/features/canvas/PipelineCanvas.tsx+++ b/frontend/src/features/canvas/PipelineCanvas.tsx@@ -18,6 +18,8 @@ import { PipelineNodeView } from './PipelineNode'import { EditableEdge } from './EditableEdge'import type { NodeMetadata, PortSpec } from '../../types'import { portsCompatible } from '../../lib/portTypes'+import { isUserScriptType } from '../../workflow/customCodeTrust'+import { hydrateUserScriptCodes } from '../../workflow/hydrateUserScriptCodes'function FitViewOnGraphChange() {const { fitView } = useReactFlow()@@ -74,6 +76,9 @@ export function PipelineCanvas() {y: event.clientY - (bounds?.top ?? 0) - 20,}addNodeFromType(meta, position)+ if (isUserScriptType(meta.type)) {+ void hydrateUserScriptCodes({ autoTrust: true })+ }},[addNodeFromType],)diff --git a/frontend/src/features/execution/CustomCodeTrustBanner.tsx b/frontend/src/features/execution/CustomCodeTrustBanner.tsxindex b08982b..4fb73c9 100644--- a/frontend/src/features/execution/CustomCodeTrustBanner.tsx+++ b/frontend/src/features/execution/CustomCodeTrustBanner.tsx@@ -1,14 +1,15 @@import { Box, Button, Typography } from '@mui/material'import { useGraphStore } from '../../store/graphStore'-import { isCustomCodeTrusted } from '../../workflow/customCodeTrust'+import { graphHasCustomCode, isCustomCodeTrusted } from '../../workflow/customCodeTrust'export function CustomCodeTrustBanner() {const nodes = useGraphStore((s) => s.nodes)const trustedCustomCodeHash = useGraphStore((s) => s.trustedCustomCodeHash)+ const userScriptCodes = useGraphStore((s) => s.userScriptCodes)const openCustomCodeTrustDialog = useGraphStore((s) => s.openCustomCodeTrustDialog)- const trusted = isCustomCodeTrusted(nodes, trustedCustomCodeHash)- const hasCustom = nodes.some((node) => node.data.type === 'custom_python')+ const trusted = isCustomCodeTrusted(nodes, trustedCustomCodeHash, userScriptCodes)+ const hasCustom = graphHasCustomCode(nodes)if (!hasCustom || trusted) return nulldiff --git a/frontend/src/features/execution/CustomCodeTrustDialog.tsx b/frontend/src/features/execution/CustomCodeTrustDialog.tsxindex 1b6e99e..c234a90 100644--- a/frontend/src/features/execution/CustomCodeTrustDialog.tsx+++ b/frontend/src/features/execution/CustomCodeTrustDialog.tsx@@ -6,22 +6,31 @@ import {Stack,Typography,} from '@mui/material'+import { useEffect } from 'react'import { useGraphStore } from '../../store/graphStore'import {- listCustomPythonNodes,+ listCustomCodeNodes,+ resolveCustomCodePreview,truncateCodePreview,} from '../../workflow/customCodeTrust'+import { hydrateUserScriptCodes } from '../../workflow/hydrateUserScriptCodes'import { runPipeline } from '../../hooks/useExecutionSocket'export function CustomCodeTrustDialog() {const open = useGraphStore((s) => s.customCodeTrustDialogOpen)const nodes = useGraphStore((s) => s.nodes)+ const userScriptCodes = useGraphStore((s) => s.userScriptCodes)const pendingRunOptions = useGraphStore((s) => s.pendingRunOptions)const pendingRunAfterTrust = useGraphStore((s) => s.pendingRunAfterTrust)const trustCustomCode = useGraphStore((s) => s.trustCustomCode)const closeCustomCodeTrustDialog = useGraphStore((s) => s.closeCustomCodeTrustDialog)- const customNodes = listCustomPythonNodes(nodes)+ const customNodes = listCustomCodeNodes(nodes)++ useEffect(() => {+ if (!open) return+ void hydrateUserScriptCodes()+ }, [open, nodes])const onConfirm = () => {const options = pendingRunOptions@@ -64,9 +73,9 @@ export function CustomCodeTrustDialog() {Trust custom Python?</Typography><Typography sx={{ fontSize: 13, color: 'rgba(244,241,234,0.6)', lineHeight: 1.5, mb: 2 }}>- This workflow includes Custom Python nodes. The code runs on your machine with full- access (same as any local script). Only continue if you reviewed the code and trust- its source.+ This workflow includes custom or reusable script nodes. The code runs on your machine+ with full access (same as any local script). Only continue if you reviewed the code and+ trust its source.</Typography><Stack spacing={1.25} sx={{ mb: 2.25, maxHeight: 220, overflow: 'auto' }}>@@ -81,7 +90,7 @@ export function CustomCodeTrustDialog() {}}><Typography sx={{ fontSize: 12, fontWeight: 650, mb: 0.5 }}>- {node.data.label ?? 'Custom Python'}{' '}+ {node.data.label ?? node.data.type}{' '}<Typography component="span" sx={{ color: 'rgba(244,241,234,0.4)', fontWeight: 500 }}>({node.id})</Typography>@@ -97,7 +106,7 @@ export function CustomCodeTrustDialog() {wordBreak: 'break-word',}}>- {truncateCodePreview(String(node.data.params.code ?? ''), 160)}+ {truncateCodePreview(resolveCustomCodePreview(node, userScriptCodes), 160)}</Typography></Box>))}diff --git a/frontend/src/features/inspector/CustomPythonParams.test.tsx b/frontend/src/features/inspector/CustomPythonParams.test.tsxindex 6c5c4c3..9fddf6b 100644--- a/frontend/src/features/inspector/CustomPythonParams.test.tsx+++ b/frontend/src/features/inspector/CustomPythonParams.test.tsx@@ -1,5 +1,6 @@import { render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { describe, expect, it, vi } from 'vitest'import { IDENTITY_CODE } from '../../test/customPythonFixtures'import { CustomPythonParams } from './CustomPythonParams'@@ -10,8 +11,19 @@ vi.mock('@monaco-editor/react', async () => {})function renderParams(onCodeChange = vi.fn()) {- render(<CustomPythonParams code={IDENTITY_CODE} onCodeChange={onCodeChange} />)- return onCodeChange+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ })+ render(+ <QueryClientProvider client={client}>+ <CustomPythonParams+ nodeId="custom-1"+ code={IDENTITY_CODE}+ onCodeChange={onCodeChange}+ />+ </QueryClientProvider>,+ )+ return { onCodeChange, client }}async function openEditor() {@@ -39,7 +51,7 @@ describe('CustomPythonParams', () => {})it('commits edits on Save and discards them on Cancel', async () => {- const onSave = renderParams()+ const { onCodeChange: onSave } = renderParams()let user = await openEditor()await user.clear(screen.getByTestId('monaco-edit'))await user.type(screen.getByTestId('monaco-edit'), 'return image * 2')@@ -62,4 +74,46 @@ describe('CustomPythonParams', () => {expect(screen.queryByRole('button', { name: /^Save$/i })).not.toBeInTheDocument()})})++ it('saves as reusable node, switches this node, and invalidates catalog', async () => {+ const { pipelineCustomNode, resetCustomCodeStore } = await import(+ '../../test/customPythonFixtures'+ )+ const { useGraphStore } = await import('../../store/graphStore')+ resetCustomCodeStore({+ nodes: [pipelineCustomNode(IDENTITY_CODE, 'custom-1')],+ })++ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ new Response(+ JSON.stringify({+ id: 'script_001',+ name: 'Sepia',+ current_version: 1,+ created_at: '',+ updated_at: '',+ node_type: 'user_script.script_001',+ }),+ { status: 200, headers: { 'Content-Type': 'application/json' } },+ ),+ )++ const { client } = renderParams()+ const invalidate = vi.spyOn(client, 'invalidateQueries')+ const user = userEvent.setup()+ await user.click(screen.getByRole('button', { name: /Save as reusable node/i }))+ await user.type(screen.getByLabelText(/Display name/i), 'Sepia')+ await user.click(screen.getByRole('button', { name: /^Save$/i }))++ await waitFor(() => expect(fetchSpy).toHaveBeenCalled())+ expect(String(fetchSpy.mock.calls[0]?.[0])).toContain('/api/user-scripts')+ await waitFor(() => {+ const node = useGraphStore.getState().nodes.find((n) => n.id === 'custom-1')+ expect(node?.data.type).toBe('user_script.script_001')+ expect(node?.data.label).toBe('Sepia')+ expect(node?.data.params.version).toBe(1)+ })+ await waitFor(() => expect(invalidate).toHaveBeenCalledWith({ queryKey: ['nodes'] }))+ fetchSpy.mockRestore()+ })})diff --git a/frontend/src/features/inspector/CustomPythonParams.tsx b/frontend/src/features/inspector/CustomPythonParams.tsxindex fc661be..c1e1596 100644--- a/frontend/src/features/inspector/CustomPythonParams.tsx+++ b/frontend/src/features/inspector/CustomPythonParams.tsx@@ -4,11 +4,19 @@ import {Box,Button,Dialog,+ DialogActions,DialogContent,+ DialogTitle,+ TextField,Typography,} from '@mui/material'+import { useQueryClient } from '@tanstack/react-query'+import { createUserScript } from '../../api/userScripts'+import { notifyError } from '../../notify'+import { useGraphStore } from '../../store/graphStore'type CustomPythonParamsProps = {+ nodeId: stringcode: stringonCodeChange: (code: string) => void}@@ -66,10 +74,15 @@ function EditIcon({ color = ICON_COLOR }: { color?: string }) {)}-export function CustomPythonParams({ code, onCodeChange }: CustomPythonParamsProps) {+export function CustomPythonParams({ nodeId, code, onCodeChange }: CustomPythonParamsProps) {+ const queryClient = useQueryClient()+ const convertNodeToUserScript = useGraphStore((s) => s.convertNodeToUserScript)const [editing, setEditing] = useState(false)const [editorSeed, setEditorSeed] = useState(code)const draftRef = useRef(code)+ const [saveOpen, setSaveOpen] = useState(false)+ const [saveName, setSaveName] = useState('')+ const [saving, setSaving] = useState(false)const openEditor = () => {draftRef.current = code@@ -91,6 +104,31 @@ export function CustomPythonParams({ code, onCodeChange }: CustomPythonParamsProed.focus()}+ const saveAsReusable = async () => {+ const name = saveName.trim()+ if (!name) {+ notifyError('Enter a display name for the reusable node')+ return+ }+ setSaving(true)+ try {+ const meta = await createUserScript(name, code)+ convertNodeToUserScript(nodeId, {+ nodeType: meta.node_type,+ label: meta.name,+ version: meta.current_version,+ code,+ })+ await queryClient.invalidateQueries({ queryKey: ['nodes'] })+ setSaveOpen(false)+ setSaveName('')+ } catch (err) {+ notifyError(err instanceof Error ? err.message : String(err))+ } finally {+ setSaving(false)+ }+ }+return (<Box sx={{ display: 'grid', gap: 1.25 }}><Typography sx={{ fontSize: 13, color: 'rgba(244,241,234,0.55)', lineHeight: 1.45 }}>@@ -105,31 +143,55 @@ export function CustomPythonParams({ code, onCodeChange }: CustomPythonParamsProalignItems: 'center',justifyContent: 'space-between',gap: 1,+ flexWrap: 'wrap',}}><Typography sx={{ fontSize: 12, fontWeight: 650, color: 'rgba(244,241,234,0.7)' }}>Code</Typography>- <Button- size="small"- variant="outlined"- startIcon={<EditIcon />}- onClick={openEditor}- sx={{- textTransform: 'none',- fontWeight: 650,- fontSize: 12,- color: ICON_COLOR,- borderColor: 'rgba(255,255,255,0.16)',- '& .MuiButton-startIcon': { color: ICON_COLOR },- '&:hover': {- borderColor: 'rgba(125,206,160,0.45)',- bgcolor: 'rgba(125,206,160,0.08)',- },- }}- >- Edit code- </Button>+ <Box sx={{ display: 'flex', gap: 1 }}>+ <Button+ size="small"+ variant="outlined"+ onClick={() => {+ setSaveName('')+ setSaveOpen(true)+ }}+ sx={{+ textTransform: 'none',+ fontWeight: 650,+ fontSize: 12,+ color: ICON_COLOR,+ borderColor: 'rgba(255,255,255,0.16)',+ '&:hover': {+ borderColor: 'rgba(93,173,226,0.45)',+ bgcolor: 'rgba(93,173,226,0.08)',+ },+ }}+ >+ Save as reusable node+ </Button>+ <Button+ size="small"+ variant="outlined"+ startIcon={<EditIcon />}+ onClick={openEditor}+ sx={{+ textTransform: 'none',+ fontWeight: 650,+ fontSize: 12,+ color: ICON_COLOR,+ borderColor: 'rgba(255,255,255,0.16)',+ '& .MuiButton-startIcon': { color: ICON_COLOR },+ '&:hover': {+ borderColor: 'rgba(125,206,160,0.45)',+ bgcolor: 'rgba(125,206,160,0.08)',+ },+ }}+ >+ Edit code+ </Button>+ </Box></Box><Box@@ -248,6 +310,72 @@ export function CustomPythonParams({ code, onCodeChange }: CustomPythonParamsPro</Box></DialogContent></Dialog>++ <Dialog+ open={saveOpen}+ onClose={() => {+ if (!saving) setSaveOpen(false)+ }}+ className="nokey"+ slotProps={{+ paper: {+ className: 'nokey',+ sx: {+ bgcolor: '#161616',+ color: ICON_COLOR,+ border: '1px solid rgba(255,255,255,0.1)',+ backgroundImage: 'none',+ },+ },+ }}+ >+ <DialogTitle sx={{ fontFamily: '"Fraunces", Georgia, serif', fontWeight: 700 }}>+ Save as reusable node+ </DialogTitle>+ <DialogContent>+ <Typography sx={{ fontSize: 13, color: 'rgba(244,241,234,0.55)', mb: 2 }}>+ Creates a new palette node under My Scripts. Later edits bump the version without+ overwriting older pipelines.+ </Typography>+ <TextField+ autoFocus+ fullWidth+ label="Display name"+ value={saveName}+ onChange={(event) => setSaveName(event.target.value)}+ disabled={saving}+ onKeyDown={(event) => {+ if (event.key === 'Enter') {+ event.preventDefault()+ void saveAsReusable()+ }+ }}+ />+ </DialogContent>+ <DialogActions sx={{ px: 3, pb: 2 }}>+ <Button+ disabled={saving}+ onClick={() => setSaveOpen(false)}+ sx={{ textTransform: 'none', color: 'rgba(244,241,234,0.65)' }}+ >+ Cancel+ </Button>+ <Button+ variant="contained"+ disabled={saving}+ onClick={() => void saveAsReusable()}+ sx={{+ textTransform: 'none',+ fontWeight: 650,+ bgcolor: '#5dade2',+ color: '#0f0f0f',+ '&:hover': { bgcolor: '#4ea0d6' },+ }}+ >+ {saving ? 'Saving…' : 'Save'}+ </Button>+ </DialogActions>+ </Dialog></Box>)}diff --git a/frontend/src/features/inspector/NodeInspector.tsx b/frontend/src/features/inspector/NodeInspector.tsxindex faef9c9..50429ec 100644--- a/frontend/src/features/inspector/NodeInspector.tsx+++ b/frontend/src/features/inspector/NodeInspector.tsx@@ -14,6 +14,8 @@ import { FileParamInput } from './FileParamInput'import { SaveImageParams } from './SaveImageParams'import { AnnotationsParams } from './AnnotationsParams'import { CustomPythonParams } from './CustomPythonParams'+import { UserScriptParams } from './UserScriptParams'+import { isUserScriptType } from '../../workflow/customCodeTrust'function buildSchema(fields: ParamField[]) {const shape: Record<string, z.ZodTypeAny> = {}@@ -48,6 +50,7 @@ export function NodeInspector() {const isLoadImage = selected?.data.type === 'load_image'const isAnnotations = selected?.data.type === 'annotations'const isCustomPython = selected?.data.type === 'custom_python'+ const isUserScript = selected ? isUserScriptType(selected.data.type) : falseconst { register, handleSubmit, reset, setValue, formState } = useForm({resolver: zodResolver(schema),@@ -131,12 +134,24 @@ export function NodeInspector() {) : isCustomPython ? (<CustomPythonParamskey={selected.id}+ nodeId={selected.id}code={String(selected.data.params.code ?? '')}onCodeChange={(nextCode) => {setValue('code', nextCode, { shouldDirty: true, shouldValidate: true })updateNodeParams(selected.id, { code: nextCode })}}/>+ ) : isUserScript ? (+ <UserScriptParams+ key={selected.id}+ nodeType={selected.data.type}+ label={selected.data.label}+ version={Number(selected.data.params.version ?? 1)}+ onVersionChange={(version) => {+ setValue('version', version, { shouldDirty: true, shouldValidate: true })+ updateNodeParams(selected.id, { version })+ }}+ />) : isLoadImage ? (<FileParamInputfield={{diff --git a/frontend/src/features/inspector/UserScriptParams.test.tsx b/frontend/src/features/inspector/UserScriptParams.test.tsxnew file mode 100644index 0000000..f82c19d--- /dev/null+++ b/frontend/src/features/inspector/UserScriptParams.test.tsx@@ -0,0 +1,130 @@+import { render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { resetCustomCodeStore } from '../../test/customPythonFixtures'+import { useGraphStore } from '../../store/graphStore'+import { userScriptCodeKey } from '../../workflow/customCodeTrust'+import { UserScriptParams } from './UserScriptParams'++vi.mock('@monaco-editor/react', async () => {+ const { MockMonacoEditor } = await import('../../test/MockMonacoEditor')+ return { default: MockMonacoEditor }+})++const V1 = 'def process(image, seed=0):\n return image\n'+const V2 = 'def process(image, seed=0):\n return image + 1\n'++function renderUserScript(onVersionChange = vi.fn()) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ })+ render(+ <QueryClientProvider client={client}>+ <UserScriptParams+ nodeType="user_script.script_001"+ label="Sepia Tone"+ version={1}+ onVersionChange={onVersionChange}+ />+ </QueryClientProvider>,+ )+ return { onVersionChange, client }+}++describe('UserScriptParams', () => {+ afterEach(() => {+ vi.restoreAllMocks()+ })++ beforeEach(() => {+ resetCustomCodeStore({+ userScriptCodes: {+ [userScriptCodeKey('user_script.script_001', 1)]: V1,+ },+ })+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => {+ const url = String(input)+ if (url.includes('/api/user-scripts') && !url.includes('/versions')) {+ return new Response(+ JSON.stringify([+ {+ id: 'script_001',+ name: 'Sepia Tone',+ current_version: 2,+ created_at: '',+ updated_at: '',+ node_type: 'user_script.script_001',+ },+ ]),+ { status: 200, headers: { 'Content-Type': 'application/json' } },+ )+ }+ return new Response('not found', { status: 404 })+ })+ })++ it('shows pinned version select and cached code', async () => {+ renderUserScript()+ const select = await screen.findByLabelText(/Pinned version/i)+ expect(select).toHaveTextContent(/v1/)+ expect(screen.getByTestId('monaco-readonly')).toHaveValue(V1)+ })++ it('saves a new version, updates param, and invalidates nodes', async () => {+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {+ const url = String(input)+ if (url.endsWith('/api/user-scripts') && (!init || init.method === undefined || init.method === 'GET')) {+ return new Response(+ JSON.stringify([+ {+ id: 'script_001',+ name: 'Sepia Tone',+ current_version: 1,+ created_at: '',+ updated_at: '',+ node_type: 'user_script.script_001',+ },+ ]),+ { status: 200, headers: { 'Content-Type': 'application/json' } },+ )+ }+ if (url.includes('/versions') && init?.method === 'POST') {+ return new Response(+ JSON.stringify({+ id: 'script_001',+ name: 'Sepia Tone',+ current_version: 2,+ created_at: '',+ updated_at: '',+ node_type: 'user_script.script_001',+ }),+ { status: 200, headers: { 'Content-Type': 'application/json' } },+ )+ }+ return new Response('not found', { status: 404 })+ })++ const { onVersionChange, client } = renderUserScript()+ const invalidate = vi.spyOn(client, 'invalidateQueries')+ const user = userEvent.setup()+ await user.click(screen.getByRole('button', { name: /Edit code/i }))+ await user.clear(screen.getByTestId('monaco-edit'))+ await user.type(screen.getByTestId('monaco-edit'), V2)+ await user.click(screen.getByRole('button', { name: /Save as new version/i }))++ await waitFor(() => expect(onVersionChange).toHaveBeenCalledWith(2))+ expect(+ fetchSpy.mock.calls.some(+ ([req, init]) =>+ String(req).includes('/api/user-scripts/script_001/versions') &&+ (init as RequestInit | undefined)?.method === 'POST',+ ),+ ).toBe(true)+ await waitFor(() => expect(invalidate).toHaveBeenCalledWith({ queryKey: ['nodes'] }))+ expect(useGraphStore.getState().userScriptCodes[userScriptCodeKey('user_script.script_001', 2)]).toBe(+ V2,+ )+ fetchSpy.mockRestore()+ })+})diff --git a/frontend/src/features/inspector/UserScriptParams.tsx b/frontend/src/features/inspector/UserScriptParams.tsxnew file mode 100644index 0000000..b045025--- /dev/null+++ b/frontend/src/features/inspector/UserScriptParams.tsx@@ -0,0 +1,350 @@+import { useEffect, useMemo, useRef, useState } from 'react'+import Editor, { type OnMount } from '@monaco-editor/react'+import {+ Box,+ Button,+ Dialog,+ DialogContent,+ MenuItem,+ TextField,+ Typography,+} from '@mui/material'+import { useQuery, useQueryClient } from '@tanstack/react-query'+import {+ createUserScriptVersion,+ getUserScriptCode,+ listUserScripts,+} from '../../api/userScripts'+import { notifyError } from '../../notify'+import { useGraphStore } from '../../store/graphStore'+import { scriptIdFromType, userScriptCodeKey } from '../../workflow/customCodeTrust'++type UserScriptParamsProps = {+ nodeType: string+ label: string+ version: number+ onVersionChange: (version: number) => void+}++const ICON_COLOR = '#f0ebe3'++const readOnlyOptions = {+ readOnly: true,+ domReadOnly: true,+ minimap: { enabled: false },+ fontSize: 12,+ scrollBeyondLastLine: false,+ wordWrap: 'on' as const,+ lineNumbers: 'on' as const,+ tabSize: 4,+ automaticLayout: true,+ renderLineHighlight: 'none' as const,+ quickSuggestions: false,+ suggestOnTriggerCharacters: false,+ parameterHints: { enabled: false },+ hover: { enabled: 'off' as const },+ contextmenu: false,+ accessibilitySupport: 'off' as const,+}++const editOptions = {+ ...readOnlyOptions,+ readOnly: false,+ domReadOnly: false,+ fontSize: 14,+ minimap: { enabled: true },+ renderLineHighlight: 'line' as const,+ contextmenu: true,+ acceptSuggestionOnEnter: 'off' as const,+ tabCompletion: 'off' as const,+ wordBasedSuggestions: 'off' as const,+ snippetSuggestions: 'none' as const,+ suggestOnTriggerCharacters: false,+ quickSuggestions: {+ other: false,+ comments: false,+ strings: false,+ },+}++function EditIcon({ color = ICON_COLOR }: { color?: string }) {+ return (+ <svg width="16" height="16" viewBox="0 0 24 24" aria-hidden focusable="false">+ <path+ fill={color}+ d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04a1.003 1.003 0 0 0 0-1.42l-2.34-2.34a1.003 1.003 0 0 0-1.42 0l-1.83 1.83 3.75 3.75 1.84-1.82z"+ />+ </svg>+ )+}++export function UserScriptParams({+ nodeType,+ label,+ version,+ onVersionChange,+}: UserScriptParamsProps) {+ const queryClient = useQueryClient()+ const cacheUserScriptCode = useGraphStore((s) => s.cacheUserScriptCode)+ const userScriptCodes = useGraphStore((s) => s.userScriptCodes)+ const trustCustomCode = useGraphStore((s) => s.trustCustomCode)++ const scriptId = scriptIdFromType(nodeType) ?? ''+ const codeKey = userScriptCodeKey(nodeType, version)+ const code = userScriptCodes[codeKey] ?? ''+ const cached = userScriptCodes[codeKey] !== undefined++ const { data: scripts = [] } = useQuery({+ queryKey: ['user-scripts'],+ queryFn: listUserScripts,+ })+ const currentVersion =+ scripts.find((item) => item.id === scriptId)?.current_version ?? version+ const versionOptions = useMemo(() => {+ const maxVersion = Math.max(1, currentVersion, version)+ return Array.from({ length: maxVersion }, (_, index) => index + 1)+ }, [currentVersion, version])++ const [editing, setEditing] = useState(false)+ const [editorSeed, setEditorSeed] = useState(code)+ const [saving, setSaving] = useState(false)+ const [failedKey, setFailedKey] = useState<string | null>(null)+ const draftRef = useRef(code)+ const fetchError = failedKey === codeKey++ useEffect(() => {+ let cancelled = false+ if (!scriptId || cached) return+ void getUserScriptCode(scriptId, version)+ .then((resp) => {+ if (cancelled) return+ cacheUserScriptCode(nodeType, version, resp.code)+ })+ .catch((err: unknown) => {+ if (cancelled) return+ setFailedKey(codeKey)+ notifyError(err instanceof Error ? err.message : String(err))+ })+ return () => {+ cancelled = true+ }+ }, [scriptId, version, nodeType, cached, cacheUserScriptCode, codeKey])++ const openEditor = () => {+ draftRef.current = code+ setEditorSeed(code)+ setEditing(true)+ }++ const closeEditor = async (save: boolean) => {+ if (!save) {+ setEditing(false)+ return+ }+ if (!scriptId) return+ setSaving(true)+ try {+ const meta = await createUserScriptVersion(scriptId, draftRef.current)+ cacheUserScriptCode(nodeType, meta.current_version, draftRef.current)+ onVersionChange(meta.current_version)+ trustCustomCode()+ await queryClient.invalidateQueries({ queryKey: ['nodes'] })+ await queryClient.invalidateQueries({ queryKey: ['user-scripts'] })+ setEditing(false)+ } catch (err) {+ notifyError(err instanceof Error ? err.message : String(err))+ } finally {+ setSaving(false)+ }+ }++ const onEditMount: OnMount = (ed, monaco) => {+ ed.getContainerDomNode().classList.add('nokey')+ ed.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.Space, () => {})+ ed.focus()+ }++ return (+ <Box sx={{ display: 'grid', gap: 1.25 }}>+ <Typography sx={{ fontSize: 13, color: 'rgba(244,241,234,0.55)', lineHeight: 1.45 }}>+ Reusable script <strong>{label}</strong> ({scriptId}). Editing always creates a new+ version; this canvas node pins the version below.+ </Typography>++ <TextField+ select+ size="small"+ label="Pinned version"+ value={version}+ onChange={(event) => {+ const next = Number(event.target.value)+ if (Number.isFinite(next) && next >= 1) onVersionChange(Math.floor(next))+ }}+ helperText="Older versions stay on disk; change only if you intend to retarget."+ >+ {versionOptions.map((option) => (+ <MenuItem key={option} value={option}>+ v{option}+ {option === currentVersion ? ' (latest)' : ''}+ </MenuItem>+ ))}+ </TextField>++ <Box+ sx={{+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'space-between',+ gap: 1,+ }}+ >+ <Typography sx={{ fontSize: 12, fontWeight: 650, color: 'rgba(244,241,234,0.7)' }}>+ Code (v{version})+ </Typography>+ <Button+ size="small"+ variant="outlined"+ startIcon={<EditIcon />}+ onClick={openEditor}+ disabled={!cached || !code}+ sx={{+ textTransform: 'none',+ fontWeight: 650,+ fontSize: 12,+ color: ICON_COLOR,+ borderColor: 'rgba(255,255,255,0.16)',+ '& .MuiButton-startIcon': { color: ICON_COLOR },+ '&:hover': {+ borderColor: 'rgba(125,206,160,0.45)',+ bgcolor: 'rgba(125,206,160,0.08)',+ },+ }}+ >+ Edit code+ </Button>+ </Box>++ <Box+ className="nokey"+ sx={{+ height: 280,+ border: '1px solid rgba(255,255,255,0.12)',+ borderRadius: 1,+ overflow: 'hidden',+ opacity: 0.92,+ }}+ >+ {!cached ? (+ <Typography sx={{ p: 2, fontSize: 12, color: 'rgba(244,241,234,0.45)' }}>+ {fetchError ? 'Failed to load script.' : 'Loading script…'}+ </Typography>+ ) : (+ <Editor+ height="100%"+ defaultLanguage="python"+ value={code}+ theme="vs-dark"+ options={readOnlyOptions}+ />+ )}+ </Box>++ <Dialog+ open={editing}+ onClose={() => {+ if (!saving) void closeEditor(false)+ }}+ fullScreen+ className="nokey"+ slotProps={{+ paper: {+ className: 'nokey',+ sx: {+ bgcolor: '#0f0f0f',+ color: ICON_COLOR,+ backgroundImage: 'none',+ display: 'flex',+ flexDirection: 'column',+ },+ },+ }}+ >+ <Box+ className="nokey"+ sx={{+ display: 'flex',+ alignItems: 'center',+ gap: 1,+ px: 2,+ py: 1.25,+ borderBottom: '1px solid rgba(255,255,255,0.1)',+ flexShrink: 0,+ }}+ >+ <Typography+ sx={{+ flex: 1,+ fontFamily: '"Fraunces", Georgia, serif',+ fontWeight: 700,+ fontSize: 18,+ letterSpacing: '-0.02em',+ }}+ >+ Edit {label} (new version)+ </Typography>+ <Button+ size="small"+ disabled={saving}+ onClick={() => void closeEditor(false)}+ sx={{ textTransform: 'none', color: 'rgba(244,241,234,0.65)' }}+ >+ Cancel+ </Button>+ <Button+ size="small"+ variant="contained"+ disabled={saving}+ onClick={() => void closeEditor(true)}+ sx={{+ textTransform: 'none',+ fontWeight: 650,+ bgcolor: '#7dcea0',+ color: '#0f0f0f',+ '&:hover': { bgcolor: '#6bbd8e' },+ }}+ >+ {saving ? 'Saving…' : 'Save as new version'}+ </Button>+ </Box>+ <DialogContent+ className="nokey"+ sx={{+ p: 0,+ flex: 1,+ minHeight: 0,+ display: 'flex',+ flexDirection: 'column',+ }}+ onKeyDown={(event) => event.stopPropagation()}+ onKeyUp={(event) => event.stopPropagation()}+ >+ <Box className="nokey" sx={{ flex: 1, minHeight: 0 }}>+ {editing ? (+ <Editor+ height="100%"+ defaultLanguage="python"+ defaultValue={editorSeed}+ theme="vs-dark"+ onChange={(value) => {+ draftRef.current = value ?? ''+ }}+ onMount={onEditMount}+ options={editOptions}+ />+ ) : null}+ </Box>+ </DialogContent>+ </Dialog>+ </Box>+ )+}diff --git a/frontend/src/features/palette/NodePalette.tsx b/frontend/src/features/palette/NodePalette.tsxindex 90858b8..b31fbe0 100644--- a/frontend/src/features/palette/NodePalette.tsx+++ b/frontend/src/features/palette/NodePalette.tsx@@ -11,6 +11,8 @@ import {import { useGraphStore } from '../../store/graphStore'import type { NodeMetadata } from '../../types'import { notifyError } from '../../notify'+import { isUserScriptType } from '../../workflow/customCodeTrust'+import { hydrateUserScriptCodes } from '../../workflow/hydrateUserScriptCodes'async function fetchNodes(): Promise<NodeMetadata[]> {const response = await fetch('/api/nodes')@@ -29,12 +31,22 @@ const CATEGORY_ACCENT: Record<string, string> = {math: '#58d68d',stochastic: '#f5b041',augment: '#e74c3c',+ script: '#f39c12',+ user_scripts: '#5dade2',+}++const CATEGORY_LABELS: Record<string, string> = {+ user_scripts: 'My Scripts',}function categoryAccent(category: string): string {return CATEGORY_ACCENT[category.toLowerCase()] ?? '#95a5a6'}+function categoryLabel(category: string): string {+ return CATEGORY_LABELS[category.toLowerCase()] ?? category+}+function portSummary(node: NodeMetadata): { inputs: number; outputs: number } {const inputs = node.ports.filter((port) => port.direction === 'input').lengthconst outputs = node.ports.filter((port) => port.direction === 'output').length@@ -101,7 +113,7 @@ function CategoryHeader({color: 'rgba(244,241,234,0.72)',}}>- {category}+ {categoryLabel(category)}</Typography><Typographysx={{@@ -351,6 +363,11 @@ export function NodePalette() {const addNode = (node: NodeMetadata) => {const offset = (useGraphStore.getState().nodes.length % 8) * 28addNodeFromType(node, { x: 180 + offset, y: 120 + offset })+ if (isUserScriptType(node.type)) {+ void hydrateUserScriptCodes({ autoTrust: true }).catch((err: unknown) => {+ notifyError(err instanceof Error ? err.message : String(err))+ })+ }}return (diff --git a/frontend/src/hooks/useWorkflowPersistence.ts b/frontend/src/hooks/useWorkflowPersistence.tsindex f560f5e..98dd972 100644--- a/frontend/src/hooks/useWorkflowPersistence.ts+++ b/frontend/src/hooks/useWorkflowPersistence.ts@@ -3,6 +3,7 @@ import { useGraphStore } from '../store/graphStore'import { materializeSampleImages } from '../workflow/materializeSampleImages'import { loadWorkflowSession, saveWorkflowSession } from '../workflow/persist'import { getWorkflow } from '../workflow/workflowLibrary'+import { hydrateUserScriptCodes } from '../workflow/hydrateUserScriptCodes'const SAVE_DEBOUNCE_MS = 400@@ -46,6 +47,9 @@ export function useWorkflowPersistence() {id: undefined,}loadWorkflow(doc)+ void hydrateUserScriptCodes().catch(() => {+ // Codes may be missing if scripts were deleted; trust stays blocked.+ })void materializeSampleImages().catch(() => {// Session may already have real upload paths; ignore sample staging failures.})diff --git a/frontend/src/store/graphStore.ts b/frontend/src/store/graphStore.tsindex 1663110..1e1f520 100644--- a/frontend/src/store/graphStore.ts+++ b/frontend/src/store/graphStore.ts@@ -9,7 +9,7 @@ import {type NodeChange,} from '@xyflow/react'import { create } from 'zustand'-import type { ExecutionPreview, GraphNodeData, NodeMetadata } from '../types'+import type { ExecutionPreview, GraphNodeData, NodeMetadata, PortSpec } from '../types'import {DEFAULT_WORKFLOW_NAME,type WorkflowDocument,@@ -19,6 +19,10 @@ import {computeCustomCodeHash,graphHasCustomCode,isCustomCodeTrusted,+ isCustomCodeType,+ isUserScriptType,+ type UserScriptCodeMap,+ userScriptCodeKey,} from '../workflow/customCodeTrust'import { portTypeColor } from '../lib/portTypes'@@ -74,13 +78,16 @@ interface GraphState {workflowCreatedAt: string | nullworkflowUpdatedAt: string | nullworkflowDirty: boolean- /** Session-only fingerprint of trusted custom_python code; null = untrusted when code exists. */+ /** Session-only fingerprint of trusted custom code; null = untrusted when code exists. */trustedCustomCodeHash: string | null+ /** Session cache of user_script sources (not persisted in workflow JSON). */+ userScriptCodes: UserScriptCodeMapcustomCodeTrustDialogOpen: booleanpendingRunOptions: { targetNodeId?: string } | null/** When true, confirming the trust dialog also starts a pipeline run. */pendingRunAfterTrust: booleansetNodeCatalog: (catalog: NodeMetadata[]) => void+ cacheUserScriptCode: (type: string, version: number, code: string) => voidonNodesChange: (changes: NodeChange<PipelineNode>[]) => voidonEdgesChange: (changes: EdgeChange[]) => voidonConnect: (connection: Connection) => void@@ -91,6 +98,11 @@ interface GraphState {duplicateNode: (nodeId: string) => voidselectNode: (nodeId: string | null) => voidupdateNodeParams: (nodeId: string, params: Record<string, unknown>) => void+ /** Replace a canvas node with a reusable user_script.* type (keeps id / edges). */+ convertNodeToUserScript: (+ nodeId: string,+ info: { nodeType: string; label: string; version: number; code: string },+ ) => voidsetLocalPreview: (nodeId: string, dataUrl: string | null) => voidsetLocalPreviews: (nodeId: string, dataUrls: string[], uploadedFiles?: string[]) => voidremoveLocalPreview: (nodeId: string, index: number) => {@@ -199,12 +211,20 @@ export const useGraphStore = create<GraphState>((set, get) => ({workflowUpdatedAt: null,workflowDirty: false,trustedCustomCodeHash: null,+ userScriptCodes: {},customCodeTrustDialogOpen: false,pendingRunOptions: null,pendingRunAfterTrust: false,setNodeCatalog: (catalog) => set({ nodeCatalog: catalog }),+ cacheUserScriptCode: (type, version, code) => {+ const key = userScriptCodeKey(type, version)+ set({+ userScriptCodes: { ...get().userScriptCodes, [key]: code },+ })+ },+onNodesChange: (changes) => {const removedIds = changes.filter((change) => change.type === 'remove')@@ -333,13 +353,15 @@ export const useGraphStore = create<GraphState>((set, get) => ({localPreviewUrls: [],},}+ const nodes = [...get().nodes, node]+ const hash = isCustomCodeType(meta.type)+ ? computeCustomCodeHash(nodes, get().userScriptCodes)+ : nullset({- nodes: [...get().nodes, node],+ nodes,selectedNodeId: id,workflowDirty: true,- ...(meta.type === 'custom_python'- ? { trustedCustomCodeHash: computeCustomCodeHash([...get().nodes, node]) }- : {}),+ ...(hash !== null ? { trustedCustomCodeHash: hash } : {}),})},@@ -367,18 +389,15 @@ export const useGraphStore = create<GraphState>((set, get) => ({uploadedFiles: [...(source.data.uploadedFiles ?? [])],},}+ const nodes = [...get().nodes.map((node) => ({ ...node, selected: false })), copy]+ const hash = isCustomCodeType(source.data.type)+ ? computeCustomCodeHash(nodes, get().userScriptCodes)+ : nullset({- nodes: [...get().nodes.map((node) => ({ ...node, selected: false })), copy],+ nodes,selectedNodeId: id,workflowDirty: true,- ...(source.data.type === 'custom_python'- ? {- trustedCustomCodeHash: computeCustomCodeHash([- ...get().nodes,- copy,- ]),- }- : {}),+ ...(hash !== null ? { trustedCustomCodeHash: hash } : {}),})},@@ -392,11 +411,68 @@ export const useGraphStore = create<GraphState>((set, get) => ({)const target = nodes.find((node) => node.id === nodeId)const autoTrust =- target?.data.type === 'custom_python' && Object.prototype.hasOwnProperty.call(params, 'code')+ (target?.data.type === 'custom_python' &&+ Object.prototype.hasOwnProperty.call(params, 'code')) ||+ (target !== undefined &&+ isUserScriptType(target.data.type) &&+ Object.prototype.hasOwnProperty.call(params, 'version'))+ const hash = autoTrust+ ? computeCustomCodeHash(nodes, get().userScriptCodes)+ : null+ set({+ nodes,+ workflowDirty: true,+ ...(hash !== null ? { trustedCustomCodeHash: hash } : {}),+ })+ },++ convertNodeToUserScript: (nodeId, info) => {+ const catalogMeta = get().nodeCatalog.find((meta) => meta.type === info.nodeType)+ const ports =+ catalogMeta?.ports ??+ ([+ {+ id: 'image',+ name: 'Image',+ direction: 'input',+ data_type: 'image',+ multiple: false,+ },+ {+ id: 'image',+ name: 'Image',+ direction: 'output',+ data_type: 'image',+ multiple: false,+ },+ ] satisfies PortSpec[])++ const userScriptCodes = {+ ...get().userScriptCodes,+ [userScriptCodeKey(info.nodeType, info.version)]: info.code,+ }+ const nodes = get().nodes.map((node) =>+ node.id === nodeId+ ? {+ ...node,+ data: {+ ...node.data,+ type: info.nodeType,+ label: info.label,+ category: catalogMeta?.category ?? 'user_scripts',+ ports,+ params: { version: info.version },+ },+ }+ : node,+ )+ const hash = computeCustomCodeHash(nodes, userScriptCodes)set({nodes,+ userScriptCodes,workflowDirty: true,- ...(autoTrust ? { trustedCustomCodeHash: computeCustomCodeHash(nodes) } : {}),+ selectedNodeId: nodeId,+ ...(hash !== null ? { trustedCustomCodeHash: hash } : {}),})},@@ -803,7 +879,10 @@ export const useGraphStore = create<GraphState>((set, get) => ({},trustCustomCode: () => {- set({ trustedCustomCodeHash: computeCustomCodeHash(get().nodes) })+ const hash = computeCustomCodeHash(get().nodes, get().userScriptCodes)+ if (hash !== null) {+ set({ trustedCustomCodeHash: hash })+ }},openCustomCodeTrustDialog: (options, runAfterTrust = true) =>@@ -820,7 +899,8 @@ export const useGraphStore = create<GraphState>((set, get) => ({pendingRunAfterTrust: false,}),- isCustomCodeTrusted: () => isCustomCodeTrusted(get().nodes, get().trustedCustomCodeHash),+ isCustomCodeTrusted: () =>+ isCustomCodeTrusted(get().nodes, get().trustedCustomCodeHash, get().userScriptCodes),graphHasCustomCode: () => graphHasCustomCode(get().nodes),}))diff --git a/frontend/src/test/customPythonFixtures.ts b/frontend/src/test/customPythonFixtures.tsindex e3dcf99..e6c02fd 100644--- a/frontend/src/test/customPythonFixtures.ts+++ b/frontend/src/test/customPythonFixtures.ts@@ -11,8 +11,8 @@ export const customPythonMeta: NodeMetadata = {category: 'script',description: 'User code',ports: [- { id: 'image', name: 'Image', direction: 'input', data_type: 'image' },- { id: 'image', name: 'Image', direction: 'output', data_type: 'image' },+ { id: 'image', name: 'Image', direction: 'input', data_type: 'image', multiple: false },+ { id: 'image', name: 'Image', direction: 'output', data_type: 'image', multiple: false },],params: [{@@ -30,7 +30,7 @@ export const loadImageMeta: NodeMetadata = {label: 'Load Images',category: 'io',description: 'Load',- ports: [{ id: 'image', name: 'Image', direction: 'output', data_type: 'image' }],+ ports: [{ id: 'image', name: 'Image', direction: 'output', data_type: 'image', multiple: false }],params: [],stochastic: false,}@@ -40,13 +40,17 @@ export function trustNode(id: string,type: string,code?: string,+ version?: number,): CustomCodeNodeLike {+ const params: Record<string, unknown> = {}+ if (code !== undefined) params.code = code+ if (version !== undefined) params.version = versionreturn {id,data: {type,label: type === 'custom_python' ? 'Custom Python' : type,- params: code === undefined ? {} : { code },+ params,},}}@@ -74,6 +78,7 @@ export function resetCustomCodeStore(patch: Partial<{nodes: Node<GraphNodeData>[]trustedCustomCodeHash: string | null+ userScriptCodes: Record<string, string>customCodeTrustDialogOpen: booleanpendingRunAfterTrust: booleanpendingRunOptions: { targetNodeId?: string } | null@@ -85,6 +90,7 @@ export function resetCustomCodeStore(selectedNodeId: null,nodeCatalog: [customPythonMeta, loadImageMeta],trustedCustomCodeHash: null,+ userScriptCodes: {},customCodeTrustDialogOpen: false,pendingRunOptions: null,pendingRunAfterTrust: false,diff --git a/frontend/src/workflow/customCodeTrust.store.test.ts b/frontend/src/workflow/customCodeTrust.store.test.tsindex 0a830bb..26a1794 100644--- a/frontend/src/workflow/customCodeTrust.store.test.ts+++ b/frontend/src/workflow/customCodeTrust.store.test.ts@@ -16,7 +16,9 @@ describe('graphStore custom code trust', () => {it('auto-trusts palette add and local code edits', () => {store().addNodeFromType(customPythonMeta, { x: 10, y: 20 })expect(store().isCustomCodeTrusted()).toBe(true)- expect(store().trustedCustomCodeHash).toBe(computeCustomCodeHash(store().nodes))+ expect(store().trustedCustomCodeHash).toBe(+ computeCustomCodeHash(store().nodes, store().userScriptCodes),+ )resetCustomCodeStore({nodes: [pipelineCustomNode(IDENTITY_CODE)],diff --git a/frontend/src/workflow/customCodeTrust.test.ts b/frontend/src/workflow/customCodeTrust.test.tsindex 0039510..70d1b0e 100644--- a/frontend/src/workflow/customCodeTrust.test.ts+++ b/frontend/src/workflow/customCodeTrust.test.ts@@ -3,24 +3,25 @@ import {computeCustomCodeHash,graphHasCustomCode,isCustomCodeTrusted,- listCustomPythonNodes,+ listCustomCodeNodes,truncateCodePreview,+ userScriptCodeKey,} from './customCodeTrust'import { trustNode } from '../test/customPythonFixtures'describe('customCodeTrust helpers', () => {- it('detects and sorts custom_python nodes', () => {+ it('detects and sorts custom_python and user_script nodes', () => {const nodes = [trustNode('z-1', 'custom_python', 'a'),- trustNode('a-1', 'custom_python', 'b'),+ trustNode('a-1', 'user_script.script_001', undefined, 2),trustNode('mid', 'gaussian_blur'),]expect(graphHasCustomCode(nodes)).toBe(true)expect(graphHasCustomCode([trustNode('x', 'load_image')])).toBe(false)- expect(listCustomPythonNodes(nodes).map((n) => n.id)).toEqual(['a-1', 'z-1'])+ expect(listCustomCodeNodes(nodes).map((n) => n.id)).toEqual(['a-1', 'z-1'])})- it('fingerprints code and treats matching hash as trusted', () => {+ it('fingerprints inline code and user script type+version+code', () => {const nodes = [trustNode('c-1', 'custom_python', 'return image')]const hash = computeCustomCodeHash(nodes)@@ -32,6 +33,21 @@ describe('customCodeTrust helpers', () => {expect(isCustomCodeTrusted(nodes, null)).toBe(false)expect(isCustomCodeTrusted(nodes, hash)).toBe(true)expect(isCustomCodeTrusted([trustNode('x', 'load_image')], null)).toBe(true)++ const scriptNodes = [trustNode('u-1', 'user_script.script_001', undefined, 1)]+ const codes = {+ [userScriptCodeKey('user_script.script_001', 1)]: 'def process(image, seed=0):\n return image\n',+ }+ expect(computeCustomCodeHash(scriptNodes)).toBeNull()+ expect(isCustomCodeTrusted(scriptNodes, 'deadbeef', {})).toBe(false)+ const scriptHash = computeCustomCodeHash(scriptNodes, codes)+ expect(scriptHash).not.toBeNull()+ expect(isCustomCodeTrusted(scriptNodes, scriptHash, codes)).toBe(true)+ expect(+ computeCustomCodeHash(scriptNodes, {+ [userScriptCodeKey('user_script.script_001', 1)]: 'changed',+ }),+ ).not.toBe(scriptHash)})it('truncates long code previews', () => {diff --git a/frontend/src/workflow/customCodeTrust.ts b/frontend/src/workflow/customCodeTrust.tsindex af9a319..b810c74 100644--- a/frontend/src/workflow/customCodeTrust.ts+++ b/frontend/src/workflow/customCodeTrust.ts@@ -1,6 +1,7 @@-/** Custom Python trust fingerprint helpers (session-only; not persisted in workflow JSON). */+/** Custom code trust fingerprint helpers (session-only; not persisted in workflow JSON). */export const CUSTOM_PYTHON_TYPE = 'custom_python'+export const USER_SCRIPT_TYPE_PREFIX = 'user_script.'export type CustomCodeNodeLike = {id: string@@ -11,6 +12,9 @@ export type CustomCodeNodeLike = {}}+/** Session cache of on-disk user script sources keyed by `type@version`. */+export type UserScriptCodeMap = Record<string, string>+/** Stable non-cryptographic hash for code fingerprints. */export function hashString(input: string): string {let hash = 2166136261@@ -21,33 +25,73 @@ export function hashString(input: string): string {return (hash >>> 0).toString(16).padStart(8, '0')}-export function listCustomPythonNodes(nodes: CustomCodeNodeLike[]): CustomCodeNodeLike[] {+export function isUserScriptType(type: string): boolean {+ return type.startsWith(USER_SCRIPT_TYPE_PREFIX)+}++export function isCustomCodeType(type: string): boolean {+ return type === CUSTOM_PYTHON_TYPE || isUserScriptType(type)+}++export function userScriptCodeKey(type: string, version: number | string): string {+ return `${type}@${version}`+}++export function scriptIdFromType(type: string): string | null {+ if (!isUserScriptType(type)) return null+ return type.slice(USER_SCRIPT_TYPE_PREFIX.length) || null+}++export function listCustomCodeNodes(nodes: CustomCodeNodeLike[]): CustomCodeNodeLike[] {return nodes- .filter((node) => node.data.type === CUSTOM_PYTHON_TYPE)+ .filter((node) => isCustomCodeType(node.data.type)).sort((a, b) => a.id.localeCompare(b.id))}+/** @deprecated Prefer listCustomCodeNodes */+export function listCustomPythonNodes(nodes: CustomCodeNodeLike[]): CustomCodeNodeLike[] {+ return listCustomCodeNodes(nodes)+}+export function graphHasCustomCode(nodes: CustomCodeNodeLike[]): boolean {- return nodes.some((node) => node.data.type === CUSTOM_PYTHON_TYPE)+ return nodes.some((node) => isCustomCodeType(node.data.type))}-/** Hash of all custom_python code params, or null if none present. */-export function computeCustomCodeHash(nodes: CustomCodeNodeLike[]): string | null {+/**+ * Hash of all custom / user-script code. Returns null when the graph has no+ * custom code, or when a user_script node's source is missing from the cache.+ */+export function computeCustomCodeHash(+ nodes: CustomCodeNodeLike[],+ userScriptCodes: UserScriptCodeMap = {},+): string | null {+ const customNodes = listCustomCodeNodes(nodes)+ if (customNodes.length === 0) return null+const parts: string[] = []- for (const node of listCustomPythonNodes(nodes)) {- const code = String(node.data.params.code ?? '')- parts.push(`${node.id}\0${code}`)+ for (const node of customNodes) {+ if (node.data.type === CUSTOM_PYTHON_TYPE) {+ const code = String(node.data.params.code ?? '')+ parts.push(`${node.id}\0${CUSTOM_PYTHON_TYPE}\0${code}`)+ continue+ }+ const version = Number(node.data.params.version ?? 1)+ const key = userScriptCodeKey(node.data.type, version)+ const code = userScriptCodes[key]+ if (code === undefined) return null+ parts.push(`${node.id}\0${node.data.type}\0${version}\0${code}`)}- if (parts.length === 0) return nullreturn hashString(parts.join('\n'))}export function isCustomCodeTrusted(nodes: CustomCodeNodeLike[],trustedHash: string | null,+ userScriptCodes: UserScriptCodeMap = {},): boolean {- const hash = computeCustomCodeHash(nodes)- if (hash === null) return true+ if (!graphHasCustomCode(nodes)) return true+ const hash = computeCustomCodeHash(nodes, userScriptCodes)+ if (hash === null) return falsereturn trustedHash === hash}@@ -56,3 +100,14 @@ export function truncateCodePreview(code: string, max = 120): string {if (flat.length <= max) return flatreturn `${flat.slice(0, max - 1)}…`}++export function resolveCustomCodePreview(+ node: CustomCodeNodeLike,+ userScriptCodes: UserScriptCodeMap = {},+): string {+ if (node.data.type === CUSTOM_PYTHON_TYPE) {+ return String(node.data.params.code ?? '')+ }+ const version = Number(node.data.params.version ?? 1)+ return userScriptCodes[userScriptCodeKey(node.data.type, version)] ?? '(loading script…)'+}diff --git a/frontend/src/workflow/hydrateUserScriptCodes.ts b/frontend/src/workflow/hydrateUserScriptCodes.tsnew file mode 100644index 0000000..da9041d--- /dev/null+++ b/frontend/src/workflow/hydrateUserScriptCodes.ts@@ -0,0 +1,48 @@+/** Fetch and cache on-disk user script sources for trust fingerprints. */++import { getUserScriptCode } from '../api/userScripts'+import { useGraphStore } from '../store/graphStore'+import {+ isUserScriptType,+ scriptIdFromType,+ userScriptCodeKey,+ type CustomCodeNodeLike,+} from './customCodeTrust'++export async function hydrateUserScriptCodes(options?: {+ nodes?: CustomCodeNodeLike[]+ /** When true, mark the graph trusted once all sources are cached. */+ autoTrust?: boolean+}): Promise<void> {+ const state = useGraphStore.getState()+ const nodes = options?.nodes ?? state.nodes+ const missing: { type: string; scriptId: string; version: number }[] = []++ for (const node of nodes) {+ if (!isUserScriptType(node.data.type)) continue+ const scriptId = scriptIdFromType(node.data.type)+ if (!scriptId) continue+ const version = Number(node.data.params.version ?? 1)+ const key = userScriptCodeKey(node.data.type, version)+ if (state.userScriptCodes[key] !== undefined) continue+ missing.push({ type: node.data.type, scriptId, version })+ }++ if (missing.length === 0) {+ if (options?.autoTrust) {+ state.trustCustomCode()+ }+ return+ }++ await Promise.all(+ missing.map(async ({ type, scriptId, version }) => {+ const { code } = await getUserScriptCode(scriptId, version)+ useGraphStore.getState().cacheUserScriptCode(type, version, code)+ }),+ )++ if (options?.autoTrust) {+ useGraphStore.getState().trustCustomCode()+ }+}diff --git a/frontend/src/workflow/workflowActions.ts b/frontend/src/workflow/workflowActions.tsindex cd4dbb7..588fcc5 100644--- a/frontend/src/workflow/workflowActions.ts+++ b/frontend/src/workflow/workflowActions.ts@@ -3,6 +3,7 @@import { useGraphStore } from '../store/graphStore'import { DEFAULT_WORKFLOW_NAME, type WorkflowDocument } from './io'import { saveWorkflowSession } from './persist'+import { hydrateUserScriptCodes } from './hydrateUserScriptCodes'import {createWorkflowId,deleteWorkflow as deleteLibraryWorkflow,@@ -32,6 +33,7 @@ export function openWorkflow(id: string): { skippedTypes: string[] } {throw new Error('Workflow not found')}const result = useGraphStore.getState().loadWorkflow(record)+ void hydrateUserScriptCodes().catch(() => {})flushSession()return result}@@ -119,6 +121,7 @@ export function loadExternalDocument(...withoutId,name: overrides?.name?.trim() || doc.name || DEFAULT_WORKFLOW_NAME,})+ void hydrateUserScriptCodes().catch(() => {})flushSession()return result}