Skip to content

Commit 3b0093d

Browse files
authored
fix(server): match manual update commands to installed cli (#15539)
1 parent 0ce43a4 commit 3b0093d

14 files changed

Lines changed: 398 additions & 15 deletions

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

Lines changed: 132 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,16 @@
1-
import { assert, it } from "@effect/vitest";
1+
import * as NodeServices from "@effect/platform-node/NodeServices";
2+
import { assert, expect, it } from "@effect/vitest";
3+
import {
4+
HostProcessArguments,
5+
HostProcessExecutablePath,
6+
HostProcessIsExecutable,
7+
HostProcessPlatform,
8+
} from "@t3tools/shared/hostProcess";
9+
import * as Effect from "effect/Effect";
10+
import * as FileSystem from "effect/FileSystem";
11+
import * as Path from "effect/Path";
212

3-
import { formatCliCommand } from "./invocation.ts";
13+
import { formatCliCommand, resolveServerInstallation } from "./invocation.ts";
414

515
it("formats package runner commands from their cache entry paths", () => {
616
for (const [entryPath, expected] of [
@@ -87,3 +97,123 @@ it("formats serve suggestions to match the launching command", () => {
8797
"t3 serve",
8898
);
8999
});
100+
101+
it.layer(NodeServices.layer)("manual server installation ownership", (it) => {
102+
it.effect("recognizes runner caches for both script and executable packages", () =>
103+
Effect.gen(function* () {
104+
const fs = yield* FileSystem.FileSystem;
105+
const path = yield* Path.Path;
106+
const root = yield* fs.makeTempDirectoryScoped();
107+
for (const [relative, kind] of [
108+
["npm/_npx/hash/node_modules/t3/dist/bin.mjs", "npx"],
109+
["npm/_npx/hash/node_modules/@t3code/t3-linux-x64/t3", "npx"],
110+
["pnpm/dlx/hash/node_modules/t3/dist/bin.mjs", "pnpm-dlx"],
111+
[".bun/install/cache/t3/dist/bin.mjs", "bunx"],
112+
] as const) {
113+
const entry = path.join(root, relative);
114+
yield* fs.makeDirectory(path.dirname(entry), { recursive: true });
115+
yield* fs.writeFileString(entry, "");
116+
const installation = yield* resolveServerInstallation.pipe(
117+
Effect.provideService(HostProcessArguments, ["node", entry]),
118+
Effect.provideService(HostProcessExecutablePath, entry),
119+
Effect.provideService(HostProcessIsExecutable, entry.endsWith("/t3")),
120+
);
121+
expect(installation).toEqual({ kind });
122+
}
123+
}),
124+
);
125+
126+
it.effect("requires the npm prefix's bin to point to the running package", () =>
127+
Effect.gen(function* () {
128+
const fs = yield* FileSystem.FileSystem;
129+
const path = yield* Path.Path;
130+
const root = yield* fs.makeTempDirectoryScoped();
131+
const prefix = path.join(root, "bunx-tools");
132+
const packageRoot = path.join(prefix, "lib/node_modules/t3");
133+
const entry = path.join(packageRoot, "dist/bin.mjs");
134+
const globalBin = path.join(prefix, "bin/t3");
135+
yield* fs.makeDirectory(path.dirname(entry), { recursive: true });
136+
yield* fs.makeDirectory(path.dirname(globalBin), { recursive: true });
137+
yield* fs.writeFileString(entry, "");
138+
yield* fs.writeFileString(
139+
path.join(packageRoot, "package.json"),
140+
'{"name":"t3","version":"0.0.45","bin":{"t3":"./dist/bin.mjs"}}',
141+
);
142+
const resolve = resolveServerInstallation.pipe(
143+
Effect.provideService(HostProcessArguments, ["node", entry]),
144+
Effect.provideService(HostProcessIsExecutable, false),
145+
Effect.provideService(HostProcessPlatform, "linux"),
146+
);
147+
expect(yield* resolve).toBeNull();
148+
yield* fs.symlink(entry, globalBin);
149+
expect(yield* resolve).toEqual({ kind: "npm-global", prefix });
150+
yield* fs.remove(globalBin);
151+
yield* fs.writeFileString(globalBin, "an unrelated t3 command");
152+
expect(yield* resolve).toBeNull();
153+
expect(yield* resolve.pipe(Effect.provideService(HostProcessPlatform, "win32"))).toBeNull();
154+
}),
155+
);
156+
157+
it.effect("proves the native executable belongs to the npm launcher", () =>
158+
Effect.gen(function* () {
159+
const fs = yield* FileSystem.FileSystem;
160+
const path = yield* Path.Path;
161+
const root = yield* fs.makeTempDirectoryScoped();
162+
const prefix = path.join(root, "bunx-tools");
163+
const packageRoot = path.join(prefix, "lib/node_modules/t3");
164+
const launcher = path.join(packageRoot, "bin/t3.js");
165+
const entry = path.join(packageRoot, "node_modules/@t3code/t3-linux-x64/t3");
166+
yield* fs.makeDirectory(path.dirname(launcher), { recursive: true });
167+
yield* fs.makeDirectory(path.dirname(entry), { recursive: true });
168+
yield* fs.makeDirectory(path.join(prefix, "bin"));
169+
yield* fs.writeFileString(launcher, "");
170+
yield* fs.writeFileString(entry, "");
171+
yield* fs.writeFileString(
172+
path.join(packageRoot, "package.json"),
173+
'{"name":"t3","version":"0.0.45","bin":{"t3":"./bin/t3.js"},"optionalDependencies":{"@t3code/t3-linux-x64":"0.0.45"}}',
174+
);
175+
yield* fs.symlink(launcher, path.join(prefix, "bin/t3"));
176+
const resolve = resolveServerInstallation.pipe(
177+
Effect.provideService(HostProcessExecutablePath, entry),
178+
Effect.provideService(HostProcessIsExecutable, true),
179+
Effect.provideService(HostProcessPlatform, "linux"),
180+
);
181+
for (const [version, expected] of [
182+
["0.0.44", null],
183+
["0.0.45", { kind: "npm-global", prefix }],
184+
]) {
185+
yield* fs.writeFileString(
186+
path.join(path.dirname(entry), "package.json"),
187+
`{"name":"@t3code/t3-linux-x64","version":"${version}"}`,
188+
);
189+
expect(yield* resolve).toEqual(expected);
190+
}
191+
}),
192+
);
193+
194+
it.effect("leaves local, standalone, missing and unreadable installs unknown", () =>
195+
Effect.gen(function* () {
196+
const fs = yield* FileSystem.FileSystem;
197+
const path = yield* Path.Path;
198+
const root = yield* fs.makeTempDirectoryScoped();
199+
for (const relative of [
200+
"project/node_modules/t3/dist/bin.mjs",
201+
"project/apps/server/dist/bin.mjs",
202+
".t3/runtime/0.0.45/t3",
203+
"missing/dist/bin.mjs",
204+
]) {
205+
const entry = path.join(root, relative);
206+
if (!relative.startsWith("missing")) {
207+
yield* fs.makeDirectory(path.dirname(entry), { recursive: true });
208+
yield* fs.writeFileString(entry, "");
209+
}
210+
expect(
211+
yield* resolveServerInstallation.pipe(
212+
Effect.provideService(HostProcessArguments, ["node", entry]),
213+
Effect.provideService(HostProcessIsExecutable, false),
214+
),
215+
).toBeNull();
216+
}
217+
}),
218+
);
219+
});

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

Lines changed: 72 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,15 @@
11
import * as Effect from "effect/Effect";
2+
import * as FileSystem from "effect/FileSystem";
3+
import * as Path from "effect/Path";
4+
import * as Schema from "effect/Schema";
25

3-
import { HostProcessArguments } from "@t3tools/shared/hostProcess";
6+
import type { ServerInstallation } from "@t3tools/contracts";
7+
import {
8+
HostProcessArguments,
9+
HostProcessExecutablePath,
10+
HostProcessIsExecutable,
11+
HostProcessPlatform,
12+
} from "@t3tools/shared/hostProcess";
413

514
import packageJson from "../../package.json" with { type: "json" };
615

@@ -36,6 +45,68 @@ function detectCliRunner(entryPath: string): CliRunner | null {
3645
return null;
3746
}
3847

48+
const InstallManifest = Schema.Struct({
49+
name: Schema.String,
50+
version: Schema.String,
51+
bin: Schema.optionalKey(Schema.Struct({ t3: Schema.String })),
52+
optionalDependencies: Schema.optionalKey(Schema.Record(Schema.String, Schema.String)),
53+
});
54+
const decodeInstallManifest = Schema.decodeUnknownEffect(Schema.fromJsonString(InstallManifest));
55+
56+
/** Prove the running package and its global bin belong together before suggesting an update. */
57+
export const resolveServerInstallation = Effect.gen(function* () {
58+
const fs = yield* FileSystem.FileSystem;
59+
const path = yield* Path.Path;
60+
const args = yield* HostProcessArguments;
61+
const executable = yield* HostProcessIsExecutable;
62+
const executablePath = yield* HostProcessExecutablePath;
63+
const platform = yield* HostProcessPlatform;
64+
const entry = yield* fs.realPath(executable ? executablePath : (args[1] ?? ""));
65+
const match =
66+
/^(.*)\/lib\/node_modules\/t3\/(?:dist\/bin\.mjs|bin\/t3\.js|node_modules\/@t3code\/t3-[^/]+\/t3)$/.exec(
67+
entry,
68+
);
69+
if (!match) {
70+
const runner = detectCliRunner(entry);
71+
return runner === null
72+
? null
73+
: ({ kind: runner === "pnpm dlx" ? "pnpm-dlx" : runner } satisfies ServerInstallation);
74+
}
75+
// A global prefix can contain runner-like names; prove its ownership first.
76+
// Windows shims and other package managers need their own ownership proof.
77+
if (platform === "win32") return null;
78+
const prefix = match[1] || "/";
79+
if (
80+
prefix.includes("/node_modules/") ||
81+
/\/(?:Cellar|Caskroom)\//i.test(prefix) ||
82+
/\/mise\/installs\/(?!node\/)[^/]+\//.test(prefix)
83+
)
84+
return null;
85+
86+
const packageRoot = path.join(prefix, "lib/node_modules/t3");
87+
const manifest = yield* fs
88+
.readFileString(path.join(packageRoot, "package.json"))
89+
.pipe(Effect.flatMap(decodeInstallManifest));
90+
if (manifest.name !== "t3" || !manifest.bin) return null;
91+
const bin = yield* fs.realPath(path.join(packageRoot, manifest.bin.t3));
92+
const globalBin = yield* fs.realPath(path.join(prefix, "bin/t3"));
93+
if (globalBin !== bin) return null;
94+
if (executable) {
95+
const nativeManifest = yield* fs
96+
.readFileString(path.join(path.dirname(entry), "package.json"))
97+
.pipe(Effect.flatMap(decodeInstallManifest));
98+
if (
99+
manifest.bin.t3 !== "./bin/t3.js" ||
100+
manifest.optionalDependencies?.[nativeManifest.name] !== nativeManifest.version ||
101+
nativeManifest.version !== manifest.version
102+
)
103+
return null;
104+
} else if (bin !== entry) {
105+
return null;
106+
}
107+
return { kind: "npm-global", prefix } satisfies ServerInstallation;
108+
}).pipe(Effect.orElseSucceed(() => null));
109+
39110
/**
40111
* The `t3` package spec to suggest. The literal spec the user typed (e.g.
41112
* `t3@nightly`) is resolved away before our process starts, so re-derive it

‎apps/server/src/environment/ServerEnvironment.test.ts‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,12 @@ import * as PlatformError from "effect/PlatformError";
1010
import * as Schema from "effect/Schema";
1111

1212
import { DEFAULT_SIGNAL_EXPORT } from "@t3tools/shared/observability";
13+
import {
14+
HostProcessArguments,
15+
HostProcessEnvironment,
16+
HostProcessIsExecutable,
17+
HostProcessPlatform,
18+
} from "@t3tools/shared/hostProcess";
1319
import * as OtelEnvironment from "@t3tools/shared/otelEnvironment";
1420

1521
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
@@ -79,6 +85,47 @@ const makeServerConfig = Effect.fn(function* (baseDir: string) {
7985
});
8086

8187
it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
88+
it.effect("publishes proven install ownership only for manually updated servers", () =>
89+
Effect.gen(function* () {
90+
const fs = yield* FileSystem.FileSystem;
91+
const baseDir = yield* fs.makeTempDirectoryScoped();
92+
const prefix = `${baseDir}/node`;
93+
const entry = `${prefix}/lib/node_modules/t3/dist/bin.mjs`;
94+
yield* fs.makeDirectory(`${prefix}/lib/node_modules/t3/dist`, { recursive: true });
95+
yield* fs.makeDirectory(`${prefix}/bin`, { recursive: true });
96+
yield* fs.writeFileString(entry, "");
97+
yield* fs.writeFileString(
98+
`${prefix}/lib/node_modules/t3/package.json`,
99+
'{"name":"t3","version":"0.0.45","bin":{"t3":"./dist/bin.mjs"}}',
100+
);
101+
yield* fs.symlink(entry, `${prefix}/bin/t3`);
102+
const config = yield* makeServerConfig(baseDir);
103+
yield* fs.makeDirectory(config.stateDir, { recursive: true });
104+
for (const mode of ["web", "desktop"] as const) {
105+
const descriptor = yield* Effect.gen(function* () {
106+
const environment = yield* ServerEnvironment.ServerEnvironment;
107+
return yield* environment.getDescriptor;
108+
}).pipe(
109+
Effect.provide(
110+
ServerEnvironment.layer.pipe(
111+
Layer.provide(emptySecretStoreLayer),
112+
Layer.provide(ServerConfig.layer({ ...config, mode })),
113+
),
114+
),
115+
Effect.provideService(HostProcessArguments, ["node", entry]),
116+
Effect.provideService(HostProcessIsExecutable, false),
117+
Effect.provideService(HostProcessPlatform, "linux"),
118+
Effect.provideService(HostProcessEnvironment, {}),
119+
);
120+
expect(descriptor.capabilities.serverInstallation).toEqual(
121+
mode === "web" ? { kind: "npm-global", prefix } : undefined,
122+
);
123+
expect(descriptor.capabilities.serverSelfUpdate).toBe(
124+
mode === "web" ? undefined : "desktop-managed",
125+
);
126+
}
127+
}),
128+
);
82129
it.effect.each([
83130
{ name: "missing", content: undefined },
84131
{ name: "empty", content: "" },

‎apps/server/src/environment/ServerEnvironment.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import * as Schema from "effect/Schema";
1515

1616
import packageJson from "../../package.json" with { type: "json" };
1717
import * as ServerSecretStore from "../auth/ServerSecretStore.ts";
18+
import { resolveServerInstallation } from "../cli/invocation.ts";
1819
import { readAgentActivityPublishingActive } from "../cloud/config.ts";
1920
import { resolveServerSelfUpdateCapability } from "../cloud/selfUpdate.ts";
2021
import { resolveServiceLauncherMode } from "../cloud/serviceLauncherClient.ts";
@@ -196,6 +197,7 @@ export const make = Effect.gen(function* () {
196197
desktopManaged: serverConfig.mode === "desktop",
197198
launcherManaged: launcher.managed,
198199
});
200+
const serverInstallation = serverSelfUpdate === null ? yield* resolveServerInstallation : null;
199201
// Static is correct: the control fd is known at bootstrap, and the desktop
200202
// app and its bundled server ship in one artifact, so a present fd means
201203
// the app speaks the requestDesktopUpdate protocol. WSL backends never get
@@ -248,6 +250,7 @@ export const make = Effect.gen(function* () {
248250
environmentIcon: true,
249251
projectCloneTracking: true,
250252
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
253+
...(serverInstallation === null ? {} : { serverInstallation }),
251254
// V2 restart recovery uses the environment-owned opt-in. The old
252255
// per-update request flag is not wired into the V2 update RPC path.
253256
...(serverSelfUpdate === "boot-service" || desktopAppUpdate

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2992,6 +2992,7 @@ export default function ChatView(props: ChatViewProps) {
29922992
}, [setDismissedVersionMismatchKey, versionMismatchDismissKey]);
29932993
const serverUpdateEnvironmentId = activeThread?.environmentId ?? null;
29942994
const versionMismatchSelfUpdate = resolveServerSelfUpdateCapability(serverConfig);
2995+
const versionMismatchInstallation = serverConfig?.environment.capabilities.serverInstallation;
29952996
const versionMismatchDesktopAppUpdate = supportsDesktopAppUpdate(serverConfig);
29962997
const versionMismatchThreadContinuation = supportsServerUpdateThreadContinuation(serverConfig);
29972998
const serverUpdateState = useAtomValue(
@@ -3113,6 +3114,7 @@ export default function ChatView(props: ChatViewProps) {
31133114
environmentId={serverUpdateEnvironmentId}
31143115
serverLabel={versionMismatchServerLabel}
31153116
selfUpdate={versionMismatchSelfUpdate}
3117+
installation={versionMismatchInstallation}
31163118
desktopAppUpdate={versionMismatchDesktopAppUpdate}
31173119
threadContinuation={versionMismatchThreadContinuation}
31183120
targetVersion={versionMismatch.clientVersion}
@@ -3154,6 +3156,7 @@ export default function ChatView(props: ChatViewProps) {
31543156
versionMismatchDismissKey,
31553157
serverUpdateEnvironmentId,
31563158
versionMismatchSelfUpdate,
3159+
versionMismatchInstallation,
31573160
versionMismatchDesktopAppUpdate,
31583161
versionMismatchThreadContinuation,
31593162
versionMismatchServerLabel,

0 commit comments

Comments
 (0)