@floless/app 0.157.0 → 0.159.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.
Files changed (44) hide show
  1. package/cli-actions.mjs +7 -0
  2. package/dist/floless-server.cjs +188306 -155284
  3. package/dist/schemas/drawing-check.profile.v1.schema.json +33 -1
  4. package/dist/skills/floless-app-actions/SKILL.md +26 -5
  5. package/dist/skills/floless-app-bridge/SKILL.md +5 -3
  6. package/dist/skills/floless-app-knowledge/SKILL.md +14 -1
  7. package/dist/skills/floless-app-knowledge/references/schema.md +4 -1
  8. package/dist/skills/floless-app-onboarding/SKILL.md +67 -4
  9. package/dist/skills/floless-app-onboarding/references/floless-surfaces.md +7 -4
  10. package/dist/skills/floless-app-queue/SKILL.md +3 -1
  11. package/dist/skills/floless-app-steel-model/SKILL.md +41 -1
  12. package/dist/skills/floless-app-steel-takeoff/SKILL.md +71 -1
  13. package/dist/skills/floless-app-workflows/SKILL.md +6 -3
  14. package/dist/web/agents.js +12 -5
  15. package/dist/web/app.css +229 -27
  16. package/dist/web/app.js +6 -0
  17. package/dist/web/aware.js +275 -64
  18. package/dist/web/chat.css +60 -22
  19. package/dist/web/chat.js +396 -59
  20. package/dist/web/commands-shell.js +546 -11
  21. package/dist/web/commands-steel.js +1 -0
  22. package/dist/web/drawing-check-editor.html +10 -0
  23. package/dist/web/drawing-check-editor.js +44 -0
  24. package/dist/web/guide.js +4 -2
  25. package/dist/web/index.html +66 -12
  26. package/dist/web/instructor.js +21 -9
  27. package/dist/web/kb-categories.js +351 -0
  28. package/dist/web/kb-graph-worker.js +73 -0
  29. package/dist/web/pages.js +185 -19
  30. package/dist/web/project-access.js +67 -8
  31. package/dist/web/project-modules.js +474 -0
  32. package/dist/web/project-workflows.js +274 -0
  33. package/dist/web/run-page-view.js +353 -0
  34. package/dist/web/steel-3d-core.js +46 -0
  35. package/dist/web/steel-3d-view.js +8 -38
  36. package/dist/web/steel-editor.html +225 -43
  37. package/dist/web/tab-signal.js +323 -0
  38. package/dist/web/terminal-requests.js +48 -7
  39. package/dist/web/workspace-root-recovery.js +119 -0
  40. package/dist/web/workspaces.js +1597 -220
  41. package/launch-starting-page.mjs +184 -0
  42. package/launch.mjs +214 -73
  43. package/package.json +7 -1
  44. package/dist/web/report-files.js +0 -50
@@ -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,21 +751,40 @@
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
  ],
760
+ // A paid module (floless.io sells it, 2026-10-22). Unlike the parsers it is NOT serverAuthorizedOnly: its
761
+ // workflow is a core default every install carries, so the card is there by default and the server adds
762
+ // a capability row only when the signed lease does not include it, which turns the card into this lock.
763
+ moduleGated: true,
764
+ accessCopy: {
765
+ 'access-required': {
766
+ status: 'Not in your plan',
767
+ body: 'Steel Model is not included in this account’s plan. Add it on floless.io, or sign in with an account that has it. Steel models already on this computer stay viewable.',
768
+ action: 'See plans', aria: 'Steel Model is not in your plan — see plans on floless.io (opens in a new tab)',
769
+ },
770
+ 'account-selection-required': {
771
+ status: 'Choose an account', body: 'Choose which FloLess account to use for Steel Model.',
772
+ action: 'Choose account', aria: 'Choose a FloLess account for Steel Model',
773
+ },
774
+ 'check-unavailable': {
775
+ status: 'Couldn’t check access', body: 'FloLess couldn’t verify Steel Model access. Existing projects were not changed.',
776
+ action: 'Check again', aria: 'Steel Model access check unavailable — check again',
777
+ },
778
+ },
752
779
  editor: '/steel-editor.html',
753
780
  filter: '/steel-filter.html',
754
781
  steps: [
755
782
  { key: 'knowledge', label: 'Knowledge' }, // per-project KB — the job's context, consulted by everything
756
783
  { key: 'drawings', label: 'Drawing Filter' },
757
784
  { key: 'model', label: 'Model' },
785
+ { key: 'pages', label: 'Pages' }, // #2262: stored, versioned HTML Pages; #2568: just before Exports (both are output)
758
786
  { key: 'exports', label: 'Exports' },
759
787
  { key: 'history', label: 'History' },
760
- { key: 'pages', label: 'Pages' }, // #2262: stored, versioned HTML Pages (every app)
761
788
  ],
762
789
  diff: true, // steel semantic diff expander
763
790
  exports: [
@@ -806,9 +833,9 @@
806
833
  { key: 'knowledge', label: 'Knowledge' }, // KB is project-level — every workspace app gets it
807
834
  { key: 'drawings', label: 'Source' }, // reuse the 'drawings' frame slot; label "Source"
808
835
  { key: 'model', label: 'Traced' }, // reuse the 'model' frame slot; label "Traced"
836
+ { key: 'pages', label: 'Pages' }, // #2262: stored, versioned HTML Pages; #2568: just before Exports (both are output)
809
837
  { key: 'exports', label: 'Exports' },
810
838
  { key: 'history', label: 'History' },
811
- { key: 'pages', label: 'Pages' }, // #2262: stored, versioned HTML Pages (every app)
812
839
  ],
813
840
  diff: false,
814
841
  exports: [
@@ -986,6 +1013,8 @@
986
1013
  steps: [
987
1014
  { key: 'knowledge', label: 'Knowledge' },
988
1015
  { key: 'pages', label: 'Pages' },
1016
+ { key: 'workflows', label: 'Workflows' }, // #2470 R6.2: the workflows this project owns
1017
+ { key: 'modules', label: 'Modules' }, // #2470 R6.7: the module projects linked to this one
989
1018
  ],
990
1019
  diff: false,
991
1020
  exports: [],
@@ -1084,7 +1113,8 @@
1084
1113
  for (const capability of capabilities || []) {
1085
1114
  if (!capability || typeof capability.templateId !== 'string'
1086
1115
  || capability.appId !== capability.templateId
1087
- || WORKSPACE_APPS[capability.templateId]?.serverAuthorizedOnly !== true) continue;
1116
+ || (WORKSPACE_APPS[capability.templateId]?.serverAuthorizedOnly !== true
1117
+ && WORKSPACE_APPS[capability.templateId]?.moduleGated !== true)) continue;
1088
1118
  const known = ['ready', 'access-required', 'account-selection-required', 'setup-provisioning', 'setup-unavailable', 'setup-integrity-failure', 'setup-repair-required', 'check-unavailable'];
1089
1119
  capabilityByRoot.set(capability.templateId, known.includes(capability.status) ? capability.status : 'check-unavailable');
1090
1120
  if (capability.setupChoice === true && ['tekla-parser', 'revit-model'].includes(capability.templateId)) setupChoiceByRoot.add(capability.templateId);
@@ -1093,6 +1123,9 @@
1093
1123
  }
1094
1124
  // A capability row exists only after the server positively found the canonical module. Add
1095
1125
  // its presentation entry even when authorization intentionally filtered it out of `apps`.
1126
+ // A module-gated card's `ready` row says the account may use it, not that its workflow is installed:
1127
+ // that stays the core-defaults check below, so a missing workflow still reads "Needs setup".
1128
+ if (WORKSPACE_APPS[capability.templateId]?.moduleGated === true && capabilityByRoot.get(capability.templateId) === 'ready') continue;
1096
1129
  if (!byRoot.has(capability.templateId)) byRoot.set(capability.templateId, [capability.templateId]);
1097
1130
  }
1098
1131
  // Keep the two built-in drawing actions visible when only one workflow is installed.
@@ -1562,15 +1595,16 @@
1562
1595
  $workflowTab.removeAttribute('aria-disabled');
1563
1596
  $workflowTab.removeAttribute('data-blocked-reason');
1564
1597
  }
1598
+ // 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.
1599
+ // Taken on the first call, whichever way it goes: leaving for Workspaces calls this with false before Workflows
1600
+ // has ever opened, and taking them only on true then wiped the icon for good.
1601
+ $workflowTab.idleNodes ??= [...$workflowTab.childNodes];
1565
1602
  if (opening) {
1566
1603
  $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
1604
  $workflowTab.innerHTML = '<span class="rtn-spinner" aria-hidden="true"></span><span>Opening Workflows…</span>';
1570
1605
  } else {
1571
1606
  $workflowTab.removeAttribute('aria-label');
1572
- $workflowTab.textContent = 'Workflows';
1573
- if ($workflowTab.idleIcon) $workflowTab.prepend($workflowTab.idleIcon);
1607
+ $workflowTab.replaceChildren(...$workflowTab.idleNodes);
1574
1608
  }
1575
1609
  }
1576
1610
  async function setMode(m) {
@@ -1778,6 +1812,9 @@
1778
1812
  closeProjMenu();
1779
1813
  if (deferIfBusy()) return;
1780
1814
  renderLanding();
1815
+ // #2470 R6.7: an open Add a module sheet shows the same cards; it repaints too. A direct optional call, not a DOM
1816
+ // event: the harnesses that lift this function have no CustomEvent.
1817
+ globalThis.flolessProjectModules?.cardsChanged?.();
1781
1818
  }
1782
1819
  }
1783
1820
 
@@ -2441,7 +2478,8 @@
2441
2478
  `<span class="ws-seed-action">Why unavailable →</span>` +
2442
2479
  `</button>`;
2443
2480
  }
2444
- if (descriptor?.serverAuthorizedOnly === true && entry.capabilityStatus && entry.capabilityStatus !== 'ready') {
2481
+ if ((descriptor?.serverAuthorizedOnly === true || descriptor?.moduleGated === true)
2482
+ && entry.capabilityStatus && entry.capabilityStatus !== 'ready') {
2445
2483
  const revitStates = {
2446
2484
  'access-required': {
2447
2485
  status: 'Access required',
@@ -2497,6 +2535,10 @@
2497
2535
  const drawingCheckCommand = ['setup-unavailable', 'setup-integrity-failure'].includes(entry.capabilityStatus)
2498
2536
  ? 'data-command-id="shell.drawing-check-retry-setup"'
2499
2537
  : 'data-command-id="shell.drawing-check-view-access"';
2538
+ // Steel Model is bought, not enabled by an owner: its lock leads to the plans page.
2539
+ const steelModelCommand = entry.capabilityStatus === 'access-required'
2540
+ ? 'data-command-id="shell.steel-model-see-plans"'
2541
+ : 'data-command-id="shell.steel-model-view-access"';
2500
2542
  const remedyState = escapeAttr(entry.capabilityStatus || 'check-unavailable');
2501
2543
  return `<${actionable ? 'button type="button"' : 'div'} class="ws-seed ws-seed-remedy" ` +
2502
2544
  `aria-label="${escapeAttr(state.aria)}" aria-describedby="${escapeAttr(descriptionId)}" ` +
@@ -2507,6 +2549,8 @@
2507
2549
  ? `${revitCommand} data-revit-remedy="${remedyState}"`
2508
2550
  : entry.templateId === 'drawing-check'
2509
2551
  ? `${drawingCheckCommand} data-module-remedy="drawing-check" data-module-remedy-state="${remedyState}"`
2552
+ : entry.templateId === 'steel-model'
2553
+ ? `${steelModelCommand} data-module-remedy="steel-model" data-module-remedy-state="${remedyState}"`
2510
2554
  : `${teklaCommand} data-module-remedy="tekla-parser" data-module-remedy-state="${remedyState}"` : '') + `>` +
2511
2555
  seedIcon('!') +
2512
2556
  `<span class="ws-seed-headline">${escapeHtml(descriptor.displayName)}</span>` +
@@ -3010,45 +3054,37 @@
3010
3054
  window.dispatchEvent(new CustomEvent('floless:open-drawing-check-access', { detail: { state } }));
3011
3055
  }
3012
3056
 
3013
- $landing.addEventListener('click', async (e) => {
3014
- const registrationReview = e.target.closest('[data-project-registration-review]');
3015
- if (registrationReview) { window.flolessProjectReconciliation?.openRegistration(registrationReview.dataset.projectRegistrationReview); return; }
3016
- const groupToggle = e.target.closest('[data-project-group-toggle]');
3017
- if (groupToggle) {
3018
- const expanded = groupToggle.getAttribute('aria-expanded') !== 'true';
3019
- const key = groupToggle.dataset.projectGroupToggle;
3020
- if (landingQuery.trim()) projectGroupSearchOverrides.set(key, expanded);
3021
- else saveProjectGroupExpanded(key, expanded);
3022
- showProjectGroup(groupToggle.closest('.ws-project-section'), expanded);
3023
- if (expanded) tipTruncatedNames();
3024
- e.stopPropagation();
3025
- return;
3026
- }
3027
- const kebab = e.target.closest('[data-kebab]');
3028
- if (kebab) { e.stopPropagation(); openProjMenu(kebab.dataset.kebab, kebab); return; }
3029
- // Before the card's own [data-open] branch below, exactly like the kebab: the thumbnail is the one
3030
- // region of the card that does something other than open the project.
3031
- const thumb = e.target.closest('[data-thumb]');
3032
- if (thumb) { e.stopPropagation(); openThumbView(thumb.dataset.thumb, thumb); return; }
3033
- const restore = e.target.closest('[data-restore]');
3034
- if (restore) { e.stopPropagation(); unarchiveProject(restore.dataset.restore); return; }
3035
- const del = e.target.closest('[data-delete-archived]');
3036
- if (del) { e.stopPropagation(); deleteArchivedProject(del.dataset.deleteArchived); return; }
3037
- if (e.target.closest('#ws-retry-projects')) { e.stopPropagation(); retryProjects(); return; }
3038
- // Clearing empties the message the button sits in, so focus goes back to the search box.
3039
- if (e.target.closest('#ws-search-clear')) { setLandingQuery(''); $landing.querySelector('#ws-landing-search')?.focus(); return; }
3040
- if (e.target.closest('#ws-workspace-folder')) {
3041
- e.stopPropagation();
3042
- if (window.flolessWorkspaceRoot) window.flolessWorkspaceRoot.open();
3057
+ /**
3058
+ * The locked Steel Model card's remedies. Not in the plan: the floless.io plans page, where the person adds
3059
+ * it. Account choice and access checks go to the shell's account gate under Steel Model's name.
3060
+ */
3061
+ function runSteelModelRemedy(remedy) {
3062
+ const state = remedy.dataset.moduleRemedyState;
3063
+ if (state === 'access-required') {
3064
+ window.open('https://floless.io/pricing', '_blank', 'noopener'); // the same plans page pages.js links
3043
3065
  return;
3044
3066
  }
3045
- if (e.target.closest('#ws-import-project')) { importProject(); return; }
3046
- const parserSetup = e.target.closest('[data-parser-setup]');
3067
+ window.dispatchEvent(new CustomEvent('floless:open-steel-model-access', { detail: { state } }));
3068
+ }
3069
+
3070
+
3071
+ // ── create cards, shared by the landing and Add a module (#2470 R6.7) ────────────────────────────────────────
3072
+ // A create card behaves the same wherever it is shown: the Workspaces landing, or a General project's Add a module
3073
+ // sheet. There, `linkFrom` names the General project the new one is linked to (spec §6.2); the landing passes none.
3074
+
3075
+ /** The remedy a click on a create card asks for (set-up, access, a report), as a thunk; null when it was not on one. */
3076
+ function createCardRemedy(target) {
3077
+ if (!target?.closest?.('[data-parser-setup], [data-revit-remedy], [data-module-remedy]')) return null;
3078
+ return () => runCreateCardRemedy(target);
3079
+ }
3080
+
3081
+ async function runCreateCardRemedy(target) {
3082
+ const parserSetup = target.closest('[data-parser-setup]');
3047
3083
  if (parserSetup) {
3048
3084
  window.flolessParserSetupRecovery?.open(parserSetup.dataset.parserSetup, parserSetup);
3049
3085
  return;
3050
3086
  }
3051
- const revitRemedy = e.target.closest('[data-revit-remedy]');
3087
+ const revitRemedy = target.closest('[data-revit-remedy]');
3052
3088
  if (revitRemedy) {
3053
3089
  if (revitRemedy.dataset.revitRemedy === 'report-issue') {
3054
3090
  window.dispatchEvent(new CustomEvent('floless:report-revit-setup-issue', {
@@ -3141,11 +3177,15 @@
3141
3177
  }));
3142
3178
  return;
3143
3179
  }
3144
- const moduleRemedy = e.target.closest('[data-module-remedy]');
3180
+ const moduleRemedy = target.closest('[data-module-remedy]');
3145
3181
  if (moduleRemedy && moduleRemedy.dataset.moduleRemedy === 'drawing-check') {
3146
3182
  await runDrawingCheckRemedy(moduleRemedy);
3147
3183
  return;
3148
3184
  }
3185
+ if (moduleRemedy && moduleRemedy.dataset.moduleRemedy === 'steel-model') {
3186
+ runSteelModelRemedy(moduleRemedy);
3187
+ return;
3188
+ }
3149
3189
  if (moduleRemedy) {
3150
3190
  if (moduleRemedy.dataset.moduleRemedyState === 'setup-provisioning') return;
3151
3191
  if (moduleRemedy.dataset.moduleRemedyState === 'setup-integrity-failure') {
@@ -3230,52 +3270,95 @@
3230
3270
  }));
3231
3271
  return;
3232
3272
  }
3273
+ }
3274
+
3275
+ /**
3276
+ * Start a create card's own flow. Called straight from the click, with nothing awaited first, so the native file
3277
+ * picker it may open still counts as the person's own gesture.
3278
+ */
3279
+ async function activateSeedCard(seed, linkFrom = null) {
3280
+ // Two ids, and they are not interchangeable: create on the LIVE app (`seed-app`), but look the
3281
+ // descriptor up by its lineage ROOT (`seed-template`) — after a rename the live id answers to no
3282
+ // descriptor, and the built-in id answers to no installed app.
3283
+ const appId = seed.dataset.seedApp;
3284
+ const templateId = seed.dataset.seedTemplate || appId;
3285
+ if (!WORKSPACE_APPS[templateId]) return;
3286
+ // Each create kind has its own branch below. The 'drawing' check stays a check rather than an
3287
+ // assumption: a future kind must declare its own branch, not silently inherit the file picker.
3288
+ if (seed.dataset.seedAction === 'drawing') {
3289
+ if (workspaceWorkflowKnownMissing(appId)) {
3290
+ showToast(missingWorkspaceWorkflowMessage(templateId), 'warn');
3291
+ return;
3292
+ }
3293
+ let files;
3294
+ try { files = await pickDrawingFiles($seedFile, templateId); } // keep native picker in the click activation
3295
+ catch { showToast('Couldn’t open the drawing picker. Try again.', 'warn'); return; }
3296
+ if (!files.length) return;
3297
+ if (workspaceWorkflowKnownMissing(appId)) {
3298
+ showToast(missingWorkspaceWorkflowMessage(templateId), 'warn');
3299
+ return;
3300
+ }
3301
+ createFromDrawing(appId, templateId, files, { linkFrom });
3302
+ } else if (seed.dataset.seedAction === 'rvt') {
3303
+ const file = await pickRvtFile($seedRvt);
3304
+ if (file) createFromRvt(appId, templateId, file, linkFrom);
3305
+ } else if (seed.dataset.seedAction === 'tekla-source') {
3306
+ openTeklaSourceChoice(appId, templateId, seed, null, linkFrom);
3307
+ } else if (seed.dataset.seedAction === 'drawing-check-profile') {
3308
+ // A client profile starts empty: the reference drawings are added on its own page, where
3309
+ // their page counts and the proposed checklist can be shown. The setup dialog asks only the
3310
+ // folder and the client's name.
3311
+ createFromDrawing(appId, templateId, [], { kind: 'drawing-check-profile', sourceLabel: 'Client profile', returnFocus: seed, linkFrom });
3312
+ } else if (seed.dataset.seedAction === 'general-project') {
3313
+ // A General project starts from nothing but its name and folder (#2470).
3314
+ createFromDrawing(appId, templateId, [], { kind: 'general-project', sourceLabel: 'Blank project', returnFocus: seed });
3315
+ } else {
3316
+ // Unreachable today, and it must not be SILENT the day it isn't: an unhandled kind still
3317
+ // renders a full dashed, focusable card, so without this the first person to add one gets a
3318
+ // control that does nothing and says nothing. A dead control is no better than a missing one.
3319
+ console.warn(`[workspaces] create action "${seed.dataset.seedAction}" has no handler — the card does nothing`);
3320
+ }
3321
+ }
3322
+
3323
+ $landing.addEventListener('click', async (e) => {
3324
+ const registrationReview = e.target.closest('[data-project-registration-review]');
3325
+ if (registrationReview) { window.flolessProjectReconciliation?.openRegistration(registrationReview.dataset.projectRegistrationReview); return; }
3326
+ const groupToggle = e.target.closest('[data-project-group-toggle]');
3327
+ if (groupToggle) {
3328
+ const expanded = groupToggle.getAttribute('aria-expanded') !== 'true';
3329
+ const key = groupToggle.dataset.projectGroupToggle;
3330
+ if (landingQuery.trim()) projectGroupSearchOverrides.set(key, expanded);
3331
+ else saveProjectGroupExpanded(key, expanded);
3332
+ showProjectGroup(groupToggle.closest('.ws-project-section'), expanded);
3333
+ if (expanded) tipTruncatedNames();
3334
+ e.stopPropagation();
3335
+ return;
3336
+ }
3337
+ const kebab = e.target.closest('[data-kebab]');
3338
+ if (kebab) { e.stopPropagation(); openProjMenu(kebab.dataset.kebab, kebab); return; }
3339
+ // Before the card's own [data-open] branch below, exactly like the kebab: the thumbnail is the one
3340
+ // region of the card that does something other than open the project.
3341
+ const thumb = e.target.closest('[data-thumb]');
3342
+ if (thumb) { e.stopPropagation(); openThumbView(thumb.dataset.thumb, thumb); return; }
3343
+ const restore = e.target.closest('[data-restore]');
3344
+ if (restore) { e.stopPropagation(); unarchiveProject(restore.dataset.restore); return; }
3345
+ const del = e.target.closest('[data-delete-archived]');
3346
+ if (del) { e.stopPropagation(); deleteArchivedProject(del.dataset.deleteArchived); return; }
3347
+ if (e.target.closest('#ws-retry-projects')) { e.stopPropagation(); retryProjects(); return; }
3348
+ // Clearing empties the message the button sits in, so focus goes back to the search box.
3349
+ if (e.target.closest('#ws-search-clear')) { setLandingQuery(''); $landing.querySelector('#ws-landing-search')?.focus(); return; }
3350
+ if (e.target.closest('#ws-workspace-folder')) {
3351
+ e.stopPropagation();
3352
+ if (window.flolessWorkspaceRoot) window.flolessWorkspaceRoot.open();
3353
+ return;
3354
+ }
3355
+ if (e.target.closest('#ws-import-project')) { importProject(); return; }
3356
+ const remedy = createCardRemedy(e.target);
3357
+ if (remedy) { await remedy(); return; }
3233
3358
  const card = e.target.closest('[data-open]');
3234
3359
  if (card) { openProject(card.dataset.open); return; }
3235
3360
  const seed = e.target.closest('[data-seed-app]');
3236
- if (seed) {
3237
- // Two ids, and they are not interchangeable: create on the LIVE app (`seed-app`), but look the
3238
- // descriptor up by its lineage ROOT (`seed-template`) — after a rename the live id answers to no
3239
- // descriptor, and the built-in id answers to no installed app.
3240
- const appId = seed.dataset.seedApp;
3241
- const templateId = seed.dataset.seedTemplate || appId;
3242
- if (!WORKSPACE_APPS[templateId]) return;
3243
- // Each create kind has its own branch below. The 'drawing' check stays a check rather than an
3244
- // assumption: a future kind must declare its own branch, not silently inherit the file picker.
3245
- if (seed.dataset.seedAction === 'drawing') {
3246
- if (workspaceWorkflowKnownMissing(appId)) {
3247
- showToast(missingWorkspaceWorkflowMessage(templateId), 'warn');
3248
- return;
3249
- }
3250
- let files;
3251
- try { files = await pickDrawingFiles($seedFile); } // keep native picker in the click activation
3252
- catch { showToast('Couldn’t open the drawing picker. Try again.', 'warn'); return; }
3253
- if (!files.length) return;
3254
- if (workspaceWorkflowKnownMissing(appId)) {
3255
- showToast(missingWorkspaceWorkflowMessage(templateId), 'warn');
3256
- return;
3257
- }
3258
- createFromDrawing(appId, templateId, files);
3259
- } else if (seed.dataset.seedAction === 'rvt') {
3260
- const file = await pickRvtFile($seedRvt);
3261
- if (file) createFromRvt(appId, templateId, file);
3262
- } else if (seed.dataset.seedAction === 'tekla-source') {
3263
- openTeklaSourceChoice(appId, templateId, seed);
3264
- } else if (seed.dataset.seedAction === 'drawing-check-profile') {
3265
- // A client profile starts empty: the reference drawings are added on its own page, where
3266
- // their page counts and the proposed checklist can be shown. The setup dialog asks only the
3267
- // folder and the client's name.
3268
- createFromDrawing(appId, templateId, [], { kind: 'drawing-check-profile', sourceLabel: 'Client profile', returnFocus: seed });
3269
- } else if (seed.dataset.seedAction === 'general-project') {
3270
- // A General project starts from nothing but its name and folder (#2470).
3271
- createFromDrawing(appId, templateId, [], { kind: 'general-project', sourceLabel: 'Blank project', returnFocus: seed });
3272
- } else {
3273
- // Unreachable today, and it must not be SILENT the day it isn't: an unhandled kind still
3274
- // renders a full dashed, focusable card, so without this the first person to add one gets a
3275
- // control that does nothing and says nothing. A dead control is no better than a missing one.
3276
- console.warn(`[workspaces] create action "${seed.dataset.seedAction}" has no handler — the card does nothing`);
3277
- }
3278
- }
3361
+ if (seed) await activateSeedCard(seed);
3279
3362
  });
3280
3363
  $landing.addEventListener('input', (e) => {
3281
3364
  if (e.target.id !== 'ws-landing-search') return;
@@ -3340,9 +3423,9 @@
3340
3423
  $teklaSourceStatus.hidden = !message;
3341
3424
  }
3342
3425
  }
3343
- function openTeklaSourceChoice(appId, templateId, returnFocus, onPicked = null) {
3426
+ function openTeklaSourceChoice(appId, templateId, returnFocus, onPicked = null, linkFrom = null) {
3344
3427
  if (!$teklaSourceModal || teklaSourceChoice) return;
3345
- teklaSourceChoice = { appId, templateId, returnFocus, onPicked };
3428
+ teklaSourceChoice = { appId, templateId, returnFocus, onPicked, linkFrom };
3346
3429
  setTeklaSourcePicking(false);
3347
3430
  $teklaSourceModal.classList.add('show');
3348
3431
  $teklaSourceDialog?.focus();
@@ -3368,7 +3451,7 @@
3368
3451
  await choice.onPicked(source);
3369
3452
  return;
3370
3453
  }
3371
- const opened = await createFromTeklaSource(choice.appId, choice.templateId, source, choice.returnFocus);
3454
+ const opened = await createFromTeklaSource(choice.appId, choice.templateId, source, choice.returnFocus, choice.linkFrom);
3372
3455
  if (opened && teklaSourceChoice === choice) closeTeklaSourceChoice(false);
3373
3456
  else if (teklaSourceChoice === choice) setTeklaSourcePicking(false,
3374
3457
  'FloLess could not open project setup. Close any other setup window, then choose the source again.');
@@ -3554,7 +3637,10 @@
3554
3637
  const name = zone.querySelector('.ws-seed-headline')?.textContent || 'This card';
3555
3638
  const other = (card) => (card && card !== name ? card : null);
3556
3639
  const revit = files.some((file) => /\.rvt$/i.test(file.name)) && other(cardFor('rvt'));
3557
- const drawing = files.some(isDrawingFile) && other(cardFor('drawing'));
3640
+ const drawingCard = files.some((file) => isDrawingFile(file) && !/\.pdf$/i.test(file.name))
3641
+ ? $landing.querySelector('[data-seed-drop-kind="drawing"]:not([data-seed-template="steel-model"]) .ws-seed-headline')?.textContent
3642
+ : cardFor('drawing');
3643
+ const drawing = files.some(isDrawingFile) && other(drawingCard);
3558
3644
  const tekla = (folderCount || files.some((file) => /\.zip$/i.test(file.name))) && other(cardFor('tekla-source'));
3559
3645
  const next = revit ? `Drop it on ${revit} instead.`
3560
3646
  : drawing ? `Drop it on ${drawing} instead.`
@@ -3664,7 +3750,8 @@
3664
3750
  return;
3665
3751
  }
3666
3752
  const drawings = files.filter(isDrawingFile);
3667
- if (!drawings.length) { showToast(misdropMessage(zone, DRAWING_FORMATS, files, folderCount), 'warn'); return; }
3753
+ if (!drawings.length) { showToast(misdropMessage(zone, templateId === 'steel-model' ? 'PDF drawing sets' : DRAWING_FORMATS, files, folderCount), 'warn'); return; }
3754
+ if (!validateSteelDrawingFiles(templateId, files)) return;
3668
3755
  if (workspaceWorkflowKnownMissing(appId)) { showToast(missingWorkspaceWorkflowMessage(templateId), 'warn'); return; }
3669
3756
  const skippedFiles = files.length - drawings.length;
3670
3757
  const skipped = [
@@ -3728,6 +3815,7 @@
3728
3815
  const $projectSetupStandard = document.getElementById('project-setup-standard');
3729
3816
  const $projectSetupError = document.getElementById('project-setup-error');
3730
3817
  const $projectSetupProvider = document.getElementById('project-setup-provider');
3818
+ const $projectSetupKickoffNote = document.getElementById('project-setup-kickoff-note');
3731
3819
  const $projectSetupCancel = document.getElementById('project-setup-cancel');
3732
3820
  const $projectSetupCreateOnly = document.getElementById('project-setup-create-only');
3733
3821
  const $projectSetupCreate = document.getElementById('project-setup-create');
@@ -3772,6 +3860,8 @@
3772
3860
  if (userMessage) return userMessage;
3773
3861
  const raw = String(error && error.body?.error || error && error.message || error || '');
3774
3862
  const code = String(error && (error.code || error.body?.code) || '');
3863
+ // This attachment refusal is authored for the person, including the PDF count/size remedy.
3864
+ if (code === 'steel-pdf-required') return raw;
3775
3865
  // Account access can expire while this dialog is open, before the folder chooser
3776
3866
  // or project creation runs. Name that cause without blaming the selected folder.
3777
3867
  const access = bridge.accountAccessText?.(error);
@@ -3821,7 +3911,7 @@
3821
3911
  $projectSetupCreate.textContent = label || 'Create project & start chat';
3822
3912
  $projectSetupCreateOnly.textContent = busy && !projectSetupState.settingUp
3823
3913
  ? 'Creating…'
3824
- : (NO_CHAT_SETUP_KINDS.includes(projectSetupState.kind) ? 'Create project' : 'Create project only');
3914
+ : projectSetupState.linkFrom ? 'Create project' : createOnlyLabel(projectSetupState.kind);
3825
3915
  if (!busy) {
3826
3916
  $projectSetupCreate.disabled = !projectSetupReady();
3827
3917
  $projectSetupCreateOnly.disabled = !projectSetupReady();
@@ -3843,13 +3933,18 @@
3843
3933
  // Every answer is checked against what can start now: preferredChatProvider() prefers the open
3844
3934
  // conversation's AI, which may since have been uninstalled, and a choice that cannot start must
3845
3935
  // never be the one shown as chosen and sent.
3846
- // Setup kinds that create a project only — no AI Chat intake, no drawing-intake task. The two model
3847
- // sources are read by FloLess itself; a Drawing Checker profile starts empty and is built on its page.
3848
- const NO_CHAT_SETUP_KINDS = ['rvt', 'tekla-source', 'drawing-check-profile', 'general-project'];
3936
+ // Setup kinds that create a project only — no AI Chat intake. The two model sources are read by
3937
+ // FloLess itself; a Drawing Checker profile starts empty and is built on its page. A General project
3938
+ // does start a chat: Flo's kickoff (#2470 R6.4).
3939
+ const NO_CHAT_SETUP_KINDS = ['rvt', 'tekla-source', 'drawing-check-profile'];
3940
+ // Setup kinds whose Create project makes no drawing-intake task: no drawings are read to start them.
3941
+ const NO_DRAWING_TASK_KINDS = ['rvt', 'tekla-source', 'drawing-check-profile', 'general-project'];
3942
+ // The secondary button says what it leaves out whenever a start-chat button sits beside it.
3943
+ const createOnlyLabel = (kind) => (NO_CHAT_SETUP_KINDS.includes(kind) ? 'Create project' : 'Create project only');
3849
3944
  // Setup kinds that start from no file at all: a Drawing Checker profile and a General project.
3850
3945
  const NO_FILE_SETUP_KINDS = ['drawing-check-profile', 'general-project'];
3851
3946
  function projectSetupProvider(state) {
3852
- if (!state || NO_CHAT_SETUP_KINDS.includes(state.kind)) return null;
3947
+ if (!state || NO_CHAT_SETUP_KINDS.includes(state.kind) || state.linkFrom) return null;
3853
3948
  const runtimes = bridge.chatProviderRuntimes?.() || [];
3854
3949
  const readiness = (id) => (id ? projectSetupProviderReadiness(runtimes.find((runtime) => runtime.id === id)) : 'unavailable');
3855
3950
  const canStart = (id) => readiness(id) !== 'unavailable';
@@ -3970,6 +4065,7 @@
3970
4065
  const provider = projectSetupProvider(state);
3971
4066
  paintProjectSetupProviders(state, provider);
3972
4067
  $projectSetupCreate.hidden = !provider;
4068
+ if ($projectSetupKickoffNote) $projectSetupKickoffNote.hidden = state.kind !== 'general-project';
3973
4069
  $projectSetupCreateOnly.classList.toggle('primary', !provider);
3974
4070
  $projectSetupTitle.textContent = `New ${descDisplayName(state.templateId)} project`;
3975
4071
  $projectSetupSourceName.textContent = state.sourceLabel || state.files[0]?.name || (state.kind === 'rvt' ? 'Revit model' : 'Drawing set');
@@ -3977,7 +4073,7 @@
3977
4073
  const $sourceKicker = $projectSetupSourceName.previousElementSibling;
3978
4074
  if ($sourceKicker) $sourceKicker.textContent = state.kind === 'general-project' ? 'Starting point' : 'Source';
3979
4075
  $projectSetupSourceName.parentElement?.setAttribute('aria-label', state.kind === 'general-project' ? 'Starting point' : 'Selected source drawings');
3980
- $projectSetupCreateOnly.textContent = state.busy ? 'Creating…' : (NO_CHAT_SETUP_KINDS.includes(state.kind) ? 'Create project' : 'Create project only');
4076
+ $projectSetupCreateOnly.textContent = state.busy ? 'Creating…' : state.linkFrom ? 'Create project' : createOnlyLabel(state.kind);
3981
4077
  $projectSetupSourceCount.textContent = state.files.length > 1 ? `+ ${state.files.length - 1} more` : '';
3982
4078
  $projectSetupFolder.textContent = state.directory
3983
4079
  ? state.directory.path
@@ -4094,19 +4190,33 @@
4094
4190
  app: state.appId,
4095
4191
  ...(state.askCatalogue ? { environment: state.environment } : {}),
4096
4192
  directorySelectionId: state.directory.selectionId,
4097
- ...(NO_CHAT_SETUP_KINDS.includes(state.kind) ? {} : { initialTask: { kind: 'drawing-intake', sourceNames: state.files.map((file) => file.name) } }),
4193
+ ...(NO_DRAWING_TASK_KINDS.includes(state.kind) ? {} : { initialTask: { kind: 'drawing-intake', sourceNames: state.files.map((file) => file.name) } }),
4194
+ ...(state.linkFrom ? { linkFrom: state.linkFrom } : {}),
4098
4195
  };
4099
- const { project } = await api('/api/projects', { method: 'POST', body: JSON.stringify(payload) });
4196
+ const created = await api('/api/projects', { method: 'POST', body: JSON.stringify(payload) });
4197
+ const project = created.project;
4198
+ // #2470 R6.7: added from a General project — the link result goes with the project to the module's own next step.
4199
+ const link = state.linkFrom ? { linkFrom: state.linkFrom, moduleLink: created.moduleLink, replayed: created.replayed === true } : null;
4200
+ if (link && link.replayed) {
4201
+ // The first try made this project and its answer was lost: open it as it is. Never import or upload again,
4202
+ // and never archive it as "empty" — whatever the first try started is still its own.
4203
+ if (!project.archived && !projects.some((item) => item.id === project.id)) projects.unshift(project);
4204
+ setProjectSetupBusy(false);
4205
+ closeProjectSetup({ restoreFocus: false });
4206
+ if (!project.archived) await openProject(project.id, state.kind === 'drawing-check-profile' ? 'model' : 'drawings');
4207
+ globalThis.flolessProjectModules?.afterCreate?.({ project, ...link, outcome: 'ok' });
4208
+ return;
4209
+ }
4100
4210
  if (state.kind === 'rvt') {
4101
4211
  setProjectSetupBusy(false);
4102
4212
  closeProjectSetup({ restoreFocus: false });
4103
- await importRvtIntoProject(project, state.files[0], state.appId);
4213
+ await importRvtIntoProject(project, state.files[0], state.appId, link);
4104
4214
  return;
4105
4215
  }
4106
4216
  if (state.kind === 'tekla-source') {
4107
4217
  setProjectSetupBusy(false);
4108
4218
  closeProjectSetup({ restoreFocus: false });
4109
- await importTeklaIntoProject(project, state.teklaSource, state.appId);
4219
+ await importTeklaIntoProject(project, state.teklaSource, state.appId, link);
4110
4220
  return;
4111
4221
  }
4112
4222
  if (state.kind === 'drawing-check-profile' || state.kind === 'general-project') {
@@ -4116,6 +4226,7 @@
4116
4226
  closeProjectSetup({ restoreFocus: false });
4117
4227
  // A General project opens on Knowledge: the job's context, and the first thing to add.
4118
4228
  await openProject(project.id, state.kind === 'general-project' ? 'knowledge' : 'model');
4229
+ if (link) globalThis.flolessProjectModules?.afterCreate?.({ project, ...link, outcome: 'ok' });
4119
4230
  return;
4120
4231
  }
4121
4232
  projects.unshift(project);
@@ -4123,7 +4234,8 @@
4123
4234
  setProjectSetupBusy(false);
4124
4235
  closeProjectSetup({ restoreFocus: false });
4125
4236
  await openProject(project.id, 'drawings');
4126
- showToast('Project created. Attach the drawings on the Drawings step when you’re ready to read them.', 'ok');
4237
+ if (link) globalThis.flolessProjectModules?.afterCreate?.({ project, ...link, outcome: 'ok', next: 'Attach the drawings on the Drawings step when you’re ready to read them.' });
4238
+ else showToast('Project created. Attach the drawings on the Drawings step when you’re ready to read them.', 'ok');
4127
4239
  return;
4128
4240
  }
4129
4241
  let snapshots = state.snapshots || null;
@@ -4148,7 +4260,8 @@
4148
4260
  track('workspace_project_created', { app: state.appId });
4149
4261
  }
4150
4262
  if (!state.opened) {
4151
- await openProject(project.id, 'drawings');
4263
+ // A General project opens on Knowledge, where its kickoff chat helps fill it (#2470 R6.4).
4264
+ await openProject(project.id, state.kind === 'general-project' ? 'knowledge' : 'drawings');
4152
4265
  state.opened = true;
4153
4266
  }
4154
4267
  await bridge.openChatConversation(result.chat.chatId);
@@ -4168,7 +4281,10 @@
4168
4281
  }
4169
4282
  setProjectSetupBusy(false);
4170
4283
  closeProjectSetup({ restoreFocus: false });
4171
- showToast('Project created — the drawing task is running in AI Chat.', 'ok');
4284
+ // A General project's chat is Flo's kickoff; its first reply may still be on its way (#2470 R6.4).
4285
+ showToast(state.kind === 'general-project'
4286
+ ? 'Project created — Flo will help you set it up in AI Chat.'
4287
+ : 'Project created — the drawing task is running in AI Chat.', 'ok');
4172
4288
  }
4173
4289
 
4174
4290
  async function resumeInterruptedProjectChatIntake() {
@@ -4181,7 +4297,7 @@
4181
4297
  const result = await bridge.resumeProjectChatIntake(submissionId);
4182
4298
  if (!result) continue;
4183
4299
  if (!projects.some((item) => item.id === result.project.id)) projects.unshift(result.project);
4184
- await openProject(result.project.id, 'drawings');
4300
+ await openProject(result.project.id, result.project.app === 'floless-general' ? 'knowledge' : 'drawings');
4185
4301
  await bridge.openChatConversation(result.chat.chatId);
4186
4302
  forgetProjectChatIntake(submissionId);
4187
4303
  showToast('Recovered the project and its AI Chat.', 'ok');
@@ -4189,6 +4305,10 @@
4189
4305
  const code = error && (error.code || error.body && error.body.code);
4190
4306
  if (code === 'project-intake-not-found' || code === 'project-intake-damaged') {
4191
4307
  forgetProjectChatIntake(submissionId);
4308
+ } else if (code === 'project-intake-project-missing') {
4309
+ // The project this setup made was removed or replaced: nothing is left to resume, so say so once (#2470 R6.4).
4310
+ forgetProjectChatIntake(submissionId);
4311
+ showToast(projectSetupErrorMessage(error), 'error');
4192
4312
  } else {
4193
4313
  console.warn('project Chat intake recovery is still pending', error);
4194
4314
  }
@@ -4202,10 +4322,11 @@
4202
4322
  * working directory. Nothing is written while the dialog is open. Creation atomically publishes
4203
4323
  * project.json and an unsent initial-task draft; the headless provider is not contacted here.
4204
4324
  */
4205
- async function createFromDrawing(appId, templateId, files, { kind = 'drawings', sourceLabel = '', teklaSource = null, returnFocus = null } = {}) {
4325
+ async function createFromDrawing(appId, templateId, files, { kind = 'drawings', sourceLabel = '', teklaSource = null, returnFocus = null, linkFrom = null } = {}) {
4206
4326
  if (!$projectSetup || projectSetupState) return false;
4207
4327
  // A Drawing Checker profile and a General project start with no source file: what goes in them comes later.
4208
4328
  if (!Array.isArray(files) || (!files.length && !NO_FILE_SETUP_KINDS.includes(kind))) return false;
4329
+ if (kind === 'drawings' && !validateSteelDrawingFiles(templateId, files)) return false;
4209
4330
  if (kind === 'drawings' && files.length > 20) {
4210
4331
  showToast('Choose up to 20 drawings for a new project.', 'warn');
4211
4332
  return false;
@@ -4219,6 +4340,9 @@
4219
4340
  providersRead: false,
4220
4341
  sourceLabel,
4221
4342
  teklaSource,
4343
+ // #2470 R6.7: the General project this one is added to, with the one operation id this dialog uses for every
4344
+ // press of Create (a retry after a lost answer is the same operation, so it can never make a second project).
4345
+ linkFrom,
4222
4346
  askCatalogue: kind === 'drawings' && templateId === 'steel-model',
4223
4347
  environment: null,
4224
4348
  directory: null,
@@ -4234,7 +4358,7 @@
4234
4358
  renderProjectSetup();
4235
4359
  $projectSetup.classList.add('show');
4236
4360
  $projectSetupFolderChoose.focus();
4237
- if (!NO_CHAT_SETUP_KINDS.includes(kind)) void refreshProjectSetupProviders(state);
4361
+ if (!NO_CHAT_SETUP_KINDS.includes(kind) && !linkFrom) void refreshProjectSetupProviders(state);
4238
4362
  try {
4239
4363
  if (kind !== 'tekla-source') {
4240
4364
  await Promise.all(files.map(assertProjectSourceReadable));
@@ -4964,23 +5088,23 @@
4964
5088
 
4965
5089
  // An RVT project is created like a drawing project: the setup dialog asks for the project folder
4966
5090
  // and name (every project lives in a chosen working directory), then the RVT is uploaded and imported.
4967
- function createFromTeklaSource(appId, templateId, source, returnFocus = null) {
5091
+ function createFromTeklaSource(appId, templateId, source, returnFocus = null, linkFrom = null) {
4968
5092
  if (!source || !['folder', 'zip'].includes(source.kind) || !Array.isArray(source.entries) || !source.entries.length) return false;
4969
5093
  if (source.kind === 'folder' && !source.entries.some((entry) => /\.db1$/i.test(entry.path) && !/(?:^|\/)xslib\.db1$/i.test(entry.path))) {
4970
5094
  showToast('That folder is not a Tekla model folder.', 'warn');
4971
5095
  return false;
4972
5096
  }
4973
5097
  return createFromDrawing(appId, templateId, source.entries.map((entry) => entry.file), {
4974
- kind: 'tekla-source', sourceLabel: source.label, teklaSource: source, returnFocus,
5098
+ kind: 'tekla-source', sourceLabel: source.label, teklaSource: source, returnFocus, linkFrom,
4975
5099
  });
4976
5100
  }
4977
5101
 
4978
- function createFromRvt(appId, templateId, file) {
5102
+ function createFromRvt(appId, templateId, file, linkFrom = null) {
4979
5103
  if (!file || !/\.rvt$/i.test(file.name)) { showToast('Choose one Revit .rvt file.', 'warn'); return; }
4980
- return createFromDrawing(appId, templateId, [file], { kind: 'rvt' });
5104
+ return createFromDrawing(appId, templateId, [file], { kind: 'rvt', linkFrom });
4981
5105
  }
4982
5106
 
4983
- async function importRvtIntoProject(project, file, appId) {
5107
+ async function importRvtIntoProject(project, file, appId, link = null) {
4984
5108
  try {
4985
5109
  const operation = await uploadRvtForProject(project, file, 0);
4986
5110
  track('workspace_project_created', { app: appId });
@@ -4989,15 +5113,18 @@
4989
5113
  paintRevitSourceState('Waiting for AWARE', 'Your RVT is stored locally and waiting for the trusted reader.');
4990
5114
  if (revitActiveOperation?.operationId !== operation.operationId) revitActiveOperation = operation;
4991
5115
  pollRevitImport(operation.operationId, project.id);
5116
+ if (link) globalThis.flolessProjectModules?.afterCreate?.({ project, ...link, outcome: 'ok' });
4992
5117
  } catch (err) {
4993
5118
  const removed = await archiveEmptyProject(project.id);
5119
+ // #2470 R6.7: the empty project is not kept linked either; the Modules step says what happened (spec §6.3).
5120
+ if (link) { await globalThis.flolessProjectModules?.afterCreate?.({ project, ...link, outcome: removed ? 'archived-empty' : 'left-empty', error: err && err.message || String(err) }); return; }
4994
5121
  showToast(removed
4995
5122
  ? `Couldn’t import the RVT — the empty project was removed. ${err && err.message || err}`
4996
5123
  : `Couldn’t import the RVT. An empty project was left behind; archive it from the ⋯ menu. ${err && err.message || err}`, 'warn');
4997
5124
  }
4998
5125
  }
4999
5126
 
5000
- async function importTeklaIntoProject(project, source, appId) {
5127
+ async function importTeklaIntoProject(project, source, appId, link = null) {
5001
5128
  try {
5002
5129
  track('workspace_project_created', { app: appId });
5003
5130
  if (!projects.some((entry) => entry.id === project.id)) projects.unshift(project);
@@ -5008,7 +5135,9 @@
5008
5135
  if (revitActiveOperation?.operationId !== operation.operationId) revitActiveOperation = operation;
5009
5136
  pollRevitImport(operation.operationId, project.id);
5010
5137
  }
5138
+ if (link) globalThis.flolessProjectModules?.afterCreate?.({ project, ...link, outcome: 'ok' });
5011
5139
  } catch (error) {
5140
+ if (link) globalThis.flolessProjectModules?.afterCreate?.({ project, ...link, outcome: 'failed-kept' });
5012
5141
  if (error?.name === 'AbortError') {
5013
5142
  if (current?.id === project.id) {
5014
5143
  paintRevitSourceState('Read cancelled', 'No read-only snapshot was created. The source Tekla model was not changed.');
@@ -5405,6 +5534,12 @@
5405
5534
  b.setAttribute('data-command-id', `shell.workspace-step#${label}`);
5406
5535
  }
5407
5536
  });
5537
+ // #2568: the tabs read in the kind's own `steps` order (the markup holds every kind's tabs once). The tablist holds
5538
+ // nothing but tabs, so moving a button within it changes only its place, never its state or listeners.
5539
+ for (const st of d.steps) {
5540
+ const b = $stepTabs.querySelector(`button[data-step="${st.key}"]`);
5541
+ if (b) $stepTabs.append(b);
5542
+ }
5408
5543
  }
5409
5544
 
5410
5545
  // Everything the server refuses on write is refused again on read. A progress record is replayed
@@ -6050,7 +6185,7 @@
6050
6185
  ? '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
6186
  : projectContractLifecycle === 'filter-checkpoint'
6052
6187
  ? '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.';
6188
+ : '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
6189
  paintStageGuidance(guidance, failedInitial || unavailableInitial ? 'failed' : 'info');
6055
6190
  if (waitingForInitial && revCardReq?.prepassReady && !revCardReq?.filterCheckpointCurrent) {
6056
6191
  appendStageGuidanceFilterAction();
@@ -6156,7 +6291,17 @@
6156
6291
  // extracted and evaluated on its own by workspace-instructor-handoff.test.ts, and a closure
6157
6292
  // variable it cannot see is a ReferenceError there. It sits at the end of the step-tabs row now
6158
6293
  // (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; }
6294
+ { const a = document.getElementById('ws-attach-revision');
6295
+ const steel = d === WORKSPACE_APPS['steel-model'];
6296
+ if (a) {
6297
+ a.hidden = s !== 'drawings' || d?.serverAuthorizedOnly === true;
6298
+ a.dataset.tip = steel
6299
+ ? 'Attach revised PDF drawings — your terminal AI reads them into a new version'
6300
+ : 'Attach a revised drawing set (PDF or image) — your terminal AI reads it into a new version';
6301
+ }
6302
+ const input = document.getElementById('ws-revision-file');
6303
+ if (input) input.accept = steel ? '.pdf' : '.pdf,image/*';
6304
+ }
6160
6305
  renderRevisionCard(); // reflect any pending/failed revision read (card shows only on the Drawings step)
6161
6306
  // The conversion offer is Model-step scoped, and re-derived on every entry rather than cached:
6162
6307
  // the project's contract can change under this shell (a revision read, another tab, the editor's
@@ -6185,6 +6330,24 @@
6185
6330
  });
6186
6331
  }
6187
6332
  }
6333
+ // #2470 R6.2: Workflows is a shell-rendered pane too: the workflows this project owns (project-workflows.js).
6334
+ // Queried here for the same reason as the Pages pane above.
6335
+ const $workflowsPane = document.getElementById('ws-workflows');
6336
+ if ($workflowsPane) {
6337
+ const showWorkflows = s === 'workflows';
6338
+ $workflowsPane.hidden = !showWorkflows;
6339
+ const project = typeof current !== 'undefined' ? current : null;
6340
+ if (showWorkflows && project && window.flolessProjectWorkflows) window.flolessProjectWorkflows.render($workflowsPane, project);
6341
+ }
6342
+ // #2470 R6.7: Modules is a shell-rendered pane too: the module projects linked to this one (project-modules.js).
6343
+ // Queried here for the same reason as the Pages pane above.
6344
+ const $modulesPane = document.getElementById('ws-modules');
6345
+ if ($modulesPane) {
6346
+ const showModules = s === 'modules';
6347
+ $modulesPane.hidden = !showModules;
6348
+ const project = typeof current !== 'undefined' ? current : null;
6349
+ if (showModules && project && window.flolessProjectModules) window.flolessProjectModules.render($modulesPane, project);
6350
+ }
6188
6351
  // Knowledge is a shell-rendered pane too: the project's Knowledge Base (References column).
6189
6352
  const showKnowledge = s === 'knowledge';
6190
6353
  $wsKnowledge.hidden = !showKnowledge;
@@ -7273,6 +7436,7 @@
7273
7436
  kbGraphIndex = null;
7274
7437
  lastStepHeadHtml = null;
7275
7438
  $wsKnowledge.querySelector('.kb-g-overview')?.remove(); // and the button already on screen goes now
7439
+ kbGraphStopWorker(); // #2491 R6.9: a layout still running for the previous project is dropped
7276
7440
  }
7277
7441
 
7278
7442
  function stopKnowledgePoll() { if (knowledgePoll) { clearInterval(knowledgePoll); knowledgePoll = null; } }
@@ -7310,6 +7474,8 @@
7310
7474
  sources: Array.isArray(manifest.sources) ? manifest.sources : [],
7311
7475
  currentGeneration: status.currentGeneration || null,
7312
7476
  organize: status.organize || null,
7477
+ // #2491 R6.9: the person's categories and where each reference sits.
7478
+ categories: status.categories || { v: 1, revision: 0, categories: [], placements: {}, state: 'absent' },
7313
7479
  queued: list.filter((r) => r && r.type === 'knowledge-organize' && r.project === proj.id),
7314
7480
  company,
7315
7481
  designSet,
@@ -7668,8 +7834,9 @@
7668
7834
  kbAddIssuePanel(st) + body + '</section>';
7669
7835
  }
7670
7836
 
7671
- function kbSourceRow(s, st) {
7837
+ function kbSourceRow(s, st, depth) {
7672
7838
  const on = !!s.useAsKb;
7839
+ const sel = kbSel.selected.has(s.sourceId);
7673
7840
  const ico = kbIcon(s.mime);
7674
7841
  const chip = KB_CHIP[s.state] || ['new', escapeHtml(String(s.state || 'new'))];
7675
7842
  const name = s.filename || 'untitled';
@@ -7683,12 +7850,13 @@
7683
7850
  // exclusions. `aria-current` (not `aria-selected`, which is invalid on a generic role and would
7684
7851
  // fail aria-allowed-attr) marks the row whose file is on screen.
7685
7852
  const isOpen = viewer.mode === 'file' && viewer.sourceId === s.sourceId;
7686
- return `<div class="kb-src${on ? '' : ' off'}${s.state === 'error' ? ' state-error' : ''}"` +
7853
+ return `<div class="kb-src${on ? '' : ' off'}${s.state === 'error' ? ' state-error' : ''}${sel ? ' selected' : ''}" draggable="true"` +
7854
+ (depth != null ? ` style="--kb-depth:${depth}"` : '') +
7687
7855
  ` data-source-id="${escapeAttr(s.sourceId)}"${isOpen ? ' aria-current="true"' : ''}>` +
7688
7856
  `<span class="kb-fico ${ico.cls}" aria-hidden="true">${ico.glyph}</span>` +
7689
7857
  `<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>` +
7858
+ `<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)}" ` +
7859
+ `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
7860
  `<div class="kb-fmeta">${escapeHtml(meta)}<span class="kb-chip ${chip[0]}">${chip[1]}</span>${kbTextChips(s)}${imported}${kbCompanyChip(s, st)}` +
7693
7861
  `${kbIsDesignSet(s, st) ? '<span class="kb-chip run kb-chip-ds">design set</span>' : ''}</div>` +
7694
7862
  kbDesignSetUse(s, st) +
@@ -7701,6 +7869,599 @@
7701
7869
  `</div>`;
7702
7870
  }
7703
7871
 
7872
+
7873
+ // ── #2491 R6.9: categories, multi-select, Move to…, drag and drop ─────────────────────────────────────
7874
+ // The pure half is web/kb-categories.js (kbc*); this is the DOM half. Categories are the person's: every change here is
7875
+ // the person's own click, which the server checks (an AI can only suggest one on a card). Each change carries the
7876
+ // categories' revision this screen drew and the project's incarnation, so a change made meanwhile elsewhere is never
7877
+ // overwritten — the server says so in words and this screen reloads.
7878
+ const KB_CAT_KEY = 'the categories', KB_PROJECT_KEY = 'the project';
7879
+ const KB_REFS_MIME = 'application/x-floless-kb-refs';
7880
+ let kbSel = { selected: new Set(), anchor: null };
7881
+ let kbSelProject = null;
7882
+ let kbCatCollapsed = new Set(); // categories the person folded (new ones start open), per project
7883
+ let kbCatCollapsedProject = null;
7884
+ let kbCatEdit = null; // { mode: 'new' | 'rename', id?, parentId?, then?: { sourceIds } } — the inline name box
7885
+ let kbCatFocus = null; // { cat: id } | { row: sourceId } — focus to restore after the next repaint
7886
+ let kbCatBusy = false;
7887
+
7888
+ function kbCats(st) {
7889
+ const c = st && st.categories;
7890
+ return c && Array.isArray(c.categories) ? c : { v: 1, revision: 0, categories: [], placements: {}, state: 'absent' };
7891
+ }
7892
+ const kbCatUsable = (st) => { const c = kbCats(st); return c.state !== 'damaged' && c.state !== 'newer'; };
7893
+ function kbCatCollapsedFor(proj) {
7894
+ if (!proj) return new Set();
7895
+ if (kbCatCollapsedProject !== proj.id) {
7896
+ kbCatCollapsedProject = proj.id;
7897
+ try { kbCatCollapsed = new Set(JSON.parse(localStorage.getItem(`floless:kb-cat-folded:${proj.id}`) || '[]')); }
7898
+ catch { kbCatCollapsed = new Set(); }
7899
+ }
7900
+ return kbCatCollapsed;
7901
+ }
7902
+ function kbCatSaveCollapsed() {
7903
+ if (!current) return;
7904
+ try { localStorage.setItem(`floless:kb-cat-folded:${current.id}`, JSON.stringify([...kbCatCollapsed])); } catch { /* private mode */ }
7905
+ }
7906
+ function kbSelFor(proj, st) {
7907
+ if (!proj || kbSelProject !== proj.id) { kbSelProject = proj ? proj.id : null; kbSel = { selected: new Set(), anchor: null }; }
7908
+ if (st) kbSel = kbcPrune(kbSel, st.sources.map((s) => s.sourceId));
7909
+ return kbSel;
7910
+ }
7911
+ function kbAnnounce(text) {
7912
+ const live = $wsKnowledge.querySelector('#kb-drop-live');
7913
+ if (!live) return;
7914
+ live.textContent = '';
7915
+ setTimeout(() => { live.textContent = text; }, 30);
7916
+ }
7917
+ /** The refs column keeps the inline name box while someone types in it: a poll must not repaint under it. */
7918
+ function kbCatEditActive() {
7919
+ // Only while an edit is open: once it is saved or cancelled the box is stale, and the repaint must remove it even
7920
+ // though it still holds focus.
7921
+ const box = $wsKnowledge.querySelector('.kb-cat-edit');
7922
+ return !!kbCatEdit && !!box && (box.contains(document.activeElement) || kbCatBusy);
7923
+ }
7924
+
7925
+ function kbCatEditHtml(depth) {
7926
+ const e = kbCatEdit;
7927
+ const verb = e.mode === 'rename' ? 'Rename' : e.then ? 'Create and move' : 'Create';
7928
+ const value = e.mode === 'rename' ? escapeAttr(e.name || '') : '';
7929
+ return `<div class="kb-cat-edit" style="--kb-depth:${depth}">` +
7930
+ `<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">` +
7931
+ `<button type="button" class="primary kb-cat-save" data-kb-cat-save data-command-id="shell.kb-category-save">${verb}</button>` +
7932
+ '<button type="button" class="kb-cat-cancel" data-kb-cat-cancel data-command-id="shell.kb-category-cancel">Cancel</button></div>';
7933
+ }
7934
+
7935
+ function kbCatRowHtml(item, file) {
7936
+ const isU = item.kind === 'uncategorized';
7937
+ const id = isU ? 'uncategorized' : item.id;
7938
+ const chev = '<svg class="kb-cat-chev" viewBox="0 0 16 16" aria-hidden="true"><path d="m6 4 4 4-4 4"/></svg>';
7939
+ const editing = kbCatEdit && kbCatEdit.mode === 'rename' && kbCatEdit.id === item.id;
7940
+ if (editing) return kbCatEditHtml(item.depth);
7941
+ const name = escapeHtml(item.name);
7942
+ const tip = item.name.length > 28 ? ` data-tip="${escapeAttr(isU ? item.name : kbcLabel(file, item.id))}"` : '';
7943
+ return `<div class="kb-cat${isU ? ' kb-uncat' : ''}${item.open ? ' open' : ''}" style="--kb-depth:${item.depth}" data-kb-drop-cat="${escapeAttr(id)}">` +
7944
+ `<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)}">` +
7945
+ `${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>` +
7946
+ (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>`) +
7947
+ '</div>' +
7948
+ (item.open && item.empty ? `<div class="kb-cat-empty" style="--kb-depth:${item.depth + 1}">${isU ? 'Nothing here.' : 'Empty. Drag references here.'}</div>` : '');
7949
+ }
7950
+
7951
+ /** The References list as a tree (once the first category exists), with the inline name box where it was asked for. */
7952
+ function kbTreeHtml(st, rows) {
7953
+ const file = kbCats(st);
7954
+ const folded = kbCatCollapsedFor(current);
7955
+ const open = new Set(['uncategorized', ...file.categories.map((c) => c.id)].filter((id) => !folded.has(id)));
7956
+ const items = kbcTreeItems(file, rows, open);
7957
+ let html = '';
7958
+ for (const item of items) {
7959
+ if (item.kind === 'row') { html += kbSourceRow(item.row, st, item.depth); continue; }
7960
+ html += kbCatRowHtml(item, file);
7961
+ if (kbCatEdit && kbCatEdit.mode === 'new' && kbCatEdit.parentId && kbCatEdit.parentId === item.id && item.open) html += kbCatEditHtml(item.depth + 1);
7962
+ }
7963
+ if (kbCatEdit && kbCatEdit.mode === 'new' && !kbCatEdit.parentId) html = kbCatEditHtml(0) + html;
7964
+ return `<div class="kb-tree" role="group" aria-label="References by category">${html}</div>`;
7965
+ }
7966
+
7967
+ /** The bar under the list while references are selected. */
7968
+ function kbSelBarHtml(st) {
7969
+ const n = kbSelFor(current, st).selected.size;
7970
+ if (!n) return '';
7971
+ return '<div class="kb-selbar" role="region" aria-label="Selected references">' +
7972
+ `<span class="kb-selbar-n">${n} selected</span>` +
7973
+ '<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>' +
7974
+ '<button type="button" class="kb-selbar-clear" data-kb-sel-clear data-command-id="shell.kb-select-clear">Clear</button></div>';
7975
+ }
7976
+
7977
+ /** The categories file could not be read, or a newer FloLess wrote it: say so, and offer to start again. */
7978
+ function kbCatUnavailableHtml(st) {
7979
+ const c = kbCats(st);
7980
+ if (kbCatUsable(st)) return '';
7981
+ const why = c.state === 'newer'
7982
+ ? 'Your categories were saved by a newer FloLess, so this one shows every reference without them.'
7983
+ : 'Your categories could not be read, so every reference is shown without them.';
7984
+ 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>` +
7985
+ '<button type="button" data-kb-cat-reset data-command-id="shell.kb-category-reset">Start again</button></div>';
7986
+ }
7987
+
7988
+ function kbCatExpected(st) {
7989
+ return { [KB_CAT_KEY]: String(kbCats(st).revision || 0), [KB_PROJECT_KEY]: current && current.uuid ? current.uuid : '' };
7990
+ }
7991
+ /** One category change against what this screen drew. The server's own sentence is shown when it refuses. */
7992
+ async function kbCatPost(tail, body, done) {
7993
+ const proj = current;
7994
+ if (!proj || kbCatBusy) return null;
7995
+ kbCatBusy = true;
7996
+ try {
7997
+ const res = await api(kbUrl(proj.id, tail), { method: 'POST', body: JSON.stringify({ expected: kbCatExpected(knowledgeState), ...body }) });
7998
+ if (current !== proj) return null;
7999
+ if (knowledgeState && res && res.categories) knowledgeState.categories = res.categories;
8000
+ if (done) done(res);
8001
+ kbInvalidateRefs();
8002
+ if (knowledgeState) paintKnowledge(knowledgeState);
8003
+ return res;
8004
+ } catch (err) {
8005
+ const said = err && err.body && typeof err.body.error === 'string' ? err.body.error : '';
8006
+ showToast(said || 'FloLess could not change your categories just now. Try again.', 'warn');
8007
+ // Changed elsewhere since the name box opened: close it, so the person sees the newer names before naming again.
8008
+ if (body.expected && err && err.body && err.body.code === 'knowledge-categories-changed') kbCatEdit = null;
8009
+ return null;
8010
+ } finally {
8011
+ kbCatBusy = false;
8012
+ if (current === proj) renderKnowledge();
8013
+ }
8014
+ }
8015
+ function kbCatOps(ops, announce, focus, expected) {
8016
+ return kbCatPost('/categories', expected ? { ops, expected } : { ops }, (res) => {
8017
+ if (announce) kbAnnounce(typeof announce === 'function' ? announce(res) : announce);
8018
+ if (focus) kbCatFocus = typeof focus === 'function' ? focus(res) : focus;
8019
+ });
8020
+ }
8021
+ function kbPlace(sourceIds, categoryId) {
8022
+ const st = knowledgeState;
8023
+ const where = categoryId ? kbcLabel(kbCats(st), categoryId) : 'Uncategorized';
8024
+ const n = sourceIds.length;
8025
+ return kbCatPost('/sources/place', { sourceIds, categoryId: categoryId || null }, (res) => {
8026
+ const moved = (res.placed || []).length;
8027
+ const missing = (res.missing || []).length;
8028
+ kbAnnounce(`Moved ${moved} reference${moved === 1 ? '' : 's'} to ${where}.${missing ? ` ${missing} ${missing === 1 ? 'was' : 'were'} no longer here.` : ''}`);
8029
+ if (categoryId) {
8030
+ // Keep the moved items in view: open the category and its ancestors.
8031
+ const file = res.categories || kbCats(st);
8032
+ for (const id of [...kbcAncestors(file, categoryId), categoryId]) kbCatCollapsed.delete(id);
8033
+ kbCatSaveCollapsed();
8034
+ }
8035
+ kbSel = { selected: new Set(), anchor: null };
8036
+ if (n) kbCatFocus = { row: sourceIds[0] };
8037
+ });
8038
+ }
8039
+
8040
+ function kbCatPop(anchor, html, label, role) {
8041
+ kbCloseConfirm();
8042
+ const box = anchor.closest('.kb-refs-body');
8043
+ if (!box) return null;
8044
+ const pop = document.createElement('div');
8045
+ pop.className = `hist-confirm${role === 'menu' ? ' kb-ds-menu kb-cat-menu' : ''}`;
8046
+ pop.setAttribute('role', role || 'dialog');
8047
+ pop.setAttribute('aria-label', label);
8048
+ pop.innerHTML = html;
8049
+ box.appendChild(pop);
8050
+ const cr = box.getBoundingClientRect();
8051
+ const br = anchor.getBoundingClientRect();
8052
+ // Below the control when it fits in view, else above it (the selection bar sits at the bottom edge).
8053
+ const below = br.bottom - cr.top + box.scrollTop + 6;
8054
+ const fits = br.bottom + 6 + pop.offsetHeight <= cr.bottom;
8055
+ pop.style.top = `${fits ? below : Math.max(box.scrollTop + 4, br.top - cr.top + box.scrollTop - pop.offsetHeight - 6)}px`;
8056
+ pop.style.left = `${Math.max(8, Math.min(br.left - cr.left, box.clientWidth - pop.offsetWidth - 8))}px`;
8057
+ document.addEventListener('mousedown', kbOnDocDown, true);
8058
+ pop.kbAnchor = anchor;
8059
+ return pop;
8060
+ }
8061
+
8062
+ /** Move to…: for references (the selection, or one row) or for a category (where it sits). */
8063
+ function kbShowMoveMenu(anchor, what) {
8064
+ const st = knowledgeState;
8065
+ const file = kbCats(st);
8066
+ const choices = kbcMenuChoices(file, what.categoryId || null);
8067
+ const currentAt = what.categoryId
8068
+ ? (file.categories.find((c) => c.id === what.categoryId) || {}).parentId || null
8069
+ : (what.sourceIds.length === 1 ? kbcPlacement(file, what.sourceIds[0]) : undefined);
8070
+ const n = what.sourceIds ? what.sourceIds.length : 0;
8071
+ const title = what.categoryId ? `Move “${escapeHtml(kbcLabel(file, what.categoryId))}” to` : `Move ${n === 1 ? 'this reference' : `${n} references`} to`;
8072
+ const items = choices.filter((c) => c.allowed).map((c) =>
8073
+ `<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}"` +
8074
+ ` 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('');
8075
+ const pop = kbCatPop(anchor, `<div class="kb-move-title">${title}</div>${items}` +
8076
+ `<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>`,
8077
+ what.categoryId ? 'Move category' : 'Move references', 'menu');
8078
+ if (!pop) return;
8079
+ pop.kbWhat = what;
8080
+ const first = pop.querySelector('[aria-checked="true"]') || pop.querySelector('.kb-ds-mi');
8081
+ if (first) first.focus();
8082
+ }
8083
+
8084
+ function kbShowCatMenu(btn) {
8085
+ const id = btn.dataset.kbCatMenu;
8086
+ const file = kbCats(knowledgeState);
8087
+ const cat = file.categories.find((c) => c.id === id);
8088
+ if (!cat) return;
8089
+ const sibs = kbcChildren(file, cat.parentId || null);
8090
+ const at = sibs.findIndex((c) => c.id === id);
8091
+ const pop = kbCatPop(btn,
8092
+ `<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>` +
8093
+ `<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>` +
8094
+ `<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>` +
8095
+ (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>` : '') +
8096
+ (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>` : '') +
8097
+ `<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>`,
8098
+ `More for ${cat.name}`, 'menu');
8099
+ const first = pop && pop.querySelector('.kb-ds-mi');
8100
+ if (first) first.focus();
8101
+ }
8102
+
8103
+ function kbShowCatDelete(anchor, id) {
8104
+ const st = knowledgeState;
8105
+ const file = kbCats(st);
8106
+ const cat = file.categories.find((c) => c.id === id);
8107
+ if (!cat) return;
8108
+ const body = kbCatDeleteSentence(file, st.sources, id);
8109
+ const pop = kbCatPop(anchor,
8110
+ `<div class="hc-title">Delete “${escapeHtml(cat.name)}”?</div><div class="hc-body">${body}</div>` +
8111
+ '<div class="hc-act"><button type="button" class="hc-cancel" data-command-id="shell.kb-category-cancel">Cancel</button>' +
8112
+ `<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>`,
8113
+ `Delete ${cat.name}`, 'dialog');
8114
+ const cancel = pop && pop.querySelector('.hc-cancel');
8115
+ if (cancel) cancel.focus();
8116
+ }
8117
+
8118
+ /** What deleting a category does, in words: its own references and its subcategories (with theirs) move up a level. */
8119
+ function kbCatDeleteSentence(file, rows, id) {
8120
+ const cat = file.categories.find((c) => c.id === id);
8121
+ const n = (rows || []).filter((r) => kbcPlacement(file, r.sourceId) === id).length;
8122
+ const subs = kbcChildren(file, id).length;
8123
+ const refs = `${n} reference${n === 1 ? '' : 's'}`;
8124
+ const kids = `${subs} subcategor${subs === 1 ? 'y' : 'ies'}`;
8125
+ if (!n && !subs) return 'It is empty. No reference is deleted.';
8126
+ if (cat && cat.parentId) {
8127
+ const to = `“${escapeHtml(kbcLabel(file, cat.parentId))}”`;
8128
+ return `Its ${[n ? refs : '', subs ? kids : ''].filter(Boolean).join(' and ')} move up to ${to}. No reference is deleted.`;
8129
+ }
8130
+ if (n && subs) return `Its ${refs} move to Uncategorized and its ${kids} to the top level. No reference is deleted.`;
8131
+ return n ? `Its ${refs} move to Uncategorized. No reference is deleted.` : `Its ${kids} move to the top level. No reference is deleted.`;
8132
+ }
8133
+
8134
+ function kbCatStartEdit(edit) {
8135
+ kbCloseConfirm();
8136
+ // The box saves against the categories as they were when it opened: a change made meanwhile elsewhere is refused, not overwritten.
8137
+ kbCatEdit = { ...edit, expected: kbCatExpected(knowledgeState) };
8138
+ if (edit.parentId) { kbCatCollapsed.delete(edit.parentId); kbCatSaveCollapsed(); }
8139
+ kbInvalidateRefs();
8140
+ if (knowledgeState) paintKnowledge(knowledgeState);
8141
+ const input = $wsKnowledge.querySelector('.kb-cat-input');
8142
+ if (input) { input.focus(); input.select(); }
8143
+ }
8144
+ function kbCatEndEdit(focus) {
8145
+ kbCatEdit = null;
8146
+ kbCatFocus = focus || null;
8147
+ kbInvalidateRefs();
8148
+ if (knowledgeState) paintKnowledge(knowledgeState);
8149
+ }
8150
+ async function kbCatSaveEdit() {
8151
+ const input = $wsKnowledge.querySelector('.kb-cat-input');
8152
+ const e = kbCatEdit;
8153
+ if (!input || !e) return;
8154
+ const name = input.value.replace(/\s+/g, ' ').trim();
8155
+ if (!name) { showToast('Give the category a name.', 'warn'); input.focus(); return; }
8156
+ if (e.mode === 'rename') {
8157
+ const res = await kbCatOps([{ op: 'rename', id: e.id, name }], `Renamed the category to ${name}.`, { cat: e.id }, e.expected);
8158
+ if (res) kbCatEdit = null;
8159
+ } else {
8160
+ 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);
8161
+ if (res) {
8162
+ kbCatEdit = null;
8163
+ const id = res.created && res.created.new;
8164
+ if (e.then && e.then.sourceIds && id) await kbPlace(e.then.sourceIds, id);
8165
+ 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 });
8166
+ }
8167
+ }
8168
+ kbInvalidateRefs();
8169
+ if (knowledgeState) paintKnowledge(knowledgeState);
8170
+ }
8171
+
8172
+ /** Restore focus after a repaint, to the item that was acted on (or its neighbour when it is gone). */
8173
+ function kbCatRestoreFocus(refsHost) {
8174
+ const f = kbCatFocus;
8175
+ if (!f) return;
8176
+ kbCatFocus = null;
8177
+ const el = f.cat ? refsHost.querySelector(`[data-kb-cat-toggle="${CSS.escape(f.cat)}"]`)
8178
+ : f.row ? refsHost.querySelector(`[data-kb-open="${CSS.escape(f.row)}"]`)
8179
+ : f.selbar ? refsHost.querySelector('[data-kb-move-sel]') : null;
8180
+ const fallback = refsHost.querySelector('.kb-cat-toggle, .kb-fname');
8181
+ (el || fallback)?.focus({ preventScroll: false });
8182
+ }
8183
+
8184
+ /** The visible references in order — Shift+click ranges and the arrow keys walk this. */
8185
+ const kbVisibleRows = () => [...$wsKnowledge.querySelectorAll('.kb-refs-body .kb-src[data-source-id]')].map((el) => el.dataset.sourceId);
8186
+ const kbFocusables = () => [...$wsKnowledge.querySelectorAll('.kb-refs-body .kb-cat-toggle, .kb-refs-body .kb-fname')];
8187
+
8188
+ function kbSelectClick(sourceId, e) {
8189
+ kbSel = kbcSelect(kbSelFor(current, knowledgeState), sourceId, { toggle: e.ctrlKey || e.metaKey, shift: e.shiftKey }, kbVisibleRows());
8190
+ kbCatFocus = { row: sourceId };
8191
+ kbInvalidateRefs();
8192
+ if (knowledgeState) paintKnowledge(knowledgeState);
8193
+ const n = kbSel.selected.size;
8194
+ kbAnnounce(n ? `${n} selected.` : 'Nothing selected.');
8195
+ }
8196
+
8197
+ /** The click handler's category half; true when it handled the click. */
8198
+ function kbCatClick(e) {
8199
+ const t = e.target;
8200
+ const toggle = t.closest('[data-kb-cat-toggle]');
8201
+ if (toggle) {
8202
+ const id = toggle.dataset.kbCatToggle;
8203
+ const folded = kbCatCollapsedFor(current);
8204
+ if (folded.has(id)) folded.delete(id); else folded.add(id);
8205
+ kbCatSaveCollapsed();
8206
+ kbCatFocus = { cat: id };
8207
+ kbInvalidateRefs();
8208
+ if (knowledgeState) paintKnowledge(knowledgeState);
8209
+ return true;
8210
+ }
8211
+ const menu = t.closest('[data-kb-cat-menu]');
8212
+ if (menu) { kbShowCatMenu(menu); return true; }
8213
+ const rename = t.closest('[data-kb-cat-rename]');
8214
+ if (rename) {
8215
+ const cat = kbCats(knowledgeState).categories.find((c) => c.id === rename.dataset.kbCatRename);
8216
+ if (cat) kbCatStartEdit({ mode: 'rename', id: cat.id, name: cat.name });
8217
+ return true;
8218
+ }
8219
+ const sub = t.closest('[data-kb-cat-sub]');
8220
+ if (sub) { kbCatStartEdit({ mode: 'new', parentId: sub.dataset.kbCatSub }); return true; }
8221
+ const up = t.closest('[data-kb-cat-up], [data-kb-cat-down]');
8222
+ if (up) {
8223
+ const id = up.dataset.kbCatUp || up.dataset.kbCatDown;
8224
+ kbCloseConfirm();
8225
+ const ops = kbcReorderOps(kbCats(knowledgeState), id, up.hasAttribute('data-kb-cat-up') ? -1 : 1);
8226
+ if (ops) kbCatOps(ops, `Moved ${kbcLabel(kbCats(knowledgeState), id)} ${up.hasAttribute('data-kb-cat-up') ? 'up' : 'down'}.`, { cat: id });
8227
+ return true;
8228
+ }
8229
+ const catMove = t.closest('[data-kb-cat-move]');
8230
+ if (catMove) {
8231
+ const id = catMove.dataset.kbCatMove;
8232
+ const anchor = $wsKnowledge.querySelector(`[data-kb-cat-menu="${CSS.escape(id)}"]`) || catMove;
8233
+ kbShowMoveMenu(anchor, { categoryId: id });
8234
+ return true;
8235
+ }
8236
+ const del = t.closest('[data-kb-cat-delete]');
8237
+ if (del) {
8238
+ const id = del.dataset.kbCatDelete;
8239
+ kbShowCatDelete($wsKnowledge.querySelector(`[data-kb-cat-menu="${CSS.escape(id)}"]`) || del, id);
8240
+ return true;
8241
+ }
8242
+ const delGo = t.closest('[data-kb-cat-delete-go]');
8243
+ if (delGo) {
8244
+ const id = delGo.dataset.kbCatDeleteGo;
8245
+ const file = kbCats(knowledgeState);
8246
+ const cat = file.categories.find((c) => c.id === id);
8247
+ const parent = cat && cat.parentId ? kbcLabel(file, cat.parentId) : 'Uncategorized';
8248
+ const n = knowledgeState.sources.filter((r) => kbcPlacement(file, r.sourceId) === id).length;
8249
+ kbCloseConfirm();
8250
+ kbCatOps([{ op: 'delete', id }], `Deleted the category ${cat ? cat.name : ''}.${n ? ` ${n} reference${n === 1 ? '' : 's'} moved up to ${parent}.` : ''}`,
8251
+ cat && cat.parentId ? { cat: cat.parentId } : null);
8252
+ return true;
8253
+ }
8254
+ const newCat = t.closest('[data-kb-cat-new]');
8255
+ if (newCat) { kbCatStartEdit({ mode: 'new', parentId: null }); return true; }
8256
+ if (t.closest('[data-kb-cat-save]')) { kbCatSaveEdit(); return true; }
8257
+ if (t.closest('[data-kb-cat-cancel]')) {
8258
+ const e2 = kbCatEdit;
8259
+ kbCatEndEdit(e2 && e2.mode === 'rename' ? { cat: e2.id } : null);
8260
+ return true;
8261
+ }
8262
+ 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; }
8263
+ const moveSel = t.closest('[data-kb-move-sel]');
8264
+ if (moveSel) { kbShowMoveMenu(moveSel, { sourceIds: [...kbSelFor(current, knowledgeState).selected] }); return true; }
8265
+ const rowMove = t.closest('[data-kb-row-move]');
8266
+ if (rowMove) {
8267
+ const id = rowMove.dataset.kbRowMove;
8268
+ const anchor = $wsKnowledge.querySelector(`[data-kb-open="${CSS.escape(id)}"]`) || rowMove;
8269
+ const sel = kbSelFor(current, knowledgeState).selected;
8270
+ kbShowMoveMenu(anchor, { sourceIds: sel.has(id) ? [...sel] : [id] });
8271
+ return true;
8272
+ }
8273
+ if (t.closest('[data-kb-sel-clear]')) {
8274
+ kbSel = { selected: new Set(), anchor: null };
8275
+ kbAnnounce('Nothing selected.');
8276
+ kbInvalidateRefs();
8277
+ if (knowledgeState) paintKnowledge(knowledgeState);
8278
+ const first = $wsKnowledge.querySelector('.kb-refs-body .kb-fname');
8279
+ if (first) first.focus();
8280
+ return true;
8281
+ }
8282
+ const go = t.closest('[data-kb-move-go]');
8283
+ if (go) {
8284
+ const pop = go.closest('.hist-confirm');
8285
+ const what = pop && pop.kbWhat;
8286
+ const to = go.dataset.kbMoveGo || null;
8287
+ kbCloseConfirm();
8288
+ if (what && what.categoryId) {
8289
+ const file = kbCats(knowledgeState);
8290
+ kbCatOps([{ op: 'move', id: what.categoryId, parentId: to }], `Moved ${kbcLabel(file, what.categoryId)} to ${to ? kbcLabel(file, to) : 'the top level'}.`, { cat: what.categoryId });
8291
+ if (to) { kbCatCollapsed.delete(to); kbCatSaveCollapsed(); }
8292
+ } else if (what && what.sourceIds) kbPlace(what.sourceIds, to);
8293
+ return true;
8294
+ }
8295
+ const moveNew = t.closest('[data-kb-move-new]');
8296
+ if (moveNew) {
8297
+ const pop = moveNew.closest('.hist-confirm');
8298
+ const what = pop && pop.kbWhat;
8299
+ kbCatStartEdit({ mode: 'new', parentId: null, then: what || null });
8300
+ return true;
8301
+ }
8302
+ // Selection: Ctrl/Cmd or Shift on a row (its name included) selects instead of opening.
8303
+ const row = t.closest('.kb-src[data-source-id]');
8304
+ if (row && (e.ctrlKey || e.metaKey || e.shiftKey) && !t.closest('[data-kb-toggle], [data-kb-remove], .kb-ds-mi, [data-company-promote]')) {
8305
+ e.preventDefault();
8306
+ kbSelectClick(row.dataset.sourceId, e);
8307
+ return true;
8308
+ }
8309
+ return false;
8310
+ }
8311
+
8312
+ function kbShowRowMenu(fname) {
8313
+ const row = fname.closest('.kb-src[data-source-id]');
8314
+ if (!row) return;
8315
+ const id = row.dataset.sourceId;
8316
+ const name = fname.textContent || 'this reference';
8317
+ const tog = row.querySelector('[data-kb-toggle]');
8318
+ const on = tog && tog.getAttribute('aria-checked') === 'true';
8319
+ const src = knowledgeState && knowledgeState.sources.find((x) => x.sourceId === id);
8320
+ const promote = src && src.kind === 'file';
8321
+ const pop = kbCatPop(fname,
8322
+ (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>` : '') +
8323
+ `<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>` +
8324
+ (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>` : '') +
8325
+ `<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>`,
8326
+ `More for ${name}`, 'menu');
8327
+ const first = pop && pop.querySelector('.kb-ds-mi');
8328
+ if (first) first.focus();
8329
+ }
8330
+
8331
+ /** 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. */
8332
+ function kbCatKeydown(e) {
8333
+ const t = e.target;
8334
+ if (t.classList && t.classList.contains('kb-cat-input')) {
8335
+ if (e.key === 'Enter') { e.preventDefault(); kbCatSaveEdit(); return true; }
8336
+ if (e.key === 'Escape') { e.preventDefault(); const e2 = kbCatEdit; kbCatEndEdit(e2 && e2.mode === 'rename' ? { cat: e2.id } : null); return true; }
8337
+ return false;
8338
+ }
8339
+ const pop = t.closest && t.closest('.kb-cat-menu, .hist-confirm');
8340
+ if (pop && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
8341
+ const items = [...pop.querySelectorAll('.kb-ds-mi')];
8342
+ const at = items.indexOf(t);
8343
+ if (at >= 0) { e.preventDefault(); items[(at + (e.key === 'ArrowDown' ? 1 : items.length - 1)) % items.length].focus(); return true; }
8344
+ }
8345
+ if (pop && e.key === 'Escape') {
8346
+ // Back to the control that opened it (the menu button, the row, the category, or the selection bar).
8347
+ const el = pop.kbAnchor;
8348
+ kbCloseConfirm();
8349
+ if (el && el.isConnected) el.focus();
8350
+ e.preventDefault();
8351
+ return true;
8352
+ }
8353
+ // Ctrl/Cmd+A anywhere in References (not in a text box) selects every visible reference, like a file list.
8354
+ if ((e.key === 'a' || e.key === 'A') && (e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && t.closest
8355
+ && t.closest('.kb-refs-body') && !t.closest('input, textarea, [contenteditable="true"]')) {
8356
+ const rows = kbVisibleRows();
8357
+ // Never the browser's own select-all here: with every category folded it would select the whole page's text.
8358
+ e.preventDefault();
8359
+ if (!rows.length) { kbAnnounce('No references are shown to select. Open a category to see its references.'); return true; }
8360
+ kbSel = kbcSelectAll(kbSelFor(current, knowledgeState), rows);
8361
+ // The repaint replaces the focused control; bring focus back to the same row or category so Escape and the arrows still work.
8362
+ const cat = t.closest('[data-kb-cat-toggle]'), row = t.closest('.kb-src[data-source-id]');
8363
+ kbCatFocus = cat ? { cat: cat.dataset.kbCatToggle } : row ? { row: row.dataset.sourceId } : null;
8364
+ kbInvalidateRefs();
8365
+ if (knowledgeState) paintKnowledge(knowledgeState);
8366
+ kbAnnounce(`All ${rows.length} selected.`);
8367
+ return true;
8368
+ }
8369
+ const catBtn = t.closest && t.closest('.kb-cat-toggle');
8370
+ const fname = t.closest && t.closest('.kb-refs-body .kb-fname');
8371
+ // Escape clears the selection from anywhere in the list, a selected name included (where a Ctrl+click leaves focus).
8372
+ if (e.key === 'Escape' && kbSel.selected.size && t.closest && t.closest('.kb-refs-body')) { $wsKnowledge.querySelector('[data-kb-sel-clear]')?.click(); return true; }
8373
+ if (!catBtn && !fname) return false;
8374
+ const menuKey = e.key === 'ContextMenu' || (e.key === 'F10' && e.shiftKey);
8375
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
8376
+ if (catBtn && e.altKey) {
8377
+ const id = catBtn.dataset.kbCatToggle;
8378
+ if (id === 'uncategorized') return true;
8379
+ e.preventDefault();
8380
+ const dir = e.key === 'ArrowUp' ? -1 : 1;
8381
+ const ops = kbcReorderOps(kbCats(knowledgeState), id, dir);
8382
+ if (ops) kbCatOps(ops, `Moved ${kbcLabel(kbCats(knowledgeState), id)} ${dir < 0 ? 'up' : 'down'}.`, { cat: id });
8383
+ return true;
8384
+ }
8385
+ const all = kbFocusables();
8386
+ const at = all.indexOf(catBtn || fname);
8387
+ const next = all[at + (e.key === 'ArrowDown' ? 1 : -1)];
8388
+ if (next) { e.preventDefault(); next.focus(); if (e.shiftKey && fname && next.classList.contains('kb-fname')) kbSelectClick(next.closest('.kb-src').dataset.sourceId, { shiftKey: true }); }
8389
+ return true;
8390
+ }
8391
+ if (catBtn && (e.key === 'ArrowRight' || e.key === 'ArrowLeft')) {
8392
+ const id = catBtn.dataset.kbCatToggle;
8393
+ const open = catBtn.getAttribute('aria-expanded') === 'true';
8394
+ if ((e.key === 'ArrowRight') !== open) { e.preventDefault(); catBtn.click(); }
8395
+ return true;
8396
+ }
8397
+ if (fname && e.key === ' ') { e.preventDefault(); kbSelectClick(fname.closest('.kb-src').dataset.sourceId, { ctrlKey: true }); return true; }
8398
+ if (e.key === 'Delete') {
8399
+ e.preventDefault();
8400
+ if (catBtn) { const id = catBtn.dataset.kbCatToggle; if (id !== 'uncategorized') kbShowCatDelete(catBtn, id); }
8401
+ else fname.closest('.kb-src').querySelector('[data-kb-remove]')?.click();
8402
+ return true;
8403
+ }
8404
+ if (menuKey) {
8405
+ e.preventDefault();
8406
+ if (catBtn) { const more = catBtn.parentElement.querySelector('[data-kb-cat-menu]'); if (more) kbShowCatMenu(more); }
8407
+ else kbShowRowMenu(fname);
8408
+ return true;
8409
+ }
8410
+ return false;
8411
+ }
8412
+
8413
+ /** A row menu's choices act through the row's own controls, so they keep every rule those controls have. */
8414
+ function kbRowAct(btn) {
8415
+ const id = btn.dataset.kbRowId;
8416
+ const row = $wsKnowledge.querySelector(`.kb-src[data-source-id="${CSS.escape(id)}"]`);
8417
+ kbCloseConfirm();
8418
+ if (!row) return;
8419
+ const act = btn.dataset.kbRowAct;
8420
+ if (act === 'promote') {
8421
+ const src = knowledgeState && knowledgeState.sources.find((x) => x.sourceId === id);
8422
+ if (src) openCompanyKnowledge({ sourceId: src.sourceId, filename: src.filename || 'untitled', mime: src.mime }, row.querySelector('.kb-fname'));
8423
+ return;
8424
+ }
8425
+ const target = act === 'toggle' ? row.querySelector('[data-kb-toggle]') : row.querySelector('[data-kb-remove]');
8426
+ if (target) target.click();
8427
+ }
8428
+
8429
+ // Drag and drop. A drag carries the selection when the dragged row is in it, else just that row. Files from the desktop
8430
+ // dropped on a category are added straight into it (the server files them only for the person's own drop).
8431
+ let kbDragIds = null;
8432
+ let kbDragHover = null; // { el, timer }
8433
+ function kbDragChip(n, name) {
8434
+ const chip = document.createElement('div');
8435
+ chip.className = 'kb-drag-chip';
8436
+ chip.textContent = n === 1 ? name : `${n} references`;
8437
+ document.body.appendChild(chip);
8438
+ setTimeout(() => chip.remove(), 0);
8439
+ return chip;
8440
+ }
8441
+ function kbDropTargetOf(e) {
8442
+ const el = e.target.closest && e.target.closest('[data-kb-drop-cat]');
8443
+ return el && el.closest('.kb-refs-body') ? el : null;
8444
+ }
8445
+ /** Open a folded category during a drag without repainting the column (the dragged row must survive). */
8446
+ function kbCatExpandInPlace(id) {
8447
+ const head = $wsKnowledge.querySelector(`.kb-cat[data-kb-drop-cat="${CSS.escape(id)}"]`);
8448
+ if (!head || !knowledgeState) return;
8449
+ const file = kbCats(knowledgeState);
8450
+ const rows = knowledgeState.sources.filter((r) => !kbInDesignSet(r, knowledgeState) && kbcPlacement(file, r.sourceId) === id);
8451
+ const depth = Number((head.getAttribute('style') || '').match(/--kb-depth:(d+)/)?.[1] || 0);
8452
+ head.classList.add('open');
8453
+ head.querySelector('.kb-cat-toggle')?.setAttribute('aria-expanded', 'true');
8454
+ head.insertAdjacentHTML('afterend', rows.map((r) => kbSourceRow(r, knowledgeState, depth + 1)).join(''));
8455
+ }
8456
+
8457
+ function kbClearDropHover() {
8458
+ if (!kbDragHover) return;
8459
+ kbDragHover.el.classList.remove('drop-target');
8460
+ kbDragHover.el.removeAttribute('data-drop-label');
8461
+ clearTimeout(kbDragHover.timer);
8462
+ kbDragHover = null;
8463
+ }
8464
+
7704
8465
  /**
7705
8466
  * #2131: a queued organize whose start met work already changing the project. Only what was recorded is said — when
7706
8467
  * the AI last tried and who held the project — never that it starts by itself: nothing here can tell whether that AI
@@ -7802,49 +8563,6 @@
7802
8563
  // way across re-renders (no visual jitter on a poll tick / repaint) without needing a persisted
7803
8564
  // layout. The force pass then relaxes overlaps via simple repulsion + edge-spring + centering.
7804
8565
  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
8566
  // View-only pan/zoom: we mutate the live SVG viewBox, never re-layout. The base 0 0 W H box IS the
7849
8567
  // fit; the Fit button + Home key restore it, and it shows only while zoomed/panned. Zoom resets on a
7850
8568
  // generation re-render (rare) — ponytail: persisting it across re-layouts isn't worth the state.
@@ -7896,7 +8614,8 @@
7896
8614
  // loading + error REUSE the file viewer's own message idiom (.kb-view-msg / .kb-view-spin /
7897
8615
  // .kb-view-ico.err / .primary Retry) so the graph's "can't show content yet" states look identical
7898
8616
  // 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>'; }
8617
+ /** The first layout is still being worked out; `note` (the loading line with Stop) shows above it, so a big map can be stopped. */
8618
+ 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
8619
  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
8620
  // Whitelist the LLM-derived page type into a SAFE single class token — never interpolate it raw (a
7902
8621
  // space would inject extra classes). Same discipline as KB_CHIP; an unknown type falls back to the
@@ -8053,23 +8772,271 @@
8053
8772
  // ── Stage C: the knowledge graph + page viewer ──────────────────────────────────
8054
8773
  // Same alive()/epoch/key contract as kbLoadPreview above — the render only happens if nothing else
8055
8774
  // (a new epoch, a changed key, a project switch, or leaving the pane) superseded this fetch meanwhile.
8775
+ // ── #2491 R6.9: the knowledge map — streamed, laid out off the main thread, coloured by the person's categories ──
8776
+ // The pure half is web/kb-categories.js (kbg*). This screen holds the whole map of the current generation: it asks for
8777
+ // chunks until there is no next, keeps links by slug until both ends have arrived, and filters and colours it itself
8778
+ // from the current categories, so a move in the tree recolours the map without asking the server again.
8779
+ let kbGm = null; // { projId, model, layoutKey, pos: Map(id → {x,y}), w, h, stopped, error, loading }
8780
+ const kbGo = { hiddenCats: new Set(), hiddenTypes: new Set(), search: '', neighbourOf: null, list: false };
8781
+ let kbGWorker = null, kbGEpoch = 0, kbGFocus = null;
8782
+
8783
+ function kbGraphResetOpts() {
8784
+ kbGo.hiddenCats = new Set(); kbGo.hiddenTypes = new Set(); kbGo.search = ''; kbGo.neighbourOf = null;
8785
+ }
8786
+ function kbGraphStopWorker() {
8787
+ if (kbGWorker) { try { kbGWorker.terminate(); } catch { /* gone */ } kbGWorker = null; }
8788
+ kbGEpoch += 1;
8789
+ }
8790
+
8056
8791
  async function kbLoadGraph(proj) {
8057
8792
  const epoch = viewEpoch, key = lastViewKey;
8058
8793
  const alive = () => epoch === viewEpoch && key === lastViewKey && current && current.id === proj.id && !$wsKnowledge.hidden;
8059
8794
  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);
8795
+ const want = knowledgeState && knowledgeState.currentGeneration ? knowledgeState.currentGeneration.generationId : null;
8796
+ // The same generation, already complete: draw it again (recoloured from the current categories), no fetch.
8797
+ if (kbGm && kbGm.projId === proj.id && kbGm.model.generationId === want && kbGm.model.done && !kbGm.error) {
8798
+ kbGraphIndex = kbGm.model.index || null;
8799
+ kbGraphRender(true);
8068
8800
  if (knowledgeState) kbPaintStepHead(knowledgeState);
8801
+ return;
8802
+ }
8803
+ // "Load the rest" after Stop carries on from the last chunk that arrived, keeping what is already drawn.
8804
+ const resume = !!(kbGm && kbGm.resume && kbGm.projId === proj.id && kbGm.model.generationId === want
8805
+ && kbGm.next !== null && kbGm.next !== undefined && !kbGm.error);
8806
+ if (!kbGm || kbGm.projId !== proj.id) kbGraphResetOpts();
8807
+ kbGraphStopWorker();
8808
+ if (resume) Object.assign(kbGm, { stopped: false, loading: true, resume: false });
8809
+ 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 };
8810
+ try {
8811
+ let generation = resume ? kbGm.model.generationId : null; let cursor = resume ? kbGm.next : 0; let restarts = 0;
8812
+ for (;;) {
8813
+ const q = generation ? `?generation=${encodeURIComponent(generation)}&cursor=${cursor}` : '';
8814
+ const r = await fetch(`/api/projects/${encodeURIComponent(proj.id)}/knowledge/graph${q}`, { signal: ac.signal, cache: 'no-store' });
8815
+ if (!r.ok) throw new Error(`graph ${r.status}`);
8816
+ const body = await r.json();
8817
+ if (!body || !body.graph) throw new Error('bad graph envelope');
8818
+ if (!alive()) return;
8819
+ const g = body.graph;
8820
+ if (g.restart) {
8821
+ // Organized again while the map was coming in: start over on the new generation (a few times at most).
8822
+ if (++restarts > 3) throw new Error('the map kept changing');
8823
+ generation = g.generationId; cursor = 0;
8824
+ kbGm.model = kbgCreate(generation); kbGm.pos = new Map(); kbGm.layoutKey = null;
8825
+ continue;
8826
+ }
8827
+ if (!Array.isArray(g.nodes)) throw new Error('bad graph envelope');
8828
+ if (!generation) { generation = g.generationId; kbGm.model = kbgCreate(generation); }
8829
+ kbgMerge(kbGm.model, g);
8830
+ kbGm.next = g.next ?? null;
8831
+ kbGraphIndex = kbGm.model.index || null;
8832
+ kbGm.loading = g.next !== null && g.next !== undefined && !kbGm.stopped;
8833
+ kbGraphRender(!kbGm.loading);
8834
+ if (knowledgeState) kbPaintStepHead(knowledgeState);
8835
+ if (!kbGm.loading) break;
8836
+ cursor = g.next;
8837
+ }
8069
8838
  } catch (err) {
8070
8839
  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)
8840
+ 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); }
8841
+ }
8842
+ }
8843
+
8844
+ /** Lay out what is drawn now, off the main thread; a newer request (or closing the map) drops the older one. */
8845
+ function kbGraphLayout(view, done) {
8846
+ kbGraphStopWorker();
8847
+ const epoch = kbGEpoch;
8848
+ const ids = view.nodes.map((n) => n.id);
8849
+ const index = new Map(ids.map((id, i) => [id, i]));
8850
+ const edges = new Int32Array(view.edges.length * 2);
8851
+ view.edges.forEach(([a, b], i) => { edges[i * 2] = index.get(a); edges[i * 2 + 1] = index.get(b); });
8852
+ const seeds = Uint32Array.from(ids, (id) => kbHash(id));
8853
+ const finish = (x, y, w, h) => {
8854
+ if (epoch !== kbGEpoch || !kbGm) return;
8855
+ kbGm.pos = new Map(ids.map((id, i) => [id, { x: x[i], y: y[i] }]));
8856
+ kbGm.w = w; kbGm.h = h;
8857
+ done();
8858
+ };
8859
+ try {
8860
+ kbGWorker = new Worker('/kb-graph-worker.js');
8861
+ kbGWorker.onmessage = (ev) => { const m = ev.data || {}; if (m.epoch === epoch) { finish(m.x, m.y, m.w, m.h); kbGraphStopWorker(); } };
8862
+ kbGWorker.onerror = () => { kbGraphStopWorker(); if (kbGm) { kbGm.error = 'layout'; const h = kbViewHost(); if (h && viewer.mode === 'graph') h.innerHTML = kbGraphError(); } };
8863
+ kbGWorker.postMessage({ epoch, n: ids.length, edges, seeds }, [edges.buffer, seeds.buffer]);
8864
+ } catch {
8865
+ kbGraphStopWorker();
8866
+ if (kbGm) { kbGm.error = 'layout'; const h = kbViewHost(); if (h && viewer.mode === 'graph') h.innerHTML = kbGraphError(); }
8867
+ }
8868
+ }
8869
+
8870
+ const KB_TYPE_LABEL = { source: 'Source', concept: 'Concept', person: 'Person' };
8871
+ function kbGraphNodeHtml(n, view, file) {
8872
+ const p = kbGm.pos.get(n.id);
8873
+ if (!p) return '';
8874
+ const m = view.member.get(n.id) || { cats: [], grouped: false };
8875
+ const cats = m.cats.slice(0, 3);
8876
+ const col = kbgColour(file, cats[0] || null);
8877
+ const label = n.kind === 'document' ? (n.filename || 'document') : (n.title || n.slug);
8878
+ const where = !m.grouped ? 'Not yet grouped' : m.cats.map((c) => (c === 'uncategorized' ? 'Uncategorized' : kbcLabel(file, c))).join(', ');
8879
+ const more = m.cats.length > 3 ? ` (+${m.cats.length - 3})` : '';
8880
+ // A document removed since the map was loaded is shown as gone at once: the cached map keeps the old flag.
8881
+ const gone = n.kind === 'document' && (n.present === false || !!(knowledgeState && !knowledgeState.sources.some((s) => s.sourceId === n.sourceId)));
8882
+ const kind = n.kind === 'document' ? (gone ? 'document, no longer in Knowledge' : 'document') : (KB_TYPE_LABEL[n.type] || 'Concept').toLowerCase() + ' page';
8883
+ const tip = `${label} · ${kind} · ${where}${more}`;
8884
+ const match = view.matchSet.has(n.id) ? ' match' : '';
8885
+ 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}`;
8886
+ const act = n.kind === 'document' ? `data-kb-doc="${escapeAttr(n.sourceId)}"` : `data-kb-node="${escapeAttr(n.slug)}"`;
8887
+ const shape = n.kind === 'document'
8888
+ ? '<rect class="kb-g-dot" x="-7" y="-7" width="14" height="14" rx="3"/>'
8889
+ : '<circle class="kb-g-dot" r="8"/>';
8890
+ 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('');
8891
+ 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)}"` +
8892
+ ` style="--kbg-c:var(${col.token})" transform="translate(${p.x.toFixed(1)},${p.y.toFixed(1)})">` +
8893
+ `<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>`;
8894
+ }
8895
+
8896
+ function kbGraphControlsHtml(view, file) {
8897
+ const legend = kbgLegend(kbGm.model, file).map((c) =>
8898
+ `<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)}"` +
8899
+ ` 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('');
8900
+ const types = ['source', 'concept', 'person'].map((t) =>
8901
+ `<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('');
8902
+ const hidden = kbGo.hiddenCats.size || kbGo.hiddenTypes.size;
8903
+ const found = kbGo.search ? `<span class="kb-gfound" role="status">${view.matches.length} found</span>` : '';
8904
+ return '<div class="kb-graph-sub kb-graph-ctl">' +
8905
+ `<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>` +
8906
+ `<div class="kb-g-types" role="group" aria-label="Show page types">${types}</div>` +
8907
+ '<div class="kb-g-tools">' +
8908
+ `<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}` +
8909
+ `<button type="button" class="kb-gneigh" role="switch" aria-checked="${kbGo.neighbourOf ? 'true' : 'false'}" data-kb-gneigh data-command-id="shell.kb-graph-neighbourhood"` +
8910
+ ` 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>` +
8911
+ '<span class="kb-gseg" role="group" aria-label="Show as">' +
8912
+ `<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>` +
8913
+ `<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>` +
8914
+ '</div></div>';
8915
+ }
8916
+
8917
+ function kbGraphNotesHtml(view, file) {
8918
+ const m = kbGm.model;
8919
+ const notes = [];
8920
+ 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>`);
8921
+ 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>`);
8922
+ if (view.capped) {
8923
+ 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(' · ');
8924
+ 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
8925
  }
8926
+ if (m.truncated) notes.push('<span>Some knowledge pages could not be read, so the map is incomplete.</span>');
8927
+ 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>');
8928
+ 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>`);
8929
+ return notes.length ? `<div class="kb-view-note kb-gnotes" role="status">${notes.join('<br>')}</div>` : '';
8930
+ }
8931
+
8932
+ /** The same nodes as an accessible list, grouped by category. */
8933
+ function kbGraphListHtml(view, file) {
8934
+ const groups = new Map();
8935
+ for (const n of view.nodes) {
8936
+ const m = view.member.get(n.id);
8937
+ // Under the first of its categories that is shown (a page drawn from two can be listed under either).
8938
+ const key = !m || !m.grouped ? 'ungrouped' : (m.cats.find((c) => !kbGo.hiddenCats.has(c)) || m.cats[0] || 'uncategorized');
8939
+ if (!groups.has(key)) groups.set(key, []);
8940
+ groups.get(key).push(n);
8941
+ }
8942
+ const name = (k) => (k === 'ungrouped' ? 'Not yet grouped' : k === 'uncategorized' ? 'Uncategorized' : kbcLabel(file, k));
8943
+ const order = [...kbcChildren(file, null).map((c) => c.id), 'uncategorized', 'ungrouped'].filter((k) => groups.has(k));
8944
+ 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>` +
8945
+ groups.get(k).sort((a, b) => String(a.title || a.filename).localeCompare(String(b.title || b.filename))).map((n) => {
8946
+ const act = n.kind === 'document' ? `data-kb-doc="${escapeAttr(n.sourceId)}"` : `data-kb-node="${escapeAttr(n.slug)}"`;
8947
+ const kind = n.kind === 'document' ? 'document' : `${(KB_TYPE_LABEL[n.type] || 'Concept').toLowerCase()} page`;
8948
+ 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>`;
8949
+ }).join('') + '</ul></section>').join('') + '</div>';
8950
+ }
8951
+
8952
+ /** Paint the map: controls, notes, and the drawing (laid out first when what is drawn changed). */
8953
+ function kbGraphRender(final) {
8954
+ const host = kbViewHost();
8955
+ if (!host || viewer.mode !== 'graph' || !kbGm) return;
8956
+ const file = kbCats(knowledgeState);
8957
+ const view = kbgView(kbGm.model, file, kbGo);
8958
+ view.matchSet = new Set(view.matches);
8959
+ kbGm.view = view; // what is drawn now, even while its layout is still being computed (the announcement reads it)
8960
+ if (!kbGm.model.nodes.size && !kbGm.loading) { host.innerHTML = kbGm.model.truncated ? kbGraphTruncatedEmpty() : kbGraphEmpty(knowledgeState); return; }
8961
+ const layoutKey = view.nodes.map((n) => n.id).join('\n') + '|' + view.edges.length;
8962
+ const paint = () => {
8963
+ const h = kbViewHost();
8964
+ if (!h || viewer.mode !== 'graph' || !kbGm) return;
8965
+ const focusId = document.activeElement && document.activeElement.dataset ? document.activeElement.dataset.kbGid : null;
8966
+ const searchHad = document.activeElement && document.activeElement.classList && document.activeElement.classList.contains('kb-gsearch');
8967
+ const W = Math.round(kbGm.w), H = Math.round(kbGm.h);
8968
+ const lines = view.edges.map(([a, b]) => { const p = kbGm.pos.get(a), q = kbGm.pos.get(b);
8969
+ 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('');
8970
+ const dots = view.nodes.map((n) => kbGraphNodeHtml(n, view, file)).join('');
8971
+ 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>';
8972
+ const body = kbGo.list ? kbGraphListHtml(view, file)
8973
+ : `<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>` +
8974
+ '<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>';
8975
+ h.innerHTML = '<section class="kb-col kb-graph">' + kbGraphControlsHtml(view, file) + kbGraphNotesHtml(view, file) + body + '</section>';
8976
+ kbGm.view = view;
8977
+ const back = (kbGFocus || focusId) && h.querySelector(`[data-kb-gid="${CSS.escape(kbGFocus || focusId)}"]`);
8978
+ if (back) back.focus({ preventScroll: true });
8979
+ kbGFocus = null;
8980
+ if (searchHad) { const s = h.querySelector('.kb-gsearch'); if (s) { s.focus(); s.setSelectionRange(s.value.length, s.value.length); } }
8981
+ };
8982
+ if (kbGo.list || layoutKey === kbGm.layoutKey) { paint(); return; }
8983
+ // While chunks are still arriving, lay out only now and then; the final chunk always lays out.
8984
+ if (!final && kbGm.layoutKey && kbGm.lastLayoutAt && Date.now() - kbGm.lastLayoutAt < 1500) { paint(); return; }
8985
+ kbGm.lastLayoutAt = Date.now();
8986
+ if (!kbGm.pos.size) host.innerHTML = kbGraphLoading(kbGraphNotesHtml(view, file));
8987
+ kbGraphLayout(view, () => { if (kbGm) kbGm.layoutKey = layoutKey; paint(); });
8988
+ }
8989
+
8990
+ /** The map's controls; true when handled. */
8991
+ function kbGraphClick(e) {
8992
+ const t = e.target;
8993
+ const cat = t.closest('[data-kb-gcat]');
8994
+ 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; }
8995
+ const type = t.closest('[data-kb-gtype]');
8996
+ 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; }
8997
+ if (t.closest('[data-kb-gall]')) { kbGo.hiddenCats.clear(); kbGo.hiddenTypes.clear(); kbGraphRender(true); kbAnnounceGraph(); return true; }
8998
+ const only = t.closest('[data-kb-gonly]');
8999
+ if (only) {
9000
+ const keep = only.dataset.kbGonly;
9001
+ kbGo.hiddenCats = new Set([...kbcChildren(kbCats(knowledgeState), null).map((c) => c.id), 'uncategorized', 'ungrouped'].filter((id) => id !== keep));
9002
+ kbGraphRender(true); kbAnnounceGraph(); return true;
9003
+ }
9004
+ if (t.closest('[data-kb-gneigh]')) {
9005
+ const focused = document.activeElement && document.activeElement.dataset ? document.activeElement.dataset.kbGid : null;
9006
+ kbGo.neighbourOf = kbGo.neighbourOf ? null : (kbGm && kbGm.lastNode) || focused || null;
9007
+ if (!kbGo.neighbourOf && !kbGm.lastNode) showToast('Point at a page or document on the map first, then choose Only neighbours.', 'warn');
9008
+ kbGFocus = kbGo.neighbourOf;
9009
+ kbGraphRender(true); kbAnnounceGraph(); return true;
9010
+ }
9011
+ const seg = t.closest('[data-kb-glist]');
9012
+ 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; }
9013
+ if (t.closest('[data-kb-gstop]')) { if (kbGm) { kbGm.stopped = true; } kbAbortPreview(); if (kbGm) { kbGm.loading = false; kbGraphRender(true); } return true; }
9014
+ if (t.closest('[data-kb-gmore]')) { lastViewKey = null; if (kbGm) kbGm.resume = true; if (knowledgeState) paintKnowledge(knowledgeState); return true; }
9015
+ const doc = t.closest('[data-kb-doc]');
9016
+ if (doc) {
9017
+ const id = doc.dataset.kbDoc;
9018
+ if (knowledgeState && knowledgeState.sources.some((s) => s.sourceId === id)) { setViewer({ mode: 'file', sourceId: id }); kbFocusSourceId = id; paintKnowledge(knowledgeState); }
9019
+ else showToast('That document is no longer in Knowledge. Organize again to update the map.', 'warn');
9020
+ return true;
9021
+ }
9022
+ return false;
9023
+ }
9024
+ function kbAnnounceGraph() {
9025
+ const v = kbGm && kbGm.view;
9026
+ if (v) kbAnnounce(`Showing ${v.nodes.length} item${v.nodes.length === 1 ? '' : 's'} on the map.`);
9027
+ }
9028
+ /** Hover or focus a node: its neighbours stand out, the rest steps back. */
9029
+ function kbGraphHighlight(id) {
9030
+ const svg = kbGraphSvgEl();
9031
+ if (!svg) return;
9032
+ svg.querySelectorAll('.near, .lit').forEach((el) => el.classList.remove('near', 'lit'));
9033
+ svg.classList.toggle('kb-hl', !!id);
9034
+ if (!id || !kbGm || !kbGm.view) return;
9035
+ kbGm.lastNode = id;
9036
+ const near = kbGm.view.adj.get(id) || new Set();
9037
+ svg.querySelector(`[data-kb-gid="${CSS.escape(id)}"]`)?.classList.add('near');
9038
+ for (const n of near) svg.querySelector(`[data-kb-gid="${CSS.escape(n)}"]`)?.classList.add('near');
9039
+ svg.querySelectorAll('.kb-g-edge').forEach((l) => { if (l.dataset.a === id || l.dataset.b === id) l.classList.add('lit'); });
8073
9040
  }
8074
9041
  /** `generationId` (optional) pins the read to one published generation — a workflow citation opens
8075
9042
  * the page AS IT READ when the workflow was built. Without it the route serves the current generation,
@@ -8424,9 +9391,16 @@
8424
9391
  const loose = st.sources.filter((source) => !kbInDesignSet(source, st));
8425
9392
  const inSet = st.sources.length - loose.length;
8426
9393
  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;
9394
+ // #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
9395
+ // make one. A categories file that cannot be read shows every reference flat and says so.
9396
+ kbSelFor(current, st);
9397
+ const tree = kbCatUsable(st) && kbCats(st).categories.length > 0;
9398
+ const newCat = kbCatUsable(st) && loose.length && !(kbCatEdit && kbCatEdit.mode === 'new' && !kbCatEdit.parentId)
9399
+ ? '<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>' : '';
9400
+ const flatEdit = !tree && kbCatEdit && kbCatEdit.mode === 'new' ? kbCatEditHtml(0) : '';
9401
+ const body = kbCatUnavailableHtml(st) + (loose.length
9402
+ ? (tree ? kbTreeHtml(st, loose) : flatEdit + loose.map((source) => kbSourceRow(source, st)).join(''))
9403
+ : (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
9404
  return '<section class="kb-col">' +
8431
9405
  '<div class="kb-refs-body">' + kbDesignSetStrip(st) +
8432
9406
  '<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 +9620,7 @@
8646
9620
  // DOM; suppressing the repaint while it's active (kbAdjustActive) is simpler and safer than
8647
9621
  // snapshotting/restoring every piece. lastRefsHtml is left stale, so the next tick (once the box is
8648
9622
  // inactive) catches the column up to the latest state.
8649
- if (html !== lastRefsHtml && !kbAdjustActive() && !kbDsPanelBusy()) {
9623
+ if (html !== lastRefsHtml && !kbAdjustActive() && !kbDsPanelBusy() && !kbCatEditActive() && !kbDragIds && !kbDragHover) {
8650
9624
  const oldBody = refsHost.querySelector('.kb-refs-body');
8651
9625
  const scrollTop = oldBody ? oldBody.scrollTop : 0;
8652
9626
  refsHost.innerHTML = html;
@@ -8662,6 +9636,7 @@
8662
9636
  kbFocusSourceId = null;
8663
9637
  }
8664
9638
  kbDsRestoreFocus(refsHost);
9639
+ kbCatRestoreFocus(refsHost);
8665
9640
  const shown = kbActiveDesignSet(st);
8666
9641
  if (kbFocusDesignSet && (shown ? shown.sourceId : null) === kbFocusDesignSet.sourceId) {
8667
9642
  const target = refsHost.querySelector('.kb-ds .kb-fname, .kb-ds button') || refsHost.querySelector('#kb-drop');
@@ -8672,6 +9647,8 @@
8672
9647
  }
8673
9648
 
8674
9649
  const key = kbViewKey(st);
9650
+ // #2491 R6.9: a category change recolours the open map from the current categories (no reload, no re-layout).
9651
+ if (key === lastViewKey && viewer.mode === 'graph' && kbGm && kbGm.catRev !== kbCats(st).revision) { kbGm.catRev = kbCats(st).revision; kbGraphRender(true); }
8675
9652
  if (key !== lastViewKey) {
8676
9653
  // The key can change WITHOUT setViewer() — e.g. a poll swaps a row's blobSha256 under an open
8677
9654
  // preview. Abort and bump the epoch here too, or the superseded download keeps streaming (its
@@ -8818,12 +9795,177 @@
8818
9795
  `<div class="company-entry-meta">Latest v${latestNumber} · ${escapeHtml(latest.filename)} · ${escapeHtml(kbBytes(latest.bytes))}` +
8819
9796
  (latest.provenance && latest.provenance.projectName
8820
9797
  ? ` · from ${escapeHtml(latest.provenance.projectName)}` : '') + '</div></div>' +
8821
- `<div class="company-entry-actions">${action}<button type="button" class="company-remove" ` +
9798
+ `<div class="company-entry-actions">${action}` +
9799
+ (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>` : '') +
9800
+ `<button type="button" class="company-remove" ` +
8822
9801
  `data-company-stage-remove="${escapeAttr(entry.librarySourceId)}" data-command-id="shell.company-remove" ` +
8823
9802
  `data-command-instance="${escapeAttr(entry.librarySourceId)}" data-command-instance-label="${escapeAttr(entry.displayName)}" ` +
8824
9803
  'data-tip="Remove this entry from company knowledge">Remove…</button></div></article>';
8825
9804
  }
8826
9805
 
9806
+ // #2491 R6.9: the company library's own categories. The dialog lists shared references by category, with New
9807
+ // category, Rename, Delete and a Move to… on each entry (no drag in a dialog). Each change carries the categories'
9808
+ // revision and the company folder this dialog drew, so a change made meanwhile elsewhere is never overwritten.
9809
+ let companyCatEdit = null; // { mode: 'new' | 'rename', id?, parentId?, name? }
9810
+ const companyTax = (state) => (state && state.taxonomy && Array.isArray(state.taxonomy.categories) ? state.taxonomy : { v: 1, revision: 0, categories: [], placements: {}, state: 'absent' });
9811
+ function companyCatEditHtml(depth) {
9812
+ const e = companyCatEdit;
9813
+ 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 || '') : ''}"` +
9814
+ ` 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">` +
9815
+ `<button type="button" class="primary" data-company-cat-save data-command-id="shell.kb-category-save">${e.mode === 'rename' ? 'Rename' : 'Create'}</button>` +
9816
+ '<button type="button" data-company-cat-cancel data-command-id="shell.kb-category-cancel">Cancel</button></div>';
9817
+ }
9818
+ function companyListHtml(entries, state) {
9819
+ const tax = companyTax(state);
9820
+ const usable = tax.state !== 'damaged' && tax.state !== 'newer';
9821
+ const head = '<div class="company-section-head"><div class="company-section-label">Shared references</div>' +
9822
+ (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>';
9823
+ 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>` +
9824
+ '<button type="button" data-company-cat-reset data-command-id="shell.kb-category-reset">Start again</button></div>';
9825
+ const topEdit = companyCatEdit && companyCatEdit.mode === 'new' && !companyCatEdit.parentId ? companyCatEditHtml(0) : '';
9826
+ if (!usable || !tax.categories.length) return head + warn + topEdit + entries.map((entry) => companyEntryHtml(entry, state)).join('');
9827
+ const byId = new Map(entries.map((e) => [e.librarySourceId, e]));
9828
+ const all = new Set(['uncategorized', ...tax.categories.map((c) => c.id)]);
9829
+ const items = kbcTreeItems(tax, entries.map((e) => ({ sourceId: e.librarySourceId })), all);
9830
+ let html = '';
9831
+ for (const item of items) {
9832
+ 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; }
9833
+ if (companyCatEdit && companyCatEdit.mode === 'rename' && companyCatEdit.id === item.id) { html += companyCatEditHtml(item.depth); continue; }
9834
+ const isU = item.kind === 'uncategorized';
9835
+ 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>` +
9836
+ (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>';
9837
+ if (companyCatEdit && companyCatEdit.mode === 'new' && companyCatEdit.parentId === item.id) html += companyCatEditHtml(item.depth + 1);
9838
+ }
9839
+ return head + topEdit + html;
9840
+ }
9841
+ async function companyCatPost(path, body, okMsg) {
9842
+ const state = companyKnowledgeState;
9843
+ if (companyKnowledgeBusy || !state || !state.available) return null;
9844
+ companyKnowledgeBusy = true; companySetError('');
9845
+ try {
9846
+ const res = await api(path, { method: 'POST', body: JSON.stringify({ expected: companyCatExpected(state), ...body }) });
9847
+ companyCatEdit = null;
9848
+ if (okMsg) showToast(okMsg, 'ok');
9849
+ return res;
9850
+ } catch (error) {
9851
+ const said = error && error.body && typeof error.body.error === 'string' && /^[A-Z]/.test(error.body.error) ? error.body.error : '';
9852
+ companySetError(said || 'FloLess could not change the company categories just now. Try again.');
9853
+ if (body.expected && error && error.body && error.body.code === 'knowledge-categories-changed') companyCatEdit = null;
9854
+ return null;
9855
+ } finally {
9856
+ companyKnowledgeBusy = false;
9857
+ try { await loadCompanyKnowledge(companyKnowledgeProjectId); } catch { /* the error line says what happened */ }
9858
+ renderCompanyKnowledge();
9859
+ }
9860
+ }
9861
+ /** What a company category change is checked against: the categories' revision and the company folder. */
9862
+ function companyCatExpected(state) {
9863
+ return { [KB_CAT_KEY]: String(companyTax(state).revision || 0), 'the company folder': `${state.companyId}|${state.path}` };
9864
+ }
9865
+ /** Open the company name box, remembering the categories it was opened on (see kbCatStartEdit). */
9866
+ function companyCatStartEdit(edit) {
9867
+ companyCatEdit = companyKnowledgeState ? { ...edit, expected: companyCatExpected(companyKnowledgeState) } : edit;
9868
+ renderCompanyKnowledge();
9869
+ const i = $companyKnowledgeList.querySelector('.company-cat-input');
9870
+ if (i) { i.focus(); i.select(); }
9871
+ }
9872
+ function companyCatSave() {
9873
+ const input = $companyKnowledgeList.querySelector('.company-cat-input');
9874
+ const e = companyCatEdit;
9875
+ if (!input || !e) return;
9876
+ const name = input.value.replace(/\s+/g, ' ').trim();
9877
+ if (!name) { companySetError('Give the category a name.'); input.focus(); return; }
9878
+ const pinned = e.expected ? { expected: e.expected } : {};
9879
+ if (e.mode === 'rename') companyCatPost('/api/company-knowledge/categories', { ops: [{ op: 'rename', id: e.id, name }], ...pinned }, `Renamed the company category to ${name}.`);
9880
+ else companyCatPost('/api/company-knowledge/categories', { ops: [{ op: 'create', name, parentId: e.parentId || null }], ...pinned }, `Created the company category ${name}.`);
9881
+ }
9882
+ function companyPop(anchor, html, label) {
9883
+ $companyKnowledgeList.querySelector('.company-pop')?.remove();
9884
+ const pop = document.createElement('div');
9885
+ pop.className = 'company-pop kb-ds-menu kb-cat-menu';
9886
+ pop.setAttribute('role', 'menu');
9887
+ pop.setAttribute('aria-label', label);
9888
+ pop.innerHTML = html;
9889
+ $companyKnowledgeList.appendChild(pop);
9890
+ const lr = $companyKnowledgeList.getBoundingClientRect(), br = anchor.getBoundingClientRect();
9891
+ // Below the button when it fits inside the dialog's visible area, else above it — never clipped by the scroll area.
9892
+ let clip = $companyKnowledgeList.parentElement;
9893
+ while (clip && clip !== document.body && !/(auto|scroll|hidden)/.test(getComputedStyle(clip).overflowY)) clip = clip.parentElement;
9894
+ const limit = Math.min(window.innerHeight, clip ? clip.getBoundingClientRect().bottom : window.innerHeight) - 8;
9895
+ const fits = br.bottom + 4 + pop.offsetHeight <= limit;
9896
+ pop.style.top = `${fits ? br.bottom - lr.top + $companyKnowledgeList.scrollTop + 4 : br.top - lr.top + $companyKnowledgeList.scrollTop - pop.offsetHeight - 4}px`;
9897
+ pop.style.left = `${Math.max(4, Math.min(br.right - lr.left - pop.offsetWidth, $companyKnowledgeList.clientWidth - pop.offsetWidth - 4))}px`;
9898
+ pop.dataset.back = anchor.dataset.companyCatMenu || anchor.dataset.companyMove || '';
9899
+ pop.querySelector('.kb-ds-mi')?.focus();
9900
+ return pop;
9901
+ }
9902
+ function companyMoveMenu(btn) {
9903
+ const state = companyKnowledgeState;
9904
+ const tax = companyTax(state);
9905
+ const id = btn.dataset.companyMove;
9906
+ const entry = state.sources.find((e) => e.librarySourceId === id);
9907
+ const now = kbcPlacement(tax, id);
9908
+ 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('');
9909
+ companyPop(btn, `<div class="kb-move-title">Move “${escapeHtml(entry ? entry.displayName : 'this reference')}” to</div>${items}`, 'Move shared reference');
9910
+ }
9911
+ function companyCatMenu(btn) {
9912
+ const id = btn.dataset.companyCatMenu;
9913
+ const cat = companyTax(companyKnowledgeState).categories.find((c) => c.id === id);
9914
+ const name = cat ? cat.name : 'this category';
9915
+ 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>` +
9916
+ `<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>` +
9917
+ `<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');
9918
+ }
9919
+ function companyCatDelete(btn) {
9920
+ const id = btn.dataset.companyCatDelete;
9921
+ const state = companyKnowledgeState;
9922
+ const tax = companyTax(state);
9923
+ const cat = tax.categories.find((c) => c.id === id);
9924
+ if (!cat) return;
9925
+ const rows = state.sources.filter((e) => !e.removedAt).map((e) => ({ sourceId: e.librarySourceId }));
9926
+ const anchor = $companyKnowledgeList.querySelector(`[data-company-cat-menu="${CSS.escape(id)}"]`) || btn;
9927
+ 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>` +
9928
+ '<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>' +
9929
+ `<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}`);
9930
+ pop.setAttribute('role', 'dialog');
9931
+ pop.classList.remove('kb-ds-menu');
9932
+ pop.classList.add('hist-confirm');
9933
+ }
9934
+ /** The dialog's category clicks; true when handled. */
9935
+ function companyCatClick(event) {
9936
+ const t = event.target;
9937
+ if (t.closest('[data-company-cat-new]')) { companyCatStartEdit({ mode: 'new', parentId: null }); return true; }
9938
+ const menu = t.closest('[data-company-cat-menu]');
9939
+ if (menu) { companyCatMenu(menu); return true; }
9940
+ const move = t.closest('[data-company-move]');
9941
+ if (move) { companyMoveMenu(move); return true; }
9942
+ const rename = t.closest('[data-company-cat-rename]');
9943
+ if (rename) {
9944
+ const cat = companyTax(companyKnowledgeState).categories.find((c) => c.id === rename.dataset.companyCatRename);
9945
+ if (cat) companyCatStartEdit({ mode: 'rename', id: cat.id, name: cat.name });
9946
+ return true;
9947
+ }
9948
+ const sub = t.closest('[data-company-cat-sub]');
9949
+ if (sub) { companyCatStartEdit({ mode: 'new', parentId: sub.dataset.companyCatSub }); return true; }
9950
+ const del = t.closest('[data-company-cat-delete]');
9951
+ if (del) { companyCatDelete(del); return true; }
9952
+ const delGo = t.closest('[data-company-cat-delete-go]');
9953
+ 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; }
9954
+ const go = t.closest('[data-company-move-go]');
9955
+ if (go) {
9956
+ const to = go.dataset.companyMoveGo || null;
9957
+ const tax = companyTax(companyKnowledgeState);
9958
+ companyCatPost('/api/company-knowledge/place', { librarySourceIds: [go.dataset.companyMoveId], categoryId: to }, `Moved it to ${to ? kbcLabel(tax, to) : 'Uncategorized'}.`);
9959
+ return true;
9960
+ }
9961
+ if (t.closest('[data-company-cat-save]')) { companyCatSave(); return true; }
9962
+ if (t.closest('[data-company-cat-cancel]')) { companyCatEdit = null; renderCompanyKnowledge(); return true; }
9963
+ if (t.closest('[data-company-pop-close]')) { $companyKnowledgeList.querySelector('.company-pop')?.remove(); return true; }
9964
+ 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; }
9965
+ if (!t.closest('.company-pop')) $companyKnowledgeList.querySelector('.company-pop')?.remove();
9966
+ return false;
9967
+ }
9968
+
8827
9969
  function renderCompanyKnowledge() {
8828
9970
  const state = companyKnowledgeState;
8829
9971
  $companyKnowledgeFolder.innerHTML = companyFolderHtml(state);
@@ -8865,7 +10007,7 @@
8865
10007
  } else {
8866
10008
  const entries = state.sources.filter((entry) => !entry.removedAt);
8867
10009
  $companyKnowledgeList.innerHTML = entries.length
8868
- ? '<div class="company-section-label">Shared references</div>' + entries.map((entry) => companyEntryHtml(entry, state)).join('')
10010
+ ? companyListHtml(entries, state)
8869
10011
  : '<div class="company-empty">No company references yet. Preview a project file and choose “Promote to company…”.</div>';
8870
10012
  }
8871
10013
 
@@ -8960,25 +10102,28 @@
8960
10102
  const entry = state.sources.find((row) => row.librarySourceId === companyKnowledgePending.librarySourceId && !row.removedAt);
8961
10103
  const latest = entry && entry.versions[entry.versions.length - 1];
8962
10104
  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`, {
10105
+ const res = await api(`/api/company-knowledge/sources/${encodeURIComponent(entry.librarySourceId)}/versions/${encodeURIComponent(latest.versionId)}/accept`, {
8964
10106
  method: 'POST', body: JSON.stringify({ projectId: companyKnowledgeProjectId }),
8965
10107
  });
8966
10108
  companyKnowledgePending = null;
8967
- showToast(`Added ${entry.displayName} v${entry.versions.length} to this project`, 'ok');
10109
+ // #2491 R6.9: where it went in this project's categories, and why.
10110
+ const placed = res && res.placement;
10111
+ 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
10112
  } else if (companyKnowledgePending?.kind === 'remove') {
8969
10113
  const entry = state.sources.find((row) => row.librarySourceId === companyKnowledgePending.librarySourceId);
8970
10114
  await api(`/api/company-knowledge/sources/${encodeURIComponent(companyKnowledgePending.librarySourceId)}`, { method: 'DELETE' });
8971
10115
  companyKnowledgePending = null;
8972
10116
  showToast(`${entry ? entry.displayName : 'Company reference'} removed`, 'ok');
8973
10117
  } else if (companyKnowledgePromotion) {
8974
- await api('/api/company-knowledge/promote', {
10118
+ const promoted = await api('/api/company-knowledge/promote', {
8975
10119
  method: 'POST', body: JSON.stringify({
8976
10120
  projectId: companyKnowledgeProjectId,
8977
10121
  sourceId: companyKnowledgePromotion.sourceId,
8978
10122
  librarySourceId: $companyPromotionLineage.value || null,
8979
10123
  }),
8980
10124
  });
8981
- showToast('Company reference published.', 'ok');
10125
+ const placed = promoted && promoted.placement;
10126
+ 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
10127
  companyKnowledgePromotion = null;
8983
10128
  }
8984
10129
  await loadCompanyKnowledge(companyKnowledgeProjectId);
@@ -8989,6 +10134,7 @@
8989
10134
 
8990
10135
  if ($companyKnowledgeModal) {
8991
10136
  $companyKnowledgeModal.addEventListener('click', (event) => {
10137
+ if (companyCatClick(event)) return;
8992
10138
  const folder = event.target.closest('[data-company-folder-choose]');
8993
10139
  if (folder) { chooseCompanyFolder(); return; }
8994
10140
  const accept = event.target.closest('[data-company-stage-accept]');
@@ -9005,6 +10151,24 @@
9005
10151
  onBackdropDismiss($companyKnowledgeModal, () => closeCompanyKnowledge());
9006
10152
  document.addEventListener('keydown', (event) => {
9007
10153
  if (!$companyKnowledgeModal.classList.contains('show')) return;
10154
+ // #2491 R6.9: the name box and the menus answer their own keys first; Escape closes them, not the dialog.
10155
+ if (event.target.classList && event.target.classList.contains('company-cat-input')) {
10156
+ if (event.key === 'Enter') { event.preventDefault(); companyCatSave(); return; }
10157
+ if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); companyCatEdit = null; renderCompanyKnowledge(); return; }
10158
+ }
10159
+ const pop = $companyKnowledgeList.querySelector('.company-pop');
10160
+ if (pop && event.key === 'Escape') {
10161
+ event.preventDefault(); event.stopPropagation();
10162
+ const back = pop.dataset.back; pop.remove();
10163
+ const el = back && ($companyKnowledgeList.querySelector(`[data-company-cat-menu="${CSS.escape(back)}"]`) || $companyKnowledgeList.querySelector(`[data-company-move="${CSS.escape(back)}"]`));
10164
+ if (el) el.focus();
10165
+ return;
10166
+ }
10167
+ if (pop && (event.key === 'ArrowDown' || event.key === 'ArrowUp')) {
10168
+ const items = [...pop.querySelectorAll('.kb-ds-mi, .hc-go')];
10169
+ const at = items.indexOf(document.activeElement);
10170
+ if (at >= 0) { event.preventDefault(); items[(at + (event.key === 'ArrowDown' ? 1 : items.length - 1)) % items.length].focus(); return; }
10171
+ }
9008
10172
  if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeCompanyKnowledge(); return; }
9009
10173
  if (event.key !== 'Tab') return;
9010
10174
  const focusable = [...$companyKnowledgeModal.querySelectorAll('button:not([hidden]):not(:disabled), input:not([hidden]):not(:disabled), [tabindex="0"]')]
@@ -9017,7 +10181,7 @@
9017
10181
  }
9018
10182
 
9019
10183
  // ── Knowledge verbs (each captures `proj` — the user may switch projects mid-await) ──
9020
- async function kbUpload(fileList) {
10184
+ async function kbUpload(fileList, categoryId) {
9021
10185
  const proj = current;
9022
10186
  const files = Array.from(fileList || []);
9023
10187
  if (!proj || !files.length) return;
@@ -9037,9 +10201,16 @@
9037
10201
  // Per file (#2491): one file FloLess cannot take (an old .doc, an unsupported type) never sinks the rest of the
9038
10202
  // drop, and it is named with the reason in the server's plain words.
9039
10203
  const res = await api(kbUrl(proj.id, '/sources'), { method: 'POST',
9040
- body: JSON.stringify({ files: uploads, partial: true, ...(proj.uuid ? { expectedProjectUuid: proj.uuid } : {}) }) });
10204
+ body: JSON.stringify({ files: uploads, partial: true, ...(proj.uuid ? { expectedProjectUuid: proj.uuid } : {}),
10205
+ ...(categoryId !== undefined ? { categoryId } : {}) }) });
9041
10206
  if (current !== proj) return;
9042
10207
  const n = (res.sources || []).length;
10208
+ // #2491 R6.9: dropped on a category — say where they went, and why when it was not that category.
10209
+ if (categoryId !== undefined && n) {
10210
+ const where = categoryId ? kbcLabel(kbCats(knowledgeState), categoryId) : 'Uncategorized';
10211
+ if (res.placement === 'placed' || categoryId === null) kbAnnounce(`Added ${n} reference${n === 1 ? '' : 's'} to ${where}.`);
10212
+ 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');
10213
+ }
9043
10214
  const missed = (res.results || []).filter((r) => r && r.outcome !== 'added');
9044
10215
  if (!missed.length) showToast(`Added ${n} reference${n === 1 ? '' : 's'}`, 'ok');
9045
10216
  else {
@@ -9653,6 +10824,10 @@
9653
10824
  // One delegated listener for the whole pane — the column is re-rendered wholesale on every state
9654
10825
  // change, so per-render wiring would leak handlers.
9655
10826
  $wsKnowledge.addEventListener('click', (e) => {
10827
+ // #2491 R6.9: categories, selection and Move to… first — their menus share the design set's menu look.
10828
+ const rowAct = e.target.closest('[data-kb-row-act]');
10829
+ if (rowAct) { kbRowAct(rowAct); return; }
10830
+ if (kbCatClick(e)) return;
9656
10831
  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
10832
  if (kbDsClick(e)) return;
9658
10833
  }
@@ -9723,6 +10898,8 @@
9723
10898
  return;
9724
10899
  }
9725
10900
  if (e.target.closest('[data-kb-fit]')) { const svg = kbGraphSvgEl(); if (svg) kbFitGraph(svg); return; }
10901
+ // The notes line (Stop, Load the rest) also shows above the first layout's spinner, outside .kb-graph.
10902
+ if (e.target.closest('.kb-graph, .kb-gnotes') && kbGraphClick(e)) return;
9726
10903
  // Open a graph node's page.
9727
10904
  const nodeEl = e.target.closest('[data-kb-node]');
9728
10905
  if (nodeEl) { setViewer({ mode: 'page', slug: nodeEl.getAttribute('data-kb-node') }); if (knowledgeState) paintKnowledge(knowledgeState); return; }
@@ -9813,6 +10990,7 @@
9813
10990
  // Graph nodes are keyboard-focusable (tabindex="0" role="button") but SVG <g> elements have no
9814
10991
  // native activation behaviour, so Enter/Space must be wired explicitly.
9815
10992
  $wsKnowledge.addEventListener('keydown', (e) => {
10993
+ if (kbCatKeydown(e)) return;
9816
10994
  // Home zooms the graph back to fit — but not while typing in the Adjust box (Home = line start there).
9817
10995
  if (e.key === 'Home' && !e.target.closest('input, textarea') && !e.target.isContentEditable) {
9818
10996
  const svg = kbGraphSvgEl();
@@ -9825,12 +11003,25 @@
9825
11003
  if (btn && btn.getAttribute('aria-disabled') !== 'true') kbAdjustSubmit();
9826
11004
  return;
9827
11005
  }
11006
+ const gnode = e.target.closest && e.target.closest('.kb-g-node[data-kb-gid]');
11007
+ if (gnode && kbGm && kbGm.view && ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight'].includes(e.key)) {
11008
+ e.preventDefault();
11009
+ const to = kbgNearest(kbGm.pos, gnode.dataset.kbGid, e.key, kbGm.view.nodes.map((x) => x.id));
11010
+ if (to) $wsKnowledge.querySelector(`.kb-g-node[data-kb-gid="${CSS.escape(to)}"]`)?.focus();
11011
+ return;
11012
+ }
11013
+ if (gnode && gnode.hasAttribute('data-kb-doc') && (e.key === 'Enter' || e.key === ' ')) { e.preventDefault(); gnode.dispatchEvent(new MouseEvent('click', { bubbles: true })); return; }
9828
11014
  if (e.key !== 'Enter' && e.key !== ' ') return;
9829
11015
  const n = e.target.closest('[data-kb-node]');
9830
11016
  if (n) { e.preventDefault(); setViewer({ mode: 'page', slug: n.getAttribute('data-kb-node') }); if (knowledgeState) paintKnowledge(knowledgeState); }
9831
11017
  });
9832
11018
  // Live-enable the Adjust submit as the user types (the draft is DOM-owned; see kbSyncAdjustSubmit).
9833
11019
  $wsKnowledge.addEventListener('input', (e) => { if (e.target && e.target.id === 'kb-adjust-input') kbSyncAdjustSubmit(); });
11020
+ // #2491 R6.9: the map's search highlights matches (it hides nothing); hover and focus light a node's neighbours.
11021
+ $wsKnowledge.addEventListener('input', (e) => { if (e.target && e.target.classList && e.target.classList.contains('kb-gsearch')) { kbGo.search = e.target.value; kbGraphRender(true); } });
11022
+ $wsKnowledge.addEventListener('mouseover', (e) => { const n = e.target.closest && e.target.closest('.kb-g-node[data-kb-gid]'); if (n) kbGraphHighlight(n.dataset.kbGid); });
11023
+ $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); });
11024
+ $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
11025
  // #2491 R6.3: Replace file… picks exactly one file.
9835
11026
  const $wsKnowledgeReplace = document.getElementById('ws-knowledge-replace');
9836
11027
  if ($wsKnowledgeReplace) $wsKnowledgeReplace.addEventListener('change', () => {
@@ -9848,18 +11039,81 @@
9848
11039
  const cur = $wsKnowledge.querySelector('.kb-drop.drag-over');
9849
11040
  if (cur) { cur.classList.remove('drag-over'); kbInvalidateRefs(); }
9850
11041
  };
9851
- $wsKnowledge.addEventListener('dragover', (e) => {
11042
+ // #2491 R6.9: dragging references (the selection, or one row) onto a category.
11043
+ $wsKnowledge.addEventListener('dragstart', (e) => {
11044
+ const row = e.target.closest && e.target.closest('.kb-src[data-source-id]');
11045
+ if (!row || !e.dataTransfer || !kbCats(knowledgeState).categories.length || !kbCatUsable(knowledgeState)) { if (row && e.dataTransfer) e.preventDefault(); return; }
11046
+ const id = row.dataset.sourceId;
11047
+ const sel = kbSelFor(current, knowledgeState).selected;
11048
+ kbDragIds = sel.has(id) ? kbVisibleRows().filter((x) => sel.has(x)) : [id];
11049
+ e.dataTransfer.effectAllowed = 'move';
11050
+ e.dataTransfer.setData(KB_REFS_MIME, JSON.stringify(kbDragIds));
11051
+ const name = row.querySelector('.kb-fname')?.childNodes[0]?.textContent || 'reference';
11052
+ try { e.dataTransfer.setDragImage(kbDragChip(kbDragIds.length, name), 12, 12); } catch { /* the browser's own image */ }
11053
+ // No cache invalidation here: a repaint during the drag would destroy this row and the browser would cancel the drop.
11054
+ // The paint guard holds repaints while a drag is in flight; the end of the drag catches the column up.
11055
+ row.classList.add('dragging');
11056
+ });
11057
+ $wsKnowledge.addEventListener('dragend', () => {
11058
+ kbDragIds = null;
11059
+ kbClearDropHover();
11060
+ $wsKnowledge.querySelectorAll('.kb-src.dragging').forEach((el) => el.classList.remove('dragging'));
11061
+ kbInvalidateRefs();
11062
+ if (knowledgeState) paintKnowledge(knowledgeState);
11063
+ });
11064
+ // dragenter and dragover both answer: a drop target must accept the drag on entering it, not only while over it.
11065
+ const kbOnDragOver = (e) => {
9852
11066
  e.preventDefault();
11067
+ const cat = kbDropTargetOf(e);
11068
+ const types = e.dataTransfer ? [...e.dataTransfer.types] : [];
11069
+ const refs = types.includes(KB_REFS_MIME) && kbDragIds;
11070
+ const files = types.includes('Files');
11071
+ if (cat && (refs || files)) {
11072
+ if (e.dataTransfer) e.dataTransfer.dropEffect = refs ? 'move' : 'copy';
11073
+ if (!kbDragHover || kbDragHover.el !== cat) {
11074
+ kbClearDropHover();
11075
+ cat.classList.add('drop-target');
11076
+ const id = cat.dataset.kbDropCat;
11077
+ const label = id === 'uncategorized' ? 'Uncategorized' : kbcLabel(kbCats(knowledgeState), id);
11078
+ const n = refs ? kbDragIds.length : (e.dataTransfer.items ? e.dataTransfer.items.length : 0);
11079
+ cat.setAttribute('data-drop-label', refs ? `Move ${n === 1 ? 'here' : `${n} here`}` : `Add ${n || ''} file${n === 1 ? '' : 's'} to ${label}`.replace(' ', ' '));
11080
+ // A folded category opens when held over it.
11081
+ const timer = setTimeout(() => {
11082
+ // Opening the folded category is the one repaint allowed mid-drag: it changes only that category's children,
11083
+ // never the dragged row.
11084
+ if (id !== 'uncategorized' && kbCatCollapsedFor(current).has(id)) { kbCatCollapsed.delete(id); kbCatSaveCollapsed(); kbCatExpandInPlace(id); }
11085
+ }, 600);
11086
+ kbDragHover = { el: cat, timer };
11087
+ }
11088
+ return;
11089
+ }
11090
+ if (kbDragHover && !cat) kbClearDropHover();
11091
+ if (refs && e.dataTransfer) e.dataTransfer.dropEffect = 'none';
9853
11092
  const dz = e.target.closest('#kb-drop');
9854
11093
  const cur = $wsKnowledge.querySelector('.kb-drop.drag-over');
9855
11094
  if (cur && cur !== dz) cur.classList.remove('drag-over');
9856
11095
  if (dz && !dz.classList.contains('drag-over')) { dz.classList.add('drag-over'); kbInvalidateRefs(); }
9857
- });
11096
+ };
11097
+ $wsKnowledge.addEventListener('dragenter', kbOnDragOver);
11098
+ $wsKnowledge.addEventListener('dragover', kbOnDragOver);
9858
11099
  $wsKnowledge.addEventListener('dragleave', (e) => { if (!$wsKnowledge.contains(e.relatedTarget)) kbClearDrag(); });
9859
11100
  $wsKnowledge.addEventListener('drop', (e) => {
9860
11101
  e.preventDefault();
9861
11102
  kbClearDrag();
9862
- if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length) kbUpload(e.dataTransfer.files);
11103
+ const cat = kbDropTargetOf(e);
11104
+ kbClearDropHover();
11105
+ const to = cat ? (cat.dataset.kbDropCat === 'uncategorized' ? null : cat.dataset.kbDropCat) : undefined;
11106
+ const raw = e.dataTransfer ? e.dataTransfer.getData(KB_REFS_MIME) : '';
11107
+ kbInvalidateRefs();
11108
+ if (raw) {
11109
+ kbDragIds = null;
11110
+ if (to === undefined) return; // dropped beside a category: nothing moves
11111
+ let ids = [];
11112
+ try { ids = JSON.parse(raw); } catch { ids = []; }
11113
+ if (Array.isArray(ids) && ids.length) kbPlace(ids.filter((x) => typeof x === 'string'), to);
11114
+ return;
11115
+ }
11116
+ if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files.length) kbUpload(e.dataTransfer.files, to === undefined ? undefined : to);
9863
11117
  });
9864
11118
 
9865
11119
  // ── Exports step ──────────────────────────────────────────────────────────────
@@ -12685,6 +13939,7 @@
12685
13939
  async function attachRevision(files) {
12686
13940
  const proj = current; // capture — the user may switch projects during the async file reads / POST
12687
13941
  if (!proj || !files.length) return;
13942
+ if (!validateSteelDrawingFiles(wsDescOf(proj) === WORKSPACE_APPS['steel-model'] ? 'steel-model' : '', files)) return;
12688
13943
  const projectGeneration = revisionOwnerGen;
12689
13944
  const attachGeneration = ++revisionAttachGen;
12690
13945
  const ownsAttach = () => current === proj
@@ -12700,7 +13955,7 @@
12700
13955
  res = await api(`/api/projects/${encodeURIComponent(proj.id)}/revision-requests`, {
12701
13956
  method: 'POST', body: JSON.stringify({ appId: proj.app, snapshots }),
12702
13957
  });
12703
- } catch (err) { if (ownsAttach()) showToast('We couldn’t attach that file because FloLess could not save it. Try again.', 'warn'); return; }
13958
+ } 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
13959
  const req = res && res.request;
12705
13960
  if (!ownsAttach()) {
12706
13961
  if (bridge.loadRequests) bridge.loadRequests().catch(() => {});
@@ -12743,7 +13998,7 @@
12743
13998
  }
12744
13999
 
12745
14000
  document.getElementById('ws-attach-revision').addEventListener('click', async () => {
12746
- const files = await pickDrawingFiles($revisionFile);
14001
+ const files = await pickDrawingFiles($revisionFile, wsDescOf(current) === WORKSPACE_APPS['steel-model'] ? 'steel-model' : '');
12747
14002
  if (files.length) attachRevision(files);
12748
14003
  });
12749
14004
 
@@ -13787,7 +15042,7 @@
13787
15042
  return line;
13788
15043
  }
13789
15044
 
13790
- function proposalRow(p, idx, bucket) {
15045
+ function proposalRow(p, idx, bucket, { preTicks = false } = {}) {
13791
15046
  // A read that only ADDS (marks on a sheet, detail anchors, moment frames) reads as an addition, not as a change.
13792
15047
  const addsOnly = isMarksRow(p) || (p.kind === 'model-changed' && (p.key === 'detail_bubbles' || p.key === 'moment_frames'));
13793
15048
  const row = revEl('div', 'rev-row ' + (addsOnly ? 'k-added' : (KIND_CLASS[p.kind] || 'k-changed')));
@@ -13814,6 +15069,23 @@
13814
15069
  // is named from its subject.
13815
15070
  const rf = p.kind === 'model-changed' ? rootField(p.key) : null;
13816
15071
  head.appendChild(revEl('span', 'rev-kind-badge', rf ? rf.badge : (isMarksRow(p) ? marksBadge(p) : (KIND_LABEL[p.kind] || p.kind))));
15072
+ // #2521 row 3b-3: the SERVER marks a row whose new height the AI of this Quick build chose (`p.ai`). The pill says who
15073
+ // chose it at a glance; what that means for the tick is in the row's note, which the checkbox is described by.
15074
+ const aiRow = p.kind === 'member-changed' && p.ai && typeof p.ai === 'object' && p.ai.heights > 0 ? p.ai : null;
15075
+ if (aiRow) {
15076
+ const pill = revEl('span', 'ai-pill rev-ai-pill', aiRow.onlyAiHeights ? 'AI-chosen height' : 'AI height');
15077
+ pill.dataset.tip = 'Chosen by the AI in the Quick model, not from the drawings.';
15078
+ head.appendChild(pill);
15079
+ }
15080
+ // Pre-ticked only when the person chose to auto-accept the AI's changes, the server says every change in the row is
15081
+ // the AI's height, and the review is not a re-render after the model moved (then every tick is cleared, below).
15082
+ const preTicked = !!(aiRow && p.preTick === true && preTicks);
15083
+ if (preTicked) box.checked = true;
15084
+ // Instructor (`?`) explains this tick in its own words, as it does the pre-selected registration row.
15085
+ if (aiRow) {
15086
+ box.dataset.commandId = `shell.revision-ai-height#${p.memberId}`;
15087
+ box.dataset.commandInstanceLabel = String(p.memberId || '');
15088
+ }
13817
15089
  // A plan proposal is titled by `viewLabel`, which the SERVER computes with `planViewLabels` (#938).
13818
15090
  // The rule needs sibling context — a page's name is enough when it carries one view and must be
13819
15091
  // disambiguated when it carries several — which a single proposal row does not have, so re-deriving
@@ -13864,9 +15136,15 @@
13864
15136
  // with other changes the read proposes for the same member; accepting it takes those too, so the
13865
15137
  // row says so FIRST (design review: it is the most consequential note) rather than letting the
13866
15138
  // height stand for the whole decision.
13867
- if (answeredEnds && otherFields) {
15139
+ if ((answeredEnds && otherFields) || (aiRow && !aiRow.onlyAiHeights)) {
13868
15140
  desc.push(revEl('div', 'rev-row-note', 'Ticking this row also applies the other changes shown for this member.'));
13869
15141
  }
15142
+ // ONE note for the AI's height (design review: never two stacked), saying whose number it is and what the tick does.
15143
+ if (aiRow) {
15144
+ desc.push(revEl('div', 'rev-row-note', preTicked
15145
+ ? 'The AI picked this height in the Quick model; it is not from the drawings or from you. It is ticked for you because you chose to auto-accept the AI’s changes: untick it to keep the height as it is.'
15146
+ : 'The AI picked this height in the Quick model; it is not from the drawings or from you. It is applied only if this row is ticked when you confirm.'));
15147
+ }
13870
15148
  desc.push(...notes);
13871
15149
  } else if (p.kind === 'model-changed') {
13872
15150
  const isGrid = p.key === 'grid';
@@ -14155,7 +15433,15 @@
14155
15433
  root.querySelectorAll('.rev-check, .rev-group-actions').forEach((control) => control.remove());
14156
15434
  }
14157
15435
 
14158
- function renderReview(summary, { readOnly = false } = {}) {
15436
+ /** #2521 row 3b-3: what the review's subtitle adds while a row starts ticked for the person; taken out when none does. */
15437
+ const PRE_TICKED_SUB = ' Some of the AI’s height changes are ticked for you because you chose to auto-accept them; untick any you do not want, then confirm.';
15438
+
15439
+ /*
15440
+ * `preTicks` (#2521 row 3b-3): whether a row the server pre-ticks (`preTick`, the person's auto-accept choice) starts
15441
+ * ticked. Off for the re-render after the model moved mid-review: that render clears every tick on purpose ("each one
15442
+ * needs deciding again"), so it never re-ticks an AI row the person had unticked (Codex plan review, finding 3).
15443
+ */
15444
+ function renderReview(summary, { readOnly = false, preTicks = true } = {}) {
14159
15445
  // COUNTS: one quiet line, and never "0 of X" — the zero clause is simply omitted.
14160
15446
  // The numbers carry a <b>, so the two figures worth scanning stand out of the muted sentence —
14161
15447
  // the rule for it existed and nothing emitted the element.
@@ -14210,7 +15496,7 @@
14210
15496
  }
14211
15497
  if (props.length) {
14212
15498
  const g = group(readOnly ? 'Changes this read proposed' : 'Needs your decision', props.length, 'proposals');
14213
- props.forEach((p, i) => g.appendChild(proposalRow(p, i, 'proposals')));
15499
+ props.forEach((p, i) => g.appendChild(proposalRow(p, i, 'proposals', { preTicks: preTicks && !readOnly })));
14214
15500
  body.appendChild(g);
14215
15501
  }
14216
15502
  if (binds.length) {
@@ -14309,9 +15595,11 @@
14309
15595
  const created = outcomes.filter((row) => ['created', 'successor'].includes(row.result));
14310
15596
  const existing = outcomes.filter((row) => ['reused', 'reopened', 'already-seeded'].includes(row.result));
14311
15597
  const removed = outcomes.filter((row) => row.result === 'not-in-report');
14312
- const attention = outcomes.filter((row) => !['created', 'reused', 'reopened', 'successor', 'already-seeded', 'not-in-report'].includes(row.result));
15598
+ // #2521 row 3b-2: a Quick RFI whose question the person's review changed. It stays open; it is not lost.
15599
+ const changed = outcomes.filter((row) => row.result === 'facts-changed');
15600
+ const attention = outcomes.filter((row) => !['created', 'reused', 'reopened', 'successor', 'already-seeded', 'not-in-report', 'facts-changed'].includes(row.result));
14313
15601
  $revReviewCounts.replaceChildren(document.createTextNode(
14314
- `RFI result: ${created.length} created · ${existing.length} existing record${existing.length === 1 ? '' : 's'} used · ${removed.length} selected question${removed.length === 1 ? '' : 's'} no longer in the final report · ${unasked.length} new question${unasked.length === 1 ? '' : 's'} appeared only at confirm and ${unasked.length === 1 ? 'was' : 'were'} not filed.${attention.length ? ` ${attention.length} other RFI result${attention.length === 1 ? '' : 's'} need attention.` : ''}`,
15602
+ `RFI result: ${created.length} created · ${existing.length} existing record${existing.length === 1 ? '' : 's'} used · ${removed.length} selected question${removed.length === 1 ? '' : 's'} no longer in the final report · ${unasked.length} new question${unasked.length === 1 ? '' : 's'} appeared only at confirm and ${unasked.length === 1 ? 'was' : 'were'} not filed.${changed.length ? ` ${changed.length} stayed open and ${changed.length === 1 ? 'was' : 'were'} not filed: your review changed the question, so the AI's recommendation no longer answers it.` : ''}${attention.length ? ` ${attention.length} other RFI result${attention.length === 1 ? '' : 's'} need attention.` : ''}`,
14315
15603
  ));
14316
15604
  $revReviewCounts.dataset.revRfiSelection = 'result';
14317
15605
  $revReviewCounts.hidden = false;
@@ -14345,6 +15633,16 @@
14345
15633
  }
14346
15634
  body.appendChild(section);
14347
15635
  }
15636
+ if (changed.length) {
15637
+ const section = group('Changed in your review, still open', changed.length);
15638
+ for (const row of changed) {
15639
+ const item = revEl('div', 'rev-row');
15640
+ item.appendChild(revEl('div', 'rev-row-title', row.gapKey));
15641
+ item.appendChild(revEl('div', 'rev-row-note', 'Changed in your review. The AI’s recommendation no longer answers this, so it stays open and is not filed.'));
15642
+ section.appendChild(item);
15643
+ }
15644
+ body.appendChild(section);
15645
+ }
14348
15646
  if (unasked.length) {
14349
15647
  const section = group('New questions that were not filed', unasked.length);
14350
15648
  for (const row of unasked) {
@@ -14365,7 +15663,7 @@
14365
15663
  }
14366
15664
  body.appendChild(section);
14367
15665
  }
14368
- if (!records.length && !removed.length && !unasked.length && !attention.length) {
15666
+ if (!records.length && !removed.length && !changed.length && !unasked.length && !attention.length) {
14369
15667
  body.appendChild(revEl('div', 'hd-empty', 'No RFI record changed with this revision.'));
14370
15668
  }
14371
15669
  $revReviewBody.replaceChildren(body);
@@ -14476,6 +15774,11 @@
14476
15774
  : moveForward
14477
15775
  ? `This read started from v${moveForward.fromVersion}. Its non-overlapping changes can be applied on top of approved v${moveForward.toVersion}; decide every overlap before applying.`
14478
15776
  : 'Nothing is applied until you confirm. Registration rows start selected; tick any other changes you want, and clear any registration this read may not change.';
15777
+ // #2521 row 3b-3: said without a number, so it cannot go stale as the person unticks (design review), and as
15778
+ // "ticked for you", never "accepted": nothing lands until the confirm.
15779
+ if (!readOnly && (summary.proposals || []).some((p) => p && p.kind === 'member-changed' && p.preTick === true && p.ai)) {
15780
+ $revReviewSub.textContent += PRE_TICKED_SUB;
15781
+ }
14479
15782
  $revReviewChanged.hidden = true;
14480
15783
  delete $revReviewChanged.dataset.kind;
14481
15784
  renderReview(summary, { readOnly });
@@ -14698,7 +16001,9 @@
14698
16001
  // `revReviewState` to the fresh stageId would leave the user looking at one review while the
14699
16002
  // next confirm submitted indices against another. Rendering first means a throw leaves the
14700
16003
  // stale-but-consistent pair, and the `finally` below still restores the button.
14701
- renderReview(fresh); // replaceChildren builds new, unticked inputs — no tick can survive it
16004
+ renderReview(fresh, { preTicks: false }); // replaceChildren builds new, unticked inputs — no tick can survive it, a pre-tick included
16005
+ // So the subtitle no longer says any row is ticked for the person (code review of 3b-3).
16006
+ $revReviewSub.textContent = $revReviewSub.textContent.replace(PRE_TICKED_SUB, '');
14702
16007
  revReviewState = { ...st, stageId: fresh.stageId, summary: fresh };
14703
16008
  if (fresh.rfiSelection?.decision === 'required') showRequiredRfiSelection(fresh, true);
14704
16009
  else {
@@ -16745,6 +18050,59 @@
16745
18050
  if (current?.id !== projectId) throw new Error('That project could not be opened. Open it from Workspaces.');
16746
18051
  }
16747
18052
 
18053
+ // #2470 R6.2: a project's Workflows step, where the workflows it owns are listed (Project access links here).
18054
+ // #2470 R6.7: the create cards a General project's Add a module sheet shows — the landing's own entries and markup,
18055
+ // minus General, so every lock, setup and remedy state reads exactly as it does on the landing.
18056
+ function moduleCreateCardsHtml() {
18057
+ return workspaceCreateEntries(wsAppEntries)
18058
+ .filter(({ entry }) => entry.templateId !== 'floless-general')
18059
+ .map(({ entry, action }) => workspaceCreateCardHtml(entry, action))
18060
+ .join('');
18061
+ }
18062
+
18063
+ /** A click on a card in the Add a module sheet: the card's remedy, or its own create flow carrying `linkFrom`. */
18064
+ function activateCreateCard(target, linkFrom) {
18065
+ const remedy = createCardRemedy(target);
18066
+ if (remedy) return { kind: 'remedy', done: remedy() };
18067
+ const seed = target?.closest?.('[data-seed-app]');
18068
+ if (!seed) return null;
18069
+ return { kind: 'create', done: activateSeedCard(seed, linkFrom) };
18070
+ }
18071
+
18072
+ /** Open a project by id, from another project's Modules step: the same open a card on the landing does. */
18073
+ async function openLinkedProject(projectId) {
18074
+ await setMode('workspaces');
18075
+ const opened = await openProject(projectId);
18076
+ if (opened === STAYED_IN_PROJECT) throw new Error('You stayed in this project, so the other one was not opened.');
18077
+ if (current?.id !== projectId) throw new Error('That project could not be opened. Open it from Workspaces.');
18078
+ }
18079
+
18080
+ /** A General project's Modules step: where Back to … after an Add a module returns to. */
18081
+ async function openModulesStep(projectId) {
18082
+ await setMode('workspaces');
18083
+ const opened = await openProject(projectId, 'modules');
18084
+ if (opened === STAYED_IN_PROJECT) throw new Error('You stayed in this project, so the other one was not opened.');
18085
+ if (current?.id !== projectId) throw new Error('That project could not be opened. Open it from Workspaces.');
18086
+ }
18087
+
18088
+ /** Show the archived projects on the Workspaces page, where Restore is, with this one in view. */
18089
+ async function showArchivedProjects(returnFocus) {
18090
+ await setMode('workspaces');
18091
+ if (current) await leaveProjectToList(returnFocus);
18092
+ if (current) return false;
18093
+ const archived = $landing.querySelector('.ws-archived');
18094
+ if (archived) { archived.open = true; archived.scrollIntoView?.({ block: 'nearest' }); archived.querySelector('summary')?.focus?.(); }
18095
+ return true;
18096
+ }
18097
+
18098
+ async function openWorkflowsStep(projectId) {
18099
+ if (typeof projectId !== 'string' || !projectId) throw new Error('That project could not be opened. Open it from Workspaces.');
18100
+ await setMode('workspaces');
18101
+ const opened = await openProject(projectId, 'workflows');
18102
+ if (opened === STAYED_IN_PROJECT) throw new Error('You stayed in this project, so the other one was not opened.');
18103
+ if (current?.id !== projectId) throw new Error('That project could not be opened. Open it from Workspaces.');
18104
+ }
18105
+
16748
18106
  // The Drawing Filter step of a project, where a drawing read's exclusions are saved and signed off.
16749
18107
  async function openDrawingsStep(projectId) {
16750
18108
  if (typeof projectId !== 'string' || !projectId) throw new Error('That project could not be opened. Open it from Workspaces.');
@@ -16796,7 +18154,11 @@
16796
18154
  };
16797
18155
  async function openConnection(target) {
16798
18156
  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.');
18157
+ // #2471: or one member an AI Chat answer cited, with the project identity it was cited in (checked at handover).
18158
+ const member = !!target && !validId(target.jointId) && validId(target.memberId);
18159
+ const thing = member ? 'member' : 'connection';
18160
+ const again = member ? 'Show in the model' : 'Open in the model';
18161
+ if (!target || !validId(target.projectId) || !(validId(target.jointId) || member)) throw connectionError(`That ${thing} could not be opened. Open its project from Workspaces.`);
16800
18162
  const mine = { id: `connection-${++connectionRequestSeq}`, page: null };
16801
18163
  withdrawConnectionRequest(connectionRequest);
16802
18164
  connectionRequest = mine;
@@ -16804,8 +18166,8 @@
16804
18166
  // Once this call has ended, for any reason, a project change it started gives way before it lands.
16805
18167
  let ended = false;
16806
18168
  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.');
18169
+ const stayedOutside = () => connectionError(`You stayed where you were, so the ${thing} was not shown. Open the project from Workspaces, then press ${again} again.`);
18170
+ const leftWorkspaces = () => connectionError(`You left Workspaces, so the ${thing} was not shown. Open the project from Workspaces, then press ${again} again.`);
16809
18171
  const pause = () => new Promise((resolve) => setTimeout(resolve, 100));
16810
18172
  /**
16811
18173
  * Wait for a step of getting there, watched: a later click ends it at once. `bounded` adds the deadline,
@@ -16822,21 +18184,28 @@
16822
18184
  await Promise.race([finished, pause()]);
16823
18185
  if (done) { if (done.error) throw done.error; return done.value; }
16824
18186
  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.');
18187
+ 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
18188
  }
16827
18189
  };
18190
+ // A project removed and made again under the same id is not the one the answer cited.
18191
+ const citedElsewhere = () => validId(target.projectUuid) && String(current?.uuid || '').toLowerCase() !== target.projectUuid.toLowerCase();
18192
+ const citedGone = () => connectionError(`This project is no longer the one the answer cited, so the ${thing} was not shown.`);
16828
18193
  let until = Infinity;
18194
+ // #2605: the document the model frame held before this call opened the project. Left for the Workspaces list,
18195
+ // a project's editor page stays in the hidden frame, and openProject's reset of it lands only later: until
18196
+ // then that page still answers to the project id, and a request handed to it dies with the reload.
18197
+ let pageLeftBehind = null;
16829
18198
  // Everything that ends this call's wait without the editor's answer.
16830
18199
  const interrupted = () => {
16831
18200
  if (superseded()) return { superseded: true };
16832
18201
  if (mode !== 'workspaces') throw leftWorkspaces();
16833
- if (current?.id !== target.projectId) throw connectionError('You moved to another project, so the connection was not shown.');
18202
+ if (current?.id !== target.projectId) throw connectionError(`You moved to another project, so the ${thing} was not shown.`);
16834
18203
  // The project's stages kept the Model step locked, or the person went to another step: the step's
16835
18204
  // own message says why, and there is nothing to wait for.
16836
18205
  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.');
18206
+ throw connectionError(`The Model step is not open, so the ${thing} was not shown. Open the Model step, then press ${again} again.`);
16838
18207
  }
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.');
18208
+ 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
18209
  return null;
16841
18210
  };
16842
18211
  try {
@@ -16844,20 +18213,21 @@
16844
18213
  // setMode leaves the person where they were when they chose to stay (an Agent with unsaved changes).
16845
18214
  if (mode !== 'workspaces') throw stayedOutside();
16846
18215
  if (current?.id !== target.projectId) {
18216
+ try { pageLeftBehind = frames.model.contentWindow?.document ?? null; } catch { pageLeftBehind = null; }
16847
18217
  const opened = await navigating(openProject(target.projectId, 'model', { stillWanted }), true);
16848
18218
  if (opened?.superseded || superseded()) return { superseded: true };
16849
18219
  // openProject answers "stayed" for several causes (the person chose to stay, the project's folder is
16850
18220
  // 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.');
18221
+ 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
18222
  if (current?.id !== target.projectId) throw connectionError('That project could not be opened. Open it from Workspaces.');
16853
18223
  } else if (currentStep !== 'model') {
16854
18224
  setStep('model');
16855
18225
  }
16856
- if (!frames.model.dataset.want) throw connectionError('This project has no model editor to show the connection in.');
18226
+ if (!frames.model.dataset.want) throw connectionError(`This project has no model editor to show the ${thing} in.`);
16857
18227
  // The editor's deadline starts once the person is in the project.
16858
18228
  until = Date.now() + CONNECTION_FRAME_WAIT_MS;
16859
18229
  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.';
18230
+ const notTaken = `The model could not take the request. Press ${again} again.`;
16861
18231
  for (;;) {
16862
18232
  // An answer already in is the editor's account of what it did: once it has selected the connection,
16863
18233
  // leaving the step or the deadline passing does not make that untrue. Only a later click, another
@@ -16866,8 +18236,8 @@
16866
18236
  if (superseded()) return { superseded: true };
16867
18237
  // The Model step may have been left after the selection, but not Workspaces: hidden, it shows nothing.
16868
18238
  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.');
18239
+ if (current?.id !== target.projectId) throw connectionError(`You moved to another project, so the ${thing} was not shown.`);
18240
+ if (frames.model.contentWindow !== page || page.document !== doc) throw connectionError(`The model reloaded, so the ${thing} was not shown. Press ${again} again.`);
16871
18241
  const outcome = settled.outcome;
16872
18242
  return outcome && typeof outcome === 'object' ? { ...outcome } : { ok: false, said: notTaken };
16873
18243
  }
@@ -16876,10 +18246,12 @@
16876
18246
  const child = frames.model.contentWindow;
16877
18247
  if (!answer) {
16878
18248
  const state = child && child.flolessEditorState;
16879
- if (state && state.project === target.projectId && typeof child.flolessEditorFocus === 'function') {
18249
+ if (state && state.project === target.projectId && typeof child.flolessEditorFocus === 'function'
18250
+ && (!pageLeftBehind || child.document !== pageLeftBehind)) {
18251
+ if (citedElsewhere()) throw citedGone();
16880
18252
  // The frame's window survives a reload; its DOCUMENT does not. That is what tells a reload apart.
16881
18253
  page = child; doc = child.document;
16882
- answer = child.flolessEditorFocus({ jointId: target.jointId, requestId: mine.id,
18254
+ answer = child.flolessEditorFocus(member ? { memberId: target.memberId, requestId: mine.id } : { jointId: target.jointId, requestId: mine.id,
16883
18255
  // #2450: the readiness card's "Raise an RFI" also opens the editor's review dialog for it.
16884
18256
  ...(target.raiseRfi === true ? { raiseRfi: true } : {}), ...(validId(target.checkId) ? { checkId: target.checkId } : {}) });
16885
18257
  if (!answer || typeof answer.then !== 'function') return { ok: false, said: notTaken };
@@ -16890,7 +18262,7 @@
16890
18262
  });
16891
18263
  }
16892
18264
  } 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.');
18265
+ throw connectionError(`The model reloaded, so the ${thing} was not shown. Press ${again} again.`);
16894
18266
  }
16895
18267
  await pause();
16896
18268
  }
@@ -17017,7 +18389,8 @@
17017
18389
  if (!drop || current?.id !== projectId) return 'The project’s Knowledge step did not open. Open the project and use Drop references there.';
17018
18390
  if (unverified || (navigator.userActivation && !navigator.userActivation.isActive)) {
17019
18391
  kbDropAttention(drop);
17020
- return 'Choose files is ready in this project’s Knowledge step. Press it to pick the files.';
18392
+ // #2427: nothing failed — the last click is the person's, so the card waits for them instead of reading red.
18393
+ return { handedOver: 'Choose files is ready in this project’s Knowledge step. Press it to pick the files.', focus: drop };
17021
18394
  }
17022
18395
  $wsKnowledgeFile.click();
17023
18396
  return '';
@@ -17053,7 +18426,7 @@
17053
18426
  // The confirm click may be too long ago by now; the Replace control is then left in front for them.
17054
18427
  if (!tekla && navigator.userActivation && !navigator.userActivation.isActive) {
17055
18428
  $revitReplace.scrollIntoView({ block: 'center' }); $revitReplace.focus();
17056
- return `${$revitReplace.textContent || 'Replace RVT…'} is ready on this project. Press it to choose the file.`;
18429
+ return { handedOver: `${$revitReplace.textContent || 'Replace RVT…'} is ready on this project. Press it to choose the file.`, focus: $revitReplace };
17057
18430
  }
17058
18431
  $revitReplace.click();
17059
18432
  return '';
@@ -17103,10 +18476,14 @@
17103
18476
  tellModelFrame({ type: 'knowledge-changed', projectId });
17104
18477
  },
17105
18478
  setMode, refresh: loadProjects, findActive: wsFindActive, find: wsFind, clearFind: wsClearFind,
17106
- openHistory: wsOpenHistory, openKnowledgePage, openKnowledgeStep, openDrawingsStep, openConnection, drawingFilterCheckpointSaved,
18479
+ openHistory: wsOpenHistory, openKnowledgePage, openKnowledgeStep, openDrawingsStep, openWorkflowsStep, openConnection, drawingFilterCheckpointSaved,
18480
+ // #2470 R6.7: the Modules step of a General project (project-modules.js).
18481
+ moduleCreateCardsHtml, activateCreateCard, openLinkedProject, openModulesStep, showArchivedProjects,
17107
18482
  syncWorkspaceReporter, openChatOwner, openPagesHome, folderDecisionCompleted,
17108
18483
  // Project access (project-access.js loads after this file): the project open now, or null.
17109
18484
  currentProject: () => ($app.classList.contains('mode-workspaces') && current ? current : null),
18485
+ // #2470 R6.2: whether the open project's kind has this step (a General project has Workflows; the others not yet).
18486
+ projectHasStep: (key) => Boolean(current && wsDescOf(current)?.steps?.some((st) => st.key === key)),
17110
18487
  };
17111
18488
  applyMode(); // restore persisted mode immediately (matches panels.js applyView timing)
17112
18489
  })();