@floless/app 0.106.0 → 0.108.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -113,6 +113,20 @@
113
113
 
114
114
  let exportState = null; // kind → { path, exportedAt } after a successful list; null = unknown/failed
115
115
  let teklaReadinessState = null; // latest machine-readable readiness result; {state:'checking'} while probing
116
+ // Same shape for the Render card. Rendering needs AWARE >= 0.103.0 AND Blender on the machine,
117
+ // neither of which floless can assume, so the card reports which one to fix rather than offering
118
+ // a button that fails. The server re-checks on POST — this badge can be minutes stale.
119
+ let renderReadinessState = null;
120
+ // Last-used render options, per project: `${projectId}` -> {viewpoints, output, quality}. Session
121
+ // only; a remembered choice is a convenience, not state worth persisting across restarts.
122
+ const renderChoices = new Map();
123
+ // Live render progress for the open project: { startedAt, stage, viewpoint, index, total }.
124
+ // A render is minutes long and the POST is silent until it finishes, so without this a working
125
+ // render and a wedged one look identical — which is how a 3m45s turntable reads as "nothing
126
+ // happened". Never a percentage: the agent reports no frame counter, and a bar we cannot drive
127
+ // would be exactly the fake progress this codebase refuses.
128
+ let renderProgress = null;
129
+ let renderTicker = null;
116
130
  const exportReceipts = new Map(); // projectId:kind → reconciled receipt counts for this browser session
117
131
  const exportBusy = new Set(); // projectId:kind → one in-flight export
118
132
  if (!$switch || !$landing || !$app) return; // markup absent — nothing to wire
@@ -171,6 +185,12 @@
171
185
  // Yields a URL, not a file, so none of the exportState/receipt plumbing applies — its status
172
186
  // comes from shareCardState and its result is a link with a Copy button (see cardHtml).
173
187
  { kind: 'share-3d', ico: '↗', name: 'Model', fmt: 'Shareable web link', verb: 'Create share link', file: false },
188
+ // ONE card, TWO export kinds (render-png / render-mp4) — a still and a turntable are
189
+ // different deliverables and both receipts show, so `file:false` and renderCardState owns
190
+ // the status instead of the single-kind exportState path. It is also the only card whose
191
+ // POST carries a body (the options modal), and the only one gated on a machine capability
192
+ // (AWARE ≥ 0.103.0 + Blender installed) rather than only on approval.
193
+ { kind: 'render', ico: '◉', name: 'Model', fmt: 'Rendered image', verb: 'Render image', file: false },
174
194
  ],
175
195
  },
176
196
  vectorize: {
@@ -772,6 +792,7 @@
772
792
  current = p;
773
793
  exportState = null;
774
794
  teklaReadinessState = null;
795
+ renderReadinessState = null;
775
796
  track('workspace_project_opened', { app: p.app }); // a real open (card click or post-create landing)
776
797
  lastRevState = 'none'; stopRevisionPoll(); // fresh project — drop any prior revision-poll state
777
798
  // Per-project, like everything above it: never let one project's answer describe another's. Not
@@ -803,6 +824,7 @@
803
824
  current = null;
804
825
  exportState = null;
805
826
  teklaReadinessState = null;
827
+ renderReadinessState = null;
806
828
  stopRevisionPoll();
807
829
  stopKnowledgePoll(); kbCloseConfirm(); kbResetViewer(); knowledgeState = null; // the KB pane is per-project — never carry it across
808
830
  lastRevState = 'none'; $revisionCard.hidden = true; closeProjMenu(); applyMode(); syncWorkspaceGuide();
@@ -2091,16 +2113,168 @@
2091
2113
 
2092
2114
  // The POST export endpoint for a card kind, project-scoped so it reads THIS project's contract
2093
2115
  // and writes into its own exports folder.
2094
- function exportUrl(kind) {
2095
- const qs = `?project=${encodeURIComponent(current.id)}`;
2096
- const base = `/api/contract/${encodeURIComponent(current.app)}`;
2116
+ /**
2117
+ * `projectId`/`appId` are passed in rather than read from `current`.
2118
+ *
2119
+ * Every pre-existing kind reached this synchronously after the `if (!current) return` guard, so
2120
+ * `current` could not move underneath it. The render kind awaits an options dialog first, and a
2121
+ * keyboard user can still switch projects while it is open — which would POST the render at a
2122
+ * DIFFERENT project than the one whose id keys `exportBusy` and the receipts.
2123
+ */
2124
+ function exportUrl(kind, projectId, appId) {
2125
+ const qs = `?project=${encodeURIComponent(projectId)}`;
2126
+ const base = `/api/contract/${encodeURIComponent(appId)}`;
2097
2127
  if (kind === 'bom-csv') return `${base}/export-bom/csv${qs}`;
2098
2128
  if (kind === 'bom-xlsx') return `${base}/export-bom/xlsx${qs}`;
2099
2129
  if (kind === 'ifc') return `${base}/export-ifc${qs}`;
2100
2130
  if (kind === 'svg') return `${base}/export-svg${qs}`;
2131
+ if (kind === 'render') return `${base}/render${qs}`;
2101
2132
  return `${base}/export-tekla${qs}`; // tekla
2102
2133
  }
2103
2134
 
2135
+ // Every existing card is one button with no options, and the grid's rhythm depends on that — so
2136
+ // the render options live in the shared themed modal rather than expanding this one card forever.
2137
+ // `type: 'select'` is the themed combobox (.wf-combo), NOT a native <select>, so no browser
2138
+ // default leaks through onto the dark theme.
2139
+ const RENDER_VIEWPOINTS = [
2140
+ { value: 'hero', label: 'Hero (three-quarter)' },
2141
+ { value: 'iso', label: 'Isometric' },
2142
+ { value: 'front', label: 'Front' },
2143
+ { value: 'back', label: 'Back' },
2144
+ { value: 'left', label: 'Left' },
2145
+ { value: 'right', label: 'Right' },
2146
+ { value: 'top', label: 'Top' },
2147
+ ];
2148
+
2149
+ // Wall-clock per viewpoint, MEASURED on the 209-member Steel Detailer demo at 1920×1080 (each
2150
+ // viewpoint is its own Blender run, so cost is per-viewpoint and additive):
2151
+ // draft right 11s end-to-end, including the one-time IFC step
2152
+ // final right 49s · back 51s · front 54s · top 98s · iso 114s
2153
+ // turntable 6m38s (288 frames at draft; a final one would be hours, hence draft-only)
2154
+ // It is a RANGE because the spread is real and structural, not noise: a flat elevation renders
2155
+ // a fraction of what an isometric or top view does, so any single number would be wrong for half
2156
+ // the angles. Erring long is deliberate — an under-promise is precisely what makes someone
2157
+ // conclude a working render has hung, which is how this dialog's old flat "about 30 seconds"
2158
+ // (against a measured 49–114s, and never multiplied by the number of angles picked) read.
2159
+ const RENDER_COST_SECONDS = {
2160
+ still: { draft: [8, 15], production: [50, 115] },
2161
+ turntable: { draft: [390, 540], production: [390, 540] },
2162
+ };
2163
+
2164
+ /** "6–9 minutes" / "about 1 minute" / "10–15 seconds" — never a false precision. */
2165
+ function humanRange(loSec, hiSec) {
2166
+ if (hiSec < 100) return `${Math.round(loSec / 5) * 5}–${Math.round(hiSec / 5) * 5} seconds`;
2167
+ const lo = Math.max(1, Math.round(loSec / 60));
2168
+ const hi = Math.max(lo, Math.round(hiSec / 60));
2169
+ return lo === hi ? `about ${lo} minute${lo === 1 ? '' : 's'}` : `${lo}–${hi} minutes`;
2170
+ }
2171
+
2172
+ /**
2173
+ * The running cost of what is currently picked — the one thing this dialog could not say with a
2174
+ * static label, because it scales with the number of viewpoints. Leads with the duration.
2175
+ */
2176
+ function renderEstimate(values) {
2177
+ const picked = String(values.viewpoint || '').split(',').map((v) => v.trim()).filter(Boolean);
2178
+ const n = picked.length;
2179
+ if (!n) return 'Pick at least one viewpoint.';
2180
+ const output = values.output === 'turntable' ? 'turntable' : 'still';
2181
+ // Turntables ignore the quality field (always draft), so the estimate must ignore it too —
2182
+ // otherwise the number moves when the user changes a control that changes nothing.
2183
+ const quality = output === 'turntable' ? 'draft' : (values.quality === 'draft' ? 'draft' : 'production');
2184
+ const [lo, hi] = RENDER_COST_SECONDS[output][quality];
2185
+ const each = n > 1 ? ` · ${n} ${output === 'turntable' ? 'turntables' : 'viewpoints'}, one after another` : '';
2186
+ // The lock is worth a clause: it is the one consequence a user cannot see coming, and finding
2187
+ // out by clicking a greyed-out Export IFC ten minutes later is a worse way to learn it.
2188
+ return `Takes ${humanRange(lo * n, hi * n)}${each}. This project's other exports wait until it finishes.`;
2189
+ }
2190
+
2191
+ async function askRenderOptions(projectId) {
2192
+ // `viewpoints` (plural) — the shape doExport actually reads. This said `viewpoint` and would
2193
+ // have thrown on `.length` the moment it was reached.
2194
+ if (!bridge.formModal) return { viewpoints: ['hero'], output: 'still', quality: 'production' };
2195
+ const last = renderChoices.get(projectId) || {};
2196
+ const chosen = await bridge.formModal({
2197
+ title: 'Render image',
2198
+ // The Tekla card in this same grid genuinely mutates a live host model, so users have an
2199
+ // earned reason to be wary of buttons here. Say plainly that this one only reads.
2200
+ sub: 'Renders the approved model. Nothing in your model changes.',
2201
+ okLabel: 'Render',
2202
+ // The estimate has to be live: it is the product of two fields (how many angles × how dear
2203
+ // each is), so no fixed label can state it. This is the difference between choosing five
2204
+ // viewpoints informed and discovering the cost eight minutes in.
2205
+ onChange: renderEstimate,
2206
+ // Cancelling must put focus back on the button that opened this. Naming it explicitly rather
2207
+ // than relying on the default (whatever happened to be focused when the modal opened): the
2208
+ // card repaints on the way in, which moves focus off the button, so the default sent it to
2209
+ // the app's hamburger. The fallback then covers the case where the repaint destroyed the
2210
+ // element this captured — it re-queries the live one.
2211
+ returnFocusTo: $wsExports.querySelector('[data-export="render"]'),
2212
+ returnFocusFallback: () => (current && current.id === projectId
2213
+ ? $wsExports.querySelector('[data-export="render"]')
2214
+ : null),
2215
+ fields: [
2216
+ {
2217
+ // Multi-select: a drawing pack usually wants several angles, and rendering them one at
2218
+ // a time meant reopening this dialog per angle. Each picked viewpoint becomes its own
2219
+ // artifact — they no longer overwrite one another.
2220
+ name: 'viewpoint', label: 'Viewpoints', type: 'select', multiple: true,
2221
+ placeholder: 'Pick one or more',
2222
+ value: (last.viewpoints && last.viewpoints.join(',')) || 'hero',
2223
+ options: RENDER_VIEWPOINTS,
2224
+ },
2225
+ {
2226
+ name: 'output', label: 'Output', type: 'select',
2227
+ value: last.output || 'still',
2228
+ options: [
2229
+ { value: 'still', label: 'Still image', meta: 'PNG' },
2230
+ // The quality choice below applies to STILLS. A turntable is ~144 frames, and at the
2231
+ // measured cost of a final frame that is hours — past any sane budget — so it always
2232
+ // renders at draft. Saying so here is the difference between a constraint and a
2233
+ // control that silently ignores what was picked.
2234
+ // Measured on the 209-member model, twice: 3m45s at a 6s revolution, 6m38s at the 12s
2235
+ // one that ships. Every frame is a separate render, so the wall-clock tracks the frame
2236
+ // count almost exactly. An under-promised duration is worse than none — it is what
2237
+ // makes someone conclude a working render has failed.
2238
+ // 7–9, not 6–9: measured 6m38s, and this must agree with the footnote's rounding
2239
+ // rather than quote a low end the render has never actually hit.
2240
+ { value: 'turntable', label: 'Turntable video', meta: 'MP4 · always draft · 7–9 min each' },
2241
+ ],
2242
+ },
2243
+ {
2244
+ // Framed as TIME, never as engine names — that is what makes the draft-then-final loop
2245
+ // discoverable to someone who has never heard of a path tracer.
2246
+ name: 'quality', label: 'Quality (still images)', type: 'select',
2247
+ value: last.quality || 'production',
2248
+ options: [
2249
+ // Per ANGLE, and said so — these were flat totals ("about 30 seconds") that neither
2250
+ // scaled with the number picked nor matched the measurement. See RENDER_COST_SECONDS.
2251
+ { value: 'draft', label: 'Draft', meta: 'about 10 seconds each' },
2252
+ { value: 'production', label: 'Final', meta: 'about 1–2 min each' },
2253
+ ],
2254
+ },
2255
+ ],
2256
+ });
2257
+ if (!chosen) return null;
2258
+ const viewpoints = String(chosen.viewpoint || '')
2259
+ .split(',').map((v) => v.trim()).filter(Boolean);
2260
+ if (!viewpoints.length) {
2261
+ showToast('Pick at least one viewpoint to render.', 'warn');
2262
+ return null;
2263
+ }
2264
+ const options = {
2265
+ viewpoints,
2266
+ output: chosen.output === 'turntable' ? 'turntable' : 'still',
2267
+ quality: chosen.quality === 'draft' ? 'draft' : 'production',
2268
+ };
2269
+ renderChoices.set(projectId, options);
2270
+ // The server renders every turntable at draft. Never let a visible choice be discarded in
2271
+ // silence — if they asked for Final and picked a turntable, say what they are getting.
2272
+ if (options.output === 'turntable' && options.quality === 'production') {
2273
+ showToast('Turntables always render at draft quality — a final one would take hours.', 'info');
2274
+ }
2275
+ return options;
2276
+ }
2277
+
2104
2278
  const receiptKey = (kind) => `${current ? current.id : ''}:${kind}`;
2105
2279
 
2106
2280
  function receiptItemText(prefix, value) {
@@ -2145,6 +2319,153 @@
2145
2319
  // one here would imply a revoke story that does not exist yet.
2146
2320
  const shareLinks = new Map();
2147
2321
 
2322
+ const RENDER_ROWS = [
2323
+ { kind: 'render-png', label: 'image' },
2324
+ { kind: 'render-mp4', label: 'turntable' },
2325
+ ];
2326
+
2327
+ /** "1:23" — elapsed, so the answer to "is it still going?" is always visible and always true. */
2328
+ function elapsedSince(startedAt) {
2329
+ const s = Math.max(0, Math.round((Date.now() - startedAt) / 1000));
2330
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
2331
+ }
2332
+
2333
+ /** The busy line: what it is doing now, which of how many, and how long it has been going. */
2334
+ function renderBusyText() {
2335
+ if (!renderProgress) return 'Rendering the approved model';
2336
+ const { stage, viewpoint, index, total, startedAt } = renderProgress;
2337
+ const clock = ` · ${elapsedSince(startedAt)}`;
2338
+ if (stage === 'preparing') return `Preparing the model${clock}`;
2339
+ if (stage === 'rendering' || stage === 'rendered') {
2340
+ const which = viewpoint ? viewpointLabel(viewpoint) : '';
2341
+ const counter = total > 1 ? ` (${index} of ${total})` : '';
2342
+ return `Rendering ${which}${counter}${clock}`;
2343
+ }
2344
+ return `Rendering${clock}`;
2345
+ }
2346
+
2347
+ window.addEventListener('floless:render-progress', (e) => {
2348
+ const m = e.detail || {};
2349
+ if (!current || m.project !== current.id) return; // another project's render
2350
+ if (m.stage === 'done' || m.stage === 'failed') { renderProgress = null; return; }
2351
+ renderProgress = {
2352
+ stage: m.stage,
2353
+ viewpoint: m.viewpoint || null,
2354
+ index: m.index || 1,
2355
+ total: m.total || 1,
2356
+ startedAt: (renderProgress && renderProgress.startedAt) || Date.now(),
2357
+ };
2358
+ paintExports(current.approvedAt);
2359
+ });
2360
+
2361
+ /** The viewpoint as a person named it, for the card's per-artifact rows. */
2362
+ function viewpointLabel(variant) {
2363
+ const known = RENDER_VIEWPOINTS.find((v) => v.value === variant);
2364
+ return known ? known.label.replace(/\s*\(.*\)$/, '').toLowerCase() : variant;
2365
+ }
2366
+
2367
+ /**
2368
+ * The Render card's state — same {meta, disabled, tip} shape as teklaCardState/shareCardState.
2369
+ *
2370
+ * Two things make it unlike the others. It reads TWO export kinds (a still and a turntable are
2371
+ * different deliverables, and last-wins would claim "rendered 14:41" while a 14:32 still also sat
2372
+ * in the folder). And it is gated on a machine CAPABILITY, not only on approval — so an
2373
+ * unrenderable machine says which of the two dependencies to fix, in the order they must be
2374
+ * fixed, rather than offering a button that fails.
2375
+ */
2376
+ function renderCardState(approved) {
2377
+ if (!approved) return {
2378
+ meta: '<span class="e-status">Available after approval</span>',
2379
+ disabled: true,
2380
+ tip: 'Approve this version first',
2381
+ };
2382
+ const readiness = renderReadinessState;
2383
+ // A render in flight outranks everything else this card could say: it is the one state the
2384
+ // user is actively waiting on, and it must show what is happening AND that time is passing.
2385
+ if (exportBusy.has(`${current.id}:render`)) {
2386
+ return {
2387
+ meta: `<span class="e-readiness checking" role="status" aria-live="polite">` +
2388
+ `<span class="rtn-spinner" aria-hidden="true"></span>${escapeHtml(renderBusyText())}</span>`,
2389
+ disabled: true,
2390
+ tip: renderBusyText(),
2391
+ };
2392
+ }
2393
+ if (readiness && readiness.state === 'checking') return {
2394
+ meta: '<span class="e-status">Checking…</span>',
2395
+ disabled: true,
2396
+ tip: 'Checking whether this computer can render',
2397
+ };
2398
+ if (readiness && !readiness.ok) {
2399
+ const recovery = readiness.recovery || { action: 'retry', label: 'Check again' };
2400
+ return {
2401
+ meta: `<span class="e-readiness blocked" role="status" aria-live="polite">${escapeHtml(readiness.message || 'Rendering is not available on this computer.')}</span>` +
2402
+ `<button type="button" class="e-recovery" data-render-recovery="${escapeAttr(recovery.action)}">${escapeHtml(recovery.label)}</button>`,
2403
+ disabled: true,
2404
+ tip: readiness.message || 'Resolve the rendering requirements first',
2405
+ };
2406
+ }
2407
+
2408
+ // `exportState == null` means the listing FAILED (or has not loaded), not that nothing was
2409
+ // rendered — printing "not rendered yet" would be a definite negative the server never
2410
+ // confirmed, and it would also drop the thumbnail and offer "Render image" for something
2411
+ // already on disk, inviting a redundant multi-minute render. The file-kind branch of cardHtml
2412
+ // makes exactly this distinction; this is the first file:false card that reads exportState,
2413
+ // so it has to make it too.
2414
+ if (exportState == null) {
2415
+ return { meta: '<span class="e-status">Status unavailable</span>', disabled: false, tip: '' };
2416
+ }
2417
+
2418
+ // One line per ARTIFACT, not per kind: a kind can now hold several viewpoints, and collapsing
2419
+ // them would claim "rendered 14:41" while three other renders also sat in the folder.
2420
+ const done = [];
2421
+ for (const { kind, label } of RENDER_ROWS) {
2422
+ const entry = exportState[kind];
2423
+ if (!entry) continue;
2424
+ const variants = Array.isArray(entry.variants) ? entry.variants : [];
2425
+ if (variants.length) {
2426
+ for (const v of variants) {
2427
+ if (!v.exportedAt) continue;
2428
+ done.push({
2429
+ key: v.variant ? `${kind}:${v.variant}` : kind,
2430
+ // The viewpoint alone is NOT enough: a still and a turntable of the same angle would
2431
+ // both read "hero", and the one thing a user needs to know at a glance is which row is
2432
+ // the video. Name the kind whenever it is not the plain still.
2433
+ label: v.variant
2434
+ ? (kind === 'render-mp4' ? `${viewpointLabel(v.variant)} turntable` : viewpointLabel(v.variant))
2435
+ : label,
2436
+ exportedAt: v.exportedAt,
2437
+ });
2438
+ }
2439
+ } else if (entry.exportedAt) {
2440
+ done.push({ key: kind, label, exportedAt: entry.exportedAt });
2441
+ }
2442
+ }
2443
+ if (!done.length) {
2444
+ return { meta: '<span class="e-status">not rendered yet</span>', disabled: false, tip: '' };
2445
+ }
2446
+ // Newest first, so the thing just produced is the thing shown at the top.
2447
+ done.sort((a, b) => String(b.exportedAt).localeCompare(String(a.exportedAt)));
2448
+ // Each artifact is ONE row — name and links side by side — inside a height-capped scroller.
2449
+ // Unbounded, this is the only card whose height grows with use: a still per viewpoint plus
2450
+ // turntables reached eight entries on the demo project, and since the grid stretches a row to
2451
+ // its tallest item, that one card was dragging every sibling down the page with it.
2452
+ const rows = done.map((row) =>
2453
+ `<div class="e-render-row">` +
2454
+ `<span class="e-done"><span class="chk">✓</span> ${escapeHtml(row.label)} <span class="t">${escapeHtml(hhmm(row.exportedAt))}</span></span>` +
2455
+ `<span class="e-links">` +
2456
+ `<button type="button" class="e-link" data-openfile="${escapeAttr(row.key)}" data-tip="Open in its default app">⧉ Open</button>` +
2457
+ `<button type="button" class="e-link" data-reveal="${escapeAttr(row.key)}" data-tip="Show the file in its folder">▤ Reveal</button>` +
2458
+ `</span>` +
2459
+ `</div>`).join('');
2460
+ // The list is keyboard-reachable on its own (tabbing hits the buttons inside), but a scroller
2461
+ // whose content overflows also needs to be focusable for someone scrolling WITHOUT tabbing
2462
+ // through every link — hence tabindex + the group label.
2463
+ return {
2464
+ meta: `<div class="e-renders" role="group" aria-label="Rendered files"${done.length > 4 ? ' tabindex="0"' : ''}>${rows}</div>`,
2465
+ disabled: false, tip: '', rendered: true,
2466
+ };
2467
+ }
2468
+
2148
2469
  // The share card's state, same {meta, disabled, tip} shape as teklaCardState. It is the second
2149
2470
  // file:false export kind, and the first whose RESULT is a URL rather than a file.
2150
2471
  function shareCardState(approved) {
@@ -2212,7 +2533,8 @@
2212
2533
  // The two file:false kinds resolve their own status; everything else uses the file/receipt path
2213
2534
  // below. `special` keeps the branches from growing a third arm each time a kind is added.
2214
2535
  const special = c.kind === 'tekla' ? teklaCardState(approved)
2215
- : c.kind === 'share-3d' ? shareCardState(approved) : null;
2536
+ : c.kind === 'share-3d' ? shareCardState(approved)
2537
+ : c.kind === 'render' ? renderCardState(approved) : null;
2216
2538
  if (special) {
2217
2539
  meta = special.meta;
2218
2540
  } else if (!approved) {
@@ -2236,18 +2558,37 @@
2236
2558
  // Re-labelled once a link exists, mirroring the file kinds' "Re-export" convention. Gated on the
2237
2559
  // in-memory record rather than exportState, which only ever tracks file exports.
2238
2560
  const shared = approved && c.kind === 'share-3d' && shareLinks.has(`${current.id}:share-3d`);
2239
- const busyLabel = c.kind === 'tekla' ? 'Sending…' : c.kind === 'share-3d' ? 'Creating…' : 'Exporting…';
2240
- const label = busy ? busyLabel : (exported || shared ? (c.kind === 'share-3d' ? 'Create new link' : 'Re-export') : c.verb);
2241
- const disabled = special ? special.disabled : !approved;
2561
+ const rendered = approved && c.kind === 'render' && special && special.rendered;
2562
+ const busyLabel = c.kind === 'tekla' ? 'Sending…' : c.kind === 'share-3d' ? 'Creating…'
2563
+ : c.kind === 'render' ? 'Rendering…' : 'Exporting…';
2564
+ const label = busy ? busyLabel
2565
+ : (exported || shared || rendered
2566
+ ? (c.kind === 'share-3d' ? 'Create new link' : c.kind === 'render' ? 'Re-render' : 'Re-export')
2567
+ : c.verb);
2568
+ // A render holds the project's lifecycle lock for its whole duration (minutes for a turntable),
2569
+ // and every other project-scoped export serializes on that same key. In-process those queue
2570
+ // with no timeout, so a sibling card clicked meanwhile would just sit on "Exporting…" with no
2571
+ // explanation. Say what is happening instead of letting it hang.
2572
+ const renderHolding = c.kind !== 'render' && exportBusy.has(`${current.id}:render`);
2573
+ const disabled = renderHolding || (special ? special.disabled : !approved);
2242
2574
  const busyTip = c.kind === 'tekla' ? 'Sending the approved model to Tekla'
2243
- : c.kind === 'share-3d' ? 'Rendering the model and uploading the link' : 'Export in progress';
2575
+ : c.kind === 'share-3d' ? 'Rendering the model and uploading the link'
2576
+ : c.kind === 'render' ? renderBusyText()
2577
+ : 'Export in progress';
2244
2578
  const tip = busy ? busyTip
2579
+ : renderHolding ? 'Waiting for the render to finish — it holds this project while it runs'
2245
2580
  : special ? special.tip : (approved ? '' : 'Approve this version first');
2246
2581
  const dis = `${disabled && !busy ? ' disabled' : ''}${busy ? ' aria-disabled="true" aria-busy="true"' : ''}${tip ? ` data-tip="${escapeAttr(tip)}"` : ''}`;
2247
2582
  return `<div class="ecard">` +
2248
2583
  `<div class="e-top"><div class="e-ico">${escapeHtml(c.ico)}</div>` +
2249
2584
  `<div><div class="e-name">${escapeHtml(c.name)}</div><div class="e-fmt">${escapeHtml(c.fmt)}</div></div></div>` +
2250
2585
  `<div class="e-meta${special ? ' e-meta-tekla' : ''}">${meta}</div>` +
2586
+ // Only the still gets a preview: an MP4 has no frame to show without decoding one, and a
2587
+ // card is not a video player. Click opens it exactly like ⧉ Open — no lightbox.
2588
+ (c.kind === 'render' && approved && exportState && exportState['render-png']
2589
+ && exportState['render-png'].exportedAt
2590
+ ? `<button type="button" class="e-thumb" data-render-thumb data-openfile="render-png" data-tip="Open the rendered image"><img alt=""></button>`
2591
+ : '') +
2251
2592
  receiptHtml(c.kind, approved) +
2252
2593
  `<div class="e-act"><button type="button" data-export="${escapeAttr(c.kind)}"${dis}>↗ ${escapeHtml(label)}</button></div>` +
2253
2594
  `</div>`;
@@ -2259,6 +2600,7 @@
2259
2600
  'data-reveal',
2260
2601
  'data-export-details',
2261
2602
  'data-tekla-recovery',
2603
+ 'data-render-recovery',
2262
2604
  'data-copyshare', // the share-link Copy button — omitted here, a repaint mid-render steals its focus
2263
2605
  ];
2264
2606
 
@@ -2302,21 +2644,68 @@
2302
2644
  const cards = (wsApp() && wsApp().exports) || [];
2303
2645
  html += '<div class="export-grid">' + cards.map((c) => cardHtml(c, approved)).join('') + '</div>';
2304
2646
  $wsExports.innerHTML = html;
2647
+ paintRenderThumb();
2305
2648
  restoreExportFocus(restoreIdentity);
2306
2649
  }
2307
2650
 
2651
+ /**
2652
+ * Wire up the render card's preview after the card markup lands.
2653
+ *
2654
+ * `src` and `alt` are set as PROPERTIES, never through markup — the same discipline kbPaintImage
2655
+ * uses, and the reason nothing here needs escaping. A 200 does not guarantee a DECODABLE image,
2656
+ * so `onerror` degrades to a muted line rather than leaving a broken-image glyph sitting in a
2657
+ * card that otherwise claims success.
2658
+ */
2659
+ function paintRenderThumb() {
2660
+ const wrap = $wsExports.querySelector('[data-render-thumb]');
2661
+ if (!wrap || !current) return;
2662
+ const img = wrap.querySelector('img');
2663
+ if (!img) return;
2664
+ img.alt = `Rendered image of ${current.name || current.app}`;
2665
+ img.onerror = () => {
2666
+ wrap.classList.add('e-thumb-failed');
2667
+ wrap.textContent = 'preview unavailable';
2668
+ };
2669
+ // Stamped per render, so a re-render can never show the previous version's picture — the one
2670
+ // thing a preview must never quietly be.
2671
+ const stamp = (exportState && exportState['render-png'] && exportState['render-png'].exportedAt) || '';
2672
+ img.src = `/api/contract/${encodeURIComponent(current.app)}/render-preview`
2673
+ + `?project=${encodeURIComponent(current.id)}&v=${encodeURIComponent(stamp)}`;
2674
+ }
2675
+
2308
2676
  async function renderExports() {
2309
2677
  if (!current) return;
2310
2678
  const id = current.id, app = current.app;
2311
2679
  const cards = (wsApp() && wsApp().exports) || [];
2312
2680
  const hasTekla = cards.some((card) => card.kind === 'tekla');
2681
+ const hasRender = cards.some((card) => card.kind === 'render');
2313
2682
  teklaReadinessState = hasTekla ? { ok: false, state: 'checking' } : null;
2683
+ renderReadinessState = hasRender ? { ok: false, state: 'checking' } : null;
2314
2684
  paintExports(current.approvedAt);
2315
2685
  let state = null;
2316
2686
  let approvedAt = current.approvedAt; // fallback if the fetch fails (best-known)
2317
2687
  const exportPromise = api(`/api/contract/${encodeURIComponent(app)}/exports?project=${encodeURIComponent(id)}`);
2318
2688
  const readinessPromise = hasTekla ? api('/api/tekla-readiness') : Promise.resolve(null);
2319
- const [exportResult, readinessResult] = await Promise.allSettled([exportPromise, readinessPromise]);
2689
+ const renderReadyPromise = hasRender ? api('/api/render/readiness') : Promise.resolve(null);
2690
+ const [exportResult, readinessResult, renderReadyResult] = await Promise.allSettled([
2691
+ exportPromise, readinessPromise, renderReadyPromise,
2692
+ ]);
2693
+ if (hasRender) {
2694
+ // A readiness probe that fails is reported as unknown-with-a-retry, never as ready — the
2695
+ // same honesty the export listing keeps ("Status unavailable", never a fake "not exported").
2696
+ renderReadinessState = renderReadyResult.status === 'fulfilled' && renderReadyResult.value && renderReadyResult.value.readiness
2697
+ ? renderReadyResult.value.readiness
2698
+ : {
2699
+ ok: false,
2700
+ state: 'error',
2701
+ // Prefer the server's own words, as the Tekla branch below already does. The route-gate
2702
+ // 409s this endpoint while AWARE is still installing and says so actionably; replacing
2703
+ // that with the generic line threw away the only sentence that told the user to wait.
2704
+ message: (renderReadyResult.reason && renderReadyResult.reason.message)
2705
+ || 'Could not check whether rendering is available.',
2706
+ recovery: { action: 'retry', label: 'Check again' },
2707
+ };
2708
+ }
2320
2709
  if (exportResult.status === 'fulfilled') {
2321
2710
  const r = exportResult.value;
2322
2711
  state = {};
@@ -2355,6 +2744,30 @@
2355
2744
  const app = current.app, projectId = current.id, approvedAt = current.approvedAt, projectName = current.name; // capture — the user may switch projects, or leave, during the await
2356
2745
  const busyKey = `${projectId}:${kind}`;
2357
2746
  if (exportBusy.has(busyKey)) return;
2747
+
2748
+ // The Render card is the only one that asks anything before it runs, so the options are
2749
+ // collected BEFORE the busy state — marking the card "Rendering…" while a dialog is still open
2750
+ // would be a lie about what the machine is doing.
2751
+ let renderOptions = null;
2752
+ if (kind === 'render') {
2753
+ renderOptions = await askRenderOptions(projectId);
2754
+ if (!renderOptions) return; // cancelled — nothing started, so nothing to unwind
2755
+ // The dialog is awaited, so the project can move under us. Everything below keys off the
2756
+ // captured ids; bailing here keeps the request itself from being aimed somewhere else.
2757
+ if (!current || current.id !== projectId) return;
2758
+ // Start the clock immediately, not on the first server event: the IFC write happens before
2759
+ // any progress arrives, and a card that says nothing for the first few seconds is precisely
2760
+ // the "did my click register?" moment this exists to remove.
2761
+ renderProgress = { stage: 'preparing', viewpoint: null, index: 1, total: renderOptions.viewpoints.length, startedAt: Date.now() };
2762
+ clearInterval(renderTicker);
2763
+ // Repaint on a slow tick so the elapsed clock advances even while the server is silent —
2764
+ // which, during a single long Blender invoke, is most of the time.
2765
+ renderTicker = setInterval(() => {
2766
+ if (current && current.id === projectId && exportBusy.has(`${projectId}:render`)) paintExports(current.approvedAt);
2767
+ else { clearInterval(renderTicker); renderTicker = null; }
2768
+ }, 1000);
2769
+ }
2770
+
2358
2771
  exportBusy.add(busyKey);
2359
2772
  // The delegated click can report BODY as active by the time this synchronous repaint runs.
2360
2773
  // Carry the activated kind through the first replacement explicitly; later repaints infer
@@ -2414,8 +2827,17 @@
2414
2827
  }
2415
2828
  return;
2416
2829
  }
2830
+ // Set when a FAILED render still published some viewpoints, so the finally can re-fetch the
2831
+ // listing rather than repaint a stale one (see the catch below).
2832
+ let publishedDespiteFailure = false;
2833
+ // True once the success path has handed off to renderExports(), so the finally does not
2834
+ // paint a stale intermediate state over it.
2835
+ let refreshing = false;
2417
2836
  try {
2418
- const res = await api(exportUrl(kind), { method: 'POST' });
2837
+ // Render is the only export whose POST carries a body — the options the modal collected.
2838
+ const res = await api(exportUrl(kind, projectId, app), renderOptions
2839
+ ? { method: 'POST', body: JSON.stringify(renderOptions), headers: { 'content-type': 'application/json' } }
2840
+ : { method: 'POST' });
2419
2841
  track('workspace_export', { app, kind }); // a successful export/bake (e.g. { app:'vectorize', kind:'svg' })
2420
2842
  if (res.counts) exportReceipts.set(`${projectId}:${kind}`, {
2421
2843
  counts: res.counts,
@@ -2435,18 +2857,49 @@
2435
2857
  : `Exported — ${res.filename || kind}`,
2436
2858
  summary && summary.partial ? 'warn' : 'ok');
2437
2859
  }
2438
- return renderExports(); // repaint status + the authoritative receipt summary
2860
+ refreshing = true;
2861
+ // The catch is what makes the finally's skip safe: if the refresh itself throws, nothing else
2862
+ // would repaint and the card would sit in its busy state forever, with exportBusy already
2863
+ // cleared underneath it. Fall back to the paint the finally would have done.
2864
+ return renderExports().catch((refreshErr) => { // repaint status + the authoritative receipt summary
2865
+ console.warn('exports refresh failed after a successful export', refreshErr);
2866
+ if (current && current.id === projectId) paintExports(current.approvedAt);
2867
+ });
2439
2868
  } catch (err) {
2440
2869
  // The durable export listing may still show the previously published file, but its in-session
2441
2870
  // receipt must not masquerade as the result of this failed attempt.
2442
2871
  exportReceipts.delete(`${projectId}:${kind}`);
2443
2872
  const needsTekla = err && err.body && err.body.needsTekla;
2444
2873
  if (kind === 'tekla' && err && err.body && err.body.readiness) teklaReadinessState = err.body.readiness;
2445
- showToast(err && err.message ? err.message : String(err), needsTekla ? 'info' : 'warn');
2874
+ // The render route ships machine-readable readiness on its 409 precisely so the card can
2875
+ // show WHICH dependency broke. Dropping it left the card looking ready with an enabled
2876
+ // button, and the only trace of the refusal was a toast that evaporates.
2877
+ if (kind === 'render' && err && err.body && err.body.readiness) renderReadinessState = err.body.readiness;
2878
+ // A partial batch is not a rollback. The server publishes each viewpoint as it finishes and
2879
+ // returns what got through on the 502 precisely so those files can be found — repainting the
2880
+ // in-memory listing here would hide them until the tab was reopened, which is the outcome
2881
+ // that field exists to prevent. Say how many survived, then re-fetch below.
2882
+ const got = kind === 'render' && err && err.body && Array.isArray(err.body.rendered)
2883
+ ? err.body.rendered.length : 0;
2884
+ publishedDespiteFailure = got > 0;
2885
+ showToast(
2886
+ got > 0
2887
+ ? `${err && err.message ? err.message : 'Rendering failed'} — ${got} viewpoint${got === 1 ? '' : 's'} did finish and ${got === 1 ? 'is' : 'are'} saved.`
2888
+ : (err && err.message ? err.message : String(err)),
2889
+ needsTekla ? 'info' : 'warn');
2446
2890
  if (kind === 'tekla' && current && current.id === projectId) paintExports(current.approvedAt);
2447
2891
  } finally {
2448
2892
  exportBusy.delete(busyKey);
2449
- if (current && current.id === projectId) paintExports(current.approvedAt);
2893
+ if (kind === 'render') {
2894
+ clearInterval(renderTicker); renderTicker = null; renderProgress = null;
2895
+ }
2896
+ // Skipped when a listing refresh is already in flight (the success path returns
2897
+ // renderExports(), which starts BEFORE this runs and finishes after). Painting here showed
2898
+ // the card un-busy against not-yet-refreshed state for about a second — long enough to read
2899
+ // "↗ Render image", greyed out, on a render that had just succeeded.
2900
+ if (!refreshing && current && current.id === projectId) paintExports(current.approvedAt);
2901
+ // Authoritative re-read: only the server knows which viewpoints actually landed.
2902
+ if (publishedDespiteFailure && current && current.id === projectId) await renderExports();
2450
2903
  }
2451
2904
  }
2452
2905
 
@@ -2468,6 +2921,70 @@
2468
2921
  });
2469
2922
  }
2470
2923
 
2924
+ /**
2925
+ * The Render card's blocked-state recovery. Each action fixes exactly the dependency the badge
2926
+ * named — and re-probes afterwards, so a fixed machine flips to a live button without a reload.
2927
+ */
2928
+ async function recoverRender(action) {
2929
+ if (!current) return;
2930
+ if (action === 'install-blender') {
2931
+ // Blender is a third-party download, not something floless can install. Send them to the
2932
+ // real source rather than pretending a button here could do it.
2933
+ window.open('https://www.blender.org/download/', '_blank', 'noopener');
2934
+ return;
2935
+ }
2936
+ if (action === 'install-agent') {
2937
+ renderReadinessState = { ok: false, state: 'checking' };
2938
+ paintExports(current.approvedAt);
2939
+ try {
2940
+ const res = await api('/api/render/install-agent', { method: 'POST' });
2941
+ renderReadinessState = res.readiness || renderReadinessState;
2942
+ // The re-probe in the same response is the authority, not the exit code. `installed` comes
2943
+ // from a regex over CLI output and goes null on any drift, and the command can exit 0
2944
+ // without the agent becoming usable — which used to show a green "installed" toast directly
2945
+ // above a card still reading "The Blender agent is not installed yet."
2946
+ showToast(res.readiness && res.readiness.ok
2947
+ ? 'Blender agent installed — you can render now.'
2948
+ : `The install finished but rendering still is not available — ${
2949
+ (res.readiness && res.readiness.message) || 'the agent did not become usable.'}`,
2950
+ res.readiness && res.readiness.ok ? 'ok' : 'warn');
2951
+ } catch (err) {
2952
+ showToast(err && err.message ? err.message : String(err), 'warn');
2953
+ // Leaving `checking` in place would strand the card disabled as "Checking…" with no
2954
+ // recovery button until the tab is reopened — a failed install that hides its own retry.
2955
+ renderReadinessState = {
2956
+ ok: false,
2957
+ state: 'error',
2958
+ message: 'Installing the Blender agent failed.',
2959
+ recovery: { action: 'retry', label: 'Check again' },
2960
+ };
2961
+ }
2962
+ if (current) paintExports(current.approvedAt);
2963
+ return;
2964
+ }
2965
+ if (action === 'update-aware') {
2966
+ // The footer pill owns updating AWARE — duplicating that flow here would give two places
2967
+ // that can start the same install.
2968
+ showToast('Use ↑ Upgrade AWARE in the footer, then click Check again.', 'info');
2969
+ return;
2970
+ }
2971
+ // 'retry' — just re-probe.
2972
+ renderReadinessState = { ok: false, state: 'checking' };
2973
+ paintExports(current.approvedAt);
2974
+ try {
2975
+ // `.readiness` — the route wraps it (see the tekla-readiness precedent). Reading the envelope
2976
+ // itself here left `state`/`recovery` undefined, so the card painted a readiness it did not have.
2977
+ renderReadinessState = (await api('/api/render/readiness')).readiness;
2978
+ } catch (err) {
2979
+ renderReadinessState = {
2980
+ ok: false, state: 'error',
2981
+ message: err && err.message ? err.message : 'Could not check whether rendering is available.',
2982
+ recovery: { action: 'retry', label: 'Check again' },
2983
+ };
2984
+ }
2985
+ if (current) paintExports(current.approvedAt);
2986
+ }
2987
+
2471
2988
  async function recoverTekla(action) {
2472
2989
  if (!current) return;
2473
2990
  if (action === 'open-tekla' || action === 'open-model' || action === 'retry') {
@@ -2496,8 +3013,17 @@
2496
3013
  return renderExports();
2497
3014
  }
2498
3015
 
3016
+ /**
3017
+ * `kind` may carry a variant as `kind:variant` (a render viewpoint), because a kind can now hold
3018
+ * several artifacts and Open/Reveal has to reach the one whose row was clicked — not merely the
3019
+ * most recent.
3020
+ */
2499
3021
  async function fileAction(endpoint, kind, failMsg) {
2500
- const st = exportState && exportState[kind];
3022
+ const [baseKind, variant] = String(kind).split(':');
3023
+ const row = exportState && exportState[baseKind];
3024
+ const st = variant && row && Array.isArray(row.variants)
3025
+ ? row.variants.find((v) => v.variant === variant)
3026
+ : row;
2501
3027
  if (!st || !st.path) return; // button only shows when a path exists; belt-and-braces
2502
3028
  try {
2503
3029
  await api(endpoint, { method: 'POST', body: JSON.stringify({ path: st.path }) });
@@ -2513,6 +3039,8 @@
2513
3039
  if (details) { showExportReceiptDetails(details.dataset.exportDetails, details); return; }
2514
3040
  const recovery = e.target.closest('[data-tekla-recovery]');
2515
3041
  if (recovery) { recoverTekla(recovery.dataset.teklaRecovery); return; }
3042
+ const renderFix = e.target.closest('[data-render-recovery]');
3043
+ if (renderFix) { recoverRender(renderFix.dataset.renderRecovery); return; }
2516
3044
  const exp = e.target.closest('[data-export]');
2517
3045
  if (exp && !exp.disabled) { doExport(exp.dataset.export); return; }
2518
3046
  const open = e.target.closest('[data-openfile]');