diff --git a/Cargo.lock b/Cargo.lock index 86bfb79f9a..1d822c9c49 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1223,6 +1223,7 @@ dependencies = [ "base64 0.22.1", "bech32 0.11.1", "buzz-credential-store", + "cap-fs-ext", "cap-std", "crc32fast", "dirs 6.0.0", @@ -1307,6 +1308,18 @@ dependencies = [ "serde_core", ] +[[package]] +name = "cap-fs-ext" +version = "4.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56ff379b70af8e08307a8f65e7040c7301cb4a572538ade16b4984f0da77847f" +dependencies = [ + "cap-primitives", + "cap-std", + "io-lifetimes 3.0.1", + "windows-sys 0.61.2", +] + [[package]] name = "cap-primitives" version = "4.0.3" diff --git a/crates/plugin-manager/Cargo.toml b/crates/plugin-manager/Cargo.toml index 599273439f..d663df9f82 100644 --- a/crates/plugin-manager/Cargo.toml +++ b/crates/plugin-manager/Cargo.toml @@ -32,6 +32,7 @@ dirs = "6" tempfile = "3" url = "2" cap-std = "4" +cap-fs-ext = "4" reqwest = { version = "0.13", default-features = false, features = ["rustls", "blocking"] } nostr = { version = "=0.45.5", default-features = false, features = ["std", "os-rng"] } # Unused in code: its build metadata (`DEP_TAURI_DEV`) tells build.rs whether diff --git a/crates/plugin-manager/src/imports.rs b/crates/plugin-manager/src/imports.rs index 4d708a36d0..8490dfda9d 100644 --- a/crates/plugin-manager/src/imports.rs +++ b/crates/plugin-manager/src/imports.rs @@ -3,8 +3,8 @@ use crate::{ access::{AccessRules, Transport}, artifact_from_parts, err, hash, icon_revision, managed::{canonical_path, valid_commit, valid_reference}, - Catalog, GitSource, InstallSource, Manager, Manifest, Release, ReloadSource, Result, UrlSource, - BASE64, LIMIT, MAX_ICON_BYTES, MAX_README_BYTES, + prepare_reload_artifact, Catalog, GitSource, InstallSource, Manager, Manifest, Release, + ReloadSource, Result, UrlSource, BASE64, LIMIT, MAX_ICON_BYTES, MAX_README_BYTES, }; use base64::Engine as _; use nostr::event::Event; @@ -279,63 +279,51 @@ pub fn prepare_upload(upload: FolderUpload) -> Result { /// Resolve the installed source natively; callers cannot supply an arbitrary path. pub fn prepare_saved_folder(manager: &Manager, id: &str) -> Result { - let plugin = manager - .catalog()? - .plugins - .into_iter() - .find(|plugin| plugin.manifest.id == id) - .ok_or("Plugin is not installed")?; - let Some(InstallSource::Folder(source)) = plugin.update_source else { - return Err("Plugin has no saved folder source".into()); - }; - let mut prepared = prepare_folder(&source.root)?; - if !prepared - .preview - .candidates - .iter() - .any(|candidate| candidate.path == source.path && candidate.manifest.id == id) - { - let prefix = if source.path == "." { - "Selected folder" - } else { - &source.path - }; - return Err(prepared - .preview - .warnings - .iter() - .find(|warning| warning.starts_with(&format!("{prefix}:"))) - .cloned() - .unwrap_or_else(|| { - "The saved folder no longer contains this plugin at its installed path.".into() - })); - } - prepared - .preview - .candidates - .retain(|candidate| candidate.path == source.path && candidate.manifest.id == id); - prepared.artifacts.retain(|path, _| path == &source.path); + let (source, release) = read_saved_folder(manager, id)?; + let mut prepared = + PreparedImport::new(source.root.display().to_string(), None, Some(source.root))?; + prepared.add(source.path, Ok(release))?; Ok(prepared) } +/// No preview is retained, installed, or published to the native import slot. #[derive(Debug, Serialize)] pub struct UpdateCheck { pub revision: String, pub publisher: Option, } -/// No preview is retained, installed, or published to the native import slot. pub fn check_saved_folder(manager: &Manager, id: &str) -> Result { - let prepared = prepare_saved_folder(manager, id)?; - prepared - .preview - .candidates - .first() - .map(|candidate| UpdateCheck { - revision: candidate.revision.clone(), - publisher: candidate.publisher.clone(), - }) - .ok_or_else(|| "Saved source has no candidate".into()) + let (_, release) = read_saved_folder(manager, id)?; + Ok(UpdateCheck { + revision: hash(&release.bytes), + publisher: release.publisher(), + }) +} + +fn read_saved_folder(manager: &Manager, id: &str) -> Result<(ReloadSource, Release)> { + let plugin = manager + .catalog()? + .plugins + .into_iter() + .find(|plugin| plugin.manifest.id == id) + .ok_or("Plugin is not installed")?; + let source = plugin + .update_source + .ok_or("Plugin has no saved folder source")?; + let InstallSource::Folder(folder) = &source else { + return Err("Plugin has no saved folder source".into()); + }; + let release = prepare_reload_artifact(&source)?; + let manifest = release + .validate() + .map_err(|reason| folder.read_error(reason))?; + if manifest.id != id { + return Err(folder.read_error( + "The saved folder no longer contains this plugin at its installed path.".into(), + )); + } + Ok((folder.clone(), release)) } pub fn prepare_folder(directory: &Path) -> Result { @@ -2574,15 +2562,225 @@ mod tests { assert!(bound .install(&manager, &bound.preview.token, "other") .is_err()); + fs::remove_file(source.join("plugin.signature.json")).unwrap(); + let expected = "dist: Incomplete signed plugin release pair"; + assert_eq!( + check_saved_folder(&manager, "example.checked").unwrap_err(), + expected + ); + assert_eq!( + prepare_saved_folder(&manager, "example.checked") + .err() + .unwrap(), + expected + ); + assert_eq!( + manager.reload_live("example.checked").err().unwrap(), + expected + ); + fs::remove_file(source.join("plugin.js")).unwrap(); - for name in ["plugin.artifact.json", "plugin.signature.json"] { - fs::remove_file(source.join(name)).unwrap(); - } + fs::remove_file(source.join("plugin.artifact.json")).unwrap(); let error = check_saved_folder(&manager, "example.checked").unwrap_err(); assert!(error.contains("dist:"), "{error}"); assert!(error.contains("plugin.js"), "{error}"); } + #[test] + fn saved_folder_checks_ignore_sibling_discovery_limits() { + let root = tempfile::tempdir().unwrap(); + plugin(root.path(), "dist", "example.checked"); + let home = tempfile::tempdir().unwrap(); + let manager = Manager::open(Some(home.path().into()), "test", false).unwrap(); + let pending = prepare_folder(root.path()).unwrap(); + let installed = pending + .install(&manager, &pending.preview.token, "dist") + .unwrap(); + let original = installed + .plugins + .iter() + .find(|p| p.manifest.id == "example.checked") + .unwrap() + .revision + .clone(); + for index in 0..MAX_PLUGINS { + plugin( + root.path(), + &format!("sibling-{index}"), + &format!("example.sibling{index}"), + ); + } + assert!(prepare_folder(root.path()).is_err()); + assert_eq!( + check_saved_folder(&manager, "example.checked") + .unwrap() + .revision, + original + ); + } + + #[cfg(unix)] + #[test] + fn saved_folder_updates_require_the_original_directory() { + let root = tempfile::tempdir().unwrap(); + let source = plugin(root.path(), "dist", "example.checked"); + let home = tempfile::tempdir().unwrap(); + let manager = Manager::open(Some(home.path().into()), "test", false).unwrap(); + let pending = prepare_folder(root.path()).unwrap(); + pending + .install(&manager, &pending.preview.token, "dist") + .unwrap(); + assert!(check_saved_folder(&manager, "example.checked").is_ok()); + + let moved = root.path().join("moved"); + fs::rename(&source, &moved).unwrap(); + std::os::unix::fs::symlink(&moved, &source).unwrap(); + + assert!(check_saved_folder(&manager, "example.checked").is_err()); + assert!(prepare_saved_folder(&manager, "example.checked").is_err()); + } + + #[test] + fn saved_folder_update_preview_ignores_siblings_and_installs_captured_bytes() { + let root = tempfile::tempdir().unwrap(); + let source = plugin(root.path(), "dist", "example.checked"); + let home = tempfile::tempdir().unwrap(); + let manager = Manager::open(Some(home.path().into()), "test", false).unwrap(); + let initial = prepare_folder(root.path()).unwrap(); + initial + .install(&manager, &initial.preview.token, "dist") + .unwrap(); + for index in 0..MAX_PLUGINS { + plugin( + root.path(), + &format!("sibling-{index}"), + &format!("example.sibling{index}"), + ); + } + fs::write( + source.join("plugin.js"), + "export function activate() { /* changed */ }", + ) + .unwrap(); + sign(&source); + let revision = check_saved_folder(&manager, "example.checked") + .unwrap() + .revision; + let preview = prepare_saved_folder(&manager, "example.checked").unwrap(); + assert_eq!(preview.preview.candidates.len(), 1); + assert_eq!(preview.preview.candidates[0].path, "dist"); + assert_eq!(preview.preview.candidates[0].revision, revision); + fs::write( + source.join("plugin.js"), + "export function activate() { /* later */ }", + ) + .unwrap(); + sign(&source); + assert_ne!( + check_saved_folder(&manager, "example.checked") + .unwrap() + .revision, + revision + ); + let installed = preview + .install(&manager, &preview.preview.token, "dist") + .unwrap(); + let plugin = installed + .plugins + .iter() + .find(|p| p.manifest.id == "example.checked") + .unwrap(); + assert_eq!(plugin.revision, revision); + let Some(InstallSource::Folder(saved)) = &plugin.update_source else { + panic!("saved folder missing") + }; + assert_eq!(saved.path, "dist"); + assert_eq!(saved.root, root.path().canonicalize().unwrap()); + } + + #[test] + fn saved_folder_check_reports_signature_only_repair_without_scanning_siblings() { + let root = tempfile::tempdir().unwrap(); + let source = plugin(root.path(), "dist", "example.checked"); + let home = tempfile::tempdir().unwrap(); + let manager = Manager::open(Some(home.path().into()), "test", false).unwrap(); + let pending = prepare_folder(root.path()).unwrap(); + pending + .install(&manager, &pending.preview.token, "dist") + .unwrap(); + // A legacy install may lack metadata even when its source is now signed. + let mut registry = manager.read().unwrap(); + registry + .installed + .get_mut("example.checked") + .unwrap() + .current_signature = None; + manager.save(®istry).unwrap(); + let installed = manager.catalog().unwrap(); + let unsigned = installed + .plugins + .iter() + .find(|p| p.manifest.id == "example.checked") + .unwrap(); + assert!(unsigned.publisher.is_none()); + let publisher = crate::sign_release(&source, TEST_SIGNING_KEY).unwrap(); + for index in 0..MAX_PLUGINS { + plugin( + root.path(), + &format!("sibling-{index}"), + &format!("example.sibling{index}"), + ); + } + let checked = check_saved_folder(&manager, "example.checked").unwrap(); + assert_eq!(checked.revision, unsigned.revision); + assert_eq!(checked.publisher.as_deref(), Some(publisher.as_str())); + let captured = prepare_saved_folder(&manager, "example.checked").unwrap(); + assert_eq!(captured.preview.candidates[0].publisher, checked.publisher); + assert!(manager + .catalog() + .unwrap() + .plugins + .iter() + .find(|p| p.manifest.id == "example.checked") + .unwrap() + .publisher + .is_none()); + fs::write(source.join("plugin.signature.json"), "{}").unwrap(); + assert!(check_saved_folder(&manager, "example.checked").is_err()); + } + + #[test] + fn saved_folder_checks_confine_replaced_paths_and_validate_package_identity() { + let root = tempfile::tempdir().unwrap(); + let source = plugin(root.path(), "dist", "example.checked"); + let home = tempfile::tempdir().unwrap(); + let manager = Manager::open(Some(home.path().into()), "test", false).unwrap(); + let pending = prepare_folder(root.path()).unwrap(); + pending + .install(&manager, &pending.preview.token, "dist") + .unwrap(); + #[cfg(unix)] + { + let outside = tempfile::tempdir().unwrap(); + let escaped = plugin(outside.path(), "dist", "example.checked"); + fs::remove_dir_all(&source).unwrap(); + std::os::unix::fs::symlink(&escaped, &source).unwrap(); + assert!(check_saved_folder(&manager, "example.checked").is_err()); + assert!(prepare_saved_folder(&manager, "example.checked").is_err()); + fs::remove_file(&source).unwrap(); + } + plugin(root.path(), "dist", "example.changed"); + assert!(check_saved_folder(&manager, "example.checked").is_err()); + assert!(prepare_saved_folder(&manager, "example.checked").is_err()); + // A signature is verified even during discovery, before owner review. + plugin(root.path(), "dist", "example.checked"); + let key = nostr::key::SecretKey::generate().to_secret_hex(); + crate::sign_release(&source, &key).unwrap(); + fs::write(source.join("plugin.signature.json"), "{}").unwrap(); + assert!(check_saved_folder(&manager, "example.checked").is_err()); + assert!(prepare_saved_folder(&manager, "example.checked").is_err()); + } + #[test] fn signed_folder_import_load_reload_and_publisher_continuity() { let root = tempfile::tempdir().unwrap(); diff --git a/crates/plugin-manager/src/lib.rs b/crates/plugin-manager/src/lib.rs index c5de4d049c..5b620a7b82 100644 --- a/crates/plugin-manager/src/lib.rs +++ b/crates/plugin-manager/src/lib.rs @@ -1,5 +1,6 @@ //! Installation and settings never execute plugin code. Both desktop and CLI use this crate. use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _}; +use cap_fs_ext::DirExt as _; use nostr::{ event::{Event, EventBuilder, FinalizeEvent, Kind, Tag}, key::{Keys, SecretKey}, @@ -711,6 +712,15 @@ impl ReloadSource { validate_candidate_path(&path)?; Ok(Self { root, path }) } + + fn read_error(&self, reason: String) -> String { + let label = if self.path == "." { + "Selected folder" + } else { + &self.path + }; + format!("{label}: {reason}") + } } // Untagged keeps existing {root, path} folder metadata readable without migration. #[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)] @@ -1718,17 +1728,24 @@ fn prepare_reload_artifact(source: &InstallSource) -> Result { let InstallSource::Folder(source) = source else { return Err("Plugin was not installed from a reloadable folder".into()); }; - let relative = validate_candidate_path(&source.path)?; - if !fs::symlink_metadata(&source.root) - .map_err(err)? - .file_type() - .is_dir() - { - return Err("Reload source root must be a regular folder".into()); - } - let directory = cap_std::fs::Dir::open_ambient_dir(&source.root, cap_std::ambient_authority()) - .map_err(err)?; - imports::read_package(&directory, &relative) + let read = || { + let relative = validate_candidate_path(&source.path)?; + if !fs::symlink_metadata(&source.root) + .map_err(err)? + .file_type() + .is_dir() + { + return Err("Reload source root must be a regular folder".into()); + } + let mut directory = + cap_std::fs::Dir::open_ambient_dir(&source.root, cap_std::ambient_authority()) + .map_err(err)?; + for part in relative.iter() { + directory = directory.open_dir_nofollow(part).map_err(err)?; + } + imports::read_package(&directory, Path::new(".")) + }; + read().map_err(|reason| source.read_error(reason)) } fn validate_candidate_path(path: &str) -> Result { // Recorded paths are lossless folder identities; spaces are part of valid names. diff --git a/docs/buzz-help.md b/docs/buzz-help.md index fe42e0c1ad..51e71b912f 100644 --- a/docs/buzz-help.md +++ b/docs/buzz-help.md @@ -199,6 +199,8 @@ For a Git-installed plugin, an agent's update request or a pinned install link can switch the tracked branch even when the code is unchanged. Review and confirm the update to save the new source; no reinstall is needed. +Manage plugins shows **Update** as soon as the background check finds a newer version. Buzz checks saved folders and eligible Git sources at startup and hourly while the app is visible. Saved folders are checked offline too. Opening Settings or returning to the window does not start a separate check. Automatic Git checks require update support and a network connection. To check a saved folder or Git source yourself, open the plugin’s details and choose **Check for updates**. Choosing **Update** opens a review before installing anything. + A plugin runs with the same reach as Buzz itself, with no sandbox. Install one only if you trust its author with your account and your computer. diff --git a/src/app/PluginImport.test.tsx b/src/app/PluginImport.test.tsx index 35d38a7be2..799932b349 100644 --- a/src/app/PluginImport.test.tsx +++ b/src/app/PluginImport.test.tsx @@ -20,6 +20,10 @@ import { } from "../plugins/installer"; import { createPluginUpdates } from "../plugins/updates"; import { PluginImport } from "./PluginImport"; +import { + createPluginUpdateChecks, + sharedPluginUpdateChecks, +} from "../plugins/update-checks"; import userEvent from "@testing-library/user-event"; import { cloneElement, StrictMode } from "react"; @@ -568,6 +572,7 @@ it("shows exact declared access and changes before an enabled update", async () } as unknown as PluginManager; render( preview), discard: vi.fn(async () => {}), }, - snapshot: () => ({ configuration, error: null }), + snapshot: () => ({ configuration, activation: {}, error: null }), subscribe: () => () => {}, installImport, change: vi.fn(), @@ -1624,6 +1631,119 @@ it("releases the serialized queue when a confirmed review unmounts and fails", a updates.dispose(); }); +it.each([false, true])( + "reconciles queued review failure and recovery (managed pin=%s)", + async (managed) => { + const source = { + repository: "https://example.com/plugins.git", + reference: "main", + path: ".", + ...(managed ? { commit: "a".repeat(40) } : {}), + }; + const manifest = { + id: "example.target", + name: "Target", + apiVersion: 1 as const, + updates: { defaultEnabled: true }, + }; + const plugin: PluginInfo = { + manifest, + source: "external", + enabled: true, + revision: "one", + previous: null, + reloadable: true, + error: null, + updateSource: { + repository: source.repository, + reference: source.reference, + path: source.path, + }, + }; + const preview: ImportPreview = { + token: "queued-preview", + source: source.repository, + commit: "a".repeat(40), + warnings: [], + candidates: [{ path: ".", manifest, revision: "two" }], + }; + const catalog = { profile: "test", location: "test", plugins: [plugin] }; + const imports = { + checkGit: vi.fn(async () => preview), + git: vi + .fn() + .mockRejectedValueOnce(new Error("Temporary acquisition failure")) + .mockResolvedValue(preview), + discard: vi.fn(async () => {}), + }; + const manager = { + imports, + snapshot: () => ({ + configuration: { + status: "ready", + externalPluginsPaused: false, + catalog, + ...(managed + ? { + managed: { + status: "ready", + path: "policy", + source: "Example", + plugins: [{ id: manifest.id, ...source, state: "outdated" }], + problems: [], + }, + } + : {}), + }, + activation: {}, + }), + subscribe: () => () => {}, + } as unknown as PluginManager; + const updates = createPluginUpdates(manager, async () => null); + let view: ReturnType | undefined; + try { + const token = (await updates.capability.refresh()).candidates[0]?.token; + if (!token) throw new Error("Expected candidate"); + const queue = updates.capability.queueUpdates([token]); + if (!queue || !startReview(updates)) + throw new Error("Expected active review"); + const element = ( + + ); + view = render(element); + expect(await screen.findByRole("alert")).toHaveTextContent( + "Temporary acquisition failure", + ); + expect(updates.isCurrentToken(token)).toBe(false); + expect(updates.capability.getSnapshot().status).toBe("error"); + view.unmount(); + view = render(element); + await screen.findByRole("dialog", { name: "Update Target" }); + await waitFor(() => expect(updates.isCurrentToken(token)).toBe(true)); + expect(updates.capability.getSnapshot().status).toBe("fresh"); + const release = updates.beginOperation(queue.id, token); + expect(release).toBeDefined(); + release?.(); + expect(imports.git).toHaveBeenLastCalledWith( + source.repository, + source.reference, + undefined, + ...(managed ? [{ commit: source.commit }] : []), + ); + } finally { + view?.unmount(); + updates.dispose(); + } + }, +); + it("opens installed details instead of adding another source", async () => { const manifest = { id: "example.duplicate", @@ -1881,7 +2001,7 @@ it("uses the live enabled state after checking a saved Git update", async () => fireEvent.click(check); try { await waitFor(() => expect(git).toHaveBeenCalledOnce()); - expect(check).toBeDisabled(); + expect(check).toHaveAttribute("aria-disabled", "true"); } finally { await act(async () => finish(rememberedPreview)); } @@ -1950,6 +2070,7 @@ it.each([ render( { expect( screen.getByRole("button", { name: "Browse plugin folder" }), ).toBeVisible(); + await user.click(screen.getByRole("button", { name: "Close" })); + await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); + expect(sharedPluginUpdateChecks(manager.imports).snapshot()).toEqual({}); }); function savedFolderProps(imports: unknown) { @@ -2249,7 +2374,7 @@ function savedFolderProps(imports: unknown) { ...rememberedPlugin, updateSource: { root: "/plugins", path: "dist" }, }, - ], + ] as [PluginInfo], }, busy: false, updateId: rememberedManifest.id, @@ -2263,7 +2388,9 @@ it("checks revisions without acquiring a preview and prepares fresh bytes only o discard: vi.fn(async () => {}), }; const props = savedFolderProps(imports); - const view = render(); + const checks = createPluginUpdateChecks(props.plugins.imports); + const view = render(); + await act(async () => checks.check(props.catalog.plugins[0])); const update = await screen.findByRole("button", { name: "Update" }); expect(imports.checkFolder).toHaveBeenCalledExactlyOnceWith( rememberedManifest.id, @@ -2281,8 +2408,7 @@ it("checks revisions without acquiring a preview and prepares fresh bytes only o view.unmount(); }); -it("retries folder diagnostics and ignores late read-only checks after unmount", async () => { - vi.useFakeTimers({ toFake: ["setInterval", "clearInterval"] }); +it("receives folder diagnostics and ignores late background checks after unmount", async () => { let finish!: (release: { revision: string }) => void; const checkFolder = vi .fn() @@ -2294,33 +2420,32 @@ it("retries folder diagnostics and ignores late read-only checks after unmount", }), ); const imports = { checkFolder, previewFolder: vi.fn(), discard: vi.fn() }; - const changed = vi.fn(); - const view = render( - , + const props = savedFolderProps(imports); + const checks = createPluginUpdateChecks(props.plugins.imports); + const plugin = props.catalog.plugins[0]; + const view = render(); + expect(checkFolder).not.toHaveBeenCalled(); + await act(async () => checks.check(plugin)); + expect(await screen.findByRole("alert")).toHaveTextContent( + "dist: plugin.js is missing", ); - try { - expect(await screen.findByRole("alert")).toHaveTextContent( - "dist: plugin.js is missing", - ); - await act(async () => vi.advanceTimersByTime(5_000)); - expect(checkFolder).toHaveBeenCalledTimes(2); - await act(async () => vi.advanceTimersByTime(10_000)); - expect(checkFolder).toHaveBeenCalledTimes(2); - view.unmount(); - await act(async () => finish({ revision: "new" })); - expect(changed).toHaveBeenLastCalledWith(false); - expect(imports.previewFolder).not.toHaveBeenCalled(); - expect(imports.discard).not.toHaveBeenCalled(); - } finally { - view.unmount(); - vi.useRealTimers(); - } + let pending!: Promise; + act(() => { + pending = checks.check(plugin); + }); + expect(checkFolder).toHaveBeenCalledTimes(2); + fireEvent.focus(window); + expect(checkFolder).toHaveBeenCalledTimes(2); + view.unmount(); + await act(async () => { + finish({ revision: "new" }); + await pending; + }); + expect(imports.previewFolder).not.toHaveBeenCalled(); + expect(imports.discard).not.toHaveBeenCalled(); }); -it("keeps unchanged checks quiet until the shared one-second loading delay", async () => { +it("keeps explicit checks quiet until the shared one-second loading delay", async () => { vi.useFakeTimers(); let finish!: (release: { revision: string }) => void; const checkFolder = vi.fn( @@ -2329,21 +2454,28 @@ it("keeps unchanged checks quiet until the shared one-second loading delay", asy finish = resolve; }), ); - const view = render(); + const props = savedFolderProps({ checkFolder }); + const checks = createPluginUpdateChecks(props.plugins.imports); + const view = render(); try { - await act(async () => {}); + let pending!: Promise; + act(() => { + pending = checks.check(props.catalog.plugins[0]); + }); await act(async () => vi.advanceTimersByTime(999)); expect(screen.queryByText("Checking for updates…")).toBeNull(); await act(async () => vi.advanceTimersByTime(1)); expect(screen.getByRole("status")).toHaveTextContent( "Checking for updates…", ); - await act(async () => finish({ revision: "old" })); + await act(async () => { + finish({ revision: "old" }); + await pending; + }); expect(screen.getByText("Up to date")).toBeVisible(); expect(screen.queryByRole("button", { name: "Update" })).toBeNull(); await act(async () => vi.advanceTimersByTime(4_000)); - expect(checkFolder).toHaveBeenCalledTimes(2); - await act(async () => finish({ revision: "old" })); + expect(checkFolder).toHaveBeenCalledOnce(); } finally { view.unmount(); vi.useRealTimers(); @@ -2371,10 +2503,8 @@ it("retains known Git updates on reopen and reacquires before review", async () }, initialUpdateAvailable: true, }; - const changed = vi.fn(); - render(); + render(); expect(screen.getByRole("button", { name: "Update" })).toBeVisible(); - expect(changed).not.toHaveBeenCalled(); expect(git).not.toHaveBeenCalled(); fireEvent.click(screen.getByRole("button", { name: "Update" })); await screen.findByRole("dialog", { name: "Update Remembered" }); @@ -2395,36 +2525,29 @@ it("refreshes a stale known update from the newly acquired package", async () => })), discard: vi.fn(async () => {}), }; - const changed = vi.fn(); - render( - , - ); + const props = savedFolderProps(imports); + const checks = createPluginUpdateChecks(props.plugins.imports); + render(); + await act(async () => checks.check(props.catalog.plugins[0])); fireEvent.click(await screen.findByRole("button", { name: "Update" })); fireEvent.click(await screen.findByRole("button", { name: "Done" })); await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); expect(screen.queryByRole("button", { name: "Update" })).toBeNull(); - expect(changed).toHaveBeenLastCalledWith(false); expect(imports.discard).toHaveBeenCalledExactlyOnceWith("remembered"); }); -it("clears a retained update action after the saved source check fails", async () => { - const changed = vi.fn(); +it("clears a retained update action after the background source check fails", async () => { + const props = savedFolderProps({ + checkFolder: vi.fn(async () => { + throw new Error("dist: invalid manifest"); + }), + }); + const checks = createPluginUpdateChecks(props.plugins.imports); render( - { - throw new Error("dist: invalid manifest"); - }), - })} - initialUpdateAvailable - onUpdateAvailableChange={changed} - />, + , ); + await act(async () => checks.check(props.catalog.plugins[0])); await screen.findByRole("alert"); - await waitFor(() => expect(changed).toHaveBeenLastCalledWith(false)); expect(screen.queryByRole("button", { name: "Update" })).toBeNull(); }); @@ -3775,6 +3898,101 @@ it("leaves an unconstrained link editable and unpinned", async () => { ); }); +it("keeps a known Update usable while background discovery is pending", async () => { + let finish!: (release: { revision: string }) => void; + const imports = { + checkFolder: vi.fn( + () => + new Promise<{ revision: string }>((resolve) => { + finish = resolve; + }), + ), + previewFolder: vi.fn(async () => rememberedPreview), + discard: vi.fn(async () => {}), + }; + const props = savedFolderProps(imports); + const checks = createPluginUpdateChecks(props.plugins.imports); + const plugin = props.catalog.plugins[0]; + if (!plugin) throw new Error("fixture plugin missing"); + checks.observe(plugin)({ revision: "new" }); + render(); + act(() => { + void checks.check(plugin); + }); + await waitFor(() => expect(imports.checkFolder).toHaveBeenCalledOnce()); + try { + const update = screen.getByRole("button", { name: "Update" }); + expect(update).toBeEnabled(); + fireEvent.click(update); + await screen.findByRole("dialog", { name: "Update Remembered" }); + expect(imports.previewFolder).toHaveBeenCalledExactlyOnceWith( + rememberedManifest.id, + ); + } finally { + await act(async () => finish({ revision: "new" })); + } +}); + +it.each([false, true])( + "keeps a manually discovered update local until confirmed (multiple=%s)", + async (multiple) => { + const user = userEvent.setup(); + const imports = { + folder: vi.fn(async () => ({ + ...rememberedPreview, + candidates: multiple + ? rememberedPreview.candidates + : [rememberedPreview.candidates[0]], + })), + discard: vi.fn(async () => {}), + }; + const manager = { + imports, + installImport: vi.fn(), + } as unknown as PluginManager; + const checks = createPluginUpdateChecks(manager.imports); + render( + , + ); + await user.click(screen.getByRole("button", { name: "Update Remembered" })); + await user.click( + screen.getByRole("button", { name: "Browse plugin folder" }), + ); + if (multiple) { + await user.click((await screen.findAllByRole("radio"))[1] as HTMLElement); + await user.click(screen.getByRole("button", { name: "Continue" })); + } + await screen.findByRole("button", { name: /^Update$/ }); + await user.keyboard("{Escape}"); + await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull()); + expect(checks.snapshot()).toEqual({}); + expect( + screen.getByRole("button", { name: "Update Remembered" }), + ).toBeVisible(); + expect(screen.queryByRole("button", { name: /^Update$/ })).toBeNull(); + expect(manager.installImport).not.toHaveBeenCalled(); + }, +); + +it("lets the owner check a changed saved folder explicitly", async () => { + const checkFolder = vi.fn(async () => ({ revision: "new" })); + render(); + expect(checkFolder).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole("button", { name: "Check for updates" })); + expect(await screen.findByRole("button", { name: "Update" })).toBeVisible(); + expect(checkFolder).toHaveBeenCalledExactlyOnceWith(rememberedManifest.id); +}); + function installedFromLink(overrides: Partial = {}): PluginInfo { return { manifest: requestedManifest, diff --git a/src/app/PluginImport.tsx b/src/app/PluginImport.tsx index ecf5bcb772..9534a1020d 100644 --- a/src/app/PluginImport.tsx +++ b/src/app/PluginImport.tsx @@ -12,21 +12,23 @@ import { useEffect, useEffectEvent, useLayoutEffect, + useMemo, + useSyncExternalStore, useRef, useState, } from "react"; import { createPortal } from "react-dom"; import { FolderOpenIcon } from "../shared/design-system/icons/index"; import { PluginAccessReview } from "./PluginAccessReview"; +import { + sharedPluginUpdateChecks, + pluginUpdateCheck, + type PluginUpdateChecks, +} from "../plugins/update-checks"; import { gitScope } from "../plugins/git-scope"; import type { PluginManager } from "../plugins/manager"; import { samePluginRelease } from "../plugins/same-release"; -import type { - Catalog, - ImportPreview, - PluginInfo, - PluginRelease, -} from "../plugins/types"; +import type { Catalog, ImportPreview, PluginInfo } from "../plugins/types"; import { pluginUpdateSource, updateSourceKey, @@ -128,6 +130,7 @@ export function PluginImport({ updateAction, requestSignal, initialUpdateAvailable = false, + updateChecks, plugins, catalog, busy, @@ -137,7 +140,6 @@ export function PluginImport({ updateId, onClosed, onOpenInstalled, - onUpdateAvailableChange, reviewRequested = false, onReviewHandled, returnFocus, @@ -159,6 +161,7 @@ export function PluginImport({ | undefined; requestSignal?: AbortSignal | undefined; initialUpdateAvailable?: boolean; + updateChecks?: PluginUpdateChecks | undefined; plugins: PluginManager; catalog: Catalog; busy: boolean; @@ -167,7 +170,6 @@ export function PluginImport({ updateId?: string; onClosed?: () => void; onOpenInstalled?: (id: string) => void; - onUpdateAvailableChange?: (available: boolean) => void; reviewRequested?: boolean; onReviewHandled?: () => void; returnFocus?: () => HTMLElement | null; @@ -208,6 +210,15 @@ export function PluginImport({ // A URL install is pinned to one artifact; it updates through its recommendation. const savedSource = recordedSource && "url" in recordedSource ? undefined : recordedSource; + const checks = useMemo( + () => updateChecks ?? sharedPluginUpdateChecks(imports), + [updateChecks, imports], + ); + const checkSnapshot = useSyncExternalStore(checks.subscribe, checks.snapshot); + const sourceCheck = pluginUpdateCheck(checkSnapshot, currentPlugin); + const checkedRelease = sourceCheck?.release; + const checking = !!sourceCheck?.checking; + const checkError = sourceCheck?.error; const [repository, setRepository] = useState( initialGit?.repository ?? (savedSource && "repository" in savedSource @@ -259,9 +270,6 @@ export function PluginImport({ requestedReference !== undefined && requestedReference !== trackedReference; const [preview, setPreview] = useState(null); - const [checkedRelease, setCheckedRelease] = useState(); - const [checking, setChecking] = useState(false); - const checkPending = useRef(false); const [discarding, setDiscarding] = useState(false); const [selected, setSelected] = useState(""); @@ -409,24 +417,6 @@ export function PluginImport({ setRepository(""); setReference(""); } - async function checkSource(operation: () => Promise) { - if (checkPending.current) return; - checkPending.current = true; - const current = lifetime.current; - setChecking(true); - try { - const release = await operation(); - if (current.active) { - setCheckedRelease(release); - setError(null); - } - } catch (reason) { - if (current.active) recordError(reason); - } finally { - checkPending.current = false; - if (current.active) setChecking(false); - } - } function rememberQueuedUpdateFailure(failure: string) { if (!updateAction || !queuedUpdate) return; lastQueuedUpdateFailure.current = failure; @@ -436,25 +426,9 @@ export function PluginImport({ queuedUpdateEnded.current = true; queuedUpdate.settled(outcome); } - const startSavedFolder = useEffectEvent(() => { - if ( - imports && - savedSource && - "root" in savedSource && - updateId && - !open && - !busy && - document.visibilityState !== "hidden" - ) - void checkSource(() => imports.checkFolder(updateId)); - }); useEffect(() => { const current = { active: true, token: "", installing: false }; lifetime.current = current; - // Defer until effects settle so Strict Mode's retired mount never acquires. - queueMicrotask(() => { - if (current.active) startSavedFolder(); - }); return () => { current.active = false; if (current.token && !current.installing) @@ -462,20 +436,6 @@ export function PluginImport({ }; }, [imports]); - const localFolder = !!savedSource && "root" in savedSource; - useEffect(() => { - if (!localFolder) return; - const timer = setInterval(() => startSavedFolder(), 5_000); - const resume = () => startSavedFolder(); - document.addEventListener("visibilitychange", resume); - window.addEventListener("focus", resume); - return () => { - clearInterval(timer); - document.removeEventListener("visibilitychange", resume); - window.removeEventListener("focus", resume); - }; - }, [localFolder]); - const candidate = preview?.candidates.find((p) => p.path === selected); const updating = !!existing; const installedSource = existing?.updateSource; @@ -547,18 +507,12 @@ export function PluginImport({ samePluginRelease(candidate, updateId ? currentPlugin : existing); const updateAvailable = !error && + !(checkError && !preview) && (preview ? !upToDate : checkedRelease !== undefined ? !samePluginRelease(checkedRelease, currentPlugin) : initialUpdateAvailable); - const notifyUpdateAvailable = useEffectEvent((available: boolean) => - onUpdateAvailableChange?.(available), - ); - useEffect(() => { - if (error || preview || checkedRelease !== undefined) - notifyUpdateAvailable(updateAvailable); - }, [updateAvailable, checkedRelease, preview, error]); useEffect(() => { if (!reviewRequested || loading) return; if (error) { @@ -640,6 +594,10 @@ export function PluginImport({ fromGit = false, ) { if (!imports || pending.current || blocked) return; + const observe = + currentPlugin && savedSource + ? checks.observe(currentPlugin, updateAction?.source) + : undefined; const returnTo = document.activeElement as HTMLElement | null; sourceTrigger.current = returnTo; pending.current = true; @@ -717,10 +675,10 @@ export function PluginImport({ throw new Error(failure); } } + if (next?.candidates.length === 1 && next.candidates[0]) + observe?.(next.candidates[0], null, next.candidates[0]); lastQueuedUpdateFailure.current = undefined; setError(null); - if (updateId && next?.candidates.length === 1) - setCheckedRelease(next.candidates[0]); setPreview(next); setReviewing(next?.candidates.length === 1); setExisting( @@ -734,7 +692,10 @@ export function PluginImport({ next?.candidates.length === 1 ? (next.candidates[0]?.path ?? "") : "", ); } catch (reason) { - if (current.active) showError(reason, returnTo, false, fromGit); + if (current.active) { + observe?.(undefined, String(reason)); + showError(reason, returnTo, false, fromGit); + } } finally { pending.current = false; if (current.active) { @@ -845,45 +806,30 @@ export function PluginImport({ void load(() => imports.previewFolder(updateId)); return; } - checkSavedGit(false); + checkSavedSource(false); } - function checkSavedGit(checkOnly = true) { + function checkSavedSource(checkOnly = true) { const source = savedSource; - if (!imports || !source || !("repository" in source)) return; + if (!imports || !source) return; + if (checkOnly) { + if (currentPlugin) void checks.check(currentPlugin, authorizeGit); + return; + } + if (!("repository" in source)) return; const acquire = async () => { - if (!checkOnly && lifetime.current.token) { + if (lifetime.current.token) { await imports.discard(lifetime.current.token); lifetime.current.token = ""; } const signed = await authorizeGit?.(source.repository); - return (checkOnly ? imports.checkGit : imports.git)( + return imports.git( signed?.repository ?? source.repository, source.reference, signed?.token, ...gitScope(updateAction?.source.commit, source.path), ); }; - if (!checkOnly) { - void load(acquire, !!updateAction); - return; - } - void checkSource(async () => { - const result = await acquire(); - if (!result) throw new Error("No update source found"); - const candidate = result.candidates.find( - (item) => item.manifest.id === updateId && item.path === source.path, - ); - if (!candidate) - throw new Error( - result.warnings.find((warning) => - warning.startsWith( - `${source.path === "." ? "Selected folder" : source.path}:`, - ), - ) ?? - "The saved repository no longer contains this plugin at its installed path.", - ); - return candidate; - }); + void load(acquire, !!updateAction, true); } async function installCandidate() { if ( @@ -1063,14 +1009,15 @@ export function PluginImport({ ); const updateActions = ( <> - {!savedSource && !preview && addButton} - {savedSource && "repository" in savedSource && ( + {!savedSource && !preview && !updateAvailable && addButton} + {savedSource && ( @@ -1080,7 +1027,7 @@ export function PluginImport({ ref={trigger} variant="prominent" size="sm" - disabled={blocked || checking} + disabled={blocked} onClick={() => { prepareReview(); }} @@ -1122,18 +1069,19 @@ export function PluginImport({ > {null} - {error && !open ? ( + {(error || checkError) && !open ? (

Source{" "} {savedSource && "repository" in savedSource ? "repository" : "folder"}{" "} - unavailable. {error.message} + unavailable. {error?.message ?? checkError}

) : null} {(preview || checkedRelease !== undefined) && !open && !error && + !checkError && !updateAvailable ? ( statusTarget ? ( createPortal(Up to date, statusTarget) @@ -1279,6 +1227,12 @@ export function PluginImport({ type="button" disabled={blocked || !candidate} onClick={() => { + if (currentPlugin && savedSource && candidate) + checks.observe(currentPlugin, updateAction?.source)( + candidate, + null, + candidate, + ); setExisting( catalog.plugins.find( (item) => item.manifest.id === candidate?.manifest.id, diff --git a/src/app/PluginUpdates.test.tsx b/src/app/PluginUpdates.test.tsx index a25cc81d64..8cf0f3f355 100644 --- a/src/app/PluginUpdates.test.tsx +++ b/src/app/PluginUpdates.test.tsx @@ -14,6 +14,10 @@ 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 { + sharedPluginUpdateChecks, + pluginUpdateAvailable, +} from "../plugins/update-checks"; import { PluginUpdateFailure, PluginUpdates, @@ -1733,9 +1737,9 @@ it.each(["drift", "missing"] as const)( kind === "drift" ? "The update candidate changed after it was checked. Check for updates again before reviewing it." : "The saved folder or repository no longer contains this plugin at its installed path."; - const refusal = await screen.findByText(failure, { exact: false }); + const review = await screen.findByRole("dialog"); + const refusal = await within(review).findByText(failure, { exact: false }); expect(refusal).toBeVisible(); - const review = screen.getByRole("dialog"); expect(capability.getQueue(accepted.id)?.items[0]?.status).toBe( "reviewing", ); @@ -1794,6 +1798,13 @@ it("keeps a queued update retryable after its fresh preview cannot be loaded", a expect(within(review).getByRole("button", { name: "Update" })).toBeEnabled(); expect(capability.getQueue(accepted.id)?.items[0]?.status).toBe("reviewing"); expect(f.installImport).not.toHaveBeenCalled(); + fireEvent.click(within(review).getByRole("button", { name: "Update" })); + await waitFor(() => expect(f.installImport).toHaveBeenCalledOnce()); + await waitFor(() => + expect(capability.getQueue(accepted.id)?.items[0]?.status).toBe( + "installed", + ), + ); }); it("ends a queued review when the host invalidates its action before confirmation", async () => { @@ -2126,6 +2137,25 @@ it("requires review when a fresh update removes a process artifact constraint", await waitFor(() => expect(f.installImport).toHaveBeenCalledOnce()); }); +it.each(["unchanged", "failed"])( + "shares a notification review's fresh %s result with Manage plugins", + async (outcome) => { + const f = fixture(); + f.freshCandidate.revision = f.plugin.revision; + if (outcome === "failed") + f.imports.git.mockRejectedValueOnce(new Error("source unavailable")); + f.mount(); + await screen.findByText("Update Notes"); + const checks = sharedPluginUpdateChecks(f.manager.imports); + expect(pluginUpdateAvailable(checks.snapshot(), f.plugin)).toBe(true); + fireEvent.click(screen.getByRole("button", { name: "Update and reload" })); + await waitFor(() => + expect(pluginUpdateAvailable(checks.snapshot(), f.plugin)).toBe(false), + ); + expect(f.installImport).not.toHaveBeenCalled(); + }, +); + const OFFLINE = "Git could not read this repository: fatal: unable to access 'https://example.com/plugins.git/': Could not resolve host: example.com"; const noticeTitle = (name: string) => `Couldn’t check ${name} for updates`; @@ -2341,6 +2371,29 @@ it("keeps Check again and the generic sentence when an authorized HTTPS check is expect(screen.queryByText(/Git needs a sign-in/)).toBeNull(); }); +it("opens an offline explicit-check notification on its first click without another discovery", async () => { + const online = vi.spyOn(navigator, "onLine", "get").mockReturnValue(false); + try { + const f = fixture(); + f.mount(); + await act(async () => { + await sharedPluginUpdateChecks(f.manager.imports).check(f.plugin); + }); + fireEvent.click( + await screen.findByRole("button", { name: "Update and reload" }), + ); + const review = await screen.findByRole("dialog", { name: "Update Notes" }); + expect( + await within(review).findByRole("button", { name: "Update" }), + ).toBeEnabled(); + expect(f.imports.checkGit).toHaveBeenCalledOnce(); + expect(f.imports.git).toHaveBeenCalledOnce(); + expect(f.installImport).not.toHaveBeenCalled(); + } finally { + online.mockRestore(); + } +}); + it("doesn’t check in the background while offline, and checks when the connection returns", async () => { const online = vi.spyOn(navigator, "onLine", "get").mockReturnValue(false); try { @@ -2442,33 +2495,157 @@ it("checks again when the connection returns before the check it dropped has fai expect(f.imports.checkGit).toHaveBeenCalledTimes(2); }); -it("keeps the connection's return for a hidden window, and checks again once it is shown", async () => { - const visibility = vi - .spyOn(document, "visibilityState", "get") - .mockReturnValue("visible"); +it.each([true, false])( + "retries a hidden reconnect only when visible and online (still connected=%s)", + async (stillConnected) => { + const online = vi.spyOn(navigator, "onLine", "get").mockReturnValue(true); + const visibility = vi + .spyOn(document, "visibilityState", "get") + .mockReturnValue("visible"); + try { + const f = fixture(); + f.candidate.revision = f.plugin.revision; + f.imports.checkGit.mockRejectedValueOnce(OFFLINE); + f.mount(); + expect( + await screen.findByText("Couldn’t check for updates."), + ).toBeVisible(); + visibility.mockReturnValue("hidden"); + await act(async () => { + window.dispatchEvent(new Event("online")); + }); + expect(f.imports.checkGit).toHaveBeenCalledOnce(); + online.mockReturnValue(stillConnected); + visibility.mockReturnValue("visible"); + await act(async () => { + document.dispatchEvent(new Event("visibilitychange")); + }); + if (!stillConnected) { + expect(f.imports.checkGit).toHaveBeenCalledOnce(); + expect(screen.getByText("Couldn’t check for updates.")).toBeVisible(); + online.mockReturnValue(true); + await act(async () => { + window.dispatchEvent(new Event("online")); + }); + } + await waitFor(() => expect(f.imports.checkGit).toHaveBeenCalledTimes(2)); + await waitFor(() => + expect(screen.queryByText("Couldn’t check for updates.")).toBeNull(), + ); + } finally { + visibility.mockRestore(); + online.mockRestore(); + } + }, +); + +it("discovers saved-folder updates on its hourly cadence while offline without reading Git", async () => { + vi.useFakeTimers({ toFake: ["Date"] }); + vi.setSystemTime(0); + const online = vi.spyOn(navigator, "onLine", "get").mockReturnValue(false); try { const f = fixture(); - f.candidate.revision = f.plugin.revision; - f.imports.checkGit.mockRejectedValueOnce(OFFLINE); + const configuration = f.state().configuration; + if (configuration.status !== "ready") throw new Error("Expected catalog"); + const folder = { + ...f.plugin, + manifest: { ...f.plugin.manifest, id: "example.folder" }, + updateSource: { root: "/plugins/folder", path: "." }, + }; + const checkFolder = vi.fn(async () => ({ revision: "folder-new" })); + Object.assign(f.imports, { checkFolder }); + f.emit({ + configuration: { + ...configuration, + catalog: { ...configuration.catalog, plugins: [f.plugin, folder] }, + }, + }); f.mount(); - expect( - await screen.findByText("Couldn’t check for updates."), - ).toBeVisible(); - visibility.mockReturnValue("hidden"); + await waitFor(() => + expect( + pluginUpdateAvailable( + sharedPluginUpdateChecks(f.manager.imports).snapshot(), + folder, + ), + ).toBe(true), + ); + expect(checkFolder).toHaveBeenCalledExactlyOnceWith(folder.manifest.id); + expect(f.imports.checkGit).not.toHaveBeenCalled(); + vi.setSystemTime(3_600_000); await act(async () => { - window.dispatchEvent(new Event("online")); + document.dispatchEvent(new Event("visibilitychange")); }); - expect(f.imports.checkGit).toHaveBeenCalledOnce(); - visibility.mockReturnValue("visible"); + expect(checkFolder).toHaveBeenCalledTimes(2); + expect(f.imports.checkGit).not.toHaveBeenCalled(); + online.mockReturnValue(true); await act(async () => { - document.dispatchEvent(new Event("visibilitychange")); + window.dispatchEvent(new Event("online")); }); + expect(f.imports.checkGit).toHaveBeenCalledOnce(); + expect(checkFolder).toHaveBeenCalledTimes(2); + } finally { + online.mockRestore(); + } +}); + +it("lets an explicit Check again try Git even when the browser reports offline", async () => { + const f = fixture(); + f.imports.checkGit.mockRejectedValueOnce(OFFLINE); + f.mount(); + const again = await screen.findByRole("button", { name: "Check again" }); + const online = vi.spyOn(navigator, "onLine", "get").mockReturnValue(false); + try { + fireEvent.click(again); await waitFor(() => expect(f.imports.checkGit).toHaveBeenCalledTimes(2)); await waitFor(() => expect(screen.queryByText("Couldn’t check for updates.")).toBeNull(), ); } finally { - visibility.mockRestore(); + online.mockRestore(); + } +}); + +it("keeps the folder cadence running while background Git is pending", async () => { + vi.useFakeTimers(); + const f = fixture(); + const configuration = f.state().configuration; + if (configuration.status !== "ready") throw new Error("Expected catalog"); + const folder = { + ...f.plugin, + manifest: { ...f.plugin.manifest, id: "example.folder" }, + updateSource: { root: "/plugins/folder", path: "." }, + }; + const checkFolder = vi.fn(async () => ({ revision: "folder-new" })); + Object.assign(f.imports, { checkFolder }); + f.emit({ + configuration: { + ...configuration, + catalog: { ...configuration.catalog, plugins: [f.plugin, folder] }, + }, + }); + let release!: () => void; + f.imports.checkGit.mockImplementationOnce( + () => + new Promise((resolve) => { + release = () => resolve(f.discovered); + }), + ); + f.mount(); + try { + await act(async () => {}); + expect(f.imports.checkGit).toHaveBeenCalledOnce(); + expect(checkFolder).toHaveBeenCalledOnce(); + await act(async () => { + await vi.advanceTimersByTimeAsync(3_600_000); + }); + expect(checkFolder).toHaveBeenCalledTimes(2); + await act(async () => { + await vi.advanceTimersByTimeAsync(3_600_000); + }); + expect(checkFolder).toHaveBeenCalledTimes(3); + expect(f.imports.checkGit).toHaveBeenCalledOnce(); + } finally { + await act(async () => release()); } }); diff --git a/src/app/PluginUpdates.tsx b/src/app/PluginUpdates.tsx index 685a594e29..d6c98db23b 100644 --- a/src/app/PluginUpdates.tsx +++ b/src/app/PluginUpdates.tsx @@ -109,18 +109,18 @@ export function PluginUpdates({ [navigation], ); useEffect(() => { + const online = () => navigator.onLine !== false; const updates = createPluginUpdates( plugins, async (repository) => (await relay.snapshot().session.authorizeGit?.(repository)) ?? null, + online, ); setStore(updates); const unregisterUpdates = installRequests.registerUpdates(updates); let timer: ReturnType | undefined; let disposed = false; - // Being offline is normal, so background checks wait for a connection. - const ready = () => - document.visibilityState !== "hidden" && navigator.onLine !== false; + const ready = () => document.visibilityState !== "hidden"; // A check that failed when the connection dropped is throttled like any // other, so the connection's return checks it again at once. The intent // lasts until a check can run: the window may be hidden. A check that @@ -133,14 +133,17 @@ export function PluginUpdates({ const check = async (force = false) => { clearTimeout(timer); if (!ready()) return; - if (reconnect && running === 0) { + if (reconnect && running === 0 && online()) { reconnect = false; force ||= failed(); } running++; - const delay = await updates.check(force).finally(() => running--); + const pending = updates.check(force).finally(() => running--); + const localDelay = updates.nextCheck(); + if (localDelay !== undefined) timer = setTimeout(scheduled, localDelay); + const delay = await pending; if (disposed || !ready()) return; - if (reconnect) { + if (reconnect && online()) { reconnect = false; if (failed()) return check(true); } diff --git a/src/app/Settings.test.tsx b/src/app/Settings.test.tsx index d6321267dd..790f9ec078 100644 --- a/src/app/Settings.test.tsx +++ b/src/app/Settings.test.tsx @@ -12,6 +12,7 @@ import { } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { useSyncExternalStore } from "react"; +import { PluginUpdates } from "./PluginUpdates"; import { ToastProvider } from "../shared/design-system/ui/Toast"; import { Context } from "@deepseek-ai/cordis"; import { afterEach, expect, it, onTestFinished, vi } from "vitest"; @@ -38,7 +39,16 @@ import type { StorageResult, } from "../plugins/types"; -afterEach(cleanup); +afterEach(() => { + cleanup(); + vi.restoreAllMocks(); +}); + +function refreshBackground() { + const now = Date.now(); + vi.spyOn(Date, "now").mockReturnValue(now + 3_600_001); + fireEvent(document, new Event("visibilitychange")); +} // Settings reads agent plugin requests from every plugin manager. const noRequests = createPluginRequests({ catalog: () => undefined, @@ -846,10 +856,9 @@ export function apply(ctx) { name: "Repair details", }); expect(within(details).getByText(signatureError)).toBeVisible(); - if (source === "git") - fireEvent.click( - within(details).getByRole("button", { name: "Check for updates" }), - ); + fireEvent.click( + within(details).getByRole("button", { name: "Check for updates" }), + ); await waitFor(() => expect( within(details).getByRole("button", { name: "Update" }), @@ -905,6 +914,7 @@ function reviewPluginFixture( id: "example.external", name: "Zebra external", apiVersion: 1, + updates: { defaultEnabled: true }, discovery: { category: "agents", tags: ["Essentials"] }, }, source: "external", @@ -971,9 +981,28 @@ function reviewPluginFixture( }), } as unknown as Parameters[0]["plugins"]; const { cards } = registry([]); - render(); + const backgroundRelay = { snapshot: () => ({ session: {} }) } as Parameters< + typeof PluginUpdates + >[0]["relay"]; + const installRequests = createPluginInstallRequests(); + const content = (show = true) => ( + + + {show && ( + + )} + + + ); + const view = render(content()); + const showSettings = (show: boolean) => view.rerender(content(show)); fireEvent.click(screen.getByRole("button", { name: "Manage plugins" })); - return { external, snapshot, publish, manager }; + return { external, snapshot, publish, manager, view, showSettings }; } it("keeps bundled plugins free of manual-plugin menus in rows and details", () => { @@ -3454,12 +3483,12 @@ it("retains both local drafts across section navigation but retires them with th }); it("allows Add to install while an independent folder check is pending, including pane remount", async () => { - let finish!: (release: { revision: string }) => void; + const finishes: ((release: { revision: string }) => void)[] = []; const fixture = reviewPluginFixture(); const checkFolder = vi.fn( () => new Promise<{ revision: string }>((resolve) => { - finish = resolve; + finishes.push(resolve); }), ); const preview = { @@ -3502,7 +3531,9 @@ it("allows Add to install while an independent folder check is pending, includin await within(dialog).findByRole("button", { name: "Install plugin" }); fixture.external.revision = "cli-reloaded"; act(fixture.publish); - await act(async () => finish({ revision: "current" })); + await act(async () => { + for (const finish of finishes) finish({ revision: "current" }); + }); expect(discard).not.toHaveBeenCalled(); fireEvent.click( within(dialog).getByRole("switch", { name: "Enable plugin" }), @@ -3732,7 +3763,12 @@ it("routes a managed plugin's updates through the managed review instead of the undefined, { commit: pinned, path: "dist" }, ); - expect(checkGit).not.toHaveBeenCalled(); + expect(checkGit).toHaveBeenCalledExactlyOnceWith( + "https://example.com/plugins", + "v1", + undefined, + { commit: pinned, path: "dist" }, + ); }); function installRequestFixture(imports: object | undefined) { @@ -3850,6 +3886,776 @@ it("leaves a confirmed install's request to the install when Settings closes", a await expect(outcome).resolves.toBe("installed"); }); +it("discovers installed source updates from the list and uses the hourly background result", async () => { + const fixture = reviewPluginFixture(); + const plugin = fixture.external; + Object.assign(plugin, { updateSource: { root: "/plugins", path: "." } }); + let revision = "updated"; + const checkFolder = vi.fn(async () => ({ revision })); + const imports = { + checkFolder, + git: vi.fn(), + install: vi.fn(), + discard: vi.fn(), + }; + Object.assign(fixture.manager, { imports }); + act(fixture.publish); + await waitFor(() => + expect(checkFolder).toHaveBeenCalledWith(plugin.manifest.id), + ); + expect( + await screen.findByRole("button", { name: "Update Zebra external" }), + ).toBeVisible(); + expect( + screen.queryByRole("complementary", { name: "Zebra external details" }), + ).toBeNull(); + expect(imports.install).not.toHaveBeenCalled(); + revision = "current"; + refreshBackground(); + await waitFor(() => + expect( + screen.queryByRole("button", { name: "Update Zebra external" }), + ).toBeNull(), + ); + expect(checkFolder).toHaveBeenCalledTimes(2); +}); + +it.each(["updated", "failed"])( + "keeps background checks silent before their %s result without opening details", + async (outcome) => { + const fixture = reviewPluginFixture(); + Object.assign(fixture.external, { updateSource: savedGitSource }); + let resolve!: (result: ReturnType) => void; + let reject!: (reason: Error) => void; + const checkGit = vi.fn( + () => + new Promise>((yes, no) => { + resolve = yes; + reject = no; + }), + ); + Object.assign(fixture.manager, { imports: { checkGit } }); + act(fixture.publish); + try { + await waitFor(() => expect(checkGit).toHaveBeenCalledOnce()); + expect( + fixture.view.container.querySelector(".buzz-loading-region"), + ).toBeNull(); + expect( + screen.getByRole("button", { name: "Disable Zebra external" }), + ).toBeEnabled(); + expect( + screen.queryByRole("complementary", { name: "Zebra external details" }), + ).toBeNull(); + } finally { + await act(async () => { + if (outcome === "updated") resolve(gitCheckResult("new")); + else reject(new Error("repository offline")); + }); + } + expect(screen.queryByText("Checking for updates…")).toBeNull(); + if (outcome === "updated") + expect( + await screen.findByRole("button", { name: "Update Zebra external" }), + ).toBeVisible(); + else expect(screen.queryByText(/Update check failed/)).toBeNull(); + expect(checkGit).toHaveBeenCalledOnce(); + expect( + screen.queryByRole("complementary", { name: "Zebra external details" }), + ).toBeNull(); + }, +); + +it("checks disabled Git plugins at their saved path while isolating source failures", async () => { + const fixture = reviewPluginFixture(); + const plugin = fixture.external; + Object.assign(plugin, { + enabled: false, + updateSource: { + repository: "https://example.com/plugins", + reference: "main", + path: "dist", + }, + }); + fixture.snapshot.configuration.catalog.plugins.push({ + ...plugin, + manifest: { + ...plugin.manifest, + id: "example.broken", + name: "Broken source", + }, + ...{ updateSource: { root: "/missing", path: "." } }, + }); + const checkFolder = vi.fn(async () => { + throw new Error("missing folder"); + }); + const checkGit = vi.fn(async () => ({ + token: "", + source: "https://example.com/plugins", + commit: null, + warnings: [], + candidates: [ + { path: "other", revision: "current", manifest: plugin.manifest }, + { path: "dist", revision: "new", manifest: plugin.manifest }, + ], + })); + Object.assign(fixture.manager, { imports: { checkFolder, checkGit } }); + act(fixture.publish); + expect( + await screen.findByRole("button", { name: "Update Zebra external" }), + ).toBeVisible(); + expect(checkGit).toHaveBeenCalledExactlyOnceWith( + "https://example.com/plugins", + "main", + undefined, + { path: "dist" }, + ); + expect(checkFolder).toHaveBeenCalledExactlyOnceWith("example.broken"); + expect( + screen.queryByRole("button", { name: "Update Broken source" }), + ).toBeNull(); +}); + +it("ignores an old source result after the installed revision changes", async () => { + const fixture = reviewPluginFixture(); + Object.assign(fixture.external, { + updateSource: { root: "/plugins", path: "." }, + }); + let finish!: (release: { revision: string }) => void; + const checkFolder = vi + .fn() + .mockImplementationOnce( + () => + new Promise<{ revision: string }>((resolve) => { + finish = resolve; + }), + ) + .mockResolvedValue("installed-again"); + Object.assign(fixture.manager, { imports: { checkFolder } }); + act(fixture.publish); + await waitFor(() => expect(checkFolder).toHaveBeenCalledOnce()); + act(() => { + const catalog = fixture.snapshot.configuration.catalog; + fixture.snapshot.configuration.catalog = { + ...catalog, + plugins: catalog.plugins.map((plugin) => + plugin.manifest.id === fixture.external.manifest.id + ? { ...plugin, revision: "installed-again" } + : plugin, + ), + }; + fixture.publish(); + }); + await act(async () => finish({ revision: "new-from-old-check" })); + await waitFor(() => expect(checkFolder).toHaveBeenCalledTimes(2)); + expect( + screen.queryByRole("button", { name: "Update Zebra external" }), + ).toBeNull(); + fireEvent.click(screen.getByRole("button", { name: "Profile" })); + await act(async () => { + fireEvent.focus(window); + }); + expect(checkFolder).toHaveBeenCalledTimes(2); +}); + +const gitCheckResult = (revision: string, path = "dist") => ({ + token: "", + source: "https://example.com/plugins", + commit: null, + warnings: [], + candidates: [ + { + path, + revision, + manifest: { + id: "example.external", + name: "Zebra external", + apiVersion: 1, + }, + }, + ], +}); +const savedGitSource = { + repository: "https://example.com/plugins", + reference: "main", + path: "dist", +}; + +it("keeps folder and Git discovery under the background owner", async () => { + const fixture = reviewPluginFixture(); + Object.assign(fixture.external, { + updateSource: { root: "/plugins", path: "." }, + }); + fixture.snapshot.configuration.catalog.plugins.push({ + ...fixture.external, + manifest: { + ...fixture.external.manifest, + id: "example.slow", + name: "Slow Git", + }, + ...{ updateSource: savedGitSource }, + }); + let finish!: (result: ReturnType) => void; + const checkGit = vi.fn( + () => + new Promise>((resolve) => { + finish = resolve; + }), + ); + let revision = "current"; + const checkFolder = vi.fn(async () => ({ revision })); + Object.assign(fixture.manager, { imports: { checkFolder, checkGit } }); + act(fixture.publish); + try { + await waitFor(() => expect(checkGit).toHaveBeenCalledOnce()); + await act(async () => {}); + revision = "updated"; + fireEvent.focus(window); + await act(async () => {}); + expect( + screen.queryByRole("button", { name: "Update Zebra external" }), + ).toBeNull(); + expect(checkFolder).toHaveBeenCalledOnce(); + expect(checkGit).toHaveBeenCalledOnce(); + } finally { + await act(async () => finish(gitCheckResult("current"))); + } + refreshBackground(); + expect( + await screen.findByRole("button", { name: "Update Zebra external" }), + ).toBeVisible(); +}); + +it("retains the serial background Git loop across Settings remounts", async () => { + const fixture = reviewPluginFixture(); + const plugins = [0, 1, 2].map((index) => ({ + ...fixture.external, + manifest: { + ...fixture.external.manifest, + id: `example.git${index}`, + name: `Git ${index}`, + }, + updateSource: { + ...savedGitSource, + repository: `https://example.com/${index}`, + }, + })); + fixture.snapshot.configuration.catalog.plugins = plugins; + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + const checkGit = vi.fn(async () => { + await gate; + return { + ...gitCheckResult("new"), + candidates: plugins.map((plugin) => ({ + path: plugin.updateSource.path, + revision: "new", + manifest: plugin.manifest, + })), + }; + }); + Object.assign(fixture.manager, { imports: { checkGit } }); + act(fixture.publish); + try { + await waitFor(() => expect(checkGit).toHaveBeenCalledOnce()); + fixture.showSettings(false); + fixture.showSettings(true); + fireEvent.click(screen.getByRole("button", { name: "Manage plugins" })); + await act(async () => {}); + expect(checkGit).toHaveBeenCalledOnce(); + } finally { + await act(async () => release()); + } + for (const plugin of plugins) { + expect( + await screen.findByRole("button", { + name: `Update ${plugin.manifest.name}`, + }), + ).toBeVisible(); + } + expect(checkGit).toHaveBeenCalledTimes(3); +}); + +it("reuses an in-flight source read after leaving and reopening Manage plugins", async () => { + const fixture = reviewPluginFixture(); + Object.assign(fixture.external, { updateSource: savedGitSource }); + let finish!: (result: ReturnType) => void; + const checkGit = vi.fn( + () => + new Promise>((resolve) => { + finish = resolve; + }), + ); + Object.assign(fixture.manager, { imports: { checkGit } }); + act(fixture.publish); + try { + await waitFor(() => expect(checkGit).toHaveBeenCalledOnce()); + fireEvent.click(screen.getByRole("button", { name: "Profile" })); + fireEvent.click(screen.getByRole("button", { name: "Manage plugins" })); + await act(async () => {}); + expect(checkGit).toHaveBeenCalledOnce(); + } finally { + await act(async () => finish(gitCheckResult("new"))); + } + expect( + await screen.findByRole("button", { name: "Update Zebra external" }), + ).toBeVisible(); +}); + +it("scopes Git acquisitions to each installed plugin path", async () => { + const fixture = reviewPluginFixture(); + Object.assign(fixture.external, { updateSource: savedGitSource }); + fixture.snapshot.configuration.catalog.plugins = [ + ...fixture.snapshot.configuration.catalog.plugins, + { + ...fixture.external, + manifest: { + ...fixture.external.manifest, + id: "example.sibling", + name: "Sibling", + }, + ...{ updateSource: { ...savedGitSource, path: "sibling" } }, + }, + ]; + const checkGit = vi.fn(async () => ({ + ...gitCheckResult("new"), + candidates: [ + ...gitCheckResult("new").candidates, + { + path: "sibling", + revision: "new", + manifest: { id: "example.sibling", name: "Sibling", apiVersion: 1 }, + }, + ], + })); + Object.assign(fixture.manager, { imports: { checkGit } }); + act(fixture.publish); + expect( + await screen.findByRole("button", { name: "Update Zebra external" }), + ).toBeVisible(); + await waitFor(() => + expect( + screen.getByRole("button", { name: "Update Sibling" }), + ).toBeVisible(), + ); + expect(checkGit).toHaveBeenCalledTimes(2); + expect(checkGit).toHaveBeenCalledWith( + savedGitSource.repository, + savedGitSource.reference, + undefined, + { path: "sibling" }, + ); +}); + +it("updates the open Git pane after a background check finds a new revision", async () => { + const fixture = reviewPluginFixture(); + Object.assign(fixture.external, { updateSource: savedGitSource }); + let revision = "current"; + const checkGit = vi.fn(async () => gitCheckResult(revision)); + Object.assign(fixture.manager, { imports: { checkGit } }); + act(fixture.publish); + await waitFor(() => expect(checkGit).toHaveBeenCalledOnce()); + fireEvent.click( + screen.getByRole("button", { name: "View Zebra external details" }), + ); + const pane = screen.getByRole("complementary", { + name: "Zebra external details", + }); + fireEvent.click( + within(pane).getByRole("button", { name: "Check for updates" }), + ); + expect(await within(pane).findByText("Up to date")).toBeVisible(); + revision = "new"; + refreshBackground(); + await waitFor(() => + expect( + within(pane).getByRole("button", { name: /^Update$/ }), + ).toBeVisible(), + ); + expect(within(pane).queryByText("Up to date")).toBeNull(); +}); + +it("shares the pending automatic Git read with the open pane", async () => { + const fixture = reviewPluginFixture(); + Object.assign(fixture.external, { updateSource: savedGitSource }); + let finish!: (result: ReturnType) => void; + const checkGit = vi.fn( + () => + new Promise>((resolve) => { + finish = resolve; + }), + ); + Object.assign(fixture.manager, { imports: { checkGit } }); + act(fixture.publish); + try { + await waitFor(() => expect(checkGit).toHaveBeenCalledOnce()); + fireEvent.click( + screen.getByRole("button", { name: "View Zebra external details" }), + ); + const pane = screen.getByRole("complementary", { + name: "Zebra external details", + }); + expect( + within(pane).getByRole("button", { name: "Check for updates" }), + ).toBeEnabled(); + fireEvent.focus(window); + await act(async () => {}); + expect(checkGit).toHaveBeenCalledOnce(); + } finally { + await act(async () => finish(gitCheckResult("new"))); + } + fireEvent.click(screen.getByRole("button", { name: "Close plugin details" })); + expect( + screen.getByRole("button", { name: "Update Zebra external" }), + ).toBeVisible(); +}); + +it("does not let opening cached details discard a pending background result", async () => { + const fixture = reviewPluginFixture(); + Object.assign(fixture.external, { updateSource: savedGitSource }); + let finish!: (result: ReturnType) => void; + const checkGit = vi + .fn() + .mockResolvedValueOnce(gitCheckResult("current")) + .mockImplementationOnce( + () => + new Promise((resolve) => { + finish = resolve; + }), + ); + Object.assign(fixture.manager, { imports: { checkGit } }); + act(fixture.publish); + await waitFor(() => expect(checkGit).toHaveBeenCalledOnce()); + await act(async () => {}); + refreshBackground(); + await waitFor(() => expect(checkGit).toHaveBeenCalledTimes(2)); + try { + fireEvent.click( + screen.getByRole("button", { name: "View Zebra external details" }), + ); + await act(async () => {}); + } finally { + await act(async () => finish(gitCheckResult("new"))); + } + const pane = screen.getByRole("complementary", { + name: "Zebra external details", + }); + await waitFor(() => + expect( + within(pane).getByRole("button", { name: /^Update$/ }), + ).toBeVisible(), + ); +}); + +it("shows a failed background check in the open Git pane", async () => { + const fixture = reviewPluginFixture(); + Object.assign(fixture.external, { updateSource: savedGitSource }); + const checkGit = vi + .fn() + .mockResolvedValueOnce(gitCheckResult("new")) + .mockRejectedValue(new Error("repository unavailable")); + Object.assign(fixture.manager, { imports: { checkGit } }); + act(fixture.publish); + await screen.findByRole("button", { name: "Update Zebra external" }); + fireEvent.click( + screen.getByRole("button", { name: "View Zebra external details" }), + ); + const pane = screen.getByRole("complementary", { + name: "Zebra external details", + }); + await waitFor(() => + expect( + within(pane).getByRole("button", { name: /^Update$/ }), + ).toBeVisible(), + ); + refreshBackground(); + await waitFor(() => expect(checkGit).toHaveBeenCalledTimes(2)); + await waitFor(() => + expect(within(pane).getByRole("alert")).toHaveTextContent( + "repository unavailable", + ), + ); + expect(within(pane).queryByRole("button", { name: /^Update$/ })).toBeNull(); +}); + +it("uses the latest source result after an update review closes", async () => { + const savePosition = vi.fn(); + const fixture = reviewPluginFixture({ + navigation: { + entryId: "update-review", + target: { version: 1, kind: "settings", section: "plugins" }, + complete: vi.fn(), + savePosition, + } as unknown as Parameters[0]["navigation"], + }); + Object.assign(fixture.external, { updateSource: savedGitSource }); + let revision = "new"; + const checkGit = vi.fn(async () => gitCheckResult(revision)); + const git = vi.fn(async () => ({ + ...gitCheckResult("new"), + token: "review", + })); + Object.assign(fixture.manager, { + imports: { checkGit, git, discard: vi.fn(async () => {}) }, + }); + act(fixture.publish); + fireEvent.click( + await screen.findByRole("button", { name: "Update Zebra external" }), + ); + expect(savePosition).toHaveBeenCalledWith( + "settings.pluginDetails", + "example.external", + ); + const close = await screen.findByRole("button", { name: "Close" }); + const dialog = close.closest('[role="dialog"]') as HTMLElement; + revision = "current"; + refreshBackground(); + await waitFor(() => expect(checkGit).toHaveBeenCalledTimes(2)); + await act(async () => {}); + fireEvent.click(within(dialog).getByRole("button", { name: "Close" })); + await waitFor(() => + expect( + screen.queryByRole("dialog", { name: "Update Zebra external" }), + ).toBeNull(), + ); + expect( + screen.queryByRole("button", { name: "Update Zebra external" }), + ).toBeNull(); + const pane = screen.getByRole("complementary", { + name: "Zebra external details", + }); + expect(within(pane).queryByRole("button", { name: /^Update$/ })).toBeNull(); +}); + +it.each(["saved", "default", "undeclared"])( + "honors automatic Git opt-outs (%s) while allowing an explicit pane check", + async (preference) => { + const fixture = reviewPluginFixture(); + Object.assign(fixture.external, { + updateSource: savedGitSource, + updateChecks: preference === "saved" ? false : undefined, + }); + if (preference !== "saved") + Object.assign(fixture.external.manifest, { + updates: + preference === "default" ? { defaultEnabled: false } : undefined, + }); + const checkGit = vi.fn(async () => gitCheckResult("new")); + Object.assign(fixture.manager, { imports: { checkGit } }); + await act(async () => { + fixture.publish(); + }); + await act(async () => { + refreshBackground(); + }); + expect(checkGit).not.toHaveBeenCalled(); + fireEvent.click( + screen.getByRole("button", { name: "View Zebra external details" }), + ); + fireEvent.click(screen.getByRole("button", { name: "Check for updates" })); + await waitFor(() => expect(checkGit).toHaveBeenCalledOnce()); + }, +); + +it("does not reacquire unchanged Git sources after management actions", async () => { + const fixture = reviewPluginFixture(); + Object.assign(fixture.external, { updateSource: savedGitSource }); + const checkGit = vi.fn(async () => gitCheckResult("new")); + Object.assign(fixture.manager, { imports: { checkGit } }); + await act(async () => { + fixture.publish(); + }); + await waitFor(() => expect(checkGit).toHaveBeenCalledOnce()); + await act(async () => { + fixture.snapshot.busy = true; + fixture.publish(); + }); + await act(async () => { + fixture.snapshot.busy = false; + fixture.snapshot.configuration.catalog = { + ...fixture.snapshot.configuration.catalog, + plugins: fixture.snapshot.configuration.catalog.plugins.map((p) => ({ + ...p, + enabled: false, + })), + }; + fixture.publish(); + }); + expect(checkGit).toHaveBeenCalledOnce(); + refreshBackground(); + await waitFor(() => expect(checkGit).toHaveBeenCalledTimes(2)); +}); + +it("does not start another source read on focus or idle management", async () => { + const fixture = reviewPluginFixture(); + Object.assign(fixture.external, { updateSource: savedGitSource }); + const checkGit = vi + .fn() + .mockResolvedValueOnce(gitCheckResult("current")) + .mockResolvedValue(gitCheckResult("new")); + Object.assign(fixture.manager, { imports: { checkGit } }); + await act(async () => fixture.publish()); + await waitFor(() => expect(checkGit).toHaveBeenCalledOnce()); + await act(async () => { + Object.assign(fixture.manager.snapshot(), { busy: true }); + fixture.publish(); + }); + fireEvent.focus(window); + fireEvent.focus(window); + expect(checkGit).toHaveBeenCalledOnce(); + await act(async () => { + Object.assign(fixture.manager.snapshot(), { busy: false }); + fixture.publish(); + }); + expect( + screen.queryByRole("button", { name: "Update Zebra external" }), + ).toBeNull(); + expect(checkGit).toHaveBeenCalledOnce(); +}); + +it.each(["opt-out", "removal"])( + "retires a queued list check after %s", + async (change) => { + const fixture = reviewPluginFixture(); + Object.assign(fixture.external, { updateSource: savedGitSource }); + let finish!: (result: ReturnType) => void; + const checkGit = vi + .fn() + .mockImplementationOnce( + () => + new Promise((resolve) => { + finish = resolve; + }), + ) + .mockResolvedValue(gitCheckResult("new")); + Object.assign(fixture.manager, { imports: { checkGit } }); + await act(async () => fixture.publish()); + await waitFor(() => expect(checkGit).toHaveBeenCalledOnce()); + const catalog = fixture.manager.snapshot().configuration; + if (catalog.status !== "ready") throw new Error("fixture not ready"); + catalog.catalog.plugins = catalog.catalog.plugins.map((item) => + item.manifest.id === fixture.external.manifest.id + ? { ...item, revision: "replacement" } + : item, + ); + await act(async () => fixture.publish()); + catalog.catalog.plugins = catalog.catalog.plugins.flatMap((item) => + item.manifest.id !== fixture.external.manifest.id + ? [item] + : change === "removal" + ? [] + : [{ ...item, updateChecks: false }], + ); + await act(async () => fixture.publish()); + await act(async () => finish(gitCheckResult("old"))); + expect(checkGit).toHaveBeenCalledOnce(); + }, +); + +it("restores an explicit pane check after opting out during automatic discovery", async () => { + const fixture = reviewPluginFixture(); + Object.assign(fixture.external, { updateSource: savedGitSource }); + let finish!: (result: ReturnType) => void; + const checkGit = vi + .fn() + .mockImplementationOnce( + () => + new Promise((resolve) => { + finish = resolve; + }), + ) + .mockResolvedValue(gitCheckResult("new")); + Object.assign(fixture.manager, { imports: { checkGit } }); + await act(async () => fixture.publish()); + await waitFor(() => expect(checkGit).toHaveBeenCalledOnce()); + fireEvent.click( + screen.getByRole("button", { name: "View Zebra external details" }), + ); + const pane = screen.getByRole("complementary", { + name: "Zebra external details", + }); + expect( + within(pane).getByRole("button", { name: "Check for updates" }), + ).toBeEnabled(); + Object.assign(fixture.external, { updateChecks: false }); + await act(async () => fixture.publish()); + await act(async () => finish(gitCheckResult("new"))); + const check = within(pane).getByRole("button", { name: "Check for updates" }); + expect(check).toBeEnabled(); + fireEvent.click(check); + await waitFor(() => expect(checkGit).toHaveBeenCalledTimes(2)); + expect( + await within(pane).findByRole("button", { name: /^Update$/ }), + ).toBeVisible(); +}); + +it("keeps keyboard focus on the row action when discovery finds an update", async () => { + const fixture = reviewPluginFixture(); + Object.assign(fixture.external, { updateSource: savedGitSource }); + let finish!: (result: ReturnType) => void; + const checkGit = vi.fn( + () => + new Promise>((resolve) => { + finish = resolve; + }), + ); + Object.assign(fixture.manager, { imports: { checkGit } }); + act(fixture.publish); + await waitFor(() => expect(checkGit).toHaveBeenCalledOnce()); + screen.getByRole("button", { name: "Disable Zebra external" }).focus(); + await act(async () => finish(gitCheckResult("new"))); + expect( + await screen.findByRole("button", { name: "Update Zebra external" }), + ).toHaveFocus(); +}); + +it("does not reacquire on a new Manage plugins visit while the section stays mounted", async () => { + const navigation = { + entryId: "first", + target: { version: 1, kind: "settings", section: "plugins" }, + complete: vi.fn(), + savePosition: vi.fn(), + } as unknown as NonNullable[0]["navigation"]>; + const fixture = reviewPluginFixture({ navigation }); + Object.assign(fixture.external, { updateSource: savedGitSource }); + let revision = "current"; + const checkGit = vi.fn(async () => gitCheckResult(revision)); + Object.assign(fixture.manager, { imports: { checkGit } }); + act(fixture.publish); + await waitFor(() => expect(checkGit).toHaveBeenCalledOnce()); + revision = "new"; + Object.assign(navigation, { entryId: "second" }); + act(fixture.publish); + await act(async () => {}); + expect( + screen.queryByRole("button", { name: "Update Zebra external" }), + ).toBeNull(); + expect(checkGit).toHaveBeenCalledOnce(); +}); + +it("shows the background notice's update immediately on opening Manage plugins without another read", async () => { + const fixture = reviewPluginFixture(); + fireEvent.click(screen.getByRole("button", { name: "Profile" })); + await act(async () => {}); + Object.assign(fixture.external, { updateSource: savedGitSource }); + const checkGit = vi.fn(async () => gitCheckResult("new")); + Object.assign(fixture.manager, { imports: { checkGit } }); + await act(async () => fixture.publish()); + await screen.findByText("Update Zebra external"); + expect(checkGit).toHaveBeenCalledOnce(); + fireEvent.click(screen.getByRole("button", { name: "Manage plugins" })); + expect( + screen.getByRole("button", { name: "Update Zebra external" }), + ).toBeVisible(); + expect( + fixture.view.container.querySelector(".buzz-loading-region"), + ).toBeNull(); + await act(async () => fireEvent.focus(window)); + expect(checkGit).toHaveBeenCalledOnce(); +}); + it("reviews a requested plugin artifact in place of the add dialog and cancels it when Settings closes", async () => { const url = vi.fn(async () => ({ token: "preview", diff --git a/src/app/Settings.tsx b/src/app/Settings.tsx index 5f5ca158f5..85868a8287 100644 --- a/src/app/Settings.tsx +++ b/src/app/Settings.tsx @@ -37,6 +37,7 @@ import { type ReactNode, forwardRef, type RefObject, + useCallback, useEffect, useLayoutEffect, useMemo, @@ -52,6 +53,11 @@ import { SquaresFourIcon, SidebarRightIcon, } from "../shared/design-system/icons/index"; +import { + sharedPluginUpdateChecks, + pluginUpdateAvailable, + type PluginUpdateChecks, +} from "../plugins/update-checks"; import { canRetryPlugin, type PluginManager } from "../plugins/manager"; import type { Catalog, PluginInfo } from "../plugins/types"; import type { Communities, Membership } from "../features/communities/service"; @@ -352,10 +358,10 @@ function PluginDetails({ onCheckAccess, catalog, authorizeGit, - onUpdateAvailableChange, reviewRequested, onReviewHandled, initialUpdateAvailable, + updateChecks, holdReview, openUpdateSettings = false, sections, @@ -374,10 +380,10 @@ function PluginDetails({ catalog: Catalog; authorizeGit: Parameters[0]["authorizeGit"]; onCheckAccess(): void; - onUpdateAvailableChange(available: boolean): void; reviewRequested: boolean; onReviewHandled(): void; initialUpdateAvailable: boolean; + updateChecks: PluginUpdateChecks; holdReview: (() => () => void) | undefined; openUpdateSettings?: boolean; sections: readonly SettingsSection[]; @@ -568,7 +574,7 @@ function PluginDetails({ key={`${plugin.revision}:${JSON.stringify(plugin.updateSource)}`} initialUpdateAvailable={initialUpdateAvailable} actionTarget={actionTarget} - onUpdateAvailableChange={onUpdateAvailableChange} + updateChecks={updateChecks} reviewRequested={reviewRequested} onReviewHandled={onReviewHandled} holdReview={holdReview} @@ -1048,9 +1054,15 @@ export function Settings({ currentNavigation.current?.savePosition(PLUGIN_DETAILS, id ?? null); }; const [reviewPluginId, setReviewPluginId] = useState(); - const [updateChecks, setUpdateChecks] = useState< - Record - >({}); + const imports = plugins.imports; + const updateChecks = useMemo( + () => sharedPluginUpdateChecks(imports), + [imports], + ); + const updateSnapshot = useSyncExternalStore( + updateChecks.subscribe, + updateChecks.snapshot, + ); const [pluginImportActions, setPluginImportActions] = useState(null); const pluginTrigger = useRef(null); @@ -1235,8 +1247,7 @@ export function Settings({ const updateAvailable = !!plugins.imports && !managedBy(managed, id) && - updateChecks[id]?.revision === plugin.revision && - !!updateChecks[id]?.available; + pluginUpdateAvailable(updateSnapshot, plugin); const name = ( {plugin.manifest.name} @@ -1355,20 +1366,26 @@ export function Settings({ )} {updateAvailable ? ( - + + ) : isRequiredPlugin(plugin) ? (