mirror of
https://github.com/Studio-Saelix/sencho.git
synced 2026-08-20 15:22:59 +00:00
feat: add sidebar update indicator toggle and Stack Health badge (#1570)
* feat: add sidebar update indicator toggle and Stack Health badge - Add image_update_sidebar_indicators setting (default off, node-scoped) - Gate the Updates filter chip and sidebar status indicators on the setting - Add "Update available" badge to Stack Health table (always visible) - Extend ImageUpdateStatus with sidebarIndicators boolean - Poll /api/image-updates/status alongside /detail in useImageUpdates - React to SENCHO_SETTINGS_CHANGED for instant toggle propagation - Reset sidebar state on node switch; generation-guard stale responses - Disable toggle when status is null (loading) or field is absent (old node) - Wire stackUpdates through ViewRouter → HomeDashboard → StackHealthTable - Update settings registry, operator docs, and sidebar/dashboard docs * fix: guard against stale node renders, memo drift, and cross-node error toasts - Track owning node ID in useImageUpdates state so React never renders node B with node A's data before the passive effect resets (P2) - Replace incorrect stackUpdates dependency with sidebarStackUpdates in chipFilteredFiles useMemo (P3) - Guard the error toast in handleSidebarIndicatorsChange so a stale PATCH failure from node A does not surface while viewing node B (P3) * fix: default sidebar update indicators to on (opt-out) The sidebar indicators are a safe convenience that most users want. Switching the default from off to on matches the opt-out convention used by prune_on_update, reclaim_hero, and health_gate_enabled.
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { apiFetch } from '@/lib/api';
|
||||
import type { StackUpdateInfo } from '@/types/imageUpdates';
|
||||
import { SENCHO_SETTINGS_CHANGED } from '@/lib/events';
|
||||
import type { ImageUpdateStatus, StackUpdateInfo } from '@/types/imageUpdates';
|
||||
|
||||
const IMAGE_UPDATE_POLL_MS = 5 * 60 * 1000;
|
||||
|
||||
@@ -10,55 +11,128 @@ const IMAGE_UPDATE_POLL_MS = 5 * 60 * 1000;
|
||||
* `refresh()` to force a refetch (e.g. after a deploy or a manual
|
||||
* registry-check trigger).
|
||||
*
|
||||
* Extracted from EditorLayout so the polling lifecycle and its state
|
||||
* live next to each other instead of being spread across a 3000-line
|
||||
* component. The dependency on `apiFetch` keeps the call routed
|
||||
* through the active-node header just like before.
|
||||
* Also owns the sidebar-indicator toggle preference, fetched from
|
||||
* /api/image-updates/status on the same cadence. All requests are
|
||||
* pinned to the captured node so a mid-flight node switch never
|
||||
* writes stale data.
|
||||
*/
|
||||
export function useImageUpdates(activeNodeId: number | undefined) {
|
||||
const [stackUpdates, setStackUpdates] = useState<Record<string, StackUpdateInfo>>({});
|
||||
const [sidebarIndicators, setSidebarIndicators] = useState(false);
|
||||
|
||||
// Track which node owns the current state. When activeNodeId changes
|
||||
// React renders once with the old owner before the passive effect clears
|
||||
// the data. Returning empty defaults when the IDs mismatch prevents a
|
||||
// single-frame flash of the wrong node's data.
|
||||
const [ownerNodeId, setOwnerNodeId] = useState<number | undefined>(activeNodeId);
|
||||
|
||||
// Generation counter: every activeNodeId change increments it, and every
|
||||
// await is gated against it so a slow response from a previous node is
|
||||
// discarded.
|
||||
const genRef = useRef(0);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const res = await apiFetch('/image-updates/detail');
|
||||
if (res.ok) {
|
||||
setStackUpdates(await res.json() as Record<string, StackUpdateInfo>);
|
||||
return;
|
||||
}
|
||||
// A remote node on an older Sencho lacks /detail; fall back to the boolean
|
||||
// map so update badges keep working until that node is upgraded.
|
||||
if (res.status === 404) {
|
||||
const boolRes = await apiFetch('/image-updates');
|
||||
if (boolRes.ok) {
|
||||
const bool = await boolRes.json() as Record<string, boolean>;
|
||||
const synthesized: Record<string, StackUpdateInfo> = {};
|
||||
for (const [stack, hasUpdate] of Object.entries(bool)) {
|
||||
synthesized[stack] = { hasUpdate, checkStatus: 'ok', lastError: null, checkedAt: 0 };
|
||||
}
|
||||
setStackUpdates(synthesized);
|
||||
const gen = ++genRef.current;
|
||||
const targetNodeId = activeNodeId ?? null;
|
||||
|
||||
// Self-contained status helper: owns fetch, parse, and state write.
|
||||
// A failure here never blocks the detail path below.
|
||||
const fetchStatus = async (): Promise<void> => {
|
||||
try {
|
||||
const res = await apiFetch('/image-updates/status', { nodeId: targetNodeId });
|
||||
if (genRef.current !== gen) return;
|
||||
if (res.ok) {
|
||||
const data = await res.json() as ImageUpdateStatus;
|
||||
if (genRef.current !== gen) return;
|
||||
setSidebarIndicators(data.sidebarIndicators ?? false);
|
||||
} else {
|
||||
console.error('[ImageUpdates] /detail 404 fallback to /image-updates failed:', boolRes.status);
|
||||
console.error('[ImageUpdates] status fetch returned', res.status);
|
||||
}
|
||||
return;
|
||||
} catch (e) {
|
||||
console.error('[ImageUpdates] status fetch failed:', e);
|
||||
}
|
||||
// Any other non-ok (500, or a proxy 5xx from an unreachable remote): keep
|
||||
// the last-known state on screen, but do not let the failure go silent.
|
||||
console.error('[ImageUpdates] /image-updates/detail returned', res.status);
|
||||
} catch (e: unknown) {
|
||||
console.error('[ImageUpdates] fetch failed:', e);
|
||||
}
|
||||
}, []);
|
||||
};
|
||||
|
||||
// Self-contained detail helper: owns fetch, parse, 404 fallback, and
|
||||
// state write. A failure here never blocks the status path above.
|
||||
const fetchDetail = async (): Promise<void> => {
|
||||
try {
|
||||
const res = await apiFetch('/image-updates/detail', { nodeId: targetNodeId });
|
||||
if (genRef.current !== gen) return;
|
||||
if (res.ok) {
|
||||
const data = await res.json() as Record<string, StackUpdateInfo>;
|
||||
if (genRef.current !== gen) return;
|
||||
setStackUpdates(data);
|
||||
return;
|
||||
}
|
||||
// A remote node on an older Sencho lacks /detail; fall back to the boolean
|
||||
// map so update badges keep working until that node is upgraded.
|
||||
if (res.status === 404) {
|
||||
const boolRes = await apiFetch('/image-updates', { nodeId: targetNodeId });
|
||||
if (genRef.current !== gen) return;
|
||||
if (boolRes.ok) {
|
||||
const bool = await boolRes.json() as Record<string, boolean>;
|
||||
if (genRef.current !== gen) return;
|
||||
const synthesized: Record<string, StackUpdateInfo> = {};
|
||||
for (const [stack, hasUpdate] of Object.entries(bool)) {
|
||||
synthesized[stack] = { hasUpdate, checkStatus: 'ok', lastError: null, checkedAt: 0 };
|
||||
}
|
||||
setStackUpdates(synthesized);
|
||||
} else {
|
||||
console.error('[ImageUpdates] /detail 404 fallback to /image-updates failed:', boolRes.status);
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Any other non-ok (500, or a proxy 5xx from an unreachable remote): keep
|
||||
// the last-known state on screen, but do not let the failure go silent.
|
||||
console.error('[ImageUpdates] /image-updates/detail returned', res.status);
|
||||
} catch (e: unknown) {
|
||||
console.error('[ImageUpdates] fetch failed:', e);
|
||||
}
|
||||
};
|
||||
|
||||
await Promise.allSettled([fetchStatus(), fetchDetail()]);
|
||||
}, [activeNodeId]);
|
||||
|
||||
// Pin the interval to the latest closure without retriggering it on
|
||||
// every render the way putting `refresh` into the deps array would.
|
||||
const refreshRef = useRef(refresh);
|
||||
refreshRef.current = refresh;
|
||||
|
||||
// Poll on mount and on node change. Reset state and capture the owning
|
||||
// node BEFORE fetching so the old node's data is cleared before the new
|
||||
// node's first response arrives, and the guard above returns empty defaults
|
||||
// on the render before this effect fires.
|
||||
useEffect(() => {
|
||||
genRef.current += 1;
|
||||
setStackUpdates({}); // eslint-disable-line react-hooks/set-state-in-effect
|
||||
setSidebarIndicators(false); // eslint-disable-line react-hooks/set-state-in-effect
|
||||
setOwnerNodeId(activeNodeId); // eslint-disable-line react-hooks/set-state-in-effect
|
||||
void refreshRef.current();
|
||||
const id = setInterval(() => { void refreshRef.current(); }, IMAGE_UPDATE_POLL_MS);
|
||||
return () => clearInterval(id);
|
||||
}, [activeNodeId]);
|
||||
|
||||
return { stackUpdates, refresh };
|
||||
// React to settings changes so toggling the sidebar-indicator preference
|
||||
// propagates immediately without waiting for the 5-minute poll.
|
||||
useEffect(() => {
|
||||
const handler = (e: Event) => {
|
||||
const detail = (e as CustomEvent<{ changedKeys?: string[] }>).detail;
|
||||
if (detail?.changedKeys?.includes('image_update_sidebar_indicators')) {
|
||||
refreshRef.current();
|
||||
}
|
||||
};
|
||||
window.addEventListener(SENCHO_SETTINGS_CHANGED, handler);
|
||||
return () => window.removeEventListener(SENCHO_SETTINGS_CHANGED, handler);
|
||||
}, []);
|
||||
|
||||
// Return empty defaults until the owning node matches the active node.
|
||||
// This prevents React from rendering node B with node A's update data and
|
||||
// sidebar preference during the single frame before the passive effect fires.
|
||||
const isOwner = activeNodeId !== undefined && activeNodeId === ownerNodeId;
|
||||
return {
|
||||
stackUpdates: isOwner ? stackUpdates : {} as Record<string, StackUpdateInfo>,
|
||||
refresh,
|
||||
sidebarIndicators: isOwner ? sidebarIndicators : false,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user