File size: 14,129 Bytes
dd87944
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import React, { useCallback, useEffect, useState } from "react";
import { http, getApiBase, getSessionToken } from "../lib/api";
import { parseAgentStatus } from "../lib/agentStatus";
import { EmoLogo } from "./EmoLogo";
import { Copy, Check, RefreshCw, Download, ShieldAlert, Apple, Box, Cpu, Monitor, Link2 } from "lucide-react";
import { toast } from "sonner";

const detectOS = () => {
  if (typeof navigator === "undefined") return "windows";
  const ua = navigator.userAgent || "";
  if (/Win/i.test(ua)) {
    const plat = navigator.userAgentData?.platform || navigator.platform || "";
    if (/arm|aarch/i.test(plat)) return "windows-arm";
    return "windows";
  }
  if (/Mac/i.test(ua)) {
    const plat = navigator.userAgentData?.platform || navigator.platform || "";
    return /arm|aarch/i.test(plat) ? "macos-arm" : "macos";
  }
  if (/Linux/i.test(ua)) {
    const plat = navigator.userAgentData?.platform || "";
    return /arm|aarch/i.test(plat) ? "linux-arm" : "linux";
  }
  return "windows";
};

const OS_OPTIONS = [
  { id: "windows", label: "Windows x64", filename: "Emo-Desktop.zip", icon: Box },
  { id: "windows-arm", label: "Windows ARM", filename: "Emo-Desktop.zip", icon: Box },
  { id: "macos", label: "macOS Intel", filename: "Emo-Desktop.zip", icon: Apple },
  { id: "macos-arm", label: "macOS Apple Silicon", filename: "Emo-Desktop.zip", icon: Apple },
  { id: "linux", label: "Linux x64", filename: "Emo-Desktop.zip", icon: Cpu },
  { id: "linux-arm", label: "Linux ARM64", filename: "Emo-Desktop.zip", icon: Cpu },
];

const DOWNLOAD_NAMES = Object.fromEntries(OS_OPTIONS.map((o) => [o.id, o.filename]));

export default function AgentSettingsPanel({ agentOnline, onRefreshStatus }) {
  const [token, setToken] = useState("");
  const [copied, setCopied] = useState("");
  const [os, setOs] = useState(detectOS());
  const [downloading, setDownloading] = useState(false);
  const [downloadingZip, setDownloadingZip] = useState(false);
  const [status, setStatus] = useState({
    connected: false,
    online: false,
    desktopOnline: false,
    linked: false,
    context: null,
  });

  const refreshLocal = useCallback(async () => {
    try {
      const r = await http.get("/agent/status");
      const parsed = parseAgentStatus(r.data);
      setStatus({
        connected: parsed.desktopOnline || parsed.desktopLinked,
        online: parsed.agentToolsOnline,
        desktopOnline: parsed.desktopOnline,
        linked: parsed.desktopLinked,
        context: r.data.context || null,
      });
    } catch {
      /* ignore */
    }
  }, []);

  useEffect(() => {
    http.get("/agent/token").then((r) => setToken(r.data.agent_token));
    refreshLocal();
    const id = setInterval(refreshLocal, 5000);
    return () => clearInterval(id);
  }, [refreshLocal]);

  const connected = status.desktopOnline || agentOnline;

  const copy = async (text, key) => {
    try {
      await navigator.clipboard.writeText(text);
      setCopied(key);
      setTimeout(() => setCopied(""), 1500);
    } catch {
      toast.error("Copie impossible");
    }
  };

  const rotate = async () => {
    if (!window.confirm("Régénérer le token ? L'ancien agent sera invalidé.")) return;
    const r = await http.post("/agent/token/rotate");
    setToken(r.data.agent_token);
    toast.success("Token régénéré");
  };

  const fetchAgentDownload = async (url, fallbackFilename) => {
    const headers = {};
    const session = getSessionToken();
    if (session) {
      headers.Authorization = `Bearer ${session}`;
      headers["X-Emo-Session"] = session;
    }
    const resp = await fetch(url, { credentials: "include", headers });
    if (!resp.ok) {
      let detail = `HTTP ${resp.status}`;
      try {
        const err = await resp.json();
        detail = err.detail || detail;
      } catch (_) {}
      throw new Error(typeof detail === "string" ? detail : "Téléchargement impossible");
    }
    const blob = await resp.blob();
    const buf = await blob.arrayBuffer();
    const bytes = new Uint8Array(buf);
    const isZipFile = bytes[0] === 0x50 && bytes[1] === 0x4b;
    const isZip =
      isZipFile ||
      resp.headers.get("content-type")?.includes("zip") ||
      resp.headers.get("content-disposition")?.includes(".zip");
    const cd = resp.headers.get("content-disposition") || "";
    const cdMatch = cd.match(/filename="?([^";]+)"?/i);
    const filename = cdMatch?.[1] || (isZip ? "Emo-Desktop.zip" : fallbackFilename);
    const outBlob = new Blob([buf], { type: isZip ? "application/zip" : blob.type });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(outBlob);
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    a.remove();
    URL.revokeObjectURL(a.href);
    return { isZip, isFallback: resp.headers.get("X-Emo-Fallback") === "python-zip" };
  };

  const downloadDesktopExe = async () => {
    setDownloading(true);
    try {
      const { isZip, isFallback } = await fetchAgentDownload(
        `${getApiBase()}/agent/desktop-exe/windows`,
        "Emo-Desktop.exe"
      );
      if (isZip || isFallback) {
        toast.success("Version Python (zip) — extrais et lance start.bat");
      } else {
        toast.success("Emo-Desktop.exe téléchargé — double-clic pour lancer");
      }
    } catch (e) {
      toast.error(e.message || "Téléchargement impossible");
    } finally {
      setDownloading(false);
    }
  };

  const downloadAgentZip = async () => {
    setDownloadingZip(true);
    try {
      const { isZip } = await fetchAgentDownload(
        `${getApiBase()}/agent/binary/${os}`,
        "Emo-Desktop.zip"
      );
      toast.success(
        isZip
          ? "Émo Desktop (Python) téléchargé — extrais et lance start.bat ou start.sh"
          : "Émo Desktop téléchargé"
      );
    } catch (e) {
      toast.error(e.message || "Téléchargement impossible");
    } finally {
      setDownloadingZip(false);
    }
  };

  const isWindows = os === "windows" || os === "windows-arm";

  const handleRefresh = () => {
    refreshLocal();
    onRefreshStatus?.();
  };

  const hostname = status.context?.hostname || status.context?.os || "";

  return (
    <div className="space-y-5 text-sm">
      <div
        className="rounded-2xl p-5 text-center space-y-3"
        style={{
          background: "var(--emo-surface-raised)",
          border: `1px solid ${connected ? "var(--emo-status-online)" : "var(--emo-border)"}`,
          boxShadow: connected ? "0 0 24px var(--emo-status-online-glow)" : "none",
        }}
      >
        <EmoLogo size="md" layout="stacked" subtitle="Desktop" online={connected} className="mx-auto" />
        <div className="flex items-center justify-center gap-2 pt-1">
          <div className={`w-2.5 h-2.5 rounded-full ${connected ? "emo-status-dot-online" : "emo-status-dot-offline"}`} />
          <span
            className="text-xs uppercase tracking-[0.2em] font-semibold"
            style={{ color: connected ? "var(--emo-status-online)" : "var(--emo-status-offline)" }}
          >
            {connected ? "Connecté" : status.linked ? "Desktop lié — en attente" : "Hors ligne"}
          </span>
          <button
            data-testid="refresh-agent-status"
            onClick={handleRefresh}
            className="ml-2 p-1 rounded em-hover"
            type="button"
          >
            <RefreshCw size={13} />
          </button>
        </div>
        {connected && hostname ? (
          <p className="text-[11px] text-muted-em font-code">{hostname}</p>
        ) : null}
        {!connected && (
          <p className="text-[11px] text-secondary-em leading-relaxed px-2">
            Lance <strong>Émo Desktop</strong> sur ce PC, clique <strong>link</strong>, connecte-toi sur le site et
            appuie sur <strong>Accepter</strong>.
          </p>
        )}
      </div>

      <div
        className="rounded-xl p-3 space-y-2"
        style={{ background: "var(--emo-bg-subtle)", border: "1px solid var(--emo-border)" }}
      >
        <div className="flex items-center gap-2 text-[10px] uppercase tracking-wider text-muted-em">
          <Monitor size={12} /> État
        </div>
        <div className="grid grid-cols-2 gap-2 text-[11px]">
          <StatusPill label="App desktop" ok={status.desktopOnline} />
          <StatusPill label="Agent outils" ok={status.online} />
          <StatusPill label="Compte lié" ok={status.linked} />
          <StatusPill label="Cloud" ok={!!getSessionToken()} />
        </div>
      </div>

      <div
        className="rounded-2xl p-4 space-y-2"
        style={{ background: "var(--emo-surface-raised)", border: "1px solid var(--emo-border)" }}
      >
        <div className="flex items-center gap-2 text-xs uppercase tracking-[0.18em] text-muted-em">
          <Link2 size={13} /> Connexion
        </div>
        <ol className="text-[11px] text-secondary-em space-y-1.5 list-decimal list-inside leading-relaxed">
          <li>
            {isWindows
              ? "Télécharge Emo-Desktop.exe et double-clic pour lancer"
              : "Télécharge et lance Émo Desktop (zip Python)"}
          </li>
          <li>Clique <strong>link</strong> — le site s&apos;ouvre</li>
          <li>Connecte-toi si besoin → <strong>Accepter</strong></li>
          <li>Le voyant passe au vert ici</li>
        </ol>
      </div>

      <div>
        <label className="text-xs uppercase tracking-[0.18em] text-muted-em mb-2 block">Plateforme</label>
        <div className="grid grid-cols-2 gap-2">
          {OS_OPTIONS.map((opt) => {
            const Icon = opt.icon;
            const active = os === opt.id;
            return (
              <button
                key={opt.id}
                type="button"
                data-testid={`os-${opt.id}-btn`}
                onClick={() => setOs(opt.id)}
                className="flex items-center gap-2 px-3 py-2 rounded-lg text-[12px] transition"
                style={{
                  background: active ? "var(--emo-accent-soft)" : "var(--emo-surface-raised)",
                  border: `1px solid ${active ? "var(--emo-accent-border)" : "var(--emo-border)"}`,
                  color: "var(--emo-text)",
                }}
              >
                <Icon size={12} style={{ color: active ? "var(--mode-color)" : "currentColor" }} />
                {opt.label}
              </button>
            );
          })}
        </div>
      </div>

      {isWindows ? (
        <>
          <button
            type="button"
            data-testid="download-desktop-exe-btn"
            onClick={downloadDesktopExe}
            disabled={downloading}
            className="w-full flex items-center justify-center gap-2 py-3.5 rounded-2xl font-medium text-sm transition-all hover:scale-[1.01] disabled:opacity-50"
            style={{
              background: "var(--mode-color)",
              color: "var(--emo-on-mode)",
              boxShadow: "0 0 24px var(--mode-glow)",
            }}
          >
            <Download size={15} />{" "}
            {downloading ? "Téléchargement…" : "Télécharger Emo-Desktop.exe (Windows)"}
          </button>
          <button
            type="button"
            data-testid="download-agent-btn"
            onClick={downloadAgentZip}
            disabled={downloadingZip}
            className="w-full flex items-center justify-center gap-2 py-2.5 rounded-xl text-[12px] transition disabled:opacity-50 em-hover"
            style={{
              background: "var(--emo-surface-raised)",
              border: "1px solid var(--emo-border)",
              color: "var(--emo-text-secondary)",
            }}
          >
            <Download size={13} />{" "}
            {downloadingZip ? "Téléchargement…" : "Version Python (zip)"}
          </button>
        </>
      ) : (
        <button
          type="button"
          data-testid="download-agent-btn"
          onClick={downloadAgentZip}
          disabled={downloadingZip}
          className="w-full flex items-center justify-center gap-2 py-3.5 rounded-2xl font-medium text-sm transition-all hover:scale-[1.01] disabled:opacity-50"
          style={{
            background: "var(--mode-color)",
            color: "var(--emo-on-mode)",
            boxShadow: "0 0 24px var(--mode-glow)",
          }}
        >
          <Download size={15} />{" "}
          {downloadingZip ? "Téléchargement…" : "Télécharger Émo Desktop"}
        </button>
      )}

      <details className="text-xs">
        <summary className="cursor-pointer text-muted-em hover:text-[var(--emo-text)]">Token agent (avancé)</summary>
        <div className="mt-3 space-y-3">
          <div className="flex items-center gap-2">
            <code
              data-testid="agent-token-display"
              className="flex-1 font-code text-[11px] px-3 py-2 rounded-lg truncate em-input"
              style={{ color: "var(--emo-code-text)" }}
            >
              {token || "…"}
            </code>
            <button type="button" data-testid="copy-token-btn" onClick={() => copy(token, "token")} className="p-2 rounded-lg glass-card">
              {copied === "token" ? <Check size={14} /> : <Copy size={14} />}
            </button>
          </div>
          <button
            type="button"
            onClick={rotate}
            data-testid="rotate-token-btn"
            className="text-[11px] text-muted-em hover:text-[var(--emo-error-text)] flex items-center gap-1"
          >
            <ShieldAlert size={11} /> Régénérer (invalide l&apos;ancien agent)
          </button>
        </div>
      </details>
    </div>
  );
}

function StatusPill({ label, ok }) {
  return (
    <div
      className="flex items-center gap-1.5 px-2 py-1.5 rounded-lg"
      style={{ background: "var(--emo-surface)", border: "1px solid var(--emo-border)" }}
    >
      <div className={`w-1.5 h-1.5 rounded-full shrink-0 ${ok ? "emo-status-dot-online" : "emo-status-dot-offline"}`} />
      <span className="text-secondary-em truncate">{label}</span>
    </div>
  );
}