Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(code): /whatsnew + graceful one-time update-available notices

Salman Qureshi6cf3682b619a
diff --git a/src/channels/cli.ts b/src/channels/cli.ts
index c229b755..78fcd8bf 100644
--- a/src/channels/cli.ts
+++ b/src/channels/cli.ts
@@ -306,6 +306,9 @@ export interface TuiState {
/** TUI frame freeze (scroll lock): all frame writes stop so the user can
* scroll/copy freely while the chat continues underneath. Ctrl+S toggles. */
tuiFrozen: boolean;
+ /** A newer Mercury version the background check found — shown as a tiny
+ * bottom-bar indicator (⬆ vX) in Mercury Code until ignored. */
+ updateAvailable: string | null;
}
const defaultState: TuiState = {
@@ -338,6 +341,7 @@ const defaultState: TuiState = {
exitEscArmed: false,
liveActivity: null,
tuiFrozen: false,
+ updateAvailable: null,
};
function shallowEqualSubAgents(a: SubAgentInfo[], b: SubAgentInfo[]): boolean {
@@ -366,6 +370,17 @@ export class CLIChannel extends BaseChannel {
private menuDepth = 0;
private menuAbortController: AbortController | null = null;
private heartbeatMsgId: string | null = null;
+
+ /** update-notice helpers, imported lazily (a static import would pull
+ * cli/daemon.js into an import cycle through channels/cli.ts). */
+ private updateNoticeApiPromise: Promise<any> | null = null;
+
+ private updateNoticeApi() {
+ if (!this.updateNoticeApiPromise) {
+ this.updateNoticeApiPromise = import('../cli/update-notice.js');
+ }
+ return this.updateNoticeApiPromise;
+ }
private stepCount = 0;
private stepStartTime = 0;
private state: TuiState = { ...defaultState };
@@ -1644,9 +1659,42 @@ export class CLIChannel extends BaseChannel {
try {
process.stdout.write('\x1b[2J\x1b[H');
} catch { /* ignore */ }
+ // Graceful one-time notices (never blocking, never repeated): the
+ // /whatsnew hint when this boot is a fresh install or an update, and a
+ // throttled background update check. Entirely async and unref'd — a slow
+ // npm look-up must never stall the TUI.
+ void this.announceVersionNotices(version);
return { ok: true, message: `Mercury Code active in ${dirName}` };
}
+ /**
+ * One-time, once-per-version notices on Mercury Code entry. Tests skip the
+ * network check (VITEST); the hint is persisted in update-state.json so it
+ * cannot repeat for the same version even across restarts.
+ */
+ private async announceVersionNotices(version: string): Promise<void> {
+ if (process.env.VITEST || process.env.MERCURY_NO_UPDATE_CHECK === '1') return;
+ try {
+ const { shouldShowWhatsNewHint, markWhatsNewHintShown, maybeCheckForUpdate } = await this.updateNoticeApi();
+ if (shouldShowWhatsNewHint(version)) {
+ markWhatsNewHintShown(version);
+ this.sendSystemNotice(`☿ Mercury v${version} is here. Type \`/whatsnew\` to see what's new.`);
+ }
+ const latest = await maybeCheckForUpdate(version);
+ if (latest) {
+ this.setUpdateAvailable(latest);
+ this.sendSystemNotice(`⬆ Update available: v${version} → v${latest}. Run \`mercury upgrade\` in your terminal when you're ready — or ignore this version with \`/update ignore\`.`);
+ }
+ } catch (err) {
+ logger.debug({ err }, 'announceVersionNotices failed (non-fatal)');
+ }
+ }
+
+ /** Latest version the user hasn't ignored (for /update ignore even when the check is throttled). */
+ setUpdateAvailable(latestVersion: string | null): void {
+ this.update({ updateAvailable: latestVersion });
+ }
+
exitMercuryCode(): void {
if (this.state.mercuryCode) {
this.setMouseEnabled(false);
diff --git a/src/cli/update-notice.test.ts b/src/cli/update-notice.test.ts
new file mode 100644
index 00000000..9ff99436
--- /dev/null
+++ b/src/cli/update-notice.test.ts
@@ -0,0 +1,97 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { mkdirSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import {
+ isNewerVersion,
+ latestSeenUpdate,
+ markWhatsNewHintShown,
+ maybeCheckForUpdate,
+ shouldShowWhatsNewHint,
+ ignoreUpdateVersion,
+} from './update-notice.js';
+import { whatsNewText } from '../utils/whats-new.js';
+
+// The helpers persist to ~/.mercury — point MERCURY_HOME at a temp dir so
+// tests never touch the real state file. The dir must exist (saveUpdateState
+// refuses to recreate a torn-down home by design).
+const tempHome = join(tmpdir(), `mercury-update-notice-test-${process.pid}`);
+
+beforeEach(() => {
+ mkdirSync(tempHome, { recursive: true });
+ process.env.MERCURY_HOME = tempHome;
+});
+
+afterEach(() => {
+ delete process.env.MERCURY_HOME;
+ rmSync(tempHome, { recursive: true, force: true });
+});
+
+/**
+ * Anti-nag contract: the /whatsnew hint fires ONCE per version (first launch
+ * or update), the update check is throttled and silent about ignored
+ * versions, and nothing ever blocks or repeats.
+ */
+describe('update-notice (graceful, once-per-version)', () => {
+ it('shows the hint on first launch ever, then never again for the same version', () => {
+ expect(shouldShowHelper('1.2.9')).toBe(true); // first launch ever
+ markWhatsNewHintShown('1.2.9');
+ expect(shouldShowHelper('1.2.9')).toBe(false); // same version → silent
+ expect(shouldShowHelper('1.3.0')).toBe(true); // update → one new hint
+ markWhatsNewHintShown('1.3.0');
+ expect(shouldShowHelper('1.3.0')).toBe(false);
+ });
+
+ it('never shows the hint after a DOWNGRADE (rollbacks are not "new")', () => {
+ markWhatsNewHintShown('1.3.0');
+ expect(shouldShowHelper('1.2.3')).toBe(false);
+ });
+
+ it('compares versions numerically (not lexically)', () => {
+ expect(isNewerVersion('1.10.0', '1.9.0')).toBe(true);
+ expect(isNewerVersion('1.9.0', '1.10.0')).toBe(false);
+ expect(isNewerVersion('1.2.9', '1.2.9')).toBe(false);
+ expect(isNewerVersion('v1.3.0', '1.2.9')).toBe(true);
+ });
+
+ it('update check is throttled and respects the ignored version (no network)', async () => {
+ // Pre-seed a throttled state (checked just now) with a newer version —
+ // maybeCheckForUpdate must reuse it without touching npm.
+ const { saveUpdateState } = await import('./update-notice.js');
+ saveUpdateState({ checkedAt: Date.now(), latestSeen: '2.0.0' });
+ expect(await maybeCheckForUpdate('1.2.9')).toBe('2.0.0');
+
+ // Ignoring the offered version silences it.
+ ignoreUpdateVersion('2.0.0');
+ expect(await maybeCheckForUpdate('1.2.9')).toBeNull();
+
+ // A DIFFERENT newer version is still offered.
+ saveUpdateState({ checkedAt: Date.now(), latestSeen: '2.1.0', ignoredUpdate: '2.0.0' });
+ expect(await maybeCheckForUpdate('1.2.9')).toBe('2.1.0');
+ });
+
+ it('latestSeenUpdate only reports versions newer than the running one', async () => {
+ const { saveUpdateState } = await import('./update-notice.js');
+ saveUpdateState({ checkedAt: Date.now(), latestSeen: '2.1.0' });
+ expect(latestSeenUpdate('1.2.9')).toBe('2.1.0');
+ saveUpdateState({ checkedAt: Date.now(), latestSeen: '1.2.9' });
+ expect(latestSeenUpdate('1.2.9')).toBeNull();
+ });
+});
+
+describe('/whatsnew content', () => {
+ it('renders curated highlights for a published version', () => {
+ const text = whatsNewText('1.2.9');
+ expect(text).toContain("**What's new in v1.2.9**");
+ expect(text).toContain('• **Progressive streaming**');
+ });
+
+ it('falls back to the releases link for unknown versions', () => {
+ const text = whatsNewText('9.9.9');
+ expect(text).toContain('releases');
+ });
+});
+
+function shouldShowHelper(v: string): boolean {
+ return shouldShowWhatsNewHint(v);
+}
\ No newline at end of file
diff --git a/src/cli/update-notice.ts b/src/cli/update-notice.ts
new file mode 100644
index 00000000..40a801e2
--- /dev/null
+++ b/src/cli/update-notice.ts
@@ -0,0 +1,130 @@
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { execFile } from 'node:child_process';
+import { getMercuryHome } from '../utils/config.js';
+import { logger } from '../utils/logger.js';
+
+/**
+ * Version-aware, GRACEFUL notices for Mercury Code:
+ *
+ * 1. One-time `/whatsnew` hint — shown only when the running version differs
+ * from the last one this machine booted (first install OR an update).
+ * Persisted, so it can never repeat for the same version.
+ * 2. Background update check — throttled to once per CHECK_INTERVAL_MS,
+ * entirely async (never blocks boot), and quiet about versions the user
+ * ignored via `/update ignore`.
+ *
+ * Anti-annoyance rules baked in: every notice fires at most once per version
+ * (persisted markers, not memory), nothing repeats within a boot, and the
+ * user can silence update banners for a given version permanently.
+ */
+
+interface UpdateState {
+ /** The version last booted on this machine — the "first time" marker. */
+ lastLaunchVersion?: string;
+ /** The latest version the user chose to ignore (`/update ignore`). */
+ ignoredUpdate?: string;
+ /** Last background check (ms epoch) — throttles npm lookups. */
+ checkedAt?: number;
+ /** Latest version observed by the last successful check. */
+ latestSeen?: string;
+}
+
+const STATE_PATH = () => join(getMercuryHome(), 'update-state.json');
+const CHECK_INTERVAL_MS = 12 * 60 * 60 * 1000; // at most one npm look-up per 12h
+
+export function loadUpdateState(): UpdateState {
+ try {
+ if (existsSync(STATE_PATH())) return JSON.parse(readFileSync(STATE_PATH(), 'utf-8')) as UpdateState;
+ } catch { /* corrupt state → start clean */ }
+ return {};
+}
+
+export function saveUpdateState(state: UpdateState): void {
+ try {
+ if (!existsSync(getMercuryHome())) return; // home torn down → nothing to persist
+ writeFileSync(STATE_PATH(), JSON.stringify(state, null, 2), 'utf-8');
+ } catch (err) {
+ logger.debug({ err }, 'update-notice: failed to persist state');
+ }
+}
+
+/** Numeric semver comparison: returns true when `a` is strictly newer than `b`. */
+export function isNewerVersion(a: string, b: string): boolean {
+ const parse = (v: string) => v.replace(/^v/, '').split(/[.\-]/).map((p) => parseInt(p, 10) || 0);
+ const [pa, pb] = [parse(a), parse(b)];
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
+ const diff = (pa[i] ?? 0) - (pb[i] ?? 0);
+ if (diff !== 0) return diff > 0;
+ }
+ return false;
+}
+
+/**
+ * Should the one-time "/whatsnew" hint show for this boot? True when this is
+ * the first launch ever (no marker) or the version CHANGED (fresh install or
+ * an update). False for every subsequent boot of the same version.
+ */
+export function shouldShowWhatsNewHint(currentVersion: string): boolean {
+ const state = loadUpdateState();
+ if (state.lastLaunchVersion === currentVersion) return false;
+ return state.lastLaunchVersion === undefined || isNewerVersion(currentVersion, state.lastLaunchVersion);
+}
+
+/** Persist that this version's hint has been shown — the anti-nag guarantee. */
+export function markWhatsNewHintShown(currentVersion: string): void {
+ const state = loadUpdateState();
+ state.lastLaunchVersion = currentVersion;
+ saveUpdateState(state);
+}
+
+/** The version the user ignored (`/update ignore`), if any. */
+export function getIgnoredUpdateVersion(): string | undefined {
+ return loadUpdateState().ignoredUpdate;
+}
+
+/** Permanently silence update notices for this specific newer version. */
+export function ignoreUpdateVersion(latestVersion: string): void {
+ const state = loadUpdateState();
+ state.ignoredUpdate = latestVersion;
+ saveUpdateState(state);
+}
+
+/** Async `npm view` with a hard timeout — must never stall a boot. */
+function fetchLatestNpmVersion(packageName: string, timeoutMs = 8_000): Promise<string | null> {
+ return new Promise((resolve) => {
+ execFile('npm', ['view', packageName, 'version'], { timeout: timeoutMs, encoding: 'utf-8' }, (err, stdout) => {
+ resolve(err ? null : String(stdout).trim() || null);
+ });
+ });
+}
+
+/**
+ * Background update check. Throttled (one remote look-up per CHECK_INTERVAL_MS
+ * across ALL boots), fully async, silent on failure. Returns the latest
+ * version when an update exists AND the user has not ignored it.
+ */
+export async function maybeCheckForUpdate(
+ currentVersion: string,
+ packageName = '@cosmicstack/mercury-agent',
+): Promise<string | null> {
+ const state = loadUpdateState();
+ const throttled = state.checkedAt !== undefined && Date.now() - state.checkedAt < CHECK_INTERVAL_MS;
+
+ let latest = throttled ? state.latestSeen : undefined;
+ if (!throttled) {
+ latest = (await fetchLatestNpmVersion(packageName)) ?? state.latestSeen;
+ saveUpdateState({ ...state, checkedAt: Date.now(), latestSeen: latest ?? state.latestSeen });
+ }
+
+ if (!latest || !isNewerVersion(latest, currentVersion)) return null;
+ if (state.ignoredUpdate === latest) return null; // user chose to ignore this version
+ return latest;
+}
+
+/** Latest version the check last saw (for `/update ignore` even when throttled). */
+export function latestSeenUpdate(currentVersion: string): string | null {
+ const state = loadUpdateState();
+ if (state.latestSeen && isNewerVersion(state.latestSeen, currentVersion)) return state.latestSeen;
+ return null;
+}
\ No newline at end of file
diff --git a/src/core/agent.ts b/src/core/agent.ts
index af5a5d13..daa15dfd 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -81,6 +81,7 @@ import { MAX_EXECUTE_CONTINUATIONS, MAX_VERIFICATION_CONTINUATIONS, executeConti
import { classifyTurnEnd, stepsExhaustedPrompt, STEPS_PAUSED_BANNER, WORK_NOT_STARTED_BANNER, type LoopEndCause } from './completion-verdict.js';
import { StallWatchdog } from './stall-watchdog.js';
import { buildFileChangePreview } from '../utils/file-preview.js';
+import { whatsNewText } from '../utils/whats-new.js';
/**
* Step-aware text stream for the TUI. The SDK's textStream concatenates
@@ -4997,6 +4998,41 @@ Is this productive iteration or a stuck loop?`,
return true;
}
+ if (cmd === '/whatsnew' || cmd.startsWith('/whatsnew ')) {
+ // Curated highlights for the running version — one friendly block,
+ // exhaustive notes stay in CHANGELOG.md / the releases page.
+ const runningVersion = channelType === 'cli' && channel instanceof CLIChannel
+ ? (channel.getTuiState().version || 'dev')
+ : 'dev';
+ await channel.send(whatsNewText(runningVersion), channelId).catch((e) => logger.warn({ e }, 'channel send failed'));
+ return true;
+ }
+
+ if (cmd.startsWith('/update')) {
+ const sub = trimmed.slice('/update'.length).trim().toLowerCase();
+ if (sub === 'ignore') {
+ const { latestSeenUpdate, ignoreUpdateVersion, getIgnoredUpdateVersion } = await import('../cli/update-notice.js');
+ const runningVersion = channelType === 'cli' && channel instanceof CLIChannel
+ ? (channel.getTuiState().version || 'dev')
+ : 'dev';
+ const target = latestSeenUpdate(runningVersion);
+ if (!target) {
+ await channel.send('Nothing to ignore — no update was offered for this version.', channelId);
+ return true;
+ }
+ if (getIgnoredUpdateVersion() === target) {
+ await channel.send(`Update to v${target} is already ignored.`, channelId);
+ return true;
+ }
+ ignoreUpdateVersion(target);
+ if (channel instanceof CLIChannel) channel.setUpdateAvailable(null);
+ await channel.send(`Ignored — update notices for v${target} are silenced permanently. \`mercury upgrade\` in the terminal still works whenever you want it.`, channelId);
+ return true;
+ }
+ await channel.send('Usage: `/update ignore` — permanently silence the offered update notice.', channelId);
+ return true;
+ }
+
if (cmd === '/saver' || cmd.startsWith('/saver ')) {
await this.handleSaverCommand(trimmed.slice('/saver'.length).trim(), channelType, channelId);
return true;
diff --git a/src/ui/App.tsx b/src/ui/App.tsx
index 15735113..6792862c 100644
--- a/src/ui/App.tsx
+++ b/src/ui/App.tsx
@@ -2725,6 +2725,9 @@ export function MercuryCodeView({
// Developer status HUD: token budget is otherwise invisible in Mercury
// Code (TokenBarView only renders in chat surfaces).
if (state.tokenInfo) rightSegs.push({ text: `⚡ ${Math.round(state.tokenInfo.percentage)}%`, color: 'green' });
+ // Update-available indicator: one dim segment, no extra row — ignorable via
+ // /update ignore, so it must never crowd the bar.
+ if (state.updateAvailable) rightSegs.push({ text: `⬆ v${state.updateAvailable}`, color: 'yellow' });
// Fit: drop whole segments from the right when the terminal is narrow.
const SEP = ' · ';
let segWidth = 4; // paddingX on both sides
diff --git a/src/utils/manual.ts b/src/utils/manual.ts
index eea00979..515b2e96 100644
--- a/src/utils/manual.ts
+++ b/src/utils/manual.ts
@@ -114,6 +114,8 @@ export function getManual(): string {
['/pair', 'Start Telegram pairing or request Telegram access'],
['/', 'Open the CLI command picker with arrow-key navigation'],
['/menu', 'Open the CLI command picker with arrow-key navigation'],
+ ['/whatsnew', "See what's new in this Mercury version"],
+ ['/update ignore', 'Silence the offered update notice permanently'],
['/help', 'Show this manual'],
['/status', 'Show config and budget info'],
['/sessions', 'List active canonical sessions'],
diff --git a/src/utils/whats-new.ts b/src/utils/whats-new.ts
new file mode 100644
index 00000000..a6a69447
--- /dev/null
+++ b/src/utils/whats-new.ts
@@ -0,0 +1,40 @@
+/**
+ * Curated "what's new" highlights per release, shown by the `/whatsnew`
+ * chat command. Keep entries to a handful of user-facing bullets — this is
+ * read by humans, not changelog archivists; the exhaustive list lives in
+ * CHANGELOG.md and on the releases page.
+ */
+const WHATS_NEW: Record<string, string[]> = {
+ '1.2.9': [
+ '**Progressive streaming** — Mercury Code now builds the document in native scrollback while it streams; you watch sections appear styled as they finish, instead of a wall of newest lines.',
+ '**End-of-task summary** — what was done, how many files changed (top 5 listed), and suggested next steps in the completion banner.',
+ '**Contextual status words** — the spinner says "Painting the UI" or "Hunting the bug" based on your request. Zero LLM tokens.',
+ '**Chat → Mercury Code hand-off** — normal chat asks once when a task looks like coding work; your choice is remembered per session.',
+ '**Provider fallback visibility** — expired token? You now see a respectful one-line notice naming the provider, the reason, and which route the task continues on.',
+ '`mercury code` launches the coding TUI straight from the terminal; `mercury uninstall` removes everything cleanly.',
+ ],
+};
+
+const RELEASES_URL = 'https://github.com/cosmicstack-labs/mercury-agent/releases';
+
+/** Markdown text for `/whatsnew` — falls back to the releases link for unknown versions. */
+export function whatsNewText(currentVersion: string): string {
+ const version = currentVersion.replace(/^v/, '');
+ const highlights = WHATS_NEW[version];
+
+ const lines: string[] = [];
+ if (highlights && highlights.length > 0) {
+ lines.push(`**What's new in v${version}**`);
+ lines.push('');
+ for (const item of highlights) lines.push(`• ${item}`);
+ lines.push('');
+ lines.push('Exhaustive notes: `CHANGELOG.md` in the install directory.');
+ } else {
+ lines.push(`**Mercury v${version}**`);
+ lines.push('');
+ lines.push('Curated highlights for this version are not published yet — the full release notes live here:');
+ }
+ lines.push('');
+ lines.push(`All releases: https://github.com/cosmicstack-labs/mercury-agent/releases`);
+ return lines.join('\n');
+}
\ No newline at end of file