Skip to content

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

refactor([importer-progress-hook]): extract useImporterProgress + shared stage-icon lookup

[._.]/ Adam Eivy6c894c86d749
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index c7af952c35..496d0a4d93 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -32,6 +32,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useSseProgress` | Generic JSON-frame EventSource subscriber. | New SSE progress stream — start here, build on top. |
| `useModelDownloadStatus` | Image/video model cache-status + SSE pre-download. | Surfacing "Available" vs "Download" badge inline in the gen form. |
| `useImageGenProgress` | Live diffusion progress for an image-gen call. | Showing per-call image-gen progress. |
+| `useImporterProgress` | Live analyze-phase stage checklist via the `importer:progress` socket (runId-filtered); exports `stageStatusIcon` for the status→icon lookup. | Importer analyze progress UI only. |
| `useMediaJobProgress` | Live progress for a single `mediaJobQueue` job. | Subscribing to a known media-job id. |
| `useMediaJobSse` | Imperative per-job `/{kind}-gen/:id/events` SSE; `attach()` returns a Promise that settles on the terminal frame. | POST-then-attach media render flows that await completion (ImageGen/VideoGen). |
| `useOpenClawStream` | OpenClaw SSE chat stream. | OpenClaw file-browser chat surface only. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 336e3e0b01..62b596a6db 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -42,6 +42,7 @@ export * from './useSharingNotifications.js';
// === Progress & streaming (SSE / socket) ===
export * from './useImageGenProgress.js';
+export * from './useImporterProgress.js';
export * from './useOpenClawStream.js';
export * from './usePipelineAutoRunProgress.js';
export * from './usePipelineEditorialProgress.js';
diff --git a/client/src/hooks/useImporterProgress.js b/client/src/hooks/useImporterProgress.js
new file mode 100644
index 0000000000..10194a438f
--- /dev/null
+++ b/client/src/hooks/useImporterProgress.js
@@ -0,0 +1,63 @@
+import { useCallback, useEffect, useRef, useState } from 'react';
+import { CheckCircle2, AlertTriangle, Loader2, Circle } from 'lucide-react';
+import socket from '../services/socket';
+
+// Maps an analyze-stage `status` to the lucide icon + className that renders
+// it in the importer checklist. Co-located with the hook so the socket frame
+// shape and its rendering stay in one place; consumers spread the entry as
+// JSX props: `<Icon className={className} />`. Falls back to the `pending`
+// row for unknown statuses (a future server status won't crash the list).
+const STAGE_STATUS_ICON = {
+ done: { Icon: CheckCircle2, className: 'w-4 h-4 text-port-success flex-shrink-0' },
+ error: { Icon: AlertTriangle, className: 'w-4 h-4 text-port-warning flex-shrink-0' },
+ running: { Icon: Loader2, className: 'w-4 h-4 text-port-accent animate-spin flex-shrink-0' },
+ pending: { Icon: Circle, className: 'w-4 h-4 text-port-text-muted/40 flex-shrink-0' },
+};
+
+export function stageStatusIcon(status) {
+ return STAGE_STATUS_ICON[status] || STAGE_STATUS_ICON.pending;
+}
+
+// Subscribes to the `importer:progress` socket stream and tracks the live
+// analyze-phase stage checklist. The server broadcasts to all clients
+// (single-user trust model), so each frame carries a `runId`: we seed the
+// stage list on a `start` frame and ignore `stage` frames that don't match
+// the run that `start` opened — guards against a straggler from a prior run.
+//
+// Returns `{ stages, reset }`. `stages` is `null` until the first `start`
+// frame, then an array of `{ id, label, status }` where status is
+// 'pending' | 'running' | 'done' | 'error'. Call `reset()` before kicking off
+// a fresh analyze to clear the prior run's checklist; the next `start` frame
+// repopulates it (a generic spinner shows in the gap).
+export function useImporterProgress() {
+ const [stages, setStages] = useState(null);
+ const activeRunIdRef = useRef(null);
+
+ const reset = useCallback(() => {
+ activeRunIdRef.current = null;
+ setStages(null);
+ }, []);
+
+ useEffect(() => {
+ const onProgress = (ev) => {
+ if (!ev || typeof ev !== 'object') return;
+ if (ev.type === 'start') {
+ activeRunIdRef.current = ev.runId;
+ setStages(
+ (Array.isArray(ev.stages) ? ev.stages : []).map((s) => ({ ...s, status: 'pending' })),
+ );
+ return;
+ }
+ if (ev.type === 'stage') {
+ if (ev.runId !== activeRunIdRef.current) return;
+ setStages((prev) =>
+ Array.isArray(prev) ? prev.map((s) => (s.id === ev.id ? { ...s, status: ev.status } : s)) : prev,
+ );
+ }
+ };
+ socket.on('importer:progress', onProgress);
+ return () => socket.off('importer:progress', onProgress);
+ }, []);
+
+ return { stages, reset };
+}
diff --git a/client/src/hooks/useImporterProgress.test.jsx b/client/src/hooks/useImporterProgress.test.jsx
new file mode 100644
index 0000000000..862d0666be
--- /dev/null
+++ b/client/src/hooks/useImporterProgress.test.jsx
@@ -0,0 +1,83 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { renderHook, act, cleanup } from '@testing-library/react';
+import { CheckCircle2, AlertTriangle, Loader2, Circle } from 'lucide-react';
+
+// Mock the socket module so the test can drive the `importer:progress` handler
+// the hook registers with `on()`.
+const handlers = new Map();
+vi.mock('../services/socket', () => ({
+ default: {
+ on: (event, fn) => { handlers.set(event, fn); },
+ off: (event, fn) => { if (handlers.get(event) === fn) handlers.delete(event); },
+ },
+}));
+
+import { useImporterProgress, stageStatusIcon } from './useImporterProgress.js';
+
+const fire = (payload) => act(() => { handlers.get('importer:progress')?.(payload); });
+
+describe('useImporterProgress', () => {
+ beforeEach(() => handlers.clear());
+ afterEach(cleanup);
+
+ it('starts with null stages', () => {
+ const { result } = renderHook(() => useImporterProgress());
+ expect(result.current.stages).toBeNull();
+ });
+
+ it('seeds the checklist from a start frame as all-pending', () => {
+ const { result } = renderHook(() => useImporterProgress());
+ fire({ type: 'start', runId: 'r1', stages: [{ id: 'canon', label: 'Canon' }, { id: 'arc', label: 'Arc' }] });
+ expect(result.current.stages).toEqual([
+ { id: 'canon', label: 'Canon', status: 'pending' },
+ { id: 'arc', label: 'Arc', status: 'pending' },
+ ]);
+ });
+
+ it('applies a matching-runId stage frame to the named stage only', () => {
+ const { result } = renderHook(() => useImporterProgress());
+ fire({ type: 'start', runId: 'r1', stages: [{ id: 'canon', label: 'Canon' }, { id: 'arc', label: 'Arc' }] });
+ fire({ type: 'stage', runId: 'r1', id: 'canon', status: 'running' });
+ expect(result.current.stages).toEqual([
+ { id: 'canon', label: 'Canon', status: 'running' },
+ { id: 'arc', label: 'Arc', status: 'pending' },
+ ]);
+ });
+
+ it('ignores stage frames from a stale run', () => {
+ const { result } = renderHook(() => useImporterProgress());
+ fire({ type: 'start', runId: 'r2', stages: [{ id: 'canon', label: 'Canon' }] });
+ fire({ type: 'stage', runId: 'r1', id: 'canon', status: 'done' });
+ expect(result.current.stages).toEqual([{ id: 'canon', label: 'Canon', status: 'pending' }]);
+ });
+
+ it('reset() clears the checklist and the active run, so a stale stage frame is ignored after', () => {
+ const { result } = renderHook(() => useImporterProgress());
+ fire({ type: 'start', runId: 'r1', stages: [{ id: 'canon', label: 'Canon' }] });
+ act(() => result.current.reset());
+ expect(result.current.stages).toBeNull();
+ // A straggler `stage` from the reset run no longer matches any active run.
+ fire({ type: 'stage', runId: 'r1', id: 'canon', status: 'done' });
+ expect(result.current.stages).toBeNull();
+ });
+
+ it('ignores malformed frames', () => {
+ const { result } = renderHook(() => useImporterProgress());
+ fire(null);
+ fire('nope');
+ expect(result.current.stages).toBeNull();
+ });
+});
+
+describe('stageStatusIcon', () => {
+ it('maps each known status to its icon', () => {
+ expect(stageStatusIcon('done').Icon).toBe(CheckCircle2);
+ expect(stageStatusIcon('error').Icon).toBe(AlertTriangle);
+ expect(stageStatusIcon('running').Icon).toBe(Loader2);
+ expect(stageStatusIcon('pending').Icon).toBe(Circle);
+ });
+
+ it('falls back to the pending row for an unknown status', () => {
+ expect(stageStatusIcon('whatever')).toBe(stageStatusIcon('pending'));
+ });
+});
diff --git a/client/src/pages/Importer.jsx b/client/src/pages/Importer.jsx
index e5f3cd66d8..efde776b88 100644
--- a/client/src/pages/Importer.jsx
+++ b/client/src/pages/Importer.jsx
@@ -1,9 +1,9 @@
import { memo, useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
-import { FileInput, Loader2, ArrowLeft, CheckCircle2, AlertTriangle, ChevronDown, ChevronRight, Wand2, Circle } from 'lucide-react';
+import { FileInput, Loader2, ArrowLeft, CheckCircle2, AlertTriangle, ChevronDown, ChevronRight, Wand2 } from 'lucide-react';
import toast from '../components/ui/Toast';
-import socket from '../services/socket';
import { useAsyncAction } from '../hooks/useAsyncAction';
+import { useImporterProgress, stageStatusIcon } from '../hooks/useImporterProgress';
import { STORY_SHAPES } from '../components/pipeline/StoryShapes';
import EntryCard from '../components/universe/EntryCard';
import { previewCanonFragments } from '../lib/canonPrompt';
@@ -87,32 +87,8 @@ export default function Importer() {
const [preview, setPreview] = useState(null);
// Live analyze-phase stage progress, driven by `importer:progress` socket
- // frames. `null` = no run started yet (or reset before a fresh Analyze).
- // The server broadcasts to all clients (single-user trust model), so each
- // frame carries a `runId` and we ignore stage frames that don't match the
- // run a `start` frame opened — guards against a straggler from a prior run.
- const [analyzeStages, setAnalyzeStages] = useState(null);
- const activeRunIdRef = useRef(null);
- useEffect(() => {
- const onProgress = (ev) => {
- if (!ev || typeof ev !== 'object') return;
- if (ev.type === 'start') {
- activeRunIdRef.current = ev.runId;
- setAnalyzeStages(
- (Array.isArray(ev.stages) ? ev.stages : []).map((s) => ({ ...s, status: 'pending' })),
- );
- return;
- }
- if (ev.type === 'stage') {
- if (ev.runId !== activeRunIdRef.current) return;
- setAnalyzeStages((prev) =>
- Array.isArray(prev) ? prev.map((s) => (s.id === ev.id ? { ...s, status: ev.status } : s)) : prev,
- );
- }
- };
- socket.on('importer:progress', onProgress);
- return () => socket.off('importer:progress', onProgress);
- }, []);
+ // frames. `null` = no run started yet. See `useImporterProgress`.
+ const { stages: analyzeStages, reset: resetAnalyzeStages } = useImporterProgress();
// Server is the source of truth for the enums — a prior client-side copy
// (`IMPORTER_ARC_ROLES_FALLBACK`) silently drifted, so we wait on the GET
@@ -213,8 +189,7 @@ export default function Importer() {
abortConfigRef.current?.abort();
// Clear any prior run's checklist; the server's `start` frame repopulates
// it once the first AI pass begins (a generic spinner shows until then).
- activeRunIdRef.current = null;
- setAnalyzeStages(null);
+ resetAnalyzeStages();
const payload = {
universeName: intake.universeName.trim(),
seriesName: intake.seriesName.trim(),
@@ -655,22 +630,17 @@ function ImporterProgress({ stages }) {
</p>
{Array.isArray(stages) && stages.length > 0 ? (
<ul className="space-y-1.5 mt-2">
- {stages.map((s) => (
- <li key={s.id} className="flex items-center gap-2 text-sm">
- {s.status === 'done' ? (
- <CheckCircle2 className="w-4 h-4 text-port-success flex-shrink-0" />
- ) : s.status === 'error' ? (
- <AlertTriangle className="w-4 h-4 text-port-warning flex-shrink-0" />
- ) : s.status === 'running' ? (
- <Loader2 className="w-4 h-4 text-port-accent animate-spin flex-shrink-0" />
- ) : (
- <Circle className="w-4 h-4 text-port-text-muted/40 flex-shrink-0" />
- )}
- <span className={s.status === 'running' ? 'text-port-text' : 'text-port-text-muted'}>
- {s.label}
- </span>
- </li>
- ))}
+ {stages.map((s) => {
+ const { Icon, className } = stageStatusIcon(s.status);
+ return (
+ <li key={s.id} className="flex items-center gap-2 text-sm">
+ <Icon className={className} />
+ <span className={s.status === 'running' ? 'text-port-text' : 'text-port-text-muted'}>
+ {s.label}
+ </span>
+ </li>
+ );
+ })}
</ul>
) : (
<p className="text-xs text-port-text-muted">Starting…</p>