Open History to see the last commit
1import type { EnvironmentMachineKind } from "@t3tools/contracts";
2import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
3import * as Effect from "effect/Effect";
4import * as FileSystem from "effect/FileSystem";
5
6import * as ProcessRunner from "../processRunner.ts";
7
8/**
9 * Best-effort hardware detection for the environment icon. Every probe is
10 * allowed to fail: a null result means "no signal", and the client draws a
11 * generic server until the user picks something in Settings → Connections.
12 */
13
14const DMI_ROOT = "/sys/class/dmi/id";
15
16// SMBIOS 3.x System Enclosure types (table 17). Codes that describe a shape
17// rather than a machine (docking stations, blades enclosures, IoT gateways)
18// fall through to null on purpose.
19const DMI_CHASSIS_KINDS: Readonly<Record<string, EnvironmentMachineKind>> = {
20 "3": "desktop", // Desktop
21 "4": "desktop", // Low Profile Desktop
22 "5": "desktop", // Pizza Box
23 "6": "desktop", // Mini Tower
24 "7": "desktop", // Tower
25 "8": "laptop", // Portable
26 "9": "laptop", // Laptop
27 "10": "laptop", // Notebook
28 "13": "desktop", // All in One
29 "14": "laptop", // Sub Notebook
30 "15": "desktop", // Space-saving
31 "16": "desktop", // Lunch Box
32 "17": "server", // Main Server Chassis
33 "18": "server", // Expansion Chassis
34 "19": "server", // SubChassis
35 "20": "server", // Bus Expansion Chassis
36 "21": "server", // Peripheral Chassis
37 "22": "server", // RAID Chassis
38 "23": "server", // Rack Mount Chassis
39 "24": "server", // Sealed-case PC
40 "28": "server", // Blade
41 "31": "laptop", // Convertible
42 "32": "laptop", // Detachable
43 "35": "desktop", // Mini PC
44};
45
46// Hypervisors and cloud providers write themselves into the DMI vendor or
47// product strings; any hit means the box is a VM, and a VM reads as "cloud"
48// regardless of the chassis type the hypervisor fakes. Hyper-V is matched on
49// its "Virtual Machine" product, not the "Microsoft Corporation" vendor that
50// physical Surface devices share.
51const VIRTUALIZATION_MARKERS = [
52 "qemu",
53 "kvm",
54 "bochs",
55 "vmware",
56 "virtualbox",
57 "innotek",
58 "xen",
59 "parallels",
60 "amazon ec2",
61 "google compute engine",
62 "digitalocean",
63 "hetzner",
64 "linode",
65 "vultr",
66 "scaleway",
67 "openstack",
68 "cloud",
69 "virtual machine",
70];
71
72function normalize(value: string | null | undefined): string | null {
73 const trimmed = value?.trim();
74 return trimmed && trimmed.length > 0 ? trimmed : null;
75}
76
77/** Marketing names and Intel-era model identifiers share these prefixes. */
78export function machineKindFromAppleProductName(name: string): EnvironmentMachineKind | null {
79 const normalized = name.trim().toLowerCase().replaceAll(/\s+/g, "");
80 if (normalized.startsWith("macmini")) return "mac-mini";
81 if (normalized.startsWith("macstudio")) return "mac-studio";
82 if (normalized.startsWith("macbook")) return "laptop";
83 if (normalized.startsWith("imac") || normalized.startsWith("macpro")) return "desktop";
84 return null;
85}
86
87export function machineKindFromDmi(input: {
88 readonly chassisType: string | null;
89 readonly sysVendor: string | null;
90 readonly productName: string | null;
91}): EnvironmentMachineKind | null {
92 const productName = input.productName ?? "";
93 const vendorAndProduct = `${input.sysVendor ?? ""} ${productName}`.toLowerCase();
94 if (VIRTUALIZATION_MARKERS.some((marker) => vendorAndProduct.includes(marker))) {
95 return "cloud";
96 }
97 // Apple hardware booting Linux (Asahi) still reports the Apple product name.
98 const appleKind = machineKindFromAppleProductName(productName);
99 if (appleKind !== null) {
100 return appleKind;
101 }
102 return input.chassisType === null ? null : (DMI_CHASSIS_KINDS[input.chassisType] ?? null);
103}
104
105const readOptionalFile = Effect.fn("readOptionalFile")(function* (path: string) {
106 const fileSystem = yield* FileSystem.FileSystem;
107 return yield* fileSystem.readFileString(path).pipe(
108 Effect.map(normalize),
109 Effect.catch(() => Effect.succeed(null)),
110 );
111});
112
113const runProbe = Effect.fn("runMachineProbe")(function* (input: {
114 readonly command: string;
115 readonly args: ReadonlyArray<string>;
116}) {
117 const processRunner = yield* ProcessRunner.ProcessRunner;
118 return yield* processRunner
119 .run({
120 command: input.command,
121 args: input.args,
122 timeout: "5 seconds",
123 timeoutBehavior: "timedOutResult",
124 })
125 .pipe(
126 Effect.map((result) => (result.code === 0 ? normalize(result.stdout) : null)),
127 Effect.catch(() => Effect.succeed(null)),
128 );
129});
130
131// IOKit's `product` node carries the marketing name ("Mac mini (2024)") on
132// Apple silicon; Intel Macs lack it, so `hw.model` ("Macmini8,1") is the
133// fallback. Both are single-digit-millisecond calls.
134const detectDarwinMachineKind = Effect.fn("detectDarwinMachineKind")(function* () {
135 const ioreg = yield* runProbe({ command: "ioreg", args: ["-rd1", "-n", "product"] });
136 const productName = ioreg?.match(/"product-name"\s*=\s*<"([^"]+)">/)?.[1] ?? null;
137 const fromProductName =
138 productName === null ? null : machineKindFromAppleProductName(productName);
139 if (fromProductName !== null) {
140 return fromProductName;
141 }
142 const model = yield* runProbe({ command: "sysctl", args: ["-n", "hw.model"] });
143 return model === null ? null : machineKindFromAppleProductName(model);
144});
145
146const detectLinuxMachineKind = Effect.fn("detectLinuxMachineKind")(function* () {
147 const [chassisType, sysVendor, productName] = yield* Effect.all([
148 readOptionalFile(`${DMI_ROOT}/chassis_type`),
149 readOptionalFile(`${DMI_ROOT}/sys_vendor`),
150 readOptionalFile(`${DMI_ROOT}/product_name`),
151 ]);
152 return machineKindFromDmi({ chassisType, sysVendor, productName });
153});
154
155export const detectServerEnvironmentMachineKind = Effect.fn("detectServerEnvironmentMachineKind")(
156 function* () {
157 const platform = yield* HostProcessPlatform;
158 switch (platform) {
159 case "darwin":
160 return yield* detectDarwinMachineKind();
161 case "linux":
162 return yield* detectLinuxMachineKind();
163 default:
164 return null;
165 }
166 },
167);