Theme applies across SketchForge and all projects.
+ onShowProjectNameInToolbarChange?.(show)}
+ />
) : null}
+ {activeSection === "shapes" ? (
+ <>
+
+ Shape defaults
+ Customize how each toolbar shape starts. Existing limits stay unchanged until you enter a custom limit.
+
+
+
+
+
+ {selectedShapeAsset.name}
+ {selectedShapeCustomized ? "Custom settings active" : "Using SketchForge defaults"}
+
+
+
+
+ {(["width", "depth", "height"] as const).map((key) => (
+
+ ))}
+
+ {selectedShapeSpecialFields.length > 0 ? (
+
+ ) : null}
+
+
Custom values apply to new shapes. A custom size limit also replaces this shape's existing resize ceilings, up to 2000 mm.
+
+ >
+ ) : null}
+
{activeSection === "history" ? (
<>
@@ -618,10 +889,23 @@ function GridColorControl({ color, onChange }: { color: string; onChange: (color
);
}
-function WorkspaceToggle({ label, checked, onChange }: { label: string; checked: boolean; onChange: (checked: boolean) => void }) {
+function WorkspaceToggle({
+ label,
+ description,
+ checked,
+ onChange,
+}: {
+ label: string;
+ description?: string;
+ checked: boolean;
+ onChange: (checked: boolean) => void;
+}) {
return (
);
diff --git a/apps/web/src/components/workplane/transformOverlayTypes.ts b/apps/web/src/components/workplane/transformOverlayTypes.ts
index 795762e..0ba8021 100644
--- a/apps/web/src/components/workplane/transformOverlayTypes.ts
+++ b/apps/web/src/components/workplane/transformOverlayTypes.ts
@@ -15,6 +15,65 @@ export type RotationPlaneView = {
export type RotationPlaneBasis = Pick;
+export const ROTATION_WHEEL_SNAP_DEGREES = 45;
+export const ROTATION_WHEEL_SHIFT_SNAP_DEGREES = 22.5;
+
+export function rotationWheelDirectionSign(screenSign: number) {
+ return screenSign < 0 ? 1 : -1;
+}
+
+export function snappedRotationDelta(rawDelta: number, insideSnapWheel: boolean, shiftKey: boolean) {
+ const step = insideSnapWheel || shiftKey ? ROTATION_WHEEL_SNAP_DEGREES : 1;
+ return Math.round(rawDelta / step) * step;
+}
+
+export function snappedWheelRotation(
+ pointerAngle: number,
+ startPointerAngle: number,
+ screenSign = 1,
+ snapDegrees = ROTATION_WHEEL_SNAP_DEGREES,
+) {
+ const snappedPointerAngle = Math.round(pointerAngle / snapDegrees) * snapDegrees;
+ const snappedStartPointerAngle = Math.round(startPointerAngle / snapDegrees) * snapDegrees;
+ let pointerDelta = snappedPointerAngle - snappedStartPointerAngle;
+ while (pointerDelta > 180) pointerDelta -= 360;
+ while (pointerDelta <= -180) pointerDelta += 360;
+ const direction = screenSign < 0 ? -1 : 1;
+ const delta = pointerDelta * direction;
+ return {
+ delta: delta === 0 ? 0 : delta,
+ pointerAngle: snappedPointerAngle,
+ };
+}
+
+export function continuousSnappedWheelRotation(
+ rotation: { delta: number; pointerAngle: number },
+ snapDegrees: number,
+ previousSnapDegrees: number | undefined,
+ previousDelta: number | undefined,
+ previousPointerAngle: number | undefined,
+ previousDeltaOffset = 0,
+ previousPointerOffset = 0,
+) {
+ const snapModeChanged = previousSnapDegrees !== undefined && previousSnapDegrees !== snapDegrees;
+ const deltaOffset = snapModeChanged && previousDelta !== undefined
+ ? previousDelta - rotation.delta
+ : previousDeltaOffset;
+ const pointerOffset = snapModeChanged && previousPointerAngle !== undefined
+ ? previousPointerAngle - rotation.pointerAngle
+ : previousPointerOffset;
+ let pointerAngle = rotation.pointerAngle + pointerOffset;
+ while (pointerAngle > 180) pointerAngle -= 360;
+ while (pointerAngle < -180) pointerAngle += 360;
+ const delta = rotation.delta + deltaOffset;
+ return {
+ delta: delta === 0 ? 0 : delta,
+ pointerAngle,
+ deltaOffset,
+ pointerOffset,
+ };
+}
+
export function normalizedRotationPlaneBasis(plane: RotationPlaneView, invertVerticalAxis = false): RotationPlaneBasis {
const longestAxis = Math.max(Math.hypot(plane.a, plane.b), Math.hypot(plane.c, plane.d));
if (!Number.isFinite(longestAxis) || longestAxis < 0.000001) {
diff --git a/apps/web/src/lib/projectThumbnail.ts b/apps/web/src/lib/projectThumbnail.ts
new file mode 100644
index 0000000..329a81f
--- /dev/null
+++ b/apps/web/src/lib/projectThumbnail.ts
@@ -0,0 +1,30 @@
+export const PROJECT_THUMBNAIL_IDLE_MS = 2_500;
+export const PROJECT_THUMBNAIL_MAX_WIDTH = 512;
+export const PROJECT_THUMBNAIL_MAX_HEIGHT = 320;
+
+export type ProjectThumbnailSceneKey = {
+ projectId: string;
+ fingerprint: string;
+};
+
+export function projectThumbnailDimensions(
+ sourceWidth: number,
+ sourceHeight: number,
+ maxWidth = PROJECT_THUMBNAIL_MAX_WIDTH,
+ maxHeight = PROJECT_THUMBNAIL_MAX_HEIGHT,
+) {
+ const width = Math.max(1, Math.round(Number.isFinite(sourceWidth) ? sourceWidth : 1));
+ const height = Math.max(1, Math.round(Number.isFinite(sourceHeight) ? sourceHeight : 1));
+ const scale = Math.min(1, maxWidth / width, maxHeight / height);
+ return {
+ width: Math.max(1, Math.round(width * scale)),
+ height: Math.max(1, Math.round(height * scale)),
+ };
+}
+
+export function projectThumbnailSceneChanged(
+ previous: ProjectThumbnailSceneKey | null,
+ current: ProjectThumbnailSceneKey,
+) {
+ return previous?.projectId === current.projectId && previous.fingerprint !== current.fingerprint;
+}
diff --git a/apps/web/src/lib/shapeCatalog.ts b/apps/web/src/lib/shapeCatalog.ts
index 48db3a8..c957ad8 100644
--- a/apps/web/src/lib/shapeCatalog.ts
+++ b/apps/web/src/lib/shapeCatalog.ts
@@ -1,7 +1,21 @@
import { canonicalizeShape } from "@/lib/workplaneShapes";
import { createLocalId } from "@/lib/localIds";
-import { DEFAULT_GEAR_CENTER_HOLE_SIZE, DEFAULT_GEAR_HELIX_ANGLE, DEFAULT_GEAR_HELIX_QUALITY, DEFAULT_GEAR_TEETH, DEFAULT_GEAR_TOOTH_SIZE, DEFAULT_GEAR_TYPE } from "@/lib/gearGeometry";
-import type { ShapeAsset, WorkplaneShape } from "@/types/sketchforge";
+import {
+ DEFAULT_GEAR_CENTER_HOLE_SIZE,
+ DEFAULT_GEAR_HELIX_ANGLE,
+ DEFAULT_GEAR_HELIX_QUALITY,
+ DEFAULT_GEAR_TEETH,
+ DEFAULT_GEAR_TOOTH_SIZE,
+ DEFAULT_GEAR_TYPE,
+ normalizeGearCenterHoleSize,
+ normalizeGearHelixAngle,
+ normalizeGearHelixQuality,
+ normalizeGearTeeth,
+ normalizeGearToothSize,
+ normalizeGearToothWidth,
+ normalizeGearType,
+} from "@/lib/gearGeometry";
+import type { ShapeAsset, ShapeCustomization, ShapeKind, WorkplaneShape } from "@/types/sketchforge";
export type ToolbarShapeAsset = ShapeAsset & { menuIcon: string };
@@ -20,6 +34,42 @@ export const toolbarShapeAssets: ToolbarShapeAsset[] = [
{ id: "gear", name: "Gear", src: "assets/sketchforge/gear-types/spur.png", menuIcon: "assets/sketchforge/gear-types/spur.png", kind: "gear", color: "#6f7f8d" },
];
+export function shapeAssetDefaultDimensions(kind: ShapeKind) {
+ const roundProfile = kind === "sphere" || kind === "torus" || kind === "ring" || kind === "halfSphere";
+ const flatProfile = kind === "torus" || kind === "ring" || kind === "text" || kind === "gear";
+ const size = kind === "gear" ? 30 : roundProfile ? 22 : 20;
+ return {
+ width: kind === "text" ? 86 : size,
+ depth: kind === "text" ? 28 : size,
+ height: kind === "gear" ? 6 : kind === "text" ? 10 : kind === "roundRoof" ? 10 : kind === "halfSphere" ? 11 : flatProfile ? 5 : 20,
+ };
+}
+
+export function shapeAssetSpecialDefaults(kind: ShapeKind, dimensions = shapeAssetDefaultDimensions(kind)): ShapeCustomization {
+ if (kind === "cylinder") return { sides: 96 };
+ if (kind === "sphere") return { steps: 24 };
+ if (kind === "halfSphere") return { steps: 32 };
+ if (kind === "cone") return { topRadius: 0, baseRadius: dimensions.width / 2, sides: 96 };
+ if (kind === "pyramid") return { sides: 4 };
+ if (kind === "roundRoof") return { sides: 64 };
+ if (kind === "tube" || kind === "ring") return { bevel: 4 };
+ if (kind === "text") return { text: "TEXT", font: "Multilanguage", bevel: 0, segments: 0 };
+ if (kind === "gear") {
+ const teeth = DEFAULT_GEAR_TEETH;
+ const toothSize = normalizeGearToothSize(DEFAULT_GEAR_TOOTH_SIZE, dimensions.width, dimensions.depth);
+ return {
+ teeth,
+ toothSize,
+ toothWidth: normalizeGearToothWidth(undefined, dimensions.width, dimensions.depth, teeth),
+ centerHoleSize: normalizeGearCenterHoleSize(DEFAULT_GEAR_CENTER_HOLE_SIZE, dimensions.width, dimensions.depth, toothSize),
+ gearType: DEFAULT_GEAR_TYPE,
+ helixAngle: DEFAULT_GEAR_HELIX_ANGLE,
+ helixQuality: DEFAULT_GEAR_HELIX_QUALITY,
+ };
+ }
+ return {};
+}
+
export function sceneShape(shape: Partial & Pick): WorkplaneShape {
const width = shape.width ?? shape.size ?? 20;
const depth = shape.depth ?? shape.size ?? 20;
@@ -77,13 +127,18 @@ export function sceneShape(shape: Partial & Pick {
- const compact = compactSampledPath(current);
- if (compact.length >= 2) paths.push(compact);
- current = [];
- };
- for (let index = 0; index < points.length - 1; index += 1) {
- const from = points[index];
- const to = points[index + 1];
- const fromInside = from.x <= 0;
- const toInside = to.x <= 0;
- if (fromInside && toInside) {
- if (current.length === 0) current.push(from);
- current.push(to);
- } else if (fromInside) {
- if (current.length === 0) current.push(from);
- current.push(axisIntersection(from, to));
- finishCurrent();
- } else if (toInside) {
- current = [axisIntersection(from, to), to];
- }
- }
- finishCurrent();
- return paths;
-}
-
function distance(a: Point2, b: Point2) {
return Math.hypot(b[0] - a[0], b[1] - a[1]);
}
@@ -193,55 +164,19 @@ function compactPolygon(points: Point2[]) {
return compact;
}
-function strokeOpenPath(points: Point2[], thickness: number) {
- if (points.length < 2) return [];
- const half = thickness / 2;
- const normals: Point2[] = [];
- for (let index = 0; index < points.length - 1; index += 1) {
- const dx = points[index + 1][0] - points[index][0];
- const dy = points[index + 1][1] - points[index][1];
- const length = Math.hypot(dx, dy);
- normals.push(length > 1e-8 ? [-dy / length, dx / length] : [0, 0]);
- }
- const offsetAt = (index: number): Point2 => {
- const previous = normals[Math.max(0, index - 1)];
- const next = normals[Math.min(normals.length - 1, index)];
- const sumX = previous[0] + next[0];
- const sumY = previous[1] + next[1];
- const sumLength = Math.hypot(sumX, sumY);
- if (sumLength <= 1e-8) return [next[0] * half, next[1] * half];
- const unit: Point2 = [sumX / sumLength, sumY / sumLength];
- const projection = Math.abs(unit[0] * next[0] + unit[1] * next[1]);
- const miter = Math.min(half * 4, half / Math.max(0.25, projection));
- return [unit[0] * miter, unit[1] * miter];
- };
- const left: Point2[] = [];
- const right: Point2[] = [];
- points.forEach((point, index) => {
- const offset = offsetAt(index);
- left.push([point[0] + offset[0], point[1] + offset[1]]);
- right.push([point[0] - offset[0], point[1] - offset[1]]);
- });
- return compactPolygon([...left, ...right.reverse()]);
-}
-
export function sketchProfileToRevolvePolygons(profile: SketchProfile, settings?: Partial) {
const normalized = normalizeSketchRevolveSettings(settings);
- const paths = orderedPaths(profile).flatMap((path) => {
+ const paths = orderedPaths(profile).filter((path) => path.closed).flatMap((path) => {
const sampled = samplePath(path, normalized.quality);
- if (path.closed) {
- const clipped = clipClosedPathToRevolveSide(sampled);
- return clipped.length >= 3 ? [{ closed: true, points: clipped }] : [];
- }
- return clipOpenPathToRevolveSide(sampled).map((points) => ({ closed: false, points }));
+ const clipped = clipClosedPathToRevolveSide(sampled);
+ return clipped.length >= 3 ? [clipped] : [];
});
if (paths.length === 0) return [];
- const maxZ = Math.max(...paths.flatMap((entry) => entry.points.map((point) => point.z)));
+ const maxZ = Math.max(...paths.flatMap((points) => points.map((point) => point.z)));
const toSectionPoint = (point: SampledPoint): Point2 => [-point.x, maxZ - point.z];
- return paths.flatMap(({ closed, points }) => {
+ return paths.flatMap((points) => {
const sectionPoints = compactPolygon(points.map(toSectionPoint));
- const polygon = closed ? sectionPoints : strokeOpenPath(sectionPoints, normalized.thickness).map((point) => [Math.max(0, point[0]), point[1]] as Point2);
- return polygon.length >= 3 ? [compactPolygon(polygon)] : [];
+ return sectionPoints.length >= 3 ? [sectionPoints] : [];
});
}
@@ -261,7 +196,7 @@ function dispose(value: unknown) {
export function buildSketchRevolveMesh(runtime: ManifoldToplevel, profile: SketchProfile, requestedSettings?: Partial): SketchRevolveMesh {
const settings = normalizeSketchRevolveSettings(requestedSettings);
const polygons = sketchProfileToRevolvePolygons(profile, settings);
- if (polygons.length === 0) throw new Error("Draw at least one connected profile on the left side of the revolve axis");
+ if (polygons.length === 0) throw new Error("Draw at least one closed profile on the left side of the revolve axis");
const disposable: unknown[] = [];
try {
const section = new runtime.CrossSection(polygons, "EvenOdd");
diff --git a/apps/web/src/lib/sketchRotation.ts b/apps/web/src/lib/sketchRotation.ts
new file mode 100644
index 0000000..8e41412
--- /dev/null
+++ b/apps/web/src/lib/sketchRotation.ts
@@ -0,0 +1,87 @@
+import type { SketchPoint, SketchProfile } from "@/types/sketchforge";
+
+export type SketchGeometrySelection = {
+ pointIds: readonly string[];
+ segmentIds: readonly string[];
+ imageIds?: readonly string[];
+};
+
+export function selectedClosedSketchPoints(
+ profile: SketchProfile,
+ selection: SketchGeometrySelection,
+): SketchPoint[] | null {
+ if (selection.imageIds?.length) return null;
+
+ const pointIds = new Set(selection.pointIds);
+ const segmentIds = new Set(selection.segmentIds);
+ if (pointIds.size < 3 || segmentIds.size !== pointIds.size) return null;
+
+ const selectedPoints = profile.points.filter((point) => pointIds.has(point.id));
+ if (selectedPoints.length !== pointIds.size) return null;
+
+ const segmentById = new Map(profile.segments.map((segment) => [segment.id, segment]));
+ const adjacency = new Map([...pointIds].map((pointId) => [pointId, new Set()]));
+
+ for (const segmentId of segmentIds) {
+ const segment = segmentById.get(segmentId);
+ if (
+ !segment
+ || segment.startId === segment.endId
+ || !pointIds.has(segment.startId)
+ || !pointIds.has(segment.endId)
+ ) {
+ return null;
+ }
+ adjacency.get(segment.startId)?.add(segment.endId);
+ adjacency.get(segment.endId)?.add(segment.startId);
+ }
+
+ if ([...adjacency.values()].some((neighbors) => neighbors.size !== 2)) return null;
+
+ const unvisited = new Set(pointIds);
+ while (unvisited.size > 0) {
+ const start = unvisited.values().next().value as string | undefined;
+ if (!start) return null;
+ const stack = [start];
+ let componentSize = 0;
+ while (stack.length > 0) {
+ const pointId = stack.pop();
+ if (!pointId || !unvisited.delete(pointId)) continue;
+ componentSize += 1;
+ adjacency.get(pointId)?.forEach((neighborId) => {
+ if (unvisited.has(neighborId)) stack.push(neighborId);
+ });
+ }
+ if (componentSize < 3) return null;
+ }
+
+ return selectedPoints;
+}
+
+export function rotateSketchPoints(points: readonly SketchPoint[], degrees = 45): SketchPoint[] {
+ if (points.length === 0) return [];
+
+ const minX = Math.min(...points.map((point) => point.x));
+ const maxX = Math.max(...points.map((point) => point.x));
+ const minZ = Math.min(...points.map((point) => point.z));
+ const maxZ = Math.max(...points.map((point) => point.z));
+ const pivot = { x: (minX + maxX) / 2, z: (minZ + maxZ) / 2 };
+ const radians = degrees * Math.PI / 180;
+ const cosine = Math.cos(radians);
+ const sine = Math.sin(radians);
+ const rotatePosition = (position: { x: number; z: number }) => {
+ const deltaX = position.x - pivot.x;
+ const deltaZ = position.z - pivot.z;
+ return {
+ x: pivot.x + deltaX * cosine - deltaZ * sine,
+ z: pivot.z + deltaX * sine + deltaZ * cosine,
+ };
+ };
+
+ return points.map((point) => ({
+ ...point,
+ ...rotatePosition(point),
+ handleIn: point.handleIn ? rotatePosition(point.handleIn) : undefined,
+ handleOut: point.handleOut ? rotatePosition(point.handleOut) : undefined,
+ }));
+}
diff --git a/apps/web/src/lib/sketchforgeMcpProtocol.ts b/apps/web/src/lib/sketchforgeMcpProtocol.ts
index b127182..8a74818 100644
--- a/apps/web/src/lib/sketchforgeMcpProtocol.ts
+++ b/apps/web/src/lib/sketchforgeMcpProtocol.ts
@@ -1,8 +1,10 @@
import type { GridSize, ShapeKind, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
export const SKETCHFORGE_MCP_ROUTE = "/api/sketchforge-mcp";
-export const SKETCHFORGE_MCP_STALE_MS = 6500;
-export const SKETCHFORGE_MCP_POLL_MS = 220;
+export const SKETCHFORGE_MCP_STALE_MS = 15_000;
+export const SKETCHFORGE_MCP_HEARTBEAT_MS = 5_000;
+export const SKETCHFORGE_MCP_LONG_POLL_TIMEOUT_MS = 25_000;
+export const SKETCHFORGE_MCP_POLL_RETRY_MS = 1_000;
export type SketchForgeMcpViewFace = "current" | "home" | "top" | "bottom" | "front" | "back" | "right" | "left";
diff --git a/apps/web/src/lib/sketchforgeMcpStore.ts b/apps/web/src/lib/sketchforgeMcpStore.ts
index 06918f0..0f03e21 100644
--- a/apps/web/src/lib/sketchforgeMcpStore.ts
+++ b/apps/web/src/lib/sketchforgeMcpStore.ts
@@ -12,10 +12,18 @@ type PendingCommand = {
timer: ReturnType;
};
+type PollWaiter = {
+ resolve: (command: SketchForgeMcpCommand | null) => void;
+ timer: ReturnType;
+ signal?: AbortSignal;
+ onAbort?: () => void;
+};
+
type SketchForgeMcpStore = {
editors: Map;
queues: Map;
pending: Map;
+ pollWaiters: Map;
};
declare global {
@@ -24,22 +32,42 @@ declare global {
}
function store() {
- globalThis.__sketchforgeMcpStore ??= {
+ const state = globalThis.__sketchforgeMcpStore ??= {
editors: new Map(),
queues: new Map(),
pending: new Map(),
+ pollWaiters: new Map(),
};
- return globalThis.__sketchforgeMcpStore;
+ // Development hot reload can preserve a store created before pollWaiters
+ // existed. Initialize it lazily so an already-open editor keeps working.
+ state.pollWaiters ??= new Map();
+ return state;
}
function createCommandId() {
return globalThis.crypto?.randomUUID?.() ?? `sketchforge-mcp-${Date.now()}-${Math.random().toString(36).slice(2)}`;
}
+function settlePollWaiter(
+ state: SketchForgeMcpStore,
+ editorId: string,
+ waiter: PollWaiter,
+ command: SketchForgeMcpCommand | null,
+) {
+ if (state.pollWaiters.get(editorId) !== waiter) return false;
+ state.pollWaiters.delete(editorId);
+ clearTimeout(waiter.timer);
+ if (waiter.signal && waiter.onAbort) {
+ waiter.signal.removeEventListener("abort", waiter.onAbort);
+ }
+ waiter.resolve(command);
+ return true;
+}
+
function prune(current = Date.now()) {
const state = store();
for (const [editorId, editor] of state.editors) {
- if (current - editor.lastSeen <= SKETCHFORGE_MCP_STALE_MS) {
+ if (state.pollWaiters.has(editorId) || current - editor.lastSeen <= SKETCHFORGE_MCP_STALE_MS) {
continue;
}
state.editors.delete(editorId);
@@ -79,6 +107,32 @@ export function pollSketchForgeMcpCommand(editorId: string) {
return queue?.shift() ?? null;
}
+export function waitForSketchForgeMcpCommand(
+ editorId: string,
+ { timeoutMs, signal }: { timeoutMs: number; signal?: AbortSignal },
+) {
+ const state = store();
+ const current = Date.now();
+ const editor = state.editors.get(editorId);
+ if (editor) state.editors.set(editorId, { ...editor, lastSeen: current });
+ prune(current);
+ const queued = state.queues.get(editorId)?.shift();
+ if (queued) return Promise.resolve(queued);
+ if (signal?.aborted) return Promise.resolve(null);
+
+ const existing = state.pollWaiters.get(editorId);
+ if (existing) settlePollWaiter(state, editorId, existing, null);
+
+ return new Promise((resolve) => {
+ let waiter: PollWaiter;
+ const timer = setTimeout(() => settlePollWaiter(state, editorId, waiter, null), Math.max(1_000, Math.min(timeoutMs, 30_000)));
+ const onAbort = () => settlePollWaiter(state, editorId, waiter, null);
+ waiter = { resolve, timer, signal, onAbort };
+ state.pollWaiters.set(editorId, waiter);
+ signal?.addEventListener("abort", onAbort, { once: true });
+ });
+}
+
export function completeSketchForgeMcpCommand(editorId: string, result: SketchForgeMcpCommandResult) {
const state = store();
const pending = state.pending.get(result.commandId);
@@ -124,9 +178,12 @@ export function dispatchSketchForgeMcpCommand({
params,
createdAt: Date.now(),
};
- const queue = state.queues.get(editor.editorId) ?? [];
- queue.push(command);
- state.queues.set(editor.editorId, queue);
+ const waiter = state.pollWaiters.get(editor.editorId);
+ if (!waiter || !settlePollWaiter(state, editor.editorId, waiter, command)) {
+ const queue = state.queues.get(editor.editorId) ?? [];
+ queue.push(command);
+ state.queues.set(editor.editorId, queue);
+ }
return new Promise((resolve) => {
const timer = setTimeout(() => {
diff --git a/apps/web/src/lib/skfProject.ts b/apps/web/src/lib/skfProject.ts
index 2889e39..4e03557 100644
--- a/apps/web/src/lib/skfProject.ts
+++ b/apps/web/src/lib/skfProject.ts
@@ -872,7 +872,7 @@ function validateShapeDefinition(definition: Record, label: str
}
if (definition.sketchRevolve !== undefined) {
const settings = objectRecord(definition.sketchRevolve, `${label}.sketchRevolve`);
- ["startAngle", "sweepAngle", "sides", "quality", "thickness"].forEach((field) => finiteNumber(settings[field], `${label}.sketchRevolve.${field}`));
+ ["startAngle", "sweepAngle", "sides", "quality"].forEach((field) => finiteNumber(settings[field], `${label}.sketchRevolve.${field}`));
}
if (kind === "gear") {
const teeth = finiteNumber(definition.teeth, `${label}.teeth`);
diff --git a/apps/web/src/lib/workplaneSettings.ts b/apps/web/src/lib/workplaneSettings.ts
index 7460fa4..7a94afd 100644
--- a/apps/web/src/lib/workplaneSettings.ts
+++ b/apps/web/src/lib/workplaneSettings.ts
@@ -1,8 +1,11 @@
-import type { GridSize, HistoryRetentionLimit, MeasurementAccuracy, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
+import type { GridSize, HistoryRetentionLimit, MeasurementAccuracy, ShapeCustomization, ShapeCustomizationMap, ShapeKind, WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import { normalizeScaleForUnits } from "@/lib/measurementUnits";
import { DEFAULT_WORKPLANE_GRID_COLOR } from "@/lib/workplaneGrid";
export const DEFAULT_SNAP_GRID: GridSize = "1.0 mm";
+export const MIN_CUSTOM_SHAPE_DIMENSION = 0.01;
+export const MAX_CUSTOM_SHAPE_DIMENSION = 2000;
+export const MAX_HIGH_RESOLUTION_SIDES = 512;
export const DEFAULT_WORKPLANE_WORKSPACE: WorkplaneWorkspaceSettings = {
width: 200,
@@ -21,9 +24,14 @@ export const DEFAULT_WORKPLANE_WORKSPACE: WorkplaneWorkspaceSettings = {
scale: "1:1 (millimeters)",
accuracy: 2,
historyLimit: 100,
+ shapeCustomizations: {},
};
const snapGridOptions: GridSize[] = ["Off", "0.1 mm", "0.25 mm", "0.5 mm", "1.0 mm", "2.0 mm", "5.0 mm", "Brick"];
+const customizableShapeKinds: ShapeKind[] = [
+ "box", "cylinder", "sphere", "sketch", "scribble", "cone", "pyramid", "roof", "text", "roundRoof",
+ "halfSphere", "torus", "tube", "gear", "ring", "wedge", "polygon", "icosahedron", "mesh",
+];
function numberOrDefault(value: unknown, fallback: number) {
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
@@ -51,6 +59,88 @@ function historyLimitOrDefault(value: unknown, fallback: HistoryRetentionLimit):
return Math.min(5000, Math.max(1, Math.round(value)));
}
+function optionalShapeDimension(value: unknown, fallback: number | undefined) {
+ if (value === undefined) return fallback;
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
+ return Math.min(MAX_CUSTOM_SHAPE_DIMENSION, Math.max(MIN_CUSTOM_SHAPE_DIMENSION, value));
+}
+
+function optionalShapeNumber(value: unknown, fallback: number | undefined, min: number, max: number, integer = false) {
+ if (value === undefined) return fallback;
+ if (typeof value !== "number" || !Number.isFinite(value)) return fallback;
+ const normalized = Math.min(max, Math.max(min, value));
+ return integer ? Math.round(normalized) : normalized;
+}
+
+function optionalShapeText(value: unknown, fallback: string | undefined, maxLength: number) {
+ if (value === undefined) return fallback;
+ if (typeof value !== "string") return fallback;
+ return value.slice(0, maxLength) || " ";
+}
+
+export function normalizeShapeCustomizations(value: unknown, fallback: ShapeCustomizationMap = {}): ShapeCustomizationMap {
+ const candidate = value && typeof value === "object" ? value as Partial> : {};
+ const normalized: ShapeCustomizationMap = {};
+ customizableShapeKinds.forEach((kind) => {
+ const raw = candidate[kind];
+ const source = raw && typeof raw === "object" ? raw as Partial : {};
+ const fallbackEntry = fallback[kind];
+ const entry: ShapeCustomization = {
+ width: optionalShapeDimension(source.width, fallbackEntry?.width),
+ depth: optionalShapeDimension(source.depth, fallbackEntry?.depth),
+ height: optionalShapeDimension(source.height, fallbackEntry?.height),
+ maxDimension: optionalShapeDimension(source.maxDimension, fallbackEntry?.maxDimension),
+ };
+ if (kind === "sphere" || kind === "halfSphere") {
+ entry.steps = optionalShapeNumber(source.steps, fallbackEntry?.steps, 6, 64, true);
+ }
+ if (kind === "cylinder" || kind === "cone") {
+ entry.sides = optionalShapeNumber(source.sides, fallbackEntry?.sides, 3, MAX_HIGH_RESOLUTION_SIDES, true);
+ } else if (kind === "pyramid") {
+ entry.sides = optionalShapeNumber(source.sides, fallbackEntry?.sides, 3, 24, true);
+ } else if (kind === "roundRoof") {
+ entry.sides = optionalShapeNumber(source.sides, fallbackEntry?.sides, 4, MAX_HIGH_RESOLUTION_SIDES, true);
+ }
+ if (kind === "cone") {
+ entry.topRadius = optionalShapeNumber(source.topRadius, fallbackEntry?.topRadius, 0, MAX_CUSTOM_SHAPE_DIMENSION / 2);
+ entry.baseRadius = optionalShapeNumber(source.baseRadius, fallbackEntry?.baseRadius, MIN_CUSTOM_SHAPE_DIMENSION, MAX_CUSTOM_SHAPE_DIMENSION / 2);
+ }
+ if (kind === "tube" || kind === "ring") {
+ entry.bevel = optionalShapeNumber(source.bevel, fallbackEntry?.bevel, 0.5, 20);
+ }
+ if (kind === "text") {
+ entry.text = optionalShapeText(source.text, fallbackEntry?.text, 24);
+ entry.font = source.font === undefined
+ ? fallbackEntry?.font
+ : ["Multilanguage", "Sans", "Serif", "Script", "Monospace", "Rounded", "Stencil"].includes(source.font)
+ ? source.font
+ : fallbackEntry?.font;
+ entry.bevel = optionalShapeNumber(source.bevel, fallbackEntry?.bevel, 0, 8);
+ entry.segments = optionalShapeNumber(source.segments, fallbackEntry?.segments, 0, 24, true);
+ }
+ if (kind === "gear") {
+ entry.teeth = optionalShapeNumber(source.teeth, fallbackEntry?.teeth, 6, 64, true);
+ entry.toothSize = optionalShapeNumber(source.toothSize, fallbackEntry?.toothSize, 0.2, MAX_CUSTOM_SHAPE_DIMENSION / 2);
+ entry.toothWidth = optionalShapeNumber(source.toothWidth, fallbackEntry?.toothWidth, MIN_CUSTOM_SHAPE_DIMENSION, MAX_CUSTOM_SHAPE_DIMENSION);
+ entry.centerHoleSize = optionalShapeNumber(source.centerHoleSize, fallbackEntry?.centerHoleSize, 0, MAX_CUSTOM_SHAPE_DIMENSION);
+ entry.gearType = source.gearType === undefined
+ ? fallbackEntry?.gearType
+ : source.gearType === "spur" || source.gearType === "helical" || source.gearType === "bevel"
+ ? source.gearType
+ : fallbackEntry?.gearType;
+ entry.helixAngle = optionalShapeNumber(source.helixAngle, fallbackEntry?.helixAngle, -45, 45);
+ entry.helixQuality = optionalShapeNumber(source.helixQuality, fallbackEntry?.helixQuality, 4, 32, true);
+ }
+ const compact = Object.fromEntries(Object.entries(entry).filter(([, entryValue]) => entryValue !== undefined)) as ShapeCustomization;
+ if (Object.keys(compact).length > 0) normalized[kind] = compact;
+ });
+ return normalized;
+}
+
+export function shapeDimensionLimit(workspace: WorkplaneWorkspaceSettings, kind: ShapeKind, appDefault: number) {
+ return workspace.shapeCustomizations[kind]?.maxDimension ?? appDefault;
+}
+
export function normalizeSnapGrid(value: unknown, fallback: GridSize = DEFAULT_SNAP_GRID): GridSize {
return snapGridOptions.includes(value as GridSize) ? (value as GridSize) : fallback;
}
@@ -75,6 +165,7 @@ export function normalizeWorkspaceSettings(value: unknown, fallback: WorkplaneWo
scale: normalizeScaleForUnits(units, stringOrDefault(candidate.scale, fallback.scale)),
accuracy: accuracyOrDefault(candidate.accuracy, fallback.accuracy),
historyLimit: historyLimitOrDefault(candidate.historyLimit, fallback.historyLimit),
+ shapeCustomizations: normalizeShapeCustomizations(candidate.shapeCustomizations, fallback.shapeCustomizations),
};
}
diff --git a/apps/web/src/lib/workplaneShapes.ts b/apps/web/src/lib/workplaneShapes.ts
index e0dda2b..b9823de 100644
--- a/apps/web/src/lib/workplaneShapes.ts
+++ b/apps/web/src/lib/workplaneShapes.ts
@@ -22,6 +22,10 @@ export function cleanNearZero(value: number, epsilon = 0.005) {
return Math.abs(value) < epsilon ? 0 : value;
}
+export function shapeTransformShouldRemainEditable(shape: WorkplaneShape) {
+ return shape.kind === "text" || Boolean(shape.groupedShapes?.length);
+}
+
export function cloneWorkplaneShapeTreeWithFreshIds(shape: WorkplaneShape, suffix: string): WorkplaneShape {
return {
...shape,
@@ -213,6 +217,14 @@ export function canonicalizeShape(shape: WorkplaneShape): WorkplaneShape {
if (shape.groupedShapes) {
next.groupedShapes = shape.groupedShapes.map(canonicalizeShape);
}
+ if (shape.sketchRevolve) {
+ next.sketchRevolve = {
+ startAngle: shape.sketchRevolve.startAngle,
+ sweepAngle: shape.sketchRevolve.sweepAngle,
+ sides: shape.sketchRevolve.sides,
+ quality: shape.sketchRevolve.quality,
+ };
+ }
if (shape.edgeTreatmentHistory) {
next.edgeTreatmentHistory = shape.edgeTreatmentHistory.map((entry) => ({
...entry,
diff --git a/apps/web/src/types/sketchforge.ts b/apps/web/src/types/sketchforge.ts
index f63e6db..4718333 100644
--- a/apps/web/src/types/sketchforge.ts
+++ b/apps/web/src/types/sketchforge.ts
@@ -44,6 +44,30 @@ export type GridSize = "Off" | "0.1 mm" | "0.25 mm" | "0.5 mm" | "1.0 mm" | "2.0
export type MeasurementAccuracy = 1 | 2 | 3;
export type HistoryRetentionLimit = "unlimited" | number;
+export type ShapeCustomization = {
+ width?: number;
+ depth?: number;
+ height?: number;
+ maxDimension?: number;
+ steps?: number;
+ sides?: number;
+ bevel?: number;
+ segments?: number;
+ topRadius?: number;
+ baseRadius?: number;
+ teeth?: number;
+ toothSize?: number;
+ toothWidth?: number;
+ centerHoleSize?: number;
+ gearType?: GearType;
+ helixAngle?: number;
+ helixQuality?: number;
+ text?: string;
+ font?: string;
+};
+
+export type ShapeCustomizationMap = Partial>;
+
export type WorkplaneWorkspaceSettings = {
width: number;
depth: number;
@@ -61,6 +85,7 @@ export type WorkplaneWorkspaceSettings = {
scale: string;
accuracy: MeasurementAccuracy;
historyLimit: HistoryRetentionLimit;
+ shapeCustomizations: ShapeCustomizationMap;
};
export type AlignAxis = "x" | "y" | "z";
@@ -102,6 +127,7 @@ export type SketchImage = {
depth: number;
opacity?: number;
lockAspect?: boolean;
+ locked?: boolean;
};
export type SketchProfile = {
@@ -119,7 +145,6 @@ export type SketchRevolveSettings = {
sweepAngle: number;
sides: number;
quality: number;
- thickness: number;
};
export type EdgeTreatmentFeature = {
diff --git a/tests/unit/projectThumbnail.test.ts b/tests/unit/projectThumbnail.test.ts
new file mode 100644
index 0000000..3d06247
--- /dev/null
+++ b/tests/unit/projectThumbnail.test.ts
@@ -0,0 +1,21 @@
+import { describe, expect, it } from "vitest";
+import {
+ projectThumbnailDimensions,
+ projectThumbnailSceneChanged,
+} from "@/lib/projectThumbnail";
+
+describe("project thumbnails", () => {
+ it("reduces a high-DPI editor canvas to the thumbnail bounds", () => {
+ expect(projectThumbnailDimensions(2048, 992)).toEqual({ width: 512, height: 248 });
+ expect(projectThumbnailDimensions(800, 1200)).toEqual({ width: 213, height: 320 });
+ expect(projectThumbnailDimensions(320, 180)).toEqual({ width: 320, height: 180 });
+ });
+
+ it("captures only changed scenes within the same project", () => {
+ const original = { projectId: "project-1", fingerprint: "scene-a" };
+ expect(projectThumbnailSceneChanged(null, original)).toBe(false);
+ expect(projectThumbnailSceneChanged(original, original)).toBe(false);
+ expect(projectThumbnailSceneChanged(original, { ...original, fingerprint: "scene-b" })).toBe(true);
+ expect(projectThumbnailSceneChanged(original, { projectId: "project-2", fingerprint: "scene-b" })).toBe(false);
+ });
+});
diff --git a/tests/unit/shapeCatalog.test.ts b/tests/unit/shapeCatalog.test.ts
index 26a507a..bbec31c 100644
--- a/tests/unit/shapeCatalog.test.ts
+++ b/tests/unit/shapeCatalog.test.ts
@@ -54,6 +54,37 @@ describe("shape catalog", () => {
});
});
+ it("applies only explicitly customized creation dimensions", () => {
+ const asset: ShapeAsset = { id: "cone", name: "Cone", src: "cone.png", kind: "cone", color: "#6e2786" };
+ const appDefault = makeShapeFromAsset(asset);
+ const customized = makeShapeFromAsset(asset, undefined, { width: 320, depth: 240, height: 180 });
+
+ expect(appDefault).toMatchObject({ width: 20, depth: 20, height: 20, baseRadius: 10 });
+ expect(customized).toMatchObject({ width: 320, depth: 240, height: 180, size: 320, baseRadius: 160 });
+ });
+
+ it("applies shape-specific creation defaults only when customized", () => {
+ const cone = makeShapeFromAsset(
+ { id: "cone", name: "Cone", src: "cone.png", kind: "cone", color: "#6e2786" },
+ undefined,
+ { topRadius: 3, baseRadius: 18, sides: 48 },
+ );
+ const text = makeShapeFromAsset(
+ { id: "text", name: "Text", src: "text.png", kind: "text", color: "#cf101b" },
+ undefined,
+ { text: "HELLO", font: "Serif", bevel: 2, segments: 6 },
+ );
+ const gear = makeShapeFromAsset(
+ { id: "gear", name: "Gear", src: "gear.svg", kind: "gear", color: "#6f7f8d" },
+ undefined,
+ { gearType: "helical", teeth: 24, toothSize: 3, toothWidth: 2, centerHoleSize: 10, helixAngle: 30, helixQuality: 24 },
+ );
+
+ expect(cone).toMatchObject({ topRadius: 3, baseRadius: 18, sides: 48 });
+ expect(text).toMatchObject({ text: "HELLO", font: "Serif", bevel: 2, segments: 6 });
+ expect(gear).toMatchObject({ gearType: "helical", teeth: 24, toothSize: 3, toothWidth: 2, centerHoleSize: 10, helixAngle: 30, helixQuality: 24 });
+ });
+
it("creates canonical scene shapes with stable defaults", () => {
const created = sceneShape({
name: "Part",
diff --git a/tests/unit/sketchRevolve.test.ts b/tests/unit/sketchRevolve.test.ts
index ccb0ecb..442745a 100644
--- a/tests/unit/sketchRevolve.test.ts
+++ b/tests/unit/sketchRevolve.test.ts
@@ -41,35 +41,38 @@ describe("sketch revolve", () => {
expect(Math.min(...mesh.positions.filter((_value, index) => index % 3 === 1))).toBeCloseTo(0, 6);
});
- it("creates thickness automatically for an open profile", () => {
+ it("requires a closed profile", () => {
const profile: SketchProfile = {
points: [{ id: "a", x: -8, z: 0 }, { id: "b", x: -8, z: 20 }],
segments: [{ id: "ab", startId: "a", endId: "b", kind: "line" }],
};
- const polygons = sketchProfileToRevolvePolygons(profile, { thickness: 2 });
- expect(polygons).toHaveLength(1);
- expect(Math.min(...polygons[0].map((point) => point[0]))).toBeCloseTo(7, 6);
- expect(Math.max(...polygons[0].map((point) => point[0]))).toBeCloseTo(9, 6);
- const mesh = buildSketchRevolveMesh(runtime, profile, { thickness: 2, sides: 24 });
- expect(mesh.triangleCount).toBeGreaterThan(0);
- expect(mesh.width).toBeCloseTo(18, 4);
- expect(mesh.height).toBeCloseTo(20, 4);
+ expect(sketchProfileToRevolvePolygons(profile)).toEqual([]);
+ expect(() => buildSketchRevolveMesh(runtime, profile, { sides: 24 })).toThrow("Draw at least one closed profile");
});
- it("allows construction points across the axis but only revolves the working-side segment", () => {
+ it("clips a closed profile at the revolve axis", () => {
const profile: SketchProfile = {
- points: [{ id: "construction", x: 10, z: 0 }, { id: "profile", x: -10, z: 20 }],
- segments: [{ id: "crossing", startId: "construction", endId: "profile", kind: "line" }],
+ points: [
+ { id: "top-right", x: 10, z: 0 },
+ { id: "top-left", x: -10, z: 0 },
+ { id: "bottom-left", x: -10, z: 20 },
+ { id: "bottom-right", x: 10, z: 20 },
+ ],
+ segments: [
+ { id: "top", startId: "top-right", endId: "top-left", kind: "line" },
+ { id: "left", startId: "top-left", endId: "bottom-left", kind: "line" },
+ { id: "bottom", startId: "bottom-left", endId: "bottom-right", kind: "line" },
+ { id: "right", startId: "bottom-right", endId: "top-right", kind: "line" },
+ ],
};
- const polygons = sketchProfileToRevolvePolygons(profile, { thickness: 1 });
+ const polygons = sketchProfileToRevolvePolygons(profile);
expect(polygons).toHaveLength(1);
- expect(Math.max(...polygons[0].map((point) => point[1]))).toBeLessThan(11);
- expect(Math.max(...polygons[0].map((point) => point[0]))).toBeGreaterThan(10);
+ expect(Math.min(...polygons[0].map((point) => point[0]))).toBeCloseTo(0, 6);
+ expect(Math.max(...polygons[0].map((point) => point[0]))).toBeCloseTo(10, 6);
- const mesh = buildSketchRevolveMesh(runtime, profile, { thickness: 1, sides: 24 });
+ const mesh = buildSketchRevolveMesh(runtime, profile, { sides: 24 });
expect(mesh.triangleCount).toBeGreaterThan(0);
- expect(mesh.height).toBeGreaterThan(9);
- expect(mesh.height).toBeLessThan(11);
+ expect(mesh.height).toBeCloseTo(20, 4);
});
it("supports partial and reverse sweeps", () => {
@@ -82,12 +85,11 @@ describe("sketch revolve", () => {
});
it("normalizes unsafe revolve settings", () => {
- expect(normalizeSketchRevolveSettings({ startAngle: -30, sweepAngle: 0, sides: 500, quality: 0, thickness: -2 })).toEqual({
+ expect(normalizeSketchRevolveSettings({ startAngle: -30, sweepAngle: 0, sides: 900, quality: 0 })).toEqual({
startAngle: 330,
sweepAngle: 1,
- sides: 128,
+ sides: 512,
quality: 1,
- thickness: 0.1,
});
});
});
diff --git a/tests/unit/sketchRotation.test.ts b/tests/unit/sketchRotation.test.ts
new file mode 100644
index 0000000..691cf85
--- /dev/null
+++ b/tests/unit/sketchRotation.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from "vitest";
+import { rotateSketchPoints, selectedClosedSketchPoints } from "@/lib/sketchRotation";
+import type { SketchProfile } from "@/types/sketchforge";
+
+const rectangle: SketchProfile = {
+ points: [
+ { id: "a", x: 0, z: 0, handleOut: { x: 1, z: 0 } },
+ { id: "b", x: 4, z: 0 },
+ { id: "c", x: 4, z: 2 },
+ { id: "d", x: 0, z: 2 },
+ ],
+ segments: [
+ { id: "ab", startId: "a", endId: "b" },
+ { id: "bc", startId: "b", endId: "c" },
+ { id: "cd", startId: "c", endId: "d" },
+ { id: "da", startId: "d", endId: "a" },
+ ],
+};
+
+describe("sketch rotation", () => {
+ it("recognizes a complete closed sketch selection", () => {
+ const points = selectedClosedSketchPoints(rectangle, {
+ pointIds: ["a", "b", "c", "d"],
+ segmentIds: ["ab", "bc", "cd", "da"],
+ });
+ expect(points?.map((point) => point.id)).toEqual(["a", "b", "c", "d"]);
+ });
+
+ it("rejects an open, partial, or image-inclusive selection", () => {
+ expect(selectedClosedSketchPoints(rectangle, {
+ pointIds: ["a", "b", "c", "d"],
+ segmentIds: ["ab", "bc", "cd"],
+ })).toBeNull();
+ expect(selectedClosedSketchPoints(rectangle, {
+ pointIds: ["a", "b", "c", "d"],
+ segmentIds: ["ab", "bc", "cd", "da"],
+ imageIds: ["reference-image"],
+ })).toBeNull();
+ });
+
+ it("rotates points and bezier handles around the selection bounds center", () => {
+ const rotated = rotateSketchPoints(rectangle.points, 90);
+ const first = rotated.find((point) => point.id === "a");
+ expect(first?.x).toBeCloseTo(3, 8);
+ expect(first?.z).toBeCloseTo(-1, 8);
+ expect(first?.handleOut?.x).toBeCloseTo(3, 8);
+ expect(first?.handleOut?.z).toBeCloseTo(0, 8);
+ });
+});
diff --git a/tests/unit/sketchforgeMcpStore.test.ts b/tests/unit/sketchforgeMcpStore.test.ts
new file mode 100644
index 0000000..70b789f
--- /dev/null
+++ b/tests/unit/sketchforgeMcpStore.test.ts
@@ -0,0 +1,67 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import {
+ completeSketchForgeMcpCommand,
+ dispatchSketchForgeMcpCommand,
+ pollSketchForgeMcpCommand,
+ registerSketchForgeMcpEditor,
+ waitForSketchForgeMcpCommand,
+} from "@/lib/sketchforgeMcpStore";
+
+const editor = {
+ editorId: "editor-test",
+ editorNumber: 12345,
+ projectId: "project-test",
+ projectName: "MCP test",
+ url: "http://localhost:3000/?editor=1",
+ focused: true,
+ shapeCount: 0,
+ selectedCount: 0,
+ notice: "",
+ lastError: null,
+};
+
+beforeEach(() => {
+ delete (globalThis as { __sketchforgeMcpStore?: unknown }).__sketchforgeMcpStore;
+ registerSketchForgeMcpEditor(editor);
+});
+
+describe("SketchForge MCP long polling", () => {
+ it("delivers a command directly to a waiting editor", async () => {
+ const poll = waitForSketchForgeMcpCommand(editor.editorId, { timeoutMs: 5_000 });
+ const result = dispatchSketchForgeMcpCommand({ editorId: editor.editorId, action: "list_objects" });
+
+ const command = await poll;
+ expect(command).toMatchObject({ action: "list_objects", params: {} });
+ expect(pollSketchForgeMcpCommand(editor.editorId)).toBeNull();
+
+ completeSketchForgeMcpCommand(editor.editorId, { commandId: command!.id, ok: true, data: [] });
+ await expect(result).resolves.toMatchObject({ commandId: command!.id, ok: true, data: [] });
+ });
+
+ it("allows only one pending poll per editor", async () => {
+ const firstPoll = waitForSketchForgeMcpCommand(editor.editorId, { timeoutMs: 5_000 });
+ const secondPoll = waitForSketchForgeMcpCommand(editor.editorId, { timeoutMs: 5_000 });
+
+ await expect(firstPoll).resolves.toBeNull();
+ const result = dispatchSketchForgeMcpCommand({ editorId: editor.editorId, action: "inspect_errors" });
+ const command = await secondPoll;
+ expect(command?.action).toBe("inspect_errors");
+
+ completeSketchForgeMcpCommand(editor.editorId, { commandId: command!.id, ok: true });
+ await expect(result).resolves.toMatchObject({ commandId: command!.id, ok: true });
+ });
+
+ it("removes an aborted poll before queueing the next command", async () => {
+ const controller = new AbortController();
+ const poll = waitForSketchForgeMcpCommand(editor.editorId, { timeoutMs: 5_000, signal: controller.signal });
+ controller.abort();
+ await expect(poll).resolves.toBeNull();
+
+ const result = dispatchSketchForgeMcpCommand({ editorId: editor.editorId, action: "get_scene" });
+ const command = pollSketchForgeMcpCommand(editor.editorId);
+ expect(command?.action).toBe("get_scene");
+
+ completeSketchForgeMcpCommand(editor.editorId, { commandId: command!.id, ok: true });
+ await expect(result).resolves.toMatchObject({ commandId: command!.id, ok: true });
+ });
+});
diff --git a/tests/unit/skfProject.test.ts b/tests/unit/skfProject.test.ts
index c0e92c7..98248e6 100644
--- a/tests/unit/skfProject.test.ts
+++ b/tests/unit/skfProject.test.ts
@@ -153,7 +153,7 @@ describe("SketchForge .skf project packages", () => {
const revolve = shape("mesh", "revolve-sketch", {
name: "Sketch revolve",
sketchOperation: "revolve",
- sketchRevolve: { startAngle: 25, sweepAngle: -220, sides: 48, quality: 8, thickness: 1.5 },
+ sketchRevolve: { startAngle: 25, sweepAngle: -220, sides: 48, quality: 8 },
sketchProfile: {
points: [{ id: "p1", x: -4, z: 0 }, { id: "p2", x: -8, z: 0 }, { id: "p3", x: -8, z: 16 }, { id: "p4", x: -4, z: 16 }],
segments: [
@@ -402,6 +402,8 @@ describe("SketchForge .skf project packages", () => {
z: 0,
width: 10,
depth: 10,
+ lockAspect: true,
+ locked: true,
}],
},
});
@@ -412,6 +414,7 @@ describe("SketchForge .skf project packages", () => {
expect(document.assets.filter((entry) => entry.kind === "image")).toHaveLength(1);
expect(restored.shapes[0].imagePlate?.dataUrl).toBe(dataUrl);
expect(restored.shapes[0].sketchProfile?.images?.[0].dataUrl).toBe(dataUrl);
+ expect(restored.shapes[0].sketchProfile?.images?.[0].locked).toBe(true);
});
it("deduplicates derived geometry when legacy imported objects share one mesh", async () => {
diff --git a/tests/unit/transformOverlayTypes.test.ts b/tests/unit/transformOverlayTypes.test.ts
index e4873c4..5e7a89b 100644
--- a/tests/unit/transformOverlayTypes.test.ts
+++ b/tests/unit/transformOverlayTypes.test.ts
@@ -1,5 +1,11 @@
import { describe, expect, it } from "vitest";
-import { normalizedRotationPlaneBasis } from "@/components/workplane/transformOverlayTypes";
+import {
+ continuousSnappedWheelRotation,
+ normalizedRotationPlaneBasis,
+ rotationWheelDirectionSign,
+ snappedRotationDelta,
+ snappedWheelRotation,
+} from "@/components/workplane/transformOverlayTypes";
describe("rotation handle projection", () => {
it("preserves face-plane foreshortening while normalizing icon size", () => {
@@ -28,4 +34,68 @@ describe("rotation handle projection", () => {
d: 1,
});
});
+
+ it("moves 45-degree rotation in the same screen direction as 22.5-degree rotation", () => {
+ const direction = rotationWheelDirectionSign(1);
+ expect(snappedWheelRotation(-52, -80, direction)).toEqual({ delta: -45, pointerAngle: -45 });
+ expect(snappedWheelRotation(-58, -80, direction)).toEqual({ delta: -45, pointerAngle: -45 });
+ expect(snappedWheelRotation(-69, -80, direction)).toEqual({ delta: 0, pointerAngle: -90 });
+ });
+
+ it("switches the wheel rotation and orange indicator to 22.5-degree marks with Shift", () => {
+ const direction = rotationWheelDirectionSign(1);
+ expect(snappedWheelRotation(-58, -80, direction, 22.5)).toEqual({ delta: -22.5, pointerAngle: -67.5 });
+ expect(snappedWheelRotation(-52, -80, direction, 22.5)).toEqual({ delta: -45, pointerAngle: -45 });
+ });
+
+ it("keeps the current result continuous when switching to 22.5-degree snapping", () => {
+ const direction = rotationWheelDirectionSign(1);
+ const coarse = snappedWheelRotation(-58, -80, direction);
+ const fineAtShift = continuousSnappedWheelRotation(
+ snappedWheelRotation(-58, -80, direction, 22.5),
+ 22.5,
+ 45,
+ coarse.delta,
+ coarse.pointerAngle,
+ );
+ expect(fineAtShift).toEqual({
+ delta: -45,
+ pointerAngle: -45,
+ deltaOffset: -22.5,
+ pointerOffset: 22.5,
+ });
+
+ const fineForward = continuousSnappedWheelRotation(
+ snappedWheelRotation(-52, -80, direction, 22.5),
+ 22.5,
+ 22.5,
+ fineAtShift.delta,
+ fineAtShift.pointerAngle,
+ fineAtShift.deltaOffset,
+ fineAtShift.pointerOffset,
+ );
+ expect(fineForward).toEqual({
+ delta: -67.5,
+ pointerAngle: -22.5,
+ deltaOffset: -22.5,
+ pointerOffset: 22.5,
+ });
+ });
+
+ it("keeps one-degree rotation outside the wheel", () => {
+ expect(snappedRotationDelta(28.4, false, false)).toBe(28);
+ });
+
+ it("retains the Shift 45-degree shortcut outside the wheel", () => {
+ expect(snappedRotationDelta(28, false, true)).toBe(45);
+ });
+
+ it("keeps absolute wheel snapping synchronized when screen rotation is inverted", () => {
+ expect(snappedWheelRotation(-134, -80, -1)).toEqual({ delta: 45, pointerAngle: -135 });
+ });
+
+ it("wraps wheel deltas across the -180/180 boundary", () => {
+ expect(snappedWheelRotation(-179, 179)).toEqual({ delta: 0, pointerAngle: -180 });
+ expect(snappedWheelRotation(-134, 179)).toEqual({ delta: 45, pointerAngle: -135 });
+ });
});
diff --git a/tests/unit/workplaneSettings.test.ts b/tests/unit/workplaneSettings.test.ts
index ffe5ea2..fcfd57a 100644
--- a/tests/unit/workplaneSettings.test.ts
+++ b/tests/unit/workplaneSettings.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { WorkplaneWorkspaceSettings } from "@/types/sketchforge";
import { formatMeasurementNumber, lengthDisplayUnit, millimetersToDisplay, normalizeScaleForUnits, parseMeasurementInput, scaleOptionsForUnits } from "@/lib/measurementUnits";
-import { canBeginShapeDrag, DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, workplaneSettingsFingerprint, workspaceHydrationSyncDecision } from "@/lib/workplaneSettings";
+import { canBeginShapeDrag, DEFAULT_SNAP_GRID, DEFAULT_WORKPLANE_WORKSPACE, normalizeSnapGrid, normalizeWorkspaceSettings, shapeDimensionLimit, workplaneSettingsFingerprint, workspaceHydrationSyncDecision } from "@/lib/workplaneSettings";
describe("workplane settings helpers", () => {
it("accepts known snap grid values and falls back for unknown values", () => {
@@ -63,6 +63,43 @@ describe("workplane settings helpers", () => {
expect(normalizeWorkspaceSettings({ gridColor: "not-a-color" }).gridColor).toBe(DEFAULT_WORKPLANE_WORKSPACE.gridColor);
});
+ it("keeps app limits until a shape receives an explicit customization", () => {
+ const untouched = normalizeWorkspaceSettings({});
+ const customized = normalizeWorkspaceSettings({
+ shapeCustomizations: {
+ box: { width: 48, maxDimension: 720 },
+ sphere: { height: Number.NaN, maxDimension: 9000 },
+ },
+ });
+
+ expect(untouched.shapeCustomizations).toEqual({});
+ expect(shapeDimensionLimit(untouched, "box", 160)).toBe(160);
+ expect(customized.shapeCustomizations.box).toEqual({ width: 48, maxDimension: 720 });
+ expect(customized.shapeCustomizations.sphere).toEqual({ maxDimension: 2000 });
+ expect(shapeDimensionLimit(customized, "box", 160)).toBe(720);
+ expect(shapeDimensionLimit(customized, "cylinder", 220)).toBe(220);
+ });
+
+ it("normalizes supported special-shape defaults", () => {
+ const customized = normalizeWorkspaceSettings({
+ shapeCustomizations: {
+ cylinder: { sides: 500 },
+ roundRoof: { sides: 900 },
+ sphere: { steps: 2 },
+ cone: { topRadius: -4, baseRadius: 9000, sides: 40 },
+ text: { text: "A custom label that is much too long", font: "Serif", bevel: 12, segments: 9.6 },
+ gear: { gearType: "helical", teeth: 23.7, toothSize: 3, centerHoleSize: -5, helixAngle: 90, helixQuality: 3 },
+ },
+ });
+
+ expect(customized.shapeCustomizations.cylinder).toEqual({ sides: 500 });
+ expect(customized.shapeCustomizations.roundRoof).toEqual({ sides: 512 });
+ expect(customized.shapeCustomizations.sphere).toEqual({ steps: 6 });
+ expect(customized.shapeCustomizations.cone).toEqual({ topRadius: 0, baseRadius: 1000, sides: 40 });
+ expect(customized.shapeCustomizations.text).toEqual({ text: "A custom label that is m", font: "Serif", bevel: 8, segments: 10 });
+ expect(customized.shapeCustomizations.gear).toEqual({ gearType: "helical", teeth: 24, toothSize: 3, centerHoleSize: 0, helixAngle: 45, helixQuality: 4 });
+ });
+
it("can require selection before a shape starts moving", () => {
expect(canBeginShapeDrag(false, false)).toBe(true);
expect(canBeginShapeDrag(true, false)).toBe(false);
diff --git a/tests/unit/workplaneShapes.test.ts b/tests/unit/workplaneShapes.test.ts
index eec21c5..ed81518 100644
--- a/tests/unit/workplaneShapes.test.ts
+++ b/tests/unit/workplaneShapes.test.ts
@@ -19,6 +19,7 @@ import {
shapeDepth,
shapeHasTaper,
shapeOverallFootprintDimensions,
+ shapeTransformShouldRemainEditable,
shapeTaperDimensions,
shapeTaperScaleAt,
shapeWidth,
@@ -129,6 +130,29 @@ describe("workplane shape helpers", () => {
expect(canonical.groupedShapes?.[0].mirrorZ).toBeUndefined();
});
+ it("keeps rotated groups editable so they can still be ungrouped", () => {
+ const child = shape({ id: "child" });
+ const group = shape({
+ id: "group",
+ kind: "mesh",
+ rotation: 45,
+ groupedBaseWidth: 20,
+ groupedBaseDepth: 20,
+ groupedBaseHeight: 20,
+ groupedShapes: [child],
+ });
+
+ expect(shapeTransformShouldRemainEditable(group)).toBe(true);
+ expect(shapeTransformShouldRemainEditable(shape({ rotation: 45 }))).toBe(false);
+ expect(canonicalizeShape(group)).toMatchObject({
+ rotation: 45,
+ groupedBaseWidth: 20,
+ groupedBaseDepth: 20,
+ groupedBaseHeight: 20,
+ groupedShapes: [{ id: "child" }],
+ });
+ });
+
it("assigns fresh object IDs throughout duplicated group trees", () => {
const original = shape({
id: "outer-group",