From 998654944a2d82391ba6ea56740d767125be64c2 Mon Sep 17 00:00:00 2001 From: JJ Eaton <58495321+jayleaton@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:41:36 +0700 Subject: [PATCH 1/6] fix(desktop): a cancelled update download closes its transfer and a retry starts fresh electron-updater 6.8.9 never handed its cancellation token to the requests doing the work. builder-util-runtime's doDownload ignored the onCancel it was given, so a cancelled full download rejected but kept its request and file open. DifferentialDownloader made its range requests with no token at all, so a cancelled differential download stayed pending and kept downloadPromise reserved, and Retry rejoined it. Both are patched to abort their requests on cancel, and the desktop waits for electron-updater to release the download before the cancel completes. Co-Authored-By: Claude Opus 5.5 --- .../src/electron/ElectronUpdater.test.ts | 132 +++++++++++++++++- apps/desktop/src/electron/ElectronUpdater.ts | 21 ++- patches/builder-util-runtime@9.7.0.patch | 24 ++++ patches/electron-updater@6.8.9.patch | 78 +++++++++++ pnpm-lock.yaml | 20 +-- pnpm-workspace.yaml | 5 +- 6 files changed, 262 insertions(+), 18 deletions(-) create mode 100644 patches/builder-util-runtime@9.7.0.patch diff --git a/apps/desktop/src/electron/ElectronUpdater.test.ts b/apps/desktop/src/electron/ElectronUpdater.test.ts index e47c741bf3bd..ee2ff7e1dcee 100644 --- a/apps/desktop/src/electron/ElectronUpdater.test.ts +++ b/apps/desktop/src/electron/ElectronUpdater.test.ts @@ -1,14 +1,22 @@ -// @effect-diagnostics nodeBuiltinImport:off -- Intercepts the spawn electron-updater requires natively. +// @effect-diagnostics nodeBuiltinImport:off -- Intercepts the spawn electron-updater requires natively, and serves updates over node:http. import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, describe, it } from "@effect/vitest"; import * as Deferred from "effect/Deferred"; import * as Effect from "effect/Effect"; +import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; +import * as Option from "effect/Option"; import * as Path from "effect/Path"; +import * as Queue from "effect/Queue"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { autoUpdater } from "electron-updater"; +import { DownloadedUpdateHelper } from "electron-updater/out/DownloadedUpdateHelper.js"; +import { ElectronHttpExecutor } from "electron-updater/out/electronHttpExecutor.js"; import type * as NodeChildProcess from "node:child_process"; +import * as NodeCrypto from "node:crypto"; +import * as NodeHttp from "node:http"; import * as NodeModule from "node:module"; +import * as NodeZlib from "node:zlib"; import { vi } from "vite-plus/test"; // electron-updater requires Electron natively, outside vi.mock's reach, and builds its @@ -116,3 +124,125 @@ describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")( ); }, ); + +// Electron's net module only exists in Electron; node:http stands in under the real download code. +class NodeHttpExecutor extends ElectronHttpExecutor { + override createRequest(options: NodeHttp.RequestOptions, callback: (response: unknown) => void) { + return NodeHttp.request(options, callback) as unknown as ReturnType< + ElectronHttpExecutor["createRequest"] + >; + } +} + +// An AppImage: two 16-byte blocks, then its deflated block map and the map's length. +const appImage = (blocks: ReadonlyArray) => { + const blockMap = NodeZlib.deflateRawSync( + JSON.stringify({ + version: "2", + files: [{ name: "file", offset: 0, checksums: blocks, sizes: blocks.map(() => 16) }], + }), + ); + const blockMapSize = Buffer.alloc(4); + blockMapSize.writeUInt32BE(blockMap.length); + const content = Buffer.from(blocks.map((block) => block.repeat(16)).join("")); + return { file: Buffer.concat([content, blockMap, blockMapSize]), blockMapSize: blockMap.length }; +}; + +// Serves the new AppImage's block map, but stalls the update's own bytes after a few of them. +const stallingUpdateServer = Effect.fn(function* (file: Buffer) { + const stalls = yield* Queue.unbounded>(); + const server = yield* Effect.acquireRelease( + Effect.callback((resume) => { + const server = NodeHttp.createServer((request, response) => { + const range = /bytes=(\d+)-(\d+)/.exec(request.headers.range ?? ""); + const [start, end] = range ? [Number(range[1]), Number(range[2])] : [0, file.length - 1]; + const body = file.subarray(start, end + 1); + response.writeHead(range ? 206 : 200, { + "content-length": body.length, + ...(range ? { "content-range": `bytes ${start}-${end}/${file.length}` } : {}), + }); + if (start >= 32) { + response.end(body); + return; + } + const closed = Deferred.makeUnsafe(); + response.on("close", () => Deferred.doneUnsafe(closed, Effect.void)); + response.write(body.subarray(0, 4)); + Queue.offerUnsafe(stalls, closed); + }); + server.listen(0, "127.0.0.1", () => resume(Effect.succeed(server))); + }), + (server) => + Effect.callback((resume) => { + server.closeAllConnections(); + server.close(() => resume(Effect.void)); + }), + ); + const address = server.address(); + const port = typeof address === "object" && address !== null ? address.port : 0; + return { url: new URL(`http://127.0.0.1:${port}/T3-Code-1.0.1.AppImage`), stalls }; +}); + +describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")( + "ElectronUpdater stalled download", + () => { + const cancelAndRetry = (differential: boolean) => + Effect.gen(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-update-stall-" }); + const installed = appImage(["A", "B"]); + const update = appImage(["A", "C"]); + const installedPath = path.join(dir, "T3-Code.AppImage"); + yield* fileSystem.writeFile(installedPath, installed.file); + yield* Effect.acquireRelease( + Effect.sync(() => vi.stubEnv("APPIMAGE", installedPath)), + () => Effect.sync(() => vi.unstubAllEnvs()), + ); + const { url, stalls } = yield* stallingUpdateServer(update.file); + const fileInfo = { + url: url.pathname.slice(1), + size: update.file.length, + blockMapSize: update.blockMapSize, + sha512: NodeCrypto.createHash("sha512").update(update.file).digest("base64"), + }; + autoUpdater.logger = null; + autoUpdater.disableDifferentialDownload = !differential; + Object.assign(autoUpdater, { + httpExecutor: new NodeHttpExecutor(), + downloadedUpdateHelper: new DownloadedUpdateHelper(path.join(dir, "cache")), + updateInfoAndProvider: { + info: { version: "1.0.1", files: [fileInfo], path: fileInfo.url, ...fileInfo }, + provider: { + resolveFiles: () => [{ url, info: fileInfo }], + fileExtraDownloadHeaders: null, + isUseMultipleRangeRequest: false, + }, + }, + }); + + const electronUpdater = yield* ElectronUpdater.ElectronUpdater; + yield* electronUpdater.on("error", () => undefined); + const download = yield* Effect.forkChild(electronUpdater.downloadUpdate); + const stalled = yield* Queue.take(stalls); + yield* Fiber.interrupt(download); + // The bounds only fail a cancelled transfer that stays open or keeps holding the updater. + const closed = yield* Deferred.await(stalled).pipe(Effect.timeoutOption("2 seconds")); + assert.isTrue(Option.isSome(closed), "the cancelled request stayed open"); + + const retry = yield* Effect.forkChild(electronUpdater.downloadUpdate); + const retried = yield* Queue.take(stalls).pipe(Effect.timeoutOption("2 seconds")); + assert.isTrue(Option.isSome(retried), "the retry joined the cancelled download"); + yield* Fiber.interrupt(retry); + }).pipe(Effect.scoped, Effect.provide([ElectronUpdater.layer, NodeServices.layer])); + + it.live("a cancelled full download closes its request and a retry downloads again", () => + cancelAndRetry(false), + ); + + it.live( + "a cancelled differential download closes its request and a retry downloads again", + () => cancelAndRetry(true), + ); + }, +); diff --git a/apps/desktop/src/electron/ElectronUpdater.ts b/apps/desktop/src/electron/ElectronUpdater.ts index 84ab0263213b..ec3b2a51d74c 100644 --- a/apps/desktop/src/electron/ElectronUpdater.ts +++ b/apps/desktop/src/electron/ElectronUpdater.ts @@ -162,15 +162,22 @@ export const make = ElectronUpdater.of({ }), downloadUpdate: Effect.suspend(() => { const channel = autoUpdater.channel; + const cancellation = new CancellationToken(); + let download: Promise | undefined; return Effect.tryPromise({ - // Interrupting cancels the download, which also frees electron-updater for the next one. - try: (signal) => { - const cancellation = new CancellationToken(); - signal.addEventListener("abort", () => cancellation.cancel(), { once: true }); - return autoUpdater.downloadUpdate(cancellation); - }, + try: () => (download = autoUpdater.downloadUpdate(cancellation)), catch: (cause) => new ElectronUpdaterDownloadUpdateError({ channel, cause }), - }).pipe(Effect.asVoid); + }).pipe( + // Interrupting cancels the download and waits until electron-updater releases it, so a retry + // starts a fresh download instead of joining the cancelled one. + Effect.onInterrupt(() => + Effect.promise(async () => { + cancellation.cancel(); + await download?.catch(() => undefined); + }), + ), + Effect.asVoid, + ); }), quitAndInstall: Effect.fn("ElectronUpdater.quitAndInstall")(function ({ isSilent, diff --git a/patches/builder-util-runtime@9.7.0.patch b/patches/builder-util-runtime@9.7.0.patch new file mode 100644 index 000000000000..8f788b304a58 --- /dev/null +++ b/patches/builder-util-runtime@9.7.0.patch @@ -0,0 +1,24 @@ +diff --git a/out/httpExecutor.js b/out/httpExecutor.js +index 8d9114761ab0cf92bf56668e8cac8139bc0d71d5..7d03adcb35cc2a1f0a5b40b0f2ceb594f39f776c 100644 +--- a/out/httpExecutor.js ++++ b/out/httpExecutor.js +@@ -270,6 +270,10 @@ Please double check that your authentication token is correct. Due to security r + this.addRedirectHandlers(request, requestOptions, options.callback, redirectCount, requestOptions => { + this.doDownload(requestOptions, options, redirectCount++); + }); ++ // Cancelling rejected the download but left its request open. ++ if (options.onCancel != null) { ++ options.onCancel(() => request.abort()); ++ } + request.end(); + } + createMaxRedirectError() { +@@ -473,6 +477,8 @@ function configurePipes(options, response) { + streams.push(new DigestTransform(options.options.sha2, "sha256", "hex")); + } + const fileOut = (0, fs_1.createWriteStream)(options.destination); ++ // pipe() never ends its destination when the response is aborted, so the file stayed open. ++ response.on("aborted", () => fileOut.destroy()); + streams.push(fileOut); + let lastStream = response; + for (const stream of streams) { diff --git a/patches/electron-updater@6.8.9.patch b/patches/electron-updater@6.8.9.patch index 1e343589cb50..93c2c9770112 100644 --- a/patches/electron-updater@6.8.9.patch +++ b/patches/electron-updater@6.8.9.patch @@ -1,3 +1,81 @@ +diff --git a/out/differentialDownloader/DifferentialDownloader.js b/out/differentialDownloader/DifferentialDownloader.js +index c6e948a79d1bb85122b21d8ddd61a5a842ca2e8d..8ccd51497b6d1ce3047afbeabac6a74cf8923f56 100644 +--- a/out/differentialDownloader/DifferentialDownloader.js ++++ b/out/differentialDownloader/DifferentialDownloader.js +@@ -17,6 +17,20 @@ class DifferentialDownloader { + this.options = options; + this.fileMetadataBuffer = null; + this.logger = options.logger; ++ this.openRequests = new Set(); ++ } ++ // Upstream never handed the cancellation token to range requests, so a cancelled download kept ++ // them open and kept AppUpdater's downloadPromise reserved until they ended. ++ createRequest(requestOptions, callback) { ++ const request = this.httpExecutor.createRequest(requestOptions, callback); ++ this.openRequests.add(request); ++ request.on("close", () => this.openRequests.delete(request)); ++ return request; ++ } ++ abortRequests() { ++ for (const request of this.openRequests) { ++ request.abort(); ++ } + } + createRequestOptions() { + const result = { +@@ -98,7 +112,8 @@ class DifferentialDownloader { + const newFileFd = await (0, fs_extra_1.open)(this.options.newFile, "w"); + fdList.push({ descriptor: newFileFd, path: this.options.newFile }); + const fileOut = (0, fs_1.createWriteStream)(this.options.newFile, { fd: newFileFd }); +- await new Promise((resolve, reject) => { ++ await this.options.cancellationToken.createPromise((resolve, reject, onCancel) => { ++ onCancel(() => this.abortRequests()); + const streams = []; + // Create our download info transformer if we have one + let downloadInfoTransform = undefined; +@@ -186,7 +201,7 @@ class DifferentialDownloader { + if (downloadInfoTransform) { + downloadInfoTransform.beginRangeDownload(); + } +- const request = this.httpExecutor.createRequest(requestOptions, response => { ++ const request = this.createRequest(requestOptions, response => { + response.on("error", reject); + response.on("aborted", () => { + reject(new Error("response has been aborted by the server")); +@@ -239,8 +254,9 @@ class DifferentialDownloader { + return buffer; + } + request(requestOptions, dataHandler) { +- return new Promise((resolve, reject) => { +- const request = this.httpExecutor.createRequest(requestOptions, response => { ++ return this.options.cancellationToken.createPromise((resolve, reject, onCancel) => { ++ onCancel(() => this.abortRequests()); ++ const request = this.createRequest(requestOptions, response => { + if (!(0, multipleRangeDownloader_1.checkIsRangesSupported)(response, reject)) { + return; + } +diff --git a/out/differentialDownloader/multipleRangeDownloader.js b/out/differentialDownloader/multipleRangeDownloader.js +index 56adc38fe831b39d8430ad8aabe8fd7a35c36b9f..4ec2494a8c64973d3cc498b124817596ace5d690 100644 +--- a/out/differentialDownloader/multipleRangeDownloader.js ++++ b/out/differentialDownloader/multipleRangeDownloader.js +@@ -54,7 +54,7 @@ function doExecuteTasks(differentialDownloader, options, out, resolve, reject) { + else { + const requestOptions = differentialDownloader.createRequestOptions(); + requestOptions.headers.Range = `bytes=${task.start}-${task.end - 1}`; +- const request = differentialDownloader.httpExecutor.createRequest(requestOptions, response => { ++ const request = differentialDownloader.createRequest(requestOptions, response => { + response.on("error", reject); + if (!checkIsRangesSupported(response, reject)) { + return; +@@ -73,7 +73,7 @@ function doExecuteTasks(differentialDownloader, options, out, resolve, reject) { + } + const requestOptions = differentialDownloader.createRequestOptions(); + requestOptions.headers.Range = ranges.substring(0, ranges.length - 2); +- const request = differentialDownloader.httpExecutor.createRequest(requestOptions, response => { ++ const request = differentialDownloader.createRequest(requestOptions, response => { + if (!checkIsRangesSupported(response, reject)) { + return; + } diff --git a/out/electronHttpExecutor.js b/out/electronHttpExecutor.js index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..c298ffe7808c421c29e16f1e2ba8510f0cd31142 100644 --- a/out/electronHttpExecutor.js diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b632d4bfbab8..a3f450eac5ec 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -283,6 +283,7 @@ overrides: react-native-svg: 15.16.1 app-builder-lib: 26.16.1 electron-updater: 6.8.9 + builder-util-runtime: 9.7.0 expo-modules-core: 58.0.30 '@exodus/bytes>@noble/hashes': 1.8.0 '@react-navigation/core': 7.24.0 @@ -349,8 +350,9 @@ patchedDependencies: '@react-navigation/native-stack@7.21.0': 990d575444c4af2ce8218b3b7a8280fe244c03abbdb32b822a2e862f791dbf42 alchemy@2.0.0-beta.85: 07cc8c7e14b3b9af143ddd40a059f117c27e55139fbf20bd5dde2eb30509cedd app-builder-lib@26.16.1: 0fbe9ae51783f5768ebe197d12d1fdb7d477a08c92e5db2f6356bcce62613c53 + builder-util-runtime@9.7.0: 73c6552e5248b5eb7f929ef7361a439158de232e1a07511cb3c9a0dc593b2848 dbus-next@0.10.2: cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4 - electron-updater@6.8.9: 5e096d34a46fdbaa6d48a5803b2c0ed9c7c04f8ab43a30ebebbf726f8f28ed8e + electron-updater@6.8.9: 90230fa7d39dc2abd7792a1e1c79ac4161da589e1cca917abe3f48e613fda7e2 expo-audio@58.0.11: 93691f7f59edb30a3bb2c23b489e605e7ea35506b1212d4a2ebbd1fd79079483 expo-modules-core@58.0.30: f0b0fd100550ed76e5c25b4d13eb7c9ff62825f8f197c53edf7bf447c50c9fb7 expo-network@58.0.4: 159c2d760d1cd5102e95df51c20600111e7a72096ef0daea8215d50cae48bd98 @@ -434,7 +436,7 @@ importers: version: 44.10.1(supports-color@8.1.1) electron-updater: specifier: 6.8.9 - version: 6.8.9(patch_hash=5e096d34a46fdbaa6d48a5803b2c0ed9c7c04f8ab43a30ebebbf726f8f28ed8e)(supports-color@8.1.1) + version: 6.8.9(patch_hash=90230fa7d39dc2abd7792a1e1c79ac4161da589e1cca917abe3f48e613fda7e2)(supports-color@8.1.1) electron-webauthn: specifier: 'catalog:' version: 1.3.1(typescript@6.0.3) @@ -17192,7 +17194,7 @@ snapshots: asn1js: 3.0.10 async-exit-hook: 2.0.1 builder-util: 26.16.0(supports-color@8.1.1) - builder-util-runtime: 9.7.0(supports-color@8.1.1) + builder-util-runtime: 9.7.0(patch_hash=73c6552e5248b5eb7f929ef7361a439158de232e1a07511cb3c9a0dc593b2848)(supports-color@8.1.1) chromium-pickle-js: 0.2.0 ci-info: 4.3.1 debug: 4.4.3(supports-color@8.1.1) @@ -17561,7 +17563,7 @@ snapshots: node-gyp-build: 4.8.4 optional: true - builder-util-runtime@9.7.0(supports-color@8.1.1): + builder-util-runtime@9.7.0(patch_hash=73c6552e5248b5eb7f929ef7361a439158de232e1a07511cb3c9a0dc593b2848)(supports-color@8.1.1): dependencies: debug: 4.4.3(supports-color@8.1.1) sax: 1.6.1 @@ -17571,7 +17573,7 @@ snapshots: builder-util@26.16.0(supports-color@8.1.1): dependencies: '@types/debug': 4.1.13 - builder-util-runtime: 9.7.0(supports-color@8.1.1) + builder-util-runtime: 9.7.0(patch_hash=73c6552e5248b5eb7f929ef7361a439158de232e1a07511cb3c9a0dc593b2848)(supports-color@8.1.1) chalk: 4.1.2 cross-spawn: 7.0.6 debug: 4.4.3(supports-color@8.1.1) @@ -18100,7 +18102,7 @@ snapshots: dependencies: app-builder-lib: 26.16.1(patch_hash=0fbe9ae51783f5768ebe197d12d1fdb7d477a08c92e5db2f6356bcce62613c53)(dmg-builder@26.16.1)(electron-builder-squirrel-windows@26.16.1)(supports-color@8.1.1) builder-util: 26.16.0(supports-color@8.1.1) - builder-util-runtime: 9.7.0(supports-color@8.1.1) + builder-util-runtime: 9.7.0(patch_hash=73c6552e5248b5eb7f929ef7361a439158de232e1a07511cb3c9a0dc593b2848)(supports-color@8.1.1) chalk: 4.1.2 ci-info: 4.4.0 dmg-builder: 26.16.1(electron-builder-squirrel-windows@26.16.1)(supports-color@8.1.1) @@ -18117,7 +18119,7 @@ snapshots: '@types/fs-extra': 9.0.13 aws4: 1.13.2 builder-util: 26.16.0(supports-color@8.1.1) - builder-util-runtime: 9.7.0(supports-color@8.1.1) + builder-util-runtime: 9.7.0(patch_hash=73c6552e5248b5eb7f929ef7361a439158de232e1a07511cb3c9a0dc593b2848)(supports-color@8.1.1) chalk: 4.1.2 form-data: 4.0.6 fs-extra: 10.1.0 @@ -18128,9 +18130,9 @@ snapshots: electron-to-chromium@1.5.430: {} - electron-updater@6.8.9(patch_hash=5e096d34a46fdbaa6d48a5803b2c0ed9c7c04f8ab43a30ebebbf726f8f28ed8e)(supports-color@8.1.1): + electron-updater@6.8.9(patch_hash=90230fa7d39dc2abd7792a1e1c79ac4161da589e1cca917abe3f48e613fda7e2)(supports-color@8.1.1): dependencies: - builder-util-runtime: 9.7.0(supports-color@8.1.1) + builder-util-runtime: 9.7.0(patch_hash=73c6552e5248b5eb7f929ef7361a439158de232e1a07511cb3c9a0dc593b2848)(supports-color@8.1.1) fs-extra: 10.1.0 js-yaml: 4.3.2 lazy-val: 1.0.5 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 5059ea4ff59e..5f5f55a0466b 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -115,6 +115,7 @@ overrides: react-native-svg: 15.16.1 app-builder-lib: 26.16.1 electron-updater: 6.8.9 + builder-util-runtime: 9.7.0 expo-modules-core: 58.0.30 # Keep jsdom's optional peer consistent so Vite+ has one test-runner instance. "@exodus/bytes>@noble/hashes": "1.8.0" @@ -238,8 +239,10 @@ patchedDependencies: # can run on worker threads: apps/server/src/process/SpawnWorker.ts. "@effect/platform-node-shared@4.1.2": patches/@effect__platform-node-shared@4.1.2.patch # Electron net requests never emit "socket", so upstream's idle timeout never fires and a - # stalled update download hangs forever. + # stalled update download hangs forever. A cancelled differential download aborts its range requests. electron-updater@6.8.9: patches/electron-updater@6.8.9.patch + # A cancelled download aborts its request and closes its file instead of leaving both open. + builder-util-runtime@9.7.0: patches/builder-util-runtime@9.7.0.patch # Local agents honor the attribution settings in the user's Cursor CLI cli-config.json, stream # shell output while it runs, and expose agent.resume() (the protocol's ResumeAction). "@cursor/sdk@1.3.1": patches/@cursor__sdk@1.3.1.patch From c6e89302f4256079182c36c891d5691a7fcec692 Mon Sep 17 00:00:00 2001 From: JJ Eaton <58495321+jayleaton@users.noreply.github.com> Date: Thu, 19 Nov 2026 12:42:01 +0700 Subject: [PATCH 2/6] fix(client-runtime): an update check's deadline interrupts the request it gave up on The 60-second Promise.race freed the check but left the refresh RPC running, so a repeat check could overlap it. Atom commands now take an abort signal that interrupts their effect, and the update check aborts each request at its deadline. Co-Authored-By: Claude Opus 5.5 --- apps/mobile/src/state/use-atom-command.ts | 12 +++- apps/web/src/state/use-atom-command.ts | 12 +++- packages/client-runtime/src/state/runtime.ts | 26 ++++++-- .../client-runtime/src/updateCheck.test.ts | 21 ++++-- packages/client-runtime/src/updateCheck.ts | 66 ++++++++++--------- 5 files changed, 90 insertions(+), 47 deletions(-) diff --git a/apps/mobile/src/state/use-atom-command.ts b/apps/mobile/src/state/use-atom-command.ts index b969091e7fa5..ea40105670dc 100644 --- a/apps/mobile/src/state/use-atom-command.ts +++ b/apps/mobile/src/state/use-atom-command.ts @@ -3,6 +3,7 @@ import { type AtomCommand, type AtomCommandOptions, type AtomCommandResult, + type AtomCommandRunOptions, runAtomCommand, } from "@t3tools/client-runtime/state/runtime"; import { useContext } from "react"; @@ -10,12 +11,17 @@ import { useContext } from "react"; export function useAtomCommand( command: AtomCommand, options?: string | AtomCommandOptions, -): (value: W) => Promise> { +): (value: W, run?: AtomCommandRunOptions) => Promise> { const registry = useContext(RegistryContext); const label = typeof options === "string" ? options : (options?.label ?? command.label); const reportFailure = typeof options === "string" ? true : (options?.reportFailure ?? true); const reportDefect = typeof options === "string" ? true : (options?.reportDefect ?? true); - return (value: W) => - runAtomCommand(registry, command, value, { label, reportFailure, reportDefect }); + return (value: W, run?: AtomCommandRunOptions) => + runAtomCommand(registry, command, value, { + label, + reportFailure, + reportDefect, + ...(run?.signal === undefined ? {} : { signal: run.signal }), + }); } diff --git a/apps/web/src/state/use-atom-command.ts b/apps/web/src/state/use-atom-command.ts index b969091e7fa5..ea40105670dc 100644 --- a/apps/web/src/state/use-atom-command.ts +++ b/apps/web/src/state/use-atom-command.ts @@ -3,6 +3,7 @@ import { type AtomCommand, type AtomCommandOptions, type AtomCommandResult, + type AtomCommandRunOptions, runAtomCommand, } from "@t3tools/client-runtime/state/runtime"; import { useContext } from "react"; @@ -10,12 +11,17 @@ import { useContext } from "react"; export function useAtomCommand( command: AtomCommand, options?: string | AtomCommandOptions, -): (value: W) => Promise> { +): (value: W, run?: AtomCommandRunOptions) => Promise> { const registry = useContext(RegistryContext); const label = typeof options === "string" ? options : (options?.label ?? command.label); const reportFailure = typeof options === "string" ? true : (options?.reportFailure ?? true); const reportDefect = typeof options === "string" ? true : (options?.reportDefect ?? true); - return (value: W) => - runAtomCommand(registry, command, value, { label, reportFailure, reportDefect }); + return (value: W, run?: AtomCommandRunOptions) => + runAtomCommand(registry, command, value, { + label, + reportFailure, + reportDefect, + ...(run?.signal === undefined ? {} : { signal: run.signal }), + }); } diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.ts index 736b10fdeeac..34df3130692c 100644 --- a/packages/client-runtime/src/state/runtime.ts +++ b/packages/client-runtime/src/state/runtime.ts @@ -145,9 +145,18 @@ export interface AtomCommandReporter { readonly error: (message: string, cause: Cause.Cause) => void; } +export interface AtomCommandRunOptions { + /** Aborting interrupts the command's effect, and with it any request the command is waiting on. */ + readonly signal?: AbortSignal; +} + export interface AtomCommand { readonly label: string; - readonly run: (registry: AtomRegistry.AtomRegistry, input: W) => Promise>; + readonly run: ( + registry: AtomRegistry.AtomRegistry, + input: W, + options?: AtomCommandRunOptions, + ) => Promise>; } export type AtomCommandConcurrency = @@ -339,10 +348,13 @@ export async function runAtomCommand( registry: AtomRegistry.AtomRegistry, command: AtomCommand, input: W, - options: AtomCommandOptions = {}, + options: AtomCommandOptions & AtomCommandRunOptions = {}, reporter: AtomCommandReporter = console, ): Promise> { - const result = await settleAtomCommandResult(() => command.run(registry, input)); + const { signal } = options; + const result = await settleAtomCommandResult(() => + command.run(registry, input, signal === undefined ? {} : { signal }), + ); reportAtomCommandResult(result, { ...options, label: options.label ?? command.label }, reporter); return result; } @@ -438,13 +450,17 @@ export function createRuntimeCommand( const concurrency = options.concurrency ?? { mode: "parallel" as const }; return { label: options.label, - run: (registry, input) => + run: (registry, input, run) => settleAtomCommandResult(() => scheduler.schedule(registry, concurrency, input, () => { const atom = runtime .atom(options.execute(input, registry)) .pipe(Atom.withLabel(options.label)); - return executeAtomQuery(registry, atom, { reportDefect: false, reportFailure: false }); + return executeAtomQuery(registry, atom, { + reportDefect: false, + reportFailure: false, + ...(run?.signal === undefined ? {} : { signal: run.signal }), + }); }), ), }; diff --git a/packages/client-runtime/src/updateCheck.test.ts b/packages/client-runtime/src/updateCheck.test.ts index 0d6baa3c9915..87f2c0d940c4 100644 --- a/packages/client-runtime/src/updateCheck.test.ts +++ b/packages/client-runtime/src/updateCheck.test.ts @@ -6,7 +6,9 @@ import { type ServerProvider, } from "@t3tools/contracts"; import { APP_NAME } from "@t3tools/shared/branding"; -import { AsyncResult } from "effect/reactivity"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { AsyncResult, Atom, AtomRegistry } from "effect/reactivity"; import { describe, expect, it, vi } from "vite-plus/test"; import { @@ -15,6 +17,7 @@ import { type UpdateCheckCommands, type UpdateCheckEnvironment, } from "./updateCheck.ts"; +import { createRuntimeCommand, runAtomCommand } from "./state/runtime.ts"; function provider( driver: string, @@ -118,12 +121,20 @@ describe("checkEnvironmentUpdates", () => { ]); }); - it("reports a request that never answers instead of waiting on it", async () => { + it("interrupts a request that never answers and reports it", async () => { using _timers = { [Symbol.dispose]: () => vi.useRealTimers() }; - vi.useFakeTimers(); + // Only the deadline is faked; the atom registry still releases the request on its own schedule. + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const interrupted = Promise.withResolvers(); + const registry = AtomRegistry.make(); + const refreshProviders = createRuntimeCommand(Atom.runtime(Layer.empty), { + label: "refresh-providers", + execute: () => + Effect.never.pipe(Effect.onInterrupt(() => Effect.sync(() => interrupted.resolve()))), + }); const check = checkEnvironmentUpdates([environment("studio", "0.1.10")], { lookupNpmRelease: async () => AsyncResult.success(null), - refreshProviders: () => new Promise(() => {}), + refreshProviders: (target, run) => runAtomCommand(registry, refreshProviders, target, run), timeoutMs: 2_000, }); await vi.advanceTimersByTimeAsync(2_000); @@ -138,6 +149,8 @@ describe("checkEnvironmentUpdates", () => { result: { status: "error", reason: "No answer after 2 seconds." }, }, ]); + // Only resolves once the deadline interrupts the request's effect. + await interrupted.promise; }); }); diff --git a/packages/client-runtime/src/updateCheck.ts b/packages/client-runtime/src/updateCheck.ts index e7767b2752cf..e42c257cecfa 100644 --- a/packages/client-runtime/src/updateCheck.ts +++ b/packages/client-runtime/src/updateCheck.ts @@ -13,6 +13,7 @@ import { compareSemverVersions } from "@t3tools/shared/semver"; import { type AtomCommandResult, + type AtomCommandRunOptions, isAtomCommandInterrupted, squashAtomCommandFailure, } from "./state/runtime.ts"; @@ -43,9 +44,11 @@ type Target = { readonly environmentId: EnvironmentId; readonly input: In export interface UpdateCheckCommands { readonly lookupNpmRelease: ( target: Target<{ readonly spec: "latest" | "nightly" }>, + run: AtomCommandRunOptions, ) => Promise>; readonly refreshProviders: ( target: Target<{ readonly refreshModels: true }>, + run: AtomCommandRunOptions, ) => Promise }, unknown>>; readonly timeoutMs?: number; } @@ -59,25 +62,23 @@ function reasonOf(error: unknown): string { return error instanceof Error && error.message.length > 0 ? error.message : "The check failed."; } -async function succeeded(command: Promise>): Promise { - const result = await command; - if (result._tag === "Success") return result.value; - throw isAtomCommandInterrupted(result) - ? new Error("The check was cancelled.") - : squashAtomCommandFailure(result); -} - -// A hung request must not hold the whole check, and its spinner, forever. -async function withTimeout(request: Promise, timeoutMs: number): Promise { - let timer: ReturnType | undefined; - const timeout = new Promise((_, reject) => { - timer = setTimeout( - () => reject(new Error(`No answer after ${Math.round(timeoutMs / 1000)} seconds.`)), - timeoutMs, - ); - }); +// A hung request must not hold the whole check, and its spinner, forever. The deadline interrupts +// the request itself, so a repeat check never overlaps one that is still running. +async function answered( + command: (run: AtomCommandRunOptions) => Promise>, + timeoutMs: number, +): Promise { + const deadline = new AbortController(); + const timer = setTimeout(() => deadline.abort(), timeoutMs); try { - return await Promise.race([request, timeout]); + const result = await command({ signal: deadline.signal }); + if (result._tag === "Success") return result.value; + if (deadline.signal.aborted) { + throw new Error(`No answer after ${Math.round(timeoutMs / 1000)} seconds.`); + } + throw isAtomCommandInterrupted(result) + ? new Error("The check was cancelled.") + : squashAtomCommandFailure(result); } finally { clearTimeout(timer); } @@ -97,13 +98,15 @@ async function checkServer( const channel = cliReleaseChannelOf(current); if (channel === "preview") return failed("Preview builds have no update track."); try { - const latest = await withTimeout( - succeeded( - commands.lookupNpmRelease({ - environmentId: environment.environmentId, - input: { spec: channel === "nightly" ? "nightly" : "latest" }, - }), - ), + const latest = await answered( + (run) => + commands.lookupNpmRelease( + { + environmentId: environment.environmentId, + input: { spec: channel === "nightly" ? "nightly" : "latest" }, + }, + run, + ), timeoutMs, ); if (latest === null) return failed(`No ${channel} release was found.`); @@ -152,13 +155,12 @@ async function checkProviders( return [{ subject, result: failed("You do not have permission to manage them.") }]; } try { - const { providers } = await withTimeout( - succeeded( - commands.refreshProviders({ - environmentId: environment.environmentId, - input: { refreshModels: true }, - }), - ), + const { providers } = await answered( + (run) => + commands.refreshProviders( + { environmentId: environment.environmentId, input: { refreshModels: true } }, + run, + ), timeoutMs, ); return providerUpdateItems(environment.label, providers); From 0f1abde9abc78cf9fcd2b6657c2cc6ae665c6d9a Mon Sep 17 00:00:00 2001 From: JJ Eaton <58495321+jayleaton@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:15:26 +0700 Subject: [PATCH 3/6] fix(desktop): a differential download cancelled between ranges opens no further range Cancelling during electron-updater's one-second pause after every 100th range rejected the download, but the scheduled continuation still ran and opened the next range, racing the retry. The patched DifferentialDownloader now clears that pending pause on cancel, and every range or copy step checks the cancellation token before it resumes, in both the single and multiple range paths. Co-Authored-By: Claude Opus 5.5 --- .../src/electron/ElectronUpdater.test.ts | 152 +++++++++++++----- patches/electron-updater@6.8.9.patch | 59 ++++++- pnpm-lock.yaml | 6 +- 3 files changed, 165 insertions(+), 52 deletions(-) diff --git a/apps/desktop/src/electron/ElectronUpdater.test.ts b/apps/desktop/src/electron/ElectronUpdater.test.ts index ee2ff7e1dcee..c8e5dcbec5ee 100644 --- a/apps/desktop/src/electron/ElectronUpdater.test.ts +++ b/apps/desktop/src/electron/ElectronUpdater.test.ts @@ -126,15 +126,22 @@ describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")( ); // Electron's net module only exists in Electron; node:http stands in under the real download code. +// `onRead` sees each response after electron-updater has handled its end. class NodeHttpExecutor extends ElectronHttpExecutor { + readonly onRead: (response: NodeHttp.IncomingMessage) => void; + constructor(onRead: (response: NodeHttp.IncomingMessage) => void) { + super(); + this.onRead = onRead; + } override createRequest(options: NodeHttp.RequestOptions, callback: (response: unknown) => void) { - return NodeHttp.request(options, callback) as unknown as ReturnType< - ElectronHttpExecutor["createRequest"] - >; + return NodeHttp.request(options, (response) => { + callback(response); + response.once("end", () => this.onRead(response)); + }) as unknown as ReturnType; } } -// An AppImage: two 16-byte blocks, then its deflated block map and the map's length. +// An AppImage: 16-byte blocks, then its deflated block map and the map's length. const appImage = (blocks: ReadonlyArray) => { const blockMap = NodeZlib.deflateRawSync( JSON.stringify({ @@ -144,24 +151,37 @@ const appImage = (blocks: ReadonlyArray) => { ); const blockMapSize = Buffer.alloc(4); blockMapSize.writeUInt32BE(blockMap.length); - const content = Buffer.from(blocks.map((block) => block.repeat(16)).join("")); + const content = Buffer.from(blocks.map((block) => block.repeat(16).slice(0, 16)).join("")); return { file: Buffer.concat([content, blockMap, blockMapSize]), blockMapSize: blockMap.length }; }; -// Serves the new AppImage's block map, but stalls the update's own bytes after a few of them. -const stallingUpdateServer = Effect.fn(function* (file: Buffer) { +type AppImage = ReturnType; + +// Serves the update, reports where each request into its blocks starts, and stalls the requests +// `stall` picks after a few bytes. +const stallingUpdateServer = Effect.fn(function* ( + update: AppImage, + stall: (start: number, seen: number) => boolean, +) { + const { file } = update; + const blocksEnd = file.length - update.blockMapSize - 4; const stalls = yield* Queue.unbounded>(); + const requests = yield* Queue.unbounded(); + const seen = new Map(); const server = yield* Effect.acquireRelease( Effect.callback((resume) => { const server = NodeHttp.createServer((request, response) => { const range = /bytes=(\d+)-(\d+)/.exec(request.headers.range ?? ""); const [start, end] = range ? [Number(range[1]), Number(range[2])] : [0, file.length - 1]; const body = file.subarray(start, end + 1); + const count = (seen.get(start) ?? 0) + 1; + seen.set(start, count); + if (start < blocksEnd) Queue.offerUnsafe(requests, start); response.writeHead(range ? 206 : 200, { "content-length": body.length, ...(range ? { "content-range": `bytes ${start}-${end}/${file.length}` } : {}), }); - if (start >= 32) { + if (!stall(start, count)) { response.end(body); return; } @@ -180,7 +200,55 @@ const stallingUpdateServer = Effect.fn(function* (file: Buffer) { ); const address = server.address(); const port = typeof address === "object" && address !== null ? address.port : 0; - return { url: new URL(`http://127.0.0.1:${port}/T3-Code-1.0.1.AppImage`), stalls }; + return { url: new URL(`http://127.0.0.1:${port}/T3-Code-1.0.1.AppImage`), stalls, requests }; +}); + +// Points the real autoUpdater at an installed ["A", "B"] AppImage and a local server for `update`. +// `read` gets the start of each range of blocks electron-updater has finished reading. +const serveUpdate = Effect.fn(function* ( + update: AppImage, + options: { + readonly differential: boolean; + readonly stall: (start: number, seen: number) => boolean; + }, +) { + const fileSystem = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + const dir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-update-stall-" }); + const installedPath = path.join(dir, "T3-Code.AppImage"); + yield* fileSystem.writeFile(installedPath, appImage(["A", "B"]).file); + yield* Effect.acquireRelease( + Effect.sync(() => vi.stubEnv("APPIMAGE", installedPath)), + () => Effect.sync(() => vi.unstubAllEnvs()), + ); + const server = yield* stallingUpdateServer(update, options.stall); + const { url } = server; + const blocksEnd = update.file.length - update.blockMapSize - 4; + const read = yield* Queue.unbounded(); + const fileInfo = { + url: url.pathname.slice(1), + size: update.file.length, + blockMapSize: update.blockMapSize, + sha512: NodeCrypto.createHash("sha512").update(update.file).digest("base64"), + }; + autoUpdater.logger = null; + autoUpdater.disableDifferentialDownload = !options.differential; + Object.assign(autoUpdater, { + httpExecutor: new NodeHttpExecutor((response) => { + const start = Number(/bytes (\d+)-/.exec(response.headers["content-range"] ?? "")?.[1]); + if (start < blocksEnd) Queue.offerUnsafe(read, start); + }), + downloadedUpdateHelper: new DownloadedUpdateHelper(path.join(dir, "cache")), + updateInfoAndProvider: { + info: { version: "1.0.1", files: [fileInfo], path: fileInfo.url, ...fileInfo }, + provider: { + resolveFiles: () => [{ url, info: fileInfo }], + fileExtraDownloadHeaders: null, + isUseMultipleRangeRequest: false, + }, + }, + }); + return { ...server, read }; }); describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")( @@ -188,39 +256,10 @@ describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")( () => { const cancelAndRetry = (differential: boolean) => Effect.gen(function* () { - const fileSystem = yield* FileSystem.FileSystem; - const path = yield* Path.Path; - const dir = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-update-stall-" }); - const installed = appImage(["A", "B"]); - const update = appImage(["A", "C"]); - const installedPath = path.join(dir, "T3-Code.AppImage"); - yield* fileSystem.writeFile(installedPath, installed.file); - yield* Effect.acquireRelease( - Effect.sync(() => vi.stubEnv("APPIMAGE", installedPath)), - () => Effect.sync(() => vi.unstubAllEnvs()), - ); - const { url, stalls } = yield* stallingUpdateServer(update.file); - const fileInfo = { - url: url.pathname.slice(1), - size: update.file.length, - blockMapSize: update.blockMapSize, - sha512: NodeCrypto.createHash("sha512").update(update.file).digest("base64"), - }; - autoUpdater.logger = null; - autoUpdater.disableDifferentialDownload = !differential; - Object.assign(autoUpdater, { - httpExecutor: new NodeHttpExecutor(), - downloadedUpdateHelper: new DownloadedUpdateHelper(path.join(dir, "cache")), - updateInfoAndProvider: { - info: { version: "1.0.1", files: [fileInfo], path: fileInfo.url, ...fileInfo }, - provider: { - resolveFiles: () => [{ url, info: fileInfo }], - fileExtraDownloadHeaders: null, - isUseMultipleRangeRequest: false, - }, - }, + const { stalls } = yield* serveUpdate(appImage(["A", "C"]), { + differential, + stall: (start) => start < 32, }); - const electronUpdater = yield* ElectronUpdater.ElectronUpdater; yield* electronUpdater.on("error", () => undefined); const download = yield* Effect.forkChild(electronUpdater.downloadUpdate); @@ -244,5 +283,36 @@ describe.skipIf(HostProcess.Platform.defaultValue() !== "linux")( "a cancelled differential download closes its request and a retry downloads again", () => cancelAndRetry(true), ); + + it.live("a differential download cancelled between ranges opens no further range", () => + Effect.gen(function* () { + // 101 changed blocks between copies of "A": electron-updater pauses for a second after + // the 100th range before it copies "A" and opens the last one. + const update = appImage( + Array.from({ length: 101 }, (_, index) => ["A", `n${index}`]).flat(), + ); + const firstRange = 16; + const { stalls, requests, read } = yield* serveUpdate(update, { + differential: true, + // The retry stalls on its first range, so any later range is the cancelled download's. + stall: (start, seen) => start === firstRange && seen > 1, + }); + const electronUpdater = yield* ElectronUpdater.ElectronUpdater; + yield* electronUpdater.on("error", () => undefined); + const download = yield* Effect.forkChild(electronUpdater.downloadUpdate); + // Reading the 100th range starts the pause. + yield* Queue.takeN(read, 100); + yield* Fiber.interrupt(download); + yield* Queue.clear(requests); + + const retry = yield* Effect.forkChild(electronUpdater.downloadUpdate); + yield* Queue.take(stalls); + assert.strictEqual(yield* Queue.take(requests), firstRange, "the retry did not start over"); + // The cancelled download's pause ends a second after it began. + const late = yield* Queue.take(requests).pipe(Effect.timeoutOption("2 seconds")); + assert.deepStrictEqual(late, Option.none(), "the cancelled download opened another range"); + yield* Fiber.interrupt(retry); + }).pipe(Effect.scoped, Effect.provide([ElectronUpdater.layer, NodeServices.layer])), + ); }, ); diff --git a/patches/electron-updater@6.8.9.patch b/patches/electron-updater@6.8.9.patch index 93c2c9770112..b52504cbe93e 100644 --- a/patches/electron-updater@6.8.9.patch +++ b/patches/electron-updater@6.8.9.patch @@ -1,5 +1,5 @@ diff --git a/out/differentialDownloader/DifferentialDownloader.js b/out/differentialDownloader/DifferentialDownloader.js -index c6e948a79d1bb85122b21d8ddd61a5a842ca2e8d..8ccd51497b6d1ce3047afbeabac6a74cf8923f56 100644 +index c6e948a79d1bb85122b21d8ddd61a5a842ca2e8d..df016d23efad23dc21212912a70ae8066cf8d974 100644 --- a/out/differentialDownloader/DifferentialDownloader.js +++ b/out/differentialDownloader/DifferentialDownloader.js @@ -17,6 +17,20 @@ class DifferentialDownloader { @@ -23,17 +23,31 @@ index c6e948a79d1bb85122b21d8ddd61a5a842ca2e8d..8ccd51497b6d1ce3047afbeabac6a74c } createRequestOptions() { const result = { -@@ -98,7 +112,8 @@ class DifferentialDownloader { +@@ -98,7 +112,12 @@ class DifferentialDownloader { const newFileFd = await (0, fs_extra_1.open)(this.options.newFile, "w"); fdList.push({ descriptor: newFileFd, path: this.options.newFile }); const fileOut = (0, fs_1.createWriteStream)(this.options.newFile, { fd: newFileFd }); - await new Promise((resolve, reject) => { + await this.options.cancellationToken.createPromise((resolve, reject, onCancel) => { -+ onCancel(() => this.abortRequests()); ++ let pause = null; ++ onCancel(() => { ++ clearTimeout(pause); ++ this.abortRequests(); ++ }); const streams = []; // Create our download info transformer if we have one let downloadInfoTransform = undefined; -@@ -186,7 +201,7 @@ class DifferentialDownloader { +@@ -163,6 +182,9 @@ class DifferentialDownloader { + requestOptions.redirect = "manual"; + w = (index) => { + var _a, _b; ++ if (this.options.cancellationToken.cancelled) { ++ return; ++ } + if (index >= tasks.length) { + if (this.fileMetadataBuffer != null) { + firstStream.write(this.fileMetadataBuffer); +@@ -186,7 +208,7 @@ class DifferentialDownloader { if (downloadInfoTransform) { downloadInfoTransform.beginRangeDownload(); } @@ -42,7 +56,16 @@ index c6e948a79d1bb85122b21d8ddd61a5a842ca2e8d..8ccd51497b6d1ce3047afbeabac6a74c response.on("error", reject); response.on("aborted", () => { reject(new Error("response has been aborted by the server")); -@@ -239,8 +254,9 @@ class DifferentialDownloader { +@@ -205,7 +227,7 @@ class DifferentialDownloader { + } + if (++downloadOperationCount === 100) { + downloadOperationCount = 0; +- setTimeout(() => w(index), 1000); ++ pause = setTimeout(() => w(index), 1000); + } + else { + w(index); +@@ -239,8 +261,9 @@ class DifferentialDownloader { return buffer; } request(requestOptions, dataHandler) { @@ -55,10 +78,30 @@ index c6e948a79d1bb85122b21d8ddd61a5a842ca2e8d..8ccd51497b6d1ce3047afbeabac6a74c return; } diff --git a/out/differentialDownloader/multipleRangeDownloader.js b/out/differentialDownloader/multipleRangeDownloader.js -index 56adc38fe831b39d8430ad8aabe8fd7a35c36b9f..4ec2494a8c64973d3cc498b124817596ace5d690 100644 +index 56adc38fe831b39d8430ad8aabe8fd7a35c36b9f..436086963c64fbe8bd5126685375dc54e669faf9 100644 --- a/out/differentialDownloader/multipleRangeDownloader.js +++ b/out/differentialDownloader/multipleRangeDownloader.js -@@ -54,7 +54,7 @@ function doExecuteTasks(differentialDownloader, options, out, resolve, reject) { +@@ -7,6 +7,9 @@ const DataSplitter_1 = require("./DataSplitter"); + const downloadPlanBuilder_1 = require("./downloadPlanBuilder"); + function executeTasksUsingMultipleRangeRequests(differentialDownloader, tasks, out, oldFileFd, reject) { + const w = (taskOffset) => { ++ if (differentialDownloader.options.cancellationToken.cancelled) { ++ return; ++ } + if (taskOffset >= tasks.length) { + if (differentialDownloader.fileMetadataBuffer != null) { + out.write(differentialDownloader.fileMetadataBuffer); +@@ -43,6 +46,9 @@ function doExecuteTasks(differentialDownloader, options, out, resolve, reject) { + if (partCount <= 1) { + // the only remote range - copy + const w = (index) => { ++ if (differentialDownloader.options.cancellationToken.cancelled) { ++ return; ++ } + if (index >= options.end) { + resolve(); + return; +@@ -54,7 +60,7 @@ function doExecuteTasks(differentialDownloader, options, out, resolve, reject) { else { const requestOptions = differentialDownloader.createRequestOptions(); requestOptions.headers.Range = `bytes=${task.start}-${task.end - 1}`; @@ -67,7 +110,7 @@ index 56adc38fe831b39d8430ad8aabe8fd7a35c36b9f..4ec2494a8c64973d3cc498b124817596 response.on("error", reject); if (!checkIsRangesSupported(response, reject)) { return; -@@ -73,7 +73,7 @@ function doExecuteTasks(differentialDownloader, options, out, resolve, reject) { +@@ -73,7 +79,7 @@ function doExecuteTasks(differentialDownloader, options, out, resolve, reject) { } const requestOptions = differentialDownloader.createRequestOptions(); requestOptions.headers.Range = ranges.substring(0, ranges.length - 2); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a3f450eac5ec..736a72ca7504 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -352,7 +352,7 @@ patchedDependencies: app-builder-lib@26.16.1: 0fbe9ae51783f5768ebe197d12d1fdb7d477a08c92e5db2f6356bcce62613c53 builder-util-runtime@9.7.0: 73c6552e5248b5eb7f929ef7361a439158de232e1a07511cb3c9a0dc593b2848 dbus-next@0.10.2: cfff57561b0ee59b5addb3b2e6c6f20906e967507a530ab67e8db8108e520ba4 - electron-updater@6.8.9: 90230fa7d39dc2abd7792a1e1c79ac4161da589e1cca917abe3f48e613fda7e2 + electron-updater@6.8.9: bac0ebe4c21f705c797b8507ad4dc9a57c096712c1e432df119cecb13522b970 expo-audio@58.0.11: 93691f7f59edb30a3bb2c23b489e605e7ea35506b1212d4a2ebbd1fd79079483 expo-modules-core@58.0.30: f0b0fd100550ed76e5c25b4d13eb7c9ff62825f8f197c53edf7bf447c50c9fb7 expo-network@58.0.4: 159c2d760d1cd5102e95df51c20600111e7a72096ef0daea8215d50cae48bd98 @@ -436,7 +436,7 @@ importers: version: 44.10.1(supports-color@8.1.1) electron-updater: specifier: 6.8.9 - version: 6.8.9(patch_hash=90230fa7d39dc2abd7792a1e1c79ac4161da589e1cca917abe3f48e613fda7e2)(supports-color@8.1.1) + version: 6.8.9(patch_hash=bac0ebe4c21f705c797b8507ad4dc9a57c096712c1e432df119cecb13522b970)(supports-color@8.1.1) electron-webauthn: specifier: 'catalog:' version: 1.3.1(typescript@6.0.3) @@ -18130,7 +18130,7 @@ snapshots: electron-to-chromium@1.5.430: {} - electron-updater@6.8.9(patch_hash=90230fa7d39dc2abd7792a1e1c79ac4161da589e1cca917abe3f48e613fda7e2)(supports-color@8.1.1): + electron-updater@6.8.9(patch_hash=bac0ebe4c21f705c797b8507ad4dc9a57c096712c1e432df119cecb13522b970)(supports-color@8.1.1): dependencies: builder-util-runtime: 9.7.0(patch_hash=73c6552e5248b5eb7f929ef7361a439158de232e1a07511cb3c9a0dc593b2848)(supports-color@8.1.1) fs-extra: 10.1.0 From da20a0633e81f3964009893de00d3e707ed66da2 Mon Sep 17 00:00:00 2001 From: JJ Eaton <58495321+jayleaton@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:21:47 +0700 Subject: [PATCH 4/6] fix(client-runtime): an update check that joins a running provider refresh stops at its deadline A single-flight command hands a joining caller the running promise, so the caller's abort signal never reached it and the update check kept spinning past its 60-second deadline. Each caller's wait now ends when its own signal aborts, and the shared refresh-providers run is interrupted after 60 seconds, so the request itself ends even when no caller can cancel it. Co-Authored-By: Claude Opus 5.5 --- packages/client-runtime/src/state/runtime.ts | 55 +++++++++++++++---- packages/client-runtime/src/state/server.ts | 2 + .../client-runtime/src/updateCheck.test.ts | 32 ++++++++++- 3 files changed, 77 insertions(+), 12 deletions(-) diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.ts index 34df3130692c..3c90f0adaafc 100644 --- a/packages/client-runtime/src/state/runtime.ts +++ b/packages/client-runtime/src/state/runtime.ts @@ -9,6 +9,7 @@ import { type EnvironmentId as EnvironmentIdType, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; +import type * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Option from "effect/Option"; @@ -78,6 +79,7 @@ interface EnvironmentCommandAtomOptions extends Omit< registry: AtomRegistry.AtomRegistry, environmentId: EnvironmentIdType, ) => Effect.Effect; + readonly timeout?: Duration.Input; } interface EnvironmentQueryAtomOptions extends Omit< @@ -201,6 +203,20 @@ async function settleAtomCommandResult( } } +// A caller may have joined a run another caller started, so its own signal only ends its wait. +function abandonOnAbort( + result: Promise>, + signal: AbortSignal | undefined, +): Promise> { + if (signal === undefined) return result; + if (signal.aborted) return Promise.resolve(AsyncResult.failure(Cause.interrupt())); + return new Promise((resolve) => { + const abandon = () => resolve(AsyncResult.failure(Cause.interrupt())); + signal.addEventListener("abort", abandon, { once: true }); + void result.then(resolve).finally(() => signal.removeEventListener("abort", abandon)); + }); +} + export function createAtomCommandScheduler(): AtomCommandScheduler { const registryStates = new WeakMap(); @@ -444,6 +460,8 @@ export function createRuntimeCommand( readonly execute: (input: W, registry: AtomRegistry.AtomRegistry) => Effect.Effect; readonly scheduler?: AtomCommandScheduler; readonly concurrency?: AtomCommandConcurrency; + /** Interrupts a run that lasts longer, ending its request for every caller waiting on it. */ + readonly timeout?: Duration.Input; }, ): AtomCommand { const scheduler = options.scheduler ?? createAtomCommandScheduler(); @@ -451,17 +469,29 @@ export function createRuntimeCommand( return { label: options.label, run: (registry, input, run) => - settleAtomCommandResult(() => - scheduler.schedule(registry, concurrency, input, () => { - const atom = runtime - .atom(options.execute(input, registry)) - .pipe(Atom.withLabel(options.label)); - return executeAtomQuery(registry, atom, { - reportDefect: false, - reportFailure: false, - ...(run?.signal === undefined ? {} : { signal: run.signal }), - }); - }), + abandonOnAbort( + settleAtomCommandResult(() => + scheduler.schedule(registry, concurrency, input, () => { + const execute = options.execute(input, registry); + const { timeout } = options; + const atom = runtime + .atom( + timeout === undefined + ? execute + : Effect.timeoutOrElse(execute, { + duration: timeout, + orElse: () => Effect.interrupt, + }), + ) + .pipe(Atom.withLabel(options.label)); + return executeAtomQuery(registry, atom, { + reportDefect: false, + reportFailure: false, + ...(run?.signal === undefined ? {} : { signal: run.signal }), + }); + }), + ), + run?.signal, ), }; } @@ -948,6 +978,7 @@ export function createEnvironmentCommand( label: options.label, ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }), ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }), + ...(options.timeout === undefined ? {} : { timeout: options.timeout }), execute: (target, registry) => runInEnvironment( target.environmentId, @@ -1082,6 +1113,7 @@ export function createEnvironmentRpcCommand< readonly environmentId: EnvironmentIdType; readonly input: NoInfer; }>; + readonly timeout?: Duration.Input; readonly onSuccess?: ( target: { readonly environmentId: EnvironmentIdType; @@ -1105,6 +1137,7 @@ export function createEnvironmentRpcCommand< label: options.label, ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }), ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }), + ...(options.timeout === undefined ? {} : { timeout: options.timeout }), execute: (input: Input, registry, environmentId) => { const target = { environmentId, diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index a1c338f90413..05e083c97866 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -1714,6 +1714,8 @@ export function createServerEnvironmentAtoms( input.modelCatalogOnly ?? false, ]), }, + // Callers that join a running refresh cannot cancel it, so a stalled one must still end. + timeout: "60 seconds", }), updateProvider: createEnvironmentRpcCommand(runtime, { label: "environment-data:server:update-provider", diff --git a/packages/client-runtime/src/updateCheck.test.ts b/packages/client-runtime/src/updateCheck.test.ts index 87f2c0d940c4..0cf9295b6a7e 100644 --- a/packages/client-runtime/src/updateCheck.test.ts +++ b/packages/client-runtime/src/updateCheck.test.ts @@ -17,7 +17,7 @@ import { type UpdateCheckCommands, type UpdateCheckEnvironment, } from "./updateCheck.ts"; -import { createRuntimeCommand, runAtomCommand } from "./state/runtime.ts"; +import { createRuntimeCommand, isAtomCommandInterrupted, runAtomCommand } from "./state/runtime.ts"; function provider( driver: string, @@ -152,6 +152,36 @@ describe("checkEnvironmentUpdates", () => { // Only resolves once the deadline interrupts the request's effect. await interrupted.promise; }); + + it("stops waiting on a refresh it joined, which the refresh's own bound interrupts", async () => { + using _timers = { [Symbol.dispose]: () => vi.useRealTimers() }; + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const interrupted = Promise.withResolvers(); + const registry = AtomRegistry.make(); + const refreshProviders = createRuntimeCommand(Atom.runtime(Layer.empty), { + label: "refresh-providers", + concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId }, + timeout: "5 seconds", + execute: (_: { readonly environmentId: string }) => + Effect.never.pipe(Effect.onInterrupt(() => Effect.sync(() => interrupted.resolve()))), + }); + // Started elsewhere, with no deadline of its own. + const elsewhere = runAtomCommand(registry, refreshProviders, { environmentId: "studio" }); + const check = checkEnvironmentUpdates([environment("studio", "0.1.10")], { + lookupNpmRelease: async () => AsyncResult.success(null), + refreshProviders: (target, run) => runAtomCommand(registry, refreshProviders, target, run), + timeoutMs: 2_000, + }); + await vi.advanceTimersByTimeAsync(2_000); + + expect((await check)[1]).toEqual({ + subject: "Providers on studio", + result: { status: "error", reason: "No answer after 2 seconds." }, + }); + await vi.advanceTimersByTimeAsync(3_000); + await interrupted.promise; + expect(isAtomCommandInterrupted(await elsewhere)).toBe(true); + }); }); describe("summarizeUpdateCheck", () => { From d42e96209836fa079499907b46badf0c1b2c5ead Mon Sep 17 00:00:00 2001 From: JJ Eaton <58495321+jayleaton@users.noreply.github.com> Date: Fri, 20 Nov 2026 00:20:20 +0700 Subject: [PATCH 5/6] fix(client-runtime): a shared provider refresh outlives the caller that started it The 60 s deadline now belongs to the update check alone. Manual refreshes keep the server's own provider budgets, so a 75 s Antigravity model discovery is no longer cut off. A single-flight run gets its own AbortController. Each caller's signal only ends that caller's wait, and the run is cancelled once the last waiter leaves. runAtomCommand keeps the two-argument call when there is no signal. Co-Authored-By: Claude Opus 5.5 --- packages/client-runtime/src/state/runtime.ts | 124 ++++++++++-------- .../client-runtime/src/state/server.test.ts | 78 +++++++++++ packages/client-runtime/src/state/server.ts | 2 - .../client-runtime/src/updateCheck.test.ts | 49 +++++-- 4 files changed, 184 insertions(+), 69 deletions(-) diff --git a/packages/client-runtime/src/state/runtime.ts b/packages/client-runtime/src/state/runtime.ts index 3c90f0adaafc..84ab894b9e84 100644 --- a/packages/client-runtime/src/state/runtime.ts +++ b/packages/client-runtime/src/state/runtime.ts @@ -9,7 +9,6 @@ import { type EnvironmentId as EnvironmentIdType, } from "@t3tools/contracts"; import * as Cause from "effect/Cause"; -import type * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Option from "effect/Option"; @@ -79,7 +78,6 @@ interface EnvironmentCommandAtomOptions extends Omit< registry: AtomRegistry.AtomRegistry, environmentId: EnvironmentIdType, ) => Effect.Effect; - readonly timeout?: Duration.Input; } interface EnvironmentQueryAtomOptions extends Omit< @@ -168,9 +166,15 @@ export type AtomCommandConcurrency = readonly key: (input: W) => string; }; +interface AtomCommandFlight { + readonly result: Promise>; + readonly controller: AbortController; + waiters: number; +} + interface AtomCommandSchedulerState { readonly serial: Map>; - readonly singleFlight: Map>; + readonly singleFlight: Map; readonly latest: Map; } @@ -185,11 +189,13 @@ interface AtomCommandLatestLane { } export interface AtomCommandScheduler { + /** `signal` ends this caller's wait; a shared single-flight run is cancelled once no caller waits. */ readonly schedule: ( registry: AtomRegistry.AtomRegistry, concurrency: AtomCommandConcurrency, input: W, - execute: () => Promise>, + execute: (signal: AbortSignal | undefined) => Promise>, + signal?: AbortSignal, ) => Promise>; } @@ -203,17 +209,20 @@ async function settleAtomCommandResult( } } -// A caller may have joined a run another caller started, so its own signal only ends its wait. +// A caller may share a run with other callers, so its own signal only ends its wait. function abandonOnAbort( result: Promise>, signal: AbortSignal | undefined, + onAbandon?: () => void, ): Promise> { if (signal === undefined) return result; - if (signal.aborted) return Promise.resolve(AsyncResult.failure(Cause.interrupt())); - return new Promise((resolve) => { - const abandon = () => resolve(AsyncResult.failure(Cause.interrupt())); + return new Promise((resolve, reject) => { + const abandon = () => { + resolve(AsyncResult.failure(Cause.interrupt())); + onAbandon?.(); + }; signal.addEventListener("abort", abandon, { once: true }); - void result.then(resolve).finally(() => signal.removeEventListener("abort", abandon)); + void result.then(resolve, reject).finally(() => signal.removeEventListener("abort", abandon)); }); } @@ -239,41 +248,52 @@ export function createAtomCommandScheduler(): AtomCommandScheduler { registry: AtomRegistry.AtomRegistry, concurrency: AtomCommandConcurrency, input: W, - execute: () => Promise>, + execute: (signal: AbortSignal | undefined) => Promise>, + signal?: AbortSignal, ): Promise> => { + if (signal?.aborted) { + return Promise.resolve(AsyncResult.failure(Cause.interrupt())); + } if (concurrency.mode === "parallel") { - return execute(); + return abandonOnAbort(execute(signal), signal); } const key = concurrency.key(input); const state = stateFor(registry); if (concurrency.mode === "singleFlight") { - const existing = state.singleFlight.get(key) as - | Promise> - | undefined; - if (existing !== undefined) { - return existing; - } - const current = execute(); - state.singleFlight.set(key, current); - void current.then( - () => { - if (state.singleFlight.get(key) === current) { - state.singleFlight.delete(key); - } - }, - () => { - if (state.singleFlight.get(key) === current) { + let flight = state.singleFlight.get(key); + if (flight === undefined) { + const controller = new AbortController(); + const started: AtomCommandFlight = { + result: execute(controller.signal), + controller, + waiters: 0, + }; + const settle = () => { + if (state.singleFlight.get(key) === started) { state.singleFlight.delete(key); } - }, - ); - return current; + }; + void started.result.then(settle, settle); + state.singleFlight.set(key, started); + flight = started; + } + const joined = flight; + joined.waiters += 1; + return abandonOnAbort(joined.result as Promise>, signal, () => { + joined.waiters -= 1; + if (joined.waiters > 0) return; + if (state.singleFlight.get(key) === joined) { + state.singleFlight.delete(key); + } + joined.controller.abort(); + }); } if (concurrency.mode === "serial") { const previous = state.serial.get(key); - const current = previous === undefined ? execute() : previous.then(execute, execute); + const run = () => execute(signal); + const current = previous === undefined ? run() : previous.then(run, run); state.serial.set(key, current); void current.then( () => { @@ -287,7 +307,7 @@ export function createAtomCommandScheduler(): AtomCommandScheduler { } }, ); - return current; + return abandonOnAbort(current, signal); } let lane = state.latest.get(key); @@ -296,16 +316,17 @@ export function createAtomCommandScheduler(): AtomCommandScheduler { state.latest.set(key, lane); } const activeLane = lane; + const run = () => execute(signal); const result = new Promise>((resolve) => { if (activeLane.pending === undefined) { activeLane.pending = { - execute: execute as () => Promise>, + execute: run as () => Promise>, resolve: [resolve as (result: AtomCommandResult) => void], }; return; } - activeLane.pending.execute = execute as () => Promise>; + activeLane.pending.execute = run as () => Promise>; activeLane.pending.resolve.push( resolve as (result: AtomCommandResult) => void, ); @@ -334,7 +355,7 @@ export function createAtomCommandScheduler(): AtomCommandScheduler { })(); } - return result; + return abandonOnAbort(result, signal); }, }; } @@ -369,7 +390,7 @@ export async function runAtomCommand( ): Promise> { const { signal } = options; const result = await settleAtomCommandResult(() => - command.run(registry, input, signal === undefined ? {} : { signal }), + signal === undefined ? command.run(registry, input) : command.run(registry, input, { signal }), ); reportAtomCommandResult(result, { ...options, label: options.label ?? command.label }, reporter); return result; @@ -460,8 +481,6 @@ export function createRuntimeCommand( readonly execute: (input: W, registry: AtomRegistry.AtomRegistry) => Effect.Effect; readonly scheduler?: AtomCommandScheduler; readonly concurrency?: AtomCommandConcurrency; - /** Interrupts a run that lasts longer, ending its request for every caller waiting on it. */ - readonly timeout?: Duration.Input; }, ): AtomCommand { const scheduler = options.scheduler ?? createAtomCommandScheduler(); @@ -469,29 +488,23 @@ export function createRuntimeCommand( return { label: options.label, run: (registry, input, run) => - abandonOnAbort( - settleAtomCommandResult(() => - scheduler.schedule(registry, concurrency, input, () => { - const execute = options.execute(input, registry); - const { timeout } = options; + settleAtomCommandResult(() => + scheduler.schedule( + registry, + concurrency, + input, + (signal) => { const atom = runtime - .atom( - timeout === undefined - ? execute - : Effect.timeoutOrElse(execute, { - duration: timeout, - orElse: () => Effect.interrupt, - }), - ) + .atom(options.execute(input, registry)) .pipe(Atom.withLabel(options.label)); return executeAtomQuery(registry, atom, { reportDefect: false, reportFailure: false, - ...(run?.signal === undefined ? {} : { signal: run.signal }), + ...(signal === undefined ? {} : { signal }), }); - }), + }, + run?.signal, ), - run?.signal, ), }; } @@ -978,7 +991,6 @@ export function createEnvironmentCommand( label: options.label, ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }), ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }), - ...(options.timeout === undefined ? {} : { timeout: options.timeout }), execute: (target, registry) => runInEnvironment( target.environmentId, @@ -1113,7 +1125,6 @@ export function createEnvironmentRpcCommand< readonly environmentId: EnvironmentIdType; readonly input: NoInfer; }>; - readonly timeout?: Duration.Input; readonly onSuccess?: ( target: { readonly environmentId: EnvironmentIdType; @@ -1137,7 +1148,6 @@ export function createEnvironmentRpcCommand< label: options.label, ...(options.scheduler === undefined ? {} : { scheduler: options.scheduler }), ...(options.concurrency === undefined ? {} : { concurrency: options.concurrency }), - ...(options.timeout === undefined ? {} : { timeout: options.timeout }), execute: (input: Input, registry, environmentId) => { const target = { environmentId, diff --git a/packages/client-runtime/src/state/server.test.ts b/packages/client-runtime/src/state/server.test.ts index e6ce1725cc15..77048c651477 100644 --- a/packages/client-runtime/src/state/server.test.ts +++ b/packages/client-runtime/src/state/server.test.ts @@ -1,4 +1,5 @@ import { + AuthOrchestrationReadScope, EnvironmentId, ProviderDriverKind, ServerSelfUpdateError, @@ -73,6 +74,7 @@ import { runDesktopCommitWithReconnectObserver, } from "./server.ts"; import { applyServerConfigProjection } from "./serverConfigProjection.ts"; +import { createEnvironmentSessionAtoms } from "./session.ts"; const CONFIG = { availableEditors: [], @@ -1840,6 +1842,82 @@ describe("provider setup commands", () => { expect(yield* Fiber.join(saved)).toBe(true); }), ); + + it.effect("lets a manual provider refresh outlast a minute", () => + Effect.gen(function* () { + using _timers = { [Symbol.dispose]: () => vi.useRealTimers() }; + vi.useFakeTimers(); + // Antigravity model discovery may take up to 90 seconds on the server. + const client = { + [WS_METHODS.serverRefreshProviders]: () => + Effect.sleep("75 seconds").pipe(Effect.as({ providers: [] })), + } as unknown as WsRpcProtocolClient; + const supervisor = EnvironmentSupervisor.EnvironmentSupervisor.of({ + target: TARGET, + state: yield* SubscriptionRef.make(AVAILABLE_CONNECTION_STATE), + session: yield* SubscriptionRef.make(Option.some(session(client))), + prepared: yield* SubscriptionRef.make(Option.none()), + connect: Effect.void, + disconnect: Effect.void, + retryNow: Effect.void, + } satisfies EnvironmentSupervisor.EnvironmentSupervisor["Service"]); + const runtime = Atom.runtime( + Layer.mergeAll( + Layer.succeed(EnvironmentRegistry.EnvironmentRegistry, { + run: (_environmentId, effect) => + Effect.provideService( + effect, + EnvironmentSupervisor.EnvironmentSupervisor, + supervisor, + ), + } as EnvironmentRegistry.EnvironmentRegistry["Service"]), + Layer.succeed( + Persistence.EnvironmentCacheStore, + {} as Persistence.EnvironmentCacheStore["Service"], + ), + ), + ); + const atoms = createServerEnvironmentAtoms(runtime, { + initialConfigValueAtom: () => Atom.make(CONFIG), + }); + const sessionState = createEnvironmentSessionAtoms(runtime).sessionStateAtom( + TARGET.environmentId, + ); + const registry = yield* Effect.acquireRelease( + Effect.sync(() => + AtomRegistry.make({ + initialValues: [ + [ + sessionState, + AsyncResult.success({ + authenticated: true, + auth: { + policy: "remote-reachable", + bootstrapMethods: [], + sessionMethods: [], + sessionCookieName: "test", + }, + scopes: [AuthOrchestrationReadScope], + }), + ], + ], + }), + ), + (registry) => Effect.sync(() => registry.dispose()), + ); + + const refresh = atoms.refreshProviders.run(registry, { + environmentId: TARGET.environmentId, + input: { refreshModels: true }, + }); + yield* Effect.promise(() => vi.advanceTimersByTimeAsync(75_000)); + + expect(yield* Effect.promise(() => refresh)).toMatchObject({ + _tag: "Success", + value: { providers: [] }, + }); + }), + ); }); describe("resource telemetry history", () => { diff --git a/packages/client-runtime/src/state/server.ts b/packages/client-runtime/src/state/server.ts index 05e083c97866..a1c338f90413 100644 --- a/packages/client-runtime/src/state/server.ts +++ b/packages/client-runtime/src/state/server.ts @@ -1714,8 +1714,6 @@ export function createServerEnvironmentAtoms( input.modelCatalogOnly ?? false, ]), }, - // Callers that join a running refresh cannot cancel it, so a stalled one must still end. - timeout: "60 seconds", }), updateProvider: createEnvironmentRpcCommand(runtime, { label: "environment-data:server:update-provider", diff --git a/packages/client-runtime/src/updateCheck.test.ts b/packages/client-runtime/src/updateCheck.test.ts index 0cf9295b6a7e..bb1c9f237635 100644 --- a/packages/client-runtime/src/updateCheck.test.ts +++ b/packages/client-runtime/src/updateCheck.test.ts @@ -17,7 +17,7 @@ import { type UpdateCheckCommands, type UpdateCheckEnvironment, } from "./updateCheck.ts"; -import { createRuntimeCommand, isAtomCommandInterrupted, runAtomCommand } from "./state/runtime.ts"; +import { createRuntimeCommand, runAtomCommand } from "./state/runtime.ts"; function provider( driver: string, @@ -153,20 +153,17 @@ describe("checkEnvironmentUpdates", () => { await interrupted.promise; }); - it("stops waiting on a refresh it joined, which the refresh's own bound interrupts", async () => { + it("stops waiting on a refresh it joined at its own deadline", async () => { using _timers = { [Symbol.dispose]: () => vi.useRealTimers() }; vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); - const interrupted = Promise.withResolvers(); const registry = AtomRegistry.make(); const refreshProviders = createRuntimeCommand(Atom.runtime(Layer.empty), { label: "refresh-providers", concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId }, - timeout: "5 seconds", - execute: (_: { readonly environmentId: string }) => - Effect.never.pipe(Effect.onInterrupt(() => Effect.sync(() => interrupted.resolve()))), + execute: (_: { readonly environmentId: string }) => Effect.never, }); // Started elsewhere, with no deadline of its own. - const elsewhere = runAtomCommand(registry, refreshProviders, { environmentId: "studio" }); + void runAtomCommand(registry, refreshProviders, { environmentId: "studio" }); const check = checkEnvironmentUpdates([environment("studio", "0.1.10")], { lookupNpmRelease: async () => AsyncResult.success(null), refreshProviders: (target, run) => runAtomCommand(registry, refreshProviders, target, run), @@ -178,9 +175,41 @@ describe("checkEnvironmentUpdates", () => { subject: "Providers on studio", result: { status: "error", reason: "No answer after 2 seconds." }, }); - await vi.advanceTimersByTimeAsync(3_000); - await interrupted.promise; - expect(isAtomCommandInterrupted(await elsewhere)).toBe(true); + }); + + it("leaves a refresh it started running for a manual refresh that joined it", async () => { + using _timers = { [Symbol.dispose]: () => vi.useRealTimers() }; + vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] }); + const started = Promise.withResolvers(); + const answer = Promise.withResolvers(); + let interrupted = false; + const registry = AtomRegistry.make(); + const refreshProviders = createRuntimeCommand(Atom.runtime(Layer.empty), { + label: "refresh-providers", + concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId }, + execute: (_: { readonly environmentId: string }) => + Effect.sync(() => started.resolve()).pipe( + Effect.andThen(Effect.promise(() => answer.promise)), + Effect.as({ providers: [] }), + Effect.onInterrupt(() => Effect.sync(() => (interrupted = true))), + ), + }); + const check = checkEnvironmentUpdates([environment("studio", "0.1.10")], { + lookupNpmRelease: async () => AsyncResult.success(null), + refreshProviders: (target, run) => runAtomCommand(registry, refreshProviders, target, run), + timeoutMs: 2_000, + }); + await started.promise; + const manual = runAtomCommand(registry, refreshProviders, { environmentId: "studio" }); + await vi.advanceTimersByTimeAsync(2_000); + + expect((await check)[1]).toEqual({ + subject: "Providers on studio", + result: { status: "error", reason: "No answer after 2 seconds." }, + }); + answer.resolve(); + expect(await manual).toMatchObject({ _tag: "Success", value: { providers: [] } }); + expect(interrupted).toBe(false); }); }); From 196c8be1158d9c8f259c206ae916d7427891f289 Mon Sep 17 00:00:00 2001 From: JJ Eaton <58495321+jayleaton@users.noreply.github.com> Date: Sat, 21 Nov 2026 01:37:41 +0700 Subject: [PATCH 6/6] fix(mcp-gateway): a launcher joins the next owner when a stopping owner resets its connection A stopping owner can accept the launcher's reconnect and then reset it while it releases the port. Only ECONNREFUSED was transient, so the launcher exited with ECONNRESET instead of moving the session; this made the owner-handover test fail on CI. Treat a reset during the handshake like a retiring owner. Co-Authored-By: Claude Opus 5.5 --- packages/mcp-gateway/src/sharedGateway.test.ts | 12 ++++++++++++ packages/mcp-gateway/src/sharedTransport.ts | 6 +++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/packages/mcp-gateway/src/sharedGateway.test.ts b/packages/mcp-gateway/src/sharedGateway.test.ts index e1b0ca5cea87..b18684bededf 100644 --- a/packages/mcp-gateway/src/sharedGateway.test.ts +++ b/packages/mcp-gateway/src/sharedGateway.test.ts @@ -650,6 +650,18 @@ describe("shared MCP gateway", () => { await transport.close(); }); + it("joins the next owner when a stopping owner resets the connection", async () => { + const input = await config(); + // A stopping owner can accept a connection and then reset it while it releases the port. + const stopping = NodeNet.createServer((socket) => { + stopping.close(); + socket.resetAndDestroy(); + }); + await new Promise((resolve) => stopping.listen(input.port, "127.0.0.1", resolve)); + const client = await mcp(input); + expect((await client.listTools()).tools.length).toBeGreaterThan(0); + }); + it("moves a running stdio session to the next owner and announces the tool change", async () => { const input = await config(); const entryPoint = diff --git a/packages/mcp-gateway/src/sharedTransport.ts b/packages/mcp-gateway/src/sharedTransport.ts index d142d4a52eab..93d68c17913e 100644 --- a/packages/mcp-gateway/src/sharedTransport.ts +++ b/packages/mcp-gateway/src/sharedTransport.ts @@ -168,11 +168,15 @@ export function connectMcpSession(input: { socket.terminate(); reject(error); }; + // An owner that is stopping can accept a connection and then reset it while it releases the + // port; the launcher treats that like a retiring owner and starts or joins the next one. const onError = (error: NodeJS.ErrnoException) => fail( error.code === "ECONNREFUSED" ? new GatewayUnavailableError("No shared gateway is listening.") - : error, + : error.code === "ECONNRESET" + ? new GatewayRetiringError("The shared gateway owner reset the connection.") + : error, ); const onClose = () => fail(