Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/fixed-inbox-render-before-role.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- The dashboard Inbox now waits for the viewer's role before its first render and re-renders as soon as the role resolves, so owners no longer lose Share → Hive actions, ▶ Play and the bulk Hive menu until the next 60-second refresh; a failed role lookup is retried with backoff and falls back to read-only.
125 changes: 125 additions & 0 deletions dashboard/test/inbox-role-race.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
'use strict';

// The Inbox must not render with an unknown role (treated as read) and must
// re-render the moment /api/role resolves, instead of waiting for the 60 s
// refresh. Functions are extracted from the generated dashboard page.
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 indexHtml = fs.readFileSync(path.join(__dirname, '..', '..', 'src', 'pkg', 'dashboard', 'static', 'index.html'), 'utf8');

function extractFunction(name) {
const start = indexHtml.indexOf('function ' + name + '(');
assert.notEqual(start, -1, `${name} function exists`);
const brace = indexHtml.indexOf('{', start);
let depth = 0;
for (let i = brace; i < indexHtml.length; i++) {
const ch = indexHtml[i];
if (ch === '{') depth++;
if (ch === '}') depth--;
if (depth === 0) return (indexHtml.slice(start - 6, start) === 'async ' ? 'async ' : '') + indexHtml.slice(start, i + 1);
}
throw new Error(`unterminated ${name}`);
}

const NAMES = ['inboxRoleKnown', 'inboxOnRoleReady', 'inboxCanShare', 'inboxViewerCanPlay', 'renderInbox', 'hiveFetchRoleOnce', 'hiveRoleSettled', 'hiveApplyRoleData', 'hiveRetryRole'];

function makeSandbox(opts) {
const panel = { innerHTML: '' };
const sb = {
window: { _hiveRoleListeners: [] },
document: { getElementById: (id) => (id === 'inbox-panel' ? panel : null) },
panel,
_inboxCache: { items: [{ source: 'plaud', id: 'a', processed: false }], sources: [], settings: {} },
_inboxSelected: new Set(),
_inboxShowProcessed: false,
_inboxFocusKey: '',
refreshSectionCardShell: () => {},
setSidebarCountBadge: () => {},
setSectionSummary: () => {},
escapeHtml: (s) => String(s),
viewerIsOwner: () => sb.window._hiveRole === 'owner',
inboxSourceIcon: () => '',
inboxCanAdd: () => false,
inboxItemHtml: () => '<div class="item"></div>',
inboxPreserveAudio: (p, fn) => fn(),
inboxApplyFocus: () => {},
// Same effect as the real showGHAuthState: it records the role.
showGHAuthState: (loggedIn, user, avatar, role) => { sb.window._hiveUser = user; if (role) sb.window._hiveRole = role; },
fetch: opts.fetch,
setTimeout: (fn) => { fn(); return 0; },
console, Math, Number, Array, Error, Promise, String,
HIVE_ROLE_FETCH_ATTEMPTS: 3,
HIVE_ROLE_RETRY_BASE_MS: 500,
HIVE_ROLE_SERVER_ERROR_STATUS: 500,
};
vm.createContext(sb);
vm.runInContext(NAMES.map(extractFunction).join('\n'), sb);
// Same registration inbox.js performs at load.
sb.window._hiveRoleListeners.push(sb.inboxOnRoleReady);
return sb;
}

test('inbox renders a loading state, not a read-only view, while the role is unknown', () => {
const sb = makeSandbox({});
sb.renderInbox();
assert.match(sb.panel.innerHTML, /Loading inbox/);
assert.doesNotMatch(sb.panel.innerHTML, /Select all/);
});

test('role arriving as owner re-renders the Inbox with the Hive actions', () => {
const sb = makeSandbox({});
sb.renderInbox();
assert.match(sb.panel.innerHTML, /Loading inbox/);
sb.window._hiveRole = 'owner';
sb.hiveRoleSettled(false);
assert.match(sb.panel.innerHTML, /Select all/);
assert.equal(sb.inboxViewerCanPlay(), true);
});

test('role arriving as read keeps the Hive actions hidden', () => {
const sb = makeSandbox({});
sb.window._hiveRole = 'read';
sb.hiveRoleSettled(false);
assert.doesNotMatch(sb.panel.innerHTML, /Loading inbox/);
assert.doesNotMatch(sb.panel.innerHTML, /Select all/);
assert.equal(sb.inboxViewerCanPlay(), false);
});

test('an unchanged role does not re-render on later auth checks', () => {
const sb = makeSandbox({});
sb.window._hiveRole = 'owner';
sb.hiveRoleSettled(false);
sb.panel.innerHTML = 'sentinel';
sb.hiveRoleSettled(false);
assert.equal(sb.panel.innerHTML, 'sentinel');
});

test('role lookup that stays failed retries, then falls back to read-only and says so', async () => {
let calls = 0;
const sb = makeSandbox({ fetch: async () => { calls++; throw new Error('network'); } });
sb.renderInbox();
assert.match(sb.panel.innerHTML, /Loading inbox/);
await sb.hiveRetryRole();
assert.equal(calls, 2, 'retried after the first attempt (made by checkGHAuth)');
assert.doesNotMatch(sb.panel.innerHTML, /Loading inbox/);
assert.doesNotMatch(sb.panel.innerHTML, /Select all/);
assert.match(sb.panel.innerHTML, /Could not determine your role/);
});

test('role lookup recovers when a retry succeeds', async () => {
let calls = 0;
const sb = makeSandbox({ fetch: async () => { calls++; return calls < 2 ? { status: 503, json: async () => ({}) } : { status: 200, json: async () => ({ user: 'andy', role: 'owner' }) }; } });
await sb.hiveRetryRole();
assert.equal(calls, 2);
assert.match(sb.panel.innerHTML, /Select all/);
assert.doesNotMatch(sb.panel.innerHTML, /Could not determine your role/);
});

test('a non-retryable answer is not retried', async () => {
const sb = makeSandbox({ fetch: async () => ({ status: 404, json: async () => { throw new Error('not json'); } }) });
await assert.rejects(sb.hiveFetchRoleOnce(), (e) => !e.retryable);
});
2 changes: 1 addition & 1 deletion src/pkg/dashboard/sentinel_pill_11416_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ func TestSentinelFlaggedPRPillWiring(t *testing.T) {
}
// The role read must not depend on a signed-in user.
roleRead := strings.Index(html, "if (roleData.sentinel_label)")
userGate := strings.Index(html, "if (roleData.user) {\n if (roleData.automerge_label)")
userGate := strings.Index(html, "if (!roleData.user) return false;")
if roleRead < 0 || userGate < 0 || roleRead > userGate {
t.Errorf("sentinel label must be read before the roleData.user gate")
}
Expand Down
91 changes: 75 additions & 16 deletions src/pkg/dashboard/static-src/js/gh-auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@
// browser as the one that asked.
let ghFlowID = '';
const GH_AUTH_CHECK_INTERVAL_MS = 300000;
// /api/role is retried on network errors and 5xx before the viewer is
// treated as read-only: 3 attempts, waiting 0.5 s then 1 s between them.
const HIVE_ROLE_FETCH_ATTEMPTS = 3;
const HIVE_ROLE_RETRY_BASE_MS = 500;
const HIVE_ROLE_SERVER_ERROR_STATUS = 500;
const GH_AUTH_SUCCESS_DISMISS_MS = 1500;

function copyDeviceCode() {
Expand Down Expand Up @@ -258,24 +263,78 @@
showToast('Signed out of GitHub', 'info');
}

async function checkGHAuth() {
/* One /api/role attempt. Network errors and 5xx are marked retryable; an
answer that is not (4xx, an HTML 404 from a static host) is final. */
async function hiveFetchRoleOnce() {
let resp;
try { resp = await fetch('/api/role'); } catch (e) { e.retryable = true; throw e; }
if (resp.status >= HIVE_ROLE_SERVER_ERROR_STATUS) {
const err = new Error('HTTP ' + resp.status);
err.retryable = true;
throw err;
}
return await resp.json();
}

/* The role is "settled" once /api/role answered or gave up. Sections that
gate on it (the Inbox) hold a neutral loading state until then and
subscribe via window._hiveRoleListeners; they are notified the first
time and whenever the role or the failed flag changes. This is separate
from _hiveAuthKnown so the tracker never waits on the retries below. */
function hiveRoleSettled(failed) {
const sig = String(window._hiveRole || '') + '|' + (failed ? 'failed' : 'ok');
const changed = !window._hiveRoleSettled || window._hiveRoleSig !== sig;
window._hiveRoleFailed = !!failed;
window._hiveRoleSettled = true;
window._hiveRoleSig = sig;
if (!changed) return;
(window._hiveRoleListeners || []).forEach(function(fn) { try { fn(); } catch (e) { console.error(e); } });
}

function hiveApplyRoleData(roleData) {
if (roleData.sentinel_label) window._hiveSentinelLabel = roleData.sentinel_label;
if (!roleData.user) return false;
if (roleData.automerge_label) window._hiveAutoMergeLabel = roleData.automerge_label;
/* OIDC identity keys ("ibmid:5500…") are not GitHub logins — don't
fabricate a github.com/<key>.png avatar for them; showGHAuthState
falls back to an initials avatar and the server-resolved
display_name. */
var ghAvatar = roleData.user.indexOf(':') === -1
? 'https://github.com/' + roleData.user + '.png'
: '';
showGHAuthState(true, roleData.user, ghAvatar, roleData.role, roleData.display_name);
return true;
}

/* Background retries after a retryable first failure, with exponential
backoff. If they all fail the viewer stays read-only and the Inbox says
so. */
async function hiveRetryRole() {
if (window._hiveRoleRetrying) return;
window._hiveRoleRetrying = true;
try {
const roleResp = await fetch('/api/role');
const roleData = await roleResp.json();
if (roleData.sentinel_label) window._hiveSentinelLabel = roleData.sentinel_label;
if (roleData.user) {
if (roleData.automerge_label) window._hiveAutoMergeLabel = roleData.automerge_label;
/* OIDC identity keys ("ibmid:5500…") are not GitHub logins — don't
fabricate a github.com/<key>.png avatar for them; showGHAuthState
falls back to an initials avatar and the server-resolved
display_name. */
var ghAvatar = roleData.user.indexOf(':') === -1
? 'https://github.com/' + roleData.user + '.png'
: '';
showGHAuthState(true, roleData.user, ghAvatar, roleData.role, roleData.display_name);
return;
for (let attempt = 1; attempt < HIVE_ROLE_FETCH_ATTEMPTS; attempt++) {
await new Promise(function(resolve) { setTimeout(resolve, HIVE_ROLE_RETRY_BASE_MS * Math.pow(2, attempt - 1)); });
try {
const roleData = await hiveFetchRoleOnce();
hiveApplyRoleData(roleData);
hiveRoleSettled(false);
return;
} catch (e) { if (!e.retryable) break; }
}
} catch (e) {}
hiveRoleSettled(true);
} finally { window._hiveRoleRetrying = false; }
}

async function checkGHAuth() {
try {
const roleData = await hiveFetchRoleOnce();
const applied = hiveApplyRoleData(roleData);
hiveRoleSettled(false);
if (applied) return;
} catch (e) {
if (e && e.retryable) hiveRetryRole(); else hiveRoleSettled(true);
}
try {
const resp = await fetch('/api/gh-user-auth/status');
const data = await resp.json();
Expand Down
9 changes: 8 additions & 1 deletion src/pkg/dashboard/static-src/js/inbox.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,12 @@
function inboxSourceIcon(src) { return INBOX_SOURCE_ICONS[src] || '📥'; }
// Uploaded documents have no audio; uploaded audio/video does.
function inboxItemHasAudio(it) { return !it || it.source !== 'upload' || it.upload_kind === 'audio' || it.upload_kind === 'video'; }
// The role is known once /api/role settled (answered, or retries gave up:
// then it is undefined and every gate treats the viewer as read-only).
// Before that the Inbox renders a neutral loading state, never a guessed 'read'.
function inboxRoleKnown() { return window._hiveRoleSettled === true || window._hiveRole !== undefined; }
function inboxOnRoleReady() { if (_inboxCache) renderInbox(); }
(window._hiveRoleListeners = window._hiveRoleListeners || []).push(inboxOnRoleReady);
function inboxItemKey(it) { return it.source + '/' + it.id; }
// Playback is a read of private audio: owners and read-write sessions.
function inboxViewerCanPlay() { return window._hiveRole === 'owner' || window._hiveRole === 'read-write'; }
Expand Down Expand Up @@ -635,7 +641,7 @@
const badge = document.getElementById('inbox-sidebar-badge');
const data = _inboxCache;
if (!panel) return;
if (!data) { panel.innerHTML = '<div class="muted-note">Loading inbox…</div>'; return; }
if (!data || !inboxRoleKnown()) { panel.innerHTML = '<div class="muted-note">Loading inbox…</div>'; return; }
const items = data.items || [];
const unprocessed = Number(data.unprocessed) || 0;
if (badge) setSidebarCountBadge(badge, unprocessed, unprocessed + ' unprocessed');
Expand All @@ -658,6 +664,7 @@
(owner ? '<button type="button" class="hv-btn btn-secondary btn-sm" data-action="inboxOpenSettings" title="Auto-routing rules, default RFC repository, dibs URL, transcription">⚙ Auto-routing (' + rules + ')</button>' : '') +
'</div></div>';
if (data.error) html += '<div class="kc-error muted-note">' + escapeHtml(data.error) + '</div>';
if (window._hiveRoleFailed && !window._hiveRole) html += '<div class="muted-xs">Could not determine your role, so actions are read-only. It will retry automatically.</div>';
if (inboxCanAdd()) html += inboxAddPanelHtml() + inboxUploadsHtml();
if (!settings.spek_ready && owner) html += '<p class="muted-xs">RFC filing needs at least one enabled, unpaused agent to draft the spec with spektacular (<code>inbox.spek.agent</code> overrides the default; <code>inbox.spek.binary</code> names the CLI the agent runs).</p>';
if (_inboxFocusKey && items.some(it => it.processed && inboxItemKey(it) === _inboxFocusKey)) _inboxShowProcessed = true;
Expand Down
Loading
Loading