verstak-desktop/frontend/src/lib/plugin-manager/PluginManager.svelte

549 lines
21 KiB
Svelte

<script>
import Icon from '../ui/Icon.svelte';
import PluginCard from './PluginCard.svelte';
import PluginBundleHost from '../plugin-host/PluginBundleHost.svelte';
import { onMount, tick } from 'svelte';
import { GetPlugins, GetCapabilities, GetPermissions, GetContributions, ReloadPlugins, GetVaultStatus, GetVaultPluginState, EnablePlugin, DisablePlugin, ReadPluginSettings, WritePluginSettings, GetPluginFrontendInfo, WriteFrontendLog } from '../../../wailsjs/go/api/App';
import { debug } from '../log/debug.js';
let plugins = [];
let capabilities = [];
let permissions = [];
let contributions = {};
let loading = true;
let error = '';
let vaultStatus = { status: 'unknown', path: '', vaultId: '' };
let vaultPluginState = { enabledPlugins: [], disabledPlugins: [], desiredPlugins: [] };
let settingsPanel = null;
let settingsData = {};
let settingsPluginId = '';
let settingsError = null;
let settingsPluginInfo = null;
let lastOpenedKey = '';
// Per-action loading state — shows feedback on specific buttons without hiding the whole list
let actionFeedback = {}; // { [pluginId]: 'enabling' | 'disabling' | null }
let reloading = false;
let toastMessage = '';
let toastType = 'success'; // 'success' | 'error' | 'info'
export let activeSettingsPluginId = '';
export let activeSettingsPanelId = '';
$: if (activeSettingsPluginId && activeSettingsPanelId) {
const key = `${activeSettingsPluginId}:${activeSettingsPanelId}`;
if (key !== lastOpenedKey) {
lastOpenedKey = key;
openSettingsFromProps(activeSettingsPluginId, activeSettingsPanelId);
}
}
function showToast(msg, type = 'success') {
toastMessage = msg;
toastType = type;
setTimeout(() => {
toastMessage = '';
}, 4000);
}
function notifyPluginsChanged() {
window.dispatchEvent(new CustomEvent('verstak:plugins-changed'));
}
function unpackBackendResult(result) {
if (Array.isArray(result) && result.length === 2 && (typeof result[1] === 'string' || result[1] == null)) {
return { value: result[0], error: result[1] || '' };
}
return { value: result, error: '' };
}
function unpackReloadResult(result) {
if (Array.isArray(result)) {
return {
count: Number(result[0] || 0),
summary: result[1] || `Reloaded ${Number(result[0] || 0)} plugin(s).`,
};
}
const count = Number(result || 0);
return { count, summary: `Reloaded ${count} plugin(s).` };
}
async function openSettingsFromProps(pluginId, panelId) {
const panel = (contributions.settingsPanels || []).find(sp => sp.pluginId === pluginId && (!panelId || sp.id === panelId));
if (panel) {
settingsPanel = panel;
settingsPluginId = pluginId;
settingsError = null;
try {
const info = await GetPluginFrontendInfo(pluginId);
settingsPluginInfo = info;
} catch { settingsPluginInfo = null; }
ReadPluginSettings(pluginId).then(result => {
const unpacked = unpackBackendResult(result);
if (unpacked.error) {
settingsError = unpacked.error;
settingsData = {};
return;
}
settingsData = unpacked.value || {};
}).catch(() => { settingsData = {}; });
} else {
settingsError = `Settings panel not found for plugin "${pluginId}". Check that the plugin is enabled and has settingsPanels in its manifest.`;
}
}
$: vaultOpen = vaultStatus.status === 'open';
$: missingInstalled = computeMissingInstalled();
function computeMissingInstalled() {
if (!vaultPluginState.desiredPlugins) return [];
const installedIDs = new Set(plugins.map(p => p.manifest?.id).filter(Boolean));
return (vaultPluginState.desiredPlugins || []).filter(dp => !installedIDs.has(dp.id));
}
async function loadAll() {
debug.log('[PluginManager] loadAll: START');
error = '';
loading = true;
try {
debug.log('[PluginManager] loadAll: calling GetPlugins...');
const p = await GetPlugins();
plugins = p || [];
debug.log('[PluginManager] loadAll: GetPlugins returned', plugins.length, 'plugins');
for (var i = 0; i < plugins.length; i++) {
debug.log('[PluginManager] loadAll: plugin[' + i + ']:', plugins[i].manifest?.id, 'status:', plugins[i].status, 'enabled:', plugins[i].enabled);
}
} catch (e) {
debug.log('[PluginManager] loadAll: GetPlugins ERROR:', String(e));
WriteFrontendLog('PluginManager', 'loadAll: GetPlugins ERROR: ' + String(e));
error = 'GetPlugins: ' + String(e);
loading = false;
return;
}
// Collect all async loads but await them so loading stays true until all are done
try {
debug.log('[PluginManager] loadAll: loading vault/capabilities/permissions/contributions...');
const [v, caps, perms, contribs] = await Promise.all([
GetVaultStatus().catch(() => ({ status: 'unknown', path: '', vaultId: '' })),
GetCapabilities().catch(() => []),
GetPermissions().catch(() => []),
GetContributions().catch(() => ({})),
]);
vaultStatus = v || { status: 'unknown', path: '', vaultId: '' };
capabilities = caps || [];
permissions = perms || [];
contributions = contribs || {};
debug.log('[PluginManager] loadAll: vault=' + vaultStatus.status + ' caps=' + capabilities.length + ' perms=' + permissions.length);
WriteFrontendLog('PluginManager', 'loadAll: vault=' + vaultStatus.status + ' caps=' + capabilities.length + ' perms=' + permissions.length);
} catch (e) {
debug.log('[PluginManager] loadAll: non-critical load ERROR:', String(e));
WriteFrontendLog('PluginManager', 'loadAll: non-critical ERROR: ' + String(e));
console.error('[PluginManager] non-critical load error:', e);
}
if (vaultStatus.status === 'open') {
try {
debug.log('[PluginManager] loadAll: calling GetVaultPluginState...');
vaultPluginState = await GetVaultPluginState() || { enabledPlugins: [], disabledPlugins: [], desiredPlugins: [] };
WriteFrontendLog('PluginManager', 'loadAll: GetVaultPluginState returned');
} catch (e) {
WriteFrontendLog('PluginManager', 'loadAll: GetVaultPluginState ERROR: ' + String(e));
}
}
loading = false;
await tick();
debug.log('[PluginManager] loadAll: END, loading=false');
WriteFrontendLog('PluginManager', 'loadAll: END, loading=false');
}
onMount(() => { loadAll(); });
async function reload() {
debug.log('[PluginManager] reload: START');
reloading = true;
error = '';
let resultMsg = '';
try {
debug.log('[PluginManager] reload: calling ReloadPlugins...');
const { count, summary } = unpackReloadResult(await ReloadPlugins());
debug.log('[PluginManager] reload: ReloadPlugins returned count=' + count + ' summary=' + summary);
resultMsg = `Reloaded ${count} plugin(s). ${summary}`;
} catch (e) {
debug.log('[PluginManager] reload: ReloadPlugins ERROR:', String(e));
error = 'Reload: ' + String(e);
reloading = false;
return;
}
debug.log('[PluginManager] reload: calling loadAll after reload...');
await loadAll();
notifyPluginsChanged();
reloading = false;
debug.log('[PluginManager] reload: END');
showToast(resultMsg, 'success');
}
async function enablePlugin(pluginId) {
debug.log('[PluginManager] enablePlugin:', pluginId);
actionFeedback = { ...actionFeedback, [pluginId]: 'enabling' };
error = '';
const err = await EnablePlugin(pluginId);
if (err) {
debug.log('[PluginManager] enablePlugin: ERROR:', err);
actionFeedback = { ...actionFeedback, [pluginId]: null };
error = 'Enable: ' + err;
return;
}
debug.log('[PluginManager] enablePlugin: success, reloading...');
// Reload to get updated state
try { await ReloadPlugins(); } catch (e) { /* ignore */ }
await loadAll();
notifyPluginsChanged();
actionFeedback = { ...actionFeedback, [pluginId]: null };
debug.log('[PluginManager] enablePlugin: done');
showToast(`Plugin "${pluginId}" enabled`, 'success');
}
async function disablePlugin(pluginId) {
debug.log('[PluginManager] disablePlugin:', pluginId);
actionFeedback = { ...actionFeedback, [pluginId]: 'disabling' };
error = '';
const err = await DisablePlugin(pluginId);
if (err) {
debug.log('[PluginManager] disablePlugin: ERROR:', err);
actionFeedback = { ...actionFeedback, [pluginId]: null };
error = 'Disable: ' + err;
return;
}
debug.log('[PluginManager] disablePlugin: success, reloading...');
// Reload to get updated state
try { await ReloadPlugins(); } catch (e) { /* ignore */ }
await loadAll();
notifyPluginsChanged();
actionFeedback = { ...actionFeedback, [pluginId]: null };
debug.log('[PluginManager] disablePlugin: done');
showToast(`Plugin "${pluginId}" disabled`, 'info');
}
$: totalPlugins = plugins.length;
$: totalCaps = capabilities.length;
$: totalPerms = permissions.length;
function closeSettings() {
settingsPanel = null;
settingsPluginId = '';
settingsError = null;
lastOpenedKey = '';
window.dispatchEvent(new CustomEvent('verstak:close-settings'));
}
function saveSettings() {
WritePluginSettings(settingsPluginId, settingsData).then(err => {
if (err) console.error('WritePluginSettings:', err);
}).catch(e => console.error('WritePluginSettings:', e));
}
</script>
<div class="plugin-manager">
<!-- Toast notification -->
{#if toastMessage}
<div class="toast" class:toast-success={toastType === 'success'} class:toast-error={toastType === 'error'} class:toast-info={toastType === 'info'}>
{toastMessage}
</div>
{/if}
<header>
<div class="header-left">
<h2>Plugin Manager</h2>
{#if vaultStatus.status !== 'unknown'}
<span class="vault-badge" class:vault-open={vaultStatus.status === 'open'} class:vault-not-created={vaultStatus.status === 'not-created'} class:vault-closed={vaultStatus.status === 'closed'} class:vault-error={vaultStatus.status === 'error'}>
Vault: {vaultStatus.status}{#if vaultStatus.path} ({vaultStatus.path}){/if}
</span>
{/if}
</div>
<button class="reload-btn" on:click={reload} type="button" disabled={loading || reloading}>
{reloading ? '⟳ Reloading...' : '⟳ Reload'}
</button>
</header>
{#if loading}
<div class="loading">Scanning plugin directories...</div>
{:else if error}
<div class="error">
<Icon name="warning" size={24} className="error-icon" />
<div class="error-message">{error}</div>
<button class="retry-btn" on:click={loadAll} type="button">⟳ Retry</button>
</div>
{:else}
<div class="summary">
<span class="badge">{totalPlugins} plugin(s) discovered</span>
<span class="badge">{totalCaps} capabilities registered</span>
<span class="badge">{totalPerms} permissions known</span>
</div>
{#if plugins.length === 0 && missingInstalled.length === 0}
<div class="empty">
<div class="empty-icon">
<svg width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
<path d="M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"/>
</svg>
</div>
<p>No plugins found</p>
<p class="hint">Plugin directories scanned:</p>
<ul class="hint-list">
<li><code>~/.config/verstak/plugins/</code> — user plugins</li>
<li><code>./plugins/</code> — bundled plugins (app directory)</li>
</ul>
<p class="hint">Place a plugin folder with <code>plugin.json</code> in one of these directories and click Reload.</p>
</div>
{:else}
<div class="plugin-list">
{#each plugins as p}
<PluginCard {p} {capabilities} {permissions} {contributions} {vaultOpen} {actionFeedback} settingsPanels={(contributions.settingsPanels || []).filter(sp => sp.pluginId === p.manifest?.id)} onEnable={enablePlugin} onDisable={disablePlugin} />
{/each}
</div>
{/if}
{#if missingInstalled.length > 0}
<div class="missing-section">
<h3>Missing Installed Plugins</h3>
<p class="missing-hint">These plugins are required by this vault but their packages are not installed locally.</p>
<div class="plugin-list">
{#each missingInstalled as mp}
<div class="plugin-card missing-card">
<div class="card-header">
<div class="plugin-id">
<span class="status-dot" style="background: #e94560"></span>
<strong>{mp.id}</strong>
{#if mp.version}<span class="version">v{mp.version}</span>{/if}
</div>
<span class="status-badge" style="color: #e94560">missing</span>
</div>
<p class="missing-text">
This plugin is listed in the vault's desired plugins but the package is not installed.
{#if mp.source && mp.source !== 'unknown'}
<span class="source-hint">Source: {mp.source}</span>
{/if}
</p>
</div>
{/each}
</div>
</div>
{/if}
{#if capabilities.length > 0}
<details class="registry-section">
<summary>Capability Registry ({totalCaps})</summary>
<table>
<thead>
<tr><th>Capability</th><th>Provider</th><th>Source</th><th>Status</th></tr>
</thead>
<tbody>
{#each capabilities as cap}
<tr>
<td><code>{cap.name}</code></td>
<td>{cap.pluginId}</td>
<td><span class="source-badge" class:source-core={cap.pluginId === 'verstak-desktop'} class:source-plugin={cap.pluginId !== 'verstak-desktop'}>{cap.pluginId === 'verstak-desktop' ? 'core' : 'plugin'}</span></td>
<td><span class="status-{cap.status}">{cap.status}</span></td>
</tr>
{/each}
</tbody>
</table>
</details>
{/if}
{/if}
<!-- Settings Panel Modal -->
{#key `settings-${settingsPluginId}`}
{#if settingsError}
<div class="modal-overlay" on:click|self={closeSettings} on:keydown|self={(e) => e.key === 'Escape' && closeSettings()} role="presentation">
<div class="modal" role="dialog" aria-modal="true" aria-label="Settings Error">
<div class="modal-header">
<h3>Settings Error</h3>
<button class="modal-close" on:click={closeSettings} type="button"></button>
</div>
<div class="modal-body">
<p class="error" style="color: #e94560;">{settingsError}</p>
</div>
</div>
</div>
{:else if settingsPanel}
<div class="modal-overlay" on:click|self={closeSettings} on:keydown|self={(e) => e.key === 'Escape' && closeSettings()} role="presentation">
<div class="modal" role="dialog" aria-modal="true" aria-label="Plugin Settings">
<div class="modal-header">
<h3>{settingsPanel.title}</h3>
<button class="modal-close" on:click={closeSettings} type="button"></button>
</div>
<div class="modal-body">
<p class="settings-hint">Plugin: <code>{settingsPluginId}</code></p>
{#if settingsPluginInfo && settingsPluginInfo.entry}
<PluginBundleHost
pluginId={settingsPluginId}
componentId={settingsPanel.component || settingsPanel.id}
/>
{:else}
<p class="settings-hint">Component: <code>{settingsPanel.component}</code></p>
<p class="placeholder">Settings panel frontend bundle not available</p>
{/if}
</div>
</div>
</div>
{/if}
{/key}
</div>
<style>
.plugin-manager {
flex: 1;
width: min(100%, 1100px);
min-height: 0;
padding: 0.5rem 0.5rem 1.5rem 0;
position: relative;
}
header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.75rem;
flex-wrap: wrap;
margin-bottom: 1.25rem;
padding-bottom: 0.75rem;
border-bottom: 1px solid #0f3460;
}
.header-left {
display: flex;
align-items: center;
gap: 0.75rem;
min-width: 0;
flex-wrap: wrap;
}
h2 { color: #e0e0e0; font-size: 1.3rem; margin: 0; }
.vault-badge {
max-width: 100%;
font-size: 0.75rem;
padding: 0.2rem 0.6rem;
border-radius: 12px;
font-weight: 600;
border: 1px solid;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.vault-open { background: rgba(78, 204, 163, 0.15); color: #4ecca3; border-color: #4ecca3; }
.vault-not-created { background: rgba(255, 200, 87, 0.15); color: #ffc857; border-color: #ffc857; }
.vault-closed { background: rgba(160, 160, 184, 0.15); color: #a0a0b8; border-color: #a0a0b8; }
.vault-error { background: rgba(233, 69, 96, 0.15); color: #e94560; border-color: #e94560; }
.reload-btn {
background: #0f3460; color: #e0e0e0; border: 1px solid #533483;
padding: 0.4rem 1rem; border-radius: 6px; cursor: pointer; font-size: 0.85rem;
}
.reload-btn:hover:not(:disabled) { background: #533483; }
.reload-btn:disabled { opacity: 0.5; cursor: not-allowed; }
/* Toast */
.toast {
position: fixed; top: 1rem; right: 1rem; z-index: 2000;
padding: 0.6rem 1.2rem; border-radius: 6px; font-size: 0.85rem;
max-width: 400px; word-break: break-word;
animation: toastIn 0.25s ease-out;
}
.toast-success { background: #1a3a2e; color: #4ecca3; border: 1px solid #4ecca3; }
.toast-error { background: #3a1a1a; color: #e94560; border: 1px solid #e94560; }
.toast-info { background: #1a1a3a; color: #a78bfa; border: 1px solid #a78bfa; }
@keyframes toastIn { from { opacity: 0; transform: translateY(-10px); } to { opacity: 1; transform: translateY(0); } }
.loading, .error {
padding: 2rem; text-align: center; color: #a0a0b8;
}
.error { color: #e94560; }
.error-icon { color: #e94560; margin-bottom: 0.5rem; }
.error-message {
font-family: monospace; font-size: 0.85rem; margin-bottom: 1rem; word-break: break-word;
}
.retry-btn {
background: #0f3460; color: #e0e0e0; border: 1px solid #533483;
padding: 0.4rem 1rem; border-radius: 6px; cursor: pointer; font-size: 0.85rem;
}
.retry-btn:hover { background: #533483; }
.summary {
display: flex; gap: 0.5rem; margin-bottom: 1rem; flex-wrap: wrap;
}
.badge {
background: #16213e; padding: 0.25rem 0.75rem; border-radius: 12px;
font-size: 0.8rem; color: #a0a0b8; border: 1px solid #0f3460;
}
.empty {
padding: 2rem; text-align: center; color: #a0a0b8;
background: #16213e; border-radius: 8px; border: 1px dashed #0f3460;
}
.empty-icon { margin-bottom: 0.5rem; color: #0f3460; }
.hint { font-size: 0.85rem; margin-top: 0.5rem; opacity: 0.7; }
.hint-list { list-style: none; padding: 0; margin: 0.5rem 0; font-size: 0.8rem; opacity: 0.7; }
.hint-list li { margin: 0.25rem 0; }
.hint code { background: #0f3460; padding: 0.1rem 0.3rem; border-radius: 3px; }
.plugin-list { display: flex; flex-direction: column; gap: 0.75rem; margin-bottom: 1.5rem; min-width: 0; }
.missing-section { margin-bottom: 1.5rem; }
.missing-section h3 { color: #e94560; font-size: 1rem; margin: 0 0 0.25rem; }
.missing-hint { color: #a0a0b8; font-size: 0.8rem; margin: 0 0 0.75rem; }
.missing-card { border-color: #e94560; opacity: 0.8; }
.missing-text { color: #a0a0b8; font-size: 0.85rem; margin: 0.5rem 0 0; }
.source-hint { display: block; margin-top: 0.25rem; font-size: 0.75rem; color: #666; }
.registry-section {
background: #16213e; border: 1px solid #0f3460;
border-radius: 8px; padding: 0.75rem; margin-top: 1rem;
}
.registry-section summary { cursor: pointer; color: #a0a0b8; font-size: 0.9rem; font-weight: 600; }
table { width: 100%; margin-top: 0.5rem; border-collapse: collapse; font-size: 0.85rem; }
th { text-align: left; padding: 0.4rem 0.5rem; color: #a0a0b8; border-bottom: 1px solid #0f3460; }
td { padding: 0.3rem 0.5rem; border-bottom: 1px solid #0f3460; }
td code { color: #e0e0e0; }
:global(.status-stable) { color: #4ecca3; }
:global(.status-draft) { color: #ffc857; }
:global(.status-deprecated) { color: #e94560; }
.source-badge { font-size: 0.75rem; padding: 0.1rem 0.4rem; border-radius: 4px; font-weight: 600; }
.source-core { background: #1a3a5c; color: #4ecca3; border: 1px solid #4ecca3; }
.source-plugin { background: #0f3460; color: #a0a0b8; border: 1px solid #533483; }
/* Modal */
.modal-overlay {
position: fixed; inset: 0;
background: rgba(0, 0, 0, 0.6);
display: flex; align-items: center; justify-content: center;
z-index: 1000;
}
.modal {
background: #16213e; border: 1px solid #0f3460; border-radius: 8px;
width: 480px; max-width: 90vw; max-height: 80vh; display: flex; flex-direction: column;
}
.modal-header {
display: flex; align-items: center; justify-content: space-between;
padding: 1rem; border-bottom: 1px solid #0f3460;
}
.modal-header h3 { margin: 0; color: #e0e0f0; font-size: 1.1rem; }
.modal-close { background: none; border: none; color: #a0a0b8; font-size: 1.2rem; cursor: pointer; padding: 0.2rem 0.5rem; }
.modal-close:hover { color: #e94560; }
.modal-body { padding: 1rem; overflow-y: auto; }
.settings-hint { color: #666; font-size: 0.8rem; margin: 0.25rem 0; }
.settings-hint code { color: #4ecca3; }
@media (max-width: 760px) {
.plugin-manager {
width: 100%;
padding-right: 0;
}
header {
align-items: flex-start;
}
.reload-btn {
width: 100%;
}
.modal {
width: min(480px, calc(100vw - 2rem));
max-height: calc(100vh - 2rem);
}
}
</style>