@devries-cameron20 / composio-1 / commits / 694231f9f
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.

feat(cli): add background upgrade-available hint on every invocation

Show a non-blocking "Update available" notice on stderr before each CLI command when a newer @composio/cli version exists on GitHub. Uses the lightweight `git/matching-refs` API (prefix-filtered to `@composio/cli@` tags) instead of the full releases endpoint, cached to ~/.composio/update-check.json with a 24-hour TTL. Runs entirely outside the Effect runtime — sync file read for the notice (~1 ms), fire-and-forget fetch for the background check. Also extracts the `withHttpServer` test helper into a shared utility (`test/__utils__/http-server.ts`) used by both update-check and upgrade-binary tests.

jkomyno committed Mar 10, 2026 at 01:19 UTC 694231f9ffcdb23ca5baf67509101355764d81dc
6 files changed +605 -37
ts/packages/cli/src/bin.ts
+9
@@ -27,6 +27,7 @@ import { ProjectContext } from 'src/services/project-context';
27 import { ProjectEnvironmentDetector } from 'src/services/project-environment-detector';
28 import { CommandRunner } from 'src/services/command-runner';
29 import { StdinLive } from 'src/services/stdin';
30 +import { showUpdateNotice, checkForUpdateInBackground } from 'src/services/update-check';
31
32 /**
33 * Concrete Effect layer compositions for the Composio CLI runtime.
@@ -172,6 +173,14 @@ const valueOptionNames = (() => {
173 return names;
174 })();
175
176 +/**
177 + * Upgrade hint — runs outside the Effect runtime, never blocks or throws.
178 + * showUpdateNotice() reads a cached file (~1 ms) and prints to stderr.
179 + * checkForUpdateInBackground() fires a non-blocking fetch to GitHub.
180 + */
181 +showUpdateNotice();
182 +checkForUpdateInBackground();
183 +
184 /**
185 * CLI entrypoint, which:
186 * - runs the Effect runtime and sets up its runtime environment
ts/packages/cli/src/services/update-check.ts new
+183
@@ -0,0 +1,183 @@
1 +import { readFileSync, mkdirSync } from 'node:fs';
2 +import { writeFile } from 'node:fs/promises';
3 +import { homedir } from 'node:os';
4 +import { dirname, join } from 'node:path';
5 +import semver from 'semver';
6 +import { bold, cyanBright, dim } from 'src/ui/colors';
7 +import { APP_VERSION, GITHUB_REPO } from '../constants';
8 +
9 +/**
10 + * Background update check for @composio/cli.
11 + *
12 + * Two entry points, both called synchronously from bin.ts BEFORE the Effect
13 + * runtime boots — they must never block or throw:
14 + *
15 + * showUpdateNotice() — sync file read (~1 ms)
16 + * checkForUpdateInBackground() — fire-and-forget fetch, no await
17 + *
18 + * Strategy:
19 + * Uses GitHub's `git/matching-refs` API with the prefix
20 + * `tags/@composio/cli@` so only CLI tags are returned (tiny payload,
21 + * no monorepo noise). The result is cached to ~/.composio/update-check.json
22 + * and refreshed at most once every 24 hours.
23 + */
24 +
25 +const CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000; // 24 hours
26 +
27 +/** Matches `refs/tags/@composio/cli@<semver>` — excludes prereleases. */
28 +const CLI_REF_RE = /^refs\/tags\/@composio\/cli@(\d+\.\d+\.\d+)$/;
29 +
30 +export interface UpdateCheckState {
31 + lastChecked: string; // ISO-8601
32 + latestVersion: string; // e.g. "0.3.0"
33 +}
34 +
35 +// ── Injectable configuration ────────────────────────────────────────────
36 +
37 +/** Dependencies injected into the update checker — mirrors the Effect service pattern. */
38 +export interface UpdateCheckConfig {
39 + readonly stateFile: string;
40 + readonly currentVersion: string;
41 + readonly checkIntervalMs: number;
42 + readonly refsUrl: string;
43 + readonly accessToken: string | undefined;
44 + readonly fetchFn: (url: string, init?: RequestInit) => Promise<Response>;
45 +}
46 +
47 +const _home = join(homedir(), '.composio');
48 +
49 +const defaultConfig: UpdateCheckConfig = {
50 + stateFile: join(_home, 'update-check.json'),
51 + currentVersion: APP_VERSION,
52 + checkIntervalMs: CHECK_INTERVAL_MS,
53 + refsUrl: `${GITHUB_REPO.API_BASE_URL}/repos/${GITHUB_REPO.OWNER}/${GITHUB_REPO.REPO}/git/matching-refs/tags/@composio/cli@`,
54 + accessToken: process.env.COMPOSIO_GITHUB_ACCESS_TOKEN,
55 + fetchFn: fetch,
56 +};
57 +
58 +// ── Pure helpers ────────────────────────────────────────────────────────
59 +
60 +/** Extract the highest stable semver from a GitHub matching-refs response. */
61 +export function parseLatestVersionFromRefs(refs: unknown): string | undefined {
62 + if (!Array.isArray(refs)) return undefined;
63 +
64 + let latest: string | undefined;
65 + for (const ref of refs) {
66 + if (typeof ref !== 'object' || ref === null || !('ref' in ref) || typeof ref.ref !== 'string')
67 + continue;
68 +
69 + const match = CLI_REF_RE.exec(ref.ref);
70 + if (!match) continue;
71 +
72 + const version = match[1];
73 + if (!latest || semver.gt(version, latest)) {
74 + latest = version;
75 + }
76 + }
77 +
78 + return latest;
79 +}
80 +
81 +// ── Factory ─────────────────────────────────────────────────────────────
82 +
83 +export function createUpdateChecker(config: UpdateCheckConfig) {
84 + /**
85 + * If a cached newer version is known, print a one-line hint to stderr.
86 + * Purely synchronous — reads a tiny JSON file and does a semver compare.
87 + */
88 + function showUpdateNotice(): void {
89 + try {
90 + const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
91 + if (!state.latestVersion || !semver.valid(state.latestVersion)) return;
92 + if (state.latestVersion === config.currentVersion) return;
93 +
94 + // Only show when the cached version is strictly newer.
95 + if (!semver.gt(state.latestVersion, config.currentVersion)) return;
96 +
97 + const msg =
98 + ` ${dim('Update available:')} ${dim(config.currentVersion)} ${dim('→')} ${bold(cyanBright(state.latestVersion))}\n` +
99 + ` ${dim('Run')} ${cyanBright('composio upgrade')} ${dim('to update')}\n`;
100 +
101 + process.stderr.write(`\n${msg}\n`);
102 + } catch {
103 + // Silently ignore — ENOENT, corrupt JSON, etc. Never block the CLI.
104 + }
105 + }
106 +
107 + /**
108 + * Fetch the latest @composio/cli tag from GitHub via the lightweight
109 + * `git/matching-refs` endpoint, then write the result to the state file.
110 + *
111 + * Returns the internal promise so tests can await completion.
112 + * The public wrapper discards it (fire-and-forget).
113 + */
114 + function checkForUpdate(): Promise<void> | undefined {
115 + try {
116 + // Throttle: skip if checked recently.
117 + try {
118 + const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
119 + if (Date.now() - new Date(state.lastChecked).getTime() < config.checkIntervalMs) {
120 + return undefined;
121 + }
122 + } catch {
123 + // ENOENT or corrupt file — re-check.
124 + }
125 +
126 + const headers: Record<string, string> = {
127 + Accept: 'application/vnd.github.v3+json',
128 + 'User-Agent': `composio-cli/${config.currentVersion}`,
129 + };
130 +
131 + if (config.accessToken) {
132 + headers.Authorization = `Bearer ${config.accessToken}`;
133 + }
134 +
135 + return (
136 + config
137 + .fetchFn(config.refsUrl, { headers, signal: AbortSignal.timeout(10_000) })
138 + .then(res => {
139 + if (!res.ok) throw new Error(`HTTP ${res.status}`);
140 + return res.json();
141 + })
142 + .then((refs: unknown) => {
143 + const latestVersion = parseLatestVersionFromRefs(refs);
144 + if (!latestVersion) return;
145 +
146 + const stateDir = dirname(config.stateFile);
147 + mkdirSync(stateDir, { recursive: true });
148 +
149 + const state: UpdateCheckState = {
150 + lastChecked: new Date().toISOString(),
151 + latestVersion,
152 + };
153 +
154 + return writeFile(config.stateFile, JSON.stringify(state, null, 2));
155 + })
156 + // Normalize return type to Promise<void> (writeFile returns void, early-return yields undefined).
157 + .then(() => {})
158 + .catch(() => {
159 + // Silently ignore — never block the CLI.
160 + })
161 + );
162 + } catch {
163 + // Silently ignore.
164 + return undefined;
165 + }
166 + }
167 +
168 + return { showUpdateNotice, checkForUpdate };
169 +}
170 +
171 +// ── Public API (production defaults, fire-and-forget) ───────────────────
172 +
173 +const _checker = createUpdateChecker(defaultConfig);
174 +
175 +/** Print upgrade hint to stderr if a newer version is cached. */
176 +export function showUpdateNotice(): void {
177 + _checker.showUpdateNotice();
178 +}
179 +
180 +/** Fire-and-forget background fetch to GitHub. */
181 +export function checkForUpdateInBackground(): void {
182 + _checker.checkForUpdate();
183 +}
ts/packages/cli/test/__utils__/http-server.ts new
+41
@@ -0,0 +1,41 @@
1 +import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
2 +
3 +/**
4 + * Spin up a local HTTP server on an ephemeral port, run the callback,
5 + * then tear down. Useful for integration-testing code that uses `fetch`.
6 + */
7 +export async function withHttpServer(
8 + handler: (req: IncomingMessage, res: ServerResponse) => void,
9 + run: (baseUrl: string) => Promise<void>
10 +): Promise<void> {
11 + const server = createServer(handler);
12 +
13 + await new Promise<void>((resolve, reject) => {
14 + server.once('error', reject);
15 + server.listen({ port: 0, host: '127.0.0.1' }, () => {
16 + server.off('error', reject);
17 + resolve();
18 + });
19 + });
20 +
21 + const address = server.address();
22 + if (address === null || typeof address === 'string') {
23 + throw new Error('Failed to bind test server to an ephemeral port');
24 + }
25 +
26 + const baseUrl = `http://127.0.0.1:${address.port}`;
27 +
28 + try {
29 + await run(baseUrl);
30 + } finally {
31 + await new Promise<void>((resolve, reject) => {
32 + server.close(error => {
33 + if (error) {
34 + reject(error);
35 + return;
36 + }
37 + resolve();
38 + });
39 + });
40 + }
41 +}
ts/packages/cli/test/__utils__/index.ts
+1
@@ -5,3 +5,4 @@ export * as MockTerminal from './services/mock-terminal';
5 export { TestLayer as TestLive } from './services/test-layer';
6 export { cli } from './cli';
7 export { pkg };
8 +export { withHttpServer } from './http-server';
ts/packages/cli/test/src/services/update-check.test.ts new
+370
@@ -0,0 +1,370 @@
1 +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
2 +import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } from 'node:fs';
3 +import { dirname, join } from 'node:path';
4 +import { tmpdir } from 'node:os';
5 +import { withHttpServer } from 'test/__utils__/http-server';
6 +import {
7 + createUpdateChecker,
8 + parseLatestVersionFromRefs,
9 + type UpdateCheckConfig,
10 + type UpdateCheckState,
11 +} from 'src/services/update-check';
12 +
13 +// ── Helpers ─────────────────────────────────────────────────────────────
14 +
15 +/** Create a temp directory that is cleaned up after each test. */
16 +let tempDir: string;
17 +beforeEach(() => {
18 + tempDir = mkdtempSync(join(tmpdir(), 'update-check-test-'));
19 +});
20 +afterEach(() => {
21 + rmSync(tempDir, { recursive: true, force: true });
22 +});
23 +
24 +/** Build a test config pointing at a temp directory with optional overrides. */
25 +function makeConfig(overrides?: Partial<UpdateCheckConfig>): UpdateCheckConfig {
26 + return {
27 + stateFile: join(tempDir, '.composio', 'update-check.json'),
28 + currentVersion: '0.2.0',
29 + checkIntervalMs: 24 * 60 * 60 * 1000,
30 + refsUrl: 'http://unused.test',
31 + accessToken: undefined,
32 + fetchFn: () => Promise.reject(new Error('fetch not configured')),
33 + ...overrides,
34 + };
35 +}
36 +
37 +/** Write a state file to the test config's stateFile path. */
38 +function writeState(config: UpdateCheckConfig, state: UpdateCheckState): void {
39 + mkdirSync(dirname(config.stateFile), { recursive: true });
40 + writeFileSync(config.stateFile, JSON.stringify(state));
41 +}
42 +
43 +/** Create a GitHub matching-refs response body. */
44 +function makeRefsPayload(versions: string[]) {
45 + return versions.map(v => ({
46 + ref: `refs/tags/@composio/cli@${v}`,
47 + node_id: 'unused',
48 + url: 'unused',
49 + object: { sha: 'abc', type: 'tag', url: 'unused' },
50 + }));
51 +}
52 +
53 +// ── parseLatestVersionFromRefs (pure) ───────────────────────────────────
54 +
55 +describe('parseLatestVersionFromRefs', () => {
56 + it('returns undefined for non-array input', () => {
57 + expect(parseLatestVersionFromRefs(null)).toBeUndefined();
58 + expect(parseLatestVersionFromRefs('string')).toBeUndefined();
59 + expect(parseLatestVersionFromRefs(42)).toBeUndefined();
60 + });
61 +
62 + it('returns undefined when no refs match the CLI pattern', () => {
63 + const refs = [
64 + { ref: 'refs/tags/@composio/core@1.0.0' },
65 + { ref: 'refs/tags/v1.0.0' },
66 + { ref: 'refs/heads/main' },
67 + ];
68 + expect(parseLatestVersionFromRefs(refs)).toBeUndefined();
69 + });
70 +
71 + it('returns the single matching version', () => {
72 + const refs = makeRefsPayload(['0.2.1']);
73 + expect(parseLatestVersionFromRefs(refs)).toBe('0.2.1');
74 + });
75 +
76 + it('returns the highest semver, not the last element', () => {
77 + // GitHub returns refs sorted lexicographically — 0.10.0 < 0.9.0 lexically
78 + // but 0.10.0 > 0.9.0 in semver.
79 + const refs = makeRefsPayload(['0.1.0', '0.10.0', '0.9.0', '0.2.0']);
80 + expect(parseLatestVersionFromRefs(refs)).toBe('0.10.0');
81 + });
82 +
83 + it('excludes prerelease tags', () => {
84 + const refs = [
85 + { ref: 'refs/tags/@composio/cli@0.2.0' },
86 + { ref: 'refs/tags/@composio/cli@0.3.0-beta.1' },
87 + ];
88 + expect(parseLatestVersionFromRefs(refs)).toBe('0.2.0');
89 + });
90 +
91 + it('skips malformed ref objects', () => {
92 + const refs = [
93 + null,
94 + 42,
95 + { noRef: true },
96 + { ref: 123 },
97 + { ref: 'refs/tags/@composio/cli@0.5.0' },
98 + ];
99 + expect(parseLatestVersionFromRefs(refs)).toBe('0.5.0');
100 + });
101 +});
102 +
103 +// ── showUpdateNotice ────────────────────────────────────────────────────
104 +
105 +describe('showUpdateNotice', () => {
106 + // eslint-disable-next-line @typescript-eslint/no-explicit-any
107 + let stderrSpy: any;
108 +
109 + beforeEach(() => {
110 + stderrSpy = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
111 + });
112 +
113 + afterEach(() => {
114 + stderrSpy.mockRestore();
115 + });
116 +
117 + it('does nothing when no state file exists', () => {
118 + const { showUpdateNotice } = createUpdateChecker(makeConfig());
119 +
120 + showUpdateNotice();
121 +
122 + expect(stderrSpy).not.toHaveBeenCalled();
123 + });
124 +
125 + it('does nothing when cached version equals current version', () => {
126 + const config = makeConfig({ currentVersion: '0.2.0' });
127 + writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.2.0' });
128 + const { showUpdateNotice } = createUpdateChecker(config);
129 +
130 + showUpdateNotice();
131 +
132 + expect(stderrSpy).not.toHaveBeenCalled();
133 + });
134 +
135 + it('does nothing when cached version is older than current', () => {
136 + const config = makeConfig({ currentVersion: '0.3.0' });
137 + writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.2.0' });
138 + const { showUpdateNotice } = createUpdateChecker(config);
139 +
140 + showUpdateNotice();
141 +
142 + expect(stderrSpy).not.toHaveBeenCalled();
143 + });
144 +
145 + it('prints upgrade hint when cached version is newer', () => {
146 + const config = makeConfig({ currentVersion: '0.2.0' });
147 + writeState(config, { lastChecked: new Date().toISOString(), latestVersion: '0.3.0' });
148 + const { showUpdateNotice } = createUpdateChecker(config);
149 +
150 + showUpdateNotice();
151 +
152 + expect(stderrSpy).toHaveBeenCalledOnce();
153 + const output = stderrSpy.mock.calls[0][0] as string;
154 + expect(output).toContain('Update available');
155 + expect(output).toContain('0.3.0');
156 + expect(output).toContain('composio upgrade');
157 + });
158 +
159 + it('silently ignores corrupt state file', () => {
160 + const config = makeConfig();
161 + mkdirSync(dirname(config.stateFile), { recursive: true });
162 + writeFileSync(config.stateFile, 'not-json!!!');
163 + const { showUpdateNotice } = createUpdateChecker(config);
164 +
165 + showUpdateNotice();
166 +
167 + expect(stderrSpy).not.toHaveBeenCalled();
168 + });
169 +
170 + it('does nothing when cached version is not valid semver', () => {
171 + const config = makeConfig({ currentVersion: '0.2.0' });
172 + writeState(config, { lastChecked: new Date().toISOString(), latestVersion: 'not-semver' });
173 + const { showUpdateNotice } = createUpdateChecker(config);
174 +
175 + showUpdateNotice();
176 +
177 + expect(stderrSpy).not.toHaveBeenCalled();
178 + });
179 +});
180 +
181 +// ── checkForUpdate ──────────────────────────────────────────────────────
182 +
183 +describe('checkForUpdate', () => {
184 + it('skips fetch when cache is fresh', () => {
185 + const fetchFn = vi.fn();
186 + const config = makeConfig({ fetchFn: fetchFn as unknown as typeof fetch });
187 + writeState(config, {
188 + lastChecked: new Date().toISOString(),
189 + latestVersion: '0.2.0',
190 + });
191 + const { checkForUpdate } = createUpdateChecker(config);
192 +
193 + const result = checkForUpdate();
194 +
195 + expect(result).toBeUndefined(); // returned early, no promise
196 + expect(fetchFn).not.toHaveBeenCalled();
197 + });
198 +
199 + it('fetches when cache is stale', async () => {
200 + const stale = new Date(Date.now() - 25 * 60 * 60 * 1000).toISOString(); // 25 hours ago
201 + const config = makeConfig({
202 + fetchFn: vi.fn().mockResolvedValue({
203 + ok: true,
204 + json: () => Promise.resolve(makeRefsPayload(['0.3.0'])),
205 + }) as unknown as typeof fetch,
206 + });
207 + writeState(config, { lastChecked: stale, latestVersion: '0.2.0' });
208 + const { checkForUpdate } = createUpdateChecker(config);
209 +
210 + await checkForUpdate();
211 +
212 + expect(config.fetchFn).toHaveBeenCalledOnce();
213 + const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
214 + expect(state.latestVersion).toBe('0.3.0');
215 + });
216 +
217 + it('fetches when no cache exists', async () => {
218 + const config = makeConfig({
219 + fetchFn: vi.fn().mockResolvedValue({
220 + ok: true,
221 + json: () => Promise.resolve(makeRefsPayload(['0.4.0', '0.3.0'])),
222 + }) as unknown as typeof fetch,
223 + });
224 + const { checkForUpdate } = createUpdateChecker(config);
225 +
226 + await checkForUpdate();
227 +
228 + expect(existsSync(config.stateFile)).toBe(true);
229 + const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
230 + expect(state.latestVersion).toBe('0.4.0');
231 + });
232 +
233 + it('fetches when cache file is corrupt', async () => {
234 + const config = makeConfig({
235 + fetchFn: vi.fn().mockResolvedValue({
236 + ok: true,
237 + json: () => Promise.resolve(makeRefsPayload(['0.5.0'])),
238 + }) as unknown as typeof fetch,
239 + });
240 + mkdirSync(dirname(config.stateFile), { recursive: true });
241 + writeFileSync(config.stateFile, 'garbage');
242 + const { checkForUpdate } = createUpdateChecker(config);
243 +
244 + await checkForUpdate();
245 +
246 + const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
247 + expect(state.latestVersion).toBe('0.5.0');
248 + });
249 +
250 + it('does not write state when no CLI tags are found', async () => {
251 + const config = makeConfig({
252 + fetchFn: vi.fn().mockResolvedValue({
253 + ok: true,
254 + json: () => Promise.resolve([{ ref: 'refs/tags/@composio/core@1.0.0' }]),
255 + }) as unknown as typeof fetch,
256 + });
257 + const { checkForUpdate } = createUpdateChecker(config);
258 +
259 + await checkForUpdate();
260 +
261 + expect(existsSync(config.stateFile)).toBe(false);
262 + });
263 +
264 + it('silently ignores HTTP errors', async () => {
265 + const config = makeConfig({
266 + fetchFn: vi.fn().mockResolvedValue({
267 + ok: false,
268 + status: 500,
269 + }) as unknown as typeof fetch,
270 + });
271 + const { checkForUpdate } = createUpdateChecker(config);
272 +
273 + // Should not throw
274 + await checkForUpdate();
275 +
276 + expect(existsSync(config.stateFile)).toBe(false);
277 + });
278 +
279 + it('silently ignores network errors', async () => {
280 + const config = makeConfig({
281 + fetchFn: vi.fn().mockRejectedValue(new Error('DNS failed')) as unknown as typeof fetch,
282 + });
283 + const { checkForUpdate } = createUpdateChecker(config);
284 +
285 + await checkForUpdate();
286 +
287 + expect(existsSync(config.stateFile)).toBe(false);
288 + });
289 +
290 + it('sends Authorization header when accessToken is set', async () => {
291 + const fetchFn = vi.fn().mockResolvedValue({
292 + ok: true,
293 + json: () => Promise.resolve(makeRefsPayload(['0.2.1'])),
294 + });
295 + const config = makeConfig({
296 + accessToken: 'ghp_secret123',
297 + fetchFn: fetchFn as unknown as typeof fetch,
298 + });
299 + const { checkForUpdate } = createUpdateChecker(config);
300 +
301 + await checkForUpdate();
302 +
303 + expect(fetchFn).toHaveBeenCalledOnce();
304 + const [, init] = fetchFn.mock.calls[0];
305 + expect(init.headers.Authorization).toBe('Bearer ghp_secret123');
306 + });
307 +
308 + it('does not send Authorization header when accessToken is undefined', async () => {
309 + const fetchFn = vi.fn().mockResolvedValue({
310 + ok: true,
311 + json: () => Promise.resolve(makeRefsPayload(['0.2.1'])),
312 + });
313 + const config = makeConfig({
314 + accessToken: undefined,
315 + fetchFn: fetchFn as unknown as typeof fetch,
316 + });
317 + const { checkForUpdate } = createUpdateChecker(config);
318 +
319 + await checkForUpdate();
320 +
321 + const [, init] = fetchFn.mock.calls[0];
322 + expect(init.headers.Authorization).toBeUndefined();
323 + });
324 +});
325 +
326 +// ── Integration: real HTTP server ───────────────────────────────────────
327 +
328 +describe('checkForUpdate with real HTTP', () => {
329 + it('fetches from a real server and writes state', async () => {
330 + await withHttpServer(
331 + (_req, res) => {
332 + res.writeHead(200, { 'Content-Type': 'application/json' });
333 + res.end(JSON.stringify(makeRefsPayload(['0.1.26', '0.2.0', '0.2.1'])));
334 + },
335 + async baseUrl => {
336 + const config = makeConfig({ refsUrl: baseUrl, fetchFn: fetch });
337 + const { checkForUpdate } = createUpdateChecker(config);
338 +
339 + await checkForUpdate();
340 +
341 + const state: UpdateCheckState = JSON.parse(readFileSync(config.stateFile, 'utf-8'));
342 + expect(state.latestVersion).toBe('0.2.1');
343 + }
344 + );
345 + });
346 +
347 + it('passes Authorization header to the server', async () => {
348 + let receivedAuth: string | undefined;
349 +
350 + await withHttpServer(
351 + (req, res) => {
352 + receivedAuth = req.headers.authorization;
353 + res.writeHead(200, { 'Content-Type': 'application/json' });
354 + res.end(JSON.stringify(makeRefsPayload(['0.2.1'])));
355 + },
356 + async baseUrl => {
357 + const config = makeConfig({
358 + refsUrl: baseUrl,
359 + accessToken: 'ghp_test_token',
360 + fetchFn: fetch,
361 + });
362 + const { checkForUpdate } = createUpdateChecker(config);
363 +
364 + await checkForUpdate();
365 +
366 + expect(receivedAuth).toBe('Bearer ghp_test_token');
367 + }
368 + );
369 + });
370 +});
ts/packages/cli/test/src/services/upgrade-binary.test.ts
+1 -37
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from '@effect/vitest';
2 import { ConfigProvider, Effect, Layer } from 'effect';
3 import { FetchHttpClient } from '@effect/platform';
4 import { BunFileSystem } from '@effect/platform-bun';
5 -import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
5 +import { withHttpServer } from 'test/__utils__/http-server';
6 import { TerminalUI } from 'src/services/terminal-ui';
7 import { UpgradeBinary, UpgradeBinaryError } from 'src/services/upgrade-binary';
8 import { NodeOs } from 'src/services/node-os';
@@ -58,42 +58,6 @@ const runUpgrade = (configEntries: ReadonlyArray<[string, string]>) =>
58 Effect.runPromise
59 );
60
61 -const withHttpServer = async (
62 - handler: (req: IncomingMessage, res: ServerResponse) => void,
63 - run: (apiBaseUrl: string) => Promise<void>
64 -) => {
65 - const server = createServer(handler);
66 -
67 - await new Promise<void>((resolve, reject) => {
68 - server.once('error', reject);
69 - server.listen({ port: 0, host: '127.0.0.1' }, () => {
70 - server.off('error', reject);
71 - resolve();
72 - });
73 - });
74 -
75 - const address = server.address();
76 - if (address === null || typeof address === 'string') {
77 - throw new Error('Failed to bind test server to an ephemeral port');
78 - }
79 -
80 - const apiBaseUrl = `http://127.0.0.1:${address.port}`;
81 -
82 - try {
83 - await run(apiBaseUrl);
84 - } finally {
85 - await new Promise<void>((resolve, reject) => {
86 - server.close(error => {
87 - if (error) {
88 - reject(error);
89 - return;
90 - }
91 - resolve();
92 - });
93 - });
94 - }
95 -};
96 -
61 describe('UpgradeBinary', () => {
62 it('wraps non-2xx releases fetch failures with fetch context (no tag branch)', async () => {
63 vi.stubGlobal('Bun', { which: vi.fn(() => null) });