@floless/app 0.160.0 → 0.162.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 (40) hide show
  1. package/aware-version-pin.mjs +43 -0
  2. package/dist/floless-server.cjs +126990 -120010
  3. package/dist/schemas/steel.model.v2.schema.json +23 -0
  4. package/dist/skills/floless-app-knowledge/SKILL.md +6 -5
  5. package/dist/skills/floless-app-rfi/SKILL.md +18 -5
  6. package/dist/skills/floless-app-steel-model/SKILL.md +28 -6
  7. package/dist/skills/floless-app-steel-takeoff/SKILL.md +579 -282
  8. package/dist/templates/floless-workspace-read.flo +9 -1
  9. package/dist/templates/steel-model.flo +6 -2
  10. package/dist/templates/viewer-3d-demo.flo +8 -2
  11. package/dist/web/app.css +198 -17
  12. package/dist/web/app.js +23 -0
  13. package/dist/web/aware.js +303 -54
  14. package/dist/web/chat-question-card.js +10 -3
  15. package/dist/web/chat.css +79 -5
  16. package/dist/web/chat.js +1513 -243
  17. package/dist/web/commands-drawing-check.js +1 -0
  18. package/dist/web/commands-filter.js +11 -0
  19. package/dist/web/commands-shell.js +467 -29
  20. package/dist/web/commands-steel.js +40 -38
  21. package/dist/web/drawing-check-editor.js +76 -3
  22. package/dist/web/index.html +46 -2
  23. package/dist/web/instructor.js +5 -3
  24. package/dist/web/leave-guard.js +12 -2
  25. package/dist/web/pages.js +43 -12
  26. package/dist/web/project-history.js +349 -0
  27. package/dist/web/project-reconciliation.js +1 -0
  28. package/dist/web/project-rfis.js +260 -21
  29. package/dist/web/startup-admission.js +53 -7
  30. package/dist/web/steel-3d-core.js +115 -6
  31. package/dist/web/steel-3d-view.js +61 -5
  32. package/dist/web/steel-editor.html +439 -118
  33. package/dist/web/steel-filter.html +139 -0
  34. package/dist/web/steel-model-v2-commands.js +3 -3
  35. package/dist/web/steel-model-v2-projection.js +132 -4
  36. package/dist/web/steel-plan-transform.js +78 -0
  37. package/dist/web/tool-updates.js +59 -3
  38. package/dist/web/workspaces.js +1553 -196
  39. package/launch.mjs +36 -5
  40. package/package.json +6 -4
package/dist/web/pages.js CHANGED
@@ -413,6 +413,7 @@
413
413
 
414
414
  const view = {
415
415
  home: null, page: null, n: null, returnFocus: null,
416
+ returnList: null, // the Pages list the viewer was opened from, which outlives its rows (#2728)
416
417
  known: [], // the versions loaded so far: a contiguous run of the newest, oldest first (#2291)
417
418
  pagingOlder: false, // a "Show older versions" request is in flight
418
419
  openSeq: 0, // each open counts up, so an earlier open's late answer never replaces a newer one
@@ -458,6 +459,18 @@
458
459
  // whole history is count minus the versions newer than it — never its position in what happens to be loaded.
459
460
  function totalVersions() { return view.page?.history?.count ?? view.known.length; }
460
461
  function position(v) { return totalVersions() - view.known.filter((x) => x.n > v.n).length; }
462
+ // #2730: a version is always called by its stored number — the one the run viewer's link, the chat's Page cards, the
463
+ // share link and the AI actions use. Until a version is dropped that number IS its place in the history, so the header
464
+ // can say "of M"; once older ones are dropped (a workflow's Page keeps its newest twenty), it says what is kept instead.
465
+ // A version a share link shows is kept however old it is, so "the newest N" is said only when the kept ones are a run.
466
+ function droppedNote() {
467
+ const latest = view.known[view.known.length - 1]?.n ?? 0;
468
+ const total = totalVersions();
469
+ if (latest <= total) return '';
470
+ const first = view.page?.history?.first;
471
+ if (Number.isInteger(first) && latest - first + 1 !== total) return 'Some older versions were removed. The newest ones are kept, and so is any version a share link shows.';
472
+ return total === 1 ? 'Only the latest version is kept. Older ones were removed.' : `Only the newest ${total} versions are kept. Older ones were removed.`;
473
+ }
461
474
  function currentVersion() { return view.known.find((v) => v.n === view.n) || null; }
462
475
  const CAPTURE_TEXT = { live: 'Captured during a live session', 'live-failed': 'Captured during a live session that later failed' };
463
476
 
@@ -534,8 +547,8 @@
534
547
  const p = view.page;
535
548
  const v = currentVersion();
536
549
  const latest = view.known[view.known.length - 1].n;
537
- const index = v ? position(v) : totalVersions();
538
550
  const total = totalVersions();
551
+ const dropped = droppedNote();
539
552
  $title.textContent = p.title;
540
553
  $ai.hidden = !v?.aiMade;
541
554
  $ai.setAttribute('data-tip', AI_TIP);
@@ -561,13 +574,13 @@
561
574
  ? 'This version is only a summary. Open the whole report FloLess keeps on this computer, in its report viewer'
562
575
  : 'Open the whole report FloLess keeps on this computer, in its report viewer');
563
576
  }
564
- $version.textContent = `Version ${index} of ${total}${view.n === latest ? ' · latest' : ''}`;
565
- $version.setAttribute('aria-label', `Version ${index} of ${total}. Choose another version`);
577
+ $version.textContent = `Version ${view.n}${dropped ? '' : ` of ${total}`}${view.n === latest ? ' · latest' : ''}`;
578
+ $version.setAttribute('aria-label', dropped ? `Version ${view.n}${view.n === latest ? ', the latest' : ''}. ${dropped} Choose another version` : `Version ${view.n} of ${total}. Choose another version`);
566
579
  const allowed = p.allowedOrigins.length;
567
580
  $allowed.hidden = allowed === 0;
568
581
  $allowed.textContent = allowed === 1 ? '1 site allowed' : `${allowed} sites allowed`;
569
582
  $sites.setAttribute('aria-label', allowed ? `Sites this Page may load (${allowed})` : 'Sites this Page may load');
570
- $frame.setAttribute('title', `Page: ${p.title}, version ${index}`);
583
+ $frame.setAttribute('title', `Page: ${p.title}, version ${view.n}`);
571
584
  }
572
585
 
573
586
  async function loadFrame() {
@@ -642,6 +655,7 @@
642
655
  if (typeof opts.beforeShow === 'function') await opts.beforeShow();
643
656
  if (seq !== view.openSeq) return false;
644
657
  view.returnFocus = !opts.beforeShow && returnFocus instanceof HTMLElement ? returnFocus : document.activeElement;
658
+ view.returnList = [...lists].find((e) => e.container.contains(view.returnFocus))?.container || null;
645
659
  view.linkAsk = null;
646
660
  view.blocked.clear();
647
661
  view.kept.clear();
@@ -678,9 +692,28 @@
678
692
  view.linkAsk = null;
679
693
  view.blocked.clear();
680
694
  paintBanner();
681
- const back = view.returnFocus;
695
+ const back = returnTarget(view.returnFocus, view.returnList);
682
696
  view.returnFocus = null;
683
- if (back?.isConnected) back.focus();
697
+ view.returnList = null;
698
+ back?.focus();
699
+ }
700
+
701
+ /** #2728: where focus goes when the viewer closes. A Page change re-reads the open lists quietly, which replaces their
702
+ * rows, so the row the viewer was opened from may be gone: the same Page's row is found again by its command in that
703
+ * list, and when the Page left the list, the list's first Page row takes focus, so a keyboard user keeps their place.
704
+ * An opener that is still in the page is the answer even when hidden (then nothing takes focus): only a replaced one
705
+ * is looked for. Nothing hidden is ever focused. */
706
+ function returnTarget(back, list) {
707
+ const shown = (el) => !!el?.isConnected
708
+ && (typeof el.checkVisibility !== 'function' || el.checkVisibility({ checkVisibilityCSS: true, visibilityProperty: true, checkOpacity: false }));
709
+ if (!back) return null;
710
+ if (back.isConnected) return shown(back) ? back : null;
711
+ const id = back.getAttribute('data-command-id');
712
+ const scope = list?.isConnected ? list : document;
713
+ const again = id ? [...scope.querySelectorAll('[data-command-id]')].find((el) => el.getAttribute('data-command-id') === id && shown(el)) : null;
714
+ if (again) return again;
715
+ const firstRow = list?.isConnected ? list.querySelector('.pg-row-open') : null;
716
+ return shown(firstRow) ? firstRow : null;
684
717
  }
685
718
 
686
719
  /** Re-read the open Page's record (its labels changed on the server). An answer that arrives after the person
@@ -723,8 +756,9 @@
723
756
  const total = totalVersions();
724
757
  const older = total - view.known.length;
725
758
  const next = Math.min(200, older);
759
+ const dropped = droppedNote();
726
760
  const options = versions.map((v) => {
727
- const label = `Version ${position(v)}${v.n === latest ? ' · latest' : ''}`;
761
+ const label = `Version ${v.n}${v.n === latest ? ' · latest' : ''}`;
728
762
  const meta = [when(v.createdAt), v.aiMade ? 'AI-made' : '', v.capture ? CAPTURE_TEXT[v.capture] : '', v.sequence ? seqLabel(v.sequence) : ''].filter(Boolean).join(' · ');
729
763
  return `<button type="button" class="wf-option pv-version-option${v.n === view.n ? ' selected' : ''}" role="option" aria-selected="${v.n === view.n}"
730
764
  aria-posinset="${position(v)}" aria-setsize="${total}" data-command-id="shell.page-version-choose#${esc(label)}" data-n="${v.n}">
@@ -738,7 +772,7 @@
738
772
  <span class="pv-option-main">${older > 200 ? `Show ${next} older versions` : `Show the last ${older} version${older === 1 ? '' : 's'}`}</span>
739
773
  <span class="pv-option-meta">${older} more not shown</span></button></div>`
740
774
  : '';
741
- $versionPop.innerHTML = `<div role="listbox" id="pv-version-list" aria-label="Versions of this Page">${options}</div>${footer}
775
+ $versionPop.innerHTML = `${dropped ? `<p class="pv-pop-note" id="pv-version-kept">${esc(dropped)}</p>` : ''}<div role="listbox" id="pv-version-list" aria-label="Versions of this Page"${dropped ? ' aria-describedby="pv-version-kept"' : ''}>${options}</div>${footer}
742
776
  <span class="pv-version-announce" role="status" aria-live="polite">${esc(view.announce || '')}</span>`;
743
777
  view.announce = '';
744
778
  $versionPop.hidden = false;
@@ -1046,10 +1080,7 @@
1046
1080
  const $sharePop = $('pv-share-pop');
1047
1081
  const PLANS_URL = 'https://floless.io/pricing';
1048
1082
 
1049
- function verLabel(n) {
1050
- const v = view.known.find((x) => x.n === n);
1051
- return v ? `version ${position(v)}` : `version ${n}`;
1052
- }
1083
+ function verLabel(n) { return `version ${n}`; } // the stored number, as every other surface says it (#2730)
1053
1084
  function latestN() { return view.known[view.known.length - 1]?.n ?? null; }
1054
1085
 
1055
1086
  /** The words for where the link stands: the button label, its tip, and the popover's first line. */
@@ -0,0 +1,349 @@
1
+ /*
2
+ * A General project's History step (#2470 R6.5): what happened in the project, newest first, in plain words — when,
3
+ * and from where (the FloLess window, AI Chat, a terminal). It renders the project journal
4
+ * (GET /api/projects/:id/journal) the way Workflows → History renders runs (web/run-history.js): one section per
5
+ * area, a search box, rows with a time, a sentence and labels, and the cut said on screen. It reads only; the journal
6
+ * is written by the server when something commits. Spec: docs/superpowers/specs/2026-10-24-2470-r6-5-history-PLAN.md.
7
+ */
8
+ (() => {
9
+ const bridge = () => window.flolessBridge || {};
10
+ const api = (path) => {
11
+ if (typeof bridge().api === 'function') return bridge().api(path);
12
+ return fetch(path).then(async (res) => {
13
+ const body = await res.json().catch(() => ({}));
14
+ if (!res.ok || body.ok === false) { const err = new Error(body.error || `HTTP ${res.status}`); err.status = res.status; err.body = body; throw err; }
15
+ return body;
16
+ });
17
+ };
18
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
19
+ const PAGE = 100;
20
+
21
+ /** The areas, in the order the owner ruled ("By area", 2026-10-24). A kind this build doesn't name is Other activity. */
22
+ const AREAS = [
23
+ { key: 'project', label: 'Project', test: (k) => k === 'project-created' },
24
+ { key: 'knowledge', label: 'Knowledge', test: (k) => k.startsWith('knowledge-') || k.startsWith('design-set-') || k.startsWith('design-issue-') },
25
+ { key: 'workflows', label: 'Workflows', test: (k) => k.startsWith('workflow-') },
26
+ { key: 'rfis', label: 'RFIs', test: (k) => k.startsWith('rfi-') },
27
+ { key: 'linked', label: 'Linked projects', test: (k) => k === 'module-linked' || k === 'module-unlinked' },
28
+ { key: 'requests', label: 'Requests', test: (k) => k === 'request-changed' },
29
+ ];
30
+ const KNOWN = new Set(['project-created', 'knowledge-organized', 'knowledge-source-added', 'knowledge-source-removed',
31
+ 'design-set-registered', 'design-set-cleared', 'design-issue-added', 'design-issue-updated', 'design-issue-withdrawn',
32
+ 'design-issue-restored', 'workflow-created', 'workflow-compiled', 'workflow-run-finished', 'rfi-raised', 'rfi-answered',
33
+ 'rfi-closed', 'module-linked', 'module-unlinked', 'request-changed']);
34
+ const OTHER = { key: 'other', label: 'Other activity' };
35
+ const areaOf = (entry) => {
36
+ const kind = String(entry?.event?.kind || '');
37
+ return (KNOWN.has(kind) && AREAS.find((a) => a.test(kind))) || OTHER;
38
+ };
39
+
40
+ /** Where the work was started from. These are origins, not proof of a person: the tips say "from", never "verified". */
41
+ const AUTHORS = {
42
+ person: { label: 'You', tip: 'Done from the FloLess window.', aria: 'Done from the FloLess window', pill: false },
43
+ 'ai-chat': { label: 'AI Chat', tip: 'AI Chat did this from a chat in FloLess.', aria: 'Done by AI Chat', pill: true },
44
+ 'ai-chat-confirmed': { label: 'AI Chat · you confirmed', tip: 'AI Chat suggested this and you confirmed it.', aria: 'Suggested by AI Chat and confirmed by you', pill: true },
45
+ terminal: { label: 'From a terminal', tip: 'Done with FloLess commands from a terminal, usually by an AI assistant working there.', aria: 'Done from a terminal', pill: true },
46
+ };
47
+ const ROUTINE_TIP = 'Started by a routine on its schedule, or by Run now on that routine.';
48
+ const FAILED_TIP = 'This didn’t finish. Open the workflow or the request to see what went wrong, then try it again.';
49
+
50
+ const S = {
51
+ loading: 'Reading history…',
52
+ empty: 'Nothing has happened in this project yet. Adding knowledge, creating a workflow, raising an RFI or linking a module shows up here.',
53
+ unavailable: 'History isn’t available right now.',
54
+ failed: 'FloLess couldn’t read this project’s history. Check that FloLess is running, then try again.',
55
+ earlierFailed: 'Couldn’t load earlier events. Try again.',
56
+ cursorGone: 'The history was tidied while you were reading it, so earlier events can’t be fetched from here.',
57
+ noAuthor: 'Older events and some automatic ones don’t show who did them.',
58
+ stale: 'Couldn’t refresh the history, so this is what was read before. Try again in a moment.',
59
+ };
60
+
61
+ const when = (iso) => {
62
+ const t = Date.parse(iso);
63
+ return Number.isFinite(t)
64
+ ? new Date(t).toLocaleString(undefined, { day: 'numeric', month: 'short', year: 'numeric', hour: '2-digit', minute: '2-digit' }) : '';
65
+ };
66
+
67
+ /**
68
+ * One state per pane, keyed by the project it shows — its id AND its incarnation (a project recreated under the same
69
+ * id starts afresh). The Workspace folder is checked on every read (loadFirst), since the project object has none.
70
+ */
71
+ const states = new WeakMap();
72
+ const identityOf = (project) => `${project.id}|${String(project.uuid || '').toLowerCase()}`;
73
+ function stateFor(pane, project) {
74
+ let st = states.get(pane);
75
+ if (!st || st.identity !== identityOf(project)) {
76
+ st = { identity: identityOf(project), projectId: project.id, uuid: null, rootId: null, entries: [], loaded: false,
77
+ nextBefore: null, unavailable: '', error: '', stale: false, earlierError: false, cursorGone: false, earlierBusy: false, firstBusy: false,
78
+ announce: '', query: '', open: new Map(), clicked: null, token: 0 };
79
+ states.set(pane, st);
80
+ }
81
+ st.project = project;
82
+ return st;
83
+ }
84
+
85
+ function skeleton(pane, st) {
86
+ if (pane.dataset.phIdentity === st.identity && pane.querySelector('.ph-list-host')) return;
87
+ pane.dataset.phProject = st.projectId;
88
+ pane.dataset.phIdentity = st.identity;
89
+ pane.setAttribute('role', 'region');
90
+ pane.setAttribute('aria-label', 'Project history');
91
+ pane.innerHTML = '<div class="step-head"><span>History</span></div>'
92
+ + '<p class="pg-sub">What happened in this project, newest first: when, and from where.</p>'
93
+ + '<div class="ph-tools" hidden><input type="search" class="ws-landing-search ph-search" data-ph-search="1" placeholder="Search history"'
94
+ + ' aria-label="Search history" autocomplete="off" data-command-id="shell.project-history-search">'
95
+ + '<p class="rh-cut ph-note" hidden></p></div>'
96
+ + '<div class="ph-list-host"></div>'
97
+ + '<div class="ph-foot"></div>'
98
+ + '<p class="sr-only ph-live" role="status" aria-live="polite"></p>';
99
+ wire(pane);
100
+ }
101
+
102
+ // Each control's Instructor id is written out whole, as the carrier guard requires.
103
+ const RETRY = '<button type="button" class="ghost rh-act" data-ph-act="retry" data-command-id="shell.project-history-retry">Try again</button>';
104
+ const CLEAR = '<button type="button" class="ghost rh-act" data-ph-act="clear-search" data-command-id="shell.project-history-clear-search">Clear search</button>';
105
+ const REREAD = '<button type="button" class="rh-btn" data-ph-act="reread" data-command-id="shell.project-history-reread">Read again</button>';
106
+ const earlierButton = (busy) => `<button type="button" class="rh-btn" data-ph-act="earlier" data-command-id="shell.project-history-earlier"${busy ? ' aria-busy="true" disabled' : ''}>Show earlier</button>`;
107
+
108
+ function authorHtml(actor) {
109
+ const a = AUTHORS[actor];
110
+ if (!a) return '';
111
+ return `<span class="${a.pill ? 'rh-pill ph-author' : 'ph-author ph-author-you'}" tabindex="0" data-tip="${esc(a.tip)}" aria-label="${esc(a.aria)}">${esc(a.label)}</span>`;
112
+ }
113
+
114
+ function rowHtml(e) {
115
+ const failed = e.event?.outcome === 'failed';
116
+ const labels = [
117
+ authorHtml(e.actor),
118
+ failed ? `<span class="rh-outcome rh-failed" tabindex="0" data-tip="${esc(FAILED_TIP)}">Failed</span>` : '',
119
+ e.event?.trigger === 'routine' ? `<span class="rh-pill" tabindex="0" data-tip="${esc(ROUTINE_TIP)}">Routine</span>` : '',
120
+ ].join('');
121
+ // The sentence is set as text after the markup is in place (paintList): it is the server's words, never markup.
122
+ return `<div class="ph-row${failed ? ' is-failed' : ''}" role="listitem" data-ph-entry="${esc(e.id)}">`
123
+ + `<time class="rh-when" datetime="${esc(e.at)}">${esc(when(e.at))}</time>`
124
+ + '<span class="ph-text"></span>'
125
+ + `<span class="ph-labels">${labels}</span></div>`;
126
+ }
127
+
128
+ const authorLabel = (e) => AUTHORS[e.actor]?.label || '';
129
+ const matches = (e, area, terms) => terms.every((t) => `${e.text || ''} ${area.label} ${authorLabel(e)}`.toLowerCase().includes(t));
130
+
131
+ function paint(pane) {
132
+ const st = states.get(pane);
133
+ if (!st) return;
134
+ const host = pane.querySelector('.ph-list-host');
135
+ const foot = pane.querySelector('.ph-foot');
136
+ const tools = pane.querySelector('.ph-tools');
137
+ const note = pane.querySelector('.ph-note');
138
+ if (!host || !foot || !tools) return;
139
+ const focused = pane.contains(document.activeElement) && !document.activeElement?.hasAttribute?.('data-ph-search')
140
+ ? document.activeElement.getAttribute('data-command-id') : null;
141
+ foot.innerHTML = '';
142
+ if (!st.loaded) {
143
+ tools.hidden = true;
144
+ if (st.error) {
145
+ pane.dataset.phState = 'error';
146
+ host.innerHTML = `<div class="pg-empty" role="alert"><p class="ph-said"></p><p>${RETRY}</p></div>`;
147
+ host.querySelector('.ph-said').textContent = st.error;
148
+ } else {
149
+ pane.dataset.phState = 'loading';
150
+ host.innerHTML = `<p class="pg-loading-line" role="status">${esc(S.loading)}</p>`;
151
+ }
152
+ return;
153
+ }
154
+ if (st.unavailable) {
155
+ pane.dataset.phState = 'unavailable';
156
+ tools.hidden = true;
157
+ host.innerHTML = `<div class="pg-empty" role="status"><p>${esc(S.unavailable)}</p><p class="ph-said"></p><p>${RETRY}</p></div>`;
158
+ host.querySelector('.ph-said').textContent = st.unavailable;
159
+ return;
160
+ }
161
+ if (!st.entries.length && !st.nextBefore) {
162
+ pane.dataset.phState = 'empty';
163
+ tools.hidden = true;
164
+ // An empty list read before is not proof that nothing happened since: a failed refresh says so here too.
165
+ host.innerHTML = (st.stale ? `<div class="pg-wf-note ph-stale" role="status"><span>${esc(S.stale)}</span> ${RETRY}</div>` : '')
166
+ + `<div class="pg-empty"><p>${esc(S.empty)}</p></div>`;
167
+ return;
168
+ }
169
+ pane.dataset.phState = 'ready';
170
+ tools.hidden = false;
171
+ const stale = st.stale ? `<div class="pg-wf-note ph-stale" role="status"><span>${esc(S.stale)}</span> ${RETRY}</div>` : '';
172
+ note.hidden = !st.entries.some((e) => !AUTHORS[e.actor]);
173
+ note.textContent = S.noAuthor;
174
+ const terms = st.query.trim().toLowerCase().split(/\s+/).filter(Boolean);
175
+ const groups = [...AREAS, OTHER].map((area) => ({ area, rows: st.entries.filter((e) => areaOf(e) === area && matches(e, area, terms)) }))
176
+ .filter((g) => g.rows.length);
177
+ const newestArea = st.entries.length ? areaOf(st.entries[0]).key : null;
178
+ if (!groups.length) {
179
+ host.innerHTML = `${stale}<div class="pg-empty" role="status"><p class="ph-nomatch"></p>`
180
+ + `<p>${CLEAR}</p></div>`;
181
+ host.querySelector('.ph-nomatch').textContent = `Nothing in the history matches “${st.query.trim()}”.${st.nextBefore ? ' Show earlier to search further back.' : ''}`;
182
+ } else {
183
+ host.innerHTML = stale + groups.map(({ area, rows }) => {
184
+ const open = terms.length > 0 || (st.open.has(area.key) ? st.open.get(area.key) : area.key === newestArea);
185
+ return `<details class="ws-archived wf-section rh-section ph-section" data-ph-area="${esc(area.key)}"${open ? ' open' : ''}>`
186
+ + `<summary class="ws-archived-summary rh-summary" data-command-id="shell.project-history-section#${esc(area.key)}" data-command-instance-label="${esc(area.label)}">`
187
+ + `<span class="ws-archived-caret hd-caret" aria-hidden="true">▸</span><span class="rh-sum-name">${esc(area.label)}</span>`
188
+ + `<span class="rh-sum-meta">${rows.length} event${rows.length === 1 ? '' : 's'}</span>`
189
+ + `<span class="rh-sum-meta">Latest ${esc(when(rows[0].at))}</span></summary>`
190
+ + `<div class="rh-list ph-list" role="list" aria-label="${esc(`${area.label} events`)}">${rows.map(rowHtml).join('')}</div></details>`;
191
+ }).join('');
192
+ const byId = new Map(st.entries.map((e) => [e.id, e]));
193
+ host.querySelectorAll('[data-ph-entry]').forEach((row) => { row.querySelector('.ph-text').textContent = byId.get(row.dataset.phEntry)?.text || ''; });
194
+ }
195
+ if (st.cursorGone) {
196
+ foot.innerHTML = `<p class="rh-cut ph-cut" role="status"><span>${esc(S.cursorGone)}</span> ${REREAD}</p>`;
197
+ } else if (st.nextBefore) {
198
+ foot.innerHTML = `<p class="rh-cut ph-cut"><span>Showing the newest ${st.entries.length} events. Older ones aren’t loaded yet.</span> `
199
+ + earlierButton(st.earlierBusy || st.firstBusy)
200
+ + (st.earlierError ? ` <span class="ph-earlier-failed" role="alert">${esc(S.earlierFailed)}</span>` : '') + '</p>';
201
+ }
202
+ if (focused && (document.activeElement === document.body || !pane.contains(document.activeElement))) {
203
+ [...pane.querySelectorAll('[data-command-id]')].find((el) => el.getAttribute('data-command-id') === focused)?.focus({ preventScroll: true });
204
+ }
205
+ const live = pane.querySelector('.ph-live');
206
+ if (live && st.announce) { live.textContent = st.announce; st.announce = ''; }
207
+ }
208
+
209
+ const journalPath = (st, before) => `/api/projects/${encodeURIComponent(st.projectId)}/journal?limit=${PAGE}${before ? `&before=${encodeURIComponent(before)}` : ''}`;
210
+ const validEntries = (body) => {
211
+ const all = Array.isArray(body?.entries) ? body.entries : [];
212
+ const good = all.filter((e) => e && typeof e.id === 'string' && typeof e.at === 'string' && typeof e.text === 'string' && e.event && typeof e.event === 'object');
213
+ if (good.length < all.length) console.warn(`The project history held ${all.length - good.length} event(s) FloLess couldn’t read; they are not shown.`);
214
+ return good;
215
+ };
216
+
217
+ /** Read the newest page. The rows shown so far stay on screen until the answer replaces them. */
218
+ async function loadFirst(pane) {
219
+ const st = states.get(pane);
220
+ if (!st) return;
221
+ const token = ++st.token;
222
+ // This read supersedes any Show earlier still in flight: its answer will be dropped, so it no longer holds the button.
223
+ // And no Show earlier starts until this read is in: an older page must continue the first page actually shown.
224
+ st.earlierBusy = false;
225
+ st.firstBusy = true;
226
+ const current = () => states.get(pane) === st && st.token === token && pane.isConnected;
227
+ let body;
228
+ try { body = await api(journalPath(st)); } catch (err) {
229
+ if (!current()) return;
230
+ st.firstBusy = false;
231
+ console.warn('The project history could not be read', err);
232
+ // Keep what is shown, and say it may be out of date.
233
+ if (st.loaded && !st.unavailable) { st.stale = true; paint(pane); return; }
234
+ st.loaded = false;
235
+ st.error = typeof err?.body?.error === 'string' && err.body.error ? err.body.error : S.failed;
236
+ paint(pane);
237
+ return;
238
+ }
239
+ if (!current()) return;
240
+ st.firstBusy = false;
241
+ const uuid = body.project?.uuid ?? null;
242
+ const rootId = body.rootId ?? null;
243
+ // Another incarnation or Workspace folder than the rows shown: what the person opened or closed was about those.
244
+ if (st.loaded && (uuid !== st.uuid || rootId !== st.rootId)) st.open = new Map();
245
+ st.error = '';
246
+ st.stale = false;
247
+ st.loaded = true;
248
+ st.unavailable = typeof body.unavailable === 'string' ? body.unavailable : '';
249
+ st.uuid = uuid;
250
+ st.rootId = rootId;
251
+ st.entries = validEntries(body);
252
+ st.nextBefore = typeof body.nextBefore === 'string' ? body.nextBefore : null;
253
+ st.cursorGone = false;
254
+ st.earlierError = false;
255
+ st.earlierBusy = false;
256
+ paint(pane);
257
+ }
258
+
259
+ /** Read the next older page. One at a time; merged by entry id; dropped if the project or its folder changed. */
260
+ async function loadEarlier(pane) {
261
+ const st = states.get(pane);
262
+ if (!st || st.earlierBusy || st.firstBusy || !st.nextBefore) return;
263
+ st.earlierBusy = true;
264
+ st.earlierError = false;
265
+ paint(pane);
266
+ const token = st.token;
267
+ const current = () => states.get(pane) === st && st.token === token && pane.isConnected;
268
+ let body;
269
+ try { body = await api(journalPath(st, st.nextBefore)); } catch (err) {
270
+ if (!current()) return;
271
+ console.warn('Earlier project history could not be read', err);
272
+ st.earlierBusy = false;
273
+ st.earlierError = true;
274
+ paint(pane);
275
+ return;
276
+ }
277
+ if (!current()) return;
278
+ st.earlierBusy = false;
279
+ if ((body.project?.uuid ?? null) !== st.uuid || (body.rootId ?? null) !== st.rootId) {
280
+ // The project was recreated or the Workspace folder switched since the first page: what is shown is stale.
281
+ void loadFirst(pane);
282
+ return;
283
+ }
284
+ if (body.cursorFound === false) { st.cursorGone = true; st.nextBefore = null; paint(pane); return; }
285
+ const seen = new Set(st.entries.map((e) => e.id));
286
+ const fresh = validEntries(body).filter((e) => !seen.has(e.id));
287
+ st.entries = st.entries.concat(fresh);
288
+ st.nextBefore = typeof body.nextBefore === 'string' ? body.nextBefore : null;
289
+ st.announce = `Loaded ${fresh.length} earlier event${fresh.length === 1 ? '' : 's'}.`;
290
+ // Focus follows the read only if the person is still on it: the button (disabled while reading, so focus may have
291
+ // fallen to the page) — never when they moved on to Search or another control meanwhile.
292
+ const active = document.activeElement;
293
+ const stillHere = !pane.hidden && (!active || active === document.body || active.getAttribute?.('data-ph-act') === 'earlier');
294
+ paint(pane);
295
+ if (!stillHere) return;
296
+ const after = pane.querySelector('[data-ph-act="earlier"]');
297
+ if (after) after.focus({ preventScroll: true });
298
+ else if (fresh.length) pane.querySelector(`[data-ph-entry="${CSS.escape(fresh[0].id)}"]`)?.closest('details')?.querySelector('summary')?.focus({ preventScroll: true });
299
+ }
300
+
301
+ const wired = new WeakSet();
302
+ function wire(pane) {
303
+ if (wired.has(pane)) return;
304
+ wired.add(pane);
305
+ // A section drawn open fires `toggle` too, so only a toggle that follows a click on its heading is the person's.
306
+ pane.addEventListener('toggle', (event) => {
307
+ const st = states.get(pane);
308
+ const box = event.target.closest?.('.ph-section');
309
+ if (st && box && box.dataset.phArea === st.clicked) { st.open.set(st.clicked, box.hasAttribute('open')); st.clicked = null; }
310
+ }, true);
311
+ pane.addEventListener('click', (event) => {
312
+ const st = states.get(pane);
313
+ if (!st) return;
314
+ if (event.target.closest('.rh-summary')) st.clicked = event.target.closest('.ph-section')?.dataset.phArea ?? null;
315
+ const act = event.target.closest('[data-ph-act]');
316
+ if (!act) return;
317
+ if (act.dataset.phAct === 'retry') { st.error = ''; const read = loadFirst(pane); paint(pane); void read; }
318
+ else if (act.dataset.phAct === 'earlier') void loadEarlier(pane);
319
+ else if (act.dataset.phAct === 'reread') { st.cursorGone = false; const read = loadFirst(pane); paint(pane); void read; }
320
+ else if (act.dataset.phAct === 'clear-search') {
321
+ st.query = '';
322
+ const input = pane.querySelector('[data-ph-search]');
323
+ if (input) { input.value = ''; input.focus(); }
324
+ paint(pane);
325
+ }
326
+ });
327
+ pane.addEventListener('input', (event) => {
328
+ const st = states.get(pane);
329
+ if (!st || !event.target.closest?.('[data-ph-search]')) return;
330
+ st.query = event.target.value;
331
+ paint(pane);
332
+ });
333
+ }
334
+
335
+ /** Show `project`'s history in `pane` (the step was opened): the cache at once, then a fresh read of the newest page. */
336
+ function render(pane, project) {
337
+ if (!pane || !project?.id) return;
338
+ const st = stateFor(pane, project);
339
+ skeleton(pane, st);
340
+ const input = pane.querySelector('[data-ph-search]');
341
+ if (input && input.value !== st.query) input.value = st.query;
342
+ // The read starts first (it marks itself in flight synchronously), then the cache is painted with that known.
343
+ const read = loadFirst(pane);
344
+ paint(pane);
345
+ void read;
346
+ }
347
+
348
+ window.flolessProjectHistory = { render };
349
+ })();
@@ -44,6 +44,7 @@
44
44
  const command = (id, instance, label) => carriers[id](instance) + (instance ? ` data-command-instance-label="${esc(label || instance)}"` : '');
45
45
  const button = (act, label, id, instance, primary = false) => `<button type="button" data-folder-action="${act}" ${command(id, instance, review?.candidate?.name || review?.candidate?.path)}${primary ? ' class="primary"' : ''}${busy ? ' disabled data-blocked-reason="FloLess is finishing this folder review."' : ''}>${label}</button>`;
46
46
  async function api(path, body) {
47
+ await globalThis.flolessStartupAdmission?.admit(path, { method: body === undefined ? 'GET' : 'POST' });
47
48
  if (body !== undefined && !sessionReady) {
48
49
  sessionReady = (async () => {
49
50
  const response = await fetch('/api/editor/session', { method: 'POST', credentials: 'same-origin' });