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

fix: show closed and disconnected process log streams as unavailable (#9959)

Adam Eivy7b88db448d6a
diff --git a/client/src/components/apps/DesktopLaunchProgress.jsx b/client/src/components/apps/DesktopLaunchProgress.jsx
index b5b654db31..110e60fb33 100644
--- a/client/src/components/apps/DesktopLaunchProgress.jsx
+++ b/client/src/components/apps/DesktopLaunchProgress.jsx
@@ -27,7 +27,7 @@ import { useProcessLogs } from '../../hooks/useProcessLogs';
* @param {() => void} props.onDismiss Close the panel (does not stop the app).
*/
export default function DesktopLaunchProgress({ appId, processName, online, relaunchLabel = 'Start', onDismiss }) {
- const { logs, subscribed } = useProcessLogs(processName, { lines: 200, appId });
+ const { logs, status, statusDetail, retry } = useProcessLogs(processName, { lines: 200, appId });
const scrollRef = useRef(null);
// `online` is two-state, but the panel has three phases. Without remembering
// that the process was ever up, a panel still open when the user closes the game
@@ -73,7 +73,7 @@ export default function DesktopLaunchProgress({ appId, processName, online, rela
ref={scrollRef}
className="m-4 mt-2 p-3 bg-port-bg border border-port-border rounded-lg font-mono text-xs h-48 overflow-y-auto"
>
- <ProcessLogLines logs={logs} subscribed={subscribed} />
+ <ProcessLogLines logs={logs} status={status} statusDetail={statusDetail} onRetry={retry} />
</div>
</div>
);
diff --git a/client/src/components/apps/DesktopLaunchProgress.test.jsx b/client/src/components/apps/DesktopLaunchProgress.test.jsx
index b1d8b21b17..959dca0240 100644
--- a/client/src/components/apps/DesktopLaunchProgress.test.jsx
+++ b/client/src/components/apps/DesktopLaunchProgress.test.jsx
@@ -74,6 +74,32 @@ describe('DesktopLaunchProgress', () => {
expect(screen.getByText(/Waiting for output/)).toBeInTheDocument();
});
+ it('shows a closed empty stream as unavailable with a retry, never Waiting for output', () => {
+ renderPanel();
+ fire('logs:subscribed', { processName: 'game' });
+ fire('logs:close', { processName: 'game', code: 1 });
+
+ expect(screen.queryByText(/Waiting for output/)).toBeNull();
+ expect(screen.queryByText(/Connecting to log stream/)).toBeNull();
+ expect(screen.getByText(/Log stream unavailable — Log stream closed \(exit code 1\)/)).toBeInTheDocument();
+
+ const subscribes = () => emitted.filter(([e]) => e === 'logs:subscribe').length;
+ expect(subscribes()).toBe(1);
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ expect(subscribes()).toBe(2);
+ expect(screen.getByText(/Connecting to log stream/)).toBeInTheDocument();
+ });
+
+ it('keeps captured lines visible under the unavailable notice after a disconnect', () => {
+ renderPanel();
+ fire('logs:subscribed', { processName: 'game' });
+ fire('logs:line', { processName: 'game', line: 'Importing assets…', type: 'stdout', timestamp: 1 });
+ fire('disconnect', 'transport close');
+
+ expect(screen.getByText('Importing assets…')).toBeInTheDocument();
+ expect(screen.getByText(/Log stream unavailable — Connection to the server was lost/)).toBeInTheDocument();
+ });
+
it('flips to running once the process is up, and frames a quit as normal', () => {
renderPanel({ online: true });
expect(screen.getByText(/Running — game/)).toBeInTheDocument();
diff --git a/client/src/components/apps/tabs/ProcessesTab.jsx b/client/src/components/apps/tabs/ProcessesTab.jsx
index 8cfc66478e..7bceafa600 100644
--- a/client/src/components/apps/tabs/ProcessesTab.jsx
+++ b/client/src/components/apps/tabs/ProcessesTab.jsx
@@ -4,7 +4,7 @@ import { Maximize2, X } from 'lucide-react';
import { applyProcessAction } from '../../../services/api';
import BrailleSpinner from '../../BrailleSpinner';
import { FormField } from '../../ui/FormField';
-import ProcessLogLines from '../../ui/ProcessLogLines';
+import ProcessLogLines, { LogStreamBadge } from '../../ui/ProcessLogLines';
import { useProcessSnapshot } from '../../../hooks/useProcessSnapshot';
import { useProcessLogs } from '../../../hooks/useProcessLogs';
import useFocusTrap from '../../../hooks/useFocusTrap';
@@ -35,7 +35,7 @@ export default function ProcessesTab({ appId, pm2ProcessNames, filterFn }) {
// Socket log lifecycle lives in the shared hook so this tab and the desktop
// launch-progress panel can't drift.
- const { logs, subscribed, clear: clearLogs } = useProcessLogs(expandedProcess, { lines: tailLines, appId });
+ const { logs, status, statusDetail, retry, clear: clearLogs } = useProcessLogs(expandedProcess, { lines: tailLines, appId });
const { data, loading, error, refetch, applySnapshot } = useProcessSnapshot(appId);
const processes = data ?? [];
@@ -185,9 +185,7 @@ export default function ProcessesTab({ appId, pm2ProcessNames, filterFn }) {
<div className="flex items-center justify-between px-4 py-2 border-b border-port-border">
<div className="flex items-center gap-3">
<span className="text-xs text-gray-400">Live logs for {proc.name}</span>
- {subscribed && (
- <span className="text-xs text-port-success">● streaming</span>
- )}
+ <LogStreamBadge status={status} />
</div>
<div className="flex items-center gap-3">
<FormField className="flex items-center gap-2" label="Tail lines:" labelClassName="text-xs text-gray-500">
@@ -232,7 +230,7 @@ export default function ProcessesTab({ appId, pm2ProcessNames, filterFn }) {
ref={logsRef}
className="h-[32rem] overflow-auto p-3 font-mono text-xs"
>
- <ProcessLogLines logs={logs} subscribed={subscribed} showTimestamps />
+ <ProcessLogLines logs={logs} status={status} statusDetail={statusDetail} onRetry={retry} showTimestamps />
</div>
</div>
</td>
@@ -276,9 +274,7 @@ export default function ProcessesTab({ appId, pm2ProcessNames, filterFn }) {
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-2 px-4 sm:px-6 py-3 sm:py-4 border-b border-port-border bg-port-card">
<div className="flex flex-wrap items-center gap-2 sm:gap-4">
<span className="text-lg font-medium text-white">Logs: {expandedProcess}</span>
- {subscribed && (
- <span className="text-sm text-port-success">● streaming</span>
- )}
+ <LogStreamBadge status={status} className="text-sm" />
</div>
<div data-testid="fullscreen-log-controls" className="flex flex-wrap items-center gap-2 sm:gap-4">
<FormField className="flex items-center gap-2" label="Tail lines:" labelClassName="text-sm text-gray-500">
@@ -321,7 +317,7 @@ export default function ProcessesTab({ appId, pm2ProcessNames, filterFn }) {
ref={fullscreenLogsRef}
className="flex-1 overflow-auto p-4 font-mono text-sm"
>
- <ProcessLogLines logs={logs} subscribed={subscribed} showTimestamps timestampGap="mr-3" />
+ <ProcessLogLines logs={logs} status={status} statusDetail={statusDetail} onRetry={retry} showTimestamps timestampGap="mr-3" />
</div>
</div>,
document.body
diff --git a/client/src/components/apps/tabs/ProcessesTab.test.jsx b/client/src/components/apps/tabs/ProcessesTab.test.jsx
index 5ccbca25b4..d34624872b 100644
--- a/client/src/components/apps/tabs/ProcessesTab.test.jsx
+++ b/client/src/components/apps/tabs/ProcessesTab.test.jsx
@@ -15,13 +15,13 @@ vi.mock('../../../hooks/useProcessSnapshot', () => ({
}));
vi.mock('../../../hooks/useProcessLogs', () => ({
- useProcessLogs: vi.fn(() => ({ logs: [], subscribed: false, clear: vi.fn() })),
+ useProcessLogs: vi.fn(() => ({ logs: [], status: 'connecting', retry: vi.fn(), clear: vi.fn() })),
}));
vi.mock('../../../lib/clipboard', () => ({ copyToClipboard: vi.fn() }));
vi.mock('../../BrailleSpinner', () => ({ default: () => null }));
vi.mock('../../ui/FormField', () => ({ FormField: ({ children }) => children }));
-vi.mock('../../ui/ProcessLogLines', () => ({ default: () => null }));
+vi.mock('../../ui/ProcessLogLines', () => ({ default: () => null, LogStreamBadge: () => null }));
// `formatCount` is deliberately NOT stubbed — a stub that returns the raw
// number would make the "N lines" assertions blind to a grouping regression.
vi.mock('../../../utils/formatters', async (importOriginal) => ({
@@ -38,7 +38,7 @@ import ProcessesTab from './ProcessesTab';
describe('ProcessesTab', () => {
beforeEach(() => {
vi.clearAllMocks();
- useProcessLogs.mockReturnValue({ logs: [], subscribed: false, clear: vi.fn() });
+ useProcessLogs.mockReturnValue({ logs: [], status: 'connecting', retry: vi.fn(), clear: vi.fn() });
});
it('passes its app id to the expanded process log subscription', () => {
@@ -55,7 +55,7 @@ describe('ProcessesTab', () => {
{ line: 'boot ok', type: 'stdout', timestamp: 100 },
{ line: 'failed once', type: 'stderr', timestamp: 200 },
],
- subscribed: true,
+ status: 'live',
clear: vi.fn(),
});
render(<ProcessesTab appId="app-1" pm2ProcessNames={['example-api']} />);
@@ -139,7 +139,7 @@ describe('ProcessesTab', () => {
it('fullscreen log viewer traps focus within the modal', () => {
useProcessLogs.mockReturnValue({
logs: [{ line: 'test', type: 'stdout', timestamp: 100 }],
- subscribed: false,
+ status: 'connecting',
clear: vi.fn(),
});
render(<ProcessesTab appId="app-1" pm2ProcessNames={['example-api']} />);
diff --git a/client/src/components/ui/ProcessLogLines.jsx b/client/src/components/ui/ProcessLogLines.jsx
index 0e484668f5..ebe64685ed 100644
--- a/client/src/components/ui/ProcessLogLines.jsx
+++ b/client/src/components/ui/ProcessLogLines.jsx
@@ -1,5 +1,35 @@
import { formatTimeOfDaySeconds } from '../../utils/formatters';
+// Status strings mirror `useProcessLogs`' LOG_STREAM_STATUS; kept as literals so
+// this presentational file doesn't import the socket-bound hook module.
+const CONNECTING = 'connecting';
+const LIVE = 'live';
+const isUnavailable = (status) => status != null && status !== CONNECTING && status !== LIVE;
+
+/** Short header label for a log stream's state: streaming when live, an "unavailable" tag when it ended. */
+export function LogStreamBadge({ status, className = 'text-xs' }) {
+ if (status === LIVE) return <span className={`${className} text-port-success`}>● streaming</span>;
+ if (isUnavailable(status)) return <span className={`${className} text-port-warning`}>● unavailable</span>;
+ return null;
+}
+
+function UnavailableNotice({ detail, onRetry }) {
+ return (
+ <div role="status" className="flex flex-wrap items-center gap-x-3 gap-y-1 py-1 text-port-warning">
+ <span>Log stream unavailable{detail ? ` — ${detail}` : ''}</span>
+ {onRetry && (
+ <button
+ type="button"
+ onClick={onRetry}
+ className="px-2 py-0.5 text-xs bg-port-card border border-port-border rounded text-white hover:bg-port-border transition-colors"
+ >
+ Retry
+ </button>
+ )}
+ </div>
+ );
+}
+
/**
* Renders a PM2 process's log lines (the body of a log pane).
*
@@ -10,21 +40,27 @@ import { formatTimeOfDaySeconds } from '../../utils/formatters';
*
* @param {object} props
* @param {Array<{line: string, type: string, timestamp: number}>} props.logs
- * @param {boolean} props.subscribed Whether the stream is connected — distinguishes
- * "not connected yet" from "connected but the process hasn't written anything".
+ * @param {'connecting'|'live'|'closed'|'error'|'disconnected'} props.status Stream state from
+ * `useProcessLogs` — distinguishes "not connected yet" from "connected but the process hasn't
+ * written anything" from "the stream ended" (closed/error/disconnected show an unavailable
+ * notice, keep any captured lines, and offer `onRetry`).
+ * @param {string|null} [props.statusDetail] Why a terminal stream ended.
+ * @param {() => void} [props.onRetry] Manual resubscribe for an unavailable stream.
* @param {boolean} [props.showTimestamps=false] Prefix each line with its local time.
* @param {string} [props.timestampGap='mr-2'] Spacing after the timestamp.
*/
-export default function ProcessLogLines({ logs, subscribed, showTimestamps = false, timestampGap = 'mr-2' }) {
+export default function ProcessLogLines({ logs, status, statusDetail, onRetry, showTimestamps = false, timestampGap = 'mr-2' }) {
+ const unavailable = isUnavailable(status);
if (logs.length === 0) {
+ if (unavailable) return <UnavailableNotice detail={statusDetail} onRetry={onRetry} />;
return (
<div className="text-gray-500">
- {subscribed ? 'Waiting for output…' : 'Connecting to log stream…'}
+ {status === LIVE ? 'Waiting for output…' : 'Connecting to log stream…'}
</div>
);
}
- return logs.map((log, i) => (
+ const rows = logs.map((log, i) => (
<div
key={`${log.timestamp}-${i}`}
className={`py-0.5 whitespace-pre-wrap break-all ${log.type === 'stderr' ? 'text-port-error' : 'text-gray-300'}`}
@@ -37,4 +73,7 @@ export default function ProcessLogLines({ logs, subscribed, showTimestamps = fal
{log.line}
</div>
));
+ return unavailable
+ ? <>{rows}<UnavailableNotice detail={statusDetail} onRetry={onRetry} /></>
+ : rows;
}
diff --git a/client/src/components/ui/README.md b/client/src/components/ui/README.md
index a119838b48..01de46c9ec 100644
--- a/client/src/components/ui/README.md
+++ b/client/src/components/ui/README.md
@@ -31,7 +31,7 @@ accessibility). Feature-specific components live under their own feature directo
| `OverflowMenu` | "…" menu that demotes rare or destructive row actions out of the visible control set. |
| `PageSkeleton` | Full-page loading skeleton that reserves the loaded layout so the first paint doesn't reflow. |
| `Pill` | Inline label badge — semantic tone, optional icon, `sm`/`xs` sizes. |
-| `ProcessLogLines` | Renders a PM2 process's log lines (the body of a log pane). |
+| `ProcessLogLines` | Renders a PM2 process's log lines (the body of a log pane) from `useProcessLogs` `status`, with an unavailable notice + Retry for ended streams; also exports `LogStreamBadge`. |
| `ProcessLogModal` | Self-contained viewer for a PM2 process's system log. |
| `ProgressBar` | Horizontal progress meter — `percent` (or `null` for indeterminate), semantic `tone`, and the ARIA trio with an accessible name from `label`. |
| `ProseEditor` | Prose-writing textarea — serif face, relaxed leading, spellcheck. Markdown string in/out. |
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 8d66c81612..ff93d201a3 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -50,7 +50,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useSpriteRecordCrud` | Rename/delete state machine for one sprite record: `view`/`rename`/`confirm` mode, name draft, busy/inline-error, silent PATCH/DELETE. | A surface that renames or deletes a sprite record (the Library catalog card, the detail header) — share this so both stay in lock-step. |
| `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. |
-| `useProcessLogs` | Live PM2 log tail for one process over the shared socket: owns the `logs:subscribe`/`line`/`subscribed`/`error` lifecycle, per-`processName` frame filtering, and a 1000-line ring buffer. Pass `appId` so an app with its own PM2_HOME streams from the right home. Returns `{ logs, subscribed }`. | Any surface showing a PM2 process's live output (Processes tab, desktop-app launch progress). |
+| `useProcessLogs` | Live PM2 log tail for one process over the shared socket: owns the `logs:subscribe`/`line`/`subscribed`/`error` lifecycle, per-`processName` frame filtering, and a 1000-line ring buffer. Pass `appId` so an app with its own PM2_HOME streams from the right home. Returns `{ logs, subscribed, status, statusDetail, retry, clear }`; `status` is `connecting`/`live`/`closed`/`error`/`disconnected`, shared by every consumer — a closed/errored/disconnected stream keeps its lines and `retry()` resubscribes once (#9959). | Any surface showing a PM2 process's live output (Processes tab, desktop-app launch progress). |
| `useMediaJobProgress` | Live progress for a single `mediaJobQueue` job. | Subscribing to a known media-job id. |
| `useSceneRenderLifecycle` | One Music Video board lane's async-render lifecycle: owns the per-scene spinner state (`genScenes`), job-id→scene correlation, orphan-terminal reconcile, and the durable-attach + `*-gen:completed/failed/canceled` socket subscription (with running-cancel toast disambiguation). Returns `{ genScenes, startScene, clearScene, trackJob }`. | A board lane that kicks media-job renders per scene and clears spinners from terminal events (reference frame, i2v clip). One call per lane. |
| `useSlotInFlight` | Whether a render slot (`{ jobId, filename }`) has an in-flight render; returns `{ inFlight, setStatus }`. A present `filename` (or 5s grace on a stale/expired job) clears `inFlight` so the render button never sticks "loading". | A render button that should disable + spin only while its own slot is actually rendering (comic pages, covers). Wire `setStatus` to the slot's `MediaJobThumb` `onStatus`. |
diff --git a/client/src/hooks/useProcessLogs.js b/client/src/hooks/useProcessLogs.js
index 0e0d67d863..e21c7d299c 100644
--- a/client/src/hooks/useProcessLogs.js
+++ b/client/src/hooks/useProcessLogs.js
@@ -29,17 +29,37 @@ const FLUSH_MS = 250;
// this registry mirrors that existing invariant rather than introducing one.
const registry = new Map(); // processName -> entry
+// Stream lifecycle, shared by every consumer of an entry. `live` is only set by
+// the server's matching `logs:subscribed` ack; the three terminal states keep
+// the captured lines but must never render as an active stream (#9959).
+export const LOG_STREAM_STATUS = Object.freeze({
+ CONNECTING: 'connecting',
+ LIVE: 'live',
+ CLOSED: 'closed', // the PM2 tail child exited
+ ERROR: 'error', // the server reported a stream error
+ DISCONNECTED: 'disconnected', // the socket transport dropped
+});
+const { CONNECTING, LIVE, CLOSED, ERROR, DISCONNECTED } = LOG_STREAM_STATUS;
+const isTerminal = (status) => status === CLOSED || status === ERROR || status === DISCONNECTED;
+
const createEntry = (processName, lines, appId) => ({
processName,
appId,
lines,
- consumers: new Set(), // Set<{ onLine, onSubscribed, onReset }>
+ consumers: new Set(), // Set<{ onLine, onStatus, onReset }>
buffer: [], // shared tail buffer for late joiners, capped at MAX_LINES
- subscribed: false,
+ status: CONNECTING,
+ detail: null, // human-readable reason for a terminal status
});
+const setEntryStatus = (entry, status, detail = null) => {
+ entry.status = status;
+ entry.detail = detail;
+ entry.consumers.forEach((consumer) => consumer.onStatus(status, detail));
+};
+
const subscribeEntry = (entry) => {
- entry.subscribed = false;
+ setEntryStatus(entry, CONNECTING);
socket.emit('logs:subscribe', {
processName: entry.processName,
lines: entry.lines,
@@ -65,14 +85,34 @@ socket.on('logs:line', (data) => {
socket.on('logs:subscribed', (data) => {
const entry = registry.get(data.processName);
if (!entry) return;
- entry.subscribed = true;
- entry.consumers.forEach((consumer) => consumer.onSubscribed());
+ setEntryStatus(entry, LIVE);
});
socket.on('logs:error', (data) => {
const entry = registry.get(data.processName);
if (!entry) return;
appendToEntry(entry, { line: `Error: ${data.error}`, type: 'stderr', timestamp: Date.now() });
+ setEntryStatus(entry, ERROR, String(data.error));
+});
+
+// The server flushes the final buffered lines BEFORE this frame (and suppresses
+// a replaced predecessor's close), so it is a real, terminal end of the stream.
+// With the socket still connected nothing else would ever re-subscribe, so the
+// entry stays closed until the user retries. An earlier `logs:error` keeps its
+// more specific detail.
+socket.on('logs:close', (data) => {
+ const entry = registry.get(data.processName);
+ if (!entry || entry.status === ERROR) return;
+ const code = data.code == null ? '' : ` (exit code ${data.code})`;
+ setEntryStatus(entry, CLOSED, `Log stream closed${code}`);
+});
+
+socket.on('disconnect', (reason) => {
+ registry.forEach((entry) => {
+ if (entry.consumers.size > 0) {
+ setEntryStatus(entry, DISCONNECTED, `Connection to the server was lost${reason ? ` (${reason})` : ''}`);
+ }
+ });
});
// The server drops every stream owned by a disconnected socket
@@ -91,11 +131,29 @@ socket.on('connect', () => {
});
});
+// Manual recovery. Acts only on a terminal entry, so several consumers (or a
+// double click) of one shared stream produce exactly ONE replacement subscribe.
+// A dropped transport reconnects first: its `connect` handler above performs the
+// resubscribe, so emitting here too would subscribe twice.
+const retryEntry = (entry) => {
+ if (!isTerminal(entry.status)) return;
+ if (entry.status === DISCONNECTED && socket.connected === false) {
+ setEntryStatus(entry, CONNECTING);
+ socket.connect?.();
+ return;
+ }
+ // The server replays the PM2 tail on every subscription — drop the old tail
+ // so the replay cannot duplicate history.
+ entry.buffer = [];
+ entry.consumers.forEach((consumer) => consumer.onReset());
+ subscribeEntry(entry);
+};
+
/**
* Subscribe to one PM2 process's live log stream over the shared socket.
*
* Wraps the `logs:subscribe` / `logs:line` / `logs:subscribed` / `logs:error`
- * dance so callers only deal with `{ logs, subscribed }`. Every frame is
+ * dance so callers only deal with `{ logs, status, ... }`. Every frame is
* filtered by `processName` before it lands — the server emits the name on each
* line, and a stale frame from a just-unsubscribed process would otherwise be
* appended to the new one's buffer.
@@ -112,22 +170,31 @@ socket.on('connect', () => {
* @param {number} [options.lines=500] Tail depth requested on subscribe.
* @param {string} [options.appId] App whose custom PM2_HOME holds the process.
* Omit for processes in the default home.
- * @returns {{ logs: Array<{line: string, type: string, timestamp: number}>, subscribed: boolean, clear: () => void }}
+ * @returns {{ logs: Array<{line: string, type: string, timestamp: number}>, subscribed: boolean,
+ * status: 'connecting'|'live'|'closed'|'error'|'disconnected', statusDetail: string|null,
+ * retry: () => void, clear: () => void }}
+ * `status` is shared by every consumer of the process; `subscribed` is just
+ * `status === 'live'`. A `closed`/`error`/`disconnected` stream keeps its
+ * captured lines but is no longer receiving — render it as unavailable and
+ * offer `retry()`, which resubscribes the shared stream once (never an
+ * automatic respawn loop).
* `clear()` empties the local buffer only — the stream stays subscribed, so
* new lines keep arriving (this backs a "Clear" button, not an unsubscribe).
* It never mutates the shared entry buffer, so it does not affect any other
* consumer's view of the same process.
*/
+const INITIAL_STREAM = { status: CONNECTING, detail: null };
+
export function useProcessLogs(processName, options = {}) {
const { lines = 500, appId } = options;
const [logs, setLogs] = useState([]);
- const [subscribed, setSubscribed] = useState(false);
+ const [stream, setStream] = useState(INITIAL_STREAM);
const pendingRef = useRef([]);
const flushTimerRef = useRef(null);
useEffect(() => {
setLogs([]);
- setSubscribed(false);
+ setStream(INITIAL_STREAM);
if (!processName) return undefined;
const flush = () => {
@@ -154,13 +221,14 @@ export function useProcessLogs(processName, options = {}) {
const consumer = {
onLine: queueLine,
- onSubscribed: () => setSubscribed(true),
+ onStatus: (status, detail) => setStream((prev) => (
+ prev.status === status && prev.detail === detail ? prev : { status, detail }
+ )),
onReset: () => {
pendingRef.current = [];
if (flushTimerRef.current != null) clearTimeout(flushTimerRef.current);
flushTimerRef.current = null;
setLogs([]);
- setSubscribed(false);
},
};
entry.consumers.add(consumer);
@@ -182,7 +250,9 @@ export function useProcessLogs(processName, options = {}) {
// consumer's own `lines`) instead of re-subscribing, which would
// replay the tail into every consumer already watching this stream. An
// expanded stream was reset above and will seed from its replay instead.
- if (entry.subscribed) setSubscribed(true);
+ // This also carries a terminal state to the newcomer instead of a false
+ // "connecting"/"live" read off a dead stream.
+ setStream({ status: entry.status, detail: entry.detail });
const seeded = entry.buffer.slice(-lines);
if (seeded.length > 0) setLogs(seeded);
}
@@ -210,7 +280,19 @@ export function useProcessLogs(processName, options = {}) {
setLogs([]);
}, []);
- return { logs, subscribed, clear };
+ const retry = useCallback(() => {
+ const entry = processName ? registry.get(processName) : null;
+ if (entry) retryEntry(entry);
+ }, [processName]);
+
+ return {
+ logs,
+ subscribed: stream.status === LIVE,
+ status: stream.status,
+ statusDetail: stream.detail,
+ retry,
+ clear,
+ };
}
export default useProcessLogs;
diff --git a/client/src/hooks/useProcessLogs.test.jsx b/client/src/hooks/useProcessLogs.test.jsx
index c7b24eb0c7..baa303b0ba 100644
--- a/client/src/hooks/useProcessLogs.test.jsx
+++ b/client/src/hooks/useProcessLogs.test.jsx
@@ -8,9 +8,10 @@ import { renderHook, act, cleanup } from '@testing-library/react';
// per event — unlike the earlier single-consumer version, `handlers` is never
// cleared between tests: the module-level listeners are bound exactly once
// for the whole file and must keep dispatching to every subsequent test.
-const { handlers, emitted } = vi.hoisted(() => ({
+const { handlers, emitted, socketState } = vi.hoisted(() => ({
handlers: new Map(), // event -> Set<fn>
emitted: [],
+ socketState: { connected: true, connectCalls: 0 },
}));
vi.mock('../services/socket', () => ({
default: {
@@ -20,6 +21,8 @@ vi.mock('../services/socket', () => ({
},
off: (event, fn) => { handlers.get(event)?.delete(fn); },
emit: (event, ...args) => { emitted.push([event, ...args]); },
+ get connected() { return socketState.connected; },
+ connect: () => { socketState.connectCalls += 1; },
},
}));
@@ -40,7 +43,12 @@ const fireRaw = (event, payload) => act(() => { handlers.get(event)?.forEach(fn
const emitsOf = (event) => emitted.filter(([e]) => e === event).map(([, payload]) => payload);
describe('useProcessLogs', () => {
- beforeEach(() => { emitted.length = 0; vi.useFakeTimers(); });
+ beforeEach(() => {
+ emitted.length = 0;
+ socketState.connected = true;
+ socketState.connectCalls = 0;
+ vi.useFakeTimers();
+ });
afterEach(() => { cleanup(); vi.useRealTimers(); });
it('subscribes to the named process and reports lines', () => {
@@ -312,4 +320,160 @@ describe('useProcessLogs', () => {
{ line: 'resumed', type: 'stdout', timestamp: 3 },
]);
});
+
+ // --- Terminal stream states (#9959) ---------------------------------
+
+ it('logs:close ends the stream for every consumer but keeps the captured lines and refcounts', () => {
+ const first = renderHook(() => useProcessLogs('game'));
+ const second = renderHook(() => useProcessLogs('game'));
+ fire('logs:subscribed', { processName: 'game' });
+ fire('logs:line', { processName: 'game', line: 'final words', type: 'stderr', timestamp: 1 });
+ expect(first.result.current.status).toBe('live');
+
+ fire('logs:close', { processName: 'game', code: 1 });
+
+ for (const { result } of [first, second]) {
+ expect(result.current.status).toBe('closed');
+ expect(result.current.subscribed).toBe(false);
+ expect(result.current.statusDetail).toBe('Log stream closed (exit code 1)');
+ expect(result.current.logs).toEqual([{ line: 'final words', type: 'stderr', timestamp: 1 }]);
+ }
+
+ // Unmounting one consumer keeps the survivor; the last one unsubscribes once.
+ first.unmount();
+ expect(emitsOf('logs:unsubscribe')).toEqual([]);
+ expect(second.result.current.status).toBe('closed');
+ second.unmount();
+ expect(emitsOf('logs:unsubscribe')).toEqual([{ processName: 'game' }]);
+ });
+
+ it('logs:error marks the stream unavailable and keeps the error line', () => {
+ const { result } = renderHook(() => useProcessLogs('game'));
+ fire('logs:subscribed', { processName: 'game' });
+ fire('logs:error', { processName: 'game', error: 'pm2 unreachable' });
+
+ expect(result.current.status).toBe('error');
+ expect(result.current.statusDetail).toBe('pm2 unreachable');
+ expect(result.current.logs[0]).toMatchObject({ line: 'Error: pm2 unreachable', type: 'stderr' });
+
+ // A follow-up close does not erase the more specific error detail.
+ fire('logs:close', { processName: 'game', code: 1 });
+ expect(result.current.status).toBe('error');
+ expect(result.current.statusDetail).toBe('pm2 unreachable');
+ });
+
+ it('ignores close/error frames for another process', () => {
+ const { result } = renderHook(() => useProcessLogs('game'));
+ fire('logs:subscribed', { processName: 'game' });
+ fire('logs:close', { processName: 'other', code: 1 });
+ fire('logs:error', { processName: 'other', error: 'boom' });
+
+ expect(result.current.status).toBe('live');
+ expect(result.current.logs).toEqual([]);
+ });
+
+ it('a late joiner inherits the terminal state instead of a false live one', () => {
+ const first = renderHook(() => useProcessLogs('game'));
+ fire('logs:subscribed', { processName: 'game' });
+ fire('logs:line', { processName: 'game', line: 'a', type: 'stdout', timestamp: 1 });
+ fire('logs:close', { processName: 'game', code: 0 });
+
+ const late = renderHook(() => useProcessLogs('game'));
+
+ expect(late.result.current.status).toBe('closed');
+ expect(late.result.current.subscribed).toBe(false);
+ expect(late.result.current.logs).toEqual([{ line: 'a', type: 'stdout', timestamp: 1 }]);
+ // Attaching never spawned a replacement stream.
+ expect(emitsOf('logs:subscribe')).toHaveLength(1);
+
+ first.unmount();
+ late.unmount();
+ });
+
+ it('a socket disconnect clears live state across consumers and retains output', () => {
+ const first = renderHook(() => useProcessLogs('game'));
+ const second = renderHook(() => useProcessLogs('game'));
+ fire('logs:subscribed', { processName: 'game' });
+ fire('logs:line', { processName: 'game', line: 'kept', type: 'stdout', timestamp: 1 });
+
+ fire('disconnect', 'transport close');
+
+ for (const { result } of [first, second]) {
+ expect(result.current.status).toBe('disconnected');
+ expect(result.current.subscribed).toBe(false);
+ expect(result.current.logs).toHaveLength(1);
+ }
+ });
+
+ it('reconnect after a disconnect replays once and goes live only on the matching ack', () => {
+ const { result } = renderHook(() => useProcessLogs('game'));
+ fire('logs:subscribed', { processName: 'game' });
+ fire('logs:line', { processName: 'game', line: 'tail', type: 'stdout', timestamp: 1 });
+ fire('disconnect', 'transport close');
+
+ fire('connect', undefined);
+ expect(emitsOf('logs:subscribe')).toHaveLength(2);
+ expect(result.current.status).toBe('connecting');
+ expect(result.current.logs).toEqual([]);
+
+ fire('logs:line', { processName: 'game', line: 'tail', type: 'stdout', timestamp: 2 });
+ expect(result.current.status).toBe('connecting');
+ fire('logs:subscribed', { processName: 'game' });
+ expect(result.current.status).toBe('live');
+ expect(result.current.logs).toEqual([{ line: 'tail', type: 'stdout', timestamp: 2 }]);
+ });
+
+ it('retry() after a close resubscribes the shared stream exactly once, without duplicating history', () => {
+ const first = renderHook(() => useProcessLogs('game'));
+ const second = renderHook(() => useProcessLogs('game'));
+ fire('logs:subscribed', { processName: 'game' });
+ fire('logs:line', { processName: 'game', line: 'old', type: 'stdout', timestamp: 1 });
+ fire('logs:close', { processName: 'game', code: 1 });
+
+ act(() => { first.result.current.retry(); });
+ // The second consumer (or a double click) must not spawn another stream.
+ act(() => { second.result.current.retry(); });
+ act(() => { first.result.current.retry(); });
+
+ expect(emitsOf('logs:subscribe')).toHaveLength(2);
+ expect(first.result.current.status).toBe('connecting');
+ expect(second.result.current.status).toBe('connecting');
+ expect(first.result.current.logs).toEqual([]);
+
+ fire('logs:subscribed', { processName: 'game' });
+ fire('logs:line', { processName: 'game', line: 'old', type: 'stdout', timestamp: 2 });
+ expect(first.result.current.status).toBe('live');
+ expect(second.result.current.logs).toEqual([{ line: 'old', type: 'stdout', timestamp: 2 }]);
+
+ first.unmount();
+ second.unmount();
+ expect(emitsOf('logs:unsubscribe')).toEqual([{ processName: 'game' }]);
+ });
+
+ it('retry() on a live stream is a no-op', () => {
+ const { result } = renderHook(() => useProcessLogs('game'));
+ fire('logs:subscribed', { processName: 'game' });
+ act(() => { result.current.retry(); });
+
+ expect(emitsOf('logs:subscribe')).toHaveLength(1);
+ expect(result.current.status).toBe('live');
+ });
+
+ it('retry() while the transport is down reconnects instead of double-subscribing', () => {
+ const { result } = renderHook(() => useProcessLogs('game'));
+ fire('logs:subscribed', { processName: 'game' });
+ socketState.connected = false;
+ fire('disconnect', 'io server disconnect');
+
+ act(() => { result.current.retry(); });
+
+ expect(socketState.connectCalls).toBe(1);
+ expect(emitsOf('logs:subscribe')).toHaveLength(1);
+ expect(result.current.status).toBe('connecting');
+
+ // The reconnect's own `connect` handler performs the single resubscribe.
+ socketState.connected = true;
+ fire('connect', undefined);
+ expect(emitsOf('logs:subscribe')).toHaveLength(2);
+ });
});