feat(environments): draw each environment as the machine it runs on (#9299)
Co-authored-by: Julius Marminge <[email protected]> Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
32 files changed
+1222
-84
No files matched your search
@@ -20,6 +20,7 @@ import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts";
|
||||
import * as ServerConfig from "../config.ts";
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import { resolveServerEnvironmentLabel } from "./ServerEnvironmentLabel.ts";
|
||||
import { detectServerEnvironmentMachineKind } from "./ServerEnvironmentMachine.ts";
|
||||
|
||||
export class ServerEnvironmentIdPersistenceError extends Schema.TaggedErrorClass<ServerEnvironmentIdPersistenceError>()(
|
||||
"ServerEnvironmentIdPersistenceError",
|
||||
@@ -188,6 +189,7 @@ export const make = Effect.gen(function* () {
|
||||
const environmentId = yield* identity.getEnvironmentId;
|
||||
const cwdBaseName = path.basename(serverConfig.cwd).trim();
|
||||
const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });
|
||||
const machine = yield* detectServerEnvironmentMachineKind();
|
||||
const launcher = yield* resolveServiceLauncherMode();
|
||||
const serverSelfUpdate = resolveServerSelfUpdateCapability({
|
||||
desktopManaged: serverConfig.mode === "desktop",
|
||||
@@ -206,6 +208,7 @@ export const make = Effect.gen(function* () {
|
||||
platform: {
|
||||
os: platformOs(hostPlatform),
|
||||
arch: platformArch(hostArchitecture),
|
||||
...(machine === null ? {} : { machine }),
|
||||
},
|
||||
serverVersion: packageJson.version,
|
||||
capabilities: {
|
||||
@@ -222,6 +225,7 @@ export const make = Effect.gen(function* () {
|
||||
threadPinReorder: true,
|
||||
threadTitleRegeneration: true,
|
||||
threadPullRequestLinking: true,
|
||||
environmentIcon: true,
|
||||
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
|
||||
...(serverSelfUpdate === "boot-service" || desktopAppUpdate
|
||||
? {
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
import { afterEach, describe, expect, it } from "@effect/vitest";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
import * as Layer from "effect/Layer";
|
||||
import * as PlatformError from "effect/PlatformError";
|
||||
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import { vi } from "vite-plus/test";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
import {
|
||||
detectServerEnvironmentMachineKind,
|
||||
machineKindFromAppleProductName,
|
||||
machineKindFromDmi,
|
||||
} from "./ServerEnvironmentMachine.ts";
|
||||
|
||||
const runMock = vi.fn<ProcessRunner.ProcessRunner["Service"]["run"]>();
|
||||
|
||||
const ProcessRunnerTest = Layer.succeed(
|
||||
ProcessRunner.ProcessRunner,
|
||||
ProcessRunner.ProcessRunner.of({ run: (input) => runMock(input) }),
|
||||
);
|
||||
|
||||
const processOutput = (stdout: string, code = 0) =>
|
||||
Effect.succeed({
|
||||
stdout,
|
||||
stderr: "",
|
||||
code: ChildProcessSpawner.ExitCode(code),
|
||||
timedOut: false,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
stdoutInvalidUtf8: false,
|
||||
stderrInvalidUtf8: false,
|
||||
});
|
||||
|
||||
const dmiFileSystem = (files: Readonly<Record<string, string>>) =>
|
||||
FileSystem.layerNoop({
|
||||
readFileString: (path) => {
|
||||
const name = path.slice(path.lastIndexOf("/") + 1);
|
||||
return name in files
|
||||
? Effect.succeed(files[name]!)
|
||||
: Effect.fail(
|
||||
PlatformError.systemError({
|
||||
_tag: "NotFound",
|
||||
module: "FileSystem",
|
||||
method: "readFileString",
|
||||
pathOrDescriptor: path,
|
||||
cause: new Error("ENOENT"),
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const withPlatform = (platform: NodeJS.Platform, fileSystem = FileSystem.layerNoop({})) =>
|
||||
Layer.mergeAll(ProcessRunnerTest, fileSystem, Layer.succeed(HostProcessPlatform, platform));
|
||||
|
||||
afterEach(() => {
|
||||
runMock.mockReset();
|
||||
});
|
||||
|
||||
describe("machineKindFromAppleProductName", () => {
|
||||
it("maps marketing names and model identifiers", () => {
|
||||
expect(machineKindFromAppleProductName("Mac mini (2024)")).toBe("mac-mini");
|
||||
expect(machineKindFromAppleProductName("Macmini8,1")).toBe("mac-mini");
|
||||
expect(machineKindFromAppleProductName("Mac Studio (2023)")).toBe("mac-studio");
|
||||
expect(machineKindFromAppleProductName("MacBook Pro (14-inch, 2024)")).toBe("laptop");
|
||||
expect(machineKindFromAppleProductName("MacBookAir10,1")).toBe("laptop");
|
||||
expect(machineKindFromAppleProductName("iMac (24-inch, 2024)")).toBe("desktop");
|
||||
expect(machineKindFromAppleProductName("Mac Pro (2023)")).toBe("desktop");
|
||||
});
|
||||
|
||||
it("returns null for Apple silicon model identifiers, which carry no product family", () => {
|
||||
expect(machineKindFromAppleProductName("Mac16,10")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("machineKindFromDmi", () => {
|
||||
it("prefers virtualization markers over chassis type", () => {
|
||||
expect(
|
||||
machineKindFromDmi({ chassisType: "1", sysVendor: "QEMU", productName: "Standard PC" }),
|
||||
).toBe("cloud");
|
||||
expect(
|
||||
machineKindFromDmi({
|
||||
chassisType: "3",
|
||||
sysVendor: "Microsoft Corporation",
|
||||
productName: "Virtual Machine",
|
||||
}),
|
||||
).toBe("cloud");
|
||||
expect(
|
||||
machineKindFromDmi({ chassisType: "1", sysVendor: "Amazon EC2", productName: "t3.large" }),
|
||||
).toBe("cloud");
|
||||
});
|
||||
|
||||
it("does not treat Microsoft hardware as a VM", () => {
|
||||
expect(
|
||||
machineKindFromDmi({
|
||||
chassisType: "9",
|
||||
sysVendor: "Microsoft Corporation",
|
||||
productName: "Surface Laptop 5",
|
||||
}),
|
||||
).toBe("laptop");
|
||||
});
|
||||
|
||||
it("maps SMBIOS chassis codes", () => {
|
||||
expect(
|
||||
machineKindFromDmi({ chassisType: "3", sysVendor: "GMKtec", productName: "NucBox K8 Plus" }),
|
||||
).toBe("desktop");
|
||||
expect(
|
||||
machineKindFromDmi({ chassisType: "10", sysVendor: "LENOVO", productName: "ThinkPad X1" }),
|
||||
).toBe("laptop");
|
||||
expect(
|
||||
machineKindFromDmi({ chassisType: "23", sysVendor: "Supermicro", productName: "X11" }),
|
||||
).toBe("server");
|
||||
expect(machineKindFromDmi({ chassisType: "1", sysVendor: null, productName: null })).toBeNull();
|
||||
expect(
|
||||
machineKindFromDmi({ chassisType: null, sysVendor: null, productName: null }),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("recognizes Apple hardware running Linux", () => {
|
||||
expect(
|
||||
machineKindFromDmi({ chassisType: "3", sysVendor: "Apple", productName: "Mac Studio" }),
|
||||
).toBe("mac-studio");
|
||||
});
|
||||
});
|
||||
|
||||
describe("detectServerEnvironmentMachineKind", () => {
|
||||
it.effect("reads the IOKit product name on macOS", () =>
|
||||
Effect.gen(function* () {
|
||||
runMock.mockReturnValueOnce(
|
||||
processOutput(
|
||||
'+-o product <class IOPlatformDevice>\n {\n "product-name" = <"Mac mini (2024)">\n }\n',
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* detectServerEnvironmentMachineKind().pipe(
|
||||
Effect.provide(withPlatform("darwin")),
|
||||
);
|
||||
|
||||
expect(result).toBe("mac-mini");
|
||||
expect(runMock).toHaveBeenCalledTimes(1);
|
||||
expect(runMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ command: "ioreg", args: ["-rd1", "-n", "product"] }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("falls back to hw.model when IOKit has no product node", () =>
|
||||
Effect.gen(function* () {
|
||||
runMock.mockReturnValueOnce(processOutput("", 1));
|
||||
runMock.mockReturnValueOnce(processOutput("MacBookPro16,1\n"));
|
||||
|
||||
const result = yield* detectServerEnvironmentMachineKind().pipe(
|
||||
Effect.provide(withPlatform("darwin")),
|
||||
);
|
||||
|
||||
expect(result).toBe("laptop");
|
||||
expect(runMock).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ command: "sysctl", args: ["-n", "hw.model"] }),
|
||||
);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns null when both macOS probes fail", () =>
|
||||
Effect.gen(function* () {
|
||||
runMock.mockImplementation((input) =>
|
||||
Effect.fail(
|
||||
new ProcessRunner.ProcessSpawnError({
|
||||
command: input.command,
|
||||
argumentCount: input.args.length,
|
||||
cause: new Error("ENOENT"),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const result = yield* detectServerEnvironmentMachineKind().pipe(
|
||||
Effect.provide(withPlatform("darwin")),
|
||||
);
|
||||
|
||||
expect(result).toBeNull();
|
||||
expect(runMock).toHaveBeenCalledTimes(2);
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("reads DMI on Linux", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* detectServerEnvironmentMachineKind().pipe(
|
||||
Effect.provide(
|
||||
withPlatform(
|
||||
"linux",
|
||||
dmiFileSystem({
|
||||
chassis_type: "3\n",
|
||||
sys_vendor: "GMKtec\n",
|
||||
product_name: "NucBox K8 Plus\n",
|
||||
}),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(result).toBe("desktop");
|
||||
expect(runMock).not.toHaveBeenCalled();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("returns null on Linux without DMI (containers, ARM boards)", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* detectServerEnvironmentMachineKind().pipe(
|
||||
Effect.provide(withPlatform("linux", dmiFileSystem({}))),
|
||||
);
|
||||
|
||||
expect(result).toBeNull();
|
||||
}),
|
||||
);
|
||||
|
||||
it.effect("skips detection on other platforms", () =>
|
||||
Effect.gen(function* () {
|
||||
const result = yield* detectServerEnvironmentMachineKind().pipe(
|
||||
Effect.provide(withPlatform("win32")),
|
||||
);
|
||||
|
||||
expect(result).toBeNull();
|
||||
expect(runMock).not.toHaveBeenCalled();
|
||||
}),
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,167 @@
|
||||
import type { EnvironmentMachineKind } from "@t3tools/contracts";
|
||||
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
|
||||
import * as Effect from "effect/Effect";
|
||||
import * as FileSystem from "effect/FileSystem";
|
||||
|
||||
import * as ProcessRunner from "../processRunner.ts";
|
||||
|
||||
/**
|
||||
* Best-effort hardware detection for the environment icon. Every probe is
|
||||
* allowed to fail: a null result means "no signal", and the client draws a
|
||||
* generic server until the user picks something in Settings → Connections.
|
||||
*/
|
||||
|
||||
const DMI_ROOT = "/sys/class/dmi/id";
|
||||
|
||||
// SMBIOS 3.x System Enclosure types (table 17). Codes that describe a shape
|
||||
// rather than a machine (docking stations, blades enclosures, IoT gateways)
|
||||
// fall through to null on purpose.
|
||||
const DMI_CHASSIS_KINDS: Readonly<Record<string, EnvironmentMachineKind>> = {
|
||||
"3": "desktop", // Desktop
|
||||
"4": "desktop", // Low Profile Desktop
|
||||
"5": "desktop", // Pizza Box
|
||||
"6": "desktop", // Mini Tower
|
||||
"7": "desktop", // Tower
|
||||
"8": "laptop", // Portable
|
||||
"9": "laptop", // Laptop
|
||||
"10": "laptop", // Notebook
|
||||
"13": "desktop", // All in One
|
||||
"14": "laptop", // Sub Notebook
|
||||
"15": "desktop", // Space-saving
|
||||
"16": "desktop", // Lunch Box
|
||||
"17": "server", // Main Server Chassis
|
||||
"18": "server", // Expansion Chassis
|
||||
"19": "server", // SubChassis
|
||||
"20": "server", // Bus Expansion Chassis
|
||||
"21": "server", // Peripheral Chassis
|
||||
"22": "server", // RAID Chassis
|
||||
"23": "server", // Rack Mount Chassis
|
||||
"24": "server", // Sealed-case PC
|
||||
"28": "server", // Blade
|
||||
"31": "laptop", // Convertible
|
||||
"32": "laptop", // Detachable
|
||||
"35": "desktop", // Mini PC
|
||||
};
|
||||
|
||||
// Hypervisors and cloud providers write themselves into the DMI vendor or
|
||||
// product strings; any hit means the box is a VM, and a VM reads as "cloud"
|
||||
// regardless of the chassis type the hypervisor fakes. Hyper-V is matched on
|
||||
// its "Virtual Machine" product, not the "Microsoft Corporation" vendor that
|
||||
// physical Surface devices share.
|
||||
const VIRTUALIZATION_MARKERS = [
|
||||
"qemu",
|
||||
"kvm",
|
||||
"bochs",
|
||||
"vmware",
|
||||
"virtualbox",
|
||||
"innotek",
|
||||
"xen",
|
||||
"parallels",
|
||||
"amazon ec2",
|
||||
"google compute engine",
|
||||
"digitalocean",
|
||||
"hetzner",
|
||||
"linode",
|
||||
"vultr",
|
||||
"scaleway",
|
||||
"openstack",
|
||||
"cloud",
|
||||
"virtual machine",
|
||||
];
|
||||
|
||||
function normalize(value: string | null | undefined): string | null {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed && trimmed.length > 0 ? trimmed : null;
|
||||
}
|
||||
|
||||
/** Marketing names and Intel-era model identifiers share these prefixes. */
|
||||
export function machineKindFromAppleProductName(name: string): EnvironmentMachineKind | null {
|
||||
const normalized = name.trim().toLowerCase().replaceAll(/\s+/g, "");
|
||||
if (normalized.startsWith("macmini")) return "mac-mini";
|
||||
if (normalized.startsWith("macstudio")) return "mac-studio";
|
||||
if (normalized.startsWith("macbook")) return "laptop";
|
||||
if (normalized.startsWith("imac") || normalized.startsWith("macpro")) return "desktop";
|
||||
return null;
|
||||
}
|
||||
|
||||
export function machineKindFromDmi(input: {
|
||||
readonly chassisType: string | null;
|
||||
readonly sysVendor: string | null;
|
||||
readonly productName: string | null;
|
||||
}): EnvironmentMachineKind | null {
|
||||
const productName = input.productName ?? "";
|
||||
const vendorAndProduct = `${input.sysVendor ?? ""} ${productName}`.toLowerCase();
|
||||
if (VIRTUALIZATION_MARKERS.some((marker) => vendorAndProduct.includes(marker))) {
|
||||
return "cloud";
|
||||
}
|
||||
// Apple hardware booting Linux (Asahi) still reports the Apple product name.
|
||||
const appleKind = machineKindFromAppleProductName(productName);
|
||||
if (appleKind !== null) {
|
||||
return appleKind;
|
||||
}
|
||||
return input.chassisType === null ? null : (DMI_CHASSIS_KINDS[input.chassisType] ?? null);
|
||||
}
|
||||
|
||||
const readOptionalFile = Effect.fn("readOptionalFile")(function* (path: string) {
|
||||
const fileSystem = yield* FileSystem.FileSystem;
|
||||
return yield* fileSystem.readFileString(path).pipe(
|
||||
Effect.map(normalize),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
);
|
||||
});
|
||||
|
||||
const runProbe = Effect.fn("runMachineProbe")(function* (input: {
|
||||
readonly command: string;
|
||||
readonly args: ReadonlyArray<string>;
|
||||
}) {
|
||||
const processRunner = yield* ProcessRunner.ProcessRunner;
|
||||
return yield* processRunner
|
||||
.run({
|
||||
command: input.command,
|
||||
args: input.args,
|
||||
timeout: "5 seconds",
|
||||
timeoutBehavior: "timedOutResult",
|
||||
})
|
||||
.pipe(
|
||||
Effect.map((result) => (result.code === 0 ? normalize(result.stdout) : null)),
|
||||
Effect.catch(() => Effect.succeed(null)),
|
||||
);
|
||||
});
|
||||
|
||||
// IOKit's `product` node carries the marketing name ("Mac mini (2024)") on
|
||||
// Apple silicon; Intel Macs lack it, so `hw.model` ("Macmini8,1") is the
|
||||
// fallback. Both are single-digit-millisecond calls.
|
||||
const detectDarwinMachineKind = Effect.fn("detectDarwinMachineKind")(function* () {
|
||||
const ioreg = yield* runProbe({ command: "ioreg", args: ["-rd1", "-n", "product"] });
|
||||
const productName = ioreg?.match(/"product-name"\s*=\s*<"([^"]+)">/)?.[1] ?? null;
|
||||
const fromProductName =
|
||||
productName === null ? null : machineKindFromAppleProductName(productName);
|
||||
if (fromProductName !== null) {
|
||||
return fromProductName;
|
||||
}
|
||||
const model = yield* runProbe({ command: "sysctl", args: ["-n", "hw.model"] });
|
||||
return model === null ? null : machineKindFromAppleProductName(model);
|
||||
});
|
||||
|
||||
const detectLinuxMachineKind = Effect.fn("detectLinuxMachineKind")(function* () {
|
||||
const [chassisType, sysVendor, productName] = yield* Effect.all([
|
||||
readOptionalFile(`${DMI_ROOT}/chassis_type`),
|
||||
readOptionalFile(`${DMI_ROOT}/sys_vendor`),
|
||||
readOptionalFile(`${DMI_ROOT}/product_name`),
|
||||
]);
|
||||
return machineKindFromDmi({ chassisType, sysVendor, productName });
|
||||
});
|
||||
|
||||
export const detectServerEnvironmentMachineKind = Effect.fn("detectServerEnvironmentMachineKind")(
|
||||
function* () {
|
||||
const platform = yield* HostProcessPlatform;
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return yield* detectDarwinMachineKind();
|
||||
case "linux":
|
||||
return yield* detectLinuxMachineKind();
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
},
|
||||
);
|
||||
Reference in new issue
Block a user