@devries-cameron20 / composio Mirror · read-only / commits / 7d586e0ba
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.

Mirrored from https://github.com/Camo67/composio.git

Synced Nov 21, 07:15 UTC

fix(cli): stop showing a stale update hint during composio upgrade (#5041)

This PR: - Skips the cached "Update available" hint when the command is `composio upgrade`. That command resolves the latest release live, so the cached line could only repeat it or name an older version. Other commands still print the hint. - Skips the background update-check request for `composio upgrade`, which already talks to GitHub itself. - Records the result in `~/.composio/update-check.json` (same schema, `lastChecked` = now) when `composio upgrade` resolves the latest stable release live. It reuses the update checker's state writer, and a failed write is ignored so it never fails the upgrade. - Leaves the cache alone for `composio upgrade <version>`, `--beta`, and a `COMPOSIO_GITHUB_TAG`/`GITHUB_TAG` pin, because the cache only holds the latest stable release. - Adds tests for each case and a `## Unreleased` CHANGELOG entry. ## Context CLI 0.5.0 was released as stable at 2026-10-21T16:10Z. On 0.4.2, `composio upgrade` printed: ``` Update available: 0.4.2 → 0.4.5 Run composio upgrade to update ┌ composio upgrade ◇ Upgrade completed! ``` and `composio -v` then printed 0.5.0. The hint came from `~/.composio/update-check.json`, `{"lastChecked":"2026-10-21T14:31:56.646Z","latestVersion":"0.4.5"}`, which was written before 0.5.0 existed and is refreshed at most once every 24 hours.

Alberto Schiabel committed Oct 27, 2026 at 13:25 UTC 7d586e0ba7f0b3b5e2497bd8368486018a888786
8 files changed +243 -29
ts/packages/cli/CHANGELOG.md
+7
@@ -12,6 +12,13 @@
12
13 ### Patch Changes
14
15 +- `composio upgrade` no longer starts with a stale "Update available" line.
16 + The line came from the cached daily update check, so right after a release
17 + it could name an older version than the one `composio upgrade` then
18 + installed. Upgrading also refreshes that cache with the latest stable release
19 + it found, so later commands stop suggesting an older version. Installing a
20 + specific version, a beta, or a pinned release tag leaves the cache unchanged.
21 +
22 - `composio proxy` now enforces the consumer permission policy that
23 `composio execute` enforces, checked against the connected account the
24 request uses. A denied request fails with the same permission error, and a
ts/packages/cli/src/cli-main.ts
+1 -1
@@ -298,7 +298,7 @@ const warnOnBackendMismatch = Effect.gen(function* () {
298
299 const cliProgram = (argv: ReadonlyArray<string>) =>
300 warnOnBackendMismatch.pipe(
301 - Effect.andThen(showUpdateNotice),
301 + Effect.andThen(showUpdateNotice(argv)),
302 Effect.andThen(showPluginAcquisitionHint(argv)),
303 Effect.andThen(runWithTelemetry(argv)),
304 Effect.catchIf(
ts/packages/cli/src/commands/background-update-check.ts
+7 -2
@@ -1,14 +1,19 @@
1 import { Effect, Predicate } from 'effect';
2 import { Command } from 'effect/cli';
3 import { versionCmd } from './version.cmd';
4 +import { upgradeCmd } from './upgrade/upgrade.cmd';
5 import { checkForUpdateInBackground } from 'src/services/update-check';
6
7 const isExplicitVersionCheck = (commandName: string, input: unknown): boolean =>
8 commandName === versionCmd.name && Predicate.hasProperty(input, 'check') && input.check === true;
9
10 +/** `composio upgrade` resolves releases itself and records a live stable result in the cache. */
11 +const resolvesReleasesItself = (commandName: string, input: unknown): boolean =>
12 + commandName === upgradeCmd.name || isExplicitVersionCheck(commandName, input);
13 +
14 /**
15 * Builds the root command so the background update request starts only after the CLI has parsed
11 - * the selected command, and never for an explicit `composio version --check`.
16 + * the selected command, and never for an explicit `composio version --check` or `composio upgrade`.
17 *
18 * `effect/cli` keeps the selected subcommand private to the parent's dispatcher, so the
19 * hook is attached per subcommand (each sees its own parsed input) plus the root itself for the
@@ -30,7 +35,7 @@ export const withBackgroundUpdateCheck = <
35 const guarded = subcommands.map(subcommand =>
36 subcommand.pipe(
37 Command.provideEffectDiscard((input: unknown) =>
33 - isExplicitVersionCheck(subcommand.name, input) ? Effect.void : startInBackground
38 + resolvesReleasesItself(subcommand.name, input) ? Effect.void : startInBackground
39 )
40 )
41 ) as unknown as Subcommands;
ts/packages/cli/src/services/update-check.ts
+62 -21
@@ -5,6 +5,7 @@ import { Data, Effect, Layer, Option, Predicate, Schema } from 'effect';
5 import semver from 'semver';
6 import { bold, cyanBright, dim } from 'src/ui/colors';
7 import { GITHUB_CONFIG } from 'src/config';
8 +import { rootCommandIndex } from 'src/utils/cli-args';
9 import { APP_VERSION } from '../constants';
10 import { NodeOs, type NodeOsShape } from './node-os';
11 import { resolveRunningCliVersion } from './run-companion-modules';
@@ -27,6 +28,12 @@ import { TerminalUI } from './terminal-ui';
28
29 const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
30
31 +/**
32 + * `composio upgrade` resolves the latest release live, so a cached hint printed before it runs
33 + * could only repeat that answer or contradict it with an older version.
34 + */
35 +const UPGRADE_COMMAND_NAME = 'upgrade';
36 +
37 /** Matches `@composio/cli@<semver>` — excludes prereleases. */
38 const CLI_RELEASE_TAG_RE = /^@composio\/cli@(\d+\.\d+\.\d+)$/;
39
@@ -122,6 +129,26 @@ const defaultConfig = (stateFile: string) =>
129 } satisfies UpdateCheckConfig;
130 });
131
132 +const attemptFileFor = (stateFile: string) => `${stateFile}.attempt`;
133 +
134 +const writeJsonFile = (file: string, value: unknown) =>
135 + Effect.gen(function* () {
136 + const fs = yield* FileSystem.FileSystem;
137 + const path = yield* Path.Path;
138 + yield* fs.makeDirectory(path.dirname(file), { recursive: true });
139 + yield* fs.writeFileString(file, JSON.stringify(value, null, 2));
140 + });
141 +
142 +/** Persist a successful check and clear any failed-attempt marker it supersedes. */
143 +const writeState = (stateFile: string, state: UpdateCheckState) =>
144 + writeJsonFile(stateFile, state).pipe(
145 + Effect.andThen(
146 + Effect.flatMap(FileSystem.FileSystem, fs =>
147 + fs.remove(attemptFileFor(stateFile), { force: true })
148 + )
149 + )
150 + );
151 +
152 // ── Pure helpers ────────────────────────────────────────────────────────
153
154 /** Extract the highest stable semver from GitHub releases that include the required binary. */
@@ -160,7 +187,7 @@ export function parseLatestVersionFromReleases(
187 // ── Factory ─────────────────────────────────────────────────────────────
188
189 export function createUpdateChecker(config: UpdateCheckConfig) {
163 - const attemptFile = `${config.stateFile}.attempt`;
190 + const attemptFile = attemptFileFor(config.stateFile);
191
192 const readState = Effect.gen(function* () {
193 const fs = yield* FileSystem.FileSystem;
@@ -176,10 +203,15 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
203
204 /**
205 * If a cached newer version is known, print a one-line hint to stderr.
179 - * Reads a tiny JSON file and does a semver compare.
206 + * Reads a tiny JSON file and does a semver compare. Skipped for `composio upgrade`.
207 */
181 - function showUpdateNotice(terminal: Pick<TerminalUI, 'capabilities' | 'error'>) {
208 + function showUpdateNotice(
209 + terminal: Pick<TerminalUI, 'capabilities' | 'error'>,
210 + commandName?: string
211 + ) {
212 return Effect.gen(function* () {
213 + if (commandName === UPGRADE_COMMAND_NAME) return;
214 +
215 // `terminal.error` writes even when stderr is redirected, so gate this
216 // advisory notice explicitly while leaving stdout out of the decision.
217 const { canDecorate } = yield* terminal.capabilities;
@@ -209,8 +241,6 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
241 * propagate back into the fire-and-forget caller.
242 */
243 const checkForUpdate = Effect.gen(function* () {
212 - const fs = yield* FileSystem.FileSystem;
213 - const path = yield* Path.Path;
244 const checkStartedAt = new Date();
245 const checkStartedAtMs = checkStartedAt.getTime();
246 const parseTimestamp = (value: string): number | undefined => {
@@ -251,11 +281,6 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
281 headers.Authorization = `Bearer ${config.accessToken}`;
282 }
283
254 - const writeJsonFile = (file: string, value: unknown) =>
255 - fs
256 - .makeDirectory(path.dirname(file), { recursive: true })
257 - .pipe(Effect.andThen(fs.writeFileString(file, JSON.stringify(value, null, 2))));
258 -
284 const fetchLatestVersion = Effect.gen(function* () {
285 const response = yield* Effect.tryPromise(() =>
286 config.fetchFn(config.releasesUrl, { headers, signal: AbortSignal.timeout(10_000) })
@@ -281,10 +306,7 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
306 lastChecked: new Date().toISOString(),
307 latestVersion: latestVersion.value ?? previousLatestVersion ?? config.currentVersion,
308 };
284 - yield* writeJsonFile(config.stateFile, state).pipe(
285 - Effect.andThen(fs.remove(attemptFile, { force: true })),
286 - Effect.ignore
287 - );
309 + yield* writeState(config.stateFile, state).pipe(Effect.ignore);
310 return { state: Option.some(state), refreshFailed: false } as const;
311 });
312
@@ -326,13 +348,32 @@ export function createUpdateChecker(config: UpdateCheckConfig) {
348
349 const DefaultConfigLayers = Layer.mergeAll(Path.layer, NodeOs.Default, BunFileSystem.layer);
350
329 -/** Print upgrade hint to stderr if a newer version is cached. */
330 -export const showUpdateNotice = Effect.gen(function* () {
331 - const terminal = yield* TerminalUI;
332 - const stateFile = yield* defaultStateFile;
333 - const config = yield* defaultConfig(stateFile);
334 - yield* createUpdateChecker(config).showUpdateNotice(terminal);
335 -}).pipe(Effect.provide(DefaultConfigLayers));
351 +/** Print upgrade hint to stderr if a newer version is cached, unless argv runs `composio upgrade`. */
352 +export const showUpdateNotice = (argv: ReadonlyArray<string>) =>
353 + Effect.gen(function* () {
354 + const terminal = yield* TerminalUI;
355 + const stateFile = yield* defaultStateFile;
356 + const config = yield* defaultConfig(stateFile);
357 + const args = argv.slice(2);
358 + yield* createUpdateChecker(config).showUpdateNotice(terminal, args[rootCommandIndex(args)]);
359 + }).pipe(Effect.provide(DefaultConfigLayers));
360 +
361 +/**
362 + * Record a live-resolved latest stable release (e.g. `@composio/cli@0.5.0`) as the cached update
363 + * check, so later hints agree with what `composio upgrade` just saw. Tags that are not a stable
364 + * CLI release are ignored, and a failed write is swallowed: the cache is advisory.
365 + */
366 +export const recordLatestStableRelease = (releaseTag: string) =>
367 + Option.fromNullishOr(CLI_RELEASE_TAG_RE.exec(releaseTag)?.[1]).pipe(
368 + Option.match({
369 + onNone: () => Effect.void,
370 + onSome: latestVersion =>
371 + Effect.gen(function* () {
372 + const stateFile = yield* defaultStateFile;
373 + yield* writeState(stateFile, { lastChecked: new Date().toISOString(), latestVersion });
374 + }).pipe(Effect.ignore),
375 + })
376 + );
377
378 /**
379 * Refresh the release cache if stale and return a machine-readable status.
ts/packages/cli/src/services/upgrade-binary.ts
+7 -1
@@ -25,6 +25,8 @@ import { atomicReplaceFile, type AtomicReplaceError } from 'src/utils/atomic-rep
25 import { extractZipSafely } from 'src/utils/extract-zip-safely';
26 import { renderPrettyError } from './utils/pretty-error';
27 import { TerminalUI } from './terminal-ui';
28 +import type { NodeOs } from './node-os';
29 +import { recordLatestStableRelease } from './update-check';
30 import {
31 collectExpectedRunCompanionAssetRelativePaths,
32 RUN_COMPANION_RELEASE_TAG_FILENAME,
@@ -118,7 +120,7 @@ const fetchLatestRelease = (
120 prerelease?: boolean;
121 tag?: string;
122 } = {}
121 -): Effect.Effect<GitHubRelease, UpgradeBinaryError, never> =>
123 +): Effect.Effect<GitHubRelease, UpgradeBinaryError, NodeOs> =>
124 Effect.gen(function* () {
125 const { githubConfig, httpClient } = ctx;
126 const prerelease = options.prerelease ?? false;
@@ -161,6 +163,10 @@ const fetchLatestRelease = (
163 );
164
165 yield* Effect.logDebug(`Resolved latest CLI release tag: ${latest.tag_name}`);
166 + // Only an unpinned stable lookup answers what the update-check cache stores.
167 + if (!prerelease) {
168 + yield* provideFsAndPath(ctx, recordLatestStableRelease(latest.tag_name));
169 + }
170 return latest;
171 }),
172 onSome: Effect.fn(function* (tag) {
ts/packages/cli/test/src/commands/background-update-check.test.ts
+17 -1
@@ -3,13 +3,15 @@ import { Effect } from 'effect';
3 import { Command } from 'effect/cli';
4 import { $defaultCmd } from 'src/commands/$default.cmd';
5 import { withBackgroundUpdateCheck } from 'src/commands/background-update-check';
6 +import { upgradeCmd } from 'src/commands/upgrade/upgrade.cmd';
7 import { versionCmd } from 'src/commands/version.cmd';
8 import { TestLive } from 'test/__utils__';
9
10 const makeRunner = (start: () => void) => {
11 const version = versionCmd.pipe(Command.withHandler(() => Effect.void));
12 + const upgrade = upgradeCmd.pipe(Command.withHandler(() => Effect.void));
13 const other = Command.make('other').pipe(Command.withHandler(() => Effect.void));
12 - const root = withBackgroundUpdateCheck($defaultCmd, [version, other], start);
14 + const root = withBackgroundUpdateCheck($defaultCmd, [version, upgrade, other], start);
15
16 return Command.runWith(root, { version: '0.0.0-test' });
17 };
@@ -38,6 +40,20 @@ describe('withBackgroundUpdateCheck', () => {
40 })
41 );
42
43 + it.effect(
44 + 'skips the background request for composio upgrade, which resolves releases live',
45 + () =>
46 + Effect.gen(function* () {
47 + const start = vi.fn();
48 + const run = makeRunner(start);
49 +
50 + yield* run(['upgrade']);
51 + yield* run(['--log-level', 'Debug', 'upgrade', '--beta']);
52 +
53 + expect(start).not.toHaveBeenCalled();
54 + })
55 + );
56 +
57 it.effect('starts the background request for other parsed commands', () =>
58 Effect.gen(function* () {
59 const start = vi.fn();
ts/packages/cli/test/src/services/update-check.test.ts
+15
@@ -221,6 +221,21 @@ describe('showUpdateNotice', () => {
221 }).pipe(Effect.provide(PlatformLayers))
222 );
223
224 + it.effect('skips the cached hint for composio upgrade but keeps it for other commands', () =>
225 + Effect.gen(function* () {
226 + const config = makeConfig({ currentVersion: '0.4.2' });
227 + writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.4.5' });
228 + const { showUpdateNotice } = createUpdateChecker(config);
229 +
230 + yield* showUpdateNotice(makeTerminal(output), 'upgrade');
231 + expect(output).toEqual([]);
232 +
233 + yield* showUpdateNotice(makeTerminal(output), 'tools');
234 + expect(output).toHaveLength(1);
235 + expect(output[0]).toContain('0.4.5');
236 + }).pipe(Effect.provide(PlatformLayers))
237 + );
238 +
239 it.effect('does not print upgrade hint when stderr is captured', () =>
240 Effect.gen(function* () {
241 const config = makeConfig({ currentVersion: '0.2.0' });
ts/packages/cli/test/src/services/upgrade-binary.test.ts
+127 -3
@@ -1,5 +1,8 @@
1 -import { describe, expect, it, vi } from '@effect/vitest';
2 -import { ConfigProvider, Effect, Layer, Option } from 'effect';
1 +import { afterAll, afterEach, describe, expect, it, vi } from '@effect/vitest';
2 +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3 +import { tmpdir } from 'node:os';
4 +import { join } from 'node:path';
5 +import { ConfigProvider, Effect, Exit, Layer, Option } from 'effect';
6 import { FetchHttpClient } from 'effect/http';
7 import * as FileSystem from 'effect/FileSystem';
8 import * as Path from 'effect/Path';
@@ -55,10 +58,17 @@ const TerminalUINoop = Layer.succeed(
58 })
59 );
60
61 +// A private home directory: stable-channel lookups record the update-check cache under it.
62 +const testHomedir = mkdtempSync(join(tmpdir(), 'composio-upgrade-home-'));
63 +const updateCheckDir = join(testHomedir, '.composio');
64 +const updateCheckFile = join(updateCheckDir, 'update-check.json');
65 +afterEach(() => rmSync(updateCheckDir, { recursive: true, force: true }));
66 +afterAll(() => rmSync(testHomedir, { recursive: true, force: true }));
67 +
68 const NodeOsTest = Layer.succeed(
69 NodeOs,
70 NodeOs.of({
61 - homedir: '/tmp',
71 + homedir: testHomedir,
72 tmpdir: '/tmp',
73 platform: 'darwin',
74 arch: 'arm64',
@@ -688,6 +698,120 @@ describe('UpgradeBinary', () => {
698 });
699 });
700
701 +describe('UpgradeBinary update-check cache', () => {
702 + // The cache that misled the user: written before 0.5.0 was released.
703 + const staleState = { lastChecked: '2026-10-21T14:31:56.646Z', latestVersion: '0.4.5' };
704 +
705 + const writeStaleState = () => {
706 + mkdirSync(updateCheckDir, { recursive: true });
707 + writeFileSync(updateCheckFile, JSON.stringify(staleState));
708 + };
709 +
710 + const readCachedState = (): unknown => JSON.parse(readFileSync(updateCheckFile, 'utf8'));
711 +
712 + const release = (version: string) => ({
713 + tag_name: `@composio/cli@${version}`,
714 + draft: false,
715 + prerelease: version.includes('-'),
716 + assets: [
717 + {
718 + name: 'composio-darwin-aarch64.zip',
719 + browser_download_url: `http://127.0.0.1/${version}.zip`,
720 + },
721 + ],
722 + });
723 +
724 + /** Serves the release list, plus any single release by tag, and installs `currentTag`. */
725 + const setUpReleases = (currentTag: string) =>
726 + Effect.gen(function* () {
727 + const fs = yield* FileSystem.FileSystem;
728 + const path = yield* Path.Path;
729 + const installDir = yield* fs.makeTempDirectoryScoped({ prefix: 'composio-upgrade-cache-' });
730 + yield* fs.writeFileString(path.join(installDir, 'release-tag.txt'), `${currentTag}\n`);
731 + vi.spyOn(process, 'execPath', 'get').mockReturnValue(path.join(installDir, 'composio'));
732 +
733 + const apiBaseUrl = yield* scopedHttpServer((req, res) => {
734 + res.writeHead(200, { 'content-type': 'application/json' });
735 + const taggedPrefix = '/repos/test-owner/test-repo/releases/tags/';
736 + res.end(
737 + JSON.stringify(
738 + req.url?.startsWith(taggedPrefix)
739 + ? release(decodeURIComponent(req.url.slice(taggedPrefix.length)).split('@').at(-1)!)
740 + : [release('0.5.1-beta.1'), release('0.5.0'), release('0.4.5'), release('0.4.2')]
741 + )
742 + );
743 + });
744 +
745 + return [
746 + ['COMPOSIO_GITHUB_API_BASE_URL', apiBaseUrl],
747 + ['COMPOSIO_GITHUB_OWNER', 'test-owner'],
748 + ['COMPOSIO_GITHUB_REPO', 'test-repo'],
749 + ] as Array<[string, string]>;
750 + });
751 +
752 + it.effect('records the live-resolved latest stable release', () => {
753 + vi.stubGlobal('Bun', { which: vi.fn(() => null) });
754 + // Only Date is faked: the upgrade awaits a real local HTTP server.
755 + vi.useFakeTimers({ toFake: ['Date'] });
756 + vi.setSystemTime(new Date('2026-10-21T16:20:00.000Z'));
757 +
758 + return Effect.gen(function* () {
759 + writeStaleState();
760 + const config = yield* setUpReleases('@composio/cli@0.5.0');
761 +
762 + const result = yield* runUpgradeSuccess(config);
763 +
764 + expect(result).toBeUndefined();
765 + expect(readCachedState()).toEqual({
766 + lastChecked: '2026-10-21T16:20:00.000Z',
767 + latestVersion: '0.5.0',
768 + });
769 + }).pipe(
770 + Effect.provide(TestPlatform),
771 + Effect.ensuring(Effect.sync(() => vi.useRealTimers())),
772 + Effect.ensuring(restoreStubsAndMocks)
773 + );
774 + });
775 +
776 + it.effect.each([
777 + { target: 'a version argument', options: { tag: '@composio/cli@0.4.2' }, env: [] },
778 + {
779 + target: 'COMPOSIO_GITHUB_TAG',
780 + options: {},
781 + env: [['COMPOSIO_GITHUB_TAG', '@composio/cli@0.4.2']] as Array<[string, string]>,
782 + },
783 + { target: '--beta', options: { prerelease: true }, env: [] },
784 + ])('leaves the cache alone when $target picks the target', ({ options, env }) => {
785 + vi.stubGlobal('Bun', { which: vi.fn(() => null) });
786 +
787 + return Effect.gen(function* () {
788 + writeStaleState();
789 + const config = yield* setUpReleases('@composio/cli@0.4.0');
790 +
791 + // The download is unreachable, so only the release lookup could have touched the cache.
792 + const exit = yield* Effect.exit(makeUpgradeEffect([...config, ...env], options));
793 +
794 + expect(Exit.isFailure(exit)).toBe(true);
795 + expect(readCachedState()).toEqual(staleState);
796 + }).pipe(Effect.provide(TestPlatform), Effect.ensuring(restoreStubsAndMocks));
797 + });
798 +
799 + it.effect('still upgrades when the cache cannot be written', () => {
800 + vi.stubGlobal('Bun', { which: vi.fn(() => null) });
801 +
802 + return Effect.gen(function* () {
803 + // A file where the cache directory should be makes every cache write fail.
804 + writeFileSync(updateCheckDir, 'not a directory');
805 + const config = yield* setUpReleases('@composio/cli@0.5.0');
806 +
807 + const result = yield* runUpgradeSuccess(config);
808 +
809 + expect(result).toBeUndefined();
810 + expect(readFileSync(updateCheckDir, 'utf8')).toBe('not a directory');
811 + }).pipe(Effect.provide(TestPlatform), Effect.ensuring(restoreStubsAndMocks));
812 + });
813 +});
814 +
815 describe('formatDownloadProgress', () => {
816 it('reports percent and both sizes when the total is known', () => {
817 expect(formatDownloadProgress({ receivedBytes: 142_000_000, totalBytes: 338_000_000 })).toBe(