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
fix: stream FableLoom editorial and production progress (#8544)
[._.]/ Adam Eivyf95ddc2f838a
diff --git a/client/src/components/fableloom/LoomEditorialAutomation.jsx b/client/src/components/fableloom/LoomEditorialAutomation.jsxindex 467f3547b4..7868280a97 100644--- a/client/src/components/fableloom/LoomEditorialAutomation.jsx+++ b/client/src/components/fableloom/LoomEditorialAutomation.jsx@@ -6,13 +6,12 @@ import {import ProviderModelSelector from '../ProviderModelSelector';import toast from '../ui/Toast';import { useAsyncAction } from '../../hooks/useAsyncAction';-import { useAutoRefetch } from '../../hooks/useAutoRefetch.js';+import { useFableLoomRun } from '../../hooks/useFableLoomRun';import useFableLoomAiRun from '../../hooks/useFableLoomAiRun';import useProviderModels from '../../hooks/useProviderModels';import {cancelLoomEditorialAutopilot,getLoom,- getLoomEditorialAutopilotRun,getLoomEditorialAutopilotStatus,remediateLoomEditorial,reviewLoomPlaythroughs,@@ -22,7 +21,6 @@ import { effectiveModelFor, effortAwareModelOptions } from '../../utils/providerimport LoomAiRunStatus from './LoomAiRunStatus';const ACTIVE_STATUSES = new Set(['running', 'canceling']);-const TERMINAL_STATUSES = new Set(['completed', 'paused', 'failed', 'canceled']);const routePayload = (route) => ({...(route.providerId ? { providerId: route.providerId } : {}),@@ -85,8 +83,19 @@ export default function LoomEditorialAutomation({ loom, dirty, onLoomUpdate }) {const [maxRounds, setMaxRounds] = useState(3);const [selfImprove, setSelfImprove] = useState(false);const [result, setResult] = useState(null);- const [autopilotRun, setAutopilotRun] = useState(null);- const handledTerminalRunRef = useRef(null);+ const loomIdentityRef = useRef(loom.id);+ loomIdentityRef.current = loom.id;+ const { run: autopilotRun, applyRun: setAutopilotRun } = useFableLoomRun({+ loomId: loom.id,+ event: 'fableloom:editorial:run',+ loadRun: () => getLoomEditorialAutopilotStatus(loom.id, { silent: true }).then(response => response.run),+ onTerminal: (run, isCurrent) => {+ setResult({ type: 'autopilot', run });+ getLoom(loom.id, { silent: true }).then(updated => {+ if (isCurrent()) onLoomUpdate(updated);+ }).catch(() => {});+ },+ });const remediationAi = useFableLoomAiRun();const playtestAi = useFableLoomAiRun();const { providers, activeProviderId, loading: providersLoading } = useProviderModels({@@ -99,53 +108,17 @@ export default function LoomEditorialAutomation({ loom, dirty, onLoomUpdate }) {const selectedModel = effectiveModelFor(selectedProvider, route.model);const routeBody = useMemo(() => routePayload(route), [route]);- useEffect(() => {- setResult(null);- setAutopilotRun(null);- handledTerminalRunRef.current = null;- let ignore = false;- getLoomEditorialAutopilotStatus(loom.id, { silent: true })- .then(({ run }) => {- if (ignore || !run) return;- setAutopilotRun(run);- if (ACTIVE_STATUSES.has(run.status)) {- setRoute({ providerId: run.route?.providerId || '', model: run.route?.model || '', effort: run.route?.effort || '' });- setMode(run.mode || 'series');- setMaxRounds(run.maxRounds);- setSelfImprove(run.selfImproveEnabled === true);- }- })- .catch(() => {});- return () => { ignore = true; };- }, [loom.id]);+ useEffect(() => { setResult(null); }, [loom.id]);const autopilotActive = ACTIVE_STATUSES.has(autopilotRun?.status);- // useAutoRefetch clears its interval when `enabled` drops, but it cannot cancel- // a request already in flight. Stamp what each poll asked about so a reply that- // lands after the loom or the run changed can't overwrite newer state — this is- // the `ignore` flag the old per-effect cleanup owned, and the same identity-ref- // pattern LoomProductionPanel uses for its batch poll.- const autopilotIdentityRef = useRef(null);- autopilotIdentityRef.current = `${loom.id}:${autopilotRun?.id ?? ''}`;- const refreshAutopilotRun = () => {- const identity = autopilotIdentityRef.current;- return getLoomEditorialAutopilotRun(loom.id, autopilotRun.id, { silent: true })- .then((run) => { if (identity === autopilotIdentityRef.current) setAutopilotRun(run); })- .catch(() => {});- };- useAutoRefetch(refreshAutopilotRun, 2000, {- enabled: autopilotActive && Boolean(autopilotRun?.id),- immediate: false,- pollOnly: true,- });-useEffect(() => {- if (!TERMINAL_STATUSES.has(autopilotRun?.status)- || handledTerminalRunRef.current === autopilotRun.id) return;- handledTerminalRunRef.current = autopilotRun.id;- setResult({ type: 'autopilot', run: autopilotRun });- getLoom(loom.id, { silent: true }).then(onLoomUpdate).catch(() => {});- }, [autopilotRun, loom.id, onLoomUpdate]);+ if (!ACTIVE_STATUSES.has(autopilotRun?.status)) return;+ setResult(null);+ setRoute({ providerId: autopilotRun.route?.providerId || '', model: autopilotRun.route?.model || '', effort: autopilotRun.route?.effort || '' });+ setMode(autopilotRun.mode || 'series');+ setMaxRounds(autopilotRun.maxRounds);+ setSelfImprove(autopilotRun.selfImproveEnabled === true);+ }, [autopilotRun?.id]);const [remediate, remediating] = useAsyncAction(async () => {const operationId = remediationAi.begin();@@ -186,9 +159,9 @@ export default function LoomEditorialAutomation({ loom, dirty, onLoomUpdate }) {...(mode === 'planning' ? { mode } : {}),...(selfImprove ? { selfImprove: true } : {}),}, { silent: true });- handledTerminalRunRef.current = null;- setAutopilotRun(run);+ if (loomIdentityRef.current !== loom.id) return;setResult(null);+ setAutopilotRun(run);toast.success(run.alreadyRunning ? 'Reattached to the active editorial autopilot' : 'Editorial autopilot started');}, { errorMessage: 'Could not start editorial autopilot' });@@ -200,7 +173,7 @@ export default function LoomEditorialAutomation({ loom, dirty, onLoomUpdate }) {const busy = remediating || playtesting || startingAutopilot || cancelingAutopilot || autopilotActive;const blocked = dirty || !loom.episodes.length;const response = result?.response;- const shownRun = result?.type === 'autopilot' ? result.run : result ? null : autopilotRun;+ const shownRun = autopilotActive || result?.type === 'autopilot' ? autopilotRun : result ? null : autopilotRun;const diagnostics = result?.type === 'remediation' ? response?.diagnostics : null;const deterministic = result?.type === 'playtest'? response?.deterministicdiff --git a/client/src/components/fableloom/LoomEditorialAutomation.test.jsx b/client/src/components/fableloom/LoomEditorialAutomation.test.jsxindex 06e10a425f..badf480f56 100644--- a/client/src/components/fableloom/LoomEditorialAutomation.test.jsx+++ b/client/src/components/fableloom/LoomEditorialAutomation.test.jsx@@ -1,5 +1,5 @@import { beforeEach, describe, expect, it, vi } from 'vitest';-import { render, screen, waitFor } from '@testing-library/react';+import { act, render, screen, waitFor } from '@testing-library/react';import userEvent from '@testing-library/user-event';import { MemoryRouter } from 'react-router';@@ -14,10 +14,11 @@ vi.mock('../../services/api', () => ({startLoomEditorialAutopilot: vi.fn(),}));vi.mock('../../services/socket', () => ({- default: { on: vi.fn(), off: vi.fn() },+ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn() },}));import * as api from '../../services/api';+import socket from '../../services/socket';import LoomEditorialAutomation from './LoomEditorialAutomation';const loom = {@@ -148,7 +149,7 @@ describe('LoomEditorialAutomation', () => {it('restores the active run configuration when reopening the editor', async () => {api.getLoomEditorialAutopilotStatus.mockResolvedValue({ run: {- id: 'active-planning-run', status: 'running', mode: 'planning', maxRounds: 2, round: 1,+ id: 'active-planning-run', loomId: 'loom-1', status: 'running', mode: 'planning', maxRounds: 2, round: 1,route: { providerId: 'codex', model: 'gpt-5', effort: 'low' }, selfImproveEnabled: false,} });renderPanel();@@ -245,3 +246,67 @@ describe('LoomEditorialAutomation', () => {expect(screen.getByText(/Save the current series-plan edits/)).toBeInTheDocument();});});++const editorialEvent = payload => socket.on.mock.calls.filter(([name]) => name === 'fableloom:editorial:run').at(-1)[1](payload);+const reconnect = () => socket.on.mock.calls.filter(([name]) => name === 'connect').at(-1)[1]();+const editorialRun = (patch = {}) => ({+ id: 'run-1', loomId: 'loom-1', createdAt: '2026-01-01T00:00:00Z',+ revision: 1, status: 'running', round: 1, maxRounds: 3, rounds: [], residualFindings: [],+ message: 'Editor running', ...patch,+});++it('renders snapshots without timer reads and reconciles reconnect/reshow once', async () => {+ const onLoomUpdate = vi.fn();+ api.getLoom.mockResolvedValue(loom);+ api.getLoomEditorialAutopilotStatus.mockResolvedValue({ run: editorialRun() });+ renderPanel({ onLoomUpdate });+ await screen.findAllByText('Editor running');+ vi.useFakeTimers();+ await act(async () => { await vi.advanceTimersByTimeAsync(10000); });+ vi.useRealTimers();+ expect(api.getLoomEditorialAutopilotStatus).toHaveBeenCalledTimes(1);+ expect(api.getLoomEditorialAutopilotRun).not.toHaveBeenCalled();+ await act(async () => editorialEvent(editorialRun({ revision: 2, message: 'Reviewer running' })));+ expect(screen.getAllByText('Reviewer running')[0]).toBeInTheDocument();+ await act(async () => editorialEvent(editorialRun({ loomId: 'other', revision: 3, message: 'Wrong loom' })));+ expect(screen.queryByText('Wrong loom')).not.toBeInTheDocument();+ const completed = editorialRun({ status: 'completed', revision: 3, message: 'Review finished' });+ api.getLoomEditorialAutopilotStatus.mockResolvedValue({ run: completed });+ await act(async () => { editorialEvent(completed); editorialEvent({ ...completed, revision: 4 }); });+ expect(onLoomUpdate).toHaveBeenCalledTimes(1);+ await act(async () => reconnect());+ expect(api.getLoomEditorialAutopilotStatus).toHaveBeenCalledTimes(2);+ const original = Object.getOwnPropertyDescriptor(document, 'visibilityState');+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'hidden' });+ act(() => document.dispatchEvent(new Event('visibilitychange')));+ Object.defineProperty(document, 'visibilityState', { configurable: true, value: 'visible' });+ await act(async () => {+ document.dispatchEvent(new Event('visibilitychange'));+ document.dispatchEvent(new Event('visibilitychange'));+ });+ if (original) Object.defineProperty(document, 'visibilityState', original);+ else delete document.visibilityState;+ expect(api.getLoomEditorialAutopilotStatus).toHaveBeenCalledTimes(3);+ expect(onLoomUpdate).toHaveBeenCalledTimes(1);+});++it('drops late initial reads, retired-run events and old-loom terminal refreshes', async () => {+ let resolveRead;+ let resolveLoom;+ api.getLoomEditorialAutopilotStatus.mockReturnValueOnce(new Promise(resolve => { resolveRead = resolve; }));+ api.getLoom.mockReturnValueOnce(new Promise(resolve => { resolveLoom = resolve; }));+ const onLoomUpdate = vi.fn();+ const panel = renderPanel({ onLoomUpdate });+ await waitFor(() => expect(resolveRead).toBeTypeOf('function'));+ await act(async () => editorialEvent(editorialRun({ revision: 2, message: 'New progress' })));+ await act(async () => resolveRead({ run: editorialRun({ message: 'Stale read' }) }));+ expect(screen.getAllByText('New progress')[0]).toBeInTheDocument();+ await act(async () => editorialEvent(editorialRun({ id: 'run-2', createdAt: '2026-01-02T00:00:00Z', message: 'New run' })));+ await act(async () => editorialEvent(editorialRun({ revision: 9, status: 'failed', message: 'Retired run' })));+ expect(screen.getAllByText('New run')[0]).toBeInTheDocument();+ await act(async () => editorialEvent(editorialRun({ id: 'run-2', createdAt: '2026-01-02T00:00:00Z', revision: 2, status: 'completed' })));+ panel.rerender(<MemoryRouter><LoomEditorialAutomation loom={{ ...loom, id: 'loom-2' }} dirty={false} onLoomUpdate={onLoomUpdate} /></MemoryRouter>);+ await act(async () => resolveLoom(loom));+ expect(onLoomUpdate).not.toHaveBeenCalled();+ expect(screen.queryByText('New run')).not.toBeInTheDocument();+});diff --git a/client/src/components/fableloom/LoomProductionPanel.jsx b/client/src/components/fableloom/LoomProductionPanel.jsxindex 717c4668a0..f31c26c995 100644--- a/client/src/components/fableloom/LoomProductionPanel.jsx+++ b/client/src/components/fableloom/LoomProductionPanel.jsx@@ -22,11 +22,11 @@ import {StopCircle,} from 'lucide-react';import { useAsyncAction } from '../../hooks/useAsyncAction';-import { useAutoRefetch } from '../../hooks/useAutoRefetch.js';+import { useFableLoomRun } from '../../hooks/useFableLoomRun';import BackendChipStrip from '../media/BackendChipStrip';import {cancelLoomEpisodeProductionBatch,- getLoomEpisodeProductionBatch,+ getLoomEpisodeProductionBatchStatus,listImageModels,listVideoModels,planLoomEpisodeProduction,@@ -78,7 +78,6 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode, onLooconst [assetScope, setAssetScope] = useState('images');const [plan, setPlan] = useState(null);const [planKey, setPlanKey] = useState(null);- const [activeBatchRun, setActiveBatchRun] = useState(null);const savedRender = asFableLoomRenderPreferences(loom.renderSettings);const [imageMode, setImageMode] = useState(savedRender.imageMode);const [imageModel, setImageModel] = useState(savedRender.imageModel);@@ -175,33 +174,12 @@ export default function LoomProductionPanel({ loom, episode, onSelectNode, onLoofetchPlan(mode);}, [planInputKey]);- useEffect(() => {- setActiveBatchRun(null);- }, [productionIdentity]);-- // Batch run polling. Only reached while a run is in progress, so the- // non-null read of activeBatchRun below is guarded by `enabled`.- const refreshBatchRun = () => getLoomEpisodeProductionBatch(- activeBatchRun.loomId,- activeBatchRun.episodeId,- activeBatchRun.id,- { silent: true },- )- .then((updated) => {- if (!updated) return;- if (`${updated.loomId}:${updated.episodeId}` !== productionIdentityRef.current) return;- setActiveBatchRun(updated);- if (updated.status === 'completed' || updated.status === 'canceled' || updated.status === 'failed') {- fetchPlan(mode);- }- })- .catch(() => {- // Polling is best-effort; the next tick can reattach to the run.- });- useAutoRefetch(refreshBatchRun, 2000, {- enabled: activeBatchRun?.status === 'in_progress',- immediate: false,- pollOnly: true,+ const { run: activeBatchRun, applyRun: setActiveBatchRun } = useFableLoomRun({+ loomId: loom.id,+ episodeId: episode.id,+ event: 'fableloom:production:run',+ loadRun: () => getLoomEpisodeProductionBatchStatus(loom.id, episode.id, { silent: true }).then(response => response.run),+ onTerminal: () => fetchPlan(mode),});const [startBatch, startingBatch] = useAsyncAction(async () => {diff --git a/client/src/components/fableloom/LoomProductionPanel.test.jsx b/client/src/components/fableloom/LoomProductionPanel.test.jsxindex b8ffc51565..e689508473 100644--- a/client/src/components/fableloom/LoomProductionPanel.test.jsx+++ b/client/src/components/fableloom/LoomProductionPanel.test.jsx@@ -2,8 +2,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';import LoomProductionPanel from './LoomProductionPanel';import * as api from '../../services/api';+import socket from '../../services/socket';vi.mock('../../services/api');+vi.mock('../../services/socket', () => ({ default: { on: vi.fn(), off: vi.fn(), emit: vi.fn() } }));describe('LoomProductionPanel', () => {const sampleLoom = { id: 'loom-1', name: 'Test Loom' };@@ -34,9 +36,10 @@ describe('LoomProductionPanel', () => {beforeEach(() => {vi.clearAllMocks();+ api.getLoomEpisodeProductionBatchStatus.mockResolvedValue({ run: null });api.planLoomEpisodeProduction.mockResolvedValue(samplePlan);api.startLoomEpisodeProductionBatch.mockResolvedValue({- id: 'batch-1',+ id: 'batch-1', loomId: 'loom-1', episodeId: 'ep-1',status: 'in_progress',summary: { total: 6, completed: 2 },});@@ -211,4 +214,36 @@ describe('LoomProductionPanel', () => {expect(screen.getByText('Episode 2 asset')).toBeInTheDocument();});+ it('reattaches and applies scoped batch events, refreshing once per terminal attempt without polling', async () => {+ const run = { id: 'batch-live', loomId: 'loom-1', episodeId: 'ep-1', status: 'in_progress', revision: 1, attempt: 1, summary: { total: 6, completed: 1 } };+ api.getLoomEpisodeProductionBatchStatus.mockResolvedValue({ run });+ const panel = render(<LoomProductionPanel loom={sampleLoom} episode={sampleEpisode} />);+ await waitFor(() => expect(api.getLoomEpisodeProductionBatchStatus).toHaveBeenCalledTimes(1));+ const emit = payload => socket.on.mock.calls.filter(([name]) => name === 'fableloom:production:run').at(-1)[1](payload);+ await act(async () => {});+ vi.useFakeTimers();+ await act(async () => { await vi.advanceTimersByTimeAsync(10000); });+ vi.useRealTimers();+ expect(api.getLoomEpisodeProductionBatchStatus).toHaveBeenCalledTimes(1);+ expect(api.getLoomEpisodeProductionBatch).not.toHaveBeenCalled();+ expect(api.planLoomEpisodeProduction).toHaveBeenCalledTimes(1);+ await act(async () => emit({ ...run, episodeId: 'other', status: 'completed', revision: 2 }));+ expect(api.planLoomEpisodeProduction).toHaveBeenCalledTimes(1);+ await act(async () => emit({ ...run, status: 'failed', error: 'Example render failed', revision: 2 }));+ expect(screen.getByText(/Example render failed/)).toBeInTheDocument();+ expect(api.planLoomEpisodeProduction).toHaveBeenCalledTimes(2);+ await act(async () => emit({ ...run, status: 'failed', revision: 3 }));+ expect(api.planLoomEpisodeProduction).toHaveBeenCalledTimes(2);+ await act(async () => emit({ ...run, attempt: 2, revision: 4 }));+ await act(async () => emit({ ...run, attempt: 2, revision: 5, status: 'completed' }));+ expect(api.planLoomEpisodeProduction).toHaveBeenCalledTimes(3);+ let resolveRead;+ api.getLoomEpisodeProductionBatchStatus.mockReturnValueOnce(new Promise(resolve => { resolveRead = resolve; }));+ await act(async () => { socket.on.mock.calls.filter(([name]) => name === 'connect').at(-1)[1](); });+ panel.rerender(<LoomProductionPanel loom={sampleLoom} episode={{ id: 'ep-2' }} />);+ await act(async () => resolveRead({ run }));+ expect(screen.queryByText(/Example render failed/)).not.toBeInTheDocument();+ expect(api.getLoomEpisodeProductionBatchStatus).toHaveBeenLastCalledWith('loom-1', 'ep-2', { silent: true });+ });+});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 81b367262d..666183cfb1 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -90,6 +90,8 @@ grep -i "what you want to do" client/src/hooks/README.md| `useProcessSnapshot` | PM2 snapshots from entry reads and server pushes, with reconnect/reshow recovery and stale-read protection. | Process lists and native-launch panels; pass an app id for custom PM2 homes. || `useCosTaskUpdates` | Shared five-event CoS task lifecycle subscription; re-subscribes on socket reconnect and forwards normalized task updates to the current callback. | A CoS task surface with its own task-status reducer. || `useSocketResource` | Initial resource read plus global/room-event, reconnect and tab-show reconciliation; single-flight reads, identity guards and immediate mutation updates. | Views replacing content polls with existing socket invalidations. |+| `useSocketResource` | Initial resource read plus room/broadcast event, reconnect and tab-show reconciliation; single-flight reads, identity guards and immediate mutation updates. | Views replacing content polls with existing socket invalidations. |+| `useFableLoomRun` | Revisioned editorial/production snapshots, identity-safe mutation replies and entry/reconnect/reshow recovery. | FableLoom run views. || `useSocketSubscription` | Refcounted `<namespace>:subscribe`/`unsubscribe` for a `registerSubscriber` room: the first mounted consumer subscribes and re-emits on every socket reconnect, the last to unmount unsubscribes, and `onResubscribe` refetches whatever a consumer may have missed while disconnected. | Any hook/page that emits a literal `<ns>:subscribe` for `cos`/`errors`/`notifications`/`agents`/`instances`/`loops`/`beeper` — don't hand-roll the reconnect dance; `client/src/socketSubscriptionConventions.test.js` enforces this. || `useAccountSyncStatus` | Per-account busy/auth state and deduplicated HTTP/socket sync outcomes. | Calendar and Messages sync controls. || `useSocket` | Shared socket instance + connection status. | You need to subscribe to a socket event. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 1d2bf317ee..6cfb89a165 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -250,3 +250,4 @@ export * from './useGoalOrganize.js';export * from './useSocketResource.js';export * from './useProcessSnapshot.js';+export * from './useFableLoomRun.js';diff --git a/client/src/hooks/useFableLoomRun.js b/client/src/hooks/useFableLoomRun.jsnew file mode 100644index 0000000000..d71e6a1ef7--- /dev/null+++ b/client/src/hooks/useFableLoomRun.js@@ -0,0 +1,92 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import socket from '../services/socket';+import { useSocketSubscription } from './useSocketSubscription';+import { useVisibilityEvent } from './useVisibilityEvent';++const terminal = run => ['completed', 'paused', 'failed', 'canceled'].includes(run?.status);++/** Snapshot stream with entry/reconnect recovery and identity-safe mutation replies. */+export function useFableLoomRun({ loomId, episodeId = null, event, loadRun, onTerminal }) {+ const key = JSON.stringify([loomId, episodeId]);+ const [state, setState] = useState({ key, run: null });+ const callbacks = useRef({ loadRun, onTerminal });+ callbacks.current = { loadRun, onTerminal };+ const controller = useRef(null);+ const currentKey = useRef(key);+ currentKey.current = key;+ useSocketSubscription('fableloom', { onResubscribe: () => controller.current?.read() });++ useEffect(() => {+ let disposed = false;+ let current = null;+ let pending = null;+ let revision = 0;+ let reconcileAgain = false;+ const retired = new Set();+ const handled = new Set();+ const active = () => !disposed && currentKey.current === key;+ const accept = run => {+ if (!active() || !run || run.loomId !== loomId+ || (episodeId && run.episodeId !== episodeId) || retired.has(run.id)) return;+ if (current?.id === run.id && run.revision != null && current.revision >= run.revision) return;+ if (current && current.id !== run.id) {+ if (run.createdAt < current.createdAt) return;+ retired.add(current.id);+ }+ current = run;+ revision += 1;+ setState({ key, run });+ const terminalKey = `${run.id}:${run.attempt || 1}`;+ if (terminal(run) && !handled.has(terminalKey)) {+ handled.add(terminalKey);+ callbacks.current.onTerminal?.(run, () => active() && current?.id === run.id);+ }+ };+ const read = () => {+ if (!active() || document.visibilityState === 'hidden') return;+ if (pending) {+ reconcileAgain = true;+ return pending;+ }+ pending = Promise.resolve().then(async () => {+ if (!active()) return;+ do {+ reconcileAgain = false;+ const started = revision;+ await Promise.resolve().then(() => callbacks.current.loadRun()).then(run => {+ if (active() && revision === started) {+ if (run) accept(run);+ else {+ current = null;+ revision += 1;+ setState({ key, run: null });+ }+ }+ }).catch(() => {});+ } while (reconcileAgain && active() && document.visibilityState !== 'hidden');+ pending = null;+ });+ return pending;+ };+ controller.current = { key, accept, read };+ setState({ key, run: null });+ socket.on(event, accept);+ read();+ return () => {+ disposed = true;+ controller.current = null;+ socket.off(event, accept);+ };+ }, [key, loomId, episodeId, event]);++ const visibility = useRef(document.visibilityState);+ useVisibilityEvent(next => {+ const changed = next !== visibility.current;+ visibility.current = next;+ if (changed && next === 'visible') controller.current?.read();+ });+ const applyRun = useCallback(run => {+ if (controller.current?.key === key) controller.current.accept(run);+ }, [key]);+ return { run: state.key === key ? state.run : null, applyRun };+}diff --git a/client/src/services/apiFableLoom.js b/client/src/services/apiFableLoom.jsindex e859fda232..58756e1d69 100644--- a/client/src/services/apiFableLoom.js+++ b/client/src/services/apiFableLoom.js@@ -170,6 +170,9 @@ export const startLoomEpisodeProductionBatch = (id, episodeId, body = {}, optionmethod: 'POST', body: JSON.stringify(body), ...options,});+export const getLoomEpisodeProductionBatchStatus = (id, episodeId, options = {}) =>+ request(episodePath(id, episodeId, '/production/batch'), options);+export const getLoomEpisodeProductionBatch = (id, episodeId, runId, options = {}) =>request(episodePath(id, episodeId, `/production/batch/${encodeURIComponent(runId)}`), options);diff --git a/server/lib/socketEventContracts.js b/server/lib/socketEventContracts.jsindex 2ffd97d2d1..e2c808a33f 100644--- a/server/lib/socketEventContracts.js+++ b/server/lib/socketEventContracts.js@@ -25,6 +25,24 @@ const input = (schema, summary) => Object.freeze({payloadSchema: zodToOpenApiSchema(schema),});+const loomRunSnapshot = (production) => Object.freeze({+ direction: 'server-to-client',+ summary: 'Revisioned public FableLoom run snapshot after an authoritative transition; no runtime handles.',+ payloadSchema: {+ type: 'object',+ required: ['id', 'loomId', 'status', 'revision', 'createdAt', 'updatedAt', ...(production ? ['episodeId', 'attempt', 'assets', 'summary'] : [])],+ properties: {+ id: { type: 'string' },+ loomId: { type: 'string' },+ ...(production ? { episodeId: { type: 'string' }, attempt: { type: 'integer' }, assets: { type: 'array', items: { type: 'object' } }, summary: { type: 'object' } } : {}),+ status: { type: 'string', enum: production ? ['in_progress', 'completed', 'failed', 'canceled'] : ['running', 'canceling', 'completed', 'paused', 'failed', 'canceled'] },+ revision: { type: 'integer' },+ createdAt: { type: 'string' },+ updatedAt: { type: 'string' },+ },+ },+});+export const SOCKET_EVENT_CONTRACTS = Object.freeze({'brain:changed': {direction: 'server-to-client',@@ -47,6 +65,8 @@ export const SOCKET_EVENT_CONTRACTS = Object.freeze({summary: 'A creative commission changed after persistence.',payloadSchema: { type: 'object', required: ['id'], properties: { id: { type: 'string' } }, additionalProperties: false },}),+ 'fableloom:editorial:run': loomRunSnapshot(false),+ 'fableloom:production:run': loomRunSnapshot(true),'app:deploy': input(appDeploySchema, 'Deploy a managed app with allowlisted flags.'),'app:standardize': input(appStandardizeSchema, 'Standardize one registered app.'),'app:update': input(appUpdateSchema, 'Run the update lifecycle for one registered app.'),diff --git a/server/routes/fableLoom.js b/server/routes/fableLoom.jsindex 9488e3e0e1..1441d1838b 100644--- a/server/routes/fableLoom.js+++ b/server/routes/fableLoom.js@@ -74,6 +74,7 @@ import {generateSeriesPlan,getFalVideoAutomation,getEpisodeProductionBatch,+ getLatestEpisodeProductionBatch,getHostedSession,getLoom,listLoomSummaries,@@ -419,6 +420,10 @@ router.post('/:id/episodes/:episodeId/production/batch', asyncHandler(async (reqres.status(201).json(await startEpisodeProductionBatch(req.params.id, req.params.episodeId, input));}));+router.get('/:id/episodes/:episodeId/production/batch', asyncHandler(async (req, res) => {+ res.json({ run: getLatestEpisodeProductionBatch(req.params.id, req.params.episodeId) });+}));+router.get('/:id/episodes/:episodeId/production/batch/:runId', asyncHandler(async (req, res) => {const run = getEpisodeProductionBatch(req.params.runId);if (!run || run.loomId !== req.params.id || run.episodeId !== req.params.episodeId) {diff --git a/server/routes/fableLoom.test.js b/server/routes/fableLoom.test.jsindex 92a971b95d..5c456994c2 100644--- a/server/routes/fableLoom.test.js+++ b/server/routes/fableLoom.test.js@@ -48,6 +48,7 @@ vi.mock('../services/fableLoom/index.js', () => ({startEpisodeProductionBatch: vi.fn(),startFalVideoAutomation: vi.fn(),getEpisodeProductionBatch: vi.fn(),+ getLatestEpisodeProductionBatch: vi.fn(),cancelEpisodeProductionBatch: vi.fn(),resumeEpisodeProductionBatch: vi.fn(),reviewEpisodeContinuity: vi.fn(),@@ -556,6 +557,15 @@ describe('FableLoom routes', () => {expect(fableLoom.planEpisodeProduction).toHaveBeenCalledWith('loom-1', 'ep-1', { mode: 'current_canon' });});+ it('reattaches the latest scoped run without starting production', async () => {+ fableLoom.getLatestEpisodeProductionBatch.mockReturnValueOnce(null);+ const res = await request(makeApp()).get('/api/fableloom/loom-1/episodes/ep-1/production/batch');+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ run: null });+ expect(fableLoom.getLatestEpisodeProductionBatch).toHaveBeenCalledWith('loom-1', 'ep-1');+ expect(fableLoom.startEpisodeProductionBatch).not.toHaveBeenCalled();+ });+it('POST /:id/episodes/:episodeId/production/batch starts a batch run', async () => {fableLoom.startEpisodeProductionBatch.mockResolvedValueOnce({ id: 'batch-1', status: 'in_progress' });const res = await request(makeApp())diff --git a/server/services/fableLoom/editorialAutopilot.js b/server/services/fableLoom/editorialAutopilot.jsindex 7d53930c39..25ae07d99c 100644--- a/server/services/fableLoom/editorialAutopilot.js+++ b/server/services/fableLoom/editorialAutopilot.js@@ -8,6 +8,7 @@* the loom writes themselves remain durable.*/+import { fableLoomRunEvents } from './runEvents.js';import { randomUUID } from 'node:crypto';import { ServerError } from '../../lib/errorHandler.js';import { LOOM_LIMITS } from '../../lib/fableLoomLimits.js';@@ -53,7 +54,8 @@ const cleanStaleRuns = () => {};const touch = (run, patch = {}) => {- Object.assign(run, patch, { updatedAt: nowIso() });+ Object.assign(run, patch, { updatedAt: nowIso(), revision: (run.revision || 0) + 1 });+ fableLoomRunEvents.emit('editorial', structuredClone(publicFableLoomEditorialAutopilot(run)));return run;};@@ -431,6 +433,7 @@ export async function startFableLoomEditorialAutopilot(loomId, {};runs.set(run.id, run);latestRunByLoom.set(loomId, run.id);+ touch(run);void (mode === 'planning' ? runPlanning(run) : runRound(run, '')).catch((error) => (run.cancelRequested ? finishCanceled(run) : finishFailed(run, error))).catch((error) => {diff --git a/server/services/fableLoom/editorialAutopilot.test.js b/server/services/fableLoom/editorialAutopilot.test.jsindex b84ed7ac00..d2cb7a4e9e 100644--- a/server/services/fableLoom/editorialAutopilot.test.js+++ b/server/services/fableLoom/editorialAutopilot.test.js@@ -1,4 +1,5 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fableLoomRunEvents } from './runEvents.js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const getLoomMock = vi.hoisted(() => vi.fn(async (id) => ({ id })));const mutateLoomMock = vi.hoisted(() => vi.fn(async (id, mutator) => mutator({@@ -91,6 +92,11 @@ beforeEach(() => {selfImproveMock.mockClear();});+const snapshots = [];+const recordSnapshot = run => snapshots.push(run);+beforeEach(() => { snapshots.length = 0; fableLoomRunEvents.on('editorial', recordSnapshot); });+afterEach(() => { fableLoomRunEvents.off('editorial', recordSnapshot); });+describe('FableLoom editorial autopilot', () => {it('completes after one editor/reviewer round when every gate passes', async () => {remediateMock.mockResolvedValueOnce(remediation(true));@@ -105,6 +111,11 @@ describe('FableLoom editorial autopilot', () => {status: 'completed', round: 1, maxRounds: 3, stepIndex: 2, stepCount: 6,});expect(finished.rounds).toHaveLength(1);+ expect(snapshots[0]).toMatchObject({ id: started.id, loomId: 'loom-example', status: 'running', revision: 1 });+ expect(snapshots.at(-1)).toMatchObject({ id: started.id, status: 'completed' });+ expect(snapshots.every(snapshot => !('previousFindingSignature' in snapshot))).toBe(true);+ expect(snapshots.map(snapshot => snapshot.revision)).toEqual(snapshots.map((_, index) => index + 1));+ expect(snapshots[0].rounds).toEqual([]);expect(remediateMock).toHaveBeenCalledWith('loom-example', {providerId: 'writer', model: 'large', effort: 'high', guidance: '',});@@ -176,6 +187,7 @@ describe('FableLoom editorial autopilot', () => {const finished = await waitForTerminal(started.id);expect(remediateMock).toHaveBeenCalledTimes(3);+ expect(snapshots.at(-1).status).toBe('failed');expect(finished).toMatchObject({status: 'failed', round: 1, stepIndex: 1, responseCorrections: 2, invalidResponses: 3,});@@ -240,6 +252,7 @@ describe('FableLoom editorial autopilot', () => {const started = await startFableLoomEditorialAutopilot('loom-example', { selfImprove: true });const finished = await waitForTerminal(started.id);+ expect(snapshots.at(-1).status).toBe('failed');expect(finished).toMatchObject({status: 'failed',error: providerError.message,@@ -266,6 +279,7 @@ describe('FableLoom editorial autopilot', () => {const started = await startFableLoomEditorialAutopilot('loom-example', { selfImprove: true });await vi.waitFor(() => expect(selfImproveMock).toHaveBeenCalledTimes(1));expect(cancelFableLoomEditorialAutopilot(started.id).status).toBe('canceling');+ expect(snapshots.at(-1).status).toBe('canceling');finishDiagnosis(null);const finished = await waitForTerminal(started.id);@@ -294,6 +308,7 @@ describe('FableLoom editorial autopilot', () => {});await vi.waitFor(() => expect(selfImproveMock).toHaveBeenCalledTimes(1));expect(cancelFableLoomEditorialAutopilot(started.id).status).toBe('canceling');+ expect(snapshots.at(-1).status).toBe('canceling');finishDiagnosis(null);const finished = await waitForTerminal(started.id);@@ -340,6 +355,7 @@ describe('FableLoom editorial autopilot', () => {expect(duplicate).toMatchObject({ id: started.id, alreadyRunning: true, maxRounds: 3 });expect(cancelFableLoomEditorialAutopilot(started.id).status).toBe('canceling');+ expect(snapshots.at(-1).status).toBe('canceling');finishRemediation(remediation(true));const finished = await waitForTerminal(started.id);diff --git a/server/services/fableLoom/index.js b/server/services/fableLoom/index.jsindex 4dba4d0eac..77735d93c2 100644--- a/server/services/fableLoom/index.js+++ b/server/services/fableLoom/index.js@@ -114,6 +114,7 @@ export {export {cancelEpisodeProductionBatch,getEpisodeProductionBatch,+ getLatestEpisodeProductionBatch,planEpisodeProduction,reviewEpisodeContinuity,resumeEpisodeProductionBatch,diff --git a/server/services/fableLoom/production.js b/server/services/fableLoom/production.jsindex c5f926e745..e5090793e1 100644--- a/server/services/fableLoom/production.js+++ b/server/services/fableLoom/production.js@@ -8,6 +8,7 @@* episode-level grouping, dependency barriers, cancellation, and resume UX.*/+import { fableLoomRunEvents } from './runEvents.js';import { randomInt, randomUUID } from 'node:crypto';import { basename } from 'node:path';import { ServerError } from '../../lib/errorHandler.js';@@ -109,6 +110,8 @@ function updateSummary(run) {function touchRun(run) {run.updatedAt = nowIso();updateSummary(run);+ run.revision = (run.revision || 0) + 1;+ fableLoomRunEvents.emit('production', structuredClone(run));}function cleanStaleRuns() {@@ -1057,6 +1060,7 @@ export async function startEpisodeProductionBatch(loomId, episodeId, options = {createdAt,updatedAt: createdAt,cancelRequested: false,+ attempt: 1,error: null,render,plan: {@@ -1076,6 +1080,7 @@ export async function startEpisodeProductionBatch(loomId, episodeId, options = {updateSummary(run);_batchRuns.set(runId, run);_runRuntime.set(runId, { tail: Promise.resolve() });+ touchRun(run);if (run.summary.pending === 0) {run.status = run.summary.failed || run.summary.blocked ? 'failed' : 'completed';touchRun(run);@@ -1085,6 +1090,12 @@ export async function startEpisodeProductionBatch(loomId, episodeId, options = {return run;}+/** Reattach on entry/reconnect without starting provider work. */+export function getLatestEpisodeProductionBatch(loomId, episodeId) {+ cleanStaleRuns();+ return [..._batchRuns.values()].reverse().find(run => run.loomId === loomId && run.episodeId === episodeId) || null;+}+/** Get the status of an ongoing or completed batch run. */export function getEpisodeProductionBatch(runId) {if (!runId || typeof runId !== 'string') return null;@@ -1127,6 +1138,7 @@ export function resumeEpisodeProductionBatch(runId) {}}run.status = 'in_progress';+ run.attempt = (run.attempt || 1) + 1;run.cancelRequested = false;run.error = null;_runRuntime.set(runId, _runRuntime.get(runId) || { tail: Promise.resolve() });diff --git a/server/services/fableLoom/production.test.js b/server/services/fableLoom/production.test.jsindex e1a5c90a40..3e228f138e 100644--- a/server/services/fableLoom/production.test.js+++ b/server/services/fableLoom/production.test.js@@ -1,8 +1,10 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { fableLoomRunEvents } from './runEvents.js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import {_resetProductionBatchRuns,cancelEpisodeProductionBatch,getEpisodeProductionBatch,+ getLatestEpisodeProductionBatch,planEpisodeProduction,reviewEpisodeContinuity,resumeEpisodeProductionBatch,@@ -65,6 +67,11 @@ vi.mock('../videoGen/history.js', () => videoHistoryMocks);vi.mock('../mediaJobQueue/index.js', () => queueMocks);vi.mock('./visualConditioning.js', () => visualConditioningMocks);+const snapshots = [];+const recordSnapshot = run => snapshots.push(run);+beforeEach(() => { snapshots.length = 0; fableLoomRunEvents.on('production', recordSnapshot); });+afterEach(() => { fableLoomRunEvents.off('production', recordSnapshot); });+describe('fableLoom production service', () => {const sampleLoom = {id: 'loom-1',@@ -313,6 +320,14 @@ describe('fableLoom production service', () => {const fetched = getEpisodeProductionBatch(run.id);expect(fetched).toEqual(run);+ const queuedCalls = queueMocks.enqueueJob.mock.calls.length;+ expect(getLatestEpisodeProductionBatch('loom-1', 'ep-1')).toBe(run);+ expect(getLatestEpisodeProductionBatch('loom-1', 'other-episode')).toBeNull();+ expect(queueMocks.enqueueJob).toHaveBeenCalledTimes(queuedCalls);+ expect(snapshots[0]).toMatchObject({ id: run.id, loomId: 'loom-1', episodeId: 'ep-1', revision: 1 });+ expect(snapshots[0].summary.queued).toBe(0);+ expect(snapshots.at(-1).summary.queued).toBeGreaterThan(0);+ expect(snapshots.every(snapshot => !('tail' in snapshot) && !('runtime' in snapshot))).toBe(true);});it('queues Reactor with its compact compiled script and fails oversized scripts before queueing', async () => {@@ -429,6 +444,7 @@ describe('fableLoom production service', () => {const canceled = await cancelEpisodeProductionBatch(run.id);expect(canceled.status).toBe('canceled');expect(canceled.cancelRequested).toBe(true);+ expect(snapshots.at(-1)).toMatchObject({ status: 'canceled', cancelRequested: true });});it('resumes a canceled run after resetting unfinished assets', async () => {@@ -437,6 +453,7 @@ describe('fableLoom production service', () => {const resumed = resumeEpisodeProductionBatch(run.id);expect(resumed.status).toBe('in_progress');+ expect(snapshots.at(-1)).toMatchObject({ status: 'in_progress', attempt: 2 });expect(resumed.assets.every((asset) => !['failed', 'blocked', 'canceled'].includes(asset.status))).toBe(true);await new Promise((resolve) => setTimeout(resolve, 0));expect(queueMocks.enqueueJob).toHaveBeenCalled();@@ -467,6 +484,7 @@ describe('fableLoom production service', () => {await new Promise((resolve) => setTimeout(resolve, 0));}expect(run.status).toBe('completed');+ expect(snapshots.at(-1)).toMatchObject({ id: run.id, status: 'completed', summary: run.summary });});it('performs episodic continuity review returning structured findings', async () => {diff --git a/server/services/fableLoom/runEvents.js b/server/services/fableLoom/runEvents.jsnew file mode 100644index 0000000000..7f30dd861c--- /dev/null+++ b/server/services/fableLoom/runEvents.js@@ -0,0 +1,4 @@+import { EventEmitter } from 'node:events';++// Public run snapshots only; runtime promises and provider handles stay local.+export const fableLoomRunEvents = new EventEmitter();diff --git a/server/services/socket.js b/server/services/socket.jsindex 370241bba2..4010619c92 100644--- a/server/services/socket.js+++ b/server/services/socket.js@@ -1,4 +1,5 @@import { recordEvents } from './sharing/recordEvents.js';+import { fableLoomRunEvents } from './fableLoom/runEvents.js';import { cosEvents } from './cosEvents.js';import { toAgentListItem } from '../lib/cosAgentListProjection.js';import { appsEvents } from './apps.js';@@ -62,6 +63,7 @@ const loopSubscribers = new Set();// liveness ONLY — see setupBeeperEventForwarding for why this may never be a// global emit.const beeperSubscribers = new Set();+const fableLoomSubscribers = new Set();// Store io instance for broadcastinglet ioInstance = null;@@ -74,7 +76,7 @@ export function getIo() {return ioInstance;}-const ALL_SUBSCRIBER_SETS = [cosSubscribers, errorSubscribers, notificationSubscribers, agentSubscribers, instanceSubscribers, loopSubscribers, beeperSubscribers];+const ALL_SUBSCRIBER_SETS = [cosSubscribers, errorSubscribers, notificationSubscribers, agentSubscribers, instanceSubscribers, loopSubscribers, beeperSubscribers, fableLoomSubscribers];function broadcastToSet(set, event, data) {const disconnected = [];@@ -152,6 +154,7 @@ function registerSubscriptionHandlers(socket, _io) {registerSubscriber(socket, 'instances', instanceSubscribers);registerSubscriber(socket, 'loops', loopSubscribers);registerSubscriber(socket, 'beeper', beeperSubscribers);+ registerSubscriber(socket, 'fableloom', fableLoomSubscribers);}function registerErrorHandlers(socket, io) {@@ -241,6 +244,7 @@ function setupEventForwarding() {setupCallStateEventForwarding();setupBeeperEventForwarding();setupRecordEventForwarding();+ setupFableLoomRunForwarding();}let persistentMindEventForwardingSetup = false;@@ -789,3 +793,15 @@ function setupMediaGenEventForwarding() {ioInstance.emit(`${prefix}:failed`, { generationId: job.id, error: job.error });});}++let fableLoomRunForwardingSetup = false;+function setupFableLoomRunForwarding() {+ if (fableLoomRunForwardingSetup) return;+ fableLoomRunForwardingSetup = true;+ fableLoomRunEvents.on('editorial', run => {+ broadcastToSet(fableLoomSubscribers, 'fableloom:editorial:run', run);+ });+ fableLoomRunEvents.on('production', run => {+ broadcastToSet(fableLoomSubscribers, 'fableloom:production:run', run);+ });+}diff --git a/server/services/socket.test.js b/server/services/socket.test.jsindex 38c4715dfd..e7a2050e32 100644--- a/server/services/socket.test.js+++ b/server/services/socket.test.js@@ -1,4 +1,5 @@import { emitRecordUpdated, emitRecordDeleted, emitRecordInvalidated } from './sharing/recordEvents.js';+import { fableLoomRunEvents } from './fableLoom/runEvents.js';import { authEvents } from './auth.js';import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';@@ -186,6 +187,25 @@ describe('socket.js — initSocket', () => {]);});+ it('delivers FableLoom snapshots only to subscribed operator views', () => {+ const viewer = makeSocket('loom-viewer');+ const peer = makeSocket('peer-relay');+ createdSockets.push(viewer, peer);+ io.connect(viewer); io.connect(peer);+ viewer.handlers['fableloom:subscribe']();+ const run = { id: 'run-example', loomId: 'loom-example', revision: 1 };+ fableLoomRunEvents.emit('editorial', run);+ fableLoomRunEvents.emit('production', run);+ expect(viewer.emitted).toContainEqual(['fableloom:editorial:run', run]);+ expect(viewer.emitted).toContainEqual(['fableloom:production:run', run]);+ expect(peer.emitted.some(([name]) => name.startsWith('fableloom:'))).toBe(false);+ expect(io.emitted.some(([name]) => name.startsWith('fableloom:'))).toBe(false);+ viewer.handlers['fableloom:unsubscribe']();+ const count = viewer.emitted.length;+ fableLoomRunEvents.emit('editorial', run);+ expect(viewer.emitted).toHaveLength(count);+ });+it('sends compact task invalidations to opted-in pages while preserving legacy subscribers', () => {const compact = makeSocket('compact-cos');const legacy = makeSocket('legacy-cos');