feat(render): pair cloud environments in app

This commit is contained in:
Shivam Sharma committed 2026-08-05 10:07:55 +05:30
1 parent 8535bb3d67
commit 47b65e7e7b
15 files changed
+529 -142

No files matched your search

+8
View File
@@ -12,3 +12,11 @@ release-mock
artifacts
native/**/target
*.log
.env
.env.*
!.env.example
*.key
*.pem
auth.json
.codex
.claude
+76
View File
@@ -0,0 +1,76 @@
import * as NodeCrypto from "node:crypto";
import {
EnvironmentHttpApi,
EnvironmentHttpForbiddenError,
EnvironmentHttpInternalServerError,
EnvironmentHttpUnauthorizedError,
} from "@t3tools/contracts";
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import * as Effect from "effect/Effect";
import * as HttpEffect from "effect/unstable/http/HttpEffect";
import { HttpServerResponse } from "effect/unstable/http";
import * as HttpApiBuilder from "effect/unstable/httpapi/HttpApiBuilder";
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
const RENDER_BOOTSTRAP_RESPONSE_HEADERS = {
"cache-control": "no-store",
pragma: "no-cache",
"referrer-policy": "no-referrer",
"x-content-type-options": "nosniff",
} as const;
export function renderSetupCodeMatches(expected: string, candidate: string): boolean {
const expectedDigest = NodeCrypto.createHash("sha256").update(expected).digest();
const candidateDigest = NodeCrypto.createHash("sha256").update(candidate).digest();
return NodeCrypto.timingSafeEqual(expectedDigest, candidateDigest);
}
const appendRenderBootstrapResponseHeaders = HttpEffect.appendPreResponseHandler(
(_request, response) =>
Effect.succeed(HttpServerResponse.setHeaders(response, RENDER_BOOTSTRAP_RESPONSE_HEADERS)),
);
export const renderBootstrapHttpApiLayer = HttpApiBuilder.group(
EnvironmentHttpApi,
"renderBootstrap",
Effect.fnUntraced(function* (handlers) {
const hostEnvironment = yield* HostProcessEnvironment;
const serverAuth = yield* EnvironmentAuth.EnvironmentAuth;
const configuredProvider = hostEnvironment.T3CODE_CLOUD_PROVIDER?.trim().toLowerCase();
const configuredSetupCode = hostEnvironment.T3CODE_RENDER_SETUP_CODE?.trim() ?? "";
const environmentLabel =
hostEnvironment.T3CODE_ENVIRONMENT_LABEL?.trim() || "Render cloud environment";
delete hostEnvironment.T3CODE_RENDER_SETUP_CODE;
return handlers.handle(
"pair",
Effect.fn("environment.renderBootstrap.pair")(function* ({ payload }) {
yield* appendRenderBootstrapResponseHeaders;
if (configuredProvider !== "render" || configuredSetupCode.length === 0) {
return yield* new EnvironmentHttpForbiddenError({
message: "This environment is not configured for Render setup.",
});
}
if (!renderSetupCodeMatches(configuredSetupCode, payload.setupCode)) {
return yield* new EnvironmentHttpUnauthorizedError({
message: "The Render setup code is invalid.",
});
}
const issued = yield* serverAuth.issuePairingCredential({ label: "Render setup" }).pipe(
Effect.mapError(
() =>
new EnvironmentHttpInternalServerError({
message: "Could not create a Render pairing credential.",
}),
),
);
return {
pairingCode: issued.credential,
label: environmentLabel,
};
}),
);
}),
);
+42 -1
View File
@@ -2,7 +2,7 @@ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
import * as NodeSocket from "@effect/platform-node/NodeSocket";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as NodeCrypto from "node:crypto";
import { HostProcessPlatform } from "@t3tools/shared/hostProcess";
import { HostProcessEnvironment, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import {
AuthAccessTokenType,
@@ -327,6 +327,7 @@ const makeBrowserOtlpPayload = (spanName: string) =>
const buildAppUnderTest = (options?: {
config?: Partial<ServerConfig.ServerConfig["Service"]>;
hostEnvironment?: NodeJS.ProcessEnv;
layers?: {
keybindings?: Partial<Keybindings.Keybindings["Service"]>;
providerRegistry?: Partial<ProviderRegistry.ProviderRegistry["Service"]>;
@@ -891,6 +892,7 @@ const buildAppUnderTest = (options?: {
Layer.provideMerge(ServerSecretStore.layer),
Layer.provide(workspaceAndProjectServicesLayer),
Layer.provideMerge(FetchHttpClient.layer),
Layer.provide(Layer.succeed(HostProcessEnvironment, options?.hostEnvironment ?? process.env)),
Layer.provide(layerConfig),
);
@@ -1396,6 +1398,45 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("pairs a Render environment from its setup code without reading logs", () =>
Effect.gen(function* () {
yield* buildAppUnderTest({
hostEnvironment: {
T3CODE_CLOUD_PROVIDER: "render",
T3CODE_ENVIRONMENT_LABEL: "Render cloud environment",
T3CODE_RENDER_SETUP_CODE: "render-setup-code-1234",
},
});
const url = yield* getHttpServerUrl("/.well-known/t3/render/pair");
const rejected = yield* fetchEffect(url, {
method: "POST",
headers: { "content-type": "application/json" },
body: jsonRequestBody({ setupCode: "wrong-code" }),
});
const response = yield* fetchEffect(url, {
method: "POST",
headers: { "content-type": "application/json" },
body: jsonRequestBody({ setupCode: "render-setup-code-1234" }),
});
const body = yield* responseJsonEffect<{
readonly pairingCode: string;
readonly label: string;
}>(response);
const exchanged = yield* exchangeAccessToken(body.pairingCode, {
scope: "orchestration:read orchestration:operate terminal:operate review:write relay:read",
});
assert.equal(rejected.status, 401);
assert.equal(response.status, 200);
assert.equal(response.headers["cache-control"], "no-store");
assert.equal(response.headers["referrer-policy"], "no-referrer");
assert.equal(body.label, "Render cloud environment");
assert.isAbove(body.pairingCode.length, 0);
assert.equal(exchanged.response.status, 200);
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("compresses large JSON responses through the composed routes", () =>
Effect.gen(function* () {
const descriptor = {
+2
View File
@@ -79,6 +79,7 @@ import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts
import { ObservabilityLive } from "./observability/Layers/Observability.ts";
import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
import { authHttpApiLayer, environmentAuthenticatedAuthLayer } from "./auth/http.ts";
import { renderBootstrapHttpApiLayer } from "./render/http.ts";
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts";
import {
@@ -428,6 +429,7 @@ export const makeRoutesLayer = Layer.mergeAll(
Layer.mergeAll(
HttpApiBuilder.layer(EnvironmentHttpApi).pipe(
Layer.provide(authHttpApiLayer),
Layer.provide(renderBootstrapHttpApiLayer),
Layer.provide(connectHttpApiLayer),
Layer.provide(orchestrationHttpApiLayer),
Layer.provide(serverEnvironmentHttpApiLayer),
@@ -0,0 +1,65 @@
import { describe, expect, it, vi } from "vite-plus/test";
import {
maskedRenderServiceUrl,
normalizeRenderServiceUrl,
RenderBootstrapRequestError,
requestRenderPairing,
} from "./renderBootstrap";
describe("normalizeRenderServiceUrl", () => {
it("accepts a bare Render hostname and keeps only its origin", () => {
expect(normalizeRenderServiceUrl("demo.onrender.com/path")).toBe("https://demo.onrender.com");
});
it("rejects Render dashboard URLs", () => {
expect(() => normalizeRenderServiceUrl("https://dashboard.render.com/web/srv-123")).toThrow(
"not the Render dashboard URL",
);
});
it("masks long service hostnames", () => {
expect(maskedRenderServiceUrl("https://t3code-cloud-demo-eg5i.onrender.com")).toBe(
"t3code-cloud-…i.onrender.com",
);
});
});
describe("requestRenderPairing", () => {
it("claims a one-time pairing credential from the service URL", async () => {
const fetcher = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>
Response.json({ pairingCode: "pairing-code", label: "Render cloud environment" }),
);
await expect(
requestRenderPairing({
serviceUrl: "demo.onrender.com",
setupCode: "setup-code",
fetcher,
}),
).resolves.toEqual({
host: "https://demo.onrender.com",
pairingCode: "pairing-code",
label: "Render cloud environment",
});
expect(fetcher).toHaveBeenCalledOnce();
expect(fetcher.mock.calls[0]?.[0].toString()).toBe(
"https://demo.onrender.com/.well-known/t3/render/pair",
);
});
it("explains a mismatched setup code", async () => {
const fetcher = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>
Response.json({ message: "invalid" }, { status: 401 }),
);
const failure = await requestRenderPairing({
serviceUrl: "https://demo.onrender.com",
setupCode: "wrong-code",
fetcher,
}).catch((error: unknown) => error);
expect(failure).toBeInstanceOf(RenderBootstrapRequestError);
expect((failure as Error).message).toContain("does not match");
});
});
+100
View File
@@ -0,0 +1,100 @@
import { EnvironmentRenderBootstrapPairingResult } from "@t3tools/contracts";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
const RenderBootstrapErrorBody = Schema.Struct({ message: Schema.String });
const decodeRenderBootstrapErrorBody = Schema.decodeUnknownOption(RenderBootstrapErrorBody);
const decodeRenderBootstrapPairingResult = Schema.decodeUnknownSync(
EnvironmentRenderBootstrapPairingResult,
);
export class RenderBootstrapRequestError extends Error {
readonly status: number | null;
constructor(message: string, status: number | null = null) {
super(message);
this.name = "RenderBootstrapRequestError";
this.status = status;
}
}
export function normalizeRenderServiceUrl(value: string): string {
const candidate = value.trim();
if (candidate.length === 0) {
throw new RenderBootstrapRequestError("Enter the Render service URL.");
}
let url: URL;
try {
url = new URL(/^https?:\/\//iu.test(candidate) ? candidate : `https://${candidate}`);
} catch {
throw new RenderBootstrapRequestError("Enter a valid Render service URL.");
}
if (url.protocol !== "https:") {
throw new RenderBootstrapRequestError("Render service URLs must use HTTPS.");
}
if (url.hostname.toLowerCase() === "dashboard.render.com") {
throw new RenderBootstrapRequestError(
"Paste the service's .onrender.com URL, not the Render dashboard URL.",
);
}
return url.origin;
}
export function maskedRenderServiceUrl(value: string): string {
try {
const hostname = new URL(value).hostname;
if (hostname.length <= 28) return hostname;
return `${hostname.slice(0, 13)}…${hostname.slice(-14)}`;
} catch {
return "Render service";
}
}
export async function requestRenderPairing(input: {
readonly serviceUrl: string;
readonly setupCode: string;
readonly fetcher?: typeof globalThis.fetch;
}): Promise<{ readonly host: string; readonly pairingCode: string; readonly label: string }> {
const host = normalizeRenderServiceUrl(input.serviceUrl);
const setupCode = input.setupCode.trim();
if (setupCode.length === 0) {
throw new RenderBootstrapRequestError("Enter the setup code used during deployment.");
}
const endpoint = new URL("/.well-known/t3/render/pair", host);
let response: Response;
try {
response = await (input.fetcher ?? globalThis.fetch)(endpoint, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ setupCode }),
cache: "no-store",
referrerPolicy: "no-referrer",
});
} catch {
throw new RenderBootstrapRequestError(
"Could not reach the Render service. A free instance can take about a minute to wake up.",
);
}
const responseBody: unknown = await response.json().catch(() => null);
if (!response.ok) {
const decodedError = decodeRenderBootstrapErrorBody(responseBody);
const serverMessage = Option.isSome(decodedError) ? decodedError.value.message : null;
const message =
response.status === 401
? "The setup code does not match the Render service."
: response.status === 403 || response.status === 404
? "This service does not have in-app Render pairing yet. Deploy the latest version."
: serverMessage || `Render pairing failed with HTTP ${response.status}.`;
throw new RenderBootstrapRequestError(message, response.status);
}
try {
const pairing = decodeRenderBootstrapPairingResult(responseBody);
return { host, pairingCode: pairing.pairingCode, label: pairing.label };
} catch {
throw new RenderBootstrapRequestError("The Render service returned an invalid pairing reply.");
}
}
+2 -2
View File
@@ -29,7 +29,6 @@ import { useNavigate, useParams } from "@tanstack/react-router";
import * as Option from "effect/Option";
import {
ArrowLeftIcon,
CloudIcon,
CornerLeftUpIcon,
FileSearchIcon,
FolderIcon,
@@ -120,6 +119,7 @@ import { CommandPaletteContent } from "./CommandPaletteContent";
import { CommandPaletteResults } from "./CommandPaletteResults";
import { AzureDevOpsIcon, BitbucketIcon, GitHubIcon, GitLabIcon } from "./Icons";
import { ProjectFavicon } from "./ProjectFavicon";
import { RenderLogo } from "./RenderLogo";
import { ProjectFilePicker } from "./files/ProjectFilePicker";
import { ProjectContentSearchDialog } from "./search/ProjectContentSearchDialog";
import { ThreadRowLeadingStatus, ThreadRowTrailingStatus } from "./ThreadStatusIndicators";
@@ -1288,7 +1288,7 @@ function OpenCommandPaletteDialog(props: {
: option.status,
disabled: !option.isConnected,
icon: option.cloudProvider ? (
<CloudIcon className={ITEM_ICON_CLASS} />
<RenderLogo className={ITEM_ICON_CLASS} />
) : (
<FolderPlusIcon className={ITEM_ICON_CLASS} />
),
+13
View File
@@ -0,0 +1,13 @@
import type { ComponentPropsWithoutRef } from "react";
/** Monochrome Render logomark from Render's official brand kit. */
export function RenderLogo(props: ComponentPropsWithoutRef<"svg">) {
return (
<svg viewBox="206 194 400 400" fill="none" aria-hidden="true" {...props}>
<path
fill="currentColor"
d="M605.28 288.733C605.221 287.368 605.102 286.033 604.984 284.668C604.954 284.342 604.954 283.986 604.894 283.659C604.805 282.829 604.687 282.027 604.568 281.197C604.449 280.336 604.36 279.506 604.241 278.675C604.152 278.082 604.034 277.488 603.915 276.924C603.737 275.886 603.559 274.818 603.351 273.78C603.173 272.949 602.965 272.148 602.787 271.317C602.609 270.516 602.431 269.745 602.253 268.944C602.045 268.113 601.778 267.312 601.54 266.481C601.333 265.71 601.125 264.968 600.887 264.197C600.62 263.366 600.323 262.535 600.027 261.704C599.789 260.992 599.552 260.28 599.314 259.568C598.928 258.53 598.513 257.521 598.127 256.512C597.919 256.008 597.741 255.533 597.533 255.029C597.058 253.931 596.584 252.863 596.079 251.795C595.901 251.409 595.723 250.994 595.545 250.608C595.07 249.599 594.535 248.62 594.031 247.641C593.793 247.196 593.586 246.751 593.348 246.306C592.755 245.208 592.102 244.111 591.478 243.043C591.3 242.746 591.152 242.449 590.974 242.153C590.291 241.025 589.579 239.927 588.837 238.83C588.688 238.592 588.54 238.355 588.391 238.118C587.501 236.812 586.581 235.507 585.631 234.231C584.741 233.044 583.82 231.857 582.871 230.7C582.811 230.611 582.752 230.522 582.663 230.433C564.319 208.211 536.626 194.089 505.609 194.059V194L505.52 194.059H505.549C496.942 194.059 488.571 195.157 480.587 197.204C475.808 198.421 471.148 200.023 466.666 201.892C465.182 202.515 463.698 203.197 462.243 203.88C432.769 218.061 411.398 246.306 406.679 279.891H406.62C404.542 294.281 400.119 307.899 393.827 320.419H394.035C372.129 363.854 327.132 393.671 275.129 393.671C251.918 393.671 230.131 387.738 211.135 377.324C208.909 376.107 206.208 377.71 206.208 380.231V393.671H206V593.254H405.7V493.448H405.907V443.545C405.907 415.982 428.258 393.642 455.832 393.642H505.757C514.305 393.642 522.587 392.544 530.512 390.497C535.291 389.251 539.951 387.678 544.433 385.809C545.917 385.186 547.401 384.504 548.855 383.821C579.398 369.106 601.303 339.288 604.894 304.071C605.221 300.719 605.399 297.307 605.399 293.865C605.399 292.145 605.369 290.424 605.28 288.733Z"
/>
</svg>
);
}
@@ -1,21 +1,28 @@
import { CheckIcon, CloudIcon, CopyIcon, ExternalLinkIcon, LoaderCircleIcon } from "lucide-react";
import { connectionStatusText } from "@t3tools/client-runtime/connection";
import {
isAtomCommandInterrupted,
squashAtomCommandFailure,
} from "@t3tools/client-runtime/state/runtime";
import type { EnvironmentId } from "@t3tools/contracts";
import {
CheckIcon,
CopyIcon,
ExternalLinkIcon,
LoaderCircleIcon,
RefreshCwIcon,
} from "lucide-react";
import { useCallback, useMemo, useState } from "react";
import { cloudEnvironmentProvider } from "~/cloud/cloudEnvironment";
import { maskedRenderServiceUrl, requestRenderPairing } from "~/cloud/renderBootstrap";
import { openCommandPalette } from "~/commandPaletteBus";
import { environmentCatalog } from "~/connection/catalog";
import { connectPairing as connectPairingAtom } from "~/connection/onboarding";
import { readHostedPairingRequest } from "~/hostedPairing";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { getPairingTokenFromUrl } from "~/pairingUrl";
import { randomHex } from "~/lib/utils";
import { useAtomCommand } from "~/state/use-atom-command";
import { type EnvironmentPresentation, useEnvironments } from "~/state/environments";
import { RenderLogo } from "../RenderLogo";
import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { stackedThreadToast, toastManager } from "../ui/toast";
@@ -27,56 +34,73 @@ const RENDER_DEPLOY_URL =
const CODEX_LOGIN_COMMAND = "codex login --device-auth";
type RenderAuthenticationMode = "api-key" | "subscription";
function pairingInput(value: string): { readonly host: string; readonly pairingCode: string } {
const url = new URL(value.trim());
const hostedRequest = readHostedPairingRequest(url);
if (hostedRequest) {
return { host: hostedRequest.host, pairingCode: hostedRequest.token };
}
const pairingCode = getPairingTokenFromUrl(url);
if (!pairingCode) {
throw new Error("Paste the full Pair URL from the Render logs.");
}
return { host: url.origin, pairingCode };
function newRenderSetupCode(): string {
return `t3-${randomHex(10)}`;
}
function CopyValueButton({ value, label }: { readonly value: string; readonly label: string }) {
const { copyToClipboard, isCopied } = useCopyToClipboard({ target: label });
return (
<Button
size="icon-sm"
variant="outline"
aria-label={`Copy ${label}`}
onClick={() => copyToClipboard(value, undefined)}
>
{isCopied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />}
</Button>
);
}
function CopyCommand({ command }: { readonly command: string }) {
const { copyToClipboard, isCopied } = useCopyToClipboard({ target: "command" });
return (
<div className="mt-2 flex min-w-0 items-start gap-2 rounded-lg border border-border/70 bg-muted/20 p-2">
<code className="min-w-0 flex-1 overflow-x-auto py-1 text-xs text-foreground">{command}</code>
<Button
size="icon-xs"
variant="ghost"
aria-label="Copy command"
onClick={() => copyToClipboard(command, undefined)}
>
{isCopied ? <CheckIcon className="size-3.5" /> : <CopyIcon className="size-3.5" />}
</Button>
<CopyValueButton value={command} label="command" />
</div>
);
}
function RenderEnvironmentRow({
environment,
busyEnvironmentId,
busyEnvironmentIds,
onConnect,
onDisconnect,
}: {
readonly environment: EnvironmentPresentation;
readonly busyEnvironmentId: EnvironmentId | null;
readonly busyEnvironmentIds: ReadonlySet<EnvironmentId>;
readonly onConnect: (environmentId: EnvironmentId) => void;
readonly onDisconnect: (environmentId: EnvironmentId) => void;
}) {
const isConnected = environment.connection.phase === "connected";
const isBusy = busyEnvironmentId === environment.environmentId;
const isBusy = busyEnvironmentIds.has(environment.environmentId);
const serviceLabel = environment.displayUrl
? maskedRenderServiceUrl(environment.displayUrl)
: null;
return (
<SettingsRow
title={environment.label}
title={
<span className="inline-flex items-center gap-2">
<RenderLogo className="size-4" />
{environment.label}
</span>
}
description="Powered by Render"
status={connectionStatusText(environment.connection)}
status={[connectionStatusText(environment.connection), serviceLabel]
.filter(Boolean)
.join(" · ")}
control={
<>
{environment.displayUrl ? (
<Button
size="icon-xs"
variant="ghost"
aria-label="Open Render service"
render={<a href={environment.displayUrl} target="_blank" rel="noreferrer" />}
>
<ExternalLinkIcon className="size-3.5" />
</Button>
) : null}
{isConnected ? (
<Button
size="xs"
@@ -110,10 +134,14 @@ export function CloudEnvironmentsSettings() {
const connectPairing = useAtomCommand(connectPairingAtom, { reportFailure: false });
const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, { reportFailure: false });
const removeEnvironment = useAtomCommand(environmentCatalog.remove, { reportFailure: false });
const [pairUrl, setPairUrl] = useState("");
const [serviceUrl, setServiceUrl] = useState("");
const [setupCode, setSetupCode] = useState(newRenderSetupCode);
const [pairing, setPairing] = useState(false);
const [pairingStatus, setPairingStatus] = useState<string | null>(null);
const [pairError, setPairError] = useState<string | null>(null);
const [busyEnvironmentId, setBusyEnvironmentId] = useState<EnvironmentId | null>(null);
const [busyEnvironmentIds, setBusyEnvironmentIds] = useState<ReadonlySet<EnvironmentId>>(
() => new Set(),
);
const [authenticationMode, setAuthenticationMode] = useState<RenderAuthenticationMode>("api-key");
const renderEnvironments = useMemo(
() => environments.filter((environment) => cloudEnvironmentProvider(environment) === "render"),
@@ -127,34 +155,49 @@ export function CloudEnvironmentsSettings() {
toastManager.add(stackedThreadToast({ type: "error", title, description }));
}, []);
const setEnvironmentBusy = useCallback((environmentId: EnvironmentId, busy: boolean) => {
setBusyEnvironmentIds((current) => {
const next = new Set(current);
if (busy) next.add(environmentId);
else next.delete(environmentId);
return next;
});
}, []);
const handlePair = useCallback(async () => {
if (pairing) return;
setPairError(null);
let input: ReturnType<typeof pairingInput>;
try {
input = pairingInput(pairUrl);
} catch (error) {
setPairError(error instanceof Error ? error.message : "Invalid Pair URL.");
return;
}
setPairing(true);
const result = await connectPairing(input);
setPairing(false);
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
const failure = squashAtomCommandFailure(result);
setPairError(failure instanceof Error ? failure.message : "Could not pair environment.");
setPairingStatus("Waking the Render service…");
try {
const pairingInput = await requestRenderPairing({ serviceUrl, setupCode });
setServiceUrl(pairingInput.host);
setPairingStatus("Connecting T3 Code…");
const result = await connectPairing({
host: pairingInput.host,
pairingCode: pairingInput.pairingCode,
});
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
const failure = squashAtomCommandFailure(result);
setPairError(failure instanceof Error ? failure.message : "Could not pair environment.");
}
return;
}
return;
toastManager.add({ type: "success", title: "Render environment connected" });
} catch (error) {
setPairError(error instanceof Error ? error.message : "Could not connect Render.");
} finally {
setPairing(false);
setPairingStatus(null);
}
setPairUrl("");
toastManager.add({ type: "success", title: "Render environment connected" });
}, [connectPairing, pairUrl]);
}, [connectPairing, pairing, serviceUrl, setupCode]);
const handleConnect = useCallback(
async (environmentId: EnvironmentId) => {
setBusyEnvironmentId(environmentId);
setEnvironmentBusy(environmentId, true);
const result = await retryEnvironment(environmentId);
setBusyEnvironmentId(null);
setEnvironmentBusy(environmentId, false);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const failure = squashAtomCommandFailure(result);
reportFailure(
@@ -163,14 +206,14 @@ export function CloudEnvironmentsSettings() {
);
}
},
[reportFailure, retryEnvironment],
[reportFailure, retryEnvironment, setEnvironmentBusy],
);
const handleDisconnect = useCallback(
async (environmentId: EnvironmentId) => {
setBusyEnvironmentId(environmentId);
setEnvironmentBusy(environmentId, true);
const result = await removeEnvironment(environmentId);
setBusyEnvironmentId(null);
setEnvironmentBusy(environmentId, false);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const failure = squashAtomCommandFailure(result);
reportFailure(
@@ -179,22 +222,40 @@ export function CloudEnvironmentsSettings() {
);
}
},
[removeEnvironment, reportFailure],
[removeEnvironment, reportFailure, setEnvironmentBusy],
);
return (
<SettingsPageContainer>
<SettingsSection
{...searchableSetting("cloud-environments")}
icon={<CloudIcon className="size-4" />}
icon={<RenderLogo className="size-5" />}
>
<SettingsRow
title="Powered by Render"
description="Creates a temporary free cloud machine for the demo."
/>
<div className="mx-3 overflow-hidden rounded-2xl border border-border/70 bg-gradient-to-br from-muted/45 via-background to-background px-5 py-5 sm:mx-4 sm:px-6">
<div className="flex items-start gap-4">
<div className="flex size-11 shrink-0 items-center justify-center rounded-xl bg-foreground text-background shadow-sm">
<RenderLogo className="size-6" />
</div>
<div className="min-w-0 space-y-1">
<h3 className="text-base font-semibold tracking-[-0.02em]">Powered by Render</h3>
<p className="max-w-xl text-sm leading-relaxed text-muted-foreground">
Deploy a temporary T3 Code machine, connect it here, and run agents on a public
GitHub repository.
</p>
<div className="flex flex-wrap gap-2 pt-2 text-[11px] font-medium text-muted-foreground">
<span className="rounded-full border border-border/70 bg-background/70 px-2 py-1">
Free demo
</span>
<span className="rounded-full border border-border/70 bg-background/70 px-2 py-1">
No logs required
</span>
</div>
</div>
</div>
</div>
</SettingsSection>
<SettingsSection title="Authenticate and deploy">
<SettingsSection title="1. Deploy">
<div className="px-3 sm:px-4">
<div
role="tablist"
@@ -221,18 +282,46 @@ export function CloudEnvironmentsSettings() {
</button>
</div>
</div>
<SettingsRow
title="Setup code"
description="Copy this into T3CODE_RENDER_SETUP_CODE when Render asks. It lets this screen pair the service without reading logs."
status="Keep it private until the demo is over."
>
<div className="mt-3 flex gap-2">
<Input
value={setupCode}
onChange={(event) => setSetupCode(event.target.value)}
aria-label="Render setup code"
autoComplete="off"
spellCheck={false}
className="font-mono text-xs"
/>
<CopyValueButton value={setupCode} label="Render setup code" />
<Button
size="icon-sm"
variant="outline"
aria-label="Generate a new setup code"
disabled={pairing}
onClick={() => setSetupCode(newRenderSetupCode())}
>
<RefreshCwIcon className="size-3.5" />
</Button>
</div>
</SettingsRow>
{authenticationMode === "api-key" ? (
<div role="tabpanel">
<SettingsRow
title="OpenAI API key"
description="Render asks for OPENAI_API_KEY before deploying and stores it as a secret. Codex is authenticated automatically when the service starts."
status="API usage is billed by OpenAI separately from Render."
description="Render asks for OPENAI_API_KEY and the setup code. Codex is authenticated automatically when the service starts."
status="OpenAI API usage is billed separately from Render."
control={
<Button
size="sm"
render={<a href={RENDER_DEPLOY_URL} target="_blank" rel="noreferrer" />}
>
Deploy with API key
Deploy on Render
<ExternalLinkIcon className="size-3.5" />
</Button>
}
@@ -242,15 +331,15 @@ export function CloudEnvironmentsSettings() {
<div role="tabpanel">
<SettingsRow
title="ChatGPT subscription"
description="Deploy without an API key. After pairing and cloning a project, run this in its T3 terminal and complete the device login."
status="Free instances forget this login when they restart or spin down."
description="Leave OPENAI_API_KEY empty. After connecting and adding a project, run the command below in its T3 terminal."
status="A free instance forgets this login whenever it restarts or spins down."
control={
<Button
size="sm"
variant="outline"
render={<a href={RENDER_DEPLOY_URL} target="_blank" rel="noreferrer" />}
>
Deploy for subscription
Deploy on Render
<ExternalLinkIcon className="size-3.5" />
</Button>
}
@@ -261,26 +350,29 @@ export function CloudEnvironmentsSettings() {
)}
</SettingsSection>
<SettingsSection title="Connect">
<SettingsSection title="2. Connect in T3 Code">
<SettingsRow
title="Pair URL"
description="Connects this T3 Code client to the cloud machine. Copy the URL from the Render logs."
title="Render service URL"
description="Paste the .onrender.com URL shown at the top of the Render service. T3 Code pairs it here automatically."
status={pairingStatus}
>
<div className="mt-3 flex flex-col gap-2 sm:flex-row">
<Input
value={pairUrl}
onChange={(event) => setPairUrl(event.target.value)}
placeholder="https://app.t3.codes/pair?host=..."
value={serviceUrl}
onChange={(event) => setServiceUrl(event.target.value)}
placeholder="https://your-service.onrender.com"
autoComplete="url"
spellCheck={false}
onKeyDown={(event) => {
if (event.key === "Enter") void handlePair();
if (event.key === "Enter" && !pairing) void handlePair();
}}
/>
<Button
disabled={pairing || pairUrl.trim().length === 0}
disabled={pairing || serviceUrl.trim().length === 0 || setupCode.trim().length === 0}
onClick={() => void handlePair()}
>
{pairing ? <LoaderCircleIcon className="size-4 animate-spin" /> : null}
Pair environment
Connect environment
</Button>
</div>
{pairError ? <p className="mt-2 text-xs text-destructive">{pairError}</p> : null}
@@ -289,17 +381,18 @@ export function CloudEnvironmentsSettings() {
<RenderEnvironmentRow
key={environment.environmentId}
environment={environment}
busyEnvironmentId={busyEnvironmentId}
busyEnvironmentIds={busyEnvironmentIds}
onConnect={(environmentId) => void handleConnect(environmentId)}
onDisconnect={(environmentId) => void handleDisconnect(environmentId)}
/>
))}
</SettingsSection>
<SettingsSection title="Ready to use">
<SettingsSection title="3. Add a project">
<SettingsRow
title="Get the code"
description="Choose Render and paste a public GitHub URL. The repository is cloned inside the cloud machine."
title="Clone a public GitHub repository"
description="Paste a GitHub URL and T3 Code clones it into the Render workspace, ready for an agent."
status={hasConnectedRenderEnvironment ? "Render is ready" : "Connect Render first"}
control={
<Button
size="sm"
@@ -11,7 +11,6 @@ import {
ArchiveIcon,
ArrowLeftIcon,
BotIcon,
CloudIcon,
FlaskConicalIcon,
GitBranchIcon,
KeyboardIcon,
@@ -36,6 +35,7 @@ import {
useSidebar,
} from "../ui/sidebar";
import { T3ConnectSidebarAvatar, T3ConnectSidebarSignIn } from "../clerk/T3ConnectSidebarSignIn";
import { RenderLogo } from "../RenderLogo";
import { scrollToSettingsTarget } from "./settingsLayout";
import {
searchSettings,
@@ -53,7 +53,7 @@ const SETTINGS_SECTION_ICONS: Readonly<
"/settings/providers": BotIcon,
"/settings/source-control": GitBranchIcon,
"/settings/connections": Link2Icon,
"/settings/cloud-environments": CloudIcon,
"/settings/cloud-environments": RenderLogo,
"/settings/beta": FlaskConicalIcon,
"/settings/archived": ArchiveIcon,
};
+16 -13
View File
@@ -15,21 +15,23 @@ The root [`render.yaml`](../../render.yaml) creates:
- a Docker web service containing T3 Code, Codex, Claude Code, Git, and the GitHub CLI;
- an ephemeral `/data` workspace for T3 Code state, provider credentials, and repositories;
- an optional `OPENAI_API_KEY` secret prompt for automatic Codex authentication;
- a private setup-code prompt for pairing the service directly inside T3 Code;
- a health check against T3 Code's public environment descriptor.
## Deploy
1. In the Render Dashboard, choose **New → Blueprint**.
2. Connect this repository and select the branch you want to deploy.
3. Choose an authentication method:
1. Open **Settings → Cloud environments** in T3 Code and copy the generated setup code.
2. Choose an authentication tab, then select **Deploy on Render**.
3. Enter the generated code in Render's `T3CODE_RENDER_SETUP_CODE` secret prompt.
4. Choose an authentication method:
- **OpenAI API key:** enter `OPENAI_API_KEY` in Render's secret prompt. Startup authenticates
Codex automatically.
- **ChatGPT subscription:** skip the optional API key, then use device login after cloning.
4. Deploy the Blueprint and wait for the service health check to pass.
5. Open the service logs and copy the `Pair URL` printed during startup. Treat this URL like a
password: it contains a one-time pairing credential.
6. Open the URL in a browser, or paste it under **Settings → Cloud environments → Pair URL**.
7. Open the Command Palette and choose **Add Project → Cloud environments → Render cloud
5. Deploy the Blueprint and wait for the service health check to pass.
6. Copy the service's `.onrender.com` URL, return to T3 Code, paste it under **Connect in T3
Code**, and select **Connect environment**. T3 Code wakes the service and exchanges the setup
code for a one-time pairing credential; there is no log-copying step.
7. Select **Add project** and choose **Cloud environments → Render cloud
environment**. Paste a public GitHub URL. T3 Code clones it directly into the Render workspace;
there is no local destination picker.
8. API-key deployments are ready immediately. For subscription authentication, open the project
@@ -64,14 +66,15 @@ session and is lost if Render restarts or spins down the service.
## T3 Connect
T3 Connect is not required for this deployment. Render already gives the environment a public HTTPS
and WebSocket endpoint, so the Pair URL registers it as a direct remote environment. Use its existing
Connect and Disconnect controls under **Settings → Cloud environments**. T3 Connect remains useful for
machines that need its managed tunnel or account-level environment discovery.
and WebSocket endpoint, so the in-app setup registers it as a direct remote environment. Use its
existing Connect and Disconnect controls under **Settings → Cloud environments**. T3 Connect remains
useful for machines that need its managed tunnel or account-level environment discovery.
## Operations
- Each deploy prints a fresh pairing URL with a 24-hour lifetime. Existing paired browser sessions
remain authenticated until revoked with `t3 auth`.
- The setup code can mint one-time pairing credentials. Treat it as a secret and remove the Render
service when the demo is over. Existing paired browser sessions remain authenticated until the
ephemeral service restarts.
- Render spins a Free web service down after 15 minutes without inbound HTTP or WebSocket traffic.
A later request starts a fresh instance, so pair, clone, and authenticate again.
- Do not use this Blueprint for untrusted users or repositories. Coding agents can execute commands
-23
View File
@@ -1,23 +0,0 @@
const chunks = [];
for await (const chunk of process.stdin) {
chunks.push(chunk);
}
const issued = JSON.parse(Buffer.concat(chunks).toString("utf8"));
if (typeof issued.credential !== "string" || issued.credential.length === 0) {
throw new Error("Pairing output did not include a credential.");
}
const publicUrl = process.env.T3CODE_PUBLIC_URL?.trim();
if (!publicUrl) {
throw new Error("T3CODE_PUBLIC_URL is required.");
}
const hostedAppUrl = process.env.T3CODE_HOSTED_APP_URL?.trim() || "https://app.t3.codes";
const environmentLabel = process.env.T3CODE_ENVIRONMENT_LABEL?.trim() || "Render cloud agent";
const pairUrl = new URL("/pair", hostedAppUrl);
pairUrl.searchParams.set("host", new URL(publicUrl).origin);
pairUrl.searchParams.set("label", environmentLabel);
pairUrl.hash = new URLSearchParams([["token", issued.credential]]).toString();
process.stdout.write(`Pair URL: ${pairUrl.toString()}\n`);
-20
View File
@@ -4,19 +4,12 @@ set -eu
script_dir="$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)"
app_root="$(CDPATH= cd -- "$script_dir/../.." && pwd)"
t3_entry="$app_root/apps/server/dist/bin.mjs"
pair_url_entry="$script_dir/pair-url.mjs"
t3() {
node "$t3_entry" "$@"
}
port="${PORT:-10000}"
t3_home="${T3CODE_HOME:-/data/t3}"
workspace_dir="${T3CODE_WORKSPACE_DIR:-/data/workspace}"
codex_home="${CODEX_HOME:-/data/codex}"
claude_config_dir="${CLAUDE_CONFIG_DIR:-/data/claude}"
public_url="${T3CODE_PUBLIC_URL:-${RENDER_EXTERNAL_URL:-}}"
pairing_ttl="${T3CODE_PAIRING_TTL:-24h}"
export CODEX_HOME="$codex_home"
export CLAUDE_CONFIG_DIR="$claude_config_dir"
@@ -35,19 +28,6 @@ if [ -n "${GH_TOKEN:-}" ]; then
gh auth setup-git
fi
if [ -n "$public_url" ]; then
pairing_json="$(t3 auth pairing create \
--base-dir "$t3_home" \
--label "Render startup" \
--ttl "$pairing_ttl" \
--json)"
printf '%s' "$pairing_json" | \
T3CODE_PUBLIC_URL="$public_url" \
node "$pair_url_entry"
else
echo "Set T3CODE_PUBLIC_URL to print a public pairing link at startup." >&2
fi
cd "$workspace_dir"
exec node "$t3_entry" start \
+29
View File
@@ -371,6 +371,34 @@ export const AuthOtherClientSessionsRevokeResult = Schema.Struct({
});
export type AuthOtherClientSessionsRevokeResult = typeof AuthOtherClientSessionsRevokeResult.Type;
export const EnvironmentRenderBootstrapPairingRequest = Schema.Struct({
setupCode: TrimmedNonEmptyString,
});
export type EnvironmentRenderBootstrapPairingRequest =
typeof EnvironmentRenderBootstrapPairingRequest.Type;
export const EnvironmentRenderBootstrapPairingResult = Schema.Struct({
pairingCode: TrimmedNonEmptyString,
label: TrimmedNonEmptyString,
});
export type EnvironmentRenderBootstrapPairingResult =
typeof EnvironmentRenderBootstrapPairingResult.Type;
const EnvironmentRenderBootstrapErrors = [
EnvironmentHttpBadRequestError,
EnvironmentHttpUnauthorizedError,
EnvironmentHttpForbiddenError,
EnvironmentHttpInternalServerError,
] as const;
export class EnvironmentRenderBootstrapHttpApi extends HttpApiGroup.make("renderBootstrap").add(
HttpApiEndpoint.post("pair", "/.well-known/t3/render/pair", {
payload: EnvironmentRenderBootstrapPairingRequest,
success: EnvironmentRenderBootstrapPairingResult,
error: EnvironmentRenderBootstrapErrors,
}),
) {}
export class EnvironmentMetadataHttpApi extends HttpApiGroup.make("metadata").add(
HttpApiEndpoint.get("descriptor", "/.well-known/t3/environment", {
success: ExecutionEnvironmentDescriptor,
@@ -551,6 +579,7 @@ export class EnvironmentConnectHttpApi extends HttpApiGroup.make("connect")
) {}
export class EnvironmentHttpApi extends HttpApi.make("environment")
.add(EnvironmentRenderBootstrapHttpApi)
.add(EnvironmentMetadataHttpApi)
.add(EnvironmentAuthHttpApi)
.add(EnvironmentOrchestrationHttpApi)
+3 -3
View File
@@ -5,7 +5,7 @@ services:
plan: free
repo: https://github.com/pingdotgg/t3code.git
branch: feat/render-cloud-environment
autoDeployTrigger: commit
autoDeployTrigger: off
dockerfilePath: ./infra/render/Dockerfile
dockerContext: .
healthCheckPath: /.well-known/t3/environment
@@ -16,7 +16,7 @@ services:
value: Render cloud environment
- key: T3CODE_WORKSPACE_DIR
value: /data/workspace
- key: T3CODE_PAIRING_TTL
value: 24h
- key: T3CODE_RENDER_SETUP_CODE
sync: false
- key: OPENAI_API_KEY
sync: false