Files
kandev/apps/web/app/settings/plugins/page.test.tsx
T
2026-08-26 11:26:09 +00:00

699 lines
26 KiB
TypeScript

import {
cleanup,
fireEvent,
render as renderWithoutSettingsProvider,
screen,
} from "@testing-library/react";
import type { ReactElement } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { toast } from "sonner";
import { SettingsSaveProvider } from "@/components/settings/settings-save-provider";
import type { InstallResult } from "@/lib/api/domains/plugins-api";
import type { PluginRecord, SyncResult } from "@/lib/types/plugins";
vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn(), warning: vi.fn() } }));
const {
enablePluginSpy,
disablePluginSpy,
uninstallPluginSpy,
installPluginFromUrlSpy,
installPluginUploadSpy,
listPluginsSpy,
syncPluginsSpy,
getMarketplaceCatalogSpy,
refreshMarketplaceSpy,
} = vi.hoisted(() => ({
enablePluginSpy: vi.fn(),
disablePluginSpy: vi.fn(),
uninstallPluginSpy: vi.fn(),
installPluginFromUrlSpy: vi.fn(),
installPluginUploadSpy: vi.fn(),
listPluginsSpy: vi.fn(),
syncPluginsSpy: vi.fn(),
getMarketplaceCatalogSpy: vi.fn(),
refreshMarketplaceSpy: vi.fn(),
}));
vi.mock("@/lib/api/domains/plugins-api", () => ({
listPlugins: (...args: unknown[]) => {
listPluginsSpy(...args);
return Promise.resolve([]);
},
enablePlugin: (...args: [string]) => {
enablePluginSpy(...args);
return Promise.resolve({ enabled: true });
},
disablePlugin: (...args: [string]) => {
disablePluginSpy(...args);
return Promise.resolve({ disabled: true });
},
uninstallPlugin: (...args: [string]) => {
return uninstallPluginSpy(...args);
},
installPluginFromUrl: (...args: [string]) => installPluginFromUrlSpy(...args),
installPluginUpload: (...args: [File]) => installPluginUploadSpy(...args),
syncPlugins: (...args: unknown[]) => syncPluginsSpy(...args),
// The auto-update controls fetch the instance-wide default on mount and
// persist per-plugin overrides; these tests don't exercise them, so provide
// inert stubs that keep useAutoUpdateSettings from throwing at mount.
getPluginSettings: () => Promise.resolve({ auto_update_default: false }),
updatePluginSettings: (enabled: boolean) => Promise.resolve({ auto_update_default: enabled }),
setPluginAutoUpdate: () => Promise.resolve(undefined),
}));
vi.mock("@/lib/api/domains/marketplace-api", () => ({
getMarketplaceCatalog: (...args: unknown[]) => getMarketplaceCatalogSpy(...args),
refreshMarketplace: (...args: unknown[]) => refreshMarketplaceSpy(...args),
}));
const { loadPluginsSpy, unloadPluginSpy } = vi.hoisted(() => ({
loadPluginsSpy: vi.fn(),
unloadPluginSpy: vi.fn(),
}));
vi.mock("@/lib/plugins/host", () => ({
loadPlugins: (...args: unknown[]) => {
loadPluginsSpy(...args);
return Promise.resolve();
},
unloadPlugin: (...args: unknown[]) => unloadPluginSpy(...args),
}));
vi.mock("@/lib/plugins/host-api", () => ({
buildHostApi: (pluginId: string) => ({ pluginId }),
}));
vi.mock("@/components/theme/app-theme", () => ({
useTheme: () => ({ resolvedTheme: "light" }),
}));
let storeState: Record<string, unknown> = {};
vi.mock("@/components/state-provider", () => ({
useAppStore: (selector: (state: Record<string, unknown>) => unknown) => selector(storeState),
useAppStoreApi: () => ({
getState: () => storeState,
setState: vi.fn(),
subscribe: vi.fn(() => () => {}),
}),
}));
import PluginsSettingsPage from "./page";
const PLUGIN_ID = "acme-tools";
const PLUGIN_DISPLAY_NAME = "Acme Tools";
const NEW_PLUGIN_ID = "new-plugin";
const SYNC_BUTTON_TESTID = "plugins-sync-button";
const CHECK_UPDATES_BUTTON_TESTID = "plugins-check-updates-button";
const INSTALL_TRIGGER_TESTID = "install-plugin-trigger";
const INSTALL_URL_INPUT_TESTID = "install-plugin-url-input";
const INSTALL_URL_SUBMIT_TESTID = "install-plugin-url-submit";
const NEW_PLUGIN_URL = "https://example.test/new-plugin-1.0.0.tar.gz";
const UPLOAD_FILENAME = "new-plugin-1.0.0.tar.gz";
function render(element: ReactElement) {
return renderWithoutSettingsProvider(<SettingsSaveProvider>{element}</SettingsSaveProvider>);
}
function activePlugin(overrides: Partial<PluginRecord> = {}): PluginRecord {
return {
id: PLUGIN_ID,
api_version: 1,
version: "1.0.0",
display_name: PLUGIN_DISPLAY_NAME,
description: "desc",
author: "acme",
categories: ["productivity"],
capabilities: {},
status: "active",
install_path: "/home/user/.kandev/plugins/acme-tools/1.0.0",
signed: true,
installed_at: "2026-01-01T00:00:00Z",
restart_count: 0,
ui: { bundle: "/ui/bundle.js", styles: ["/ui/style.css"] },
...overrides,
};
}
function installedPlugin(overrides: Partial<PluginRecord> = {}): PluginRecord {
return activePlugin({
id: NEW_PLUGIN_ID,
display_name: "New Plugin",
install_path: `/home/user/.kandev/plugins/${NEW_PLUGIN_ID}/1.0.0`,
...overrides,
});
}
function setStoreState(plugins: PluginRecord[]) {
storeState = {
auth: { user: null },
plugins: { items: plugins, loading: false, loaded: true, error: null },
setPlugins: vi.fn(),
setPluginsLoading: vi.fn(),
setPluginsError: vi.fn(),
upsertPlugin: vi.fn(),
removePlugin: vi.fn(),
};
}
function emptySyncResult(overrides: Partial<SyncResult> = {}): SyncResult {
return { added: [], installed: [], missing: [], errors: [], ...overrides };
}
function catalogEntry(overrides: Record<string, unknown> = {}) {
return {
id: PLUGIN_ID,
name: PLUGIN_DISPLAY_NAME,
description: "",
author: "acme",
categories: [],
icon_url: "",
repo_url: "",
version: "2.0.0",
min_kandev_version: "",
package_url: "https://example.test/acme-tools-2.0.0.tar.gz",
package_sha256: "",
stars: 0,
updated_at: "",
install_state: "update_available",
installed_version: "1.0.0",
source_id: "official",
source_name: "Kandev Official",
...overrides,
};
}
beforeEach(() => {
uninstallPluginSpy.mockResolvedValue({ deleted: true });
installPluginFromUrlSpy.mockResolvedValue({ plugin: installedPlugin() });
installPluginUploadSpy.mockResolvedValue({ plugin: installedPlugin() });
syncPluginsSpy.mockResolvedValue(emptySyncResult());
getMarketplaceCatalogSpy.mockReset();
getMarketplaceCatalogSpy.mockResolvedValue({ plugins: [], sources: [] });
refreshMarketplaceSpy.mockReset();
refreshMarketplaceSpy.mockResolvedValue({ refreshed: true });
});
afterEach(() => {
cleanup();
vi.clearAllMocks();
storeState = {};
});
describe("PluginsSettingsPage", () => {
it("renders the plugins settings surface unconditionally — plugins ship unflagged", () => {
setStoreState([]);
const { container } = render(<PluginsSettingsPage />);
expect(container.firstChild).not.toBeNull();
});
it("shows an empty state when there are no plugins", () => {
setStoreState([]);
render(<PluginsSettingsPage />);
expect(screen.getByText(/no plugins/i)).toBeTruthy();
});
it("lists plugins with their status, version, and an unsigned badge when unverified", () => {
setStoreState([
activePlugin(),
activePlugin({ id: "unsigned-one", display_name: "Unsigned Plugin", signed: false }),
]);
render(<PluginsSettingsPage />);
expect(screen.getByText(PLUGIN_DISPLAY_NAME)).toBeTruthy();
expect(screen.getByText(/acme-tools.*v1\.0\.0/)).toBeTruthy();
expect(screen.getAllByText(/active/i).length).toBeGreaterThan(0);
expect(screen.getAllByTestId("plugin-unsigned-badge")).toHaveLength(1);
});
it("disables an active plugin: calls the API, unloads the bundle, and updates the store", async () => {
setStoreState([activePlugin()]);
render(<PluginsSettingsPage />);
fireEvent.click(screen.getByRole("button", { name: /disable/i }));
await vi.waitFor(() => expect(disablePluginSpy).toHaveBeenCalledWith(PLUGIN_ID));
expect(unloadPluginSpy).toHaveBeenCalledWith(PLUGIN_ID);
const upsertPlugin = storeState.upsertPlugin as ReturnType<typeof vi.fn>;
expect(upsertPlugin).toHaveBeenCalledWith(
expect.objectContaining({ id: PLUGIN_ID, status: "disabled" }),
);
});
it("enables a disabled plugin: calls the API, updates the store, and reloads the bundle", async () => {
setStoreState([activePlugin({ status: "disabled" })]);
render(<PluginsSettingsPage />);
fireEvent.click(screen.getByRole("button", { name: /enable/i }));
await vi.waitFor(() => expect(enablePluginSpy).toHaveBeenCalledWith(PLUGIN_ID));
const upsertPlugin = storeState.upsertPlugin as ReturnType<typeof vi.fn>;
expect(upsertPlugin).toHaveBeenCalledWith(
expect.objectContaining({ id: PLUGIN_ID, status: "active" }),
);
await vi.waitFor(() =>
expect(loadPluginsSpy).toHaveBeenCalledWith(
[
expect.objectContaining({
id: PLUGIN_ID,
bundleUrl: `/api/plugins/${PLUGIN_ID}/bundle?v=1.0.0`,
}),
],
expect.any(Function),
),
);
});
it("uninstalls a plugin after confirmation: calls the API, unloads the bundle, and removes it from the store", async () => {
setStoreState([activePlugin()]);
render(<PluginsSettingsPage />);
fireEvent.click(screen.getByRole("button", { name: /uninstall/i }));
expect(screen.getByTestId("plugin-uninstall-confirm-popover").textContent).toContain("Acme");
fireEvent.click(screen.getByTestId("plugin-uninstall-confirm"));
await vi.waitFor(() => expect(uninstallPluginSpy).toHaveBeenCalledWith(PLUGIN_ID));
expect(unloadPluginSpy).toHaveBeenCalledWith(PLUGIN_ID);
const removePlugin = storeState.removePlugin as ReturnType<typeof vi.fn>;
expect(removePlugin).toHaveBeenCalledWith(PLUGIN_ID);
});
it("does not uninstall when the confirmation dialog is cancelled", () => {
setStoreState([activePlugin()]);
render(<PluginsSettingsPage />);
fireEvent.click(screen.getByRole("button", { name: /uninstall/i }));
fireEvent.click(screen.getByRole("button", { name: /^cancel$/i }));
expect(uninstallPluginSpy).not.toHaveBeenCalled();
});
it("disables auto-update while an uninstall request is pending", async () => {
let resolveUninstall!: (result: { deleted: boolean }) => void;
uninstallPluginSpy.mockReturnValueOnce(
new Promise((resolve) => {
resolveUninstall = resolve;
}),
);
setStoreState([activePlugin({ auto_update: null })]);
render(<PluginsSettingsPage />);
fireEvent.click(screen.getByRole("button", { name: /uninstall/i }));
fireEvent.click(screen.getByTestId("plugin-uninstall-confirm"));
await vi.waitFor(() => expect(uninstallPluginSpy).toHaveBeenCalledWith(PLUGIN_ID));
const autoUpdate = screen.getByTestId(`plugin-auto-update-${PLUGIN_ID}`);
try {
expect((autoUpdate as HTMLButtonElement).disabled).toBe(true);
} finally {
resolveUninstall({ deleted: true });
const removePlugin = storeState.removePlugin as ReturnType<typeof vi.fn>;
await vi.waitFor(() => expect(removePlugin).toHaveBeenCalledWith(PLUGIN_ID));
}
});
});
describe("PluginsSettingsPage member view", () => {
it("keeps instance-global plugin controls hidden from members", () => {
setStoreState([activePlugin()]);
storeState.auth = { mode: "enabled", user: { role: "member" } };
render(<PluginsSettingsPage />);
expect(screen.getByText(PLUGIN_DISPLAY_NAME)).toBeTruthy();
expect(screen.queryByTestId(SYNC_BUTTON_TESTID)).toBeNull();
expect(screen.queryByTestId(CHECK_UPDATES_BUTTON_TESTID)).toBeNull();
expect(screen.queryByTestId(INSTALL_TRIGGER_TESTID)).toBeNull();
expect(screen.queryByTestId("plugins-auto-update-default")).toBeNull();
expect(screen.queryByRole("button", { name: /disable|uninstall|update/i })).toBeNull();
});
});
describe("PluginsSettingsPage install dialog", () => {
it("shows a spinner while a URL install is pending", async () => {
let resolveInstall!: (result: InstallResult) => void;
const pendingInstall = new Promise<InstallResult>((resolve) => {
resolveInstall = resolve;
});
installPluginFromUrlSpy.mockReturnValueOnce(pendingInstall);
setStoreState([]);
render(<PluginsSettingsPage />);
fireEvent.click(screen.getByTestId(INSTALL_TRIGGER_TESTID));
fireEvent.change(screen.getByTestId(INSTALL_URL_INPUT_TESTID), {
target: { value: NEW_PLUGIN_URL },
});
fireEvent.click(screen.getByTestId(INSTALL_URL_SUBMIT_TESTID));
await vi.waitFor(() => expect(installPluginFromUrlSpy).toHaveBeenCalledWith(NEW_PLUGIN_URL));
const submit = screen.getByTestId(INSTALL_URL_SUBMIT_TESTID);
expect((submit as HTMLButtonElement).disabled).toBe(true);
expect(submit.getAttribute("aria-busy")).toBe("true");
expect(submit.querySelector(".animate-spin")).not.toBeNull();
expect(submit.textContent).toMatch(/installing/i);
resolveInstall({ plugin: installedPlugin() });
await vi.waitFor(() => expect(screen.queryByTestId("install-plugin-dialog")).toBeNull());
});
it("installs a plugin from a URL: calls the API, loads the bundle, and updates the store", async () => {
setStoreState([]);
render(<PluginsSettingsPage />);
fireEvent.click(screen.getByTestId(INSTALL_TRIGGER_TESTID));
fireEvent.change(screen.getByTestId(INSTALL_URL_INPUT_TESTID), {
target: { value: NEW_PLUGIN_URL },
});
fireEvent.click(screen.getByTestId(INSTALL_URL_SUBMIT_TESTID));
await vi.waitFor(() => expect(installPluginFromUrlSpy).toHaveBeenCalledWith(NEW_PLUGIN_URL));
const upsertPlugin = storeState.upsertPlugin as ReturnType<typeof vi.fn>;
expect(upsertPlugin).toHaveBeenCalledWith(expect.objectContaining({ id: NEW_PLUGIN_ID }));
await vi.waitFor(() =>
expect(loadPluginsSpy).toHaveBeenCalledWith(
[
expect.objectContaining({
id: NEW_PLUGIN_ID,
bundleUrl: `/api/plugins/${NEW_PLUGIN_ID}/bundle?v=1.0.0`,
}),
],
expect.any(Function),
),
);
});
it("installs a plugin by uploading a file: calls the API and updates the store", async () => {
setStoreState([]);
const file = new File([new Uint8Array([1, 2, 3])], UPLOAD_FILENAME, {
type: "application/gzip",
});
render(<PluginsSettingsPage />);
fireEvent.click(screen.getByTestId(INSTALL_TRIGGER_TESTID));
// Radix TabsTrigger switches tabs on mousedown, not click (see
// @radix-ui/react-tabs) — fireEvent.click alone never fires it.
fireEvent.mouseDown(screen.getByTestId("install-plugin-tab-upload"));
fireEvent.change(screen.getByTestId("install-plugin-file-input"), {
target: { files: [file] },
});
fireEvent.click(screen.getByTestId("install-plugin-upload-submit"));
await vi.waitFor(() => expect(installPluginUploadSpy).toHaveBeenCalledWith(file));
const upsertPlugin = storeState.upsertPlugin as ReturnType<typeof vi.fn>;
expect(upsertPlugin).toHaveBeenCalledWith(expect.objectContaining({ id: NEW_PLUGIN_ID }));
});
});
describe("PluginsSettingsPage install dialog state reset", () => {
it("clears the selected file after a successful upload install so reopening starts empty", async () => {
setStoreState([]);
const file = new File([new Uint8Array([1, 2, 3])], UPLOAD_FILENAME, {
type: "application/gzip",
});
render(<PluginsSettingsPage />);
fireEvent.click(screen.getByTestId(INSTALL_TRIGGER_TESTID));
fireEvent.mouseDown(screen.getByTestId("install-plugin-tab-upload"));
fireEvent.change(screen.getByTestId("install-plugin-file-input"), {
target: { files: [file] },
});
expect(screen.getByTestId("install-plugin-dropzone").textContent).toContain(UPLOAD_FILENAME);
fireEvent.click(screen.getByTestId("install-plugin-upload-submit"));
// afterInstall closes the dialog by flipping the controlled `open` prop
// directly (not via onOpenChange), so the lifted file state must still be
// reset — otherwise the stale file leaks into the next open.
await vi.waitFor(() => expect(screen.queryByTestId("install-plugin-dialog")).toBeNull());
fireEvent.click(screen.getByTestId(INSTALL_TRIGGER_TESTID));
fireEvent.mouseDown(screen.getByTestId("install-plugin-tab-upload"));
expect(screen.getByTestId("install-plugin-dropzone").textContent).not.toContain(
UPLOAD_FILENAME,
);
expect((screen.getByTestId("install-plugin-upload-submit") as HTMLButtonElement).disabled).toBe(
true,
);
});
it("shows a warning toast (not a bare success toast) when the package installed but failed to start", async () => {
installPluginFromUrlSpy.mockResolvedValueOnce({
plugin: installedPlugin({ status: "error" }),
warning: "plugin installed but failed to start: handshake timed out",
});
setStoreState([]);
render(<PluginsSettingsPage />);
fireEvent.click(screen.getByTestId(INSTALL_TRIGGER_TESTID));
fireEvent.change(screen.getByTestId(INSTALL_URL_INPUT_TESTID), {
target: { value: NEW_PLUGIN_URL },
});
fireEvent.click(screen.getByTestId(INSTALL_URL_SUBMIT_TESTID));
await vi.waitFor(() =>
expect(toast.warning).toHaveBeenCalledWith(
"plugin installed but failed to start: handshake timed out",
),
);
expect(toast.success).not.toHaveBeenCalled();
const upsertPlugin = storeState.upsertPlugin as ReturnType<typeof vi.fn>;
expect(upsertPlugin).toHaveBeenCalledWith(
expect.objectContaining({ id: NEW_PLUGIN_ID, status: "error" }),
);
});
it("shows the backend's error message inline when install fails", async () => {
installPluginFromUrlSpy.mockRejectedValueOnce(
new Error("bad checksum for server/plugin-linux-amd64"),
);
setStoreState([]);
render(<PluginsSettingsPage />);
fireEvent.click(screen.getByTestId(INSTALL_TRIGGER_TESTID));
fireEvent.change(screen.getByTestId(INSTALL_URL_INPUT_TESTID), {
target: { value: "https://example.test/bad.tar.gz" },
});
fireEvent.click(screen.getByTestId(INSTALL_URL_SUBMIT_TESTID));
await vi.waitFor(() =>
expect(screen.getByTestId("install-plugin-error").textContent).toMatch(/bad checksum/),
);
});
});
describe("PluginsSettingsPage sync button", () => {
it("syncs plugins: calls the API, refreshes the list, and toasts a summary", async () => {
setStoreState([]);
syncPluginsSpy.mockResolvedValueOnce(emptySyncResult({ added: ["sideloaded-plugin"] }));
const callsBeforeClick = listPluginsSpy.mock.calls.length;
render(<PluginsSettingsPage />);
fireEvent.click(screen.getByTestId(SYNC_BUTTON_TESTID));
await vi.waitFor(() => expect(syncPluginsSpy).toHaveBeenCalled());
await vi.waitFor(() =>
expect(listPluginsSpy.mock.calls.length).toBeGreaterThan(callsBeforeClick),
);
const setPlugins = storeState.setPlugins as ReturnType<typeof vi.fn>;
await vi.waitFor(() => expect(setPlugins).toHaveBeenCalledWith([]));
await vi.waitFor(() => expect(toast.success).toHaveBeenCalledWith("Sync: 1 sideloaded"));
expect(refreshMarketplaceSpy).not.toHaveBeenCalled();
});
it("toasts 'Everything up to date' when the sync finds nothing to do", async () => {
setStoreState([]);
syncPluginsSpy.mockResolvedValueOnce(emptySyncResult());
render(<PluginsSettingsPage />);
fireEvent.click(screen.getByTestId(SYNC_BUTTON_TESTID));
await vi.waitFor(() => expect(toast.success).toHaveBeenCalledWith("Everything up to date"));
});
it("shows sync errors inline", async () => {
setStoreState([]);
syncPluginsSpy.mockResolvedValueOnce(
emptySyncResult({
errors: [{ path: "/plugins/junk.tar.gz", reason: "invalid gzip stream" }],
}),
);
render(<PluginsSettingsPage />);
expect(screen.queryByTestId("plugins-sync-errors")).toBeNull();
fireEvent.click(screen.getByTestId(SYNC_BUTTON_TESTID));
await vi.waitFor(() =>
expect(screen.getByTestId("plugins-sync-errors").textContent).toMatch(/invalid gzip stream/),
);
});
it("toasts an error and does not refresh the list when the sync call fails", async () => {
setStoreState([]);
syncPluginsSpy.mockRejectedValueOnce(new Error("backend unreachable"));
render(<PluginsSettingsPage />);
// Let the mount-triggered usePlugins() load settle before capturing the
// baseline call count, so it only reflects the click below.
await vi.waitFor(() => expect(listPluginsSpy).toHaveBeenCalled());
const callsBeforeClick = listPluginsSpy.mock.calls.length;
fireEvent.click(screen.getByTestId(SYNC_BUTTON_TESTID));
await vi.waitFor(() => expect(toast.error).toHaveBeenCalledWith("backend unreachable"));
expect(listPluginsSpy.mock.calls.length).toBe(callsBeforeClick);
});
});
describe("PluginsSettingsPage marketplace updates", () => {
it("checks for updates without a filesystem sync and refreshes the row in place", async () => {
setStoreState([activePlugin()]);
getMarketplaceCatalogSpy.mockResolvedValueOnce({ plugins: [], sources: [] });
getMarketplaceCatalogSpy.mockResolvedValueOnce({ plugins: [catalogEntry()], sources: [] });
render(<PluginsSettingsPage />);
await vi.waitFor(() => expect(getMarketplaceCatalogSpy).toHaveBeenCalledTimes(1));
fireEvent.click(screen.getByTestId(CHECK_UPDATES_BUTTON_TESTID));
await vi.waitFor(() =>
expect(screen.getByTestId(`plugin-latest-version-${PLUGIN_ID}`).textContent).toContain(
"2.0.0",
),
);
expect(screen.queryByTestId(`plugin-update-available-${PLUGIN_ID}`)).toBeNull();
expect(screen.getByTestId(`plugin-update-${PLUGIN_ID}`).getAttribute("data-variant")).toBe(
"default",
);
const refreshOrder = refreshMarketplaceSpy.mock.invocationCallOrder[0];
const catalogOrder = getMarketplaceCatalogSpy.mock.invocationCallOrder[1];
expect(refreshOrder).toBeLessThan(catalogOrder);
expect(syncPluginsSpy).not.toHaveBeenCalled();
});
it("shows a checking indicator while a triggered check is in flight, then a last-checked timestamp", async () => {
setStoreState([]);
render(<PluginsSettingsPage />);
await vi.waitFor(() => expect(screen.getByTestId("plugins-updates-last-checked")).toBeTruthy());
let resolveCatalog!: (v: { plugins: unknown[]; sources: unknown[] }) => void;
getMarketplaceCatalogSpy.mockReturnValueOnce(
new Promise((resolve) => {
resolveCatalog = resolve;
}),
);
fireEvent.click(screen.getByTestId(CHECK_UPDATES_BUTTON_TESTID));
await vi.waitFor(() => expect(screen.getByTestId("plugins-updates-checking")).toBeTruthy());
resolveCatalog({ plugins: [], sources: [] });
await vi.waitFor(() => expect(screen.queryByTestId("plugins-updates-checking")).toBeNull());
expect(screen.getByTestId("plugins-updates-last-checked")).toBeTruthy();
});
it("contains a marketplace check failure: the inline error renders while the plugin list and sync summary stay intact", async () => {
setStoreState([activePlugin()]);
getMarketplaceCatalogSpy.mockRejectedValue(new Error("marketplace is unavailable"));
render(<PluginsSettingsPage />);
fireEvent.click(screen.getByTestId(CHECK_UPDATES_BUTTON_TESTID));
await vi.waitFor(() =>
expect(screen.getByTestId("plugins-update-check-error").textContent).toContain(
"marketplace is unavailable",
),
);
expect(screen.getByText(PLUGIN_DISPLAY_NAME)).toBeTruthy();
expect(syncPluginsSpy).not.toHaveBeenCalled();
});
});
describe("PluginsSettingsPage marketplace update lifecycle", () => {
it("reloads the Installed catalog after a successful Browse install", async () => {
setStoreState([]);
getMarketplaceCatalogSpy.mockResolvedValue({
plugins: [
catalogEntry({
id: NEW_PLUGIN_ID,
name: "New Plugin",
version: "1.0.0",
install_state: "available",
installed_version: undefined,
package_url: NEW_PLUGIN_URL,
}),
],
sources: [
{
id: "official",
name: "Official",
url: "https://example.test",
enabled: true,
builtin: true,
healthy: true,
},
],
});
render(<PluginsSettingsPage />);
fireEvent.mouseDown(screen.getByTestId("plugins-tab-browse"));
await vi.waitFor(() =>
expect(screen.getByTestId(`marketplace-install-${NEW_PLUGIN_ID}`)).toBeTruthy(),
);
const callsBeforeInstall = getMarketplaceCatalogSpy.mock.calls.length;
fireEvent.click(screen.getByTestId(`marketplace-install-${NEW_PLUGIN_ID}`));
await vi.waitFor(() => expect(installPluginFromUrlSpy).toHaveBeenCalledWith(NEW_PLUGIN_URL));
await vi.waitFor(() =>
expect(getMarketplaceCatalogSpy.mock.calls.length).toBeGreaterThanOrEqual(
callsBeforeInstall + 2,
),
);
});
it("after a successful manual update, the version updates and the update button disappears", async () => {
setStoreState([activePlugin()]);
getMarketplaceCatalogSpy.mockResolvedValueOnce({ plugins: [catalogEntry()], sources: [] });
installPluginFromUrlSpy.mockResolvedValueOnce({ plugin: activePlugin({ version: "2.0.0" }) });
getMarketplaceCatalogSpy.mockResolvedValueOnce({
plugins: [catalogEntry({ install_state: "installed", installed_version: "2.0.0" })],
sources: [],
});
render(<PluginsSettingsPage />);
await vi.waitFor(() => expect(screen.getByTestId(`plugin-update-${PLUGIN_ID}`)).toBeTruthy());
fireEvent.click(screen.getByTestId(`plugin-update-${PLUGIN_ID}`));
await vi.waitFor(() =>
expect(installPluginFromUrlSpy).toHaveBeenCalledWith(
"https://example.test/acme-tools-2.0.0.tar.gz",
),
);
await vi.waitFor(() => expect(screen.queryByTestId(`plugin-update-${PLUGIN_ID}`)).toBeNull());
expect(toast.success).toHaveBeenCalledWith(expect.stringContaining(PLUGIN_DISPLAY_NAME));
});
it("shows an inline error on a failed manual update and keeps the Update button clickable", async () => {
setStoreState([activePlugin()]);
getMarketplaceCatalogSpy.mockResolvedValue({ plugins: [catalogEntry()], sources: [] });
installPluginFromUrlSpy.mockRejectedValueOnce(new Error("bad checksum"));
render(<PluginsSettingsPage />);
await vi.waitFor(() => expect(screen.getByTestId(`plugin-update-${PLUGIN_ID}`)).toBeTruthy());
fireEvent.click(screen.getByTestId(`plugin-update-${PLUGIN_ID}`));
await vi.waitFor(() =>
expect(screen.getByTestId(`plugin-update-error-${PLUGIN_ID}`).textContent).toContain(
"bad checksum",
),
);
const button = screen.getByTestId(`plugin-update-${PLUGIN_ID}`) as HTMLButtonElement;
expect(button.disabled).toBe(false);
});
});