Skip to content

LordOS — a free, fast and secure GNU/Linux distribution based on Debian, with its own desktop environment: display server and Wayland compositor in C, a React UI engine on QuickJS, and private native apps.

Monitor: per-destination switches, history zoom, lighter map dots

Federico Pereira63fe86509fec
diff --git a/apps/monitor/History.jsx b/apps/monitor/History.jsx
new file mode 100644
index 0000000..f5a5b02
--- /dev/null
+++ b/apps/monitor/History.jsx
@@ -0,0 +1,124 @@
+// History.jsx — the Network tab's traffic history (0.8.2, docs/MONITOR.md "Traffic history"): the
+// same mirrored chart as the live minute, over 1 hour, 24 hours, 7 or 30 days, read from the file
+// lord-server keeps (monitor.history). Step back and forward one window at a time; "Now" comes back
+// to the present. The file holds bytes per minute (7 days) and per hour (30 days), for the machine
+// and for each app; never an address or a name.
+import { View, Text, Segmented, useTheme, useLocale, monitor, formatDate, formatTime } from '@lordos/sdk';
+import { useEffect, useState } from 'react';
+import { TrafficChart } from './TrafficChart.jsx';
+
+// window and bucket of each zoom: about 60–170 bars, like the live minute
+export const RANGES = {
+ '1h': { span: 3600, step: 60 },
+ '24h': { span: 86400, step: 900 },
+ '7d': { span: 7 * 86400, step: 3600 },
+ '30d': { span: 30 * 86400, step: 6 * 3600 },
+};
+
+// end: Unix seconds of the window's end, or null for "now". The window is aligned to its buckets.
+export function windowOf(range, end) {
+ const r = RANGES[range];
+ if (!r) return null;
+ const now = Math.floor(Date.now() / 1000);
+ const e = Math.ceil((end ?? now) / r.step) * r.step;
+ return { from: e - r.span, step: r.step, n: Math.round(r.span / r.step), end: e, live: end == null || e >= Math.ceil(now / r.step) * r.step };
+}
+
+// The history for one window (app: an app id, or null for the machine). Re-read every minute while
+// the window reaches the present; an older window is read once.
+export function useHistory(range, end, app = null) {
+ const [data, setData] = useState(null);
+ const w = windowOf(range, end);
+ const key = w ? `${range}|${w.from}|${app}` : '';
+ useEffect(() => {
+ if (!w) { setData(null); return undefined; }
+ const read = () => {
+ const x = windowOf(range, end);
+ setData(x ? { w: x, h: monitor.history({ from: x.from, step: x.step, n: x.n, app }) } : null);
+ };
+ read();
+ if (!w.live) return undefined;
+ const timer = setInterval(read, 60000);
+ return () => clearInterval(timer);
+ }, [key]);
+ return data;
+}
+
+// [rx, tx] in bytes per second per bucket (the chart's unit) and the window's totals in bytes.
+export function historyBuckets(d) {
+ if (!d?.h) return { buckets: [], totals: [0, 0] };
+ const { rx, tx } = d.h, step = d.w.step;
+ let r = 0, t = 0;
+ const buckets = rx.map((v, i) => { r += v; t += tx[i]; return [v / step, tx[i] / step]; });
+ return { buckets, totals: [r, t] };
+}
+
+const when = (s, withDate) => {
+ const d = new Date(s * 1000);
+ return withDate ? `${formatDate(d, 'short')} ${formatTime(d)}` : formatTime(d);
+};
+
+// "Oct 18 14:00" … "15:00" under the chart, and the window as one line for the header.
+export function rangeLabels(d, range) {
+ if (!d?.w) return ['', ''];
+ const longRange = range === '7d' || range === '30d';
+ return [when(d.w.from, true), d.w.live ? '' : when(d.w.end, longRange || new Date(d.w.from * 1000).getDate() !== new Date(d.w.end * 1000).getDate())];
+}
+
+function Arrow({ glyph, on, onClick }) {
+ const t = useTheme();
+ return (
+ <View onClick={on ? onClick : undefined} style={{ width: 22, height: 18, borderRadius: 5, justifyContent: 'center', alignItems: 'center',
+ backgroundColor: t.control, opacity: on ? 1 : 0.4 }}>
+ <Text style={{ fontSize: 11, fontWeight: 700, color: t.text }}>{glyph}</Text>
+ </View>
+ );
+}
+
+// The zoom (live minute, 1 h, 24 h, 7 d, 30 d) and, on a history zoom, ‹ › and "Now".
+export function HistoryControls({ range, setRange, end, setEnd, oldest }) {
+ const t = useTheme();
+ const { t: tr } = useLocale();
+ const w = windowOf(range, end);
+ const canBack = !!w && (!oldest || w.from > oldest);
+ const step = (dir) => {
+ const r = RANGES[range];
+ const e = (w?.end ?? Math.floor(Date.now() / 1000)) + dir * r.span;
+ setEnd(e >= Math.floor(Date.now() / 1000) ? null : e);
+ };
+ return (
+ <View style={{ gap: 4 }}>
+ <Segmented small fill value={range} onChange={(v) => { setRange(v); setEnd(null); }}
+ options={[['live', tr('monitor.hist.live')], ['1h', tr('monitor.hist.1h')], ['24h', tr('monitor.hist.24h')], ['7d', tr('monitor.hist.7d')], ['30d', tr('monitor.hist.30d')]]} />
+ {w ? (
+ <View style={{ flexDirection: 'row', alignItems: 'center', gap: 6, direction: 'ltr' }}>
+ <Arrow glyph="‹" on={canBack} onClick={() => step(-1)} />
+ <Arrow glyph="›" on={!w.live} onClick={() => step(1)} />
+ <View style={{ flex: 1 }} />
+ <View onClick={w.live ? undefined : () => setEnd(null)} style={{ paddingHorizontal: 8, height: 18, borderRadius: 5, justifyContent: 'center',
+ backgroundColor: w.live ? 'transparent' : t.accent }}>
+ <Text style={{ fontSize: 10, fontWeight: 600, color: w.live ? t.textDim : '#fff' }}>{tr('monitor.now')}</Text>
+ </View>
+ </View>
+ ) : null}
+ </View>
+ );
+}
+
+// The chart for a history window (data from useHistory: the machine's or one app's).
+export function HistoryChart({ data: d, range, height = 52, compact }) {
+ const t = useTheme();
+ const { t: tr } = useLocale();
+ const { buckets, totals } = historyBuckets(d);
+ const [left, right] = rangeLabels(d, range);
+ if (d && !d.h) return <Text style={{ fontSize: 11, color: t.textDim, lineHeight: 1.35 }}>{tr('monitor.hist.unavailable')}</Text>;
+ const empty = d?.h && !d.h.enabled && !d.h.res;
+ return (
+ <View style={{ gap: 4 }}>
+ <TrafficChart buckets={buckets.length ? buckets : [[0, 0], [0, 0]]} shift={1} height={height} totals={compact ? null : totals}
+ caption={tr(`monitor.hist.per.${range}`)} axis={compact ? null : [left, right || tr('monitor.now')]} compact={compact} />
+ {empty ? <Text style={{ fontSize: 10, color: t.textDim, lineHeight: 1.35 }}>{tr('monitor.hist.off')}</Text> : null}
+ {!empty && d?.h && !d.h.res ? <Text style={{ fontSize: 10, color: t.textDim, lineHeight: 1.35 }}>{tr('monitor.hist.none')}</Text> : null}
+ </View>
+ );
+}
diff --git a/apps/monitor/MapView.jsx b/apps/monitor/MapView.jsx
index f4c98c0..1af7150 100644
--- a/apps/monitor/MapView.jsx
+++ b/apps/monitor/MapView.jsx
@@ -8,9 +8,9 @@
// así que mover y acercar no esperan al dibujo. Las etiquetas son texto del motor: siempre nítidas.
import { View, Text, Image, useTheme, useLocale, addListener, formatNumber, tOptional, useAppWindow, useStore, windows, settings } from '@lordos/sdk';
import { useEffect, useMemo, useRef, useState } from 'react';
-import { parseColor } from './draw.js';
+import { parseColor, canvas, dot } from './draw.js';
import { COUNTRY_LL } from './countries.js';
-import { C } from './index.jsx';
+import { C, useCardStyle } from './index.jsx';
// ---- traffic direction on the arcs ----
// Dots travel along each arc while bytes move: sent (orange) from "This computer" to the place,
@@ -18,14 +18,23 @@ import { C } from './index.jsx';
// drawn dimmed (map.c). The dots are engine views moved with lord.setStyle (no React render per
// frame) at FLOW_FPS with the window in front and FLOW_FPS_BEHIND behind it, only for arcs on
// screen and at most FLOW_ARCS of them; the timer stops with the window minimized, while the map
-// moves and when nothing moves. Each frame repaints the box around the dots (about 0.35 % of a
-// 1.8 GHz core per frame per second with CPU compositing, docs/MONITOR.md). With Reduce motion each
-// busy arc gets two still arrows instead.
+// moves and when nothing moves. Each dot is a small ready-made image, and each frame repaints only
+// the small boxes the dots left and entered (the engine's several damaged rectangles, 0.8.2; the
+// cost is in docs/MONITOR.md). With Reduce motion each busy arc gets two still arrows instead.
const FLOW_FPS = 12, FLOW_FPS_BEHIND = 5, FLOW_ARCS = 12, FLOW_MIN = 256; // FLOW_MIN: bytes per second that count as "moving"
// 0 at FLOW_MIN, 1 from about 4 MB/s
const flowLevel = (rate) => (rate > FLOW_MIN ? Math.max(0, Math.min(1, Math.log10(rate / FLOW_MIN) / 4.2)) : -1);
const bez = (a, k) => { const u = 1 - k; return [u * u * a.x0 + 2 * u * k * a.cx + k * k * a.x1, u * u * a.y0 + 2 * u * k * a.cy + k * k * a.y1]; };
+// One moving dot as a ready-made 9×9 image (a ring and the direction's color): the engine only
+// blits it, instead of filling and stroking a rounded box with antialiasing on every frame (0.8.2).
+function dotSprite(fill, ring) {
+ const cv = canvas(9, 9), [, , , ra] = parseColor(ring);
+ dot(cv, 4.5, 4.5, 4.5, ring, ra);
+ dot(cv, 4.5, 4.5, 2.5, fill, 1);
+ return cv;
+}
+
// arcs: [{ cc, x0, y0, cx, cy, x1, y1, tx, rx }] in the map's pixels.
function FlowLayer({ arcs, w, h, paused }) {
const t = useTheme();
@@ -72,8 +81,9 @@ function FlowLayer({ arcs, w, h, paused }) {
tm = setTimeout(step, 1000 / fps);
return () => clearTimeout(tm);
}, [animate, sig, w, h, fps]);
- if (paused || hidden) return null;
const ring = t.mode === 'dark' ? 'rgba(20,21,24,0.85)' : 'rgba(255,255,255,0.9)';
+ const sprites = useMemo(() => ({ tx: dotSprite(C.tx, ring), rx: dotSprite(C.rx, ring) }), [ring]);
+ if (paused || hidden) return null;
if (!motion) {
// still markers at 38 % (received) and 62 % (sent) of each busy arc: a short comet of three
// dots, the biggest in front, so it reads as pointing the way the bytes go (no rotation needed)
@@ -99,9 +109,8 @@ function FlowLayer({ arcs, w, h, paused }) {
{dots.map((d) => {
const [x, y, on] = place(d, now);
return (
- <View key={d.key} ref={(r) => { if (r) nodes.current.set(d.key, r.id); else nodes.current.delete(d.key); }}
- style={{ position: 'absolute', left: on ? x : -20, top: on ? y : -20, width: 9, height: 9, borderRadius: 5, pointerEvents: 'none',
- backgroundColor: d.dir > 0 ? C.tx : C.rx, border: `2px solid ${ring}` }} />
+ <Image key={d.key} ref={(r) => { if (r) nodes.current.set(d.key, r.id); else nodes.current.delete(d.key); }} pixels={d.dir > 0 ? sprites.tx : sprites.rx}
+ style={{ position: 'absolute', left: on ? x : -20, top: on ? y : -20, width: 9, height: 9, pointerEvents: 'none' }} />
);
})}
</>
@@ -174,6 +183,7 @@ export function MapView({ places, home, selected, onSelect, geoOn, fitKey }) {
tx: p.rateTx || 0, rx: p.rateRx || 0, idle: (p.rateTx || 0) + (p.rateRx || 0) < FLOW_MIN,
}));
const dark = t.mode === 'dark';
+ const card = useCardStyle();
const colors = {
land: rgba(dark ? '#8a93a8' : '#9aa3b5', dark ? 0.30 : 0.42),
border: rgba(dark ? '#cfd6e6' : '#ffffff', dark ? (v && v.ppd > 6 ? 0.42 : 0.25) : 0.9),
@@ -382,7 +392,8 @@ export function MapView({ places, home, selected, onSelect, geoOn, fitKey }) {
backgroundColor: dark ? 'rgba(40,42,48,0.92)' : 'rgba(255,255,255,0.95)', border: `1px solid ${t.separator}` };
const btnText = { fontSize: 15, fontWeight: 600, color: t.text, lineHeight: 1 };
return (
- <View ref={box} style={{ flex: 1, minHeight: 120, overflow: 'hidden', borderRadius: 8, direction: 'ltr' }}
+ // the card's own color, opaque: a repaint of the moving dots starts here instead of at the card
+ <View ref={box} style={{ flex: 1, minHeight: 120, overflow: 'hidden', borderRadius: 8, direction: 'ltr', backgroundColor: card.bg }}
onMouseDown={onMouseDown} onWheel={onWheel} onPinch={onPinch} onDoubleClick={onDoubleClick}>
{img && <Image ref={imgRef} pixels={frame.pixels} style={{ position: 'absolute', left: img.left, top: img.top, width: img.width, height: img.height, pointerEvents: 'none' }} />}
{v && <FlowLayer arcs={flowArcs} w={w} h={h} paused={moving || !!live.current} />}
diff --git a/apps/monitor/Network.jsx b/apps/monitor/Network.jsx
index 27d9d5d..ff7ab20 100644
--- a/apps/monitor/Network.jsx
+++ b/apps/monitor/Network.jsx
@@ -13,7 +13,7 @@
// de regla de la lista y los contadores de permitidas/denegadas ya están en su lugar.
import {
View, Text, Image, ScrollView, SearchField, useTheme, useLocale, useStore, monitor, monitorConnections, useMonitor,
- formatBytes, formatNumber, tOptional, useSystemInfo, wm, direction, firewall, firewallState, useLauncherApps, Lumo, Button, useAppWindow,
+ formatBytes, formatNumber, tOptional, useSystemInfo, wm, direction, firewall, firewallState, useLauncherApps, Lumo, Button, useAppWindow, fwRule,
} from '@lordos/sdk';
import { useEffect, useMemo, useRef, useState } from 'react';
import { C, fmt, AppGlyph, useCardStyle } from './index.jsx';
@@ -21,6 +21,7 @@ import { Glyph } from './icons.jsx';
import { MapView } from './MapView.jsx';
import { TrafficChart, systemBuckets } from './TrafficChart.jsx';
import { RuleSheet } from './RuleSheet.jsx';
+import { HistoryControls, HistoryChart, useHistory } from './History.jsx';
export const appKeyOf = (c) => (c.self ? 'lordos' : c.app || c.exe || c.name || '?');
const countryName = (cc) => (cc ? tOptional(`countries.${cc}`) || cc : '');
@@ -205,11 +206,91 @@ function Activity({ hist, selected }) {
);
}
-function AppRow({ g, open, selected, onToggle, onSelect, onHost, names, maxBytes, tr, hist }) {
+// The destinations of an app, one row per name the system resolver gave (its addresses together),
+// or per address when no name is known; busiest first.
+function domainsOf(g, names) {
+ const out = new Map();
+ for (const h of g.hosts.values()) {
+ const name = names.get(h.remote) || null, key = name || h.remote;
+ const d = out.get(key) || { key, name, addrs: [], ports: new Set(), sent: 0, recv: 0, count: 0, cc: h.cc, scope: h.scope, recent: true, denied: false };
+ d.addrs.push(h.remote);
+ for (const p of h.ports || []) d.ports.add(p);
+ d.sent += h.sent || 0;
+ d.recv += h.recv || 0;
+ d.count += h.count || 0;
+ if (!h.recent) d.recent = false;
+ if (h.denied) d.denied = true;
+ if (!d.cc && h.cc) { d.cc = h.cc; d.scope = h.scope; }
+ out.set(key, d);
+ }
+ return [...out.values()].sort((a, b) => b.sent + b.recv - (a.sent + a.recv) || b.count - a.count);
+}
+
+// The first port seen ("TCP 443") as the connection the verdict is worked out for.
+function portOf(d) {
+ const p = [...d.ports][0];
+ const m = p ? /^(TCP|UDP) (\d+)$/.exec(p) : null;
+ return m ? { proto: m[1].toLowerCase(), port: Number(m[2]) } : { proto: 'tcp', port: 443 };
+}
+
+// One destination's own allow / deny switch (0.8.2): what the app's rules decide for it right now
+// (sdk/fwrule.js decide, the same order as the kernel), and one click writes, flips or removes the
+// rule for exactly that name (or address) with lord.fw, as Settings → Network rules by app does.
+function DomainSwitch({ d, g, rules, restricted, can, tr }) {
+ const t = useTheme();
+ const q = { names: d.name ? [d.name] : [], addr: d.addrs[0], ...portOf(d) };
+ const v = fwRule.decide(rules, q, restricted);
+ const on = v ? v.action === 'allow' : true;
+ const locked = !can || v?.by === 'restricted';
+ const flip = (e) => {
+ e.stopPropagation();
+ if (locked) return;
+ const op = fwRule.toggleOp(rules, { name: d.name, addr: d.addrs[0], ...portOf(d) }, restricted);
+ if (!op) return;
+ if (op.op === 'add') firewall.addRule({ app: g.key, ...op.rule });
+ else if (op.op === 'update') firewall.updateRule(op.id, op.rule);
+ else firewall.removeRule(op.id);
+ };
+ const color = on ? '#30d158' : '#ff453a';
+ return (
+ <View onClick={flip} style={{ width: 22, height: 12, borderRadius: 6, backgroundColor: on ? 'rgba(48,209,88,0.32)' : 'rgba(255,69,58,0.32)',
+ opacity: locked ? 0.45 : 1, justifyContent: 'center', alignItems: on ? 'flex-end' : 'flex-start', paddingHorizontal: 2, direction: 'ltr' }}>
+ <View style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: color }} />
+ </View>
+ );
+}
+
+// Why a destination is allowed or blocked when it isn't its own rule: the rule that decides it
+// ("*.example.com", "everything") or the app's restriction.
+function ruleHint(tr, d, rules, restricted) {
+ const v = fwRule.decide(rules, { names: d.name ? [d.name] : [], addr: d.addrs[0], ...portOf(d) }, restricted);
+ if (!v) return '';
+ if (v.by === 'restricted') return tr('monitor.net.domainRestricted');
+ const own = d.name ? fwRule.normDomain(d.name) : d.addrs[0];
+ if (v.rule.dst === own && !v.rule.port && !v.rule.proto) return '';
+ return v.rule.dst === 'any' ? tr('monitor.net.domainByDefault') : tr('monitor.net.domainByRule', { rule: v.rule.dst });
+}
+
+const DOMAINS_SHOWN = 8;
+
+function AppRow({ g, open, selected, onToggle, onSelect, onHost, names, maxBytes, tr, hist, all, onAll, restricted }) {
const t = useTheme();
const label = g.key === 'lordos' ? tr('monitor.lordos') : g.name;
const total = g.sent + g.recv;
- const hosts = [...g.hosts.values()].sort((a, b) => b.sent + b.recv - (a.sent + a.recv) || b.count - a.count);
+ // the order is kept while the row is open, so a switch doesn't move under the pointer when the
+ // traffic changes: busiest first when it opens, newcomers below
+ const order = useRef(null);
+ if (!open) order.current = null;
+ let domains = open ? domainsOf(g, names) : [];
+ if (open) {
+ const seen = order.current || new Map();
+ for (const d of domains) if (!seen.has(d.key)) seen.set(d.key, seen.size);
+ order.current = seen;
+ domains = [...domains].sort((a, b) => seen.get(a.key) - seen.get(b.key));
+ }
+ const can = firewall.available() && firewall.enforceable(g.key);
+ const rules = open && can ? firewall.rules(g.key) : [];
+ const shownDomains = all ? domains : domains.slice(0, DOMAINS_SHOWN);
const active = g.conns.length - g.listen.length;
return (
<View>
@@ -243,16 +324,29 @@ function AppRow({ g, open, selected, onToggle, onSelect, onHost, names, maxBytes
<RuleSwitch g={g} selected={selected} tr={tr} />
</View>
{open && (
- <View style={{ ...(direction() === 'rtl' ? { paddingRight: 46, paddingLeft: 8 } : { paddingLeft: 46, paddingRight: 8 }), paddingBottom: 4, gap: 1 }}>
- {hosts.slice(0, 30).map((h) => (
- <View key={h.remote} onClick={() => onHost(h.remote)} style={{ flexDirection: 'row', alignItems: 'center', gap: 6, height: 22 }}>
- <View style={{ width: 6, height: 6, borderRadius: 3, backgroundColor: h.denied ? '#ff453a' : h.scope === 'internet' || h.recent ? t.accent : t.textDim }} />
- <Text style={{ flex: 1, fontSize: 11, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', fontFamily: 'monospace' }}>{names.get(h.remote) || h.remote}</Text>
- <Text style={{ fontSize: 10, color: t.textDim, whiteSpace: 'nowrap' }}>{placeOf(tr, h)}</Text>
+ <View style={{ ...(direction() === 'rtl' ? { paddingRight: 30, paddingLeft: 8 } : { paddingLeft: 30, paddingRight: 8 }), paddingBottom: 4, gap: 1 }}>
+ {shownDomains.map((d) => {
+ const hint = can ? ruleHint(tr, d, rules, restricted) : '';
+ return (
+ <View key={d.key} onClick={() => onHost(d.addrs[0])} style={{ flexDirection: 'row', alignItems: 'center', gap: 6, minHeight: 22 }}>
+ <View style={{ width: 6, height: 6, borderRadius: 3, backgroundColor: d.denied ? '#ff453a' : d.scope === 'internet' || d.recent ? t.accent : t.textDim }} />
+ <View style={{ flex: 1, minWidth: 0 }}>
+ <Text style={{ fontSize: 11, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden', fontFamily: 'monospace', direction: 'ltr', textAlign: 'start' }}>
+ {d.name || d.key}{d.addrs.length > 1 ? ` (${d.addrs.length})` : ''}
+ </Text>
+ {hint ? <Text style={{ fontSize: 9, color: t.textDim, whiteSpace: 'nowrap', overflow: 'hidden' }}>{hint}</Text> : null}
+ </View>
+ <Text style={{ fontSize: 10, color: t.textDim, whiteSpace: 'nowrap' }}>{placeOf(tr, d)}</Text>
+ {can ? <DomainSwitch d={d} g={g} rules={rules} restricted={restricted} can={can} tr={tr} /> : null}
+ </View>
+ );
+ })}
+ {!domains.length && <Text style={{ fontSize: 11, color: t.textDim, height: 22 }}>{tr('monitor.net.onlyListening', { ports: g.listen.map((c) => c.lport).join(', ') })}</Text>}
+ {domains.length > DOMAINS_SHOWN ? (
+ <View onClick={onAll} style={{ height: 20, justifyContent: 'center' }}>
+ <Text style={{ fontSize: 10, color: t.accent }}>{all ? tr('monitor.net.fewer') : tr('monitor.net.moreDomains', { count: domains.length - DOMAINS_SHOWN })}</Text>
</View>
- ))}
- {!hosts.length && <Text style={{ fontSize: 11, color: t.textDim, height: 22 }}>{tr('monitor.net.onlyListening', { ports: g.listen.map((c) => c.lport).join(', ') })}</Text>}
- {hosts.length > 30 && <Text style={{ fontSize: 10, color: t.textDim }}>{tr('monitor.net.more', { count: hosts.length - 30 })}</Text>}
+ ) : null}
</View>
)}
</View>
@@ -285,26 +379,31 @@ function useRateHistory(apps) {
}
// The machine's traffic: current rates, the mirrored chart of the last 60 s and its totals. It
-// redraws at the 4 samples per second with the window in front (1 per second behind).
-function SystemTraffic({ tr }) {
+// redraws at the 4 samples per second with the window in front (1 per second behind). With a
+// history zoom (0.8.2) the chart shows that window from the history file instead.
+function SystemTraffic({ tr, range, setRange, end, setEnd, sysHist }) {
const t = useTheme();
const { focused } = useAppWindow() || {};
- const samples = useMonitor({ everyMs: focused === false ? 1000 : 250 });
+ const samples = useMonitor({ everyMs: range !== 'live' ? 0 : focused === false ? 1000 : 250 }) || [];
const last = samples[samples.length - 1];
const { buckets, shift, totals } = systemBuckets(samples, 60);
return (
<View style={{ gap: 6 }}>
- <View style={{ flexDirection: 'row', gap: 14, paddingHorizontal: 2 }}>
- <View style={{ flex: 1 }}>
- <Text style={{ fontSize: 10, color: t.textDim }}>{`↓ ${tr('monitor.received')}`}</Text>
- <Text style={{ fontSize: 14, fontWeight: 600, color: C.rx }}>{fmt.rate(tr, last?.net.rx)}</Text>
- </View>
- <View style={{ flex: 1 }}>
- <Text style={{ fontSize: 10, color: t.textDim }}>{`↑ ${tr('monitor.sent')}`}</Text>
- <Text style={{ fontSize: 14, fontWeight: 600, color: C.tx }}>{fmt.rate(tr, last?.net.tx)}</Text>
+ {range === 'live' ? (
+ <View style={{ flexDirection: 'row', gap: 14, paddingHorizontal: 2 }}>
+ <View style={{ flex: 1 }}>
+ <Text style={{ fontSize: 10, color: t.textDim }}>{`↓ ${tr('monitor.received')}`}</Text>
+ <Text style={{ fontSize: 14, fontWeight: 600, color: C.rx }}>{fmt.rate(tr, last?.net.rx)}</Text>
+ </View>
+ <View style={{ flex: 1 }}>
+ <Text style={{ fontSize: 10, color: t.textDim }}>{`↑ ${tr('monitor.sent')}`}</Text>
+ <Text style={{ fontSize: 14, fontWeight: 600, color: C.tx }}>{fmt.rate(tr, last?.net.tx)}</Text>
+ </View>
</View>
- </View>
- <TrafficChart buckets={buckets} shift={shift} totals={totals} seconds={60} />
+ ) : null}
+ <HistoryControls range={range} setRange={setRange} end={end} setEnd={setEnd} oldest={sysHist?.h?.oldest || 0} />
+ {range === 'live' ? <TrafficChart buckets={buckets} shift={shift} totals={totals} seconds={60} />
+ : <HistoryChart data={sysHist} range={range} />}
</View>
);
}
@@ -370,7 +469,7 @@ function KV({ k, v, mono, color }) {
const upDown = (tr, g) => tr('monitor.net.downUp', { down: formatBytes(g.recv || 0), up: formatBytes(g.sent || 0) });
-function Summary({ groups, conns, last, tr, fw, names }) {
+function Summary({ groups, conns, last, tr, fw, names, range, sysHist, launcher }) {
const t = useTheme();
let fwAllowed = 0, fwDenied = 0;
for (const v of Object.values(fw?.counts || {})) { fwAllowed += v[0] || 0; fwDenied += v[1] || 0; }
@@ -413,6 +512,22 @@ function Summary({ groups, conns, last, tr, fw, names }) {
))}
{!groups.length && <Text style={{ fontSize: 12, color: t.textDim }}>{tr('monitor.net.none')}</Text>}
</Section>
+ {range !== 'live' ? (
+ <Section title={tr('monitor.hist.topApps', { range: tr(`monitor.hist.${range}`) })}>
+ {(sysHist?.h?.top || []).slice(0, 6).map(([id, rx, tx]) => {
+ const la = launcher.find((a) => a.id === id || `lpk:${a.id}` === id || `desktop:${a.id}` === id);
+ const item = { app: id, appName: la?.name, name: la?.name || id, appIcon: la?.icon || '', self: id === 'lordos' };
+ return (
+ <View key={id} style={{ flexDirection: 'row', alignItems: 'center', gap: 6 }}>
+ <AppGlyph item={item} size={14} />
+ <Text style={{ flex: 1, minWidth: 0, fontSize: 12, color: t.text, whiteSpace: 'nowrap', overflow: 'hidden' }}>{id === 'lordos' ? tr('monitor.lordos') : la?.name || id.replace(/^(desktop|lpk):/, '')}</Text>
+ <Text style={{ fontSize: 10, color: t.textDim, whiteSpace: 'nowrap' }}>{upDown(tr, { recv: rx, sent: tx })}</Text>
+ </View>
+ );
+ })}
+ {!(sysHist?.h?.top || []).length && <Text style={{ fontSize: 12, color: t.textDim }}>{tr('monitor.net.none')}</Text>}
+ </Section>
+ ) : null}
<Section title={tr('monitor.net.topHosts')}>
{hosts.slice(0, 6).map((h) => (
<View key={`${h.app.key}${h.remote}`} style={{ gap: 1 }}>
@@ -450,7 +565,7 @@ function HostRow({ h, name, selected, onSelect, can, onRule, tr }) {
);
}
-function Detail({ g, tr, user, names, host, onHost, onRule, hist }) {
+function Detail({ g, tr, user, names, host, onHost, onRule, hist, range, end }) {
const t = useTheme();
const can = firewall.available() && firewall.enforceable(g.key);
const ports = new Set(), local = new Set();
@@ -485,7 +600,7 @@ function Detail({ g, tr, user, names, host, onHost, onRule, hist }) {
<Section title={tr('monitor.net.data')}>
<KV k={`↓ ${tr('monitor.received')}`} v={`${formatBytes(g.recv)} · ${fmt.rate(tr, g.rateRx)}`} color={C.rx} />
<KV k={`↑ ${tr('monitor.sent')}`} v={`${formatBytes(g.sent)} · ${fmt.rate(tr, g.rateTx)}`} color={C.tx} />
- <AppTraffic hist={hist} />
+ {range === 'live' ? <AppTraffic hist={hist} /> : <AppHistory app={g.key} range={range} end={end} />}
</Section>
<Section title={tr('monitor.net.ports')}>
<Text style={{ fontSize: 12, color: t.text, lineHeight: 1.4 }}>{[...ports].join(' · ') || '—'}</Text>
@@ -510,6 +625,12 @@ function AppTraffic({ hist }) {
return <TrafficChart buckets={buckets} height={40} seconds={60} />;
}
+// The selected app's share of the history window (the same zoom as the machine's chart).
+function AppHistory({ app, range, end }) {
+ const d = useHistory(range, end, app);
+ return <HistoryChart data={d} range={range} height={40} />;
+}
+
function PlaceDetail({ p, tr }) {
const t = useTheme();
const hosts = [...p.hosts].sort((a, b) => b.sent + b.recv - (a.sent + a.recv));
@@ -565,6 +686,11 @@ export function NetworkTab({ last, prefs }) {
const [place, setPlace] = useState(null); // país elegido en el mapa
const [host, setHost] = useState(null); // the selected app's address with the actions open
const [sheet, setSheet] = useState(null); // { app, label, dst, action, suggestions, note }
+ const [allDomains, setAllDomains] = useState(() => new Set()); // apps whose every destination is listed
+ const [range, setRange] = useState('live'); // the traffic chart's zoom: 'live' or a history window
+ const [end, setEnd] = useState(null); // the history window's end (Unix s), null = now
+ const sysHist = useHistory(range === 'live' ? null : range, end, null);
+ const restrictedOf = useMemo(() => firewall.state().restricted || {}, [fw.rev]);
const names = useMemo(() => namesOf(fw.events), [fw.events]);
const hist = useRateHistory(apps);
const ruleFor = (g, addr, action) => {
@@ -597,13 +723,15 @@ export function NetworkTab({ last, prefs }) {
{enabled && conns && !conns.ok && <Text style={{ fontSize: 12, color: '#ff9f0a', padding: 8 }}>{tr('monitor.net.noDiag')}</Text>}
{shown.map((g) => (
<AppRow key={g.key} g={g} tr={tr} open={open.has(g.key)} selected={selected === g.key} maxBytes={maxBytes} names={names} hist={hist.get(g.key)}
+ all={allDomains.has(g.key)} restricted={restrictedOf[g.key] || []}
+ onAll={() => setAllDomains((s0) => { const n = new Set(s0); if (n.has(g.key)) n.delete(g.key); else n.add(g.key); return n; })}
onToggle={() => toggle(g.key)} onSelect={() => { setPlace(null); setHost(null); setSelected(selected === g.key ? null : g.key); }}
onHost={(addr) => { setPlace(null); setSelected(g.key); setHost(addr); }} />
))}
{enabled && conns && !shown.length && <Text style={{ fontSize: 12, color: t.textDim, padding: 8 }}>{tr('monitor.net.none')}</Text>}
</ScrollView>
<View style={{ height: 1, backgroundColor: t.separator }} />
- <SystemTraffic tr={tr} />
+ <SystemTraffic tr={tr} range={range} setRange={setRange} end={end} setEnd={setEnd} sysHist={sysHist} />
</View>
{/* centro: el mapa ocupa toda la altura */}
<View style={{ ...column, flex: 1, minWidth: 0, gap: 8, padding: 10 }}>
@@ -626,8 +754,8 @@ export function NetworkTab({ last, prefs }) {
<ScrollView style={{ flex: 1 }} gutter>
<View style={{ gap: 16 }}>
{selPlace ? <PlaceDetail p={selPlace} tr={tr} /> : sel ? (
- <Detail g={sel} tr={tr} user={sys.user} names={names} host={host} onHost={setHost} hist={hist.get(sel.key)} onRule={(addr, action) => ruleFor(sel, addr, action)} />
- ) : <Summary groups={apps} conns={conns} last={last} tr={tr} fw={fw} names={names} />}
+ <Detail g={sel} tr={tr} user={sys.user} names={names} host={host} onHost={setHost} hist={hist.get(sel.key)} range={range} end={end} onRule={(addr, action) => ruleFor(sel, addr, action)} />
+ ) : <Summary groups={apps} conns={conns} last={last} tr={tr} fw={fw} names={names} range={range} sysHist={sysHist} launcher={launcher} />}
</View>
</ScrollView>
</View>
diff --git a/apps/monitor/Privacy.jsx b/apps/monitor/Privacy.jsx
index 4cd4746..4dfdaea 100644
--- a/apps/monitor/Privacy.jsx
+++ b/apps/monitor/Privacy.jsx
@@ -1,8 +1,11 @@
// Privacy.jsx — the "Monitor" item of Settings → Privacy (another module builds the page and the
// Monitor registers itself with registerPrivacySection, if it exists). Two switches, saved in
-// settings: see each app's connections and place them on the map with the local country database.
+// settings: see each app's connections and place them on the map with the local country database;
+// and, since 0.8.2, keep a traffic history (bytes per minute and per hour, never addresses) with
+// "Clear History" (monitor.clearHistory, docs/MONITOR.md "Traffic history").
// Drawn like the Settings sections: a 13/600 header, an inset GroupBox and a footer.
-import { View, Text, Toggle, Button, GroupBox, useTheme, useLocale, useSettings, wm, spacing, typeScale } from '@lordos/sdk';
+import { View, Text, Toggle, Button, GroupBox, useTheme, useLocale, useSettings, wm, spacing, typeScale, monitor } from '@lordos/sdk';
+import { useState } from 'react';
function Row({ label, hint, children }) {
const t = useTheme();
@@ -23,6 +26,7 @@ export function MonitorPrivacy() {
const [s, set] = useSettings();
const m = s.monitor || {};
const put = (patch) => set({ monitor: { ...m, ...patch } });
+ const [cleared, setCleared] = useState(false);
return (
<View style={{ gap: 6 }}>
<View style={{ flexDirection: 'row', alignItems: 'center', minHeight: 22, paddingHorizontal: spacing.xs, gap: spacing.s }}>
@@ -36,6 +40,13 @@ export function MonitorPrivacy() {
<Row label={tr('monitor.privacy.geo')} hint={tr('monitor.privacy.geoHint')}>
<Toggle small on={m.geo !== false} onChange={(on) => put({ geo: on })} />
</Row>
+ <Row label={tr('monitor.privacy.history')} hint={tr('monitor.privacy.historyHint')}>
+ <Toggle small on={m.history !== false} onChange={(on) => put({ history: on })} />
+ </Row>
+ <View style={{ flexDirection: 'row', justifyContent: 'flex-end', paddingVertical: 6 }}>
+ <Button small label={cleared ? tr('monitor.privacy.cleared') : tr('monitor.privacy.clear')} disabled={cleared}
+ onClick={() => { if (monitor.clearHistory()) setCleared(true); }} />
+ </View>
</GroupBox>
<Text style={{ fontSize: typeScale.caption, color: t.textDim, lineHeight: 1.4, marginHorizontal: spacing.xs, textAlign: 'start' }}>{tr('monitor.privacy.local')}</Text>
</View>
diff --git a/apps/monitor/TrafficChart.jsx b/apps/monitor/TrafficChart.jsx
index c77a958..127b02b 100644
--- a/apps/monitor/TrafficChart.jsx
+++ b/apps/monitor/TrafficChart.jsx
@@ -26,7 +26,8 @@ function Pill({ arrow, value, color, t }) {
}
// totals: [rxBytes, txBytes] over the visible period (shown as pills) or null.
-export function TrafficChart({ buckets, shift = 0, seconds = 60, height = 52, totals, compact }) {
+// caption replaces "last 60 s" and axis the [left, right] labels under it (the history's dates).
+export function TrafficChart({ buckets, shift = 0, seconds = 60, height = 52, totals, compact, caption, axis }) {
const t = useTheme();
const { t: tr } = useLocale();
const box = useRef(null);
@@ -51,7 +52,7 @@ export function TrafficChart({ buckets, shift = 0, seconds = 60, height = 52, to
<Pill arrow="↑" value={formatBytes(totals[1])} color={C.tx} t={t} />
<Pill arrow="↓" value={formatBytes(totals[0])} color={C.rx} t={t} />
<View style={{ flex: 1 }} />
- <Text style={{ fontSize: 9, color: t.textDim, whiteSpace: 'nowrap' }}>{tr('monitor.net.lastSeconds', { n: seconds })}</Text>
+ <Text style={{ fontSize: 9, color: t.textDim, whiteSpace: 'nowrap' }}>{caption || tr('monitor.net.lastSeconds', { n: seconds })}</Text>
</View>
) : null}
<View ref={box} style={{ height, direction: 'ltr', borderRadius: 4, overflow: 'hidden' }}>
@@ -61,8 +62,8 @@ export function TrafficChart({ buckets, shift = 0, seconds = 60, height = 52, to
</View>
{!compact ? (
<View style={{ flexDirection: 'row', direction: 'ltr' }}>
- <Text style={{ flex: 1, fontSize: 9, color: t.textDim }}>{tr('monitor.agoSeconds', { n: seconds })}</Text>
- <Text style={{ fontSize: 9, color: t.textDim }}>{tr('monitor.now')}</Text>
+ <Text style={{ flex: 1, fontSize: 9, color: t.textDim }}>{axis ? axis[0] : tr('monitor.agoSeconds', { n: seconds })}</Text>
+ <Text style={{ fontSize: 9, color: t.textDim }}>{axis ? axis[1] : tr('monitor.now')}</Text>
</View>
) : null}
</View>
diff --git a/assets/locales/en/monitor.json b/assets/locales/en/monitor.json
index cb074f5..b20d645 100644
--- a/assets/locales/en/monitor.json
+++ b/assets/locales/en/monitor.json
@@ -134,7 +134,7 @@
"privacy.connectionsHint": "Monitor lists your apps' network connections (address, port, state and process). It only reads kernel state; it does not block anything.",
"privacy.geo": "Locate connections on the map",
"privacy.geoHint": "Looks up the country of each address in a database shipped with LordOS (DB-IP Lite Country, CC BY 4.0).",
- "privacy.local": "Everything is computed on this computer, and only while Monitor is open. No IP address leaves the computer.",
+ "privacy.local": "Everything is computed on this computer. The live lists only run while Monitor is open; the traffic history, when it is on, is recorded by your session. No IP address leaves the computer.",
"privacy.open": "Open Monitor",
"net.placeApps": "Apps",
"net.privacyShort": "IP-to-country from a local database (DB-IP Lite, CC BY 4.0, db-ip.com): no address leaves the computer.",
@@ -217,5 +217,30 @@
"proc.cmdline": "Command line",
"proc.noCmdline": "(none: a kernel thread or a process that cleared it)",
"proc.tab.stats": "Statistics",
- "proc.tab.files": "Open files and ports"
+ "proc.tab.files": "Open files and ports",
+ "hist.live": "60 s",
+ "hist.1h": "1 h",
+ "hist.24h": "24 h",
+ "hist.7d": "7 d",
+ "hist.30d": "30 d",
+ "hist.per.1h": "per minute",
+ "hist.per.24h": "every 15 min",
+ "hist.per.7d": "per hour",
+ "hist.per.30d": "every 6 h",
+ "hist.unavailable": "The traffic history is not available in this session.",
+ "hist.off": "The traffic history is off (Settings → Privacy → Monitor).",
+ "hist.none": "Nothing was recorded in this period.",
+ "hist.topApps": "Most traffic · {range}",
+ "net.moreDomains": {
+ "one": "{count} more…",
+ "other": "{count} more…"
+ },
+ "net.fewer": "Show fewer",
+ "net.domainRestricted": "Blocked by this app's restrictions",
+ "net.domainByDefault": "Follows this app's default",
+ "net.domainByRule": "By the rule {rule}",
+ "privacy.history": "Keep a traffic history",
+ "privacy.historyHint": "Bytes received and sent per minute for 7 days and per hour for 30 days, for the computer and for each app. Never addresses, names or countries. Kept only in your home folder.",
+ "privacy.clear": "Clear History",
+ "privacy.cleared": "History cleared"
}
diff --git a/assets/locales/es/monitor.json b/assets/locales/es/monitor.json
index 78afbc6..ea5d2bf 100644
--- a/assets/locales/es/monitor.json
+++ b/assets/locales/es/monitor.json
@@ -134,7 +134,7 @@
"privacy.connectionsHint": "El Monitor lista las conexiones de red de tus apps (dirección, puerto, estado y proceso). Solo lee el estado del núcleo; no bloquea nada.",
"privacy.geo": "Ubicar las conexiones en el mapa",
"privacy.geoHint": "Busca el país de cada dirección en una base incluida en LordOS (DB-IP Lite Country, CC BY 4.0).",
- "privacy.local": "Todo se calcula en este equipo y solo mientras el Monitor está abierto. Ninguna dirección IP sale del equipo.",
+ "privacy.local": "Todo se calcula en este equipo. Las listas en vivo solo funcionan mientras el Monitor está abierto; el historial de tráfico, si está prendido, lo registra tu sesión. Ninguna dirección IP sale del equipo.",
"privacy.open": "Abrir Monitor",
"net.placeApps": "Apps",
"net.privacyShort": "País por IP con una base local (DB-IP Lite, CC BY 4.0, db-ip.com): ninguna dirección sale del equipo.",
@@ -217,5 +217,30 @@
"proc.cmdline": "Línea de comandos",
"proc.noCmdline": "(ninguna: un hilo del núcleo o un proceso que la borró)",
"proc.tab.stats": "Estadísticas",
- "proc.tab.files": "Archivos y puertos abiertos"
+ "proc.tab.files": "Archivos y puertos abiertos",
+ "hist.live": "60 s",
+ "hist.1h": "1 h",
+ "hist.24h": "24 h",
+ "hist.7d": "7 d",
+ "hist.30d": "30 d",
+ "hist.per.1h": "por minuto",
+ "hist.per.24h": "cada 15 min",
+ "hist.per.7d": "por hora",
+ "hist.per.30d": "cada 6 h",
+ "hist.unavailable": "El historial de tráfico no está disponible en esta sesión.",
+ "hist.off": "El historial de tráfico está apagado (Ajustes → Privacidad → Monitor).",
+ "hist.none": "No se registró nada en este período.",
+ "hist.topApps": "Más tráfico · {range}",
+ "net.moreDomains": {
+ "one": "{count} más…",
+ "other": "{count} más…"
+ },
+ "net.fewer": "Mostrar menos",
+ "net.domainRestricted": "Bloqueado por las restricciones de esta app",
+ "net.domainByDefault": "Sigue lo predeterminado de esta app",
+ "net.domainByRule": "Por la regla {rule}",
+ "privacy.history": "Guardar un historial de tráfico",
+ "privacy.historyHint": "Bytes recibidos y enviados por minuto durante 7 días y por hora durante 30 días, del equipo y de cada app. Nunca direcciones, nombres ni países. Se guarda solo en tu carpeta personal.",
+ "privacy.clear": "Borrar historial",
+ "privacy.cleared": "Historial borrado"
}
diff --git a/assets/locales/pt/monitor.json b/assets/locales/pt/monitor.json
index c0a44a7..d7eeb36 100644
--- a/assets/locales/pt/monitor.json
+++ b/assets/locales/pt/monitor.json
@@ -134,7 +134,7 @@
"privacy.connectionsHint": "O Monitor lista as conexões de rede dos seus apps (endereço, porta, estado e processo). Só lê o estado do núcleo; não bloqueia nada.",
"privacy.geo": "Localizar as conexões no mapa",
"privacy.geoHint": "Busca o país de cada endereço numa base incluída no LordOS (DB-IP Lite Country, CC BY 4.0).",
- "privacy.local": "Tudo é calculado neste computador e só enquanto o Monitor está aberto. Nenhum endereço IP sai do computador.",
+ "privacy.local": "Tudo é calculado neste computador. As listas ao vivo só funcionam enquanto o Monitor está aberto; o histórico de tráfego, se estiver ligado, é registrado pela sua sessão. Nenhum endereço IP sai do computador.",
"privacy.open": "Abrir Monitor",
"net.placeApps": "Apps",
"net.privacyShort": "País por IP com uma base local (DB-IP Lite, CC BY 4.0, db-ip.com): nenhum endereço sai do computador.",
@@ -217,5 +217,30 @@
"proc.cmdline": "Linha de comando",
"proc.noCmdline": "(nenhuma: uma thread do núcleo ou um processo que a apagou)",
"proc.tab.stats": "Estatísticas",
- "proc.tab.files": "Arquivos e portas abertos"
+ "proc.tab.files": "Arquivos e portas abertos",
+ "hist.live": "60 s",
+ "hist.1h": "1 h",
+ "hist.24h": "24 h",
+ "hist.7d": "7 d",
+ "hist.30d": "30 d",
+ "hist.per.1h": "por minuto",
+ "hist.per.24h": "a cada 15 min",
+ "hist.per.7d": "por hora",
+ "hist.per.30d": "a cada 6 h",
+ "hist.unavailable": "O histórico de tráfego não está disponível nesta sessão.",
+ "hist.off": "O histórico de tráfego está desligado (Ajustes → Privacidade → Monitor).",
+ "hist.none": "Nada foi registrado neste período.",
+ "hist.topApps": "Mais tráfego · {range}",
+ "net.moreDomains": {
+ "one": "mais {count}…",
+ "other": "mais {count}…"
+ },
+ "net.fewer": "Mostrar menos",
+ "net.domainRestricted": "Bloqueado pelas restrições deste app",
+ "net.domainByDefault": "Segue o padrão deste app",
+ "net.domainByRule": "Pela regra {rule}",
+ "privacy.history": "Manter um histórico de tráfego",
+ "privacy.historyHint": "Bytes recebidos e enviados por minuto durante 7 dias e por hora durante 30 dias, do computador e de cada app. Nunca endereços, nomes ou países. Fica só na sua pasta pessoal.",
+ "privacy.clear": "Apagar histórico",
+ "privacy.cleared": "Histórico apagado"
}
diff --git a/sdk/monitor.js b/sdk/monitor.js
index 8e99dea..cd0a9f9 100644
--- a/sdk/monitor.js
+++ b/sdk/monitor.js
@@ -14,6 +14,12 @@
// await monitor.stopProcess(p, 'TERM' | 'KILL') the user's own: lord-server signals it; another
// user's or root's: the root helper (administrators)
//
+// Traffic history (0.8.2, docs/MONITOR.md "Traffic history"): lord-server records the machine's and
+// each of the user's apps' bytes per minute (7 days) and per hour (30 days) in a file of the user's,
+// while Settings → Privacy → Monitor → "Keep a traffic history" is on (settings.monitor.history).
+// monitor.history({ from, step, n, app }) → { res, oldest, now, rx: [n], tx: [n], top: [[app, rx, tx]] } | null
+// monitor.clearHistory() → true when it is gone
+//
// Phase 2 (not implemented yet): monitor.deviceUsers() → [{ kind: 'camera' | 'microphone',
// app, name, pid }] and the monitorDevices store; and the firewall with per-app and per-domain rules,
// which rely on the same connection records (the `verdict` field, always 'allow' today).
@@ -22,6 +28,7 @@ import { createStore, useStore } from './store.js';
import { locale } from './i18n.js';
import { admin } from './admin.js';
import { codeError } from './errors.js';
+import { settings } from './settings.js';
export const MONITOR_HISTORY = 240; // 60 s at 4 samples per second
export const monitorSamples = createStore([]);
@@ -204,6 +211,26 @@ async function stopProcess(p, kind, { own } = {}) {
await admin.run('proc-signal', `${p.pid} ${p.st} ${kind}`, null, { quiet: true });
}
+// The history records in lord-server, with the window closed too; the switch is the user's setting
+// (lord-server ignores it on the login screen and in isolated apps).
+let historyOn = null;
+function syncHistory() {
+ const on = settings.get()?.monitor?.history !== false;
+ if (on === historyOn || !available() || typeof lord.monitor.historyEnable !== 'function') return;
+ historyOn = on;
+ try { lord.monitor.historyEnable(on); } catch (e) { /* an older lord-server */ }
+}
+if (typeof lord !== 'undefined') { syncHistory(); settings.subscribe(syncHistory); }
+
+function history({ from, step, n, app = null }) {
+ if (!available() || typeof lord.monitor.history !== 'function') return null;
+ try { return lord.monitor.history({ from: Math.floor(from), step: Math.floor(step), n: Math.floor(n), app }); } catch (e) { return null; }
+}
+function clearHistory() {
+ if (!available() || typeof lord.monitor.historyClear !== 'function') return false;
+ try { return !!lord.monitor.historyClear(); } catch (e) { return false; }
+}
+
let infoCache = null;
export const monitor = {
available,
@@ -211,4 +238,6 @@ export const monitor = {
deviceUsers: () => [], // phase 2
watchProcess,
stopProcess,
+ history,
+ clearHistory,
};