diff --git a/design-docs/editor-ask-ai.md b/design-docs/editor-ask-ai.md new file mode 100644 index 00000000..95ac30ae --- /dev/null +++ b/design-docs/editor-ask-ai.md @@ -0,0 +1,43 @@ +# Ask AI: a request on picked geometry, done by a coding agent + +Status: built on branch `feat/editor-manual-mode-ux` (2026-11-29), manual mode only. + +## The need + +A person modelling in the editor's manual mode often knows what they want ("a boss around this hole, 20 mm across") but not +the operations that make it. They asked to write that sentence right on the picked geometry. + +## What was tried + +Three clickable prototypes (2026-11-28): + +1. **Stored comments.** The note is kept on the geometry; an agent reads them later. Rejected by the user: "还不如不加留言功能". + A person wants the change, not a note waiting for someone. +2. **Comment thread with replies.** Too heavy for one sentence. +3. **Request run at once.** Chosen: the note starts an agent right away and the page shows the result. + +## How it works + +- The person picks faces, edges, solids or components and opens "Ask AI" (in the context bar or the command bar). +- `POST /api/requests {note, items}` makes a request. `AgentRequests` (`src/simplecadapi/editor/agent_requests.py`) starts + `claude -p` in the workspace. The prompt holds the note, the picks as `ql` selectors (the code the selection cell holds), + the notebook's steps and the instruction to name a new step with `# 名称:` / `# 说明:` lines (the feature tree shows them). +- **What the agent may use:** `sca cell`, `sca snapshot`, `sca ops`, Read/Glob/Grep, and the SDK skill. Edit, Write, web + access and other shell commands are denied. So the running editor stays the one writer of the notebook, and the page + shows each edit live. +- **Progress:** the agent's stream (`--output-format stream-json`) is turned into stages (理解需求 → 查看零件 → 修改模型 → 检查结果 → + 完成) and steps in plain words. They reach the pages as `request` messages. +- **One undo step:** the agent's cell commands carry its request id (`SCA_AGENT_REQUEST` in its environment, sent as the + header `X-Sca-Agent-Request` by `sca`). The server notes the cells each one touched. When the request ends, only those + cells' changes are recorded as one history entry (`FeatureService.record_changes(..., only=...)`). Edits the person made + meanwhile are not taken back by undoing the agent. +- **Kept across restarts:** requests are stored in `.sca-editor/requests.json` and ids go on from the last one. A request + cut off by a restart is marked failed. +- **Choosing an agent:** `SCA_AGENT_CMD` replaces the executable (the tests use a stand-in). `SCA_AGENT_MODEL` picks the + model, otherwise the CLI's default. + +## Open + +- **Cost:** a request is a full agent run. The user raised this. There is no budget or per-request limit yet. +- **Other agents:** another coding agent would need the same contract: edit only through `sca cell`, and pass the request id. +- **No cancel button:** a request ends by itself, after 10 minutes at most. diff --git a/design-docs/editor-sw-terms.md b/design-docs/editor-sw-terms.md new file mode 100644 index 00000000..3ed2efd2 --- /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 | …约束 | …配合(铰链、滑块、齿轮、齿条小齿轮、皮带/链、锁定) | +| 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. +- 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. diff --git a/editor-web/src/App.tsx b/editor-web/src/App.tsx index 0b10ca16..fc2205d5 100644 --- a/editor-web/src/App.tsx +++ b/editor-web/src/App.tsx @@ -9,7 +9,7 @@ import { selectionAnchorMm } from "@/lib/selection-anchor"; import { SketchScene } from "@/components/SketchScene"; import { CommandBar } from "@/components/CommandBar"; import { FEATURE_ICONS } from "@/components/feature-icons"; -import { FeatureTree, type TreeSketches } from "@/components/FeatureTree"; +import { FeatureTree, type TreeShow, type TreeSketches } from "@/components/FeatureTree"; import { assemblyCommands, commandsFromSpecs, fitScore, plainLabel, selectionContext, selectionHint, visibleCommands, whenFor, type Command } from "@/lib/commands"; import { ModeSwitch, type EditorMode } from "@/components/ModeSwitch"; import { MANUAL_MODE } from "@/lib/manual-mode"; @@ -21,6 +21,7 @@ import { TagSplits, parseTagSplits, type TagSplit } from "@/components/TagSplits import { NewNotebookPrompt } from "@/components/NewNotebookPrompt"; import { FloatingPanels } from "@/components/FloatingPanels"; import { OperationPanel } from "@/components/OperationPanel"; +import { UnsavedParams } from "@/components/UnsavedParams"; import { PressPullHandle } from "@/components/PressPullHandle"; import { addPick, featureParams, pickSlot, quickStart, refLabel, removePick } from "@/lib/operation-session"; import { createSettler, SETTLE_MS } from "@/lib/settle"; @@ -37,6 +38,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"; @@ -50,9 +52,9 @@ import { SURFACE_NODE_PREFIX, isSurfaceNode, parsePreview, previewSummary, type import { closedLoop, gordonFamilies, loopNormal } from "@/lib/curve-net"; import { EnvelopeSocket, type Envelope } from "@/lib/envelope"; import { emptyDoc, normalizeDoc } from "@/lib/sketch"; -import { frameFromEntity, type PlaneSpec } from "@/lib/sketch-plane"; +import { frameFromEntity, frameSpec, type Frame, type PlaneSpec } from "@/lib/sketch-plane"; import { useFeatures } from "@/lib/useFeatures"; -import { describeSketch, nextSketchSelection, readHidden, sketchCentre, sketchInfos, toggleHidden, writeHidden } from "@/lib/sketch-scene"; +import { describeSketch, nextSketchSelection, readHidden, sketchCentre, sketchInfos, toggleHidden, withParamValues, writeHidden } from "@/lib/sketch-scene"; import { useSketchShapes } from "@/lib/useSketchShapes"; import type { Vec3 } from "@/lib/sketch-plane"; import { PALETTES } from "@/scene/theme"; @@ -60,11 +62,18 @@ 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 { fetchStepFaces, stepHighlight, type StepFaces } from "@/lib/feature-faces"; +import { useBackendDown } from "@/lib/backend-link"; +import { historyWords } from "@/lib/history-words"; +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"; +import { isWords, saidIn } from "@/lib/words"; /** The pick intents and their keys: 1 vertex, 2 edge, 3 face, 4 solid (Plasticity's order), 5 component, 6 sketch. */ /** How long the left column slides from one mode to the other. */ @@ -87,10 +96,15 @@ const MODES = ALL_MODES.filter((item) => MANUAL_MODE || item.mode !== "sketch"); * selection into the notebook (see `selection.set`). */ /** The tabs of each mode; the workspace tab is in both (opening or making a notebook is not a code-only thing). */ const MANUAL_TABS = ["features", "assembly"]; +/** The faces of the step the feature tree points at (blue: apart from the orange of the selection). */ +const FEATURE_FACE_COLOR = "#2f6fe4"; +/** How long the pointer rests on a step's row before its faces are asked of the kernel. */ +const HOVER_ASK_MS = 100; const CODE_TABS = ["notebook", "module"]; export function App() { - useI18n(); // a change of language renders the whole editor again + const { language } = useI18n(); // a change of language renders the whole editor again + const backendDown = useBackendDown(); const viewRef = useRef(null); // Whether a model of the open notebook is on screen (it may be the last run's, // restored while the kernel boots): then nothing is being waited for. @@ -137,11 +151,23 @@ 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 [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([]); 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([]); @@ -179,6 +205,15 @@ export function App() { dialogRef.current = dialog; const [guiBusy, setGuiBusy] = useState(false); const [guiError, setGuiError] = useState(null); + // steps an undo or redo brought back where their old place was not certain: the tree asks the person to check the order + const [unsureCells, setUnsureCells] = useState([]); + // what the last undo or redo did, under the undo buttons for a few seconds + const [historyNote, setHistoryNote] = useState(null); + useEffect(() => { + if (!historyNote) return; + const timer = window.setTimeout(() => setHistoryNote(null), 6000); + return () => window.clearTimeout(timer); + }, [historyNote]); const modeBeforeDialog = useRef(null); // Sketch mode: drawing happens in the viewport (see components/sketch). `plane: null` is the plane choice. @@ -204,7 +239,10 @@ export function App() { () => sketchInfos(gui.state.features).map((info) => ({ ...info, doc: { ...info.doc, plane: resolvePlane(info.doc.plane, workplanes) } })), [gui.state.features, workplanes], ); - const sketchShapes = useSketchShapes(sketchList); + // drawn as the model is built: with the sliders' current values (a value tried and not yet written into the code too) + const paramValues = useMemo(() => new Map(params.flatMap((param) => (typeof param.value === "number" ? [[param.id, param.value] as const] : []))), [params]); + const sketchesAsBuilt = useMemo(() => sketchList.map((info) => withParamValues(info, paramValues)), [sketchList, paramValues]); + const sketchShapes = useSketchShapes(sketchesAsBuilt); const [hiddenSketches, setHiddenSketches] = useState>(() => new Set()); const hiddenRef = useRef(hiddenSketches); hiddenRef.current = hiddenSketches; @@ -458,24 +496,45 @@ 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))); + }); + + // 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) => { + // `said` is the translatable form of the message; a raw error of the kernel has none and shows as it came if (typeof envelope["error"] === "string") { - if (envelope["error"]) { - log.push("error", envelope["error"]); + const message = saidIn(envelope, "error"); + if (message) { + log.push("error", message); setLoading(null); + setExportState((current) => (current?.phase === "working" ? { phase: "error", message } : current)); } } else if (typeof envelope["info"] === "string") { - setStatus(t(envelope["info"])); - log.push("info", t(envelope["info"])); + const message = saidIn(envelope, "info") ?? ""; + setStatus(isWords(envelope["said"]) ? message : t(message)); + log.push("info", isWords(envelope["said"]) ? message : t(message)); setLoading(null); // a notice ends a wait as well (an empty notebook has no model to wait for) } else if (typeof envelope["working"] === "string") { - setStatus(envelope["working"]); - log.push("run", envelope["working"]); - setLoading(envelope["working"].replace(/…$/, "")); + const message = saidIn(envelope, "working") ?? ""; + setStatus(message); + log.push("run", message); + setLoading(message.replace(/…$/, "")); } 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"] })); @@ -605,6 +664,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]; @@ -656,8 +720,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(); @@ -665,6 +735,7 @@ export function App() { }, 600); return () => { window.clearTimeout(send); + window.clearTimeout(lost); window.clearTimeout(snapshot); }; }, [selection]); @@ -798,6 +869,21 @@ export function App() { editSessionPicksRef.current = editSessionPicks; /** Tune the numbers of a feature of the tree in place (Esc gives them back). */ + /** A step written as code (by the AI or by hand): its numbers (its params cell's sliders) tuned in the same panel as a + * feature made with the buttons, Enter keeps them in the code; with no numbers to tune, the code mode, where it is written. */ + const editCodeStep = useCallback((feature: FeatureRow) => { + if (sessionRef.current) confirmSession(); + if (!featureParams(paramsRef.current, feature.slug).length) { + log.push("info", t("{{name}} has no numbers to tune here: its code is open in code mode.", { name: feature.title || feature.slug })); + changeMode("code"); + return; + } + setSession({ + slug: feature.slug, cell: feature.cell, title: feature.title || t("Numbers"), specId: "", anchorMm: anchorRef.current, editing: true, busy: false, + error: null, handle: null, pick: null, edits: 0, + }); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [log.push]); const editInPlace = useCallback((feature: FeatureRow, spec: Spec): boolean => { if (!featureParams(paramsRef.current, feature.slug).length) return false; setSession({ @@ -839,16 +925,23 @@ export function App() { async (command: FeatureCommand) => { setGuiBusy(true); setGuiError(null); + setUnsureCells([]); + // what an undo or redo is about to change, in words, said once it is done ("已撤销:添加「球体」") + const doing = + command.op === "undo" ? historyWords(gui.state.undo_label, gui.state.features, gui.catalog) : command.op === "redo" ? historyWords(gui.state.redo_label, gui.state.features, gui.catalog) : null; try { const result = await gui.run(command); - log.push("ok", command.op === "undo" || command.op === "redo" ? t(command.op) : t("{{op}} {{name}}", { op: t(command.op), name: result.name })); + const done = doing ? (command.op === "undo" ? t("Undone: {{what}}", { what: doing }) : t("Redone: {{what}}", { what: doing })) : null; + log.push("ok", done ?? (command.op === "undo" || command.op === "redo" ? t(command.op) : t("{{op}} {{name}}", { op: t(command.op), name: result.name }))); + setHistoryNote(done); + setUnsureCells(result.unsure ?? []); } catch (error) { setGuiError(error instanceof Error ? error.message : String(error)); } finally { setGuiBusy(false); } }, - [gui.run, log.push], + [gui.run, gui.state, gui.catalog, log.push], ); const undo = useCallback(() => void runFeature({ op: "undo" }), [runFeature]); const redo = useCallback(() => void runFeature({ op: "redo" }), [runFeature]); @@ -898,11 +991,24 @@ export function App() { } else beginSketch({ mode: "new", name: "", plane: null, doc: emptyDoc() }); }, [beginSketch, noNotebook]); const endSketch = useCallback(() => { + madeForSketch.current = null; setSketchSession(null); setSketchNotice(null); if (modeBeforeSketch.current !== null) setSelectionMode(modeBeforeSketch.current); modeBeforeSketch.current = null; }, []); + // "Sketch on this face" adds a workplane first: a sketch given up removes it, so nothing is left of what was not drawn + // (the removal is one step of the history, like any other: undo brings the workplane back) + const madeForSketch = useRef<{ name: string; cell: string } | null>(null); + const cancelSketch = useCallback(() => { + const made = madeForSketch.current; + endSketch(); + if (!made) return; + void gui + .run({ op: "delete", cell: made.cell }) + .then(() => log.push("info", t("the sketch was cancelled: its workplane {{name}} was taken back", { name: made.name }))) + .catch(() => undefined); // it stays in the tree, where the person can delete or undo it + }, [endSketch, gui.run, log.push]); /** Finish: the add or edit command; rejects with the server's message (shown in the sketch bar), leaves sketch mode on success. * With `after.extrude` ("finish and extrude") the new sketch is selected and the extrude form opens on it. */ const submitSketch = useCallback( @@ -980,8 +1086,38 @@ export function App() { return; } setBarNote(null); - beginSketch({ mode: "new", name: "", plane: resolved.frame, doc: emptyDoc(resolved.frame) }); - }, [resolveFace, startSketch, beginSketch]); + // The sketch follows the face: a workplane on the face first (it names the face by reference, so it moves with it), the + // sketch on that workplane (its cell writes plane=). A frame of numbers would stay where the face was. + const request = workplaneRequest([face]); + let plane: Frame = resolved.frame; + if (request) { + setGuiBusy(true); + setGuiError(null); + try { + const selections = Object.fromEntries(Object.entries(request.selections).map(([slot, items]) => [slot, items.map(pickedPayload)])); + const result = await gui.run({ op: "add", spec: "workplane", values: { method: request.method }, selections }); + assertCellRan(result); + log.push("ok", t("added {{name}}", { name: result.name })); + // the kernel reports the workplane's own frame after the run: draw on it (until then, the face's frame, same plane) + const deadline = Date.now() + 5000; + let made = workplanesRef.current.find((wp) => wp.name === result.name); + while (!made && Date.now() < deadline) { + await new Promise((resolve) => window.setTimeout(resolve, 100)); + made = workplanesRef.current.find((wp) => wp.name === result.name); + } + plane = made ? workplanePlane(made) : frameSpec({ workplane: result.name, ...resolved.frame }); + madeForSketch.current = result.cell ? { name: result.name, cell: result.cell.id } : null; + } catch (error) { + setGuiError(error instanceof Error ? error.message : String(error)); + return; + } finally { + setGuiBusy(false); + } + } + const made = madeForSketch.current; + beginSketch({ mode: "new", name: "", plane, doc: emptyDoc(plane) }); + madeForSketch.current = made; // beginSketch does not end a sketch, but keep it explicit: this session made it + }, [resolveFace, startSketch, beginSketch, gui.run, log.push]); /** "Workplane from selection" (Space): the workplane cell of the constructor the selection names; it becomes the active * workplane and the camera turns to it once the kernel reports its frame. */ @@ -1332,6 +1468,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", @@ -1514,6 +1660,84 @@ export function App() { }; handleEditFeatureRef.current = handleEditFeature; + // A step of the tree shown on the model: the faces it made on the finished part (found by the recorded history), while + // the pointer is on its row or pinned by a click on it (both by cell). Only a highlight: the selection (what the AI is + // given) stays as it is. + const [pinnedStep, setPinnedStep] = useState(null); + const [hoverStep, setHoverStep] = useState(null); + const activeStep = hoverStep ?? pinnedStep; + // Asked of the server once per step and model (the live model carries no history), kept per step: what is shown for one + // row is never another row's answer (an answer still on its way is no answer yet). + const [stepFaces, setStepFaces] = useState>(new Map()); + const askedSteps = useRef(new Set()); + const faceVersion = useRef(sceneVersion); + useEffect(() => { + faceVersion.current = sceneVersion; // a new model: new faces + askedSteps.current = new Set(); + setStepFaces(new Map()); + }, [sceneVersion]); + const askFaces = useCallback((cell: string | null) => { + if (!cell || askedSteps.current.has(cell)) return; + askedSteps.current.add(cell); + const version = faceVersion.current; + void fetchStepFaces(cell) + .catch(() => ({ faces: [], nodes: [] })) + .then((found) => { + if (faceVersion.current === version) setStepFaces((previous) => new Map(previous).set(cell, found)); + }); + }, []); + // a clicked step is asked at once; a row the pointer passes over only once it rests there a moment, so sweeping down a + // long tree does not queue a kernel call per row + useEffect(() => { + if (pinnedStep && !stepFaces.has(pinnedStep)) askFaces(pinnedStep); + }, [pinnedStep, stepFaces, askFaces]); + useEffect(() => { + if (!hoverStep || stepFaces.has(hoverStep)) return; + const timer = window.setTimeout(() => askFaces(hoverStep), HOVER_ASK_MS); + return () => window.clearTimeout(timer); + }, [hoverStep, stepFaces, askFaces]); + const highlightOf = useCallback( + (cell: string | null) => { + const found = cell ? stepFaces.get(cell) : undefined; + if (!found) return null; + // a step that made the part on screen without faces of its own (a move, a scale) lights up the part as a whole + const shownPart = gui.state.product?.body ?? gui.state.tip; + const step = gui.state.features.find((feature) => feature.cell === cell); + return stepHighlight(found, Boolean(step && shownPart && step.makes.includes(shownPart))); + }, + [stepFaces, gui.state.product, gui.state.tip, gui.state.features], + ); + // the model shows the row under the pointer, else the clicked one; the clicked row's own note is about the clicked row + const activeHighlight = useMemo(() => highlightOf(activeStep), [highlightOf, activeStep]); + const pinnedHighlight = useMemo(() => highlightOf(pinnedStep), [highlightOf, pinnedStep]); + useEffect(() => { + const view = viewRef.current; + if (!view || !activeHighlight) return; + // a whole part is marked by its solid entity (a mark without an entity draws nothing) + const solids = activeHighlight.wholeNodes.flatMap((nodeId) => { + const node = view.nodes.find((item) => item.node_id === nodeId); + return (view.sidecarFor(node)?.entities ?? []).filter((entity) => entity.kind === "solid").map((entity) => ({ node: nodeId, entity: entity.entity_id })); + }); + const marks = [...activeHighlight.faces.map((face) => ({ node: face.nodeId, entity: face.entityId })), ...solids]; + for (const mark of marks) view.addMark(mark.node, mark.entity, FEATURE_FACE_COLOR); + return () => marks.forEach((mark) => view.removeMark(`${mark.node}::${mark.entity}`)); + }, [activeHighlight]); + // another notebook: what the tree showed or said was about the old one + useEffect(() => { + setPinnedStep(null); + setHoverStep(null); + setUnsureCells([]); + }, [currentPath]); + const treeShow = useMemo( + () => ({ + pinned: pinnedStep, + hover: hoverStep, + found: pinnedHighlight ? { faces: pinnedHighlight.faces.length, whole: pinnedHighlight.whole } : null, + onPin: setPinnedStep, + onHover: setHoverStep, + }), + [pinnedStep, hoverStep, pinnedHighlight], + ); const treeSketches = useMemo( () => ({ infos: sketchList, @@ -1568,7 +1792,7 @@ export function App() { <> {t("features")} {t("assembly")} - {t("workspace")} + {t("files")} ) : ( <> @@ -1578,19 +1802,31 @@ export function App() { )} + {!session && ( + socketRef.current?.send({ type: "param.commit", names })} + onRevert={(names) => socketRef.current?.send({ type: "param.revert", names })} + /> + )} setUnsureCells([])} onEdit={handleEditFeature} + onEditCode={editCodeStep} onDelete={(feature) => void runFeature({ op: "delete", cell: feature.cell })} onUseProduct={(body) => void runFeature({ op: "use_as_product", body })} onRepairRef={(cell, slot, index, choice) => void runFeature({ op: "ref_repair", cell, slot, index, choice })} onUndo={undo} onRedo={redo} + historyNote={historyNote} sketches={treeSketches} + show={treeShow} /> @@ -1699,7 +1935,19 @@ 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); + for (const feature of gui.state.features) { + const spec = feature.gui ? gui.catalog?.specs.find((item) => item.id === feature.gui?.spec) : undefined; + const name = feature.title || (spec ? t(plainLabel(spec.id, spec.label)) : ""); + if (name) names.set(feature.cell, name); + } + return names; + // 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 (
@@ -1711,7 +1959,21 @@ export function App() { status={status} themePreference={theme.preference} onTheme={theme.cycle} + onExport={() => { + setExportState({ phase: "working" }); + socketRef.current?.send({ type: "export.request" }); + }} /> + setExportState(null)} /> + {backendDown && ( + // the background service cannot be reached: say what that means and what to do, once, at the top +
+

{t("The editor's background service has disconnected.")}

+

+ {t("Changes made now are not saved, and a sketch being drawn cannot be finished. Start the service again (run sca edit in the terminal): this page reconnects by itself. If it does not, reload the page.")} +

+
+ )}
@@ -1739,7 +2001,7 @@ export function App() { ))}
-
+
{!MANUAL_MODE ? ( panelFor("code") ) : ( @@ -1881,18 +2143,34 @@ export function App() { }} onConfirm={confirmSession} onCancel={cancelSession} + moreLabel={session.specId ? undefined : t("Change it in code (code mode)")} onMore={() => { const current = sessionRef.current; const row = current?.cell ? gui.state.features.find((feature) => feature.cell === current.cell) : undefined; const spec = current ? gui.catalog?.specs.find((item) => item.id === current.specId) : undefined; confirmSession(); if (row && spec) setDialog({ spec, edit: row }); + else if (current && !current.specId) changeMode("code"); // a step written as code: its code }} /> )} {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 + }} + /> + )} {( : null} - rightNotice={partial && !sketching ? : null} + rightNotice={partial && !sketching ? : null} /> )} {sketchSession && viewRef.current && ( @@ -1917,7 +2195,7 @@ export function App() { workplanes={workplanes.map((wp) => ({ name: wp.name, plane: workplanePlane(wp) }))} onPlane={choosePlane} onSubmit={submitSketch} - onExit={endSketch} + onExit={cancelSketch} /> )}
diff --git a/editor-web/src/components/AskAiPanel.tsx b/editor-web/src/components/AskAiPanel.tsx new file mode 100644 index 00000000..25e55942 --- /dev/null +++ b/editor-web/src/components/AskAiPanel.tsx @@ -0,0 +1,258 @@ +import { Check, Loader2, MessageSquare, Minus, X, XCircle } from "lucide-react"; +import { useEffect, useRef, useState } from "react"; + +import { Button } from "@/components/ui/button"; +import { useI18n } from "@/i18n"; +import { clock, describeCounts, isSendKey, say, type AgentRequest } from "@/lib/agent-requests"; +import { useFloatingDrag } from "@/lib/useFloatingDrag"; +import { cn } from "@/lib/utils"; + +/** The "ask the AI" panel: what is picked, a box to say what to do with it, and the requests sent so far with their state. + * Sending hands the request to a coding agent that edits the notebook; the model updates on the page when it is done. */ +export function AskAiPanel({ + open, + targets, + requests, + loaded, + onSubmit, + onClose, + onOpen, +}: { + open: boolean; + /** What is picked, in words ("1 个面"); empty: nothing picked. */ + targets: string; + requests: readonly AgentRequest[]; + /** Whether the list the page opened with has arrived: requests finished before that count as seen (no pop-up on reload). */ + loaded: boolean; + /** Send the note; resolves when the server has taken it (the agent then runs on its own). */ + onSubmit: (note: string) => 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(t(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")} +
+