feat(editor): sca edit — the web editor, now part of the SDK
The editor moves in from sca-web-editor as simplecadapi.editor (UI sources in editor-web/, built into the package; 'editor' extra). It no longer records anything itself: the kernel runs the notebook with the SDK cell executor, the server asks it for the product (runtime.live.publish_live) when marimo reports a completed run, and parameters are saved values the executor applies, so marimo's dataflow reruns what reads them. Controls come from '# ui:' comments; a workspace is any directory of notebooks. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -70,3 +70,8 @@ examples/bowl_connector/re_work/
|
||||
examples/bowl_connector/__pycache__/
|
||||
examples/bowl_connector/.re_server.lock
|
||||
session-audit-*.md
|
||||
|
||||
# Editor web UI (built into the package: `cd editor-web && npm run build`)
|
||||
editor-web/node_modules/
|
||||
editor-web/dist/
|
||||
src/simplecadapi/editor/webui/
|
||||
|
||||
@@ -6,6 +6,29 @@ user-facing notes live in [`docs/updates/`](docs/updates/) (English and
|
||||
|
||||
## Unreleased
|
||||
|
||||
### Added
|
||||
|
||||
- `sca edit [WORKSPACE]`: the web editor, now part of the SDK
|
||||
(`simplecadapi.editor`, UI sources in `editor-web/`; needs the `editor`
|
||||
extra). It runs a workspace's notebooks in a marimo kernel with the SDK's
|
||||
own cell executor, so the editor, `sca run` and `run_notebook` share one
|
||||
runtime, and marimo's dataflow decides what a parameter change reruns.
|
||||
- Notebook parameters: the numbers, bools and `scad.var`s of a
|
||||
`# ---- params ----` cell are discoverable (`sca params`,
|
||||
`simplecadapi.runtime.params.list_parameters`) with an optional trailing
|
||||
`# ui: slider(min, max, step=, unit=, label=)` comment to pick the control.
|
||||
Existing notebooks need no change.
|
||||
- `sca ls [DIR]` lists the SimpleCAD notebooks under a directory (id, part or
|
||||
assembly, the notebooks each uses); `simplecadapi.runtime.workspace` also
|
||||
parses `# ---- feature: ... ----` headers.
|
||||
- `simplecadapi.runtime.live`: project the running kernel's product to a
|
||||
`.scadpkg` (`live_package`, `publish_live`).
|
||||
|
||||
### Fixed
|
||||
|
||||
- The notebook executor no longer fails on cells that are not part of the
|
||||
notebook (the editor's scratch cell raised `KeyError`).
|
||||
|
||||
### Changed
|
||||
|
||||
- pymupdf is no longer a default-install dependency: it is optional under
|
||||
|
||||
@@ -342,8 +342,14 @@ marimo edit bracket.py # reactive editor
|
||||
sca run bracket.py # run, print a JSON report
|
||||
sca run bracket.py --set width=80 --out out/bracket.scadpkg
|
||||
sca export out/bracket.scadpkg --output-dir out/exports # AP242 STEP, STL, OBJ
|
||||
sca edit . # web editor over this directory of notebooks
|
||||
```
|
||||
|
||||
`sca edit` (`pip install "simplecadapi[editor]"`) is a code-first editor: the
|
||||
notebook's cells on the left, the live model on the right, and a slider or
|
||||
toggle for every parameter (`# ---- params ----` cells; a `# ui:` comment on
|
||||
the line picks the control). See `docs/skill/references/docs/guides/notebook-runtime.md`.
|
||||
|
||||
## Notebook Runtime
|
||||
|
||||
The same runtime runs a notebook in the marimo editor, under `sca run`, and
|
||||
|
||||
@@ -133,7 +133,9 @@ In a notebook every block is one `@app.cell`:
|
||||
the exception.
|
||||
- Parameters live in their own cell(s) at the top (`# ---- params ----`),
|
||||
grouped by what is overridden together: an override replaces every
|
||||
variable of its cell. The product — the `Part` or `Assembly` whose id is
|
||||
variable of its cell. A trailing `# ui: slider(min, max, step=, unit=,
|
||||
label=)` comment (or `number(...)`, `toggle()`) on a parameter's line
|
||||
chooses the control an editor offers; see the notebook runtime guide. The product — the `Part` or `Assembly` whose id is
|
||||
the notebook id — is made in the last cell. A notebook that describes a part family names the
|
||||
product `scad.notebook_id()`, and each use gives the member its id
|
||||
(`scad.use("link_bar.py", id="crank", ...)`).
|
||||
|
||||
@@ -142,6 +142,45 @@ run.values["width"] # any top-level variable
|
||||
|
||||
Errors raised by a cell propagate unchanged.
|
||||
|
||||
## Parameters and the editor
|
||||
|
||||
A **parameter** is a top-level variable a cell assigns a number, a bool, or a
|
||||
`scad.var`, in a cell headed `# ---- params ----` (or `# ---- params: <group> ----`).
|
||||
No change to a notebook is needed for an editor to list them. A trailing
|
||||
`# ui:` comment on the line says which control to offer:
|
||||
|
||||
```python
|
||||
# ---- params ----
|
||||
OUTER_D = scad.var("outer_d", 100.0, unit="mm") # ui: slider(50, 200, step=1, label="Outer diameter")
|
||||
BOLTS = 6 # ui: number(3, 12, step=1)
|
||||
CHAMFER = True # no comment: a toggle, inferred
|
||||
```
|
||||
|
||||
`slider(min, max, step=)`, `number(min=, max=, step=)` and `toggle()` take
|
||||
`unit=` and `label=`. Without the comment a number gets a number box and a
|
||||
bool a toggle. A bad comment is reported (`sca params`) and the inferred
|
||||
control is used. A `scad.var`'s `unit` and `comment` show up in the editor.
|
||||
|
||||
```bash
|
||||
sca params bracket.py # features (# ---- feature: ... ---- headers) and parameters, from the file
|
||||
sca ls [DIR] # the notebooks under DIR: id, part or assembly, the notebooks each uses
|
||||
```
|
||||
|
||||
A **workspace** is any directory tree: its models are the notebooks whose
|
||||
header has `[tool.simplecadapi]`, wherever they are. There is no manifest.
|
||||
|
||||
`sca edit [WORKSPACE]` (needs `pip install "simplecadapi[editor]"`) opens a
|
||||
code-first editor on a workspace. The notebooks run in a marimo kernel with
|
||||
this runtime's executor, so a model gives the same product in the editor as
|
||||
under `sca run`; marimo's dataflow decides what reruns. A slider does not
|
||||
edit the file: the editor saves the value (`params.json` in the notebook's
|
||||
state directory), the kernel executor applies it as the declaring cell
|
||||
finishes, and marimo reruns the cells that read it. **Write to source**
|
||||
commits the saved values into the notebook; **revert** drops them. A headless
|
||||
run takes only the overrides it is given, never the saved values, and the
|
||||
notebook an assembly `use`s is run from its file: tune a part by opening it
|
||||
and writing the value to source.
|
||||
|
||||
## Composing notebooks
|
||||
|
||||
`scad.use(path, **overrides)` runs another notebook and returns its product,
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the Oxlint configuration
|
||||
|
||||
If you are developing a production application, we recommend enabling type-aware lint rules by installing `oxlint-tsgolint` and editing `.oxlintrc.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"options": {
|
||||
"typeAware": true
|
||||
},
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See the [Oxlint rules documentation](https://oxc.rs/docs/guide/usage/linter/rules) for the full list of rules and categories.
|
||||
@@ -0,0 +1,12 @@
|
||||
<!doctype html>
|
||||
<html lang="en" class="dark">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>SimpleCAD Studio</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
Generated
+3008
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,46 @@
|
||||
{
|
||||
"name": "simplecad-editor-web",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc --noEmit -p tsconfig.json && vite build",
|
||||
"lint": "oxlint",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit -p tsconfig.json"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/lang-python": "^6.2.1",
|
||||
"@codemirror/theme-one-dark": "^6.1.3",
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@types/three": "^0.186.0",
|
||||
"@uiw/react-codemirror": "^4.25.12",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"fflate": "^0.8.3",
|
||||
"lucide-react": "^1.48.0",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
"react-resizable-panels": "^4.13.3",
|
||||
"tailwind-merge": "^3.7.0",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"three": "^0.186.1",
|
||||
"tw-animate-css": "^1.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@radix-ui/react-scroll-area": "^1.2.18",
|
||||
"@radix-ui/react-separator": "^1.1.15",
|
||||
"@radix-ui/react-slider": "^1.4.7",
|
||||
"@radix-ui/react-slot": "^1.3.3",
|
||||
"@radix-ui/react-tabs": "^1.1.21",
|
||||
"@radix-ui/react-tooltip": "^1.2.16",
|
||||
"@types/node": "^24.13.3",
|
||||
"@types/react": "^19.2.18",
|
||||
"@types/react-dom": "^19.2.7",
|
||||
"@vitejs/plugin-react": "^6.1.1",
|
||||
"oxlint": "^1.81.0",
|
||||
"typescript": "~6.0.2",
|
||||
"vite": "^8.3.0"
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 9.3 KiB |
@@ -0,0 +1,24 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||
</symbol>
|
||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||
</symbol>
|
||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||
</symbol>
|
||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||
</symbol>
|
||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,251 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
|
||||
import { CellEditor, type NotebookCell, type NotebookFeature, type ParamMeta } from "@/components/CellEditor";
|
||||
import { Header } from "@/components/Header";
|
||||
import { Inspector, type FederatedNode } from "@/components/Inspector";
|
||||
import { NotebookList } from "@/components/NotebookList";
|
||||
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@/components/ui/resizable";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import {
|
||||
fetchPackage,
|
||||
getWorkspace,
|
||||
newNotebook,
|
||||
openNotebook,
|
||||
select as publishSelection,
|
||||
type NotebookRow,
|
||||
} from "@/lib/api";
|
||||
import { EnvelopeSocket, type Envelope } from "@/lib/envelope";
|
||||
import { Viewport, type PickResult, type SelectionMode } from "@/scene/Viewport";
|
||||
import { openCadPackage } from "@/scene/product-package";
|
||||
import { buildFederatedFeatureModel } from "@/scene/scene2";
|
||||
import type { SceneView } from "@/scene/scene-view";
|
||||
|
||||
type FederatedModel = ReturnType<typeof buildFederatedFeatureModel>["model"];
|
||||
|
||||
/** Editor application: left = workspace + notebook editing, right = live
|
||||
* model preview driven by the in-memory scadpkg stream (architecture rule 4).
|
||||
*/
|
||||
export function App() {
|
||||
const viewRef = useRef<SceneView | null>(null);
|
||||
const socketRef = useRef<EnvelopeSocket | null>(null);
|
||||
|
||||
const [notebooks, setNotebooks] = useState<NotebookRow[]>([]);
|
||||
const [notebook, setNotebook] = useState<string | null>(null);
|
||||
const [kind, setKind] = useState<string | null>(null);
|
||||
const [kernelAlive, setKernelAlive] = useState(false);
|
||||
const [marimoUrl, setMarimoUrl] = useState<string | null>(null);
|
||||
const [status, setStatus] = useState("Connecting…");
|
||||
|
||||
const [params, setParams] = useState<ParamMeta[]>([]);
|
||||
const [cells, setCells] = useState<NotebookCell[]>([]);
|
||||
const [features, setFeatures] = useState<NotebookFeature[]>([]);
|
||||
const [federated, setFederated] = useState<FederatedNode[]>([]);
|
||||
const [pick, setPick] = useState<PickResult | null>(null);
|
||||
const [selectionMode, setSelectionMode] = useState<SelectionMode>("solid");
|
||||
const [packageInfo, setPackageInfo] = useState<{
|
||||
name: string | null;
|
||||
revision: number;
|
||||
occurrences: number;
|
||||
assets: number;
|
||||
exported: string | null;
|
||||
} | null>(null);
|
||||
|
||||
// -- package → viewport (the UI update path) --------------------------------
|
||||
|
||||
// Camera framing is disruptive during slider drags; frame once per notebook.
|
||||
const framedNotebook = useRef<string | null>(null);
|
||||
|
||||
const loadPackageBytes = useCallback(async (bytes: Uint8Array, revision: number, name: string | null) => {
|
||||
const view = viewRef.current;
|
||||
if (!view) return;
|
||||
try {
|
||||
const opened = await openCadPackage(bytes);
|
||||
await view.loadScene(opened.files);
|
||||
const manifest = view.engine.manifest;
|
||||
if (!manifest) throw new Error("scene manifest missing");
|
||||
const federatedModel = buildFederatedFeatureModel(manifest, opened.files);
|
||||
setFederated(
|
||||
federatedModel.model.graph.nodes.map((node) => ({
|
||||
id: node.node_id,
|
||||
label: node.display?.label ?? node.op,
|
||||
kind: node.op,
|
||||
})),
|
||||
);
|
||||
setPackageInfo({
|
||||
name,
|
||||
revision,
|
||||
occurrences: manifest.nodes.length,
|
||||
assets: manifest.geometry_assets.length,
|
||||
exported: null,
|
||||
});
|
||||
setStatus(
|
||||
`${manifest.nodes.length} occurrences · ${manifest.geometry_assets.length} geometry assets · ${federatedModel.model.graph.nodes.length} features`,
|
||||
);
|
||||
if (framedNotebook.current !== name) {
|
||||
view.frame();
|
||||
framedNotebook.current = name;
|
||||
}
|
||||
} catch (error) {
|
||||
setStatus(error instanceof Error ? error.message : "Unable to open package");
|
||||
}
|
||||
}, []);
|
||||
|
||||
// -- socket + lifecycle ------------------------------------------------------
|
||||
|
||||
useEffect(() => {
|
||||
const socket = new EnvelopeSocket(`ws://${window.location.host}/ws`);
|
||||
socketRef.current = socket;
|
||||
|
||||
socket.on("hello", (envelope) => {
|
||||
setNotebook((envelope["notebook"] as string) ?? null);
|
||||
setKernelAlive(Boolean(envelope["kernel"]));
|
||||
setMarimoUrl((envelope["marimo_url"] as string) ?? null);
|
||||
void getWorkspace().then((data) => {
|
||||
setNotebooks(data.notebooks);
|
||||
const current = data.notebooks.find((row) => row.current);
|
||||
if (current) setKind(current.kind);
|
||||
});
|
||||
});
|
||||
|
||||
socket.on("params.schema", (envelope) => {
|
||||
const vars = (envelope["vars"] as ParamMeta[] | undefined) ?? [];
|
||||
setParams(vars.map((param) => ({ ...param })));
|
||||
});
|
||||
|
||||
socket.on("params.values", (envelope) => {
|
||||
const values = envelope["values"] as Record<string, number | boolean>;
|
||||
setParams((previous) =>
|
||||
previous.map((param) => (param.id in values ? { ...param, value: values[param.id] } : param)),
|
||||
);
|
||||
});
|
||||
|
||||
socket.on("notebook.cells", (envelope) => setCells((envelope["cells"] as NotebookCell[]) ?? []));
|
||||
socket.on("notebook.features", (envelope) => setFeatures((envelope["features"] as NotebookFeature[]) ?? []));
|
||||
|
||||
socket.on("package", (envelope) => {
|
||||
const revision = Number(envelope["revision"] ?? 0);
|
||||
void fetchPackage().then((bytes) =>
|
||||
loadPackageBytes(bytes, revision, (envelope["name"] as string) ?? null),
|
||||
);
|
||||
});
|
||||
|
||||
socket.on("status", (envelope) => {
|
||||
// An empty error means "the model is fine again": keep the package line.
|
||||
if (typeof envelope["error"] === "string") {
|
||||
if (envelope["error"]) setStatus(`error: ${envelope["error"]}`);
|
||||
}
|
||||
else if (typeof envelope["exported"] === "string") {
|
||||
setStatus(`exported ${envelope["exported"]}`);
|
||||
setPackageInfo((previous) => (previous ? { ...previous, exported: envelope["exported"] as string } : previous));
|
||||
} else if (typeof envelope["created"] === "string") setStatus(`created ${envelope["created"]}`);
|
||||
});
|
||||
|
||||
socket.connect();
|
||||
return () => socket.close();
|
||||
}, [loadPackageBytes]);
|
||||
|
||||
// -- actions ------------------------------------------------------------------
|
||||
|
||||
const handlePick = useCallback((result: PickResult) => {
|
||||
setPick(result);
|
||||
// Publish for agents (GET /api/studio/selected), including a compact
|
||||
// entity payload so the agent sees what the human sees.
|
||||
void publishSelection({
|
||||
notebook: notebook,
|
||||
node_id: result.nodeId,
|
||||
entity_id: result.entityId,
|
||||
mode: result.mode,
|
||||
entity: result.entity
|
||||
? { kind: result.entity.kind, id: result.entity.entity_id, data: result.entity.properties ?? null }
|
||||
: null,
|
||||
}).catch(() => undefined);
|
||||
}, [notebook]);
|
||||
|
||||
const refreshWorkspace = useCallback(() => {
|
||||
void getWorkspace().then((data) => {
|
||||
setNotebooks(data.notebooks);
|
||||
const current = data.notebooks.find((row) => row.current);
|
||||
setKind(current?.kind ?? null);
|
||||
});
|
||||
}, []);
|
||||
|
||||
const handleOpen = (path: string) => {
|
||||
setStatus(`opening ${path}…`);
|
||||
openNotebook(path)
|
||||
.then(refreshWorkspace)
|
||||
.catch((error) => setStatus(`open failed: ${error.message}`));
|
||||
};
|
||||
|
||||
const handleNew = (name: string, newKind: "part" | "assembly") => {
|
||||
newNotebook(name, newKind)
|
||||
.then(refreshWorkspace)
|
||||
.catch((error) => setStatus(`create failed: ${error.message}`));
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex h-screen flex-col overflow-hidden">
|
||||
<Header
|
||||
notebook={notebook}
|
||||
kind={kind}
|
||||
kernelAlive={kernelAlive}
|
||||
status={status}
|
||||
marimoUrl={marimoUrl}
|
||||
onExport={() => socketRef.current?.send({ type: "export.request" })}
|
||||
onRerun={() => socketRef.current?.send({ type: "rerun.request" })}
|
||||
onNewNotebook={handleNew}
|
||||
/>
|
||||
<ResizablePanelGroup className="min-h-0 flex-1">
|
||||
<ResizablePanel defaultSize={30} minSize={18} className="min-w-0">
|
||||
<Tabs defaultValue="notebook" className="h-full">
|
||||
<TabsList className="mx-2 mt-2">
|
||||
<TabsTrigger value="notebook">notebook</TabsTrigger>
|
||||
<TabsTrigger value="workspace">workspace</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="notebook" className="h-[calc(100%-3rem)]">
|
||||
<CellEditor cells={cells} features={features} params={params} socket={socketRef.current} />
|
||||
</TabsContent>
|
||||
<TabsContent value="workspace" className="h-[calc(100%-3rem)]">
|
||||
<NotebookList notebooks={notebooks} onOpen={handleOpen} />
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
</ResizablePanel>
|
||||
<ResizableHandle />
|
||||
<ResizablePanel defaultSize={48} minSize={30} className="min-w-0">
|
||||
<div className="flex h-full flex-col">
|
||||
<div className="flex items-center gap-1.5 border-b px-2 py-1">
|
||||
{(["solid", "face", "edge"] as SelectionMode[]).map((mode) => (
|
||||
<button
|
||||
key={mode}
|
||||
type="button"
|
||||
className={`rounded px-2 py-0.5 text-[10px] font-semibold uppercase ${
|
||||
selectionMode === mode ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:bg-accent"
|
||||
}`}
|
||||
onClick={() => setSelectionMode(mode)}
|
||||
>
|
||||
{mode}
|
||||
</button>
|
||||
))}
|
||||
<span className="flex-1" />
|
||||
<button
|
||||
type="button"
|
||||
className="rounded px-2 py-0.5 text-[10px] font-semibold uppercase text-muted-foreground hover:bg-accent"
|
||||
onClick={() => viewRef.current?.frame()}
|
||||
>
|
||||
fit
|
||||
</button>
|
||||
</div>
|
||||
<div className="min-h-0 flex-1">
|
||||
<Viewport viewRef={viewRef} selectionMode={selectionMode} onPick={handlePick} />
|
||||
</div>
|
||||
</div>
|
||||
</ResizablePanel>
|
||||
<ResizableHandle />
|
||||
<ResizablePanel defaultSize={22} minSize={14} className="min-w-0">
|
||||
<Inspector pick={pick} features={federated} packageInfo={packageInfo} />
|
||||
</ResizablePanel>
|
||||
</ResizablePanelGroup>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export type { Envelope };
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 13 KiB |
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 8.5 KiB |
@@ -0,0 +1,443 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import CodeMirror from "@uiw/react-codemirror";
|
||||
import { python } from "@codemirror/lang-python";
|
||||
import { oneDark } from "@codemirror/theme-one-dark";
|
||||
import { Loader2, Play, Plus, RotateCcw } from "lucide-react";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Slider } from "@/components/ui/slider";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
export type NotebookCell = {
|
||||
id: string;
|
||||
name: string;
|
||||
code: string;
|
||||
status?: string | null;
|
||||
errors?: string[] | null;
|
||||
output?: string | null;
|
||||
console?: string[];
|
||||
/** Slug of the cell's `# ---- feature: ... ----` header, if it has one. */
|
||||
feature?: string | null;
|
||||
};
|
||||
/** One feature header; `cell` is the id of the cell it opens. */
|
||||
export type NotebookFeature = { cell: string; label: string; kind?: string };
|
||||
export type ParamValue = number | boolean;
|
||||
/** A parameter the notebook declares (see `sca params`); `cell` is the id of
|
||||
* the declaring cell. `modified`: the value differs from the source. */
|
||||
export type ParamMeta = {
|
||||
id: string;
|
||||
label: string;
|
||||
cell: string;
|
||||
group: string;
|
||||
kind: "float" | "int" | "bool";
|
||||
control: "slider" | "number" | "toggle";
|
||||
min: number | null;
|
||||
max: number | null;
|
||||
step: number | null;
|
||||
unit: string | null;
|
||||
default: ParamValue;
|
||||
value: ParamValue;
|
||||
modified?: boolean;
|
||||
comment?: string | null;
|
||||
issues?: string[];
|
||||
};
|
||||
|
||||
type SocketLike = { send: (message: Record<string, unknown>) => void } | null;
|
||||
|
||||
/** The notebook document, laid out like marimo's own webui:
|
||||
*
|
||||
* [① gutter] [ code editor ]
|
||||
* [ ] [ output / ui elements ] ← params sliders live here
|
||||
* [ ] [ console (dimmer) ]
|
||||
*
|
||||
* Hovering the gap between cells reveals a "+" (insert cell). The gutter
|
||||
* circle is the run control; the smaller circle below it is the two-stage
|
||||
* rollback (delete the cell and restore the state before it). Ctrl+Enter or
|
||||
* the gutter runs the cell via `code.edit`; the package event refreshes
|
||||
* everything else.
|
||||
*/
|
||||
export function CellEditor({
|
||||
cells,
|
||||
features,
|
||||
params,
|
||||
socket,
|
||||
}: {
|
||||
cells: NotebookCell[];
|
||||
features: NotebookFeature[];
|
||||
params: ParamMeta[];
|
||||
socket: SocketLike;
|
||||
}) {
|
||||
const [drafts, setDrafts] = useState<Map<string, string>>(new Map());
|
||||
const [running, setRunning] = useState<string | null>(null);
|
||||
// Two-stage rollback: arm on the first gutter click (button red, cell
|
||||
// dimmed), confirm on the second; any click elsewhere disarms.
|
||||
const [armedRollback, setArmedRollback] = useState<string | null>(null);
|
||||
|
||||
const featureByCell = new Map(features.map((feature) => [feature.cell, feature]));
|
||||
|
||||
// Differential semantics: the server rolls the runtime back to cell-1,
|
||||
// runs this cell, and leaves the suffix stale.
|
||||
const run = (cell: NotebookCell) => {
|
||||
const code = drafts.get(cell.id) ?? cell.code;
|
||||
setRunning(cell.id);
|
||||
socket?.send({ type: "code.edit", cell: cell.id, code });
|
||||
window.setTimeout(() => setRunning((current) => (current === cell.id ? null : current)), 2500);
|
||||
};
|
||||
|
||||
const rollback = (cell: NotebookCell) => {
|
||||
setArmedRollback(null);
|
||||
socket?.send({ type: "rollback.request", cell: cell.id });
|
||||
};
|
||||
|
||||
const insert = (after: string | null) => {
|
||||
socket?.send({ type: "insert.request", after });
|
||||
};
|
||||
|
||||
// Forward slider bursts; the server coalesces (latest-wins rebuild).
|
||||
const pendingParams = useRef(new Map<string, ParamValue>());
|
||||
const paramTimer = useRef<number | null>(null);
|
||||
const forwardParam = (id: string, value: ParamValue) => {
|
||||
pendingParams.current.set(id, value);
|
||||
if (paramTimer.current !== null) return;
|
||||
paramTimer.current = window.setTimeout(() => {
|
||||
paramTimer.current = null;
|
||||
socket?.send({ type: "param.set", values: Object.fromEntries(pendingParams.current) });
|
||||
pendingParams.current.clear();
|
||||
}, 60);
|
||||
};
|
||||
|
||||
// Disarm rollback when clicking anywhere outside the armed button.
|
||||
useEffect(() => {
|
||||
if (!armedRollback) return;
|
||||
const onPointerDown = (event: PointerEvent) => {
|
||||
const target = event.target as HTMLElement | null;
|
||||
if (!target?.closest(`[data-rollback-armed="${CSS.escape(armedRollback)}"]`)) {
|
||||
setArmedRollback(null);
|
||||
}
|
||||
};
|
||||
window.addEventListener("pointerdown", onPointerDown, true);
|
||||
return () => window.removeEventListener("pointerdown", onPointerDown, true);
|
||||
}, [armedRollback]);
|
||||
|
||||
if (cells.length === 0) {
|
||||
return <p className="p-3 text-xs text-muted-foreground">Waiting for the kernel to publish cells…</p>;
|
||||
}
|
||||
// marimo-style insertion affordance: hover the gap between cells.
|
||||
const gaps: (string | null)[] = [null, ...cells.map((c) => c.id)];
|
||||
return (
|
||||
<ScrollArea className="h-full">
|
||||
<div className="px-2 py-2">
|
||||
{cells.map((cell, index) => (
|
||||
<div key={cell.id}>
|
||||
<CellGap after={gaps[index]} onInsert={insert} />
|
||||
<CellCard
|
||||
cell={cell}
|
||||
index={index}
|
||||
feature={featureByCell.get(cell.id)}
|
||||
params={params.filter((param) => param.cell === cell.id)}
|
||||
draft={drafts.get(cell.id)}
|
||||
dirty={drafts.get(cell.id) !== undefined && drafts.get(cell.id) !== cell.code}
|
||||
runningName={running}
|
||||
socket={socket}
|
||||
forwardParam={forwardParam}
|
||||
onRun={run}
|
||||
onRollback={rollback}
|
||||
onDraftChange={(value) =>
|
||||
setDrafts((previous) => {
|
||||
const next = new Map(previous);
|
||||
next.set(cell.id, value);
|
||||
return next;
|
||||
})
|
||||
}
|
||||
armed={armedRollback === cell.id}
|
||||
onArm={() => setArmedRollback((current) => (current === cell.id ? null : cell.id))}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
<CellGap after={cells[cells.length - 1].id} onInsert={insert} />
|
||||
</div>
|
||||
</ScrollArea>
|
||||
);
|
||||
}
|
||||
|
||||
/** Hover divider between cells with a "+" insertion button. */
|
||||
function CellGap({ after, onInsert }: { after: string | null; onInsert: (after: string | null) => void }) {
|
||||
return (
|
||||
<div className="group/gap relative flex h-4 items-center justify-start">
|
||||
<div className="absolute inset-x-4 h-px bg-transparent transition-colors group-hover/gap:bg-border" />
|
||||
<button
|
||||
type="button"
|
||||
title="Insert cell here"
|
||||
className="z-10 ml-10 flex h-5 w-5 items-center justify-center rounded-full border bg-card text-muted-foreground opacity-0 shadow-sm transition-opacity hover:border-primary/50 hover:text-foreground group-hover/gap:opacity-100"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onInsert(after);
|
||||
}}
|
||||
>
|
||||
<Plus className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** One cell document: gutter controls + code + output + console. */
|
||||
function CellCard({
|
||||
cell,
|
||||
index,
|
||||
feature,
|
||||
params,
|
||||
draft,
|
||||
dirty,
|
||||
runningName,
|
||||
socket,
|
||||
forwardParam,
|
||||
onRun,
|
||||
onRollback,
|
||||
onDraftChange,
|
||||
armed,
|
||||
onArm,
|
||||
}: {
|
||||
cell: NotebookCell;
|
||||
index: number;
|
||||
feature?: NotebookFeature;
|
||||
params: ParamMeta[];
|
||||
draft: string | undefined;
|
||||
dirty: boolean;
|
||||
runningName: string | null;
|
||||
socket: SocketLike;
|
||||
forwardParam: (id: string, value: ParamValue) => void;
|
||||
onRun: (cell: NotebookCell) => void;
|
||||
onRollback: (cell: NotebookCell) => void;
|
||||
onDraftChange: (value: string) => void;
|
||||
armed: boolean;
|
||||
onArm: () => void;
|
||||
}) {
|
||||
const failed = cell.status === "exception" || cell.status === "error";
|
||||
const stale = cell.status === "stale";
|
||||
const isRunning = runningName === cell.id || cell.status === "running";
|
||||
const hasOutput =
|
||||
Boolean(cell.output) || (cell.console?.length ?? 0) > 0 || params.length > 0;
|
||||
return (
|
||||
// marimo cells are open documents: spacing + hover outline, not cards.
|
||||
<section
|
||||
className={cn(
|
||||
"group relative flex gap-1 rounded-md py-0.5 transition-colors hover:bg-white/[0.02]",
|
||||
stale && "opacity-55",
|
||||
)}
|
||||
>
|
||||
{/* gutter: run control + state, rollback below it */}
|
||||
<div className="flex shrink-0 flex-col items-center gap-1 pt-1">
|
||||
<button
|
||||
type="button"
|
||||
title={failed ? "cell failed — click to rerun" : `run ${cell.feature ?? cell.name}`}
|
||||
className={cn(
|
||||
"flex h-7 w-7 shrink-0 items-center justify-center rounded-full border text-[10px] font-semibold",
|
||||
isRunning
|
||||
? "border-primary/40 text-primary"
|
||||
: failed
|
||||
? "border-destructive/60 bg-destructive/15 text-destructive"
|
||||
: dirty
|
||||
? "border-amber-500/50 text-amber-400 hover:bg-accent"
|
||||
: "border-transparent text-muted-foreground/60 group-hover:border-border group-hover:text-muted-foreground",
|
||||
)}
|
||||
onClick={() => onRun(cell)}
|
||||
>
|
||||
{isRunning ? (
|
||||
<Loader2 className="h-3.5 w-3.5 animate-spin" />
|
||||
) : failed ? (
|
||||
<span className="h-2 w-2 rounded-full bg-destructive" />
|
||||
) : dirty ? (
|
||||
<span className="h-2 w-2 rounded-full bg-amber-400" />
|
||||
) : (
|
||||
<>
|
||||
<span className="group-hover:hidden">{index + 1}</span>
|
||||
<Play className="hidden h-3 w-3 group-hover:block" />
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
{/* rollback: first click arms (button turns solid red, content
|
||||
dims); second click on it confirms; any click elsewhere disarms. */}
|
||||
<button
|
||||
type="button"
|
||||
data-rollback-armed={cell.id}
|
||||
title={
|
||||
armed
|
||||
? "Click again to delete this cell and roll back"
|
||||
: "Rollback: delete this cell and restore the state before it"
|
||||
}
|
||||
className={cn(
|
||||
"flex h-7 w-7 shrink-0 items-center justify-center rounded-full border text-[10px] font-semibold",
|
||||
armed
|
||||
? "border-destructive bg-destructive text-destructive-foreground opacity-100"
|
||||
: "border-transparent text-muted-foreground/60 opacity-0 group-hover:border-border group-hover:text-muted-foreground group-hover:opacity-100",
|
||||
)}
|
||||
onClick={() => {
|
||||
if (armed) {
|
||||
onArm();
|
||||
onRollback(cell);
|
||||
} else {
|
||||
onArm();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<RotateCcw className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
<div className={cn("min-w-0 flex-1", armed && "opacity-40 grayscale")}>
|
||||
<div className="relative">
|
||||
<CodeMirror
|
||||
value={draft ?? cell.code}
|
||||
height="auto"
|
||||
extensions={[python()]}
|
||||
theme={oneDark}
|
||||
basicSetup={{ lineNumbers: false, foldGutter: false, highlightActiveLine: false }}
|
||||
onChange={onDraftChange}
|
||||
onKeyDown={(event) => {
|
||||
if ((event.ctrlKey || event.metaKey) && event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
onRun(cell);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{/* identity chips float over the editor's top-right corner */}
|
||||
<span className="pointer-events-none absolute right-2 top-1 z-10 flex items-center gap-1.5">
|
||||
{feature && (
|
||||
<Badge variant="secondary" className="normal-case">
|
||||
{feature.label}
|
||||
{feature.kind ? ` · ${feature.kind}` : ""}
|
||||
</Badge>
|
||||
)}
|
||||
{stale && (
|
||||
<Badge variant="outline" className="text-amber-400">
|
||||
stale
|
||||
</Badge>
|
||||
)}
|
||||
<span className="font-mono text-[10px] text-muted-foreground">{cell.name === "_" ? "" : cell.name}</span>
|
||||
</span>
|
||||
</div>
|
||||
{/* errors: marimo puts the exception box under the code */}
|
||||
{(cell.errors?.length ?? 0) > 0 && (
|
||||
<div className="mx-2 my-1 rounded border border-destructive/40 bg-destructive/10 px-2 py-1">
|
||||
{cell.errors?.map((message, errorIndex) => (
|
||||
<pre key={errorIndex} className="whitespace-pre-wrap text-[11px] text-destructive">
|
||||
{message}
|
||||
</pre>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{/* output zone: ui elements (params) first, then rich output */}
|
||||
{hasOutput && (
|
||||
<div className="px-2 py-1">
|
||||
{params.length > 0 && (
|
||||
<div className="pb-1">
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-1.5">
|
||||
{params.map((param) => (
|
||||
<ParamControl key={param.id} param={param} forwardParam={forwardParam} />
|
||||
))}
|
||||
</div>
|
||||
{params.some((param) => param.modified) && (
|
||||
<div className="flex justify-end gap-2 pt-1 text-[10px] uppercase">
|
||||
<button
|
||||
type="button"
|
||||
className="text-muted-foreground hover:text-foreground"
|
||||
title="Drop the edited values; back to what the source says"
|
||||
onClick={() => socket?.send({ type: "param.revert", names: params.filter((p) => p.modified).map((p) => p.id) })}
|
||||
>
|
||||
revert
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="text-primary hover:text-primary/80"
|
||||
title="Write the edited values into the notebook source"
|
||||
onClick={() => socket?.send({ type: "param.commit", names: params.filter((p) => p.modified).map((p) => p.id) })}
|
||||
>
|
||||
write to source
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{cell.output && (
|
||||
<pre className="max-h-44 overflow-auto whitespace-pre-wrap text-xs text-foreground/90">{cell.output}</pre>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{/* console: stdout/stderr under the output, marimo-style */}
|
||||
{(cell.console?.length ?? 0) > 0 && (
|
||||
<div className="max-h-44 overflow-auto border-l-2 border-border px-2 py-0.5">
|
||||
{cell.console?.map((line, lineIndex) => (
|
||||
<pre
|
||||
key={lineIndex}
|
||||
className={cn(
|
||||
"whitespace-pre-wrap text-[11px]",
|
||||
/error|traceback|failed/i.test(line) ? "text-destructive" : "text-muted-foreground",
|
||||
)}
|
||||
>
|
||||
{line}
|
||||
</pre>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
/** One parameter: a slider, a number box or a toggle, by its `# ui:` comment. */
|
||||
function ParamControl({
|
||||
param,
|
||||
forwardParam,
|
||||
}: {
|
||||
param: ParamMeta;
|
||||
forwardParam: (id: string, value: ParamValue) => void;
|
||||
}) {
|
||||
const label = param.label || param.id;
|
||||
const title = [param.comment, ...(param.issues ?? [])].filter(Boolean).join("\n") || undefined;
|
||||
if (param.control === "toggle") {
|
||||
return (
|
||||
<label className="flex items-center justify-between text-[11px]" title={title}>
|
||||
<span className={cn("text-muted-foreground", param.modified && "text-amber-400")}>{label}</span>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={Boolean(param.value)}
|
||||
onChange={(event) => forwardParam(param.id, event.target.checked)}
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
const value = Number(param.value);
|
||||
return (
|
||||
<div title={title}>
|
||||
<div className="mb-0.5 flex items-baseline justify-between text-[11px]">
|
||||
<label className={cn("text-muted-foreground", param.modified && "text-amber-400")}>{label}</label>
|
||||
{param.control === "number" ? (
|
||||
<input
|
||||
type="number"
|
||||
className="w-20 rounded border bg-transparent px-1 text-right font-mono"
|
||||
value={value}
|
||||
min={param.min ?? undefined}
|
||||
max={param.max ?? undefined}
|
||||
step={param.step ?? (param.kind === "int" ? 1 : "any")}
|
||||
onChange={(event) => {
|
||||
const next = event.target.valueAsNumber;
|
||||
if (Number.isFinite(next)) forwardParam(param.id, next);
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<span className="font-mono">{value}</span>
|
||||
)}
|
||||
{param.unit && <span className="ml-1 text-muted-foreground">{param.unit}</span>}
|
||||
</div>
|
||||
{param.control === "slider" && param.min !== null && param.max !== null && (
|
||||
<Slider
|
||||
value={[value]}
|
||||
min={param.min}
|
||||
max={param.max}
|
||||
step={param.step ?? (param.kind === "int" ? 1 : (param.max - param.min) / 200)}
|
||||
onValueChange={([next]) => forwardParam(param.id, next)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import { useState } from "react";
|
||||
import { Download, ExternalLink, Plus, RefreshCw } from "lucide-react";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
/** Top bar: workspace identity, runtime state, and global actions. */
|
||||
export function Header({
|
||||
notebook,
|
||||
kind,
|
||||
kernelAlive,
|
||||
status,
|
||||
onExport,
|
||||
onRerun,
|
||||
onNewNotebook,
|
||||
marimoUrl,
|
||||
}: {
|
||||
notebook: string | null;
|
||||
kind: string | null;
|
||||
kernelAlive: boolean;
|
||||
status: string;
|
||||
onExport: () => void;
|
||||
onRerun: () => void;
|
||||
onNewNotebook: (name: string, kind: "part" | "assembly") => void;
|
||||
marimoUrl: string | null;
|
||||
}) {
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [name, setName] = useState("");
|
||||
const [kindChoice, setKindChoice] = useState<"part" | "assembly">("part");
|
||||
|
||||
const submit = async () => {
|
||||
if (!name.trim()) return;
|
||||
onNewNotebook(name.trim(), kindChoice);
|
||||
setName("");
|
||||
setCreating(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<header className="flex h-12 shrink-0 items-center gap-3 border-b bg-card px-3">
|
||||
<span className="text-sm font-semibold tracking-tight">SimpleCAD Studio</span>
|
||||
{notebook && (
|
||||
<span className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<span className="font-mono text-foreground">{notebook}</span>
|
||||
{kind && kind !== "helper" && <Badge variant={kind === "entry" ? "default" : "secondary"}>{kind}</Badge>}
|
||||
</span>
|
||||
)}
|
||||
<span className={`ml-1 inline-block h-2 w-2 rounded-full ${kernelAlive ? "bg-primary" : "bg-destructive"}`} />
|
||||
<span className="min-w-0 flex-1 truncate text-xs text-muted-foreground" title={status}>
|
||||
{status}
|
||||
</span>
|
||||
{creating ? (
|
||||
<span className="flex items-center gap-1.5">
|
||||
<input
|
||||
autoFocus
|
||||
value={name}
|
||||
placeholder="name"
|
||||
className="h-7 w-32 rounded-md border bg-background px-2 font-mono text-xs"
|
||||
onChange={(event) => setName(event.target.value)}
|
||||
onKeyDown={(event) => event.key === "Enter" && void submit()}
|
||||
/>
|
||||
<select
|
||||
value={kindChoice}
|
||||
className="h-7 rounded-md border bg-background px-1 text-xs"
|
||||
onChange={(event) => setKindChoice(event.target.value as "part" | "assembly")}
|
||||
>
|
||||
<option value="part">part</option>
|
||||
<option value="assembly">assembly</option>
|
||||
</select>
|
||||
<Button size="sm" onClick={() => void submit()}>
|
||||
create
|
||||
</Button>
|
||||
<Button size="sm" variant="ghost" onClick={() => setCreating(false)}>
|
||||
cancel
|
||||
</Button>
|
||||
</span>
|
||||
) : (
|
||||
<Button size="sm" variant="outline" onClick={() => setCreating(true)}>
|
||||
<Plus /> new
|
||||
</Button>
|
||||
)}
|
||||
<Button size="sm" variant="outline" onClick={onRerun} title="Re-run the entry cell">
|
||||
<RefreshCw /> rerun
|
||||
</Button>
|
||||
<Button size="sm" onClick={onExport} title="Persist <entry>.scadpkg next to the entry script">
|
||||
<Download /> export
|
||||
</Button>
|
||||
{marimoUrl && (
|
||||
<Button size="sm" variant="ghost" asChild>
|
||||
<a href={marimoUrl} target="_blank" rel="noreferrer" title="Open the raw marimo editor">
|
||||
<ExternalLink /> marimo
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import type { PickResult } from "@/scene/Viewport";
|
||||
|
||||
export type FederatedNode = { id: string; label: string; kind: string };
|
||||
|
||||
/** Right-hand inspector: current selection, feature DAG, package meta. */
|
||||
export function Inspector({
|
||||
pick,
|
||||
features,
|
||||
packageInfo,
|
||||
}: {
|
||||
pick: PickResult | null;
|
||||
features: FederatedNode[];
|
||||
packageInfo: { name: string | null; revision: number; occurrences: number; assets: number; exported: string | null } | null;
|
||||
}) {
|
||||
return (
|
||||
<Tabs defaultValue="selection" className="h-full">
|
||||
<TabsList className="mx-2 mt-2">
|
||||
<TabsTrigger value="selection">selection</TabsTrigger>
|
||||
<TabsTrigger value="features">features</TabsTrigger>
|
||||
<TabsTrigger value="package">package</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="selection" className="h-[calc(100%-3rem)]">
|
||||
<ScrollArea className="h-full px-3">
|
||||
{pick ? (
|
||||
<div className="space-y-2 text-xs">
|
||||
<dl className="space-y-1.5">
|
||||
<Row label="mode" value={pick.mode} />
|
||||
<Row label="node" value={pick.nodeId} mono />
|
||||
<Row label="entity" value={pick.entityId ?? "—"} mono />
|
||||
{pick.entity?.kind && <Row label="entity kind" value={String(pick.entity.kind)} />}
|
||||
</dl>
|
||||
<Separator className="my-2" />
|
||||
{pick.entity?.properties && (
|
||||
<Section title="properties" body={pretty(pick.entity.properties)} />
|
||||
)}
|
||||
{pick.entity?.geometry && (
|
||||
<Section title="geometry" body={pretty(pick.entity.geometry)} />
|
||||
)}
|
||||
<p className="pt-1 text-[10px] uppercase tracking-wide text-muted-foreground">
|
||||
Agents read this via GET /api/studio/selected
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">Click a solid, face, or edge in the viewport.</p>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
<TabsContent value="features" className="h-[calc(100%-3rem)]">
|
||||
<ScrollArea className="h-full px-3">
|
||||
<ul className="space-y-1 text-xs">
|
||||
{features.map((feature) => (
|
||||
<li key={feature.id} className="flex items-center gap-2">
|
||||
<span className="font-mono text-muted-foreground">{feature.kind}</span>
|
||||
<span>{feature.label}</span>
|
||||
</li>
|
||||
))}
|
||||
{features.length === 0 && (
|
||||
<li className="text-xs text-muted-foreground">No features yet — run the notebook.</li>
|
||||
)}
|
||||
</ul>
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
<TabsContent value="package" className="h-[calc(100%-3rem)]">
|
||||
<ScrollArea className="h-full px-3">
|
||||
{packageInfo ? (
|
||||
<dl className="space-y-1.5 text-xs">
|
||||
<Row label="entry" value={packageInfo.name ?? "—"} mono />
|
||||
<Row label="revision" value={`#${packageInfo.revision}`} mono />
|
||||
<Row label="occurrences" value={String(packageInfo.occurrences)} />
|
||||
<Row label="geometry assets" value={String(packageInfo.assets)} />
|
||||
<Row label="exported to" value={packageInfo.exported ?? "not exported"} mono />
|
||||
</dl>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">No package received yet.</p>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
);
|
||||
}
|
||||
|
||||
function Row({ label, value, mono }: { label: string; value: string; mono?: boolean }) {
|
||||
return (
|
||||
<div className="flex items-baseline justify-between gap-2">
|
||||
<dt className="shrink-0 text-muted-foreground">{label}</dt>
|
||||
<dd className={mono ? "truncate font-mono" : "truncate"} title={value}>
|
||||
{value}
|
||||
</dd>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** Compact JSON for inspector readouts (objects only; scalars inlined). */
|
||||
function pretty(value: Record<string, unknown>): string {
|
||||
try {
|
||||
return JSON.stringify(value, (_key, item) => (typeof item === "number" ? Number(item.toFixed(3)) : item), 1);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
}
|
||||
|
||||
function Section({ title, body }: { title: string; body: string }) {
|
||||
return (
|
||||
<div>
|
||||
<p className="mb-0.5 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">{title}</p>
|
||||
<pre className="max-h-48 overflow-auto rounded bg-background/60 p-1.5 font-mono text-[10px] leading-relaxed text-foreground/85">
|
||||
{body}
|
||||
</pre>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { NotebookRow } from "@/lib/api";
|
||||
|
||||
/** Workspace notebook list. Entries are executable models; helpers are
|
||||
* listed for orientation but opening one is refused by the server. */
|
||||
export function NotebookList({
|
||||
notebooks,
|
||||
onOpen,
|
||||
}: {
|
||||
notebooks: NotebookRow[];
|
||||
onOpen: (path: string) => void;
|
||||
}) {
|
||||
if (notebooks.length === 0) {
|
||||
return <p className="p-3 text-xs text-muted-foreground">No notebooks in this workspace.</p>;
|
||||
}
|
||||
return (
|
||||
<ScrollArea className="h-full">
|
||||
<ul className="p-1.5">
|
||||
{notebooks.map((row) => (
|
||||
<li key={row.path}>
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-left text-xs hover:bg-accent",
|
||||
row.current && "bg-accent",
|
||||
)}
|
||||
onClick={() => !row.current && onOpen(row.path)}
|
||||
title={row.path}
|
||||
>
|
||||
<span className="font-mono">{row.name}</span>
|
||||
{row.entry ? (
|
||||
<Badge variant="default">{row.kind}</Badge>
|
||||
) : (
|
||||
<Badge variant="outline" className="text-muted-foreground">
|
||||
helper
|
||||
</Badge>
|
||||
)}
|
||||
{row.current && <span className="ml-auto text-[10px] uppercase text-primary">open</span>}
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</ScrollArea>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import * as React from "react";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const badgeVariants = cva(
|
||||
"inline-flex items-center rounded-md border px-1.5 py-0.5 text-[10px] font-semibold uppercase tracking-wide transition-colors",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "border-transparent bg-primary text-primary-foreground",
|
||||
secondary: "border-transparent bg-secondary text-secondary-foreground",
|
||||
outline: "text-foreground",
|
||||
destructive: "border-transparent bg-destructive text-destructive-foreground",
|
||||
},
|
||||
},
|
||||
defaultVariants: { variant: "default" },
|
||||
},
|
||||
);
|
||||
|
||||
function Badge({
|
||||
className,
|
||||
variant,
|
||||
...props
|
||||
}: React.ComponentProps<"span"> & VariantProps<typeof badgeVariants>) {
|
||||
return <span className={cn(badgeVariants({ variant }), className)} {...props} />;
|
||||
}
|
||||
|
||||
export { Badge, badgeVariants };
|
||||
@@ -0,0 +1,41 @@
|
||||
import * as React from "react";
|
||||
import { Slot } from "@radix-ui/react-slot";
|
||||
import { cva, type VariantProps } from "class-variance-authority";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
const buttonVariants = cva(
|
||||
"inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:size-4 [&_svg]:shrink-0",
|
||||
{
|
||||
variants: {
|
||||
variant: {
|
||||
default: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
|
||||
destructive: "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
|
||||
outline: "border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",
|
||||
secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
default: "h-8 px-3 py-1.5",
|
||||
sm: "h-7 rounded-md px-2.5 text-xs",
|
||||
lg: "h-9 rounded-md px-4",
|
||||
icon: "h-8 w-8",
|
||||
},
|
||||
},
|
||||
defaultVariants: { variant: "default", size: "default" },
|
||||
},
|
||||
);
|
||||
|
||||
function Button({
|
||||
className,
|
||||
variant,
|
||||
size,
|
||||
asChild = false,
|
||||
...props
|
||||
}: React.ComponentProps<"button"> & VariantProps<typeof buttonVariants> & { asChild?: boolean }) {
|
||||
const Comp = asChild ? Slot : "button";
|
||||
return <Comp className={cn(buttonVariants({ variant, size, className }))} {...props} />;
|
||||
}
|
||||
|
||||
export { Button, buttonVariants };
|
||||
@@ -0,0 +1,31 @@
|
||||
import * as React from "react";
|
||||
import { Group, Panel, Separator } from "react-resizable-panels";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** Horizontal split container: <ResizablePanelGroup><ResizablePanel/>… */
|
||||
function ResizablePanelGroup({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Group>) {
|
||||
return <Group orientation="horizontal" className={cn("flex h-full w-full", className)} {...props} />;
|
||||
}
|
||||
|
||||
const ResizablePanel = Panel;
|
||||
|
||||
function ResizableHandle({
|
||||
className,
|
||||
...props
|
||||
}: React.ComponentProps<typeof Separator>) {
|
||||
return (
|
||||
<Separator
|
||||
className={cn(
|
||||
"relative w-[3px] shrink-0 bg-border transition-colors hover:bg-primary/50",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { ResizablePanelGroup, ResizablePanel, ResizableHandle };
|
||||
@@ -0,0 +1,33 @@
|
||||
import * as React from "react";
|
||||
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function ScrollArea({ className, children, ...props }: React.ComponentProps<typeof ScrollAreaPrimitive.Root>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.Root className={cn("relative overflow-hidden", className)} {...props}>
|
||||
{/* Radix sets `display: table` inline on the viewport, which lets wide
|
||||
children (code editors) stretch the panel. Force block + full width
|
||||
so inner scrollers own the overflow instead. */}
|
||||
<ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit] [&>div]:!block">
|
||||
{children}
|
||||
</ScrollAreaPrimitive.Viewport>
|
||||
<ScrollBar />
|
||||
<ScrollAreaPrimitive.Corner />
|
||||
</ScrollAreaPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
function ScrollBar({ className, ...props }: React.ComponentProps<typeof ScrollAreaPrimitive.ScrollAreaScrollbar>) {
|
||||
return (
|
||||
<ScrollAreaPrimitive.ScrollAreaScrollbar
|
||||
orientation="vertical"
|
||||
className={cn("flex touch-none select-none transition-colors w-2 border-l border-l-transparent p-[1px]", className)}
|
||||
{...props}
|
||||
>
|
||||
<ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
|
||||
</ScrollAreaPrimitive.ScrollAreaScrollbar>
|
||||
);
|
||||
}
|
||||
|
||||
export { ScrollArea, ScrollBar };
|
||||
@@ -0,0 +1,26 @@
|
||||
import * as React from "react";
|
||||
import * as SeparatorPrimitive from "@radix-ui/react-separator";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function Separator({
|
||||
className,
|
||||
orientation = "horizontal",
|
||||
decorative = true,
|
||||
...props
|
||||
}: React.ComponentProps<typeof SeparatorPrimitive.Root>) {
|
||||
return (
|
||||
<SeparatorPrimitive.Root
|
||||
decorative={decorative}
|
||||
orientation={orientation}
|
||||
className={cn(
|
||||
"shrink-0 bg-border",
|
||||
orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export { Separator };
|
||||
@@ -0,0 +1,21 @@
|
||||
import * as React from "react";
|
||||
import * as SliderPrimitive from "@radix-ui/react-slider";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
/** Dual-thumb-capable range control; the studio uses single-thumb mode. */
|
||||
function Slider({ className, ...props }: React.ComponentProps<typeof SliderPrimitive.Root>) {
|
||||
return (
|
||||
<SliderPrimitive.Root
|
||||
className={cn("relative flex w-full touch-none select-none items-center", className)}
|
||||
{...props}
|
||||
>
|
||||
<SliderPrimitive.Track className="relative h-1 w-full grow overflow-hidden rounded-full bg-muted">
|
||||
<SliderPrimitive.Range className="absolute h-full bg-primary" />
|
||||
</SliderPrimitive.Track>
|
||||
<SliderPrimitive.Thumb className="block h-3.5 w-3.5 rounded-full border border-primary bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50" />
|
||||
</SliderPrimitive.Root>
|
||||
);
|
||||
}
|
||||
|
||||
export { Slider };
|
||||
@@ -0,0 +1,35 @@
|
||||
import * as React from "react";
|
||||
import * as TabsPrimitive from "@radix-ui/react-tabs";
|
||||
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
function Tabs({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Root>) {
|
||||
return <TabsPrimitive.Root className={cn("flex flex-col", className)} {...props} />;
|
||||
}
|
||||
|
||||
function TabsList({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.List>) {
|
||||
return (
|
||||
<TabsPrimitive.List
|
||||
className={cn("inline-flex h-8 items-center justify-start gap-1 rounded-md bg-muted p-1 text-muted-foreground", className)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TabsTrigger({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Trigger>) {
|
||||
return (
|
||||
<TabsPrimitive.Trigger
|
||||
className={cn(
|
||||
"inline-flex items-center justify-center gap-1.5 whitespace-nowrap rounded-sm px-2.5 py-1 text-xs font-medium transition-all focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",
|
||||
className,
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function TabsContent({ className, ...props }: React.ComponentProps<typeof TabsPrimitive.Content>) {
|
||||
return <TabsPrimitive.Content className={cn("mt-2 flex-1 outline-none", className)} {...props} />;
|
||||
}
|
||||
|
||||
export { Tabs, TabsList, TabsTrigger, TabsContent };
|
||||
@@ -0,0 +1,82 @@
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
|
||||
@custom-variant dark (&:is(.dark *));
|
||||
|
||||
/* Studio is dark-first: the :root block IS the dark theme. */
|
||||
:root {
|
||||
--radius: 0.5rem;
|
||||
--background: oklch(0.16 0.014 260);
|
||||
--foreground: oklch(0.93 0.006 260);
|
||||
--card: oklch(0.2 0.016 260);
|
||||
--card-foreground: oklch(0.93 0.006 260);
|
||||
--popover: oklch(0.2 0.016 260);
|
||||
--popover-foreground: oklch(0.93 0.006 260);
|
||||
--primary: oklch(0.85 0.18 130);
|
||||
--primary-foreground: oklch(0.18 0.03 130);
|
||||
--secondary: oklch(0.26 0.02 260);
|
||||
--secondary-foreground: oklch(0.93 0.006 260);
|
||||
--muted: oklch(0.26 0.02 260);
|
||||
--muted-foreground: oklch(0.68 0.015 260);
|
||||
--accent: oklch(0.3 0.03 260);
|
||||
--accent-foreground: oklch(0.95 0.005 260);
|
||||
--destructive: oklch(0.62 0.2 25);
|
||||
--destructive-foreground: oklch(0.97 0.01 25);
|
||||
--border: oklch(0.3 0.02 260);
|
||||
--input: oklch(0.3 0.02 260);
|
||||
--ring: oklch(0.85 0.18 130);
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--color-card: var(--card);
|
||||
--color-card-foreground: var(--card-foreground);
|
||||
--color-popover: var(--popover);
|
||||
--color-popover-foreground: var(--popover-foreground);
|
||||
--color-primary: var(--primary);
|
||||
--color-primary-foreground: var(--primary-foreground);
|
||||
--color-secondary: var(--secondary);
|
||||
--color-secondary-foreground: var(--secondary-foreground);
|
||||
--color-muted: var(--muted);
|
||||
--color-muted-foreground: var(--muted-foreground);
|
||||
--color-accent: var(--accent);
|
||||
--color-accent-foreground: var(--accent-foreground);
|
||||
--color-destructive: var(--destructive);
|
||||
--color-destructive-foreground: var(--destructive-foreground);
|
||||
--color-border: var(--border);
|
||||
--color-input: var(--input);
|
||||
--color-ring: var(--ring);
|
||||
--radius-sm: calc(var(--radius) - 4px);
|
||||
--radius-md: calc(var(--radius) - 2px);
|
||||
--radius-lg: var(--radius);
|
||||
--radius-xl: calc(var(--radius) + 4px);
|
||||
}
|
||||
|
||||
@layer base {
|
||||
* {
|
||||
@apply border-border outline-ring/50;
|
||||
}
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif;
|
||||
}
|
||||
/* Code hosts and CAD readouts get the mono face. */
|
||||
.font-mono,
|
||||
code,
|
||||
pre {
|
||||
font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace;
|
||||
}
|
||||
/* Notebook cells: the editor fills its card and adapts to the resizable
|
||||
* panel; long lines scroll inside instead of stretching the card. */
|
||||
.cm-editor {
|
||||
width: 100%;
|
||||
}
|
||||
.cm-editor .cm-scroller {
|
||||
overflow-x: auto;
|
||||
overflow-y: hidden;
|
||||
}
|
||||
.cm-editor.cm-focused {
|
||||
outline: none;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
/** REST surface of the runtime server (`sca edit <workspace>`).
|
||||
*
|
||||
* The WebSocket (`lib/envelope.ts`) carries live model events; these calls
|
||||
* cover discovery, control, and the agent-facing selection contract.
|
||||
*/
|
||||
|
||||
export type NotebookRow = {
|
||||
name: string;
|
||||
path: string;
|
||||
entry: boolean;
|
||||
kind: "part" | "assembly" | "helper";
|
||||
current: boolean;
|
||||
/** Definition id from the notebook header. */
|
||||
id?: string;
|
||||
/** Notebooks this one runs with use(...), workspace-relative. */
|
||||
uses?: string[];
|
||||
error?: string | null;
|
||||
};
|
||||
|
||||
export type SelectedInfo = {
|
||||
selected: Record<string, unknown>;
|
||||
notebook: string | null;
|
||||
};
|
||||
|
||||
async function json<T>(response: Response): Promise<T> {
|
||||
if (!response.ok) {
|
||||
const body = await response.text().catch(() => "");
|
||||
throw new Error(`${response.status} ${response.statusText}: ${body.slice(0, 200)}`);
|
||||
}
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
/** Notebooks in the workspace with entry/helper classification. */
|
||||
export function getWorkspace(): Promise<{ notebooks: NotebookRow[] }> {
|
||||
return fetch("/api/workspace").then((response) => json<{ notebooks: NotebookRow[] }>(response));
|
||||
}
|
||||
|
||||
/** Switch the active entry notebook (server restarts the kernel). */
|
||||
export function openNotebook(path: string): Promise<{ ok: boolean }> {
|
||||
return fetch("/api/workspace/open", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ path }),
|
||||
}).then((response) => json<{ ok: boolean }>(response));
|
||||
}
|
||||
|
||||
/** Provision a new entry notebook from the server template and open it. */
|
||||
export function newNotebook(name: string, kind: "part" | "assembly"): Promise<{ created: string }> {
|
||||
return fetch("/api/workspace/new", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name, kind }),
|
||||
}).then((response) => json<{ created: string }>(response));
|
||||
}
|
||||
|
||||
/** Latest in-memory scadpkg bytes (rule 4: never a disk read). */
|
||||
export async function fetchPackage(): Promise<Uint8Array> {
|
||||
const response = await fetch("/api/package/latest");
|
||||
if (!response.ok) throw new Error("no package published yet");
|
||||
return new Uint8Array(await response.arrayBuffer());
|
||||
}
|
||||
|
||||
/** Publish the viewport selection so agents can read it. */
|
||||
export function select(selection: Record<string, unknown>): Promise<{ ok: boolean }> {
|
||||
return fetch("/api/studio/select", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(selection),
|
||||
}).then((response) => json<{ ok: boolean }>(response));
|
||||
}
|
||||
|
||||
/** Agent-facing read: what the human has selected right now. */
|
||||
export function getSelected(): Promise<SelectedInfo> {
|
||||
return fetch("/api/studio/selected").then((response) => json<SelectedInfo>(response));
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/** Live event socket: server-pushed model envelopes over /ws.
|
||||
*
|
||||
* Envelope types (workspace_server.replay order): params.schema,
|
||||
* params.values, geometry, tree, notebook.cells, notebook.features,
|
||||
* package, selection, status, hello.
|
||||
*/
|
||||
|
||||
export type Envelope = Record<string, unknown> & { type: string };
|
||||
type Handler = (envelope: Envelope) => void;
|
||||
|
||||
export class EnvelopeSocket {
|
||||
private ws: WebSocket | null = null;
|
||||
private handlers = new Map<string, Set<Handler>>();
|
||||
private backoffMs = 500;
|
||||
private closed = false;
|
||||
|
||||
constructor(private readonly url: string) {}
|
||||
|
||||
on(type: string, handler: Handler): () => void {
|
||||
let set = this.handlers.get(type);
|
||||
if (!set) {
|
||||
set = new Set();
|
||||
this.handlers.set(type, set);
|
||||
}
|
||||
set.add(handler);
|
||||
return () => set!.delete(handler);
|
||||
}
|
||||
|
||||
connect(): void {
|
||||
this.closed = false;
|
||||
const ws = new WebSocket(this.url);
|
||||
this.ws = ws;
|
||||
ws.onopen = () => {
|
||||
this.backoffMs = 500;
|
||||
};
|
||||
ws.onmessage = (event) => {
|
||||
let envelope: Envelope;
|
||||
try {
|
||||
envelope = JSON.parse(String(event.data));
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
const set = this.handlers.get(envelope.type);
|
||||
if (set) for (const handler of set) handler(envelope);
|
||||
const anySet = this.handlers.get("*");
|
||||
if (anySet) for (const handler of anySet) handler(envelope);
|
||||
};
|
||||
ws.onclose = () => {
|
||||
if (this.closed) return;
|
||||
// Kernel/server restarts must transparently re-attach the UI.
|
||||
setTimeout(() => this.connect(), this.backoffMs);
|
||||
this.backoffMs = Math.min(this.backoffMs * 2, 8000);
|
||||
};
|
||||
}
|
||||
|
||||
/** Send one ui command (param.set / export.request / code.edit / rerun.request). */
|
||||
send(message: Record<string, unknown>): void {
|
||||
if (this.ws?.readyState === WebSocket.OPEN) {
|
||||
this.ws.send(JSON.stringify(message));
|
||||
}
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closed = true;
|
||||
this.ws?.close();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { clsx, type ClassValue } from "clsx";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
/** shadcn/ui class combiner. */
|
||||
export function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
|
||||
import { App } from "./App";
|
||||
import "./index.css";
|
||||
|
||||
createRoot(document.getElementById("root")!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,86 @@
|
||||
import { useEffect, useRef } from "react";
|
||||
import * as THREE from "three";
|
||||
|
||||
import { SceneView, type PickResult, type SelectionMode } from "@/scene/scene-view";
|
||||
|
||||
export type { PickResult, SelectionMode };
|
||||
|
||||
const SELECTION_COLOR = "#4ade80";
|
||||
|
||||
// Module-load marker: distinguishes "stale bundle served" from "effect not
|
||||
// running" when debugging the imperative scene handle from the console.
|
||||
if (typeof window !== "undefined") {
|
||||
(window as unknown as { __studioViewportLoaded?: boolean }).__studioViewportLoaded = true;
|
||||
document.documentElement.dataset.viewportLoaded = "1";
|
||||
}
|
||||
|
||||
/** Mounts the three.js SceneView once; owns the selection highlight and
|
||||
* bridges picks to React.
|
||||
*
|
||||
* The parent owns the SceneView instance (imperative scene loading does not
|
||||
* map to React state); this component guarantees mount/dispose, draws the
|
||||
* entity highlight for the current pick, and forwards picks after publishing
|
||||
* them to the agent-facing selection API.
|
||||
*/
|
||||
export function Viewport({
|
||||
viewRef,
|
||||
selectionMode,
|
||||
onPick,
|
||||
}: {
|
||||
viewRef: React.MutableRefObject<SceneView | null>;
|
||||
selectionMode: SelectionMode;
|
||||
onPick: (pick: PickResult) => void;
|
||||
}) {
|
||||
const hostRef = useRef<HTMLDivElement>(null);
|
||||
const pickRef = useRef(onPick);
|
||||
pickRef.current = onPick;
|
||||
// The highlight overlays attach themselves into the scene graph; keep the
|
||||
// handles so the previous highlight can be removed on the next pick.
|
||||
const overlayRef = useRef<THREE.Object3D[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
const host = hostRef.current;
|
||||
if (!host) return;
|
||||
const view = new SceneView(host, {
|
||||
onPick: (result) => {
|
||||
// Swap the highlight: dispose the previous overlays, build fresh ones.
|
||||
for (const object of overlayRef.current) {
|
||||
object.parent?.remove(object);
|
||||
object.traverse((child) => {
|
||||
const mesh = child as THREE.Mesh;
|
||||
mesh.geometry?.dispose?.();
|
||||
const material = mesh.material as THREE.Material | THREE.Material[] | undefined;
|
||||
if (Array.isArray(material)) material.forEach((item) => item.dispose());
|
||||
else material?.dispose?.();
|
||||
});
|
||||
}
|
||||
overlayRef.current = result.entityId
|
||||
? view.buildEntityOverlays(result.nodeId, result.entityId, SELECTION_COLOR, 0.8)
|
||||
: [];
|
||||
// Main-world telemetry mirror: debug probes may run in an isolated
|
||||
// JS world, so expose pick/overlay state through the DOM instead.
|
||||
document.documentElement.dataset.pickedEntity = result.entityId ?? "";
|
||||
document.documentElement.dataset.overlayCount = String(overlayRef.current.length);
|
||||
pickRef.current(result);
|
||||
},
|
||||
selectionMode: "solid",
|
||||
});
|
||||
viewRef.current = view;
|
||||
// Debug/agent affordance: reach the imperative scene from the console.
|
||||
(window as unknown as { __studioView?: SceneView }).__studioView = view;
|
||||
// The renderer self-observes host resizes; nothing to wire here.
|
||||
return () => {
|
||||
for (const object of overlayRef.current) object.parent?.remove(object);
|
||||
overlayRef.current = [];
|
||||
view.dispose();
|
||||
viewRef.current = null;
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
viewRef.current?.setSelectionMode(selectionMode);
|
||||
}, [selectionMode, viewRef]);
|
||||
|
||||
return <div ref={hostRef} className="h-full w-full" />;
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// Shared CAD<->glTF three.js helpers, extracted from main.ts so the package
|
||||
// viewer and the reverse-engineering mode load scenes through one code path.
|
||||
|
||||
import * as THREE from 'three';
|
||||
import { LineMaterial } from 'three/addons/lines/LineMaterial.js';
|
||||
import { LineSegments2 } from 'three/addons/lines/LineSegments2.js';
|
||||
import { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js';
|
||||
import type { SceneNode, Transform, Vec3 } from './scene2';
|
||||
|
||||
export const CAD_TO_GLTF = new THREE.Matrix4().set(0.001, 0, 0, 0, 0, 0, 0.001, 0, 0, -0.001, 0, 0, 0, 0, 0, 1);
|
||||
export const GLTF_TO_CAD = new THREE.Matrix4().set(1000, 0, 0, 0, 0, 0, -1000, 0, 0, 1000, 0, 0, 0, 0, 0, 1);
|
||||
|
||||
export function placementMatrix(transform: Transform): THREE.Matrix4 {
|
||||
const { origin, x_axis, y_axis, z_axis } = transform;
|
||||
const cad = new THREE.Matrix4().set(
|
||||
x_axis[0], y_axis[0], z_axis[0], origin[0],
|
||||
x_axis[1], y_axis[1], z_axis[1], origin[1],
|
||||
x_axis[2], y_axis[2], z_axis[2], origin[2],
|
||||
0, 0, 0, 1,
|
||||
);
|
||||
return CAD_TO_GLTF.clone().multiply(cad).multiply(GLTF_TO_CAD);
|
||||
}
|
||||
|
||||
export function cadPointToGltf(point: Vec3): THREE.Vector3 {
|
||||
return new THREE.Vector3(point[0] / 1000, point[2] / 1000, -point[1] / 1000);
|
||||
}
|
||||
|
||||
export const CAD_EDGE_LINE_WIDTH = 2.4;
|
||||
/** Explicit dark edge color — must read as a firm outline on the lit body
|
||||
* while staying distinguishable from the pure-black viewport background. */
|
||||
export const CAD_EDGE_COLOR = '#3a414d';
|
||||
export const DEFAULT_BASE_COLOR: [number, number, number, 1] = [0.72, 0.75, 0.78, 1];
|
||||
|
||||
export type Resolution = { width: number; height: number };
|
||||
|
||||
export function materialFor(node: SceneNode): THREE.MeshStandardMaterial {
|
||||
const color = node.material_id ? [0.68, 0.78, 0.88, 1] as const : DEFAULT_BASE_COLOR;
|
||||
// Faces are pushed back in depth: edge lines lie exactly ON the surface, and
|
||||
// without the offset the face triangles win the depth fight per-pixel —
|
||||
// edges render as broken dashed fragments (classic CAD z-fighting).
|
||||
return new THREE.MeshStandardMaterial({ color: new THREE.Color(color[0], color[1], color[2]), metalness: 0.08, roughness: 0.52, side: THREE.FrontSide, transparent: color[3] < 1, opacity: color[3], polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 1 });
|
||||
}
|
||||
|
||||
export function edgeMaterial(resolution: Resolution): LineMaterial {
|
||||
// Negative slope-scaled polygon offset: at silhouettes the line runs along
|
||||
// a surface seen edge-on and parts of its quad sit genuinely behind the
|
||||
// local surface depth — a constant bias loses there, a slope-scaled pull
|
||||
// (mirror of the faces' +1 push) wins at every viewing angle.
|
||||
const material = new LineMaterial({ color: CAD_EDGE_COLOR, linewidth: CAD_EDGE_LINE_WIDTH, worldUnits: false, depthTest: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2 });
|
||||
material.resolution.set(Math.max(resolution.width, 1), Math.max(resolution.height, 1));
|
||||
return material;
|
||||
}
|
||||
|
||||
export function addWideEdgeVisual(source: THREE.LineSegments, resolution: Resolution): void {
|
||||
const position = source.geometry.getAttribute('position');
|
||||
const index = source.geometry.index;
|
||||
const indexCount = index?.count ?? position.count;
|
||||
const positions: number[] = [];
|
||||
for (let offset = 0; offset + 1 < indexCount; offset += 2) {
|
||||
const a = index ? index.getX(offset) : offset;
|
||||
const b = index ? index.getX(offset + 1) : offset + 1;
|
||||
positions.push(position.getX(a), position.getY(a), position.getZ(a), position.getX(b), position.getY(b), position.getZ(b));
|
||||
}
|
||||
const geometry = new LineSegmentsGeometry();
|
||||
geometry.setPositions(positions);
|
||||
const visual = new LineSegments2(geometry, edgeMaterial(resolution));
|
||||
visual.name = 'cad-edge-visual';
|
||||
visual.userData.pickable = false;
|
||||
source.add(visual);
|
||||
const pickingMaterial = new THREE.LineBasicMaterial();
|
||||
pickingMaterial.visible = false;
|
||||
source.material = pickingMaterial;
|
||||
}
|
||||
|
||||
export function disposeObject(root: THREE.Object3D): void {
|
||||
const disposedGeometries = new Set<THREE.BufferGeometry>();
|
||||
const disposedMaterials = new Set<THREE.Material>();
|
||||
root.traverse((object) => {
|
||||
if (object instanceof THREE.Mesh || object instanceof THREE.LineSegments || object instanceof THREE.Points) {
|
||||
if (!disposedGeometries.has(object.geometry)) {
|
||||
object.geometry.dispose();
|
||||
disposedGeometries.add(object.geometry);
|
||||
}
|
||||
const materials = Array.isArray(object.material) ? object.material : [object.material];
|
||||
materials.forEach((material) => {
|
||||
if (!disposedMaterials.has(material)) {
|
||||
material.dispose();
|
||||
disposedMaterials.add(material);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import * as THREE from 'three';
|
||||
|
||||
type ClickSelectionControls = {
|
||||
target: THREE.Vector3;
|
||||
update(): void;
|
||||
};
|
||||
|
||||
type ClickSelectionOptions = {
|
||||
element: HTMLElement;
|
||||
camera: THREE.PerspectiveCamera;
|
||||
controls: ClickSelectionControls;
|
||||
movementThreshold?: number;
|
||||
onPointerStateChange?: (active: boolean) => void;
|
||||
onClick: (event: PointerEvent) => void;
|
||||
};
|
||||
|
||||
export function bindClickSelection(options: ClickSelectionOptions): () => void {
|
||||
const { element, camera, controls, onClick, movementThreshold = 4 } = options;
|
||||
let pointerDown: {
|
||||
x: number;
|
||||
y: number;
|
||||
button: number;
|
||||
position: THREE.Vector3;
|
||||
up: THREE.Vector3;
|
||||
target: THREE.Vector3;
|
||||
zoom: number;
|
||||
} | null = null;
|
||||
|
||||
const onPointerDown = (event: PointerEvent): void => {
|
||||
pointerDown = {
|
||||
x: event.clientX,
|
||||
y: event.clientY,
|
||||
button: event.button,
|
||||
position: camera.position.clone(),
|
||||
up: camera.up.clone(),
|
||||
target: controls.target.clone(),
|
||||
zoom: camera.zoom,
|
||||
};
|
||||
options.onPointerStateChange?.(true);
|
||||
};
|
||||
const onPointerUp = (event: PointerEvent): void => {
|
||||
const down = pointerDown;
|
||||
pointerDown = null;
|
||||
options.onPointerStateChange?.(false);
|
||||
if (!down || down.button !== 0 || event.button !== 0) return;
|
||||
if (Math.hypot(event.clientX - down.x, event.clientY - down.y) > movementThreshold) return;
|
||||
|
||||
// The controls may have applied pointer movement between down and up
|
||||
// (turntable damping, trackball momentum). Drain it, then restore the
|
||||
// click-time camera — position and orientation — before picking.
|
||||
controls.update();
|
||||
camera.position.copy(down.position);
|
||||
camera.up.copy(down.up);
|
||||
camera.zoom = down.zoom;
|
||||
camera.updateProjectionMatrix();
|
||||
controls.target.copy(down.target);
|
||||
controls.update();
|
||||
onClick(event);
|
||||
};
|
||||
const onPointerLeave = (): void => {
|
||||
pointerDown = null;
|
||||
options.onPointerStateChange?.(false);
|
||||
};
|
||||
|
||||
element.addEventListener('pointerdown', onPointerDown);
|
||||
element.addEventListener('pointerup', onPointerUp);
|
||||
element.addEventListener('pointerleave', onPointerLeave);
|
||||
return () => {
|
||||
element.removeEventListener('pointerdown', onPointerDown);
|
||||
element.removeEventListener('pointerup', onPointerUp);
|
||||
element.removeEventListener('pointerleave', onPointerLeave);
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,474 @@
|
||||
import { strFromU8, unzipSync } from 'fflate';
|
||||
import type { SceneManifest } from './scene2';
|
||||
|
||||
export type PackageFiles = Record<string, Uint8Array>;
|
||||
|
||||
export type OpenedCadPackage = {
|
||||
files: PackageFiles;
|
||||
packageContentHash: string;
|
||||
schemaVersion: '3.0';
|
||||
};
|
||||
|
||||
type HashRecord = {
|
||||
uri?: string;
|
||||
path?: string;
|
||||
sha256: string;
|
||||
byte_length: number;
|
||||
};
|
||||
|
||||
// A record whose payload is one exact ZIP member (definition, occurrence
|
||||
// graph, member blob, scene projection manifest); v3 always addresses these
|
||||
// by an explicit path.
|
||||
type MemberRecord = {
|
||||
path: string;
|
||||
sha256: string;
|
||||
byte_length: number;
|
||||
};
|
||||
|
||||
// A scene asset record addressed by its scene URI.
|
||||
type AssetRecord = HashRecord & { uri: string };
|
||||
|
||||
type DefinitionKind = 'single_solid' | 'assembly';
|
||||
|
||||
type DefinitionRecord = MemberRecord & {
|
||||
definition_kind: DefinitionKind;
|
||||
definition_id: string;
|
||||
revision: string;
|
||||
content_hash: string;
|
||||
};
|
||||
|
||||
type PackageRoot = {
|
||||
path: string;
|
||||
definition_kind: DefinitionKind;
|
||||
definition_id: string;
|
||||
revision: string;
|
||||
content_hash: string;
|
||||
};
|
||||
|
||||
type MemberStorage = { kind: 'member'; path: string };
|
||||
|
||||
type ArchiveStorage = {
|
||||
kind: 'archive';
|
||||
manifest_name: string;
|
||||
members: { path: string; sha256: string }[];
|
||||
};
|
||||
|
||||
type BlobRecord = {
|
||||
sha256: string;
|
||||
byte_length: number;
|
||||
media_type: string;
|
||||
storage: MemberStorage | ArchiveStorage;
|
||||
};
|
||||
|
||||
type SceneAssetSource =
|
||||
| { kind: 'definition'; definition_id: string }
|
||||
| { kind: 'blob'; sha256: string };
|
||||
|
||||
type SceneProjection = {
|
||||
manifest: MemberRecord;
|
||||
scene_id: string;
|
||||
revision: string;
|
||||
assets: { uri: string; source: SceneAssetSource }[];
|
||||
};
|
||||
|
||||
type ProductManifest = {
|
||||
schema_version: string;
|
||||
artifact_kind: string;
|
||||
content_hash: string;
|
||||
root: PackageRoot;
|
||||
definitions: DefinitionRecord[];
|
||||
blobs: BlobRecord[];
|
||||
occurrence_graph: HashRecord;
|
||||
projections: { scene?: SceneProjection };
|
||||
};
|
||||
|
||||
|
||||
|
||||
const MAX_PACKAGE_BYTES = 256 * 1024 * 1024;
|
||||
const MAX_PACKAGE_MEMBERS = 10_000;
|
||||
const MAX_UNPACKED_BYTES = 512 * 1024 * 1024;
|
||||
const MAX_MEMBER_BYTES = 256 * 1024 * 1024;
|
||||
const MAX_MANIFEST_BYTES = 32 * 1024 * 1024;
|
||||
const MAX_COMPRESSION_RATIO = 100;
|
||||
|
||||
const MANIFEST_KEYS = ['artifact_kind', 'blobs', 'content_hash', 'definitions', 'occurrence_graph', 'projections', 'root', 'schema_version'];
|
||||
|
||||
const SHA256_PATTERN = /^sha256:[0-9a-f]{64}$/;
|
||||
|
||||
function validateMemberName(name: string): void {
|
||||
if (!/^[A-Za-z0-9][A-Za-z0-9._/-]{0,4095}$/.test(name)
|
||||
|| name.split('/').some((segment) => !segment || segment === '.' || segment === '..')) {
|
||||
throw new Error(`invalid package member: ${name}`);
|
||||
}
|
||||
}
|
||||
|
||||
function extractArchive(raw: Uint8Array, manifestNames: readonly string[]): PackageFiles {
|
||||
if (raw.byteLength > MAX_PACKAGE_BYTES) throw new Error('package exceeds browser size limit');
|
||||
let memberCount = 0;
|
||||
let unpackedBytes = 0;
|
||||
const seenNames = new Set<string>();
|
||||
unzipSync(raw, { filter: (entry) => {
|
||||
validateMemberName(entry.name);
|
||||
const foldedName = entry.name.toLowerCase();
|
||||
if (seenNames.has(foldedName)) throw new Error(`duplicate or case-colliding package member: ${entry.name}`);
|
||||
seenNames.add(foldedName);
|
||||
memberCount += 1;
|
||||
unpackedBytes += entry.originalSize;
|
||||
if (entry.compression !== 0 && entry.compression !== 8) throw new Error(`unsupported ZIP compression method: ${entry.name}`);
|
||||
if (memberCount > MAX_PACKAGE_MEMBERS) throw new Error('package member count exceeds browser limit');
|
||||
if (entry.originalSize > MAX_MEMBER_BYTES) throw new Error(`package member exceeds browser size limit: ${entry.name}`);
|
||||
if (manifestNames.includes(entry.name) && entry.originalSize > MAX_MANIFEST_BYTES) throw new Error(`${entry.name} is too large`);
|
||||
if (unpackedBytes > MAX_UNPACKED_BYTES) throw new Error('package expands beyond browser size limit');
|
||||
if (entry.originalSize > MAX_COMPRESSION_RATIO * Math.max(1, entry.size)) throw new Error(`package member compression ratio is too high: ${entry.name}`);
|
||||
return false;
|
||||
}});
|
||||
const presentManifests = manifestNames.filter((name) => seenNames.has(name.toLowerCase()));
|
||||
if (presentManifests.length !== 1) throw new Error('package must contain exactly one supported manifest');
|
||||
if (unpackedBytes > MAX_COMPRESSION_RATIO * raw.byteLength) throw new Error('package compression ratio is too high');
|
||||
const files = unzipSync(raw) as PackageFiles;
|
||||
const entries = Object.entries(files);
|
||||
if (entries.length !== memberCount) throw new Error('package member count changed during extraction');
|
||||
if (entries.reduce((sum, [, value]) => sum + value.byteLength, 0) !== unpackedBytes) {
|
||||
throw new Error('package decoded size differs from ZIP metadata');
|
||||
}
|
||||
return files;
|
||||
}
|
||||
|
||||
function parseManifest<T>(files: PackageFiles, name: string): T {
|
||||
const payload = files[name];
|
||||
if (!payload || payload.byteLength > MAX_MANIFEST_BYTES) throw new Error(`${name} is missing or too large`);
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(strFromU8(payload));
|
||||
} catch {
|
||||
throw new Error(`${name} is not valid JSON`);
|
||||
}
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Error(`${name} must contain an object`);
|
||||
return value as T;
|
||||
}
|
||||
|
||||
function recordPath(record: HashRecord): string {
|
||||
const path = record.uri ?? record.path;
|
||||
if (typeof path !== 'string') throw new Error('package record path is missing');
|
||||
validateMemberName(path);
|
||||
return path;
|
||||
}
|
||||
|
||||
function canonicalJson(value: unknown): string {
|
||||
if (value === null || typeof value === 'boolean' || typeof value === 'string') return JSON.stringify(value);
|
||||
if (typeof value === 'number') {
|
||||
if (!Number.isFinite(value)) throw new Error('manifest contains a non-finite number');
|
||||
if (Number.isInteger(value) && !Number.isSafeInteger(value)) throw new Error('manifest contains an unsafe integer');
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`;
|
||||
if (typeof value !== 'object') throw new Error('manifest contains a non-JSON value');
|
||||
const object = value as Record<string, unknown>;
|
||||
return `{${Object.keys(object).sort().map((key) => `${JSON.stringify(key)}:${canonicalJson(object[key])}`).join(',')}}`;
|
||||
}
|
||||
|
||||
async function sha256(payload: Uint8Array): Promise<string> {
|
||||
const view = payload.buffer.slice(payload.byteOffset, payload.byteOffset + payload.byteLength) as ArrayBuffer;
|
||||
const bytes = new Uint8Array(await crypto.subtle.digest('SHA-256', view));
|
||||
return `sha256:${Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')}`;
|
||||
}
|
||||
|
||||
async function canonicalHash(value: unknown): Promise<string> {
|
||||
return sha256(new TextEncoder().encode(canonicalJson(value)));
|
||||
}
|
||||
|
||||
async function validateRecords(files: PackageFiles, records: HashRecord[], manifestName: string): Promise<void> {
|
||||
const referenced = new Set<string>([manifestName]);
|
||||
for (const record of records) {
|
||||
const path = recordPath(record);
|
||||
if (referenced.has(path)) throw new Error(`duplicate package reference: ${path}`);
|
||||
referenced.add(path);
|
||||
const payload = files[path];
|
||||
if (!payload) throw new Error(`package member is missing: ${path}`);
|
||||
if (!Number.isSafeInteger(record.byte_length) || record.byte_length < 0 || payload.byteLength !== record.byte_length) {
|
||||
throw new Error(`package member length differs: ${path}`);
|
||||
}
|
||||
if (!SHA256_PATTERN.test(record.sha256) || await sha256(payload) !== record.sha256) {
|
||||
throw new Error(`package member hash differs: ${path}`);
|
||||
}
|
||||
}
|
||||
const names = Object.keys(files);
|
||||
if (names.length !== referenced.size || names.some((name) => !referenced.has(name))) {
|
||||
throw new Error(`${manifestName} references do not match package members`);
|
||||
}
|
||||
}
|
||||
|
||||
function requireObject(value: unknown, what: string): Record<string, unknown> {
|
||||
if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error(`${what} must contain an object`);
|
||||
return value as Record<string, unknown>;
|
||||
}
|
||||
|
||||
function requireRecordArray(value: unknown, what: string): Record<string, unknown>[] {
|
||||
if (!Array.isArray(value) || value.some((item) => typeof item !== 'object' || item === null || Array.isArray(item))) {
|
||||
throw new Error(`${what} must be an array of records`);
|
||||
}
|
||||
return value as Record<string, unknown>[];
|
||||
}
|
||||
|
||||
function requireString(holder: Record<string, unknown>, field: string, what: string): string {
|
||||
const value = holder[field];
|
||||
if (typeof value !== 'string') throw new Error(`${what} ${field} is missing`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function requireSha256(holder: Record<string, unknown>, field: string, what: string): string {
|
||||
const value = requireString(holder, field, what);
|
||||
if (!SHA256_PATTERN.test(value)) throw new Error(`${what} ${field} is not a sha256 digest`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function requireByteLength(holder: Record<string, unknown>, what: string): number {
|
||||
const value = holder.byte_length;
|
||||
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0) throw new Error(`${what} byte_length is invalid`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function requireMemberPath(holder: Record<string, unknown>, field: string, what: string): string {
|
||||
const value = requireString(holder, field, what);
|
||||
validateMemberName(value);
|
||||
return value;
|
||||
}
|
||||
|
||||
function requireDefinitionKind(holder: Record<string, unknown>, what: string): DefinitionKind {
|
||||
const value = holder.definition_kind;
|
||||
if (value !== 'single_solid' && value !== 'assembly') throw new Error(`${what} definition_kind is unsupported`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function requireAssetRecord(raw: Record<string, unknown>, what: string): AssetRecord {
|
||||
return {
|
||||
uri: requireMemberPath(raw, 'uri', what),
|
||||
sha256: requireSha256(raw, 'sha256', what),
|
||||
byte_length: requireByteLength(raw, what),
|
||||
};
|
||||
}
|
||||
|
||||
// Strictly ascending adjacent pairs prove sortedness and uniqueness in one
|
||||
// pass; member names and hex digests are pure ASCII, so JS string comparison
|
||||
// equals the byte-order sort of the canonical writer.
|
||||
function requireSortedUnique(values: string[], what: string): void {
|
||||
if (!values.every((value, index) => index === 0 || values[index - 1] < value)) throw new Error(what);
|
||||
}
|
||||
|
||||
type ParsedPackage = {
|
||||
definitionRecords: DefinitionRecord[];
|
||||
blobByHash: Map<string, BlobRecord>;
|
||||
occurrenceGraph: MemberRecord;
|
||||
sceneProjection: SceneProjection | null;
|
||||
contentHash: string;
|
||||
};
|
||||
|
||||
// Mirrors the structural invariants of product-package-3.schema.json and
|
||||
// ProductPackage._validate_manifest without a JSON-Schema engine.
|
||||
function parseProductManifest(manifest: Record<string, unknown>): ParsedPackage {
|
||||
const keys = Object.keys(manifest);
|
||||
if (keys.length !== MANIFEST_KEYS.length || MANIFEST_KEYS.some((key) => !(key in manifest))) {
|
||||
throw new Error(`product package manifest keys are not canonical: ${keys.sort().join(', ')}`);
|
||||
}
|
||||
|
||||
const definitionRecords = requireRecordArray(manifest.definitions, 'package definitions').map((raw) => ({
|
||||
path: requireMemberPath(raw, 'path', 'definition record'),
|
||||
sha256: requireSha256(raw, 'sha256', 'definition record'),
|
||||
byte_length: requireByteLength(raw, 'definition record'),
|
||||
definition_kind: requireDefinitionKind(raw, 'definition record'),
|
||||
definition_id: requireString(raw, 'definition_id', 'definition record'),
|
||||
revision: requireString(raw, 'revision', 'definition record'),
|
||||
content_hash: requireSha256(raw, 'content_hash', 'definition record'),
|
||||
})) as DefinitionRecord[];
|
||||
if (definitionRecords.length === 0) throw new Error('package definitions are empty');
|
||||
requireSortedUnique(definitionRecords.map((record) => record.path), 'definition records must be unique and path-sorted');
|
||||
const definitionIds = definitionRecords.map((record) => record.definition_id);
|
||||
if (new Set(definitionIds).size !== definitionIds.length) throw new Error('definition IDs must be unique');
|
||||
const definitionPathSet = new Set(definitionRecords.map((record) => record.path));
|
||||
|
||||
const rootRaw = requireObject(manifest.root, 'package root');
|
||||
if (!definitionPathSet.has(requireMemberPath(rootRaw, 'path', 'package root'))) throw new Error('package root does not resolve');
|
||||
|
||||
const blobRecords = requireRecordArray(manifest.blobs, 'package blobs').map((raw) => {
|
||||
const sha256 = requireSha256(raw, 'sha256', 'blob record');
|
||||
const storageRaw = requireObject(raw.storage, `blob ${sha256} storage`);
|
||||
let storage: MemberStorage | ArchiveStorage;
|
||||
if (storageRaw.kind === 'member') {
|
||||
storage = { kind: 'member', path: requireMemberPath(storageRaw, 'path', 'blob storage') };
|
||||
} else if (storageRaw.kind === 'archive') {
|
||||
storage = {
|
||||
kind: 'archive',
|
||||
manifest_name: requireString(storageRaw, 'manifest_name', 'blob storage'),
|
||||
members: requireRecordArray(storageRaw.members, 'archive blob members').map((member) => ({
|
||||
path: requireMemberPath(member, 'path', 'archive blob member'),
|
||||
sha256: requireSha256(member, 'sha256', 'archive blob member'),
|
||||
})),
|
||||
};
|
||||
} else {
|
||||
throw new Error(`blob ${sha256} storage kind is unsupported`);
|
||||
}
|
||||
return { sha256, byte_length: requireByteLength(raw, 'blob record'), media_type: requireString(raw, 'media_type', 'blob record'), storage };
|
||||
}) as BlobRecord[];
|
||||
requireSortedUnique(blobRecords.map((record) => record.sha256), 'blob records must be unique and hash-sorted');
|
||||
const blobByHash = new Map(blobRecords.map((record) => [record.sha256, record]));
|
||||
for (const record of blobRecords) {
|
||||
if (record.storage.kind === 'member') {
|
||||
if (definitionPathSet.has(record.storage.path)) throw new Error('blob member path collides with definition');
|
||||
} else {
|
||||
const memberPaths = record.storage.members.map((member) => member.path);
|
||||
if (new Set(memberPaths).size !== memberPaths.length) throw new Error(`archive blob members are duplicated: ${record.sha256}`);
|
||||
if (memberPaths.join('\u0000') !== [...memberPaths].sort().join('\u0000')) throw new Error('archive blob members must be path-sorted');
|
||||
for (const member of record.storage.members) {
|
||||
if (!blobByHash.has(member.sha256)) throw new Error(`archive blob member is not declared: ${member.path}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const occurrenceRaw = requireObject(manifest.occurrence_graph, 'occurrence graph record');
|
||||
const occurrenceGraph: MemberRecord = {
|
||||
path: requireMemberPath(occurrenceRaw, 'path', 'occurrence graph record'),
|
||||
sha256: requireSha256(occurrenceRaw, 'sha256', 'occurrence graph record'),
|
||||
byte_length: requireByteLength(occurrenceRaw, 'occurrence graph record'),
|
||||
};
|
||||
|
||||
const projectionsRaw = requireObject(manifest.projections, 'package projections');
|
||||
let sceneProjection: SceneProjection | null = null;
|
||||
if (projectionsRaw.scene !== undefined) {
|
||||
const raw = requireObject(projectionsRaw.scene, 'scene projection');
|
||||
const manifestRecord = requireObject(raw.manifest, 'scene projection manifest record');
|
||||
sceneProjection = {
|
||||
manifest: {
|
||||
path: requireMemberPath(manifestRecord, 'path', 'scene projection manifest'),
|
||||
sha256: requireSha256(manifestRecord, 'sha256', 'scene projection manifest'),
|
||||
byte_length: requireByteLength(manifestRecord, 'scene projection manifest'),
|
||||
}, scene_id: requireString(raw, 'scene_id', 'scene projection'),
|
||||
revision: requireString(raw, 'revision', 'scene projection'),
|
||||
assets: requireRecordArray(raw.assets, 'scene projection assets').map((asset) => {
|
||||
const uri = requireString(asset, 'uri', 'scene projection asset');
|
||||
const sourceRaw = requireObject(asset.source, `scene projection asset source: ${uri}`);
|
||||
if (sourceRaw.kind === 'definition') {
|
||||
return { uri, source: { kind: 'definition', definition_id: requireString(sourceRaw, 'definition_id', 'scene projection source') } };
|
||||
}
|
||||
if (sourceRaw.kind === 'blob') {
|
||||
return { uri, source: { kind: 'blob', sha256: requireSha256(sourceRaw, 'sha256', 'scene projection source') } };
|
||||
}
|
||||
throw new Error(`scene projection asset source kind is unsupported: ${uri}`);
|
||||
}),
|
||||
};
|
||||
const definitionIdSet = new Set(definitionIds);
|
||||
const seenUris = new Set<string>();
|
||||
for (const asset of sceneProjection.assets) {
|
||||
if (seenUris.has(asset.uri)) throw new Error(`scene projection asset URIs must be unique: ${asset.uri}`);
|
||||
seenUris.add(asset.uri);
|
||||
if (asset.source.kind === 'definition' && !definitionIdSet.has(asset.source.definition_id)) {
|
||||
throw new Error(`scene projection definition does not resolve: ${asset.uri}`);
|
||||
}
|
||||
if (asset.source.kind === 'blob' && !blobByHash.has(asset.source.sha256)) {
|
||||
throw new Error(`scene projection blob does not resolve: ${asset.uri}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { definitionRecords, blobByHash, occurrenceGraph, sceneProjection, contentHash: requireSha256(manifest, 'content_hash', 'product package') };
|
||||
}
|
||||
|
||||
function parseSceneManifest(value: unknown, name: string): SceneManifest {
|
||||
const manifest = requireObject(value, name);
|
||||
if (requireString(manifest, 'schema_version', name) !== '2.0') throw new Error(`unsupported scene schema: ${String(manifest.schema_version)}`);
|
||||
if (requireString(manifest, 'units', name) !== 'mm') throw new Error(`${name} units are unsupported`);
|
||||
const revision = requireSha256(manifest, 'revision', name);
|
||||
for (const field of ['roots', 'definitions', 'geometry_assets', 'entity_assets', 'product_assets', 'feature_graph_assets', 'source_assets', 'nodes', 'connectors', 'joints', 'feature_index', 'source_index', 'connector_index', 'joint_index']) {
|
||||
if (!Array.isArray(manifest[field])) throw new Error(`${name} ${field} must be an array`);
|
||||
}
|
||||
requireObject(manifest.camera, `${name} camera`);
|
||||
requireObject(manifest.extensions, `${name} extensions`);
|
||||
const scene = manifest as unknown as SceneManifest;
|
||||
for (const asset of [...scene.geometry_assets, ...scene.entity_assets, ...scene.source_assets]) {
|
||||
if (typeof asset.uri !== 'string' || !SHA256_PATTERN.test(asset.sha256) || !Number.isSafeInteger(asset.byte_length)) {
|
||||
throw new Error(`${name} contains an invalid asset record`);
|
||||
}
|
||||
}
|
||||
if (!SHA256_PATTERN.test(revision)) throw new Error(`${name} revision is invalid`);
|
||||
return scene;
|
||||
}
|
||||
|
||||
export async function openCadPackage(raw: Uint8Array): Promise<OpenedCadPackage> {
|
||||
const files = extractArchive(raw, ['package.json']);
|
||||
const manifest = parseManifest<ProductManifest>(files, 'package.json');
|
||||
if (manifest.schema_version !== '3.0' || manifest.artifact_kind !== 'product_package') throw new Error('unsupported product package schema');
|
||||
const parsed = parseProductManifest(manifest as unknown as Record<string, unknown>);
|
||||
const draft = { ...(manifest as unknown as Record<string, unknown>) };
|
||||
delete draft.content_hash;
|
||||
if (parsed.contentHash !== await canonicalHash(draft)) throw new Error('product package content_hash is invalid');
|
||||
|
||||
// Member closure: every record above maps 1:1 onto a ZIP member and the
|
||||
// archive may hold nothing else. Archive-kind blobs contribute no direct
|
||||
// member; their inner payloads appear separately as member-kind blobs.
|
||||
const memberBlobs = [...parsed.blobByHash.values()]
|
||||
.filter((record) => record.storage.kind === 'member')
|
||||
.map((record) => ({ path: (record.storage as MemberStorage).path, sha256: record.sha256, byte_length: record.byte_length }));
|
||||
await validateRecords(files, [
|
||||
...parsed.definitionRecords,
|
||||
parsed.occurrenceGraph,
|
||||
...memberBlobs,
|
||||
...(parsed.sceneProjection ? [parsed.sceneProjection.manifest] : []),
|
||||
], 'package.json');
|
||||
|
||||
// The occurrence graph and the product/feature-graph ZIP payloads are never
|
||||
// consumed by the viewer, so they are integrity-checked as members above but
|
||||
// neither re-derived from definitions nor re-packed into canonical archives.
|
||||
if (!parsed.sceneProjection) throw new Error('product package does not embed a scene projection');
|
||||
const projection = parsed.sceneProjection;
|
||||
const sceneValue = parseManifest(files, projection.manifest.path);
|
||||
const scene = parseSceneManifest(sceneValue, 'scene manifest');
|
||||
const sceneDraft = { ...(sceneValue as Record<string, unknown>) };
|
||||
delete sceneDraft.revision;
|
||||
if (scene.revision !== await canonicalHash(sceneDraft)) throw new Error('scene revision is invalid');
|
||||
if (scene.scene_id !== projection.scene_id || scene.revision !== projection.revision) {
|
||||
throw new Error('embedded scene identity differs from package projection');
|
||||
}
|
||||
|
||||
const sourceByUri = new Map(projection.assets.map((asset) => [asset.uri, asset.source]));
|
||||
const outFiles: PackageFiles = { 'scene.json': files[projection.manifest.path] };
|
||||
const materialize = (records: HashRecord[], collection: string): void => {
|
||||
for (const record of records) {
|
||||
const uri = recordPath(record);
|
||||
const source = sourceByUri.get(uri);
|
||||
if (!source) throw new Error(`scene ${collection} asset is not covered by the package projection: ${uri}`);
|
||||
if (source.kind !== 'blob') throw new Error(`scene ${collection} asset must resolve to a package blob: ${uri}`);
|
||||
const blob = parsed.blobByHash.get(source.sha256);
|
||||
if (!blob || blob.storage.kind !== 'member') throw new Error(`scene ${collection} asset resolves to an archive blob: ${uri}`);
|
||||
if (record.sha256 !== blob.sha256 || record.byte_length !== blob.byte_length) {
|
||||
throw new Error(`scene ${collection} asset identity differs from package blob: ${uri}`);
|
||||
}
|
||||
outFiles[uri] = files[blob.storage.path];
|
||||
}
|
||||
};
|
||||
materialize(scene.geometry_assets, 'geometry');
|
||||
materialize(scene.entity_assets, 'entity');
|
||||
materialize(scene.source_assets, 'source');
|
||||
|
||||
for (const record of scene.product_assets) {
|
||||
const uri = recordPath(record);
|
||||
const source = sourceByUri.get(uri);
|
||||
if (!source) throw new Error(`scene product asset is not covered by the package projection: ${uri}`);
|
||||
if (source.kind !== 'definition') throw new Error(`scene product asset must resolve to a package definition: ${uri}`);
|
||||
}
|
||||
for (const record of scene.feature_graph_assets) {
|
||||
const uri = recordPath(record);
|
||||
const source = sourceByUri.get(uri);
|
||||
if (!source) throw new Error(`scene feature graph asset is not covered by the package projection: ${uri}`);
|
||||
if (source.kind !== 'blob') throw new Error(`scene feature graph asset must resolve to a package blob: ${uri}`);
|
||||
}
|
||||
|
||||
const identity = (record: { definition_kind: string; definition_id: string; revision: string; content_hash: string }): string =>
|
||||
[record.definition_kind, record.definition_id, record.revision, record.content_hash].join('\u0000');
|
||||
const packageIdentities = parsed.definitionRecords.map(identity).sort();
|
||||
const sceneIdentities = scene.product_assets.map(identity).sort();
|
||||
if (packageIdentities.length !== sceneIdentities.length
|
||||
|| packageIdentities.some((item, index) => item !== sceneIdentities[index])) {
|
||||
throw new Error('product package definitions differ from embedded scene product assets');
|
||||
}
|
||||
|
||||
return { files: outFiles, packageContentHash: parsed.contentHash, schemaVersion: '3.0' };
|
||||
}
|
||||
@@ -0,0 +1,718 @@
|
||||
// Standalone BRep scene renderer component.
|
||||
//
|
||||
// Owns everything visual about rendering a scene-2.0 package (GLB faces +
|
||||
// line edges + entity sidecars): materials, lighting (studio environment +
|
||||
// key light), postprocessing (GTAO ambient occlusion), camera (free
|
||||
// trackball), edge display (seam/degenerate edges split into their own
|
||||
// toggleable visuals), fit/snapshot and lifecycle. It has no notion of
|
||||
// selection or annotation — embed it directly, or compose it under a
|
||||
// higher-level view (see src/scene-view.ts for the picking/marks layer).
|
||||
//
|
||||
// import { BRepRenderer } from './renderer';
|
||||
// const viewer = new BRepRenderer(hostElement);
|
||||
// await viewer.loadScene(files); // scene-2.0 files (see product-package)
|
||||
// viewer.setSeamsVisible(false); // default
|
||||
// viewer.setSSAO(true); // default
|
||||
|
||||
import * as THREE from 'three';
|
||||
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
|
||||
import { TrackballControls } from 'three/addons/controls/TrackballControls.js';
|
||||
import { GTAOPass } from 'three/addons/postprocessing/GTAOPass.js';
|
||||
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
|
||||
import { LineMaterial } from 'three/addons/lines/LineMaterial.js';
|
||||
import { LineSegments2 } from 'three/addons/lines/LineSegments2.js';
|
||||
import { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js';
|
||||
import { strFromU8 } from 'fflate';
|
||||
import { DEFAULT_BASE_COLOR, CAD_EDGE_COLOR, CAD_EDGE_LINE_WIDTH, cadPointToGltf, disposeObject, materialFor, placementMatrix } from '../cad-three';
|
||||
import type { PackageFiles } from '../product-package';
|
||||
import type { Entity, EntitySidecar, FaceGroup, SceneManifest, SceneNode, Vec3 } from '../scene2';
|
||||
|
||||
/** Render layers: faces (0, default) go through lighting + AO; edges (1) and
|
||||
* annotation overlays (2) composite AFTER the AO pass so their color is
|
||||
* constant — no GI darkening — while still depth-testing against faces. */
|
||||
export const FACE_LAYER = 0;
|
||||
export const EDGE_LAYER = 1;
|
||||
export const OVERLAY_LAYER = 2;
|
||||
|
||||
export type CameraState = {
|
||||
position: Vec3;
|
||||
target: Vec3;
|
||||
up: Vec3;
|
||||
fov_deg: number;
|
||||
width: number;
|
||||
height: number;
|
||||
};
|
||||
|
||||
export type BRepRendererOptions = {
|
||||
background?: string;
|
||||
/** GTAO ambient occlusion pass (default on). */
|
||||
ssao?: boolean;
|
||||
/** Show seam/degenerate edges (default off — pro viewers hide them). */
|
||||
seams?: boolean;
|
||||
};
|
||||
|
||||
type Resolution = { width: number; height: number };
|
||||
|
||||
/** Direct geometry channel payload (no .scadpkg container): the authoring
|
||||
* runtime tessellates the live solid and ships the render mesh as-is. */
|
||||
export type LiveGeometryPayload = {
|
||||
schema: 'sca-live-geometry-1';
|
||||
step: string;
|
||||
/** Triangle vertices in CAD space (mm, +Z up). */
|
||||
positions: number[][];
|
||||
normals: number[][];
|
||||
indices: number[];
|
||||
/** Flat segment endpoints in CAD space (x1,y1,z1,x2,y2,z2, ...). */
|
||||
edge_positions: number[];
|
||||
face_groups: { entity_id: string; first: number; count: number }[];
|
||||
stats: { volume: number; faces: number };
|
||||
};
|
||||
|
||||
function isHiddenEdge(entity: Entity | undefined): boolean {
|
||||
const props = entity?.properties as { seam?: unknown; degenerate?: unknown } | undefined;
|
||||
return props?.seam === true || props?.degenerate === true;
|
||||
}
|
||||
|
||||
export class BRepRenderer {
|
||||
readonly host: HTMLElement;
|
||||
readonly threeScene: THREE.Scene;
|
||||
readonly camera: THREE.PerspectiveCamera;
|
||||
readonly renderer: THREE.WebGLRenderer;
|
||||
readonly controls: TrackballControls;
|
||||
readonly modelRoot = new THREE.Group();
|
||||
|
||||
manifest: SceneManifest | null = null;
|
||||
files: PackageFiles | null = null;
|
||||
nodeVisibility = new Map<string, boolean>();
|
||||
|
||||
private loader = new GLTFLoader();
|
||||
private geometryCache = new Map<string, THREE.Object3D>();
|
||||
private edgeCache = new Map<string, THREE.Object3D>();
|
||||
private entityCache = new Map<string, EntitySidecar>();
|
||||
private nodeObjects = new Map<string, THREE.Group>();
|
||||
private faceRT: THREE.WebGLRenderTarget | null = null;
|
||||
private beautyRT: THREE.WebGLRenderTarget | null = null;
|
||||
private ssaoPass: GTAOPass | null = null;
|
||||
private ssaoEnabled: boolean;
|
||||
private rendererClearColor: THREE.Color;
|
||||
private blitScene: THREE.Scene | null = null;
|
||||
private blitCamera: THREE.OrthographicCamera | null = null;
|
||||
private copyMaterial: THREE.MeshBasicMaterial | null = null;
|
||||
private presentMaterial: THREE.MeshBasicMaterial | null = null;
|
||||
private edgesVisible = true;
|
||||
private seamsVisible: boolean;
|
||||
private observer: ResizeObserver;
|
||||
private pendingFrame = true;
|
||||
private disposed = false;
|
||||
|
||||
constructor(host: HTMLElement, options: BRepRendererOptions = {}) {
|
||||
this.host = host;
|
||||
this.ssaoEnabled = options.ssao ?? true;
|
||||
this.seamsVisible = options.seams ?? false;
|
||||
this.threeScene = new THREE.Scene();
|
||||
this.camera = new THREE.PerspectiveCamera(42, 1, 0.01, 1000);
|
||||
this.camera.up.set(0, 0, 1);
|
||||
this.camera.position.set(2.4, 2.1, 3.0);
|
||||
this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
|
||||
// Background comes from the renderer clear color, NOT scene.background:
|
||||
// a Color scene.background force-clears the framebuffer on EVERY
|
||||
// renderer.render() (even autoClear=false), which would wipe the
|
||||
// face/color buffer when the edge pass draws on top of it. The clear
|
||||
// color is consumed raw as linear working-space values, so convert the
|
||||
// sRGB design color first — otherwise the presented background is ~4x
|
||||
// brighter than intended.
|
||||
this.rendererClearColor = new THREE.Color(options.background ?? '#0b0e12').convertSRGBToLinear();
|
||||
this.renderer.setClearColor(this.rendererClearColor, 1);
|
||||
this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
|
||||
this.renderer.outputColorSpace = THREE.SRGBColorSpace;
|
||||
this.renderer.toneMapping = THREE.ACESFilmicToneMapping;
|
||||
this.renderer.toneMappingExposure = 1.1;
|
||||
host.append(this.renderer.domElement);
|
||||
// resize() calls setSize(w, h, updateStyle=false), so the backing store is
|
||||
// host-size × pixelRatio while the CSS display size stays unset — a host
|
||||
// that does not style the canvas itself then renders the HiDPI buffer at
|
||||
// attribute size and crops it. Pin the display size to the host.
|
||||
this.renderer.domElement.style.width = '100%';
|
||||
this.renderer.domElement.style.height = '100%';
|
||||
this.renderer.domElement.style.display = 'block';
|
||||
// Trackball rotation: no fixed orbit axis, so the model can be rolled
|
||||
// past any pole — a turntable (OrbitControls) caps vertical sweep below
|
||||
// 180° no matter how the polar angle is clamped.
|
||||
this.controls = new TrackballControls(this.camera, this.renderer.domElement);
|
||||
this.controls.rotateSpeed = 1.0;
|
||||
this.controls.zoomSpeed = 1.0;
|
||||
this.controls.dynamicDampingFactor = 0.35;
|
||||
this.controls.minDistance = 0.01;
|
||||
this.controls.maxDistance = 1000;
|
||||
// Host pages may own the keyboard (text inputs); TrackballControls'
|
||||
// window-level A/S/D drag modifiers must not react to typing. The tuple
|
||||
// type is fixed, so park unreachable key codes instead of leaving A/S/D live.
|
||||
this.controls.keys = ['__unused_rotate', '__unused_zoom', '__unused_pan'];
|
||||
// Shift+left-drag pans. TrackballControls has no modifier support, but its
|
||||
// `keyState` field (the keyboard A/S/D path) deliberately outranks the
|
||||
// mouse-button gesture, so borrowing it reuses the controls' own pan
|
||||
// seeding, damping and release. onPointerUp only resets `state`, so the
|
||||
// keyState clear is on us. Capture on the host precedes the controls'
|
||||
// listeners on the canvas.
|
||||
host.addEventListener(
|
||||
'pointerdown',
|
||||
(event) => {
|
||||
if (!event.shiftKey || event.button !== 0 || this.controls.enabled === false) return;
|
||||
// `keyState` drives the controls' real keyboard-pan path but is not
|
||||
// in the shipped typings; the runtime field is the documented state
|
||||
// machine (PAN=2, NONE=-1).
|
||||
const controls = this.controls as TrackballControls & { keyState: number };
|
||||
controls.keyState = 2; // TrackballControls._STATE.PAN
|
||||
const release = (): void => {
|
||||
controls.keyState = -1; // TrackballControls._STATE.NONE
|
||||
window.removeEventListener('pointerup', release);
|
||||
window.removeEventListener('pointercancel', release);
|
||||
};
|
||||
window.addEventListener('pointerup', release);
|
||||
window.addEventListener('pointercancel', release);
|
||||
},
|
||||
true,
|
||||
);
|
||||
this.modelRoot.name = 'scene-root';
|
||||
this.threeScene.add(this.modelRoot);
|
||||
this.setupLighting();
|
||||
this.setupPostprocessing();
|
||||
this.observer = new ResizeObserver(() => this.resize());
|
||||
this.observer.observe(host);
|
||||
this.resize();
|
||||
this.renderer.setAnimationLoop(() => this.render());
|
||||
}
|
||||
|
||||
private loopRunning = true;
|
||||
|
||||
/** Demand-render flag: the loop always ticks (damping needs it) but the
|
||||
* expensive SSAO pipeline only runs when something actually changed. */
|
||||
private needsRender = true;
|
||||
|
||||
/** Schedule one repaint (scene loads, picks, selection, external edits). */
|
||||
invalidate(): void {
|
||||
this.needsRender = true;
|
||||
}
|
||||
|
||||
/** Pause/resume the render loop. Inactive panels must not burn GPU —
|
||||
* several editor modes stay mounted, each with its own WebGL context. */
|
||||
setRunning(running: boolean): void {
|
||||
if (running === this.loopRunning) return;
|
||||
this.loopRunning = running;
|
||||
if (running) {
|
||||
this.renderer.setAnimationLoop(() => this.render());
|
||||
} else {
|
||||
this.renderer.setAnimationLoop(null);
|
||||
}
|
||||
}
|
||||
|
||||
isRunning(): boolean {
|
||||
return this.loopRunning;
|
||||
}
|
||||
|
||||
private setupLighting(): void {
|
||||
// Image-based studio lighting instead of hand-placed fill lights; one
|
||||
// directional key stays for crisp specular definition on flats.
|
||||
const pmrem = new THREE.PMREMGenerator(this.renderer);
|
||||
this.threeScene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
|
||||
this.threeScene.environmentIntensity = 0.7;
|
||||
pmrem.dispose();
|
||||
const keyLight = new THREE.DirectionalLight('#fff8e9', 1.4);
|
||||
keyLight.position.set(4, 7, 5);
|
||||
this.threeScene.add(keyLight, keyLight.target);
|
||||
}
|
||||
|
||||
private setupPostprocessing(): void {
|
||||
// Manual pipeline instead of EffectComposer, so edges can composite AFTER
|
||||
// the AO blend:
|
||||
// 1. faces (layer 0) render into faceRT — this carries the face depth
|
||||
// 2. GTAO blends beauty*ao into beautyRT; a copy brings it back onto
|
||||
// faceRT, keeping faceRT's depth attachment intact
|
||||
// 3. edges (layer 1) + overlays (layer 2) render into faceRT with plain
|
||||
// depth testing — after AO, hence constant color, correctly occluded
|
||||
// 4. faceRT presents to screen through tone mapping
|
||||
const size = this.resolution();
|
||||
const pixelRatio = this.renderer.getPixelRatio();
|
||||
const width = Math.max(size.width * pixelRatio, 1);
|
||||
const height = Math.max(size.height * pixelRatio, 1);
|
||||
const options: THREE.RenderTargetOptions = { type: THREE.HalfFloatType, samples: 4 };
|
||||
this.faceRT = new THREE.WebGLRenderTarget(width, height, options);
|
||||
this.beautyRT = new THREE.WebGLRenderTarget(width, height, options);
|
||||
if (this.ssaoEnabled) {
|
||||
const ssaoPass = new GTAOPass(this.threeScene, this.camera, width, height);
|
||||
ssaoPass.output = GTAOPass.OUTPUT.Default;
|
||||
ssaoPass.blendIntensity = 0.65;
|
||||
this.tuneSSAO(ssaoPass, 0.01);
|
||||
this.ssaoPass = ssaoPass;
|
||||
}
|
||||
this.blitScene = new THREE.Scene();
|
||||
this.blitCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
|
||||
this.copyMaterial = new THREE.MeshBasicMaterial({ map: this.beautyRT.texture, toneMapped: false, depthTest: false, depthWrite: false });
|
||||
this.presentMaterial = new THREE.MeshBasicMaterial({ map: this.faceRT.texture, toneMapped: true, depthTest: false, depthWrite: false });
|
||||
const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2), this.copyMaterial);
|
||||
quad.frustumCulled = false;
|
||||
this.blitScene.add(quad);
|
||||
}
|
||||
|
||||
/** Draws one material over the whole current render target. */
|
||||
private blit(material: THREE.Material): void {
|
||||
const quad = this.blitScene!.children[0] as THREE.Mesh;
|
||||
quad.material = material;
|
||||
this.renderer.render(this.blitScene!, this.blitCamera!);
|
||||
}
|
||||
|
||||
/** GTAO works in world units — retune the radius to the model's scale. */
|
||||
private tuneSSAO(pass: GTAOPass, modelRadius: number): void {
|
||||
pass.updateGtaoMaterial({
|
||||
radius: Math.max(modelRadius * 0.14, 0.002),
|
||||
distanceExponent: 1.0,
|
||||
thickness: 1.0,
|
||||
scale: 1.0,
|
||||
samples: 16,
|
||||
distanceFallOff: 1.0,
|
||||
screenSpaceRadius: false,
|
||||
});
|
||||
}
|
||||
|
||||
private lastCameraPos = new THREE.Vector3();
|
||||
private lastCameraQuat = new THREE.Quaternion();
|
||||
|
||||
/** True when the camera pose changed since the previous call. */
|
||||
private cameraMoved(): boolean {
|
||||
const changed =
|
||||
!this.camera.position.equals(this.lastCameraPos) ||
|
||||
!this.camera.quaternion.equals(this.lastCameraQuat);
|
||||
this.lastCameraPos.copy(this.camera.position);
|
||||
this.lastCameraQuat.copy(this.camera.quaternion);
|
||||
return changed;
|
||||
}
|
||||
|
||||
private render(): void {
|
||||
if (!this.faceRT || !this.blitScene) return;
|
||||
this.controls.update();
|
||||
// Camera pose change (damping, user input) or an explicit invalidation
|
||||
// triggers the expensive SSAO chain; an idle scene skips it entirely.
|
||||
if (!this.cameraMoved() && !this.needsRender) return;
|
||||
this.needsRender = false;
|
||||
const previousTarget = this.renderer.getRenderTarget();
|
||||
const previousAutoClear = this.renderer.autoClear;
|
||||
|
||||
// 1. faces + background (layer 0) — carries the face depth buffer
|
||||
this.camera.layers.set(FACE_LAYER);
|
||||
this.renderer.setRenderTarget(this.faceRT);
|
||||
this.renderer.clear();
|
||||
this.renderer.render(this.threeScene, this.camera);
|
||||
|
||||
// 2. ambient occlusion on faces only
|
||||
if (this.ssaoPass && this.ssaoEnabled && this.beautyRT) {
|
||||
this.ssaoPass.render(this.renderer, this.beautyRT, this.faceRT, 0, false);
|
||||
// 2b. bring the AO'ed color back onto faceRT; its depth survives because
|
||||
// the copy quad does not write depth
|
||||
this.renderer.setRenderTarget(this.faceRT);
|
||||
this.renderer.autoClear = false;
|
||||
this.copyMaterial!.map = this.beautyRT.texture;
|
||||
this.blit(this.copyMaterial!);
|
||||
}
|
||||
|
||||
// 3. edges + annotation overlays, composited after AO with plain depth
|
||||
// testing against the face depth — constant color, correctly occluded
|
||||
this.camera.layers.set(EDGE_LAYER);
|
||||
this.camera.layers.enable(OVERLAY_LAYER);
|
||||
this.renderer.setRenderTarget(this.faceRT);
|
||||
this.renderer.render(this.threeScene, this.camera);
|
||||
this.camera.layers.set(FACE_LAYER);
|
||||
|
||||
// 4. present through tone mapping
|
||||
this.renderer.setRenderTarget(previousTarget);
|
||||
this.renderer.autoClear = previousAutoClear;
|
||||
this.blit(this.presentMaterial!);
|
||||
}
|
||||
|
||||
// -- scene loading -------------------------------------------------------
|
||||
|
||||
private bytesFor(uri: string): Uint8Array {
|
||||
const value = this.files?.[uri];
|
||||
if (!value) throw new Error(`scene file is missing: ${uri}`);
|
||||
return value;
|
||||
}
|
||||
|
||||
private async loadGlb(uri: string): Promise<THREE.Object3D> {
|
||||
const bytes = this.bytesFor(uri);
|
||||
const buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) as ArrayBuffer;
|
||||
const gltf = await this.loader.parseAsync(buffer, '');
|
||||
return gltf.scene;
|
||||
}
|
||||
|
||||
private resolution(): Resolution {
|
||||
return { width: this.renderer.domElement.clientWidth, height: this.renderer.domElement.clientHeight };
|
||||
}
|
||||
|
||||
sidecarFor(node: SceneNode | undefined): EntitySidecar | null {
|
||||
if (!this.manifest || !this.files || !node?.entity_asset_id) return null;
|
||||
const asset = this.manifest.entity_assets.find((item) => item.asset_id === node.entity_asset_id);
|
||||
if (!asset) return null;
|
||||
const cached = this.entityCache.get(asset.asset_id);
|
||||
if (cached) return cached;
|
||||
const parsed = JSON.parse(strFromU8(this.bytesFor(asset.uri))) as EntitySidecar;
|
||||
if ((parsed.schema_version !== '1.0' && parsed.schema_version !== '2.0') || parsed.definition_id !== node.definition_id) throw new Error(`entity sidecar identity differs: ${asset.uri}`);
|
||||
this.entityCache.set(asset.asset_id, parsed);
|
||||
return parsed;
|
||||
}
|
||||
|
||||
async loadScene(files: PackageFiles): Promise<void> {
|
||||
this.needsRender = true;
|
||||
const hadScene = this.modelRoot.children.length > 0;
|
||||
const sceneBytes = files['scene.json'];
|
||||
if (!sceneBytes) throw new Error('scene.json is missing from the scene files');
|
||||
const manifest = JSON.parse(strFromU8(sceneBytes)) as SceneManifest;
|
||||
if (manifest.schema_version !== '2.0' && manifest.schema_version !== 're-mode-source-1') throw new Error(`unsupported scene schema: ${manifest.schema_version}`);
|
||||
this.clearScene();
|
||||
this.files = files;
|
||||
this.manifest = manifest;
|
||||
const nodesByParent = new Map<string | null, SceneNode[]>();
|
||||
for (const node of manifest.nodes) nodesByParent.set(node.parent_node_id, [...(nodesByParent.get(node.parent_node_id) ?? []), node]);
|
||||
const build = async (parent: THREE.Object3D, parentId: string | null): Promise<void> => {
|
||||
for (const node of nodesByParent.get(parentId) ?? []) {
|
||||
const object = new THREE.Group();
|
||||
object.name = node.node_id;
|
||||
object.matrixAutoUpdate = false;
|
||||
object.matrix.copy(placementMatrix(node.transform));
|
||||
object.visible = this.nodeVisibility.get(node.node_id) ?? true;
|
||||
object.userData.nodeId = node.node_id;
|
||||
object.userData.definitionId = node.definition_id;
|
||||
this.nodeObjects.set(node.node_id, object);
|
||||
parent.add(object);
|
||||
if (node.node_kind === 'part' || node.node_kind === 'solid') {
|
||||
const instance = await this.instantiateNode(node);
|
||||
instance.traverse((child: THREE.Object3D) => { child.userData.nodeId = node.node_id; child.userData.definitionId = node.definition_id; });
|
||||
object.add(instance);
|
||||
}
|
||||
await build(object, node.node_id);
|
||||
}
|
||||
};
|
||||
await build(this.modelRoot, null);
|
||||
this.setVertexCloudsVisible(false);
|
||||
// Re-frame only on the FIRST load; watched reloads (Studio live view,
|
||||
// agent artifact iterations) must keep the user's camera pose and zoom.
|
||||
if (!hadScene) this.pendingFrame = true;
|
||||
this.resize();
|
||||
}
|
||||
|
||||
/** Live view fast path: build the scene straight from a tessellated render
|
||||
* mesh, skipping the .scadpkg container (zip, hash verification, BREP and
|
||||
* feature-graph payloads entirely). Camera pose is preserved on reloads. */
|
||||
loadLiveGeometry(payload: LiveGeometryPayload): void {
|
||||
const hadScene = this.modelRoot.children.length > 0;
|
||||
this.clearScene();
|
||||
this.files = {};
|
||||
this.manifest = null;
|
||||
const group = new THREE.Group();
|
||||
group.name = 'live-geometry';
|
||||
const geometry = new THREE.BufferGeometry();
|
||||
geometry.setAttribute('position', new THREE.Float32BufferAttribute(payload.positions.flat(), 3));
|
||||
geometry.setAttribute('normal', new THREE.Float32BufferAttribute(payload.normals.flat(), 3));
|
||||
geometry.setIndex(payload.indices);
|
||||
const [r, g, b] = DEFAULT_BASE_COLOR;
|
||||
const mesh = new THREE.Mesh(geometry, new THREE.MeshStandardMaterial({ color: new THREE.Color(r, g, b), metalness: 0.08, roughness: 0.52, side: THREE.FrontSide, polygonOffset: true, polygonOffsetFactor: 1, polygonOffsetUnits: 1 }));
|
||||
mesh.name = 'live-faces';
|
||||
mesh.layers.set(FACE_LAYER);
|
||||
group.add(mesh);
|
||||
group.add(this.edgeLineVisual(payload.edge_positions, 'live-edges'));
|
||||
this.modelRoot.add(group);
|
||||
if (!hadScene) this.pendingFrame = true;
|
||||
this.resize();
|
||||
}
|
||||
|
||||
private async instantiateNode(node: SceneNode): Promise<THREE.Group> {
|
||||
if (!this.manifest) throw new Error('scene is not loaded');
|
||||
const sidecar = this.sidecarFor(node);
|
||||
const group = new THREE.Group();
|
||||
group.name = node.display_name || node.node_id;
|
||||
const geometryAsset = node.geometry_asset_id ? this.manifest.geometry_assets.find((asset) => asset.asset_id === node.geometry_asset_id) : undefined;
|
||||
if (geometryAsset) {
|
||||
let geometry = this.geometryCache.get(geometryAsset.asset_id);
|
||||
if (!geometry) {
|
||||
geometry = await this.loadGlb(geometryAsset.uri);
|
||||
this.geometryCache.set(geometryAsset.asset_id, geometry);
|
||||
}
|
||||
const renderGeometry = geometry.clone(true);
|
||||
renderGeometry.traverse((child) => {
|
||||
if (child instanceof THREE.Mesh) child.material = materialFor(node);
|
||||
});
|
||||
group.add(renderGeometry);
|
||||
}
|
||||
const edgeAsset = sidecar ? this.manifest.geometry_assets.find((asset) => asset.asset_id === sidecar.edge_asset_id) : undefined;
|
||||
if (edgeAsset && sidecar) {
|
||||
let edge = this.edgeCache.get(edgeAsset.asset_id);
|
||||
if (!edge) {
|
||||
edge = await this.loadGlb(edgeAsset.uri);
|
||||
this.edgeCache.set(edgeAsset.asset_id, edge);
|
||||
}
|
||||
const edgeInstance = edge.clone(true);
|
||||
this.buildEdgeVisuals(edgeInstance, sidecar);
|
||||
group.add(edgeInstance);
|
||||
}
|
||||
if (sidecar) {
|
||||
const vertices = sidecar.entities.filter((entity) => entity.kind === 'vertex');
|
||||
if (vertices.length) {
|
||||
const positions = new Float32Array(vertices.length * 3);
|
||||
vertices.forEach((entity, index) => {
|
||||
const position = entity.properties.position;
|
||||
if (Array.isArray(position) && position.length === 3 && position.every((item) => typeof item === 'number')) cadPointToGltf(position as Vec3).toArray(positions, index * 3);
|
||||
});
|
||||
const vertexGeometry = new THREE.BufferGeometry();
|
||||
vertexGeometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
|
||||
const vertexPoints = new THREE.Points(vertexGeometry, new THREE.PointsMaterial({ color: '#d8ff83', size: 7, sizeAttenuation: false, depthWrite: false, transparent: true, opacity: 0.48 }));
|
||||
vertexPoints.visible = false;
|
||||
vertexPoints.userData.pickRole = 'vertex';
|
||||
vertexPoints.userData.pickable = true;
|
||||
vertexPoints.userData.vertexEntityIds = vertices.map((entity) => entity.entity_id);
|
||||
group.add(vertexPoints);
|
||||
}
|
||||
}
|
||||
return group;
|
||||
}
|
||||
|
||||
/** Split the edge asset into regular and seam/degenerate wide-line visuals. */
|
||||
private buildEdgeVisuals(edgeObject: THREE.Object3D, sidecar: EntitySidecar): void {
|
||||
const entitiesById = new Map(sidecar.entities.map((entity) => [entity.entity_id, entity]));
|
||||
edgeObject.traverse((child) => {
|
||||
if (!(child instanceof THREE.LineSegments)) return;
|
||||
const source = child as THREE.LineSegments;
|
||||
const index = source.geometry.index;
|
||||
const position = source.geometry.getAttribute('position');
|
||||
const indexCount = index?.count ?? position.count;
|
||||
const groups = [...sidecar.edge_groups].sort((a, b) => a.first_index - b.first_index);
|
||||
const regular: number[] = [];
|
||||
const seams: number[] = [];
|
||||
const pushRange = (target: number[], first: number, count: number): void => {
|
||||
for (let offset = first; offset + 1 < first + count; offset += 2) {
|
||||
const a = index ? index.getX(offset) : offset;
|
||||
const b = index ? index.getX(offset + 1) : offset + 1;
|
||||
target.push(position.getX(a), position.getY(a), position.getZ(a), position.getX(b), position.getY(b), position.getZ(b));
|
||||
}
|
||||
};
|
||||
let cursor = 0;
|
||||
for (const group of groups) {
|
||||
const start = Math.max(group.first_index, 0);
|
||||
if (start > cursor) pushRange(regular, cursor, start - cursor);
|
||||
const target = isHiddenEdge(entitiesById.get(group.entity_id)) ? seams : regular;
|
||||
pushRange(target, start, group.index_count);
|
||||
cursor = Math.max(cursor, start + group.index_count);
|
||||
}
|
||||
if (cursor < indexCount) pushRange(regular, cursor, indexCount - cursor);
|
||||
// the source keeps the original geometry for index-based picking only
|
||||
source.material = new THREE.LineBasicMaterial({ visible: false });
|
||||
if (regular.length) source.add(this.edgeLineVisual(regular, 'cad-edge-visual'));
|
||||
if (seams.length) {
|
||||
const seamVisual = this.edgeLineVisual(seams, 'cad-edge-seam');
|
||||
seamVisual.visible = this.seamsVisible && this.edgesVisible;
|
||||
source.add(seamVisual);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private edgeLineVisual(positions: number[], name: string): LineSegments2 {
|
||||
const geometry = new LineSegmentsGeometry();
|
||||
geometry.setPositions(positions);
|
||||
// Negative slope-scaled offset mirrors the faces' push (see materialFor):
|
||||
// keeps silhouette edges continuous where a flat bias loses.
|
||||
const material = new LineMaterial({ color: CAD_EDGE_COLOR, linewidth: CAD_EDGE_LINE_WIDTH, worldUnits: false, depthTest: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2 });
|
||||
const size = this.resolution();
|
||||
material.resolution.set(Math.max(size.width, 1), Math.max(size.height, 1));
|
||||
const visual = new LineSegments2(geometry, material);
|
||||
visual.name = name;
|
||||
visual.layers.set(EDGE_LAYER);
|
||||
visual.userData.pickable = false;
|
||||
return visual;
|
||||
}
|
||||
|
||||
clearScene(): void {
|
||||
for (const object of this.geometryCache.values()) disposeObject(object);
|
||||
for (const object of this.edgeCache.values()) disposeObject(object);
|
||||
while (this.modelRoot.children.length) {
|
||||
const child = this.modelRoot.children[0];
|
||||
disposeObject(child);
|
||||
this.modelRoot.remove(child);
|
||||
}
|
||||
this.nodeObjects.clear();
|
||||
this.nodeVisibility.clear();
|
||||
this.edgeCache.clear();
|
||||
this.entityCache.clear();
|
||||
this.geometryCache.clear();
|
||||
this.manifest = null;
|
||||
this.files = null;
|
||||
}
|
||||
|
||||
// -- display options -------------------------------------------------------
|
||||
|
||||
setEdgesVisible(visible: boolean): void {
|
||||
this.edgesVisible = visible;
|
||||
this.modelRoot.traverse((object) => {
|
||||
if (object.name === 'cad-edge-visual') object.visible = visible;
|
||||
if (object.name === 'cad-edge-seam') object.visible = visible && this.seamsVisible;
|
||||
});
|
||||
}
|
||||
|
||||
setSeamsVisible(visible: boolean): void {
|
||||
this.seamsVisible = visible;
|
||||
this.modelRoot.traverse((object) => {
|
||||
if (object.name === 'cad-edge-seam') object.visible = visible && this.edgesVisible;
|
||||
});
|
||||
}
|
||||
|
||||
get seamsShown(): boolean {
|
||||
return this.seamsVisible;
|
||||
}
|
||||
|
||||
setSSAO(enabled: boolean): void {
|
||||
if (!this.ssaoPass || this.ssaoEnabled === enabled) return;
|
||||
this.ssaoEnabled = enabled;
|
||||
this.ssaoPass.enabled = enabled;
|
||||
}
|
||||
|
||||
get ssaoOn(): boolean {
|
||||
return this.ssaoEnabled && this.ssaoPass !== null;
|
||||
}
|
||||
|
||||
setVertexCloudsVisible(visible: boolean): void {
|
||||
this.modelRoot.traverse((child) => {
|
||||
if (child.userData.pickRole === 'vertex') child.visible = visible;
|
||||
});
|
||||
}
|
||||
|
||||
setNodeVisible(nodeId: string, visible: boolean): void {
|
||||
const object = this.nodeObjects.get(nodeId);
|
||||
if (!object) return;
|
||||
object.visible = visible;
|
||||
this.nodeVisibility.set(nodeId, visible);
|
||||
}
|
||||
|
||||
// -- accessors -------------------------------------------------------------
|
||||
|
||||
get nodes(): SceneNode[] {
|
||||
return this.manifest?.nodes ?? [];
|
||||
}
|
||||
|
||||
get domElement(): HTMLCanvasElement {
|
||||
return this.renderer.domElement;
|
||||
}
|
||||
|
||||
nodeObject(nodeId: string): THREE.Group | undefined {
|
||||
return this.nodeObjects.get(nodeId);
|
||||
}
|
||||
|
||||
entityFor(nodeId: string, entityId: string): Entity | null {
|
||||
const node = this.manifest?.nodes.find((item) => item.node_id === nodeId);
|
||||
return this.sidecarFor(node)?.entities.find((item) => item.entity_id === entityId) ?? null;
|
||||
}
|
||||
|
||||
// -- camera + lifecycle --------------------------------------------------------
|
||||
|
||||
frame(): void {
|
||||
this.needsRender = true;
|
||||
const box = new THREE.Box3().setFromObject(this.modelRoot);
|
||||
if (box.isEmpty()) return;
|
||||
const center = box.getCenter(new THREE.Vector3());
|
||||
const size = box.getSize(new THREE.Vector3());
|
||||
// The 0.0005 floor only guards degenerate/empty geometry; it must stay
|
||||
// well below real model radii (a 0.01 floor pushed small parts 3.6x away).
|
||||
const radius = Math.max(size.length() * 0.5, 0.0005);
|
||||
// FIT is also the escape hatch from a rolled-around trackball orientation:
|
||||
// restore the canonical Z-up before re-framing.
|
||||
this.camera.up.set(0, 0, 1);
|
||||
// 2.3 (not the textbook ~2.8, nor 2.05): the bounding sphere over-covers
|
||||
// flat parts, but 2.05 read as slightly too large in review.
|
||||
this.camera.position.copy(center).add(new THREE.Vector3(1, 0.78, 1).normalize().multiplyScalar(radius * 2.3));
|
||||
this.camera.near = Math.max(radius / 100, 1e-5);
|
||||
this.camera.far = Math.max(radius * 100, 0.5);
|
||||
this.camera.updateProjectionMatrix();
|
||||
this.controls.target.copy(center);
|
||||
// Absolute minDistance (0.01 in the constructor) would clamp the zoomed-in
|
||||
// camera for small models; frame re-derives both bounds from the radius.
|
||||
this.controls.minDistance = radius * 0.2;
|
||||
this.controls.maxDistance = radius * 12;
|
||||
// Kill the trackball's rotational inertia — otherwise it keeps rolling the
|
||||
// freshly framed camera away from the canonical pose. These internals are
|
||||
// stable across three.js versions; there is no public "stop momentum" API.
|
||||
const trackball = this.controls as unknown as {
|
||||
_movePrev: THREE.Vector2; _moveCurr: THREE.Vector2; _lastAngle: number;
|
||||
_zoomStart: THREE.Vector2; _zoomEnd: THREE.Vector2;
|
||||
_panStart: THREE.Vector2; _panEnd: THREE.Vector2;
|
||||
};
|
||||
trackball._movePrev.copy(trackball._moveCurr);
|
||||
trackball._lastAngle = 0;
|
||||
trackball._zoomStart.copy(trackball._zoomEnd);
|
||||
trackball._panStart.copy(trackball._panEnd);
|
||||
this.controls.update();
|
||||
if (this.ssaoPass) this.tuneSSAO(this.ssaoPass, radius);
|
||||
}
|
||||
|
||||
getCameraState(): CameraState {
|
||||
const bounds = this.renderer.domElement.getBoundingClientRect();
|
||||
return {
|
||||
position: [this.camera.position.x, this.camera.position.y, this.camera.position.z],
|
||||
target: [this.controls.target.x, this.controls.target.y, this.controls.target.z],
|
||||
up: [this.camera.up.x, this.camera.up.y, this.camera.up.z],
|
||||
fov_deg: this.camera.fov,
|
||||
width: Math.round(bounds.width),
|
||||
height: Math.round(bounds.height),
|
||||
};
|
||||
}
|
||||
|
||||
snapshotPng(): string | null {
|
||||
try {
|
||||
this.render();
|
||||
return this.renderer.domElement.toDataURL('image/png');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private resize(): void {
|
||||
const width = this.host.clientWidth;
|
||||
const height = this.host.clientHeight;
|
||||
if (width <= 0 || height <= 0) return;
|
||||
this.renderer.setSize(width, height, false);
|
||||
// TrackballControls maps pointer deltas through the element rect, which
|
||||
// this host changes on load and panel resizes.
|
||||
this.controls.handleResize();
|
||||
this.camera.aspect = width / Math.max(height, 1);
|
||||
this.camera.updateProjectionMatrix();
|
||||
const pixelRatio = this.renderer.getPixelRatio();
|
||||
const deviceWidth = Math.max(Math.round(width * pixelRatio), 1);
|
||||
const deviceHeight = Math.max(Math.round(height * pixelRatio), 1);
|
||||
this.faceRT?.setSize(deviceWidth, deviceHeight);
|
||||
this.beautyRT?.setSize(deviceWidth, deviceHeight);
|
||||
this.ssaoPass?.setSize(deviceWidth, deviceHeight);
|
||||
// The scene may load before the host has its final layout; re-frame once.
|
||||
if (this.pendingFrame && this.modelRoot.children.length) {
|
||||
this.pendingFrame = false;
|
||||
this.frame();
|
||||
}
|
||||
const resolution = this.resolution();
|
||||
this.modelRoot.traverse((object) => {
|
||||
if (object instanceof LineSegments2) object.material.resolution.set(resolution.width, resolution.height);
|
||||
});
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed) return;
|
||||
this.disposed = true;
|
||||
this.observer.disconnect();
|
||||
this.renderer.setAnimationLoop(null);
|
||||
this.clearScene();
|
||||
this.controls.dispose();
|
||||
this.faceRT?.dispose();
|
||||
this.beautyRT?.dispose();
|
||||
this.ssaoPass?.dispose?.();
|
||||
if (this.blitScene) {
|
||||
const quad = this.blitScene.children[0] as THREE.Mesh | undefined;
|
||||
quad?.geometry.dispose();
|
||||
this.copyMaterial?.dispose();
|
||||
this.presentMaterial?.dispose();
|
||||
}
|
||||
this.renderer.dispose();
|
||||
this.renderer.domElement.remove();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
// Standalone BRep renderer component — public entry point.
|
||||
//
|
||||
// Embed this to render a scene-2.0 package (faces + edges) with CAD-grade
|
||||
// presentation: image-based studio lighting, GTAO ambient occlusion, free
|
||||
// trackball camera, and toggleable seam/degenerate edge display. Selection
|
||||
// and annotation are NOT part of this component; build them on top
|
||||
// (reference implementation: src/scene-view.ts).
|
||||
|
||||
export {
|
||||
BRepRenderer,
|
||||
EDGE_LAYER,
|
||||
FACE_LAYER,
|
||||
OVERLAY_LAYER,
|
||||
type BRepRendererOptions,
|
||||
type CameraState,
|
||||
type LiveGeometryPayload,
|
||||
} from './brep-renderer';
|
||||
@@ -0,0 +1,343 @@
|
||||
// Interactive BRep selection view used by the reverse-engineering mode.
|
||||
// A thin selection/annotation layer on top of the standalone BRepRenderer
|
||||
// component (src/renderer): this class adds raycast picking, selection
|
||||
// modes and annotation marks. All rendering — materials, edge display,
|
||||
// lighting, ambient occlusion, camera — lives in the renderer component.
|
||||
|
||||
import * as THREE from 'three';
|
||||
import { LineMaterial } from 'three/addons/lines/LineMaterial.js';
|
||||
import { LineSegments2 } from 'three/addons/lines/LineSegments2.js';
|
||||
import { LineSegmentsGeometry } from 'three/addons/lines/LineSegmentsGeometry.js';
|
||||
import { bindClickSelection } from './components/click-selection';
|
||||
import { disposeObject } from './cad-three';
|
||||
import { BRepRenderer, OVERLAY_LAYER, type CameraState, type LiveGeometryPayload } from './renderer';
|
||||
|
||||
export type { LiveGeometryPayload };
|
||||
import type { PackageFiles } from './product-package';
|
||||
import type { Entity, EntitySidecar, FaceGroup, SceneNode } from './scene2';
|
||||
|
||||
export type SelectionMode = 'component' | 'solid' | 'face' | 'edge' | 'vertex';
|
||||
export type PickResult = { nodeId: string; entityId: string | null; mode: SelectionMode; entity: Entity | null };
|
||||
export type { CameraState };
|
||||
|
||||
export const MARK_COLORS = ['#ff5c5c', '#ffd23f', '#4ade80', '#60a5fa', '#c084fc', '#fb923c', '#f472b6', '#34d399'];
|
||||
|
||||
export type SceneViewOptions = {
|
||||
onPick?: (result: PickResult) => void;
|
||||
selectionMode?: SelectionMode;
|
||||
background?: string;
|
||||
interactive?: boolean;
|
||||
/** GTAO ambient occlusion (default on). */
|
||||
ssao?: boolean;
|
||||
/** Show seam/degenerate edges (default off). */
|
||||
seams?: boolean;
|
||||
};
|
||||
|
||||
type Mark = { key: string; color: string; overlays: THREE.Object3D[] };
|
||||
|
||||
export class SceneView {
|
||||
readonly engine: BRepRenderer;
|
||||
onPick: ((result: PickResult) => void) | null;
|
||||
|
||||
private raycaster = new THREE.Raycaster();
|
||||
private pointer = new THREE.Vector2();
|
||||
selectionMode: SelectionMode;
|
||||
marks: Mark[] = [];
|
||||
private unbindClick: (() => void) | null = null;
|
||||
private disposed = false;
|
||||
|
||||
constructor(host: HTMLElement, options: SceneViewOptions = {}) {
|
||||
this.onPick = options.onPick ?? null;
|
||||
this.selectionMode = options.selectionMode ?? 'face';
|
||||
this.engine = new BRepRenderer(host, { background: options.background, ssao: options.ssao, seams: options.seams });
|
||||
if (options.interactive !== false) {
|
||||
this.unbindClick = bindClickSelection({
|
||||
element: this.engine.domElement,
|
||||
camera: this.engine.camera,
|
||||
controls: this.engine.controls,
|
||||
onClick: (event) => {
|
||||
const result = this.pick(event);
|
||||
if (result) this.onPick?.(result);
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// -- scene loading ---------------------------------------------------------
|
||||
|
||||
async loadScene(files: PackageFiles): Promise<void> {
|
||||
this.clearMarks();
|
||||
await this.engine.loadScene(files);
|
||||
this.applySelectionModeVisibility();
|
||||
}
|
||||
|
||||
loadLiveGeometry(payload: LiveGeometryPayload): void {
|
||||
this.clearMarks();
|
||||
this.engine.loadLiveGeometry(payload);
|
||||
}
|
||||
|
||||
/** Pause/resume the render loop (inactive editor modes must not render). */
|
||||
setRunning(running: boolean): void {
|
||||
this.engine.setRunning(running);
|
||||
}
|
||||
|
||||
clearScene(): void {
|
||||
this.clearMarks();
|
||||
this.engine.clearScene();
|
||||
}
|
||||
|
||||
sidecarFor(node: SceneNode | undefined): EntitySidecar | null {
|
||||
return this.engine.sidecarFor(node);
|
||||
}
|
||||
|
||||
entityFor(nodeId: string, entityId: string): Entity | null {
|
||||
return this.engine.entityFor(nodeId, entityId);
|
||||
}
|
||||
|
||||
get nodes(): SceneNode[] {
|
||||
return this.engine.nodes;
|
||||
}
|
||||
|
||||
nodeObject(nodeId: string): THREE.Group | undefined {
|
||||
return this.engine.nodeObject(nodeId);
|
||||
}
|
||||
|
||||
// -- picking ---------------------------------------------------------------
|
||||
|
||||
setSelectionMode(mode: SelectionMode): void {
|
||||
this.selectionMode = mode;
|
||||
this.applySelectionModeVisibility();
|
||||
}
|
||||
|
||||
private applySelectionModeVisibility(): void {
|
||||
this.engine.setVertexCloudsVisible(this.selectionMode === 'vertex');
|
||||
}
|
||||
|
||||
private isEffectivelyVisible(object: THREE.Object3D): boolean {
|
||||
for (let current: THREE.Object3D | null = object; current; current = current.parent) {
|
||||
if (!current.visible) return false;
|
||||
if (current === this.engine.modelRoot) break;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private pointerRay(event: PointerEvent): void {
|
||||
const bounds = this.engine.domElement.getBoundingClientRect();
|
||||
this.pointer.x = ((event.clientX - bounds.left) / bounds.width) * 2 - 1;
|
||||
this.pointer.y = -((event.clientY - bounds.top) / bounds.height) * 2 + 1;
|
||||
this.raycaster.setFromCamera(this.pointer, this.engine.camera);
|
||||
const distance = this.engine.camera.position.distanceTo(this.engine.controls.target);
|
||||
const worldPerPixel = 2 * Math.tan(THREE.MathUtils.degToRad(this.engine.camera.fov * 0.5)) * distance / Math.max(bounds.height, 1);
|
||||
this.raycaster.params.Line.threshold = worldPerPixel * 5;
|
||||
this.raycaster.params.Points.threshold = worldPerPixel * 8;
|
||||
}
|
||||
|
||||
/** A hidden seam/degenerate edge must not answer edge picks. */
|
||||
private isEdgePickable(entityId: string | undefined, sidecar: EntitySidecar | null): boolean {
|
||||
if (this.engine.seamsShown) return true;
|
||||
const entity = sidecar?.entities.find((item) => item.entity_id === entityId);
|
||||
const props = entity?.properties as { seam?: unknown; degenerate?: unknown } | undefined;
|
||||
return props?.seam !== true && props?.degenerate !== true;
|
||||
}
|
||||
|
||||
pick(event: PointerEvent): PickResult | null {
|
||||
this.pointerRay(event);
|
||||
const hits = this.raycaster.intersectObjects(this.engine.modelRoot.children, true).filter((hit) => {
|
||||
if (hit.object.userData.pickable === false || !this.isEffectivelyVisible(hit.object)) return false;
|
||||
return typeof hit.object.userData.nodeId === 'string';
|
||||
});
|
||||
const meshHit = hits.find((hit) => hit.object instanceof THREE.Mesh);
|
||||
if (this.selectionMode === 'component' || this.selectionMode === 'solid' || this.selectionMode === 'face') {
|
||||
if (!meshHit) return null;
|
||||
} else {
|
||||
const wanted = this.selectionMode === 'edge'
|
||||
? (hit: THREE.Intersection) => hit.object instanceof THREE.LineSegments
|
||||
: (hit: THREE.Intersection) => hit.object instanceof THREE.Points;
|
||||
let candidate: THREE.Intersection | undefined;
|
||||
for (const hit of hits.filter(wanted)) {
|
||||
if (this.selectionMode === 'edge') {
|
||||
const nodeId = hit.object.userData.nodeId as string;
|
||||
const node = this.engine.nodes.find((item) => item.node_id === nodeId);
|
||||
const sidecar = this.engine.sidecarFor(node);
|
||||
const entityId = this.edgeEntityIdForHit(hit, sidecar);
|
||||
if (!this.isEdgePickable(entityId, sidecar)) continue;
|
||||
}
|
||||
candidate = hit;
|
||||
break;
|
||||
}
|
||||
if (!candidate) return null;
|
||||
if (meshHit) {
|
||||
const occlusionAllowance = this.selectionMode === 'edge' ? this.raycaster.params.Line.threshold : this.raycaster.params.Points.threshold;
|
||||
if (candidate.distance > meshHit.distance + occlusionAllowance * 1.5) return null;
|
||||
}
|
||||
}
|
||||
const hit = (this.selectionMode === 'edge' || this.selectionMode === 'vertex')
|
||||
? hits.find((item) => this.selectionMode === 'edge' ? item.object instanceof THREE.LineSegments : item.object instanceof THREE.Points) ?? meshHit
|
||||
: meshHit;
|
||||
if (!hit) return null;
|
||||
const nodeId = hit.object.userData.nodeId as string;
|
||||
const node = this.engine.nodes.find((item) => item.node_id === nodeId);
|
||||
const sidecar = this.sidecarFor(node);
|
||||
if (this.selectionMode === 'component') {
|
||||
return { nodeId, entityId: null, mode: 'component', entity: null };
|
||||
}
|
||||
if (this.selectionMode === 'solid') {
|
||||
const solid = sidecar?.entities.find((item) => item.kind === 'solid') ?? null;
|
||||
return { nodeId, entityId: solid?.entity_id ?? null, mode: 'solid', entity: solid };
|
||||
}
|
||||
let entityId: string | undefined;
|
||||
if (this.selectionMode === 'face' && hit.object instanceof THREE.Mesh && typeof hit.faceIndex === 'number') {
|
||||
const triangleOffset = hit.faceIndex * 3;
|
||||
entityId = sidecar?.face_groups.find((group: FaceGroup) => triangleOffset >= group.first_index && triangleOffset < group.first_index + group.index_count)?.entity_id;
|
||||
} else if (this.selectionMode === 'edge' && hit.object instanceof THREE.LineSegments && typeof hit.index === 'number') {
|
||||
entityId = this.edgeEntityIdForHit(hit, sidecar);
|
||||
} else if (this.selectionMode === 'vertex' && hit.object instanceof THREE.Points && typeof hit.index === 'number') {
|
||||
entityId = hit.object.userData.vertexEntityIds?.[hit.index];
|
||||
}
|
||||
if (!entityId) return null;
|
||||
return { nodeId, entityId, mode: this.selectionMode, entity: this.entityFor(nodeId, entityId) };
|
||||
}
|
||||
|
||||
private edgeEntityIdForHit(hit: THREE.Intersection, sidecar: EntitySidecar | null): string | undefined {
|
||||
if (!(hit.object instanceof THREE.LineSegments) || typeof hit.index !== 'number' || !sidecar) return undefined;
|
||||
return sidecar.edge_groups.find((group: FaceGroup) => hit.index! >= group.first_index && hit.index! < group.first_index + group.index_count)?.entity_id;
|
||||
}
|
||||
|
||||
// -- highlight + marks -------------------------------------------------------
|
||||
|
||||
private attachOverlay(source: THREE.Object3D, overlay: THREE.Object3D): THREE.Object3D {
|
||||
this.engine.invalidate();
|
||||
overlay.name = 'entity-overlay';
|
||||
overlay.userData.pickable = false;
|
||||
// Overlays composite in the post-AO edge pass (see BRepRenderer): their
|
||||
// color must not be darkened by ambient occlusion.
|
||||
overlay.layers.set(OVERLAY_LAYER);
|
||||
overlay.renderOrder = 10;
|
||||
overlay.matrix.copy(source.matrix);
|
||||
overlay.matrixAutoUpdate = false;
|
||||
overlay.visible = source.visible;
|
||||
source.parent?.add(overlay);
|
||||
return overlay;
|
||||
}
|
||||
|
||||
buildEntityOverlays(nodeId: string, entityId: string | null, color: string, opacity = 0.72): THREE.Object3D[] {
|
||||
const object = this.engine.nodeObject(nodeId);
|
||||
const node = this.engine.nodes.find((item) => item.node_id === nodeId);
|
||||
const sidecar = this.engine.sidecarFor(node);
|
||||
if (!object || !sidecar) return [];
|
||||
const overlays: THREE.Object3D[] = [];
|
||||
const entityGroup = entityId ? sidecar.face_groups.find((group: FaceGroup) => group.entity_id === entityId) : undefined;
|
||||
const edgeGroup = entityId ? sidecar.edge_groups.find((group: FaceGroup) => group.entity_id === entityId) : undefined;
|
||||
// Entity ids carry the owning graph segment (entity/<graph>/solid/x);
|
||||
// classify by path SEGMENT, never by a positional prefix.
|
||||
const kindOf = (id: string | null | undefined) =>
|
||||
id?.split('/').find((part) => part === 'solid' || part === 'face' || part === 'edge' || part === 'vertex');
|
||||
const isSolid = kindOf(entityId) === 'solid';
|
||||
const isVertex = kindOf(entityId) === 'vertex';
|
||||
object.traverse((child: THREE.Object3D) => {
|
||||
if (overlays.length || !this.isEffectivelyVisible(child) || !(child instanceof THREE.Mesh || child instanceof THREE.LineSegments || child instanceof THREE.Points)) return;
|
||||
const source = child as THREE.Mesh | THREE.LineSegments | THREE.Points;
|
||||
const range = entityGroup || edgeGroup;
|
||||
if (!range && !isVertex && !isSolid) return;
|
||||
if (entityGroup && !(source instanceof THREE.Mesh)) return;
|
||||
if (edgeGroup && !entityGroup && !(source instanceof THREE.LineSegments)) return;
|
||||
if (isVertex && !source.userData.vertexEntityIds?.includes(entityId!)) return;
|
||||
if (source instanceof THREE.LineSegments && range) {
|
||||
const lineGeometry = new LineSegmentsGeometry();
|
||||
const positions: number[] = [];
|
||||
const index = source.geometry.index;
|
||||
const position = source.geometry.getAttribute('position');
|
||||
for (let offset = range.first_index; offset < range.first_index + range.index_count; offset += 2) {
|
||||
const a = index ? index.getX(offset) : offset;
|
||||
const b = index ? index.getX(offset + 1) : offset + 1;
|
||||
positions.push(position.getX(a), position.getY(a), position.getZ(a), position.getX(b), position.getY(b), position.getZ(b));
|
||||
}
|
||||
lineGeometry.setPositions(positions);
|
||||
const material = new LineMaterial({ color, linewidth: 5, worldUnits: false, transparent: true, opacity: 1, depthTest: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -4, polygonOffsetUnits: -4 });
|
||||
material.resolution.set(this.engine.domElement.clientWidth, this.engine.domElement.clientHeight);
|
||||
overlays.push(this.attachOverlay(source, new LineSegments2(lineGeometry, material)));
|
||||
} else if (source instanceof THREE.Points) {
|
||||
const geometry = source.geometry.clone();
|
||||
const vertexIndex = source.userData.vertexEntityIds.indexOf(entityId!);
|
||||
geometry.setDrawRange(vertexIndex, 1);
|
||||
overlays.push(this.attachOverlay(source, new THREE.Points(geometry, new THREE.PointsMaterial({ color, size: 16, sizeAttenuation: false, transparent: true, opacity: 1, depthTest: true, depthWrite: false, polygonOffset: true, polygonOffsetFactor: -4, polygonOffsetUnits: -4 }))));
|
||||
} else {
|
||||
const geometry = source.geometry.clone();
|
||||
if (range) geometry.setDrawRange(range.first_index, range.index_count);
|
||||
// Depth-tested so highlights hide behind the body like real geometry;
|
||||
// the polygon offset keeps the overlay from z-fighting its own face.
|
||||
overlays.push(this.attachOverlay(source, new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({ color, transparent: true, opacity: isSolid ? opacity * 0.55 : opacity, depthTest: true, depthWrite: false, side: THREE.DoubleSide, polygonOffset: true, polygonOffsetFactor: -4, polygonOffsetUnits: -4 }))));
|
||||
}
|
||||
});
|
||||
return overlays;
|
||||
}
|
||||
|
||||
addMark(nodeId: string, entityId: string | null, color: string): void {
|
||||
const key = `${nodeId}::${entityId ?? 'component'}`;
|
||||
if (this.marks.some((mark) => mark.key === key)) return;
|
||||
const overlays = this.buildEntityOverlays(nodeId, entityId, color);
|
||||
if (overlays.length) this.marks.push({ key, color, overlays });
|
||||
}
|
||||
|
||||
removeMark(key: string): void {
|
||||
const index = this.marks.findIndex((mark) => mark.key === key);
|
||||
if (index < 0) return;
|
||||
for (const overlay of this.marks[index].overlays) {
|
||||
overlay.parent?.remove(overlay);
|
||||
disposeObject(overlay);
|
||||
}
|
||||
this.marks.splice(index, 1);
|
||||
}
|
||||
|
||||
clearMarks(): void {
|
||||
this.engine.invalidate();
|
||||
for (const mark of this.marks) {
|
||||
for (const overlay of mark.overlays) {
|
||||
overlay.parent?.remove(overlay);
|
||||
disposeObject(overlay);
|
||||
}
|
||||
}
|
||||
this.marks = [];
|
||||
}
|
||||
|
||||
hasMark(nodeId: string, entityId: string | null): boolean {
|
||||
return this.marks.some((mark) => mark.key === `${nodeId}::${entityId ?? 'component'}`);
|
||||
}
|
||||
|
||||
// -- display options + camera + lifecycle --------------------------------------
|
||||
|
||||
setEdgesVisible(visible: boolean): void {
|
||||
this.engine.invalidate();
|
||||
this.engine.setEdgesVisible(visible);
|
||||
}
|
||||
|
||||
setSeamsVisible(visible: boolean): void {
|
||||
this.engine.invalidate();
|
||||
this.engine.setSeamsVisible(visible);
|
||||
}
|
||||
|
||||
setSSAO(enabled: boolean): void {
|
||||
this.engine.invalidate();
|
||||
this.engine.setSSAO(enabled);
|
||||
}
|
||||
|
||||
frame(): void {
|
||||
this.engine.invalidate();
|
||||
this.engine.frame();
|
||||
}
|
||||
|
||||
getCameraState(): CameraState {
|
||||
return this.engine.getCameraState();
|
||||
}
|
||||
|
||||
snapshotPng(): string | null {
|
||||
return this.engine.snapshotPng();
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
if (this.disposed) return;
|
||||
this.disposed = true;
|
||||
this.unbindClick?.();
|
||||
this.engine.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
import { strFromU8 } from 'fflate';
|
||||
import type { PackageFiles } from './product-package';
|
||||
|
||||
export type Vec3 = [number, number, number];
|
||||
export type Transform = { origin: Vec3; x_axis: Vec3; y_axis: Vec3; z_axis: Vec3 };
|
||||
export type SourceRecord = Record<string, unknown> & {
|
||||
kind: string;
|
||||
definition_id?: string;
|
||||
graph_id?: string;
|
||||
node_id?: string;
|
||||
output_slot?: number;
|
||||
topology_kind?: string;
|
||||
topo_id?: string;
|
||||
};
|
||||
export type Definition = {
|
||||
definition_id: string;
|
||||
definition_kind: 'single_solid' | 'assembly';
|
||||
revision: string;
|
||||
content_hash: string;
|
||||
product_asset_id: string;
|
||||
feature_graph_asset_id: string;
|
||||
};
|
||||
export type SceneNode = {
|
||||
node_id: string;
|
||||
parent_node_id: string | null;
|
||||
display_name: string;
|
||||
node_kind: 'part' | 'assembly' | 'solid';
|
||||
definition_id: string;
|
||||
definition_kind: 'single_solid' | 'assembly';
|
||||
component_id: string | null;
|
||||
instance_id: string | null;
|
||||
transform: Transform;
|
||||
geometry_asset_id: string | null;
|
||||
entity_asset_id: string | null;
|
||||
material_id: string | null;
|
||||
properties: Record<string, unknown>;
|
||||
};
|
||||
export type Asset = {
|
||||
asset_id: string;
|
||||
uri: string;
|
||||
media_type: string;
|
||||
sha256: string;
|
||||
byte_length: number;
|
||||
};
|
||||
export type Entity = {
|
||||
entity_id: string;
|
||||
kind: 'solid' | 'face' | 'edge' | 'vertex';
|
||||
topo_id: string;
|
||||
parent_entity_ids: string[];
|
||||
child_entity_ids: string[];
|
||||
source: SourceRecord;
|
||||
properties: Record<string, unknown>;
|
||||
geometry: Record<string, unknown>;
|
||||
tags: string[];
|
||||
};
|
||||
export type EntitySidecar = {
|
||||
schema_version: '1.0' | '2.0';
|
||||
definition_id: string;
|
||||
geometry_asset_id: string;
|
||||
edge_asset_id: string;
|
||||
geometry_engine?: Record<string, unknown>;
|
||||
entities: Entity[];
|
||||
face_groups: FaceGroup[];
|
||||
edge_groups: FaceGroup[];
|
||||
};
|
||||
export type FaceGroup = { entity_id: string; first_index: number; index_count: number };
|
||||
export type SourceAsset = {
|
||||
source_asset_id: string;
|
||||
uri: string;
|
||||
sha256: string;
|
||||
byte_length: number;
|
||||
media_type: string;
|
||||
display_name: string;
|
||||
};
|
||||
export type SourceSpan = {
|
||||
source_asset_id: string;
|
||||
uri: string;
|
||||
start_line: number;
|
||||
end_line: number;
|
||||
symbol: string | null;
|
||||
};
|
||||
export type Feature = {
|
||||
feature_id: string;
|
||||
definition_id: string;
|
||||
graph_id: string;
|
||||
node_id: string;
|
||||
op: string;
|
||||
label: string | null;
|
||||
parameters: Record<string, unknown>;
|
||||
input_feature_ids: string[];
|
||||
output_count: number;
|
||||
source_spans: SourceSpan[];
|
||||
};
|
||||
export type ConnectorSnapshot = {
|
||||
connector_snapshot_id: string;
|
||||
node_id: string;
|
||||
definition_id: string;
|
||||
definition_kind: 'single_solid' | 'assembly';
|
||||
connector_id: string;
|
||||
name: string;
|
||||
anchor_kind: 'placement' | 'geometry' | 'public';
|
||||
local_frame: Transform;
|
||||
binding: Record<string, unknown> | null;
|
||||
source_connector_snapshot_id: string | null;
|
||||
source_feature_id: string | null;
|
||||
};
|
||||
export type ConnectorRef = {
|
||||
definition_id: string;
|
||||
component_id: string;
|
||||
instance_id: string;
|
||||
connector_id: string;
|
||||
connector_snapshot_id: string;
|
||||
};
|
||||
export type Joint = {
|
||||
joint_id: string;
|
||||
assembly_definition_id: string;
|
||||
joint_type: 'fixed' | 'revolute' | 'prismatic' | 'cylindrical' | 'planar' | 'ball' | 'gear' | 'belt' | 'rack_pinion';
|
||||
connector_a: ConnectorRef;
|
||||
connector_b: ConnectorRef;
|
||||
parameters: Record<string, unknown>;
|
||||
limits: Record<string, unknown> | null;
|
||||
source_feature_id: string | null;
|
||||
};
|
||||
export type SceneManifest = {
|
||||
schema_version: '2.0' | 're-mode-source-1';
|
||||
artifact_kind?: 're_mode_source_scene';
|
||||
scene_id: string;
|
||||
revision: string;
|
||||
units: 'mm';
|
||||
roots: string[];
|
||||
definitions: Definition[];
|
||||
geometry_assets: Asset[];
|
||||
entity_assets: Asset[];
|
||||
product_assets: Array<Asset & { definition_id: string; definition_kind: 'single_solid' | 'assembly'; revision: string; content_hash: string }>,
|
||||
feature_graph_assets: Array<Asset & { definition_id: string; graph_id: string; graph_revision: string }>;
|
||||
source_assets: SourceAsset[];
|
||||
nodes: SceneNode[];
|
||||
connectors: ConnectorSnapshot[];
|
||||
joints: Joint[];
|
||||
feature_index: Feature[];
|
||||
source_index: Array<{
|
||||
source_index_id: string;
|
||||
source_asset_id: string;
|
||||
uri: string;
|
||||
definition_id: string;
|
||||
feature_id: string;
|
||||
start_line: number;
|
||||
end_line: number;
|
||||
symbol: string | null;
|
||||
}>;
|
||||
connector_index: Array<{
|
||||
connector_index_id: string;
|
||||
definition_id: string;
|
||||
node_id: string;
|
||||
connector_id: string;
|
||||
connector_snapshot_id: string;
|
||||
source_feature_id: string | null;
|
||||
}>;
|
||||
joint_index: Array<{
|
||||
joint_index_id: string;
|
||||
assembly_definition_id: string;
|
||||
joint_id: string;
|
||||
source_feature_id: string | null;
|
||||
}>;
|
||||
camera: { target: Vec3; position: Vec3; up: Vec3; near: number; far: number; fit_mode: string; margin: number };
|
||||
extensions: Record<string, unknown>;
|
||||
};
|
||||
export type OperationSource = {
|
||||
path?: string | null;
|
||||
line: number;
|
||||
column: number;
|
||||
end_line: number;
|
||||
end_column: number;
|
||||
call_text?: string;
|
||||
callsite_id: string;
|
||||
assignment_targets: string[];
|
||||
};
|
||||
export type ModelNode = {
|
||||
node_id: string;
|
||||
definition_id: string;
|
||||
graph_id: string;
|
||||
local_node_id: string;
|
||||
op: string;
|
||||
params: Record<string, unknown>;
|
||||
inputs: string[];
|
||||
output_count: number;
|
||||
display: { label?: string; category?: string; summary?: string };
|
||||
source?: OperationSource;
|
||||
sources: OperationSource[];
|
||||
};
|
||||
export type ModelDocument = { graph: { graph_id: string; nodes: ModelNode[] }; leaf_ids: string[] };
|
||||
|
||||
export function buildFederatedFeatureModel(
|
||||
manifest: SceneManifest,
|
||||
files: PackageFiles,
|
||||
): { model: ModelDocument; sources: Map<string, string> } {
|
||||
const pathBySourceId = new Map<string, string>();
|
||||
const sources = new Map<string, string>();
|
||||
for (const asset of manifest.source_assets) {
|
||||
let path = asset.display_name;
|
||||
const content = strFromU8(files[asset.uri]);
|
||||
const existing = sources.get(path);
|
||||
if (existing !== undefined && existing !== content) {
|
||||
path = `${path} [${asset.source_asset_id.slice(7, 15)}]`;
|
||||
}
|
||||
sources.set(path, content);
|
||||
pathBySourceId.set(asset.source_asset_id, path);
|
||||
}
|
||||
|
||||
const nodes: ModelNode[] = manifest.feature_index.map((feature) => {
|
||||
const featureSources = feature.source_spans.map((span, index) => {
|
||||
const sourcePath = pathBySourceId.get(span.source_asset_id);
|
||||
return {
|
||||
path: sourcePath ?? null,
|
||||
line: span.start_line,
|
||||
column: 0,
|
||||
end_line: span.end_line,
|
||||
end_column: 0,
|
||||
callsite_id: `${feature.feature_id}/source/${index}`,
|
||||
assignment_targets: span.symbol ? [span.symbol] : [],
|
||||
} satisfies OperationSource;
|
||||
});
|
||||
return {
|
||||
node_id: feature.feature_id,
|
||||
definition_id: feature.definition_id,
|
||||
graph_id: feature.graph_id,
|
||||
local_node_id: feature.node_id,
|
||||
op: feature.op,
|
||||
params: feature.parameters,
|
||||
inputs: feature.input_feature_ids,
|
||||
output_count: feature.output_count,
|
||||
display: {
|
||||
label: feature.label ?? undefined,
|
||||
category: feature.definition_id,
|
||||
},
|
||||
source: featureSources[0],
|
||||
sources: featureSources,
|
||||
};
|
||||
});
|
||||
const consumed = new Set(nodes.flatMap((node) => node.inputs));
|
||||
const leafIds = nodes.filter((node) => !consumed.has(node.node_id)).map((node) => node.node_id);
|
||||
return {
|
||||
model: { graph: { graph_id: 'federated', nodes }, leaf_ids: leafIds },
|
||||
sources,
|
||||
};
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
"allowArbitraryExtensions": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"paths": {
|
||||
"@/*": ["./src/*"]
|
||||
}
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"module": "nodenext",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import path from "node:path";
|
||||
|
||||
import tailwindcss from "@tailwindcss/vite";
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { defineConfig } from "vite";
|
||||
|
||||
// The studio webui. In dev, API/WebSocket traffic proxies to the runtime
|
||||
// server (`sca edit`, default :7180); `npm run build` emits the
|
||||
// static bundle the server hosts from simplecadapi/editor/webui.
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
resolve: {
|
||||
alias: {
|
||||
"@": path.resolve(import.meta.dirname, "./src"),
|
||||
},
|
||||
},
|
||||
server: {
|
||||
port: 5180,
|
||||
proxy: {
|
||||
"/api": "http://127.0.0.1:7180",
|
||||
"/ws": { target: "ws://127.0.0.1:7180", ws: true },
|
||||
},
|
||||
},
|
||||
build: {
|
||||
outDir: "../src/simplecadapi/editor/webui",
|
||||
emptyOutDir: true,
|
||||
chunkSizeWarningLimit: 1600,
|
||||
},
|
||||
});
|
||||
+8
-1
@@ -49,7 +49,11 @@ dev = [
|
||||
drawing = [
|
||||
"pymupdf>=1.28.2",
|
||||
]
|
||||
editor = []
|
||||
editor = [
|
||||
"starlette>=1.7.0",
|
||||
"uvicorn>=0.54.0",
|
||||
"websockets>=16.1.1",
|
||||
]
|
||||
inspect = [
|
||||
"matplotlib>=3.7.0",
|
||||
]
|
||||
@@ -81,6 +85,9 @@ core-metadata-version = "2.4"
|
||||
# Ship harness-neutral source; sca skill compiles it on the user's machine.
|
||||
packages = ["src/simplecadapi"]
|
||||
include = ["src/**/*"]
|
||||
# The built webui (`cd editor-web && npm run build`) is git-ignored; ship it
|
||||
# with `sca edit` when it has been built.
|
||||
artifacts = ["src/simplecadapi/editor/webui/**"]
|
||||
|
||||
[tool.hatch.build.targets.wheel.force-include]
|
||||
"docs/skill" = "simplecadapi/skill/resources/docs/skill"
|
||||
|
||||
@@ -9,6 +9,7 @@ Groups, each owned by its module and registered here at parser level so
|
||||
sca export <package.scadpkg> [--format ...]
|
||||
sca run <notebook.py> [--set NAME=VALUE] [--out ...]
|
||||
sca ls [DIR] | sca params <notebook.py>
|
||||
sca edit [WORKSPACE] # the web editor (needs the 'editor' extra)
|
||||
|
||||
Shared contract: group handlers return ``(report, exit_code)`` and are
|
||||
followed by the group's own printer (human-readable for init/addon, JSON
|
||||
@@ -30,6 +31,7 @@ from .skill.compiler import SkillBuildError
|
||||
|
||||
def build_parser() -> argparse.ArgumentParser:
|
||||
from .addon import cli as addon_cli
|
||||
from .editor import cli as editor_cli
|
||||
from .exporter import cli as exporter_cli
|
||||
from .runtime import cli as runtime_cli
|
||||
from .skill import cli as skill_cli
|
||||
@@ -44,6 +46,7 @@ def build_parser() -> argparse.ArgumentParser:
|
||||
)
|
||||
subparsers = parser.add_subparsers(dest="group", required=True)
|
||||
addon_cli.configure(subparsers)
|
||||
editor_cli.configure(subparsers)
|
||||
exporter_cli.configure(subparsers)
|
||||
runtime_cli.configure(subparsers)
|
||||
skill_cli.configure(subparsers)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
"""The SimpleCAD editor: ``sca edit <workspace>``.
|
||||
|
||||
A code-first CAD editor over a workspace of SimpleCAD notebooks. It runs
|
||||
the notebooks in a marimo kernel with the SDK's own cell executor, so a
|
||||
model gives the same product in the editor as under ``sca run``. Needs the
|
||||
``editor`` extra (``pip install "simplecadapi[editor]"``).
|
||||
"""
|
||||
@@ -0,0 +1,58 @@
|
||||
"""The ``sca edit`` command (see :mod:`simplecadapi.cli`).
|
||||
|
||||
::
|
||||
|
||||
sca edit [WORKSPACE] # open the editor on a directory of notebooks
|
||||
sca edit path/to/model.py # ... starting at one notebook
|
||||
sca edit --port 7180 --no-browser
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
DEFAULT_PORT = 7180
|
||||
|
||||
|
||||
def configure(subparsers: argparse._SubParsersAction) -> None:
|
||||
parser = subparsers.add_parser(
|
||||
"edit",
|
||||
help="open the web editor on a workspace of SimpleCAD notebooks",
|
||||
description="Serve the code-first CAD editor for WORKSPACE (default: the "
|
||||
"current directory): a directory of notebooks with [tool.simplecadapi] "
|
||||
"headers, or one such notebook. Needs the 'editor' extra.",
|
||||
)
|
||||
parser.add_argument("workspace", type=Path, nargs="?", default=Path.cwd())
|
||||
parser.add_argument("--host", default="127.0.0.1")
|
||||
parser.add_argument("--port", type=int, default=DEFAULT_PORT)
|
||||
parser.add_argument("--no-browser", action="store_true", help="do not open a browser tab")
|
||||
parser.set_defaults(handler=_execute, printer=lambda report: None)
|
||||
|
||||
|
||||
def _execute(args: argparse.Namespace) -> tuple[dict[str, Any], int]:
|
||||
try:
|
||||
from .server import serve_workspace
|
||||
except ModuleNotFoundError as error:
|
||||
raise ValueError(
|
||||
f"the editor needs the 'editor' extra ({error.name} is missing): "
|
||||
'pip install "simplecadapi[editor]"'
|
||||
) from error
|
||||
target = args.workspace.expanduser().resolve()
|
||||
notebook = None
|
||||
if target.is_file():
|
||||
notebook, target = target, target.parent
|
||||
elif not target.is_dir():
|
||||
raise ValueError(f"{args.workspace}: no such file or directory")
|
||||
code = serve_workspace(
|
||||
target,
|
||||
host=args.host,
|
||||
port=args.port,
|
||||
open_browser=not args.no_browser,
|
||||
notebook=notebook,
|
||||
)
|
||||
return {}, code
|
||||
|
||||
|
||||
__all__ = ["configure"]
|
||||
@@ -0,0 +1,485 @@
|
||||
"""Host the workspace's marimo kernel as a subprocess and drive it.
|
||||
|
||||
The bridge owns exactly one headless ``marimo edit`` server per workspace.
|
||||
It creates the kernel session by holding one WebSocket connection (the same
|
||||
thing a browser tab does) and drives everything else through marimo's HTTP
|
||||
API:
|
||||
|
||||
- ``POST /api/kernel/execute`` runs driver snippets in the kernel's scratch
|
||||
cell (deliberately auth-exempt for agents);
|
||||
- ``marimo._code_mode`` edits, runs and deletes notebook cells;
|
||||
- the kernel runs the notebook with the SimpleCAD cell executor
|
||||
(:mod:`simplecadapi.runtime.executor`), exactly as ``sca run`` does; the
|
||||
bridge asks it for the product with
|
||||
:func:`simplecadapi.runtime.live.publish_live` once the cells settle.
|
||||
|
||||
The held WebSocket also carries marimo's own messages; ``completed-run`` ends
|
||||
every batch of cell runs, whoever started it (this bridge, or a person
|
||||
typing in the embedded marimo editor), and is what the server reacts to.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from typing import Callable
|
||||
|
||||
import websockets
|
||||
|
||||
SESSION_ID = "sca-runtime"
|
||||
|
||||
|
||||
class KernelError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
class MarimoKernel:
|
||||
def __init__(
|
||||
self,
|
||||
notebook: Path,
|
||||
*,
|
||||
server_port: int,
|
||||
on_run_complete: Callable[[], None] | None = None,
|
||||
) -> None:
|
||||
self.notebook = notebook.expanduser().resolve()
|
||||
self.on_run_complete = on_run_complete
|
||||
self._own_calls = 0
|
||||
self._own_ended = 0.0
|
||||
self.workspace = self.notebook.parent
|
||||
self.marimo_port = _free_port(server_port + 1)
|
||||
self.marimo_url = f"http://127.0.0.1:{self.marimo_port}"
|
||||
self._process: subprocess.Popen[bytes] | None = None
|
||||
self._token: str | None = None
|
||||
self._ws_thread: threading.Thread | None = None
|
||||
self._stop = threading.Event()
|
||||
self._lock = threading.Lock()
|
||||
|
||||
# -- lifecycle ---------------------------------------------------------------
|
||||
|
||||
def _ensure_lazy_config(self) -> None:
|
||||
"""Provision marimo's lazy reactive mode for the workspace.
|
||||
|
||||
The editor's execution semantics (cell rollback, differential
|
||||
re-runs, stale suffixes) are marimo's lazy mode:
|
||||
runtime.on_cell_change="lazy". marimo discovers config by walking up
|
||||
from its cwd (the workspace), so when NO .marimo.toml exists on that
|
||||
path this writes one at the workspace root — workspaces may live
|
||||
anywhere on disk. An existing config anywhere up the tree always
|
||||
wins (the user's choice).
|
||||
"""
|
||||
probe = self.workspace
|
||||
while True:
|
||||
if (probe / ".marimo.toml").is_file():
|
||||
return
|
||||
parent = probe.parent
|
||||
if parent == probe:
|
||||
break
|
||||
probe = parent
|
||||
try:
|
||||
(self.workspace / ".marimo.toml").write_text(
|
||||
"# Provisioned by sca edit: rollback / differential rerun\n"
|
||||
"# semantics need marimo's lazy reactive mode.\n"
|
||||
'[runtime]\non_cell_change = "lazy"\n',
|
||||
encoding="utf-8",
|
||||
)
|
||||
except OSError as exc:
|
||||
print(f"[sca edit] could not write lazy-mode config: {exc}", file=sys.stderr)
|
||||
|
||||
def start(self, timeout: float = 60.0) -> None:
|
||||
"""Spawn marimo, wait for readiness, create the kernel session and
|
||||
instantiate the notebook (runs all cells top-to-bottom)."""
|
||||
self._ensure_lazy_config()
|
||||
env = dict(os.environ)
|
||||
log_path = self.workspace / ".sca-editor" / "marimo-kernel.log"
|
||||
log_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
self._log_file = log_path.open("ab")
|
||||
self._process = subprocess.Popen(
|
||||
[
|
||||
sys.executable, "-m", "marimo", "edit", str(self.notebook),
|
||||
"--headless", "--no-token", "--port", str(self.marimo_port),
|
||||
],
|
||||
cwd=str(self.workspace),
|
||||
env=env,
|
||||
stdout=self._log_file,
|
||||
stderr=subprocess.STDOUT,
|
||||
)
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if self._process.poll() is not None:
|
||||
raise KernelError(f"marimo exited with code {self._process.returncode}")
|
||||
try:
|
||||
with urllib.request.urlopen(f"{self.marimo_url}/api/sessions", timeout=2) as resp:
|
||||
resp.read()
|
||||
break
|
||||
except (urllib.error.URLError, OSError):
|
||||
time.sleep(0.3)
|
||||
else:
|
||||
self.stop()
|
||||
raise KernelError(f"marimo not ready after {timeout:.0f}s")
|
||||
|
||||
self._token = self._fetch_token()
|
||||
self._hold_session()
|
||||
self.instantiate()
|
||||
|
||||
@property
|
||||
def alive(self) -> bool:
|
||||
return self._process is not None and self._process.poll() is None
|
||||
|
||||
def stop(self) -> None:
|
||||
self._stop.set()
|
||||
if self._process is not None and self._process.poll() is None:
|
||||
self._process.terminate()
|
||||
try:
|
||||
self._process.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
self._process.kill()
|
||||
if getattr(self, "_log_file", None) is not None:
|
||||
try:
|
||||
self._log_file.close()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# -- session plumbing ----------------------------------------------------------
|
||||
|
||||
def _fetch_token(self) -> str:
|
||||
"""The skew-protection token ships in the marimo homepage HTML."""
|
||||
with urllib.request.urlopen(f"{self.marimo_url}/", timeout=5) as resp:
|
||||
html = resp.read().decode("utf-8", "replace")
|
||||
match = re.search(r'"serverToken":\s*"([^"]+)"', html)
|
||||
if match is None:
|
||||
raise KernelError("could not read marimo server token from homepage")
|
||||
return match.group(1)
|
||||
|
||||
def _hold_session(self) -> None:
|
||||
"""Hold one WS connection to marimo — this creates and keeps the
|
||||
kernel session alive (a headless browser tab, effectively).
|
||||
|
||||
marimo restarts its websocket service whenever the notebook file
|
||||
changes on disk (code.edit persists) — the connection dies with
|
||||
1012/service-restart. The holder must reconnect, or the session
|
||||
silently dies and every later edit/run becomes a no-op.
|
||||
"""
|
||||
|
||||
def run() -> None:
|
||||
import asyncio
|
||||
|
||||
async def main() -> None:
|
||||
uri = (
|
||||
f"ws://127.0.0.1:{self.marimo_port}/ws"
|
||||
f"?session_id={SESSION_ID}&file_key={self.notebook}"
|
||||
)
|
||||
while not self._stop.is_set():
|
||||
try:
|
||||
async with websockets.connect(uri, max_size=None) as ws:
|
||||
async for message in ws:
|
||||
self._on_message(message)
|
||||
except Exception:
|
||||
if self._stop.is_set():
|
||||
return
|
||||
# marimo restarted; re-hold the same session id.
|
||||
await asyncio.sleep(1.0)
|
||||
|
||||
asyncio.run(main())
|
||||
|
||||
self._ws_thread = threading.Thread(target=run, name="marimo-bridge-ws", daemon=True)
|
||||
self._ws_thread.start()
|
||||
time.sleep(1.0)
|
||||
|
||||
def _on_message(self, message: str | bytes) -> None:
|
||||
try:
|
||||
data = json.loads(message)
|
||||
except (TypeError, ValueError):
|
||||
return
|
||||
if not isinstance(data, dict) or data.get("op") != "completed-run":
|
||||
return
|
||||
# Runs this bridge asked for (scratch snippets, publishing) end in a
|
||||
# completed-run too; only the cell runs of someone else count.
|
||||
if self._own_calls or time.monotonic() - self._own_ended < 0.5:
|
||||
return
|
||||
if self.on_run_complete is not None:
|
||||
self.on_run_complete()
|
||||
|
||||
def instantiate(self) -> None:
|
||||
"""Run all notebook cells (what the marimo frontend does on load)."""
|
||||
self._post("/api/kernel/instantiate", {"objectIds": [], "values": []})
|
||||
|
||||
def list_cells(self) -> list[dict]:
|
||||
"""Notebook cells as [{id, name, code, status, output, console}].
|
||||
|
||||
Mirrors the marimo reading experience: each cell carries its last
|
||||
execution status, main output text, and buffered console output so
|
||||
the studio can render code → output interleaved. Infrastructure
|
||||
cells (the setup cell) are hidden; every other cell, anonymous ones
|
||||
included, is one block of the notebook. Cells are addressed by id.
|
||||
"""
|
||||
hidden = {"setup"}
|
||||
result = self.execute(
|
||||
"import json as _json\n"
|
||||
"import marimo._code_mode as _cm\n"
|
||||
"def _text(_o):\n"
|
||||
" if _o is None:\n"
|
||||
" return None\n"
|
||||
" # CellOutput.data is str | list[Error] | dict[str, Any] — render\n"
|
||||
" # each shape as plain text instead of its repr.\n"
|
||||
" _d = getattr(_o, 'data', None)\n"
|
||||
" if isinstance(_d, str):\n"
|
||||
" _v = _d\n"
|
||||
" elif isinstance(_d, dict):\n"
|
||||
" _v = _d.get('text/plain') or str(_d)\n"
|
||||
" elif isinstance(_d, (list, tuple)):\n"
|
||||
" _parts = []\n"
|
||||
" for _item in _d:\n"
|
||||
" _m = getattr(_item, 'message', None)\n"
|
||||
" _parts.append(_m if isinstance(_m, str) else str(_item))\n"
|
||||
" _v = '\\n'.join(_parts)\n"
|
||||
" else:\n"
|
||||
" _v = str(_d) if _d is not None else None\n"
|
||||
" if isinstance(_v, str):\n"
|
||||
" if _v.lstrip().startswith('['):\n"
|
||||
" # marimo serialises mimebundle outputs as a JSON array of\n"
|
||||
" # '<mimetype>:<text>' strings — prefer the text/plain entry.\n"
|
||||
" try:\n"
|
||||
" import json as _json\n"
|
||||
" _arr = _json.loads(_v)\n"
|
||||
" except Exception:\n"
|
||||
" _arr = None\n"
|
||||
" if isinstance(_arr, list):\n"
|
||||
" _plain = [str(_x)[len('text/plain:'):] for _x in _arr if isinstance(_x, str) and _x.startswith('text/plain:')]\n"
|
||||
" _v = _plain[0] if _plain else '\\n'.join(str(_x) for _x in _arr)\n"
|
||||
" if _v.startswith('text/plain:'):\n"
|
||||
" _v = _v[len('text/plain:'):]\n"
|
||||
" if _v.lstrip().startswith('<'):\n"
|
||||
" import html as _html, re as _re\n"
|
||||
" _v = _html.unescape(_re.sub(r'<[^>]+>', '', _v)).strip()\n"
|
||||
" return _v\n"
|
||||
" return str(_v) if _v is not None else None\n"
|
||||
"_ctx = _cm.get_context()\n"
|
||||
"_rows = []\n"
|
||||
"for _c in _ctx.cells:\n"
|
||||
" _st = getattr(_c, 'status', None)\n"
|
||||
" _rows.append({\n"
|
||||
" 'id': _c.id, 'name': _c.name, 'code': _c.code,\n"
|
||||
" 'status': getattr(_st, 'value', None) if _st is not None else None,\n"
|
||||
" 'errors': [str(getattr(_e, 'msg', _e))[:300] for _e in (getattr(_c, 'errors', None) or [])][:4],\n"
|
||||
" 'output': (_text(_c.output) or '')[:400] if getattr(_c, 'output', None) is not None else None,\n"
|
||||
" 'console': [t for t in ((_text(_o) or '')[-4000:] for _o in (getattr(_c, 'console_outputs', None) or [])[-4:]) if t],\n"
|
||||
" })\n"
|
||||
"print(_json.dumps(_rows))\n"
|
||||
)
|
||||
for line in (result.get("log") or "").splitlines():
|
||||
line = line.strip()
|
||||
if line.startswith("["):
|
||||
try:
|
||||
cells = json.loads(line)
|
||||
if isinstance(cells, list):
|
||||
return [c for c in cells if isinstance(c, dict) and str(c.get("name", "")) not in hidden]
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
return []
|
||||
|
||||
# -- cell commands ----------------------------------------------------------
|
||||
|
||||
def run_cells(self, cell_ids: list[str]) -> dict:
|
||||
"""Queue cells to run (lazy mode: their dependents turn stale)."""
|
||||
return self.execute(_driver("\n".join(f" ctx.run_cell({cell_id!r})" for cell_id in cell_ids)))
|
||||
|
||||
def edit_cell(self, cell_id: str, code: str) -> dict:
|
||||
"""Replace a cell's code (persisted to the file) and run it."""
|
||||
return self.execute(
|
||||
"import json as _json\n"
|
||||
f"__code = _json.loads({json.dumps(json.dumps(code))})\n"
|
||||
+ _driver(f" ctx.edit_cell({cell_id!r}, code=__code)\n ctx.run_cell({cell_id!r})")
|
||||
)
|
||||
|
||||
def delete_cell(self, cell_id: str) -> dict:
|
||||
return self.execute(_driver(f" ctx.delete_cell({cell_id!r})"))
|
||||
|
||||
def insert_cell(self, after: str | None) -> dict:
|
||||
"""Insert one empty, named cell after *after* (at the top if None).
|
||||
|
||||
The cell carries a comment placeholder — marimo's create_cell drops
|
||||
trailing cells when saving an EMPTY-code insertion — and is not
|
||||
executed.
|
||||
"""
|
||||
if after:
|
||||
create = f" ctx.create_cell('# new cell', after={after!r}, name=__name)\n"
|
||||
else:
|
||||
create = (
|
||||
" if __names:\n"
|
||||
" ctx.create_cell('# new cell', before=__names[0], name=__name)\n"
|
||||
" else:\n"
|
||||
" ctx.create_cell('# new cell', name=__name)\n"
|
||||
)
|
||||
return self.execute(
|
||||
_driver(
|
||||
" __names = [c.name for c in ctx.cells]\n"
|
||||
" __name = 'new_cell'\n"
|
||||
" __i = 1\n"
|
||||
" while __name in __names:\n"
|
||||
" __i += 1\n"
|
||||
" __name = f'new_cell_{__i}'\n" + create
|
||||
)
|
||||
)
|
||||
|
||||
def stale_cells(self) -> list[str]:
|
||||
"""Ids of the cells that need a run (inputs changed, code edited)."""
|
||||
result = self.execute(
|
||||
"import json as _json\n"
|
||||
"import marimo._code_mode as _cm\n"
|
||||
"_ids = []\n"
|
||||
"for _c in _cm.get_context().cells:\n"
|
||||
" _st = getattr(_c, 'status', None)\n"
|
||||
" if _c.name != 'setup' and getattr(_st, 'value', _st) == 'stale':\n"
|
||||
" _ids.append(_c.id)\n"
|
||||
"print('SCA-STALE', _json.dumps(_ids))\n"
|
||||
)
|
||||
for line in (result.get("log") or "").splitlines():
|
||||
if line.startswith("SCA-STALE "):
|
||||
try:
|
||||
return [str(item) for item in json.loads(line[len("SCA-STALE "):])]
|
||||
except json.JSONDecodeError:
|
||||
break
|
||||
return []
|
||||
|
||||
def wait_idle(self, timeout: float = 120.0) -> bool:
|
||||
"""Wait until no cell is queued or running; False on timeout.
|
||||
|
||||
``run_cell`` only awaits submission; the cells' state is final once
|
||||
the kernel goes idle. Poll with short scratch executes (never sleep
|
||||
inside the kernel itself).
|
||||
"""
|
||||
probe = (
|
||||
"import marimo._code_mode as _cm\n"
|
||||
"_busy = [c.name for c in _cm.get_context().cells"
|
||||
" if str(getattr(getattr(c, 'status', ''), 'value', getattr(c, 'status', ''))) in ('queued', 'running')]\n"
|
||||
"print('SCA-BUSY' if _busy else 'SCA-IDLE')\n"
|
||||
)
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if "SCA-IDLE" in (self.execute(probe, timeout=15).get("log") or ""):
|
||||
return True
|
||||
time.sleep(0.2)
|
||||
return False
|
||||
|
||||
def run_until_settled(self, cell_ids: list[str], *, rounds: int = 8) -> None:
|
||||
"""Run *cell_ids*, then every cell that turned stale, until none is.
|
||||
|
||||
Lazy mode marks a run cell's dependents stale instead of running
|
||||
them; a parameter change wants the whole chain, so follow up.
|
||||
"""
|
||||
if cell_ids:
|
||||
self.run_cells(cell_ids)
|
||||
self.wait_idle()
|
||||
for _ in range(rounds):
|
||||
stale = self.stale_cells()
|
||||
if not stale:
|
||||
return
|
||||
self.run_cells(stale)
|
||||
self.wait_idle()
|
||||
|
||||
def publish(self, url: str, step: str = "") -> dict:
|
||||
"""Have the kernel project its product and POST the package to *url*.
|
||||
|
||||
Returns ``{"ok": True, "id", "kind"}`` or ``{"ok": False, "error"}``;
|
||||
a notebook that has not produced its product yet is an error value,
|
||||
not an exception.
|
||||
"""
|
||||
result = self.execute(
|
||||
"from simplecadapi.runtime.live import publish_live as _publish\n"
|
||||
"try:\n"
|
||||
f" _p = _publish({url!r}, step={step!r})\n"
|
||||
" print('SCA-PUBLISHED', _p.definition_id, _p.definition_kind)\n"
|
||||
"except Exception as _e:\n"
|
||||
" print('SCA-PUBLISH-ERROR', type(_e).__name__ + ':', str(_e).splitlines()[0] if str(_e) else '')\n",
|
||||
timeout=180,
|
||||
)
|
||||
for line in (result.get("log") or "").splitlines():
|
||||
if line.startswith("SCA-PUBLISHED "):
|
||||
_, definition_id, kind = line.split(" ", 2)
|
||||
return {"ok": True, "id": definition_id, "kind": kind}
|
||||
if line.startswith("SCA-PUBLISH-ERROR "):
|
||||
return {"ok": False, "error": line[len("SCA-PUBLISH-ERROR "):]}
|
||||
return {"ok": False, "error": (result.get("log") or "publishing failed").strip()[-300:]}
|
||||
|
||||
# -- driving --------------------------------------------------------------------
|
||||
|
||||
def execute(self, code: str, timeout: float = 120.0) -> dict:
|
||||
"""Run a scratch snippet in the kernel; returns {success, output, log}."""
|
||||
self._own_calls += 1
|
||||
try:
|
||||
return self._execute(code, timeout)
|
||||
finally:
|
||||
self._own_ended = time.monotonic()
|
||||
self._own_calls -= 1
|
||||
|
||||
def _execute(self, code: str, timeout: float) -> dict:
|
||||
body = json.dumps({"code": code}).encode("utf-8")
|
||||
request = urllib.request.Request(
|
||||
f"{self.marimo_url}/api/kernel/execute",
|
||||
data=body,
|
||||
headers={"Content-Type": "application/json", "Marimo-Session-Id": SESSION_ID},
|
||||
method="POST",
|
||||
)
|
||||
result: dict = {"success": None, "output": "", "log": ""}
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
event = ""
|
||||
for raw in response:
|
||||
line = raw.decode("utf-8", "replace").rstrip("\r\n")
|
||||
if line.startswith("event:"):
|
||||
event = line[len("event:"):].strip()
|
||||
continue
|
||||
if not line.startswith("data:"):
|
||||
continue
|
||||
try:
|
||||
payload = json.loads(line[len("data:"):].strip())
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
if event == "stdout" and isinstance(payload.get("data"), str):
|
||||
result["log"] += payload["data"]
|
||||
elif event == "stderr" and isinstance(payload.get("data"), str):
|
||||
result["log"] += payload["data"]
|
||||
elif event == "done":
|
||||
result["success"] = bool(payload.get("success", False))
|
||||
output = (payload.get("output") or {}).get("data")
|
||||
if isinstance(output, str):
|
||||
result["output"] = output
|
||||
return result
|
||||
|
||||
# -- helpers ----------------------------------------------------------------------
|
||||
|
||||
def _post(self, path: str, payload: dict, timeout: float = 30.0) -> dict:
|
||||
body = json.dumps(payload).encode("utf-8")
|
||||
headers = {"Content-Type": "application/json", "Marimo-Session-Id": SESSION_ID}
|
||||
if self._token is not None:
|
||||
headers["Marimo-Server-Token"] = self._token
|
||||
request = urllib.request.Request(
|
||||
f"{self.marimo_url}{path}", data=body, headers=headers, method="POST"
|
||||
)
|
||||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||||
data = response.read()
|
||||
return json.loads(data) if data else {}
|
||||
|
||||
|
||||
def _driver(inner: str) -> str:
|
||||
"""A scratch snippet running *inner* (indented lines) in a code-mode batch."""
|
||||
return "import marimo._code_mode as cm\nasync with cm.get_context() as ctx:\n" + inner + "\n"
|
||||
|
||||
|
||||
def _free_port(start: int) -> int:
|
||||
for port in range(start, start + 32):
|
||||
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
||||
try:
|
||||
sock.bind(("127.0.0.1", port))
|
||||
except OSError:
|
||||
continue
|
||||
return port
|
||||
raise KernelError(f"no free port at or above {start}")
|
||||
@@ -0,0 +1,769 @@
|
||||
"""The editor server: webui static files + WS hub + the workspace's marimo kernel.
|
||||
|
||||
This is the ``sca edit <workspace>`` application. The workspace is a plain
|
||||
directory of SimpleCAD notebooks (:mod:`simplecadapi.runtime.workspace`).
|
||||
The server hosts a marimo kernel for one notebook at a time
|
||||
(:mod:`.kernel`); the kernel runs the notebook with the same executor
|
||||
``sca run`` uses. When the cells settle — whoever ran them — the server
|
||||
asks the kernel for the product's package (``publish_live``), keeps the
|
||||
bytes, and tells the webuis. Commands from the webui are translated into
|
||||
kernel cell operations; parameter values the webui sets are saved where the
|
||||
kernel executor applies them (:mod:`simplecadapi.runtime.params`), so
|
||||
marimo's own dataflow reruns exactly the cells that read them.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import webbrowser
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import uvicorn
|
||||
from starlette.applications import Starlette
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import FileResponse, JSONResponse, Response
|
||||
from starlette.routing import Route, WebSocketRoute
|
||||
from starlette.staticfiles import StaticFiles
|
||||
from starlette.websockets import WebSocketDisconnect
|
||||
|
||||
from ..runtime.cells import cell_keys
|
||||
from ..runtime.config import NotebookConfig, read_notebook_config
|
||||
from ..runtime.params import (
|
||||
ParamSpec,
|
||||
commit_value,
|
||||
parameters_in_cell,
|
||||
read_saved_params,
|
||||
write_saved_params,
|
||||
)
|
||||
from ..runtime.workspace import features_in_cell, scan_workspace
|
||||
from .kernel import MarimoKernel
|
||||
from .templates import create_notebook
|
||||
from .ws import WsHub
|
||||
|
||||
|
||||
def _webui_dir() -> Path:
|
||||
"""The built webui: ``editor-web`` builds into the package directory
|
||||
(``npm run build``), and the wheel ships it from there."""
|
||||
return Path(__file__).resolve().parent / "webui"
|
||||
|
||||
|
||||
DIST_DIR = _webui_dir()
|
||||
|
||||
|
||||
def pick_notebook(workspace: Path, prefer: Path | None = None) -> Path | None:
|
||||
"""The notebook to open first: the one asked for, else the product.
|
||||
|
||||
Without a request that is the first assembly nothing else uses (the
|
||||
top of the product), else the first notebook.
|
||||
"""
|
||||
if prefer is not None and prefer.is_file():
|
||||
return prefer.resolve()
|
||||
entries = scan_workspace(workspace)
|
||||
if not entries:
|
||||
return None
|
||||
used = {use for entry in entries for use in entry.uses}
|
||||
tops = [e for e in entries if e.kind == "assembly" and e.path not in used]
|
||||
chosen = (tops or entries)[0]
|
||||
return (workspace / chosen.path).resolve()
|
||||
|
||||
|
||||
class WorkspaceState:
|
||||
"""Shared server state: hub + kernel + workspace info + latest envelopes.
|
||||
|
||||
A webui that connects (or refreshes) later must still see the current
|
||||
model, so the latest envelope per type is cached and replayed.
|
||||
|
||||
Parameter bursts collapse: while one rebuild is in flight, newer values
|
||||
accumulate in ``_pending_params`` and exactly one follow-up rebuild runs
|
||||
with the merged latest values ("latest wins").
|
||||
"""
|
||||
|
||||
# Envelope types worth replaying, in replay order. "package" is a light
|
||||
# revision event; the bytes themselves live on /api/package/latest.
|
||||
_REPLAYED = (
|
||||
"notebook.cells",
|
||||
"notebook.features",
|
||||
"params.schema",
|
||||
"params.values",
|
||||
"package",
|
||||
"selection",
|
||||
)
|
||||
|
||||
def __init__(self, workspace: Path, notebook: Path | None = None) -> None:
|
||||
self.workspace = workspace.expanduser().resolve()
|
||||
self.hub = WsHub()
|
||||
self.kernel: MarimoKernel | None = None
|
||||
self.notebook: Path | None = pick_notebook(self.workspace, notebook)
|
||||
self.port = 0
|
||||
self.lock = threading.Lock()
|
||||
self.latest: dict[str, dict] = {}
|
||||
self.latest_package_bytes: bytes | None = None
|
||||
self.package_revision = 0
|
||||
self.selection: dict = {}
|
||||
self.cells: list[dict] = []
|
||||
self.specs: dict[str, ParamSpec] = {}
|
||||
self._pending_params: dict[str, float | int | bool] = {}
|
||||
self._rebuild_inflight = False
|
||||
self._rebuild_cond = threading.Condition()
|
||||
# One rebuild per interval; later slider batches keep merging.
|
||||
self._rebuild_min_interval = 0.35
|
||||
self._last_rebuild_at = 0.0
|
||||
self._children: dict[Path, int] = {}
|
||||
self._settle_timer: threading.Timer | None = None
|
||||
self._settle_lock = threading.Lock()
|
||||
self._last_publish_error = ""
|
||||
|
||||
# -- notebook / kernel lifecycle ---------------------------------------------
|
||||
|
||||
@property
|
||||
def config(self) -> NotebookConfig | None:
|
||||
return read_notebook_config(self.notebook) if self.notebook else None
|
||||
|
||||
def open_notebook(self, rel_path: str) -> None:
|
||||
"""Switch the active notebook: restart the kernel on it.
|
||||
|
||||
Runs synchronously (the caller wraps it in a thread): marimo boot
|
||||
takes seconds.
|
||||
"""
|
||||
target = (self.workspace / rel_path).resolve()
|
||||
if not target.is_file() or self.workspace not in target.parents:
|
||||
raise ValueError(f"notebook outside workspace: {rel_path}")
|
||||
if read_notebook_config(target) is None:
|
||||
raise ValueError(f"not a SimpleCAD notebook (no [tool.simplecadapi]): {rel_path}")
|
||||
self.start_kernel(target)
|
||||
|
||||
def start_kernel(self, notebook: Path) -> None:
|
||||
"""Boot a marimo kernel for *notebook*, adopt it, and publish its product.
|
||||
|
||||
Shared by server boot, open_notebook, and the auto-heal watch.
|
||||
"""
|
||||
with self.lock:
|
||||
old = self.kernel
|
||||
self.kernel = None
|
||||
if old is not None:
|
||||
old.stop()
|
||||
kernel = MarimoKernel(notebook, server_port=self.port, on_run_complete=self.schedule_settle)
|
||||
kernel.start()
|
||||
with self.lock:
|
||||
self.kernel = kernel
|
||||
self.notebook = notebook
|
||||
# Envelopes from the previous model must not replay.
|
||||
self.latest.clear()
|
||||
self.latest_package_bytes = None
|
||||
self.selection = {}
|
||||
self.cells = []
|
||||
self.specs = {}
|
||||
self._last_publish_error = ""
|
||||
self._children = self._child_mtimes()
|
||||
self.hub.broadcast(self.hello())
|
||||
kernel.wait_idle()
|
||||
self.settle()
|
||||
threading.Thread(
|
||||
target=self._watch_children, args=(kernel,), name="child-watch", daemon=True
|
||||
).start()
|
||||
|
||||
def watch_kernel(self) -> None:
|
||||
"""Auto-heal: the marimo python session can die on crashes or
|
||||
external file edits while the marimo SERVER process stays alive
|
||||
(`kernel.alive` is blind to that). Probe the session with scratch
|
||||
pings; two consecutive failures mean the session is gone — restart.
|
||||
"""
|
||||
failures = 0
|
||||
while True:
|
||||
time.sleep(5)
|
||||
kernel = self.kernel
|
||||
if kernel is None or kernel._stop.is_set():
|
||||
return
|
||||
if not kernel.alive:
|
||||
self.hub.broadcast({"type": "status", "error": "marimo server exited — restarting kernel"})
|
||||
break
|
||||
try:
|
||||
result = kernel.execute("print('sca-ping')", timeout=10)
|
||||
failures = failures + 1 if result.get("success") is False else 0
|
||||
except Exception:
|
||||
failures += 1
|
||||
if failures >= 2:
|
||||
self.hub.broadcast({"type": "status", "error": "kernel session lost — restarting"})
|
||||
break
|
||||
try:
|
||||
assert self.notebook is not None
|
||||
self.start_kernel(self.notebook)
|
||||
self.hub.broadcast({"type": "status", "recovered": self.notebook.name})
|
||||
except Exception as exc:
|
||||
self.hub.broadcast({"type": "status", "error": f"kernel restart failed: {exc}"})
|
||||
|
||||
# -- child notebooks ---------------------------------------------------------
|
||||
|
||||
def _child_mtimes(self) -> dict[Path, int]:
|
||||
"""Modification times of the notebooks this one runs with ``use``.
|
||||
|
||||
``use`` runs a child headless, outside the kernel's dataflow, so
|
||||
marimo never sees an edit to it; the editor does, and reruns the
|
||||
cells that call ``use`` (the children's own cache, keyed by their
|
||||
files, decides what is rebuilt).
|
||||
"""
|
||||
if self.notebook is None:
|
||||
return {}
|
||||
entries = {entry.path: entry for entry in scan_workspace(self.workspace)}
|
||||
start = self.notebook.relative_to(self.workspace).as_posix()
|
||||
seen: set[str] = set()
|
||||
pending = list(entries[start].uses) if start in entries else []
|
||||
while pending:
|
||||
path = pending.pop()
|
||||
if path in seen:
|
||||
continue
|
||||
seen.add(path)
|
||||
if path in entries:
|
||||
pending.extend(entries[path].uses)
|
||||
mtimes: dict[Path, int] = {}
|
||||
for path in seen:
|
||||
try:
|
||||
mtimes[self.workspace / path] = (self.workspace / path).stat().st_mtime_ns
|
||||
except OSError:
|
||||
mtimes[self.workspace / path] = 0
|
||||
return mtimes
|
||||
|
||||
def _watch_children(self, kernel: MarimoKernel) -> None:
|
||||
while not kernel._stop.is_set():
|
||||
time.sleep(1.0)
|
||||
if self.kernel is not kernel:
|
||||
return
|
||||
try:
|
||||
current = self._child_mtimes()
|
||||
if current == self._children:
|
||||
continue
|
||||
self._children = current
|
||||
uses = [cell["id"] for cell in self.cells if "use(" in cell["code"]]
|
||||
if uses:
|
||||
kernel.run_until_settled(uses)
|
||||
self.schedule_settle()
|
||||
except Exception as exc:
|
||||
self.hub.broadcast({"type": "status", "error": f"child refresh failed: {str(exc)[-200:]}"})
|
||||
|
||||
def remember(self, envelope: dict) -> None:
|
||||
if envelope.get("type") in self._REPLAYED:
|
||||
self.latest[envelope["type"]] = envelope
|
||||
|
||||
def emit(self, envelope: dict) -> None:
|
||||
self.remember(envelope)
|
||||
self.hub.broadcast(envelope)
|
||||
|
||||
def replay(self) -> list[dict]:
|
||||
return [self.latest[key] for key in self._REPLAYED if key in self.latest]
|
||||
|
||||
def hello(self) -> dict:
|
||||
return {
|
||||
"type": "hello",
|
||||
"workspace": str(self.workspace),
|
||||
"notebook": self.notebook.name if self.notebook else None,
|
||||
"kernel": self.kernel is not None and self.kernel.alive,
|
||||
"marimo_url": self.kernel.marimo_url if self.kernel else None,
|
||||
}
|
||||
|
||||
# -- settling: the cells ran; publish what they made -----------------------
|
||||
|
||||
def schedule_settle(self) -> None:
|
||||
"""A batch of cell runs ended: settle once the activity calms down."""
|
||||
with self._settle_lock:
|
||||
if self._settle_timer is not None:
|
||||
self._settle_timer.cancel()
|
||||
self._settle_timer = threading.Timer(0.4, self._settle_in_thread)
|
||||
self._settle_timer.daemon = True
|
||||
self._settle_timer.start()
|
||||
|
||||
def _settle_in_thread(self) -> None:
|
||||
try:
|
||||
self.settle()
|
||||
except Exception as exc: # never let a timer thread die silently
|
||||
self.hub.broadcast({"type": "status", "error": str(exc)[-300:]})
|
||||
|
||||
def settle(self) -> None:
|
||||
"""Push the cells, features and parameters, then the product package."""
|
||||
kernel = self.kernel
|
||||
if kernel is None:
|
||||
return
|
||||
with self._settle_lock:
|
||||
self.push_cells()
|
||||
result = kernel.publish(self.package_url, step=self.notebook.stem if self.notebook else "")
|
||||
if result.get("ok"):
|
||||
self._last_publish_error = ""
|
||||
return
|
||||
message = str(result.get("error", ""))
|
||||
# A notebook mid-edit has no product yet; say so once, not per run.
|
||||
if message != self._last_publish_error:
|
||||
self._last_publish_error = message
|
||||
self.hub.broadcast({"type": "status", "error": message[-300:]})
|
||||
|
||||
@property
|
||||
def package_url(self) -> str:
|
||||
return f"http://127.0.0.1:{self.port}/api/runtime/package"
|
||||
|
||||
def push_cells(self) -> None:
|
||||
"""Broadcast the cells, their feature headers and the parameters."""
|
||||
kernel = self.kernel
|
||||
if kernel is None:
|
||||
return
|
||||
cells = kernel.list_cells()
|
||||
keys = cell_keys(cell["code"] for cell in cells)
|
||||
features: list[dict] = []
|
||||
specs: list[ParamSpec] = []
|
||||
for cell, key in zip(cells, keys):
|
||||
cell["key"] = key
|
||||
found = features_in_cell(cell["code"], key)
|
||||
cell["feature"] = found[0].slug if found else None
|
||||
features.extend(
|
||||
{"cell": cell["id"], "label": feature.slug, "kind": feature.role or "feature"}
|
||||
for feature in found
|
||||
)
|
||||
specs.extend(
|
||||
ParamSpec(**{**spec.__dict__, "cell": cell["id"]})
|
||||
for spec in parameters_in_cell(cell["code"], key)
|
||||
)
|
||||
self.cells = cells
|
||||
self.specs = {spec.name: spec for spec in specs}
|
||||
self.emit({"type": "notebook.cells", "cells": cells})
|
||||
self.emit({"type": "notebook.features", "features": features})
|
||||
self.emit_params()
|
||||
|
||||
def emit_params(self) -> None:
|
||||
config = self.config
|
||||
saved = read_saved_params(config) if config is not None else {}
|
||||
variables = []
|
||||
for spec in self.specs.values():
|
||||
row = spec.to_dict()
|
||||
row["id"] = spec.name
|
||||
row["value"] = saved.get(spec.name, spec.default)
|
||||
row["modified"] = spec.name in saved and saved[spec.name] != spec.default
|
||||
variables.append(row)
|
||||
self.emit({"type": "params.schema", "vars": variables})
|
||||
self.emit({"type": "params.values", "values": {row["id"]: row["value"] for row in variables}})
|
||||
|
||||
# -- webui command -> kernel operation ---------------------------------------
|
||||
|
||||
def dispatch_command(self, message: dict) -> dict:
|
||||
"""Translate one ui command into kernel operations. Returns an ack."""
|
||||
kernel = self.kernel
|
||||
if kernel is None:
|
||||
return {"type": "error", "message": "no kernel"}
|
||||
kind = message.get("type")
|
||||
if kind == "param.set":
|
||||
self._enqueue_params(kernel, dict(message.get("values", {})))
|
||||
return {"type": "ack", "command": kind}
|
||||
if kind == "export.request":
|
||||
self._export()
|
||||
return {"type": "ack", "command": kind}
|
||||
if kind in ("param.commit", "param.revert"):
|
||||
names = [str(name) for name in message.get("names", [])] or list(self.specs)
|
||||
self._in_thread(lambda: self._commit(kernel, names, revert=kind == "param.revert"))
|
||||
return {"type": "ack", "command": kind}
|
||||
|
||||
cell = str(message.get("cell") or "")
|
||||
if kind == "rerun.request":
|
||||
# Header rerun (no cell) refreshes the whole notebook; a per-cell
|
||||
# rerun runs that cell and leaves its dependents stale.
|
||||
ids = [cell] if cell else [c["id"] for c in self.cells]
|
||||
action = lambda: kernel.run_cells(ids) # noqa: E731
|
||||
elif kind == "insert.request":
|
||||
after = message.get("after")
|
||||
action = lambda: kernel.insert_cell(str(after) if after else None) # noqa: E731
|
||||
elif kind == "rollback.request":
|
||||
# Delete the cell (persisted to the file); marimo marks what read
|
||||
# its variables stale.
|
||||
action = lambda: kernel.delete_cell(cell) # noqa: E731
|
||||
elif kind == "code.edit":
|
||||
code = _module_code(str(message.get("code", "")))
|
||||
action = lambda: kernel.edit_cell(cell, code) # noqa: E731
|
||||
else:
|
||||
return {"type": "error", "message": f"unknown command: {kind}"}
|
||||
|
||||
def run() -> None:
|
||||
result = action()
|
||||
if result.get("success") is False:
|
||||
self.hub.broadcast(
|
||||
{"type": "status", "error": (result.get("log") or "kernel command failed")[-400:]}
|
||||
)
|
||||
kernel.wait_idle()
|
||||
# The kernel reports a completed run for these too, but settle
|
||||
# even when it reported failure: the edit may have applied and
|
||||
# the error state is what the notebook UI must show.
|
||||
self.schedule_settle()
|
||||
|
||||
self._in_thread(run)
|
||||
return {"type": "ack", "command": kind}
|
||||
|
||||
def _in_thread(self, work: Any) -> None:
|
||||
def run() -> None:
|
||||
try:
|
||||
work()
|
||||
except Exception as exc: # surface, never crash the WS handler
|
||||
self.hub.broadcast({"type": "status", "error": str(exc)[-400:]})
|
||||
|
||||
threading.Thread(target=run, name="kernel-command", daemon=True).start()
|
||||
|
||||
# -- parameters --------------------------------------------------------------
|
||||
|
||||
def _clean_params(self, values: dict) -> dict[str, float | int | bool]:
|
||||
"""Keep the values that name a parameter, clamped and typed to it."""
|
||||
clean: dict[str, float | int | bool] = {}
|
||||
for name, raw in values.items():
|
||||
spec = self.specs.get(str(name))
|
||||
if spec is None or isinstance(raw, str):
|
||||
continue
|
||||
if spec.kind == "bool":
|
||||
clean[spec.name] = bool(raw)
|
||||
continue
|
||||
if isinstance(raw, bool):
|
||||
continue
|
||||
number = float(raw)
|
||||
if spec.min is not None:
|
||||
number = max(spec.min, number)
|
||||
if spec.max is not None:
|
||||
number = min(spec.max, number)
|
||||
clean[spec.name] = int(round(number)) if spec.kind == "int" else number
|
||||
return clean
|
||||
|
||||
def _enqueue_params(self, kernel: MarimoKernel, values: dict) -> None:
|
||||
"""Coalesce slider bursts: at most one rebuild in flight; newer values
|
||||
always win; one follow-up rebuild per settled gesture."""
|
||||
clean = self._clean_params(values)
|
||||
if not clean:
|
||||
return
|
||||
with self._rebuild_cond:
|
||||
self._pending_params.update(clean)
|
||||
threading.Thread(target=self._rebuild_loop, args=(kernel,), name="param-rebuild", daemon=True).start()
|
||||
|
||||
def _rebuild_loop(self, kernel: MarimoKernel) -> None:
|
||||
with self._rebuild_cond:
|
||||
if self._rebuild_inflight:
|
||||
return # the running loop will pick up our pending values
|
||||
self._rebuild_inflight = True
|
||||
try:
|
||||
while True:
|
||||
with self._rebuild_cond:
|
||||
if not self._pending_params:
|
||||
return
|
||||
partial = dict(self._pending_params)
|
||||
self._pending_params.clear()
|
||||
since = time.monotonic() - self._last_rebuild_at
|
||||
if since < self._rebuild_min_interval:
|
||||
time.sleep(self._rebuild_min_interval - since)
|
||||
self._last_rebuild_at = time.monotonic()
|
||||
try:
|
||||
self._apply_params(kernel, partial)
|
||||
except Exception as exc:
|
||||
self.hub.broadcast({"type": "status", "error": str(exc)[-400:]})
|
||||
finally:
|
||||
with self._rebuild_cond:
|
||||
self._rebuild_inflight = False
|
||||
|
||||
def _apply_params(self, kernel: MarimoKernel, values: dict[str, float | int | bool]) -> None:
|
||||
"""Save the values, then run the cells that declare them.
|
||||
|
||||
The kernel executor puts the saved values in place as those cells
|
||||
finish; marimo's dataflow marks what reads them stale, and
|
||||
``run_until_settled`` runs exactly that.
|
||||
"""
|
||||
config = self.config
|
||||
if config is None:
|
||||
raise RuntimeError("no SimpleCAD notebook is open")
|
||||
saved = read_saved_params(config)
|
||||
cells: list[str] = []
|
||||
for name, value in values.items():
|
||||
spec = self.specs[name]
|
||||
if value == spec.default:
|
||||
saved.pop(name, None) # back at the source value
|
||||
else:
|
||||
saved[name] = value
|
||||
if spec.cell not in cells:
|
||||
cells.append(spec.cell)
|
||||
write_saved_params(config, saved)
|
||||
self.emit_params()
|
||||
kernel.run_until_settled(cells)
|
||||
self.schedule_settle()
|
||||
|
||||
def _commit(self, kernel: MarimoKernel, names: list[str], *, revert: bool) -> None:
|
||||
"""Write saved values into the notebook source, or drop them."""
|
||||
config = self.config
|
||||
if config is None:
|
||||
return
|
||||
saved = read_saved_params(config)
|
||||
names = [name for name in names if name in saved]
|
||||
if not names:
|
||||
return
|
||||
if not revert:
|
||||
codes = {cell["id"]: cell["code"] for cell in self.cells}
|
||||
changed: dict[str, str] = {}
|
||||
for name in names:
|
||||
spec = self.specs.get(name)
|
||||
if spec is None:
|
||||
continue
|
||||
code = commit_value(changed.get(spec.cell, codes[spec.cell]), name, saved[name])
|
||||
if code is None:
|
||||
self.hub.broadcast({"type": "status", "error": f"cannot write {name} into the source"})
|
||||
return
|
||||
changed[spec.cell] = code
|
||||
for cell_id, code in changed.items():
|
||||
kernel.edit_cell(cell_id, code)
|
||||
kernel.wait_idle()
|
||||
for name in names:
|
||||
saved.pop(name, None)
|
||||
write_saved_params(config, saved)
|
||||
if revert:
|
||||
kernel.run_until_settled([self.specs[name].cell for name in names if name in self.specs])
|
||||
self.schedule_settle()
|
||||
|
||||
# -- export ------------------------------------------------------------------
|
||||
|
||||
def _export(self) -> None:
|
||||
"""Write the latest package next to the notebook: ``out/<stem>.scadpkg``."""
|
||||
if not self.latest_package_bytes or self.notebook is None:
|
||||
self.hub.broadcast({"type": "status", "error": "nothing to export yet"})
|
||||
return
|
||||
target = self.notebook.parent / "out" / f"{self.notebook.stem}.scadpkg"
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(self.latest_package_bytes)
|
||||
self.hub.broadcast({"type": "status", "exported": str(target)})
|
||||
|
||||
|
||||
def _module_code(code: str) -> str:
|
||||
"""marimo's code_mode compiles cell code as a MODULE: a top-level
|
||||
``return`` (normal in marimo's file format) is a SyntaxError there.
|
||||
Strip it — the returned expression stays in place and becomes the cell
|
||||
output, which is semantically equivalent."""
|
||||
lines: list[str] = []
|
||||
for line in code.splitlines():
|
||||
stripped = line.lstrip()
|
||||
indent = line[: len(line) - len(stripped)]
|
||||
if stripped == "return":
|
||||
lines.append(f"{indent}pass")
|
||||
elif stripped.startswith("return "):
|
||||
lines.append(f"{indent}{stripped[len('return '):].strip()}")
|
||||
else:
|
||||
lines.append(line)
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def create_app(state: WorkspaceState) -> Starlette:
|
||||
hub = state.hub
|
||||
|
||||
async def health(request: Request) -> JSONResponse:
|
||||
return JSONResponse(
|
||||
{
|
||||
"ok": True,
|
||||
"workspace": str(state.workspace),
|
||||
"notebook": state.notebook.name if state.notebook else None,
|
||||
"kernel": state.kernel is not None and state.kernel.alive,
|
||||
}
|
||||
)
|
||||
|
||||
async def push_package(request: Request) -> JSONResponse:
|
||||
"""The kernel hands over the fresh in-memory scadpkg bytes.
|
||||
|
||||
The bytes are cached for late webuis and agents; webuis only get a
|
||||
lightweight revision event and fetch bytes on demand.
|
||||
"""
|
||||
body = await request.body()
|
||||
if not body:
|
||||
return JSONResponse({"ok": False, "error": "empty package"}, status_code=400)
|
||||
state.latest_package_bytes = bytes(body)
|
||||
state.package_revision += 1
|
||||
state.emit(
|
||||
{
|
||||
"type": "package",
|
||||
"revision": state.package_revision,
|
||||
"step": request.headers.get("X-Live-Step", ""),
|
||||
"name": state.notebook.stem if state.notebook else None,
|
||||
"size": len(body),
|
||||
}
|
||||
)
|
||||
# The model is fine again: clear a stale "no product yet" message.
|
||||
hub.broadcast({"type": "status", "error": ""})
|
||||
return JSONResponse({"ok": True, "revision": state.package_revision})
|
||||
|
||||
async def latest_package(request: Request) -> Response:
|
||||
"""The freshest scadpkg bytes."""
|
||||
if state.latest_package_bytes:
|
||||
return Response(
|
||||
content=state.latest_package_bytes,
|
||||
media_type="application/vnd.simplecad.scadpkg",
|
||||
headers={"Content-Disposition": 'inline; filename="latest.scadpkg"'},
|
||||
)
|
||||
return JSONResponse({"error": "no package published yet"}, status_code=404)
|
||||
|
||||
async def workspace_list(request: Request) -> JSONResponse:
|
||||
"""The SimpleCAD notebooks of the workspace."""
|
||||
current = state.notebook.relative_to(state.workspace).as_posix() if state.notebook else None
|
||||
rows = [
|
||||
{
|
||||
"name": Path(entry.path).stem,
|
||||
"path": entry.path,
|
||||
"entry": True,
|
||||
"kind": entry.kind,
|
||||
"id": entry.id,
|
||||
"uses": list(entry.uses),
|
||||
"current": entry.path == current,
|
||||
"error": entry.error,
|
||||
}
|
||||
for entry in scan_workspace(state.workspace)
|
||||
]
|
||||
return JSONResponse({"notebooks": rows})
|
||||
|
||||
async def workspace_open(request: Request) -> JSONResponse:
|
||||
"""Switch the active notebook (restarts the kernel)."""
|
||||
try:
|
||||
message = json.loads(await request.body())
|
||||
rel_path = str(message["path"])
|
||||
except Exception:
|
||||
return JSONResponse({"ok": False, "error": "body must be {path}"}, status_code=400)
|
||||
|
||||
def run() -> None:
|
||||
try:
|
||||
state.open_notebook(rel_path)
|
||||
except Exception as exc:
|
||||
hub.broadcast({"type": "status", "error": f"open failed: {exc}"})
|
||||
|
||||
threading.Thread(target=run, name="notebook-open", daemon=True).start()
|
||||
return JSONResponse({"ok": True, "opening": rel_path})
|
||||
|
||||
async def workspace_new(request: Request) -> JSONResponse:
|
||||
"""Write a new notebook from a template, then open it."""
|
||||
try:
|
||||
message = json.loads(await request.body())
|
||||
path = create_notebook(
|
||||
state.workspace, str(message["name"]), str(message.get("kind", "part"))
|
||||
)
|
||||
except (FileExistsError, ValueError) as exc:
|
||||
return JSONResponse({"ok": False, "error": str(exc)}, status_code=400)
|
||||
rel_path = path.relative_to(state.workspace).as_posix()
|
||||
|
||||
def run() -> None:
|
||||
try:
|
||||
state.open_notebook(rel_path)
|
||||
hub.broadcast({"type": "status", "created": rel_path})
|
||||
except Exception as exc:
|
||||
hub.broadcast({"type": "status", "error": f"open failed: {exc}"})
|
||||
|
||||
threading.Thread(target=run, name="notebook-new", daemon=True).start()
|
||||
return JSONResponse({"ok": True, "created": rel_path})
|
||||
|
||||
async def studio_select(request: Request) -> JSONResponse:
|
||||
"""Webui reports the viewport selection; agents read it back."""
|
||||
try:
|
||||
message = json.loads(await request.body())
|
||||
except (json.JSONDecodeError, UnicodeDecodeError):
|
||||
return JSONResponse({"ok": False, "error": "invalid json"}, status_code=400)
|
||||
state.selection = message if isinstance(message, dict) else {"value": message}
|
||||
state.emit({"type": "selection", **state.selection})
|
||||
return JSONResponse({"ok": True})
|
||||
|
||||
async def studio_selected(request: Request) -> JSONResponse:
|
||||
"""Agent-facing read: what does the human have selected right now?"""
|
||||
return JSONResponse({"selected": state.selection, "notebook": state.notebook.name if state.notebook else None})
|
||||
|
||||
async def ws_endpoint(websocket) -> None:
|
||||
await hub.connect(websocket)
|
||||
await websocket.send_json(state.hello())
|
||||
for envelope in state.replay():
|
||||
await websocket.send_json(envelope)
|
||||
try:
|
||||
while True:
|
||||
message = await websocket.receive_json()
|
||||
try:
|
||||
if isinstance(message, dict) and str(message.get("type", "")).endswith(
|
||||
(".set", ".request", ".edit", ".commit", ".revert")
|
||||
):
|
||||
ack = await asyncio.to_thread(state.dispatch_command, message)
|
||||
await websocket.send_json(ack)
|
||||
else:
|
||||
await websocket.send_json({"type": "echo", "message": message})
|
||||
except Exception as exc: # one bad command must not kill the socket
|
||||
await websocket.send_json({"type": "error", "message": str(exc)[-300:]})
|
||||
except WebSocketDisconnect:
|
||||
hub.disconnect(websocket)
|
||||
|
||||
routes = [
|
||||
Route("/api/health", health),
|
||||
Route("/api/runtime/package", push_package, methods=["POST"]),
|
||||
Route("/api/package/latest", latest_package, methods=["GET"]),
|
||||
Route("/api/workspace", workspace_list, methods=["GET"]),
|
||||
Route("/api/workspace/open", workspace_open, methods=["POST"]),
|
||||
Route("/api/workspace/new", workspace_new, methods=["POST"]),
|
||||
Route("/api/studio/select", studio_select, methods=["POST"]),
|
||||
Route("/api/studio/selected", studio_selected, methods=["GET"]),
|
||||
WebSocketRoute("/ws", ws_endpoint),
|
||||
]
|
||||
app = Starlette(routes=routes)
|
||||
if DIST_DIR.is_dir():
|
||||
app.mount("/", StaticFiles(directory=DIST_DIR, html=True), name="webui")
|
||||
return app
|
||||
|
||||
|
||||
def serve_workspace(
|
||||
workspace: Path,
|
||||
*,
|
||||
host: str,
|
||||
port: int,
|
||||
open_browser: bool,
|
||||
notebook: Path | None = None,
|
||||
) -> int:
|
||||
workspace = workspace.expanduser().resolve()
|
||||
if not workspace.is_dir():
|
||||
print(f"[sca edit] workspace directory does not exist: {workspace}", file=sys.stderr)
|
||||
return 2
|
||||
|
||||
state = WorkspaceState(workspace, notebook)
|
||||
state.port = port
|
||||
app = create_app(state)
|
||||
config = uvicorn.Config(app, host=host, port=port, log_level="warning")
|
||||
server = uvicorn.Server(config)
|
||||
|
||||
original_startup = server.startup
|
||||
|
||||
async def startup(sockets=None):
|
||||
await original_startup(sockets)
|
||||
hub = state.hub
|
||||
hub.attach_loop(asyncio.get_running_loop())
|
||||
print(f"[sca edit] workspace {state.workspace}")
|
||||
|
||||
if state.notebook is None:
|
||||
print("[sca edit] no SimpleCAD notebook found in the workspace", file=sys.stderr)
|
||||
hub.broadcast({"type": "status", "error": "no SimpleCAD notebook in the workspace; create one"})
|
||||
else:
|
||||
def boot() -> None:
|
||||
try:
|
||||
assert state.notebook is not None
|
||||
state.start_kernel(state.notebook)
|
||||
except Exception as exc:
|
||||
print(f"[sca edit] kernel boot failed: {exc}", file=sys.stderr)
|
||||
hub.broadcast({"type": "status", "error": f"kernel boot failed: {exc}"})
|
||||
return
|
||||
kernel = state.kernel
|
||||
assert kernel is not None
|
||||
print(f"[sca edit] marimo kernel ready on {kernel.marimo_url}")
|
||||
state.watch_kernel()
|
||||
|
||||
threading.Thread(target=boot, name="kernel-boot", daemon=True).start()
|
||||
|
||||
print(f"[sca edit] serving http://{host}:{port}/")
|
||||
if open_browser:
|
||||
threading.Thread(
|
||||
target=webbrowser.open, args=(f"http://127.0.0.1:{port}/",), daemon=True
|
||||
).start()
|
||||
|
||||
server.startup = startup
|
||||
|
||||
original_shutdown = server.shutdown
|
||||
|
||||
async def shutdown(sockets=None):
|
||||
if state.kernel is not None:
|
||||
state.kernel.stop()
|
||||
await original_shutdown(sockets=sockets)
|
||||
|
||||
server.shutdown = shutdown
|
||||
server.run()
|
||||
return 0
|
||||
@@ -0,0 +1,135 @@
|
||||
"""New notebooks: a part or an assembly, as the editor's "new" action writes them.
|
||||
|
||||
Both follow the feature tree convention (``docs/skill/.../feature-tree-convention.md``):
|
||||
a ``# ---- params ----`` cell, one cell per feature, the product last.
|
||||
The parameters carry ``# ui:`` comments so the editor offers sliders.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
from ..runtime.workspace import scan_workspace
|
||||
|
||||
_HEADER = '''# /// script
|
||||
# requires-python = ">=3.10"
|
||||
# dependencies = ["simplecadapi"]
|
||||
#
|
||||
# [tool.simplecadapi]
|
||||
# id = "{id}"
|
||||
# revision = "1.0.0"
|
||||
# ///
|
||||
import marimo
|
||||
|
||||
app = marimo.App(width="medium")
|
||||
|
||||
with app.setup:
|
||||
import simplecadapi as scad
|
||||
'''
|
||||
|
||||
_PART = '''
|
||||
|
||||
@app.cell
|
||||
def _():
|
||||
# ---- params ----
|
||||
RADIUS = scad.var("radius", 25.0, comment="Radius", unit="mm") # ui: slider(5, 60, step=1, label="Radius")
|
||||
HEIGHT = scad.var("height", 10.0, comment="Height", unit="mm") # ui: slider(2, 40, step=1, label="Height")
|
||||
return HEIGHT, RADIUS
|
||||
|
||||
|
||||
@app.cell
|
||||
def _(HEIGHT, RADIUS):
|
||||
# ---- feature: base (build) ----
|
||||
base = scad.make_cylinder_rsolid(
|
||||
radius=RADIUS,
|
||||
height=HEIGHT,
|
||||
bottom_face_center=(0.0, 0.0, 0.0),
|
||||
axis=(0.0, 0.0, 1.0),
|
||||
)
|
||||
return (base,)
|
||||
|
||||
|
||||
@app.cell
|
||||
def _(base):
|
||||
{variable} = scad.Part(part_id=scad.notebook_id(), body=base)
|
||||
return ({variable},)
|
||||
'''
|
||||
|
||||
_ASSEMBLY = '''
|
||||
|
||||
@app.cell
|
||||
def _():
|
||||
# ---- feature: parts (add) ----
|
||||
{uses}
|
||||
return {names},
|
||||
|
||||
|
||||
@app.cell
|
||||
def _({names}):
|
||||
# ---- feature: layout (add) ----
|
||||
_assembly = scad.make_assembly_rassembly(
|
||||
assembly_id=scad.notebook_id(), name="{title}"
|
||||
)
|
||||
{components}
|
||||
{variable} = _assembly
|
||||
return ({variable},)
|
||||
'''
|
||||
|
||||
_RUNNER = '''
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run()
|
||||
'''
|
||||
|
||||
_NAME = re.compile(r"[A-Za-z_][A-Za-z0-9_-]*")
|
||||
|
||||
|
||||
def render_notebook(name: str, kind: str = "part", parts: list[tuple[str, str]] | None = None) -> str:
|
||||
"""The source of a new notebook called *name*.
|
||||
|
||||
An assembly lists the part notebooks it uses as ``(path, variable)``.
|
||||
"""
|
||||
if not _NAME.fullmatch(name):
|
||||
raise ValueError(f"invalid notebook name: {name!r}")
|
||||
variable = name.replace("-", "_")
|
||||
header = _HEADER.format(id=name)
|
||||
if kind == "part":
|
||||
return header + _PART.format(variable=variable) + _RUNNER
|
||||
if kind != "assembly":
|
||||
raise ValueError(f"unknown notebook kind: {kind}")
|
||||
if not parts:
|
||||
raise ValueError("an assembly uses part notebooks; create a part first")
|
||||
names = ", ".join(variable_name for _, variable_name in parts)
|
||||
uses = "\n".join(f' {variable_name} = scad.use("{path}")' for path, variable_name in parts)
|
||||
components = "\n".join(
|
||||
" _assembly = scad.add_component_rassembly(\n"
|
||||
f' assembly=_assembly, item={variable_name}, component_id="{variable_name}",\n'
|
||||
" placement=scad.identity_placement_rplacement(),\n"
|
||||
" )"
|
||||
for _, variable_name in parts
|
||||
)
|
||||
body = _ASSEMBLY.format(
|
||||
uses=uses, names=names, title=name, components=components, variable=variable
|
||||
)
|
||||
return header + body + _RUNNER
|
||||
|
||||
|
||||
def create_notebook(workspace: Path, name: str, kind: str = "part") -> Path:
|
||||
"""Write a new notebook into *workspace*; refuses to clobber a file."""
|
||||
if not _NAME.fullmatch(name):
|
||||
raise ValueError(f"invalid notebook name: {name!r}")
|
||||
root = workspace.resolve()
|
||||
path = root / f"{name}.py"
|
||||
if path.exists():
|
||||
raise FileExistsError(f"notebook already exists: {path}")
|
||||
parts: list[tuple[str, str]] = []
|
||||
if kind == "assembly":
|
||||
for entry in scan_workspace(root):
|
||||
if entry.kind == "part":
|
||||
# Relative to the new notebook, which sits at the workspace root.
|
||||
parts.append((entry.path, re.sub(r"\W", "_", Path(entry.path).stem)))
|
||||
if len(parts) == 2:
|
||||
break
|
||||
path.write_text(render_notebook(name, kind, parts), encoding="utf-8")
|
||||
return path
|
||||
@@ -0,0 +1,53 @@
|
||||
"""WebSocket hub: connection registry and JSON broadcast.
|
||||
|
||||
The runtime (server-side, possibly from a worker thread) pushes messages;
|
||||
every connected webui receives them. Delivery is fire-and-forget — the
|
||||
webui is a viewport, not a durable consumer.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
from typing import Any
|
||||
|
||||
from starlette.websockets import WebSocket
|
||||
|
||||
|
||||
class WsHub:
|
||||
def __init__(self) -> None:
|
||||
self._clients: set[WebSocket] = set()
|
||||
self._lock = asyncio.Lock()
|
||||
self._loop: asyncio.AbstractEventLoop | None = None
|
||||
|
||||
def attach_loop(self, loop: asyncio.AbstractEventLoop) -> None:
|
||||
"""Bind the running server loop so worker threads can push."""
|
||||
self._loop = loop
|
||||
|
||||
async def connect(self, websocket: WebSocket) -> None:
|
||||
await websocket.accept()
|
||||
async with self._lock:
|
||||
self._clients.add(websocket)
|
||||
|
||||
def disconnect(self, websocket: WebSocket) -> None:
|
||||
self._clients.discard(websocket)
|
||||
|
||||
def broadcast(self, message: dict[str, Any]) -> None:
|
||||
"""Push one JSON message to every connected client (thread-safe)."""
|
||||
self.broadcast_text(json.dumps(message, ensure_ascii=False))
|
||||
|
||||
def broadcast_text(self, text: str) -> None:
|
||||
"""Push one pre-serialized JSON frame to every client (thread-safe)."""
|
||||
loop = self._loop
|
||||
if loop is None or loop.is_closed():
|
||||
return
|
||||
asyncio.run_coroutine_threadsafe(self._send_all(text), loop)
|
||||
|
||||
async def _send_all(self, text: str) -> None:
|
||||
async with self._lock:
|
||||
clients = tuple(self._clients)
|
||||
for client in clients:
|
||||
try:
|
||||
await client.send_text(text)
|
||||
except Exception:
|
||||
self._clients.discard(client)
|
||||
@@ -0,0 +1,152 @@
|
||||
"""The editor's server-side logic and templates (no kernel is started).
|
||||
|
||||
An end-to-end run against a real marimo kernel is opt-in:
|
||||
``SCA_EDITOR_E2E=1 pytest test/test_editor.py``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
pytest.importorskip("starlette")
|
||||
|
||||
from simplecadapi.editor.server import WorkspaceState, _module_code, pick_notebook
|
||||
from simplecadapi.editor.templates import create_notebook, render_notebook
|
||||
from simplecadapi.runtime import run_notebook
|
||||
from simplecadapi.runtime.params import ParamSpec, parameters_in_cell
|
||||
|
||||
|
||||
def specs_of(code: str) -> dict[str, ParamSpec]:
|
||||
return {spec.name: spec for spec in parameters_in_cell(code)}
|
||||
|
||||
|
||||
class TemplatesTest(unittest.TestCase):
|
||||
def test_new_part_runs_and_offers_sliders(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path = create_notebook(Path(tmp), "bracket", "part")
|
||||
run = run_notebook(path)
|
||||
self.assertEqual(run.definition.definition_kind, "single_solid")
|
||||
self.assertEqual(run.definition.definition_id, "bracket")
|
||||
from simplecadapi.runtime.params import list_parameters
|
||||
|
||||
controls = {spec.name: spec.control for spec in list_parameters(path)}
|
||||
self.assertEqual(controls, {"RADIUS": "slider", "HEIGHT": "slider"})
|
||||
|
||||
def test_new_assembly_uses_the_workspace_parts(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
with self.assertRaisesRegex(ValueError, "create a part first"):
|
||||
create_notebook(root, "unit", "assembly")
|
||||
create_notebook(root, "bracket", "part")
|
||||
create_notebook(root, "pin-a", "part")
|
||||
path = create_notebook(root, "unit", "assembly")
|
||||
run = run_notebook(path)
|
||||
self.assertEqual(run.definition.definition_kind, "assembly")
|
||||
self.assertEqual(run.definition.definition_id, "unit")
|
||||
|
||||
def test_names_and_kinds_are_checked(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
for bad in ("", "1abc", "a b", "../x"):
|
||||
with self.assertRaises(ValueError):
|
||||
create_notebook(Path(tmp), bad)
|
||||
with self.assertRaises(ValueError):
|
||||
render_notebook("x", "gadget")
|
||||
create_notebook(Path(tmp), "once")
|
||||
with self.assertRaises(FileExistsError):
|
||||
create_notebook(Path(tmp), "once")
|
||||
|
||||
|
||||
class PickNotebookTest(unittest.TestCase):
|
||||
def test_prefers_the_asked_one_then_the_top_assembly(self) -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
self.assertIsNone(pick_notebook(root))
|
||||
create_notebook(root, "a-part", "part")
|
||||
create_notebook(root, "b-part", "part")
|
||||
self.assertEqual(pick_notebook(root), (root / "a-part.py").resolve())
|
||||
create_notebook(root, "top", "assembly")
|
||||
self.assertEqual(pick_notebook(root), (root / "top.py").resolve())
|
||||
self.assertEqual(pick_notebook(root, root / "b-part.py"), (root / "b-part.py").resolve())
|
||||
|
||||
|
||||
class ParamCleaningTest(unittest.TestCase):
|
||||
def state(self) -> WorkspaceState:
|
||||
state = WorkspaceState(Path(tempfile.gettempdir()))
|
||||
state.specs = specs_of(
|
||||
"# ---- params ----\n"
|
||||
"W = 20.0 # ui: slider(10, 40)\n"
|
||||
"N = 4 # ui: slider(2, 8)\n"
|
||||
"F = False\n"
|
||||
)
|
||||
return state
|
||||
|
||||
def test_values_are_clamped_and_typed(self) -> None:
|
||||
clean = self.state()._clean_params({"W": 99, "N": 3.6, "F": 1, "NOPE": 1})
|
||||
self.assertEqual(clean, {"W": 40.0, "N": 4, "F": True})
|
||||
self.assertIsInstance(clean["N"], int)
|
||||
|
||||
def test_wrong_kinds_are_dropped(self) -> None:
|
||||
self.assertEqual(self.state()._clean_params({"W": "7", "F": "yes"}), {})
|
||||
self.assertEqual(self.state()._clean_params({"N": True}), {})
|
||||
|
||||
|
||||
class ModuleCodeTest(unittest.TestCase):
|
||||
def test_top_level_return_is_stripped_for_code_mode(self) -> None:
|
||||
code = "x = 1\nif x:\n return\nreturn (x,)"
|
||||
self.assertEqual(_module_code(code), "x = 1\nif x:\n pass\n(x,)")
|
||||
|
||||
|
||||
@unittest.skipUnless(os.environ.get("SCA_EDITOR_E2E"), "set SCA_EDITOR_E2E=1 to boot a marimo kernel")
|
||||
class EditorEndToEndTest(unittest.TestCase):
|
||||
def test_slider_rebuilds_the_part_and_commit_writes_the_source(self) -> None:
|
||||
import threading
|
||||
|
||||
import uvicorn
|
||||
|
||||
from simplecadapi.editor.server import create_app
|
||||
from simplecadapi.runtime.params import read_saved_params
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
path = create_notebook(root, "bracket", "part")
|
||||
state = WorkspaceState(root)
|
||||
state.port = 17731
|
||||
app = create_app(state)
|
||||
server = uvicorn.Server(uvicorn.Config(app, 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)
|
||||
self.assertIn("RADIUS", state.specs)
|
||||
first = state.latest_package_bytes
|
||||
self.assertTrue(first)
|
||||
state.dispatch_command({"type": "param.set", "values": {"RADIUS": 40}})
|
||||
deadline = time.monotonic() + 90
|
||||
while state.latest_package_bytes == first and time.monotonic() < deadline:
|
||||
time.sleep(0.5)
|
||||
self.assertNotEqual(state.latest_package_bytes, first)
|
||||
self.assertEqual(read_saved_params(state.config), {"RADIUS": 40.0})
|
||||
state.dispatch_command({"type": "param.commit", "names": ["RADIUS"]})
|
||||
deadline = time.monotonic() + 60
|
||||
while "40.0" not in path.read_text() and time.monotonic() < deadline:
|
||||
time.sleep(0.5)
|
||||
self.assertIn('scad.var("radius", 40.0', path.read_text())
|
||||
self.assertEqual(read_saved_params(state.config), {})
|
||||
with urllib.request.urlopen(f"http://127.0.0.1:{state.port}/api/health") as response:
|
||||
self.assertTrue(json.load(response)["kernel"])
|
||||
finally:
|
||||
if state.kernel is not None:
|
||||
state.kernel.stop()
|
||||
server.should_exit = True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -3257,6 +3257,12 @@ dev = [
|
||||
drawing = [
|
||||
{ name = "pymupdf" },
|
||||
]
|
||||
editor = [
|
||||
{ name = "starlette" },
|
||||
{ name = "uvicorn" },
|
||||
{ name = "websockets", version = "16.1.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11'" },
|
||||
{ name = "websockets", version = "17.1", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11'" },
|
||||
]
|
||||
fem = [
|
||||
{ name = "ccx2paraview", extra = ["vtk"] },
|
||||
{ name = "gmsh" },
|
||||
@@ -3308,8 +3314,11 @@ requires-dist = [
|
||||
{ name = "pytest-cov", marker = "extra == 'dev'", specifier = ">=4.0" },
|
||||
{ name = "rfc8785", specifier = ">=0.1.4,<0.2.0" },
|
||||
{ name = "rich", specifier = ">=14.0.0" },
|
||||
{ name = "starlette", marker = "extra == 'editor'", specifier = ">=1.7.0" },
|
||||
{ name = "tomli", marker = "python_full_version < '3.11'", specifier = ">=2.0,<3" },
|
||||
{ name = "typing-extensions", specifier = ">=4.12,<5" },
|
||||
{ name = "uvicorn", marker = "extra == 'editor'", specifier = ">=0.54.0" },
|
||||
{ name = "websockets", marker = "extra == 'editor'", specifier = ">=16.1.1" },
|
||||
]
|
||||
provides-extras = ["dev", "drawing", "editor", "inspect", "whucad", "gmsh", "fem"]
|
||||
|
||||
|
||||
Reference in New Issue
Block a user