import { AlertTriangle, CheckCircle2, FolderOpen, PackagePlus, Palette, RefreshCw, Settings2, Shield, ShieldAlert, Sparkles, Terminal, Trash2, } from 'lucide-react' import React, { useEffect, useMemo, useRef, useState } from 'react' import '../i18n/domains/plugins.gen' import '../i18n/domains/settings.gen' import { I18nKey, locText, t } from '../i18n' import { ActiveThemePayload, CustomThemeScheme, Locale, PluginInfo, PluginUIContributions, ScanReport, ViewContribution, } from '../types' import { Button, IconButton, Tip } from '../ui/controls' import { ConfirmDialog, Modal } from '../ui/dialog' import { PopupSelect, Segmented, Switch } from '../ui/settings' import { api } from '../wails' import { PluginMarket } from './PluginMarket' import { PluginPanelFrame } from './PluginPanelFrame' import { PluginAppIcon, PluginApprovalBody, PluginSearchInput, PluginTrustBadge } from './PluginParts' import { SchemaForm } from './SchemaForm' // Search only earns its space once the list is long enough to scan. const SEARCH_THRESHOLD = 12 // A manual refresh spins at least this long so the click visibly lands. const MIN_SPIN_MS = 500 interface Props { locale: Locale appearance: 'light' | 'dark' safeMode?: boolean runtimeCommit?: string onRefresh: () => void onError: (title: string, e: unknown) => void onThemeChanged?: () => void /** Switches the app language (used after enabling a language pack). */ onLocaleSwitch?: (l: Locale) => void onOpenView?: (view: ViewContribution, vm?: string) => void onNavigate?: (target: { page?: string; vm?: string }) => void } // VM-only settings are edited in each VM's settings. function hasAppSettings(p: PluginInfo): boolean { const schema = p.settings if (!schema) return false return Object.values(schema.properties ?? {}).some((prop) => { const scope = prop['x-scope'] || schema['x-scope'] || 'app' return scope === 'app' || scope === 'both' }) } /** Top-level Plugins & Themes management page. */ export const PluginsPage: React.FC = ({ locale, appearance, safeMode, runtimeCommit, onRefresh, onError, onThemeChanged, onLocaleSwitch, onOpenView, onNavigate, }) => { const tr = (k: I18nKey, v?: Record) => t(locale, k, v) const [activeTab, setActiveTab] = useState<'installed' | 'market'>('installed') const [query, setQuery] = useState('') const [plugins, setPlugins] = useState([]) const [contribs, setContribs] = useState(null) const [activeTheme, setActiveTheme] = useState(null) const [loading, setLoading] = useState(true) const [busyID, setBusyID] = useState('') const [approveTarget, setApproveTarget] = useState(null) const [approveReport, setApproveReport] = useState(null) const [approveChecked, setApproveChecked] = useState(false) const approveTargetIDRef = useRef('') const [settingsTarget, setSettingsTarget] = useState(null) const settingsRuntimeWarning = plugins.find((p) => p.id === settingsTarget?.id)?.runtime_warning const [settingsValues, setSettingsValues] = useState>({}) const settingsSaveQueuesRef = useRef(new Map>()) const [logTarget, setLogTarget] = useState<{ id: string; text: string } | null>(null) const [removeTarget, setRemoveTarget] = useState(null) const [disableTarget, setDisableTarget] = useState(null) const [deleteSchemeTarget, setDeleteSchemeTarget] = useState(null) // Static risk scan modal state (pre-install .zip preview or installed plugin scan) const [scanModal, setScanModal] = useState<{ mode: 'archive' | 'installed' archivePath?: string report: ScanReport } | null>(null) const [scanBusy, setScanBusy] = useState(false) // Mount the market (and touch the network) only after its tab is opened. const [marketOpened, setMarketOpened] = useState(false) const [marketRefresh, setMarketRefresh] = useState(0) const [marketBusy, setMarketBusy] = useState(false) const [reloading, setReloading] = useState(false) const [schemeEditorOpen, setSchemeEditorOpen] = useState(false) const [schemeName, setSchemeName] = useState('') const [seedAccent, setSeedAccent] = useState('#007aff') const [seedSurface, setSeedSurface] = useState('') const reload = async () => { try { const [list, ui, th] = await Promise.all([ api.ListPlugins(), api.GetPluginUIContributions(), api.GetActiveTheme(), ]) setPlugins(list ?? []) setContribs(ui) setActiveTheme(th) return { ui, th } } catch (e) { onError(tr('pluginFailLoad'), e) return null } finally { setLoading(false) } } const manualReload = async () => { setReloading(true) const started = Date.now() await reload() const wait = MIN_SPIN_MS - (Date.now() - started) if (wait > 0) await new Promise((r) => window.setTimeout(r, wait)) setReloading(false) } // Enabling a language pack means the user wants that language: switch to // its first locale unless the current one is already among them. const adoptPluginLocale = (p: PluginInfo) => { const tags = p.locales ?? [] if (tags.length > 0 && !tags.includes(locale)) onLocaleSwitch?.(tags[0]) } // Enabling a theme plugin from the market switches to its first theme only // while the user is still on the built-in default theme. const adoptPluginTheme = async ( p: PluginInfo, ui: PluginUIContributions | null | undefined, currentTheme: ActiveThemePayload | null | undefined, ) => { if (safeMode) return const curID = currentTheme?.theme_id ?? '' if (curID && curID !== 'builtin.theme.default') return const matched = (ui?.themes ?? []).find((th) => th.pluginId === p.id) if (!matched) return try { await api.SetActiveTheme(matched.id, '') setActiveTheme(await api.GetActiveTheme()) } catch (e) { onError(tr('pluginFailSwitchTheme'), e) } } const onMarketChanged = async ({ enabled }: { enabled?: PluginInfo }) => { const latest = await reload() if (enabled) { await adoptPluginTheme(enabled, latest?.ui, latest?.th) adoptPluginLocale(enabled) } onRefresh() onThemeChanged?.() } useEffect(() => { void reload() }, [safeMode, runtimeCommit, locale]) useEffect(() => { if (activeTab === 'market') setMarketOpened(true) }, [activeTab]) const togglePlugin = async (p: PluginInfo, enable: boolean, confirmed = false) => { // Disabling a plugin that still owns VMs leaves them "driver unavailable": say so first. if (!enable && p.in_use && !confirmed) { setDisableTarget(p) return } if (enable && p.needs_approval) { approveTargetIDRef.current = p.id setApproveChecked(false) setApproveReport(null) setApproveTarget(p) void api.ScanInstalledPlugin(p.id) .then((rep) => { if (approveTargetIDRef.current === p.id) setApproveReport(rep) }) .catch((e) => console.warn('[plugins] ScanInstalledPlugin failed:', p.id, e)) return } setBusyID(p.id) try { if (enable) await api.EnablePlugin(p.id, false) else await api.DisablePlugin(p.id) await reload() onRefresh() onThemeChanged?.() if (enable) adoptPluginLocale(p) } catch (e) { onError(tr('pluginFailToggle'), e) } finally { setBusyID('') } } const closeApprove = () => { approveTargetIDRef.current = '' setApproveTarget(null) setApproveReport(null) } const confirmApprove = async () => { if (!approveTarget || !approveChecked) return const target = approveTarget closeApprove() setBusyID(target.id) try { await api.EnablePlugin(target.id, true) await reload() onRefresh() onThemeChanged?.() adoptPluginLocale(target) } catch (e) { onError(tr('pluginFailEnable'), e) } finally { setBusyID('') } } const importLocalZip = async () => { try { const path = await api.PickFile(tr('pluginImportTitle'), '*.zip') if (!path) return setScanBusy(true) const report = await api.InspectPluginArchive(path) setScanModal({ mode: 'archive', archivePath: path, report }) } catch (e) { onError(tr('pluginFailScan'), e) } finally { setScanBusy(false) } } const confirmInstallScannedArchive = async () => { if (!scanModal || scanModal.mode !== 'archive' || !scanModal.archivePath || scanModal.report.hard_blocked) return const archivePath = scanModal.archivePath setScanBusy(true) try { await api.InstallPluginArchive(archivePath) setScanModal(null) await reload() onRefresh() } catch (e) { onError(tr('pluginFailImport'), e) } finally { setScanBusy(false) } } const inspectInstalledPlugin = async (p: PluginInfo) => { setScanBusy(true) try { const report = await api.ScanInstalledPlugin(p.id) setScanModal({ mode: 'installed', report }) } catch (e) { onError(tr('pluginFailScan'), e) } finally { setScanBusy(false) } } const linkDevDir = async () => { try { const dir = await api.PickDirectory(tr('pluginLinkDevTitle')) if (!dir) return await api.LinkPluginDev(dir) await reload() onRefresh() } catch (e) { onError(tr('pluginFailLinkDev'), e) } } const removePlugin = async (p: PluginInfo) => { setBusyID(p.id) try { await api.RemovePlugin(p.id, false) await reload() onRefresh() onThemeChanged?.() } catch (e) { onError(tr('pluginFailRemove'), e) } finally { setBusyID('') } } const openPluginSettings = async (p: PluginInfo) => { try { const vals = await api.GetPluginSettings(p.id, '') setSettingsValues((vals ?? {}) as Record) setSettingsTarget(p) } catch (e) { onError(tr('pluginFailLoadSettings'), e) } } const savePluginSettings = async (patch: Record) => { setSettingsValues((current) => ({ ...current, ...patch })) const target = settingsTarget if (!target) return const previous = settingsSaveQueuesRef.current.get(target.id) ?? Promise.resolve() const save = previous.catch((error) => { console.warn('[plugins] previous settings save failed:', error) }).then(() => api.SetPluginSettings(target.id, '', patch)) settingsSaveQueuesRef.current.set(target.id, save) try { await save onRefresh() } catch (e) { onError(tr('pluginFailSaveSettings'), e) } finally { if (settingsSaveQueuesRef.current.get(target.id) === save) { settingsSaveQueuesRef.current.delete(target.id) } } } const openPluginLog = async (p: PluginInfo) => { try { const txt = await api.ReadPluginLog(p.id) setLogTarget({ id: p.id, text: txt || tr('pluginLogEmpty') }) } catch (e) { onError(tr('pluginFailReadLog'), e) } } const selectTheme = async (themeID: string, schemeID = '') => { try { await api.SetActiveTheme(themeID, schemeID) await reload() onThemeChanged?.() } catch (e) { onError(tr('pluginFailSwitchTheme'), e) } } const saveScheme = async () => { if (!activeTheme || !schemeName.trim()) return const id = `custom-${Date.now()}` const scheme: CustomThemeScheme = { id, theme_id: activeTheme.theme_id, name: schemeName.trim(), appearance, seeds: { accent: seedAccent, ...(seedSurface.trim() ? { surface: seedSurface.trim() } : {}), }, } try { await api.SaveCustomThemeScheme(scheme) await api.SetActiveTheme(activeTheme.theme_id, id) setSchemeEditorOpen(false) setSchemeName('') setSeedSurface('') await reload() onThemeChanged?.() } catch (e) { onError(tr('pluginFailSaveScheme'), e) } } const deleteScheme = async (schemeID: string) => { try { await api.DeleteCustomThemeScheme(schemeID) await reload() onThemeChanged?.() } catch (e) { onError(tr('pluginFailDeleteScheme'), e) } } const q = query.trim().toLowerCase() const matchesFilter = (p: PluginInfo) => { if (!q) return true const name = locText(p.name, locale, p.id).toLowerCase() const desc = locText(p.description, locale, '').toLowerCase() return name.includes(q) || desc.includes(q) || p.id.toLowerCase().includes(q) } // System plugins are part of the host and never listed; builtins keep backend order. const builtins = useMemo(() => plugins.filter((p) => p.source === 'builtin'), [plugins]) const external = useMemo(() => plugins.filter((p) => p.source !== 'builtin'), [plugins]) const filteredBuiltins = useMemo(() => builtins.filter(matchesFilter), [builtins, q, locale]) const filteredExternal = useMemo(() => external.filter(matchesFilter), [external, q, locale]) const themes = contribs?.themes ?? [] const settingsPanels = (contribs?.panels ?? []).filter((p) => p.slot === 'settings.plugin') const presetSchemes = activeTheme?.theme?.schemes ?? [] const customSchemes = (activeTheme?.custom_schemes ?? []).filter((s) => s.theme_id === activeTheme?.theme_id) const activeCount = useMemo(() => plugins.filter((p) => p.state === 'active').length, [plugins]) const activeThemeObj = themes.find((th) => th.id === (activeTheme?.theme_id || 'builtin.theme.default')) ?? themes[0] const activeSchemeSeeds = useMemo(() => { const base = { ...(activeTheme?.theme?.seeds ?? {}) } if (activeTheme?.active_scheme) { const custom = customSchemes.find((s) => s.id === activeTheme.active_scheme) const preset = presetSchemes.find((s) => s.id === activeTheme.active_scheme) if (custom?.seeds) return { ...base, ...custom.seeds } if (preset?.seeds) return { ...base, ...preset.seeds } } return base }, [activeTheme, customSchemes, presetSchemes]) // The switch already says on/off, so only surface states that need attention. const stateBadge = (p: PluginInfo) => { if (p.state === 'degraded') return {tr('pluginStateDegraded')} if (p.state === 'failed') return {tr('pluginStateFailed')} if (p.state === 'pending' && p.enabled) return {tr('pluginStatePending')} return null } const renderRow = (p: PluginInfo) => { const isBuiltin = p.source === 'builtin' const perms = p.permissions ?? [] const highPerms = perms.filter((x) => x.level === 'high') const desc = locText(p.description, locale, '') const fault = p.error || p.degraded_reason const alert = fault || (p.needs_approval && highPerms.length > 0 ? tr('pluginHighRiskNotice') : '') return (
{locText(p.name, locale, p.id)} {stateBadge(p)}
{desc &&
{desc}
} {!isBuiltin && (
v{p.version} {perms.length > 0 && ( x.name).join(', ') })}> {tr('pluginPermCount', { count: perms.length })} )}
)} {alert && (
{fault ?
)} {p.runtime_warning && (
)}
{!isBuiltin && ( } onClick={() => void inspectInstalledPlugin(p)} /> )} {hasAppSettings(p) && ( } onClick={() => void openPluginSettings(p)} /> )} {p.log_path && ( } onClick={() => void openPluginLog(p)} /> )} {p.removable && ( } onClick={() => setRemoveTarget(p)} /> )} {p.system ? ( // Locked on: a disabled switch keeps the column aligned; the // wrapper lets the tooltip work on a disabled control. {}} /> ) : ( void togglePlugin(p, checked)} /> )}
) } const renderScanReportBody = (report: ScanReport) => { const hard = report.hard_findings ?? [] const caps = report.capabilities ?? [] const pending = report.pending_findings ?? [] const execs = report.executables ?? [] return (
{report.hard_blocked ?
{report.native_exec_notice && locText(report.native_exec_notice, locale, '') && (
)} {hard.length > 0 && (
{tr('pluginScanHardSection')}
{hard.map((f, idx) => (
{f.check} {f.target && {f.target}}
{locText(f.localized, locale, f.message)}
))}
)} {caps.length > 0 && (
{tr('pluginScanCapabilitiesSection')}
{caps.map((c) => (
{c.level.toUpperCase()} {locText(c.title, locale, c.id)} {c.id}
{locText(c.summary, locale, '')}
{(c.examples?.length ?? 0) > 0 && (
{c.examples!.map((ex, i) =>
· {ex}
)} {(c.extra_count ?? 0) > 0 && (
· {tr('pluginScanMoreItems', { count: c.extra_count! })}
)}
)}
))}
)} {(pending.length > 0 || execs.length > 0) && (
{tr('pluginScanAdvisoriesSection')}
{pending.map((f, idx) => (
{f.check} {f.target && {f.target}}
{locText(f.localized, locale, f.message)}
))} {execs.map((ex) => (
{ex.declared ? 'EXE' : 'UNLISTED'} {ex.path}
SHA-256: {ex.sha256}
))}
)}
) } const showThemeHero = themes.length > 1 && !q const showSearch = plugins.length > SEARCH_THRESHOLD const noMatches = !loading && !!q && filteredBuiltins.length === 0 && filteredExternal.length === 0 const previewAccent = activeSchemeSeeds.accent || 'var(--accent)' const previewSurface = activeSchemeSeeds.surface || 'var(--surface-canvas)' return (

{tr('sidebarPlugins')}

{!loading && {tr('pluginActiveCount', { active: activeCount, total: plugins.length })}}
{activeTab === 'installed' && showSearch && ( )} } disabled={activeTab === 'market' ? marketBusy : reloading} onClick={() => activeTab === 'market' ? setMarketRefresh((n) => n + 1) : void manualReload()} /> } onClick={linkDevDir} />
{marketOpened && ( )} {activeTab === 'installed' && ( <> {showThemeHero && (
{tr('pluginThemeSection')}
)} {noMatches &&
{tr('pluginSearchEmpty')}
} {filteredExternal.length > 0 && (
{tr('pluginExternalSection')} {filteredExternal.length}
{filteredExternal.map(renderRow)}
)} {(loading || filteredBuiltins.length > 0) && (
{tr('pluginBuiltinSection')} {!loading && {filteredBuiltins.length}}
{loading ? (
{[0, 1, 2].map((i) => (
)} {settingsPanels.length > 0 && contribs?.asset_token ? (
{tr('pluginPanelsSection')}
{settingsPanels.map((panel) => ( ))}
) : (
)} )} {scanModal && ( { if (!scanBusy) setScanModal(null) }} >
{renderScanReportBody(scanModal.report)}
{scanModal.report.tier ? `${scanModal.report.tier} · ${scanModal.report.trust || 'community'}` : ''} {scanModal.mode === 'archive' ? ( <> ) : ( )}
)} {approveTarget && (
)} {settingsTarget && settingsTarget.settings && ( setSettingsTarget(null)} >
{settingsRuntimeWarning && (
)} void savePluginSettings(patch)} />
)} {disableTarget && ( setDisableTarget(null)} onConfirm={() => { const target = disableTarget setDisableTarget(null) void togglePlugin(target, false, true) }} >
{locText(disableTarget.name, locale, disableTarget.id)}
)} {removeTarget && ( setRemoveTarget(null)} onConfirm={() => { const target = removeTarget setRemoveTarget(null) void removePlugin(target) }} >
{removeTarget.id}@{removeTarget.version}
)} {deleteSchemeTarget && ( setDeleteSchemeTarget(null)} onConfirm={() => { const target = deleteSchemeTarget setDeleteSchemeTarget(null) void deleteScheme(target.id) }} /> )} {logTarget && ( setLogTarget(null)} >
{logTarget.text}
)} {schemeEditorOpen && ( setSchemeEditorOpen(false)} >
)}
) }