feat(cli): add channel-aware update notifier (#265)

* feat(cli): show cached update notices after commands

* docs(cli): describe update notices

* fix(cli): type update check environment

* fix(cli): decouple update notice display from refresh and harden suppression

Display a cached "update available" notice based solely on the lastNoticeAt
24h throttle, independent of checkedAt refresh freshness, matching the design's
independent display/refresh decisions. Suppress the check unconditionally under
--json, CI, and non-TTY before consulting output-mode preferences, so a
KTX_OUTPUT=pretty override can no longer make CI/non-TTY contexts phone npm.
This commit is contained in:
Andrey Avtomonov 2026-06-06 10:42:10 +02:00 committed by GitHub
parent 377f21acd7
commit 698efdcef8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
14 changed files with 1153 additions and 4 deletions

View file

@ -0,0 +1,95 @@
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
readUpdateCheckCache,
updateCheckCachePath,
writeUpdateCheckCache,
} from '../../src/update-check/cache.js';
describe('update-check cache', () => {
let homeDir: string;
beforeEach(async () => {
homeDir = await mkdtemp(join(tmpdir(), 'ktx-update-check-cache-'));
});
afterEach(async () => {
await rm(homeDir, { recursive: true, force: true });
});
it('uses ~/.ktx/update-check.json', () => {
expect(updateCheckCachePath(homeDir)).toBe(join(homeDir, '.ktx', 'update-check.json'));
});
it('round-trips strict cache data', async () => {
await writeUpdateCheckCache(
{
checkedAt: '2026-06-06T10:00:00.000Z',
channel: 'latest',
installedVersion: '0.9.0',
latestForChannel: '0.10.0',
lastNoticeAt: '2026-06-06T11:00:00.000Z',
},
{ homeDir },
);
await expect(readUpdateCheckCache({ homeDir })).resolves.toEqual({
checkedAt: '2026-06-06T10:00:00.000Z',
channel: 'latest',
installedVersion: '0.9.0',
latestForChannel: '0.10.0',
lastNoticeAt: '2026-06-06T11:00:00.000Z',
});
});
it('returns null when the cache file is missing', async () => {
await expect(readUpdateCheckCache({ homeDir })).resolves.toBeNull();
});
it('returns null when the cache file is corrupt JSON', async () => {
await mkdir(join(homeDir, '.ktx'), { recursive: true });
await writeFile(updateCheckCachePath(homeDir), '{bad json', 'utf-8');
await expect(readUpdateCheckCache({ homeDir })).resolves.toBeNull();
});
it('returns null when the cache has unknown fields', async () => {
await mkdir(join(homeDir, '.ktx'), { recursive: true });
await writeFile(
updateCheckCachePath(homeDir),
JSON.stringify(
{
checkedAt: '2026-06-06T10:00:00.000Z',
channel: 'latest',
installedVersion: '0.9.0',
latestForChannel: '0.10.0',
unexpected: true,
},
null,
2,
),
'utf-8',
);
await expect(readUpdateCheckCache({ homeDir })).resolves.toBeNull();
});
it('writes formatted JSON with a trailing newline', async () => {
await writeUpdateCheckCache(
{
checkedAt: '2026-06-06T10:00:00.000Z',
channel: 'next',
installedVersion: '0.10.0-rc.1',
latestForChannel: '0.10.0-rc.2',
},
{ homeDir },
);
const raw = await readFile(updateCheckCachePath(homeDir), 'utf-8');
expect(raw).toContain('"channel": "next"');
expect(raw.endsWith('\n')).toBe(true);
});
});

View file

@ -0,0 +1,57 @@
import { describe, expect, it } from 'vitest';
import { decideUpdate, inferUpdateChannel } from '../../src/update-check/channel.js';
describe('inferUpdateChannel', () => {
it.each([
['0.9.0', 'latest'],
['0.10.0-rc.3', 'next'],
['0.10.0-myfeat.2', null],
['0.0.0', null],
['not-a-version', null],
])('maps %s to %s', (installed, expected) => {
expect(inferUpdateChannel(installed)).toBe(expected);
});
});
describe('decideUpdate', () => {
it.each([
[
'stable behind',
'0.9.0',
{ latest: '0.10.0', next: '0.11.0-rc.1' },
{ status: 'available', channel: 'latest', target: '0.10.0' },
],
[
'stable equal',
'0.10.0',
{ latest: '0.10.0', next: '0.11.0-rc.1' },
{ status: 'upToDate', channel: 'latest', target: '0.10.0' },
],
[
'stable ahead',
'0.11.0',
{ latest: '0.10.0', next: '0.11.0-rc.1' },
{ status: 'upToDate', channel: 'latest', target: '0.10.0' },
],
[
'rc behind',
'0.11.0-rc.1',
{ latest: '0.10.0', next: '0.11.0-rc.2' },
{ status: 'available', channel: 'next', target: '0.11.0-rc.2' },
],
[
'rc equal',
'0.11.0-rc.2',
{ latest: '0.10.0', next: '0.11.0-rc.2' },
{ status: 'upToDate', channel: 'next', target: '0.11.0-rc.2' },
],
['branch prerelease', '0.11.0-myfeat.1', { latest: '0.10.0', next: '0.11.0-rc.2' }, { status: 'skip' }],
['missing channel tag', '0.9.0', { next: '0.11.0-rc.2' }, { status: 'skip' }],
['invalid installed version', 'bad', { latest: '0.10.0' }, { status: 'skip' }],
['invalid target version', '0.9.0', { latest: 'bad' }, { status: 'skip' }],
['local development version', '0.0.0', { latest: '0.10.0' }, { status: 'skip' }],
])('%s', (_name, installed, distTags, expected) => {
expect(decideUpdate(installed, distTags)).toEqual(expected);
});
});

View file

@ -0,0 +1,152 @@
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { buildKtxProgram } from '../../src/cli-program.js';
import type { KtxCliDeps, KtxCliIo, KtxCliPackageInfo } from '../../src/cli-runtime.js';
import { updateCheckCachePath } from '../../src/update-check/cache.js';
function makeIo(stdoutIsTTY = true): { io: KtxCliIo; stdout: () => string; stderr: () => string } {
let stdout = '';
let stderr = '';
return {
io: {
stdout: {
isTTY: stdoutIsTTY,
write: (chunk) => {
stdout += chunk;
},
},
stderr: {
write: (chunk) => {
stderr += chunk;
},
},
},
stdout: () => stdout,
stderr: () => stderr,
};
}
describe('cli-program update check hooks', () => {
let projectDir: string;
let homeDir: string;
const info: KtxCliPackageInfo = { name: '@kaelio/ktx', version: '0.9.0' };
beforeEach(async () => {
projectDir = await mkdtemp(join(tmpdir(), 'ktx-update-project-'));
homeDir = await mkdtemp(join(tmpdir(), 'ktx-update-home-'));
await writeFile(join(projectDir, 'ktx.yaml'), '{}\n', 'utf-8');
await mkdir(join(homeDir, '.ktx'), { recursive: true });
vi.stubEnv('KTX_TELEMETRY_DISABLED', '1');
vi.stubEnv('CI', '');
vi.stubEnv('DO_NOT_TRACK', '');
});
afterEach(async () => {
vi.unstubAllEnvs();
await rm(projectDir, { recursive: true, force: true });
await rm(homeDir, { recursive: true, force: true });
});
it('prints a stale-cache notice without awaiting the background refresh', async () => {
await writeFile(
updateCheckCachePath(homeDir),
JSON.stringify(
{
checkedAt: '2026-06-05T10:00:00.000Z',
channel: 'latest',
installedVersion: '0.9.0',
latestForChannel: '0.10.0',
},
null,
2,
),
'utf-8',
);
const io = makeIo(true);
const deps: KtxCliDeps = { doctor: async () => 0 };
const fetchDistTags = vi.fn(
() =>
new Promise<Record<string, string>>(() => {
return;
}),
);
const program = buildKtxProgram({
io: io.io,
deps,
packageInfo: info,
runInit: async () => 0,
updateCheck: {
env: { NO_COLOR: '1' },
fetchDistTags,
homeDir,
now: () => new Date('2026-06-06T12:00:00.000Z'),
},
});
await program.parseAsync(['--project-dir', projectDir, 'status'], { from: 'user' });
expect(fetchDistTags).toHaveBeenCalledTimes(1);
expect(io.stderr()).toContain('↑ Update available: ktx 0.9.0 → 0.10.0\n npm i -g @kaelio/ktx\n');
});
it('prints a queued fresh-cache notice after the action', async () => {
await writeFile(
updateCheckCachePath(homeDir),
JSON.stringify(
{
checkedAt: '2026-06-06T11:00:00.000Z',
channel: 'latest',
installedVersion: '0.9.0',
latestForChannel: '0.10.0',
},
null,
2,
),
'utf-8',
);
const io = makeIo(true);
const fetchDistTags = vi.fn(async () => ({ latest: '0.10.0' }));
const program = buildKtxProgram({
io: io.io,
deps: { doctor: async () => 0 },
packageInfo: info,
runInit: async () => 0,
updateCheck: {
env: { NO_COLOR: '1' },
fetchDistTags,
homeDir,
now: () => new Date('2026-06-06T12:00:00.000Z'),
},
});
await program.parseAsync(['--project-dir', projectDir, 'status'], { from: 'user' });
expect(fetchDistTags).not.toHaveBeenCalled();
expect(io.stderr()).toContain('↑ Update available: ktx 0.9.0 → 0.10.0\n npm i -g @kaelio/ktx\n');
});
it('does not run update checks for the hidden completion command', async () => {
const io = makeIo(true);
const fetchDistTags = vi.fn(async () => ({ latest: '0.10.0' }));
const program = buildKtxProgram({
io: io.io,
deps: {},
packageInfo: info,
runInit: async () => 0,
updateCheck: {
env: { NO_COLOR: '1' },
fetchDistTags,
homeDir,
now: () => new Date('2026-06-06T12:00:00.000Z'),
},
});
await program.parseAsync(['__complete', '--', 'ktx', 'co'], { from: 'user' });
expect(fetchDistTags).not.toHaveBeenCalled();
expect(io.stderr()).not.toContain('Update available');
});
});

View file

@ -0,0 +1,80 @@
import { EventEmitter } from 'node:events';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const requestMock = vi.hoisted(() => vi.fn());
vi.mock('node:https', () => ({
request: requestMock,
}));
type MockResponse = EventEmitter & { statusCode?: number };
type MockRequest = EventEmitter & {
destroy: ReturnType<typeof vi.fn>;
end: () => void;
setTimeout: ReturnType<typeof vi.fn>;
};
function mockHttpsResponse(statusCode: number, body: string): { socket: { unref: ReturnType<typeof vi.fn> } } {
const socket = { unref: vi.fn() };
requestMock.mockImplementation((_url: unknown, _options: unknown, callback: (response: MockResponse) => void) => {
const request = new EventEmitter() as MockRequest;
request.destroy = vi.fn();
request.setTimeout = vi.fn();
request.end = () => {
request.emit('socket', socket);
const response = new EventEmitter() as MockResponse;
response.statusCode = statusCode;
callback(response);
response.emit('data', Buffer.from(body));
response.emit('end');
};
return request;
});
return { socket };
}
describe('fetchDistTags', () => {
beforeEach(() => {
requestMock.mockReset();
});
it('fetches @kaelio/ktx npm dist-tags and unrefs the socket', async () => {
const { socket } = mockHttpsResponse(200, JSON.stringify({ latest: '0.10.0', next: '0.11.0-rc.1' }));
const { fetchDistTags } = await import('../../src/update-check/registry.js');
await expect(fetchDistTags()).resolves.toEqual({ latest: '0.10.0', next: '0.11.0-rc.1' });
expect(requestMock).toHaveBeenCalledWith(
expect.any(URL),
expect.objectContaining({
method: 'GET',
headers: expect.objectContaining({ accept: 'application/json' }),
}),
expect.any(Function),
);
const [url] = requestMock.mock.calls[0] as [URL];
expect(url.toString()).toBe('https://registry.npmjs.org/-/package/@kaelio/ktx/dist-tags');
expect(socket.unref).toHaveBeenCalledTimes(1);
});
it('rejects non-2xx responses', async () => {
mockHttpsResponse(503, 'registry unavailable');
const { fetchDistTags } = await import('../../src/update-check/registry.js');
await expect(fetchDistTags()).rejects.toThrow('npm dist-tags request failed with 503');
});
it('rejects invalid JSON payloads', async () => {
mockHttpsResponse(200, '{bad json');
const { fetchDistTags } = await import('../../src/update-check/registry.js');
await expect(fetchDistTags()).rejects.toThrow();
});
it('rejects payloads that are not string dist-tag maps', async () => {
mockHttpsResponse(200, JSON.stringify({ latest: 123 }));
const { fetchDistTags } = await import('../../src/update-check/registry.js');
await expect(fetchDistTags()).rejects.toThrow();
});
});

View file

@ -0,0 +1,332 @@
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { updateCheckCachePath } from '../../src/update-check/cache.js';
import {
prepareUpdateCheckNotice,
renderUpdateNotice,
shouldSuppressUpdateCheck,
} from '../../src/update-check/update-check.js';
function makeIo(stdoutIsTTY = true) {
let stderr = '';
return {
io: {
stdout: {
isTTY: stdoutIsTTY,
write: () => {},
},
stderr: {
write: (chunk: string) => {
stderr += chunk;
},
},
},
stderr: () => stderr,
};
}
async function flushAsyncWork(): Promise<void> {
await new Promise<void>((resolve) => {
setImmediate(resolve);
});
await new Promise<void>((resolve) => {
setImmediate(resolve);
});
}
describe('update-check orchestration', () => {
let homeDir: string;
beforeEach(async () => {
homeDir = await mkdtemp(join(tmpdir(), 'ktx-update-check-'));
});
afterEach(async () => {
await rm(homeDir, { recursive: true, force: true });
});
it.each([
['json option', true, {}, { json: true }],
['json output option', true, {}, { output: 'json' }],
['json format option', true, {}, { format: 'json' }],
['CI', true, { CI: '1' }, {}],
['non-TTY stdout', false, {}, {}],
['KTX_NO_UPDATE_CHECK', true, { KTX_NO_UPDATE_CHECK: '1' }, {}],
['NO_UPDATE_NOTIFIER', true, { NO_UPDATE_NOTIFIER: '1' }, {}],
['DO_NOT_TRACK', true, { DO_NOT_TRACK: '1' }, {}],
])('suppresses cache and network work for %s', async (_name, stdoutIsTTY, env, commandOptions) => {
const fetchDistTags = vi.fn(async () => ({ latest: '0.10.0' }));
const result = await prepareUpdateCheckNotice({
io: makeIo(stdoutIsTTY).io,
env,
homeDir,
installedVersion: '0.9.0',
commandOptions,
now: () => new Date('2026-06-06T12:00:00.000Z'),
fetchDistTags,
});
expect(result.notice).toBeNull();
expect(fetchDistTags).not.toHaveBeenCalled();
await expect(readFile(updateCheckCachePath(homeDir), 'utf-8')).rejects.toThrow();
});
it.each([
['CI', true, { CI: '1', KTX_OUTPUT: 'pretty' }],
['non-TTY stdout', false, { KTX_OUTPUT: 'pretty' }],
])('suppresses cache and network work for %s even when pretty output is forced', async (_name, stdoutIsTTY, env) => {
const fetchDistTags = vi.fn(async () => ({ latest: '0.10.0' }));
const result = await prepareUpdateCheckNotice({
io: makeIo(stdoutIsTTY).io,
env,
homeDir,
installedVersion: '0.9.0',
commandOptions: {},
now: () => new Date('2026-06-06T12:00:00.000Z'),
fetchDistTags,
});
expect(result.notice).toBeNull();
expect(fetchDistTags).not.toHaveBeenCalled();
await expect(readFile(updateCheckCachePath(homeDir), 'utf-8')).rejects.toThrow();
});
it('does not suppress when only KTX_TELEMETRY_DISABLED is set', () => {
expect(
shouldSuppressUpdateCheck({
io: makeIo(true).io,
env: { KTX_TELEMETRY_DISABLED: '1' } as NodeJS.ProcessEnv,
commandOptions: {},
}),
).toBe(false);
});
it('renders a compact no-color stable notice', () => {
expect(
renderUpdateNotice({
installedVersion: '0.9.0',
targetVersion: '0.10.0',
channel: 'latest',
env: { NO_COLOR: '1' },
}),
).toBe('↑ Update available: ktx 0.9.0 → 0.10.0\n npm i -g @kaelio/ktx\n');
});
it('renders the next-channel install command', () => {
expect(
renderUpdateNotice({
installedVersion: '0.10.0-rc.1',
targetVersion: '0.10.0-rc.2',
channel: 'next',
env: { NO_COLOR: '1' },
}),
).toBe('↑ Update available: ktx 0.10.0-rc.1 → 0.10.0-rc.2\n npm i -g @kaelio/ktx@next\n');
});
it('queues a cached notice and stamps lastNoticeAt', async () => {
await mkdir(join(homeDir, '.ktx'), { recursive: true });
await writeFile(
updateCheckCachePath(homeDir),
JSON.stringify(
{
checkedAt: '2026-06-06T11:00:00.000Z',
channel: 'latest',
installedVersion: '0.9.0',
latestForChannel: '0.10.0',
},
null,
2,
),
'utf-8',
);
const fetchDistTags = vi.fn(async () => ({ latest: '0.10.0' }));
const result = await prepareUpdateCheckNotice({
io: makeIo(true).io,
env: { NO_COLOR: '1' },
homeDir,
installedVersion: '0.9.0',
now: () => new Date('2026-06-06T12:00:00.000Z'),
fetchDistTags,
});
expect(result.notice).toBe('↑ Update available: ktx 0.9.0 → 0.10.0\n npm i -g @kaelio/ktx\n');
expect(fetchDistTags).not.toHaveBeenCalled();
const stored = JSON.parse(await readFile(updateCheckCachePath(homeDir), 'utf-8')) as { lastNoticeAt?: string };
expect(stored.lastNoticeAt).toBe('2026-06-06T12:00:00.000Z');
});
it('queues a stale cached notice and still refreshes in the background', async () => {
await mkdir(join(homeDir, '.ktx'), { recursive: true });
await writeFile(
updateCheckCachePath(homeDir),
JSON.stringify(
{
checkedAt: '2026-06-05T10:00:00.000Z',
channel: 'latest',
installedVersion: '0.9.0',
latestForChannel: '0.10.0',
lastNoticeAt: '2026-06-05T11:00:00.000Z',
},
null,
2,
),
'utf-8',
);
const fetchDistTags = vi.fn(async () => ({ latest: '0.11.0' }));
const result = await prepareUpdateCheckNotice({
io: makeIo(true).io,
env: { NO_COLOR: '1' },
homeDir,
installedVersion: '0.9.0',
now: () => new Date('2026-06-06T12:00:00.000Z'),
fetchDistTags,
});
expect(result.notice).toBe('↑ Update available: ktx 0.9.0 → 0.10.0\n npm i -g @kaelio/ktx\n');
expect(fetchDistTags).toHaveBeenCalledTimes(1);
await flushAsyncWork();
await vi.waitFor(async () => {
const stored = JSON.parse(await readFile(updateCheckCachePath(homeDir), 'utf-8')) as {
latestForChannel: string;
lastNoticeAt?: string;
};
expect(stored.latestForChannel).toBe('0.11.0');
expect(stored.lastNoticeAt).toBe('2026-06-06T12:00:00.000Z');
});
});
it('throttles a cached notice for 24 hours', async () => {
await mkdir(join(homeDir, '.ktx'), { recursive: true });
await writeFile(
updateCheckCachePath(homeDir),
JSON.stringify(
{
checkedAt: '2026-06-06T11:00:00.000Z',
channel: 'latest',
installedVersion: '0.9.0',
latestForChannel: '0.10.0',
lastNoticeAt: '2026-06-06T11:30:00.000Z',
},
null,
2,
),
'utf-8',
);
await expect(
prepareUpdateCheckNotice({
io: makeIo(true).io,
env: { NO_COLOR: '1' },
homeDir,
installedVersion: '0.9.0',
now: () => new Date('2026-06-06T12:00:00.000Z'),
fetchDistTags: vi.fn(async () => ({ latest: '0.10.0' })),
}),
).resolves.toEqual({ notice: null });
});
it('does not show stale cache after the installed version changes and schedules a refresh', async () => {
await mkdir(join(homeDir, '.ktx'), { recursive: true });
await writeFile(
updateCheckCachePath(homeDir),
JSON.stringify(
{
checkedAt: '2026-06-06T11:00:00.000Z',
channel: 'latest',
installedVersion: '0.9.0',
latestForChannel: '0.10.0',
},
null,
2,
),
'utf-8',
);
const fetchDistTags = vi.fn(async () => ({ latest: '0.10.0' }));
const result = await prepareUpdateCheckNotice({
io: makeIo(true).io,
env: { NO_COLOR: '1' },
homeDir,
installedVersion: '0.10.0',
now: () => new Date('2026-06-06T12:00:00.000Z'),
fetchDistTags,
});
expect(result.notice).toBeNull();
expect(fetchDistTags).toHaveBeenCalledTimes(1);
});
it('refreshes stale cache in the background and preserves lastNoticeAt for the same install', async () => {
await mkdir(join(homeDir, '.ktx'), { recursive: true });
await writeFile(
updateCheckCachePath(homeDir),
JSON.stringify(
{
checkedAt: '2026-06-05T10:00:00.000Z',
channel: 'latest',
installedVersion: '0.9.0',
latestForChannel: '0.10.0',
lastNoticeAt: '2026-06-06T09:00:00.000Z',
},
null,
2,
),
'utf-8',
);
await prepareUpdateCheckNotice({
io: makeIo(true).io,
env: { NO_COLOR: '1' },
homeDir,
installedVersion: '0.9.0',
now: () => new Date('2026-06-06T12:00:00.000Z'),
fetchDistTags: vi.fn(async () => ({ latest: '0.11.0' })),
});
await flushAsyncWork();
await vi.waitFor(async () => {
const stored = JSON.parse(await readFile(updateCheckCachePath(homeDir), 'utf-8')) as {
checkedAt: string;
latestForChannel: string;
lastNoticeAt?: string;
};
expect(stored.checkedAt).toBe('2026-06-06T12:00:00.000Z');
expect(stored.latestForChannel).toBe('0.11.0');
expect(stored.lastNoticeAt).toBe('2026-06-06T09:00:00.000Z');
});
});
it('swallows refresh failures and leaves existing cache untouched', async () => {
await mkdir(join(homeDir, '.ktx'), { recursive: true });
const originalCache = {
checkedAt: '2026-06-05T10:00:00.000Z',
channel: 'latest',
installedVersion: '0.9.0',
latestForChannel: '0.10.0',
lastNoticeAt: '2026-06-06T09:00:00.000Z',
};
await writeFile(updateCheckCachePath(homeDir), JSON.stringify(originalCache, null, 2), 'utf-8');
await prepareUpdateCheckNotice({
io: makeIo(true).io,
env: { NO_COLOR: '1' },
homeDir,
installedVersion: '0.9.0',
now: () => new Date('2026-06-06T12:00:00.000Z'),
fetchDistTags: vi.fn(async () => {
throw new Error('offline');
}),
});
await flushAsyncWork();
await expect(readFile(updateCheckCachePath(homeDir), 'utf-8')).resolves.toBe(JSON.stringify(originalCache, null, 2));
});
});