KiThe 0.3.24

A numerical suite for chemical kinetics and thermodynamics, combustion, TGA, heat and mass transfer,chemical equilibrium, chemical engeneering
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
use crate::Kinetics::experimental_kinetics::catalog::client::{
    CATALOG_TRANSFER_CHUNK_SIZE, CatalogPublicationSearchRequest, CatalogRemoteClient,
    CatalogSearchEntry, CatalogTransferArtifact, CatalogTransferManifest, CatalogTransferReceipt,
    VirtualCatalogServer,
};
use crate::Kinetics::experimental_kinetics::catalog::{
    CatalogId, CatalogObjectKind, CatalogPublication, CatalogPublicationSnapshot,
    LocalArtifactResolution,
};
use crate::gui::experimental_kinetics_gui::test_options::CatalogArtifactListing;
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::fs::{self, File, OpenOptions};
use std::io::{Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, Receiver, TryRecvError};
use std::sync::{Arc, Mutex};

enum TransferTaskOutput {
    Uploaded(CatalogTransferReceipt),
    SearchResults(Vec<CatalogPublication>),
    Downloaded(PathBuf),
}

#[derive(Clone, Debug, Default)]
struct TransferProgress {
    phase: String,
    file_name: String,
    bytes_done: u64,
    total_bytes: u64,
}

/// Explicit GUI for exercising the remote transfer protocol against an in-memory service.
pub struct CatalogTransferUi {
    open: bool,
    server: Arc<VirtualCatalogServer>,
    local_publication: Option<CatalogId>,
    remote_publications: Vec<CatalogPublication>,
    remote_publication: Option<CatalogId>,
    remote_search: String,
    destination_folder: String,
    task: Option<Receiver<Result<TransferTaskOutput, String>>>,
    progress: Arc<Mutex<TransferProgress>>,
    status: Option<String>,
}

impl Default for CatalogTransferUi {
    fn default() -> Self {
        Self {
            open: false,
            server: Arc::new(VirtualCatalogServer::default()),
            local_publication: None,
            remote_publications: Vec::new(),
            remote_publication: None,
            remote_search: String::new(),
            destination_folder: String::new(),
            task: None,
            progress: Arc::new(Mutex::new(TransferProgress::default())),
            status: None,
        }
    }
}

impl CatalogTransferUi {
    pub fn open(&mut self) {
        self.open = true;
    }

    pub(super) fn show(
        &mut self,
        ctx: &egui::Context,
        local_publications: &[CatalogPublication],
        artifacts: &HashMap<CatalogId, CatalogArtifactListing>,
    ) {
        self.poll_task();
        self.reconcile_selections(local_publications);
        if !self.open {
            return;
        }

        let service = self.server.service_info();
        let mut open = self.open;
        egui::Window::new("Catalog transfers: virtual server")
            .open(&mut open)
            .resizable(true)
            .default_width(620.0)
            .show(ctx, |ui| {
                ui.label("In-memory test endpoint. Nothing is sent over the network or stored in the local SQLite catalog.");
                match &service {
                    Ok(info) => {
                        ui.small(format!(
                            "{} · protocol v{} · chunks up to {} KiB",
                            info.display_name,
                            info.wire_schema_version,
                            info.max_chunk_size / 1024
                        ));
                    }
                    Err(error) => {
                        ui.colored_label(egui::Color32::RED, error.to_string());
                    }
                }

                ui.separator();
                ui.heading("Send a local publication");
                egui::ComboBox::from_label("Local publication")
                    .selected_text(
                        self.local_publication
                            .as_ref()
                            .and_then(|id| {
                                local_publications
                                    .iter()
                                    .find(|publication| &publication.id == id)
                            })
                            .map(publication_label)
                            .unwrap_or_else(|| "Select a publication".into()),
                    )
                    .show_ui(ui, |ui| {
                        for publication in local_publications {
                            ui.selectable_value(
                                &mut self.local_publication,
                                Some(publication.id.clone()),
                                publication_label(publication),
                            );
                        }
                    });
                let selected_local = self
                    .local_publication
                    .as_ref()
                    .and_then(|id| local_publications.iter().find(|publication| &publication.id == id));
                if let Some(publication) = selected_local {
                    ui.small(format!(
                        "{} attached file(s). The immutable publication ID is used as the retry key.",
                        publication.artifact_ids.len()
                    ));
                }
                let upload_enabled = self.task.is_none() && selected_local.is_some();
                if ui
                    .add_enabled(upload_enabled, egui::Button::new("Send snapshot"))
                    .on_hover_text("Transfers the immutable card snapshot, publication metadata and selected files. Existing local files are read only.")
                    .clicked()
                    && let Some(publication) = selected_local
                {
                    match build_transfer(publication, artifacts) {
                        Ok((manifest, file_paths)) => self.start_upload(manifest, file_paths),
                        Err(error) => self.status = Some(error),
                    }
                }

                ui.separator();
                ui.heading("Receive a remote publication");
                ui.horizontal(|ui| {
                    ui.add(
                        egui::TextEdit::singleline(&mut self.remote_search)
                            .hint_text("Search author, description or object ID"),
                    );
                    if ui
                        .add_enabled(self.task.is_none(), egui::Button::new("Search virtual server"))
                        .clicked()
                    {
                        self.start_search();
                    }
                });
                egui::ComboBox::from_label("Remote publication")
                    .selected_text(
                        self.remote_publication
                            .as_ref()
                            .and_then(|id| {
                                self.remote_publications
                                    .iter()
                                    .find(|publication| &publication.id == id)
                            })
                            .map(publication_label)
                            .unwrap_or_else(|| "No remote publication selected".into()),
                    )
                    .show_ui(ui, |ui| {
                        for publication in &self.remote_publications {
                            ui.selectable_value(
                                &mut self.remote_publication,
                                Some(publication.id.clone()),
                                publication_label(publication),
                            );
                        }
                    });
                ui.horizontal(|ui| {
                    ui.add(
                        egui::TextEdit::singleline(&mut self.destination_folder)
                            .hint_text("Destination folder"),
                    );
                    if ui.button("Choose...").clicked()
                        && let Some(path) = rfd::FileDialog::new().pick_folder()
                    {
                        self.destination_folder = path.display().to_string();
                    }
                });
                let download_enabled = self.task.is_none()
                    && self.remote_publication.is_some()
                    && !self.destination_folder.trim().is_empty();
                if ui
                    .add_enabled(download_enabled, egui::Button::new("Receive package"))
                    .on_hover_text("Downloads to a new folder, verifies every file, and writes the card/publication manifest. Existing files are never overwritten.")
                    .clicked()
                    && let Some(publication_id) = self.remote_publication.clone()
                {
                    let destination = PathBuf::from(self.destination_folder.trim());
                    self.start_download(publication_id, destination);
                }

                if self.task.is_some() {
                    let progress = self.progress.lock().map(|value| value.clone()).unwrap_or_default();
                    ui.separator();
                    ui.label(if progress.file_name.is_empty() {
                        progress.phase.clone()
                    } else {
                        format!("{} · {}", progress.phase, progress.file_name)
                    });
                    let fraction = if progress.total_bytes == 0 {
                        0.0
                    } else {
                        (progress.bytes_done as f64 / progress.total_bytes as f64).clamp(0.0, 1.0)
                            as f32
                    };
                    ui.add(egui::ProgressBar::new(fraction).show_percentage());
                    ctx.request_repaint_after(std::time::Duration::from_millis(50));
                }
                if let Some(status) = &self.status {
                    ui.separator();
                    ui.label(status);
                }
            });
        self.open = open;
    }

    fn reconcile_selections(&mut self, local_publications: &[CatalogPublication]) {
        if self.local_publication.as_ref().is_some_and(|id| {
            !local_publications
                .iter()
                .any(|publication| &publication.id == id)
        }) {
            self.local_publication = None;
        }
        if self.remote_publication.as_ref().is_some_and(|id| {
            !self
                .remote_publications
                .iter()
                .any(|publication| &publication.id == id)
        }) {
            self.remote_publication = None;
        }
    }

    fn poll_task(&mut self) {
        let result = match self.task.as_ref().map(Receiver::try_recv) {
            Some(Ok(result)) => Some(result),
            Some(Err(TryRecvError::Disconnected)) => {
                Some(Err("Transfer worker stopped without a result.".into()))
            }
            Some(Err(TryRecvError::Empty)) | None => None,
        };
        let Some(result) = result else { return };
        self.task = None;
        match result {
            Ok(TransferTaskOutput::Uploaded(receipt)) => {
                self.status = Some(format!(
                    "Sent publication {}: {} file(s), {} bytes{}.",
                    receipt.publication_id,
                    receipt.artifact_count,
                    receipt.total_bytes,
                    if receipt.already_committed {
                        " (already received; retry was idempotent)"
                    } else {
                        ""
                    }
                ));
            }
            Ok(TransferTaskOutput::SearchResults(publications)) => {
                let count = publications.len();
                self.remote_publications = publications;
                self.remote_publication =
                    self.remote_publications.first().map(|item| item.id.clone());
                self.status = Some(format!("Found {count} virtual publication(s)."));
            }
            Ok(TransferTaskOutput::Downloaded(path)) => {
                self.status = Some(format!("Received and verified package: {}", path.display()));
            }
            Err(error) => self.status = Some(error),
        }
    }

    fn spawn_task<F>(&mut self, progress: TransferProgress, worker: F)
    where
        F: FnOnce(Arc<Mutex<TransferProgress>>) -> Result<TransferTaskOutput, String>
            + Send
            + 'static,
    {
        if self.task.is_some() {
            return;
        }
        self.status = None;
        if let Ok(mut current) = self.progress.lock() {
            *current = progress;
        }
        let progress = Arc::clone(&self.progress);
        let (sender, receiver) = mpsc::channel();
        self.task = Some(receiver);
        if let Err(error) = std::thread::Builder::new()
            .name("catalog-transfer".into())
            .spawn(move || {
                let _ = sender.send(worker(progress));
            })
        {
            self.task = None;
            self.status = Some(format!("Could not start transfer worker: {error}"));
        }
    }

    fn start_upload(
        &mut self,
        manifest: CatalogTransferManifest,
        files: Vec<(CatalogId, PathBuf)>,
    ) {
        let server = Arc::clone(&self.server);
        let total_bytes = manifest
            .artifacts
            .iter()
            .map(|artifact| artifact.size_bytes)
            .fold(0_u64, u64::saturating_add);
        self.spawn_task(
            TransferProgress {
                phase: "Preparing upload".into(),
                file_name: String::new(),
                bytes_done: 0,
                total_bytes,
            },
            move |progress| upload_bundle(&*server, manifest, files, progress),
        );
    }

    fn start_search(&mut self) {
        let server = Arc::clone(&self.server);
        let query = self.remote_search.clone();
        self.spawn_task(
            TransferProgress {
                phase: "Searching virtual service".into(),
                ..TransferProgress::default()
            },
            move |_| search_all_publications(&*server, &query),
        );
    }

    fn start_download(&mut self, publication_id: CatalogId, destination: PathBuf) {
        let server = Arc::clone(&self.server);
        self.spawn_task(
            TransferProgress {
                phase: "Preparing download".into(),
                ..TransferProgress::default()
            },
            move |progress| download_bundle(&*server, &publication_id, &destination, progress),
        );
    }
}

fn publication_label(publication: &CatalogPublication) -> String {
    let target = match publication.object_kind {
        CatalogObjectKind::Experiment => "Experiment",
        CatalogObjectKind::Series => "Series",
    };
    format!(
        "{target} · {} · {} · {} file(s)",
        publication.object_id,
        publication.created_at_rfc3339,
        publication.artifact_ids.len()
    )
}

fn build_transfer(
    publication: &CatalogPublication,
    local_artifacts: &HashMap<CatalogId, CatalogArtifactListing>,
) -> Result<(CatalogTransferManifest, Vec<(CatalogId, PathBuf)>), String> {
    let cards = match &publication.snapshot {
        Some(CatalogPublicationSnapshot::Experiment(experiment)) => {
            vec![CatalogSearchEntry::Experiment(experiment.clone())]
        }
        Some(CatalogPublicationSnapshot::Series {
            series,
            experiments,
        }) => std::iter::once(CatalogSearchEntry::Series(series.clone()))
            .chain(
                experiments
                    .iter()
                    .cloned()
                    .map(CatalogSearchEntry::Experiment),
            )
            .collect(),
        None => {
            return Err("This legacy publication has no immutable card snapshot to send.".into());
        }
    };
    let mut artifacts = Vec::with_capacity(publication.artifact_ids.len());
    let mut files = Vec::with_capacity(publication.artifact_ids.len());
    for artifact_id in &publication.artifact_ids {
        let listing = local_artifacts
            .get(artifact_id)
            .ok_or_else(|| format!("Artifact {artifact_id} is missing from the local catalog."))?;
        let path = match &listing.local_resolution {
            LocalArtifactResolution::Available(path) => path.clone(),
            LocalArtifactResolution::Missing(path) => {
                return Err(format!("Local artifact is missing: {}", path.display()));
            }
            LocalArtifactResolution::NoLocalCopy => {
                return Err(format!("Artifact {artifact_id} has no local file to send."));
            }
        };
        let artifact = &listing.artifact;
        artifacts.push(CatalogTransferArtifact {
            id: artifact.id.clone(),
            purpose: artifact.purpose.clone(),
            format: artifact.format.clone(),
            file_name: artifact.file_name.clone(),
            size_bytes: artifact.size_bytes,
            sha256: artifact.sha256.clone(),
        });
        files.push((artifact_id.clone(), path));
    }
    let manifest = CatalogTransferManifest {
        wire_schema_version:
            crate::Kinetics::experimental_kinetics::catalog::client::CATALOG_WIRE_SCHEMA_VERSION,
        publication: publication.clone(),
        cards,
        artifacts,
    };
    manifest
        .validate()
        .map_err(|error| format!("Cannot send publication: {error}"))?;
    Ok((manifest, files))
}

fn upload_bundle(
    client: &dyn CatalogRemoteClient,
    manifest: CatalogTransferManifest,
    files: Vec<(CatalogId, PathBuf)>,
    progress: Arc<Mutex<TransferProgress>>,
) -> Result<TransferTaskOutput, String> {
    let ticket = client
        .begin_upload(manifest.clone())
        .map_err(|error| format!("Could not start upload: {error}"))?;
    if ticket.already_committed {
        return client
            .commit_upload(&ticket.upload_id)
            .map(TransferTaskOutput::Uploaded)
            .map_err(|error| format!("Could not confirm previous upload: {error}"));
    }
    let files_by_id = files.into_iter().collect::<HashMap<_, _>>();
    let missing_ids = ticket
        .missing_artifacts
        .iter()
        .cloned()
        .collect::<std::collections::HashSet<_>>();
    let mut bytes_done = manifest
        .artifacts
        .iter()
        .filter(|artifact| !missing_ids.contains(&artifact.id))
        .map(|artifact| artifact.size_bytes)
        .fold(0_u64, u64::saturating_add)
        .saturating_add(
            ticket
                .next_offsets
                .values()
                .copied()
                .fold(0_u64, u64::saturating_add),
        );
    for artifact_id in &ticket.missing_artifacts {
        let artifact = manifest
            .artifacts
            .iter()
            .find(|item| &item.id == artifact_id)
            .ok_or_else(|| format!("Server requested unknown artifact {artifact_id}."))?;
        let path = files_by_id
            .get(artifact_id)
            .ok_or_else(|| format!("No local path is available for {}.", artifact.file_name))?;
        let mut file = File::open(path)
            .map_err(|error| format!("Could not open {}: {error}", path.display()))?;
        let actual_size = file
            .metadata()
            .map_err(|error| format!("Could not inspect {}: {error}", path.display()))?
            .len();
        if actual_size != artifact.size_bytes {
            return Err(format!(
                "{} changed since publication: expected {} bytes, found {}.",
                artifact.file_name, artifact.size_bytes, actual_size
            ));
        }
        let mut offset = *ticket.next_offsets.get(artifact_id).unwrap_or(&0);
        if offset > actual_size {
            return Err(format!(
                "Upload resume offset exceeds {} size.",
                artifact.file_name
            ));
        }
        file.seek(SeekFrom::Start(offset))
            .map_err(|error| format!("Could not seek {}: {error}", path.display()))?;
        if let Ok(mut current) = progress.lock() {
            current.phase = "Uploading".into();
            current.file_name = artifact.file_name.clone();
        }
        if actual_size == 0 {
            client
                .upload_chunk(&ticket.upload_id, artifact_id, 0, &[], true)
                .map_err(|error| format!("Could not upload {}: {error}", artifact.file_name))?;
            continue;
        }
        let mut buffer = vec![0_u8; CATALOG_TRANSFER_CHUNK_SIZE];
        loop {
            let count = file
                .read(&mut buffer)
                .map_err(|error| format!("Could not read {}: {error}", path.display()))?;
            if count == 0 {
                return Err(format!(
                    "Unexpected end of file while reading {}.",
                    path.display()
                ));
            }
            let is_last = offset.saturating_add(count as u64) == actual_size;
            client
                .upload_chunk(
                    &ticket.upload_id,
                    artifact_id,
                    offset,
                    &buffer[..count],
                    is_last,
                )
                .map_err(|error| format!("Upload failed for {}: {error}", artifact.file_name))?;
            offset += count as u64;
            bytes_done = bytes_done.saturating_add(count as u64);
            if let Ok(mut current) = progress.lock() {
                current.bytes_done = bytes_done.min(current.total_bytes);
            }
            if is_last {
                break;
            }
        }
    }
    client
        .commit_upload(&ticket.upload_id)
        .map(TransferTaskOutput::Uploaded)
        .map_err(|error| format!("Upload is incomplete or could not be committed: {error}"))
}

fn search_all_publications(
    client: &dyn CatalogRemoteClient,
    query: &str,
) -> Result<TransferTaskOutput, String> {
    let mut publications = Vec::new();
    let mut cursor = None;
    loop {
        let page = client
            .search_publications(&CatalogPublicationSearchRequest {
                text: query.to_owned(),
                page_size: 100,
                cursor,
            })
            .map_err(|error| format!("Remote catalog search failed: {error}"))?;
        publications.extend(page.items);
        cursor = page.next_cursor;
        if cursor.is_none() {
            break;
        }
    }
    Ok(TransferTaskOutput::SearchResults(publications))
}

fn download_bundle(
    client: &dyn CatalogRemoteClient,
    publication_id: &CatalogId,
    destination: &Path,
    progress: Arc<Mutex<TransferProgress>>,
) -> Result<TransferTaskOutput, String> {
    let manifest = client
        .get_transfer_manifest(publication_id)
        .map_err(|error| format!("Could not receive publication metadata: {error}"))?;
    manifest
        .validate()
        .map_err(|error| format!("Remote publication is invalid: {error}"))?;
    if !destination.is_dir() {
        return Err(format!(
            "Destination is not an existing folder: {}",
            destination.display()
        ));
    }
    let final_folder = destination.join(format!("publication-{}", publication_id));
    if final_folder.exists() {
        return Err(format!(
            "Destination already exists: {}",
            final_folder.display()
        ));
    }
    let staging = destination.join(format!(
        ".catalog-transfer-{}-{}.partial",
        publication_id,
        uuid::Uuid::new_v4()
    ));
    fs::create_dir(&staging)
        .map_err(|error| format!("Could not create temporary receive folder: {error}"))?;
    let result = download_into_staging(client, publication_id, &manifest, &staging, &progress);
    if let Err(error) = result {
        let _ = fs::remove_dir_all(&staging);
        return Err(error);
    }
    if let Err(error) = fs::rename(&staging, &final_folder) {
        let _ = fs::remove_dir_all(&staging);
        return Err(format!(
            "Could not publish verified download folder: {error}"
        ));
    }
    Ok(TransferTaskOutput::Downloaded(final_folder))
}

fn download_into_staging(
    client: &dyn CatalogRemoteClient,
    publication_id: &CatalogId,
    manifest: &CatalogTransferManifest,
    staging: &Path,
    progress: &Arc<Mutex<TransferProgress>>,
) -> Result<(), String> {
    let total_bytes = manifest
        .artifacts
        .iter()
        .map(|artifact| artifact.size_bytes)
        .fold(0_u64, u64::saturating_add);
    let mut bytes_done = 0_u64;
    for artifact in &manifest.artifacts {
        let path = staging.join(&artifact.file_name);
        let mut output = OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&path)
            .map_err(|error| format!("Could not create {}: {error}", path.display()))?;
        let mut hasher = Sha256::new();
        let mut offset = 0_u64;
        if let Ok(mut current) = progress.lock() {
            current.phase = "Downloading".into();
            current.file_name = artifact.file_name.clone();
            current.total_bytes = total_bytes;
        }
        loop {
            let chunk = client
                .download_chunk(
                    publication_id,
                    &artifact.id,
                    offset,
                    CATALOG_TRANSFER_CHUNK_SIZE,
                )
                .map_err(|error| format!("Download failed for {}: {error}", artifact.file_name))?;
            if chunk.offset != offset || (chunk.bytes.is_empty() && !chunk.is_last) {
                return Err(format!(
                    "Remote service returned an invalid chunk for {}.",
                    artifact.file_name
                ));
            }
            output
                .write_all(&chunk.bytes)
                .map_err(|error| format!("Could not write {}: {error}", path.display()))?;
            hasher.update(&chunk.bytes);
            offset = offset.saturating_add(chunk.bytes.len() as u64);
            bytes_done = bytes_done.saturating_add(chunk.bytes.len() as u64);
            if let Ok(mut current) = progress.lock() {
                current.bytes_done = bytes_done.min(total_bytes);
            }
            if chunk.is_last {
                break;
            }
        }
        output
            .flush()
            .and_then(|()| output.sync_all())
            .map_err(|error| format!("Could not finalize {}: {error}", path.display()))?;
        let actual_checksum = digest_hex(hasher.finalize().as_slice());
        if offset != artifact.size_bytes || !actual_checksum.eq_ignore_ascii_case(&artifact.sha256)
        {
            return Err(format!(
                "Downloaded file failed size/SHA-256 verification: {}",
                artifact.file_name
            ));
        }
    }
    let manifest_path = staging.join("catalog-transfer.json");
    let encoded = serde_json::to_vec_pretty(manifest)
        .map_err(|error| format!("Could not serialize received card manifest: {error}"))?;
    let mut output = OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&manifest_path)
        .map_err(|error| format!("Could not create transfer manifest: {error}"))?;
    output
        .write_all(&encoded)
        .and_then(|()| output.sync_all())
        .map_err(|error| format!("Could not save transfer manifest: {error}"))
}

fn digest_hex(digest: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut encoded = String::with_capacity(digest.len() * 2);
    for byte in digest {
        encoded.push(HEX[(byte >> 4) as usize] as char);
        encoded.push(HEX[(byte & 0x0f) as usize] as char);
    }
    encoded
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Kinetics::experimental_kinetics::catalog::CatalogArtifact;
    use crate::Kinetics::experimental_kinetics::catalog::client::CATALOG_WIRE_SCHEMA_VERSION;
    use crate::Kinetics::experimental_kinetics::catalog::{
        CatalogArtifactPurpose, CatalogExperiment, CatalogPublicationSnapshot, SourceKind,
    };
    use egui_kittest::{Harness, kittest::Queryable};

    fn experiment_card() -> CatalogExperiment {
        let id = CatalogId::new();
        CatalogExperiment {
            id: id.clone(),
            source_identity: id.as_str().into(),
            display_name: "remote-test-run".into(),
            source_kind: SourceKind::Measured,
            date: None,
            sample: None,
            instrument: Some("TGA-1".into()),
            operator: None,
            thermal_mode: None,
            temperature_k: Some(500.0),
            heating_rate_k_per_min: None,
            comment: Some("transfer harness".into()),
            tags: vec![],
        }
    }

    #[test]
    fn virtual_server_upload_search_and_receive_work_through_gui() {
        let source_root = tempfile::tempdir().unwrap();
        let destination_root = tempfile::tempdir().unwrap();
        let bytes = b"time,mass\n0,10\n1,9\n";
        let source_path = source_root.path().join("typed.csv");
        fs::write(&source_path, bytes).unwrap();
        let experiment = experiment_card();
        let artifact_id = CatalogId::new();
        let publication = CatalogPublication {
            id: CatalogId::new(),
            object_kind: CatalogObjectKind::Experiment,
            object_id: experiment.id.clone(),
            parent_publication_id: None,
            created_at_rfc3339: "2026-12-03T10:00:00Z".into(),
            author: Some("operator".into()),
            description: Some("round-trip test".into()),
            series_members: vec![],
            artifact_ids: vec![artifact_id.clone()],
            snapshot: Some(CatalogPublicationSnapshot::Experiment(experiment.clone())),
            typed_documents: vec![],
        };
        let artifact = CatalogArtifact {
            id: artifact_id.clone(),
            purpose: CatalogArtifactPurpose::TypedKiTheDocument,
            format: "csv".into(),
            file_name: "typed.csv".into(),
            size_bytes: bytes.len() as u64,
            sha256: digest_hex(&Sha256::digest(bytes)),
            locations: vec![],
        };
        let local_publications = vec![publication.clone()];
        let artifacts = HashMap::from([(
            artifact_id,
            CatalogArtifactListing {
                artifact,
                local_resolution: LocalArtifactResolution::Available(source_path.clone()),
            },
        )]);
        let mut transfer_ui = CatalogTransferUi::default();
        transfer_ui.open();
        transfer_ui.local_publication = Some(publication.id.clone());
        transfer_ui.destination_folder = destination_root.path().display().to_string();
        let mut harness = Harness::builder()
            .with_accessibility_check(false)
            .build_ui_state(
                |ui, state: &mut CatalogTransferUi| {
                    state.show(ui.ctx(), &local_publications, &artifacts)
                },
                transfer_ui,
            );

        harness.run();
        harness.get_by_label("Send snapshot").click();
        wait_for_transfer(&mut harness);
        assert!(
            harness
                .state()
                .status
                .as_deref()
                .unwrap()
                .contains("Sent publication")
        );

        harness.get_by_label("Search virtual server").click();
        wait_for_transfer(&mut harness);
        assert_eq!(harness.state().remote_publications.len(), 1);
        harness.get_by_label("Receive package").click();
        wait_for_transfer(&mut harness);
        let received_dir = destination_root
            .path()
            .join(format!("publication-{}", publication.id));
        assert_eq!(fs::read(received_dir.join("typed.csv")).unwrap(), bytes);
        let received_manifest: CatalogTransferManifest =
            serde_json::from_slice(&fs::read(received_dir.join("catalog-transfer.json")).unwrap())
                .unwrap();
        assert_eq!(received_manifest.publication, publication);
        assert_eq!(
            received_manifest.wire_schema_version,
            CATALOG_WIRE_SCHEMA_VERSION
        );
        assert!(
            harness
                .state()
                .status
                .as_deref()
                .unwrap()
                .contains("verified package")
        );
    }

    fn wait_for_transfer(harness: &mut Harness<'_, CatalogTransferUi>) {
        for _ in 0..200 {
            harness.run();
            if harness.state().task.is_none() {
                return;
            }
            std::thread::sleep(std::time::Duration::from_millis(5));
        }
        panic!("virtual catalog transfer did not complete");
    }
}