TypeScript
feat(devices): add read-only update discovery and remote ownership (#12818)
Julius Marminge61b25b88d792
diff --git a/apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsx b/apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsxindex 9af958c82b7..8d2a6700005 100644--- a/apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsx+++ b/apps/mobile/src/features/devices/DevicePreviewRouteScreen.tsx@@ -1,4 +1,8 @@-import { deviceToolVersionLabels } from "@t3tools/client-runtime/state/device";+import {+ deviceToolVersionLabels,+ deviceToolUpdateOwnership,+ deviceToolUpdatePolicy,+} from "@t3tools/client-runtime/state/device";import { useIsFocused, useNavigation, type StaticScreenProps } from "@react-navigation/native";import { createNativeStackNavigator } from "@react-navigation/native-stack";import { EnvironmentId, ThreadId } from "@t3tools/contracts";@@ -131,6 +135,18 @@ function DevicePreviewScreen({void retryHost({ environmentId, input: { retryHostId: host.id } });},})) ?? []),+ ...(state.data?.supportsToolInspection+ ? [+ {+ id: "check-device-tools",+ title: "Check device tool versions",+ icon: "arrow.clockwise" as const,+ onPress: () => {+ void retryHost({ environmentId, input: { inspectOnly: true } });+ },+ },+ ]+ : []),{id: "device-tools",title: "Device tool versions",@@ -138,17 +154,26 @@ function DevicePreviewScreen({onPress: () =>Alert.alert("Device tool versions",- deviceToolVersionLabels(- state.data?.hosts.find((host) => host.id === preview?.session.hostId)?.tools,- ).join("\n") ++ deviceToolUpdateOwnership ++ "\n\n" ++ deviceToolUpdatePolicy(+ state.data?.hosts.find((host) => host.id === preview?.session.hostId)?.tools,+ ) ++ "\n\n" ++ deviceToolVersionLabels(+ state.data?.hosts.find((host) => host.id === preview?.session.hostId)?.tools,+ ).join("\n") +"\n" +- (state.data?.hostStatuses[preview?.session.hostId ?? ""]?.detail ?? ""),+ (state.data?.hosts.find((host) => host.id === preview?.session.hostId)+ ?.toolInspectionError ??+ state.data?.hostStatuses[preview?.session.hostId ?? ""]?.detail ??+ ""),),},{id: "reload",title: "Reload stream",- icon: "arrow.clockwise",+ icon: "arrow.clockwise" as const,disabled: !preview || shuttingDown,onPress: () => {setInputConnected(false);@@ -178,7 +203,7 @@ function DevicePreviewScreen({{id: "rotate",title: "Rotate device",- icon: "arrow.clockwise",+ icon: "arrow.clockwise" as const,disabled: !inputConnected,onPress: () => streamRef.current?.rotate(),},diff --git a/apps/server/src/device/DeviceHost.ts b/apps/server/src/device/DeviceHost.tsindex 0aa784b7149..14537985b9b 100644--- a/apps/server/src/device/DeviceHost.ts+++ b/apps/server/src/device/DeviceHost.ts@@ -80,6 +80,7 @@ export class DeviceHost extends Context.Service<{readonly id: DeviceHostId;readonly summary: Effect.Effect<DeviceHostSummary>;+ readonly inspect?: Effect.Effect<DeviceHostSummary, DeviceHostError>;readonly platformAvailability: (platform: DevicePlatform,) => Effect.Effect<DevicePlatformAvailability>;diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.tsindex b3ff08aea1c..ce57c724f8b 100644--- a/apps/server/src/device/DeviceService.test.ts+++ b/apps/server/src/device/DeviceService.test.ts@@ -67,6 +67,7 @@ const fixture = Effect.fn("fixture")(function* (bootError?: string,failListAfterShutdown = false,runtimeFailure?: NodeRuntimeUnavailableError | DeviceHost.DeviceHostError,+ inspectError = false,) {const settings = yield* Ref.make(DEFAULT_SERVER_SETTINGS);const starts: string[] = [];@@ -82,6 +83,17 @@ const fixture = Effect.fn("fixture")(function* (run: () => Effect.succeed({ code: 0, stdout: "Pixel_API_35\n", stderr: "" }),};const host: DeviceHost.DeviceHost["Service"] = {+ ...(inspectError+ ? {+ inspect: Effect.fail(+ new DeviceHost.DeviceHostError({+ hostId: LOCAL_DEVICE_HOST_ID,+ step: "probe",+ cause: new Error("offline"),+ }),+ ),+ }+ : {}),id: LOCAL_DEVICE_HOST_ID,summary: Effect.succeed({id: LOCAL_DEVICE_HOST_ID,@@ -623,3 +635,28 @@ it.effect("host retry exposes actionable failure without internal IDs or diagnos});}).pipe(Effect.scoped),);++it.effect("version discovery does not grant consent or start device tools", () =>+ Effect.gen(function* () {+ const { service, starts, agentStarts, requests } = yield* fixture();+ const state = yield* service.inspect;+ expect(state.supportsToolInspection).toBe(true);+ expect(state.hostStatus).toBe("disabled");+ expect(state.hosts).toHaveLength(1);+ expect(starts).toEqual([]);+ expect(agentStarts).toEqual([]);+ expect(requests).toEqual([]);+ }).pipe(Effect.scoped),+);++it.effect("failed read-only discovery preserves lifecycle status and installed inventory", () =>+ Effect.gen(function* () {+ const { service, starts } = yield* fixture(Effect.void, undefined, false, undefined, true);+ const state = yield* service.inspect;+ expect(state.supportsToolInspection).toBe(true);+ expect(state.hostStatus).toBe("disabled");+ expect(state.hosts[0]?.hubInstalled).toBe(true);+ expect(state.hosts[0]?.toolInspectionError).toContain("Reconnect the host");+ expect(starts).toEqual([]);+ }).pipe(Effect.scoped),+);diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.tsindex bb06ef66731..ddbe07ad9de 100644--- a/apps/server/src/device/DeviceService.ts+++ b/apps/server/src/device/DeviceService.ts@@ -126,6 +126,7 @@ export class DeviceService extends Context.Service<) => Effect.Effect<DeviceServiceState, DeviceError>;/** Refreshes devices only after device support has been enabled. */readonly list: Effect.Effect<DeviceServiceState, DeviceError>;+ readonly inspect: Effect.Effect<DeviceServiceState>;readonly retryHost: (hostId: DeviceHostId) => Effect.Effect<DeviceServiceState, DeviceError>;readonly open: (input: DeviceOpenInput) => Effect.Effect<DeviceSession, DeviceError>;readonly close: (input: DeviceCloseInput) => Effect.Effect<void, DeviceError>;@@ -204,6 +205,7 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*const stateRef = yield* SynchronizedRef.make<ServiceState>({state: {supportsHostRetry: true,+ supportsToolInspection: true,hosts: initialHosts,hostStatus: initialSettings.enabled ? "idle" : "disabled",hostStatuses: {},@@ -465,6 +467,38 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*return (yield* SynchronizedRef.get(stateRef)).state;}).pipe(Effect.withSpan("DeviceService.list"));+ const inspect = Effect.gen(function* () {+ yield* Effect.forEach(+ hosts.values(),+ (host) =>+ Effect.gen(function* () {+ const result = yield* (host.inspect ?? host.summary).pipe(Effect.result);+ if (hosts.get(host.id) !== host) return;+ if (result._tag === "Failure") {+ yield* publish((state) => ({+ ...state,+ hosts: state.hosts.map((value) =>+ value.id === host.id+ ? {+ ...value,+ toolInspectionError:+ "Cannot check versions. Reconnect the host and check again. Installed tools have not been changed.",+ }+ : value,+ ),+ }));+ return;+ }+ yield* publish((state) => ({+ ...state,+ hosts: state.hosts.map((value) => (value.id === host.id ? result.success : value)),+ }));+ }),+ { concurrency: 4 },+ );+ return (yield* SynchronizedRef.get(stateRef)).state;+ });+const retryHost: DeviceService["Service"]["retryHost"] = Effect.fn("DeviceService.retryHost")(function* (hostId) {yield* resolveHost(hostId);@@ -866,6 +900,7 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*...DeviceService.of({testHost,retryHost,+ inspect,agentCli: Effect.fail(new DeviceHostUnavailableError({hostId: LOCAL_DEVICE_HOST_ID,diff --git a/apps/server/src/device/SshDeviceHost.ts b/apps/server/src/device/SshDeviceHost.tsindex 9ac2fa2580f..4ed6d740215 100644--- a/apps/server/src/device/SshDeviceHost.ts+++ b/apps/server/src/device/SshDeviceHost.ts@@ -371,7 +371,7 @@ export const make = Effect.fn("SshDeviceHost.make")(function* (Effect.gen(function* () {stopped = false;if (ready) return ready;- summary = yield* provide(probe(config));+ summary = yield* provide(probe(config, owner));yield* onPhase(summary.hubInstalled ? "starting" : "installing",summary.hubInstalled@@ -424,6 +424,13 @@ export const make = Effect.fn("SshDeviceHost.make")(function* (return {id: config.id,summary: Effect.sync(() => summary),+ inspect: provide(probe(config, owner)).pipe(+ Effect.tap((value) =>+ Effect.sync(() => {+ summary = value;+ }),+ ),+ ),current: Effect.sync(() => ready),ensureReady,ensureAgentReady: (onPhase) =>@@ -452,7 +459,7 @@ export const make = Effect.fn("SshDeviceHost.make")(function* (stopAgent: changeAgent(false).pipe(Effect.asVoid, Effect.ignore),stop,platformAvailability: (platform) =>- provide(probe(config)).pipe(+ provide(probe(config, owner)).pipe(Effect.map((value) => {summary = { ...summary, platforms: value.platforms };return value.platforms.find((p) => p.platform === platform)!;diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.tsindex 9194846d62b..05b680b441f 100644--- a/apps/server/src/ws.ts+++ b/apps/server/src/ws.ts@@ -3456,10 +3456,14 @@ const makeWsRpcLayer = ([WS_METHODS.deviceList]: (input) =>observeRpcEffect(WS_METHODS.deviceList,- authorizeEffect(- requiredScopeForDeviceList(input),- input.retryHostId ? deviceService.retryHost(input.retryHostId) : deviceService.list,- ),+ input.inspectOnly+ ? deviceService.inspect+ : authorizeEffect(+ requiredScopeForDeviceList(input),+ input.retryHostId+ ? deviceService.retryHost(input.retryHostId)+ : deviceService.list,+ ),{"rpc.aggregate": "device",},diff --git a/apps/web/src/components/device/DeviceToolVersions.tsx b/apps/web/src/components/device/DeviceToolVersions.tsxindex 2ed11f7d920..0501c8370bd 100644--- a/apps/web/src/components/device/DeviceToolVersions.tsx+++ b/apps/web/src/components/device/DeviceToolVersions.tsx@@ -1,12 +1,19 @@+import type { ReactNode } from "react";import type { DeviceToolVersions as ToolVersions } from "@t3tools/contracts";import { Popover, PopoverPopup, PopoverTitle, PopoverTrigger } from "~/components/ui/popover";export function DeviceToolVersions({tools,+ action,kind,+ owner,+ error,}: {tools: ToolVersions | undefined;+ action?: ReactNode;kind?: keyof ToolVersions;+ owner?: string | undefined;+ error?: string | undefined;}) {const selected = kind ? tools?.[kind] : undefined;const version =@@ -33,7 +40,9 @@ export function DeviceToolVersions({: selected? "Not installed": "Version unknown"- : "Versions"}+ : error+ ? "Versions unavailable"+ : "Versions"}</PopoverTrigger><PopoverPopup align="end" className="w-80"><PopoverTitle className="text-sm">{kind ? label : "Device tools"}</PopoverTitle>@@ -65,6 +74,15 @@ export function DeviceToolVersions({) : (<p className="mt-3 text-xs text-muted-foreground">Versions have not been checked.</p>)}+ <p className="mt-4 border-t border-border/50 pt-3 text-xs text-muted-foreground">+ {owner ? `Managed by ${owner}. ` : ""}Tools update automatically on this host when needed.+ </p>+ {error ? (+ <p role="status" className="mt-2 text-xs text-destructive">+ {error}+ </p>+ ) : null}+ {action ? <div className="mt-3">{action}</div> : null}</PopoverPopup></Popover>);diff --git a/apps/web/src/components/settings/DeviceHostsSettings.tsx b/apps/web/src/components/settings/DeviceHostsSettings.tsxindex d81ce316705..ffed54e1464 100644--- a/apps/web/src/components/settings/DeviceHostsSettings.tsx+++ b/apps/web/src/components/settings/DeviceHostsSettings.tsx@@ -5,7 +5,7 @@ import { Spinner } from "../ui/spinner";import type { EnvironmentId, SshDeviceHostConfig } from "@t3tools/contracts";import { randomUUID } from "../../lib/utils";import { useState } from "react";-import { useDeviceState } from "../../state/device";+import { deviceEnvironment, useDeviceState } from "../../state/device";import { serverEnvironment } from "../../state/server";import { useAtomCommand } from "../../state/use-atom-command";import { Button } from "../ui/button";@@ -110,6 +110,7 @@ export function DeviceHostsSettings(props: { environmentId: EnvironmentId | null</p>) : null}<DeviceHostList+ environmentLabel={environment.label}environmentId={environment.environmentId}hosts={environment.serverConfig?.settings.deviceHosts ?? []}busy={projectScope || busy}@@ -158,6 +159,7 @@ export function DeviceHostsSettings(props: { environmentId: EnvironmentId | null}function DeviceHostList({+ environmentLabel,environmentId,hosts,busy,@@ -166,6 +168,7 @@ function DeviceHostList({checks,testConnection,}: {+ environmentLabel: string;environmentId: EnvironmentId;hosts: ReadonlyArray<SshDeviceHostConfig>;busy: boolean;@@ -175,6 +178,8 @@ function DeviceHostList({testConnection: ReturnType<typeof useHostConnectionChecks>["testConnection"];}) {const { state } = useDeviceState(environmentId);+ const retry = useAtomCommand(deviceEnvironment.list);+ const [retrying, setRetrying] = useState<string | null>(null);return (<>{hosts.length === 0 ? (@@ -238,9 +243,11 @@ function DeviceHostList({</div><p className="truncate text-xs text-muted-foreground">{host.target}</p><DeviceToolVersions+ owner={environmentLabel}+ error={state.hosts.find((value) => value.id === host.id)?.toolInspectionError}tools={- (check?.status === "connected" ? check.tools : undefined) ??- state.hosts.find((value) => value.id === host.id)?.tools+ state.hosts.find((value) => value.id === host.id)?.tools ??+ (check?.status === "connected" ? check.tools : undefined)}/>{check?.status === "local" ? (@@ -290,14 +297,32 @@ function DeviceHostList({</MenuItem></MenuPopup></Menu>- <Button- size="sm"- variant="outline"- disabled={busy || progress !== null}- onClick={() => void testConnection(host)}- >- Test connection- </Button>+ {status?.status === "failed" &&+ state.supportsHostRetry &&+ state.hostStatus !== "disabled" ? (+ <Button+ size="sm"+ variant="outline"+ disabled={busy || retrying !== null}+ onClick={() => {+ setRetrying(host.id);+ void retry({ environmentId, input: { retryHostId: host.id } }).finally(() =>+ setRetrying(null),+ );+ }}+ >+ {retrying === host.id ? "Retrying…" : "Retry"}+ </Button>+ ) : (+ <Button+ size="sm"+ variant="outline"+ disabled={busy || progress !== null}+ onClick={() => void testConnection(host)}+ >+ Test connection+ </Button>+ )}</div>);})}diff --git a/apps/web/src/components/settings/IntegrationsSettings.tsx b/apps/web/src/components/settings/IntegrationsSettings.tsxindex 5f2e149d17f..851ca7439f9 100644--- a/apps/web/src/components/settings/IntegrationsSettings.tsx+++ b/apps/web/src/components/settings/IntegrationsSettings.tsx@@ -685,6 +685,21 @@ function DeviceIntegrationControls({}};+ const checkVersions = state.supportsToolInspection ? (+ <Button+ size="sm"+ variant="outline"+ disabled={!environmentId || pending !== null || busy}+ onClick={() => {+ if (!environmentId) return;+ setPending("check");+ void list({ environmentId, input: { inspectOnly: true } }).finally(() => setPending(null));+ }}+ >+ {pending === "check" ? "Checking…" : "Check versions"}+ </Button>+ ) : null;+return (<><SettingsRow@@ -695,6 +710,7 @@ function DeviceIntegrationControls({control={<><DeviceToolVersions+ action={checkVersions}kind="hub"tools={state.hosts.find((host) => host.kind === "local")?.tools}/>@@ -758,6 +774,7 @@ function DeviceIntegrationControls({control={<><DeviceToolVersions+ action={checkVersions}kind="agent"tools={state.hosts.find((host) => host.kind === "local")?.tools}/>@@ -780,12 +797,12 @@ function DeviceIntegrationControls({</>}/>- {state.hostStatus === "failed" && state.hostStatusDetail ? (- <p role="alert" className="px-4 py-3 text-xs text-destructive">- {state.hostStatusDetail}- </p>+ {environmentId ? (+ <DeviceHostUpdates+ state={{ ...state, hosts: state.hosts.filter((host) => host.kind === "local") }}+ environmentId={environmentId}+ />) : null}- {environmentId ? <DeviceHostUpdates state={state} environmentId={environmentId} /> : null}<DeviceHostsSettings environmentId={environmentId} /></>);diff --git a/docs/user/devices.md b/docs/user/devices.mdindex b388688bae2..02e06d2bdff 100644--- a/docs/user/devices.md+++ b/docs/user/devices.md@@ -102,3 +102,9 @@ T3 provides discovery, streaming, and control. Arrange app builds,installation, and connectivity to development servers such as Metro separately.A simulator on another machine cannot reach Metro through your environment'slocalhost without forwarding or another reachable address.++## Device tool updates++The connected T3 server manages the device hub and agent tools on its own machine and configured SSH hosts. Required versions install automatically the next time those tools are used. Settings → Integrations → Check device tool versions reads installed versions without installing tools or starting devices.++To receive newer tool versions on a remote environment, update that environment's T3 server. Updating only the browser or mobile app does not update the remote server. An offline host keeps its installed files, but an update needs network access before device support can start; T3 does not fall back to an older version. Reconnect the host and use Retry if installation fails. Existing device and agent-access settings are preserved.diff --git a/packages/client-runtime/src/state/device.ts b/packages/client-runtime/src/state/device.tsindex 5e08de264de..a9f5d5bb2eb 100644--- a/packages/client-runtime/src/state/device.ts+++ b/packages/client-runtime/src/state/device.ts@@ -84,3 +84,16 @@ export function deviceToolVersionLabels(tools: DeviceToolVersions | undefined) {return `${name}: installed ${installed}; required ${tool.requiredVersion}${tool.runningVersion ? `; running ${tool.runningVersion}` : ""}.`;});}++export function deviceToolUpdatePolicy(tools: DeviceToolVersions | undefined) {+ if (!tools) return "Versions have not been checked. Reconnect the host and check versions.";+ const outdated = [tools.hub, tools.agent].filter(+ (tool) =>+ tool.installedVersions.length > 0 && !tool.installedVersions.includes(tool.requiredVersion),+ );+ return outdated.length > 0+ ? "Update pending. Required tools will install automatically when next used. The host needs network access; an older install is not used as a fallback."+ : "Required tools are installed automatically when needed. Checking versions does not install or start anything.";+}+export const deviceToolUpdateOwnership =+ "This environment's T3 server chooses device tool versions for itself and its SSH hosts. Update that server to receive newer tool versions; updating only your browser or mobile app does not update a remote server.";diff --git a/packages/contracts/src/device.ts b/packages/contracts/src/device.tsindex afcc04dbefb..20b49f85012 100644--- a/packages/contracts/src/device.ts+++ b/packages/contracts/src/device.ts@@ -93,6 +93,7 @@ export const DeviceHostSummary = Schema.Struct({label: TrimmedNonEmptyString,platforms: Schema.Array(DevicePlatformAvailability),tools: Schema.optional(DeviceToolVersions),+ toolInspectionError: Schema.optional(Schema.String),hubInstalled: Schema.Boolean,agentDeviceInstalled: Schema.Boolean,});@@ -128,6 +129,7 @@ export type DeviceSession = typeof DeviceSession.Type;export const DeviceServiceState = Schema.Struct({supportsHostRetry: Schema.optional(Schema.Boolean),+ supportsToolInspection: Schema.optional(Schema.Boolean),hosts: Schema.Array(DeviceHostSummary),hostStatus: DeviceHostStatus,hostStatusDetail: Schema.optional(Schema.String),@@ -152,6 +154,8 @@ export const DeviceServiceState = Schema.Struct({export type DeviceServiceState = typeof DeviceServiceState.Type;export const DeviceListInput = Schema.Struct({+ /** Read inventory without installing tools or starting helpers. */+ inspectOnly: Schema.optional(Schema.Boolean),/** Retry this host only, including agent tools if access was already granted. */retryHostId: Schema.optional(DeviceHostId),});