Open-source SEO, GEO, and marketing skills for AI agents.
feat(cli): notfair update + fix the dead in-app update check, add one-click restart
Yuting Zhongf95decc65456
diff --git a/README.md b/README.mdindex 3a6d7610..000c7a70 100644--- a/README.md+++ b/README.md@@ -85,6 +85,7 @@ notfair start Same, with --port <n>, --no-open, --foreground, --data-dnotfair status Running? pid, port, uptime, autostart statenotfair stop Stop the background servernotfair logs Show / follow the server log (-n N, -f)+notfair update Update to the latest npm version + restart the servernotfair autostart enable | disable | status — start at login (macOS launchd)notfair doctor Preflight checks with a Fix: line per failure```diff --git a/notfair/CHANGELOG.md b/notfair/CHANGELOG.mdindex de092998..196f2c71 100644--- a/notfair/CHANGELOG.md+++ b/notfair/CHANGELOG.md@@ -1,5 +1,11 @@# NotFair+## Unreleased++**`notfair update` — one command from "there's a newer version" to running it.** Checks npm, installs globally, and restarts whatever is running: launchd-managed servers restart through the (freshly rewritten) LaunchAgent, background daemons are stopped and relaunched on the same port and data dir, and source checkouts are pointed at `git pull && pnpm build` instead of being paved over.++**In-app updates actually work now — and finish with one click.** The sidebar's update check had been dead since the rebrand: it asked the npm registry for `NotFair`, but the registry is case-sensitive and the package is `notfair`, so the "update available" button never appeared. Fixed — and upgraded: after installing an update, background and launchd-managed servers now show **Restart now**, restart themselves, and reload the page on the new version. No more "go restart it in your terminal" (that note remains only for foreground/dev runs, which the app never kills).+## 0.9.6 — 2026-07-21**NotFair now runs in the background — and survives reboots.** `notfair` (or `notfair start`) detaches the server, waits for it to answer, and opens the UI; your terminal stays free and closing it no longer kills the loop. New lifecycle commands: `notfair status` (pid, port, uptime, health), `notfair stop` (finally implemented), and `notfair logs -f` (server log lives at `~/.notfair/logs/server.log`). `notfair autostart enable` installs a macOS LaunchAgent that starts NotFair at login and restarts it if it crashes — launchd becomes the single owner, so `start`/`stop` delegate to it instead of racing it for the port, the agent captures your shell's PATH so `claude`/`codex` stay reachable at login, and `start` self-heals the entry when an upgrade moves the package on disk. `--foreground` keeps the old attached behavior.diff --git a/notfair/README.md b/notfair/README.mdindex 18fba0dc..5077ee66 100644--- a/notfair/README.md+++ b/notfair/README.md@@ -65,6 +65,7 @@ notfair start Same as above (--foreground to stay attached)notfair status Running? pid, port, uptime, autostart statenotfair stop Stop the background servernotfair logs [-n N] [-f] Show / follow the server log+notfair update Update to the latest npm version + restart the servernotfair autostart enable Start automatically at login (macOS launchd)notfair autostart disable Remove the LaunchAgent + stop the servernotfair autostart status Is the LaunchAgent installed and loaded?@@ -76,6 +77,8 @@ notfair --helpOptions on `start`: `--port <n>` (default 3327), `--no-open`, `--foreground`, `--data-dir <path>`.Options on `doctor`: `--port <n>`, `--data-dir <path>`.+**Updating.** `notfair update` checks npm, installs the newer version globally, and restarts whatever is running — through launchd when autostart is enabled (rewriting the LaunchAgent to the fresh install), or by stopping and relaunching the background daemon. The app has the same flow built in: the sidebar footer shows the running version, an "✨ vX.Y.Z available" button appears when npm has a newer release, and clicking it installs the update and then offers **Restart now** — the server restarts itself (launchd- and daemon-managed runs) and the page reloads on the new version. Foreground/dev runs are never killed from the app; they get a "restart in your terminal" note instead.+When autostart is enabled, launchd owns the server: `notfair start` delegates to it (never spawns a competing copy), `notfair stop` stops it until your next login, and `notfair autostart disable` removes it entirely. The LaunchAgent captures your shell's PATH so the `claude` / `codex` binaries stay reachable at login, and `notfair start` self-heals the entry if an upgrade moved the package on disk. Global install is recommended for autostart — the npx cache can be cleared at any time.`doctor` checks Node ≥ 20 (24 recommended), Claude Code on PATH, Codex on PATH, at least one harness ready, a writable data directory, and a free preferred port. It exits 0 if every check is passing and 1 otherwise, with a `Fix:` line under each failure naming the exact command to run.diff --git a/notfair/bin/cli.mjs b/notfair/bin/cli.mjsindex afa16df5..11f3d2e7 100755--- a/notfair/bin/cli.mjs+++ b/notfair/bin/cli.mjs@@ -99,6 +99,11 @@ programPORT: String(port),HOSTNAME: "127.0.0.1",NOTFAIR_DATA_DIR: opts.dataDir,+ // Tells the server who supervises it, so /api/restart knows whether+ // an in-app "Restart now" is safe (launchd flows through untouched).+ NOTFAIR_MANAGED: opts.foreground+ ? process.env.NOTFAIR_MANAGED ?? "foreground"+ : "daemon",};if (opts.foreground) {@@ -335,6 +340,78 @@ programprocess.exit(failed === 0 ? 0 : 1);});+program+ .command("update")+ .description("Update NotFair to the latest npm version and restart the running server.")+ .option("--data-dir <dir>", "Override data directory", (dir) => resolve(dir), DATA_DIR)+ .action(async (opts) => {+ const current = readPackageVersion();+ const latest = await fetchLatestVersion();+ if (!latest) {+ console.error("Could not reach the npm registry — are you online?");+ process.exit(1);+ }+ if (!isVersionNewer(latest, current)) {+ console.log(`Already on the latest version (v${current}).`);+ return;+ }+ console.log(`Update available: v${current} → v${latest}`);++ // A source checkout can't be updated by npm — don't pave over it.+ if (existsSync(join(PKG_ROOT, "src")) && existsSync(join(PKG_ROOT, "next.config.ts"))) {+ console.log("You're running from source. Update with: git pull && pnpm install && pnpm build");+ process.exit(1);+ }++ console.log(`Installing notfair@${latest} globally…`);+ const installed = await runInherit("npm", ["install", "-g", `notfair@${latest}`]);+ if (!installed) {+ console.error("npm install failed. Try it directly: npm install -g notfair@latest");+ process.exit(1);+ }+ const newCli = await globalCliPath();+ if (PKG_ROOT.includes(`${sep}_npx${sep}`) && newCli) {+ console.log("Installed globally — run future commands as plain `notfair`.");+ }++ // Restart whatever is running so the new version actually loads.+ if (process.platform === "darwin" && existsSync(plistPath())) {+ const cfg = readPlistConfig();+ const port = cfg?.port ?? 3327;+ if (newCli) {+ writeFileSync(plistPath(), renderPlist(port, cfg?.dataDir ?? DATA_DIR, newCli));+ }+ await reloadLaunchAgent();+ const url = `http://127.0.0.1:${port}`;+ const healthy = await waitFor(() => isHealthy(url), 30_000, 500);+ console.log(+ healthy+ ? `Updated to v${latest} — NotFair restarted on ${url}.`+ : `Updated to v${latest}, but the restart hasn't answered yet — check \`notfair status\`.`,+ );+ return;+ }++ const state = getState(opts.dataDir);+ if (state && isPidAlive(state.pid)) {+ if (!newCli) {+ console.log(`Updated to v${latest}. Restart to apply: notfair stop && notfair start`);+ return;+ }+ console.log("Restarting the background server…");+ try {+ process.kill(state.pid, "SIGTERM");+ } catch {}+ await waitFor(() => !isPidAlive(state.pid), 10_000);+ clearState(opts.dataDir);+ const args = [newCli, "start", "--no-open", "--port", String(state.port), "--data-dir", state.data_dir ?? opts.dataDir];+ const ok = await runInherit(process.execPath, args);+ process.exit(ok ? 0 : 1);+ }++ console.log(`Updated to v${latest}. Start it with: notfair start`);+ });+const autostart = program.command("autostart").description("Start NotFair automatically at login (macOS launchd).");@@ -498,6 +575,55 @@ function formatUptime(startedAt) {return ` (up ${Math.floor(h / 24)}d)`;}+// --- update helpers ---++async function fetchLatestVersion() {+ try {+ const res = await fetch("https://registry.npmjs.org/notfair/latest", {+ signal: AbortSignal.timeout(5_000),+ headers: { accept: "application/json" },+ });+ if (!res.ok) return null;+ const data = await res.json();+ return typeof data.version === "string" ? data.version : null;+ } catch {+ return null;+ }+}++/** True when `a` is strictly newer than `b` by major.minor.patch. */+function isVersionNewer(a, b) {+ const parse = (v) => v.split(/[-+]/)[0].split(".").map((n) => Number(n) || 0);+ const [amaj, amin, apat] = parse(a);+ const [bmaj, bmin, bpat] = parse(b);+ if (amaj !== bmaj) return amaj > bmaj;+ if (amin !== bmin) return amin > bmin;+ return apat > bpat;+}++/** The freshly-installed global CLI — stable across upgrades, unlike npx cache paths. */+async function globalCliPath() {+ const r = await runCheck("npm", ["root", "-g"], 15_000);+ if (!r.ok) return null;+ const cli = join(r.stdout.trim(), "notfair", "bin", "cli.mjs");+ return existsSync(cli) ? cli : null;+}++/** Run a command with inherited stdio; true on exit 0. */+function runInherit(cmd, args) {+ return new Promise((resolvePromise) => {+ let child;+ try {+ child = spawn(cmd, args, { stdio: "inherit" });+ } catch {+ resolvePromise(false);+ return;+ }+ child.on("error", () => resolvePromise(false));+ child.on("close", (code) => resolvePromise(code === 0));+ });+}+// --- launchd helpers (macOS autostart) ---function requireDarwin() {@@ -545,10 +671,10 @@ function xmlEscape(s) {* crash). PATH is captured from the enabling shell — launchd's default PATH* would hide the claude/codex binaries the agents need.*/-function renderPlist(port, dataDir) {+function renderPlist(port, dataDir, cliPath = CLI_PATH) {const args = [process.execPath,- CLI_PATH,+ cliPath,"start","--foreground","--no-open",diff --git a/notfair/src/app/api/restart/route.ts b/notfair/src/app/api/restart/route.tsnew file mode 100644index 00000000..6b2cf6ae--- /dev/null+++ b/notfair/src/app/api/restart/route.ts@@ -0,0 +1,107 @@+import { spawn } from "node:child_process";+import { existsSync } from "node:fs";+import { join } from "node:path";+import { NextResponse } from "next/server";++export const dynamic = "force-dynamic";+export const runtime = "nodejs";++/**+ * POST /api/restart+ *+ * Restart the server so a just-installed upgrade actually loads. How+ * depends on who supervises us (NOTFAIR_MANAGED, set by the CLI):+ *+ * - launchd: exit(0) — KeepAlive brings us straight back on the same+ * plist, whose global-install path npm just updated in place.+ * - daemon: no supervisor, so hand off to a detached waiter process that+ * watches for our pid to die, then starts the freshly-installed CLI on+ * the same port and data dir.+ * - foreground/dev: refuse — killing the process under a user's terminal+ * (or `pnpm dev`) is their call, not ours.+ */+export async function POST() {+ const managed = process.env.NOTFAIR_MANAGED ?? null;++ if (managed === "launchd") {+ scheduleExit();+ return NextResponse.json({ ok: true, note: "Restarting via launchd…" });+ }++ if (managed === "daemon") {+ const cli = await globalCliPath();+ if (!cli) {+ return NextResponse.json(+ {+ ok: false,+ error: "Could not locate the globally-installed notfair CLI.",+ hint: "Restart from your terminal: notfair stop && notfair start",+ },+ { status: 409 },+ );+ }+ const port = process.env.PORT ?? "3327";+ const dataDir = process.env.NOTFAIR_DATA_DIR ?? "";+ // The waiter must outlive us and only bind the port once we're gone.+ const waiter = `+ const [pid, cli, port, dataDir] = process.argv.slice(1);+ const deadline = Date.now() + 30000;+ const timer = setInterval(() => {+ let dead = false;+ try { process.kill(Number(pid), 0); } catch { dead = true; }+ if (!dead && Date.now() < deadline) return;+ clearInterval(timer);+ if (dead) {+ const { spawn } = require("node:child_process");+ const args = [cli, "start", "--no-open", "--port", port];+ if (dataDir) args.push("--data-dir", dataDir);+ spawn(process.execPath, args, { detached: true, stdio: "ignore" }).unref();+ }+ process.exit(0);+ }, 300);+ `;+ spawn(+ process.execPath,+ ["-e", waiter, String(process.pid), cli, port, dataDir],+ { detached: true, stdio: "ignore" },+ ).unref();+ scheduleExit();+ return NextResponse.json({ ok: true, note: "Restarting…" });+ }++ return NextResponse.json(+ {+ ok: false,+ error: `Not restartable from the app (mode: ${managed ?? "unknown"}).`,+ hint: "Restart NotFair from the terminal that runs it.",+ },+ { status: 409 },+ );+}++function scheduleExit() {+ // Let the response flush before dying.+ setTimeout(() => process.exit(0), 500).unref();+}++async function globalCliPath(): Promise<string | null> {+ const root = await new Promise<string | null>((resolve) => {+ let out = "";+ let child;+ try {+ child = spawn("npm", ["root", "-g"], { stdio: ["ignore", "pipe", "ignore"] });+ } catch {+ resolve(null);+ return;+ }+ child.stdout.on("data", (c) => {+ out += c.toString();+ });+ child.on("error", () => resolve(null));+ child.on("close", (code) => resolve(code === 0 ? out.trim() : null));+ setTimeout(() => resolve(null), 10_000).unref();+ });+ if (!root) return null;+ const cli = join(root, "notfair", "bin", "cli.mjs");+ return existsSync(cli) ? cli : null;+}diff --git a/notfair/src/app/api/upgrade/route.ts b/notfair/src/app/api/upgrade/route.tsindex d15fec22..04d52c20 100644--- a/notfair/src/app/api/upgrade/route.ts+++ b/notfair/src/app/api/upgrade/route.ts@@ -77,13 +77,19 @@ export async function POST() {// 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);+ // launchd/daemon servers can restart themselves via /api/restart;+ // foreground and dev runs belong to the user's terminal.+ const managed = process.env.NOTFAIR_MANAGED ?? null;+ const canRestart = managed === "launchd" || managed === "daemon";resolve(NextResponse.json({ok: true,installed_version: latest ?? null,running_version: getCurrentVersion(),- note:- "Upgraded. Restart NotFair to load the new version (`notfair` in your terminal).",+ can_restart: canRestart,+ note: canRestart+ ? "Upgraded — restarting loads the new version."+ : "Upgraded. Restart NotFair to load the new version (`notfair` in your terminal).",elapsed_ms,stdout_tail: stdout.slice(-1000),}),diff --git a/notfair/src/components/sidebar-version.tsx b/notfair/src/components/sidebar-version.tsxindex 04915359..287134ec 100644--- a/notfair/src/components/sidebar-version.tsx+++ b/notfair/src/components/sidebar-version.tsx@@ -1,7 +1,7 @@"use client";import { useEffect, useState } from "react";-import { Loader2, Sparkles } from "lucide-react";+import { Loader2, RefreshCw, Sparkles } from "lucide-react";import { toast } from "sonner";import { Button } from "@/components/ui/button";@@ -12,15 +12,18 @@ type VersionInfo = {has_update: boolean;};+type Phase = "idle" | "upgrading" | "restartable" | "restarting" | "manual";+/**- * Sidebar footer: current version + an Upgrade button when npm reports a- * newer version. Clicking Upgrade runs `npm i -g notfair@latest` via- * /api/upgrade and tells the user to restart.+ * Sidebar footer: current version + the update flow. When npm reports a+ * newer version an Update button appears; clicking it runs+ * `npm i -g notfair@latest` via /api/upgrade. Background/launchd servers+ * then offer one-click Restart (/api/restart) and the page reloads on the+ * new version; foreground/dev runs are told to restart from the terminal.*/export function SidebarVersion() {const [info, setInfo] = useState<VersionInfo | null>(null);- const [upgrading, setUpgrading] = useState(false);- const [upgraded, setUpgraded] = useState(false);+ const [phase, setPhase] = useState<Phase>("idle");useEffect(() => {let cancelled = false;@@ -38,12 +41,12 @@ export function SidebarVersion() {}, []);async function upgrade() {- if (!info?.has_update || upgrading) return;- setUpgrading(true);+ if (!info?.has_update || phase !== "idle") return;+ setPhase("upgrading");try {const res = await fetch("/api/upgrade", { method: "POST" });const body = (await res.json()) as- | { ok: true; note?: string }+ | { ok: true; note?: string; can_restart?: boolean }| { ok: false; error?: string; command?: string; hint?: string };if (!res.ok || !body.ok) {const msg = !body.ok@@ -55,24 +58,74 @@ export function SidebarVersion() {} else {toast.error(msg, { duration: 8_000 });}+ setPhase("idle");return;}- setUpgraded(true);- toast.success(- body.note ??- "Upgraded. Restart NotFair in your terminal to apply.",- { duration: 15_000 },- );+ if (body.can_restart) {+ setPhase("restartable");+ toast.success(`v${info.latest} installed — restart to apply.`, {+ duration: 10_000,+ });+ } else {+ setPhase("manual");+ toast.success(+ body.note ?? "Upgraded. Restart NotFair in your terminal to apply.",+ { duration: 15_000 },+ );+ }} catch (err) {toast.error(err instanceof Error ? err.message : String(err));- } finally {- setUpgrading(false);+ setPhase("idle");+ }+ }++ async function restart() {+ if (phase !== "restartable") return;+ setPhase("restarting");+ try {+ const res = await fetch("/api/restart", { method: "POST" });+ const body = (await res.json()) as { ok: boolean; hint?: string };+ if (!res.ok || !body.ok) {+ toast.error(body.hint ?? "Could not restart from here — use your terminal.", {+ duration: 10_000,+ });+ setPhase("manual");+ return;+ }+ } catch {+ // The server may die mid-response — that's the restart happening.}+ // Poll until the new version answers, then hard-reload so the client+ // bundle matches the server again.+ const target = info?.latest ?? null;+ const deadline = Date.now() + 60_000;+ const poll = async () => {+ try {+ const v = (await (+ await fetch("/api/version", { cache: "no-store" })+ ).json()) as VersionInfo;+ if (!target || v.current === target) {+ window.location.reload();+ return;+ }+ } catch {+ // Still down — keep waiting.+ }+ if (Date.now() < deadline) {+ setTimeout(poll, 1_500);+ } else {+ toast.error("The server hasn't come back yet — check `notfair status`.", {+ duration: 10_000,+ });+ setPhase("manual");+ }+ };+ setTimeout(poll, 2_000);}if (!info) {return (- <div className="px-1 text-[11px] font-mono text-[hsl(var(--notfair-ink-5))]">+ <div className="px-1 text-[11px] font-mono text-[hsl(var(--notfair-ink-4))]">NotFair</div>);@@ -84,19 +137,19 @@ export function SidebarVersion() {NotFair v{info.current}</span>- {info.has_update && !upgraded && (+ {info.has_update && (phase === "idle" || phase === "upgrading") && (<Buttonsize="sm"variant="outline"- disabled={upgrading}+ disabled={phase === "upgrading"}onClick={upgrade}title={`Update available: v${info.latest}`}className="h-6 gap-1 px-2 text-[10.5px] font-medium">- {upgrading ? (+ {phase === "upgrading" ? (<><Loader2 className="h-3 w-3 animate-spin" />- Upgrading…+ Updating…</>) : (<>@@ -107,7 +160,29 @@ export function SidebarVersion() {</Button>)}- {upgraded && (+ {(phase === "restartable" || phase === "restarting") && (+ <Button+ size="sm"+ variant="outline"+ disabled={phase === "restarting"}+ onClick={restart}+ className="h-6 gap-1 px-2 text-[10.5px] font-medium"+ >+ {phase === "restarting" ? (+ <>+ <Loader2 className="h-3 w-3 animate-spin" />+ Restarting…+ </>+ ) : (+ <>+ <RefreshCw className="h-3 w-3" />+ Restart now+ </>+ )}+ </Button>+ )}++ {phase === "manual" && (<span className="text-[10.5px] text-[hsl(var(--notfair-accent))]">Restart to apply</span>diff --git a/notfair/src/server/version.test.ts b/notfair/src/server/version.test.tsnew file mode 100644index 00000000..58b6fcb7--- /dev/null+++ b/notfair/src/server/version.test.ts@@ -0,0 +1,42 @@+import { afterEach, describe, expect, it, vi } from "vitest";++import {+ _resetLatestCache,+ getLatestVersion,+ isSemverGreater,+} from "@/server/version";++afterEach(() => {+ _resetLatestCache();+ vi.unstubAllGlobals();+});++describe("getLatestVersion", () => {+ it("queries the lowercase npm package name (the registry is case-sensitive)", async () => {+ const fetchMock = vi.fn(async (_input: RequestInfo | URL, _init?: RequestInit) =>+ new Response(JSON.stringify({ version: "9.9.9" }), { status: 200 }),+ );+ vi.stubGlobal("fetch", fetchMock);+ const latest = await getLatestVersion(true);+ expect(latest).toBe("9.9.9");+ expect(String(fetchMock.mock.calls[0]![0])).toBe(+ "https://registry.npmjs.org/notfair/latest",+ );+ });++ it("returns null on registry errors instead of throwing", async () => {+ vi.stubGlobal("fetch", vi.fn(async () => new Response("nope", { status: 404 })));+ expect(await getLatestVersion(true)).toBeNull();+ });+});++describe("isSemverGreater", () => {+ it("orders by major.minor.patch and ignores pre-release suffixes", () => {+ expect(isSemverGreater("0.9.7", "0.9.6")).toBe(true);+ expect(isSemverGreater("0.10.0", "0.9.9")).toBe(true);+ expect(isSemverGreater("1.0.0", "0.99.99")).toBe(true);+ expect(isSemverGreater("0.9.6", "0.9.6")).toBe(false);+ expect(isSemverGreater("0.9.5", "0.9.6")).toBe(false);+ expect(isSemverGreater("0.9.7-beta.1", "0.9.6")).toBe(true);+ });+});diff --git a/notfair/src/server/version.ts b/notfair/src/server/version.tsindex 31a30868..abf9a9cc 100644--- a/notfair/src/server/version.ts+++ b/notfair/src/server/version.ts@@ -8,7 +8,9 @@*/import pkg from "../../package.json";-const PACKAGE_NAME = "NotFair";+// npm package names are lowercase and the registry is case-sensitive —+// "NotFair" 404s and silently kills the update check.+const PACKAGE_NAME = "notfair";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