@devries-cameron20 / t3code Mirror · read-only / commits / cadf7d5fe3
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 10:45 UTC

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

t3 up asks one question (T3 Connect and/or the local network) or takes flags, then runs T3 Code as the background service, restarting only when a setting it reads at start changed. t3 status (and --json) shows the setup; t3 connect is t3 up --connect. A new background service listens on this machine only until you choose the local network (T3CODE_LAN); older installs keep their LAN access. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Oct 31, 2026 at 01:12 UTC cadf7d5fe305ee347cb2662dc563a0984f198900
17 files changed +1263 -322
apps/server/src/binCli.ts
+6 -2
@@ -13,7 +13,6 @@ import { authCommand } from "./cli/auth.ts";
13 import { environmentCommand } from "./cli/environment.ts";
14 import { appCommand } from "./cli/app.ts";
15 import { browserCommand } from "./cli/browser.ts";
16 -import { connectCommand } from "./cli/connect.ts";
16 import { pairCommand } from "./cli/pair.ts";
17 import { hasCloudPublicConfig } from "./cloud/publicConfig.ts";
18 import { extendConnectionAttemptTimeout, keepOutboundFetchOnHttp1 } from "./outboundHttp.ts";
@@ -31,6 +30,7 @@ import { servicePreflightCommand } from "./cli/servicePreflight.ts";
30 import { themeCommand } from "./cli/theme.ts";
31 import { traceCommand } from "./cli/trace.ts";
32 import { triageCommand } from "./cli/triage.ts";
33 +import { connectCommand, statusCommand, upCommand } from "./cli/up.ts";
34
35 const layerCliRuntime = Layer.mergeAll(NodeServices.layer, NetService.layer);
36
@@ -60,7 +60,9 @@ const connectUnavailableCommand = Command.make("connect", {
60
61 export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
62 Command.make("t3", { ...sharedServerCommandFlags }).pipe(
63 - Command.withDescription("Run the T3 Code server."),
63 + Command.withDescription(
64 + "Run T3 Code in this terminal and open it in your browser. To use it from your other devices, run `t3 up`.",
65 + ),
66 Command.withHandler(runDefaultServerCommand),
67 Command.withSubcommands([
68 Command.make("help").pipe(
@@ -80,6 +82,8 @@ export const makeCli = ({ cloudEnabled = hasCloudPublicConfig } = {}) =>
82 browserCommand,
83 projectCommand,
84 threadCommand,
85 + upCommand,
86 + statusCommand,
87 serviceCommand,
88 updateCommand,
89 uninstallCommand,
apps/server/src/cli/config.test.ts
+20 -1
@@ -49,6 +49,7 @@ const minimalDesktopFlags = (baseDir: string) => ({
49 logWebSocketEvents: Option.none<boolean>(),
50 tailscaleServeEnabled: Option.none<boolean>(),
51 tailscaleServePort: Option.none<number>(),
52 + lan: Option.none<boolean>(),
53 });
54
55 const encodeDesktopBootstrap = Schema.encodeEffect(Schema.fromJsonString(DesktopBackendBootstrap));
@@ -231,6 +232,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
232 logWebSocketEvents: Option.none<boolean>(),
233 tailscaleServeEnabled: Option.none<boolean>(),
234 tailscaleServePort: Option.none<number>(),
235 + lan: Option.none<boolean>(),
236 };
237 const layerConfig = ConfigProvider.layer(
238 ConfigProvider.fromEnv({
@@ -275,6 +277,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
277 logWebSocketEvents: Option.none<boolean>(),
278 tailscaleServeEnabled: Option.none<boolean>(),
279 tailscaleServePort: Option.none<number>(),
280 + lan: Option.none<boolean>(),
281 };
282 const layerConfig = ConfigProvider.layer(
283 ConfigProvider.fromEnv({ env: { T3CODE_DEV_AUTH_TOKEN: secret } }),
@@ -330,6 +333,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
333 logWebSocketEvents: Option.some(false),
334 tailscaleServeEnabled: Option.none(),
335 tailscaleServePort: Option.none(),
336 + lan: Option.none(),
337 },
338 Option.none(),
339 ).pipe(
@@ -406,6 +410,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
410 logWebSocketEvents: Option.none(),
411 tailscaleServeEnabled: Option.none(),
412 tailscaleServePort: Option.none(),
413 + lan: Option.none(),
414 },
415 Option.some("Debug"),
416 ).pipe(
@@ -553,6 +558,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
558 logWebSocketEvents: Option.none(),
559 tailscaleServeEnabled: Option.none(),
560 tailscaleServePort: Option.none(),
561 + lan: Option.none(),
562 },
563 Option.none(),
564 ).pipe(
@@ -601,6 +607,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
607 logWebSocketEvents: Option.none(),
608 tailscaleServeEnabled: Option.none(),
609 tailscaleServePort: Option.none(),
610 + lan: Option.none(),
611 },
612 Option.none(),
613 ).pipe(
@@ -641,6 +648,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
648 logWebSocketEvents: Option.none(),
649 tailscaleServeEnabled: Option.none(),
650 tailscaleServePort: Option.none(),
651 + lan: Option.none(),
652 },
653 Option.none(),
654 {
@@ -703,6 +711,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
711 logWebSocketEvents: Option.none(),
712 tailscaleServeEnabled: Option.none(),
713 tailscaleServePort: Option.none(),
714 + lan: Option.none(),
715 },
716 Option.none(),
717 ).pipe(
@@ -742,6 +751,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
751 logWebSocketEvents: Option.none<boolean>(),
752 tailscaleServeEnabled: Option.none<boolean>(),
753 tailscaleServePort: Option.none<number>(),
754 + lan: Option.none<boolean>(),
755 });
756
757 it.effect(
@@ -863,7 +873,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
873 }),
874 );
875
866 - it.effect("listens on private networks only under the service launcher with no host set", () =>
876 + it.effect("listens on private networks per T3CODE_LAN, else under the service launcher", () =>
877 Effect.gen(function* () {
878 const { join } = yield* Path.Path;
879 const baseDir = join(NodeOS.tmpdir(), "t3-cli-config-service-host");
@@ -893,6 +903,7 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
903 }),
904 );
905
906 + // A service installed before T3CODE_LAN existed.
907 expect(yield* resolveHost({ connected: true })).toEqual({
908 host: "0.0.0.0",
909 privateNetworkOnly: true,
@@ -902,6 +913,14 @@ it.layer(NodeServices.layer)("cli config resolution", (it) => {
913 host: "127.0.0.1",
914 privateNetworkOnly: undefined,
915 });
916 + expect(yield* resolveHost({ connected: true, env: { T3CODE_LAN: "false" } })).toEqual({
917 + host: undefined,
918 + privateNetworkOnly: undefined,
919 + });
920 + expect(yield* resolveHost({ connected: false, env: { T3CODE_LAN: "true" } })).toEqual({
921 + host: "0.0.0.0",
922 + privateNetworkOnly: true,
923 + });
924 // Without the launcher's IPC channel the context was inherited, e.g. by
925 // `t3 serve` started from an agent inside the service.
926 expect(yield* resolveHost({ connected: false })).toEqual({
apps/server/src/cli/config.ts
+21 -7
@@ -85,6 +85,12 @@ const tailscaleServePortFlag = Flag.Int("tailscale-serve-port").pipe(
85 Flag.withDescription("HTTPS port for Tailscale Serve when --tailscale-serve is enabled."),
86 Flag.optional,
87 );
88 +const lanFlag = Flag.Boolean("lan").pipe(
89 + Flag.withDescription(
90 + "Accept connections from your local network and tailnet, not only this machine (equivalent to T3CODE_LAN).",
91 + ),
92 + Flag.optional,
93 +);
94
95 export const traceFileConfig = Config.String("T3CODE_TRACE_FILE").pipe(
96 Config.option,
@@ -165,6 +171,7 @@ const EnvServerConfig = Config.all({
171 Config.option,
172 Config.map(Option.getOrUndefined),
173 ),
174 + lan: Config.Boolean("T3CODE_LAN").pipe(Config.option, Config.map(Option.getOrUndefined)),
175 });
176
177 const DevAuthTokenConfig = Config.Redacted("T3CODE_DEV_AUTH_TOKEN").pipe(
@@ -200,6 +207,7 @@ export interface CliServerFlags {
207 readonly logWebSocketEvents: Option.Option<boolean>;
208 readonly tailscaleServeEnabled: Option.Option<boolean>;
209 readonly tailscaleServePort: Option.Option<number>;
210 + readonly lan: Option.Option<boolean>;
211 }
212
213 export interface CliAuthLocationFlags {
@@ -234,6 +242,7 @@ export const sharedServerCommandFlags = {
242 logWebSocketEvents: logWebSocketEventsFlag,
243 tailscaleServeEnabled: tailscaleServeFlag,
244 tailscaleServePort: tailscaleServePortFlag,
245 + lan: lanFlag,
246 } as const;
247
248 const resolveOptionPrecedence = <Value>(
@@ -277,6 +286,7 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct
286 logWebSocketEvents: flags.logWebSocketEvents ?? Option.none(),
287 tailscaleServeEnabled: flags.tailscaleServeEnabled ?? Option.none(),
288 tailscaleServePort: flags.tailscaleServePort ?? Option.none(),
289 + lan: flags.lan ?? Option.none(),
290 } satisfies CliServerFlags;
291 const bootstrapFd = Option.getOrUndefined(normalizedFlags.bootstrapFd) ?? env.bootstrapFd;
292 const bootstrapEnvelope =
@@ -410,16 +420,19 @@ export const resolveServerConfig = Effect.fn("config.resolveServerConfig")(funct
420 Option.fromUndefinedOr(env.host),
421 Option.fromUndefinedOr(bootstrap?.host),
422 );
413 - // A background service exists to be reached from other devices, so it
414 - // listens on private networks unless `service.env` sets `T3CODE_HOST`.
415 - // Clients then learn its LAN address and prefer it over T3 Connect.
423 + // Private networks only, so clients learn a LAN address and prefer it over
424 + // T3 Connect. `t3 service install` writes T3CODE_LAN=false for a new
425 + // service; one installed before T3CODE_LAN existed keeps listening.
426 + const lan = resolveOptionPrecedence(normalizedFlags.lan, Option.fromUndefinedOr(env.lan));
427 const privateNetworkOnly =
428 Option.isNone(explicitHost) &&
429 mode === "web" &&
419 - (yield* resolveServiceLauncherMode().pipe(
420 - Effect.map((launcher) => launcher.managed),
421 - Effect.orElseSucceed(() => false),
422 - ));
430 + (Option.isSome(lan)
431 + ? lan.value
432 + : yield* resolveServiceLauncherMode().pipe(
433 + Effect.map((launcher) => launcher.managed),
434 + Effect.orElseSucceed(() => false),
435 + ));
436 const host = Option.getOrElse(explicitHost, () =>
437 privateNetworkOnly ? "0.0.0.0" : mode === "desktop" ? "127.0.0.1" : undefined,
438 );
@@ -530,6 +543,7 @@ export const resolveCliAuthConfig = (
543 logWebSocketEvents: Option.none(),
544 tailscaleServeEnabled: Option.none(),
545 tailscaleServePort: Option.none(),
546 + lan: Option.none(),
547 },
548 cliLogLevel,
549 );
apps/server/src/cli/connect.ts
+44 -86
@@ -9,7 +9,6 @@ import {
9 type RelayClientInstallProgressStage,
10 } from "@t3tools/contracts";
11 import { RelayOkResponse } from "@t3tools/contracts/relay";
12 -import * as HostProcess from "@t3tools/shared/HostProcess";
12 import * as RelayClient from "@t3tools/shared/relayClient";
13 import { withRelayClientTracing } from "@t3tools/shared/relayTracing";
14 import * as Cause from "effect/Cause";
@@ -23,6 +22,7 @@ import * as Exit from "effect/Exit";
22 import * as FileSystem from "effect/FileSystem";
23 import * as Layer from "effect/Layer";
24 import * as Option from "effect/Option";
25 +import * as Path from "effect/Path";
26 import * as References from "effect/References";
27 import * as Schema from "effect/Schema";
28 import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
@@ -60,8 +60,10 @@ const jsonFlag = Flag.Boolean("json").pipe(
60
61 const isCloudCliTokenManagerError = Schema.is(CliTokenManager.CloudCliTokenManagerError);
62
63 -const headlessFlag = Flag.Boolean("headless").pipe(
64 - Flag.withDescription("Authorize without a local browser using the OAuth device flow."),
63 +export const headlessFlag = Flag.Boolean("headless").pipe(
64 + Flag.withDescription(
65 + "Sign in with a URL and code on any device. Automatic without a terminal or over SSH.",
66 + ),
67 Flag.withDefault(false),
68 );
69
@@ -85,13 +87,10 @@ function formatDeviceAuthorizationPrompt(
87 ): string {
88 const minutes = Math.max(1, Math.round(Duration.toMinutes(prompt.expiresIn)));
89 return [
88 - "Headless authorization",
89 - "Open this URL on a device with a browser:",
90 + "Sign in to T3 Connect. Open on any device:",
91 ` ${prompt.verificationUriComplete ?? prompt.verificationUri}`,
91 - "",
92 - `Confirm this code when asked: ${prompt.userCode}`,
93 - "",
94 - `Waiting for approval (expires in ${minutes} min). Press Ctrl+C to cancel.`,
92 + `Code: ${prompt.userCode}`,
93 + `Waiting for approval. Expires in ${minutes} min. Ctrl+C cancels.`,
94 ].join("\n");
95 }
96
@@ -99,20 +98,21 @@ const authorizeCli = Effect.fn("cloud.cli.authorize")(function* (options: {
98 readonly headless: boolean;
99 }) {
100 const tokens = yield* CliTokenManager.CloudCliTokenManager;
102 - const useOutOfBandOAuth = options.headless || (yield* headlessSessionConfig);
101 + // Without a terminal, no key press can open a browser, so sign in with a code.
102 + const useOutOfBandOAuth =
103 + options.headless ||
104 + (yield* headlessSessionConfig) ||
105 + !(process.stdin.isTTY && process.stdout.isTTY);
106 if (!useOutOfBandOAuth) {
107 const authorization = yield* tokens.get;
108 if (authorization._tag === "Authorized") {
109 return authorization.token.identity ?? null;
110 }
108 - yield* Console.log("\nHeadless mode enabled. A new authorization link is ready below.");
111 }
112 const existing = yield* tokens.getExisting.pipe(
113 Effect.catchTags({
114 CloudCliCredentialRefreshError: () =>
113 - Console.log(
114 - "The stored T3 Connect credential could not be refreshed; signing in again.",
115 - ).pipe(Effect.as(Option.none())),
115 + Console.log("T3 Connect sign-in expired. Sign in again.").pipe(Effect.as(Option.none())),
116 }),
117 );
118 if (Option.isSome(existing)) {
@@ -363,17 +363,15 @@ function formatAlertBox(text: string): string {
363 * Waits for the server that `t3 connect` just started to prove other devices
364 * can reach it, so a broken tunnel fails setup instead of looking green.
365 */
366 -const waitForReachability = Effect.fn("cloud.cli.wait_for_reachability")(function* () {
367 - yield* Console.log("\nChecking that other devices can reach this machine...");
366 +export const waitForReachability = Effect.fn("cloud.cli.wait_for_reachability")(function* () {
367 + yield* Console.log("Checking T3 Connect...");
368 const deadline =
369 (yield* Clock.currentTimeMillis) + Duration.toMillis(CLOUD_CLI_REACHABILITY_WAIT);
370 let last: EnvironmentConnectReachability | null = null;
371 while (true) {
372 last = (yield* checkLiveReachability()) ?? last;
373 if (last?.status === "reachable") {
374 - yield* Console.log(
375 - `✓ Other devices can reach this machine · ${formatConnectReachable(last)}`,
376 - );
374 + yield* Console.log("✓ T3 Connect is reachable.");
375 return;
376 }
377 if ((yield* Clock.currentTimeMillis) >= deadline) break;
@@ -481,7 +479,7 @@ const reportCloudDisconnectResults = Effect.fn("cloud.cli.report_disconnect_resu
479 },
480 );
481
484 -const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
482 +export const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
483 readonly clearAuthorization: boolean;
484 }) {
485 yield* CliState.setCliDesiredCloudLink(false);
@@ -505,9 +503,10 @@ const disconnectCloud = Effect.fn("cloud.cli.disconnect")(function* (options: {
503 "Signed out of T3 Connect locally.\nThe background service is managed separately with `t3 service`.",
504 );
505 }
506 + return liveResult;
507 });
508
510 -const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E>(
509 +export const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E>(
510 flags: { readonly baseDir: Option.Option<string> },
511 run: Effect.Effect<
512 A,
@@ -519,6 +518,7 @@ const runCloudCommand = Effect.fn("cloud.cli.run_cloud_command")(function* <A, E
518 | BootService.BootService
519 | Crypto.Crypto
520 | FileSystem.FileSystem
521 + | Path.Path
522 | HttpClient.HttpClient
523 | Prompt.Environment
524 | ServerConfig.ServerConfig
@@ -558,28 +558,35 @@ function formatRelayClientReady(version: string): string {
558 const linkEnvironmentForConnect = Effect.fn("cloud.cli.link_environment")(function* (options: {
559 readonly headless: boolean;
560 readonly publishOnly?: boolean;
561 + /** For `t3 up`, where the user already chose T3 Connect: install it quietly, without asking. */
562 + readonly installRelayClient?: boolean;
563 }) {
564 const publishOnly = options.publishOnly ?? false;
565 if (!publishOnly) {
566 const relayClient = yield* RelayClient.RelayClient;
567 const installed = yield* acquireRelayClientForLink(
568 relayClient,
567 - confirmRelayClientInstall,
568 - reportRelayClientInstallProgress,
569 + options.installRelayClient === true ? () => Effect.succeed(true) : confirmRelayClientInstall,
570 + options.installRelayClient === true
571 + ? (event) =>
572 + event.type === "progress" && event.stage === "downloading"
573 + ? Console.log("Installing the T3 Connect relay client...")
574 + : Effect.void
575 + : reportRelayClientInstallProgress,
576 );
577 if (Option.isNone(installed)) {
578 yield* Console.log("T3 Connect setup cancelled. The relay client was not installed.");
579 return null;
580 }
574 - yield* Console.log(formatRelayClientReady(installed.value.version));
581 + if (options.installRelayClient !== true) {
582 + yield* Console.log(formatRelayClientReady(installed.value.version));
583 + }
584 }
585
586 const identity = yield* authorizeCli(options);
587 yield* CliState.setCliDesiredCloudLink(true, publishOnly ? "publish_only" : "managed");
588 if (yield* CliState.dropRevokedCloudLink) {
580 - yield* Console.log(
581 - "Removed the link T3 Connect no longer accepts. The next start links this environment again.",
582 - );
589 + yield* Console.log("Replacing the link T3 Connect revoked.");
590 }
591 if (publishOnly) {
592 const secrets = yield* ServerSecretStore.ServerSecretStore;
@@ -587,6 +594,7 @@ const linkEnvironmentForConnect = Effect.fn("cloud.cli.link_environment")(functi
594 }
595 return { identity } as const;
596 });
597 +export { linkEnvironmentForConnect };
598
599 const connectLoginCommand = Command.make("login", {
600 ...projectLocationFlags,
@@ -776,62 +784,12 @@ const connectLogoutCommand = Command.make("logout", {
784 ),
785 );
786
779 -const reportServiceOnboarding = Effect.fn("cli.connect.report_service_onboarding")(function* (
780 - outcome: CliService.ServiceOnboardingOutcome,
781 -) {
782 - if (outcome === "pending") {
783 - yield* Console.log(
784 - "\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.",
785 - );
786 - return;
787 - }
788 - if (outcome === "ready") {
789 - const platform = yield* HostProcess.Platform;
790 - yield* Console.log(
791 - platform === "darwin"
792 - ? "\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."
793 - : "\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.",
794 - );
795 - return;
796 - }
797 - const serveCommand = yield* resolveCliCommand("serve");
798 - yield* Console.log(
799 - `\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.`,
800 - );
801 -});
802 -
803 -export const connectCommand = Command.make("connect", {
804 - ...projectLocationFlags,
805 - headless: headlessFlag,
806 -}).pipe(
807 - Command.withDescription("Set up T3 Connect for this machine."),
808 - Command.withHandler((flags) =>
809 - runCloudCommand(
810 - flags,
811 - Effect.gen(function* () {
812 - yield* Console.log("T3 Connect\n");
813 - const linked = yield* linkEnvironmentForConnect(flags);
814 - if (!linked) {
815 - return;
816 - }
817 - yield* Console.log(`✓ Authorized${connectedAs(linked.identity)}`);
818 -
819 - const outcome = yield* CliService.recoverServiceOnboardingOffer(
820 - CliService.offerServiceDuringOnboarding,
821 - );
822 - yield* reportServiceOnboarding(outcome);
823 - if (outcome !== "skipped") {
824 - yield* waitForReachability();
825 - }
826 - }),
827 - ),
828 - ),
829 - Command.withSubcommands([
830 - connectLoginCommand,
831 - connectLinkCommand,
832 - connectPublishCommand,
833 - connectStatusCommand,
834 - connectUnlinkCommand,
835 - connectLogoutCommand,
836 - ]),
837 -);
787 +// `t3 connect` itself is `t3 up --connect`, in up.ts.
788 +export const connectSubcommands = [
789 + connectLoginCommand,
790 + connectLinkCommand,
791 + connectPublishCommand,
792 + connectStatusCommand,
793 + connectUnlinkCommand,
794 + connectLogoutCommand,
795 +] as const;
apps/server/src/cli/pair.ts
+1 -1
@@ -512,7 +512,7 @@ export const pairCommand = Command.make("pair", {
512 pairingBaseUrl = resolveDirectPairingBaseUrl(target.state);
513 if (isLoopbackHost(new URL(pairingBaseUrl).hostname)) {
514 notes.push(
515 - "This URL is only reachable from this machine. Re-run with --tailscale, or restart the server with a reachable --host.",
515 + "This URL is only reachable from this machine. To reach it from your other devices, run `t3 up`, or re-run with --tailscale.",
516 );
517 } else if (target.state.privateNetworkOnly) {
518 notes.push(
apps/server/src/cli/server.ts
+4 -2
@@ -69,13 +69,15 @@ export const runDefaultServerCommand = Effect.fn("server.runDefaultServerCommand
69 });
70
71 export const startCommand = Command.make("start", { ...sharedServerCommandFlags }).pipe(
72 - Command.withDescription("Run the T3 Code server."),
72 + Command.withDescription("Same as `t3`."),
73 + Command.unlisted,
74 Command.withHandler((flags) => runServerCommand(flags, { rejectRunningServer: true })),
75 );
76
77 export const serveCommand = Command.make("serve", { ...sharedServerCommandFlags }).pipe(
78 + Command.withShortDescription("Run T3 Code in this terminal, with no browser."),
79 Command.withDescription(
78 - "Run the T3 Code server without opening a browser and print headless pairing details.",
80 + "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`.",
81 ),
82 Command.withHandler((flags) =>
83 runServerCommand(flags, {
apps/server/src/cli/service.test.ts
+42 -92
@@ -6,18 +6,13 @@ import * as ConfigProvider from "effect/ConfigProvider";
6 import * as Effect from "effect/Effect";
7 import * as FileSystem from "effect/FileSystem";
8 import * as Layer from "effect/Layer";
9 -import * as Terminal from "effect/Terminal";
9 import * as TestConsole from "effect/testing/TestConsole";
10 import { Command } from "effect/cli";
11 import { afterEach, vi } from "vite-plus/test";
12
13 import packageJson from "../../package.json" with { type: "json" };
14 import * as BootService from "../cloud/bootService.ts";
16 -import {
17 - offerServiceDuringOnboarding,
18 - recoverServiceOnboardingOffer,
19 - serviceCommand,
20 -} from "./service.ts";
15 +import { serviceCommand } from "./service.ts";
16
17 afterEach(() => vi.restoreAllMocks());
18
@@ -90,6 +85,47 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands
85 }),
86 );
87
88 + it.effect.each([
89 + { label: "a new service", installed: false, env: "", expected: "T3CODE_LAN=false\n" },
90 + // Services installed before T3CODE_LAN existed keep listening on the local network.
91 + { label: "an older service", installed: true, env: "", expected: "" },
92 + {
93 + label: "a set host",
94 + installed: false,
95 + env: "T3CODE_HOST=::\n",
96 + expected: "T3CODE_HOST=::\n",
97 + },
98 + ])("install keeps $label off the local network only when it is new", (input) =>
99 + Effect.gen(function* () {
100 + const fs = yield* FileSystem.FileSystem;
101 + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-service-cli-test-" });
102 + yield* fs.writeFileString(`${baseDir}/service.env`, input.env);
103 + const { service } = makeTestService({
104 + ...status,
105 + installed: input.installed,
106 + current: false,
107 + });
108 + vi.spyOn(BootService, "layer").mockReturnValue(
109 + Layer.succeed(BootService.BootService, service),
110 + );
111 +
112 + yield* Command.runWith(serviceCommand, { version: packageJson.version })([
113 + "install",
114 + "--base-dir",
115 + baseDir,
116 + ]).pipe(
117 + Effect.provideService(HostProcess.Environment, {}),
118 + Effect.provide(
119 + Layer.mergeAll(
120 + ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
121 + Layer.fresh(TestConsole.layer),
122 + ),
123 + ),
124 + );
125 + expect(yield* fs.readFileString(`${baseDir}/service.env`)).toBe(input.expected);
126 + }),
127 + );
128 +
129 it.effect("protect refuses root before creating any T3 directories", () =>
130 Effect.gen(function* () {
131 const fs = yield* FileSystem.FileSystem;
@@ -159,89 +195,3 @@ it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("service commands
195 }),
196 );
197 });
162 -
163 -it.effect("leaves a newer service unchanged during onboarding without prompting", () =>
164 - Effect.gen(function* () {
165 - const { service, installOptions } = makeTestService(newerServiceStatus);
166 - const terminal = Terminal.make({
167 - columns: Effect.succeed(80),
168 - rows: Effect.succeed(24),
169 - readInput: Effect.die("Onboarding must not prompt to replace a newer service."),
170 - readLine: Effect.die("Onboarding must not prompt to replace a newer service."),
171 - display: () => Effect.die("Onboarding must not prompt to replace a newer service."),
172 - });
173 -
174 - const ready = yield* offerServiceDuringOnboarding.pipe(
175 - Effect.provideService(BootService.BootService, service),
176 - Effect.provideService(Terminal.Terminal, terminal),
177 - Effect.provide(NodeServices.layer),
178 - );
179 -
180 - expect(ready).toBe("skipped");
181 - expect(installOptions).toEqual([]);
182 - }),
183 -);
184 -
185 -const withTerminal = (isTTY: { readonly stdin: boolean; readonly stdout: boolean }) =>
186 - Effect.acquireRelease(
187 - Effect.sync(() =>
188 - (
189 - [
190 - [process.stdin, isTTY.stdin],
191 - [process.stdout, isTTY.stdout],
192 - ] as const
193 - ).map(([stream, value]) => {
194 - const descriptor = Object.getOwnPropertyDescriptor(stream, "isTTY");
195 - Object.defineProperty(stream, "isTTY", { configurable: true, value });
196 - return { stream, descriptor };
197 - }),
198 - ),
199 - (saved) =>
200 - Effect.sync(() => {
201 - for (const { stream, descriptor } of saved) {
202 - if (descriptor === undefined) Reflect.deleteProperty(stream, "isTTY");
203 - else Object.defineProperty(stream, "isTTY", descriptor);
204 - }
205 - }),
206 - );
207 -
208 -it.effect.each([
209 - { label: "stdin and stdout are", stdin: false, stdout: false },
210 - { label: "stdin is", stdin: false, stdout: true },
211 - { label: "stdout is", stdin: true, stdout: false },
212 -])("skips the onboarding service prompt when $label not a terminal", (isTTY) =>
213 - Effect.gen(function* () {
214 - yield* withTerminal(isTTY);
215 - const { service, installOptions } = makeTestService({
216 - ...status,
217 - installed: false,
218 - current: false,
219 - });
220 - const terminal = Terminal.make({
221 - columns: Effect.succeed(80),
222 - rows: Effect.succeed(24),
223 - readInput: Effect.die("Onboarding must not prompt without a terminal."),
224 - readLine: Effect.die("Onboarding must not prompt without a terminal."),
225 - display: () => Effect.die("Onboarding must not prompt without a terminal."),
226 - });
227 -
228 - const ready = yield* offerServiceDuringOnboarding.pipe(
229 - Effect.provideService(BootService.BootService, service),
230 - Effect.provideService(Terminal.Terminal, terminal),
231 - Effect.provide(NodeServices.layer),
232 - );
233 -
234 - expect(ready).toBe("skipped");
235 - expect(installOptions).toEqual([]);
236 - }),
237 -);
238 -
239 -// regression: #9602 diagnose incomplete headless server setup
240 -it.effect("keeps the manual-server fallback when background prerequisites fail", () =>
241 - Effect.gen(function* () {
242 - const ready = yield* recoverServiceOnboardingOffer(
243 - Effect.fail(new BootService.BootServicePrerequisiteError({ problem: "linger-disabled" })),
244 - );
245 - expect(ready).toBe("skipped");
246 - }),
247 -);
apps/server/src/cli/service.ts
+73 -99
@@ -1,17 +1,19 @@
1 +import * as NodeUtil from "node:util";
2 +
3 import * as HostProcess from "@t3tools/shared/HostProcess";
4 import * as Console from "effect/Console";
5 import * as Effect from "effect/Effect";
6 +import * as FileSystem from "effect/FileSystem";
7 import * as Layer from "effect/Layer";
8 import * as Path from "effect/Path";
6 -import * as Terminal from "effect/Terminal";
9 import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
10 import { FetchHttpClient } from "effect/http";
11
12 import packageJson from "../../package.json" with { type: "json" };
13 import * as BootService from "../cloud/bootService.ts";
14 import * as ServiceProtection from "../cloud/serviceProtection.ts";
13 -import { compareExactServiceVersions } from "../cloud/serviceProtocol.ts";
14 -import type * as ServerConfig from "../config.ts";
15 +import { compareExactServiceVersions, SERVICE_ENV_FILE } from "../cloud/serviceProtocol.ts";
16 +import * as ServerConfig from "../config.ts";
17 import * as ProcessRunner from "../processRunner.ts";
18 import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
19 import { resolveEntryPath } from "./invocation.ts";
@@ -34,15 +36,72 @@ export type ServiceReconcileResult =
36 readonly plan: BootService.BootServicePlan;
37 };
38
37 -const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?: {
39 +const SERVICE_ENV_KEY = /^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/u;
40 +
41 +/**
42 + * Sets or removes (`undefined`) entries in `service.env` text and keeps every
43 + * other line, including comments, as the user wrote it.
44 + */
45 +export const upsertServiceEnv = (
46 + contents: string,
47 + entries: Readonly<Record<string, string | undefined>>,
48 +): string => {
49 + const written = new Set<string>();
50 + const lines = contents.split("\n").flatMap((line) => {
51 + const key = SERVICE_ENV_KEY.exec(line)?.[1];
52 + if (key === undefined || !Object.hasOwn(entries, key)) return [line];
53 + const value = entries[key];
54 + if (value === undefined || written.has(key)) return [];
55 + written.add(key);
56 + return [`${key}=${value}`];
57 + });
58 + while (lines.at(-1) === "") lines.pop();
59 + for (const [key, value] of Object.entries(entries)) {
60 + if (value !== undefined && !written.has(key)) lines.push(`${key}=${value}`);
61 + }
62 + return lines.length === 0 ? "" : `${lines.join("\n")}\n`;
63 +};
64 +
65 +/** `service.env` under `baseDir`, parsed as the service launcher parses it. */
66 +export const readServiceEnv = Effect.fn("cli.service.read_env")(function* (baseDir: string) {
67 + const fs = yield* FileSystem.FileSystem;
68 + const path = (yield* Path.Path).join(baseDir, SERVICE_ENV_FILE);
69 + const contents = (yield* fs.exists(path)) ? yield* fs.readFileString(path) : "";
70 + const entries = Object.entries(NodeUtil.parseEnv(contents)).flatMap(([key, value]) =>
71 + value === undefined ? [] : [[key, value] as const],
72 + );
73 + return { path, contents, entries: Object.fromEntries(entries) };
74 +});
75 +
76 +export const writeServiceEnv = Effect.fn("cli.service.write_env")(function* (
77 + baseDir: string,
78 + entries: Readonly<Record<string, string | undefined>>,
79 +) {
80 + const fs = yield* FileSystem.FileSystem;
81 + const current = yield* readServiceEnv(baseDir);
82 + const next = upsertServiceEnv(current.contents, entries);
83 + if (next === current.contents) return;
84 + yield* fs.makeDirectory(baseDir, { recursive: true });
85 + yield* fs.writeFileString(current.path, next);
86 +});
87 +
88 +export const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?: {
89 readonly allowDowngrade?: boolean;
90 readonly start?: boolean;
91 }) {
92 + const { baseDir } = yield* ServerConfig.ServerConfig;
93 const service = yield* BootService.BootService;
94 const status = yield* service.status;
95 if (status.installed && status.current) {
96 return { changed: false, status } satisfies ServiceReconcileResult;
97 }
98 + if (status.supported && !status.installed) {
99 + // A new service listens on this machine only, until `t3 up` opens the local network.
100 + const { entries } = yield* readServiceEnv(baseDir);
101 + if (entries.T3CODE_LAN === undefined && entries.T3CODE_HOST === undefined) {
102 + yield* writeServiceEnv(baseDir, { T3CODE_LAN: "false" });
103 + }
104 + }
105 if (
106 status.installedVersion !== undefined &&
107 options?.allowDowngrade !== true &&
@@ -61,13 +120,13 @@ const reconcileService = Effect.fn("cli.service.reconcile")(function* (options?:
120 } satisfies ServiceReconcileResult;
121 });
122
64 -function formatServiceChange(
123 +export function formatServiceChange(
124 result: Extract<ServiceReconcileResult, { readonly changed: true }>,
125 ): string {
126 if (result.plan.handedOff === true) {
68 - 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}`;
127 + return `Service update to t3@${packageJson.version} queued. This session will disconnect.\nLog: ${result.plan.logPath}`;
128 }
70 - return `${result.previouslyInstalled ? "Updated" : "Installed"} T3 Code service with t3@${packageJson.version}.\nLogs: ${result.plan.logPath}`;
129 + return `Service ${result.previouslyInstalled ? "updated" : "installed"} · t3@${packageJson.version}\nLog: ${result.plan.logPath}`;
130 }
131
132 function formatProtection(
@@ -129,7 +188,7 @@ const runServiceCommand = Effect.fn("cli.service.run")(function* <A, E, R>(
188 ) {
189 const logLevel = yield* GlobalFlag.LogLevel;
190 const config = yield* resolveCliAuthConfig(flags, logLevel);
132 - return yield* run.pipe(Effect.provide(layer(config)));
191 + return yield* run.pipe(Effect.provide(Layer.merge(layer(config), ServerConfig.layer(config))));
192 });
193
194 const serviceReconcileFlags = {
@@ -141,7 +200,9 @@ const serviceReconcileFlags = {
200 };
201
202 const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pipe(
144 - Command.withDescription("Install T3 Code as a background service for this user."),
203 + Command.withDescription(
204 + "Install T3 Code as a background service for this user. `t3 up` also chooses how your other devices reach it.",
205 + ),
206 Command.withHandler((flags) =>
207 runServiceCommand(
208 flags,
@@ -154,6 +215,9 @@ const serviceInstallCommand = Command.make("install", serviceReconcileFlags).pip
215 return;
216 }
217 yield* Console.log(formatServiceChange(result));
218 + if (!result.previouslyInstalled) {
219 + yield* Console.log("Run `t3 up` to choose how your other devices reach it.");
220 + }
221 }),
222 ),
223 ),
@@ -353,96 +417,6 @@ const serviceProtectCommand = Command.make("protect", {
417 ),
418 );
419
356 -export type ServiceOnboardingOutcome = "ready" | "pending" | "skipped";
357 -
358 -export const offerServiceDuringOnboarding = Effect.gen(function* () {
359 - const service = yield* BootService.BootService;
360 - const status = yield* service.status;
361 - const { supported, installed, current } = status;
362 - if (!supported) {
363 - return "skipped" as const;
364 - }
365 - if (installed && current) {
366 - yield* Console.log("T3 Code is already set up to run in the background on this machine.");
367 - return "ready" as const;
368 - }
369 - for (const problem of status.problems ?? []) {
370 - yield* Console.warn(`[${problem}] ${BootService.formatBootServiceProblem(problem)}`);
371 - }
372 - if (
373 - installed &&
374 - status.installedVersion !== undefined &&
375 - compareExactServiceVersions(status.installedVersion, packageJson.version) > 0
376 - ) {
377 - yield* Console.log(
378 - `A newer t3@${status.installedVersion} background service is installed. Leaving it unchanged.`,
379 - );
380 - return "skipped" as const;
381 - }
382 - // Both streams must be terminals: with stdout redirected the prompt is
383 - // invisible and the command would hang waiting on it.
384 - if (!(process.stdin.isTTY && process.stdout.isTTY)) {
385 - yield* Console.log(
386 - "Not a terminal, so background setup was skipped. Run `t3 service install` to set it up.",
387 - );
388 - return "skipped" as const;
389 - }
390 - const platform = yield* HostProcess.Platform;
391 - const wanted = yield* Prompt.run(
392 - Prompt.Confirm({
393 - message: installed
394 - ? "The installed T3 Code service needs an update or repair. Update it now?"
395 - : platform === "darwin"
396 - ? "Run T3 Code in the background whenever you log in to this Mac? " +
397 - "It stays reachable through T3 Connect while you are logged in."
398 - : "Run T3 Code in the background whenever this machine boots? " +
399 - "It stays reachable through T3 Connect even after you log out.",
400 - initial: true,
401 - }),
402 - );
403 - if (!wanted) {
404 - return "skipped" as const;
405 - }
406 - const result = yield* reconcileService();
407 - if (result.changed) {
408 - yield* Console.log(
409 - result.plan.handedOff === true
410 - ? formatServiceChange(result)
411 - : `Background service ${result.previouslyInstalled ? "updated" : "installed"}. Logs: ${result.plan.logPath}`,
412 - );
413 - }
414 - return result.changed && result.plan.handedOff === true
415 - ? ("pending" as const)
416 - : ("ready" as const);
417 -});
418 -
419 -const reportServiceSetupFailure = (error: BootService.BootServiceError) =>
420 - Console.warn(`Background setup did not finish: ${error.message}`).pipe(
421 - Effect.as("skipped" as const),
422 - );
423 -
424 -export const recoverServiceOnboardingOffer = <R>(
425 - offer: Effect.Effect<
426 - ServiceOnboardingOutcome,
427 - BootService.BootServiceError | Terminal.QuitError,
428 - R
429 - >,
430 -) =>
431 - offer.pipe(
432 - Effect.catchTags({
433 - QuitError: () => Effect.succeed("skipped" as const),
434 - BootServiceUnsupportedError: (error) =>
435 - Console.log(`Skipping background setup: ${error.message}`).pipe(
436 - Effect.as("skipped" as const),
437 - ),
438 - BootServiceCommandError: reportServiceSetupFailure,
439 - BootServiceInstallError: reportServiceSetupFailure,
440 - BootServicePrerequisiteError: reportServiceSetupFailure,
441 - BootServiceUpdatePendingError: reportServiceSetupFailure,
442 - BootServiceDowngradeRefusedError: reportServiceSetupFailure,
443 - }),
444 - );
445 -
420 export const serviceCommand = Command.make("service").pipe(
421 Command.withDescription("Manage the T3 Code background service."),
422 Command.withSubcommands([
apps/server/src/cli/up.connect.test.ts new
+126
@@ -0,0 +1,126 @@
1 +import * as NodeServices from "@effect/platform-node/NodeServices";
2 +import { expect, it } from "@effect/vitest";
3 +import * as HostProcess from "@t3tools/shared/HostProcess";
4 +import * as NetService from "@t3tools/shared/Net";
5 +import * as ConfigProvider from "effect/ConfigProvider";
6 +import * as Effect from "effect/Effect";
7 +import * as FileSystem from "effect/FileSystem";
8 +import * as Layer from "effect/Layer";
9 +import * as TestConsole from "effect/testing/TestConsole";
10 +import { Command } from "effect/cli";
11 +import { vi } from "vite-plus/test";
12 +
13 +import packageJson from "../../package.json" with { type: "json" };
14 +import * as BootService from "../cloud/bootService.ts";
15 +import { upCommand } from "./up.ts";
16 +
17 +// T3 Connect's flows run only in builds with its public config, and they call
18 +// the relay; this file swaps in the link and unlink steps.
19 +const events = vi.hoisted((): Array<string> => []);
20 +// The CLI link marker, kept in memory instead of the secret store.
21 +const link = vi.hoisted(() => ({
22 + desired: false,
23 + mode: "managed" as "managed" | "publish_only",
24 +}));
25 +vi.mock("../cloud/CliState.ts", async (importOriginal) => ({
26 + ...(await importOriginal<typeof import("../cloud/CliState.ts")>()),
27 + readCliDesiredCloudLink: Effect.sync(() => link.desired),
28 + readCliDesiredLinkMode: Effect.sync(() => link.mode),
29 + setCliDesiredCloudLink: (desired: boolean, mode: "managed" | "publish_only" = "managed") =>
30 + Effect.sync(() => {
31 + link.desired = desired;
32 + link.mode = mode;
33 + }),
34 +}));
35 +vi.mock("../cloud/publicConfig.ts", async (importOriginal) => ({
36 + ...(await importOriginal<typeof import("../cloud/publicConfig.ts")>()),
37 + hasCloudPublicConfig: true,
38 +}));
39 +vi.mock("./connect.ts", async (importOriginal) => {
40 + const actual = await importOriginal<typeof import("./connect.ts")>();
41 + return {
42 + ...actual,
43 + linkEnvironmentForConnect: () =>
44 + Effect.sync(() => {
45 + events.push("link");
46 + link.desired = true;
47 + link.mode = "managed";
48 + return { identity: "me@example.com" } as const;
49 + }),
50 + disconnectCloud: () =>
51 + Effect.sync(() => {
52 + events.push("unlink");
53 + link.desired = false;
54 + return { status: "succeeded" } as const;
55 + }),
56 + };
57 +});
58 +
59 +it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 up with T3 Connect", (it) => {
60 + it.effect.each([
61 + { label: "no link", prior: null, events: ["link", "restart", "unlink", "restart"] },
62 + // The publish-only link comes back, with its activity publishing.
63 + {
64 + label: "a publish-only link",
65 + prior: "publish_only" as const,
66 + events: ["link", "restart", "restart"],
67 + },
68 + ])("a failed restart after --connect undoes it, then restarts: $label before", (input) =>
69 + Effect.gen(function* () {
70 + events.length = 0;
71 + link.desired = input.prior !== null;
72 + link.mode = input.prior ?? "managed";
73 + const fs = yield* FileSystem.FileSystem;
74 + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-up-connect-test-" });
75 + yield* fs.writeFileString(`${baseDir}/service.env`, "T3CODE_LAN=false\n");
76 + const status = {
77 + supported: true,
78 + installed: true,
79 + current: true,
80 + unitPath: "/home/me/.config/systemd/user/t3code.service",
81 + logPath: "/home/me/.t3/userdata/logs/boot-service.log",
82 + };
83 + vi.spyOn(BootService, "layer").mockReturnValue(
84 + Layer.succeed(
85 + BootService.BootService,
86 + BootService.BootService.of({
87 + status: Effect.succeed(status),
88 + withStopped: (operation) => operation,
89 + restart: Effect.sync(() => events.push("restart")).pipe(
90 + Effect.andThen(
91 + Effect.fail(new BootService.BootServiceCommandError({ step: "restart" })),
92 + ),
93 + ),
94 + install: () => Effect.die("an installed, current service is not reinstalled"),
95 + uninstall: Effect.succeed(false),
96 + }),
97 + ),
98 + );
99 +
100 + const exit = yield* Command.runWith(upCommand, { version: packageJson.version })([
101 + "--base-dir",
102 + baseDir,
103 + "--connect",
104 + ]).pipe(
105 + Effect.provideService(HostProcess.Environment, {}),
106 + Effect.provide(
107 + Layer.mergeAll(
108 + ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
109 + Layer.fresh(TestConsole.layer),
110 + ),
111 + ),
112 + Effect.exit,
113 + );
114 +
115 + expect(exit._tag).toBe("Failure");
116 + // Any unlink comes before the restart on the old settings.
117 + expect(events).toEqual(input.events);
118 + expect(link).toEqual(
119 + input.prior === null
120 + ? { desired: false, mode: "managed" }
121 + : { desired: true, mode: input.prior },
122 + );
123 + expect(yield* fs.readFileString(`${baseDir}/service.env`)).toBe("T3CODE_LAN=false\n");
124 + }),
125 + );
126 +});
apps/server/src/cli/up.test.ts new
+356
@@ -0,0 +1,356 @@
1 +import * as NodeServices from "@effect/platform-node/NodeServices";
2 +import { expect, it } from "@effect/vitest";
3 +import * as HostProcess from "@t3tools/shared/HostProcess";
4 +import * as NetService from "@t3tools/shared/Net";
5 +import * as Cause from "effect/Cause";
6 +import * as ConfigProvider from "effect/ConfigProvider";
7 +import * as Effect from "effect/Effect";
8 +import * as FileSystem from "effect/FileSystem";
9 +import * as Layer from "effect/Layer";
10 +import * as Option from "effect/Option";
11 +import * as Queue from "effect/Queue";
12 +import * as Terminal from "effect/Terminal";
13 +import * as TestConsole from "effect/testing/TestConsole";
14 +import { Command } from "effect/cli";
15 +import { afterEach, vi } from "vite-plus/test";
16 +
17 +import packageJson from "../../package.json" with { type: "json" };
18 +import * as BootService from "../cloud/bootService.ts";
19 +import { upsertServiceEnv } from "./service.ts";
20 +import { connectEnabled, planRoutes, upCommand } from "./up.ts";
21 +
22 +const none = Option.none<boolean>();
23 +
24 +it.each([
25 + {
26 + label: "a new machine starts from T3 Connect and asks",
27 + setup: { installed: false, connect: false, lan: false },
28 + flags: { connect: none, lan: none },
29 + expected: { routes: { connect: true, lan: false }, ask: ["connect", "lan"] },
30 + },
31 + {
32 + label: "a build without T3 Connect never offers it",
33 + setup: { installed: false, connect: null, lan: false },
34 + flags: { connect: none, lan: none },
35 + expected: { routes: { connect: false, lan: false }, ask: ["lan"] },
36 + },
37 + {
38 + label: "a rerun starts from the current setup",
39 + setup: { installed: true, connect: false, lan: true },
40 + flags: { connect: none, lan: none },
41 + expected: { routes: { connect: false, lan: true }, ask: ["connect", "lan"] },
42 + },
43 + {
44 + label: "a route flag on a new machine turns on only that route",
45 + setup: { installed: false, connect: false, lan: false },
46 + flags: { connect: none, lan: Option.some(true) },
47 + expected: { routes: { connect: false, lan: true }, ask: [] },
48 + },
49 + {
50 + label: "a route flag asks nothing and keeps the other route",
51 + setup: { installed: true, connect: true, lan: true },
52 + flags: { connect: none, lan: Option.some(false) },
53 + expected: { routes: { connect: true, lan: false }, ask: [] },
54 + },
55 +])("$label", ({ setup, flags, expected }) => {
56 + expect(planRoutes(setup, flags)).toEqual(expected);
57 +});
58 +
59 +const SERVICE = {
60 + supported: true,
61 + installed: true,
62 + current: true,
63 + unitPath: "/home/me/.config/systemd/user/t3code.service",
64 + logPath: "/home/me/.t3/userdata/logs/boot-service.log",
65 +} as const;
66 +
67 +it.each([
68 + {
69 + label: "a CLI managed link",
70 + cliDesired: true,
71 + cliMode: "managed",
72 + managedTunnel: false,
73 + revoked: false,
74 + on: true,
75 + },
76 + {
77 + label: "a link the app made",
78 + cliDesired: false,
79 + cliMode: "managed",
80 + managedTunnel: true,
81 + revoked: false,
82 + on: true,
83 + },
84 + {
85 + label: "a publish-only link",
86 + cliDesired: true,
87 + cliMode: "publish_only",
88 + managedTunnel: false,
89 + revoked: false,
90 + on: false,
91 + },
92 + {
93 + label: "a publish-only link with an old tunnel config",
94 + cliDesired: true,
95 + cliMode: "publish_only",
96 + managedTunnel: true,
97 + revoked: false,
98 + on: false,
99 + },
100 + {
101 + label: "a revoked link",
102 + cliDesired: true,
103 + cliMode: "managed",
104 + managedTunnel: true,
105 + revoked: true,
106 + on: false,
107 + },
108 + {
109 + label: "no link",
110 + cliDesired: false,
111 + cliMode: "managed",
112 + managedTunnel: false,
113 + revoked: false,
114 + on: false,
115 + },
116 +] as const)("T3 Connect is on for $label: $on", ({ label: _, on, ...link }) => {
117 + expect(connectEnabled(link)).toBe(on);
118 +});
119 +
120 +// Prompts run only when both streams are terminals.
121 +const asTerminal = Effect.acquireRelease(
122 + Effect.sync(() =>
123 + [process.stdin, process.stdout].map((stream) => {
124 + const descriptor = Object.getOwnPropertyDescriptor(stream, "isTTY");
125 + Object.defineProperty(stream, "isTTY", { configurable: true, value: true });
126 + return { stream, descriptor };
127 + }),
128 + ),
129 + (saved) =>
130 + Effect.sync(() => {
131 + for (const { stream, descriptor } of saved) {
132 + if (descriptor === undefined) Reflect.deleteProperty(stream, "isTTY");
133 + else Object.defineProperty(stream, "isTTY", descriptor);
134 + }
135 + }),
136 +);
137 +
138 +const answering = (text: string) =>
139 + Terminal.make({
140 + columns: Effect.succeed(80),
141 + rows: Effect.succeed(24),
142 + readInput: Effect.gen(function* () {
143 + const input = yield* Queue.unbounded<Terminal.UserInput, Cause.Done>();
144 + yield* Queue.offer(input, {
145 + input: Option.some(text),
146 + key: { name: text, ctrl: false, meta: false, shift: false },
147 + });
148 + return input;
149 + }),
150 + readLine: Effect.succeed(text),
151 + display: () => Effect.void,
152 + });
153 +
154 +it.layer(Layer.mergeAll(NodeServices.layer, NetService.layer))("t3 up", (it) => {
155 + afterEach(() => vi.restoreAllMocks());
156 +
157 + it.effect.each<{
158 + readonly label: string;
159 + readonly installed: boolean;
160 + readonly status?: Partial<BootService.BootServiceStatus>;
161 + readonly installFails?: boolean;
162 + readonly restartFails?: boolean;
163 + /** Runs as if in a terminal, answering each question with this text. */
164 + readonly answer?: string;
165 + readonly prints?: string;
166 + readonly env: string;
167 + readonly args: ReadonlyArray<string>;
168 + readonly installs: number;
169 + readonly restarts: number;
170 + readonly envAfter: string;
171 + }>([
172 + {
173 + label: "nothing changed",
174 + installed: true,
175 + env: "T3CODE_LAN=false\n",
176 + args: ["--no-lan"],
177 + installs: 0,
178 + restarts: 0,
179 + envAfter: "T3CODE_LAN=false\n",
180 + },
181 + {
182 + label: "the local network opens",
183 + installed: true,
184 + env: "T3CODE_LAN=false\n",
185 + args: ["--lan"],
186 + installs: 0,
187 + restarts: 1,
188 + envAfter: "T3CODE_LAN=true\n",
189 + },
190 + {
191 + label: "a new service starts with its settings",
192 + installed: false,
193 + env: "",
194 + args: ["--lan"],
195 + installs: 1,
196 + restarts: 0,
197 + envAfter: "T3CODE_LAN=true\n",
198 + },
199 + {
200 + label: "a route turns off with no service to run",
201 + installed: false,
202 + env: "T3CODE_LAN=true\n",
203 + args: ["--no-lan"],
204 + installs: 0,
205 + restarts: 0,
206 + envAfter: "T3CODE_LAN=false\n",
207 + },
208 + {
209 + label: "a stopped newer service starts as it is",
210 + installed: true,
211 + status: { current: false, installedVersion: "999.0.0", problems: ["service-stopped"] },
212 + env: "T3CODE_LAN=false\n",
213 + args: ["--yes"],
214 + installs: 0,
215 + restarts: 1,
216 + envAfter: "T3CODE_LAN=false\n",
217 + },
218 + {
219 + label: "a failed update keeps service.env matching the old service",
220 + // The old service still runs, so no foreground server is offered.
221 + prints: "Fix that, then run `t3 up` again.",
222 + installed: true,
223 + status: { current: false },
224 + installFails: true,
225 + env: "",
226 + args: ["--no-lan"],
227 + installs: 0,
228 + restarts: 0,
229 + envAfter: "",
230 + },
231 + {
232 + label: "a failed restart puts service.env back and restarts on it",
233 + installed: true,
234 + restartFails: true,
235 + env: "T3CODE_LAN=false\n",
236 + args: ["--lan"],
237 + installs: 0,
238 + restarts: 2,
239 + envAfter: "T3CODE_LAN=false\n",
240 + },
241 + {
242 + label: "declining an update changes nothing",
243 + installed: true,
244 + status: { current: false },
245 + answer: "n",
246 + env: "T3CODE_LAN=false\n",
247 + args: ["--lan"],
248 + installs: 0,
249 + restarts: 0,
250 + envAfter: "T3CODE_LAN=false\n",
251 + },
252 + {
253 + label: "no service manager still records the choice",
254 + installed: false,
255 + status: { supported: false },
256 + env: "",
257 + args: ["--lan"],
258 + installs: 0,
259 + restarts: 0,
260 + envAfter: "T3CODE_LAN=true\n",
261 + },
262 + {
263 + label: "the old default is kept",
264 + installed: true,
265 + env: "",
266 + args: ["--yes"],
267 + installs: 0,
268 + restarts: 0,
269 + envAfter: "T3CODE_LAN=true\n",
270 + },
271 + ])("restarts the service only when it must: $label", (input) =>
272 + Effect.gen(function* () {
273 + const fs = yield* FileSystem.FileSystem;
274 + const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-up-test-" });
275 + yield* fs.writeFileString(`${baseDir}/service.env`, input.env);
276 + let installs = 0;
277 + let restarts = 0;
278 + const status = {
279 + ...SERVICE,
280 + installed: input.installed,
281 + current: input.installed,
282 + ...input.status,
283 + };
284 + vi.spyOn(BootService, "layer").mockReturnValue(
285 + Layer.succeed(
286 + BootService.BootService,
287 + BootService.BootService.of({
288 + status: Effect.succeed(status),
289 + withStopped: (operation) => operation,
290 + restart: Effect.sync(() => restarts++).pipe(
291 + Effect.andThen(
292 + input.restartFails === true
293 + ? Effect.fail(new BootService.BootServiceCommandError({ step: "restart" }))
294 + : Effect.succeed("restarted" as const),
295 + ),
296 + ),
297 + install: () =>
298 + input.installFails === true
299 + ? Effect.fail(
300 + new BootService.BootServicePrerequisiteError({ problem: "linger-disabled" }),
301 + )
302 + : Effect.sync(() => {
303 + installs++;
304 + return {
305 + program: ["t3"],
306 + baseDir,
307 + unitPath: status.unitPath,
308 + logPath: status.logPath,
309 + };
310 + }),
311 + uninstall: Effect.succeed(false),
312 + }),
313 + ),
314 + );
315 +
316 + if (input.answer !== undefined) yield* asTerminal;
317 + const { exit, lines } = yield* Command.runWith(upCommand, { version: packageJson.version })([
318 + "--base-dir",
319 + baseDir,
320 + ...input.args,
321 + ]).pipe(
322 + Effect.provideService(HostProcess.Environment, {}),
323 + input.answer === undefined
324 + ? (effect) => effect
325 + : Effect.provideService(Terminal.Terminal, answering(input.answer)),
326 + Effect.exit,
327 + Effect.flatMap((exit) =>
328 + Effect.map(TestConsole.logLines, (lines) => ({ exit, lines: lines.map(String) })),
329 + ),
330 + Effect.provide(
331 + Layer.mergeAll(
332 + ConfigProvider.layer(ConfigProvider.fromEnv({ env: {} })),
333 + Layer.fresh(TestConsole.layer),
334 + ),
335 + ),
336 + );
337 + if (input.prints !== undefined) {
338 + expect(lines.join("\n")).toContain(input.prints);
339 + }
340 + expect(exit._tag).toBe(input.restartFails === true ? "Failure" : "Success");
341 + expect({ installs, restarts }).toEqual({
342 + installs: input.installs,
343 + restarts: input.restarts,
344 + });
345 + expect(yield* fs.readFileString(`${baseDir}/service.env`)).toBe(input.envAfter);
346 + }),
347 + );
348 +});
349 +
350 +it("rewrites only the named service.env keys and keeps the user's lines", () => {
351 + const before = ["# my settings", "T3CODE_PORT=4000", "export T3CODE_LAN=0", "T3CODE_LAN=1", ""];
352 + expect(upsertServiceEnv(before.join("\n"), { T3CODE_LAN: "true", T3CODE_HOST: undefined })).toBe(
353 + ["# my settings", "T3CODE_PORT=4000", "T3CODE_LAN=true", ""].join("\n"),
354 + );
355 + expect(upsertServiceEnv("", { T3CODE_LAN: "false" })).toBe("T3CODE_LAN=false\n");
356 +});
apps/server/src/cli/up.ts new
+510
@@ -0,0 +1,510 @@
1 +import * as HostProcess from "@t3tools/shared/HostProcess";
2 +import * as Config from "effect/Config";
3 +import * as ConfigProvider from "effect/ConfigProvider";
4 +import * as Console from "effect/Console";
5 +import * as Effect from "effect/Effect";
6 +import * as Layer from "effect/Layer";
7 +import * as Option from "effect/Option";
8 +import { Command, Flag, GlobalFlag, Prompt } from "effect/cli";
9 +import * as CliError from "effect/cli/CliError";
10 +
11 +import packageJson from "../../package.json" with { type: "json" };
12 +import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
13 +import * as BootService from "../cloud/bootService.ts";
14 +import * as CliState from "../cloud/CliState.ts";
15 +import { CLOUD_ENDPOINT_RUNTIME_CONFIG, CLOUD_LINK_REVOKED } from "../cloud/config.ts";
16 +import { hasCloudPublicConfig } from "../cloud/publicConfig.ts";
17 +import { compareExactServiceVersions } from "../cloud/serviceProtocol.ts";
18 +import * as ServerConfig from "../config.ts";
19 +import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
20 +import {
21 + connectSubcommands,
22 + disconnectCloud,
23 + headlessFlag,
24 + linkEnvironmentForConnect,
25 + runCloudCommand,
26 + waitForReachability,
27 +} from "./connect.ts";
28 +import { resolveHostCliCommand } from "./invocation.ts";
29 +import * as CliService from "./service.ts";
30 +
31 +type Route = "connect" | "lan";
32 +type Routes = Readonly<Record<Route, boolean>>;
33 +
34 +/** How other devices reach this machine now. */
35 +interface Setup {
36 + readonly service: BootService.BootServiceStatus;
37 + /** Null in builds without T3 Connect. Off when T3 Connect revoked the link. */
38 + readonly connect: boolean | null;
39 + /** T3 Connect revoked the link; `t3 connect` links again. */
40 + readonly connectRevoked: boolean;
41 + readonly lan: boolean;
42 + /** An installed service with no T3CODE_LAN keeps the old default: on. */
43 + readonly lanFromOldDefault: boolean;
44 + readonly host: string | undefined;
45 +}
46 +
47 +/**
48 + * T3 Connect is on when this CLI asked for a managed link, or when the desktop or
49 + * web app made one: that saves the tunnel config but no CLI marker. Revoked is off.
50 + */
51 +export const connectEnabled = (link: {
52 + readonly cliDesired: boolean;
53 + readonly cliMode: CliState.CliDesiredLinkMode;
54 + readonly managedTunnel: boolean;
55 + readonly revoked: boolean;
56 +}) =>
57 + // The server starts no tunnel for a CLI publish-only link, even with an old tunnel config.
58 + !link.revoked && (link.cliDesired ? link.cliMode === "managed" : link.managedTunnel);
59 +
60 +const readSetup = Effect.fn("cli.up.read_setup")(function* () {
61 + const { baseDir } = yield* ServerConfig.ServerConfig;
62 + const service = yield* (yield* BootService.BootService).status;
63 + const { entries } = yield* CliService.readServiceEnv(baseDir);
64 + // Parsed as the server parses it.
65 + const lan = yield* Config.Boolean("T3CODE_LAN")
66 + .pipe(Config.option)
67 + .parse(ConfigProvider.fromEnv({ env: entries }));
68 + const secrets = yield* ServerSecretStore.ServerSecretStore;
69 + const connectRevoked =
70 + hasCloudPublicConfig && Option.isSome(yield* secrets.get(CLOUD_LINK_REVOKED));
71 + const connect = hasCloudPublicConfig
72 + ? connectEnabled({
73 + cliDesired: yield* CliState.readCliDesiredCloudLink,
74 + cliMode: yield* CliState.readCliDesiredLinkMode,
75 + managedTunnel: Option.isSome(yield* secrets.get(CLOUD_ENDPOINT_RUNTIME_CONFIG)),
76 + revoked: connectRevoked,
77 + })
78 + : null;
79 + return {
80 + service,
81 + connect,
82 + connectRevoked,
83 + lan: Option.getOrElse(lan, () => service.installed),
84 + lanFromOldDefault: Option.isNone(lan) && service.installed,
85 + host: entries.T3CODE_HOST,
86 + } satisfies Setup;
87 +});
88 +
89 +/**
90 + * The routes `t3 up` starts from. With no route flag it asks about every
91 + * route, starting a machine with no service from T3 Connect. Any route flag
92 + * means it asks nothing and keeps the routes not named as they are.
93 + */
94 +export const planRoutes = (
95 + setup: { readonly installed: boolean; readonly connect: boolean | null; readonly lan: boolean },
96 + flags: { readonly connect: Option.Option<boolean>; readonly lan: Option.Option<boolean> },
97 +) => {
98 + const ask = Option.isNone(flags.connect) && Option.isNone(flags.lan);
99 + const start = {
100 + connect: setup.connect === true || (ask && !setup.installed && setup.connect !== null),
101 + lan: setup.lan,
102 + };
103 + return {
104 + routes: {
105 + connect: Option.getOrElse(flags.connect, () => start.connect),
106 + lan: Option.getOrElse(flags.lan, () => start.lan),
107 + } satisfies Routes,
108 + ask: ask
109 + ? (["connect", "lan"] as const).filter((r) => r !== "connect" || setup.connect !== null)
110 + : [],
111 + };
112 +};
113 +
114 +/** A running service reads T3CODE_LAN and its T3 Connect link only when it starts. */
115 +const needsRestart = (before: Routes, after: Routes) =>
116 + after.lan !== before.lan || (after.connect && !before.connect);
117 +
118 +const CHOICES = {
119 + connect: { title: "T3 Connect", description: "Creates a tunnel to control your PC." },
120 + lan: { title: "Local network", description: "LAN and tailnet. Pairing code required." },
121 +} satisfies Record<Route, { readonly title: string; readonly description: string }>;
122 +
123 +const formatSetup = (setup: Setup) => {
124 + const { service } = setup;
125 + const rows: ReadonlyArray<readonly [string, string]> = [
126 + [
127 + "Service",
128 + !service.supported
129 + ? "unavailable"
130 + : service.installed
131 + ? `installed · t3@${service.installedVersion ?? packageJson.version}`
132 + : "not installed",
133 + ],
134 + ...(setup.connect === null
135 + ? []
136 + : [
137 + [
138 + "T3 Connect",
139 + setup.connect
140 + ? "on · your T3 account"
141 + : setup.connectRevoked
142 + ? "off · link revoked. Run `t3 connect`."
143 + : "off",
144 + ] as const,
145 + ]),
146 + [
147 + "Local network",
148 + setup.host !== undefined
149 + ? `overridden · T3CODE_HOST=${setup.host}`
150 + : setup.lanFromOldDefault
151 + ? "on · kept from an older install"
152 + : setup.lan
153 + ? "on · pairing code only"
154 + : "off",
155 + ],
156 + ];
157 + const notes = [
158 + ...(setup.host === undefined && setup.lan
159 + ? ["Anyone on your LAN or tailnet can reach the port. A pairing code is the only lock."]
160 + : []),
161 + ...(setup.lanFromOldDefault
162 + ? ["Older installs keep LAN access on. Turn it off: `t3 up --no-lan`."]
163 + : []),
164 + ];
165 + return [
166 + ...rows.map(([label, value]) => ` ${label.padEnd(15)}${value}`),
167 + ...(notes.length === 0 ? [] : ["", ...notes]),
168 + ].join("\n");
169 +};
170 +
171 +const formatNextSteps = (routes: Routes, serviceInstalled: boolean) =>
172 + [
173 + ...(routes.connect
174 + ? ["On your other device, sign in to T3 Connect with the same account."]
175 + : []),
176 + ...(routes.lan ? ["Run `t3 pair`. Use the code on your other device."] : []),
177 + ...(routes.connect || routes.lan
178 + ? []
179 + : [
180 + serviceInstalled
181 + ? "Remote access is off. T3 Code still runs here in the background."
182 + : "Remote access is off. Run `t3` to use T3 Code here.",
183 + ]),
184 + ].join("\n");
185 +
186 +const interactiveTerminal = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);
187 +
188 +const setUp = Effect.fn("cli.up")(function* (flags: {
189 + readonly baseDir: Option.Option<string>;
190 + readonly connect: Option.Option<boolean>;
191 + readonly lan: Option.Option<boolean>;
192 + readonly yes: boolean;
193 + readonly headless: boolean;
194 +}) {
195 + const { baseDir } = yield* ServerConfig.ServerConfig;
196 + const service = yield* BootService.BootService;
197 + const before = yield* readSetup();
198 + if (before.connect === null && Option.getOrElse(flags.connect, () => false)) {
199 + return yield* new CliError.UserError({
200 + cause: "connect",
201 + userMessage: "T3 Connect is unavailable in this build.",
202 + });
203 + }
204 +
205 + const current = { connect: before.connect === true, lan: before.lan };
206 + // A publish-only link is not "on", but a rollback must put it back.
207 + const priorPublishOnly =
208 + hasCloudPublicConfig &&
209 + (yield* CliState.readCliDesiredCloudLink) &&
210 + (yield* CliState.readCliDesiredLinkMode) === "publish_only";
211 + const plan = planRoutes({ ...before, installed: before.service.installed }, flags);
212 + const interactive = !flags.yes && interactiveTerminal();
213 + let routes = plan.routes;
214 + if (plan.ask.length > 0 && interactive) {
215 + if (before.service.installed) yield* Console.log(`Current setup\n${formatSetup(before)}\n`);
216 + const picked = yield* Prompt.run(
217 + Prompt.MultiSelect({
218 + message: "Allow connections through:",
219 + selectAll: "Select all",
220 + selectNone: "Clear all",
221 + inverseSelection: "Invert selection",
222 + choices: plan.ask.map((route) => ({
223 + ...CHOICES[route],
224 + value: route,
225 + selected: plan.routes[route],
226 + })),
227 + }),
228 + ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(null) }));
229 + if (picked === null) return yield* Console.log("Nothing changed.");
230 + routes = { connect: picked.includes("connect"), lan: picked.includes("lan") };
231 + } else if (plan.ask.length > 0 && !flags.yes && !before.service.installed) {
232 + return yield* new CliError.UserError({
233 + cause: "routes",
234 + userMessage: `No terminal. Choose access with ${
235 + before.connect === null ? "--lan" : "--connect or --lan"
236 + }, or use --yes for the default. See \`t3 up --help\`.`,
237 + });
238 + }
239 + // Nothing to run in the background, but a route left on still gets turned off.
240 + if (!before.service.installed && !routes.connect && !routes.lan) {
241 + if (current.connect || before.connectRevoked) {
242 + yield* disconnectCloud({ clearAuthorization: false });
243 + }
244 + if (current.lan) yield* CliService.writeServiceEnv(baseDir, { T3CODE_LAN: "false" });
245 + return yield* Console.log(formatNextSteps(routes, false));
246 + }
247 + const { installedVersion } = before.service;
248 + const newer =
249 + installedVersion !== undefined &&
250 + compareExactServiceVersions(installedVersion, packageJson.version) > 0;
251 + // Asked before anything changes, so a declined restart leaves service.env
252 + // matching what the running service read when it started.
253 + // A stopped service of this version is not current, so reconcile starts it;
254 + // a newer one is left alone and needs this restart to start.
255 + const stopped = before.service.problems?.includes("service-stopped") === true;
256 + const restart =
257 + before.service.installed &&
258 + (before.service.current || newer) &&
259 + (needsRestart(current, routes) || stopped);
260 + // An older or broken service is reinstalled, which restarts it too.
261 + const update = before.service.installed && !before.service.current && !newer && !stopped;
262 + if ((restart || update) && interactive && !stopped) {
263 + const confirmed = yield* Prompt.run(
264 + Prompt.Confirm({
265 + message: update
266 + ? "Update and restart T3 Code? Running agent turns will stop."
267 + : "Apply changes and restart? Running agent turns will stop.",
268 + initial: true,
269 + }),
270 + ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) }));
271 + if (!confirmed) return yield* Console.log("Nothing changed.");
272 + }
273 +
274 + if (routes.connect && !current.connect) {
275 + const linked = yield* linkEnvironmentForConnect({
276 + headless: flags.headless,
277 + installRelayClient: true,
278 + });
279 + if (linked === null) return;
280 + yield* Console.log(
281 + `✓ Signed in to T3 Connect${linked.identity ? ` as ${linked.identity}` : ""}`,
282 + );
283 + }
284 + // A running server unlinks live; when that fails, only a restart stops its tunnel.
285 + const unlinkFailed =
286 + !routes.connect && (current.connect || before.connectRevoked)
287 + ? (yield* disconnectCloud({ clearAuthorization: false })).status === "failed"
288 + : false;
289 + const previousLan = (yield* CliService.readServiceEnv(baseDir)).entries.T3CODE_LAN;
290 + // Also with no service manager: the file records the choice that `t3 status` shows.
291 + yield* CliService.writeServiceEnv(baseDir, { T3CODE_LAN: String(routes.lan) });
292 + // When the service step fails, an installed service still runs with the old
293 + // value, so the file goes back to match it.
294 + // A new T3 Connect link is undone too, with any tunnel the failed start saved, so a
295 + // rerun sees it as a change and restarts. The sign-in stays.
296 + const restoreServiceEnv = before.service.installed
297 + ? CliService.writeServiceEnv(baseDir, { T3CODE_LAN: previousLan }).pipe(
298 + Effect.andThen(
299 + !routes.connect || current.connect
300 + ? Effect.void
301 + : priorPublishOnly
302 + ? CliState.setCliDesiredCloudLink(true, "publish_only")
303 + : disconnectCloud({ clearAuthorization: false }).pipe(Effect.asVoid),
304 + ),
305 + )
306 + : Effect.void;
307 + // A failed update or restart may still have started the service with the new
308 + // settings, so restart it once more on the old ones.
309 + const rollBack = before.service.installed
310 + ? restoreServiceEnv.pipe(Effect.andThen(service.restart.pipe(Effect.ignore)))
311 + : Effect.void;
312 + if (before.host !== undefined) {
313 + yield* Console.warn(
314 + `T3CODE_HOST=${before.host} in service.env overrides the network choice. Remove it to apply it.`,
315 + );
316 + }
317 +
318 + const printServeCommand = Effect.fn(function* (reason: string) {
319 + const { command } = yield* resolveHostCliCommand("serve", [
320 + ...Option.match(flags.baseDir, { onNone: () => [], onSome: (dir) => ["--base-dir", dir] }),
321 + // Explicit either way, so a T3CODE_LAN in the shell cannot override the choice.
322 + routes.lan ? "--lan" : "--no-lan",
323 + ]);
324 + yield* Console.log(`${reason} Keep this command running:\n ${command}`);
325 + // A host wins over --lan and --no-lan, as it does in service.env.
326 + const shellHost = (yield* HostProcess.Environment).T3CODE_HOST;
327 + if (shellHost !== undefined) {
328 + yield* Console.warn(
329 + `T3CODE_HOST=${shellHost} in this shell overrides that choice. Unset it before you run the command.`,
330 + );
331 + }
332 + });
333 + let started = false;
334 + if (!before.service.supported) {
335 + yield* printServeCommand("Background service unavailable.");
336 + } else {
337 + if (newer) {
338 + yield* Console.log(`Keeping installed service version t3@${installedVersion}.`);
339 + }
340 + if (update && !interactive) {
341 + yield* Console.log("Updating T3 Code. Running agent turns will stop.");
342 + }
343 + const result = newer
344 + ? ({ changed: false } as const)
345 + : yield* CliService.reconcileService().pipe(
346 + Effect.catchTags({
347 + BootServicePrerequisiteError: (error) => Effect.succeed({ failed: error.message }),
348 + BootServiceUnsupportedError: (error) => Effect.succeed({ failed: error.message }),
349 + }),
350 + Effect.tapError(() => rollBack),
351 + );
352 + if ("failed" in result && before.service.installed) {
353 + // The old service still runs, so a foreground server would clash with it.
354 + yield* restoreServiceEnv;
355 + yield* Console.log(
356 + `Service setup failed: ${result.failed} Fix that, then run \`t3 up\` again.`,
357 + );
358 + } else if ("failed" in result) {
359 + yield* printServeCommand(`Service setup failed: ${result.failed}`);
360 + } else if (result.changed) {
361 + yield* Console.log(CliService.formatServiceChange(result));
362 + started = true;
363 + } else if (restart || (unlinkFailed && before.service.installed)) {
364 + const confirmed =
365 + restart ||
366 + !interactive ||
367 + (yield* Prompt.run(
368 + Prompt.Confirm({
369 + message:
370 + "The running service still has T3 Connect on. Restart it? Running agent turns will stop.",
371 + initial: true,
372 + }),
373 + ).pipe(Effect.catchTags({ QuitError: () => Effect.succeed(false) })));
374 + if (!confirmed) {
375 + yield* Console.log("Run `t3 service restart` to turn T3 Connect off.");
376 + } else {
377 + if (!interactive && !stopped) {
378 + yield* Console.log("Restarting T3 Code. Running agent turns will stop.");
379 + }
380 + const outcome = yield* service.restart.pipe(Effect.tapError(() => rollBack));
381 + if (outcome === "queued") {
382 + yield* Console.log("Restart queued. This session will disconnect.");
383 + }
384 + if (outcome === "skipped") {
385 + yield* Console.log(
386 + "The installed service runs another T3 home, so it was not restarted. Pass its --base-dir.",
387 + );
388 + }
389 + started = outcome === "restarted";
390 + }
391 + }
392 + }
393 + if (started && routes.connect && !current.connect) yield* waitForReachability();
394 +
395 + const after = yield* readSetup();
396 + yield* Console.log(
397 + // From what took effect: a failed service step can undo a choice.
398 + `\nThis machine\n${formatSetup(after)}\n\n${formatNextSteps(
399 + { connect: after.connect === true, lan: after.lan },
400 + after.service.installed,
401 + )}`,
402 + );
403 +});
404 +
405 +export const upCommand = Command.make("up", {
406 + ...projectLocationFlags,
407 + connect: Flag.Boolean("connect").pipe(
408 + Flag.withDescription(
409 + "Allow access through T3 Connect with your T3 account. Turn off with --no-connect.",
410 + ),
411 + Flag.optional,
412 + ),
413 + lan: Flag.Boolean("lan").pipe(
414 + Flag.withDescription(
415 + "Allow LAN and tailnet connections. Anyone there can reach the port; a pairing code is the only lock. Turn off with --no-lan.",
416 + ),
417 + Flag.optional,
418 + ),
419 + yes: Flag.Boolean("yes").pipe(
420 + Flag.withDescription(
421 + "Ask nothing. Keep the access settings; a new machine gets T3 Connect. A restart stops running agent turns.",
422 + ),
423 + Flag.withDefault(false),
424 + ),
425 + headless: headlessFlag,
426 +}).pipe(
427 + Command.withShortDescription("Set up remote access and the T3 Code background service."),
428 + Command.withDescription(
429 + "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.",
430 + ),
431 + Command.withExamples([
432 + { command: "t3 up", description: "Choose remote access." },
433 + { command: "t3 up --connect", description: "Turn on T3 Connect. Keep other settings." },
434 + { command: "t3 up --lan", description: "Allow LAN access with pairing codes." },
435 + { command: "t3 up --no-lan", description: "Stop LAN access." },
436 + { command: "t3 up --yes", description: "Take the defaults with no questions." },
437 + { command: "t3 status --json", description: "Read the settings from a script." },
438 + ]),
439 + Command.withHandler((flags) => runCloudCommand(flags, setUp(flags), { quietLogs: true })),
440 +);
441 +
442 +export const connectCommand = Command.make("connect", {
443 + ...projectLocationFlags,
444 + headless: headlessFlag,
445 +}).pipe(
446 + Command.withDescription("Set up T3 Connect for this machine. Same as `t3 up --connect`."),
447 + Command.withHandler((flags) =>
448 + runCloudCommand(
449 + flags,
450 + setUp({ ...flags, connect: Option.some(true), lan: Option.none(), yes: false }),
451 + { quietLogs: true },
452 + ),
453 + ),
454 + Command.withSubcommands(connectSubcommands),
455 +);
456 +
457 +/** `t3 status --json`, for scripts and agents. */
458 +const setupJson = (setup: Setup) =>
459 + JSON.stringify(
460 + {
461 + service: {
462 + supported: setup.service.supported,
463 + installed: setup.service.installed,
464 + installedVersion: setup.service.installedVersion ?? null,
465 + },
466 + connect:
467 + setup.connect === null ? null : { enabled: setup.connect, revoked: setup.connectRevoked },
468 + lan: {
469 + enabled: setup.lan,
470 + inheritedDefault: setup.lanFromOldDefault,
471 + hostOverride: setup.host ?? null,
472 + },
473 + },
474 + null,
475 + 2,
476 + );
477 +
478 +export const statusCommand = Command.make("status", {
479 + ...projectLocationFlags,
480 + json: Flag.Boolean("json").pipe(
481 + Flag.withDescription("Print the settings as JSON. Does not test connections."),
482 + Flag.withDefault(false),
483 + ),
484 +}).pipe(
485 + Command.withDescription("Show service setup and remote access settings."),
486 + Command.withExamples([
487 + { command: "t3 status", description: "Show the settings." },
488 + { command: "t3 status --json", description: "Print them for scripts and agents." },
489 + ]),
490 + Command.withHandler(
491 + Effect.fn("cli.status")(function* (flags) {
492 + const config = yield* resolveCliAuthConfig(flags, yield* GlobalFlag.LogLevel, {
493 + quietLogs: flags.json,
494 + });
495 + // Only what readSetup reads: no database, unlike the T3 Connect commands.
496 + const setup = yield* readSetup().pipe(
497 + Effect.provide(
498 + Layer.merge(CliService.layer(config), ServerSecretStore.layer).pipe(
499 + Layer.provideMerge(ServerConfig.layer(config)),
500 + ),
501 + ),
502 + );
503 + yield* Console.log(
504 + flags.json
505 + ? setupJson(setup)
506 + : `This machine\n${formatSetup(setup)}\n\nChange access: \`t3 up\`.`,
507 + );
508 + }),
509 + ),
510 +);
docs/user/background-service.md
+22 -15
@@ -8,13 +8,15 @@ to keep a terminal open.
8 Install the `t3` CLI first ([Install T3 Code](./install.md#command-line)), then
9 run these commands on the machine that will host T3 Code:
10
11 -| Task | Command |
12 -| ------------------------------- | ---------------------- |
13 -| Install and start | `t3 service install` |
14 -| Inspect status and log location | `t3 service status` |
15 -| Move to a newer release | `t3 update` |
16 -| Restart | `t3 service restart` |
17 -| Stop and remove from startup | `t3 service uninstall` |
11 +| Task | Command |
12 +| ------------------------------------- | ---------------------- |
13 +| Set up access from your other devices | `t3 up` |
14 +| See how your other devices reach it | `t3 status` |
15 +| Install and start | `t3 service install` |
16 +| Inspect status and log location | `t3 service status` |
17 +| Move to a newer release | `t3 update` |
18 +| Restart | `t3 service restart` |
19 +| Stop and remove from startup | `t3 service uninstall` |
20
21 Uninstalling the service leaves your projects, threads, and settings intact.
22 Running `t3 service install` again repairs a service that `t3 service status`
@@ -42,13 +44,18 @@ under T3 home. Pass `--yes` from a script.
44
45 ## Local network access
46
45 -The service listens on your local network and Tailscale addresses, so the
46 -desktop and mobile apps on the same network connect directly instead of through
47 -T3 Connect. The hosted web app at app.t3.codes stays on T3 Connect, because
48 -browsers block plain HTTP from an HTTPS page. The service does not answer on
49 -public addresses, and every device still needs to pair or sign in. To keep the service reachable from this machine only, set
50 -`T3CODE_HOST=127.0.0.1` in `service.env` (below). Any `T3CODE_HOST` value
51 -replaces this default.
47 +A new service answers only on this machine. Other devices reach it through
48 +T3 Connect, or directly once you choose the local network in `t3 up` (or run
49 +`t3 up --lan`, which sets `T3CODE_LAN=true` in `service.env`). It then listens on
50 +your local network and Tailscale addresses, so the desktop and mobile apps on
51 +the same network connect directly instead of through T3 Connect. It still does
52 +not answer on public addresses. Anyone on the same network can reach the port,
53 +so a pairing code is all that keeps them out. The hosted web app at app.t3.codes
54 +stays on T3 Connect, because browsers block plain HTTP from an HTTPS page.
55 +
56 +A service installed before `T3CODE_LAN` existed keeps listening on the local
57 +network. `t3 status` says so, and `t3 up --no-lan` turns it off. Any
58 +`T3CODE_HOST` value replaces this setting.
59
60 ## Configure the service environment
61
@@ -91,7 +98,7 @@ enabled, or keep `t3 serve` running in a terminal. Minimize the desktop app rath
98 than closing its last window, which stops its local server. Linking T3 Connect
99 does not configure automatic startup at Windows sign-in.
100
94 -T3 Connect can offer service installation during setup, but the two are managed
101 +`t3 up` installs the service when you set up T3 Connect, but the two are managed
102 separately. Signing out of T3 Connect does not stop or uninstall the service.
103
104 ## Keep the server responsive when agents use all memory
docs/user/faq.md
+2 -2
@@ -13,7 +13,7 @@ Bring your own: Claude Code, Codex, Cursor, Grok Build, OpenCode, Google Antigra
13 We were inspired by the Codex desktop app, Conductor, Claude Desktop, and Cursor Glass, but none met our bar. What you get:
14
15 - Bring your own sub. Claude, Codex, and whatever else you already have installed.
16 -- Best in class remote. Run `npx t3 connect` on any box and drive it from anywhere.
16 +- Best in class remote. Run `npx t3 up` on any box and drive it from anywhere.
17 - Best in class mobile app.
18 - Truly 100% open source. If we go the wrong direction, fork it.
19
@@ -37,7 +37,7 @@ T3 Code drives Claude through Anthropic's Agent SDK. I confirmed it's a real bug
37
38 ## How do I use T3 Code remotely?
39
40 -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)
40 +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)
41
42 ## How do I use T3 Code on my phone?
43
docs/user/install.md
+1
@@ -29,6 +29,7 @@ line to add. Set `T3CODE_CHANNEL=nightly` to install the nightly train, or
29 | ------------------------------------------------ | ----------------------------------------------------------------------- |
30 | Start the server and open the web app | `t3` |
31 | Start the server without a browser | `t3 serve` |
32 +| Use it from your other devices | `t3 up` ([details](./remote-access.md)) |
33 | Keep it running in the background (macOS, Linux) | `t3 service install` ([details](./background-service.md)) |
34 | Move to the newest release | `t3 update` |
35 | Reclaim database space | `t3 doctor` ([details](./background-service.md#reclaim-database-space)) |
docs/user/remote-access.md
+33 -13
@@ -12,17 +12,20 @@ Sharing & access**, sign in, and enable **T3 Connect** for that environment.
12 For a command-line host, run:
13
14 ```bash
15 -t3 connect
15 +t3 up
16 ```
17
18 -Follow the sign-in instructions. On Linux and macOS, setup offers a
19 -[background service](./background-service.md); if you decline it, start the
20 -server with `t3 serve`.
18 +It asks how your other devices reach the machine: T3 Connect, the local network,
19 +or both. Choose T3 Connect and follow the sign-in instructions. On Linux and
20 +macOS, it then runs T3 Code as a [background service](./background-service.md).
21 +`t3 connect` is the same as `t3 up --connect`. Run `t3 up` again to change your
22 +choice, and `t3 status` to see it.
23
22 -The background service is not available on Windows. Keep the desktop app running
23 -with its local environment enabled, or keep `t3 serve` running in a terminal.
24 -Closing the desktop app's last window stops its local server. Saving your
25 -sign-in alone does not start a server or make the machine reachable.
24 +The background service is not available on Windows, so there `t3 up` prints the
25 +`t3 serve` command to keep running in a terminal. You can also keep the desktop
26 +app running with its local environment enabled. Closing the desktop app's last
27 +window stops its local server. Saving your sign-in alone does not start a server
28 +or make the machine reachable.
29
30 On your other device, sign in to the same T3 Connect account and choose the
31 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
39 previous credential expires. A failed renewal affects that request; it does not
40 disconnect an otherwise healthy conversation.
41
42 +### Scripts and agents
43 +
44 +`t3 up` asks nothing when you name a choice: `--connect`, `--lan`, or their
45 +`--no-` forms. Choices you do not name keep their settings, and `--yes` takes
46 +the defaults. Without a terminal:
47 +
48 +- T3 Connect sign-in prints a URL and a code. Approve it on any device.
49 +- A needed restart runs without asking, and stops running agent turns.
50 +- With nothing set up and no choice named, `t3 up` stops and names the flags.
51 +
52 +`t3 status --json` prints the settings. `t3 up --help` lists every flag with
53 +examples.
54 +
55 ### More machines with T3 Chat
56
57 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
72 then create a pairing link using an address the other device can reach. Changing
73 network access restarts the desktop app. You can turn it off in the same place.
74
59 -For a command-line host, replace `<private-ip>` with the host's LAN or tailnet
60 -address:
75 +For a command-line host, choose the local network in `t3 up`, or run:
76
77 ```bash
63 -t3 serve --host <private-ip>
78 +t3 up --lan
79 ```
80
81 +For a server in a terminal, run `t3 serve --lan`. Either way, T3 Code then
82 +accepts connections from your local network and tailnet, so a pairing code is
83 +all that keeps other devices on them out.
84 +
85 If a server is already running, generate a fresh link without restarting it:
86
87 ```bash
@@ -105,8 +124,9 @@ machine's current LAN and Tailscale addresses and adds them as routes, so
124 pairing once through T3 Connect is enough to use the LAN at home. When the
125 machine's LAN address changes, for example after it joins another Wi-Fi network,
126 the learned route follows it. The machine must allow network access for its LAN
108 -address to be learned. The [background service](./background-service.md#local-network-access)
109 -allows it on private networks by default. You can reorder a learned route, but not remove it; it
127 +address to be learned: **Network access** in the desktop app, or the
128 +[local network](./background-service.md#local-network-access) choice in `t3 up`.
129 +You can reorder a learned route, but not remove it; it
130 goes away with the route it was learned through, or when the machine stops
131 reporting that address.
132
scripts/install.ps1
+1 -1
@@ -230,5 +230,5 @@ if ($interactive) { [Console]::Error.Write("`r$esc[2K") }
230 if (($env:PATH -split ";") -notcontains $binDir) {
231 Write-Host " Add $binDir to your PATH, then run ${bold}t3$reset.`n"
232 } else {
233 - Write-Host " Run ${bold}t3$reset to get started.`n"
233 + Write-Host " Run ${bold}t3$reset to use T3 Code here, or ${bold}t3 up$reset to use it from your other devices.`n"
234 }
scripts/install.sh
+1 -1
@@ -238,6 +238,6 @@ grep -qxF "$launcher" "$launchers" 2>/dev/null || printf '%s\n' "$launcher" >> "
238 if "$interactive"; then printf '\r\033[2K' >&2; fi
239 printf ' %sInstalled T3 Code %s%s\n\n' "$green" "$version" "$reset" >&2
240 case ":${PATH}:" in
241 - *":${bin_dir}:"*) printf ' Run %st3%s to get started.\n\n' "$bold" "$reset" ;;
241 + *":${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" ;;
242 *) printf ' Add %s to your PATH, then run %st3%s.\n\n' "$bin_dir" "$bold" "$reset" ;;
243 esac