Skip to content

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

fix(updater): stage releases until user applies

Yuting Zhong7e91b24e7e97
diff --git a/notfair/CHANGELOG.md b/notfair/CHANGELOG.md
index 3d4b81fd..ccdab93e 100644
--- a/notfair/CHANGELOG.md
+++ b/notfair/CHANGELOG.md
@@ -1,5 +1,9 @@
# NotFair
+## 0.9.15 — 2026-07-21
+
+**Background updates no longer modify a running installation.** NotFair now downloads the exact npm release into its local update cache without installing it; only clicking **Update to v…** performs the global install, immediately restarts a managed server, and reloads the app. This removes the live-file replacement window that could leave Chrome requesting chunks from two different builds.
+
## 0.9.14 — 2026-07-21
**Goal chat now reflects Codex’s real model defaults and reasoning controls.** The model menu no longer duplicates the configured default, and each provider-supported reasoning effort can be selected per goal and carried safely through the chat API to the Codex CLI.
diff --git a/notfair/package.json b/notfair/package.json
index 30529098..fe0d384e 100644
--- a/notfair/package.json
+++ b/notfair/package.json
@@ -1,6 +1,6 @@
{
"name": "notfair",
- "version": "0.9.14",
+ "version": "0.9.15",
"description": "Goal-driven, loop-powered marketing agents that crush your business goals 24/7 — on your own machine. Say 'cut CAC to $30' and a dedicated agent turns it into a server-verified metric, then moves the number check after check while you sleep. Rides your existing Claude Code or Codex login.",
"license": "MIT",
"bin": {
diff --git a/notfair/src/app/api/upgrade/route.test.ts b/notfair/src/app/api/upgrade/route.test.ts
index d13afb53..deb936c1 100644
--- a/notfair/src/app/api/upgrade/route.test.ts
+++ b/notfair/src/app/api/upgrade/route.test.ts
@@ -2,7 +2,7 @@ import { EventEmitter } from "node:events";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { homedir, tmpdir } from "node:os";
import { join } from "node:path";
-import { beforeEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
spawn: vi.fn(),
@@ -13,6 +13,7 @@ vi.mock("@/server/version", () => ({
_resetLatestCache: vi.fn(),
getCurrentVersion: vi.fn(() => "0.9.7"),
getLatestVersion: vi.fn(async () => "0.9.8"),
+ isSemverGreater: vi.fn(() => true),
}));
import { POST, syncInstalledNativeBindings } from "./route";
@@ -30,28 +31,96 @@ function fakeChild() {
}
describe("POST /api/upgrade", () => {
+ let dataDir: string;
+ const originalDataDir = process.env.NOTFAIR_DATA_DIR;
+
beforeEach(() => {
vi.clearAllMocks();
+ return mkdtemp(join(tmpdir(), "notfair-update-data-")).then((dir) => {
+ dataDir = dir;
+ process.env.NOTFAIR_DATA_DIR = dir;
+ });
});
- it("starts npm from the stable home directory instead of the server cwd", async () => {
+ afterEach(async () => {
+ if (originalDataDir === undefined) delete process.env.NOTFAIR_DATA_DIR;
+ else process.env.NOTFAIR_DATA_DIR = originalDataDir;
+ await rm(dataDir, { recursive: true, force: true });
+ });
+
+ it("downloads the package without modifying the installed version", async () => {
const child = fakeChild();
mocks.spawn.mockReturnValue(child);
const responsePromise = POST();
- expect(mocks.spawn).toHaveBeenCalledWith(
+ await vi.waitFor(() => {
+ expect(mocks.spawn).toHaveBeenCalledWith(
+ "npm",
+ [
+ "pack",
+ "--pack-destination",
+ join(dataDir, "updates", "0.9.8"),
+ "--silent",
+ ],
+ expect.objectContaining({ cwd: homedir() }),
+ );
+ });
+ expect(mocks.spawn).not.toHaveBeenCalledWith(
"npm",
- ["i", "-g", "notfair@latest"],
- expect.objectContaining({ cwd: homedir() }),
+ expect.arrayContaining(["-g"]),
+ expect.anything(),
);
+ await mkdir(join(dataDir, "updates", "0.9.8"), { recursive: true });
+ await writeFile(join(dataDir, "updates", "0.9.8", "notfair-0.9.8.tgz"), "package");
+ child.emit("exit", 0);
+ const response = await responsePromise;
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toMatchObject({
+ ok: true,
+ downloaded_version: "0.9.8",
+ });
+ });
+
+ it("runs npm install only for an explicit apply action", async () => {
+ const updateDir = join(dataDir, "updates", "0.9.8");
+ const tarball = join(updateDir, "notfair-0.9.8.tgz");
+ await mkdir(updateDir, { recursive: true });
+ await writeFile(tarball, "package");
+ await writeFile(
+ join(dataDir, "updates", "pending.json"),
+ JSON.stringify({
+ version: "0.9.8",
+ tarball,
+ downloaded_at: new Date().toISOString(),
+ }),
+ );
+ const child = fakeChild();
+ mocks.spawn.mockReturnValue(child);
+
+ const responsePromise = POST(
+ new Request("http://localhost/api/upgrade", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ action: "apply" }),
+ }),
+ );
+
+ await vi.waitFor(() => {
+ expect(mocks.spawn).toHaveBeenCalledWith(
+ "npm",
+ ["i", "-g", tarball],
+ expect.objectContaining({ cwd: homedir() }),
+ );
+ });
child.emit("exit", 7);
const response = await responsePromise;
expect(response.status).toBe(500);
await expect(response.json()).resolves.toMatchObject({
ok: false,
- error: "npm exited with code 7",
+ error: "npm install exited with code 7",
});
});
diff --git a/notfair/src/app/api/upgrade/route.ts b/notfair/src/app/api/upgrade/route.ts
index 925ccfb9..02500089 100644
--- a/notfair/src/app/api/upgrade/route.ts
+++ b/notfair/src/app/api/upgrade/route.ts
@@ -1,55 +1,270 @@
import { spawn } from "node:child_process";
-import { copyFile, readdir } from "node:fs/promises";
+import { copyFile, mkdir, readFile, readdir, rename, stat, writeFile } from "node:fs/promises";
import { homedir } from "node:os";
-import { join } from "node:path";
+import { dirname, join, resolve } from "node:path";
import { NextResponse } from "next/server";
-import { _resetLatestCache, getCurrentVersion, getLatestVersion } from "@/server/version";
+import {
+ _resetLatestCache,
+ getCurrentVersion,
+ getLatestVersion,
+ isSemverGreater,
+} from "@/server/version";
export const dynamic = "force-dynamic";
export const runtime = "nodejs";
const UPGRADE_TIMEOUT_MS = 5 * 60 * 1000;
const TAIL_BYTES = 4_000;
+const VERSION_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
+
+type UpgradeAction = "prepare" | "apply";
+
+type PendingUpdate = {
+ version: string;
+ tarball: string;
+ downloaded_at: string;
+};
+
+type CommandResult = {
+ code: number | null;
+ elapsed_ms: number;
+ stdout: string;
+ stderr: string;
+ spawn_error?: string;
+};
/**
* POST /api/upgrade
*
- * Runs `npm i -g notfair@latest` from the user's shell environment.
- * The currently-running NotFair process keeps the old code loaded in
- * memory (Node module cache), so the user must restart `notfair` to
- * pick up the upgraded binary. The response message says so.
+ * `prepare` is intentionally download-only: it asks npm to pack the exact
+ * registry version into NotFair's data directory and records the staged
+ * tarball. It never changes the running installation.
*
- * If npm isn't on PATH (e.g. the user runs NotFair 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.
+ * `apply` is only sent after the user clicks Update. It installs that exact
+ * staged tarball globally. The client immediately follows a successful apply
+ * with /api/restart when NotFair owns its background process.
*/
-export async function POST() {
- // A running standalone bundle can be replaced by a source rebuild or by
- // the upgrade itself. Never let npm inherit that now-missing directory:
- // Node aborts in process.cwd() with ENOENT (`npm` exit code 7) before the
- // install even starts. The user's home directory is stable across both.
- return new Promise<Response>((resolve) => {
- const startedAt = Date.now();
- const child = spawn("npm", ["i", "-g", "notfair@latest"], {
- stdio: ["ignore", "pipe", "pipe"],
- env: process.env,
- cwd: homedir(),
+export async function POST(request?: Request) {
+ const action = await requestedAction(request);
+ if (!action) {
+ return NextResponse.json(
+ { ok: false, error: "Unknown upgrade action." },
+ { status: 400 },
+ );
+ }
+ return action === "apply" ? applyUpdate() : prepareUpdate();
+}
+
+async function requestedAction(request?: Request): Promise<UpgradeAction | null> {
+ if (!request) return "prepare";
+ try {
+ const body = (await request.json()) as { action?: unknown };
+ if (body.action === undefined || body.action === "prepare") return "prepare";
+ if (body.action === "apply") return "apply";
+ return null;
+ } catch {
+ return "prepare";
+ }
+}
+
+async function prepareUpdate(): Promise<Response> {
+ const latest = await getLatestVersion(true);
+ const current = getCurrentVersion();
+ if (!latest) {
+ return NextResponse.json(
+ { ok: false, error: "Could not reach the npm registry." },
+ { status: 503 },
+ );
+ }
+ if (!VERSION_PATTERN.test(latest)) {
+ return NextResponse.json(
+ { ok: false, error: "The npm registry returned an invalid version." },
+ { status: 502 },
+ );
+ }
+ if (!isSemverGreater(latest, current)) {
+ return NextResponse.json({
+ ok: true,
+ downloaded_version: latest,
+ running_version: current,
+ already_current: true,
});
+ }
+
+ const tarball = stagedTarballPath(latest);
+ const existing = await isFile(tarball);
+ if (!existing) {
+ await mkdir(dirname(tarball), { recursive: true });
+ const result = await runNpm([
+ "pack",
+ `notfair@${latest}`,
+ "--pack-destination",
+ dirname(tarball),
+ "--silent",
+ ]);
+ if (result.spawn_error) {
+ return npmUnavailableResponse(result.spawn_error, "download");
+ }
+ if (result.code !== 0 || !(await isFile(tarball))) {
+ return npmFailureResponse(result, "download", latest);
+ }
+ }
+
+ await writePendingUpdate({
+ version: latest,
+ tarball,
+ downloaded_at: new Date().toISOString(),
+ });
+
+ return NextResponse.json({
+ ok: true,
+ downloaded_version: latest,
+ running_version: current,
+ note: `v${latest} downloaded and ready to install.`,
+ });
+}
+
+async function applyUpdate(): Promise<Response> {
+ const pending = await readPendingUpdate();
+ if (!pending || !(await isFile(pending.tarball))) {
+ return NextResponse.json(
+ {
+ ok: false,
+ error: "The downloaded update is missing. Download it again before applying.",
+ },
+ { status: 409 },
+ );
+ }
+
+ const result = await runNpm(["i", "-g", pending.tarball]);
+ if (result.spawn_error) {
+ return npmUnavailableResponse(result.spawn_error, "install", pending.version);
+ }
+ if (result.code !== 0) {
+ return npmFailureResponse(result, "install", pending.version);
+ }
+
+ try {
+ await syncGlobalNativeBindings();
+ } catch (error) {
+ return NextResponse.json(
+ {
+ ok: false,
+ error:
+ "NotFair was installed, but its native database module could not be prepared for this Node.js version.",
+ hint: error instanceof Error ? error.message : String(error),
+ command: `npm i -g notfair@${pending.version}`,
+ },
+ { status: 500 },
+ );
+ }
+
+ _resetLatestCache();
+ const managed = process.env.NOTFAIR_MANAGED ?? null;
+ const canRestart = managed === "launchd" || managed === "daemon";
+ return NextResponse.json({
+ ok: true,
+ installed_version: pending.version,
+ running_version: getCurrentVersion(),
+ can_restart: canRestart,
+ note: canRestart
+ ? "Installed — restarting loads the new version."
+ : "Installed. Restart NotFair to load the new version (`notfair` in your terminal).",
+ elapsed_ms: result.elapsed_ms,
+ stdout_tail: result.stdout.slice(-1000),
+ });
+}
+
+function updateRoot(): string {
+ const dataDir = process.env.NOTFAIR_DATA_DIR ?? join(homedir(), ".notfair");
+ return resolve(dataDir, "updates");
+}
+
+function stagedTarballPath(version: string): string {
+ return join(updateRoot(), version, `notfair-${version}.tgz`);
+}
+
+function pendingUpdatePath(): string {
+ return join(updateRoot(), "pending.json");
+}
+
+async function writePendingUpdate(update: PendingUpdate): Promise<void> {
+ const target = pendingUpdatePath();
+ const temporary = `${target}.${process.pid}.tmp`;
+ await mkdir(dirname(target), { recursive: true });
+ await writeFile(temporary, `${JSON.stringify(update)}\n`, { mode: 0o600 });
+ await rename(temporary, target);
+}
+async function readPendingUpdate(): Promise<PendingUpdate | null> {
+ try {
+ const parsed = JSON.parse(await readFile(pendingUpdatePath(), "utf8")) as Partial<PendingUpdate>;
+ if (
+ typeof parsed.version !== "string" ||
+ !VERSION_PATTERN.test(parsed.version) ||
+ typeof parsed.tarball !== "string" ||
+ typeof parsed.downloaded_at !== "string"
+ ) {
+ return null;
+ }
+ const expected = stagedTarballPath(parsed.version);
+ if (resolve(parsed.tarball) !== resolve(expected)) return null;
+ return parsed as PendingUpdate;
+ } catch {
+ return null;
+ }
+}
+
+async function isFile(path: string): Promise<boolean> {
+ try {
+ return (await stat(path)).isFile();
+ } catch {
+ return false;
+ }
+}
+
+function runNpm(args: string[]): Promise<CommandResult> {
+ // A running standalone bundle can be replaced by a source rebuild or an
+ // explicit install. Never inherit a now-missing server working directory:
+ // npm aborts in process.cwd() with ENOENT (exit code 7) before doing work.
+ return new Promise((resolveCommand) => {
+ const startedAt = Date.now();
let stdout = "";
let stderr = "";
+ let settled = false;
+ let child;
+ try {
+ child = spawn("npm", args, {
+ stdio: ["ignore", "pipe", "pipe"],
+ env: process.env,
+ cwd: homedir(),
+ });
+ } catch (error) {
+ resolveCommand({
+ code: null,
+ elapsed_ms: Date.now() - startedAt,
+ stdout,
+ stderr,
+ spawn_error: error instanceof Error ? error.message : String(error),
+ });
+ return;
+ }
+
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);
- }
+ 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 finish = (result: CommandResult) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(killTimer);
+ resolveCommand(result);
+ };
const killTimer = setTimeout(() => {
try {
child.kill("SIGTERM");
@@ -58,109 +273,62 @@ export async function POST() {
}
}, 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 process. Run `npm i -g notfair@latest` in your terminal instead.",
- command: "npm i -g notfair@latest",
- },
- { status: 500 },
- ),
- );
+ child.on("error", (error) => {
+ finish({
+ code: null,
+ elapsed_ms: Date.now() - startedAt,
+ stdout,
+ stderr,
+ spawn_error: error.message,
+ });
});
-
- child.on("exit", async (code) => {
- clearTimeout(killTimer);
- const elapsed_ms = Date.now() - startedAt;
- if (code === 0) {
- try {
- await syncGlobalNativeBindings();
- } catch (error) {
- resolve(
- NextResponse.json(
- {
- ok: false,
- error: "NotFair was installed, but its native database module could not be prepared for this Node.js version.",
- hint: error instanceof Error ? error.message : String(error),
- command: "npm i -g notfair@latest",
- },
- { status: 500 },
- ),
- );
- return;
- }
- _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);
- // 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(),
- 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),
- }),
- );
- } 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@latest",
- },
- { status: 500 },
- ),
- );
- }
+ child.on("exit", (code) => {
+ finish({ code, elapsed_ms: Date.now() - startedAt, stdout, stderr });
});
});
}
+function npmUnavailableResponse(error: string, operation: "download" | "install", version?: string) {
+ const command = version ? `npm i -g notfair@${version}` : "npm i -g notfair@latest";
+ return NextResponse.json(
+ {
+ ok: false,
+ error,
+ hint: `Could not run npm to ${operation} the update. Run \`${command}\` in your terminal instead.`,
+ command,
+ },
+ { status: 500 },
+ );
+}
+
+function npmFailureResponse(
+ result: CommandResult,
+ operation: "download" | "install",
+ version: string,
+) {
+ return NextResponse.json(
+ {
+ ok: false,
+ error: `npm ${operation} exited with code ${result.code}`,
+ elapsed_ms: result.elapsed_ms,
+ stdout_tail: result.stdout.slice(-1000),
+ stderr_tail: result.stderr.slice(-1000),
+ command: `npm i -g notfair@${version}`,
+ },
+ { status: 500 },
+ );
+}
+
async function syncGlobalNativeBindings() {
const root = await npmGlobalRoot();
await syncInstalledNativeBindings(join(root, "notfair"));
}
async function npmGlobalRoot(): Promise<string> {
- return new Promise((resolve, reject) => {
- let stdout = "";
- const child = spawn("npm", ["root", "-g"], {
- stdio: ["ignore", "pipe", "pipe"],
- env: process.env,
- cwd: homedir(),
- });
- child.stdout?.on("data", (chunk: Buffer) => {
- stdout += chunk.toString("utf8");
- });
- child.on("error", reject);
- child.on("exit", (code) => {
- const root = stdout.trim();
- if (code === 0 && root) {
- resolve(root);
- } else {
- reject(new Error(`Could not locate npm's global package directory (exit ${code}).`));
- }
- });
- });
+ const result = await runNpm(["root", "-g"]);
+ const root = result.stdout.trim();
+ if (result.code === 0 && root) return root;
+ throw new Error(`Could not locate npm's global package directory (exit ${result.code}).`);
}
/**
diff --git a/notfair/src/components/sidebar-version.test.tsx b/notfair/src/components/sidebar-version.test.tsx
index c5184768..a1b6018e 100644
--- a/notfair/src/components/sidebar-version.test.tsx
+++ b/notfair/src/components/sidebar-version.test.tsx
@@ -26,7 +26,7 @@ describe("SidebarVersion", () => {
vi.unstubAllGlobals();
});
- it("automatically installs an available update before asking to apply it", async () => {
+ it("only downloads an available update before asking the user to apply it", async () => {
fetchMock
.mockResolvedValueOnce(
jsonResponse({ current: "0.9.13", latest: "0.9.14", has_update: true }),
@@ -36,23 +36,29 @@ describe("SidebarVersion", () => {
render(<SidebarVersion />);
await waitFor(() => {
- expect(fetchMock).toHaveBeenCalledWith("/api/upgrade", { method: "POST" });
+ expect(fetchMock).toHaveBeenCalledWith("/api/upgrade", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ action: "prepare" }),
+ });
});
expect(
await screen.findByRole("button", { name: /update to v0\.9\.14/i }),
).toBeEnabled();
expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(toastSuccess).not.toHaveBeenCalled();
expect(screen.queryByRole("button", { name: /restart now/i })).toBeNull();
});
- it("restarts immediately when the user applies the installed update", async () => {
+ it("installs and restarts only after the user clicks Update", async () => {
fetchMock
.mockResolvedValueOnce(
jsonResponse({ current: "0.9.13", latest: "0.9.14", has_update: true }),
)
+ .mockResolvedValueOnce(jsonResponse({ ok: true }))
.mockResolvedValueOnce(jsonResponse({ ok: true, can_restart: true }))
// Keep the restart request pending so the component remains in its
- // visible restarting state without beginning the version poll.
+ // visible updating state without beginning the version poll.
.mockReturnValueOnce(new Promise<Response>(() => {}));
render(<SidebarVersion />);
@@ -61,11 +67,16 @@ describe("SidebarVersion", () => {
);
await waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledWith("/api/upgrade", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ action: "apply" }),
+ });
expect(fetchMock).toHaveBeenCalledWith("/api/restart", { method: "POST" });
});
expect(screen.queryByRole("button", { name: /restart now/i })).toBeNull();
expect(
- screen.getByRole("button", { name: /restarting/i }),
+ screen.getByRole("button", { name: /updating/i }),
).toBeDisabled();
});
@@ -74,6 +85,9 @@ describe("SidebarVersion", () => {
.mockResolvedValueOnce(
jsonResponse({ current: "0.9.13", latest: "0.9.14", has_update: true }),
)
+ .mockResolvedValueOnce(
+ jsonResponse({ ok: true }),
+ )
.mockResolvedValueOnce(
jsonResponse({
ok: true,
@@ -84,8 +98,11 @@ describe("SidebarVersion", () => {
render(<SidebarVersion />);
+ fireEvent.click(
+ await screen.findByRole("button", { name: /update to v0\.9\.14/i }),
+ );
expect(await screen.findByText("Restart to apply")).toBeInTheDocument();
- expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(fetchMock).toHaveBeenCalledTimes(3);
expect(toastSuccess).toHaveBeenCalledWith(
"Restart NotFair from your terminal.",
{ duration: 15_000 },
@@ -100,7 +117,7 @@ describe("SidebarVersion", () => {
.mockResolvedValueOnce(
jsonResponse({ ok: false, error: "registry unavailable" }, false),
)
- .mockResolvedValueOnce(jsonResponse({ ok: true, can_restart: true }));
+ .mockResolvedValueOnce(jsonResponse({ ok: true }));
render(<SidebarVersion />);
const retry = await screen.findByRole("button", { name: /retry update/i });
diff --git a/notfair/src/components/sidebar-version.tsx b/notfair/src/components/sidebar-version.tsx
index 8732d88d..98d84d43 100644
--- a/notfair/src/components/sidebar-version.tsx
+++ b/notfair/src/components/sidebar-version.tsx
@@ -16,16 +16,16 @@ type Phase =
| "idle"
| "downloading"
| "ready"
- | "restarting"
+ | "updating"
| "manual"
| "failed";
/**
- * Sidebar footer: current version + the update flow. When npm reports a
- * newer version, it installs automatically through /api/upgrade. Once ready,
- * the Update button restarts background/launchd servers through /api/restart
- * and reloads on the new version. Foreground/dev runs are told to restart
- * from the terminal because the app does not own those processes.
+ * Sidebar footer: current version + a two-phase update flow. A newer package
+ * is downloaded in the background without touching the running install. The
+ * Update button explicitly installs it, restarts an owned background server,
+ * and reloads on the new version. Foreground/dev runs are told to restart from
+ * the terminal after the explicit install because the app does not own them.
*/
export function SidebarVersion() {
const [info, setInfo] = useState<VersionInfo | null>(null);
@@ -58,9 +58,13 @@ export function SidebarVersion() {
if (!version.has_update) return;
setPhase("downloading");
try {
- const res = await fetch("/api/upgrade", { method: "POST" });
+ const res = await fetch("/api/upgrade", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ action: "prepare" }),
+ });
const body = (await res.json()) as
- | { ok: true; note?: string; can_restart?: boolean }
+ | { ok: true; note?: string }
| { ok: false; error?: string; command?: string; hint?: string };
if (!res.ok || !body.ok) {
const msg = !body.ok
@@ -75,32 +79,51 @@ export function SidebarVersion() {
setPhase("failed");
return;
}
- if (body.can_restart) {
- setPhase("ready");
- toast.success(`v${version.latest} installed — click Update to apply.`, {
- duration: 10_000,
- });
- } else {
- setPhase("manual");
- toast.success(
- body.note ?? "Upgraded. Restart NotFair in your terminal to apply.",
- { duration: 15_000 },
- );
- }
+ setPhase("ready");
} catch (err) {
toast.error(err instanceof Error ? err.message : String(err));
setPhase("failed");
}
}
- async function restart() {
+ async function applyAndRestart() {
if (phase !== "ready") return;
- setPhase("restarting");
+ setPhase("updating");
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.", {
+ const applyResponse = await fetch("/api/upgrade", {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ action: "apply" }),
+ });
+ const applyBody = (await applyResponse.json()) as
+ | { ok: true; can_restart: boolean; note?: string }
+ | { ok: false; error?: string; hint?: string; command?: string };
+ if (!applyResponse.ok || !applyBody.ok) {
+ const message = !applyBody.ok
+ ? applyBody.hint ?? applyBody.error ?? "Could not install the update."
+ : "Could not install the update.";
+ if (!applyBody.ok && applyBody.command) {
+ await navigator.clipboard.writeText(applyBody.command).catch(() => {});
+ toast.error(`${message}\nCommand copied to clipboard.`, { duration: 10_000 });
+ } else {
+ toast.error(message, { duration: 10_000 });
+ }
+ setPhase("ready");
+ return;
+ }
+ if (!applyBody.can_restart) {
+ toast.success(
+ applyBody.note ?? "Installed. Restart NotFair from your terminal to apply.",
+ { duration: 15_000 },
+ );
+ setPhase("manual");
+ return;
+ }
+
+ const restartResponse = await fetch("/api/restart", { method: "POST" });
+ const restartBody = (await restartResponse.json()) as { ok: boolean; hint?: string };
+ if (!restartResponse.ok || !restartBody.ok) {
+ toast.error(restartBody.hint ?? "Could not restart from here — use your terminal.", {
duration: 10_000,
});
setPhase("manual");
@@ -177,19 +200,19 @@ export function SidebarVersion() {
</Button>
)}
- {(phase === "ready" || phase === "restarting") && (
+ {(phase === "ready" || phase === "updating") && (
<Button
size="sm"
variant="outline"
- disabled={phase === "restarting"}
- onClick={restart}
- title={`Restart and update to v${info.latest}`}
+ disabled={phase === "updating"}
+ onClick={applyAndRestart}
+ title={`Install v${info.latest} and restart now`}
className="h-6 gap-1 px-2 text-[10.5px] font-medium"
>
- {phase === "restarting" ? (
+ {phase === "updating" ? (
<>
<Loader2 className="h-3 w-3 animate-spin" />
- Restarting…
+ Updating…
</>
) : (
<>