@floless/app 0.157.0 → 0.158.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.
@@ -419,11 +419,19 @@
419
419
  description: 'PDF or image',
420
420
  accept: { 'application/pdf': ['.pdf'], 'image/*': ['.png', '.jpg', '.jpeg', '.gif', '.webp', '.bmp'] },
421
421
  }];
422
- async function pickDrawingFiles(fallbackInput) {
422
+ const STEEL_DRAWING_FILE_TYPES = [{ description: 'PDF drawing sets', accept: { 'application/pdf': ['.pdf'] } }];
423
+ function validateSteelDrawingFiles(templateId, files) {
424
+ if (templateId !== 'steel-model' || files.every((file) => /\.pdf$/i.test(file.name))) return true;
425
+ showToast('Steel Model reads PDF drawing sets. Nothing was attached because the selection contains a non-PDF file. Choose PDF drawings instead.', 'warn');
426
+ return false;
427
+ }
428
+ async function pickDrawingFiles(fallbackInput, templateId) {
429
+ const steel = templateId === 'steel-model';
430
+ if (fallbackInput) fallbackInput.accept = steel ? '.pdf' : '.pdf,image/*';
423
431
  if (window.showOpenFilePicker) {
424
432
  const wasFocused = pageHasFocus(), startedAt = Date.now();
425
433
  try {
426
- const handles = await window.showOpenFilePicker({ multiple: true, types: DRAWING_FILE_TYPES });
434
+ const handles = await window.showOpenFilePicker({ multiple: true, types: steel ? STEEL_DRAWING_FILE_TYPES : DRAWING_FILE_TYPES, excludeAcceptAllOption: steel });
427
435
  return Promise.all(handles.map((h) => h.getFile()));
428
436
  } catch (err) {
429
437
  if (chooserEndedWithoutChoice(err, wasFocused, startedAt)) return []; // a cancel is silent; a refusal said so
@@ -743,10 +751,10 @@
743
751
  {
744
752
  kind: 'drawing',
745
753
  headline: 'Steel model from drawings',
746
- capability: 'PDF or image → 3D steel model',
747
- sub: 'Turn steel drawings into a 3D model you can review and export.',
748
- label: 'Pick drawings',
749
- dropHint: 'Click or drop drawings',
754
+ capability: 'PDF drawing set → 3D steel model',
755
+ sub: 'Turn a PDF drawing set into a 3D model you can review and export.',
756
+ label: 'Pick PDF drawings',
757
+ dropHint: 'Click or drop PDFs',
750
758
  },
751
759
  ],
752
760
  editor: '/steel-editor.html',
@@ -755,9 +763,9 @@
755
763
  { key: 'knowledge', label: 'Knowledge' }, // per-project KB — the job's context, consulted by everything
756
764
  { key: 'drawings', label: 'Drawing Filter' },
757
765
  { key: 'model', label: 'Model' },
766
+ { key: 'pages', label: 'Pages' }, // #2262: stored, versioned HTML Pages; #2568: just before Exports (both are output)
758
767
  { key: 'exports', label: 'Exports' },
759
768
  { key: 'history', label: 'History' },
760
- { key: 'pages', label: 'Pages' }, // #2262: stored, versioned HTML Pages (every app)
761
769
  ],
762
770
  diff: true, // steel semantic diff expander
763
771
  exports: [
@@ -806,9 +814,9 @@
806
814
  { key: 'knowledge', label: 'Knowledge' }, // KB is project-level — every workspace app gets it
807
815
  { key: 'drawings', label: 'Source' }, // reuse the 'drawings' frame slot; label "Source"
808
816
  { key: 'model', label: 'Traced' }, // reuse the 'model' frame slot; label "Traced"
817
+ { key: 'pages', label: 'Pages' }, // #2262: stored, versioned HTML Pages; #2568: just before Exports (both are output)
809
818
  { key: 'exports', label: 'Exports' },
810
819
  { key: 'history', label: 'History' },
811
- { key: 'pages', label: 'Pages' }, // #2262: stored, versioned HTML Pages (every app)
812
820
  ],
813
821
  diff: false,
814
822
  exports: [
@@ -1562,15 +1570,16 @@
1562
1570
  $workflowTab.removeAttribute('aria-disabled');
1563
1571
  $workflowTab.removeAttribute('data-blocked-reason');
1564
1572
  }
1573
+ // The tab's own icon and label, kept on the tab while the spinner stands in for them and put back when it is done.
1574
+ // Taken on the first call, whichever way it goes: leaving for Workspaces calls this with false before Workflows
1575
+ // has ever opened, and taking them only on true then wiped the icon for good.
1576
+ $workflowTab.idleNodes ??= [...$workflowTab.childNodes];
1565
1577
  if (opening) {
1566
1578
  $workflowTab.setAttribute('aria-label', 'Opening Workflows');
1567
- // The tab's own icon is kept on the tab while the spinner stands in for it, and put back when it is done.
1568
- $workflowTab.idleIcon ??= $workflowTab.querySelector?.('.mode-icon') || null;
1569
1579
  $workflowTab.innerHTML = '<span class="rtn-spinner" aria-hidden="true"></span><span>Opening Workflows…</span>';
1570
1580
  } else {
1571
1581
  $workflowTab.removeAttribute('aria-label');
1572
- $workflowTab.textContent = 'Workflows';
1573
- if ($workflowTab.idleIcon) $workflowTab.prepend($workflowTab.idleIcon);
1582
+ $workflowTab.replaceChildren(...$workflowTab.idleNodes);
1574
1583
  }
1575
1584
  }
1576
1585
  async function setMode(m) {
@@ -3248,7 +3257,7 @@
3248
3257
  return;
3249
3258
  }
3250
3259
  let files;
3251
- try { files = await pickDrawingFiles($seedFile); } // keep native picker in the click activation
3260
+ try { files = await pickDrawingFiles($seedFile, templateId); } // keep native picker in the click activation
3252
3261
  catch { showToast('Couldn’t open the drawing picker. Try again.', 'warn'); return; }
3253
3262
  if (!files.length) return;
3254
3263
  if (workspaceWorkflowKnownMissing(appId)) {
@@ -3554,7 +3563,10 @@
3554
3563
  const name = zone.querySelector('.ws-seed-headline')?.textContent || 'This card';
3555
3564
  const other = (card) => (card && card !== name ? card : null);
3556
3565
  const revit = files.some((file) => /\.rvt$/i.test(file.name)) && other(cardFor('rvt'));
3557
- const drawing = files.some(isDrawingFile) && other(cardFor('drawing'));
3566
+ const drawingCard = files.some((file) => isDrawingFile(file) && !/\.pdf$/i.test(file.name))
3567
+ ? $landing.querySelector('[data-seed-drop-kind="drawing"]:not([data-seed-template="steel-model"]) .ws-seed-headline')?.textContent
3568
+ : cardFor('drawing');
3569
+ const drawing = files.some(isDrawingFile) && other(drawingCard);
3558
3570
  const tekla = (folderCount || files.some((file) => /\.zip$/i.test(file.name))) && other(cardFor('tekla-source'));
3559
3571
  const next = revit ? `Drop it on ${revit} instead.`
3560
3572
  : drawing ? `Drop it on ${drawing} instead.`
@@ -3664,7 +3676,8 @@
3664
3676
  return;
3665
3677
  }
3666
3678
  const drawings = files.filter(isDrawingFile);
3667
- if (!drawings.length) { showToast(misdropMessage(zone, DRAWING_FORMATS, files, folderCount), 'warn'); return; }
3679
+ if (!drawings.length) { showToast(misdropMessage(zone, templateId === 'steel-model' ? 'PDF drawing sets' : DRAWING_FORMATS, files, folderCount), 'warn'); return; }
3680
+ if (!validateSteelDrawingFiles(templateId, files)) return;
3668
3681
  if (workspaceWorkflowKnownMissing(appId)) { showToast(missingWorkspaceWorkflowMessage(templateId), 'warn'); return; }
3669
3682
  const skippedFiles = files.length - drawings.length;
3670
3683
  const skipped = [
@@ -3772,6 +3785,8 @@
3772
3785
  if (userMessage) return userMessage;
3773
3786
  const raw = String(error && error.body?.error || error && error.message || error || '');
3774
3787
  const code = String(error && (error.code || error.body?.code) || '');
3788
+ // This attachment refusal is authored for the person, including the PDF count/size remedy.
3789
+ if (code === 'steel-pdf-required') return raw;
3775
3790
  // Account access can expire while this dialog is open, before the folder chooser
3776
3791
  // or project creation runs. Name that cause without blaming the selected folder.
3777
3792
  const access = bridge.accountAccessText?.(error);
@@ -4206,6 +4221,7 @@
4206
4221
  if (!$projectSetup || projectSetupState) return false;
4207
4222
  // A Drawing Checker profile and a General project start with no source file: what goes in them comes later.
4208
4223
  if (!Array.isArray(files) || (!files.length && !NO_FILE_SETUP_KINDS.includes(kind))) return false;
4224
+ if (kind === 'drawings' && !validateSteelDrawingFiles(templateId, files)) return false;
4209
4225
  if (kind === 'drawings' && files.length > 20) {
4210
4226
  showToast('Choose up to 20 drawings for a new project.', 'warn');
4211
4227
  return false;
@@ -5405,6 +5421,12 @@
5405
5421
  b.setAttribute('data-command-id', `shell.workspace-step#${label}`);
5406
5422
  }
5407
5423
  });
5424
+ // #2568: the tabs read in the kind's own `steps` order (the markup holds every kind's tabs once). The tablist holds
5425
+ // nothing but tabs, so moving a button within it changes only its place, never its state or listeners.
5426
+ for (const st of d.steps) {
5427
+ const b = $stepTabs.querySelector(`button[data-step="${st.key}"]`);
5428
+ if (b) $stepTabs.append(b);
5429
+ }
5408
5430
  }
5409
5431
 
5410
5432
  // Everything the server refuses on write is refused again on read. A progress record is replayed
@@ -6050,7 +6072,7 @@
6050
6072
  ? 'Drawing read not started · Open Requests — if Start in AI Chat is shown, choose it; otherwise copy the request into Claude Code or Codex. Then return to review and save the Drawing Filter.'
6051
6073
  : projectContractLifecycle === 'filter-checkpoint'
6052
6074
  ? 'Drawing read needs restarting · The earlier drawing request is no longer available. Attach the drawing set again in Drawing Filter to restart the read.'
6053
- : 'Start in Drawing Filter by attaching a PDF or image. The Model, Exports, and History stages unlock after the first steel model is created.';
6075
+ : 'Start in Drawing Filter by attaching a PDF drawing set. The Model, Exports, and History stages unlock after the first steel model is created.';
6054
6076
  paintStageGuidance(guidance, failedInitial || unavailableInitial ? 'failed' : 'info');
6055
6077
  if (waitingForInitial && revCardReq?.prepassReady && !revCardReq?.filterCheckpointCurrent) {
6056
6078
  appendStageGuidanceFilterAction();
@@ -6156,7 +6178,17 @@
6156
6178
  // extracted and evaluated on its own by workspace-instructor-handoff.test.ts, and a closure
6157
6179
  // variable it cannot see is a ReferenceError there. It sits at the end of the step-tabs row now
6158
6180
  // (the breadcrumb row that used to hold it is gone), and is a Drawings-step control either way.
6159
- { const a = document.getElementById('ws-attach-revision'); if (a) a.hidden = s !== 'drawings' || d?.serverAuthorizedOnly === true; }
6181
+ { const a = document.getElementById('ws-attach-revision');
6182
+ const steel = d === WORKSPACE_APPS['steel-model'];
6183
+ if (a) {
6184
+ a.hidden = s !== 'drawings' || d?.serverAuthorizedOnly === true;
6185
+ a.dataset.tip = steel
6186
+ ? 'Attach revised PDF drawings — your terminal AI reads them into a new version'
6187
+ : 'Attach a revised drawing set (PDF or image) — your terminal AI reads it into a new version';
6188
+ }
6189
+ const input = document.getElementById('ws-revision-file');
6190
+ if (input) input.accept = steel ? '.pdf' : '.pdf,image/*';
6191
+ }
6160
6192
  renderRevisionCard(); // reflect any pending/failed revision read (card shows only on the Drawings step)
6161
6193
  // The conversion offer is Model-step scoped, and re-derived on every entry rather than cached:
6162
6194
  // the project's contract can change under this shell (a revision read, another tab, the editor's
@@ -7273,6 +7305,7 @@
7273
7305
  kbGraphIndex = null;
7274
7306
  lastStepHeadHtml = null;
7275
7307
  $wsKnowledge.querySelector('.kb-g-overview')?.remove(); // and the button already on screen goes now
7308
+ kbGraphStopWorker(); // #2491 R6.9: a layout still running for the previous project is dropped
7276
7309
  }
7277
7310
 
7278
7311
  function stopKnowledgePoll() { if (knowledgePoll) { clearInterval(knowledgePoll); knowledgePoll = null; } }
@@ -7310,6 +7343,8 @@
7310
7343
  sources: Array.isArray(manifest.sources) ? manifest.sources : [],
7311
7344
  currentGeneration: status.currentGeneration || null,
7312
7345
  organize: status.organize || null,
7346
+ // #2491 R6.9: the person's categories and where each reference sits.
7347
+ categories: status.categories || { v: 1, revision: 0, categories: [], placements: {}, state: 'absent' },
7313
7348
  queued: list.filter((r) => r && r.type === 'knowledge-organize' && r.project === proj.id),
7314
7349
  company,
7315
7350
  designSet,
@@ -7668,8 +7703,9 @@
7668
7703
  kbAddIssuePanel(st) + body + '</section>';
7669
7704
  }
7670
7705
 
7671
- function kbSourceRow(s, st) {
7706
+ function kbSourceRow(s, st, depth) {
7672
7707
  const on = !!s.useAsKb;
7708
+ const sel = kbSel.selected.has(s.sourceId);
7673
7709
  const ico = kbIcon(s.mime);
7674
7710
  const chip = KB_CHIP[s.state] || ['new', escapeHtml(String(s.state || 'new'))];
7675
7711
  const name = s.filename || 'untitled';
@@ -7683,12 +7719,13 @@
7683
7719
  // exclusions. `aria-current` (not `aria-selected`, which is invalid on a generic role and would
7684
7720
  // fail aria-allowed-attr) marks the row whose file is on screen.
7685
7721
  const isOpen = viewer.mode === 'file' && viewer.sourceId === s.sourceId;
7686
- return `<div class="kb-src${on ? '' : ' off'}${s.state === 'error' ? ' state-error' : ''}"` +
7722
+ return `<div class="kb-src${on ? '' : ' off'}${s.state === 'error' ? ' state-error' : ''}${sel ? ' selected' : ''}" draggable="true"` +
7723
+ (depth != null ? ` style="--kb-depth:${depth}"` : '') +
7687
7724
  ` data-source-id="${escapeAttr(s.sourceId)}"${isOpen ? ' aria-current="true"' : ''}>` +
7688
7725
  `<span class="kb-fico ${ico.cls}" aria-hidden="true">${ico.glyph}</span>` +
7689
7726
  `<div class="kb-fbody">` +
7690
- `<button type="button" class="kb-fname" data-kb-open="${escapeAttr(s.sourceId)}" ` +
7691
- `data-tip="Preview “${escapeAttr(name)}”">${escapeHtml(name)}</button>` +
7727
+ `<button type="button" class="kb-fname" data-kb-open="${escapeAttr(s.sourceId)}" data-command-id="shell.kb-reference#${escapeAttr(s.sourceId)}" data-command-instance-label="${escapeAttr(name)}" ` +
7728
+ `data-tip="Preview “${escapeAttr(name)}” · Ctrl or Shift to select, Ctrl+A for all">${escapeHtml(name)}${sel ? '<span class="kb-sr"> (selected)</span>' : ''}</button>` +
7692
7729
  `<div class="kb-fmeta">${escapeHtml(meta)}<span class="kb-chip ${chip[0]}">${chip[1]}</span>${kbTextChips(s)}${imported}${kbCompanyChip(s, st)}` +
7693
7730
  `${kbIsDesignSet(s, st) ? '<span class="kb-chip run kb-chip-ds">design set</span>' : ''}</div>` +
7694
7731
  kbDesignSetUse(s, st) +
@@ -7701,6 +7738,599 @@
7701
7738
  `</div>`;
7702
7739
  }
7703
7740
 
7741
+
7742
+ // ── #2491 R6.9: categories, multi-select, Move to…, drag and drop ─────────────────────────────────────
7743
+ // The pure half is web/kb-categories.js (kbc*); this is the DOM half. Categories are the person's: every change here is
7744
+ // the person's own click, which the server checks (an AI can only suggest one on a card). Each change carries the
7745
+ // categories' revision this screen drew and the project's incarnation, so a change made meanwhile elsewhere is never
7746
+ // overwritten — the server says so in words and this screen reloads.
7747
+ const KB_CAT_KEY = 'the categories', KB_PROJECT_KEY = 'the project';
7748
+ const KB_REFS_MIME = 'application/x-floless-kb-refs';
7749
+ let kbSel = { selected: new Set(), anchor: null };
7750
+ let kbSelProject = null;
7751
+ let kbCatCollapsed = new Set(); // categories the person folded (new ones start open), per project
7752
+ let kbCatCollapsedProject = null;
7753
+ let kbCatEdit = null; // { mode: 'new' | 'rename', id?, parentId?, then?: { sourceIds } } — the inline name box
7754
+ let kbCatFocus = null; // { cat: id } | { row: sourceId } — focus to restore after the next repaint
7755
+ let kbCatBusy = false;
7756
+
7757
+ function kbCats(st) {
7758
+ const c = st && st.categories;
7759
+ return c && Array.isArray(c.categories) ? c : { v: 1, revision: 0, categories: [], placements: {}, state: 'absent' };
7760
+ }
7761
+ const kbCatUsable = (st) => { const c = kbCats(st); return c.state !== 'damaged' && c.state !== 'newer'; };
7762
+ function kbCatCollapsedFor(proj) {
7763
+ if (!proj) return new Set();
7764
+ if (kbCatCollapsedProject !== proj.id) {
7765
+ kbCatCollapsedProject = proj.id;
7766
+ try { kbCatCollapsed = new Set(JSON.parse(localStorage.getItem(`floless:kb-cat-folded:${proj.id}`) || '[]')); }
7767
+ catch { kbCatCollapsed = new Set(); }
7768
+ }
7769
+ return kbCatCollapsed;
7770
+ }
7771
+ function kbCatSaveCollapsed() {
7772
+ if (!current) return;
7773
+ try { localStorage.setItem(`floless:kb-cat-folded:${current.id}`, JSON.stringify([...kbCatCollapsed])); } catch { /* private mode */ }
7774
+ }
7775
+ function kbSelFor(proj, st) {
7776
+ if (!proj || kbSelProject !== proj.id) { kbSelProject = proj ? proj.id : null; kbSel = { selected: new Set(), anchor: null }; }
7777
+ if (st) kbSel = kbcPrune(kbSel, st.sources.map((s) => s.sourceId));
7778
+ return kbSel;
7779
+ }
7780
+ function kbAnnounce(text) {
7781
+ const live = $wsKnowledge.querySelector('#kb-drop-live');
7782
+ if (!live) return;
7783
+ live.textContent = '';
7784
+ setTimeout(() => { live.textContent = text; }, 30);
7785
+ }
7786
+ /** The refs column keeps the inline name box while someone types in it: a poll must not repaint under it. */
7787
+ function kbCatEditActive() {
7788
+ // Only while an edit is open: once it is saved or cancelled the box is stale, and the repaint must remove it even
7789
+ // though it still holds focus.
7790
+ const box = $wsKnowledge.querySelector('.kb-cat-edit');
7791
+ return !!kbCatEdit && !!box && (box.contains(document.activeElement) || kbCatBusy);
7792
+ }
7793
+
7794
+ function kbCatEditHtml(depth) {
7795
+ const e = kbCatEdit;
7796
+ const verb = e.mode === 'rename' ? 'Rename' : e.then ? 'Create and move' : 'Create';
7797
+ const value = e.mode === 'rename' ? escapeAttr(e.name || '') : '';
7798
+ return `<div class="kb-cat-edit" style="--kb-depth:${depth}">` +
7799
+ `<input type="text" class="kb-cat-input" maxlength="80" value="${value}" aria-label="${e.mode === 'rename' ? 'New name for the category' : 'Name of the new category'}" placeholder="Category name" data-command-id="shell.kb-category-name">` +
7800
+ `<button type="button" class="primary kb-cat-save" data-kb-cat-save data-command-id="shell.kb-category-save">${verb}</button>` +
7801
+ '<button type="button" class="kb-cat-cancel" data-kb-cat-cancel data-command-id="shell.kb-category-cancel">Cancel</button></div>';
7802
+ }
7803
+
7804
+ function kbCatRowHtml(item, file) {
7805
+ const isU = item.kind === 'uncategorized';
7806
+ const id = isU ? 'uncategorized' : item.id;
7807
+ const chev = '<svg class="kb-cat-chev" viewBox="0 0 16 16" aria-hidden="true"><path d="m6 4 4 4-4 4"/></svg>';
7808
+ const editing = kbCatEdit && kbCatEdit.mode === 'rename' && kbCatEdit.id === item.id;
7809
+ if (editing) return kbCatEditHtml(item.depth);
7810
+ const name = escapeHtml(item.name);
7811
+ const tip = item.name.length > 28 ? ` data-tip="${escapeAttr(isU ? item.name : kbcLabel(file, item.id))}"` : '';
7812
+ return `<div class="kb-cat${isU ? ' kb-uncat' : ''}${item.open ? ' open' : ''}" style="--kb-depth:${item.depth}" data-kb-drop-cat="${escapeAttr(id)}">` +
7813
+ `<button type="button" class="kb-cat-toggle" data-kb-cat-toggle="${escapeAttr(id)}" aria-expanded="${item.open ? 'true' : 'false'}"${tip} data-command-id="shell.kb-category-toggle#${escapeAttr(id)}" data-command-instance-label="${escapeAttr(item.name)}">` +
7814
+ `${chev}<span class="kb-cat-name">${name}</span><span class="kb-cat-count" aria-label="${item.count} reference${item.count === 1 ? '' : 's'}">(${item.count})</span></button>` +
7815
+ (isU ? '' : `<button type="button" class="kb-cat-more" data-kb-cat-menu="${escapeAttr(item.id)}" aria-label="More for ${escapeAttr(item.name)}" aria-haspopup="menu" data-tip="Rename, move or delete" data-command-id="shell.kb-category-menu#${escapeAttr(item.id)}" data-command-instance-label="${escapeAttr(item.name)}">⋯</button>`) +
7816
+ '</div>' +
7817
+ (item.open && item.empty ? `<div class="kb-cat-empty" style="--kb-depth:${item.depth + 1}">${isU ? 'Nothing here.' : 'Empty. Drag references here.'}</div>` : '');
7818
+ }
7819
+
7820
+ /** The References list as a tree (once the first category exists), with the inline name box where it was asked for. */
7821
+ function kbTreeHtml(st, rows) {
7822
+ const file = kbCats(st);
7823
+ const folded = kbCatCollapsedFor(current);
7824
+ const open = new Set(['uncategorized', ...file.categories.map((c) => c.id)].filter((id) => !folded.has(id)));
7825
+ const items = kbcTreeItems(file, rows, open);
7826
+ let html = '';
7827
+ for (const item of items) {
7828
+ if (item.kind === 'row') { html += kbSourceRow(item.row, st, item.depth); continue; }
7829
+ html += kbCatRowHtml(item, file);
7830
+ if (kbCatEdit && kbCatEdit.mode === 'new' && kbCatEdit.parentId && kbCatEdit.parentId === item.id && item.open) html += kbCatEditHtml(item.depth + 1);
7831
+ }
7832
+ if (kbCatEdit && kbCatEdit.mode === 'new' && !kbCatEdit.parentId) html = kbCatEditHtml(0) + html;
7833
+ return `<div class="kb-tree" role="group" aria-label="References by category">${html}</div>`;
7834
+ }
7835
+
7836
+ /** The bar under the list while references are selected. */
7837
+ function kbSelBarHtml(st) {
7838
+ const n = kbSelFor(current, st).selected.size;
7839
+ if (!n) return '';
7840
+ return '<div class="kb-selbar" role="region" aria-label="Selected references">' +
7841
+ `<span class="kb-selbar-n">${n} selected</span>` +
7842
+ '<button type="button" class="kb-selbar-move" data-kb-move-sel aria-haspopup="menu" data-command-id="shell.kb-move-to#selection" data-command-instance-label="the selected references">Move to…</button>' +
7843
+ '<button type="button" class="kb-selbar-clear" data-kb-sel-clear data-command-id="shell.kb-select-clear">Clear</button></div>';
7844
+ }
7845
+
7846
+ /** The categories file could not be read, or a newer FloLess wrote it: say so, and offer to start again. */
7847
+ function kbCatUnavailableHtml(st) {
7848
+ const c = kbCats(st);
7849
+ if (kbCatUsable(st)) return '';
7850
+ const why = c.state === 'newer'
7851
+ ? 'Your categories were saved by a newer FloLess, so this one shows every reference without them.'
7852
+ : 'Your categories could not be read, so every reference is shown without them.';
7853
+ return `<div class="kb-cat-warn" role="status"><span>${why} You can update FloLess, or start again with no categories (the saved ones are kept aside).</span>` +
7854
+ '<button type="button" data-kb-cat-reset data-command-id="shell.kb-category-reset">Start again</button></div>';
7855
+ }
7856
+
7857
+ function kbCatExpected(st) {
7858
+ return { [KB_CAT_KEY]: String(kbCats(st).revision || 0), [KB_PROJECT_KEY]: current && current.uuid ? current.uuid : '' };
7859
+ }
7860
+ /** One category change against what this screen drew. The server's own sentence is shown when it refuses. */
7861
+ async function kbCatPost(tail, body, done) {
7862
+ const proj = current;
7863
+ if (!proj || kbCatBusy) return null;
7864
+ kbCatBusy = true;
7865
+ try {
7866
+ const res = await api(kbUrl(proj.id, tail), { method: 'POST', body: JSON.stringify({ expected: kbCatExpected(knowledgeState), ...body }) });
7867
+ if (current !== proj) return null;
7868
+ if (knowledgeState && res && res.categories) knowledgeState.categories = res.categories;
7869
+ if (done) done(res);
7870
+ kbInvalidateRefs();
7871
+ if (knowledgeState) paintKnowledge(knowledgeState);
7872
+ return res;
7873
+ } catch (err) {
7874
+ const said = err && err.body && typeof err.body.error === 'string' ? err.body.error : '';
7875
+ showToast(said || 'FloLess could not change your categories just now. Try again.', 'warn');
7876
+ // Changed elsewhere since the name box opened: close it, so the person sees the newer names before naming again.
7877
+ if (body.expected && err && err.body && err.body.code === 'knowledge-categories-changed') kbCatEdit = null;
7878
+ return null;
7879
+ } finally {
7880
+ kbCatBusy = false;
7881
+ if (current === proj) renderKnowledge();
7882
+ }
7883
+ }
7884
+ function kbCatOps(ops, announce, focus, expected) {
7885
+ return kbCatPost('/categories', expected ? { ops, expected } : { ops }, (res) => {
7886
+ if (announce) kbAnnounce(typeof announce === 'function' ? announce(res) : announce);
7887
+ if (focus) kbCatFocus = typeof focus === 'function' ? focus(res) : focus;
7888
+ });
7889
+ }
7890
+ function kbPlace(sourceIds, categoryId) {
7891
+ const st = knowledgeState;
7892
+ const where = categoryId ? kbcLabel(kbCats(st), categoryId) : 'Uncategorized';
7893
+ const n = sourceIds.length;
7894
+ return kbCatPost('/sources/place', { sourceIds, categoryId: categoryId || null }, (res) => {
7895
+ const moved = (res.placed || []).length;
7896
+ const missing = (res.missing || []).length;
7897
+ kbAnnounce(`Moved ${moved} reference${moved === 1 ? '' : 's'} to ${where}.${missing ? ` ${missing} ${missing === 1 ? 'was' : 'were'} no longer here.` : ''}`);
7898
+ if (categoryId) {
7899
+ // Keep the moved items in view: open the category and its ancestors.
7900
+ const file = res.categories || kbCats(st);
7901
+ for (const id of [...kbcAncestors(file, categoryId), categoryId]) kbCatCollapsed.delete(id);
7902
+ kbCatSaveCollapsed();
7903
+ }
7904
+ kbSel = { selected: new Set(), anchor: null };
7905
+ if (n) kbCatFocus = { row: sourceIds[0] };
7906
+ });
7907
+ }
7908
+
7909
+ function kbCatPop(anchor, html, label, role) {
7910
+ kbCloseConfirm();
7911
+ const box = anchor.closest('.kb-refs-body');
7912
+ if (!box) return null;
7913
+ const pop = document.createElement('div');
7914
+ pop.className = `hist-confirm${role === 'menu' ? ' kb-ds-menu kb-cat-menu' : ''}`;
7915
+ pop.setAttribute('role', role || 'dialog');
7916
+ pop.setAttribute('aria-label', label);
7917
+ pop.innerHTML = html;
7918
+ box.appendChild(pop);
7919
+ const cr = box.getBoundingClientRect();
7920
+ const br = anchor.getBoundingClientRect();
7921
+ // Below the control when it fits in view, else above it (the selection bar sits at the bottom edge).
7922
+ const below = br.bottom - cr.top + box.scrollTop + 6;
7923
+ const fits = br.bottom + 6 + pop.offsetHeight <= cr.bottom;
7924
+ pop.style.top = `${fits ? below : Math.max(box.scrollTop + 4, br.top - cr.top + box.scrollTop - pop.offsetHeight - 6)}px`;
7925
+ pop.style.left = `${Math.max(8, Math.min(br.left - cr.left, box.clientWidth - pop.offsetWidth - 8))}px`;
7926
+ document.addEventListener('mousedown', kbOnDocDown, true);
7927
+ pop.kbAnchor = anchor;
7928
+ return pop;
7929
+ }
7930
+
7931
+ /** Move to…: for references (the selection, or one row) or for a category (where it sits). */
7932
+ function kbShowMoveMenu(anchor, what) {
7933
+ const st = knowledgeState;
7934
+ const file = kbCats(st);
7935
+ const choices = kbcMenuChoices(file, what.categoryId || null);
7936
+ const currentAt = what.categoryId
7937
+ ? (file.categories.find((c) => c.id === what.categoryId) || {}).parentId || null
7938
+ : (what.sourceIds.length === 1 ? kbcPlacement(file, what.sourceIds[0]) : undefined);
7939
+ const n = what.sourceIds ? what.sourceIds.length : 0;
7940
+ const title = what.categoryId ? `Move “${escapeHtml(kbcLabel(file, what.categoryId))}” to` : `Move ${n === 1 ? 'this reference' : `${n} references`} to`;
7941
+ const items = choices.filter((c) => c.allowed).map((c) =>
7942
+ `<button type="button" role="menuitemradio" aria-checked="${c.id === currentAt ? 'true' : 'false'}" class="kb-ds-mi kb-move-mi" style="--kb-depth:${c.id ? c.depth + 1 : 0}"` +
7943
+ ` data-kb-move-go="${escapeAttr(c.id || '')}" data-command-id="shell.kb-move-to-go#${escapeAttr(c.id || 'uncategorized')}" data-command-instance-label="${escapeAttr(c.name)}">${escapeHtml(c.name)}</button>`).join('');
7944
+ const pop = kbCatPop(anchor, `<div class="kb-move-title">${title}</div>${items}` +
7945
+ `<button type="button" role="menuitem" class="kb-ds-mi kb-move-new" data-kb-move-new data-command-id="shell.kb-category-new">New category…</button>`,
7946
+ what.categoryId ? 'Move category' : 'Move references', 'menu');
7947
+ if (!pop) return;
7948
+ pop.kbWhat = what;
7949
+ const first = pop.querySelector('[aria-checked="true"]') || pop.querySelector('.kb-ds-mi');
7950
+ if (first) first.focus();
7951
+ }
7952
+
7953
+ function kbShowCatMenu(btn) {
7954
+ const id = btn.dataset.kbCatMenu;
7955
+ const file = kbCats(knowledgeState);
7956
+ const cat = file.categories.find((c) => c.id === id);
7957
+ if (!cat) return;
7958
+ const sibs = kbcChildren(file, cat.parentId || null);
7959
+ const at = sibs.findIndex((c) => c.id === id);
7960
+ const pop = kbCatPop(btn,
7961
+ `<button type="button" role="menuitem" class="kb-ds-mi" data-kb-cat-rename="${escapeAttr(id)}" data-command-id="shell.kb-category-rename#${escapeAttr(id)}" data-command-instance-label="${escapeAttr(cat.name)}">Rename…</button>` +
7962
+ `<button type="button" role="menuitem" class="kb-ds-mi" data-kb-cat-sub="${escapeAttr(id)}" data-command-id="shell.kb-category-new-sub#${escapeAttr(id)}" data-command-instance-label="${escapeAttr(cat.name)}">New subcategory…</button>` +
7963
+ `<button type="button" role="menuitem" class="kb-ds-mi" data-kb-cat-move="${escapeAttr(id)}" data-command-id="shell.kb-move-to#${escapeAttr(id)}" data-command-instance-label="${escapeAttr(cat.name)}">Move to…</button>` +
7964
+ (at > 0 ? `<button type="button" role="menuitem" class="kb-ds-mi" data-kb-cat-up="${escapeAttr(id)}" data-command-id="shell.kb-category-up#${escapeAttr(id)}" data-command-instance-label="${escapeAttr(cat.name)}">Move up</button>` : '') +
7965
+ (at < sibs.length - 1 ? `<button type="button" role="menuitem" class="kb-ds-mi" data-kb-cat-down="${escapeAttr(id)}" data-command-id="shell.kb-category-down#${escapeAttr(id)}" data-command-instance-label="${escapeAttr(cat.name)}">Move down</button>` : '') +
7966
+ `<button type="button" role="menuitem" class="kb-ds-mi danger" data-kb-cat-delete="${escapeAttr(id)}" data-command-id="shell.kb-category-delete#${escapeAttr(id)}" data-command-instance-label="${escapeAttr(cat.name)}">Delete…</button>`,
7967
+ `More for ${cat.name}`, 'menu');
7968
+ const first = pop && pop.querySelector('.kb-ds-mi');
7969
+ if (first) first.focus();
7970
+ }
7971
+
7972
+ function kbShowCatDelete(anchor, id) {
7973
+ const st = knowledgeState;
7974
+ const file = kbCats(st);
7975
+ const cat = file.categories.find((c) => c.id === id);
7976
+ if (!cat) return;
7977
+ const body = kbCatDeleteSentence(file, st.sources, id);
7978
+ const pop = kbCatPop(anchor,
7979
+ `<div class="hc-title">Delete “${escapeHtml(cat.name)}”?</div><div class="hc-body">${body}</div>` +
7980
+ '<div class="hc-act"><button type="button" class="hc-cancel" data-command-id="shell.kb-category-cancel">Cancel</button>' +
7981
+ `<button type="button" class="hc-go danger" data-kb-cat-delete-go="${escapeAttr(id)}" data-command-id="shell.kb-category-delete#${escapeAttr(id)}" data-command-instance-label="${escapeAttr(cat.name)}">Delete category</button></div>`,
7982
+ `Delete ${cat.name}`, 'dialog');
7983
+ const cancel = pop && pop.querySelector('.hc-cancel');
7984
+ if (cancel) cancel.focus();
7985
+ }
7986
+
7987
+ /** What deleting a category does, in words: its own references and its subcategories (with theirs) move up a level. */
7988
+ function kbCatDeleteSentence(file, rows, id) {
7989
+ const cat = file.categories.find((c) => c.id === id);
7990
+ const n = (rows || []).filter((r) => kbcPlacement(file, r.sourceId) === id).length;
7991
+ const subs = kbcChildren(file, id).length;
7992
+ const refs = `${n} reference${n === 1 ? '' : 's'}`;
7993
+ const kids = `${subs} subcategor${subs === 1 ? 'y' : 'ies'}`;
7994
+ if (!n && !subs) return 'It is empty. No reference is deleted.';
7995
+ if (cat && cat.parentId) {
7996
+ const to = `“${escapeHtml(kbcLabel(file, cat.parentId))}”`;
7997
+ return `Its ${[n ? refs : '', subs ? kids : ''].filter(Boolean).join(' and ')} move up to ${to}. No reference is deleted.`;
7998
+ }
7999
+ if (n && subs) return `Its ${refs} move to Uncategorized and its ${kids} to the top level. No reference is deleted.`;
8000
+ return n ? `Its ${refs} move to Uncategorized. No reference is deleted.` : `Its ${kids} move to the top level. No reference is deleted.`;
8001
+ }
8002
+
8003
+ function kbCatStartEdit(edit) {
8004
+ kbCloseConfirm();
8005
+ // The box saves against the categories as they were when it opened: a change made meanwhile elsewhere is refused, not overwritten.
8006
+ kbCatEdit = { ...edit, expected: kbCatExpected(knowledgeState) };
8007
+ if (edit.parentId) { kbCatCollapsed.delete(edit.parentId); kbCatSaveCollapsed(); }
8008
+ kbInvalidateRefs();
8009
+ if (knowledgeState) paintKnowledge(knowledgeState);
8010
+ const input = $wsKnowledge.querySelector('.kb-cat-input');
8011
+ if (input) { input.focus(); input.select(); }
8012
+ }
8013
+ function kbCatEndEdit(focus) {
8014
+ kbCatEdit = null;
8015
+ kbCatFocus = focus || null;
8016
+ kbInvalidateRefs();
8017
+ if (knowledgeState) paintKnowledge(knowledgeState);
8018
+ }
8019
+ async function kbCatSaveEdit() {
8020
+ const input = $wsKnowledge.querySelector('.kb-cat-input');
8021
+ const e = kbCatEdit;
8022
+ if (!input || !e) return;
8023
+ const name = input.value.replace(/\s+/g, ' ').trim();
8024
+ if (!name) { showToast('Give the category a name.', 'warn'); input.focus(); return; }
8025
+ if (e.mode === 'rename') {
8026
+ const res = await kbCatOps([{ op: 'rename', id: e.id, name }], `Renamed the category to ${name}.`, { cat: e.id }, e.expected);
8027
+ if (res) kbCatEdit = null;
8028
+ } else {
8029
+ const res = await kbCatOps([{ op: 'create', tempId: 'new', name, parentId: e.parentId || null }], `Created the category ${name}.`, (r) => ({ cat: r.created && r.created.new }), e.expected);
8030
+ if (res) {
8031
+ kbCatEdit = null;
8032
+ const id = res.created && res.created.new;
8033
+ if (e.then && e.then.sourceIds && id) await kbPlace(e.then.sourceIds, id);
8034
+ if (e.then && e.then.categoryId && id) await kbCatOps([{ op: 'move', id: e.then.categoryId, parentId: id }], `Moved the category into ${name}.`, { cat: e.then.categoryId });
8035
+ }
8036
+ }
8037
+ kbInvalidateRefs();
8038
+ if (knowledgeState) paintKnowledge(knowledgeState);
8039
+ }
8040
+
8041
+ /** Restore focus after a repaint, to the item that was acted on (or its neighbour when it is gone). */
8042
+ function kbCatRestoreFocus(refsHost) {
8043
+ const f = kbCatFocus;
8044
+ if (!f) return;
8045
+ kbCatFocus = null;
8046
+ const el = f.cat ? refsHost.querySelector(`[data-kb-cat-toggle="${CSS.escape(f.cat)}"]`)
8047
+ : f.row ? refsHost.querySelector(`[data-kb-open="${CSS.escape(f.row)}"]`)
8048
+ : f.selbar ? refsHost.querySelector('[data-kb-move-sel]') : null;
8049
+ const fallback = refsHost.querySelector('.kb-cat-toggle, .kb-fname');
8050
+ (el || fallback)?.focus({ preventScroll: false });
8051
+ }
8052
+
8053
+ /** The visible references in order — Shift+click ranges and the arrow keys walk this. */
8054
+ const kbVisibleRows = () => [...$wsKnowledge.querySelectorAll('.kb-refs-body .kb-src[data-source-id]')].map((el) => el.dataset.sourceId);
8055
+ const kbFocusables = () => [...$wsKnowledge.querySelectorAll('.kb-refs-body .kb-cat-toggle, .kb-refs-body .kb-fname')];
8056
+
8057
+ function kbSelectClick(sourceId, e) {
8058
+ kbSel = kbcSelect(kbSelFor(current, knowledgeState), sourceId, { toggle: e.ctrlKey || e.metaKey, shift: e.shiftKey }, kbVisibleRows());
8059
+ kbCatFocus = { row: sourceId };
8060
+ kbInvalidateRefs();
8061
+ if (knowledgeState) paintKnowledge(knowledgeState);
8062
+ const n = kbSel.selected.size;
8063
+ kbAnnounce(n ? `${n} selected.` : 'Nothing selected.');
8064
+ }
8065
+
8066
+ /** The click handler's category half; true when it handled the click. */
8067
+ function kbCatClick(e) {
8068
+ const t = e.target;
8069
+ const toggle = t.closest('[data-kb-cat-toggle]');
8070
+ if (toggle) {
8071
+ const id = toggle.dataset.kbCatToggle;
8072
+ const folded = kbCatCollapsedFor(current);
8073
+ if (folded.has(id)) folded.delete(id); else folded.add(id);
8074
+ kbCatSaveCollapsed();
8075
+ kbCatFocus = { cat: id };
8076
+ kbInvalidateRefs();
8077
+ if (knowledgeState) paintKnowledge(knowledgeState);
8078
+ return true;
8079
+ }
8080
+ const menu = t.closest('[data-kb-cat-menu]');
8081
+ if (menu) { kbShowCatMenu(menu); return true; }
8082
+ const rename = t.closest('[data-kb-cat-rename]');
8083
+ if (rename) {
8084
+ const cat = kbCats(knowledgeState).categories.find((c) => c.id === rename.dataset.kbCatRename);
8085
+ if (cat) kbCatStartEdit({ mode: 'rename', id: cat.id, name: cat.name });
8086
+ return true;
8087
+ }
8088
+ const sub = t.closest('[data-kb-cat-sub]');
8089
+ if (sub) { kbCatStartEdit({ mode: 'new', parentId: sub.dataset.kbCatSub }); return true; }
8090
+ const up = t.closest('[data-kb-cat-up], [data-kb-cat-down]');
8091
+ if (up) {
8092
+ const id = up.dataset.kbCatUp || up.dataset.kbCatDown;
8093
+ kbCloseConfirm();
8094
+ const ops = kbcReorderOps(kbCats(knowledgeState), id, up.hasAttribute('data-kb-cat-up') ? -1 : 1);
8095
+ if (ops) kbCatOps(ops, `Moved ${kbcLabel(kbCats(knowledgeState), id)} ${up.hasAttribute('data-kb-cat-up') ? 'up' : 'down'}.`, { cat: id });
8096
+ return true;
8097
+ }
8098
+ const catMove = t.closest('[data-kb-cat-move]');
8099
+ if (catMove) {
8100
+ const id = catMove.dataset.kbCatMove;
8101
+ const anchor = $wsKnowledge.querySelector(`[data-kb-cat-menu="${CSS.escape(id)}"]`) || catMove;
8102
+ kbShowMoveMenu(anchor, { categoryId: id });
8103
+ return true;
8104
+ }
8105
+ const del = t.closest('[data-kb-cat-delete]');
8106
+ if (del) {
8107
+ const id = del.dataset.kbCatDelete;
8108
+ kbShowCatDelete($wsKnowledge.querySelector(`[data-kb-cat-menu="${CSS.escape(id)}"]`) || del, id);
8109
+ return true;
8110
+ }
8111
+ const delGo = t.closest('[data-kb-cat-delete-go]');
8112
+ if (delGo) {
8113
+ const id = delGo.dataset.kbCatDeleteGo;
8114
+ const file = kbCats(knowledgeState);
8115
+ const cat = file.categories.find((c) => c.id === id);
8116
+ const parent = cat && cat.parentId ? kbcLabel(file, cat.parentId) : 'Uncategorized';
8117
+ const n = knowledgeState.sources.filter((r) => kbcPlacement(file, r.sourceId) === id).length;
8118
+ kbCloseConfirm();
8119
+ kbCatOps([{ op: 'delete', id }], `Deleted the category ${cat ? cat.name : ''}.${n ? ` ${n} reference${n === 1 ? '' : 's'} moved up to ${parent}.` : ''}`,
8120
+ cat && cat.parentId ? { cat: cat.parentId } : null);
8121
+ return true;
8122
+ }
8123
+ const newCat = t.closest('[data-kb-cat-new]');
8124
+ if (newCat) { kbCatStartEdit({ mode: 'new', parentId: null }); return true; }
8125
+ if (t.closest('[data-kb-cat-save]')) { kbCatSaveEdit(); return true; }
8126
+ if (t.closest('[data-kb-cat-cancel]')) {
8127
+ const e2 = kbCatEdit;
8128
+ kbCatEndEdit(e2 && e2.mode === 'rename' ? { cat: e2.id } : null);
8129
+ return true;
8130
+ }
8131
+ if (t.closest('[data-kb-cat-reset]')) { kbCatPost('/categories', { reset: true }, () => kbAnnounce('Started again with no categories. The old ones are kept aside.')); return true; }
8132
+ const moveSel = t.closest('[data-kb-move-sel]');
8133
+ if (moveSel) { kbShowMoveMenu(moveSel, { sourceIds: [...kbSelFor(current, knowledgeState).selected] }); return true; }
8134
+ const rowMove = t.closest('[data-kb-row-move]');
8135
+ if (rowMove) {
8136
+ const id = rowMove.dataset.kbRowMove;
8137
+ const anchor = $wsKnowledge.querySelector(`[data-kb-open="${CSS.escape(id)}"]`) || rowMove;
8138
+ const sel = kbSelFor(current, knowledgeState).selected;
8139
+ kbShowMoveMenu(anchor, { sourceIds: sel.has(id) ? [...sel] : [id] });
8140
+ return true;
8141
+ }
8142
+ if (t.closest('[data-kb-sel-clear]')) {
8143
+ kbSel = { selected: new Set(), anchor: null };
8144
+ kbAnnounce('Nothing selected.');
8145
+ kbInvalidateRefs();
8146
+ if (knowledgeState) paintKnowledge(knowledgeState);
8147
+ const first = $wsKnowledge.querySelector('.kb-refs-body .kb-fname');
8148
+ if (first) first.focus();
8149
+ return true;
8150
+ }
8151
+ const go = t.closest('[data-kb-move-go]');
8152
+ if (go) {
8153
+ const pop = go.closest('.hist-confirm');
8154
+ const what = pop && pop.kbWhat;
8155
+ const to = go.dataset.kbMoveGo || null;
8156
+ kbCloseConfirm();
8157
+ if (what && what.categoryId) {
8158
+ const file = kbCats(knowledgeState);
8159
+ kbCatOps([{ op: 'move', id: what.categoryId, parentId: to }], `Moved ${kbcLabel(file, what.categoryId)} to ${to ? kbcLabel(file, to) : 'the top level'}.`, { cat: what.categoryId });
8160
+ if (to) { kbCatCollapsed.delete(to); kbCatSaveCollapsed(); }
8161
+ } else if (what && what.sourceIds) kbPlace(what.sourceIds, to);
8162
+ return true;
8163
+ }
8164
+ const moveNew = t.closest('[data-kb-move-new]');
8165
+ if (moveNew) {
8166
+ const pop = moveNew.closest('.hist-confirm');
8167
+ const what = pop && pop.kbWhat;
8168
+ kbCatStartEdit({ mode: 'new', parentId: null, then: what || null });
8169
+ return true;
8170
+ }
8171
+ // Selection: Ctrl/Cmd or Shift on a row (its name included) selects instead of opening.
8172
+ const row = t.closest('.kb-src[data-source-id]');
8173
+ if (row && (e.ctrlKey || e.metaKey || e.shiftKey) && !t.closest('[data-kb-toggle], [data-kb-remove], .kb-ds-mi, [data-company-promote]')) {
8174
+ e.preventDefault();
8175
+ kbSelectClick(row.dataset.sourceId, e);
8176
+ return true;
8177
+ }
8178
+ return false;
8179
+ }
8180
+
8181
+ function kbShowRowMenu(fname) {
8182
+ const row = fname.closest('.kb-src[data-source-id]');
8183
+ if (!row) return;
8184
+ const id = row.dataset.sourceId;
8185
+ const name = fname.textContent || 'this reference';
8186
+ const tog = row.querySelector('[data-kb-toggle]');
8187
+ const on = tog && tog.getAttribute('aria-checked') === 'true';
8188
+ const src = knowledgeState && knowledgeState.sources.find((x) => x.sourceId === id);
8189
+ const promote = src && src.kind === 'file';
8190
+ const pop = kbCatPop(fname,
8191
+ (kbCats(knowledgeState).categories.length ? `<button type="button" role="menuitem" class="kb-ds-mi" data-kb-row-move="${escapeAttr(id)}" data-command-id="shell.kb-move-to#${escapeAttr(id)}" data-command-instance-label="${escapeAttr(name)}">Move to…</button>` : '') +
8192
+ `<button type="button" role="menuitem" class="kb-ds-mi" data-kb-row-act="toggle" data-kb-row-id="${escapeAttr(id)}" data-command-id="shell.kb-category-row-toggle#${escapeAttr(id)}" data-command-instance-label="${escapeAttr(name)}">${on ? 'Exclude from the knowledge base' : 'Include in the knowledge base'}</button>` +
8193
+ (promote ? `<button type="button" role="menuitem" class="kb-ds-mi" data-kb-row-act="promote" data-kb-row-id="${escapeAttr(id)}" data-command-id="shell.company-promote-source#${escapeAttr(id)}" data-command-instance-label="${escapeAttr(name)}">Promote to company…</button>` : '') +
8194
+ `<button type="button" role="menuitem" class="kb-ds-mi danger" data-kb-row-act="remove" data-kb-row-id="${escapeAttr(id)}" data-command-id="shell.kb-category-row-remove#${escapeAttr(id)}" data-command-instance-label="${escapeAttr(name)}">Remove…</button>`,
8195
+ `More for ${name}`, 'menu');
8196
+ const first = pop && pop.querySelector('.kb-ds-mi');
8197
+ if (first) first.focus();
8198
+ }
8199
+
8200
+ /** The keyboard half: arrows walk the list, Space selects, Ctrl+A selects every visible row, Alt+arrows reorder a category, Delete asks, the menu key opens a menu. */
8201
+ function kbCatKeydown(e) {
8202
+ const t = e.target;
8203
+ if (t.classList && t.classList.contains('kb-cat-input')) {
8204
+ if (e.key === 'Enter') { e.preventDefault(); kbCatSaveEdit(); return true; }
8205
+ if (e.key === 'Escape') { e.preventDefault(); const e2 = kbCatEdit; kbCatEndEdit(e2 && e2.mode === 'rename' ? { cat: e2.id } : null); return true; }
8206
+ return false;
8207
+ }
8208
+ const pop = t.closest && t.closest('.kb-cat-menu, .hist-confirm');
8209
+ if (pop && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
8210
+ const items = [...pop.querySelectorAll('.kb-ds-mi')];
8211
+ const at = items.indexOf(t);
8212
+ if (at >= 0) { e.preventDefault(); items[(at + (e.key === 'ArrowDown' ? 1 : items.length - 1)) % items.length].focus(); return true; }
8213
+ }
8214
+ if (pop && e.key === 'Escape') {
8215
+ // Back to the control that opened it (the menu button, the row, the category, or the selection bar).
8216
+ const el = pop.kbAnchor;
8217
+ kbCloseConfirm();
8218
+ if (el && el.isConnected) el.focus();
8219
+ e.preventDefault();
8220
+ return true;
8221
+ }
8222
+ // Ctrl/Cmd+A anywhere in References (not in a text box) selects every visible reference, like a file list.
8223
+ if ((e.key === 'a' || e.key === 'A') && (e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && t.closest
8224
+ && t.closest('.kb-refs-body') && !t.closest('input, textarea, [contenteditable="true"]')) {
8225
+ const rows = kbVisibleRows();
8226
+ // Never the browser's own select-all here: with every category folded it would select the whole page's text.
8227
+ e.preventDefault();
8228
+ if (!rows.length) { kbAnnounce('No references are shown to select. Open a category to see its references.'); return true; }
8229
+ kbSel = kbcSelectAll(kbSelFor(current, knowledgeState), rows);
8230
+ // The repaint replaces the focused control; bring focus back to the same row or category so Escape and the arrows still work.
8231
+ const cat = t.closest('[data-kb-cat-toggle]'), row = t.closest('.kb-src[data-source-id]');
8232
+ kbCatFocus = cat ? { cat: cat.dataset.kbCatToggle } : row ? { row: row.dataset.sourceId } : null;
8233
+ kbInvalidateRefs();
8234
+ if (knowledgeState) paintKnowledge(knowledgeState);
8235
+ kbAnnounce(`All ${rows.length} selected.`);
8236
+ return true;
8237
+ }
8238
+ const catBtn = t.closest && t.closest('.kb-cat-toggle');
8239
+ const fname = t.closest && t.closest('.kb-refs-body .kb-fname');
8240
+ // Escape clears the selection from anywhere in the list, a selected name included (where a Ctrl+click leaves focus).
8241
+ if (e.key === 'Escape' && kbSel.selected.size && t.closest && t.closest('.kb-refs-body')) { $wsKnowledge.querySelector('[data-kb-sel-clear]')?.click(); return true; }
8242
+ if (!catBtn && !fname) return false;
8243
+ const menuKey = e.key === 'ContextMenu' || (e.key === 'F10' && e.shiftKey);
8244
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
8245
+ if (catBtn && e.altKey) {
8246
+ const id = catBtn.dataset.kbCatToggle;
8247
+ if (id === 'uncategorized') return true;
8248
+ e.preventDefault();
8249
+ const dir = e.key === 'ArrowUp' ? -1 : 1;
8250
+ const ops = kbcReorderOps(kbCats(knowledgeState), id, dir);
8251
+ if (ops) kbCatOps(ops, `Moved ${kbcLabel(kbCats(knowledgeState), id)} ${dir < 0 ? 'up' : 'down'}.`, { cat: id });
8252
+ return true;
8253
+ }
8254
+ const all = kbFocusables();
8255
+ const at = all.indexOf(catBtn || fname);
8256
+ const next = all[at + (e.key === 'ArrowDown' ? 1 : -1)];
8257
+ if (next) { e.preventDefault(); next.focus(); if (e.shiftKey && fname && next.classList.contains('kb-fname')) kbSelectClick(next.closest('.kb-src').dataset.sourceId, { shiftKey: true }); }
8258
+ return true;
8259
+ }
8260
+ if (catBtn && (e.key === 'ArrowRight' || e.key === 'ArrowLeft')) {
8261
+ const id = catBtn.dataset.kbCatToggle;
8262
+ const open = catBtn.getAttribute('aria-expanded') === 'true';
8263
+ if ((e.key === 'ArrowRight') !== open) { e.preventDefault(); catBtn.click(); }
8264
+ return true;
8265
+ }
8266
+ if (fname && e.key === ' ') { e.preventDefault(); kbSelectClick(fname.closest('.kb-src').dataset.sourceId, { ctrlKey: true }); return true; }
8267
+ if (e.key === 'Delete') {
8268
+ e.preventDefault();
8269
+ if (catBtn) { const id = catBtn.dataset.kbCatToggle; if (id !== 'uncategorized') kbShowCatDelete(catBtn, id); }
8270
+ else fname.closest('.kb-src').querySelector('[data-kb-remove]')?.click();
8271
+ return true;
8272
+ }
8273
+ if (menuKey) {
8274
+ e.preventDefault();
8275
+ if (catBtn) { const more = catBtn.parentElement.querySelector('[data-kb-cat-menu]'); if (more) kbShowCatMenu(more); }
8276
+ else kbShowRowMenu(fname);
8277
+ return true;
8278
+ }
8279
+ return false;
8280
+ }
8281
+
8282
+ /** A row menu's choices act through the row's own controls, so they keep every rule those controls have. */
8283
+ function kbRowAct(btn) {
8284
+ const id = btn.dataset.kbRowId;
8285
+ const row = $wsKnowledge.querySelector(`.kb-src[data-source-id="${CSS.escape(id)}"]`);
8286
+ kbCloseConfirm();
8287
+ if (!row) return;
8288
+ const act = btn.dataset.kbRowAct;
8289
+ if (act === 'promote') {
8290
+ const src = knowledgeState && knowledgeState.sources.find((x) => x.sourceId === id);
8291
+ if (src) openCompanyKnowledge({ sourceId: src.sourceId, filename: src.filename || 'untitled', mime: src.mime }, row.querySelector('.kb-fname'));
8292
+ return;
8293
+ }
8294
+ const target = act === 'toggle' ? row.querySelector('[data-kb-toggle]') : row.querySelector('[data-kb-remove]');
8295
+ if (target) target.click();
8296
+ }
8297
+
8298
+ // Drag and drop. A drag carries the selection when the dragged row is in it, else just that row. Files from the desktop
8299
+ // dropped on a category are added straight into it (the server files them only for the person's own drop).
8300
+ let kbDragIds = null;
8301
+ let kbDragHover = null; // { el, timer }
8302
+ function kbDragChip(n, name) {
8303
+ const chip = document.createElement('div');
8304
+ chip.className = 'kb-drag-chip';
8305
+ chip.textContent = n === 1 ? name : `${n} references`;
8306
+ document.body.appendChild(chip);
8307
+ setTimeout(() => chip.remove(), 0);
8308
+ return chip;
8309
+ }
8310
+ function kbDropTargetOf(e) {
8311
+ const el = e.target.closest && e.target.closest('[data-kb-drop-cat]');
8312
+ return el && el.closest('.kb-refs-body') ? el : null;
8313
+ }
8314
+ /** Open a folded category during a drag without repainting the column (the dragged row must survive). */
8315
+ function kbCatExpandInPlace(id) {
8316
+ const head = $wsKnowledge.querySelector(`.kb-cat[data-kb-drop-cat="${CSS.escape(id)}"]`);
8317
+ if (!head || !knowledgeState) return;
8318
+ const file = kbCats(knowledgeState);
8319
+ const rows = knowledgeState.sources.filter((r) => !kbInDesignSet(r, knowledgeState) && kbcPlacement(file, r.sourceId) === id);
8320
+ const depth = Number((head.getAttribute('style') || '').match(/--kb-depth:(d+)/)?.[1] || 0);
8321
+ head.classList.add('open');
8322
+ head.querySelector('.kb-cat-toggle')?.setAttribute('aria-expanded', 'true');
8323
+ head.insertAdjacentHTML('afterend', rows.map((r) => kbSourceRow(r, knowledgeState, depth + 1)).join(''));
8324
+ }
8325
+
8326
+ function kbClearDropHover() {
8327
+ if (!kbDragHover) return;
8328
+ kbDragHover.el.classList.remove('drop-target');
8329
+ kbDragHover.el.removeAttribute('data-drop-label');
8330
+ clearTimeout(kbDragHover.timer);
8331
+ kbDragHover = null;
8332
+ }
8333
+
7704
8334
  /**
7705
8335
  * #2131: a queued organize whose start met work already changing the project. Only what was recorded is said — when
7706
8336
  * the AI last tried and who held the project — never that it starts by itself: nothing here can tell whether that AI
@@ -7802,49 +8432,6 @@
7802
8432
  // way across re-renders (no visual jitter on a poll tick / repaint) without needing a persisted
7803
8433
  // layout. The force pass then relaxes overlaps via simple repulsion + edge-spring + centering.
7804
8434
  function kbHash(s) { let h = 2166136261; for (let i = 0; i < s.length; i++) { h ^= s.charCodeAt(i); h = Math.imul(h, 16777619); } return h >>> 0; }
7805
- function kbLayout(nodes, edges) {
7806
- const W = 600, H = 440, N = nodes.length;
7807
- const iters = N <= 60 ? 300 : N <= 150 ? 150 : 60;
7808
- const R = Math.min(W, H) / 2 - 40;
7809
- const pos = nodes.map((n, i) => { const ang = i * 2.399963 + (kbHash(n.id) % 628) / 100; const rad = 18 + (N > 1 ? (i / (N - 1)) * R : 0);
7810
- return { id: n.id, x: W / 2 + Math.cos(ang) * rad, y: H / 2 + Math.sin(ang) * rad }; });
7811
- const idx = new Map(pos.map((p, i) => [p.id, i]));
7812
- const K = 140;
7813
- for (let it = 0; it < iters; it++) {
7814
- const fx = new Array(N).fill(0), fy = new Array(N).fill(0);
7815
- for (let i = 0; i < N; i++) for (let j = i + 1; j < N; j++) {
7816
- let dx = pos[i].x - pos[j].x, dy = pos[i].y - pos[j].y; const d2 = dx * dx + dy * dy || 0.01, d = Math.sqrt(d2), rep = 9000 / d2;
7817
- fx[i] += dx / d * rep; fy[i] += dy / d * rep; fx[j] -= dx / d * rep; fy[j] -= dy / d * rep; }
7818
- for (const e of edges) { const i = idx.get(e.a), j = idx.get(e.b); if (i == null || j == null) continue;
7819
- let dx = pos[j].x - pos[i].x, dy = pos[j].y - pos[i].y; const d = Math.sqrt(dx * dx + dy * dy) || 0.01, s = (d - K) * 0.02;
7820
- fx[i] += dx / d * s; fy[i] += dy / d * s; fx[j] -= dx / d * s; fy[j] -= dy / d * s; }
7821
- for (let i = 0; i < N; i++) { fx[i] += (W / 2 - pos[i].x) * 0.01; fy[i] += (H / 2 - pos[i].y) * 0.01;
7822
- pos[i].x = Math.max(24, Math.min(W - 24, pos[i].x + Math.max(-20, Math.min(20, fx[i]))));
7823
- pos[i].y = Math.max(24, Math.min(H - 24, pos[i].y + Math.max(-20, Math.min(20, fy[i])))); }
7824
- }
7825
- return { pos, idx, W, H };
7826
- }
7827
-
7828
- // Node fields are ALL escaped (title/slug/type are LLM-derived). Each node carries an aria-label AND
7829
- // a type-bearing data-tip so its taxonomy is available to AT + sighted users, not encoded by colour
7830
- // alone (WCAG 1.4.1). An invisible r=16 hit circle widens the click/focus target behind the r=9 dot.
7831
- function kbGraphSvg(graph) {
7832
- if (!graph || !graph.nodes.length) return graph && graph.truncated ? kbGraphTruncatedEmpty() : kbGraphEmpty(knowledgeState);
7833
- const { pos, idx, W, H } = kbLayout(graph.nodes, graph.edges);
7834
- const lines = graph.edges.map((e) => { const a = pos[idx.get(e.a)], b = pos[idx.get(e.b)];
7835
- return (a && b) ? `<line class="kb-g-edge" x1="${a.x.toFixed(1)}" y1="${a.y.toFixed(1)}" x2="${b.x.toFixed(1)}" y2="${b.y.toFixed(1)}"/>` : ''; }).join('');
7836
- const dots = graph.nodes.map((n, i) => { const p = pos[i];
7837
- return `<g class="kb-g-node kb-g-${escapeAttr(n.type)}" tabindex="0" role="button" aria-label="${escapeAttr(n.title + ', ' + n.type)}" data-kb-node="${escapeAttr(n.slug)}" data-tip="${escapeAttr(n.title + ' · ' + n.type)}" data-pos="${p.x.toFixed(1)},${p.y.toFixed(1)}" transform="translate(${p.x.toFixed(1)},${p.y.toFixed(1)})">` +
7838
- `<circle class="kb-g-hit" r="16"/><circle class="kb-g-dot" r="9"/><text x="13" y="4">${escapeHtml(n.title)}</text></g>`; }).join('');
7839
- const legend = '<div class="kb-g-legend"><span class="kb-gleg src">Source</span><span class="kb-gleg con">Concept</span><span class="kb-gleg per">Person</span></div>';
7840
- const note = graph.truncated ? `<div class="kb-view-note">Showing ${graph.nodes.length} — graph truncated (some pages omitted)</div>` : '';
7841
- // No header of its own: the step's single full-width band above the split names this pane, and
7842
- // the Overview button moved there so it survives opening a page. See kbStepHeadHtml.
7843
- return '<section class="kb-col kb-graph">' +
7844
- '<div class="kb-graph-sub">' + legend + '<span class="kb-g-hint">Click a node to open its page · scroll to zoom · drag to pan</span></div>' +
7845
- `<div class="kb-graph-body"><svg viewBox="0 0 ${W} ${H}" data-vb-base="0 0 ${W} ${H}" class="kb-graph-svg" role="group" aria-label="Knowledge graph">${lines}${dots}</svg>` +
7846
- `<button type="button" class="kb-g-fit" data-kb-fit hidden data-tip="Zoom to fit (Home)" aria-label="Zoom to fit">⤢ Fit</button></div>${note}</section>`;
7847
- }
7848
8435
  // View-only pan/zoom: we mutate the live SVG viewBox, never re-layout. The base 0 0 W H box IS the
7849
8436
  // fit; the Fit button + Home key restore it, and it shows only while zoomed/panned. Zoom resets on a
7850
8437
  // generation re-render (rare) — ponytail: persisting it across re-layouts isn't worth the state.
@@ -7896,7 +8483,8 @@
7896
8483
  // loading + error REUSE the file viewer's own message idiom (.kb-view-msg / .kb-view-spin /
7897
8484
  // .kb-view-ico.err / .primary Retry) so the graph's "can't show content yet" states look identical
7898
8485
  // to the file preview's — one learned pattern, not a second near-duplicate.
7899
- function kbGraphLoading() { return '<section class="kb-col"><div class="kb-view-msg"><div class="kb-view-spin" role="status" aria-label="Building graph"></div><div class="kb-view-msg-title">Building graph…</div></div></section>'; }
8486
+ /** The first layout is still being worked out; `note` (the loading line with Stop) shows above it, so a big map can be stopped. */
8487
+ function kbGraphLoading(note = '') { return '<section class="kb-col">' + note + '<div class="kb-view-msg"><div class="kb-view-spin" role="status" aria-label="Building graph"></div><div class="kb-view-msg-title">Building graph…</div></div></section>'; }
7900
8488
  function kbGraphError() { return '<section class="kb-col"><div class="kb-view-msg"><span class="kb-view-ico err" aria-hidden="true">⚠</span><div class="kb-view-msg-title">Couldn’t load the graph.</div><div class="kb-view-act"><button type="button" class="primary" data-kb-graph-retry>↻ Retry</button></div></div></section>'; }
7901
8489
  // Whitelist the LLM-derived page type into a SAFE single class token — never interpolate it raw (a
7902
8490
  // space would inject extra classes). Same discipline as KB_CHIP; an unknown type falls back to the
@@ -8053,23 +8641,271 @@
8053
8641
  // ── Stage C: the knowledge graph + page viewer ──────────────────────────────────
8054
8642
  // Same alive()/epoch/key contract as kbLoadPreview above — the render only happens if nothing else
8055
8643
  // (a new epoch, a changed key, a project switch, or leaving the pane) superseded this fetch meanwhile.
8644
+ // ── #2491 R6.9: the knowledge map — streamed, laid out off the main thread, coloured by the person's categories ──
8645
+ // The pure half is web/kb-categories.js (kbg*). This screen holds the whole map of the current generation: it asks for
8646
+ // chunks until there is no next, keeps links by slug until both ends have arrived, and filters and colours it itself
8647
+ // from the current categories, so a move in the tree recolours the map without asking the server again.
8648
+ let kbGm = null; // { projId, model, layoutKey, pos: Map(id → {x,y}), w, h, stopped, error, loading }
8649
+ const kbGo = { hiddenCats: new Set(), hiddenTypes: new Set(), search: '', neighbourOf: null, list: false };
8650
+ let kbGWorker = null, kbGEpoch = 0, kbGFocus = null;
8651
+
8652
+ function kbGraphResetOpts() {
8653
+ kbGo.hiddenCats = new Set(); kbGo.hiddenTypes = new Set(); kbGo.search = ''; kbGo.neighbourOf = null;
8654
+ }
8655
+ function kbGraphStopWorker() {
8656
+ if (kbGWorker) { try { kbGWorker.terminate(); } catch { /* gone */ } kbGWorker = null; }
8657
+ kbGEpoch += 1;
8658
+ }
8659
+
8056
8660
  async function kbLoadGraph(proj) {
8057
8661
  const epoch = viewEpoch, key = lastViewKey;
8058
8662
  const alive = () => epoch === viewEpoch && key === lastViewKey && current && current.id === proj.id && !$wsKnowledge.hidden;
8059
8663
  const ac = new AbortController(); kbTextAbort = ac;
8060
- try {
8061
- const r = await fetch(`/api/projects/${encodeURIComponent(proj.id)}/knowledge/graph`, { signal: ac.signal, cache: 'no-store' });
8062
- if (!r.ok) throw new Error(`graph ${r.status}`);
8063
- const body = await r.json();
8064
- if (!body || !body.graph || !Array.isArray(body.graph.nodes)) throw new Error('bad graph envelope');
8065
- if (!alive()) return;
8066
- kbGraphIndex = body.graph.index || null; // feeds the step header's ✦ Overview button
8067
- const h = kbViewHost(); if (h) h.innerHTML = kbGraphSvg(body.graph);
8664
+ const want = knowledgeState && knowledgeState.currentGeneration ? knowledgeState.currentGeneration.generationId : null;
8665
+ // The same generation, already complete: draw it again (recoloured from the current categories), no fetch.
8666
+ if (kbGm && kbGm.projId === proj.id && kbGm.model.generationId === want && kbGm.model.done && !kbGm.error) {
8667
+ kbGraphIndex = kbGm.model.index || null;
8668
+ kbGraphRender(true);
8068
8669
  if (knowledgeState) kbPaintStepHead(knowledgeState);
8670
+ return;
8671
+ }
8672
+ // "Load the rest" after Stop carries on from the last chunk that arrived, keeping what is already drawn.
8673
+ const resume = !!(kbGm && kbGm.resume && kbGm.projId === proj.id && kbGm.model.generationId === want
8674
+ && kbGm.next !== null && kbGm.next !== undefined && !kbGm.error);
8675
+ if (!kbGm || kbGm.projId !== proj.id) kbGraphResetOpts();
8676
+ kbGraphStopWorker();
8677
+ if (resume) Object.assign(kbGm, { stopped: false, loading: true, resume: false });
8678
+ else kbGm = { projId: proj.id, model: kbgCreate(null), layoutKey: null, pos: new Map(), w: 600, h: 440, stopped: false, error: null, loading: true, next: null };
8679
+ try {
8680
+ let generation = resume ? kbGm.model.generationId : null; let cursor = resume ? kbGm.next : 0; let restarts = 0;
8681
+ for (;;) {
8682
+ const q = generation ? `?generation=${encodeURIComponent(generation)}&cursor=${cursor}` : '';
8683
+ const r = await fetch(`/api/projects/${encodeURIComponent(proj.id)}/knowledge/graph${q}`, { signal: ac.signal, cache: 'no-store' });
8684
+ if (!r.ok) throw new Error(`graph ${r.status}`);
8685
+ const body = await r.json();
8686
+ if (!body || !body.graph) throw new Error('bad graph envelope');
8687
+ if (!alive()) return;
8688
+ const g = body.graph;
8689
+ if (g.restart) {
8690
+ // Organized again while the map was coming in: start over on the new generation (a few times at most).
8691
+ if (++restarts > 3) throw new Error('the map kept changing');
8692
+ generation = g.generationId; cursor = 0;
8693
+ kbGm.model = kbgCreate(generation); kbGm.pos = new Map(); kbGm.layoutKey = null;
8694
+ continue;
8695
+ }
8696
+ if (!Array.isArray(g.nodes)) throw new Error('bad graph envelope');
8697
+ if (!generation) { generation = g.generationId; kbGm.model = kbgCreate(generation); }
8698
+ kbgMerge(kbGm.model, g);
8699
+ kbGm.next = g.next ?? null;
8700
+ kbGraphIndex = kbGm.model.index || null;
8701
+ kbGm.loading = g.next !== null && g.next !== undefined && !kbGm.stopped;
8702
+ kbGraphRender(!kbGm.loading);
8703
+ if (knowledgeState) kbPaintStepHead(knowledgeState);
8704
+ if (!kbGm.loading) break;
8705
+ cursor = g.next;
8706
+ }
8069
8707
  } catch (err) {
8070
8708
  if (err && err.name === 'AbortError') return;
8071
- if (alive()) { kbGraphIndex = null; const h = kbViewHost(); if (h) h.innerHTML = kbGraphError(); if (knowledgeState) kbPaintStepHead(knowledgeState); } // Retry re-keys via setViewer — matches the file-viewer idiom (no poll-flicker)
8709
+ if (alive()) { kbGraphIndex = null; if (kbGm) kbGm.error = String(err && err.message || err); const h = kbViewHost(); if (h) h.innerHTML = kbGraphError(); if (knowledgeState) kbPaintStepHead(knowledgeState); }
8710
+ }
8711
+ }
8712
+
8713
+ /** Lay out what is drawn now, off the main thread; a newer request (or closing the map) drops the older one. */
8714
+ function kbGraphLayout(view, done) {
8715
+ kbGraphStopWorker();
8716
+ const epoch = kbGEpoch;
8717
+ const ids = view.nodes.map((n) => n.id);
8718
+ const index = new Map(ids.map((id, i) => [id, i]));
8719
+ const edges = new Int32Array(view.edges.length * 2);
8720
+ view.edges.forEach(([a, b], i) => { edges[i * 2] = index.get(a); edges[i * 2 + 1] = index.get(b); });
8721
+ const seeds = Uint32Array.from(ids, (id) => kbHash(id));
8722
+ const finish = (x, y, w, h) => {
8723
+ if (epoch !== kbGEpoch || !kbGm) return;
8724
+ kbGm.pos = new Map(ids.map((id, i) => [id, { x: x[i], y: y[i] }]));
8725
+ kbGm.w = w; kbGm.h = h;
8726
+ done();
8727
+ };
8728
+ try {
8729
+ kbGWorker = new Worker('/kb-graph-worker.js');
8730
+ kbGWorker.onmessage = (ev) => { const m = ev.data || {}; if (m.epoch === epoch) { finish(m.x, m.y, m.w, m.h); kbGraphStopWorker(); } };
8731
+ kbGWorker.onerror = () => { kbGraphStopWorker(); if (kbGm) { kbGm.error = 'layout'; const h = kbViewHost(); if (h && viewer.mode === 'graph') h.innerHTML = kbGraphError(); } };
8732
+ kbGWorker.postMessage({ epoch, n: ids.length, edges, seeds }, [edges.buffer, seeds.buffer]);
8733
+ } catch {
8734
+ kbGraphStopWorker();
8735
+ if (kbGm) { kbGm.error = 'layout'; const h = kbViewHost(); if (h && viewer.mode === 'graph') h.innerHTML = kbGraphError(); }
8736
+ }
8737
+ }
8738
+
8739
+ const KB_TYPE_LABEL = { source: 'Source', concept: 'Concept', person: 'Person' };
8740
+ function kbGraphNodeHtml(n, view, file) {
8741
+ const p = kbGm.pos.get(n.id);
8742
+ if (!p) return '';
8743
+ const m = view.member.get(n.id) || { cats: [], grouped: false };
8744
+ const cats = m.cats.slice(0, 3);
8745
+ const col = kbgColour(file, cats[0] || null);
8746
+ const label = n.kind === 'document' ? (n.filename || 'document') : (n.title || n.slug);
8747
+ const where = !m.grouped ? 'Not yet grouped' : m.cats.map((c) => (c === 'uncategorized' ? 'Uncategorized' : kbcLabel(file, c))).join(', ');
8748
+ const more = m.cats.length > 3 ? ` (+${m.cats.length - 3})` : '';
8749
+ // A document removed since the map was loaded is shown as gone at once: the cached map keeps the old flag.
8750
+ const gone = n.kind === 'document' && (n.present === false || !!(knowledgeState && !knowledgeState.sources.some((s) => s.sourceId === n.sourceId)));
8751
+ const kind = n.kind === 'document' ? (gone ? 'document, no longer in Knowledge' : 'document') : (KB_TYPE_LABEL[n.type] || 'Concept').toLowerCase() + ' page';
8752
+ const tip = `${label} · ${kind} · ${where}${more}`;
8753
+ const match = view.matchSet.has(n.id) ? ' match' : '';
8754
+ const cls = `kb-g-node ${n.kind === 'document' ? 'kb-g-doc' : 'kb-g-page kb-g-' + escapeAttr(n.type || 'concept')}${m.grouped ? '' : ' ungrouped'}${gone ? ' gone' : ''}${col.hatch ? ' hatch' : ''}${match}`;
8755
+ const act = n.kind === 'document' ? `data-kb-doc="${escapeAttr(n.sourceId)}"` : `data-kb-node="${escapeAttr(n.slug)}"`;
8756
+ const shape = n.kind === 'document'
8757
+ ? '<rect class="kb-g-dot" x="-7" y="-7" width="14" height="14" rx="3"/>'
8758
+ : '<circle class="kb-g-dot" r="8"/>';
8759
+ const rings = cats.slice(1).map((c, i) => `<circle class="kb-g-ring" r="${11 + i * 3}" style="--kbg-c:var(${kbgColour(file, c).token})"/>`).join('');
8760
+ return `<g class="${cls}" tabindex="0" role="button" ${act} data-command-id="shell.kb-graph-open#${escapeAttr(n.id)}" data-command-instance-label="${escapeAttr(label)}" data-kb-gid="${escapeAttr(n.id)}" aria-label="${escapeAttr(tip)}" data-tip="${escapeAttr(tip)}"` +
8761
+ ` style="--kbg-c:var(${col.token})" transform="translate(${p.x.toFixed(1)},${p.y.toFixed(1)})">` +
8762
+ `<circle class="kb-g-hit" r="16"/>${rings}${shape}<text x="13" y="4">${escapeHtml(label.length > 40 ? label.slice(0, 39) + '…' : label)}</text></g>`;
8763
+ }
8764
+
8765
+ function kbGraphControlsHtml(view, file) {
8766
+ const legend = kbgLegend(kbGm.model, file).map((c) =>
8767
+ `<button type="button" class="kb-gchip${c.hatch ? ' hatch' : ''}${c.dashed ? ' dashed' : ''}" aria-pressed="${kbGo.hiddenCats.has(c.id) ? 'false' : 'true'}" data-kb-gcat="${escapeAttr(c.id)}"` +
8768
+ ` style="--kbg-c:var(${c.token})" data-command-id="shell.kb-graph-filter#${escapeAttr('cat-' + c.id)}" data-command-instance-label="${escapeAttr(c.name)}" data-tip="Show or hide ${escapeAttr(c.name)}"><span class="kb-gsw" aria-hidden="true"></span>${escapeHtml(c.name)} <span class="kb-gn">${c.n}</span></button>`).join('');
8769
+ const types = ['source', 'concept', 'person'].map((t) =>
8770
+ `<button type="button" class="kb-gchip kb-gtype" aria-pressed="${kbGo.hiddenTypes.has(t) ? 'false' : 'true'}" data-kb-gtype="${t}" data-command-id="shell.kb-graph-filter#${escapeAttr('type-' + t)}" data-command-instance-label="${escapeAttr(KB_TYPE_LABEL[t] + ' pages')}">${KB_TYPE_LABEL[t]} pages</button>`).join('');
8771
+ const hidden = kbGo.hiddenCats.size || kbGo.hiddenTypes.size;
8772
+ const found = kbGo.search ? `<span class="kb-gfound" role="status">${view.matches.length} found</span>` : '';
8773
+ return '<div class="kb-graph-sub kb-graph-ctl">' +
8774
+ `<div class="kb-g-legend" role="group" aria-label="Show categories">${legend}${hidden ? '<button type="button" class="kb-link" data-kb-gall data-command-id="shell.kb-graph-filter#all" data-command-instance-label="every category">Show all</button>' : ''}</div>` +
8775
+ `<div class="kb-g-types" role="group" aria-label="Show page types">${types}</div>` +
8776
+ '<div class="kb-g-tools">' +
8777
+ `<input type="search" class="kb-gsearch" placeholder="Find on the map" aria-label="Find on the map" value="${escapeAttr(kbGo.search)}" data-command-id="shell.kb-graph-search">${found}` +
8778
+ `<button type="button" class="kb-gneigh" role="switch" aria-checked="${kbGo.neighbourOf ? 'true' : 'false'}" data-kb-gneigh data-command-id="shell.kb-graph-neighbourhood"` +
8779
+ ` data-tip="${kbGo.neighbourOf ? 'Show the whole map again' : 'Focus or hover a node first, then show only it and its neighbours'}">Only neighbours</button>` +
8780
+ '<span class="kb-gseg" role="group" aria-label="Show as">' +
8781
+ `<button type="button" aria-pressed="${kbGo.list ? 'false' : 'true'}" data-kb-glist="0" data-command-id="shell.kb-graph-list-toggle#${escapeAttr('map')}" data-command-instance-label="${escapeAttr('Map')}">Map</button>` +
8782
+ `<button type="button" aria-pressed="${kbGo.list ? 'true' : 'false'}" data-kb-glist="1" data-command-id="shell.kb-graph-list-toggle#${escapeAttr('list')}" data-command-instance-label="${escapeAttr('List')}">List</button></span>` +
8783
+ '</div></div>';
8784
+ }
8785
+
8786
+ function kbGraphNotesHtml(view, file) {
8787
+ const m = kbGm.model;
8788
+ const notes = [];
8789
+ if (kbGm.loading) notes.push(`<span>Loading more… ${m.nodes.size.toLocaleString()} of about ${Math.max(m.total, m.nodes.size).toLocaleString()} pages and documents.</span> <button type="button" class="kb-link" data-kb-gstop data-command-id="shell.kb-graph-load-more">Stop</button>`);
8790
+ else if (kbGm.stopped && !m.done) notes.push(`<span>Stopped at ${m.nodes.size.toLocaleString()} of about ${m.total.toLocaleString()}.</span> <button type="button" class="kb-link" data-kb-gmore data-command-id="shell.kb-graph-load-more">Load the rest</button>`);
8791
+ if (view.capped) {
8792
+ const tops = kbcChildren(file, null).slice(0, 6).map((c) => `<button type="button" class="kb-link" data-kb-gonly="${escapeAttr(c.id)}" data-command-id="shell.kb-graph-show-category#${escapeAttr(c.id)}" data-command-instance-label="${escapeAttr(c.name)}">${escapeHtml(c.name)}</button>`).join(' · ');
8793
+ notes.push(`<span>Showing ${view.capped.shown.toLocaleString()} of ${view.capped.total.toLocaleString()} items.${tops ? ' Pick one category to see all of it:' : ' Hide some page types to see the rest.'}</span> ${tops}`);
8072
8794
  }
8795
+ if (m.truncated) notes.push('<span>Some knowledge pages could not be read, so the map is incomplete.</span>');
8796
+ if (m.done && !m.grouped && m.nodes.size) notes.push('<span>This knowledge base was organized before categories. Organize again to group its pages by your categories.</span>');
8797
+ if (view.pending && m.done) notes.push(`<span>${view.pending} link${view.pending === 1 ? '' : 's'} point to pages that are not on the map.</span>`);
8798
+ return notes.length ? `<div class="kb-view-note kb-gnotes" role="status">${notes.join('<br>')}</div>` : '';
8799
+ }
8800
+
8801
+ /** The same nodes as an accessible list, grouped by category. */
8802
+ function kbGraphListHtml(view, file) {
8803
+ const groups = new Map();
8804
+ for (const n of view.nodes) {
8805
+ const m = view.member.get(n.id);
8806
+ // Under the first of its categories that is shown (a page drawn from two can be listed under either).
8807
+ const key = !m || !m.grouped ? 'ungrouped' : (m.cats.find((c) => !kbGo.hiddenCats.has(c)) || m.cats[0] || 'uncategorized');
8808
+ if (!groups.has(key)) groups.set(key, []);
8809
+ groups.get(key).push(n);
8810
+ }
8811
+ const name = (k) => (k === 'ungrouped' ? 'Not yet grouped' : k === 'uncategorized' ? 'Uncategorized' : kbcLabel(file, k));
8812
+ const order = [...kbcChildren(file, null).map((c) => c.id), 'uncategorized', 'ungrouped'].filter((k) => groups.has(k));
8813
+ return '<div class="kb-glist">' + order.map((k) => `<section class="kb-glist-g"><h4>${escapeHtml(name(k))} <span class="kb-gn">${groups.get(k).length}</span></h4><ul>` +
8814
+ groups.get(k).sort((a, b) => String(a.title || a.filename).localeCompare(String(b.title || b.filename))).map((n) => {
8815
+ const act = n.kind === 'document' ? `data-kb-doc="${escapeAttr(n.sourceId)}"` : `data-kb-node="${escapeAttr(n.slug)}"`;
8816
+ const kind = n.kind === 'document' ? 'document' : `${(KB_TYPE_LABEL[n.type] || 'Concept').toLowerCase()} page`;
8817
+ return `<li><button type="button" class="kb-glist-i${view.matchSet.has(n.id) ? ' match' : ''}" ${act} data-command-id="shell.kb-graph-open#${escapeAttr(n.id)}" data-command-instance-label="${escapeAttr(n.title || n.filename || n.slug)}">${escapeHtml(n.title || n.filename || n.slug)}<span class="kb-gk">${kind}</span></button></li>`;
8818
+ }).join('') + '</ul></section>').join('') + '</div>';
8819
+ }
8820
+
8821
+ /** Paint the map: controls, notes, and the drawing (laid out first when what is drawn changed). */
8822
+ function kbGraphRender(final) {
8823
+ const host = kbViewHost();
8824
+ if (!host || viewer.mode !== 'graph' || !kbGm) return;
8825
+ const file = kbCats(knowledgeState);
8826
+ const view = kbgView(kbGm.model, file, kbGo);
8827
+ view.matchSet = new Set(view.matches);
8828
+ kbGm.view = view; // what is drawn now, even while its layout is still being computed (the announcement reads it)
8829
+ if (!kbGm.model.nodes.size && !kbGm.loading) { host.innerHTML = kbGm.model.truncated ? kbGraphTruncatedEmpty() : kbGraphEmpty(knowledgeState); return; }
8830
+ const layoutKey = view.nodes.map((n) => n.id).join('\n') + '|' + view.edges.length;
8831
+ const paint = () => {
8832
+ const h = kbViewHost();
8833
+ if (!h || viewer.mode !== 'graph' || !kbGm) return;
8834
+ const focusId = document.activeElement && document.activeElement.dataset ? document.activeElement.dataset.kbGid : null;
8835
+ const searchHad = document.activeElement && document.activeElement.classList && document.activeElement.classList.contains('kb-gsearch');
8836
+ const W = Math.round(kbGm.w), H = Math.round(kbGm.h);
8837
+ const lines = view.edges.map(([a, b]) => { const p = kbGm.pos.get(a), q = kbGm.pos.get(b);
8838
+ return p && q ? `<line class="kb-g-edge" data-a="${escapeAttr(a)}" data-b="${escapeAttr(b)}" x1="${p.x.toFixed(1)}" y1="${p.y.toFixed(1)}" x2="${q.x.toFixed(1)}" y2="${q.y.toFixed(1)}"/>` : ''; }).join('');
8839
+ const dots = view.nodes.map((n) => kbGraphNodeHtml(n, view, file)).join('');
8840
+ const defs = '<defs><pattern id="kbg-hatch" width="4" height="4" patternUnits="userSpaceOnUse" patternTransform="rotate(45)"><line x1="0" y1="0" x2="0" y2="4" class="kb-g-hatchline"/></pattern></defs>';
8841
+ const body = kbGo.list ? kbGraphListHtml(view, file)
8842
+ : `<div class="kb-graph-body"><svg viewBox="0 0 ${W} ${H}" data-vb-base="0 0 ${W} ${H}" class="kb-graph-svg" role="group" aria-label="Knowledge map, ${view.nodes.length} items">${defs}${lines}${dots}</svg>` +
8843
+ '<button type="button" class="kb-g-fit" data-kb-fit hidden data-tip="Zoom to fit (Home)" aria-label="Zoom to fit" data-command-id="shell.kb-graph-fit">⤢ Fit</button></div>';
8844
+ h.innerHTML = '<section class="kb-col kb-graph">' + kbGraphControlsHtml(view, file) + kbGraphNotesHtml(view, file) + body + '</section>';
8845
+ kbGm.view = view;
8846
+ const back = (kbGFocus || focusId) && h.querySelector(`[data-kb-gid="${CSS.escape(kbGFocus || focusId)}"]`);
8847
+ if (back) back.focus({ preventScroll: true });
8848
+ kbGFocus = null;
8849
+ if (searchHad) { const s = h.querySelector('.kb-gsearch'); if (s) { s.focus(); s.setSelectionRange(s.value.length, s.value.length); } }
8850
+ };
8851
+ if (kbGo.list || layoutKey === kbGm.layoutKey) { paint(); return; }
8852
+ // While chunks are still arriving, lay out only now and then; the final chunk always lays out.
8853
+ if (!final && kbGm.layoutKey && kbGm.lastLayoutAt && Date.now() - kbGm.lastLayoutAt < 1500) { paint(); return; }
8854
+ kbGm.lastLayoutAt = Date.now();
8855
+ if (!kbGm.pos.size) host.innerHTML = kbGraphLoading(kbGraphNotesHtml(view, file));
8856
+ kbGraphLayout(view, () => { if (kbGm) kbGm.layoutKey = layoutKey; paint(); });
8857
+ }
8858
+
8859
+ /** The map's controls; true when handled. */
8860
+ function kbGraphClick(e) {
8861
+ const t = e.target;
8862
+ const cat = t.closest('[data-kb-gcat]');
8863
+ if (cat) { const id = cat.dataset.kbGcat; if (kbGo.hiddenCats.has(id)) kbGo.hiddenCats.delete(id); else kbGo.hiddenCats.add(id); kbGraphRender(true); kbAnnounceGraph(); return true; }
8864
+ const type = t.closest('[data-kb-gtype]');
8865
+ if (type) { const id = type.dataset.kbGtype; if (kbGo.hiddenTypes.has(id)) kbGo.hiddenTypes.delete(id); else kbGo.hiddenTypes.add(id); kbGraphRender(true); kbAnnounceGraph(); return true; }
8866
+ if (t.closest('[data-kb-gall]')) { kbGo.hiddenCats.clear(); kbGo.hiddenTypes.clear(); kbGraphRender(true); kbAnnounceGraph(); return true; }
8867
+ const only = t.closest('[data-kb-gonly]');
8868
+ if (only) {
8869
+ const keep = only.dataset.kbGonly;
8870
+ kbGo.hiddenCats = new Set([...kbcChildren(kbCats(knowledgeState), null).map((c) => c.id), 'uncategorized', 'ungrouped'].filter((id) => id !== keep));
8871
+ kbGraphRender(true); kbAnnounceGraph(); return true;
8872
+ }
8873
+ if (t.closest('[data-kb-gneigh]')) {
8874
+ const focused = document.activeElement && document.activeElement.dataset ? document.activeElement.dataset.kbGid : null;
8875
+ kbGo.neighbourOf = kbGo.neighbourOf ? null : (kbGm && kbGm.lastNode) || focused || null;
8876
+ if (!kbGo.neighbourOf && !kbGm.lastNode) showToast('Point at a page or document on the map first, then choose Only neighbours.', 'warn');
8877
+ kbGFocus = kbGo.neighbourOf;
8878
+ kbGraphRender(true); kbAnnounceGraph(); return true;
8879
+ }
8880
+ const seg = t.closest('[data-kb-glist]');
8881
+ if (seg) { kbGo.list = seg.dataset.kbGlist === '1'; kbGraphRender(true); const b = kbViewHost()?.querySelector(`[data-kb-glist="${kbGo.list ? 1 : 0}"]`); if (b) b.focus(); return true; }
8882
+ if (t.closest('[data-kb-gstop]')) { if (kbGm) { kbGm.stopped = true; } kbAbortPreview(); if (kbGm) { kbGm.loading = false; kbGraphRender(true); } return true; }
8883
+ if (t.closest('[data-kb-gmore]')) { lastViewKey = null; if (kbGm) kbGm.resume = true; if (knowledgeState) paintKnowledge(knowledgeState); return true; }
8884
+ const doc = t.closest('[data-kb-doc]');
8885
+ if (doc) {
8886
+ const id = doc.dataset.kbDoc;
8887
+ if (knowledgeState && knowledgeState.sources.some((s) => s.sourceId === id)) { setViewer({ mode: 'file', sourceId: id }); kbFocusSourceId = id; paintKnowledge(knowledgeState); }
8888
+ else showToast('That document is no longer in Knowledge. Organize again to update the map.', 'warn');
8889
+ return true;
8890
+ }
8891
+ return false;
8892
+ }
8893
+ function kbAnnounceGraph() {
8894
+ const v = kbGm && kbGm.view;
8895
+ if (v) kbAnnounce(`Showing ${v.nodes.length} item${v.nodes.length === 1 ? '' : 's'} on the map.`);
8896
+ }
8897
+ /** Hover or focus a node: its neighbours stand out, the rest steps back. */
8898
+ function kbGraphHighlight(id) {
8899
+ const svg = kbGraphSvgEl();
8900
+ if (!svg) return;
8901
+ svg.querySelectorAll('.near, .lit').forEach((el) => el.classList.remove('near', 'lit'));
8902
+ svg.classList.toggle('kb-hl', !!id);
8903
+ if (!id || !kbGm || !kbGm.view) return;
8904
+ kbGm.lastNode = id;
8905
+ const near = kbGm.view.adj.get(id) || new Set();
8906
+ svg.querySelector(`[data-kb-gid="${CSS.escape(id)}"]`)?.classList.add('near');
8907
+ for (const n of near) svg.querySelector(`[data-kb-gid="${CSS.escape(n)}"]`)?.classList.add('near');
8908
+ svg.querySelectorAll('.kb-g-edge').forEach((l) => { if (l.dataset.a === id || l.dataset.b === id) l.classList.add('lit'); });
8073
8909
  }
8074
8910
  /** `generationId` (optional) pins the read to one published generation — a workflow citation opens
8075
8911
  * the page AS IT READ when the workflow was built. Without it the route serves the current generation,
@@ -8424,9 +9260,16 @@
8424
9260
  const loose = st.sources.filter((source) => !kbInDesignSet(source, st));
8425
9261
  const inSet = st.sources.length - loose.length;
8426
9262
  const jump = inSet ? `<button type="button" class="kb-link kb-ds-jump" data-kb-ds-jump data-command-id="shell.kb-design-set-jump" data-tip="Go to the Design set">${inSet} more in the design set</button>` : '';
8427
- const body = (loose.length
8428
- ? loose.map((source) => kbSourceRow(source, st)).join('')
8429
- : (inSet ? '' : '<div class="kb-empty">No references yet — drop files above (PDF, Word, Excel, email, pictures or text), or ask your terminal AI to add them.</div>')) + jump;
9263
+ // #2491 R6.9: once the first category exists the list is a tree; until then it is exactly the flat list, plus a way to
9264
+ // make one. A categories file that cannot be read shows every reference flat and says so.
9265
+ kbSelFor(current, st);
9266
+ const tree = kbCatUsable(st) && kbCats(st).categories.length > 0;
9267
+ const newCat = kbCatUsable(st) && loose.length && !(kbCatEdit && kbCatEdit.mode === 'new' && !kbCatEdit.parentId)
9268
+ ? '<button type="button" class="kb-link kb-cat-new" data-kb-cat-new data-command-id="shell.kb-category-new" data-tip="Group references into categories">+ New category</button>' : '';
9269
+ const flatEdit = !tree && kbCatEdit && kbCatEdit.mode === 'new' ? kbCatEditHtml(0) : '';
9270
+ const body = kbCatUnavailableHtml(st) + (loose.length
9271
+ ? (tree ? kbTreeHtml(st, loose) : flatEdit + loose.map((source) => kbSourceRow(source, st)).join(''))
9272
+ : (inSet ? '' : '<div class="kb-empty">No references yet — drop files above (PDF, Word, Excel, email, pictures or text), or ask your terminal AI to add them.</div>')) + newCat + jump + kbSelBarHtml(st);
8430
9273
  return '<section class="kb-col">' +
8431
9274
  '<div class="kb-refs-body">' + kbDesignSetStrip(st) +
8432
9275
  '<button type="button" class="kb-drop" id="kb-drop" data-command-id="shell.add-knowledge" data-tip="Drop PDF, Word, Excel, email (.msg, .eml), picture or text files here, or click to pick them">' +
@@ -8646,7 +9489,7 @@
8646
9489
  // DOM; suppressing the repaint while it's active (kbAdjustActive) is simpler and safer than
8647
9490
  // snapshotting/restoring every piece. lastRefsHtml is left stale, so the next tick (once the box is
8648
9491
  // inactive) catches the column up to the latest state.
8649
- if (html !== lastRefsHtml && !kbAdjustActive() && !kbDsPanelBusy()) {
9492
+ if (html !== lastRefsHtml && !kbAdjustActive() && !kbDsPanelBusy() && !kbCatEditActive() && !kbDragIds && !kbDragHover) {
8650
9493
  const oldBody = refsHost.querySelector('.kb-refs-body');
8651
9494
  const scrollTop = oldBody ? oldBody.scrollTop : 0;
8652
9495
  refsHost.innerHTML = html;
@@ -8662,6 +9505,7 @@
8662
9505
  kbFocusSourceId = null;
8663
9506
  }
8664
9507
  kbDsRestoreFocus(refsHost);
9508
+ kbCatRestoreFocus(refsHost);
8665
9509
  const shown = kbActiveDesignSet(st);
8666
9510
  if (kbFocusDesignSet && (shown ? shown.sourceId : null) === kbFocusDesignSet.sourceId) {
8667
9511
  const target = refsHost.querySelector('.kb-ds .kb-fname, .kb-ds button') || refsHost.querySelector('#kb-drop');
@@ -8672,6 +9516,8 @@
8672
9516
  }
8673
9517
 
8674
9518
  const key = kbViewKey(st);
9519
+ // #2491 R6.9: a category change recolours the open map from the current categories (no reload, no re-layout).
9520
+ if (key === lastViewKey && viewer.mode === 'graph' && kbGm && kbGm.catRev !== kbCats(st).revision) { kbGm.catRev = kbCats(st).revision; kbGraphRender(true); }
8675
9521
  if (key !== lastViewKey) {
8676
9522
  // The key can change WITHOUT setViewer() — e.g. a poll swaps a row's blobSha256 under an open
8677
9523
  // preview. Abort and bump the epoch here too, or the superseded download keeps streaming (its
@@ -8818,12 +9664,177 @@
8818
9664
  `<div class="company-entry-meta">Latest v${latestNumber} · ${escapeHtml(latest.filename)} · ${escapeHtml(kbBytes(latest.bytes))}` +
8819
9665
  (latest.provenance && latest.provenance.projectName
8820
9666
  ? ` · from ${escapeHtml(latest.provenance.projectName)}` : '') + '</div></div>' +
8821
- `<div class="company-entry-actions">${action}<button type="button" class="company-remove" ` +
9667
+ `<div class="company-entry-actions">${action}` +
9668
+ (state.taxonomy && Array.isArray(state.taxonomy.categories) && state.taxonomy.categories.length ? `<button type="button" data-company-move="${escapeAttr(entry.librarySourceId)}" aria-haspopup="menu" data-command-id="shell.kb-move-to#${escapeAttr(entry.librarySourceId)}" data-command-instance-label="${escapeAttr(entry.displayName)}" data-tip="Move to another company category">Move to…</button>` : '') +
9669
+ `<button type="button" class="company-remove" ` +
8822
9670
  `data-company-stage-remove="${escapeAttr(entry.librarySourceId)}" data-command-id="shell.company-remove" ` +
8823
9671
  `data-command-instance="${escapeAttr(entry.librarySourceId)}" data-command-instance-label="${escapeAttr(entry.displayName)}" ` +
8824
9672
  'data-tip="Remove this entry from company knowledge">Remove…</button></div></article>';
8825
9673
  }
8826
9674
 
9675
+ // #2491 R6.9: the company library's own categories. The dialog lists shared references by category, with New
9676
+ // category, Rename, Delete and a Move to… on each entry (no drag in a dialog). Each change carries the categories'
9677
+ // revision and the company folder this dialog drew, so a change made meanwhile elsewhere is never overwritten.
9678
+ let companyCatEdit = null; // { mode: 'new' | 'rename', id?, parentId?, name? }
9679
+ const companyTax = (state) => (state && state.taxonomy && Array.isArray(state.taxonomy.categories) ? state.taxonomy : { v: 1, revision: 0, categories: [], placements: {}, state: 'absent' });
9680
+ function companyCatEditHtml(depth) {
9681
+ const e = companyCatEdit;
9682
+ return `<div class="kb-cat-edit company-cat-edit" style="--kb-depth:${depth}"><input type="text" class="kb-cat-input company-cat-input" maxlength="80" value="${e.mode === 'rename' ? escapeAttr(e.name || '') : ''}"` +
9683
+ ` aria-label="${e.mode === 'rename' ? 'New name for the company category' : 'Name of the new company category'}" placeholder="Category name" data-command-id="shell.kb-category-name">` +
9684
+ `<button type="button" class="primary" data-company-cat-save data-command-id="shell.kb-category-save">${e.mode === 'rename' ? 'Rename' : 'Create'}</button>` +
9685
+ '<button type="button" data-company-cat-cancel data-command-id="shell.kb-category-cancel">Cancel</button></div>';
9686
+ }
9687
+ function companyListHtml(entries, state) {
9688
+ const tax = companyTax(state);
9689
+ const usable = tax.state !== 'damaged' && tax.state !== 'newer';
9690
+ const head = '<div class="company-section-head"><div class="company-section-label">Shared references</div>' +
9691
+ (usable ? '<button type="button" class="kb-link" data-company-cat-new data-command-id="shell.kb-category-new" data-tip="Group shared references into categories">+ New category</button>' : '') + '</div>';
9692
+ const warn = usable ? '' : `<div class="kb-cat-warn" role="status"><span>${tax.state === 'newer' ? 'The company categories were saved by a newer FloLess' : 'The company categories could not be read'}, so the shared references are listed without them. You can start again with no categories (the saved ones are kept aside).</span>` +
9693
+ '<button type="button" data-company-cat-reset data-command-id="shell.kb-category-reset">Start again</button></div>';
9694
+ const topEdit = companyCatEdit && companyCatEdit.mode === 'new' && !companyCatEdit.parentId ? companyCatEditHtml(0) : '';
9695
+ if (!usable || !tax.categories.length) return head + warn + topEdit + entries.map((entry) => companyEntryHtml(entry, state)).join('');
9696
+ const byId = new Map(entries.map((e) => [e.librarySourceId, e]));
9697
+ const all = new Set(['uncategorized', ...tax.categories.map((c) => c.id)]);
9698
+ const items = kbcTreeItems(tax, entries.map((e) => ({ sourceId: e.librarySourceId })), all);
9699
+ let html = '';
9700
+ for (const item of items) {
9701
+ if (item.kind === 'row') { const e = byId.get(item.row.sourceId); if (e) html += `<div class="company-cat-row" style="--kb-depth:${item.depth}">${companyEntryHtml(e, state)}</div>`; continue; }
9702
+ if (companyCatEdit && companyCatEdit.mode === 'rename' && companyCatEdit.id === item.id) { html += companyCatEditHtml(item.depth); continue; }
9703
+ const isU = item.kind === 'uncategorized';
9704
+ html += `<div class="company-cat${isU ? ' kb-uncat' : ''}" style="--kb-depth:${item.depth}"><span class="kb-cat-name">${escapeHtml(item.name)}</span><span class="kb-cat-count">(${item.count})</span>` +
9705
+ (isU ? '' : `<button type="button" class="kb-cat-more" data-company-cat-menu="${escapeAttr(item.id)}" aria-haspopup="menu" aria-label="More for ${escapeAttr(item.name)}" data-tip="Rename, add a subcategory or delete" data-command-id="shell.kb-category-menu#${escapeAttr(item.id)}" data-command-instance-label="${escapeAttr(item.name)}">⋯</button>`) + '</div>';
9706
+ if (companyCatEdit && companyCatEdit.mode === 'new' && companyCatEdit.parentId === item.id) html += companyCatEditHtml(item.depth + 1);
9707
+ }
9708
+ return head + topEdit + html;
9709
+ }
9710
+ async function companyCatPost(path, body, okMsg) {
9711
+ const state = companyKnowledgeState;
9712
+ if (companyKnowledgeBusy || !state || !state.available) return null;
9713
+ companyKnowledgeBusy = true; companySetError('');
9714
+ try {
9715
+ const res = await api(path, { method: 'POST', body: JSON.stringify({ expected: companyCatExpected(state), ...body }) });
9716
+ companyCatEdit = null;
9717
+ if (okMsg) showToast(okMsg, 'ok');
9718
+ return res;
9719
+ } catch (error) {
9720
+ const said = error && error.body && typeof error.body.error === 'string' && /^[A-Z]/.test(error.body.error) ? error.body.error : '';
9721
+ companySetError(said || 'FloLess could not change the company categories just now. Try again.');
9722
+ if (body.expected && error && error.body && error.body.code === 'knowledge-categories-changed') companyCatEdit = null;
9723
+ return null;
9724
+ } finally {
9725
+ companyKnowledgeBusy = false;
9726
+ try { await loadCompanyKnowledge(companyKnowledgeProjectId); } catch { /* the error line says what happened */ }
9727
+ renderCompanyKnowledge();
9728
+ }
9729
+ }
9730
+ /** What a company category change is checked against: the categories' revision and the company folder. */
9731
+ function companyCatExpected(state) {
9732
+ return { [KB_CAT_KEY]: String(companyTax(state).revision || 0), 'the company folder': `${state.companyId}|${state.path}` };
9733
+ }
9734
+ /** Open the company name box, remembering the categories it was opened on (see kbCatStartEdit). */
9735
+ function companyCatStartEdit(edit) {
9736
+ companyCatEdit = companyKnowledgeState ? { ...edit, expected: companyCatExpected(companyKnowledgeState) } : edit;
9737
+ renderCompanyKnowledge();
9738
+ const i = $companyKnowledgeList.querySelector('.company-cat-input');
9739
+ if (i) { i.focus(); i.select(); }
9740
+ }
9741
+ function companyCatSave() {
9742
+ const input = $companyKnowledgeList.querySelector('.company-cat-input');
9743
+ const e = companyCatEdit;
9744
+ if (!input || !e) return;
9745
+ const name = input.value.replace(/\s+/g, ' ').trim();
9746
+ if (!name) { companySetError('Give the category a name.'); input.focus(); return; }
9747
+ const pinned = e.expected ? { expected: e.expected } : {};
9748
+ if (e.mode === 'rename') companyCatPost('/api/company-knowledge/categories', { ops: [{ op: 'rename', id: e.id, name }], ...pinned }, `Renamed the company category to ${name}.`);
9749
+ else companyCatPost('/api/company-knowledge/categories', { ops: [{ op: 'create', name, parentId: e.parentId || null }], ...pinned }, `Created the company category ${name}.`);
9750
+ }
9751
+ function companyPop(anchor, html, label) {
9752
+ $companyKnowledgeList.querySelector('.company-pop')?.remove();
9753
+ const pop = document.createElement('div');
9754
+ pop.className = 'company-pop kb-ds-menu kb-cat-menu';
9755
+ pop.setAttribute('role', 'menu');
9756
+ pop.setAttribute('aria-label', label);
9757
+ pop.innerHTML = html;
9758
+ $companyKnowledgeList.appendChild(pop);
9759
+ const lr = $companyKnowledgeList.getBoundingClientRect(), br = anchor.getBoundingClientRect();
9760
+ // Below the button when it fits inside the dialog's visible area, else above it — never clipped by the scroll area.
9761
+ let clip = $companyKnowledgeList.parentElement;
9762
+ while (clip && clip !== document.body && !/(auto|scroll|hidden)/.test(getComputedStyle(clip).overflowY)) clip = clip.parentElement;
9763
+ const limit = Math.min(window.innerHeight, clip ? clip.getBoundingClientRect().bottom : window.innerHeight) - 8;
9764
+ const fits = br.bottom + 4 + pop.offsetHeight <= limit;
9765
+ pop.style.top = `${fits ? br.bottom - lr.top + $companyKnowledgeList.scrollTop + 4 : br.top - lr.top + $companyKnowledgeList.scrollTop - pop.offsetHeight - 4}px`;
9766
+ pop.style.left = `${Math.max(4, Math.min(br.right - lr.left - pop.offsetWidth, $companyKnowledgeList.clientWidth - pop.offsetWidth - 4))}px`;
9767
+ pop.dataset.back = anchor.dataset.companyCatMenu || anchor.dataset.companyMove || '';
9768
+ pop.querySelector('.kb-ds-mi')?.focus();
9769
+ return pop;
9770
+ }
9771
+ function companyMoveMenu(btn) {
9772
+ const state = companyKnowledgeState;
9773
+ const tax = companyTax(state);
9774
+ const id = btn.dataset.companyMove;
9775
+ const entry = state.sources.find((e) => e.librarySourceId === id);
9776
+ const now = kbcPlacement(tax, id);
9777
+ const items = kbcMenuChoices(tax, null).map((c) => `<button type="button" role="menuitemradio" aria-checked="${c.id === now ? 'true' : 'false'}" class="kb-ds-mi kb-move-mi" style="--kb-depth:${c.id ? c.depth + 1 : 0}" data-company-move-go="${escapeAttr(c.id || '')}" data-company-move-id="${escapeAttr(id)}" data-command-id="shell.kb-move-to-go#${escapeAttr(c.id || 'uncategorized')}" data-command-instance-label="${escapeAttr(c.name)}">${escapeHtml(c.name)}</button>`).join('');
9778
+ companyPop(btn, `<div class="kb-move-title">Move “${escapeHtml(entry ? entry.displayName : 'this reference')}” to</div>${items}`, 'Move shared reference');
9779
+ }
9780
+ function companyCatMenu(btn) {
9781
+ const id = btn.dataset.companyCatMenu;
9782
+ const cat = companyTax(companyKnowledgeState).categories.find((c) => c.id === id);
9783
+ const name = cat ? cat.name : 'this category';
9784
+ companyPop(btn, `<button type="button" role="menuitem" class="kb-ds-mi" data-company-cat-rename="${escapeAttr(id)}" data-command-id="shell.kb-category-rename#${escapeAttr(id)}" data-command-instance-label="${escapeAttr(name)}">Rename…</button>` +
9785
+ `<button type="button" role="menuitem" class="kb-ds-mi" data-company-cat-sub="${escapeAttr(id)}" data-command-id="shell.kb-category-new-sub#${escapeAttr(id)}" data-command-instance-label="${escapeAttr(name)}">New subcategory…</button>` +
9786
+ `<button type="button" role="menuitem" class="kb-ds-mi danger" data-company-cat-delete="${escapeAttr(id)}" data-command-id="shell.kb-category-delete#${escapeAttr(id)}" data-command-instance-label="${escapeAttr(name)}">Delete…</button>`, 'Company category');
9787
+ }
9788
+ function companyCatDelete(btn) {
9789
+ const id = btn.dataset.companyCatDelete;
9790
+ const state = companyKnowledgeState;
9791
+ const tax = companyTax(state);
9792
+ const cat = tax.categories.find((c) => c.id === id);
9793
+ if (!cat) return;
9794
+ const rows = state.sources.filter((e) => !e.removedAt).map((e) => ({ sourceId: e.librarySourceId }));
9795
+ const anchor = $companyKnowledgeList.querySelector(`[data-company-cat-menu="${CSS.escape(id)}"]`) || btn;
9796
+ const pop = companyPop(anchor, `<div class="hc-title">Delete “${escapeHtml(cat.name)}”?</div><div class="hc-body">${kbCatDeleteSentence(tax, rows, id).replace('No reference is deleted.', 'No shared reference is deleted.')}</div>` +
9797
+ '<div class="hc-act"><button type="button" class="hc-cancel kb-ds-mi" data-company-pop-close data-command-id="shell.kb-category-cancel">Cancel</button>' +
9798
+ `<button type="button" class="hc-go danger" data-company-cat-delete-go="${escapeAttr(id)}" data-command-id="shell.kb-category-delete#${escapeAttr(id)}" data-command-instance-label="${escapeAttr(cat.name)}">Delete category</button></div>`, `Delete ${cat.name}`);
9799
+ pop.setAttribute('role', 'dialog');
9800
+ pop.classList.remove('kb-ds-menu');
9801
+ pop.classList.add('hist-confirm');
9802
+ }
9803
+ /** The dialog's category clicks; true when handled. */
9804
+ function companyCatClick(event) {
9805
+ const t = event.target;
9806
+ if (t.closest('[data-company-cat-new]')) { companyCatStartEdit({ mode: 'new', parentId: null }); return true; }
9807
+ const menu = t.closest('[data-company-cat-menu]');
9808
+ if (menu) { companyCatMenu(menu); return true; }
9809
+ const move = t.closest('[data-company-move]');
9810
+ if (move) { companyMoveMenu(move); return true; }
9811
+ const rename = t.closest('[data-company-cat-rename]');
9812
+ if (rename) {
9813
+ const cat = companyTax(companyKnowledgeState).categories.find((c) => c.id === rename.dataset.companyCatRename);
9814
+ if (cat) companyCatStartEdit({ mode: 'rename', id: cat.id, name: cat.name });
9815
+ return true;
9816
+ }
9817
+ const sub = t.closest('[data-company-cat-sub]');
9818
+ if (sub) { companyCatStartEdit({ mode: 'new', parentId: sub.dataset.companyCatSub }); return true; }
9819
+ const del = t.closest('[data-company-cat-delete]');
9820
+ if (del) { companyCatDelete(del); return true; }
9821
+ const delGo = t.closest('[data-company-cat-delete-go]');
9822
+ if (delGo) { const cat = companyTax(companyKnowledgeState).categories.find((c) => c.id === delGo.dataset.companyCatDeleteGo); companyCatPost('/api/company-knowledge/categories', { ops: [{ op: 'delete', id: delGo.dataset.companyCatDeleteGo }] }, `Deleted the company category ${cat ? cat.name : ''}.`); return true; }
9823
+ const go = t.closest('[data-company-move-go]');
9824
+ if (go) {
9825
+ const to = go.dataset.companyMoveGo || null;
9826
+ const tax = companyTax(companyKnowledgeState);
9827
+ companyCatPost('/api/company-knowledge/place', { librarySourceIds: [go.dataset.companyMoveId], categoryId: to }, `Moved it to ${to ? kbcLabel(tax, to) : 'Uncategorized'}.`);
9828
+ return true;
9829
+ }
9830
+ if (t.closest('[data-company-cat-save]')) { companyCatSave(); return true; }
9831
+ if (t.closest('[data-company-cat-cancel]')) { companyCatEdit = null; renderCompanyKnowledge(); return true; }
9832
+ if (t.closest('[data-company-pop-close]')) { $companyKnowledgeList.querySelector('.company-pop')?.remove(); return true; }
9833
+ if (t.closest('[data-company-cat-reset]')) { companyCatPost('/api/company-knowledge/categories', { reset: true }, 'Started the company categories again. The old ones are kept aside.'); return true; }
9834
+ if (!t.closest('.company-pop')) $companyKnowledgeList.querySelector('.company-pop')?.remove();
9835
+ return false;
9836
+ }
9837
+
8827
9838
  function renderCompanyKnowledge() {
8828
9839
  const state = companyKnowledgeState;
8829
9840
  $companyKnowledgeFolder.innerHTML = companyFolderHtml(state);
@@ -8865,7 +9876,7 @@
8865
9876
  } else {
8866
9877
  const entries = state.sources.filter((entry) => !entry.removedAt);
8867
9878
  $companyKnowledgeList.innerHTML = entries.length
8868
- ? '<div class="company-section-label">Shared references</div>' + entries.map((entry) => companyEntryHtml(entry, state)).join('')
9879
+ ? companyListHtml(entries, state)
8869
9880
  : '<div class="company-empty">No company references yet. Preview a project file and choose “Promote to company…”.</div>';
8870
9881
  }
8871
9882
 
@@ -8960,25 +9971,28 @@
8960
9971
  const entry = state.sources.find((row) => row.librarySourceId === companyKnowledgePending.librarySourceId && !row.removedAt);
8961
9972
  const latest = entry && entry.versions[entry.versions.length - 1];
8962
9973
  if (!entry || !latest) throw new Error('That company version is no longer available.');
8963
- await api(`/api/company-knowledge/sources/${encodeURIComponent(entry.librarySourceId)}/versions/${encodeURIComponent(latest.versionId)}/accept`, {
9974
+ const res = await api(`/api/company-knowledge/sources/${encodeURIComponent(entry.librarySourceId)}/versions/${encodeURIComponent(latest.versionId)}/accept`, {
8964
9975
  method: 'POST', body: JSON.stringify({ projectId: companyKnowledgeProjectId }),
8965
9976
  });
8966
9977
  companyKnowledgePending = null;
8967
- showToast(`Added ${entry.displayName} v${entry.versions.length} to this project`, 'ok');
9978
+ // #2491 R6.9: where it went in this project's categories, and why.
9979
+ const placed = res && res.placement;
9980
+ showToast(`Added ${entry.displayName} v${entry.versions.length} to this project${placed && placed.categoryId ? `, in ${placed.where}` : ''}.${placed && placed.note && !placed.categoryId ? ` ${placed.note}` : ''}`, placed && placed.note && !placed.categoryId ? 'warn' : 'ok');
8968
9981
  } else if (companyKnowledgePending?.kind === 'remove') {
8969
9982
  const entry = state.sources.find((row) => row.librarySourceId === companyKnowledgePending.librarySourceId);
8970
9983
  await api(`/api/company-knowledge/sources/${encodeURIComponent(companyKnowledgePending.librarySourceId)}`, { method: 'DELETE' });
8971
9984
  companyKnowledgePending = null;
8972
9985
  showToast(`${entry ? entry.displayName : 'Company reference'} removed`, 'ok');
8973
9986
  } else if (companyKnowledgePromotion) {
8974
- await api('/api/company-knowledge/promote', {
9987
+ const promoted = await api('/api/company-knowledge/promote', {
8975
9988
  method: 'POST', body: JSON.stringify({
8976
9989
  projectId: companyKnowledgeProjectId,
8977
9990
  sourceId: companyKnowledgePromotion.sourceId,
8978
9991
  librarySourceId: $companyPromotionLineage.value || null,
8979
9992
  }),
8980
9993
  });
8981
- showToast('Company reference published.', 'ok');
9994
+ const placed = promoted && promoted.placement;
9995
+ showToast(`Company reference published${placed && placed.categoryId ? `, in ${placed.where}` : ''}.${placed && placed.note && !placed.categoryId ? ` ${placed.note}` : ''}`, placed && placed.note && !placed.categoryId ? 'warn' : 'ok');
8982
9996
  companyKnowledgePromotion = null;
8983
9997
  }
8984
9998
  await loadCompanyKnowledge(companyKnowledgeProjectId);
@@ -8989,6 +10003,7 @@
8989
10003
 
8990
10004
  if ($companyKnowledgeModal) {
8991
10005
  $companyKnowledgeModal.addEventListener('click', (event) => {
10006
+ if (companyCatClick(event)) return;
8992
10007
  const folder = event.target.closest('[data-company-folder-choose]');
8993
10008
  if (folder) { chooseCompanyFolder(); return; }
8994
10009
  const accept = event.target.closest('[data-company-stage-accept]');
@@ -9005,6 +10020,24 @@
9005
10020
  onBackdropDismiss($companyKnowledgeModal, () => closeCompanyKnowledge());
9006
10021
  document.addEventListener('keydown', (event) => {
9007
10022
  if (!$companyKnowledgeModal.classList.contains('show')) return;
10023
+ // #2491 R6.9: the name box and the menus answer their own keys first; Escape closes them, not the dialog.
10024
+ if (event.target.classList && event.target.classList.contains('company-cat-input')) {
10025
+ if (event.key === 'Enter') { event.preventDefault(); companyCatSave(); return; }
10026
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); companyCatEdit = null; renderCompanyKnowledge(); return; }
10027
+ }
10028
+ const pop = $companyKnowledgeList.querySelector('.company-pop');
10029
+ if (pop && event.key === 'Escape') {
10030
+ event.preventDefault(); event.stopPropagation();
10031
+ const back = pop.dataset.back; pop.remove();
10032
+ const el = back && ($companyKnowledgeList.querySelector(`[data-company-cat-menu="${CSS.escape(back)}"]`) || $companyKnowledgeList.querySelector(`[data-company-move="${CSS.escape(back)}"]`));
10033
+ if (el) el.focus();
10034
+ return;
10035
+ }
10036
+ if (pop && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) {
10037
+ const items = [...pop.querySelectorAll('.kb-ds-mi, .hc-go')];
10038
+ const at = items.indexOf(document.activeElement);
10039
+ if (at >= 0) { event.preventDefault(); items[(at + (event.key === 'ArrowDown' ? 1 : items.length - 1)) % items.length].focus(); return; }
10040
+ }
9008
10041
  if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeCompanyKnowledge(); return; }
9009
10042
  if (event.key !== 'Tab') return;
9010
10043
  const focusable = [...$companyKnowledgeModal.querySelectorAll('button:not([hidden]):not(:disabled), input:not([hidden]):not(:disabled), [tabindex="0"]')]
@@ -9017,7 +10050,7 @@
9017
10050
  }
9018
10051
 
9019
10052
  // ── Knowledge verbs (each captures `proj` — the user may switch projects mid-await) ──
9020
- async function kbUpload(fileList) {
10053
+ async function kbUpload(fileList, categoryId) {
9021
10054
  const proj = current;
9022
10055
  const files = Array.from(fileList || []);
9023
10056
  if (!proj || !files.length) return;
@@ -9037,9 +10070,16 @@
9037
10070
  // Per file (#2491): one file FloLess cannot take (an old .doc, an unsupported type) never sinks the rest of the
9038
10071
  // drop, and it is named with the reason in the server's plain words.
9039
10072
  const res = await api(kbUrl(proj.id, '/sources'), { method: 'POST',
9040
- body: JSON.stringify({ files: uploads, partial: true, ...(proj.uuid ? { expectedProjectUuid: proj.uuid } : {}) }) });
10073
+ body: JSON.stringify({ files: uploads, partial: true, ...(proj.uuid ? { expectedProjectUuid: proj.uuid } : {}),
10074
+ ...(categoryId !== undefined ? { categoryId } : {}) }) });
9041
10075
  if (current !== proj) return;
9042
10076
  const n = (res.sources || []).length;
10077
+ // #2491 R6.9: dropped on a category — say where they went, and why when it was not that category.
10078
+ if (categoryId !== undefined && n) {
10079
+ const where = categoryId ? kbcLabel(kbCats(knowledgeState), categoryId) : 'Uncategorized';
10080
+ if (res.placement === 'placed' || categoryId === null) kbAnnounce(`Added ${n} reference${n === 1 ? '' : 's'} to ${where}.`);
10081
+ else showToast(`Added ${n} reference${n === 1 ? '' : 's'}, in Uncategorized: ${res.placement === 'unknown-category' ? 'that category is no longer there' : res.placement === 'unavailable' ? 'your categories could not be read' : 'only you can file references into a category'}.`, 'warn');
10082
+ }
9043
10083
  const missed = (res.results || []).filter((r) => r && r.outcome !== 'added');
9044
10084
  if (!missed.length) showToast(`Added ${n} reference${n === 1 ? '' : 's'}`, 'ok');
9045
10085
  else {
@@ -9653,6 +10693,10 @@
9653
10693
  // One delegated listener for the whole pane — the column is re-rendered wholesale on every state
9654
10694
  // change, so per-render wiring would leak handlers.
9655
10695
  $wsKnowledge.addEventListener('click', (e) => {
10696
+ // #2491 R6.9: categories, selection and Move to… first — their menus share the design set's menu look.
10697
+ const rowAct = e.target.closest('[data-kb-row-act]');
10698
+ if (rowAct) { kbRowAct(rowAct); return; }
10699
+ if (kbCatClick(e)) return;
9656
10700
  if (e.target.closest('.kb-ds') || e.target.closest('.kb-ds-menu') || e.target.closest('[data-kb-ds-jump]') || e.target.closest('[data-kb-ds-fremove], [data-kb-ds-fwithdraw]')) {
9657
10701
  if (kbDsClick(e)) return;
9658
10702
  }
@@ -9723,6 +10767,8 @@
9723
10767
  return;
9724
10768
  }
9725
10769
  if (e.target.closest('[data-kb-fit]')) { const svg = kbGraphSvgEl(); if (svg) kbFitGraph(svg); return; }
10770
+ // The notes line (Stop, Load the rest) also shows above the first layout's spinner, outside .kb-graph.
10771
+ if (e.target.closest('.kb-graph, .kb-gnotes') && kbGraphClick(e)) return;
9726
10772
  // Open a graph node's page.
9727
10773
  const nodeEl = e.target.closest('[data-kb-node]');
9728
10774
  if (nodeEl) { setViewer({ mode: 'page', slug: nodeEl.getAttribute('data-kb-node') }); if (knowledgeState) paintKnowledge(knowledgeState); return; }
@@ -9813,6 +10859,7 @@
9813
10859
  // Graph nodes are keyboard-focusable (tabindex="0" role="button") but SVG <g> elements have no
9814
10860
  // native activation behaviour, so Enter/Space must be wired explicitly.
9815
10861
  $wsKnowledge.addEventListener('keydown', (e) => {
10862
+ if (kbCatKeydown(e)) return;
9816
10863
  // Home zooms the graph back to fit — but not while typing in the Adjust box (Home = line start there).
9817
10864
  if (e.key === 'Home' && !e.target.closest('input, textarea') && !e.target.isContentEditable) {
9818
10865
  const svg = kbGraphSvgEl();
@@ -9825,12 +10872,25 @@
9825
10872
  if (btn && btn.getAttribute('aria-disabled') !== 'true') kbAdjustSubmit();
9826
10873
  return;
9827
10874
  }
10875
+ const gnode = e.target.closest && e.target.closest('.kb-g-node[data-kb-gid]');
10876
+ if (gnode && kbGm && kbGm.view && ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
10877
+ e.preventDefault();
10878
+ const to = kbgNearest(kbGm.pos, gnode.dataset.kbGid, e.key, kbGm.view.nodes.map((x) => x.id));
10879
+ if (to) $wsKnowledge.querySelector(`.kb-g-node[data-kb-gid="${CSS.escape(to)}"]`)?.focus();
10880
+ return;
10881
+ }
10882
+ if (gnode && gnode.hasAttribute('data-kb-doc') && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); gnode.dispatchEvent(new MouseEvent('click', { bubbles: true })); return; }
9828
10883
  if (e.key !== 'Enter' && e.key !== ' ') return;
9829
10884
  const n = e.target.closest('[data-kb-node]');
9830
10885
  if (n) { e.preventDefault(); setViewer({ mode: 'page', slug: n.getAttribute('data-kb-node') }); if (knowledgeState) paintKnowledge(knowledgeState); }
9831
10886
  });
9832
10887
  // Live-enable the Adjust submit as the user types (the draft is DOM-owned; see kbSyncAdjustSubmit).
9833
10888
  $wsKnowledge.addEventListener('input', (e) => { if (e.target && e.target.id === 'kb-adjust-input') kbSyncAdjustSubmit(); });
10889
+ // #2491 R6.9: the map's search highlights matches (it hides nothing); hover and focus light a node's neighbours.
10890
+ $wsKnowledge.addEventListener('input', (e) => { if (e.target && e.target.classList && e.target.classList.contains('kb-gsearch')) { kbGo.search = e.target.value; kbGraphRender(true); } });
10891
+ $wsKnowledge.addEventListener('mouseover', (e) => { const n = e.target.closest && e.target.closest('.kb-g-node[data-kb-gid]'); if (n) kbGraphHighlight(n.dataset.kbGid); });
10892
+ $wsKnowledge.addEventListener('mouseout', (e) => { if (e.target.closest && e.target.closest('.kb-g-node') && !(e.relatedTarget && e.relatedTarget.closest && e.relatedTarget.closest('.kb-g-node'))) kbGraphHighlight(null); });
10893
+ $wsKnowledge.addEventListener('focusin', (e) => { const n = e.target.closest && e.target.closest('.kb-g-node[data-kb-gid]'); if (n) kbGraphHighlight(n.dataset.kbGid); });
9834
10894
  // #2491 R6.3: Replace file… picks exactly one file.
9835
10895
  const $wsKnowledgeReplace = document.getElementById('ws-knowledge-replace');
9836
10896
  if ($wsKnowledgeReplace) $wsKnowledgeReplace.addEventListener('change', () => {
@@ -9848,18 +10908,81 @@
9848
10908
  const cur = $wsKnowledge.querySelector('.kb-drop.drag-over');
9849
10909
  if (cur) { cur.classList.remove('drag-over'); kbInvalidateRefs(); }
9850
10910
  };
9851
- $wsKnowledge.addEventListener('dragover', (e) => {
10911
+ // #2491 R6.9: dragging references (the selection, or one row) onto a category.
10912
+ $wsKnowledge.addEventListener('dragstart', (e) => {
10913
+ const row = e.target.closest && e.target.closest('.kb-src[data-source-id]');
10914
+ if (!row || !e.dataTransfer || !kbCats(knowledgeState).categories.length || !kbCatUsable(knowledgeState)) { if (row && e.dataTransfer) e.preventDefault(); return; }
10915
+ const id = row.dataset.sourceId;
10916
+ const sel = kbSelFor(current, knowledgeState).selected;
10917
+ kbDragIds = sel.has(id) ? kbVisibleRows().filter((x) => sel.has(x)) : [id];
10918
+ e.dataTransfer.effectAllowed = 'move';
10919
+ e.dataTransfer.setData(KB_REFS_MIME, JSON.stringify(kbDragIds));
10920
+ const name = row.querySelector('.kb-fname')?.childNodes[0]?.textContent || 'reference';
10921
+ try { e.dataTransfer.setDragImage(kbDragChip(kbDragIds.length, name), 12, 12); } catch { /* the browser's own image */ }
10922
+ // No cache invalidation here: a repaint during the drag would destroy this row and the browser would cancel the drop.
10923
+ // The paint guard holds repaints while a drag is in flight; the end of the drag catches the column up.
10924
+ row.classList.add('dragging');
10925
+ });
10926
+ $wsKnowledge.addEventListener('dragend', () => {
10927
+ kbDragIds = null;
10928
+ kbClearDropHover();
10929
+ $wsKnowledge.querySelectorAll('.kb-src.dragging').forEach((el) => el.classList.remove('dragging'));
10930
+ kbInvalidateRefs();
10931
+ if (knowledgeState) paintKnowledge(knowledgeState);
10932
+ });
10933
+ // dragenter and dragover both answer: a drop target must accept the drag on entering it, not only while over it.
10934
+ const kbOnDragOver = (e) => {
9852
10935
  e.preventDefault();
10936
+ const cat = kbDropTargetOf(e);
10937
+ const types = e.dataTransfer ? [...e.dataTransfer.types] : [];
10938
+ const refs = types.includes(KB_REFS_MIME) && kbDragIds;
10939
+ const files = types.includes('Files');
10940
+ if (cat && (refs || files)) {
10941
+ if (e.dataTransfer) e.dataTransfer.dropEffect = refs ? 'move' : 'copy';
10942
+ if (!kbDragHover || kbDragHover.el !== cat) {
10943
+ kbClearDropHover();
10944
+ cat.classList.add('drop-target');
10945
+ const id = cat.dataset.kbDropCat;
10946
+ const label = id === 'uncategorized' ? 'Uncategorized' : kbcLabel(kbCats(knowledgeState), id);
10947
+ const n = refs ? kbDragIds.length : (e.dataTransfer.items ? e.dataTransfer.items.length : 0);
10948
+ cat.setAttribute('data-drop-label', refs ? `Move ${n === 1 ? 'here' : `${n} here`}` : `Add ${n || ''} file${n === 1 ? '' : 's'} to ${label}`.replace(' ', ' '));
10949
+ // A folded category opens when held over it.
10950
+ const timer = setTimeout(() => {
10951
+ // Opening the folded category is the one repaint allowed mid-drag: it changes only that category's children,
10952
+ // never the dragged row.
10953
+ if (id !== 'uncategorized' && kbCatCollapsedFor(current).has(id)) { kbCatCollapsed.delete(id); kbCatSaveCollapsed(); kbCatExpandInPlace(id); }
10954
+ }, 600);
10955
+ kbDragHover = { el: cat, timer };
10956
+ }
10957
+ return;
10958
+ }
10959
+ if (kbDragHover && !cat) kbClearDropHover();
10960
+ if (refs && e.dataTransfer) e.dataTransfer.dropEffect = 'none';
9853
10961
  const dz = e.target.closest('#kb-drop');
9854
10962
  const cur = $wsKnowledge.querySelector('.kb-drop.drag-over');
9855
10963
  if (cur && cur !== dz) cur.classList.remove('drag-over');
9856
10964
  if (dz && !dz.classList.contains('drag-over')) { dz.classList.add('drag-over'); kbInvalidateRefs(); }
9857
- });
10965
+ };
10966
+ $wsKnowledge.addEventListener('dragenter', kbOnDragOver);
10967
+ $wsKnowledge.addEventListener('dragover', kbOnDragOver);
9858
10968
  $wsKnowledge.addEventListener('dragleave', (e) => { if (!$wsKnowledge.contains(e.relatedTarget)) kbClearDrag(); });
9859
10969
  $wsKnowledge.addEventListener('drop', (e) => {
9860
10970
  e.preventDefault();
9861
10971
  kbClearDrag();
9862
- if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length) kbUpload(e.dataTransfer.files);
10972
+ const cat = kbDropTargetOf(e);
10973
+ kbClearDropHover();
10974
+ const to = cat ? (cat.dataset.kbDropCat === 'uncategorized' ? null : cat.dataset.kbDropCat) : undefined;
10975
+ const raw = e.dataTransfer ? e.dataTransfer.getData(KB_REFS_MIME) : '';
10976
+ kbInvalidateRefs();
10977
+ if (raw) {
10978
+ kbDragIds = null;
10979
+ if (to === undefined) return; // dropped beside a category: nothing moves
10980
+ let ids = [];
10981
+ try { ids = JSON.parse(raw); } catch { ids = []; }
10982
+ if (Array.isArray(ids) && ids.length) kbPlace(ids.filter((x) => typeof x === 'string'), to);
10983
+ return;
10984
+ }
10985
+ if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length) kbUpload(e.dataTransfer.files, to === undefined ? undefined : to);
9863
10986
  });
9864
10987
 
9865
10988
  // ── Exports step ──────────────────────────────────────────────────────────────
@@ -12685,6 +13808,7 @@
12685
13808
  async function attachRevision(files) {
12686
13809
  const proj = current; // capture — the user may switch projects during the async file reads / POST
12687
13810
  if (!proj || !files.length) return;
13811
+ if (!validateSteelDrawingFiles(wsDescOf(proj) === WORKSPACE_APPS['steel-model'] ? 'steel-model' : '', files)) return;
12688
13812
  const projectGeneration = revisionOwnerGen;
12689
13813
  const attachGeneration = ++revisionAttachGen;
12690
13814
  const ownsAttach = () => current === proj
@@ -12700,7 +13824,7 @@
12700
13824
  res = await api(`/api/projects/${encodeURIComponent(proj.id)}/revision-requests`, {
12701
13825
  method: 'POST', body: JSON.stringify({ appId: proj.app, snapshots }),
12702
13826
  });
12703
- } catch (err) { if (ownsAttach()) showToast('We couldn’t attach that file because FloLess could not save it. Try again.', 'warn'); return; }
13827
+ } catch (err) { if (ownsAttach()) showToast(err?.body?.code === 'steel-pdf-required' ? err.body.error : 'We couldn’t attach that file because FloLess could not save it. Try again.', 'warn'); return; }
12704
13828
  const req = res && res.request;
12705
13829
  if (!ownsAttach()) {
12706
13830
  if (bridge.loadRequests) bridge.loadRequests().catch(() => {});
@@ -12743,7 +13867,7 @@
12743
13867
  }
12744
13868
 
12745
13869
  document.getElementById('ws-attach-revision').addEventListener('click', async () => {
12746
- const files = await pickDrawingFiles($revisionFile);
13870
+ const files = await pickDrawingFiles($revisionFile, wsDescOf(current) === WORKSPACE_APPS['steel-model'] ? 'steel-model' : '');
12747
13871
  if (files.length) attachRevision(files);
12748
13872
  });
12749
13873
 
@@ -16796,7 +17920,11 @@
16796
17920
  };
16797
17921
  async function openConnection(target) {
16798
17922
  const validId = (id) => typeof id === 'string' && !!id && id.length <= 200;
16799
- if (!target || !validId(target.projectId) || !validId(target.jointId)) throw connectionError('That connection could not be opened. Open its project from Workspaces.');
17923
+ // #2471: or one member an AI Chat answer cited, with the project identity it was cited in (checked at handover).
17924
+ const member = !!target && !validId(target.jointId) && validId(target.memberId);
17925
+ const thing = member ? 'member' : 'connection';
17926
+ const again = member ? 'Show in the model' : 'Open in the model';
17927
+ if (!target || !validId(target.projectId) || !(validId(target.jointId) || member)) throw connectionError(`That ${thing} could not be opened. Open its project from Workspaces.`);
16800
17928
  const mine = { id: `connection-${++connectionRequestSeq}`, page: null };
16801
17929
  withdrawConnectionRequest(connectionRequest);
16802
17930
  connectionRequest = mine;
@@ -16804,8 +17932,8 @@
16804
17932
  // Once this call has ended, for any reason, a project change it started gives way before it lands.
16805
17933
  let ended = false;
16806
17934
  const stillWanted = () => !ended && !superseded();
16807
- const stayedOutside = () => connectionError('You stayed where you were, so the connection was not shown. Open the project from Workspaces, then press Open in the model again.');
16808
- const leftWorkspaces = () => connectionError('You left Workspaces, so the connection was not shown. Open the project from Workspaces, then press Open in the model again.');
17935
+ const stayedOutside = () => connectionError(`You stayed where you were, so the ${thing} was not shown. Open the project from Workspaces, then press ${again} again.`);
17936
+ const leftWorkspaces = () => connectionError(`You left Workspaces, so the ${thing} was not shown. Open the project from Workspaces, then press ${again} again.`);
16809
17937
  const pause = () => new Promise((resolve) => setTimeout(resolve, 100));
16810
17938
  /**
16811
17939
  * Wait for a step of getting there, watched: a later click ends it at once. `bounded` adds the deadline,
@@ -16822,21 +17950,24 @@
16822
17950
  await Promise.race([finished, pause()]);
16823
17951
  if (done) { if (done.error) throw done.error; return done.value; }
16824
17952
  if (superseded()) return { superseded: true };
16825
- if (Date.now() >= bound) throw connectionError('The project did not open in time, so the connection was not shown. Open it from Workspaces, then press Open in the model again.');
17953
+ if (Date.now() >= bound) throw connectionError(`The project did not open in time, so the ${thing} was not shown. Open it from Workspaces, then press ${again} again.`);
16826
17954
  }
16827
17955
  };
17956
+ // A project removed and made again under the same id is not the one the answer cited.
17957
+ const citedElsewhere = () => validId(target.projectUuid) && String(current?.uuid || '').toLowerCase() !== target.projectUuid.toLowerCase();
17958
+ const citedGone = () => connectionError(`This project is no longer the one the answer cited, so the ${thing} was not shown.`);
16828
17959
  let until = Infinity;
16829
17960
  // Everything that ends this call's wait without the editor's answer.
16830
17961
  const interrupted = () => {
16831
17962
  if (superseded()) return { superseded: true };
16832
17963
  if (mode !== 'workspaces') throw leftWorkspaces();
16833
- if (current?.id !== target.projectId) throw connectionError('You moved to another project, so the connection was not shown.');
17964
+ if (current?.id !== target.projectId) throw connectionError(`You moved to another project, so the ${thing} was not shown.`);
16834
17965
  // The project's stages kept the Model step locked, or the person went to another step: the step's
16835
17966
  // own message says why, and there is nothing to wait for.
16836
17967
  if (currentStep !== 'model' && !(pendingPresenceStep && pendingPresenceStep.step === 'model')) {
16837
- throw connectionError('The Model step is not open, so the connection was not shown. Open the Model step, then press Open in the model again.');
17968
+ throw connectionError(`The Model step is not open, so the ${thing} was not shown. Open the Model step, then press ${again} again.`);
16838
17969
  }
16839
- if (Date.now() >= until) throw connectionError('The model did not open in time, so the connection was not shown. Open the Model step, then press Open in the model again.');
17970
+ if (Date.now() >= until) throw connectionError(`The model did not open in time, so the ${thing} was not shown. Open the Model step, then press ${again} again.`);
16840
17971
  return null;
16841
17972
  };
16842
17973
  try {
@@ -16848,16 +17979,16 @@
16848
17979
  if (opened?.superseded || superseded()) return { superseded: true };
16849
17980
  // openProject answers "stayed" for several causes (the person chose to stay, the project's folder is
16850
17981
  // not available and its dialog is open, another navigation took over): say only what is certain.
16851
- if (opened === STAYED_IN_PROJECT) throw connectionError('That project did not open, so the connection was not shown. Open it from Workspaces to see why, then press Open in the model again.');
17982
+ if (opened === STAYED_IN_PROJECT) throw connectionError(`That project did not open, so the ${thing} was not shown. Open it from Workspaces to see why, then press ${again} again.`);
16852
17983
  if (current?.id !== target.projectId) throw connectionError('That project could not be opened. Open it from Workspaces.');
16853
17984
  } else if (currentStep !== 'model') {
16854
17985
  setStep('model');
16855
17986
  }
16856
- if (!frames.model.dataset.want) throw connectionError('This project has no model editor to show the connection in.');
17987
+ if (!frames.model.dataset.want) throw connectionError(`This project has no model editor to show the ${thing} in.`);
16857
17988
  // The editor's deadline starts once the person is in the project.
16858
17989
  until = Date.now() + CONNECTION_FRAME_WAIT_MS;
16859
17990
  let answer = null, settled = null, page = null, doc = null;
16860
- const notTaken = 'The model could not take the request. Press Open in the model again.';
17991
+ const notTaken = `The model could not take the request. Press ${again} again.`;
16861
17992
  for (;;) {
16862
17993
  // An answer already in is the editor's account of what it did: once it has selected the connection,
16863
17994
  // leaving the step or the deadline passing does not make that untrue. Only a later click, another
@@ -16866,8 +17997,8 @@
16866
17997
  if (superseded()) return { superseded: true };
16867
17998
  // The Model step may have been left after the selection, but not Workspaces: hidden, it shows nothing.
16868
17999
  if (mode !== 'workspaces') throw leftWorkspaces();
16869
- if (current?.id !== target.projectId) throw connectionError('You moved to another project, so the connection was not shown.');
16870
- if (frames.model.contentWindow !== page || page.document !== doc) throw connectionError('The model reloaded, so the connection was not shown. Press Open in the model again.');
18000
+ if (current?.id !== target.projectId) throw connectionError(`You moved to another project, so the ${thing} was not shown.`);
18001
+ if (frames.model.contentWindow !== page || page.document !== doc) throw connectionError(`The model reloaded, so the ${thing} was not shown. Press ${again} again.`);
16871
18002
  const outcome = settled.outcome;
16872
18003
  return outcome && typeof outcome === 'object' ? { ...outcome } : { ok: false, said: notTaken };
16873
18004
  }
@@ -16877,9 +18008,10 @@
16877
18008
  if (!answer) {
16878
18009
  const state = child && child.flolessEditorState;
16879
18010
  if (state && state.project === target.projectId && typeof child.flolessEditorFocus === 'function') {
18011
+ if (citedElsewhere()) throw citedGone();
16880
18012
  // The frame's window survives a reload; its DOCUMENT does not. That is what tells a reload apart.
16881
18013
  page = child; doc = child.document;
16882
- answer = child.flolessEditorFocus({ jointId: target.jointId, requestId: mine.id,
18014
+ answer = child.flolessEditorFocus(member ? { memberId: target.memberId, requestId: mine.id } : { jointId: target.jointId, requestId: mine.id,
16883
18015
  // #2450: the readiness card's "Raise an RFI" also opens the editor's review dialog for it.
16884
18016
  ...(target.raiseRfi === true ? { raiseRfi: true } : {}), ...(validId(target.checkId) ? { checkId: target.checkId } : {}) });
16885
18017
  if (!answer || typeof answer.then !== 'function') return { ok: false, said: notTaken };
@@ -16890,7 +18022,7 @@
16890
18022
  });
16891
18023
  }
16892
18024
  } else if (child !== page || child.document !== doc) {
16893
- throw connectionError('The model reloaded, so the connection was not shown. Press Open in the model again.');
18025
+ throw connectionError(`The model reloaded, so the ${thing} was not shown. Press ${again} again.`);
16894
18026
  }
16895
18027
  await pause();
16896
18028
  }
@@ -17017,7 +18149,8 @@
17017
18149
  if (!drop || current?.id !== projectId) return 'The project’s Knowledge step did not open. Open the project and use Drop references there.';
17018
18150
  if (unverified || (navigator.userActivation && !navigator.userActivation.isActive)) {
17019
18151
  kbDropAttention(drop);
17020
- return 'Choose files is ready in this project’s Knowledge step. Press it to pick the files.';
18152
+ // #2427: nothing failed — the last click is the person's, so the card waits for them instead of reading red.
18153
+ return { handedOver: 'Choose files is ready in this project’s Knowledge step. Press it to pick the files.', focus: drop };
17021
18154
  }
17022
18155
  $wsKnowledgeFile.click();
17023
18156
  return '';
@@ -17053,7 +18186,7 @@
17053
18186
  // The confirm click may be too long ago by now; the Replace control is then left in front for them.
17054
18187
  if (!tekla && navigator.userActivation && !navigator.userActivation.isActive) {
17055
18188
  $revitReplace.scrollIntoView({ block: 'center' }); $revitReplace.focus();
17056
- return `${$revitReplace.textContent || 'Replace RVT…'} is ready on this project. Press it to choose the file.`;
18189
+ return { handedOver: `${$revitReplace.textContent || 'Replace RVT…'} is ready on this project. Press it to choose the file.`, focus: $revitReplace };
17057
18190
  }
17058
18191
  $revitReplace.click();
17059
18192
  return '';