feat(cli): npx t3 now steers you to an installed t3 #25417
main fromfeat/steer-off-npxopened View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- packages/shared/src/shell.ts lines 981 to 983OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -965,3 +965,19 @@965965 ? { ...baselinePatch, ...profiledPatch }966966 : baselinePatch;967967 });968+969+/**970+ * A command to paste that puts `directory` on PATH for new zsh, bash, or fish terminals. Undefined971+ * on Windows (a pasted command would flatten the registry PATH's `%VAR%` entries), for other972+ * shells, or for unsafe paths.973+ */974+export function pathSetupCommand(input: {975+ readonly directory: string;976+ readonly home: string;977+ readonly shell: string | undefined;978+ readonly platform: NodeJS.Platform;979+}): string | undefined {980+ if (input.platform === "win32") return undefined;981+ const directory = input.directory.startsWith(`${input.home}/`)982+ ? `$HOME${input.directory.slice(input.home.length)}`983+ : input.directory;
- packages/shared/src/shell.ts lines 988 to 990OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -967,0 +970,21 @@970+ * A command to paste that puts `directory` on PATH for new zsh, bash, or fish terminals. Undefined971+ * on Windows (a pasted command would flatten the registry PATH's `%VAR%` entries), for other972+ * shells, or for unsafe paths.973+ */974+export function pathSetupCommand(input: {975+ readonly directory: string;976+ readonly home: string;977+ readonly shell: string | undefined;978+ readonly platform: NodeJS.Platform;979+}): string | undefined {980+ if (input.platform === "win32") return undefined;981+ const underHome = input.directory.startsWith(`${input.home}/`);982+ const rest = underHome ? input.directory.slice(input.home.length) : input.directory;983+ if (!/^[\w./-]+$/.test(rest)) return undefined;984+ const directory = underHome ? `$HOME${rest}` : rest;985+ const shell = input.shell?.split("/").pop();986+ if (shell === "fish") return `fish_add_path ${directory}`;987+ const line = `export PATH="${directory}:$PATH"`;988+ if (shell === "zsh") return `echo '${line}' >> ~/.zshrc`;989+ if (shell === "bash") {990+ return `echo '${line}' >> ${input.platform === "darwin" ? "~/.bash_profile" : "~/.bashrc"}`;packages/shared/src/shell.ts lines 990 to 990OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -967,0 +970,21 @@970+ * A command to paste that puts `directory` on PATH for new zsh, bash, or fish terminals. Undefined971+ * on Windows (a pasted command would flatten the registry PATH's `%VAR%` entries), for other972+ * shells, or for unsafe paths.973+ */974+export function pathSetupCommand(input: {975+ readonly directory: string;976+ readonly home: string;977+ readonly shell: string | undefined;978+ readonly platform: NodeJS.Platform;979+}): string | undefined {980+ if (input.platform === "win32") return undefined;981+ const underHome = input.directory.startsWith(`${input.home}/`);982+ const rest = underHome ? input.directory.slice(input.home.length) : input.directory;983+ if (!/^[\w./-]+$/.test(rest)) return undefined;984+ const directory = underHome ? `$HOME${rest}` : rest;985+ const shell = input.shell?.split("/").pop();986+ if (shell === "fish") return `fish_add_path ${directory}`;987+ const line = `export PATH="${directory}:$PATH"`;988+ if (shell === "zsh") return `echo '${line}' >> ~/.zshrc`;989+ if (shell === "bash") {990+ return `echo '${line}' >> ${input.platform === "darwin" ? "~/.bash_profile" : "~/.bashrc"}`;
- apps/server/src/cli/install.ts lines 109 to 111OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +91,21 @@91+ yield* fs.symlink(executable, staging).pipe(92+ Effect.andThen(fs.rename(staging, link)),93+ Effect.tapError(() => fs.remove(staging, { force: true }).pipe(Effect.ignore)),94+ Effect.mapError(failed(`Could not link ${link}.`)),95+ );96+ }97+98+ // Pruning keeps what recorded launchers point at; a background service cannot see binDir otherwise.99+ const recorded = path.join(100+ yield* fs.realPath(binDir).pipe(Effect.orElseSucceed(() => binDir)),101+ name,102+ );103+ const launchersFile = path.join(runtimeDir, "launchers");104+ const launchers = yield* fs.readFileString(launchersFile).pipe(Effect.orElseSucceed(() => ""));105+ if (!launchers.split(/\r?\n/).includes(recorded)) {106+ yield* fs.writeFileString(launchersFile, `${recorded}\n`, { flag: "a" }).pipe(Effect.ignore);107+ }108+109+ const same = (entry: string) =>110+ windows ? entry.toLowerCase() === binDir.toLowerCase() : entry === binDir;111+ const onPath = (environment.PATH ?? environment.Path ?? "").split(windows ? ";" : ":").some(same);
- apps/server/src/cli/pair.ts line 75OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -72,4 +72,4 @@7272 ...(this.inLinkedWorktree7373 ? ["In a linked worktree, pass --base-dir to pair with a server outside it."]7474 : []),75- "Start one with `npx t3 serve`, or connect this machine with T3 Connect: `npx t3 connect`.",75+ "Start one with `t3 serve`, or connect this machine with T3 Connect: `t3 connect`.",apps/web/src/components/onboarding/WelcomeWizard.tsx line 533OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -529,4 +530,4 @@529530 <p className="text-sm text-muted-foreground">530531 Run this on each computer you want to connect.531532 </p>532- <CommandBlock command="npx t3 connect" className="mt-3" />533+ <CommandBlock command={t3InstallCommand(navigator.platform)} className="mt-3" />apps/web/src/components/onboarding/WelcomeWizard.tsx line 534OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -529,4 +530,5 @@529530 <p className="text-sm text-muted-foreground">530531 Run this on each computer you want to connect.531532 </p>532- <CommandBlock command="npx t3 connect" className="mt-3" />533+ <CommandBlock command={t3InstallCommand(navigator.platform)} className="mt-3" />534+ <CommandBlock command="t3 connect" className="mt-2" />apps/web/src/components/settings/CliCommandSettingsRow.tsx line 46OutdatedResolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -42,4 +42,5 @@4242 ? "Run T3 Code's CLI as `t3` from any terminal."4343 : state.onPath4444 ? `Installed at ${state.installedPath}. Open a new terminal to use it.`45- : `Installed at ${state.installedPath}, which is not on your PATH yet. Add its folder to your PATH to run \`t3\`.`;45+ : state.pathCommand46+ ? `Installed at ${state.installedPath}, which is not on your PATH yet. Run \`${state.pathCommand}\`, then open a new terminal.`
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- scripts/install.ps1 lines 222 to 222OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -216,3 +216,7 @@216216 Step "Setting up the t3 command..."217217 New-Item -ItemType Directory -Force -Path $binDir | Out-Null218218 $shim = Join-Path $binDir "t3.cmd"219+# Replace only a shim that runs a version in this home; never the desktop app's or another t3.220+if (Test-Path $shim) {221+ $existingTarget = ""222+ foreach ($line in Get-Content $shim) {
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- @@ -101,4 +108,9 @@101108 export function runCli() {102109 extendConnectionAttemptTimeout();103110 keepOutboundFetchOnHttp1();104- Command.run(cli, { version: packageJson.version }).pipe(111+ offerCliInstall({112+ args: process.argv.slice(2),113+ interactive: Boolean(process.stdin.isTTY && process.stdout.isTTY),114+ foreground: inTerminalForeground,115+ confirm: confirmCliInstall,116+ }).pipe(apps/server/src/cli/install.ts lines 22 to 25Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +1,20 @@1+import * as HostProcess from "@t3tools/shared/HostProcess";2+import { pathSetupCommand } from "@t3tools/shared/shell";3+import * as Console from "effect/Console";4+import * as Duration from "effect/Duration";5+import * as Effect from "effect/Effect";6+import * as FileSystem from "effect/FileSystem";7+import * as Option from "effect/Option";8+import * as Path from "effect/Path";9+import * as Schema from "effect/Schema";10+import { Command, Prompt } from "effect/cli";11+import * as ChildProcess from "effect/process/ChildProcess";12+import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";13+14+import packageJson from "../../package.json" with { type: "json" };15+import { launcherOwnsVersionsDir, windowsShimTarget } from "../cloud/pinnedRuntime.ts";16+import { detectCliRunner, resolveCliCommand, resolveEntryPath } from "./invocation.ts";17+18+export class CliInstallError extends Schema.TaggedError<CliInstallError>()("CliInstallError", {19+ reason: Schema.String,20+}) {apps/server/src/cli/pair.ts lines 300 to 301OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -290,4 +294,8 @@290294 } satisfies DiscoveredPairTarget;291295 }292296 }293- return yield* new NoRunningServerError({ checkedStatePaths, inLinkedWorktree });297+ return yield* new NoRunningServerError({298+ checkedStatePaths,299+ inLinkedWorktree,300+ serveCommand: yield* resolveCliCommand("serve"),301+ connectCommand: yield* resolveCliCommand("connect"),apps/server/src/cli/uninstall.test.ts line 42OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -34,3 +34,9 @@3434 assert.isUndefined(yield* findOwnedLauncher({ launchedAs: undefined, versionsDir }));3535 }).pipe(Effect.scoped, Effect.provideService(HostProcess.Platform, "linux")),3636 );37+38+ it.effect("also finds recorded launchers that npx did not start from", () =>39+ Effect.gen(function* () {40+ const fs = yield* FileSystem.FileSystem;41+ const path = yield* Path.Path;42+ const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-uninstall-" });docs/user/updating.md lines 99 to 100OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -96,4 +96,5 @@96969797 If you run the server with `npx` rather than an installed `t3`, there is9898 nothing to update on the host: stop the server and relaunch it as99-`npx t3@<client-version>` with the same subcommand and options.99+`T3CODE_USE_NPM=1 npx t3@<client-version>` with the same subcommand and100+options. `T3CODE_USE_NPM=1` keeps npx from running a newer installed `t3`.scripts/npm-launcher/t3.mjs lines 258 to 265OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -147,6 +255,11 @@147255 for (const signal of ["SIGINT", "SIGTERM", "SIGHUP"]) {148256 process.on(signal, () => (ipc || signal !== "SIGINT") && child.kill(signal));149257 }150- child.on("error", (error) => fail(error));258+ child.on("error", (error) => finish(() => (fallback ? fallback() : fail(error))));151259 child.on("exit", (code, signal) =>152- process.exit(code ?? 128 + (os.constants.signals[signal] || 1)),260+ finish(() =>261+ // 126 and 127 mean the shell could not run it; t3 itself never exits with them.262+ fallback && (code === 126 || code === 127)263+ ? fallback()264+ : process.exit(code ?? 128 + (os.constants.signals[signal] || 1)),265+ ),
- @@ -230,7 +235,21 @@235+ "$versions_dir"/* | "$real_versions_dir"/* | "${t3_home}/bin/t3") ;;236+ *) fail "another t3 is already at ${bin_dir}/t3. Remove it and run this again, or run ${target_dir}/t3 directly." ;;237+ esac238+fi230239 ln -sfn "${target_dir}/t3" "${bin_dir}/t3"231240 # Pruning keeps what this launcher points at; a background service cannot see bin_dir otherwise.232241 launcher="$(CDPATH='' cd -P -- "$bin_dir" && pwd)/t3"233242 launchers="${t3_home}/runtime/launchers"234243 grep -qxF "$launcher" "$launchers" 2>/dev/null || printf '%s\n' "$launcher" >> "$launchers"235244 if "$interactive"; then printf '\r\033[2K' >&2; fi236245 printf ' %sInstalled T3 Code %s%s\n\n' "$green" "$version" "$reset" >&2246+# A command to paste for zsh, Linux bash, or fish, like `t3 install` prints. macOS bash reads only247+# one of several startup files, so no single file is safe to change there.248+path_command=249+path_rest="$bin_dir"250+path_prefix=251+case "$bin_dir" in "$HOME"/*) path_rest="${bin_dir#"$HOME"}" path_prefix='$HOME' ;; esac252+case "$path_rest" in *[!A-Za-z0-9_./-]*) path_rest= ;; esac253+if [ -n "$path_rest" ]; then254+ path_line="export PATH=\"${path_prefix}${path_rest}:\$PATH\""255+ case "${SHELL##*/}" in
- apps/desktop/src/app/DesktopCliShim.test.ts lines 102 to 103Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -66,0 +81,21 @@81+ "while :; do sleep 0.05; done",82+ "",83+ ].join("\n"),84+ );85+ const piped = NodeChildProcess.spawnSync(shim, ["once"], {86+ encoding: "utf8",87+ input: "hello\n",88+ });89+ expect(piped.stdout).toBe("read: hello\n");90+ expect(piped.status).toBe(4);91+92+ const running = NodeChildProcess.spawn(shim, ["wait"], { stdio: ["pipe", "pipe", "inherit"] });93+ running.stdin.end("hi\n");94+ await new Promise<void>((resolve) =>95+ running.stdout.on("data", (chunk: Buffer) => chunk.includes("ready") && resolve()),96+ );97+ const exited = NodeEvents.EventEmitter.once(running, "exit");98+ running.kill("SIGTERM");99+ expect((await exited)[0]).toBe(143);100+ expect(NodeFS.existsSync(NodePath.join(root, "cli-got-term"))).toBe(true);101+ expect(NodeFS.existsSync(NodePath.join(root, "unmounted"))).toBe(true);apps/server/src/cli/install.test.ts lines 237 to 250OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +230,21 @@230+ yield* TestClock.adjust("30 seconds");231+ assert.isTrue(yield* Fiber.join(unanswered));232+ assert.isTrue(yield* fs.exists(declined));233+ assert.isFalse(yield* fs.exists(link));234+ }).pipe(Effect.scoped),235+ );236+237+ it("reads the terminal's foreground group from /proc and ps", () =>238+ Effect.sync(() => {239+ // The command name can hold spaces and parentheses.240+ const stat = (pgrp: number, tpgid: number) =>241+ `4242 (t3 (serve) x) S 100 ${pgrp} 100 34816 ${tpgid} 4194560 0 0`;242+ assert.isTrue(isForegroundProcStat(stat(4242, 4242)));243+ assert.isFalse(isForegroundProcStat(stat(4242, 4300)));244+ assert.isFalse(isForegroundProcStat(stat(4242, -1)));245+ assert.isFalse(isForegroundProcStat(""));246+ assert.isTrue(isForegroundPs(" 4242 4242\n"));247+ assert.isFalse(isForegroundPs(" 4300 4242\n"));248+ assert.isFalse(isForegroundPs(" -1 4242\n"));249+ assert.isFalse(isForegroundPs(""));250+ }));apps/server/src/cli/install.ts lines 97 to 103Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +66,21 @@66+ const link = path.join(binDir, name);67+ const failed = (reason: string) => (cause: unknown) => new CliInstallError({ reason, cause });68+69+ // Resolve fully so a link through a symlinked T3 home still counts as ours; a dangling one70+ // (a pruned version) falls back to its own text.71+ const current = windows72+ ? yield* fs.readFileString(link).pipe(Effect.map(windowsShimTarget), Effect.option)73+ : yield* fs.readLink(link).pipe(74+ Effect.flatMap((target) =>75+ fs.realPath(link).pipe(Effect.orElseSucceed(() => path.resolve(binDir, target))),76+ ),77+ Effect.option,78+ );79+ const occupied = Option.isSome(current) || (yield* fs.exists(link));80+ if (81+ occupied &&82+ !(83+ Option.isSome(current) &&84+ current.value !== undefined &&85+ launcherOwnsVersionsDir(path, versionsDir, current.value)86+ )@@ -216,3 +216,15 @@216216 Step "Setting up the t3 command..."217217 New-Item -ItemType Directory -Force -Path $binDir | Out-Null218218 $shim = Join-Path $binDir "t3.cmd"219+# Replace only a shim that runs a version in this home; never the desktop app's or another t3.220+if (Test-Path -LiteralPath $shim) {221+ $existingTarget = ""222+ # The shim is UTF-8 without a BOM; Windows PowerShell 5.1 reads files as ANSI by default.223+ foreach ($line in [System.IO.File]::ReadAllLines($shim, [System.Text.Encoding]::UTF8)) {224+ if ($line -match '^"([^"]+)"') { $existingTarget = $Matches[1]; break }225+ }226+ $ownedPrefix = $versionsDir.TrimEnd('\', '/') + [System.IO.Path]::DirectorySeparatorChar227+ if (-not $existingTarget.StartsWith($ownedPrefix, [System.StringComparison]::OrdinalIgnoreCase)) {228+ Fail "another t3 is already at $shim. Remove it and run this again, or run $(Join-Path $targetDir 't3.exe') directly."229+ }230+}
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XXL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/desktop/src/app/DesktopCliCommand.ts line 239OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -210,4 +236,4 @@210236 );211237 }212238 const onPath = pathEntries(process.env.PATH, ":");213- const candidates = unixCandidates(environment.homeDirectory, environment.platform);239+ const candidates = userCandidates(environment.homeDirectory);
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:XL
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XXL
- apps/web/src/components/onboarding/WelcomeWizard.tsx lines 1803 to 1804Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -1756,3 +1758,8 @@17561758 );17571759 }175817601761+/** The desktop app links `t3` on first launch; this puts its folder on PATH when it is not. */1762+function CliPathSetup() {1763+ const { state, busy, run } = useDesktopCliCommand();1764+ const setup = state?.pathSetup;1765+ if (!setup) return null;
- apps/desktop/src/app/DesktopCliCommand.ts line 400Resolvedby t3dotgg(GitHub profile, opens in a new tab)@@ -283,4 +349,11 @@283349 return yield* state;284350 }).pipe(Effect.withSpan("desktop.cliCommand.uninstall"));285351286- return DesktopCliCommand.of({ state, install, uninstall });352+ // One at a time, so Settings and onboarding cannot both append the line.353+ const addToPathPermit = yield* Semaphore.make(1);354+ const addToPath: DesktopCliCommand["Service"]["addToPath"] = Effect.gen(function* () {355+ const installed = yield* installedAt;356+ if (Option.isNone(installed)) return yield* fail("Install the t3 command first.");357+ const setup = startupLine(installed.value);358+ if (setup === undefined) return yield* fail("T3 Code cannot add t3 to this shell's PATH.");359+ if (!(yield* folderOnPath(installed.value)) && !(yield* hasLine(setup))) {
- scripts/npm-launcher/t3.mjs line 243OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -145 +223,21 @@223+ );224+ if (changed <= info.ctimeMs) {225+ found.push({ version: desktop, command: shim });226+ }227+ }228+ } catch {}229+ }230+ return found.sort((a, b) => compareVersions(b.version, a.version))[0];231+}232+233+function note(message) {234+ if (process.stderr.isTTY) process.stderr.write(`t3: ${message}\n`);235+}236+145237 async function main() {238+ const home = t3Home();239+ // Service IPC and signals must reach the child; terminal Ctrl-C already does, so do not forward SIGINT twice.240+ const ipc = process.send !== undefined;241+ // `install` links npm's copy itself; the desktop app's t3 cannot install itself.242+ const installed =243+ ipc || process.env.T3CODE_USE_NPM === "1" || process.argv[2] === "install"
Sign in to join this conversation.



macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed