diff --git a/apps/desktop/src/electron/ElectronUpdater.test.ts b/apps/desktop/src/electron/ElectronUpdater.test.ts index e47c741bf3bd..c8e5dcbec5ee 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,195 @@ 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, (response) => { + callback(response); + response.once("end", () => this.onRead(response)); + }) as unknown as ReturnType; + } +} + +// 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({ + 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).slice(0, 16)).join("")); + return { file: Buffer.concat([content, blockMap, blockMapSize]), blockMapSize: blockMap.length }; +}; + +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 (!stall(start, count)) { + 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, 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")( + "ElectronUpdater stalled download", + () => { + const cancelAndRetry = (differential: boolean) => + Effect.gen(function* () { + 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); + 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), + ); + + 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/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/packages/client-runtime/src/state/server.test.ts b/packages/client-runtime/src/state/server.test.ts index 1778f91ebc76..919d9b3915be 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, @@ -74,6 +75,7 @@ import { } from "./server.ts"; import { runAtomCommand } from "./runtime.ts"; import { applyServerConfigProjection } from "./serverConfigProjection.ts"; +import { createEnvironmentSessionAtoms } from "./session.ts"; const CONFIG = { availableEditors: [], @@ -1856,6 +1858,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 = runAtomCommand(registry, atoms.refreshProviders, { + 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/updateCheck.test.ts b/packages/client-runtime/src/updateCheck.test.ts index 0d6baa3c9915..bb1c9f237635 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,67 @@ describe("checkEnvironmentUpdates", () => { result: { status: "error", reason: "No answer after 2 seconds." }, }, ]); + // Only resolves once the deadline interrupts the request's effect. + await interrupted.promise; + }); + + 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 registry = AtomRegistry.make(); + const refreshProviders = createRuntimeCommand(Atom.runtime(Layer.empty), { + label: "refresh-providers", + concurrency: { mode: "singleFlight", key: ({ environmentId }) => environmentId }, + execute: (_: { readonly environmentId: string }) => Effect.never, + }); + // Started elsewhere, with no deadline of its own. + 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), + 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." }, + }); + }); + + 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); }); }); diff --git a/packages/client-runtime/src/updateCheck.ts b/packages/client-runtime/src/updateCheck.ts index e7767b2752cf..8492108ecc1e 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 AtomCommandOptions, 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: Pick, ) => Promise>; readonly refreshProviders: ( target: Target<{ readonly refreshModels: true }>, + run: Pick, ) => 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: Pick) => 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); 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( 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 74ada590655b..128e0f7d92f7 100644 --- a/patches/electron-updater@6.8.9.patch +++ b/patches/electron-updater@6.8.9.patch @@ -1,5 +1,126 @@ +diff --git a/out/differentialDownloader/DifferentialDownloader.js b/out/differentialDownloader/DifferentialDownloader.js +index c6e948a79d1bb85122b21d8ddd61a5a842ca2e8d..df016d23efad23dc21212912a70ae8066cf8d974 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,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) => { ++ let pause = null; ++ onCancel(() => { ++ clearTimeout(pause); ++ this.abortRequests(); ++ }); + const streams = []; + // Create our download info transformer if we have one + let downloadInfoTransform = undefined; +@@ -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(); + } +- 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")); +@@ -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) { +- 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..436086963c64fbe8bd5126685375dc54e669faf9 100644 +--- a/out/differentialDownloader/multipleRangeDownloader.js ++++ b/out/differentialDownloader/multipleRangeDownloader.js +@@ -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}`; +- const request = differentialDownloader.httpExecutor.createRequest(requestOptions, response => { ++ const request = differentialDownloader.createRequest(requestOptions, response => { + response.on("error", reject); + if (!checkIsRangesSupported(response, reject)) { + return; +@@ -73,7 +79,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..e6fb0b8aafda6ae0797d3127b5aa661b0d202ca5 100644 +index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..b13c07b415f24b5551d7b31aa279c7f12ce26764 100644 --- a/out/electronHttpExecutor.js +++ b/out/electronHttpExecutor.js @@ -3,7 +3,34 @@ Object.defineProperty(exports, "__esModule", { value: true }); @@ -37,7 +158,7 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..e6fb0b8aafda6ae0797d3127b5aa661b function getNetSession() { return require("electron").session.fromPartition(exports.NET_SESSION_NAME, { cache: false, -@@ -16,27 +43,133 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { +@@ -16,27 +43,140 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { this.cachedSession = null; } async download(url, destination, options) { @@ -97,6 +218,7 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..e6fb0b8aafda6ae0797d3127b5aa661b + let fileOut = null; + let upstream = null; + let settled = false; ++ let abortRequest = null; + const callback = error => { + if (settled) { + return; @@ -115,9 +237,12 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..e6fb0b8aafda6ae0797d3127b5aa661b + fileOut.end(); + } + }; -+ // doDownload never calls onCancel, so a cancel settles here once the file is closed, and a -+ // response that arrives after it is not written. The request runs on until its idle timeout. -+ const cancel = () => callback(new builder_util_runtime_1.CancellationError()); ++ // A cancel aborts the request (builder-util-runtime's patched doDownload hands it over) and ++ // settles here once the file is closed; a response that arrives after it is not written. ++ const cancel = () => { ++ abortRequest?.(); ++ callback(new builder_util_runtime_1.CancellationError()); ++ }; + cancellationToken.onCancel(cancel); + if (settled) { + return; @@ -127,6 +252,9 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..e6fb0b8aafda6ae0797d3127b5aa661b + destination, + options, + callback, ++ onCancel: abort => { ++ abortRequest = abort; ++ }, + responseHandler: response => { + if (settled) { + return; @@ -187,7 +315,7 @@ index 0ae9e1126e1dc136977914ef1bfd46709fc9db1b..e6fb0b8aafda6ae0797d3127b5aa661b }); } createRequest(options, callback) { -@@ -61,6 +194,35 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { +@@ -61,6 +201,35 @@ class ElectronHttpExecutor extends builder_util_runtime_1.HttpExecutor { } return request; } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7edea0303341..70b305068ce7 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 @@ -348,8 +349,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: 91b5648a7eed42761523ef542ebb7e548b037eda41d66533c8152ac65ac72155 + electron-updater@6.8.9: 2dbffd56e3ae3ce69cf31c1a8d1962066459dcca851c85c53ae70133e0fee198 expo-audio@58.0.11: 93691f7f59edb30a3bb2c23b489e605e7ea35506b1212d4a2ebbd1fd79079483 expo-modules-core@58.0.30: f0b0fd100550ed76e5c25b4d13eb7c9ff62825f8f197c53edf7bf447c50c9fb7 expo-network@58.0.4: 159c2d760d1cd5102e95df51c20600111e7a72096ef0daea8215d50cae48bd98 @@ -436,7 +438,7 @@ importers: version: 44.10.1(supports-color@8.1.1) electron-updater: specifier: 6.8.9 - version: 6.8.9(patch_hash=91b5648a7eed42761523ef542ebb7e548b037eda41d66533c8152ac65ac72155)(supports-color@8.1.1) + version: 6.8.9(patch_hash=2dbffd56e3ae3ce69cf31c1a8d1962066459dcca851c85c53ae70133e0fee198)(supports-color@8.1.1) electron-webauthn: specifier: 'catalog:' version: 1.3.1(typescript@6.0.3) @@ -17261,7 +17263,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) @@ -17630,7 +17632,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 @@ -17640,7 +17642,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) @@ -18169,7 +18171,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) @@ -18186,7 +18188,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 @@ -18197,9 +18199,9 @@ snapshots: electron-to-chromium@1.5.430: {} - electron-updater@6.8.9(patch_hash=91b5648a7eed42761523ef542ebb7e548b037eda41d66533c8152ac65ac72155)(supports-color@8.1.1): + electron-updater@6.8.9(patch_hash=2dbffd56e3ae3ce69cf31c1a8d1962066459dcca851c85c53ae70133e0fee198)(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 7c2dc8477f98..a3a9f3fcaacf 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" @@ -239,8 +240,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, expose agent.resume() (the protocol's ResumeAction), and offer # background shells to the host so they can outlive the run.