@floless/app 0.144.0 → 0.146.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.
@@ -580,6 +580,40 @@ export function revitObjectBounds(objects, includeHidden = false) {
580
580
  return box;
581
581
  }
582
582
 
583
+ /** How much nearer than a snap point a surface must be to hide it, in model millimetres. */
584
+ export const REVIT_SNAP_OCCLUSION_TOLERANCE_MM = 0.5;
585
+ const occlusionBoxes = new WeakMap();
586
+
587
+ /**
588
+ * Is `point` hidden from `origin` by a visible, un-clipped surface nearer than `tolerance` (render
589
+ * units) short of it? Only meshes whose world box the sight segment crosses are raycast, one at a time,
590
+ * and the answer is given at the first hit that counts — the same visibility rule as the surface pick.
591
+ */
592
+ export function revitSnapPointOccluded(point, origin, meshes, planes = [], tolerance = 0) {
593
+ if (!Array.isArray(origin) || !Array.isArray(point) || !meshes?.length) return false;
594
+ const from = new THREE.Vector3().fromArray(origin); const to = new THREE.Vector3().fromArray(point);
595
+ const length = from.distanceTo(to); const far = length - Math.max(0, tolerance);
596
+ if (!(far > 0)) return false;
597
+ const probe = new THREE.Raycaster(from, to.clone().sub(from).divideScalar(length), 0, far);
598
+ const entry = new THREE.Vector3(); const hits = [];
599
+ for (const mesh of meshes) {
600
+ if (!mesh?.visible) continue;
601
+ // World box cached per mesh, rebuilt when the mesh moves (its world matrix changes).
602
+ let cached = occlusionBoxes.get(mesh);
603
+ if (!cached || !cached.matrix.equals(mesh.matrixWorld)) {
604
+ if (!mesh.geometry.boundingBox) mesh.geometry.computeBoundingBox();
605
+ cached = { matrix: mesh.matrixWorld.clone(), box: mesh.geometry.boundingBox.clone().applyMatrix4(mesh.matrixWorld) };
606
+ occlusionBoxes.set(mesh, cached);
607
+ }
608
+ const box = cached.box;
609
+ const crossing = box.containsPoint(from) ? from : probe.ray.intersectBox(box, entry);
610
+ if (!crossing || from.distanceTo(crossing) > far) continue;
611
+ hits.length = 0; mesh.raycast(probe, hits);
612
+ if (hits.some((hit) => hit.distance <= far && planes.every((plane) => plane.distanceToPoint(hit.point) >= -1e-7))) return true;
613
+ }
614
+ return false;
615
+ }
616
+
583
617
  export function createRevitViewport({ canvas, onSelect = () => {}, onOutlineBuild = () => {}, formatDistance = (valueMm) => `${Math.round(valueMm)} mm`, includeHiddenSelectionBounds = false }) {
584
618
  if (typeof formatDistance !== 'function') throw new TypeError('Model viewport distance formatter must be a function.');
585
619
  const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false }); renderer.setPixelRatio(Math.min(devicePixelRatio || 1, 2)); renderer.setClearColor(0x020817, 1); renderer.localClippingEnabled = true;
@@ -1297,6 +1331,32 @@ export function createRevitViewport({ canvas, onSelect = () => {}, onOutlineBuil
1297
1331
  side: mesh.material.side, metalness: mesh.material.metalness, roughness: mesh.material.roughness,
1298
1332
  })),
1299
1333
  pickSurface,
1334
+ // Where the pick ray through this pointer starts (the eye, or the near plane when orthographic), in
1335
+ // the same frame as pickSurface's hit. Snapping covers the sightline between the two (#1747).
1336
+ pointerRayOrigin(clientX, clientY) { return setRayAt(clientX, clientY)?.origin.toArray() ?? null; },
1337
+ // Snapping follows exactly what the surface pick follows (ownerHitsAt): only visible meshes, and
1338
+ // only what the section planes keep. An element is skipped whole when hidden or when its envelope
1339
+ // lies entirely on the cut-away side of a plane; a single point is kept only on the kept side.
1340
+ snapVisibility() {
1341
+ const planes = activeRenderPlanes;
1342
+ return {
1343
+ element(mesh, min, max) {
1344
+ if (!mesh?.visible) return false;
1345
+ return planes.every((plane) => {
1346
+ const n = plane.normal;
1347
+ return n.x * (n.x >= 0 ? max[0] : min[0]) + n.y * (n.y >= 0 ? max[1] : min[1]) + n.z * (n.z >= 0 ? max[2] : min[2]) + plane.constant >= -1e-7;
1348
+ });
1349
+ },
1350
+ point(point) {
1351
+ return planes.every((plane) => plane.normal.x * point[0] + plane.normal.y * point[1] + plane.normal.z * point[2] + plane.constant >= -1e-7);
1352
+ },
1353
+ // Hidden behind something nearer the eye? See revitSnapPointOccluded; the tolerance is a fixed
1354
+ // half millimetre of model length, whatever the viewing distance.
1355
+ occluded(point, origin, meshes) {
1356
+ return revitSnapPointOccluded(point, origin, meshes, planes, REVIT_SNAP_OCCLUSION_TOLERANCE_MM / geometryFrame.millimetresPerRenderUnit);
1357
+ },
1358
+ };
1359
+ },
1300
1360
  projectPoint(point) { const value = new THREE.Vector3().fromArray(point).project(camera); const rect = canvas.getBoundingClientRect(); return { x: rect.left + (value.x * .5 + .5) * rect.width, y: rect.top + (-value.y * .5 + .5) * rect.height, visible: value.z >= -1 && value.z <= 1 }; },
1301
1361
  // xeoRVT GLB millimetres cross the render boundary as metres (root scale 0.001). Convert only
1302
1362
  // the measured display value back here; persisted provider coordinates remain untouched.
@@ -50,3 +50,22 @@ body:has(.editor-root[data-model-state="empty"]) .read-only-chip{display:none}
50
50
  #tooltip{position:fixed;z-index:100;background:var(--panel);border:1px solid var(--line);border-radius:6px;padding:5px 8px;font-size:11.5px;line-height:1.35;color:var(--text);pointer-events:none;max-width:260px;box-shadow:var(--shadow-tip);opacity:0;transition:opacity .12s}#tooltip.show{opacity:1}
51
51
  @media(max-width:820px){:root{--panelw:280px}.authority-kicker,.source-name{display:none}}
52
52
  .tekla-audit-omissions{grid-column:1/-1;margin:0;padding:6px 2px;color:var(--muted);font-size:11px;line-height:1.4}
53
+ /* Questions in chat (#1653): the shared card (web/model-chat-questions.js) as one more Properties section, in this
54
+ page's own tokens. Its words and rows come from the module; only the look is this page's. */
55
+ .insp-after{padding:0 12px 18px}.insp-after:empty{display:none}.insp-note+.insp-after{padding-top:0}
56
+ .chat-questions{padding:10px 0;border-top:1px solid var(--line)}
57
+ .chat-q-title{font-size:10px;color:var(--muted);text-transform:uppercase;letter-spacing:.1em;margin-bottom:7px}
58
+ .chat-q{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:2px 8px;align-items:center;padding:6px 0;border-bottom:1px solid var(--line)}
59
+ .chat-q:last-child{border-bottom:0}
60
+ .chat-q-note{grid-column:1;font-size:12px;color:var(--text);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
61
+ .chat-q-meta,.chat-q-about,.chat-q-ai{grid-column:1;font-size:10.5px;color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
62
+ .chat-q-ai{font-style:italic}
63
+ .chat-questions .ghost{background:transparent;border:1px solid var(--line);color:var(--muted);font-size:11px;min-height:0;padding:2px 8px;border-radius:4px;white-space:nowrap;cursor:pointer}
64
+ .chat-questions .ghost:hover{background:transparent;color:var(--text);border-color:var(--accent)}
65
+ .chat-questions .ghost:focus-visible{outline:2px solid var(--accent);outline-offset:1px}
66
+ .chat-q-show{grid-column:2;align-self:center}
67
+ .chat-q-more>summary,.chat-q-orphans>summary{cursor:pointer;font-size:11px;color:var(--muted);padding:4px 0;list-style-position:inside}
68
+ .chat-q-more>summary::marker,.chat-q-orphans>summary::marker{color:inherit}
69
+ .chat-q-more>summary:hover,.chat-q-orphans>summary:hover{color:var(--text)}
70
+ .chat-q-more>summary:focus-visible,.chat-q-orphans>summary:focus-visible{outline:2px solid var(--accent);outline-offset:1px;border-radius:3px}
71
+ .chat-q-failed{display:flex;align-items:center;gap:6px;flex-wrap:wrap;font-size:11px;color:var(--muted)}
@@ -31,6 +31,7 @@ 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
33
  import { teklaAssemblyMembership, teklaGeometrySelection } from './model-tekla-selection.js';
34
+ import { modelSubjectLabel, renderChatQuestions, subjectLabelText, subjectsKeyOf } from './model-chat-questions.js';
34
35
 
35
36
  const $ = (id) => document.getElementById(id);
36
37
  const projectId = new URLSearchParams(location.search).get('project') || '';
@@ -47,6 +48,8 @@ window.addEventListener('storage', (event) => { if (event.key === hostThemeKey)
47
48
  const modelProduct = isTeklaParser ? 'Tekla Parser' : 'Revit Parser';
48
49
  const sourceProduct = isTeklaParser ? 'Tekla' : 'Revit';
49
50
  const commandPrefix = isTeklaParser ? 'tekla-parser' : 'revit';
51
+ // AI Chat names this viewer's objects as this model's (#1653): the pill, the card and the chat model's links.
52
+ const subjectSource = isTeklaParser ? 'tekla-parser' : 'revit';
50
53
  const editorProjectRoute = isTeklaParser ? '/api/editor/tekla-projects' : '/api/editor/revit-projects';
51
54
  const contractRoute = isTeklaParser ? '/api/contract/tekla-parser' : '/api/contract/revit-model';
52
55
  let entities = [], properties = [], relationships = [], entityById = new Map(), propertyByEntity = new Map(), selectedId = null, selectedIds = [], selectionOrigin = 'tree', classificationFollowedId = null, facade = null, viewport = null, inspector = null;
@@ -82,6 +85,8 @@ let terminalDisposed = false;
82
85
  let bfcacheSuspended = false;
83
86
  let revisionLoadToken = 0;
84
87
  let revisionLoadController = null;
88
+ // The revision shown and the source file it was read from: what a chat question about these objects is kept against.
89
+ let loadedRevisionId = null, loadedSourceDigest = null;
85
90
  const MODEL_VIEWER_MAX_TILE_BYTES = 256 * 1024 * 1024;
86
91
  const MODEL_VIEWER_MAX_AGGREGATE_BYTES = MODEL_VIEWER_MAX_TILE_BYTES + (128 * 1024 * 1024 * 5);
87
92
  const editorStateRecovery = createModelEditorStateRecoveryStore({
@@ -95,6 +100,65 @@ const modelSearchQueries = new Map();
95
100
  const modelSearchResults = new Map();
96
101
  const selectionOriginGuard = createModelSelectionOriginGuard();
97
102
 
103
+ /* -- AI Chat and the selection (#1653) ------------------------------------------------------------------------------
104
+ The selection as model objects a question may be about: the selected entities, named the way the server names them
105
+ (web/model-chat-questions.js), with the revision shown and the source file it was read from. A question never
106
+ follows an id into another source file, so both travel with it. */
107
+ function selectedSubjectItems() {
108
+ return selectedIds.filter((id) => typeof id === 'string' && id.startsWith('element:') && entityById.has(id))
109
+ .map((id) => ({ kind: 'element', id }));
110
+ }
111
+ function subjectLabelOf(id) {
112
+ const entity = entityById.get(id);
113
+ return entity ? subjectLabelText(modelSubjectLabel(subjectSource, entity, propertyByEntity.get(id) || [])) : '';
114
+ }
115
+ function modelSubjects() {
116
+ const items = selectedSubjectItems();
117
+ if (!items.length || !loadedRevisionId || !loadedSourceDigest) return null;
118
+ return { source: subjectSource, revision: loadedRevisionId, sourceDigest: loadedSourceDigest, total: items.length, key: subjectsKeyOf(items),
119
+ items: items.slice(0, 200).map((item) => ({ ...item, label: subjectLabelOf(item.id) || item.id })) };
120
+ }
121
+
122
+ /* Questions in chat: read from the server's per-project index while AI Chat is scoped to this project, and painted
123
+ after the properties (or under the empty note, where questions about objects not in this model are listed). */
124
+ let chatLinks = { state: 'idle', links: [], partial: false, key: '' }, chatLinksFetch = null, chatLinksAgain = false;
125
+ const chatQuestionsUi = { moreOpen: false, orphansOpen: false };
126
+ function chatScopeProjectId() {
127
+ try { return window.parent !== window ? window.parent.flolessChat?.scopeProjectId?.() ?? null : null; } catch { return null; }
128
+ }
129
+ function chatLinksAvailable() { return !!projectId && chatScopeProjectId() === projectId; }
130
+ function refreshChatLinks(force) {
131
+ if (!chatLinksAvailable()) {
132
+ if (chatLinks.state !== 'idle') { chatLinks = { state: 'idle', links: [], partial: false, key: '' }; inspector?.refreshAfter(); }
133
+ return;
134
+ }
135
+ if (chatLinksFetch) { chatLinksAgain = chatLinksAgain || !!force; return; }
136
+ chatLinksFetch = (async () => {
137
+ let next;
138
+ try {
139
+ const response = await fetch(`/api/chat/subject-links?ownerKind=project&ownerId=${encodeURIComponent(projectId)}&source=${subjectSource}`,
140
+ { credentials: 'same-origin', cache: 'no-store' });
141
+ if (!response.ok) throw new Error(`subject links ${response.status}`);
142
+ const body = await response.json();
143
+ const links = Array.isArray(body.links) ? body.links : [];
144
+ next = { state: 'ready', links, partial: body.partial === true, key: JSON.stringify([links, body.partial === true]) };
145
+ } catch (error) { console.warn('[model] Questions in chat could not be loaded', error); next = { state: 'failed', links: [], partial: false, key: 'failed' }; }
146
+ const changed = next.key !== chatLinks.key || next.state !== chatLinks.state;
147
+ chatLinks = next;
148
+ if (changed) { inspector?.refreshAfter(); window.__instructor?.notifyChanged(); }
149
+ })().finally(() => { chatLinksFetch = null; if (chatLinksAgain) { chatLinksAgain = false; refreshChatLinks(false); } });
150
+ }
151
+ // In the model shown now: the same source file, and an entity with that id.
152
+ function chatSubjectResolves(link) { return link.sourceDigest === loadedSourceDigest && entityById.has(link.id); }
153
+ const chatQuestionsSection = Object.freeze({ id: 'chat-questions', editable: false, render(host) {
154
+ if (!chatLinksAvailable()) return;
155
+ const box = renderChatQuestions({ doc: document, chatLinks, selected: selectedSubjectItems(), resolves: chatSubjectResolves,
156
+ currentLabel: (link) => subjectLabelOf(link.id), commandPrefix, ui: chatQuestionsUi, toast,
157
+ onShow: (link) => !!modelPanelBridge?.openChat(link.chatId, link.messageEventId, projectId),
158
+ onRetry: () => refreshChatLinks(true) });
159
+ if (box) host.append(box);
160
+ } });
161
+
98
162
  function modelPanelSnapshot() {
99
163
  const bodies = {};
100
164
  for (const tab of modelExplorerTabs) bodies[tab.key] = serializeModelPanelNodes($(tab.bodyId), tab.key);
@@ -248,16 +312,16 @@ function inspect(id, syncViewport = true, publish = true, origin = 'tree') {
248
312
  classificationFollowedId = nextFollowedId;
249
313
  if (publish) modelPanelBridge?.publishSnapshot();
250
314
  }
251
- if (!id) { inspector.render({ state: 'empty' }); if (publish) modelPanelBridge?.publishSelection(selectionOrigin); return true; }
315
+ if (!id) { inspector.render({ state: 'empty', after: [chatQuestionsSection] }); if (publish) modelPanelBridge?.publishSelection(selectionOrigin); return true; }
252
316
  const entity = entityById.get(id);
253
- if (!entity) { inspector.render({ state: 'unavailable', message: 'This object is not in the loaded revision.' }); if (publish) modelPanelBridge?.publishSelection(selectionOrigin); return false; }
317
+ if (!entity) { inspector.render({ state: 'unavailable', message: 'This object is not in the loaded revision.', after: [chatQuestionsSection] }); if (publish) modelPanelBridge?.publishSelection(selectionOrigin); return false; }
254
318
  const own = propertyByEntity.get(id) || [];
255
319
  const groups = isTeklaParser ? teklaPropertyGroups(own) : groupRevitProperties(own);
256
320
  const sections = [];
257
321
  if (isTeklaParser && auditFindingsFor(id).length) sections.push(auditInspectorSection(auditFindingsFor(id)));
258
322
  if (!isTeklaParser) sections.push(propertySection('Identity', [['Element', entity.id], ['Name', entity.name], ['Category', entity.categoryName ?? entity.category], ['Family', entity.familyName ?? entity.family], ['Type', entity.typeName], ['Level', entity.levelName]]));
259
323
  sections.push(importedPropertySection(groups));
260
- inspector.render({ state: 'ready', heading: isTeklaParser ? (teklaObjectFields(entity, own).name || entity.typeName || 'Tekla object') : (entity.name || entity.typeName || entity.id), sections });
324
+ inspector.render({ state: 'ready', heading: isTeklaParser ? (teklaObjectFields(entity, own).name || entity.typeName || 'Tekla object') : (entity.name || entity.typeName || entity.id), sections, after: [chatQuestionsSection] });
261
325
  if (publish) modelPanelBridge?.publishSelection(selectionOrigin);
262
326
  window.__instructor?.notifyChanged();
263
327
  return true;
@@ -1024,6 +1088,7 @@ async function loadRevision(state, authority, spatialCandidate) {
1024
1088
  if (token !== revisionLoadToken) return false;
1025
1089
  commitSpatialForRevision(spatialCandidate);
1026
1090
  teklaAudit = null; selectedId = null; selectedIds = []; geometrySelectionIds = [];
1091
+ loadedRevisionId = handle.revisionId; loadedSourceDigest = handle.sourceSha256;
1027
1092
  entities = nextEntities; properties = nextProperties; relationships = nextRelationships; entityById = nextEntityById; propertyByEntity = nextPropertyByEntity; teklaAudit = nextAudit;
1028
1093
  teklaAssemblyMembers = isTeklaParser ? teklaAssemblyMembership(nextRelationships) : new Map();
1029
1094
  selectionTools?.generationChanged();
@@ -1087,6 +1152,9 @@ function mountPanels() {
1087
1152
  return true;
1088
1153
  },
1089
1154
  panel: (tab) => tab === null || revitPanelHost.show(tab),
1155
+ selectedSubjects: modelSubjects,
1156
+ // AI Chat saved a question about model objects, or its scope changed: read the links again.
1157
+ chatLinksChanged: () => refreshChatLinks(true),
1090
1158
  });
1091
1159
  }
1092
1160
 
@@ -1278,6 +1346,7 @@ async function boot() {
1278
1346
  const authority = authorityButtons(state); const initialSpatial = await prepareSpatialForRevision(state, state[authority]);
1279
1347
  try { await loadRevision(state, authority, initialSpatial); } finally { initialSpatial.dispose(); }
1280
1348
  mountSharedModelTools();
1349
+ refreshChatLinks(false); window.addEventListener('focus', () => refreshChatLinks(false));
1281
1350
  const releasePointerCoordinates = viewport.onPointerWorld((renderPoint) => {
1282
1351
  lastCursorCoordinates = renderPoint && spatialTools ? spatialTools.coordinates(viewport.renderToCanonicalPoint(renderPoint)) : null;
1283
1352
  renderCursorCoordinates();
@@ -3511,6 +3511,7 @@ let GridDisplay = null; // grid-display.js — the Grid pane's ONE boundary betw
3511
3511
  let ViewGen = null; // steel-view-generation.js pure F11 helpers — loaded before saved views are sanitised
3512
3512
  let ModelCmd = null; // steel-model-commands.js — the model boundary's WRITE half (unit 5, P3a); the read half is steel-model-adapter.js
3513
3513
  let V2Projection = null, V2Commands = null, V2Validation = null, FilterCore = null, ProfileColours = null, ReferenceSheet = null, ReadConfidence = null;
3514
+ let ChatQuestions = null; // model-chat-questions.js — the Questions in chat card and chat labels, shared with every model viewer
3514
3515
  let ModelPanelBridge = null; // model-panel-bridge.js — feeds the workspace's left Model section (see modelPanelSnapshot)
3515
3516
  let modelPanelBridge = null, modelPanelGeneration = -1, modelPanelSelKey = null; // see modelPanelPublishPick
3516
3517
  // The 3D panel's container and its four tab bodies, found once and then HELD: in the main window they move
@@ -4143,7 +4144,7 @@ async function boot() {
4143
4144
  if (!APP_ID) { showEmpty('⊞', 'No workflow selected', 'Open a workflow in the FloLess canvas, then open the contract editor from that workflow’s node.'); return; }
4144
4145
  armEarlyViewToggle(); // BEFORE the first await — that is the whole point; see above
4145
4146
  startContractEvents(); // subscribe first; contract events buffer until the atomic snapshot is installed
4146
- [DisplayUnits, GridDisplay, SteelCore, ViewGen, ModelCmd, DetailRefs, V2Projection, V2Commands, V2Validation, SplitView, FilterCore, PlanXf, CatalogPicker, ModelEditor, ViewportToolbar, ModelLighting, PointerDock, EditorShell, ReviewClient, ProfileColours, ReferenceSheet, ReadConfidence, CkStd, ModelPanelBridge] = await Promise.all([
4147
+ [DisplayUnits, GridDisplay, SteelCore, ViewGen, ModelCmd, DetailRefs, V2Projection, V2Commands, V2Validation, SplitView, FilterCore, PlanXf, CatalogPicker, ModelEditor, ViewportToolbar, ModelLighting, PointerDock, EditorShell, ReviewClient, ProfileColours, ReferenceSheet, ReadConfidence, CkStd, ModelPanelBridge, ChatQuestions] = await Promise.all([
4147
4148
  import('./display-units.js'), import('./grid-display.js'),
4148
4149
  import('./steel-3d-core.js'), import('./steel-view-generation.js'), import('./steel-model-commands.js'),
4149
4150
  import('./steel-detail-refs.js'), import('./steel-model-v2-projection.js'),
@@ -4153,7 +4154,7 @@ async function boot() {
4153
4154
  import('./model-viewport-toolbar.js'), import('./model-viewport-lighting.js'), import('./model-pointer-dock.js'), import('./model-editor-shell.js'),
4154
4155
  import('./connection-review-client.js'), import('./steel-profile-colours.js'),
4155
4156
  import('./steel-reference-sheet.js'), import('./steel-read-confidence.js'),
4156
- import('./checkpoint-standard.js'), import('./model-panel-bridge.js'),
4157
+ import('./checkpoint-standard.js'), import('./model-panel-bridge.js'), import('./model-chat-questions.js'),
4157
4158
  ]);
4158
4159
  ({ FT_TO_MM, IN_TO_MM, LB_PER_FT_TO_KG_PER_M } = SteelCore); // the shared unit constants, bound before main() and every reader of them
4159
4160
  // BEFORE the first paint, deliberately. Every length on this page reads through it, so resolving it
@@ -14177,22 +14178,14 @@ function canonicalTargetItems(ids){
14177
14178
  }
14178
14179
  return {items,ignored,total};
14179
14180
  }
14180
- // A label exactly as the server stores it (server/chat-subjects.ts): control characters and runs of space collapsed,
14181
- // cut to 120 characters, trimmed. Sent this way and compared this way, so an unchanged long name never reads as renamed.
14182
- function subjectLabelText(text){return [...String(text||'').replace(/[\u0000-\u001f\u007f]+/g,' ').replace(/\s+/g,' ').trim()].slice(0,120).join('').trimEnd();}
14181
+ // A label exactly as the server stores it, and the selection's key: both shared with every model viewer.
14182
+ function subjectLabelText(text){return ChatQuestions.subjectLabelText(text);}
14183
14183
  function subjectLabel(item){
14184
14184
  if(item.kind==='member'){const m=(C.members||[]).find(x=>x&&x.id===item.id);return m?((m.mark||m.id)+(m.profile?' · '+m.profile:'')):item.id;}
14185
14185
  if(item.kind==='joint')return 'Connection '+item.id; // a placed joint (C.joints), never a connection-library row
14186
14186
  const d=(C.detail_placements||[]).find(x=>x&&x.id===item.id);return 'Detail '+((d&&d.detailName)||item.id);
14187
14187
  }
14188
- // 64-bit FNV-1a over the WHOLE canonical list, so a pill left out for one selection returns for another even
14189
- // when only objects past the 200 the pane receives changed.
14190
- function subjectsKeyOf(items){
14191
- let h1=0x811c9dc5,h2=0x01000193;
14192
- for(const item of items){const text=item.kind+':'+item.id+'\n';
14193
- for(let i=0;i<text.length;i++){const c=text.charCodeAt(i);h1=Math.imul(h1^c,0x01000193)>>>0;h2=Math.imul(h2^c,0x811c9dc5)>>>0;}}
14194
- return h1.toString(16).padStart(8,'0')+h2.toString(16).padStart(8,'0');
14195
- }
14188
+ function subjectsKeyOf(items){return ChatQuestions.subjectsKeyOf(items);}
14196
14189
  function modelSubjects(){
14197
14190
  const items=canonicalTargetItems([...selIds]).items;
14198
14191
  if(!items.length)return null;
@@ -14212,7 +14205,7 @@ function modelPanelPublishPick(){
14212
14205
  question. The links come from the server's per-project index; nothing is re-attached by label, and an object
14213
14206
  no longer in the model keeps its questions under "Questions about objects no longer in the model", with the
14214
14207
  label it had when asked. A failed read says so and offers Retry: it never claims there are no questions. */
14215
- let chatLinks={state:'idle',links:[],partial:false,key:''},chatLinksFetch=null,chatLinksAgain=false,chatQuestionsOpen=false,chatQuestionsMoreOpen=false;
14208
+ let chatLinks={state:'idle',links:[],partial:false,key:''},chatLinksFetch=null,chatLinksAgain=false;
14216
14209
  function chatScopeProjectId(){try{return window.parent&&window.parent!==window&&window.parent.flolessChat&&window.parent.flolessChat.scopeProjectId?window.parent.flolessChat.scopeProjectId():null;}catch(_){return null;}}
14217
14210
  function chatLinksAvailable(){return !!PROJECT&&chatScopeProjectId()===PROJECT;}
14218
14211
  function refreshChatLinks(force){
@@ -14238,94 +14231,22 @@ function chatSubjectResolves(link){
14238
14231
  if(link.kind==='detail')return (C.detail_placements||[]).some(d=>d&&d.id===link.id);
14239
14232
  return false;
14240
14233
  }
14241
- function chatQuestionDate(iso){const d=new Date(iso);return Number.isNaN(d.getTime())?'':d.toLocaleDateString(undefined,{day:'numeric',month:'short',year:'numeric'});}
14242
- // One row per question: the links of one message collapse into it, naming the objects it was about. A link is
14243
- // the person's selection, the chat model's note on it, or its answer naming the object (#1653). What a row says
14244
- // never depends on which link arrived first: every link of a question carries the same question line and time,
14245
- // the newest note wins, and "named in the answer" is a fact of the set.
14246
- function chatQuestionRows(links){
14247
- const byMessage=new Map();
14248
- for(const link of links){
14249
- let row=byMessage.get(link.messageEventId);
14250
- if(!row){row={link,labels:[],seen:new Set(),selected:false,named:false,aiNote:'',aiSeq:-1};byMessage.set(link.messageEventId,row);}
14251
- const key=link.kind+'\0'+link.id;
14252
- if(!row.seen.has(key)){row.seen.add(key);row.labels.push(link.label||link.id);}
14253
- if(link.origin==='ai-answer')row.named=true;else if(link.origin==='ai-note'){if(link.linkSequence>row.aiSeq){row.aiSeq=link.linkSequence;row.aiNote=link.aiNote||'';}}
14254
- else{if(!row.selected)row.link=link;row.selected=true;} // "When asked" reads the label from when the person asked
14255
- }
14256
- const askedAt=row=>String(row.link.askedAt||row.link.createdAt);
14257
- return [...byMessage.values()].sort((a,b)=>askedAt(b).localeCompare(askedAt(a))||(b.link.sequence-a.link.sequence));
14258
- }
14259
- // The id is all a link knows of its object, and a reader may give a removed member's id to a new one. So a row
14260
- // whose object is named differently now says what it was called when asked, rather than quietly vouching for it.
14261
- function chatQuestionWas(row){
14262
- const link=row.link;if(!link.label)return '';
14263
- const now=subjectLabelText(subjectLabel({kind:link.kind,id:link.id}));
14264
- return now&&now!==subjectLabelText(link.label)?link.label:'';
14265
- }
14266
- function chatQuestionRow(row,{about,unresolved}){
14267
- const link=row.link,li=document.createElement('div');li.className='chat-q';
14268
- const note=document.createElement('div');note.className='chat-q-note';note.textContent=link.note;note.dataset.tip=link.note;
14269
- li.append(note);
14270
- // The chat model's own sentence, said to be its own: untrusted text, one line, textContent only.
14271
- if(row.aiNote){const ai=document.createElement('div');ai.className='chat-q-ai';ai.textContent='AI note: '+row.aiNote;ai.dataset.tip=row.aiNote;li.append(ai);}
14272
- const meta=document.createElement('div');meta.className='chat-q-meta';
14273
- meta.textContent=[link.chatTitle,chatQuestionDate(link.askedAt||link.createdAt)].filter(Boolean).join(' · ')+(link.archived?' · archived':'');
14274
- li.append(meta);
14275
- if(row.named){const named=document.createElement('div');named.className='chat-q-about';named.textContent=row.selected?'Also named in the answer':'Named in the answer';li.append(named);}
14276
- if(about){const who=document.createElement('div');who.className='chat-q-about';
14277
- const names=row.labels.slice(0,3);who.textContent=(unresolved?'Was: ':'About ')+names.join(', ')+(row.labels.length>3?' and '+(row.labels.length-3)+' more':'');li.append(who);}
14278
- else{const was=chatQuestionWas(row);if(was){const who=document.createElement('div');who.className='chat-q-about';who.textContent='When asked: '+was;li.append(who);}}
14279
- const show=document.createElement('button');show.type='button';show.className='ghost chat-q-show';show.textContent='Show in chat';
14280
- show.dataset.commandId='steel.chat-question-show#'+link.messageEventId;show.dataset.commandInstanceLabel=link.note;
14281
- show.setAttribute('aria-label','Show in chat: '+link.note);
14282
- show.style.gridRow='1/span '+li.children.length; // spans every line this row has, and no empty ones
14283
- show.onclick=()=>{if(!modelPanelBridge||!modelPanelBridge.openChat(link.chatId,link.messageEventId,PROJECT))toast('AI Chat is not open for this project. Open the project in Workspaces, then choose Show in chat again.');};
14284
- li.append(show);return li;
14285
- }
14286
- function chatQuestionList(host,rows,opts){
14287
- const shown=rows.slice(0,3),rest=rows.slice(3);
14288
- for(const row of shown)host.append(chatQuestionRow(row,opts));
14289
- if(rest.length){const more=document.createElement('details');more.className='chat-q-more';more.open=chatQuestionsMoreOpen;
14290
- const sum=document.createElement('summary');sum.dataset.commandId='steel.chat-questions-more';more.append(sum);
14291
- const say=()=>{sum.textContent=more.open?'Show fewer':'Show '+rest.length+' more';};say();
14292
- more.addEventListener('toggle',()=>{chatQuestionsMoreOpen=more.open;say();}); // stays open across inspector repaints
14293
- for(const row of rest)more.append(chatQuestionRow(row,opts));host.append(more);}
14294
- }
14234
+ // The card's rows and words are shared with every model viewer (web/model-chat-questions.js); Steel decides only when
14235
+ // the panel may show it and which objects are selected and still in the model.
14236
+ const chatQuestionsUi={moreOpen:false,orphansOpen:false}; // stays open across inspector repaints
14295
14237
  function paintChatQuestions(p){
14296
14238
  p.querySelector(':scope > .chat-questions')?.remove();
14297
- if(!chatLinksAvailable()||chatLinks.state==='idle')return;
14239
+ if(!ChatQuestions||!chatLinksAvailable()||chatLinks.state==='idle')return;
14298
14240
  const takeover=gridMode||memberEndScan||memberEndReview||viewPropsId||dimStyleMode||NO_PLAN_VIEW||provisionalSelId||refSelectedObjIdx!==null||mode!=='sel';
14299
14241
  if(takeover)return;
14300
14242
  const selected=canonicalTargetItems([...selIds]).items;
14301
14243
  const nothing=!selIds.size&&!selGridIds.size&&!selDimIds.size;
14302
14244
  if(!selected.length&&!nothing)return;
14303
- const box=document.createElement('section');box.className='chat-questions';box.setAttribute('aria-label','Questions in chat');
14304
- const head=document.createDocumentFragment(); // the section's own top rule separates it from the inspector
14305
- if(chatLinks.state==='failed'){
14306
- // Said with nothing selected too: that is where questions about removed objects would be listed.
14307
- const line=document.createElement('div');line.className='hint chat-q-failed';line.textContent='Questions in chat could not be loaded.';
14308
- const retry=document.createElement('button');retry.type='button';retry.className='ghost';retry.textContent='Retry';retry.dataset.commandId='steel.chat-questions-retry';
14309
- retry.onclick=()=>refreshChatLinks(true);line.append(' ',retry);box.append(head,line);p.append(box);return;
14310
- }
14311
- const atLeast=chatLinks.partial?'at least ':'';
14312
- if(selected.length){
14313
- const keys=new Set(selected.map(item=>item.kind+'\0'+item.id));
14314
- const rows=chatQuestionRows(chatLinks.links.filter(link=>keys.has(link.kind+'\0'+link.id)));
14315
- if(!rows.length)return;
14316
- const title=document.createElement('div');title.className='sect chat-q-title';title.textContent='Questions in chat ('+atLeast+rows.length+')';
14317
- box.append(head,title);chatQuestionList(box,rows,{about:selected.length>1,unresolved:false});
14318
- p.append(box);return;
14319
- }
14320
- const orphans=chatQuestionRows(chatLinks.links.filter(link=>!chatSubjectResolves(link)));
14321
- if(!orphans.length)return;
14322
- const det=document.createElement('details');det.className='chat-q-orphans';det.open=chatQuestionsOpen;
14323
- det.addEventListener('toggle',()=>{chatQuestionsOpen=det.open;});
14324
- const sum=document.createElement('summary');sum.dataset.commandId='steel.chat-questions-orphans';
14325
- // Removed, or never there: an answer can name an id the model lacks.
14326
- sum.textContent='Questions about objects not in the model ('+atLeast+orphans.length+')';det.append(sum);
14327
- chatQuestionList(det,orphans,{about:true,unresolved:true});
14328
- box.append(head,det);p.append(box);
14245
+ const box=ChatQuestions.renderChatQuestions({doc:document,chatLinks,selected,resolves:chatSubjectResolves,
14246
+ currentLabel:link=>subjectLabelText(subjectLabel({kind:link.kind,id:link.id})),commandPrefix:'steel',
14247
+ onShow:link=>!!modelPanelBridge&&modelPanelBridge.openChat(link.chatId,link.messageEventId,PROJECT),
14248
+ onRetry:()=>refreshChatLinks(true),toast,ui:chatQuestionsUi});
14249
+ if(box)p.append(box);
14329
14250
  }
14330
14251
  function modelPanelSnapshot(){
14331
14252
  const n=allMembers().length;
@@ -351,6 +351,9 @@
351
351
  const $revitOpenModel = document.getElementById('ws-revit-open-model');
352
352
  const $revitReplace = document.getElementById('ws-revit-replace');
353
353
  const $revitRetry = document.getElementById('ws-revit-retry');
354
+ const $importReport = document.getElementById('ws-import-report');
355
+ /** The failed import the "Report this problem" button would hand to support, or null. */
356
+ let reportImportOperation = null;
354
357
  const $revitCancel = document.getElementById('ws-revit-cancel');
355
358
  const $revitReassure = document.getElementById('ws-source-reassure');
356
359
  let revitSourceState = null;
@@ -2723,6 +2726,17 @@
2723
2726
  paintRevitSourceActions('failed', revitSourceState?.canReplace === true, revitActiveOperation?.failure?.retryable !== false);
2724
2727
  }
2725
2728
  });
2729
+ $importReport?.addEventListener('click', () => {
2730
+ const operation = reportImportOperation;
2731
+ if (!operation || !current) return;
2732
+ const title = $sourcePlaceholder?.querySelector('.ws-source-title')?.textContent || '';
2733
+ window.dispatchEvent(new CustomEvent('floless:report-import-issue', { detail: {
2734
+ importer: isTeklaParserProject(current) ? 'tekla' : 'revit',
2735
+ operationId: operation.operationId,
2736
+ title,
2737
+ returnFocus: $importReport,
2738
+ } }));
2739
+ });
2726
2740
  $revitRetry?.addEventListener('click', async () => {
2727
2741
  const project = current;
2728
2742
  const failedOperationId = revitActiveOperation?.operationId;
@@ -2735,7 +2749,7 @@
2735
2749
  pollRevitImport(started.operation.operationId, project.id);
2736
2750
  } catch (error) {
2737
2751
  paintRevitSourceState('Couldn’t retry the RVT', `${error && error.message || error} The existing model was not changed.`);
2738
- paintRevitSourceActions('failed', revitSourceState?.canReplace === true, revitActiveOperation?.failure?.retryable !== false);
2752
+ paintRevitSourceActions('failed', revitSourceState?.canReplace === true, revitActiveOperation?.failure?.retryable !== false, revitActiveOperation);
2739
2753
  }
2740
2754
  });
2741
2755
  $revitCancel?.addEventListener('click', async () => {
@@ -3452,6 +3466,12 @@
3452
3466
  $revitRetry.dataset.commandId = 'revit.retry-import';
3453
3467
  $revitRetry.dataset.tip = 'Try importing the already stored RVT again.';
3454
3468
  }
3469
+ if ($importReport) {
3470
+ $importReport.dataset.commandId = tekla ? 'tekla-parser.report-import-failure' : 'revit.report-import-failure';
3471
+ $importReport.dataset.tip = tekla
3472
+ ? 'Send this read’s failure details to the FloLess team. You see exactly what is included before sending.'
3473
+ : 'Send this import’s failure details to the FloLess team. You see exactly what is included before sending.';
3474
+ }
3455
3475
  $revitCancel.textContent = tekla ? 'Cancel read' : 'Cancel import';
3456
3476
  $revitCancel.dataset.commandId = tekla ? 'tekla-parser.cancel-import' : 'revit.cancel-import';
3457
3477
  $revitCancel.dataset.tip = tekla
@@ -3463,14 +3483,26 @@
3463
3483
  window.__instructor?.notifyChanged();
3464
3484
  }
3465
3485
 
3466
- function paintRevitSourceActions(mode, canReplace = true, canRetry = true) {
3486
+ // #1757: a failed import the person can hand to support. Only a durable failed operation qualifies
3487
+ // (a browser-side admission failure has no record to attach), and not the two kinds whose next step
3488
+ // is not support: access (sign in) and superseded (nothing to do).
3489
+ function reportableImport(operation) {
3490
+ return !!operation && operation.state === 'failed' && typeof operation.operationId === 'string'
3491
+ && !['access', 'superseded'].includes(operation.failure?.kind);
3492
+ }
3493
+
3494
+ function paintRevitSourceActions(mode, canReplace = true, canRetry = true, failedOperation = null) {
3467
3495
  if (!$revitSourceActions) return;
3468
3496
  if (isTeklaParserProject()) canRetry = false;
3469
3497
  const busy = mode === 'active' || mode === 'uploading';
3498
+ const canReport = mode === 'failed' && reportableImport(failedOperation);
3499
+ reportImportOperation = canReport ? failedOperation : null;
3470
3500
  $revitOpenModel.hidden = mode !== 'imported';
3471
- $revitSourceActions.hidden = !canReplace && !busy && !(mode === 'failed' && canRetry) && mode !== 'imported';
3501
+ // Report counts toward the row: a failure with no Replace access and no Retry still offers it.
3502
+ $revitSourceActions.hidden = !canReplace && !busy && !(mode === 'failed' && canRetry) && !canReport && mode !== 'imported';
3472
3503
  $revitReplace.hidden = busy || !canReplace;
3473
3504
  $revitRetry.hidden = mode !== 'failed' || !canRetry;
3505
+ if ($importReport) $importReport.hidden = !canReport;
3474
3506
  $revitCancel.hidden = mode !== 'active';
3475
3507
  $revitReassure.hidden = !busy;
3476
3508
  // This is also the live region: aria-busy would suppress spoken progress.
@@ -3515,7 +3547,7 @@
3515
3547
  failure?.message || (tekla
3516
3548
  ? 'Choose the Tekla model folder or ZIP again to start a new read.'
3517
3549
  : 'FloLess could not import this model. Try again or contact support if the problem continues.'));
3518
- paintRevitSourceActions('failed', response.state.canReplace === true, failure?.retryable !== false);
3550
+ paintRevitSourceActions('failed', response.state.canReplace === true, failure?.retryable !== false, revitActiveOperation);
3519
3551
  } else {
3520
3552
  const source = response.state.source;
3521
3553
  const admissionFailure = tekla ? teklaAdmissionFailures.get(projectId) : null;
@@ -3815,7 +3847,7 @@
3815
3847
  failure?.message || (tekla
3816
3848
  ? 'Choose the Tekla model folder or ZIP again to start a new read.'
3817
3849
  : 'FloLess could not import this model. Try again or contact support if the problem continues.'));
3818
- paintRevitSourceActions('failed', revitSourceState?.canReplace === true, !tekla && failure?.retryable !== false);
3850
+ paintRevitSourceActions('failed', revitSourceState?.canReplace === true, !tekla && failure?.retryable !== false, operation);
3819
3851
  await refreshModelPresence(projectId, current.app, true);
3820
3852
  await refreshApprovalState(projectId);
3821
3853
  if (!tekla && failure?.retryable !== false && !$revitRetry?.hidden) queueMicrotask(() => $revitRetry?.focus());
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@floless/app",
3
- "version": "0.144.0",
3
+ "version": "0.146.0",
4
4
  "type": "module",
5
5
  "description": "Thin localhost host for floless.app — serves web/ and shells the aware CLI. No engine, no LLM.",
6
6
  "bin": {