Skip to content

Open-source SEO, GEO, and marketing skills for AI agents.

feat(notfair-cmo): show version + one-click upgrade in sidebar footer

Yuting Zhong3eac50976b28
diff --git a/notfair-cmo/src/app/api/upgrade/route.ts b/notfair-cmo/src/app/api/upgrade/route.ts
new file mode 100644
index 00000000..7143c204
--- /dev/null
+++ b/notfair-cmo/src/app/api/upgrade/route.ts
@@ -0,0 +1,108 @@
+import { spawn } from "node:child_process";
+import { NextResponse } from "next/server";
+
+import { _resetLatestCache, getCurrentVersion, getLatestVersion } from "@/server/version";
+
+export const dynamic = "force-dynamic";
+export const runtime = "nodejs";
+
+const UPGRADE_TIMEOUT_MS = 5 * 60 * 1000;
+const TAIL_BYTES = 4_000;
+
+/**
+ * POST /api/upgrade
+ *
+ * Runs `npm i -g notfair-cmo@latest` from the user's shell environment.
+ * The currently-running notfair-cmo process keeps the old code loaded in
+ * memory (Node module cache), so the user must restart `notfair-cmo` to
+ * pick up the upgraded binary. The response message says so.
+ *
+ * If npm isn't on PATH (e.g. the user runs notfair-cmo from a node_modules
+ * shim that doesn't expose npm globally), we surface the spawn error so
+ * the client can show the copyable command instead.
+ */
+export async function POST() {
+ // Use a login shell so the npm install runs against the user's actual
+ // PATH (Homebrew Node etc.). `-l` ensures their shell profile is read.
+ return new Promise<Response>((resolve) => {
+ const startedAt = Date.now();
+ const child = spawn("npm", ["i", "-g", "notfair-cmo@latest"], {
+ stdio: ["ignore", "pipe", "pipe"],
+ env: process.env,
+ });
+
+ let stdout = "";
+ let stderr = "";
+ const append = (target: "out" | "err") => (chunk: Buffer) => {
+ const text = chunk.toString("utf8");
+ if (target === "out") {
+ stdout = (stdout + text).slice(-TAIL_BYTES);
+ } else {
+ stderr = (stderr + text).slice(-TAIL_BYTES);
+ }
+ };
+ child.stdout?.on("data", append("out"));
+ child.stderr?.on("data", append("err"));
+
+ const killTimer = setTimeout(() => {
+ try {
+ child.kill("SIGTERM");
+ } catch {
+ // best-effort
+ }
+ }, UPGRADE_TIMEOUT_MS);
+
+ child.on("error", (err) => {
+ clearTimeout(killTimer);
+ resolve(
+ NextResponse.json(
+ {
+ ok: false,
+ error: err.message,
+ hint:
+ "Could not run `npm` from the notfair-cmo process. Run `npm i -g notfair-cmo@latest` in your terminal instead.",
+ command: "npm i -g notfair-cmo@latest",
+ },
+ { status: 500 },
+ ),
+ );
+ });
+
+ child.on("exit", async (code) => {
+ clearTimeout(killTimer);
+ const elapsed_ms = Date.now() - startedAt;
+ if (code === 0) {
+ _resetLatestCache();
+ // Confirm by refreshing the version snapshot. The current version
+ // is still the old one (we're still running) — but `latest` from
+ // the registry should now match what we just installed.
+ const latest = await getLatestVersion(true);
+ resolve(
+ NextResponse.json({
+ ok: true,
+ installed_version: latest ?? null,
+ running_version: getCurrentVersion(),
+ note:
+ "Upgraded. Restart notfair-cmo to load the new version (`notfair-cmo` in your terminal).",
+ elapsed_ms,
+ stdout_tail: stdout.slice(-1000),
+ }),
+ );
+ } else {
+ resolve(
+ NextResponse.json(
+ {
+ ok: false,
+ error: `npm exited with code ${code}`,
+ elapsed_ms,
+ stdout_tail: stdout.slice(-1000),
+ stderr_tail: stderr.slice(-1000),
+ command: "npm i -g notfair-cmo@latest",
+ },
+ { status: 500 },
+ ),
+ );
+ }
+ });
+ });
+}
diff --git a/notfair-cmo/src/app/api/version/route.ts b/notfair-cmo/src/app/api/version/route.ts
new file mode 100644
index 00000000..c7387ad1
--- /dev/null
+++ b/notfair-cmo/src/app/api/version/route.ts
@@ -0,0 +1,19 @@
+import { NextResponse } from "next/server";
+
+import { getVersionStatus } from "@/server/version";
+
+export const dynamic = "force-dynamic";
+export const runtime = "nodejs";
+
+/**
+ * GET /api/version
+ *
+ * Returns the installed notfair-cmo version + the latest version on npm
+ * + whether an update is available. The sidebar polls this once on mount;
+ * the latest-version lookup is cached for 1 hour in-process so this is
+ * cheap to call.
+ */
+export async function GET() {
+ const status = await getVersionStatus();
+ return NextResponse.json(status);
+}
diff --git a/notfair-cmo/src/components/app-sidebar.tsx b/notfair-cmo/src/components/app-sidebar.tsx
index 071ef733..42c6465c 100644
--- a/notfair-cmo/src/components/app-sidebar.tsx
+++ b/notfair-cmo/src/components/app-sidebar.tsx
@@ -33,6 +33,7 @@ import { ProjectSwitcher } from "./project-switcher";
import { AgentNav } from "./agent-nav";
import { ApprovalsLiveBadge } from "./live-badge";
import { HarnessFooter } from "./harness-footer";
+import { SidebarVersion } from "./sidebar-version";
type NavItem = {
href: string;
@@ -130,14 +131,15 @@ export async function AppSidebar() {
)}
</SidebarContent>
- {active && harnessUsage && (
- <SidebarFooter className="border-t border-border/60 px-3 py-2 group-data-[collapsible=icon]:hidden">
+ <SidebarFooter className="border-t border-border/60 px-3 py-2 group-data-[collapsible=icon]:hidden">
+ {active && harnessUsage && (
<HarnessFooter
adapter={active.harness_adapter}
usage={harnessUsage}
/>
- </SidebarFooter>
- )}
+ )}
+ <SidebarVersion />
+ </SidebarFooter>
</Sidebar>
);
}
diff --git a/notfair-cmo/src/components/sidebar-version.test.tsx b/notfair-cmo/src/components/sidebar-version.test.tsx
new file mode 100644
index 00000000..04891aee
--- /dev/null
+++ b/notfair-cmo/src/components/sidebar-version.test.tsx
@@ -0,0 +1,134 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { fireEvent, render, screen, waitFor } from "@testing-library/react";
+
+import { SidebarVersion } from "./sidebar-version";
+
+vi.mock("sonner", () => ({
+ toast: { success: vi.fn(), error: vi.fn() },
+}));
+
+const originalFetch = globalThis.fetch;
+
+function mockFetch(handler: (url: string, init?: RequestInit) => unknown) {
+ globalThis.fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
+ const url =
+ typeof input === "string"
+ ? input
+ : input instanceof URL
+ ? input.toString()
+ : input.url;
+ const value = handler(url, init);
+ return new Response(JSON.stringify(value), {
+ status: typeof value === "object" && value && "__status" in value
+ ? (value as { __status: number }).__status
+ : 200,
+ headers: { "content-type": "application/json" },
+ });
+ }) as typeof fetch;
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+});
+
+afterEach(() => {
+ globalThis.fetch = originalFetch;
+});
+
+describe("SidebarVersion", () => {
+ it("renders just the version when no update is available", async () => {
+ mockFetch(() => ({ current: "0.7.0", latest: "0.7.0", has_update: false }));
+ render(<SidebarVersion />);
+ await waitFor(() =>
+ expect(screen.getByText(/notfair-cmo v0\.7\.0/)).toBeInTheDocument(),
+ );
+ expect(screen.queryByRole("button")).not.toBeInTheDocument();
+ });
+
+ it("shows the Update button when has_update=true", async () => {
+ mockFetch(() => ({ current: "0.7.0", latest: "0.8.1", has_update: true }));
+ render(<SidebarVersion />);
+ await waitFor(() =>
+ expect(screen.getByRole("button", { name: /v0\.8\.1 available/ })).toBeInTheDocument(),
+ );
+ });
+
+ it("POSTs /api/upgrade on click and shows 'Restart to apply' on success", async () => {
+ const fetchSpy = vi.fn(
+ async (input: RequestInfo | URL, _init?: RequestInit): Promise<Response> => {
+ const url =
+ typeof input === "string"
+ ? input
+ : input instanceof URL
+ ? input.toString()
+ : input.url;
+ if (url.endsWith("/api/version")) {
+ return new Response(
+ JSON.stringify({ current: "0.7.0", latest: "0.8.0", has_update: true }),
+ { status: 200 },
+ );
+ }
+ if (url.endsWith("/api/upgrade")) {
+ return new Response(JSON.stringify({ ok: true, note: "Upgraded." }), {
+ status: 200,
+ });
+ }
+ return new Response("{}", { status: 200 });
+ },
+ );
+ globalThis.fetch = fetchSpy as typeof fetch;
+
+ render(<SidebarVersion />);
+ const btn = await screen.findByRole("button", { name: /v0\.8\.0 available/ });
+ fireEvent.click(btn);
+
+ await waitFor(() => expect(screen.getByText(/Restart to apply/)).toBeInTheDocument());
+ const upgradeCall = fetchSpy.mock.calls.find(([u]) => String(u).endsWith("/api/upgrade"));
+ expect(upgradeCall).toBeDefined();
+ expect(upgradeCall![1]!.method).toBe("POST");
+ });
+
+ it("keeps the Upgrade button enabled when the API errors (so the user can retry)", async () => {
+ const fetchSpy = vi.fn(async (input: RequestInfo | URL) => {
+ const url =
+ typeof input === "string"
+ ? input
+ : input instanceof URL
+ ? input.toString()
+ : input.url;
+ if (url.endsWith("/api/version")) {
+ return new Response(
+ JSON.stringify({ current: "0.7.0", latest: "0.8.0", has_update: true }),
+ { status: 200 },
+ );
+ }
+ return new Response(
+ JSON.stringify({ ok: false, error: "npm not on PATH", command: "npm i -g notfair-cmo@latest" }),
+ { status: 500 },
+ );
+ });
+ globalThis.fetch = fetchSpy as typeof fetch;
+
+ render(<SidebarVersion />);
+ const btn = await screen.findByRole("button", { name: /v0\.8\.0 available/ });
+ fireEvent.click(btn);
+
+ // After the failed upgrade, the button label resets and stays clickable.
+ await waitFor(() =>
+ expect(screen.getByRole("button", { name: /v0\.8\.0 available/ })).not.toBeDisabled(),
+ );
+ });
+
+ it("falls back to a minimal label when /api/version is unreachable", async () => {
+ globalThis.fetch = vi.fn(async () => {
+ throw new Error("offline");
+ }) as typeof fetch;
+ render(<SidebarVersion />);
+ // Initial render shows the fallback before fetch resolves; offline keeps it.
+ await waitFor(() =>
+ expect(screen.getByText(/notfair-cmo/)).toBeInTheDocument(),
+ );
+ expect(screen.queryByRole("button")).not.toBeInTheDocument();
+ });
+});
diff --git a/notfair-cmo/src/components/sidebar-version.tsx b/notfair-cmo/src/components/sidebar-version.tsx
new file mode 100644
index 00000000..196c59e4
--- /dev/null
+++ b/notfair-cmo/src/components/sidebar-version.tsx
@@ -0,0 +1,117 @@
+"use client";
+
+import { useEffect, useState } from "react";
+import { Loader2, Sparkles } from "lucide-react";
+import { toast } from "sonner";
+
+import { Button } from "@/components/ui/button";
+
+type VersionInfo = {
+ current: string;
+ latest: string | null;
+ has_update: boolean;
+};
+
+/**
+ * Sidebar footer: current version + an Upgrade button when npm reports a
+ * newer version. Clicking Upgrade runs `npm i -g notfair-cmo@latest` via
+ * /api/upgrade and tells the user to restart.
+ */
+export function SidebarVersion() {
+ const [info, setInfo] = useState<VersionInfo | null>(null);
+ const [upgrading, setUpgrading] = useState(false);
+ const [upgraded, setUpgraded] = useState(false);
+
+ useEffect(() => {
+ let cancelled = false;
+ fetch("/api/version", { cache: "no-store" })
+ .then((r) => r.json() as Promise<VersionInfo>)
+ .then((v) => {
+ if (!cancelled) setInfo(v);
+ })
+ .catch(() => {
+ // Offline / blocked — keep the bar empty rather than spam errors.
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, []);
+
+ async function upgrade() {
+ if (!info?.has_update || upgrading) return;
+ setUpgrading(true);
+ try {
+ const res = await fetch("/api/upgrade", { method: "POST" });
+ const body = (await res.json()) as
+ | { ok: true; note?: string }
+ | { ok: false; error?: string; command?: string; hint?: string };
+ if (!res.ok || !body.ok) {
+ const msg = !body.ok
+ ? body.hint ?? body.error ?? "Upgrade failed"
+ : "Upgrade failed";
+ if (!body.ok && body.command) {
+ await navigator.clipboard.writeText(body.command).catch(() => {});
+ toast.error(`${msg}\nCommand copied to clipboard.`, { duration: 10_000 });
+ } else {
+ toast.error(msg, { duration: 8_000 });
+ }
+ return;
+ }
+ setUpgraded(true);
+ toast.success(
+ body.note ??
+ "Upgraded. Restart notfair-cmo in your terminal to apply.",
+ { duration: 15_000 },
+ );
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : String(err));
+ } finally {
+ setUpgrading(false);
+ }
+ }
+
+ if (!info) {
+ return (
+ <div className="px-1 text-[11px] font-mono text-[hsl(var(--notfair-ink-5))]">
+ notfair-cmo
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex items-center justify-between gap-2 px-1 text-[11px]">
+ <span className="font-mono text-[hsl(var(--notfair-ink-4))]">
+ notfair-cmo v{info.current}
+ </span>
+
+ {info.has_update && !upgraded && (
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={upgrading}
+ onClick={upgrade}
+ title={`Update available: v${info.latest}`}
+ className="h-6 gap-1 px-2 text-[10.5px] font-medium"
+ >
+ {upgrading ? (
+ <>
+ <Loader2 className="h-3 w-3 animate-spin" />
+ Upgrading…
+ </>
+ ) : (
+ <>
+ <Sparkles className="h-3 w-3" />
+ v{info.latest} available
+ </>
+ )}
+ </Button>
+ )}
+
+ {upgraded && (
+ <span className="text-[10.5px] text-emerald-600 dark:text-emerald-400">
+ Restart to apply
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/notfair-cmo/src/server/version.test.ts b/notfair-cmo/src/server/version.test.ts
new file mode 100644
index 00000000..cf131596
--- /dev/null
+++ b/notfair-cmo/src/server/version.test.ts
@@ -0,0 +1,136 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ _resetLatestCache,
+ getCurrentVersion,
+ getLatestVersion,
+ getVersionStatus,
+ isSemverGreater,
+} from "./version";
+
+const originalFetch = globalThis.fetch;
+
+beforeEach(() => {
+ _resetLatestCache();
+});
+
+afterEach(() => {
+ _resetLatestCache();
+ globalThis.fetch = originalFetch;
+});
+
+describe("getCurrentVersion", () => {
+ it("returns a non-empty semver string from package.json", () => {
+ const v = getCurrentVersion();
+ expect(v).toMatch(/^\d+\.\d+\.\d+/);
+ });
+});
+
+describe("isSemverGreater", () => {
+ it.each([
+ ["1.0.0", "0.9.9", true],
+ ["1.1.0", "1.0.9", true],
+ ["0.0.2", "0.0.1", true],
+ ["0.0.1", "0.0.1", false],
+ ["0.0.1", "0.0.2", false],
+ ["1.0.0", "1.0.0", false],
+ ["2.0.0", "10.0.0", false],
+ ["10.0.0", "9.99.99", true],
+ ])("isSemverGreater(%s, %s) === %s", (a, b, expected) => {
+ expect(isSemverGreater(a, b)).toBe(expected);
+ });
+
+ it("ignores pre-release / build suffixes (compares numeric core only)", () => {
+ expect(isSemverGreater("1.0.0", "1.0.0-rc.1")).toBe(false);
+ expect(isSemverGreater("1.0.1-rc.1", "1.0.0")).toBe(true);
+ });
+});
+
+describe("getLatestVersion", () => {
+ it("returns the npm registry version on success", async () => {
+ globalThis.fetch = vi.fn(async () =>
+ new Response(JSON.stringify({ version: "9.9.9" }), { status: 200 }),
+ ) as typeof fetch;
+ const v = await getLatestVersion();
+ expect(v).toBe("9.9.9");
+ });
+
+ it("caches within the TTL window", async () => {
+ const spy = vi.fn(async () =>
+ new Response(JSON.stringify({ version: "1.2.3" }), { status: 200 }),
+ );
+ globalThis.fetch = spy as typeof fetch;
+ await getLatestVersion();
+ await getLatestVersion();
+ await getLatestVersion();
+ expect(spy).toHaveBeenCalledTimes(1);
+ });
+
+ it("re-fetches after force=true", async () => {
+ const spy = vi.fn(async () =>
+ new Response(JSON.stringify({ version: "1.2.3" }), { status: 200 }),
+ );
+ globalThis.fetch = spy as typeof fetch;
+ await getLatestVersion();
+ await getLatestVersion(true);
+ expect(spy).toHaveBeenCalledTimes(2);
+ });
+
+ it("returns null on registry errors instead of throwing", async () => {
+ globalThis.fetch = vi.fn(async () =>
+ new Response("server is on fire", { status: 503 }),
+ ) as typeof fetch;
+ expect(await getLatestVersion()).toBeNull();
+ });
+
+ it("returns null when fetch rejects (offline)", async () => {
+ globalThis.fetch = vi.fn(async () => {
+ throw new Error("ECONNREFUSED");
+ }) as typeof fetch;
+ expect(await getLatestVersion()).toBeNull();
+ });
+
+ it("returns null when the response is not JSON or lacks version", async () => {
+ globalThis.fetch = vi.fn(async () =>
+ new Response(JSON.stringify({ name: "notfair-cmo" }), { status: 200 }),
+ ) as typeof fetch;
+ expect(await getLatestVersion()).toBeNull();
+ });
+});
+
+describe("getVersionStatus", () => {
+ it("flags has_update=true when registry reports a newer version", async () => {
+ const current = getCurrentVersion();
+ const bumped = bumpPatch(current);
+ globalThis.fetch = vi.fn(async () =>
+ new Response(JSON.stringify({ version: bumped }), { status: 200 }),
+ ) as typeof fetch;
+ const status = await getVersionStatus();
+ expect(status.current).toBe(current);
+ expect(status.latest).toBe(bumped);
+ expect(status.has_update).toBe(true);
+ });
+
+ it("flags has_update=false when current is the latest", async () => {
+ const current = getCurrentVersion();
+ globalThis.fetch = vi.fn(async () =>
+ new Response(JSON.stringify({ version: current }), { status: 200 }),
+ ) as typeof fetch;
+ const status = await getVersionStatus();
+ expect(status.has_update).toBe(false);
+ });
+
+ it("flags has_update=false (not unknown) when registry is unreachable", async () => {
+ globalThis.fetch = vi.fn(async () => {
+ throw new Error("network down");
+ }) as typeof fetch;
+ const status = await getVersionStatus();
+ expect(status.latest).toBeNull();
+ expect(status.has_update).toBe(false);
+ });
+});
+
+function bumpPatch(v: string): string {
+ const [maj, min, patch] = v.split(".").map((n) => parseInt(n, 10));
+ return `${maj}.${min}.${(patch ?? 0) + 1}`;
+}
diff --git a/notfair-cmo/src/server/version.ts b/notfair-cmo/src/server/version.ts
new file mode 100644
index 00000000..c21e0064
--- /dev/null
+++ b/notfair-cmo/src/server/version.ts
@@ -0,0 +1,95 @@
+/**
+ * Notfair-cmo version helpers.
+ *
+ * Reads the current version from package.json (JSON import is statically
+ * resolved by Next.js so it works in dev, prod standalone, and tests).
+ * Probes the npm registry for the latest published version with a 1-hour
+ * cache so the UI doesn't pound registry.npmjs.org on every refresh.
+ */
+import pkg from "../../package.json";
+
+const PACKAGE_NAME = "notfair-cmo";
+const NPM_REGISTRY_LATEST = `https://registry.npmjs.org/${PACKAGE_NAME}/latest`;
+const NPM_FETCH_TIMEOUT_MS = 5_000;
+const LATEST_CACHE_TTL_MS = 60 * 60 * 1000; // 1 hour
+
+let _cachedLatest: { version: string; checkedAt: number } | null = null;
+
+export function getCurrentVersion(): string {
+ return (pkg as { version?: string }).version ?? "0.0.0";
+}
+
+/**
+ * Fetch the latest published version from npm. Cached in-process for
+ * 1 hour; pass `force` to bypass after a successful upgrade.
+ *
+ * Returns null when the registry is unreachable (offline, network down,
+ * registry 5xx). Callers should treat null as "no update info" rather
+ * than "no update available."
+ */
+export async function getLatestVersion(
+ force = false,
+ now: number = Date.now(),
+): Promise<string | null> {
+ if (
+ !force &&
+ _cachedLatest &&
+ now - _cachedLatest.checkedAt < LATEST_CACHE_TTL_MS
+ ) {
+ return _cachedLatest.version;
+ }
+ try {
+ const res = await fetch(NPM_REGISTRY_LATEST, {
+ signal: AbortSignal.timeout(NPM_FETCH_TIMEOUT_MS),
+ headers: { accept: "application/json" },
+ });
+ if (!res.ok) return null;
+ const data = (await res.json()) as { version?: unknown };
+ if (typeof data.version !== "string") return null;
+ _cachedLatest = { version: data.version, checkedAt: now };
+ return data.version;
+ } catch {
+ return null;
+ }
+}
+
+/** True when `a` is strictly newer than `b` by major.minor.patch ordering. */
+export function isSemverGreater(a: string, b: string): boolean {
+ const pa = parseSemver(a);
+ const pb = parseSemver(b);
+ if (pa.major !== pb.major) return pa.major > pb.major;
+ if (pa.minor !== pb.minor) return pa.minor > pb.minor;
+ return pa.patch > pb.patch;
+}
+
+function parseSemver(v: string): { major: number; minor: number; patch: number } {
+ // Strip any pre-release / build suffix; we only compare the numeric core.
+ const core = v.split(/[-+]/)[0]!;
+ const parts = core.split(".");
+ return {
+ major: Number(parts[0] ?? 0) || 0,
+ minor: Number(parts[1] ?? 0) || 0,
+ patch: Number(parts[2] ?? 0) || 0,
+ };
+}
+
+export interface VersionStatus {
+ current: string;
+ latest: string | null;
+ has_update: boolean;
+}
+
+export async function getVersionStatus(): Promise<VersionStatus> {
+ const current = getCurrentVersion();
+ const latest = await getLatestVersion();
+ return {
+ current,
+ latest,
+ has_update: latest !== null && isSemverGreater(latest, current),
+ };
+}
+
+/** Test-only: forget the cached registry response. */
+export function _resetLatestCache(): void {
+ _cachedLatest = null;
+}