@devries-cameron20 / t3code Mirror · read-only / commits / 3dc54f43df
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, 02:00 UTC

feat(desktop): a fresh install sets up the t3 command (#33153)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Theo Browne committed Nov 8, 2026 at 18:14 UTC 3dc54f43dfaf9f3fa7258c7cf65b63c5428a8c7c
18 files changed +529 -70
apps/desktop/src/app/DesktopApp.test.ts
+1
@@ -117,6 +117,7 @@ it.effect.each([false, true])(
117 Effect.provideService(DesktopShellEnvironment.DesktopShellEnvironment, {
118 installIntoProcess: Effect.succeed(true),
119 awaitDiscovery: Effect.succeed(true),
120 + awaitUserShellDiscovery: Effect.succeed(true),
121 updates: Stream.empty,
122 }),
123 Effect.provideService(DesktopAppSettings.DesktopAppSettings, {
apps/desktop/src/app/DesktopApp.ts
+13
@@ -15,6 +15,7 @@ import { installDesktopIpcHandlers } from "../ipc/DesktopIpcHandlers.ts";
15 import * as DesktopAppActivation from "./DesktopAppActivation.ts";
16 import * as DesktopAppIdentity from "./DesktopAppIdentity.ts";
17 import * as DesktopClerk from "./DesktopClerk.ts";
18 +import * as DesktopCliCommand from "./DesktopCliCommand.ts";
19 import * as DesktopApplicationMenu from "../window/DesktopApplicationMenu.ts";
20 import * as DesktopWindow from "../window/DesktopWindow.ts";
21 import * as PreviewPasskeys from "../preview/Passkeys.ts";
@@ -192,6 +193,18 @@ const bootstrap = Effect.gen(function* () {
193 );
194
195 yield* snapShot.initialize;
196 + // Only the user's own login shell PATH shows every t3 a new terminal runs; a fresh install has
197 + // no cached one. Without it, the command is left to Settings.
198 + const installCli = (yield* DesktopCliCommand.DesktopCliCommand).installOnFirstLaunch;
199 + yield* Effect.forkScoped(
200 + (yield* DesktopShellEnvironment.DesktopShellEnvironment).awaitUserShellDiscovery.pipe(
201 + Effect.flatMap((found) =>
202 + found || environment.platform === "win32"
203 + ? installCli
204 + : logBootstrapInfo("skipped installing the t3 command without the shell PATH"),
205 + ),
206 + ),
207 + );
208
209 if (!settings.localEnvironmentEnabled) {
210 yield* logBootstrapInfo("bootstrap skipping local environment (disabled in settings)");
apps/desktop/src/app/DesktopCliCommand.test.ts
+160 -13
@@ -24,6 +24,7 @@ const environmentFor = (
24 homeDirectory: input.home,
25 baseDir: input.baseDir,
26 stateDir: path.join(input.baseDir, "userdata"),
27 + desktopSettingsPath: path.join(input.baseDir, "userdata", "desktop-settings.json"),
28 serverRoot: "/opt/T3 Code/resources/app.asar",
29 appImagePath: Option.none(),
30 } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
@@ -48,21 +49,22 @@ const commandIn = (
49 DesktopEnvironment.DesktopEnvironment,
50 environmentFor(path, { ...input, baseDir }),
51 ),
51 - Effect.provideService(HostProcess.Environment, input.env ?? { PATH: "" }),
52 + Effect.provideService(HostProcess.Environment, input.env ?? { PATH: "", SHELL: "/bin/zsh" }),
53 );
54 return yield* spawner
55 ? make.pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner))
56 : make;
57 });
58
58 -const fakePowerShell = (initial: string) => {
59 +/** `inherited` stands in for the app's own environment, which `extendEnv` passes on. */
60 +const fakePowerShell = (initial: string, inherited: Record<string, string> = {}) => {
61 const registry = { path: initial, failReads: false, writes: 0 };
62 const spawner = ChildProcessSpawner.make((command) =>
63 Effect.sync(() => {
64 const { options } = command as unknown as {
63 - readonly options: { readonly env?: Record<string, string> };
65 + readonly options: { readonly env?: Record<string, string>; readonly extendEnv?: boolean };
66 };
65 - const env = options.env ?? {};
67 + const env = { ...(options.extendEnv ? inherited : {}), ...options.env };
68 let exitCode = 0;
69 let stdout = "";
70 if (env.T3_SET === "1") {
@@ -94,10 +96,11 @@ const fakePowerShell = (initial: string) => {
96 it.layer(NodeServices.layer)("DesktopCliCommand", (it) => {
97 it.effect("links the launcher onto PATH and removes only that link", () =>
98 Effect.gen(function* () {
99 + const env: NodeJS.ProcessEnv = { PATH: "", SHELL: "/bin/zsh" };
100 const fs = yield* FileSystem.FileSystem;
101 const path = yield* Path.Path;
102 const home = yield* fs.makeTempDirectoryScoped();
100 - const command = yield* commandIn({ home });
103 + const command = yield* commandIn({ home, env });
104 const link = path.join(home, ".local", "bin", "t3");
105
106 expect(yield* command.state).toEqual({
@@ -106,24 +109,66 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => {
109 onPath: false,
110 launcherPath: null,
111 });
112 + yield* command.installOnFirstLaunch;
113 + expect((yield* command.state).installedPath).toBe(link);
114 const installed = yield* command.install;
115 expect(installed.installedPath).toBe(link);
116 expect(installed.launcherPath).toBe(path.join(home, ".t3", "bin", "t3"));
117 + expect(installed.pathSetup).toEqual({ file: "~/.zshrc", added: false });
118 expect(yield* fs.readLink(link)).toBe(path.join(home, ".t3", "bin", "t3"));
119 expect((yield* command.install).installedPath).toBe(link);
120
121 + // Add to PATH appends one line, once, and keeps a final line with no newline intact.
122 + const zshrc = path.join(home, ".zshrc");
123 + yield* fs.writeFileString(zshrc, "# mine");
124 + // A folder already on PATH needs nothing.
125 + env.PATH = path.join(home, ".local", "bin");
126 + yield* command.addToPath;
127 + expect(yield* fs.readFileString(zshrc)).toBe("# mine");
128 + env.PATH = "";
129 + yield* Effect.all([command.addToPath, command.addToPath], { concurrency: "unbounded" });
130 + expect((yield* command.addToPath).pathSetup).toEqual({ file: "~/.zshrc", added: true });
131 + expect(yield* fs.readFileString(zshrc)).toBe(
132 + '# mine\n# Added by T3 Code\nexport PATH="$PATH:$HOME/.local/bin"\n',
133 + );
134 +
135 expect((yield* command.uninstall).installedPath).toBeNull();
136 expect(yield* fs.exists(link)).toBe(false);
137 expect(yield* fs.exists(path.join(home, ".t3", "bin", "t3"))).toBe(true);
138 + // Removed stays removed: first launch never installs again.
139 + yield* command.installOnFirstLaunch;
140 + expect(yield* fs.exists(link)).toBe(false);
141 +
142 + // Also when first launch was put off (no shell PATH yet) and the user removed it meanwhile.
143 + const laterHome = yield* fs.makeTempDirectoryScoped();
144 + const later = yield* commandIn({ home: laterHome, env });
145 + yield* later.install;
146 + yield* later.uninstall;
147 + yield* later.installOnFirstLaunch;
148 + expect(yield* fs.exists(path.join(laterHome, ".local", "bin", "t3"))).toBe(false);
149 +
150 + // An app that ran before left its settings or launcher. Its user may have removed t3 or
151 + // chosen another, so first launch leaves it to Settings, where Install still works.
152 + for (const left of ["userdata/desktop-settings.json", "bin/t3"]) {
153 + const upgradedHome = yield* fs.makeTempDirectoryScoped();
154 + const leftFile = path.join(upgradedHome, ".t3", left);
155 + yield* fs.makeDirectory(path.dirname(leftFile), { recursive: true });
156 + yield* fs.writeFileString(leftFile, `#!/bin/sh\n# ${DesktopCliShim.MARKER}\n`);
157 + const upgraded = yield* commandIn({ home: upgradedHome, env });
158 + yield* upgraded.installOnFirstLaunch;
159 + const upgradedLink = path.join(upgradedHome, ".local", "bin", "t3");
160 + expect(yield* fs.exists(upgradedLink)).toBe(false);
161 + expect((yield* upgraded.install).installedPath).toBe(upgradedLink);
162 + }
163 }).pipe(Effect.scoped),
164 );
165
166 it.effect("never replaces or removes a t3 it did not create", () =>
167 Effect.gen(function* () {
168 + const env: NodeJS.ProcessEnv = { PATH: "", SHELL: "/bin/zsh" };
169 const fs = yield* FileSystem.FileSystem;
170 const path = yield* Path.Path;
171 const home = yield* fs.makeTempDirectoryScoped();
126 - const env: NodeJS.ProcessEnv = { PATH: "" };
172 const command = yield* commandIn({ home, env });
173 const theirs = path.join(home, ".local", "bin", "t3");
174 yield* fs.makeDirectory(path.dirname(theirs), { recursive: true });
@@ -132,11 +177,24 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => {
177 yield* fs.symlink(path.join(home, "gone"), path.join(home, "bin", "t3"));
178
179 const error = yield* Effect.flip(command.install);
135 - expect(error.message).toContain("Another t3 command is already installed");
180 + expect(error.message).toContain("Another t3 command is already in");
181 yield* command.uninstall;
182 expect(yield* fs.readFileString(theirs)).toBe("npm's t3\n");
183 expect(yield* fs.readLink(path.join(home, "bin", "t3"))).toBe(path.join(home, "gone"));
184
185 + // A fresh install beside someone else's t3 (even off PATH or a dangling link) adds no second
186 + // t3 in ~/bin.
187 + for (const dangling of [false, true]) {
188 + const besideHome = yield* fs.makeTempDirectoryScoped();
189 + const other = path.join(besideHome, ".local", "bin", "t3");
190 + yield* fs.makeDirectory(path.dirname(other), { recursive: true });
191 + yield* dangling
192 + ? fs.symlink(path.join(besideHome, "gone"), other)
193 + : fs.writeFileString(other, "npm's t3\n");
194 + yield* (yield* commandIn({ home: besideHome })).installOnFirstLaunch;
195 + expect(yield* fs.exists(path.join(besideHome, "bin", "t3"))).toBe(false);
196 + }
197 +
198 const launcher = path.join(home, ".t3", "bin", "t3");
199 yield* fs.writeFileString(launcher, "npm's t3\n");
200 env.PATH = path.dirname(launcher);
@@ -149,40 +207,102 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => {
207
208 it.effect("finds and removes a link left by a previous T3 home", () =>
209 Effect.gen(function* () {
210 + const env: NodeJS.ProcessEnv = { PATH: "", SHELL: "/bin/zsh" };
211 const fs = yield* FileSystem.FileSystem;
212 const path = yield* Path.Path;
213 const home = yield* fs.makeTempDirectoryScoped();
155 - const before = yield* commandIn({ home, baseDir: path.join(home, "old-t3") });
214 + const before = yield* commandIn({ home, baseDir: path.join(home, "old-t3"), env });
215 const link = (yield* before.install).installedPath;
216
158 - const after = yield* commandIn({ home, baseDir: path.join(home, "new-t3") });
159 - expect((yield* after.state).installedPath).toBe(link);
217 + const after = yield* commandIn({ home, baseDir: path.join(home, "new-t3"), env });
218 + // A first launch leaves another home's command alone; only Install takes it over.
219 + yield* after.installOnFirstLaunch;
220 + expect(yield* fs.readLink(link!)).toBe(path.join(home, "old-t3", "bin", "t3"));
221 + // On PATH, it runs the other home's launcher. Settings offers Install (not Remove, and not
222 + // "another t3 runs first"), which updates that link in place.
223 + env.PATH = path.dirname(link!);
224 + expect(yield* after.state).toMatchObject({ installedPath: null, onPath: false });
225 + expect((yield* after.state).shadowedBy).toBeUndefined();
226 + env.PATH = "";
227 + // Off PATH, Add to PATH would expose the other home's command, not this one.
228 + expect((yield* after.state).pathSetup).toBeUndefined();
229 + yield* Effect.flip(after.addToPath);
230 + expect(yield* fs.exists(path.join(home, ".zshrc"))).toBe(false);
231 + // Behind another t3 the install fails, and the old link still works.
232 + const shadow = path.join(home, "shadow");
233 + yield* fs.makeDirectory(shadow);
234 + yield* fs.writeFileString(path.join(shadow, "t3"), "#!/bin/sh\n", { mode: 0o755 });
235 + env.PATH = shadow;
236 + yield* Effect.flip(after.install);
237 + expect(yield* fs.readLink(link!)).toBe(path.join(home, "old-t3", "bin", "t3"));
238 + // Install takes it over, also with its folder first on PATH.
239 + env.PATH = path.dirname(link!);
240 expect((yield* after.install).installedPath).toBe(link);
241 expect(yield* fs.readLink(link!)).toBe(path.join(home, "new-t3", "bin", "t3"));
242 + env.PATH = "";
243 yield* after.uninstall;
244 expect(yield* fs.exists(path.join(home, ".local", "bin", "t3"))).toBe(false);
245 expect(yield* fs.exists(path.join(home, "bin", "t3"))).toBe(false);
246 +
247 + // A folder already on PATH wins, even written with a trailing slash.
248 + env.PATH = `${path.join(home, "bin")}/`;
249 + expect((yield* after.install).installedPath).toBe(path.join(home, "bin", "t3"));
250 +
251 + // An old link of ours is updated where it is, not moved to a folder that may be off PATH.
252 + yield* fs.writeFileString(path.join(home, "bin", "t3.staging"), "mine");
253 + yield* fs.remove(path.join(home, "bin", "t3"));
254 + yield* fs.symlink(path.join(home, "old-t3", "bin", "t3"), path.join(home, "bin", "t3"));
255 + env.PATH = "";
256 + expect((yield* after.install).installedPath).toBe(path.join(home, "bin", "t3"));
257 + expect(yield* fs.readLink(path.join(home, "bin", "t3"))).toBe(
258 + path.join(home, "new-t3", "bin", "t3"),
259 + );
260 + expect(yield* fs.exists(path.join(home, ".local", "bin", "t3"))).toBe(false);
261 + expect(yield* fs.readFileString(path.join(home, "bin", "t3.staging"))).toBe("mine");
262 }).pipe(Effect.scoped),
263 );
264
265 it.effect("refuses to install behind another t3 that runs first", () =>
266 Effect.gen(function* () {
267 + const env: NodeJS.ProcessEnv = { PATH: "", SHELL: "/bin/zsh" };
268 const fs = yield* FileSystem.FileSystem;
269 const path = yield* Path.Path;
270 const home = yield* fs.makeTempDirectoryScoped();
271 const shadow = path.join(home, "shadow");
272 yield* fs.makeDirectory(shadow);
273 yield* fs.writeFileString(path.join(shadow, "t3"), "#!/bin/sh\n", { mode: 0o755 });
176 - const env = { PATH: [shadow, path.join(home, ".local", "bin")].join(":") };
274 + env.PATH = [shadow, `${path.join(home, ".local", "bin")}/`].join(":");
275
276 const command = yield* commandIn({ home, env });
277 const theirs = path.join(shadow, "t3");
278 expect((yield* command.state).shadowedBy).toBe(theirs);
279 const error = yield* Effect.flip(command.install);
280 expect(error.message).toContain(theirs);
281 + yield* command.installOnFirstLaunch;
282 expect(yield* fs.exists(path.join(home, ".local", "bin", "t3"))).toBe(false);
283 + expect(yield* fs.readFileString(theirs)).toBe("#!/bin/sh\n");
284 +
285 + // Its folder is already on PATH behind theirs; adding it again would change which t3 runs.
286 + yield* fs.makeDirectory(path.join(home, ".local", "bin"), { recursive: true });
287 + yield* fs.symlink(
288 + path.join(home, ".t3", "bin", "t3"),
289 + path.join(home, ".local", "bin", "t3"),
290 + );
291 + const behind = yield* command.state;
292 + expect(behind.installedPath).toBe(path.join(home, ".local", "bin", "t3"));
293 + expect(behind.pathSetup).toBeUndefined();
294 + // Off PATH behind theirs, adding the folder would still put ours first.
295 + env.PATH = shadow;
296 + expect((yield* command.state).pathSetup).toBeUndefined();
297 + yield* Effect.flip(command.addToPath);
298 + expect(yield* fs.exists(path.join(home, ".zshrc"))).toBe(false);
299 + env.PATH = [shadow, `${path.join(home, ".local", "bin")}/`].join(":");
300 + yield* fs.remove(path.join(home, ".local", "bin", "t3"));
301
302 + // A first-launch install that failed is not retried behind the user's back.
303 yield* fs.remove(theirs);
304 + yield* command.installOnFirstLaunch;
305 + expect(yield* fs.exists(path.join(home, ".local", "bin", "t3"))).toBe(false);
306 const installed = yield* command.install;
307 expect(installed).toMatchObject({
308 onPath: true,
@@ -196,6 +316,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => {
316 "skips a t3 directory or a file this user cannot execute",
317 () =>
318 Effect.gen(function* () {
319 + const env: NodeJS.ProcessEnv = { PATH: "", SHELL: "/bin/zsh" };
320 const fs = yield* FileSystem.FileSystem;
321 const path = yield* Path.Path;
322 const home = yield* fs.makeTempDirectoryScoped();
@@ -209,7 +330,7 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => {
330 yield* fs.chmod(path.join(plain, "t3"), process.getuid?.() === 0 ? 0o600 : 0o601);
331 yield* fs.makeDirectory(shadow);
332 yield* fs.writeFileString(path.join(shadow, "t3"), "#!/bin/sh\n", { mode: 0o755 });
212 - const env = { PATH: [folder, plain, shadow, path.join(home, ".local", "bin")].join(":") };
333 + env.PATH = [folder, plain, shadow, path.join(home, ".local", "bin")].join(":");
334
335 const command = yield* commandIn({ home, env });
336 expect((yield* command.state).shadowedBy).toBe(path.join(shadow, "t3"));
@@ -227,11 +348,12 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => {
348
349 it.effect("does not treat its own launcher as another t3 when its folder is first on PATH", () =>
350 Effect.gen(function* () {
351 + const env: NodeJS.ProcessEnv = { PATH: "", SHELL: "/bin/zsh" };
352 const fs = yield* FileSystem.FileSystem;
353 const path = yield* Path.Path;
354 const home = yield* fs.makeTempDirectoryScoped();
355 const launcher = path.join(home, ".t3", "bin", "t3");
234 - const env = { PATH: [path.dirname(launcher), path.join(home, ".local", "bin")].join(":") };
356 + env.PATH = [path.dirname(launcher), path.join(home, ".local", "bin")].join(":");
357
358 const command = yield* commandIn({ home, env });
359 const installed = yield* command.install;
@@ -274,6 +396,21 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => {
396 expect(registry.path).toBe(`${userPath};${launcherDir}`);
397 yield* command.uninstall;
398 expect(registry.path).toBe(userPath);
399 +
400 + // A `;` in the folder would split it into two PATH entries, so nothing is written.
401 + const split = fakePowerShell(userPath);
402 + const semicolon = yield* commandIn(
403 + { home, baseDir: `${home}\\T3;Home`, platform: "win32" },
404 + split.spawner,
405 + );
406 + expect((yield* Effect.flip(semicolon.install)).message).toContain('has a ";"');
407 + expect(split.registry).toMatchObject({ path: userPath, writes: 0 });
408 +
409 + // An inherited T3_SET=1 never turns a read into a write of the whole PATH.
410 + const inherited = fakePowerShell(userPath, { T3_SET: "1", T3_PATH: "C:\\other" });
411 + const reader = yield* commandIn({ home, platform: "win32" }, inherited.spawner);
412 + yield* reader.install;
413 + expect(inherited.registry).toMatchObject({ path: `${userPath};${launcherDir}`, writes: 1 });
414 }).pipe(Effect.scoped),
415 );
416
@@ -294,6 +431,16 @@ it.layer(NodeServices.layer)("DesktopCliCommand", (it) => {
431 expect((yield* command.state).installedPath).toBeNull();
432 yield* command.uninstall;
433 expect(registry.path).toBe(userPath);
434 +
435 + // A fresh install beside a standalone t3.cmd (from `t3 install`), even off PATH, leaves
436 + // PATH alone.
437 + const besideHome = yield* fs.makeTempDirectoryScoped();
438 + yield* fs.makeDirectory(path.join(besideHome, ".local", "bin"), { recursive: true });
439 + yield* fs.writeFileString(path.join(besideHome, ".local", "bin", "t3.cmd"), "@echo off\r\n");
440 + const beside = fakePowerShell("C:\\Tools");
441 + yield* (yield* commandIn({ home: besideHome, platform: "win32" }, beside.spawner))
442 + .installOnFirstLaunch;
443 + expect(beside.registry).toMatchObject({ path: "C:\\Tools", writes: 0 });
444 }).pipe(Effect.scoped),
445 );
446 });
apps/desktop/src/app/DesktopCliCommand.ts
+197 -24
@@ -8,23 +8,34 @@ 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 Random from "effect/Random";
12 import * as Schema from "effect/Schema";
13 +import * as Semaphore from "effect/Semaphore";
14 import * as Stream from "effect/Stream";
15 import * as ChildProcess from "effect/process/ChildProcess";
16 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
17
18 +import { pathSetup, readUserLoginShell } from "@t3tools/shared/shell";
19 +
20 import * as DesktopCliShim from "./DesktopCliShim.ts";
21 import * as DesktopEnvironment from "./DesktopEnvironment.ts";
22 +import { makeComponentLogger } from "./DesktopObservability.ts";
23 +
24 +const { logInfo, logWarning } = makeComponentLogger("desktop-cli-command");
25
26 export class DesktopCliCommandError extends Schema.TaggedError<DesktopCliCommandError>()(
27 "DesktopCliCommandError",
28 { message: Schema.String },
29 ) {}
30
24 -const unixCandidates = (home: string, platform: NodeJS.Platform) =>
31 +const userCandidates = (home: string) => [`${home}/.local/bin`, `${home}/bin`];
32 +
33 +// Older builds also linked into these macOS folders. Such a link is found, updated in place, and
34 +// removed, but no new link goes there.
35 +const knownLocations = (home: string, platform: NodeJS.Platform) =>
36 platform === "darwin"
26 - ? ["/opt/homebrew/bin", "/usr/local/bin", `${home}/.local/bin`, `${home}/bin`]
27 - : [`${home}/.local/bin`, `${home}/bin`];
37 + ? [...userCandidates(home), "/opt/homebrew/bin", "/usr/local/bin"]
38 + : userCandidates(home);
39
40 const pathEntries = (value: string | undefined, separator: string) =>
41 (value ?? "").split(separator).filter((entry) => entry.length > 0);
@@ -59,6 +70,10 @@ export class DesktopCliCommand extends Context.Service<
70 readonly state: Effect.Effect<DesktopCliCommandState>;
71 readonly install: Effect.Effect<DesktopCliCommandState, DesktopCliCommandError>;
72 readonly uninstall: Effect.Effect<DesktopCliCommandState, DesktopCliCommandError>;
73 + /** Adds the installed command's folder to PATH in the user's shell startup file. */
74 + readonly addToPath: Effect.Effect<DesktopCliCommandState, DesktopCliCommandError>;
75 + /** Installs the command on a fresh install's first launch; removing it in Settings sticks. */
76 + readonly installOnFirstLaunch: Effect.Effect<void>;
77 }
78 >()("@t3tools/desktop/app/DesktopCliCommand") {}
79
@@ -74,9 +89,14 @@ export const make = Effect.gen(function* () {
89 const launcher = DesktopCliShim.launcherPath(environment);
90 const binDirectory = path.dirname(launcher);
91 const ownedPathMarker = path.join(environment.stateDir, "cli-command-path-entry");
92 + const firstLaunchMarker = path.join(environment.stateDir, "cli-command-first-launch");
93
94 const fail = (message: string) => new DesktopCliCommandError({ message });
95 const exists = (target: string) => fs.exists(target).pipe(Effect.orElseSucceed(() => false));
96 + // Read before this launch writes either one: an app that ran before left its launcher or
97 + // settings. Its user may have removed t3 or chosen another, so only Settings installs there.
98 + const freshInstall =
99 + !(yield* exists(launcher)) && !(yield* exists(environment.desktopSettingsPath));
100 const writableDirectory = (directory: string) =>
101 fs.access(directory, { writable: true }).pipe(
102 Effect.as(true),
@@ -97,8 +117,8 @@ export const make = Effect.gen(function* () {
117
118 // PATH can reach the regular launcher directly; removal still requires isOurLink.
119 const runsOurLauncher = Effect.fn("DesktopCliCommand.runsOurLauncher")(
120 + // Another T3 home's link is marked too, so compare where it leads, not the marker alone.
121 function* (candidate: string) {
101 - if (yield* isOurLink(candidate)) return true;
122 const [resolved, ours] = yield* Effect.all([fs.realPath(candidate), fs.realPath(launcher)]);
123 if (resolved !== ours) return false;
124 const info = yield* fs.stat(candidate);
@@ -127,7 +147,8 @@ export const make = Effect.gen(function* () {
147 return stdout;
148 }),
149 );
130 - const readUserPath = powershell({}).pipe(
150 + // Explicit, so an inherited T3_SET=1 can never turn a read into a PATH write.
151 + const readUserPath = powershell({ T3_SET: "0" }).pipe(
152 Effect.map((encoded) => Buffer.from(encoded.trim(), "base64").toString("utf8")),
153 Effect.mapError(() => fail("Could not read your PATH, so it was left unchanged.")),
154 );
@@ -164,6 +185,13 @@ export const make = Effect.gen(function* () {
185 return first;
186 });
187
188 + /** A link to this home's launcher; another home's link is marked too. */
189 + const leadsHere = (link: string) =>
190 + fs.readLink(link).pipe(
191 + Effect.map((target) => target === launcher),
192 + Effect.orElseSucceed(() => false),
193 + );
194 +
195 const installedAt = Effect.gen(function* () {
196 if (windows) {
197 if (!(yield* exists(ownedPathMarker))) return Option.none<string>();
@@ -172,31 +200,77 @@ export const make = Effect.gen(function* () {
200 ? Option.some(launcher)
201 : Option.none<string>();
202 }
175 - for (const directory of unixCandidates(environment.homeDirectory, environment.platform)) {
203 + for (const directory of knownLocations(environment.homeDirectory, environment.platform)) {
204 const link = path.join(directory, "t3");
205 if (yield* isOurLink(link)) return Option.some(link);
206 }
207 return Option.none<string>();
208 });
209
210 + const startupLine = (installedPath: string) => {
211 + const setup = pathSetup({
212 + directory: path.dirname(installedPath),
213 + home: environment.homeDirectory,
214 + // A Finder or desktop launch may not set SHELL.
215 + shell: env.SHELL || readUserLoginShell(),
216 + platform: environment.platform,
217 + configHome: env.XDG_CONFIG_HOME,
218 + zdotdir: env.ZDOTDIR,
219 + });
220 + if (setup === undefined) return undefined;
221 + const file = setup.file.startsWith("~/")
222 + ? path.join(environment.homeDirectory, setup.file.slice(2))
223 + : setup.file;
224 + return { ...setup, path: file };
225 + };
226 + const hasLine = (setup: { readonly path: string; readonly line: string }) =>
227 + fs.readFileString(setup.path).pipe(
228 + Effect.map((content) => content.split("\n").some((line) => line.trim() === setup.line)),
229 + Effect.orElseSucceed(() => false),
230 + );
231 +
232 + const folderOnPath = (link: string) =>
233 + Effect.sync(() =>
234 + pathEntries(env.PATH, ":").some((entry) => entry.replace(/\/+$/, "") === path.dirname(link)),
235 + );
236 +
237 const state: DesktopCliCommand["Service"]["state"] = Effect.gen(function* () {
238 if (!environment.isPackaged) {
239 return { supported: false, installedPath: null, onPath: false, launcherPath: null } as const;
240 }
241 const launcherPath = (yield* exists(launcher)) ? launcher : null;
187 - const installed = yield* installedAt;
188 - const shadowedBy = yield* foreignFirstOnPath;
242 + const found = yield* installedAt;
243 + // Our link into another T3 home is not this app's command; Install updates it in place.
244 + const installed =
245 + windows || (Option.isSome(found) && (yield* leadsHere(found.value)))
246 + ? found
247 + : Option.none<string>();
248 + const shadowedBy = (yield* foreignFirstOnPath).pipe(
249 + Option.filter((first) => first !== Option.getOrUndefined(found)),
250 + );
251 const shadow = Option.isSome(shadowedBy) ? { shadowedBy: shadowedBy.value } : {};
252 const first = yield* firstOnPath;
253 const onPath = windows
254 ? Option.isSome(installed)
255 : Option.isSome(first) && (yield* runsOurLauncher(first.value));
256 + // Only a folder missing from PATH, with no other t3 first: with one, the added folder (last
257 + // on PATH) would still not run this t3.
258 + const setup =
259 + onPath ||
260 + Option.isSome(shadowedBy) ||
261 + Option.isNone(installed) ||
262 + (yield* folderOnPath(installed.value))
263 + ? undefined
264 + : startupLine(installed.value);
265 return {
266 supported: true,
267 installedPath: Option.getOrNull(installed),
268 onPath,
269 launcherPath,
270 ...shadow,
271 + ...(setup === undefined
272 + ? {}
273 + : { pathSetup: { file: setup.file, added: yield* hasLine(setup) } }),
274 };
275 }).pipe(
276 Effect.orElseSucceed(() => ({
@@ -222,6 +296,12 @@ export const make = Effect.gen(function* () {
296 if (!environment.isPackaged) return yield* fail("The t3 command needs an installed app.");
297 yield* ensureLauncher;
298 if (windows) {
299 + // PATH would split the folder at the `;`, leaving two wrong entries behind.
300 + if (binDirectory.includes(";")) {
301 + return yield* fail(
302 + `T3 Code cannot put ${binDirectory} on PATH because it has a ";". Run ${launcher} directly.`,
303 + );
304 + }
305 const entries = pathEntries(yield* readUserPath, ";");
306 if (!entries.some((entry) => sameWindowsPath(entry, binDirectory))) {
307 yield* writeUserPath([...entries, binDirectory].join(";"));
@@ -231,26 +311,27 @@ export const make = Effect.gen(function* () {
311 }
312 return yield* state;
313 }
234 - const existing = yield* installedAt;
235 - if (Option.isSome(existing)) {
236 - const target = yield* fs.readLink(existing.value).pipe(Effect.option);
314 + const candidates = userCandidates(environment.homeDirectory);
315 + const replaced = Option.getOrUndefined(yield* installedAt);
316 + if (replaced !== undefined) {
317 + const target = yield* fs.readLink(replaced).pipe(Effect.option);
318 if (Option.getOrUndefined(target) === launcher) return yield* state;
238 - yield* fs
239 - .remove(existing.value)
240 - .pipe(Effect.mapError(() => fail(`Could not replace ${existing.value}.`)));
319 }
320 const shadowedBy = yield* foreignFirstOnPath;
243 - if (Option.isSome(shadowedBy)) {
321 + // Our own link into another T3 home runs first too; it is the one this install updates.
322 + if (Option.isSome(shadowedBy) && shadowedBy.value !== replaced) {
323 return yield* fail(
324 `Another t3 at ${shadowedBy.value} runs first in a new terminal. Remove it, or run the launcher directly at ${launcher}.`,
325 );
326 }
248 - const onPath = pathEntries(env.PATH, ":");
249 - const candidates = unixCandidates(environment.homeDirectory, environment.platform);
250 - for (const directory of [
327 + // An old link of ours is updated where it is, so a t3 that works now keeps working. It is
328 + // removed only once a new link exists elsewhere.
329 + const onPath = pathEntries(env.PATH, ":").map((entry) => entry.replace(/\/+$/, ""));
330 + for (const directory of new Set([
331 + ...(replaced === undefined ? [] : [path.dirname(replaced)]),
332 ...candidates.filter((candidate) => onPath.includes(candidate)),
333 ...candidates.filter((candidate) => !onPath.includes(candidate)),
253 - ]) {
334 + ])) {
335 const link = path.join(directory, "t3");
336 const created = (yield* exists(directory))
337 ? yield* writableDirectory(directory)
@@ -259,18 +340,38 @@ export const make = Effect.gen(function* () {
340 Effect.orElseSucceed(() => false),
341 );
342 if (!created) continue;
262 - const linked = yield* fs.symlink(launcher, link).pipe(
343 + // Our own link is swapped in place; anything else there makes symlink fail and stays.
344 + const staging = `${link}.${yield* Random.nextIntBetween(0, 0xffffff)}.tmp`;
345 + const linked = yield* (
346 + link === replaced
347 + ? fs
348 + .symlink(launcher, staging)
349 + .pipe(
350 + Effect.andThen(
351 + fs
352 + .rename(staging, link)
353 + .pipe(Effect.tapError(() => fs.remove(staging).pipe(Effect.ignore))),
354 + ),
355 + )
356 + : fs.symlink(launcher, link)
357 + ).pipe(
358 Effect.as(true),
359 Effect.orElseSucceed(() => false),
360 );
266 - if (linked) return yield* state;
361 + if (!linked) continue;
362 + if (replaced !== undefined && replaced !== link) {
363 + yield* fs.remove(replaced).pipe(Effect.ignore);
364 + }
365 + return yield* state;
366 }
367 return yield* fail(
269 - `Another t3 command is already installed, or no folder on your PATH is writable. Run the launcher directly at ${launcher}.`,
368 + `Another t3 command is already in ~/.local/bin and ~/bin, or neither is writable. Run the launcher directly at ${launcher}.`,
369 );
370 }).pipe(Effect.withSpan("desktop.cliCommand.install"));
371
372 const uninstall: DesktopCliCommand["Service"]["uninstall"] = Effect.gen(function* () {
373 + // A first launch put off for the shell PATH must not bring back what the user removed.
374 + yield* fs.writeFileString(firstLaunchMarker, "").pipe(Effect.ignore);
375 if (windows) {
376 if (yield* exists(ownedPathMarker)) {
377 const entries = pathEntries(yield* readUserPath, ";");
@@ -280,7 +381,7 @@ export const make = Effect.gen(function* () {
381 }
382 return yield* state;
383 }
283 - for (const directory of unixCandidates(environment.homeDirectory, environment.platform)) {
384 + for (const directory of knownLocations(environment.homeDirectory, environment.platform)) {
385 const link = path.join(directory, "t3");
386 if (yield* isOurLink(link)) {
387 yield* fs.remove(link).pipe(Effect.mapError(() => fail(`Could not remove ${link}.`)));
@@ -289,7 +390,79 @@ export const make = Effect.gen(function* () {
390 return yield* state;
391 }).pipe(Effect.withSpan("desktop.cliCommand.uninstall"));
392
292 - return DesktopCliCommand.of({ state, install, uninstall });
393 + // One at a time, so Settings and onboarding cannot both append the line.
394 + const addToPathPermit = yield* Semaphore.make(1);
395 + const addToPath: DesktopCliCommand["Service"]["addToPath"] = Effect.gen(function* () {
396 + const installed = yield* installedAt;
397 + if (Option.isNone(installed) || !(yield* leadsHere(installed.value))) {
398 + return yield* fail("Install the t3 command first.");
399 + }
400 + const setup = startupLine(installed.value);
401 + if (setup === undefined) return yield* fail("T3 Code cannot add t3 to this shell's PATH.");
402 + const shadowedBy = yield* foreignFirstOnPath;
403 + if (Option.isSome(shadowedBy)) {
404 + return yield* fail(
405 + `Another t3 at ${shadowedBy.value} runs first; T3 Code leaves it in place.`,
406 + );
407 + }
408 + if (!(yield* folderOnPath(installed.value)) && !(yield* hasLine(setup))) {
409 + yield* fs.makeDirectory(path.dirname(setup.path), { recursive: true }).pipe(
410 + Effect.andThen(
411 + fs.writeFileString(setup.path, `\n# Added by T3 Code\n${setup.line}\n`, { flag: "a" }),
412 + ),
413 + Effect.mapError(() => fail(`Could not add t3 to ${setup.file}.`)),
414 + );
415 + }
416 + return yield* state;
417 + }).pipe(addToPathPermit.withPermits(1), Effect.withSpan("desktop.cliCommand.addToPath"));
418 +
419 + const installOnFirstLaunch: DesktopCliCommand["Service"]["installOnFirstLaunch"] = Effect.gen(
420 + function* () {
421 + if (!environment.isPackaged || (yield* exists(firstLaunchMarker))) return;
422 + // Mark first so a failed or removed install is never retried behind the user's back.
423 + yield* fs.writeFileString(firstLaunchMarker, "");
424 + if (!freshInstall) {
425 + return yield* logInfo("left the t3 command to Settings on an existing install");
426 + }
427 + // Another T3 home's app owns the existing link; only Install in Settings may take it over.
428 + const existing = Option.getOrUndefined(yield* installedAt);
429 + if (existing !== undefined) {
430 + const target = yield* fs.readLink(existing).pipe(Effect.option);
431 + if (Option.getOrUndefined(target) !== launcher) {
432 + return yield* logInfo("left another T3 Code app's t3 command in place", {
433 + existing,
434 + });
435 + }
436 + }
437 + // A t3 that is not ours in these folders, even off PATH, means the user has one already. On
438 + // Windows the app never writes there, so any t3 there is someone else's.
439 + for (const directory of userCandidates(environment.homeDirectory)) {
440 + for (const name of windows ? ["t3.cmd", "t3.exe"] : ["t3"]) {
441 + const other = path.join(directory, name);
442 + const present =
443 + (yield* exists(other)) || Option.isSome(yield* fs.readLink(other).pipe(Effect.option));
444 + if (present && (windows || !(yield* isOurLink(other)))) {
445 + return yield* logInfo("left the t3 command to Settings beside another t3", { other });
446 + }
447 + }
448 + }
449 + const installed = yield* install;
450 + yield* logInfo("installed the t3 command on first launch", {
451 + installedPath: installed.installedPath,
452 + onPath: installed.onPath,
453 + });
454 + },
455 + ).pipe(
456 + // Our own messages are short and name only paths; anything else is logged as a category.
457 + Effect.catch((error) =>
458 + logWarning("did not install the t3 command on first launch", {
459 + reason: error._tag === "DesktopCliCommandError" ? error.message : "state-write-failed",
460 + }),
461 + ),
462 + Effect.withSpan("desktop.cliCommand.installOnFirstLaunch"),
463 + );
464 +
465 + return DesktopCliCommand.of({ state, install, uninstall, addToPath, installOnFirstLaunch });
466 });
467
468 export const layer = Layer.effect(DesktopCliCommand, make);
apps/desktop/src/app/DesktopCliShim.ts
+3 -1
@@ -2,6 +2,7 @@ import * as Cause from "effect/Cause";
2 import * as Effect from "effect/Effect";
3 import * as FileSystem from "effect/FileSystem";
4 import * as Option from "effect/Option";
5 +import * as Random from "effect/Random";
6
7 import * as DesktopEnvironment from "./DesktopEnvironment.ts";
8 import { makeComponentLogger } from "./DesktopObservability.ts";
@@ -147,7 +148,8 @@ export const install = Effect.gen(function* () {
148 }
149 if (Option.getOrUndefined(existing) !== content) {
150 yield* fs.makeDirectory(path.dirname(shimPath), { recursive: true });
150 - const staging = `${shimPath}.${process.pid}.tmp`;
151 + // Unique per call: backend startup and the first-launch command install can race here.
152 + const staging = `${shimPath}.${process.pid}.${yield* Random.nextIntBetween(0, 0xffffff)}.tmp`;
153 yield* fs.writeFileString(staging, content, { mode: 0o755 });
154 yield* fs.rename(staging, shimPath);
155 yield* logInfo("installed t3 launcher", { shimPath });
apps/desktop/src/backend/DesktopBackendConfiguration.test.ts
+1
@@ -27,6 +27,7 @@ const layerShellEnvironment = (prepared = true) =>
27 Layer.succeed(DesktopShellEnvironment.DesktopShellEnvironment, {
28 installIntoProcess: Effect.succeed(prepared),
29 awaitDiscovery: Effect.succeed(prepared),
30 + awaitUserShellDiscovery: Effect.succeed(prepared),
31 updates: Stream.empty,
32 });
33
apps/desktop/src/ipc/DesktopIpcHandlers.ts
+2
@@ -80,6 +80,7 @@ import {
80 getCliCommandState,
81 installCliCommand,
82 uninstallCliCommand,
83 + addCliCommandToPath,
84 } from "./methods/cliCommand.ts";
85
86 export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers")(function* () {
@@ -162,6 +163,7 @@ export const installDesktopIpcHandlers = Effect.fn("desktop.ipc.installHandlers"
163 yield* ipc.handle(getCliCommandState);
164 yield* ipc.handle(installCliCommand);
165 yield* ipc.handle(uninstallCliCommand);
166 + yield* ipc.handle(addCliCommandToPath);
167 for (const previewMethod of PreviewIpc.methods) {
168 // Explicit types preserve the error/service union of these heterogeneous preview methods.
169 yield* ipc.handle<
apps/desktop/src/ipc/channels.ts
+1
@@ -31,6 +31,7 @@ export const UPDATE_CHECK_CHANNEL = "desktop:update-check";
31 export const CLI_COMMAND_GET_STATE_CHANNEL = "desktop:cli-command-get-state";
32 export const CLI_COMMAND_INSTALL_CHANNEL = "desktop:cli-command-install";
33 export const CLI_COMMAND_UNINSTALL_CHANNEL = "desktop:cli-command-uninstall";
34 +export const CLI_COMMAND_ADD_TO_PATH_CHANNEL = "desktop:cli-command-add-to-path";
35 export const GET_APP_BRANDING_CHANNEL = "desktop:get-app-branding";
36 export const GET_RELAY_TELEMETRY_ENABLED_CHANNEL = "desktop:get-relay-telemetry-enabled";
37 export const GET_SYSTEM_LOCALE_CHANNEL = "desktop:get-system-locale";
apps/desktop/src/ipc/methods/cliCommand.ts
+9
@@ -32,3 +32,12 @@ export const uninstallCliCommand = makeIpcMethod({
32 return yield* (yield* DesktopCliCommand.DesktopCliCommand).uninstall;
33 }),
34 });
35 +
36 +export const addCliCommandToPath = makeIpcMethod({
37 + channel: IpcChannels.CLI_COMMAND_ADD_TO_PATH_CHANNEL,
38 + payload: Schema.Void,
39 + result: DesktopCliCommandStateSchema,
40 + handler: Effect.fn("desktop.ipc.cliCommand.addToPath")(function* () {
41 + return yield* (yield* DesktopCliCommand.DesktopCliCommand).addToPath;
42 + }),
43 +});
apps/desktop/src/preload.ts
+1
@@ -285,6 +285,7 @@ contextBridge.exposeInMainWorld("desktopBridge", {
285 getState: () => ipcRenderer.invoke(IpcChannels.CLI_COMMAND_GET_STATE_CHANNEL),
286 install: () => ipcRenderer.invoke(IpcChannels.CLI_COMMAND_INSTALL_CHANNEL),
287 uninstall: () => ipcRenderer.invoke(IpcChannels.CLI_COMMAND_UNINSTALL_CHANNEL),
288 + addToPath: () => ipcRenderer.invoke(IpcChannels.CLI_COMMAND_ADD_TO_PATH_CHANNEL),
289 },
290 onUpdateState: (listener) => {
291 const wrappedListener = (_event: Electron.IpcRendererEvent, state: unknown) => {
apps/desktop/src/shell/DesktopShellEnvironment.test.ts
+21 -1
@@ -444,10 +444,13 @@ describe("DesktopShellEnvironment", () => {
444 const env: NodeJS.ProcessEnv = { SHELL: "/bin/failing", PATH: "/usr/bin" };
445 const commands: string[] = [];
446
447 - yield* runShellEnvironment({
447 + const discovery = (service: DesktopShellEnvironment.DesktopShellEnvironment["Service"]) =>
448 + Effect.all([service.awaitDiscovery, service.awaitUserShellDiscovery]);
449 + const answered = yield* runShellEnvironment({
450 env,
451 platform: "linux",
452 userShell: "/usr/local/bin/fish",
453 + use: (service) => discovery(service).pipe(Effect.map(([, fromUserShell]) => fromUserShell)),
454 handler: (command) => {
455 if (command._tag !== "StandardCommand") return "";
456 commands.push(command.command);
@@ -459,6 +462,23 @@ describe("DesktopShellEnvironment", () => {
462
463 assert.deepEqual(commands, ["/bin/failing", "/usr/local/bin/fish"]);
464 assert.equal(env.PATH, "/home/test/.local/bin:/usr/bin");
465 + // The account's own login shell answered.
466 + assert.isTrue(answered);
467 +
468 + // Only the platform fallback answered: its PATH can miss folders the user's shell adds.
469 + const fallbackOnly = yield* runShellEnvironment({
470 + env: { SHELL: "/usr/bin/fish", PATH: "/usr/bin" },
471 + platform: "linux",
472 + use: (service) =>
473 + discovery(service).pipe(
474 + Effect.map(([prepared, fromUserShell]) => prepared && !fromUserShell),
475 + ),
476 + handler: (command) =>
477 + command._tag === "StandardCommand" && command.command === "/usr/bin/fish"
478 + ? { output: "", exitCode: 7 }
479 + : envOutput({ PATH: "/usr/bin" }),
480 + }).pipe(Effect.provide(Logger.layer([])));
481 + assert.isTrue(fallbackOnly);
482 }),
483 );
484
apps/desktop/src/shell/DesktopShellEnvironment.ts
+38 -10
@@ -3,6 +3,7 @@ import {
3 applyShellEnvironment,
4 buildEnvironmentCaptureCommand,
5 listLoginShellCandidates,
6 + readUserLoginShell,
7 setWindowsPath,
8 } from "@t3tools/shared/shell";
9 import * as Context from "effect/Context";
@@ -79,6 +80,8 @@ export class DesktopShellEnvironment extends Context.Service<
80 // Desktop owns discovery, including on cache misses; the backend receives updates over fd4.
81 readonly installIntoProcess: Effect.Effect<boolean>;
82 readonly awaitDiscovery: Effect.Effect<boolean>;
83 + /** Whether the user's own login shell, not a fallback, gave the PATH a new terminal gets. */
84 + readonly awaitUserShellDiscovery: Effect.Effect<boolean>;
85 readonly updates: Stream.Stream<DesktopShellEnvironmentSnapshot>;
86 }
87 >()("@t3tools/desktop/shell/DesktopShellEnvironment") {}
@@ -417,19 +420,24 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
420 function* (
421 config: ShellEnvironmentConfig,
422 ): Effect.fn.Return<
420 - boolean,
423 + ShellDiscovery,
424 never,
425 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
426 > {
427 const fileSystem = yield* FileSystem.FileSystem;
428 const shellEnvironment: EnvironmentPatch = {};
429 + const userShells = [config.env.SHELL?.trim(), readUserLoginShell()];
430
431 + let answeredBy: string | undefined;
432 for (const shell of listLoginShellCandidates(config.platform, config.env.SHELL)) {
433 Object.assign(
434 shellEnvironment,
435 yield* readLoginShellEnvironment(shell, LOGIN_SHELL_ENV_NAMES, config.env),
436 );
432 - if (shellEnvironment.PATH) break;
437 + if (shellEnvironment.PATH) {
438 + answeredBy = shell;
439 + break;
440 + }
441 }
442
443 const launchctlPath =
@@ -518,24 +526,33 @@ const installPosixEnvironment = Effect.fn("desktop.shellEnvironment.installPosix
526 }
527 }
528
521 - return Option.isSome(trimNonEmpty(shellEnvironment.PATH));
529 + const prepared = Option.isSome(trimNonEmpty(shellEnvironment.PATH));
530 + return { prepared, fromUserShell: prepared && userShells.includes(answeredBy) };
531 },
532 );
533
534 +/** `fromUserShell` is false when only a fallback shell answered, whose PATH can miss folders. */
535 +interface ShellDiscovery {
536 + readonly prepared: boolean;
537 + readonly fromUserShell: boolean;
538 +}
539 +
540 const installShellEnvironment = (
541 config: ShellEnvironmentConfig,
542 ): Effect.Effect<
528 - boolean,
543 + ShellDiscovery,
544 never,
545 ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem
546 > => {
547 if (config.platform === "win32") {
533 - return installWindowsEnvironment(config);
548 + return installWindowsEnvironment(config).pipe(
549 + Effect.map((prepared) => ({ prepared, fromUserShell: prepared })),
550 + );
551 }
552 if (config.platform === "darwin" || config.platform === "linux") {
553 return installPosixEnvironment(config);
554 }
538 - return Effect.succeed(false);
555 + return Effect.succeed({ prepared: false, fromUserShell: false });
556 };
557
558 const ShellEnvironmentCache = Schema.fromJsonString(
@@ -578,7 +595,7 @@ export const make = Effect.gen(function* () {
595 const cachePath = path.join(environment.stateDir, "shell-environment-cache.json");
596 const changes = yield* PubSub.unbounded<DesktopShellEnvironmentSnapshot>();
597 const latest = yield* Ref.make<Option.Option<DesktopShellEnvironmentSnapshot>>(Option.none());
581 - const discovered = yield* Deferred.make<boolean>();
598 + const discovered = yield* Deferred.make<ShellDiscovery>();
599 const publish = Effect.fn("desktop.shellEnvironment.publish")(function* (
600 patch: ShellEnvironmentPatch,
601 discovered = false,
@@ -597,7 +614,11 @@ export const make = Effect.gen(function* () {
614 const refresh = Effect.gen(function* () {
615 // Refresh from the inherited baseline so removed cached paths and values do not survive.
616 const fresh = { ...inherited };
600 - const prepared = yield* installShellEnvironment({ env: fresh, platform: environment.platform });
617 + const discovery = yield* installShellEnvironment({
618 + env: fresh,
619 + platform: environment.platform,
620 + });
621 + const { prepared } = discovery;
622 const patch = Object.fromEntries(
623 Object.keys(ShellEnvironmentPatch.fields).map((name) => [name, fresh[name] ?? null]),
624 );
@@ -616,7 +637,7 @@ export const make = Effect.gen(function* () {
637 Effect.catch(() => Effect.logWarning("Could not cache shell environment")),
638 );
639 }
619 - return prepared;
640 + return discovery;
641 }).pipe(
642 Effect.provideService(FileSystem.FileSystem, fileSystem),
643 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
@@ -669,7 +690,14 @@ export const make = Effect.gen(function* () {
690 );
691 return DesktopShellEnvironment.of({
692 installIntoProcess,
672 - awaitDiscovery: installIntoProcess.pipe(Effect.andThen(Deferred.await(discovered))),
693 + awaitDiscovery: installIntoProcess.pipe(
694 + Effect.andThen(Deferred.await(discovered)),
695 + Effect.map(({ prepared }) => prepared),
696 + ),
697 + awaitUserShellDiscovery: installIntoProcess.pipe(
698 + Effect.andThen(Deferred.await(discovered)),
699 + Effect.map(({ fromUserShell }) => fromUserShell),
700 + ),
701 updates,
702 });
703 });
apps/desktop/src/telemetry/DesktopTelemetryPublisher.test.ts
+1
@@ -92,6 +92,7 @@ describe("DesktopTelemetryPublisher", () => {
92 Layer.succeed(DesktopShellEnvironment.DesktopShellEnvironment, {
93 installIntoProcess: Effect.succeed(true),
94 awaitDiscovery: Effect.succeed(true),
95 + awaitUserShellDiscovery: Effect.succeed(true),
96 updates: Stream.make({
97 version: 1,
98 type: "shellEnvironment",
apps/web/src/components/onboarding/WelcomeWizard.tsx
+30
@@ -84,6 +84,7 @@ import { connectPairing } from "../../connection/onboarding";
84 import { getProviderSummary } from "../settings/providerStatus";
85 import { providerClients } from "../settings/providerDriverMeta";
86 import { ChatGptWelcomeCoordinator } from "../settings/ChatGptWelcomeCoordinator";
87 +import { useDesktopCliCommand } from "../settings/CliCommandSettingsRow";
88 import { AddManagedCodexAccountDialog, CodexSetupSection } from "../settings/CodexSetupSection";
89 import { readCodexSetupMode } from "../settings/CodexSetupSection.logic";
90 import { buildProviderInstanceUpdatePatch } from "../settings/SettingsPanels.logic";
@@ -701,6 +702,7 @@ function AgentsStep({
702 ))}
703 </div>
704 </ScrollArea>
705 + <CliPathSetup />
706 <div className="mt-6 flex justify-end">
707 <Button autoFocus onClick={onContinue}>
708 Continue
@@ -1794,6 +1796,34 @@ function ImportRowMeta({
1796 );
1797 }
1798
1799 +/** The desktop app links `t3` on a fresh install; this puts its folder on PATH when it is not. */
1800 +function CliPathSetup() {
1801 + const { state, busy, run } = useDesktopCliCommand();
1802 + const setup = state?.pathSetup;
1803 + if (!setup) return null;
1804 + return (
1805 + <div className="mt-5 flex items-center justify-between gap-3">
1806 + <p className="text-sm text-muted-foreground">
1807 + {setup.added ? (
1808 + <>
1809 + Added to {setup.file}. Open a new terminal to use <code className="font-mono">t3</code>.
1810 + </>
1811 + ) : (
1812 + <>
1813 + Use <code className="font-mono">t3</code> from any terminal. Adds one line to{" "}
1814 + {setup.file}.
1815 + </>
1816 + )}
1817 + </p>
1818 + {setup.added ? null : (
1819 + <Button size="sm" variant="outline" disabled={busy} onClick={() => run("addToPath")}>
1820 + Add to PATH
1821 + </Button>
1822 + )}
1823 + </div>
1824 + );
1825 +}
1826 +
1827 function StepShell({
1828 title,
1829 description,
apps/web/src/components/settings/CliCommandSettingsRow.tsx
+39 -14
@@ -11,13 +11,19 @@ import { stackedThreadToast, toastManager } from "../ui/toast";
11 import { SettingsRow } from "./settingsLayout";
12 import { searchableSetting } from "./settingsSearch";
13
14 -export function CliCommandSettingsRow() {
14 +const FAILURE_TITLES = {
15 + install: "Could not install t3",
16 + uninstall: "Could not remove t3",
17 + addToPath: "Could not add t3 to PATH",
18 +} as const;
19 +
20 +/** The desktop `t3` command's state, and its actions with a toast on failure. */
21 +export function useDesktopCliCommand() {
22 const bridge = getDesktopCliCommandBridge();
23 const query = useEnvironmentQuery(bridge ? desktopCliCommandStateAtom : null);
17 - const state = query.data;
24 const [pending, setPending] = useState(false);
25
20 - const change = (action: "install" | "uninstall") => {
26 + const run = (action: keyof typeof FAILURE_TITLES) => {
27 if (!bridge || pending) return;
28 setPending(true);
29 void bridge[action]()
@@ -26,7 +32,7 @@ export function CliCommandSettingsRow() {
32 toastManager.add(
33 stackedThreadToast({
34 type: "error",
29 - title: action === "install" ? "Could not install t3" : "Could not remove t3",
35 + title: FAILURE_TITLES[action],
36 description: error instanceof Error ? error.message : "Something went wrong.",
37 }),
38 );
@@ -34,7 +40,17 @@ export function CliCommandSettingsRow() {
40 .finally(() => setPending(false));
41 };
42
37 - if (!bridge || !state?.supported) return null;
43 + return {
44 + state: bridge ? query.data : undefined,
45 + busy: pending || query.isPending,
46 + run,
47 + };
48 +}
49 +
50 +export function CliCommandSettingsRow() {
51 + const { state, busy, run } = useDesktopCliCommand();
52 +
53 + if (!state?.supported) return null;
54 const installed = state.installedPath !== null;
55 const description = state.shadowedBy
56 ? `Another t3 at ${state.shadowedBy} runs first in a new terminal. Remove it to use T3 Code's.`
@@ -42,21 +58,30 @@ export function CliCommandSettingsRow() {
58 ? "Run T3 Code's CLI as `t3` from any terminal."
59 : state.onPath
60 ? `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\`.`;
61 + : state.pathSetup?.added
62 + ? `Installed at ${state.installedPath} and added to PATH in ${state.pathSetup.file}. Open a new terminal to use it.`
63 + : `Installed at ${state.installedPath}, which is not on your PATH yet.${state.pathSetup ? "" : " Add its folder to your PATH to run `t3`."}`;
64
65 return (
66 <SettingsRow
67 {...searchableSetting("cli-command")}
68 description={description}
69 control={
52 - <Button
53 - size="sm"
54 - variant="outline"
55 - disabled={pending || query.isPending || (!installed && Boolean(state.shadowedBy))}
56 - onClick={() => change(installed ? "uninstall" : "install")}
57 - >
58 - {installed ? "Remove" : "Install"}
59 - </Button>
70 + <div className="flex gap-2">
71 + {state.pathSetup && !state.pathSetup.added ? (
72 + <Button size="sm" variant="outline" disabled={busy} onClick={() => run("addToPath")}>
73 + Add to PATH
74 + </Button>
75 + ) : null}
76 + <Button
77 + size="sm"
78 + variant="outline"
79 + disabled={busy || (!installed && Boolean(state.shadowedBy))}
80 + onClick={() => run(installed ? "uninstall" : "install")}
81 + >
82 + {installed ? "Remove" : "Install"}
83 + </Button>
84 + </div>
85 }
86 />
87 );
docs/user/install.md
+8 -6
@@ -129,12 +129,14 @@ Nix manages both the desktop app and the bundled
129
130 ### The `t3` command
131
132 -The desktop app includes the `t3` command-line tool. To run it from any
133 -terminal, open **Settings → About** and choose **Install** next to
134 -**t3 command**. On macOS and Linux it adds a `t3` link to a folder on your
135 -`PATH`; on Windows it adds the app's command folder to your `PATH`. Open a new
136 -terminal afterwards. **Remove** takes it off again. If you already have `t3`
137 -from npm, it stays as it is.
132 +The desktop app includes the `t3` command-line tool. A new install sets it up
133 +on first launch; after an update, or any time, choose **Install** next to
134 +**t3 command** in **Settings → About**. On macOS and Linux it adds a `t3` link
135 +in `~/.local/bin` (or `~/bin`); on Windows it adds the app's command folder to
136 +your `PATH`. Open a new terminal afterwards. If the folder is not on your
137 +`PATH`, **Add to PATH** in the welcome setup or **Settings → About** adds one
138 +line to your shell's startup file. **Remove** takes it off, and the app does not
139 +add it again. If you already have another `t3`, it stays as it is.
140
141 ### Windows Subsystem for Linux
142
packages/contracts/src/ipc.ts
+3
@@ -334,6 +334,8 @@ export const DesktopCliCommandStateSchema = Schema.Struct({
334 installedPath: Schema.NullOr(Schema.String),
335 onPath: Schema.Boolean,
336 shadowedBy: Schema.optionalKey(Schema.String),
337 + /** For an installed `t3` that is off PATH: the shell startup file that adds it, and whether it has. */
338 + pathSetup: Schema.optionalKey(Schema.Struct({ file: Schema.String, added: Schema.Boolean })),
339 /** The app's bundled `t3` launcher, which runs without Node or a PATH entry. */
340 launcherPath: Schema.NullOr(Schema.String),
341 });
@@ -1142,6 +1144,7 @@ export interface DesktopBridge {
1144 getState: () => Promise<DesktopCliCommandState>;
1145 install: () => Promise<DesktopCliCommandState>;
1146 uninstall: () => Promise<DesktopCliCommandState>;
1147 + addToPath: () => Promise<DesktopCliCommandState>;
1148 };
1149 webLinks: {
1150 setReady: (ready: boolean) => Promise<void>;
packages/shared/src/shell.ts
+1 -1
@@ -132,7 +132,7 @@ function trimNonEmpty(value: string | null | undefined): string | undefined {
132 return trimmed && trimmed.length > 0 ? trimmed : undefined;
133 }
134
135 -function readUserLoginShell(): string | undefined {
135 +export function readUserLoginShell(): string | undefined {
136 try {
137 return trimNonEmpty(NodeOS.userInfo().shell);
138 } catch {