install method

  1. @override
Future<OmnixModelInstallation> install(
  1. OmnixModelInstallRequest request, {
  2. void onProgress(
    1. int progress
    )?,
  3. OmnixCancellationToken? cancellationToken,
})
override

Implementation

@override
Future<OmnixModelInstallation> install(
  OmnixModelInstallRequest request, {
  void Function(int progress)? onProgress,
  OmnixCancellationToken? cancellationToken,
}) async {
  await initialize();
  cancellationToken?.throwIfCancelled();
  if (request.requiresIntegrityVerification &&
      !supportsModelArtifactVerification) {
    throw UnsupportedError(
      'This platform cannot verify downloaded model artifacts.',
    );
  }

  var builder = FlutterGemma.installModel(
    modelType: _modelType(request.template),
    fileType: _fileType(request.format),
  );
  builder = switch (request.source) {
    OmnixNetworkModelSource(
      :final uri,
      :final authToken,
      :final foreground,
    ) =>
      builder.fromNetwork(
        uri.toString(),
        token: _nonEmpty(authToken),
        foreground: foreground,
      ),
    OmnixAssetModelSource(:final path) => builder.fromAsset(path),
    OmnixFileModelSource(:final path) => builder.fromFile(path),
    OmnixBundledModelSource(:final name) => builder.fromBundled(name),
  };

  if (onProgress != null) builder.withProgress(onProgress);

  final pluginCancellation = CancelToken();
  StreamSubscription<String>? cancellationSubscription;
  if (cancellationToken != null) {
    builder.withCancelToken(pluginCancellation);
    cancellationSubscription = cancellationToken.cancellations.listen(
      pluginCancellation.cancel,
    );
  }

  try {
    final installation = await builder.install();
    final artifactName = installation.spec.files.first.filename;
    if (request.requiresIntegrityVerification) {
      try {
        await verifyModelArtifact(
          path: await FlutterGemma.getModelPath(artifactName),
          expectedSize: request.expectedSizeBytes!,
          expectedSha256: request.expectedSha256!,
        );
      } catch (_) {
        try {
          await FlutterGemma.clearActiveInferenceIdentity();
        } catch (_) {
          // Continue cleanup even if the active identity cannot be cleared.
        }
        try {
          await FlutterGemma.uninstallModel(artifactName);
        } catch (_) {
          // Preserve the verification failure as the actionable error.
        }
        rethrow;
      }
    }
    return OmnixModelInstallation(
      artifactName: artifactName,
      template: request.template,
      format: request.format,
      capabilities: request.capabilities,
      notes: installation.notes,
    );
  } on DownloadCancelledException catch (error) {
    throw OmnixOperationCancelled(error.message);
  } finally {
    await cancellationSubscription?.cancel();
  }
}