Skip to content

Commit 7eca0ed

Browse files
fix(web): hand-started t3 servers get an update command that updates them (#29462)
Co-authored-by: Julius Marminge <[email protected]>
1 parent 719707c commit 7eca0ed

13 files changed

Lines changed: 153 additions & 40 deletions

File tree

‎apps/server/src/cli/invocation.test.ts‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,43 @@ it.layer(NodeServices.layer)("manual server installation ownership", (it) => {
291291
}),
292292
);
293293

294+
it.effect("names the launcher symlink that started a downloaded runtime", () =>
295+
Effect.gen(function* () {
296+
const fs = yield* FileSystem.FileSystem;
297+
const path = yield* Path.Path;
298+
const root = yield* fs.realPath(yield* fs.makeTempDirectoryScoped());
299+
// The install script's launcher names ~/.t3, which here links to a home elsewhere.
300+
const executable = path.join(root, "data/t3/runtime/versions/1.0.0/t3");
301+
const launcher = path.join(root, "bin/t3");
302+
const copy = path.join(root, "bin/t3-copy");
303+
yield* fs.makeDirectory(path.dirname(executable), { recursive: true });
304+
yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
305+
yield* fs.writeFileString(executable, "", { mode: 0o755 });
306+
yield* fs.writeFileString(copy, "", { mode: 0o755 });
307+
yield* fs.symlink(path.join(root, "data/t3"), path.join(root, ".t3"));
308+
yield* fs.symlink(path.join(root, ".t3/runtime/versions/1.0.0/t3"), launcher);
309+
// Earlier PATH entries hold a directory and a non-executable file named t3.
310+
yield* fs.makeDirectory(path.join(root, "shadow-dir/t3"), { recursive: true });
311+
yield* fs.makeDirectory(path.join(root, "shadow-file"));
312+
yield* fs.writeFileString(path.join(root, "shadow-file/t3"), "");
313+
const resolve = (invokedAs: string) =>
314+
resolveServerInstallation.pipe(
315+
Effect.provideService(HostProcess.ExecutablePath, executable),
316+
Effect.provideService(HostProcess.IsExecutable, true),
317+
Effect.provideService(HostProcess.InvokedAs, invokedAs),
318+
Effect.provideService(HostProcess.WorkingDirectory, root),
319+
Effect.provideService(HostProcess.Environment, { PATH: "shadow-dir:shadow-file:bin" }),
320+
Effect.provideService(HostProcess.Platform, "linux"),
321+
);
322+
const baseDir = path.join(root, ".t3");
323+
324+
expect(yield* resolve("t3")).toEqual({ kind: "t3-launcher", launcher, baseDir });
325+
expect(yield* resolve(launcher)).toEqual({ kind: "t3-launcher", launcher, baseDir });
326+
expect(yield* resolve(executable)).toBeNull();
327+
expect(yield* resolve(copy)).toBeNull();
328+
}),
329+
);
330+
294331
it.effect("leaves local, standalone, missing and unreadable installs unknown", () =>
295332
Effect.gen(function* () {
296333
const fs = yield* FileSystem.FileSystem;

‎apps/server/src/cli/invocation.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,9 @@ import * as HostProcess from "@t3tools/shared/HostProcess";
99
import { resolveCommandPath } from "@t3tools/shared/shell";
1010

1111
import packageJson from "../../package.json" with { type: "json" };
12+
import { resolveLauncherPath } from "../cloud/pinnedRuntime.ts";
13+
14+
const PINNED_RUNTIME_ENTRY = /^(.*)\/runtime\/versions\/[^/]+\/t3$/;
1215

1316
export type CliRunner = "npx" | "pnpm dlx" | "bunx";
1417

@@ -67,6 +70,21 @@ export const resolveServerInstallation = Effect.gen(function* () {
6770
const path = yield* Path.Path;
6871
const platform = yield* HostProcess.Platform;
6972
const entry = yield* fs.realPath(yield* resolveEntryPath);
73+
const runtime = PINNED_RUNTIME_ENTRY.exec(entry);
74+
if (runtime) {
75+
const launcher = yield* resolveLauncherPath;
76+
if (launcher === undefined) return null;
77+
// Fails for a runtime started directly, as SSH launches do, or through a copy.
78+
const link = yield* fs.readLink(launcher);
79+
// Keep the home as the link spells it; `t3 update` only repoints links into that spelling.
80+
const linked = PINNED_RUNTIME_ENTRY.exec(path.resolve(path.dirname(launcher), link));
81+
if (!linked || (yield* fs.realPath(linked[1] || "/")) !== (runtime[1] || "/")) return null;
82+
return {
83+
kind: "t3-launcher",
84+
launcher,
85+
baseDir: linked[1] || "/",
86+
} satisfies ServerInstallation;
87+
}
7088
const match = /^(.*)\/lib\/node_modules\/t3\/(?:dist\/bin\.mjs|bin\/t3\.mjs)$/.exec(entry);
7189
if (!match) {
7290
const runner = detectCliRunner(entry);

‎apps/server/src/cli/uninstall.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,11 @@ import {
1616
generatedWindowsShimTarget,
1717
isVersionExecutable,
1818
pinnedRuntimeVersionsDir,
19+
resolveLauncherPath,
1920
} from "../cloud/pinnedRuntime.ts";
2021
import { projectLocationFlags, resolveCliAuthConfig } from "./config.ts";
2122
import * as CliService from "./service.ts";
22-
import { findWindowsShim, resolveLauncherPath } from "./update.ts";
23+
import { findWindowsShim } from "./update.ts";
2324

2425
export class CliUninstallError extends Schema.TaggedError<CliUninstallError>()(
2526
"CliUninstallError",

‎apps/server/src/cli/update.test.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,12 +17,15 @@ import { afterEach, vi } from "vite-plus/test";
1717

1818
import packageJson from "../../package.json" with { type: "json" };
1919
import * as BootService from "../cloud/bootService.ts";
20-
import { pinnedRuntimePaths, prunePinnedRuntimes } from "../cloud/pinnedRuntime.ts";
20+
import {
21+
pinnedRuntimePaths,
22+
prunePinnedRuntimes,
23+
resolveLauncherPath,
24+
} from "../cloud/pinnedRuntime.ts";
2125
import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
2226
import * as ProcessRunner from "../processRunner.ts";
2327
import {
2428
repointLauncher,
25-
resolveLauncherPath,
2629
resolveMirrorVersion,
2730
resolveNewestVersion,
2831
runUpdate,
@@ -411,7 +414,7 @@ it.layer(NodeServices.layer)("t3 update launcher", (it) => {
411414
const root = yield* fs.makeTempDirectoryScoped({ prefix: "t3-update-" });
412415
const launcher = path.join(root, "bin/t3");
413416
yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
414-
yield* fs.writeFileString(launcher, "");
417+
yield* fs.writeFileString(launcher, "", { mode: 0o755 });
415418

416419
const bare = yield* resolveLauncherPath.pipe(
417420
Effect.provideService(HostProcess.InvokedAs, "t3"),

‎apps/server/src/cli/update.ts‎

Lines changed: 1 addition & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ import {
3232
pinnedRuntimeVersionsDir,
3333
prunePinnedRuntimes,
3434
recordPinnedRuntimeLauncher,
35+
resolveLauncherPath,
3536
windowsShimTarget,
3637
} from "../cloud/pinnedRuntime.ts";
3738
import { compareExactServiceVersions, isExactServiceVersion } from "../cloud/serviceProtocol.ts";
@@ -194,28 +195,6 @@ export const repointLauncher = Effect.fn("cli.update.repoint_launcher")(function
194195
return Option.some(input.launchedAs);
195196
});
196197

197-
/** Node preserves argv0's spelling; resolve bare names on PATH to find the launcher symlink. */
198-
export const resolveLauncherPath = Effect.gen(function* () {
199-
const path = yield* Path.Path;
200-
const fs = yield* FileSystem.FileSystem;
201-
const invokedAs = yield* HostProcess.InvokedAs;
202-
const cwd = yield* HostProcess.WorkingDirectory;
203-
const environment = yield* HostProcess.Environment;
204-
const platform = yield* HostProcess.Platform;
205-
if (invokedAs.includes("/") || invokedAs.includes("\\")) {
206-
return path.resolve(cwd, invokedAs);
207-
}
208-
const delimiter = platform === "win32" ? ";" : ":";
209-
for (const directory of (environment["PATH"] ?? "").split(delimiter)) {
210-
if (directory.length === 0) continue;
211-
const candidate = path.join(directory, invokedAs);
212-
if (yield* fs.exists(candidate).pipe(Effect.orElseSucceed(() => false))) {
213-
return candidate;
214-
}
215-
}
216-
return undefined;
217-
});
218-
219198
/** Windows executables see their own path, so find the installer shim by matching t3.cmd targets on PATH. */
220199
export const findWindowsShim = Effect.fn("cli.update.find_windows_shim")(function* (
221200
executablePath: string,

‎apps/server/src/cloud/pinnedRuntime.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -447,6 +447,34 @@ export function launcherOwnsVersionsDir(
447447
return relative.length > 0 && !relative.startsWith("..") && !path.isAbsolute(relative);
448448
}
449449

450+
/** Node preserves argv0's spelling; resolve bare names on PATH to find the launcher symlink. */
451+
export const resolveLauncherPath = Effect.gen(function* () {
452+
const path = yield* Path.Path;
453+
const fs = yield* FileSystem.FileSystem;
454+
const invokedAs = yield* HostProcess.InvokedAs;
455+
const cwd = yield* HostProcess.WorkingDirectory;
456+
const environment = yield* HostProcess.Environment;
457+
const platform = yield* HostProcess.Platform;
458+
if (invokedAs.includes("/") || invokedAs.includes("\\")) {
459+
return path.resolve(cwd, invokedAs);
460+
}
461+
const delimiter = platform === "win32" ? ";" : ":";
462+
for (const directory of (environment["PATH"] ?? "").split(delimiter)) {
463+
if (directory.length === 0) continue;
464+
const candidate = path.resolve(cwd, directory, invokedAs);
465+
const info = yield* fs.stat(candidate).pipe(Effect.option);
466+
// Like the shell, pass over directories and non-executable files named the same.
467+
if (
468+
Option.isSome(info) &&
469+
info.value.type === "File" &&
470+
(platform === "win32" || (info.value.mode & 0o111) !== 0)
471+
) {
472+
return candidate;
473+
}
474+
}
475+
return undefined;
476+
});
477+
450478
/**
451479
* `t3 update` repoints the launcher it was started through, which may be on neither PATH nor the
452480
* default bin dir. Unrecorded, the next prune would remove the runtime it now points at.

‎apps/server/src/server.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
1616
import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
1717
import * as NodeServices from "@effect/platform-node/NodeServices";
1818
import { EnvironmentHttpApi, type RepositoryIdentity } from "@t3tools/contracts";
19+
import * as HostProcess from "@t3tools/shared/HostProcess";
1920
import * as Cause from "effect/Cause";
2021
import * as Duration from "effect/Duration";
2122
import * as Deferred from "effect/Deferred";
@@ -36,6 +37,7 @@ import {
3637
keepIdleConnections,
3738
rejectRequestsUntilServing,
3839
} from "./httpResponseErrorGuard.ts";
40+
import { resolveLauncherPath } from "./cloud/pinnedRuntime.ts";
3941
import { fixPath } from "./os-jank.ts";
4042
import * as Ws from "./ws.ts";
4143
import * as AgentScopeLive from "./process/agentScope.ts";
@@ -877,6 +879,8 @@ const layerMakeServer = Layer.unwrap(
877879
const routesReady = yield* Deferred.make<void>();
878880
const layerLauncher = ServiceLauncherClient.layer;
879881

882+
// fixPath rewrites PATH, so pin the launcher the shell chose before it does.
883+
const invokedAs = (yield* resolveLauncherPath) ?? (yield* HostProcess.InvokedAs);
880884
yield* fixPath({ shellEnvironmentPrepared: config.shellEnvironmentPrepared });
881885

882886
const layerHttpListening = Layer.effectDiscard(
@@ -1290,6 +1294,7 @@ const layerMakeServer = Layer.unwrap(
12901294
Layer.provide(VcsProcess.layer),
12911295
Layer.provideMerge(AgentScopeLive.layer),
12921296
Layer.provideMerge(layerPlatformServices),
1297+
Layer.provide(Layer.succeed(HostProcess.InvokedAs, invokedAs)),
12931298
);
12941299
}),
12951300
).pipe(Layer.provide(ProcessRunner.layer));

‎apps/web/src/components/ServerUpdateAction.tsx‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -276,17 +276,17 @@ export function ServerUpdateAction({
276276
const canUpdate = useAtomValue(sessionStateAtom, canUpdateServer);
277277
const updatesDenial = managedUpdatesDenial(useManagedPolicy(environmentId));
278278
const update = useServerUpdate();
279+
const updatesInstall =
280+
installation?.kind === "npm-global" || installation?.kind === "t3-launcher";
279281
const { copyToClipboard } = useCopyToClipboard<{ command: string }>({
280-
target: installation?.kind === "npm-global" ? "update command" : "relaunch command",
282+
target: updatesInstall ? "update command" : "relaunch command",
281283
onCopy: ({ command }) => {
282284
toastManager.add({
283285
type: "success",
284-
title:
285-
installation?.kind === "npm-global" ? "Update command copied" : "Relaunch command copied",
286-
description:
287-
installation?.kind === "npm-global"
288-
? `Run \`${command}\` on ${serverLabel}, then restart t3 with your usual options.`
289-
: `Stop t3 on ${serverLabel}, then relaunch with \`${command}\` using the same subcommand and options. This does not update an installed t3 command.`,
286+
title: updatesInstall ? "Update command copied" : "Relaunch command copied",
287+
description: updatesInstall
288+
? `Run \`${command}\` on ${serverLabel}, then restart t3 with your usual options.`
289+
: `Stop t3 on ${serverLabel}, then relaunch with \`${command}\` using the same subcommand and options. This does not update an installed t3 command.`,
290290
});
291291
},
292292
onError: (error) => {
@@ -353,7 +353,7 @@ export function ServerUpdateAction({
353353
selfUpdate === null ? manualServerUpdateCommand(targetVersion, installation) : null;
354354
const actionLabel =
355355
manualCommand !== null
356-
? installation?.kind === "npm-global"
356+
? updatesInstall
357357
? "Copy update command"
358358
: "Copy relaunch command"
359359
: label;

‎apps/web/src/versionSkew.test.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,27 @@ const MISMATCH_HINT =
2020
"Version mismatch. Try syncing the client and server to the same T3 Code version.";
2121

2222
describe("versionSkew", () => {
23-
it("updates only the proven npm prefix and safely quotes its path", () => {
23+
it("updates only the proven install and safely quotes its paths", () => {
2424
expect(manualServerUpdateCommand("0.0.45", { kind: "npm-global", prefix: "/opt/node" })).toBe(
2525
"npm install --global --prefix '/opt/node' [email protected]",
2626
);
2727
expect(
2828
manualServerUpdateCommand("0.0.45", { kind: "npm-global", prefix: "/opt/maria's node" }),
2929
).toBe("npm install --global --prefix '/opt/maria'\\''s node' [email protected]");
30+
expect(
31+
manualServerUpdateCommand("0.0.45", {
32+
kind: "t3-launcher",
33+
launcher: "t3",
34+
baseDir: "/home/u/.t3",
35+
}),
36+
).toBe("'t3' update --base-dir '/home/u/.t3' 0.0.45");
37+
expect(
38+
manualServerUpdateCommand("0.0.45", {
39+
kind: "t3-launcher",
40+
launcher: "/opt/maria's bin/t3",
41+
baseDir: "/data/t3 home",
42+
}),
43+
).toBe("'/opt/maria'\\''s bin/t3' update --base-dir '/data/t3 home' 0.0.45");
3044
});
3145
beforeEach(() => {
3246
branding.APP_VERSION = "0.0.34";

‎apps/web/src/versionSkew.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,9 +99,13 @@ export function manualServerUpdateCommand(
9999
targetVersion: string,
100100
installation?: ServerInstallation,
101101
): string {
102+
const quote = (value: string) => `'${value.replaceAll("'", "'\\''")}'`;
102103
if (installation?.kind === "npm-global") {
103-
const prefix = `'${installation.prefix.replaceAll("'", "'\\''")}'`;
104-
return `npm install --global --prefix ${prefix} t3@${targetVersion}`;
104+
return `npm install --global --prefix ${quote(installation.prefix)} t3@${targetVersion}`;
105+
}
106+
if (installation?.kind === "t3-launcher") {
107+
// An inherited T3CODE_HOME would otherwise send the update to a home the launcher is not in.
108+
return `${quote(installation.launcher)} update --base-dir ${quote(installation.baseDir)} ${targetVersion}`;
105109
}
106110
const runner =
107111
installation?.kind === "pnpm-dlx" ? "pnpm dlx" : installation?.kind === "bunx" ? "bunx" : "npx";

0 commit comments

Comments
 (0)