diff --git a/docs/buzz-help.md b/docs/buzz-help.md index 5af9fee20e..c1d0300fee 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -1842,6 +1842,8 @@ tab, asks **Discard changes?** first; **Keep editing** keeps them. sources at startup and once per hour while the app is visible. Checks do not install or reload plugins. A notice offers **Update and reload**, or **Review permissions** when access increases; either opens the update review. + While a request waits for a check or another review, it shows **Preparing update…**; + **Later** cancels that pending request. Other Update actions wait until it finishes. Even when access is unchanged, choose **Update** in that review to install and reload the candidate. Click the notice body to open that plugin’s update checkbox in Manage plugins. diff --git a/src/app/PluginUpdates.test.tsx b/src/app/PluginUpdates.test.tsx index 98f12f89e9..c7915f8319 100644 --- a/src/app/PluginUpdates.test.tsx +++ b/src/app/PluginUpdates.test.tsx @@ -10,6 +10,8 @@ import { within, } from "@testing-library/react"; import { afterEach, expect, it, vi } from "vitest"; +import userEvent from "@testing-library/user-event"; +import "../../tests/sonner-dom"; import type { ReactNode } from "react"; import { Context as CordisContext } from "@deepseek-ai/cordis"; import { @@ -114,31 +116,44 @@ function fixture() { }; const installRequests = createPluginInstallRequests(); const relay = { snapshot: () => ({ session: {} }) } as AppServices["relay"]; - const mount = (plugins = manager) => - render( - - - - - screen.getByRole("button", { name: "View Notes details" }) - } - /> - - Profile - - - - - - , - ); + const profileTrigger: { current: HTMLButtonElement | null } = { + current: null, + }; + const tree = (plugins = manager) => ( + + + + + screen.getByRole("button", { name: "View Notes details" }) + } + /> + + { + profileTrigger.current = node; + }} + > + Profile + + + profileTrigger.current} + /> + + + + + ); + const mount = (plugins = manager) => render(tree(plugins)); return { source, candidate, @@ -151,6 +166,7 @@ function fixture() { navigation, installRequests, manager, + tree, state: () => snapshot, emit(next: Partial>) { snapshot = { ...snapshot, ...next }; @@ -623,7 +639,702 @@ it("retains an accepted update review when the Marketplace consumer unmounts", a ); }); -it("refreshes instead of opening a stale retained update", async () => { +it.each([ + [ + "personal Git package path", + "https://github.com/example-org/personal-plugins.git", + "plugins/notes", + ], + [ + "ordinary Git host package path", + "https://example.org/example-org/plugins.git", + "extensions/notes", + ], +])( + "opens a fresh review from one click on a stale update (%s)", + async (_, repository, path) => { + const f = fixture(); + f.source.repository = repository; + f.source.path = path; + f.discovered.source = repository; + f.candidate.path = path; + f.fresh.source = repository; + f.freshCandidate.path = path; + f.mount(); + const update = await screen.findByRole("button", { + name: "Update and reload", + }); + await waitFor(() => + expect(f.installRequests.updates?.getSnapshot().status).toBe("fresh"), + ); + + f.plugin.revision = "changed before review"; + fireEvent.click(update); + + await waitFor(() => expect(f.imports.checkGit).toHaveBeenCalledTimes(2)); + expect(f.imports.checkGit).toHaveBeenLastCalledWith( + repository, + "main", + undefined, + { commit: undefined, path }, + ); + const confirm = await screen.findByRole("button", { + name: /^Update$/, + }); + const review = confirm.closest('[role="dialog"]'); + if (!review) throw new Error("Expected the update review dialog"); + expect(review).toHaveAccessibleName("Update Notes"); + expect(confirm).toBeEnabled(); + expect(f.installImport).not.toHaveBeenCalled(); + }, +); + +it.each([ + [ + "personal Git package path", + "https://github.com/example-org/personal-plugins.git", + "plugins/notes", + ], + [ + "ordinary Git host package path", + "https://example.org/example-org/plugins.git", + "extensions/notes", + ], +])( + "preserves one update click while an update check is already running (%s)", + async (_, repository, path) => { + const f = fixture(); + f.source.repository = repository; + f.source.path = path; + f.discovered.source = repository; + f.candidate.path = path; + f.fresh.source = repository; + f.freshCandidate.path = path; + f.mount(); + const update = await screen.findByRole("button", { + name: "Update and reload", + }); + await waitFor(() => + expect(f.installRequests.updates?.getSnapshot().status).toBe("fresh"), + ); + const capability = f.installRequests.updates; + const staleToken = capability?.getSnapshot().candidates[0]?.token; + if (!capability || !staleToken) + throw new Error("Expected a fresh update token"); + f.plugin.revision = "changed while refresh runs"; + + let releaseCheck!: () => void; + f.imports.checkGit.mockImplementationOnce( + () => + new Promise((resolve) => { + releaseCheck = () => resolve(f.discovered); + }), + ); + const refresh = capability.refresh(); + try { + await waitFor(() => { + expect(f.imports.checkGit).toHaveBeenCalledTimes(2); + expect(releaseCheck).toBeTypeOf("function"); + }); + expect(f.imports.checkGit).toHaveBeenLastCalledWith( + repository, + "main", + undefined, + { commit: undefined, path }, + ); + + fireEvent.click(update); + expect(f.installImport).not.toHaveBeenCalled(); + } finally { + await act(async () => { + releaseCheck(); + await refresh; + }); + } + + expect(f.imports.checkGit).toHaveBeenCalledTimes(2); + expect(capability.getSnapshot()).toMatchObject({ + status: "fresh", + candidates: [ + { + id: "example.notes", + installedRevision: "changed while refresh runs", + candidateRevision: "new", + }, + ], + }); + expect(capability.getSnapshot().candidates[0]?.token).not.toBe(staleToken); + const confirm = await screen.findByRole("button", { + name: /^Update$/, + }); + const review = confirm.closest('[role="dialog"]'); + if (!review) throw new Error("Expected the update review dialog"); + expect(review).toHaveAccessibleName("Update Notes"); + expect(confirm).toBeEnabled(); + expect(f.plugin.enabled).toBe(true); + expect(f.plugin.updateChecks).toBeUndefined(); + expect(f.plugin.updateSource).toBe(f.source); + expect(f.manager.change).not.toHaveBeenCalled(); + expect(f.navigation.open).not.toHaveBeenCalled(); + expect(f.installImport).not.toHaveBeenCalled(); + }, +); + +it("keeps one notification click queued while another review owns the lease", async () => { + const user = userEvent.setup(); + const f = fixture(); + const releaseReview = f.installRequests.tryHoldReview(); + if (!releaseReview) throw new Error("Expected to hold the review lease"); + f.mount(); + const update = await screen.findByRole("button", { + name: "Update and reload", + }); + + try { + update.focus(); + await user.keyboard("{Enter}"); + expect( + await screen.findByRole("button", { name: "Preparing update…" }), + ).toHaveAttribute("aria-disabled", "true"); + expect(update).toHaveFocus(); + await user.keyboard("{Enter}"); + expect(screen.getByRole("button", { name: "Later" })).toBeVisible(); + expect(screen.queryByRole("button", { name: /^Update$/ })).toBeNull(); + await user.click(screen.getByRole("button", { name: "Profile" })); + await user.click(await screen.findByRole("menuitem", { name: /Plugins/ })); + const menuUpdate = await screen.findByRole("menuitem", { + name: "Update Notes", + }); + expect(menuUpdate).toHaveAttribute("aria-disabled", "true"); + expect( + screen.getByRole("menuitem", { name: "Manage plugins" }), + ).not.toHaveAttribute("aria-disabled", "true"); + await user.keyboard("{Escape}{Escape}"); + expect(screen.getByRole("button", { name: "Profile" })).toHaveFocus(); + expect(f.installImport).not.toHaveBeenCalled(); + } finally { + act(() => releaseReview()); + } + + expect(await screen.findByRole("button", { name: /^Update$/ })).toBeVisible(); + expect(screen.getAllByRole("dialog", { name: "Update Notes" })).toHaveLength( + 1, + ); + expect(f.imports.git).toHaveBeenCalledOnce(); + expect(f.installImport).not.toHaveBeenCalled(); + const review = screen.getByRole("dialog", { name: "Update Notes" }); + await user.click(within(review).getByRole("button", { name: "Close" })); + await waitFor(() => + expect(screen.getByRole("button", { name: "Profile" })).toHaveFocus(), + ); +}); + +it.each(["queued", "refreshing"])( + "opens plugin settings if a %s notification loses its update store", + async (phase) => { + const f = fixture(); + const replacement = fixture(); + const releaseReview = f.installRequests.tryHoldReview(); + if (!releaseReview) throw new Error("Expected to hold the review lease"); + const view = f.mount(); + const update = await screen.findByRole("button", { + name: "Update and reload", + }); + const capability = f.installRequests.updates; + if (!capability) throw new Error("Expected an update capability"); + let releaseCheck: (() => void) | undefined; + let refresh: ReturnType | undefined; + if (phase === "refreshing") { + f.imports.checkGit.mockImplementationOnce( + () => + new Promise((resolve) => { + releaseCheck = () => resolve(f.discovered); + }), + ); + refresh = capability.refresh(); + await waitFor(() => expect(releaseCheck).toBeTypeOf("function")); + } + + try { + fireEvent.click(update); + await screen.findByRole("button", { name: "Preparing update…" }); + view.rerender(f.tree(replacement.manager)); + + await waitFor(() => + expect(f.navigation.open).toHaveBeenCalledExactlyOnceWith({ + version: 1, + kind: "settings", + section: "plugins", + pluginId: "example.notes", + }), + ); + expect( + await screen.findByRole("button", { name: "Update and reload" }), + ).toBeEnabled(); + expect(screen.queryByRole("button", { name: /^Update$/ })).toBeNull(); + } finally { + await act(async () => { + releaseReview(); + releaseCheck?.(); + await refresh; + }); + } + expect(f.navigation.open).toHaveBeenCalledOnce(); + expect(f.imports.git).not.toHaveBeenCalled(); + expect(replacement.imports.git).not.toHaveBeenCalled(); + expect(f.installImport).not.toHaveBeenCalled(); + expect(replacement.installImport).not.toHaveBeenCalled(); + }, +); + +it("does not navigate when a pending notification refresh finishes after unmount", async () => { + const f = fixture(); + const view = f.mount(); + const update = await screen.findByRole("button", { + name: "Update and reload", + }); + const capability = f.installRequests.updates; + if (!capability) throw new Error("Expected an update capability"); + let releaseCheck!: () => void; + f.imports.checkGit.mockImplementationOnce( + () => + new Promise((resolve) => { + releaseCheck = () => resolve(f.discovered); + }), + ); + const refresh = capability.refresh(); + try { + await waitFor(() => expect(releaseCheck).toBeTypeOf("function")); + fireEvent.click(update); + await screen.findByRole("button", { name: "Preparing update…" }); + view.unmount(); + } finally { + await act(async () => { + releaseCheck(); + await refresh; + }); + } + expect(f.navigation.open).not.toHaveBeenCalled(); + expect(f.imports.git).not.toHaveBeenCalled(); + expect(f.installImport).not.toHaveBeenCalled(); +}); + +it("keeps a menu-started update cancellable after Later and returns focus to Profile", async () => { + const user = userEvent.setup(); + const f = fixture(); + const releaseReview = f.installRequests.tryHoldReview(); + if (!releaseReview) throw new Error("Expected to hold the review lease"); + f.mount(); + await screen.findByRole("button", { name: "Update and reload" }); + await user.click(screen.getByRole("button", { name: "Later" })); + const profile = screen.getByRole("button", { name: "Profile" }); + + try { + profile.focus(); + await user.keyboard("{ArrowDown}"); + const plugins = await screen.findByRole("menuitem", { name: /Plugins/ }); + plugins.focus(); + await user.keyboard("{ArrowRight}"); + const update = await screen.findByRole("menuitem", { + name: "Update Notes", + }); + update.focus(); + await user.keyboard("{Enter}"); + + expect( + await screen.findByRole("button", { name: "Preparing update…" }), + ).toHaveAttribute("aria-disabled", "true"); + expect(screen.getByRole("button", { name: "Later" })).toBeVisible(); + expect(f.imports.git).not.toHaveBeenCalled(); + expect(f.installImport).not.toHaveBeenCalled(); + } finally { + act(() => releaseReview()); + } + + const review = await screen.findByRole("dialog", { name: "Update Notes" }); + expect( + within(review).getByRole("button", { name: /^Update$/ }), + ).toBeEnabled(); + expect(screen.getAllByRole("dialog", { name: "Update Notes" })).toHaveLength( + 1, + ); + expect(f.imports.git).toHaveBeenCalledOnce(); + await user.click(within(review).getByRole("button", { name: "Close" })); + await waitFor(() => expect(profile).toHaveFocus()); + expect(f.installImport).not.toHaveBeenCalled(); +}); + +it("cancels a queued notification action and restores keyboard updating in Plugins", async () => { + const user = userEvent.setup(); + const f = fixture(); + const releaseReview = f.installRequests.tryHoldReview(); + if (!releaseReview) throw new Error("Expected to hold the review lease"); + const registerUpdates = vi.spyOn(f.installRequests, "registerUpdates"); + f.mount(); + const update = await screen.findByRole("button", { + name: "Update and reload", + }); + const capability = registerUpdates.mock.calls[0]?.[0]?.capability; + if (!capability) throw new Error("Expected an update capability"); + const queueUpdates = vi.spyOn(capability, "queueUpdates"); + + try { + fireEvent.click(update); + await screen.findByRole("button", { name: "Preparing update…" }); + const queued = queueUpdates.mock.results[0]?.value; + if (!queued) + throw new Error("Expected the host to accept the notification queue"); + fireEvent.click(screen.getByRole("button", { name: "Later" })); + await waitFor(() => + expect(capability.getQueue(queued.id)?.status).toBe("cancelled"), + ); + } finally { + act(() => releaseReview()); + } + + expect(screen.queryByRole("dialog", { name: "Update Notes" })).toBeNull(); + expect(f.navigation.open).not.toHaveBeenCalled(); + expect(f.installImport).not.toHaveBeenCalled(); + screen.getByRole("button", { name: "Profile" }).focus(); + await user.keyboard("{ArrowDown}"); + const plugins = await screen.findByRole("menuitem", { name: /Plugins/ }); + plugins.focus(); + await user.keyboard("{ArrowRight}"); + const menuUpdate = await screen.findByRole("menuitem", { + name: "Update Notes", + }); + expect(menuUpdate).not.toHaveAttribute("aria-disabled", "true"); + menuUpdate.focus(); + await user.keyboard("{Enter}"); + expect( + await screen.findByRole("dialog", { name: "Update Notes" }), + ).toBeVisible(); + expect(f.imports.git).toHaveBeenCalledOnce(); + expect(f.installImport).not.toHaveBeenCalled(); +}); + +it("opens plugin settings when the update queue has reached its capacity", async () => { + const f = fixture(); + f.mount(); + const update = await screen.findByRole("button", { + name: "Update and reload", + }); + const capability = f.installRequests.updates; + const token = capability?.getSnapshot().candidates[0]?.token; + if (!capability || !token) throw new Error("Expected a fresh update token"); + const releaseReview = f.installRequests.tryHoldReview(); + if (!releaseReview) throw new Error("Expected to hold the review lease"); + const queues: { id: string }[] = []; + + try { + act(() => { + for (let index = 0; index < 50; index++) { + const queue = capability.queueUpdates([token]); + if (!queue) + throw new Error("Expected the host to accept a queued update"); + queues.push(queue); + } + }); + expect(capability.getSnapshot().status).toBe("fresh"); + expect(capability.getSnapshot().candidates[0]?.token).toBe(token); + + fireEvent.click(update); + + await waitFor(() => + expect(f.navigation.open).toHaveBeenCalledWith({ + version: 1, + kind: "settings", + section: "plugins", + pluginId: "example.notes", + }), + ); + await waitFor(() => expect(update).toBeEnabled()); + expect(screen.queryByRole("button", { name: /^Update$/ })).toBeNull(); + expect(f.installImport).not.toHaveBeenCalled(); + } finally { + act(() => { + for (const queue of queues) capability.cancelQueue(queue.id); + releaseReview(); + }); + } +}); + +it("opens plugin settings if a queued notification update becomes stale", async () => { + const f = fixture(); + const releaseReview = f.installRequests.tryHoldReview(); + if (!releaseReview) throw new Error("Expected to hold the review lease"); + f.mount(); + const update = await screen.findByRole("button", { + name: "Update and reload", + }); + + try { + fireEvent.click(update); + await screen.findByRole("button", { name: "Preparing update…" }); + f.plugin.revision = "changed while queued"; + } finally { + act(() => releaseReview()); + } + + await waitFor(() => + expect(f.navigation.open).toHaveBeenCalledWith({ + version: 1, + kind: "settings", + section: "plugins", + pluginId: "example.notes", + }), + ); + expect(f.installImport).not.toHaveBeenCalled(); +}); + +it.each(["Later", "Dismiss plugin update notice"])( + "does not open a review after %s cancels a pending notification click", + async (dismissLabel) => { + const f = fixture(); + f.mount(); + const update = await screen.findByRole("button", { + name: "Update and reload", + }); + const capability = f.installRequests.updates; + if (!capability) throw new Error("Expected an update capability"); + + let releaseCheck!: () => void; + f.imports.checkGit.mockImplementationOnce( + () => + new Promise((resolve) => { + releaseCheck = () => resolve(f.discovered); + }), + ); + const refresh = capability.refresh(); + await waitFor(() => expect(f.imports.checkGit).toHaveBeenCalledTimes(2)); + fireEvent.click(update); + fireEvent.click(screen.getByRole("button", { name: dismissLabel })); + + await act(async () => { + releaseCheck(); + await refresh; + }); + + await waitFor(() => + expect(screen.queryByRole("dialog", { name: "Update Notes" })).toBeNull(), + ); + expect(f.navigation.open).not.toHaveBeenCalled(); + expect(f.installImport).not.toHaveBeenCalled(); + }, +); + +it.each(["error", "up to date"] as const)( + "keeps a pending notice cancellable when its candidate disappears (%s) before a later check finishes", + async (outcome) => { + const f = fixture(); + const configuration = f.state().configuration; + if (configuration.status !== "ready") throw new Error("Expected catalog"); + const otherSource = { + repository: "https://example.com/other.git", + reference: "main", + path: "other", + }; + const other: PluginInfo = { + ...f.plugin, + manifest: { ...f.plugin.manifest, id: "example.other", name: "Other" }, + updateSource: otherSource, + }; + const otherDiscovered: ImportPreview = { + token: "other-metadata", + source: otherSource.repository, + commit: "b".repeat(40), + candidates: [ + { + path: otherSource.path, + manifest: other.manifest, + revision: other.revision, + publisher: null, + }, + ], + warnings: [], + }; + f.emit({ + configuration: { + ...configuration, + catalog: { ...configuration.catalog, plugins: [f.plugin, other] }, + }, + }); + f.imports.checkGit + .mockResolvedValueOnce(f.discovered) + .mockResolvedValueOnce(otherDiscovered); + f.mount(); + const update = await screen.findByRole("button", { + name: "Update and reload", + }); + const capability = f.installRequests.updates; + if (!capability) throw new Error("Expected an update capability"); + + let releaseNotes!: () => void; + let releaseOther!: () => void; + f.imports.checkGit + .mockImplementationOnce( + () => + new Promise((resolve, reject) => { + releaseNotes = () => + outcome === "error" + ? reject(new Error("Notes repository failed")) + : resolve({ + ...f.discovered, + candidates: [ + { ...f.candidate, revision: f.plugin.revision }, + ], + }); + }), + ) + .mockImplementationOnce( + () => + new Promise((resolve) => { + releaseOther = () => resolve(otherDiscovered); + }), + ); + + const refresh = capability.refresh(); + try { + await waitFor(() => expect(releaseNotes).toBeTypeOf("function")); + fireEvent.click(update); + expect( + await screen.findByRole("button", { name: "Preparing update…" }), + ).toHaveAttribute("aria-disabled", "true"); + + await act(async () => { + releaseNotes(); + }); + await waitFor(() => expect(releaseOther).toBeTypeOf("function")); + await waitFor(() => + expect(capability.getSnapshot().candidates).toEqual([]), + ); + expect( + screen.getByRole("button", { name: "Preparing update…" }), + ).toBeVisible(); + expect(screen.getByRole("button", { name: "Later" })).toBeVisible(); + expect( + screen.getByRole("button", { name: "Dismiss plugin update notice" }), + ).toBeVisible(); + + fireEvent.click( + screen.getByRole("button", { + name: outcome === "error" ? "Later" : "Dismiss plugin update notice", + }), + ); + } finally { + await act(async () => { + releaseOther?.(); + await refresh; + }); + } + + await waitFor(() => + expect(screen.queryByRole("dialog", { name: "Update Notes" })).toBeNull(), + ); + expect(f.navigation.open).not.toHaveBeenCalled(); + expect(f.installImport).not.toHaveBeenCalled(); + }, +); + +it("keeps Profile focus tied to its own request when another queued review runs first", async () => { + const user = userEvent.setup(); + const f = fixture(); + const configuration = f.state().configuration; + if (configuration.status !== "ready") throw new Error("Expected catalog"); + const otherSource = { + repository: "https://example.com/other.git", + reference: "main", + path: "other", + }; + const other: PluginInfo = { + ...f.plugin, + manifest: { ...f.plugin.manifest, id: "example.other", name: "Other" }, + updateSource: otherSource, + }; + const otherCandidate = { + path: otherSource.path, + manifest: other.manifest, + revision: "new-other", + publisher: null as string | null, + }; + const otherDiscovered: ImportPreview = { + token: "other-metadata", + source: otherSource.repository, + commit: "b".repeat(40), + candidates: [otherCandidate], + warnings: [], + }; + const otherFresh: ImportPreview = { + ...otherDiscovered, + token: "other-immutable-preview", + candidates: [{ ...otherCandidate }], + }; + f.emit({ + configuration: { + ...configuration, + catalog: { ...configuration.catalog, plugins: [f.plugin, other] }, + }, + }); + f.imports.checkGit + .mockResolvedValueOnce(f.discovered) + .mockResolvedValueOnce(otherDiscovered); + f.imports.git + .mockResolvedValueOnce(otherFresh) + .mockResolvedValueOnce(f.fresh); + const releaseReview = f.installRequests.tryHoldReview(); + if (!releaseReview) throw new Error("Expected to hold the review lease"); + f.mount(); + await waitFor(() => + expect(f.installRequests.updates?.getSnapshot().candidates).toHaveLength(2), + ); + const market = f.installRequests.updatesFor("example.market"); + const otherToken = market + ?.getSnapshot() + .candidates.find((c) => c.id === "example.other")?.token; + if (!market || !otherToken) + throw new Error("Expected a fresh token for Other"); + + const profile = screen.getByRole("button", { name: "Profile" }); + const details = screen.getByRole("button", { name: "View Notes details" }); + try { + act(() => { + if (!market.queueUpdates([otherToken])) + throw new Error("Expected Other review to queue"); + }); + + profile.focus(); + await user.keyboard("{ArrowDown}"); + const plugins = await screen.findByRole("menuitem", { name: /Plugins/ }); + plugins.focus(); + await user.keyboard("{ArrowRight}"); + const menuUpdate = await screen.findByRole("menuitem", { + name: "Update Notes", + }); + menuUpdate.focus(); + await user.keyboard("{Enter}"); + expect( + await screen.findByRole("button", { name: "Preparing update…" }), + ).toHaveAttribute("aria-disabled", "true"); + + details.focus(); + expect(details).toHaveFocus(); + } finally { + act(() => releaseReview()); + } + + const otherDialog = await screen.findByRole("dialog", { + name: "Update Other", + }); + await user.click(within(otherDialog).getByRole("button", { name: "Close" })); + const notesDialog = await screen.findByRole("dialog", { + name: "Update Notes", + }); + await user.click(within(notesDialog).getByRole("button", { name: "Close" })); + await waitFor(() => expect(profile).toHaveFocus()); + expect(f.installImport).not.toHaveBeenCalled(); +}); + +it("reviews a newer candidate discovered during a stale notice refresh without auto-installing", async () => { const f = fixture(); f.mount(); const update = await screen.findByRole("button", { @@ -634,18 +1345,124 @@ it("refreshes instead of opening a stale retained update", async () => { ); f.plugin.revision = "changed before review"; + const newerManifest = { ...f.plugin.manifest, host: { files: true } }; + const newerCandidate = { + ...f.candidate, + manifest: newerManifest, + revision: "v2-during-refresh", + }; + f.imports.checkGit.mockResolvedValueOnce({ + ...f.discovered, + candidates: [newerCandidate], + }); + f.imports.git.mockResolvedValueOnce({ + ...f.fresh, + candidates: [{ ...newerCandidate }], + }); + fireEvent.click(update); - await waitFor(() => expect(f.imports.checkGit).toHaveBeenCalledTimes(2)); - expect(screen.queryByRole("button", { name: "Update" })).toBeNull(); - fireEvent.click( - await screen.findByRole("button", { name: "Update and reload" }), - ); + const confirm = await screen.findByRole("button", { name: /^Update$/ }); + const review = confirm.closest('[role="dialog"]'); + if (!review) throw new Error("Expected the update review dialog"); + expect(review).toHaveAccessibleName("Update Notes"); expect( - await screen.findByRole("dialog", { name: "Update Notes" }), + await within(review).findByText("Read your files (added)"), ).toBeVisible(); + expect(confirm).toBeEnabled(); + expect(f.installImport).not.toHaveBeenCalled(); + expect(f.navigation.open).not.toHaveBeenCalled(); +}); + +it("opens actionable plugin settings when a clicked update disappears", async () => { + const f = fixture(); + f.mount(); + const update = await screen.findByRole("button", { + name: "Update and reload", + }); + await waitFor(() => + expect(f.installRequests.updates?.getSnapshot().status).toBe("fresh"), + ); + + f.plugin.revision = "changed before review"; + f.imports.checkGit.mockImplementationOnce(async () => ({ + ...f.discovered, + candidates: [], + })); + fireEvent.click(update); + + await waitFor(() => + expect(f.navigation.open).toHaveBeenCalledWith({ + version: 1, + kind: "settings", + section: "plugins", + pluginId: "example.notes", + }), + ); + expect(f.installImport).not.toHaveBeenCalled(); }); +it.each([ + "disabled checks", + "enabled state", + "source", + "explicit check choice", +])( + "opens plugin settings if %s change during a stale notice refresh", + async (drift) => { + const f = fixture(); + f.mount(); + const update = await screen.findByRole("button", { + name: "Update and reload", + }); + await waitFor(() => + expect(f.installRequests.updates?.getSnapshot().status).toBe("fresh"), + ); + + let finish!: (preview: ImportPreview) => void; + f.imports.checkGit.mockImplementationOnce( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + f.plugin.revision = "changed before review"; + fireEvent.click(update); + await waitFor(() => expect(f.imports.checkGit).toHaveBeenCalledTimes(2)); + + try { + if (drift === "disabled checks") f.plugin.updateChecks = false; + if (drift === "enabled state") f.plugin.enabled = false; + if (drift === "source") + f.plugin.updateSource = { ...f.source, reference: "release" }; + if (drift === "explicit check choice") f.plugin.updateChecks = true; + } finally { + await act(async () => finish(f.discovered)); + } + + await waitFor(() => + expect(f.navigation.open).toHaveBeenCalledExactlyOnceWith({ + version: 1, + kind: "settings", + section: "plugins", + pluginId: "example.notes", + }), + ); + await waitFor(() => + expect(f.installRequests.updates?.getSnapshot().status).toBe( + drift === "disabled checks" ? "disabled" : "fresh", + ), + ); + if (drift !== "disabled checks") + expect( + await screen.findByRole("button", { name: "Update and reload" }), + ).toBeEnabled(); + expect(screen.queryByRole("button", { name: /^Update$/ })).toBeNull(); + expect(f.imports.git).not.toHaveBeenCalled(); + expect(f.installImport).not.toHaveBeenCalled(); + }, +); + it("opens a known update when an unrelated plugin check fails", async () => { const f = fixture(); const configuration = f.state().configuration; diff --git a/src/app/PluginUpdates.tsx b/src/app/PluginUpdates.tsx index d085e1ec68..685a594e29 100644 --- a/src/app/PluginUpdates.tsx +++ b/src/app/PluginUpdates.tsx @@ -45,7 +45,7 @@ const Context = createContext<{ updates: readonly PluginUpdate[]; recommended: readonly string[]; busy: boolean; - open(update: PluginUpdate): void; + open(update: PluginUpdate, returnFocus?: () => HTMLElement | null): void; /** Plugins the owner asked to check again, while that check runs. */ checking: readonly string[]; checkAgain(id: string): Promise; @@ -54,6 +54,12 @@ const noSubscribe = () => () => {}; const empty: readonly PluginUpdate[] = []; const noUpdates = () => empty; const noQueueRevision = () => 0; +type PendingNotificationAction = { + store: Updates; + update: PluginUpdate; + queueId?: string; + returnFocus?: (() => HTMLElement | null) | undefined; +}; export function PluginUpdates({ plugins, @@ -71,8 +77,12 @@ export function PluginUpdates({ const [store, setStore] = useState(); const [action, setAction] = useState(); const [actionQueueId, setActionQueueId] = useState(); + const pendingAction = useRef( + undefined, + ); + const [pendingUpdate, setPendingUpdate] = useState(); const reviewLeaseRevision = useRef(undefined); - const returnFocus = useRef(null); + const returnFocus = useRef<(() => HTMLElement | null) | undefined>(undefined); const state = useSyncExternalStore(plugins.subscribe, plugins.snapshot); const updates = useSyncExternalStore( store?.subscribe ?? noSubscribe, @@ -88,6 +98,16 @@ export function PluginUpdates({ ); const authorizeGit = async (repository: string) => (await relay.snapshot().session.authorizeGit?.(repository)) ?? null; + const openPluginSettings = useCallback( + (pluginId: string) => + void navigation.open({ + version: 1, + kind: "settings", + section: "plugins", + pluginId, + }), + [navigation], + ); useEffect(() => { const updates = createPluginUpdates( plugins, @@ -147,14 +167,91 @@ export function PluginUpdates({ updates.dispose(); }; }, [plugins, relay, installRequests]); + useEffect( + () => () => { + pendingAction.current = undefined; + }, + [], + ); const configuration = state.configuration; const catalog = configuration.status === "ready" ? configuration.catalog : undefined; - const open = (update: PluginUpdate) => { - if (state.busy || action || !update.token) return; - returnFocus.current = document.activeElement as HTMLElement; - if (!store?.capability.queueUpdates([update.token])) - void store?.check(true); + const clearPendingAction = useCallback( + (intent: NonNullable) => { + if (pendingAction.current !== intent) return false; + pendingAction.current = undefined; + setPendingUpdate(undefined); + return true; + }, + [], + ); + const continueNotificationAction = async ( + intent: NonNullable, + ) => { + const store = intent.store; + try { + const checking = store.capability.getSnapshot().status === "checking"; + await store.check(!checking); + if (pendingAction.current !== intent) return; + const current = store + .snapshot() + .find((item) => item.id === intent.update.id); + if ( + !current?.candidate || + !current.token || + current.installedEnabled !== intent.update.installedEnabled || + current.updateChoice !== intent.update.updateChoice || + updateSourceKey(current.source) !== + updateSourceKey(intent.update.source) + ) { + clearPendingAction(intent); + openPluginSettings(intent.update.id); + return; + } + const queued = store.capability.queueUpdates([current.token]); + if (queued) { + intent.queueId = queued.id; + return; + } + } catch { + // The notification remains a route to the plugin's actionable settings state. + } + if (clearPendingAction(intent)) openPluginSettings(intent.update.id); + }; + const open = ( + update: PluginUpdate, + focusTarget?: () => HTMLElement | null, + ) => { + if (state.busy || action || pendingAction.current) return; + if (!store || !update.token) { + openPluginSettings(update.id); + return; + } + const intent: PendingNotificationAction = { + store, + update, + returnFocus: focusTarget, + }; + pendingAction.current = intent; + setPendingUpdate(update); + const queued = store.capability.queueUpdates([update.token]); + if (queued) { + intent.queueId = queued.id; + return; + } + if (store.isCurrentToken(update.token)) { + if (clearPendingAction(intent)) openPluginSettings(update.id); + return; + } + void continueNotificationAction(intent); + }; + const dismiss = (update: PluginUpdate) => { + const intent = pendingAction.current; + if (intent?.update.id === update.id) { + clearPendingAction(intent); + if (intent.queueId) intent.store.capability.cancelQueue(intent.queueId); + } + store?.later(update); }; useEffect(() => { if ( @@ -167,8 +264,17 @@ export function PluginUpdates({ return; const review = store.startNextReview(installRequests.tryHoldReview); if (!review) return; + const intent = pendingAction.current; + const notificationReview = intent?.queueId === review.queueId; + if (intent && notificationReview) clearPendingAction(intent); reviewLeaseRevision.current = installRequests.reviewRevision(); - returnFocus.current = document.activeElement as HTMLElement; + // A notification can wait for another review while the person moves focus. + if (notificationReview && intent.returnFocus) { + returnFocus.current = intent.returnFocus; + } else { + const focused = document.activeElement as HTMLElement; + returnFocus.current = () => focused; + } setAction(review.update); setActionQueueId(review.queueId); }, [ @@ -178,7 +284,29 @@ export function PluginUpdates({ queueRevision, reviewRevision, installRequests, + clearPendingAction, ]); + const pendingQueueId = pendingAction.current?.queueId; + const pendingQueue = pendingQueueId + ? store?.capability.getQueue(pendingQueueId) + : undefined; + useEffect(() => { + const intent = pendingAction.current; + if (!intent) return; + if (intent.store !== store || (intent.queueId && !pendingQueue)) { + if (clearPendingAction(intent)) openPluginSettings(intent.update.id); + return; + } + if (!pendingQueue || action) return; + if ( + !["failed", "cancelled", "completed", "partial"].includes( + pendingQueue.status, + ) + ) + return; + if (clearPendingAction(intent) && pendingQueue.status === "failed") + openPluginSettings(intent.update.id); + }, [store, action, pendingQueue, openPluginSettings, clearPendingAction]); const activeReview = store?.getActiveReview(); const endReview = useCallback( (review: NonNullable, error?: string) => @@ -300,6 +428,19 @@ export function PluginUpdates({ setChecking((ids) => ids.filter((item) => item !== id)); } }; + const visibleUpdates = updates.filter( + (update) => + // A failed check stays on its Settings row. + update.candidate && + (!store?.hidden(update) || pendingUpdate?.id === update.id) && + update.id !== action?.id, + ); + const notices = + pendingUpdate && + pendingUpdate.id !== action?.id && + !visibleUpdates.some((update) => update.id === pendingUpdate.id) + ? [...visibleUpdates, pendingUpdate] + : visibleUpdates; return ( entry.id), }} > @@ -342,53 +483,44 @@ export function PluginUpdates({ }} /> )} - {updates - .filter( - (update) => - // A failed check stays on its Settings row. - update.candidate && - !store?.hidden(update) && - update.id !== action?.id, - ) - .map((update) => { - const plugin = catalog?.plugins.find( - (p) => p.manifest.id === update.id, - ); - const name = plugin?.manifest.name ?? update.id; - const manage = { - label: `Manage ${name} update checks`, - open: () => - void navigation.open({ - version: 1, - kind: "settings", - section: "plugins", - pluginId: update.id, - }), - }; - const review = needsReview(update); - return ( - store?.later(update)} - closeLabel="Dismiss plugin update notice" - navigation={manage} + {notices.map((update) => { + const plugin = catalog?.plugins.find( + (p) => p.manifest.id === update.id, + ); + const name = plugin?.manifest.name ?? update.id; + const manage = { + label: `Manage ${name} update checks`, + open: () => openPluginSettings(update.id), + }; + const review = needsReview(update); + return ( + dismiss(update)} + closeLabel="Dismiss plugin update notice" + navigation={manage} + > + - - - ); - })} + {pendingUpdate?.id === update.id + ? "Preparing update…" + : review + ? "Review permissions" + : "Update and reload"} + + + + ); + })} {validAction && catalog && ( returnFocus.current} + returnFocus={() => { + const target = returnFocus.current?.(); + return target?.isConnected ? target : null; + }} queuedUpdate={queuedUpdate} onClosed={() => { setRecovering((ids) => @@ -471,9 +606,11 @@ function automaticTitle(source: string, changes: readonly ManagedChange[]) { export function PluginUpdatesMenu({ onManage, recommendations, + returnFocus, }: { onManage(): void; recommendations: number; + returnFocus?: () => HTMLElement | null; }) { const context = useContext(Context); // A failed check is reported on its plugin's row in Manage plugins. @@ -506,7 +643,7 @@ export function PluginUpdatesMenu({ context?.open(update)} + onClick={() => context?.open(update, returnFocus)} > Update {update.candidate?.manifest.name ?? update.id} diff --git a/src/app/shell/ProfileButton.tsx b/src/app/shell/ProfileButton.tsx index 49e4ceb90b..064f12295f 100644 --- a/src/app/shell/ProfileButton.tsx +++ b/src/app/shell/ProfileButton.tsx @@ -540,6 +540,7 @@ export function ProfileButton({ profileTrigger.current} onManage={() => { handoff.current = true; onSettings("plugins"); diff --git a/src/shared/design-system/ui/Toast.test.tsx b/src/shared/design-system/ui/Toast.test.tsx index 828ce5b99a..2123359d32 100644 --- a/src/shared/design-system/ui/Toast.test.tsx +++ b/src/shared/design-system/ui/Toast.test.tsx @@ -230,7 +230,7 @@ it("keeps all unresolved recovery controls accessible, including after Escape an expect(screen.getAllByRole("button", { name: /Retry/ })).toHaveLength(5); }); -it("explicit dismissal calls the source once", async () => { +it("explicit dismissal calls the source once, synchronously on button activation", async () => { const dismiss = vi.fn(); render( @@ -240,6 +240,7 @@ it("explicit dismissal calls the source once", async () => { fireEvent.click( await screen.findByRole("button", { name: "Dismiss notification" }), ); + expect(dismiss).toHaveBeenCalledOnce(); await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument(), ); diff --git a/src/shared/design-system/ui/Toast.tsx b/src/shared/design-system/ui/Toast.tsx index 232e77badb..8e03b36d5d 100644 --- a/src/shared/design-system/ui/Toast.tsx +++ b/src/shared/design-system/ui/Toast.tsx @@ -5,6 +5,7 @@ import { useEffectEvent, useId, useLayoutEffect, + useRef, useState, useSyncExternalStore, type ReactNode, @@ -269,6 +270,7 @@ export function ToastNotice({ ); const dismissed = useEffectEvent(() => onDismiss?.()); const dismissible = timeout > 0 || !!onDismiss; + const closeNotice = useRef<(() => void) | undefined>(undefined); useEffect(() => { let active = true; let closed = false; @@ -278,6 +280,7 @@ export function ToastNotice({ source.update(null); dismissed(); }; + closeNotice.current = onClose; toast.custom(() => , { id, toasterId, @@ -287,6 +290,7 @@ export function ToastNotice({ }); return () => { active = false; + closeNotice.current = undefined; source.update(null); toast.dismiss(id); }; @@ -311,6 +315,7 @@ export function ToastNotice({ onClose: dismissible ? () => { toast.dismiss(id); + closeNotice.current?.(); } : undefined, }); diff --git a/tests/browser/plugin-import.spec.mjs b/tests/browser/plugin-import.spec.mjs index 9dabdfb5d7..c54319d8ae 100644 --- a/tests/browser/plugin-import.spec.mjs +++ b/tests/browser/plugin-import.spec.mjs @@ -2356,6 +2356,153 @@ test("a failed update check stays on its Settings row, and Check again clears it await expect(page.getByText("Update Standup Notes")).toHaveCount(0); }); +test("one notification-button click opens a review after a concurrent update check", async ({ + page, + app, +}, info) => { + const repository = "https://github.com/example-org/personal-plugins.git"; + const plugin = (id, name, path) => ({ + manifest: { + id, + name, + apiVersion: 1, + updates: { defaultEnabled: true }, + }, + source: "external", + enabled: true, + revision: "installed", + previous: null, + reloadable: true, + error: null, + updateSource: { repository, reference: "main", path }, + }); + const sample = { + path: "plugins/notes", + revision: "available", + manifest: { + id: "example.notes", + name: "Notes", + apiVersion: 1, + updates: { defaultEnabled: true }, + }, + }; + await page.addInitScript( + (installedPlugins) => { + window.installedPlugins = installedPlugins; + }, + [ + plugin("example.notes", "Notes", sample.path), + plugin("example.missing", "Missing", sample.path), + ], + ); + await nativeImports(page, [sample], { source: repository, warnings: [] }); + const checks = () => + page.evaluate( + () => + window.importCalls.filter( + (call) => + call.command === "plugin_import_git" && call.args?.checkOnly, + ).length, + ); + await page.goto(app.origin); + await expect.poll(checks).toBe(1); + const notice = page.getByRole("dialog", { + name: "Update Notes", + exact: true, + }); + await expect( + notice.getByRole("button", { name: "Update and reload", exact: true }), + ).toBeVisible(); + await notice.screenshot({ path: info.outputPath("notification-before.png") }); + const manage = notice.getByRole("button", { + name: "Manage Notes update checks", + exact: true, + }); + await manage.focus(); + await manage.press("Enter"); + await expect(settingsDialog(page)).toBeVisible(); + const details = page.getByRole("complementary", { name: "Notes details" }); + await expect(details).toBeVisible(); + await expect(notice).toBeVisible(); + const actions = page.getByRole("menu", { name: "Plugin actions" }); + await expect( + actions.getByRole("menuitemcheckbox", { + name: "Check for updates automatically", + }), + ).toBeFocused(); + // Follow the focused menu → details → Settings path while the notice stays above it. + await page.keyboard.press("Escape"); + await expect(actions).toHaveCount(0); + await page.keyboard.press("Escape"); + await expect(details).toHaveCount(0); + await page.keyboard.press("Escape"); + await expect(settingsDialog(page)).toHaveCount(0); + + await openSettings(page); + await selectSettingsSection(page, "Manage plugins"); + const again = settingsDialog(page).getByRole("button", { + name: "Check again", + exact: true, + }); + await expect(again).toBeVisible(); + await page.evaluate(() => { + window.heldGitCheck = new Promise((resolve) => { + window.releaseGitCheck = resolve; + }); + }); + await again.click(); + await expect.poll(checks).toBe(2); + await page.keyboard.press("Escape"); + await expect(settingsDialog(page)).toHaveCount(0); + + await page.setViewportSize({ width: 480, height: 700 }); + await page.evaluate(() => { + document.documentElement.dataset.colorMode = "dark"; + document.documentElement.style.fontSize = "20px"; + }); + await expect(page.locator("html")).toHaveAttribute("data-color-mode", "dark"); + const update = notice.getByRole("button", { + name: "Update and reload", + exact: true, + }); + await update.click(); + try { + await expect( + notice.getByRole("button", { name: "Preparing update…", exact: true }), + ).toBeDisabled(); + await notice.screenshot({ + path: info.outputPath("notification-refresh.png"), + }); + } finally { + await page.evaluate(() => window.releaseGitCheck()); + } + + const review = page.getByRole("dialog", { + name: "Update Notes", + exact: true, + }); + const confirm = review.getByRole("button", { name: "Update", exact: true }); + await expect(confirm).toBeVisible(); + await expect(confirm).toBeEnabled(); + expect( + await page.evaluate( + () => + window.importCalls.filter( + (call) => call.command === "plugin_import_install", + ).length, + ), + ).toBe(0); + await page.setViewportSize({ width: 1440, height: 950 }); + await page.evaluate(() => { + document.documentElement.dataset.colorMode = "light"; + }); + await expect(page.locator("html")).toHaveAttribute( + "data-color-mode", + "light", + ); + await review.screenshot({ path: info.outputPath("notification-review.png") }); +}); + test("a policy's automatic install is noted once and labelled in Settings", async ({ page, app,