Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

fix(cad): correct thumbnail PNG encode; local Chromium rendering in dev

Sidwebworks5dc6bc262a26
diff --git a/packages/database/supabase/functions/thumbnail/index.ts b/packages/database/supabase/functions/thumbnail/index.ts
index deda10a8d9..f723741399 100644
--- a/packages/database/supabase/functions/thumbnail/index.ts
+++ b/packages/database/supabase/functions/thumbnail/index.ts
@@ -7,6 +7,7 @@ import { corsHeaders } from "../lib/headers.ts";
import {
ImageMagick,
MagickColor,
+ MagickFormat,
initializeImageMagick,
} from "npm:@imagemagick/[email protected]";
@@ -22,7 +23,11 @@ const payloadSchema = z.object({
url: z.string(),
});
-const browserWSEndpoint = `ws://5.161.255.30?token=59ecf910-aaa8-4c7e-aedb-7c18b34e266e`;
+// Remote browserless in prod; a local Chromium container (ws://chrome:3000) in
+// dev via BROWSERLESS_WS_URL, so the thumbnail flow is testable end-to-end locally.
+const browserWSEndpoint =
+ Deno.env.get("BROWSERLESS_WS_URL") ??
+ `ws://5.161.255.30?token=59ecf910-aaa8-4c7e-aedb-7c18b34e266e`;
serve(async (req: Request) => {
if (req.method === "OPTIONS") {
@@ -41,6 +46,9 @@ serve(async (req: Request) => {
browser = await puppeteer.connect({
browserWSEndpoint,
+ // Locally the target is the portless erp host (self-signed CA); prod uses a
+ // valid cert so this is a no-op there.
+ ignoreHTTPSErrors: true,
});
console.log("browser connected");
const page = await browser.newPage();
@@ -70,7 +78,12 @@ serve(async (req: Request) => {
img.transparent(new MagickColor("white"));
img.resize(300, 300);
- return img.write((data) => data);
+ // Set the output format explicitly and COPY the bytes out of the callback:
+ // the `data` handed to `write` is a view into ImageMagick's WASM heap that is
+ // reused/freed once the callback returns — returning it directly yields a
+ // corrupt PNG (valid header, garbage body → "200 but invalid image").
+ img.format = MagickFormat.Png;
+ return img.write((data) => new Uint8Array(data));
});
return new Response(result, {
diff --git a/packages/dev/docker/docker-compose.dev.yml b/packages/dev/docker/docker-compose.dev.yml
index 6cd05a5653..6b85f4111b 100644
--- a/packages/dev/docker/docker-compose.dev.yml
+++ b/packages/dev/docker/docker-compose.dev.yml
@@ -296,6 +296,9 @@ services:
# edge container itself).
INNGEST_DEV: "1"
INNGEST_BASE_URL: http://inngest:8288
+ # Local Chromium for the `thumbnail` edge fn (the `chrome` profile below).
+ # Prod reads no env → falls back to the remote browserless box.
+ BROWSERLESS_WS_URL: ws://chrome:3000
volumes:
- ./packages/database/supabase/functions:/home/deno/functions:ro
- ./packages/database/src:/home/src:ro
@@ -372,6 +375,33 @@ services:
- inngest:/data
- ${HOME}/.portless/ca.pem:/etc/ssl/certs/portless-ca.pem:ro
+ # Local headless Chromium for the `thumbnail` edge fn — opt-in
+ # (`crbn up --thumbnails` enables this profile). v1 browserless (swiftshader
+ # WebGL, so the GLB render works) is compatible with the edge fn's puppeteer
+ # 16.2.0. edge-runtime reaches it at ws://chrome:3000; it in turn renders the
+ # portless ERP host (VERCEL_URL, e.g. erp.<prefix>.dev) through the portless
+ # proxy on the host — the same host-gateway path the inngest service uses. The
+ # raw ERP dev port only binds 127.0.0.1, so it is NOT container-reachable; the
+ # proxy is. The edge fn connects with ignoreHTTPSErrors for the self-signed CA.
+ chrome:
+ image: browserless/chrome:1-puppeteer-21.3.6
+ restart: unless-stopped
+ profiles: ["chrome"]
+ deploy:
+ resources:
+ limits:
+ memory: ${MEM_CHROME:-1g}
+ cpus: ${CPU_CHROME:-1}
+ environment:
+ # Match the edge fn's connect URL (ws://chrome:3000, no token).
+ TOKEN: ""
+ CONNECTION_TIMEOUT: "60000"
+ extra_hosts:
+ - "host.docker.internal:host-gateway"
+ # Resolve the portless erp host (erp.<prefix>.dev) to the host, so the
+ # rendered VERCEL_URL reaches the portless proxy — mirrors inngest.
+ - "${INNGEST_TLS_HOST}:host-gateway"
+
volumes:
pgdata:
pgconfig:
diff --git a/packages/dev/src/commands/up.ts b/packages/dev/src/commands/up.ts
index f3ab1b0ea6..ff8b4d5cbf 100644
--- a/packages/dev/src/commands/up.ts
+++ b/packages/dev/src/commands/up.ts
@@ -94,6 +94,12 @@ type UpOpts = {
* hosts where the Supabase dashboard and email testing UI aren't needed.
*/
minimal?: boolean;
+ /**
+ * Boot a local headless Chromium container (compose `chrome` profile) and
+ * flag the model-thumbnail job to render locally against it, so the thumbnail
+ * flow is testable in dev. Off by default (the job skips on local otherwise).
+ */
+ thumbnails?: boolean;
};
type Ctx = {
@@ -112,6 +118,7 @@ export async function up(opts: UpOpts = {}) {
const shouldRegen = shouldMigrate && (opts.regen ?? true);
const shouldBorrow = opts.borrow === true;
const minimal = opts.minimal ?? false;
+ const thumbnails = opts.thumbnails === true;
// Services-only mode: boot compose stack + portless aliases (api/studio/
// mail/inngest URLs still useful), skip spawnApps + auto-`down` on Ctrl+C.
// Triggered by --no-apps OR by deselecting everything in the picker.
@@ -156,6 +163,16 @@ export async function up(opts: UpOpts = {}) {
log.info("portless disabled (CARBON_PORTLESS=0) — using localhost URLs");
}
+ // The chrome container reaches the ERP through the portless proxy (the raw
+ // dev port only binds 127.0.0.1). Without portless there's no reachable ERP
+ // URL, so local thumbnail rendering can't work — don't boot chrome for nothing.
+ const chromeEnabled = thumbnails && portless;
+ if (thumbnails && !portless) {
+ log.warn(
+ "--thumbnails needs portless (chrome reaches the ERP via the proxy) — ignoring"
+ );
+ }
+
const allApps = opts.all === true;
const selectedApps = appsRequested
? allApps
@@ -209,13 +226,14 @@ export async function up(opts: UpOpts = {}) {
slug,
portless,
selectedApps.includes("assembler"),
+ chromeEnabled,
borrowedEntry
);
if (borrowedEntry) {
await waitForServices(ctx);
} else {
await pullImages(ctx, { force: opts.pull === true, minimal });
- await bootDockerStack(ctx, { minimal });
+ await bootDockerStack(ctx, { minimal, chrome: chromeEnabled });
await waitForServices(ctx);
}
await runDatabaseMigrations(ctx, { shouldMigrate, shouldRegen });
@@ -343,6 +361,7 @@ async function provisionSlot(
slug: string,
portless: boolean,
includeAssembler: boolean,
+ thumbnails: boolean,
borrowedEntry?: { ports: PortMap; redisDb: number; jwt: JwtCreds }
): Promise<Ctx> {
let ctx!: Ctx;
@@ -387,6 +406,7 @@ async function provisionSlot(
portless,
branchPrefix,
includeAssembler,
+ thumbnails,
...slot
})
);
@@ -462,8 +482,11 @@ async function pullImages(
}
}
-async function bootDockerStack(ctx: Ctx, opts: { minimal: boolean }) {
- const serviceCount = opts.minimal ? 8 : 11;
+async function bootDockerStack(
+ ctx: Ctx,
+ opts: { minimal: boolean; chrome?: boolean }
+) {
+ const serviceCount = (opts.minimal ? 8 : 11) + (opts.chrome ? 1 : 0);
const label = opts.minimal
? "Boot docker compose stack (minimal — no studio/meta/inbucket)"
: "Boot docker compose stack";
@@ -472,7 +495,10 @@ async function bootDockerStack(ctx: Ctx, opts: { minimal: boolean }) {
title: label,
task: async (msg) => {
msg(`starting ${serviceCount} services`);
- await bootStack(ctx.root, ctx.slug, { minimal: opts.minimal });
+ await bootStack(ctx.root, ctx.slug, {
+ minimal: opts.minimal,
+ chrome: opts.chrome
+ });
return "containers up";
}
}
diff --git a/packages/dev/src/env.ts b/packages/dev/src/env.ts
index b051205d16..ee0bb65164 100644
--- a/packages/dev/src/env.ts
+++ b/packages/dev/src/env.ts
@@ -21,6 +21,11 @@ export function renderEnv(opts: {
* pinned in `.env` via `#force` wins regardless.
*/
includeAssembler?: boolean;
+ /**
+ * When true (`crbn up --thumbnails`), let the model-thumbnail job render
+ * locally against the `chrome` compose service instead of skipping on local.
+ */
+ thumbnails?: boolean;
}): string {
const {
slug,
@@ -29,7 +34,8 @@ export function renderEnv(opts: {
jwt,
portless,
branchPrefix,
- includeAssembler = true
+ includeAssembler = true,
+ thumbnails = false
} = opts;
const host = (sub: string) => `${sub}.${branchPrefix}.dev`;
@@ -123,6 +129,15 @@ export function renderEnv(opts: {
lines.push("# Assembler not selected this run — URL omitted so the CAD");
lines.push("# pipeline skips cleanly (assemblerEnabled() gates on it).");
}
+ if (thumbnails && portless) {
+ lines.push("");
+ lines.push("# Local Chromium thumbnail rendering (crbn up --thumbnails).");
+ lines.push("# The chrome container renders VERCEL_URL (the portless erp");
+ lines.push(
+ "# host) through the portless proxy, like the inngest container."
+ );
+ lines.push("THUMBNAIL_RENDER_LOCAL=true");
+ }
lines.push("");
lines.push("# Dev auth bypass");
lines.push("[email protected]");
diff --git a/packages/dev/src/main.ts b/packages/dev/src/main.ts
index 55e382285d..202529cd10 100644
--- a/packages/dev/src/main.ts
+++ b/packages/dev/src/main.ts
@@ -77,6 +77,12 @@ const main = defineCommand({
default: false,
description:
"Skip non-essential services (Studio, Postgres-Meta, Inbucket) to reduce memory footprint (useful for headless/CI builds)"
+ },
+ thumbnails: {
+ type: "boolean",
+ default: false,
+ description:
+ "Run a local headless Chromium container so model-thumbnail renders locally (default: skipped on local)"
}
},
run: ({ args }) =>
@@ -90,7 +96,8 @@ const main = defineCommand({
portless: args.portless !== false,
run: typeof args.run === "string" ? args.run : undefined,
volumes: args.volumes === true,
- minimal: args.minimal === true
+ minimal: args.minimal === true,
+ thumbnails: args.thumbnails === true
})
}),
down: defineCommand({
diff --git a/packages/dev/src/services/compose.ts b/packages/dev/src/services/compose.ts
index 3503b241a7..1c71cf3f31 100644
--- a/packages/dev/src/services/compose.ts
+++ b/packages/dev/src/services/compose.ts
@@ -56,12 +56,14 @@ export type Container = {
export async function bootStack(
root: string,
slug: string,
- opts?: { minimal?: boolean; services?: string[] }
+ opts?: { minimal?: boolean; services?: string[]; chrome?: boolean }
) {
const args = devArgs(root, slug, "--env-file", ".env.local");
// When specific services are requested, don't activate profiles — compose
// starts only the named services (+ dependencies) regardless of profiles.
if (!opts?.services && !opts?.minimal) args.push("--profile", "full");
+ // Opt-in local Chromium for the thumbnail edge fn (`crbn up --thumbnails`).
+ if (!opts?.services && opts?.chrome) args.push("--profile", "chrome");
args.push("up", "-d");
if (opts?.services) args.push(...opts.services);
await execStrict("docker", args, root);
diff --git a/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts b/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts
index 63a9462a62..5a2429a0a5 100644
--- a/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts
+++ b/packages/jobs/src/inngest/functions/tasks/model-thumbnail.ts
@@ -9,25 +9,40 @@ import { nanoid } from "nanoid";
import { inngest } from "../../client";
export const modelThumbnailFunction = inngest.createFunction(
- { id: "model-thumbnail", retries: 3 },
+ {
+ id: "model-thumbnail",
+ retries: 3,
+ // One render per model at a time — overlapping runs (regenerate + the
+ // optimise-chained event, or rapid clicks) would race the "delete previous
+ // thumbnail" step and can strand a just-published object. (This event's
+ // payload key is `modelId`, not `modelUploadId`.)
+ singleton: { key: "event.data.modelId", mode: "skip" }
+ },
{ event: "carbon/model-thumbnail" },
async ({ event, step, logger }) => {
const { modelId, companyId } = event.data;
const isLocal = NODE_ENV !== "production";
-
+ // Dev opt-in: render via a local Chromium container (`crbn up --thumbnails`).
+ const renderLocal = process.env.THUMBNAIL_RENDER_LOCAL === "true";
+
+ // `VERCEL_URL` is the ERP's own URL in every env — prod app URL, or the
+ // portless `https://erp.<prefix>.dev` host locally. The local Chromium
+ // container reaches that host through the portless proxy (host-gateway),
+ // the same way the inngest container reaches the ERP; the raw ERP port only
+ // binds 127.0.0.1 and isn't reachable from a container.
const getModelUrl = (id: string) => {
- if (isLocal) return `http://localhost:3000/file/model/${id}`;
const domain = VERCEL_URL?.startsWith("https://")
? VERCEL_URL
: `https://${VERCEL_URL}`;
return `${domain}/file/model/${id}`;
};
- if (isLocal) {
- logger.info("Skipping model-thumbnail task on local", {
- payload: event.data
- });
+ if (isLocal && !renderLocal) {
+ logger.info(
+ "Skipping model-thumbnail on local (run `crbn up --thumbnails` to render via local Chromium)",
+ { payload: event.data }
+ );
return;
}