John Smith
john@example.com
import toast from 'react-hot-toast'
import { Mesh, Vector2, Vector3 } from 'three'
import { assign, fromPromise, setup } from 'xstate'
import type { Node } from '@rust/kcl-lib/bindings/Node'
import { deleteSegment } from '@src/clientSideScene/deleteSegment'
import {
orthoScale,
quaternionFromUpNForward,
} from '@src/clientSideScene/helpers'
import type { Setting } from '@src/lib/settings/initialSettings'
import type { CameraProjectionType } from '@rust/kcl-lib/bindings/CameraProjectionType'
import { DRAFT_DASHED_LINE } from '@src/clientSideScene/sceneConstants'
import { DRAFT_POINT } from '@src/clientSideScene/sceneUtils'
import { createProfileStartHandle } from '@src/clientSideScene/segments'
import type { MachineManager } from '@src/components/MachineManagerProvider'
import type { ModelingMachineContext } from '@src/components/ModelingMachineProvider'
import type { SidebarType } from '@src/components/ModelingSidebar/ModelingPanes'
applyConstraintEqualAngle,
equalAngleInfo,
} from '@src/components/Toolbar/EqualAngle'
applyConstraintEqualLength,
setEqualLengthInfo,
} from '@src/components/Toolbar/EqualLength'
applyConstraintHorzVert,
horzVertInfo,
} from '@src/components/Toolbar/HorzVert'
import { intersectInfo } from '@src/components/Toolbar/Intersect'
applyRemoveConstrainingValues,
removeConstrainingValuesInfo,
} from '@src/components/Toolbar/RemoveConstrainingValues'
absDistanceInfo,
applyConstraintAxisAlign,
} from '@src/components/Toolbar/SetAbsDistance'
import { angleBetweenInfo } from '@src/components/Toolbar/SetAngleBetween'
applyConstraintHorzVertAlign,
horzVertDistanceInfo,
} from '@src/components/Toolbar/SetHorzVertDistance'
import { angleLengthInfo } from '@src/components/Toolbar/angleLengthInfo'
import { createLiteral, createLocalName } from '@src/lang/create'
import { updateModelingState } from '@src/lang/modelingWorkflows'
addClone,
addHelix,
addOffsetPlane,
addShell,
insertNamedConstant,
insertVariableAndOffsetPathToNode,
replaceValueAtNodePath,
} from '@src/lang/modifyAst'
import type {
ChamferParameters,
FilletParameters,
} from '@src/lang/modifyAst/addEdgeTreatment'
EdgeTreatmentType,
modifyAstWithEdgeTreatmentAndTag,
editEdgeTreatment,
getPathToExtrudeForSegmentSelection,
mutateAstWithTagForSketchSegment,
addExtrude,
addLoft,
addRevolve,
addSweep,
getAxisExpressionAndIndex,
} from '@src/lang/modifyAst/addSweep'
applyIntersectFromTargetOperatorSelections,
applySubtractFromTargetOperatorSelections,
applyUnionFromTargetOperatorSelections,
} from '@src/lang/modifyAst/boolean'
deleteSelectionPromise,
deletionErrorMessage,
} from '@src/lang/modifyAst/deleteSelection'
import { setAppearance } from '@src/lang/modifyAst/setAppearance'
setTranslate,
setRotate,
insertExpressionNode,
retrievePathToNodeFromTransformSelection,
} from '@src/lang/modifyAst/setTransform'
getNodeFromPath,
findPipesWithImportAlias,
findImportNodeAndAlias,
isNodeSafeToReplacePath,
stringifyPathToNode,
updatePathToNodesAfterEdit,
valueOrVariable,
artifactIsPlaneWithPaths,
isCursorInFunctionDefinition,
} from '@src/lang/queryAst'
getFaceCodeRef,
getPathsFromArtifact,
getPathsFromPlaneArtifact,
getPlaneFromArtifact,
} from '@src/lang/std/artifactGraph'
import type { Coords2d } from '@src/lang/std/sketch'
Artifact,
CallExpressionKw,
Expr,
KclValue,
Literal,
Name,
PathToNode,
PipeExpression,
Program,
VariableDeclaration,
VariableDeclarator,
} from '@src/lang/wasm'
import { parse, recast, resultIsOk, sketchFromKclValue } from '@src/lang/wasm'
import type { ModelingCommandSchema } from '@src/lib/commandBarConfigs/modelingCommandConfig'
import type { KclCommandValue } from '@src/lib/commandTypes'
import { EXECUTION_TYPE_REAL } from '@src/lib/constants'
import type { DefaultPlaneStr } from '@src/lib/planes'
Axis,
DefaultPlaneSelection,
Selection,
Selections,
} from '@src/lib/selections'
import { handleSelectionBatch, updateSelections } from '@src/lib/selections'
codeManager,
editorManager,
engineCommandManager,
kclManager,
sceneEntitiesManager,
sceneInfra,
} from '@src/lib/singletons'
import type { ToolbarModeName } from '@src/lib/toolbar'
import { err, reportRejection, trap } from '@src/lib/trap'
import { uuidv4 } from '@src/lib/utils'
import type { ImportStatement } from '@rust/kcl-lib/bindings/ImportStatement'
import { isDesktop } from '@src/lib/isDesktop'
crossProduct,
isCursorInSketchCommandRange,
updateSketchDetailsNodePaths,
} from '@src/lang/util'
import { kclEditorActor } from '@src/machines/kclEditorMachine'
import type { Plane } from '@rust/kcl-lib/bindings/Plane'
import type { Point3d } from '@rust/kcl-lib/bindings/ModelingCmd'
import { getNodePathFromSourceRange } from '@src/lang/queryAstNodePathUtils'
import { letEngineAnimateAndSyncCamAfter } from '@src/clientSideScene/CameraControls'
export type SetSelections =
| {
selectionType: 'singleCodeCursor'
selection?: Selection
scrollIntoView?: boolean
}
selectionType: 'axisSelection'
selection: Axis
selectionType: 'defaultPlaneSelection'
selection: DefaultPlaneSelection
selectionType: 'completeSelection'
selection: Selections
updatedSketchEntryNodePath?: PathToNode
updatedSketchNodePaths?: PathToNode[]
updatedPlaneNodePath?: PathToNode
selectionType: 'mirrorCodeMirrorSelections'
export type MouseState =
type: 'idle'
type: 'isHovering'
on: any
type: 'isDragging'
type: 'timeoutEnd'
pathToNodeString: string
export interface SketchDetails {
// there is no artifactGraph in sketch mode, so this is only used as vital information when entering sketch mode
// or on full/nonMock execution in sketch mode (manual code edit) as the entry point, as it will be accurate in these situations
sketchEntryNodePath: PathToNode
sketchNodePaths: PathToNode[]
planeNodePath: PathToNode
zAxis: [number, number, number]
yAxis: [number, number, number]
origin: [number, number, number]
// face id or plane id, both are strings
animateTargetId?: string
// this is the expression that was added when as sketch tool was used but not completed
// i.e first click for the center of the circle, but not the second click for the radius
// we added a circle to editor, but they bailed out early so we should remove it, set to -1 to ignore
expressionIndexToDelete?: number
export interface SketchDetailsUpdate {
updatedEntryNodePath: PathToNode
updatedSketchNodePaths: PathToNode[]
// see comment in SketchDetails
expressionIndexToDelete: number
export interface SegmentOverlay {
windowCoords: Coords2d
angle: number
group: any
pathToNode: PathToNode
visible: boolean
hasThreeDotMenu: boolean
filterValue?: string
export interface SegmentOverlays {
[pathToNodeString: string]: SegmentOverlay[]
export interface EdgeCutInfo {
type: 'edgeCut'
tagName: string
subType: 'base' | 'opposite' | 'adjacent'
export interface CapInfo {
type: 'cap'
subType: 'start' | 'end'
export type ExtrudeFacePlane = {
type: 'extrudeFace'
position: [number, number, number]
sketchPathToNode: PathToNode
extrudePathToNode: PathToNode
faceInfo:
type: 'wall'
| CapInfo
| EdgeCutInfo
faceId: string
export type DefaultPlane = {
type: 'defaultPlane'
plane: DefaultPlaneStr
planeId: string
export type OffsetPlane = {
type: 'offsetPlane'
export type SegmentOverlayPayload =
type: 'set-one'
seg: SegmentOverlay[]
type: 'delete-one'
| { type: 'clear' }
type: 'set-many'
overlays: SegmentOverlays
export interface Store {
videoElement?: HTMLVideoElement
openPanes: SidebarType[]
cameraProjection?: Setting<CameraProjectionType>
export type SketchTool =
| 'line'
| 'tangentialArc'
| 'rectangle'
| 'center rectangle'
| 'circle'
| 'circleThreePoint'
| 'arc'
| 'arcThreePoint'
| 'none'
export type ModelingMachineEvent =
type: 'Enter sketch'
data?: {
forceNewSketch?: boolean
| { type: 'Sketch On Face' }
type: 'Select sketch plane'
data: DefaultPlane | ExtrudeFacePlane | OffsetPlane
type: 'Set selection'
data: SetSelections
type: 'Delete selection'
| { type: 'Sketch no face' }
| { type: 'Cancel'; cleanup?: () => void }
type: 'Add start point' | 'Continue existing profile'
data: {
| { type: 'Close sketch' }
| { type: 'Make segment horizontal' }
| { type: 'Make segment vertical' }
| { type: 'Constrain horizontal distance' }
| { type: 'Constrain ABS X' }
| { type: 'Constrain ABS Y' }
| { type: 'Constrain vertical distance' }
| { type: 'Constrain angle' }
| { type: 'Constrain perpendicular distance' }
| { type: 'Constrain horizontally align' }
| { type: 'Constrain vertically align' }
| { type: 'Constrain snap to X' }
| { type: 'Constrain snap to Y' }
type: 'Constrain length'
data: ModelingCommandSchema['Constrain length']
| { type: 'Constrain equal length' }
| { type: 'Constrain parallel' }
| { type: 'Constrain remove constraints'; data?: PathToNode }
type: 'event.parameter.create'
data: ModelingCommandSchema['event.parameter.create']
type: 'event.parameter.edit'
data: ModelingCommandSchema['event.parameter.edit']
| { type: 'Export'; data: ModelingCommandSchema['Export'] }
type: 'Boolean Subtract'
data: ModelingCommandSchema['Boolean Subtract']
type: 'Boolean Union'
data: ModelingCommandSchema['Boolean Union']
type: 'Boolean Intersect'
data: ModelingCommandSchema['Boolean Intersect']
| { type: 'Make'; data: ModelingCommandSchema['Make'] }
| { type: 'Extrude'; data?: ModelingCommandSchema['Extrude'] }
| { type: 'Sweep'; data?: ModelingCommandSchema['Sweep'] }
| { type: 'Loft'; data?: ModelingCommandSchema['Loft'] }
| { type: 'Shell'; data?: ModelingCommandSchema['Shell'] }
| { type: 'Revolve'; data?: ModelingCommandSchema['Revolve'] }
| { type: 'Fillet'; data?: ModelingCommandSchema['Fillet'] }
| { type: 'Chamfer'; data?: ModelingCommandSchema['Chamfer'] }
| { type: 'Offset plane'; data: ModelingCommandSchema['Offset plane'] }
| { type: 'Helix'; data: ModelingCommandSchema['Helix'] }
| { type: 'Prompt-to-edit'; data: ModelingCommandSchema['Prompt-to-edit'] }
data: ModelingCommandSchema['Delete selection']
| { type: 'Appearance'; data: ModelingCommandSchema['Appearance'] }
| { type: 'Translate'; data: ModelingCommandSchema['Translate'] }
| { type: 'Rotate'; data: ModelingCommandSchema['Rotate'] }
| { type: 'Clone'; data: ModelingCommandSchema['Clone'] }
type:
| 'Add circle origin'
| 'Add circle center'
| 'Add center rectangle origin'
| 'click in scene'
| 'Add first point'
data: [x: number, y: number]
type: 'Add second point'
p1: [x: number, y: number]
p2: [x: number, y: number]
type: 'xstate.done.actor.animate-to-face'
output: SketchDetails
| { type: 'xstate.done.actor.animate-to-sketch'; output: SketchDetails }
| { type: `xstate.done.actor.do-constrain${string}`; output: SetSelections }
| 'xstate.done.actor.set-up-draft-circle'
| 'xstate.done.actor.set-up-draft-rectangle'
| 'xstate.done.actor.set-up-draft-center-rectangle'
| 'xstate.done.actor.set-up-draft-circle-three-point'
| 'xstate.done.actor.set-up-draft-arc'
| 'xstate.done.actor.set-up-draft-arc-three-point'
| 'xstate.done.actor.split-sketch-pipe-if-needed'
| 'xstate.done.actor.actor-circle-three-point'
| 'xstate.done.actor.reeval-node-paths'
output: SketchDetailsUpdate
type: 'xstate.done.actor.setup-client-side-sketch-segments9'
| { type: 'Set mouse state'; data: MouseState }
| { type: 'Set context'; data: Partial<Store> }
type: 'Set Segment Overlays'
data: SegmentOverlayPayload
type: 'Center camera on selection'
type: 'Delete segment'
data: PathToNode
type: 'code edit during sketch'
type: 'Constrain with named value'
data: ModelingCommandSchema['Constrain with named value']
type: 'change tool'
tool: SketchTool
| { type: 'Finish rectangle' }
| { type: 'Finish center rectangle' }
| { type: 'Finish circle' }
| { type: 'Finish circle three point' }
| { type: 'Finish arc' }
| { type: 'Artifact graph populated' }
| { type: 'Artifact graph emptied' }
| { type: 'Artifact graph initialized' }
type: 'Toggle default plane visibility'
planeKey: keyof PlaneVisibilityMap
type: 'Save default plane visibility'
type: 'Restore default plane visibility'
export type MoveDesc = { line: number; snippet: string }
export const PERSIST_MODELING_CONTEXT = 'persistModelingContext'
interface PersistedModelingContext {
openPanes: Store['openPanes']
type PersistedKeys = keyof PersistedModelingContext
export const PersistedValues: PersistedKeys[] = ['openPanes']
export const getPersistedContext = (): Partial<PersistedModelingContext> => {
const c = (typeof window !== 'undefined' &&
JSON.parse(localStorage.getItem(PERSIST_MODELING_CONTEXT) || '{}')) || {
openPanes: isDesktop()
? (['feature-tree', 'code', 'files'] satisfies Store['openPanes'])
: (['feature-tree', 'code'] satisfies Store['openPanes']),
return c
export interface ModelingMachineContext {
currentMode: ToolbarModeName
currentTool: SketchTool
toastId: string | null
machineManager: MachineManager
selection: string[]
selectionRanges: Selections
sketchDetails: SketchDetails | null
sketchPlaneId: string
sketchEnginePathId: string
moveDescs: MoveDesc[]
mouseState: MouseState
segmentOverlays: SegmentOverlays
segmentHoverMap: { [pathToNodeString: string]: number }
store: Store
defaultPlaneVisibility: PlaneVisibilityMap
savedDefaultPlaneVisibility: PlaneVisibilityMap
planesInitialized: boolean
export type PlaneVisibilityMap = {
xy: boolean
xz: boolean
yz: boolean
export const modelingMachineDefaultContext: ModelingMachineContext = {
currentMode: 'modeling',
currentTool: 'none',
toastId: null,
machineManager: {
machines: [],
machineApiIp: null,
currentMachine: null,
setCurrentMachine: () => {},
noMachinesReason: () => undefined,
},
selection: [],
selectionRanges: {
otherSelections: [],
graphSelections: [],
sketchDetails: {
sketchEntryNodePath: [],
planeNodePath: [],
sketchNodePaths: [],
zAxis: [0, 0, 1],
yAxis: [0, 1, 0],
origin: [0, 0, 0],
sketchPlaneId: '',
sketchEnginePathId: '',
moveDescs: [],
mouseState: { type: 'idle' },
segmentOverlays: {},
segmentHoverMap: {},
store: {
openPanes: getPersistedContext().openPanes || ['code'],
defaultPlaneVisibility: {
xy: true,
xz: true,
yz: true,
// Manually toggled plane visibility is saved and restored when going back to modeling mode
savedDefaultPlaneVisibility: {
planesInitialized: false,
const NO_INPUT_PROVIDED_MESSAGE = 'No input provided'
export const modelingMachine = setup({
types: {
context: {} as ModelingMachineContext,
events: {} as ModelingMachineEvent,
input: {} as ModelingMachineContext,
guards: {
'Selection is on face': ({
context: { selectionRanges },
event,
}): boolean => {
if (event.type !== 'Enter sketch') return false
if (event.data?.forceNewSketch) return false
if (artifactIsPlaneWithPaths(selectionRanges)) {
return true
} else if (selectionRanges.graphSelections[0]?.artifact) {
// See if the selection is "close enough" to be coerced to the plane later
const maybePlane = getPlaneFromArtifact(
selectionRanges.graphSelections[0].artifact,
kclManager.artifactGraph
)
return !err(maybePlane)
if (
isCursorInFunctionDefinition(
kclManager.ast,
selectionRanges.graphSelections[0]
) {
return false
return !!isCursorInSketchCommandRange(
kclManager.artifactGraph,
selectionRanges
'Has exportable geometry': () => false,
'has valid selection for deletion': () => false,
'is-error-free': (): boolean => {
return kclManager.errors.length === 0 && !kclManager.hasErrors()
'no kcl errors': () => {
return !kclManager.hasErrors()
'is editing existing sketch': ({ context: { sketchDetails } }) =>
isEditingExistingSketch({ sketchDetails }),
'Can make selection horizontal': ({ context: { selectionRanges } }) => {
const info = horzVertInfo(selectionRanges, 'horizontal')
if (err(info)) return false
return info.enabled
'Can make selection vertical': ({ context: { selectionRanges } }) => {
const info = horzVertInfo(selectionRanges, 'vertical')
'Can constrain horizontal distance': ({ context: { selectionRanges } }) => {
const info = horzVertDistanceInfo({
selectionRanges: selectionRanges,
constraint: 'setHorzDistance',
})
'Can constrain vertical distance': ({ context: { selectionRanges } }) => {
constraint: 'setVertDistance',
'Can constrain ABS X': ({ context: { selectionRanges } }) => {
const info = absDistanceInfo({
selectionRanges,
constraint: 'xAbs',
'Can constrain ABS Y': ({ context: { selectionRanges } }) => {
constraint: 'yAbs',
'Can constrain angle': ({ context: { selectionRanges } }) => {
const angleBetween = angleBetweenInfo({
if (err(angleBetween)) return false
const angleLength = angleLengthInfo({
angleOrLength: 'setAngle',
if (err(angleLength)) return false
return angleBetween.enabled || angleLength.enabled
'Can constrain length': ({ context: { selectionRanges } }) => {
return angleLength.enabled
'Can constrain perpendicular distance': ({
}) => {
const info = intersectInfo({ selectionRanges })
'Can constrain horizontally align': ({ context: { selectionRanges } }) => {
'Can constrain vertically align': ({ context: { selectionRanges } }) => {
'Can constrain snap to X': ({ context: { selectionRanges } }) => {
constraint: 'snapToXAxis',
'Can constrain snap to Y': ({ context: { selectionRanges } }) => {
constraint: 'snapToYAxis',
'Can constrain equal length': ({ context: { selectionRanges } }) => {
const info = setEqualLengthInfo({
'Can constrain parallel': ({ context: { selectionRanges } }) => {
const info = equalAngleInfo({
'Can constrain remove constraints': ({
if (event.type !== 'Constrain remove constraints') return false
const info = removeConstrainingValuesInfo({
pathToNodes: event.data && [event.data],
'Can convert to named value': ({ event }) => {
if (event.type !== 'Constrain with named value') return false
if (!event.data) return false
const ast = parse(recast(kclManager.ast))
if (err(ast) || !ast.program || ast.errors.length > 0) return false
const isSafeRetVal = isNodeSafeToReplacePath(
ast.program,
event.data.currentValue.pathToNode
if (err(isSafeRetVal)) return false
return isSafeRetVal.isSafe
'next is tangential arc': ({ context: { sketchDetails, currentTool } }) =>
currentTool === 'tangentialArc' &&
'next is rectangle': ({ context: { currentTool } }) =>
currentTool === 'rectangle',
'next is center rectangle': ({ context: { currentTool } }) =>
currentTool === 'center rectangle',
'next is circle': ({ context: { currentTool } }) =>
currentTool === 'circle',
'next is circle three point': ({ context: { currentTool } }) =>
currentTool === 'circleThreePoint',
'next is circle three point neo': ({ context: { currentTool } }) =>
'next is line': ({ context }) => context.currentTool === 'line',
'next is none': ({ context }) => context.currentTool === 'none',
'next is arc': ({ context }) => context.currentTool === 'arc',
'next is arc three point': ({ context }) =>
context.currentTool === 'arcThreePoint',
// end guards
actions: {
toastError: ({ event }) => {
if ('output' in event && event.output instanceof Error) {
toast.error(event.output.message)
} else if ('data' in event && event.data instanceof Error) {
toast.error(event.data.message)
} else if ('error' in event && event.error instanceof Error) {
toast.error(event.error.message)
'assign tool in context': assign({
currentTool: ({ event }) =>
event.type === 'change tool' ? event.data.tool || 'none' : 'none',
}),
'reset selections': assign({
selectionRanges: { graphSelections: [], otherSelections: [] },
'enter sketching mode': assign({ currentMode: 'sketching' }),
'enter modeling mode': assign({ currentMode: 'modeling' }),
'set sketchMetadata from pathToNode': assign(
({ context: { sketchDetails } }) => {
if (!sketchDetails?.sketchEntryNodePath || !sketchDetails) return {}
return {
...sketchDetails,
sketchEntryNodePath: sketchDetails.sketchEntryNodePath,
),
'hide default planes': assign({
defaultPlaneVisibility: () => {
// eslint-disable-next-line @typescript-eslint/no-floating-promises
kclManager.hidePlanes()
return { xy: false, xz: false, yz: false }
'reset sketch metadata': assign({
sketchDetails: null,
'reset camera position': () => {
engineCommandManager.sendSceneCommand({
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'default_camera_look_at',
center: { x: 0, y: 0, z: 0 },
vantage: { x: 0, y: -1250, z: 580 },
up: { x: 0, y: 0, z: 1 },
'set new sketch metadata': assign(({ event }) => {
event.type !== 'xstate.done.actor.animate-to-sketch' &&
event.type !== 'xstate.done.actor.animate-to-face'
return {}
sketchDetails: event.output,
'set up draft line': assign(({ context: { sketchDetails }, event }) => {
if (!sketchDetails) return {}
if (event.type !== 'Add start point') return {}
sceneEntitiesManager
.setupDraftSegment(
event.data.sketchEntryNodePath || sketchDetails.sketchEntryNodePath,
event.data.sketchNodePaths || sketchDetails.sketchNodePaths,
sketchDetails.planeNodePath,
sketchDetails.zAxis,
sketchDetails.yAxis,
sketchDetails.origin,
'line'
.then(() => {
return codeManager.updateEditorWithAstAndWriteToFile(kclManager.ast)
sketchEntryNodePath: event.data.sketchEntryNodePath,
sketchNodePaths: event.data.sketchNodePaths,
'set up draft arc': assign(({ context: { sketchDetails }, event }) => {
if (event.type !== 'Continue existing profile') return {}
'tangentialArc'
'listen for rectangle origin': ({ context: { sketchDetails } }) => {
if (!sketchDetails) return
const quaternion = quaternionFromUpNForward(
new Vector3(...sketchDetails.yAxis),
new Vector3(...sketchDetails.zAxis)
// Position the click raycast plane
sceneEntitiesManager.intersectionPlane.setRotationFromQuaternion(
quaternion
sceneEntitiesManager.intersectionPlane.position.copy(
new Vector3(...(sketchDetails?.origin || [0, 0, 0]))
sceneInfra.setCallbacks({
onClick: (args) => {
if (!args) return
if (args.mouseEvent.which !== 1) return
const twoD = args.intersectionPoint?.twoD
if (twoD) {
sceneInfra.modelingSend({
type: 'click in scene',
data: sceneEntitiesManager.getSnappedDragPoint(
twoD,
args.intersects,
args.mouseEvent
).snappedPoint,
} else {
console.error('No intersection point found')
'listen for center rectangle origin': ({ context: { sketchDetails } }) => {
type: 'Add center rectangle origin',
data: [twoD.x, twoD.y],
'listen for circle origin': ({ context: { sketchDetails } }) => {
const { intersectionPoint } = args
if (!intersectionPoint?.twoD) return
type: 'Add circle origin',
'listen for circle first point': ({ context: { sketchDetails } }) => {
type: 'Add first point',
'listen for circle second point': ({
context: { sketchDetails },
if (event.type !== 'Add first point') return
const dummy = new Mesh()
dummy.position.set(0, 0, 0)
const scale = sceneInfra.getClientSceneScaleFactor(dummy)
const position = new Vector3(event.data[0], event.data[1], 0)
position.applyQuaternion(quaternion)
const draftPoint = createProfileStartHandle({
isDraft: true,
from: event.data,
scale,
theme: sceneInfra._theme,
draftPoint.position.copy(position)
sceneInfra.scene.add(draftPoint)
type: 'Add second point',
p1: event.data,
p2: [twoD.x, twoD.y],
'update sketchDetails': assign(({ event, context }) => {
event.type !== 'xstate.done.actor.actor-circle-three-point' &&
event.type !== 'xstate.done.actor.set-up-draft-circle' &&
event.type !== 'xstate.done.actor.set-up-draft-arc' &&
event.type !== 'xstate.done.actor.set-up-draft-arc-three-point' &&
event.type !== 'xstate.done.actor.set-up-draft-circle-three-point' &&
event.type !== 'xstate.done.actor.set-up-draft-rectangle' &&
event.type !== 'xstate.done.actor.set-up-draft-center-rectangle' &&
event.type !== 'xstate.done.actor.split-sketch-pipe-if-needed' &&
event.type !== 'xstate.done.actor.reeval-node-paths'
if (!context.sketchDetails) return {}
...context.sketchDetails,
planeNodePath:
event.output.updatedPlaneNodePath ||
context.sketchDetails?.planeNodePath ||
[],
sketchEntryNodePath: event.output.updatedEntryNodePath,
sketchNodePaths: event.output.updatedSketchNodePaths,
expressionIndexToDelete: event.output.expressionIndexToDelete,
'update sketchDetails arc': assign(({ event, context }) => {
'show default planes': assign({
kclManager.showPlanes()
return { xy: true, xz: true, yz: true }
'show default planes if no errors': assign({
defaultPlaneVisibility: ({ context }) => {
if (!kclManager.hasErrors()) {
return { ...context.defaultPlaneVisibility }
'setup noPoints onClick listener': ({
context: { sketchDetails, currentTool },
sceneEntitiesManager.setupNoPointsListener({
sketchDetails,
currentTool,
afterClick: (_, data) =>
sceneInfra.modelingSend(
currentTool === 'tangentialArc'
? { type: 'Continue existing profile', data }
: currentTool === 'arc'
? { type: 'Add start point', data }
: { type: 'Add start point', data }
'add axis n grid': ({ context: { sketchDetails } }) => {
if (localStorage.getItem('disableAxis')) return
sceneEntitiesManager.createSketchAxis(
sketchDetails.origin
codeManager.updateEditorWithAstAndWriteToFile(kclManager.ast)
'reset client scene mouse handlers': () => {
// when not in sketch mode we don't need any mouse listeners
// (note the orbit controls are always active though)
sceneInfra.resetMouseListeners()
'clientToEngine cam sync direction': () => {
sceneInfra.camControls.syncDirection = 'clientToEngine'
/** TODO: this action is hiding unawaited asynchronous code */
'set selection filter to faces only': () => {
kclManager.setSelectionFilter(['face', 'object'])
'set selection filter to defaults': () => {
kclManager.defaultSelectionFilter()
'Delete segment': ({ context: { sketchDetails }, event }) => {
if (event.type !== 'Delete segment') return
if (!sketchDetails || !event.data) return
deleteSegment({
pathToNode: event.data,
}).then(() => {
'Set context': assign({
store: ({ context: { store }, event }) => {
if (event.type !== 'Set context') return store
if (!event.data) return store
const result = {
...store,
...event.data,
const persistedContext: Partial<PersistedModelingContext> = {}
for (const key of PersistedValues) {
persistedContext[key] = result[key]
if (typeof window !== 'undefined') {
window.localStorage.setItem(
PERSIST_MODELING_CONTEXT,
JSON.stringify(persistedContext)
return result
'remove draft entities': () => {
const draftPoint = sceneInfra.scene.getObjectByName(DRAFT_POINT)
if (draftPoint) {
sceneInfra.scene.remove(draftPoint)
const draftLine = sceneInfra.scene.getObjectByName(DRAFT_DASHED_LINE)
if (draftLine) {
sceneInfra.scene.remove(draftLine)
'add draft line': ({ event, context }) => {
event.type !== 'Add start point' &&
event.type !== 'xstate.done.actor.setup-client-side-sketch-segments9'
return
let sketchEntryNodePath: PathToNode | undefined
if (event.type === 'Add start point') {
sketchEntryNodePath = event.data?.sketchEntryNodePath
} else if (
event.type === 'xstate.done.actor.setup-client-side-sketch-segments9'
sketchEntryNodePath =
context.sketchDetails?.sketchNodePaths.slice(-1)[0]
if (!sketchEntryNodePath) return
const varDec = getNodeFromPath<VariableDeclaration>(
sketchEntryNodePath,
'VariableDeclaration'
if (err(varDec)) return
const varName = varDec.node.declaration.id.name
const sg = sketchFromKclValue(kclManager.variables[varName], varName)
if (err(sg)) return
const lastSegment = sg.paths[sg.paths.length - 1] || sg.start
const to = lastSegment.to
const { group, updater } = sceneEntitiesManager.drawDashedLine({
from: to,
to: [to[0] + 0.001, to[1] + 0.001],
sceneInfra.scene.add(group)
const orthoFactor = orthoScale(sceneInfra.camControls.camera)
onMove: (args) => {
if (!context.sketchDetails) return
const { snappedPoint, isSnapped } =
sceneEntitiesManager.getSnappedDragPoint(
intersectionPoint.twoD,
if (isSnapped) {
sceneEntitiesManager.positionDraftPoint({
snappedPoint: new Vector2(...snappedPoint),
origin: context.sketchDetails.origin,
yAxis: context.sketchDetails.yAxis,
zAxis: context.sketchDetails.zAxis,
sceneEntitiesManager.removeDraftPoint()
updater(
group,
[intersectionPoint.twoD.x, intersectionPoint.twoD.y],
orthoFactor
'reset deleteIndex': assign(({ context: { sketchDetails } }) => {
expressionIndexToDelete: -1,
'enable copilot': () => {},
'disable copilot': () => {},
'Set selection': assign(
({ context: { selectionRanges, sketchDetails }, event }) => {
// this was needed for ts after adding 'Set selection' action to on done modal events
const setSelections =
('data' in event &&
event.data &&
'selectionType' in event.data &&
event.data) ||
('output' in event &&
event.output &&
'selectionType' in event.output &&
event.output) ||
null
if (!setSelections) return {}
let selections: Selections = {
if (setSelections.selectionType === 'singleCodeCursor') {
if (!setSelections.selection && editorManager.isShiftDown) {
// if the user is holding shift, but they didn't select anything
// don't nuke their other selections (frustrating to have one bad click ruin your
// whole selection)
selections = {
graphSelections: selectionRanges.graphSelections,
otherSelections: selectionRanges.otherSelections,
} else if (!setSelections.selection && !editorManager.isShiftDown) {
} else if (setSelections.selection && !editorManager.isShiftDown) {
graphSelections: [setSelections.selection],
} else if (setSelections.selection && editorManager.isShiftDown) {
// selecting and deselecting multiple objects
/**
* There are two scenarios:
* 1. General case:
* When selecting and deselecting edges,
* faces or segment (during sketch edit)
* we use its artifact ID to identify the selection
* 2. Initial sketch setup:
* The artifact is not yet created
* so we use the codeRef.range
*/
let updatedSelections: typeof selectionRanges.graphSelections
// 1. General case: Artifact exists, use its ID
if (setSelections.selection.artifact?.id) {
// check if already selected
const alreadySelected = selectionRanges.graphSelections.some(
(selection) =>
selection.artifact?.id ===
setSelections.selection?.artifact?.id
if (alreadySelected && setSelections.selection?.artifact?.id) {
// remove it
updatedSelections = selectionRanges.graphSelections.filter(
selection.artifact?.id !==
// add it
updatedSelections = [
...selectionRanges.graphSelections,
setSelections.selection,
]
// 2. Initial sketch setup: Artifact not yet created – use codeRef.range
const selectionRange = JSON.stringify(
setSelections.selection?.codeRef?.range
(selection) => {
const existingRange = JSON.stringify(selection.codeRef?.range)
return existingRange === selectionRange
if (alreadySelected && setSelections.selection?.codeRef?.range) {
JSON.stringify(selection.codeRef?.range) !== selectionRange
graphSelections: updatedSelections,
const { engineEvents, codeMirrorSelection, updateSceneObjectColors } =
handleSelectionBatch({
selections,
if (codeMirrorSelection) {
kclEditorActor.send({
type: 'setLastSelectionEvent',
codeMirrorSelection,
scrollIntoView: setSelections.scrollIntoView ?? false,
// If there are engine commands that need sent off, send them
// TODO: This should be handled outside of an action as its own
// actor, so that the system state is more controlled.
engineEvents &&
engineEvents.forEach((event) => {
engineCommandManager
.sendSceneCommand(event)
.catch(reportRejection)
updateSceneObjectColors()
selectionRanges: selections,
if (setSelections.selectionType === 'mirrorCodeMirrorSelections') {
selectionRanges: setSelections.selection,
setSelections.selectionType === 'axisSelection' ||
setSelections.selectionType === 'defaultPlaneSelection'
if (editorManager.isShiftDown) {
otherSelections: [setSelections.selection],
if (setSelections.selectionType === 'completeSelection') {
const codeMirrorSelection = editorManager.createEditorSelection(
setSelections.selection
scrollIntoView: false,
if (!sketchDetails)
sketchEntryNodePath:
setSelections.updatedSketchEntryNodePath ||
sketchDetails?.sketchEntryNodePath ||
sketchNodePaths:
setSelections.updatedSketchNodePaths ||
sketchDetails?.sketchNodePaths ||
setSelections.updatedPlaneNodePath ||
sketchDetails?.planeNodePath ||
'Set mouse state': () => {},
'Set Segment Overlays': () => {},
'Center camera on selection': () => {},
'Submit to Text-to-CAD API': () => {},
'Set sketchDetails': () => {},
'debug-action': (data) => {
console.log('re-eval debug-action', data)
'Toggle default plane visibility': assign(({ context, event }) => {
if (event.type !== 'Toggle default plane visibility') return {}
const currentVisibilityMap = context.defaultPlaneVisibility
const currentVisibility = currentVisibilityMap[event.planeKey]
const newVisibility = !currentVisibility
kclManager.engineCommandManager
.setPlaneHidden(event.planeId, !newVisibility)
...currentVisibilityMap,
[event.planeKey]: newVisibility,
// Saves the default plane visibility to be able to restore when going back from sketch mode
'Save default plane visibility': assign(({ context, event }) => {
...context.defaultPlaneVisibility,
'Restore default plane visibility': assign(({ context }) => {
for (const planeKey of Object.keys(
context.savedDefaultPlaneVisibility
) as (keyof PlaneVisibilityMap)[]) {
kclManager.setPlaneVisibilityByKey(
planeKey,
context.savedDefaultPlaneVisibility[planeKey]
...context.savedDefaultPlaneVisibility,
'show sketch error toast': assign(() => {
// toast message that stays open until closed programmatically
const toastId = toast.error(
"Error in kcl script, sketch cannot be drawn until it's fixed",
{ duration: Infinity }
toastId,
'remove sketch error toast': assign(({ context }) => {
if (context.toastId) {
toast.dismiss(context.toastId)
return { toastId: null }
// end actions
actors: {
sketchExit: fromPromise(
async (args: { input: { context: { store: Store } } }) => {
const store = args.input.context.store
// When cancelling the sketch mode we should disable sketch mode within the engine.
await engineCommandManager.sendSceneCommand({
cmd: { type: 'sketch_mode_disable' },
if (store.cameraProjection?.current === 'perspective') {
await sceneInfra.camControls.snapToPerspectiveBeforeHandingBackControlToEngine()
sceneInfra.camControls.syncDirection = 'engineToClient'
// TODO: Re-evaluate if this pause/play logic is needed.
store.videoElement?.pause()
await kclManager
.executeCode()
if (engineCommandManager.idleMode) return
store.videoElement?.play().catch((e: Error) => {
console.warn('Video playing was prevented', e)
sceneEntitiesManager.tearDownSketch({ removeAxis: false })
sceneEntitiesManager.removeSketchGrid()
sceneEntitiesManager.resetOverlays()
/* Below are all the do-constrain sketch actors,
* which aren't using updateModelingState and don't have the 'no kcl errors' guard yet */
'do-constrain-remove-constraint': fromPromise(
async ({
input: { selectionRanges, sketchDetails, data },
}: {
input: Pick<
ModelingMachineContext,
'selectionRanges' | 'sketchDetails'
> & { data?: PathToNode }
const constraint = applyRemoveConstrainingValues({
pathToNodes: data && [data],
if (trap(constraint)) return
const { pathToNodeMap } = constraint
let updatedAst = await sceneEntitiesManager.updateAstAndRejigSketch(
pathToNodeMap[0],
sketchDetails.sketchNodePaths,
constraint.modifiedAst,
if (trap(updatedAst, { suppress: true })) return
if (!updatedAst) return
await codeManager.updateEditorWithAstAndWriteToFile(updatedAst.newAst)
selectionType: 'completeSelection',
selection: updateSelections(
pathToNodeMap,
updatedAst.newAst
'do-constrain-horizontally': fromPromise(
input: { selectionRanges, sketchDetails },
input: Pick<ModelingMachineContext, 'selectionRanges' | 'sketchDetails'>
const constraint = applyConstraintHorzVert(
'horizontal',
kclManager.variables
if (trap(constraint)) return false
const { modifiedAst, pathToNodeMap } = constraint
const updatedAst = await sceneEntitiesManager.updateAstAndRejigSketch(
sketchDetails.sketchEntryNodePath,
modifiedAst,
'do-constrain-vertically': fromPromise(
'vertical',
sketchDetails.sketchEntryNodePath || [],
'do-constrain-horizontally-align': fromPromise(
const constraint = applyConstraintHorzVertAlign({
sketchDetails?.sketchEntryNodePath || [],
const updatedSelectionRanges = updateSelections(
selection: updatedSelectionRanges,
'do-constrain-vertically-align': fromPromise(
'do-constrain-snap-to-x': fromPromise(
const constraint = applyConstraintAxisAlign({
if (err(constraint)) return false
'do-constrain-snap-to-y': fromPromise(
'do-constrain-parallel': fromPromise(
const constraint = applyConstraintEqualAngle({
if (!sketchDetails) {
trap(new Error('No sketch details'))
const recastAst = parse(recast(modifiedAst))
if (err(recastAst) || !resultIsOk(recastAst)) return
recastAst.program,
'do-constrain-equal-length': fromPromise(
const constraint = applyConstraintEqualLength({
/* Below are actors being defined in src/components/ModelingMachineProvider.tsx
'Get vertical info': fromPromise(
async (_: {
return {} as SetSelections
'Get ABS X info': fromPromise(
'Get ABS Y info': fromPromise(
'Get angle info': fromPromise(
'Get perpendicular distance info': fromPromise(
'AST-undo-startSketchOn': fromPromise(
async (_: { input: Pick<ModelingMachineContext, 'sketchDetails'> }) => {
return undefined
'animate-to-face': fromPromise(
async (_: { input?: ExtrudeFacePlane | DefaultPlane | OffsetPlane }) => {
return {} as ModelingMachineContext['sketchDetails']
'Get horizontal info': fromPromise(
input: Pick<ModelingMachineContext, 'sketchDetails' | 'selectionRanges'>
astConstrainLength: fromPromise(
'sketchDetails' | 'selectionRanges'
> & {
lengthValue?: KclCommandValue
'setup-client-side-sketch-segments': fromPromise(
input: { sketchDetails, selectionRanges },
input: {
if (!sketchDetails.sketchEntryNodePath?.length) return
await sceneEntitiesManager.setupSketch({
sketchEntryNodePath: sketchDetails?.sketchEntryNodePath || [],
sketchNodePaths: sketchDetails.sketchNodePaths,
forward: sketchDetails.zAxis,
up: sketchDetails.yAxis,
position: sketchDetails.origin,
maybeModdedAst: kclManager.ast,
sceneEntitiesManager.setupSketchIdleCallbacks({
planeNodePath: sketchDetails.planeNodePath,
// We will want to pass sketchTools here
// to add their interactions
// We will want to update the context with sketchTools.
// They'll be used for their .destroy() in tearDownSketch
'animate-to-sketch': fromPromise(
input: { selectionRanges },
}): Promise<ModelingMachineContext['sketchDetails']> => {
const artifact = selectionRanges.graphSelections[0].artifact
const plane = getPlaneFromArtifact(artifact, kclManager.artifactGraph)
if (err(plane)) return Promise.reject(plane)
// if the user selected a segment, make sure we enter the right sketch as there can be multiple on a plane
// but still works if the user selected a plane/face by defaulting to the first path
const mainPath =
artifact?.type === 'segment' || artifact?.type === 'solid2d'
? artifact?.pathId
: plane?.pathIds[0]
let sketch: KclValue | null = null
let planeVar: Plane | null = null
for (const variable of Object.values(kclManager.execState.variables)) {
// find programMemory that matches path artifact
variable?.type === 'Sketch' &&
variable.value.artifactId === mainPath
sketch = variable
break
// if the variable is an sweep, check if the underlying sketch matches the artifact
variable?.type === 'Solid' &&
variable.value.sketch.on.type === 'plane' &&
variable.value.sketch.artifactId === mainPath
sketch = {
type: 'Sketch',
value: variable.value.sketch,
if (variable?.type === 'Plane' && plane.id === variable.value.id) {
planeVar = variable.value
if (!sketch || sketch.type !== 'Sketch') {
if (artifact?.type !== 'plane')
return Promise.reject(new Error('No sketch'))
const planeCodeRef = getFaceCodeRef(artifact)
if (planeVar && planeCodeRef) {
const toTuple = (point: Point3d): [number, number, number] => [
point.x,
point.y,
point.z,
const planPath = getNodePathFromSourceRange(
planeCodeRef.range
await letEngineAnimateAndSyncCamAfter(
artifact.id
const normal = crossProduct(planeVar.xAxis, planeVar.yAxis)
planeNodePath: planPath,
zAxis: toTuple(normal),
yAxis: toTuple(planeVar.yAxis),
origin: toTuple(planeVar.origin),
const info = await sceneEntitiesManager.getSketchOrientationDetails(
sketch.value
info?.sketchDetails?.faceId || ''
const sketchArtifact = kclManager.artifactGraph.get(mainPath)
if (sketchArtifact?.type !== 'path')
return Promise.reject(new Error('No sketch artifact'))
const sketchPaths = getPathsFromArtifact({
artifact: kclManager.artifactGraph.get(plane.id),
sketchPathToNode: sketchArtifact?.codeRef?.pathToNode,
artifactGraph: kclManager.artifactGraph,
ast: kclManager.ast,
if (err(sketchPaths)) return Promise.reject(sketchPaths)
let codeRef = getFaceCodeRef(plane)
if (!codeRef) return Promise.reject(new Error('No plane codeRef'))
// codeRef.pathToNode is not always populated correctly
const planeNodePath = getNodePathFromSourceRange(
codeRef.range
sketchEntryNodePath: sketchArtifact.codeRef.pathToNode || [],
sketchNodePaths: sketchPaths,
planeNodePath,
zAxis: info.sketchDetails.zAxis || null,
yAxis: info.sketchDetails.yAxis || null,
origin: info.sketchDetails.origin.map(
(a) => a / sceneInfra._baseUnitMultiplier
) as [number, number, number],
animateTargetId: info?.sketchDetails?.faceId || '',
'Apply named value constraint': fromPromise(
input,
data?: ModelingCommandSchema['Constrain with named value']
}): Promise<SetSelections> => {
const { selectionRanges, sketchDetails, data } = input
return Promise.reject(new Error('No sketch details'))
if (!data) {
return Promise.reject(new Error('No data from command flow'))
let pResult = parse(recast(kclManager.ast))
if (trap(pResult) || !resultIsOk(pResult))
return Promise.reject(new Error('Unexpected compilation error'))
let parsed = pResult.program
let result: {
modifiedAst: Node<Program>
pathToReplaced: PathToNode | null
exprInsertIndex: number
} = {
modifiedAst: parsed,
pathToReplaced: null,
exprInsertIndex: -1,
// If the user provided a constant name,
// we need to insert the named constant
// and then replace the node with the constant's name.
if ('variableName' in data.namedValue) {
const astAfterReplacement = replaceValueAtNodePath({
ast: parsed,
pathToNode: data.currentValue.pathToNode,
newExpressionString: data.namedValue.variableName,
if (trap(astAfterReplacement)) {
return Promise.reject(astAfterReplacement)
const parseResultAfterInsertion = parse(
recast(
insertNamedConstant({
node: astAfterReplacement.modifiedAst,
newExpression: data.namedValue,
result.exprInsertIndex = data.namedValue.insertIndex
trap(parseResultAfterInsertion) ||
!resultIsOk(parseResultAfterInsertion)
return Promise.reject(parseResultAfterInsertion)
result = {
modifiedAst: parseResultAfterInsertion.program,
pathToReplaced: astAfterReplacement.pathToReplaced,
exprInsertIndex: result.exprInsertIndex,
} else if ('valueText' in data.namedValue) {
// If they didn't provide a constant name,
// just replace the node with the value.
newExpressionString: data.namedValue.valueText,
// The `replacer` function returns a pathToNode that assumes
// an identifier is also being inserted into the AST, creating an off-by-one error.
// This corrects that error, but TODO we should fix this upstream
// to avoid this kind of error in the future.
astAfterReplacement.pathToReplaced[1][0] =
(astAfterReplacement.pathToReplaced[1][0] as number) - 1
result = astAfterReplacement
pResult = parse(recast(result.modifiedAst))
parsed = pResult.program
if (trap(parsed)) return Promise.reject(parsed)
if (!result.pathToReplaced)
return Promise.reject(new Error('No path to replaced node'))
const {
updatedSketchEntryNodePath,
updatedSketchNodePaths,
updatedPlaneNodePath,
} = updateSketchDetailsNodePaths({
parsed,
if (err(updatedAst)) return Promise.reject(updatedAst)
const selection = updateSelections(
{ 0: result.pathToReplaced },
if (err(selection)) return Promise.reject(selection)
selection,
'set-up-draft-circle': fromPromise(
input: Pick<ModelingMachineContext, 'sketchDetails'> & {
return {} as SketchDetailsUpdate
'set-up-draft-circle-three-point': fromPromise(
data: { p1: [x: number, y: number]; p2: [x: number, y: number] }
'set-up-draft-rectangle': fromPromise(
'set-up-draft-center-rectangle': fromPromise(
'set-up-draft-arc': fromPromise(
'set-up-draft-arc-three-point': fromPromise(
'split-sketch-pipe-if-needed': fromPromise(
'submit-prompt-edit': fromPromise(
input: ModelingCommandSchema['Prompt-to-edit']
}) => {}
/* Below are recent modeling codemods that are using updateModelinState,
* trigger toastError on Error, and have the 'no kcl errors' guard yet */
extrudeAstMod: fromPromise(
input: ModelingCommandSchema['Extrude'] | undefined
if (!input) {
return Promise.reject(new Error(NO_INPUT_PROVIDED_MESSAGE))
const { nodeToEdit, sketches, length } = input
const { ast } = kclManager
const astResult = addExtrude({
ast,
sketches,
length,
nodeToEdit,
if (err(astResult)) {
return Promise.reject(new Error("Couldn't add extrude statement"))
const { modifiedAst, pathToNode } = astResult
await updateModelingState(
EXECUTION_TYPE_REAL,
{
focusPath: [pathToNode],
sweepAstMod: fromPromise(
input: ModelingCommandSchema['Sweep'] | undefined
const { nodeToEdit, sketches, path, sectional } = input
const astResult = addSweep({
path,
sectional,
return Promise.reject(astResult)
loftAstMod: fromPromise(
input: ModelingCommandSchema['Loft'] | undefined
const { sketches } = input
const astResult = addLoft({ ast, sketches })
revolveAstMod: fromPromise(
input: ModelingCommandSchema['Revolve'] | undefined
const { nodeToEdit, sketches, angle, axis, edge, axisOrEdge } = input
const astResult = addRevolve({
angle,
axisOrEdge,
axis,
edge,
offsetPlaneAstMod: fromPromise(
input: ModelingCommandSchema['Offset plane'] | undefined
// Extract inputs
const ast = kclManager.ast
const { plane: selection, distance, nodeToEdit } = input
let insertIndex: number | undefined = undefined
let planeName: string | undefined = undefined
// If this is an edit flow, first we're going to remove the old plane
if (nodeToEdit && typeof nodeToEdit[1][0] === 'number') {
// Extract the plane name from the node to edit
const planeNameNode = getNodeFromPath<VariableDeclaration>(
if (err(planeNameNode)) {
console.error('Error extracting plane name')
planeName = planeNameNode.node.declaration.id.name
const newBody = [...ast.body]
newBody.splice(nodeToEdit[1][0], 1)
ast.body = newBody
insertIndex = nodeToEdit[1][0]
// Extract the default plane from selection
const plane = selection.otherSelections[0]
if (!(plane && plane instanceof Object && 'name' in plane))
return trap('No plane selected')
// Get the default plane name from the selection
const offsetPlaneResult = addOffsetPlane({
node: ast,
defaultPlane: plane.name,
offset:
'variableName' in distance
? distance.variableIdentifierAst
: distance.valueAst,
insertIndex,
planeName,
// Insert the distance variable if the user has provided a variable name
'variableName' in distance &&
distance.variableName &&
typeof offsetPlaneResult.pathToNode[1][0] === 'number'
const insertIndex = Math.min(
offsetPlaneResult.pathToNode[1][0],
distance.insertIndex
const newBody = [...offsetPlaneResult.modifiedAst.body]
newBody.splice(insertIndex, 0, distance.variableDeclarationAst)
offsetPlaneResult.modifiedAst.body = newBody
// Since we inserted a new variable, we need to update the path to the extrude argument
offsetPlaneResult.pathToNode[1][0]++
offsetPlaneResult.modifiedAst,
focusPath: [offsetPlaneResult.pathToNode],
helixAstMod: fromPromise(
input: ModelingCommandSchema['Helix'] | undefined
mode,
cylinder,
revolutions,
angleStart,
ccw,
radius,
} = input
let opInsertIndex: number | undefined = undefined
let opVariableName: string | undefined = undefined
// If this is an edit flow, first we're going to remove the old one
// Extract the old name from the node to edit
const oldNode = getNodeFromPath<VariableDeclaration>(
if (err(oldNode)) {
opVariableName = oldNode.node.declaration.id.name
opInsertIndex = nodeToEdit[1][0]
let cylinderDeclarator: VariableDeclarator | undefined
let axisExpression:
| Node<CallExpressionKw | Name>
| Node<Literal>
| undefined
if (mode === 'Cylinder') {
!(
cylinder &&
cylinder.graphSelections[0] &&
cylinder.graphSelections[0].artifact?.type === 'wall'
return Promise.reject(new Error('Cylinder argument not valid'))
const clonedAstForGetExtrude = structuredClone(ast)
const extrudeLookupResult = getPathToExtrudeForSegmentSelection(
clonedAstForGetExtrude,
cylinder.graphSelections[0],
if (err(extrudeLookupResult)) {
return Promise.reject(extrudeLookupResult)
const extrudeNode = getNodeFromPath<VariableDeclaration>(
extrudeLookupResult.pathToExtrudeNode,
if (err(extrudeNode)) {
return Promise.reject(extrudeNode)
cylinderDeclarator = extrudeNode.node.declaration
} else if (mode === 'Axis' || mode === 'Edge') {
const getAxisResult = getAxisExpressionAndIndex(mode, axis, edge, ast)
if (err(getAxisResult)) {
return Promise.reject(getAxisResult)
axisExpression = getAxisResult.generatedAxis
return Promise.reject(
new Error(
'Generated axis or cylinder declarator selection is missing.'
// TODO: figure out if we want to smart insert after the sketch as below
// *or* after the sweep that consumes the sketch, in which case the below code doesn't work
// If an axis was selected in KCL, find the max index to insert the revolve command
// if (axisIndexIfAxis) {
// opInsertIndex = axisIndexIfAxis + 1
// }
for (const v of [revolutions, angleStart, radius, length]) {
if (v === undefined) {
continue
const variable = v as KclCommandValue
// Insert the variable if it exists
if ('variableName' in variable && variable.variableName) {
newBody.splice(
variable.insertIndex,
0,
variable.variableDeclarationAst
const { modifiedAst, pathToNode } = addHelix({
revolutions: valueOrVariable(revolutions),
angleStart: valueOrVariable(angleStart),
radius: radius ? valueOrVariable(radius) : undefined,
axis: axisExpression,
cylinder: cylinderDeclarator,
length: length ? valueOrVariable(length) : undefined,
insertIndex: opInsertIndex,
variableName: opVariableName,
shellAstMod: fromPromise(
input: ModelingCommandSchema['Shell'] | undefined
const { selection, thickness, nodeToEdit } = input
let variableName: string | undefined = undefined
// If this is an edit flow, first we're going to remove the old extrusion
const variableNode = getNodeFromPath<VariableDeclaration>(
err(variableNode) ||
variableNode.node.type !== 'VariableDeclaration'
console.error('Error extracting name')
variableName = variableNode.node.declaration.id.name
// Removing the old statement
// Turn the selection into the faces list
const faces: Expr[] = []
let pathToExtrudeNode: PathToNode | undefined = undefined
for (const graphSelection of selection.graphSelections) {
graphSelection,
"Couldn't find extrude paths from getPathToExtrudeForSegmentSelection",
{ cause: extrudeLookupResult }
return new Error("Couldn't find extrude node from selection", {
cause: extrudeNode,
const segmentNode = getNodeFromPath<VariableDeclaration>(
extrudeLookupResult.pathToSegmentNode,
if (err(segmentNode)) {
new Error("Couldn't find segment node from selection", {
cause: segmentNode,
if (extrudeNode.node.declaration.init.type === 'CallExpressionKw') {
pathToExtrudeNode = extrudeLookupResult.pathToExtrudeNode
segmentNode.node.declaration.init.type === 'PipeExpression'
pathToExtrudeNode = extrudeLookupResult.pathToSegmentNode
"Couldn't find extrude node that was either a call expression or a pipe",
{ cause: segmentNode }
const selectedArtifact = graphSelection.artifact
if (!selectedArtifact) {
return Promise.reject(new Error('Bad artifact from selection'))
// Check on the selection, and handle the wall vs cap cases
let expr: Expr
if (selectedArtifact.type === 'cap') {
expr = createLiteral(selectedArtifact.subType)
} else if (selectedArtifact.type === 'wall') {
const tagResult = mutateAstWithTagForSketchSegment(
extrudeLookupResult.pathToSegmentNode
if (err(tagResult)) {
return Promise.reject(tagResult)
const { tag } = tagResult
expr = createLocalName(tag)
new Error('Artifact is neither a cap nor a wall')
faces.push(expr)
if (!pathToExtrudeNode) {
return Promise.reject(new Error('No path to extrude node found'))
const extrudeNode = getNodeFromPath<VariableDeclarator>(
pathToExtrudeNode,
'VariableDeclarator'
new Error("Couldn't find extrude node", {
// Perform the shell op
const sweepName = extrudeNode.node.id.name
const addResult = addShell({
sweepName,
faces: faces,
thickness:
'variableName' in thickness
? thickness.variableIdentifierAst
: thickness.valueAst,
variableName,
// Insert the thickness variable if the user has provided a variable name
'variableName' in thickness &&
thickness.variableName &&
typeof addResult.pathToNode[1][0] === 'number'
addResult.pathToNode[1][0],
thickness.insertIndex
const newBody = [...addResult.modifiedAst.body]
newBody.splice(insertIndex, 0, thickness.variableDeclarationAst)
addResult.modifiedAst.body = newBody
addResult.pathToNode[1][0]++
addResult.modifiedAst,
focusPath: [addResult.pathToNode],
filletAstMod: fromPromise(
input: ModelingCommandSchema['Fillet'] | undefined
let modifiedAst = structuredClone(ast)
let focusPath: PathToNode[] = []
const { nodeToEdit, selection, radius } = input
const parameters: FilletParameters = {
type: EdgeTreatmentType.Fillet,
const dependencies = {
// Apply or edit fillet
if (nodeToEdit) {
// Edit existing fillet
// selection is not the edge treatment itself,
// but just the first edge in the fillet expression >
// we need to find the edgeCut artifact
// and build a new selection from it
// TODO: this is a bit of a hack, we should be able
// to get the edgeCut artifact from the selection
const firstSelection = selection.graphSelections[0]
const edgeCutArtifact = Array.from(
kclManager.artifactGraph.values()
).find(
(artifact) =>
artifact.type === 'edgeCut' &&
artifact.consumedEdgeId === firstSelection.artifact?.id
if (!edgeCutArtifact || edgeCutArtifact.type !== 'edgeCut') {
'Failed to retrieve edgeCut artifact from sweepEdge selection'
const edgeTreatmentSelection = {
artifact: edgeCutArtifact,
codeRef: edgeCutArtifact.codeRef,
const editResult = await editEdgeTreatment(
edgeTreatmentSelection,
parameters
if (err(editResult)) return Promise.reject(editResult)
modifiedAst = editResult.modifiedAst
focusPath = [editResult.pathToEdgeTreatmentNode]
// Apply fillet to selection
const filletResult = await modifyAstWithEdgeTreatmentAndTag(
parameters,
dependencies
if (err(filletResult)) return Promise.reject(filletResult)
modifiedAst = filletResult.modifiedAst
focusPath = filletResult.pathToEdgeTreatmentNode
focusPath: focusPath,
chamferAstMod: fromPromise(
input: ModelingCommandSchema['Chamfer'] | undefined
const { nodeToEdit, selection, length } = input
const parameters: ChamferParameters = {
type: EdgeTreatmentType.Chamfer,
// Apply or edit chamfer
// Edit existing chamfer
// but just the first edge in the chamfer expression >
// Apply chamfer to selection
const chamferResult = await modifyAstWithEdgeTreatmentAndTag(
if (err(chamferResult)) return Promise.reject(chamferResult)
modifiedAst = chamferResult.modifiedAst
focusPath = chamferResult.pathToEdgeTreatmentNode
'actor.parameter.create': fromPromise(
input: ModelingCommandSchema['event.parameter.create'] | undefined
const { value } = input
if (!('variableName' in value)) {
return Promise.reject(new Error('variable name is required'))
const newAst = insertNamedConstant({
node: kclManager.ast,
newExpression: value,
await updateModelingState(newAst, EXECUTION_TYPE_REAL, {
'actor.parameter.edit': fromPromise(
input: ModelingCommandSchema['event.parameter.edit'] | undefined
// Get the variable AST node to edit
const { nodeToEdit, value } = input
const newAst = structuredClone(kclManager.ast)
const variableNode = getNodeFromPath<Node<VariableDeclarator>>(
newAst,
nodeToEdit
variableNode.node.type !== 'VariableDeclarator' ||
!variableNode.node
return Promise.reject(new Error('No variable found, this is a bug'))
// Mutate the variable's value
variableNode.node.init = value.valueAst
deleteSelectionAstMod: fromPromise(
({
input: { selectionRanges: Selections }
return new Promise((resolve, reject) => {
if (!selectionRanges) {
reject(new Error(deletionErrorMessage))
const selection = selectionRanges.graphSelections[0]
deleteSelectionPromise(selection)
.then((result) => {
if (err(result)) {
reject(result)
resolve(result)
.catch(reject)
appearanceAstMod: fromPromise(
input: ModelingCommandSchema['Appearance'] | undefined
const { color, nodeToEdit } = input
if (!(nodeToEdit && typeof nodeToEdit[1][0] === 'number')) {
return Promise.reject(new Error('Appearance is only an edit flow'))
const result = setAppearance({
color,
return Promise.reject(err(result))
result.modifiedAst,
focusPath: [result.pathToNode],
translateAstMod: fromPromise(
input: ModelingCommandSchema['Translate'] | undefined
const modifiedAst = structuredClone(ast)
const { x, y, z, nodeToEdit, selection } = input
let pathToNode = nodeToEdit
if (!(pathToNode && typeof pathToNode[1][0] === 'number')) {
const result = retrievePathToNodeFromTransformSelection(
ast
return Promise.reject(result)
pathToNode = result
// Look for the last pipe with the import alias and a call to translate, with a fallback to rotate.
// Otherwise create one
const importNodeAndAlias = findImportNodeAndAlias(ast, pathToNode)
if (importNodeAndAlias) {
const pipes = findPipesWithImportAlias(ast, pathToNode, 'translate')
const lastPipe = pipes.at(-1)
if (lastPipe && lastPipe.pathToNode) {
pathToNode = lastPipe.pathToNode
const otherRelevantPipes = findPipesWithImportAlias(
pathToNode,
'rotate'
const lastRelevantPipe = otherRelevantPipes.at(-1)
if (lastRelevantPipe && lastRelevantPipe.pathToNode) {
pathToNode = lastRelevantPipe.pathToNode
pathToNode = insertExpressionNode(
importNodeAndAlias.alias
insertVariableAndOffsetPathToNode(x, modifiedAst, pathToNode)
insertVariableAndOffsetPathToNode(y, modifiedAst, pathToNode)
insertVariableAndOffsetPathToNode(z, modifiedAst, pathToNode)
const result = setTranslate({
x: valueOrVariable(x),
y: valueOrVariable(y),
z: valueOrVariable(z),
rotateAstMod: fromPromise(
input: ModelingCommandSchema['Rotate'] | undefined
const { roll, pitch, yaw, nodeToEdit, selection } = input
// Look for the last pipe with the import alias and a call to rotate, with a fallback to translate.
const pipes = findPipesWithImportAlias(ast, pathToNode, 'rotate')
'translate'
insertVariableAndOffsetPathToNode(roll, modifiedAst, pathToNode)
insertVariableAndOffsetPathToNode(pitch, modifiedAst, pathToNode)
insertVariableAndOffsetPathToNode(yaw, modifiedAst, pathToNode)
const result = setRotate({
roll: valueOrVariable(roll),
pitch: valueOrVariable(pitch),
yaw: valueOrVariable(yaw),
cloneAstMod: fromPromise(
input: ModelingCommandSchema['Clone'] | undefined
const { nodeToEdit, selection, variableName } = input
const returnEarly = true
const geometryNode = getNodeFromPath<
VariableDeclaration | ImportStatement | PipeExpression
>(
['VariableDeclaration', 'ImportStatement', 'PipeExpression'],
returnEarly
if (err(geometryNode)) {
new Error("Couldn't find corresponding path to node")
let geometryName: string | undefined
if (geometryNode.node.type === 'VariableDeclaration') {
geometryName = geometryNode.node.declaration.id.name
geometryNode.node.type === 'ImportStatement' &&
geometryNode.node.selector.type === 'None' &&
geometryNode.node.selector.alias
geometryName = geometryNode.node.selector.alias?.name
new Error("Couldn't find corresponding geometry")
const result = addClone({
geometryName,
exportFromEngine: fromPromise(
async ({}: { input?: ModelingCommandSchema['Export'] }) => {
return undefined as Error | undefined
makeFromEngine: fromPromise(
async ({}: {
input?: {
} & ModelingCommandSchema['Make']
boolSubtractAstMod: fromPromise(
input: ModelingCommandSchema['Boolean Subtract'] | undefined
const { target, tool } = input
!target.graphSelections[0].artifact ||
!tool.graphSelections[0].artifact
return Promise.reject(new Error('No artifact in selections found'))
await applySubtractFromTargetOperatorSelections(
target.graphSelections[0],
tool.graphSelections[0],
boolUnionAstMod: fromPromise(
input: ModelingCommandSchema['Boolean Union'] | undefined
const { solids } = input
if (!solids.graphSelections[0].artifact) {
await applyUnionFromTargetOperatorSelections(solids, {
boolIntersectAstMod: fromPromise(
await applyIntersectFromTargetOperatorSelections(solids, {
/* Pierre: looks like somewhat of a one-off */
'reeval-node-paths': fromPromise(
input: { sketchDetails },
input: Pick<ModelingMachineContext, 'sketchDetails'>
const errorMessage =
'Unable to maintain sketch mode - code changes affected sketch references. Please re-enter.'
return Promise.reject(new Error(errorMessage))
// hasErrors is for parse errors, errors is for runtime errors
if (kclManager.errors.length > 0 || kclManager.hasErrors()) {
// if there's an error in the execution, we don't actually want to disable sketch mode
// instead we'll give the user the chance to fix their error
updatedEntryNodePath: sketchDetails.sketchEntryNodePath,
updatedSketchNodePaths: sketchDetails.sketchNodePaths,
updatedPlaneNodePath: sketchDetails.planeNodePath,
const updatedPlaneNodePath = updatePathToNodesAfterEdit(
kclManager._lastAst,
sketchDetails.planeNodePath
if (err(updatedPlaneNodePath)) {
const maybePlaneArtifact = [...kclManager.artifactGraph.values()].find(
(artifact) => {
const codeRef = getFaceCodeRef(artifact)
if (!codeRef) return false
return (
stringifyPathToNode(codeRef.pathToNode) ===
stringifyPathToNode(updatedPlaneNodePath)
!maybePlaneArtifact ||
(maybePlaneArtifact.type !== 'plane' &&
maybePlaneArtifact.type !== 'startSketchOnFace')
let planeArtifact: Artifact | undefined
if (maybePlaneArtifact.type === 'plane') {
planeArtifact = maybePlaneArtifact
const face = kclManager.artifactGraph.get(maybePlaneArtifact.faceId)
if (face) {
planeArtifact = face
!planeArtifact ||
(planeArtifact.type !== 'cap' &&
planeArtifact.type !== 'wall' &&
planeArtifact.type !== 'plane')
const newPaths = getPathsFromPlaneArtifact(
planeArtifact,
kclManager.ast
updatedEntryNodePath: newPaths[0],
updatedSketchNodePaths: newPaths,
// end actors
}).createMachine({
/** @xstate-layout N4IgpgJg5mDOIC5QFkD2EwBsCWA7KAxAMICGuAxlgNoAMAuoqAA6qzYAu2qujIAHogC0ANmEBmAHQBGAJwBWABwKpSqTQDsUsQBoQAT0QAmdQBYJYmmPVjDh4YsMKZAX2e60GHPgIBlMOwACWCwwck5uWgYkEBY2cJ5ogQRBNRkzOUsFOTFFGhNZQ10DBBkZCXU7Szl5KRMTWxNXd3QsPEI-QIBbVABXYKD2EnYwSN5Yji4E0CSUqSlDCQUTGRpZefV1GWF1IsQxbYkTOS0FDRo5dRpDKTkmkA9W7w6A8m5hvnZR6PH43hnU4QSVYWbYyMQKdQKRy7BDCfLSYTXQzHUQmJQuNz3Fpedr+AJ+KCdMC4QIAeQAbmAAE6YEh6WBfZisCbcP5COaKCTydQXHkydRwjYw44LSz2YQaWw5ex3B444jE4ZUl4kIlUkgBbhBEJhSaMmLM36JdlSSHmVbGZY5NLCBQw040CSImjKUrZFSy7FtAgAFVQUCgmDAAQwADMSD1MIEmLTcMHydg2AAjbA4dh6fU-SZs5LzNGHGgSmTzCG1Wow+SO11bMQmHKVRqYuVtCTYCBBggAURJ1KCAGt-OQABaZw3Z43JZFSQ5g4RqFSGZbImEVMqQyEQyFw+a3Jte-Ct9tgLs95WwAfsYdUKRRJlxcfTIQNcpQ23XflKeyFfSIUTTuQAXMcIXDIThSJ6ngtm2Hadh8VI9Bgo73qyE4iDQjqbLUpiFhYVgmDChhWJIjhXBcci2ks5EQY8UCHh2PgAO5gGATBISyUz8EI1TqEC2zZHUO7GN+xTXPsBaLjYeQSiYArUTidHHgAMqgoafPQYxjihj7JIogJpFOciGDI1zbDCC6SC6qwmNstaKGiclQUeBAAEpgOSqCYJSbFGtpgiaDxOSaLpwjFlYwgwmIpQKE65E2P5FS1A5B7QcepKhqGwTRrGIzqd8mkcTMc48VcOFgo4NwyGZEqSJW1VOBkhHqEltEpQQAASrR8N5D6cTpKxOjQxZZMYczzARGSOuh5wXFo9SGM1Cm+EOWCYN1Wm9YI1SOsYhbLLUUIqOFP4IKa1zlHk1lOJs2zgXukHJU5ABiqZBmpt4GshBVcf16EZLIlxzcux2GKscgSNUshzvYAFWAtrVEEOqqhtSa1fck1XlJc4gCqaxm2gRi5g-IUViu6813TRi1uYqEhMCQ6pEkqEjkFSYBDDl71ZutMyYeDRk8mIppqMcdrHYLtrg6WSwqJY4Jw051MkrT9Oqv41ISJAHCozmfmReUxg5CLdaEUdxS1jyhxLJsKyrF+8swXwLBUm9GmfTr1gLFktpSCF-IaKLZsXeDxZ5EZIMQrW9vHsgJADtrqHWJIpzWhctoCkDIlgtOXvglowFQo2zT3S1TkACIhMM2pBrqES5Xe7E61kkg+37pRwkZeQEfY-6mvURympcthR76YAfII7CoIIRAAIKl-H2liILEiOORBfrMc+HHaB06zqB1jHJkGJF5TrUAApUqgnRMOw4+T5rLt5W7qGIjxcwCasVSUWZxaAk4Jig4vS6R8sTF0WtPJgTA2bqgoBzV2Ddn7nHKIvDYZUVj2B0MDTY0VawulMIvSwt1j7yVaj6aBsBaTDHnhtContkTFmMjJOoCgMHFHyKYRYs5kTImqDYYezlUCDEoXXD68DfKaAWLaQyEJyKbGslIGE9QliSxBoRQaAoXTDyIJgbgsDH6iOoYNLk-IeRwlAnkOQm9WF1h4ksFe-cLClGHgAIVQB5NmuB8Q9CTOwdUYQqE8zsIcEKdlrHyFNnsIs5gLFgjqBoXOYhnGuKDGQAIABVXAephFczRn5fMWQFCIgYY4fIEUKjRSyBY7INRbSJLcSkgAkqeYIfisn5XdtULkmgbAgykmiCKSgeL-0XIDRehCQEnyPBIIcbYwCn2yrAAg09nbYHDGEAIUB1RMCHAEFgTBIzswgP4oQmgzClGsqsGhyh9hmWRGYTQh1TC2ElIXcZxDJmwCHKgBicyyBwEWcs1ZgQNkkC2QEMAV9OCQCObmYqYJIpQnQisVOOxjpqHYecOo2wQqiBBmM5sB4fAXmHMQMglBVqtKftpPOZQtgFPWPyOaEU6yHEhLcpcIMNgLUJYOIcJKYGYG5ZeEcFL9FJFqGdNEAN-JXDSCwxAag9bLGqH+NE3JdxEJbIK4l5dXrBmCISRU0KljEUhDYX2TDwQRWnOhFQQU4Tgm2DJLlRLeWvAwGCiAHAQw9CpG0fsPLoU3E0ODXOLobiBR5CuTYHDgQ+zmKsfkzqeXEG4LAHxJA8ABAYhwbZuBVYQACOSEgmAei6Prj5XqcwNhckGuK3SS5Kpi2kgiUw1l8hBvVa8zVLqJBaqHPUpyMcBzagNSSQt1JODkGLYGwydyQkXAsDJRcZkBRmDmDkSK+xcGCyTUK3tLqB0diHXqsAo7AifN9QALzeNOkVFaxUZGiioeoBDqhIgDvKnFUTjI3COMWI4u7hz7p5Ye48RBU3pszRe7A16STFpDImQYMDA2SqdLjf2Vz7UEVML-EKVlHAVEsIBocwGhWgZTbgNN6pM2UmWVOzACG02krLSI+98qGp8yWMsNOhl+Rd0XOYMKoEJTZAAi8-FtE+2keHOR8DlHIMeOnk4nwAQAAaM7ZBAi0HMfmGwrAfoQPgsGGwZXggsThBJFN5JSb7bJiD1HFPKYCAATQ0+UgeInETzhRWbOsZQqmFgsfsZh4n9ySZ7bZpycmqMZo8WQQMLHsk5iDXpao9QcXWUJgRfJQJCPFjsuiJqVnu08uk-2qL9nYsBCDPgdgwrOZtInEGx0aR5gaFNBCCU4SEBGRCsorOGww7bGI2Vuz8mHM7OpJA3AnryD7OVJ6pjyG709TFZl3Le0LrMMLPIsWPswbZFrByQy2QeQjcix2aLCmAjQdg4MTAmA9ABGLdgKAuAUNbEODg5hkUVAizMgU1+g19g3AAug87B6Kvjaq7RydxbHvPZwG9jTFkXQyRMcUjQ38BQFlGVONFRWNUEoi5Dy7lXM2wDzUwAIE81MzusosSK-9B6XSOARTdQJfunDrJFcQEOQNQ5ixTqnNPUAufp4Cbu+XTXRO64uUC5hESEQZQBCx5MifhdKxdsD5OPFgAAI49HgzVqAdWZ3GCBCsKwGwUSlGEkYMNy86xXKUNZao-OyOC+u3TdUD3qAre5uxiUA1bA+2MDNAUBMFf1HrPyONmwPcya9xN1m3RKQvF1+wBkAe0b7QWCoU4QWQSZAIiobOi7ax2CrXCRP5WOxuuDPfb1vr8D+qFTO4N2RlBhtEzb+0-9LZLHQuCLIQba-keHPF4ME8PLQqMqUcGnmuGL3tPMLkfEsb7AdcAiTZXRvvLxD0an+qiQkgWRAHRrZcDuQHBITKR-BDkBwIqQQbAMCv5da-09p+s9iEDZWLkRQQjLIQsG0MyRdcwLYQaGSUQcRYQcfA-QII-EdH-c-S-PAG-MAO-fwB-J-bAF-N-MAD-HlL-M9WAP-G8OBNjE6NIaKI4QyRcWQZQOoSxeVKwR0POLGK0VdQnLtYnLXUnLAzKAIZAk-RUBZakC+KkWmChUMVAKkTobA9gXA5-EkV-GZYgoVUg1Av-HPd2dCPmH2awayAUJwRtYoHkMwCwawOqbhYwEbaeBiDNc9eQmDG9BjRbJDSgAIPAOQggC-OMK-TAiQGAG+W7dwwQXw1AOfLvIEJ5DQLcGPbDS4J0UQReX2Yw4bYrfgvdRw5wm7Vwu7eDTw5jHw3APwyQ+QmQoYOQhQkI-wQQcIuDTASI8o6IvQicZEcEJ0G2YHYsfebDGwRYCxN+GWUfBwpwr1WHbAejRjLw4MKI-w9A6-VAW-UIwQaY+jVouQmIo4coWaNHPOcEOVHrcQMwCiAUZVeYRECY-IzY4oxDUoxYyo6QmMGo+QxQ9Y+4loqI3YwEeJC4WwWwLIHzIwN9TpYsMPH2fTSzDXPfPIr1JTFTVTMovwgIrAjA1YrA9YkgJMWAQQPgbY9ohrSlXqbhR0ZBCUSwKaLoiKQWBYeQTdK4CUfydXPgzXXIyYwIJEtTVE1AAgF46o9gWoz4ho3E-
id: 'Modeling',
context: ({ input }) => ({
...modelingMachineDefaultContext,
...input,
states: {
idle: {
on: {
'Enter sketch': [
target: 'animating to existing sketch',
guard: 'Selection is on face',
target: 'Sketch no face',
guard: 'no kcl errors',
],
Extrude: {
target: 'Applying extrude',
reenter: true,
Sweep: {
target: 'Applying sweep',
Loft: {
target: 'Applying loft',
Revolve: {
target: 'Applying revolve',
'Offset plane': {
target: 'Applying offset plane',
Helix: {
target: 'Applying helix',
Shell: {
target: 'Applying shell',
Fillet: {
target: 'Applying fillet',
Chamfer: {
target: 'Applying chamfer',
'event.parameter.create': {
target: '#Modeling.parameter.creating',
'event.parameter.edit': {
target: '#Modeling.parameter.editing',
Export: {
target: 'Exporting',
guard: 'Has exportable geometry',
Make: {
target: 'Making',
'Delete selection': {
target: 'Applying Delete selection',
guard: 'has valid selection for deletion',
'Text-to-CAD': {
target: 'idle',
reenter: false,
actions: ['Submit to Text-to-CAD API'],
'Prompt-to-edit': 'Applying Prompt-to-edit',
Appearance: {
target: 'Applying appearance',
Translate: {
target: 'Applying translate',
Rotate: {
target: 'Applying rotate',
Clone: {
target: 'Applying clone',
'Boolean Subtract': {
target: 'Boolean subtracting',
'Boolean Union': {
target: 'Boolean uniting',
'Boolean Intersect': {
target: 'Boolean intersecting',
entry: 'reset client scene mouse handlers',
hidePlanes: {
'Artifact graph populated': {
target: 'showPlanes',
entry: 'hide default planes',
showPlanes: {
'Artifact graph emptied': 'hidePlanes',
entry: ['show default planes'],
description: `We want to disable selections and hover highlights here, because users can't do anything with that information until they actually add something to the scene. The planes are just for orientation here.`,
exit: 'set selection filter to defaults',
initial: 'hidePlanes',
Sketch: {
SketchIdle: {
'Make segment vertical': {
guard: 'Can make selection vertical',
target: 'Await constrain vertically',
'Make segment horizontal': {
guard: 'Can make selection horizontal',
target: 'Await constrain horizontally',
'Constrain horizontal distance': {
target: 'Await horizontal distance info',
guard: 'Can constrain horizontal distance',
'Constrain vertical distance': {
target: 'Await vertical distance info',
guard: 'Can constrain vertical distance',
'Constrain ABS X': {
target: 'Await ABS X info',
guard: 'Can constrain ABS X',
'Constrain ABS Y': {
target: 'Await ABS Y info',
guard: 'Can constrain ABS Y',
'Constrain angle': {
target: 'Await angle info',
guard: 'Can constrain angle',
'Constrain length': {
target: 'Apply length constraint',
guard: 'Can constrain length',
'Constrain perpendicular distance': {
target: 'Await perpendicular distance info',
guard: 'Can constrain perpendicular distance',
'Constrain horizontally align': {
guard: 'Can constrain horizontally align',
target: 'Await constrain horizontally align',
'Constrain vertically align': {
guard: 'Can constrain vertically align',
target: 'Await constrain vertically align',
'Constrain snap to X': {
guard: 'Can constrain snap to X',
target: 'Await constrain snap to X',
'Constrain snap to Y': {
guard: 'Can constrain snap to Y',
target: 'Await constrain snap to Y',
'Constrain equal length': {
guard: 'Can constrain equal length',
target: 'Await constrain equal length',
'Constrain parallel': {
target: 'Await constrain parallel',
guard: 'Can constrain parallel',
'Constrain remove constraints': {
guard: 'Can constrain remove constraints',
target: 'Await constrain remove constraints',
'code edit during sketch': 'clean slate',
'change tool': {
target: 'Change Tool',
'set up segments': {
invoke: {
src: 'setup-client-side-sketch-segments',
id: 'setup-client-side-sketch-segments3',
input: ({ context: { sketchDetails, selectionRanges } }) => ({
onDone: [
target: 'scene drawn',
guard: 'is-error-free',
target: 'sketch-can-not-be-drawn',
onError: {
target: '#Modeling.idle',
'scene drawn': {},
'sketch-can-not-be-drawn': {
entry: 'show sketch error toast',
exit: 'remove sketch error toast',
initial: 'set up segments',
'Await horizontal distance info': {
src: 'Get horizontal info',
id: 'get-horizontal-info',
input: ({ context: { selectionRanges, sketchDetails } }) => ({
onDone: {
target: 'SketchIdle',
actions: 'Set selection',
onError: 'SketchIdle',
'Await vertical distance info': {
src: 'Get vertical info',
id: 'get-vertical-info',
'Await ABS X info': {
src: 'Get ABS X info',
id: 'get-abs-x-info',
'Await ABS Y info': {
src: 'Get ABS Y info',
id: 'get-abs-y-info',
'Await angle info': {
src: 'Get angle info',
id: 'get-angle-info',
'Apply length constraint': {
src: 'astConstrainLength',
id: 'AST-constrain-length',
input: ({ context: { selectionRanges, sketchDetails }, event }) => {
const data =
event.type === 'Constrain length' ? event.data : undefined
lengthValue: data?.length,
'Await perpendicular distance info': {
src: 'Get perpendicular distance info',
id: 'get-perpendicular-distance-info',
'Line tool': {
exit: [],
Init: {
entry: 'setup noPoints onClick listener',
'Add start point': {
target: 'normal',
actions: 'set up draft line',
exit: 'remove draft entities',
normal: {
'Close sketch': {
target: 'Finish profile',
'Finish profile': {
id: 'setup-client-side-sketch-segments7',
onDone: 'Init',
onError: 'Init',
initial: 'Init',
always: [
guard: 'is editing existing sketch',
'Line tool',
'Tangential arc to': {
'Continue existing profile': {
actions: 'set up draft arc',
id: 'setup-client-side-sketch-segments6',
'undo startSketchOn': {
invoke: [
id: 'sketchExit',
src: 'sketchExit',
input: ({ context }) => ({ context }),
src: 'AST-undo-startSketchOn',
id: 'AST-undo-startSketchOn',
input: ({ context: { sketchDetails } }) => ({ sketchDetails }),
actions: 'enter modeling mode',
'Rectangle tool': {
'Awaiting second corner': {
'Finish rectangle': {
target: 'Finished Rectangle',
actions: 'reset deleteIndex',
'Awaiting origin': {
'click in scene': {
target: 'adding draft rectangle',
entry: 'listen for rectangle origin',
'Finished Rectangle': {
id: 'setup-client-side-sketch-segments',
onDone: 'Awaiting origin',
'adding draft rectangle': {
src: 'set-up-draft-rectangle',
id: 'set-up-draft-rectangle',
target: 'Awaiting second corner',
actions: 'update sketchDetails',
onError: 'Awaiting origin',
input: ({ context: { sketchDetails }, event }) => {
if (event.type !== 'click in scene')
data: [0, 0],
data: event.data,
initial: 'Awaiting origin',
'Center Rectangle tool': {
'Awaiting corner': {
'Finish center rectangle': {
target: 'Finished Center Rectangle',
'Add center rectangle origin': {
target: 'add draft center rectangle',
entry: 'listen for center rectangle origin',
'Finished Center Rectangle': {
id: 'setup-client-side-sketch-segments2',
'add draft center rectangle': {
src: 'set-up-draft-center-rectangle',
id: 'set-up-draft-center-rectangle',
target: 'Awaiting corner',
if (event.type !== 'Add center rectangle origin')
'clean slate': {
src: 'reeval-node-paths',
id: 'reeval-node-paths',
input: ({ context: { sketchDetails } }) => ({
actions: 'toastError',
'Converting to named value': {
src: 'Apply named value constraint',
id: 'astConstrainNamedValue',
if (event.type !== 'Constrain with named value') {
data: undefined,
'Await constrain remove constraints': {
src: 'do-constrain-remove-constraint',
id: 'do-constrain-remove-constraint',
data:
event.type === 'Constrain remove constraints'
? event.data
: undefined,
'Await constrain horizontally': {
src: 'do-constrain-horizontally',
id: 'do-constrain-horizontally',
'Await constrain vertically': {
src: 'do-constrain-vertically',
id: 'do-constrain-vertically',
'Await constrain horizontally align': {
src: 'do-constrain-horizontally-align',
id: 'do-constrain-horizontally-align',
input: ({ context }) => ({
selectionRanges: context.selectionRanges,
sketchDetails: context.sketchDetails,
'Await constrain vertically align': {
src: 'do-constrain-vertically-align',
id: 'do-constrain-vertically-align',
'Await constrain snap to X': {
src: 'do-constrain-snap-to-x',
id: 'do-constrain-snap-to-x',
'Await constrain snap to Y': {
src: 'do-constrain-snap-to-y',
id: 'do-constrain-snap-to-y',
'Await constrain equal length': {
src: 'do-constrain-equal-length',
id: 'do-constrain-equal-length',
'Await constrain parallel': {
src: 'do-constrain-parallel',
id: 'do-constrain-parallel',
'Change Tool ifs': {
guard: 'next is none',
target: 'Line tool',
guard: 'next is line',
target: 'Rectangle tool',
guard: 'next is rectangle',
target: 'Tangential arc to',
guard: 'next is tangential arc',
target: 'Circle tool',
guard: 'next is circle',
target: 'Center Rectangle tool',
guard: 'next is center rectangle',
target: 'Circle three point tool',
guard: 'next is circle three point neo',
target: 'Arc tool',
guard: 'next is arc',
target: 'Arc three point tool',
guard: 'next is arc three point',
'Circle tool': {
entry: 'listen for circle origin',
'Add circle origin': {
target: 'adding draft circle',
'Awaiting Radius': {
'Finish circle': {
target: 'Finished Circle',
'Finished Circle': {
id: 'setup-client-side-sketch-segments4',
'adding draft circle': {
src: 'set-up-draft-circle',
id: 'set-up-draft-circle',
target: 'Awaiting Radius',
if (event.type !== 'Add circle origin')
'Change Tool': {
'splitting sketch pipe': {
src: 'split-sketch-pipe-if-needed',
id: 'split-sketch-pipe-if-needed',
target: 'setup sketch for tool',
onError: '#Modeling.Sketch.SketchIdle',
'setup sketch for tool': {
onDone: '#Modeling.Sketch.Change Tool ifs',
initial: 'splitting sketch pipe',
entry: ['assign tool in context', 'reset selections'],
'Circle three point tool': {
'Awaiting first point': {
'Add first point': 'Awaiting second point',
entry: 'listen for circle first point',
'Awaiting second point': {
'Add second point': {
target: 'adding draft circle three point',
actions: 'remove draft entities',
entry: 'listen for circle second point',
'adding draft circle three point': {
src: 'set-up-draft-circle-three-point',
id: 'set-up-draft-circle-three-point',
target: 'Awaiting third point',
if (event.type !== 'Add second point')
data: { p1: [0, 0], p2: [0, 0] },
'Awaiting third point': {
'Finish circle three point': {
target: 'Finished circle three point',
'Finished circle three point': {
id: 'setup-client-side-sketch-segments5',
onDone: 'Awaiting first point',
initial: 'Awaiting first point',
'change tool': 'Change Tool',
'Arc tool': {
'Awaiting start point': {
target: 'Awaiting for circle center',
actions: 'update sketchDetails arc',
'Awaiting for circle center': {
entry: ['listen for rectangle origin'],
'click in scene': 'Adding draft arc',
'Adding draft arc': {
src: 'set-up-draft-arc',
id: 'set-up-draft-arc',
target: 'Awaiting endAngle',
'Awaiting endAngle': {
'Finish arc': 'Finishing arc',
'Finishing arc': {
id: 'setup-client-side-sketch-segments8',
onDone: 'Awaiting start point',
initial: 'Awaiting start point',
'Arc three point tool': {
target: 'Adding draft arc three point',
entry: ['listen for rectangle origin', 'add draft line'],
'Adding draft arc three point': {
src: 'set-up-draft-arc-three-point',
id: 'set-up-draft-arc-three-point',
'Finish arc': {
target: 'Finishing arc',
'Close sketch': 'Finish profile',
id: 'setup-client-side-sketch-segments9',
id: 'setup-client-side-sketch-segments10',
Cancel: '.undo startSketchOn',
'Delete segment': {
actions: ['Delete segment', 'Set sketchDetails', 'reset selections'],
'code edit during sketch': '.clean slate',
'Constrain with named value': {
target: '.Converting to named value',
guard: 'Can convert to named value',
exit: ['enable copilot'],
entry: ['add axis n grid', 'clientToEngine cam sync direction'],
'Sketch no face': {
entry: [
'disable copilot',
'show default planes',
'set selection filter to faces only',
'enter sketching mode',
exit: ['hide default planes', 'set selection filter to defaults'],
'Select sketch plane': {
target: 'animating to plane',
actions: ['reset sketch metadata'],
'animating to plane': {
src: 'animate-to-face',
id: 'animate-to-face',
input: ({ event }) => {
if (event.type !== 'Select sketch plane') return undefined
return event.data
target: 'Sketch',
actions: 'set new sketch metadata',
onError: 'Sketch no face',
'animating to existing sketch': {
src: 'animate-to-sketch',
id: 'animate-to-sketch',
actions: [
'set new sketch metadata',
onError: 'idle',
'Applying extrude': {
src: 'extrudeAstMod',
id: 'extrudeAstMod',
if (event.type !== 'Extrude') return undefined
onDone: ['idle'],
'Applying sweep': {
src: 'sweepAstMod',
id: 'sweepAstMod',
if (event.type !== 'Sweep') return undefined
'Applying loft': {
src: 'loftAstMod',
id: 'loftAstMod',
if (event.type !== 'Loft') return undefined
'Applying revolve': {
src: 'revolveAstMod',
id: 'revolveAstMod',
if (event.type !== 'Revolve') return undefined
'Applying offset plane': {
src: 'offsetPlaneAstMod',
id: 'offsetPlaneAstMod',
if (event.type !== 'Offset plane') return undefined
'Applying helix': {
src: 'helixAstMod',
id: 'helixAstMod',
if (event.type !== 'Helix') return undefined
'Applying shell': {
src: 'shellAstMod',
id: 'shellAstMod',
if (event.type !== 'Shell') return undefined
'Applying fillet': {
src: 'filletAstMod',
id: 'filletAstMod',
if (event.type !== 'Fillet') return undefined
'Applying chamfer': {
src: 'chamferAstMod',
id: 'chamferAstMod',
if (event.type !== 'Chamfer') return undefined
parameter: {
type: 'parallel',
creating: {
src: 'actor.parameter.create',
id: 'actor.parameter.create',
if (event.type !== 'event.parameter.create') return undefined
onDone: ['#Modeling.idle'],
editing: {
src: 'actor.parameter.edit',
id: 'actor.parameter.edit',
if (event.type !== 'event.parameter.edit') return undefined
'Applying Prompt-to-edit': {
src: 'submit-prompt-edit',
id: 'submit-prompt-edit',
if (event.type !== 'Prompt-to-edit' || !event.data) {
prompt: '',
selection: { graphSelections: [], otherSelections: [] },
onDone: 'idle',
'Applying Delete selection': {
src: 'deleteSelectionAstMod',
id: 'deleteSelectionAstMod',
input: ({ event, context }) => {
return { selectionRanges: context.selectionRanges }
actions: ({ event }) => {
if ('error' in event && err(event.error)) {
'Applying appearance': {
src: 'appearanceAstMod',
id: 'appearanceAstMod',
if (event.type !== 'Appearance') return undefined
'Applying translate': {
src: 'translateAstMod',
id: 'translateAstMod',
if (event.type !== 'Translate') return undefined
'Applying rotate': {
src: 'rotateAstMod',
id: 'rotateAstMod',
if (event.type !== 'Rotate') return undefined
'Applying clone': {
src: 'cloneAstMod',
id: 'cloneAstMod',
if (event.type !== 'Clone') return undefined
Exporting: {
src: 'exportFromEngine',
id: 'exportFromEngine',
if (event.type !== 'Export') return undefined
onError: ['idle'],
Making: {
src: 'makeFromEngine',
id: 'makeFromEngine',
if (event.type !== 'Make' || !context.machineManager) return undefined
machineManager: context.machineManager,
'Boolean subtracting': {
src: 'boolSubtractAstMod',
id: 'boolSubtractAstMod',
input: ({ event }) =>
event.type !== 'Boolean Subtract' ? undefined : event.data,
'Boolean uniting': {
src: 'boolUnionAstMod',
id: 'boolUnionAstMod',
event.type !== 'Boolean Union' ? undefined : event.data,
'Boolean intersecting': {
src: 'boolIntersectAstMod',
id: 'boolIntersectAstMod',
event.type !== 'Boolean Intersect' ? undefined : event.data,
initial: 'idle',
Cancel: {
target: '.idle',
// TODO what if we're existing extrude equipped, should these actions still be fired?
// maybe cancel needs to have a guard for if else logic?
'reset sketch metadata',
'enable copilot',
'enter modeling mode',
'Set selection': {
'Set mouse state': {
actions: 'Set mouse state',
'Set context': {
actions: 'Set context',
'Set Segment Overlays': {
actions: 'Set Segment Overlays',
'Center camera on selection': {
actions: 'Center camera on selection',
'Toggle default plane visibility': {
actions: 'Toggle default plane visibility',
export function isEditingExistingSketch({
}): boolean {
// should check that the variable declaration is a pipeExpression
// and that the pipeExpression contains a "startProfile" callExpression
if (!sketchDetails?.sketchEntryNodePath) return false
const variableDeclaration = getNodeFromPath<VariableDeclarator>(
'VariableDeclarator',
false,
true // suppress noise because we know sketchEntryNodePath might not match up to the ast if the user changed the code
// and is dealt with in `re-eval nodePaths`
if (variableDeclaration instanceof Error) return false
if (variableDeclaration.node.type !== 'VariableDeclarator') return false
const maybePipeExpression = variableDeclaration.node.init
maybePipeExpression.type === 'CallExpressionKw' &&
(maybePipeExpression.callee.name.name === 'startProfile' ||
maybePipeExpression.callee.name.name === 'circle' ||
maybePipeExpression.callee.name.name === 'circleThreePoint')
if (maybePipeExpression.type !== 'PipeExpression') return false
const hasStartProfileAt = maybePipeExpression.body.some(
(item) =>
item.type === 'CallExpressionKw' &&
item.callee.name.name === 'startProfile'
const hasCircle =
maybePipeExpression.body.some(
item.type === 'CallExpressionKw' && item.callee.name.name === 'circle'
) ||
item.callee.name.name === 'circleThreePoint'
return (hasStartProfileAt && maybePipeExpression.body.length > 1) || hasCircle
export function pipeHasCircle({
if (err(variableDeclaration)) return false
const pipeExpression = variableDeclaration.node.init
if (pipeExpression.type !== 'PipeExpression') return false
const hasCircle = pipeExpression.body.some(
return hasCircle