feat(cloud): stream relay client installation over rpc

Co-authored-by: codex <[email protected]>
This commit is contained in:
Julius Marmingeandcodex committed 2026-06-03 23:48:05 -07:00
1 parent 944e73ff9a
commit 5bb5be63ac
22 files changed
+393 -217

No files matched your search

@@ -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);
-2
View File
@@ -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";
@@ -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<boolean> = [];
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]);
}),
);
});
@@ -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;
}),
});
+1 -17
View File
@@ -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(() =>
-2
View File
@@ -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;
@@ -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"),
}),
),
),
+62
View File
@@ -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<ServerEnvironmentShape>;
repositoryIdentityResolver?: Partial<RepositoryIdentityResolverShape>;
cloudManagedEndpointRuntime?: Partial<CloudManagedEndpointRuntimeShape>;
relayClient?: Partial<RelayClient.RelayClientShape>;
};
}) =>
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();
+9 -6
View File
@@ -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(
+40
View File
@@ -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<string, AuthEnvironmentScope>([
[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<RelayClientInstallProgressEvent, RelayClientInstallFailedError>(
(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,
+77 -42
View File
@@ -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 = <A, E>(
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",
);
+34 -23
View File
@@ -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<void, CloudEnvironmentLinkError> {
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: {},
@@ -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),
@@ -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(),
-12
View File
@@ -245,18 +245,6 @@ function makeDesktopBridge(overrides: Partial<DesktopBridge> = {}): 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 () => {
@@ -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<typeof WS_METHODS.serverSignalProcess>;
};
readonly cloud: {
readonly getRelayClientStatus: RpcUnaryNoArgMethod<typeof WS_METHODS.cloudGetRelayClientStatus>;
readonly installRelayClient: (
onProgress?: (event: RelayClientInstallProgressEvent) => void,
) => Promise<RelayClientStatus>;
};
readonly orchestration: {
readonly dispatchCommand: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.dispatchCommand>;
readonly getTurnDiff: RpcUnaryMethod<typeof ORCHESTRATION_WS_METHODS.getTurnDiff>;
@@ -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)),
+1
View File
@@ -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";
-22
View File
@@ -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<boolean>;
clearCloudAuthToken: () => Promise<void>;
fetchCloudAuth: (input: DesktopCloudAuthFetchInput) => Promise<DesktopCloudAuthFetchResult>;
getRelayClientStatus: () => Promise<DesktopRelayClientStatus>;
installRelayClient: () => Promise<DesktopRelayClientStatus>;
onCloudAuthCallback: (listener: (rawUrl: string) => void) => () => void;
onMenuAction: (listener: (action: string) => void) => () => void;
getUpdateState: () => Promise<DesktopUpdateState>;
+63
View File
@@ -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>()(
"RelayClientInstallFailedError",
{
reason: RelayClientInstallFailureReasonSchema,
message: Schema.String,
},
) {}
+24
View File
@@ -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,
+17 -1
View File
@@ -117,7 +117,14 @@ describe("RelayClient", () => {
configProvider: emptyConfigProvider,
});
const installed = yield* manager.install;
const progress: Array<string> = [];
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,
+31 -4
View File
@@ -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<RelayClientStatus>;
readonly install: Effect.Effect<AvailableRelayClient, RelayClientInstallError>;
readonly installWithProgress: (
report: (event: RelayClientInstallProgressEvent) => Effect.Effect<void>,
) => Effect.Effect<AvailableRelayClient, RelayClientInstallError>;
}
export class RelayClient extends Context.Service<RelayClient, RelayClientShape>()(
@@ -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<void>,
) {
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<void>,
) {
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) =>