Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ Requires Node 22.12+. No Python, no other runtime.
```bash
npm i -g meshy-cli # installs `meshy` and `meshy-cli`
meshy doctor # checks the environment, no network
meshy view ./car.glb # opens the model in a 3D viewer in the browser, local only
```

The same build is published as [`@meshy-ai/cli`](https://www.npmjs.com/package/@meshy-ai/cli).
Expand Down
6 changes: 6 additions & 0 deletions assets/viewer-env.hdr

Large diffs are not rendered by default.

41 changes: 41 additions & 0 deletions docs/decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -1679,3 +1679,44 @@ behind it, and what a reviewer should check. IDs are stable; append, do not renu
- The transport's own rules are unchanged: it still follows no redirect and
refuses a URL outside its base. The proxy only carries the request, and for
`https:` URLs it sees a CONNECT tunnel, not the request.

## D-094 `meshy view` shows a local model in a browser viewer served on 127.0.0.1

- Agents deliver a `.glb`, but some hosts cannot show one: an editor tab may
only say "binary file", and a terminal has nothing to render with. Hosts with
a browser panel or a default browser can show a page. `view` turns a local
`.glb`/`.gltf` into that page. It is local only, with no API call and no
credential, so it is in `LOCAL_COMMANDS`.
- One server shows one model. `/` is the page, `/model.glb` (or
`/model.gltf`) is the file, and `/env.hdr` is the lighting environment. For a
`.gltf`, the buffers and textures beside it (`.bin`, `.png`, `.jpg`, `.jpeg`,
`.webp`, `.ktx2`) are also served, resolved with `realpath` and kept inside
the model's folder. Nothing else on disk is reachable: not the folder's
sidecars (which hold signed URLs), not other files, and not links out of the
folder. The server binds 127.0.0.1 and answers only GET and HEAD with a
`127.0.0.1` or `localhost` Host header, which blocks DNS rebinding. Its
responses carry no CORS headers, so other origins cannot read them.
- The page aims for a neutral studio look rather than a debug view: Neutral
tone mapping, a studio environment, a key light with a soft ground shadow,
fills scaled to the model, a 35° camera framing the bounds, and a dark radial
backdrop. The numbers live in `viewerPage()`, set so a white surface stays
below clipping. Post-processing (AO, bloom) is left out to keep the page
small. The first animation clip, if any, plays.
- An untextured preview often has no material and no normals. glTF's default
material is white and fully metallic, which reads as a flat, overexposed
shape, so a file without materials renders as matte grey clay. Missing
normals are computed (smooth), as glTF asks of the viewer.
- three.js and its addons come from jsDelivr at a pinned version, and the
import map carries each file's SRI hash. Bundling three.js would add about
1 MB to the package for one command. The environment map ships in the
package instead (`assets/viewer-env.hdr`, 512×256, about 0.5 MB), so the
lighting works wherever jsDelivr does. It is built from Poly Haven's CC0 "Decor Shop" by
`scripts/make-viewer-env.mjs`.
- `view` prints the envelope (`result.url`) once the server listens, then
keeps serving until Ctrl-C (exit 0) or 30 minutes without a request.
`--detach` starts the same server in a detached child, waits for its URL and
returns at once with `detached: true` and the child's `pid`. That is the form
an agent uses: one command, one URL to open in its browser panel.
`--no-open` skips the default browser (`MESHY_CLI_NO_BROWSER` does as well).
- Reviewer check: a new route must not widen what the server reads beyond the
one model and its own referenced files.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"types": "dist/index.d.ts",
"files": [
"dist",
"assets",
"README.md",
"LICENSE",
".env.example",
Expand Down
75 changes: 75 additions & 0 deletions scripts/make-viewer-env.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// Builds assets/viewer-env.hdr, the lighting environment `meshy view` ships.
//
// node scripts/make-viewer-env.mjs decor_shop_1k.hdr
//
// Source: Poly Haven "Decor Shop" (CC0), the 1k Radiance .hdr from
// https://polyhaven.com/a/decor_shop. It is halved to 512×256 (2×2 box filter;
// the viewer only lights with it, the background is hidden) and its saturation
// lowered by 45% for a neutral studio light. Written flat
// (no run-length encoding), which every Radiance reader accepts.
import { readFileSync, writeFileSync } from "node:fs";

const SATURATION = 0.55;
const src = readFileSync(process.argv[2]);

// Header: lines up to a blank one, then the resolution line.
let pos = 0;
const line = () => {
const end = src.indexOf(0x0a, pos);
const text = src.subarray(pos, end).toString("latin1");
pos = end + 1;
return text;
};
if (!line().startsWith("#?")) throw new Error("not a Radiance file");
while (line() !== "");
const [, height, , width] = line().split(" ").map((v, i) => (i % 2 ? Number(v) : v));

// Scanlines (new-style RLE), decoded to linear RGB floats.
const rgb = new Float32Array(width * height * 3);
const scan = new Uint8Array(width * 4);
for (let y = 0; y < height; y++) {
if (src[pos] !== 2 || src[pos + 1] !== 2) throw new Error("expected run-length encoded scanlines");
pos += 4;
for (let c = 0; c < 4; c++) {
for (let x = 0; x < width; ) {
let n = src[pos++];
if (n > 128) {
n -= 128;
scan.fill(src[pos++], c * width + x, c * width + x + n);
} else {
scan.set(src.subarray(pos, pos + n), c * width + x);
pos += n;
}
x += n;
}
}
for (let x = 0; x < width; x++) {
const e = scan[3 * width + x];
const f = e ? 2 ** (e - 136) : 0;
for (let c = 0; c < 3; c++) rgb[(y * width + x) * 3 + c] = scan[c * width + x] * f;
}
}

// Halve, desaturate, encode RGBE.
const w = width / 2, h = height / 2;
const out = Buffer.alloc(w * h * 4);
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const px = [0, 0, 0];
for (const [dx, dy] of [[0, 0], [1, 0], [0, 1], [1, 1]]) {
for (let c = 0; c < 3; c++) px[c] += rgb[((2 * y + dy) * width + 2 * x + dx) * 3 + c] / 4;
}
const lum = 0.2126 * px[0] + 0.7152 * px[1] + 0.0722 * px[2];
const v = px.map((p) => lum + (p - lum) * SATURATION);
const max = Math.max(...v);
const i = (y * w + x) * 4;
if (max < 1e-32) continue;
const e = Math.ceil(Math.log2(max) + 1e-9);
const scale = 256 / 2 ** e;
for (let c = 0; c < 3; c++) out[i + c] = Math.min(255, Math.floor(v[c] * scale));
out[i + 3] = e + 128;
}
}
const header = `#?RADIANCE\n# Poly Haven "Decor Shop" (CC0), 512x256, saturation x${SATURATION}\nFORMAT=32-bit_rle_rgbe\n\n-Y ${h} +X ${w}\n`;
writeFileSync(new URL("../assets/viewer-env.hdr", import.meta.url), Buffer.concat([Buffer.from(header, "latin1"), out]));
console.log(`assets/viewer-env.hdr: ${w}x${h}`);
5 changes: 4 additions & 1 deletion skills/meshy-cli/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ meshy inspect faces --model ./model.glb --max-faces 300000 # exit 0 pass |
meshy mesh prepare-print ./model.obj --height-mm 75 # writes ./model.print.obj (Y-up → Z-up, grounded)
meshy slicer detect
meshy slicer open --slicer OrcaSlicer --file ./model.print.obj # launch only; not proof of import
meshy view ./model.glb --detach --no-open --format json # result.url: interactive 3D view on 127.0.0.1
```

`download` needs an explicit selector when a task has several assets (it lists
Expand All @@ -137,7 +138,9 @@ faces` answers only the face-count question. The API does not report
`face_count`, so measure the downloaded model with `--model <file.glb>`; a task
source answers `unknown` (exit 13) — never treat that as a pass, and do not
start a remesh unless the user agrees. `prepare-print` never edits the input unless
`--in-place`.
`--in-place`. `view` shows a local `.glb`/`.gltf` in a browser viewer served on
127.0.0.1 (nothing is uploaded; the page loads three.js from jsDelivr) and stops
after 30 minutes without a request; `--detach` returns the URL at once.

## Constraints that will bite

Expand Down
1 change: 1 addition & 0 deletions src/cmd/resources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export const RESOURCES: ResourceEntry[] = [
{ name: "mesh", summary: "prepare-print: OBJ Y-up → Z-up, scale to height, centre, ground at Z=0" },
{ name: "slicer", summary: "detect installed slicers | open a model in one" },
{ name: "doctor", summary: "local environment diagnosis (no network by default)" },
{ name: "view", summary: "show a local .glb/.gltf in an interactive 3D viewer in the browser (local only)" },
{ name: "auto-split", summary: "split a model into printable parts (auto / by named parts / by colour; optional connectors)" },
{ name: "usage", summary: "usage tasks: finished API tasks with the credits each consumed (Studio/Enterprise)" },
];
Expand Down
104 changes: 104 additions & 0 deletions src/cmd/view.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
/**
* view — show a local .glb/.gltf in a browser viewer (D-094).
*
* Local only: no API, no credential. The model is served read-only on
* 127.0.0.1 and the page opens in the default browser unless --no-open. The
* envelope (with `url`) is printed as soon as the server listens; the command
* then keeps serving until Ctrl-C or VIEW_IDLE_MS without a request.
* `--detach` hands the server to a background process and returns at once,
* which is what an agent wants: it runs one command and gets a URL.
*/

import { spawn } from "node:child_process";
import { Command } from "commander";
import { emitResult, openCommand } from "../internal/command-helpers.js";
import { abortSignal } from "../internal/context.js";
import { UsageError } from "../internal/errors.js";
import { openBrowser } from "../internal/oauth.js";
import { buildLocalRuntime } from "../internal/runtime.js";
import { resolveViewModel, startViewer, VIEW_IDLE_MS, type ViewModel } from "../internal/viewer.js";

interface ViewOptions {
open: boolean;
detach?: boolean;
}

/** Set on the background child that `--detach` starts; it serves and reports its URL on stdout. */
const CHILD_ENV = "MESHY_VIEW_CHILD";

function describe(model: ViewModel, url: string, extra: Record<string, unknown>): Record<string, unknown> {
return { url, file: model.path, bytes: model.bytes, idle_timeout_s: VIEW_IDLE_MS / 1000, ...extra };
}

/** Start the server in a detached child and wait for the URL it prints. */
function startDetached(model: ViewModel): Promise<{ url: string; pid: number }> {
const script = process.argv[1];
if (!script) throw new UsageError("--detach needs the meshy entry script");
const child = spawn(process.execPath, [script, "view", model.path, "--no-open", "--no-update-check"], {
detached: true,
stdio: ["ignore", "pipe", "ignore"],
env: { ...process.env, [CHILD_ENV]: "1" },
});
return new Promise((resolve, reject) => {
let out = "";
let settled = false;
const fail = (why: string) => {
if (settled) return;
settled = true;
child.kill();
reject(new UsageError(`the background viewer did not start: ${why}`));
};
const timer = setTimeout(() => fail("no URL within 10 s"), 10_000);
child.on("error", (err) => fail(err.message));
child.on("exit", (code) => fail(`it exited with ${code}`));
child.stdout!.on("data", (chunk: Buffer) => {
out += chunk.toString();
const line = out.split("\n")[0]!;
if (!out.includes("\n") || settled) return;
clearTimeout(timer);
child.removeAllListeners("exit");
child.stdout!.destroy();
child.unref();
if (!/^http:\/\/127\.0\.0\.1:\d+\/$/.test(line)) return fail(`unexpected output '${line}'`);
settled = true;
resolve({ url: line, pid: child.pid! });
});
});
}

export function buildViewCommand(): Command {
return new Command("view")
.description(
"Show a local .glb or .gltf in an interactive 3D viewer in the browser. Serves the model read-only on 127.0.0.1 " +
`(nothing is uploaded) and stops after ${VIEW_IDLE_MS / 60_000} min without a request or on Ctrl-C. ` +
"--detach serves from a background process and returns the URL at once",
)
.argument("<model>", "path to a .glb or .gltf file")
.option("--no-open", "print the URL without opening a browser")
.option("--detach", "serve from a background process and return immediately")
.action(async (input: string, opts: ViewOptions, thisCmd: Command) => {
const opened = openCommand(thisCmd, "view");
if (opened.flags.output !== undefined) throw new UsageError("--output/-o has no meaning for view; this command writes no files");
buildLocalRuntime(opened.flags);
const model = resolveViewModel(input);

if (opts.detach) {
const { url, pid } = await startDetached(model);
const browserOpened = opts.open ? await openBrowser(url) : false;
await emitResult(opened, describe(model, url, { opened: browserOpened, detached: true, pid }));
return;
}

const viewer = await startViewer(model);
abortSignal().addEventListener("abort", () => viewer.close(), { once: true });
if (process.env[CHILD_ENV]) {
process.stdout.write(`${viewer.url}\n`);
} else {
const browserOpened = opts.open ? await openBrowser(viewer.url) : false;
await emitResult(opened, describe(model, viewer.url, { opened: browserOpened, detached: false }));
}
await viewer.closed;
});
}

export const viewCommand = buildViewCommand();
Loading
Loading