downloadModelWithProgress method

  1. @override
Stream<DownloadProgress> downloadModelWithProgress(
  1. ModelSpec spec, {
  2. String? token,
})
override

Downloads a model with progress tracking

Implementation

@override
Stream<DownloadProgress> downloadModelWithProgress(ModelSpec spec, {String? token}) async* {
  await _ensureInitialized();

  debugPrint('WebModelManager: Starting download for ${spec.name}');

  // Phase 5: Delegate to Modern API
  final registry = ServiceRegistry.instance;
  final handlerRegistry = registry.sourceHandlerRegistry;
  final totalFiles = spec.files.length;

  for (int i = 0; i < totalFiles; i++) {
    final file = spec.files[i];

    // Emit file start progress
    yield DownloadProgress(
      currentFileIndex: i,
      totalFiles: totalFiles,
      currentFileProgress: 0,
      currentFileName: file.filename,
    );

    // Get handler for this file's source
    final handler = handlerRegistry.getHandler(file.source);
    if (handler == null) {
      throw ModelStorageException(
        'No handler for ${file.source.runtimeType}',
        null,
        'downloadModelWithProgress',
      );
    }

    // For NetworkSource with token, update the source
    ModelSource sourceToInstall = file.source;
    if (sourceToInstall is NetworkSource && token != null) {
      sourceToInstall = NetworkSource(sourceToInstall.url, authToken: token);
    }

    // Download via Modern API handler with progress
    // All handlers implement installWithProgress (handlers that don't support
    // true progress will emit 100% immediately)
    await for (final progress in handler.installWithProgress(sourceToInstall)) {
      yield DownloadProgress(
        currentFileIndex: i,
        totalFiles: totalFiles,
        currentFileProgress: progress,
        currentFileName: file.filename,
      );
    }
  }

  // Set as active after successful download
  setActiveModel(spec);

  // Emit final progress
  yield DownloadProgress(
    currentFileIndex: totalFiles,
    totalFiles: totalFiles,
    currentFileProgress: 100,
    currentFileName: 'Complete',
  );

  debugPrint('WebModelManager: Download completed for ${spec.name}');
}