From 5bb5be63ac4773c133cee919a99d278e2d423d78 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 2 Jun 2026 20:34:38 -0700 Subject: [PATCH] feat(cloud): stream relay client installation over rpc Co-authored-by: codex --- apps/desktop/src/ipc/DesktopIpcHandlers.ts | 4 - apps/desktop/src/ipc/channels.ts | 2 - .../src/ipc/methods/relayClient.test.ts | 43 ------- apps/desktop/src/ipc/methods/relayClient.ts | 27 ---- apps/desktop/src/main.ts | 18 +-- apps/desktop/src/preload.ts | 2 - .../src/cloud/ManagedEndpointRuntime.test.ts | 2 + apps/server/src/server.test.ts | 62 +++++++++ apps/server/src/server.ts | 15 ++- apps/server/src/ws.ts | 40 ++++++ apps/web/src/cloud/linkEnvironment.test.ts | 119 +++++++++++------- apps/web/src/cloud/linkEnvironment.ts | 57 +++++---- .../settings/SettingsPanels.browser.tsx | 12 -- .../service.threadSubscriptions.test.ts | 4 + apps/web/src/localApi.test.ts | 12 -- packages/client-runtime/src/wsRpcClient.ts | 28 +++++ packages/contracts/src/index.ts | 1 + packages/contracts/src/ipc.ts | 22 ---- packages/contracts/src/relayClient.ts | 63 ++++++++++ packages/contracts/src/rpc.ts | 24 ++++ packages/shared/src/relayClient.test.ts | 18 ++- packages/shared/src/relayClient.ts | 35 +++++- 22 files changed, 393 insertions(+), 217 deletions(-) delete mode 100644 apps/desktop/src/ipc/methods/relayClient.test.ts delete mode 100644 apps/desktop/src/ipc/methods/relayClient.ts create mode 100644 packages/contracts/src/relayClient.ts diff --git a/apps/desktop/src/ipc/DesktopIpcHandlers.ts b/apps/desktop/src/ipc/DesktopIpcHandlers.ts index 98e34bba59..40f8405487 100644 --- a/apps/desktop/src/ipc/DesktopIpcHandlers.ts +++ b/apps/desktop/src/ipc/DesktopIpcHandlers.ts @@ -9,7 +9,6 @@ import { setCloudAuthToken, } from "./methods/cloudAuth.ts"; import { getClientSettings, setClientSettings } from "./methods/clientSettings.ts"; -import { getRelayClientStatus, installRelayClient } from "./methods/relayClient.ts"; import { getSavedEnvironmentRegistry, getSavedEnvironmentSecret, @@ -88,9 +87,6 @@ export const installDesktopIpcHandlers = Effect.gen(function* () { yield* ipc.handle(setCloudAuthToken); yield* ipc.handle(clearCloudAuthToken); yield* ipc.handle(fetchCloudAuth); - yield* ipc.handle(getRelayClientStatus); - yield* ipc.handle(installRelayClient); - yield* ipc.handle(getUpdateState); yield* ipc.handle(setUpdateChannel); yield* ipc.handle(downloadUpdate); diff --git a/apps/desktop/src/ipc/channels.ts b/apps/desktop/src/ipc/channels.ts index 8332cc464c..1ded238c66 100644 --- a/apps/desktop/src/ipc/channels.ts +++ b/apps/desktop/src/ipc/channels.ts @@ -8,8 +8,6 @@ export const GET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:get-cloud-auth-token"; export const SET_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:set-cloud-auth-token"; export const CLEAR_CLOUD_AUTH_TOKEN_CHANNEL = "desktop:clear-cloud-auth-token"; export const FETCH_CLOUD_AUTH_CHANNEL = "desktop:fetch-cloud-auth"; -export const GET_RELAY_CLIENT_STATUS_CHANNEL = "desktop:get-relay-client-status"; -export const INSTALL_RELAY_CLIENT_CHANNEL = "desktop:install-relay-client"; export const CLOUD_AUTH_CALLBACK_CHANNEL = "desktop:cloud-auth-callback"; export const MENU_ACTION_CHANNEL = "desktop:menu-action"; export const UPDATE_STATE_CHANNEL = "desktop:update-state"; diff --git a/apps/desktop/src/ipc/methods/relayClient.test.ts b/apps/desktop/src/ipc/methods/relayClient.test.ts deleted file mode 100644 index 73e0da4ed2..0000000000 --- a/apps/desktop/src/ipc/methods/relayClient.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import { describe, expect, it } from "@effect/vitest"; -import * as RelayClient from "@t3tools/shared/relayClient"; -import * as Effect from "effect/Effect"; -import * as Layer from "effect/Layer"; - -import { getRelayClientStatus, installRelayClient } from "./relayClient.ts"; - -const available = { - status: "available", - executablePath: "/Users/test/.t3/tools/cloudflared/cloudflared", - source: "managed", - version: RelayClient.CLOUDFLARED_VERSION, -} as const; - -describe("Desktop relay client IPC", () => { - it.effect("reads status and delegates installation to the shared manager", () => - Effect.gen(function* () { - const installed: Array = []; - const layer = Layer.succeed( - RelayClient.RelayClient, - RelayClient.RelayClient.of({ - resolve: Effect.succeed({ - status: "missing", - version: RelayClient.CLOUDFLARED_VERSION, - }), - install: Effect.sync(() => { - installed.push(true); - return available; - }), - }), - ); - - expect(yield* getRelayClientStatus.handler(undefined).pipe(Effect.provide(layer))).toEqual({ - status: "missing", - version: RelayClient.CLOUDFLARED_VERSION, - }); - expect(yield* installRelayClient.handler(undefined).pipe(Effect.provide(layer))).toEqual( - available, - ); - expect(installed).toEqual([true]); - }), - ); -}); diff --git a/apps/desktop/src/ipc/methods/relayClient.ts b/apps/desktop/src/ipc/methods/relayClient.ts deleted file mode 100644 index dafd20700f..0000000000 --- a/apps/desktop/src/ipc/methods/relayClient.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { DesktopRelayClientStatusSchema } from "@t3tools/contracts"; -import * as RelayClient from "@t3tools/shared/relayClient"; -import * as Effect from "effect/Effect"; -import * as Schema from "effect/Schema"; - -import * as IpcChannels from "../channels.ts"; -import { makeIpcMethod } from "../DesktopIpc.ts"; - -export const getRelayClientStatus = makeIpcMethod({ - channel: IpcChannels.GET_RELAY_CLIENT_STATUS_CHANNEL, - payload: Schema.Undefined, - result: DesktopRelayClientStatusSchema, - handler: Effect.fn("desktop.ipc.relayClient.getStatus")(function* () { - const relayClient = yield* RelayClient.RelayClient; - return yield* relayClient.resolve; - }), -}); - -export const installRelayClient = makeIpcMethod({ - channel: IpcChannels.INSTALL_RELAY_CLIENT_CHANNEL, - payload: Schema.Undefined, - result: DesktopRelayClientStatusSchema, - handler: Effect.fn("desktop.ipc.relayClient.install")(function* () { - const relayClient = yield* RelayClient.RelayClient; - return yield* relayClient.install; - }), -}); diff --git a/apps/desktop/src/main.ts b/apps/desktop/src/main.ts index e8177355e9..9356eef441 100644 --- a/apps/desktop/src/main.ts +++ b/apps/desktop/src/main.ts @@ -9,7 +9,6 @@ import * as Option from "effect/Option"; import * as Electron from "electron"; import * as NetService from "@t3tools/shared/Net"; -import * as RelayClient from "@t3tools/shared/relayClient"; import { resolveRemoteT3CliPackageSpec } from "@t3tools/ssh/command"; import type { RemoteT3RunnerOptions } from "@t3tools/ssh/tunnel"; import serverPackageJson from "../../server/package.json" with { type: "json" }; @@ -95,17 +94,6 @@ const desktopSshEnvironmentLayer = Layer.unwrap( }), ); -const desktopRelayClientLayer = Layer.unwrap( - Effect.gen(function* () { - const environment = yield* DesktopEnvironment.DesktopEnvironment; - return RelayClient.layerCloudflared({ - baseDir: environment.baseDir, - platform: environment.platform, - arch: environment.processArch, - }); - }), -); - const electronLayer = Layer.mergeAll( ElectronApp.layer, ElectronDialog.layer, @@ -153,11 +141,7 @@ const desktopApplicationLayer = Layer.mergeAll( DesktopCloudAuth.layer, DesktopShellEnvironment.layer, desktopSshLayer, -).pipe( - Layer.provideMerge(DesktopUpdates.layer), - Layer.provideMerge(desktopRelayClientLayer), - Layer.provideMerge(desktopBackendLayer), -); +).pipe(Layer.provideMerge(DesktopUpdates.layer), Layer.provideMerge(desktopBackendLayer)); const desktopRuntimeLayer = ElectronProtocol.layerSchemePrivileges.pipe( Layer.flatMap(() => diff --git a/apps/desktop/src/preload.ts b/apps/desktop/src/preload.ts index 1dde53c27a..84f7580cb0 100644 --- a/apps/desktop/src/preload.ts +++ b/apps/desktop/src/preload.ts @@ -102,8 +102,6 @@ contextBridge.exposeInMainWorld("desktopBridge", { ipcRenderer.invoke(IpcChannels.SET_CLOUD_AUTH_TOKEN_CHANNEL, token), clearCloudAuthToken: () => ipcRenderer.invoke(IpcChannels.CLEAR_CLOUD_AUTH_TOKEN_CHANNEL), fetchCloudAuth: (input) => ipcRenderer.invoke(IpcChannels.FETCH_CLOUD_AUTH_CHANNEL, input), - getRelayClientStatus: () => ipcRenderer.invoke(IpcChannels.GET_RELAY_CLIENT_STATUS_CHANNEL), - installRelayClient: () => ipcRenderer.invoke(IpcChannels.INSTALL_RELAY_CLIENT_CHANNEL), onCloudAuthCallback: (listener) => { const wrappedListener = (_event: Electron.IpcRendererEvent, rawUrl: unknown) => { if (typeof rawUrl !== "string") return; diff --git a/apps/server/src/cloud/ManagedEndpointRuntime.test.ts b/apps/server/src/cloud/ManagedEndpointRuntime.test.ts index 03e6e2c0d2..10358c79a8 100644 --- a/apps/server/src/cloud/ManagedEndpointRuntime.test.ts +++ b/apps/server/src/cloud/ManagedEndpointRuntime.test.ts @@ -22,6 +22,7 @@ const relayClientAvailableLayer = Layer.succeed( version: RelayClient.CLOUDFLARED_VERSION, }), install: Effect.die("unused"), + installWithProgress: () => Effect.die("unused"), }), ); @@ -333,6 +334,7 @@ describe("CloudManagedEndpointRuntime", () => { version: RelayClient.CLOUDFLARED_VERSION, }), install: Effect.die("unused"), + installWithProgress: () => Effect.die("unused"), }), ), ), diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index c85ca112a1..29f103a50e 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -35,6 +35,7 @@ import { type DpopPublicJwk, } from "@t3tools/shared/dpop"; import { RELAY_HEALTH_REQUEST_TYP, RELAY_MINT_REQUEST_TYP } from "@t3tools/shared/relayJwt"; +import * as RelayClient from "@t3tools/shared/relayClient"; import { assert, it } from "@effect/vitest"; import { assertFailure, assertInclude, assertTrue } from "@effect/vitest/utils"; import * as Clock from "effect/Clock"; @@ -359,6 +360,7 @@ const buildAppUnderTest = (options?: { serverEnvironment?: Partial; repositoryIdentityResolver?: Partial; cloudManagedEndpointRuntime?: Partial; + relayClient?: Partial; }; }) => Effect.gen(function* () { @@ -762,6 +764,20 @@ const buildAppUnderTest = (options?: { }), ), ), + Layer.provide( + Layer.succeed( + RelayClient.RelayClient, + RelayClient.RelayClient.of({ + resolve: Effect.succeed({ + status: "missing", + version: RelayClient.CLOUDFLARED_VERSION, + }), + install: Effect.die("unused relay-client install"), + installWithProgress: () => Effect.die("unused relay-client install"), + ...options?.layers?.relayClient, + }), + ), + ), Layer.provideMerge(makeAuthTestLayer()), Layer.provideMerge(ServerSecretStore.layer), Layer.provide(workspaceAndProjectServicesLayer), @@ -1950,6 +1966,52 @@ it.layer(NodeServices.layer)("server router seam", (it) => { }).pipe(Effect.provide(NodeHttpServer.layerTest)), ); + it.effect( + "reports relay client status and streams installation progress over environment RPC", + () => + Effect.gen(function* () { + const installedRelayClient = { + status: "available" as const, + executablePath: "/tmp/t3/tools/cloudflared", + source: "managed" as const, + version: RelayClient.CLOUDFLARED_VERSION, + }; + yield* buildAppUnderTest({ + layers: { + relayClient: { + resolve: Effect.succeed({ + status: "missing", + version: RelayClient.CLOUDFLARED_VERSION, + }), + install: Effect.succeed(installedRelayClient), + installWithProgress: (report) => + report({ type: "progress", stage: "checking" }).pipe( + Effect.andThen(report({ type: "progress", stage: "downloading" })), + Effect.as(installedRelayClient), + ), + }, + }, + }); + + const wsUrl = yield* getWsServerUrl("/ws"); + const status = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => client[WS_METHODS.cloudGetRelayClientStatus]({})), + ); + const installEvents = yield* Effect.scoped( + withWsRpcClient(wsUrl, (client) => + client[WS_METHODS.cloudInstallRelayClient]({}).pipe(Stream.runCollect), + ), + ); + + assert.equal(status.status, "missing"); + assert.deepEqual(Array.from(installEvents), [ + { type: "progress", stage: "checking" }, + { type: "progress", stage: "downloading" }, + { type: "complete", status: installedRelayClient }, + ]); + }).pipe(Effect.provide(NodeHttpServer.layerTest)), + ); + it.effect("requires relay write scope to update agent activity publication", () => Effect.gen(function* () { yield* buildAppUnderTest(); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 9249099c8f..9dc2cd7d25 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -243,6 +243,14 @@ const AuthLayerLive = EnvironmentAuth.layer.pipe( Layer.provide(ServerSecretStore.layer), ); +const CloudManagedEndpointRuntimeLive = Layer.mergeAll( + RelayClientLive, + CloudManagedEndpointRuntime.layer.pipe( + Layer.provide(ServerSecretStore.layer), + Layer.provide(RelayClientLive), + ), +); + const ProviderRuntimeLayerLive = ProviderSessionReaperLive.pipe( Layer.provideMerge(ProviderLayerLive), Layer.provideMerge(OrchestrationLayerLive), @@ -284,12 +292,7 @@ const RuntimeCoreDependenciesLive = ReactorLayerLive.pipe( Layer.provideMerge(ServerEnvironmentLive), Layer.provideMerge(AuthLayerLive), Layer.provideMerge(ServerSecretStore.layer), - Layer.provideMerge( - CloudManagedEndpointRuntime.layer.pipe( - Layer.provide(ServerSecretStore.layer), - Layer.provide(RelayClientLive), - ), - ), + Layer.provideMerge(CloudManagedEndpointRuntimeLive), ); const RuntimeDependenciesLive = RuntimeCoreDependenciesLive.pipe( diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index da8e3f694d..059918e132 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -14,6 +14,7 @@ import { AuthOrchestrationOperateScope, AuthOrchestrationReadScope, AuthReviewWriteScope, + AuthRelayWriteScope, AuthTerminalOperateScope, AuthAccessReadScope, AuthAccessStreamError, @@ -34,6 +35,8 @@ import { ORCHESTRATION_WS_METHODS, ProjectSearchEntriesError, ProjectWriteFileError, + RelayClientInstallFailedError, + type RelayClientInstallProgressEvent, OrchestrationReplayEventsError, FilesystemBrowseError, EnvironmentAuthorizationError, @@ -96,6 +99,7 @@ import * as VcsProcess from "./vcs/VcsProcess.ts"; import * as PairingGrantStore from "./auth/PairingGrantStore.ts"; import * as SessionStore from "./auth/SessionStore.ts"; import { failEnvironmentAuthInvalid, failEnvironmentInternal } from "./auth/http.ts"; +import * as RelayClient from "@t3tools/shared/relayClient"; const isOrchestrationDispatchCommandError = Schema.is(OrchestrationDispatchCommandError); const isWorkspacePathOutsideRootError = Schema.is(WorkspacePathOutsideRootError); @@ -145,6 +149,8 @@ const RPC_REQUIRED_SCOPE = new Map([ [WS_METHODS.serverGetProcessDiagnostics, AuthOrchestrationReadScope], [WS_METHODS.serverGetProcessResourceHistory, AuthOrchestrationReadScope], [WS_METHODS.serverSignalProcess, AuthOrchestrationOperateScope], + [WS_METHODS.cloudGetRelayClientStatus, AuthRelayWriteScope], + [WS_METHODS.cloudInstallRelayClient, AuthRelayWriteScope], [WS_METHODS.sourceControlLookupRepository, AuthOrchestrationReadScope], [WS_METHODS.sourceControlCloneRepository, AuthOrchestrationOperateScope], [WS_METHODS.sourceControlPublishRepository, AuthOrchestrationOperateScope], @@ -260,6 +266,7 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) => const sessions = yield* SessionStore.SessionStore; const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics; const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor; + const relayClient = yield* RelayClient.RelayClient; const authorizationError = (requiredScope: AuthEnvironmentScope) => new EnvironmentAuthorizationError({ message: `The authenticated token is missing required scope: ${requiredScope}.`, @@ -1070,6 +1077,39 @@ const makeWsRpcLayer = (currentSession: AuthenticatedSession) => observeRpcEffect(WS_METHODS.serverSignalProcess, processDiagnostics.signal(input), { "rpc.aggregate": "server", }), + [WS_METHODS.cloudGetRelayClientStatus]: (_input) => + observeRpcEffect(WS_METHODS.cloudGetRelayClientStatus, relayClient.resolve, { + "rpc.aggregate": "cloud", + }), + [WS_METHODS.cloudInstallRelayClient]: (_input) => + observeRpcStream( + WS_METHODS.cloudInstallRelayClient, + Stream.callback( + (queue) => + relayClient + .installWithProgress((event) => Queue.offer(queue, event).pipe(Effect.asVoid)) + .pipe( + Effect.flatMap((status) => + Queue.offer(queue, { + type: "complete", + status, + }), + ), + Effect.catchTag("RelayClientInstallError", (error) => + Queue.fail( + queue, + new RelayClientInstallFailedError({ + reason: error.reason, + message: error.message, + }), + ), + ), + Effect.andThen(Queue.end(queue)), + Effect.forkScoped, + ), + ), + { "rpc.aggregate": "cloud" }, + ), [WS_METHODS.sourceControlLookupRepository]: (input) => observeRpcEffect( WS_METHODS.sourceControlLookupRepository, diff --git a/apps/web/src/cloud/linkEnvironment.test.ts b/apps/web/src/cloud/linkEnvironment.test.ts index fa04b06eb0..2cb80fac1a 100644 --- a/apps/web/src/cloud/linkEnvironment.test.ts +++ b/apps/web/src/cloud/linkEnvironment.test.ts @@ -1,7 +1,6 @@ import { EnvironmentId } from "@t3tools/contracts"; import { RelayWebClientId } from "@t3tools/contracts/relay"; import { afterEach, beforeEach, vi } from "vitest"; -import type { DesktopBridge } from "@t3tools/contracts"; import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; @@ -16,7 +15,6 @@ import { import type { SavedEnvironmentRecord } from "../environments/runtime"; import { connectManagedCloudEnvironment, - ensureDesktopRelayClientAvailable, linkEnvironmentToCloud, linkPrimaryEnvironmentToCloud, listManagedCloudEnvironments, @@ -31,6 +29,17 @@ import { } from "../environments/primary"; const getSavedEnvironmentSecretMock = vi.fn(); +const confirmRelayClientInstallMock = vi.fn(); +const getRelayClientStatusMock = vi.fn(); +const installRelayClientMock = vi.fn(); +const environmentConnectionMock = { + client: { + cloud: { + getRelayClientStatus: getRelayClientStatusMock, + installRelayClient: installRelayClientMock, + }, + }, +}; const createProofMock = vi.fn( (_input: { readonly method: string; readonly url: string; readonly accessToken?: string }) => @@ -61,6 +70,9 @@ const withCloudServices = ( vi.mock("../localApi", () => ({ ensureLocalApi: () => ({ + dialogs: { + confirm: confirmRelayClientInstallMock, + }, persistence: { getSavedEnvironmentSecret: getSavedEnvironmentSecretMock, }, @@ -73,6 +85,11 @@ vi.mock("../environments/primary", () => ({ resolvePrimaryEnvironmentHttpUrl: vi.fn((path: string) => `http://127.0.0.1:3000${path}`), })); +vi.mock("../environments/runtime", () => ({ + getPrimaryEnvironmentConnection: () => environmentConnectionMock, + readEnvironmentConnection: () => environmentConnectionMock, +})); + const savedEnvironment: SavedEnvironmentRecord = { environmentId: EnvironmentId.make("env-1"), label: "Desktop", @@ -93,6 +110,15 @@ function validChallenge() { }; } +function availableRelayClient() { + return { + status: "available", + executablePath: "/Users/test/.t3/tools/cloudflared/cloudflared", + source: "managed", + version: "2026.5.2", + }; +} + function requestBodyText(body: BodyInit | null | undefined): string { return body instanceof Uint8Array ? new TextDecoder().decode(body) : String(body ?? ""); } @@ -107,9 +133,13 @@ describe("web cloud link environment client", () => { beforeEach(() => { vi.restoreAllMocks(); + vi.clearAllMocks(); createProofMock.mockClear(); vi.stubEnv("VITE_T3CODE_RELAY_URL", "https://relay.example.test"); getSavedEnvironmentSecretMock.mockResolvedValue("local-bearer"); + confirmRelayClientInstallMock.mockResolvedValue(true); + getRelayClientStatusMock.mockResolvedValue(availableRelayClient()); + installRelayClientMock.mockResolvedValue(availableRelayClient()); vi.mocked(readPrimaryEnvironmentDescriptor).mockReturnValue(null); vi.mocked(readPrimaryEnvironmentTarget).mockReturnValue(null); vi.mocked(resolvePrimaryEnvironmentHttpUrl).mockImplementation( @@ -124,47 +154,51 @@ describe("web cloud link environment client", () => { expect(normalizeRelayBaseUrl(" ")).toBeNull(); }); - it("installs the relay client after desktop confirmation", async () => { - vi.stubGlobal("window", {}); - const confirm = vi.fn().mockResolvedValue(true); - const installRelayClient = vi.fn().mockResolvedValue({ - status: "available", - executablePath: "/Users/test/.t3/tools/cloudflared/cloudflared", - source: "managed", - version: "2026.5.2", - }); - window.desktopBridge = { - confirm, - getRelayClientStatus: vi.fn().mockResolvedValue({ - status: "missing", - version: "2026.5.2", + it.effect( + "installs the relay client over environment RPC before requesting a cloud challenge", + () => + Effect.gen(function* () { + getRelayClientStatusMock.mockResolvedValue({ + status: "missing", + version: "2026.5.2", + }); + vi.mocked(readPrimaryEnvironmentDescriptor).mockReturnValue({ + environmentId: EnvironmentId.make("env-1"), + label: "Desktop", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.0.0-test", + capabilities: { repositoryIdentity: true }, + }); + vi.mocked(readPrimaryEnvironmentTarget).mockReturnValue({ + source: "desktop-managed", + target: { + httpBaseUrl: "http://127.0.0.1:3000", + wsBaseUrl: "ws://127.0.0.1:3000", + }, + }); + const fetchMock = vi + .fn() + .mockResolvedValueOnce(Response.json(validChallenge())) + .mockResolvedValueOnce(Response.json({ malformed: true })); + vi.stubGlobal("fetch", fetchMock); + + yield* withCloudServices( + linkPrimaryEnvironmentToCloud({ + clerkToken: "clerk-token", + }), + ).pipe(Effect.flip); + + expect(confirmRelayClientInstallMock).toHaveBeenCalledOnce(); + expect(getRelayClientStatusMock).toHaveBeenCalledOnce(); + expect(installRelayClientMock).toHaveBeenCalledOnce(); + expect(installRelayClientMock.mock.invocationCallOrder[0]).toBeLessThan( + fetchMock.mock.invocationCallOrder[0]!, + ); + expect(String(fetchMock.mock.calls[0]?.[0])).toBe( + "https://relay.example.test/v1/client/environment-link-challenges", + ); }), - installRelayClient, - } as unknown as DesktopBridge; - - await Effect.runPromise(ensureDesktopRelayClientAvailable()); - - expect(confirm).toHaveBeenCalledOnce(); - expect(installRelayClient).toHaveBeenCalledOnce(); - }); - - it("does not install the relay client when desktop confirmation is declined", async () => { - vi.stubGlobal("window", {}); - const installRelayClient = vi.fn(); - window.desktopBridge = { - confirm: vi.fn().mockResolvedValue(false), - getRelayClientStatus: vi.fn().mockResolvedValue({ - status: "missing", - version: "2026.5.2", - }), - installRelayClient, - } as unknown as DesktopBridge; - - await expect(Effect.runPromise(ensureDesktopRelayClientAvailable())).rejects.toMatchObject({ - message: "Relay client installation was cancelled.", - }); - expect(installRelayClient).not.toHaveBeenCalled(); - }); + ); it.effect("lists relay-managed environments for hosted and served web clients", () => Effect.gen(function* () { @@ -453,6 +487,7 @@ describe("web cloud link environment client", () => { }), ); + expect(getRelayClientStatusMock).toHaveBeenCalledOnce(); expect(String(fetchMock.mock.calls[0]?.[0])).toBe( "https://relay.example.test/v1/client/environment-link-challenges", ); diff --git a/apps/web/src/cloud/linkEnvironment.ts b/apps/web/src/cloud/linkEnvironment.ts index 81548d34ff..21fdf52f43 100644 --- a/apps/web/src/cloud/linkEnvironment.ts +++ b/apps/web/src/cloud/linkEnvironment.ts @@ -27,10 +27,15 @@ import { makeEnvironmentHttpApiClient, ManagedRelayClient, ManagedRelayDpopSigner, + type WsRpcClient, } from "@t3tools/client-runtime"; import { ensureLocalApi } from "../localApi"; -import type { SavedEnvironmentRecord } from "../environments/runtime"; +import { + getPrimaryEnvironmentConnection, + readEnvironmentConnection, + type SavedEnvironmentRecord, +} from "../environments/runtime"; import { readPrimaryEnvironmentDescriptor, readPrimaryEnvironmentTarget, @@ -56,23 +61,22 @@ export class CloudEnvironmentLinkError extends Data.TaggedError("CloudEnvironmen readonly cause?: unknown; }> {} -const desktopRelayClientBridgeError = (cause: unknown) => +const relayClientRpcError = (message: string) => (cause: unknown) => new CloudEnvironmentLinkError({ - message: "Could not prepare the relay client.", + message, cause, }); -export function ensureDesktopRelayClientAvailable(): Effect.Effect< - void, - CloudEnvironmentLinkError -> { - const bridge = typeof window === "undefined" ? undefined : window.desktopBridge; - if (!bridge) return Effect.void; +const RELAY_CLIENT_INSTALL_PROMPT = + "T3 Code needs the relay client to make this environment available through T3 Cloud. Download and install it now?"; +function ensureRelayClientAvailable( + client: WsRpcClient, +): Effect.Effect { return Effect.gen(function* () { const status = yield* Effect.tryPromise({ - try: () => bridge.getRelayClientStatus(), - catch: desktopRelayClientBridgeError, + try: () => client.cloud.getRelayClientStatus(), + catch: relayClientRpcError("Could not check relay client availability."), }); if (status.status === "available") return; if (status.status === "unsupported") { @@ -82,11 +86,8 @@ export function ensureDesktopRelayClientAvailable(): Effect.Effect< } const confirmed = yield* Effect.tryPromise({ - try: () => - bridge.confirm( - "T3 Code needs the relay client to make this environment available through T3 Cloud. Download and install it now?", - ), - catch: desktopRelayClientBridgeError, + try: () => ensureLocalApi().dialogs.confirm(RELAY_CLIENT_INSTALL_PROMPT), + catch: relayClientRpcError("Could not confirm relay client installation."), }); if (!confirmed) { return yield* new CloudEnvironmentLinkError({ @@ -95,8 +96,8 @@ export function ensureDesktopRelayClientAvailable(): Effect.Effect< } const installed = yield* Effect.tryPromise({ - try: () => bridge.installRelayClient(), - catch: desktopRelayClientBridgeError, + try: () => client.cloud.installRelayClient(), + catch: relayClientRpcError("Could not install the relay client."), }); if (installed.status !== "available") { return yield* new CloudEnvironmentLinkError({ @@ -538,6 +539,17 @@ export function linkEnvironmentToCloud(input: { }); } + const connection = readEnvironmentConnection(input.environment.environmentId); + if (!connection) { + return yield* new CloudEnvironmentLinkError({ + message: `${input.environment.label} is not connected.`, + }); + } + yield* ensureRelayClientAvailable(connection.client); + + const environmentClient = yield* makeEnvironmentHttpApiClient(input.environment.httpBaseUrl); + const headers = { authorization: `Bearer ${bearerToken}` }; + const challenge = yield* relayClient .createEnvironmentLinkChallenge({ clerkToken: input.clerkToken, @@ -554,10 +566,9 @@ export function linkEnvironmentToCloud(input: { ), ), ); - const environmentClient = yield* makeEnvironmentHttpApiClient(input.environment.httpBaseUrl); const proof = yield* environmentClient.cloud .linkProof({ - headers: { authorization: `Bearer ${bearerToken}` }, + headers, payload: { challenge: challenge.challenge, relayIssuer: configuredRelayUrl, @@ -593,7 +604,7 @@ export function linkEnvironmentToCloud(input: { yield* environmentClient.cloud .relayConfig({ - headers: { authorization: `Bearer ${bearerToken}` }, + headers, payload: { relayUrl: configuredRelayUrl, relayIssuer: link.relayIssuer, @@ -624,7 +635,8 @@ export function linkPrimaryEnvironmentToCloud(input: { message: "Local environment is not ready yet.", }); } - yield* ensureDesktopRelayClientAvailable(); + const environmentClient = yield* makeEnvironmentHttpApiClient(target.httpBaseUrl); + yield* ensureRelayClientAvailable(getPrimaryEnvironmentConnection().client); const challenge = yield* relayClient .createEnvironmentLinkChallenge({ @@ -642,7 +654,6 @@ export function linkPrimaryEnvironmentToCloud(input: { ), ), ); - const environmentClient = yield* makeEnvironmentHttpApiClient(target.httpBaseUrl); const proof = yield* environmentClient.cloud .linkProof({ headers: {}, diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx index bed17319a7..e8f46505ed 100644 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -470,18 +470,6 @@ const createDesktopBridgeStub = (overrides?: { headers: {}, body: "", }), - getRelayClientStatus: vi.fn().mockResolvedValue({ - status: "available", - executablePath: "/usr/local/bin/cloudflared", - source: "path", - version: "2026.5.2", - }), - installRelayClient: vi.fn().mockResolvedValue({ - status: "available", - executablePath: "/usr/local/bin/cloudflared", - source: "path", - version: "2026.5.2", - }), onCloudAuthCallback: () => () => {}, onMenuAction: () => () => {}, getUpdateState: vi.fn().mockResolvedValue(idleUpdateState), diff --git a/apps/web/src/environments/runtime/service.threadSubscriptions.test.ts b/apps/web/src/environments/runtime/service.threadSubscriptions.test.ts index 33e2b0aa8c..675a486803 100644 --- a/apps/web/src/environments/runtime/service.threadSubscriptions.test.ts +++ b/apps/web/src/environments/runtime/service.threadSubscriptions.test.ts @@ -81,6 +81,10 @@ vi.mock("@t3tools/client-runtime", async (importOriginal) => { dispose: async () => undefined, reconnect: async () => undefined, isHeartbeatFresh: () => false, + cloud: { + getRelayClientStatus: vi.fn(), + installRelayClient: vi.fn(), + }, orchestration: { dispatchCommand: vi.fn(), getTurnDiff: vi.fn(), diff --git a/apps/web/src/localApi.test.ts b/apps/web/src/localApi.test.ts index 9b98055d5b..e50dbd9f5f 100644 --- a/apps/web/src/localApi.test.ts +++ b/apps/web/src/localApi.test.ts @@ -245,18 +245,6 @@ function makeDesktopBridge(overrides: Partial = {}): DesktopBridg headers: {}, body: "", }), - getRelayClientStatus: async () => ({ - status: "available", - executablePath: "/usr/local/bin/cloudflared", - source: "path", - version: "2026.5.2", - }), - installRelayClient: async () => ({ - status: "available", - executablePath: "/usr/local/bin/cloudflared", - source: "path", - version: "2026.5.2", - }), onCloudAuthCallback: () => () => undefined, onMenuAction: () => () => undefined, getUpdateState: async () => { diff --git a/packages/client-runtime/src/wsRpcClient.ts b/packages/client-runtime/src/wsRpcClient.ts index 407f840b46..c1c683616b 100644 --- a/packages/client-runtime/src/wsRpcClient.ts +++ b/packages/client-runtime/src/wsRpcClient.ts @@ -4,6 +4,8 @@ import { type GitRunStackedActionResult, type LocalApi, ORCHESTRATION_WS_METHODS, + type RelayClientInstallProgressEvent, + type RelayClientStatus, type ServerSettingsPatch, type VcsStatusResult, type VcsStatusStreamEvent, @@ -150,6 +152,12 @@ export interface WsRpcClient { >; readonly signalProcess: RpcUnaryMethod; }; + readonly cloud: { + readonly getRelayClientStatus: RpcUnaryNoArgMethod; + readonly installRelayClient: ( + onProgress?: (event: RelayClientInstallProgressEvent) => void, + ) => Promise; + }; readonly orchestration: { readonly dispatchCommand: RpcUnaryMethod; readonly getTurnDiff: RpcUnaryMethod; @@ -320,6 +328,26 @@ export function createWsRpcClient( signalProcess: (input) => transport.request((client) => client[WS_METHODS.serverSignalProcess](input)), }, + cloud: { + getRelayClientStatus: () => + transport.request((client) => client[WS_METHODS.cloudGetRelayClientStatus]({})), + installRelayClient: async (onProgress) => { + let installed: RelayClientStatus | null = null; + await transport.requestStream( + (client) => client[WS_METHODS.cloudInstallRelayClient]({}), + (event) => { + onProgress?.(event); + if (event.type === "complete") { + installed = event.status; + } + }, + ); + if (installed) { + return installed; + } + throw new Error("Relay client install stream completed without a final status."); + }, + }, orchestration: { dispatchCommand: (input) => transport.request((client) => client[ORCHESTRATION_WS_METHODS.dispatchCommand](input)), diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index bf26014c46..163d5e236c 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -2,6 +2,7 @@ export * from "./baseSchemas.ts"; export * from "./auth.ts"; export * from "./environment.ts"; export * from "./environmentHttp.ts"; +export * from "./relayClient.ts"; export * from "./desktopBootstrap.ts"; export * from "./remoteAccess.ts"; export * from "./ipc.ts"; diff --git a/packages/contracts/src/ipc.ts b/packages/contracts/src/ipc.ts index c7a4e6b5dc..56f929f7de 100644 --- a/packages/contracts/src/ipc.ts +++ b/packages/contracts/src/ipc.ts @@ -394,26 +394,6 @@ export const DesktopCloudAuthFetchResultSchema = Schema.Struct({ }); export type DesktopCloudAuthFetchResult = typeof DesktopCloudAuthFetchResultSchema.Type; -export const DesktopRelayClientStatusSchema = Schema.Union([ - Schema.Struct({ - status: Schema.Literal("available"), - executablePath: Schema.String, - source: Schema.Literals(["override", "managed", "path"]), - version: Schema.String, - }), - Schema.Struct({ - status: Schema.Literal("missing"), - version: Schema.String, - }), - Schema.Struct({ - status: Schema.Literal("unsupported"), - platform: Schema.String, - arch: Schema.String, - version: Schema.String, - }), -]); -export type DesktopRelayClientStatus = typeof DesktopRelayClientStatusSchema.Type; - export interface DesktopBridge { getAppBranding: () => DesktopAppBranding | null; getLocalEnvironmentBootstrap: () => DesktopEnvironmentBootstrap | null; @@ -464,8 +444,6 @@ export interface DesktopBridge { setCloudAuthToken: (token: string) => Promise; clearCloudAuthToken: () => Promise; fetchCloudAuth: (input: DesktopCloudAuthFetchInput) => Promise; - getRelayClientStatus: () => Promise; - installRelayClient: () => Promise; onCloudAuthCallback: (listener: (rawUrl: string) => void) => () => void; onMenuAction: (listener: (action: string) => void) => () => void; getUpdateState: () => Promise; diff --git a/packages/contracts/src/relayClient.ts b/packages/contracts/src/relayClient.ts new file mode 100644 index 0000000000..e78078d1ee --- /dev/null +++ b/packages/contracts/src/relayClient.ts @@ -0,0 +1,63 @@ +import * as Schema from "effect/Schema"; + +export const RelayClientStatusSchema = Schema.Union([ + Schema.Struct({ + status: Schema.Literal("available"), + executablePath: Schema.String, + source: Schema.Literals(["override", "managed", "path"]), + version: Schema.String, + }), + Schema.Struct({ + status: Schema.Literal("missing"), + version: Schema.String, + }), + Schema.Struct({ + status: Schema.Literal("unsupported"), + platform: Schema.String, + arch: Schema.String, + version: Schema.String, + }), +]); +export type RelayClientStatus = typeof RelayClientStatusSchema.Type; + +export const RelayClientInstallProgressStageSchema = Schema.Literals([ + "checking", + "waiting_for_lock", + "downloading", + "verifying", + "installing", + "validating", + "activating", +]); +export type RelayClientInstallProgressStage = typeof RelayClientInstallProgressStageSchema.Type; + +export const RelayClientInstallProgressEventSchema = Schema.Union([ + Schema.Struct({ + type: Schema.Literal("progress"), + stage: RelayClientInstallProgressStageSchema, + }), + Schema.Struct({ + type: Schema.Literal("complete"), + status: RelayClientStatusSchema, + }), +]); +export type RelayClientInstallProgressEvent = typeof RelayClientInstallProgressEventSchema.Type; + +export const RelayClientInstallFailureReasonSchema = Schema.Literals([ + "download_failed", + "invalid_checksum", + "install_locked", + "override_missing", + "unsupported_platform", + "validation_failed", + "write_failed", +]); +export type RelayClientInstallFailureReason = typeof RelayClientInstallFailureReasonSchema.Type; + +export class RelayClientInstallFailedError extends Schema.TaggedErrorClass()( + "RelayClientInstallFailedError", + { + reason: RelayClientInstallFailureReasonSchema, + message: Schema.String, + }, +) {} diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 814e403b64..5a145f3f65 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -58,6 +58,11 @@ import { OrchestrationRpcSchemas, } from "./orchestration.ts"; import { ProviderInstanceId } from "./providerInstance.ts"; +import { + RelayClientInstallFailedError, + RelayClientInstallProgressEventSchema, + RelayClientStatusSchema, +} from "./relayClient.ts"; import { ProjectSearchEntriesError, ProjectSearchEntriesInput, @@ -166,6 +171,10 @@ export const WS_METHODS = { serverGetProcessResourceHistory: "server.getProcessResourceHistory", serverSignalProcess: "server.signalProcess", + // Cloud environment methods + cloudGetRelayClientStatus: "cloud.getRelayClientStatus", + cloudInstallRelayClient: "cloud.installRelayClient", + // Source control methods sourceControlLookupRepository: "sourceControl.lookupRepository", sourceControlCloneRepository: "sourceControl.cloneRepository", @@ -263,6 +272,19 @@ export const WsServerSignalProcessRpc = Rpc.make(WS_METHODS.serverSignalProcess, error: EnvironmentAuthorizationError, }); +export const WsCloudGetRelayClientStatusRpc = Rpc.make(WS_METHODS.cloudGetRelayClientStatus, { + payload: Schema.Struct({}), + success: RelayClientStatusSchema, + error: EnvironmentAuthorizationError, +}); + +export const WsCloudInstallRelayClientRpc = Rpc.make(WS_METHODS.cloudInstallRelayClient, { + payload: Schema.Struct({}), + success: RelayClientInstallProgressEventSchema, + error: Schema.Union([RelayClientInstallFailedError, EnvironmentAuthorizationError]), + stream: true, +}); + export const WsSourceControlLookupRepositoryRpc = Rpc.make( WS_METHODS.sourceControlLookupRepository, { @@ -536,6 +558,8 @@ export const WsRpcGroup = RpcGroup.make( WsServerGetProcessDiagnosticsRpc, WsServerGetProcessResourceHistoryRpc, WsServerSignalProcessRpc, + WsCloudGetRelayClientStatusRpc, + WsCloudInstallRelayClientRpc, WsSourceControlLookupRepositoryRpc, WsSourceControlCloneRepositoryRpc, WsSourceControlPublishRepositoryRpc, diff --git a/packages/shared/src/relayClient.test.ts b/packages/shared/src/relayClient.test.ts index 1acdbea754..7e552194da 100644 --- a/packages/shared/src/relayClient.test.ts +++ b/packages/shared/src/relayClient.test.ts @@ -117,7 +117,14 @@ describe("RelayClient", () => { configProvider: emptyConfigProvider, }); - const installed = yield* manager.install; + const progress: Array = []; + const installed = yield* manager.installWithProgress((event) => + Effect.sync(() => { + if (event.type === "progress") { + progress.push(event.stage); + } + }), + ); const managedPath = resolveManagedCloudflaredPath({ baseDir, platform: "linux", @@ -132,6 +139,15 @@ describe("RelayClient", () => { expect(new TextDecoder().decode(yield* fileSystem.readFile(managedPath))).toBe( "test-cloudflared-binary", ); + expect(progress).toEqual([ + "checking", + "waiting_for_lock", + "downloading", + "verifying", + "installing", + "validating", + "activating", + ]); expect(yield* manager.resolve).toEqual(installed); }).pipe( Effect.scoped, diff --git a/packages/shared/src/relayClient.ts b/packages/shared/src/relayClient.ts index 7271f894ec..a73ec18317 100644 --- a/packages/shared/src/relayClient.ts +++ b/packages/shared/src/relayClient.ts @@ -1,4 +1,8 @@ import * as Clock from "effect/Clock"; +import type { + RelayClientInstallProgressEvent, + RelayClientInstallProgressStage, +} from "@t3tools/contracts"; import * as Config from "effect/Config"; import * as ConfigProvider from "effect/ConfigProvider"; import * as Context from "effect/Context"; @@ -125,6 +129,9 @@ export interface CloudflaredRelayClientOptions { export interface RelayClientShape { readonly resolve: Effect.Effect; readonly install: Effect.Effect; + readonly installWithProgress: ( + report: (event: RelayClientInstallProgressEvent) => Effect.Effect, + ) => Effect.Effect; } export class RelayClient extends Context.Service()( @@ -298,7 +305,9 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function const downloadAsset = Effect.fn("cloudflared.downloadAsset")(function* ( asset: CloudflaredReleaseAsset, + report: (stage: RelayClientInstallProgressStage) => Effect.Effect, ) { + yield* report("downloading"); const response = yield* httpClient.execute(HttpClientRequest.get(asset.url)).pipe( Effect.flatMap(HttpClientResponse.filterStatusOk), Effect.mapError( @@ -322,6 +331,7 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function ), ), ); + yield* report("verifying"); const checksum = yield* crypto.digest("SHA-256", bytes).pipe( Effect.mapError( (cause) => @@ -368,7 +378,10 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function }); }); - const installUnlocked: RelayClientShape["install"] = Effect.gen(function* () { + const installUnlocked = Effect.fn("cloudflared.installUnlocked")(function* ( + report: (stage: RelayClientInstallProgressStage) => Effect.Effect, + ) { + yield* report("checking"); const existing = yield* resolve; if (existing.status === "available") return existing; const config = yield* loadCloudflaredConfig; @@ -392,6 +405,7 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function .pipe( wrapInstallFailure("write_failed", "Could not create the relay client tool directory."), ); + yield* report("waiting_for_lock"); yield* acquireInstallLock(lockPath).pipe( Effect.catchTag("PlatformError", (cause) => Effect.fail( @@ -415,8 +429,10 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function tempDirectory, releaseAsset.archive === "tgz" ? "cloudflared.tgz" : executableFileName(platform), ); + const download = yield* downloadAsset(releaseAsset, report); + yield* report("installing"); yield* fileSystem - .writeFile(archivePath, yield* downloadAsset(releaseAsset)) + .writeFile(archivePath, download) .pipe(wrapInstallFailure("write_failed", "Could not write the relay client download.")); const executablePath = path.join(tempDirectory, executableFileName(platform)); @@ -430,11 +446,13 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function .chmod(executablePath, 0o755) .pipe(wrapInstallFailure("write_failed", "Could not make the relay client executable.")); } + yield* report("validating"); yield* runCommand(executablePath, ["--version"]).pipe( wrapInstallFailure("validation_failed", "The downloaded relay client binary did not run."), ); const stagedPath = `${managedPath}.${yield* crypto.randomUUIDv4}.tmp`; + yield* report("activating"); yield* fileSystem .rename(executablePath, stagedPath) .pipe(wrapInstallFailure("write_failed", "Could not stage the relay client.")); @@ -466,9 +484,18 @@ export const makeCloudflaredRelayClient = Effect.fn("cloudflared.make")(function ), ); }); - const install = installSemaphore.withPermit(installUnlocked); + const installWithProgress: RelayClientShape["installWithProgress"] = (report) => + installSemaphore.withPermit( + installUnlocked((stage) => + report({ + type: "progress", + stage, + }), + ), + ); + const install = installWithProgress(() => Effect.void); - return RelayClient.of({ resolve, install }); + return RelayClient.of({ resolve, install, installWithProgress }); }); export const layerCloudflared = (options: CloudflaredRelayClientOptions) =>