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
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
import { useState, useEffect, useRef } from "react";
import { ChevronLeft } from "lucide-react";
import { Header } from "@/components/header";
import { Footer } from "@/components/footer";
import { EditRobotDialog } from "@/components/edit-robot-dialog";
import { DeviceDashboard } from "@/components/device-dashboard";
import { CalibrationView } from "@/components/calibration-view";
import { TeleoperationView } from "@/components/teleoperation-view";
import { SetupCards } from "@/components/setup-cards";
import { DocsSection } from "@/components/docs-section";
import { RoadmapSection } from "@/components/roadmap-section";
import { HardwareSupportSection } from "@/components/hardware-support-section";
import { useToast } from "@/hooks/use-toast";
import { Toaster } from "@/components/ui/toaster";
import {
  findPort,
  isWebSerialSupported,
  type RobotConnection,
  type RobotConfig,
} from "@lerobot/web";
import {
  getAllSavedRobots,
  getUnifiedRobotData,
  saveDeviceInfo,
  removeRobotData,
  type DeviceInfo,
} from "@/lib/unified-storage";

function App() {
  const [view, setView] = useState<
    "dashboard" | "calibrating" | "teleoperating"
  >("dashboard");
  const [robots, setRobots] = useState<RobotConnection[]>([]);
  const [selectedRobot, setSelectedRobot] = useState<RobotConnection | null>(
    null
  );
  const [editingRobot, setEditingRobot] = useState<RobotConnection | null>(
    null
  );
  const [isConnecting, setIsConnecting] = useState(false);
  const hardwareSectionRef = useRef<HTMLDivElement>(null);
  const { toast } = useToast();

  // Check browser support
  const isSupported = isWebSerialSupported();

  useEffect(() => {
    if (!isSupported) {
      toast({
        title: "Browser Not Supported",
        description:
          "WebSerial API is not supported. Please use Chrome, Edge, or another Chromium-based browser.",
        variant: "destructive",
      });
    }
  }, [isSupported, toast]);

  useEffect(() => {
    const loadSavedRobots = async () => {
      if (!isSupported) return;

      try {
        setIsConnecting(true);

        // Get saved robot configurations
        const savedRobots = getAllSavedRobots();

        if (savedRobots.length > 0) {
          const robotConfigs: RobotConfig[] = savedRobots.map((device) => ({
            robotType: device.robotType as "so100_follower" | "so100_leader",
            robotId: device.robotId,
            serialNumber: device.serialNumber,
          }));

          // Auto-connect to saved robots
          const findPortProcess = await findPort({
            robotConfigs,
            onMessage: (msg: string) => {
              console.log("Connection message:", msg);
            },
          });

          const reconnectedRobots = await findPortProcess.result;

          // Merge saved device info (names, etc.) with fresh connection data
          const robotsWithSavedInfo = reconnectedRobots.map((robot) => {
            const savedData = getUnifiedRobotData(robot.serialNumber || "");
            if (savedData?.device_info) {
              return {
                ...robot,
                robotId: savedData.device_info.robotId,
                name: savedData.device_info.robotId, // Use the saved custom name
                robotType: savedData.device_info.robotType as
                  | "so100_follower"
                  | "so100_leader",
              };
            }
            return robot;
          });

          setRobots(robotsWithSavedInfo);
        }
      } catch (error) {
        console.error("Failed to load saved robots:", error);
        toast({
          title: "Connection Error",
          description: "Failed to reconnect to saved robots",
          variant: "destructive",
        });
      } finally {
        setIsConnecting(false);
      }
    };

    loadSavedRobots();
  }, [isSupported, toast]);

  const handleFindNewRobots = async () => {
    if (!isSupported) {
      toast({
        title: "Browser Not Supported",
        description: "WebSerial API is required for robot connection",
        variant: "destructive",
      });
      return;
    }

    try {
      setIsConnecting(true);

      // Interactive mode - show browser dialog
      const findPortProcess = await findPort({
        onMessage: (msg: string) => {
          console.log("Find port message:", msg);
        },
      });

      const newRobots = await findPortProcess.result;

      if (newRobots.length > 0) {
        setRobots((prev: RobotConnection[]) => {
          const existingSerialNumbers = new Set(
            prev.map((r: RobotConnection) => r.serialNumber)
          );
          const uniqueNewRobots = newRobots.filter(
            (r: RobotConnection) => !existingSerialNumbers.has(r.serialNumber)
          );

          // Auto-edit first new robot for configuration
          if (uniqueNewRobots.length > 0) {
            setEditingRobot(uniqueNewRobots[0]);
          }

          return [...prev, ...uniqueNewRobots];
        });

        toast({
          title: "Robots Found",
          description: `Found ${newRobots.length} robot(s)`,
        });
      } else {
        toast({
          title: "No Robots Found",
          description: "No compatible devices detected",
        });
      }
    } catch (error) {
      console.error("Failed to find robots:", error);
      toast({
        title: "Connection Error",
        description: "Failed to find robots. Please try again.",
        variant: "destructive",
      });
    } finally {
      setIsConnecting(false);
    }
  };

  const handleUpdateRobot = (updatedRobot: RobotConnection) => {
    // Save device info to unified storage
    if (updatedRobot.serialNumber && updatedRobot.robotId) {
      const deviceInfo: DeviceInfo = {
        serialNumber: updatedRobot.serialNumber,
        robotType: updatedRobot.robotType || "so100_follower",
        robotId: updatedRobot.robotId,
        usbMetadata: updatedRobot.usbMetadata
          ? {
              vendorId: parseInt(updatedRobot.usbMetadata.vendorId || "0", 16),
              productId: parseInt(
                updatedRobot.usbMetadata.productId || "0",
                16
              ),
              serialNumber: updatedRobot.usbMetadata.serialNumber,
              manufacturer: updatedRobot.usbMetadata.manufacturerName,
              product: updatedRobot.usbMetadata.productName,
            }
          : undefined,
      };
      saveDeviceInfo(updatedRobot.serialNumber, deviceInfo);
    }

    setRobots((prev) =>
      prev.map((r) =>
        r.serialNumber === updatedRobot.serialNumber ? updatedRobot : r
      )
    );
    setEditingRobot(null);
  };

  const handleRemoveRobot = (robotId: string) => {
    const robot = robots.find((r) => r.robotId === robotId);
    if (robot?.serialNumber) {
      removeRobotData(robot.serialNumber);
    }

    setRobots((prev) => prev.filter((r) => r.robotId !== robotId));

    toast({
      title: "Robot Removed",
      description: `${robotId} has been removed from the registry`,
    });
  };

  const handleCalibrate = (robot: RobotConnection) => {
    if (!robot.isConnected) {
      toast({
        title: "Robot Not Connected",
        description: "Please connect the robot before calibrating",
        variant: "destructive",
      });
      return;
    }

    setSelectedRobot(robot);
    setView("calibrating");
  };

  const handleTeleoperate = (robot: RobotConnection) => {
    if (!robot.isConnected) {
      toast({
        title: "Robot Not Connected",
        description: "Please connect the robot before teleoperating",
        variant: "destructive",
      });
      return;
    }

    setSelectedRobot(robot);
    setView("teleoperating");
  };

  const handleCloseSubView = () => {
    setSelectedRobot(null);
    setView("dashboard");
  };

  const scrollToHardware = () => {
    hardwareSectionRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  const renderView = () => {
    switch (view) {
      case "calibrating":
        return selectedRobot && <CalibrationView robot={selectedRobot} />;
      case "teleoperating":
        return selectedRobot && <TeleoperationView robot={selectedRobot} />;
      case "dashboard":
      default:
        return (
          <div className="space-y-20">
            <DeviceDashboard
              robots={robots}
              onCalibrate={handleCalibrate}
              onTeleoperate={handleTeleoperate}
              onRemove={handleRemoveRobot}
              onEdit={setEditingRobot}
              onFindNew={handleFindNewRobots}
              isConnecting={isConnecting}
              onScrollToHardware={scrollToHardware}
            />
            <div>
              <div className="mb-6">
                <h2 className="text-3xl font-bold font-mono tracking-wider mb-2 uppercase">
                  install
                </h2>
                <p className="text-sm text-muted-foreground font-mono">
                  Choose your preferred development environment
                </p>
              </div>
              <SetupCards />
            </div>
            <DocsSection />
            <RoadmapSection />
            <div ref={hardwareSectionRef}>
              <HardwareSupportSection />
            </div>
          </div>
        );
    }
  };

  const PageHeader = () => {
    return (
      <div className="flex items-center justify-between mb-12">
        <div className="flex items-center gap-4">
          <div>
            {view === "calibrating" && selectedRobot ? (
              <h1 className="font-mono text-4xl font-bold tracking-wider">
                <span className="text-muted-foreground uppercase">
                  calibrate:
                </span>{" "}
                <span
                  className="text-primary text-glitch uppercase"
                  data-text={selectedRobot.robotId}
                >
                  {selectedRobot.robotId?.toUpperCase()}
                </span>
              </h1>
            ) : view === "teleoperating" && selectedRobot ? (
              <h1 className="font-mono text-4xl font-bold tracking-wider">
                <span className="text-muted-foreground uppercase">
                  teleoperate:
                </span>{" "}
                <span
                  className="text-primary text-glitch uppercase"
                  data-text={selectedRobot.robotId}
                >
                  {selectedRobot.robotId?.toUpperCase()}
                </span>
              </h1>
            ) : (
              <h1
                className="font-mono text-4xl font-bold text-primary tracking-wider text-glitch uppercase"
                data-text="dashboard"
              >
                DASHBOARD
              </h1>
            )}
            <div className="h-6 flex items-center">
              {view !== "dashboard" ? (
                <button
                  onClick={handleCloseSubView}
                  className="flex items-center gap-2 text-sm text-muted-foreground font-mono hover:text-primary transition-colors"
                >
                  <ChevronLeft className="w-4 h-4" />
                  <span className="uppercase">back to dashboard</span>
                </button>
              ) : (
                <p className="text-sm text-muted-foreground font-mono">{""} </p>
              )}
            </div>
          </div>
        </div>
      </div>
    );
  };

  return (
    <div className="flex flex-col min-h-screen font-sans bg-gray-200 dark:bg-background">
      <Header />
      <main className="flex-grow container mx-auto py-12 px-4 md:px-6">
        <PageHeader />
        {renderView()}
        <EditRobotDialog
          robot={editingRobot}
          isOpen={!!editingRobot}
          onOpenChange={(open) => !open && setEditingRobot(null)}
          onSave={handleUpdateRobot}
        />
      </main>
      <Footer />
      <Toaster />
    </div>
  );
}

export default App;