Skip to content
TypeScript

feat(cli): t3 up asks how your other devices reach this machine (#27996)

Theo Brownecadf7d5fe305
diff --git a/apps/server/src/binCli.ts b/apps/server/src/binCli.ts
index b26b4fd9f0d..7c136ae5326 100644
--- a/apps/server/src/binCli.ts
+++ b/apps/server/src/binCli.ts
@@ -13,7 +13,6 @@ import { authCommand } from "./cli/auth.ts";
import { environmentCommand } from "./cli/environment.ts";
import { appCommand } from "./cli/app.ts";
import { browserCommand } from "./cli/browser.ts";
-import { connectCommand } from "./cli/connect.ts";
import { pairCommand } from "./cli/pair.ts";
import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
import { extendConnectionAttemptTimeout, keepOutboundFetchOnHttp1 } from "./outboundHttp.ts";
@@ -31,6 +30,7 @@ import { servicePreflightCommand } from "./cli/servicePreflight.ts";
import { themeCommand } from "./cli/theme.ts";
import { traceCommand } from "./cli/trace.ts";
import { triageCommand } from "./cli/triage.ts";
+import { connectCommand, statusCommand, upCommand } from "./cli/up.ts";
const layerCliRuntime = Layer.mergeAll(NodeServices.layer, NetService.layer);
@@ -60,7 +60,9 @@ const connectUnavailableCommand = Command.make("connect", {
export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
Command.make("t3", { ...sharedServerCommandFlags }).pipe(
- Command.withDescription("Run the T3 Code server."),
+ Command.withDescription(
+ "Run T3 Code in this terminal and open it in your browser. To use it from your other devices, run `t3 up`.",
+ ),
Command.withHandler(runDefaultServerCommand),
Command.withSubcommands([
Command.make("help").pipe(
@@ -80,6 +82,8 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
browserCommand,
projectCommand,
threadCommand,
+ upCommand,
+ statusCommand,
serviceCommand,
updateCommand,
uninstallCommand,
diff --git a/apps/server/src/cli/config.test.ts b/apps/server/src/cli/config.test.ts
index c7f47c655dc..297b225b6ad 100644
--- a/apps/server/src/cli/config.test.ts
+++ b/apps/server/src/cli/config.test.ts
@@ -49,6 +49,7 @@ const minimalDesktopFlags = (baseDir: string) => ({
logWebSocketEvents: Option.none<boolean>(),
tailscaleServeEnabled: Option.none<boolean>(),
tailscaleServePort: Option.none<number>(),
+ lan: Option.none<boolean>(),
});
const encodeDesktopBootstrap = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
@@ -231,6 +232,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
logWebSocketEvents: Option.none<boolean>(),
tailscaleServeEnabled: Option.none<boolean>(),
tailscaleServePort: Option.none<number>(),
+ lan: Option.none<boolean>(),
};
const layerConfig = ConfigProvider.layer(
ConfigProvider.fromEnv({
@@ -275,6 +277,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
logWebSocketEvents: Option.none<boolean>(),
tailscaleServeEnabled: Option.none<boolean>(),
tailscaleServePort: Option.none<number>(),
+ lan: Option.none<boolean>(),
};
const layerConfig = ConfigProvider.layer(
ConfigProvider.fromEnv({ env: { T3CODE_DEV_AUTH_TOKEN: secret } }),
@@ -330,6 +333,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
logWebSocketEvents: Option.some(false),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
+ lan: Option.none(),
},
Option.none(),
).pipe(
@@ -406,6 +410,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
+ lan: Option.none(),
},
Option.some("Debug"),
).pipe(
@@ -553,6 +558,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
+ lan: Option.none(),
},
Option.none(),
).pipe(
@@ -601,6 +607,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
+ lan: Option.none(),
},
Option.none(),
).pipe(
@@ -641,6 +648,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
+ lan: Option.none(),
},
Option.none(),
{
@@ -703,6 +711,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
+ lan: Option.none(),
},
Option.none(),
).pipe(
@@ -742,6 +751,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
logWebSocketEvents: Option.none<boolean>(),
tailscaleServeEnabled: Option.none<boolean>(),
tailscaleServePort: Option.none<number>(),
+ lan: Option.none<boolean>(),
});
it.effect(
@@ -863,7 +873,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
}),
);
- it.effect("listens on private networks only under the service launcher with no host set", () =>
+ it.effect("listens on private networks per T3CODE_LAN, else under the service launcher", () =>
Effect.gen(function* () {
const { join } = yield* Path.Path;
const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-service-host");
@@ -893,6 +903,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
}),
);
+ // A service installed before T3CODE_LAN existed.
expect(yield* resolveHost({ connected: true })).toEqual({
host: "0.0.0.0",
privateNetworkOnly: true,
@@ -902,6 +913,14 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
host: "127.0.0.1",
privateNetworkOnly: undefined,
});
+ expect(yield* resolveHost({ connected: true, env: { T3CODE_LAN: "false" } })).toEqual({
+ host: undefined,
+ privateNetworkOnly: undefined,
+ });
+ expect(yield* resolveHost({ connected: false, env: { T3CODE_LAN: "true" } })).toEqual({
+ host: "0.0.0.0",
+ privateNetworkOnly: true,
+ });
// Without the launcher's IPC channel the context was inherited, e.g. by
// `t3 serve` started from an agent inside the service.
expect(yield* resolveHost({ connected: false })).toEqual({
diff --git a/apps/server/src/cli/config.ts b/apps/server/src/cli/config.ts
index 720569b6137..f86fde0f597 100644
--- a/apps/server/src/cli/config.ts
+++ b/apps/server/src/cli/config.ts
@@ -85,6 +85,12 @@ const tailscaleServePortFlag = Flag.Int("tailscale-serve-port").pipe(
Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale-serve is enabled."),
Flag.optional,
);
+const lanFlag = Flag.Boolean("lan").pipe(
+ Flag.withDescription(
+ "Accept connections from your local network and tailnet, not only this machine (equivalent to T3CODE_LAN).",
+ ),
+ Flag.optional,
+);
export const traceFileConfig = Config.String("T3CODE_TRACE_FILE").pipe(
Config.option,
@@ -165,6 +171,7 @@ const EnvServerConfig = Config.all({
Config.option,
Config.map(Option.getOrUndefined),
),
+ lan: Config.Boolean("T3CODE_LAN").pipe(Config.option, Config.map(Option.getOrUndefined)),
});
const DevAuthTokenConfig = Config.Redacted("T3CODE_DEV_AUTH_TOKEN").pipe(
@@ -200,6 +207,7 @@ export interface CliServerFlags {
readonly logWebSocketEvents: Option.Option<boolean>;
readonly tailscaleServeEnabled: Option.Option<boolean>;
readonly tailscaleServePort: Option.Option<number>;
+ readonly lan: Option.Option<boolean>;
}
export interface CliAuthLocationFlags {
@@ -234,6 +242,7 @@ export const sharedServerCommandFlags = {
logWebSocketEvents: logWebSocketEventsFlag,
tailscaleServeEnabled: tailscaleServeFlag,
tailscaleServePort: tailscaleServePortFlag,
+ lan: lanFlag,
} as const;
const resolveOptionPrecedence = <Value>(
@@ -277,6 +286,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct
logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
+ lan: flags.lan ?? Option.none(),
} satisfies CliServerFlags;
const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
const bootstrapEnvelope =
@@ -410,16 +420,19 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct
Option.fromUndefinedOr(env.host),
Option.fromUndefinedOr(bootstrap?.host),
);
- // A background service exists to be reached from other devices, so it
- // listens on private networks unless `service.env` sets `T3CODE_HOST`.
- // Clients then learn its LAN address and prefer it over T3 Connect.
+ // Private networks only, so clients learn a LAN address and prefer it over
+ // T3 Connect. `t3 service install` writes T3CODE_LAN=false for a new
+ // service; one installed before T3CODE_LAN existed keeps listening.
+ const lan = resolveOptionPrecedence(normalizedFlags.lan, Option.fromUndefinedOr(env.lan));
const privateNetworkOnly =
Option.isNone(explicitHost) &&
mode === "web" &&
- (yield* resolveServiceLauncherMode().pipe(
- Effect.map((launcher) => launcher.managed),
- Effect.orElseSucceed(() => false),
- ));
+ (Option.isSome(lan)
+ ? lan.value
+ : yield* resolveServiceLauncherMode().pipe(
+ Effect.map((launcher) => launcher.managed),
+ Effect.orElseSucceed(() => false),
+ ));
const host = Option.getOrElse(explicitHost, () =>
privateNetworkOnly ? "0.0.0.0" : mode === "desktop" ? "127.0.0.1" : undefined,
);
@@ -530,6 +543,7 @@ export const resolveCliAuthConfig = (
logWebSocketEvents: Option.none(),
tailscaleServeEnabled: Option.none(),
tailscaleServePort: Option.none(),
+ lan: Option.none(),
},
cliLogLevel,
);
diff --git a/apps/server/src/cli/connect.ts b/apps/server/src/cli/connect.ts
index 5e39625754a..e0aea76ef04 100644
--- a/apps/server/src/cli/connect.ts
+++ b/apps/server/src/cli/connect.ts
@@ -9,7 +9,6 @@ import {
type RelayClientInstallProgressStage,
} from "@t3tools/contracts";
import { RelayOkResponse } from "@t3tools/contracts/relay";
-import * as HostProcess from "@t3tools/shared/HostProcess";
import * as RelayClient from "@t3tools/shared/relayClient";
import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
import * as Cause from "effect/Cause";
@@ -23,6 +22,7 @@ import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
+import * as Path from "effect/Path";
import * as References from "effect/References";
import * as Schema from "effect/Schema";
import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
@@ -60,8 +60,10 @@ const jsonFlag = Flag.Boolean("json").pipe(
const isCloudCliTokenManagerError = Schema.is(CliTokenManager.CloudCliTokenManagerError);
-const headlessFlag = Flag.Boolean("headless").pipe(
- Flag.withDescription("Authorize without a local browser using the OAuth device flow."),
+export const headlessFlag = Flag.Boolean("headless").pipe(
+ Flag.withDescription(
+ "Sign in with a URL and code on any device. Automatic without a terminal or over SSH.",
+ ),
Flag.withDefault(false),
);
@@ -85,13 +87,10 @@ function formatDeviceAuthorizationPrompt(
): string {
const minutes = Math.max(1, Math.round(Duration.toMinutes(prompt.expiresIn)));
return [
- "Headless authorization",
- "Open this URL on a device with a browser:",
+ "Sign in to T3 Connect. Open on any device:",
` ${prompt.verificationUriComplete ?? prompt.verificationUri}`,
- "",
- `Confirm this code when asked: ${prompt.userCode}`,
- "",
- `Waiting for approval (expires in ${minutes} min). Press Ctrl+C to cancel.`,
+ `Code: ${prompt.userCode}`,
+ `Waiting for approval. Expires in ${minutes} min. Ctrl+C cancels.`,
].join("\n");
}
@@ -99,20 +98,21 @@ const authorizeCli = Effect.fn("cloud.cli.authorize")(function* (options: {
readonly headless: boolean;
}) {
const tokens = yield* CliTokenManager.CloudCliTokenManager;
- const useOutOfBandOAuth = options.headless || (yield* headlessSessionConfig);
+ // Without a terminal, no key press can open a browser, so sign in with a code.
+ const useOutOfBandOAuth =
+ options.headless ||
+ (yield* headlessSessionConfig) ||
+ !(process.stdin.isTTY && process.stdout.isTTY);
if (!useOutOfBandOAuth) {
const authorization = yield* tokens.get;
if (authorization._tag === "Authorized") {
return authorization.token.identity ?? null;
}
- yield* Console.log("\nHeadless mode enabled. A new authorization link is ready below.");
}
const existing = yield* tokens.getExisting.pipe(
Effect.catchTags({
CloudCliCredentialRefreshError: () =>
- Console.log(
- "The stored T3 Connect credential could not be refreshed; signing in again.",
- ).pipe(Effect.as(Option.none())),
+ Console.log("T3 Connect sign-in expired. Sign in again.").pipe(Effect.as(Option.none())),
}),
);
if (Option.isSome(existing)) {
@@ -363,17 +363,15 @@ function formatAlertBox(text: string): string {
* Waits for the server that `t3 connect` just started to prove other devices
* can reach it, so a broken tunnel fails setup instead of looking green.
*/
-const waitForReachability = Effect.fn("cloud.cli.wait_for_reachability")(function* () {
- yield* Console.log("\nChecking that other devices can reach this machine...");
+export const waitForReachability = Effect.fn("cloud.cli.wait_for_reachability")(function* () {
+ yield* Console.log("Checking T3 Connect...");
const deadline =
(yield* Clock.currentTimeMillis) + Duration.toMillis(CLOUD_CLI_REACHABILITY_WAIT);
let last: EnvironmentConnectReachability | null = null;
while (true) {
last = (yield* checkLiveReachability()) ?? last;
if (last?.status === "reachable") {
- yield* Console.log(
- `✓ Other devices can reach this machine · ${formatConnectReachable(last)}`,
- );
+ yield* Console.log("✓ T3 Connect is reachable.");
return;
}
if ((yield* Clock.currentTimeMillis) >= deadline) break;
@@ -481,7 +479,7 @@ const reportCloudDisconnectResults = Effect.fn("cloud.cli.report_disconnect_resu
},
);
-const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
+export const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
readonly clearAuthorization: boolean;
}) {
yield* CliState.setCliDesiredCloudLink(false);
@@ -505,9 +503,10 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
"Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
);
}
+ return liveResult;
});
-const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E>(
+export const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E>(
flags: { readonly baseDir: Option.Option<string> },
run: Effect.Effect<
A,
@@ -519,6 +518,7 @@ const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E
| BootService.BootService
| Crypto.Crypto
| FileSystem.FileSystem
+ | Path.Path
| HttpClient.HttpClient
| Prompt.Environment
| ServerConfig.ServerConfig
@@ -558,28 +558,35 @@ function formatRelayClientReady(version: string): string {
const linkEnvironmentForConnect = Effect.fn("cloud.cli.link_environment")(function* (options: {
readonly headless: boolean;
readonly publishOnly?: boolean;
+ /** For `t3 up`, where the user already chose T3 Connect: install it quietly, without asking. */
+ readonly installRelayClient?: boolean;
}) {
const publishOnly = options.publishOnly ?? false;
if (!publishOnly) {
const relayClient = yield* RelayClient.RelayClient;
const installed = yield* acquireRelayClientForLink(
relayClient,
- confirmRelayClientInstall,
- reportRelayClientInstallProgress,
+ options.installRelayClient === true ? () => Effect.succeed(true) : confirmRelayClientInstall,
+ options.installRelayClient === true
+ ? (event) =>
+ event.type === "progress" && event.stage === "downloading"
+ ? Console.log("Installing the T3 Connect relay client...")
+ : Effect.void
+ : reportRelayClientInstallProgress,
);
if (Option.isNone(installed)) {
yield* Console.log("T3 Connect setup cancelled. The relay client was not installed.");
return null;
}
- yield* Console.log(formatRelayClientReady(installed.value.version));
+ if (options.installRelayClient !== true) {
+ yield* Console.log(formatRelayClientReady(installed.value.version));
+ }
}
const identity = yield* authorizeCli(options);
yield* CliState.setCliDesiredCloudLink(true, publishOnly ? "publish_only" : "managed");
if (yield* CliState.dropRevokedCloudLink) {
- yield* Console.log(
- "Removed the link T3 Connect no longer accepts. The next start links this environment again.",
- );
+ yield* Console.log("Replacing the link T3 Connect revoked.");
}
if (publishOnly) {
const secrets = yield* ServerSecretStore.ServerSecretStore;
@@ -587,6 +594,7 @@ const linkEnvironmentForConnect = Effect.fn("cloud.cli.link_environment")(functi
}
return { identity } as const;
});
+export { linkEnvironmentForConnect };
const connectLoginCommand = Command.make("login", {
...projectLocationFlags,
@@ -776,62 +784,12 @@ const connectLogoutCommand = Command.make("logout", {
),
);
-const reportServiceOnboarding = Effect.fn("cli.connect.report_service_onboarding")(function* (
- outcome: CliService.ServiceOnboardingOutcome,
-) {
- if (outcome === "pending") {
- yield* Console.log(
- "\nBackground service restarting\n\nThe server establishes the T3 Connect link once it is back. Check the log above if it does not come back.",
- );
- return;
- }
- if (outcome === "ready") {
- const platform = yield* HostProcess.Platform;
- yield* Console.log(
- platform === "darwin"
- ? "\n✓ Background service ready\n\nT3 Code is set to run while you are logged in to this Mac. The server establishes the T3 Connect link on startup."
- : "\n✓ Background service ready\n\nT3 Code is set to keep running after you log out. The server establishes the T3 Connect link on startup.",
- );
- return;
- }
- const serveCommand = yield* resolveCliCommand("serve");
- yield* Console.log(
- `\nNext\n Start the server with \`${serveCommand}\` to make this machine reachable.\n It checks that other devices can reach this machine when it starts.`,
- );
-});
-
-export const connectCommand = Command.make("connect", {
- ...projectLocationFlags,
- headless: headlessFlag,
-}).pipe(
- Command.withDescription("Set up T3 Connect for this machine."),
- Command.withHandler((flags) =>
- runCloudCommand(
- flags,
- Effect.gen(function* () {
- yield* Console.log("T3 Connect\n");
- const linked = yield* linkEnvironmentForConnect(flags);
- if (!linked) {
- return;
- }
- yield* Console.log(`✓ Authorized${connectedAs(linked.identity)}`);
-
- const outcome = yield* CliService.recoverServiceOnboardingOffer(
- CliService.offerServiceDuringOnboarding,
- );
- yield* reportServiceOnboarding(outcome);
- if (outcome !== "skipped") {
- yield* waitForReachability();
- }
- }),
- ),
- ),
- Command.withSubcommands([
- connectLoginCommand,
- connectLinkCommand,
- connectPublishCommand,
- connectStatusCommand,
- connectUnlinkCommand,
- connectLogoutCommand,
- ]),
-);
+// `t3 connect` itself is `t3 up --connect`, in up.ts.
+export const connectSubcommands = [
+ connectLoginCommand,
+ connectLinkCommand,
+ connectPublishCommand,
+ connectStatusCommand,
+ connectUnlinkCommand,
+ connectLogoutCommand,
+] as const;
diff --git a/apps/server/src/cli/pair.ts b/apps/server/src/cli/pair.ts
index abec0f6c5e9..92615b9c837 100644
--- a/apps/server/src/cli/pair.ts
+++ b/apps/server/src/cli/pair.ts
@@ -512,7 +512,7 @@ export const pairCommand = Command.make("pair", {
pairingBaseUrl = resolveDirectPairingBaseUrl(target.state);
if (isLoopbackHost(new URL(pairingBaseUrl).hostname)) {
notes.push(
- "This URL is only reachable from this machine. Re-run with --tailscale, or restart the server with a reachable --host.",
+ "This URL is only reachable from this machine. To reach it from your other devices, run `t3 up`, or re-run with --tailscale.",
);
} else if (target.state.privateNetworkOnly) {
notes.push(
diff --git a/apps/server/src/cli/server.ts b/apps/server/src/cli/server.ts
index fee427cc7fa..c7ef946777a 100644
--- a/apps/server/src/cli/server.ts
+++ b/apps/server/src/cli/server.ts
@@ -69,13 +69,15 @@ export const runDefaultServerCommand = Effect.fn("server.runDefaultServerCommand
});
export const startCommand = Command.make("start", { ...sharedServerCommandFlags }).pipe(
- Command.withDescription("Run the T3 Code server."),
+ Command.withDescription("Same as `t3`."),
+ Command.unlisted,
Command.withHandler((flags) => runServerCommand(flags, { rejectRunningServer: true })),
);
export const serveCommand = Command.make("serve", { ...sharedServerCommandFlags }).pipe(
+ Command.withShortDescription("Run T3 Code in this terminal, with no browser."),
Command.withDescription(
- "Run the T3 Code server without opening a browser and print headless pairing details.",
+ "Run T3 Code in this terminal without opening a browser, and print pairing details. The background service runs this. To set up access from your other devices, run `t3 up`.",
),
Command.withHandler((flags) =>
runServerCommand(flags, {
diff --git a/apps/server/src/cli/service.test.ts b/apps/server/src/cli/service.test.ts
index e66f4bde771..4358165958a 100644
--- a/apps/server/src/cli/service.test.ts
+++ b/apps/server/src/cli/service.test.ts
@@ -6,18 +6,13 @@ import * as ConfigProvider from "effect/ConfigProvider";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
-import * as Terminal from "effect/Terminal";
import * as TestConsole from "effect/testing/TestConsole";
import { Command } from "effect/cli";
import { afterEach, vi } from "vite-plus/test";
import packageJson from "../../package.json" with { type: "json" };
import * as BootService from "../cloud/bootService.ts";
-import {
- offerServiceDuringOnboarding,
- recoverServiceOnboardingOffer,
- serviceCommand,
-} from "./service.ts";
+import { serviceCommand } from "./service.ts";
afterEach(() => vi.restoreAllMocks());
@@ -90,6 +85,47 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands
}),
);
+ it.effect.each([
+ { label: "a new service", installed: false, env: "", expected: "T3CODE_LAN=false\n" },
+ // Services installed before T3CODE_LAN existed keep listening on the local network.
+ { label: "an older service", installed: true, env: "", expected: "" },
+ {
+ label: "a set host",
+ installed: false,
+ env: "T3CODE_HOST=::\n",
+ expected: "T3CODE_HOST=::\n",
+ },
+ ])("install keeps $label off the local network only when it is new", (input) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
+ yield* fs.writeFileString(`${baseDir}/service.env`, input.env);
+ const { service } = makeTestService({
+ ...status,
+ installed: input.installed,
+ current: false,
+ });
+ vi.spyOn(BootService, "layer").mockReturnValue(
+ Layer.succeed(BootService.BootService, service),
+ );
+
+ yield* Command.runWith(serviceCommand, { version: packageJson.version })([
+ "install",
+ "--base-dir",
+ baseDir,
+ ]).pipe(
+ Effect.provideService(HostProcess.Environment, {}),
+ Effect.provide(
+ Layer.mergeAll(
+ ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
+ Layer.fresh(TestConsole.layer),
+ ),
+ ),
+ );
+ expect(yield* fs.readFileString(`${baseDir}/service.env`)).toBe(input.expected);
+ }),
+ );
+
it.effect("protect refuses root before creating any T3 directories", () =>
Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
@@ -159,89 +195,3 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands
}),
);
});
-
-it.effect("leaves a newer service unchanged during onboarding without prompting", () =>
- Effect.gen(function* () {
- const { service, installOptions } = makeTestService(newerServiceStatus);
- const terminal = Terminal.make({
- columns: Effect.succeed(80),
- rows: Effect.succeed(24),
- readInput: Effect.die("Onboarding must not prompt to replace a newer service."),
- readLine: Effect.die("Onboarding must not prompt to replace a newer service."),
- display: () => Effect.die("Onboarding must not prompt to replace a newer service."),
- });
-
- const ready = yield* offerServiceDuringOnboarding.pipe(
- Effect.provideService(BootService.BootService, service),
- Effect.provideService(Terminal.Terminal, terminal),
- Effect.provide(NodeServices.layer),
- );
-
- expect(ready).toBe("skipped");
- expect(installOptions).toEqual([]);
- }),
-);
-
-const withTerminal = (isTTY: { readonly stdin: boolean; readonly stdout: boolean }) =>
- Effect.acquireRelease(
- Effect.sync(() =>
- (
- [
- [process.stdin, isTTY.stdin],
- [process.stdout, isTTY.stdout],
- ] as const
- ).map(([stream, value]) => {
- const descriptor = Object.getOwnPropertyDescriptor(stream, "isTTY");
- Object.defineProperty(stream, "isTTY", { configurable: true, value });
- return { stream, descriptor };
- }),
- ),
- (saved) =>
- Effect.sync(() => {
- for (const { stream, descriptor } of saved) {
- if (descriptor === undefined) Reflect.deleteProperty(stream, "isTTY");
- else Object.defineProperty(stream, "isTTY", descriptor);
- }
- }),
- );
-
-it.effect.each([
- { label: "stdin and stdout are", stdin: false, stdout: false },
- { label: "stdin is", stdin: false, stdout: true },
- { label: "stdout is", stdin: true, stdout: false },
-])("skips the onboarding service prompt when $label not a terminal", (isTTY) =>
- Effect.gen(function* () {
- yield* withTerminal(isTTY);
- const { service, installOptions } = makeTestService({
- ...status,
- installed: false,
- current: false,
- });
- const terminal = Terminal.make({
- columns: Effect.succeed(80),
- rows: Effect.succeed(24),
- readInput: Effect.die("Onboarding must not prompt without a terminal."),
- readLine: Effect.die("Onboarding must not prompt without a terminal."),
- display: () => Effect.die("Onboarding must not prompt without a terminal."),
- });
-
- const ready = yield* offerServiceDuringOnboarding.pipe(
- Effect.provideService(BootService.BootService, service),
- Effect.provideService(Terminal.Terminal, terminal),
- Effect.provide(NodeServices.layer),
- );
-
- expect(ready).toBe("skipped");
- expect(installOptions).toEqual([]);
- }),
-);
-
-// regression: #9602 diagnose incomplete headless server setup
-it.effect("keeps the manual-server fallback when background prerequisites fail", () =>
- Effect.gen(function* () {
- const ready = yield* recoverServiceOnboardingOffer(
- Effect.fail(new BootService.BootServicePrerequisiteError({ problem: "linger-disabled" })),
- );
- expect(ready).toBe("skipped");
- }),
-);
diff --git a/apps/server/src/cli/service.ts b/apps/server/src/cli/service.ts
index 42fcc6a2b90..b78ee31c9fa 100644
--- a/apps/server/src/cli/service.ts
+++ b/apps/server/src/cli/service.ts
@@ -1,17 +1,19 @@
+import * as NodeUtil from "node:util";
+
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as Console from "effect/Console";
import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
-import * as Terminal from "effect/Terminal";
import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
import { FetchHttpClient } from "effect/http";
import packageJson from "../../package.json" with { type: "json" };
import * as BootService from "../cloud/bootService.ts";
import * as ServiceProtection from "../cloud/serviceProtection.ts";
-import { compareExactServiceVersions } from "../cloud/serviceProtocol.ts";
-import type * as ServerConfig from "../config.ts";
+import { compareExactServiceVersions, SERVICE_ENV_FILE } from "../cloud/serviceProtocol.ts";
+import * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
import { resolveEntryPath } from "./invocation.ts";
@@ -34,15 +36,72 @@ export type ServiceReconcileResult =
readonly plan: BootService.BootServicePlan;
};
-const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?: {
+const SERVICE_ENV_KEY = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/u;
+
+/**
+ * Sets or removes (`undefined`) entries in `service.env` text and keeps every
+ * other line, including comments, as the user wrote it.
+ */
+export const upsertServiceEnv = (
+ contents: string,
+ entries: Readonly<Record<string, string | undefined>>,
+): string => {
+ const written = new Set<string>();
+ const lines = contents.split("\n").flatMap((line) => {
+ const key = SERVICE_ENV_KEY.exec(line)?.[1];
+ if (key === undefined || !Object.hasOwn(entries, key)) return [line];
+ const value = entries[key];
+ if (value === undefined || written.has(key)) return [];
+ written.add(key);
+ return [`${key}=${value}`];
+ });
+ while (lines.at(-1) === "") lines.pop();
+ for (const [key, value] of Object.entries(entries)) {
+ if (value !== undefined && !written.has(key)) lines.push(`${key}=${value}`);
+ }
+ return lines.length === 0 ? "" : `${lines.join("\n")}\n`;
+};
+
+/** `service.env` under `baseDir`, parsed as the service launcher parses it. */
+export const readServiceEnv = Effect.fn("cli.service.read_env")(function* (baseDir: string) {
+ const fs = yield* FileSystem.FileSystem;
+ const path = (yield* Path.Path).join(baseDir, SERVICE_ENV_FILE);
+ const contents = (yield* fs.exists(path)) ? yield* fs.readFileString(path) : "";
+ const entries = Object.entries(NodeUtil.parseEnv(contents)).flatMap(([key, value]) =>
+ value === undefined ? [] : [[key, value] as const],
+ );
+ return { path, contents, entries: Object.fromEntries(entries) };
+});
+
+export const writeServiceEnv = Effect.fn("cli.service.write_env")(function* (
+ baseDir: string,
+ entries: Readonly<Record<string, string | undefined>>,
+) {
+ const fs = yield* FileSystem.FileSystem;
+ const current = yield* readServiceEnv(baseDir);
+ const next = upsertServiceEnv(current.contents, entries);
+ if (next === current.contents) return;
+ yield* fs.makeDirectory(baseDir, { recursive: true });
+ yield* fs.writeFileString(current.path, next);
+});
+
+export const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?: {
readonly allowDowngrade?: boolean;
readonly start?: boolean;
}) {
+ const { baseDir } = yield* ServerConfig.ServerConfig;
const service = yield* BootService.BootService;
const status = yield* service.status;
if (status.installed && status.current) {
return { changed: false, status } satisfies ServiceReconcileResult;
}
+ if (status.supported && !status.installed) {
+ // A new service listens on this machine only, until `t3 up` opens the local network.
+ const { entries } = yield* readServiceEnv(baseDir);
+ if (entries.T3CODE_LAN === undefined && entries.T3CODE_HOST === undefined) {
+ yield* writeServiceEnv(baseDir, { T3CODE_LAN: "false" });
+ }
+ }
if (
status.installedVersion !== undefined &&
options?.allowDowngrade !== true &&
@@ -61,13 +120,13 @@ const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?:
} satisfies ServiceReconcileResult;
});
-function formatServiceChange(
+export function formatServiceChange(
result: Extract<ServiceReconcileResult, { readonly changed: true }>,
): string {
if (result.plan.handedOff === true) {
- return `Handed the T3 Code service switch to t3@${packageJson.version} to a separate systemd unit, since this session runs inside the service and disconnects when it restarts.\nResult: ${result.plan.logPath}`;
+ return `Service update to t3@${packageJson.version} queued. This session will disconnect.\nLog: ${result.plan.logPath}`;
}
- return `${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`;
+ return `Service ${result.previouslyInstalled ? "updated" : "installed"} · t3@${packageJson.version}\nLog: ${result.plan.logPath}`;
}
function formatProtection(
@@ -129,7 +188,7 @@ const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E, R>(
) {
const logLevel = yield* GlobalFlag.LogLevel;
const config = yield* resolveCliAuthConfig(flags, logLevel);
- return yield* run.pipe(Effect.provide(layer(config)));
+ return yield* run.pipe(Effect.provide(Layer.merge(layer(config), ServerConfig.layer(config))));
});
const serviceReconcileFlags = {
@@ -141,7 +200,9 @@ const serviceReconcileFlags = {
};
const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pipe(
- Command.withDescription("Install T3 Code as a background service for this user."),
+ Command.withDescription(
+ "Install T3 Code as a background service for this user. `t3 up` also chooses how your other devices reach it.",
+ ),
Command.withHandler((flags) =>
runServiceCommand(
flags,
@@ -154,6 +215,9 @@ const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pip
return;
}
yield* Console.log(formatServiceChange(result));
+ if (!result.previouslyInstalled) {
+ yield* Console.log("Run `t3 up` to choose how your other devices reach it.");
+ }
}),
),
),
@@ -353,96 +417,6 @@ const serviceProtectCommand = Command.make("protect", {
),
);
-export type ServiceOnboardingOutcome = "ready" | "pending" | "skipped";
-
-export const offerServiceDuringOnboarding = Effect.gen(function* () {
- const service = yield* BootService.BootService;
- const status = yield* service.status;
- const { supported, installed, current } = status;
- if (!supported) {
- return "skipped" as const;
- }
- if (installed && current) {
- yield* Console.log("T3 Code is already set up to run in the background on this machine.");
- return "ready" as const;
- }
- for (const problem of status.problems ?? []) {
- yield* Console.warn(`[${problem}] ${BootService.formatBootServiceProblem(problem)}`);
- }
- if (
- installed &&
- status.installedVersion !== undefined &&
- compareExactServiceVersions(status.installedVersion, packageJson.version) > 0
- ) {
- yield* Console.log(
- `A newer t3@${status.installedVersion} background service is installed. Leaving it unchanged.`,
- );
- return "skipped" as const;
- }
- // Both streams must be terminals: with stdout redirected the prompt is
- // invisible and the command would hang waiting on it.
- if (!(process.stdin.isTTY && process.stdout.isTTY)) {
- yield* Console.log(
- "Not a terminal, so background setup was skipped. Run `t3 service install` to set it up.",
- );
- return "skipped" as const;
- }
- const platform = yield* HostProcess.Platform;
- const wanted = yield* Prompt.run(
- Prompt.Confirm({
- message: installed
- ? "The installed T3 Code service needs an update or repair. Update it now?"
- : platform === "darwin"
- ? "Run T3 Code in the background whenever you log in to this Mac? " +
- "It stays reachable through T3 Connect while you are logged in."
- : "Run T3 Code in the background whenever this machine boots? " +
- "It stays reachable through T3 Connect even after you log out.",
- initial: true,
- }),
- );
- if (!wanted) {
- return "skipped" as const;
- }
- const result = yield* reconcileService();
- if (result.changed) {
- yield* Console.log(
- result.plan.handedOff === true
- ? formatServiceChange(result)
- : `Background service ${result.previouslyInstalled ? "updated" : "installed"}. Logs: ${result.plan.logPath}`,
- );
- }
- return result.changed && result.plan.handedOff === true
- ? ("pending" as const)
- : ("ready" as const);
-});
-
-const reportServiceSetupFailure = (error: BootService.BootServiceError) =>
- Console.warn(`Background setup did not finish: ${error.message}`).pipe(
- Effect.as("skipped" as const),
- );
-
-export const recoverServiceOnboardingOffer = <R>(
- offer: Effect.Effect<
- ServiceOnboardingOutcome,
- BootService.BootServiceError | Terminal.QuitError,
- R
- >,
-) =>
- offer.pipe(
- Effect.catchTags({
- QuitError: () => Effect.succeed("skipped" as const),
- BootServiceUnsupportedError: (error) =>
- Console.log(`Skipping background setup: ${error.message}`).pipe(
- Effect.as("skipped" as const),
- ),
- BootServiceCommandError: reportServiceSetupFailure,
- BootServiceInstallError: reportServiceSetupFailure,
- BootServicePrerequisiteError: reportServiceSetupFailure,
- BootServiceUpdatePendingError: reportServiceSetupFailure,
- BootServiceDowngradeRefusedError: reportServiceSetupFailure,
- }),
- );
-
export const serviceCommand = Command.make("service").pipe(
Command.withDescription("Manage the T3 Code background service."),
Command.withSubcommands([
diff --git a/apps/server/src/cli/up.connect.test.ts b/apps/server/src/cli/up.connect.test.ts
new file mode 100644
index 00000000000..a0d707e5051
--- /dev/null
+++ b/apps/server/src/cli/up.connect.test.ts
@@ -0,0 +1,126 @@
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { expect, it } from "@effect/vitest";
+import * as HostProcess from "@t3tools/shared/HostProcess";
+import * as NetService from "@t3tools/shared/Net";
+import * as ConfigProvider from "effect/ConfigProvider";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Layer from "effect/Layer";
+import * as TestConsole from "effect/testing/TestConsole";
+import { Command } from "effect/cli";
+import { vi } from "vite-plus/test";
+
+import packageJson from "../../package.json" with { type: "json" };
+import * as BootService from "../cloud/bootService.ts";
+import { upCommand } from "./up.ts";
+
+// T3 Connect's flows run only in builds with its public config, and they call
+// the relay; this file swaps in the link and unlink steps.
+const events = vi.hoisted((): Array<string> => []);
+// The CLI link marker, kept in memory instead of the secret store.
+const link = vi.hoisted(() => ({
+ desired: false,
+ mode: "managed" as "managed" | "publish_only",
+}));
+vi.mock("../cloud/CliState.ts", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../cloud/CliState.ts")>()),
+ readCliDesiredCloudLink: Effect.sync(() => link.desired),
+ readCliDesiredLinkMode: Effect.sync(() => link.mode),
+ setCliDesiredCloudLink: (desired: boolean, mode: "managed" | "publish_only" = "managed") =>
+ Effect.sync(() => {
+ link.desired = desired;
+ link.mode = mode;
+ }),
+}));
+vi.mock("../cloud/publicConfig.ts", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../cloud/publicConfig.ts")>()),
+ hasCloudPublicConfig: true,
+}));
+vi.mock("./connect.ts", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("./connect.ts")>();
+ return {
+ ...actual,
+ linkEnvironmentForConnect: () =>
+ Effect.sync(() => {
+ events.push("link");
+ link.desired = true;
+ link.mode = "managed";
+ return { identity: "[email protected]" } as const;
+ }),
+ disconnectCloud: () =>
+ Effect.sync(() => {
+ events.push("unlink");
+ link.desired = false;
+ return { status: "succeeded" } as const;
+ }),
+ };
+});
+
+it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 up with T3 Connect", (it) => {
+ it.effect.each([
+ { label: "no link", prior: null, events: ["link", "restart", "unlink", "restart"] },
+ // The publish-only link comes back, with its activity publishing.
+ {
+ label: "a publish-only link",
+ prior: "publish_only" as const,
+ events: ["link", "restart", "restart"],
+ },
+ ])("a failed restart after --connect undoes it, then restarts: $label before", (input) =>
+ Effect.gen(function* () {
+ events.length = 0;
+ link.desired = input.prior !== null;
+ link.mode = input.prior ?? "managed";
+ const fs = yield* FileSystem.FileSystem;
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-up-connect-test-" });
+ yield* fs.writeFileString(`${baseDir}/service.env`, "T3CODE_LAN=false\n");
+ const status = {
+ supported: true,
+ installed: true,
+ current: true,
+ unitPath: "/home/me/.config/systemd/user/t3code.service",
+ logPath: "/home/me/.t3/userdata/logs/boot-service.log",
+ };
+ vi.spyOn(BootService, "layer").mockReturnValue(
+ Layer.succeed(
+ BootService.BootService,
+ BootService.BootService.of({
+ status: Effect.succeed(status),
+ withStopped: (operation) => operation,
+ restart: Effect.sync(() => events.push("restart")).pipe(
+ Effect.andThen(
+ Effect.fail(new BootService.BootServiceCommandError({ step: "restart" })),
+ ),
+ ),
+ install: () => Effect.die("an installed, current service is not reinstalled"),
+ uninstall: Effect.succeed(false),
+ }),
+ ),
+ );
+
+ const exit = yield* Command.runWith(upCommand, { version: packageJson.version })([
+ "--base-dir",
+ baseDir,
+ "--connect",
+ ]).pipe(
+ Effect.provideService(HostProcess.Environment, {}),
+ Effect.provide(
+ Layer.mergeAll(
+ ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
+ Layer.fresh(TestConsole.layer),
+ ),
+ ),
+ Effect.exit,
+ );
+
+ expect(exit._tag).toBe("Failure");
+ // Any unlink comes before the restart on the old settings.
+ expect(events).toEqual(input.events);
+ expect(link).toEqual(
+ input.prior === null
+ ? { desired: false, mode: "managed" }
+ : { desired: true, mode: input.prior },
+ );
+ expect(yield* fs.readFileString(`${baseDir}/service.env`)).toBe("T3CODE_LAN=false\n");
+ }),
+ );
+});
diff --git a/apps/server/src/cli/up.test.ts b/apps/server/src/cli/up.test.ts
new file mode 100644
index 00000000000..9fbe515944a
--- /dev/null
+++ b/apps/server/src/cli/up.test.ts
@@ -0,0 +1,356 @@
+import * as NodeServices from "@effect/platform-node/NodeServices";
+import { expect, it } from "@effect/vitest";
+import * as HostProcess from "@t3tools/shared/HostProcess";
+import * as NetService from "@t3tools/shared/Net";
+import * as Cause from "effect/Cause";
+import * as ConfigProvider from "effect/ConfigProvider";
+import * as Effect from "effect/Effect";
+import * as FileSystem from "effect/FileSystem";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import * as Queue from "effect/Queue";
+import * as Terminal from "effect/Terminal";
+import * as TestConsole from "effect/testing/TestConsole";
+import { Command } from "effect/cli";
+import { afterEach, vi } from "vite-plus/test";
+
+import packageJson from "../../package.json" with { type: "json" };
+import * as BootService from "../cloud/bootService.ts";
+import { upsertServiceEnv } from "./service.ts";
+import { connectEnabled, planRoutes, upCommand } from "./up.ts";
+
+const none = Option.none<boolean>();
+
+it.each([
+ {
+ label: "a new machine starts from T3 Connect and asks",
+ setup: { installed: false, connect: false, lan: false },
+ flags: { connect: none, lan: none },
+ expected: { routes: { connect: true, lan: false }, ask: ["connect", "lan"] },
+ },
+ {
+ label: "a build without T3 Connect never offers it",
+ setup: { installed: false, connect: null, lan: false },
+ flags: { connect: none, lan: none },
+ expected: { routes: { connect: false, lan: false }, ask: ["lan"] },
+ },
+ {
+ label: "a rerun starts from the current setup",
+ setup: { installed: true, connect: false, lan: true },
+ flags: { connect: none, lan: none },
+ expected: { routes: { connect: false, lan: true }, ask: ["connect", "lan"] },
+ },
+ {
+ label: "a route flag on a new machine turns on only that route",
+ setup: { installed: false, connect: false, lan: false },
+ flags: { connect: none, lan: Option.some(true) },
+ expected: { routes: { connect: false, lan: true }, ask: [] },
+ },
+ {
+ label: "a route flag asks nothing and keeps the other route",
+ setup: { installed: true, connect: true, lan: true },
+ flags: { connect: none, lan: Option.some(false) },
+ expected: { routes: { connect: true, lan: false }, ask: [] },
+ },
+])("$label", ({ setup, flags, expected }) => {
+ expect(planRoutes(setup, flags)).toEqual(expected);
+});
+
+const SERVICE = {
+ supported: true,
+ installed: true,
+ current: true,
+ unitPath: "/home/me/.config/systemd/user/t3code.service",
+ logPath: "/home/me/.t3/userdata/logs/boot-service.log",
+} as const;
+
+it.each([
+ {
+ label: "a CLI managed link",
+ cliDesired: true,
+ cliMode: "managed",
+ managedTunnel: false,
+ revoked: false,
+ on: true,
+ },
+ {
+ label: "a link the app made",
+ cliDesired: false,
+ cliMode: "managed",
+ managedTunnel: true,
+ revoked: false,
+ on: true,
+ },
+ {
+ label: "a publish-only link",
+ cliDesired: true,
+ cliMode: "publish_only",
+ managedTunnel: false,
+ revoked: false,
+ on: false,
+ },
+ {
+ label: "a publish-only link with an old tunnel config",
+ cliDesired: true,
+ cliMode: "publish_only",
+ managedTunnel: true,
+ revoked: false,
+ on: false,
+ },
+ {
+ label: "a revoked link",
+ cliDesired: true,
+ cliMode: "managed",
+ managedTunnel: true,
+ revoked: true,
+ on: false,
+ },
+ {
+ label: "no link",
+ cliDesired: false,
+ cliMode: "managed",
+ managedTunnel: false,
+ revoked: false,
+ on: false,
+ },
+] as const)("T3 Connect is on for $label: $on", ({ label: _, on, ...link }) => {
+ expect(connectEnabled(link)).toBe(on);
+});
+
+// Prompts run only when both streams are terminals.
+const asTerminal = Effect.acquireRelease(
+ Effect.sync(() =>
+ [process.stdin, process.stdout].map((stream) => {
+ const descriptor = Object.getOwnPropertyDescriptor(stream, "isTTY");
+ Object.defineProperty(stream, "isTTY", { configurable: true, value: true });
+ return { stream, descriptor };
+ }),
+ ),
+ (saved) =>
+ Effect.sync(() => {
+ for (const { stream, descriptor } of saved) {
+ if (descriptor === undefined) Reflect.deleteProperty(stream, "isTTY");
+ else Object.defineProperty(stream, "isTTY", descriptor);
+ }
+ }),
+);
+
+const answering = (text: string) =>
+ Terminal.make({
+ columns: Effect.succeed(80),
+ rows: Effect.succeed(24),
+ readInput: Effect.gen(function* () {
+ const input = yield* Queue.unbounded<Terminal.UserInput, Cause.Done>();
+ yield* Queue.offer(input, {
+ input: Option.some(text),
+ key: { name: text, ctrl: false, meta: false, shift: false },
+ });
+ return input;
+ }),
+ readLine: Effect.succeed(text),
+ display: () => Effect.void,
+ });
+
+it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 up", (it) => {
+ afterEach(() => vi.restoreAllMocks());
+
+ it.effect.each<{
+ readonly label: string;
+ readonly installed: boolean;
+ readonly status?: Partial<BootService.BootServiceStatus>;
+ readonly installFails?: boolean;
+ readonly restartFails?: boolean;
+ /** Runs as if in a terminal, answering each question with this text. */
+ readonly answer?: string;
+ readonly prints?: string;
+ readonly env: string;
+ readonly args: ReadonlyArray<string>;
+ readonly installs: number;
+ readonly restarts: number;
+ readonly envAfter: string;
+ }>([
+ {
+ label: "nothing changed",
+ installed: true,
+ env: "T3CODE_LAN=false\n",
+ args: ["--no-lan"],
+ installs: 0,
+ restarts: 0,
+ envAfter: "T3CODE_LAN=false\n",
+ },
+ {
+ label: "the local network opens",
+ installed: true,
+ env: "T3CODE_LAN=false\n",
+ args: ["--lan"],
+ installs: 0,
+ restarts: 1,
+ envAfter: "T3CODE_LAN=true\n",
+ },
+ {
+ label: "a new service starts with its settings",
+ installed: false,
+ env: "",
+ args: ["--lan"],
+ installs: 1,
+ restarts: 0,
+ envAfter: "T3CODE_LAN=true\n",
+ },
+ {
+ label: "a route turns off with no service to run",
+ installed: false,
+ env: "T3CODE_LAN=true\n",
+ args: ["--no-lan"],
+ installs: 0,
+ restarts: 0,
+ envAfter: "T3CODE_LAN=false\n",
+ },
+ {
+ label: "a stopped newer service starts as it is",
+ installed: true,
+ status: { current: false, installedVersion: "999.0.0", problems: ["service-stopped"] },
+ env: "T3CODE_LAN=false\n",
+ args: ["--yes"],
+ installs: 0,
+ restarts: 1,
+ envAfter: "T3CODE_LAN=false\n",
+ },
+ {
+ label: "a failed update keeps service.env matching the old service",
+ // The old service still runs, so no foreground server is offered.
+ prints: "Fix that, then run `t3 up` again.",
+ installed: true,
+ status: { current: false },
+ installFails: true,
+ env: "",
+ args: ["--no-lan"],
+ installs: 0,
+ restarts: 0,
+ envAfter: "",
+ },
+ {
+ label: "a failed restart puts service.env back and restarts on it",
+ installed: true,
+ restartFails: true,
+ env: "T3CODE_LAN=false\n",
+ args: ["--lan"],
+ installs: 0,
+ restarts: 2,
+ envAfter: "T3CODE_LAN=false\n",
+ },
+ {
+ label: "declining an update changes nothing",
+ installed: true,
+ status: { current: false },
+ answer: "n",
+ env: "T3CODE_LAN=false\n",
+ args: ["--lan"],
+ installs: 0,
+ restarts: 0,
+ envAfter: "T3CODE_LAN=false\n",
+ },
+ {
+ label: "no service manager still records the choice",
+ installed: false,
+ status: { supported: false },
+ env: "",
+ args: ["--lan"],
+ installs: 0,
+ restarts: 0,
+ envAfter: "T3CODE_LAN=true\n",
+ },
+ {
+ label: "the old default is kept",
+ installed: true,
+ env: "",
+ args: ["--yes"],
+ installs: 0,
+ restarts: 0,
+ envAfter: "T3CODE_LAN=true\n",
+ },
+ ])("restarts the service only when it must: $label", (input) =>
+ Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-up-test-" });
+ yield* fs.writeFileString(`${baseDir}/service.env`, input.env);
+ let installs = 0;
+ let restarts = 0;
+ const status = {
+ ...SERVICE,
+ installed: input.installed,
+ current: input.installed,
+ ...input.status,
+ };
+ vi.spyOn(BootService, "layer").mockReturnValue(
+ Layer.succeed(
+ BootService.BootService,
+ BootService.BootService.of({
+ status: Effect.succeed(status),
+ withStopped: (operation) => operation,
+ restart: Effect.sync(() => restarts++).pipe(
+ Effect.andThen(
+ input.restartFails === true
+ ? Effect.fail(new BootService.BootServiceCommandError({ step: "restart" }))
+ : Effect.succeed("restarted" as const),
+ ),
+ ),
+ install: () =>
+ input.installFails === true
+ ? Effect.fail(
+ new BootService.BootServicePrerequisiteError({ problem: "linger-disabled" }),
+ )
+ : Effect.sync(() => {
+ installs++;
+ return {
+ program: ["t3"],
+ baseDir,
+ unitPath: status.unitPath,
+ logPath: status.logPath,
+ };
+ }),
+ uninstall: Effect.succeed(false),
+ }),
+ ),
+ );
+
+ if (input.answer !== undefined) yield* asTerminal;
+ const { exit, lines } = yield* Command.runWith(upCommand, { version: packageJson.version })([
+ "--base-dir",
+ baseDir,
+ ...input.args,
+ ]).pipe(
+ Effect.provideService(HostProcess.Environment, {}),
+ input.answer === undefined
+ ? (effect) => effect
+ : Effect.provideService(Terminal.Terminal, answering(input.answer)),
+ Effect.exit,
+ Effect.flatMap((exit) =>
+ Effect.map(TestConsole.logLines, (lines) => ({ exit, lines: lines.map(String) })),
+ ),
+ Effect.provide(
+ Layer.mergeAll(
+ ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
+ Layer.fresh(TestConsole.layer),
+ ),
+ ),
+ );
+ if (input.prints !== undefined) {
+ expect(lines.join("\n")).toContain(input.prints);
+ }
+ expect(exit._tag).toBe(input.restartFails === true ? "Failure" : "Success");
+ expect({ installs, restarts }).toEqual({
+ installs: input.installs,
+ restarts: input.restarts,
+ });
+ expect(yield* fs.readFileString(`${baseDir}/service.env`)).toBe(input.envAfter);
+ }),
+ );
+});
+
+it("rewrites only the named service.env keys and keeps the user's lines", () => {
+ const before = ["# my settings", "T3CODE_PORT=4000", "export T3CODE_LAN=0", "T3CODE_LAN=1", ""];
+ expect(upsertServiceEnv(before.join("\n"), { T3CODE_LAN: "true", T3CODE_HOST: undefined })).toBe(
+ ["# my settings", "T3CODE_PORT=4000", "T3CODE_LAN=true", ""].join("\n"),
+ );
+ expect(upsertServiceEnv("", { T3CODE_LAN: "false" })).toBe("T3CODE_LAN=false\n");
+});
diff --git a/apps/server/src/cli/up.ts b/apps/server/src/cli/up.ts
new file mode 100644
index 00000000000..7f307aec4b3
--- /dev/null
+++ b/apps/server/src/cli/up.ts
@@ -0,0 +1,510 @@
+import * as HostProcess from "@t3tools/shared/HostProcess";
+import * as Config from "effect/Config";
+import * as ConfigProvider from "effect/ConfigProvider";
+import * as Console from "effect/Console";
+import * as Effect from "effect/Effect";
+import * as Layer from "effect/Layer";
+import * as Option from "effect/Option";
+import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
+import * as CliError from "effect/cli/CliError";
+
+import packageJson from "../../package.json" with { type: "json" };
+import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
+import * as BootService from "../cloud/bootService.ts";
+import * as CliState from "../cloud/CliState.ts";
+import { CLOUD_ENDPOINT_RUNTIME_CONFIG, CLOUD_LINK_REVOKED } from "../cloud/config.ts";
+import { hasCloudPublicConfig } from "../cloud/publicConfig.ts";
+import { compareExactServiceVersions } from "../cloud/serviceProtocol.ts";
+import * as ServerConfig from "../config.ts";
+import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
+import {
+ connectSubcommands,
+ disconnectCloud,
+ headlessFlag,
+ linkEnvironmentForConnect,
+ runCloudCommand,
+ waitForReachability,
+} from "./connect.ts";
+import { resolveHostCliCommand } from "./invocation.ts";
+import * as CliService from "./service.ts";
+
+type Route = "connect" | "lan";
+type Routes = Readonly<Record<Route, boolean>>;
+
+/** How other devices reach this machine now. */
+interface Setup {
+ readonly service: BootService.BootServiceStatus;
+ /** Null in builds without T3 Connect. Off when T3 Connect revoked the link. */
+ readonly connect: boolean | null;
+ /** T3 Connect revoked the link; `t3 connect` links again. */
+ readonly connectRevoked: boolean;
+ readonly lan: boolean;
+ /** An installed service with no T3CODE_LAN keeps the old default: on. */
+ readonly lanFromOldDefault: boolean;
+ readonly host: string | undefined;
+}
+
+/**
+ * T3 Connect is on when this CLI asked for a managed link, or when the desktop or
+ * web app made one: that saves the tunnel config but no CLI marker. Revoked is off.
+ */
+export const connectEnabled = (link: {
+ readonly cliDesired: boolean;
+ readonly cliMode: CliState.CliDesiredLinkMode;
+ readonly managedTunnel: boolean;
+ readonly revoked: boolean;
+}) =>
+ // The server starts no tunnel for a CLI publish-only link, even with an old tunnel config.
+ !link.revoked && (link.cliDesired ? link.cliMode === "managed" : link.managedTunnel);
+
+const readSetup = Effect.fn("cli.up.read_setup")(function* () {
+ const { baseDir } = yield* ServerConfig.ServerConfig;
+ const service = yield* (yield* BootService.BootService).status;
+ const { entries } = yield* CliService.readServiceEnv(baseDir);
+ // Parsed as the server parses it.
+ const lan = yield* Config.Boolean("T3CODE_LAN")
+ .pipe(Config.option)
+ .parse(ConfigProvider.fromEnv({ env: entries }));
+ const secrets = yield* ServerSecretStore.ServerSecretStore;
+ const connectRevoked =
+ hasCloudPublicConfig && Option.isSome(yield* secrets.get(CLOUD_LINK_REVOKED));
+ const connect = hasCloudPublicConfig
+ ? connectEnabled({
+ cliDesired: yield* CliState.readCliDesiredCloudLink,
+ cliMode: yield* CliState.readCliDesiredLinkMode,
+ managedTunnel: Option.isSome(yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)),
+ revoked: connectRevoked,
+ })
+ : null;
+ return {
+ service,
+ connect,
+ connectRevoked,
+ lan: Option.getOrElse(lan, () => service.installed),
+ lanFromOldDefault: Option.isNone(lan) && service.installed,
+ host: entries.T3CODE_HOST,
+ } satisfies Setup;
+});
+
+/**
+ * The routes `t3 up` starts from. With no route flag it asks about every
+ * route, starting a machine with no service from T3 Connect. Any route flag
+ * means it asks nothing and keeps the routes not named as they are.
+ */
+export const planRoutes = (
+ setup: { readonly installed: boolean; readonly connect: boolean | null; readonly lan: boolean },
+ flags: { readonly connect: Option.Option<boolean>; readonly lan: Option.Option<boolean> },
+) => {
+ const ask = Option.isNone(flags.connect) && Option.isNone(flags.lan);
+ const start = {
+ connect: setup.connect === true || (ask && !setup.installed && setup.connect !== null),
+ lan: setup.lan,
+ };
+ return {
+ routes: {
+ connect: Option.getOrElse(flags.connect, () => start.connect),
+ lan: Option.getOrElse(flags.lan, () => start.lan),
+ } satisfies Routes,
+ ask: ask
+ ? (["connect", "lan"] as const).filter((r) => r !== "connect" || setup.connect !== null)
+ : [],
+ };
+};
+
+/** A running service reads T3CODE_LAN and its T3 Connect link only when it starts. */
+const needsRestart = (before: Routes, after: Routes) =>
+ after.lan !== before.lan || (after.connect && !before.connect);
+
+const CHOICES = {
+ connect: { title: "T3 Connect", description: "Creates a tunnel to control your PC." },
+ lan: { title: "Local network", description: "LAN and tailnet. Pairing code required." },
+} satisfies Record<Route, { readonly title: string; readonly description: string }>;
+
+const formatSetup = (setup: Setup) => {
+ const { service } = setup;
+ const rows: ReadonlyArray<readonly [string, string]> = [
+ [
+ "Service",
+ !service.supported
+ ? "unavailable"
+ : service.installed
+ ? `installed · t3@${service.installedVersion ?? packageJson.version}`
+ : "not installed",
+ ],
+ ...(setup.connect === null
+ ? []
+ : [
+ [
+ "T3 Connect",
+ setup.connect
+ ? "on · your T3 account"
+ : setup.connectRevoked
+ ? "off · link revoked. Run `t3 connect`."
+ : "off",
+ ] as const,
+ ]),
+ [
+ "Local network",
+ setup.host !== undefined
+ ? `overridden · T3CODE_HOST=${setup.host}`
+ : setup.lanFromOldDefault
+ ? "on · kept from an older install"
+ : setup.lan
+ ? "on · pairing code only"
+ : "off",
+ ],
+ ];
+ const notes = [
+ ...(setup.host === undefined && setup.lan
+ ? ["Anyone on your LAN or tailnet can reach the port. A pairing code is the only lock."]
+ : []),
+ ...(setup.lanFromOldDefault
+ ? ["Older installs keep LAN access on. Turn it off: `t3 up --no-lan`."]
+ : []),
+ ];
+ return [
+ ...rows.map(([label, value]) => ` ${label.padEnd(15)}${value}`),
+ ...(notes.length === 0 ? [] : ["", ...notes]),
+ ].join("\n");
+};
+
+const formatNextSteps = (routes: Routes, serviceInstalled: boolean) =>
+ [
+ ...(routes.connect
+ ? ["On your other device, sign in to T3 Connect with the same account."]
+ : []),
+ ...(routes.lan ? ["Run `t3 pair`. Use the code on your other device."] : []),
+ ...(routes.connect || routes.lan
+ ? []
+ : [
+ serviceInstalled
+ ? "Remote access is off. T3 Code still runs here in the background."
+ : "Remote access is off. Run `t3` to use T3 Code here.",
+ ]),
+ ].join("\n");
+
+const interactiveTerminal = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);
+
+const setUp = Effect.fn("cli.up")(function* (flags: {
+ readonly baseDir: Option.Option<string>;
+ readonly connect: Option.Option<boolean>;
+ readonly lan: Option.Option<boolean>;
+ readonly yes: boolean;
+ readonly headless: boolean;
+}) {
+ const { baseDir } = yield* ServerConfig.ServerConfig;
+ const service = yield* BootService.BootService;
+ const before = yield* readSetup();
+ if (before.connect === null && Option.getOrElse(flags.connect, () => false)) {
+ return yield* new CliError.UserError({
+ cause: "connect",
+ userMessage: "T3 Connect is unavailable in this build.",
+ });
+ }
+
+ const current = { connect: before.connect === true, lan: before.lan };
+ // A publish-only link is not "on", but a rollback must put it back.
+ const priorPublishOnly =
+ hasCloudPublicConfig &&
+ (yield* CliState.readCliDesiredCloudLink) &&
+ (yield* CliState.readCliDesiredLinkMode) === "publish_only";
+ const plan = planRoutes({ ...before, installed: before.service.installed }, flags);
+ const interactive = !flags.yes && interactiveTerminal();
+ let routes = plan.routes;
+ if (plan.ask.length > 0 && interactive) {
+ if (before.service.installed) yield* Console.log(`Current setup\n${formatSetup(before)}\n`);
+ const picked = yield* Prompt.run(
+ Prompt.MultiSelect({
+ message: "Allow connections through:",
+ selectAll: "Select all",
+ selectNone: "Clear all",
+ inverseSelection: "Invert selection",
+ choices: plan.ask.map((route) => ({
+ ...CHOICES[route],
+ value: route,
+ selected: plan.routes[route],
+ })),
+ }),
+ ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(null) }));
+ if (picked === null) return yield* Console.log("Nothing changed.");
+ routes = { connect: picked.includes("connect"), lan: picked.includes("lan") };
+ } else if (plan.ask.length > 0 && !flags.yes && !before.service.installed) {
+ return yield* new CliError.UserError({
+ cause: "routes",
+ userMessage: `No terminal. Choose access with ${
+ before.connect === null ? "--lan" : "--connect or --lan"
+ }, or use --yes for the default. See \`t3 up --help\`.`,
+ });
+ }
+ // Nothing to run in the background, but a route left on still gets turned off.
+ if (!before.service.installed && !routes.connect && !routes.lan) {
+ if (current.connect || before.connectRevoked) {
+ yield* disconnectCloud({ clearAuthorization: false });
+ }
+ if (current.lan) yield* CliService.writeServiceEnv(baseDir, { T3CODE_LAN: "false" });
+ return yield* Console.log(formatNextSteps(routes, false));
+ }
+ const { installedVersion } = before.service;
+ const newer =
+ installedVersion !== undefined &&
+ compareExactServiceVersions(installedVersion, packageJson.version) > 0;
+ // Asked before anything changes, so a declined restart leaves service.env
+ // matching what the running service read when it started.
+ // A stopped service of this version is not current, so reconcile starts it;
+ // a newer one is left alone and needs this restart to start.
+ const stopped = before.service.problems?.includes("service-stopped") === true;
+ const restart =
+ before.service.installed &&
+ (before.service.current || newer) &&
+ (needsRestart(current, routes) || stopped);
+ // An older or broken service is reinstalled, which restarts it too.
+ const update = before.service.installed && !before.service.current && !newer && !stopped;
+ if ((restart || update) && interactive && !stopped) {
+ const confirmed = yield* Prompt.run(
+ Prompt.Confirm({
+ message: update
+ ? "Update and restart T3 Code? Running agent turns will stop."
+ : "Apply changes and restart? Running agent turns will stop.",
+ initial: true,
+ }),
+ ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) }));
+ if (!confirmed) return yield* Console.log("Nothing changed.");
+ }
+
+ if (routes.connect && !current.connect) {
+ const linked = yield* linkEnvironmentForConnect({
+ headless: flags.headless,
+ installRelayClient: true,
+ });
+ if (linked === null) return;
+ yield* Console.log(
+ `✓ Signed in to T3 Connect${linked.identity ? ` as ${linked.identity}` : ""}`,
+ );
+ }
+ // A running server unlinks live; when that fails, only a restart stops its tunnel.
+ const unlinkFailed =
+ !routes.connect && (current.connect || before.connectRevoked)
+ ? (yield* disconnectCloud({ clearAuthorization: false })).status === "failed"
+ : false;
+ const previousLan = (yield* CliService.readServiceEnv(baseDir)).entries.T3CODE_LAN;
+ // Also with no service manager: the file records the choice that `t3 status` shows.
+ yield* CliService.writeServiceEnv(baseDir, { T3CODE_LAN: String(routes.lan) });
+ // When the service step fails, an installed service still runs with the old
+ // value, so the file goes back to match it.
+ // A new T3 Connect link is undone too, with any tunnel the failed start saved, so a
+ // rerun sees it as a change and restarts. The sign-in stays.
+ const restoreServiceEnv = before.service.installed
+ ? CliService.writeServiceEnv(baseDir, { T3CODE_LAN: previousLan }).pipe(
+ Effect.andThen(
+ !routes.connect || current.connect
+ ? Effect.void
+ : priorPublishOnly
+ ? CliState.setCliDesiredCloudLink(true, "publish_only")
+ : disconnectCloud({ clearAuthorization: false }).pipe(Effect.asVoid),
+ ),
+ )
+ : Effect.void;
+ // A failed update or restart may still have started the service with the new
+ // settings, so restart it once more on the old ones.
+ const rollBack = before.service.installed
+ ? restoreServiceEnv.pipe(Effect.andThen(service.restart.pipe(Effect.ignore)))
+ : Effect.void;
+ if (before.host !== undefined) {
+ yield* Console.warn(
+ `T3CODE_HOST=${before.host} in service.env overrides the network choice. Remove it to apply it.`,
+ );
+ }
+
+ const printServeCommand = Effect.fn(function* (reason: string) {
+ const { command } = yield* resolveHostCliCommand("serve", [
+ ...Option.match(flags.baseDir, { onNone: () => [], onSome: (dir) => ["--base-dir", dir] }),
+ // Explicit either way, so a T3CODE_LAN in the shell cannot override the choice.
+ routes.lan ? "--lan" : "--no-lan",
+ ]);
+ yield* Console.log(`${reason} Keep this command running:\n ${command}`);
+ // A host wins over --lan and --no-lan, as it does in service.env.
+ const shellHost = (yield* HostProcess.Environment).T3CODE_HOST;
+ if (shellHost !== undefined) {
+ yield* Console.warn(
+ `T3CODE_HOST=${shellHost} in this shell overrides that choice. Unset it before you run the command.`,
+ );
+ }
+ });
+ let started = false;
+ if (!before.service.supported) {
+ yield* printServeCommand("Background service unavailable.");
+ } else {
+ if (newer) {
+ yield* Console.log(`Keeping installed service version t3@${installedVersion}.`);
+ }
+ if (update && !interactive) {
+ yield* Console.log("Updating T3 Code. Running agent turns will stop.");
+ }
+ const result = newer
+ ? ({ changed: false } as const)
+ : yield* CliService.reconcileService().pipe(
+ Effect.catchTags({
+ BootServicePrerequisiteError: (error) => Effect.succeed({ failed: error.message }),
+ BootServiceUnsupportedError: (error) => Effect.succeed({ failed: error.message }),
+ }),
+ Effect.tapError(() => rollBack),
+ );
+ if ("failed" in result && before.service.installed) {
+ // The old service still runs, so a foreground server would clash with it.
+ yield* restoreServiceEnv;
+ yield* Console.log(
+ `Service setup failed: ${result.failed} Fix that, then run \`t3 up\` again.`,
+ );
+ } else if ("failed" in result) {
+ yield* printServeCommand(`Service setup failed: ${result.failed}`);
+ } else if (result.changed) {
+ yield* Console.log(CliService.formatServiceChange(result));
+ started = true;
+ } else if (restart || (unlinkFailed && before.service.installed)) {
+ const confirmed =
+ restart ||
+ !interactive ||
+ (yield* Prompt.run(
+ Prompt.Confirm({
+ message:
+ "The running service still has T3 Connect on. Restart it? Running agent turns will stop.",
+ initial: true,
+ }),
+ ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) })));
+ if (!confirmed) {
+ yield* Console.log("Run `t3 service restart` to turn T3 Connect off.");
+ } else {
+ if (!interactive && !stopped) {
+ yield* Console.log("Restarting T3 Code. Running agent turns will stop.");
+ }
+ const outcome = yield* service.restart.pipe(Effect.tapError(() => rollBack));
+ if (outcome === "queued") {
+ yield* Console.log("Restart queued. This session will disconnect.");
+ }
+ if (outcome === "skipped") {
+ yield* Console.log(
+ "The installed service runs another T3 home, so it was not restarted. Pass its --base-dir.",
+ );
+ }
+ started = outcome === "restarted";
+ }
+ }
+ }
+ if (started && routes.connect && !current.connect) yield* waitForReachability();
+
+ const after = yield* readSetup();
+ yield* Console.log(
+ // From what took effect: a failed service step can undo a choice.
+ `\nThis machine\n${formatSetup(after)}\n\n${formatNextSteps(
+ { connect: after.connect === true, lan: after.lan },
+ after.service.installed,
+ )}`,
+ );
+});
+
+export const upCommand = Command.make("up", {
+ ...projectLocationFlags,
+ connect: Flag.Boolean("connect").pipe(
+ Flag.withDescription(
+ "Allow access through T3 Connect with your T3 account. Turn off with --no-connect.",
+ ),
+ Flag.optional,
+ ),
+ lan: Flag.Boolean("lan").pipe(
+ Flag.withDescription(
+ "Allow LAN and tailnet connections. Anyone there can reach the port; a pairing code is the only lock. Turn off with --no-lan.",
+ ),
+ Flag.optional,
+ ),
+ yes: Flag.Boolean("yes").pipe(
+ Flag.withDescription(
+ "Ask nothing. Keep the access settings; a new machine gets T3 Connect. A restart stops running agent turns.",
+ ),
+ Flag.withDefault(false),
+ ),
+ headless: headlessFlag,
+}).pipe(
+ Command.withShortDescription("Set up remote access and the T3 Code background service."),
+ Command.withDescription(
+ "Set up remote access and the T3 Code background service. Access flags skip the question, and routes not named keep their settings. Without a terminal, a needed restart runs without asking and stops running agent turns.",
+ ),
+ Command.withExamples([
+ { command: "t3 up", description: "Choose remote access." },
+ { command: "t3 up --connect", description: "Turn on T3 Connect. Keep other settings." },
+ { command: "t3 up --lan", description: "Allow LAN access with pairing codes." },
+ { command: "t3 up --no-lan", description: "Stop LAN access." },
+ { command: "t3 up --yes", description: "Take the defaults with no questions." },
+ { command: "t3 status --json", description: "Read the settings from a script." },
+ ]),
+ Command.withHandler((flags) => runCloudCommand(flags, setUp(flags), { quietLogs: true })),
+);
+
+export const connectCommand = Command.make("connect", {
+ ...projectLocationFlags,
+ headless: headlessFlag,
+}).pipe(
+ Command.withDescription("Set up T3 Connect for this machine. Same as `t3 up --connect`."),
+ Command.withHandler((flags) =>
+ runCloudCommand(
+ flags,
+ setUp({ ...flags, connect: Option.some(true), lan: Option.none(), yes: false }),
+ { quietLogs: true },
+ ),
+ ),
+ Command.withSubcommands(connectSubcommands),
+);
+
+/** `t3 status --json`, for scripts and agents. */
+const setupJson = (setup: Setup) =>
+ JSON.stringify(
+ {
+ service: {
+ supported: setup.service.supported,
+ installed: setup.service.installed,
+ installedVersion: setup.service.installedVersion ?? null,
+ },
+ connect:
+ setup.connect === null ? null : { enabled: setup.connect, revoked: setup.connectRevoked },
+ lan: {
+ enabled: setup.lan,
+ inheritedDefault: setup.lanFromOldDefault,
+ hostOverride: setup.host ?? null,
+ },
+ },
+ null,
+ 2,
+ );
+
+export const statusCommand = Command.make("status", {
+ ...projectLocationFlags,
+ json: Flag.Boolean("json").pipe(
+ Flag.withDescription("Print the settings as JSON. Does not test connections."),
+ Flag.withDefault(false),
+ ),
+}).pipe(
+ Command.withDescription("Show service setup and remote access settings."),
+ Command.withExamples([
+ { command: "t3 status", description: "Show the settings." },
+ { command: "t3 status --json", description: "Print them for scripts and agents." },
+ ]),
+ Command.withHandler(
+ Effect.fn("cli.status")(function* (flags) {
+ const config = yield* resolveCliAuthConfig(flags, yield* GlobalFlag.LogLevel, {
+ quietLogs: flags.json,
+ });
+ // Only what readSetup reads: no database, unlike the T3 Connect commands.
+ const setup = yield* readSetup().pipe(
+ Effect.provide(
+ Layer.merge(CliService.layer(config), ServerSecretStore.layer).pipe(
+ Layer.provideMerge(ServerConfig.layer(config)),
+ ),
+ ),
+ );
+ yield* Console.log(
+ flags.json
+ ? setupJson(setup)
+ : `This machine\n${formatSetup(setup)}\n\nChange access: \`t3 up\`.`,
+ );
+ }),
+ ),
+);
diff --git a/docs/user/background-service.md b/docs/user/background-service.md
index 566f7ab9d60..c36527b2c42 100644
--- a/docs/user/background-service.md
+++ b/docs/user/background-service.md
@@ -8,13 +8,15 @@ to keep a terminal open.
Install the `t3` CLI first ([Install T3 Code](./install.md#command-line)), then
run these commands on the machine that will host T3 Code:
-| Task | Command |
-| ------------------------------- | ---------------------- |
-| Install and start | `t3 service install` |
-| Inspect status and log location | `t3 service status` |
-| Move to a newer release | `t3 update` |
-| Restart | `t3 service restart` |
-| Stop and remove from startup | `t3 service uninstall` |
+| Task | Command |
+| ------------------------------------- | ---------------------- |
+| Set up access from your other devices | `t3 up` |
+| See how your other devices reach it | `t3 status` |
+| Install and start | `t3 service install` |
+| Inspect status and log location | `t3 service status` |
+| Move to a newer release | `t3 update` |
+| Restart | `t3 service restart` |
+| Stop and remove from startup | `t3 service uninstall` |
Uninstalling the service leaves your projects, threads, and settings intact.
Running `t3 service install` again repairs a service that `t3 service status`
@@ -42,13 +44,18 @@ under T3 home. Pass `--yes` from a script.
## Local network access
-The service listens on your local network and Tailscale addresses, so the
-desktop and mobile apps on the same network connect directly instead of through
-T3 Connect. The hosted web app at app.t3.codes stays on T3 Connect, because
-browsers block plain HTTP from an HTTPS page. The service does not answer on
-public addresses, and every device still needs to pair or sign in. To keep the service reachable from this machine only, set
-`T3CODE_HOST=127.0.0.1` in `service.env` (below). Any `T3CODE_HOST` value
-replaces this default.
+A new service answers only on this machine. Other devices reach it through
+T3 Connect, or directly once you choose the local network in `t3 up` (or run
+`t3 up --lan`, which sets `T3CODE_LAN=true` in `service.env`). It then listens on
+your local network and Tailscale addresses, so the desktop and mobile apps on
+the same network connect directly instead of through T3 Connect. It still does
+not answer on public addresses. Anyone on the same network can reach the port,
+so a pairing code is all that keeps them out. The hosted web app at app.t3.codes
+stays on T3 Connect, because browsers block plain HTTP from an HTTPS page.
+
+A service installed before `T3CODE_LAN` existed keeps listening on the local
+network. `t3 status` says so, and `t3 up --no-lan` turns it off. Any
+`T3CODE_HOST` value replaces this setting.
## Configure the service environment
@@ -91,7 +98,7 @@ enabled, or keep `t3 serve` running in a terminal. Minimize the desktop app rath
than closing its last window, which stops its local server. Linking T3 Connect
does not configure automatic startup at Windows sign-in.
-T3 Connect can offer service installation during setup, but the two are managed
+`t3 up` installs the service when you set up T3 Connect, but the two are managed
separately. Signing out of T3 Connect does not stop or uninstall the service.
## Keep the server responsive when agents use all memory
diff --git a/docs/user/faq.md b/docs/user/faq.md
index 62a5e1a8446..6f4a02e485b 100644
--- a/docs/user/faq.md
+++ b/docs/user/faq.md
@@ -13,7 +13,7 @@ Bring your own: Claude Code, Codex, Cursor, Grok Build, OpenCode, Google Antigra
We were inspired by the Codex desktop app, Conductor, Claude Desktop, and Cursor Glass, but none met our bar. What you get:
- Bring your own sub. Claude, Codex, and whatever else you already have installed.
-- Best in class remote. Run `npx t3 connect` on any box and drive it from anywhere.
+- Best in class remote. Run `npx t3 up` on any box and drive it from anywhere.
- Best in class mobile app.
- Truly 100% open source. If we go the wrong direction, fork it.
@@ -37,7 +37,7 @@ T3 Code drives Claude through Anthropic's Agent SDK. I confirmed it's a real bug
## How do I use T3 Code remotely?
-Your agents run wherever T3 Code runs: your desktop, a server, a VPS. You connect to it from anywhere. I do this constantly. Less than 5% of my prompts run on my laptop. Run `npx t3 connect` on that machine and you get really good remote support. T3 Connect is the easy path. LAN pairing and Tailscale work too, and [app.t3.codes](https://app.t3.codes) is the web client. [Remote access](./remote-access.md)
+Your agents run wherever T3 Code runs: your desktop, a server, a VPS. You connect to it from anywhere. I do this constantly. Less than 5% of my prompts run on my laptop. Run `npx t3 up` on that machine and you get really good remote support. T3 Connect is the easy path. LAN pairing and Tailscale work too, and [app.t3.codes](https://app.t3.codes) is the web client. [Remote access](./remote-access.md)
## How do I use T3 Code on my phone?
diff --git a/docs/user/install.md b/docs/user/install.md
index 1e1693d0b32..3f44f5b596b 100644
--- a/docs/user/install.md
+++ b/docs/user/install.md
@@ -29,6 +29,7 @@ line to add. Set `T3CODE_CHANNEL=nightly` to install the nightly train, or
| ------------------------------------------------ | ----------------------------------------------------------------------- |
| Start the server and open the web app | `t3` |
| Start the server without a browser | `t3 serve` |
+| Use it from your other devices | `t3 up` ([details](./remote-access.md)) |
| Keep it running in the background (macOS, Linux) | `t3 service install` ([details](./background-service.md)) |
| Move to the newest release | `t3 update` |
| Reclaim database space | `t3 doctor` ([details](./background-service.md#reclaim-database-space)) |
diff --git a/docs/user/remote-access.md b/docs/user/remote-access.md
index 9c426b64b13..c7e69989e04 100644
--- a/docs/user/remote-access.md
+++ b/docs/user/remote-access.md
@@ -12,17 +12,20 @@ Sharing & access**, sign in, and enable **T3 Connect** for that environment.
For a command-line host, run:
```bash
-t3 connect
+t3 up
```
-Follow the sign-in instructions. On Linux and macOS, setup offers a
-[background service](./background-service.md); if you decline it, start the
-server with `t3 serve`.
+It asks how your other devices reach the machine: T3 Connect, the local network,
+or both. Choose T3 Connect and follow the sign-in instructions. On Linux and
+macOS, it then runs T3 Code as a [background service](./background-service.md).
+`t3 connect` is the same as `t3 up --connect`. Run `t3 up` again to change your
+choice, and `t3 status` to see it.
-The background service is not available on Windows. Keep the desktop app running
-with its local environment enabled, or keep `t3 serve` running in a terminal.
-Closing the desktop app's last window stops its local server. Saving your
-sign-in alone does not start a server or make the machine reachable.
+The background service is not available on Windows, so there `t3 up` prints the
+`t3 serve` command to keep running in a terminal. You can also keep the desktop
+app running with its local environment enabled. Closing the desktop app's last
+window stops its local server. Saving your sign-in alone does not start a server
+or make the machine reachable.
On your other device, sign in to the same T3 Connect account and choose the
environment. On the app.t3.codes home page with no computer added yet, signing
@@ -36,6 +39,19 @@ connection. Pull request diffs and provider settings keep working after the
previous credential expires. A failed renewal affects that request; it does not
disconnect an otherwise healthy conversation.
+### Scripts and agents
+
+`t3 up` asks nothing when you name a choice: `--connect`, `--lan`, or their
+`--no-` forms. Choices you do not name keep their settings, and `--yes` takes
+the defaults. Without a terminal:
+
+- T3 Connect sign-in prints a URL and a code. Approve it on any device.
+- A needed restart runs without asking, and stops running agent turns.
+- With nothing set up and no choice named, `t3 up` stops and names the flags.
+
+`t3 status --json` prints the settings. `t3 up --help` lists every flag with
+examples.
+
### More machines with T3 Chat
Each T3 Connect account can link up to 3 machines. Phones and browsers do not
@@ -56,13 +72,16 @@ On a desktop host, open **Settings → Sharing & access**, enable **Network acce
then create a pairing link using an address the other device can reach. Changing
network access restarts the desktop app. You can turn it off in the same place.
-For a command-line host, replace `<private-ip>` with the host's LAN or tailnet
-address:
+For a command-line host, choose the local network in `t3 up`, or run:
```bash
-t3 serve --host <private-ip>
+t3 up --lan
```
+For a server in a terminal, run `t3 serve --lan`. Either way, T3 Code then
+accepts connections from your local network and tailnet, so a pairing code is
+all that keeps other devices on them out.
+
If a server is already running, generate a fresh link without restarting it:
```bash
@@ -105,8 +124,9 @@ machine's current LAN and Tailscale addresses and adds them as routes, so
pairing once through T3 Connect is enough to use the LAN at home. When the
machine's LAN address changes, for example after it joins another Wi-Fi network,
the learned route follows it. The machine must allow network access for its LAN
-address to be learned. The [background service](./background-service.md#local-network-access)
-allows it on private networks by default. You can reorder a learned route, but not remove it; it
+address to be learned: **Network access** in the desktop app, or the
+[local network](./background-service.md#local-network-access) choice in `t3 up`.
+You can reorder a learned route, but not remove it; it
goes away with the route it was learned through, or when the machine stops
reporting that address.
diff --git a/scripts/install.ps1 b/scripts/install.ps1
index 60a70fefc72..fe452674c20 100644
--- a/scripts/install.ps1
+++ b/scripts/install.ps1
@@ -230,5 +230,5 @@ if ($interactive) { [Console]::Error.Write("`r$esc[2K") }
if (($env:PATH -split ";") -notcontains $binDir) {
Write-Host " Add $binDir to your PATH, then run ${bold}t3$reset.`n"
} else {
- Write-Host " Run ${bold}t3$reset to get started.`n"
+ Write-Host " Run ${bold}t3$reset to use T3 Code here, or ${bold}t3 up$reset to use it from your other devices.`n"
}
diff --git a/scripts/install.sh b/scripts/install.sh
index 8f617793527..4ea200589a6 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -238,6 +238,6 @@ grep -qxF "$launcher" "$launchers" 2>/dev/null || printf '%s\n' "$launcher" >> "
if "$interactive"; then printf '\r\033[2K' >&2; fi
printf ' %sInstalled T3 Code %s%s\n\n' "$green" "$version" "$reset" >&2
case ":${PATH}:" in
- *":${bin_dir}:"*) printf ' Run %st3%s to get started.\n\n' "$bold" "$reset" ;;
+ *":${bin_dir}:"*) printf ' Run %st3%s to use T3 Code here, or %st3 up%s to use it from your other devices.\n\n' "$bold" "$reset" "$bold" "$reset" ;;
*) printf ' Add %s to your PATH, then run %st3%s.\n\n' "$bin_dir" "$bold" "$reset" ;;
esac