@floless/app 0.145.0 → 0.147.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.
@@ -0,0 +1,178 @@
1
+ /*
2
+ * model-chat-questions.js - model objects in AI Chat (#1653), shared by every model viewer and the server.
3
+ *
4
+ * A question asked in the left AI Chat with objects selected is linked to them, and the chat model may link the
5
+ * objects its answer names. This module holds what every viewer must say the same way: how an object is named when it
6
+ * goes to chat, the key that tells one selection from another, and the "Questions in chat" card. The Steel Model and
7
+ * the snapshot viewer (Revit, Tekla Parser) all render the card from here, and the server names objects with the same
8
+ * function the viewer uses, so a label never differs between the pill, the card and the chat model's links. Each page
9
+ * styles the card with its own theme tokens; the words and the rows are only here.
10
+ *
11
+ * Pure: no page globals. DOM builders take the document they build in.
12
+ */
13
+ import { teklaObjectFields, teklaObjectLabel } from './model-property-display.js';
14
+
15
+ /** A label exactly as the server stores it (server/chat-subjects.ts): control characters and runs of space
16
+ * collapsed, cut to 120 characters, trimmed. Sent this way and compared this way, so an unchanged long name never
17
+ * reads as renamed. */
18
+ export function subjectLabelText(text) {
19
+ return [...String(text || '').replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim()].slice(0, 120).join('').trimEnd();
20
+ }
21
+
22
+ /**
23
+ * An object of a snapshot model as AI Chat names it. Revit: what it is, then its id (`Basic Wall · element:382`) -
24
+ * many elements share a type and some rows carry none, so a name without the id reads as a duplicate. Tekla Parser:
25
+ * the name, profile and Tekla ID the viewer shows, with the entity id added when the read had no Tekla ID.
26
+ * `rows` are the entity's property rows (Tekla reads its name and profile from them).
27
+ */
28
+ export function modelSubjectLabel(source, entity, rows = []) {
29
+ const id = String(entity?.id ?? '');
30
+ if (source === 'tekla-parser') {
31
+ const fields = teklaObjectFields(entity || {}, rows);
32
+ const label = teklaObjectLabel(entity || {}, rows);
33
+ return fields.id == null ? `${label} · ${id}` : label;
34
+ }
35
+ const what = entity?.name || entity?.typeName || entity?.categoryName || entity?.category || 'Revit element';
36
+ return `${what} · ${id}`;
37
+ }
38
+
39
+ /** 64-bit FNV-1a over the WHOLE canonical list, so a pill left out for one selection returns for another even when
40
+ * only objects past the 200 the pane receives changed. */
41
+ export function subjectsKeyOf(items) {
42
+ let h1 = 0x811c9dc5, h2 = 0x01000193;
43
+ for (const item of items) {
44
+ const text = `${item.kind}:${item.id}\n`;
45
+ for (let i = 0; i < text.length; i++) {
46
+ const c = text.charCodeAt(i);
47
+ h1 = Math.imul(h1 ^ c, 0x01000193) >>> 0; h2 = Math.imul(h2 ^ c, 0x811c9dc5) >>> 0;
48
+ }
49
+ }
50
+ return h1.toString(16).padStart(8, '0') + h2.toString(16).padStart(8, '0');
51
+ }
52
+
53
+ /* -- Questions in chat: the object card ---------------------------------------------------------------------------
54
+ Selecting an object shows how many questions were about it, the first line of each, and Show in chat, which opens
55
+ that conversation at that question. Nothing is re-attached by label: an object the model no longer has keeps its
56
+ questions under "Questions about objects not in the model", with the label it had when asked. A failed read says so
57
+ and offers Retry; it never claims there are no questions. */
58
+
59
+ /** Said when Show in chat cannot reach AI Chat for this project. */
60
+ export const CHAT_NOT_OPEN_COPY = 'AI Chat is not open for this project. Open the project in Workspaces, then choose Show in chat again.';
61
+
62
+ export function chatQuestionDate(iso) {
63
+ const date = new Date(iso);
64
+ return Number.isNaN(date.getTime()) ? '' : date.toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: 'numeric' });
65
+ }
66
+
67
+ /**
68
+ * One row per question: the links of one message collapse into it, naming the objects it was about. A link is the
69
+ * person's selection, the chat model's note on it, or its answer naming the object. What a row says never depends on
70
+ * which link arrived first: every link of a question carries the same question line and time, the newest note wins,
71
+ * and "named in the answer" is a fact of the set. Newest question first.
72
+ */
73
+ export function chatQuestionRows(links) {
74
+ const byMessage = new Map();
75
+ for (const link of links) {
76
+ let row = byMessage.get(link.messageEventId);
77
+ if (!row) { row = { link, labels: [], seen: new Set(), selected: false, named: false, aiNote: '', aiSeq: -1 }; byMessage.set(link.messageEventId, row); }
78
+ const key = `${link.kind}\0${link.id}`;
79
+ if (!row.seen.has(key)) { row.seen.add(key); row.labels.push(link.label || link.id); }
80
+ if (link.origin === 'ai-answer') row.named = true;
81
+ else if (link.origin === 'ai-note') { if (link.linkSequence > row.aiSeq) { row.aiSeq = link.linkSequence; row.aiNote = link.aiNote || ''; } }
82
+ else { if (!row.selected) row.link = link; row.selected = true; } // "When asked" reads the label from when the person asked
83
+ }
84
+ const askedAt = (row) => String(row.link.askedAt || row.link.createdAt);
85
+ return [...byMessage.values()].sort((a, b) => askedAt(b).localeCompare(askedAt(a)) || (b.link.sequence - a.link.sequence));
86
+ }
87
+
88
+ /** The id is all a link knows of its object, and a reader may give a removed object's id to a new one. So a row whose
89
+ * object is named differently now says what it was called when asked, rather than quietly vouching for it.
90
+ * `currentLabel(link)` is the object's label now, '' when unknown. */
91
+ export function chatQuestionWas(row, currentLabel) {
92
+ const link = row.link; if (!link.label) return '';
93
+ const now = subjectLabelText(currentLabel(link));
94
+ return now && now !== subjectLabelText(link.label) ? link.label : '';
95
+ }
96
+
97
+ function chatQuestionRow(doc, row, opts) {
98
+ const { about, unresolved, commandPrefix, currentLabel, onShow, toast } = opts;
99
+ const link = row.link, li = doc.createElement('div'); li.className = 'chat-q';
100
+ const note = doc.createElement('div'); note.className = 'chat-q-note'; note.textContent = link.note; note.dataset.tip = link.note;
101
+ li.append(note);
102
+ // The chat model's own sentence, said to be its own: untrusted text, one line, textContent only.
103
+ if (row.aiNote) { const ai = doc.createElement('div'); ai.className = 'chat-q-ai'; ai.textContent = `AI note: ${row.aiNote}`; ai.dataset.tip = row.aiNote; li.append(ai); }
104
+ const meta = doc.createElement('div'); meta.className = 'chat-q-meta';
105
+ meta.textContent = [link.chatTitle, chatQuestionDate(link.askedAt || link.createdAt)].filter(Boolean).join(' · ') + (link.archived ? ' · archived' : '');
106
+ li.append(meta);
107
+ if (row.named) { const named = doc.createElement('div'); named.className = 'chat-q-about'; named.textContent = row.selected ? 'Also named in the answer' : 'Named in the answer'; li.append(named); }
108
+ if (about) {
109
+ const who = doc.createElement('div'); who.className = 'chat-q-about';
110
+ const names = row.labels.slice(0, 3);
111
+ who.textContent = (unresolved ? 'Was: ' : 'About ') + names.join(', ') + (row.labels.length > 3 ? ` and ${row.labels.length - 3} more` : '');
112
+ li.append(who);
113
+ } else {
114
+ const was = chatQuestionWas(row, currentLabel);
115
+ if (was) { const who = doc.createElement('div'); who.className = 'chat-q-about'; who.textContent = `When asked: ${was}`; li.append(who); }
116
+ }
117
+ const show = doc.createElement('button'); show.type = 'button'; show.className = 'ghost chat-q-show'; show.textContent = 'Show in chat';
118
+ show.dataset.commandId = `${commandPrefix}.chat-question-show#${link.messageEventId}`; show.dataset.commandInstanceLabel = link.note;
119
+ show.setAttribute('aria-label', `Show in chat: ${link.note}`);
120
+ show.style.gridRow = `1/span ${li.children.length}`; // spans every line this row has, and no empty ones
121
+ show.onclick = () => { if (!onShow(link)) toast(CHAT_NOT_OPEN_COPY); };
122
+ li.append(show); return li;
123
+ }
124
+
125
+ function chatQuestionList(doc, host, rows, opts) {
126
+ const shown = rows.slice(0, 3), rest = rows.slice(3);
127
+ for (const row of shown) host.append(chatQuestionRow(doc, row, opts));
128
+ if (!rest.length) return;
129
+ const more = doc.createElement('details'); more.className = 'chat-q-more'; more.open = opts.ui.moreOpen === true;
130
+ const sum = doc.createElement('summary'); sum.dataset.commandId = `${opts.commandPrefix}.chat-questions-more`; more.append(sum);
131
+ const say = () => { sum.textContent = more.open ? 'Show fewer' : `Show ${rest.length} more`; }; say();
132
+ more.addEventListener('toggle', () => { opts.ui.moreOpen = more.open; say(); }); // stays open across repaints
133
+ for (const row of rest) more.append(chatQuestionRow(doc, row, opts));
134
+ host.append(more);
135
+ }
136
+
137
+ /**
138
+ * The "Questions in chat" card, or null when there is nothing to say.
139
+ * chatLinks {state: 'idle'|'ready'|'failed', links, partial}
140
+ * selected the selected objects as [{kind, id}]; empty when nothing is selected, and then the questions about
141
+ * objects not in the model are offered instead
142
+ * resolves(link) the link's object is in the model shown now
143
+ * currentLabel(link) the object's label now, '' when unknown
144
+ * commandPrefix the page's Instructor namespace ('steel', 'revit', 'tekla-parser')
145
+ * onShow(link) open AI Chat at that question; false when AI Chat cannot be reached
146
+ * onRetry(), toast(text)
147
+ * ui {moreOpen, orphansOpen}, kept by the page so an open list stays open across repaints
148
+ */
149
+ export function renderChatQuestions({ doc, chatLinks, selected, resolves, currentLabel, commandPrefix, onShow, onRetry, toast, ui }) {
150
+ if (!chatLinks || chatLinks.state === 'idle') return null;
151
+ const box = doc.createElement('section'); box.className = 'chat-questions'; box.setAttribute('aria-label', 'Questions in chat');
152
+ if (chatLinks.state === 'failed') {
153
+ // Said with nothing selected too: that is where questions about removed objects would be listed.
154
+ const line = doc.createElement('div'); line.className = 'hint chat-q-failed'; line.textContent = 'Questions in chat could not be loaded.';
155
+ const retry = doc.createElement('button'); retry.type = 'button'; retry.className = 'ghost'; retry.textContent = 'Retry';
156
+ retry.dataset.commandId = `${commandPrefix}.chat-questions-retry`;
157
+ retry.onclick = () => onRetry(); line.append(' ', retry); box.append(line); return box;
158
+ }
159
+ const opts = { commandPrefix, currentLabel, onShow, toast, ui };
160
+ const atLeast = chatLinks.partial ? 'at least ' : '';
161
+ if (selected.length) {
162
+ const keys = new Set(selected.map((item) => `${item.kind}\0${item.id}`));
163
+ const rows = chatQuestionRows(chatLinks.links.filter((link) => keys.has(`${link.kind}\0${link.id}`) && resolves(link)));
164
+ if (!rows.length) return null;
165
+ const title = doc.createElement('div'); title.className = 'sect chat-q-title'; title.textContent = `Questions in chat (${atLeast}${rows.length})`;
166
+ box.append(title); chatQuestionList(doc, box, rows, { ...opts, about: selected.length > 1, unresolved: false });
167
+ return box;
168
+ }
169
+ const orphans = chatQuestionRows(chatLinks.links.filter((link) => !resolves(link)));
170
+ if (!orphans.length) return null;
171
+ const det = doc.createElement('details'); det.className = 'chat-q-orphans'; det.open = ui.orphansOpen === true;
172
+ det.addEventListener('toggle', () => { ui.orphansOpen = det.open; });
173
+ const sum = doc.createElement('summary'); sum.dataset.commandId = `${commandPrefix}.chat-questions-orphans`;
174
+ // Removed, never there, or read from another source file: an answer can name an id the model lacks.
175
+ sum.textContent = `Questions about objects not in the model (${atLeast}${orphans.length})`; det.append(sum);
176
+ chatQuestionList(doc, det, orphans, { ...opts, about: true, unresolved: true });
177
+ box.append(det); return box;
178
+ }
@@ -34,7 +34,7 @@ const PLACEMENTS = ['floating', 'docked'];
34
34
  * readOnly?: boolean,
35
35
  * emptyMessage?: string,
36
36
  * }} options
37
- * @returns {{ render(view): void, headerText(): string, destroy(): void }}
37
+ * @returns {{ render(view): void, refreshAfter(): void, headerText(): string, destroy(): void }}
38
38
  */
39
39
  export function mountInspectorShell({
40
40
  panel, doc, win, placement, readOnly = false,
@@ -57,6 +57,42 @@ export function mountInspectorShell({
57
57
  };
58
58
 
59
59
  let header = null;
60
+ // TRAILING SECTIONS (`view.after`) say something about the selection in EVERY settled state - after the body when
61
+ // an object is shown, after the note when nothing is selected or it went away (#1653: Questions in chat lists
62
+ // questions about objects no longer in the model when nothing is selected). They live in their own container so
63
+ // they can repaint alone (`refreshAfter`) when their own data arrives, without rebuilding the property sections
64
+ // above - a search typed into those survives.
65
+ let after = [];
66
+ let afterHost = null;
67
+
68
+ const paintSection = (section) => {
69
+ // `editable !== false` rather than `editable === true`: undeclared fails closed.
70
+ if (readOnly && section.editable !== false) return null;
71
+ const host = el('div', 'insp-section');
72
+ host.dataset.section = section.id || '';
73
+ if (section.heading) host.append(el('div', 'insp-section-heading', section.heading));
74
+ try {
75
+ section.render(host);
76
+ } catch (error) {
77
+ // Said in place rather than swallowed. A section that vanishes without explanation reads as
78
+ // "this object has no dimensions" - a confident wrong answer, the worst state a property panel
79
+ // can be in. The user gets the fact; the console keeps the cause for whoever debugs it.
80
+ try { win.console?.error?.('[inspector] a section could not be shown', section.id || '', error); } catch { /* reporting must not throw */ }
81
+ host.append(el('div', 'insp-error', 'This section could not be shown.'));
82
+ }
83
+ return host;
84
+ };
85
+
86
+ const paintAfter = () => {
87
+ // A trailing section that has nothing to say leaves no empty ruled box behind.
88
+ afterHost.replaceChildren(...after.map(paintSection).filter((host) => host && host.children.length));
89
+ };
90
+ const withAfter = (sections) => {
91
+ after = Array.isArray(sections) ? sections : [];
92
+ afterHost = el('div', 'insp-after');
93
+ paintAfter();
94
+ return afterHost;
95
+ };
60
96
 
61
97
  /**
62
98
  * Paint a view.
@@ -71,13 +107,14 @@ export function mountInspectorShell({
71
107
  * also simply more accurate: this is a heading rendered as text, never a tooltip.
72
108
  */
73
109
  const render = (view = {}) => {
74
- const { state = 'empty', heading = '', message, sections = [] } = view;
110
+ const { state = 'empty', heading = '', message, sections = [], after: trailing = [] } = view;
75
111
 
76
112
  if (state === 'loading') {
77
113
  // The header is REUSED, not rebuilt, so the box it occupies never collapses mid-load.
78
114
  panel.setAttribute('aria-busy', 'true');
79
115
  const kept = header && heading === header.textContent ? header : el('div', 'insp-head', heading);
80
116
  header = kept;
117
+ after = []; afterHost = null;
81
118
  panel.replaceChildren(kept, el('div', 'insp-note', 'Loading…'));
82
119
  return;
83
120
  }
@@ -90,7 +127,7 @@ export function mountInspectorShell({
90
127
  header = null;
91
128
  // The two are DIFFERENT facts. "Nothing selected" and "what you had is gone" collapse into one
92
129
  // only if you are willing to tell the user they deselected something the model removed.
93
- panel.replaceChildren(el('div', `insp-note insp-${state}`, message || emptyMessage));
130
+ panel.replaceChildren(el('div', `insp-note insp-${state}`, message || emptyMessage), withAfter(trailing));
94
131
  return;
95
132
  }
96
133
 
@@ -98,30 +135,18 @@ export function mountInspectorShell({
98
135
  const body = el('div', 'insp-body');
99
136
 
100
137
  for (const section of sections) {
101
- // `editable !== false` rather than `editable === true`: undeclared fails closed.
102
- if (readOnly && section.editable !== false) continue;
103
-
104
- const host = el('div', 'insp-section');
105
- host.dataset.section = section.id || '';
106
- if (section.heading) host.append(el('div', 'insp-section-heading', section.heading));
107
- try {
108
- section.render(host);
109
- } catch {
110
- // Said in place rather than swallowed. A section that vanishes without explanation reads as
111
- // "this object has no dimensions" - a confident wrong answer, the worst state a property panel
112
- // can be in. The error itself is the host's to log; the user gets the fact.
113
- host.append(el('div', 'insp-error', 'This section could not be shown.'));
114
- }
115
- body.append(host);
138
+ const host = paintSection(section);
139
+ if (host) body.append(host);
116
140
  }
117
141
 
118
- panel.replaceChildren(header, body);
142
+ panel.replaceChildren(header, body, withAfter(trailing));
119
143
  };
120
144
 
121
145
  render({ state: 'empty' });
122
146
 
123
147
  return {
124
148
  render,
149
+ refreshAfter() { if (afterHost) paintAfter(); },
125
150
  headerText: () => (header ? header.textContent : ''),
126
151
  destroy() { panel.replaceChildren(); },
127
152
  };
@@ -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;