kcl-lib 0.2.143

KittyCAD Language implementation and tools
Documentation
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
//! Standard library clone.

use std::collections::HashMap;

use kcmc::ModelingCmd;
use kcmc::each_cmd as mcmd;
use kcmc::ok_response::OkModelingCmdResponse;
use kcmc::shared::BodyType;
use kcmc::websocket::OkWebSocketResponseData;
use kittycad_modeling_cmds::{self as kcmc};

use super::extrude::do_post_extrude;
use crate::errors::KclError;
use crate::errors::KclErrorDetails;
use crate::execution::ExecState;
use crate::execution::ExtrudeSurface;
use crate::execution::GeometryWithImportedGeometry;
use crate::execution::KclValue;
use crate::execution::ModelingCmdMeta;
use crate::execution::Sketch;
use crate::execution::Solid;
use crate::execution::types::ArrayLen;
use crate::execution::types::PrimitiveType;
use crate::execution::types::RuntimeType;
use crate::parsing::ast::types::TagNode;
use crate::std::Args;
use crate::std::extrude::BeingExtruded;
use crate::std::extrude::NamedCapTags;

type Result<T> = std::result::Result<T, KclError>;

/// Clone a sketch or solid.
///
/// This works essentially like a copy-paste operation.
pub async fn clone(exec_state: &mut ExecState, args: Args) -> Result<KclValue> {
    let geometries = args.get_unlabeled_kw_arg(
        "geometry",
        &RuntimeType::Array(
            Box::new(RuntimeType::Union(vec![
                RuntimeType::Primitive(PrimitiveType::Sketch),
                RuntimeType::Primitive(PrimitiveType::Solid),
                RuntimeType::imported(),
            ])),
            ArrayLen::Minimum(1),
        ),
        exec_state,
    )?;

    let cloned = inner_clone(geometries, exec_state, args).await?;
    Ok(cloned.into())
}

async fn inner_clone(
    geometries: Vec<GeometryWithImportedGeometry>,
    exec_state: &mut ExecState,
    args: Args,
) -> Result<Vec<GeometryWithImportedGeometry>> {
    let mut res = vec![];

    for g in geometries {
        let new_id = exec_state.next_uuid();
        let mut geometry = g.clone();
        let old_id = geometry.id(&args.ctx).await?;

        let mut new_geometry = match &geometry {
            GeometryWithImportedGeometry::ImportedGeometry(imported) => {
                let mut new_imported = imported.clone();
                new_imported.id = new_id;
                GeometryWithImportedGeometry::ImportedGeometry(new_imported)
            }
            GeometryWithImportedGeometry::Sketch(sketch) => {
                let mut new_sketch = sketch.clone();
                new_sketch.id = new_id;
                new_sketch.original_id = new_id;
                new_sketch.artifact_id = new_id.into();
                GeometryWithImportedGeometry::Sketch(new_sketch)
            }
            GeometryWithImportedGeometry::Solid(solid) => {
                // We flush before the clone so all the shit exists.
                exec_state
                    .flush_batch_for_solids(
                        ModelingCmdMeta::from_args(exec_state, &args),
                        std::slice::from_ref(solid),
                    )
                    .await?;

                let mut new_solid = solid.clone();
                new_solid.id = new_id;
                if let Some(sketch) = new_solid.sketch_mut() {
                    sketch.original_id = new_id;
                }
                new_solid.artifact_id = new_id.into();
                GeometryWithImportedGeometry::Solid(new_solid)
            }
        };

        if args.ctx.no_engine_commands().await {
            res.push(new_geometry);
        } else {
            exec_state
                .batch_modeling_cmd(
                    ModelingCmdMeta::from_args_id(exec_state, &args, new_id),
                    ModelingCmd::from(mcmd::EntityClone::builder().entity_id(old_id).build()),
                )
                .await?;

            fix_tags_and_references(&mut new_geometry, old_id, exec_state, &args)
                .await
                .map_err(|e| {
                    KclError::new_internal(KclErrorDetails::new(
                        format!("failed to fix tags and references: {e:?}"),
                        vec![args.source_range],
                    ))
                })?;
            res.push(new_geometry)
        }
    }

    Ok(res)
}
/// Fix the tags and references of the cloned geometry.
async fn fix_tags_and_references(
    new_geometry: &mut GeometryWithImportedGeometry,
    old_geometry_id: uuid::Uuid,
    exec_state: &mut ExecState,
    args: &Args,
) -> Result<()> {
    let new_geometry_id = new_geometry.id(&args.ctx).await?;
    let entity_id_map = get_old_new_child_map(new_geometry_id, old_geometry_id, exec_state, args).await?;

    // Fix the path references in the new geometry.
    match new_geometry {
        GeometryWithImportedGeometry::ImportedGeometry(_) => {}
        GeometryWithImportedGeometry::Sketch(sketch) => {
            sketch.clone = Some(old_geometry_id);
            fix_sketch_tags_and_references(sketch, &entity_id_map, exec_state, args, None).await?;
        }
        GeometryWithImportedGeometry::Solid(solid) => {
            let (start_tag, end_tag) = get_named_cap_tags(solid);
            let solid_value = solid.value.clone();

            // Make the sketch id the new geometry id.
            let sketch = solid.sketch_mut().ok_or_else(|| {
                KclError::new_type(KclErrorDetails::new(
                    "Cloning solids created without a sketch is not yet supported.".to_owned(),
                    vec![args.source_range],
                ))
            })?;
            sketch.id = new_geometry_id;
            sketch.original_id = new_geometry_id;
            sketch.artifact_id = new_geometry_id.into();
            sketch.clone = Some(old_geometry_id);

            fix_sketch_tags_and_references(sketch, &entity_id_map, exec_state, args, Some(solid_value)).await?;
            let sketch_for_post = sketch.clone();

            // Fix the edge cuts.
            for edge_cut in solid.edge_cuts.iter_mut() {
                if let Some(id) = entity_id_map.get(&edge_cut.id()) {
                    edge_cut.set_id(*id);
                } else {
                    crate::log::logln!(
                        "Failed to find new edge cut id for old edge cut id: {:?}",
                        edge_cut.id()
                    );
                }
                if let Some(new_edge_id) = entity_id_map.get(&edge_cut.edge_id()) {
                    edge_cut.set_edge_id(*new_edge_id);
                } else {
                    crate::log::logln!("Failed to find new edge id for old edge id: {:?}", edge_cut.edge_id());
                }
            }

            // Do the after extrude things to update those ids, based on the new sketch
            // information.
            let new_solid = do_post_extrude(
                &sketch_for_post,
                new_geometry_id.into(),
                solid.sectional,
                &NamedCapTags {
                    start: start_tag.as_ref(),
                    end: end_tag.as_ref(),
                },
                kittycad_modeling_cmds::shared::ExtrudeMethod::New,
                exec_state,
                args,
                None,
                Some(&entity_id_map.clone()),
                BodyType::Solid, // TODO: Support surface clones.
                BeingExtruded::Sketch,
            )
            .await?;

            *solid = new_solid;
        }
    }

    Ok(())
}

async fn get_old_new_child_map(
    new_geometry_id: uuid::Uuid,
    old_geometry_id: uuid::Uuid,
    exec_state: &mut ExecState,
    args: &Args,
) -> Result<HashMap<uuid::Uuid, uuid::Uuid>> {
    // Get the old geometries entity ids.
    let response = exec_state
        .send_modeling_cmd(
            ModelingCmdMeta::from_args(exec_state, args),
            ModelingCmd::from(
                mcmd::EntityGetAllChildUuids::builder()
                    .entity_id(old_geometry_id)
                    .build(),
            ),
        )
        .await?;
    let OkWebSocketResponseData::Modeling {
        modeling_response: OkModelingCmdResponse::EntityGetAllChildUuids(old_resp),
    } = response
    else {
        return Err(KclError::new_engine(KclErrorDetails::new(
            format!("EntityGetAllChildUuids response was not as expected: {response:?}"),
            vec![args.source_range],
        )));
    };
    let old_entity_ids = old_resp.entity_ids;

    // Get the new geometries entity ids.
    let response = exec_state
        .send_modeling_cmd(
            ModelingCmdMeta::from_args(exec_state, args),
            ModelingCmd::from(
                mcmd::EntityGetAllChildUuids::builder()
                    .entity_id(new_geometry_id)
                    .build(),
            ),
        )
        .await?;
    let OkWebSocketResponseData::Modeling {
        modeling_response: OkModelingCmdResponse::EntityGetAllChildUuids(new_resp),
    } = response
    else {
        return Err(KclError::new_engine(KclErrorDetails::new(
            format!("EntityGetAllChildUuids response was not as expected: {response:?}"),
            vec![args.source_range],
        )));
    };
    let new_entity_ids = new_resp.entity_ids;

    // Create a map of old entity ids to new entity ids.
    Ok(HashMap::from_iter(
        old_entity_ids
            .iter()
            .zip(new_entity_ids.iter())
            .map(|(old_id, new_id)| (*old_id, *new_id)),
    ))
}

/// Fix the tags and references of a sketch.
async fn fix_sketch_tags_and_references(
    new_sketch: &mut Sketch,
    entity_id_map: &HashMap<uuid::Uuid, uuid::Uuid>,
    exec_state: &mut ExecState,
    args: &Args,
    surfaces: Option<Vec<ExtrudeSurface>>,
) -> Result<()> {
    // Fix the path references in the sketch.
    for path in new_sketch.paths.as_mut_slice() {
        if let Some(new_path_id) = entity_id_map.get(&path.get_id()) {
            path.set_id(*new_path_id);
        } else {
            // We log on these because we might have already flushed and the id is no longer
            // relevant since filleted or something.
            crate::log::logln!("Failed to find new path id for old path id: {:?}", path.get_id());
        }
    }

    // Map the surface tags to the new surface ids.
    let mut surface_id_map: HashMap<String, &ExtrudeSurface> = HashMap::new();
    let surfaces = surfaces.unwrap_or_default();
    for surface in surfaces.iter() {
        if let Some(tag) = surface.get_tag() {
            surface_id_map.insert(tag.name.clone(), surface);
        }
    }

    // Fix the tags
    // This is annoying, in order to fix the tags we need to iterate over the paths again, but not
    // mutable borrow the paths.
    for path in new_sketch.paths.clone() {
        // Check if this path has a tag.
        if let Some(tag) = path.get_tag() {
            let mut surface = None;
            if let Some(found_surface) = surface_id_map.get(&tag.name) {
                let mut new_surface = (*found_surface).clone();
                let Some(new_face_id) = entity_id_map.get(&new_surface.face_id()).copied() else {
                    return Err(KclError::new_engine(KclErrorDetails::new(
                        format!(
                            "Failed to find new face id for old face id: {:?}",
                            new_surface.face_id()
                        ),
                        vec![args.source_range],
                    )));
                };
                new_surface.set_face_id(new_face_id);
                surface = Some(new_surface);
            }

            new_sketch.add_tag(&tag, &path, exec_state, surface.as_ref());
        }
    }

    // Fix the base path.
    if let Some(new_base_path) = entity_id_map.get(&new_sketch.start.geo_meta.id) {
        new_sketch.start.geo_meta.id = *new_base_path;
    } else {
        crate::log::logln!(
            "Failed to find new base path id for old base path id: {:?}",
            new_sketch.start.geo_meta.id
        );
    }

    Ok(())
}

// Return the named cap tags for the original solid.
fn get_named_cap_tags(solid: &Solid) -> (Option<TagNode>, Option<TagNode>) {
    let mut start_tag = None;
    let mut end_tag = None;
    // Check the start cap.
    if let Some(start_cap_id) = solid.start_cap_id {
        // Check if we had a value for that cap.
        for value in &solid.value {
            if value.get_id() == start_cap_id {
                start_tag = value.get_tag();
                break;
            }
        }
    }

    // Check the end cap.
    if let Some(end_cap_id) = solid.end_cap_id {
        // Check if we had a value for that cap.
        for value in &solid.value {
            if value.get_id() == end_cap_id {
                end_tag = value.get_tag();
                break;
            }
        }
    }

    (start_tag, end_tag)
}

#[cfg(test)]
mod tests {
    use pretty_assertions::assert_eq;
    use pretty_assertions::assert_ne;

    use crate::exec::KclValue;

    // Ensure the clone function returns a sketch with different ids for all the internal paths and
    // the resulting sketch.
    #[tokio::test(flavor = "multi_thread")]
    async fn kcl_test_clone_sketch() {
        let code = r#"cube = startSketchOn(XY)
    |> startProfile(at = [0,0])
    |> line(end = [0, 10])
    |> line(end = [10, 0])
    |> line(end = [0, -10])
    |> close()

clonedCube = clone(cube)
"#;
        let ctx = crate::test_server::new_context(true, None).await.unwrap();
        let program = crate::Program::parse_no_errs(code).unwrap();

        // Execute the program.
        let result = ctx.run_with_caching(program.clone()).await.unwrap();
        let cube = result.variables.get("cube").unwrap();
        let cloned_cube = result.variables.get("clonedCube").unwrap();

        assert_ne!(cube, cloned_cube);

        let KclValue::Sketch { value: cube } = cube else {
            panic!("Expected a sketch, got: {cube:?}");
        };
        let KclValue::Sketch { value: cloned_cube } = cloned_cube else {
            panic!("Expected a sketch, got: {cloned_cube:?}");
        };

        assert_ne!(cube.id, cloned_cube.id);
        assert_ne!(cube.original_id, cloned_cube.original_id);
        assert_ne!(cube.artifact_id, cloned_cube.artifact_id);

        assert_eq!(cloned_cube.artifact_id, cloned_cube.id.into());
        assert_eq!(cloned_cube.original_id, cloned_cube.id);

        for (path, cloned_path) in cube.paths.iter().zip(cloned_cube.paths.iter()) {
            assert_ne!(path.get_id(), cloned_path.get_id());
            assert_eq!(path.get_tag(), cloned_path.get_tag());
        }

        assert_eq!(cube.tags.len(), 0);
        assert_eq!(cloned_cube.tags.len(), 0);

        ctx.close().await;
    }

    // Ensure the clone function returns a solid with different ids for all the internal paths and
    // references.
    #[tokio::test(flavor = "multi_thread")]
    async fn kcl_test_clone_solid() {
        let code = r#"cube = startSketchOn(XY)
    |> startProfile(at = [0,0])
    |> line(end = [0, 10])
    |> line(end = [10, 0])
    |> line(end = [0, -10])
    |> close()
    |> extrude(length = 5)

clonedCube = clone(cube)
"#;
        let ctx = crate::test_server::new_context(true, None).await.unwrap();
        let program = crate::Program::parse_no_errs(code).unwrap();

        // Execute the program.
        let result = ctx.run_with_caching(program.clone()).await.unwrap();
        let cube = result.variables.get("cube").unwrap();
        let cloned_cube = result.variables.get("clonedCube").unwrap();

        assert_ne!(cube, cloned_cube);

        let KclValue::Solid { value: cube } = cube else {
            panic!("Expected a solid, got: {cube:?}");
        };
        let KclValue::Solid { value: cloned_cube } = cloned_cube else {
            panic!("Expected a solid, got: {cloned_cube:?}");
        };
        let cube_sketch = cube.sketch().expect("Expected cube to have a sketch");
        let cloned_cube_sketch = cloned_cube.sketch().expect("Expected cloned cube to have a sketch");

        assert_ne!(cube.id, cloned_cube.id);
        assert_ne!(cube_sketch.id, cloned_cube_sketch.id);
        assert_ne!(cube_sketch.original_id, cloned_cube_sketch.original_id);
        assert_ne!(cube.artifact_id, cloned_cube.artifact_id);
        assert_ne!(cube_sketch.artifact_id, cloned_cube_sketch.artifact_id);

        assert_eq!(cloned_cube.artifact_id, cloned_cube.id.into());

        for (path, cloned_path) in cube_sketch.paths.iter().zip(cloned_cube_sketch.paths.iter()) {
            assert_ne!(path.get_id(), cloned_path.get_id());
            assert_eq!(path.get_tag(), cloned_path.get_tag());
        }

        for (value, cloned_value) in cube.value.iter().zip(cloned_cube.value.iter()) {
            assert_ne!(value.get_id(), cloned_value.get_id());
            assert_eq!(value.get_tag(), cloned_value.get_tag());
        }

        assert_eq!(cube_sketch.tags.len(), 0);
        assert_eq!(cloned_cube_sketch.tags.len(), 0);

        assert_eq!(cube.edge_cuts.len(), 0);
        assert_eq!(cloned_cube.edge_cuts.len(), 0);

        ctx.close().await;
    }

    // Ensure the clone function returns a sketch with different ids for all the internal paths and
    // the resulting sketch.
    // AND TAGS.
    #[tokio::test(flavor = "multi_thread")]
    async fn kcl_test_clone_sketch_with_tags() {
        let code = r#"cube = startSketchOn(XY)
    |> startProfile(at = [0,0]) // tag this one
    |> line(end = [0, 10], tag = $tag02)
    |> line(end = [10, 0], tag = $tag03)
    |> line(end = [0, -10], tag = $tag04)
    |> close(tag = $tag05)

clonedCube = clone(cube)
"#;
        let ctx = crate::test_server::new_context(true, None).await.unwrap();
        let program = crate::Program::parse_no_errs(code).unwrap();

        // Execute the program.
        let result = ctx.run_with_caching(program.clone()).await.unwrap();
        let cube = result.variables.get("cube").unwrap();
        let cloned_cube = result.variables.get("clonedCube").unwrap();

        assert_ne!(cube, cloned_cube);

        let KclValue::Sketch { value: cube } = cube else {
            panic!("Expected a sketch, got: {cube:?}");
        };
        let KclValue::Sketch { value: cloned_cube } = cloned_cube else {
            panic!("Expected a sketch, got: {cloned_cube:?}");
        };

        assert_ne!(cube.id, cloned_cube.id);
        assert_ne!(cube.original_id, cloned_cube.original_id);

        for (path, cloned_path) in cube.paths.iter().zip(cloned_cube.paths.iter()) {
            assert_ne!(path.get_id(), cloned_path.get_id());
            assert_eq!(path.get_tag(), cloned_path.get_tag());
        }

        for (tag_name, tag) in &cube.tags {
            let cloned_tag = cloned_cube.tags.get(tag_name).unwrap();

            let tag_info = tag.get_cur_info().unwrap();
            let cloned_tag_info = cloned_tag.get_cur_info().unwrap();

            assert_ne!(tag_info.id, cloned_tag_info.id);
            assert_ne!(tag_info.geometry.id(), cloned_tag_info.geometry.id());
            assert_ne!(tag_info.path, cloned_tag_info.path);
            assert_eq!(tag_info.surface, None);
            assert_eq!(cloned_tag_info.surface, None);
        }

        ctx.close().await;
    }

    // Ensure the clone function returns a solid with different ids for all the internal paths and
    // references.
    // WITH TAGS.
    #[tokio::test(flavor = "multi_thread")]
    async fn kcl_test_clone_solid_with_tags() {
        let code = r#"cube = startSketchOn(XY)
    |> startProfile(at = [0,0]) // tag this one
    |> line(end = [0, 10], tag = $tag02)
    |> line(end = [10, 0], tag = $tag03)
    |> line(end = [0, -10], tag = $tag04)
    |> close(tag = $tag05)
    |> extrude(length = 5) // TODO: Tag these

clonedCube = clone(cube)
"#;
        let ctx = crate::test_server::new_context(true, None).await.unwrap();
        let program = crate::Program::parse_no_errs(code).unwrap();

        // Execute the program.
        let result = ctx.run_with_caching(program.clone()).await.unwrap();
        let cube = result.variables.get("cube").unwrap();
        let cloned_cube = result.variables.get("clonedCube").unwrap();

        assert_ne!(cube, cloned_cube);

        let KclValue::Solid { value: cube } = cube else {
            panic!("Expected a solid, got: {cube:?}");
        };
        let KclValue::Solid { value: cloned_cube } = cloned_cube else {
            panic!("Expected a solid, got: {cloned_cube:?}");
        };
        let cube_sketch = cube.sketch().expect("Expected cube to have a sketch");
        let cloned_cube_sketch = cloned_cube.sketch().expect("Expected cloned cube to have a sketch");

        assert_ne!(cube.id, cloned_cube.id);
        assert_ne!(cube_sketch.id, cloned_cube_sketch.id);
        assert_ne!(cube_sketch.original_id, cloned_cube_sketch.original_id);
        assert_ne!(cube.artifact_id, cloned_cube.artifact_id);
        assert_ne!(cube_sketch.artifact_id, cloned_cube_sketch.artifact_id);

        assert_eq!(cloned_cube.artifact_id, cloned_cube.id.into());

        for (path, cloned_path) in cube_sketch.paths.iter().zip(cloned_cube_sketch.paths.iter()) {
            assert_ne!(path.get_id(), cloned_path.get_id());
            assert_eq!(path.get_tag(), cloned_path.get_tag());
        }

        for (value, cloned_value) in cube.value.iter().zip(cloned_cube.value.iter()) {
            assert_ne!(value.get_id(), cloned_value.get_id());
            assert_eq!(value.get_tag(), cloned_value.get_tag());
        }

        for (tag_name, tag) in &cube_sketch.tags {
            let cloned_tag = cloned_cube_sketch.tags.get(tag_name).unwrap();

            let tag_info = tag.get_cur_info().unwrap();
            let cloned_tag_info = cloned_tag.get_cur_info().unwrap();

            assert_ne!(tag_info.id, cloned_tag_info.id);
            assert_ne!(tag_info.geometry.id(), cloned_tag_info.geometry.id());
            assert_ne!(tag_info.path, cloned_tag_info.path);
            assert_ne!(tag_info.surface, cloned_tag_info.surface);
        }

        assert_eq!(cube.edge_cuts.len(), 0);
        assert_eq!(cloned_cube.edge_cuts.len(), 0);

        ctx.close().await;
    }

    // Ensure we can get all paths even on a sketch where we closed it and it was already closed.
    #[tokio::test(flavor = "multi_thread")]
    #[ignore = "this test is not working yet, need to fix the getting of ids if sketch already closed"]
    async fn kcl_test_clone_cube_already_closed_sketch() {
        let code = r#"// Clone a basic solid and move it.

exampleSketch = startSketchOn(XY)
  |> startProfile(at = [0, 0])
  |> line(end = [10, 0])
  |> line(end = [0, 10])
  |> line(end = [-10, 0])
  |> line(end = [0, -10])
  |> close()

cube = extrude(exampleSketch, length = 5)
clonedCube = clone(cube)
    |> translate(
        x = 25.0,
    )"#;
        let ctx = crate::test_server::new_context(true, None).await.unwrap();
        let program = crate::Program::parse_no_errs(code).unwrap();

        // Execute the program.
        let result = ctx.run_with_caching(program.clone()).await.unwrap();
        let cube = result.variables.get("cube").unwrap();
        let cloned_cube = result.variables.get("clonedCube").unwrap();

        assert_ne!(cube, cloned_cube);

        let KclValue::Solid { value: cube } = cube else {
            panic!("Expected a solid, got: {cube:?}");
        };
        let KclValue::Solid { value: cloned_cube } = cloned_cube else {
            panic!("Expected a solid, got: {cloned_cube:?}");
        };
        let cube_sketch = cube.sketch().expect("Expected cube to have a sketch");
        let cloned_cube_sketch = cloned_cube.sketch().expect("Expected cloned cube to have a sketch");

        assert_ne!(cube.id, cloned_cube.id);
        assert_ne!(cube_sketch.id, cloned_cube_sketch.id);
        assert_ne!(cube_sketch.original_id, cloned_cube_sketch.original_id);
        assert_ne!(cube.artifact_id, cloned_cube.artifact_id);
        assert_ne!(cube_sketch.artifact_id, cloned_cube_sketch.artifact_id);

        assert_eq!(cloned_cube.artifact_id, cloned_cube.id.into());

        for (path, cloned_path) in cube_sketch.paths.iter().zip(cloned_cube_sketch.paths.iter()) {
            assert_ne!(path.get_id(), cloned_path.get_id());
            assert_eq!(path.get_tag(), cloned_path.get_tag());
        }

        for (value, cloned_value) in cube.value.iter().zip(cloned_cube.value.iter()) {
            assert_ne!(value.get_id(), cloned_value.get_id());
            assert_eq!(value.get_tag(), cloned_value.get_tag());
        }

        for (tag_name, tag) in &cube_sketch.tags {
            let cloned_tag = cloned_cube_sketch.tags.get(tag_name).unwrap();

            let tag_info = tag.get_cur_info().unwrap();
            let cloned_tag_info = cloned_tag.get_cur_info().unwrap();

            assert_ne!(tag_info.id, cloned_tag_info.id);
            assert_ne!(tag_info.geometry.id(), cloned_tag_info.geometry.id());
            assert_ne!(tag_info.path, cloned_tag_info.path);
            assert_ne!(tag_info.surface, cloned_tag_info.surface);
        }

        for (edge_cut, cloned_edge_cut) in cube.edge_cuts.iter().zip(cloned_cube.edge_cuts.iter()) {
            assert_ne!(edge_cut.id(), cloned_edge_cut.id());
            assert_ne!(edge_cut.edge_id(), cloned_edge_cut.edge_id());
            assert_eq!(edge_cut.tag(), cloned_edge_cut.tag());
        }

        ctx.close().await;
    }

    // Ensure the clone function returns a solid with different ids for all the internal paths and
    // references.
    // WITH TAGS AND EDGE CUTS.
    #[tokio::test(flavor = "multi_thread")]
    #[ignore] // until https://github.com/KittyCAD/engine/pull/3380 lands
    async fn kcl_test_clone_solid_with_edge_cuts() {
        let code = r#"cube = startSketchOn(XY)
    |> startProfile(at = [0,0]) // tag this one
    |> line(end = [0, 10], tag = $tag02)
    |> line(end = [10, 0], tag = $tag03)
    |> line(end = [0, -10], tag = $tag04)
    |> close(tag = $tag05)
    |> extrude(length = 5) // TODO: Tag these
  |> fillet(
    radius = 2,
    tags = [
      getNextAdjacentEdge(tag02),
    ],
    tag = $fillet01,
  )
  |> fillet(
    radius = 2,
    tags = [
      getNextAdjacentEdge(tag04),
    ],
    tag = $fillet02,
  )
  |> chamfer(
    length = 2,
    tags = [
      getNextAdjacentEdge(tag03),
    ],
    tag = $chamfer01,
  )
  |> chamfer(
    length = 2,
    tags = [
      getNextAdjacentEdge(tag05),
    ],
    tag = $chamfer02,
  )

clonedCube = clone(cube)
"#;
        let ctx = crate::test_server::new_context(true, None).await.unwrap();
        let program = crate::Program::parse_no_errs(code).unwrap();

        // Execute the program.
        let result = ctx.run_with_caching(program.clone()).await.unwrap();
        let cube = result.variables.get("cube").unwrap();
        let cloned_cube = result.variables.get("clonedCube").unwrap();

        assert_ne!(cube, cloned_cube);

        let KclValue::Solid { value: cube } = cube else {
            panic!("Expected a solid, got: {cube:?}");
        };
        let KclValue::Solid { value: cloned_cube } = cloned_cube else {
            panic!("Expected a solid, got: {cloned_cube:?}");
        };
        let cube_sketch = cube.sketch().expect("Expected cube to have a sketch");
        let cloned_cube_sketch = cloned_cube.sketch().expect("Expected cloned cube to have a sketch");

        assert_ne!(cube.id, cloned_cube.id);
        assert_ne!(cube_sketch.id, cloned_cube_sketch.id);
        assert_ne!(cube_sketch.original_id, cloned_cube_sketch.original_id);
        assert_ne!(cube.artifact_id, cloned_cube.artifact_id);
        assert_ne!(cube_sketch.artifact_id, cloned_cube_sketch.artifact_id);

        assert_eq!(cloned_cube.artifact_id, cloned_cube.id.into());

        for (value, cloned_value) in cube.value.iter().zip(cloned_cube.value.iter()) {
            assert_ne!(value.get_id(), cloned_value.get_id());
            assert_eq!(value.get_tag(), cloned_value.get_tag());
        }

        for (edge_cut, cloned_edge_cut) in cube.edge_cuts.iter().zip(cloned_cube.edge_cuts.iter()) {
            assert_ne!(edge_cut.id(), cloned_edge_cut.id());
            assert_ne!(edge_cut.edge_id(), cloned_edge_cut.edge_id());
            assert_eq!(edge_cut.tag(), cloned_edge_cut.tag());
        }

        ctx.close().await;
    }
}