Skip to content

Commit 5c5fa5f

Browse files
feat(devices): show installed and running tool versions per host (pingdotgg#12816)
1 parent 6cc7f70 commit 5c5fa5f

14 files changed

Lines changed: 349 additions & 21 deletions

File tree

‎apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsx‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { deviceToolVersionLabels } from "@t3tools/client-runtime/state/device";
12
import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";
23
import { createNativeStackNavigator } from "@react-navigation/native-stack";
34
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
@@ -116,6 +117,18 @@ function DevicePreviewScreen({
116117
};
117118

118119
const controls: ScreenHeaderMenuItem[] = [
120+
{
121+
id: "device-tools",
122+
title: "Device tool versions",
123+
icon: "info.circle",
124+
onPress: () =>
125+
Alert.alert(
126+
"Device tool versions",
127+
deviceToolVersionLabels(
128+
state.data?.hosts.find((host) => host.id === preview?.session.hostId)?.tools,
129+
).join("\n"),
130+
),
131+
},
119132
{
120133
id: "reload",
121134
title: "Reload stream",

‎apps/server/src/device/DeviceToolchain.test.ts‎

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as PlatformError from "effect/PlatformError";
12
import { expect, it } from "@effect/vitest";
23
import * as NodeServices from "@effect/platform-node/NodeServices";
34
import * as Effect from "effect/Effect";
@@ -6,7 +7,12 @@ import * as Path from "effect/Path";
67
import * as ChildProcessSpawner from "effect/unstable/process/ChildProcessSpawner";
78

89
import * as ProcessRunner from "../processRunner.ts";
9-
import { ensureDeviceHub, isDeviceHubInstalled } from "./DeviceToolchain.ts";
10+
import {
11+
deviceToolVersions,
12+
DEVICE_HUB_VERSION,
13+
ensureDeviceHub,
14+
isDeviceHubInstalled,
15+
} from "./DeviceToolchain.ts";
1016

1117
it.effect("failed installation cleans staging and exposes only a safe failure message", () =>
1218
Effect.gen(function* () {
@@ -37,3 +43,57 @@ it.effect("failed installation cleans staging and exposes only a safe failure me
3743
expect(yield* fs.readDirectory(path.join(baseDir, "tools", "expo-device-hub"))).toEqual([]);
3844
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
3945
);
46+
47+
it.effect("inventory reports only completed versions without installing the required version", () =>
48+
Effect.gen(function* () {
49+
const fs = yield* FileSystem.FileSystem;
50+
const path = yield* Path.Path;
51+
const base = yield* fs.makeTempDirectoryScoped();
52+
for (const [version, sentinel] of [
53+
["0.9.0", "0.9.0"],
54+
[DEVICE_HUB_VERSION, "wrong"],
55+
[".staging-123", ".staging-123"],
56+
]) {
57+
const dir = path.join(base, "tools", "expo-device-hub", version!);
58+
yield* fs.makeDirectory(path.join(dir, "node_modules/expo-device-hub/dist/server"), {
59+
recursive: true,
60+
});
61+
yield* fs.writeFileString(
62+
path.join(dir, "node_modules/expo-device-hub/dist/server/cli.mjs"),
63+
"",
64+
);
65+
yield* fs.writeFileString(path.join(dir, ".install-complete"), sentinel!);
66+
}
67+
const tools = yield* deviceToolVersions(base);
68+
expect(tools?.hub).toEqual({
69+
requiredVersion: DEVICE_HUB_VERSION,
70+
installedVersions: ["0.9.0"],
71+
runningVersion: null,
72+
});
73+
expect(tools?.agent.installedVersions).toEqual([]);
74+
expect(yield* isDeviceHubInstalled(base)).toBe(false);
75+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
76+
);
77+
78+
it.effect("unreadable inventory stays unknown instead of reporting no installs", () =>
79+
Effect.gen(function* () {
80+
const tools = yield* deviceToolVersions("/unreadable");
81+
expect(tools).toBeUndefined();
82+
}).pipe(
83+
Effect.provideService(
84+
FileSystem.FileSystem,
85+
FileSystem.makeNoop({
86+
readDirectory: () =>
87+
Effect.fail(
88+
PlatformError.systemError({
89+
_tag: "PermissionDenied",
90+
module: "FileSystem",
91+
method: "readDirectory",
92+
description: "denied",
93+
}),
94+
),
95+
}),
96+
),
97+
Effect.provide(NodeServices.layer),
98+
),
99+
);

‎apps/server/src/device/DeviceToolchain.ts‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { DeviceToolVersions } from "@t3tools/contracts";
12
/**
23
* Pinned installs of the two external tools device support is built on.
34
*
@@ -221,3 +222,46 @@ export const isDeviceHubInstalled = (baseDir: string) =>
221222

222223
export const isAgentDeviceInstalled = (baseDir: string) =>
223224
isToolInstalled(baseDir, AGENT_DEVICE_SPEC, (paths) => paths.agentDevice);
225+
226+
/** Read completed installs without downloading or starting either tool. */
227+
export const deviceToolVersions = Effect.fn("DeviceToolchain.versions")(function* (
228+
baseDir: string,
229+
running: { hub?: string; agent?: string } = {},
230+
) {
231+
const fs = yield* FileSystem.FileSystem;
232+
const path = yield* Path.Path;
233+
const inspect = Effect.fn("DeviceToolchain.inspect")(function* (spec: ToolSpec) {
234+
const directory = path.join(baseDir, "tools", spec.name);
235+
const names = yield* fs.readDirectory(directory).pipe(
236+
Effect.catchIf(
237+
(error) => error.reason._tag === "NotFound",
238+
() => Effect.succeed([]),
239+
),
240+
);
241+
const versions = yield* Effect.filter(names, (version) =>
242+
/^[0-9]+\.[0-9]+\.[0-9]+(?:-[a-zA-Z0-9.-]+)?$/.test(version)
243+
? Effect.gen(function* () {
244+
const paths = toolPaths(path, baseDir, { ...spec, version });
245+
const sentinel = yield* fs.readFileString(paths.sentinelPath).pipe(
246+
Effect.catchIf(
247+
(error) => error.reason._tag === "NotFound",
248+
() => Effect.succeed(null),
249+
),
250+
);
251+
return sentinel?.trim() === version && (yield* fs.exists(paths.entryPath));
252+
})
253+
: Effect.succeed(false),
254+
);
255+
return {
256+
requiredVersion: spec.version,
257+
installedVersions: versions.sort(),
258+
runningVersion: (spec.name === DEVICE_HUB_PACKAGE ? running.hub : running.agent) ?? null,
259+
};
260+
});
261+
return yield* Effect.gen(function* () {
262+
return {
263+
hub: yield* inspect(HUB_SPEC),
264+
agent: yield* inspect(AGENT_DEVICE_SPEC),
265+
} satisfies DeviceToolVersions;
266+
}).pipe(Effect.orElseSucceed(() => undefined));
267+
});

‎apps/server/src/device/LocalDeviceHost.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import * as Exit from "effect/Exit";
3131
import * as FileSystem from "effect/FileSystem";
3232
import * as Layer from "effect/Layer";
3333
import * as Path from "effect/Path";
34+
import * as Option from "effect/Option";
3435
import * as Ref from "effect/Ref";
3536
import * as Schema from "effect/Schema";
3637
import * as Scope from "effect/Scope";
@@ -50,6 +51,8 @@ import {
5051
ensureDeviceHub,
5152
isAgentDeviceInstalled,
5253
isDeviceHubInstalled,
54+
deviceToolVersions,
55+
DEVICE_HUB_VERSION,
5356
} from "./DeviceToolchain.ts";
5457

5558
const HUB_READY_TIMEOUT_MS = 30_000;
@@ -76,6 +79,7 @@ const AgentDeviceDaemonFile = Schema.Struct({
7679
httpPort: Schema.Int,
7780
token: Schema.String,
7881
pid: Schema.optional(Schema.Int),
82+
version: Schema.optional(Schema.String),
7983
});
8084
const decodeDaemonFile = Schema.decodeUnknownEffect(Schema.fromJsonString(AgentDeviceDaemonFile));
8185

@@ -232,7 +236,26 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
232236
Effect.provideService(Path.Path, path),
233237
),
234238
]);
239+
const running = yield* Ref.get(runningRef);
240+
const daemon = running?.agentDevice
241+
? yield* readDaemonFile().pipe(Effect.option)
242+
: Option.none();
243+
const hubAlive = running
244+
? yield* running.hub.child.isRunning.pipe(Effect.orElseSucceed(() => false))
245+
: false;
246+
const agentAlive =
247+
Option.isSome(daemon) && daemon.value.pid ? yield* isProcessAlive(daemon.value.pid) : false;
248+
const tools = yield* deviceToolVersions(config.baseDir, {
249+
...(hubAlive ? { hub: DEVICE_HUB_VERSION } : {}),
250+
...(agentAlive && Option.isSome(daemon) && daemon.value.version
251+
? { agent: daemon.value.version }
252+
: {}),
253+
}).pipe(
254+
Effect.provideService(FileSystem.FileSystem, fs),
255+
Effect.provideService(Path.Path, path),
256+
);
235257
return {
258+
tools,
236259
id: hostId,
237260
kind: "local",
238261
label: "This machine",

‎apps/server/src/device/SshDeviceHost.test.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ it.effect("preserves installed status after probes and cleans failed agent activ
2020
const fs = yield* FileSystem.FileSystem;
2121
const home = yield* fs.makeTempDirectoryScoped();
2222
const modes: string[] = [];
23+
const owners: string[] = [];
2324
let forwards = 0;
2425
let failForward = true;
2526
let rejectConfig = true;
@@ -62,6 +63,7 @@ it.effect("preserves installed status after probes and cleans failed agent activ
6263
);
6364
const mode = /const mode = "([^"]+)"/.exec(script)?.[1] ?? "";
6465
modes.push(mode);
66+
owners.push(/const owner = "([^"]+)"/.exec(script)?.[1] ?? "");
6567
output = JSON.stringify({
6668
nodePath: "/node",
6769
platforms: [{ platform: "ios", available: true }],
@@ -110,6 +112,12 @@ it.effect("preserves installed status after probes and cleans failed agent activ
110112
),
111113
);
112114
yield* host.ensureReady(() => Effect.void);
115+
yield* SshDeviceHost.probe({ id: "test", label: "Test", target: "test.example" }).pipe(
116+
Effect.provide(ServerConfig.layerTest(home, home)),
117+
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
118+
);
119+
expect(new Set(owners).size).toBe(1);
120+
expect(owners[0]).toMatch(/^[a-f0-9]{24}$/);
113121
expect(forwards).toBe(1);
114122
expect(modes.filter((mode) => mode === "start")).toHaveLength(2);
115123
yield* host.platformAvailability("ios");

‎apps/server/src/device/SshDeviceHost.ts‎

Lines changed: 31 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import * as NodeCrypto from "node:crypto";
22
import {
33
type DeviceHostSummary,
44
DevicePlatformAvailability,
5+
DeviceToolVersions,
56
type SshDeviceHostConfig,
67
} from "@t3tools/contracts";
78
import { runSshCommand, baseSshArgs, resolveSshCommand } from "@t3tools/ssh/command";
@@ -24,6 +25,7 @@ import { quoteRemoteArg, remoteDeviceEnvironment, remoteDeviceScript } from "./s
2425

2526
const Probe = Schema.Struct({
2627
nodePath: Schema.String,
28+
tools: Schema.optional(DeviceToolVersions),
2729
platforms: Schema.Array(DevicePlatformAvailability),
2830
});
2931
const Started = Schema.Struct({
@@ -70,8 +72,23 @@ const bootstrap = (
7072
),
7173
);
7274

73-
export const probe = Effect.fn("SshDeviceHost.probe")(function* (config: SshDeviceHostConfig) {
74-
const result = yield* bootstrap(config, "probe", "probe");
75+
const ownerFor = Effect.fn("SshDeviceHost.ownerFor")(function* (hostId: string) {
76+
const fs = yield* FileSystem.FileSystem;
77+
const server = yield* ServerConfig.ServerConfig;
78+
const environmentId = yield* fs
79+
.readFileString(server.environmentIdPath)
80+
.pipe(Effect.orElseSucceed(() => server.stateDir));
81+
return NodeCrypto.createHash("sha256")
82+
.update(`${environmentId}\0${server.stateDir}\0${hostId}`)
83+
.digest("hex")
84+
.slice(0, 24);
85+
});
86+
87+
export const probe = Effect.fn("SshDeviceHost.probe")(function* (
88+
config: SshDeviceHostConfig,
89+
owner?: string,
90+
) {
91+
const result = yield* bootstrap(config, owner ?? (yield* ownerFor(config.id)), "probe");
7592
const value = yield* decodeProbe(result.stdout.trim()).pipe(
7693
Effect.mapError(
7794
(cause) =>
@@ -82,8 +99,11 @@ export const probe = Effect.fn("SshDeviceHost.probe")(function* (config: SshDevi
8299
id: config.id,
83100
label: config.label,
84101
kind: "ssh",
85-
hubInstalled: false,
86-
agentDeviceInstalled: false,
102+
tools: value.tools,
103+
hubInstalled:
104+
value.tools?.hub.installedVersions.includes(value.tools.hub.requiredVersion) ?? false,
105+
agentDeviceInstalled:
106+
value.tools?.agent.installedVersions.includes(value.tools.agent.requiredVersion) ?? false,
87107
platforms: value.platforms,
88108
} satisfies DeviceHostSummary;
89109
});
@@ -106,23 +126,21 @@ export const make = Effect.fn("SshDeviceHost.make")(function* (
106126
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
107127
const parentScope = yield* Scope.Scope;
108128
const ssh = yield* resolveSshCommand;
109-
const environmentId = yield* fs
110-
.readFileString(server.environmentIdPath)
111-
.pipe(Effect.orElseSucceed(() => server.stateDir));
112-
const owner = NodeCrypto.createHash("sha256")
113-
.update(`${environmentId}\0${server.stateDir}\0${config.id}`)
114-
.digest("hex")
115-
.slice(0, 24);
129+
const owner = yield* ownerFor(config.id);
116130
const provide = <A, E>(
117131
effect: Effect.Effect<
118132
A,
119133
E,
120-
FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner
134+
| FileSystem.FileSystem
135+
| Path.Path
136+
| ChildProcessSpawner.ChildProcessSpawner
137+
| ServerConfig.ServerConfig
121138
>,
122139
) =>
123140
effect.pipe(
124141
Effect.provideService(FileSystem.FileSystem, fs),
125142
Effect.provideService(Path.Path, path),
143+
Effect.provideService(ServerConfig.ServerConfig, server),
126144
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
127145
);
128146
const lock = yield* Semaphore.make(1);
@@ -183,6 +201,7 @@ export const make = Effect.fn("SshDeviceHost.make")(function* (
183201
summary = {
184202
...summary,
185203
platforms: remote.platforms,
204+
tools: remote.tools,
186205
hubInstalled: true,
187206
agentDeviceInstalled: wantsAgent || summary.agentDeviceInstalled,
188207
};

‎apps/server/src/device/sshDeviceScript.test.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -83,15 +83,16 @@ const state=process.env.AGENT_DEVICE_STATE_DIR || args[args.indexOf('--state-dir
8383
const file=path.join(state,'daemon.json');
8484
if(args[0]==='daemon') { const data=JSON.parse(fs.readFileSync(file,'utf8')); fs.writeFileSync(path.join(state,'stopped-agent'),String(data.pid)); try {process.kill(data.pid,'SIGTERM')} catch {} }
8585
else if(args[0]==='serve') { const server=http.createServer((req,res)=>{res.statusCode=fs.existsSync(path.join(state,'unhealthy-agent-'+process.pid))?503:200;res.end('ok');}); server.listen(0,'127.0.0.1',()=>{fs.writeFileSync(file,JSON.stringify({httpPort:server.address().port,pid:process.pid,token:'test'}));process.send?.('ready');process.disconnect?.();}); }
86-
else { const child=spawn(process.execPath,[process.argv[1],'serve'],{detached:true,stdio:['ignore','ignore','ignore','ipc'],env:process.env});await new Promise((resolve,reject)=>{child.once('message',resolve);child.once('error',reject);});child.unref(); }
86+
else { const child=spawn(process.execPath,[path.join(path.dirname(process.argv[1]),'daemon.mjs'),'serve'],{detached:true,stdio:['ignore','ignore','ignore','ipc'],env:process.env});await new Promise((resolve,reject)=>{child.once('message',resolve);child.once('error',reject);});child.unref(); }
8787
`,
8888
);
89+
await NodeFSP.copyFile(agent, NodePath.join(NodePath.dirname(agent), "daemon.mjs"));
8990
const nextHubVersion = DEVICE_HUB_VERSION + "-upgrade";
9091
const nextAgentVersion = AGENT_DEVICE_VERSION + "-upgrade";
9192
let invocation = 0;
9293
const invoke = async (
9394
owner: string,
94-
mode: "start" | "agent-start" | "stop-agent" | "stop",
95+
mode: "probe" | "start" | "agent-start" | "stop-agent" | "stop",
9596
upgraded = false,
9697
) => {
9798
const file = NodePath.join(home, `${owner}-${mode}-${invocation++}.cjs`);
@@ -107,14 +108,19 @@ else { const child=spawn(process.execPath,[process.argv[1],'serve'],{detached:tr
107108
});
108109
return result.stdout ? JSON.parse(result.stdout) : null;
109110
};
111+
const inventory = await invoke("one", "probe");
112+
expect(inventory.tools.hub.installedVersions).toEqual([DEVICE_HUB_VERSION]);
113+
expect(inventory.tools.hub.runningVersion).toBeNull();
114+
expect(inventory.tools.agent.installedVersions).toEqual([AGENT_DEVICE_VERSION]);
115+
await expect(NodeFSP.stat(NodePath.join(root, "hosts/one/hub.json"))).rejects.toThrow();
110116
const template = NodePath.join(home, "hub-template");
111117
await NodeFSP.cp(hubDir, template, { recursive: true });
112118
await NodeFSP.rm(NodePath.join(hubDir, ".install-complete"));
113119
const installLock = hubDir + ".lock";
114120
await NodeFSP.symlink("2147483647:exited-installer", installLock);
115121
await NodeFSP.writeFile(
116122
NodePath.join(bin, "npm"),
117-
`#!${process.execPath}\nconst fs=require('node:fs');const args=process.argv.slice(2);fs.cpSync(${JSON.stringify(template)},args[args.indexOf('--prefix')+1],{recursive:true});`,
123+
`#!${process.execPath}\nconst fs=require('node:fs');const args=process.argv.slice(2);if(args[0]==='--version'){console.log('10.0.0');process.exit(0);}fs.cpSync(${JSON.stringify(template)},args[args.indexOf('--prefix')+1],{recursive:true});`,
118124
{ mode: 0o755 },
119125
);
120126
await NodeFSP.mkdir(NodePath.join(root, "hosts/one"), { recursive: true });
@@ -135,6 +141,9 @@ else { const child=spawn(process.execPath,[process.argv[1],'serve'],{detached:tr
135141
]);
136142
expect(concurrentAgent.hubPort).toBe(first.hubPort);
137143
expect(concurrentAgent.daemonPort).toBe(first.daemonPort);
144+
const running = await invoke("one", "probe");
145+
expect(running.tools.hub.runningVersion).toBe(DEVICE_HUB_VERSION);
146+
expect(running.tools.agent.runningVersion).toBe(AGENT_DEVICE_VERSION);
138147
const second = await invoke("two", "agent-start");
139148
const reused = await invoke("one", "agent-start");
140149
expect(reused.hubPort).toBe(first.hubPort);

0 commit comments

Comments
 (0)