Files
Reims-Go/frontend/src/components/PluginsPage.tsx
T
千川白浪 7b76330d28 Merge pull request #163 from Nwflower/refactor/entropy-convergence
架构降熵:合并重复实现、拆分过大的文件、删除不再使用的代码,并用测试守护这些规则。
2026-12-04 16:10:06 +08:00

1009 lines
39 KiB
TypeScript

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<Props> = ({
locale, appearance, safeMode, runtimeCommit, onRefresh, onError, onThemeChanged, onLocaleSwitch, onOpenView, onNavigate,
}) => {
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
const [activeTab, setActiveTab] = useState<'installed' | 'market'>('installed')
const [query, setQuery] = useState('')
const [plugins, setPlugins] = useState<PluginInfo[]>([])
const [contribs, setContribs] = useState<PluginUIContributions | null>(null)
const [activeTheme, setActiveTheme] = useState<ActiveThemePayload | null>(null)
const [loading, setLoading] = useState(true)
const [busyID, setBusyID] = useState('')
const [approveTarget, setApproveTarget] = useState<PluginInfo | null>(null)
const [approveReport, setApproveReport] = useState<ScanReport | null>(null)
const [approveChecked, setApproveChecked] = useState(false)
const approveTargetIDRef = useRef('')
const [settingsTarget, setSettingsTarget] = useState<PluginInfo | null>(null)
const settingsRuntimeWarning = plugins.find((p) => p.id === settingsTarget?.id)?.runtime_warning
const [settingsValues, setSettingsValues] = useState<Record<string, unknown>>({})
const settingsSaveQueuesRef = useRef(new Map<string, Promise<void>>())
const [logTarget, setLogTarget] = useState<{ id: string; text: string } | null>(null)
const [removeTarget, setRemoveTarget] = useState<PluginInfo | null>(null)
const [disableTarget, setDisableTarget] = useState<PluginInfo | null>(null)
const [deleteSchemeTarget, setDeleteSchemeTarget] = useState<CustomThemeScheme | null>(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<string, unknown>)
setSettingsTarget(p)
} catch (e) {
onError(tr('pluginFailLoadSettings'), e)
}
}
const savePluginSettings = async (patch: Record<string, unknown>) => {
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 <span className="badge rg-p-badge badge-warn">{tr('pluginStateDegraded')}</span>
if (p.state === 'failed') return <span className="badge rg-p-badge badge-warn">{tr('pluginStateFailed')}</span>
if (p.state === 'pending' && p.enabled) return <span className="badge rg-p-badge">{tr('pluginStatePending')}</span>
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 (
<div className={`row plugin-row${p.enabled ? ' is-enabled' : ''}`} key={p.id}>
<PluginAppIcon plugin={p} size="md" />
<div className="row-main">
<div className="row-title">
<span className="plugin-row-name">{locText(p.name, locale, p.id)}</span>
{stateBadge(p)}
</div>
{desc && <div className="row-sub plugin-row-desc" title={desc}>{desc}</div>}
{!isBuiltin && (
<div className="row-sub plugin-row-meta">
<PluginTrustBadge locale={locale} trust={p.trust} publisher={p.publisher} />
<span className="mono">v{p.version}</span>
{perms.length > 0 && (
<Tip label={tr('pluginPermissionsLabel', { list: perms.map((x) => x.name).join(', ') })}>
<span>{tr('pluginPermCount', { count: perms.length })}</span>
</Tip>
)}
</div>
)}
{alert && (
<div className="row-sub plugin-row-alert">
{fault ? <AlertTriangle size={12} aria-hidden="true" /> : <ShieldAlert size={12} aria-hidden="true" />}
<span>{alert}</span>
</div>
)}
{p.runtime_warning && (
<div className="row-sub plugin-row-alert">
<AlertTriangle size={12} aria-hidden="true" />
<span>{p.runtime_warning}</span>
</div>
)}
</div>
<div className="row-right">
{!isBuiltin && (
<IconButton label={tr('pluginScanInspect')} icon={<Shield size={15} />} onClick={() => void inspectInstalledPlugin(p)} />
)}
{hasAppSettings(p) && (
<IconButton label={tr('pluginSettings')} icon={<Settings2 size={15} />} onClick={() => void openPluginSettings(p)} />
)}
{p.log_path && (
<IconButton label={tr('pluginViewLog')} icon={<Terminal size={15} />} onClick={() => void openPluginLog(p)} />
)}
{p.removable && (
<IconButton
disabled={p.in_use || busyID === p.id}
label={p.in_use ? tr('pluginInUse') : tr('pluginRemove')}
icon={<Trash2 size={15} />}
onClick={() => setRemoveTarget(p)}
/>
)}
{p.system ? (
// Locked on: a disabled switch keeps the column aligned; the
// wrapper lets the tooltip work on a disabled control.
<Tip label={tr('pluginAlwaysOn')}>
<span className="plugin-row-locked" tabIndex={0}>
<Switch label={locText(p.name, locale, p.id)} checked disabled onChange={() => {}} />
</span>
</Tip>
) : (
<Switch
label={locText(p.name, locale, p.id)}
disabled={busyID === p.id || (!!safeMode && !isBuiltin)}
checked={p.enabled}
onChange={(checked) => void togglePlugin(p, checked)}
/>
)}
</div>
</div>
)
}
const renderScanReportBody = (report: ScanReport) => {
const hard = report.hard_findings ?? []
const caps = report.capabilities ?? []
const pending = report.pending_findings ?? []
const execs = report.executables ?? []
return (
<div className="stack-3">
<div className={`notice ${report.hard_blocked ? 'notice-error' : report.needs_approval ? 'notice-warn' : 'notice-ok'}`}>
<span className="notice-main">
{report.hard_blocked
? <ShieldAlert size={15} className="notice-icon" aria-hidden="true" />
: report.needs_approval
? <AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
: <CheckCircle2 size={15} className="notice-icon" aria-hidden="true" />}
<span>{locText(report.headline, locale, report.hard_blocked ? 'Blocked' : 'Passed')}</span>
</span>
</div>
{report.native_exec_notice && locText(report.native_exec_notice, locale, '') && (
<div className="notice notice-warn">
<span className="notice-main">
<ShieldAlert size={15} className="notice-icon" aria-hidden="true" />
<span>{locText(report.native_exec_notice, locale, '')}</span>
</span>
</div>
)}
{hard.length > 0 && (
<div className="plugin-scan-section">
<div className="plugin-scan-section-title is-danger">{tr('pluginScanHardSection')}</div>
<div className="list">
{hard.map((f, idx) => (
<div className="row" key={`${f.check}-${idx}`}>
<div className="row-main">
<div className="row-title">
<span className="badge rg-p-badge badge-danger">{f.check}</span>
{f.target && <span className="mono">{f.target}</span>}
</div>
<div className="row-sub">{locText(f.localized, locale, f.message)}</div>
</div>
</div>
))}
</div>
</div>
)}
{caps.length > 0 && (
<div className="plugin-scan-section">
<div className="plugin-scan-section-title">{tr('pluginScanCapabilitiesSection')}</div>
<div className="list">
{caps.map((c) => (
<div className="row" key={c.id}>
<div className="row-main">
<div className="row-title">
<span className={`badge rg-p-badge${c.level === 'high' ? ' badge-warn' : ''}`}>{c.level.toUpperCase()}</span>
<span>{locText(c.title, locale, c.id)}</span>
<span className="mono muted" style={{ fontSize: 'var(--fs-11)' }}>{c.id}</span>
</div>
<div className="row-sub">{locText(c.summary, locale, '')}</div>
{(c.examples?.length ?? 0) > 0 && (
<div className="plugin-scan-examples mono">
{c.examples!.map((ex, i) => <div key={i}>· {ex}</div>)}
{(c.extra_count ?? 0) > 0 && (
<div className="muted">· {tr('pluginScanMoreItems', { count: c.extra_count! })}</div>
)}
</div>
)}
</div>
</div>
))}
</div>
</div>
)}
{(pending.length > 0 || execs.length > 0) && (
<div className="plugin-scan-section">
<div className="plugin-scan-section-title">{tr('pluginScanAdvisoriesSection')}</div>
<div className="list">
{pending.map((f, idx) => (
<div className="row" key={`pend-${f.check}-${idx}`}>
<div className="row-main">
<div className="row-title">
<span className="badge rg-p-badge">{f.check}</span>
{f.target && <span className="mono">{f.target}</span>}
</div>
<div className="row-sub">{locText(f.localized, locale, f.message)}</div>
</div>
</div>
))}
{execs.map((ex) => (
<div className="row" key={ex.path}>
<div className="row-main">
<div className="row-title">
<span className={`badge rg-p-badge${ex.declared ? '' : ' badge-danger'}`}>{ex.declared ? 'EXE' : 'UNLISTED'}</span>
<span className="mono">{ex.path}</span>
</div>
<div className="row-sub mono selectable">SHA-256: {ex.sha256}</div>
</div>
</div>
))}
</div>
</div>
)}
</div>
)
}
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 (
<div className="page plugins-page">
<header className="page-head">
<div className="page-title plugins-page-title">
<h1>{tr('sidebarPlugins')}</h1>
{!loading && <span>{tr('pluginActiveCount', { active: activeCount, total: plugins.length })}</span>}
</div>
<div className="actions">
{activeTab === 'installed' && showSearch && (
<PluginSearchInput
value={query}
onChange={setQuery}
placeholder={tr('pluginSearchPlaceholder')}
/>
)}
<IconButton
label={activeTab === 'market' ? tr('pluginMarketRefresh') : tr('refresh')}
icon={<RefreshCw size={16} className={(activeTab === 'market' ? marketBusy : reloading) ? 'spin' : undefined} />}
disabled={activeTab === 'market' ? marketBusy : reloading}
onClick={() => activeTab === 'market' ? setMarketRefresh((n) => n + 1) : void manualReload()}
/>
<IconButton label={tr('pluginLinkDevBtn')} icon={<FolderOpen size={16} />} onClick={linkDevDir} />
<Button variant="primary" disabled={scanBusy} icon={<PackagePlus size={14} aria-hidden="true" />} onClick={importLocalZip}>
{tr('pluginImportBtn')}
</Button>
</div>
</header>
<div className="plugins-switch">
<Segmented
label={tr('sidebarPlugins')}
value={activeTab}
onChange={setActiveTab}
options={[
{ value: 'installed', label: tr('pluginTabInstalled') },
{ value: 'market', label: tr('pluginTabMarket') },
]}
/>
</div>
{marketOpened && (
<div hidden={activeTab !== 'market'}>
<PluginMarket
locale={locale}
safeMode={safeMode}
installed={plugins}
refreshSignal={marketRefresh}
onBusyChange={setMarketBusy}
onChanged={onMarketChanged}
onError={onError}
/>
</div>
)}
{activeTab === 'installed' && (
<>
{showThemeHero && (
<section className="section">
<div className="section-title">{tr('pluginThemeSection')}</div>
<div className="theme-hero-card">
<div className="theme-mini-preview" style={{ background: previewSurface }} aria-hidden="true">
<div className="theme-mini-chrome">
<span className="theme-mini-dot" />
<span className="theme-mini-dot" />
<span className="theme-mini-dot" />
</div>
<div className="theme-mini-body">
<div className="theme-mini-sidebar">
<span className="theme-mini-pill" style={{ background: previewAccent }} />
<span className="theme-mini-line" />
<span className="theme-mini-line short" />
</div>
<div className="theme-mini-main">
<div className="theme-mini-bar" />
<div className="theme-mini-cta" style={{ background: previewAccent }} />
</div>
</div>
</div>
<div className="theme-hero-info">
<div className="theme-hero-top">
<div>
<div className="theme-hero-kicker">
<Sparkles size={12} aria-hidden="true" />
{tr('pluginActiveTheme')}
</div>
<div className="theme-hero-title">
{activeThemeObj ? locText(activeThemeObj.name, locale, activeThemeObj.id) : tr('pluginSchemeDefault')}
</div>
<div className="row-sub">
{safeMode ? tr('pluginThemeSafeModeHint') : tr('pluginThemeHint')}
</div>
</div>
<div className="hstack">
<PopupSelect
label={tr('pluginThemePackLabel')}
value={activeTheme?.theme_id || 'builtin.theme.default'}
options={themes.map((th) => ({
value: th.id,
label: locText(th.name, locale, th.id),
disabled: !!safeMode && th.id !== 'builtin.theme.default',
}))}
onChange={(id) => { if (!safeMode) void selectTheme(id) }}
/>
{activeTheme && activeTheme.theme_id !== 'builtin.theme.default' && (
<Button icon={<Palette size={14} aria-hidden="true" />} onClick={() => setSchemeEditorOpen(true)}>
{tr('pluginNewScheme')}
</Button>
)}
</div>
</div>
{activeTheme && activeTheme.theme_id !== 'builtin.theme.default' ? (
<div className="theme-scheme-strip">
<span className="muted" style={{ fontSize: 'var(--fs-12)' }}>{tr('pluginColorSchemes')}</span>
<div className="theme-scheme-chips" role="radiogroup" aria-label={tr('pluginColorSchemes')}>
<button
type="button"
role="radio"
aria-checked={!activeTheme.active_scheme}
className={`plugin-pill${!activeTheme.active_scheme ? ' is-active' : ''}`}
onClick={() => void selectTheme(activeTheme.theme_id, '')}
>
{tr('pluginSchemeDefault')}
</button>
{presetSchemes.map((s) => (
<button
key={s.id}
type="button"
role="radio"
aria-checked={activeTheme.active_scheme === s.id}
className={`plugin-pill${activeTheme.active_scheme === s.id ? ' is-active' : ''}`}
onClick={() => void selectTheme(activeTheme.theme_id, s.id)}
>
{s.seeds?.accent && <span className="plugins-scheme-dot" style={{ background: s.seeds.accent }} aria-hidden="true" />}
{locText(s.name, locale, s.id)}
</button>
))}
{customSchemes.map((s) => (
<span className="hstack" style={{ gap: 2 }} key={s.id}>
<button
type="button"
role="radio"
aria-checked={activeTheme.active_scheme === s.id}
className={`plugin-pill${activeTheme.active_scheme === s.id ? ' is-active' : ''}`}
onClick={() => void selectTheme(activeTheme.theme_id, s.id)}
>
{s.seeds?.accent && <span className="plugins-scheme-dot" style={{ background: s.seeds.accent }} aria-hidden="true" />}
{s.name}
</button>
<IconButton small label={tr('pluginDeleteScheme')} icon={<Trash2 size={12} />} onClick={() => setDeleteSchemeTarget(s)} />
</span>
))}
</div>
</div>
) : (
<div className="row-sub">{tr('pluginThemeEmptyHint')}</div>
)}
</div>
</div>
</section>
)}
{noMatches && <div className="plugins-empty">{tr('pluginSearchEmpty')}</div>}
{filteredExternal.length > 0 && (
<section className="section">
<div className="section-title">
<span>{tr('pluginExternalSection')}</span>
<span className="section-count">{filteredExternal.length}</span>
</div>
<div className="list">{filteredExternal.map(renderRow)}</div>
</section>
)}
{(loading || filteredBuiltins.length > 0) && (
<section className="section">
<div className="section-title">
<span>{tr('pluginBuiltinSection')}</span>
{!loading && <span className="section-count">{filteredBuiltins.length}</span>}
</div>
{loading ? (
<div className="skeleton-list" role="status" aria-label={tr('sidebarPlugins')}>
{[0, 1, 2].map((i) => (
<div className="skeleton-row" key={i} aria-hidden="true">
<div className="skeleton-stack">
<div className="skeleton-bar w-title" />
<div className="skeleton-bar w-sub" />
</div>
<div className="skeleton-bar w-btn" />
</div>
))}
</div>
) : (
<div className="list">{filteredBuiltins.map(renderRow)}</div>
)}
</section>
)}
{settingsPanels.length > 0 && contribs?.asset_token ? (
<section className="section" data-rg-slot="settings.plugin">
<div className="section-title">{tr('pluginPanelsSection')}</div>
{settingsPanels.map((panel) => (
<PluginPanelFrame
key={`${panel.pluginId}:${panel.id}`}
locale={locale}
panel={panel}
assetToken={contribs.asset_token!}
appearance={appearance}
onOpenView={onOpenView}
onNavigate={onNavigate}
/>
))}
</section>
) : (
<div className="rg-slot-anchor" data-rg-slot="settings.plugin" />
)}
</>
)}
{scanModal && (
<Modal
title={scanModal.mode === 'archive' ? tr('pluginScanArchiveTitle') : tr('pluginScanModalTitle')}
subtitle={scanModal.report.plugin_id ? `${locText(scanModal.report.name, locale, scanModal.report.plugin_id)} · v${scanModal.report.version || '—'}` : scanModal.archivePath}
closeLabel={tr('close')}
onClose={() => { if (!scanBusy) setScanModal(null) }}
>
<div className="dialog-body">
{renderScanReportBody(scanModal.report)}
</div>
<div className="dialog-foot">
<span className="muted mono" style={{ fontSize: 'var(--fs-11)' }}>
{scanModal.report.tier ? `${scanModal.report.tier} · ${scanModal.report.trust || 'community'}` : ''}
</span>
<span className="hstack">
{scanModal.mode === 'archive' ? (
<>
<Button variant="ghost" disabled={scanBusy} onClick={() => setScanModal(null)}>{tr('cancel')}</Button>
<Button
variant="primary"
disabled={scanBusy || scanModal.report.hard_blocked}
onClick={() => void confirmInstallScannedArchive()}
>
{scanModal.report.hard_blocked ? tr('pluginScanBlockedBtn') : tr('pluginScanInstallConfirm')}
</Button>
</>
) : (
<Button variant="primary" onClick={() => setScanModal(null)}>{tr('pluginDone')}</Button>
)}
</span>
</div>
</Modal>
)}
{approveTarget && (
<Modal
title={tr('pluginApproveTitle')}
subtitle={locText(approveTarget.name, locale, approveTarget.id)}
closeLabel={tr('close')}
onClose={closeApprove}
>
<div className="dialog-body">
<PluginApprovalBody locale={locale} plugin={approveTarget} report={approveReport} />
<label className="choice">
<input type="checkbox" checked={approveChecked} onChange={(e) => setApproveChecked(e.target.checked)} />
<span>{tr('pluginApproveCheckbox')}</span>
</label>
</div>
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" onClick={closeApprove}>{tr('cancel')}</Button>
<Button variant="primary" disabled={!approveChecked} onClick={() => void confirmApprove()}>
{tr('pluginApproveConfirm')}
</Button>
</span>
</div>
</Modal>
)}
{settingsTarget && settingsTarget.settings && (
<Modal
title={locText(settingsTarget.name, locale, settingsTarget.id)}
subtitle={tr('pluginGlobalSettings')}
closeLabel={tr('close')}
onClose={() => setSettingsTarget(null)}
>
<div className="dialog-body">
{settingsRuntimeWarning && (
<div className="notice notice-warn">
<AlertTriangle size={15} className="notice-icon" aria-hidden="true" />
<span>{settingsRuntimeWarning}</span>
</div>
)}
<SchemaForm
locale={locale}
schema={settingsTarget.settings}
values={settingsValues}
scopeFilter="app"
onChange={(_, patch) => void savePluginSettings(patch)}
/>
</div>
<div className="dialog-foot">
<span />
<Button variant="primary" onClick={() => setSettingsTarget(null)}>{tr('pluginDone')}</Button>
</div>
</Modal>
)}
{disableTarget && (
<ConfirmDialog
title={tr('pluginDisableInUseTitle')}
description={tr('pluginDisableInUseBody')}
cancelLabel={tr('cancel')}
confirmLabel={tr('pluginDisable')}
onCancel={() => setDisableTarget(null)}
onConfirm={() => {
const target = disableTarget
setDisableTarget(null)
void togglePlugin(target, false, true)
}}
>
<div className="row-sub">{locText(disableTarget.name, locale, disableTarget.id)}</div>
</ConfirmDialog>
)}
{removeTarget && (
<ConfirmDialog
title={tr('pluginRemove')}
description={locText(removeTarget.name, locale, removeTarget.id)}
cancelLabel={tr('cancel')}
confirmLabel={tr('pluginRemove')}
onCancel={() => setRemoveTarget(null)}
onConfirm={() => {
const target = removeTarget
setRemoveTarget(null)
void removePlugin(target)
}}
>
<div className="row-sub mono">{removeTarget.id}@{removeTarget.version}</div>
</ConfirmDialog>
)}
{deleteSchemeTarget && (
<ConfirmDialog
title={tr('pluginDeleteScheme')}
description={deleteSchemeTarget.name}
cancelLabel={tr('cancel')}
confirmLabel={tr('pluginDeleteScheme')}
onCancel={() => setDeleteSchemeTarget(null)}
onConfirm={() => {
const target = deleteSchemeTarget
setDeleteSchemeTarget(null)
void deleteScheme(target.id)
}}
/>
)}
{logTarget && (
<Modal
title={tr('pluginLogTitle', { id: logTarget.id })}
closeLabel={tr('close')}
onClose={() => setLogTarget(null)}
>
<div className="dialog-body">
<pre className="plugin-log-pre mono selectable">{logTarget.text}</pre>
</div>
</Modal>
)}
{schemeEditorOpen && (
<Modal
title={tr('pluginSchemeModalTitle')}
closeLabel={tr('close')}
onClose={() => setSchemeEditorOpen(false)}
>
<div className="dialog-body">
<label className="field">
<span className="field-label">{tr('pluginSchemeName')}</span>
<input className="input rg-p-input" value={schemeName} onChange={(e) => setSchemeName(e.target.value)} placeholder={tr('pluginSchemePlaceholder')} />
</label>
<label className="hstack">
<span className="field-label">{tr('pluginAccentSeed')}</span>
<input type="color" value={seedAccent} onChange={(e) => setSeedAccent(e.target.value)} />
<span className="mono">{seedAccent}</span>
</label>
<label className="field">
<span className="field-label">{tr('pluginSurfaceSeed')}</span>
<input className="input rg-p-input mono" value={seedSurface} onChange={(e) => setSeedSurface(e.target.value)} placeholder="#1d1e23" />
</label>
</div>
<div className="dialog-foot">
<span />
<span className="hstack">
<Button variant="ghost" onClick={() => setSchemeEditorOpen(false)}>{tr('cancel')}</Button>
<Button variant="primary" disabled={!schemeName.trim()} onClick={() => void saveScheme()}>{tr('save')}</Button>
</span>
</div>
</Modal>
)}
</div>
)
}