performBackgroundInstallations method

Future<void> performBackgroundInstallations()

Perform background plugin startup checks and installations.

Implementation

Future<void> performBackgroundInstallations() async {
  try {
    final diff = computeDiff?.call() ?? const MarketplaceDiff();

    final pendingNames = [
      ...diff.missing,
      ...diff.sourceChanged.map((c) => c.name),
    ];

    installationStatus.value = PluginInstallationStatus(
      marketplaces: pendingNames
          .map(
            (name) => MarketplaceInstallStatus(
              name: name,
              status: InstallationStatus.pending,
            ),
          )
          .toList(),
      plugins: const [],
    );

    if (pendingNames.isEmpty) return;

    final result = await reconcileMarketplaces?.call(
      onProgress: (event) {
        if (event is ReconciliationInstalling) {
          _updateMarketplaceStatus(event.name, InstallationStatus.installing);
        } else if (event is ReconciliationInstalled) {
          _updateMarketplaceStatus(event.name, InstallationStatus.installed);
        } else if (event is ReconciliationFailed) {
          _updateMarketplaceStatus(
            event.name,
            InstallationStatus.failed,
            event.error,
          );
        }
      },
    );

    if (result == null) return;

    logEvent?.call('tengu_marketplace_background_install', {
      'installed_count': result.installed.length,
      'updated_count': result.updated.length,
      'failed_count': result.failed.length,
      'up_to_date_count': result.upToDate.length,
    });

    if (result.installed.isNotEmpty) {
      // New marketplaces installed — auto-refresh plugins.
      try {
        await refreshActivePlugins?.call();
      } catch (_) {
        needsRefresh.value = true;
      }
    } else if (result.updated.isNotEmpty) {
      // Existing marketplaces updated — notify for /reload-plugins.
      needsRefresh.value = true;
    }
  } catch (_) {
    // Swallow — background installation must not crash.
  }
}