liven 0.0.5

LIVEN is a fast, lightweight database built to capture, store, and stream data in real time.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
import { Suspense, useState, useEffect, useRef } from "react";
import { WifiOff, RefreshCw, Shield, Activity, XCircle, X } from "lucide-react";
import { Route, Switch, useLocation } from "wouter";

// Components & Pages
import Navbar from "./components/Navbar";
import QueryGuideModal from "./components/QueryGuideModal";
import Dashboard from "./pages/Dashboard";
import QueryConsole from "./pages/QueryConsole";
import StreamExplorer from "./pages/StreamExplorer";
import Security from "./pages/Security";
import Login from "./pages/Login";

// Types, Constants & Helpers
import { Record, Metrics, ActivityLog } from "./types";
import { getDbApiUrl, setDbPort } from "./utils/api";
import { fetchAuthStatus, submitSystemLogout } from "./utils/requests";

export default function App() {
  const [location, setLocation] = useLocation();

  const [securityMode, setSecurityMode] = useState<string>("none");
  const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
  const [userRole, setUserRole] = useState<string | null>(null);
  const [userId, setUserId] = useState<string | null>(null);
  const [authChecking, setAuthChecking] = useState<boolean>(true);
  const [capabilityError, setCapabilityError] = useState<string | null>(null);

  // Register a global fetch interceptor inside useEffect to handle 401/403 redirections
  useEffect(() => {
    const originalFetch = window.fetch;
    window.fetch = async (input, init) => {
      init = init || {};
      init.credentials = "include";
      try {
        const response = await originalFetch(input, init);
        if (response.status === 401) {
          const urlStr =
            typeof input === "string"
              ? input
              : input instanceof Request
                ? input.url
                : "";
          // Exclude check-auth, login and config endpoints to prevent loop
          if (
            !urlStr.includes("/api/system/auth/status") &&
            !urlStr.includes("/api/system/auth/login") &&
            !urlStr.includes("/api/system/config")
          ) {
            setIsAuthenticated(false);
          }
        } else if (response.status === 403) {
          // Authenticated but insufficient role capability — do NOT log out
          // or redirect. Surface the error to the user instead.
          let message = "You don't have permission to perform this action.";
          try {
            const cloned = response.clone();
            const text = await cloned.text();
            if (text) message = text;
          } catch {
            // ignore — fall back to default message
          }
          setCapabilityError(message);
        }
        return response;
      } catch (err) {
        throw err;
      }
    };
    return () => {
      window.fetch = originalFetch;
    };
  }, [setLocation]);

  // Redirection effects for unauthenticated / authenticated routing
  useEffect(() => {
    if (!authChecking) {
      if (securityMode === "auth_key" && !isAuthenticated) {
        if (location !== "/login") {
          setLocation("/login");
        }
      } else if (isAuthenticated && location === "/login") {
        setLocation("/");
      }
    }
  }, [authChecking, securityMode, isAuthenticated, location, setLocation]);

  // Auto-dismiss capability error toast after 4 seconds
  useEffect(() => {
    if (capabilityError) {
      const timer = setTimeout(() => setCapabilityError(null), 4000);
      return () => clearTimeout(timer);
    }
  }, [capabilityError]);

  // Derive activeTab from URL location path for sidebar/header rendering
  let activeTab: "dashboard" | "query" | "explorer" | "security" = "dashboard";
  if (location === "/query") {
    activeTab = "query";
  } else if (location === "/explorer") {
    activeTab = "explorer";
  } else if (location === "/security") {
    activeTab = "security";
  }

  const setActiveTab = (
    tab: "dashboard" | "query" | "explorer" | "security",
  ) => {
    if (tab === "dashboard") {
      setLocation("/");
    } else {
      setLocation("/" + tab);
    }
  };

  // Theme support (system, light, dark)
  const [theme, setTheme] = useState<"system" | "light" | "dark">(
    () =>
      (localStorage.getItem("liven-theme") as "system" | "light" | "dark") ||
      "system",
  );
  const [resolvedTheme, setResolvedTheme] = useState<"light" | "dark">("light");

  useEffect(() => {
    localStorage.setItem("liven-theme", theme);
    const mediaQuery = window.matchMedia("(prefers-color-scheme: dark)");

    const updateTheme = () => {
      let active: "light" | "dark" = "light";
      if (theme === "system") {
        active = mediaQuery.matches ? "dark" : "light";
      } else {
        active = theme;
      }
      setResolvedTheme(active);

      if (active === "dark") {
        document.documentElement.classList.add("dark");
      } else {
        document.documentElement.classList.remove("dark");
      }
    };

    updateTheme();

    if (theme === "system") {
      mediaQuery.addEventListener("change", updateTheme);
      return () => mediaQuery.removeEventListener("change", updateTheme);
    }
  }, [theme]);

  // Server state
  const [wsConnected, setWsConnected] = useState(false);
  const [hasAttemptedConnect, setHasAttemptedConnect] = useState(false);
  const [metrics, setMetrics] = useState<Metrics>({
    ram_usage: 0,
    disk_size: 0,
    segments: 0,
    sequence_id: 0,
    key_count: 0,
    total_streams: 0,
  });

  // Live Activities Log State
  const [activities, setActivities] = useState<ActivityLog[]>([]);
  const [activityFilter, setActivityFilter] = useState<
    "all" | "storage" | "query" | "stream" | "server"
  >("all");

  // Track operational metrics delta
  const prevMetricsRef = useRef<Metrics | null>(null);
  const queriesThisSecondRef = useRef<number>(0);
  const lastSequenceIdRef = useRef<number | null>(null);

  const addActivity = (
    message: string,
    category: "storage" | "query" | "server" | "stream",
    type: "info" | "success" | "warn" | "error" = "info",
  ) => {
    const newLog: ActivityLog = {
      id: Math.random().toString(36).substring(2, 9),
      timestamp: new Date().toLocaleTimeString(),
      type,
      category,
      message,
    };
    setActivities((prev) => [newLog, ...prev].slice(0, 100));
  };

  // Query Console states (lifted up to load templates)
  const [query, setQuery] = useState('from("logs") | limit(10)');
  const [queryResults, setQueryResults] = useState<Record[]>([]);
  const [isQueryRunning, setIsQueryRunning] = useState(false);
  const [queryStats, setQueryStats] = useState({ count: 0, timeMs: 0 });
  const [activeStreamQuery, setActiveStreamQuery] = useState<string | null>(
    null,
  );
  const activeStreamQueryRef = useRef<string | null>(null);
  useEffect(() => {
    activeStreamQueryRef.current = activeStreamQuery;
  }, [activeStreamQuery]);

  const [queryCurrentPage, setQueryCurrentPage] = useState<number>(1);
  const [queryPageSize, setQueryPageSize] = useState<number>(50);
  const [queryError, setQueryError] = useState("");
  const [isHelpOpen, setIsHelpOpen] = useState(false);

  // Database Stream explorer state
  const [streams, setStreams] = useState<string[]>([]);
  const [selectedStream, setSelectedStream] = useState<string>("");
  const [browsedRecords, setBrowsedRecords] = useState<Record[]>([]);
  const [browsedCurrentPage, setBrowsedCurrentPage] = useState<number>(1);
  const [browsedPageSize, setBrowsedPageSize] = useState<number>(50);

  // Historical ingestion chart points (live tracking)
  const [ingestChart, setIngestChart] = useState<number[]>(
    Array.from({ length: 120 }, () => 0),
  );
  const [queryChart, setQueryChart] = useState<number[]>(
    Array.from({ length: 120 }, () => 0),
  );
  const [dbPortVal, setDbPortVal] = useState<string>("43121");
  const [webuiPortVal, setWebuiPortVal] = useState<string>("43120");

  const fetchConfig = async () => {
    try {
      const res = await fetch("/api/system/config");
      if (res.ok) {
        const data = await res.json();
        const webui_port = data.webui_port.toString();
        const db_port = data.db_port.toString();
        setDbPortVal(db_port);
        setWebuiPortVal(webui_port);
        setDbPort(webui_port);
        setSecurityMode(data.security.mode);
        addActivity(
          `System configuration loaded. DB Port: ${db_port}, Web UI Port: ${webui_port}`,
          "server",
          "success",
        );
        return { db_port, webui_port, mode: data.security.mode };
      }
    } catch (e) {
      console.error("Failed to fetch system config:", e);
    }
    return null;
  };

  const wsRef = useRef<WebSocket | null>(null);

  // Load config and check auth on mount
  useEffect(() => {
    const initApp = async () => {
      try {
        const cfg = await fetchConfig();
        if (cfg) {
          if (cfg.mode === "auth_key") {
            try {
              const status = await fetchAuthStatus();
              if (status.authenticated) {
                setIsAuthenticated(true);
                setUserRole(status.role || null);
                setUserId(status.user_id || null);
              } else {
                setIsAuthenticated(false);
                setUserRole(null);
                addActivity(
                  "Administrative session requires security authentication. Challenge response pending.",
                  "server",
                  "warn",
                );
              }
            } catch (err) {
              console.error("Auth status check failed:", err);
              setIsAuthenticated(false);
              setUserRole(null);
            }
          } else {
            setIsAuthenticated(true);
          }
        } else {
          setIsAuthenticated(true);
        }
      } catch (err) {
        console.error("App initialization failed:", err);
      } finally {
        setAuthChecking(false);
      }
    };
    initApp();
  }, []);

  // Redirect from security page if user doesn't have admin role
  useEffect(() => {
    if (!authChecking && location === "/security" && userRole !== "admin") {
      setLocation("/unauthorized");
    }
  }, [authChecking, location, userRole]);

  // Manage WebSocket connection and fetch initial streams when authenticated
  useEffect(() => {
    if (isAuthenticated) {
      connectWS();
      fetchStreams();
    } else {
      if (wsRef.current) {
        wsRef.current.close();
        wsRef.current = null;
      }
      setWsConnected(false);
    }

    return () => {
      if (wsRef.current) {
        wsRef.current.close();
        wsRef.current = null;
      }
    };
  }, [isAuthenticated]);

  // Slide charts forward with 0s if WS disconnected
  useEffect(() => {
    let fallbackInterval: any = null;
    if (!wsConnected) {
      fallbackInterval = setInterval(() => {
        setIngestChart((prev) => [...prev.slice(1), 0]);
        setQueryChart((prev) => [...prev.slice(1), 0]);
      }, 1000);
    }
    return () => {
      if (fallbackInterval) clearInterval(fallbackInterval);
    };
  }, [wsConnected]);

  const connectWS = () => {
    const wsProtocol = window.location.protocol === "https:" ? "wss:" : "ws:";
    const wsUrl = `${wsProtocol}//${window.location.host}/ws`;

    const ws = new WebSocket(wsUrl);
    wsRef.current = ws;

    ws.onopen = () => {
      setWsConnected(true);
      setHasAttemptedConnect(true);
      addActivity(
        "Real-time live WebSocket connection established with backend.",
        "server",
        "success",
      );
    };

    ws.onclose = () => {
      setWsConnected(false);
      setHasAttemptedConnect(true);
      addActivity(
        "Real-time live WebSocket connection lost. Retrying...",
        "server",
        "error",
      );
      if (wsRef.current === ws) {
        setTimeout(() => {
          if (wsRef.current === ws) {
            connectWS();
          }
        }, 3000);
      }
    };

    ws.onmessage = (event) => {
      try {
        const msg = JSON.parse(event.data);
        if (msg.type === "metrics") {
          setMetrics({
            ram_usage: msg.ram_usage,
            disk_size: msg.disk_size,
            segments: msg.segments,
            sequence_id: msg.sequence_id,
            key_count: msg.key_count,
            total_streams: msg.total_streams,
          });

          const newSeq = msg.sequence_id;
          let ingestCount = 0;
          if (lastSequenceIdRef.current !== null) {
            ingestCount = Math.max(0, newSeq - lastSequenceIdRef.current);
          }
          lastSequenceIdRef.current = newSeq;

          // Slide charts forward
          setIngestChart((prev) => [...prev.slice(1), ingestCount]);

          const queryCount = queriesThisSecondRef.current;
          queriesThisSecondRef.current = 0;
          setQueryChart((prev) => [...prev.slice(1), queryCount]);

          // Log activities when database updates or state changes
          if (ingestCount > 0) {
            addActivity(
              `Appended ${ingestCount} record(s) to storage logs (seq #${newSeq - 1})`,
              "storage",
              "success",
            );
          }

          if (prevMetricsRef.current) {
            if (prevMetricsRef.current.key_count !== msg.key_count) {
              addActivity(
                `Database active key index updated: ${msg.key_count} keys in skiplist`,
                "storage",
                "info",
              );
            }
            if (prevMetricsRef.current.segments !== msg.segments) {
              addActivity(
                `New active log segment segment_${msg.segments.toString().padStart(5, "0")}.log allocated`,
                "storage",
                "success",
              );
            }
          }
          prevMetricsRef.current = msg;
        } else if (msg.type === "query_result") {
          if (activeStreamQueryRef.current) {
            setQueryResults((prev) => {
              // If continuous, append and limit to last 200 items to avoid lagging
              const updated = [msg.data, ...prev];
              return updated.slice(0, 200);
            });
            setQueryStats((prev) => ({
              count: prev.count + 1,
              timeMs: prev.timeMs,
            }));
            queriesThisSecondRef.current++;
            addActivity(
              `Streaming query match on [${msg.data.stream_name}] key "${msg.data.key}"`,
              "query",
              "info",
            );
          }
        }
      } catch (e) {
        console.error("WS parse error:", e);
      }
    };
  };

  const fetchStreams = async () => {
    try {
      const res = await fetch(getDbApiUrl("/api/streams"));
      if (res.ok) {
        const data = await res.json();
        setStreams(data);
        const nonSystemStreams = data.filter((s: string) => s !== "auth_keys");
        if (
          nonSystemStreams.length > 0 &&
          (!selectedStream || selectedStream === "auth_keys")
        ) {
          setSelectedStream(nonSystemStreams[0]);
        }
        addActivity(
          `Discovered ${data.length} active database storage stream(s): ${data.join(", ") || "none"}`,
          "stream",
          "success",
        );
      }
    } catch (e) {
      console.error("Failed to fetch streams", e);
      addActivity(
        "Failed to fetch streams list from database REST API",
        "stream",
        "error",
      );
    }
  };

  // Browse records in selected stream
  useEffect(() => {
    if (selectedStream) {
      loadStreamRecords();
    }
  }, [selectedStream]);

  const loadStreamRecords = async () => {
    try {
      // Execute a quick scan query for the specific stream
      const res = await fetch(getDbApiUrl("/api/query"), {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          query: `from("${selectedStream}") | limit(10000)`,
        }),
      });
      if (res.ok) {
        const recs = await res.json();
        setBrowsedRecords(recs);
        setBrowsedCurrentPage(1); // Reset page to 1 on load
        addActivity(
          `Scanned and loaded ${recs.length} records for stream "${selectedStream}"`,
          "stream",
          "info",
        );
      }
    } catch (e) {
      console.error("Failed to load records for stream", e);
      addActivity(
        `Failed to load records for stream "${selectedStream}"`,
        "stream",
        "error",
      );
    }
  };

  const sendHeartbeat = async () => {
    try {
      const response = await fetch(getDbApiUrl("/api/heartbeat"), {
        method: "GET",
        credentials: "include",
      });

      if (!response.ok) {
        console.warn("Heartbeat failed, session may have expired");
        setIsAuthenticated(false);
      }
    } catch (error) {
      console.error("Heartbeat error:", error);
    }
  };

  // Set up heartbeat every 5 minutes (300000 ms) for authenticated users
  useEffect(() => {
    if (isAuthenticated) {
      const heartbeatInterval = setInterval(() => {
        sendHeartbeat();
      }, 300000); // 5 minutes

      return () => clearInterval(heartbeatInterval);
    }
  }, [isAuthenticated]);

  if (authChecking) {
    return (
      <div className="flex items-center justify-center min-h-screen bg-zinc-950">
        <div className="flex flex-col items-center gap-4">
          <div className="animate-spin w-8 h-8 border-2 border-primary border-t-transparent rounded-full" />
          <p className="text-xs font-semibold tracking-widest text-primary uppercase animate-pulse">
            Initializing Gateway...
          </p>
        </div>
      </div>
    );
  }

  if (location === "/login") {
    return (
      <Login
        onLoginSuccess={async () => {
          setIsAuthenticated(true);
          try {
            const status = await fetchAuthStatus();
            setUserRole(status.role || null);
            setUserId(status.user_id || null);
          } catch {
            setUserRole(null);
          }
          setLocation("/");
        }}
      />
    );
  }

  return (
    <>
      <div className="flex flex-col min-h-screen bg-body-bg text-text-main transition-colors duration-300">
        {hasAttemptedConnect && !wsConnected && (
          <div className="fixed inset-0 z-50 backdrop-blur-md flex items-center justify-center p-4 select-none animate-fade-in">
            <div className="bg-white dark:bg-zinc-800 rounded-xl border border-zinc-200/60 dark:border-zinc-800/40 p-6 shadow-lg max-w-xs w-full text-center flex flex-col items-center space-y-4">
              <div className="relative flex items-center justify-center w-10 h-10 rounded-full bg-zinc-100 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700 text-zinc-500 dark:text-zinc-400">
                <WifiOff className="w-5 h-5" />
              </div>

              <div className="space-y-1">
                <h3 className="text-xs font-bold text-zinc-900 dark:text-zinc-100 tracking-wider uppercase">
                  LIVEN Offline
                </h3>
                <p className="text-[11px] text-zinc-500 dark:text-zinc-400">
                  Real-time database socket lost
                </p>
              </div>

              <code className="block w-full bg-zinc-50 dark:bg-zinc-950/40 p-2 rounded text-zinc-600 dark:text-zinc-300 font-mono text-[11px] border border-zinc-200/60 dark:border-zinc-800/40">
                liven start
              </code>

              <button
                onClick={() => {
                  addActivity(
                    "Re-triggering connection attempt...",
                    "server",
                    "info",
                  );
                  window.location.reload();
                }}
                className="w-full py-2 px-4 rounded-md bg-primary hover:bg-primary-hover text-white text-xs font-bold uppercase tracking-wider transition-all active:scale-[0.98] flex items-center justify-center gap-1.5 shadow-sm"
              >
                <RefreshCw className="w-3.5 h-3.5" />
                Reconnect
              </button>
            </div>
          </div>
        )}

        {/* Capability error toast — auto-dismissed after 4 seconds */}
        {capabilityError && (
          <div className="fixed top-4 right-4 z-50 max-w-sm animate-slide-left">
            <div className="bg-rose-50 dark:bg-rose-950/90 border border-rose-200 dark:border-rose-800/60 rounded-lg p-4 shadow-xl flex items-start gap-3">
              <div className="shrink-0 mt-0.5">
                <XCircle className="w-4 h-4 text-rose-500" />
              </div>
              <div className="flex-1 min-w-0">
                <p className="text-xs font-semibold text-rose-800 dark:text-rose-200">
                  {capabilityError}
                </p>
              </div>
              <button
                onClick={() => setCapabilityError(null)}
                className="shrink-0 p-0.5 rounded text-rose-400 hover:text-rose-600 dark:hover:text-rose-300 transition-colors"
              >
                <X className="w-3.5 h-3.5" />
              </button>
            </div>
          </div>
        )}

        {/* TOP NAVBAR & FIXED SIDEBAR */}
        <Navbar
          activeTab={activeTab}
          setActiveTab={setActiveTab}
          theme={theme}
          setTheme={setTheme}
          securityMode={securityMode}
          isAuthenticated={isAuthenticated}
          userRole={userRole}
          onLogout={async () => {
            try {
              await submitSystemLogout();
              setIsAuthenticated(false);
              addActivity(
                "Symmetric session terminated successfully. Redirected to login.",
                "server",
                "info",
              );
            } catch (err: any) {
              console.error("Logout failed:", err);
              addActivity(
                `Failed to gracefully terminate auth session: ${err.message}`,
                "server",
                "error",
              );
            }
          }}
        />

        {/* MAIN PANEL CONTENT */}
        <main className="flex-1 flex flex-col overflow-y-auto pl-0 md:pl-64 pt-14 md:pt-0">
          <div className="flex-1 p-8 space-y-8">
            <Suspense
              fallback={
                <div className="flex items-center justify-center py-20">
                  <div className="animate-spin w-6 h-6 border-2 border-primary border-t-transparent rounded-full" />
                </div>
              }
            >
              <Switch>
                <Route path="/">
                  <Dashboard
                    metrics={metrics}
                    streams={streams}
                    wsConnected={wsConnected}
                    activities={activities}
                    setActivities={setActivities}
                    ingestChart={ingestChart}
                    queryChart={queryChart}
                    activityFilter={activityFilter}
                    setActivityFilter={setActivityFilter}
                    dbPort={dbPortVal}
                    webuiPort={webuiPortVal}
                    resolvedTheme={resolvedTheme}
                  />
                </Route>
                <Route path="/dashboard">
                  <Dashboard
                    metrics={metrics}
                    streams={streams}
                    wsConnected={wsConnected}
                    activities={activities}
                    setActivities={setActivities}
                    ingestChart={ingestChart}
                    queryChart={queryChart}
                    activityFilter={activityFilter}
                    setActivityFilter={setActivityFilter}
                    dbPort={dbPortVal}
                    webuiPort={webuiPortVal}
                    resolvedTheme={resolvedTheme}
                  />
                </Route>
                <Route path="/query">
                  <QueryConsole
                    query={query}
                    setQuery={setQuery}
                    queryResults={queryResults}
                    setQueryResults={setQueryResults}
                    isQueryRunning={isQueryRunning}
                    setIsQueryRunning={setIsQueryRunning}
                    queryStats={queryStats}
                    setQueryStats={setQueryStats}
                    activeStreamQuery={activeStreamQuery}
                    setActiveStreamQuery={setActiveStreamQuery}
                    queryCurrentPage={queryCurrentPage}
                    setQueryCurrentPage={setQueryCurrentPage}
                    queryPageSize={queryPageSize}
                    setQueryPageSize={setQueryPageSize}
                    queryError={queryError}
                    setQueryError={setQueryError}
                    resolvedTheme={resolvedTheme}
                    wsConnected={wsConnected}
                    wsRef={wsRef}
                    queriesThisSecondRef={queriesThisSecondRef}
                    addActivity={addActivity}
                    setIsHelpOpen={setIsHelpOpen}
                    streams={streams}
                    userRole={userRole}
                  />
                </Route>
                <Route path="/explorer">
                  <StreamExplorer
                    streams={streams}
                    selectedStream={selectedStream}
                    setSelectedStream={setSelectedStream}
                    browsedRecords={browsedRecords}
                    setBrowsedRecords={setBrowsedRecords}
                    browsedCurrentPage={browsedCurrentPage}
                    setBrowsedCurrentPage={setBrowsedCurrentPage}
                    browsedPageSize={browsedPageSize}
                    setBrowsedPageSize={setBrowsedPageSize}
                    loadStreamRecords={loadStreamRecords}
                    fetchStreams={fetchStreams}
                    addActivity={addActivity}
                    resolvedTheme={resolvedTheme}
                    userRole={userRole}
                  />
                </Route>
                <Route path="/unauthorized">
                  <div className="flex-1 flex items-center justify-center p-8">
                    <div className="text-center bg-white dark:bg-zinc-900 p-8 rounded-lg border border-zinc-200 dark:border-zinc-800 shadow-lg max-w-md w-full">
                      <div className="mb-6">
                        <Shield className="w-12 h-12 text-rose-500 mx-auto mb-4" />
                        <h2 className="text-2xl font-bold text-zinc-900 dark:text-zinc-100 mb-2">
                          Unauthorized Access
                        </h2>
                        <p className="text-zinc-600 dark:text-zinc-400 mb-1">
                          You don't have permission to access this resource.
                        </p>
                        <p className="text-zinc-500 dark:text-zinc-500 text-sm">
                          Please contact your administrator if you believe this
                          is an error.
                        </p>
                      </div>
                      <button
                        onClick={() => {
                          setLocation("/");
                          setActiveTab("dashboard");
                        }}
                        className="w-full px-4 py-2.5 bg-primary text-white rounded-lg hover:bg-primary-dark transition-all active:scale-[0.98] flex items-center justify-center gap-2 font-semibold"
                      >
                        <Activity className="w-4 h-4" />
                        Return to Dashboard
                      </button>
                    </div>
                  </div>
                </Route>
                <Route path="/security">
                  {userRole === "admin" ? (
                    <Security
                      addActivity={addActivity}
                      resolvedTheme={resolvedTheme}
                      currentKeyId={userId}
                    />
                  ) : (
                    <div className="p-8 text-center bg-white dark:bg-gray-500 rounded-md border border-slate-200 dark:border-slate-800">
                      <h3 className="text-lg font-bold text-slate-900 dark:text-white mb-2">
                        Access Denied
                      </h3>
                      <p className="text-slate-600 dark:text-slate-300 mb-4">
                        You don't have permission to access this page.
                      </p>
                      <button
                        onClick={() => setActiveTab("dashboard")}
                        className="px-4 py-2 bg-primary text-white rounded hover:bg-primary-dark transition-colors"
                      >
                        Return to Dashboard
                      </button>
                    </div>
                  )}
                </Route>
                <Route>
                  <div className="p-8 text-center bg-white dark:bg-gray-500 rounded-md border border-slate-200 dark:border-slate-800">
                    <h3 className="text-lg font-bold text-slate-900 dark:text-white mb-2">
                      Page Not Found
                    </h3>
                    <p className="text-sm text-slate-500 dark:text-slate-400 mb-6">
                      The requested path does not exist on this server.
                    </p>
                    <button
                      onClick={() => setLocation("/")}
                      className="py-2.5 px-5 rounded bg-primary hover:bg-primary-hover text-white text-xs font-semibold active:scale-[0.98] transition-all"
                    >
                      Return to Dashboard
                    </button>
                  </div>
                </Route>
              </Switch>
            </Suspense>
          </div>
        </main>

        {/* HELP GUIDE MODAL DIALOG */}
        <QueryGuideModal
          isOpen={isHelpOpen}
          onClose={() => setIsHelpOpen(false)}
          setQuery={setQuery}
          addActivity={addActivity}
        />
      </div>
    </>
  );
}