"use client"; import { useState, useEffect, useRef } from "react"; import PropTypes from "prop-types"; import { Modal, Button } from "@/shared/components"; import { translate } from "@/i18n/runtime"; /** * Xiaomi MiMo Desktop Plan auth modal. * * Desktop Plan = Xiaomi account weekly quota (mimo-v2.6 family). Two ways in: * 1. Import local MiMo Desktop credentials (~/.local/share/mimocode/auth.json) * 2. Server-side login โ no Desktop needed; picks a MiMo account cluster * (cn / sgp / ams / ru / in). The account session (passToken) is captured * server-side and stored per connection. * * Token Plan (cloud sk- API key) uses the standard "API Key" entry point. */ const CLUSTERS = [ { id: "cn", flag: "๐จ๐ณ", name: "China (Mainland)", host: "mimo-server-cn" }, { id: "sgp", flag: "๐ธ๐ฌ", name: "Singapore", host: "mimo-server-sgp" }, { id: "ams", flag: "๐ช๐บ", name: "Europe ยท Amsterdam", host: "mimo-server-ams" }, { id: "ru", flag: "๐ท๐บ", name: "Russia", host: "mimo-server-ru" }, { id: "in", flag: "๐ฎ๐ณ", name: "India", host: "mimo-server-in" }, ]; export default function XiaomiMimoAuthModal({ isOpen, onSuccess, onClose }) { const [phase, setPhase] = useState("detecting"); // detecting | found | not-found | importing const [detectResult, setDetectResult] = useState(null); const [existingConnection, setExistingConnection] = useState(null); const [error, setError] = useState(null); // Server-side session login const [showClusterModal, setShowClusterModal] = useState(false); const [sessBusy, setSessBusy] = useState(false); const [sessPolling, setSessPolling] = useState(false); const [sessError, setSessError] = useState(null); const [sessPageUrl, setSessPageUrl] = useState(null); const [sessRegion, setSessRegion] = useState("cn"); const sessTimerRef = useRef(null); const stopSessionPoll = () => { if (sessTimerRef.current) { clearInterval(sessTimerRef.current); sessTimerRef.current = null; } setSessPolling(false); }; useEffect(() => () => stopSessionPoll(), []); // Detect local credentials when the modal opens (non-blocking: never trap the spinner) useEffect(() => { if (!isOpen) return; setPhase("detecting"); setError(null); setDetectResult(null); setExistingConnection(null); setShowClusterModal(false); setSessError(null); const runDetect = async () => { try { const res = await fetch("/api/oauth/xiaomi-mimo/auto-import", { signal: AbortSignal.timeout(5000), }); const data = await res.json(); if (data.found && data.apiKey) { setDetectResult(data); setPhase("found"); // Non-blocking: flag an already-imported account fetch("/api/providers", { signal: AbortSignal.timeout(3000) }) .then((r) => r.json()) .then((provData) => { const foundConn = (provData.connections || []).find( (c) => c.provider === "xiaomi-mimo" && data.uid && (c.email === `${data.uid}@xiaomi` || c.providerSpecificData?.uid === data.uid || c.providerSpecificData?.mimoUserId === data.uid), ); if (foundConn) setExistingConnection(foundConn); }) .catch(() => {}); } else { setPhase("not-found"); } } catch { setPhase("not-found"); } }; runDetect(); }, [isOpen]); // Import the auto-detected local desktop credentials const handleImportLocal = async () => { if (!detectResult?.apiKey) return; setPhase("importing"); setError(null); try { const res = await fetch("/api/oauth/xiaomi-mimo/api-key", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ apiKey: detectResult.apiKey, uid: detectResult.uid, baseUrl: detectResult.baseUrl, mimoPassToken: detectResult.mimoPassToken || null, mimoUserId: detectResult.mimoUserId || null, mimoCUserId: detectResult.mimoCUserId || null, }), }); const data = await res.json(); if (!res.ok || !data.success) throw new Error(data.error || "Import failed"); onSuccess?.(data.connection); onClose(); } catch (err) { setPhase("found"); setError(err.message); } }; // Server-side login (account.xiaomi.com) for the chosen cluster const startSessionLogin = async (region) => { setSessBusy(true); setSessError(null); setShowClusterModal(false); setSessRegion(region); try { const res = await fetch("/api/oauth/xiaomi-mimo/login/start", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ region }), }); const data = await res.json(); if (!res.ok || !data.pageUrl) throw new Error(data.error || "Failed to start login"); setSessPageUrl(data.pageUrl); window.open(data.pageUrl, "mimo-session-login", "width=500,height=760"); setSessPolling(true); const startedAt = Date.now(); sessTimerRef.current = setInterval(async () => { if (Date.now() - startedAt > 14 * 60 * 1000) { stopSessionPoll(); setSessError("Login timed out. Please retry."); return; } try { const sres = await fetch(`/api/oauth/xiaomi-mimo/login/status?state=${data.state}`); const sd = await sres.json(); if (sd.status === "pending") return; stopSessionPoll(); if (sd.status !== "done") { setSessError(sd.error || "Login session expired โ please retry."); return; } const save = await fetch("/api/oauth/xiaomi-mimo/api-key", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ apiKey: "", uid: sd.userId || null, mimoPassToken: sd.passToken, mimoUserId: sd.userId || null, mimoCUserId: sd.cUserId || null, region: sd.region || sessRegion, }), }); const saved = await save.json(); if (!save.ok || !saved.success) throw new Error(saved.error || "Failed to save credentials"); onSuccess?.(saved.connection); onClose(); } catch (err) { stopSessionPoll(); setSessError(err.message); } }, 2500); } catch (err) { setSessError(err.message); } finally { setSessBusy(false); } }; // The server-login card, shown in both the found and not-found states const renderServerLogin = () => (
{translate(sessError)}
}Reading local MiMo Desktop credentials...
Connecting...
This account is already connected (no need to import again)
UID: {detectResult.uid || "โ"} ยท Status: {existingConnection.testStatus === "active" ? "Active" : "Untested"}
Xiaomi MiMo Desktop credentials found!
UID: {detectResult.uid || "โ"} ยท Source: {detectResult.source?.split(/[\\/]/).pop()}
{translate(error)}
No local Desktop credentials found
You can still sign in via browser โ no Desktop client needed.
Choose the region cluster of your Xiaomi account: