Live and historical operation activity: extraction returns, settlements, readiness
diff --git a/src/collections/Shims.ts b/src/collections/Shims.ts
index 98cc768a..735603da 100644
--- a/src/collections/Shims.ts
+++ b/src/collections/Shims.ts
@@ -1,5 +1,6 @@
import { GlobalConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
+import { invalidateConfigCache } from "@/lib/config-cache";
export const Shims: GlobalConfig = {
slug: "shims",
@@ -7,6 +8,10 @@ export const Shims: GlobalConfig = {
read: requirePermission("shims:read"),
update: requirePermission("shims:update"),
},
+ hooks: {
+ // The (frontend) layout caches this global for 60s (lib/config-cache.ts).
+ afterChange: [() => invalidateConfigCache("global:shims")],
+ },
fields: [
{
name: "shims",
diff --git a/src/collections/game/GameRules.ts b/src/collections/game/GameRules.ts
index a5033f86..79f2e655 100644
--- a/src/collections/game/GameRules.ts
+++ b/src/collections/game/GameRules.ts
@@ -1,5 +1,6 @@
import { GlobalConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
+import { invalidateConfigCache } from "@/lib/config-cache";
export const GameRules: GlobalConfig = {
slug: "game-rules",
@@ -7,6 +8,10 @@ export const GameRules: GlobalConfig = {
read: requirePermission("game-rules:read"),
update: requirePermission("game-rules:update"),
},
+ hooks: {
+ // The (frontend) layout caches this global for 60s (lib/config-cache.ts).
+ afterChange: [() => invalidateConfigCache("global:game-rules")],
+ },
fields: [
{
name: "mainCurrency",
diff --git a/src/collections/minigames/Minigames.ts b/src/collections/minigames/Minigames.ts
index cdf1b015..38e0e949 100644
--- a/src/collections/minigames/Minigames.ts
+++ b/src/collections/minigames/Minigames.ts
@@ -1,5 +1,6 @@
import { CollectionConfig } from "payload";
import { requirePermission } from "@/utils/access-control/hasPermission";
+import { invalidateMinigameRegistryCache } from "@/lib/minigames/loadRegistry";
/**
* Registry of minigames.
@@ -26,6 +27,13 @@ export const Minigames: CollectionConfig = {
update: requirePermission("minigames:update"),
delete: requirePermission("minigames:delete"),
},
+ hooks: {
+ // The frontend caches this registry briefly (loadRegistry.ts) because the
+ // layout reads it on every render. Drop that cache on any write so a status
+ // flip (upcoming -> active) is visible immediately.
+ afterChange: [() => invalidateMinigameRegistryCache()],
+ afterDelete: [() => invalidateMinigameRegistryCache()],
+ },
fields: [
{
name: "key",
diff --git a/src/collections/users/Profiles.ts b/src/collections/users/Profiles.ts
index cd76010a..b579fba4 100644
--- a/src/collections/users/Profiles.ts
+++ b/src/collections/users/Profiles.ts
@@ -3,6 +3,7 @@ import { Award } from "@/payload-types";
import { broadcastToUser } from "@/lib/realtime/bus";
import { notifyAwardGrants } from "@/lib/awards";
import { hasPermission } from "@/utils/access-control/hasPermission";
+import { invalidateQualificationCache } from "@/utils/access-control/qualificationCache";
import { lexicalPlaintextLength } from "@/lib/lexical/text";
export const Profiles: CollectionConfig = {
@@ -31,6 +32,10 @@ export const Profiles: CollectionConfig = {
async ({ doc }) => {
const userId = typeof doc.user === "object" ? doc.user?.id : doc.user;
if (typeof userId === "number") {
+ // Qualification flags gate division nav + admin-page access and are
+ // cached for 30s; drop the entry so a granted/revoked qualification
+ // takes effect on the next request instead of up to 30s later.
+ invalidateQualificationCache(userId);
broadcastToUser("profile-update", userId, { profileId: doc.id });
}
},
diff --git a/src/components/frontend/baseManagement/ProductionPanel.tsx b/src/components/frontend/baseManagement/ProductionPanel.tsx
index 61a0206a..46834af4 100644
--- a/src/components/frontend/baseManagement/ProductionPanel.tsx
+++ b/src/components/frontend/baseManagement/ProductionPanel.tsx
@@ -6,7 +6,6 @@ import { toast } from "sonner";
import { Pause, Play } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Item, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item";
-import { useGameTick } from "@/hooks/useGameTick";
import { toggleProduction } from "@/app/(frontend)/logistics/base/actions";
export interface ProductionRecipeLine {
@@ -41,7 +40,6 @@ export function ProductionPanel({
}: ProductionPanelProps) {
const router = useRouter();
const [loading, setLoading] = useState(false);
- useGameTick(() => router.refresh());
if (!complete) return null;
if (inputs.length === 0 && outputs.length === 0) return null;
diff --git a/src/components/frontend/baseManagement/SlotsPanel.tsx b/src/components/frontend/baseManagement/SlotsPanel.tsx
index 4fdb0a71..f4fb53cc 100644
--- a/src/components/frontend/baseManagement/SlotsPanel.tsx
+++ b/src/components/frontend/baseManagement/SlotsPanel.tsx
@@ -7,7 +7,6 @@ import { Blocks, Plus, X } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Item, ItemContent, ItemDescription, ItemTitle } from "@/components/ui/item";
-import { useGameTick } from "@/hooks/useGameTick";
import { installModule, uninstallModule } from "@/app/(frontend)/logistics/base/actions";
export interface ModuleEffectLine {
@@ -51,7 +50,6 @@ export function SlotsPanel({
}: SlotsPanelProps) {
const router = useRouter();
const [loading, setLoading] = useState(null);
- useGameTick(() => router.refresh());
if (slots <= 0 && options.length === 0 && installed.length === 0) return null;
diff --git a/src/components/frontend/blocks/NavCore.tsx b/src/components/frontend/blocks/NavCore.tsx
index 70587be3..c141db27 100644
--- a/src/components/frontend/blocks/NavCore.tsx
+++ b/src/components/frontend/blocks/NavCore.tsx
@@ -37,6 +37,11 @@ export function NavCore({
}) {
if (items.length === 0) return null;
+ // `prefetch={false}` on the links below: the (frontend) layout is
+ // force-dynamic with no loading.tsx, so a prefetched nav link is a full
+ // server render (auth sweep + layout queries). With ~35 sidebar links per
+ // open tab, prefetching turned every page load into dozens of renders.
+ // Navigation itself stays client-side.
return (
{label}
@@ -65,7 +70,7 @@ export function NavCore({
{item.items?.map((subItem) => (
-
+
{subItem.icon ? : null}
{subItem.title}
@@ -77,7 +82,7 @@ export function NavCore({
>
) : (
-
+
{item.title}
diff --git a/src/components/frontend/intelligence/MissionReminderToasts.tsx b/src/components/frontend/intelligence/MissionReminderToasts.tsx
index 7b36dec4..6bef1f5c 100644
--- a/src/components/frontend/intelligence/MissionReminderToasts.tsx
+++ b/src/components/frontend/intelligence/MissionReminderToasts.tsx
@@ -212,7 +212,10 @@ export function MissionReminderToasts() {
writeReminderDismissals(dismissedRef.current, now);
void fetchReminders();
- const interval = setInterval(() => void fetchReminders(), POLL_MS);
+ const interval = setInterval(() => {
+ if (document.hidden) return;
+ void fetchReminders();
+ }, POLL_MS);
return () => {
mountedRef.current = false;
clearInterval(interval);
diff --git a/src/components/frontend/logistics/ShipmentToasts.tsx b/src/components/frontend/logistics/ShipmentToasts.tsx
index 699bc1ce..519ce03b 100644
--- a/src/components/frontend/logistics/ShipmentToasts.tsx
+++ b/src/components/frontend/logistics/ShipmentToasts.tsx
@@ -62,11 +62,16 @@ export function ShipmentToasts() {
useEffect(() => {
fetchShipments();
- const interval = setInterval(fetchShipments, 30_000);
+ const interval = setInterval(() => {
+ if (document.hidden) return;
+ fetchShipments();
+ }, 30_000);
return () => clearInterval(interval);
}, [fetchShipments]);
- useGameTick(() => fetchShipments());
+ useGameTick(() => {
+ if (!document.hidden) fetchShipments();
+ });
if (shipments.length === 0) return null;
diff --git a/src/components/frontend/minigames/ChipBankCard.tsx b/src/components/frontend/minigames/ChipBankCard.tsx
index 7d732d8e..47a016d3 100644
--- a/src/components/frontend/minigames/ChipBankCard.tsx
+++ b/src/components/frontend/minigames/ChipBankCard.tsx
@@ -75,7 +75,10 @@ export function ChipBankCard({ initialChipBank, initialChipTopUpAt }: ChipBankCa
}, [refreshChipState]);
useEffect(() => {
- const poll = window.setInterval(refreshChipState, 5000);
+ const poll = window.setInterval(() => {
+ if (document.hidden) return;
+ refreshChipState();
+ }, 5000);
return () => window.clearInterval(poll);
}, [refreshChipState]);
diff --git a/src/components/frontend/notifications/NotificationsBell.tsx b/src/components/frontend/notifications/NotificationsBell.tsx
index 7af59589..6c995fbf 100644
--- a/src/components/frontend/notifications/NotificationsBell.tsx
+++ b/src/components/frontend/notifications/NotificationsBell.tsx
@@ -81,6 +81,7 @@ export function NotificationsBell() {
const [scope, setScope] = useState(readStoredScope);
const [canViewOthers, setCanViewOthers] = useState(false);
const intervalRef = useRef | null>(null);
+ const eventTimerRef = useRef | null>(null);
const unreadCount = notifications.filter((n) => !n.read).length;
@@ -106,11 +107,27 @@ export function NotificationsBell() {
useEffect(() => {
void fetchNotifications();
- intervalRef.current = setInterval(() => void fetchNotifications(), POLL_MS);
- const onNotification = () => void fetchNotifications();
+ intervalRef.current = setInterval(() => {
+ // A hidden tab costs a full auth + query per poll while nobody is
+ // looking; it catches up on the next poll after it becomes visible.
+ if (document.hidden) return;
+ void fetchNotifications();
+ }, POLL_MS);
+ // A notification burst (e.g. a mission completion granting XP) emits one
+ // event per recipient row. Coalesce them into at most one refetch per
+ // second instead of one request per event.
+ const onNotification = () => {
+ if (document.hidden) return;
+ if (eventTimerRef.current) return;
+ eventTimerRef.current = setTimeout(() => {
+ eventTimerRef.current = null;
+ void fetchNotifications();
+ }, 1000);
+ };
window.addEventListener(NOTIFICATION_EVENT, onNotification);
return () => {
if (intervalRef.current) clearInterval(intervalRef.current);
+ if (eventTimerRef.current) clearTimeout(eventTimerRef.current);
window.removeEventListener(NOTIFICATION_EVENT, onNotification);
};
}, [fetchNotifications]);
diff --git a/src/components/frontend/operations/OperationsRealtimeRefresher.tsx b/src/components/frontend/operations/OperationsRealtimeRefresher.tsx
deleted file mode 100644
index 0110f93b..00000000
--- a/src/components/frontend/operations/OperationsRealtimeRefresher.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-"use client";
-
-import { useRouter } from "next/navigation";
-import { useGameTick } from "@/hooks/useGameTick";
-
-/**
- * Enhancement-only realtime refresh for /operations surfaces. The server
- * re-fetch on navigation is the correctness source; this only triggers an
- * early refresh when a game tick lands while the page is open.
- */
-export function OperationsRealtimeRefresher() {
- const router = useRouter();
- useGameTick(() => {
- router.refresh();
- });
- return null;
-}
diff --git a/src/components/frontend/operations/index.ts b/src/components/frontend/operations/index.ts
index 9907b6d4..3e5d49ef 100644
--- a/src/components/frontend/operations/index.ts
+++ b/src/components/frontend/operations/index.ts
@@ -7,7 +7,6 @@ export { NoticeState } from "./NoticeState";
export { StrategicSummary } from "./StrategicSummary";
export { PageShell } from "./PageShell";
export { STATUS_TONE_CLASSES, DOSSIER, statusToneFor, type StatusTone } from "./tokens";
-export { OperationsRealtimeRefresher } from "./OperationsRealtimeRefresher";
export {
RecentOperationsCard,
MyExtractionsCard,
diff --git a/src/components/frontend/realtime/GameTickRealtime.tsx b/src/components/frontend/realtime/GameTickRealtime.tsx
index 93214a51..fffc80ff 100644
--- a/src/components/frontend/realtime/GameTickRealtime.tsx
+++ b/src/components/frontend/realtime/GameTickRealtime.tsx
@@ -39,13 +39,40 @@ export function GameTickRealtime() {
useEffect(() => {
const source = new EventSource("/api/realtime");
let refreshTimer: ReturnType | null = null;
- const refresh = (delay = 250) => {
+ let skippedWhileHidden = false;
+ /**
+ * One coalesced refresh per burst. The window used to be 250ms, which real
+ * bursts walk straight through: a mission completion grants one XP event
+ * per attendee (40-120 broadcasts in a few seconds), and each broadcast
+ * re-renders the whole route tree (layout + page, ~20 queries) for every
+ * connected client. A 1s window keeps the same visible update latency while
+ * turning a burst into a couple of renders instead of dozens.
+ *
+ * Hidden tabs skip the render entirely; they cost the server a full SSR pass
+ * for a page nobody is looking at. They refresh once when they become
+ * visible again.
+ */
+ const refresh = (delay = 1000) => {
+ if (typeof document !== "undefined" && document.hidden) {
+ skippedWhileHidden = true;
+ return;
+ }
if (refreshTimer) return;
refreshTimer = setTimeout(() => {
refreshTimer = null;
+ if (document.hidden) {
+ skippedWhileHidden = true;
+ return;
+ }
router.refresh();
}, delay);
};
+ const onVisibility = () => {
+ if (document.hidden || !skippedWhileHidden) return;
+ skippedWhileHidden = false;
+ refresh(0);
+ };
+ document.addEventListener("visibilitychange", onVisibility);
source.addEventListener("game-tick", (event) => {
let detail: GameTickDetail = {};
try {
@@ -147,6 +174,7 @@ export function GameTickRealtime() {
});
return () => {
if (refreshTimer) clearTimeout(refreshTimer);
+ document.removeEventListener("visibilitychange", onVisibility);
source.close();
};
}, [router]);
diff --git a/src/components/frontend/storage/EventLedger.tsx b/src/components/frontend/storage/EventLedger.tsx
index 066e2701..fd25a9dd 100644
--- a/src/components/frontend/storage/EventLedger.tsx
+++ b/src/components/frontend/storage/EventLedger.tsx
@@ -110,12 +110,14 @@ export function EventLedger({
useEffect(() => {
const interval = setInterval(() => {
+ if (document.hidden) return;
if (initialDone.current) fetchEntries();
}, 30_000);
return () => clearInterval(interval);
}, [fetchEntries]);
useGameTick(() => {
+ if (document.hidden) return;
if (initialDone.current) fetchEntries();
});
diff --git a/src/lib/config-cache.ts b/src/lib/config-cache.ts
new file mode 100644
index 00000000..c4e5881a
--- /dev/null
+++ b/src/lib/config-cache.ts
@@ -0,0 +1,75 @@
+/**
+ * Tiny TTL cache for admin-authored configuration reads.
+ *
+ * The `(frontend)` layout renders on every navigation and on every realtime
+ * refresh, and it reads globals that change maybe once a month (shims, game
+ * rules). Under concurrent load those reads multiply by clients x refreshes for
+ * data that is identical for everyone.
+ *
+ * Only use this for values that are the same for every user and are edited by
+ * admins, never for anything user-scoped (permissions, presence, balances).
+ * `globalThis`-anchored so route bundles share one copy, like the SSE bus and
+ * the minigame registry cache.
+ */
+const DEFAULT_TTL_MS = 60_000;
+
+interface CacheEntry {
+ value: unknown;
+ loadedAt: number;
+}
+
+interface CacheHolder {
+ __ptfConfigCache?: Map;
+ __ptfConfigInflight?: Map>;
+}
+
+function holder(): CacheHolder {
+ return globalThis as typeof globalThis & CacheHolder;
+}
+
+function entries(): Map {
+ const store = holder();
+ return (store.__ptfConfigCache ??= new Map());
+}
+
+function inflight(): Map> {
+ const store = holder();
+ return (store.__ptfConfigInflight ??= new Map>());
+}
+
+export async function cachedConfig(
+ key: string,
+ load: () => Promise,
+ ttlMs: number = DEFAULT_TTL_MS,
+): Promise {
+ const now = Date.now();
+ const hit = entries().get(key);
+ if (hit && now - hit.loadedAt < ttlMs) return hit.value as T;
+
+ const pending = inflight().get(key);
+ if (pending) return pending as Promise;
+
+ const promise = load()
+ .then((value) => {
+ entries().set(key, { value, loadedAt: Date.now() });
+ inflight().delete(key);
+ return value;
+ })
+ .catch((error: unknown) => {
+ inflight().delete(key);
+ throw error;
+ });
+
+ inflight().set(key, promise as Promise);
+ return promise;
+}
+
+/** Drop one cached key, or the whole cache when no key is given. */
+export function invalidateConfigCache(key?: string): void {
+ if (key === undefined) {
+ entries().clear();
+ inflight().clear();
+ return;
+ }
+ entries().delete(key);
+}
diff --git a/src/lib/contributions/index.ts b/src/lib/contributions/index.ts
index 76b8e6b6..eadd015c 100644
--- a/src/lib/contributions/index.ts
+++ b/src/lib/contributions/index.ts
@@ -97,22 +97,6 @@ function actorLabel(userId: number, actorName?: string | null): string {
return actorName && actorName.trim().length > 0 ? actorName : `User #${userId}`;
}
-/** Resolve a user's display name for human-readable event messages. */
-async function resolveUserName(payload: Payload, userId: number): Promise {
- try {
- const user = (await payload.findByID({
- collection: "users",
- id: userId,
- depth: 0,
- overrideAccess: true,
- select: { displayName: true, username: true },
- })) as unknown as { displayName?: string | null; username?: string | null };
- return user.displayName || user.username || `User #${userId}`;
- } catch {
- return `User #${userId}`;
- }
-}
-
/** Deterministic content hash for deduping wiki edits. Server-only. */
export function contentHash(text: string): string {
return createHash("sha256").update(text).digest("hex").slice(0, 16);
@@ -183,23 +167,81 @@ async function missionEntryCount(
return totalDocs;
}
-async function sourceStillExists(
- payload: Payload,
- sourceCollection: ContributionSourceCollection,
- sourceId: number,
-): Promise {
- if (sourceCollection === "manual") return true;
+async function resolveUserNames(payload: Payload, userIds: number[]): Promise