The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 10:45 UTC
fix(updates): version checks respect your configured npm registry (#27847)
Co-authored-by: Scott Van Vliet <782486+svanvliet@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Oct 30, 2026 at 16:38 UTC
d2d1e4f50ef856f940d91858915368500657b0b7
22 files changed
+821
-183
apps/server/src/auth/RpcAuthorization.ts
+1
@@ -61,6 +61,7 @@ export const RPC_REQUIRED_SCOPES = {
61
[WS_METHODS.projectsMutate]: AuthOrchestrationOperateScope,
62
[WS_METHODS.serverProbe]: AuthOrchestrationReadScope,
63
[WS_METHODS.serverGetConfig]: AuthOrchestrationReadScope,
64
+ [WS_METHODS.serverGetNpmRelease]: AuthOrchestrationReadScope,
65
[WS_METHODS.serverRefreshProviders]: AuthOrchestrationReadScope,
66
[WS_METHODS.serverUpdateProvider]: AuthProvidersManageScope,
67
[WS_METHODS.providerAuthStart]: AuthProvidersManageScope,
apps/server/src/cloud/npmRelease.test.ts
new
+198
@@ -0,0 +1,198 @@
1
+import * as NodeServices from "@effect/platform-node/NodeServices";
2
+import { expect, it } from "@effect/vitest";
3
+import { ServerNpmReleaseError } from "@t3tools/contracts";
4
+import * as HostProcess from "@t3tools/shared/HostProcess";
5
+import * as Deferred from "effect/Deferred";
6
+import * as Effect from "effect/Effect";
7
+import * as FileSystem from "effect/FileSystem";
8
+import * as Path from "effect/Path";
9
+import * as Queue from "effect/Queue";
10
+import * as Fiber from "effect/Fiber";
11
+import { HttpClient, HttpClientResponse } from "effect/http";
12
+import * as Result from "effect/Result";
13
+import * as TestClock from "effect/testing/TestClock";
14
+import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
15
+
16
+import * as ProcessRunner from "../processRunner.ts";
17
+import * as NpmRelease from "./npmRelease.ts";
18
+
19
+const version = "0.1.5-nightly.20261030.1";
20
+const output = (stdout: string, code = 0): ProcessRunner.ProcessRunOutput => ({
21
+ stdout,
22
+ stderr: "",
23
+ code: ChildProcessSpawner.ExitCode(code),
24
+ timedOut: false,
25
+ stdoutTruncated: false,
26
+ stderrTruncated: false,
27
+ stdoutInvalidUtf8: false,
28
+ stderrInvalidUtf8: false,
29
+});
30
+
31
+const noPublicRegistry = HttpClient.make(() =>
32
+ Effect.die("a configured npm lookup must not fall back to public npm"),
33
+);
34
+// A fake npm on PATH decides whether npm counts as installed.
35
+const makeService = Effect.fnUntraced(function* (
36
+ run: ProcessRunner.ProcessRunner["Service"]["run"],
37
+ publicRegistry: HttpClient.HttpClient = noPublicRegistry,
38
+ npmInstalled = true,
39
+) {
40
+ const fs = yield* FileSystem.FileSystem;
41
+ const path = yield* Path.Path;
42
+ const npmBin = yield* fs.makeTempDirectoryScoped({ prefix: "t3-npm-release-" });
43
+ for (const name of ["npm", "npm.cmd"]) {
44
+ yield* fs.writeFileString(path.join(npmBin, name), "", { mode: 0o755 });
45
+ }
46
+ return yield* NpmRelease.make().pipe(
47
+ Effect.provideService(ProcessRunner.ProcessRunner, { run }),
48
+ Effect.provideService(HttpClient.HttpClient, publicRegistry),
49
+ Effect.provideService(HostProcess.Environment, {
50
+ PATH: npmInstalled ? npmBin : "",
51
+ PATHEXT: ".CMD",
52
+ }),
53
+ );
54
+}, Effect.provide(NodeServices.layer));
55
+
56
+it.effect.each([
57
+ {
58
+ spec: version,
59
+ stdout: JSON.stringify({ version, t3code: { databaseMigration: 42 } }),
60
+ migration: 42,
61
+ },
62
+ {
63
+ spec: "nightly",
64
+ stdout: JSON.stringify([{ version, t3code: { databaseMigration: 42 } }]),
65
+ migration: 42,
66
+ },
67
+ { spec: "latest", stdout: JSON.stringify(version), migration: undefined },
68
+])("reads $spec through npm and retains migration compatibility metadata", (fixture) =>
69
+ Effect.gen(function* () {
70
+ const calls: ProcessRunner.ProcessRunInput[] = [];
71
+ const service = yield* makeService((input) => {
72
+ calls.push(input);
73
+ return Effect.succeed(output(fixture.stdout));
74
+ });
75
+ const expected = {
76
+ version,
77
+ ...(fixture.migration === undefined ? {} : { databaseMigration: fixture.migration }),
78
+ };
79
+ expect(yield* service.get({ spec: fixture.spec })).toEqual(expected);
80
+ expect(yield* service.get({ spec: fixture.spec })).toEqual(expected);
81
+ expect(calls).toHaveLength(1);
82
+ expect(calls[0]).toMatchObject({
83
+ command: expect.stringMatching(/[/\\]npm(?:\.cmd)?$/i),
84
+ args: ["view", "--global", "--json", `t3@${fixture.spec}`, "version", "t3code"],
85
+ maxOutputBytes: 256 * 1024,
86
+ });
87
+ yield* TestClock.adjust("1 minute");
88
+ expect(yield* service.get({ spec: fixture.spec })).toEqual(expected);
89
+ expect(calls).toHaveLength(2);
90
+ }),
91
+);
92
+
93
+it.effect("treats a registry 404 as unpublished without trying another registry", () =>
94
+ Effect.gen(function* () {
95
+ const service = yield* makeService(() =>
96
+ Effect.succeed(output('{"error":{"code":"E404"}}', 1)),
97
+ );
98
+ expect(yield* service.get({ spec: version })).toBeNull();
99
+ }),
100
+);
101
+
102
+const spawnFailure = () =>
103
+ Effect.fail(
104
+ new ProcessRunner.ProcessSpawnError({
105
+ command: "npm",
106
+ argumentCount: 6,
107
+ cause: new Error("EACCES"),
108
+ }),
109
+ );
110
+
111
+it.effect.each([
112
+ output("not json"),
113
+ output('{"error":{"code":"E401","detail":"sensitive"}}', 1),
114
+ output('{"version":"9.9.9"}'),
115
+ output("[]"),
116
+ output("", 9009),
117
+ { ...output(JSON.stringify({ version })), stdoutTruncated: true },
118
+ { ...output(JSON.stringify({ version })), timedOut: true },
119
+ "spawn failure",
120
+] as const)("reports an unavailable lookup rather than an unpublished release: %j", (result) =>
121
+ Effect.gen(function* () {
122
+ const service = yield* makeService(() =>
123
+ result === "spawn failure" ? spawnFailure() : Effect.succeed(result),
124
+ );
125
+ const found = yield* service.get({ spec: version }).pipe(Effect.result);
126
+ expect(Result.isFailure(found)).toBe(true);
127
+ if (Result.isFailure(found)) {
128
+ expect(found.failure).toBeInstanceOf(ServerNpmReleaseError);
129
+ expect(found.failure.message).not.toContain("sensitive");
130
+ }
131
+ }),
132
+);
133
+
134
+it.effect("falls back to public npm only when npm is not installed", () =>
135
+ Effect.gen(function* () {
136
+ const urls: string[] = [];
137
+ const service = yield* makeService(
138
+ () => Effect.die("npm is not installed"),
139
+ HttpClient.make((request) => {
140
+ urls.push(request.url);
141
+ const response = request.url.endsWith("/nightly")
142
+ ? new Response(JSON.stringify({ version, t3code: { databaseMigration: 42 } }))
143
+ : request.url.endsWith("/latest")
144
+ ? new Response(new ReadableStream())
145
+ : new Response("{}", { status: 404 });
146
+ return Effect.succeed(HttpClientResponse.fromWeb(request, response));
147
+ }),
148
+ false,
149
+ );
150
+ expect(yield* service.get({ spec: "nightly" })).toEqual({ version, databaseMigration: 42 });
151
+ expect(yield* service.get({ spec: "9.9.9" })).toBeNull();
152
+ const stalled = yield* service.get({ spec: "latest" }).pipe(Effect.result, Effect.forkChild);
153
+ yield* TestClock.adjust("15 seconds");
154
+ expect(Result.isFailure(yield* Fiber.join(stalled))).toBe(true);
155
+ expect(urls).toEqual([
156
+ "https://registry.npmjs.org/t3/nightly",
157
+ "https://registry.npmjs.org/t3/9.9.9",
158
+ "https://registry.npmjs.org/t3/latest",
159
+ ]);
160
+ }),
161
+);
162
+
163
+it.effect("runs at most two npm lookups at once", () =>
164
+ Effect.gen(function* () {
165
+ const started = yield* Queue.unbounded<void>();
166
+ const release = yield* Deferred.make<void>();
167
+ let running = 0;
168
+ let peak = 0;
169
+ const service = yield* makeService(() =>
170
+ Effect.gen(function* () {
171
+ peak = Math.max(peak, ++running);
172
+ yield* Queue.offer(started, undefined);
173
+ yield* Deferred.await(release);
174
+ running--;
175
+ return output('{"error":{"code":"E404"}}', 1);
176
+ }),
177
+ );
178
+ const lookups = yield* Effect.forEach(
179
+ ["1.0.0", "1.0.1", "1.0.2"],
180
+ (spec) => service.get({ spec }),
181
+ { concurrency: "unbounded" },
182
+ ).pipe(Effect.forkChild);
183
+ yield* Queue.take(started);
184
+ yield* Queue.take(started);
185
+ yield* Deferred.succeed(release, undefined);
186
+ expect(yield* Fiber.join(lookups)).toEqual([null, null, null]);
187
+ expect(peak).toBe(2);
188
+ }),
189
+);
190
+
191
+it.effect.each(["--registry=https://example.com", "../other", "other-package@latest", "*", ""])(
192
+ "rejects invalid release specs before spawning npm: %s",
193
+ (spec) =>
194
+ Effect.gen(function* () {
195
+ const service = yield* makeService(() => Effect.die("invalid specs must not spawn npm"));
196
+ expect(Result.isFailure(yield* service.get({ spec }).pipe(Effect.result))).toBe(true);
197
+ }),
198
+);
apps/server/src/cloud/npmRelease.ts
new
+132
@@ -0,0 +1,132 @@
1
+import {
2
+ ServerNpmReleaseError,
3
+ ServerNpmReleaseInput,
4
+ type ServerNpmRelease,
5
+} from "@t3tools/contracts";
6
+import { npmReleaseDatabaseMigration } from "@t3tools/shared/cliRelease";
7
+import { resolveCommandPath } from "@t3tools/shared/shell";
8
+import * as Cache from "effect/Cache";
9
+import * as Context from "effect/Context";
10
+import * as Duration from "effect/Duration";
11
+import * as Effect from "effect/Effect";
12
+import * as Layer from "effect/Layer";
13
+import * as Option from "effect/Option";
14
+import * as Schema from "effect/Schema";
15
+import * as Semaphore from "effect/Semaphore";
16
+import { FetchHttpClient, HttpClient } from "effect/http";
17
+
18
+import * as ProcessRunner from "../processRunner.ts";
19
+
20
+const Version = Schema.String.check(Schema.isPattern(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/));
21
+const Manifest = Schema.Struct({ version: Version, t3code: Schema.optionalKey(Schema.Unknown) });
22
+// npm prints a bare version string when the release has no `t3code` field.
23
+const decodeManifest = Schema.decodeUnknownOption(
24
+ Schema.fromJsonString(Schema.Union([Manifest, Schema.Tuple([Manifest]), Version])),
25
+);
26
+const decodeError = Schema.decodeUnknownOption(
27
+ Schema.fromJsonString(Schema.Struct({ error: Schema.Struct({ code: Schema.String }) })),
28
+);
29
+const decodeInput = Schema.decodeUnknownEffect(ServerNpmReleaseInput);
30
+
31
+export class NpmRelease extends Context.Service<
32
+ NpmRelease,
33
+ {
34
+ readonly get: (
35
+ input: ServerNpmReleaseInput,
36
+ ) => Effect.Effect<ServerNpmRelease | null, ServerNpmReleaseError>;
37
+ }
38
+>()("t3/cloud/npmRelease") {}
39
+
40
+function toRelease(spec: string, json: string) {
41
+ const decoded = Option.getOrUndefined(decodeManifest(json));
42
+ const manifest =
43
+ typeof decoded === "string"
44
+ ? { version: decoded }
45
+ : decoded && ("version" in decoded ? decoded : decoded[0]);
46
+ if (!manifest || (spec !== "latest" && spec !== "nightly" && manifest.version !== spec)) {
47
+ return Effect.fail(
48
+ new ServerNpmReleaseError({ reason: "npm returned invalid release metadata." }),
49
+ );
50
+ }
51
+ const databaseMigration = npmReleaseDatabaseMigration(manifest);
52
+ return Effect.succeed({
53
+ version: manifest.version,
54
+ ...(databaseMigration === undefined ? {} : { databaseMigration }),
55
+ });
56
+}
57
+
58
+export const make = Effect.fn("NpmRelease.make")(function* () {
59
+ const runner = yield* ProcessRunner.ProcessRunner;
60
+ const http = yield* HttpClient.HttpClient;
61
+ const lookupPublic = Effect.fn("NpmRelease.lookupPublic")(function* (spec: string) {
62
+ const unreachable = new ServerNpmReleaseError({
63
+ reason: "npm is not installed and the public npm registry could not be reached.",
64
+ });
65
+ const json = yield* Effect.gen(function* () {
66
+ const response = yield* http.get(`https://registry.npmjs.org/t3/${spec}`);
67
+ if (response.status === 404) return Option.none<string>();
68
+ if (response.status < 200 || response.status >= 300) return yield* unreachable;
69
+ return Option.some(yield* response.text);
70
+ }).pipe(
71
+ Effect.timeout(Duration.seconds(15)),
72
+ Effect.mapError(() => unreachable),
73
+ );
74
+ return Option.isNone(json) ? null : yield* toRelease(spec, json.value);
75
+ });
76
+ // npm loads the whole package history per lookup, so a burst of specs must not spawn one each.
77
+ const npmPermits = yield* Semaphore.make(2);
78
+ const cache = yield* Cache.make({
79
+ capacity: 32,
80
+ timeToLive: Duration.minutes(1),
81
+ lookup: Effect.fn("NpmRelease.lookup")(function* (spec: string) {
82
+ // Without npm there is no configured registry to honor, so use the public one.
83
+ const npmPath = yield* resolveCommandPath("npm");
84
+ if (npmPath === null) return yield* lookupPublic(spec);
85
+ const output = yield* npmPermits
86
+ .withPermits(1)(
87
+ runner.run({
88
+ command: npmPath,
89
+ // Named fields keep the output small; the full package document grows with every release.
90
+ args: ["view", "--global", "--json", `t3@${spec}`, "version", "t3code"],
91
+ timeout: Duration.seconds(15),
92
+ maxOutputBytes: 256 * 1024,
93
+ }),
94
+ )
95
+ .pipe(
96
+ Effect.tapError((error) =>
97
+ Effect.logInfo("npm release lookup failed", { tag: error._tag }),
98
+ ),
99
+ Effect.mapError(
100
+ () => new ServerNpmReleaseError({ reason: "npm could not complete the lookup." }),
101
+ ),
102
+ );
103
+ if (output.timedOut || output.stdoutTruncated || output.stdoutInvalidUtf8) {
104
+ return yield* new ServerNpmReleaseError({ reason: "npm returned an incomplete response." });
105
+ }
106
+ if (output.code !== 0) {
107
+ const error = Option.getOrUndefined(decodeError(output.stdout));
108
+ if (error?.error.code === "E404") return null;
109
+ yield* Effect.logInfo("npm release lookup failed", {
110
+ exitCode: output.code,
111
+ npmErrorCode: error?.error.code,
112
+ });
113
+ return yield* new ServerNpmReleaseError({ reason: "npm could not read release metadata." });
114
+ }
115
+ return yield* toRelease(spec, output.stdout);
116
+ }),
117
+ });
118
+ return NpmRelease.of({
119
+ get: Effect.fn("NpmRelease.get")(function* (input) {
120
+ const { spec } = yield* decodeInput(input).pipe(
121
+ Effect.mapError(
122
+ () => new ServerNpmReleaseError({ reason: "Invalid release version or track." }),
123
+ ),
124
+ );
125
+ return yield* Cache.get(cache, spec);
126
+ }),
127
+ });
128
+});
129
+
130
+export const layer = Layer.effect(NpmRelease, make()).pipe(
131
+ Layer.provide([ProcessRunner.layer, FetchHttpClient.layer]),
132
+);
apps/server/src/environment/ServerEnvironment.ts
+1
@@ -265,6 +265,7 @@ export const make = Effect.gen(function* () {
265
projectCloneTracking: true,
266
ignoredFileListing: true,
267
triage: true,
268
+ npmReleaseLookup: true,
269
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
270
...(serverInstallation === null ? {} : { serverInstallation }),
271
...(serverSelfUpdate === "boot-service" || desktopAppUpdate
apps/server/src/observability/RpcInstrumentation.ts
+1
@@ -33,6 +33,7 @@ const RPC_AGGREGATES = {
33
[WS_METHODS.projectsMutate]: "orchestration",
34
[WS_METHODS.serverProbe]: "server",
35
[WS_METHODS.serverGetConfig]: "server",
36
+ [WS_METHODS.serverGetNpmRelease]: "server",
37
[WS_METHODS.serverRefreshProviders]: "server",
38
[WS_METHODS.serverUpdateProvider]: "server",
39
[WS_METHODS.providerAuthStart]: "provider",
apps/server/src/provider/Drivers/CodexDriver.test.ts
+3
-1
@@ -667,7 +667,9 @@ it.layer(layerTest)("CodexDriver", (it) => {
667
homePath: NodePath.join(tempDir, "codex-home"),
668
},
669
}).pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, metadataSpawner));
670
- const capabilities = yield* instance.snapshot.resolveMaintenance();
670
+ const capabilities = yield* instance.snapshot
671
+ .resolveMaintenance()
672
+ .pipe(Effect.provideService(HostProcess.Environment, { PATH: "" }));
673
const latestVersion = yield* resolveLatestProviderVersion(capabilities).pipe(
674
Effect.provideServiceEffect(
675
ProviderLatestVersions.ProviderLatestVersions,
apps/server/src/provider/ProviderRegistry.ts
+6
-3
@@ -44,6 +44,7 @@ import type {
44
import {
45
makeManualOnlyProviderMaintenanceCapabilities,
46
type ProviderMaintenanceCapabilities,
47
+ latestProviderVersionCacheKeys,
48
} from "@t3tools/provider-core/server/maintenanceResolver";
49
import type { ProviderSnapshotSource } from "./builtInProviderCatalog.ts";
50
@@ -718,9 +719,11 @@ export const layer = Layer.effect(
719
Effect.gen(function* () {
720
yield* instance.invalidateCaches ?? Effect.void;
721
const maintenance = yield* instance.snapshot.resolveMaintenance({ fresh: true });
721
- if (maintenance.packageName) {
722
- yield* latestVersions.invalidate(maintenance.packageName);
723
- }
722
+ yield* Effect.forEach(
723
+ latestProviderVersionCacheKeys(maintenance),
724
+ latestVersions.invalidate,
725
+ { discard: true },
726
+ );
727
}).pipe(Effect.catchCause((cause) => recoverInstanceFailure(instance.instanceId, cause))),
728
{ concurrency: "unbounded", discard: true },
729
);
apps/server/src/ws.test.ts
+2
@@ -85,6 +85,7 @@ import * as ServerEnvironment from "./environment/ServerEnvironment.ts";
85
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
86
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
87
import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
88
+import * as NpmRelease from "./cloud/npmRelease.ts";
89
import * as SessionStore from "./auth/SessionStore.ts";
90
import * as SourceControlDiscovery from "./sourceControl/SourceControlDiscovery.ts";
91
import * as SourceControlRepositoryService from "./sourceControl/SourceControlRepositoryService.ts";
@@ -534,6 +535,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll(
535
Layer.mock(ServerLifecycleEvents.ServerLifecycleEvents)({}),
536
Layer.mock(ServerRuntimeStartup.ServerRuntimeStartup)({}),
537
Layer.mock(ServerSelfUpdate.ServerSelfUpdate)({}),
538
+ Layer.mock(NpmRelease.NpmRelease)({}),
539
Layer.mock(SessionStore.SessionStore)({ cookieName: "config-test", legacyCookieName: undefined }),
540
Layer.mock(SourceControlDiscovery.SourceControlDiscovery)({}),
541
Layer.mock(SourceControlRepositoryService.SourceControlRepositoryService)({}),
apps/server/src/ws.ts
+6
-1
@@ -178,6 +178,7 @@ import * as ProviderMaintenanceRunner from "./provider/providerMaintenanceRunner
178
import * as ProviderAuthService from "./provider/ProviderAuthService.ts";
179
import { makeProviderInstallation } from "./provider/providerInstallation.ts";
180
import * as ServerSelfUpdate from "./cloud/selfUpdate.ts";
181
+import * as NpmRelease from "./cloud/npmRelease.ts";
182
import * as ServerLifecycleEvents from "./serverLifecycleEvents.ts";
183
import * as ServerRuntimeStartup from "./serverRuntimeStartup.ts";
184
import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
@@ -1333,6 +1334,7 @@ export const layerWsRpc = (
1334
const providerAuth = yield* ProviderAuthService.ProviderAuthService;
1335
const providerInstallation = yield* makeProviderInstallation();
1336
const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
1337
+ const npmRelease = yield* NpmRelease.NpmRelease;
1338
const config = yield* ServerConfig.ServerConfig;
1339
const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
1340
const storageCleanup = yield* StorageCleanup.StorageCleanup;
@@ -2481,6 +2483,7 @@ export const layerWsRpc = (
2483
[WS_METHODS.providerInstallSubscribe]: (input) => providerInstallation.subscribe(input),
2484
[WS_METHODS.providerInstallRemove]: (input) => providerInstallation.remove(input),
2485
[WS_METHODS.serverUpdateServer]: (input) => serverSelfUpdate.update(input),
2486
+ [WS_METHODS.serverGetNpmRelease]: (input) => npmRelease.get(input),
2487
[WS_METHODS.serverUpdateServerWithProgress]: (input) =>
2488
ServerSelfUpdate.updateProgressStream(serverSelfUpdate, input),
2489
[WS_METHODS.serverCommitDesktopUpdate]: (input) =>
@@ -3272,6 +3275,7 @@ export const layer = Layer.unwrap(
3275
Effect.gen(function* () {
3276
const serverBrowser = yield* ServerBrowser.ServerBrowser;
3277
const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
3278
+ const npmRelease = yield* NpmRelease.NpmRelease;
3279
const pullRequests = yield* PullRequestService.PullRequestService;
3280
const reviewGuides = yield* PullRequestReviewGuideService.PullRequestReviewGuideService;
3281
const peerLinks = yield* PeerLinks.PeerLinks;
@@ -3346,6 +3350,7 @@ export const layer = Layer.unwrap(
3350
Layer.provide(Layer.succeed(SqlClient.SqlClient, sql)),
3351
Layer.provide(AgentSessionScanner.layer),
3352
Layer.provide(ProviderMaintenanceRunner.layer),
3353
+ Layer.provide(Layer.succeed(NpmRelease.NpmRelease, npmRelease)),
3354
Layer.provide(Layer.succeed(ServerSelfUpdate.ServerSelfUpdate, serverSelfUpdate)),
3355
// Share server-lifetime PR caches so WS mutations invalidate every client's HTTP diffs.
3356
Layer.provide(Layer.succeed(PullRequestService.PullRequestService, pullRequests)),
@@ -3397,4 +3402,4 @@ export const layer = Layer.unwrap(
3402
),
3403
);
3404
}),
3400
-);
3405
+).pipe(Layer.provide(NpmRelease.layer));
apps/web/src/components/settings/UpdateTrackSwitchDialog.tsx
+6
-4
@@ -9,7 +9,7 @@ import { AsyncResult } from "effect/reactivity";
9
import { APP_VERSION } from "~/branding";
10
import { useDesktopUpdateState } from "~/state/desktopUpdate";
11
import { useEnvironments } from "~/state/environments";
12
-import { npmReleaseAtom } from "~/state/npmRelease";
12
+import { npmReleaseAtom, npmReleaseFailureMessage } from "~/state/npmRelease";
13
import { downloadLocalUpdate, installLocalUpdate } from "../sidebar/SidebarUpdatePill";
14
import { UpdateEverythingDialog } from "../sidebar/UpdateEverythingDialog";
15
import {
@@ -51,9 +51,11 @@ export function UpdateTrackSwitchDialog({
51
<AlertDialogHeader>
52
<AlertDialogTitle>Switch to {label}</AlertDialogTitle>
53
<AlertDialogDescription>
54
- {AsyncResult.isFailure(release) || AsyncResult.isSuccess(release)
55
- ? `Could not find the latest ${label} release on npm. Try again later.`
56
- : "Checking releases…"}
54
+ {AsyncResult.isFailure(release)
55
+ ? npmReleaseFailureMessage(release.cause)
56
+ : AsyncResult.isSuccess(release)
57
+ ? `Could not find the latest ${label} release in this environment's npm registry.`
58
+ : "Checking releases…"}
59
</AlertDialogDescription>
60
</AlertDialogHeader>
61
<AlertDialogFooter>
apps/web/src/components/sidebar/updateEverything.logic.test.ts
-19
@@ -69,7 +69,6 @@ describe("collectServerUpdateTargets", () => {
69
machine("manual", "0.0.40", undefined),
70
],
71
"0.0.50",
72
- true,
72
);
73
74
expect(targets.map((target) => [target.serverLabel, target.targetVersion])).toEqual([
@@ -85,24 +84,6 @@ describe("collectServerUpdateTargets", () => {
84
["manual", "needs a manual update"],
85
]);
86
});
88
-
89
- it("waits for npm only for hosts that install from it or when the release may lack archives", () => {
90
- const hosts = [
91
- machine("archive-service", "0.0.41-nightly.20260914.1700", "boot-service"),
92
- machine("npm-service", "0.0.41-nightly.20260914.1699", "boot-service"),
93
- machine("legacy-respawn", "0.1.4-nightly.20261027.3796", "respawn"),
94
- machine("desktop", "0.1.4-nightly.20261027.3796", "desktop-managed"),
95
- ];
96
- const waits = (releaseArchivesPublished: boolean) =>
97
- collectServerUpdateTargets(
98
- hosts,
99
- "0.1.5-nightly.20261029.3873",
100
- releaseArchivesPublished,
101
- ).waitForNpm.map((target) => target.serverLabel);
102
-
103
- expect(waits(true)).toEqual(["npm-service", "legacy-respawn"]);
104
- expect(waits(false)).toEqual(["archive-service", "npm-service", "legacy-respawn"]);
105
- });
87
});
88
89
describe("collectChannelSwitchTargets", () => {
apps/web/src/components/sidebar/updateEverything.logic.ts
+3
-18
@@ -63,25 +63,18 @@ export interface SkippedMachine {
63
readonly reason: string;
64
}
65
66
-/** Boot services before this build installed the server from npm, not from release archives. */
67
-const RELEASE_ARCHIVE_SELF_UPDATE_SINCE = "0.0.41-nightly.20260914.1700";
68
-
66
/** Skip current and app-hosted servers; the latter update with the app and would relaunch mid-run.
70
- * Desktop-managed servers use their own feed. `waitForNpm` lists targets that need
71
- * `t3@<targetVersion>` on npm first. `releaseArchivesPublished` means the version came from the
72
- * desktop feed: its GitHub Release goes public with the CLI archives that boot services download. */
67
+ * Desktop-managed servers use their own feed. Each server's updater checks that it can install the
68
+ * release before it restarts, so no registry precheck runs here. */
69
export function collectServerUpdateTargets(
70
machines: ReadonlyArray<UpdateEverythingMachine>,
71
targetVersion: string,
76
- releaseArchivesPublished: boolean,
72
): {
73
readonly targets: ServerUpdateTarget[];
74
readonly skipped: SkippedMachine[];
80
- readonly waitForNpm: ServerUpdateTarget[];
75
} {
76
const targets: ServerUpdateTarget[] = [];
77
const skipped: SkippedMachine[] = [];
84
- const waitForNpm: ServerUpdateTarget[] = [];
78
for (const machine of machines) {
79
const config = machine.serverConfig;
80
if (machine.hostedByThisApp) continue;
@@ -125,16 +118,8 @@ export function collectServerUpdateTargets(
118
targetVersion,
119
};
120
targets.push(target);
128
- if (
129
- selfUpdate !== "desktop-managed" &&
130
- (!releaseArchivesPublished ||
131
- selfUpdate === "respawn" ||
132
- compareSemverVersions(serverVersion, RELEASE_ARCHIVE_SELF_UPDATE_SINCE) < 0)
133
- ) {
134
- waitForNpm.push(target);
135
- }
121
}
137
- return { targets, skipped, waitForNpm };
122
+ return { targets, skipped };
123
}
124
125
function unavailableReason(machine: UpdateEverythingMachine): string | null {
apps/web/src/components/sidebar/useUpdateEverything.ts
+3
-24
@@ -5,7 +5,6 @@ import { APP_VERSION } from "~/branding";
5
import { isDesktopLocalConnectionTarget } from "~/connection/desktopLocal";
6
import { isElectron } from "~/env";
7
import { useEnvironments } from "~/state/environments";
8
-import { useNpmReleasePublished } from "~/state/npmRelease";
8
import { environmentIdsKey } from "~/state/environmentAtomList";
9
import { environmentUpdateStatesAtom } from "~/state/server";
10
import { environmentSessionStatesAtom } from "~/state/session";
@@ -21,7 +20,6 @@ import {
20
collectUpdateEverythingResult,
21
describeUpdateEverything,
22
runUpdateEverything,
24
- type SkippedMachine,
23
type UpdateRunMachine,
24
} from "./updateEverything.logic";
25
import {
@@ -68,28 +66,9 @@ export function useUpdateEverything(
66
canMaintain: canUpdateServer(sessionStates[index]!),
67
updateState: updateStates[index]!,
68
}));
71
- // A track switch's target came from npm already.
72
- const {
73
- targets: behindServers,
74
- skipped: unreachable,
75
- waitForNpm,
76
- } = channelSwitch
77
- ? { ...collectChannelSwitchTargets(machines, channelSwitch), waitForNpm: [] }
78
- : collectServerUpdateTargets(machines, targetVersion, localUpdateVersion !== null);
79
- const published = useNpmReleasePublished(waitForNpm.length > 0 ? targetVersion : null);
80
- const servers = published
81
- ? behindServers
82
- : behindServers.filter((server) => !waitForNpm.includes(server));
83
- const skipped: ReadonlyArray<SkippedMachine> = [
84
- ...unreachable,
85
- ...behindServers
86
- .filter((server) => !servers.includes(server))
87
- .map((server) => ({
88
- environmentId: server.environmentId,
89
- label: server.serverLabel,
90
- reason: `t3@${targetVersion} is not on npm yet`,
91
- })),
92
- ];
69
+ const { targets: servers, skipped } = channelSwitch
70
+ ? collectChannelSwitchTargets(machines, channelSwitch)
71
+ : collectServerUpdateTargets(machines, targetVersion);
72
// Track-only hosts save a setting and restart nothing, so they are neither listed nor counted.
73
const moving = servers.filter((server) => server.trackOnly !== true);
74
const restarts = collectRestartingMachines(machines, moving, localUpdateVersion !== null);
apps/web/src/state/npmRelease.test.ts
+156
-48
@@ -1,60 +1,168 @@
1
-import { AtomRegistry } from "effect/reactivity";
2
-import * as AsyncResult from "effect/reactivity/AsyncResult";
3
-import { afterAll, afterEach, describe, expect, it, vi } from "vite-plus/test";
1
+import * as NodeAssert from "node:assert/strict";
2
5
-import { npmReleasePublishedAtom } from "./npmRelease";
3
+import { EnvironmentId, ServerConfig, ServerNpmReleaseError } from "@t3tools/contracts";
4
+import { expect, it } from "@effect/vitest";
5
+import * as Cause from "effect/Cause";
6
+import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity";
7
+import * as Effect from "effect/Effect";
8
+import * as Schema from "effect/Schema";
9
+import { vi } from "vite-plus/test";
10
7
-const version = "0.0.46-nightly.20261012.3021";
11
+import { npmReleaseAtom, npmReleaseFailureMessage } from "./npmRelease";
12
+import { primaryEnvironmentIdAtom } from "./primaryEnvironment";
13
+import { serverEnvironment } from "./server";
14
9
-// FetchHttpClient reads globalThis.fetch once and keeps it, so every test shares this mock.
10
-const fetchMock = vi.fn<typeof fetch>();
11
-vi.stubGlobal("fetch", fetchMock);
12
-
13
-async function settledCheck() {
14
- const atom = npmReleasePublishedAtom(version);
15
- const registry = AtomRegistry.make();
16
- const unmount = registry.mount(atom);
17
- try {
18
- await vi.waitFor(() => {
19
- const result = registry.get(atom);
20
- expect(AsyncResult.isInitial(result) || result.waiting).toBe(false);
21
- });
22
- return registry.get(atom);
23
- } finally {
24
- unmount();
25
- registry.dispose();
26
- }
27
-}
15
+vi.mock("./server", () => ({
16
+ serverEnvironment: { npmRelease: vi.fn(), configValueAtom: vi.fn() },
17
+}));
18
+vi.mock("./presentation", () => ({
19
+ environmentSummaries: { connectedEnvironmentIdsAtom: Atom.make(["first", "second"]) },
20
+}));
21
+vi.mock("./primaryEnvironment", () => ({
22
+ primaryEnvironmentIdAtom: Atom.make<EnvironmentId | null>(null),
23
+}));
24
29
-describe("npmReleasePublishedAtom", () => {
30
- afterEach(() => {
31
- fetchMock.mockReset();
32
- });
25
+const version = "0.0.46-nightly.20261012.3021";
26
+const first = EnvironmentId.make("first");
27
+const second = EnvironmentId.make("second");
28
+const decodeServerConfig = Schema.decodeUnknownSync(ServerConfig);
29
34
- afterAll(() => {
35
- vi.unstubAllGlobals();
30
+const configFor = (environmentId: EnvironmentId | null, supported = true) =>
31
+ decodeServerConfig({
32
+ environment: {
33
+ environmentId,
34
+ label: environmentId,
35
+ platform: { os: "linux", arch: "x64" },
36
+ serverVersion: version,
37
+ capabilities: {
38
+ repositoryIdentity: true,
39
+ ...(supported ? { npmReleaseLookup: true } : {}),
40
+ },
41
+ },
42
+ auth: {
43
+ policy: "loopback-browser",
44
+ bootstrapMethods: [],
45
+ sessionMethods: [],
46
+ sessionCookieName: "test",
47
+ },
48
+ cwd: "/test",
49
+ keybindingsConfigPath: "/test/keybindings.json",
50
+ keybindings: [],
51
+ issues: [],
52
+ providers: [],
53
+ availableEditors: [],
54
+ observability: {
55
+ logsDirectoryPath: "/test/logs",
56
+ localTracingEnabled: false,
57
+ otlpTracesEnabled: false,
58
+ otlpMetricsEnabled: false,
59
+ },
60
+ settings: {},
61
});
62
38
- it("checks npm without tracing headers, so the browser skips the preflight npm rejects", async () => {
39
- fetchMock.mockImplementation(async () => Response.json({ version }));
40
-
41
- const result = await settledCheck();
63
+function setup(supported = true) {
64
+ vi.mocked(serverEnvironment.configValueAtom)
65
+ .mockReset()
66
+ .mockImplementation((environmentId) => Atom.make(configFor(environmentId, supported)));
67
+ return vi.mocked(serverEnvironment.npmRelease).mockReset();
68
+}
69
43
- expect(fetchMock).toHaveBeenCalledTimes(1);
44
- const request = new Request(fetchMock.mock.calls[0]?.[0] ?? "", fetchMock.mock.calls[0]?.[1]);
45
- expect(request.url).toBe(`https://registry.npmjs.org/t3/${version}`);
46
- expect(request.headers.get("traceparent")).toBeNull();
47
- expect(request.headers.get("b3")).toBeNull();
48
- expect(AsyncResult.getOrElse(result, () => false)).toBe(true);
49
- });
70
+it.effect(
71
+ "resolves track metadata through the primary environment and follows primary changes",
72
+ () =>
73
+ Effect.gen(function* () {
74
+ const query = setup();
75
+ query.mockImplementation(({ environmentId }) =>
76
+ Atom.make(
77
+ AsyncResult.success({ version, databaseMigration: environmentId === first ? 42 : 43 }),
78
+ ),
79
+ );
80
+ const registry = AtomRegistry.make();
81
+ const release = npmReleaseAtom("nightly");
82
+ NodeAssert.ok(
83
+ Atom.isWritable<EnvironmentId | null, EnvironmentId | null>(primaryEnvironmentIdAtom),
84
+ "Expected the mocked primary environment atom to be writable.",
85
+ );
86
+ registry.set(primaryEnvironmentIdAtom, first);
87
+ const unmount = registry.mount(release);
88
+ try {
89
+ expect(
90
+ yield* AtomRegistry.getResult(registry, release, { suspendOnWaiting: true }),
91
+ ).toEqual({
92
+ version,
93
+ databaseMigration: 42,
94
+ });
95
+ registry.set(primaryEnvironmentIdAtom, second);
96
+ expect(
97
+ yield* AtomRegistry.getResult(registry, release, { suspendOnWaiting: true }),
98
+ ).toEqual({
99
+ version,
100
+ databaseMigration: 43,
101
+ });
102
+ } finally {
103
+ unmount();
104
+ registry.dispose();
105
+ }
106
+ }),
107
+);
108
51
- // regression: #18709 update-everything skipped npm-installed servers
52
- it("leaves a failed first check unknown, which callers read as unpublished", async () => {
53
- fetchMock.mockRejectedValue(new TypeError("Failed to fetch"));
109
+it.effect("resolves track metadata through a supporting server when there is no primary", () =>
110
+ Effect.gen(function* () {
111
+ const query = setup();
112
+ vi.mocked(serverEnvironment.configValueAtom).mockImplementation((environmentId) =>
113
+ Atom.make(
114
+ environmentId === first ? configFor(environmentId, false) : configFor(environmentId),
115
+ ),
116
+ );
117
+ query.mockReturnValue(Atom.make(AsyncResult.success({ version })));
118
+ const registry = AtomRegistry.make();
119
+ const release = npmReleaseAtom("nightly");
120
+ const unmount = registry.mount(release);
121
+ try {
122
+ expect(yield* AtomRegistry.getResult(registry, release, { suspendOnWaiting: true })).toEqual({
123
+ version,
124
+ databaseMigration: undefined,
125
+ });
126
+ expect(query).toHaveBeenCalledWith({ environmentId: second, input: { spec: "nightly" } });
127
+ } finally {
128
+ unmount();
129
+ registry.dispose();
130
+ }
131
+ }),
132
+);
133
55
- const result = await settledCheck();
134
+it.effect("does not call an unsupported RPC or fetch public npm for an older primary server", () =>
135
+ Effect.gen(function* () {
136
+ const query = setup(false);
137
+ using fetch = vi
138
+ .spyOn(globalThis, "fetch")
139
+ .mockRejectedValue(new Error("Unexpected browser fetch"));
140
+ const registry = AtomRegistry.make();
141
+ NodeAssert.ok(
142
+ Atom.isWritable<EnvironmentId | null, EnvironmentId | null>(primaryEnvironmentIdAtom),
143
+ "Expected the mocked primary environment atom to be writable.",
144
+ );
145
+ registry.set(primaryEnvironmentIdAtom, first);
146
+ const release = npmReleaseAtom("latest");
147
+ const unmount = registry.mount(release);
148
+ try {
149
+ const error = yield* AtomRegistry.getResult(registry, release).pipe(Effect.flip);
150
+ expect(npmReleaseFailureMessage(Cause.fail(error))).toContain(
151
+ "Update it before switching tracks",
152
+ );
153
+ expect(query).not.toHaveBeenCalled();
154
+ expect(fetch).not.toHaveBeenCalled();
155
+ } finally {
156
+ unmount();
157
+ registry.dispose();
158
+ }
159
+ }),
160
+);
161
57
- expect(AsyncResult.isFailure(result)).toBe(true);
58
- expect(AsyncResult.getOrElse(result, () => false)).toBe(false);
59
- });
162
+it("only displays the safe release error, not arbitrary transport diagnostics", () => {
163
+ const error = new ServerNpmReleaseError({ reason: "Install npm on the server's PATH." });
164
+ expect(npmReleaseFailureMessage(Cause.fail(error))).toBe(error.message);
165
+ expect(
166
+ npmReleaseFailureMessage(Cause.fail(new Error("sensitive transport details"))),
167
+ ).not.toContain("sensitive");
168
});
apps/web/src/state/npmRelease.ts
+51
-50
@@ -1,58 +1,59 @@
1
-import { useAtomValue } from "@effect/atom-react";
2
-import { npmReleaseDatabaseMigration } from "@t3tools/shared/cliRelease";
1
+import { type ServerConfig, ServerNpmReleaseError } from "@t3tools/contracts";
2
+import * as Cause from "effect/Cause";
3
import * as Effect from "effect/Effect";
4
-import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
5
-import { AsyncResult, Atom } from "effect/reactivity";
4
+import * as Option from "effect/Option";
5
+import * as Schema from "effect/Schema";
6
+import { Atom } from "effect/reactivity";
7
7
-export interface NpmRelease {
8
- readonly version: string;
9
- /** Absent on releases published before npm manifests carried it. */
10
- readonly databaseMigration: number | undefined;
8
+import { environmentSummaries } from "./presentation";
9
+import { primaryEnvironmentIdAtom } from "./primaryEnvironment";
10
+import { serverEnvironment } from "./server";
11
+
12
+const isServerNpmReleaseError = Schema.is(ServerNpmReleaseError);
13
+
14
+function unsupportedLookup(config: ServerConfig | null): ServerNpmReleaseError | null {
15
+ if (config === null) {
16
+ return new ServerNpmReleaseError({ reason: "Connect to this server to check releases." });
17
+ }
18
+ return config.environment.capabilities.npmReleaseLookup === true
19
+ ? null
20
+ : new ServerNpmReleaseError({
21
+ reason: "This server does not support registry lookups. Update it before switching tracks.",
22
+ });
23
+}
24
+
25
+export function npmReleaseFailureMessage(cause: Cause.Cause<unknown>): string {
26
+ const error = Option.getOrUndefined(Cause.findErrorOption(cause));
27
+ return isServerNpmReleaseError(error)
28
+ ? error.message
29
+ : "Could not check this environment's npm registry. Check the connection and registry settings.";
30
}
31
13
-/** `spec` is an exact version or a dist-tag such as `nightly`. Null when npm has no such release.
14
- * Refreshes only while mounted; the published check below keeps its own versions alive. */
32
export const npmReleaseAtom = Atom.family((spec: string) =>
16
- Atom.make(
17
- Effect.gen(function* () {
18
- const response = yield* HttpClient.get(
19
- `https://registry.npmjs.org/t3/${encodeURIComponent(spec)}`,
33
+ Atom.make((get) => {
34
+ const primary = get(primaryEnvironmentIdAtom);
35
+ // With the desktop's local server turned off there is no primary, so a connected server answers.
36
+ const candidates =
37
+ primary === null ? get(environmentSummaries.connectedEnvironmentIdsAtom) : [primary];
38
+ const environmentId =
39
+ candidates.find(
40
+ (id) => unsupportedLookup(get(serverEnvironment.configValueAtom(id))) === null,
41
+ ) ?? candidates[0];
42
+ if (environmentId === undefined) {
43
+ return Effect.fail(
44
+ new ServerNpmReleaseError({ reason: "Connect to a server to check releases." }),
45
);
21
- if (response.status === 404) return null;
22
- const body = yield* HttpClientResponse.filterStatusOk(response).pipe(
23
- Effect.flatMap((ok) => ok.json),
46
+ }
47
+ const unsupported = unsupportedLookup(get(serverEnvironment.configValueAtom(environmentId)));
48
+ if (unsupported !== null) return Effect.fail(unsupported);
49
+ return get
50
+ .result(serverEnvironment.npmRelease({ environmentId, input: { spec } }))
51
+ .pipe(
52
+ Effect.map((release) =>
53
+ release === null
54
+ ? null
55
+ : { version: release.version, databaseMigration: release.databaseMigration },
56
+ ),
57
);
25
- if (
26
- typeof body !== "object" ||
27
- body === null ||
28
- !("version" in body) ||
29
- typeof body.version !== "string"
30
- ) {
31
- return null;
32
- }
33
- return {
34
- version: body.version,
35
- databaseMigration: npmReleaseDatabaseMigration(body),
36
- } satisfies NpmRelease;
37
- }).pipe(
38
- // Tracing headers would make the browser send a CORS preflight, which npm rejects.
39
- Effect.provideService(HttpClient.TracerPropagationEnabled, false),
40
- Effect.provide(FetchHttpClient.layer),
41
- ),
42
- ).pipe(Atom.withRefresh("5 minutes"), Atom.withLabel(`npm-release:${spec}`)),
43
-);
44
-
45
-export const npmReleasePublishedAtom = Atom.family((version: string) =>
46
- Atom.make((get) =>
47
- get.result(npmReleaseAtom(version)).pipe(Effect.map((release) => release?.version === version)),
48
- ).pipe(Atom.keepAlive, Atom.withLabel(`npm-release-published:${version}`)),
49
-);
50
-
51
-const NO_VERSION_ATOM = Atom.make(AsyncResult.success(false)).pipe(
52
- Atom.withLabel("npm-release-published:none"),
58
+ }).pipe(Atom.withLabel(`npm-release:${spec}`)),
59
);
54
-
55
-export function useNpmReleasePublished(version: string | null): boolean {
56
- const result = useAtomValue(version ? npmReleasePublishedAtom(version) : NO_VERSION_ATOM);
57
- return AsyncResult.getOrElse(result, () => false);
58
-}
docs/user/updating.md
+15
-5
@@ -22,11 +22,11 @@ restart from the update button when you are ready. A server still restarting
22
finishes on its own, and the button keeps showing it after the desktop app
23
restarts.
24
25
-Remote desktop apps never wait for npm. When the desktop app offers the update,
26
-background services update right away too. Other servers, including older
27
-background services, update only after that version is published to npm. The
28
-confirmation lists each machine it skips and why, such as a machine that is
29
-offline or needs a manual update. Use **Settings → Environments** for those.
25
+Each server checks that it can install the release before it restarts. If the
26
+release is not available to a server yet, its update fails, the server keeps
27
+running, and you can retry. The confirmation lists each machine it skips and
28
+why, such as a machine that is offline or needs a manual update. Use
29
+**Settings → Environments** for those.
30
31
If a desktop app restarts on its old version, T3 Code tells you the update did
32
not apply. It does not install that version again on its own, even when another
@@ -143,6 +143,16 @@ choose **Update** to install it. If not, the window links to the last version
143
that started on your computer. Download and install it to go back. Use **Copy
144
details** to include the error in a bug report.
145
146
+## Registries and proxies
147
+
148
+Each server checks T3 Code releases, and providers installed with npm, through
149
+its own npm, so the checks use npm's configured registry, authentication, and
150
+proxy settings. Providers installed with Homebrew or pnpm check through those
151
+tools.
152
+Configure npm on the server's machine. If that registry cannot be reached, the
153
+release shows as unavailable; T3 Code does not try the public registry instead.
154
+Machines without npm check the public npm registry directly.
155
+
156
## Update providers
157
158
**Settings → Providers** shows provider updates for the selected environment.
packages/client-runtime/src/state/server.ts
+6
@@ -1265,6 +1265,12 @@ export function createServerEnvironmentAtoms<R, E>(
1265
label: "environment-data:server:trace-diagnostics",
1266
tag: WS_METHODS.serverGetTraceDiagnostics,
1267
}),
1268
+ npmRelease: createEnvironmentRpcQueryAtomFamily(runtime, {
1269
+ label: "environment-data:server:npm-release",
1270
+ tag: WS_METHODS.serverGetNpmRelease,
1271
+ staleTimeMs: 60_000,
1272
+ refreshIntervalMs: 5 * 60_000,
1273
+ }),
1274
processDiagnostics: createEnvironmentRpcQueryAtomFamily(runtime, {
1275
label: "environment-data:server:process-diagnostics",
1276
tag: WS_METHODS.serverGetProcessDiagnostics,
packages/contracts/src/environment.ts
+2
@@ -124,6 +124,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
124
threadPullRequestWatch: Schema.optionalKey(Schema.Boolean),
125
pullRequestStackActions: Schema.optionalKey(Schema.Boolean),
126
serverSelfUpdate: Schema.optionalKey(ServerSelfUpdateCapability),
127
+ /** Server answers server.getNpmRelease using its configured npm registry. */
128
+ npmReleaseLookup: Schema.optionalKey(Schema.Boolean),
129
/** Manual commands must update this install, not the host's default global prefix. */
130
serverInstallation: ForwardCompatibleOptional(ServerInstallation),
131
serverSelfUpdateProgress: Schema.optionalKey(Schema.Boolean),
packages/contracts/src/rpc.ts
+11
@@ -323,6 +323,9 @@ import {
323
ServerRemoveKeybindingResult,
324
ServerProviderUpdatedPayload,
325
ServerSelfUpdateError,
326
+ ServerNpmRelease,
327
+ ServerNpmReleaseError,
328
+ ServerNpmReleaseInput,
329
ServerSelfUpdateInput,
330
ServerSelfUpdateProgressEvent,
331
ServerSelfUpdateResult,
@@ -492,6 +495,7 @@ export const WS_METHODS = {
495
496
serverProbe: "server.probe",
497
serverGetConfig: "server.getConfig",
498
+ serverGetNpmRelease: "server.getNpmRelease",
499
serverRefreshProviders: "server.refreshProviders",
500
serverUpdateProvider: "server.updateProvider",
501
serverUpdateServer: "server.updateServer",
@@ -745,6 +749,12 @@ const WsProviderInstallRemoveRpc = Rpc.make(WS_METHODS.providerInstallRemove, {
749
error: ProviderSetupRpcError,
750
});
751
752
+const WsServerGetNpmReleaseRpc = Rpc.make(WS_METHODS.serverGetNpmRelease, {
753
+ payload: ServerNpmReleaseInput,
754
+ success: Schema.NullOr(ServerNpmRelease),
755
+ error: Schema.Union([ServerNpmReleaseError, EnvironmentAuthorizationError]),
756
+});
757
+
758
const WsServerUpdateServerRpc = Rpc.make(WS_METHODS.serverUpdateServer, {
759
payload: ServerSelfUpdateInput,
760
success: ServerSelfUpdateResult,
@@ -1971,6 +1981,7 @@ export const WsRpcGroup = RpcGroup.make(
1981
WsProviderInstallSubscribeRpc,
1982
WsProviderInstallRemoveRpc,
1983
WsServerUpdateServerRpc,
1984
+ WsServerGetNpmReleaseRpc,
1985
WsServerUpdateServerWithProgressRpc,
1986
WsServerCommitDesktopUpdateRpc,
1987
WsServerUpsertKeybindingRpc,
packages/contracts/src/server.ts
+23
@@ -881,6 +881,29 @@ export class ServerProviderUpdateError extends Schema.TaggedError<ServerProvider
881
}
882
}
883
884
+export const ServerNpmReleaseInput = Schema.Struct({
885
+ spec: Schema.String.check(
886
+ Schema.isMaxLength(64),
887
+ Schema.isPattern(/^(?:latest|nightly|\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)$/),
888
+ ),
889
+});
890
+export type ServerNpmReleaseInput = typeof ServerNpmReleaseInput.Type;
891
+
892
+export const ServerNpmRelease = Schema.Struct({
893
+ version: Schema.String,
894
+ databaseMigration: Schema.optionalKey(Schema.Int),
895
+});
896
+export type ServerNpmRelease = typeof ServerNpmRelease.Type;
897
+
898
+export class ServerNpmReleaseError extends Schema.TaggedError<ServerNpmReleaseError>()(
899
+ "ServerNpmReleaseError",
900
+ { reason: Schema.String },
901
+) {
902
+ override get message(): string {
903
+ return `Could not check the configured npm registry: ${this.reason}`;
904
+ }
905
+}
906
+
907
export const ServerSelfUpdateInput = Schema.Struct({
908
/** Exact npm version, never a dist-tag, so server and client agree on the request. */
909
targetVersion: TrimmedNonEmptyString,
packages/provider-core/src/server/maintenanceResolver.test.ts
+134
-7
@@ -10,6 +10,7 @@ import * as Crypto from "effect/Crypto";
10
import * as Deferred from "effect/Deferred";
11
import * as Effect from "effect/Effect";
12
import * as Fiber from "effect/Fiber";
13
+import * as Layer from "effect/Layer";
14
import * as Sink from "effect/Sink";
15
import * as Stream from "effect/Stream";
16
import * as HttpClient from "effect/http/HttpClient";
@@ -127,7 +128,9 @@ function stdoutSpawner(
128
});
129
}
130
130
-it.layer(NodeServices.layer)("providerMaintenance", (it) => {
131
+it.layer(
132
+ NodeServices.layer.pipe(Layer.merge(Layer.succeed(HostProcess.Environment, { PATH: "" }))),
133
+)("providerMaintenance", (it) => {
134
it.effect("prefers the installer's own latest version over the npm registry", () =>
135
resolveLatestProviderVersion({ ...manualPackageTool, latestVersion: "1.2.0" }).pipe(
136
Effect.provide(ProviderLatestVersions.layer),
@@ -200,6 +203,96 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
203
),
204
);
205
206
+ it.effect.each([
207
+ { install: "native", stdout: '"1.2.0"', exitCode: 0, latest: "1.2.0" },
208
+ { install: "manual", stdout: '["1.2.0"]', exitCode: 0, latest: "1.2.0" },
209
+ { install: "npm", stdout: '"1.2.0"', exitCode: 0, latest: "1.2.0" },
210
+ { install: "native", stdout: "", exitCode: 1, latest: null },
211
+ { install: "npm", stdout: '"1.2.0"', exitCode: 1, latest: null },
212
+ { install: "native", stdout: "not json", exitCode: 0, latest: null },
213
+ { install: "manual", stdout: '["1.2.0", "1.3.0"]', exitCode: 0, latest: null },
214
+ { install: "manual", stdout: '""', exitCode: 0, latest: null },
215
+ ])(
216
+ "uses npm's registry for $install installs (exit $exitCode, output $stdout)",
217
+ (fixture) =>
218
+ Effect.gen(function* () {
219
+ const tempDir = yield* makeTempDir("t3-registry-version");
220
+ const npmBinDir = NodePath.join(tempDir, "npm-bin");
221
+ writeExecutable(NodePath.join(npmBinDir, "npm"));
222
+ const binaryPath =
223
+ fixture.install === "npm"
224
+ ? linkIntoPackage(tempDir, "package-tool", [
225
+ "lib",
226
+ "node_modules",
227
+ "@example",
228
+ "package-tool",
229
+ ])
230
+ : NodePath.join(tempDir, ".local/bin/native-package-tool");
231
+ if (fixture.install !== "npm") writeExecutable(binaryPath);
232
+ let probes = 0;
233
+ const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
234
+ fixture.install === "native" ? nativePackageToolUpdate : packageToolUpdate,
235
+ { binaryPath, env: { PATH: "" } },
236
+ ).pipe(
237
+ Effect.provideService(HostProcess.Environment, { PATH: npmBinDir }),
238
+ Effect.provideService(
239
+ ChildProcessSpawner.ChildProcessSpawner,
240
+ stdoutSpawner(
241
+ (command, args) => {
242
+ probes++;
243
+ expect(command).toBe(NodePath.join(npmBinDir, "npm"));
244
+ expect(args).toEqual([
245
+ "view",
246
+ "--global",
247
+ ...(fixture.install === "npm" ? ["--prefix", tempDir] : []),
248
+ "--json",
249
+ `${capabilities.packageName}@latest`,
250
+ "version",
251
+ ]);
252
+ return fixture.stdout;
253
+ },
254
+ () => fixture.exitCode,
255
+ ),
256
+ ),
257
+ );
258
+ const program = Effect.gen(function* () {
259
+ yield* enrichProviderSnapshotWithVersionAdvisory(
260
+ installedPackageToolProvider,
261
+ capabilities,
262
+ { enableProviderUpdateChecks: false },
263
+ );
264
+ expect(probes).toBe(0);
265
+ const snapshot = yield* enrichProviderSnapshotWithVersionAdvisory(
266
+ installedPackageToolProvider,
267
+ capabilities,
268
+ );
269
+ expect(snapshot.versionAdvisory?.latestVersion).toBe(fixture.latest);
270
+ expect(probes).toBe(1);
271
+ expect(yield* resolveLatestProviderVersion(capabilities)).toBe(fixture.latest);
272
+ expect(probes).toBe(1);
273
+ yield* invalidateLatestProviderVersion(capabilities);
274
+ expect(yield* resolveLatestProviderVersion(capabilities)).toBe(fixture.latest);
275
+ expect(probes).toBe(2);
276
+ });
277
+ yield* program.pipe(
278
+ Effect.provideServiceEffect(
279
+ ProviderLatestVersions.ProviderLatestVersions,
280
+ ProviderLatestVersions.make([
281
+ ["@example/package-tool", "9.9.9"],
282
+ ["@example/native-package-tool", "9.9.9"],
283
+ ]),
284
+ ),
285
+ Effect.provideService(
286
+ HttpClient.HttpClient,
287
+ HttpClient.make(() =>
288
+ Effect.die("a configured npm lookup must not fall back to public npm"),
289
+ ),
290
+ ),
291
+ );
292
+ }),
293
+ { skip: !symlinksSupported || windowsHost },
294
+ );
295
+
296
it("pins the advertised stable version in a pnpm-global update command", () => {
297
const advisoryFor = (
298
maintenanceCapabilities: ReturnType<typeof makeProviderMaintenanceCapabilities>,
@@ -674,15 +767,36 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
767
case: "the eligible release",
768
outdated: { "@example/package-tool": { current: "1.0.0", latest: "1.1.0" } },
769
exitCode: 1,
770
+ npmOutput: '"1.2.0"',
771
expected: "1.1.0",
772
},
679
- { case: "no update during cooldown", outdated: {}, exitCode: 0, expected: "1.0.0" },
773
{
681
- case: "the npm fallback when the pnpm probe fails",
774
+ case: "no update during cooldown",
775
+ outdated: {},
776
+ exitCode: 0,
777
+ npmOutput: '"1.2.0"',
778
+ expected: "1.0.0",
779
+ },
780
+ {
781
+ case: "the public registry fallback when pnpm fails and npm is unavailable",
782
outdated: { "@example/package-tool": { current: "1.0.0", latest: "1.1.0" } },
783
exitCode: 2,
784
expected: "9.9.9",
785
},
786
+ {
787
+ case: "the configured npm registry when the pnpm probe fails",
788
+ outdated: {},
789
+ exitCode: 2,
790
+ npmOutput: '"1.2.0"',
791
+ expected: "1.2.0",
792
+ },
793
+ {
794
+ case: "an unknown version when both configured lookups fail",
795
+ outdated: {},
796
+ exitCode: 2,
797
+ npmOutput: "not json",
798
+ expected: null,
799
+ },
800
])(
801
"advertises $case for pnpm-global installs",
802
(fixture) =>
@@ -690,6 +804,7 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
804
const tempDir = yield* makeTempDir("t3-pnpm-latest");
805
const pnpmBinDir = NodePath.join(tempDir, "pnpm-bin");
806
writeExecutable(NodePath.join(pnpmBinDir, "pnpm"));
807
+ if (fixture.npmOutput !== undefined) writeExecutable(NodePath.join(pnpmBinDir, "npm"));
808
const link = linkIntoPackage(tempDir, "package-tool", [
809
".local",
810
"share",
@@ -701,6 +816,7 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
816
"package-tool",
817
]);
818
819
+ let npmProbes = 0;
820
const capabilities = yield* resolveProviderMaintenanceCapabilitiesEffect(
821
packageToolUpdate,
822
{ binaryPath: link, env: { PATH: "" } },
@@ -709,12 +825,17 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
825
Effect.provideService(
826
ChildProcessSpawner.ChildProcessSpawner,
827
stdoutSpawner(
712
- (_command, args) =>
713
- args[0] === "outdated"
828
+ (_command, args) => {
829
+ if (args[0] === "view") {
830
+ npmProbes++;
831
+ return fixture.npmOutput ?? "";
832
+ }
833
+ return args[0] === "outdated"
834
? JSON.stringify(fixture.outdated)
835
: JSON.stringify([
836
{ dependencies: { "@example/package-tool": { version: "1.0.0" } } },
717
- ]),
837
+ ]);
838
+ },
839
(args) => (args[0] === "outdated" ? fixture.exitCode : 0),
840
),
841
),
@@ -734,10 +855,16 @@ it.layer(NodeServices.layer)("providerMaintenance", (it) => {
855
),
856
);
857
expect(provider.versionAdvisory).toMatchObject({
737
- status: fixture.expected === "1.0.0" ? "current" : "behind_latest",
858
+ status:
859
+ fixture.expected === null
860
+ ? "unknown"
861
+ : fixture.expected === "1.0.0"
862
+ ? "current"
863
+ : "behind_latest",
864
currentVersion: "1.0.0",
865
latestVersion: fixture.expected,
866
});
867
+ expect(npmProbes).toBe(fixture.exitCode === 2 && fixture.npmOutput !== undefined ? 1 : 0);
868
}),
869
{ skip: !symlinksSupported || windowsHost },
870
);
packages/provider-core/src/server/maintenanceResolver.ts
+61
-3
@@ -712,6 +712,63 @@ function makeManualProviderMaintenanceCapabilities(
712
});
713
}
714
715
+const decodeNpmViewVersion = Schema.decodeUnknownOption(
716
+ Schema.fromJsonString(Schema.Union([Schema.String, Schema.Tuple([Schema.String])])),
717
+);
718
+
719
+const withConfiguredNpmVersionLookup = Effect.fn("withConfiguredNpmVersionLookup")(function* (
720
+ capabilities: ProviderMaintenanceCapabilities,
721
+) {
722
+ const packageName = capabilities.packageName;
723
+ if (!packageName || capabilities.latestVersion !== undefined) {
724
+ return capabilities;
725
+ }
726
+ const npmPath = yield* resolveCommandPath("npm");
727
+ if (!npmPath) return capabilities;
728
+ const services = yield* Effect.context<ProviderMaintenanceResolverServices>();
729
+ const update = capabilities.update;
730
+ const prefixIndex = update?.lockKey.startsWith("npm-global:")
731
+ ? update.args.indexOf("--prefix")
732
+ : -1;
733
+ const prefix = prefixIndex >= 0 ? update?.args[prefixIndex + 1] : undefined;
734
+ const lookup = runProbe(
735
+ npmPath,
736
+ [
737
+ "view",
738
+ "--global",
739
+ ...(prefix ? ["--prefix", prefix] : []),
740
+ "--json",
741
+ `${packageName}@latest`,
742
+ "version",
743
+ ],
744
+ {},
745
+ ).pipe(
746
+ Effect.map((stdout) => {
747
+ const value = stdout ? Option.getOrNull(decodeNpmViewVersion(stdout.trim())) : null;
748
+ return nonEmptyString(typeof value === "string" ? value : value?.[0]);
749
+ }),
750
+ Effect.tap((version) =>
751
+ version === null
752
+ ? Effect.logWarning("Configured npm version lookup failed", { packageName })
753
+ : Effect.void,
754
+ ),
755
+ Effect.provideContext(services),
756
+ );
757
+ return {
758
+ ...capabilities,
759
+ // npm owns registry, scoped auth and proxy configuration; failure must not retry public npm.
760
+ latestVersion: null,
761
+ lookupLatestVersion: capabilities.lookupLatestVersion
762
+ ? capabilities.lookupLatestVersion.pipe(
763
+ Effect.filterOrElse(
764
+ (version) => version !== null,
765
+ () => lookup,
766
+ ),
767
+ )
768
+ : lookup,
769
+ };
770
+});
771
+
772
export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(
773
"resolveProviderMaintenanceCapabilitiesEffect",
774
)(function* (
@@ -746,7 +803,7 @@ export const resolveProviderMaintenanceCapabilitiesEffect = Effect.fn(
803
env,
804
platform: yield* HostProcess.Platform,
805
});
749
-});
806
+}, Effect.flatMap(withConfiguredNpmVersionLookup));
807
808
export const makeCachedProviderMaintenanceResolution = Effect.fn(
809
"makeCachedProviderMaintenanceResolution",
@@ -840,10 +897,11 @@ const fetchNpmLatestVersion = Effect.fn("fetchNpmLatestVersion")(function* (pack
897
898
/** The installer's own answer is cached apart from the npm registry entry. */
899
function installerLatestVersionKey(capabilities: ProviderMaintenanceCapabilities) {
900
+ if (!capabilities.lookupLatestVersion) return null;
901
const update = capabilities.update;
844
- return capabilities.lookupLatestVersion && update
902
+ return update
903
? [update.lockKey, update.executable, ...update.args].join("\0")
846
- : null;
904
+ : capabilities.packageName && `npm-registry\0${capabilities.packageName}`;
905
}
906
907
export function latestProviderVersionCacheKeys(