From e6dd68b209b4b3e45175a9db6ba71488f0abb047 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=99=88=E5=A5=87?= <16399091+binaricat@users.noreply.github.com> Date: Mon, 26 Oct 2026 17:00:56 +0000 Subject: [PATCH] feat(plugins): check published updates from bound source catalogs --- application/i18n/locales/en/core.ts | 6 ++ application/i18n/locales/zh-CN/core.ts | 6 ++ application/i18n/locales/zh-TW/core.ts | 6 ++ application/state/usePluginManager.ts | 3 +- application/state/usePluginUpdateCheck.ts | 52 ++++++++++++++ .../settings/tabs/PluginSettingsLanding.tsx | 15 ++-- .../PluginUpdateCheck.interaction.test.tsx | 60 ++++++++++++++++ .../SettingsPluginsTab.interaction.test.tsx | 8 +++ .../settings/tabs/SettingsPluginsTab.tsx | 4 +- .../services/pluginUpdateCheck.test.ts | 71 +++++++++++++++++++ infrastructure/services/pluginUpdateCheck.ts | 64 +++++++++++++++++ package-lock.json | 1 + package.json | 1 + 13 files changed, 291 insertions(+), 6 deletions(-) create mode 100644 application/state/usePluginUpdateCheck.ts create mode 100644 components/settings/tabs/PluginUpdateCheck.interaction.test.tsx create mode 100644 infrastructure/services/pluginUpdateCheck.test.ts create mode 100644 infrastructure/services/pluginUpdateCheck.ts diff --git a/application/i18n/locales/en/core.ts b/application/i18n/locales/en/core.ts index f2a8383e6..1d20bd2da 100644 --- a/application/i18n/locales/en/core.ts +++ b/application/i18n/locales/en/core.ts @@ -1,6 +1,12 @@ import type { Messages } from '../types'; export const enCoreMessages: Messages = { + "settings.plugins.landing.checkUpdates": "Check for updates", + "settings.plugins.landing.checkingUpdates": "Checking…", + "settings.plugins.landing.updateSummary": "Checked: {checked} · Published updates: {updates} · Not checked: {skipped}.", + "settings.plugins.landing.updateSourcesFailed": "Unavailable sources: {count}.", + "settings.plugins.landing.updateReview": "Review updates in the plugin manager before installing.", + "settings.plugins.landing.updateAvailable": "Version {version} available", "settings.plugins.landing.loading": "Loading installed plugins…", "settings.plugins.landing.settingsUnavailable": "No plugin settings are available in this context.", "settings.plugins.landing.options": "Plugin options", diff --git a/application/i18n/locales/zh-CN/core.ts b/application/i18n/locales/zh-CN/core.ts index 19c2ac57d..c2c477a7d 100644 --- a/application/i18n/locales/zh-CN/core.ts +++ b/application/i18n/locales/zh-CN/core.ts @@ -1,6 +1,12 @@ import type { Messages } from '../types'; export const zhCNCoreMessages: Messages = { + "settings.plugins.landing.checkUpdates": "检查更新", + "settings.plugins.landing.checkingUpdates": "正在检查…", + "settings.plugins.landing.updateSummary": "已检查:{checked} · 已发布更新:{updates} · 未检查:{skipped}。", + "settings.plugins.landing.updateSourcesFailed": "不可用来源:{count}。", + "settings.plugins.landing.updateReview": "安装前请在插件管理器中查看更新详情。", + "settings.plugins.landing.updateAvailable": "可更新至 {version}", "settings.plugins.landing.loading": "正在载入已安装插件…", "settings.plugins.landing.settingsUnavailable": "当前上下文中没有可用的插件设置。", "settings.plugins.landing.options": "插件选项", diff --git a/application/i18n/locales/zh-TW/core.ts b/application/i18n/locales/zh-TW/core.ts index 51550691e..a63fb6c22 100644 --- a/application/i18n/locales/zh-TW/core.ts +++ b/application/i18n/locales/zh-TW/core.ts @@ -1,6 +1,12 @@ import type { Messages } from '../types'; export const zhTWCoreMessages: Messages = { + "settings.plugins.landing.checkUpdates": "檢查更新", + "settings.plugins.landing.checkingUpdates": "正在檢查…", + "settings.plugins.landing.updateSummary": "已檢查:{checked} · 已發佈更新:{updates} · 未檢查:{skipped}。", + "settings.plugins.landing.updateSourcesFailed": "無法使用的來源:{count}。", + "settings.plugins.landing.updateReview": "安裝前請在外掛管理器中查看更新詳情。", + "settings.plugins.landing.updateAvailable": "可更新至 {version}", "settings.plugins.landing.loading": "正在載入已安裝外掛…", "settings.plugins.landing.settingsUnavailable": "目前內容中沒有可用的外掛設定。", "settings.plugins.landing.options": "外掛選項", diff --git a/application/state/usePluginManager.ts b/application/state/usePluginManager.ts index 95787f2c2..a8f5d4b0d 100644 --- a/application/state/usePluginManager.ts +++ b/application/state/usePluginManager.ts @@ -10,7 +10,8 @@ export function usePluginManager() { const [error, setError] = useState(null); const generation = useRef(0); const mutation = useRef(false); - const refresh = useCallback(async () => { + const refresh = useCallback(async (options?: { clearError?: boolean }) => { + if (options?.clearError) setError(null); const current = ++generation.current; try { const bridge = netcattyBridge.get(); diff --git a/application/state/usePluginUpdateCheck.ts b/application/state/usePluginUpdateCheck.ts new file mode 100644 index 000000000..35540e750 --- /dev/null +++ b/application/state/usePluginUpdateCheck.ts @@ -0,0 +1,52 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { checkPluginUpdates, type PluginUpdateCheckResult } from '../../infrastructure/services/pluginUpdateCheck'; +import { netcattyBridge } from '../../infrastructure/services/netcattyBridge'; + +/** Manual catalog checks only; no scheduler, install or permission mutation. */ +export function usePluginUpdateCheck(plugins: readonly NetcattyInstalledPlugin[]) { + const [result, setResult] = useState(null); + const [error, setError] = useState(null); + const [busy, setBusy] = useState(false); + const pending = useRef(false); + const mounted = useRef(false); + useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []); + const generation = useRef(0); + const identityKey = useMemo(() => JSON.stringify(plugins.map((plugin) => [ + plugin.id, plugin.activeVersion, plugin.archiveSha256, plugin.source?.id, + plugin.source?.kind, plugin.source?.origin, + ])), [plugins]); + useEffect(() => { + generation.current++; + setResult(null); + setError(null); + const requests = generation; + return () => { requests.current++; }; + }, [identityKey]); + useEffect(() => { + const invalidate = () => { + generation.current++; + setResult(null); + setError(null); + }; + const unsubscribe = netcattyBridge.get()?.onPluginContributionsChanged?.(invalidate); + window.addEventListener('netcatty:plugin-packages-changed', invalidate); + return () => { unsubscribe?.(); window.removeEventListener('netcatty:plugin-packages-changed', invalidate); }; + }, []); + const check = useCallback(async () => { + if (pending.current) return; + pending.current = true; + const current = generation.current; + setBusy(true); setError(null); setResult(null); + try { + const value = await checkPluginUpdates(netcattyBridge.require()); + if (mounted.current && current === generation.current) setResult(value); + } catch (cause) { + if (mounted.current && current === generation.current) setError(cause instanceof Error ? cause.message : String(cause)); + } finally { + pending.current = false; + // This component may still be mounted with a refreshed package list. + if (mounted.current) setBusy(false); + } + }, []); + return { result, error, busy, check }; +} diff --git a/components/settings/tabs/PluginSettingsLanding.tsx b/components/settings/tabs/PluginSettingsLanding.tsx index e8bb9f7d3..a2ddb8b51 100644 --- a/components/settings/tabs/PluginSettingsLanding.tsx +++ b/components/settings/tabs/PluginSettingsLanding.tsx @@ -1,6 +1,7 @@ import React, { useCallback, useMemo, useState } from 'react'; import { RefreshCw, Settings2 } from 'lucide-react'; import { useI18n } from '../../../application/i18n/I18nProvider'; +import type { usePluginUpdateCheck } from '../../../application/state/usePluginUpdateCheck'; import type { usePluginManager } from '../../../application/state/usePluginManager'; import { Button } from '../../ui/button'; import { Input } from '../../ui/input'; @@ -10,11 +11,12 @@ import { PluginLogSettings } from './PluginLogSettings'; type Manager = ReturnType; -export function PluginSettingsLanding({ manager, settingsAvailable, settingsError, managerButtonRef, onManage }: { +export function PluginSettingsLanding({ manager, settingsAvailable, settingsError, managerButtonRef, updates, onManage }: { manager: Manager; settingsAvailable: ReadonlySet; settingsError?: string; managerButtonRef?: React.Ref; + updates?: ReturnType; onManage: (pluginId: string | null, opener: HTMLElement) => void; }) { const { t, resolvedLocale } = useI18n(); @@ -47,9 +49,12 @@ export function PluginSettingsLanding({ manager, settingsAvailable, settingsErro - void manager.refresh().catch(() => {})}> - }> + + {updates && } + + }> + {updates?.error &&

{updates.error}

} + {updates?.result &&

{t('settings.plugins.landing.updateSummary').replace('{checked}', String(updates.result.checked)).replace('{updates}', String(updates.result.updates.length)).replace('{skipped}', String(updates.result.skipped))}{updates.result.failedSources > 0 && ` ${t('settings.plugins.landing.updateSourcesFailed').replace('{count}', String(updates.result.failedSources))}`} {t('settings.plugins.landing.updateReview')}

} {settingsError &&

{settingsError}

} {manager.error &&

{manager.error}

} {!manager.statusKnown && !manager.error &&

{t('settings.plugins.landing.loading')}

} @@ -61,12 +66,14 @@ export function PluginSettingsLanding({ manager, settingsAvailable, settingsErro {visible.map((plugin) => { const name = nameOf(plugin); const description = localized(plugin.manifest?.description); + const availableUpdate = updates?.result?.updates.find((item) => item.pluginId === plugin.id && item.sourceId === plugin.source?.id); const declaredSettings = Boolean(plugin.manifest?.contributes?.settings?.length || plugin.manifest?.contributes?.views?.some((view) => view.location === 'settings')); return } label={ {name} {plugin.activeVersion && {plugin.activeVersion}} } description={<> {[plugin.manifest?.publisher, sourceOf(plugin), statusOf(plugin)].filter(Boolean).join(' · ')} + {availableUpdate && {t('settings.plugins.landing.updateAvailable').replace('{version}', availableUpdate.availableVersion)}} {description && {description}} }>
diff --git a/components/settings/tabs/PluginUpdateCheck.interaction.test.tsx b/components/settings/tabs/PluginUpdateCheck.interaction.test.tsx new file mode 100644 index 000000000..334571edc --- /dev/null +++ b/components/settings/tabs/PluginUpdateCheck.interaction.test.tsx @@ -0,0 +1,60 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { JSDOM } from 'jsdom'; + +test('manual update action coalesces clicks, never runs on mount, and reports incomplete source checks honestly', async () => { + const dom = new JSDOM('
', { pretendToBeVisual: true, url: 'http://localhost' }); + const previous = new Map(); + const install = (key: string, value: unknown) => { + previous.set(key, Object.getOwnPropertyDescriptor(globalThis, key)); + Object.defineProperty(globalThis, key, { configurable: true, writable: true, value }); + }; + for (const key of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent']) install(key, key === 'window' ? dom.window : dom.window[key as keyof typeof dom.window]); + install('IS_REACT_ACT_ENVIRONMENT', true); + const { default: React, act } = await import('react'); + const { createRoot } = await import('react-dom/client'); + const { I18nProvider } = await import('../../../application/i18n/I18nProvider'); + const { PluginSettingsLanding } = await import('./PluginSettingsLanding'); + const { usePluginUpdateCheck } = await import('../../../application/state/usePluginUpdateCheck'); + const root = createRoot(document.getElementById('root')!); + const source: NetcattyPluginSource = { id: 'official', kind: 'official', name: 'Official source', origin: 'https://plugins.example.com', enabled: true }; + const plugin = { id: 'com.example.alpha', enabled: false, activeVersion: '1.0.0', archiveSha256: 'a'.repeat(64), source, + manifest: { manifestVersion: 1, id: 'com.example.alpha', name: 'Alpha', version: '1.0.0', publisher: 'example', engines: { netcatty: '>=0.0.0', api: '>=0.1.0-internal <0.2.0' }, main: { browser: 'index.js' } }, + runtime: { status: 'stopped', kind: null, lastError: null, quarantinedAt: null } } as NetcattyInstalledPlugin; + const plugins = [plugin]; + const manager = { plugins, available: true, statusKnown: true, busy: false, error: null, credentialStorageAvailable: true, async refresh() {}, async setEnabled() {}, async importPackage() {}, async uninstall() {} }; + let catalogReads = 0; let mutations = 0; let offline = false; + let release: () => void; + const gate = new Promise((resolve) => { release = resolve; }); + Object.assign(dom.window, { netcatty: { + async listPlugins() { return plugins; }, async listPluginSources() { return [source]; }, + async listPluginCatalog(id: string) { assert.equal(id, source.id); catalogReads++; await gate; return { entries: [{ id: plugin.id, version: '1.1.0', artifact: { url: 'https://plugins.example.com/synthetic.ncpkg', sha256: 'b'.repeat(64) } }], source: offline ? 'cached' : 'registry', error: offline ? 'synthetic offline' : null }; }, + async getPluginLogStatus() { return { saveToDisk: false, verbose: false, droppedRecords: 0, writeErrors: 0, pendingBytes: 0, maxBytes: 3145728, retentionDays: 7 }; }, + async installCatalogPlugin() { mutations++; }, async setPluginEnabled() { mutations++; }, async checkForUpdates() { mutations++; }, + } }); + function Page() { const updates = usePluginUpdateCheck(plugins); return {}} />; } + const check = () => [...document.querySelectorAll('button')].find((button) => button.textContent === 'Check for updates')!; + try { + await act(async () => root.render()); + assert.equal(catalogReads, 0, 'rendering settings does not schedule checks'); + await act(async () => { const button = check(); button.click(); button.click(); }); + assert.equal(catalogReads, 1); + assert.equal([...document.querySelectorAll('button')].find((button) => button.textContent === 'Checking…')!.disabled, true); + await act(async () => release()); + assert.match(document.body.textContent!, /Published updates: 1/); + assert.match(document.body.textContent!, /Version 1.1.0 available/); + assert.equal(mutations, 0); + await act(async () => window.dispatchEvent(new Event('netcatty:plugin-packages-changed'))); + assert.doesNotMatch(document.body.textContent!, /Version 1.1.0 available/, 'source/package changes invalidate prior results'); + offline = true; + await act(async () => check().click()); + assert.match(document.body.textContent!, /Checked: 0/); + assert.match(document.body.textContent!, /Not checked: 1/); + assert.match(document.body.textContent!, /Unavailable sources: 1/); + assert.doesNotMatch(document.body.textContent!, /Version 1.1.0 available/); + assert.equal(mutations, 0); + } finally { + await act(async () => root.unmount()); dom.window.close(); + for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); } + } +}); diff --git a/components/settings/tabs/SettingsPluginsTab.interaction.test.tsx b/components/settings/tabs/SettingsPluginsTab.interaction.test.tsx index 6c8bc6ef9..0d018f5ce 100644 --- a/components/settings/tabs/SettingsPluginsTab.interaction.test.tsx +++ b/components/settings/tabs/SettingsPluginsTab.interaction.test.tsx @@ -27,6 +27,7 @@ test('landing settings entry targets the declared plugin and a manager tab round Object.assign(dom.window, { netcatty: { async getPluginRuntimeStatus() { return { available: true, experimental: true, credentialStorageAvailable: true }; }, async listPlugins() { return [plugin]; }, + async setPluginEnabled() { throw new Error('Synthetic management failure'); }, async getPluginLogStatus() { return { saveToDisk: false, verbose: false, droppedRecords: 0, writeErrors: 0, pendingBytes: 0, maxBytes: 3145728, retentionDays: 7 }; }, async getPluginContributions() { return { locale: 'en', plugins: [{ id: plugin.id, version: '1.0.0', displayName: 'Alpha', description: 'Synthetic plugin', commands: [], keybindings: [], menus: [], views: [], settings: [{ id: 'com.example.alpha.setting', label: 'Alpha setting', control: 'text', scope: 'application', scopeId: 'application', value: 'synthetic', visible: true, configured: true }] }] }; }, async getPluginScopeCatalog() { return { workspace: [], host: [], session: [], device: [] }; }, @@ -58,6 +59,13 @@ test('landing settings entry targets the declared plugin and a manager tab round await act(async () => { document.activeElement!.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })); await settle(); }); assert.equal(document.querySelector('[role=dialog]'), null); assert.equal(document.activeElement, settings); + const toggle = document.querySelector('button[aria-label="Disable Alpha"]')!; + await act(async () => { toggle.click(); await settle(); }); + assert.match(document.querySelector('[role=alert]')!.textContent!, /Synthetic management failure/); + assert.equal(toggle.getAttribute('aria-checked'), 'true', 'failed mutation retains actual host state'); + const refresh = document.querySelector('button[aria-label="Refresh installed plugins"]')!; + await act(async () => { refresh.click(); await settle(); }); + assert.equal(document.querySelector('[role=alert]'), null, 'explicit successful refresh clears an acknowledged manager error'); } finally { await act(async () => root.unmount()); dom.window.close(); for (const [key, descriptor] of previous) { if (descriptor) Object.defineProperty(globalThis, key, descriptor); else Reflect.deleteProperty(globalThis, key); } diff --git a/components/settings/tabs/SettingsPluginsTab.tsx b/components/settings/tabs/SettingsPluginsTab.tsx index a81934770..a04229be4 100644 --- a/components/settings/tabs/SettingsPluginsTab.tsx +++ b/components/settings/tabs/SettingsPluginsTab.tsx @@ -1,4 +1,5 @@ import { PluginThirdPartyMarket } from './PluginThirdPartyMarket'; +import { usePluginUpdateCheck } from '../../../application/state/usePluginUpdateCheck'; import { usePluginManager } from '../../../application/state/usePluginManager'; import { PluginManagementDialog } from './PluginManagementDialog'; import { PluginMarketplace } from './PluginMarketplace'; @@ -399,6 +400,7 @@ function PluginManagementContent({ handoff, manager, initialSelectedId }: { export default function SettingsPluginsTab() { const manager = usePluginManager(); + const updates = usePluginUpdateCheck(manager.plugins); const [open, setOpen] = useState(false); const [initialSelectedId, setInitialSelectedId] = useState(null); const opener = useRef(null); @@ -410,7 +412,7 @@ export default function SettingsPluginsTab() { return ( - { + { opener.current = element; setInitialSelectedId(pluginId); setOpen(true); diff --git a/infrastructure/services/pluginUpdateCheck.test.ts b/infrastructure/services/pluginUpdateCheck.test.ts new file mode 100644 index 000000000..023a56dde --- /dev/null +++ b/infrastructure/services/pluginUpdateCheck.test.ts @@ -0,0 +1,71 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { checkPluginUpdates } from './pluginUpdateCheck'; + +const official: NetcattyPluginSource = { id: 'official', kind: 'official', name: 'Official source', origin: 'https://plugins.example.com', enabled: true }; +const third: NetcattyPluginSource = { id: 'third-party:synthetic', kind: 'third-party', name: 'Synthetic source', origin: 'https://synthetic.example.com', enabled: true }; +const local: NetcattyPluginSource = { id: 'local', kind: 'local', name: 'Local import', origin: null }; +const plugin = (id: string, version: string, source?: NetcattyPluginSource): NetcattyInstalledPlugin => ({ id, activeVersion: version, source, archiveSha256: 'a'.repeat(64), enabled: false, manifest: null, runtime: { status: 'stopped', kind: null, lastError: null, quarantinedAt: null } }); +const entry = (id: string, version: string) => ({ id, version, artifact: { url: 'https://plugins.example.com/synthetic.ncpkg', sha256: 'b'.repeat(64) } }) as NetcattyPluginCatalogEntry; +const catalog = (entries: NetcattyPluginCatalogEntry[]): NetcattyPluginCatalogSnapshot => ({ source: 'registry', error: null, entries }); + +test('update checks compare semantic versions within each host-bound source and never mutate or fetch directly', async () => { + const installed = [plugin('com.example.alpha', '1.9.0', official), plugin('com.example.beta', '2.0.0-beta.1', third), plugin('com.example.local', '1.0.0', local), plugin('com.example.unknown', '1.0.0')]; + const requested: string[] = []; + let mutations = 0; + const bridge = { + async listPlugins() { return installed; }, async listPluginSources() { return [official, third]; }, + async listPluginCatalog(sourceId?: string) { + requested.push(sourceId!); + return sourceId === official.id ? catalog([entry(installed[0].id, '1.10.0'), entry(installed[1].id, '99.0.0')]) : catalog([entry(installed[1].id, '2.0.0')]); + }, + async installCatalogPlugin() { mutations++; }, async setPluginEnabled() { mutations++; }, async checkForUpdates() { mutations++; }, + }; + const previous = globalThis.fetch; + globalThis.fetch = async () => { throw new Error('Direct fetching is forbidden'); }; + try { + const result = await checkPluginUpdates(bridge); + assert.deepEqual(requested, [official.id, third.id]); + assert.equal(result.checked, 2); + assert.equal(result.skipped, 2); + assert.equal(result.failedSources, 0); + assert.deepEqual(result.updates, [ + { pluginId: installed[0].id, sourceId: official.id, installedVersion: '1.9.0', availableVersion: '1.10.0' }, + { pluginId: installed[1].id, sourceId: third.id, installedVersion: '2.0.0-beta.1', availableVersion: '2.0.0' }, + ]); + assert.equal(mutations, 0); + } finally { globalThis.fetch = previous; } +}); + +test('cached, failed, disabled and unpublished sources do not claim an update check succeeded', async () => { + const disabled = { ...third, enabled: false }; + const installed = [plugin('com.example.alpha', '1.0.0', official), plugin('com.example.beta', '1.0.0', disabled)]; + const calls: string[] = []; + const result = await checkPluginUpdates({ async listPlugins() { return installed; }, async listPluginSources() { return [official, disabled]; }, + async listPluginCatalog(sourceId) { calls.push(sourceId!); return { source: 'cached', error: 'synthetic offline', entries: [entry(installed[0].id, '2.0.0')] }; } }); + assert.deepEqual(calls, [official.id]); + assert.equal(result.checked, 0); assert.equal(result.skipped, 2); assert.equal(result.failedSources, 1); assert.deepEqual(result.updates, []); + const unpublished = await checkPluginUpdates({ async listPlugins() { return [installed[0]]; }, async listPluginSources() { return [official]; }, async listPluginCatalog() { return catalog([{ ...entry(installed[0].id, '2.0.0'), artifact: undefined }]); } }); + assert.equal(unpublished.checked, 0); assert.equal(unpublished.skipped, 1); +}); + +test('source or installed package replacement during an asynchronous catalog read invalidates results', async () => { + for (const change of ['source', 'hash', 'disabled']) { + const before = plugin('com.example.alpha', '1.0.0', official); + let installed = [before]; let sources = [official]; + const result = await checkPluginUpdates({ async listPlugins() { return installed; }, async listPluginSources() { return sources; }, async listPluginCatalog() { + if (change === 'source') { installed = [{ ...before, source: third }]; sources = [third]; } + if (change === 'hash') installed = [{ ...before, archiveSha256: 'c'.repeat(64) }]; + if (change === 'disabled') sources = [{ ...official, enabled: false }]; + return catalog([entry(before.id, '2.0.0')]); + } }); + assert.deepEqual(result.updates, [], change); assert.equal(result.checked, 0, change); assert.equal(result.skipped, 1, change); + } +}); + +test('a failing source leaves other fresh source results intact and missing APIs fail explicitly', async () => { + const installed = [plugin('com.example.alpha', '1.0.0', official), plugin('com.example.beta', '1.0.0', third)]; + const result = await checkPluginUpdates({ async listPlugins() { return installed; }, async listPluginSources() { return [official, third]; }, async listPluginCatalog(id) { if (id === third.id) throw new Error('synthetic source unavailable'); return catalog([entry(installed[0].id, '1.1.0')]); } }); + assert.equal(result.failedSources, 1); assert.equal(result.checked, 1); assert.equal(result.skipped, 1); assert.equal(result.updates[0].sourceId, official.id); + await assert.rejects(checkPluginUpdates({}), /unavailable/); +}); diff --git a/infrastructure/services/pluginUpdateCheck.ts b/infrastructure/services/pluginUpdateCheck.ts new file mode 100644 index 000000000..addfc948e --- /dev/null +++ b/infrastructure/services/pluginUpdateCheck.ts @@ -0,0 +1,64 @@ +import { gt, valid } from 'semver'; + +export interface PluginUpdateCandidate { + pluginId: string; + sourceId: string; + installedVersion: string; + availableVersion: string; +} +export interface PluginUpdateCheckResult { + checkedAt: number; + checked: number; + updates: PluginUpdateCandidate[]; + skipped: number; + failedSources: number; +} + +type UpdateBridge = Pick; +const sameSource = (left?: NetcattyPluginSource, right?: NetcattyPluginSource) => Boolean(left && right + && left.id === right.id && left.kind === right.kind && left.origin === right.origin); +const sameInstallation = (left: NetcattyInstalledPlugin, right?: NetcattyInstalledPlugin) => Boolean(right + && left.activeVersion === right.activeVersion && left.archiveSha256 === right.archiveSha256 + && sameSource(left.source, right.source)); + +/** Read-only: host catalogs own fetching, source consent, bounds and cache status. */ +export async function checkPluginUpdates(bridge: UpdateBridge): Promise { + if (!bridge.listPlugins || !bridge.listPluginSources || !bridge.listPluginCatalog) throw new Error('Plugin update checks are unavailable'); + const installed = await bridge.listPlugins(); + const sources = await bridge.listPluginSources(); + const groups = new Map(); + for (const plugin of installed) { + const source = sources.find((item) => sameSource(plugin.source, item)); + // Local/unknown/removed/disabled bindings never fall back to another market. + if (!plugin.activeVersion || !valid(plugin.activeVersion) || !source || source.kind === 'local' || source.enabled === false) continue; + groups.set(source.id, [...(groups.get(source.id) ?? []), plugin]); + } + const checked = new Set(); + const candidates: PluginUpdateCandidate[] = []; + let failedSources = 0; + // At most one catalog read at a time; the host supports at most 32 custom sources. + for (const [sourceId, plugins] of groups) { + try { + const catalog = await bridge.listPluginCatalog(sourceId); + if (catalog.error || catalog.source !== 'registry') { failedSources++; continue; } + for (const plugin of plugins) { + const entry = catalog.entries.find((item) => item.id === plugin.id && item.artifact); + if (!entry || !valid(entry.version)) continue; + checked.add(plugin.id); + if (gt(entry.version, plugin.activeVersion!)) candidates.push({ + pluginId: plugin.id, sourceId, installedVersion: plugin.activeVersion!, availableVersion: entry.version, + }); + } + } catch { failedSources++; } + } + // Revalidate host-owned source/package binding after every asynchronous read. + // This publishes metadata only; installation stays in the existing manager flow. + const current = await bridge.listPlugins(); + const currentSources = await bridge.listPluginSources(); + for (const plugin of installed) { + const source = currentSources.find((item) => item.id === plugin.source?.id); + if (!sameInstallation(plugin, current.find((item) => item.id === plugin.id)) || !sameSource(plugin.source, source) || source?.enabled === false) checked.delete(plugin.id); + } + const updates = candidates.filter((candidate) => checked.has(candidate.pluginId)); + return { checkedAt: Date.now(), checked: checked.size, updates, skipped: current.length - checked.size, failedSources }; +} diff --git a/package-lock.json b/package-lock.json index e650e190c..0eea407e0 100644 --- a/package-lock.json +++ b/package-lock.json @@ -32,6 +32,7 @@ "jsqr": "^1.4.0", "node-pty": "1.1.0", "re2js": "2.8.6", + "semver": "^7.7.3", "serialport": "^13.0.0", "socks-proxy-agent": "^8.0.5", "ssh2-sftp-client": "^12.0.1", diff --git a/package.json b/package.json index b59cb79fc..c0ca65f41 100644 --- a/package.json +++ b/package.json @@ -96,6 +96,7 @@ "jsqr": "^1.4.0", "node-pty": "1.1.0", "re2js": "2.8.6", + "semver": "^7.7.3", "serialport": "^13.0.0", "socks-proxy-agent": "^8.0.5", "ssh2-sftp-client": "^12.0.1",