@floless/app 0.105.0 → 0.107.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: {
@@ -201,17 +221,43 @@
201
221
  ],
202
222
  },
203
223
  };
204
- const wsApp = () => (current ? WORKSPACE_APPS[current.app] : null);
205
- const appDisplayName = (id) => (WORKSPACE_APPS[id] && WORKSPACE_APPS[id].displayName) || id;
224
+ // A project names its app by the LIVE id, which a rename or a duplicate moves off the descriptor
225
+ // keys above — so resolve through the lineage ROOT the server ships beside it (`templateId`, derived
226
+ // from the app-origin store, which rename and duplicate both carry). A renamed steel-model still
227
+ // finds the steel descriptor, so its projects still open and still say "Steel model".
228
+ // • falls back to `app` for a server that predates the field, and because for a canonical app the
229
+ // two are the same string anyway;
230
+ // • `p.app` remains the LIVE id everywhere it addresses the server — the frames' ?app=, the export
231
+ // and approve routes — so this is a presentation resolution only, never a re-pointing.
232
+ const wsDescOf = (p) => (p && WORKSPACE_APPS[p.templateId || p.app]) || null;
233
+ const wsApp = () => wsDescOf(current);
234
+ /** A project's app in HUMAN words ("Steel model"), falling back to the raw id for an app we have
235
+ * no descriptor for — the only case that still reads as a slug, and it is one we can't name. */
236
+ const projectAppName = (p) => (wsDescOf(p) || {}).displayName || (p && p.app) || '';
237
+ /** The same, by DESCRIPTOR KEY — for the create cards, which name an app we have a descriptor for. */
238
+ const descDisplayName = (templateId) => (WORKSPACE_APPS[templateId] || {}).displayName || templateId;
239
+ /** Whether this project's app has been renamed or duplicated away from its built-in id. The only
240
+ * case where naming the live workflow on the card tells the user something they don't know. */
241
+ const wsRenamed = (p) => !!(p && p.templateId && p.app && p.app !== p.templateId);
206
242
  let mode = 'workflows';
207
243
  try { if (localStorage.getItem(LS_MODE) === 'workspaces') mode = 'workspaces'; } catch { /* private mode */ }
208
244
  let projects = [];
209
245
  let projectsLoadError = null; // last /api/projects failure reason, or null — an empty list means
210
246
  // "none yet" ONLY when this is null (see the empty state in renderLanding)
211
247
  let archived = []; // archived projects (the "Trash") — listed under a collapsed section on the landing
212
- // Installed workspace apps, in descriptor order. Populated from /api/apps in loadProjects():
213
- // the set = apps flagged workspace===true that ALSO have a WORKSPACE_APPS descriptor (an app
214
- // flagged workspace with no descriptor is skipped with a console note — never a broken open).
248
+ // Installed workspace apps, in descriptor order — `{ appId, templateId, ambiguous }` per entry.
249
+ // Populated from /api/apps in loadProjects(): the set = apps flagged workspace===true whose LINEAGE
250
+ // ROOT has a WORKSPACE_APPS descriptor (an app whose root we have no descriptor for is skipped with
251
+ // a console note — never a broken open).
252
+ //
253
+ // Two ids, because a rename separates them and each half is load-bearing: `appId` is the LIVE app a
254
+ // card creates on (post the descriptor key after a rename and the server rightly 404s "not
255
+ // installed"), `templateId` is the descriptor key supplying the card's copy. ONE entry per
256
+ // descriptor, preferring the canonical install: steel declares two create actions, so an entry per
257
+ // installed app would double the landing's most important surface the moment anyone duplicates a
258
+ // workflow. `ambiguous` marks a root with more than one live app behind it, so that single card can
259
+ // say which workflow it will use rather than silently picking (see renderLanding).
260
+ //
215
261
  // Drives the per-app create cards. Falls back to the descriptor keys if /api/apps can't be read.
216
262
  // Starts at the descriptor keys so the create cards are on the FIRST paint, then /api/apps narrows
217
263
  // them. Two alternatives were tried and rejected against measurements:
@@ -223,7 +269,10 @@
223
269
  // The hazard those were guarding — clicking a card for an app that isn't installed — is closed
224
270
  // where it belongs instead: POST /api/projects refuses an app with no readable source, so no
225
271
  // client's paint timing can mint an orphan project, and the click surfaces an honest error toast.
226
- let wsAppIds = Object.keys(WORKSPACE_APPS);
272
+ // The pre-/api/apps default (and the failure fallback): assume each descriptor's canonical app is
273
+ // the installed one. Unambiguous by construction — one entry per descriptor, appId === templateId.
274
+ const wsDefaultAppEntries = () => Object.keys(WORKSPACE_APPS).map((id) => ({ appId: id, templateId: id, ambiguous: false }));
275
+ let wsAppEntries = wsDefaultAppEntries();
227
276
  let current = null; // the open project (null = landing)
228
277
 
229
278
  // The open app's visible label for a step key (Model→"Model" for steel, "Traced" for vectorize) —
@@ -246,7 +295,7 @@
246
295
  // `exported` = an SVG export file exists (from the last export listing); best-known from
247
296
  // exportState, which renderExports() populates. Unknown before Exports is opened → false.
248
297
  const exported = !!(exportState && exportState.svg && exportState.svg.exportedAt);
249
- bridge.setWorkspaceGuide({ app: current.app, name: current.name, displayName: appDisplayName(current.app), approved: !!current.approvedAt, exported });
298
+ bridge.setWorkspaceGuide({ app: current.app, name: current.name, displayName: projectAppName(current), approved: !!current.approvedAt, exported });
250
299
  }
251
300
 
252
301
  // ── mode ────────────────────────────────────────────────────────────────────
@@ -357,35 +406,53 @@
357
406
  }
358
407
  if (archivedSig(archived) !== archivedBefore) renderLanding();
359
408
  // Which workspace apps to offer a create card for: those flagged workspace===true on /api/apps
360
- // that we ALSO know how to render (have a WORKSPACE_APPS descriptor). Keep descriptor order for a
361
- // stable card order. A load failure RE-WIDENS wsAppIds to the descriptor keys (the catch assigns
362
- // them): still usable, and a card for something uninstalled is refused by the server on click.
363
- const cardsBefore = wsAppIds.join(',');
409
+ // whose LINEAGE ROOT we also know how to render (have a WORKSPACE_APPS descriptor). Matching on
410
+ // the root, not the raw id, is what keeps the cards alive across a rename — a renamed steel-model
411
+ // is still flagged workspace, but under a key no descriptor answers to. /api/apps already carries
412
+ // `templateId` per app (the picker's fork/update badges read the same field), so no extra call.
413
+ // Keep descriptor order for a stable card order. A load failure RE-WIDENS the entries to the
414
+ // descriptor keys (the catch assigns them): still usable, and a card for something uninstalled is
415
+ // refused by the server on click.
416
+ const cardsSig = (entries) => entries.map((e) => `${e.appId}>${e.templateId}${e.ambiguous ? '?' : ''}`).join(',');
417
+ const cardsBefore = cardsSig(wsAppEntries);
364
418
  try {
365
419
  const { apps } = await api('/api/apps');
366
420
  if (stale()) return;
367
- const flagged = new Set((apps || []).filter((a) => a && a.workspace === true).map((a) => a.id));
368
- wsAppIds = Object.keys(WORKSPACE_APPS).filter((id) => flagged.has(id));
421
+ // Group the live workspace apps by lineage root, so one descriptor yields one card even when
422
+ // several installed apps share a root (an original plus a duplicate, say).
423
+ const byRoot = new Map();
424
+ for (const a of apps || []) {
425
+ if (!a || a.workspace !== true) continue;
426
+ const root = a.templateId || a.id;
427
+ if (!WORKSPACE_APPS[root]) {
428
+ console.warn(`[workspaces] app "${a.id}" is flagged workspace but its lineage root "${root}" has no client descriptor — skipping its create card`);
429
+ continue;
430
+ }
431
+ if (!byRoot.has(root)) byRoot.set(root, []);
432
+ byRoot.get(root).push(a.id);
433
+ }
434
+ wsAppEntries = Object.keys(WORKSPACE_APPS).filter((root) => byRoot.has(root)).map((root) => {
435
+ // Sorted, so which app a card targets is stable across loads rather than dependent on the
436
+ // order `aware app list` happened to return. The canonical install wins when present: it is
437
+ // the one the user has not deliberately made a variant of.
438
+ const ids = byRoot.get(root).slice().sort();
439
+ return { appId: ids.indexOf(root) >= 0 ? root : ids[0], templateId: root, ambiguous: ids.length > 1 };
440
+ });
369
441
  // Hardening: /api/apps loaded but flagged NONE of our known workspace apps (a transient
370
442
  // appWorkspace read blip returning false for all). Rather than render zero create cards, fall
371
443
  // back to the descriptor keys — the same usable default a full /api/apps failure lands on.
372
- if (wsAppIds.length === 0 && Object.keys(WORKSPACE_APPS).length > 0) {
373
- wsAppIds = Object.keys(WORKSPACE_APPS);
374
- }
375
- for (const a of apps || []) {
376
- if (a && a.workspace === true && !WORKSPACE_APPS[a.id]) {
377
- console.warn(`[workspaces] app "${a.id}" is flagged workspace but has no client descriptor — skipping its create card`);
378
- }
444
+ if (wsAppEntries.length === 0 && Object.keys(WORKSPACE_APPS).length > 0) {
445
+ wsAppEntries = wsDefaultAppEntries();
379
446
  }
380
447
  } catch {
381
448
  if (stale()) return;
382
449
  // /api/apps failed — fall back to the descriptor keys so the create cards still work.
383
- wsAppIds = Object.keys(WORKSPACE_APPS);
450
+ wsAppEntries = wsDefaultAppEntries();
384
451
  }
385
452
  // Second paint ONLY if /api/apps actually changed the card set. It usually confirms what the
386
453
  // previous answer already showed, and a blind repaint seconds later would blow away whatever the
387
454
  // user has since touched in the landing — an open kebab menu, the expanded Archived section.
388
- if (wsAppIds.join(',') !== cardsBefore) {
455
+ if (cardsSig(wsAppEntries) !== cardsBefore) {
389
456
  // #ws-proj-menu lives outside $landing, so the rebuild below does NOT close it — it would stay
390
457
  // pinned at the coordinates of the kebab that opened it while the grid reflows under it
391
458
  // (dropping create cards shifts every project card up), leaving it beside a different project
@@ -451,11 +518,11 @@
451
518
  `<button type="button" class="ws-import-btn" id="ws-import-project" data-tip="Restore a project from an exported .zip file">↓ Import project…</button></div>`;
452
519
  // Create affordances stay docked at the top, separate from existing projects. Drawing-first
453
520
  // entries lead; importing the current Workflows model stays last because it is a different mode.
454
- const createEntries = wsAppIds
455
- .flatMap((id) => {
456
- const d = WORKSPACE_APPS[id];
521
+ const createEntries = wsAppEntries
522
+ .flatMap((entry) => {
523
+ const d = WORKSPACE_APPS[entry.templateId];
457
524
  const actions = d && Array.isArray(d.createActions) ? d.createActions : [];
458
- return actions.map((action) => ({ id, d, action }));
525
+ return actions.map((action) => ({ entry, d, action }));
459
526
  })
460
527
  .sort((a, b) => {
461
528
  if (a.action.kind === 'current' && b.action.kind !== 'current') return 1;
@@ -464,31 +531,53 @@
464
531
  });
465
532
  if (createEntries.length) {
466
533
  html += `<div class="ws-create-grid">`;
467
- for (const { id, action } of createEntries) {
534
+ for (const { entry, action } of createEntries) {
468
535
  const isDrawing = action.kind === 'drawing';
536
+ // Name the target workflow ONLY when the root has more than one live app behind it, so the
537
+ // ordinary card stays clean and the extra line means something wherever it does appear. It
538
+ // must also go on the aria-label: the button's own aria-label REPLACES the accessible name
539
+ // computed from its children, so a descendant span alone is silent to a screen reader.
540
+ const target = entry.ambiguous ? entry.appId : '';
469
541
  html += `<button type="button" class="ws-seed${isDrawing ? ' ws-seed-drop' : ''}" ` +
470
- `aria-label="${escapeAttr(action.label || action.headline)}" ` +
471
- `data-seed-app="${escapeAttr(id)}" data-seed-action="${escapeAttr(action.kind)}"` +
472
- (isDrawing ? ` data-seed-drop="${escapeAttr(id)}"` : '') +
542
+ `aria-label="${escapeAttr((action.label || action.headline) + (target ? ` (on the ${target} workflow)` : ''))}" ` +
543
+ `data-seed-app="${escapeAttr(entry.appId)}" data-seed-template="${escapeAttr(entry.templateId)}" data-seed-action="${escapeAttr(action.kind)}"` +
544
+ (isDrawing ? ` data-seed-drop="${escapeAttr(entry.appId)}"` : '') +
473
545
  `>` +
474
546
  `<span class="plus">+</span>` +
475
547
  `<span class="ws-seed-headline">${escapeHtml(action.headline)}</span>` +
476
548
  (action.capability ? `<span class="ws-seed-capability">${escapeHtml(action.capability)}</span>` : '') +
477
549
  `<span class="ws-seed-sub">${escapeHtml(action.sub)}</span>` +
550
+ (target
551
+ ? `<span class="ws-seed-target" data-tip="You have more than one of these workflows installed.\nThis card creates on:\n${escapeAttr(target)}">On ${escapeHtml(target)}</span>`
552
+ : '') +
478
553
  `</button>`;
479
554
  }
480
555
  html += `</div>`;
481
556
  }
482
557
  html += `<div class="ws-grid">`;
483
558
  for (const p of projects) {
484
- const d = WORKSPACE_APPS[p.app];
485
- const displayApp = appDisplayName(p.app);
559
+ const d = wsDescOf(p);
560
+ const displayApp = projectAppName(p);
486
561
  const projectCapability = d && d.projectCapability ? d.projectCapability : '';
562
+ // The badge says what KIND of document this is — a renamed steel-model is still a Steel model,
563
+ // so it keeps saying so. The live workflow name is added beside it only when it DIFFERS from the
564
+ // built-in, where it is the one thing the badge can no longer tell you; an ordinary card renders
565
+ // no workflow name at all and reads exactly as before (the markup around it is restructured, so
566
+ // the RENDERED TEXT is what is unchanged, not the HTML). Mono + dim is this app's established
567
+ // "technical identifier, not prose" treatment (.rtn-wf, .wf-option-meta, and the timestamp .t
568
+ // right next to it), which keeps it from reading as a second capability line. The full value
569
+ // rides in the tip because the slug is the part that gets abbreviated when room runs out.
570
+ // Every segment is its own element so the layout can say which ones may be abbreviated and which
571
+ // may not — see .ws-meta-app. The separators stay real TEXT (not CSS ::before) so the line still
572
+ // reads as "Trace · westfield-trace · 2 h ago" to a screen reader and to a copy-paste.
573
+ const wfName = wsRenamed(p)
574
+ ? `<span class="ws-sep"> · </span><span class="ws-meta-wf" data-tip="The workflow this project runs on:\n${escapeAttr(p.app)}">${escapeHtml(p.app)}</span>`
575
+ : '';
487
576
  html += `<div class="ws-card" role="button" tabindex="0" data-open="${escapeAttr(p.id)}">` +
488
577
  `<span class="ws-thumb"><span class="ws-kind">${escapeHtml(displayApp)}</span>▦</span>` +
489
578
  `<span class="ws-body"><span><span class="ws-name">${escapeHtml(p.name)}</span>` +
490
579
  (projectCapability ? `<span class="ws-meta">${escapeHtml(projectCapability)}</span>` : '') +
491
- `<span class="ws-meta">${escapeHtml(displayApp)} · <span class="t">${escapeHtml(relAgo(p.updatedAt))}</span></span></span>` +
580
+ `<span class="ws-meta ws-meta-app"><span class="ws-meta-kind">${escapeHtml(displayApp)}</span>${wfName}<span class="ws-sep"> · </span><span class="t">${escapeHtml(relAgo(p.updatedAt))}</span></span></span>` +
492
581
  `<button type="button" class="ws-kebab" data-kebab="${escapeAttr(p.id)}" aria-label="Project actions" data-tip="Rename · Duplicate · Export · Archive">⋯</button>` +
493
582
  `</span></div>`;
494
583
  }
@@ -518,11 +607,16 @@
518
607
  if (archived.length) {
519
608
  let rows = '';
520
609
  for (const p of archived) {
521
- const displayApp = appDisplayName(p.app);
610
+ const displayApp = projectAppName(p);
611
+ // Tooltip only, deliberately: the Trash is a scan-and-act list where the user's own project
612
+ // NAME is the identifier (it doesn't even carry projectCapability), and a third clause on an
613
+ // already-compact dim line works against that. The disambiguating value lands where it is
614
+ // actionable — the live grid, one Restore away.
615
+ const wfTip = wsRenamed(p) ? ` data-tip="The workflow this project runs on:\n${escapeAttr(p.app)}"` : '';
522
616
  rows += `<div class="ws-archived-row">` +
523
617
  `<span class="ws-archived-info">` +
524
618
  `<span class="ws-archived-name">${escapeHtml(p.name)}</span>` +
525
- `<span class="ws-archived-meta">${escapeHtml(displayApp)} · archived <span class="t">${escapeHtml(relAgo(p.updatedAt))}</span></span>` +
619
+ `<span class="ws-archived-meta"${wfTip}>${escapeHtml(displayApp)} · archived <span class="t">${escapeHtml(relAgo(p.updatedAt))}</span></span>` +
526
620
  `</span>` +
527
621
  `<span class="ws-archived-actions">` +
528
622
  `<button type="button" class="btn-mini ws-restore" data-restore="${escapeAttr(p.id)}" data-tip="Un-archive — returns to the live grid">↺ Restore</button>` +
@@ -552,12 +646,16 @@
552
646
  if (card) { openProject(card.dataset.open); return; }
553
647
  const seed = e.target.closest('[data-seed-app]');
554
648
  if (seed) {
555
- const id = seed.dataset.seedApp;
556
- const d = WORKSPACE_APPS[id];
557
- if (d && seed.dataset.seedAction === 'drawing') {
649
+ // Two ids, and they are not interchangeable: create on the LIVE app (`seed-app`), but look the
650
+ // descriptor up by its lineage ROOT (`seed-template`) — after a rename the live id answers to no
651
+ // descriptor, and the built-in id answers to no installed app.
652
+ const appId = seed.dataset.seedApp;
653
+ const templateId = seed.dataset.seedTemplate || appId;
654
+ if (!WORKSPACE_APPS[templateId]) return;
655
+ if (seed.dataset.seedAction === 'drawing') {
558
656
  const files = await pickDrawingFiles($seedFile); // drop-a-drawing: open the picker
559
- if (files.length) createFromDrawing(id, files);
560
- } else createSeeded(id); // takeoff import
657
+ if (files.length) createFromDrawing(appId, templateId, files);
658
+ } else createSeeded(appId, templateId); // takeoff import
561
659
  }
562
660
  });
563
661
  $landing.addEventListener('keydown', (e) => {
@@ -595,7 +693,8 @@
595
693
  e.preventDefault();
596
694
  zone.classList.remove('drag-over');
597
695
  const files = Array.from((e.dataTransfer && e.dataTransfer.files) || []);
598
- if (files.length) createFromDrawing(zone.dataset.seedDrop, files);
696
+ // Same two ids as the click path — the dropzone IS the seed button, so it carries both.
697
+ if (files.length) createFromDrawing(zone.dataset.seedDrop, zone.dataset.seedTemplate || zone.dataset.seedDrop, files);
599
698
  });
600
699
 
601
700
  async function promptName(title, label, value) {
@@ -604,14 +703,16 @@
604
703
  return res && typeof res.name === 'string' && res.name.trim() ? res.name.trim() : null;
605
704
  }
606
705
 
607
- async function createSeeded(appId) {
706
+ // `appId` is the LIVE app to create on; `templateId` its lineage root, which supplies the wording.
707
+ // They differ whenever the workflow has been renamed or duplicated — see the seed-card comment.
708
+ async function createSeeded(appId, templateId) {
608
709
  const name = await promptName('New project', 'Name this project', '');
609
710
  if (!name) return;
610
711
  try {
611
712
  const { project, seeded } = await api('/api/projects', { method: 'POST', body: JSON.stringify({ name, app: appId, seedFromApp: true }) });
612
713
  // Tell the truth about the import: seeded=false means there was no current model to copy
613
714
  // (or it was unreadable) — the project is EMPTY, don't imply the model came across.
614
- const seedLabel = (WORKSPACE_APPS[appId] && WORKSPACE_APPS[appId].seedLabel) || 'model';
715
+ const seedLabel = (WORKSPACE_APPS[templateId] && WORKSPACE_APPS[templateId].seedLabel) || 'model';
615
716
  if (seeded) showToast(`Project "${project.name}" created from the current ${seedLabel}`, 'ok');
616
717
  else showToast(`Project "${project.name}" created — empty (no current ${seedLabel} to import)`, 'warn');
617
718
  track('workspace_project_created', { app: appId }); // takeoff-import create path
@@ -625,10 +726,10 @@
625
726
  // v1. ROLLBACK on cancel/error — if the user cancels the name prompt, or the file can't be read,
626
727
  // AFTER the row is created, archive the empty project so no dead, openable project is left
627
728
  // behind (the row is created before the source exists — spec §4.1).
628
- async function createFromDrawing(appId, files) {
729
+ async function createFromDrawing(appId, templateId, files) {
629
730
  // Ask for the name FIRST (before creating a row) so the common "cancel the prompt" path never
630
731
  // creates anything to roll back.
631
- const name = await promptName(`New ${appDisplayName(appId)} project`, 'Name this project', '');
732
+ const name = await promptName(`New ${descDisplayName(templateId)} project`, 'Name this project', '');
632
733
  if (!name) return;
633
734
  let project;
634
735
  try {
@@ -676,23 +777,39 @@
676
777
  let p = projects.find((x) => x.id === id);
677
778
  if (!p) { try { p = (await api('/api/projects')).projects.find((x) => x.id === id); } catch { /* fall through */ } }
678
779
  if (!p) { showToast('Project not found — it may have been archived.', 'warn'); return loadProjects(); }
679
- // Never a broken open (spec §3.2): a project whose app has no client descriptor (uninstalled or
680
- // renamed workspace app) can't be rendered — toast and bail BEFORE mutating any view state,
681
- // matching the create-card skip. wsApp() would return null for it and the frame wiring would fail.
682
- if (!WORKSPACE_APPS[p.app]) { showToast('This project’s app isn’t available as a workspace.', 'warn'); return; }
780
+ // Never a broken open (spec §3.2): a project whose app has no client descriptor can't be rendered
781
+ // — toast and bail BEFORE mutating any view state, matching the create-card skip. wsApp() would
782
+ // return null for it and the frame wiring would fail.
783
+ //
784
+ // Resolving through the lineage root took RENAMED and DUPLICATED apps out of this branch, which is
785
+ // the whole point of that change — so what remains is the genuinely unknown app: a workspace app
786
+ // we ship no descriptor for. The copy therefore names that, and says what can be done about it,
787
+ // rather than describing a state the user can no longer get themselves into by renaming.
788
+ if (!wsDescOf(p)) {
789
+ showToast('Workspaces has no view for this project’s app yet — ask the AI to add one.', 'warn');
790
+ return;
791
+ }
683
792
  current = p;
684
793
  exportState = null;
685
794
  teklaReadinessState = null;
795
+ renderReadinessState = null;
686
796
  track('workspace_project_opened', { app: p.app }); // a real open (card click or post-create landing)
687
797
  lastRevState = 'none'; stopRevisionPoll(); // fresh project — drop any prior revision-poll state
798
+ // Per-project, like everything above it: never let one project's answer describe another's. Not
799
+ // observable today (every history render is preceded by a fetch that sets it, and a failed fetch
800
+ // renders no rows), but leaving a stale cross-project value in place is the shape of bug this
801
+ // file resets state to avoid — and the next path that renders rows would inherit it.
802
+ histDiffSupported = false;
688
803
  $projName.textContent = p.name;
689
804
  $crumbName.textContent = p.name;
690
- $status.textContent = appDisplayName(p.app);
805
+ $status.textContent = projectAppName(p);
691
806
  // Lazily src the frames once per project; switching steps only toggles hidden so the
692
807
  // editor's state survives a Source⇄Traced round-trip. Frame URLs come from the app descriptor:
693
808
  // the 'model' frame loads the app's editor; the 'drawings' frame loads its filter (steel) OR is
694
809
  // left empty when the app has no filter step (vectorize — its Source step shows a placeholder).
695
- const d = WORKSPACE_APPS[p.app]; // guaranteed present — the guard above bailed on an unknown app
810
+ const d = wsDescOf(p); // guaranteed present — the guard above bailed on an unknown app
811
+ // The LIVE app id, deliberately: the frames address the server with it (contract reads, saves),
812
+ // and after a rename only the live id resolves. Only the descriptor came from the lineage root.
696
813
  const qs = `?app=${encodeURIComponent(p.app)}&project=${encodeURIComponent(p.id)}`;
697
814
  frames.model.dataset.want = `${d.editor}${qs}`;
698
815
  frames.drawings.dataset.want = d.filter ? `${d.filter}${qs}` : '';
@@ -707,6 +824,7 @@
707
824
  current = null;
708
825
  exportState = null;
709
826
  teklaReadinessState = null;
827
+ renderReadinessState = null;
710
828
  stopRevisionPoll();
711
829
  stopKnowledgePoll(); kbCloseConfirm(); kbResetViewer(); knowledgeState = null; // the KB pane is per-project — never carry it across
712
830
  lastRevState = 'none'; $revisionCard.hidden = true; closeProjMenu(); applyMode(); syncWorkspaceGuide();
@@ -792,11 +910,11 @@
792
910
  if (stillOpen && !$wsHistory.hidden && res && res.version && Number.isInteger(Number(res.version.n))) {
793
911
  expandDiffOnce = { projectId: approvingProject.id, n: Number(res.version.n) };
794
912
  }
795
- showToast(`Approved — "${approvingProject.name}" is baked into ${appDisplayName(approvingProject.app)}`, 'ok');
913
+ showToast(`Approved — "${approvingProject.name}" is baked into ${projectAppName(approvingProject)}`, 'ok');
796
914
  track('workspace_project_approved', { app: approvingProject.app }); // a successful sign-off
797
915
  // First Approve for this app calms the "✦ Start here" beacon (the document-archetype
798
916
  // analog of a workflow's first Run); ticks the Review + Approve guide rows.
799
- if (bridge.markWorkspaceApproved && WORKSPACE_APPS[approvingProject.app]?.docGuide) {
917
+ if (bridge.markWorkspaceApproved && wsDescOf(approvingProject)?.docGuide) {
800
918
  bridge.markWorkspaceApproved(approvingProject.app);
801
919
  }
802
920
  if (stillOpen) {
@@ -1995,16 +2113,168 @@
1995
2113
 
1996
2114
  // The POST export endpoint for a card kind, project-scoped so it reads THIS project's contract
1997
2115
  // and writes into its own exports folder.
1998
- function exportUrl(kind) {
1999
- const qs = `?project=${encodeURIComponent(current.id)}`;
2000
- 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)}`;
2001
2127
  if (kind === 'bom-csv') return `${base}/export-bom/csv${qs}`;
2002
2128
  if (kind === 'bom-xlsx') return `${base}/export-bom/xlsx${qs}`;
2003
2129
  if (kind === 'ifc') return `${base}/export-ifc${qs}`;
2004
2130
  if (kind === 'svg') return `${base}/export-svg${qs}`;
2131
+ if (kind === 'render') return `${base}/render${qs}`;
2005
2132
  return `${base}/export-tekla${qs}`; // tekla
2006
2133
  }
2007
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
+
2008
2278
  const receiptKey = (kind) => `${current ? current.id : ''}:${kind}`;
2009
2279
 
2010
2280
  function receiptItemText(prefix, value) {
@@ -2049,6 +2319,153 @@
2049
2319
  // one here would imply a revoke story that does not exist yet.
2050
2320
  const shareLinks = new Map();
2051
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
+
2052
2469
  // The share card's state, same {meta, disabled, tip} shape as teklaCardState. It is the second
2053
2470
  // file:false export kind, and the first whose RESULT is a URL rather than a file.
2054
2471
  function shareCardState(approved) {
@@ -2116,7 +2533,8 @@
2116
2533
  // The two file:false kinds resolve their own status; everything else uses the file/receipt path
2117
2534
  // below. `special` keeps the branches from growing a third arm each time a kind is added.
2118
2535
  const special = c.kind === 'tekla' ? teklaCardState(approved)
2119
- : c.kind === 'share-3d' ? shareCardState(approved) : null;
2536
+ : c.kind === 'share-3d' ? shareCardState(approved)
2537
+ : c.kind === 'render' ? renderCardState(approved) : null;
2120
2538
  if (special) {
2121
2539
  meta = special.meta;
2122
2540
  } else if (!approved) {
@@ -2140,18 +2558,37 @@
2140
2558
  // Re-labelled once a link exists, mirroring the file kinds' "Re-export" convention. Gated on the
2141
2559
  // in-memory record rather than exportState, which only ever tracks file exports.
2142
2560
  const shared = approved && c.kind === 'share-3d' && shareLinks.has(`${current.id}:share-3d`);
2143
- const busyLabel = c.kind === 'tekla' ? 'Sending…' : c.kind === 'share-3d' ? 'Creating…' : 'Exporting…';
2144
- const label = busy ? busyLabel : (exported || shared ? (c.kind === 'share-3d' ? 'Create new link' : 'Re-export') : c.verb);
2145
- 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);
2146
2574
  const busyTip = c.kind === 'tekla' ? 'Sending the approved model to Tekla'
2147
- : 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';
2148
2578
  const tip = busy ? busyTip
2579
+ : renderHolding ? 'Waiting for the render to finish — it holds this project while it runs'
2149
2580
  : special ? special.tip : (approved ? '' : 'Approve this version first');
2150
2581
  const dis = `${disabled && !busy ? ' disabled' : ''}${busy ? ' aria-disabled="true" aria-busy="true"' : ''}${tip ? ` data-tip="${escapeAttr(tip)}"` : ''}`;
2151
2582
  return `<div class="ecard">` +
2152
2583
  `<div class="e-top"><div class="e-ico">${escapeHtml(c.ico)}</div>` +
2153
2584
  `<div><div class="e-name">${escapeHtml(c.name)}</div><div class="e-fmt">${escapeHtml(c.fmt)}</div></div></div>` +
2154
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
+ : '') +
2155
2592
  receiptHtml(c.kind, approved) +
2156
2593
  `<div class="e-act"><button type="button" data-export="${escapeAttr(c.kind)}"${dis}>↗ ${escapeHtml(label)}</button></div>` +
2157
2594
  `</div>`;
@@ -2163,6 +2600,7 @@
2163
2600
  'data-reveal',
2164
2601
  'data-export-details',
2165
2602
  'data-tekla-recovery',
2603
+ 'data-render-recovery',
2166
2604
  'data-copyshare', // the share-link Copy button — omitted here, a repaint mid-render steals its focus
2167
2605
  ];
2168
2606
 
@@ -2206,21 +2644,68 @@
2206
2644
  const cards = (wsApp() && wsApp().exports) || [];
2207
2645
  html += '<div class="export-grid">' + cards.map((c) => cardHtml(c, approved)).join('') + '</div>';
2208
2646
  $wsExports.innerHTML = html;
2647
+ paintRenderThumb();
2209
2648
  restoreExportFocus(restoreIdentity);
2210
2649
  }
2211
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
+
2212
2676
  async function renderExports() {
2213
2677
  if (!current) return;
2214
2678
  const id = current.id, app = current.app;
2215
2679
  const cards = (wsApp() && wsApp().exports) || [];
2216
2680
  const hasTekla = cards.some((card) => card.kind === 'tekla');
2681
+ const hasRender = cards.some((card) => card.kind === 'render');
2217
2682
  teklaReadinessState = hasTekla ? { ok: false, state: 'checking' } : null;
2683
+ renderReadinessState = hasRender ? { ok: false, state: 'checking' } : null;
2218
2684
  paintExports(current.approvedAt);
2219
2685
  let state = null;
2220
2686
  let approvedAt = current.approvedAt; // fallback if the fetch fails (best-known)
2221
2687
  const exportPromise = api(`/api/contract/${encodeURIComponent(app)}/exports?project=${encodeURIComponent(id)}`);
2222
2688
  const readinessPromise = hasTekla ? api('/api/tekla-readiness') : Promise.resolve(null);
2223
- 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
+ }
2224
2709
  if (exportResult.status === 'fulfilled') {
2225
2710
  const r = exportResult.value;
2226
2711
  state = {};
@@ -2259,6 +2744,30 @@
2259
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
2260
2745
  const busyKey = `${projectId}:${kind}`;
2261
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
+
2262
2771
  exportBusy.add(busyKey);
2263
2772
  // The delegated click can report BODY as active by the time this synchronous repaint runs.
2264
2773
  // Carry the activated kind through the first replacement explicitly; later repaints infer
@@ -2318,8 +2827,17 @@
2318
2827
  }
2319
2828
  return;
2320
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;
2321
2836
  try {
2322
- 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' });
2323
2841
  track('workspace_export', { app, kind }); // a successful export/bake (e.g. { app:'vectorize', kind:'svg' })
2324
2842
  if (res.counts) exportReceipts.set(`${projectId}:${kind}`, {
2325
2843
  counts: res.counts,
@@ -2339,18 +2857,49 @@
2339
2857
  : `Exported — ${res.filename || kind}`,
2340
2858
  summary && summary.partial ? 'warn' : 'ok');
2341
2859
  }
2342
- 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
+ });
2343
2868
  } catch (err) {
2344
2869
  // The durable export listing may still show the previously published file, but its in-session
2345
2870
  // receipt must not masquerade as the result of this failed attempt.
2346
2871
  exportReceipts.delete(`${projectId}:${kind}`);
2347
2872
  const needsTekla = err && err.body && err.body.needsTekla;
2348
2873
  if (kind === 'tekla' && err && err.body && err.body.readiness) teklaReadinessState = err.body.readiness;
2349
- 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');
2350
2890
  if (kind === 'tekla' && current && current.id === projectId) paintExports(current.approvedAt);
2351
2891
  } finally {
2352
2892
  exportBusy.delete(busyKey);
2353
- 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();
2354
2903
  }
2355
2904
  }
2356
2905
 
@@ -2372,6 +2921,70 @@
2372
2921
  });
2373
2922
  }
2374
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
+
2375
2988
  async function recoverTekla(action) {
2376
2989
  if (!current) return;
2377
2990
  if (action === 'open-tekla' || action === 'open-model' || action === 'retry') {
@@ -2400,8 +3013,17 @@
2400
3013
  return renderExports();
2401
3014
  }
2402
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
+ */
2403
3021
  async function fileAction(endpoint, kind, failMsg) {
2404
- 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;
2405
3027
  if (!st || !st.path) return; // button only shows when a path exists; belt-and-braces
2406
3028
  try {
2407
3029
  await api(endpoint, { method: 'POST', body: JSON.stringify({ path: st.path }) });
@@ -2417,6 +3039,8 @@
2417
3039
  if (details) { showExportReceiptDetails(details.dataset.exportDetails, details); return; }
2418
3040
  const recovery = e.target.closest('[data-tekla-recovery]');
2419
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; }
2420
3044
  const exp = e.target.closest('[data-export]');
2421
3045
  if (exp && !exp.disabled) { doExport(exp.dataset.export); return; }
2422
3046
  const open = e.target.closest('[data-openfile]');
@@ -2606,6 +3230,12 @@
2606
3230
  };
2607
3231
 
2608
3232
  let versions = []; // last-rendered ledger (newest first)
3233
+ // Whether the semantic comparison applies to THIS project — the SERVER's answer, so the rule lives
3234
+ // in one place instead of being duplicated here. Today that answer is "is this app steel-model",
3235
+ // decided from the live app id; it is NOT contract-type aware (that work is deferred — see
3236
+ // `appSupportsDiff`'s header server-side). Set on every versions fetch; the conservative default is
3237
+ // false so a failed or never-run fetch shows no toggle rather than a dead one.
3238
+ let histDiffSupported = false;
2609
3239
  let expandDiffOnce = null; // { projectId, n }: successful Approve opens only that project's new row
2610
3240
 
2611
3241
  function changeCellHtml(v, canDiff) {
@@ -2638,11 +3268,18 @@
2638
3268
  const action = v.current
2639
3269
  ? ''
2640
3270
  : `<button type="button" class="btn-mini" data-rollback="${escapeAttr(String(v.n))}" data-tip="Restore this version as a new version">↺ Rollback</button>`;
2641
- // "What changed" disclosure — only when the app HAS a semantic diff (steel; wsApp().diff) AND the
2642
- // version has a predecessor (n>1). v1 is the baseline, and a no-diff app (vectorize) gets NO toggle
2643
- // on ANY row — an ABSENT control, never a disabled one (spec §4.4, mirroring the v1-baseline branch).
3271
+ // "What changed" disclosure — only when the semantic diff APPLIES and the version has a
3272
+ // predecessor (n>1). v1 is the baseline, and a no-diff app (vectorize) gets NO toggle on ANY row —
3273
+ // an ABSENT control, never a disabled one (spec §4.4, mirroring the v1-baseline branch).
3274
+ //
3275
+ // `histDiffSupported` is the SERVER's answer (`diffSupported` on the versions response) rather
3276
+ // than this side's own reading of the app descriptor. Not because the server currently knows
3277
+ // more — it applies the same "is this steel-model" rule — but because TWO copies of one rule
3278
+ // drift, and when they drift this way the user gets a "View detailed changes" control that then
3279
+ // answers 409: an affordance they can never satisfy. One answer, from the side that also owns the
3280
+ // refusal. Defaults to the descriptor when the field is absent (an older server).
2644
3281
  const isApprovalBaseline = v.kind === 'approve' && v.changeSummary && v.changeSummary.from == null;
2645
- const canDiff = !!(wsApp() && wsApp().diff) && Number(v.n) > 1 && !isApprovalBaseline;
3282
+ const canDiff = histDiffSupported && Number(v.n) > 1 && !isApprovalBaseline;
2646
3283
  const verRow = `<tr class="${v.current ? 'current' : ''}" data-ver="${escapeAttr(String(v.n))}">` +
2647
3284
  `<td><span class="ver${v.current ? ' cur' : ''}">v${escapeHtml(String(v.n))}</span></td>` +
2648
3285
  `<td class="htime">${escapeHtml(histWhen(v.ts))}</td>` +
@@ -2669,6 +3306,8 @@
2669
3306
  try {
2670
3307
  const r = await api(`/api/projects/${encodeURIComponent(id)}/versions`);
2671
3308
  rows = Array.isArray(r.versions) ? r.versions : [];
3309
+ // Absent on an older server → fall back to the descriptor, which is the pre-change behaviour.
3310
+ histDiffSupported = typeof r.diffSupported === 'boolean' ? r.diffSupported : !!(wsApp() && wsApp().diff);
2672
3311
  approvedAt = r.approvedAt || undefined;
2673
3312
  current.approvedAt = approvedAt; // re-sync — an in-editor autosave clears the sign-off server-side
2674
3313
  } catch (err) {
@@ -3241,7 +3880,7 @@
3241
3880
  const rows = projects.slice().sort((a, b) => a.name.localeCompare(b.name));
3242
3881
  let html = rows.map((p) => {
3243
3882
  const pid = escapeAttr(p.id);
3244
- const displayApp = appDisplayName(p.app);
3883
+ const displayApp = projectAppName(p);
3245
3884
  const meta = `${escapeHtml(displayApp)} · ${escapeHtml(relAgo(p.updatedAt))}`;
3246
3885
  // A PURE SWITCHER: no per-row Rename/Duplicate/Archive icons — project MANAGEMENT lives only on
3247
3886
  // the landing cards' ⋯ menu (a picker that only lets you switch has one predictable affordance