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([issue-1087]): extract shared useInstallStream hook for SSE install modals

Adam Eivy78a3b3ec89d5
diff --git a/client/src/components/imageGen/Flux2InstallModal.jsx b/client/src/components/imageGen/Flux2InstallModal.jsx
index b026948769..a9a683c3cd 100644
--- a/client/src/components/imageGen/Flux2InstallModal.jsx
+++ b/client/src/components/imageGen/Flux2InstallModal.jsx
@@ -10,16 +10,11 @@
* EventSource, which the server interprets as a cancel and SIGTERMs pip.
*/
-import { useEffect, useRef, useState } from 'react';
+import { useEffect, useState } from 'react';
import { CheckCircle2, Loader2, AlertCircle, Download, X } from 'lucide-react';
-import { safeParseJSON } from '../../lib/genUtils';
+import { useInstallStream } from '../../hooks/useInstallStream';
import Modal from '../ui/Modal';
-// Cap on retained log lines. A torch install can emit hundreds of pip output
-// lines; without this the array grows unbounded and re-renders cost more per
-// append (slice copy is O(n) but n is bounded).
-const MAX_LOG_LINES = 500;
-
const STAGES = [
{ id: 'detect', label: 'Detect Python' },
{ id: 'venv', label: 'Create venv' },
@@ -31,89 +26,27 @@ const STAGES = [
const STAGE_INDEX = Object.fromEntries(STAGES.map((s, i) => [s.id, i]));
export default function Flux2InstallModal({ open, onClose, onComplete }) {
- const [currentStage, setCurrentStage] = useState(null);
- const [logs, setLogs] = useState([]);
- const [done, setDone] = useState(false);
- const [error, setError] = useState(null);
const [confirmingCancel, setConfirmingCancel] = useState(false);
- const logsEndRef = useRef(null);
- const esRef = useRef(null);
- // Stash onComplete in a ref so the EventSource effect doesn't re-run (and
- // tear down the SSE connection) every time the parent re-renders with a
- // fresh inline arrow. Without this, ImageGen's frequent state churn
- // (gallery, generating, localProgress) would kill the install mid-stream.
- const onCompleteRef = useRef(onComplete);
- useEffect(() => { onCompleteRef.current = onComplete; }, [onComplete]);
-
- const appendLog = (entry) => setLogs((prev) => {
- const next = prev.length >= MAX_LOG_LINES ? [...prev.slice(-(MAX_LOG_LINES - 1)), entry] : [...prev, entry];
- return next;
- });
-
- useEffect(() => {
- if (!open) {
- setCurrentStage(null);
- setLogs([]);
- setDone(false);
- setError(null);
- setConfirmingCancel(false);
- if (esRef.current) { esRef.current.close(); esRef.current = null; }
- return;
- }
-
- const es = new EventSource('/api/image-gen/setup/flux2-install');
- esRef.current = es;
-
- es.onmessage = (ev) => {
- const msg = safeParseJSON(ev.data);
- if (!msg) return;
- if (msg.type === 'stage') {
- setCurrentStage(msg.stage);
- appendLog({ kind: 'stage', text: msg.message || msg.stage });
- } else if (msg.type === 'log') {
- appendLog({ kind: 'log', text: msg.message });
- } else if (msg.type === 'complete') {
- setDone(true);
- appendLog({ kind: 'success', text: msg.message });
- es.close();
- esRef.current = null;
- onCompleteRef.current?.();
- } else if (msg.type === 'error') {
- setError(msg.message);
- appendLog({ kind: 'error', text: msg.message });
- es.close();
- esRef.current = null;
- }
- };
-
- es.onerror = () => {
- // Network drop or server killed the stream. If we already saw `complete`
- // this is harmless; otherwise surface it so the user isn't stuck on a
- // forever-spinning modal.
- setError((prev) => prev ?? (done ? null : 'Connection to installer lost. Restart PortOS or try again.'));
- es.close();
- esRef.current = null;
- };
-
- return () => {
- if (esRef.current) { esRef.current.close(); esRef.current = null; }
- };
- // onComplete intentionally excluded — it lives in onCompleteRef.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [open]);
+ // The shared install-stream hook owns the EventSource lifecycle, log
+ // accumulation, stage tracking, connection-lost handling and auto-scroll.
+ // onComplete is ref-stashed inside the hook so ImageGen's frequent state
+ // churn (gallery, generating, localProgress) can't kill the install
+ // mid-stream by re-running the effect.
+ const { logs, currentStage, done, error, logsEndRef, close } = useInstallStream(
+ '/api/image-gen/setup/flux2-install',
+ { enabled: open, onComplete },
+ );
- // Auto-scroll on every log line. `behavior: 'auto'` (instant) avoids
- // queueing hundreds of smooth-scroll animations during a chatty pip install.
- useEffect(() => {
- if (logsEndRef.current) {
- logsEndRef.current.scrollIntoView({ behavior: 'auto', block: 'end' });
- }
- }, [logs.length]);
+ // Reset the cancel-confirm prompt whenever the modal closes, so a reopen
+ // never starts mid-confirmation. (The stream state itself resets inside the
+ // hook when `enabled` flips false.)
+ useEffect(() => { if (!open) setConfirmingCancel(false); }, [open]);
const installRunning = !done && !error && currentStage && currentStage !== 'verify';
const performClose = () => {
- if (esRef.current) { esRef.current.close(); esRef.current = null; }
+ close();
+ setConfirmingCancel(false);
onClose();
};
diff --git a/client/src/components/videoGen/RuntimeInstallModal.jsx b/client/src/components/videoGen/RuntimeInstallModal.jsx
index 6a4aa83120..a3a5eee8ea 100644
--- a/client/src/components/videoGen/RuntimeInstallModal.jsx
+++ b/client/src/components/videoGen/RuntimeInstallModal.jsx
@@ -13,123 +13,37 @@
* EventSource, which the server interprets as a SIGTERM to the bash child.
*/
-import { useEffect, useRef, useState } from 'react';
+import { useEffect, useState } from 'react';
import { CheckCircle2, Loader2, AlertCircle, Download, X } from 'lucide-react';
-import { safeParseJSON } from '../../lib/genUtils';
+import { useInstallStream } from '../../hooks/useInstallStream';
import Modal from '../ui/Modal';
const MAX_LOG_LINES = 1000;
export default function RuntimeInstallModal({ open, runtime, label, onClose, onComplete }) {
- const [logs, setLogs] = useState([]);
- const [streamStarted, setStreamStarted] = useState(false);
- const [done, setDone] = useState(false);
- const [error, setError] = useState(null);
const [confirmingCancel, setConfirmingCancel] = useState(false);
- const logsEndRef = useRef(null);
- const esRef = useRef(null);
- // Mirror `done` into a ref so es.onerror can read the latest value — the
- // effect's closure captures the initial `done=false` and never refreshes,
- // so without this the modal flashes "Connection to installer lost" when
- // the server cleanly closes the SSE socket right after sending `complete`.
- const doneRef = useRef(false);
- // Stash onComplete in a ref so the EventSource effect doesn't tear down
- // mid-install on every parent re-render with a fresh inline arrow.
- const onCompleteRef = useRef(onComplete);
- useEffect(() => { onCompleteRef.current = onComplete; }, [onComplete]);
-
- // Pip and git can each emit hundreds of lines/sec. Per-line setState would
- // re-render the entire log list on every line — buffer into a ref and
- // flush on a short debounce so the React tree settles at ~10 Hz instead.
- const pendingRef = useRef([]);
- const flushTimerRef = useRef(null);
- const flush = () => {
- flushTimerRef.current = null;
- if (pendingRef.current.length === 0) return;
- const incoming = pendingRef.current;
- pendingRef.current = [];
- setLogs((prev) => {
- const combined = prev.length + incoming.length > MAX_LOG_LINES
- ? [...prev, ...incoming].slice(-MAX_LOG_LINES)
- : [...prev, ...incoming];
- return combined;
- });
- };
- const appendLog = (entry) => {
- pendingRef.current.push(entry);
- if (flushTimerRef.current == null) {
- flushTimerRef.current = setTimeout(flush, 100);
- }
- };
-
- useEffect(() => {
- if (!open || !runtime) {
- setLogs([]);
- setStreamStarted(false);
- setDone(false);
- doneRef.current = false;
- setError(null);
- setConfirmingCancel(false);
- pendingRef.current = [];
- if (flushTimerRef.current != null) { clearTimeout(flushTimerRef.current); flushTimerRef.current = null; }
- if (esRef.current) { esRef.current.close(); esRef.current = null; }
- return;
- }
-
- setStreamStarted(true);
- const es = new EventSource(`/api/video-gen/setup/runtime-install?runtime=${encodeURIComponent(runtime)}`);
- esRef.current = es;
-
- es.onmessage = (ev) => {
- const msg = safeParseJSON(ev.data);
- if (!msg) return;
- if (msg.type === 'log') {
- appendLog({ kind: 'log', text: msg.message });
- } else if (msg.type === 'complete') {
- setDone(true);
- doneRef.current = true;
- appendLog({ kind: 'success', text: msg.message });
- flush();
- es.close();
- esRef.current = null;
- onCompleteRef.current?.();
- } else if (msg.type === 'error') {
- setError(msg.message);
- appendLog({ kind: 'error', text: msg.message });
- flush();
- es.close();
- esRef.current = null;
- }
- };
-
- es.onerror = () => {
- setError((prev) => prev ?? (doneRef.current ? null : 'Connection to installer lost. Restart PortOS or try again.'));
- es.close();
- esRef.current = null;
- };
-
- return () => {
- if (flushTimerRef.current != null) { clearTimeout(flushTimerRef.current); flushTimerRef.current = null; }
- if (esRef.current) { esRef.current.close(); esRef.current = null; }
- };
- // onComplete intentionally excluded — it lives in onCompleteRef.
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [open, runtime]);
+ // The shared install-stream hook owns the EventSource lifecycle, log
+ // accumulation, connection-lost handling and auto-scroll. Pip/git emit
+ // hundreds of lines/sec, so flush on a 100ms debounce instead of per-line.
+ // The runtime install has no structured `stage` events (the bash script
+ // emits free-form log lines), so `currentStage` is unused here.
+ const { logs, done, error, streamStarted, logsEndRef, close } = useInstallStream(
+ open && runtime ? `/api/video-gen/setup/runtime-install?runtime=${encodeURIComponent(runtime)}` : null,
+ { enabled: open && !!runtime, onComplete, maxLogLines: MAX_LOG_LINES, flushMs: 100 },
+ );
- useEffect(() => {
- if (logsEndRef.current) {
- logsEndRef.current.scrollIntoView({ behavior: 'auto', block: 'end' });
- }
- }, [logs.length]);
+ // Reset the cancel-confirm prompt whenever the modal closes so a reopen never
+ // starts mid-confirmation. (Stream state resets inside the hook.)
+ useEffect(() => { if (!open || !runtime) setConfirmingCancel(false); }, [open, runtime]);
// True from the moment the EventSource opens — closing the modal between
// the open and the first log line must still confirm before killing the
- // server-side bash child. Previously gated on `logs.length > 0`, which let
- // a quick X-click silently drop a just-started install.
+ // server-side bash child.
const installRunning = streamStarted && !done && !error;
const performClose = () => {
- if (esRef.current) { esRef.current.close(); esRef.current = null; }
+ close();
+ setConfirmingCancel(false);
onClose();
};
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 6fcf4ffd72..0e732262be 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -36,6 +36,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| Hook | Purpose | Use when |
|---|---|---|
| `useSseProgress` | Generic JSON-frame EventSource subscriber. | New SSE progress stream — start here, build on top. |
+| `useInstallStream` | BYO-runtime install-log EventSource lifecycle: `stage`/`log`/`complete`/`error` frame dispatch, capped + optionally-debounced log accumulation, "connection lost" handling, ref-stashed `onComplete`, auto-scroll. | A streamed install/setup modal that shows live SSE log lines (FLUX.2, video runtimes). Don't re-roll the EventSource teardown/onComplete-ref dance. |
| `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. |
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 6a7edf1f69..4cde9e42af 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -56,6 +56,7 @@ export * from './useArcCanvasSync.js';
// === Progress & streaming (SSE / socket) ===
export * from './useImageGenProgress.js';
export * from './useImporterProgress.js';
+export * from './useInstallStream.js';
export * from './useOpenClawStream.js';
export * from './usePipelineAutoRunProgress.js';
export * from './usePipelineEditorialProgress.js';
diff --git a/client/src/hooks/useInstallStream.js b/client/src/hooks/useInstallStream.js
new file mode 100644
index 0000000000..1ab6a9892d
--- /dev/null
+++ b/client/src/hooks/useInstallStream.js
@@ -0,0 +1,163 @@
+import { useEffect, useRef, useState } from 'react';
+import { safeParseJSON } from '../lib/genUtils';
+
+/**
+ * Shared EventSource lifecycle for the BYO runtime install modals
+ * (Flux2InstallModal, RuntimeInstallModal). Both streamed the same shape of
+ * SSE install log — open on `open`, dispatch `stage`/`log`/`complete`/`error`
+ * frames, cap the retained log, surface a "connection lost" error when the
+ * socket drops before `complete`, and auto-scroll the log to the bottom — so
+ * the plumbing lives here once and each modal keeps only its own chrome.
+ *
+ * Frame contract (matches the server emitters in pythonSetup.js /
+ * setup-image-video.sh):
+ * { type: 'stage', stage, message? } → advances currentStage + logs it
+ * { type: 'log', message } → appends a log line
+ * { type: 'complete', message } → done=true, onComplete(), closes
+ * { type: 'error', message } → error set, closes
+ *
+ * Closing the EventSource (via `close()` on cancel, or unmount/disable) is what
+ * the server interprets as a cancel — it SIGTERMs the underlying pip/bash child.
+ *
+ * `flushMs` controls log batching: 0 flushes each line synchronously (fine for
+ * the structured, bounded FLUX.2 stream); >0 buffers and flushes on a debounce
+ * so a chatty pip/git stream re-renders the log list at ~1/flushMs Hz instead
+ * of once per line.
+ *
+ * @param {string|null} url - SSE endpoint; null/empty leaves the stream closed.
+ * @param {object} opts
+ * @param {boolean} [opts.enabled=true] - when false, the stream stays closed and state resets.
+ * @param {() => void} [opts.onComplete] - fired once on the `complete` frame.
+ * @param {number} [opts.maxLogLines=500] - cap on retained log lines.
+ * @param {number} [opts.flushMs=0] - 0 = per-line flush; >0 = debounce window.
+ * @returns {{ logs, currentStage, done, error, streamStarted, logsEndRef, close }}
+ */
+
+const DEFAULT_MAX_LOG_LINES = 500;
+const CONNECTION_LOST_MESSAGE = 'Connection to installer lost. Restart PortOS or try again.';
+
+export function useInstallStream(url, {
+ enabled = true,
+ onComplete,
+ maxLogLines = DEFAULT_MAX_LOG_LINES,
+ flushMs = 0,
+} = {}) {
+ const [logs, setLogs] = useState([]);
+ const [currentStage, setCurrentStage] = useState(null);
+ const [done, setDone] = useState(false);
+ const [error, setError] = useState(null);
+ const [streamStarted, setStreamStarted] = useState(false);
+ const logsEndRef = useRef(null);
+ const esRef = useRef(null);
+ // Mirror `done` into a ref so es.onerror reads the latest value — the effect
+ // closure captures the initial done=false and never refreshes, so without
+ // this the modal can flash "Connection lost" when the server cleanly closes
+ // the socket right after sending `complete`.
+ const doneRef = useRef(false);
+ // Stash onComplete in a ref so the EventSource effect doesn't tear down the
+ // SSE connection on every parent re-render with a fresh inline arrow.
+ const onCompleteRef = useRef(onComplete);
+ useEffect(() => { onCompleteRef.current = onComplete; }, [onComplete]);
+
+ // Buffer incoming lines and flush them together. Pip and git can each emit
+ // hundreds of lines/sec; per-line setState would re-render the whole log list
+ // on every line.
+ const pendingRef = useRef([]);
+ const flushTimerRef = useRef(null);
+ const flush = () => {
+ flushTimerRef.current = null;
+ if (pendingRef.current.length === 0) return;
+ const incoming = pendingRef.current;
+ pendingRef.current = [];
+ setLogs((prev) => {
+ const combined = [...prev, ...incoming];
+ return combined.length > maxLogLines ? combined.slice(-maxLogLines) : combined;
+ });
+ };
+ const appendLog = (entry) => {
+ pendingRef.current.push(entry);
+ if (flushMs > 0) {
+ if (flushTimerRef.current == null) flushTimerRef.current = setTimeout(flush, flushMs);
+ } else {
+ flush();
+ }
+ };
+
+ useEffect(() => {
+ const clearFlush = () => {
+ if (flushTimerRef.current != null) { clearTimeout(flushTimerRef.current); flushTimerRef.current = null; }
+ };
+ const closeStream = () => {
+ if (esRef.current) { esRef.current.close(); esRef.current = null; }
+ };
+
+ if (!enabled || !url) {
+ setLogs([]);
+ setCurrentStage(null);
+ setDone(false);
+ doneRef.current = false;
+ setError(null);
+ setStreamStarted(false);
+ pendingRef.current = [];
+ clearFlush();
+ closeStream();
+ return undefined;
+ }
+
+ setStreamStarted(true);
+ const es = new EventSource(url);
+ esRef.current = es;
+
+ es.onmessage = (ev) => {
+ const msg = safeParseJSON(ev.data);
+ if (!msg) return;
+ if (msg.type === 'stage') {
+ setCurrentStage(msg.stage);
+ appendLog({ kind: 'stage', text: msg.message || msg.stage });
+ } else if (msg.type === 'log') {
+ appendLog({ kind: 'log', text: msg.message });
+ } else if (msg.type === 'complete') {
+ setDone(true);
+ doneRef.current = true;
+ appendLog({ kind: 'success', text: msg.message });
+ flush();
+ closeStream();
+ onCompleteRef.current?.();
+ } else if (msg.type === 'error') {
+ setError(msg.message);
+ appendLog({ kind: 'error', text: msg.message });
+ flush();
+ closeStream();
+ }
+ };
+
+ es.onerror = () => {
+ // Network drop or server killed the stream. If we already saw `complete`
+ // this is harmless; otherwise surface it so the user isn't stuck on a
+ // forever-spinning modal.
+ setError((prev) => prev ?? (doneRef.current ? null : CONNECTION_LOST_MESSAGE));
+ closeStream();
+ };
+
+ return () => {
+ clearFlush();
+ closeStream();
+ };
+ // onComplete intentionally excluded — it lives in onCompleteRef.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [url, enabled, maxLogLines, flushMs]);
+
+ // Auto-scroll on every new line. behavior:'auto' (instant) avoids queueing
+ // hundreds of smooth-scroll animations during a chatty install.
+ useEffect(() => {
+ if (logsEndRef.current) {
+ logsEndRef.current.scrollIntoView({ behavior: 'auto', block: 'end' });
+ }
+ }, [logs.length]);
+
+ const close = () => {
+ if (esRef.current) { esRef.current.close(); esRef.current = null; }
+ };
+
+ return { logs, currentStage, done, error, streamStarted, logsEndRef, close };
+}
diff --git a/client/src/hooks/useInstallStream.test.jsx b/client/src/hooks/useInstallStream.test.jsx
new file mode 100644
index 0000000000..4723e47fc5
--- /dev/null
+++ b/client/src/hooks/useInstallStream.test.jsx
@@ -0,0 +1,194 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { renderHook, act } from '@testing-library/react';
+import { useInstallStream } from './useInstallStream';
+
+// jsdom has no EventSource — stand up a minimal mock that records instances
+// and lets a test drive onmessage / onerror by hand.
+class MockEventSource {
+ constructor(url) {
+ this.url = url;
+ this.onmessage = null;
+ this.onerror = null;
+ this.onopen = null;
+ this.closed = false;
+ this.readyState = MockEventSource.OPEN;
+ MockEventSource.instances.push(this);
+ }
+
+ close() { this.closed = true; this.readyState = MockEventSource.CLOSED; }
+
+ emit(payload) { this.onmessage?.({ data: JSON.stringify(payload) }); }
+
+ emitRaw(data) { this.onmessage?.({ data }); }
+
+ fail() { this.readyState = MockEventSource.CLOSED; this.onerror?.(); }
+}
+MockEventSource.CONNECTING = 0;
+MockEventSource.OPEN = 1;
+MockEventSource.CLOSED = 2;
+
+const last = () => MockEventSource.instances[MockEventSource.instances.length - 1];
+
+beforeEach(() => {
+ MockEventSource.instances = [];
+ global.EventSource = MockEventSource;
+ // jsdom doesn't implement scrollIntoView; the auto-scroll effect calls it.
+ Element.prototype.scrollIntoView = vi.fn();
+});
+
+afterEach(() => {
+ delete global.EventSource;
+ vi.useRealTimers();
+});
+
+describe('useInstallStream', () => {
+ it('does not open a stream when disabled', () => {
+ renderHook(() => useInstallStream('/x', { enabled: false }));
+ expect(MockEventSource.instances).toHaveLength(0);
+ });
+
+ it('does not open a stream when url is null', () => {
+ renderHook(() => useInstallStream(null, { enabled: true }));
+ expect(MockEventSource.instances).toHaveLength(0);
+ });
+
+ it('opens the given url when enabled and marks the stream started', () => {
+ const { result } = renderHook(() => useInstallStream('/api/install', { enabled: true }));
+ expect(last().url).toBe('/api/install');
+ expect(result.current.streamStarted).toBe(true);
+ });
+
+ it('tracks stages and logs them', () => {
+ const { result } = renderHook(() => useInstallStream('/x', { enabled: true }));
+ act(() => { last().emit({ type: 'stage', stage: 'venv', message: 'Creating venv' }); });
+ expect(result.current.currentStage).toBe('venv');
+ expect(result.current.logs).toEqual([{ kind: 'stage', text: 'Creating venv' }]);
+ });
+
+ it('falls back to the stage id when a stage frame has no message', () => {
+ const { result } = renderHook(() => useInstallStream('/x', { enabled: true }));
+ act(() => { last().emit({ type: 'stage', stage: 'detect' }); });
+ expect(result.current.logs).toEqual([{ kind: 'stage', text: 'detect' }]);
+ });
+
+ it('appends log frames as log lines', () => {
+ const { result } = renderHook(() => useInstallStream('/x', { enabled: true }));
+ act(() => {
+ last().emit({ type: 'log', message: 'line 1' });
+ last().emit({ type: 'log', message: 'line 2' });
+ });
+ expect(result.current.logs).toEqual([
+ { kind: 'log', text: 'line 1' },
+ { kind: 'log', text: 'line 2' },
+ ]);
+ });
+
+ it('sets done, logs success, fires onComplete and closes on complete', () => {
+ const onComplete = vi.fn();
+ const { result } = renderHook(() => useInstallStream('/x', { enabled: true, onComplete }));
+ act(() => { last().emit({ type: 'complete', message: 'All set' }); });
+ expect(result.current.done).toBe(true);
+ expect(result.current.logs).toEqual([{ kind: 'success', text: 'All set' }]);
+ expect(onComplete).toHaveBeenCalledTimes(1);
+ expect(last().closed).toBe(true);
+ });
+
+ it('sets error, logs it and closes on error', () => {
+ const { result } = renderHook(() => useInstallStream('/x', { enabled: true }));
+ act(() => { last().emit({ type: 'error', message: 'boom' }); });
+ expect(result.current.error).toBe('boom');
+ expect(result.current.logs).toEqual([{ kind: 'error', text: 'boom' }]);
+ expect(last().closed).toBe(true);
+ });
+
+ it('surfaces a connection-lost error when the socket drops before complete', () => {
+ const { result } = renderHook(() => useInstallStream('/x', { enabled: true }));
+ act(() => { last().fail(); });
+ expect(result.current.error).toMatch(/Connection to installer lost/);
+ });
+
+ it('does NOT surface a connection-lost error when the socket drops after complete', () => {
+ const { result } = renderHook(() => useInstallStream('/x', { enabled: true }));
+ act(() => { last().emit({ type: 'complete', message: 'done' }); });
+ act(() => { last().fail(); });
+ expect(result.current.error).toBeNull();
+ });
+
+ it('silently ignores unparseable frames', () => {
+ const { result } = renderHook(() => useInstallStream('/x', { enabled: true }));
+ act(() => { expect(() => last().emitRaw('not json')).not.toThrow(); });
+ expect(result.current.logs).toEqual([]);
+ expect(last().closed).toBe(false);
+ });
+
+ it('caps the retained log lines at maxLogLines', () => {
+ const { result } = renderHook(() => useInstallStream('/x', { enabled: true, maxLogLines: 3 }));
+ act(() => {
+ for (let i = 0; i < 6; i++) last().emit({ type: 'log', message: `l${i}` });
+ });
+ expect(result.current.logs.map((e) => e.text)).toEqual(['l3', 'l4', 'l5']);
+ });
+
+ it('does not tear down the stream on parent re-render with a fresh onComplete', () => {
+ let onComplete = vi.fn();
+ const { rerender } = renderHook(({ cb }) => useInstallStream('/x', { enabled: true, onComplete: cb }), {
+ initialProps: { cb: onComplete },
+ });
+ const first = last();
+ onComplete = vi.fn();
+ rerender({ cb: onComplete });
+ // Same EventSource instance — no teardown/reopen from the new inline arrow.
+ expect(MockEventSource.instances).toHaveLength(1);
+ expect(first.closed).toBe(false);
+ // The latest onComplete is the one that fires.
+ act(() => { first.emit({ type: 'complete', message: 'done' }); });
+ expect(onComplete).toHaveBeenCalledTimes(1);
+ });
+
+ it('resets state and closes the stream when disabled', () => {
+ const { result, rerender } = renderHook(
+ ({ enabled }) => useInstallStream('/x', { enabled }),
+ { initialProps: { enabled: true } },
+ );
+ const es = last();
+ act(() => { result.current; es.emit({ type: 'log', message: 'hi' }); });
+ rerender({ enabled: false });
+ expect(es.closed).toBe(true);
+ expect(result.current.logs).toEqual([]);
+ expect(result.current.streamStarted).toBe(false);
+ expect(result.current.done).toBe(false);
+ expect(result.current.error).toBeNull();
+ });
+
+ it('close() tears down the active stream', () => {
+ const { result } = renderHook(() => useInstallStream('/x', { enabled: true }));
+ expect(last().closed).toBe(false);
+ act(() => { result.current.close(); });
+ expect(last().closed).toBe(true);
+ });
+
+ it('buffers log lines and flushes on the debounce window when flushMs > 0', () => {
+ vi.useFakeTimers();
+ const { result } = renderHook(() => useInstallStream('/x', { enabled: true, flushMs: 100 }));
+ act(() => {
+ last().emit({ type: 'log', message: 'a' });
+ last().emit({ type: 'log', message: 'b' });
+ });
+ // Not flushed yet — still buffered.
+ expect(result.current.logs).toEqual([]);
+ act(() => { vi.advanceTimersByTime(100); });
+ expect(result.current.logs.map((e) => e.text)).toEqual(['a', 'b']);
+ });
+
+ it('flushes buffered lines immediately on a terminal frame even with flushMs > 0', () => {
+ vi.useFakeTimers();
+ const { result } = renderHook(() => useInstallStream('/x', { enabled: true, flushMs: 100 }));
+ act(() => {
+ last().emit({ type: 'log', message: 'a' });
+ last().emit({ type: 'complete', message: 'done' });
+ });
+ // complete forces a flush — both the buffered log and the success line land.
+ expect(result.current.logs.map((e) => e.text)).toEqual(['a', 'done']);
+ expect(result.current.done).toBe(true);
+ });
+});