Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

fix(cli): make version update checks reliable (#3952)

Alberto Schiabel473e9d20ad24
diff --git a/ts/e2e-tests/cli/version/README.md b/ts/e2e-tests/cli/version/README.md
index 0ef8b6323..3cf3c1a20 100644
--- a/ts/e2e-tests/cli/version/README.md
+++ b/ts/e2e-tests/cli/version/README.md
@@ -10,15 +10,18 @@ The CLI separates decoration (stderr) from data (stdout). This suite ensures:
- stdout contains the version from `packages/cli/package.json`
- stderr is empty (no decoration leaks into piped output)
- Redirecting stdout to a file captures the clean version string
+- `composio version --check` emits deterministic JSON for known and unknown release states
## What It Tests
-| Test | Description |
-| --- | --- |
-| Exit code | `composio version` returns 0 |
-| stdout | Output matches `package.json` version |
-| stderr | Empty when piped |
-| File redirect | `composio version > out.txt` captures the version in the file |
+| Test | Description |
+| ---------------- | ---------------------------------------------------------------- |
+| Exit code | `composio version` returns 0 |
+| stdout | Output matches `package.json` version |
+| stderr | Empty when piped |
+| File redirect | `composio version > out.txt` captures the version in the file |
+| Update available | `version --check` reports a newer cached stable version |
+| Unknown status | `version --check` does not report a failed refresh as up to date |
## Requirements
diff --git a/ts/e2e-tests/cli/version/e2e.test.ts b/ts/e2e-tests/cli/version/e2e.test.ts
index b2feb0232..afa410b21 100644
--- a/ts/e2e-tests/cli/version/e2e.test.ts
+++ b/ts/e2e-tests/cli/version/e2e.test.ts
@@ -4,7 +4,13 @@
* Verifies that the compiled composio CLI behaves correctly in a scratch container.
*/
-import { e2e, sanitizeOutput, type E2ETestResult, type E2ETestResultWithFiles } from '@e2e-tests/utils';
+import {
+ e2e,
+ parseJsonStdout,
+ sanitizeOutput,
+ type E2ETestResult,
+ type E2ETestResultWithFiles,
+} from '@e2e-tests/utils';
import { TIMEOUTS } from '@e2e-tests/utils/const';
import { describe, it, expect, beforeAll } from 'bun:test';
import cliPkg from '../../../packages/cli/package.json' with { type: 'json' };
@@ -16,10 +22,18 @@ e2e(import.meta.url, {
defineTests: ({ runCmd }) => {
const expectedVersion = String(cliPkg.version ?? '').trim();
let versionResult: E2ETestResult;
+ let updateAvailableResult: E2ETestResult;
+ let unknownStatusResult: E2ETestResult;
let redirectedResult: E2ETestResultWithFiles<'out.txt'>;
beforeAll(async () => {
versionResult = await runCmd('composio version');
+ updateAvailableResult = await runCmd(
+ `mkdir -p .composio && printf '%s' '{"lastChecked":"2099-01-01T00:00:00.000Z","latestVersion":"99.0.0"}' > .composio/update-check.json && HOME="$PWD" composio version --check`
+ );
+ unknownStatusResult = await runCmd(
+ `mkdir -p .composio && printf '%s' '{"lastAttempted":"2099-01-01T00:00:00.000Z"}' > .composio/update-check.json.attempt && HOME="$PWD" composio version --check`
+ );
redirectedResult = await runCmd({
command: 'composio version > out.txt',
files: ['out.txt'],
@@ -40,6 +54,34 @@ e2e(import.meta.url, {
});
});
+ describe('composio version --check with a known update', () => {
+ it('exits successfully with clean machine-readable output', () => {
+ expect(updateAvailableResult.exitCode).toBe(0);
+ expect(updateAvailableResult.stderr).toBe('');
+ expect(parseJsonStdout(updateAvailableResult)).toEqual({
+ current: expectedVersion,
+ latestStable: '99.0.0',
+ updateAvailable: true,
+ checkStatus: 'update-available',
+ lastChecked: '2099-01-01T00:00:00.000Z',
+ });
+ });
+ });
+
+ describe('composio version --check when the latest release is unknown', () => {
+ it('exits successfully without claiming the current version is up to date', () => {
+ expect(unknownStatusResult.exitCode).toBe(0);
+ expect(unknownStatusResult.stderr).toBe('');
+ expect(parseJsonStdout(unknownStatusResult)).toEqual({
+ current: expectedVersion,
+ latestStable: null,
+ updateAvailable: false,
+ checkStatus: 'unknown',
+ lastChecked: null,
+ });
+ });
+ });
+
describe('stdout redirection to out.txt', () => {
it('exits successfully', () => {
expect(redirectedResult.exitCode).toBe(0);
diff --git a/ts/packages/cli/CHANGELOG.md b/ts/packages/cli/CHANGELOG.md
index 87585eff7..81e83d6b3 100644
--- a/ts/packages/cli/CHANGELOG.md
+++ b/ts/packages/cli/CHANGELOG.md
@@ -15,6 +15,7 @@
### Patch Changes
+- Make `composio version --check` report `checkStatus: "unknown"` when GitHub cannot confirm the latest stable release, preserve the last successful cache on failed refreshes, and avoid racing the command with the startup update check.
- Make multi-account selection a stable CLI feature: `execute`, `listen`, and `link --alias` no longer honor the old experimental toggle; `proxy` now accepts `--account <alias|word_id|connected-account-id>`; and duplicate-alias link errors explain how to select the existing account.
- 8467efd: Fix `composio whoami` reporting the API key's home organization after `composio orgs switch`. Session info requests now forward the selected global organization.
- 5f004ff: Drop `COMPOSIO_UPSERT_RECIPE` and `COMPOSIO_GET_RECIPE` from the CLI meta-tool list. These slugs were removed from `@composio/client` (alpha.74), so listing them broke the type-checked CLI build.
diff --git a/ts/packages/cli/src/cli-main.ts b/ts/packages/cli/src/cli-main.ts
index 68d86d95f..c9b617e3b 100644
--- a/ts/packages/cli/src/cli-main.ts
+++ b/ts/packages/cli/src/cli-main.ts
@@ -30,7 +30,7 @@ import { ProjectContext } from 'src/services/project-context';
import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
import { CommandRunner } from 'src/services/command-runner';
import { StdinLive } from 'src/services/stdin';
-import { showUpdateNotice, checkForUpdateInBackground } from 'src/services/update-check';
+import { showUpdateNotice } from 'src/services/update-check';
import {
createCliCommandTelemetryContext,
getPrimaryLifecycleFailedEvent,
@@ -173,8 +173,6 @@ const runWithTelemetry = Effect.gen(function* () {
);
});
-checkForUpdateInBackground();
-
showUpdateNotice.pipe(
Effect.andThen(runWithTelemetry),
Effect.catchIf(ValidationError.isValidationError, error => {
diff --git a/ts/packages/cli/src/commands/background-update-check.ts b/ts/packages/cli/src/commands/background-update-check.ts
new file mode 100644
index 000000000..3ea317ff3
--- /dev/null
+++ b/ts/packages/cli/src/commands/background-update-check.ts
@@ -0,0 +1,44 @@
+import { Command } from '@effect/cli';
+import { Effect, Option } from 'effect';
+import { versionCmd } from './version.cmd';
+import { checkForUpdateInBackground } from 'src/services/update-check';
+
+type RootCommandInput = {
+ readonly subcommand: Option.Option<unknown>;
+};
+
+type ParsedSubcommand = readonly [commandTag: unknown, input: unknown];
+
+const isParsedSubcommand = (value: unknown): value is ParsedSubcommand =>
+ Array.isArray(value) && value.length === 2;
+
+const isExplicitVersionCheck = (subcommand: Option.Option<unknown>): boolean =>
+ Option.exists(subcommand, selected => {
+ if (!isParsedSubcommand(selected) || selected[0] !== versionCmd.tag) {
+ return false;
+ }
+
+ const input = selected[1];
+ return typeof input === 'object' && input !== null && 'check' in input && input.check === true;
+ });
+
+/**
+ * Starts the background update request after @effect/cli has parsed the selected command.
+ *
+ * @effect/cli v3 retains the selected command tag alongside its parsed input at runtime,
+ * even though the public root-input type erases that tuple.
+ */
+export const withBackgroundUpdateCheck = <
+ Name extends string,
+ R,
+ E,
+ Input extends RootCommandInput,
+>(
+ command: Command.Command<Name, R, E, Input>,
+ start: () => void = checkForUpdateInBackground
+): Command.Command<Name, R, E, Input> =>
+ command.pipe(
+ Command.provideEffectDiscard(({ subcommand }) =>
+ isExplicitVersionCheck(subcommand) ? Effect.void : Effect.sync(start)
+ )
+ );
diff --git a/ts/packages/cli/src/commands/index.ts b/ts/packages/cli/src/commands/index.ts
index 0034a54f6..e42126280 100644
--- a/ts/packages/cli/src/commands/index.ts
+++ b/ts/packages/cli/src/commands/index.ts
@@ -57,6 +57,7 @@ import {
import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
import { installSkill, type SkillInstallTarget } from 'src/effects/install-skill';
import { experimental, type CommandVisibility, tagged, visibleValues } from './feature-tags';
+import { withBackgroundUpdateCheck } from './background-update-check';
const ROOT_COMMANDS = [
tagged(versionCmd),
@@ -452,7 +453,7 @@ export const runWithConfig = Effect.gen(function* () {
isExperimentalFeatureEnabled: feature => cliUserConfig.isExperimentalFeatureEnabled(feature),
};
const version = yield* getVersion;
- const rootCommand = buildRootCommand(visibility);
+ const rootCommand = withBackgroundUpdateCheck(buildRootCommand(visibility));
const run = Command.run(rootCommand, {
name: 'composio',
executable: 'composio',
diff --git a/ts/packages/cli/src/commands/version.cmd.ts b/ts/packages/cli/src/commands/version.cmd.ts
index d40c47559..254232221 100644
--- a/ts/packages/cli/src/commands/version.cmd.ts
+++ b/ts/packages/cli/src/commands/version.cmd.ts
@@ -8,7 +8,7 @@ import { bold, cyanBright } from 'src/ui/colors';
const check = Options.boolean('check').pipe(
Options.withDescription(
'Check for a newer stable release and print a machine-readable JSON status ' +
- '({current, latestStable, updateAvailable, lastChecked}). ' +
+ '({current, latestStable, updateAvailable, checkStatus, lastChecked}). ' +
'Refreshes the release cache when it is older than 24 hours.'
)
);
@@ -34,6 +34,8 @@ export const versionCmd = Command.make('version', { check }).pipe(
yield* ui.log.info(
`Update available: ${status.current} → ${bold(cyanBright(status.latestStable))} — run ${cyanBright('composio upgrade')}`
);
+ } else if (status.checkStatus === 'unknown') {
+ yield* ui.log.warn('Unable to determine the latest stable Composio CLI release.');
} else {
yield* ui.log.info(`${status.current} is up to date.`);
}
diff --git a/ts/packages/cli/src/services/update-check.ts b/ts/packages/cli/src/services/update-check.ts
index 96c9fed4d..917384f43 100644
--- a/ts/packages/cli/src/services/update-check.ts
+++ b/ts/packages/cli/src/services/update-check.ts
@@ -41,6 +41,8 @@ export interface UpdateStatus {
latestStable: string | null;
/** True when a strictly newer stable release than `current` is available. */
updateAvailable: boolean;
+ /** Whether the latest known state is current, actionable, or unavailable. */
+ checkStatus: 'up-to-date' | 'update-available' | 'unknown';
/** When the release list was last fetched (ISO-8601), if ever. */
lastChecked: string | null;
}
@@ -52,7 +54,13 @@ const UpdateCheckStateSchema = Schema.parseJson(
})
);
-/** Non-2xx response from the GitHub releases API; swallowed after the state write. */
+const UpdateCheckAttemptSchema = Schema.parseJson(
+ Schema.Struct({
+ lastAttempted: Schema.String,
+ })
+);
+
+/** Non-2xx GitHub response; recorded as a failed attempt and otherwise swallowed. */
class UpdateCheckHttpError extends Data.TaggedError('UpdateCheckHttpError')<{
readonly status: number;
}> {}
@@ -145,12 +153,20 @@ export function parseLatestVersionFromReleases(
// ── Factory ─────────────────────────────────────────────────────────────
export function createUpdateChecker(config: UpdateCheckConfig) {
+ const attemptFile = `${config.stateFile}.attempt`;
+
const readState = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const rawState = yield* fs.readFileString(config.stateFile);
return yield* Schema.decodeUnknown(UpdateCheckStateSchema)(rawState);
});
+ const readAttempt = Effect.gen(function* () {
+ const fs = yield* FileSystem.FileSystem;
+ const rawAttempt = yield* fs.readFileString(attemptFile);
+ return yield* Schema.decodeUnknown(UpdateCheckAttemptSchema)(rawAttempt);
+ });
+
/**
* If a cached newer version is known, print a one-line hint to stderr.
* Reads a tiny JSON file and does a semver compare.
@@ -161,14 +177,15 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
if (!capabilities.isInteractive) return;
const state = yield* readState;
- if (!state.latestVersion || !semver.valid(state.latestVersion)) return;
- if (state.latestVersion === config.currentVersion) return;
+ const latestVersion = semver.valid(state.latestVersion);
+ const currentVersion = semver.valid(config.currentVersion);
+ if (!latestVersion || !currentVersion || latestVersion === currentVersion) return;
// Only show when the cached version is strictly newer.
- if (!semver.gt(state.latestVersion, config.currentVersion)) return;
+ if (!semver.gt(latestVersion, currentVersion)) return;
const msg =
- ` ${dim('Update available:')} ${dim(config.currentVersion)} ${dim('→')} ${bold(cyanBright(state.latestVersion))}\n` +
+ ` ${dim('Update available:')} ${dim(config.currentVersion)} ${dim('→')} ${bold(cyanBright(latestVersion))}\n` +
` ${dim('Run')} ${cyanBright('composio upgrade')} ${dim('to update')}\n`;
yield* terminal.error(`\n${msg}`);
@@ -185,15 +202,32 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
const checkForUpdate = Effect.gen(function* () {
const fs = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
+ const checkStartedAt = new Date();
+ const checkStartedAtMs = checkStartedAt.getTime();
+ const parseTimestamp = (value: string): number | undefined => {
+ const timestamp = new Date(value).getTime();
+ return Number.isFinite(timestamp) ? timestamp : undefined;
+ };
// Throttle: skip if checked recently. A missing or corrupt state file
// just means "re-check".
const cachedState = yield* Effect.option(readState);
+ const lastCheckedAt = Option.getOrUndefined(
+ Option.map(cachedState, state => parseTimestamp(state.lastChecked))
+ );
+ if (lastCheckedAt !== undefined && checkStartedAtMs - lastCheckedAt < config.checkIntervalMs) {
+ return { state: cachedState, refreshFailed: false } as const;
+ }
+ const failedAttempt = yield* Effect.option(readAttempt);
+ const lastAttemptedAt = Option.getOrUndefined(
+ Option.map(failedAttempt, attempt => parseTimestamp(attempt.lastAttempted))
+ );
if (
- Option.isSome(cachedState) &&
- Date.now() - new Date(cachedState.value.lastChecked).getTime() < config.checkIntervalMs
+ lastAttemptedAt !== undefined &&
+ (lastCheckedAt === undefined || lastAttemptedAt > lastCheckedAt) &&
+ checkStartedAtMs - lastAttemptedAt < config.checkIntervalMs
) {
- return;
+ return { state: cachedState, refreshFailed: true } as const;
}
const previousLatestVersion = Option.getOrUndefined(
Option.map(cachedState, state => state.latestVersion)
@@ -208,22 +242,10 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
headers.Authorization = `Bearer ${config.accessToken}`;
}
- // Always persist lastChecked to prevent retry loops when the fetch
- // fails or returns no matching releases with a matching binary.
- const writeState = (latestVersion?: string) =>
- fs.makeDirectory(path.dirname(config.stateFile), { recursive: true }).pipe(
- Effect.matchEffect({
- // If we can't create the directory, bail out silently.
- onFailure: () => Effect.void,
- onSuccess: () => {
- const state: UpdateCheckState = {
- lastChecked: new Date().toISOString(),
- latestVersion: latestVersion ?? previousLatestVersion ?? config.currentVersion,
- };
- return fs.writeFileString(config.stateFile, JSON.stringify(state, null, 2));
- },
- })
- );
+ const writeJsonFile = (file: string, value: unknown) =>
+ fs
+ .makeDirectory(path.dirname(file), { recursive: true })
+ .pipe(Effect.andThen(fs.writeFileString(file, JSON.stringify(value, null, 2))));
const fetchLatestVersion = Effect.gen(function* () {
const response = yield* Effect.tryPromise(() =>
@@ -236,12 +258,25 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
return parseLatestVersionFromReleases(releases, config.binaryAssetName);
});
- yield* fetchLatestVersion.pipe(
- Effect.flatMap(writeState),
- // Silently ignore fetch/parse errors — never block the CLI.
- // Still update the timestamp to prevent unbounded retry loops.
- Effect.catchAll(() => Effect.ignore(writeState()))
+ const latestVersion = yield* Effect.option(fetchLatestVersion);
+ if (Option.isNone(latestVersion)) {
+ yield* Effect.ignore(
+ writeJsonFile(attemptFile, {
+ lastAttempted: checkStartedAt.toISOString(),
+ })
+ );
+ return { state: cachedState, refreshFailed: true } as const;
+ }
+
+ const state: UpdateCheckState = {
+ lastChecked: new Date().toISOString(),
+ latestVersion: latestVersion.value ?? previousLatestVersion ?? config.currentVersion,
+ };
+ yield* writeJsonFile(config.stateFile, state).pipe(
+ Effect.andThen(fs.remove(attemptFile, { force: true })),
+ Effect.ignore
);
+ return { state: Option.some(state), refreshFailed: false } as const;
});
/**
@@ -251,27 +286,32 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
*/
const getUpdateStatus: Effect.Effect<UpdateStatus, never, FileSystem.FileSystem | Path.Path> =
Effect.gen(function* () {
- yield* checkForUpdate;
- const state = yield* Effect.option(readState);
+ const { state, refreshFailed } = yield* checkForUpdate;
const cachedLatest = Option.getOrUndefined(Option.map(state, s => s.latestVersion));
- // The cache falls back to the current version when no release was found,
- // so a prerelease can leak into latestVersion — never report that as stable.
+ const validLatest = cachedLatest ? semver.valid(cachedLatest) : null;
+ const validCurrent = semver.valid(config.currentVersion);
const latestStable =
- cachedLatest && semver.valid(cachedLatest) && semver.prerelease(cachedLatest) === null
- ? cachedLatest
- : null;
+ validLatest && semver.prerelease(validLatest) === null ? validLatest : null;
+ const updateAvailable =
+ validCurrent !== null && latestStable !== null && semver.gt(latestStable, validCurrent);
+ const checkStatus = updateAvailable
+ ? 'update-available'
+ : refreshFailed || validCurrent === null || latestStable === null
+ ? 'unknown'
+ : 'up-to-date';
return {
current: config.currentVersion,
latestStable,
- updateAvailable: latestStable !== null && semver.gt(latestStable, config.currentVersion),
+ updateAvailable,
+ checkStatus,
lastChecked: Option.getOrElse(
Option.map(state, s => s.lastChecked),
() => null as string | null
),
} satisfies UpdateStatus;
- }).pipe(Effect.orDie);
+ });
return { showUpdateNotice, checkForUpdate, getUpdateStatus };
}
@@ -300,8 +340,8 @@ export const getUpdateStatus: Effect.Effect<UpdateStatus> = Effect.gen(function*
/** Fire-and-forget background fetch to GitHub. */
export function checkForUpdateInBackground(): void {
- // Runs from cli-main before the runtime boots; runPromiseExit never throws back
- // into the caller and checkForUpdate swallows its own failures.
+ // Uses a detached runtime so short-lived command handlers do not interrupt the refresh.
+ // runPromiseExit never throws into the caller, and checkForUpdate swallows its own failures.
void Effect.runPromiseExit(
Effect.gen(function* () {
const stateFile = yield* defaultStateFile;
diff --git a/ts/packages/cli/test/src/commands/background-update-check.test.ts b/ts/packages/cli/test/src/commands/background-update-check.test.ts
new file mode 100644
index 000000000..9b069342d
--- /dev/null
+++ b/ts/packages/cli/test/src/commands/background-update-check.test.ts
@@ -0,0 +1,59 @@
+import { Command } from '@effect/cli';
+import { describe, expect, layer, vi } from '@effect/vitest';
+import { Effect } from 'effect';
+import { $defaultCmd } from 'src/commands/$default.cmd';
+import { withBackgroundUpdateCheck } from 'src/commands/background-update-check';
+import { versionCmd } from 'src/commands/version.cmd';
+import { TestLive } from 'test/__utils__';
+
+const makeRunner = (start: () => void) => {
+ const version = versionCmd.pipe(Command.withHandler(() => Effect.void));
+ const other = Command.make('other').pipe(Command.withHandler(() => Effect.void));
+ const root = $defaultCmd.pipe(Command.withSubcommands([version, other]), command =>
+ withBackgroundUpdateCheck(command, start)
+ );
+
+ return Command.run(root, {
+ name: 'composio',
+ executable: 'composio',
+ version: '0.0.0-test',
+ });
+};
+
+describe('withBackgroundUpdateCheck', () => {
+ layer(TestLive())(it => {
+ it.scoped('skips the background request for an explicit version check', () =>
+ Effect.gen(function* () {
+ const start = vi.fn();
+
+ yield* makeRunner(start)(['node', 'composio', 'version', '--check']);
+
+ expect(start).not.toHaveBeenCalled();
+ })
+ );
+
+ it.scoped('uses parsed root options when identifying an explicit version check', () =>
+ Effect.gen(function* () {
+ const start = vi.fn();
+ const run = makeRunner(start);
+
+ yield* run(['node', 'composio', '--log-level', 'debug', 'version', '--check']);
+ yield* run(['node', 'composio', '--log-level=debug', 'version', '--check']);
+
+ expect(start).not.toHaveBeenCalled();
+ })
+ );
+
+ it.scoped('starts the background request for other parsed commands', () =>
+ Effect.gen(function* () {
+ const start = vi.fn();
+ const run = makeRunner(start);
+
+ yield* run(['node', 'composio', 'version']);
+ yield* run(['node', 'composio', 'other']);
+
+ expect(start).toHaveBeenCalledTimes(2);
+ })
+ );
+ });
+});
diff --git a/ts/packages/cli/test/src/services/update-check.test.ts b/ts/packages/cli/test/src/services/update-check.test.ts
index d33e65f6b..d1d50dd7e 100644
--- a/ts/packages/cli/test/src/services/update-check.test.ts
+++ b/ts/packages/cli/test/src/services/update-check.test.ts
@@ -3,7 +3,7 @@ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync
import { dirname, join } from 'node:path';
import { tmpdir } from 'node:os';
import { BunFileSystem, BunPath } from '@effect/platform-bun';
-import { Effect, Layer } from 'effect';
+import { Effect, Fiber, Layer } from 'effect';
import { withHttpServerEffect } from 'test/__utils__/http-server';
import type { TerminalUI } from 'src/services/terminal-ui';
import {
@@ -71,6 +71,16 @@ function makeReleasesPayload(versions: string[], assetName = 'composio-darwin-aa
}));
}
+function makeDeferred<T>() {
+ let resolve!: (value: T | PromiseLike<T>) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+}
+
// ── parseLatestVersionFromReleases (pure) ───────────────────────────────
describe('parseLatestVersionFromReleases', () => {
@@ -264,12 +274,13 @@ describe('getUpdateStatus', () => {
current: '0.2.0',
latestStable: '0.3.0',
updateAvailable: true,
+ checkStatus: 'update-available',
lastChecked: expect.any(String),
});
}).pipe(Effect.provide(PlatformLayers))
);
- it.effect('reports no update when the fetch fails and no cache exists', () =>
+ it.effect('reports an unknown status when the fetch fails and no cache exists', () =>
Effect.gen(function* () {
const config = makeConfig({
currentVersion: '0.2.0',
@@ -279,8 +290,36 @@ describe('getUpdateStatus', () => {
const status = yield* getUpdateStatus;
- expect(status.updateAvailable).toBe(false);
- expect(status.lastChecked).toEqual(expect.any(String));
+ expect(status).toEqual({
+ current: '0.2.0',
+ latestStable: null,
+ updateAvailable: false,
+ checkStatus: 'unknown',
+ lastChecked: null,
+ });
+ expect(existsSync(config.stateFile)).toBe(false);
+ }).pipe(Effect.provide(PlatformLayers))
+ );
+
+ it.effect('does not call a stale cached version up to date after a failed refresh', () =>
+ Effect.gen(function* () {
+ const config = makeConfig({
+ currentVersion: '0.2.0',
+ fetchFn: vi.fn().mockRejectedValue(new Error('offline')) as unknown as typeof fetch,
+ });
+ const lastChecked = '2020-01-01T00:00:00.000Z';
+ writeState(config, { lastChecked, latestVersion: '0.2.0' });
+ const { getUpdateStatus } = createUpdateChecker(config);
+
+ const status = yield* getUpdateStatus;
+
+ expect(status).toEqual({
+ current: '0.2.0',
+ latestStable: '0.2.0',
+ updateAvailable: false,
+ checkStatus: 'unknown',
+ lastChecked,
+ });
}).pipe(Effect.provide(PlatformLayers))
);
@@ -297,6 +336,7 @@ describe('getUpdateStatus', () => {
expect(status.latestStable).toBeNull();
expect(status.updateAvailable).toBe(false);
+ expect(status.checkStatus).toBe('unknown');
}).pipe(Effect.provide(PlatformLayers))
);
@@ -315,6 +355,25 @@ describe('getUpdateStatus', () => {
expect(fetchFn).not.toHaveBeenCalled();
expect(status.latestStable).toBe('0.2.1');
expect(status.updateAvailable).toBe(true);
+ expect(status.checkStatus).toBe('update-available');
+ }).pipe(Effect.provide(PlatformLayers))
+ );
+
+ it.effect('reports an unknown status for an invalid installed version', () =>
+ Effect.gen(function* () {
+ const config = makeConfig({ currentVersion: 'corrupt-tag' });
+ writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });
+ const { getUpdateStatus } = createUpdateChecker(config);
+
+ const status = yield* getUpdateStatus;
+
+ expect(status).toEqual({
+ current: 'corrupt-tag',
+ latestStable: '0.3.0',
+ updateAvailable: false,
+ checkStatus: 'unknown',
+ lastChecked: expect.any(String),
+ });
}).pipe(Effect.provide(PlatformLayers))
);
});
@@ -466,7 +525,7 @@ describe('checkForUpdate', () => {
}).pipe(Effect.provide(PlatformLayers))
);
- it.effect('writes lastChecked on HTTP errors to prevent retry loops', () =>
+ it.effect('does not create authoritative state after an HTTP error', () =>
Effect.gen(function* () {
const config = makeConfig({
fetchFn: vi.fn().mockResolvedValue({
@@ -479,14 +538,11 @@ describe('checkForUpdate', () => {
// Should not fail
yield* checkForUpdate;
- expect(existsSync(config.stateFile)).toBe(true);
- const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
- expect(state.lastChecked).toBeDefined();
- expect(state.latestVersion).toBe(config.currentVersion);
+ expect(existsSync(config.stateFile)).toBe(false);
}).pipe(Effect.provide(PlatformLayers))
);
- it.effect('writes lastChecked on network errors to prevent retry loops', () =>
+ it.effect('does not create authoritative state after a network error', () =>
Effect.gen(function* () {
const config = makeConfig({
fetchFn: vi.fn().mockRejectedValue(new Error('DNS failed')) as unknown as typeof fetch,
@@ -495,10 +551,95 @@ describe('checkForUpdate', () => {
yield* checkForUpdate;
- expect(existsSync(config.stateFile)).toBe(true);
+ expect(existsSync(config.stateFile)).toBe(false);
+ }).pipe(Effect.provide(PlatformLayers))
+ );
+
+ it.effect('throttles repeated network errors without creating authoritative state', () =>
+ Effect.gen(function* () {
+ const fetchFn = vi.fn().mockRejectedValue(new Error('DNS failed'));
+ const config = makeConfig({ fetchFn: fetchFn as unknown as typeof fetch });
+ const { checkForUpdate } = createUpdateChecker(config);
+
+ yield* checkForUpdate;
+ yield* checkForUpdate;
+
+ expect(fetchFn).toHaveBeenCalledOnce();
+ expect(existsSync(config.stateFile)).toBe(false);
+ expect(existsSync(`${config.stateFile}.attempt`)).toBe(true);
+ }).pipe(Effect.provide(PlatformLayers))
+ );
+
+ it.effect('preserves stale successful state after a network error', () =>
+ Effect.gen(function* () {
+ const config = makeConfig({
+ fetchFn: vi.fn().mockRejectedValue(new Error('DNS failed')) as unknown as typeof fetch,
+ });
+ const previousState: UpdateCheckState = {
+ lastChecked: staleLastChecked,
+ latestVersion: '0.3.0',
+ };
+ writeState(config, previousState);
+ const { checkForUpdate } = createUpdateChecker(config);
+
+ yield* checkForUpdate;
+
const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
- expect(state.lastChecked).toBeDefined();
- expect(state.latestVersion).toBe(config.currentVersion);
+ expect(state).toEqual(previousState);
+ }).pipe(Effect.provide(PlatformLayers))
+ );
+
+ it.effect('does not let an older failed check supersede successful state', () =>
+ Effect.gen(function* () {
+ const failedResponse = makeDeferred<Response>();
+ const failedRequestStarted = makeDeferred<void>();
+ const failingConfig = makeConfig({
+ fetchFn: vi.fn(() => {
+ failedRequestStarted.resolve();
+ return failedResponse.promise;
+ }),
+ });
+ const successfulConfig = makeConfig({
+ fetchFn: vi.fn().mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve(makeReleasesPayload(['0.3.0'])),
+ }) as unknown as typeof fetch,
+ });
+ const failingFiber = yield* Effect.fork(createUpdateChecker(failingConfig).checkForUpdate);
+
+ yield* Effect.promise(() => failedRequestStarted.promise);
+ const successfulAt = new Date(pinnedNow.getTime() + 60_000);
+ yield* Effect.sync(() => vi.setSystemTime(successfulAt));
+ yield* createUpdateChecker(successfulConfig).checkForUpdate;
+ yield* Effect.sync(() => vi.setSystemTime(new Date(successfulAt.getTime() + 60_000)));
+ yield* Effect.sync(() => failedResponse.reject(new Error('transient failure')));
+ yield* Fiber.join(failingFiber);
+
+ const state: UpdateCheckState = JSON.parse(readFileSync(failingConfig.stateFile, 'utf-8'));
+ expect(state).toEqual({
+ lastChecked: successfulAt.toISOString(),
+ latestVersion: '0.3.0',
+ });
+ expect(JSON.parse(readFileSync(`${failingConfig.stateFile}.attempt`, 'utf-8'))).toEqual({
+ lastAttempted: pinnedNow.toISOString(),
+ });
+
+ const recoveryFetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve(makeReleasesPayload(['0.4.0'])),
+ });
+ yield* Effect.sync(() =>
+ vi.setSystemTime(new Date(successfulAt.getTime() + failingConfig.checkIntervalMs + 1))
+ );
+ yield* createUpdateChecker(makeConfig({ fetchFn: recoveryFetch as unknown as typeof fetch }))
+ .checkForUpdate;
+
+ expect(recoveryFetch).toHaveBeenCalledOnce();
+ const refreshedState: UpdateCheckState = JSON.parse(
+ readFileSync(failingConfig.stateFile, 'utf-8')
+ );
+ expect(refreshedState.latestVersion).toBe('0.4.0');
+ expect(existsSync(`${failingConfig.stateFile}.attempt`)).toBe(false);
}).pipe(Effect.provide(PlatformLayers))
);