Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
refactor(client): extract useAsyncAction hook and apply to pipeline stages
Adam Eivy39548513b45e
diff --git a/client/src/components/pipeline/stages/EpisodeVideoStage.jsx b/client/src/components/pipeline/stages/EpisodeVideoStage.jsxindex 096bfc0bc8..c10566f109 100644--- a/client/src/components/pipeline/stages/EpisodeVideoStage.jsx+++ b/client/src/components/pipeline/stages/EpisodeVideoStage.jsx@@ -6,6 +6,7 @@ import { generatePipelineVisualImage } from '../../../services/api';import { getCreativeDirectorProject } from '../../../services/apiCreativeDirector';import { getSceneStatusBadge, PROJECT_STATUS_LABEL } from '../../creative-director/sceneStatus';import ScenePreview from '../../creative-director/ScenePreview';+import { useAsyncAction } from '../../../hooks/useAsyncAction';const POLL_INTERVAL_MS = 4000;@@ -28,7 +29,6 @@ export default function EpisodeVideoStage({ issue, onStageUpdate }) {const usableScenes = storyboardScenes.filter((s) => (s?.description || '').trim().length > 0);const [cdProject, setCdProject] = useState(null);- const [submitting, setSubmitting] = useState(false);const [confirmRestart, setConfirmRestart] = useState(false);// Initialize from the persisted stage values so a page reload (or a fresh// tab) doesn't lose the user's previous picks. Falls through to defaults@@ -75,20 +75,26 @@ export default function EpisodeVideoStage({ issue, onStageUpdate }) {};}, [cdProjectId]);+ const [runSubmit, submitting] = useAsyncAction(+ async ({ force }) => {+ const payload = { aspectRatio, quality };+ if (force) payload.force = true;+ return generatePipelineVisualImage(issue.id, 'episodeVideo', payload).catch((err) => {+ // Re-throw with a force-aware fallback so useAsyncAction's toaster+ // surfaces the right verb (start vs restart) if the server didn't+ // include a message.+ throw new Error(err.message || (force ? 'Failed to restart episode render' : 'Failed to start episode render'));+ });+ },+ );+const submit = async ({ force }) => {if (!force && !usableScenes.length) {toast.error('Add storyboard scenes with descriptions first');return;}setConfirmRestart(false);- setSubmitting(true);- const payload = { aspectRatio, quality };- if (force) payload.force = true;- const result = await generatePipelineVisualImage(issue.id, 'episodeVideo', payload).catch((err) => {- toast.error(err.message || (force ? 'Failed to restart episode render' : 'Failed to start episode render'));- return null;- });- setSubmitting(false);+ const result = await runSubmit({ force });if (!result) return;if (force) {// Only clear the prior project view AFTER the restart kickoff succeeds.diff --git a/client/src/components/pipeline/stages/ProseStage.jsx b/client/src/components/pipeline/stages/ProseStage.jsxindex 2905a1e4d7..c0d55f5be6 100644--- a/client/src/components/pipeline/stages/ProseStage.jsx+++ b/client/src/components/pipeline/stages/ProseStage.jsx@@ -1,21 +1,20 @@-import { useState } from 'react';import { Library, Loader2 } from 'lucide-react';import toast from '../../ui/Toast';import { extractPipelineBibles } from '../../../services/api';+import { useAsyncAction } from '../../../hooks/useAsyncAction';import TextStagePanel from './TextStagePanel';export default function ProseStage({ issue, series, onStageUpdate, onSeriesUpdate }) {- const [extracting, setExtracting] = useState(false);const proseReady = (issue.stages?.prose?.output || '').trim().length > 0;+ const [runExtract, extracting] = useAsyncAction(+ () => extractPipelineBibles(series.id, { issueId: issue.id }),+ { errorMessage: 'Extraction failed' },+ );+const handleExtract = async () => {if (!series) return;- setExtracting(true);- const result = await extractPipelineBibles(series.id, { issueId: issue.id }).catch((err) => {- toast.error(err.message || 'Extraction failed');- return null;- });- setExtracting(false);+ const result = await runExtract();if (!result) return;onSeriesUpdate?.(result.series);const counts = ['characters', 'settings', 'objects'].map(diff --git a/client/src/components/pipeline/stages/TextStagePanel.jsx b/client/src/components/pipeline/stages/TextStagePanel.jsxindex 093760dad8..07ad2a07fe 100644--- a/client/src/components/pipeline/stages/TextStagePanel.jsx+++ b/client/src/components/pipeline/stages/TextStagePanel.jsx@@ -9,6 +9,7 @@ import { useEffect, useState } from 'react';import { Loader2, Sparkles, Save } from 'lucide-react';import toast from '../../ui/Toast';import { generatePipelineStage, updatePipelineIssue, PIPELINE_STAGE_LABELS } from '../../../services/api';+import { useAsyncAction } from '../../../hooks/useAsyncAction';const STATUS_LABEL = {empty: 'Not started',@@ -40,24 +41,27 @@ export default function TextStagePanel({const stage = issue.stages?.[stageId] || { status: 'empty', input: '', output: '' };const [draftOutput, setDraftOutput] = useState(stage.output || '');const [draftInput, setDraftInput] = useState(stage.input || '');- const [generating, setGenerating] = useState(stage.status === 'generating');- const [saving, setSaving] = useState(false);+ // Server-pushed in-flight state — separate from the hook's local-action+ // running flag so an auto-run kicked off elsewhere still keeps the+ // Generate button locked.+ const [serverGenerating, setServerGenerating] = useState(stage.status === 'generating');// Reset local edits when the stage record changes from the parent (e.g.// auto-run pushed a new output).useEffect(() => {setDraftOutput(stage.output || '');setDraftInput(stage.input || '');- setGenerating(stage.status === 'generating');+ setServerGenerating(stage.status === 'generating');}, [stage.output, stage.input, stage.status, stage.lastRunId]);+ const [runGenerate, localGenerating] = useAsyncAction(+ () => generatePipelineStage(issue.id, stageId, { seedInput: draftInput }),+ { errorMessage: `Failed to generate ${stageId}` },+ );+ const generating = localGenerating || serverGenerating;+const handleGenerate = async () => {- setGenerating(true);- const result = await generatePipelineStage(issue.id, stageId, { seedInput: draftInput }).catch((err) => {- toast.error(err.message || `Failed to generate ${stageId}`);- return null;- });- setGenerating(false);+ const result = await runGenerate();if (!result) return;onStageUpdate?.(stageId, result.stage);toast.success(`${PIPELINE_STAGE_LABELS[stageId]} generated`);@@ -65,9 +69,8 @@ export default function TextStagePanel({const dirty = draftOutput !== (stage.output || '') || draftInput !== (stage.input || '');- const handleSave = async () => {- setSaving(true);- const patch = {+ const [runSave, saving] = useAsyncAction(+ () => updatePipelineIssue(issue.id, {stages: {[stageId]: {status: 'edited',@@ -75,12 +78,12 @@ export default function TextStagePanel({output: draftOutput,},},- };- const updated = await updatePipelineIssue(issue.id, patch).catch((err) => {- toast.error(err.message || 'Save failed');- return null;- });- setSaving(false);+ }),+ { errorMessage: 'Save failed' },+ );++ const handleSave = async () => {+ const updated = await runSave();if (!updated) return;onStageUpdate?.(stageId, updated.stages[stageId], updated);toast.success(`${PIPELINE_STAGE_LABELS[stageId]} saved`);diff --git a/client/src/hooks/useAsyncAction.js b/client/src/hooks/useAsyncAction.jsnew file mode 100644index 0000000000..fc00925ffb--- /dev/null+++ b/client/src/hooks/useAsyncAction.js@@ -0,0 +1,33 @@+import { useState, useCallback } from 'react';+import toast from '../components/ui/Toast';++/**+ * Wraps an async action with `running` state and toast-on-error.+ *+ * Usage:+ * const [run, running] = useAsyncAction(async (id) => {+ * return await someApi(id);+ * }, { errorMessage: 'Failed to do thing' });+ * // ...+ * <button disabled={running} onClick={() => run(thing.id)}>Go</button>+ *+ * The fn return value is what `run` resolves to. If the fn throws, the+ * error is toasted and `run` resolves to `null`. The hook only models a+ * single boolean in-flight flag — keyed/indexed loading states (e.g. "which+ * row is saving") need a different abstraction.+ */+export function useAsyncAction(fn, { errorMessage } = {}) {+ const [running, setRunning] = useState(false);+ const run = useCallback(async (...args) => {+ setRunning(true);+ const result = await Promise.resolve(fn(...args)).catch((err) => {+ toast.error(err?.message || errorMessage || 'Action failed');+ return null;+ });+ setRunning(false);+ return result;+ }, [fn, errorMessage]);+ return [run, running];+}++export default useAsyncAction;