feat(update): integrate managed installs and recoverable in-app updates (#6168)

Add owner-aware Stable and Preview updates with explicit consent, verified release plans, protected process handoff and bounded service recovery. Keep configuration and conversations separate from program rollback.

Include the compact About controls, Windows long-path support, native package recovery checks and optional macOS Dock lifecycle integration. Preserve documented guidance for installations owned by other managers.

This code integration does not publish packages, enable signing or advance the public update channel.

Co-authored-by: chengyongru <61816729+chengyongru@users.noreply.github.com>
This commit is contained in:
Xubin Renandchengyongru authored and GitHub committed 2026-10-21 19:16:56 +08:00
1 parent 76da55994b
commit fbb61a373f
216 files changed
+27948 -1084

No files matched your search

+10 -2
View File
@@ -402,6 +402,9 @@ describe("App layout", () => {
}] },
});
render(<App />);
// Await the lazy module itself; cold Vite transformation is not the task
// capability contract exercised by the timed DOM assertions below.
await act(async () => { await import("@/components/thread/ThreadShell"); });
await screen.findByRole("textbox", {}, { timeout: 5_000 });
if (supported) await screen.findByRole("button", { name: /Config check Running/ });
else expect(screen.queryByText("Config check")).not.toBeInTheDocument();
@@ -3122,11 +3125,15 @@ describe("App layout", () => {
});
it("opens the settings view from the sidebar footer", async () => {
mockFetchRoutes({ "/api/settings": baseSettingsPayload() });
mockFetchRoutes({
"/api/settings": baseSettingsPayload(),
"/api/settings/version-check": { updateAvailable: null },
});
render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
fireEvent.click(within(screen.getByRole("navigation", { name: "Sidebar navigation" }))
.getByRole("button", { name: "Settings" }));
await act(async () => { await import("@/components/settings/SettingsView"); });
const nav = await screen.findByRole("navigation", { name: "Settings sections" });
for (const name of ["Overview", "Appearance", "Models", "Capabilities", "System", "Advanced", "About"]) {
expect(within(nav).getByRole("button", { name })).toBeInTheDocument();
@@ -3138,7 +3145,8 @@ describe("App layout", () => {
fireEvent.click(within(nav).getByRole("button", { name: "Capabilities" }));
expect(screen.getByRole("switch", { name: "Image generation" })).toBeInTheDocument();
fireEvent.click(within(nav).getByRole("button", { name: "About" }));
expect(await screen.findByRole("button", { name: "Check for updates" })).toBeInTheDocument();
expect(await screen.findByText("You're up to date")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Check again" })).toBeInTheDocument();
});
it("restores the settings section from the URL hash after a page reload", async () => {
+18
View File
@@ -0,0 +1,18 @@
import { execFileSync, spawnSync } from "node:child_process";
import { expect, it } from "vitest";
const root = process.cwd();
const bunError = spawnSync("bun", ["--version"], { timeout: 10_000 }).error;
const bunAvailable = !(bunError && "code" in bunError && bunError.code === "ENOENT");
it.skipIf(!bunAvailable)("Bun loads React runtime code for the packaged Vite SSR build", () => {
// Type-only aliases previously made Bun execute @types/react/index.d.ts.
// npm-only development can skip this; native-package CI installs pinned Bun.
const html = execFileSync("bun", ["--eval", `
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { jsx } from "react/jsx-runtime";
console.log(renderToStaticMarkup(createElement("div", null, jsx("span", {children: "ready"}))));
`], { cwd: root, encoding: "utf8", timeout: 10_000 });
expect(html.trim()).toBe("<div><span>ready</span></div>");
});
+24
View File
@@ -76,3 +76,27 @@ it("keeps the visible assistant identity when translating existing interaction f
expect(preview.getByText("Support assistant:已关闭")).toBeVisible();
});
it("quietly keeps Preview selection and translates update feedback without executing an update", async () => {
const source = "webui/src/components/settings/overview/VersionCheckRowView.tsx";
window.history.replaceState({}, "", `/gallery.html#${new URLSearchParams({ component: source })}`);
const fetch = vi.fn().mockResolvedValue({ ok: true, json: async () => inventory });
vi.stubGlobal("fetch", fetch);
render(<Gallery />);
const preview = within(await screen.findByRole("region", { name: "Component preview" }));
await userEvent.click(preview.getByRole("combobox", { name: "Version state" }));
await userEvent.click(await screen.findByRole("option", { name: "preview" }));
const toggle = preview.getByRole("switch", { name: "Receive preview updates" });
await userEvent.click(toggle);
expect(toggle).toBeChecked();
expect(preview.queryByText("Sample preference saved; nothing will be installed or restarted.")).toBeNull();
await userEvent.click(preview.getByRole("button", { name: "Update" }));
expect(preview.getByText("Update review selected; this preview does not install or restart anything.")).toBeVisible();
await chooseChinese();
expect(preview.getByText("已选择查看更新;组件预览不会安装或重启。")).toBeVisible();
expect(toggle).toBeChecked();
expect(preview.getByText("v0.3.7.dev2026101501")).toBeVisible();
expect(fetch).toHaveBeenCalledTimes(1);
});
+62 -4
View File
@@ -15,16 +15,74 @@ import { jsonResponse, settingsPayload, renderSettingsView, installSettingsViewT
describe("Settings overview and appearance", () => {
installSettingsViewTestHooks();
it.each([{ capabilities: [] }, { capabilities: ["webui.core.v1", "webui.self-update.v1"] }])(
"checks on About entry without calling the legacy updater (%j)",
async ({ capabilities }) => {
const fetcher = vi.fn(async () => jsonResponse({
updateAvailable: { currentVersion: "0.2.2", latestVersion: "0.3.6" },
}));
vi.stubGlobal("fetch", fetcher);
render(
<ClientProvider client={new NanobotClient({ url: "ws://localhost:8765" })} token="tok"
webuiCapabilities={capabilities}>
<AboutSettings settings={settingsPayload()} />
</ClientProvider>,
);
expect(await screen.findByRole("link", { name: "Installation guide" })).toBeVisible();
expect(fetcher).toHaveBeenCalledTimes(1);
expect(fetcher).toHaveBeenCalledWith("/api/settings/version-check", expect.any(Object));
expect(screen.queryByRole("button", { name: /^Update$/ })).not.toBeInTheDocument();
},
);
it("displays a caller-owned version result and delegates checking without a client provider", () => {
const check = vi.fn();
render(<VersionCheckRowView currentVersion="0.3.5" checking={false}
const { rerender } = render(<VersionCheckRowView currentVersion="0.3.5" checking={false}
result={{ type: "update", latestVersion: "0.3.6", pypiUrl: "https://pypi.org/project/nanobot-ai/" }} onCheck={check} />);
expect(screen.getByText("Update available v0.3.6")).toBeVisible();
expect(screen.getByText("v0.3.6")).toBeVisible();
expect(screen.getByRole("link", { name: "PyPI" })).toHaveAttribute("href", "https://pypi.org/project/nanobot-ai/");
fireEvent.click(screen.getByRole("button", { name: "Check for updates" }));
rerender(<VersionCheckRowView currentVersion="0.3.5" checking={false} result={{ type: "up-to-date" }} onCheck={check} />);
expect(screen.getByText("You're up to date")).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Check again" }));
expect(check).toHaveBeenCalledTimes(1);
});
it("delegates update actions and keeps saved-job details available in the shared view", () => {
const requestUpdate = vi.fn();
const props = { currentVersion: "0.3.5", checking: false, onCheck: vi.fn(),
onRequestUpdate: requestUpdate };
const { rerender } = render(<VersionCheckRowView {...props}
result={{ type: "update", latestVersion: "0.3.7.dev2026101501",
releaseUrl: "https://github.com/HKUDS/nanobot/releases/tag/v0.3.7.dev2026101501" }} />);
expect(screen.getByText("v0.3.7.dev2026101501")).toBeVisible();
expect(screen.getByRole("link", { name: "Release notes" })).toHaveAttribute("href",
"https://github.com/HKUDS/nanobot/releases/tag/v0.3.7.dev2026101501");
expect(requestUpdate).not.toHaveBeenCalled();
expect(screen.queryByRole("link", { name: "Installation guide" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: /^Update$/ }));
expect(requestUpdate).toHaveBeenCalledTimes(1);
rerender(<VersionCheckRowView {...props} currentVersion="0.3.6"
result={{ type: "up-to-date" }} hasPendingUpdate />);
expect(screen.queryByRole("button", { name: /^Update$/ })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "View details" }));
expect(requestUpdate).toHaveBeenCalledTimes(2);
});
it("lets the visible Preview label toggle the setting without consenting to an update", () => {
const changeChannel = vi.fn().mockResolvedValue(undefined);
const requestUpdate = vi.fn();
render(<VersionCheckRowView currentVersion="0.3.6" checking={false} result={null} onCheck={vi.fn()}
releaseStatus={{ channel: "stable", revision: 1, currentVersion: "0.3.6", state: "current" }}
canChangeChannel onChangeChannel={changeChannel} onRequestUpdate={requestUpdate} />);
const toggle = screen.getByRole("switch", { name: "Receive preview updates" });
expect(toggle).toHaveAccessibleDescription("Try new features early.");
fireEvent.click(document.querySelector(`label[for="${toggle.id}"]`)!);
expect(changeChannel).toHaveBeenCalledTimes(1);
expect(changeChannel).toHaveBeenCalledWith("preview");
expect(requestUpdate).not.toHaveBeenCalled();
});
it("opens the notifications section and preserves independent browser-local channel preferences", () => {
writeLocalPreferences({ ...DEFAULT_LOCAL_PREFS, notificationSound: true });
renderSettingsView({ initialSection: "appearance", initialSettings: settingsPayload(), showSidebar: true });
@@ -74,7 +132,7 @@ describe("Settings overview and appearance", () => {
initialSettings: { ...settingsPayload(), version: { current: "0.3.5", commit } },
});
expect(screen.getByText("v0.3.5")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Check for updates" })).toBeEnabled();
expect(screen.getByText("Checking...")).toBeVisible();
expect(document.querySelector('a[href*="/commit/"]')).toBeNull();
const reportUrl = new URL(screen.getByRole("link", { name: "Report an issue" }).getAttribute("href")!);
expect(reportUrl.searchParams.get("version")).toBe("0.3.5");
+172
View File
@@ -0,0 +1,172 @@
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { AboutSettings } from "@/components/settings/overview/OverviewSettings";
import { NanobotClient } from "@/lib/nanobot-client";
import { ClientProvider } from "@/providers/ClientProvider";
import { useVersionCheck } from "@/providers/VersionCheckProvider";
import { jsonResponse, settingsPayload } from "@/tests/settings-test-utils";
afterEach(() => { cleanup(); vi.unstubAllGlobals(); vi.restoreAllMocks(); });
const state = (channel = "stable", revision = 0, status = "current") => ({
updateAvailable: null, can_change_channel: true,
releaseStatus: { channel, revision, currentVersion: "0.3.7.dev42", state: status },
});
function Controls() {
const channel = useVersionCheck();
return <>
<button onClick={() => void channel.changeChannel("preview")}>Subscribe preview</button>
<button onClick={() => void channel.changeChannel("stable")}>Subscribe stable</button>
<input aria-label="Draft" />
</>;
}
function view(client: NanobotClient, token = "channel-a", native = false) {
return <ClientProvider client={client} token={token} checkUpdatesOnConnect allowUpdateFlow={!native}
webuiCapabilities={["webui.update-channels.v1"]}>
<AboutSettings settings={settingsPayload()} /><Controls />
</ClientProvider>;
}
describe("Installation-owned release channels", () => {
it("shows saving progress, then quietly selects a channel without installation or restart consent", async () => {
const client = new NanobotClient({ url: "ws://localhost:8765" });
let resolve!: (value: unknown) => void;
const mutation = vi.spyOn(client, "requestMutation").mockImplementation(() => new Promise(done => { resolve = done; }));
const fetcher = vi.fn().mockResolvedValueOnce(jsonResponse(state()))
.mockResolvedValueOnce(jsonResponse(state("preview", 1, "unavailable")));
vi.stubGlobal("fetch", fetcher);
render(view(client));
const selector = await screen.findByRole("switch", { name: "Receive preview updates" });
expect(selector).toBeVisible();
expect(selector).toHaveAccessibleDescription("Try new features early.");
expect(selector).toHaveAttribute("aria-checked", "false");
fireEvent.change(screen.getByLabelText("Draft"), { target: { value: "Keep writing" } });
fireEvent.click(selector);
expect(selector).toBeDisabled();
expect(screen.getByText("Saving…")).toBeVisible();
fireEvent.click(screen.getByText("Subscribe stable"));
expect(mutation).toHaveBeenCalledOnce();
expect(mutation).toHaveBeenCalledWith("settings.nanobot.update.channel", { channel: "preview", revision: 0 }, expect.any(Number));
await act(async () => resolve({ channel: "preview", revision: 1 }));
await waitFor(() => expect(selector).toBeEnabled());
expect(selector).toHaveAttribute("aria-checked", "true");
expect(selector).toBeVisible();
expect(screen.queryByText("Saving…")).toBeNull();
expect(screen.queryByText("Update preference saved")).toBeNull();
expect(screen.getByText(/Could not verify/)).toBeVisible();
expect(screen.queryByText("You're up to date")).toBeNull();
expect(screen.getByLabelText("Draft")).toHaveValue("Keep writing");
expect(fetcher).toHaveBeenCalledWith("/api/settings/version-check?channel_status=1", expect.any(Object));
expect(mutation).toHaveBeenCalledOnce();
});
it("reloads a quietly saved channel and uses its latest revision for the next save", async () => {
const client = new NanobotClient({ url: "ws://localhost:8765" });
let selection = { channel: "stable", revision: 0 };
const mutation = vi.spyOn(client, "requestMutation").mockImplementation(async (_action, payload) => {
selection = { channel: String(payload?.channel), revision: selection.revision + 1 };
return selection;
});
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse(state(selection.channel, selection.revision))));
const first = render(view(client));
fireEvent.click(await screen.findByRole("switch", { name: "Receive preview updates" }));
await waitFor(() => expect(screen.getByRole("switch")).toBeEnabled());
expect(screen.getByRole("switch")).toHaveAttribute("aria-checked", "true");
first.unmount();
render(view(client));
const selector = await screen.findByRole("switch", { name: "Receive preview updates" });
expect(selector).toHaveAttribute("aria-checked", "true");
fireEvent.click(selector);
await waitFor(() => expect(selector).toBeEnabled());
expect(selector).toHaveAttribute("aria-checked", "false");
expect(mutation).toHaveBeenNthCalledWith(1, "settings.nanobot.update.channel", { channel: "preview", revision: 0 }, expect.any(Number));
expect(mutation).toHaveBeenNthCalledWith(2, "settings.nanobot.update.channel", { channel: "stable", revision: 1 }, expect.any(Number));
expect(screen.queryByText("Update preference saved")).toBeNull();
});
it("shares the post-save check when About is reentered during a channel mutation and retries its failure", async () => {
const client = new NanobotClient({ url: "ws://localhost:8765" });
let resolveSave!: (value: unknown) => void;
const mutation = vi.spyOn(client, "requestMutation").mockImplementation(() => new Promise(done => { resolveSave = done; }));
const fetcher = vi.fn().mockResolvedValueOnce(jsonResponse(state()))
.mockRejectedValueOnce(new Error("Channel check unavailable"))
.mockResolvedValueOnce(jsonResponse(state("preview", 1)));
vi.stubGlobal("fetch", fetcher);
const surface = (about: boolean) => <ClientProvider client={client} token="save-reentry"
webuiCapabilities={["webui.update-channels.v1"]}>
{about && <AboutSettings settings={settingsPayload()} />}
</ClientProvider>;
const mounted = render(surface(true));
fireEvent.click(await screen.findByRole("switch", { name: "Receive preview updates" }));
mounted.rerender(surface(false));
mounted.rerender(surface(true));
expect(screen.getByText("Saving…")).toBeVisible();
expect(fetcher).toHaveBeenCalledOnce();
await act(async () => resolveSave({ channel: "preview", revision: 1 }));
expect(await screen.findByText("Channel check unavailable")).toBeVisible();
expect(fetcher).toHaveBeenCalledTimes(2);
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
await waitFor(() => expect(screen.getByRole("switch")).toBeEnabled());
expect(screen.getByRole("switch")).toHaveAttribute("aria-checked", "true");
expect(screen.getByText("You're up to date")).toBeVisible();
expect(fetcher).toHaveBeenCalledTimes(3);
expect(mutation).toHaveBeenCalledOnce();
expect(mutation).toHaveBeenCalledWith("settings.nanobot.update.channel", { channel: "preview", revision: 0 }, expect.any(Number));
});
it("resynchronizes a stale tab or lost response and waits for stable without downgrading", async () => {
const client = new NanobotClient({ url: "ws://localhost:8765" });
const mutation = vi.spyOn(client, "requestMutation").mockRejectedValue(new Error("Channel changed elsewhere; check again"));
vi.stubGlobal("fetch", vi.fn().mockResolvedValueOnce(jsonResponse(state("preview", 1)))
.mockResolvedValueOnce(jsonResponse(state("stable", 2, "waiting_stable"))));
render(view(client));
fireEvent.click(await screen.findByRole("switch", { name: "Receive preview updates" }));
await waitFor(() => expect(screen.getByRole("switch")).toHaveAttribute("aria-checked", "false"));
expect(screen.getByText(/Channel changed elsewhere/)).toBeVisible();
expect(screen.getByText(/newer stable release/)).toBeVisible();
expect(screen.queryByText("You're up to date")).toBeNull();
expect(mutation).toHaveBeenCalledOnce();
});
it("does not let a late old-host mutation change the new host or discard its draft", async () => {
const client = new NanobotClient({ url: "ws://localhost:8765" });
let resolve!: (value: unknown) => void;
vi.spyOn(client, "requestMutation").mockImplementation(() => new Promise(done => { resolve = done; }));
vi.stubGlobal("fetch", vi.fn().mockResolvedValueOnce(jsonResponse(state()))
.mockResolvedValueOnce(jsonResponse(state("stable", 4)))
.mockResolvedValueOnce(jsonResponse(state("preview", 1))));
const { rerender } = render(view(client));
fireEvent.click(await screen.findByRole("switch", { name: "Receive preview updates" }));
fireEvent.change(screen.getByLabelText("Draft"), { target: { value: "Survives" } });
rerender(view(client, "channel-b"));
await screen.findByRole("switch", { name: "Receive preview updates" });
await waitFor(() => expect(screen.getByRole("switch")).toBeEnabled());
await act(async () => resolve({ channel: "preview", revision: 1 }));
expect(screen.getByRole("switch")).toHaveAttribute("aria-checked", "false");
expect(screen.getByLabelText("Draft")).toHaveValue("Survives");
});
it("does not turn a missing channel result into a green success", async () => {
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse({ updateAvailable: null })));
render(view(new NanobotClient({ url: "ws://localhost:8765" })));
expect(await screen.findByText(/did not return its update channel/)).toBeVisible();
expect(screen.queryByText("You're up to date")).toBeNull();
});
it("shows a read-only channel for remote callers and leaves native updates to the distributor", async () => {
const client = new NanobotClient({ url: "ws://localhost:8765" });
const mutation = vi.spyOn(client, "requestMutation");
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse({ ...state(), can_change_channel: false })));
const { rerender } = render(view(client));
const selector = await screen.findByRole("switch", { name: "Receive preview updates" });
expect(selector).toBeDisabled();
expect(selector).toHaveAccessibleDescription(/Open this gateway on localhost or allow remote package installation/);
fireEvent.click(screen.getByText("Subscribe preview"));
expect(mutation).not.toHaveBeenCalled();
rerender(view(client, "native", true));
await waitFor(() => expect(screen.queryByRole("switch")).toBeNull());
expect(mutation).not.toHaveBeenCalled();
});
});
+636
View File
@@ -0,0 +1,636 @@
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as api from "@/lib/api";
import { copyTextToClipboard } from "@/lib/clipboard";
import type { NanobotClient } from "@/lib/nanobot-client";
import type { ConnectionStatus } from "@/lib/types";
import { UpdateFlowProvider, useUpdateFlow } from "@/providers/UpdateFlowProvider";
import { ClientProvider } from "@/providers/ClientProvider";
import { AboutSettings } from "@/components/settings/overview/OverviewSettings";
import { settingsPayload } from "@/tests/settings-test-utils";
vi.mock("@/lib/api", async (original) => ({
...await original<typeof api>(), createUpdateReview: vi.fn(), readUpdateReview: vi.fn(),
readUpdateJob: vi.fn(), prepareUpdate: vi.fn(), executeUpdate: vi.fn(), settleUpdate: vi.fn(), checkVersion: vi.fn(), fetchSettings: vi.fn(),
}));
vi.mock("@/lib/clipboard", () => ({ copyTextToClipboard: vi.fn() }));
const id = "71c91a73-842e-42e9-aeb4-61a5bfe51135";
let connectionStatus: ConnectionStatus = "open";
const client = { get status() { return connectionStatus; } } as NanobotClient;
const review: api.UpdateReviewResponse = {
plan: { id, installation_id: "installed-a", host: "test Mac", running_version: "0.3.5", target_version: "0.3.6",
action: "upgrade", validity: "current", execution_blocked_reason: null, profiles: [] },
installation_allowed: true, execution_available: true,
};
const externalReview: api.UpdateReviewResponse = {
...review, execution_available: false,
plan: { ...review.plan, execution_blocked_reason: "installation_owner", guide: {
method: "pipx", host: "remote-server", environment: "/server/pipx/venvs/nanobot-ai-work", shell: "sh", reason: "registry",
inspect_command: "env PIPX_HOME=/server/pipx pipx list",
update_command: "env PIPX_HOME=/server/pipx pipx upgrade nanobot-ai-work",
verify_command: "/server/pipx/venvs/nanobot-ai-work/bin/python -I -m nanobot --version",
} },
};
const job = (phase: api.UpdateJobPhase, confirmation: string | null = null): api.UpdateJob => ({
id, installation_id: "installed-a", target_version: "0.3.6", running_version: "0.3.5",
recorded_phase: phase, mutation_started: false, execution_confirmation_id: confirmation,
});
function Entry() {
const flow = useUpdateFlow();
return <button disabled={!flow.open} onClick={flow.open}>Update entry</button>;
}
function view(token = "gateway-a", enabled = true, canSettleHandoff = true) {
return <UpdateFlowProvider client={client} token={token} enabled={enabled} canSettleHandoff={canSettleHandoff}><Entry /></UpdateFlowProvider>;
}
beforeEach(() => {
connectionStatus = "open";
vi.resetAllMocks(); sessionStorage.clear();
vi.mocked(api.createUpdateReview).mockResolvedValue(review);
vi.mocked(api.readUpdateReview).mockResolvedValue(review);
vi.mocked(api.prepareUpdate).mockResolvedValue({ job: job("preparing") });
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job("ready") });
vi.mocked(api.executeUpdate).mockResolvedValue({ job: job("checking", "confirmed") });
vi.mocked(api.checkVersion).mockResolvedValue({ updateAvailable: null });
});
afterEach(() => { cleanup(); sessionStorage.clear(); vi.useRealTimers(); });
describe("Real update consent and recovery", () => {
it("opens the original confirmation from an automatically checked About update without consenting to installation", async () => {
vi.mocked(api.checkVersion).mockResolvedValue({ installation_method: "managed",
updateAvailable: { currentVersion: "0.3.5", latestVersion: "0.3.6" } });
render(<ClientProvider client={client} token="about-confirmation" webuiCapabilities={["webui.update-flow.v1"]}>
<AboutSettings settings={settingsPayload()} />
</ClientProvider>);
fireEvent.click(await screen.findByRole("button", { name: /^Update$/ }));
expect(await screen.findByRole("button", { name: "Update & restart" })).toBeEnabled();
expect(api.checkVersion).toHaveBeenCalledOnce();
expect(api.createUpdateReview).toHaveBeenCalledOnce();
expect(api.prepareUpdate).not.toHaveBeenCalled();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("offers installation-bound instructions and copy feedback, without installation consent", async () => {
vi.mocked(api.createUpdateReview).mockResolvedValue(externalReview);
vi.mocked(copyTextToClipboard).mockResolvedValueOnce(false).mockResolvedValueOnce(true);
render(view());
fireEvent.click(screen.getByText("Update entry"));
await screen.findByRole("heading", { name: "Update via pipx" });
expect(screen.getByText("Gateway: remote-server")).toBeVisible();
expect(screen.getByText(/connect by SSH or its server console/)).toBeVisible();
expect(screen.getByLabelText("Update command")).toHaveValue(externalReview.plan.guide!.update_command);
fireEvent.click(screen.getByRole("button", { name: "Copy command" }));
await screen.findByText("Could not copy. Select and copy the command above.");
fireEvent.click(screen.getByRole("button", { name: "Copy command" }));
await screen.findByRole("button", { name: "Copied" });
expect(copyTextToClipboard).toHaveBeenLastCalledWith(externalReview.plan.guide!.update_command);
fireEvent.click(screen.getByRole("button", { name: "Inspect this installation" }));
expect(screen.getByRole("button", { name: "Inspect this installation" })).toHaveAttribute("aria-expanded", "true");
fireEvent.click(screen.getByRole("button", { name: "Inspect this installation" }));
expect(screen.getByRole("button", { name: "Inspect this installation" })).toHaveAttribute("aria-expanded", "false");
expect(api.prepareUpdate).not.toHaveBeenCalled();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("verifies the running gateway, reports mismatch and offline errors, never infers success from package installation", async () => {
vi.mocked(api.createUpdateReview).mockResolvedValue(externalReview);
vi.mocked(api.fetchSettings).mockResolvedValueOnce({ ...settingsPayload(), version: { current: "0.3.5" } })
.mockRejectedValueOnce(new Error("offline"))
.mockResolvedValueOnce({ ...settingsPayload(), version: { current: "0.3.6" } });
render(view());
fireEvent.click(screen.getByText("Update entry"));
const check = await screen.findByRole("button", { name: "Check running gateway" });
fireEvent.click(check);
await screen.findByText(/reports v0.3.5, not the notice’s v0.3.6/);
fireEvent.click(check);
await screen.findByText(/Could not read the running version/);
fireEvent.click(check);
await screen.findByText("Confirmed: this gateway is running v0.3.6.");
expect(api.fetchSettings).toHaveBeenLastCalledWith("gateway-a");
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("discards an old gateway's late verification on a credential switch", async () => {
vi.mocked(api.createUpdateReview).mockResolvedValue(externalReview);
let resolve!: (value: Awaited<ReturnType<typeof api.fetchSettings>>) => void;
vi.mocked(api.fetchSettings).mockImplementation(() => new Promise(done => { resolve = done; }));
const mounted = render(view());
fireEvent.click(screen.getByText("Update entry"));
fireEvent.click(await screen.findByRole("button", { name: "Check running gateway" }));
mounted.rerender(view("gateway-b"));
await act(async () => { resolve({ ...settingsPayload(), version: { current: "0.3.6" } }); });
expect(screen.queryByText(/Confirmed: this gateway/)).not.toBeInTheDocument();
expect(screen.queryByText("Gateway: remote-server")).not.toBeInTheDocument();
});
it("retains the safe fallback for an older host without optional guidance", async () => {
vi.mocked(api.createUpdateReview).mockResolvedValue({ ...review, execution_available: false,
plan: { ...review.plan, execution_blocked_reason: "installation_owner" } });
render(view());
fireEvent.click(screen.getByText("Update entry"));
await screen.findByRole("link", { name: "Update instructions for your installation" });
expect(screen.queryByRole("button", { name: "Update & restart" })).not.toBeInTheDocument();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("guides an already installed target through restart without offering another installation", async () => {
vi.mocked(api.createUpdateReview).mockResolvedValue({ ...externalReview,
plan: { ...externalReview.plan, action: "restart", execution_blocked_reason: "not_upgrade",
guide: { ...externalReview.plan.guide!, reason: "restart", update_command: null, inspect_command: null } } });
render(view());
fireEvent.click(screen.getByText("Update entry"));
await screen.findByRole("heading", { name: "Restart and verify" });
expect(screen.getByRole("button", { name: "Check running gateway" })).toBeVisible();
expect(screen.queryByLabelText("Update command")).not.toBeInTheDocument();
expect(api.prepareUpdate).not.toHaveBeenCalled();
});
it("does not send a managed-install user to the terminal during a long reconnect", async () => {
vi.useFakeTimers();
connectionStatus = "closed";
sessionStorage.setItem("nanobot.pending-update.v1", id);
sessionStorage.setItem("nanobot.pending-update-recovery.v1", JSON.stringify({
id, command: "private recovery command", automatic: true,
}));
render(view());
await act(async () => { await vi.advanceTimersByTimeAsync(123_000); });
expect(screen.getByText(/nanobot will try to restore service/)).toBeVisible();
expect(screen.queryByDisplayValue("private recovery command")).not.toBeInTheDocument();
expect(api.executeUpdate).not.toHaveBeenCalled();
expect(api.readUpdateJob).not.toHaveBeenCalled();
});
it("reports a restored service without claiming the update succeeded or asking for terminal repair", async () => {
sessionStorage.setItem("nanobot.pending-update.v1", id);
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: {
...job("failed", "confirmed"), previous_version: "0.3.5", service_restored: true,
mutation_started: true, recovery_command: "private recovery command",
} });
render(view());
await screen.findByText("Previous version restored");
expect(screen.getByText(/v0.3.5 is running again/)).toBeInTheDocument();
expect(screen.queryByText("Update complete")).not.toBeInTheDocument();
expect(screen.queryByDisplayValue("private recovery command")).not.toBeInTheDocument();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("keeps polling a failed attempt while its independent recovery owner is active", async () => {
sessionStorage.setItem("nanobot.pending-update.v1", id);
vi.mocked(api.readUpdateJob).mockResolvedValueOnce({ job: {
...job("failed", "confirmed"), recovery_active: true, mutation_started: true,
} }).mockResolvedValue({ job: {
...job("failed", "confirmed"), previous_version: "0.3.5", service_restored: true,
} });
render(view());
await screen.findByText("Previous version restored", {}, { timeout: 4000 });
expect(api.readUpdateJob).toHaveBeenCalledTimes(2);
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it.each(["0.3.7.dev42", "0.3.7"])("shows preview risk only for a preview installation target (%s)", async (version) => {
vi.mocked(api.createUpdateReview).mockResolvedValue({ ...review, plan: { ...review.plan, target_version: version } });
render(view());
fireEvent.click(screen.getByText("Update entry"));
await screen.findByRole("button", { name: "Update & restart" });
expect(screen.queryByText("This is a preview release and may have bugs.") !== null).toBe(version.includes(".dev"));
expect(api.prepareUpdate).not.toHaveBeenCalled();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it.each(["preparation_requested", "preparing"] as const)("settles a refreshed %s job before reviewing a fresh plan, without the handoff extension", async (phase) => {
vi.useFakeTimers();
vi.mocked(api.prepareUpdate).mockResolvedValue({ job: job(phase) });
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job(phase) });
let resolveSettlement!: (value: { job: api.UpdateJob }) => void;
vi.mocked(api.settleUpdate).mockImplementation(() => new Promise(resolve => { resolveSettlement = resolve; }));
const mounted = render(view("gateway-a", true, false));
fireEvent.click(screen.getByText("Update entry"));
await act(async () => {});
fireEvent.click(screen.getByRole("button", { name: "Update & restart" }));
await act(async () => {});
expect(screen.getByRole("button", { name: "Please wait" })).toBeDisabled();
expect(screen.queryByRole("button", { name: "Review update" })).not.toBeInTheDocument();
mounted.unmount();
// A refresh restores the durable ID, not the old tab's installation consent.
render(view("gateway-a", true, false));
await act(async () => {});
expect(screen.getByRole("button", { name: "Review update" })).toBeEnabled();
await act(async () => { await vi.advanceTimersByTimeAsync(123_000); });
expect(screen.getByRole("button", { name: "Review update" })).toBeEnabled();
expect(api.settleUpdate).not.toHaveBeenCalled();
expect(api.createUpdateReview).toHaveBeenCalledOnce();
expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBe(id);
const nextId = "81c91a73-842e-42e9-aeb4-61a5bfe51135";
vi.mocked(api.createUpdateReview).mockResolvedValue({ ...review, plan: { ...review.plan, id: nextId, target_version: "0.3.7" } });
fireEvent.click(screen.getByRole("button", { name: "Review update" }));
await act(async () => {});
expect(screen.getByRole("button", { name: "Please wait" })).toBeDisabled();
expect(api.createUpdateReview).toHaveBeenCalledOnce();
expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBe(id);
await act(async () => resolveSettlement({ job: job("preparation_failed") }));
expect(screen.getByText(/Updating to v0.3.7/)).toBeVisible();
expect(screen.getByRole("button", { name: "Update & restart" })).toBeEnabled();
expect(api.settleUpdate).toHaveBeenCalledOnce();
expect(api.settleUpdate).toHaveBeenCalledWith(client, id);
expect(api.createUpdateReview).toHaveBeenCalledTimes(2);
expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBeNull();
expect(sessionStorage.getItem("nanobot.pending-update-recovery.v1")).toBeNull();
await act(async () => { await vi.advanceTimersByTimeAsync(3000); });
expect(api.prepareUpdate).toHaveBeenCalledOnce();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("keeps an active preparer's refused settlement and retries status read-only", async () => {
vi.useFakeTimers();
sessionStorage.setItem("nanobot.pending-update.v1", id);
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job("preparing") });
vi.mocked(api.settleUpdate).mockRejectedValue(new api.ApiError(409, "Preparation owner still active"));
render(view("gateway-a", true, false));
await act(async () => {});
fireEvent.click(screen.getByRole("button", { name: "Review update" }));
await act(async () => {});
expect(screen.getByText(/previous update could not be cleared safely/)).toBeVisible();
expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBe(id);
fireEvent.click(screen.getByRole("button", { name: "Check again" }));
await act(async () => { await vi.advanceTimersByTimeAsync(600); });
expect(api.readUpdateJob).toHaveBeenCalledTimes(2);
expect(screen.getByRole("button", { name: "Review update" })).toBeEnabled();
await act(async () => { await vi.advanceTimersByTimeAsync(3000); });
expect(screen.getByRole("button", { name: "Review update" })).toBeEnabled();
expect(api.settleUpdate).toHaveBeenCalledOnce();
expect(api.createUpdateReview).not.toHaveBeenCalled();
expect(api.prepareUpdate).not.toHaveBeenCalled();
expect(api.executeUpdate).not.toHaveBeenCalled();
expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBe(id);
});
it("keeps a lost preparation-settlement response recoverable without creating another job", async () => {
vi.useFakeTimers();
sessionStorage.setItem("nanobot.pending-update.v1", id);
sessionStorage.setItem("nanobot.pending-update-recovery.v1", JSON.stringify({ id, command: "saved recovery command" }));
let saved = job("preparing");
vi.mocked(api.readUpdateJob).mockImplementation(async () => ({ job: saved }));
vi.mocked(api.settleUpdate).mockImplementation(async () => {
saved = job("preparation_failed");
throw new Error("response lost after settlement");
});
const mounted = render(view("gateway-a", true, false));
await act(async () => {});
fireEvent.click(screen.getByRole("button", { name: "Review update" }));
await act(async () => {});
expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBe(id);
expect(sessionStorage.getItem("nanobot.pending-update-recovery.v1")).toContain("saved recovery command");
fireEvent.click(screen.getByRole("button", { name: "Check again" }));
await act(async () => { await vi.advanceTimersByTimeAsync(600); });
expect(screen.getByText("Update did not finish")).toBeVisible();
expect(api.readUpdateJob).toHaveBeenCalledTimes(2);
expect(api.settleUpdate).toHaveBeenCalledOnce();
expect(api.createUpdateReview).not.toHaveBeenCalled();
expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBe(id);
mounted.unmount();
render(view("gateway-a", true, false));
await act(async () => {});
expect(screen.getByText("Update did not finish")).toBeVisible();
expect(api.createUpdateReview).not.toHaveBeenCalled();
expect(api.prepareUpdate).not.toHaveBeenCalled();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("retires a restored failed handoff and reviews a fresh plan before new consent", async () => {
sessionStorage.setItem("nanobot.pending-update.v1", id);
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job("handoff_failed", "previous") });
vi.mocked(api.settleUpdate).mockResolvedValue({ job: job("cancelled", "previous") });
const nextId = "81c91a73-842e-42e9-aeb4-61a5bfe51135";
vi.mocked(api.createUpdateReview).mockResolvedValue({ ...review, plan: { ...review.plan, id: nextId } });
render(view());
fireEvent.click(await screen.findByRole("button", { name: "Review update" }));
await screen.findByRole("button", { name: "Update & restart" });
expect(api.settleUpdate).toHaveBeenCalledWith(client, id);
expect(api.createUpdateReview).toHaveBeenCalledOnce();
expect(api.executeUpdate).not.toHaveBeenCalled();
expect(api.prepareUpdate).not.toHaveBeenCalled();
expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBeNull();
vi.mocked(api.prepareUpdate).mockResolvedValue({ job: { ...job("preparing"), id: nextId } });
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: { ...job("ready"), id: nextId } });
fireEvent.click(screen.getByRole("button", { name: "Update & restart" }));
await waitFor(() => expect(api.executeUpdate).toHaveBeenCalledWith(client, nextId));
expect(api.executeUpdate).toHaveBeenCalledOnce();
});
it("keeps a refused settlement recoverable and Check again strictly read-only", async () => {
sessionStorage.setItem("nanobot.pending-update.v1", id);
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job("handoff_failed", "previous") });
vi.mocked(api.settleUpdate).mockRejectedValue(new api.ApiError(409, "Worker still active"));
render(view());
fireEvent.click(await screen.findByRole("button", { name: "Review update" }));
await screen.findByText(/previous update could not be cleared safely/);
expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBe(id);
expect(api.createUpdateReview).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Check again" }));
await screen.findByRole("button", { name: "Review update" });
expect(api.readUpdateJob).toHaveBeenCalledTimes(2);
expect(api.settleUpdate).toHaveBeenCalledOnce();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("can leave an expired READY review without bypassing gateway settlement", async () => {
sessionStorage.setItem("nanobot.pending-update.v1", id);
vi.mocked(api.readUpdateReview).mockResolvedValue({ ...review, execution_available: false,
plan: { ...review.plan, validity: "expired", execution_blocked_reason: "review_changed" } });
vi.mocked(api.settleUpdate).mockResolvedValue({ job: job("cancelled") });
render(view());
fireEvent.click(await screen.findByRole("button", { name: "Review update" }));
await screen.findByRole("button", { name: "Update & restart" });
expect(api.settleUpdate).toHaveBeenCalledWith(client, id);
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("recovers a lost settlement response after reload without restoring consent", async () => {
sessionStorage.setItem("nanobot.pending-update.v1", id);
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job("cancelled", "previous") });
vi.mocked(api.settleUpdate).mockResolvedValue({ job: job("cancelled", "previous") });
render(view());
fireEvent.click(await screen.findByRole("button", { name: "Review update" }));
await screen.findByRole("button", { name: "Update & restart" });
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("does not retry execution or send unsupported settlement to older hosts", async () => {
sessionStorage.setItem("nanobot.pending-update.v1", id);
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job("handoff_failed", "previous") });
render(view("gateway-a", true, false));
fireEvent.click(await screen.findByRole("button", { name: "Check again" }));
await waitFor(() => expect(api.readUpdateJob).toHaveBeenCalledTimes(2));
expect(api.executeUpdate).not.toHaveBeenCalled();
expect(api.settleUpdate).not.toHaveBeenCalled();
});
it("reviews on open and stages/executes the same exact plan only after confirmation", async () => {
render(view());
fireEvent.click(screen.getByText("Update entry"));
expect(await screen.findByText(/Updating to v0.3.6/)).toBeVisible();
expect(api.prepareUpdate).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Update & restart" }));
await waitFor(() => expect(api.executeUpdate).toHaveBeenCalledOnce());
expect(api.executeUpdate).toHaveBeenCalledWith(client, id);
expect(api.prepareUpdate).toHaveBeenCalledOnce();
expect(api.prepareUpdate).toHaveBeenCalledWith(client, id);
});
it("reads a restored READY job but never restores installation consent", async () => {
sessionStorage.setItem("nanobot.pending-update.v1", id);
render(view());
await screen.findByText(/Updating to v0.3.6/);
expect(api.createUpdateReview).not.toHaveBeenCalled();
expect(api.prepareUpdate).not.toHaveBeenCalled();
expect(api.executeUpdate).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Update & restart" }));
await waitFor(() => expect(api.executeUpdate).toHaveBeenCalledOnce());
});
it("waits for the restored review before enabling confirmation", async () => {
sessionStorage.setItem("nanobot.pending-update.v1", id);
let resolveReview!: (value: api.UpdateReviewResponse) => void;
vi.mocked(api.readUpdateReview).mockImplementation(() => new Promise(resolve => { resolveReview = resolve; }));
render(view());
await waitFor(() => expect(api.readUpdateReview).toHaveBeenCalledWith("gateway-a", id));
expect(screen.queryByRole("button", { name: "Update & restart" })).toBeNull();
expect(screen.getByRole("button", { name: "Please wait" })).toBeDisabled();
expect(screen.getByText("Checking the update…")).toBeVisible();
await act(async () => resolveReview(review));
expect(screen.getByRole("button", { name: "Update & restart" })).toBeEnabled();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("allows a fresh review after a rejected stale preparation has no saved job", async () => {
// Another tab changed the channel after this plan was reviewed. The gateway
// rejects preparation before creating a job; a 404 alone is not that proof.
vi.mocked(api.prepareUpdate).mockRejectedValue(new api.ApiError(409, "Preparation refused"));
vi.mocked(api.readUpdateJob).mockRejectedValue(new api.ApiError(404, "No saved update"));
render(view());
fireEvent.click(screen.getByText("Update entry"));
fireEvent.click(await screen.findByRole("button", { name: "Update & restart" }));
await screen.findByText(/No package files were changed. Review the update again/);
expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBeNull();
const nextId = "81c91a73-842e-42e9-aeb4-61a5bfe51135";
vi.mocked(api.createUpdateReview).mockResolvedValue({ ...review, plan: { ...review.plan, id: nextId } });
fireEvent.click(screen.getByRole("button", { name: "Check again" }));
await screen.findByRole("button", { name: "Update & restart" });
expect(api.createUpdateReview).toHaveBeenCalledTimes(2);
expect(api.prepareUpdate).toHaveBeenCalledOnce();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("retains an unknown preparation outcome even if the job is not visible yet", async () => {
vi.mocked(api.prepareUpdate).mockRejectedValue(new api.ApiError(504, "Request timed out"));
vi.mocked(api.readUpdateJob).mockRejectedValue(new api.ApiError(404, "No saved update"));
render(view());
fireEvent.click(screen.getByText("Update entry"));
fireEvent.click(await screen.findByRole("button", { name: "Update & restart" }));
await screen.findByText(/Could not read the saved update/);
expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBe(id);
fireEvent.click(screen.getByRole("button", { name: "Check again" }));
await waitFor(() => expect(api.readUpdateJob).toHaveBeenCalledTimes(2));
expect(api.createUpdateReview).toHaveBeenCalledOnce();
expect(api.prepareUpdate).toHaveBeenCalledOnce();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("preserves a durable job after a preparation error instead of granting new consent", async () => {
vi.mocked(api.prepareUpdate).mockRejectedValue(new api.ApiError(409, "Read the saved state"));
render(view());
fireEvent.click(screen.getByText("Update entry"));
fireEvent.click(await screen.findByRole("button", { name: "Update & restart" }));
await waitFor(() => expect(api.readUpdateJob).toHaveBeenCalled());
await screen.findByRole("button", { name: "Update & restart" });
expect(sessionStorage.getItem("nanobot.pending-update.v1")).toBe(id);
expect(api.createUpdateReview).toHaveBeenCalledOnce();
expect(api.prepareUpdate).toHaveBeenCalledOnce();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("never creates or executes a second job after a lost execution response", async () => {
vi.mocked(api.executeUpdate).mockRejectedValue(new Error("connection closed"));
vi.mocked(api.readUpdateJob).mockResolvedValueOnce({ job: job("ready") }).mockResolvedValue({ job: job("ready", "confirmed") });
render(view());
fireEvent.click(screen.getByText("Update entry"));
fireEvent.click(await screen.findByRole("button", { name: "Update & restart" }));
await screen.findByText(/request may have been accepted/);
fireEvent.click(screen.getByRole("button", { name: "Check again" }));
await waitFor(() => expect(api.readUpdateJob).toHaveBeenCalledTimes(2));
expect(api.executeUpdate).toHaveBeenCalledOnce();
expect(api.createUpdateReview).toHaveBeenCalledOnce();
expect(screen.getByRole("button", { name: "Checking..." })).toBeDisabled();
expect(await screen.findByRole("button", { name: "Please wait" })).toBeDisabled();
});
it("does not report completion until the actual running version matches", async () => {
sessionStorage.setItem("nanobot.pending-update.v1", id);
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job("succeeded", "confirmed") });
const mounted = render(view());
await screen.findByText("Reconnecting…");
expect(screen.queryByText("Update complete")).toBeNull();
mounted.unmount();
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: { ...job("succeeded", "confirmed"), running_version: "0.3.6" } });
render(view());
expect(await screen.findByText("Update complete")).toBeVisible();
expect(screen.getByText("Now running v0.3.6.")).toBeVisible();
expect(screen.getAllByRole("button").filter(button => button.textContent === "Done")).toHaveLength(1);
});
it("waits for authenticated reconnect when a restart invalidates an in-flight journal read", async () => {
vi.useFakeTimers();
sessionStorage.setItem("nanobot.pending-update.v1", id);
let rejectRead!: (reason: unknown) => void;
vi.mocked(api.readUpdateJob).mockImplementationOnce(() => new Promise((_, reject) => { rejectRead = reject; }));
const mounted = render(view());
await act(async () => {
connectionStatus = "reconnecting";
rejectRead(new api.ApiError(401, "Unauthorized"));
});
expect(screen.getByText("Reconnecting…")).toBeVisible();
expect(screen.queryByText(/Could not read the saved update/)).toBeNull();
await act(async () => { await vi.advanceTimersByTimeAsync(3000); });
expect(api.readUpdateJob).toHaveBeenCalledTimes(1);
// Bootstrap renews the API token before the socket finishes reconnecting.
mounted.rerender(view("renewed-gateway-a"));
expect(api.readUpdateJob).toHaveBeenCalledTimes(1);
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: {
...job("succeeded", "confirmed"), mutation_started: true, running_version: "0.3.6",
} });
connectionStatus = "open";
await act(async () => { await vi.advanceTimersByTimeAsync(1500); });
expect(api.readUpdateJob).toHaveBeenLastCalledWith("renewed-gateway-a", id);
expect(screen.getByText("Update complete")).toBeVisible();
expect(api.createUpdateReview).not.toHaveBeenCalled();
expect(api.prepareUpdate).not.toHaveBeenCalled();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("still reports rejected journal access on an authenticated connection", async () => {
sessionStorage.setItem("nanobot.pending-update.v1", id);
vi.mocked(api.readUpdateJob).mockRejectedValue(new api.ApiError(401, "Unauthorized"));
render(view());
expect(await screen.findByText(/Could not read the saved update/)).toBeVisible();
expect(screen.getByRole("button", { name: "Check again" })).toBeEnabled();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("replaces a prolonged reconnect with the actual journal error and allows a read-only retry", async () => {
vi.useFakeTimers();
sessionStorage.setItem("nanobot.pending-update.v1", id);
connectionStatus = "reconnecting";
render(view());
await act(async () => { await vi.advanceTimersByTimeAsync(123_000); });
expect(screen.getByText("Reconnecting…")).toBeVisible();
connectionStatus = "open";
vi.mocked(api.readUpdateJob).mockRejectedValue(new api.ApiError(403, "Forbidden"));
await act(async () => { await vi.advanceTimersByTimeAsync(1500); });
expect(screen.getByText(/Could not read the saved update/)).toBeVisible();
expect(screen.queryByText("Reconnecting…")).toBeNull();
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: {
...job("succeeded", "confirmed"), running_version: "0.3.6",
} });
await act(async () => { fireEvent.click(screen.getByRole("button", { name: "Check again" })); });
await act(async () => { await vi.advanceTimersByTimeAsync(600); });
expect(screen.getByText("Update complete")).toBeVisible();
expect(api.prepareUpdate).not.toHaveBeenCalled();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("keeps one preparation when double-clicked, hidden and reopened", async () => {
let resolve!: (value: { job: api.UpdateJob }) => void;
vi.useFakeTimers();
vi.mocked(api.prepareUpdate).mockImplementation(() => new Promise(done => { resolve = done; }));
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job("preparing") });
render(view("gateway-a", true, false));
fireEvent.click(screen.getByText("Update entry"));
await act(async () => {});
const button = screen.getByRole("button", { name: "Update & restart" });
fireEvent.click(button);
fireEvent.click(button);
fireEvent.click(screen.getByRole("button", { name: "Hide" }));
fireEvent.click(screen.getByText("Update entry"));
await act(async () => resolve({ job: job("preparing") }));
await act(async () => { await vi.advanceTimersByTimeAsync(123_000); });
expect(screen.getByRole("button", { name: "Please wait" })).toBeDisabled();
expect(screen.queryByRole("button", { name: "Review update" })).not.toBeInTheDocument();
expect(api.settleUpdate).not.toHaveBeenCalled();
expect(api.executeUpdate).not.toHaveBeenCalled();
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: job("ready") });
await act(async () => { await vi.advanceTimersByTimeAsync(1500); });
expect(api.executeUpdate).toHaveBeenCalledOnce();
expect(api.createUpdateReview).toHaveBeenCalledOnce();
expect(api.prepareUpdate).toHaveBeenCalledOnce();
expect(api.executeUpdate).toHaveBeenCalledWith(client, id);
});
it("acknowledges a read-only retry even when the same failure returns immediately", async () => {
vi.useFakeTimers();
sessionStorage.setItem("nanobot.pending-update.v1", id);
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: {
...job("restart_failed", "confirmed"), mutation_started: true,
} });
render(view());
await act(async () => {});
const retry = screen.getByRole("button", { name: "Check again" });
fireEvent.click(retry);
fireEvent.click(retry);
await act(async () => { await vi.advanceTimersByTimeAsync(599); });
expect(screen.getByRole("button", { name: "Checking..." })).toBeDisabled();
expect(api.readUpdateJob).toHaveBeenCalledTimes(2);
await act(async () => { await vi.advanceTimersByTimeAsync(1); });
expect(screen.getByRole("button", { name: "Check again" })).toBeEnabled();
expect(screen.getByText("Update did not finish")).toBeVisible();
expect(api.createUpdateReview).not.toHaveBeenCalled();
expect(api.prepareUpdate).not.toHaveBeenCalled();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("can reopen a hidden saved update from About even after the new version is installed", async () => {
sessionStorage.setItem("nanobot.pending-update.v1", id);
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: {
...job("restart_failed", "confirmed"), mutation_started: true, running_version: "0.3.6",
} });
render(<ClientProvider client={client} token="gateway-a" checkUpdatesOnConnect webuiCapabilities={["webui.update-flow.v1"]}>
<AboutSettings settings={settingsPayload()} />
</ClientProvider>);
fireEvent.click(await screen.findByRole("button", { name: "Close" }));
expect(screen.queryByRole("alertdialog")).toBeNull();
expect(screen.getByText("You're up to date")).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "View details" }));
expect(screen.getByRole("alertdialog", { name: "Update did not finish" })).toBeVisible();
expect(api.createUpdateReview).not.toHaveBeenCalled();
expect(api.prepareUpdate).not.toHaveBeenCalled();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
it("ignores an old gateway's late review without starting an installation", async () => {
let resolve!: (value: api.UpdateReviewResponse) => void;
vi.mocked(api.createUpdateReview).mockImplementation(() => new Promise(done => { resolve = done; }));
const mounted = render(view());
fireEvent.click(screen.getByText("Update entry"));
mounted.rerender(view("gateway-b"));
await act(async () => resolve(review));
expect(screen.queryByRole("alertdialog")).toBeNull();
expect(api.prepareUpdate).not.toHaveBeenCalled();
});
it("keeps unsupported or unauthorized installations read-only", async () => {
vi.mocked(api.createUpdateReview).mockResolvedValue({ ...review, installation_allowed: false });
render(view());
fireEvent.click(screen.getByText("Update entry"));
expect(await screen.findByText(/Open this gateway on localhost/)).toBeVisible();
expect(screen.queryByRole("button", { name: "Update & restart" })).toBeNull();
expect(screen.getByRole("button", { name: "Close" })).toBeEnabled();
expect(api.prepareUpdate).not.toHaveBeenCalled();
});
it("does not offer the flow to older hosts without its optional capability", () => {
render(view("gateway-a", false));
expect(screen.getByText("Update entry")).toBeDisabled();
expect(api.createUpdateReview).not.toHaveBeenCalled();
});
it("shows the saved host recovery command after mutation failure without executing it", async () => {
sessionStorage.setItem("nanobot.pending-update.v1", id);
const command = `python3 -I -S ~/.nanobot/updates/recover.py ${id} --repair`;
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: {
...job("failed", "confirmed"), mutation_started: true, recovery_command: command,
} });
render(view());
expect(await screen.findByDisplayValue(command)).toBeVisible();
expect(screen.getByRole("button", { name: "Check again" })).toBeEnabled();
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: {
...job("succeeded", "confirmed"), running_version: "0.3.6", mutation_started: true,
} });
fireEvent.click(screen.getByRole("button", { name: "Check again" }));
expect(await screen.findByText("Update complete")).toBeVisible();
expect(api.executeUpdate).not.toHaveBeenCalled();
expect(JSON.parse(sessionStorage.getItem("nanobot.pending-update-recovery.v1") || "{}").command).toBe(command);
});
it("shows recovery after an admitted job fails during backup before package mutation", async () => {
sessionStorage.setItem("nanobot.pending-update.v1", id);
const command = `python3 -I -S /private/update/recover.py ${id} --repair`;
vi.mocked(api.readUpdateJob).mockResolvedValue({ job: {
...job("failed", "confirmed"), recovery_command: command,
} });
render(view());
expect(await screen.findByDisplayValue(command)).toBeVisible();
expect(screen.getByText(/The update stopped before installation. No package files were changed/)).toBeVisible();
expect(screen.getAllByText(/Run this command in a terminal/)).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: "Check again" }));
await waitFor(() => expect(api.readUpdateJob).toHaveBeenCalledTimes(2));
expect(api.createUpdateReview).not.toHaveBeenCalled();
expect(api.prepareUpdate).not.toHaveBeenCalled();
expect(api.executeUpdate).not.toHaveBeenCalled();
});
});
+195
View File
@@ -0,0 +1,195 @@
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { useState } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";
import { Sidebar } from "@/components/Sidebar";
import { AboutSettings } from "@/components/settings/overview/OverviewSettings";
import { UpdateNotice } from "@/components/UpdateNotice";
import { ClientProvider } from "@/providers/ClientProvider";
import { useVersionCheck } from "@/providers/VersionCheckProvider";
import { NanobotClient } from "@/lib/nanobot-client";
import { jsonResponse, settingsPayload } from "@/tests/settings-test-utils";
afterEach(() => { cleanup(); vi.unstubAllGlobals(); vi.useRealTimers(); });
const client = new NanobotClient({ url: "ws://localhost:8765" });
const available = (version = "0.3.6") => ({ updateAvailable: { currentVersion: "0.3.5", latestVersion: version } });
it.each([
["uv", "Update via uv"], ["pipx", "Update via pipx"], ["pip", "Update via pip"],
["source", "Update via source checkout"], ["container", "Update via container deployment"],
["managed", "Update"], ["future-owner", "Update"],
])("labels the update entry with the detected owner (%s)", async (method, label) => {
vi.stubGlobal("fetch", vi.fn().mockResolvedValue(jsonResponse({ ...available(), installation_method: method })));
const request = vi.fn();
render(<ClientProvider token="test" client={client}><AboutSettings settings={settingsPayload()} onRequestUpdate={request} /></ClientProvider>);
const entry = await screen.findByRole("button", { name: label });
fireEvent.click(entry);
expect(request).toHaveBeenCalledOnce();
});
function Surface() {
const update = useVersionCheck();
const [about, setAbout] = useState(false);
return <>
<input aria-label="Draft" />
{update.result?.type === "update" && update.dismissedVersion !== update.result.latestVersion && (
<UpdateNotice version={update.result.latestVersion} onOpen={() => setAbout(true)} onDismiss={update.dismiss} />
)}
<button onClick={() => void update.check()}>Refresh version</button>
{about && <AboutSettings settings={{ ...settingsPayload(), version: { current: "0.3.5" } }} />}
</>;
}
const view = (token = "host-a") => <ClientProvider client={client} token={token} checkUpdatesOnConnect><Surface /></ClientProvider>;
describe("Sidebar update entry", () => {
it("keeps About update actions available after dismissing the sidebar notice", async () => {
const fetcher = vi.fn(async () => jsonResponse(available()));
vi.stubGlobal("fetch", fetcher);
const { rerender } = render(view("dismiss-sidebar"));
fireEvent.click(await screen.findByRole("button", { name: "Update available v0.3.6" }));
fireEvent.click(screen.getByRole("button", { name: "Dismiss update notice" }));
rerender(<ClientProvider client={client} token="dismiss-sidebar" checkUpdatesOnConnect>
<Surface />
<AboutSettings settings={settingsPayload()} onRequestUpdate={vi.fn()} />
</ClientProvider>);
expect(await screen.findByRole("button", { name: /^Update$/ })).toBeVisible();
expect(screen.queryByRole("button", { name: "Update available v0.3.6" })).toBeNull();
expect(screen.queryByRole("button", { name: "Dismiss update notice" })).toBeNull();
expect(fetcher).toHaveBeenCalledTimes(2);
});
it("automatically checks each About entry, shares an in-flight check and retries failures without a loading delay", async () => {
let resolve!: (response: Response) => void;
const fetcher = vi.fn().mockImplementation(() => new Promise<Response>(done => { resolve = done; }));
vi.stubGlobal("fetch", fetcher);
const surface = (about: boolean) => <ClientProvider client={client} token="about-entry" checkUpdatesOnConnect>
{about && <AboutSettings settings={settingsPayload()} />}
</ClientProvider>;
const mounted = render(surface(false));
expect(fetcher).toHaveBeenCalledOnce();
mounted.rerender(surface(true));
expect(screen.getByRole("status")).toHaveTextContent("Checking...");
expect(fetcher).toHaveBeenCalledOnce();
await act(async () => resolve(jsonResponse({ updateAvailable: null })));
expect(screen.getByText("You're up to date")).toBeVisible();
mounted.rerender(surface(false));
mounted.rerender(surface(true));
expect(fetcher).toHaveBeenCalledTimes(2);
expect(screen.getByRole("status")).toHaveTextContent("Checking...");
await act(async () => resolve(jsonResponse({ updateAvailable: null })));
fetcher.mockRejectedValueOnce(new Error("Connection unavailable"));
fireEvent.click(screen.getByRole("button", { name: "Check again" }));
expect(await screen.findByText("Connection unavailable")).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
expect(screen.getByRole("status")).toHaveTextContent("Checking...");
expect(fetcher).toHaveBeenCalledTimes(4);
await act(async () => resolve(jsonResponse(available())));
expect(screen.getByRole("link", { name: "Installation guide" })).toBeVisible();
});
it("opens the provided update confirmation directly without navigating through details", () => {
const openDetails = vi.fn();
const requestUpdate = vi.fn();
render(<UpdateNotice version="0.3.6" onOpen={openDetails} onDismiss={vi.fn()} onRequestUpdate={requestUpdate} />);
expect(requestUpdate).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Update available v0.3.6" }));
expect(requestUpdate).toHaveBeenCalledOnce();
expect(openDetails).not.toHaveBeenCalled();
expect(screen.queryByRole("button", { name: "View details" })).toBeNull();
});
it("uses the same direct confirmation in About when an update action is available", async () => {
vi.stubGlobal("fetch", vi.fn(async () => jsonResponse(available())));
const requestUpdate = vi.fn();
render(<ClientProvider client={client} token="about-update" checkUpdatesOnConnect>
<AboutSettings settings={{ ...settingsPayload(), version: { current: "0.3.5" } }} onRequestUpdate={requestUpdate} />
</ClientProvider>);
const button = await screen.findByRole("button", { name: /^Update$/ });
expect(screen.queryByRole("link", { name: "Installation guide" })).toBeNull();
expect(requestUpdate).not.toHaveBeenCalled();
fireEvent.click(button);
expect(requestUpdate).toHaveBeenCalledOnce();
});
it("opens in place, preserves the draft, and navigates only from View details", async () => {
const fetcher = vi.fn(async () => jsonResponse(available()));
vi.stubGlobal("fetch", fetcher);
render(view());
fireEvent.change(screen.getByLabelText("Draft"), { target: { value: "Keep writing" } });
fireEvent.click(await screen.findByRole("button", { name: "Update available v0.3.6" }));
expect(screen.getByRole("dialog", { name: "Update available v0.3.6" })).toBeVisible();
expect(screen.queryByRole("link", { name: "Installation guide" })).toBeNull();
expect(screen.getByLabelText("Draft")).toHaveValue("Keep writing");
fireEvent.keyDown(screen.getByRole("dialog"), { key: "Escape" });
await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
expect(screen.getByRole("button", { name: "Update available v0.3.6" })).toHaveFocus();
fireEvent.click(screen.getByRole("button", { name: "Update available v0.3.6" }));
fireEvent.click(screen.getByRole("button", { name: "View details" }));
expect(await screen.findByRole("link", { name: "Installation guide" })).toHaveAttribute("href", "https://github.com/HKUDS/nanobot#-install");
expect(fetcher).toHaveBeenCalledTimes(2);
expect(fetcher).toHaveBeenCalledWith("/api/settings/version-check", expect.any(Object));
});
it("deduplicates checks, dismisses one version, and shows a later version", async () => {
let resolve!: (response: Response) => void;
const fetcher = vi.fn().mockImplementationOnce(() => new Promise<Response>((done) => { resolve = done; }))
.mockResolvedValueOnce(jsonResponse(available())).mockResolvedValueOnce(jsonResponse(available("0.3.7")));
vi.stubGlobal("fetch", fetcher);
render(view());
fireEvent.click(screen.getByText("Refresh version"));
expect(fetcher).toHaveBeenCalledTimes(1);
await act(async () => resolve(jsonResponse(available())));
fireEvent.click(screen.getByRole("button", { name: "Update available v0.3.6" }));
fireEvent.click(screen.getByRole("button", { name: "Dismiss update notice" }));
expect(screen.queryByRole("button", { name: "Update available v0.3.6" })).toBeNull();
fireEvent.click(screen.getByText("Refresh version"));
await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));
expect(screen.queryByRole("button", { name: "Update available v0.3.6" })).toBeNull();
fireEvent.click(screen.getByText("Refresh version"));
expect(await screen.findByRole("button", { name: "Update available v0.3.7" })).toBeVisible();
});
it("ignores late host results without remounting the client or losing its draft", async () => {
let resolveOld!: (response: Response) => void;
const fetcher = vi.fn().mockImplementationOnce(() => new Promise<Response>((done) => { resolveOld = done; }))
.mockResolvedValueOnce(jsonResponse({ updateAvailable: null }));
vi.stubGlobal("fetch", fetcher);
const { rerender } = render(view());
fireEvent.change(screen.getByLabelText("Draft"), { target: { value: "Keep this draft" } });
rerender(view("host-b"));
await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(2));
await act(async () => resolveOld(jsonResponse(available())));
expect(screen.queryByRole("button", { name: /Update available/ })).toBeNull();
expect(screen.getByLabelText("Draft")).toHaveValue("Keep this draft");
});
it.each([null, new Error("offline")])("keeps an unavailable check quiet (%s)", async (failure) => {
const fetcher = vi.fn().mockImplementation(() => failure ? Promise.reject(failure) : Promise.resolve(jsonResponse({ updateAvailable: null })));
vi.stubGlobal("fetch", fetcher);
render(view());
await waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1));
expect(screen.queryByRole("button", { name: /Update available/ })).toBeNull();
expect(screen.queryByRole("alert")).toBeNull();
});
it("renders the same entry in expanded and collapsed navigation", () => {
const noop = vi.fn();
const props = { sessions: [], activeKey: null, loading: false, newChatActive: false,
onNewChat: noop, onSelect: noop, onRequestDelete: noop, onTogglePin: noop, onRequestRename: noop,
onToggleArchive: noop, onToggleGroup: noop, onRequestRenameProject: noop, onNewChatInProject: noop,
onOpenSettings: noop, onOpenApps: noop, onOpenSkills: noop, onOpenAutomations: noop, onOpenChannels: noop,
onOpenSearch: noop, onToggleArchived: noop, onOpenUpdates: noop,
availableUpdate: { version: "0.3.6", onDismiss: noop } };
const { rerender } = render(<ClientProvider client={client} token="test"><Sidebar {...props} /></ClientProvider>);
fireEvent.click(screen.getByRole("button", { name: "Update available v0.3.6" }));
expect(noop).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "View details" }));
expect(noop).toHaveBeenCalledOnce();
rerender(<ClientProvider client={client} token="test"><Sidebar {...props} collapsed /></ClientProvider>);
expect(screen.getByRole("button", { name: "Update available v0.3.6" })).toBeVisible();
expect(screen.queryByText("Update available")).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Update available v0.3.6" }));
expect(screen.getByRole("dialog", { name: "Update available v0.3.6" })).toBeVisible();
});
});