multiuser: token identity, invites + bootstrap, owner-gated runs, fork, user packages; spectator spa; utc house rule

This commit is contained in:
2026-11-14 20:01:15 +00:00
parent 9f85adc3c6
commit 711634cc38
15 changed files with 1134 additions and 105 deletions
+217 -18
View File
@@ -12,10 +12,14 @@
const $ = (id) => document.getElementById(id);
const TOKEN_KEY = 'rp-token';
const authToken = () => { try { return localStorage.getItem(TOKEN_KEY) ?? ''; } catch { return ''; } };
const state = {
view: null, runId: null, seq: 0, poll: null, paper: [],
files: null, drafts: {}, currentFile: null, fileSpecs: {}, repoPrompts: {},
vars: [], pkg: null, log: [],
me: null, // the signed-in user ({ id, name, superuser }) or null
};
// --- diagnostics: a rolling event log that survives refreshes ---------------
@@ -48,7 +52,10 @@ async function api(path, opts = {}) {
try {
const res = await fetch(`/api${path}`, {
method: opts.method ?? 'GET',
headers: opts.body !== undefined ? { 'content-type': 'application/json' } : {},
headers: {
...(opts.body !== undefined ? { 'content-type': 'application/json' } : {}),
...(authToken() ? { authorization: `Bearer ${authToken()}` } : {}),
},
body: opts.body !== undefined ? JSON.stringify(opts.body) : undefined,
...(opts.keepalive ? { keepalive: true } : {}), // outlives the page — the notepad flush
});
@@ -58,6 +65,14 @@ async function api(path, opts = {}) {
e.detail = data.detail;
e.status = res.status;
logEvent('api', `${label} ${res.status} ${Math.round(performance.now() - started)}ms — ${e.message}`);
// a rejected token ends the session: drop it and show the claim
// view — every path leads there until a fresh one is claimed
if (res.status === 401 && path !== '/session' && authToken()) {
try { localStorage.removeItem(TOKEN_KEY); } catch {}
state.me = null;
logEvent('nav', 'signed out: token rejected');
setTimeout(render, 0);
}
throw e;
}
logEvent('api', `${label} ${res.status} ${Math.round(performance.now() - started)}ms`);
@@ -348,6 +363,7 @@ async function render() {
stopPoll();
hideBanner();
const p = location.pathname;
if (!state.me) return viewClaim(seq); // signed out: every path leads to the claim
let m;
if (p === '/') return viewHome(seq);
if (p === '/new') return viewNew(seq);
@@ -359,8 +375,13 @@ async function render() {
function show(view) {
if (state.view === 'play' && view !== 'play') saveNotes(); // flush the pad when leaving play
state.view = view;
for (const v of ['home', 'new', 'setup', 'play']) $(`view-${v}`).hidden = v !== view;
for (const v of ['claim', 'home', 'new', 'setup', 'play']) $(`view-${v}`).hidden = v !== view;
document.body.classList.toggle('play', view === 'play');
// identity chrome: who is signed in. Signing in is permanent and
// per-browser (the token lives in localStorage); there is no sign-out
// — the lifecycle story is a roadmap extension point
$('who').textContent = state.me ? `${state.me.name}${state.me.superuser ? ' · op' : ''}` : '';
$('who').title = state.me?.id ?? '';
$('window-info').textContent = '';
$('conflict').hidden = true;
renderMeter(null);
@@ -368,6 +389,21 @@ function show(view) {
if (view !== 'play') $('ask-modal').close();
}
// --- the claim view ---------------------------------------------------------------
async function viewClaim(seq) {
show('claim');
$('claim-code').value = '';
$('claim-name').value = '';
let fresh = false;
try { fresh = (await api('/session')).fresh; } catch {} // public: works signed out
if (seq !== state.seq) return;
$('claim-hint').textContent = fresh
? 'this deployment has no users yet — the superuser invite is in state/bootstrap-invite.txt on the server'
: 'a single-use invite code, from the operator';
$('claim-code').focus();
}
// --- home -----------------------------------------------------------------------
async function viewHome(seq) {
@@ -378,16 +414,81 @@ async function viewHome(seq) {
list.textContent = '';
if (!runs.length) {
list.appendChild(el('div', 'hint', 'no runs yet — start one from a package'));
return;
}
for (const r of runs) {
const mine = state.me && r.owner === state.me.id;
const card = el('button', 'card run-card');
card.appendChild(el('span', 'card-name', r.display ?? r.id));
card.appendChild(el('span', 'card-meta', `${r.package} · ring A ${r.fill?.a ?? 0} / B ${r.fill?.b ?? 0} · ${r.id}${r.model ? ` · ${r.model}` : ''}`));
// the name carries the content facts plus the ownership garnish;
// started-or-forked rides the meta — chrome, never model-facing
card.appendChild(el('span', 'card-name', `${r.display ?? r.id}${ownershipTag(r, mine)}`));
card.appendChild(el('span', 'card-meta', `${r.package} · ${r.forked ? `forked ${fmtUnix(r.forked)}` : `started ${r.created ?? '?'}`} · ring A ${r.fill?.a ?? 0} / B ${r.fill?.b ?? 0} · ${r.id}${r.model ? ` · ${r.model}` : ''}`));
card.appendChild(el('span', `card-state ${runStateClass(r)}`, runStateText(r)));
card.addEventListener('click', () => navigate(r.lastSession ? `/runs/${r.id}` : `/runs/${r.id}/setup`));
// another user's draft is read-only: the play view says so; your own opens the editor
card.addEventListener('click', () => navigate(r.lastSession || !mine ? `/runs/${r.id}` : `/runs/${r.id}/setup`));
list.appendChild(card);
}
await renderAdmin(seq);
}
const ownershipTag = (r, mine) =>
(mine ? ' · yours' : r.owner == null ? ' · ownerless' : ` · ${r.ownerName ?? 'someone'}'s`);
// all times UTC (house rule): unixtime -> "YYYY-MM-DD HH:MM:SS UTC"
function fmtUnix(t) {
const iso = new Date(Number(t) * 1000).toISOString();
return `${iso.slice(0, 10)} ${iso.slice(11, 19)} UTC`;
}
// --- admin (superuser, on home): invites and users -------------------------------
async function renderAdmin(seq) {
const box = $('admin');
if (!state.me?.superuser) { box.hidden = true; return; }
box.hidden = false;
const [inv, us] = await Promise.all([api('/invites'), api('/users')]);
if (seq !== state.seq) return;
const invList = $('invite-list');
invList.textContent = '';
for (const i of inv.invites) {
const row = el('div', 'admin-row');
row.appendChild(el('span', 'grow', `#${i.id} ${i.kind} — ${i.state}`));
if (i.state === 'unclaimed') {
const b = el('button', null, 'revoke');
b.addEventListener('click', async () => {
try { await api(`/invites/${i.id}`, { method: 'DELETE' }); render(); } catch (e) { banner(e.message); }
});
row.appendChild(b);
}
invList.appendChild(row);
}
const userList = $('user-list');
userList.textContent = '';
for (const u of us.users) {
const row = el('div', 'admin-row');
row.appendChild(el('span', 'grow', `${u.name} · ${u.id}${u.superuser ? ' · op' : ''}`));
if (u.id !== state.me.id) {
const b = el('button', 'danger', 'revoke');
b.addEventListener('click', () => revokeUser(u, b));
row.appendChild(b);
}
userList.appendChild(row);
}
}
// revocation destroys the identity — two-click armed, like every destructive act
let revokeArmed = null;
function revokeUser(u, btn) {
if (revokeArmed === null) {
btn.textContent = 'sure? click again';
revokeArmed = setTimeout(() => { revokeArmed = null; btn.textContent = 'revoke'; }, 5000);
return;
}
clearTimeout(revokeArmed);
revokeArmed = null;
btn.textContent = 'revoke';
api(`/users/${u.id}/revoke`, { method: 'POST', body: {} })
.then(() => render())
.catch((e) => banner(e.message));
}
function runStateText(r) {
@@ -417,7 +518,8 @@ async function viewNew(seq) {
for (const p of pkgs) {
const card = el('button', 'card package-card');
card.appendChild(el('span', 'card-name', p.display));
card.appendChild(el('span', 'card-meta', `${p.name} · records ${p.records ? 'on' : 'off'} · turn-0 ${p.turn0 ? 'yes' : 'no'} · seed ${p.seed ? 'yes' : 'no'}`));
const origin = p.origin === 'user' ? `user${p.ownerName ? `, by ${p.ownerName}` : ''}` : 'system';
card.appendChild(el('span', 'card-meta', `${p.name} · ${origin} · records ${p.records ? 'on' : 'off'} · turn-0 ${p.turn0 ? 'yes' : 'no'} · seed ${p.seed ? 'yes' : 'no'}`));
if (!p.complete) card.appendChild(el('span', 'card-state attention', 'incomplete — missing backdrop or character'));
card.addEventListener('click', () => pickPackage(p));
list.appendChild(card);
@@ -513,6 +615,7 @@ async function viewSetup(id, seq) {
}
if (seq !== state.seq) return;
if (!detail.draft) return navigate(`/runs/${id}`); // started runs live in play
if (detail.run.owner !== state.me.id) return navigate(`/runs/${id}`); // not yours: read-only — fork to edit
state.files = files.files;
state.repoPrompts = { 'system.md': prompts.system, 'invariants.md': prompts.invariants };
@@ -556,6 +659,8 @@ async function viewSetup(id, seq) {
nav.appendChild(item);
}
selectFile('system.md'); // how the model is prompted, first thing
$('savepkg-state').textContent = '';
$('savepkg-name').value = '';
}
function selectFile(f) {
@@ -638,6 +743,26 @@ async function saveDirty() {
markNav();
}
// save the run's craft as a new user package — published to every user
// of the deployment, gm.md included. Saves what the run has saved:
// drafts flush first. The display name is the save's one decision.
async function saveAsPackage() {
const name = $('savepkg-name').value.trim();
if (!name) return banner('the package needs a display name');
$('savepkg-btn').disabled = true;
$('savepkg-state').textContent = 'saving…';
try {
await saveDirty();
const r = await api('/packages', { method: 'POST', body: { from: state.runId, name } });
$('savepkg-state').textContent = `saved — ${r.package.id}`;
$('savepkg-name').value = '';
} catch (e) {
banner(e.message);
$('savepkg-state').textContent = 'not saved';
}
$('savepkg-btn').disabled = false;
}
// delete this draft: two-click armed (destructive), then home.
// A played run refuses server-side — stories are deleted by hand.
let deleteArmed = null;
@@ -728,21 +853,37 @@ async function refreshPlay(id, seq) {
return banner(`could not reach the server: ${e.message}`); // stay put — transient
}
if (seq !== state.seq) return;
if (detail.draft) return navigate(`/runs/${id}/setup`);
const mine = state.me && detail.run.owner === state.me.id;
if (detail.draft) {
if (mine) return navigate(`/runs/${id}/setup`);
// someone else's unstarted run: nothing to read but its existence
show('play');
state.runId = id;
$('window-info').textContent = `${detail.display} — a draft, not yours`;
$('transcript').textContent = '';
$('transcript').appendChild(el('div', 'hint', 'this run is still a draft — fork it to make it yours and edit it'));
return;
}
$('window-info').textContent = detail.open
$('window-info').textContent = (detail.open
? `${detail.display} — window ${detail.window}${detail.fresh ? ' — fresh' : ''}${detail.pendingAsk ? ' — waiting for your answer' : ''}`
: `${detail.display} — no open window`;
: `${detail.display} — no open window`)
+ (mine ? '' : detail.run.owner == null ? ' — ownerless' : ' — spectating');
renderMeter(detail);
renderPaper(detail.paper);
$('conflict').hidden = true;
// spectator mode: read everything, mutate nothing — the fork is the
// way in. Ownerless runs are spectators for everyone alike.
$('paper-edit').hidden = !mine;
$('gm-notes').readOnly = !mine;
let beatNeeded = false;
if (detail.open) {
const session = await api(`/runs/${id}/session`);
if (seq !== state.seq) return;
renderTranscript(session.entries);
beatNeeded = detail.fresh && !session.entries.some((e) => e.t === 'msg' && e.m.role === 'user');
beatNeeded = mine && detail.fresh && !session.entries.some((e) => e.t === 'msg' && e.m.role === 'user');
} else {
$('transcript').textContent = '';
}
@@ -751,13 +892,17 @@ async function refreshPlay(id, seq) {
if (beatNeeded) await offerBeat(id, seq);
// controls
$('window-open').hidden = detail.open;
$('hk-run').hidden = !detail.open;
$('hk-replay').hidden = !detail.lastSession; // any session log is replayable
setInput(detail.open && !detail.pendingAsk);
$('window-open').hidden = detail.open || !mine;
$('hk-run').hidden = !detail.open || !mine;
$('hk-replay').hidden = !detail.lastSession || !mine; // any session log is replayable, by the owner
setInput(detail.open && !detail.pendingAsk && mine);
$('gm-input').placeholder = mine
? 'GM line — Enter sends, Shift+Enter newlines'
: 'spectating — fork this run to continue it as yours';
// pending ask: the modal re-presents after a refresh
if (detail.pendingAsk) {
// pending ask: the modal re-presents after a refresh — the owner's
// to answer; a spectator follows the thread in the transcript
if (detail.pendingAsk && mine) {
$('ask-question').textContent = detail.pendingAsk;
$('ask-modal').showModal();
$('ask-answer').focus();
@@ -896,6 +1041,22 @@ function setBusy(on, text = 'her turn…') {
if (on) $('busy').textContent = text;
}
// fork: a copy of this run under you — any run, anyone's, including
// yours. Lands you in the fork.
async function forkRun() {
if (!state.runId) return;
setBusy(true, 'forking…');
try {
const r = await api(`/runs/${state.runId}/fork`, { method: 'POST', body: {} });
setBusy(false);
logEvent('nav', `forked ${state.runId} -> ${r.run}`);
navigate(`/runs/${r.run}`);
} catch (e) {
setBusy(false);
banner(e.message);
}
}
async function openWindow() {
const override = $('hk-override').checked;
hideBanner();
@@ -982,6 +1143,27 @@ async function loadLog() {
// --- wiring --------------------------------------------------------------------------
$('home-link').addEventListener('click', (e) => { e.preventDefault(); navigate('/'); });
$('claim-form').addEventListener('submit', async (e) => {
e.preventDefault();
try {
const r = await api('/claim', { method: 'POST', body: { code: $('claim-code').value.trim(), name: $('claim-name').value.trim() } });
try { localStorage.setItem(TOKEN_KEY, r.token); } catch {}
state.me = r.user;
logEvent('nav', `claimed: ${r.user.name}${r.user.superuser ? ' (op)' : ''}`);
navigate('/');
} catch (err) {
banner(err.message);
}
});
$('invite-mint').addEventListener('click', async () => {
try {
const r = await api('/invites', { method: 'POST', body: {} });
$('invite-code').textContent = r.code; // shown once — it is never listed again
render();
} catch (e) {
banner(e.message);
}
});
$('new-run-btn').addEventListener('click', () => navigate('/new'));
$('create-back').addEventListener('click', () => { $('create-form').hidden = true; $('package-pick').hidden = false; });
$('create-form').addEventListener('submit', async (e) => {
@@ -1017,6 +1199,8 @@ $('setup-edit').addEventListener('scroll', () => {
$('edit-hl').scrollLeft = $('setup-edit').scrollLeft;
});
$('setup-start').addEventListener('click', startRun);
$('savepkg-btn').addEventListener('click', saveAsPackage);
$('fork-btn').addEventListener('click', forkRun);
$('gm-send').addEventListener('click', sendTurn);
$('gm-input').addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendTurn(); }
@@ -1036,4 +1220,19 @@ $('gm-notes').addEventListener('blur', saveNotes);
window.addEventListener('pagehide', saveNotes); // tab close / reload mid-debounce
$('diag-btn').addEventListener('click', toggleDiag);
render();
// --- boot --------------------------------------------------------------------------
// restore the session from the stored token; a rejected or absent
// token leaves me signed out, and every path leads to the claim view
(async () => {
if (authToken()) {
try {
const s = await api('/session');
state.me = s.user;
if (!state.me) { try { localStorage.removeItem(TOKEN_KEY); } catch {} }
} catch {
state.me = null;
}
}
render();
})();
+32
View File
@@ -9,6 +9,7 @@
<body>
<header>
<a id="home-link" href="/">rp-test</a>
<span id="who"></span>
<div id="window-info"></div>
<div id="context-meter" title="context usage of the last call">
<div id="context-bar"><div id="context-fill"></div></div>
@@ -18,10 +19,31 @@
</header>
<main>
<section id="view-claim" hidden>
<h1>claim an invite</h1>
<p class="hint" id="claim-hint"></p>
<form id="claim-form">
<label class="field">invite code <input id="claim-code" autocomplete="off"></label>
<label class="field">display name <input id="claim-name" autocomplete="off"></label>
<div class="form-actions">
<button type="submit" class="primary">claim</button>
</div>
</form>
</section>
<section id="view-home" hidden>
<h1>runs</h1>
<div id="run-list"></div>
<button id="new-run-btn" class="primary">new run</button>
<section id="admin" hidden>
<h2>admin</h2>
<div class="form-actions">
<button id="invite-mint">mint invite</button>
<span id="invite-code"></span>
</div>
<div id="invite-list"></div>
<div id="user-list"></div>
</section>
</section>
<section id="view-new" hidden>
@@ -56,6 +78,11 @@
<span id="setup-vars-state"></span>
</div>
</div>
<div id="setup-savepkg">
<input id="savepkg-name" placeholder="new package display name" autocomplete="off">
<button id="savepkg-btn">save as package</button>
<span id="savepkg-state"></span>
</div>
<div class="setup-body">
<nav id="setup-files"></nav>
<div id="setup-editor">
@@ -109,6 +136,11 @@
<details id="hk-log" hidden><summary>window log</summary><pre id="hk-log-content"></pre></details>
<details id="hk-replay-log" hidden><summary>replay manifest</summary><pre id="hk-replay-content"></pre></details>
</section>
<section id="fork-pane">
<h2>fork</h2>
<p class="hint">a copy of this run — yours to continue</p>
<button id="fork-btn">fork this run</button>
</section>
</aside>
<footer>
+30
View File
@@ -128,6 +128,36 @@ h1 { font-size: 15px; letter-spacing: 0.1em; text-transform: uppercase; color: v
#new-run-btn { margin-top: 8px; }
/* --- identity + admin --- */
#who { color: var(--dim); font-size: 13px; }
#logout-btn { font-size: 11px; padding: 1px 8px; color: var(--dim); }
#claim-form { max-width: 480px; }
#admin { max-width: 560px; margin-top: 28px; border-top: 1px solid var(--line); padding-top: 14px; }
#admin h2 {
margin: 0 0 10px; font-size: 11px; letter-spacing: 0.14em;
text-transform: uppercase; color: var(--dim); font-weight: normal;
}
#invite-code { font: 12px ui-monospace, Consolas, monospace; color: var(--accent); word-break: break-all; }
.admin-row { display: flex; align-items: center; gap: 8px; font-size: 13px; color: var(--dim); padding: 3px 0; }
.admin-row .grow { flex: 1; }
.admin-row button { font-size: 11px; padding: 1px 8px; color: var(--dim); }
.admin-row button.danger { color: var(--danger); }
/* --- setup: save-as-package --- */
#setup-savepkg { display: flex; gap: 8px; max-width: 560px; margin-bottom: 14px; align-items: center; }
#setup-savepkg input { flex: 1; }
#savepkg-state { color: var(--dim); font-size: 12px; }
/* --- aside: fork --- */
#fork-pane { margin-top: 22px; }
#fork-pane .hint { margin: 0 0 8px; }
#fork-pane button { width: 100%; }
/* the naming form (new run) and the vars box (setup) */
#create-form { max-width: 560px; }
#create-form h2 { font-size: 15px; margin: 0 0 14px; color: var(--text); font-weight: 600; }