Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion packages/user-intent-kit/src/adapters/desktop.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import { execSync } from 'node:child_process';
import { platform } from 'node:os';
import { collectHostTelemetry } from '../host-telemetry.js';

/**
* Desktop Adapter - detects active window and context on macOS.
Expand All @@ -13,15 +14,19 @@ import { platform } from 'node:os';
export class DesktopAdapter {
#client;
#pollTimer;
#machine;
#kind;
#pollIntervalMs;

/**
* @param {import('../client.js').IntentClient} client
* @param {object} [opts]
* @param {number} [opts.pollIntervalMs=30000] - How often to publish state
*/
constructor(client, { pollIntervalMs = 30000 } = {}) {
constructor(client, { pollIntervalMs = 30000, machine, kind } = {}) {
this.#client = client;
this.#machine = machine ?? client?.deviceId ?? undefined;
this.#kind = kind;
this.#pollIntervalMs = pollIntervalMs;
this.#pollTimer = null;
}
Expand Down Expand Up @@ -57,9 +62,13 @@ export class DesktopAdapter {
}

#detectState() {
// Vitals ride along with the desktop card so a machine's row shows what it
// is and how it is doing, the same fields the Pi publishes — otherwise a
// Mac appears in the fleet as a name and nothing else.
const state = {
screen_active: true,
context: 'active',
...collectHostTelemetry({ machine: this.#machine, kind: this.#kind }),
};

try {
Expand Down
151 changes: 148 additions & 3 deletions packages/user-intent-kit/src/host-telemetry.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,43 @@
* passed on whichever box happened to run them.
*/

import { execFileSync } from 'node:child_process';
import { readFileSync, readdirSync } from 'node:fs';
import { cpus, loadavg, platform } from 'node:os';
import { cpus, freemem, loadavg, platform, totalmem } from 'node:os';

/** Plausible CPU die temperatures. Outside this, assume the sensor lied. */
const TEMP_MIN_C = 1;
const TEMP_MAX_C = 150;

const THERMAL_ROOT = '/sys/class/thermal';

/** Real sensor reads. Swapped out wholesale in tests. */
/** Bytes per GB, base 10 — matching the units already published by the fleet. */
const BYTES_PER_GB = 1e9;

/**
* Run a command for a fact we cannot get from Node. Arguments are passed as
* argv, never interpolated into a shell string, and a failure is just an
* absent field.
*/
function run(cmd, args) {
try {
return execFileSync(cmd, args, {
encoding: 'utf8',
timeout: 2000,
stdio: ['ignore', 'pipe', 'ignore'],
}).trim();
} catch {
return '';
}
}

export const defaultSources = {
platform: () => platform(),
loadavg: () => loadavg(),
cpuCount: () => cpus()?.length,
totalMemBytes: () => totalmem(),
freeMemBytes: () => freemem(),
run,
listThermalZones: () => readdirSync(THERMAL_ROOT).filter((z) => z.startsWith('thermal_zone')),
readThermalZone: (zone) => readFileSync(`${THERMAL_ROOT}/${zone}/temp`, 'utf8'),
};
Expand Down Expand Up @@ -62,6 +85,105 @@ function readLoad(sources) {
return out;
}

/**
* Installed and free memory, in GB (1e9 bytes, the unit the fleet already
* publishes — a MacBook with 128 GiB reports 137.4).
*
* Deliberately no used-percentage. On macOS `freemem()` counts only genuinely
* free pages and excludes the cache, which the OS will hand back on demand, so
* a percentage derived from it reads as 95% used on a machine that is not
* short of memory at all. Free and total are facts; the percentage would be an
* alarm the numbers do not support.
*
* @returns {{mem_total_gb?: number, mem_free_gb?: number}}
*/
function readMemory(sources) {
const out = {};
const total = sources.totalMemBytes?.();
const free = sources.freeMemBytes?.();
Comment on lines +102 to +103

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Isolate failures from each memory reading

When either injected memory accessor throws, the outer catch discards both metrics: a failing totalMemBytes prevents freeMemBytes from running, while a failing freeMemBytes abandons the already-read total before out is returned. This violates the field-by-field best-effort contract for hosts where only one memory source is readable; catch each accessor independently so the surviving measurement is still published.

Useful? React with 👍 / 👎.


if (Number.isFinite(total) && total > 0) {
out.mem_total_gb = Math.round((total / BYTES_PER_GB) * 10) / 10;
}
if (Number.isFinite(free) && free >= 0) {
out.mem_free_gb = Math.round((free / BYTES_PER_GB) * 10) / 10;
}
return out;
}

/**
* Hardware description never changes while the process runs, so it is read
* once — but keyed by the sources object rather than module-global, or the
* first caller's answer would be served to every later one regardless of what
* it asked. (A module-level cache also made the function untestable: injected
* sources were ignored once the real machine had populated it.)
*/
const hardwareCache = new WeakMap();

/**
* What this machine is, in the words its own OS uses — "Apple M4 (Mac16,10)",
* "Raspberry Pi 5 Model B". Purely descriptive; the dashboard shows it so a
* card is identifiable without knowing the hostname convention.
*/
function readHardware(sources) {
if (hardwareCache.has(sources)) return hardwareCache.get(sources);

let hw = '';
if (sources.platform() === 'darwin') {
const chip = sources.run('/usr/sbin/sysctl', ['-n', 'machdep.cpu.brand_string']);
const model = sources.run('/usr/sbin/sysctl', ['-n', 'hw.model']);
hw = chip && model ? `${chip} (${model})` : chip || model;
} else if (sources.platform() === 'linux') {
// The Pi names itself here; \0-terminated, hence the trim.
try {
hw = readFileSync('/proc/device-tree/model', 'utf8').replace(/\0/g, '').trim();
} catch {
hw = '';
}
}
hardwareCache.set(sources, hw);
return hw;
}

/**
* Which way this host reaches the network, and at what address.
*
* Reported as the medium ("wifi" / "ethernet") plus the LAN address, so a
* card shows how a machine is attached — the Pi is deliberately never on the
* house wifi, and seeing that at a glance matters.
*
* No SSID: on current macOS that needs location permission, and a field that
* works on one machine and silently fails on another is worse than no field.
*/
function readNetwork(sources) {
const out = {};
const os = sources.platform();

if (os === 'darwin') {
const iface = (sources.run('/sbin/route', ['-n', 'get', 'default']).match(/interface:\s*(\S+)/) || [])[1];
if (!iface) return out;
const ip = sources.run('/usr/sbin/ipconfig', ['getifaddr', iface]);
if (ip) out.lan_ip = ip;
// The Wi-Fi port maps to one device (often en1); anything else is wired.
const ports = sources.run('/usr/sbin/networksetup', ['-listallhardwareports']);
const wifiDev = (ports.match(/Hardware Port:\s*Wi-Fi\s*\nDevice:\s*(\S+)/) || [])[1];
out.network = iface === wifiDev ? 'wifi' : 'ethernet';
} else if (os === 'linux') {
const iface = (sources.run('/sbin/ip', ['route', 'show', 'default']).match(/dev\s+(\S+)/) || [])[1];
if (!iface) return out;
const addr = sources.run('/sbin/ip', ['-4', '-o', 'addr', 'show', iface]);
const ip = (addr.match(/inet\s+([\d.]+)/) || [])[1];
if (ip) out.lan_ip = ip;
try {
readdirSync(`/sys/class/net/${iface}/wireless`);
out.network = 'wifi';
} catch {
out.network = 'ethernet';
}
}
return out;
}

/**
* CPU temperature from the Linux thermal zones (Raspberry Pi and friends).
*
Expand Down Expand Up @@ -104,19 +226,29 @@ function readLinuxTempC(sources) {
*
* @param {object} [opts]
* @param {string} [opts.machine] - stable device name (e.g. "mac-mini")
* @param {string} [opts.kind] - role the fleet knows this box by ("car-pi",
* "mac-mini"); the Pi already publishes this, so Macs use the same word
* rather than inventing a second vocabulary for the same idea
* @param {object} [opts.sources] - injectable sensor reads, for tests
* @returns {object} only the fields that were readable
*/
export function collectHostTelemetry({ machine, sources = defaultSources } = {}) {
export function collectHostTelemetry({ machine, kind, sources = defaultSources } = {}) {
const host = {};
if (machine) host.machine = machine;
if (kind) host.kind = kind;

try {
Object.assign(host, readLoad(sources));
} catch {
// Load is best-effort like everything else here.
}

try {
Object.assign(host, readMemory(sources));
} catch {
// Memory is best-effort too; publish whatever else we managed to read.
}

try {
if (sources.platform() === 'linux') {
const tempC = readLinuxTempC(sources);
Expand All @@ -126,5 +258,18 @@ export function collectHostTelemetry({ machine, sources = defaultSources } = {})
// No thermal zones exposed; publish without a temperature.
}

try {
const hw = readHardware(sources);
if (hw) host.hw = hw;
} catch {
// Descriptive only; never worth failing a heartbeat over.
}

try {
Object.assign(host, readNetwork(sources));
} catch {
// Same: an unknown link is published as no link, not a wrong one.
}

return host;
}
79 changes: 78 additions & 1 deletion packages/user-intent-kit/test/host-telemetry.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,18 @@ import { collectHostTelemetry } from '../src/host-telemetry.js';
* suite happens to expose, so on a Mac the Linux thermal path would never run
* and "tests pass" would say nothing about the Pi.
*/
function sources({ platform = 'linux', load = [1.8, 1.7, 1.6], cpuCount = 4, zones = {} } = {}) {
function sources({ platform = 'linux', load = [1.8, 1.7, 1.6], cpuCount = 4, zones = {},
totalMem = 16e9, freeMem = 4e9, commands = {} } = {}) {
return {
platform: () => platform,
loadavg: () => load,
cpuCount: () => cpuCount,
totalMemBytes: () => totalMem,
freeMemBytes: () => freeMem,
run: (cmd, args) => {
const key = `${cmd} ${(args || []).join(' ')}`;
return (commands && commands[key]) || '';
},
listThermalZones: () => Object.keys(zones),
readThermalZone: (zone) => {
const value = zones[zone];
Expand Down Expand Up @@ -153,3 +160,73 @@ test('never throws, whatever the sensors do', () => {
test('works against the real machine without arguments', () => {
assert.doesNotThrow(() => collectHostTelemetry());
});

// --- memory ---

test('publishes installed and free memory in GB', () => {
const host = collectHostTelemetry({ sources: sources({ totalMem: 25.8e9, freeMem: 1.2e9 }) });
assert.equal(host.mem_total_gb, 25.8);
assert.equal(host.mem_free_gb, 1.2);
});

test('publishes no used-percentage, which macOS free memory cannot support', () => {
const host = collectHostTelemetry({ sources: sources() });
assert.ok(!('mem_used_pct' in host), 'derived a usage figure from an unreliable free count');
});

test('zero free memory is a real reading, not a missing one', () => {
const host = collectHostTelemetry({ sources: sources({ freeMem: 0 }) });
assert.equal(host.mem_free_gb, 0);
});

test('omits memory when the host cannot report it', () => {
const blind = sources();
blind.totalMemBytes = () => undefined;
blind.freeMemBytes = () => undefined;
const host = collectHostTelemetry({ sources: blind });
assert.ok(!('mem_total_gb' in host));
assert.ok(!('mem_free_gb' in host));
assert.ok('load_1m' in host, 'a missing memory reading must not suppress load');
});

test('memory survives a hostile sensor without throwing', () => {
const hostile = sources();
hostile.totalMemBytes = () => { throw new Error('boom'); };
assert.doesNotThrow(() => collectHostTelemetry({ sources: hostile }));
});

// --- hardware + network ---

test('describes Mac hardware from the OS, not from guesswork', () => {
const host = collectHostTelemetry({ sources: sources({ platform: 'darwin', commands: {
'/usr/sbin/sysctl -n machdep.cpu.brand_string': 'Apple M4',
'/usr/sbin/sysctl -n hw.model': 'Mac16,10',
}})});
assert.equal(host.hw, 'Apple M4 (Mac16,10)');
});

test('reports a wired Mac as ethernet, not wifi', () => {
const host = collectHostTelemetry({ sources: sources({ platform: 'darwin', commands: {
'/sbin/route -n get default': ' interface: en0',
'/usr/sbin/ipconfig getifaddr en0': '192.168.50.241',
'/usr/sbin/networksetup -listallhardwareports': 'Hardware Port: Wi-Fi\nDevice: en1\n',
}})});
assert.equal(host.network, 'ethernet');
assert.equal(host.lan_ip, '192.168.50.241');
});

test('reports a Mac on the wifi device as wifi', () => {
const host = collectHostTelemetry({ sources: sources({ platform: 'darwin', commands: {
'/sbin/route -n get default': ' interface: en1',
'/usr/sbin/ipconfig getifaddr en1': '192.168.50.99',
'/usr/sbin/networksetup -listallhardwareports': 'Hardware Port: Wi-Fi\nDevice: en1\n',
}})});
assert.equal(host.network, 'wifi');
});

test('omits hardware and network when the commands fail', () => {
const host = collectHostTelemetry({ sources: sources({ platform: 'darwin', commands: {} })});
assert.ok(!('hw' in host), 'invented a hardware description');
assert.ok(!('network' in host), 'guessed a network medium');
assert.ok(!('lan_ip' in host));
});
Loading