import { useEffect, useState } from "react" import { createRoot } from "react-dom/client" import { invoke } from "@tauri-apps/api/core" import { Store } from "@tauri-apps/plugin-store" import { ExternalLink, Eye, EyeOff, GalleryVerticalEnd, RefreshCw } from "lucide-react" import { Tabs, TabsContent, TabsList, TabsTrigger } from "./components/ui/tabs" import { cn } from "./lib/utils" type MachineOs = { name: string version?: string | null architecture?: string | null } type MachineMetrics = { collectedAt: string cpuLogicalCores: number cpuPhysicalCores?: number | null cpuUsagePercent: number memoryTotalBytes: number memoryUsedBytes: number memoryUsedPercent: number uptimeSeconds: number } type MachineInventory = { cpuBrand?: string | null hostIdentifier?: string | null } type MachineProfile = { hostname: string os: MachineOs macAddresses: string[] serialNumbers: string[] inventory: MachineInventory metrics: MachineMetrics } type MachineRegisterResponse = { machineId: string tenantId?: string | null companyId?: string | null companySlug?: string | null machineToken: string machineEmail?: string | null expiresAt?: number | null } type AgentConfig = { machineId: string tenantId?: string | null companySlug?: string | null machineEmail?: string | null apiBaseUrl: string appUrl: string createdAt: number lastSyncedAt?: number | null expiresAt?: number | null heartbeatIntervalSec?: number | null } declare global { interface ImportMetaEnv { readonly VITE_APP_URL?: string readonly VITE_API_BASE_URL?: string } interface ImportMeta { readonly env: ImportMetaEnv } } const STORE_FILENAME = "machine-agent.json" const DEFAULT_APP_URL = import.meta.env.MODE === "production" ? "https://tickets.esdrasrenan.com.br" : "http://localhost:3000" function normalizeUrl(value?: string | null, fallback = DEFAULT_APP_URL) { const trimmed = (value ?? fallback).trim() if (!trimmed.startsWith("http")) return fallback return trimmed.replace(/\/+$/, "") } const appUrl = normalizeUrl(import.meta.env.VITE_APP_URL, DEFAULT_APP_URL) const apiBaseUrl = normalizeUrl(import.meta.env.VITE_API_BASE_URL, appUrl) async function loadStore(): Promise { return await Store.load(STORE_FILENAME) } async function readToken(store: Store): Promise { return (await store.get("token")) ?? null } async function writeToken(store: Store, token: string): Promise { await store.set("token", token) await store.save() } async function readConfig(store: Store): Promise { return (await store.get("config")) ?? null } async function writeConfig(store: Store, cfg: AgentConfig): Promise { await store.set("config", cfg) await store.save() } function bytes(n?: number) { if (!n || !Number.isFinite(n)) return "—" const u = ["B","KB","MB","GB","TB"] let v = n; let i = 0 while (v >= 1024 && i < u.length - 1) { v/=1024; i++ } return `${v.toFixed(v>=10||i===0?0:1)} ${u[i]}` } function pct(p?: number) { return !p && p !== 0 ? "—" : `${p.toFixed(0)}%` } function App() { const [store, setStore] = useState(null) const [token, setToken] = useState(null) const [config, setConfig] = useState(null) const [profile, setProfile] = useState(null) const [error, setError] = useState(null) const [busy, setBusy] = useState(false) const [status, setStatus] = useState(null) const [showSecret, setShowSecret] = useState(false) const [provisioningSecret, setProvisioningSecret] = useState("") const [tenantId, setTenantId] = useState("") const [company, setCompany] = useState("") const [collabEmail, setCollabEmail] = useState("") const [collabName, setCollabName] = useState("") const [updating, setUpdating] = useState(false) useEffect(() => { (async () => { try { const s = await loadStore() setStore(s) const t = await readToken(s) setToken(t) const cfg = await readConfig(s) setConfig(cfg) if (!t) { const p = await invoke("collect_machine_profile") setProfile(p) } setStatus(t ? "online" : null) } catch (err) { setError("Falha ao carregar estado do agente.") } })() }, []) async function register() { if (!profile) return if (!provisioningSecret.trim()) { setError("Informe o código de provisionamento."); return } setBusy(true); setError(null) try { const payload = { provisioningSecret: provisioningSecret.trim(), tenantId: tenantId.trim() || undefined, companySlug: company.trim() || undefined, hostname: profile.hostname, os: profile.os, macAddresses: profile.macAddresses, serialNumbers: profile.serialNumbers, metadata: { inventory: profile.inventory, metrics: profile.metrics, collaborator: collabEmail ? { email: collabEmail.trim(), name: collabName.trim() || undefined } : undefined }, registeredBy: "desktop-agent", } const res = await fetch(`${apiBaseUrl}/api/machines/register`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload) }) if (!res.ok) { const text = await res.text() throw new Error(`Falha no registro (${res.status}): ${text.slice(0,300)}`) } const data = (await res.json()) as MachineRegisterResponse if (!store) throw new Error("Store ausente") await writeToken(store, data.machineToken) const cfg: AgentConfig = { machineId: data.machineId, tenantId: data.tenantId ?? null, companySlug: data.companySlug ?? null, machineEmail: data.machineEmail ?? null, apiBaseUrl, appUrl, createdAt: Date.now(), lastSyncedAt: Date.now(), expiresAt: data.expiresAt ?? null, } await writeConfig(store, cfg) setConfig(cfg); setToken(data.machineToken) await invoke("start_machine_agent", { baseUrl: apiBaseUrl, token: data.machineToken, status: "online", intervalSeconds: 300 }) setStatus("online") } catch (err) { setError(err instanceof Error ? err.message : String(err)) } finally { setBusy(false) } } async function openSystem() { if (!token || !config) return const url = `${config.appUrl}/machines/handshake?token=${encodeURIComponent(token)}` try { // open in default browser; fallback to in-webview const { openUrl } = await import("@tauri-apps/plugin-opener") await openUrl(url) } catch { window.location.replace(url) } } async function reprovision() { if (!store) return await store.delete("token"); await store.delete("config"); await store.save() setToken(null); setConfig(null); setStatus(null) const p = await invoke("collect_machine_profile") setProfile(p) } async function sendInventoryNow() { if (!token || !profile) return setBusy(true); setError(null) try { const payload = { machineToken: token, hostname: profile.hostname, os: profile.os, metrics: profile.metrics, inventory: profile.inventory, } const res = await fetch(`${apiBaseUrl}/api/machines/inventory`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), }) if (!res.ok) { const text = await res.text() throw new Error(`Falha ao enviar inventário (${res.status}): ${text.slice(0, 200)}`) } } catch (err) { setError(err instanceof Error ? err.message : String(err)) } finally { setBusy(false) } } async function checkForUpdates() { try { setUpdating(true) const { check } = await import("@tauri-apps/plugin-updater") const update = await check() if (update && (update as any).available) { // download and install then relaunch await (update as any).downloadAndInstall() const { relaunch } = await import("@tauri-apps/plugin-process") await relaunch() } else { alert("Nenhuma atualização disponível.") } } catch (error) { console.error("Falha ao verificar atualizações", error) alert("Falha ao verificar atualizações.") } finally { setUpdating(false) } } return (
Sistema de chamados

Agente Desktop

{error ?

{error}

: null} {!token ? (

Informe os dados para registrar esta máquina.

setProvisioningSecret(e.target.value)} />
setCompany(e.target.value)} />
setCollabEmail(e.target.value)} />
setCollabName(e.target.value)} />
setTenantId(e.target.value)} />
{profile ? (
Hostname
{profile.hostname}
Sistema
{profile.os.name}
CPU
{pct(profile.metrics.cpuUsagePercent)}
Memória
{bytes(profile.metrics.memoryUsedBytes)} / {bytes(profile.metrics.memoryTotalBytes)}
) : null}
) : (
Resumo Inventário Diagnóstico Configurações
CPU
{profile ? pct(profile.metrics.cpuUsagePercent) : "—"}
Memória
{profile ? `${bytes(profile.metrics.memoryUsedBytes)} / ${bytes(profile.metrics.memoryTotalBytes)}` : "—"}

Inventário básico coletado localmente. Envie para sincronizar com o servidor.

Hostname
{profile?.hostname ?? "—"}
Sistema
{profile?.os?.name ?? "—"} {profile?.os?.version ?? ""}

Token armazenado: {token?.slice(0, 6)}…{token?.slice(-6)}

Base URL: {apiBaseUrl}

setCollabEmail(e.target.value)} />
setCollabName(e.target.value)} />
)}
Logotipo Rever Tecnologia
) } function StatusBadge({ status }: { status: string | null }) { const s = (status ?? "").toLowerCase() const label = s === "online" ? "Online" : s === "offline" ? "Offline" : s === "maintenance" ? "Manutenção" : "Sem status" const dot = s === "online" ? "bg-emerald-500" : s === "offline" ? "bg-rose-500" : s === "maintenance" ? "bg-amber-500" : "bg-slate-400" const ring = s === "online" ? "bg-emerald-400/30" : s === "offline" ? "bg-rose-400/30" : s === "maintenance" ? "bg-amber-400/30" : "bg-slate-300/30" const isOnline = s === "online" return ( {isOnline ? : null} {label} ) } const root = document.getElementById("root") || (() => { const el = document.createElement("div"); el.id = "root"; document.body.appendChild(el); return el })() createRoot(root).render()