File size: 4,760 Bytes
c8cad77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { useEffect, useRef, useState } from "react";
import { Bot, Loader2, Square } from "lucide-react";
import { Button } from "@/components/ui/button";
import { useApi } from "@/contexts/ApiContext";
import { useToast } from "@/hooks/use-toast";
import { useRobots } from "@/hooks/useRobots";
import { apiRequest } from "@/lib/apiClient";

interface ReplayResponse {
  success: boolean;
  message: string;
}

interface ReplayStatus {
  replay_active: boolean;
  error: string | null;
}

interface ReplayButtonProps {
  repoId: string;
  episodeIndex: number;
  /** Called once the arm starts moving, so the footage can run alongside it. */
  onStart: () => void;
  /** Called once the arm is released, whether the replay ended, failed or was stopped. */
  onEnd: () => void;
}

/**
 * Plays the episode's recorded actions on the selected follower arm. Only
 * shown when that arm is ready to move.
 */
const ReplayButton: React.FC<ReplayButtonProps> = ({ repoId, episodeIndex, onStart, onEnd }) => {
  const { baseUrl, fetchWithHeaders } = useApi();
  const { selectedRecord: robot } = useRobots();
  const { toast } = useToast();
  const [phase, setPhase] = useState<"idle" | "starting" | "playing">("idle");
  // Paging to another episode while the arm connects must not drag the
  // footage back to the one being replayed.
  const episodeRef = useRef(episodeIndex);
  episodeRef.current = episodeIndex;

  // A replay keeps running when this button unmounts (another dataset, another
  // page), so pick it back up to keep it stoppable.
  useEffect(() => {
    apiRequest<ReplayStatus>(baseUrl, fetchWithHeaders, "/replay-status")
      .then((status) => {
        if (status.replay_active) setPhase("playing");
      })
      .catch(() => undefined);
  }, [baseUrl, fetchWithHeaders]);

  // Poll only while the arm moves, to notice when the episode ends or fails.
  useEffect(() => {
    if (phase !== "playing") return;
    const timer = setInterval(async () => {
      try {
        const status = await apiRequest<ReplayStatus>(baseUrl, fetchWithHeaders, "/replay-status");
        if (status.replay_active) return;
        setPhase("idle");
        onEnd();
        if (status.error) {
          toast({ title: "Replay failed", description: status.error, variant: "destructive" });
        }
      } catch {
        // Keep the Stop button: the next poll retries.
      }
    }, 500);
    return () => clearInterval(timer);
  }, [phase, baseUrl, fetchWithHeaders, toast, onEnd]);

  // Back to Play only once the status poll sees the arm released.
  const stop = async () => {
    try {
      const res = await apiRequest<ReplayResponse>(baseUrl, fetchWithHeaders, "/stop-replay", {
        method: "POST",
        action: "Stop",
      });
      if (!res.success) throw new Error(res.message);
    } catch (e) {
      toast({
        title: "Could not stop the robot",
        description: e instanceof Error ? e.message : String(e),
        variant: "destructive",
      });
    }
  };

  // A running replay stays stoppable even once the robot is no longer selected.
  if (phase === "playing") {
    return (
      <Button
        variant="outline"
        size="sm"
        onClick={stop}
        className="h-7 gap-1.5 border-red-900 bg-red-950/40 text-xs text-red-300 hover:bg-red-950 hover:text-red-200"
      >
        <Square className="h-3 w-3 fill-current" />
        Stop robot
      </Button>
    );
  }

  if (!robot?.is_clean) return null;

  const start = async () => {
    setPhase("starting");
    try {
      const res = await apiRequest<ReplayResponse>(baseUrl, fetchWithHeaders, "/start-replay", {
        method: "POST",
        body: {
          follower_port: robot.follower_port,
          follower_config: robot.follower_config,
          dataset_repo_id: repoId,
          episode_index: episodeIndex,
        },
        action: "Replay",
      });
      if (!res.success) throw new Error(res.message);
      setPhase("playing");
      if (episodeRef.current === episodeIndex) onStart();
    } catch (e) {
      setPhase("idle");
      toast({
        title: "Could not replay this episode",
        description: e instanceof Error ? e.message : String(e),
        variant: "destructive",
      });
    }
  };

  return (
    <Button
      variant="outline"
      size="sm"
      onClick={start}
      disabled={phase === "starting"}
      title={`Replay this episode on ${robot.name}`}
      className="h-7 gap-1.5 border-gray-800 bg-gray-950 text-xs text-gray-300 hover:bg-gray-900"
    >
      {phase === "starting" ? (
        <Loader2 className="h-3.5 w-3.5 animate-spin" />
      ) : (
        <Bot className="h-3.5 w-3.5" />
      )}
      Play on robot
    </Button>
  );
};

export default ReplayButton;