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

perf: stop the global maintenance banner refetching on every journal write (#10954)

Adam Eivy90ae791b152c
diff --git a/client/src/components/MaintenanceBanner.jsx b/client/src/components/MaintenanceBanner.jsx
index 5362b2931f..f3b9acbe19 100644
--- a/client/src/components/MaintenanceBanner.jsx
+++ b/client/src/components/MaintenanceBanner.jsx
@@ -2,10 +2,10 @@ import { Link } from 'react-router';
import { formatCount } from '../utils/formatters.js';
import { useMaintenance } from '../hooks/useMaintenance.js';
export default function MaintenanceBanner() {
- const { status } = useMaintenance();
+ const { status } = useMaintenance({ mode: 'banner' });
if (!status || status.state === 'normal') return null;
const label = status.state === 'ready' ? 'Maintenance ready — new work is held.'
- : status.state === 'draining' ? `Maintenance draining — ${formatCount(status.blockers.length)} operation(s) finishing.`
+ : status.state === 'draining' ? `Maintenance draining — ${formatCount(status.blockerCount)} operation(s) finishing.`
: 'Maintenance readiness unknown.';
return <div role="status" className="px-4 py-2 text-sm bg-port-card border-b border-port-border">{label} <Link className="underline" to="/settings/general">View maintenance</Link></div>;
}
diff --git a/client/src/components/MaintenanceBanner.test.jsx b/client/src/components/MaintenanceBanner.test.jsx
new file mode 100644
index 0000000000..1c3117032f
--- /dev/null
+++ b/client/src/components/MaintenanceBanner.test.jsx
@@ -0,0 +1,23 @@
+import { describe, expect, it, vi } from 'vitest';
+import { render, screen } from '@testing-library/react';
+import { MemoryRouter } from 'react-router';
+const fixture = vi.hoisted(() => ({ status: null, options: null }));
+vi.mock('../hooks/useMaintenance.js', () => ({ useMaintenance: options => { fixture.options = options; return { status: fixture.status }; } }));
+import MaintenanceBanner from './MaintenanceBanner.jsx';
+
+const show = status => { fixture.status = status; return render(<MemoryRouter><MaintenanceBanner /></MemoryRouter>); };
+
+describe('MaintenanceBanner', () => {
+ it('uses the coarse banner mode and renders the draining blocker count', () => {
+ show({ state: 'draining', blockerCount: 3 });
+ expect(fixture.options).toEqual({ mode: 'banner' });
+ expect(screen.getByRole('status')).toHaveTextContent('3 operation(s) finishing');
+ });
+ it('renders nothing for normal operation and a warning for unavailable state', () => {
+ const { container, unmount } = show({ state: 'normal', blockerCount: 0 });
+ expect(container).toBeEmptyDOMElement();
+ unmount();
+ show({ state: 'unavailable', blockerCount: 0 });
+ expect(screen.getByRole('status')).toHaveTextContent('readiness unknown');
+ });
+});
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 142aeb253a..57029e3535 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -100,7 +100,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useShellSession` | All Socket.IO `shell:*` session/terminal state + lifecycle for the Shell page: owns the xterm instance, the attach/detach/generation-guard contract (`pendingAttachRef {target,generation}`, `claim`, `userIdleRef`, `mountedRef`), URL sync, and every session action. Returns `{ terminalRef, connected, sessions, activeSessionId, activeSession, interactiveCount, liveRunCount, isLiveRun, emitShellInput, sendImage, sendCommand, sendCd, sendCtrlB, sendCtrlC, sendNavKey, restartSession, stopSession, startNewSession, switchToSession, killOtherSession }` so the route stays presentational. `sendCd(path)` sends a FOLDER over `shell:cd` rather than composing a `cd` line — the server renders it for the session's actual shell (`server/lib/shellCd.js`), which is the only form that works on a Windows cmd.exe session. `sendCommand(cmd)` submits with CR, never `\n` (see `SUBMIT_KEY` in `server/lib/tuiHandshake.js`). `sendImage(file, message)` is the one operation that leaves the socket — it POSTs to `/api/shell/sessions/:id/image` so a running agent TUI gets the photo's path pasted into its prompt. | The Shell page (`pages/Shell.jsx`) — don't re-roll the single-subscriber PTY attach lifecycle. |
| `useUpdateChecker` | Update-available + install-out-of-sync advisories as *state* (`{ update, outOfSync, ignoreUpdate, dismissUpdate, clearOutOfSync, dismissOutOfSync }`), never toasts — a non-transient advisory must not occlude the screen's primary action (#3786). Out-of-sync dismissals persist per on-disk commit in `safeStorage`, so a later `git pull` re-raises; `clearOutOfSync` is the session-only clear used when the user acts on it. | Never call it directly — `components/UpdateBanners` owns the single instance and Layout renders that once at the app root. A second caller means a second status fetch and socket subscription. |
| `useCharacterAugmentation` | The propose → tick → selectively-apply loop for cast-integrity character augmentation (#6417): owns `preview`/`accepted`/`proposing`/`applying` and enforces the rules both surfaces share — nothing accepted until ticked, "no improvement offered" is a success not an error, and a lock stops the flow at propose AND at apply. Caller supplies only the two request thunks and an `onApplied`. | A surface that augments character framework fields — Universe cast panel and the Writers Room Cast pane both use it; do not re-roll the state machine. |
-| `useMaintenance` | Server-confirmed maintenance status and `refresh`. | Admission hold, blockers, and reconnect invalidation. |
+| `useMaintenance` | Server-confirmed maintenance status and `refresh`; `{ mode: 'banner' }` follows the coarse `maintenance:readiness` push instead of refetching. | Admission hold, blockers, and reconnect invalidation; the global banner. |
| `useLatestRequest` | `begin()` → `isCurrent()`: a latest-request-wins guard. Each `begin()` supersedes earlier requests (and unmount supersedes all), so an older response resolving late can see `isCurrent() === false` and drop its setState. | A load keyed on changing input (a debounced search, a `?subject=` route param) where responses can arrive out of order and overwrite the view the user has already moved to. |
| `useMounted` | `mountedRef` whose `.current` is true while mounted. | Async deferred work that must abort on unmount. |
| `useMemoRecorder` | Owns one memo recorder through permission prompts, stop/cancel, and unmount; exposes `{ recording, starting, start, stop, cancel, stream }`. | Catalog voice memos and song takes. |
diff --git a/client/src/hooks/useMaintenance.js b/client/src/hooks/useMaintenance.js
index 7c2b51770c..6de02697f0 100644
--- a/client/src/hooks/useMaintenance.js
+++ b/client/src/hooks/useMaintenance.js
@@ -3,7 +3,14 @@ import useMounted from './useMounted.js';
import { useSocket } from './useSocket.js';
import { getMaintenanceStatus } from '../services/apiSystem.js';
-export function useMaintenance() {
+// mode 'banner' follows only the coarse `maintenance:readiness` projection
+// ({ state, blockerCount }) after the bootstrap/reconnect read, so detailed
+// operation-journal invalidations never refetch for the always-mounted banner.
+// The default 'detailed' mode refetches the full status (hold identity/revision).
+const toBanner = ({ state, blockers, blockerCount }) => ({ state, blockerCount: blockerCount ?? blockers?.length ?? 0 });
+
+export function useMaintenance({ mode = 'detailed' } = {}) {
+ const banner = mode === 'banner';
const [status, setStatus] = useState(null);
const mounted = useMounted();
const generation = useRef(0);
@@ -12,23 +19,31 @@ export function useMaintenance() {
const requested = ++generation.current;
try {
const next = await getMaintenanceStatus({ silent: true });
- if (mounted.current && requested === generation.current) setStatus(next);
+ if (mounted.current && requested === generation.current) setStatus(banner ? toBanner(next) : next);
} catch {
if (mounted.current && requested === generation.current) setStatus({ state: 'unknown', error: 'Could not read maintenance status.' });
}
- }, [mounted]);
+ }, [mounted, banner]);
useEffect(() => {
refresh();
const disconnected = () => { ++generation.current; setStatus({ state: 'unknown', error: 'Connection lost. Readiness is unknown.' }); };
- socket.on('maintenance:changed', refresh);
+ // A pushed projection is newer than any in-flight read: invalidate it.
+ const readiness = projection => {
+ if (!mounted.current || !projection?.state) return;
+ ++generation.current;
+ setStatus(toBanner(projection));
+ };
+ if (banner) socket.on('maintenance:readiness', readiness);
+ else socket.on('maintenance:changed', refresh);
socket.on('connect', refresh);
socket.on('disconnect', disconnected);
return () => {
++generation.current;
+ socket.off('maintenance:readiness', readiness);
socket.off('maintenance:changed', refresh);
socket.off('connect', refresh);
socket.off('disconnect', disconnected);
};
- }, [socket, refresh]);
+ }, [socket, refresh, banner, mounted]);
return { status, refresh };
}
diff --git a/client/src/hooks/useMaintenance.test.jsx b/client/src/hooks/useMaintenance.test.jsx
index 0bc07501e2..f3c1cb2bc9 100644
--- a/client/src/hooks/useMaintenance.test.jsx
+++ b/client/src/hooks/useMaintenance.test.jsx
@@ -37,3 +37,38 @@ describe('confirmed maintenance readiness', () => {
expect(listeners.size).toBe(0);
});
});
+describe('banner mode', () => {
+ const banner = () => renderHook(() => useMaintenance({ mode: 'banner' }));
+ it('reads once, ignores detailed invalidations, and follows the coarse readiness projection', async () => {
+ fetchStatus.mockResolvedValueOnce({ state: 'normal', blockers: [] });
+ const { result } = banner();
+ await act(async () => {});
+ expect(listeners.has('maintenance:changed')).toBe(false);
+ expect(fetchStatus).toHaveBeenCalledTimes(1);
+ act(() => listeners.get('maintenance:readiness')({ state: 'draining', blockerCount: 2 }));
+ expect(result.current.status).toEqual({ state: 'draining', blockerCount: 2 });
+ act(() => listeners.get('maintenance:readiness')({ state: 'normal', blockerCount: 0 }));
+ expect(result.current.status.state).toBe('normal');
+ expect(fetchStatus).toHaveBeenCalledTimes(1);
+ });
+ it('lets a pushed projection beat an older in-flight read', async () => {
+ const old = deferred();
+ fetchStatus.mockReturnValueOnce(old.promise);
+ const { result } = banner();
+ act(() => listeners.get('maintenance:readiness')({ state: 'draining', blockerCount: 1 }));
+ await act(async () => old.resolve({ state: 'ready', blockers: [] }));
+ expect(result.current.status.state).toBe('draining');
+ });
+ it('goes unknown on disconnect, rereads on reconnect, and unsubscribes everything', async () => {
+ fetchStatus.mockResolvedValueOnce({ state: 'normal', blockers: [] });
+ const { result, unmount } = banner();
+ await act(async () => {});
+ act(() => listeners.get('disconnect')());
+ expect(result.current.status.state).toBe('unknown');
+ fetchStatus.mockResolvedValueOnce({ state: 'draining', blockers: [{}, {}, {}] });
+ await act(async () => listeners.get('connect')());
+ expect(result.current.status).toEqual({ state: 'draining', blockerCount: 3 });
+ unmount();
+ expect(listeners.size).toBe(0);
+ });
+});
diff --git a/server/services/maintenanceControl.js b/server/services/maintenanceControl.js
index 8e69a2e37d..b43d5d6ad1 100644
--- a/server/services/maintenanceControl.js
+++ b/server/services/maintenanceControl.js
@@ -5,16 +5,34 @@ import { assertNotRealDataWrite } from '../lib/testDataIsolation.js';
let watcher;
let timer;
let boundIo;
+let lastReadiness = null;
+
+// Coarse banner projection: state, plus the blocker count only while draining
+// (the one state that displays it). Operation-list/revision churn in a stable
+// state leaves it unchanged. Carries no hold capability, resource, owner or PID.
+export function readinessProjection(status = maintenance.status()) {
+ return { state: status.state, blockerCount: status.state === 'draining' ? status.blockers.length : 0 };
+}
+
+function emitChanges() {
+ boundIo?.emit('maintenance:changed');
+ const next = readinessProjection();
+ if (lastReadiness && lastReadiness.state === next.state && lastReadiness.blockerCount === next.blockerCount) return;
+ lastReadiness = next;
+ boundIo?.emit('maintenance:readiness', next);
+}
+
export function bindMaintenanceIo(io) {
boundIo = io;
if (watcher) return;
+ lastReadiness = readinessProjection();
assertNotRealDataWrite(maintenance.directory, 'maintenance notifications');
mkdirSync(maintenance.directory, { recursive: true, mode: 0o700 });
// Cross-process runner settlements also invalidate the UI. Payload contains
// no operation capability or private resource identity; GET remains auth gated.
watcher = watch(maintenance.directory, () => {
if (timer) clearTimeout(timer);
- timer = setTimeout(() => { timer = null; boundIo?.emit('maintenance:changed'); }, 100);
+ timer = setTimeout(() => { timer = null; emitChanges(); }, 100);
timer.unref?.();
});
watcher.unref?.();
diff --git a/server/services/maintenanceControl.test.js b/server/services/maintenanceControl.test.js
new file mode 100644
index 0000000000..9279ddf56f
--- /dev/null
+++ b/server/services/maintenanceControl.test.js
@@ -0,0 +1,54 @@
+import { afterAll, describe, expect, it, vi } from 'vitest';
+import { rmSync } from 'node:fs';
+
+const gate = vi.hoisted(() => ({ root: null, admission: null }));
+vi.mock('../lib/maintenanceAdmission.js', async () => {
+ const actual = await vi.importActual('../lib/maintenanceAdmission.js');
+ const { mkdtempSync: mk } = await import('node:fs');
+ const { tmpdir: tmp } = await import('node:os');
+ const { join: j } = await import('node:path');
+ gate.root = mk(j(tmp(), 'maintenance-control-'));
+ gate.admission = actual.createMaintenanceAdmission(gate.root);
+ return { ...actual, maintenance: gate.admission };
+});
+import { bindMaintenanceIo, readinessProjection } from './maintenanceControl.js';
+
+afterAll(() => rmSync(gate.root, { recursive: true, force: true }));
+
+const sent = [];
+const io = { emit: (name, payload) => sent.push({ name, payload }) };
+const count = name => sent.filter(e => e.name === name).length;
+
+describe('maintenance notifications', () => {
+ it('keeps detailed invalidations but only pushes the coarse readiness projection when it changes', async () => {
+ bindMaintenanceIo(io);
+ const maintenance = gate.admission;
+
+ // Normal admit/settle churn rewrites the journal but not the banner projection.
+ const op = maintenance.admit('agent', 'resource-that-must-not-leak');
+ await vi.waitFor(() => expect(count('maintenance:changed')).toBeGreaterThanOrEqual(1));
+ op.finish();
+ await vi.waitFor(() => expect(count('maintenance:changed')).toBeGreaterThanOrEqual(2));
+ expect(count('maintenance:readiness')).toBe(0);
+
+ // Hold with a running operation: draining with a blocker count.
+ const running = maintenance.admit('agent', 'resource-that-must-not-leak');
+ maintenance.begin({ reason: 'Service work', owner: 'Operator' });
+ await vi.waitFor(() => expect(count('maintenance:readiness')).toBe(1));
+ expect(sent.find(e => e.name === 'maintenance:readiness').payload).toEqual({ state: 'draining', blockerCount: 1 });
+
+ // Settling the blocker moves to ready (count no longer displayed).
+ running.finish();
+ await vi.waitFor(() => expect(count('maintenance:readiness')).toBe(2));
+ expect(sent.filter(e => e.name === 'maintenance:readiness')[1].payload).toEqual({ state: 'ready', blockerCount: 0 });
+
+ // Leaving the hold returns to normal.
+ const { hold } = maintenance.status();
+ maintenance.resume({ id: hold.id, revision: hold.revision });
+ await vi.waitFor(() => expect(count('maintenance:readiness')).toBe(3));
+
+ // Nothing private is broadcast.
+ expect(JSON.stringify(sent)).not.toMatch(/resource-that-must-not-leak|pid|owner|hold/i);
+ expect(readinessProjection()).toEqual({ state: 'normal', blockerCount: 0 });
+ });
+});