Compare commits

..
Author SHA1 Message Date
paseo-bot[bot] b3e7ff2183 fix(acp): start the optional scan budget with the listing 2026-11-26 03:44:09 +00:00
paseo-bot[bot] 29c2b57653 test(server): wait for the watcher before deleting a file
The native macOS watcher starts delivering events after subscription returns. Use the existing liveness canary before removing the file under test.
2026-11-26 03:43:46 +00:00
paseo-bot[bot] 51c230752d test(website): check plugin search parameters by name
Native GET form submission and hydrated navigation serialize the same filters in different orders. Verify the term and ranking window in both flows.
2026-11-26 03:43:46 +00:00
paseo-bot[bot] 4d02cc2a58 fix(acp): keep import results when extra pages stall
Once the provider supplies enough sessions, bound the time spent looking for newer ones. Return the rows already collected and close the listing connection when the extra scan ends.
2026-11-26 03:43:46 +00:00
paseo-bot[bot] 64de264e3f fix(acp): show the latest sessions in Import Session
ACP peers can return sessions in storage order. Applying the result limit before sorting discards newer sessions before the daemon receives them.
2026-11-26 03:43:46 +00:00
31 changed files with 704 additions and 2253 deletions
+3 -3
View File
@@ -38,9 +38,9 @@ on:
- "true"
- "false"
rollout_hours:
description: "Rollout duration in hours: a 5% canary hold, then a ramp to 100%. Use 0 to admit everyone at once."
description: "Linear rollout duration in hours. Use 0 for instant rollout."
required: false
default: "18"
default: "36"
type: string
concurrency:
@@ -51,7 +51,7 @@ env:
SOURCE_TAG: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.tag || github.ref_name }}
CHECKOUT_REF: ${{ github.event_name == 'workflow_dispatch' && (github.event.inputs.checkout_ref || github.ref_name) || github.ref_name }}
SHOULD_PUBLISH: ${{ github.event_name != 'workflow_dispatch' || github.event.inputs.publish != 'false' }}
ROLLOUT_HOURS: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.rollout_hours || '18' }}
ROLLOUT_HOURS: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.rollout_hours || '36' }}
DESKTOP_PACKAGE_PATH: "packages/desktop"
jobs:
+31 -93
View File
@@ -48,7 +48,7 @@ the shipped source.
The user decides when the changes on `main` warrant a release and how much risk it takes:
1. **Direct stable release** for a low-risk batch of polish and bug fixes. Stable desktop updates
start with a 5% canary and ramp over 18 hours (see [Staged rollout](#staged-rollout-stable-channel)), and store
already ramp over 36 hours (see [Staged rollout](#staged-rollout-stable-channel)), and store
review often takes about a day, with no guaranteed timing.
2. **Beta flow**, the default for changes that need testing. Release candidates on the `beta`
channel. Each beta folds into the series' single changelog entry, publishes npm only on the
@@ -324,33 +324,11 @@ Use the beta path when you need to:
## Staged rollout (stable channel)
A stable desktop release reaches automatic updates in stages, so a bad release reaches few installs before you stop it. Each install decides locally from two fields in the release manifests, `releaseDate` and `rolloutHours`. No server tracks installs.
Stable desktop releases go out via a linear time-based rollout for automatic update checks: 0% admitted when the updater manifests appear, 100% admitted 36 hours later, linear ramp in between. Manual checks bypass the rollout so a user can install immediately when they click **Check**. Beta releases bypass the rollout entirely — beta users always receive updates immediately.
| Stage | Rule |
| -------------- | -------------------------------------------------------------------------------------------------------- |
| Canary | For the first 8 hours, 5% of installs are admitted. |
| Ramp | From 8 hours to `rolloutHours` (18 by default), admission rises in a straight line from 5% to 100%. |
| Check interval | An install asks GitHub for the latest release at most once every 6 hours. |
| Cooldown | After an install updates, it skips paced releases for 72 hours. |
| Staged update | An install that holds a downloaded update keeps it and does not download the paced release that follows. |
The rollout is driven by a `rolloutHours` field stamped into the GitHub Release manifests (`latest-mac.yml`, `latest-linux.yml`, `latest.yml`) by the `finalize-rollout` job in `desktop-release.yml`.
A paced release is a stable release with `rolloutHours` above 0. When `rolloutHours` is under 16, the canary hold is half of `rolloutHours`.
Every release places each install at a new position in the rollout, so the canary group changes with each release. With one or two releases per day, an install updates at most once every 72 hours and skips the releases in between.
These paths skip the stages:
- A manual check (**Check**) always asks GitHub and always offers the latest release.
- A release with `rolloutHours: 0` is an emergency release. Every install takes it at its next check, during a cooldown too, and it replaces a staged update.
- The beta channel has no stages. A beta install takes each release at its next check.
The **Notify** update mode follows the same stages and prompts instead of downloading. **Off** makes no automatic requests.
`packages/desktop/src/features/app-update-rollout.ts` owns the curve. `app-update-pacing.ts` owns the check interval and the cooldown, and `app-update-service.ts` owns the staged update.
### How a release is published
The `finalize-rollout` job in `desktop-release.yml` stamps `releaseDate` and `rolloutHours` into the GitHub Release manifests (`latest-mac.yml`, `latest-linux.yml`, `latest.yml`). Desktop release builds publish in two phases:
Desktop release builds now publish in two phases:
- The GitHub Release stays a draft while platform build jobs upload the installers/packages (`.dmg`, `.zip`, `.exe`, `.AppImage`, etc.).
- The final job merges and stamps every channel manifest, uploads them with the final `releaseDate` and `rolloutHours`, then publishes the GitHub Release.
@@ -360,20 +338,20 @@ Drafts do not appear in GitHub's releases feed. Updater clients continue to see
### Default behavior
Follow the [standard stable release procedure](#standard-release-stable). The tag push starts
the desktop release workflow, which sets an 18-hour rollout when it publishes the release.
the desktop release workflow, which sets a 36-hour rollout when it publishes the release.
The `rollout_hours` input on `desktop-release.yml` is read only on `workflow_dispatch`. Tag-push runs always use 18. To get any other rollout duration on a fresh release, use the post-publish flip below.
The `rollout_hours` input on `desktop-release.yml` is **only read on `workflow_dispatch`** — tag-push runs always default to 36. To get any other rollout duration on a fresh release, use the post-publish flip below.
### Emergency release (rollout_hours=0)
### Instant-admit release (rollout_hours=0)
Follow the [standard stable release procedure](#standard-release-stable). Wait for Desktop
Release to publish, then update the manifests to admit everyone at once.
Release to publish, then update the manifests to admit everyone immediately.
```bash
# 1. Wait for Desktop Release to publish the GitHub Release.
gh run watch <desktop-release-run-id> --exit-status
# 2. Flip the published manifests to an emergency release.
# 2. Flip the published manifests to instant admit.
gh workflow run desktop-rollout.yml \
-f tag=v0.1.64 \
-f rollout_hours=0
@@ -381,13 +359,23 @@ gh workflow run desktop-rollout.yml \
Dispatch only after `finalize-rollout` has published the release. Until then the release is a draft, and a draft has no tag: `desktop-rollout.yml` looks the release up by tag and fails with `release not found`. The concurrency group `desktop-rollout-<tag>` that the two workflows share orders them only once both are queued; it does not hold an early dispatch until the draft is published.
The first public manifests carry `rolloutHours=18` for the minutes between publish and the flip. An install sees the flip at its next check, which is up to 6 hours after its previous one. In automatic mode it then downloads the release and installs it when the app quits.
The first public manifests carry `rolloutHours=36` for the minutes between publish and the flip. The renderer polls every 30 minutes, so active stable users pick up the new manifest on their next check.
### Adjusting an already-published release
To change the rollout duration on a release that already shipped, use the `desktop-rollout.yml` workflow. It edits the manifests in place on the GitHub release without rebuilding anything. It rewrites only `rolloutHours`. `releaseDate` is preserved, so the rollout clock keeps running from the original publish time.
To change the rollout duration on a release that's already shipped — e.g. flip a hotfix to instant admit, or slow a release down — use the dedicated `desktop-rollout.yml` workflow. It edits the manifests in place on the GitHub release without rebuilding anything. It only rewrites `rolloutHours`; `releaseDate` is preserved, so the rollout clock keeps ticking from the original publish time.
To slow a rollout down, for example to 72 hours since the original release:
**Hotfix (instant admit) on an already-shipped release:**
```bash
gh workflow run desktop-rollout.yml \
-f tag=v0.1.42 \
-f rollout_hours=0
```
`rollout_hours=0` admits 100% of stable users on their next update check (within ~30 min for active clients).
**Slow a rollout down** (e.g. extend total duration to 72h since the original release):
```bash
gh workflow run desktop-rollout.yml \
@@ -395,59 +383,13 @@ gh workflow run desktop-rollout.yml \
-f rollout_hours=72
```
`rollout_hours` is the total duration since the original release date. If `v0.1.42` was published 2 hours ago and you set `rollout_hours=72`, the ramp finishes 70 hours from now.
A longer rollout does not stop a release. The canary group still updates. To stop a release, [halt it](#halt-a-release).
`rollout_hours` is **total duration since the original release date**, not "extend by N more hours from now." If `v0.1.42` was published 2h ago and you set `rollout_hours=72`, the ramp finishes 70h from now.
The dispatch is idempotent and shares the `desktop-rollout-<tag>` concurrency group with `desktop-release.yml`'s `finalize-rollout` job, so it serializes safely against an in-flight tag-push pipeline targeting the same release.
### Halt a release
Stable installs and the download page follow the release that GitHub marks as latest. To stop a release, mark the last good release as latest:
```bash
# v0.1.41 is the last good release.
gh release edit v0.1.41 --latest
# Prints v0.1.41 when the halt is in effect.
gh api repos/getpaseo/paseo/releases/latest --jq .tag_name
```
The halt applies to every stable install from its next check, including installs older than the staged rollout:
- An install that has not downloaded the halted release no longer sees it.
- An install that downloaded it asks GitHub again before it installs at quit, and drops the download.
- An install that already runs the halted release stays on it, because the app never downgrades. [Ship a fix](#fix-a-bad-release).
A halt does not reach the beta channel. Beta installs read the release list by date and still take the halted release.
To resume a halted release, run `gh release edit v0.1.42 --latest` with its tag.
### Fix a bad release
1. [Halt](#halt-a-release) the bad release.
2. Ship the fix as the next patch with the [standard stable release procedure](#standard-release-stable).
3. After Desktop Release publishes the fix, make sure that GitHub marks it as latest:
```bash
gh api repos/getpaseo/paseo/releases/latest --jq .tag_name
```
If the command prints another tag, run `gh release edit <fix-tag> --latest`.
4. Flip the fix to an [emergency release](#emergency-release-rollout_hours0):
```bash
gh workflow run desktop-rollout.yml \
-f tag=<fix-tag> \
-f rollout_hours=0
```
Do not leave the fix as a paced release. The installs that took the bad release are in their 72-hour cooldown and skip a paced release. An install that holds the bad release as a staged update, and did not check during the halt, keeps it when a paced release follows. An emergency release reaches both.
### Custom ramp on a manually-dispatched build
`desktop-release.yml` accepts `rollout_hours` only on `workflow_dispatch`, which is the path used to rebuild an existing tag (retry a failed release, force a rebuild on a different ref). On that path, you can stamp a different ramp directly:
`desktop-release.yml` accepts `rollout_hours` only on `workflow_dispatch`, which is the path used to **rebuild an existing tag** (retry a failed release, force a rebuild on a different ref). When you go that route, you can stamp a non-default ramp directly:
```bash
gh workflow run desktop-release.yml \
@@ -455,18 +397,14 @@ gh workflow run desktop-release.yml \
-f rollout_hours=6
```
For a fresh release with a custom ramp, follow the [emergency release procedure](#emergency-release-rollout_hours0)
For a fresh release with a custom ramp, follow the [instant-admit procedure](#instant-admit-release-rollout_hours0)
and set `rollout_hours` to your chosen duration.
### Releasing during an active rollout
If you ship N+1 while N is still ramping, N+1 starts a new rollout from its own publish time, and the rollout of N ends because installs no longer see its manifests.
If you ship N+1 while N is still ramping, N+1 starts a fresh rollout from its own publish timestamp. N's rollout effectively ends — the newer manifest supersedes it. Rollout-aware clients revalidate the manifest for up to five seconds before installing a downloaded update on quit. If N+1 has replaced N but the client is not admitted to N+1 yet, it skips the downloaded N and waits rather than installing two updates in succession. If revalidation times out, the app exits without installing the cached update.
An install that holds N as a staged update keeps N when N+1 is a paced release, and installs N when the app quits. It then waits out its cooldown before it takes a later paced release. The hold covers only paced patch releases that the install saw one after the other. If the install missed a release, it evaluates the newest release instead: it replaces N when it is admitted, and drops N when it is not.
A minor or major release always ends the hold. The version numbers do not show whether a fix shipped between `0.17.4` and `0.18.0`, so the install treats `0.18.0` as if it missed a release.
Before an install at quit, the app asks GitHub for the latest release for up to five seconds. If that check does not finish in time, the app exits without installing the staged update.
If N+1 is a hotfix for a bug in N, dispatch `desktop-rollout.yml -f tag=v0.1.<N+1> -f rollout_hours=0` after N+1 publishes so the users who already got N reach the fix fast.
### macOS system floor
@@ -479,10 +417,10 @@ macOS 13 maps to Darwin 22. The two values use different version domains; do not
### Limitations
- A release cannot be recalled from an install that runs it. `allowDowngrade` is `false`. [Halt](#halt-a-release) the release to protect the other installs, then [ship a fix](#fix-a-bad-release).
- An emergency release reaches a running install at its next check, up to 6 hours after its previous one. A manual check sees it at once.
- Installs older than the canary and cooldown build have neither. They ramp in a straight line over `rolloutHours` and check every 30 minutes. Installs older than the staged rollout ignore `rolloutHours` and update at once.
- The app window starts every automatic check. A release whose window does not load cannot update itself, and its users must download a new build from the website. Smoke the packaged app before you publish.
- **No pause / kill switch.** To stop new admissions, ship a superseding release. Clients revalidate on quit and will not install the superseded download, but a client that already completed installation cannot be recalled; ship a hotfix `+1` patch.
- **No rollback.** `allowDowngrade = false`. Bad release = ship a hotfix.
- **Bootstrap caveat.** Clients running a build older than the rollout feature ignore `rolloutHours` and admit immediately. Rollout protection only applies to clients running the rollout-aware version or later.
- **Up to ~30 min automatic admission latency.** Renderer polls every 30 minutes, so a stable user may take up to that long to be evaluated against the rollout window. Clicking **Check** is manual and bypasses rollout admission.
## Mobile builds (EAS)
@@ -1,487 +0,0 @@
import { chmod, mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
AUTOMATIC_CHECK_INTERVAL_MS,
UPDATE_COOLDOWN_MS,
createAppUpdatePacing,
} from "./app-update-pacing";
const HOUR_MS = 3_600_000;
const START = Date.parse("2026-04-28T12:00:00.000Z");
const tempDirs: string[] = [];
afterEach(async () => {
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));
});
async function createUserData(): Promise<string> {
const dir = await mkdtemp(path.join(os.tmpdir(), "paseo-update-pacing-"));
tempDirs.push(dir);
return dir;
}
interface Install {
filePath: string;
errors: unknown[];
advance(ms: number): void;
setClock(time: number): void;
/** Starts the app again, as a new process would, on the given version. */
launch(version: string): ReturnType<typeof createAppUpdatePacing>;
readFile(): Promise<unknown>;
}
async function createInstall(input?: { filePath?: string }): Promise<Install> {
const filePath = input?.filePath ?? path.join(await createUserData(), "app-update-pacing.json");
const errors: unknown[] = [];
let now = START;
return {
filePath,
errors,
advance(ms) {
now += ms;
},
setClock(time) {
now = time;
},
launch(version) {
return createAppUpdatePacing({
filePath: () => filePath,
currentVersion: () => version,
now: () => now,
reportError: (error) => errors.push(error),
});
},
async readFile() {
return JSON.parse(await readFile(filePath, "utf8"));
},
};
}
describe("automatic check interval", () => {
it("is due on a fresh install", async () => {
const install = await createInstall();
const pacing = install.launch("1.2.3");
expect(await pacing.isAutomaticCheckDue()).toBe(true);
});
it("is not due again until 6 hours after a recorded check", async () => {
const install = await createInstall();
const pacing = install.launch("1.2.3");
await pacing.recordAutomaticCheck();
expect(await pacing.isAutomaticCheckDue()).toBe(false);
install.advance(AUTOMATIC_CHECK_INTERVAL_MS - 1);
expect(await pacing.isAutomaticCheckDue()).toBe(false);
install.advance(1);
expect(await pacing.isAutomaticCheckDue()).toBe(true);
});
it("stays due until a check is recorded, so a failed check is retried", async () => {
const install = await createInstall();
const pacing = install.launch("1.2.3");
expect(await pacing.isAutomaticCheckDue()).toBe(true);
install.advance(HOUR_MS);
expect(await pacing.isAutomaticCheckDue()).toBe(true);
});
it("remembers the last check across restarts", async () => {
const install = await createInstall();
await install.launch("1.2.3").recordAutomaticCheck();
install.advance(HOUR_MS);
expect(await install.launch("1.2.3").isAutomaticCheckDue()).toBe(false);
install.advance(AUTOMATIC_CHECK_INTERVAL_MS);
expect(await install.launch("1.2.3").isAutomaticCheckDue()).toBe(true);
});
it("is due when the last check is in the future because the clock moved back", async () => {
const install = await createInstall();
install.setClock(START + 365 * 24 * HOUR_MS);
await install.launch("1.2.3").recordAutomaticCheck();
install.setClock(START);
const pacing = install.launch("1.2.3");
expect(await pacing.isAutomaticCheckDue()).toBe(true);
await pacing.recordAutomaticCheck();
expect(await install.readFile()).toMatchObject({ lastAutoCheckAt: START });
});
it("is due after the clock jumps forward", async () => {
const install = await createInstall();
const pacing = install.launch("1.2.3");
await pacing.recordAutomaticCheck();
install.setClock(START + 365 * 24 * HOUR_MS);
expect(await pacing.isAutomaticCheckDue()).toBe(true);
});
});
describe("update cooldown", () => {
it("does not start on a fresh install", async () => {
const install = await createInstall();
const pacing = install.launch("1.2.3");
expect(await pacing.isInUpdateCooldown()).toBe(false);
expect(await install.readFile()).toEqual({
lastAutoCheckAt: null,
lastVersionSeen: "1.2.3",
lastAutoUpdateAt: null,
});
});
it("does not start when the app upgrades from a build that kept no pacing state", async () => {
const install = await createInstall();
// The earlier build never wrote the file, so there is no version to compare with.
const pacing = install.launch("1.2.4");
expect(await pacing.isInUpdateCooldown()).toBe(false);
expect(await install.readFile()).toMatchObject({
lastVersionSeen: "1.2.4",
lastAutoUpdateAt: null,
});
});
it("starts when the app launches on a newer version and lasts 72 hours", async () => {
const install = await createInstall();
await install.launch("1.2.3").start();
install.advance(HOUR_MS);
const pacing = install.launch("1.2.4");
expect(await pacing.isInUpdateCooldown()).toBe(true);
expect(await install.readFile()).toMatchObject({
lastVersionSeen: "1.2.4",
lastAutoUpdateAt: START + HOUR_MS,
});
install.advance(UPDATE_COOLDOWN_MS - 1);
expect(await pacing.isInUpdateCooldown()).toBe(true);
install.advance(1);
expect(await pacing.isInUpdateCooldown()).toBe(false);
});
it("starts when a prerelease build is replaced by its release", async () => {
const install = await createInstall();
await install.launch("1.3.0-beta.2").start();
expect(await install.launch("1.3.0").isInUpdateCooldown()).toBe(true);
});
it("is not restarted by launching the same version again", async () => {
const install = await createInstall();
await install.launch("1.2.3").start();
await install.launch("1.2.4").start();
install.advance(UPDATE_COOLDOWN_MS - HOUR_MS);
expect(await install.launch("1.2.4").isInUpdateCooldown()).toBe(true);
install.advance(HOUR_MS);
expect(await install.launch("1.2.4").isInUpdateCooldown()).toBe(false);
expect(await install.readFile()).toMatchObject({ lastAutoUpdateAt: START });
});
it("is not started by a downgrade, and a downgrade keeps a running cooldown", async () => {
const install = await createInstall();
await install.launch("1.2.4").start();
install.advance(HOUR_MS);
expect(await install.launch("1.2.3").isInUpdateCooldown()).toBe(false);
expect(await install.readFile()).toMatchObject({
lastVersionSeen: "1.2.4",
lastAutoUpdateAt: null,
});
install.advance(HOUR_MS);
await install.launch("1.2.5").start();
install.advance(HOUR_MS);
expect(await install.launch("1.2.4").isInUpdateCooldown()).toBe(true);
expect(await install.readFile()).toMatchObject({
lastVersionSeen: "1.2.5",
lastAutoUpdateAt: START + 2 * HOUR_MS,
});
});
it("is not restarted by switching between two installed builds", async () => {
const install = await createInstall();
await install.launch("1.2.3").start();
await install.launch("1.2.4").start();
install.advance(UPDATE_COOLDOWN_MS);
for (let round = 0; round < 3; round += 1) {
expect(await install.launch("1.2.3").isInUpdateCooldown()).toBe(false);
expect(await install.launch("1.2.4").isInUpdateCooldown()).toBe(false);
}
expect(await install.readFile()).toMatchObject({
lastVersionSeen: "1.2.4",
lastAutoUpdateAt: START,
});
});
it("is not started when the stored version cannot be compared", async () => {
const install = await createInstall();
await writeFile(
install.filePath,
JSON.stringify({ lastAutoCheckAt: null, lastVersionSeen: "nightly", lastAutoUpdateAt: null }),
);
expect(await install.launch("1.2.4").isInUpdateCooldown()).toBe(false);
expect(await install.readFile()).toMatchObject({ lastVersionSeen: "1.2.4" });
});
it("is over when the recorded update is in the future because the clock moved back", async () => {
const install = await createInstall();
await install.launch("1.2.3").start();
install.setClock(START + 365 * 24 * HOUR_MS);
await install.launch("1.2.4").start();
install.setClock(START);
expect(await install.launch("1.2.4").isInUpdateCooldown()).toBe(false);
});
it("is over after the clock jumps forward", async () => {
const install = await createInstall();
await install.launch("1.2.3").start();
const pacing = install.launch("1.2.4");
expect(await pacing.isInUpdateCooldown()).toBe(true);
install.setClock(START + 365 * 24 * HOUR_MS);
expect(await pacing.isInUpdateCooldown()).toBe(false);
});
it("is measured from launch, even when nothing asks until later", async () => {
const install = await createInstall();
await install.launch("1.2.3").start();
const pacing = install.launch("1.2.4");
await pacing.start();
install.advance(UPDATE_COOLDOWN_MS);
expect(await pacing.isInUpdateCooldown()).toBe(false);
});
});
describe("damaged pacing state", () => {
const damagedFiles: Array<[string, string]> = [
["an empty file", ""],
["truncated JSON", '{"lastAutoCheckAt": 17773'],
["binary garbage", "\u0000\u0001�\u0000"],
["a JSON array", "[1, 2, 3]"],
["JSON null", "null"],
["a JSON number", "42"],
["a JSON string", '"hello"'],
];
for (const [name, contents] of damagedFiles) {
it(`treats ${name} as a fresh install and replaces it`, async () => {
const install = await createInstall();
await writeFile(install.filePath, contents);
const pacing = install.launch("1.2.3");
expect(await pacing.isAutomaticCheckDue()).toBe(true);
expect(await pacing.isInUpdateCooldown()).toBe(false);
expect(await install.readFile()).toEqual({
lastAutoCheckAt: null,
lastVersionSeen: "1.2.3",
lastAutoUpdateAt: null,
});
});
}
it("drops each field that has the wrong shape", async () => {
const install = await createInstall();
await writeFile(
install.filePath,
JSON.stringify({
lastAutoCheckAt: "yesterday",
lastVersionSeen: 5,
lastAutoUpdateAt: { at: START },
}),
);
const pacing = install.launch("1.2.3");
expect(await pacing.isAutomaticCheckDue()).toBe(true);
expect(await pacing.isInUpdateCooldown()).toBe(false);
});
it("drops timestamps that are not real times", async () => {
const install = await createInstall();
for (const timestamp of ["-1", "1e400", "NaN"]) {
await writeFile(
install.filePath,
`{"lastAutoCheckAt": ${timestamp}, "lastVersionSeen": "1.2.3", "lastAutoUpdateAt": ${timestamp}}`,
);
const pacing = install.launch("1.2.3");
expect(await pacing.isAutomaticCheckDue()).toBe(true);
expect(await pacing.isInUpdateCooldown()).toBe(false);
}
});
it("keeps the valid fields next to a damaged one", async () => {
const install = await createInstall();
await writeFile(
install.filePath,
JSON.stringify({
lastAutoCheckAt: START,
lastVersionSeen: "1.2.3",
lastAutoUpdateAt: "garbage",
futureField: true,
}),
);
const pacing = install.launch("1.2.3");
expect(await pacing.isAutomaticCheckDue()).toBe(false);
expect(await pacing.isInUpdateCooldown()).toBe(false);
});
it("ignores a temp file left behind by a crash in the middle of a write", async () => {
const install = await createInstall();
await install.launch("1.2.3").recordAutomaticCheck();
await writeFile(`${install.filePath}.tmp.999.crashed`, '{"lastAutoCheckAt": 1');
const pacing = install.launch("1.2.3");
expect(await pacing.isAutomaticCheckDue()).toBe(false);
expect(install.errors).toEqual([]);
});
it("leaves one complete file after every write", async () => {
const install = await createInstall();
const pacing = install.launch("1.2.3");
await Promise.all(
Array.from({ length: 25 }, async () => {
await pacing.recordAutomaticCheck();
await pacing.isAutomaticCheckDue();
}),
);
expect(await readdir(path.dirname(install.filePath))).toEqual(["app-update-pacing.json"]);
expect(await install.readFile()).toEqual({
lastAutoCheckAt: START,
lastVersionSeen: "1.2.3",
lastAutoUpdateAt: null,
});
});
});
describe("pacing state that cannot be stored", () => {
it("never throttles checks and never starts a cooldown when the file cannot be written", async () => {
const userData = await createUserData();
const blocker = path.join(userData, "not-a-directory");
await writeFile(blocker, "");
const install = await createInstall({ filePath: path.join(blocker, "app-update-pacing.json") });
for (const version of ["1.2.3", "1.2.4", "1.2.5"]) {
const pacing = install.launch(version);
await pacing.recordAutomaticCheck();
expect(await pacing.isAutomaticCheckDue()).toBe(true);
expect(await pacing.isInUpdateCooldown()).toBe(false);
}
expect(install.errors.length).toBeGreaterThan(0);
});
// Windows has no directory write permission to revoke, and root ignores it.
it.skipIf(process.platform === "win32" || process.getuid?.() === 0)(
"does not restart the cooldown on every launch when a version advance cannot be stored",
async () => {
const install = await createInstall();
await install.launch("1.2.3").start();
const stateDir = path.dirname(install.filePath);
await chmod(stateDir, 0o555);
try {
for (let launch = 0; launch < 3; launch += 1) {
install.advance(HOUR_MS);
const pacing = install.launch("1.2.4");
expect(await pacing.isInUpdateCooldown()).toBe(false);
await pacing.recordAutomaticCheck();
expect(await pacing.isAutomaticCheckDue()).toBe(true);
}
expect(await install.readFile()).toMatchObject({ lastVersionSeen: "1.2.3" });
expect(install.errors.length).toBeGreaterThan(0);
} finally {
await chmod(stateDir, 0o755);
}
},
);
it("keeps the last stored check time when a later write fails", async () => {
const userData = await createUserData();
const stateDir = path.join(userData, "state");
await mkdir(stateDir);
const install = await createInstall({
filePath: path.join(stateDir, "app-update-pacing.json"),
});
const pacing = install.launch("1.2.3");
await pacing.recordAutomaticCheck();
await rm(stateDir, { recursive: true });
await writeFile(stateDir, "");
install.advance(AUTOMATIC_CHECK_INTERVAL_MS);
await pacing.recordAutomaticCheck();
expect(await pacing.isAutomaticCheckDue()).toBe(true);
});
it("treats an unreadable file as a fresh install", async () => {
const install = await createInstall();
await mkdir(install.filePath);
const pacing = install.launch("1.2.3");
expect(await pacing.isAutomaticCheckDue()).toBe(true);
expect(await pacing.isInUpdateCooldown()).toBe(false);
await expect(pacing.recordAutomaticCheck()).resolves.toBeUndefined();
expect(install.errors.length).toBeGreaterThan(0);
});
it("drops a change when the finished file cannot replace the stored one", async () => {
const install = await createInstall();
// A directory at the file path lets the temp file be written but not renamed into place.
await mkdir(install.filePath);
const pacing = install.launch("1.2.3");
await pacing.recordAutomaticCheck();
expect(await pacing.isAutomaticCheckDue()).toBe(true);
expect(await readdir(path.dirname(install.filePath))).toEqual(["app-update-pacing.json"]);
});
it("stays open when the file path or the running version cannot be resolved", async () => {
const errors: unknown[] = [];
const brokenPath = createAppUpdatePacing({
filePath: () => {
throw new Error("userData is not available");
},
currentVersion: () => "1.2.3",
now: () => START,
reportError: (error) => errors.push(error),
});
const install = await createInstall();
const brokenVersion = createAppUpdatePacing({
filePath: () => install.filePath,
currentVersion: () => {
throw new Error("version is not available");
},
now: () => START,
reportError: (error) => errors.push(error),
});
for (const pacing of [brokenPath, brokenVersion]) {
await expect(pacing.start()).resolves.toBeUndefined();
await expect(pacing.recordAutomaticCheck()).resolves.toBeUndefined();
expect(await pacing.isAutomaticCheckDue()).toBe(true);
expect(await pacing.isInUpdateCooldown()).toBe(false);
}
expect(errors.length).toBeGreaterThan(0);
});
});
@@ -1,168 +0,0 @@
import { randomUUID } from "node:crypto";
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
import path from "node:path";
import { z } from "zod";
import { isNewerVersion } from "./app-update-version.js";
export const AUTOMATIC_CHECK_INTERVAL_MS = 6 * 60 * 60 * 1000;
export const UPDATE_COOLDOWN_MS = 72 * 60 * 60 * 1000;
/**
* Paces automatic updates so frequent releases stay calm: automatic checks run
* at most once per interval, and a paced release is deferred for the cooldown
* after the app last moved to a newer version.
*
* Every answer fails open. Missing, damaged, unreadable or unwritable state, a
* clock that jumped, and any unexpected error all answer "check now" and "not in
* cooldown". No method rejects.
*/
export interface AppUpdatePacing {
/** Loads the stored state and notes the running version. Call once at startup. */
start(): Promise<void>;
isAutomaticCheckDue(): Promise<boolean>;
recordAutomaticCheck(): Promise<void>;
isInUpdateCooldown(): Promise<boolean>;
}
export interface AppUpdatePacingDeps {
filePath(): string;
currentVersion(): string;
now(): number;
reportError?(error: unknown): void;
}
const TimestampSchema = z.number().finite().nonnegative().nullable().catch(null);
// Loose, so a field added by a newer build survives a launch of this one.
const PacingStateSchema = z.looseObject({
lastAutoCheckAt: TimestampSchema,
lastVersionSeen: z.string().min(1).nullable().catch(null),
lastAutoUpdateAt: TimestampSchema,
});
type PacingState = z.output<typeof PacingStateSchema>;
const EMPTY_STATE: PacingState = {
lastAutoCheckAt: null,
lastVersionSeen: null,
lastAutoUpdateAt: null,
};
/**
* A window is open only while `now` sits inside it. A timestamp in the future
* comes from a clock that moved back, and it must not hold the window open
* until the clock catches up.
*/
function isWithinWindow(startedAt: number | null, now: number, durationMs: number): boolean {
if (startedAt === null) return false;
const elapsed = now - startedAt;
return elapsed >= 0 && elapsed < durationMs;
}
function isMissingFileError(error: unknown): boolean {
return error instanceof Error && (error as NodeJS.ErrnoException).code === "ENOENT";
}
export function createAppUpdatePacing(deps: AppUpdatePacingDeps): AppUpdatePacing {
// `state` always equals what is on disk. A change that cannot be stored is
// dropped, so a version advance that fails to persist cannot restart the
// cooldown on every launch.
let state: PacingState = EMPTY_STATE;
let loaded = false;
let operationQueue: Promise<void> = Promise.resolve();
function enqueue<T>(operation: () => Promise<T>): Promise<T> {
const result = operationQueue.then(operation, operation);
operationQueue = result.then(
() => undefined,
() => undefined,
);
return result;
}
async function readState(filePath: string): Promise<PacingState> {
let raw: string;
try {
raw = await readFile(filePath, "utf8");
} catch (error) {
if (!isMissingFileError(error)) deps.reportError?.(error);
return EMPTY_STATE;
}
try {
return PacingStateSchema.parse(JSON.parse(raw));
} catch (error) {
deps.reportError?.(error);
return EMPTY_STATE;
}
}
async function store(next: PacingState): Promise<void> {
const filePath = deps.filePath();
const tempFilePath = `${filePath}.tmp.${process.pid}.${randomUUID()}`;
try {
await mkdir(path.dirname(filePath), { recursive: true });
await writeFile(tempFilePath, `${JSON.stringify(next, null, 2)}\n`, "utf8");
await rename(tempFilePath, filePath);
state = next;
} catch (error) {
deps.reportError?.(error);
await rm(tempFilePath, { force: true }).catch(() => undefined);
}
}
async function noteRunningVersion(): Promise<void> {
const currentVersion = deps.currentVersion();
const previousVersion = state.lastVersionSeen;
if (previousVersion === currentVersion) return;
// `lastVersionSeen` is the newest version this install has run. A launch of
// an older build leaves it alone, so switching between two installed builds
// cannot restart the cooldown each time the newer one starts.
if (previousVersion !== null && isNewerVersion(previousVersion, currentVersion)) return;
// With no earlier version to compare (first launch, or the first launch of
// a build that keeps this state), the app did not necessarily update.
const updated = previousVersion !== null && isNewerVersion(currentVersion, previousVersion);
await store({
...state,
lastVersionSeen: currentVersion,
lastAutoUpdateAt: updated ? deps.now() : state.lastAutoUpdateAt,
});
}
async function ensureLoaded(): Promise<void> {
if (loaded) return;
state = await readState(deps.filePath());
await noteRunningVersion();
loaded = true;
}
function withState<T>(fallback: T, read: () => T | Promise<T>): Promise<T> {
return enqueue(async () => {
try {
await ensureLoaded();
return await read();
} catch (error) {
deps.reportError?.(error);
return fallback;
}
});
}
return {
start: () => withState(undefined, () => undefined),
isAutomaticCheckDue: () =>
withState(
true,
() => !isWithinWindow(state.lastAutoCheckAt, deps.now(), AUTOMATIC_CHECK_INTERVAL_MS),
),
recordAutomaticCheck: () =>
withState(undefined, () => store({ ...state, lastAutoCheckAt: deps.now() })),
isInUpdateCooldown: () =>
withState(false, () =>
isWithinWindow(state.lastAutoUpdateAt, deps.now(), UPDATE_COOLDOWN_MS),
),
};
}
@@ -1,234 +1,156 @@
import { describe, expect, it } from "vitest";
import {
isPacedRelease,
rolloutAdmissionPercent,
rolloutBucket,
rolloutManifestSchema,
shouldAdmitAppUpdate,
} from "./app-update-rollout";
const RELEASE_DATE = "2026-04-28T00:00:00.000Z";
const RELEASE_TIME = Date.parse(RELEASE_DATE);
const HOUR_MS = 3_600_000;
const MAX_BUCKET = (0x100000000 - 1) / 0x100000000;
function admitsStable(input: {
ageHours: number;
bucket: number;
rolloutHours?: number;
intent?: "automatic" | "manual";
}): boolean {
return shouldAdmitAppUpdate({
channel: "stable",
intent: input.intent ?? "automatic",
rolloutHours: input.rolloutHours ?? 18,
releaseDate: RELEASE_DATE,
now: RELEASE_TIME + input.ageHours * HOUR_MS,
bucket: input.bucket,
});
}
describe("rolloutAdmissionPercent", () => {
it("holds the default 18 hour rollout at 5% for 8 hours, then ramps linearly to 100%", () => {
expect(rolloutAdmissionPercent({ rolloutHours: 18, ageHours: 0 })).toBe(5);
expect(rolloutAdmissionPercent({ rolloutHours: 18, ageHours: 4 })).toBe(5);
expect(rolloutAdmissionPercent({ rolloutHours: 18, ageHours: 8 })).toBe(5);
expect(rolloutAdmissionPercent({ rolloutHours: 18, ageHours: 13 })).toBe(52.5);
expect(rolloutAdmissionPercent({ rolloutHours: 18, ageHours: 18 })).toBe(100);
expect(rolloutAdmissionPercent({ rolloutHours: 18, ageHours: 500 })).toBe(100);
});
it("never decreases as a release ages", () => {
let previous = 0;
for (let ageHours = 0; ageHours <= 20; ageHours += 0.25) {
const percent = rolloutAdmissionPercent({ rolloutHours: 18, ageHours });
expect(percent).toBeGreaterThanOrEqual(previous);
previous = percent;
}
});
it("shortens the canary hold to half of a rollout shorter than 16 hours", () => {
expect(rolloutAdmissionPercent({ rolloutHours: 6, ageHours: 2.9 })).toBe(5);
expect(rolloutAdmissionPercent({ rolloutHours: 6, ageHours: 3 })).toBe(5);
expect(rolloutAdmissionPercent({ rolloutHours: 6, ageHours: 4.5 })).toBe(52.5);
expect(rolloutAdmissionPercent({ rolloutHours: 6, ageHours: 6 })).toBe(100);
});
it("keeps the canary hold at 8 hours when a rollout is slowed down", () => {
expect(rolloutAdmissionPercent({ rolloutHours: 72, ageHours: 8 })).toBe(5);
expect(rolloutAdmissionPercent({ rolloutHours: 72, ageHours: 40 })).toBe(52.5);
expect(rolloutAdmissionPercent({ rolloutHours: 72, ageHours: 72 })).toBe(100);
});
it("completes a tiny rollout without dividing by zero", () => {
expect(rolloutAdmissionPercent({ rolloutHours: 0.001, ageHours: 0 })).toBe(5);
expect(rolloutAdmissionPercent({ rolloutHours: 0.001, ageHours: 0.001 })).toBe(100);
expect(rolloutAdmissionPercent({ rolloutHours: Number.MIN_VALUE, ageHours: 1 })).toBe(100);
});
it("treats a release dated slightly in the future as just released", () => {
expect(rolloutAdmissionPercent({ rolloutHours: 18, ageHours: -1 })).toBe(5);
});
});
import { bucketFromStagingUserId, shouldAdmitAppUpdate } from "./app-update-rollout";
describe("shouldAdmitAppUpdate", () => {
it("admits only the canary bucket during the canary hold", () => {
expect(admitsStable({ ageHours: 0, bucket: 0 })).toBe(true);
expect(admitsStable({ ageHours: 4, bucket: 0.049 })).toBe(true);
expect(admitsStable({ ageHours: 4, bucket: 0.05 })).toBe(false);
expect(admitsStable({ ageHours: 8, bucket: 0.05 })).toBe(false);
expect(admitsStable({ ageHours: 8, bucket: MAX_BUCKET })).toBe(false);
});
it("admits by bucket along the ramp", () => {
expect(admitsStable({ ageHours: 13, bucket: 0.52 })).toBe(true);
expect(admitsStable({ ageHours: 13, bucket: 0.53 })).toBe(false);
});
it("admits every bucket at and after the rollout end", () => {
expect(admitsStable({ ageHours: 18, bucket: MAX_BUCKET })).toBe(true);
expect(admitsStable({ ageHours: 24 * 365, bucket: MAX_BUCKET })).toBe(true);
});
it("lets manual checks bypass the rollout", () => {
expect(admitsStable({ ageHours: 1, bucket: MAX_BUCKET, intent: "manual" })).toBe(true);
expect(admitsStable({ ageHours: -48, bucket: MAX_BUCKET, intent: "manual" })).toBe(true);
});
it("admits everyone to an emergency release with rolloutHours 0", () => {
expect(admitsStable({ ageHours: 0, bucket: MAX_BUCKET, rolloutHours: 0 })).toBe(true);
expect(admitsStable({ ageHours: -48, bucket: MAX_BUCKET, rolloutHours: 0 })).toBe(true);
});
it("admits beta, missing rollout hours, and a missing or unparseable release date", () => {
const base = {
intent: "automatic" as const,
rolloutHours: 18,
releaseDate: RELEASE_DATE,
now: RELEASE_TIME + HOUR_MS,
bucket: MAX_BUCKET,
};
expect(shouldAdmitAppUpdate({ ...base, channel: "beta" })).toBe(true);
expect(shouldAdmitAppUpdate({ ...base, channel: "stable", rolloutHours: undefined })).toBe(
true,
);
expect(shouldAdmitAppUpdate({ ...base, channel: "stable", releaseDate: undefined })).toBe(true);
expect(shouldAdmitAppUpdate({ ...base, channel: "stable", releaseDate: "not a date" })).toBe(
true,
);
});
it("keeps a client whose clock is slightly behind the release date in the canary hold", () => {
expect(admitsStable({ ageHours: -1, bucket: 0.049 })).toBe(true);
expect(admitsStable({ ageHours: -1, bucket: 0.05 })).toBe(false);
expect(admitsStable({ ageHours: -2, bucket: 0.05 })).toBe(false);
});
it("admits a client whose clock is too far behind the release date to place on the curve", () => {
// With releases shipping more often than the clock error, this client
// would otherwise see every release as unreleased and never update.
expect(admitsStable({ ageHours: -2.01, bucket: MAX_BUCKET })).toBe(true);
expect(admitsStable({ ageHours: -24 * 365, bucket: MAX_BUCKET })).toBe(true);
});
it("treats garbage manifest rollout fields as missing and admits", () => {
const parsed = rolloutManifestSchema.parse({
rolloutHours: "not a number",
releaseDate: 12345,
});
it("keeps automatic stable updates behind the rollout window", () => {
expect(
shouldAdmitAppUpdate({
channel: "stable",
intent: "automatic",
rolloutHours: parsed.rolloutHours,
releaseDate: parsed.releaseDate,
now: RELEASE_TIME + HOUR_MS,
bucket: MAX_BUCKET,
rolloutHours: 24,
releaseDate: "2026-04-28T00:00:00.000Z",
now: Date.parse("2026-04-28T12:00:00.000Z"),
bucket: 0.51,
}),
).toBe(false);
});
it("lets manual stable checks bypass rollout admission", () => {
expect(
shouldAdmitAppUpdate({
channel: "stable",
intent: "manual",
rolloutHours: 24,
releaseDate: "2026-04-28T00:00:00.000Z",
now: Date.parse("2026-04-28T12:00:00.000Z"),
bucket: 0.99,
}),
).toBe(true);
});
it("parses the stamped rollout fields that older clients already read", () => {
expect(rolloutManifestSchema.parse({ rolloutHours: 18, releaseDate: RELEASE_DATE })).toEqual({
rolloutHours: 18,
releaseDate: RELEASE_DATE,
});
expect(rolloutManifestSchema.parse({ rolloutHours: "18" }).rolloutHours).toBe(18);
expect(rolloutManifestSchema.parse({ rolloutHours: -1 }).rolloutHours).toBeUndefined();
it("admits beta, missing rollout hours, zero-hour rollout, and missing release date", () => {
expect(
shouldAdmitAppUpdate({
channel: "beta",
intent: "automatic",
rolloutHours: 24,
releaseDate: "2026-04-28T00:00:00.000Z",
now: Date.parse("2026-04-28T01:00:00.000Z"),
bucket: 0.99,
}),
).toBe(true);
expect(
shouldAdmitAppUpdate({
channel: "stable",
intent: "automatic",
rolloutHours: undefined,
releaseDate: "2026-04-28T00:00:00.000Z",
now: Date.parse("2026-04-28T01:00:00.000Z"),
bucket: 0.99,
}),
).toBe(true);
expect(
shouldAdmitAppUpdate({
channel: "stable",
intent: "automatic",
rolloutHours: 0,
releaseDate: "2026-04-28T00:00:00.000Z",
now: Date.parse("2026-04-28T01:00:00.000Z"),
bucket: 0.99,
}),
).toBe(true);
expect(
shouldAdmitAppUpdate({
channel: "stable",
intent: "automatic",
rolloutHours: 24,
releaseDate: undefined,
now: Date.parse("2026-04-28T01:00:00.000Z"),
bucket: 0.99,
}),
).toBe(true);
});
});
describe("isPacedRelease", () => {
it("paces only stable releases with a positive rollout duration", () => {
expect(isPacedRelease({ channel: "stable", rolloutHours: 18 })).toBe(true);
expect(isPacedRelease({ channel: "stable", rolloutHours: 0.5 })).toBe(true);
expect(isPacedRelease({ channel: "stable", rolloutHours: 0 })).toBe(false);
expect(isPacedRelease({ channel: "stable", rolloutHours: undefined })).toBe(false);
expect(isPacedRelease({ channel: "beta", rolloutHours: 18 })).toBe(false);
});
});
describe("rolloutBucket", () => {
const stagingUserId = "3f2c1b6e-8a4d-5c7e-9b1a-2d3e4f5a6b7c";
it("blocks future automatic releases and admits the same release manually", () => {
const input = {
channel: "stable" as const,
rolloutHours: 24,
releaseDate: "2026-04-28T02:00:00.000Z",
now: Date.parse("2026-04-28T01:00:00.000Z"),
bucket: 0,
};
function stagingUserIdAt(index: number): string {
return `00000000-0000-5000-8000-${index.toString(16).padStart(12, "0")}`;
}
it("is stable for one install and one version", () => {
expect(rolloutBucket(stagingUserId, "1.2.4")).toBe(rolloutBucket(stagingUserId, "1.2.4"));
expect(shouldAdmitAppUpdate({ ...input, intent: "automatic" })).toBe(false);
expect(shouldAdmitAppUpdate({ ...input, intent: "manual" })).toBe(true);
});
it("always lands in [0, 1)", () => {
for (let index = 0; index < 2000; index += 1) {
const bucket = rolloutBucket(stagingUserIdAt(index), "1.2.4");
expect(bucket).toBeGreaterThanOrEqual(0);
expect(bucket).toBeLessThan(1);
}
it("blocks the bucket-zero client at exact release time, admits as soon as time advances", () => {
expect(
shouldAdmitAppUpdate({
channel: "stable",
intent: "automatic",
rolloutHours: 24,
releaseDate: "2026-04-28T00:00:00.000Z",
now: Date.parse("2026-04-28T00:00:00.000Z"),
bucket: 0,
}),
).toBe(false);
expect(
shouldAdmitAppUpdate({
channel: "stable",
intent: "automatic",
rolloutHours: 24,
releaseDate: "2026-04-28T00:00:00.000Z",
now: Date.parse("2026-04-28T00:00:00.001Z"),
bucket: 0,
}),
).toBe(true);
});
it("gives one install a different bucket for each version", () => {
const buckets = new Set(
Array.from({ length: 50 }, (_, patch) => rolloutBucket(stagingUserId, `1.2.${patch}`)),
);
expect(buckets.size).toBe(50);
it("admits the highest-bucket automatic client at and past the rollout end", () => {
const maxBucket = (0x100000000 - 1) / 0x100000000;
expect(
shouldAdmitAppUpdate({
channel: "stable",
intent: "automatic",
rolloutHours: 24,
releaseDate: "2026-04-28T00:00:00.000Z",
now: Date.parse("2026-04-29T00:00:00.000Z"),
bucket: maxBucket,
}),
).toBe(true);
expect(
shouldAdmitAppUpdate({
channel: "stable",
intent: "automatic",
rolloutHours: 24,
releaseDate: "2026-04-28T00:00:00.000Z",
now: Date.parse("2027-04-28T00:00:00.000Z"),
bucket: maxBucket,
}),
).toBe(true);
});
it("spreads installs evenly so about 5% land in the canary", () => {
const installs = 20_000;
let canary = 0;
for (let index = 0; index < installs; index += 1) {
if (rolloutBucket(stagingUserIdAt(index), "1.2.4") < 0.05) canary += 1;
}
expect(canary / installs).toBeGreaterThan(0.04);
expect(canary / installs).toBeLessThan(0.06);
it("admits when releaseDate is unparseable", () => {
expect(
shouldAdmitAppUpdate({
channel: "stable",
intent: "automatic",
rolloutHours: 24,
releaseDate: "not a date",
now: Date.parse("2026-04-28T12:00:00.000Z"),
bucket: 0.99,
}),
).toBe(true);
});
it("picks a fresh canary group for each version", () => {
const installs = 20_000;
let canaryForBoth = 0;
for (let index = 0; index < installs; index += 1) {
const id = stagingUserIdAt(index);
if (rolloutBucket(id, "1.2.4") < 0.05 && rolloutBucket(id, "1.2.5") < 0.05) {
canaryForBoth += 1;
}
}
// Independent 5% groups overlap in about 0.25% of installs. A sticky bucket
// would overlap in all 5%.
expect(canaryForBoth / installs).toBeLessThan(0.01);
});
it("maps the maximum 32-bit slot to a bucket strictly less than 1", () => {
const allOnes = "ffffffff-ffff-ffff-ffff-ffffffffffff";
const allZeros = "00000000-0000-0000-0000-000000000000";
it("never leaves an install outside the canary for every version", () => {
for (let index = 0; index < 200; index += 1) {
const id = stagingUserIdAt(index);
let canaryReleases = 0;
for (let patch = 0; patch < 400; patch += 1) {
if (rolloutBucket(id, `1.2.${patch}`) < 0.05) canaryReleases += 1;
}
expect(canaryReleases).toBeGreaterThan(0);
}
expect(bucketFromStagingUserId(allOnes)).toBeLessThan(1);
expect(bucketFromStagingUserId(allOnes)).toBeGreaterThan(0.999);
expect(bucketFromStagingUserId(allZeros)).toBe(0);
});
});
@@ -1,16 +1,9 @@
import { createHash } from "node:crypto";
import { UUID } from "builder-util-runtime";
import { z } from "zod";
export type AppReleaseChannel = "stable" | "beta";
export type AppUpdateCheckIntent = "automatic" | "manual";
const HOUR_MS = 3_600_000;
const CANARY_PERCENT = 5;
const MAX_CANARY_HOURS = 8;
// A release date this far ahead of the local clock means the clock is wrong,
// not that the release is new. One hour of daylight-saving error stays inside.
const CLOCK_SKEW_TOLERANCE_HOURS = 2;
export const rolloutManifestSchema = z.object({
rolloutHours: z
.union([z.number(), z.string().transform(Number)])
@@ -20,37 +13,6 @@ export const rolloutManifestSchema = z.object({
releaseDate: z.string().optional().catch(undefined),
});
/**
* A paced release reaches automatic clients gradually. Every other release
* (beta, `rolloutHours: 0`, or no usable `rolloutHours`) reaches them at once.
*/
export function isPacedRelease(args: {
channel: AppReleaseChannel;
rolloutHours: number | undefined;
}): boolean {
return args.channel === "stable" && args.rolloutHours != null && args.rolloutHours > 0;
}
/**
* Share of automatic clients admitted to a paced release: a canary hold at 5%,
* then a linear ramp to 100% at `rolloutHours`.
*/
export function rolloutAdmissionPercent(args: { rolloutHours: number; ageHours: number }): number {
const ageHours = Math.max(0, args.ageHours);
if (ageHours >= args.rolloutHours) return 100;
const canaryHours = Math.min(MAX_CANARY_HOURS, args.rolloutHours / 2);
if (ageHours <= canaryHours) return CANARY_PERCENT;
const rampProgress = (ageHours - canaryHours) / (args.rolloutHours - canaryHours);
return Math.min(100, CANARY_PERCENT + (100 - CANARY_PERCENT) * rampProgress);
}
/**
* Every branch that cannot place the client on the rollout curve admits it.
* A client must never be refused a release because of bad metadata or a bad
* local clock.
*/
export function shouldAdmitAppUpdate(args: {
channel: AppReleaseChannel;
intent: AppUpdateCheckIntent;
@@ -60,26 +22,21 @@ export function shouldAdmitAppUpdate(args: {
bucket: number;
}): boolean {
if (args.intent === "manual") return true;
if (!isPacedRelease(args) || args.rolloutHours == null) return true;
if (args.channel !== "stable") return true;
if (args.rolloutHours == null) return true;
if (args.rolloutHours === 0) return true;
if (!args.releaseDate) return true;
const releaseTime = new Date(args.releaseDate).getTime();
if (Number.isNaN(releaseTime)) return true;
const ageHours = (args.now - releaseTime) / HOUR_MS;
if (Number.isNaN(ageHours)) return true;
if (ageHours < -CLOCK_SKEW_TOLERANCE_HOURS) return true;
const ageHours = (args.now - releaseTime) / 3_600_000;
if (ageHours < 0) return false;
const percent = rolloutAdmissionPercent({ rolloutHours: args.rolloutHours, ageHours });
return args.bucket * 100 < percent;
const pct = Math.min(100, (ageHours / args.rolloutHours) * 100);
return args.bucket * 100 < pct;
}
/**
* Position of one install in one release's rollout, in [0, 1). Salting with the
* version gives every release a different canary group, so no install is first
* for every release and none is last for every release.
*/
export function rolloutBucket(stagingUserId: string, version: string): number {
const digest = createHash("sha256").update(`${stagingUserId}:${version}`).digest();
return digest.readUInt32BE(0) / 0x100000000;
export function bucketFromStagingUserId(stagingUserId: string): number {
return UUID.parse(stagingUserId).readUInt32BE(12) / 0x100000000;
}
@@ -1,19 +1,8 @@
import { mkdtemp, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, it, vi } from "vitest";
import { describe, expect, it, vi } from "vitest";
import type { DesktopUpdateMode } from "../settings/desktop-settings";
import {
AUTOMATIC_CHECK_INTERVAL_MS,
UPDATE_COOLDOWN_MS,
createAppUpdatePacing,
type AppUpdatePacing,
} from "./app-update-pacing";
import type { AppReleaseChannel, AppUpdateCheckIntent } from "./app-update-rollout";
import {
createAppUpdateService,
type AppUpdateCheckResult,
type AppUpdateDownloadProgress,
type AppUpdateInstallRequest,
type AppUpdateRuntime,
@@ -183,18 +172,9 @@ class FakeAppUpdateRuntime implements AppUpdateRuntime {
}
}
/** An install whose automatic checks are always due and that never updated recently. */
const unpaced: AppUpdatePacing = {
start: async () => undefined,
isAutomaticCheckDue: async () => true,
recordAutomaticCheck: async () => undefined,
isInUpdateCooldown: async () => false,
};
function createService(input?: {
now?: () => number;
bucket?: (version: string) => Promise<number>;
pacing?: AppUpdatePacing;
bucket?: () => Promise<number>;
updateMode?: () => DesktopUpdateMode | Promise<DesktopUpdateMode>;
reportSettingsError?: (error: unknown) => void;
onDownloadProgress?: (progress: AppUpdateDownloadProgress | null) => void;
@@ -205,7 +185,6 @@ function createService(input?: {
isPackaged: () => true,
now: input?.now ?? (() => Date.parse("2026-04-28T12:00:00.000Z")),
bucket: input?.bucket ?? (async () => 0.99),
pacing: input?.pacing ?? unpaced,
updateMode: input?.updateMode,
reportSettingsError: input?.reportSettingsError,
onDownloadProgress: input?.onDownloadProgress,
@@ -349,7 +328,7 @@ describe("app update service", () => {
intent: "manual",
});
await new Promise<void>((resolve) => setImmediate(resolve));
await Promise.resolve();
expect(runtime.checkCount).toBe(1);
automaticCheck.resolve({ isUpdateAvailable: false, updateInfo: rolledOutUpdate });
@@ -393,7 +372,7 @@ describe("app update service", () => {
});
});
it("replaces a downloaded update when a later release that skips a version is admitted", async () => {
it("replaces a downloaded update when a newer release is admitted", async () => {
const { runtime, service } = createService({ bucket: async () => 0 });
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: rolledOutUpdate });
@@ -404,8 +383,8 @@ describe("app update service", () => {
});
runtime.finishUpdateDownload(rolledOutUpdate);
const laterUpdate = { ...rolledOutUpdate, version: "1.2.6" };
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: laterUpdate });
const newerUpdate = { ...rolledOutUpdate, version: "1.2.5" };
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: newerUpdate });
const result = await service.checkForAppUpdate({
currentVersion: "1.2.3",
releaseChannel: "stable",
@@ -417,7 +396,7 @@ describe("app update service", () => {
readyToInstall: false,
downloading: true,
currentVersion: "1.2.3",
latestVersion: "1.2.6",
latestVersion: "1.2.5",
body: null,
date: "2026-04-28T00:00:00.000Z",
errorMessage: null,
@@ -435,8 +414,8 @@ describe("app update service", () => {
});
runtime.finishUpdateDownload(rolledOutUpdate);
const laterUpdate = { ...rolledOutUpdate, version: "1.2.6" };
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: laterUpdate });
const newerUpdate = { ...rolledOutUpdate, version: "1.2.5" };
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: newerUpdate });
const installed = await service.installUpdateOnQuit({
currentVersion: "1.2.3",
releaseChannel: "stable",
@@ -444,13 +423,13 @@ describe("app update service", () => {
});
expect(installed).toBe(true);
expect(runtime.installedVersions).toEqual(["1.2.6"]);
expect(runtime.installedVersions).toEqual(["1.2.5"]);
expect(runtime.installModes).toEqual([
{ targetVersion: "1.2.6", isSilent: true, isForceRunAfter: false },
{ targetVersion: "1.2.5", isSilent: true, isForceRunAfter: false },
]);
});
it("does not install an older download when a later release that skips a version is still rolling out", async () => {
it("does not install an older download while its replacement is still rolling out", async () => {
const now = Date.parse("2026-04-28T12:00:00.000Z");
const { runtime, service } = createService({ now: () => now, bucket: async () => 0.4 });
const olderUpdate = {
@@ -466,12 +445,12 @@ describe("app update service", () => {
});
runtime.finishUpdateDownload(olderUpdate);
const laterUpdate = {
const newerUpdate = {
...rolledOutUpdate,
version: "1.2.6",
version: "1.2.5",
releaseDate: "2026-04-28T12:00:00.000Z",
};
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: laterUpdate });
runtime.nextCheck({ isUpdateAvailable: true, updateInfo: newerUpdate });
const installed = await service.installUpdateOnQuit({
currentVersion: "1.2.3",
releaseChannel: "stable",
@@ -1324,710 +1303,3 @@ describe("app update service", () => {
});
});
});
const HOUR_MS = 3_600_000;
const START = Date.parse("2026-04-28T12:00:00.000Z");
const tempDirs: string[] = [];
afterEach(async () => {
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { force: true, recursive: true })));
});
/** A paced stable release whose rollout finished long before `START`. */
function pacedRelease(version: string): RuntimeUpdateInfo {
return { version, releaseDate: "2026-04-20T00:00:00.000Z", rolloutHours: 18 };
}
/** A paced stable release published at `publishedAt`, so only its canary group is admitted. */
function newPacedRelease(version: string, publishedAt: number): RuntimeUpdateInfo {
return { version, releaseDate: new Date(publishedAt).toISOString(), rolloutHours: 18 };
}
function emergencyRelease(version: string): RuntimeUpdateInfo {
return { ...pacedRelease(version), rolloutHours: 0 };
}
interface RunningApp {
runtime: FakeAppUpdateRuntime;
/** Makes the release feed answer the next check with `release` as the latest release. */
publish(release: RuntimeUpdateInfo): void;
check(input?: {
intent?: AppUpdateCheckIntent;
releaseChannel?: AppReleaseChannel;
}): Promise<AppUpdateCheckResult>;
/** Finds `release` with an automatic check and finishes downloading it. */
stage(release: RuntimeUpdateInfo): Promise<void>;
quit(): Promise<boolean>;
}
function startApp(
version: string,
options?: {
now?: () => number;
bucket?: (version: string) => Promise<number>;
pacing?: AppUpdatePacing;
updateMode?: () => DesktopUpdateMode;
},
): RunningApp {
const { runtime, service } = createService({
now: options?.now ?? (() => START),
bucket: options?.bucket ?? (async () => 0),
pacing: options?.pacing,
updateMode: options?.updateMode,
});
const app: RunningApp = {
runtime,
publish(release) {
// The updater reports the running version as "no update" before it asks
// whether the install is admitted.
runtime.nextCheck({ isUpdateAvailable: release.version !== version, updateInfo: release });
},
check(input) {
return service.checkForAppUpdate({
currentVersion: version,
releaseChannel: input?.releaseChannel ?? "stable",
intent: input?.intent ?? "automatic",
});
},
async stage(release) {
app.publish(release);
const found = await app.check();
expect(found).toMatchObject({ hasUpdate: true, latestVersion: release.version });
runtime.finishUpdateDownload(release);
},
quit() {
return service.installUpdateOnQuit({
currentVersion: version,
releaseChannel: "stable",
signal: new AbortController().signal,
});
},
};
return app;
}
interface Install {
now(): number;
advance(ms: number): void;
setClock(time: number): void;
/** Starts the app again, as a new process would, on the given version. */
launch(
version: string,
options?: {
bucket?: (version: string) => Promise<number>;
updateMode?: () => DesktopUpdateMode;
},
): Promise<RunningApp>;
}
async function createInstall(): Promise<Install> {
const userData = await mkdtemp(path.join(os.tmpdir(), "paseo-update-service-"));
tempDirs.push(userData);
let now = START;
return {
now: () => now,
advance(ms) {
now += ms;
},
setClock(time) {
now = time;
},
async launch(version, options) {
const pacing = createAppUpdatePacing({
filePath: () => path.join(userData, "app-update-pacing.json"),
currentVersion: () => version,
now: () => now,
});
await pacing.start();
return startApp(version, { ...options, now: () => now, pacing });
},
};
}
const noUpdate = {
hasUpdate: false,
readyToInstall: false,
downloading: false,
errorMessage: null,
};
describe("automatic check interval", () => {
it("asks the release feed once per six hours", async () => {
const install = await createInstall();
const app = await install.launch("1.2.3");
app.publish(pacedRelease("1.2.3"));
app.publish(pacedRelease("1.2.3"));
expect(await app.check()).toMatchObject(noUpdate);
expect(app.runtime.checkCount).toBe(1);
install.advance(AUTOMATIC_CHECK_INTERVAL_MS - 1);
expect(await app.check()).toMatchObject(noUpdate);
expect(app.runtime.checkCount).toBe(1);
install.advance(1);
expect(await app.check()).toMatchObject(noUpdate);
expect(app.runtime.checkCount).toBe(2);
});
it("keeps the interval across a restart", async () => {
const install = await createInstall();
const firstRun = await install.launch("1.2.3");
firstRun.publish(pacedRelease("1.2.3"));
await firstRun.check();
install.advance(HOUR_MS);
const secondRun = await install.launch("1.2.3");
secondRun.publish(pacedRelease("1.2.3"));
expect(await secondRun.check()).toMatchObject(noUpdate);
expect(secondRun.runtime.checkCount).toBe(0);
install.advance(5 * HOUR_MS);
await secondRun.check();
expect(secondRun.runtime.checkCount).toBe(1);
});
it("checks again right after a failed check", async () => {
const install = await createInstall();
const app = await install.launch("1.2.3");
app.runtime.failNextCheck(new Error("net::ERR_INTERNET_DISCONNECTED"));
app.runtime.failNextCheck(new Error("502 Bad Gateway"));
app.publish(pacedRelease("1.2.4"));
expect((await app.check()).errorMessage).toBe("net::ERR_INTERNET_DISCONNECTED");
expect((await app.check()).errorMessage).toBe("502 Bad Gateway");
expect(await app.check()).toMatchObject({ hasUpdate: true, latestVersion: "1.2.4" });
expect(app.runtime.checkCount).toBe(3);
});
it("checks again right after the release feed could not be read", async () => {
const install = await createInstall();
const app = await install.launch("1.2.3");
app.runtime.nextCheck(null);
app.publish(pacedRelease("1.2.4"));
expect(await app.check()).toMatchObject(noUpdate);
expect(await app.check()).toMatchObject({ hasUpdate: true, latestVersion: "1.2.4" });
expect(app.runtime.checkCount).toBe(2);
});
it("checks again when the clock moved back", async () => {
const install = await createInstall();
const app = await install.launch("1.2.3");
app.publish(pacedRelease("1.2.3"));
await app.check();
install.setClock(START - 30 * 24 * HOUR_MS);
app.publish(pacedRelease("1.2.4"));
expect(await app.check()).toMatchObject({ hasUpdate: true, latestVersion: "1.2.4" });
});
it("always runs a manual check", async () => {
const install = await createInstall();
const app = await install.launch("1.2.3");
app.publish(pacedRelease("1.2.3"));
await app.check();
app.publish(pacedRelease("1.2.4"));
expect(await app.check({ intent: "manual" })).toMatchObject({
hasUpdate: true,
latestVersion: "1.2.4",
});
app.publish(pacedRelease("1.2.5"));
expect(await app.check({ intent: "manual" })).toMatchObject({
hasUpdate: true,
latestVersion: "1.2.5",
});
expect(app.runtime.checkCount).toBe(3);
});
it("does not let a manual check delay the next automatic check", async () => {
const install = await createInstall();
const app = await install.launch("1.2.3");
app.publish(pacedRelease("1.2.3"));
await app.check({ intent: "manual" });
app.publish(pacedRelease("1.2.4"));
expect(await app.check()).toMatchObject({ hasUpdate: true, latestVersion: "1.2.4" });
});
it("revalidates a staged update at quit inside the interval", async () => {
const install = await createInstall();
const app = await install.launch("1.2.3");
await app.stage(pacedRelease("1.2.4"));
// The release was halted: the feed points back at the running version.
install.advance(HOUR_MS);
app.publish(pacedRelease("1.2.3"));
expect(await app.quit()).toBe(false);
expect(app.runtime.checkCount).toBe(2);
expect(app.runtime.installedVersions).toEqual([]);
});
it("installs a staged update at quit inside the interval", async () => {
const install = await createInstall();
const app = await install.launch("1.2.3");
await app.stage(pacedRelease("1.2.4"));
install.advance(HOUR_MS);
app.publish(pacedRelease("1.2.4"));
expect(await app.quit()).toBe(true);
expect(app.runtime.installedVersions).toEqual(["1.2.4"]);
});
it("makes no request while updates are off, then checks as soon as they are on", async () => {
let mode: DesktopUpdateMode = "off";
const install = await createInstall();
const app = await install.launch("1.2.3", { updateMode: () => mode });
app.publish(pacedRelease("1.2.4"));
expect(await app.check()).toMatchObject(noUpdate);
expect(app.runtime.checkCount).toBe(0);
mode = "automatic";
expect(await app.check()).toMatchObject({ hasUpdate: true, latestVersion: "1.2.4" });
expect(app.runtime.checkCount).toBe(1);
});
it("does not space out checks on the beta channel", async () => {
const install = await createInstall();
const app = await install.launch("1.3.0-beta.1");
app.publish(pacedRelease("1.3.0-beta.1"));
app.publish(pacedRelease("1.3.0-beta.2"));
await app.check({ releaseChannel: "beta" });
expect(await app.check({ releaseChannel: "beta" })).toMatchObject({
hasUpdate: true,
latestVersion: "1.3.0-beta.2",
});
expect(app.runtime.checkCount).toBe(2);
});
it("checks at once after the release channel changes", async () => {
const install = await createInstall();
const app = await install.launch("1.2.3");
app.publish(pacedRelease("1.2.3"));
await app.check();
app.publish(pacedRelease("1.3.0-beta.1"));
expect(await app.check({ releaseChannel: "beta" })).toMatchObject({
hasUpdate: true,
latestVersion: "1.3.0-beta.1",
});
app.publish(pacedRelease("1.2.3"));
expect(await app.check()).toMatchObject(noUpdate);
expect(app.runtime.checkCount).toBe(3);
await app.check();
expect(app.runtime.checkCount).toBe(3);
});
it("reports an update being downloaded, then ready, without asking the feed again", async () => {
const install = await createInstall();
const app = await install.launch("1.2.3");
const release = pacedRelease("1.2.4");
app.publish(release);
expect(await app.check()).toMatchObject({ hasUpdate: true, downloading: true });
expect(await app.check()).toMatchObject({
hasUpdate: true,
readyToInstall: false,
downloading: true,
latestVersion: "1.2.4",
date: "2026-04-20T00:00:00.000Z",
});
app.runtime.finishUpdateDownload(release);
expect(await app.check()).toMatchObject({
hasUpdate: true,
readyToInstall: true,
downloading: false,
latestVersion: "1.2.4",
});
expect(app.runtime.checkCount).toBe(1);
});
it("retries a failed download at the next automatic check", async () => {
const install = await createInstall();
const app = await install.launch("1.2.3");
const release = pacedRelease("1.2.4");
app.publish(release);
await app.check();
app.runtime.failRuntime(new Error("ECONNRESET"));
app.publish(release);
await app.check();
expect(app.runtime.checkCount).toBe(2);
});
it("keeps offering a found update in notify mode, and downloads it once automatic is chosen", async () => {
let mode: DesktopUpdateMode = "notify";
const install = await createInstall();
const app = await install.launch("1.2.3", { updateMode: () => mode });
const release = pacedRelease("1.2.4");
app.publish(release);
expect(await app.check()).toMatchObject({ hasUpdate: true, downloading: false });
expect(await app.check()).toMatchObject({
hasUpdate: true,
downloading: false,
latestVersion: "1.2.4",
});
expect(app.runtime.checkCount).toBe(1);
mode = "automatic";
app.publish(release);
expect(await app.check()).toMatchObject({ hasUpdate: true, downloading: true });
expect(app.runtime.checkCount).toBe(2);
});
});
describe("update cooldown", () => {
async function launchRightAfterUpdating(options?: {
updateMode?: () => DesktopUpdateMode;
}): Promise<{ install: Install; app: RunningApp }> {
const install = await createInstall();
await install.launch("1.2.3");
const app = await install.launch("1.2.4", options);
return { install, app };
}
it("defers a paced release for 72 hours after the app updated", async () => {
const { install, app } = await launchRightAfterUpdating();
app.publish(pacedRelease("1.2.5"));
expect(await app.check()).toMatchObject(noUpdate);
install.advance(UPDATE_COOLDOWN_MS - 1);
app.publish(pacedRelease("1.2.5"));
expect(await app.check()).toMatchObject(noUpdate);
install.advance(AUTOMATIC_CHECK_INTERVAL_MS);
app.publish(pacedRelease("1.2.5"));
expect(await app.check()).toMatchObject({
hasUpdate: true,
downloading: true,
latestVersion: "1.2.5",
});
});
it("does not defer on the first launch that keeps pacing state", async () => {
const install = await createInstall();
const app = await install.launch("1.2.4");
app.publish(pacedRelease("1.2.5"));
expect(await app.check()).toMatchObject({ hasUpdate: true, latestVersion: "1.2.5" });
});
it("finds a paced release with a manual check during the cooldown", async () => {
const { app } = await launchRightAfterUpdating();
app.publish(pacedRelease("1.2.5"));
expect(await app.check({ intent: "manual" })).toMatchObject({
hasUpdate: true,
latestVersion: "1.2.5",
});
});
it("delivers an emergency release during the cooldown", async () => {
const { app } = await launchRightAfterUpdating();
app.publish(emergencyRelease("1.2.5"));
expect(await app.check()).toMatchObject({
hasUpdate: true,
downloading: true,
latestVersion: "1.2.5",
});
});
it("delivers a release that has no rollout window during the cooldown", async () => {
const { app } = await launchRightAfterUpdating();
app.publish({ version: "1.2.5" });
expect(await app.check()).toMatchObject({ hasUpdate: true, latestVersion: "1.2.5" });
});
it("does not defer the beta channel", async () => {
const { app } = await launchRightAfterUpdating();
app.publish(pacedRelease("1.3.0-beta.1"));
expect(await app.check({ releaseChannel: "beta" })).toMatchObject({
hasUpdate: true,
latestVersion: "1.3.0-beta.1",
});
});
it("defers the notify-mode prompt the same way", async () => {
const { install, app } = await launchRightAfterUpdating({ updateMode: () => "notify" });
app.publish(pacedRelease("1.2.5"));
expect(await app.check()).toMatchObject(noUpdate);
install.advance(UPDATE_COOLDOWN_MS);
app.publish(pacedRelease("1.2.5"));
expect(await app.check()).toMatchObject({
hasUpdate: true,
downloading: false,
latestVersion: "1.2.5",
});
});
it("installs at quit an update the user asked for during the cooldown", async () => {
const { app } = await launchRightAfterUpdating();
const release = pacedRelease("1.2.5");
app.publish(release);
await app.check({ intent: "manual" });
app.runtime.finishUpdateDownload(release);
app.publish(release);
expect(await app.quit()).toBe(true);
expect(app.runtime.installedVersions).toEqual(["1.2.5"]);
});
});
describe("staged update", () => {
it("is kept when the next paced release ships", async () => {
const app = startApp("1.2.3");
await app.stage(pacedRelease("1.2.4"));
app.publish(pacedRelease("1.2.5"));
expect(await app.check()).toMatchObject({
hasUpdate: true,
readyToInstall: true,
downloading: false,
latestVersion: "1.2.4",
});
expect(app.runtime.checkCount).toBe(2);
app.publish(pacedRelease("1.2.5"));
expect(await app.quit()).toBe(true);
expect(app.runtime.installedVersions).toEqual(["1.2.4"]);
expect(app.runtime.requestedDownloadVersions).toEqual([]);
});
it("is installed at quit when the next paced release shipped since the last check", async () => {
const app = startApp("1.2.3");
await app.stage(pacedRelease("1.2.4"));
app.publish(pacedRelease("1.2.5"));
expect(await app.quit()).toBe(true);
expect(app.runtime.installedVersions).toEqual(["1.2.4"]);
});
it("is kept through a run of paced releases seen one after the other", async () => {
const app = startApp("1.2.3");
await app.stage(pacedRelease("1.2.4"));
for (const next of ["1.2.5", "1.2.6", "1.2.7"]) {
app.publish(pacedRelease(next));
expect(await app.check()).toMatchObject({ readyToInstall: true, latestVersion: "1.2.4" });
}
app.publish(pacedRelease("1.2.7"));
expect(await app.quit()).toBe(true);
expect(app.runtime.installedVersions).toEqual(["1.2.4"]);
});
it("is dropped when a release was missed and the newest one is not admitted yet", async () => {
const app = startApp("1.2.3", { bucket: async (version) => (version === "1.2.4" ? 0 : 0.99) });
await app.stage(pacedRelease("1.2.4"));
app.publish(pacedRelease("1.2.5"));
await app.check();
// 1.2.6 was never seen. It may have been the fix for a bad 1.2.4.
app.publish(newPacedRelease("1.2.7", START));
expect(await app.check()).toMatchObject(noUpdate);
app.publish(newPacedRelease("1.2.7", START));
expect(await app.quit()).toBe(false);
expect(app.runtime.installedVersions).toEqual([]);
});
it("is replaced when a release was missed and the newest one is admitted", async () => {
const app = startApp("1.2.3");
await app.stage(pacedRelease("1.2.4"));
app.publish(pacedRelease("1.2.6"));
expect(await app.check()).toMatchObject({
hasUpdate: true,
readyToInstall: false,
downloading: true,
latestVersion: "1.2.6",
});
});
it("is not held against a minor release, which may follow a patch this install never saw", async () => {
const app = startApp("1.2.3", { bucket: async (version) => (version === "1.2.4" ? 0 : 0.99) });
await app.stage(pacedRelease("1.2.4"));
// 1.2.5 may have shipped as the fix for a bad 1.2.4 before 1.3.0.
app.publish(newPacedRelease("1.3.0", START));
expect(await app.check()).toMatchObject(noUpdate);
app.publish(newPacedRelease("1.3.0", START));
expect(await app.quit()).toBe(false);
expect(app.runtime.installedVersions).toEqual([]);
});
it("does not hold a download that finished after a newer release was admitted", async () => {
const app = startApp("1.2.3");
const first = pacedRelease("1.2.4");
const second = pacedRelease("1.2.5");
app.publish(first);
await app.check();
app.publish(second);
await app.check();
app.runtime.finishUpdateDownload(first);
app.publish(second);
expect(await app.check()).toMatchObject({
hasUpdate: true,
readyToInstall: false,
latestVersion: "1.2.5",
});
app.publish(second);
expect(await app.quit()).toBe(true);
expect(app.runtime.installedVersions).toEqual(["1.2.5"]);
});
it("is replaced by an emergency release", async () => {
const app = startApp("1.2.3");
await app.stage(pacedRelease("1.2.4"));
const hotfix = emergencyRelease("1.2.5");
app.publish(hotfix);
expect(await app.check()).toMatchObject({
hasUpdate: true,
readyToInstall: false,
downloading: true,
latestVersion: "1.2.5",
});
app.runtime.finishUpdateDownload(hotfix);
app.publish(hotfix);
expect(await app.quit()).toBe(true);
expect(app.runtime.installedVersions).toEqual(["1.2.5"]);
});
it("is dropped when the emergency release that follows it cannot be installed on this system", async () => {
const app = startApp("1.2.3");
await app.stage(pacedRelease("1.2.4"));
// The updater refuses a release whose minimum system version is too new.
app.runtime.nextCheck({ isUpdateAvailable: false, updateInfo: emergencyRelease("1.2.5") });
expect(await app.check()).toMatchObject(noUpdate);
expect(await app.quit()).toBe(false);
});
it("is replaced by an emergency release first seen at quit", async () => {
const app = startApp("1.2.3");
await app.stage(pacedRelease("1.2.4"));
app.publish(emergencyRelease("1.2.5"));
expect(await app.quit()).toBe(true);
expect(app.runtime.installedVersions).toEqual(["1.2.5"]);
});
it("is replaced when the release it was held against becomes an emergency release", async () => {
const app = startApp("1.2.3");
await app.stage(pacedRelease("1.2.4"));
app.publish(pacedRelease("1.2.5"));
await app.check();
app.publish(emergencyRelease("1.2.5"));
expect(await app.check()).toMatchObject({
hasUpdate: true,
readyToInstall: false,
latestVersion: "1.2.5",
});
});
it("is replaced by a manual check that finds the next release", async () => {
const app = startApp("1.2.3");
await app.stage(pacedRelease("1.2.4"));
app.publish(pacedRelease("1.2.5"));
expect(await app.check({ intent: "manual" })).toMatchObject({
hasUpdate: true,
readyToInstall: false,
latestVersion: "1.2.5",
});
});
it("is dropped when its release is halted", async () => {
const app = startApp("1.2.3");
await app.stage(pacedRelease("1.2.4"));
app.publish(pacedRelease("1.2.3"));
expect(await app.check()).toMatchObject(noUpdate);
app.publish(pacedRelease("1.2.3"));
expect(await app.quit()).toBe(false);
expect(app.runtime.installedVersions).toEqual([]);
});
it("is kept when the release it was held against is halted", async () => {
const app = startApp("1.2.3");
const release = pacedRelease("1.2.4");
await app.stage(release);
app.publish(pacedRelease("1.2.5"));
await app.check();
app.publish(release);
expect(await app.check()).toMatchObject({ readyToInstall: true, latestVersion: "1.2.4" });
app.publish(release);
expect(await app.quit()).toBe(true);
expect(app.runtime.installedVersions).toEqual(["1.2.4"]);
});
});
describe("rollout admission", () => {
it("places the install on each release's own rollout", async () => {
const bucket = async (version: string) => (version === "1.2.4" ? 0 : 0.99);
const first = startApp("1.2.3", { bucket });
first.publish(newPacedRelease("1.2.4", START));
expect(await first.check()).toMatchObject({ hasUpdate: true, latestVersion: "1.2.4" });
const second = startApp("1.2.3", { bucket });
second.publish(newPacedRelease("1.2.5", START));
expect(await second.check()).toMatchObject(noUpdate);
});
it("admits a paced release when the install's rollout position cannot be read", async () => {
const app = startApp("1.2.3", {
bucket: async () => {
throw new Error("EACCES: permission denied, open '.updaterId'");
},
});
app.publish(newPacedRelease("1.2.4", START));
expect(await app.check()).toMatchObject({
hasUpdate: true,
latestVersion: "1.2.4",
errorMessage: null,
});
});
it("runs a manual check without the install's rollout position", async () => {
const app = startApp("1.2.3", {
bucket: async () => {
throw new Error("EACCES: permission denied, open '.updaterId'");
},
});
app.publish(newPacedRelease("1.2.4", START));
expect(await app.check({ intent: "manual" })).toMatchObject({
hasUpdate: true,
latestVersion: "1.2.4",
errorMessage: null,
});
});
});
@@ -1,13 +1,10 @@
import type { DesktopUpdateMode } from "../settings/desktop-settings.js";
import type { AppUpdatePacing } from "./app-update-pacing.js";
import {
isPacedRelease,
rolloutManifestSchema,
shouldAdmitAppUpdate,
type AppReleaseChannel,
type AppUpdateCheckIntent,
} from "./app-update-rollout.js";
import { isNextPatchRelease } from "./app-update-version.js";
export interface AppUpdateDownloadProgress {
version: string | null;
@@ -110,14 +107,11 @@ export interface AppUpdateServiceDeps {
runtime: AppUpdateRuntime;
isPackaged(): boolean;
now(): number;
/** Position of this install in the rollout of `version`, in [0, 1). */
bucket(version: string): Promise<number>;
pacing: AppUpdatePacing;
bucket(): Promise<number>;
updateMode?: () => DesktopUpdateMode | Promise<DesktopUpdateMode>;
onDownloadProgress?(progress: AppUpdateDownloadProgress | null): void;
reportSettingsError?(error: unknown): void;
reportCheckError?(error: unknown): void;
reportAdmissionError?(error: unknown): void;
reportRuntimeError?(error: unknown): void;
reportInstallError?(message: string): void;
}
@@ -195,9 +189,6 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
let configuredReleaseChannel: AppReleaseChannel | null = null;
let preparationError: { version: string; message: string } | null = null;
let preparingUpdateVersion: string | null = null;
// The newest release seen in an unbroken run of paced releases since the
// staged update became ready. Null whenever nothing is staged.
let stagedChainHead: string | null = null;
let currentAutoDownload = true;
let checkQueue: Promise<void> = Promise.resolve();
@@ -205,24 +196,21 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
return downloadedUpdateVersion === version;
}
function setStagedUpdate(version: string | null): void {
downloadedUpdateVersion = version;
stagedChainHead = version;
}
function clearUpdateState(): void {
cachedUpdateInfo = null;
setStagedUpdate(null);
downloadedUpdateVersion = null;
preparationError = null;
preparingUpdateVersion = null;
deps.onDownloadProgress?.(null);
}
/** What is already known about an update, without asking the release feed. */
function buildKnownUpdateResult(currentVersion: string): AppUpdateCheckResult {
function buildPreviouslyAdmittedUpdateResult(
currentVersion: string,
checkedInfo: RuntimeUpdateInfo,
): AppUpdateCheckResult | null {
const info = cachedUpdateInfo;
if (!info || info.version === currentVersion) {
return buildCheckResult({ currentVersion, hasUpdate: false, readyToInstall: false });
if (!info || info.version === currentVersion || info.version !== checkedInfo.version) {
return null;
}
const readyToInstall = isReadyToInstallVersion(info.version);
@@ -236,78 +224,6 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
});
}
function buildPreviouslyAdmittedUpdateResult(
currentVersion: string,
checkedInfo: RuntimeUpdateInfo,
): AppUpdateCheckResult | null {
const info = cachedUpdateInfo;
if (!info || info.version === currentVersion || info.version !== checkedInfo.version) {
return null;
}
return buildKnownUpdateResult(currentVersion);
}
/**
* A staged update is not replaced by the paced release that follows it, so
* an install that is slow to restart does not download every release. The
* hold covers only a run of paced releases seen one after the other: a gap
* means a release was missed, and the missed one may have been the fix for
* the staged one. Emergency releases and manual checks always replace it.
*/
function stagedUpdateHoldsAgainst(
info: RuntimeUpdateInfo,
releaseChannel: AppReleaseChannel,
): boolean {
const staged = downloadedUpdateVersion;
if (staged === null || stagedChainHead === null) return false;
if (cachedUpdateInfo?.version !== staged || info.version === staged) return false;
const { rolloutHours } = rolloutManifestSchema.parse(info);
if (!isPacedRelease({ channel: releaseChannel, rolloutHours })) return false;
return info.version === stagedChainHead || isNextPatchRelease(stagedChainHead, info.version);
}
/**
* Whether an automatic check may take this release now. Any failure to
* decide admits the release: an install is never refused an update because
* its own rollout state could not be read.
*/
async function admitsAutomatically(
info: RuntimeUpdateInfo,
releaseChannel: AppReleaseChannel,
): Promise<boolean> {
try {
const { rolloutHours, releaseDate } = rolloutManifestSchema.parse(info);
if (!isPacedRelease({ channel: releaseChannel, rolloutHours })) return true;
if (stagedUpdateHoldsAgainst(info, releaseChannel)) return false;
if (await deps.pacing.isInUpdateCooldown()) return false;
return shouldAdmitAppUpdate({
channel: releaseChannel,
intent: "automatic",
rolloutHours,
releaseDate,
now: deps.now(),
bucket: await deps.bucket(info.version),
});
} catch (error) {
deps.reportAdmissionError?.(error);
return true;
}
}
/** An admitted update that is neither downloaded nor downloading. */
function hasUnpreparedUpdate(currentVersion: string): boolean {
const info = cachedUpdateInfo;
return (
info !== null &&
info.version !== currentVersion &&
!isReadyToInstallVersion(info.version) &&
preparingUpdateVersion !== info.version
);
}
async function resolveUpdateMode(): Promise<DesktopUpdateMode> {
if (!deps.updateMode) {
return "automatic";
@@ -340,15 +256,20 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
releaseChannel,
autoDownload: initialAutoDownload,
shouldAdmitUpdate: async (info) => {
// A manual check needs no rollout or pacing state, so nothing that
// breaks that state can stop the user from updating by hand.
const admitted = intent === "manual" || (await admitsAutomatically(info, releaseChannel));
// Read the mode after every other await, so a mode saved during the
// check is the one that decides.
const parsed = rolloutManifestSchema.parse(info);
const bucket = await deps.bucket();
const liveMode = await resolveUpdateMode();
if (intent === "automatic" && liveMode === "off") {
return false;
}
const admitted = shouldAdmitAppUpdate({
channel: releaseChannel,
intent,
rolloutHours: parsed.rolloutHours,
releaseDate: parsed.releaseDate,
now: deps.now(),
bucket,
});
if (admitted) {
currentAutoDownload = resolveAutoDownload(liveMode, autoDownloadOverride);
deps.runtime.setAutoDownload?.(currentAutoDownload);
@@ -358,7 +279,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
onUpdateAvailable(info) {
const alreadyReady = downloadedUpdateVersion === info.version;
cachedUpdateInfo = info;
if (!alreadyReady) setStagedUpdate(null);
downloadedUpdateVersion = alreadyReady ? info.version : null;
if (!alreadyReady && currentAutoDownload && preparingUpdateVersion === null) {
preparingUpdateVersion = info.version;
}
@@ -379,7 +300,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
// A superseded download can finish after a newer manifest check. Keep
// the validated manifest as the install target in that case.
cachedUpdateInfo ??= info;
setStagedUpdate(info.version);
downloadedUpdateVersion = info.version;
if (preparingUpdateVersion === info.version) {
preparingUpdateVersion = null;
}
@@ -453,68 +374,17 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
});
}
/**
* The release feed answered with a release this check may not take. An
* update admitted earlier survives only when the feed still names it, or
* when it is staged and holds against the release the feed names now.
*/
function resolveUnavailableUpdateResult(
check: {
currentVersion: string;
releaseChannel: AppReleaseChannel;
intent: AppUpdateCheckIntent;
},
info: RuntimeUpdateInfo,
): AppUpdateCheckResult {
const admittedUpdate = buildPreviouslyAdmittedUpdateResult(check.currentVersion, info);
if (admittedUpdate) {
return admittedUpdate;
}
if (check.intent === "automatic" && stagedUpdateHoldsAgainst(info, check.releaseChannel)) {
stagedChainHead = info.version;
return buildKnownUpdateResult(check.currentVersion);
}
clearUpdateState();
return buildCheckResult({
currentVersion: check.currentVersion,
hasUpdate: false,
readyToInstall: false,
});
}
/**
* Reasons to ask the release feed before the next check is due: a change of
* channel makes the known update stale, and an update that should be
* downloading but is not needs the check to start it again.
*/
function mustCheckNow(
currentVersion: string,
releaseChannel: AppReleaseChannel,
autoDownload: boolean,
): boolean {
const channelChanged =
configuredReleaseChannel !== null && configuredReleaseChannel !== releaseChannel;
return channelChanged || (autoDownload && hasUnpreparedUpdate(currentVersion));
}
interface UpdateCheckInput {
async function checkForAppUpdate({
currentVersion,
releaseChannel,
intent,
autoDownload,
}: {
currentVersion: string;
releaseChannel: AppReleaseChannel;
intent: AppUpdateCheckIntent;
autoDownload?: boolean;
}
/**
* `spaced` checks are the background ones the app makes on its own. On the
* stable channel they ask the release feed at most once per pacing interval
* and answer from what is already known in between.
*/
async function runUpdateCheck(
{ currentVersion, releaseChannel, intent, autoDownload }: UpdateCheckInput,
{ spaced }: { spaced: boolean },
): Promise<AppUpdateCheckResult> {
}): Promise<AppUpdateCheckResult> {
if (!deps.isPackaged()) {
return buildCheckResult({
currentVersion,
@@ -524,9 +394,6 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
}
return runCheckExclusively(async () => {
const respectsInterval = spaced && intent === "automatic" && releaseChannel === "stable";
const checkIsDue = respectsInterval ? await deps.pacing.isAutomaticCheckDue() : true;
const mode = deps.updateMode ? await resolveUpdateMode() : "automatic";
if (intent === "automatic" && mode === "off") {
return buildCheckResult({
@@ -535,25 +402,18 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
readyToInstall: false,
});
}
const initialAutoDownload = resolveAutoDownload(mode, autoDownload);
if (!checkIsDue && !mustCheckNow(currentVersion, releaseChannel, initialAutoDownload)) {
return buildKnownUpdateResult(currentVersion);
}
if (intent === "manual") {
preparationError = null;
}
configureRuntime(releaseChannel, intent, initialAutoDownload, autoDownload);
configureRuntime(
releaseChannel,
intent,
resolveAutoDownload(mode, autoDownload),
autoDownload,
);
try {
const result = await deps.runtime.checkForUpdates();
// Only a check that read the release feed counts. A failed check
// throws, and an unreadable feed answers null: both run again at the
// next opportunity.
if (respectsInterval && result) {
await deps.pacing.recordAutomaticCheck();
}
if (intent === "automatic" && deps.updateMode && (await resolveUpdateMode()) === "off") {
return buildCheckResult({
currentVersion,
@@ -571,10 +431,20 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
}
if (!result.isUpdateAvailable) {
return resolveUnavailableUpdateResult(
{ currentVersion, releaseChannel, intent },
const admittedUpdate = buildPreviouslyAdmittedUpdateResult(
currentVersion,
result.updateInfo,
);
if (admittedUpdate) {
return admittedUpdate;
}
clearUpdateState();
return buildCheckResult({
currentVersion,
hasUpdate: false,
readyToInstall: false,
});
}
return resolveAvailableUpdateResult(currentVersion, result.updateInfo);
@@ -590,10 +460,6 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
});
}
function checkForAppUpdate(input: UpdateCheckInput): Promise<AppUpdateCheckResult> {
return runUpdateCheck(input, { spaced: true });
}
async function downloadAndInstallUpdate(
{
currentVersion,
@@ -612,10 +478,12 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
};
}
const check = await runUpdateCheck(
{ currentVersion, releaseChannel, intent: "manual", autoDownload: false },
{ spaced: false },
);
const check = await checkForAppUpdate({
currentVersion,
releaseChannel,
intent: "manual",
autoDownload: false,
});
if (!check.hasUpdate) {
return {
installed: false,
@@ -674,7 +542,7 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
// event clears that version, then the next iteration starts the newly
// validated release instead of treating the stale artifact as ready.
if (attemptedVersion === readyVersion && !isReadyToInstallVersion(readyVersion)) {
setStagedUpdate(readyVersion);
downloadedUpdateVersion = readyVersion;
clearPreparingVersion(readyVersion);
} else if (preparingUpdateVersion === attemptedVersion) {
clearPreparingVersion(attemptedVersion);
@@ -763,12 +631,11 @@ export function createAppUpdateService(deps: AppUpdateServiceDeps): AppUpdateSer
return false;
}
// The staged update is validated against the release feed before every
// install, however recently the app last checked.
const check = await runUpdateCheck(
{ currentVersion, releaseChannel, intent: "automatic" },
{ spaced: false },
);
const check = await checkForAppUpdate({
currentVersion,
releaseChannel,
intent: "automatic",
});
if (signal.aborted || !check.hasUpdate) {
return false;
}
@@ -1,69 +0,0 @@
import { describe, expect, it } from "vitest";
import { isNewerVersion, isNextPatchRelease } from "./app-update-version";
describe("isNewerVersion", () => {
it("orders releases by major, minor, then patch", () => {
expect(isNewerVersion("0.17.5", "0.17.4")).toBe(true);
expect(isNewerVersion("0.18.0", "0.17.9")).toBe(true);
expect(isNewerVersion("1.0.0", "0.99.99")).toBe(true);
expect(isNewerVersion("0.17.10", "0.17.9")).toBe(true);
});
it("does not call the same or an older version newer", () => {
expect(isNewerVersion("0.17.4", "0.17.4")).toBe(false);
expect(isNewerVersion("0.17.3", "0.17.4")).toBe(false);
expect(isNewerVersion("0.16.9", "0.17.0")).toBe(false);
});
it("orders a release after its own prereleases", () => {
expect(isNewerVersion("0.17.0", "0.17.0-beta.2")).toBe(true);
expect(isNewerVersion("0.17.0-beta.2", "0.17.0")).toBe(false);
expect(isNewerVersion("0.17.0-beta.2", "0.16.4")).toBe(true);
});
it("orders prereleases numerically, not as text", () => {
expect(isNewerVersion("0.17.0-beta.10", "0.17.0-beta.9")).toBe(true);
expect(isNewerVersion("0.17.0-beta.2", "0.17.0-beta.2")).toBe(false);
expect(isNewerVersion("0.17.0-beta.1", "0.17.0-alpha.5")).toBe(true);
expect(isNewerVersion("0.17.0-beta.1.1", "0.17.0-beta.1")).toBe(true);
});
it("ignores a leading v and build metadata", () => {
expect(isNewerVersion("v0.17.5", "0.17.4")).toBe(true);
expect(isNewerVersion("0.17.5+build.7", "0.17.5")).toBe(false);
});
it("never calls a version newer when either side is not a version", () => {
expect(isNewerVersion("0.17.5", "")).toBe(false);
expect(isNewerVersion("0.17.5", "latest")).toBe(false);
expect(isNewerVersion("nightly", "0.17.4")).toBe(false);
expect(isNewerVersion("0.17", "0.16.0")).toBe(false);
expect(isNewerVersion("0.17.5.1", "0.17.4")).toBe(false);
});
});
describe("isNextPatchRelease", () => {
it("accepts only the patch release that directly follows", () => {
expect(isNextPatchRelease("0.17.4", "0.17.5")).toBe(true);
expect(isNextPatchRelease("0.17.9", "0.17.10")).toBe(true);
});
it("rejects a skipped release, the same release, and an older release", () => {
expect(isNextPatchRelease("0.17.4", "0.17.6")).toBe(false);
expect(isNextPatchRelease("0.17.4", "0.17.4")).toBe(false);
expect(isNextPatchRelease("0.17.4", "0.17.3")).toBe(false);
});
it("rejects a minor or major bump", () => {
expect(isNextPatchRelease("0.17.4", "0.18.0")).toBe(false);
expect(isNextPatchRelease("0.17.4", "1.17.5")).toBe(false);
});
it("rejects prereleases and anything that is not a version", () => {
expect(isNextPatchRelease("0.17.4", "0.17.5-beta.1")).toBe(false);
expect(isNextPatchRelease("0.17.4-beta.1", "0.17.5")).toBe(false);
expect(isNextPatchRelease("0.17.4", "next")).toBe(false);
expect(isNextPatchRelease("", "0.17.5")).toBe(false);
});
});
@@ -1,67 +0,0 @@
interface ParsedVersion {
core: [number, number, number];
prerelease: string[];
}
const VERSION_PATTERN = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
const NUMERIC_IDENTIFIER = /^\d+$/;
function parseVersion(version: string): ParsedVersion | null {
const match = VERSION_PATTERN.exec(version.trim());
if (!match) return null;
return {
core: [Number(match[1]), Number(match[2]), Number(match[3])],
prerelease: match[4] ? match[4].split(".") : [],
};
}
function comparePrereleaseIdentifier(left: string, right: string): number {
const leftNumeric = NUMERIC_IDENTIFIER.test(left);
const rightNumeric = NUMERIC_IDENTIFIER.test(right);
if (leftNumeric && rightNumeric) return Number(left) - Number(right);
if (leftNumeric) return -1;
if (rightNumeric) return 1;
if (left === right) return 0;
return left < right ? -1 : 1;
}
function comparePrerelease(left: string[], right: string[]): number {
// A release sorts after its own prereleases.
if (left.length === 0 || right.length === 0) return right.length - left.length;
for (let index = 0; index < Math.min(left.length, right.length); index += 1) {
const order = comparePrereleaseIdentifier(left[index], right[index]);
if (order !== 0) return order;
}
return left.length - right.length;
}
function compareVersions(left: ParsedVersion, right: ParsedVersion): number {
for (let index = 0; index < left.core.length; index += 1) {
const order = left.core[index] - right.core[index];
if (order !== 0) return order;
}
return comparePrerelease(left.prerelease, right.prerelease);
}
/** False when either side is not a version, so an unknown version never counts as an update. */
export function isNewerVersion(candidate: string, baseline: string): boolean {
const parsedCandidate = parseVersion(candidate);
const parsedBaseline = parseVersion(baseline);
if (!parsedCandidate || !parsedBaseline) return false;
return compareVersions(parsedCandidate, parsedBaseline) > 0;
}
/** True only for the release that directly follows `previous` on the same minor line. */
export function isNextPatchRelease(previous: string, next: string): boolean {
const parsedPrevious = parseVersion(previous);
const parsedNext = parseVersion(next);
if (!parsedPrevious || !parsedNext) return false;
if (parsedPrevious.prerelease.length > 0 || parsedNext.prerelease.length > 0) return false;
const [previousMajor, previousMinor, previousPatch] = parsedPrevious.core;
const [nextMajor, nextMinor, nextPatch] = parsedNext.core;
return (
nextMajor === previousMajor && nextMinor === previousMinor && nextPatch === previousPatch + 1
);
}
@@ -47,7 +47,6 @@ const { autoUpdaterMock, getAllWindowsMock, desktopSettingsMock } = vi.hoisted((
vi.mock("electron", () => ({
app: {
// No userData path: update pacing has no state file here, so it paces nothing.
getPath: vi.fn(),
isPackaged: true,
},
@@ -78,11 +77,14 @@ vi.mock("electron-updater", () => ({
}));
import {
bucketFromStagingUserId,
checkForAppUpdate,
createAppUpdateLifecycleLogger,
downloadAndInstallUpdate,
resolveStagingUserId,
rolloutManifestSchema,
runElectronQuitAndInstall,
shouldAdmitToRollout,
shouldInstallAppUpdateOnQuit,
} from "./auto-updater";
@@ -434,7 +436,156 @@ describe("shouldInstallAppUpdateOnQuit", () => {
});
});
describe("resolveStagingUserId", () => {
describe("shouldAdmitToRollout", () => {
it("admits beta, missing rollout hours, zero-hour rollout, and missing release date", () => {
expect(
shouldAdmitToRollout({
channel: "beta",
rolloutHours: 24,
releaseDate: "2026-04-28T00:00:00.000Z",
now: Date.parse("2026-04-28T01:00:00.000Z"),
bucket: 0.99,
}),
).toBe(true);
expect(
shouldAdmitToRollout({
channel: "stable",
rolloutHours: undefined,
releaseDate: "2026-04-28T00:00:00.000Z",
now: Date.parse("2026-04-28T01:00:00.000Z"),
bucket: 0.99,
}),
).toBe(true);
expect(
shouldAdmitToRollout({
channel: "stable",
rolloutHours: 0,
releaseDate: "2026-04-28T00:00:00.000Z",
now: Date.parse("2026-04-28T01:00:00.000Z"),
bucket: 0.99,
}),
).toBe(true);
expect(
shouldAdmitToRollout({
channel: "stable",
rolloutHours: 24,
releaseDate: undefined,
now: Date.parse("2026-04-28T01:00:00.000Z"),
bucket: 0.99,
}),
).toBe(true);
});
it("blocks future releases and respects the linear threshold mid-rollout", () => {
expect(
shouldAdmitToRollout({
channel: "stable",
rolloutHours: 24,
releaseDate: "2026-04-28T02:00:00.000Z",
now: Date.parse("2026-04-28T01:00:00.000Z"),
bucket: 0,
}),
).toBe(false);
expect(
shouldAdmitToRollout({
channel: "stable",
rolloutHours: 24,
releaseDate: "2026-04-28T00:00:00.000Z",
now: Date.parse("2026-04-28T12:00:00.000Z"),
bucket: 0.49,
}),
).toBe(true);
expect(
shouldAdmitToRollout({
channel: "stable",
rolloutHours: 24,
releaseDate: "2026-04-28T00:00:00.000Z",
now: Date.parse("2026-04-28T12:00:00.000Z"),
bucket: 0.51,
}),
).toBe(false);
});
it("blocks the bucket-zero client at exact release time, admits as soon as time advances", () => {
expect(
shouldAdmitToRollout({
channel: "stable",
rolloutHours: 24,
releaseDate: "2026-04-28T00:00:00.000Z",
now: Date.parse("2026-04-28T00:00:00.000Z"),
bucket: 0,
}),
).toBe(false);
expect(
shouldAdmitToRollout({
channel: "stable",
rolloutHours: 24,
releaseDate: "2026-04-28T00:00:00.000Z",
now: Date.parse("2026-04-28T00:00:00.001Z"),
bucket: 0,
}),
).toBe(true);
});
it("admits the highest-bucket client at and past the rollout end", () => {
const maxBucket = (0x100000000 - 1) / 0x100000000;
expect(
shouldAdmitToRollout({
channel: "stable",
rolloutHours: 24,
releaseDate: "2026-04-28T00:00:00.000Z",
now: Date.parse("2026-04-29T00:00:00.000Z"),
bucket: maxBucket,
}),
).toBe(true);
expect(
shouldAdmitToRollout({
channel: "stable",
rolloutHours: 24,
releaseDate: "2026-04-28T00:00:00.000Z",
now: Date.parse("2027-04-28T00:00:00.000Z"),
bucket: maxBucket,
}),
).toBe(true);
});
it("admits when releaseDate is unparseable", () => {
expect(
shouldAdmitToRollout({
channel: "stable",
rolloutHours: 24,
releaseDate: "not a date",
now: Date.parse("2026-04-28T12:00:00.000Z"),
bucket: 0.99,
}),
).toBe(true);
});
it("treats garbage manifest rollout fields as missing and admits", () => {
const parsed = rolloutManifestSchema.parse({
rolloutHours: "not a number",
releaseDate: 12345,
});
expect(
shouldAdmitToRollout({
channel: "stable",
rolloutHours: parsed.rolloutHours,
releaseDate: parsed.releaseDate,
now: Date.parse("2026-04-28T12:00:00.000Z"),
bucket: 0.99,
}),
).toBe(true);
});
it("maps the maximum 32-bit slot to a bucket strictly less than 1", () => {
const allOnes = "ffffffff-ffff-ffff-ffff-ffffffffffff";
const allZeros = "00000000-0000-0000-0000-000000000000";
expect(bucketFromStagingUserId(allOnes)).toBeLessThan(1);
expect(bucketFromStagingUserId(allOnes)).toBeGreaterThan(0.999);
expect(bucketFromStagingUserId(allZeros)).toBe(0);
});
it("creates and then reuses the on-disk staging user id", async () => {
const tempDir = await mkdtemp(path.join(os.tmpdir(), "paseo-updater-id-"));
const filePath = path.join(tempDir, ".updaterId");
+17 -25
View File
@@ -19,14 +19,18 @@ import {
type RuntimeUpdateCheckResult,
type RuntimeUpdateInfo,
} from "./app-update-service.js";
import { createAppUpdatePacing } from "./app-update-pacing.js";
import {
rolloutBucket,
bucketFromStagingUserId,
rolloutManifestSchema,
shouldAdmitAppUpdate,
type AppReleaseChannel,
type AppUpdateCheckIntent,
} from "./app-update-rollout.js";
export {
bucketFromStagingUserId,
rolloutManifestSchema,
shouldAdmitAppUpdate,
type AppReleaseChannel,
type AppUpdateCheckIntent,
type AppUpdateCheckResult,
@@ -89,6 +93,16 @@ function isUpdateChannelNotPublished(error: unknown): boolean {
);
}
export function shouldAdmitToRollout(args: {
channel: AppReleaseChannel;
rolloutHours: number | undefined;
releaseDate: string | undefined;
now: number;
bucket: number;
}): boolean {
return shouldAdmitAppUpdate({ ...args, intent: "automatic" });
}
export async function resolveStagingUserId(filePath: string): Promise<string> {
try {
const id = (await readFile(filePath, "utf8")).trim();
@@ -363,21 +377,11 @@ class ElectronAppUpdateRuntime implements AppUpdateRuntime {
}
}
const appUpdatePacing = createAppUpdatePacing({
filePath: () => path.join(app.getPath("userData"), "app-update-pacing.json"),
currentVersion: () => app.getVersion(),
now: () => Date.now(),
reportError: (error) => {
console.warn("[auto-updater] Update pacing state is unavailable, not pacing updates:", error);
},
});
const appUpdateService = createAppUpdateService({
runtime: new ElectronAppUpdateRuntime(),
isPackaged: () => app.isPackaged,
now: () => Date.now(),
bucket: async (version) => rolloutBucket(await getStagingUserId(), version),
pacing: appUpdatePacing,
bucket: async () => bucketFromStagingUserId(await getStagingUserId()),
updateMode: async () => (await getDesktopSettingsStore().get()).updates.mode,
onDownloadProgress: broadcastDownloadProgress,
reportSettingsError: (error) => {
@@ -389,9 +393,6 @@ const appUpdateService = createAppUpdateService({
reportCheckError: (error) => {
console.error("[auto-updater] Failed to check for updates:", error);
},
reportAdmissionError: (error) => {
console.warn("[auto-updater] Failed to place this install in the rollout, admitting:", error);
},
reportRuntimeError: (error) => {
console.error("[auto-updater] Updater event failed:", error);
},
@@ -404,15 +405,6 @@ const appUpdateService = createAppUpdateService({
// Public API
// ---------------------------------------------------------------------------
/**
* Notes the running version, so the launch that follows an update starts the
* update cooldown. Call once when the app is ready. Never rejects.
*/
export function startAppUpdatePacing(): Promise<void> {
if (!app.isPackaged) return Promise.resolve();
return appUpdatePacing.start();
}
export async function checkForAppUpdate({
currentVersion,
releaseChannel,
+1 -2
View File
@@ -106,7 +106,7 @@ import {
import { runDesktopStartup } from "./desktop-startup.js";
import { registerBrowserAutomationIpc } from "./features/browser-automation/ipc.js";
import { BrowserKeyboard } from "./features/browser-keyboard/index.js";
import { installAppUpdateOnQuit, startAppUpdatePacing } from "./features/auto-updater.js";
import { installAppUpdateOnQuit } from "./features/auto-updater.js";
import {
buildAgentDeepLinkRoute,
parseAgentDeepLink,
@@ -945,7 +945,6 @@ async function bootstrap(): Promise<void> {
}
await app.whenReady();
void startAppUpdatePacing();
const appDistDir = getAppDistDir();
protocol.handle(APP_SCHEME, (request) => {
@@ -356,10 +356,12 @@ async function listSessions(
state: AcpConnectionState,
signal: AbortSignal,
): Promise<void> {
const extraScanDeadline = performance.now() + EXTRA_SESSION_SCAN_BUDGET_MS;
await withRequestRuntime(state, {
boundarySessionId: "sessions",
signal,
run: (runtime) => runtime.listSessions({ cwd: input.cwd, limit: input.limit }),
run: (runtime) =>
runtime.listSessions({ cwd: input.cwd, limit: input.limit, extraScanDeadline }),
publish(selected) {
state.emit({
type: "sessions",
@@ -375,6 +377,10 @@ async function listSessions(
});
}
function sessionUpdatedAt(session: SessionInfo): number {
return Date.parse(session.updatedAt ?? "") || 0;
}
function retireSession(state: AcpConnectionState, sessionId: string): void {
if (state.sessions.delete(sessionId)) {
state.emit({ type: "session.closed", sessionId });
@@ -475,6 +481,7 @@ interface ActivePrompt {
const DEFAULT_DEFERRED_SETTLE_DELAY_MS = 500;
const SESSION_SCAN_LIMIT = 500;
const EXTRA_SESSION_SCAN_BUDGET_MS = 2_000;
// COMPAT(acpAutoAccept): added in v0.17.4, remove after 2027-05-23. The generic ACP adapter saves
// its Auto Accept toggle as this setting on agents that later moved to a bundled ACP provider.
const LEGACY_AUTO_ACCEPT_SETTING = "auto_accept";
@@ -992,17 +999,38 @@ class AcpRuntime {
return true;
}
/** Follows `nextCursor` until `limit` sessions, the last page, or the scan cap. */
async listSessions({ cwd, limit }: { cwd?: string; limit?: number }): Promise<SessionInfo[]> {
/** Selects the most recent sessions from a bounded scan of the provider's pages. */
async listSessions({
cwd,
limit,
extraScanDeadline,
}: {
cwd?: string;
limit?: number;
extraScanDeadline: number;
}): Promise<SessionInfo[]> {
const wanted = Math.min(limit ?? SESSION_SCAN_LIMIT, SESSION_SCAN_LIMIT);
const sessions: SessionInfo[] = [];
let cursor: string | undefined;
do {
const page = await this.call(this.connection.listSessions({ cwd, cursor }));
sessions.push(...page.sessions);
// ACP does not guarantee that sessions arrive in recency order.
for (let pages = 0; pages < SESSION_SCAN_LIMIT; pages += 1) {
// Once we have enough rows, pages can improve the order only within the original budget.
const remainingMs =
cursor && sessions.length >= wanted ? extraScanDeadline - performance.now() : undefined;
if (remainingMs !== undefined && remainingMs <= 0) break;
const request = this.call(this.connection.listSessions({ cwd, cursor }));
const page =
remainingMs === undefined
? await request
: await withTimeout(request, remainingMs, "ACP listing scan budget expired").catch(
() => undefined,
);
if (!page) break;
sessions.push(...page.sessions.slice(0, SESSION_SCAN_LIMIT - sessions.length));
cursor = page.nextCursor ?? undefined;
} while (cursor && sessions.length < wanted);
return sessions.slice(0, wanted);
if (!cursor || sessions.length === SESSION_SCAN_LIMIT) break;
}
return sessions.sort((a, b) => sessionUpdatedAt(b) - sessionUpdatedAt(a)).slice(0, wanted);
}
async drainNotifications(): Promise<void> {
+36
View File
@@ -7184,6 +7184,42 @@ describe("ACP tool call rows", () => {
}
});
it("returns enough sessions and closes the connection when another page stalls", async () => {
const harness = connectorHarness({
capabilities: { sessionCapabilities: { list: {} } },
handleRequest(runtime, request) {
if (request.method !== "session/list") return false;
const { cursor } = request.params as { cursor?: string };
if (!cursor) {
runtime.respond(request, {
sessions: [{ sessionId: "s1", cwd: "/repo", title: "First page" }],
nextCursor: "stalled",
});
}
return true;
},
});
const connection = await runAcpProvider({
id: "stalled-listing",
label: "Stalled listing",
connector: harness.connector,
}).connect({ versions: [1], capabilities: ["prompt.message", "session.list"] });
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
await connection.send({ type: "sessions", requestId: "list", limit: 1 });
await expect.poll(() => countRequests(harness.instances[1], "session/list")).toBe(2);
const listed = await waitForEvent(events, (event) => event.type === "sessions");
expect(listed).toMatchObject({ sessions: [{ title: "First page" }] });
await expect.poll(() => harness.instances[1].readsCanceled).toBe(true);
expect(harness.instances[1].writesClosed).toBe(true);
} finally {
const listing = harness.instances[1];
if (listing && !listing.readsCanceled) listing.closeFromAgent();
await connection.close();
}
});
it("resumes the generic ACP adapter's saved Auto Accept toggle in the unattended mode", async () => {
const harness = connectorHarness({
configOptions: [
@@ -996,35 +996,6 @@ describe("bundled Paseo skill", () => {
await server.close();
}
});
it.each([
[
"create_agent",
"Hide the agent from the UI. Inherits your visibility when omitted. Omit unless the user asks for a specific value.",
],
[
"create_workspace",
"Hide the workspace from the UI. Inherits your visibility when omitted. Omit unless the user asks for a specific value.",
],
])("describes %s background without suggesting when to set it", async (name, description) => {
const server = await createAgentMcpServer({
agentManager: new BoundaryAgentManagerFake() as AgentManager,
agentStorage: new BoundaryAgentStorageFake() as AgentStorage,
providerSnapshotManager:
new BoundaryProviderSnapshotManagerFake() as unknown as ProviderSnapshotManager,
logger: createTestLogger(),
});
const client = await connectInMemoryMcpClient(server);
try {
const { tools } = await client.listTools();
const tool = tools.find((entry) => entry.name === name)!;
expect(tool.inputSchema.properties!.background).toMatchObject({ description });
} finally {
await client.close();
await server.close();
}
});
});
describe("Paseo tool timeline presentation", () => {
@@ -25,7 +25,6 @@ import { AgentManager } from "./agent-manager.js";
import { buildProviderRegistry } from "./provider-registry.js";
import { ProviderOverrideSchema } from "@getpaseo/protocol/provider-config";
import { PluginAgentClientRegistry } from "./plugin-provider.js";
import { ToolPolicyUnsupportedError } from "./provider-options.js";
import { runProviderRefreshWithDeadline } from "./provider-refresh-deadline.js";
import {
isStaleProviderSessionError,
@@ -3870,70 +3869,3 @@ test("a plugin session reopen sends the wrap the session opened with", async ()
await session.close();
await registry.shutdown();
});
describe("plugin provider tool policy", () => {
const hubMcpServers = { hub: { type: "http" as const, url: "https://hub.test/mcp" } };
const grants = { preapproved: [{ kind: "mcp" as const, server: "hub", tool: "reply" }] };
async function createWithToolPolicy(
capabilities: ProviderConnection["capabilities"],
toolPolicy: { preapproved: (typeof grants)["preapproved"] },
) {
const logger = createTestLogger();
const harness = createProviderHarness({ capabilities });
const plugins = new PluginAgentClientRegistry(logger);
plugins.replace([harness.registration]);
const registry = buildProviderRegistry(logger, { pluginProviders: plugins.definitions() });
const manager = new AgentManager({
logger,
clients: { "plugin-direct": registry["plugin-direct"].createClient(logger) },
providerDefinitions: { "plugin-direct": registry["plugin-direct"] },
});
const created = manager
.createAgent(
{ provider: "plugin-direct", cwd: tmpdir(), mcpServers: hubMcpServers, toolPolicy },
undefined,
{ workspaceId: undefined },
)
.then(
(agent) => ({ agent, error: null }),
(error: unknown) => ({ agent: null, error }),
);
const result = await created;
const opened = harness.inputs.filter((input) => input.type === "session.open");
await Promise.all(manager.listAgents().map((item) => manager.closeAgent(item.id)));
await plugins.shutdown();
return { ...result, opened };
}
test.each([
["exact grants", grants],
["an empty grant list", { preapproved: [] }],
])(
"a plugin without permission.tool_policy refuses %s with ToolPolicyUnsupportedError",
async (_label, toolPolicy) => {
const result = await createWithToolPolicy(CAPABILITIES, toolPolicy);
expect(result.error).toBeInstanceOf(ToolPolicyUnsupportedError);
expect(result.error).toMatchObject({
code: "tool_policy_unsupported",
provider: "plugin-direct",
});
expect(result.opened).toEqual([]);
},
);
test.each([
["exact grants", grants],
["an empty grant list", { preapproved: [] }],
])("a plugin with permission.tool_policy opens with %s", async (_label, toolPolicy) => {
const result = await createWithToolPolicy(
[...CAPABILITIES, "permission.tool_policy"],
toolPolicy,
);
expect(result.error).toBeNull();
expect(result.opened).toHaveLength(1);
expect(result.opened[0]).toMatchObject({ config: { toolPolicy } });
});
});
@@ -81,7 +81,7 @@ import {
formatProviderDiagnostic,
type DiagnosticEntry,
} from "./providers/diagnostic-utils.js";
import { LaunchWrapUnsupportedError, ToolPolicyUnsupportedError } from "./provider-options.js";
import { LaunchWrapUnsupportedError } from "./provider-options.js";
import type { RegisteredProviderDefinition } from "./provider-registry.js";
import { runProviderTurn } from "./providers/provider-runner.js";
import { StaleProviderSessionError } from "./stale-provider-session-error.js";
@@ -349,12 +349,6 @@ class ProviderRuntime {
throw new Error(`Provider session already exists: ${input.sessionId}`);
}
const connection = await this.getConnection();
if (input.config.toolPolicy && !connection.capabilities.includes("permission.tool_policy")) {
throw new ToolPolicyUnsupportedError(
this.registration.id,
`Provider '${this.registration.id}' cannot preapprove exact MCP tools: its connection does not offer permission.tool_policy`,
);
}
requireProviderCapabilities(connection.capabilities, {
type: "session.open",
requestId: "capability-check",
@@ -1069,8 +1063,6 @@ function createPluginProviderDefinition(
requiresConfiguration: registration.requiresConfiguration,
defaultModeId: null,
modes: [],
// Each connection negotiates permission.tool_policy, so the registry lets a policy through and
// ProviderRuntime.openSession refuses it with ToolPolicyUnsupportedError when it is not offered.
supportsExactMcpPreapproval: true,
supportsLaunchWrap: registration.launchWrap === true,
createClient,
@@ -1224,7 +1224,7 @@ function createToolCatalog(
.boolean()
.optional()
.describe(
"Hide the agent from the UI. Inherits your visibility when omitted. Omit unless the user asks for a specific value.",
"True creates a background agent: hidden from tabs, default lists, your subagent track and notifications. You still get its finish notification and can address it by id. Omit to inherit your own value (false without a caller); use it for helpers the user does not need to watch.",
),
};
const legacyCreateAgentPlacementFields = {
@@ -1435,7 +1435,7 @@ function createToolCatalog(
.boolean()
.optional()
.describe(
"Hide the workspace from the UI. Inherits your visibility when omitted. Omit unless the user asks for a specific value.",
"True hides the workspace from default lists and the sidebar while its contents remain durable and accessible; omit background to inherit your own visibility (true when you or your current workspace are background, false without a caller), and override it only when the user explicitly asks.",
),
mode: z
.enum(["branch-off", "checkout-branch", "checkout-pr"])
@@ -0,0 +1,68 @@
// An ACP peer that returns sessions in storage order, with an optional page boundary.
const readline = require("node:readline");
const { existsSync, renameSync, writeFileSync } = require("node:fs");
const path = require("node:path");
const stalledListing = process.argv.indexOf("--stall-after-first-page");
const controlDir = stalledListing === -1 ? null : process.argv[stalledListing + 1];
if (process.argv.includes("--version")) {
process.stdout.write("1.5.13\n");
process.exit(0);
}
const sessions = Array.from({ length: 317 }, (_, index) => ({
sessionId: `session-${index}`,
cwd: process.cwd(),
title: `September session ${index}`,
updatedAt: "2026-09-08T11:36:19Z",
}));
sessions[42] = {
...sessions[42],
title: "Latest November session",
updatedAt: "2026-11-23T04:07:46Z",
};
readline.createInterface({ input: process.stdin }).on("line", (line) => {
const { id, method, params } = JSON.parse(line);
if (id === undefined) return;
let response;
if (method === "initialize") {
response = {
result: { protocolVersion: 1, agentCapabilities: { sessionCapabilities: { list: {} } } },
};
} else if (method === "session/list") {
if (controlDir) {
if (params.cursor) {
writeFileSync(path.join(controlDir, "second-page"), "");
return;
}
const marker = path.join(controlDir, "first-page");
writeFileSync(marker + ".tmp", String(process.pid));
renameSync(marker + ".tmp", marker);
const gate = setInterval(() => {
if (!existsSync(path.join(controlDir, "release-first-page"))) return;
clearInterval(gate);
process.stdout.write(
JSON.stringify({
jsonrpc: "2.0",
id,
result: { sessions: sessions.slice(0, 42), nextCursor: "next" },
}) + "\n",
);
}, 10);
return;
}
const pageSize = process.argv.includes("--paginated") ? 42 : sessions.length;
response = {
result: params.cursor
? { sessions: sessions.slice(pageSize) }
: {
sessions: sessions.slice(0, pageSize),
nextCursor: pageSize < sessions.length ? "next" : null,
},
};
} else {
response = { error: { code: -32601, message: `Unsupported method ${method}` } };
}
process.stdout.write(JSON.stringify({ jsonrpc: "2.0", id, ...response }) + "\n");
});
@@ -1,5 +1,7 @@
import { describe, test, expect } from "vitest";
import { describe, test, expect, vi } from "vitest";
import { mkdtemp, rm, readFile, writeFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import { setTimeout as delay } from "node:timers/promises";
import os from "node:os";
import path from "node:path";
import { loadConfig } from "../config.js";
@@ -165,6 +167,122 @@ test("Antigravity creates an agent and answers a prompt with real agy", async ({
}
}, 120000);
test.each(["one page", "two pages"])(
"Antigravity lists the latest importable sessions from %s in storage order",
async (pages) => {
const command = [
process.execPath,
path.resolve(import.meta.dirname, "antigravity-session-list-fixture.cjs"),
];
if (pages === "two pages") command.push("--paginated");
const daemon = await createTestPaseoDaemon({
agentClients: {},
mcpEnabled: false,
builtinPlugins: new BuiltinPluginLoader(undefined, ["antigravity-provider"]),
providerOverrides: { antigravity: { command, paseoTools: { enabled: false } } },
});
const client = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.17.3",
});
const providers = ["antigravity"];
try {
await client.connect();
await client.refreshProvidersSnapshot({ cwd: daemon.paseoHome, providers });
const search = await client.fetchRecentProviderSessions({
providers,
limit: 5,
query: "November",
});
expect(search.entries.map((session) => session.title)).toEqual(["Latest November session"]);
const wide = await client.fetchRecentProviderSessions({ providers, limit: 100 });
expect(wide.entries[0]?.title).toBe("Latest November session");
const recent = await client.fetchRecentProviderSessions({ providers });
expect(recent.entries).toHaveLength(20);
expect(recent.entries[0]?.title).toBe("Latest November session");
} finally {
await client.close();
await daemon.close();
}
},
30_000,
);
test("Antigravity returns a late full page before Import Session times out", async () => {
const controlDir = await mkdtemp(path.join(os.tmpdir(), "paseo-antigravity-listing-"));
const command = [
process.execPath,
path.resolve(import.meta.dirname, "antigravity-session-list-fixture.cjs"),
"--stall-after-first-page",
controlDir,
];
const daemon = await createTestPaseoDaemon({
agentClients: {},
mcpEnabled: false,
builtinPlugins: new BuiltinPluginLoader(undefined, ["antigravity-provider"]),
providerOverrides: { antigravity: { command, paseoTools: { enabled: false } } },
});
const client = new DaemonClient({
url: `ws://127.0.0.1:${daemon.port}/ws`,
appVersion: "0.17.3",
});
const providers = ["antigravity"];
try {
await client.connect();
await client.refreshProvidersSnapshot({ cwd: daemon.paseoHome, providers });
vi.useFakeTimers({ toFake: ["performance", "setTimeout", "clearTimeout"] });
const result = client.fetchRecentProviderSessions({ providers });
let returned = false;
const markReturned = () => {
returned = true;
};
void result.then(markReturned, markReturned);
const firstPage = path.join(controlDir, "first-page");
await waitForFixture(() => existsSync(firstPage), "first page requested");
const pid = Number(await readFile(firstPage, "utf8"));
await vi.advanceTimersByTimeAsync(59_000);
await writeFile(path.join(controlDir, "release-first-page"), "");
// Let real I/O deliver the page before advancing to the client deadline.
// The provider signals a second request but never answers it.
const secondPage = path.join(controlDir, "second-page");
await waitForFixture(() => returned || existsSync(secondPage), "result or second page request");
await vi.advanceTimersByTimeAsync(1_000);
const recent = await result;
expect(recent.entries.map((session) => session.title)).toEqual(
Array.from({ length: 20 }, (_, index) => `September session ${index}`),
);
await waitForFixture(() => {
try {
process.kill(pid, 0);
return false;
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ESRCH") return true;
throw error;
}
}, "listing process exited");
} finally {
if (vi.isFakeTimers()) {
await vi.advanceTimersByTimeAsync(2_000);
vi.useRealTimers();
}
await client.close();
await daemon.close();
await rm(controlDir, { recursive: true, force: true });
}
});
async function waitForFixture(condition: () => boolean, description: string): Promise<void> {
// Use real timers for subprocess I/O while the RPC clock is paused.
const deadline = Date.now() + 10_000;
while (!condition()) {
if (Date.now() >= deadline) throw new Error(`Timed out waiting for ${description}`);
await delay(10);
}
}
test("bundled fx requires a config entry and lists models instead of its providers", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-fx-optin-"));
const record = path.join(root, "launches.txt");
@@ -194,12 +194,14 @@ test("classifies a removed file as deleted", async () => {
const root = await createRoot();
const target = join(root, "removed.txt");
await writeFile(target, "before");
const canary = createWatcherLivenessCanary(root);
const events: FileChange[] = [];
const subscription = await subscribeToFileChanges(root, (error, batch) => {
expect(error).toBeNull();
events.push(...batch);
events.push(...canary.filterEvents(batch));
});
await canary.verify();
await rm(target);
// macOS FSEvents can replay the write above as a create after the subscription starts,
// so the delete is the latest event for the path, not the first. Native recursive delivery
+17 -2
View File
@@ -177,7 +177,7 @@ test("filters by search and clears to all plugins", async ({ page }) => {
test("keeps the directory's ranking window when searching", async ({ page }) => {
await page.goto("/plugins?window=month");
await submitSearch(page, "graphite");
await expect(page).toHaveURL(/\/plugins\/all\?q=graphite&window=month$/);
await expectDirectorySearch(page, "graphite", "month");
await expect(page.getByRole("link", { name: "This month" })).toHaveAttribute(
"aria-current",
"true",
@@ -358,10 +358,16 @@ test.describe("search engine visits without JavaScript", () => {
});
test("renders search results and submits the search form", async ({ page }) => {
await page.goto("/plugins/all?q=graphite");
await page.goto("/plugins?window=month");
await submitSearch(page, "graphite");
await expectDirectorySearch(page, "graphite", "month");
await expect(
page.getByRole("heading", { level: 1, name: /^Results for “graphite”/ }),
).toBeVisible();
await expect(page.getByRole("link", { name: "This month" })).toHaveAttribute(
"aria-current",
"true",
);
await expect(page.getByRole("main").getByRole("link", { name: /Graphite/ })).toBeVisible();
await expect(page.getByRole("link", { name: /Dracula/ })).toHaveCount(0);
@@ -459,6 +465,15 @@ async function submitSearch(page: Page, term: string) {
await page.keyboard.press("Enter");
}
async function expectDirectorySearch(page: Page, term: string, window: string) {
await expect(page).toHaveURL(
(url) =>
url.pathname === "/plugins/all" &&
url.searchParams.get("q") === term &&
url.searchParams.get("window") === window,
);
}
async function typeSearch(page: Page, term: string) {
await page.getByRole("searchbox", { name: "Search plugins" }).pressSequentially(term);
}
+1 -1
View File
@@ -38,6 +38,6 @@ Check these items in order:
## Webhook and schedule runs
Runs started by inbound webhooks appear in **Activity** under `webhook.received`. If an HTTP `POST` returns an error status (`400`, `401`, `403`, `409`, `413`, `429`, or `503`), see [Inbound webhooks](/docs/hub/triggers/webhooks#request-limits-and-responses).
Runs started by inbound webhooks appear in **Activity** under `webhook.received`. If an HTTP `POST` returns an error status (`400`, `401`, `403`, `409`, `413`, or `429`), see [Inbound webhooks](/docs/hub/triggers/webhooks#request-limits-and-responses).
Scheduled runs appear in **Activity** under `schedule.tick`. While a scheduled run is still active, Hub skips newly due occurrences for that trigger until the active run completes or fails.
+1 -1
View File
@@ -36,6 +36,6 @@ Hub 会记录每一次已接受的事件,无论它是否启动了运行。使
## Webhook 与定时运行 {#webhook-and-schedule-runs}
由入站 webhook 启动的运行会以 `webhook.received` 出现在 **Activity** 中。如果 HTTP `POST` 返回错误状态码(`400`、`401`、`403`、`409`、`413`、`429` 或 `503`),参见[入站 webhook](/docs/hub/triggers/webhooks#request-limits-and-responses)。
由入站 webhook 启动的运行会以 `webhook.received` 出现在 **Activity** 中。如果 HTTP `POST` 返回错误状态码(`400`、`401`、`403`、`409`、`413` 或 `429`),参见[入站 webhook](/docs/hub/triggers/webhooks#request-limits-and-responses)。
定时运行会以 `schedule.tick` 出现在 **Activity** 中。当某次定时运行仍在进行时,Hub 会跳过该触发器新到期的计划,直到当前运行完成或失败。
-1
View File
@@ -97,7 +97,6 @@ Runs appear in [Activity](/docs/hub/activity) under the source `webhook.received
| `409` | The trigger is disabled. |
| `413` | Request body exceeds 32 KiB. |
| `429` | Endpoint exceeded 60 new deliveries in the current minute window. |
| `503` | Hub's database is unavailable. Retry after `Retry-After` seconds. |
## How the payload reaches the agent
@@ -95,7 +95,6 @@ curl -X POST "$WEBHOOK_URL" \
| `409` | 触发器已禁用。 |
| `413` | 请求体超过 32 KiB。 |
| `429` | 端点在当前 1 分钟窗口内超过了 60 次新投递。 |
| `503` | Hub 的数据库暂时不可用。请在 `Retry-After` 秒后重试。 |
## 负载如何传递给 Agent {#how-the-payload-reaches-the-agent}
+1 -3
View File
@@ -40,9 +40,7 @@ When the release is ready, the final stable tag is `v0.1.92` — not `v0.1.93`.
## Stable channel
The stable channel is the default. Stable desktop releases roll out gradually over **18 hours**: a small group of installs gets the release first, then everyone else over the following hours. If something unexpected slips through, it doesn't hit everyone at once.
After the desktop app updates, it waits **3 days** before it takes the next regular release, so frequent releases don't mean frequent restarts. Urgent fixes skip the wait. Clicking **Check** in the app skips both the rollout and the wait and installs immediately.
The stable channel is the default. Stable desktop releases roll out gradually over **36 hours** so that if something unexpected slips through, it doesn't hit everyone at once. Automatic update checks pick up the release as the rollout progresses; clicking **Check** in the app bypasses the rollout and installs immediately.
Stable releases are what most users should run.
+1 -3
View File
@@ -38,9 +38,7 @@ v0.1.92-beta.3
## 稳定版渠道 {#stable-channel}
稳定版渠道是默认渠道。桌面端稳定版会在 **18 小时**内逐步推送:先推送给一小部分用户,再在随后的几小时内推送给所有人。这样即使有意外问题漏网,也不会同时影响所有人。
桌面应用更新后,会等待 **3 天**再接收下一个常规版本,因此频繁发版不会带来频繁重启。紧急修复不受这段等待限制。在应用中点击 **检查** 会跳过分批推送和等待,立即安装。
稳定版渠道是默认渠道。桌面端稳定版会在 **36 小时**内逐步推送,这样即使有意外问题漏网,也不会同时影响所有人。自动更新检查会随着推送进度获取新版本;在应用中点击 **检查** 会跳过分批推送,立即安装。
大多数用户应该使用稳定版。
-12
View File
@@ -626,18 +626,6 @@ test("desktop release creates release-manifests before entering it and uses the
assert.match(workflow, /mkdir -p release-manifests\s*\n\s+cd release-manifests/);
});
test("desktop release stamps an 18-hour rollout on a tag push and by default on a manual run", () => {
const workflow = readFileSync(new URL(".github/workflows/desktop-release.yml", repoRoot), "utf8");
const manualRunDefault = /\n {6}rollout_hours:\n(?: {8}.*\n)*? {8}default: "(\d+)"/.exec(
workflow,
);
const tagPushDefault =
/\n {2}ROLLOUT_HOURS: \$\{\{.*inputs\.rollout_hours \|\| '(\d+)' \}\}/.exec(workflow);
assert.equal(manualRunDefault?.[1], "18");
assert.equal(tagPushDefault?.[1], "18");
});
test("macOS release xcrun wrapper retries transient stapling and notarization failures without rebuilding", async (t) => {
const wrapperSource = readFileSync(new URL("scripts/macos-xcrun-retry.sh", repoRoot), "utf8");
const networkLostError =
+1 -1
View File
@@ -44,7 +44,7 @@ For a local daemon, `project create` defaults to the current directory and resol
**`create_workspace`** — create a workspace independently of any agent. Required: `isolation` (`local` or `worktree`). Worktree isolation supports `mode: "branch-off" | "checkout-branch" | "checkout-pr"`: use `branchName`/`baseBranch` for a new branch, `branch` for an existing branch, or `prNumber` plus optional `forge` for a change request. Use `path` for a local directory or source checkout and `projectId` for the owning project; when no path is supplied, a worktree may resolve its source from `projectId`. `worktreeSlug` controls the managed path. Returns the workspace descriptor centered on `workspaceId`.
`background` hides the workspace from the UI. It inherits your visibility when omitted. Omit it unless the user asks for a specific value.
`background: true` hides a workspace from default lists and the sidebar while its contents remain durable and accessible; omit `background` to inherit your current workspace’s value (false without a caller), and override it only when the user explicitly asks.
Choose `baseBranch` explicitly: `origin/main` selects the remote-tracking branch; `refs/heads/main` selects local main. Bare `main` prefers local main when it exists, otherwise origin/main. Paseo retains the resolved ref for workspace comparisons, even after rebasing the branch or changing its PR target.