Skip to main content

kcl_lib/std/
clone.rs

1//! Standard library clone.
2
3use std::collections::HashMap;
4
5use kcmc::ModelingCmd;
6use kcmc::each_cmd as mcmd;
7use kcmc::ok_response::OkModelingCmdResponse;
8use kcmc::websocket::OkWebSocketResponseData;
9use kittycad_modeling_cmds::{self as kcmc};
10
11use super::extrude::do_post_extrude;
12use crate::errors::KclError;
13use crate::errors::KclErrorDetails;
14use crate::execution::CreatorFace;
15use crate::execution::EntityCloneInfo;
16use crate::execution::ExecState;
17use crate::execution::ExtrudeSurface;
18use crate::execution::Geometry;
19use crate::execution::GeometryWithImportedGeometry;
20use crate::execution::KclValue;
21use crate::execution::Metadata;
22use crate::execution::ModelingCmdMeta;
23use crate::execution::Sketch;
24use crate::execution::Solid;
25use crate::execution::SolidCreator;
26use crate::execution::TagEngineInfo;
27use crate::execution::TagIdentifier;
28use crate::execution::types::ArrayLen;
29use crate::execution::types::PrimitiveType;
30use crate::execution::types::RuntimeType;
31use crate::parsing::ast::types::TagNode;
32use crate::std::Args;
33use crate::std::extrude::BeingExtruded;
34use crate::std::extrude::NamedCapTags;
35
36type Result<T> = std::result::Result<T, KclError>;
37
38/// Clone a sketch or solid.
39///
40/// This works essentially like a copy-paste operation.
41pub async fn clone(exec_state: &mut ExecState, args: Args) -> Result<KclValue> {
42    let geometries = args.get_unlabeled_kw_arg(
43        "geometry",
44        &RuntimeType::Array(
45            Box::new(RuntimeType::Union(vec![
46                RuntimeType::Primitive(PrimitiveType::Sketch),
47                RuntimeType::Primitive(PrimitiveType::Solid),
48                RuntimeType::imported(),
49            ])),
50            ArrayLen::Minimum(1),
51        ),
52        exec_state,
53    )?;
54
55    let cloned = inner_clone(geometries, exec_state, args).await?;
56    Ok(cloned.into())
57}
58
59async fn inner_clone(
60    geometries: Vec<GeometryWithImportedGeometry>,
61    exec_state: &mut ExecState,
62    args: Args,
63) -> Result<Vec<GeometryWithImportedGeometry>> {
64    let mut res = vec![];
65
66    for g in geometries {
67        let new_id = exec_state.next_uuid();
68        let mut geometry = g.clone();
69        let old_id = geometry.id(&args.ctx).await?;
70        // Pattern copies have a new top-level entity ID, but their KCL
71        // geometry still describes the source topology. Map that source
72        // topology directly to the clone so paths and tagged faces receive
73        // the clone's child IDs.
74        let source_topology_id = match &geometry {
75            GeometryWithImportedGeometry::Sketch(sketch) => sketch.original_id,
76            GeometryWithImportedGeometry::Solid(solid) => solid.topology_id(),
77            GeometryWithImportedGeometry::ImportedGeometry(_) => old_id,
78        };
79        let mut entity_clone_info = None;
80
81        let mut new_geometry = match &geometry {
82            GeometryWithImportedGeometry::ImportedGeometry(imported) => {
83                let mut new_imported = imported.clone();
84                new_imported.id = new_id;
85                GeometryWithImportedGeometry::ImportedGeometry(new_imported)
86            }
87            GeometryWithImportedGeometry::Sketch(sketch) => {
88                let mut new_sketch = sketch.clone();
89                new_sketch.id = new_id;
90                new_sketch.original_id = new_id;
91                new_sketch.artifact_id = new_id.into();
92                GeometryWithImportedGeometry::Sketch(new_sketch)
93            }
94            GeometryWithImportedGeometry::Solid(solid) => {
95                // We flush before the clone so all the shit exists.
96                exec_state
97                    .flush_batch_for_solids(
98                        ModelingCmdMeta::from_args(exec_state, &args),
99                        std::slice::from_ref(solid),
100                    )
101                    .await?;
102
103                let mut new_solid = solid.clone();
104                // Sweep-backed solids have separate engine entity and body
105                // artifact IDs. Preserve that split so the cloned Path and
106                // Sweep can coexist. Pattern copies replace `artifact_id`
107                // with their own entity ID, so consult their retained source
108                // artifact to recover the same distinction.
109                let source_artifact_id = solid.pattern_source_artifact_id.unwrap_or(solid.artifact_id);
110                let result_artifact_id = if source_artifact_id == source_topology_id.into() {
111                    new_id.into()
112                } else {
113                    exec_state.next_artifact_id()
114                };
115                entity_clone_info = Some(EntityCloneInfo {
116                    source_artifact_id,
117                    result_artifact_id,
118                    source_topology_id: source_topology_id.into(),
119                });
120                new_solid.id = new_id;
121                new_solid.value_id = new_id;
122                new_solid.become_new_body(new_id, result_artifact_id);
123                if let Some(sketch) = new_solid.sketch_mut() {
124                    sketch.original_id = new_id;
125                }
126                GeometryWithImportedGeometry::Solid(new_solid)
127            }
128        };
129
130        if args.ctx.no_engine_commands().await {
131            res.push(new_geometry);
132        } else {
133            exec_state
134                .batch_modeling_cmd_with_entity_clone_info(
135                    ModelingCmdMeta::from_args_id(exec_state, &args, new_id),
136                    ModelingCmd::from(mcmd::EntityClone::builder().entity_id(old_id).build()),
137                    entity_clone_info,
138                )
139                .await?;
140
141            fix_tags_and_references(&mut new_geometry, old_id, source_topology_id, exec_state, &args).await?;
142            res.push(new_geometry)
143        }
144    }
145
146    Ok(res)
147}
148/// Fix the tags and references of the cloned geometry.
149pub(super) async fn fix_tags_and_references(
150    new_geometry: &mut GeometryWithImportedGeometry,
151    old_geometry_id: uuid::Uuid,
152    source_topology_id: uuid::Uuid,
153    exec_state: &mut ExecState,
154    args: &Args,
155) -> Result<()> {
156    let new_geometry_id = new_geometry.id(&args.ctx).await?;
157    let entity_id_map =
158        get_old_new_child_map(new_geometry_id, old_geometry_id, source_topology_id, exec_state, args).await?;
159
160    // Fix the path references in the new geometry.
161    match new_geometry {
162        GeometryWithImportedGeometry::ImportedGeometry(_) => {}
163        GeometryWithImportedGeometry::Sketch(sketch) => {
164            sketch.clone = Some(source_topology_id);
165            fix_sketch_tags_and_references(sketch, &entity_id_map, exec_state, None).await?;
166        }
167        GeometryWithImportedGeometry::Solid(solid) => {
168            let body_type = match solid.best_guess_body_type {
169                Some(body_type) => body_type,
170                None => super::surfaces::query_body_type(solid, exec_state, args).await?,
171            };
172            solid.best_guess_body_type = Some(body_type);
173
174            let (start_tag, end_tag) = get_named_cap_tags(solid);
175            let solid_value = solid.value.clone();
176            let solid_artifact_id = solid.artifact_id;
177            let old_face_tag_names = solid.faces.keys().cloned().collect::<Vec<_>>();
178            let face_creator = match &solid.creator {
179                SolidCreator::Face(face) => Some((
180                    remap_id(face.face_id, &entity_id_map),
181                    remap_id(face.solid_id, &entity_id_map),
182                )),
183                _ => None,
184            };
185
186            if solid.sketch().is_none() {
187                remap_edge_cuts(solid, &entity_id_map);
188                remap_sketchless_solid(solid, &entity_id_map);
189                solid.faces.clear();
190                restore_face_tags(solid, &old_face_tag_names, exec_state);
191                return Ok(());
192            }
193
194            // Make the sketch id the new geometry id.
195            let sketch = solid.sketch_mut().ok_or_else(|| {
196                KclError::new_internal(KclErrorDetails::new(
197                    "A sketch-backed clone lost its creator sketch during metadata reconstruction.".to_owned(),
198                    vec![args.source_range],
199                ))
200            })?;
201            sketch.id = new_geometry_id;
202            sketch.original_id = new_geometry_id;
203            sketch.artifact_id = new_geometry_id.into();
204            sketch.clone = Some(source_topology_id);
205
206            fix_sketch_tags_and_references(sketch, &entity_id_map, exec_state, Some(solid_value)).await?;
207            let sketch_for_post = sketch.clone();
208
209            // Do the after extrude things to update those ids, based on the new sketch
210            // information.
211            let mut new_solid = do_post_extrude(
212                &sketch_for_post,
213                solid_artifact_id,
214                solid.sectional,
215                &NamedCapTags {
216                    start: start_tag.as_ref(),
217                    end: end_tag.as_ref(),
218                },
219                kittycad_modeling_cmds::shared::ExtrudeMethod::New,
220                exec_state,
221                args,
222                None,
223                Some(&entity_id_map.clone()),
224                body_type,
225                BeingExtruded::Sketch,
226            )
227            .await?;
228
229            if let Some((face_id, solid_id)) = face_creator {
230                let rebuilt_sketch = new_solid.sketch().cloned().ok_or_else(|| {
231                    KclError::new_internal(KclErrorDetails::new(
232                        "A face-created clone lost its creator sketch during metadata reconstruction.".to_owned(),
233                        vec![args.source_range],
234                    ))
235                })?;
236                new_solid.creator = SolidCreator::Face(CreatorFace {
237                    face_id,
238                    solid_id,
239                    sketch: rebuilt_sketch,
240                });
241            }
242
243            restore_sketch_tag_surfaces(&mut new_solid);
244            *solid = new_solid;
245
246            restore_face_tags(solid, &old_face_tag_names, exec_state);
247        }
248    }
249
250    Ok(())
251}
252
253fn remap_id(id: uuid::Uuid, entity_id_map: &HashMap<uuid::Uuid, uuid::Uuid>) -> uuid::Uuid {
254    entity_id_map.get(&id).copied().unwrap_or(id)
255}
256
257fn remap_edge_cuts(solid: &mut Solid, entity_id_map: &HashMap<uuid::Uuid, uuid::Uuid>) {
258    for edge_cut in &mut solid.edge_cuts {
259        edge_cut.set_id(remap_id(edge_cut.id(), entity_id_map));
260        edge_cut.set_edge_id(remap_id(edge_cut.edge_id(), entity_id_map));
261    }
262    for id in &mut solid.pending_edge_cut_ids {
263        *id = remap_id(*id, entity_id_map);
264    }
265}
266
267fn remap_sketchless_solid(solid: &mut Solid, entity_id_map: &HashMap<uuid::Uuid, uuid::Uuid>) {
268    for surface in &mut solid.value {
269        surface.set_id(remap_id(surface.get_id(), entity_id_map));
270        surface.set_face_id(remap_id(surface.face_id(), entity_id_map));
271    }
272
273    solid.start_cap_id = solid.start_cap_id.map(|id| remap_id(id, entity_id_map));
274    solid.end_cap_id = solid.end_cap_id.map(|id| remap_id(id, entity_id_map));
275
276    if let SolidCreator::Edge(creator) = &mut solid.creator {
277        creator.edge_id = remap_id(creator.edge_id, entity_id_map);
278        creator.body_id = remap_id(creator.body_id, entity_id_map);
279    }
280}
281
282/// Restore any sketch tag surfaces that could not be mapped from stale source
283/// metadata before [`do_post_extrude`] rebuilt the cloned solid's surfaces.
284fn restore_sketch_tag_surfaces(solid: &mut Solid) {
285    let surfaces_by_tag = solid
286        .value
287        .iter()
288        .filter_map(|surface| surface.get_tag().map(|tag| (tag.name.clone(), surface.clone())))
289        .collect::<HashMap<_, _>>();
290    let Some(sketch) = solid.sketch_mut() else {
291        return;
292    };
293
294    for (name, tag) in &mut sketch.tags {
295        let Some(surface) = surfaces_by_tag.get(name) else {
296            continue;
297        };
298        let Some((_, info)) = tag.info.last_mut() else {
299            continue;
300        };
301        if info.surface.is_none() {
302            info.surface = Some(surface.clone());
303        }
304    }
305}
306
307/// Rebuild the face tag map of a cloned solid from its new surfaces.
308///
309/// [`do_post_extrude`] leaves `faces` empty, and we can't reuse the sketch's
310/// tags like tagging at creation time does, because the cloned sketch still
311/// carries the original solid's face info. Build fresh tag identifiers from
312/// the new surfaces, which have the clone's face ids.
313fn restore_face_tags(solid: &mut Solid, face_tag_names: &[String], exec_state: &ExecState) {
314    let surfaces = solid.value.clone();
315    for surface in surfaces {
316        let Some(tag) = surface.get_tag() else {
317            continue;
318        };
319        if !face_tag_names.iter().any(|tag_name| tag_name == &tag.name) {
320            continue;
321        }
322
323        let mut solid_copy = solid.clone();
324        if let Some(sketch) = solid_copy.sketch_mut() {
325            // Avoid recursive tags.
326            sketch.tags.clear();
327        }
328        solid_copy.faces.clear();
329
330        let tag_id = TagIdentifier {
331            value: tag.name.clone(),
332            info: vec![(
333                exec_state.stack().current_epoch(),
334                TagEngineInfo {
335                    id: surface.get_id(),
336                    surface: Some(surface.clone()),
337                    path: None,
338                    geometry: Geometry::Solid(solid_copy),
339                },
340            )],
341            meta: vec![Metadata {
342                source_range: tag.clone().into(),
343            }],
344        };
345
346        match solid.faces.get_mut(&tag.name) {
347            Some(existing_tag) => existing_tag.merge_info(&tag_id),
348            None => {
349                solid.faces.insert(tag.name.clone(), tag_id);
350            }
351        }
352    }
353
354    for name in face_tag_names {
355        if !solid.faces.contains_key(name) {
356            crate::log::logln!("Failed to find new face for face tag: {name:?}");
357        }
358    }
359}
360
361async fn get_old_new_child_map(
362    new_geometry_id: uuid::Uuid,
363    old_geometry_id: uuid::Uuid,
364    source_topology_id: uuid::Uuid,
365    exec_state: &mut ExecState,
366    args: &Args,
367) -> Result<HashMap<uuid::Uuid, uuid::Uuid>> {
368    // Artifact graph ID management expects the cloned entity's own children
369    // to be queried first. Pattern copies retain the source topology in KCL,
370    // though, so use that topology for the runtime old-to-new ID map.
371    if old_geometry_id != source_topology_id {
372        get_all_child_uuids(old_geometry_id, exec_state, args).await?;
373    }
374
375    // Get the old geometries entity ids.
376    let old_entity_ids = get_all_child_uuids(source_topology_id, exec_state, args).await?;
377
378    // Get the new geometries entity ids.
379    let new_entity_ids = get_all_child_uuids(new_geometry_id, exec_state, args).await?;
380
381    // Create a map of old entity ids to new entity ids.
382    let mut entity_id_map = HashMap::from_iter(
383        old_entity_ids
384            .iter()
385            .zip(new_entity_ids.iter())
386            .map(|(old_id, new_id)| (*old_id, *new_id)),
387    );
388    entity_id_map.insert(old_geometry_id, new_geometry_id);
389    entity_id_map.insert(source_topology_id, new_geometry_id);
390    Ok(entity_id_map)
391}
392
393async fn get_all_child_uuids(
394    geometry_id: uuid::Uuid,
395    exec_state: &mut ExecState,
396    args: &Args,
397) -> Result<Vec<uuid::Uuid>> {
398    let response = exec_state
399        .send_modeling_cmd(
400            ModelingCmdMeta::from_args(exec_state, args),
401            ModelingCmd::from(mcmd::EntityGetAllChildUuids::builder().entity_id(geometry_id).build()),
402        )
403        .await?;
404    let OkWebSocketResponseData::Modeling {
405        modeling_response: OkModelingCmdResponse::EntityGetAllChildUuids(resp),
406    } = response
407    else {
408        return Err(KclError::new_engine(KclErrorDetails::new(
409            format!("EntityGetAllChildUuids response was not as expected: {response:?}"),
410            vec![args.source_range],
411        )));
412    };
413    Ok(resp.entity_ids)
414}
415
416/// Fix the tags and references of a sketch.
417async fn fix_sketch_tags_and_references(
418    new_sketch: &mut Sketch,
419    entity_id_map: &HashMap<uuid::Uuid, uuid::Uuid>,
420    exec_state: &mut ExecState,
421    surfaces: Option<Vec<ExtrudeSurface>>,
422) -> Result<()> {
423    // Fix the path references in the sketch.
424    for path in new_sketch.paths.as_mut_slice() {
425        if let Some(new_path_id) = entity_id_map.get(&path.get_id()) {
426            path.set_id(*new_path_id);
427        } else {
428            // We log on these because we might have already flushed and the id is no longer
429            // relevant since filleted or something.
430            crate::log::logln!("Failed to find new path id for old path id: {:?}", path.get_id());
431        }
432    }
433
434    // Map the surface tags to the new surface ids.
435    let mut surface_id_map: HashMap<String, &ExtrudeSurface> = HashMap::new();
436    let surfaces = surfaces.unwrap_or_default();
437    for surface in surfaces.iter() {
438        if let Some(tag) = surface.get_tag() {
439            surface_id_map.insert(tag.name.clone(), surface);
440        }
441    }
442
443    // Fix the tags
444    // This is annoying, in order to fix the tags we need to iterate over the paths again, but not
445    // mutable borrow the paths.
446    for path in new_sketch.paths.clone() {
447        // Check if this path has a tag.
448        if let Some(tag) = path.get_tag() {
449            let mut surface = None;
450            if let Some(found_surface) = surface_id_map.get(&tag.name) {
451                let mut new_surface = (*found_surface).clone();
452                if let Some(new_face_id) = entity_id_map.get(&new_surface.face_id()).copied() {
453                    new_surface.set_face_id(new_face_id);
454                    surface = Some(new_surface);
455                } else {
456                    // A boolean can retain a tagged path while replacing or
457                    // removing its old face. `do_post_extrude` queries the
458                    // live topology and rebuilds this optional surface data.
459                    crate::log::logln!(
460                        "Failed to find new face id for stale old face id: {:?}",
461                        new_surface.face_id()
462                    );
463                }
464            }
465
466            new_sketch.add_tag(&tag, &path, exec_state, surface.as_ref());
467        }
468    }
469
470    // Fix the base path.
471    if let Some(new_base_path) = entity_id_map.get(&new_sketch.start.geo_meta.id) {
472        new_sketch.start.geo_meta.id = *new_base_path;
473    } else {
474        crate::log::logln!(
475            "Failed to find new base path id for old base path id: {:?}",
476            new_sketch.start.geo_meta.id
477        );
478    }
479
480    Ok(())
481}
482
483// Return the named cap tags for the original solid.
484fn get_named_cap_tags(solid: &Solid) -> (Option<TagNode>, Option<TagNode>) {
485    let mut start_tag = None;
486    let mut end_tag = None;
487    // Check the start cap.
488    if let Some(start_cap_id) = solid.start_cap_id {
489        // Check if we had a value for that cap.
490        for value in &solid.value {
491            if value.get_id() == start_cap_id {
492                start_tag = value.get_tag();
493                break;
494            }
495        }
496    }
497
498    // Check the end cap.
499    if let Some(end_cap_id) = solid.end_cap_id {
500        // Check if we had a value for that cap.
501        for value in &solid.value {
502            if value.get_id() == end_cap_id {
503                end_tag = value.get_tag();
504                break;
505            }
506        }
507    }
508
509    (start_tag, end_tag)
510}
511
512#[cfg(test)]
513mod tests {
514    use kcl_api::artifact::SweepSubType;
515    use kittycad_modeling_cmds::shared::BodyType;
516    use pretty_assertions::assert_eq;
517    use pretty_assertions::assert_ne;
518
519    use crate::exec::KclValueView;
520    use crate::execution::Artifact;
521    use crate::execution::ArtifactGraph;
522    use crate::execution::ArtifactId;
523    use crate::execution::Solid;
524    use crate::execution::SolidCreator;
525
526    fn assert_cloned_composite_topology(artifact_graph: &ArtifactGraph, cloned_composite: &Solid) {
527        let Some(Artifact::CompositeSolid(cloned_artifact)) = artifact_graph.get(&cloned_composite.artifact_id) else {
528            panic!("Expected a cloned composite solid artifact at the engine entity ID");
529        };
530        assert_eq!(cloned_artifact.id, cloned_composite.artifact_id);
531        assert!(!cloned_artifact.consumed);
532
533        let cloned_face_sweep_ids = artifact_graph
534            .values()
535            .filter_map(|artifact| match artifact {
536                Artifact::Wall(wall) if wall.cmd_id == cloned_composite.id => Some(wall.sweep_id),
537                Artifact::Cap(cap) if cap.cmd_id == cloned_composite.id => Some(cap.sweep_id),
538                _ => None,
539            })
540            .collect::<Vec<_>>();
541        assert!(!cloned_face_sweep_ids.is_empty());
542
543        for sweep_id in cloned_face_sweep_ids {
544            let Some(Artifact::Sweep(sweep)) = artifact_graph.get(&sweep_id) else {
545                panic!("Expected every cloned composite face to reference a sweep");
546            };
547            assert_eq!(sweep.code_ref, cloned_artifact.code_ref);
548            let source_sweep_id = sweep.source_sweep_id.expect("Expected cloned sweep provenance");
549            assert_ne!(sweep.id, source_sweep_id);
550            assert!(matches!(artifact_graph.get(&source_sweep_id), Some(Artifact::Sweep(_))));
551        }
552    }
553
554    // Ensure the clone function returns a sketch with different ids for all the internal paths and
555    // the resulting sketch.
556    #[tokio::test(flavor = "multi_thread")]
557    async fn kcl_test_clone_sketch() {
558        let code = r#"cube = startSketchOn(XY)
559    |> startProfile(at = [0,0])
560    |> line(end = [0, 10])
561    |> line(end = [10, 0])
562    |> line(end = [0, -10])
563    |> close()
564
565clonedCube = clone(cube)
566"#;
567        let ctx = crate::test_server::new_context(true, None).await.unwrap();
568        let program = crate::Program::parse_no_errs(code).unwrap();
569
570        // Execute the program.
571        let result = ctx.run_with_caching(program.clone()).await.unwrap();
572        let cube = result.variables.get("cube").unwrap();
573        let cloned_cube = result.variables.get("clonedCube").unwrap();
574
575        assert_ne!(cube, cloned_cube);
576
577        let KclValueView::Sketch { value: cube } = cube else {
578            panic!("Expected a sketch, got: {cube:?}");
579        };
580        let KclValueView::Sketch { value: cloned_cube } = cloned_cube else {
581            panic!("Expected a sketch, got: {cloned_cube:?}");
582        };
583
584        assert_ne!(cube.id, cloned_cube.id);
585        assert_ne!(cube.original_id, cloned_cube.original_id);
586        assert_ne!(cube.artifact_id, cloned_cube.artifact_id);
587
588        assert_eq!(cloned_cube.artifact_id, cloned_cube.id.into());
589        assert_eq!(cloned_cube.original_id, cloned_cube.id);
590
591        for (path, cloned_path) in cube.paths.iter().zip(cloned_cube.paths.iter()) {
592            assert_ne!(path.get_id(), cloned_path.get_id());
593            assert_eq!(path.get_tag(), cloned_path.get_tag());
594        }
595
596        assert_eq!(cube.tags.len(), 0);
597        assert_eq!(cloned_cube.tags.len(), 0);
598
599        ctx.close().await;
600    }
601
602    // Ensure the clone function returns a solid with different ids for all the internal paths and
603    // references.
604    #[tokio::test(flavor = "multi_thread")]
605    async fn kcl_test_clone_solid() {
606        let code = r#"cube = startSketchOn(XY)
607    |> startProfile(at = [0,0])
608    |> line(end = [0, 10])
609    |> line(end = [10, 0])
610    |> line(end = [0, -10])
611    |> close()
612    |> extrude(length = 5)
613
614clonedCube = clone(cube)
615"#;
616        let ctx = crate::test_server::new_context(true, None).await.unwrap();
617        let program = crate::Program::parse_no_errs(code).unwrap();
618
619        // Execute the program.
620        let result = ctx.run_with_caching(program.clone()).await.unwrap();
621        let cube = result.variables.get("cube").unwrap();
622        let cloned_cube = result.variables.get("clonedCube").unwrap();
623
624        assert_ne!(cube, cloned_cube);
625
626        let KclValueView::Solid { value: cube } = cube else {
627            panic!("Expected a solid, got: {cube:?}");
628        };
629        let KclValueView::Solid { value: cloned_cube } = cloned_cube else {
630            panic!("Expected a solid, got: {cloned_cube:?}");
631        };
632        let cube_sketch = cube.sketch().expect("Expected cube to have a sketch");
633        let cloned_cube_sketch = cloned_cube.sketch().expect("Expected cloned cube to have a sketch");
634
635        assert_ne!(cube.id, cloned_cube.id);
636        assert_ne!(cube_sketch.id, cloned_cube_sketch.id);
637        assert_ne!(cube_sketch.original_id, cloned_cube_sketch.original_id);
638        assert_ne!(cube.artifact_id, cloned_cube.artifact_id);
639        assert_ne!(cube_sketch.artifact_id, cloned_cube_sketch.artifact_id);
640
641        assert_ne!(cloned_cube.artifact_id, cloned_cube.id.into());
642
643        for (path, cloned_path) in cube_sketch.paths.iter().zip(cloned_cube_sketch.paths.iter()) {
644            assert_ne!(path.get_id(), cloned_path.get_id());
645            assert_eq!(path.get_tag(), cloned_path.get_tag());
646        }
647
648        for (value, cloned_value) in cube.value.iter().zip(cloned_cube.value.iter()) {
649            assert_ne!(value.get_id(), cloned_value.get_id());
650            assert_eq!(value.get_tag(), cloned_value.get_tag());
651        }
652
653        assert_eq!(cube_sketch.tags.len(), 0);
654        assert_eq!(cloned_cube_sketch.tags.len(), 0);
655
656        assert_eq!(cube.edge_cuts.len(), 0);
657        assert_eq!(cloned_cube.edge_cuts.len(), 0);
658
659        ctx.close().await;
660    }
661
662    #[tokio::test(flavor = "multi_thread")]
663    async fn kcl_test_clone_sketch_backed_surface_operations() {
664        let code = r#"extrudeProfile = startSketchOn(XZ)
665  |> startProfile(at = [0, 0])
666  |> line(end = [4, 0])
667  |> line(end = [2, 3])
668surfaceExtrude = extrude(extrudeProfile, length = 2, bodyType = SURFACE)
669surfaceExtrudeClone = clone(surfaceExtrude)
670
671revolveProfile = startSketchOn(XZ)
672  |> startProfile(at = [5, 0])
673  |> line(end = [2, 3])
674surfaceRevolve = revolve(revolveProfile, axis = Y, angle = 180deg, bodyType = SURFACE)
675surfaceRevolveClone = clone(surfaceRevolve)
676
677sweepProfile = startSketchOn(XY)
678  |> startProfile(at = [-10, 10])
679  |> line(end = [4, 0])
680sweepPath = startSketchOn(XY)
681  |> startProfile(at = [0, 0])
682  |> line(end = [10, 0])
683  |> tangentialArc(end = [4, -4])
684surfaceSweep = sweep(sweepProfile, path = sweepPath, bodyType = SURFACE)
685surfaceSweepClone = clone(surfaceSweep)
686
687loftProfileA = startSketchOn(offsetPlane(XZ, offset = -10))
688  |> startProfile(at = [-2, -2])
689  |> line(end = [4, 0])
690loftProfileB = startSketchOn(offsetPlane(XZ, offset = -15))
691  |> startProfile(at = [-1, -1])
692  |> line(end = [2, 0])
693surfaceLoft = loft([loftProfileA, loftProfileB], bodyType = SURFACE)
694surfaceLoftClone = clone(surfaceLoft)
695"#;
696        let ctx = crate::test_server::new_context(true, None).await.unwrap();
697        let program = crate::Program::parse_no_errs(code).unwrap();
698
699        let result = ctx.run_with_caching(program).await.unwrap();
700        for (source_name, clone_name) in [
701            ("surfaceExtrude", "surfaceExtrudeClone"),
702            ("surfaceRevolve", "surfaceRevolveClone"),
703            ("surfaceSweep", "surfaceSweepClone"),
704            ("surfaceLoft", "surfaceLoftClone"),
705        ] {
706            let KclValueView::Solid { value: source } = result.variables.get(source_name).unwrap() else {
707                panic!("Expected {source_name} to be a surface body");
708            };
709            let KclValueView::Solid { value: cloned } = result.variables.get(clone_name).unwrap() else {
710                panic!("Expected {clone_name} to be a surface body");
711            };
712
713            assert_ne!(source.id, cloned.id);
714            assert_eq!(cloned.best_guess_body_type, Some(BodyType::Surface));
715            assert!(matches!(cloned.creator, SolidCreator::Sketch(_)));
716            assert!(!cloned.value.is_empty());
717        }
718
719        ctx.close().await;
720    }
721
722    #[tokio::test(flavor = "multi_thread")]
723    async fn kcl_test_clone_edge_created_surface() {
724        let code = r#"@settings(kclVersion = 2.0)
725
726baseSketch = sketch(on = XY) {
727  bottom = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
728  right = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
729  top = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
730  left = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
731  coincident([bottom.end, right.start])
732  coincident([right.end, top.start])
733  coincident([top.end, left.start])
734  coincident([left.end, bottom.start])
735}
736base = extrude(region(segments = [baseSketch.bottom, baseSketch.right]), length = 5mm)
737source = extrude(
738  getOppositeEdge(base.sketch.tags.bottom),
739  length = 3mm,
740  bodyType = SURFACE,
741  method = NEW,
742)
743cloned = clone(source)
744"#;
745        let ctx = crate::test_server::new_context(true, None).await.unwrap();
746        let program = crate::Program::parse_no_errs(code).unwrap();
747
748        let result = ctx.run_with_caching(program).await.unwrap();
749        let KclValueView::Solid { value: source } = result.variables.get("source").unwrap() else {
750            panic!("Expected an edge-created source surface");
751        };
752        let KclValueView::Solid { value: cloned } = result.variables.get("cloned").unwrap() else {
753            panic!("Expected a cloned edge-created surface");
754        };
755        let SolidCreator::Edge(source_creator) = &source.creator else {
756            panic!("Expected the source surface to retain its edge creator");
757        };
758        let SolidCreator::Edge(cloned_creator) = &cloned.creator else {
759            panic!("Expected the cloned surface to retain its edge creator");
760        };
761
762        assert_ne!(source.id, cloned.id);
763        assert_eq!(cloned.best_guess_body_type, Some(BodyType::Surface));
764        assert_eq!(cloned_creator.body_id, cloned.id);
765        assert_ne!(source_creator.edge_id, cloned_creator.edge_id);
766        assert_ne!(source.value[0].get_id(), cloned.value[0].get_id());
767        assert_ne!(source.value[0].face_id(), cloned.value[0].face_id());
768
769        ctx.close().await;
770    }
771
772    #[tokio::test(flavor = "multi_thread")]
773    async fn kcl_test_clone_preserves_face_creator() {
774        let code = r#"profile = startSketchOn(XY)
775  |> startProfile(at = [0, 0])
776  |> yLine(length = 1, tag = $a)
777  |> xLine(length = 1, tag = $b)
778  |> close(tag = $c)
779base = extrude(profile, length = 1)
780source = extrude(c, length = 4, method = NEW)
781cloned = clone(source)
782"#;
783        let ctx = crate::test_server::new_context(true, None).await.unwrap();
784        let program = crate::Program::parse_no_errs(code).unwrap();
785
786        let result = ctx.run_with_caching(program).await.unwrap();
787        let KclValueView::Solid { value: source } = result.variables.get("source").unwrap() else {
788            panic!("Expected a face-created source body");
789        };
790        let KclValueView::Solid { value: cloned } = result.variables.get("cloned").unwrap() else {
791            panic!("Expected a cloned face-created body");
792        };
793        let SolidCreator::Face(source_creator) = &source.creator else {
794            panic!("Expected the source body to retain its face creator");
795        };
796        let SolidCreator::Face(cloned_creator) = &cloned.creator else {
797            panic!("Expected the cloned body to retain its face creator");
798        };
799
800        assert_ne!(source.id, cloned.id);
801        assert_ne!(source_creator.face_id, cloned_creator.face_id);
802        assert_ne!(source_creator.solid_id, cloned_creator.solid_id);
803        assert_ne!(source_creator.sketch.id, cloned_creator.sketch.id);
804        assert_ne!(source_creator.sketch.original_id, cloned_creator.sketch.original_id);
805
806        ctx.close().await;
807    }
808
809    #[tokio::test(flavor = "multi_thread")]
810    async fn kcl_test_clone_procedural_blend_surface() {
811        let code = r#"@settings(defaultLengthUnit = mm, kclVersion = 2.0)
812
813sketchA = sketch(on = YZ) {
814  line1 = line(start = [var 4.1mm, var -0.1mm], end = [var 5.5mm, var 0mm])
815  line2 = line(start = [var 5.5mm, var 0mm], end = [var 5.5mm, var 3mm])
816  line3 = line(start = [var 5.5mm, var 3mm], end = [var 3.9mm, var 2.8mm])
817  line4 = line(start = [var 4.1mm, var 3mm], end = [var 4.5mm, var -0.2mm])
818  coincident([line1.end, line2.start])
819  coincident([line2.end, line3.start])
820  coincident([line3.end, line4.start])
821  coincident([line4.end, line1.start])
822}
823
824sketchB = sketch(on = -XZ) {
825  line5 = line(start = [var -5.3mm, var -0.1mm], end = [var -3.5mm, var -0.1mm])
826  line6 = line(start = [var -3.5mm, var -0.1mm], end = [var -3.5mm, var 3.1mm])
827  line7 = line(start = [var -3.5mm, var 4.5mm], end = [var -5.4mm, var 4.5mm])
828  line8 = line(start = [var -5.3mm, var 3.1mm], end = [var -5.3mm, var -0.1mm])
829  coincident([line5.end, line6.start])
830  coincident([line6.end, line7.start])
831  coincident([line7.end, line8.start])
832  coincident([line8.end, line5.start])
833}
834
835surfaceA = extrude(region(segments = [sketchB.line5, sketchB.line6]), length = -2mm, bodyType = SURFACE)
836surfaceB = extrude(region(segments = [sketchA.line1, sketchA.line2]), length = -2mm, bodyType = SURFACE)
837bridge = blend([surfaceA.sketch.tags.line7, surfaceB.sketch.tags.line3])
838bridgeClone = clone(bridge)
839"#;
840        let ctx = crate::test_server::new_context(true, None).await.unwrap();
841        let program = crate::Program::parse_no_errs(code).unwrap();
842
843        let result = ctx.run_with_caching(program).await.unwrap();
844        let KclValueView::Solid { value: bridge } = result.variables.get("bridge").unwrap() else {
845            panic!("Expected blend to create a procedural surface");
846        };
847        let KclValueView::Solid { value: cloned } = result.variables.get("bridgeClone").unwrap() else {
848            panic!("Expected blend clone to create a procedural surface");
849        };
850
851        assert_ne!(bridge.id, cloned.id);
852        assert_eq!(cloned.best_guess_body_type, Some(BodyType::Surface));
853        assert!(matches!(cloned.creator, SolidCreator::Procedural));
854        let Some(Artifact::Sweep(cloned_sweep)) = result.artifact_graph.get(&cloned.artifact_id) else {
855            panic!("Expected the blend clone to have a sweep artifact");
856        };
857        assert_eq!(cloned_sweep.sub_type, SweepSubType::Blend);
858        assert_eq!(cloned_sweep.source_sweep_id, Some(bridge.artifact_id));
859
860        ctx.close().await;
861    }
862
863    #[tokio::test(flavor = "multi_thread")]
864    async fn kcl_test_clone_multi_body_join_queries_body_type() {
865        let code = r#"@settings(kclVersion = 2.0)
866
867targetSketch = sketch(on = XY) {
868  bottom = line(start = [var -10, var -10], end = [var 10, var -10])
869  right = line(start = [var 10, var -10], end = [var 10, var 10])
870  top = line(start = [var 10, var 10], end = [var -10, var 10])
871  left = line(start = [var -10, var 10], end = [var -10, var -10])
872  coincident([bottom.end, right.start])
873  coincident([right.end, top.start])
874  coincident([top.end, left.start])
875  coincident([left.end, bottom.start])
876}
877target = extrude(region(point = [0, 0], sketch = targetSketch), length = 10)
878
879cutterSketch = sketch(on = XY) {
880  bottom = line(start = [var -1, var -12], end = [var 1, var -12])
881  right = line(start = [var 1, var -12], end = [var 1, var 12])
882  top = line(start = [var 1, var 12], end = [var -1, var 12])
883  left = line(start = [var -1, var 12], end = [var -1, var -12])
884  coincident([bottom.end, right.start])
885  coincident([right.end, top.start])
886  coincident([top.end, left.start])
887  coincident([left.end, bottom.start])
888}
889cutter = extrude(region(point = [0, 0], sketch = cutterSketch), length = 10)
890
891pieces = split([target], tools = [cutter], keepTools = true)
892joined = joinSurfaces(pieces)
893joinedClone = clone(joined)
894"#;
895        let ctx = crate::test_server::new_context(true, None).await.unwrap();
896        let program = crate::Program::parse_no_errs(code).unwrap();
897
898        let result = ctx.run_with_caching(program).await.unwrap();
899        let KclValueView::Solid { value: joined } = result.variables.get("joined").unwrap() else {
900            panic!("Expected joinSurfaces to create a procedural body");
901        };
902        let KclValueView::Solid { value: cloned } = result.variables.get("joinedClone").unwrap() else {
903            panic!("Expected joinSurfaces body to clone");
904        };
905
906        assert_ne!(joined.id, cloned.id);
907        assert!(joined.best_guess_body_type.is_none());
908        assert!(cloned.best_guess_body_type.is_some());
909        assert!(matches!(cloned.creator, SolidCreator::Procedural));
910
911        ctx.close().await;
912    }
913
914    #[tokio::test(flavor = "multi_thread")]
915    async fn kcl_test_clone_loft() {
916        let code = r#"@settings(kclVersion = 2.0)
917
918firstSketch = sketch(on = XY) {
919  circle1 = circle(start = [var 10, var 0], center = [var 0, var 0])
920}
921secondSketch = sketch(on = offsetPlane(XY, offset = 10)) {
922  circle1 = circle(start = [var 5, var 0], center = [var 0, var 0])
923}
924
925lofted = loft([
926  region(segments = [firstSketch.circle1]),
927  region(segments = [secondSketch.circle1]),
928])
929clonedLoft = clone(lofted)
930"#;
931        let ctx = crate::test_server::new_context(true, None).await.unwrap();
932        let program = crate::Program::parse_no_errs(code).unwrap();
933
934        let result = ctx.run_with_caching(program).await.unwrap();
935        let KclValueView::Solid { value: lofted } = result.variables.get("lofted").unwrap() else {
936            panic!("Expected a solid loft");
937        };
938        let KclValueView::Solid { value: cloned_loft } = result.variables.get("clonedLoft").unwrap() else {
939            panic!("Expected a cloned solid loft");
940        };
941
942        assert_eq!(lofted.topology_id(), lofted.id);
943        assert_eq!(lofted.original_id(), lofted.id);
944        assert_eq!(lofted.artifact_id, lofted.id.into());
945
946        assert_ne!(lofted.id, cloned_loft.id);
947        assert_ne!(lofted.artifact_id, cloned_loft.artifact_id);
948        assert_eq!(cloned_loft.topology_id(), cloned_loft.id);
949        assert_eq!(cloned_loft.original_id(), cloned_loft.id);
950        assert_eq!(cloned_loft.artifact_id, cloned_loft.id.into());
951
952        let loft_sketch = lofted.sketch().expect("Expected loft to retain its base sketch");
953        let cloned_sketch = cloned_loft
954            .sketch()
955            .expect("Expected cloned loft to retain its base sketch");
956        for (path, cloned_path) in loft_sketch.paths.iter().zip(cloned_sketch.paths.iter()) {
957            assert_ne!(path.get_id(), cloned_path.get_id());
958            assert_eq!(path.get_tag(), cloned_path.get_tag());
959        }
960
961        assert!(!cloned_loft.value.is_empty());
962        for (surface, cloned_surface) in lofted.value.iter().zip(cloned_loft.value.iter()) {
963            assert_ne!(surface.get_id(), cloned_surface.get_id());
964            assert_eq!(surface.get_tag(), cloned_surface.get_tag());
965        }
966
967        let Some(Artifact::Sweep(source_sweep)) = result.artifact_graph.get(&lofted.artifact_id) else {
968            panic!("Expected the source loft to be represented by a sweep artifact");
969        };
970        assert_eq!(source_sweep.sub_type, SweepSubType::Loft);
971
972        let Some(Artifact::Sweep(cloned_sweep)) = result.artifact_graph.get(&cloned_loft.artifact_id) else {
973            panic!("Expected the cloned loft to be represented by a sweep artifact");
974        };
975        assert_eq!(cloned_sweep.sub_type, SweepSubType::Loft);
976        assert_eq!(cloned_sweep.source_sweep_id, Some(lofted.artifact_id));
977        assert_eq!(cloned_sweep.path_id, source_sweep.path_id);
978        assert!(!cloned_sweep.consumed);
979
980        ctx.close().await;
981    }
982
983    #[tokio::test(flavor = "multi_thread")]
984    async fn kcl_test_clone_composite_solid_keeps_engine_artifact_id() {
985        let code = r#"left = startSketchOn(XY)
986    |> startProfile(at = [0, 0])
987    |> line(end = [10, 0])
988    |> line(end = [0, 10])
989    |> line(end = [-10, 0])
990    |> close()
991    |> extrude(length = 5)
992
993right = startSketchOn(XY)
994    |> startProfile(at = [5, 0])
995    |> line(end = [10, 0])
996    |> line(end = [0, 10])
997    |> line(end = [-10, 0])
998    |> close()
999    |> extrude(length = 5)
1000
1001composite = union([left, right])
1002clonedComposite = clone(composite)
1003"#;
1004        let ctx = crate::test_server::new_context(true, None).await.unwrap();
1005        let program = crate::Program::parse_no_errs(code).unwrap();
1006
1007        let result = ctx.run_with_caching(program).await.unwrap();
1008        let KclValueView::Solid { value: composite } = result.variables.get("composite").unwrap() else {
1009            panic!("Expected composite to be a solid");
1010        };
1011        let KclValueView::Solid {
1012            value: cloned_composite,
1013        } = result.variables.get("clonedComposite").unwrap()
1014        else {
1015            panic!("Expected clonedComposite to be a solid");
1016        };
1017
1018        assert_eq!(composite.artifact_id, composite.id.into());
1019        assert_eq!(cloned_composite.artifact_id, cloned_composite.id.into());
1020        assert_ne!(composite.id, cloned_composite.id);
1021        assert_ne!(composite.original_id(), composite.id);
1022        assert_eq!(composite.topology_id(), composite.id);
1023        assert_eq!(cloned_composite.original_id(), cloned_composite.id);
1024        assert_eq!(cloned_composite.topology_id(), cloned_composite.id);
1025
1026        assert_cloned_composite_topology(&result.artifact_graph, cloned_composite);
1027
1028        ctx.close().await;
1029    }
1030
1031    #[tokio::test(flavor = "multi_thread")]
1032    async fn kcl_test_clone_imported_patterned_composite_uses_composite_topology() {
1033        let module_code = r#"left = startSketchOn(XY)
1034    |> startProfile(at = [0, 0])
1035    |> line(end = [10, 0])
1036    |> line(end = [0, 10])
1037    |> line(end = [-10, 0])
1038    |> close()
1039    |> extrude(length = 5)
1040
1041right = startSketchOn(XY)
1042    |> startProfile(at = [5, 0])
1043    |> line(end = [10, 0])
1044    |> line(end = [0, 10])
1045    |> line(end = [-10, 0])
1046    |> close()
1047    |> extrude(length = 5)
1048
1049export composite = union([left, right])
1050"#;
1051        let code = r#"import composite from 'composite.kcl'
1052
1053patterned = patternLinear3d(
1054    composite,
1055    instances = 2,
1056    distance = 20,
1057    axis = [1, 0, 0],
1058)
1059patternCopy = patterned[1]
1060clonedCopy = clone(patternCopy)
1061"#;
1062        let tmpdir = tempfile::TempDir::with_prefix("clone_imported_patterned_composite").unwrap();
1063        let main_path = tmpdir.path().join("main.kcl");
1064        std::fs::write(tmpdir.path().join("composite.kcl"), module_code).unwrap();
1065        std::fs::write(&main_path, code).unwrap();
1066
1067        let ctx = crate::test_server::new_context(true, Some(main_path)).await.unwrap();
1068        let program = crate::Program::parse_no_errs(code).unwrap();
1069
1070        let result = ctx.run_with_caching(program).await.unwrap();
1071        let KclValueView::Solid { value: composite } = result.variables.get("composite").unwrap() else {
1072            panic!("Expected composite to be a solid");
1073        };
1074        let KclValueView::Solid { value: pattern_copy } = result.variables.get("patternCopy").unwrap() else {
1075            panic!("Expected patternCopy to be a solid");
1076        };
1077        let KclValueView::Solid { value: cloned_copy } = result.variables.get("clonedCopy").unwrap() else {
1078            panic!("Expected clonedCopy to be a solid");
1079        };
1080
1081        assert_eq!(composite.topology_id(), composite.id);
1082        assert_eq!(pattern_copy.topology_id(), composite.id);
1083        assert_eq!(cloned_copy.original_id(), cloned_copy.id);
1084        assert_eq!(cloned_copy.topology_id(), cloned_copy.id);
1085        assert_eq!(cloned_copy.artifact_id, cloned_copy.id.into());
1086        assert_ne!(pattern_copy.id, cloned_copy.id);
1087        assert!(result.artifact_graph.get(&pattern_copy.artifact_id).is_none());
1088        assert_cloned_composite_topology(&result.artifact_graph, cloned_copy);
1089
1090        ctx.close().await;
1091    }
1092
1093    // Ensure the clone function returns a sketch with different ids for all the internal paths and
1094    // the resulting sketch.
1095    // AND TAGS.
1096    #[tokio::test(flavor = "multi_thread")]
1097    async fn kcl_test_clone_sketch_with_tags() {
1098        let code = r#"cube = startSketchOn(XY)
1099    |> startProfile(at = [0,0]) // tag this one
1100    |> line(end = [0, 10], tag = $tag02)
1101    |> line(end = [10, 0], tag = $tag03)
1102    |> line(end = [0, -10], tag = $tag04)
1103    |> close(tag = $tag05)
1104
1105clonedCube = clone(cube)
1106"#;
1107        let ctx = crate::test_server::new_context(true, None).await.unwrap();
1108        let program = crate::Program::parse_no_errs(code).unwrap();
1109
1110        // Execute the program.
1111        let result = ctx.run_with_caching(program.clone()).await.unwrap();
1112        let cube = result.variables.get("cube").unwrap();
1113        let cloned_cube = result.variables.get("clonedCube").unwrap();
1114
1115        assert_ne!(cube, cloned_cube);
1116
1117        let KclValueView::Sketch { value: cube } = cube else {
1118            panic!("Expected a sketch, got: {cube:?}");
1119        };
1120        let KclValueView::Sketch { value: cloned_cube } = cloned_cube else {
1121            panic!("Expected a sketch, got: {cloned_cube:?}");
1122        };
1123
1124        assert_ne!(cube.id, cloned_cube.id);
1125        assert_ne!(cube.original_id, cloned_cube.original_id);
1126
1127        for (path, cloned_path) in cube.paths.iter().zip(cloned_cube.paths.iter()) {
1128            assert_ne!(path.get_id(), cloned_path.get_id());
1129            assert_eq!(path.get_tag(), cloned_path.get_tag());
1130        }
1131
1132        for (tag_name, tag) in &cube.tags {
1133            let cloned_tag = cloned_cube.tags.get(tag_name).unwrap();
1134
1135            let tag_info = tag.get_cur_info().unwrap();
1136            let cloned_tag_info = cloned_tag.get_cur_info().unwrap();
1137
1138            assert_ne!(tag_info.id, cloned_tag_info.id);
1139            assert_ne!(tag_info.geometry.id(), cloned_tag_info.geometry.id());
1140            assert_ne!(tag_info.path, cloned_tag_info.path);
1141            assert_eq!(tag_info.surface, None);
1142            assert_eq!(cloned_tag_info.surface, None);
1143        }
1144
1145        ctx.close().await;
1146    }
1147
1148    // Ensure the clone function returns a solid with different ids for all the internal paths and
1149    // references.
1150    // WITH TAGS.
1151    #[tokio::test(flavor = "multi_thread")]
1152    async fn kcl_test_clone_solid_with_tags() {
1153        let code = r#"cube = startSketchOn(XY)
1154    |> startProfile(at = [0,0]) // tag this one
1155    |> line(end = [0, 10], tag = $tag02)
1156    |> line(end = [10, 0], tag = $tag03)
1157    |> line(end = [0, -10], tag = $tag04)
1158    |> close(tag = $tag05)
1159    |> extrude(length = 5, tagEnd = $endCap)
1160
1161clonedCube = clone(cube)
1162"#;
1163        let ctx = crate::test_server::new_context(true, None).await.unwrap();
1164        let program = crate::Program::parse_no_errs(code).unwrap();
1165
1166        // Execute the program.
1167        let result = ctx.run_with_caching(program.clone()).await.unwrap();
1168        let cube = result.variables.get("cube").unwrap();
1169        let cloned_cube = result.variables.get("clonedCube").unwrap();
1170
1171        assert_ne!(cube, cloned_cube);
1172
1173        let KclValueView::Solid { value: cube } = cube else {
1174            panic!("Expected a solid, got: {cube:?}");
1175        };
1176        let KclValueView::Solid { value: cloned_cube } = cloned_cube else {
1177            panic!("Expected a solid, got: {cloned_cube:?}");
1178        };
1179        let cube_sketch = cube.sketch().expect("Expected cube to have a sketch");
1180        let cloned_cube_sketch = cloned_cube.sketch().expect("Expected cloned cube to have a sketch");
1181
1182        assert_ne!(cube.id, cloned_cube.id);
1183        assert_ne!(cube_sketch.id, cloned_cube_sketch.id);
1184        assert_ne!(cube_sketch.original_id, cloned_cube_sketch.original_id);
1185        assert_ne!(cube.artifact_id, cloned_cube.artifact_id);
1186        assert_ne!(cube_sketch.artifact_id, cloned_cube_sketch.artifact_id);
1187
1188        assert_ne!(cloned_cube.artifact_id, cloned_cube.id.into());
1189
1190        for (path, cloned_path) in cube_sketch.paths.iter().zip(cloned_cube_sketch.paths.iter()) {
1191            assert_ne!(path.get_id(), cloned_path.get_id());
1192            assert_eq!(path.get_tag(), cloned_path.get_tag());
1193        }
1194
1195        for (value, cloned_value) in cube.value.iter().zip(cloned_cube.value.iter()) {
1196            assert_ne!(value.get_id(), cloned_value.get_id());
1197            assert_eq!(value.get_tag(), cloned_value.get_tag());
1198        }
1199
1200        for (tag_name, tag) in &cube_sketch.tags {
1201            let cloned_tag = cloned_cube_sketch.tags.get(tag_name).unwrap();
1202
1203            let tag_info = tag.get_cur_info().unwrap();
1204            let cloned_tag_info = cloned_tag.get_cur_info().unwrap();
1205
1206            assert_ne!(tag_info.id, cloned_tag_info.id);
1207            assert_ne!(tag_info.geometry.id(), cloned_tag_info.geometry.id());
1208            assert_eq!(tag_info.path.is_some(), cloned_tag_info.path.is_some());
1209            if let (Some(path), Some(cloned_path)) = (&tag_info.path, &cloned_tag_info.path) {
1210                assert_ne!(path, cloned_path);
1211            }
1212            assert_eq!(tag_info.surface.is_some(), cloned_tag_info.surface.is_some());
1213            if let (Some(surface), Some(cloned_surface)) = (&tag_info.surface, &cloned_tag_info.surface) {
1214                assert_ne!(surface, cloned_surface);
1215            }
1216        }
1217
1218        for (tag_name, tag) in &cube.faces {
1219            let cloned_tag = cloned_cube.faces.get(tag_name).unwrap();
1220
1221            let tag_info = tag.get_cur_info().unwrap();
1222            let cloned_tag_info = cloned_tag.get_cur_info().unwrap();
1223
1224            assert_ne!(tag_info.id, cloned_tag_info.id);
1225            assert_ne!(tag_info.geometry.id(), cloned_tag_info.geometry.id());
1226            assert_ne!(tag_info.surface, cloned_tag_info.surface);
1227        }
1228        assert!(cube.faces.contains_key("endCap"));
1229        assert!(cloned_cube.faces.contains_key("endCap"));
1230
1231        assert_eq!(cube.edge_cuts.len(), 0);
1232        assert_eq!(cloned_cube.edge_cuts.len(), 0);
1233
1234        ctx.close().await;
1235    }
1236
1237    // Pattern copies retain the source topology in program memory. Cloning a
1238    // copy must map that source topology directly onto the clone so both wall
1239    // and cap tags refer to the clone's faces.
1240    #[tokio::test(flavor = "multi_thread")]
1241    async fn kcl_test_clone_pattern_copy_with_face_tags() {
1242        let code = r#"source = startSketchOn(XY)
1243    |> startProfile(at = [0, 0])
1244    |> line(end = [0, 10], tag = $wall)
1245    |> line(end = [10, 0])
1246    |> line(end = [0, -10])
1247    |> close()
1248    |> extrude(length = 5, tagEnd = $endCap)
1249
1250patterned = patternLinear3d(
1251    source,
1252    instances = 2,
1253    distance = 15,
1254    axis = [1, 0, 0],
1255)
1256patternCopy = patterned[1]
1257clonedCopy = clone(patternCopy)
1258"#;
1259        let program = crate::Program::parse_no_errs(code).unwrap();
1260        let ctx = crate::test_server::new_context(true, None).await.unwrap();
1261
1262        let result = ctx.run_with_caching(program).await.unwrap();
1263        let source = result.variables.get("source").unwrap();
1264        let pattern_copy = result.variables.get("patternCopy").unwrap();
1265        let cloned_copy = result.variables.get("clonedCopy").unwrap();
1266
1267        let KclValueView::Solid { value: source } = source else {
1268            panic!("Expected a solid, got: {source:?}");
1269        };
1270        let KclValueView::Solid { value: pattern_copy } = pattern_copy else {
1271            panic!("Expected a solid, got: {pattern_copy:?}");
1272        };
1273        let KclValueView::Solid { value: cloned_copy } = cloned_copy else {
1274            panic!("Expected a solid, got: {cloned_copy:?}");
1275        };
1276        let pattern_sketch = pattern_copy.sketch().expect("Expected pattern copy to have a sketch");
1277        let cloned_sketch = cloned_copy.sketch().expect("Expected cloned copy to have a sketch");
1278        assert_eq!(pattern_copy.original_id(), source.id);
1279        assert_eq!(cloned_copy.original_id(), cloned_copy.id);
1280        assert!(result.artifact_graph.get(&pattern_copy.artifact_id).is_none());
1281        assert_ne!(cloned_copy.artifact_id, cloned_copy.id.into());
1282
1283        let pattern_wall = pattern_sketch.tags.get("wall").unwrap().get_cur_info().unwrap();
1284        let cloned_wall = cloned_sketch.tags.get("wall").unwrap().get_cur_info().unwrap();
1285        assert_ne!(pattern_wall.id, cloned_wall.id);
1286        assert_ne!(pattern_wall.surface, cloned_wall.surface);
1287        let cloned_wall_id = ArtifactId::new(
1288            cloned_wall
1289                .surface
1290                .as_ref()
1291                .expect("Expected cloned wall tag to reference a surface")
1292                .face_id(),
1293        );
1294
1295        let pattern_cap = pattern_copy.faces.get("endCap").unwrap().get_cur_info().unwrap();
1296        let cloned_cap = cloned_copy.faces.get("endCap").unwrap().get_cur_info().unwrap();
1297        assert_ne!(pattern_cap.id, cloned_cap.id);
1298        assert_ne!(pattern_cap.surface, cloned_cap.surface);
1299        let cloned_cap_id = ArtifactId::new(
1300            cloned_cap
1301                .surface
1302                .as_ref()
1303                .expect("Expected cloned cap tag to reference a surface")
1304                .face_id(),
1305        );
1306
1307        assert!(matches!(
1308            result.artifact_graph.get(&cloned_copy.artifact_id),
1309            Some(Artifact::Sweep(sweep))
1310                if sweep.path_id == cloned_copy.id.into()
1311        ));
1312        assert!(matches!(
1313            result.artifact_graph.get(&cloned_copy.id.into()),
1314            Some(Artifact::Path(path))
1315                if path.sweep_id == Some(cloned_copy.artifact_id)
1316        ));
1317        assert!(matches!(
1318            result.artifact_graph.get(&cloned_wall_id),
1319            Some(Artifact::Wall(wall)) if wall.sweep_id == cloned_copy.artifact_id
1320        ));
1321        assert!(matches!(
1322            result.artifact_graph.get(&cloned_cap_id),
1323            Some(Artifact::Cap(cap)) if cap.sweep_id == cloned_copy.artifact_id
1324        ));
1325
1326        ctx.close().await;
1327    }
1328
1329    // Ensure we can get all paths even on a sketch where we closed it and it was already closed.
1330    #[tokio::test(flavor = "multi_thread")]
1331    #[ignore = "this test is not working yet, need to fix the getting of ids if sketch already closed"]
1332    async fn kcl_test_clone_cube_already_closed_sketch() {
1333        let code = r#"// Clone a basic solid and move it.
1334
1335exampleSketch = startSketchOn(XY)
1336  |> startProfile(at = [0, 0])
1337  |> line(end = [10, 0])
1338  |> line(end = [0, 10])
1339  |> line(end = [-10, 0])
1340  |> line(end = [0, -10])
1341  |> close()
1342
1343cube = extrude(exampleSketch, length = 5)
1344clonedCube = clone(cube)
1345    |> translate(
1346        x = 25.0,
1347    )"#;
1348        let ctx = crate::test_server::new_context(true, None).await.unwrap();
1349        let program = crate::Program::parse_no_errs(code).unwrap();
1350
1351        // Execute the program.
1352        let result = ctx.run_with_caching(program.clone()).await.unwrap();
1353        let cube = result.variables.get("cube").unwrap();
1354        let cloned_cube = result.variables.get("clonedCube").unwrap();
1355
1356        assert_ne!(cube, cloned_cube);
1357
1358        let KclValueView::Solid { value: cube } = cube else {
1359            panic!("Expected a solid, got: {cube:?}");
1360        };
1361        let KclValueView::Solid { value: cloned_cube } = cloned_cube else {
1362            panic!("Expected a solid, got: {cloned_cube:?}");
1363        };
1364        let cube_sketch = cube.sketch().expect("Expected cube to have a sketch");
1365        let cloned_cube_sketch = cloned_cube.sketch().expect("Expected cloned cube to have a sketch");
1366
1367        assert_ne!(cube.id, cloned_cube.id);
1368        assert_ne!(cube_sketch.id, cloned_cube_sketch.id);
1369        assert_ne!(cube_sketch.original_id, cloned_cube_sketch.original_id);
1370        assert_ne!(cube.artifact_id, cloned_cube.artifact_id);
1371        assert_ne!(cube_sketch.artifact_id, cloned_cube_sketch.artifact_id);
1372
1373        assert_ne!(cloned_cube.artifact_id, cloned_cube.id.into());
1374
1375        for (path, cloned_path) in cube_sketch.paths.iter().zip(cloned_cube_sketch.paths.iter()) {
1376            assert_ne!(path.get_id(), cloned_path.get_id());
1377            assert_eq!(path.get_tag(), cloned_path.get_tag());
1378        }
1379
1380        for (value, cloned_value) in cube.value.iter().zip(cloned_cube.value.iter()) {
1381            assert_ne!(value.get_id(), cloned_value.get_id());
1382            assert_eq!(value.get_tag(), cloned_value.get_tag());
1383        }
1384
1385        for (tag_name, tag) in &cube_sketch.tags {
1386            let cloned_tag = cloned_cube_sketch.tags.get(tag_name).unwrap();
1387
1388            let tag_info = tag.get_cur_info().unwrap();
1389            let cloned_tag_info = cloned_tag.get_cur_info().unwrap();
1390
1391            assert_ne!(tag_info.id, cloned_tag_info.id);
1392            assert_ne!(tag_info.geometry.id(), cloned_tag_info.geometry.id());
1393            assert_ne!(tag_info.path, cloned_tag_info.path);
1394            assert_ne!(tag_info.surface, cloned_tag_info.surface);
1395        }
1396
1397        for (edge_cut, cloned_edge_cut) in cube.edge_cuts.iter().zip(cloned_cube.edge_cuts.iter()) {
1398            assert_ne!(edge_cut.id(), cloned_edge_cut.id());
1399            assert_ne!(edge_cut.edge_id(), cloned_edge_cut.edge_id());
1400            assert_eq!(edge_cut.tag(), cloned_edge_cut.tag());
1401        }
1402
1403        ctx.close().await;
1404    }
1405
1406    // Ensure the clone function returns a solid with different ids for all the internal paths and
1407    // references.
1408    // WITH TAGS AND EDGE CUTS.
1409    #[tokio::test(flavor = "multi_thread")]
1410    async fn kcl_test_clone_solid_with_edge_cuts() {
1411        let code = r#"cube = startSketchOn(XY)
1412    |> startProfile(at = [0,0]) // tag this one
1413    |> line(end = [0, 10], tag = $tag02)
1414    |> line(end = [10, 0], tag = $tag03)
1415    |> line(end = [0, -10], tag = $tag04)
1416    |> close(tag = $tag05)
1417    |> extrude(length = 5) // TODO: Tag these
1418  |> fillet(
1419    radius = 2,
1420    tags = [
1421      getNextAdjacentEdge(tag02),
1422    ],
1423    tag = $fillet01,
1424  )
1425  |> fillet(
1426    radius = 2,
1427    tags = [
1428      getNextAdjacentEdge(tag04),
1429    ],
1430    tag = $fillet02,
1431  )
1432  |> chamfer(
1433    length = 2,
1434    tags = [
1435      getNextAdjacentEdge(tag03),
1436    ],
1437    tag = $chamfer01,
1438  )
1439  |> chamfer(
1440    length = 2,
1441    tags = [
1442      getNextAdjacentEdge(tag05),
1443    ],
1444    tag = $chamfer02,
1445  )
1446
1447clonedCube = clone(cube)
1448"#;
1449        let ctx = crate::test_server::new_context(true, None).await.unwrap();
1450        let program = crate::Program::parse_no_errs(code).unwrap();
1451
1452        // Execute the program.
1453        let result = ctx.run_with_caching(program.clone()).await.unwrap();
1454        let cube = result.variables.get("cube").unwrap();
1455        let cloned_cube = result.variables.get("clonedCube").unwrap();
1456
1457        assert_ne!(cube, cloned_cube);
1458
1459        let KclValueView::Solid { value: cube } = cube else {
1460            panic!("Expected a solid, got: {cube:?}");
1461        };
1462        let KclValueView::Solid { value: cloned_cube } = cloned_cube else {
1463            panic!("Expected a solid, got: {cloned_cube:?}");
1464        };
1465        let cube_sketch = cube.sketch().expect("Expected cube to have a sketch");
1466        let cloned_cube_sketch = cloned_cube.sketch().expect("Expected cloned cube to have a sketch");
1467
1468        assert_ne!(cube.id, cloned_cube.id);
1469        assert_ne!(cube_sketch.id, cloned_cube_sketch.id);
1470        assert_ne!(cube_sketch.original_id, cloned_cube_sketch.original_id);
1471        assert_ne!(cube.artifact_id, cloned_cube.artifact_id);
1472        assert_ne!(cube_sketch.artifact_id, cloned_cube_sketch.artifact_id);
1473
1474        assert_ne!(cloned_cube.artifact_id, cloned_cube.id.into());
1475
1476        for (value, cloned_value) in cube.value.iter().zip(cloned_cube.value.iter()) {
1477            assert_ne!(value.get_id(), cloned_value.get_id());
1478            assert_eq!(value.get_tag(), cloned_value.get_tag());
1479        }
1480
1481        for (edge_cut, cloned_edge_cut) in cube.edge_cuts.iter().zip(cloned_cube.edge_cuts.iter()) {
1482            assert_ne!(edge_cut.id(), cloned_edge_cut.id());
1483            assert_ne!(edge_cut.edge_id(), cloned_edge_cut.edge_id());
1484            assert_eq!(edge_cut.tag(), cloned_edge_cut.tag());
1485        }
1486
1487        ctx.close().await;
1488    }
1489}