sailfork / t3code-github / apps/ desktop/ src/ updates/ DesktopRemoteUpdates.test.ts

import { assert, describe, it } from "@effect/vitest";
import type {
  DesktopTelemetryRequestDesktopUpdate,
  DesktopTelemetryCommitDesktopUpdate,
  DesktopTelemetryCancelDesktopUpdate,
  DesktopUpdateStatusReport,
} from "@t3tools/contracts";
import * as Deferred from "effect/Deferred";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Fiber from "effect/Fiber";
import * as Layer from "effect/Layer";
import * as Queue from "effect/Queue";
import * as Ref from "effect/Ref";
import * as Stream from "effect/Stream";
import * as TestClock from "effect/testing/TestClock";

import * as ElectronUpdater from "../electron/ElectronUpdater.ts";
import * as DesktopState from "../app/DesktopState.ts";
import * as DesktopTelemetryPublisher from "../telemetry/DesktopTelemetryPublisher.ts";
import * as DesktopRemoteUpdates from "./DesktopRemoteUpdates.ts";
import * as DesktopUpdates from "./DesktopUpdates.ts";
import { makeHarness } from "./updatesTestHarness.ts";

// Updater runPromise handlers need real microtasks between test-runtime fiber yields.
const settle = Effect.gen(function* () {
  for (let i = 0; i < 20; i += 1) {
    yield* Effect.yieldNow;
    yield* Effect.promise(() => Promise.resolve());
  }
});

const request = (requestId: string): DesktopTelemetryRequestDesktopUpdate => ({
  version: 1,
  type: "requestDesktopUpdate",
  requestId,
});

function runRemoteUpdatesTest(
  harness: ReturnType<typeof makeHarness>,
  body: (context: {
    readonly reports: DesktopUpdateStatusReport[];
    readonly requests: Queue.Queue<DesktopTelemetryRequestDesktopUpdate>;
    readonly commits: Queue.Queue<DesktopTelemetryCommitDesktopUpdate>;
    readonly cancellations: Queue.Queue<DesktopTelemetryCancelDesktopUpdate>;
  }) => Effect.Effect<void, never, DesktopUpdates.DesktopUpdates | DesktopState.DesktopState>,
) {
  return Effect.scoped(
    Effect.gen(function* () {
      const requests = yield* Queue.unbounded<DesktopTelemetryRequestDesktopUpdate>();
      const commits = yield* Queue.unbounded<DesktopTelemetryCommitDesktopUpdate>();
      const cancellations = yield* Queue.unbounded<DesktopTelemetryCancelDesktopUpdate>();
      const reports: DesktopUpdateStatusReport[] = [];
      const publisher = DesktopTelemetryPublisher.DesktopTelemetryPublisher.of({
        latest: Effect.succeedNone,
        changes: Stream.empty,
        encoded: Stream.empty,
        handleControlForSource: () => Effect.void,
        removeControlSource: () => Effect.void,
        publishUpdateReport: (report) =>
          Effect.sync(() => {
            reports.push(report);
          }),
        updateRequests: Stream.fromQueue(requests),
        updateCommits: Stream.fromQueue(commits),
        updateCancellations: Stream.fromQueue(cancellations),
      });

      const updates = yield* DesktopUpdates.DesktopUpdates;
      yield* updates.configure;
      yield* DesktopRemoteUpdates.listen.pipe(
        Effect.provideService(DesktopTelemetryPublisher.DesktopTelemetryPublisher, publisher),
      );
      yield* settle;
      yield* body({ reports, requests, commits, cancellations });
    }),
  ).pipe(Effect.provide(Layer.merge(TestClock.layer(), harness.layer)));
}

function terminalReports(reports: DesktopUpdateStatusReport[]): DesktopUpdateStatusReport[] {
  return reports.filter((report) => report.outcome !== undefined);
}

describe("DesktopRemoteUpdates", () => {
  it.effect("drives check, download, and install with no local confirmation", () => {
    const harness = makeHarness();

    return runRemoteUpdatesTest(harness, ({ reports, requests, commits }) =>
      Effect.gen(function* () {
        yield* Queue.offer(requests, request("req-1"));
        yield* settle;
        assert.equal(harness.checkCount(), 1);

        harness.emit("update-available", { version: "1.2.4" });
        yield* settle;
        harness.emit("update-downloaded", { version: "1.2.4" });
        yield* settle;

        const terminals = terminalReports(reports);
        assert.equal(terminals.length, 1);
        assert.equal(terminals[0]?.outcome, "ready-to-install");
        assert.equal(terminals[0]?.requestId, "req-1");
        assert.equal(harness.quitAndInstalls(), 0);

        yield* Queue.offer(commits, {
          version: 1,
          type: "commitDesktopUpdate",
          requestId: "req-1",
        });
        yield* settle;
        assert.equal(harness.quitAndInstalls(), 1);

        const statuses = reports
          .filter((report) => report.requestId === "req-1")
          .map((report) => report.state.status);
        assert.include(statuses, "available");
        assert.include(statuses, "downloaded");
      }),
    );
  });

  it.effect("switches to the requested track before preparing its release", () => {
    // In-memory settings keep the channel write off real disk I/O.
    const harness = makeHarness({ beforeSetUpdateChannel: Effect.void });

    return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
      Effect.gen(function* () {
        const updates = yield* DesktopUpdates.DesktopUpdates;
        yield* Queue.offer(requests, {
          ...request("req-switch"),
          channel: "nightly",
          targetVersion: "1.2.4-nightly.20261027.1",
        });
        yield* settle;
        assert.equal((yield* updates.getState).channel, "nightly");

        harness.emit("update-available", { version: "1.2.4-nightly.20261027.1" });
        yield* settle;
        harness.emit("update-downloaded", { version: "1.2.4-nightly.20261027.1" });
        yield* settle;

        const terminals = terminalReports(reports);
        assert.deepEqual(
          terminals.map((report) => [report.requestId, report.outcome]),
          [["req-switch", "ready-to-install"]],
        );
        assert.equal(terminals[0]?.state.downloadedVersion, "1.2.4-nightly.20261027.1");
      }),
    );
  });

  it.effect(
    "refuses a crossing whose feed has only an older build, and never offers it later",
    () => {
      const harness = makeHarness({ beforeSetUpdateChannel: Effect.void });

      return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
        Effect.gen(function* () {
          const updates = yield* DesktopUpdates.DesktopUpdates;
          const older = "1.2.4-nightly.20261020.1";
          yield* Queue.offer(requests, {
            ...request("req-older"),
            channel: "nightly",
            targetVersion: "1.2.4-nightly.20261027.1",
          });
          yield* settle;
          // Answers the track change's check, then the request's own check.
          harness.emit("update-available", { version: older });
          yield* settle;
          harness.emit("update-available", { version: older });
          yield* settle;

          assert.deepEqual(
            terminalReports(reports).map((report) => [report.outcome, report.reason]),
            [["failed", "The desktop app found no build of 1.2.4-nightly.20261027.1."]],
          );
          // The saved track is the user's intent; a retry picks it up from here.
          assert.equal((yield* updates.getState).channel, "nightly");

          // A plain update afterwards cannot reach the build the switch refused.
          yield* Queue.offer(requests, request("req-plain"));
          yield* settle;
          harness.emit("update-available", { version: older });
          yield* settle;
          assert.isNull((yield* updates.getState).availableVersion);
          assert.equal(harness.downloadCount(), 0);
        }),
      );
    },
  );

  it.effect("only saves the track on a host already running the release", () => {
    const harness = makeHarness({ savedChannel: "nightly" });

    return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
      Effect.gen(function* () {
        const updates = yield* DesktopUpdates.DesktopUpdates;
        yield* Queue.offer(requests, {
          ...request("req-track-only"),
          channel: "latest",
          targetVersion: "1.2.3",
        });
        yield* settle;
        // Even with a newer build on the feed, the host only saves its track.
        harness.emit("update-available", { version: "1.2.4" });
        yield* settle;

        assert.deepEqual(
          terminalReports(reports).map((report) => report.outcome),
          ["up-to-date"],
        );
        assert.equal((yield* updates.getState).channel, "latest");
        assert.equal(harness.downloadCount(), 0);
      }),
    );
  });

  it.effect("drops a retained download below the switch's checked release", () => {
    const harness = makeHarness({ beforeSetUpdateChannel: Effect.void });

    return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
      Effect.gen(function* () {
        const updates = yield* DesktopUpdates.DesktopUpdates;
        // Downloaded earlier on this Stable host, before the switch checked 1.2.5.
        harness.emit("update-downloaded", { version: "1.2.4" });
        yield* settle;
        assert.equal((yield* updates.getState).downloadedVersion, "1.2.4");

        yield* Queue.offer(requests, {
          ...request("req-floor"),
          channel: "latest",
          targetVersion: "1.2.5",
        });
        yield* settle;
        harness.emit("update-available", { version: "1.2.5" });
        yield* settle;
        harness.emit("update-downloaded", { version: "1.2.5" });
        yield* settle;

        assert.deepEqual(
          terminalReports(reports).map((report) => [
            report.outcome,
            report.state.downloadedVersion,
          ]),
          [["ready-to-install", "1.2.5"]],
        );
      }),
    );
  });

  it.effect("refuses to cross tracks remotely while WSL backends need their own checks", () => {
    const harness = makeHarness({ beforeSetUpdateChannel: Effect.void, wslBackend: true });

    return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
      Effect.gen(function* () {
        const updates = yield* DesktopUpdates.DesktopUpdates;
        yield* Queue.offer(requests, {
          ...request("req-wsl"),
          channel: "nightly",
          targetVersion: "1.2.4-nightly.20261027.1",
        });
        yield* settle;

        assert.deepEqual(
          terminalReports(reports).map((report) => report.outcome),
          ["failed"],
        );
        assert.include(terminalReports(reports)[0]?.reason ?? "", "Switch it on that machine");
        assert.equal((yield* updates.getState).channel, "latest");
      }),
    );
  });

  it.effect("fails a switch that leaves a same-track host below the checked release", () => {
    const harness = makeHarness({ beforeSetUpdateChannel: Effect.void });

    return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
      Effect.gen(function* () {
        yield* Queue.offer(requests, {
          ...request("req-behind"),
          channel: "latest",
          targetVersion: "1.2.5",
        });
        yield* settle;
        // The feed lags npm and has nothing newer than this host's 1.2.3.
        harness.emit("update-not-available");
        yield* settle;
        harness.emit("update-not-available");
        yield* settle;

        assert.deepEqual(
          terminalReports(reports).map((report) => [report.outcome, report.reason]),
          [["failed", "The desktop app found no build of 1.2.5."]],
        );
      }),
    );
  });

  it.effect("fails a crossing to an older-numbered Stable that the feed does not offer", () => {
    const harness = makeHarness({
      appVersion: "1.2.4-nightly.20261027.1",
      beforeSetUpdateChannel: Effect.void,
    });

    return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
      Effect.gen(function* () {
        yield* Queue.offer(requests, {
          ...request("req-to-stable"),
          channel: "latest",
          targetVersion: "1.2.3",
        });
        yield* settle;
        harness.emit("update-not-available");
        yield* settle;
        harness.emit("update-not-available");
        yield* settle;

        // Still on Nightly, though the target is numbered below this build.
        assert.deepEqual(
          terminalReports(reports).map((report) => [report.outcome, report.reason]),
          [["failed", "The desktop app found no build of 1.2.3."]],
        );
      }),
    );
  });

  it.effect("accepts a newer build than the checked release on the requested track", () => {
    const harness = makeHarness({ beforeSetUpdateChannel: Effect.void });

    return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
      Effect.gen(function* () {
        const newer = "1.2.4-nightly.20261028.2";
        yield* Queue.offer(requests, {
          ...request("req-newer"),
          channel: "nightly",
          targetVersion: "1.2.4-nightly.20261027.1",
        });
        yield* settle;
        harness.emit("update-available", { version: newer });
        yield* settle;
        harness.emit("update-downloaded", { version: newer });
        yield* settle;

        assert.deepEqual(
          terminalReports(reports).map((report) => [
            report.outcome,
            report.state.downloadedVersion,
          ]),
          [["ready-to-install", newer]],
        );
      }),
    );
  });

  it.effect("reports a failed outcome when quitAndInstall fails", () => {
    const harness = makeHarness({
      quitAndInstall: Effect.fail(
        new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
          channel: "latest",
          isSilent: true,
          isForceRunAfter: true,
          cause: new Error("spawn failed"),
        }),
      ),
    });

    return runRemoteUpdatesTest(harness, ({ reports, requests, commits }) =>
      Effect.gen(function* () {
        yield* Queue.offer(requests, request("req-4"));
        yield* settle;
        harness.emit("update-available", { version: "1.2.4" });
        yield* settle;
        harness.emit("update-downloaded", { version: "1.2.4" });
        yield* settle;

        yield* Queue.offer(commits, {
          version: 1,
          type: "commitDesktopUpdate",
          requestId: "req-4",
        });
        yield* settle;

        const terminals = terminalReports(reports);
        assert.deepEqual(
          terminals.map((report) => report.outcome),
          ["ready-to-install", "failed"],
        );
        assert.equal(terminals[1]?.state.errorContext, "install");
      }),
    );
  });

  it.effect("joins an in-progress install on commit instead of failing the token", () => {
    const installStarted = Deferred.makeUnsafe<void>();
    const releaseInstall = Deferred.makeUnsafe<void>();
    const harness = makeHarness({
      stopBackend: Deferred.succeed(installStarted, undefined).pipe(
        Effect.andThen(Deferred.await(releaseInstall)),
      ),
    });

    return runRemoteUpdatesTest(harness, ({ reports, requests, commits }) =>
      Effect.gen(function* () {
        const updates = yield* DesktopUpdates.DesktopUpdates;
        yield* Queue.offer(requests, request("req-join-commit"));
        yield* settle;
        harness.emit("update-available", { version: "1.2.4" });
        yield* settle;
        harness.emit("update-downloaded", { version: "1.2.4" });
        yield* settle;
        assert.deepEqual(
          terminalReports(reports).map((report) => report.outcome),
          ["ready-to-install"],
        );

        const localInstall = yield* updates.install.pipe(Effect.forkChild);
        yield* Deferred.await(installStarted);
        yield* Queue.offer(commits, {
          version: 1,
          type: "commitDesktopUpdate",
          requestId: "req-join-commit",
        });
        yield* settle;

        assert.deepEqual(
          terminalReports(reports).map((report) => report.outcome),
          ["ready-to-install"],
        );
        assert.equal(harness.quitAndInstalls(), 0);

        yield* Deferred.succeed(releaseInstall, undefined);
        yield* Fiber.join(localInstall);
      }),
    );
  });

  it.effect("does not join a normal app quit as an update install", () => {
    const harness = makeHarness();

    return runRemoteUpdatesTest(harness, ({ reports, requests, commits }) =>
      Effect.gen(function* () {
        const desktopState = yield* DesktopState.DesktopState;
        yield* Queue.offer(requests, request("req-normal-quit"));
        yield* settle;
        harness.emit("update-available", { version: "1.2.4" });
        yield* settle;
        harness.emit("update-downloaded", { version: "1.2.4" });
        yield* settle;

        yield* Ref.set(desktopState.quitting, true);
        yield* Queue.offer(commits, {
          version: 1,
          type: "commitDesktopUpdate",
          requestId: "req-normal-quit",
        });
        yield* settle;

        assert.deepEqual(
          terminalReports(reports).map((report) => report.outcome),
          ["ready-to-install", "failed"],
        );
        assert.equal(harness.quitAndInstalls(), 0);
      }),
    );
  });

  it.effect("does not misread a lingering install error as a failed retry", () => {
    let installAttempts = 0;
    const harness = makeHarness({
      quitAndInstall: Effect.suspend(() => {
        installAttempts += 1;
        return installAttempts === 1
          ? Effect.fail(
              new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
                channel: "latest",
                isSilent: true,
                isForceRunAfter: true,
                cause: new Error("first attempt failed"),
              }),
            )
          : Effect.void;
      }),
    });

    return runRemoteUpdatesTest(harness, ({ reports, requests, commits }) =>
      Effect.gen(function* () {
        yield* Queue.offer(requests, request("req-5"));
        yield* settle;
        harness.emit("update-available", { version: "1.2.4" });
        yield* settle;
        harness.emit("update-downloaded", { version: "1.2.4" });
        yield* settle;
        yield* Queue.offer(commits, {
          version: 1,
          type: "commitDesktopUpdate",
          requestId: "req-5",
        });
        yield* settle;
        yield* Queue.offer(requests, request("req-6"));
        yield* settle;
        yield* Queue.offer(commits, {
          version: 1,
          type: "commitDesktopUpdate",
          requestId: "req-6",
        });
        yield* settle;

        const retryTerminals = terminalReports(reports).filter(
          (report) => report.requestId === "req-6",
        );
        assert.deepEqual(
          retryTerminals.map((report) => report.outcome),
          ["ready-to-install"],
        );
        assert.equal(harness.quitAndInstalls(), 2);
      }),
    );
  });

  it.effect("ignores an unrelated updater event while an install is starting", () => {
    const stopStarted = Deferred.makeUnsafe<void>();
    const releaseStop = Deferred.makeUnsafe<void>();
    const harness = makeHarness({
      stopBackend: Deferred.succeed(stopStarted, undefined).pipe(
        Effect.andThen(Deferred.await(releaseStop)),
      ),
    });

    return runRemoteUpdatesTest(harness, ({ reports, requests, commits }) =>
      Effect.gen(function* () {
        yield* Queue.offer(requests, request("req-late-event"));
        yield* settle;
        harness.emit("update-available", { version: "1.2.4" });
        yield* settle;
        harness.emit("update-downloaded", { version: "1.2.4" });
        yield* settle;

        yield* Queue.offer(commits, {
          version: 1,
          type: "commitDesktopUpdate",
          requestId: "req-late-event",
        });
        yield* Deferred.await(stopStarted);
        harness.emit("download-progress", { percent: 90 });
        yield* settle;
        yield* Deferred.succeed(releaseStop, undefined);
        yield* settle;

        assert.deepEqual(
          terminalReports(reports)
            .filter((report) => report.requestId === "req-late-event")
            .map((report) => report.outcome),
          ["ready-to-install"],
        );
      }),
    );
  });

  it.effect("retries a download refused while the check still holds the reservation", () => {
    const releaseCheck = Deferred.makeUnsafe<void>();
    const harness = makeHarness({ checkForUpdates: Deferred.await(releaseCheck) });

    return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
      Effect.gen(function* () {
        yield* Queue.offer(requests, request("req-8"));
        yield* settle;
        assert.equal(harness.checkCount(), 1);

        harness.emit("update-available", { version: "1.2.4" });
        yield* settle;
        assert.equal(harness.downloadCount(), 0);

        yield* Deferred.succeed(releaseCheck, undefined);
        yield* settle;
        yield* TestClock.adjust(Duration.millis(300));
        yield* settle;
        assert.equal(harness.downloadCount(), 1);

        harness.emit("update-downloaded", { version: "1.2.4" });
        yield* settle;
        assert.deepEqual(
          terminalReports(reports).map((report) => report.outcome),
          ["ready-to-install"],
        );
        assert.equal(harness.quitAndInstalls(), 0);
      }),
    );
  });

  it.effect("waits for the download reservation before reporting prepared", () => {
    const releaseDownload = Deferred.makeUnsafe<void>();
    const harness = makeHarness({ downloadUpdate: Deferred.await(releaseDownload) });

    return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
      Effect.gen(function* () {
        yield* Queue.offer(requests, request("req-10"));
        yield* settle;
        harness.emit("update-available", { version: "1.2.4" });
        yield* settle;
        harness.emit("update-downloaded", { version: "1.2.4" });
        yield* settle;
        assert.deepEqual(terminalReports(reports), []);
        assert.equal(harness.quitAndInstalls(), 0);

        yield* Deferred.succeed(releaseDownload, undefined);
        yield* settle;
        yield* TestClock.adjust(Duration.millis(300));
        yield* settle;
        assert.deepEqual(
          terminalReports(reports).map((report) => report.outcome),
          ["ready-to-install"],
        );
        assert.equal(harness.quitAndInstalls(), 0);
      }),
    );
  });

  it.effect("joins an install that is already tearing the app down", () => {
    const harness = makeHarness();

    return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
      Effect.gen(function* () {
        const desktopState = yield* DesktopState.DesktopState;
        harness.emit("update-downloaded", { version: "1.2.4" });
        yield* settle;
        yield* Ref.set(desktopState.quitting, true);

        yield* Queue.offer(requests, request("req-9"));
        yield* settle;

        assert.deepEqual(
          terminalReports(reports).map((report) => report.outcome),
          ["ready-to-install"],
        );
        assert.equal(harness.quitAndInstalls(), 0);
      }),
    );
  });

  it.effect("does not run the installer twice for a repeated commit", () => {
    const harness = makeHarness();

    return runRemoteUpdatesTest(harness, ({ requests, commits }) =>
      Effect.gen(function* () {
        yield* Queue.offer(requests, request("req-repeat"));
        yield* settle;
        harness.emit("update-available", { version: "1.2.4" });
        yield* settle;
        harness.emit("update-downloaded", { version: "1.2.4" });
        yield* settle;

        const commit = {
          version: 1,
          type: "commitDesktopUpdate",
          requestId: "req-repeat",
        } as const;
        yield* Queue.offer(commits, commit);
        yield* settle;
        yield* Queue.offer(commits, commit);
        yield* settle;

        assert.equal(harness.quitAndInstalls(), 1);
      }),
    );
  });

  it.effect("waits for a background check before installing a prepared update", () => {
    const backgroundCheckStarted = Deferred.makeUnsafe<void>();
    const releaseBackgroundCheck = Deferred.makeUnsafe<void>();
    let checks = 0;
    const harness = makeHarness({
      checkForUpdates: Effect.suspend(() => {
        checks += 1;
        return checks === 2
          ? Deferred.succeed(backgroundCheckStarted, undefined).pipe(
              Effect.andThen(Deferred.await(releaseBackgroundCheck)),
            )
          : Effect.void;
      }),
    });

    return runRemoteUpdatesTest(harness, ({ requests, commits }) =>
      Effect.gen(function* () {
        const updates = yield* DesktopUpdates.DesktopUpdates;
        yield* Queue.offer(requests, request("req-background-check"));
        yield* settle;
        harness.emit("update-available", { version: "1.2.4" });
        yield* settle;
        harness.emit("update-downloaded", { version: "1.2.4" });
        yield* settle;

        const backgroundCheck = yield* updates.check("poll").pipe(Effect.forkChild);
        yield* Deferred.await(backgroundCheckStarted);
        assert.equal((yield* updates.getState).status, "checking");

        yield* Queue.offer(commits, {
          version: 1,
          type: "commitDesktopUpdate",
          requestId: "req-background-check",
        });
        yield* settle;
        assert.equal(harness.quitAndInstalls(), 0);

        harness.emit("update-downloaded", { version: "1.2.4" });
        yield* Deferred.succeed(releaseBackgroundCheck, undefined);
        yield* Fiber.join(backgroundCheck);
        yield* settle;
        assert.equal(harness.quitAndInstalls(), 1);
      }),
    );
  });

  it.effect("rejects a new preparation while an install commit is active", () => {
    const installStarted = Deferred.makeUnsafe<void>();
    const releaseInstall = Deferred.makeUnsafe<void>();
    const harness = makeHarness({
      quitAndInstall: Deferred.succeed(installStarted, undefined).pipe(
        Effect.andThen(Deferred.await(releaseInstall)),
        Effect.andThen(
          Effect.fail(
            new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
              channel: "latest",
              isSilent: true,
              isForceRunAfter: true,
              cause: new Error("installer refused"),
            }),
          ),
        ),
      ),
    });

    return runRemoteUpdatesTest(harness, ({ reports, requests, commits }) =>
      Effect.gen(function* () {
        yield* Queue.offer(requests, request("req-active"));
        yield* settle;
        harness.emit("update-available", { version: "1.2.4" });
        yield* settle;
        harness.emit("update-downloaded", { version: "1.2.4" });
        yield* settle;
        yield* Queue.offer(commits, {
          version: 1,
          type: "commitDesktopUpdate",
          requestId: "req-active",
        });
        yield* Deferred.await(installStarted);

        yield* Queue.offer(requests, request("req-overlap"));
        yield* settle;
        const overlap = terminalReports(reports).find(
          (report) => report.requestId === "req-overlap",
        );
        assert.equal(overlap?.outcome, "failed");
        assert.equal(overlap?.reason, "A prepared desktop update is already in progress.");

        yield* Deferred.succeed(releaseInstall, undefined);
        yield* settle;
      }),
    );
  });

  it.effect("cancels a track switch while its own feed check is still running", () => {
    const releaseCheck = Deferred.makeUnsafe<void>();
    const harness = makeHarness({
      beforeSetUpdateChannel: Effect.void,
      checkForUpdates: Deferred.await(releaseCheck),
    });

    return runRemoteUpdatesTest(harness, ({ requests, cancellations }) =>
      Effect.gen(function* () {
        yield* Queue.offer(requests, {
          ...request("req-switch-cancel"),
          channel: "nightly",
          targetVersion: "1.2.4-nightly.20261027.1",
        });
        yield* settle;
        const updates = yield* DesktopUpdates.DesktopUpdates;
        yield* Queue.offer(cancellations, {
          version: 1,
          type: "cancelDesktopUpdate",
          requestId: "req-switch-cancel",
        });
        yield* settle;
        // The next request starts without waiting for the cancelled switch's feed check.
        yield* Queue.offer(requests, {
          ...request("req-switch-back"),
          channel: "latest",
          targetVersion: "1.2.3",
        });
        yield* settle;

        assert.equal((yield* updates.getState).channel, "latest");
        yield* Deferred.succeed(releaseCheck, undefined);
      }),
    );
  });

  it.effect("cancels an active preparation so the next request can run", () => {
    const releaseCheck = Deferred.makeUnsafe<void>();
    const harness = makeHarness({ checkForUpdates: Deferred.await(releaseCheck) });

    return runRemoteUpdatesTest(harness, ({ requests, cancellations }) =>
      Effect.gen(function* () {
        yield* Queue.offer(requests, request("req-cancel"));
        yield* settle;
        yield* Queue.offer(cancellations, {
          version: 1,
          type: "cancelDesktopUpdate",
          requestId: "req-cancel",
        });
        yield* settle;
        yield* Deferred.succeed(releaseCheck, undefined);
        yield* Queue.offer(requests, request("req-next"));
        yield* settle;

        assert.equal(harness.checkCount(), 2);
      }),
    );
  });

  it.effect("remembers a cancellation that arrives before its request starts", () => {
    const harness = makeHarness();

    return runRemoteUpdatesTest(harness, ({ requests, cancellations }) =>
      Effect.gen(function* () {
        yield* Queue.offer(cancellations, {
          version: 1,
          type: "cancelDesktopUpdate",
          requestId: "req-early-cancel",
        });
        yield* Queue.offer(requests, request("req-early-cancel"));
        yield* settle;

        assert.equal(harness.checkCount(), 0);

        yield* Queue.offer(requests, request("req-after-early-cancel"));
        yield* settle;
        assert.equal(harness.checkCount(), 1);
      }),
    );
  });

  it.effect("does not install after cancellation wins the commit claim", () => {
    const harness = makeHarness();

    return runRemoteUpdatesTest(harness, ({ reports, requests, commits, cancellations }) =>
      Effect.gen(function* () {
        yield* Queue.offer(requests, request("req-cancel-before-commit"));
        yield* settle;
        harness.emit("update-available", { version: "1.2.4" });
        yield* settle;
        harness.emit("update-downloaded", { version: "1.2.4" });
        yield* settle;

        yield* Queue.offer(cancellations, {
          version: 1,
          type: "cancelDesktopUpdate",
          requestId: "req-cancel-before-commit",
        });
        yield* settle;
        yield* Queue.offer(commits, {
          version: 1,
          type: "commitDesktopUpdate",
          requestId: "req-cancel-before-commit",
        });
        yield* settle;

        assert.equal(harness.quitAndInstalls(), 0);
        assert.deepEqual(
          terminalReports(reports)
            .filter((report) => report.requestId === "req-cancel-before-commit")
            .map((report) => report.outcome),
          ["ready-to-install", "failed"],
        );
      }),
    );
  });

  it.effect("retains an install failure after cancellation loses the commit claim", () => {
    const installStarted = Deferred.makeUnsafe<void>();
    const releaseInstall = Deferred.makeUnsafe<void>();
    const harness = makeHarness({
      quitAndInstall: Deferred.succeed(installStarted, undefined).pipe(
        Effect.andThen(Deferred.await(releaseInstall)),
        Effect.andThen(
          Effect.fail(
            new ElectronUpdater.ElectronUpdaterQuitAndInstallError({
              channel: "latest",
              isSilent: true,
              isForceRunAfter: true,
              cause: new Error("installer refused"),
            }),
          ),
        ),
      ),
    });

    return runRemoteUpdatesTest(harness, ({ reports, requests, commits, cancellations }) =>
      Effect.gen(function* () {
        yield* Queue.offer(requests, request("req-cancel-after-commit"));
        yield* settle;
        harness.emit("update-available", { version: "1.2.4" });
        yield* settle;
        harness.emit("update-downloaded", { version: "1.2.4" });
        yield* settle;
        const commit = {
          version: 1,
          type: "commitDesktopUpdate",
          requestId: "req-cancel-after-commit",
        } as const;
        yield* Queue.offer(commits, commit);
        yield* Deferred.await(installStarted);
        yield* Queue.offer(cancellations, {
          version: 1,
          type: "cancelDesktopUpdate",
          requestId: "req-cancel-after-commit",
        });
        yield* settle;
        yield* Deferred.succeed(releaseInstall, undefined);
        yield* settle;
        yield* Queue.offer(commits, commit);
        yield* settle;

        assert.deepEqual(
          terminalReports(reports)
            .filter((report) => report.requestId === "req-cancel-after-commit")
            .map((report) => report.outcome),
          ["ready-to-install", "failed", "failed"],
        );
      }),
    );
  });

  it.effect("reports up-to-date without installing when there is no update", () => {
    const harness = makeHarness();

    return runRemoteUpdatesTest(harness, ({ reports, requests }) =>
      Effect.gen(function* () {
        yield* Queue.offer(requests, request("req-2"));
        yield* settle;
        harness.emit("update-not-available");
        yield* settle;

        const terminals = terminalReports(reports);
        assert.equal(terminals.length, 1);
        assert.equal(terminals[0]?.outcome, "up-to-date");
        assert.equal(terminals[0]?.requestId, "req-2");
        assert.equal(harness.quitAndInstalls(), 0);
      }),
    );
  });
});