Naseer-010 commited on
Commit
f1982b6
·
1 Parent(s): 32f20b5

fixing frontend

Browse files
Files changed (2) hide show
  1. frontend/app/page.tsx +56 -41
  2. server/app.py +20 -4
frontend/app/page.tsx CHANGED
@@ -1,11 +1,12 @@
1
  "use client";
2
 
3
- import { useEffect, useRef, useState } from "react";
4
  import { FlipWords } from "@/components/ui/FlipWords";
5
  import { FloatingDock } from "@/components/ui/FloatingDock";
6
  import { FocusCards } from "@/components/ui/FocusCards";
7
  import { TextGenerateEffect } from "@/components/ui/TextGenerateEffect";
8
  import { ClusterSimulation } from "@/components/simulation/ClusterSimulation";
 
9
  import type { DockItem, FocusCard } from "@/components/ui/types";
10
 
11
  type TelemetrySnapshot = {
@@ -234,9 +235,8 @@ function RevealSection({
234
  <section
235
  id={id}
236
  ref={ref}
237
- className={`scroll-mt-28 transition-all duration-700 motion-reduce:transform-none motion-reduce:opacity-100 ${
238
- visible ? "translate-y-0 opacity-100" : "translate-y-4 opacity-0"
239
- } ${className ?? ""}`}
240
  >
241
  {children}
242
  </section>
@@ -346,45 +346,61 @@ function parseTelemetry(payload: unknown): TelemetrySnapshot | null {
346
  };
347
  }
348
 
349
- export default function Home() {
350
- const [telemetry, setTelemetry] = useState<TelemetrySnapshot | null>(null);
351
- const [telemetryError, setTelemetryError] = useState<string | null>(null);
352
- const [showScrollCue, setShowScrollCue] = useState(true);
 
 
 
 
 
353
 
354
  useEffect(() => {
355
- let mounted = true;
356
-
357
- const loadTelemetry = async () => {
358
- try {
359
- const response = await fetch("/api/telemetry", { cache: "no-store" });
360
- if (!response.ok) {
361
- throw new Error(`telemetry request failed (${response.status})`);
362
- }
363
-
364
- const payload: unknown = await response.json();
365
- const parsed = parseTelemetry(payload);
366
-
367
- if (!parsed) {
368
- throw new Error("telemetry payload did not match expected schema");
369
- }
 
 
 
 
370
 
371
- if (!mounted) return;
372
- setTelemetry(parsed);
373
- setTelemetryError(null);
374
- } catch (error) {
375
- if (!mounted) return;
376
- setTelemetryError(error instanceof Error ? error.message : "unable to fetch telemetry");
377
- }
378
- };
379
 
380
- loadTelemetry();
381
- const timer = window.setInterval(loadTelemetry, 2500);
 
 
382
 
383
- return () => {
384
- mounted = false;
385
- window.clearInterval(timer);
386
- };
387
- }, []);
 
 
 
 
 
 
 
 
 
 
 
388
 
389
  useEffect(() => {
390
  const onScroll = () => {
@@ -635,9 +651,8 @@ export default function Home() {
635
 
636
  <div className="mt-4 flex items-center gap-2 font-mono text-xs text-zinc-500">
637
  <span
638
- className={`inline-block h-2 w-2 rounded-full ${
639
- DEPLOYMENT_LIVE ? "animate-pulse bg-emerald-400" : "bg-amber-400"
640
- }`}
641
  />
642
  {DEPLOYMENT_LIVE ? "Simulation Online" : "Coming Soon"}
643
  </div>
 
1
  "use client";
2
 
3
+ import { useCallback, useEffect, useRef, useState } from "react";
4
  import { FlipWords } from "@/components/ui/FlipWords";
5
  import { FloatingDock } from "@/components/ui/FloatingDock";
6
  import { FocusCards } from "@/components/ui/FocusCards";
7
  import { TextGenerateEffect } from "@/components/ui/TextGenerateEffect";
8
  import { ClusterSimulation } from "@/components/simulation/ClusterSimulation";
9
+ import { useSimulationSocket } from "@/lib/useSimulationSocket";
10
  import type { DockItem, FocusCard } from "@/components/ui/types";
11
 
12
  type TelemetrySnapshot = {
 
235
  <section
236
  id={id}
237
  ref={ref}
238
+ className={`scroll-mt-28 transition-all duration-700 motion-reduce:transform-none motion-reduce:opacity-100 ${visible ? "translate-y-0 opacity-100" : "translate-y-4 opacity-0"
239
+ } ${className ?? ""}`}
 
240
  >
241
  {children}
242
  </section>
 
346
  };
347
  }
348
 
349
+ function useAnimatedFallback(): TelemetrySnapshot {
350
+ const [snapshot, setSnapshot] = useState<TelemetrySnapshot>({
351
+ step: 0,
352
+ cpuLoads: [0.3, 0.25, 0.4, 0.35, 0.28, 0.32, 0.38, 0.22],
353
+ queueLengths: [4, 6, 3, 8, 5, 7, 2, 4],
354
+ latencyMs: 32.5,
355
+ failedNodes: [],
356
+ requestRate: 142,
357
+ });
358
 
359
  useEffect(() => {
360
+ let step = 0;
361
+ const timer = setInterval(() => {
362
+ step += 1;
363
+ const t = step * 0.15;
364
+ setSnapshot({
365
+ step,
366
+ cpuLoads: Array.from({ length: 8 }, (_, i) =>
367
+ Math.max(0.05, Math.min(0.95, 0.35 + 0.25 * Math.sin(t + i * 0.8) + (Math.random() - 0.5) * 0.08))
368
+ ),
369
+ queueLengths: Array.from({ length: 8 }, (_, i) =>
370
+ Math.max(0, Math.round(12 + 10 * Math.sin(t * 0.7 + i) + Math.random() * 4))
371
+ ),
372
+ latencyMs: Math.max(8, 35 + 20 * Math.sin(t * 0.5) + Math.random() * 8),
373
+ failedNodes: step % 30 > 22 && step % 30 < 28 ? [Math.floor(Math.random() * 7) + 1] : [],
374
+ requestRate: Math.max(50, 150 + 80 * Math.sin(t * 0.3) + Math.random() * 20),
375
+ });
376
+ }, 500);
377
+ return () => clearInterval(timer);
378
+ }, []);
379
 
380
+ return snapshot;
381
+ }
 
 
 
 
 
 
382
 
383
+ export default function Home() {
384
+ const { packet, connected } = useSimulationSocket();
385
+ const animatedFallback = useAnimatedFallback();
386
+ const [showScrollCue, setShowScrollCue] = useState(true);
387
 
388
+ const telemetry: TelemetrySnapshot | null = (() => {
389
+ if (connected && packet?.observation) {
390
+ const obs = packet.observation;
391
+ return {
392
+ step: obs.step ?? 0,
393
+ cpuLoads: obs.cpu_loads ?? [],
394
+ queueLengths: obs.queue_lengths ?? [],
395
+ latencyMs: obs.latency_ms ?? 0,
396
+ failedNodes: obs.failed_nodes ?? [],
397
+ requestRate: obs.request_rate ?? 0,
398
+ };
399
+ }
400
+ return animatedFallback;
401
+ })();
402
+
403
+ const telemetryError: string | null = !connected ? "backend offline — showing animated preview" : null;
404
 
405
  useEffect(() => {
406
  const onScroll = () => {
 
651
 
652
  <div className="mt-4 flex items-center gap-2 font-mono text-xs text-zinc-500">
653
  <span
654
+ className={`inline-block h-2 w-2 rounded-full ${DEPLOYMENT_LIVE ? "animate-pulse bg-emerald-400" : "bg-amber-400"
655
+ }`}
 
656
  />
657
  {DEPLOYMENT_LIVE ? "Simulation Online" : "Coming Soon"}
658
  </div>
server/app.py CHANGED
@@ -22,10 +22,12 @@ _global_env = DistributedInfraEnvironment()
22
  _viz_env = DistributedInfraEnvironment()
23
  _viz_lock = asyncio.Lock()
24
 
 
25
  # 2. Create a "factory function" that returns our active instance
26
  def env_factory():
27
  return _global_env
28
 
 
29
  # 3. Pass the callable factory function to OpenEnv
30
  app = create_app(
31
  env_factory,
@@ -34,16 +36,25 @@ app = create_app(
34
  env_name="distributed_infra_env",
35
  )
36
 
 
 
 
 
 
 
 
 
37
 
38
- #Clear formatted document page for root url
 
39
  @app.get("/")
40
  def home():
41
  # Safely locate the home.html file in the same directory as this script
42
  html_file_path = os.path.join(os.path.dirname(__file__), "home.html")
43
-
44
  with open(html_file_path, "r", encoding="utf-8") as file:
45
  html_content = file.read()
46
-
47
  return HTMLResponse(content=html_content)
48
 
49
 
@@ -110,7 +121,9 @@ async def simulation_socket(websocket: WebSocket):
110
 
111
  obs = _viz_env.step(action=action)
112
  if obs.done:
113
- obs = _viz_env.reset(task=_viz_env.sim.task_id or "cascading_failure")
 
 
114
 
115
  await websocket.send_json(
116
  {
@@ -126,10 +139,13 @@ async def simulation_socket(websocket: WebSocket):
126
  except (WebSocketDisconnect, RuntimeError):
127
  return
128
 
 
129
  def main():
130
  """Entry point for direct execution."""
131
  import uvicorn
 
132
  uvicorn.run(app, host="0.0.0.0", port=8000)
133
 
 
134
  if __name__ == "__main__":
135
  main()
 
22
  _viz_env = DistributedInfraEnvironment()
23
  _viz_lock = asyncio.Lock()
24
 
25
+
26
  # 2. Create a "factory function" that returns our active instance
27
  def env_factory():
28
  return _global_env
29
 
30
+
31
  # 3. Pass the callable factory function to OpenEnv
32
  app = create_app(
33
  env_factory,
 
36
  env_name="distributed_infra_env",
37
  )
38
 
39
+ # --- CORS for Next.js frontend ---
40
+ app.add_middleware(
41
+ CORSMiddleware,
42
+ allow_origins=["http://localhost:3000", "http://127.0.0.1:3000", "*"],
43
+ allow_credentials=True,
44
+ allow_methods=["*"],
45
+ allow_headers=["*"],
46
+ )
47
 
48
+
49
+ # Clear formatted document page for root url
50
  @app.get("/")
51
  def home():
52
  # Safely locate the home.html file in the same directory as this script
53
  html_file_path = os.path.join(os.path.dirname(__file__), "home.html")
54
+
55
  with open(html_file_path, "r", encoding="utf-8") as file:
56
  html_content = file.read()
57
+
58
  return HTMLResponse(content=html_content)
59
 
60
 
 
121
 
122
  obs = _viz_env.step(action=action)
123
  if obs.done:
124
+ obs = _viz_env.reset(
125
+ task=_viz_env.sim.task_id or "cascading_failure"
126
+ )
127
 
128
  await websocket.send_json(
129
  {
 
139
  except (WebSocketDisconnect, RuntimeError):
140
  return
141
 
142
+
143
  def main():
144
  """Entry point for direct execution."""
145
  import uvicorn
146
+
147
  uvicorn.run(app, host="0.0.0.0", port=8000)
148
 
149
+
150
  if __name__ == "__main__":
151
  main()