From 779885391e42491a9cdd7260c689a294a6c77630 Mon Sep 17 00:00:00 2001 From: lizaixi01 Date: Sun, 29 Nov 2026 16:44:08 +0800 Subject: [PATCH 01/55] editor i18n: the Chinese UI names things the way SolidWorks does MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DECISION: the Chinese translation table uses the SolidWorks Chinese terms wherever the editor named the same thing differently (基准面, 完全定义/欠定义/过定义, 几何关系/尺寸, 镜向, 构造几何线, 拉伸凸台/拉伸切除, 移动面, 简单直孔, 边线, and 配合 for assembly joints). Only words a person reads change; the SDK, the notebook code, the table's keys and everything an agent reads stay as they are. WHY (discussion of 2026-11-29 between the user and the assistant; record: design-docs/editor-sw-terms.md): the user, learning CAD through the editor's manual mode and SolidWorks videos side by side, compared the two term by term and kept looking for the SolidWorks word and not finding it (工作平面 for a 基准面, 已求解 for 完全定义, 约束 for 几何关系 and 尺寸, 镜像 for 镜向). The people this manual mode is for learned CAD on SolidWorks. The user's judgement: rename so that everything a person reads matches SolidWorks as far as possible, as its own branch, while the kernel stays the agent-friendly tool it is. Words only, so no code path changes. ALTERNATIVE CONSIDERED AND REJECTED: replacing "约束" and "边" everywhere. 约束 also names assembly joints, which SolidWorks calls 配合, and 边 occurs inside other words (边界, 两边); both were changed key by key instead. 基本体 is kept: SolidWorks has no primitives, so there is no word to copy. WHAT CHANGES: editor-web/src/i18n/locales/zh-CN.json, 73 values (no key added, removed or reordered). Behaviour that differs from SolidWorks (pick-kind chips instead of hover selection, connectors instead of face mates, no rollback bar) is not touched here. Checked: `vitest run src/i18n` (3 passed: every key the source uses has a Chinese entry, interpolations kept) and `tsc --noEmit` in this branch, on origin/master. Seen in the running editor on the working branch: the pick chips read 边线, a picked face offers 简单直孔. Not checked: every dialog that shows the renamed words. Co-Authored-By: Claude Opus 5.5 --- editor-web/src/i18n/locales/zh-CN.json | 146 ++++++++++++------------- 1 file changed, 73 insertions(+), 73 deletions(-) diff --git a/editor-web/src/i18n/locales/zh-CN.json b/editor-web/src/i18n/locales/zh-CN.json index 7cf741b5..35087170 100644 --- a/editor-web/src/i18n/locales/zh-CN.json +++ b/editor-web/src/i18n/locales/zh-CN.json @@ -9,7 +9,7 @@ "1 cell": "1 个单元", "1 cell re-evaluated in {{time}}": "1 个单元重新计算,用时 {{time}}", "1 curve": "1 条曲线", - "1 edge": "1 条边", + "1 edge": "1 条边线", "1 entity": "1 个图元", "1 error": "1 个错误", "1 face": "1 个面", @@ -33,7 +33,7 @@ "A face parallel to the first.": "与第一个面平行的面。", "A feature keeps its name.": "特征名称创建后不可更改。", "A part holds one solid: this one starts the part.": "一个零件只有一个实体:这个实体是零件的起点。", - "A path in space: lines, arcs and splines through points in space, on workplanes or at vertices of the model, joined into one wire (a sweep path, a rail). Drawn in the viewport with snapping.": "空间中的路径:由经过空间点、工作平面上的点或模型顶点的直线、圆弧和样条连接成一条线框(可作扫掠路径或导轨)。在视口中带吸附绘制。", + "A path in space: lines, arcs and splines through points in space, on workplanes or at vertices of the model, joined into one wire (a sweep path, a rail). Drawn in the viewport with snapping.": "空间中的路径:由经过空间点、基准面上的点或模型顶点的直线、圆弧和样条连接成一条线框(可作扫掠路径或导轨)。在视口中带吸附绘制。", "A planar face (for an axis: the face the plane starts from).": "一个平面(对于轴:平面起始的那个面)。", "A rectangular block; its bottom face is centred on the origin point.": "长方体,底面中心位于原点。", "A round hole from a point on a surface, in a direction, to a depth.": "从表面上一点沿某方向打到指定深度的圆孔。", @@ -44,9 +44,9 @@ "A surface filling the closed loop the picked curves make.": "填充选中曲线所围闭环的曲面。", "A surface through two families of crossing curves (found from where they cross).": "穿过两组互相交叉曲线的曲面(按交点自动分组)。", "A tagged entity was split": "一个带标签的实体被拆分了", - "A workplane from picked geometry: on a planar face (x along an edge if one is picked, an offset along the normal), halfway between two parallel faces, through three vertices, or through an edge turned about it; or placed by hand (moved and turned with the handles) on XY / XZ / YZ, another workplane or a face. Sketch on it, or place features in it with `with wp:`.": "由所选几何生成工作平面:在平面上(选了边时 x 轴沿该边,可沿法向偏移)、两个平行面的中间、过三个顶点,或过一条边并绕它旋转;也可在 XY / XZ / YZ、其他工作平面或某个面上用手柄平移旋转手动放置。可在上面画草图,或用 `with wp:` 在其中放置特征。", - "A workplane from the selection (Space): a flat face, a face and an edge, two parallel faces, three vertices or an edge. New sketches go on it.": "由所选对象生成工作平面(空格):一个平面、一个面和一条边、两个平行面、三个顶点或一条边。新草图会画在上面。", - "A workplane needs one flat face, a face and an edge, two parallel faces, three vertices or one edge.": "创建工作平面需要:一个平面、一个面和一条边、两个平行面、三个顶点或一条边。", + "A workplane from picked geometry: on a planar face (x along an edge if one is picked, an offset along the normal), halfway between two parallel faces, through three vertices, or through an edge turned about it; or placed by hand (moved and turned with the handles) on XY / XZ / YZ, another workplane or a face. Sketch on it, or place features in it with `with wp:`.": "由所选几何生成基准面:在平面上(选了边时 x 轴沿该边,可沿法向偏移)、两个平行面的中间、过三个顶点,或过一条边并绕它旋转;也可在 XY / XZ / YZ、其他基准面或某个面上用手柄平移旋转手动放置。可在上面画草图,或用 `with wp:` 在其中放置特征。", + "A workplane from the selection (Space): a flat face, a face and an edge, two parallel faces, three vertices or an edge. New sketches go on it.": "由所选对象生成基准面(空格):一个平面、一个面和一条边、两个平行面、三个顶点或一条边。新草图会画在上面。", + "A workplane needs one flat face, a face and an edge, two parallel faces, three vertices or one edge.": "创建基准面需要:一个平面、一个面和一条边、两个平行面、三个顶点或一条边。", "ANCHOR MODE: click a spline's curve to add an anchor (the curve stays), click an inner anchor to remove it. Esc or Shift+A leaves.": "锚点模式:点击样条曲线添加锚点(曲线不变),点击内部锚点删除它。Esc 或 Shift+A 退出。", "Accept this look-alike": "接受这个相似项", "Actions for the selection": "当前选择可用的操作", @@ -81,14 +81,14 @@ "Assign material": "指定材料", "At": "位置", "Attach a connector datum frame to a Part definition.": "给零件定义附加一个连接器基准坐标系。", - "Auto constraints": "自动约束", - "Auto constraints: near-horizontal and vertical lines are constrained as you draw": "自动约束:绘制时,接近水平或竖直的线会自动加上约束", + "Auto constraints": "自动添加几何关系", + "Auto constraints: near-horizontal and vertical lines are constrained as you draw": "自动添加几何关系:绘制时,接近水平或竖直的线会自动加上几何关系", "Axis": "轴", "Axis point": "轴上一点", "Backlash": "侧隙", "Base": "基准", - "Belt constraint": "皮带约束", - "Bevel the picked edges.": "对所选的边倒角。", + "Belt constraint": "皮带/链配合", + "Bevel the picked edges.": "对所选的边线倒角。", "Bezier surface": "贝塞尔曲面", "Body": "实体", "Body id": "实体 id", @@ -136,7 +136,7 @@ "Click again to delete": "再点一次删除", "Click again to delete this cell": "再点一次删除此单元", "Click an item to delete it.": "点击要删除的对象。", - "Click edges on the model to add them": "在模型上点击边即可加入", + "Click edges on the model to add them": "在模型上点击边线即可加入", "Click faces on the model to add them": "在模型上点击面即可加入", "Click or shift-click to select; drag a point or a line to move it; click inside a loop for the profile, shift-click for a hole. Click a spline to show its handles.": "点击或 Shift+点击选择;拖动点或线来移动;点击环内部设为轮廓,Shift+点击设为孔。点击样条显示它的控制柄。", "Click the centre.": "点击圆心。", @@ -192,12 +192,12 @@ "Connector id": "连接器 id", "Connector ref": "连接器引用", "Connectors of this part": "本零件的连接器", - "Constrain two component connectors to the same frame.": "把两个组件的连接器约束到同一坐标系。", - "Constrain two connectors as a prismatic slider pair.": "把两个连接器约束为移动副。", - "Constrain two connectors as a revolute axis pair.": "把两个连接器约束为转动副。", - "Constraint id": "约束 id", - "Constraints": "约束", - "Construction": "构造线", + "Constrain two component connectors to the same frame.": "把两个零部件的连接器锁定在同一坐标系(锁定配合)。", + "Constrain two connectors as a prismatic slider pair.": "把两个连接器配合为滑块配合。", + "Constrain two connectors as a revolute axis pair.": "把两个连接器配合为铰链配合。", + "Constraint id": "几何关系 id", + "Constraints": "几何关系/尺寸", + "Construction": "构造几何线", "Construction geometry (X): toggles the selected lines, or what you draw next": "构造几何(X):切换选中线条的构造属性,或接下来要画的线条", "Control points": "控制点", "Convert a face's surface (and its boundary curves) to B-splines, so the surface edits can work on it.": "把面的曲面(及其边界曲线)转换为 B 样条,以便进行曲面编辑。", @@ -216,7 +216,7 @@ "Create a Gordon Face from intersecting profile and guide edge networks.": "由相交的截面边网格和导引边网格生成 Gordon 面。", "Create a bolt along +Z with its head underside on the Z=0 plane.": "沿 +Z 创建螺栓,头部下表面位于 Z=0 平面。", "Create a box with native kernel-backed Face topology tags.": "创建带内核面拓扑标签的长方体。", - "Create a canonical right-handed placement in the active workplane.": "在当前工作平面中创建标准右手位姿。", + "Create a canonical right-handed placement in the active workplane.": "在当前基准面中创建标准右手位姿。", "Create a circular edge.": "创建圆形边。", "Create a circular face.": "创建圆形面。", "Create a circular wire.": "创建圆形线框。", @@ -243,7 +243,7 @@ "Create a point in 3D space and return it as a vertex.": "在三维空间中创建一个点,以顶点形式返回。", "Create a polyline wire from a point list.": "由点列表创建多段线线框。", "Create a radial pattern of solids.": "创建实体的环形阵列。", - "Create a recorded workplane from an origin, a normal and an x direction.": "由原点、法向和 x 方向创建一个被记录的工作平面。", + "Create a recorded workplane from an origin, a normal and an x direction.": "由原点、法向和 x 方向创建一个被记录的基准面。", "Create a rectangular face.": "创建矩形面。", "Create a rectangular wire.": "创建矩形线框。", "Create a revolved solid, with optional kernel-role-based tags.": "创建旋转实体,可选按内核角色打标签。", @@ -261,10 +261,10 @@ "Create a wire containing an arc defined by a center, radius, and angle range.": "创建一条线框,包含由圆心、半径和角度范围定义的圆弧。", "Create a wire containing an arc defined by three points.": "创建一条线框,包含由三点定义的圆弧。", "Create a wire from a list of connected edges.": "由一组相连的边创建线框。", - "Create a workplane moved and turned relative to a workplane or a named plane.": "相对于某个工作平面或命名平面平移并旋转,创建工作平面。", - "Create a workplane normal to a curve: the plane of a sweep profile.": "创建垂直于曲线的工作平面,即扫掠轮廓所在的平面。", - "Create a workplane on a planar face of the model.": "在模型的一个平面上创建工作平面。", - "Create a workplane through an axis, turned about it by an angle.": "创建过一条轴并绕它旋转一定角度的工作平面。", + "Create a workplane moved and turned relative to a workplane or a named plane.": "相对于某个基准面或命名平面平移并旋转,创建基准面。", + "Create a workplane normal to a curve: the plane of a sweep profile.": "创建垂直于曲线的基准面,即扫掠轮廓所在的平面。", + "Create a workplane on a planar face of the model.": "在模型的一个平面上创建基准面。", + "Create a workplane through an axis, turned about it by an angle.": "创建过一条轴并绕它旋转一定角度的基准面。", "Create an arc edge from a center, radius, and angle range.": "由圆心、半径和角度范围创建圆弧边。", "Create an arc edge from three points.": "由三点创建圆弧边。", "Create an elliptical face.": "创建椭圆面。", @@ -278,7 +278,7 @@ "Create an involute spur gear (straight teeth, helix angle = 0).": "创建渐开线直齿轮(直齿,螺旋角为 0)。", "Create an open loft Shell with endpoint-Wire and side-Face naming.": "创建开放的放样壳,并为端部线框和侧面命名。", "Create an oriented Solid from one valid closed Shell.": "由一个有效的闭合壳创建有方向的实体。", - "Create the workplane halfway between two parallel planar faces (a symmetry plane).": "在两个平行平面的中间创建工作平面(对称面)。", + "Create the workplane halfway between two parallel planar faces (a symmetry plane).": "在两个平行平面的中间创建基准面(对称面)。", "Curve": "曲线", "Curves": "曲线", "Cut": "切除", @@ -294,7 +294,7 @@ "Degree max": "最高阶次", "Degree min": "最低阶次", "Delete": "删除", - "Delete constraint": "删除约束", + "Delete constraint": "删除几何关系", "Delete this cell": "删除此单元", "Delete this feature": "删除此特征", "Delete {{id}}": "删除 {{id}}", @@ -319,7 +319,7 @@ "Draft planar, cylindrical or conical faces by a signed angle in degrees.": "按带符号的角度(度)对平面、圆柱面或圆锥面拔模。", "Drag an anchor (its handles follow) or a handle: each side has its own direction and pull. Hold Shift while dragging a handle to put the other one in line (smooth); S smooths the selected anchors. Shift+A: anchor mode (add/remove anchors by clicking); Delete removes the selected anchor.": "拖动锚点(控制柄跟随)或控制柄:两侧各有自己的方向和力度。拖动控制柄时按住 Shift 让另一侧与之共线(光滑);S 让选中的锚点变光滑。Shift+A:锚点模式(点击添加/删除锚点);Delete 删除选中的锚点。", "Draw a chain of lines, arcs or splines, or a closed loop: the wire is made of one.": "画一条由直线、圆弧或样条组成的链,或一个闭环:线框由其中一条构成。", - "Draw curves in space (W): lines, arcs and splines on workplanes, snapped to the model; each is an edge, one after another joined end to end (pick several to sweep along them, or to make a surface).": "在空间中绘制曲线(W):在工作平面上画直线、圆弧和样条,可吸附到模型;每条都是一个 edge,首尾相接(选中多条可以沿它们扫掠,或者构造曲面)。", + "Draw curves in space (W): lines, arcs and splines on workplanes, snapped to the model; each is an edge, one after another joined end to end (pick several to sweep along them, or to make a surface).": "在空间中绘制曲线(W):在基准面上画直线、圆弧和样条,可吸附到模型;每条都是一个 edge,首尾相接(选中多条可以沿它们扫掠,或者构造曲面)。", "Drive angle degrees": "驱动角度(度)", "Drive depth": "驱动深度", "Drive distance": "驱动距离", @@ -328,11 +328,11 @@ "Driving dimension: click to make it a reference": "驱动尺寸:点击改为参考尺寸", "Drop the edited values; back to what the source says": "丢弃修改的值,恢复为源码中的值", "Eccentricity": "偏心距", - "Edge": "边", + "Edge": "边线", "Edge a": "边 a", "Edge b": "边 b", "Edge connector": "边连接器", - "Edges": "边", + "Edges": "边线", "Edit sketch": "编辑草图", "Edit this feature": "编辑此特征", "Edit {{what}}": "编辑{{what}}", @@ -352,8 +352,8 @@ "Expose an existing connector on a direct child component.": "把直接子组件上已有的连接器公开出来。", "Extend: grow a line's end to the next entity (SDK extend_rsketch)": "延伸:把直线的一端延伸到下一个图元(SDK extend_rsketch)", "Extrude": "拉伸", - "Extrude (cut)": "拉伸(切除)", - "Extrude (join)": "拉伸(合并)", + "Extrude (cut)": "拉伸切除", + "Extrude (join)": "拉伸凸台", "Extrude a planar face until a target surface, including curved surfaces.": "把平面拉伸到目标表面为止(包括曲面)。", "Extrude a planar sketch face by a vector, with a taper in degrees.": "按向量拉伸平面草图面,并带拔模角(度)。", "Extrude face": "拉伸面", @@ -393,7 +393,7 @@ "Fit point grid": "拟合点阵", "Fit the sketch in the view (F)": "让草图充满视图(F)", "Fix": "固定", - "Fixed constraint": "固定约束", + "Fixed constraint": "锁定配合", "Flat face": "平面", "Flat face from curves": "由曲线生成平面", "Flip": "翻转", @@ -404,7 +404,7 @@ "Fold to its title": "收起为标题", "Free boundaries": "自由边界", "From": "起点", - "Gear constraint": "齿轮约束", + "Gear constraint": "齿轮配合", "Gear height": "齿轮高度", "Glue": "粘合", "Gordon surface": "Gordon 曲面", @@ -432,7 +432,7 @@ "Hide this sketch in the viewport": "在视口中隐藏此草图", "Hole": "孔", "Hole depth": "孔深", - "Hole here": "在此打孔", + "Hole here": "简单直孔", "Hole style": "孔类型", "Holes": "孔", "Hollow the body, opening the picked faces.": "把实体挖空,并打开所选的面。", @@ -481,8 +481,8 @@ "Middle": "中点", "Midpoint": "中点", "Minor radius": "短半径", - "Mirror": "镜像", - "Mirror a body in a plane, and optionally join the halves.": "以平面镜像实体,可选把两半合并。", + "Mirror": "镜向", + "Mirror a body in a plane, and optionally join the halves.": "以平面镜向实体,可选把两半合并。", "Model with buttons and dialogs: features, sketches, assemblies": "用按钮和对话框建模:特征、草图、装配", "Module": "模数", "More": "更多", @@ -571,7 +571,7 @@ "Pitch radius b": "节圆半径 b", "Place a connector of this part on the picked flat face: move and turn its frame with the handles, then add it (assemblies join parts at connectors).": "在所选平面上放置此零件的连接器:用手柄平移旋转其坐标系后添加(装配通过连接器连接零件)。", "Place a connector on the picked face with the handles": "用手柄在选中的面上放置连接器", - "Place a workplane with handles (Space): on the picked flat face, else on the active workplane, else on XY; move and turn it, then sketch on it.": "用手柄放置工作平面(空格):放在所选平面上,否则放在当前工作平面上,再否则放在 XY 上;平移旋转后即可在上面画草图。", + "Place a workplane with handles (Space): on the picked flat face, else on the active workplane, else on XY; move and turn it, then sketch on it.": "用手柄放置基准面(空格):放在所选平面上,否则放在当前基准面上,再否则放在 XY 上;平移旋转后即可在上面画草图。", "Place component": "放置组件", "Place it with the handles, name it, add it.": "用手柄摆好位置,起名,然后添加。", "Place parts, ground one, and join connector frames with joints and mates.": "放置零件、固定其中一个,并用运动副和配合连接各连接器坐标系。", @@ -587,10 +587,10 @@ "Pole count": "控制点数", "Poles": "控制点", "Polyline": "多段线", - "Press / pull": "推拉", + "Press / pull": "移动面", "Pressure angle": "压力角", "Primitives": "基本体", - "Prismatic constraint": "移动副约束", + "Prismatic constraint": "滑块配合", "Product": "产品", "Profile": "轮廓", "Profile of the wire": "线框的轮廓", @@ -617,7 +617,7 @@ "Push the sketch through the body and remove what it passes.": "把草图推入实体,去除经过的部分。", "Rack connector": "齿条连接器", "Rack height": "齿条高度", - "Rack pinion constraint": "齿轮齿条约束", + "Rack pinion constraint": "齿条小齿轮配合", "Radial pattern": "环形阵列", "Radius": "半径", "Radius: must be greater than zero": "半径:必须大于零", @@ -637,12 +637,12 @@ "Refresh parts": "刷新零件", "Refresh the list of parts": "刷新零件列表", "Remove a component grounding marker.": "取消组件的固定标记。", - "Require fully constrained": "要求完全约束", + "Require fully constrained": "要求完全定义", "Reset": "重置", "Return a semantic shape view with a canonical tag assignment.": "返回带规范标签的语义形体视图。", "Return unique closed and open free boundary wires of a Shell.": "返回壳上不重复的闭合与开放自由边界线框。", "Revert": "还原", - "Revolute constraint": "转动副约束", + "Revolute constraint": "铰链配合", "Revolve": "旋转", "Revolve sketch": "旋转草图", "Right": "右", @@ -653,7 +653,7 @@ "Roller diameter": "滚子直径", "Roller radius": "滚子半径", "Rotate": "旋转变换", - "Round the picked edges.": "对所选的边倒圆角。", + "Round the picked edges.": "对所选的边线倒圆角。", "Ruled": "直纹", "Ruled surface": "直纹面", "Ruled surface between two curves": "两条曲线之间的直纹面", @@ -679,7 +679,7 @@ "Segment → curve (edge)": "线段 → 曲线(边)", "Segment → wire": "线段 → 线框", "Select / move": "选择 / 移动", - "Select geometry, then pick a constraint on the left.": "先选择几何,再在左侧选一个约束。", + "Select geometry, then pick a constraint on the left.": "先选择几何,再在左侧选一个几何关系或尺寸。", "Select: its connectors are drawn in the viewport": "选中:在视口中显示它的连接器", "Set body appearance": "设置实体外观", "Set curve poles": "设置曲线控制点", @@ -695,7 +695,7 @@ "Shape": "形体", "Shell": "抽壳", "Shell a solid, with optional kernel-role-based face tags.": "对实体抽壳,可选按内核角色给面打标签。", - "Show constraints and diagnostics": "显示约束和诊断", + "Show constraints and diagnostics": "显示几何关系、尺寸和诊断", "Show highlight": "显示高亮", "Show the command bar": "显示命令栏", "Show the command bar (/ or Ctrl/Cmd+K)": "显示命令栏(/ 或 Ctrl/Cmd+K)", @@ -707,7 +707,7 @@ "Sketch name": "草图名称", "Sketch on face": "在面上画草图", "Sketch on the plane of {{name}}": "在 {{name}} 的平面上绘制草图", - "Sketch on the workplane {{name}}": "在工作平面 {{name}} 上绘制草图", + "Sketch on the workplane {{name}}": "在基准面 {{name}} 上绘制草图", "Sketch on the {{plane}} plane": "在 {{plane}} 平面上绘制草图", "Sketch on this face": "在此面上画草图", "Sketch profile": "草图轮廓", @@ -716,7 +716,7 @@ "Skip non intersecting": "跳过不相交的", "Snap": "吸附", "Snap to grid, points and the model's vertices (hold Alt to skip once)": "吸附到网格、点和模型顶点(按住 Alt 临时跳过)", - "Snaps to vertices, edge midpoints, workplane origins, its own points and the grid. Tab: next plane · ⌫: back": "吸附到顶点、边中点、工作平面原点、已画的点和网格。Tab:下一个平面 · ⌫:回退", + "Snaps to vertices, edge midpoints, workplane origins, its own points and the grid. Tab: next plane · ⌫: back": "吸附到顶点、边中点、基准面原点、已画的点和网格。Tab:下一个平面 · ⌫:回退", "Solid": "实体", "Solid from shell": "由壳生成实体", "Solids": "实体", @@ -763,7 +763,7 @@ "Taper": "拔模角", "Target": "目标", "Targets": "目标", - "That face is not flat: a workplane lies on a plane. Pick a flat face, or nothing to place one on the active workplane.": "这个面不是平面:工作平面必须位于平面上。请选择一个平面,或不选任何东西以放在当前工作平面上。", + "That face is not flat: a workplane lies on a plane. Pick a flat face, or nothing to place one on the active workplane.": "这个面不是平面:基准面必须位于平面上。请选择一个平面,或不选任何东西以放在当前基准面上。", "The body this feature works on (default: the last one made).": "此特征作用的实体(默认:最近创建的那个)。", "The body this solid is joined to, cut from or intersected with (default: the body so far).": "此实体要与之合并、从中切除或求交的实体(默认:当前已有的实体)。", "The face details are still loading; try again in a moment.": "面的详情仍在加载,请稍后再试。", @@ -858,13 +858,13 @@ "Wire (path / profile curve): an open chain or a closed loop, for a sweep path or a loft section": "线框(路径/轮廓曲线):开放链或闭环,用作扫掠路径或放样截面", "Wire from curves": "由曲线生成线框", "Wire from edges": "由边生成线框", - "Workplane": "工作平面", - "Workplane from axis": "由轴生成工作平面", - "Workplane from face": "由面生成工作平面", - "Workplane from selection": "由所选对象生成工作平面", - "Workplane midplane": "中间工作平面", - "Workplane normal to curve": "垂直于曲线的工作平面", - "Workplane offset": "偏移工作平面", + "Workplane": "基准面", + "Workplane from axis": "由轴生成基准面", + "Workplane from face": "由面生成基准面", + "Workplane from selection": "由所选对象生成基准面", + "Workplane midplane": "中间基准面", + "Workplane normal to curve": "垂直于曲线的基准面", + "Workplane offset": "偏移基准面", "Wrap one Solid, or several named solids, as a semantic Part.": "把一个实体(或多个具名实体)包装为语义零件。", "Write the edited values into the notebook source": "把修改的值写入 notebook 源码", "Write this B-spline as anchors with a handle on each side, keeping its shape (SDK convert_spline_to_anchors_rsketch)": "把这条 B 样条改写为两侧带控制柄的锚点形式,形状不变(SDK convert_spline_to_anchors_rsketch)", @@ -873,7 +873,7 @@ "X axis": "X 轴", "X dir": "X 方向", "X edge": "X 方向边", - "XY, XZ or YZ, the name of a workplane of the notebook, or face (the picked face).": "XY、XZ 或 YZ,notebook 中某个工作平面的名称,或 face(所选面)。", + "XY, XZ or YZ, the name of a workplane of the notebook, or face (the picked face).": "XY、XZ 或 YZ,notebook 中某个基准面的名称,或 face(所选面)。", "Y": "Y", "Y axis": "Y 轴", "a cell changed on disk while you were editing it: kept the file's version. Your unsaved text was:": "你编辑期间,这个单元在磁盘上被修改了:已保留文件中的版本。你未保存的内容是:", @@ -901,7 +901,7 @@ "asking the SDK…": "正在请求 SDK…", "assembly": "装配", "auto": "自动", - "auto h/v": "自动约束", + "auto h/v": "自动添加几何关系", "axis": "轴", "base": "基准", "belt": "皮带", @@ -929,18 +929,18 @@ "component…": "组件…", "conc": "同心", "confirm delete {{name}}": "确认删除 {{name}}", - "conflict": "冲突", - "conflicting": "冲突", + "conflict": "过定义", + "conflicting": "过定义", "connector id": "连接器 id", "connector {{id}} added": "已添加连接器 {{id}}", "connectors of {{part}}: {{error}}": "{{part}} 的连接器:{{error}}", "connectors set": "已设置连接器", "connector…": "连接器…", "constraint id \"{{id}}\" is invalid or used twice": "约束 id“{{id}}”无效或重复", - "constraints": "约束", - "constraints ({{count}})": "约束({{count}})", - "constraints need a grounded component: the solver moves everything else relative to it": "约束需要一个固定组件:求解器会相对它移动其它组件", - "construct": "构造线", + "constraints": "几何关系/尺寸", + "constraints ({{count}})": "几何关系/尺寸({{count}})", + "constraints need a grounded component: the solver moves everything else relative to it": "配合需要一个固定的零部件:求解器会相对它移动其它组件", + "construct": "构造几何线", "convert to anchors (K)": "转为锚点形式(K)", "convert: select one B-spline that has control points (a spline drawn with the spline tool already has anchors)": "转换:请选中一条控制点形式的 B 样条(用样条工具画的已经是锚点形式)", "cosmetic": "示意", @@ -974,7 +974,7 @@ "drawing plane": "绘图平面", "drive {{unit}}": "驱动 {{unit}}", "drv": "驱动", - "edge": "边", + "edge": "边线", "edges": "边数", "edit": "修改", "edit {{name}}": "编辑 {{name}}", @@ -1049,7 +1049,7 @@ "modifier": "修改", "move": "平移", "move along its own x, y, z (mm)": "沿自身 x、y、z 移动(mm)", - "moved and turned from a plane, a workplane or a face": "从平面、工作平面或面平移并旋转得到", + "moved and turned from a plane, a workplane or a face": "从平面、基准面或面平移并旋转得到", "name": "名称", "name, e.g. bracket": "名称,例如 bracket", "needs dof 0 to finish": "自由度为 0 才能完成", @@ -1097,7 +1097,7 @@ "perp": "垂直", "persp": "透视", "phase deg": "相位(度)", - "pick edges in the viewport": "请在视口中选择边", + "pick edges in the viewport": "请在视口中选择边线", "pick faces in the viewport": "请在视口中选择面", "pick in viewport": "在视口中拾取", "picked face": "所选面", @@ -1116,7 +1116,7 @@ "project is not available while a draft is in progress: finish it or press Esc first": "正在绘制时不能投影:先完成,或按 Esc", "project sketch": "投影草图", "project: there is no other sketch in this notebook to project from; finish and add another sketch first": "投影:这个 notebook 里没有其它草图可投影;请先完成并添加另一个草图", - "project: {{entities}} and {{points}} from {{from}} (construction, fixed)": "投影:从 {{from}} 引入 {{entities}} 和 {{points}}(构造线,固定)", + "project: {{entities}} and {{points}} from {{from}} (construction, fixed)": "投影:从 {{from}} 引入 {{entities}} 和 {{points}}(构造几何线,固定)", "properties": "属性", "pulley radius A": "带轮半径 A", "pulley radius B": "带轮半径 B", @@ -1133,7 +1133,7 @@ "references:": "引用:", "removed {{ids}}": "删除了 {{ids}}", "removes this solid from the body": "从已有实体中去除这个实体", - "require fully constrained": "要求完全约束", + "require fully constrained": "要求完全定义", "revert": "还原", "revolute (hinge)": "旋转(铰链)", "round": "圆形", @@ -1159,7 +1159,7 @@ "snap": "吸附", "solid": "实体", "solve": "求解", - "solved": "已求解", + "solved": "完全定义", "solved: the constraints hold (drag a joint's slider in the notebook's parameters)": "已求解:约束成立(可在 notebook 参数中拖动关节滑块)", "solving": "求解中", "solving the sketch…": "正在求解草图…", @@ -1181,7 +1181,7 @@ "the closed loop": "那个闭环", "the component id \"{{id}}\" is used twice": "组件 id“{{id}}”被重复使用", "the grounded component \"{{id}}\" is not in the assembly": "固定组件“{{id}}”不在装配中", - "the sketch has a conflict: fix the constraints marked in red": "草图有冲突:请修正标红的约束", + "the sketch has a conflict: fix the constraints marked in red": "草图过定义:请修正标红的几何关系或尺寸", "the whole model comes back once it is fixed.": "修复后会恢复完整模型。", "this part declares no connectors: type an id": "这个零件没有声明连接器:请输入 id", "this tool places nothing": "这个工具不放置任何东西", @@ -1195,8 +1195,8 @@ "turn about its own axis": "绕自身的轴旋转", "turn angle": "旋转角度", "unable to open the preview": "无法打开预览", - "under-constrained {{dof}} dof": "欠约束 {{dof}} 自由度", - "underconstrained": "欠约束", + "under-constrained {{dof}} dof": "欠定义(还有 {{dof}} 个自由度)", + "underconstrained": "欠定义", "undo": "撤销", "unfold all": "全部展开", "union": "合并", @@ -1229,10 +1229,10 @@ "{{count}} cells": "{{count}} 个单元", "{{count}} cells re-evaluated in {{time}}": "{{count}} 个单元重新计算,用时 {{time}}", "{{count}} circles": "{{count}} 个圆", - "{{count}} construction": "{{count}} 条构造线", + "{{count}} construction": "{{count}} 条构造几何线", "{{count}} curves": "{{count}} 条曲线", "{{count}} did not complete": "{{count}} 个未完成", - "{{count}} edges": "{{count}} 条边", + "{{count}} edges": "{{count}} 条边线", "{{count}} entities": "{{count}} 个图元", "{{count}} errors": "{{count}} 个错误", "{{count}} faces": "{{count}} 个面", @@ -1283,7 +1283,7 @@ "{{what}} selected: {{actions}}.": "已选中{{what}}:可{{actions}}。", "{{what}}, in the order clicked": "{{what}},按点击顺序", "{{who}}: \"{{name}}\" is not a connector name": "{{who}}:“{{name}}”不是连接器名称", - "{{who}}: a constraint joins two different components": "{{who}}:约束必须连接两个不同的组件", + "{{who}}: a constraint joins two different components": "{{who}}:配合必须连接两个不同的零部件", "{{who}}: pick the component of {{side}}": "{{who}}:请选择 {{side}} 端的组件", "{{who}}: pick the connector of {{side}}": "{{who}}:请选择 {{side}} 端的连接器", "{{who}}: the drive is a number": "{{who}}:驱动值必须是数字", From 824608e7ebc06bda787d74dca965ab5e4b28e0c0 Mon Sep 17 00:00:00 2001 From: lizaixi01 Date: Sun, 29 Nov 2026 16:44:08 +0800 Subject: [PATCH 02/55] docs(design): record why the editor's Chinese wording follows SolidWorks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DECISION: keep the term-by-term table of the change "editor i18n: the Chinese UI names things the way SolidWorks does" as a design record, so that a later reader sees which words changed, which were kept on purpose (基本体, 组件) and that behaviour differences are a separate matter. WHY: the decision is about words only, and its reasons are not visible from the diff of a translation table; the repo's rule is that a decision that outlives one commit gets a record in design-docs/. WHAT CHANGES: design-docs/editor-sw-terms.md (new; design-docs/ is git-ignored, added with -f). Checked: the table matches the 73 values the previous commit changes. Co-Authored-By: Claude Opus 5.5 --- design-docs/editor-sw-terms.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 design-docs/editor-sw-terms.md diff --git a/design-docs/editor-sw-terms.md b/design-docs/editor-sw-terms.md new file mode 100644 index 00000000..8593fcbc --- /dev/null +++ b/design-docs/editor-sw-terms.md @@ -0,0 +1,32 @@ +# Editor wording follows SolidWorks (Chinese UI) + +The editor's manual mode is used by people who learned CAD on SolidWorks. Where the editor named a thing differently, they +looked for the SolidWorks word and did not find it. The Chinese translation table (`editor-web/src/i18n/locales/zh-CN.json`) +now uses the SolidWorks Chinese terms. Only words a person reads changed: the SDK, the notebook code, the keys of the table and +everything an agent reads stay as they were, so the kernel stays agent-friendly. + +| Thing | Was | Now (SolidWorks) | +|---|---|---| +| A plane to sketch on | 工作平面 | 基准面 | +| Sketch fully determined | 已求解 | 完全定义 | +| Sketch still free to move | 欠约束 N 自由度 | 欠定义(还有 N 个自由度) | +| Sketch over-determined | 冲突 | 过定义 | +| Sketch constraints (as a group) | 约束 | 几何关系/尺寸 | +| Automatic horizontal/vertical | 自动约束 | 自动添加几何关系 | +| Construction geometry | 构造线 | 构造几何线 | +| Mirror | 镜像 | 镜向 | +| Extrude that adds | 拉伸(合并) | 拉伸凸台 | +| Extrude that removes | 拉伸(切除) | 拉伸切除 | +| Push or pull a face | 推拉 | 移动面 | +| Hole on a face | 在此打孔 | 简单直孔 | +| An edge to pick | 边 | 边线 | +| Assembly joints | …约束 | …配合(铰链、滑块、齿轮、齿条小齿轮、皮带/链、锁定) | + +Not changed on purpose: + +- **基本体** (box, cylinder, …): SolidWorks has no primitives (it sketches and extrudes), so there is no word to copy. +- **组件** for an assembly component: SolidWorks says 零部件 or 组件; both are understood. +- Behaviour that differs from SolidWorks (pick-kind chips instead of hover selection, connectors instead of face mates, no + rollback bar) is not a wording question; it is listed with the editor's open issues. + +The SolidWorks terms are the ones its Chinese releases commonly use; a few may differ slightly between versions. From 97522cbe5503e66c9858d2884f4325af1b05d89e Mon Sep 17 00:00:00 2001 From: lizaixi01 Date: Tue, 1 Dec 2026 11:29:32 +0800 Subject: [PATCH 03/55] =?UTF-8?q?editor=20i18n:=20an=20assembly=20componen?= =?UTF-8?q?t=20is=20=E9=9B=B6=E9=83=A8=E4=BB=B6,=20as=20in=20SolidWorks?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SolidWorks' Chinese help says 零部件 throughout (插入零部件, 零部件属性); the table mixed it with 组件 (review of #102). The wording note said both were SolidWorks' words; it now lists 零部件 with the other terms. Co-Authored-By: Claude Opus 5.5 --- design-docs/editor-sw-terms.md | 2 +- editor-web/src/i18n/locales/zh-CN.json | 50 +++++++++++++------------- 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/design-docs/editor-sw-terms.md b/design-docs/editor-sw-terms.md index 8593fcbc..3ed2efd2 100644 --- a/design-docs/editor-sw-terms.md +++ b/design-docs/editor-sw-terms.md @@ -21,11 +21,11 @@ everything an agent reads stay as they were, so the kernel stays agent-friendly. | Hole on a face | 在此打孔 | 简单直孔 | | An edge to pick | 边 | 边线 | | Assembly joints | …约束 | …配合(铰链、滑块、齿轮、齿条小齿轮、皮带/链、锁定) | +| A part or sub-assembly placed in an assembly | 组件 | 零部件 | Not changed on purpose: - **基本体** (box, cylinder, …): SolidWorks has no primitives (it sketches and extrudes), so there is no word to copy. -- **组件** for an assembly component: SolidWorks says 零部件 or 组件; both are understood. - Behaviour that differs from SolidWorks (pick-kind chips instead of hover selection, connectors instead of face mates, no rollback bar) is not a wording question; it is listed with the editor's open issues. diff --git a/editor-web/src/i18n/locales/zh-CN.json b/editor-web/src/i18n/locales/zh-CN.json index 35087170..000f12bc 100644 --- a/editor-web/src/i18n/locales/zh-CN.json +++ b/editor-web/src/i18n/locales/zh-CN.json @@ -173,10 +173,10 @@ "Combine with": "与之合并", "Combined with:": "与之合并:", "Command bar": "命令栏", - "Component id": "组件 id", - "Components": "组件", - "Components move away from the assembly centre; with an axis they move along it, to the side they are on.": "组件会远离装配中心移动;指定轴时,沿轴向各自所在的一侧移动。", - "Components, the grounded one, and the joints and mates between connector frames.": "组件、被固定的组件,以及连接器坐标系之间的运动副和配合。", + "Component id": "零部件 id", + "Components": "零部件", + "Components move away from the assembly centre; with an axis they move along it, to the side they are on.": "零部件会远离装配中心移动;指定轴时,沿轴向各自所在的一侧移动。", + "Components, the grounded one, and the joints and mates between connector frames.": "零部件、被固定的零部件,以及连接器坐标系之间的运动副和配合。", "Compound from assembly": "由装配生成复合体", "Compute the boolean difference of solids.": "计算实体的布尔差集。", "Compute the boolean intersection of two 2D faces.": "计算两个二维面的布尔交集。", @@ -349,7 +349,7 @@ "Every operation and drawing is written into a notebook. Create one first (it starts empty).": "所有操作和绘图都会写入 notebook。请先新建一个(新建的 notebook 是空的)。", "Every option (dialog)": "全部选项(对话框)", "Exploded view": "爆炸视图", - "Expose an existing connector on a direct child component.": "把直接子组件上已有的连接器公开出来。", + "Expose an existing connector on a direct child component.": "把直接子零部件上已有的连接器公开出来。", "Extend: grow a line's end to the next entity (SDK extend_rsketch)": "延伸:把直线的一端延伸到下一个图元(SDK extend_rsketch)", "Extrude": "拉伸", "Extrude (cut)": "拉伸切除", @@ -408,8 +408,8 @@ "Gear height": "齿轮高度", "Glue": "粘合", "Gordon surface": "Gordon 曲面", - "Ground a component at its current authored placement.": "把组件固定在当前设定的位姿上。", - "Ground component": "固定组件", + "Ground a component at its current authored placement.": "把零部件固定在当前设定的位姿上。", + "Ground component": "固定零部件", "Guide radius": "导引半径", "Guides": "导引线", "Handedness": "旋向", @@ -489,7 +489,7 @@ "Move": "移动", "Move (G)": "平移(G)", "Move a body by an offset.": "按偏移量移动实体。", - "Move an existing assembly component by replacing its placement.": "替换位姿以移动装配中已有的组件。", + "Move an existing assembly component by replacing its placement.": "替换位姿以移动装配中已有的零部件。", "Multiplicity": "重数", "N lobes": "凸瓣数", "N teeth": "齿数", @@ -497,9 +497,9 @@ "Name of the new notebook": "新 notebook 的名称", "Network surface": "网格曲面", "New body": "新建实体", - "No components. Add a part notebook of this workspace; the first one added is the ground.": "还没有组件。从工作区添加一个零件 notebook;第一个添加的会被固定。", + "No components. Add a part notebook of this workspace; the first one added is the ground.": "还没有零部件。从工作区添加一个零件 notebook;第一个添加的会被固定。", "No connectors yet. A connector is a frame (origin, x, y) an assembly joins parts by: pick a planar face and add one.": "还没有连接器。连接器是装配用来连接零件的坐标系(原点、x、y):选一个平面再添加。", - "No constraints: every component sits at its placement. A joint moves one component about a connector of another; a drive becomes a slider.": "没有约束:每个组件都在自己的位置。关节让一个组件绕另一个组件的连接器运动;驱动会成为一个滑块。", + "No constraints: every component sits at its placement. A joint moves one component about a connector of another; a drive becomes a slider.": "没有约束:每个零部件都在自己的位置。关节让一个零部件绕另一个零部件的连接器运动;驱动会成为一个滑块。", "No features yet. Add a Box or another operation from the command bar; each one becomes an ordinary cell in the notebook.": "还没有特征。从命令栏添加方块或其他操作,每个操作都会成为 notebook 中的一个普通单元。", "No notebook is open": "当前没有打开的 notebook", "No notebook is open: create one first.": "当前没有打开的 notebook:请先新建一个。", @@ -572,7 +572,7 @@ "Place a connector of this part on the picked flat face: move and turn its frame with the handles, then add it (assemblies join parts at connectors).": "在所选平面上放置此零件的连接器:用手柄平移旋转其坐标系后添加(装配通过连接器连接零件)。", "Place a connector on the picked face with the handles": "用手柄在选中的面上放置连接器", "Place a workplane with handles (Space): on the picked flat face, else on the active workplane, else on XY; move and turn it, then sketch on it.": "用手柄放置基准面(空格):放在所选平面上,否则放在当前基准面上,再否则放在 XY 上;平移旋转后即可在上面画草图。", - "Place component": "放置组件", + "Place component": "放置零部件", "Place it with the handles, name it, add it.": "用手柄摆好位置,起名,然后添加。", "Place parts, ground one, and join connector frames with joints and mates.": "放置零件、固定其中一个,并用运动副和配合连接各连接器坐标系。", "Placement": "位姿", @@ -629,14 +629,14 @@ "Rectangle → wire": "矩形 → 线框", "Redo": "重做", "Redo (Ctrl/Cmd+Shift+Z)": "重做(Ctrl/Cmd+Shift+Z)", - "Reference a connector through a component instance.": "通过组件实例引用一个连接器。", + "Reference a connector through a component instance.": "通过零部件实例引用一个连接器。", "Reference dimension: click to make it driving": "参考尺寸:点击改为驱动尺寸", "Reference direction": "参考方向", "Refit a face's surface as a B-spline of the given degrees and pole counts, or with the fewest poles that keep within ``tolerance``.": "按给定阶次和控制点数把面的曲面重新拟合为 B 样条,或用满足 ``tolerance`` 的最少控制点拟合。", "Refit an edge's curve as a B-spline of ``degree`` with ``pole_count`` poles, or with the fewest poles that keep within ``tolerance``.": "把边的曲线重新拟合为 ``degree`` 阶、``pole_count`` 个控制点的 B 样条,或用满足 ``tolerance`` 的最少控制点拟合。", "Refresh parts": "刷新零件", "Refresh the list of parts": "刷新零件列表", - "Remove a component grounding marker.": "取消组件的固定标记。", + "Remove a component grounding marker.": "取消零部件的固定标记。", "Require fully constrained": "要求完全定义", "Reset": "重置", "Return a semantic shape view with a canonical tag assignment.": "返回带规范标签的语义形体视图。", @@ -720,7 +720,7 @@ "Solid": "实体", "Solid from shell": "由壳生成实体", "Solids": "实体", - "Source component id": "源组件 id", + "Source component id": "源零部件 id", "Source connector id": "源连接器 id", "Spacing": "间距", "Sphere": "球体", @@ -769,7 +769,7 @@ "The face details are still loading; try again in a moment.": "面的详情仍在加载,请稍后再试。", "The flat face a closed loop of curves of the notebook bounds (the curves in any order; the normal says which side is up).": "由 notebook 中一圈闭合曲线围成的平面(曲线顺序不限;法向决定哪一面朝上)。", "The flat face the picked curves bound (they make a closed loop in one plane).": "选中曲线围成的平面(它们在同一平面内构成闭环)。", - "The grounded component never moves": "固定组件永远不动", + "The grounded component never moves": "固定零部件永远不动", "The model before {{step}}": "{{step}} 之前的模型", "The notebook behind the model: cells, parameters, the workspace": "模型背后的 notebook:单元、参数、工作区", "The origin's offset along the base's own x, y and normal (mm).": "原点沿基准自身的 x、y 和法向的偏移(mm)。", @@ -835,7 +835,7 @@ "Undo the last sketch edit (Ctrl/Cmd+Z)": "撤销上一次草图修改(Ctrl/Cmd+Z)", "Unfold": "展开", "Unfold every cell": "展开所有单元", - "Unground component": "取消固定组件", + "Unground component": "取消固定零部件", "Union": "合并", "Until": "直到", "Upper value": "上限值", @@ -880,7 +880,7 @@ "a free vector": "自由向量", "add": "添加", "add assembly": "添加装配", - "add component": "添加组件", + "add component": "添加零部件", "add feature": "添加特征", "added {{name}}": "已添加 {{name}}", "adding…": "正在添加…", @@ -923,10 +923,10 @@ "closed loop": "闭环", "coinc": "重合", "colin": "共线", - "comp": "组件", - "component \"{{id}}\": lowercase letters, digits and underscores, starting with a letter": "组件“{{id}}”:只能用小写字母、数字和下划线,并以字母开头", - "component id": "组件 id", - "component…": "组件…", + "comp": "零部件", + "component \"{{id}}\": lowercase letters, digits and underscores, starting with a letter": "零部件“{{id}}”:只能用小写字母、数字和下划线,并以字母开头", + "component id": "零部件 id", + "component…": "零部件…", "conc": "同心", "confirm delete {{name}}": "确认删除 {{name}}", "conflict": "过定义", @@ -939,7 +939,7 @@ "constraint id \"{{id}}\" is invalid or used twice": "约束 id“{{id}}”无效或重复", "constraints": "几何关系/尺寸", "constraints ({{count}})": "几何关系/尺寸({{count}})", - "constraints need a grounded component: the solver moves everything else relative to it": "配合需要一个固定的零部件:求解器会相对它移动其它组件", + "constraints need a grounded component: the solver moves everything else relative to it": "配合需要一个固定的零部件:求解器会相对它移动其它零部件", "construct": "构造几何线", "convert to anchors (K)": "转为锚点形式(K)", "convert: select one B-spline that has control points (a spline drawn with the spline tool already has anchors)": "转换:请选中一条控制点形式的 B 样条(用样条工具画的已经是锚点形式)", @@ -1179,8 +1179,8 @@ "tags": "标签", "tang": "相切", "the closed loop": "那个闭环", - "the component id \"{{id}}\" is used twice": "组件 id“{{id}}”被重复使用", - "the grounded component \"{{id}}\" is not in the assembly": "固定组件“{{id}}”不在装配中", + "the component id \"{{id}}\" is used twice": "零部件 id“{{id}}”被重复使用", + "the grounded component \"{{id}}\" is not in the assembly": "固定零部件“{{id}}”不在装配中", "the sketch has a conflict: fix the constraints marked in red": "草图过定义:请修正标红的几何关系或尺寸", "the whole model comes back once it is fixed.": "修复后会恢复完整模型。", "this part declares no connectors: type an id": "这个零件没有声明连接器:请输入 id", @@ -1284,7 +1284,7 @@ "{{what}}, in the order clicked": "{{what}},按点击顺序", "{{who}}: \"{{name}}\" is not a connector name": "{{who}}:“{{name}}”不是连接器名称", "{{who}}: a constraint joins two different components": "{{who}}:配合必须连接两个不同的零部件", - "{{who}}: pick the component of {{side}}": "{{who}}:请选择 {{side}} 端的组件", + "{{who}}: pick the component of {{side}}": "{{who}}:请选择 {{side}} 端的零部件", "{{who}}: pick the connector of {{side}}": "{{who}}:请选择 {{side}} 端的连接器", "{{who}}: the drive is a number": "{{who}}:驱动值必须是数字", "{{who}}: the lower limit must be below the upper one": "{{who}}:下限必须小于上限", From 8989e25078a44e6fc008ba441ad34df6b6a3223b Mon Sep 17 00:00:00 2001 From: lizaixi01 Date: Sun, 29 Nov 2026 17:09:45 +0800 Subject: [PATCH 04/55] editor: manual mode can be switched on for development with VITE_MANUAL_MODE=1 DECISION: MANUAL_MODE stays off in a release, and `VITE_MANUAL_MODE=1` (for `npm run dev` or a build) turns it on. WHY (work with the user on the editor's human interface, 2026-11-27 to 11-29): the user learns CAD through the editor's manual mode and improves it, so it had to run without editing the constant every time and without the risk of committing it switched on. The release keeps the code mode only, as the comment of this file says, until manual mode has a plan of its own. ALTERNATIVE CONSIDERED AND REJECTED: flipping the constant to true locally (it is one stray commit away from shipping). WHAT CHANGES: editor-web/src/lib/manual-mode.ts. Nothing else reads the variable; without it the editor is as before. Checked: tsc --noEmit and vitest run (331 passed) in editor-web, on this commit. Co-Authored-By: Claude Opus 5.5 --- editor-web/src/lib/manual-mode.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/editor-web/src/lib/manual-mode.ts b/editor-web/src/lib/manual-mode.ts index 50e3ac7d..8d2d225a 100644 --- a/editor-web/src/lib/manual-mode.ts +++ b/editor-web/src/lib/manual-mode.ts @@ -1,6 +1,8 @@ /** - * Manual modelling (features, sketches, assemblies by buttons and dialogs) is built but not offered: it needs a plan of - * its own before it is a release. While this is false the editor has the code mode only: no mode switch, no command - * bar, none of its keys, and the notebook is where a model is made. Nothing of manual mode is removed. + * Manual modelling (features, sketches, assemblies by buttons and dialogs) is built but not offered by default: it needs a + * plan of its own before it is a release. While this is false the editor has the code mode only: no mode switch, no + * command bar, none of its keys, and the notebook is where a model is made. Nothing of manual mode is removed. + * + * `VITE_MANUAL_MODE=1 npm run dev` (or a build made with it) turns it on, to work on it without changing the release. */ -export const MANUAL_MODE = false; +export const MANUAL_MODE = import.meta.env.VITE_MANUAL_MODE === "1"; From be3760eb5bc6f0afdb0fad18d613af7e39bcfb8d Mon Sep 17 00:00:00 2001 From: lizaixi01 Date: Sun, 29 Nov 2026 17:09:46 +0800 Subject: [PATCH 05/55] fix(editor): redo keeps a cell's id after an undo renamed it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DECISION: while an undo or redo applies its steps, those steps stay reachable by _rename, so a cell id that changes during the apply (a deleted cell brought back gets a new id) is updated in them too. WHY (found by the user on 2026-11-28: "为什么我撤销重做几次居然会报错,点不了了"): undo and redo pop the steps off both stacks before applying them. An undo that brings back a deleted cell renames its id in the stacks, but the steps being applied were on neither stack at that moment, so they kept the old id; the next redo then looked for a cell that no longer existed and failed, and every later undo or redo failed with it. WHAT CHANGES: src/simplecadapi/editor/gui_features.py (FeatureService._applying, used by undo, redo and _rename). Checked: the editor tests (test_editor_features.py) pass at the end of this series; at this commit only tsc and vitest were run (331 passed). Seen in the running editor: undoing and redoing several times no longer fails. Co-Authored-By: Claude Opus 5.5 --- src/simplecadapi/editor/gui_features.py | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/src/simplecadapi/editor/gui_features.py b/src/simplecadapi/editor/gui_features.py index bff2d9e4..fb6c4612 100644 --- a/src/simplecadapi/editor/gui_features.py +++ b/src/simplecadapi/editor/gui_features.py @@ -66,6 +66,7 @@ def __init__(self, state: Any): self._lock = threading.RLock() self._undo: list[list[dict]] = [] self._redo: list[list[dict]] = [] + self._applying: list[dict] | None = None # the steps an undo or redo is applying (off both stacks meanwhile) self._notebook: Any = None # -- reading ---------------------------------------------------------------------------------------------------- @@ -515,8 +516,12 @@ def undo(self) -> dict[str, Any]: if not self._undo: raise GuiError("nothing to undo") steps = self._undo.pop() - for step in reversed(steps): - self._apply(step, forward=False) + self._applying = steps # off both stacks while it runs: _rename must still reach it + try: + for step in reversed(steps): + self._apply(step, forward=False) + finally: + self._applying = None self._redo.append(steps) return self._result(None, [], "undo") @@ -526,8 +531,12 @@ def redo(self) -> dict[str, Any]: if not self._redo: raise GuiError("nothing to redo") steps = self._redo.pop() - for step in steps: - self._apply(step, forward=True) + self._applying = steps # off both stacks while it runs: _rename must still reach it + try: + for step in steps: + self._apply(step, forward=True) + finally: + self._applying = None self._undo.append(steps) return self._result(None, [], "redo") @@ -701,7 +710,7 @@ def _apply(self, step: dict, *, forward: bool) -> None: raise GuiError(f"cannot {'redo' if forward else 'undo'}: the notebook changed since ({exc})", conflict=exc.conflict) from exc def _rename(self, old: str, new: str) -> None: - for steps in (*self._undo, *self._redo): + for steps in (*self._undo, *self._redo, *([self._applying] if self._applying else [])): for step in steps: if step.get("id") == old: step["id"] = new From 5284f9ddf3f064101ad6a9d251c4eee318a3ef87 Mon Sep 17 00:00:00 2001 From: lizaixi01 Date: Sun, 29 Nov 2026 17:09:47 +0800 Subject: [PATCH 06/55] fix(editor): a slider value kept into its params cell no longer breaks undo and redo DECISION: when the person keeps a value tuned on a slider (the editor rewrites the params cell), the undo history takes the new code as that cell's code (FeatureService.follow), so undo and redo go on from it. An edit made in the code itself is not followed: undoing over that is still refused, never forced. WHY (the user, 2026-11-28, after dragging a slider and pressing undo): the history remembered the params cell's code from when the feature was made, so after a slider change undo said the code had been changed elsewhere and stopped. A slider is part of the GUI, not an edit somewhere else; the refusal is meant for edits in code, which must not be overwritten. ALTERNATIVE CONSIDERED AND REJECTED: recording each slider change as an undo step of its own (the slider already has its own reset, and one drag would fill the history). WHAT CHANGES: gui_features.py (follow), server.py (_commit calls it with each changed cell's old and new code), and the test test_numbers_tuned_on_the_sliders_and_kept_do_not_break_undo_and_redo. Checked: test_editor_features.py at the end of this series (see the last commit); tsc and vitest on this commit (331 passed). Co-Authored-By: Claude Opus 5.5 --- src/simplecadapi/editor/gui_features.py | 16 +++++++++ src/simplecadapi/editor/server.py | 2 ++ test/test_editor_features.py | 43 +++++++++++++++++++++++++ 3 files changed, 61 insertions(+) diff --git a/src/simplecadapi/editor/gui_features.py b/src/simplecadapi/editor/gui_features.py index fb6c4612..3c8a69ce 100644 --- a/src/simplecadapi/editor/gui_features.py +++ b/src/simplecadapi/editor/gui_features.py @@ -540,6 +540,22 @@ def redo(self) -> dict[str, Any]: self._undo.append(steps) return self._result(None, [], "redo") + def follow(self, changes: Mapping[str, tuple[str, str]]) -> None: + """Cells the person changed through the GUI outside a command (a slider's value kept into its params cell): the + history takes the new code as the cell's, so undo and redo go on from it. ``changes`` maps a cell id to + (old code, new code); a step remembers a cell's code only where it equals the old one. An edit made in the code + itself does not come here: undoing over that is still refused, never forced.""" + with self._lock: + for steps in (*self._undo, *self._redo): + for step in steps: + change = changes.get(step.get("id", "")) + if change is None: + continue + old, new = change + for key in ("code", "old", "new"): + if isinstance(step.get(key), str) and step[key].strip() == old.strip(): + step[key] = new + # -- internals ------------------------------------------------------------------------------------------------------ def _sync(self) -> None: """History belongs to one open notebook.""" diff --git a/src/simplecadapi/editor/server.py b/src/simplecadapi/editor/server.py index b99e7a65..369bed62 100644 --- a/src/simplecadapi/editor/server.py +++ b/src/simplecadapi/editor/server.py @@ -1565,6 +1565,8 @@ def _commit(self, kernel: MarimoKernel, names: list[str], *, revert: bool) -> No for cell_id, code in changed.items(): kernel.edit_cell(cell_id, code) kernel.wait_idle() + # the person kept the value through the GUI: undo and redo follow it (an edit in the code is not this) + self.features.follow({cell_id: (codes[cell_id], code) for cell_id, code in changed.items()}) for name in names: saved.pop(name, None) write_saved_params(config, saved) diff --git a/test/test_editor_features.py b/test/test_editor_features.py index b8a39a93..ff8750b0 100644 --- a/test/test_editor_features.py +++ b/test/test_editor_features.py @@ -291,6 +291,49 @@ def test_the_commands_add_edit_undo_and_redo_against_the_real_editor(tmp_path): server.should_exit = True +def test_numbers_tuned_on_the_sliders_and_kept_do_not_break_undo_and_redo(tmp_path): + """Keeping a slider's value writes it into the params cell; that is the person's own GUI edit, so undo and redo follow it.""" + import threading + + import uvicorn + + from simplecadapi.editor.server import WorkspaceState, create_app + from simplecadapi.editor.templates import create_notebook + from simplecadapi.runtime.params import write_saved_params + + path = create_notebook(tmp_path, "bracket", "sample") + state = WorkspaceState(tmp_path) + state.port = 17733 + server = uvicorn.Server(uvicorn.Config(create_app(state), port=state.port, log_level="error")) + threading.Thread(target=server.run, daemon=True).start() + state.hub.attach_loop(__import__("asyncio").new_event_loop()) + try: + state.start_kernel(path) + service = state.features + before = [c["code"] for c in state.cells] + service.add({"spec": "hole", "values": {"position": [0.0, 0.0, 10.0], "direction": "-z", "diameter": 8.0, "depth": 12.0}}) + _wait_idle(state) + # the slider moved and the person kept it (Enter): the value goes into the source + write_saved_params(state.config, {"HOLE_DIAMETER": 9.0}) + state._commit(state.kernel, ["HOLE_DIAMETER"], revert=False) + _wait_idle(state) + assert "default=9.0" in path.read_text() + + service.undo() + _wait_idle(state) + assert [c["code"] for c in state.cells] == before + service.redo() + _wait_idle(state) + assert "default=9.0" in path.read_text() # redo brings back what was kept, not the first default + service.undo() + _wait_idle(state) + assert [c["code"] for c in state.cells] == before + finally: + if state.kernel is not None: + state.kernel.stop() + server.should_exit = True + + def test_a_blank_notebook_gets_its_product_with_the_first_feature(tmp_path): import threading From 4b3556bb3718b1abcba18c48c99c5631a591e34d Mon Sep 17 00:00:00 2001 From: lizaixi01 Date: Sun, 29 Nov 2026 17:09:48 +0800 Subject: [PATCH 07/55] fix(editor): the left panel never scrolls sideways DECISION: the left panel's content box clips (overflow-clip) instead of hiding overflow, so it cannot be scrolled. WHY (seen on 2026-11-28): a panel that was not shown still got focus, and the box holding both scrolled sideways by 156 px, so the tree appeared cut off at the left. overflow-hidden still lets a box scroll by focus; overflow-clip does not. WHAT CHANGES: one class in editor-web/src/App.tsx. Checked: tsc and vitest on this commit (331 passed); in the running editor the tree no longer shifts. Co-Authored-By: Claude Opus 5.5 --- editor-web/src/App.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/editor-web/src/App.tsx b/editor-web/src/App.tsx index 0b10ca16..f2d67682 100644 --- a/editor-web/src/App.tsx +++ b/editor-web/src/App.tsx @@ -1739,7 +1739,7 @@ export function App() { ))} -
+
{!MANUAL_MODE ? ( panelFor("code") ) : ( From 654594aaccb184519d8213dbdb52f191877a9348 Mon Sep 17 00:00:00 2001 From: lizaixi01 Date: Sun, 29 Nov 2026 17:09:50 +0800 Subject: [PATCH 08/55] feat(editor): export says where the files went, writes STEP and STL, and offers save as MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DECISION: the header has an Export button; export writes the package and, next to it, STEP and STL (each on its own, so one failing keeps the other), then a dialog shows the folder, a copy button, and "Save as…" for each file (the browser's save dialog, or a download where that is not allowed). WHY (the user, 2026-11-27: "导出成功了,但是不知道导出到哪了…就像另存为一样"): the export only wrote a status line with a path. A person exports to take the model elsewhere (another CAD program, a slicer), which needs STEP or STL and needs to know where the file is. WHAT CHANGES: components/ExportDialog.tsx (new), Header.tsx (button), App.tsx (state), server.py (_export writes STEP and STL and remembers the files; GET /api/export/file/{name} serves only those names), Chinese strings. Checked: tsc and vitest on this commit (334 passed); exported in the running editor; the save dialog falls back to a download in the embedded browser, where it is refused. Co-Authored-By: Claude Opus 5.5 --- editor-web/src/App.tsx | 13 ++ editor-web/src/components/ExportDialog.tsx | 133 +++++++++++++++++++++ editor-web/src/components/Header.tsx | 17 ++- editor-web/src/i18n/locales/zh-CN.json | 18 ++- src/simplecadapi/editor/server.py | 26 +++- 5 files changed, 204 insertions(+), 3 deletions(-) create mode 100644 editor-web/src/components/ExportDialog.tsx diff --git a/editor-web/src/App.tsx b/editor-web/src/App.tsx index f2d67682..84ac1c10 100644 --- a/editor-web/src/App.tsx +++ b/editor-web/src/App.tsx @@ -37,6 +37,7 @@ import { viewPose } from "@/lib/sketch-plane"; import * as THREE from "three"; import { addConnectorFrame, connectorFrameFromFace, setConnectorsCommand, setRef } from "@/lib/assembly"; import { useAssemblyEditor, useConnectorDraft } from "@/lib/useAssembly"; +import { ExportDialog, type ExportState } from "@/components/ExportDialog"; import { Header } from "@/components/Header"; import { Inspector } from "@/components/Inspector"; import { SketchMode, type FaceCheck, type SketchAfter, type SketchSession } from "@/components/sketch/SketchMode"; @@ -137,6 +138,7 @@ export function App() { const [currentPath, setCurrentPath] = useState(null); const [kernelAlive, setKernelAlive] = useState(false); const [status, setStatus] = useState(() => t("Connecting…")); + const [exportState, setExportState] = useState(null); const [params, setParams] = useState([]); const [cells, setCells] = useState([]); @@ -464,6 +466,8 @@ export function App() { if (envelope["error"]) { log.push("error", envelope["error"]); setLoading(null); + const message = envelope["error"]; + setExportState((current) => (current?.phase === "working" ? { phase: "error", message } : current)); } } else if (typeof envelope["info"] === "string") { setStatus(t(envelope["info"])); @@ -476,6 +480,10 @@ export function App() { } else if (typeof envelope["exported"] === "string") { setStatus(t("exported {{path}}", { path: envelope["exported"] })); log.push("ok", t("exported {{file}}", { file: envelope["exported"] })); + setLoading(null); + const dir = envelope["export_dir"]; + const files = envelope["export_files"]; + if (typeof dir === "string" && Array.isArray(files)) setExportState({ phase: "done", dir, files: files.map(String) }); } else if (typeof envelope["created"] === "string") { setStatus(t("created {{path}}", { path: envelope["created"] })); log.push("ok", t("created {{name}}", { name: envelope["created"] })); @@ -1711,7 +1719,12 @@ export function App() { status={status} themePreference={theme.preference} onTheme={theme.cycle} + onExport={() => { + setExportState({ phase: "working" }); + socketRef.current?.send({ type: "export.request" }); + }} /> + setExportState(null)} />
diff --git a/editor-web/src/components/ExportDialog.tsx b/editor-web/src/components/ExportDialog.tsx new file mode 100644 index 00000000..8ce4fb2c --- /dev/null +++ b/editor-web/src/components/ExportDialog.tsx @@ -0,0 +1,133 @@ +import { Check, Copy, Download, Loader2 } from "lucide-react"; +import { useState } from "react"; + +import { Button } from "@/components/ui/button"; +import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { useI18n } from "@/i18n"; + +/** Where an export stands: being made, written (the folder and the file names), or failed. */ +export type ExportState = { phase: "working" } | { phase: "done"; dir: string; files: string[] } | { phase: "error"; message: string } | null; + +/** What each kind of file is for, in a person's words (English keys of the translation table). */ +const PURPOSE: Record = { + step: "STEP: opens in other CAD programs (SolidWorks, FreeCAD, Fusion 360)", + stl: "STL: for a 3D printer's slicer", + scadpkg: "SimpleCAD package: the full model with its history, for this SDK", +}; + +type SavePicker = (options: { suggestedName: string }) => Promise<{ createWritable: () => Promise<{ write: (data: Blob) => Promise; close: () => Promise }> }>; + +/** Save one exported file where the person chooses: the system "save as" dialog where the browser has one, else a download. */ +async function saveAs(name: string): Promise<"saved" | "downloaded" | "cancelled"> { + const picker = (window as unknown as { showSaveFilePicker?: SavePicker }).showSaveFilePicker; + if (picker) { + let handle; + try { + handle = await picker({ suggestedName: name }); + } catch { + return "cancelled"; // the person closed the dialog + } + try { + const response = await fetch(`/api/export/file/${encodeURIComponent(name)}`); + if (!response.ok) throw new Error(`HTTP ${response.status}`); + const writable = await handle.createWritable(); + await writable.write(await response.blob()); + await writable.close(); + return "saved"; + } catch { + // some browsers (an embedded one) show the dialog but refuse the write: a plain download still works + } + } + const link = document.createElement("a"); + link.href = `/api/export/file/${encodeURIComponent(name)}`; + link.download = name; + link.click(); + return "downloaded"; +} + +/** The export dialog: it waits for the files, then says where they were written and offers "save as" for each. */ +export function ExportDialog({ state, onClose }: { state: ExportState; onClose: () => void }) { + const { t } = useI18n(); + const [copied, setCopied] = useState(false); + const [saved, setSaved] = useState>({}); + const open = state !== null; + const copy = (text: string) => { + void navigator.clipboard?.writeText(text).then(() => { + setCopied(true); + window.setTimeout(() => setCopied(false), 1500); + }); + }; + const save = (name: string) => { + saveAs(name) + .then((outcome) => { + if (outcome === "saved") setSaved((s) => ({ ...s, [name]: t("Saved where you chose.") })); + if (outcome === "downloaded") setSaved((s) => ({ ...s, [name]: t("Downloaded: look in the browser's downloads (usually the Downloads folder).") })); + }) + .catch(() => setSaved((s) => ({ ...s, [name]: t("Could not save it here. Use the folder above: the file is already there.") }))); + }; + return ( + { + if (!next) { + setSaved({}); + onClose(); + } + }} + > + + + {t("Export")} + + {state?.phase === "working" && t("Making the files from the model; this takes a few seconds…")} + {state?.phase === "done" && t("The files were written to this folder (next to the notebook):")} + {state?.phase === "error" && t("The export failed:")} + + + {state?.phase === "working" && ( +
+ + {t("building the package")} +
+ )} + {state?.phase === "error" &&

{state.message}

} + {state?.phase === "done" && ( +
+
+ {state.dir} + +
+
    + {state.files.map((name) => { + const kind = name.split(".").pop()?.toLowerCase() ?? ""; + return ( +
  • +
    +
    +
    {name}
    + {PURPOSE[kind] &&
    {t(PURPOSE[kind])}
    } +
    + +
    + {saved[name] &&

    {saved[name]}

    } +
  • + ); + })} +
+
+ )} + + + +
+
+ ); +} diff --git a/editor-web/src/components/Header.tsx b/editor-web/src/components/Header.tsx index b4f1bb62..2ae382df 100644 --- a/editor-web/src/components/Header.tsx +++ b/editor-web/src/components/Header.tsx @@ -1,4 +1,4 @@ -import { Languages, Monitor, Moon, Sun } from "lucide-react"; +import { Download, Languages, Monitor, Moon, Sun } from "lucide-react"; import type { ThemePreference } from "@/lib/theme"; @@ -15,6 +15,7 @@ export function Header({ status, themePreference, onTheme, + onExport, }: { notebook: string | null; kind: string | null; @@ -22,6 +23,8 @@ export function Header({ status: string; themePreference: ThemePreference; onTheme: () => void; + /** Write STEP and STL of the model next to the notebook (in out/); absent: no button. */ + onExport?: () => void; }) { const { t, language } = useI18n(); const failing = status.startsWith("error"); @@ -48,6 +51,18 @@ export function Header({ > {status} + {onExport && ( + + )} ))}
)}
); - }), + })} + + ); +} + +const SLOT_WORD: Record = { faces: "face", edges: "edge", vertices: "vertex", face: "face", edge: "edge" }; +const STATE_WORD: Record = { ok: "still there", merged: "still there (merged)", split: "split into pieces: pick one", lost: "can't be found" }; + +/** A failed step in a person's words: what did not work, what to do, and the SDK's own message folded away. */ +function FailureNote({ name, texts }: { name: string; texts: string[] }) { + const parts = sdkErrorParts(texts); + return ( +
+

{t("{{name}} did not work", { name })}

+

{t("Try changing its numbers, or select the part and ask the AI to find out why and fix it.")}

+ {parts.full && ( +
+ {t("Details (the SDK's message, in English)")} +
+ {parts.what &&

{parts.what}

} + {parts.causes.length > 0 &&

{t("Possible causes:")} {parts.causes.join("; ")}

} + {parts.fixes.length > 0 &&

{t("How to fix:")} {parts.fixes.join("; ")}

} + {!parts.what &&

{parts.full.slice(0, 600)}

} +
+
)}
); @@ -139,6 +164,23 @@ export function FeatureTree({ }; const stale = state.product && state.tip && state.product.body !== state.tip ? state.product : null; + + /** A feature's name for a person: its operation in their language (Box → 方块), numbered when the operation repeats; a + * feature with a written name (`# 名称:…`) shows that, other code its own name. */ + const plainName = (feature: (typeof state.features)[number]): string => { + if (feature.title) return feature.title; // the name written for a person (# 名称:…), by the agent or by hand + const spec = feature.gui ? catalog?.specs.find((item) => item.id === feature.gui?.spec) : undefined; + if (!spec) return feature.slug; + const label = t(plainLabel(spec.id, spec.label)); + const same = state.features.filter((other) => other.gui?.spec === feature.gui?.spec); + return same.length > 1 ? `${label} ${same.indexOf(feature) + 1}` : label; + }; + /** The name of the feature that makes a body (bodies are code names). */ + const bodyName = (body: string): string => { + const maker = state.features.find((feature) => feature.makes.includes(body)); + return maker ? plainName(maker) : body; + }; + return (
@@ -148,10 +190,10 @@ export function FeatureTree({ {stale && state.tip && (
- {t("The product still builds from")} {stale.body}. + {t("The finished part is the result of {{name}}.", { name: bodyName(stale.body) })}
)} @@ -160,22 +202,24 @@ export function FeatureTree({ {t("{{count}} solids are open, and a Part holds exactly one solid. Choose the part:", { count: state.open.length })} {state.open.map((body) => ( ))}
)} - {error &&
{error}
} + {error &&
{plainGuiError(error)}
} {state.features.length === 0 ? (

{t("No features yet. Add a Box or another operation from the command bar; each one becomes an ordinary cell in the notebook.")}

) : (
    - {state.features.map((feature) => { + {state.features.map((feature, position) => { const spec = feature.gui ? catalog?.specs.find((item) => item.id === feature.gui?.spec) : undefined; - const problem = errorText(feature); - const productBodies = state.product ? [state.product.body] : []; - const isProduct = feature.makes.some((name) => productBodies.includes(name)); + const name = plainName(feature); + const failed = isFailed(feature); + // No "product" badge: in a chain of steps the part is the last one, as in any feature tree. When it is not, or when + // several solids are open, the banners above the list say so and offer the choice (the product is chosen, never + // guessed: design-docs/part-holds-one-solid.md). const canEdit = Boolean(feature.gui && spec); const Icon = feature.gui ? FEATURE_ICONS[feature.gui.spec] : CODE_FEATURE_ICON; const sketch = sketches?.infos.find((info) => info.cell === feature.cell); @@ -198,26 +242,26 @@ export function FeatureTree({ >
    - {feature.index} + {position + 1} {Icon ? : } - {feature.slug} - {isProduct && ( - - {t("product")} - - )} - {t(feature.role)} + {name} {sketch && sketch.usedBy.length > 0 && ( {t("used")} )} - {spec ? plainLabel(spec.id, spec.label) : feature.gui ? feature.gui.spec.replace(/_/g, " ") : "code"}
    - ${feature.makes.join(", ")}`}> - {feature.reads.length > 0 ? feature.reads.join(", ") : "start"} {feature.makes.length > 0 ? feature.makes.join(", ") : "no body"} - + {(() => { + // what the step does, in a sentence: its written note (# 说明:…), else what it builds on + const lineage = feature.reads.length > 0 ? t("builds on {{names}}", { names: feature.reads.map((body) => `「${bodyName(body)}」`).join(t(", ")) }) : t("a new shape"); + const text = feature.note || lineage; + return ( + + {text} + + ); + })()} {sketch && ( )} - + @@ -256,9 +300,9 @@ export function FeatureTree({
    - {problem &&

    {problem}

    } - {problem && onRepairRef && spec?.slots.some((slot) => slot.kind === "select") && ( - onRepairRef(feature.cell, slot, index, choice)} /> + {failed && } + {failed && onRepairRef && spec?.slots.some((slot) => slot.kind === "select") && ( + onRepairRef(feature.cell, slot, index, choice)} /> )} ); diff --git a/editor-web/src/components/Header.tsx b/editor-web/src/components/Header.tsx index 2ae382df..f653fce4 100644 --- a/editor-web/src/components/Header.tsx +++ b/editor-web/src/components/Header.tsx @@ -35,8 +35,8 @@ export function Header({ {notebook ? ( - {notebook} - {kind && kind !== "helper" && {kind}} + {notebook.replace(/\.py$/, "")} + {kind && kind !== "helper" && {t(kind)}} ) : ( {t("no notebook")} diff --git a/editor-web/src/components/ParamControl.tsx b/editor-web/src/components/ParamControl.tsx index 182503fc..dcc37fe1 100644 --- a/editor-web/src/components/ParamControl.tsx +++ b/editor-web/src/components/ParamControl.tsx @@ -1,4 +1,5 @@ import { useEffect, useRef, useState } from "react"; +import { plainParamLabel } from "@/lib/plain-label"; import { Slider } from "@/components/ui/slider"; import { cn } from "@/lib/utils"; @@ -43,7 +44,7 @@ export function ParamControl({ useEffect(() => { if (!dragging.current) setDrag(null); }, [param.value]); - const label = param.label || param.id; + const label = plainParamLabel(param.label || param.id); const title = [param.comment, ...(param.issues ?? [])].filter(Boolean).join("\n") || undefined; const ink = param.modified ? "text-focus" : "text-name"; if (param.control === "toggle") { diff --git a/editor-web/src/components/PartialModel.tsx b/editor-web/src/components/PartialModel.tsx index f618e763..4d8a1bb9 100644 --- a/editor-web/src/components/PartialModel.tsx +++ b/editor-web/src/components/PartialModel.tsx @@ -9,8 +9,13 @@ import { t } from "@/i18n"; * whole model replaces it; the failing step is marked in the feature tree as well. */ /** `docked`: laid out in a column of floating cards (manual mode) instead of pinned to the viewport's top right corner. */ export function PartialNotice({ partial, titles, docked = false }: { partial: PartialModel; titles: ReadonlyMap; docked?: boolean }) { - const { title, reason, after } = useMemo(() => describePartial(partial, titles), [partial, titles]); + const { after } = useMemo(() => describePartial(partial, titles), [partial, titles]); const full = partial.failed.map((cell) => cell.error).filter(Boolean).join("\n"); + // in a person's words: which step, that it did not work; the program's own message stays in the tooltip and the tree + const first = partial.failed[0]; + const step = titles.get(first.cell) || first.name; + const title = t("Showing the model before「{{step}}」", { step }); + const reason = first.status === "interrupted" ? t("「{{step}}」was stopped", { step }) : t("「{{step}}」did not work", { step }); return (
    ; picked: Record; refs?: Record } | null; makes: string[]; @@ -169,7 +172,7 @@ export function refTone(state: RefState): "pass" | "warn" | "fail" { export function candidateLabel(candidate: RefCandidate): string { const at = candidate.center.map((v) => (Math.abs(v) < 5e-5 ? "0" : String(Math.round(v * 10) / 10))).join(", "); const unit = candidate.kind === "edge" ? "mm" : "mm²"; - return `${candidate.geom_type.toLowerCase()} at (${at}), ${Math.round(candidate.size * 10) / 10} ${unit}`; + return t("{{kind}} at ({{at}}), {{size}} {{unit}}", { kind: t(candidate.geom_type.toLowerCase()), at, size: Math.round(candidate.size * 10) / 10, unit }); } /** How the references of a feature resolve now (asks the kernel). */ diff --git a/editor-web/src/lib/plain-label.test.ts b/editor-web/src/lib/plain-label.test.ts new file mode 100644 index 00000000..0112a47b --- /dev/null +++ b/editor-web/src/lib/plain-label.test.ts @@ -0,0 +1,47 @@ +import { beforeAll, describe, expect, it } from "vitest"; + +import i18n from "@/i18n"; +import { plainParamLabel, sdkErrorParts } from "@/lib/plain-label"; + +describe("plainParamLabel", () => { + beforeAll(async () => { + await i18n.changeLanguage("zh-CN"); + }); + + it("uses the table for a whole label", () => { + expect(plainParamLabel("Width (x)")).toBe("宽度(x)"); + }); + + it("translates a point coordinate's label as its slot label and axis", () => { + expect(plainParamLabel("Bottom face centre x")).toBe(`${i18n.t("Bottom face centre")} x`); + expect(plainParamLabel("Bottom face centre x")).not.toContain("Bottom"); + }); + + it("keeps a label it cannot translate", () => { + expect(plainParamLabel("frobnicate z")).toBe("frobnicate z"); + }); +}); + +describe("sdkErrorParts", () => { + const full = [ + "SimpleCADError: Operation: shell_rsolid", + "What happened: Failed to apply the shell operation.", + "Possible causes:", + "- The thickness is not a positive finite scalar.", + "- No valid faces were selected for removal.", + "How to fix:", + "- Use a positive shell thickness.", + "Technical details: ValueError: Shell failed", + ].join("\n"); + + it("reads what happened, the causes and the fixes from the fullest text, not a cut-short one", () => { + const parts = sdkErrorParts(["SimpleCADError: Operation: shell_rsolid\nWhat happened: F", full]); + expect(parts.what).toBe("Failed to apply the shell operation."); + expect(parts.causes).toEqual(["The thickness is not a positive finite scalar.", "No valid faces were selected for removal."]); + expect(parts.fixes).toEqual(["Use a positive shell thickness."]); + }); + + it("gives nothing it cannot find", () => { + expect(sdkErrorParts(["boom"])).toMatchObject({ what: null, causes: [], fixes: [], full: "boom" }); + }); +}); diff --git a/editor-web/src/lib/plain-label.ts b/editor-web/src/lib/plain-label.ts new file mode 100644 index 00000000..cd17f956 --- /dev/null +++ b/editor-web/src/lib/plain-label.ts @@ -0,0 +1,46 @@ +import { t } from "@/i18n"; + +/** A parameter's label in the person's language: the label itself when the table has it, else a point coordinate's label + * ("Bottom face centre x": the slot's label, then its axis) as the translated slot label and the axis. */ +export function plainParamLabel(label: string): string { + const whole = t(label); + if (whole !== label) return whole; + const axis = /^(.*\S) ([xyz])$/.exec(label); + if (axis) { + const base = t(axis[1]); + if (base !== axis[1]) return `${base} ${axis[2]}`; + } + return label; +} + +/** A feature command's error in the person's words where it is a known one (undo or redo refused because the code changed + * since, or nothing left to undo), else the error as the server said it. */ +export function plainGuiError(message: string): string { + const refused = /^cannot (undo|redo): the notebook changed since/.exec(message); + if (refused) + return refused[1] === "undo" + ? t("Can't undo: this step's code was changed somewhere else afterwards (in the code, or by the AI). Undo stopped so it won't overwrite that change.") + : t("Can't redo: the code was changed somewhere else afterwards (in the code, or by the AI). Redo stopped so it won't overwrite that change."); + if (message === "nothing to undo") return t("Nothing left to undo."); + if (message === "nothing to redo") return t("Nothing left to redo."); + return message; +} + +/** The parts of the SDK's error messages ("What happened:", "Possible causes:", "How to fix:"), from the fullest of the + * texts a failed step carries (one of them may be a cut-short summary, a single letter). */ +export function sdkErrorParts(texts: readonly string[]): { what: string | null; causes: string[]; fixes: string[]; full: string } { + const full = [...texts].sort((a, b) => b.length - a.length)[0] ?? ""; + const lines = full.split("\n").map((line) => line.trim()); + const what = lines.find((line) => line.startsWith("What happened:"))?.replace("What happened:", "").trim() || null; + const list = (title: string) => { + const at = lines.indexOf(title); + if (at === -1) return []; + const out: string[] = []; + for (const line of lines.slice(at + 1)) { + if (!line.startsWith("-")) break; + out.push(line.replace(/^-\s*/, "")); + } + return out; + }; + return { what, causes: list("Possible causes:"), fixes: list("How to fix:"), full }; +} diff --git a/src/simplecadapi/editor/gui_features.py b/src/simplecadapi/editor/gui_features.py index 3c8a69ce..023395e7 100644 --- a/src/simplecadapi/editor/gui_features.py +++ b/src/simplecadapi/editor/gui_features.py @@ -27,6 +27,14 @@ _PARAMS_FOR = re.compile(r"^#\s*-{3,}\s*params:\s*(?P[a-z][a-z0-9_]*)\s*-{3,}\s*$") _PRODUCT_BODY = re.compile(r"(\bbody\s*=\s*)([A-Za-z_][A-Za-z0-9_]*)") _ROLES_WITH_BODIES = {"build", "add", "subtract", "modifier", "intersect"} +_TITLE = re.compile(r"^\s*#\s*(?:名称|name)\s*[::]\s*(?P.+?)\s*$", re.MULTILINE | re.IGNORECASE) +_NOTE = re.compile(r"^\s*#\s*(?:说明|note)\s*[::]\s*(?P.+?)\s*$", re.MULTILINE | re.IGNORECASE) + + +def feature_words(code: str) -> tuple[str | None, str | None]: + """A feature cell's name and one-line note for a person, from its ``# 名称:…`` and ``# 说明:…`` comment lines.""" + title, note = _TITLE.search(code), _NOTE.search(code) + return (title.group("text") if title else None), (note.group("text") if note else None) class GuiError(Exception): @@ -129,6 +137,8 @@ def snapshot(self) -> dict[str, Any]: "index": index + 1, "slug": head.slug, "role": head.role, + "title": feature_words(code)[0], + "note": feature_words(code)[1], "gui": { "spec": gui["spec"], "values": gui.get("values", {}), From ccb02317de3bf5ce712e3d49f1b6e6bf746adae6 Mon Sep 17 00:00:00 2001 From: lizaixi01 Date: Sun, 29 Nov 2026 17:09:52 +0800 Subject: [PATCH 10/55] editor: clicking the picked tree row again or the empty list clears the pick MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DECISION: in the feature tree, a click on the row that is already picked, or on the empty part of the list, clears the pick (Ctrl/Cmd keeps adding and removing as before). WHY (the user, 2026-11-28: "按草图点击左边区域是无法取消选中的"): once a sketch row was picked there was no way to unpick it from the tree, which every file list and feature tree allows. WHAT CHANGES: lib/tree-click.ts (new, with tests: the decision as a pure function), FeatureTree.tsx (onSelect takes null). Checked: tsc and vitest on this commit (343 passed); tried in the running editor. Co-Authored-By: Claude Opus 5.5 --- editor-web/src/components/FeatureTree.tsx | 16 +++++++++++++--- editor-web/src/lib/tree-click.test.ts | 22 ++++++++++++++++++++++ editor-web/src/lib/tree-click.ts | 9 +++++++++ 3 files changed, 44 insertions(+), 3 deletions(-) create mode 100644 editor-web/src/lib/tree-click.test.ts create mode 100644 editor-web/src/lib/tree-click.ts diff --git a/editor-web/src/components/FeatureTree.tsx b/editor-web/src/components/FeatureTree.tsx index 2c4a3d79..5b31a252 100644 --- a/editor-web/src/components/FeatureTree.tsx +++ b/editor-web/src/components/FeatureTree.tsx @@ -1,4 +1,5 @@ import { Eye, EyeOff, Pencil, Redo2, Trash2, Undo2 } from "lucide-react"; +import { rowClick } from "@/lib/tree-click"; import { plainGuiError, sdkErrorParts } from "@/lib/plain-label"; import { useEffect, useRef, useState } from "react"; @@ -122,7 +123,8 @@ export type TreeSketches = { selected: readonly string[]; hover: string | null; onToggleHidden: (name: string) => void; - onSelect: (name: string, additive: boolean) => void; + /** Pick a row (Ctrl/Cmd: add or take out); null clears the selection. */ + onSelect: (name: string | null, additive: boolean) => void; onHover: (name: string | null) => void; }; @@ -207,8 +209,14 @@ export function FeatureTree({ ))}
    )} - {error &&
    {plainGuiError(error)}
    } + { + // a click on the empty part of the list (not on a row or a button) clears what the tree picked + if (!(event.target as HTMLElement).closest("li, button")) sketches?.onSelect(null, false); + }} + > {state.features.length === 0 ? (

    {t("No features yet. Add a Box or another operation from the command bar; each one becomes an ordinary cell in the notebook.")}

    ) : ( @@ -237,7 +245,9 @@ export function FeatureTree({ onMouseLeave={sketch ? () => sketches?.onHover(null) : undefined} onClick={sketch ? (event) => { if ((event.target as HTMLElement).closest("button")) return; - sketches?.onSelect(sketch.name, event.ctrlKey || event.metaKey); + const click = rowClick(sketch.name, sketches?.selected ?? [], event.ctrlKey || event.metaKey); + if (click.kind === "clear") sketches?.onSelect(null, false); // the picked row again: nothing picked + else sketches?.onSelect(sketch.name, click.additive); } : undefined} >
    diff --git a/editor-web/src/lib/tree-click.test.ts b/editor-web/src/lib/tree-click.test.ts new file mode 100644 index 00000000..73b960f4 --- /dev/null +++ b/editor-web/src/lib/tree-click.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "vitest"; + +import { rowClick } from "@/lib/tree-click"; + +describe("rowClick", () => { + it("clears the selection when the only picked row is clicked again", () => { + expect(rowClick("sketch", ["sketch"], false)).toEqual({ kind: "clear" }); + }); + + it("picks a row that is not picked", () => { + expect(rowClick("sketch", [], false)).toEqual({ kind: "pick", additive: false }); + expect(rowClick("sketch", ["path"], false)).toEqual({ kind: "pick", additive: false }); + }); + + it("picks the clicked row alone when several are picked", () => { + expect(rowClick("sketch", ["sketch", "path"], false)).toEqual({ kind: "pick", additive: false }); + }); + + it("leaves Ctrl/Cmd+click to the additive pick", () => { + expect(rowClick("sketch", ["sketch"], true)).toEqual({ kind: "pick", additive: true }); + }); +}); diff --git a/editor-web/src/lib/tree-click.ts b/editor-web/src/lib/tree-click.ts new file mode 100644 index 00000000..4d7b887d --- /dev/null +++ b/editor-web/src/lib/tree-click.ts @@ -0,0 +1,9 @@ +/** What a click on a row of the feature tree does to the selection, the way every file list does it: a plain click on the one + * row already picked clears the selection, a plain click on another row picks that row alone, and Ctrl/Cmd+click adds or takes + * out the row (the caller's additive pick). */ +export type RowClick = { kind: "clear" } | { kind: "pick"; additive: boolean }; + +export function rowClick(name: string, selected: readonly string[], additive: boolean): RowClick { + if (!additive && selected.length === 1 && selected[0] === name) return { kind: "clear" }; + return { kind: "pick", additive }; +} From 4992faecbe8d34ccdc08c35d7825523c2a6bd488 Mon Sep 17 00:00:00 2001 From: lizaixi01 Date: Sun, 29 Nov 2026 17:09:54 +0800 Subject: [PATCH 11/55] editor: every slider has a box to type its value in MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DECISION: ParamControl shows the number box by default (editable = true); a caller that wants a bare slider passes false. WHY (the user, 2026-11-28: "这个拖动应该改成可以输入,这样更方便"): a person who knows the number (a 40 mm plate) types it rather than drags to it; the box existed but only in the operation panel. WHAT CHANGES: the default of one prop in components/ParamControl.tsx. Checked: tsc and vitest on this commit (343 passed); typed values in the running editor. Co-Authored-By: Claude Opus 5.5 --- editor-web/src/components/ParamControl.tsx | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/editor-web/src/components/ParamControl.tsx b/editor-web/src/components/ParamControl.tsx index dcc37fe1..dbae416a 100644 --- a/editor-web/src/components/ParamControl.tsx +++ b/editor-web/src/components/ParamControl.tsx @@ -29,10 +29,11 @@ export type ParamMeta = { export function ParamControl({ param, forwardParam, - editable = false, + editable = true, }: { param: ParamMeta; - /** A slider also has a box to type the value in (the operation panel: exact values matter while tuning). */ + /** A slider also has a box to type the value in (on by default: a person who knows the number types it rather than drags to + * it); false leaves the slider alone. */ editable?: boolean; /** `now`: send at once (a click, a release) instead of when the changes settle. */ forwardParam: (id: string, value: ParamValue, now?: boolean) => void; From 437950b65b332a964a51a973159abc31352e59cd Mon Sep 17 00:00:00 2001 From: lizaixi01 Date: Sun, 29 Nov 2026 17:09:55 +0800 Subject: [PATCH 12/55] editor: the inspector measures what is picked (sizes, and between two picks: distance and angle) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DECISION: the inspector shows for each picked item what it is and its measures (a plane face's area and normal, a cylinder's diameter, an edge's length…), with a copy button for each number; for two picks it shows the distance between parallel faces, the angle, the centre distance and the offsets, for more the totals. The ids and raw properties stay, folded under "Details (for the AI and developers)". While an item's details load it shows nothing rather than "nothing to measure". WHY (the user, 2026-11-28: "检查器里的东西也非常看不懂,都是英文,我想先看看 onshape 或者 sw 是怎么做的"): the inspector listed entity ids and a JSON tree. SolidWorks' Measure tool and Onshape's measure panel show the measures of the picked geometry and, for two picks, the distance and angle between them; that is what a person picks things to find out. WHAT CHANGES: lib/measure.ts (new, pure, 9 tests), components/Inspector.tsx, Chinese strings. Checked: tsc and vitest on this commit (352 passed); picked faces and edges of a flange in the running editor. Co-Authored-By: Claude Opus 5.5 --- editor-web/src/components/Inspector.tsx | 98 +++++++++++++---- editor-web/src/i18n/locales/zh-CN.json | 40 ++++++- editor-web/src/lib/measure.test.ts | 96 +++++++++++++++++ editor-web/src/lib/measure.ts | 133 ++++++++++++++++++++++++ 4 files changed, 344 insertions(+), 23 deletions(-) create mode 100644 editor-web/src/lib/measure.test.ts create mode 100644 editor-web/src/lib/measure.ts diff --git a/editor-web/src/components/Inspector.tsx b/editor-web/src/components/Inspector.tsx index 8285369e..f07cf52f 100644 --- a/editor-web/src/components/Inspector.tsx +++ b/editor-web/src/components/Inspector.tsx @@ -3,6 +3,7 @@ import { ScrollArea } from "@/components/ui/scroll-area"; import { JsonTree } from "@/components/JsonTree"; import type { SelectionItem } from "@/lib/selection"; import { MANUAL_MODE } from "@/lib/manual-mode"; +import { measureItem, measureMany, measurePair, type MeasureRow } from "@/lib/measure"; import { t } from "@/i18n"; /** Right-hand inspector: what is selected in the viewport, each item with @@ -41,29 +42,49 @@ export function Inspector({ selection, sketches = [] }: { selection: SelectionIt ))} - {selection.map((item) => ( -
  • -
    - {item.kind} - - {item.variable} - -
    -
    - - - {item.definitionId && } -
    - {item.pending &&

    {t("loading details…")}

    } - {(item.properties || item.geometry) && ( -
    - {item.properties && } - {item.geometry && } - {item.tags && item.tags.length > 0 && } -
    - )} + {selection.length >= 2 && selection.every((item) => !item.pending) && ( +
  • +

    {selection.length === 2 ? t("Between the two") : t("Altogether")}

    +
  • - ))} + )} + {selection.map((item) => { + const measured = measureItem(item); + const title = measured.titleValues + ? t(measured.title, { kind: t(measured.titleValues.kind), way: t(measured.titleValues.way) }) + : t(measured.title); + return ( +
  • +
    + {t(item.kind)} + {item.pending ? t("loading details…") : title} +
    + {/* while the details load there is nothing to measure yet: say nothing rather than "nothing to measure" */} + {!item.pending && ( +
    + +
    + )} + {/* what the code and the AI use: kept, out of the way */} +
    + {t("Details (for the AI and developers)")} +
    + + + + {item.definitionId && } +
    + {(item.properties || item.geometry) && ( +
    + {item.properties && } + {item.geometry && } + {item.tags && item.tags.length > 0 && } +
    + )} +
    +
  • + ); + })}
)}
@@ -71,6 +92,39 @@ export function Inspector({ selection, sketches = [] }: { selection: SelectionIt ); } +/** Measured numbers: a label, the value with its unit, and a button that copies the plain number. */ +function Rows({ rows }: { rows: MeasureRow[] }) { + if (!rows.length) return

{t("Nothing to measure here")}

; + return ( +
+ {rows.map((row) => ( +
+
{t(row.label)}
+
+ {row.value} {row.unit && {row.unit}} +
+ {row.copy && ( + + )} +
+ ))} +
+ ); +} + function Line({ label, value }: { label: string; value: string }) { return (
diff --git a/editor-web/src/i18n/locales/zh-CN.json b/editor-web/src/i18n/locales/zh-CN.json index cfd64276..e9ec7891 100644 --- a/editor-web/src/i18n/locales/zh-CN.json +++ b/editor-web/src/i18n/locales/zh-CN.json @@ -64,7 +64,7 @@ "An empty workspace. Start with a part: a notebook that builds one solid.": "工作区是空的。先建一个零件:一个构建单个实体的 notebook。", "Anchor mode": "锚点模式", "Anchor mode (Shift+A, with a B-spline picked): a click on its curve adds an anchor, a click on an inner anchor removes it (SDK insert/remove_spline_anchor_rsketch); Esc leaves": "锚点模式(选中 B 样条后按 Shift+A):点击曲线添加锚点,点击内部锚点删除它(SDK insert/remove_spline_anchor_rsketch);Esc 退出", - "Angle": "角度", + "Angle": "夹角", "Angle about the edge": "绕边的角度", "Angle arc → curve (edge)": "角度圆弧 → 曲线(边)", "Angle arc → wire": "角度圆弧 → 线框", @@ -1317,9 +1317,47 @@ "builds on {{names}}": "在{{names}}的基础上", "a new shape": "新建一个形状", "This step was written as code (by the AI or by hand): to change it, leave the AI a comment, or edit it in code mode": "这一步是用代码写的(AI 写的或手写的):想改它,就选中后给 AI 留言,或者在代码模式里改", + "Between the two": "两者之间", + "Altogether": "合计", + "Details (for the AI and developers)": "详细数据(给 AI 和开发者)", + "variable": "变量名", + "Nothing to measure here": "这里没有可测量的数值", + "Copy": "复制", + "{{kind}} · {{way}}": "{{kind}} · {{way}}", + "Cylindrical face": "圆柱面", + "Spherical face": "球面", + "Ring face": "圆环面", + "Curved face": "曲面", + "facing up (+Z)": "朝上(+Z)", + "facing down (−Z)": "朝下(−Z)", + "facing +X": "朝 +X", + "facing −X": "朝 −X", + "facing +Y": "朝 +Y", + "facing −Y": "朝 −Y", + "slanted": "斜面", + "Straight edge": "直线边线", + "Circle": "圆", + "Arc": "圆弧", + "Curved edge": "曲线边线", + "Component": "组件", + "Area": "面积", + "Size": "大小", + "Size (X × Y × Z)": "尺寸(X × Y × Z)", + "Volume": "体积", + "Surface area": "表面积", + "Centre of mass": "重心", + "Position": "位置", + "Distance between the faces": "两面距离", + "Centre distance": "中心距离", + "ΔX / ΔY / ΔZ": "ΔX / ΔY / ΔZ", + "Total area": "总面积", + "Total length": "总长度", "vertex": "顶点", + "component": "组件", "{{kind}} at ({{at}}), {{size}} {{unit}}": "{{kind}},位置 ({{at}}),{{size}} {{unit}}", + "cylinder": "圆柱面", "bspline": "自由曲面", + "sphere": "球面", "{{what}} {{n}}: {{state}}": "第 {{n}} 个{{what}}:{{state}}", "still there": "还在", "still there (merged)": "还在(被合并了)", diff --git a/editor-web/src/lib/measure.test.ts b/editor-web/src/lib/measure.test.ts new file mode 100644 index 00000000..1abe5f5f --- /dev/null +++ b/editor-web/src/lib/measure.test.ts @@ -0,0 +1,96 @@ +import { describe, expect, it } from "vitest"; + +import { facing, fmt, measureItem, measureMany, measurePair, type MeasureItem } from "@/lib/measure"; + +const topFace: MeasureItem = { + kind: "face", + properties: { area: 1200, centroid: [0, 0, 20], bounds: { min: [-20, -15, 20], max: [20, 15, 20] } }, + geometry: { type: "plane", normal: [0, 0, 1] }, +}; +const bottomFace: MeasureItem = { + kind: "face", + properties: { area: 1200, centroid: [0, 0, 0], bounds: { min: [-20, -15, 0], max: [20, 15, 0] } }, + geometry: { type: "plane", normal: [0, 0, -1] }, +}; +const sideFace: MeasureItem = { + kind: "face", + properties: { area: 600, centroid: [20, 0, 10] }, + geometry: { type: "plane", normal: [1, 0, 0] }, +}; + +describe("fmt", () => { + it("keeps two decimals at most and drops -0", () => { + expect(fmt(12.3456)).toBe("12.35"); + expect(fmt(40)).toBe("40"); + expect(fmt(-0.001)).toBe("0"); + }); +}); + +describe("facing", () => { + it("names an axis direction and calls anything else slanted", () => { + expect(facing([0, 0, 1])).toBe("facing up (+Z)"); + expect(facing([0, 0, -2])).toBe("facing down (−Z)"); + expect(facing([0.7, 0, 0.7])).toBe("slanted"); + }); +}); + +describe("measureItem", () => { + it("gives a flat face its direction, area, size and centre", () => { + const m = measureItem(topFace); + expect(m.titleValues).toEqual({ kind: "Flat face", way: "facing up (+Z)" }); + expect(m.rows.map((r) => [r.label, r.value])).toEqual([ + ["Area", "1200"], + ["Size", "40 × 30"], + ["Centre", "(0, 0, 20)"], + ]); + }); + + it("gives a hole's wall its diameter", () => { + const m = measureItem({ kind: "face", properties: { area: 754 }, geometry: { type: "cylinder", radius: 6 } }); + expect(m.title).toBe("Cylindrical face"); + expect(m.rows[0]).toMatchObject({ label: "Diameter", value: "12" }); + }); + + it("tells a full circle from an arc, and gives a straight edge its length", () => { + expect(measureItem({ kind: "edge", properties: { length: 2 * Math.PI * 6 }, geometry: { type: "circle", radius: 6 } }).title).toBe("Circle"); + expect(measureItem({ kind: "edge", properties: { length: Math.PI * 6 }, geometry: { type: "circle", radius: 6 } }).title).toBe("Arc"); + const line = measureItem({ kind: "edge", properties: { length: 40 }, geometry: { type: "line" } }); + expect(line.title).toBe("Straight edge"); + expect(line.rows[0]).toMatchObject({ label: "Length", value: "40" }); + }); + + it("gives a solid its size, volume and surface area", () => { + const m = measureItem({ kind: "solid", properties: { bounds: { min: [-20, -15, 0], max: [20, 15, 20] }, volume: 24000, surface_area: 5200 } }); + expect(m.rows.map((r) => [r.label, r.value])).toEqual([ + ["Size (X × Y × Z)", "40 × 30 × 20"], + ["Volume", "24000"], + ["Surface area", "5200"], + ]); + }); +}); + +describe("measurePair", () => { + it("measures two parallel faces: the distance between them, no angle, and the centre offset", () => { + const rows = Object.fromEntries(measurePair(topFace, bottomFace).map((r) => [r.label, r.value])); + expect(rows["Distance between the faces"]).toBe("20"); + expect(rows.Angle).toBe("0"); + expect(rows["Centre distance"]).toBe("20"); + expect(rows["ΔX / ΔY / ΔZ"]).toBe("0 / 0 / 20"); + }); + + it("gives two faces at a right angle their angle and no face distance", () => { + const rows = Object.fromEntries(measurePair(topFace, sideFace).map((r) => [r.label, r.value])); + expect(rows.Angle).toBe("90"); + expect(rows["Distance between the faces"]).toBeUndefined(); + }); +}); + +describe("measureMany", () => { + it("adds up the faces' area and the edges' length", () => { + const rows = measureMany([topFace, bottomFace, sideFace, { kind: "edge", properties: { length: 40 } }]); + expect(rows.map((r) => [r.label, r.value])).toEqual([ + ["Total area", "3000"], + ["Total length", "40"], + ]); + }); +}); diff --git a/editor-web/src/lib/measure.ts b/editor-web/src/lib/measure.ts new file mode 100644 index 00000000..28c1ac01 --- /dev/null +++ b/editor-web/src/lib/measure.ts @@ -0,0 +1,133 @@ +/** What picked geometry measures, in a person's words: the inspector's top block (Onshape-style: picking is measuring). + * + * Built from what a pick already carries (properties: bounds, area, length, volume, surface_area, centroid, position; + * geometry: type, normal, radius), so nothing is asked of the kernel. Two items give the distance between their centres + * with its X/Y/Z parts, and for two flat faces the angle between them and, when they are parallel, the distance between the + * planes; more items give the total area or length. Words are English keys of the translation table. */ + +export type MeasureItem = { kind: string; properties?: Record | null; geometry?: Record | null }; +/** One line: `label` and `unit` are translation keys; `value` is the number as shown; `copy` the plain number to copy. */ +export type MeasureRow = { label: string; value: string; unit?: string; copy?: string }; +export type Measured = { title: string; titleValues?: Record; rows: MeasureRow[] }; + +type V3 = [number, number, number]; + +const vec = (value: unknown): V3 | null => + Array.isArray(value) && value.length >= 3 && value.slice(0, 3).every((n) => typeof n === "number" && Number.isFinite(n)) ? [value[0], value[1], value[2]] : null; +const num = (value: unknown): number | null => (typeof value === "number" && Number.isFinite(value) ? value : null); +const sub = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; +const dot = (a: V3, b: V3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; +const norm = (a: V3) => Math.hypot(a[0], a[1], a[2]); + +/** A number for a person: at most two decimals, no trailing zeros, no "-0". */ +export function fmt(value: number): string { + const rounded = Math.round(value * 100) / 100; + return String(Object.is(rounded, -0) ? 0 : rounded); +} + +const row = (label: string, value: number, unit?: string): MeasureRow => ({ label, value: fmt(value), unit, copy: fmt(value) }); + +/** Which way a flat face points, when it points along an axis (Z is up in this editor). */ +export function facing(normal: V3 | null): string | null { + if (!normal) return null; + const n = norm(normal); + if (!(n > 0)) return null; + const [x, y, z] = normal.map((c) => c / n); + const sides: [number, string][] = [ + [z, "facing up (+Z)"], [-z, "facing down (−Z)"], [x, "facing +X"], [-x, "facing −X"], [y, "facing +Y"], [-y, "facing −Y"], + ]; + const best = sides.find(([c]) => c > 0.999); + return best ? best[1] : "slanted"; +} + +function center(item: MeasureItem): V3 | null { + return vec(item.properties?.centroid) ?? vec(item.properties?.position) ?? vec(item.geometry?.position); +} + +function extents(item: MeasureItem): V3 | null { + const bounds = item.properties?.bounds as { min?: unknown; max?: unknown } | undefined; + const min = vec(bounds?.min); + const max = vec(bounds?.max); + return min && max ? sub(max, min) : null; +} + +/** One picked item: what it is and its key numbers. */ +export function measureItem(item: MeasureItem): Measured { + const p = item.properties ?? {}; + const g = item.geometry ?? {}; + const type = typeof g.type === "string" ? g.type : ""; + const radius = num(g.radius); + const rows: MeasureRow[] = []; + const middle = center(item); + if (item.kind === "face") { + const area = num(p.area); + if (type === "cylinder" && radius !== null) rows.push(row("Diameter", radius * 2, "mm")); + if (type === "sphere" && radius !== null) rows.push(row("Diameter", radius * 2, "mm")); + if (area !== null) rows.push(row("Area", area, "mm²")); + const size = extents(item); + if (size && type === "plane") { + const sides = size.filter((d) => d > 1e-6); + if (sides.length === 2) rows.push({ label: "Size", value: `${fmt(sides[0])} × ${fmt(sides[1])}`, unit: "mm" }); + } + if (middle) rows.push({ label: "Centre", value: `(${middle.map(fmt).join(", ")})`, unit: "mm" }); + const kind = { plane: "Flat face", cylinder: "Cylindrical face", sphere: "Spherical face", torus: "Ring face" }[type] ?? "Curved face"; + const way = type === "plane" ? facing(vec(g.normal)) : null; + return { title: way ? "{{kind}} · {{way}}" : kind, titleValues: way ? { kind, way } : undefined, rows }; + } + if (item.kind === "edge") { + const length = num(p.length); + const full = radius !== null && length !== null && Math.abs(length - 2 * Math.PI * radius) < 1e-3 * Math.max(1, length); + if (type === "circle" && radius !== null) rows.push(row("Diameter", radius * 2, "mm")); + if (length !== null) rows.push(row("Length", length, "mm")); + if (middle) rows.push({ label: "Centre", value: `(${middle.map(fmt).join(", ")})`, unit: "mm" }); + const kind = type === "line" ? "Straight edge" : type === "circle" ? (full ? "Circle" : "Arc") : "Curved edge"; + return { title: kind, rows }; + } + if (item.kind === "solid" || item.kind === "component") { + const size = extents(item); + if (size) rows.push({ label: "Size (X × Y × Z)", value: size.map(fmt).join(" × "), unit: "mm", copy: size.map(fmt).join(" × ") }); + const volume = num(p.volume); + if (volume !== null) rows.push(row("Volume", volume, "mm³")); + const surface = num(p.surface_area); + if (surface !== null) rows.push(row("Surface area", surface, "mm²")); + if (middle) rows.push({ label: "Centre of mass", value: `(${middle.map(fmt).join(", ")})`, unit: "mm" }); + return { title: item.kind === "component" ? "Component" : "Solid", rows }; + } + if (item.kind === "vertex") { + if (middle) rows.push({ label: "Position", value: `(${middle.map(fmt).join(", ")})`, unit: "mm" }); + return { title: "Point", rows }; + } + return { title: item.kind, rows }; +} + +/** Two picked items: the distance between their centres and its parts; two flat faces add their angle, and the distance + * between them when they are parallel. */ +export function measurePair(a: MeasureItem, b: MeasureItem): MeasureRow[] { + const rows: MeasureRow[] = []; + const ca = center(a); + const cb = center(b); + const na = a.geometry?.type === "plane" ? vec(a.geometry?.normal) : null; + const nb = b.geometry?.type === "plane" ? vec(b.geometry?.normal) : null; + if (na && nb && norm(na) > 0 && norm(nb) > 0) { + const cos = Math.min(1, Math.abs(dot(na, nb)) / (norm(na) * norm(nb))); + const angle = (Math.acos(cos) * 180) / Math.PI; + if (angle < 0.01 && ca && cb) rows.push(row("Distance between the faces", Math.abs(dot(sub(cb, ca), na)) / norm(na), "mm")); + rows.push(row("Angle", angle, "°")); + } + if (ca && cb) { + const d = sub(cb, ca); + rows.push(row("Centre distance", norm(d), "mm")); + rows.push({ label: "ΔX / ΔY / ΔZ", value: d.map((c) => fmt(Math.abs(c))).join(" / "), unit: "mm", copy: d.map((c) => fmt(Math.abs(c))).join(" / ") }); + } + return rows; +} + +/** Three or more items: the total area of the faces and the total length of the edges among them. */ +export function measureMany(items: readonly MeasureItem[]): MeasureRow[] { + const area = items.filter((i) => i.kind === "face").reduce((sum, i) => sum + (num(i.properties?.area) ?? 0), 0); + const length = items.filter((i) => i.kind === "edge").reduce((sum, i) => sum + (num(i.properties?.length) ?? 0), 0); + const rows: MeasureRow[] = []; + if (area > 0) rows.push(row("Total area", area, "mm²")); + if (length > 0) rows.push(row("Total length", length, "mm")); + return rows; +} From 5ec30060b31778ac3c5ed6d7ddb6833e37fb8678 Mon Sep 17 00:00:00 2001 From: lizaixi01 Date: Sun, 29 Nov 2026 17:09:56 +0800 Subject: [PATCH 13/55] editor: the floating cards can be dragged out of each other's way and stay on screen MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DECISION: the inspector (by its header) and the notice under it (anywhere on it) can be dragged; where each was put is remembered in this browser, two quick presses put it back, and a card is always kept at least partly on screen (also when a remembered place no longer fits the window). A drag the system breaks off ends. WHY (the user, 2026-11-29: "我希望这两个框能拖动,要不然就会像现在这样挤成一堆"): the inspector, the partial-model notice and the AI panel sat in the same corner and covered each other. The code review of 2026-11-29 found that a card could be dragged out of reach for good and that a cancelled drag never ended; both are handled here. ALTERNATIVE CONSIDERED AND REJECTED: reusing lib/useDraggable.ts, which centres dialogs and has a different contract. WHAT CHANGES: lib/useFloatingDrag.ts (new; clampToView is pure and tested), FloatingPanels.tsx, the inspector header as the handle. Checked: tsc and vitest on this commit (355 passed); in the running editor a card placed off screen came back on reload. Co-Authored-By: Claude Opus 5.5 --- editor-web/src/components/FloatingPanels.tsx | 16 ++- editor-web/src/components/Inspector.tsx | 8 +- editor-web/src/i18n/locales/zh-CN.json | 1 + editor-web/src/lib/useFloatingDrag.test.ts | 24 ++++ editor-web/src/lib/useFloatingDrag.ts | 121 +++++++++++++++++++ 5 files changed, 165 insertions(+), 5 deletions(-) create mode 100644 editor-web/src/lib/useFloatingDrag.test.ts create mode 100644 editor-web/src/lib/useFloatingDrag.ts diff --git a/editor-web/src/components/FloatingPanels.tsx b/editor-web/src/components/FloatingPanels.tsx index b57007ef..2a13c29c 100644 --- a/editor-web/src/components/FloatingPanels.tsx +++ b/editor-web/src/components/FloatingPanels.tsx @@ -1,6 +1,7 @@ import { useState, type ReactNode } from "react"; import { ChevronsRight, ScanSearch } from "lucide-react"; +import { useFloatingDrag } from "@/lib/useFloatingDrag"; import { useSizeTransition } from "@/lib/useSizeTransition"; import { cn } from "@/lib/utils"; import { t } from "@/i18n"; @@ -55,12 +56,19 @@ export function FloatingPanels({ }) { const [inspectorOpen, setInspectorOpen] = useRemembered("sca.floating.inspector"); const inspectorBox = useSizeTransition(inspectorOpen); + // the person moves these out of each other's way: the inspector by its header, the notice anywhere on it + const inspectorDrag = useFloatingDrag("sca.floating.inspector.at"); + const noticeDrag = useFloatingDrag("sca.floating.notice.at", { anywhere: true }); return (
{!task && leftNotice &&
{leftNotice}
}
{ + inspectorBox.current = element; + inspectorDrag.bind.ref(element); + }} className={cn(CARD, "relative flex flex-col overflow-hidden", inspectorOpen ? "max-h-[70%] w-full" : "hover:bg-accent")} data-testid={inspectorOpen ? "floating-inspector" : undefined} > @@ -84,7 +92,11 @@ export function FloatingPanels({ )}
- {rightNotice &&
{rightNotice}
} + {rightNotice && ( +
+ {rightNotice} +
+ )}
{!task && (
diff --git a/editor-web/src/components/Inspector.tsx b/editor-web/src/components/Inspector.tsx index f07cf52f..b0446a4b 100644 --- a/editor-web/src/components/Inspector.tsx +++ b/editor-web/src/components/Inspector.tsx @@ -13,9 +13,11 @@ export function Inspector({ selection, sketches = [] }: { selection: SelectionIt const count = selection.length + sketches.length; return (
-
- {t("selection")} - {count > 0 && {count}} +
+ {t("selection")} + + {count > 0 && {count}} +
{count === 0 ? ( diff --git a/editor-web/src/i18n/locales/zh-CN.json b/editor-web/src/i18n/locales/zh-CN.json index e9ec7891..63aef98a 100644 --- a/editor-web/src/i18n/locales/zh-CN.json +++ b/editor-web/src/i18n/locales/zh-CN.json @@ -1354,6 +1354,7 @@ "Total length": "总长度", "vertex": "顶点", "component": "组件", + "Drag to move · double-click to put it back": "拖动可移动 · 双击放回原处", "{{kind}} at ({{at}}), {{size}} {{unit}}": "{{kind}},位置 ({{at}}),{{size}} {{unit}}", "cylinder": "圆柱面", "bspline": "自由曲面", diff --git a/editor-web/src/lib/useFloatingDrag.test.ts b/editor-web/src/lib/useFloatingDrag.test.ts new file mode 100644 index 00000000..0563629a --- /dev/null +++ b/editor-web/src/lib/useFloatingDrag.test.ts @@ -0,0 +1,24 @@ +import { describe, expect, it } from "vitest"; + +import { clampToView } from "@/lib/useFloatingDrag"; + +const view = { width: 1440, height: 900 }; +// the inspector as the layout puts it: against the right edge, below the top bar +const inspector = { left: 1130, top: 156, width: 300, height: 400 }; + +describe("clampToView", () => { + it("leaves an offset that keeps the card on screen as it is", () => { + expect(clampToView({ x: -400, y: 200 }, inspector, view)).toEqual({ x: -400, y: 200 }); + }); + + it("stops a card at the right edge from being pushed out to the right", () => { + // the right-hand limit is relative to the card: it may go only until 48 px of it are left on screen + expect(clampToView({ x: 600, y: 0 }, inspector, view).x).toBe(1440 - 48 - 1130); + }); + + it("stops a card going out to the left, above the window, or below it", () => { + const kept = clampToView({ x: -5000, y: -5000 }, inspector, view); + expect(kept).toEqual({ x: 48 - 1130 - 300, y: -156 }); + expect(clampToView({ x: 0, y: 5000 }, inspector, view).y).toBe(900 - 48 - 156); + }); +}); diff --git a/editor-web/src/lib/useFloatingDrag.ts b/editor-web/src/lib/useFloatingDrag.ts new file mode 100644 index 00000000..6a3e8df7 --- /dev/null +++ b/editor-web/src/lib/useFloatingDrag.ts @@ -0,0 +1,121 @@ +import { useCallback, useRef, useState, type CSSProperties, type PointerEvent } from "react"; + +/** How far a floating card is moved from where the layout puts it (px). */ +export type Offset = { x: number; y: number }; +/** Where the card sits with no offset (its layout box), and the window. */ +export type Box = { left: number; top: number; width: number; height: number }; + +/** The offset kept so the card stays reachable: at least `keep` px of it on screen left and right, its top (where the handle + * is) never above the window and at least `keep` px above its bottom. */ +export function clampToView(offset: Offset, base: Box, view: { width: number; height: number }, keep = 48): Offset { + const clamp = (v: number, low: number, high: number) => Math.min(Math.max(v, low), Math.max(low, high)); + return { + x: clamp(offset.x, keep - base.left - base.width, view.width - keep - base.left), + y: clamp(offset.y, -base.top, view.height - keep - base.top), + }; +} + +function read(key: string): Offset { + try { + const value = JSON.parse(window.localStorage.getItem(key) ?? "null") as Offset | null; + return value && Number.isFinite(value.x) && Number.isFinite(value.y) ? value : { x: 0, y: 0 }; + } catch { + return { x: 0, y: 0 }; + } +} + +function save(key: string, offset: Offset): void { + try { + window.localStorage.setItem(key, JSON.stringify(offset)); + } catch { + // storage blocked: the card stays where it is until the page reloads + } +} + +const view = () => ({ width: window.innerWidth, height: window.innerHeight }); + +/** A floating card the person can drag by its handle (an element inside it marked `data-drag-handle`, or the whole card when + * `anywhere`), remembered in this browser and always kept on screen. Buttons and fields inside the handle keep their clicks; + * two quick presses on the handle put the card back. Spread `bind` on the card. */ +export function useFloatingDrag(key: string, { anywhere = false }: { anywhere?: boolean } = {}) { + const [offset, setOffset] = useState(() => read(key)); + const offsetRef = useRef(offset); + offsetRef.current = offset; + const drag = useRef<{ from: { x: number; y: number }; start: Offset; base: Box; id: number; moving: boolean } | null>(null); + // the pointer is captured on press (so the card follows it anywhere), which retargets the browser's double-click to the + // card: the double-click that puts it back is told here instead, from two presses on the handle close in time and place + const lastPress = useRef<{ t: number; x: number; y: number } | null>(null); + const putBack = () => { + setOffset({ x: 0, y: 0 }); + save(key, { x: 0, y: 0 }); + }; + const onHandle = (target: EventTarget | null): boolean => { + const element = target as HTMLElement | null; + if (!element || element.closest("button, input, textarea, select, a, [role=slider]")) return false; + return anywhere || !!element.closest("[data-drag-handle]"); + }; + /** The card's layout box: where it is now, less the offset it is moved by. */ + const baseOf = (element: HTMLElement, by: Offset): Box => { + const r = element.getBoundingClientRect(); + return { left: r.left - by.x, top: r.top - by.y, width: r.width, height: r.height }; + }; + // A remembered offset from another window size could put the card out of reach: pull it back in once it is on screen. + const ref = useCallback( + (element: HTMLElement | null) => { + if (!element) return; + const current = offsetRef.current; + if (!current.x && !current.y) return; + const kept = clampToView(current, baseOf(element, current), view()); + if (kept.x !== current.x || kept.y !== current.y) { + setOffset(kept); + save(key, kept); + } + }, + [key], + ); + const finish = (element: HTMLElement, pointerId: number) => { + const d = drag.current; + if (!d) return; + drag.current = null; + if (element.hasPointerCapture?.(pointerId)) element.releasePointerCapture(pointerId); + if (!d.moving) return; // a click, not a drag + save(key, offsetRef.current); + }; + const style: CSSProperties = offset.x || offset.y ? { transform: `translate(${offset.x}px, ${offset.y}px)` } : {}; + return { + offset, + bind: { + ref, + style, + onPointerDown: (event: PointerEvent) => { + if (event.button !== 0 || !onHandle(event.target)) return; + event.preventDefault(); + const now = performance.now(); + const before = lastPress.current; + lastPress.current = { t: now, x: event.clientX, y: event.clientY }; + if (before && now - before.t < 400 && Math.hypot(event.clientX - before.x, event.clientY - before.y) < 6) { + lastPress.current = null; + drag.current = null; + putBack(); + return; + } + event.currentTarget.setPointerCapture(event.pointerId); + drag.current = { from: { x: event.clientX, y: event.clientY }, start: offset, base: baseOf(event.currentTarget, offset), id: event.pointerId, moving: false }; + }, + onPointerMove: (event: PointerEvent) => { + const d = drag.current; + if (!d || d.id !== event.pointerId) return; + if (!d.moving) { + if (Math.hypot(event.clientX - d.from.x, event.clientY - d.from.y) < 4) return; // a click, so far + d.moving = true; + } + const next = { x: d.start.x + event.clientX - d.from.x, y: d.start.y + event.clientY - d.from.y }; + setOffset(clampToView(next, d.base, view())); + }, + onPointerUp: (event: PointerEvent) => finish(event.currentTarget, event.pointerId), + // a drag the system breaks off (another window takes the pointer) ends here, so the card does not keep following + onPointerCancel: (event: PointerEvent) => finish(event.currentTarget, event.pointerId), + onLostPointerCapture: (event: PointerEvent) => finish(event.currentTarget, event.pointerId), + }, + }; +} From c4d119376582d4b808e5dde187b088d14196f054 Mon Sep 17 00:00:00 2001 From: lizaixi01 Date: Mon, 30 Nov 2026 12:58:07 +0800 Subject: [PATCH 14/55] editor: the feature tree's name and note tags are matched without Chinese in the library's source MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The library carries no Chinese (test_library_is_english). The tags `# 名称:` and `# 说明:` are still read, written as \u escapes, and `# name:` / `# note:` work as before. Co-Authored-By: Claude Opus 5.5 --- src/simplecadapi/editor/gui_features.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/simplecadapi/editor/gui_features.py b/src/simplecadapi/editor/gui_features.py index 023395e7..217a31c5 100644 --- a/src/simplecadapi/editor/gui_features.py +++ b/src/simplecadapi/editor/gui_features.py @@ -27,12 +27,15 @@ _PARAMS_FOR = re.compile(r"^#\s*-{3,}\s*params:\s*(?P[a-z][a-z0-9_]*)\s*-{3,}\s*$") _PRODUCT_BODY = re.compile(r"(\bbody\s*=\s*)([A-Za-z_][A-Za-z0-9_]*)") _ROLES_WITH_BODIES = {"build", "add", "subtract", "modifier", "intersect"} -_TITLE = re.compile(r"^\s*#\s*(?:名称|name)\s*[::]\s*(?P.+?)\s*$", re.MULTILINE | re.IGNORECASE) -_NOTE = re.compile(r"^\s*#\s*(?:说明|note)\s*[::]\s*(?P.+?)\s*$", re.MULTILINE | re.IGNORECASE) +# The tags a person writes over a feature cell: ``# name: ...`` / ``# note: ...``, or the Chinese words for "name" and +# "note" with an ASCII or a full-width colon (escaped here: the library's source stays English). +_TITLE = re.compile(r"^\s*#\s*(?:\u540d\u79f0|name)\s*[:\uff1a]\s*(?P.+?)\s*$", re.MULTILINE | re.IGNORECASE) +_NOTE = re.compile(r"^\s*#\s*(?:\u8bf4\u660e|note)\s*[:\uff1a]\s*(?P.+?)\s*$", re.MULTILINE | re.IGNORECASE) def feature_words(code: str) -> tuple[str | None, str | None]: - """A feature cell's name and one-line note for a person, from its ``# 名称:…`` and ``# 说明:…`` comment lines.""" + """A feature cell's name and one-line note for a person, from its ``# name: ...`` and ``# note: ...`` comment lines + (or the same tags in Chinese).""" title, note = _TITLE.search(code), _NOTE.search(code) return (title.group("text") if title else None), (note.group("text") if note else None) From 061f1d9aaa96ae72a9b124aba8a10996dc087178 Mon Sep 17 00:00:00 2001 From: lizaixi01 Date: Tue, 1 Dec 2026 11:34:10 +0800 Subject: [PATCH 15/55] =?UTF-8?q?editor=20i18n:=20the=20inspector's=20word?= =?UTF-8?q?=20for=20an=20assembly=20component=20is=20=E9=9B=B6=E9=83=A8?= =?UTF-8?q?=E4=BB=B6=20too?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- editor-web/src/i18n/locales/zh-CN.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/editor-web/src/i18n/locales/zh-CN.json b/editor-web/src/i18n/locales/zh-CN.json index 63aef98a..52a7e804 100644 --- a/editor-web/src/i18n/locales/zh-CN.json +++ b/editor-web/src/i18n/locales/zh-CN.json @@ -1339,7 +1339,7 @@ "Circle": "圆", "Arc": "圆弧", "Curved edge": "曲线边线", - "Component": "组件", + "Component": "零部件", "Area": "面积", "Size": "大小", "Size (X × Y × Z)": "尺寸(X × Y × Z)", @@ -1353,7 +1353,7 @@ "Total area": "总面积", "Total length": "总长度", "vertex": "顶点", - "component": "组件", + "component": "零部件", "Drag to move · double-click to put it back": "拖动可移动 · 双击放回原处", "{{kind}} at ({{at}}), {{size}} {{unit}}": "{{kind}},位置 ({{at}}),{{size}} {{unit}}", "cylinder": "圆柱面", From 1ef7c83888e3c43e4dfc838ed8dc7f6f3155bd7c Mon Sep 17 00:00:00 2001 From: lizaixi01 Date: Tue, 1 Dec 2026 23:34:42 +0800 Subject: [PATCH 16/55] fix(editor): an exported file with a non-ASCII name downloads (RFC 5987 filename*) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DECISION: GET /api/export/file/{name} sends Content-Disposition as an ASCII filename plus filename*=UTF-8'' (server._attachment). WHY: HTTP headers are Latin-1; a part named in Chinese (法兰.step) made the header fail to encode and the page's "save as" answer 500 (review of #103 by NiJingzhe, point 1). Checked: ExportedFileTest in test_editor.py (a 法兰.step download: 200, the bytes, an ASCII header with the filename* form). Co-Authored-By: Claude Opus 5.5 --- src/simplecadapi/editor/server.py | 13 ++++++++++++- test/test_editor.py | 25 +++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/src/simplecadapi/editor/server.py b/src/simplecadapi/editor/server.py index 60647910..f516dab7 100644 --- a/src/simplecadapi/editor/server.py +++ b/src/simplecadapi/editor/server.py @@ -1834,6 +1834,17 @@ def walk(cid: str) -> set[str]: return {cid: walk(cid) for cid in refs} + +def _attachment(name: str) -> str: + """A ``Content-Disposition`` that downloads *name* under its own name, also when it is not ASCII (a Chinese notebook + name): HTTP headers are Latin-1, so the name goes as RFC 5987 ``filename*``, with an ASCII ``filename`` for old + clients.""" + from urllib.parse import quote + + fallback = name.encode("ascii", "replace").decode("ascii").replace('"', "_").replace("\\", "_") + return f"attachment; filename=\"{fallback}\"; filename*=UTF-8''{quote(name, safe='')}" + + def _module_code(code: str) -> str: """marimo's code_mode compiles cell code as a MODULE: a ``return`` in the cell's own scope (normal in marimo's file format) is a SyntaxError there. @@ -2117,7 +2128,7 @@ async def exported_file(request: Request) -> Response: return Response( content=path.read_bytes(), media_type="application/octet-stream", - headers={"Content-Disposition": f'attachment; filename="{path.name}"'}, + headers={"Content-Disposition": _attachment(path.name)}, ) async def api_cells(request: Request) -> JSONResponse: diff --git a/test/test_editor.py b/test/test_editor.py index 5a2c6eaf..9aa79274 100644 --- a/test/test_editor.py +++ b/test/test_editor.py @@ -1659,3 +1659,28 @@ def test_a_deleted_notebook_is_kept_in_the_trash_and_the_last_open_one_stays(sel self.assertIn("only notebook", refused.json()["error"]) self.assertTrue(first.exists()) self.assertEqual(client.post("/api/workspace/delete", json={"path": "../x.py"}).status_code, 400) + + +class ExportedFileTest(unittest.TestCase): + """The page's "save as" downloads an exported file under its own name, a Chinese one too (review of #103).""" + + def test_a_non_ascii_name_is_sent_in_the_rfc_5987_form(self) -> None: + from starlette.testclient import TestClient + + from simplecadapi.editor.server import create_app + + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + first = create_notebook(root, "first", "sample") + out = root / "out" / "法兰.step" + out.parent.mkdir() + out.write_bytes(b"ISO-10303-21;") + state = WorkspaceState(root, first) + state.exported_files = {"法兰.step": out} + client = TestClient(create_app(state)) + reply = client.get("/api/export/file/%E6%B3%95%E5%85%B0.step") + self.assertEqual(reply.status_code, 200) + self.assertEqual(reply.content, b"ISO-10303-21;") + disposition = reply.headers["content-disposition"] + self.assertIn("filename*=UTF-8''%E6%B3%95%E5%85%B0.step", disposition) + self.assertTrue(disposition.isascii()) From 791bdfe760fb0260511f33d63532a401e8801716 Mon Sep 17 00:00:00 2001 From: lizaixi01 Date: Tue, 1 Dec 2026 23:35:02 +0800 Subject: [PATCH 17/55] =?UTF-8?q?fix(editor):=20a=20long=20export=20error?= =?UTF-8?q?=20keeps=20its=20beginning=20("STEP=20export=20failed:=20?= =?UTF-8?q?=E2=80=A6")?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DECISION: the status line of a failed STEP/STL export is cut to its first 300 characters, not its last. WHY: with a long error the cut dropped "STEP export failed:", so the page said what went wrong without saying it was the export (review of #103 by NiJingzhe, point 2). Checked: python -m py_compile; the line is the same otherwise. Co-Authored-By: Claude Opus 5.5 --- src/simplecadapi/editor/server.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/simplecadapi/editor/server.py b/src/simplecadapi/editor/server.py index f516dab7..c2de9307 100644 --- a/src/simplecadapi/editor/server.py +++ b/src/simplecadapi/editor/server.py @@ -1799,7 +1799,7 @@ def _export(self) -> None: make(target, target.with_suffix(suffix)) written.append(target.with_suffix(suffix).name) except Exception as error: # noqa: BLE001 - reported to the person, the package is still written - self.hub.broadcast({"type": "status", "error": f"{suffix[1:].upper()} export failed: {error}"[-300:]}) + self.hub.broadcast({"type": "status", "error": f"{suffix[1:].upper()} export failed: {error}"[:300]}) self.exported_files = {name: target.parent / name for name in written} self.hub.broadcast({"type": "status", "exported": f"{target.parent} ({', '.join(written)})", "export_dir": str(target.parent), "export_files": written}) From 04e766801a4594fae902c4b8fb88c2989e1187d1 Mon Sep 17 00:00:00 2001 From: lizaixi01 Date: Tue, 1 Dec 2026 23:35:02 +0800 Subject: [PATCH 18/55] fix(editor): closing the export dialog by its button forgets what was saved DECISION: every way out of the export dialog (its Close button, Esc, a click outside) goes through one close that clears the "Saved where you chose." notes. WHY: only the dialog's own onOpenChange cleared them; the Close button called onClose directly, so the next export showed the last one's notes (review of #103 by NiJingzhe, point 3). Checked: tsc in editor-web. Co-Authored-By: Claude Opus 5.5 --- editor-web/src/components/ExportDialog.tsx | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/editor-web/src/components/ExportDialog.tsx b/editor-web/src/components/ExportDialog.tsx index 8ce4fb2c..891649f1 100644 --- a/editor-web/src/components/ExportDialog.tsx +++ b/editor-web/src/components/ExportDialog.tsx @@ -65,14 +65,16 @@ export function ExportDialog({ state, onClose }: { state: ExportState; onClose: }) .catch(() => setSaved((s) => ({ ...s, [name]: t("Could not save it here. Use the folder above: the file is already there.") }))); }; + // every way out (the close button, Esc, a click outside) forgets what was saved: the next export starts clean + const close = () => { + setSaved({}); + onClose(); + }; return ( { - if (!next) { - setSaved({}); - onClose(); - } + if (!next) close(); }} > @@ -123,7 +125,7 @@ export function ExportDialog({ state, onClose }: { state: ExportState; onClose:
)} - From 761b316e4f99c29b08db194f40c4308d38c8f4b0 Mon Sep 17 00:00:00 2001 From: lizaixi01 Date: Sun, 29 Nov 2026 17:09:57 +0800 Subject: [PATCH 19/55] editor: the inspector says whether the pick reached the AI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DECISION: the inspector header shows "sending to AI…", "sent to AI ✓" or "not sent to AI, pick again"; the server echoes every selection it takes, also one equal to the last, and always answers an entity lookup, and a pick whose details never arrive is sent without them after a timeout. WHY (the user, 2026-11-28, before asking the AI about a face: "可是我确实选中了,难道出 bug 了"): nothing showed whether the pick had reached the notebook the agent reads. Found while building it: the server skipped the echo for an unchanged selection (a false "not sent"), and an entity lookup that raised never answered, so the pick waited for ever. WHAT CHANGES: lib/selection-sync.ts (new, with tests), App.tsx, Inspector.tsx, server.py (echo, lookup), the test test_the_same_selection_sent_twice_is_echoed_both_times. Checked: tsc and vitest on this commit (357 passed); the server test at the end of this series. Co-Authored-By: Claude Opus 5.5 --- editor-web/src/App.tsx | 25 ++++++++++++++-- editor-web/src/components/Inspector.tsx | 8 +++++- editor-web/src/i18n/locales/zh-CN.json | 3 ++ editor-web/src/lib/selection-sync.test.ts | 16 +++++++++++ editor-web/src/lib/selection-sync.ts | 16 +++++++++++ src/simplecadapi/editor/server.py | 8 +++++- test/test_editor_features.py | 35 +++++++++++++++++++++++ 7 files changed, 107 insertions(+), 4 deletions(-) create mode 100644 editor-web/src/lib/selection-sync.test.ts create mode 100644 editor-web/src/lib/selection-sync.ts diff --git a/editor-web/src/App.tsx b/editor-web/src/App.tsx index 730c9b34..8807c03b 100644 --- a/editor-web/src/App.tsx +++ b/editor-web/src/App.tsx @@ -61,6 +61,7 @@ import { assertCellRan, cellFailure, isCellCommand, pickedPayload, suggestName, import { useRunLog } from "@/lib/runlog"; import { useTheme } from "@/lib/theme"; import { selectionPayload, variableNames, type SelectionItem } from "@/lib/selection"; +import { afterEcho, selectionKey, SYNC_TIMEOUT_MS, type SyncState } from "@/lib/selection-sync"; import { cn } from "@/lib/utils"; import { Boxes, Cable, Play, Square } from "lucide-react"; import { Viewport, type PickResult, type SelectionMode } from "@/scene/Viewport"; @@ -144,6 +145,8 @@ export function App() { const [cells, setCells] = useState([]); const [features, setFeatures] = useState([]); const [picked, setPicked] = useState[]>([]); + const [syncState, setSyncState] = useState("idle"); + const sentSelection = useRef(null); // The notebook's workplanes as the kernel reported them, and the one Space made (or chose) last: new sketches go on it. const [workplanes, setWorkplanes] = useState([]); const [tagSplits, setTagSplits] = useState([]); @@ -460,6 +463,12 @@ export function App() { ); }); + // The server took the selection: it is in the notebook and the agent's snapshot. + socket.on("selection", (envelope) => { + const items = Array.isArray(envelope["items"]) ? (envelope["items"] as { entity_id?: unknown; node_id?: unknown }[]) : []; + setSyncState((state) => afterEcho(state, sentSelection.current, selectionKey(items))); + }); + // Messages of the server. Errors go to the log (the dock opens on one), not the header. socket.on("status", (envelope) => { if (typeof envelope["error"] === "string") { @@ -613,6 +622,11 @@ export function App() { if (needsDetails && item.entityId) { item.pending = true; socketRef.current?.send({ type: "entity.info", entity_id: item.entityId, node_id: item.nodeId }); + // a reply that never comes must not hold the pick back from the agent for ever: send it without its details + const entityId = item.entityId; + window.setTimeout(() => { + setPicked((previous) => previous.map((other) => (other.entityId === entityId && other.pending ? { ...other, pending: false } : other))); + }, SYNC_TIMEOUT_MS); } setPicked((previous) => { if (!result.additive) return [item]; @@ -664,8 +678,14 @@ export function App() { } // The notebook gets the selection when every picked entity is described. const waiting = selection.some((item) => item.pending); + const payload = selectionPayload(selection); + setSyncState(payload.length ? "syncing" : "idle"); + let lost = 0; const send = window.setTimeout(() => { - if (!waiting) socketRef.current?.send({ type: "selection.set", items: selectionPayload(selection) }); + if (waiting) return; + sentSelection.current = selectionKey(payload); + socketRef.current?.send({ type: "selection.set", items: payload }); + if (payload.length) lost = window.setTimeout(() => setSyncState((state) => (state === "syncing" ? "failed" : state)), SYNC_TIMEOUT_MS); }, 40); const snapshot = window.setTimeout(() => { const png = viewRef.current?.snapshotPng(); @@ -673,6 +693,7 @@ export function App() { }, 600); return () => { window.clearTimeout(send); + window.clearTimeout(lost); window.clearTimeout(snapshot); }; }, [selection]); @@ -1707,7 +1728,6 @@ export function App() { () => [...selection, ...livePickedSurfaces.map((name) => ({ nodeId: SURFACE_NODE_PREFIX + name, entityId: null }))], [selection, livePickedSurfaces], ); - const inspectorPanel = ; // the names the feature tree shows (# 名称:…, or the operation in the person's language), for notices about a step const stepNames = useMemo(() => { const names = new Map(cellTitles); @@ -1720,6 +1740,7 @@ export function App() { // the names are translated: a change of language makes them again // eslint-disable-next-line react-hooks/exhaustive-deps }, [cellTitles, gui.state.features, gui.catalog, language]); + const inspectorPanel = ; return (
diff --git a/editor-web/src/components/Inspector.tsx b/editor-web/src/components/Inspector.tsx index b0446a4b..31fffb8d 100644 --- a/editor-web/src/components/Inspector.tsx +++ b/editor-web/src/components/Inspector.tsx @@ -2,6 +2,7 @@ import { Badge } from "@/components/ui/badge"; import { ScrollArea } from "@/components/ui/scroll-area"; import { JsonTree } from "@/components/JsonTree"; import type { SelectionItem } from "@/lib/selection"; +import type { SyncState } from "@/lib/selection-sync"; import { MANUAL_MODE } from "@/lib/manual-mode"; import { measureItem, measureMany, measurePair, type MeasureRow } from "@/lib/measure"; import { t } from "@/i18n"; @@ -9,13 +10,18 @@ import { t } from "@/i18n"; /** Right-hand inspector: what is selected in the viewport, each item with * the variable the selection cell assigns it to and its data as a tree. */ /** `sketches`: the named values picked with the sketch selection mode, sketches and 3D curves (`kind`: the badge). */ -export function Inspector({ selection, sketches = [] }: { selection: SelectionItem[]; sketches?: { name: string; kind?: "sketch" | "curve" | "surface"; rows: { label: string; value: string }[] }[] }) { +export function Inspector({ selection, sketches = [], sync = "idle" }: { selection: SelectionItem[]; sync?: SyncState; sketches?: { name: string; kind?: "sketch" | "curve" | "surface"; rows: { label: string; value: string }[] }[] }) { const count = selection.length + sketches.length; return (
{t("selection")} + {selection.length > 0 && sync !== "idle" && ( + + {sync === "synced" ? t("sent to AI ✓") : sync === "failed" ? t("not sent to AI, pick again") : t("sending to AI…")} + + )} {count > 0 && {count}}
diff --git a/editor-web/src/i18n/locales/zh-CN.json b/editor-web/src/i18n/locales/zh-CN.json index 52a7e804..e61b216f 100644 --- a/editor-web/src/i18n/locales/zh-CN.json +++ b/editor-web/src/i18n/locales/zh-CN.json @@ -1038,6 +1038,9 @@ "loading": "加载中", "loading connectors": "正在加载连接器", "loading details…": "正在加载详情…", + "sent to AI ✓": "已同步给 AI ✓", + "not sent to AI, pick again": "没发给 AI,请重新选一次", + "sending to AI…": "正在同步给 AI…", "loading…": "加载中…", "local": "局部", "log": "日志", diff --git a/editor-web/src/lib/selection-sync.test.ts b/editor-web/src/lib/selection-sync.test.ts new file mode 100644 index 00000000..b48e906f --- /dev/null +++ b/editor-web/src/lib/selection-sync.test.ts @@ -0,0 +1,16 @@ +import { describe, expect, it } from "vitest"; + +import { afterEcho, selectionKey } from "@/lib/selection-sync"; + +describe("selection sync", () => { + it("keys a selection by its entity ids, falling back to the node", () => { + expect(selectionKey([{ entity_id: "f1", node_id: "n" }, { entity_id: null, node_id: "n2" }])).toBe("f1|n2"); + expect(selectionKey([])).toBe(""); + }); + + it("is synced only when the server echoes what was sent", () => { + expect(afterEcho("syncing", "f1", "f1")).toBe("synced"); + expect(afterEcho("syncing", "f1|f2", "f1")).toBe("syncing"); + expect(afterEcho("failed", "f1", "f1")).toBe("failed"); + }); +}); diff --git a/editor-web/src/lib/selection-sync.ts b/editor-web/src/lib/selection-sync.ts new file mode 100644 index 00000000..4ad9c819 --- /dev/null +++ b/editor-web/src/lib/selection-sync.ts @@ -0,0 +1,16 @@ +/** Whether the picked items reached the server (and so the coding agent), shown next to the selection: the person must + * never believe the AI sees a face that never left the browser. */ +export type SyncState = "idle" | "syncing" | "synced" | "failed"; + +/** How long a pick may wait for its details, or a sent selection for the server's echo, before it counts as lost. */ +export const SYNC_TIMEOUT_MS = 8000; + +/** The identity of a selection, the same on both sides: the entity ids (or node ids) in order. */ +export function selectionKey(items: readonly { entity_id?: unknown; node_id?: unknown }[]): string { + return items.map((item) => String(item.entity_id ?? item.node_id ?? "")).join("|"); +} + +/** The state once the server echoes a selection: synced when it is the one last sent, unchanged otherwise. */ +export function afterEcho(state: SyncState, sent: string | null, echoed: string): SyncState { + return state === "syncing" && sent === echoed ? "synced" : state; +} diff --git a/src/simplecadapi/editor/server.py b/src/simplecadapi/editor/server.py index c2de9307..5ce9bf5a 100644 --- a/src/simplecadapi/editor/server.py +++ b/src/simplecadapi/editor/server.py @@ -1320,7 +1320,11 @@ def dispatch_command(self, message: dict) -> dict: node_id = message.get("node_id") def lookup() -> None: - info = kernel.entity_info(entity_id) + # always answer: a webui waits for this reply before it hands the pick to the agent + try: + info = kernel.entity_info(entity_id) + except Exception: + info = None self.hub.broadcast( {"type": "entity.info", "entity_id": entity_id, "node_id": node_id, "entity": info} ) @@ -1597,6 +1601,8 @@ def _set_selection(self, kernel: MarimoKernel, items: list[dict]) -> None: return code = selection_cell_code(self.selection_items) if cell is not None and code.strip() == cell["code"].strip(): + # nothing to write, but the page that sent it waits for this echo to say "sent to AI": always give it + self.emit({"type": "selection", "items": self._selection_summary(), "variables": variable_names(self.selection_items)}) self.write_snapshot() return if cell is not None: diff --git a/test/test_editor_features.py b/test/test_editor_features.py index ff8750b0..adfd1705 100644 --- a/test/test_editor_features.py +++ b/test/test_editor_features.py @@ -334,6 +334,41 @@ def test_numbers_tuned_on_the_sliders_and_kept_do_not_break_undo_and_redo(tmp_pa server.should_exit = True +def test_the_same_selection_sent_twice_is_echoed_both_times(tmp_path): + """The page says "sent to AI" only on the server's echo; a repeat of the selection already written must be echoed too.""" + import threading + import time + + import uvicorn + + from simplecadapi.editor.server import WorkspaceState, create_app + from simplecadapi.editor.templates import create_notebook + + path = create_notebook(tmp_path, "bracket", "sample") + state = WorkspaceState(tmp_path) + state.port = 17735 + server = uvicorn.Server(uvicorn.Config(create_app(state), port=state.port, log_level="error")) + threading.Thread(target=server.run, daemon=True).start() + state.hub.attach_loop(__import__("asyncio").new_event_loop()) + try: + state.start_kernel(path) + echoes: list[dict] = [] + emit = state.emit + state.emit = lambda envelope: (echoes.append(envelope) if envelope.get("type") == "selection" else None, emit(envelope))[1] # type: ignore[method-assign] + face = {"kind": "face", "entity_id": "entity/bracket/face/face_1", "node_id": "node/bracket", + "properties": {"centroid": [0.0, 0.0, 10.0], "area": 100.0}, "geometry": {"type": "plane", "normal": [0.0, 0.0, 1.0]}} + state._set_selection(state.kernel, [face]) + time.sleep(1.0) + state._set_selection(state.kernel, [face]) # the same again: nothing to write, still an echo + time.sleep(0.5) + ids = [[item["entity_id"] for item in e["items"]] for e in echoes] + assert ids[-2:] == [["entity/bracket/face/face_1"], ["entity/bracket/face/face_1"]] + finally: + if state.kernel is not None: + state.kernel.stop() + server.should_exit = True + + def test_a_blank_notebook_gets_its_product_with_the_first_feature(tmp_path): import threading From e20385edfe75358bbce3e18fd76ad6a7ac9670b7 Mon Sep 17 00:00:00 2001 From: lizaixi01 Date: Sun, 29 Nov 2026 17:09:58 +0800 Subject: [PATCH 20/55] feat(editor): leave the AI a request on picked geometry; a headless coding agent does it, in one undo step MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit DECISION (record: design-docs/editor-ask-ai.md): with faces, edges or solids picked, "Ask AI" opens a panel where the person writes one sentence; the editor starts a headless coding agent (`claude -p`) in the workspace with the request and the picks as ql selectors, shows its progress (stages, steps in plain words, elapsed time) and its result, and records all the agent's edits as one undo step, so the undo button takes them back. WHY (discussion with the user, 2026-11-28 and 11-29): the user asked to write a comment right on picked geometry. Three prototypes were tried; the one where comments are only stored for a later agent was rejected ("还不如不加留言功能": a person wants the change, not a note). The chosen one runs the agent at once. Then: it felt slow, so a progress bar with stages and steps; the box closed after sending, so it stays open with "write another"; results are kept until read; Enter sent half-typed Chinese, so the IME is respected; undo must work, so the edits are one history entry. The cost of running a model per request was raised by the user; the model is the CLI's default unless SCA_AGENT_MODEL says otherwise. The agent edits only through the running editor's cell commands (no file edits, no other shell, no web), so the page shows each change live. The code review of 2026-11-29 found that the undo step also took in edits the person made while the agent worked: the agent's commands now carry its request id (SCA_AGENT_REQUEST, header X-Sca-Agent-Request) and only the cells they touched go into its step. ALTERNATIVES CONSIDERED AND REJECTED: stored comments only (above); an agent with free file access (two writers of one notebook). WHAT CHANGES: agent_requests.py (new), server.py (/api/requests, the "request" message, tagged cell commands), cli.py (the header), gui_features.py (cell_changes, record_changes, "modify" as a role with bodies), AskAiPanel.tsx and lib/agent-requests.ts (new), App.tsx, commands.ts (in the context bar; a label starts lower case only by its first letter), Chinese strings, tests (test_editor_agent_requests.py, two in test_editor_features.py). Requests are kept in .sca-editor/requests.json; one interrupted by a restart is marked failed. Checked: tsc and vitest (364 passed); pytest test_editor_features.py, test_editor_agent_requests.py and test_editor.py: 157 passed, 3 failed, the same 3 that fail without this series (starlette's test client needs httpx2, not installed here). Requests run against the real editor and agent during the sessions above. Co-Authored-By: Claude Opus 5.5 --- editor-web/src/App.tsx | 43 ++- editor-web/src/components/AskAiPanel.tsx | 258 ++++++++++++++++ editor-web/src/i18n/locales/zh-CN.json | 19 ++ editor-web/src/lib/agent-requests.test.ts | 58 ++++ editor-web/src/lib/agent-requests.ts | 69 +++++ editor-web/src/lib/commands.ts | 9 +- src/simplecadapi/editor/agent_requests.py | 345 ++++++++++++++++++++++ src/simplecadapi/editor/cli.py | 7 +- src/simplecadapi/editor/gui_features.py | 45 ++- src/simplecadapi/editor/server.py | 39 ++- test/test_editor_agent_requests.py | 221 ++++++++++++++ test/test_editor_features.py | 101 +++++++ 12 files changed, 1207 insertions(+), 7 deletions(-) create mode 100644 editor-web/src/components/AskAiPanel.tsx create mode 100644 editor-web/src/lib/agent-requests.test.ts create mode 100644 editor-web/src/lib/agent-requests.ts create mode 100644 src/simplecadapi/editor/agent_requests.py create mode 100644 test/test_editor_agent_requests.py diff --git a/editor-web/src/App.tsx b/editor-web/src/App.tsx index 8807c03b..8e3d7826 100644 --- a/editor-web/src/App.tsx +++ b/editor-web/src/App.tsx @@ -63,7 +63,9 @@ import { useTheme } from "@/lib/theme"; import { selectionPayload, variableNames, type SelectionItem } from "@/lib/selection"; import { afterEcho, selectionKey, SYNC_TIMEOUT_MS, type SyncState } from "@/lib/selection-sync"; import { cn } from "@/lib/utils"; -import { Boxes, Cable, Play, Square } from "lucide-react"; +import { Boxes, Cable, MessageSquare, Play, Square } from "lucide-react"; +import { AskAiPanel } from "@/components/AskAiPanel"; +import { describeTargets, fetchRequests, isAgentRequest, mergeRequest, submitRequest, type AgentRequest } from "@/lib/agent-requests"; import { Viewport, type PickResult, type SelectionMode } from "@/scene/Viewport"; import type { SceneView } from "@/scene/scene-view"; import { t, useI18n } from "@/i18n"; @@ -140,6 +142,15 @@ export function App() { const [kernelAlive, setKernelAlive] = useState(false); const [status, setStatus] = useState(() => t("Connecting…")); const [exportState, setExportState] = useState(null); + const [askOpen, setAskOpen] = useState(false); + const [agentRequests, setAgentRequests] = useState([]); + const [agentRequestsLoaded, setAgentRequestsLoaded] = useState(false); + useEffect(() => { + void fetchRequests() + .then(setAgentRequests) + .catch(() => undefined) + .finally(() => setAgentRequestsLoaded(true)); + }, []); const [params, setParams] = useState([]); const [cells, setCells] = useState([]); @@ -469,6 +480,12 @@ export function App() { setSyncState((state) => afterEcho(state, sentSelection.current, selectionKey(items))); }); + // Requests left for the coding agent: their state as the agent works (agent_requests.py). + socket.on("request", (envelope) => { + const request = envelope["request"]; + if (isAgentRequest(request)) setAgentRequests((previous) => mergeRequest(previous, request)); + }); + // Messages of the server. Errors go to the log (the dock opens on one), not the header. socket.on("status", (envelope) => { if (typeof envelope["error"] === "string") { @@ -1361,6 +1378,16 @@ export function App() { () => [ // The assembly layout is not a dialog: it is its own panel (registered below), so its spec is left out of the generic list. ...commandsFromSpecs((gui.catalog?.specs ?? []).filter((spec) => spec.id !== "assembly" && spec.id !== "workplane" && spec.id !== "curve"), openSpec, FEATURE_ICONS), + { + id: "ask_ai", + label: "Ask AI", + group: "More", + keywords: ["ai", "agent", "ask", "comment", "note", "request", "留言", "评论", "问 AI"], + description: "Tell the AI in one sentence what to do with what you picked; it edits the model for you and the page updates when it is done.", + icon: MessageSquare, + when: (context) => context.faces + context.edges + context.vertices + context.solids + context.components > 0, + run: () => setAskOpen(true), + }, { id: "curve_draw", label: "3D curve", @@ -1939,6 +1966,20 @@ export function App() { {mode === "manual" && !session && !sketching && !dialog && !placing && !drawing && leftTab !== "assembly" && loading === null && viewRef.current && ( )} + {mode === "manual" && ( + setAskOpen(false)} + onOpen={() => setAskOpen(true)} + onSubmit={async (note) => { + const made = await submitRequest(note, selectionPayload(selection)); + setAgentRequests((previous) => mergeRequest(previous, made)); // the box stays open for a follow-up + }} + /> + )} {( Promise; + onClose: () => void; + /** Bring the box back (the panel stays up for results after it was closed). */ + onOpen: () => void; +}) { + const { t } = useI18n(); + const [note, setNote] = useState(""); + const [sending, setSending] = useState(false); + const [error, setError] = useState(null); + const box = useRef(null); + useEffect(() => { + if (open) box.current?.focus(); + }, [open]); + const recent = requests.slice(-20).reverse(); + const working = requests.some((item) => item.state === "working"); + const [seenUntil, setSeenUntil] = useState(null); + useEffect(() => { + if (loaded && seenUntil === null) setSeenUntil(requests.reduce((top, item) => (item.state !== "working" ? Math.max(top, item.id) : top), 0)); + }, [loaded, seenUntil, requests]); + const [expanded, setExpanded] = useState>({}); + const [now, setNow] = useState(() => Date.now() / 1000); + useEffect(() => { + if (!working) return; + const tick = window.setInterval(() => setNow(Date.now() / 1000), 1000); + return () => window.clearInterval(tick); + }, [working]); + // Folded to a small bar at the corner (minimise, or close while the agent still works): out of the way, still showing it moves. + const [collapsed, setCollapsed] = useState(false); + const panelDrag = useFloatingDrag("sca.floating.ask-ai.at"); + useEffect(() => { + if (open) setCollapsed(false); // asking again brings the whole panel back + }, [open]); + // A request that finished stays in view until the person closes the panel: the agent's sentence is the answer they wait for. + const seen = seenUntil ?? Infinity; // until the first list arrives nothing counts as new + const unseen = requests.some((item) => item.state !== "working" && item.id > seen); + const unseenCount = requests.filter((item) => item.state !== "working" && item.id > seen).length; + if (!open && !working && !unseen) return null; + const markSeen = () => setSeenUntil(requests.reduce((top, item) => (item.state !== "working" ? Math.max(top, item.id) : top), seenUntil ?? 0)); + const close = () => { + markSeen(); + setCollapsed(working); // the agent still works: fold to the bar instead of hiding what it is doing + onClose(); + }; + const minimise = () => { + setCollapsed(true); + onClose(); + }; + + if (collapsed) { + const current = [...requests].reverse().find((item) => item.state === "working"); + const phase = current?.phases?.[Math.min(current.phase ?? 0, (current.phases?.length ?? 1) - 1)]; + return ( + + ); + } + + const send = async () => { + if (!note.trim() || sending) return; + setSending(true); + setError(null); + try { + await onSubmit(note.trim()); + setNote(""); + } catch (failure) { + setError(failure instanceof Error ? failure.message : String(failure)); + } finally { + setSending(false); + } + }; + + return ( +
event.stopPropagation()} + {...panelDrag.bind} + > +
+ + {t("Ask AI")} + + +
+ {open && ( + <> +
+ {t("About")}:{targets || t("the whole part")} +
+