Skip to content

Commit 98087ac

Browse files
feat: improve CLI update check with caching (#1549)
1 parent 6c03e69 commit 98087ac

4 files changed

Lines changed: 184 additions & 66 deletions

File tree

.changeset/hip-pots-study.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"task-master-ai": patch
3+
---
4+
5+
Improve CLI startup speed by 2x
Lines changed: 162 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,88 +1,187 @@
11
/**
2-
* @fileoverview Check npm registry for package updates
2+
* @fileoverview Check npm registry for package updates with caching
3+
*
4+
* Uses a simple file-based cache in the OS temp directory to avoid
5+
* hitting npm on every CLI invocation. Cache expires after 1 hour.
36
*/
47

8+
import fs from 'node:fs';
59
import https from 'https';
10+
import os from 'node:os';
11+
import path from 'node:path';
612

713
import { fetchChangelogHighlights } from './changelog.js';
814
import type { UpdateInfo } from './types.js';
915
import { compareVersions, getCurrentVersion } from './version.js';
1016

17+
// ============================================================================
18+
// Cache Configuration
19+
// ============================================================================
20+
21+
/** Cache TTL: 1 hour in milliseconds */
22+
const CACHE_TTL_MS = 60 * 60 * 1000;
23+
24+
/** Cache file name */
25+
const CACHE_FILENAME = 'taskmaster-update-cache.json';
26+
27+
interface UpdateCache {
28+
timestamp: number;
29+
latestVersion: string;
30+
highlights?: string[];
31+
}
32+
33+
// ============================================================================
34+
// Cache Operations (Single Responsibility: cache I/O)
35+
// ============================================================================
36+
1137
/**
12-
* Check for newer version of task-master-ai
38+
* Get the path to the update cache file in OS temp directory
1339
*/
14-
export async function checkForUpdate(
15-
currentVersionOverride?: string
16-
): Promise<UpdateInfo> {
17-
const currentVersion = currentVersionOverride || getCurrentVersion();
40+
const getCachePath = (): string => path.join(os.tmpdir(), CACHE_FILENAME);
1841

19-
return new Promise((resolve) => {
20-
const options = {
21-
hostname: 'registry.npmjs.org',
22-
path: '/task-master-ai',
23-
method: 'GET',
24-
headers: {
25-
Accept: 'application/vnd.npm.install-v1+json',
26-
'User-Agent': `task-master-ai/${currentVersion}`
27-
}
28-
};
42+
/**
43+
* Read cached update info if still valid
44+
* @returns Cached data or null if expired/missing/invalid
45+
*/
46+
function readCache(): UpdateCache | null {
47+
try {
48+
const cachePath = getCachePath();
49+
if (!fs.existsSync(cachePath)) return null;
2950

30-
const req = https.request(options, (res) => {
31-
let data = '';
51+
const data: UpdateCache = JSON.parse(fs.readFileSync(cachePath, 'utf-8'));
52+
const isExpired = Date.now() - data.timestamp > CACHE_TTL_MS;
3253

33-
res.on('data', (chunk) => {
34-
data += chunk;
35-
});
54+
return isExpired ? null : data;
55+
} catch {
56+
return null;
57+
}
58+
}
3659

37-
res.on('end', async () => {
38-
try {
39-
if (res.statusCode !== 200)
40-
throw new Error(`npm registry status ${res.statusCode}`);
41-
const npmData = JSON.parse(data);
42-
const latestVersion = npmData['dist-tags']?.latest || currentVersion;
60+
/**
61+
* Write update info to cache
62+
*/
63+
function writeCache(latestVersion: string, highlights?: string[]): void {
64+
try {
65+
fs.writeFileSync(
66+
getCachePath(),
67+
JSON.stringify(
68+
{
69+
timestamp: Date.now(),
70+
latestVersion,
71+
highlights
72+
} satisfies UpdateCache,
73+
null,
74+
2
75+
)
76+
);
77+
} catch {
78+
// Cache write failures are non-critical - silently ignore
79+
}
80+
}
4381

44-
const needsUpdate =
45-
compareVersions(currentVersion, latestVersion) < 0;
82+
// ============================================================================
83+
// NPM Registry Operations (Single Responsibility: npm API)
84+
// ============================================================================
4685

47-
// Fetch highlights if update is needed
48-
let highlights: string[] | undefined;
49-
if (needsUpdate) {
50-
highlights = await fetchChangelogHighlights(latestVersion);
51-
}
86+
/** Request timeout for npm registry */
87+
const NPM_TIMEOUT_MS = 3000;
5288

53-
resolve({
54-
currentVersion,
55-
latestVersion,
56-
needsUpdate,
57-
highlights
58-
});
59-
} catch {
60-
resolve({
61-
currentVersion,
62-
latestVersion: currentVersion,
63-
needsUpdate: false
64-
});
89+
/**
90+
* Fetch latest version from npm registry
91+
* @returns Latest version string or null on failure
92+
*/
93+
function fetchLatestVersion(currentVersion: string): Promise<string | null> {
94+
return new Promise((resolve) => {
95+
const req = https.request(
96+
{
97+
hostname: 'registry.npmjs.org',
98+
path: '/task-master-ai',
99+
method: 'GET',
100+
headers: {
101+
Accept: 'application/vnd.npm.install-v1+json',
102+
'User-Agent': `task-master-ai/${currentVersion}`
65103
}
66-
});
67-
});
68-
69-
req.on('error', () => {
70-
resolve({
71-
currentVersion,
72-
latestVersion: currentVersion,
73-
needsUpdate: false
74-
});
75-
});
104+
},
105+
(res) => {
106+
let data = '';
107+
res.on('data', (chunk) => (data += chunk));
108+
res.on('end', () => {
109+
try {
110+
if (res.statusCode !== 200) {
111+
resolve(null);
112+
return;
113+
}
114+
const npmData = JSON.parse(data);
115+
resolve(npmData['dist-tags']?.latest || null);
116+
} catch {
117+
resolve(null);
118+
}
119+
});
120+
}
121+
);
76122

77-
req.setTimeout(3000, () => {
123+
req.on('error', () => resolve(null));
124+
req.setTimeout(NPM_TIMEOUT_MS, () => {
78125
req.destroy();
79-
resolve({
80-
currentVersion,
81-
latestVersion: currentVersion,
82-
needsUpdate: false
83-
});
126+
resolve(null);
84127
});
85-
86128
req.end();
87129
});
88130
}
131+
132+
// ============================================================================
133+
// Public API
134+
// ============================================================================
135+
136+
/**
137+
* Build UpdateInfo response
138+
*/
139+
function buildUpdateInfo(
140+
currentVersion: string,
141+
latestVersion: string,
142+
highlights?: string[]
143+
): UpdateInfo {
144+
return {
145+
currentVersion,
146+
latestVersion,
147+
needsUpdate: compareVersions(currentVersion, latestVersion) < 0,
148+
highlights
149+
};
150+
}
151+
152+
/**
153+
* Check for newer version of task-master-ai
154+
* Uses a 1-hour cache to avoid hitting npm on every CLI invocation
155+
*/
156+
export async function checkForUpdate(
157+
currentVersionOverride?: string
158+
): Promise<UpdateInfo> {
159+
const currentVersion = currentVersionOverride || getCurrentVersion();
160+
161+
// Return cached result if valid
162+
const cached = readCache();
163+
if (cached) {
164+
return buildUpdateInfo(
165+
currentVersion,
166+
cached.latestVersion,
167+
cached.highlights
168+
);
169+
}
170+
171+
// Fetch from npm registry
172+
const latestVersion = await fetchLatestVersion(currentVersion);
173+
if (!latestVersion) {
174+
return buildUpdateInfo(currentVersion, currentVersion);
175+
}
176+
177+
// Fetch changelog highlights if update available
178+
const needsUpdate = compareVersions(currentVersion, latestVersion) < 0;
179+
const highlights = needsUpdate
180+
? await fetchChangelogHighlights(latestVersion)
181+
: undefined;
182+
183+
// Cache result
184+
writeCache(latestVersion, highlights);
185+
186+
return buildUpdateInfo(currentVersion, latestVersion, highlights);
187+
}

apps/cli/vitest.config.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,10 @@ import rootConfig from '../../vitest.config';
44
/**
55
* CLI package Vitest configuration
66
* Extends root config with CLI-specific settings
7+
*
8+
* Integration tests (.test.ts) spawn CLI processes and need more time.
9+
* The 30s timeout is reasonable now that auto-update network calls are skipped
10+
* when TASKMASTER_SKIP_AUTO_UPDATE=1 or NODE_ENV=test.
711
*/
812
export default mergeConfig(
913
rootConfig,
@@ -15,7 +19,10 @@ export default mergeConfig(
1519
'tests/**/*.spec.ts',
1620
'src/**/*.test.ts',
1721
'src/**/*.spec.ts'
18-
]
22+
],
23+
// Integration tests spawn CLI processes - 30s is reasonable with optimized startup
24+
testTimeout: 30000,
25+
hookTimeout: 15000
1926
}
2027
})
2128
);

scripts/modules/commands.js

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5402,9 +5402,16 @@ async function runCLI(argv = process.argv) {
54025402
displayBanner();
54035403
}
54045404

5405-
// Check for updates BEFORE executing the command
5405+
// Check for updates BEFORE executing the command (skip entirely in test/CI mode)
5406+
const skipAutoUpdate =
5407+
process.env.TASKMASTER_SKIP_AUTO_UPDATE === '1' ||
5408+
process.env.CI ||
5409+
process.env.NODE_ENV === 'test';
5410+
54065411
const currentVersion = getTaskMasterVersion();
5407-
const updateInfo = await checkForUpdate(currentVersion);
5412+
const updateInfo = skipAutoUpdate
5413+
? { currentVersion, latestVersion: currentVersion, needsUpdate: false }
5414+
: await checkForUpdate(currentVersion);
54085415

54095416
if (updateInfo.needsUpdate) {
54105417
// Display the upgrade notification first

0 commit comments

Comments
 (0)