@floless/app 0.154.0 → 0.155.1

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.
Files changed (47) hide show
  1. package/dist/floless-server.cjs +49502 -37986
  2. package/dist/schemas/steel.model.v2.schema.json +19 -5
  3. package/dist/skills/floless-app-onboarding/SKILL.md +22 -13
  4. package/dist/skills/floless-app-onboarding/references/floless-surfaces.md +12 -8
  5. package/dist/skills/floless-app-steel-model/SKILL.md +23 -2
  6. package/dist/skills/floless-app-steel-takeoff/SKILL.md +158 -65
  7. package/dist/skills/floless-app-workflows/SKILL.md +23 -5
  8. package/dist/skills/floless-app-workflows/references/blender-exec.md +183 -0
  9. package/dist/skills/floless-app-workflows/references/dev-server-and-run-trace.md +27 -12
  10. package/dist/templates/blender-construction-sequence.flo +96 -0
  11. package/dist/web/agents.js +33 -13
  12. package/dist/web/app.css +275 -33
  13. package/dist/web/aware.js +745 -82
  14. package/dist/web/chat-question-card.js +477 -0
  15. package/dist/web/chat.css +177 -12
  16. package/dist/web/chat.js +1537 -717
  17. package/dist/web/commands-shell.js +424 -7
  18. package/dist/web/commands-steel.js +105 -4
  19. package/dist/web/guide.js +4 -3
  20. package/dist/web/index.html +96 -7
  21. package/dist/web/instructor.js +10 -9
  22. package/dist/web/left-pane.js +40 -3
  23. package/dist/web/media-player.js +234 -0
  24. package/dist/web/model-editor-contract.js +2 -0
  25. package/dist/web/model-editor-revit-adapter.js +1 -0
  26. package/dist/web/model-editor-steel-adapter.js +89 -1
  27. package/dist/web/model-panel-bridge.js +16 -2
  28. package/dist/web/model-view-query.js +590 -0
  29. package/dist/web/model-viewport-revit-adapter.js +15 -1
  30. package/dist/web/model-viewport-toolbar.js +5 -2
  31. package/dist/web/pages.js +592 -0
  32. package/dist/web/panels.js +2 -1
  33. package/dist/web/revit-editor.js +181 -16
  34. package/dist/web/run-progress.js +193 -0
  35. package/dist/web/run-strip.js +173 -0
  36. package/dist/web/steel-3d-core.js +70 -0
  37. package/dist/web/steel-editor.html +2751 -219
  38. package/dist/web/steel-frames-core.js +958 -0
  39. package/dist/web/steel-last-seen.js +315 -0
  40. package/dist/web/steel-marks-core.js +530 -0
  41. package/dist/web/steel-model-slim.js +95 -0
  42. package/dist/web/steel-model-v2-client-validation.js +14 -2
  43. package/dist/web/steel-model-v2-commands.js +258 -27
  44. package/dist/web/steel-model-v2-projection.js +78 -18
  45. package/dist/web/steel-read-confidence.js +11 -2
  46. package/dist/web/workspaces.js +416 -26
  47. package/package.json +3 -2
@@ -30,7 +30,8 @@ import { createModelPanelBridge, createModelSelectionOriginGuard, createPanelHos
30
30
  import { mountModelDisplayUnits } from './model-display-units.js';
31
31
  import { formatModelProperty, teklaObjectFields, teklaObjectLabel, teklaPropertyGroups, teklaTypeGroups } from './model-property-display.js';
32
32
  import { formatLength, parseLengthMm } from './display-units.js';
33
- import { teklaAssemblyMembership, teklaGeometrySelection } from './model-tekla-selection.js';
33
+ import { TEKLA_GEOMETRY_SELECTION_CAP, teklaAssemblyMembership, teklaGeometrySelection } from './model-tekla-selection.js';
34
+ import { displayNeedsSelection, dominantColour, evaluateModelViewQuery, objectFact, parseModelViewCommand, propertyFact } from './model-view-query.js';
34
35
  import { modelSubjectLabel, renderChatQuestions, subjectLabelText, subjectsKeyOf } from './model-chat-questions.js';
35
36
 
36
37
  const $ = (id) => document.getElementById(id);
@@ -89,6 +90,9 @@ let revisionLoadToken = 0;
89
90
  let revisionLoadController = null;
90
91
  // The revision shown and the source file it was read from: what a chat question about these objects is kept against.
91
92
  let loadedRevisionId = null, loadedSourceDigest = null;
93
+ // #2255: an AI view command is applied only to the view it was claimed for. A new session starts with every revision
94
+ // load, and `viewerLoading` is true while one runs (cleared only by the load that set it).
95
+ let viewerSessionId = crypto.randomUUID(), viewerLoading = false;
92
96
  const MODEL_VIEWER_MAX_TILE_BYTES = 256 * 1024 * 1024;
93
97
  const MODEL_VIEWER_MAX_AGGREGATE_BYTES = MODEL_VIEWER_MAX_TILE_BYTES + (128 * 1024 * 1024 * 5);
94
98
  const editorStateRecovery = createModelEditorStateRecoveryStore({
@@ -170,6 +174,7 @@ function modelPanelSnapshot() {
170
174
  || displayUnitControl?.units?.();
171
175
  const displayGridLength = (mm) => `${formatLength(mm, displayedUnits)}${displayedUnits === 'mm' ? ' mm' : ''}`;
172
176
  return { context: $('modelName')?.textContent || 'Project model', selectedId, selectedIds: [...selectedIds], selectionOrigin,
177
+ viewer: { projectId, source: subjectSource, revision: loadedRevisionId, sourceDigest: loadedSourceDigest, viewerSessionId, loading: viewerLoading },
173
178
  ...(isTeklaParser ? { focusEntityId: selectedId, geometrySelectionIds: [...geometrySelectionIds] } : {}),
174
179
  ...(gridEntity && Array.isArray(gridLevels) && gridLevels.length ? { gridVisibility: {
175
180
  entityId: gridEntity.id,
@@ -324,6 +329,7 @@ function inspect(id, syncViewport = true, publish = true, origin = 'tree') {
324
329
  selectedId = id;
325
330
  selectionOrigin = origin;
326
331
  if (syncViewport) selectedIds = id ? [id] : [];
332
+ if (isTeklaParser && dropStaleFollowedRow(selectedIds) && publish) modelPanelBridge?.publishSnapshot();
327
333
  window.__revitInstructorState = { ...(window.__revitInstructorState || {}), selected: id };
328
334
  if (syncViewport) {
329
335
  if (id) clipSession?.clearSelection?.();
@@ -357,7 +363,17 @@ function inspect(id, syncViewport = true, publish = true, origin = 'tree') {
357
363
  return true;
358
364
  }
359
365
 
360
- function selectTeklaObjects(id, ids, visibleOnly = false) {
366
+ /** A list click's selection in the Revit viewer: the rows clicked, shown in 3D; `fit` frames them (the AI's selection). */
367
+ function selectRevitEntities(id, ids, fit = false, origin = 'tree') {
368
+ if (!ids.every((each) => entityById.has(each))) return false;
369
+ selectedIds = [...ids]; if (ids.length) clipSession?.clearSelection?.();
370
+ selectionOriginGuard.run(() => viewport.setSelection({ ids }));
371
+ const result = inspect(ids.includes(id) ? id : (ids.at(-1) ?? null), false, false, origin);
372
+ if (fit && ids.length) facade.dispatch('model.fit-selection');
373
+ return result;
374
+ }
375
+
376
+ function selectTeklaObjects(id, ids, visibleOnly = false, fit = true, origin = 'tree') {
361
377
  if (!ids.every((each) => entityById.has(each))) return false;
362
378
  const visible = visibleOnly
363
379
  ? new Set((viewport.selectionTools?.allHits() || []).map((hit) => hit.entity.sourceId)) : null;
@@ -371,12 +387,138 @@ function selectTeklaObjects(id, ids, visibleOnly = false) {
371
387
  if (ids.length) clipSession?.clearSelection?.();
372
388
  selectionOriginGuard.run(() => viewport.setSelection({ ids: geometryIds }));
373
389
  const selected = ids.includes(id) ? id : (ids.at(-1) ?? null);
374
- const result = inspect(selected, false, true, 'tree');
375
- if (geometryIds.length) facade.dispatch('model.fit-selection');
390
+ const result = inspect(selected, false, true, origin);
391
+ if (geometryIds.length) { if (fit) facade.dispatch('model.fit-selection'); }
376
392
  else if (ids.length) toast(visibleOnly ? 'This type has no visible geometry to select.' : 'This object has no verified geometry to frame.');
377
393
  return result;
378
394
  }
379
395
 
396
+ /* -- AI Chat's view command (#2255) ------------------------------------------------------------------------------------
397
+ The AI's structured query, evaluated over the objects this viewer already holds and applied through the paths a list
398
+ click and the toolbar use. Synchronous from its first check to its last change, so a revision switch, a reload or
399
+ another command can never land in the middle. The result is this viewer's report; the server checks its shape. */
400
+ const VIEWER_DISPLAY_MODES = Object.freeze(['wire', 'xray', 'solid', 'realistic']);
401
+
402
+ function viewCandidates() {
403
+ const colours = viewport?.entityColours?.() ?? new Map();
404
+ const candidates = [];
405
+ for (const entity of entities) {
406
+ if (entity?.structuralGrid?.mapping?.kind === 'symmetric') continue;
407
+ // A Tekla query matches the objects that are drawn (parts, bolts): an assembly would bring in every part it holds,
408
+ // whatever that part's own profile or length. Revit lists every object and reports those with nothing to draw.
409
+ if (isTeklaParser && !(entity.geometry || []).length) continue;
410
+ const facts = new Map(), names = new Map();
411
+ const add = (name, fact) => {
412
+ const shown = typeof name === 'string' ? name.trim() : ''; if (!shown) return;
413
+ const key = shown.toLocaleLowerCase(); const list = facts.get(key) || []; list.push(fact); facts.set(key, list);
414
+ if (!names.has(key)) names.set(key, shown);
415
+ };
416
+ const own = propertyByEntity.get(entity.id) || [];
417
+ if (isTeklaParser) {
418
+ // The rows the Properties panel shows, with its rule for canonical millimetres (not for UDAs).
419
+ for (const group of teklaPropertyGroups(own)) for (const row of group.rows) add(row.name, propertyFact(row, { tekla: true, canonicalMillimetres: group.key !== 'tekla-udas' }));
420
+ if (entity.nativeKind || entity.typeName) add('Type', objectFact(entity.nativeKind || entity.typeName));
421
+ if (entity.nativeSubtype) add('Subtype', objectFact(entity.nativeSubtype));
422
+ } else {
423
+ for (const row of own) add(row.name, propertyFact(row));
424
+ for (const [name, value] of [['Name', entity.name], ['Category', entity.categoryName ?? entity.category], ['Family', entity.familyName ?? entity.family],
425
+ ['Type', entity.typeName], ['Level', entity.levelName]]) if (value != null && value !== '') add(name, objectFact(value));
426
+ }
427
+ candidates.push({ id: entity.id, label: subjectLabelOf(entity.id) || entity.id, facts, names, colour: dominantColour(colours.get(entity.id) || []) });
428
+ }
429
+ return candidates;
430
+ }
431
+
432
+ function applyModelView(command, target) {
433
+ // The viewport's public state (web/model-viewport-state.js): how many objects it shows selected.
434
+ const selectedNow = () => viewport?.getState?.()?.selectionCount ?? 0;
435
+ const base = { total: 0, matched: 0, selectionApplied: 0, selectedFinal: selectedNow(), notDrawable: 0, noField: 0, unchecked: 0, overCap: false,
436
+ framed: false, display: null, skipped: [], assumptions: [], references: [], samples: [] };
437
+ const refuse = (reason, extra = {}) => ({ ...base, status: 'not-applied', reason, ...extra });
438
+ // Only the view this command was claimed for: same session, same project, same revision of the same source file.
439
+ if (viewerLoading) return refuse('loading');
440
+ if (!target || target.viewerSessionId !== viewerSessionId) return refuse('session-changed');
441
+ if (target.projectId !== projectId || target.revision !== loadedRevisionId || target.sourceDigest !== loadedSourceDigest) return refuse('model-changed');
442
+ let parsed, selection = null, total = entities.length;
443
+ try {
444
+ parsed = parseModelViewCommand(command);
445
+ if (parsed.select) {
446
+ const candidates = viewCandidates();
447
+ if (parsed.select.kind === 'where') total = candidates.length;
448
+ // What is selected now, as the query compares with it: in Tekla the parts lit in 3D (an assembly picked in the
449
+ // tree selects its parts), in Revit the selected objects. Ids are checked against every object of the revision.
450
+ const evaluation = evaluateModelViewQuery(candidates, parsed.select, { selectedIds: isTeklaParser ? [...geometrySelectionIds] : [...selectedIds],
451
+ knownIds: new Set(entityById.keys()), revision: loadedRevisionId, displayUnits: displayUnitControl?.units?.() });
452
+ if (!evaluation.ok) return refuse(evaluation.reason, { total, field: evaluation.field ?? null, commonFields: evaluation.commonFields ?? null, missing: evaluation.missing ?? 0 });
453
+ const counts = { total, matched: evaluation.matchedIds.length, noField: evaluation.noField, unchecked: evaluation.unchecked,
454
+ references: evaluation.references, assumptions: evaluation.assumptions };
455
+ if (!evaluation.matchedIds.length) return refuse('no-match', counts);
456
+ // A Tekla query matched drawn objects already; ids may name an assembly, which the list click's resolver turns into
457
+ // its parts (bounded at 5,000). Revit selects the matched objects that have a shape.
458
+ // A structural grid has no geometry of its own; the viewport draws it, and both click paths select it.
459
+ const isGrid = (id) => entityById.get(id)?.structuralGrid?.mapping?.kind === 'symmetric';
460
+ const resolved = isTeklaParser ? teklaGeometrySelection(evaluation.matchedIds, entityById, teklaAssemblyMembers)
461
+ : evaluation.matchedIds.filter((id) => (entityById.get(id)?.geometry || []).length);
462
+ const drawable = resolved && [...new Set([...resolved, ...evaluation.matchedIds.filter(isGrid)])];
463
+ // The cap counts everything that would be selected, a grid included, before anything changes.
464
+ if (!drawable || (isTeklaParser && drawable.length > TEKLA_GEOMETRY_SELECTION_CAP)) return refuse('over-cap', { ...counts, overCap: true });
465
+ const drawn = new Set(drawable);
466
+ const notDrawable = evaluation.matchedIds.filter((id) => !drawn.has(id)
467
+ && !(isTeklaParser && (teklaAssemblyMembers.get(id) || []).some((member) => drawn.has(member)))).length;
468
+ if (!drawable.length) return refuse('nothing-drawable', { ...counts, notDrawable });
469
+ selection = { ids: isTeklaParser ? evaluation.matchedIds : drawable, drawable, counts: { ...counts, notDrawable } };
470
+ }
471
+ } catch (error) {
472
+ // Nothing has changed yet: a command this viewer cannot evaluate changes nothing, and says so.
473
+ console.error('[revit-editor] an AI view command could not be evaluated', error);
474
+ return refuse('failed', { total });
475
+ }
476
+ const display = parsed.display;
477
+ // A display change that works on the selection needs objects selected in 3D, not only rows in a list.
478
+ if (displayNeedsSelection(display) && !selection && !selectedNow()) return refuse('selection-required', { total });
479
+ const skipped = [], applied = [];
480
+ const fitSelection = !!selection && display?.fit !== 'none' && display?.fit !== 'all';
481
+ // Nothing has changed up to here. From here on, every step is the call a person's click makes.
482
+ if (selection) {
483
+ const selected = isTeklaParser ? selectTeklaObjects(selection.ids[0], selection.ids, false, false, 'viewport')
484
+ : selectRevitEntities(selection.ids[0], selection.ids, false, 'viewport');
485
+ if (!selected) return refuse('failed', { total });
486
+ }
487
+ const selectionApplied = selection ? (isTeklaParser ? geometrySelectionIds.length : selectedIds.length) : 0;
488
+ // Framed only when the fit ran: a selection with nothing visible to frame leaves the camera where it was.
489
+ let framed = false;
490
+ try {
491
+ if (fitSelection) framed = facade.dispatch('model.fit-selection') === true;
492
+ if (display?.visibility === 'isolate') { facade.dispatch('model.isolate'); applied.push('isolate'); }
493
+ if (display?.visibility === 'hide-selected') { facade.dispatch('model.hide-selected'); applied.push('hide-selected'); }
494
+ // The toolbar's Show all also brings back hidden grid levels (its click handler, below).
495
+ if (display?.visibility === 'show-all') { facade.dispatch('model.show-all'); viewport.setGridHiddenLevels([]); syncGridVisibilityAction(); applied.push('show-all'); }
496
+ if (display?.ghostUnselected != null) { facade.dispatch('model.ghost-unselected.set', display.ghostUnselected); applied.push('ghost'); }
497
+ if (display?.mode) {
498
+ if (VIEWER_DISPLAY_MODES.includes(display.mode)) { facade.dispatch('model.display-mode.set', display.mode); applied.push('mode'); }
499
+ else skipped.push('mode-unsupported');
500
+ }
501
+ if (display?.fit === 'all') { facade.dispatch('model.fit'); applied.push('fit-all'); }
502
+ else if (display?.fit === 'selection' && !selection && selectedNow()) { framed = facade.dispatch('model.fit-selection') === true; applied.push('fit-selection'); }
503
+ } catch (error) {
504
+ console.error('[revit-editor] an AI display change failed part way', error);
505
+ skipped.push('display-failed');
506
+ }
507
+ reflectToolbarState();
508
+ modelPanelBridge?.publishSnapshot();
509
+ window.__instructor?.notifyChanged();
510
+ const state = viewport.getState?.() ?? {};
511
+ const mode = facade.displayMode();
512
+ return {
513
+ ...base, ...(selection?.counts ?? {}), total,
514
+ status: skipped.length ? 'partial' : 'applied', reason: null, skipped,
515
+ // framed: the view was moved onto the selection (Zoom to the whole model is reported as its own step).
516
+ selectionApplied, selectedFinal: state.selectionCount ?? 0, framed,
517
+ display: { ghostUnselected: facade.ghostUnselected() === true, mode: VIEWER_DISPLAY_MODES.includes(mode) ? mode : 'solid', filtered: state.hasVisibilityFilter === true, applied },
518
+ samples: selection ? selection.drawable.slice(0, 10).map((id) => (subjectLabelOf(id) || id).slice(0, 120)) : [],
519
+ };
520
+ }
521
+
380
522
  function row(label, count, entityId, objectFields = null) {
381
523
  const button = document.createElement('button'); button.type = 'button'; button.className = 'explorer-row';
382
524
  if (entityId) button.dataset.entityId = entityId;
@@ -436,22 +578,39 @@ function renderClassification(host, values = entities, relationValues = [], foll
436
578
  if (relationValues.length > 500) { const note = document.createElement('div'); note.className = 'explorer-empty'; note.textContent = `Showing 500 of ${relationValues.length.toLocaleString()} supplied relationships.`; host.append(note); }
437
579
  }
438
580
 
439
- function renderEntityList(host, values, ownProperties = propertyByEntity, memberships = teklaAssemblyMembers) {
581
+ // Once the object renderEntityList added a row for past the first page is no longer selected (another row clicked,
582
+ // the selection cleared), that row goes and its note stops saying "plus the selected object". Only the tree on the page
583
+ // counts: a tree staged for a revision that may still fail to load is not the one the person sees.
584
+ function dropStaleFollowedRow(selected) {
585
+ const extra = document.querySelector('[data-followed-row]');
586
+ if (!extra || selected.includes(extra.dataset.entityId)) return false;
587
+ const note = extra.parentElement?.querySelector(':scope > [data-plain-note]');
588
+ if (note) { note.textContent = note.dataset.plainNote; delete note.dataset.plainNote; }
589
+ extra.remove();
590
+ return true;
591
+ }
592
+
593
+ function renderEntityList(host, values, ownProperties = propertyByEntity, memberships = teklaAssemblyMembers, followedId = null) {
440
594
  host.replaceChildren();
441
595
  if (!values.length) { const empty = document.createElement('div'); empty.className = 'explorer-empty'; empty.textContent = 'No objects in this index.'; host.append(empty); return; }
442
596
  const fragment = document.createDocumentFragment();
443
597
  const limit = 500;
444
- for (const entity of values.slice(0, limit)) {
598
+ // An object picked in 3D past the first page still gets its row, after the page, so Follow selection can reveal it.
599
+ const followed = followedId && values.length > limit ? values.slice(limit).find((entity) => entity.id === followedId) : null;
600
+ for (const entity of followed ? [...values.slice(0, limit), followed] : values.slice(0, limit)) {
445
601
  const memberCount = isTeklaParser && memberships.has(entity.id) ? memberships.get(entity.id).length : null;
446
602
  const fields = isTeklaParser ? teklaObjectFields(entity, ownProperties.get(entity.id)) : null;
447
603
  const item = row(isTeklaParser ? (fields.name ?? entity.nativeKind ?? entity.typeName ?? 'Tekla object') : (entity.name || entity.typeName || entity.id), memberCount, entity.id, fields);
448
604
  if (memberCount != null) item.dataset.tip = `${memberCount} assembly members; selects all signed member geometry`;
449
605
  fragment.append(item);
606
+ if (entity === followed) item.dataset.followedRow = 'true';
450
607
  }
451
608
  host.append(fragment);
452
609
  if (values.length > 500) {
453
610
  const note = document.createElement('div'); note.className = 'explorer-empty';
454
- note.textContent = isTeklaParser ? `Showing first 500 of ${values.length.toLocaleString()} objects. Select the Type to select all visible matching geometry.` : `Showing 500 of ${values.length.toLocaleString()} objects.`;
611
+ const plain = `Showing first 500 of ${values.length.toLocaleString()} objects. Select the Type to select all visible matching geometry.`;
612
+ note.textContent = isTeklaParser ? (followed ? plain.replace(' objects.', ' objects, plus the selected object.') : plain) : `Showing 500 of ${values.length.toLocaleString()} objects.`;
613
+ if (followed) note.dataset.plainNote = plain;
455
614
  host.append(note);
456
615
  }
457
616
  }
@@ -508,10 +667,10 @@ function renderTeklaTypes(host, values, ownProperties, memberships = teklaAssemb
508
667
  for (const group of teklaTypeGroups(browsable)) {
509
668
  const grouped = [...group.values, ...group.subtypes.flatMap((subtype) => subtype.values)];
510
669
  branch(host, group.label, grouped, (children) => {
511
- if (group.values.length) renderEntityList(children, group.values, ownProperties, memberships);
670
+ if (group.values.length) renderEntityList(children, group.values, ownProperties, memberships, followedId);
512
671
  for (const subtype of group.subtypes) {
513
672
  const containsFollowed = subtype.values.some((entity) => entity.id === followedId);
514
- branch(children, subtype.label, subtype.values, (body) => renderEntityList(body, subtype.values, ownProperties, memberships),
673
+ branch(children, subtype.label, subtype.values, (body) => renderEntityList(body, subtype.values, ownProperties, memberships, followedId),
515
674
  { expanded: !!normalized, populated: !!normalized || containsFollowed });
516
675
  }
517
676
  }, { expanded: !!normalized, populated: !!normalized || grouped.some((entity) => entity.id === followedId) });
@@ -1171,6 +1330,7 @@ async function loadRevision(state, authority, spatialCandidate) {
1171
1330
  const handle = state[authority]; if (!handle) throw new Error(`No ${authority} model revision is available.`);
1172
1331
  restoreLoadingState($('loadingState'));
1173
1332
  $('loadingState').style.display = 'flex';
1333
+ viewerLoading = true; viewerSessionId = crypto.randomUUID(); modelPanelBridge?.publishSnapshot();
1174
1334
  try {
1175
1335
  const base = `/api/editor/model/${encodeURIComponent(state.projectUuid)}/${encodeURIComponent(handle.revisionId)}`;
1176
1336
  const manifest = (await json(`${base}/manifest`)).manifest;
@@ -1243,6 +1403,7 @@ async function loadRevision(state, authority, spatialCandidate) {
1243
1403
  $('revitExplorerTypes').replaceChildren(...staged.types.childNodes);
1244
1404
  inspect(null, true, false, 'tree');
1245
1405
  renderTeklaAudit();
1406
+ viewerLoading = false;
1246
1407
  modelPanelBridge?.ready(handle.revisionId);
1247
1408
  if (loadedNothingDrawn) renderTeklaNothingDrawnState($('loadingState'), loadedNothingDrawn.count, loadedNothingDrawn.gridDrawn);
1248
1409
  else $('loadingState').style.display = 'none';
@@ -1255,6 +1416,9 @@ async function loadRevision(state, authority, spatialCandidate) {
1255
1416
  else $('loadingState').style.display = 'none';
1256
1417
  }
1257
1418
  throw error;
1419
+ } finally {
1420
+ // A failed switch keeps the previous revision on screen: it is ready again. A newer load owns the flag instead.
1421
+ if (token === revisionLoadToken && viewerLoading) { viewerLoading = false; modelPanelBridge?.publishSnapshot(); }
1258
1422
  }
1259
1423
  }
1260
1424
 
@@ -1277,13 +1441,9 @@ function mountPanels() {
1277
1441
  selectionState: () => isTeklaParser ? { focusEntityId: selectedId, geometrySelectionIds: [...geometrySelectionIds] } : {},
1278
1442
  // ids: what a list click selects (Ctrl/Shift can make it several, or none). The Properties panel shows the row clicked
1279
1443
  // when it stays selected, else the last one; the viewport shows them all.
1280
- select: (id, ids = [id]) => {
1281
- if (isTeklaParser) return selectTeklaObjects(id, ids);
1282
- if (!ids.every((each) => entityById.has(each))) return false;
1283
- selectedIds = [...ids]; if (ids.length) clipSession?.clearSelection?.();
1284
- selectionOriginGuard.run(() => viewport.setSelection({ ids }));
1285
- return inspect(ids.includes(id) ? id : (ids.at(-1) ?? null), false, false, 'tree');
1286
- },
1444
+ select: (id, ids = [id]) => (isTeklaParser ? selectTeklaObjects(id, ids) : selectRevitEntities(id, ids)),
1445
+ // #2255: an AI view command this window claimed, applied in this viewer.
1446
+ view: (command, target) => applyModelView(command, target),
1287
1447
  expand: (groupId) => expandModelPanelGroup(modelExplorerTabs, $, groupId),
1288
1448
  selectGroup: (groupId) => isTeklaParser && selectModelPanelGroup(modelExplorerTabs, $, groupId),
1289
1449
  search: (tab, query) => renderExplorerSearch(tab, query, selectedIds.length === 1 ? selectedIds[0] : null),
@@ -1507,6 +1667,11 @@ async function boot() {
1507
1667
  } });
1508
1668
  facade = createReadOnlyModelEditorAdapter({ viewport, host: { openSavedViews } }); toolbarChrome = wireToolbar();
1509
1669
  window.__revitEditorTest = { dispatchLog: () => facade.dispatchLog(), selected: () => selectedId, entityCount: () => entities.length,
1670
+ // #2255: the raw rows and the drawn objects, so a test can count a query's matches without the query code.
1671
+ rows: (id) => (propertyByEntity.get(id) || []).map((row) => ({ name: row.name, value: row.value, unit: row.unit ?? null, groupName: row.groupName ?? null,
1672
+ semantic: row.semantic ?? null, valueEncoding: row.valueEncoding ?? null })),
1673
+ drawnIds: () => entities.filter((entity) => (entity.geometry || []).length).map((entity) => entity.id),
1674
+ selectedIds: () => [...selectedIds],
1510
1675
  selectionState: () => ({ focusEntityId: selectedId, geometrySelectionIds: [...geometrySelectionIds] }),
1511
1676
  selectionCapabilities: () => selectionTools?.capabilities() ?? null, spatialState: () => spatialTools?.state() ?? null,
1512
1677
  editorState: () => facade.getState(), presentation: () => viewport.presentationProbe(),
@@ -0,0 +1,193 @@
1
+ // Live run progress (#2228): the pure half. Turns the `node-progress` records a long run streams
2
+ // (a Blender animation: "render", 143 of 240 frames) into what the run strip and the report overlay
3
+ // say — headline, detail, elapsed, bar fraction, and a stalled/paused state — with no DOM. web/aware.js
4
+ // mounts it; server/run-progress-ui.test.ts drives it in Node through module.exports.
5
+ //
6
+ // Honesty rules, owned here so both surfaces obey them:
7
+ // - a fraction exists only when the producer reported a total; there is no invented percentage;
8
+ // - within one pass the count never goes backwards (a late, lower record is ignored);
9
+ // - a new pass (new total or new pass label) restarts the bar and the time estimate;
10
+ // - the time estimate appears only after 3 units and 5 seconds, is rounded, and hides when it swings;
11
+ // - silence is "still running · no update for 1:10", never "stuck".
12
+ // A plain script (no import/export) like flo.js; every top-level name is prefixed `rp`.
13
+
14
+ const RP_STALL_MS = 60_000;
15
+ const RP_STALL_HINT_MS = 5 * 60_000;
16
+ const RP_ETA_MIN_UNITS = 3;
17
+ const RP_ETA_MIN_MS = 5_000;
18
+ const RP_ETA_SAMPLES = 10;
19
+ const RP_ETA_SWING = 0.3;
20
+
21
+ const RP_PHASES = {
22
+ import: 'Importing the model',
23
+ look: 'Applying materials',
24
+ setup: 'Preparing the scene',
25
+ stage: 'Preparing the scene',
26
+ render: 'Rendering',
27
+ encode: 'Writing the video',
28
+ parse: 'Reading the model',
29
+ tessellate: 'Building the geometry',
30
+ batch: 'Drawing the model',
31
+ complete: 'Finishing up',
32
+ };
33
+
34
+ function rpPhaseLabel(phase) {
35
+ if (typeof phase !== 'string' || !phase) return 'Working';
36
+ if (RP_PHASES[phase]) return RP_PHASES[phase];
37
+ const words = phase.replace(/[-_.]+/g, ' ').trim();
38
+ return words ? words.charAt(0).toUpperCase() + words.slice(1) : 'Working';
39
+ }
40
+
41
+ /** m:ss, or h:mm:ss from an hour. */
42
+ function rpClock(ms) {
43
+ const total = Math.max(0, Math.floor((Number(ms) || 0) / 1000));
44
+ const h = Math.floor(total / 3600);
45
+ const m = Math.floor((total % 3600) / 60);
46
+ const s = total % 60;
47
+ const ss = String(s).padStart(2, '0');
48
+ return h > 0 ? `${h}:${String(m).padStart(2, '0')}:${ss}` : `${m}:${ss}`;
49
+ }
50
+
51
+ /** "less than a minute left" / "about 4 minutes left" / "about 25 minutes left" / "about 3 hours left". */
52
+ function rpEtaText(ms) {
53
+ const min = ms / 60_000;
54
+ if (min < 1) return 'less than a minute left';
55
+ if (min < 1.5) return 'about a minute left';
56
+ if (min <= 10) return `about ${Math.round(min)} minutes left`;
57
+ if (min <= 120) return `about ${Math.round(min / 5) * 5} minutes left`;
58
+ const h = Math.round(min / 60);
59
+ return `about ${h} hour${h === 1 ? '' : 's'} left`;
60
+ }
61
+
62
+ function rpCreate(startedAt) {
63
+ return { startedAt, lastAt: startedAt, current: null, passKey: null, passIndex: 0, samples: [], shownEta: null, suppressed: false };
64
+ }
65
+
66
+ function rpPassKey(rec) {
67
+ return `${rec.node || ''}|${rec.phase || ''}|${rec.total || ''}|${rec.message || ''}`;
68
+ }
69
+
70
+ /** Fold one record (as relayed by the server) into the state. Returns the same state. */
71
+ function rpApply(st, rec, now) {
72
+ if (!st || !rec || typeof rec !== 'object') return st;
73
+ st.lastAt = now;
74
+ if (rec.suppressed) { st.suppressed = true; return st; }
75
+ const key = rpPassKey(rec);
76
+ const prev = st.current;
77
+ let sameStream = prev && key === st.passKey;
78
+ if (sameStream && typeof rec.done === 'number' && typeof prev.done === 'number' && rec.done < prev.done) {
79
+ // Back at the start (0 or 1) is a producer that began a new pass without labelling it; anything
80
+ // else lower is a late record within the pass — the bar never goes backwards.
81
+ if (rec.done > 1) return st;
82
+ sameStream = false;
83
+ }
84
+ if (!sameStream) {
85
+ if (prev && typeof prev.total === 'number') st.passIndex += 1;
86
+ st.passKey = key;
87
+ st.samples = [];
88
+ st.shownEta = null;
89
+ st.passStartedAt = now;
90
+ }
91
+ if (typeof rec.done === 'number') {
92
+ const last = st.samples[st.samples.length - 1];
93
+ if (!last || rec.done > last.done) st.samples.push({ done: rec.done, at: now });
94
+ if (st.samples.length > RP_ETA_SAMPLES + 1) st.samples.shift();
95
+ }
96
+ st.current = { node: rec.node || null, phase: rec.phase, done: rec.done, total: rec.total, message: rec.message };
97
+ return st;
98
+ }
99
+
100
+ function rpMedian(xs) {
101
+ const s = xs.slice().sort((a, b) => a - b);
102
+ const mid = Math.floor(s.length / 2);
103
+ return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
104
+ }
105
+
106
+ /** Remaining ms for the current pass, or null when it would be a guess. */
107
+ function rpEta(st, now) {
108
+ const c = st.current;
109
+ if (!c || typeof c.total !== 'number' || typeof c.done !== 'number' || c.done >= c.total) return null;
110
+ if (c.done < RP_ETA_MIN_UNITS || st.samples.length < 2) return null;
111
+ if (now - (st.passStartedAt || st.startedAt) < RP_ETA_MIN_MS) return null;
112
+ const perUnit = [];
113
+ for (let i = 1; i < st.samples.length; i++) {
114
+ const a = st.samples[i - 1], b = st.samples[i];
115
+ perUnit.push((b.at - a.at) / (b.done - a.done));
116
+ }
117
+ const est = rpMedian(perUnit) * (c.total - c.done);
118
+ return Number.isFinite(est) && est >= 0 ? est : null;
119
+ }
120
+
121
+ /**
122
+ * What to show now. `kind` is 'running' | 'stalled' | 'paused'; `fraction` is null when there is no
123
+ * honest one. `valueText` is the progressbar's spoken value.
124
+ */
125
+ function rpView(st, now, fallbackHeadline) {
126
+ const c = st && st.current;
127
+ const elapsed = rpClock(now - st.startedAt);
128
+ const quiet = now - st.lastAt;
129
+ let headline;
130
+ let fraction = null;
131
+ let valueNow = null;
132
+ let valueMax = null;
133
+ if (c && typeof c.total === 'number' && c.total > 0 && typeof c.done === 'number') {
134
+ const unit = c.phase === 'render' ? 'frame' : null;
135
+ headline = unit
136
+ ? `Rendering frame ${Math.min(c.done, c.total)} of ${c.total}`
137
+ : `${rpPhaseLabel(c.phase)} · ${Math.min(c.done, c.total)} of ${c.total}`;
138
+ fraction = Math.max(0, Math.min(1, c.done / c.total));
139
+ valueNow = Math.min(c.done, c.total);
140
+ valueMax = c.total;
141
+ } else if (c) {
142
+ headline = `${rpPhaseLabel(c.phase)}…`;
143
+ } else {
144
+ headline = fallbackHeadline || 'Working…';
145
+ }
146
+ const parts = [];
147
+ if (c && c.message) parts.push(c.message.charAt(0).toUpperCase() + c.message.slice(1));
148
+ let kind = 'running';
149
+ if (st.suppressed) {
150
+ kind = 'paused';
151
+ fraction = null;
152
+ parts.length = 0;
153
+ parts.push('Live updates paused. The run is still going.');
154
+ } else if (quiet >= RP_STALL_MS) {
155
+ kind = 'stalled';
156
+ parts.push(`Still running · no update for ${rpClock(quiet)}`);
157
+ if (quiet >= RP_STALL_HINT_MS) parts.push('Long renders can go quiet. You can keep working or stop the run.');
158
+ } else {
159
+ if (fraction !== null) parts.unshift(`${Math.floor(fraction * 100)}%`);
160
+ const eta = rpEta(st, now);
161
+ if (eta !== null) {
162
+ const prevShown = st.shownEta;
163
+ // Hide a jumping number rather than show it: compare against the last shown estimate, aged.
164
+ // An estimate that has already run out (aged below 30 s) is compared as 30 s, so a sudden long
165
+ // tail after it counts as a swing too.
166
+ const aged = prevShown ? Math.max(prevShown.ms - (now - prevShown.at), 30_000) : null;
167
+ const swing = aged !== null ? Math.abs(eta - aged) / aged : 0;
168
+ st.shownEta = { ms: eta, at: now };
169
+ if (swing <= RP_ETA_SWING) parts.push(rpEtaText(eta));
170
+ }
171
+ }
172
+ const detail = parts.join(' · ');
173
+ const valueText = [headline, kind === 'running' ? null : detail].filter(Boolean).join(', ');
174
+ return { kind, headline, detail, elapsed, fraction, valueNow, valueMax, valueText, passIndex: st.passIndex };
175
+ }
176
+
177
+ /** The terminal line: "Finished in 12:40" / "Stopped at frame 143 of 240" / "Stopped with a problem". */
178
+ function rpEndText(st, outcome, now) {
179
+ const c = st && st.current;
180
+ if (outcome === 'ok') return `Finished in ${rpClock(now - st.startedAt)}`;
181
+ const at = c && typeof c.total === 'number' && typeof c.done === 'number'
182
+ ? (c.phase === 'render' ? ` at frame ${c.done} of ${c.total}` : ` at ${c.done} of ${c.total}`)
183
+ : '';
184
+ if (outcome === 'stopped') return `Stopped${at}`;
185
+ if (outcome === 'not-run') return 'Didn’t run';
186
+ // The run ended while FloLess could not hear it (it restarted, or forgot the run): say only what is known.
187
+ if (outcome === 'unknown') return 'The run ended while FloLess was disconnected — run it again if its result is missing';
188
+ return 'Stopped with a problem';
189
+ }
190
+
191
+ if (typeof module !== 'undefined' && module.exports) {
192
+ module.exports = { rpCreate, rpApply, rpView, rpEndText, rpClock, rpEtaText, rpPhaseLabel, RP_STALL_MS };
193
+ }