diff --git a/changelog.d/added-nav-count-deltas.md b/changelog.d/added-nav-count-deltas.md new file mode 100644 index 0000000000..04022dce2b --- /dev/null +++ b/changelog.d/added-nav-count-deltas.md @@ -0,0 +1 @@ +- Tracker, online-contributor and Knowledge sidebar count pills briefly show the actual signed increase or decrease on live updates, with directional amber feedback and a static reduced-motion alternative. diff --git a/src/docs/dashboard-sections.md b/src/docs/dashboard-sections.md index 7b807078b6..e8a9246a4b 100644 --- a/src/docs/dashboard-sections.md +++ b/src/docs/dashboard-sections.md @@ -18,6 +18,14 @@ Hive has two release lines. **v5** is the stable line. **v6** is the newer line. For short definitions of the names the dashboard uses, see the [dashboard glossary](dashboard-glossary.md). For how the dashboard is built, see the [spoke dashboard guide](dashboard.md). +### Live sidebar count feedback + +The Hive activity monitor, Contributors and Knowledge navigation pills briefly show an upward or downward arrow and the actual signed count change. The number remains readable and the link works as before. Reduced-motion preferences keep the feedback static; there is no extra polling or repeated announcement on unchanged refreshes. + +The tracker’s gold pill counts default-view **rows** (issues, except folded review notes, plus PRs not drawn under an issue); its orange pill counts **waiting-on-you items**. These are not separate issue and PR totals. Contributors animates only **online** in online/registered, using the existing registered-profile heartbeat window, not connected sockets or changes in registered totals. Knowledge counts **facts**, the sum of layer `total_pages` values, when enabled; its disabled zero does not mean stored facts were deleted. If a remote layer is unhealthy, Knowledge still loads its available facts, marks the count as partial in its accessible label and tooltip, and suppresses delta feedback until a complete count is known again. + +Initial or unknown counts and route/filter redraws do not animate. After reconnection, feedback describes only the observed net numeric change, not whether an item was merged, closed or otherwise removed. + ## Words used on this page These words have a special meaning in Hive. Each entry explains them again the first time it uses them. diff --git a/src/pkg/dashboard/nav_count_delta.test.js b/src/pkg/dashboard/nav_count_delta.test.js new file mode 100644 index 0000000000..b226c2163e --- /dev/null +++ b/src/pkg/dashboard/nav_count_delta.test.js @@ -0,0 +1,290 @@ +// Execute the shipped helper and real badge writers, with a tiny DOM and +// deterministic clock. No browser, polling loop or Go process is started. +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const source = name => fs.readFileSync(path.join(__dirname, 'static-src/js', name + '.js'), 'utf8'); +const fn = (file, name) => { + const found = source(file).match(new RegExp('(?:async )?function ' + name + '\\([^\\n]*\\) \\{[\\s\\S]*?\\n \\}')); + assert.ok(found, name); + return found[0]; +}; +const IDS = ['activity-monitor-sidebar-badge', 'activity-monitor-waiting-badge', 'contributors-sidebar-badge', 'knowledge-sidebar-badge']; + +function load() { + let now = 0, nextTimer = 0; + const timers = new Map(), elements = new Map(); + function element(id) { + const attrs = {}; + const el = { id, attrs, textContent: '', hidden: false, title: '', + setAttribute(k, v) { attrs[k] = String(v); }, + removeAttribute(k) { delete attrs[k]; }, + querySelector() { return null; }, + classList: { toggle() {} }, + }; + elements.set(id, el); + return el; + } + IDS.concat(['activity-monitor-panel']).forEach(element); + const document = { hidden: false, getElementById: id => elements.get(id) || null }; + const ctx = vm.createContext({ document, window: {}, console, Number, + setTimeout(cb, ms) { const id = ++nextTimer; timers.set(id, { cb, at: now + ms }); return id; }, + clearTimeout(id) { timers.delete(id); }, + }); + vm.runInContext(source('nav-count-delta'), ctx); + vm.runInContext(` + var _kbCache = null, _kbInitialLoad = true, _kbRendered = false, _kbSetupView = 'none'; + var _cachedContributors = [], _stageTracker = null, _stageTrackerMoves = {}, _stageTrackerEvents = []; + var _stageTrackerFilter = {repo: 'filtered-out'}, _stageTrackerGroup = 'none', _stageTrackerCelebrating = {}; + function refreshSectionCardShell() {} + function setSectionSummary() {} + function contributorsSectionSummary() { return ''; } + function formatNumber(n) { return Number(n).toLocaleString('en-US'); } + var knowledgeRenders = 0; + function renderKnowledge() { knowledgeRenders++; } + function fetchBeadSynthStatus() {} + function fetchFactHistory() {} + function stageTrackerNoteMerges() {} + function stageTrackerNoteOpened() {} + function stageTrackerNoteMoves() {} + function stageTrackerSyncToolbar() {} + function stageTrackerWorkers() { return []; } + function stageTrackerNoteTuckSetting() { return false; } + function stageTrackerSharedPRs() { return {}; } + function stageTrackerRepoChipOn() { return false; } + function stageTrackerRepoChipSetting() { return ''; } + function stageTrackerTrainContiguous(rows) { return rows; } + function stageTrackerRegressionHandled() { return false; } + function stageTrackerOpenCounts() { return null; } + function stageTrackerRenderLabelDialog() {} + function stageTrackerMotionEffect() { return ''; } + function stageTrackerMotionSetting() { return ''; } + function stageTrackerReducedMotion() { return false; } + function stageTrackerSelectionSync() {} + function stageTrackerWaitingToast() {} + function stageTrackerActedAgo() { return ''; } + function setIfChanged(el, text) { el.innerHTML = text; } + `, ctx); + for (const [file, names] of [ + ['knowledge', ['sidebarPairBadgeText', 'setSidebarPairBadge', 'setSidebarCountBadge', 'kbTotalFactsFromStats', 'kbFactsLabel', 'kbSidebarFactCount', 'fetchKnowledgeStats']], + ['contributors', ['contributorsOnlineTitle', 'updateContributorBadge']], + ['tracker-waiting', ['stageTrackerWaitingOnYou', 'stageTrackerWaitingTitle', 'stageTrackerWaitKindWords', 'stageTrackerRenderWaiting']], + ['tracker-words-stage', ['stageTrackerDefaultFilter']], + ['tracker-filter-render', ['renderStageTracker']], + ['tracker-merged', ['stageTrackerMergingHoldRelease']], + ]) { + for (const name of names) vm.runInContext(fn(file, name), ctx); + } + for (const name of ['STAGE_TRACKER_AGE_MS', 'STAGE_TRACKER_SORTS', 'STAGE_TRACKER_ACTED_FILTERS', 'STAGE_TRACKER_PAGE_SIZES', 'STAGE_TRACKER_DEFAULT_PAGE_SIZE', 'STAGE_TRACKER_ATTENTION_STAGES']) { + const declaration = source(name === 'STAGE_TRACKER_ACTED_FILTERS' ? 'tracker-row' : 'tracker-words-stage').match(new RegExp('const ' + name + ' = [^\\n]+')); + assert.ok(declaration, name); + vm.runInContext(declaration[0], ctx); + } + vm.runInContext(source('tracker-filter'), ctx); + vm.runInContext(`const STAGE_TRACKER_WAITING_TOOLTIP_MAX = 5; const STAGE_TRACKER_WAIT_KIND_WORDS = {};`, ctx); + return { ctx, document, timers, element, badge: id => elements.get(id), + tick(ms = 1400) { + now += ms; + for (const [id, timer] of [...timers]) if (timer.at <= now) { timers.delete(id); timer.cb(); } + }, + }; +} +const delta = badge => badge.attrs['data-count-delta']; +const item = (number, kind = 'issue', extra = {}) => ({ repo: 'o/r', number, kind, ...extra }); +const stats = (...counts) => ({ enabled: true, layers: counts.map(total_pages => ({ type: 'project', total_pages })) }); +const knowledge = async (api, payload) => { + api.ctx.fetch = async url => ({ ok: true, json: async () => url === '/api/knowledge/stats' ? payload : [] }); + await api.ctx.fetchKnowledgeStats(); +}; + +for (const id of IDS) { + test(id + ': initial/unchanged/unknown/zero, rapid changes, cleanup and rerender', () => { + const api = load(), badge = api.badge(id), write = (n, live = true) => api.ctx.navCountDelta(badge, n, 'Count ' + n, live); + write(0); + assert.equal(delta(badge), undefined); + write(0); + assert.equal(api.timers.size, 0); + write(3); + assert.equal(delta(badge), '↑ +3'); + assert.match(badge.attrs['aria-label'], /increased by 3/); + const phase = badge.attrs['data-count-phase']; + api.tick(500); + write(5); + assert.equal(delta(badge), '↑ +2'); + assert.notEqual(badge.attrs['data-count-phase'], phase); + assert.equal(api.timers.size, 1); + write(3); + assert.equal(delta(badge), '↓ -2'); + write(3); + assert.equal(api.timers.size, 1); + api.tick(); + assert.equal(delta(badge), undefined); + assert.equal(api.timers.size, 0); + assert.equal(badge.attrs['aria-label'], 'Count 3'); + write(0); + assert.equal(delta(badge), '↓ -3', 'zero is a known value'); + for (const invalid of [null, undefined, NaN, -1, '8', Infinity, 1.5]) { + write(invalid); + write(8); + assert.equal(delta(badge), undefined, 'unknown -> known seeds, not a synthetic increase'); + } + write(9, false); + assert.equal(delta(badge), undefined, 'cached/route redraw does not animate'); + write(9); + assert.equal(delta(badge), undefined, 'redraw advanced the baseline'); + write(10); + const replacement = api.element(id); + api.ctx.navCountDelta(replacement, 10, 'Count 10'); + assert.equal(delta(badge), undefined); + assert.equal(delta(replacement), undefined); + assert.equal(api.timers.size, 0, 'replacement cancels the old element timer'); + }); +} + +test('real tracker renderer: new issues, PR removal, batching, filters, invalid payloads', () => { + const api = load(), badge = api.badge(IDS[0]), render = items => api.ctx.renderStageTracker({ items }); + render([item(1), item(2, 'pr')]); + assert.equal(badge.textContent, '2'); + assert.equal(delta(badge), undefined); + render([item(1), item(2, 'pr'), item(3)]); + assert.equal(delta(badge), '↑ +1'); + render([item(1), item(3)]); + assert.equal(delta(badge), '↓ -1'); + render([item(1), item(3), item(4), item(5), item(6)]); + assert.equal(delta(badge), '↑ +3'); + api.tick(); + api.ctx.renderStageTracker(); + assert.equal(delta(badge), undefined); + // A PR under a listed issue shares its row, not a new count. + render([item(1), item(3), item(4), item(5), item(6), item(7, 'pr', { nested_under: 1 })]); + assert.equal(delta(badge), undefined); + api.ctx.renderStageTracker({ status: 'initializing' }); + render([]); + assert.equal(badge.textContent, '0'); + assert.equal(delta(badge), undefined); +}); + +test('real waiting badge writer: independent count, explicit zero and invalid header', () => { + const api = load(), badge = api.badge(IDS[1]); + const write = count => api.ctx.stageTrackerRenderWaiting({ waiting_on_human: { count, items: [] } }, 0); + write(2); + write(5); + assert.equal(delta(badge), '↑ +3'); + write(0); + assert.equal(badge.textContent, '0'); + assert.equal(delta(badge), '↓ -5'); + write(undefined); + write(3); + assert.equal(delta(badge), undefined); + assert.equal(api.timers.size, 0); + assert.equal(delta(api.badge(IDS[0])), undefined); +}); + +test('a merged PR count delayed by the existing hold animates when that hold releases', () => { + const api = load(), badge = api.badge(IDS[0]); + api.ctx._stageTrackerMergingHold = {}; + api.ctx.holding = true; + api.ctx.stageTrackerMergingHoldView = d => api.ctx.holding ? { ...d, items: d.items.concat(item(2, 'pr')) } : d; + api.ctx.renderStageTracker({ items: [item(1)] }); + assert.equal(badge.textContent, '2'); + api.ctx.holding = false; + api.ctx.stageTrackerMergingHoldRelease(); + assert.equal(badge.textContent, '1'); + assert.equal(delta(badge), '↓ -1'); + api.tick(); + api.ctx.renderStageTracker(); + assert.equal(delta(badge), undefined, 'later cached redraw does not replay the release'); +}); + +test('contributors use online only, not active sockets or denominator changes', () => { + const api = load(), badge = api.badge(IDS[2]); + const write = (online, registered = 12, active = 99) => api.ctx.updateContributorBadge({ online, registered, active, presence_window: '15m' }); + write(2); + assert.equal(badge.textContent, '2/12'); + write(2, 20, 1); + assert.equal(delta(badge), undefined); + write(5, 20); + assert.equal(delta(badge), '↑ +3'); + write(3, 21); + assert.equal(delta(badge), '↓ -2'); + write(0); + assert.equal(badge.textContent, '0/12'); + assert.equal(delta(badge), '↓ -3'); + write(undefined); + assert.equal(badge.textContent, '0/12', 'unknown does not replace display with a fabricated zero'); + write(4); + assert.equal(delta(badge), undefined); +}); + +test('knowledge uses numeric layer fact totals, independent of formatting and disabled priming', async () => { + const api = load(), badge = api.badge(IDS[3]); + await knowledge(api, stats(1000, 20)); + assert.equal(badge.textContent, 1020); + assert.equal(delta(badge), undefined); + await knowledge(api, stats(1000, 20)); + assert.equal(delta(badge), undefined); + await knowledge(api, stats(1001, 22)); + assert.equal(delta(badge), '↑ +3'); + await knowledge(api, stats(1000, 21)); + assert.equal(delta(badge), '↓ -2'); + await knowledge(api, { enabled: true }); + assert.equal(badge.textContent, 1021); + assert.equal(badge.attrs['aria-label'], 'Knowledge fact count unavailable'); + assert.equal(api.ctx._kbInitialLoad, false); + await knowledge(api, stats()); + assert.equal(badge.textContent, 0); + assert.equal(delta(badge), undefined); + await knowledge(api, stats(2)); + assert.equal(delta(badge), '↑ +2'); + await knowledge(api, { enabled: false, layers: [] }); + assert.equal(delta(badge), undefined, 'disabling priming is not fact deletion'); + assert.equal(api.timers.size, 0); +}); + +test('an unhealthy Knowledge layer still loads and refreshes known facts without a synthetic delta', async () => { + const api = load(), badge = api.badge(IDS[3]); + const partial = { enabled: true, layers: [ + { type: 'project', total_pages: 5, healthy: true }, + { type: 'global', healthy: false }, + ] }; + await knowledge(api, partial); + assert.equal(badge.textContent, 5); + assert.equal(delta(badge), undefined); + assert.equal(badge.attrs['aria-label'], '5 facts known; some layer counts unavailable'); + assert.equal(api.ctx.knowledgeRenders, 1, 'first load renders despite the unhealthy remote'); + assert.equal(api.ctx._kbInitialLoad, false); + assert.equal(api.ctx._kbCache.layers[1].healthy, false); + assert.ok(Array.isArray(api.ctx._kbCache._documents), 'document fetch still reaches the cache'); + await knowledge(api, stats(7)); + assert.equal(badge.textContent, 7); + assert.equal(delta(badge), undefined, 'partial -> complete seeds a new baseline'); + await knowledge(api, stats(10)); + assert.equal(delta(badge), '↑ +3'); + await knowledge(api, partial); + assert.equal(badge.textContent, 5, 'known facts refresh when a layer later becomes unhealthy'); + assert.equal(delta(badge), undefined, 'missing remote counts are not fact deletion'); + assert.equal(api.timers.size, 0); + assert.equal(api.ctx._kbCache.layers[1].healthy, false); + assert.equal(api.ctx.knowledgeRenders, 3, 'changed layer sets keep rendering'); +}); + +test('reduced motion keeps static signed feedback; hidden tabs advance without animation', () => { + const api = load(), badge = api.badge(IDS[2]); + api.ctx.window.matchMedia = () => ({ matches: true }); + api.ctx.navCountDelta(badge, 1, '1 online'); + api.ctx.navCountDelta(badge, 4, '4 online'); + assert.equal(delta(badge), '↑ +3', 'feedback remains readable with reduced motion'); + // CSS, not a JS listener, disables motion (including preference changes + // during a cue). Keep that shipped rule covered alongside behavior. + const css = fs.readFileSync(path.join(__dirname, 'static-src/css/design-system.css'), 'utf8'); + assert.match(css, /@media \(prefers-reduced-motion: reduce\) \{\s*\[data-count-phase\]::after \{ animation: none; \}/); + api.document.hidden = true; + api.ctx.navCountDelta(badge, 7, '7 online'); + assert.equal(delta(badge), undefined); + api.document.hidden = false; + api.ctx.navCountDelta(badge, 7, '7 online'); + assert.equal(delta(badge), undefined); + assert.equal(api.timers.size, 0); +}); diff --git a/src/pkg/dashboard/stage_tracker_ui_test.go b/src/pkg/dashboard/stage_tracker_ui_test.go index 60a235754c..67f573b713 100644 --- a/src/pkg/dashboard/stage_tracker_ui_test.go +++ b/src/pkg/dashboard/stage_tracker_ui_test.go @@ -26,7 +26,7 @@ func TestStageTrackerSectionWiring(t *testing.T) { `id="oc-waiting-on-you" data-action="showWaitingOnYou"`, `id="activity-monitor-waiting" data-action="hamFilter" data-arg0="waitingOnYou" data-arg1="toggle"`, `if (f.waitingOnYou && !item.waiting_on_you) return false;`, - `function stageTrackerRenderWaiting(d, nowMs)`, + `function stageTrackerRenderWaiting(d, nowMs, live = true)`, `function stageTrackerWaitingToast(w, nowMs)`, `if (typeof window.hiveKioskMode === 'function' && window.hiveKioskMode()) return;`, `const STAGE_TRACKER_WAITING_FILTER_PARAM = 'waiting-on-you';`, diff --git a/src/pkg/dashboard/stage_tracker_waiting.test.js b/src/pkg/dashboard/stage_tracker_waiting.test.js index 4c89c3274a..846970be2e 100644 --- a/src/pkg/dashboard/stage_tracker_waiting.test.js +++ b/src/pkg/dashboard/stage_tracker_waiting.test.js @@ -18,6 +18,7 @@ function pick(re, what) { function load(env) { const src = [ + fs.readFileSync(path.join(__dirname, 'static-src/js/nav-count-delta.js'), 'utf8'), 'var toasts = [];', 'var navigated = [];', 'var filtered = [];', @@ -40,7 +41,7 @@ function load(env) { pick(/function stageTrackerWaitingOnYou\(d\) \{[\s\S]*?\n \}\n/, 'stageTrackerWaitingOnYou'), pick(/function stageTrackerWaitKindWords\(kind\) \{[^\n]*\n/, 'stageTrackerWaitKindWords'), pick(/function stageTrackerWaitingTitle\(w, nowMs\) \{[\s\S]*?\n \}\n/, 'stageTrackerWaitingTitle'), - pick(/function stageTrackerRenderWaiting\(d, nowMs\) \{[\s\S]*?\n \}\n/, 'stageTrackerRenderWaiting'), + pick(/function stageTrackerRenderWaiting\(d, nowMs, live = true\) \{[\s\S]*?\n \}\n/, 'stageTrackerRenderWaiting'), pick(/function stageTrackerWaitingToast\(w, nowMs\) \{[\s\S]*?\n \}\n/, 'stageTrackerWaitingToast'), pick(/function stageTrackerWaitingToastText\(w\) \{[\s\S]*?\n \}\n/, 'stageTrackerWaitingToastText'), pick(/function showWaitingOnYou\(\) \{[\s\S]*?\n \}\n/, 'showWaitingOnYou'), diff --git a/src/pkg/dashboard/static-src/css/design-system.css b/src/pkg/dashboard/static-src/css/design-system.css index 41957ae967..472b1a51d8 100644 --- a/src/pkg/dashboard/static-src/css/design-system.css +++ b/src/pkg/dashboard/static-src/css/design-system.css @@ -84,6 +84,33 @@ .oc-nav-count--waiting:not([data-zero]) + .oc-nav-count { margin-left: var(--sp-1); } .oc-nav-count--waiting:not([data-zero]) { --component-status: var(--status-attention); background: color-mix(in srgb, var(--component-status) 16%, transparent); border-color: color-mix(in srgb, var(--component-status) 50%, transparent); color: var(--component-status); } .oc-nav-count--waiting[data-zero] { display: none; } + /* A short, out-of-flow net delta on explicitly wired navigation counts. + Keep the zero waiting badge visible just long enough to show its drop. */ + .oc-nav-count[data-count-delta] { position: relative; } + .oc-nav-item:has(> .oc-nav-count[data-count-delta]) { overflow: visible; z-index: 1; } + #activity-monitor-waiting-badge[data-zero][data-count-delta] { + display: inline-flex; position: absolute; right: 3rem; + visibility: hidden; padding: 0; border: 0; + } + .oc-nav-count[data-count-delta]::after { + content: attr(data-count-delta); position: absolute; bottom: calc(100% + 2px); right: 0; + visibility: visible; pointer-events: none; z-index: 1; padding: var(--sp-0) var(--sp-2); border-radius: var(--r-pill); + background: var(--surface); color: var(--brand); border: 1px solid var(--brand); + font-size: var(--fs-2xs); line-height: 1.4; font-variant-numeric: tabular-nums; + } + #contributors-sidebar-badge[data-count-delta]::after, + #knowledge-sidebar-badge[data-count-delta]::after { + bottom: auto; top: 50%; right: calc(100% + var(--sp-1)); translate: 0 -50%; + } + [data-count-direction="up"] { --nav-count-start: 3px; } + [data-count-direction="down"] { --nav-count-start: -3px; } + [data-count-phase="a"]::after { animation: nav-count-a 220ms ease-out; } + [data-count-phase="b"]::after { animation: nav-count-b 220ms ease-out; } + @keyframes nav-count-a { from { opacity: 0; transform: translateY(var(--nav-count-start)); } to { opacity: 1; transform: translateY(0); } } + @keyframes nav-count-b { from { opacity: 0; transform: translateY(var(--nav-count-start)); } to { opacity: 1; transform: translateY(0); } } + @media (prefers-reduced-motion: reduce) { + [data-count-phase]::after { animation: none; } + } /* pill size steps */ .token-model-chip { padding: 4px 10px; font-size: var(--fs-sm); } .nous-config-pill { padding: 3px 10px; font-size: var(--fs-sm); } diff --git a/src/pkg/dashboard/static-src/js/contributors.js b/src/pkg/dashboard/static-src/js/contributors.js index 3c1f4af243..0e5410074c 100644 --- a/src/pkg/dashboard/static-src/js/contributors.js +++ b/src/pkg/dashboard/static-src/js/contributors.js @@ -493,12 +493,17 @@ refreshSectionCardShell('contributors-section'); const sidebarBadge = document.getElementById('contributors-sidebar-badge'); const statusBadge = document.getElementById('contributors-status-badge'); - if (!pool) return; - const onlineCount = Number(pool.online) || 0; - const totalCount = Number(pool.registered) || 0; + if (!pool || !Number.isSafeInteger(pool.online) || pool.online < 0 || + !Number.isSafeInteger(pool.registered) || pool.registered < 0) { + navCountDelta(sidebarBadge, null); + return; + } + const onlineCount = pool.online; + const totalCount = pool.registered; const tip = contributorsOnlineTitle(onlineCount, totalCount, pool.presence_window); // Same two-part pill as Governor / Overview: "online/total". if (sidebarBadge) setSidebarPairBadge(sidebarBadge, onlineCount, totalCount, tip); + navCountDelta(sidebarBadge, onlineCount, 'Contributors: ' + tip); setSectionSummary('contributors-section', contributorsSectionSummary(_cachedContributors || [], pool)); if (statusBadge) { statusBadge.textContent = `${onlineCount} online / ${totalCount} registered`; @@ -530,4 +535,3 @@ } // fetchContributors() + fetchLeaderboard() — deferred to _deferredInit - diff --git a/src/pkg/dashboard/static-src/js/knowledge.js b/src/pkg/dashboard/static-src/js/knowledge.js index 173320d116..a60de19e0d 100644 --- a/src/pkg/dashboard/static-src/js/knowledge.js +++ b/src/pkg/dashboard/static-src/js/knowledge.js @@ -150,6 +150,16 @@ return formatNumber(total) + ' fact' + (total === 1 ? '' : 's'); } + // Validate the same layer totals used by the displayed facts badge. + // Missing layers are unknown, not an empty knowledge base. + function kbSidebarFactCount(stats) { + if (!stats || typeof stats.enabled !== 'boolean') return null; + if (!stats.enabled) return 0; + if (!Array.isArray(stats.layers) || stats.layers.some(l => !l || !Number.isSafeInteger(l.total_pages) || l.total_pages < 0)) return null; + const count = kbTotalFactsFromStats(stats); + return Number.isSafeInteger(count) ? count : null; + } + // ── Document Sources ── const DOC_CONTENT_ICONS = { 'text/html': '🌐', 'application/pdf': '📄', 'text/plain': '📝', 'text/markdown': '📝', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': '📋' }; @@ -231,10 +241,21 @@ _kbCache = await r.json(); _kbCache._documents = (docsR && docsR.ok) ? await docsR.json() : []; setSectionSummary('knowledge-section', kbFactsLabel(kbTotalFactsFromStats(_kbCache))); - var kbBadge = document.getElementById('knowledge-sidebar-badge'); + const kbBadge = document.getElementById('knowledge-sidebar-badge'); if (kbBadge) { - var kbFacts = kbTotalFactsFromStats(_kbCache); - setSidebarCountBadge(kbBadge, _kbCache && _kbCache.enabled ? kbFacts : 0, kbFactsLabel(kbFacts)); + const kbFacts = kbSidebarFactCount(_kbCache); + const kbShown = kbTotalFactsFromStats(_kbCache); + const hasLayers = Array.isArray(_kbCache.layers); + const title = kbFacts !== null ? kbFactsLabel(kbShown) : hasLayers + ? kbFactsLabel(kbShown) + ' known; some layer counts unavailable' + : 'Knowledge fact count unavailable'; + // Toggling priming changes what the badge shows, not stored facts. + if (prev && prev.enabled !== _kbCache.enabled) navCountDelta(kbBadge, null); + // Partial layer stats still refresh the section and its known + // facts. Only the delta baseline needs a complete numeric total. + if (kbFacts !== null || hasLayers) setSidebarCountBadge(kbBadge, _kbCache.enabled ? kbShown : 0, title); + else kbBadge.title = title; + navCountDelta(kbBadge, kbFacts, title); } if (_kbInitialLoad && _kbCache && _kbCache.enabled) { _kbSetupView = 'none'; @@ -2397,4 +2418,3 @@ await kcSyncNow(name); setTimeout(() => kbLoadIntegrationsModal(_kbIntegrationSelected), 1500); } - diff --git a/src/pkg/dashboard/static-src/js/nav-count-delta.js b/src/pkg/dashboard/static-src/js/nav-count-delta.js new file mode 100644 index 0000000000..c06c2c08b0 --- /dev/null +++ b/src/pkg/dashboard/static-src/js/nav-count-delta.js @@ -0,0 +1,54 @@ + // Only explicitly wired navigation counts participate. Keep raw-number + // baselines outside the DOM: filters/routes can redraw without live data. + const NAV_COUNT_CUE_MS = 1400; + const _navCountDeltas = new Map(); + function navCountDelta(badge, count, label, live = true) { + if (!badge) return; + let state = _navCountDeltas.get(badge.id); + const replaced = state && state.badge !== badge; + if (replaced) state.clear(); + if (!state || replaced) { + state = { badge, count: null, timer: null, phase: false, delta: '', label: '' }; + state.clear = () => { + if (state.timer !== null) clearTimeout(state.timer); + state.timer = null; + state.delta = ''; + badge.removeAttribute('data-count-delta'); + badge.removeAttribute('data-count-direction'); + badge.removeAttribute('data-count-phase'); + if (state.label) badge.setAttribute('aria-label', state.label); + }; + _navCountDeltas.set(badge.id, state); + } + if (!Number.isSafeInteger(count) || count < 0) { + if (label) state.label = label; + state.clear(); + state.count = null; + return; + } + state.label = label; + const previous = state.count; + state.count = count; + if (previous === null || previous === count || replaced) { + badge.setAttribute('aria-label', label + state.delta); + return; + } + state.clear(); + // Re-rendering cached rows is not a new observation. A reconnect is + // simply a net count change; never claim it was a merge/open event. + if (!live || document.hidden) return; + const delta = count - previous; + state.delta = ', ' + (delta > 0 ? 'increased' : 'decreased') + ' by ' + Math.abs(delta); + badge.setAttribute('aria-label', label + state.delta); + badge.setAttribute('data-count-delta', (delta > 0 ? '↑ +' : '↓ ') + delta); + badge.setAttribute('data-count-direction', delta > 0 ? 'up' : 'down'); + state.phase = !state.phase; + badge.setAttribute('data-count-phase', state.phase ? 'a' : 'b'); + state.timer = setTimeout(state.clear, NAV_COUNT_CUE_MS); + } + + function stageTrackerSidebarCountsUnknown() { + for (const id of ['activity-monitor-sidebar-badge', 'activity-monitor-waiting-badge']) { + navCountDelta(document.getElementById(id), null); + } + } diff --git a/src/pkg/dashboard/static-src/js/tracker-filter-render.js b/src/pkg/dashboard/static-src/js/tracker-filter-render.js index 71a9d7dc71..27a0629c86 100644 --- a/src/pkg/dashboard/static-src/js/tracker-filter-render.js +++ b/src/pkg/dashboard/static-src/js/tracker-filter-render.js @@ -51,7 +51,7 @@ _stageTrackerPollErrorSince = 0; } - function renderStageTracker(data) { + function renderStageTracker(data, countRefresh = false) { if (data && typeof data === 'object') { _stageTracker = data; stageTrackerNoteMerges(data); stageTrackerNoteOpened(data); stageTrackerNoteMoves(data); } // Row-action feedback rides the payload: a result toast leaves and a // row stops "acting" once the item it targets reads a new state. @@ -62,6 +62,7 @@ // Rows under a "Merging" hold the payload already dropped ride along (#15245). const d = typeof stageTrackerMergingHoldView === 'function' ? stageTrackerMergingHoldView(_stageTracker, _stageTrackerMergingHold, nowMs) : _stageTracker; if (!d || d.status === 'initializing' || !Array.isArray(d.items)) { + stageTrackerSidebarCountsUnknown(); setIfChanged(el, '