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::SolidCreatorView;
515    use kcl_api::SolidView;
516    use kcl_api::artifact::SweepSubType;
517    use kittycad_modeling_cmds::shared::BodyType;
518    use pretty_assertions::assert_eq;
519    use pretty_assertions::assert_ne;
520
521    use crate::exec::KclValueView;
522    use crate::execution::Artifact;
523    use crate::execution::ArtifactGraph;
524    use crate::execution::EdgeCutViewExt;
525    use crate::execution::ExecOutcome;
526    use crate::execution::ExtrudeSurfaceViewExt;
527    use crate::execution::KclValue;
528    use crate::execution::PathViewExt;
529    use crate::execution::Solid;
530    use crate::execution::SolidViewExt;
531
532    fn runtime_solid<'a>(outcome: &'a ExecOutcome, name: &str) -> &'a Solid {
533        let value = outcome
534            .test_program_memory
535            .get(name)
536            .unwrap_or_else(|| panic!("Expected runtime value for {name}"));
537        let KclValue::Solid { value } = value else {
538            panic!("Expected {name} to be a runtime solid, got: {value:?}");
539        };
540        value
541    }
542
543    fn assert_cloned_composite_topology(artifact_graph: &ArtifactGraph, cloned_composite: &SolidView) {
544        let Some(Artifact::CompositeSolid(cloned_artifact)) = artifact_graph.get(&cloned_composite.artifact_id) else {
545            panic!("Expected a cloned composite solid artifact at the engine entity ID");
546        };
547        assert_eq!(cloned_artifact.id, cloned_composite.artifact_id);
548        assert!(!cloned_artifact.consumed);
549
550        let cloned_face_sweep_ids = artifact_graph
551            .values()
552            .filter_map(|artifact| match artifact {
553                Artifact::Wall(wall) if wall.cmd_id == cloned_composite.id => Some(wall.sweep_id),
554                Artifact::Cap(cap) if cap.cmd_id == cloned_composite.id => Some(cap.sweep_id),
555                _ => None,
556            })
557            .collect::<Vec<_>>();
558        assert!(!cloned_face_sweep_ids.is_empty());
559
560        for sweep_id in cloned_face_sweep_ids {
561            let Some(Artifact::Sweep(sweep)) = artifact_graph.get(&sweep_id) else {
562                panic!("Expected every cloned composite face to reference a sweep");
563            };
564            assert_eq!(sweep.code_ref, cloned_artifact.code_ref);
565            let source_sweep_id = sweep.source_sweep_id.expect("Expected cloned sweep provenance");
566            assert_ne!(sweep.id, source_sweep_id);
567            assert!(matches!(artifact_graph.get(&source_sweep_id), Some(Artifact::Sweep(_))));
568        }
569    }
570
571    // Ensure the clone function returns a sketch with different ids for all the internal paths and
572    // the resulting sketch.
573    #[tokio::test(flavor = "multi_thread")]
574    async fn kcl_test_clone_sketch() {
575        let code = r#"cube = startSketchOn(XY)
576    |> startProfile(at = [0,0])
577    |> line(end = [0, 10])
578    |> line(end = [10, 0])
579    |> line(end = [0, -10])
580    |> close()
581
582clonedCube = clone(cube)
583"#;
584        let ctx = crate::test_server::new_context(true, None, true).await.unwrap();
585        let program = crate::Program::parse_no_errs(code).unwrap();
586
587        // Execute the program.
588        let result = ctx.run_with_caching(program.clone()).await.unwrap();
589        let cube = result.variables.get("cube").unwrap();
590        let cloned_cube = result.variables.get("clonedCube").unwrap();
591
592        assert_ne!(cube, cloned_cube);
593
594        let KclValueView::Sketch { value: cube } = cube else {
595            panic!("Expected a sketch, got: {cube:?}");
596        };
597        let KclValueView::Sketch { value: cloned_cube } = cloned_cube else {
598            panic!("Expected a sketch, got: {cloned_cube:?}");
599        };
600
601        assert_ne!(cube.id, cloned_cube.id);
602        assert_ne!(cube.original_id, cloned_cube.original_id);
603        assert_ne!(cube.artifact_id, cloned_cube.artifact_id);
604
605        assert_eq!(cloned_cube.artifact_id, cloned_cube.id.into());
606        assert_eq!(cloned_cube.original_id, cloned_cube.id);
607
608        for (path, cloned_path) in cube.paths.iter().zip(cloned_cube.paths.iter()) {
609            assert_ne!(path.get_id(), cloned_path.get_id());
610            assert_eq!(path.get_tag(), cloned_path.get_tag());
611        }
612
613        assert_eq!(cube.tags.len(), 0);
614        assert_eq!(cloned_cube.tags.len(), 0);
615
616        ctx.close().await;
617    }
618
619    // Ensure the clone function returns a solid with different ids for all the internal paths and
620    // references.
621    #[tokio::test(flavor = "multi_thread")]
622    async fn kcl_test_clone_solid() {
623        let code = r#"cube = startSketchOn(XY)
624    |> startProfile(at = [0,0])
625    |> line(end = [0, 10])
626    |> line(end = [10, 0])
627    |> line(end = [0, -10])
628    |> close()
629    |> extrude(length = 5)
630
631clonedCube = clone(cube)
632"#;
633        let ctx = crate::test_server::new_context(true, None, true).await.unwrap();
634        let program = crate::Program::parse_no_errs(code).unwrap();
635
636        // Execute the program.
637        let result = ctx.run_with_caching(program.clone()).await.unwrap();
638        let cube = result.variables.get("cube").unwrap();
639        let cloned_cube = result.variables.get("clonedCube").unwrap();
640
641        assert_ne!(cube, cloned_cube);
642
643        let KclValueView::Solid { value: cube } = cube else {
644            panic!("Expected a solid, got: {cube:?}");
645        };
646        let KclValueView::Solid { value: cloned_cube } = cloned_cube else {
647            panic!("Expected a solid, got: {cloned_cube:?}");
648        };
649        let cube_sketch = cube.sketch().expect("Expected cube to have a sketch");
650        let cloned_cube_sketch = cloned_cube.sketch().expect("Expected cloned cube to have a sketch");
651
652        assert_ne!(cube.id, cloned_cube.id);
653        assert_ne!(cube_sketch.id, cloned_cube_sketch.id);
654        assert_ne!(cube_sketch.original_id, cloned_cube_sketch.original_id);
655        assert_ne!(cube.artifact_id, cloned_cube.artifact_id);
656        assert_ne!(cube_sketch.artifact_id, cloned_cube_sketch.artifact_id);
657
658        assert_ne!(cloned_cube.artifact_id, cloned_cube.id.into());
659
660        for (path, cloned_path) in cube_sketch.paths.iter().zip(cloned_cube_sketch.paths.iter()) {
661            assert_ne!(path.get_id(), cloned_path.get_id());
662            assert_eq!(path.get_tag(), cloned_path.get_tag());
663        }
664
665        for (value, cloned_value) in cube.value.iter().zip(cloned_cube.value.iter()) {
666            assert_ne!(value.get_id(), cloned_value.get_id());
667            assert_eq!(value.get_tag(), cloned_value.get_tag());
668        }
669
670        assert_eq!(cube_sketch.tags.len(), 0);
671        assert_eq!(cloned_cube_sketch.tags.len(), 0);
672
673        assert_eq!(cube.edge_cuts.len(), 0);
674        assert_eq!(cloned_cube.edge_cuts.len(), 0);
675
676        ctx.close().await;
677    }
678
679    #[tokio::test(flavor = "multi_thread")]
680    async fn kcl_test_clone_sketch_backed_surface_operations() {
681        let code = r#"extrudeProfile = startSketchOn(XZ)
682  |> startProfile(at = [0, 0])
683  |> line(end = [4, 0])
684  |> line(end = [2, 3])
685surfaceExtrude = extrude(extrudeProfile, length = 2, bodyType = SURFACE)
686surfaceExtrudeClone = clone(surfaceExtrude)
687
688revolveProfile = startSketchOn(XZ)
689  |> startProfile(at = [5, 0])
690  |> line(end = [2, 3])
691surfaceRevolve = revolve(revolveProfile, axis = Y, angle = 180deg, bodyType = SURFACE)
692surfaceRevolveClone = clone(surfaceRevolve)
693
694sweepProfile = startSketchOn(XY)
695  |> startProfile(at = [-10, 10])
696  |> line(end = [4, 0])
697sweepPath = startSketchOn(XY)
698  |> startProfile(at = [0, 0])
699  |> line(end = [10, 0])
700  |> tangentialArc(end = [4, -4])
701surfaceSweep = sweep(sweepProfile, path = sweepPath, bodyType = SURFACE)
702surfaceSweepClone = clone(surfaceSweep)
703
704loftProfileA = startSketchOn(offsetPlane(XZ, offset = -10))
705  |> startProfile(at = [-2, -2])
706  |> line(end = [4, 0])
707loftProfileB = startSketchOn(offsetPlane(XZ, offset = -15))
708  |> startProfile(at = [-1, -1])
709  |> line(end = [2, 0])
710surfaceLoft = loft([loftProfileA, loftProfileB], bodyType = SURFACE)
711surfaceLoftClone = clone(surfaceLoft)
712"#;
713        let ctx = crate::test_server::new_context(true, None, true).await.unwrap();
714        let program = crate::Program::parse_no_errs(code).unwrap();
715
716        let result = ctx.run_with_caching(program).await.unwrap();
717        for (source_name, clone_name) in [
718            ("surfaceExtrude", "surfaceExtrudeClone"),
719            ("surfaceRevolve", "surfaceRevolveClone"),
720            ("surfaceSweep", "surfaceSweepClone"),
721            ("surfaceLoft", "surfaceLoftClone"),
722        ] {
723            let KclValueView::Solid { value: source } = result.variables.get(source_name).unwrap() else {
724                panic!("Expected {source_name} to be a surface body");
725            };
726            let KclValueView::Solid { value: cloned } = result.variables.get(clone_name).unwrap() else {
727                panic!("Expected {clone_name} to be a surface body");
728            };
729
730            assert_ne!(source.id, cloned.id);
731            assert_eq!(
732                runtime_solid(&result, clone_name).best_guess_body_type,
733                Some(BodyType::Surface)
734            );
735            assert!(matches!(cloned.creator, SolidCreatorView::Sketch(_)));
736            assert!(!cloned.value.is_empty());
737        }
738
739        ctx.close().await;
740    }
741
742    #[tokio::test(flavor = "multi_thread")]
743    async fn kcl_test_clone_edge_created_surface() {
744        let code = r#"@settings(kclVersion = 2.0)
745
746baseSketch = sketch(on = XY) {
747  bottom = line(start = [var 0mm, var 0mm], end = [var 10mm, var 0mm])
748  right = line(start = [var 10mm, var 0mm], end = [var 10mm, var 10mm])
749  top = line(start = [var 10mm, var 10mm], end = [var 0mm, var 10mm])
750  left = line(start = [var 0mm, var 10mm], end = [var 0mm, var 0mm])
751  coincident([bottom.end, right.start])
752  coincident([right.end, top.start])
753  coincident([top.end, left.start])
754  coincident([left.end, bottom.start])
755}
756base = extrude(region(segments = [baseSketch.bottom, baseSketch.right]), length = 5mm)
757source = extrude(
758  getOppositeEdge(base.sketch.tags.bottom),
759  length = 3mm,
760  bodyType = SURFACE,
761  method = NEW,
762)
763cloned = clone(source)
764"#;
765        let ctx = crate::test_server::new_context(true, None, true).await.unwrap();
766        let program = crate::Program::parse_no_errs(code).unwrap();
767
768        let result = ctx.run_with_caching(program).await.unwrap();
769        let KclValueView::Solid { value: source } = result.variables.get("source").unwrap() else {
770            panic!("Expected an edge-created source surface");
771        };
772        let KclValueView::Solid { value: cloned } = result.variables.get("cloned").unwrap() else {
773            panic!("Expected a cloned edge-created surface");
774        };
775        let SolidCreatorView::Edge {
776            edge_id: source_edge_id,
777            ..
778        } = &source.creator
779        else {
780            panic!("Expected the source surface to retain its edge creator");
781        };
782        let SolidCreatorView::Edge {
783            edge_id: cloned_edge_id,
784            body_id: cloned_body_id,
785        } = &cloned.creator
786        else {
787            panic!("Expected the cloned surface to retain its edge creator");
788        };
789
790        assert_ne!(source.id, cloned.id);
791        assert_eq!(
792            runtime_solid(&result, "cloned").best_guess_body_type,
793            Some(BodyType::Surface)
794        );
795        assert_eq!(*cloned_body_id, cloned.id);
796        assert_ne!(source_edge_id, cloned_edge_id);
797        assert_ne!(source.value[0].get_id(), cloned.value[0].get_id());
798        assert_ne!(source.value[0].face_id(), cloned.value[0].face_id());
799
800        ctx.close().await;
801    }
802
803    #[tokio::test(flavor = "multi_thread")]
804    async fn kcl_test_clone_preserves_face_creator() {
805        let code = r#"profile = startSketchOn(XY)
806  |> startProfile(at = [0, 0])
807  |> yLine(length = 1, tag = $a)
808  |> xLine(length = 1, tag = $b)
809  |> close(tag = $c)
810base = extrude(profile, length = 1)
811source = extrude(c, length = 4, method = NEW)
812cloned = clone(source)
813"#;
814        let ctx = crate::test_server::new_context(true, None, true).await.unwrap();
815        let program = crate::Program::parse_no_errs(code).unwrap();
816
817        let result = ctx.run_with_caching(program).await.unwrap();
818        let KclValueView::Solid { value: source } = result.variables.get("source").unwrap() else {
819            panic!("Expected a face-created source body");
820        };
821        let KclValueView::Solid { value: cloned } = result.variables.get("cloned").unwrap() else {
822            panic!("Expected a cloned face-created body");
823        };
824        let SolidCreatorView::Face {
825            face_id: source_face_id,
826            solid_id: source_solid_id,
827            sketch: source_sketch,
828        } = &source.creator
829        else {
830            panic!("Expected the source body to retain its face creator");
831        };
832        let SolidCreatorView::Face {
833            face_id: cloned_face_id,
834            solid_id: cloned_solid_id,
835            sketch: cloned_sketch,
836        } = &cloned.creator
837        else {
838            panic!("Expected the cloned body to retain its face creator");
839        };
840
841        assert_ne!(source.id, cloned.id);
842        assert_ne!(source_face_id, cloned_face_id);
843        assert_ne!(source_solid_id, cloned_solid_id);
844        assert_ne!(source_sketch.id, cloned_sketch.id);
845        assert_ne!(source_sketch.original_id, cloned_sketch.original_id);
846
847        ctx.close().await;
848    }
849
850    #[tokio::test(flavor = "multi_thread")]
851    async fn kcl_test_clone_procedural_blend_surface() {
852        let code = r#"@settings(defaultLengthUnit = mm, kclVersion = 2.0)
853
854sketchA = sketch(on = YZ) {
855  line1 = line(start = [var 4.1mm, var -0.1mm], end = [var 5.5mm, var 0mm])
856  line2 = line(start = [var 5.5mm, var 0mm], end = [var 5.5mm, var 3mm])
857  line3 = line(start = [var 5.5mm, var 3mm], end = [var 3.9mm, var 2.8mm])
858  line4 = line(start = [var 4.1mm, var 3mm], end = [var 4.5mm, var -0.2mm])
859  coincident([line1.end, line2.start])
860  coincident([line2.end, line3.start])
861  coincident([line3.end, line4.start])
862  coincident([line4.end, line1.start])
863}
864
865sketchB = sketch(on = -XZ) {
866  line5 = line(start = [var -5.3mm, var -0.1mm], end = [var -3.5mm, var -0.1mm])
867  line6 = line(start = [var -3.5mm, var -0.1mm], end = [var -3.5mm, var 3.1mm])
868  line7 = line(start = [var -3.5mm, var 4.5mm], end = [var -5.4mm, var 4.5mm])
869  line8 = line(start = [var -5.3mm, var 3.1mm], end = [var -5.3mm, var -0.1mm])
870  coincident([line5.end, line6.start])
871  coincident([line6.end, line7.start])
872  coincident([line7.end, line8.start])
873  coincident([line8.end, line5.start])
874}
875
876surfaceA = extrude(region(segments = [sketchB.line5, sketchB.line6]), length = -2mm, bodyType = SURFACE)
877surfaceB = extrude(region(segments = [sketchA.line1, sketchA.line2]), length = -2mm, bodyType = SURFACE)
878bridge = blend([surfaceA.sketch.tags.line7, surfaceB.sketch.tags.line3])
879bridgeClone = clone(bridge)
880"#;
881        let ctx = crate::test_server::new_context(true, None, true).await.unwrap();
882        let program = crate::Program::parse_no_errs(code).unwrap();
883
884        let result = ctx.run_with_caching(program).await.unwrap();
885        let KclValueView::Solid { value: bridge } = result.variables.get("bridge").unwrap() else {
886            panic!("Expected blend to create a procedural surface");
887        };
888        let KclValueView::Solid { value: cloned } = result.variables.get("bridgeClone").unwrap() else {
889            panic!("Expected blend clone to create a procedural surface");
890        };
891
892        assert_ne!(bridge.id, cloned.id);
893        assert_eq!(
894            runtime_solid(&result, "bridgeClone").best_guess_body_type,
895            Some(BodyType::Surface)
896        );
897        assert!(matches!(cloned.creator, SolidCreatorView::Procedural));
898        let Some(Artifact::Sweep(cloned_sweep)) = result.artifact_graph.get(&cloned.artifact_id) else {
899            panic!("Expected the blend clone to have a sweep artifact");
900        };
901        assert_eq!(cloned_sweep.sub_type, SweepSubType::Blend);
902        assert_eq!(cloned_sweep.source_sweep_id, Some(bridge.artifact_id));
903
904        ctx.close().await;
905    }
906
907    #[tokio::test(flavor = "multi_thread")]
908    async fn kcl_test_clone_multi_body_join_queries_body_type() {
909        let code = r#"@settings(kclVersion = 2.0)
910
911targetSketch = sketch(on = XY) {
912  bottom = line(start = [var -10, var -10], end = [var 10, var -10])
913  right = line(start = [var 10, var -10], end = [var 10, var 10])
914  top = line(start = [var 10, var 10], end = [var -10, var 10])
915  left = line(start = [var -10, var 10], end = [var -10, var -10])
916  coincident([bottom.end, right.start])
917  coincident([right.end, top.start])
918  coincident([top.end, left.start])
919  coincident([left.end, bottom.start])
920}
921target = extrude(region(point = [0, 0], sketch = targetSketch), length = 10)
922
923cutterSketch = sketch(on = XY) {
924  bottom = line(start = [var -1, var -12], end = [var 1, var -12])
925  right = line(start = [var 1, var -12], end = [var 1, var 12])
926  top = line(start = [var 1, var 12], end = [var -1, var 12])
927  left = line(start = [var -1, var 12], end = [var -1, var -12])
928  coincident([bottom.end, right.start])
929  coincident([right.end, top.start])
930  coincident([top.end, left.start])
931  coincident([left.end, bottom.start])
932}
933cutter = extrude(region(point = [0, 0], sketch = cutterSketch), length = 10)
934
935pieces = split([target], tools = [cutter], keepTools = true)
936joined = joinSurfaces(pieces)
937joinedClone = clone(joined)
938"#;
939        let ctx = crate::test_server::new_context(true, None, true).await.unwrap();
940        let program = crate::Program::parse_no_errs(code).unwrap();
941
942        let result = ctx.run_with_caching(program).await.unwrap();
943        let KclValueView::Solid { value: joined } = result.variables.get("joined").unwrap() else {
944            panic!("Expected joinSurfaces to create a procedural body");
945        };
946        let KclValueView::Solid { value: cloned } = result.variables.get("joinedClone").unwrap() else {
947            panic!("Expected joinSurfaces body to clone");
948        };
949
950        assert_ne!(joined.id, cloned.id);
951        assert!(runtime_solid(&result, "joined").best_guess_body_type.is_none());
952        assert!(runtime_solid(&result, "joinedClone").best_guess_body_type.is_some());
953        assert!(matches!(cloned.creator, SolidCreatorView::Procedural));
954
955        ctx.close().await;
956    }
957
958    #[tokio::test(flavor = "multi_thread")]
959    async fn kcl_test_clone_loft() {
960        let code = r#"@settings(kclVersion = 2.0)
961
962firstSketch = sketch(on = XY) {
963  circle1 = circle(start = [var 10, var 0], center = [var 0, var 0])
964}
965secondSketch = sketch(on = offsetPlane(XY, offset = 10)) {
966  circle1 = circle(start = [var 5, var 0], center = [var 0, var 0])
967}
968
969lofted = loft([
970  region(segments = [firstSketch.circle1]),
971  region(segments = [secondSketch.circle1]),
972])
973clonedLoft = clone(lofted)
974"#;
975        let ctx = crate::test_server::new_context(true, None, true).await.unwrap();
976        let program = crate::Program::parse_no_errs(code).unwrap();
977
978        let result = ctx.run_with_caching(program).await.unwrap();
979        let KclValueView::Solid { value: lofted } = result.variables.get("lofted").unwrap() else {
980            panic!("Expected a solid loft");
981        };
982        let KclValueView::Solid { value: cloned_loft } = result.variables.get("clonedLoft").unwrap() else {
983            panic!("Expected a cloned solid loft");
984        };
985
986        assert_eq!(lofted.topology_id(), lofted.id);
987        assert_eq!(lofted.original_id(), lofted.id);
988        assert_eq!(lofted.artifact_id, lofted.id.into());
989
990        assert_ne!(lofted.id, cloned_loft.id);
991        assert_ne!(lofted.artifact_id, cloned_loft.artifact_id);
992        assert_eq!(cloned_loft.topology_id(), cloned_loft.id);
993        assert_eq!(cloned_loft.original_id(), cloned_loft.id);
994        assert_eq!(cloned_loft.artifact_id, cloned_loft.id.into());
995
996        let loft_sketch = lofted.sketch().expect("Expected loft to retain its base sketch");
997        let cloned_sketch = cloned_loft
998            .sketch()
999            .expect("Expected cloned loft to retain its base sketch");
1000        for (path, cloned_path) in loft_sketch.paths.iter().zip(cloned_sketch.paths.iter()) {
1001            assert_ne!(path.get_id(), cloned_path.get_id());
1002            assert_eq!(path.get_tag(), cloned_path.get_tag());
1003        }
1004
1005        assert!(!cloned_loft.value.is_empty());
1006        for (surface, cloned_surface) in lofted.value.iter().zip(cloned_loft.value.iter()) {
1007            assert_ne!(surface.get_id(), cloned_surface.get_id());
1008            assert_eq!(surface.get_tag(), cloned_surface.get_tag());
1009        }
1010
1011        let Some(Artifact::Sweep(source_sweep)) = result.artifact_graph.get(&lofted.artifact_id) else {
1012            panic!("Expected the source loft to be represented by a sweep artifact");
1013        };
1014        assert_eq!(source_sweep.sub_type, SweepSubType::Loft);
1015
1016        let Some(Artifact::Sweep(cloned_sweep)) = result.artifact_graph.get(&cloned_loft.artifact_id) else {
1017            panic!("Expected the cloned loft to be represented by a sweep artifact");
1018        };
1019        assert_eq!(cloned_sweep.sub_type, SweepSubType::Loft);
1020        assert_eq!(cloned_sweep.source_sweep_id, Some(lofted.artifact_id));
1021        assert_eq!(cloned_sweep.path_id, source_sweep.path_id);
1022        assert!(!cloned_sweep.consumed);
1023
1024        ctx.close().await;
1025    }
1026
1027    #[tokio::test(flavor = "multi_thread")]
1028    async fn kcl_test_clone_composite_solid_keeps_engine_artifact_id() {
1029        let code = r#"left = startSketchOn(XY)
1030    |> startProfile(at = [0, 0])
1031    |> line(end = [10, 0])
1032    |> line(end = [0, 10])
1033    |> line(end = [-10, 0])
1034    |> close()
1035    |> extrude(length = 5)
1036
1037right = startSketchOn(XY)
1038    |> startProfile(at = [5, 0])
1039    |> line(end = [10, 0])
1040    |> line(end = [0, 10])
1041    |> line(end = [-10, 0])
1042    |> close()
1043    |> extrude(length = 5)
1044
1045composite = union([left, right])
1046clonedComposite = clone(composite)
1047"#;
1048        let ctx = crate::test_server::new_context(true, None, true).await.unwrap();
1049        let program = crate::Program::parse_no_errs(code).unwrap();
1050
1051        let result = ctx.run_with_caching(program).await.unwrap();
1052        let KclValueView::Solid { value: composite } = result.variables.get("composite").unwrap() else {
1053            panic!("Expected composite to be a solid");
1054        };
1055        let KclValueView::Solid {
1056            value: cloned_composite,
1057        } = result.variables.get("clonedComposite").unwrap()
1058        else {
1059            panic!("Expected clonedComposite to be a solid");
1060        };
1061
1062        assert_eq!(composite.artifact_id, composite.id.into());
1063        assert_eq!(cloned_composite.artifact_id, cloned_composite.id.into());
1064        assert_ne!(composite.id, cloned_composite.id);
1065        assert_ne!(composite.original_id(), composite.id);
1066        assert_eq!(composite.topology_id(), composite.id);
1067        assert_eq!(cloned_composite.original_id(), cloned_composite.id);
1068        assert_eq!(cloned_composite.topology_id(), cloned_composite.id);
1069
1070        assert_cloned_composite_topology(&result.artifact_graph, cloned_composite);
1071
1072        ctx.close().await;
1073    }
1074
1075    #[tokio::test(flavor = "multi_thread")]
1076    async fn kcl_test_clone_imported_patterned_composite_uses_composite_topology() {
1077        let module_code = r#"left = startSketchOn(XY)
1078    |> startProfile(at = [0, 0])
1079    |> line(end = [10, 0])
1080    |> line(end = [0, 10])
1081    |> line(end = [-10, 0])
1082    |> close()
1083    |> extrude(length = 5)
1084
1085right = startSketchOn(XY)
1086    |> startProfile(at = [5, 0])
1087    |> line(end = [10, 0])
1088    |> line(end = [0, 10])
1089    |> line(end = [-10, 0])
1090    |> close()
1091    |> extrude(length = 5)
1092
1093export composite = union([left, right])
1094"#;
1095        let code = r#"import composite from 'composite.kcl'
1096
1097patterned = patternLinear3d(
1098    composite,
1099    instances = 2,
1100    distance = 20,
1101    axis = [1, 0, 0],
1102)
1103patternCopy = patterned[1]
1104clonedCopy = clone(patternCopy)
1105"#;
1106        let tmpdir = tempfile::TempDir::with_prefix("clone_imported_patterned_composite").unwrap();
1107        let main_path = tmpdir.path().join("main.kcl");
1108        std::fs::write(tmpdir.path().join("composite.kcl"), module_code).unwrap();
1109        std::fs::write(&main_path, code).unwrap();
1110
1111        let ctx = crate::test_server::new_context(true, Some(main_path), true)
1112            .await
1113            .unwrap();
1114        let program = crate::Program::parse_no_errs(code).unwrap();
1115
1116        let result = ctx.run_with_caching(program).await.unwrap();
1117        let KclValueView::Solid { value: composite } = result.variables.get("composite").unwrap() else {
1118            panic!("Expected composite to be a solid");
1119        };
1120        let KclValueView::Solid { value: pattern_copy } = result.variables.get("patternCopy").unwrap() else {
1121            panic!("Expected patternCopy to be a solid");
1122        };
1123        let KclValueView::Solid { value: cloned_copy } = result.variables.get("clonedCopy").unwrap() else {
1124            panic!("Expected clonedCopy to be a solid");
1125        };
1126
1127        assert_eq!(composite.topology_id(), composite.id);
1128        assert_eq!(pattern_copy.topology_id(), composite.id);
1129        assert_eq!(cloned_copy.original_id(), cloned_copy.id);
1130        assert_eq!(cloned_copy.topology_id(), cloned_copy.id);
1131        assert_eq!(cloned_copy.artifact_id, cloned_copy.id.into());
1132        assert_ne!(pattern_copy.id, cloned_copy.id);
1133        assert!(result.artifact_graph.get(&pattern_copy.artifact_id).is_none());
1134        assert_cloned_composite_topology(&result.artifact_graph, cloned_copy);
1135
1136        ctx.close().await;
1137    }
1138
1139    // Ensure the clone function returns a sketch with different ids for all the internal paths and
1140    // the resulting sketch.
1141    // AND TAGS.
1142    #[tokio::test(flavor = "multi_thread")]
1143    async fn kcl_test_clone_sketch_with_tags() {
1144        let code = r#"cube = startSketchOn(XY)
1145    |> startProfile(at = [0,0]) // tag this one
1146    |> line(end = [0, 10], tag = $tag02)
1147    |> line(end = [10, 0], tag = $tag03)
1148    |> line(end = [0, -10], tag = $tag04)
1149    |> close(tag = $tag05)
1150
1151clonedCube = clone(cube)
1152"#;
1153        let ctx = crate::test_server::new_context(true, None, true).await.unwrap();
1154        let program = crate::Program::parse_no_errs(code).unwrap();
1155
1156        // Execute the program.
1157        let result = ctx.run_with_caching(program.clone()).await.unwrap();
1158        let cube = result.variables.get("cube").unwrap();
1159        let cloned_cube = result.variables.get("clonedCube").unwrap();
1160
1161        assert_ne!(cube, cloned_cube);
1162
1163        let KclValueView::Sketch { value: cube } = cube else {
1164            panic!("Expected a sketch, got: {cube:?}");
1165        };
1166        let KclValueView::Sketch { value: cloned_cube } = cloned_cube else {
1167            panic!("Expected a sketch, got: {cloned_cube:?}");
1168        };
1169
1170        assert_ne!(cube.id, cloned_cube.id);
1171        assert_ne!(cube.original_id, cloned_cube.original_id);
1172
1173        for (path, cloned_path) in cube.paths.iter().zip(cloned_cube.paths.iter()) {
1174            assert_ne!(path.get_id(), cloned_path.get_id());
1175            assert_eq!(path.get_tag(), cloned_path.get_tag());
1176        }
1177
1178        for (tag_name, tag) in &cube.tags {
1179            assert_eq!(Some(tag), cloned_cube.tags.get(tag_name));
1180        }
1181
1182        ctx.close().await;
1183    }
1184
1185    // Ensure the clone function returns a solid with different ids for all the internal paths and
1186    // references.
1187    // WITH TAGS.
1188    #[tokio::test(flavor = "multi_thread")]
1189    async fn kcl_test_clone_solid_with_tags() {
1190        let code = r#"cube = startSketchOn(XY)
1191    |> startProfile(at = [0,0]) // tag this one
1192    |> line(end = [0, 10], tag = $tag02)
1193    |> line(end = [10, 0], tag = $tag03)
1194    |> line(end = [0, -10], tag = $tag04)
1195    |> close(tag = $tag05)
1196    |> extrude(length = 5, tagEnd = $endCap)
1197
1198clonedCube = clone(cube)
1199"#;
1200        let ctx = crate::test_server::new_context(true, None, true).await.unwrap();
1201        let program = crate::Program::parse_no_errs(code).unwrap();
1202
1203        // Execute the program.
1204        let result = ctx.run_with_caching(program.clone()).await.unwrap();
1205        let cube = result.variables.get("cube").unwrap();
1206        let cloned_cube = result.variables.get("clonedCube").unwrap();
1207
1208        assert_ne!(cube, cloned_cube);
1209
1210        let KclValueView::Solid { value: cube } = cube else {
1211            panic!("Expected a solid, got: {cube:?}");
1212        };
1213        let KclValueView::Solid { value: cloned_cube } = cloned_cube else {
1214            panic!("Expected a solid, got: {cloned_cube:?}");
1215        };
1216        let cube_sketch = cube.sketch().expect("Expected cube to have a sketch");
1217        let cloned_cube_sketch = cloned_cube.sketch().expect("Expected cloned cube to have a sketch");
1218
1219        assert_ne!(cube.id, cloned_cube.id);
1220        assert_ne!(cube_sketch.id, cloned_cube_sketch.id);
1221        assert_ne!(cube_sketch.original_id, cloned_cube_sketch.original_id);
1222        assert_ne!(cube.artifact_id, cloned_cube.artifact_id);
1223        assert_ne!(cube_sketch.artifact_id, cloned_cube_sketch.artifact_id);
1224
1225        assert_ne!(cloned_cube.artifact_id, cloned_cube.id.into());
1226
1227        for (path, cloned_path) in cube_sketch.paths.iter().zip(cloned_cube_sketch.paths.iter()) {
1228            assert_ne!(path.get_id(), cloned_path.get_id());
1229            assert_eq!(path.get_tag(), cloned_path.get_tag());
1230        }
1231
1232        for (value, cloned_value) in cube.value.iter().zip(cloned_cube.value.iter()) {
1233            assert_ne!(value.get_id(), cloned_value.get_id());
1234            assert_eq!(value.get_tag(), cloned_value.get_tag());
1235        }
1236
1237        for (tag_name, tag) in &cube_sketch.tags {
1238            assert_eq!(Some(tag), cloned_cube_sketch.tags.get(tag_name));
1239        }
1240
1241        for (tag_name, tag) in &cube.faces {
1242            assert_eq!(Some(tag), cloned_cube.faces.get(tag_name));
1243        }
1244        assert!(cube.faces.contains_key("endCap"));
1245        assert!(cloned_cube.faces.contains_key("endCap"));
1246
1247        assert_eq!(cube.edge_cuts.len(), 0);
1248        assert_eq!(cloned_cube.edge_cuts.len(), 0);
1249
1250        ctx.close().await;
1251    }
1252
1253    // Pattern copies retain the source topology in program memory. Cloning a
1254    // copy must map that source topology directly onto the clone so both wall
1255    // and cap tags refer to the clone's faces.
1256    #[tokio::test(flavor = "multi_thread")]
1257    async fn kcl_test_clone_pattern_copy_with_face_tags() {
1258        let code = r#"source = startSketchOn(XY)
1259    |> startProfile(at = [0, 0])
1260    |> line(end = [0, 10], tag = $wall)
1261    |> line(end = [10, 0])
1262    |> line(end = [0, -10])
1263    |> close()
1264    |> extrude(length = 5, tagEnd = $endCap)
1265
1266patterned = patternLinear3d(
1267    source,
1268    instances = 2,
1269    distance = 15,
1270    axis = [1, 0, 0],
1271)
1272patternCopy = patterned[1]
1273clonedCopy = clone(patternCopy)
1274"#;
1275        let program = crate::Program::parse_no_errs(code).unwrap();
1276        let ctx = crate::test_server::new_context(true, None, true).await.unwrap();
1277
1278        let result = ctx.run_with_caching(program).await.unwrap();
1279        let source = result.variables.get("source").unwrap();
1280        let pattern_copy = result.variables.get("patternCopy").unwrap();
1281        let cloned_copy = result.variables.get("clonedCopy").unwrap();
1282
1283        let KclValueView::Solid { value: source } = source else {
1284            panic!("Expected a solid, got: {source:?}");
1285        };
1286        let KclValueView::Solid { value: pattern_copy } = pattern_copy else {
1287            panic!("Expected a solid, got: {pattern_copy:?}");
1288        };
1289        let KclValueView::Solid { value: cloned_copy } = cloned_copy else {
1290            panic!("Expected a solid, got: {cloned_copy:?}");
1291        };
1292        let pattern_sketch = pattern_copy.sketch().expect("Expected pattern copy to have a sketch");
1293        let cloned_sketch = cloned_copy.sketch().expect("Expected cloned copy to have a sketch");
1294        assert_eq!(pattern_copy.original_id(), source.id);
1295        assert_eq!(cloned_copy.original_id(), cloned_copy.id);
1296        assert!(result.artifact_graph.get(&pattern_copy.artifact_id).is_none());
1297        assert_ne!(cloned_copy.artifact_id, cloned_copy.id.into());
1298
1299        assert_eq!(pattern_sketch.tags.get("wall"), cloned_sketch.tags.get("wall"));
1300        assert_eq!(pattern_copy.faces.get("endCap"), cloned_copy.faces.get("endCap"));
1301
1302        assert!(matches!(
1303            result.artifact_graph.get(&cloned_copy.artifact_id),
1304            Some(Artifact::Sweep(sweep))
1305                if sweep.path_id == cloned_copy.id.into()
1306        ));
1307        assert!(matches!(
1308            result.artifact_graph.get(&cloned_copy.id.into()),
1309            Some(Artifact::Path(path))
1310                if path.sweep_id == Some(cloned_copy.artifact_id)
1311        ));
1312        assert!(
1313            result
1314                .artifact_graph
1315                .values()
1316                .any(|artifact| matches!(artifact, Artifact::Wall(wall) if wall.sweep_id == cloned_copy.artifact_id))
1317        );
1318        assert!(
1319            result
1320                .artifact_graph
1321                .values()
1322                .any(|artifact| matches!(artifact, Artifact::Cap(cap) if cap.sweep_id == cloned_copy.artifact_id))
1323        );
1324
1325        ctx.close().await;
1326    }
1327
1328    // Ensure we can get all paths even on a sketch where we closed it and it was already closed.
1329    #[tokio::test(flavor = "multi_thread")]
1330    #[ignore = "this test is not working yet, need to fix the getting of ids if sketch already closed"]
1331    async fn kcl_test_clone_cube_already_closed_sketch() {
1332        let code = r#"// Clone a basic solid and move it.
1333
1334exampleSketch = startSketchOn(XY)
1335  |> startProfile(at = [0, 0])
1336  |> line(end = [10, 0])
1337  |> line(end = [0, 10])
1338  |> line(end = [-10, 0])
1339  |> line(end = [0, -10])
1340  |> close()
1341
1342cube = extrude(exampleSketch, length = 5)
1343clonedCube = clone(cube)
1344    |> translate(
1345        x = 25.0,
1346    )"#;
1347        let ctx = crate::test_server::new_context(true, None, true).await.unwrap();
1348        let program = crate::Program::parse_no_errs(code).unwrap();
1349
1350        // Execute the program.
1351        let result = ctx.run_with_caching(program.clone()).await.unwrap();
1352        let cube = result.variables.get("cube").unwrap();
1353        let cloned_cube = result.variables.get("clonedCube").unwrap();
1354
1355        assert_ne!(cube, cloned_cube);
1356
1357        let KclValueView::Solid { value: cube } = cube else {
1358            panic!("Expected a solid, got: {cube:?}");
1359        };
1360        let KclValueView::Solid { value: cloned_cube } = cloned_cube else {
1361            panic!("Expected a solid, got: {cloned_cube:?}");
1362        };
1363        let cube_sketch = cube.sketch().expect("Expected cube to have a sketch");
1364        let cloned_cube_sketch = cloned_cube.sketch().expect("Expected cloned cube to have a sketch");
1365
1366        assert_ne!(cube.id, cloned_cube.id);
1367        assert_ne!(cube_sketch.id, cloned_cube_sketch.id);
1368        assert_ne!(cube_sketch.original_id, cloned_cube_sketch.original_id);
1369        assert_ne!(cube.artifact_id, cloned_cube.artifact_id);
1370        assert_ne!(cube_sketch.artifact_id, cloned_cube_sketch.artifact_id);
1371
1372        assert_ne!(cloned_cube.artifact_id, cloned_cube.id.into());
1373
1374        for (path, cloned_path) in cube_sketch.paths.iter().zip(cloned_cube_sketch.paths.iter()) {
1375            assert_ne!(path.get_id(), cloned_path.get_id());
1376            assert_eq!(path.get_tag(), cloned_path.get_tag());
1377        }
1378
1379        for (value, cloned_value) in cube.value.iter().zip(cloned_cube.value.iter()) {
1380            assert_ne!(value.get_id(), cloned_value.get_id());
1381            assert_eq!(value.get_tag(), cloned_value.get_tag());
1382        }
1383
1384        for (tag_name, tag) in &cube_sketch.tags {
1385            assert_eq!(Some(tag), cloned_cube_sketch.tags.get(tag_name));
1386        }
1387
1388        for (edge_cut, cloned_edge_cut) in cube.edge_cuts.iter().zip(cloned_cube.edge_cuts.iter()) {
1389            assert_ne!(edge_cut.id(), cloned_edge_cut.id());
1390            assert_ne!(edge_cut.edge_id(), cloned_edge_cut.edge_id());
1391            assert_eq!(edge_cut.tag(), cloned_edge_cut.tag());
1392        }
1393
1394        ctx.close().await;
1395    }
1396
1397    // Ensure the clone function returns a solid with different ids for all the internal paths and
1398    // references.
1399    // WITH TAGS AND EDGE CUTS.
1400    #[tokio::test(flavor = "multi_thread")]
1401    async fn kcl_test_clone_solid_with_edge_cuts() {
1402        let code = r#"cube = startSketchOn(XY)
1403    |> startProfile(at = [0,0]) // tag this one
1404    |> line(end = [0, 10], tag = $tag02)
1405    |> line(end = [10, 0], tag = $tag03)
1406    |> line(end = [0, -10], tag = $tag04)
1407    |> close(tag = $tag05)
1408    |> extrude(length = 5) // TODO: Tag these
1409  |> fillet(
1410    radius = 2,
1411    tags = [
1412      getNextAdjacentEdge(tag02),
1413    ],
1414    tag = $fillet01,
1415  )
1416  |> fillet(
1417    radius = 2,
1418    tags = [
1419      getNextAdjacentEdge(tag04),
1420    ],
1421    tag = $fillet02,
1422  )
1423  |> chamfer(
1424    length = 2,
1425    tags = [
1426      getNextAdjacentEdge(tag03),
1427    ],
1428    tag = $chamfer01,
1429  )
1430  |> chamfer(
1431    length = 2,
1432    tags = [
1433      getNextAdjacentEdge(tag05),
1434    ],
1435    tag = $chamfer02,
1436  )
1437
1438clonedCube = clone(cube)
1439"#;
1440        let ctx = crate::test_server::new_context(true, None, true).await.unwrap();
1441        let program = crate::Program::parse_no_errs(code).unwrap();
1442
1443        // Execute the program.
1444        let result = ctx.run_with_caching(program.clone()).await.unwrap();
1445        let cube = result.variables.get("cube").unwrap();
1446        let cloned_cube = result.variables.get("clonedCube").unwrap();
1447
1448        assert_ne!(cube, cloned_cube);
1449
1450        let KclValueView::Solid { value: cube } = cube else {
1451            panic!("Expected a solid, got: {cube:?}");
1452        };
1453        let KclValueView::Solid { value: cloned_cube } = cloned_cube else {
1454            panic!("Expected a solid, got: {cloned_cube:?}");
1455        };
1456        let cube_sketch = cube.sketch().expect("Expected cube to have a sketch");
1457        let cloned_cube_sketch = cloned_cube.sketch().expect("Expected cloned cube to have a sketch");
1458
1459        assert_ne!(cube.id, cloned_cube.id);
1460        assert_ne!(cube_sketch.id, cloned_cube_sketch.id);
1461        assert_ne!(cube_sketch.original_id, cloned_cube_sketch.original_id);
1462        assert_ne!(cube.artifact_id, cloned_cube.artifact_id);
1463        assert_ne!(cube_sketch.artifact_id, cloned_cube_sketch.artifact_id);
1464
1465        assert_ne!(cloned_cube.artifact_id, cloned_cube.id.into());
1466
1467        for (value, cloned_value) in cube.value.iter().zip(cloned_cube.value.iter()) {
1468            assert_ne!(value.get_id(), cloned_value.get_id());
1469            assert_eq!(value.get_tag(), cloned_value.get_tag());
1470        }
1471
1472        for (edge_cut, cloned_edge_cut) in cube.edge_cuts.iter().zip(cloned_cube.edge_cuts.iter()) {
1473            assert_ne!(edge_cut.id(), cloned_edge_cut.id());
1474            assert_ne!(edge_cut.edge_id(), cloned_edge_cut.edge_id());
1475            assert_eq!(edge_cut.tag(), cloned_edge_cut.tag());
1476        }
1477
1478        ctx.close().await;
1479    }
1480
1481    // KCL 3.0 copy of kcl_test_clone_solid_with_edge_cuts. Edge cuts are sent
1482    // to the engine immediately, so every adjacent edge is looked up before
1483    // the first fillet consumes any of them.
1484    #[tokio::test(flavor = "multi_thread")]
1485    async fn kcl_test_clone_solid_with_edge_cuts_v3() {
1486        let code = r#"@settings(kclVersion = "3.0-preview")
1487
1488baseCube = startSketchOn(XY)
1489    |> startProfile(at = [0,0]) // tag this one
1490    |> line(end = [0, 10], tag = $tag02)
1491    |> line(end = [10, 0], tag = $tag03)
1492    |> line(end = [0, -10], tag = $tag04)
1493    |> close(tag = $tag05)
1494    |> extrude(length = 5) // TODO: Tag these
1495
1496tag02NextAdjacentEdge = getNextAdjacentEdge(tag02)
1497tag03NextAdjacentEdge = getNextAdjacentEdge(tag03)
1498tag04NextAdjacentEdge = getNextAdjacentEdge(tag04)
1499tag05NextAdjacentEdge = getNextAdjacentEdge(tag05)
1500
1501cube = baseCube
1502  |> fillet(
1503    radius = 2,
1504    tags = [
1505      tag02NextAdjacentEdge,
1506    ],
1507    tag = $fillet01,
1508  )
1509  |> fillet(
1510    radius = 2,
1511    tags = [
1512      tag04NextAdjacentEdge,
1513    ],
1514    tag = $fillet02,
1515  )
1516  |> chamfer(
1517    length = 2,
1518    tags = [
1519      tag03NextAdjacentEdge,
1520    ],
1521    tag = $chamfer01,
1522  )
1523  |> chamfer(
1524    length = 2,
1525    tags = [
1526      tag05NextAdjacentEdge,
1527    ],
1528    tag = $chamfer02,
1529  )
1530
1531clonedCube = clone(cube)
1532"#;
1533        let ctx = crate::test_server::new_context(true, None, true).await.unwrap();
1534        let program = crate::Program::parse_no_errs(code).unwrap();
1535
1536        // Execute the program.
1537        let result = ctx.run_with_caching(program.clone()).await.unwrap();
1538        let cube = result.variables.get("cube").unwrap();
1539        let cloned_cube = result.variables.get("clonedCube").unwrap();
1540
1541        assert_ne!(cube, cloned_cube);
1542
1543        let KclValueView::Solid { value: cube } = cube else {
1544            panic!("Expected a solid, got: {cube:?}");
1545        };
1546        let KclValueView::Solid { value: cloned_cube } = cloned_cube else {
1547            panic!("Expected a solid, got: {cloned_cube:?}");
1548        };
1549        let cube_sketch = cube.sketch().expect("Expected cube to have a sketch");
1550        let cloned_cube_sketch = cloned_cube.sketch().expect("Expected cloned cube to have a sketch");
1551
1552        assert_ne!(cube.id, cloned_cube.id);
1553        assert_ne!(cube_sketch.id, cloned_cube_sketch.id);
1554        assert_ne!(cube_sketch.original_id, cloned_cube_sketch.original_id);
1555        assert_ne!(cube.artifact_id, cloned_cube.artifact_id);
1556        assert_ne!(cube_sketch.artifact_id, cloned_cube_sketch.artifact_id);
1557
1558        assert_ne!(cloned_cube.artifact_id, cloned_cube.id.into());
1559
1560        for (value, cloned_value) in cube.value.iter().zip(cloned_cube.value.iter()) {
1561            assert_ne!(value.get_id(), cloned_value.get_id());
1562            assert_eq!(value.get_tag(), cloned_value.get_tag());
1563        }
1564
1565        for (edge_cut, cloned_edge_cut) in cube.edge_cuts.iter().zip(cloned_cube.edge_cuts.iter()) {
1566            assert_ne!(edge_cut.id(), cloned_edge_cut.id());
1567            assert_ne!(edge_cut.edge_id(), cloned_edge_cut.edge_id());
1568            assert_eq!(edge_cut.tag(), cloned_edge_cut.tag());
1569        }
1570
1571        ctx.close().await;
1572    }
1573}