Initial import of streamline
This commit is contained in:
@@ -0,0 +1,57 @@
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import { fetchUserInfo, getCurrentSsoUser, isLogin, loadSsoSdk, login as ssoLogin, logout as ssoLogout, setCurrentSsoUser, ssoAvailable, type SsoUser } from "../lib/sso";
|
||||
import { mockEnabled } from "../lib/mockBoard";
|
||||
import { resetIntro } from "../lib/swarmIntro";
|
||||
|
||||
/**
|
||||
* `?mock=1` on the dev server: SSO can't hand a session to localhost (see
|
||||
* COLLABORATOR.md §6), so the mock board renders as a stand-in viewer. Only the
|
||||
* client's idea of "who am I" — never cached, never sent as a credential; every
|
||||
* authed route still verifies server-side. Dev-only: mockEnabled() is false in builds.
|
||||
*/
|
||||
const MOCK_VIEWER: SsoUser | null = mockEnabled()
|
||||
? { email: "mock.viewer@localhost", name: "Mock viewer", avatarUrl: "" }
|
||||
: null;
|
||||
|
||||
/**
|
||||
* SSO session state for the header. Probes the inspireCloud `getUserInfo` faas
|
||||
* function on mount; if a session exists, exposes the user (avatar/name/email)
|
||||
* and mirrors it into the sso module cache so api.ts can stamp the creator email
|
||||
* on imports. We do NOT auto-redirect to SSO — this is a local tool that must
|
||||
* stay usable off-VPN, so login is an explicit header action.
|
||||
*/
|
||||
export function useSso() {
|
||||
// Seed from the cached profile so a returning user renders instantly — the
|
||||
// spinner only shows on a genuine cold start (no cache).
|
||||
const cached = MOCK_VIEWER ?? getCurrentSsoUser();
|
||||
const [user, setUser] = useState<SsoUser | null>(cached);
|
||||
const [loading, setLoading] = useState(!cached);
|
||||
|
||||
useEffect(() => {
|
||||
if (MOCK_VIEWER) return;
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
// Re-verify in the background. With a cached user this is silent; only a
|
||||
// confirmed logged-out result downgrades the UI back to the gate.
|
||||
// The SDK is a lazy chunk now: if the chunk itself can't be fetched we
|
||||
// could not check at all — keep a cached user rather than log them out.
|
||||
const sdkOk = await loadSsoSdk();
|
||||
if (cancelled) return;
|
||||
if (!sdkOk && cached) { setLoading(false); return; }
|
||||
const u = sdkOk && (await isLogin()) ? await fetchUserInfo() : null;
|
||||
if (cancelled) return;
|
||||
setUser(u);
|
||||
setCurrentSsoUser(u);
|
||||
setLoading(false);
|
||||
})();
|
||||
return () => { cancelled = true; };
|
||||
}, []);
|
||||
|
||||
// The SDK is a lazy chunk (see lib/sso.ts). logout() clears the cached profile
|
||||
// synchronously and queues the SDK teardown ahead of any following login(), so
|
||||
// `logout(); login();` (EddyConnect) still runs in that order.
|
||||
const login = useCallback(() => { void ssoLogin(location.href); }, []);
|
||||
const logout = useCallback(() => { resetIntro(user?.email); void ssoLogout(); setUser(null); }, [user?.email]);
|
||||
|
||||
return { user, loading, login, logout, canLogin: ssoAvailable() };
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
import { useEffect, useMemo, useRef, useState, useCallback } from "react";
|
||||
import type { Task, Feature, Security, Prototype, Verification, BoardItem } from "../types";
|
||||
import { api, wsUrl, type ClusterSnapshot } from "../lib/api";
|
||||
import { fetchLists, startBoardBoot, type ActiveLists, type BoardBoot, type DoneLists } from "../lib/boardLoad";
|
||||
import { mergeMissing, removeOne, replaceRows, tagItem, upsertOne, upsertRows } from "../lib/boardRows";
|
||||
import { applyClusterSnapshot, applyListEval, setClusterState } from "../lib/clusterStore";
|
||||
|
||||
/** Control plane pushes `node:status` every 3s while a tab is attached.
|
||||
* Silence longer than this means the socket is a zombie (proxy drop, sleep). */
|
||||
const WS_STALE_MS = 12_000;
|
||||
const WS_WATCH_MS = 4_000;
|
||||
const WS_BACKOFF_CAP_MS = 15_000;
|
||||
/** One active-slice re-read per burst of `queue:reordered`. */
|
||||
const REORDER_DEBOUNCE_MS = 400;
|
||||
|
||||
function wsBackoffMs(attempt: number): number {
|
||||
return Math.min(1000 * 2 ** attempt, WS_BACKOFF_CAP_MS);
|
||||
}
|
||||
|
||||
/** Close without the handshake-abort console error StrictMode otherwise logs. */
|
||||
function releaseSocket(socket: WebSocket): void {
|
||||
if (socket.readyState === WebSocket.CONNECTING) {
|
||||
socket.addEventListener("open", () => socket.close(), { once: true });
|
||||
} else if (socket.readyState === WebSocket.OPEN) {
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The board's five lists, kept live over the WS.
|
||||
*
|
||||
* `boot`: the first load's requests, already in flight since module load (see
|
||||
* lib/boardLoad.ts — they don't wait on SSO, and a deep link's drawer detail
|
||||
* gates them). Without one the hook starts its own, gated on `holdUntil` the
|
||||
* same way: the server answers in turn, and while it serialises the big lists
|
||||
* the one small request the user is waiting on would sit behind them. Either
|
||||
* way the first load is two-phase — `phase=active` paints the board,
|
||||
* `phase=done` is merged in behind it. Later refreshes are never held.
|
||||
*
|
||||
* The fleet snapshot (nodes / eval / fix slots) is NOT state here: it goes to
|
||||
* lib/clusterStore.ts and is read by the few components that show it, so a
|
||||
* `node:status` no longer re-renders the board.
|
||||
*/
|
||||
export function useTasks({ holdUntil, boot }: { holdUntil?: Promise<unknown> | null; boot?: BoardBoot | null } = {}) {
|
||||
const [tasks, setTasks] = useState<Task[]>([]);
|
||||
const [features, setFeatures] = useState<Feature[]>([]);
|
||||
const [security, setSecurity] = useState<Security[]>([]);
|
||||
const [prototypes, setPrototypes] = useState<Prototype[]>([]);
|
||||
const [verifications, setVerifications] = useState<Verification[]>([]);
|
||||
const [currentId, setCurrentId] = useState<string | null>(null);
|
||||
// The socket handlers close over the mount-time scope; they read these refs.
|
||||
const currentIdRef = useRef<string | null>(null);
|
||||
currentIdRef.current = currentId;
|
||||
const [connected, setConnected] = useState(false);
|
||||
const connectedRef = useRef(false);
|
||||
const wsRef = useRef<WebSocket | null>(null);
|
||||
// Ids deleted over the WS while a list request was in flight: that response
|
||||
// still carries them, and must not bring them back.
|
||||
const deletedRef = useRef(new Set<string>());
|
||||
|
||||
/** Full reload of all five lists (WS reconnect, or a mutation while disconnected). */
|
||||
const refresh = useCallback(async () => {
|
||||
// Satellites in parallel with the lists, not after them: nothing here depends
|
||||
// on the other. The snapshot's eval figure is the fresher one — the list's is
|
||||
// only a fallback for when it hasn't arrived (or /nodes isn't deployed).
|
||||
const nodesDone = api.nodes().then(applyClusterSnapshot).catch(() => { /* control plane may not expose nodes yet */ });
|
||||
deletedRef.current.clear();
|
||||
const d = await fetchLists();
|
||||
// Replace (a row the server no longer lists is gone), but unchanged rows keep
|
||||
// their objects — a reconnect that brings nothing new re-renders nothing.
|
||||
setTasks((prev) => replaceRows(prev, d.tasks, deletedRef.current));
|
||||
setFeatures((prev) => replaceRows(prev, d.features, deletedRef.current));
|
||||
setSecurity((prev) => replaceRows(prev, d.security, deletedRef.current));
|
||||
setPrototypes((prev) => replaceRows(prev, d.prototypes, deletedRef.current));
|
||||
setVerifications((prev) => replaceRows(prev, d.verifications, deletedRef.current));
|
||||
setCurrentId(d.currentId);
|
||||
applyListEval(d.eval);
|
||||
await nodesDone;
|
||||
}, []);
|
||||
|
||||
/**
|
||||
* `queue:reordered` moves priority keys the WS doesn't itemise. They only
|
||||
* exist on queued rows, so re-read just the active slice and upsert it — the
|
||||
* done slice (~70% of the bytes) can't have changed.
|
||||
*/
|
||||
const refreshActive = useCallback(async () => {
|
||||
const d = await fetchLists("active");
|
||||
setTasks((prev) => upsertRows(prev, d.tasks, deletedRef.current));
|
||||
setFeatures((prev) => upsertRows(prev, d.features, deletedRef.current));
|
||||
setSecurity((prev) => upsertRows(prev, d.security, deletedRef.current));
|
||||
setPrototypes((prev) => upsertRows(prev, d.prototypes, deletedRef.current));
|
||||
setVerifications((prev) => upsertRows(prev, d.verifications, deletedRef.current));
|
||||
setCurrentId(d.currentId);
|
||||
applyListEval(d.eval);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
let closed = false;
|
||||
// StrictMode runs this twice; both runs share the boot (nothing is refetched)
|
||||
// and the surviving one marks it consumed.
|
||||
const b = boot && !boot.consumed ? boot : startBoardBoot(holdUntil ?? null);
|
||||
void b.nodes.then((snap) => { if (!closed && snap) applyClusterSnapshot(snap); });
|
||||
void (async () => {
|
||||
deletedRef.current.clear();
|
||||
let a: ActiveLists;
|
||||
try {
|
||||
a = await b.active;
|
||||
} catch {
|
||||
if (!closed) void refresh().catch(() => {});
|
||||
return;
|
||||
}
|
||||
if (closed) return;
|
||||
b.consumed = true;
|
||||
// Upsert, not replace: a WS row that landed before this response is at
|
||||
// least as fresh as it, and a row outside the active slice is not "gone".
|
||||
setTasks((prev) => upsertRows(prev, a.tasks, deletedRef.current));
|
||||
setFeatures((prev) => upsertRows(prev, a.features, deletedRef.current));
|
||||
setSecurity((prev) => upsertRows(prev, a.security, deletedRef.current));
|
||||
setPrototypes((prev) => upsertRows(prev, a.prototypes, deletedRef.current));
|
||||
setVerifications((prev) => upsertRows(prev, a.verifications, deletedRef.current));
|
||||
setCurrentId(a.currentId);
|
||||
applyListEval(a.eval);
|
||||
let d: DoneLists;
|
||||
try { d = await b.done; } catch { return; }
|
||||
if (closed) return;
|
||||
// Only ids we don't have: anything already here came from the active slice
|
||||
// or the WS and is at least as fresh.
|
||||
const skip = deletedRef.current;
|
||||
setTasks((prev) => mergeMissing(prev, d.tasks, skip));
|
||||
setFeatures((prev) => mergeMissing(prev, d.features, skip));
|
||||
setSecurity((prev) => mergeMissing(prev, d.security, skip));
|
||||
})();
|
||||
|
||||
// queue:reordered comes in bursts (one reorder can emit several back to back)
|
||||
// — one re-read per burst.
|
||||
let reorderTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
const onReordered = () => {
|
||||
if (reorderTimer) clearTimeout(reorderTimer);
|
||||
reorderTimer = setTimeout(() => {
|
||||
reorderTimer = null;
|
||||
if (!closed) void refreshActive().catch(() => {});
|
||||
}, REORDER_DEBOUNCE_MS);
|
||||
};
|
||||
|
||||
let socket: WebSocket | null = null;
|
||||
let retryTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let watchTimer: ReturnType<typeof setInterval> | null = null;
|
||||
let attempt = 0;
|
||||
let everOpened = false;
|
||||
let lastHeard = Date.now();
|
||||
|
||||
const applyMessage = (ev: MessageEvent) => {
|
||||
lastHeard = Date.now();
|
||||
try {
|
||||
const msg = JSON.parse(ev.data) as { type: string; payload: unknown };
|
||||
if (msg.type === "task:created" || msg.type === "task:updated") {
|
||||
const t = msg.payload as Task;
|
||||
setTasks((prev) => upsertOne(prev, t));
|
||||
if (t.status === "fixing") setCurrentId(t.id);
|
||||
else if (currentIdRef.current === t.id) setCurrentId(null);
|
||||
} else if (msg.type === "task:deleted") {
|
||||
const { id } = msg.payload as { id: string };
|
||||
deletedRef.current.add(id);
|
||||
setTasks((prev) => removeOne(prev, id));
|
||||
if (currentIdRef.current === id) setCurrentId(null);
|
||||
} else if (msg.type === "feature:created" || msg.type === "feature:updated") {
|
||||
const f = msg.payload as Feature;
|
||||
setFeatures((prev) => upsertOne(prev, f));
|
||||
} else if (msg.type === "feature:deleted") {
|
||||
const { id } = msg.payload as { id: string };
|
||||
deletedRef.current.add(id);
|
||||
setFeatures((prev) => removeOne(prev, id));
|
||||
} else if (msg.type === "security:created" || msg.type === "security:updated") {
|
||||
const s = msg.payload as Security;
|
||||
setSecurity((prev) => upsertOne(prev, s));
|
||||
} else if (msg.type === "security:deleted") {
|
||||
const { id } = msg.payload as { id: string };
|
||||
deletedRef.current.add(id);
|
||||
setSecurity((prev) => removeOne(prev, id));
|
||||
} else if (msg.type === "prototype:created" || msg.type === "prototype:updated") {
|
||||
const p = msg.payload as Prototype;
|
||||
setPrototypes((prev) => upsertOne(prev, p));
|
||||
} else if (msg.type === "prototype:deleted") {
|
||||
const { id } = msg.payload as { id: string };
|
||||
deletedRef.current.add(id);
|
||||
setPrototypes((prev) => removeOne(prev, id));
|
||||
} else if (msg.type === "verification:created" || msg.type === "verification:updated") {
|
||||
const v = msg.payload as Verification;
|
||||
setVerifications((prev) => upsertOne(prev, v));
|
||||
} else if (msg.type === "verification:deleted") {
|
||||
const { id } = msg.payload as { id: string };
|
||||
deletedRef.current.add(id);
|
||||
setVerifications((prev) => removeOne(prev, id));
|
||||
} else if (msg.type === "queue:reordered") {
|
||||
onReordered();
|
||||
} else if (msg.type === "eval:status") {
|
||||
const p = msg.payload as { inFlight: number; capacity: number };
|
||||
setClusterState({ eval: { inFlight: p.inFlight, capacity: p.capacity } });
|
||||
} else if (msg.type === "node:status") {
|
||||
applyClusterSnapshot(msg.payload as ClusterSnapshot);
|
||||
}
|
||||
} catch {}
|
||||
};
|
||||
|
||||
const connect = () => {
|
||||
if (closed) return;
|
||||
if (socket && (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING)) return;
|
||||
const ws = new WebSocket(wsUrl());
|
||||
socket = ws;
|
||||
wsRef.current = ws;
|
||||
ws.onopen = () => {
|
||||
if (closed || socket !== ws) return;
|
||||
lastHeard = Date.now();
|
||||
connectedRef.current = true;
|
||||
setConnected(true);
|
||||
attempt = 0;
|
||||
// Missed events while we were down; skip the first open (the first load covers it).
|
||||
if (everOpened) void refresh().catch(() => {});
|
||||
everOpened = true;
|
||||
};
|
||||
ws.onmessage = (ev) => {
|
||||
if (closed || socket !== ws) return;
|
||||
applyMessage(ev);
|
||||
};
|
||||
ws.onclose = () => {
|
||||
// Only the live socket may touch connected / schedule reconnect.
|
||||
// A CLOSING predecessor can fire after connect() already moved on to a new one.
|
||||
if (closed || socket !== ws) return;
|
||||
socket = null;
|
||||
connectedRef.current = false;
|
||||
setConnected(false);
|
||||
if (retryTimer) clearTimeout(retryTimer);
|
||||
const delay = wsBackoffMs(attempt);
|
||||
attempt += 1;
|
||||
retryTimer = setTimeout(connect, delay);
|
||||
};
|
||||
};
|
||||
|
||||
const reconnectNow = () => {
|
||||
if (closed) return;
|
||||
if (retryTimer) { clearTimeout(retryTimer); retryTimer = null; }
|
||||
attempt = 0;
|
||||
if (socket && socket.readyState === WebSocket.OPEN) {
|
||||
if (Date.now() - lastHeard > WS_STALE_MS) socket.close();
|
||||
return;
|
||||
}
|
||||
connect();
|
||||
};
|
||||
|
||||
connect();
|
||||
watchTimer = setInterval(() => {
|
||||
if (closed || !socket || socket.readyState !== WebSocket.OPEN) return;
|
||||
if (Date.now() - lastHeard > WS_STALE_MS) socket.close();
|
||||
}, WS_WATCH_MS);
|
||||
|
||||
const onVisible = () => {
|
||||
if (document.visibilityState === "visible") reconnectNow();
|
||||
};
|
||||
const onOnline = () => reconnectNow();
|
||||
document.addEventListener("visibilitychange", onVisible);
|
||||
window.addEventListener("online", onOnline);
|
||||
|
||||
return () => {
|
||||
closed = true;
|
||||
if (retryTimer) clearTimeout(retryTimer);
|
||||
if (watchTimer) clearInterval(watchTimer);
|
||||
if (reorderTimer) clearTimeout(reorderTimer);
|
||||
document.removeEventListener("visibilitychange", onVisible);
|
||||
window.removeEventListener("online", onOnline);
|
||||
connectedRef.current = false;
|
||||
if (socket) releaseSocket(socket);
|
||||
};
|
||||
// Mount-once: `boot` / `holdUntil` only matter to the first load, and
|
||||
// currentId is read through its ref rather than as a dependency.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [refresh, refreshActive]);
|
||||
|
||||
// NB: no clock lives here. A `nowTick` in this hook's state re-rendered the
|
||||
// whole board every second — see lib/clock.ts; components that show a clock
|
||||
// subscribe to it themselves, at their own cadence.
|
||||
|
||||
// Merged view: BoardItem[] with kind discriminator. The array is new whenever
|
||||
// any list changes, but each ROW keeps its tagged object for as long as its
|
||||
// source row is unchanged (lib/boardRows.ts::tagItem) — which is what lets
|
||||
// memo(TaskCard) skip every card but the one a WS update touched.
|
||||
const items = useMemo<BoardItem[]>(() => {
|
||||
const out: BoardItem[] = [];
|
||||
for (const t of tasks) out.push(tagItem("bug", t));
|
||||
for (const f of features) out.push(tagItem("feature", f));
|
||||
for (const s of security) out.push(tagItem("security", s));
|
||||
for (const p of prototypes) out.push(tagItem("prototype", p));
|
||||
for (const v of verifications) out.push(tagItem("verify", v));
|
||||
return out;
|
||||
}, [tasks, features, security, prototypes, verifications]);
|
||||
|
||||
/** Is the WS up right now? For callers deciding whether a refetch is redundant. */
|
||||
const isConnected = useCallback(() => connectedRef.current, []);
|
||||
|
||||
return { tasks, features, security, prototypes, verifications, items, currentId, connected, isConnected, refresh };
|
||||
}
|
||||
Reference in New Issue
Block a user