Compare commits

...
26 changed files with 1281 additions and 94 deletions

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
.git
.repos
.t3
.vite-plus
node_modules
apps/*/node_modules
packages/*/node_modules
apps/*/dist
packages/*/dist
release
release-mock
artifacts
native/**/target
*.log
.env
.env.*
!.env.example
*.key
*.pem
auth.json
.codex
.claude
+1
View File
@@ -69,6 +69,7 @@ Full docs live in [docs/](./docs). There's no docs site yet.
- [Permission modes](./docs/user/permission-modes.md)
- [Keyboard shortcuts](./docs/user/keybindings.md)
- [Remote access from a phone or another machine](./docs/user/remote-access.md)
- [Deploy a cloud environment on Render](./docs/user/render.md)
- [Keeping app and server in sync](./docs/user/updating.md)
- [Source control integrations](./docs/user/source-control.md)
- Multiple accounts: [Codex](./docs/user/providers-codex.md) · [Claude](./docs/user/providers-claude.md)
@@ -5,6 +5,7 @@ import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as PlatformError from "effect/PlatformError";
import * as Schema from "effect/Schema";
import { HostProcessEnvironment } from "@t3tools/shared/hostProcess";
import * as ServerConfig from "../config.ts";
import * as ServerEnvironment from "./ServerEnvironment.ts";
@@ -73,6 +74,33 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
}),
);
it.effect("advertises a Render cloud workspace from the host environment", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const baseDir = yield* fileSystem.makeTempDirectoryScoped({
prefix: "t3-server-render-environment-test-",
});
const descriptor = yield* Effect.gen(function* () {
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
return yield* serverEnvironment.getDescriptor;
}).pipe(
Effect.provide(makeServerEnvironmentLayer(baseDir)),
Effect.provideService(HostProcessEnvironment, {
T3CODE_CLOUD_PROVIDER: "render",
T3CODE_ENVIRONMENT_LABEL: "Render cloud environment",
T3CODE_WORKSPACE_DIR: "/data/workspace",
}),
);
expect(descriptor.label).toBe("Render cloud environment");
expect(descriptor.cloud).toEqual({
provider: "render",
workspaceRoot: "/data/workspace",
});
}),
);
it.effect("structures persisted environment id filesystem failures", () =>
Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
@@ -1,5 +1,9 @@
import { EnvironmentId, type ExecutionEnvironmentDescriptor } from "@t3tools/contracts";
import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
import {
HostProcessArchitecture,
HostProcessEnvironment,
HostProcessPlatform,
} from "@t3tools/shared/hostProcess";
import * as Context from "effect/Context";
import * as Crypto from "effect/Crypto";
import * as Effect from "effect/Effect";
@@ -69,6 +73,7 @@ export const make = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
const hostPlatform = yield* HostProcessPlatform;
const hostArchitecture = yield* HostProcessArchitecture;
const hostEnvironment = yield* HostProcessEnvironment;
const readPersistedEnvironmentId = Effect.gen(function* () {
const exists = yield* fileSystem.exists(serverConfig.environmentIdPath).pipe(
@@ -125,7 +130,16 @@ export const make = Effect.gen(function* () {
const environmentId = EnvironmentId.make(environmentIdRaw);
const cwdBaseName = path.basename(serverConfig.cwd).trim();
const label = yield* resolveServerEnvironmentLabel({ cwdBaseName });
const configuredLabel = hostEnvironment.T3CODE_ENVIRONMENT_LABEL?.trim();
const label = configuredLabel || (yield* resolveServerEnvironmentLabel({ cwdBaseName }));
const cloudProvider = hostEnvironment.T3CODE_CLOUD_PROVIDER?.trim().toLowerCase();
const cloud =
cloudProvider === "render"
? {
provider: "render" as const,
workspaceRoot: hostEnvironment.T3CODE_WORKSPACE_DIR?.trim() || serverConfig.cwd,
}
: undefined;
const launcher = yield* resolveServiceLauncherMode();
const serverSelfUpdate = resolveServerSelfUpdateCapability({
desktopManaged: serverConfig.mode === "desktop",
@@ -139,6 +153,7 @@ export const make = Effect.gen(function* () {
os: platformOs(hostPlatform),
arch: platformArch(hostArchitecture),
},
...(cloud ? { cloud } : {}),
serverVersion: packageJson.version,
capabilities: {
repositoryIdentity: true,
+61
View File
@@ -0,0 +1,61 @@
import {
EnvironmentHttpApi,
EnvironmentHttpForbiddenError,
EnvironmentHttpInternalServerError,
} 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;
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 environmentLabel =
hostEnvironment.T3CODE_ENVIRONMENT_LABEL?.trim() || "Render cloud environment";
return handlers.handle(
"pair",
Effect.fn("environment.renderBootstrap.pair")(function* () {
yield* appendRenderBootstrapResponseHeaders;
if (configuredProvider !== "render") {
return yield* new EnvironmentHttpForbiddenError({
message: "This environment is not configured for Render setup.",
});
}
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,
};
}),
);
}),
);
+33 -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,36 @@ it.layer(NodeServices.layer)("server router seam", (it) => {
}).pipe(Effect.provide(NodeHttpServer.layerTest)),
);
it.effect("pairs a Render environment from its service URL without reading logs", () =>
Effect.gen(function* () {
yield* buildAppUnderTest({
hostEnvironment: {
T3CODE_CLOUD_PROVIDER: "render",
T3CODE_ENVIRONMENT_LABEL: "Render cloud environment",
},
});
const url = yield* getHttpServerUrl("/.well-known/t3/render/pair");
const response = yield* fetchEffect(url, {
method: "POST",
});
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(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,59 @@
import { describe, expect, it } from "vite-plus/test";
import { cloudCloneDestination, cloudEnvironmentProvider } from "./cloudEnvironment";
describe("cloudEnvironmentProvider", () => {
it("uses advertised Render metadata", () => {
expect(
cloudEnvironmentProvider({
displayUrl: null,
serverConfig: {
environment: {
environmentId: "environment-1",
label: "Render cloud environment",
platform: { os: "linux", arch: "x64" },
cloud: { provider: "render", workspaceRoot: "/data/workspace" },
serverVersion: "1.0.0",
capabilities: { repositoryIdentity: true },
},
} as never,
}),
).toBe("render");
});
it("recognizes disconnected onrender.com environments", () => {
expect(
cloudEnvironmentProvider({
displayUrl: "https://t3code-cloud-demo.onrender.com",
serverConfig: null,
}),
).toBe("render");
});
});
describe("cloudCloneDestination", () => {
it("clones provider repositories under the cloud workspace root", () => {
expect(
cloudCloneDestination({
workspaceRoot: "/data/workspace/",
repository: {
provider: "github",
nameWithOwner: "shivamhwp/render-ad",
url: "https://github.com/shivamhwp/render-ad",
sshUrl: "[email protected]:shivamhwp/render-ad.git",
},
remoteUrl: "[email protected]:shivamhwp/render-ad.git",
}),
).toBe("/data/workspace/render-ad");
});
it("derives a directory from arbitrary Git URLs", () => {
expect(
cloudCloneDestination({
workspaceRoot: "/data/workspace",
repository: null,
remoteUrl: "https://example.com/team/project.git?ref=main",
}),
).toBe("/data/workspace/project");
});
});
+65
View File
@@ -0,0 +1,65 @@
import type { ServerConfig, SourceControlRepositoryInfo } from "@t3tools/contracts";
export type CloudEnvironmentProvider = "render";
interface CloudEnvironmentLike {
readonly displayUrl: string | null;
readonly serverConfig: ServerConfig | null;
}
function isRenderHostname(value: string): boolean {
try {
return new URL(value).hostname.toLowerCase().endsWith(".onrender.com");
} catch {
return false;
}
}
export function cloudEnvironmentProvider(
environment: CloudEnvironmentLike,
): CloudEnvironmentProvider | null {
const advertisedProvider = environment.serverConfig?.environment.cloud?.provider;
if (advertisedProvider === "render") {
return advertisedProvider;
}
return environment.displayUrl && isRenderHostname(environment.displayUrl) ? "render" : null;
}
export function cloudEnvironmentWorkspaceRoot(environment: CloudEnvironmentLike): string | null {
return environment.serverConfig?.environment.cloud?.workspaceRoot ?? null;
}
export function cloudEnvironmentProviderLabel(provider: CloudEnvironmentProvider): string {
switch (provider) {
case "render":
return "Render";
}
}
export function inferRepositoryDirectoryName(input: {
readonly repository: SourceControlRepositoryInfo | null;
readonly remoteUrl: string;
}): string | null {
const candidate = input.repository?.nameWithOwner ?? input.remoteUrl;
const withoutQuery = candidate.split(/[?#]/, 1)[0]?.replace(/[\\/]+$/, "") ?? "";
const segment =
withoutQuery
.split(/[\\/:]/)
.at(-1)
?.replace(/\.git$/i, "")
.trim() ?? "";
return segment.length > 0 && segment !== "." && segment !== ".." ? segment : null;
}
export function cloudCloneDestination(input: {
readonly workspaceRoot: string;
readonly repository: SourceControlRepositoryInfo | null;
readonly remoteUrl: string;
}): string | null {
const directoryName = inferRepositoryDirectoryName(input);
if (!directoryName) {
return null;
}
const workspaceRoot = input.workspaceRoot.trim().replace(/[\\/]+$/, "");
return workspaceRoot.length > 0 ? `${workspaceRoot}/${directoryName}` : null;
}
@@ -0,0 +1,63 @@
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",
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 when the service is still running an older deployment", async () => {
const fetcher = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>
Response.json({ message: "missing" }, { status: 404 }),
);
const failure = await requestRenderPairing({
serviceUrl: "https://demo.onrender.com",
fetcher,
}).catch((error: unknown) => error);
expect(failure).toBeInstanceOf(RenderBootstrapRequestError);
expect((failure as Error).message).toContain("Deploy the latest version");
});
});
+91
View File
@@ -0,0 +1,91 @@
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 fetcher?: typeof globalThis.fetch;
}): Promise<{ readonly host: string; readonly pairingCode: string; readonly label: string }> {
const host = normalizeRenderServiceUrl(input.serviceUrl);
const endpoint = new URL("/.well-known/t3/render/pair", host);
let response: Response;
try {
response = await (input.fetcher ?? globalThis.fetch)(endpoint, {
method: "POST",
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 === 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.");
}
}
+222 -88
View File
@@ -119,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";
@@ -134,6 +135,13 @@ import { ComposerHandleContext, useComposerHandleContext } from "../composerHand
import type { ChatComposerHandle } from "./chat/ChatComposer";
import { getProjectOrderKey, selectProjectGroupingSettings } from "../logicalProject";
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
import {
cloudCloneDestination,
cloudEnvironmentProvider,
cloudEnvironmentProviderLabel,
cloudEnvironmentWorkspaceRoot,
type CloudEnvironmentProvider,
} from "../cloud/cloudEnvironment";
import {
buildSidebarProjectPickerEntries,
buildSidebarProjectSnapshots,
@@ -170,6 +178,7 @@ interface AddProjectEnvironmentOption {
readonly isPrimary: boolean;
readonly isConnected: boolean;
readonly status: string;
readonly cloudProvider: CloudEnvironmentProvider | null;
}
type AddProjectRemoteProviderKind = Extract<
@@ -192,6 +201,7 @@ type AddProjectCloneFlow =
readonly repository: SourceControlRepositoryInfo | null;
readonly remoteUrl: string;
};
type AddProjectCloneConfirmation = Extract<AddProjectCloneFlow, { readonly step: "confirm" }>;
const REMOTE_PROJECT_SOURCES: ReadonlyArray<AddProjectRemoteSource> = [
"url",
@@ -540,6 +550,10 @@ function OpenCommandPaletteDialog(props: {
const lookupRepository = useAtomQueryRunner(sourceControlEnvironment.repository, {
reportFailure: false,
});
const loadSourceControlDiscovery = useAtomQueryRunner(sourceControlEnvironment.discovery, {
reportFailure: false,
reportDefect: false,
});
const loadBrowsePath = useAtomQueryRunner(filesystemEnvironment.browse, {
reportFailure: false,
reportDefect: false,
@@ -695,6 +709,7 @@ function OpenCommandPaletteDialog(props: {
isPrimary,
isConnected: canCreateProjectInEnvironment(environment.connection.phase),
status: connectionStatusText(environment.connection),
cloudProvider: cloudEnvironmentProvider(environment),
};
});
@@ -1209,7 +1224,7 @@ function OpenCommandPaletteDialog(props: {
);
const startAddProjectSourceSelection = useCallback(
(environmentId: EnvironmentId): void => {
async (environmentId: EnvironmentId): Promise<void> => {
const environment = environments.find(
(candidate) => candidate.environmentId === environmentId,
);
@@ -1225,13 +1240,21 @@ function OpenCommandPaletteDialog(props: {
}
setAddProjectEnvironmentId(environmentId);
setAddProjectCloneFlow(null);
let discovery = browseEnvironmentId === environmentId ? sourceControlDiscovery.data : null;
if (discovery === null) {
const discoveryResult = await loadSourceControlDiscovery({
environmentId,
input: {},
});
if (discoveryResult._tag === "Success") {
discovery = discoveryResult.value;
}
}
pushPaletteView({
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
groups: buildAddProjectSourceGroups(
environmentId,
buildAddProjectRemoteSourceReadiness(
browseEnvironmentId === environmentId ? sourceControlDiscovery.data : null,
),
buildAddProjectRemoteSourceReadiness(discovery),
),
});
},
@@ -1239,44 +1262,83 @@ function OpenCommandPaletteDialog(props: {
browseEnvironmentId,
buildAddProjectSourceGroups,
environments,
loadSourceControlDiscovery,
pushPaletteView,
sourceControlDiscovery.data,
],
);
const addProjectEnvironmentItems: CommandPaletteActionItem[] = addProjectEnvironmentOptions.map(
(option) => ({
const addProjectEnvironmentGroups = useMemo<CommandPaletteView["groups"]>(() => {
const toItem = (option: AddProjectEnvironmentOption): CommandPaletteActionItem => ({
kind: "action",
value: `action:add-project:environment:${option.environmentId}`,
searchTerms: [option.label, option.environmentId, option.isPrimary ? "this device" : ""],
searchTerms: [
option.label,
option.environmentId,
option.isPrimary ? "this device" : "",
option.cloudProvider ? "cloud render" : "",
],
title: option.label,
description: option.isConnected
? option.isPrimary
? "This device"
: option.environmentId
? option.cloudProvider
? `Cloud workspace · Powered by ${cloudEnvironmentProviderLabel(option.cloudProvider)}`
: option.isPrimary
? "This device"
: option.environmentId
: option.status,
disabled: !option.isConnected,
icon: <FolderPlusIcon className={ITEM_ICON_CLASS} />,
icon: option.cloudProvider ? (
<RenderLogo className={ITEM_ICON_CLASS} />
) : (
<FolderPlusIcon className={ITEM_ICON_CLASS} />
),
keepOpen: true,
run: async () => {
startAddProjectSourceSelection(option.environmentId);
if (option.cloudProvider) {
startAddProjectClone(option.environmentId, "url");
return;
}
await startAddProjectSourceSelection(option.environmentId);
},
}),
);
});
const cloudItems = addProjectEnvironmentOptions
.filter((option) => option.cloudProvider !== null)
.map(toItem);
const deviceItems = addProjectEnvironmentOptions
.filter((option) => option.cloudProvider === null)
.map(toItem);
const addProjectEnvironmentGroups = useMemo<CommandPaletteView["groups"]>(
() => [
{
value: "environments",
label: "Environments",
items: addProjectEnvironmentItems,
},
],
[addProjectEnvironmentItems],
return [
...(cloudItems.length > 0
? [
{
value: "cloud-environments",
label: "Cloud environments · Powered by Render",
items: cloudItems,
},
]
: []),
...(deviceItems.length > 0
? [
{
value: "device-environments",
label: "Devices",
items: deviceItems,
},
]
: []),
];
}, [addProjectEnvironmentOptions, startAddProjectClone, startAddProjectSourceSelection]);
const hasCloudAddProjectEnvironment = addProjectEnvironmentOptions.some(
(option) => option.cloudProvider !== null,
);
const openAddProjectFlow = useCallback(() => {
if (addProjectEnvironmentOptions.length > 1 || defaultAddProjectEnvironmentId === null) {
if (
hasCloudAddProjectEnvironment ||
addProjectEnvironmentOptions.length > 1 ||
defaultAddProjectEnvironmentId === null
) {
pushPaletteView({
addonIcon: <FolderPlusIcon className={ADDON_ICON_CLASS} />,
groups: addProjectEnvironmentGroups,
@@ -1301,6 +1363,7 @@ function OpenCommandPaletteDialog(props: {
addProjectEnvironmentGroups,
addProjectEnvironmentOptions.length,
defaultAddProjectEnvironmentId,
hasCloudAddProjectEnvironment,
pushPaletteView,
startAddProjectSourceSelection,
]);
@@ -1664,6 +1727,119 @@ function OpenCommandPaletteDialog(props: {
return getAddProjectInitialQueryForEnvironment(environmentId);
}
function getCloudCloneDestination(flow: AddProjectCloneConfirmation): string | null | undefined {
const environment = environments.find(
(candidate) => candidate.environmentId === flow.environmentId,
);
if (!environment) {
return undefined;
}
const workspaceRoot = cloudEnvironmentWorkspaceRoot(environment);
if (!workspaceRoot) {
return undefined;
}
return cloudCloneDestination({
workspaceRoot,
repository: flow.repository,
remoteUrl: flow.remoteUrl,
});
}
async function cloneIntoCloudEnvironmentIfConfigured(
flow: AddProjectCloneConfirmation,
): Promise<boolean> {
const destination = getCloudCloneDestination(flow);
if (destination === undefined) {
return false;
}
if (destination === null) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Unable to name cloud workspace",
description: "Use a repository URL whose final path contains the repository name.",
}),
);
return true;
}
await cloneAndAddRemoteProject(flow, destination);
return true;
}
async function cloneAndAddRemoteProject(
flow: AddProjectCloneConfirmation,
destinationPathInput: string,
): Promise<void> {
const rawDestination = destinationPathInput.trim();
if (rawDestination.length === 0 || isRemoteProjectCloning) {
return;
}
const targetEnvironment = environments.find(
(candidate) => candidate.environmentId === flow.environmentId,
);
const targetPlatform = getEnvironmentBrowsePlatform(
targetEnvironment?.serverConfig?.environment.platform.os,
);
const targetCurrentProjectCwd =
currentProjectEnvironmentId === flow.environmentId ? currentProjectCwd : null;
if (isUnsupportedWindowsProjectPath(rawDestination, targetPlatform)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Clone failed",
description: "Windows-style paths are only supported on Windows.",
}),
);
return;
}
if (isExplicitRelativeProjectPath(rawDestination) && !targetCurrentProjectCwd) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Clone failed",
description: "Relative paths require an active project.",
}),
);
return;
}
const destinationPath = resolveProjectPathForDispatch(rawDestination, targetCurrentProjectCwd);
if (destinationPath.length === 0) {
return;
}
setIsRemoteProjectCloning(true);
const cloneResult = await cloneRepository({
environmentId: flow.environmentId,
input: {
remoteUrl: flow.remoteUrl,
destinationPath,
},
});
setIsRemoteProjectCloning(false);
if (cloneResult._tag === "Failure") {
if (!isAtomCommandInterrupted(cloneResult)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Clone failed",
description: errorMessage(squashAtomCommandFailure(cloneResult)),
}),
);
}
return;
}
await handleAddProjectForEnvironment({
environmentId: flow.environmentId,
rawCwd: cloneResult.value.cwd,
platform: targetPlatform,
currentProjectCwd: targetCurrentProjectCwd,
});
}
async function submitAddProjectCloneFlow(destinationPathInput?: string): Promise<void> {
if (!addProjectCloneFlow) {
return;
@@ -1687,15 +1863,19 @@ function OpenCommandPaletteDialog(props: {
const provider = remoteProjectSourceProvider(addProjectCloneFlow.source);
if (!provider) {
const destinationPath = getDefaultCloneParentPath(addProjectCloneFlow.environmentId);
setAddProjectCloneFlow({
const confirmation: AddProjectCloneConfirmation = {
step: "confirm",
environmentId: addProjectCloneFlow.environmentId,
source: addProjectCloneFlow.source,
repositoryInput: rawRepository,
repository: null,
remoteUrl: rawRepository,
});
};
if (await cloneIntoCloudEnvironmentIfConfigured(confirmation)) {
return;
}
const destinationPath = getDefaultCloneParentPath(addProjectCloneFlow.environmentId);
setAddProjectCloneFlow(confirmation);
setHighlightedItemValue(null);
setQuery(destinationPath);
setBrowseGeneration((generation) => generation + 1);
@@ -1724,78 +1904,32 @@ function OpenCommandPaletteDialog(props: {
return;
}
const repository = lookupResult.value;
const destinationPath = getDefaultCloneParentPath(addProjectCloneFlow.environmentId);
setAddProjectCloneFlow({
const cloneEnvironment = environments.find(
(environment) => environment.environmentId === addProjectCloneFlow.environmentId,
);
const confirmation: AddProjectCloneConfirmation = {
step: "confirm",
environmentId: addProjectCloneFlow.environmentId,
source: addProjectCloneFlow.source,
repositoryInput: rawRepository,
repository,
remoteUrl: repository.sshUrl,
});
remoteUrl:
cloneEnvironment && cloudEnvironmentWorkspaceRoot(cloneEnvironment)
? repository.url
: repository.sshUrl,
};
if (await cloneIntoCloudEnvironmentIfConfigured(confirmation)) {
return;
}
const destinationPath = getDefaultCloneParentPath(addProjectCloneFlow.environmentId);
setAddProjectCloneFlow(confirmation);
setHighlightedItemValue(null);
setQuery(destinationPath);
setBrowseGeneration((generation) => generation + 1);
return;
}
const rawDestination = (destinationPathInput ?? query).trim();
if (rawDestination.length === 0 || isRemoteProjectCloning) {
return;
}
if (isUnsupportedWindowsProjectPath(rawDestination, browseEnvironmentPlatform)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Clone failed",
description: "Windows-style paths are only supported on Windows.",
}),
);
return;
}
if (isExplicitRelativeProjectPath(rawDestination) && !currentProjectCwdForBrowse) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Clone failed",
description: "Relative paths require an active project.",
}),
);
return;
}
const destinationPath = resolveProjectPathForDispatch(
rawDestination,
currentProjectCwdForBrowse,
);
if (destinationPath.length === 0) {
return;
}
setIsRemoteProjectCloning(true);
const cloneResult = await cloneRepository({
environmentId: addProjectCloneFlow.environmentId,
input: {
remoteUrl: addProjectCloneFlow.remoteUrl,
destinationPath,
},
});
setIsRemoteProjectCloning(false);
if (cloneResult._tag === "Failure") {
if (!isAtomCommandInterrupted(cloneResult)) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Clone failed",
description: errorMessage(squashAtomCommandFailure(cloneResult)),
}),
);
}
return;
}
await handleAddProject(cloneResult.value.cwd);
await cloneAndAddRemoteProject(addProjectCloneFlow, destinationPathInput ?? query);
}
const browseTo = useCallback(
+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>
);
}
@@ -0,0 +1,347 @@
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 } 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 { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
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";
import { SettingsPageContainer, SettingsRow, SettingsSection } from "./settingsLayout";
import { searchableSetting } from "./settingsSearch";
const RENDER_DEPLOY_URL =
"https://render.com/deploy?repo=https%3A%2F%2Fgithub.com%2Fpingdotgg%2Ft3code%2Ftree%2Ffeat%2Frender-cloud-environment";
const CODEX_LOGIN_COMMAND = "codex login --device-auth";
type RenderAuthenticationMode = "api-key" | "subscription";
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 }) {
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>
<CopyValueButton value={command} label="command" />
</div>
);
}
function RenderEnvironmentRow({
environment,
busyEnvironmentIds,
onConnect,
onDisconnect,
}: {
readonly environment: EnvironmentPresentation;
readonly busyEnvironmentIds: ReadonlySet<EnvironmentId>;
readonly onConnect: (environmentId: EnvironmentId) => void;
readonly onDisconnect: (environmentId: EnvironmentId) => void;
}) {
const isConnected = environment.connection.phase === "connected";
const isBusy = busyEnvironmentIds.has(environment.environmentId);
const serviceLabel = environment.displayUrl
? maskedRenderServiceUrl(environment.displayUrl)
: null;
return (
<SettingsRow
title={
<span className="inline-flex items-center gap-2">
<RenderLogo className="size-4" />
{environment.label}
</span>
}
description="Powered by Render"
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"
variant="outline"
onClick={() => openCommandPalette({ open: "add-project" })}
>
Add project
</Button>
) : null}
<Button
size="xs"
variant="outline"
disabled={isBusy}
onClick={() =>
isConnected
? onDisconnect(environment.environmentId)
: onConnect(environment.environmentId)
}
>
{isBusy ? <LoaderCircleIcon className="size-3 animate-spin" /> : null}
{isConnected ? "Disconnect" : "Connect"}
</Button>
</>
}
/>
);
}
export function CloudEnvironmentsSettings() {
const { environments } = useEnvironments();
const connectPairing = useAtomCommand(connectPairingAtom, { reportFailure: false });
const retryEnvironment = useAtomCommand(environmentCatalog.retryNow, { reportFailure: false });
const removeEnvironment = useAtomCommand(environmentCatalog.remove, { reportFailure: false });
const [serviceUrl, setServiceUrl] = useState("");
const [pairing, setPairing] = useState(false);
const [pairingStatus, setPairingStatus] = useState<string | null>(null);
const [pairError, setPairError] = useState<string | 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"),
[environments],
);
const hasConnectedRenderEnvironment = renderEnvironments.some(
(environment) => environment.connection.phase === "connected",
);
const reportFailure = useCallback((title: string, description: string) => {
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);
setPairing(true);
setPairingStatus("Waking the Render service…");
try {
const pairingInput = await requestRenderPairing({ serviceUrl });
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;
}
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);
}
}, [connectPairing, pairing, serviceUrl]);
const handleConnect = useCallback(
async (environmentId: EnvironmentId) => {
setEnvironmentBusy(environmentId, true);
const result = await retryEnvironment(environmentId);
setEnvironmentBusy(environmentId, false);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const failure = squashAtomCommandFailure(result);
reportFailure(
"Could not connect Render environment",
failure instanceof Error ? failure.message : "Could not connect Render environment.",
);
}
},
[reportFailure, retryEnvironment, setEnvironmentBusy],
);
const handleDisconnect = useCallback(
async (environmentId: EnvironmentId) => {
setEnvironmentBusy(environmentId, true);
const result = await removeEnvironment(environmentId);
setEnvironmentBusy(environmentId, false);
if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) {
const failure = squashAtomCommandFailure(result);
reportFailure(
"Could not disconnect Render environment",
failure instanceof Error ? failure.message : "Could not disconnect Render environment.",
);
}
},
[removeEnvironment, reportFailure, setEnvironmentBusy],
);
return (
<SettingsPageContainer>
<SettingsSection
{...searchableSetting("cloud-environments")}
icon={<RenderLogo className="size-5" />}
/>
<SettingsSection title="1. Deploy to Render">
<div className="px-3 sm:px-4">
<div
role="tablist"
aria-label="Codex authentication method"
className="inline-flex rounded-lg border border-border/70 bg-muted/20 p-1"
>
<button
type="button"
role="tab"
aria-selected={authenticationMode === "api-key"}
className="rounded-md px-3 py-1.5 text-xs font-medium text-muted-foreground aria-selected:bg-background aria-selected:text-foreground aria-selected:shadow-xs"
onClick={() => setAuthenticationMode("api-key")}
>
OpenAI API key
</button>
<button
type="button"
role="tab"
aria-selected={authenticationMode === "subscription"}
className="rounded-md px-3 py-1.5 text-xs font-medium text-muted-foreground aria-selected:bg-background aria-selected:text-foreground aria-selected:shadow-xs"
onClick={() => setAuthenticationMode("subscription")}
>
ChatGPT subscription
</button>
</div>
</div>
{authenticationMode === "api-key" ? (
<div role="tabpanel">
<SettingsRow
title="OpenAI API key"
description="Render asks for OPENAI_API_KEY. 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 on Render
<ExternalLinkIcon className="size-3.5" />
</Button>
}
/>
</div>
) : (
<div role="tabpanel">
<SettingsRow
title="ChatGPT subscription"
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 on Render
<ExternalLinkIcon className="size-3.5" />
</Button>
}
>
<CopyCommand command={CODEX_LOGIN_COMMAND} />
</SettingsRow>
</div>
)}
</SettingsSection>
<SettingsSection title="2. Connect in T3 Code">
<SettingsRow
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={serviceUrl}
onChange={(event) => setServiceUrl(event.target.value)}
placeholder="https://your-service.onrender.com"
autoComplete="url"
spellCheck={false}
onKeyDown={(event) => {
if (event.key === "Enter" && !pairing) void handlePair();
}}
/>
<Button
disabled={pairing || serviceUrl.trim().length === 0}
onClick={() => void handlePair()}
>
{pairing ? <LoaderCircleIcon className="size-4 animate-spin" /> : null}
Connect environment
</Button>
</div>
{pairError ? <p className="mt-2 text-xs text-destructive">{pairError}</p> : null}
</SettingsRow>
{renderEnvironments.map((environment) => (
<RenderEnvironmentRow
key={environment.environmentId}
environment={environment}
busyEnvironmentIds={busyEnvironmentIds}
onConnect={(environmentId) => void handleConnect(environmentId)}
onDisconnect={(environmentId) => void handleDisconnect(environmentId)}
/>
))}
</SettingsSection>
<SettingsSection title="3. Add a project">
<SettingsRow
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"
disabled={!hasConnectedRenderEnvironment}
onClick={() => openCommandPalette({ open: "add-project" })}
>
Add project
</Button>
}
/>
</SettingsSection>
</SettingsPageContainer>
);
}
@@ -131,6 +131,7 @@ import { ConnectionStatusDot } from "../ConnectionStatusDot";
import { ServerUpdateAction, ServerUpdateProgress } from "../ServerUpdateAction";
import { CloudEnvironmentConnectRows } from "../cloud/CloudEnvironmentConnectList";
import { ITEM_ROW_CLASSNAME, ITEM_ROW_INNER_CLASSNAME } from "./itemRows";
import { cloudEnvironmentProvider, cloudEnvironmentProviderLabel } from "~/cloud/cloudEnvironment";
const DEFAULT_TAILSCALE_SERVE_PORT = 443;
const EMPTY_ADVERTISED_ENDPOINTS: ReadonlyArray<AdvertisedEndpoint> = [];
@@ -1394,7 +1395,9 @@ function SavedBackendListRow({
environment.entry.profile.value._tag === "SshConnectionProfile"
? environment.entry.profile.value.target
: null;
const cloudProvider = cloudEnvironmentProvider(environment);
const metadataBits = [
cloudProvider ? `Powered by ${cloudEnvironmentProviderLabel(cloudProvider)}` : null,
sshTarget ? `SSH ${formatDesktopSshTarget(sshTarget)}` : null,
environment.relayManaged ? "T3 Connect" : null,
].filter((value): value is string => value !== null);
@@ -1742,6 +1745,10 @@ export function ConnectionsSettings() {
.toSorted((left, right) => left.label.localeCompare(right.label)),
[environments],
);
const savedNonCloudEnvironments = useMemo(
() => savedEnvironments.filter((environment) => cloudEnvironmentProvider(environment) === null),
[savedEnvironments],
);
const savedDesktopSshEnvironmentsByAlias = useMemo(
() =>
savedEnvironments.reduce<Record<string, EnvironmentPresentation>>(
@@ -3408,7 +3415,7 @@ export function ConnectionsSettings() {
</Dialog>
}
>
{savedEnvironments.map((environment) => (
{savedNonCloudEnvironments.map((environment) => (
<SavedBackendListRow
key={environment.environmentId}
environment={environment}
@@ -35,6 +35,7 @@ import {
useSidebar,
} from "../ui/sidebar";
import { T3ConnectSidebarAvatar, T3ConnectSidebarSignIn } from "../clerk/T3ConnectSidebarSignIn";
import { RenderLogo } from "../RenderLogo";
import { scrollToSettingsTarget } from "./settingsLayout";
import {
searchSettings,
@@ -52,6 +53,7 @@ const SETTINGS_SECTION_ICONS: Readonly<
"/settings/providers": BotIcon,
"/settings/source-control": GitBranchIcon,
"/settings/connections": Link2Icon,
"/settings/cloud-environments": RenderLogo,
"/settings/beta": FlaskConicalIcon,
"/settings/archived": ArchiveIcon,
};
@@ -104,7 +104,7 @@ export function SettingsSection({
title: string;
icon?: ReactNode;
headerAction?: ReactNode;
children: ReactNode;
children?: ReactNode;
}) {
const targetRef = useSettingsSearchTarget<HTMLElement>(sectionProps.id);
@@ -122,7 +122,9 @@ export function SettingsSection({
</h2>
<div className="flex min-h-7 min-w-7 items-center justify-end">{headerAction}</div>
</div>
<div className="relative space-y-1 overflow-visible text-foreground">{children}</div>
{children !== undefined && children !== null ? (
<div className="relative space-y-1 overflow-visible text-foreground">{children}</div>
) : null}
</section>
);
}
@@ -5,6 +5,7 @@ export type SettingsPath =
| "/settings/providers"
| "/settings/source-control"
| "/settings/connections"
| "/settings/cloud-environments"
| "/settings/beta"
| "/settings/archived";
@@ -26,6 +27,7 @@ export const SETTINGS_SECTION_LABELS: Readonly<Record<SettingsPath, string>> = {
"/settings/providers": "Providers",
"/settings/source-control": "Source Control",
"/settings/connections": "Connections",
"/settings/cloud-environments": "Cloud environments",
"/settings/beta": "Beta",
"/settings/archived": "Archive",
};
@@ -166,6 +168,11 @@ export const SETTINGS_SEARCH_ITEMS = [
title: "Source control",
to: "/settings/source-control",
},
{
id: "cloud-environments",
title: "Cloud environments",
to: "/settings/cloud-environments",
},
{
id: "remote-environments",
title: "Remote environments",
+22
View File
@@ -20,6 +20,7 @@ import { Route as SettingsKeybindingsRouteImport } from './routes/settings.keybi
import { Route as SettingsGeneralRouteImport } from './routes/settings.general'
import { Route as SettingsDiagnosticsRouteImport } from './routes/settings.diagnostics'
import { Route as SettingsConnectionsRouteImport } from './routes/settings.connections'
import { Route as SettingsCloudEnvironmentsRouteImport } from './routes/settings.cloud-environments'
import { Route as SettingsBetaRouteImport } from './routes/settings.beta'
import { Route as SettingsArchivedRouteImport } from './routes/settings.archived'
import { Route as SettingsAppearanceRouteImport } from './routes/settings.appearance'
@@ -81,6 +82,12 @@ const SettingsConnectionsRoute = SettingsConnectionsRouteImport.update({
path: '/connections',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsCloudEnvironmentsRoute =
SettingsCloudEnvironmentsRouteImport.update({
id: '/cloud-environments',
path: '/cloud-environments',
getParentRoute: () => SettingsRoute,
} as any)
const SettingsBetaRoute = SettingsBetaRouteImport.update({
id: '/beta',
path: '/beta',
@@ -122,6 +129,7 @@ export interface FileRoutesByFullPath {
'/settings/appearance': typeof SettingsAppearanceRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/beta': typeof SettingsBetaRoute
'/settings/cloud-environments': typeof SettingsCloudEnvironmentsRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
@@ -139,6 +147,7 @@ export interface FileRoutesByTo {
'/settings/appearance': typeof SettingsAppearanceRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/beta': typeof SettingsBetaRoute
'/settings/cloud-environments': typeof SettingsCloudEnvironmentsRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
@@ -159,6 +168,7 @@ export interface FileRoutesById {
'/settings/appearance': typeof SettingsAppearanceRoute
'/settings/archived': typeof SettingsArchivedRoute
'/settings/beta': typeof SettingsBetaRoute
'/settings/cloud-environments': typeof SettingsCloudEnvironmentsRoute
'/settings/connections': typeof SettingsConnectionsRoute
'/settings/diagnostics': typeof SettingsDiagnosticsRoute
'/settings/general': typeof SettingsGeneralRoute
@@ -180,6 +190,7 @@ export interface FileRouteTypes {
| '/settings/appearance'
| '/settings/archived'
| '/settings/beta'
| '/settings/cloud-environments'
| '/settings/connections'
| '/settings/diagnostics'
| '/settings/general'
@@ -197,6 +208,7 @@ export interface FileRouteTypes {
| '/settings/appearance'
| '/settings/archived'
| '/settings/beta'
| '/settings/cloud-environments'
| '/settings/connections'
| '/settings/diagnostics'
| '/settings/general'
@@ -216,6 +228,7 @@ export interface FileRouteTypes {
| '/settings/appearance'
| '/settings/archived'
| '/settings/beta'
| '/settings/cloud-environments'
| '/settings/connections'
| '/settings/diagnostics'
| '/settings/general'
@@ -314,6 +327,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof SettingsConnectionsRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/cloud-environments': {
id: '/settings/cloud-environments'
path: '/cloud-environments'
fullPath: '/settings/cloud-environments'
preLoaderRoute: typeof SettingsCloudEnvironmentsRouteImport
parentRoute: typeof SettingsRoute
}
'/settings/beta': {
id: '/settings/beta'
path: '/beta'
@@ -377,6 +397,7 @@ interface SettingsRouteChildren {
SettingsAppearanceRoute: typeof SettingsAppearanceRoute
SettingsArchivedRoute: typeof SettingsArchivedRoute
SettingsBetaRoute: typeof SettingsBetaRoute
SettingsCloudEnvironmentsRoute: typeof SettingsCloudEnvironmentsRoute
SettingsConnectionsRoute: typeof SettingsConnectionsRoute
SettingsDiagnosticsRoute: typeof SettingsDiagnosticsRoute
SettingsGeneralRoute: typeof SettingsGeneralRoute
@@ -389,6 +410,7 @@ const SettingsRouteChildren: SettingsRouteChildren = {
SettingsAppearanceRoute: SettingsAppearanceRoute,
SettingsArchivedRoute: SettingsArchivedRoute,
SettingsBetaRoute: SettingsBetaRoute,
SettingsCloudEnvironmentsRoute: SettingsCloudEnvironmentsRoute,
SettingsConnectionsRoute: SettingsConnectionsRoute,
SettingsDiagnosticsRoute: SettingsDiagnosticsRoute,
SettingsGeneralRoute: SettingsGeneralRoute,
@@ -0,0 +1,7 @@
import { createFileRoute } from "@tanstack/react-router";
import { CloudEnvironmentsSettings } from "../components/settings/CloudEnvironmentsSettings";
export const Route = createFileRoute("/settings/cloud-environments")({
component: CloudEnvironmentsSettings,
});
+79
View File
@@ -0,0 +1,79 @@
# Deploy a Cloud Environment on Render
This experimental setup runs one T3 Code environment as a Render web service. The environment owns
the provider processes, repositories, worktrees, terminals, and T3 Code state. The web, desktop, and
mobile clients connect to it over Render's public HTTPS and WebSocket endpoint.
This is an ephemeral, one-session demo environment, not a multi-tenant hosted service. The Free
instance can run multiple agent threads, but loses its files and authentication when it restarts or
spins down.
## What the Blueprint Creates
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;
- in-app pairing directly from the service URL;
- a health check against T3 Code's public environment descriptor.
## Deploy
1. Open **Settings → Cloud environments** in T3 Code.
2. Choose an authentication method, then select **Deploy on Render**:
- **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.
3. Deploy the Blueprint and wait for the service health check to pass.
4. 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 requests a one-time
pairing credential; there is no log-copying step.
5. 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.
6. API-key deployments are ready immediately. For subscription authentication, open the project
terminal, run `codex login --device-auth`, complete the device login, and start an agent.
Repositories are selected after pairing rather than baked into the Blueprint. Each clone is stored
under `/data/workspace` for the current Free-instance session.
The Render service advertises cloud metadata in its normal T3 environment descriptor. That is what
lets clients present it as a cloud device and automatically route project cloning to its cloud
workspace while leaving the existing local-device folder flow unchanged.
The demo Blueprint is pinned to `feat/render-cloud-environment` so it can deploy before the draft
pull request is merged. Update the `branch` field in `render.yaml` if you rename or reuse the branch.
## Provider Authentication
For API-key authentication, the Blueprint declares `OPENAI_API_KEY` with `sync: false`. Render asks
for it during the initial deployment and stores it as a secret; the value is never committed to the
repository. The startup script pipes it to `codex login --with-api-key` and removes it from the
server process environment afterward.
For ChatGPT subscription authentication, clone a public project, open its T3 Code terminal, and run:
```sh
codex login --device-auth
```
Follow the printed link and enter the device code. The login lasts for the current Free-instance
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 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
- Anyone with the service URL can request a standard T3 Code pairing credential. Use this setup only
for a private demo and remove the Render service afterward. 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
and access every secret available to the service.
+40
View File
@@ -0,0 +1,40 @@
FROM node:24.19.0-bookworm-slim
ARG VP_VERSION=0.2.2
ARG CODEX_VERSION=0.146.0
ARG CLAUDE_CODE_VERSION=2.1.220
ENV CI=1 \
VP_NODE_MANAGER=no \
PATH="/root/.vite-plus/bin:${PATH}"
RUN apt-get update \
&& apt-get install --yes --no-install-recommends \
build-essential \
ca-certificates \
curl \
gh \
git \
openssh-client \
python3 \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY . .
RUN curl -fsSL https://vite.plus | bash \
&& vp install --frozen-lockfile \
&& vp run --filter t3 build \
&& npm install --global \
"@anthropic-ai/claude-code@${CLAUDE_CODE_VERSION}" \
"@openai/codex@${CODEX_VERSION}"
ENV T3CODE_HOME=/data/t3 \
T3CODE_WORKSPACE_DIR=/data/workspace \
CODEX_HOME=/data/codex \
CLAUDE_CONFIG_DIR=/data/claude
EXPOSE 10000
ENTRYPOINT ["/app/infra/render/start.sh"]
+37
View File
@@ -0,0 +1,37 @@
#!/bin/sh
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"
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}"
export CODEX_HOME="$codex_home"
export CLAUDE_CONFIG_DIR="$claude_config_dir"
export T3CODE_CLOUD_PROVIDER="${T3CODE_CLOUD_PROVIDER:-render}"
export T3CODE_ENVIRONMENT_LABEL="${T3CODE_ENVIRONMENT_LABEL:-Render cloud environment}"
export T3CODE_WORKSPACE_DIR="$workspace_dir"
mkdir -p "$t3_home" "$workspace_dir" "$codex_home" "$claude_config_dir"
if [ -n "${OPENAI_API_KEY:-}" ]; then
printf '%s\n' "$OPENAI_API_KEY" | codex login --with-api-key
unset OPENAI_API_KEY
fi
if [ -n "${GH_TOKEN:-}" ]; then
gh auth setup-git
fi
cd "$workspace_dir"
exec node "$t3_entry" start \
--host 0.0.0.0 \
--port "$port" \
--base-dir "$t3_home" \
--no-browser
+11
View File
@@ -20,6 +20,16 @@ export const ExecutionEnvironmentPlatform = Schema.Struct({
});
export type ExecutionEnvironmentPlatform = typeof ExecutionEnvironmentPlatform.Type;
export const ExecutionEnvironmentCloudProvider = Schema.Literals(["render"]);
export type ExecutionEnvironmentCloudProvider = typeof ExecutionEnvironmentCloudProvider.Type;
/** Metadata advertised by a backend whose workspace is hosted by a cloud provider. */
export const ExecutionEnvironmentCloud = Schema.Struct({
provider: ExecutionEnvironmentCloudProvider,
workspaceRoot: TrimmedNonEmptyString,
});
export type ExecutionEnvironmentCloud = typeof ExecutionEnvironmentCloud.Type;
/** How a server can replace itself with another version when asked over RPC.
New servers only advertise the stable launcher-backed "boot-service" path;
"respawn" remains decodable for compatibility with older servers. */
@@ -67,6 +77,7 @@ export const ExecutionEnvironmentDescriptor = Schema.Struct({
environmentId: EnvironmentId,
label: TrimmedNonEmptyString,
platform: ExecutionEnvironmentPlatform,
cloud: Schema.optionalKey(ExecutionEnvironmentCloud),
serverVersion: TrimmedNonEmptyString,
capabilities: ExecutionEnvironmentCapabilities,
});
+20
View File
@@ -371,6 +371,25 @@ export const AuthOtherClientSessionsRevokeResult = Schema.Struct({
});
export type AuthOtherClientSessionsRevokeResult = typeof AuthOtherClientSessionsRevokeResult.Type;
export const EnvironmentRenderBootstrapPairingResult = Schema.Struct({
pairingCode: TrimmedNonEmptyString,
label: TrimmedNonEmptyString,
});
export type EnvironmentRenderBootstrapPairingResult =
typeof EnvironmentRenderBootstrapPairingResult.Type;
const EnvironmentRenderBootstrapErrors = [
EnvironmentHttpForbiddenError,
EnvironmentHttpInternalServerError,
] as const;
export class EnvironmentRenderBootstrapHttpApi extends HttpApiGroup.make("renderBootstrap").add(
HttpApiEndpoint.post("pair", "/.well-known/t3/render/pair", {
success: EnvironmentRenderBootstrapPairingResult,
error: EnvironmentRenderBootstrapErrors,
}),
) {}
export class EnvironmentMetadataHttpApi extends HttpApiGroup.make("metadata").add(
HttpApiEndpoint.get("descriptor", "/.well-known/t3/environment", {
success: ExecutionEnvironmentDescriptor,
@@ -551,6 +570,7 @@ export class EnvironmentConnectHttpApi extends HttpApiGroup.make("connect")
) {}
export class EnvironmentHttpApi extends HttpApi.make("environment")
.add(EnvironmentRenderBootstrapHttpApi)
.add(EnvironmentMetadataHttpApi)
.add(EnvironmentAuthHttpApi)
.add(EnvironmentOrchestrationHttpApi)
+20
View File
@@ -0,0 +1,20 @@
services:
- type: web
name: t3code-cloud-demo
runtime: docker
plan: free
repo: https://github.com/pingdotgg/t3code.git
branch: feat/render-cloud-environment
autoDeployTrigger: off
dockerfilePath: ./infra/render/Dockerfile
dockerContext: .
healthCheckPath: /.well-known/t3/environment
envVars:
- key: T3CODE_CLOUD_PROVIDER
value: render
- key: T3CODE_ENVIRONMENT_LABEL
value: Render cloud environment
- key: T3CODE_WORKSPACE_DIR
value: /data/workspace
- key: OPENAI_API_KEY
sync: false