@devries-cameron20 / composio-1 / commits / 473e9d20a
Fork 0

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)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/3944 - reports `checkStatus: "unknown"` instead of fabricating an up-to-date result when GitHub refreshes fail - preserves the last successful release cache and throttles failed attempts separately - uses `Command.provideEffectDiscard` to start background checks after parsing and skips explicit `composio version --check` invocations - validates installed release versions before semver comparison - adds deterministic unit concurrency coverage and compiled-binary CLI E2E coverage ## Verification - `pnpm --filter @composio/cli test` (`963` passed, `1` skipped) - `pnpm typecheck` (`14/14` tasks) - `pnpm build:packages` (`19/19` tasks) - `pnpm --filter @e2e-tests/cli-version test:e2e:cli` (`9` passed) - `pnpm build:binary` followed by `pnpm install:binary` - installed Mach-O binary smoke checks for plain version, live and cached `version --check`, unknown status, and both leading `--log-level` forms - scoped ESLint on all changed TypeScript files - `git diff --check` Repository-wide `pnpm lint` remains red on 52 existing errors across unrelated docs and scripts; the changed TypeScript files pass scoped ESLint.

Alberto Schiabel committed Jul 27, 2026 at 08:19 UTC 473e9d20ad2449c6011306526c02287ea261d7f7
10 files changed +396 -65
ts/e2e-tests/cli/version/README.md
+9 -6
@@ -10,15 +10,18 @@ The CLI separates decoration (stderr) from data (stdout). This suite ensures:
10 - stdout contains the version from `packages/cli/package.json`
11 - stderr is empty (no decoration leaks into piped output)
12 - Redirecting stdout to a file captures the clean version string
13 +- `composio version --check` emits deterministic JSON for known and unknown release states
14
15 ## What It Tests
16
16 -| Test | Description |
17 -| --- | --- |
18 -| Exit code | `composio version` returns 0 |
19 -| stdout | Output matches `package.json` version |
20 -| stderr | Empty when piped |
21 -| File redirect | `composio version > out.txt` captures the version in the file |
17 +| Test | Description |
18 +| ---------------- | ---------------------------------------------------------------- |
19 +| Exit code | `composio version` returns 0 |
20 +| stdout | Output matches `package.json` version |
21 +| stderr | Empty when piped |
22 +| File redirect | `composio version > out.txt` captures the version in the file |
23 +| Update available | `version --check` reports a newer cached stable version |
24 +| Unknown status | `version --check` does not report a failed refresh as up to date |
25
26 ## Requirements
27
ts/e2e-tests/cli/version/e2e.test.ts
+43 -1
@@ -4,7 +4,13 @@
4 * Verifies that the compiled composio CLI behaves correctly in a scratch container.
5 */
6
7 -import { e2e, sanitizeOutput, type E2ETestResult, type E2ETestResultWithFiles } from '@e2e-tests/utils';
7 +import {
8 + e2e,
9 + parseJsonStdout,
10 + sanitizeOutput,
11 + type E2ETestResult,
12 + type E2ETestResultWithFiles,
13 +} from '@e2e-tests/utils';
14 import { TIMEOUTS } from '@e2e-tests/utils/const';
15 import { describe, it, expect, beforeAll } from 'bun:test';
16 import cliPkg from '../../../packages/cli/package.json' with { type: 'json' };
@@ -16,10 +22,18 @@ e2e(import.meta.url, {
22 defineTests: ({ runCmd }) => {
23 const expectedVersion = String(cliPkg.version ?? '').trim();
24 let versionResult: E2ETestResult;
25 + let updateAvailableResult: E2ETestResult;
26 + let unknownStatusResult: E2ETestResult;
27 let redirectedResult: E2ETestResultWithFiles<'out.txt'>;
28
29 beforeAll(async () => {
30 versionResult = await runCmd('composio version');
31 + updateAvailableResult = await runCmd(
32 + `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`
33 + );
34 + unknownStatusResult = await runCmd(
35 + `mkdir -p .composio && printf '%s' '{"lastAttempted":"2099-01-01T00:00:00.000Z"}' > .composio/update-check.json.attempt && HOME="$PWD" composio version --check`
36 + );
37 redirectedResult = await runCmd({
38 command: 'composio version > out.txt',
39 files: ['out.txt'],
@@ -40,6 +54,34 @@ e2e(import.meta.url, {
54 });
55 });
56
57 + describe('composio version --check with a known update', () => {
58 + it('exits successfully with clean machine-readable output', () => {
59 + expect(updateAvailableResult.exitCode).toBe(0);
60 + expect(updateAvailableResult.stderr).toBe('');
61 + expect(parseJsonStdout(updateAvailableResult)).toEqual({
62 + current: expectedVersion,
63 + latestStable: '99.0.0',
64 + updateAvailable: true,
65 + checkStatus: 'update-available',
66 + lastChecked: '2099-01-01T00:00:00.000Z',
67 + });
68 + });
69 + });
70 +
71 + describe('composio version --check when the latest release is unknown', () => {
72 + it('exits successfully without claiming the current version is up to date', () => {
73 + expect(unknownStatusResult.exitCode).toBe(0);
74 + expect(unknownStatusResult.stderr).toBe('');
75 + expect(parseJsonStdout(unknownStatusResult)).toEqual({
76 + current: expectedVersion,
77 + latestStable: null,
78 + updateAvailable: false,
79 + checkStatus: 'unknown',
80 + lastChecked: null,
81 + });
82 + });
83 + });
84 +
85 describe('stdout redirection to out.txt', () => {
86 it('exits successfully', () => {
87 expect(redirectedResult.exitCode).toBe(0);
ts/packages/cli/CHANGELOG.md
+1
@@ -15,6 +15,7 @@
15
16 ### Patch Changes
17
18 +- 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.
19 - 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.
20 - 8467efd: Fix `composio whoami` reporting the API key's home organization after `composio orgs switch`. Session info requests now forward the selected global organization.
21 - 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.
ts/packages/cli/src/cli-main.ts
+1 -3
@@ -30,7 +30,7 @@ import { ProjectContext } from 'src/services/project-context';
30 import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
31 import { CommandRunner } from 'src/services/command-runner';
32 import { StdinLive } from 'src/services/stdin';
33 -import { showUpdateNotice, checkForUpdateInBackground } from 'src/services/update-check';
33 +import { showUpdateNotice } from 'src/services/update-check';
34 import {
35 createCliCommandTelemetryContext,
36 getPrimaryLifecycleFailedEvent,
@@ -173,8 +173,6 @@ const runWithTelemetry = Effect.gen(function* () {
173 );
174 });
175
176 -checkForUpdateInBackground();
177 -
176 showUpdateNotice.pipe(
177 Effect.andThen(runWithTelemetry),
178 Effect.catchIf(ValidationError.isValidationError, error => {
ts/packages/cli/src/commands/background-update-check.ts new
+44
@@ -0,0 +1,44 @@
1 +import { Command } from '@effect/cli';
2 +import { Effect, Option } from 'effect';
3 +import { versionCmd } from './version.cmd';
4 +import { checkForUpdateInBackground } from 'src/services/update-check';
5 +
6 +type RootCommandInput = {
7 + readonly subcommand: Option.Option<unknown>;
8 +};
9 +
10 +type ParsedSubcommand = readonly [commandTag: unknown, input: unknown];
11 +
12 +const isParsedSubcommand = (value: unknown): value is ParsedSubcommand =>
13 + Array.isArray(value) && value.length === 2;
14 +
15 +const isExplicitVersionCheck = (subcommand: Option.Option<unknown>): boolean =>
16 + Option.exists(subcommand, selected => {
17 + if (!isParsedSubcommand(selected) || selected[0] !== versionCmd.tag) {
18 + return false;
19 + }
20 +
21 + const input = selected[1];
22 + return typeof input === 'object' && input !== null && 'check' in input && input.check === true;
23 + });
24 +
25 +/**
26 + * Starts the background update request after @effect/cli has parsed the selected command.
27 + *
28 + * @effect/cli v3 retains the selected command tag alongside its parsed input at runtime,
29 + * even though the public root-input type erases that tuple.
30 + */
31 +export const withBackgroundUpdateCheck = <
32 + Name extends string,
33 + R,
34 + E,
35 + Input extends RootCommandInput,
36 +>(
37 + command: Command.Command<Name, R, E, Input>,
38 + start: () => void = checkForUpdateInBackground
39 +): Command.Command<Name, R, E, Input> =>
40 + command.pipe(
41 + Command.provideEffectDiscard(({ subcommand }) =>
42 + isExplicitVersionCheck(subcommand) ? Effect.void : Effect.sync(start)
43 + )
44 + );
ts/packages/cli/src/commands/index.ts
+2 -1
@@ -57,6 +57,7 @@ import {
57 import { CLI_EXPERIMENTAL_FEATURES } from 'src/constants';
58 import { installSkill, type SkillInstallTarget } from 'src/effects/install-skill';
59 import { experimental, type CommandVisibility, tagged, visibleValues } from './feature-tags';
60 +import { withBackgroundUpdateCheck } from './background-update-check';
61
62 const ROOT_COMMANDS = [
63 tagged(versionCmd),
@@ -452,7 +453,7 @@ export const runWithConfig = Effect.gen(function* () {
453 isExperimentalFeatureEnabled: feature => cliUserConfig.isExperimentalFeatureEnabled(feature),
454 };
455 const version = yield* getVersion;
455 - const rootCommand = buildRootCommand(visibility);
456 + const rootCommand = withBackgroundUpdateCheck(buildRootCommand(visibility));
457 const run = Command.run(rootCommand, {
458 name: 'composio',
459 executable: 'composio',
ts/packages/cli/src/commands/version.cmd.ts
+3 -1
@@ -8,7 +8,7 @@ import { bold, cyanBright } from 'src/ui/colors';
8 const check = Options.boolean('check').pipe(
9 Options.withDescription(
10 'Check for a newer stable release and print a machine-readable JSON status ' +
11 - '({current, latestStable, updateAvailable, lastChecked}). ' +
11 + '({current, latestStable, updateAvailable, checkStatus, lastChecked}). ' +
12 'Refreshes the release cache when it is older than 24 hours.'
13 )
14 );
@@ -34,6 +34,8 @@ export const versionCmd = Command.make('version', { check }).pipe(
34 yield* ui.log.info(
35 `Update available: ${status.current} → ${bold(cyanBright(status.latestStable))} — run ${cyanBright('composio upgrade')}`
36 );
37 + } else if (status.checkStatus === 'unknown') {
38 + yield* ui.log.warn('Unable to determine the latest stable Composio CLI release.');
39 } else {
40 yield* ui.log.info(`${status.current} is up to date.`);
41 }
ts/packages/cli/src/services/update-check.ts
+80 -40
@@ -41,6 +41,8 @@ export interface UpdateStatus {
41 latestStable: string | null;
42 /** True when a strictly newer stable release than `current` is available. */
43 updateAvailable: boolean;
44 + /** Whether the latest known state is current, actionable, or unavailable. */
45 + checkStatus: 'up-to-date' | 'update-available' | 'unknown';
46 /** When the release list was last fetched (ISO-8601), if ever. */
47 lastChecked: string | null;
48 }
@@ -52,7 +54,13 @@ const UpdateCheckStateSchema = Schema.parseJson(
54 })
55 );
56
55 -/** Non-2xx response from the GitHub releases API; swallowed after the state write. */
57 +const UpdateCheckAttemptSchema = Schema.parseJson(
58 + Schema.Struct({
59 + lastAttempted: Schema.String,
60 + })
61 +);
62 +
63 +/** Non-2xx GitHub response; recorded as a failed attempt and otherwise swallowed. */
64 class UpdateCheckHttpError extends Data.TaggedError('UpdateCheckHttpError')<{
65 readonly status: number;
66 }> {}
@@ -145,12 +153,20 @@ export function parseLatestVersionFromReleases(
153 // ── Factory ─────────────────────────────────────────────────────────────
154
155 export function createUpdateChecker(config: UpdateCheckConfig) {
156 + const attemptFile = `${config.stateFile}.attempt`;
157 +
158 const readState = Effect.gen(function* () {
159 const fs = yield* FileSystem.FileSystem;
160 const rawState = yield* fs.readFileString(config.stateFile);
161 return yield* Schema.decodeUnknown(UpdateCheckStateSchema)(rawState);
162 });
163
164 + const readAttempt = Effect.gen(function* () {
165 + const fs = yield* FileSystem.FileSystem;
166 + const rawAttempt = yield* fs.readFileString(attemptFile);
167 + return yield* Schema.decodeUnknown(UpdateCheckAttemptSchema)(rawAttempt);
168 + });
169 +
170 /**
171 * If a cached newer version is known, print a one-line hint to stderr.
172 * Reads a tiny JSON file and does a semver compare.
@@ -161,14 +177,15 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
177 if (!capabilities.isInteractive) return;
178
179 const state = yield* readState;
164 - if (!state.latestVersion || !semver.valid(state.latestVersion)) return;
165 - if (state.latestVersion === config.currentVersion) return;
180 + const latestVersion = semver.valid(state.latestVersion);
181 + const currentVersion = semver.valid(config.currentVersion);
182 + if (!latestVersion || !currentVersion || latestVersion === currentVersion) return;
183
184 // Only show when the cached version is strictly newer.
168 - if (!semver.gt(state.latestVersion, config.currentVersion)) return;
185 + if (!semver.gt(latestVersion, currentVersion)) return;
186
187 const msg =
171 - ` ${dim('Update available:')} ${dim(config.currentVersion)} ${dim('→')} ${bold(cyanBright(state.latestVersion))}\n` +
188 + ` ${dim('Update available:')} ${dim(config.currentVersion)} ${dim('→')} ${bold(cyanBright(latestVersion))}\n` +
189 ` ${dim('Run')} ${cyanBright('composio upgrade')} ${dim('to update')}\n`;
190
191 yield* terminal.error(`\n${msg}`);
@@ -185,15 +202,32 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
202 const checkForUpdate = Effect.gen(function* () {
203 const fs = yield* FileSystem.FileSystem;
204 const path = yield* Path.Path;
205 + const checkStartedAt = new Date();
206 + const checkStartedAtMs = checkStartedAt.getTime();
207 + const parseTimestamp = (value: string): number | undefined => {
208 + const timestamp = new Date(value).getTime();
209 + return Number.isFinite(timestamp) ? timestamp : undefined;
210 + };
211
212 // Throttle: skip if checked recently. A missing or corrupt state file
213 // just means "re-check".
214 const cachedState = yield* Effect.option(readState);
215 + const lastCheckedAt = Option.getOrUndefined(
216 + Option.map(cachedState, state => parseTimestamp(state.lastChecked))
217 + );
218 + if (lastCheckedAt !== undefined && checkStartedAtMs - lastCheckedAt < config.checkIntervalMs) {
219 + return { state: cachedState, refreshFailed: false } as const;
220 + }
221 + const failedAttempt = yield* Effect.option(readAttempt);
222 + const lastAttemptedAt = Option.getOrUndefined(
223 + Option.map(failedAttempt, attempt => parseTimestamp(attempt.lastAttempted))
224 + );
225 if (
193 - Option.isSome(cachedState) &&
194 - Date.now() - new Date(cachedState.value.lastChecked).getTime() < config.checkIntervalMs
226 + lastAttemptedAt !== undefined &&
227 + (lastCheckedAt === undefined || lastAttemptedAt > lastCheckedAt) &&
228 + checkStartedAtMs - lastAttemptedAt < config.checkIntervalMs
229 ) {
196 - return;
230 + return { state: cachedState, refreshFailed: true } as const;
231 }
232 const previousLatestVersion = Option.getOrUndefined(
233 Option.map(cachedState, state => state.latestVersion)
@@ -208,22 +242,10 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
242 headers.Authorization = `Bearer ${config.accessToken}`;
243 }
244
211 - // Always persist lastChecked to prevent retry loops when the fetch
212 - // fails or returns no matching releases with a matching binary.
213 - const writeState = (latestVersion?: string) =>
214 - fs.makeDirectory(path.dirname(config.stateFile), { recursive: true }).pipe(
215 - Effect.matchEffect({
216 - // If we can't create the directory, bail out silently.
217 - onFailure: () => Effect.void,
218 - onSuccess: () => {
219 - const state: UpdateCheckState = {
220 - lastChecked: new Date().toISOString(),
221 - latestVersion: latestVersion ?? previousLatestVersion ?? config.currentVersion,
222 - };
223 - return fs.writeFileString(config.stateFile, JSON.stringify(state, null, 2));
224 - },
225 - })
226 - );
245 + const writeJsonFile = (file: string, value: unknown) =>
246 + fs
247 + .makeDirectory(path.dirname(file), { recursive: true })
248 + .pipe(Effect.andThen(fs.writeFileString(file, JSON.stringify(value, null, 2))));
249
250 const fetchLatestVersion = Effect.gen(function* () {
251 const response = yield* Effect.tryPromise(() =>
@@ -236,12 +258,25 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
258 return parseLatestVersionFromReleases(releases, config.binaryAssetName);
259 });
260
239 - yield* fetchLatestVersion.pipe(
240 - Effect.flatMap(writeState),
241 - // Silently ignore fetch/parse errors — never block the CLI.
242 - // Still update the timestamp to prevent unbounded retry loops.
243 - Effect.catchAll(() => Effect.ignore(writeState()))
261 + const latestVersion = yield* Effect.option(fetchLatestVersion);
262 + if (Option.isNone(latestVersion)) {
263 + yield* Effect.ignore(
264 + writeJsonFile(attemptFile, {
265 + lastAttempted: checkStartedAt.toISOString(),
266 + })
267 + );
268 + return { state: cachedState, refreshFailed: true } as const;
269 + }
270 +
271 + const state: UpdateCheckState = {
272 + lastChecked: new Date().toISOString(),
273 + latestVersion: latestVersion.value ?? previousLatestVersion ?? config.currentVersion,
274 + };
275 + yield* writeJsonFile(config.stateFile, state).pipe(
276 + Effect.andThen(fs.remove(attemptFile, { force: true })),
277 + Effect.ignore
278 );
279 + return { state: Option.some(state), refreshFailed: false } as const;
280 });
281
282 /**
@@ -251,27 +286,32 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
286 */
287 const getUpdateStatus: Effect.Effect<UpdateStatus, never, FileSystem.FileSystem | Path.Path> =
288 Effect.gen(function* () {
254 - yield* checkForUpdate;
255 - const state = yield* Effect.option(readState);
289 + const { state, refreshFailed } = yield* checkForUpdate;
290
291 const cachedLatest = Option.getOrUndefined(Option.map(state, s => s.latestVersion));
258 - // The cache falls back to the current version when no release was found,
259 - // so a prerelease can leak into latestVersion — never report that as stable.
292 + const validLatest = cachedLatest ? semver.valid(cachedLatest) : null;
293 + const validCurrent = semver.valid(config.currentVersion);
294 const latestStable =
261 - cachedLatest && semver.valid(cachedLatest) && semver.prerelease(cachedLatest) === null
262 - ? cachedLatest
263 - : null;
295 + validLatest && semver.prerelease(validLatest) === null ? validLatest : null;
296 + const updateAvailable =
297 + validCurrent !== null && latestStable !== null && semver.gt(latestStable, validCurrent);
298 + const checkStatus = updateAvailable
299 + ? 'update-available'
300 + : refreshFailed || validCurrent === null || latestStable === null
301 + ? 'unknown'
302 + : 'up-to-date';
303
304 return {
305 current: config.currentVersion,
306 latestStable,
268 - updateAvailable: latestStable !== null && semver.gt(latestStable, config.currentVersion),
307 + updateAvailable,
308 + checkStatus,
309 lastChecked: Option.getOrElse(
310 Option.map(state, s => s.lastChecked),
311 () => null as string | null
312 ),
313 } satisfies UpdateStatus;
274 - }).pipe(Effect.orDie);
314 + });
315
316 return { showUpdateNotice, checkForUpdate, getUpdateStatus };
317 }
@@ -300,8 +340,8 @@ export const getUpdateStatus: Effect.Effect<UpdateStatus> = Effect.gen(function*
340
341 /** Fire-and-forget background fetch to GitHub. */
342 export function checkForUpdateInBackground(): void {
303 - // Runs from cli-main before the runtime boots; runPromiseExit never throws back
304 - // into the caller and checkForUpdate swallows its own failures.
343 + // Uses a detached runtime so short-lived command handlers do not interrupt the refresh.
344 + // runPromiseExit never throws into the caller, and checkForUpdate swallows its own failures.
345 void Effect.runPromiseExit(
346 Effect.gen(function* () {
347 const stateFile = yield* defaultStateFile;
ts/packages/cli/test/src/commands/background-update-check.test.ts new
+59
@@ -0,0 +1,59 @@
1 +import { Command } from '@effect/cli';
2 +import { describe, expect, layer, vi } from '@effect/vitest';
3 +import { Effect } from 'effect';
4 +import { $defaultCmd } from 'src/commands/$default.cmd';
5 +import { withBackgroundUpdateCheck } from 'src/commands/background-update-check';
6 +import { versionCmd } from 'src/commands/version.cmd';
7 +import { TestLive } from 'test/__utils__';
8 +
9 +const makeRunner = (start: () => void) => {
10 + const version = versionCmd.pipe(Command.withHandler(() => Effect.void));
11 + const other = Command.make('other').pipe(Command.withHandler(() => Effect.void));
12 + const root = $defaultCmd.pipe(Command.withSubcommands([version, other]), command =>
13 + withBackgroundUpdateCheck(command, start)
14 + );
15 +
16 + return Command.run(root, {
17 + name: 'composio',
18 + executable: 'composio',
19 + version: '0.0.0-test',
20 + });
21 +};
22 +
23 +describe('withBackgroundUpdateCheck', () => {
24 + layer(TestLive())(it => {
25 + it.scoped('skips the background request for an explicit version check', () =>
26 + Effect.gen(function* () {
27 + const start = vi.fn();
28 +
29 + yield* makeRunner(start)(['node', 'composio', 'version', '--check']);
30 +
31 + expect(start).not.toHaveBeenCalled();
32 + })
33 + );
34 +
35 + it.scoped('uses parsed root options when identifying an explicit version check', () =>
36 + Effect.gen(function* () {
37 + const start = vi.fn();
38 + const run = makeRunner(start);
39 +
40 + yield* run(['node', 'composio', '--log-level', 'debug', 'version', '--check']);
41 + yield* run(['node', 'composio', '--log-level=debug', 'version', '--check']);
42 +
43 + expect(start).not.toHaveBeenCalled();
44 + })
45 + );
46 +
47 + it.scoped('starts the background request for other parsed commands', () =>
48 + Effect.gen(function* () {
49 + const start = vi.fn();
50 + const run = makeRunner(start);
51 +
52 + yield* run(['node', 'composio', 'version']);
53 + yield* run(['node', 'composio', 'other']);
54 +
55 + expect(start).toHaveBeenCalledTimes(2);
56 + })
57 + );
58 + });
59 +});
ts/packages/cli/test/src/services/update-check.test.ts
+154 -13
@@ -3,7 +3,7 @@ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync
3 import { dirname, join } from 'node:path';
4 import { tmpdir } from 'node:os';
5 import { BunFileSystem, BunPath } from '@effect/platform-bun';
6 -import { Effect, Layer } from 'effect';
6 +import { Effect, Fiber, Layer } from 'effect';
7 import { withHttpServerEffect } from 'test/__utils__/http-server';
8 import type { TerminalUI } from 'src/services/terminal-ui';
9 import {
@@ -71,6 +71,16 @@ function makeReleasesPayload(versions: string[], assetName = 'composio-darwin-aa
71 }));
72 }
73
74 +function makeDeferred<T>() {
75 + let resolve!: (value: T | PromiseLike<T>) => void;
76 + let reject!: (reason?: unknown) => void;
77 + const promise = new Promise<T>((resolvePromise, rejectPromise) => {
78 + resolve = resolvePromise;
79 + reject = rejectPromise;
80 + });
81 + return { promise, resolve, reject };
82 +}
83 +
84 // ── parseLatestVersionFromReleases (pure) ───────────────────────────────
85
86 describe('parseLatestVersionFromReleases', () => {
@@ -264,12 +274,13 @@ describe('getUpdateStatus', () => {
274 current: '0.2.0',
275 latestStable: '0.3.0',
276 updateAvailable: true,
277 + checkStatus: 'update-available',
278 lastChecked: expect.any(String),
279 });
280 }).pipe(Effect.provide(PlatformLayers))
281 );
282
272 - it.effect('reports no update when the fetch fails and no cache exists', () =>
283 + it.effect('reports an unknown status when the fetch fails and no cache exists', () =>
284 Effect.gen(function* () {
285 const config = makeConfig({
286 currentVersion: '0.2.0',
@@ -279,8 +290,36 @@ describe('getUpdateStatus', () => {
290
291 const status = yield* getUpdateStatus;
292
282 - expect(status.updateAvailable).toBe(false);
283 - expect(status.lastChecked).toEqual(expect.any(String));
293 + expect(status).toEqual({
294 + current: '0.2.0',
295 + latestStable: null,
296 + updateAvailable: false,
297 + checkStatus: 'unknown',
298 + lastChecked: null,
299 + });
300 + expect(existsSync(config.stateFile)).toBe(false);
301 + }).pipe(Effect.provide(PlatformLayers))
302 + );
303 +
304 + it.effect('does not call a stale cached version up to date after a failed refresh', () =>
305 + Effect.gen(function* () {
306 + const config = makeConfig({
307 + currentVersion: '0.2.0',
308 + fetchFn: vi.fn().mockRejectedValue(new Error('offline')) as unknown as typeof fetch,
309 + });
310 + const lastChecked = '2020-01-01T00:00:00.000Z';
311 + writeState(config, { lastChecked, latestVersion: '0.2.0' });
312 + const { getUpdateStatus } = createUpdateChecker(config);
313 +
314 + const status = yield* getUpdateStatus;
315 +
316 + expect(status).toEqual({
317 + current: '0.2.0',
318 + latestStable: '0.2.0',
319 + updateAvailable: false,
320 + checkStatus: 'unknown',
321 + lastChecked,
322 + });
323 }).pipe(Effect.provide(PlatformLayers))
324 );
325
@@ -297,6 +336,7 @@ describe('getUpdateStatus', () => {
336
337 expect(status.latestStable).toBeNull();
338 expect(status.updateAvailable).toBe(false);
339 + expect(status.checkStatus).toBe('unknown');
340 }).pipe(Effect.provide(PlatformLayers))
341 );
342
@@ -315,6 +355,25 @@ describe('getUpdateStatus', () => {
355 expect(fetchFn).not.toHaveBeenCalled();
356 expect(status.latestStable).toBe('0.2.1');
357 expect(status.updateAvailable).toBe(true);
358 + expect(status.checkStatus).toBe('update-available');
359 + }).pipe(Effect.provide(PlatformLayers))
360 + );
361 +
362 + it.effect('reports an unknown status for an invalid installed version', () =>
363 + Effect.gen(function* () {
364 + const config = makeConfig({ currentVersion: 'corrupt-tag' });
365 + writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });
366 + const { getUpdateStatus } = createUpdateChecker(config);
367 +
368 + const status = yield* getUpdateStatus;
369 +
370 + expect(status).toEqual({
371 + current: 'corrupt-tag',
372 + latestStable: '0.3.0',
373 + updateAvailable: false,
374 + checkStatus: 'unknown',
375 + lastChecked: expect.any(String),
376 + });
377 }).pipe(Effect.provide(PlatformLayers))
378 );
379 });
@@ -466,7 +525,7 @@ describe('checkForUpdate', () => {
525 }).pipe(Effect.provide(PlatformLayers))
526 );
527
469 - it.effect('writes lastChecked on HTTP errors to prevent retry loops', () =>
528 + it.effect('does not create authoritative state after an HTTP error', () =>
529 Effect.gen(function* () {
530 const config = makeConfig({
531 fetchFn: vi.fn().mockResolvedValue({
@@ -479,14 +538,11 @@ describe('checkForUpdate', () => {
538 // Should not fail
539 yield* checkForUpdate;
540
482 - expect(existsSync(config.stateFile)).toBe(true);
483 - const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
484 - expect(state.lastChecked).toBeDefined();
485 - expect(state.latestVersion).toBe(config.currentVersion);
541 + expect(existsSync(config.stateFile)).toBe(false);
542 }).pipe(Effect.provide(PlatformLayers))
543 );
544
489 - it.effect('writes lastChecked on network errors to prevent retry loops', () =>
545 + it.effect('does not create authoritative state after a network error', () =>
546 Effect.gen(function* () {
547 const config = makeConfig({
548 fetchFn: vi.fn().mockRejectedValue(new Error('DNS failed')) as unknown as typeof fetch,
@@ -495,10 +551,95 @@ describe('checkForUpdate', () => {
551
552 yield* checkForUpdate;
553
498 - expect(existsSync(config.stateFile)).toBe(true);
554 + expect(existsSync(config.stateFile)).toBe(false);
555 + }).pipe(Effect.provide(PlatformLayers))
556 + );
557 +
558 + it.effect('throttles repeated network errors without creating authoritative state', () =>
559 + Effect.gen(function* () {
560 + const fetchFn = vi.fn().mockRejectedValue(new Error('DNS failed'));
561 + const config = makeConfig({ fetchFn: fetchFn as unknown as typeof fetch });
562 + const { checkForUpdate } = createUpdateChecker(config);
563 +
564 + yield* checkForUpdate;
565 + yield* checkForUpdate;
566 +
567 + expect(fetchFn).toHaveBeenCalledOnce();
568 + expect(existsSync(config.stateFile)).toBe(false);
569 + expect(existsSync(`${config.stateFile}.attempt`)).toBe(true);
570 + }).pipe(Effect.provide(PlatformLayers))
571 + );
572 +
573 + it.effect('preserves stale successful state after a network error', () =>
574 + Effect.gen(function* () {
575 + const config = makeConfig({
576 + fetchFn: vi.fn().mockRejectedValue(new Error('DNS failed')) as unknown as typeof fetch,
577 + });
578 + const previousState: UpdateCheckState = {
579 + lastChecked: staleLastChecked,
580 + latestVersion: '0.3.0',
581 + };
582 + writeState(config, previousState);
583 + const { checkForUpdate } = createUpdateChecker(config);
584 +
585 + yield* checkForUpdate;
586 +
587 const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
500 - expect(state.lastChecked).toBeDefined();
501 - expect(state.latestVersion).toBe(config.currentVersion);
588 + expect(state).toEqual(previousState);
589 + }).pipe(Effect.provide(PlatformLayers))
590 + );
591 +
592 + it.effect('does not let an older failed check supersede successful state', () =>
593 + Effect.gen(function* () {
594 + const failedResponse = makeDeferred<Response>();
595 + const failedRequestStarted = makeDeferred<void>();
596 + const failingConfig = makeConfig({
597 + fetchFn: vi.fn(() => {
598 + failedRequestStarted.resolve();
599 + return failedResponse.promise;
600 + }),
601 + });
602 + const successfulConfig = makeConfig({
603 + fetchFn: vi.fn().mockResolvedValue({
604 + ok: true,
605 + json: () => Promise.resolve(makeReleasesPayload(['0.3.0'])),
606 + }) as unknown as typeof fetch,
607 + });
608 + const failingFiber = yield* Effect.fork(createUpdateChecker(failingConfig).checkForUpdate);
609 +
610 + yield* Effect.promise(() => failedRequestStarted.promise);
611 + const successfulAt = new Date(pinnedNow.getTime() + 60_000);
612 + yield* Effect.sync(() => vi.setSystemTime(successfulAt));
613 + yield* createUpdateChecker(successfulConfig).checkForUpdate;
614 + yield* Effect.sync(() => vi.setSystemTime(new Date(successfulAt.getTime() + 60_000)));
615 + yield* Effect.sync(() => failedResponse.reject(new Error('transient failure')));
616 + yield* Fiber.join(failingFiber);
617 +
618 + const state: UpdateCheckState = JSON.parse(readFileSync(failingConfig.stateFile, 'utf-8'));
619 + expect(state).toEqual({
620 + lastChecked: successfulAt.toISOString(),
621 + latestVersion: '0.3.0',
622 + });
623 + expect(JSON.parse(readFileSync(`${failingConfig.stateFile}.attempt`, 'utf-8'))).toEqual({
624 + lastAttempted: pinnedNow.toISOString(),
625 + });
626 +
627 + const recoveryFetch = vi.fn().mockResolvedValue({
628 + ok: true,
629 + json: () => Promise.resolve(makeReleasesPayload(['0.4.0'])),
630 + });
631 + yield* Effect.sync(() =>
632 + vi.setSystemTime(new Date(successfulAt.getTime() + failingConfig.checkIntervalMs + 1))
633 + );
634 + yield* createUpdateChecker(makeConfig({ fetchFn: recoveryFetch as unknown as typeof fetch }))
635 + .checkForUpdate;
636 +
637 + expect(recoveryFetch).toHaveBeenCalledOnce();
638 + const refreshedState: UpdateCheckState = JSON.parse(
639 + readFileSync(failingConfig.stateFile, 'utf-8')
640 + );
641 + expect(refreshedState.latestVersion).toBe('0.4.0');
642 + expect(existsSync(`${failingConfig.stateFile}.attempt`)).toBe(false);
643 }).pipe(Effect.provide(PlatformLayers))
644 );
645