TypeScript
fix(web): device tool update failures show the server error, not network advice (#17569)
Scott Norteman17fa62886656
diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.tsindex 13e0c3873e3..25eab7a2ed4 100644--- a/apps/server/src/device/DeviceService.test.ts+++ b/apps/server/src/device/DeviceService.test.ts@@ -886,3 +886,65 @@ it.effect("reconciles SSH host settings without publishing no-op changes", () =>Effect.provide(Layer.mergeAll(ServerSettings.layerTest(), NodeServices.layer)),),);++it.effect("a failed tool update reports npm's exit code but not its output", () =>+ Effect.gen(function* () {+ const host: DeviceHost.DeviceHost["Service"] = {+ id: LOCAL_DEVICE_HOST_ID,+ summary: Effect.succeed({+ id: LOCAL_DEVICE_HOST_ID,+ kind: "local",+ label: "Test server",+ platforms: [],+ hubInstalled: false,+ agentDeviceInstalled: false,+ }),+ platformAvailability: (platform) => Effect.succeed({ platform, available: false }),+ ensureReady: () => Effect.die("Updating a tool does not start the hub"),+ ensureAgentReady: () => Effect.die("Updating a tool does not start the agent"),+ current: Effect.succeed(null),+ stopAgent: Effect.void,+ stop: Effect.void,+ };+ const npmFailure = {+ code: ChildProcessSpawner.ExitCode(243),+ stdout: "",+ stderr: "npm error EACCES https://private:[email protected]/expo-device-hub",+ timedOut: false,+ stdoutTruncated: false,+ stderrTruncated: false,+ stdoutInvalidUtf8: false,+ stderrInvalidUtf8: false,+ };+ const service = yield* DeviceService.make.pipe(+ Effect.provideService(DeviceHost.DeviceHost, host),+ Effect.provideService(ProcessRunner.ProcessRunner, {+ run: () => Effect.succeed(npmFailure),+ }),+ Effect.provideService(+ HttpClient.HttpClient,+ HttpClient.make(() => Effect.die("Updating a tool makes no hub requests")),+ ),+ );++ const error = yield* service.updateTool("hub").pipe(Effect.flip);+ expect(error).toMatchObject({+ _tag: "DeviceOperationError",+ reason: "command_failed",+ exitCode: 243,+ });+ expect(error.message).toBe(+ "Device update device tool failed: The device command failed (exit code 243).",+ );+ }).pipe(+ Effect.provide(+ Layer.mergeAll(+ ServerSettings.layerTest({ enableDeviceSupport: true }),+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-device-update-" }),+ NodeCrypto.layer,+ NetService.layer,+ ).pipe(Layer.provideMerge(NodeServices.layer)),+ ),+ Effect.scoped,+ ),+);diff --git a/apps/server/src/device/DeviceService.ts b/apps/server/src/device/DeviceService.tsindex 8b025ba4c87..d453d15adac 100644--- a/apps/server/src/device/DeviceService.ts+++ b/apps/server/src/device/DeviceService.ts@@ -1033,6 +1033,8 @@ export const make = Effect.gen(function* () {new DeviceOperationError({operation: "update device tool",reason: "command_failed",+ // Only the exit code goes into the shown message; npm's stderr can carry registry credentials.+ ...(cause.exitCode !== undefined ? { exitCode: cause.exitCode } : {}),cause,}),),diff --git a/apps/web/src/components/settings/DeviceToolUpdate.test.tsx b/apps/web/src/components/settings/DeviceToolUpdate.test.tsxnew file mode 100644index 00000000000..12ab6242b1a--- /dev/null+++ b/apps/web/src/components/settings/DeviceToolUpdate.test.tsx@@ -0,0 +1,142 @@+import { EnvironmentRpcUnavailableError } from "@t3tools/client-runtime/rpc";+import {+ DeviceOperationError,+ EnvironmentId,+ LOCAL_DEVICE_HOST_ID,+ type DeviceServiceState,+} from "@t3tools/contracts";+import * as Cause from "effect/Cause";+import { act, type ReactNode } from "react";+import { create, type ReactTestRenderer } from "react-test-renderer";+import { afterEach, beforeEach, expect, it, vi } from "vite-plus/test";++const { list } = vi.hoisted(() => ({ list: vi.fn() }));++vi.mock("~/state/use-atom-command", () => ({+ useAtomCommand: (command: unknown) => (command === "list" ? list : vi.fn()),+}));+vi.mock("~/state/device", () => ({+ deviceEnvironment: { list: "list", configure: "configure" },+ useDeviceState: () => ({ state: deviceState, loaded: true }),+}));+vi.mock("~/state/session", async (importOriginal) => ({+ ...(await importOriginal<typeof import("~/state/session")>()),+ useEnvironmentScope: () => true,+ readEnvironmentScope: () => true,+}));+vi.mock("./SettingsScopeContext", () => ({+ useSettingsScope: () => ({+ scope: { kind: "all", environmentIds: [] },+ search: {},+ environment: null,+ environments: [],+ target: null,+ connectedEnvironments: [],+ targets: [],+ }),+ useOptionalSettingsScope: () => null,+}));+vi.mock("./useScopedSettings", async (importOriginal) => ({+ ...(await importOriginal<typeof import("./useScopedSettings")>()),+ useUpdateScopedSettings: () => vi.fn(),+}));+// Rows resolve scope and permissions; only their controls matter here.+vi.mock("./settingsLayout", async (importOriginal) => ({+ ...(await importOriginal<typeof import("./settingsLayout")>()),+ SettingsRow: ({ control, children }: { control?: ReactNode; children?: ReactNode }) => (+ <>+ {control}+ {children}+ </>+ ),+}));+// The version popover holds the Update button; render the button in place of the popover.+vi.mock("../device/DeviceToolVersions", () => ({+ DeviceToolVersions: ({ action }: { action?: ReactNode }) => action ?? null,+}));+vi.mock("../device/DeviceHostUpdates", () => ({ DeviceHostUpdates: () => null }));+vi.mock("./DeviceHostsSettings", () => ({ DeviceHostsSettings: () => null }));++import { DeviceIntegrationControls } from "./IntegrationsSettings";++const environmentId = EnvironmentId.make("environment-1");+const deviceState = {+ supportsToolUpdate: true,+ hosts: [+ {+ id: LOCAL_DEVICE_HOST_ID,+ kind: "local",+ label: "This computer",+ platforms: [],+ tools: {+ hub: { requiredVersion: "0.12.0", installedVersions: [], runningVersion: null },+ agent: { requiredVersion: "1.0.0", installedVersions: ["1.0.0"], runningVersion: null },+ },+ hubInstalled: false,+ agentDeviceInstalled: true,+ },+ ],+ hostStatus: "idle",+ hostStatuses: {},+ devices: [],+ sessions: [],+ onboardingCompleted: true,+ agentAccessEnabled: false,+ hubBasePath: "/device-hub",+ revision: 1,+} satisfies DeviceServiceState;++let renderer: ReactTestRenderer | undefined;++beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ list.mockReset();+});++afterEach(async () => {+ await act(() => renderer?.unmount());+ vi.unstubAllGlobals();+});++it.each([+ {+ name: "a failed install",+ error: new DeviceOperationError({+ operation: "update device tool",+ reason: "command_failed",+ exitCode: 243,+ cause: new Error("npm error EACCES https://private:[email protected]/hub"),+ }),+ message: "Device update device tool failed: The device command failed (exit code 243).",+ },+ {+ name: "a lost connection",+ error: new EnvironmentRpcUnavailableError({+ environmentId,+ message: "Query environment is not connected.",+ }),+ message: "Query environment is not connected.",+ },+])(+ "reports $name as the server describes it, not as a network problem",+ async ({ error, message }) => {+ list.mockResolvedValue({ _tag: "Failure", cause: Cause.fail(error) });+ await act(() => {+ renderer = create(+ <DeviceIntegrationControls+ environmentId={environmentId}+ enabled+ agentAccessEnabled={false}+ />,+ );+ });++ const update = renderer!.root.find(+ (node) => node.type === "button" && node.props.children === "Update to v0.12.0",+ );+ await act(async () => update.props.onClick());++ expect(list).toHaveBeenCalledWith({ environmentId, input: { updateTool: "hub" } });+ expect(renderer!.root.find((node) => node.props.role === "alert").props.children).toBe(message);+ },+);diff --git a/apps/web/src/components/settings/IntegrationsSettings.tsx b/apps/web/src/components/settings/IntegrationsSettings.tsxindex 04ba15eec6c..723887f0094 100644--- a/apps/web/src/components/settings/IntegrationsSettings.tsx+++ b/apps/web/src/components/settings/IntegrationsSettings.tsx@@ -44,6 +44,7 @@ import { useEnvironments, usePrimaryEnvironment } from "~/state/environments";import { deviceEnvironment, useDeviceState } from "~/state/device";import { readEnvironmentScope, useEnvironmentScope } from "~/state/session";import { useAtomCommand } from "~/state/use-atom-command";+import { formatEnvironmentQueryError } from "~/state/query";import { previewEnvironment } from "~/state/preview";import { useServerConfigs } from "~/state/entities";import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";@@ -728,7 +729,7 @@ function DeviceIntegrationSettings() {);}-function DeviceIntegrationControls({+export function DeviceIntegrationControls({environmentId,enabled,agentAccessEnabled,@@ -820,11 +821,7 @@ function DeviceIntegrationControls({void list({ environmentId, input: { updateTool: tool } }).then((result) => {if (result._tag === "Failure")- setUpdateError({- tool,- message:- "Update failed. Check this host's network connection and try again.",- });+ setUpdateError({ tool, message: formatEnvironmentQueryError(result.cause) });}).finally(() => setPending(null));}}