import { MACHINE_METRICS_HISTORY_LIMIT, MACHINE_METRICS_INTERVAL_MS, type KeepAwakeMode, type MachineKeepAwake, type MachineMetrics, type MachinePower, } from "@linkshell/wire"; import { dateLocaleTag } from "@linkshell/client-core"; import { useEffect, useState } from "react"; import { Alert, Pressable, StyleSheet, useColorScheme, View } from "react-native"; import Svg, { Circle, G, Line, Path } from "react-native-svg"; import { useConnection } from "@/lib/client"; import { haptics } from "@/lib/haptics"; import { useLocale } from "@/lib/locale"; import { metricPercent, useMachineMetrics } from "@/lib/machine-metrics"; import { colors, palette } from "@/theme/colors"; import { radius, type } from "@/theme/type"; import { Button } from "./button"; import { Text } from "./fixed-text"; import { Icon } from "./icon"; import { PressableFeedback } from "./pressable-feedback"; const percent = (value: number | null) => (value == null ? "—" : `${Math.round(value)}%`); export function isHostLowBattery(power?: MachinePower | null): boolean { if (!power) return false; return Boolean(power.onBattery && !power.charging && power.percent !== null && power.percent < 20); } function History({ history }: { history: MachineMetrics[] }) { const tint = palette[useColorScheme() === "dark" ? "dark" : "light"]; const latest = history.at(-1)?.sampledAt; const samples = Array(MACHINE_METRICS_HISTORY_LIMIT).fill(undefined); if (latest !== undefined) { for (const sample of history) { const index = MACHINE_METRICS_HISTORY_LIMIT - 1 - Math.round((latest - sample.sampledAt) / MACHINE_METRICS_INTERVAL_MS); if (index >= 0 && index < samples.length) samples[index] = sample; } } const series = (kind: "cpu" | "memory") => { const paths: { d: string; x: number; y: number }[] = []; let d = ""; let x = 0; let y = 0; for (let column = 0; column < samples.length; column++) { const sample = samples[column]; const value = sample ? (kind === "cpu" ? sample.cpu.usage : metricPercent(sample.memory.usedBytes, sample.memory.totalBytes)) : null; if (value === null) { if (d) paths.push({ d, x, y }); d = ""; continue; } x = 3 + column * 10; y = 61 - value * 0.58; d += `${d ? " L" : "M"}${x} ${y}`; } if (d) paths.push({ d, x, y }); const color = kind === "cpu" ? tint.accent : tint.secondaryLabel; return paths.map((path, index) => ( )); }; return ( {[3, 32, 61].map((y) => ( ))} {series("cpu")} {series("memory")} ); } function ResourceRow({ label, value, detail, warn, }: { label: string; value: string; detail?: string; warn?: boolean; }) { return ( {label} {detail ? ( {detail} ) : null} {value} ); } export function ComputerMetrics({ data }: { data: ReturnType }) { const { link } = useConnection(); const { locale, t, pick } = useLocale(); const { metrics, history, online, locked, unavailable, error, retry } = data; const [expanded, setExpanded] = useState(false); const [keepAwakeExpanded, setKeepAwakeExpanded] = useState(false); const [keepAwakeOverride, setKeepAwakeOverride] = useState(null); const [switchingKeepAwake, setSwitchingKeepAwake] = useState(false); const gib = (bytes: number) => `${(bytes / 1024 ** 3).toLocaleString(dateLocaleTag(locale), { maximumFractionDigits: 1 })} GB`; useEffect(() => { if (metrics?.keepAwake) setKeepAwakeOverride(metrics.keepAwake); }, [metrics?.keepAwake]); useEffect(() => { if (!online || metrics?.keepAwake) return; let cancelled = false; link .call("machine.keepAwake", {}, 10_000) .then((res) => { if (!cancelled) setKeepAwakeOverride(res); }) .catch(() => {}); return () => { cancelled = true; }; }, [link, online, metrics?.keepAwake]); const keepAwake = keepAwakeOverride ?? metrics?.keepAwake; const power = metrics?.power; const lowBattery = isHostLowBattery(power); const setKeepAwakeMode = async (mode: KeepAwakeMode) => { if (switchingKeepAwake || !online) return; setSwitchingKeepAwake(true); try { const updated = await link.call("machine.keepAwake", { mode }, 10_000); setKeepAwakeOverride(updated); setKeepAwakeExpanded(false); haptics.selection(); } catch (reason) { haptics.error(); Alert.alert( t("power.keepAwake"), reason instanceof Error ? reason.message : String(reason), ); } finally { setSwitchingKeepAwake(false); } }; const powerValue = (() => { if (!power) return null; if (power.percent === null) return t("power.pluggedIn"); const pct = Math.round(power.percent); if (power.charging) return t("power.charging", { percent: pct }); if (power.onBattery) return t("power.onBattery", { percent: pct }); return `${t("power.pluggedIn")} · ${pct}%`; })(); const status = locked ? pick({ zh: "解锁后查看资源使用", en: "Unlock to view system metrics", ja: "ロック解除後にリソースを表示" }) : !online ? pick({ zh: "连接电脑后查看资源使用", en: "Connect to view system metrics", ja: "PC 接続後にリソースを表示" }) : unavailable ? pick({ zh: "更新电脑端后可查看资源使用", en: "Update LinkShell Host to view metrics", ja: "PC 側の更新でリソースを表示可能" }) : error ? pick({ zh: "资源读取失败", en: "Failed to read metrics", ja: "リソースの取得に失敗しました" }) : t("common.loading"); const disk = metrics?.disk; const keepAwakeOptions: { mode: KeepAwakeMode; label: string; desc: string }[] = [ { mode: "smart", label: t("power.keepAwakeSmart"), desc: t("power.keepAwakeSmartDesc") }, { mode: "always", label: t("power.keepAwakeAlways"), desc: t("power.keepAwakeAlwaysDesc") }, { mode: "off", label: t("power.keepAwakeOff"), desc: t("power.keepAwakeOffDesc") }, ]; const currentKeepAwakeLabel = keepAwake ? (keepAwakeOptions.find((opt) => opt.mode === keepAwake.mode)?.label ?? t("power.keepAwakeSmart")) : ""; return ( {lowBattery && power?.percent !== null && power?.percent !== undefined ? ( {t("power.lowBatteryWarning", { percent: Math.round(power.percent) })} ) : null} {pick({ zh: "资源与电源", en: "System & Power", ja: "システムと電源" })} {metrics ? ( <> {powerValue ? ( ) : null} {online && keepAwake ? ( { haptics.selection(); setKeepAwakeExpanded((value) => !value); }} accessibilityRole="button" accessibilityState={{ expanded: keepAwakeExpanded }} accessibilityLabel={t("power.keepAwake")} style={{ marginHorizontal: -16, paddingHorizontal: 16, minHeight: 42, flexDirection: "row", alignItems: "center", gap: 10 }} > {t("power.keepAwake")} {keepAwake.active ? : null} {currentKeepAwakeLabel} {keepAwakeExpanded ? ( {keepAwakeOptions.map((opt) => { const selected = keepAwake.mode === opt.mode; return ( void setKeepAwakeMode(opt.mode)} accessibilityRole="radio" accessibilityState={{ selected }} style={({ pressed }) => ({ flexDirection: "row", alignItems: "center", gap: 10, paddingVertical: 8, paddingLeft: 8, borderTopWidth: StyleSheet.hairlineWidth, borderTopColor: colors.separator, opacity: pressed ? 0.6 : 1, })} > {opt.label} {opt.desc} {selected ? : null} ); })} ) : null} ) : null} setExpanded((value) => !value)} accessibilityRole="button" accessibilityState={{ expanded }} accessibilityLabel={pick({ zh: "使用趋势与详情", en: "Trends & Details", ja: "推移と詳細" })} style={{ marginHorizontal: -16, paddingHorizontal: 16, minHeight: 42, flexDirection: "row", alignItems: "center", gap: 8 }} > {pick({ zh: "使用趋势与详情", en: "Trends & Details", ja: "推移と詳細" })} {expanded ? ( CPU {pick({ zh: "内存", en: "Memory", ja: "メモリ" })} {pick({ zh: "最近 2 分钟", en: "2 min ago", ja: "2分前" })} {pick({ zh: "现在", en: "Now", ja: "現在" })} {metrics.cpu.model} · {metrics.cpu.cores} cores {disk ? ( {disk.path} · {percent(metricPercent(disk.usedBytes, disk.totalBytes))} ) : null} ) : null} ) : ( {status} {error && !unavailable ? ( <> {error}