387 lines
12 KiB
JavaScript
387 lines
12 KiB
JavaScript
// web/view-play.mjs — the play surface: the transcript, her two
|
|
// blocks (the status pane and the agenda pane — one widget, two
|
|
// instances), the GM notepad, housekeeping (close session, the
|
|
// dry-run replay), fork, and the input line.
|
|
|
|
import { $, el } from './dom.mjs';
|
|
import { api } from './client.mjs';
|
|
import { state } from './state.mjs';
|
|
import { banner, hideBanner, renderMeter, setBusy, setSessionInfo } from './chrome.mjs';
|
|
import { navigate, render, runGone } from './router.mjs';
|
|
import { logEvent } from './log.mjs';
|
|
import { armedButton, modelList, modelsBox, paneEditor } from './widgets.mjs';
|
|
import { renderTranscript } from './transcript.mjs';
|
|
|
|
// her two blocks, split along the seam: how she is (the status) vs
|
|
// what she means to do (the agenda). Both render compact, mirroring
|
|
// the wire formats the model cites.
|
|
const statusPane = paneEditor({
|
|
section: 'status-pane',
|
|
body: 'status',
|
|
empty: 'a blank sheet',
|
|
placeholder: 'one description per line — empty clears the status',
|
|
rows: 5,
|
|
format: (items) => items.join(', '), // compact, mirroring the <status> wire format
|
|
toText: (items) => items.join('\n'),
|
|
fromText: (text) => text
|
|
.split('\n').flatMap((l) => l.replace(/^\s*[-*]\s+/, '').split(','))
|
|
.map((x) => x.trim()).filter(Boolean),
|
|
save: (items) => api(`/runs/${state.runId}/status`, { method: 'POST', body: { items } }),
|
|
});
|
|
const agendaPane = paneEditor({
|
|
section: 'agenda-pane',
|
|
body: 'agenda',
|
|
empty: 'a clear head',
|
|
placeholder: 'one item per line, top first — empty clears the agenda',
|
|
rows: 4,
|
|
// the queue numbered from the top, exactly as the model cites it
|
|
format: (items) => items.map((d, i) => `${i}. ${d}`).join('; '),
|
|
toText: (items) => items.join('\n'),
|
|
fromText: (text) => text
|
|
.split('\n').flatMap((l) => l.replace(/^\s*[-*]\s+\d*[.:)]?\s*/, '').split(','))
|
|
.map((x) => x.trim()).filter(Boolean),
|
|
save: (items) => api(`/runs/${state.runId}/agenda`, { method: 'POST', body: { items } }),
|
|
});
|
|
|
|
const models = modelsBox('models-pane', { title: 'models' });
|
|
|
|
export function leave() {
|
|
saveNotes();
|
|
stopPoll();
|
|
$('ask-modal').close();
|
|
}
|
|
|
|
export async function enter(id, seq) {
|
|
statusPane.reset();
|
|
agendaPane.reset();
|
|
$('conflict').hidden = true;
|
|
await saveNotes(); // flush the pad for the previous run before switching
|
|
state.runId = id;
|
|
notesDirty = false;
|
|
$('gm-notes').value = '';
|
|
$('notes-state').textContent = '';
|
|
await refreshPlay(id, seq);
|
|
}
|
|
|
|
async function refreshPlay(id, seq) {
|
|
let detail;
|
|
try {
|
|
detail = await api(`/runs/${id}`);
|
|
} catch (e) {
|
|
if (e.status === 404) return runGone(id, location.pathname);
|
|
return banner(`could not reach the server: ${e.message}`); // stay put — transient
|
|
}
|
|
if (seq !== state.seq) return;
|
|
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
|
|
setSessionInfo(`${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;
|
|
}
|
|
|
|
setSessionInfo((detail.open
|
|
? `${detail.display} — session ${detail.session}${detail.fresh ? ' — fresh' : ''}${detail.pendingAsk ? ' — waiting for your answer' : ''}`
|
|
: `${detail.display} — no open session`)
|
|
+ (mine ? '' : detail.run.owner == null ? ' — ownerless' : ' — spectating'));
|
|
renderMeter(detail);
|
|
statusPane.set(detail.status);
|
|
agendaPane.set(detail.agenda);
|
|
$('conflict').hidden = true;
|
|
|
|
// spectator mode: read everything, mutate nothing — the fork is the
|
|
// way in. Ownerless runs are spectators for everyone alike.
|
|
statusPane.setEditable(mine);
|
|
agendaPane.setEditable(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, { onConflict: showConflict });
|
|
beatNeeded = mine && detail.fresh && !session.entries.some((e) => e.t === 'msg' && e.m.role === 'user');
|
|
} else {
|
|
$('transcript').textContent = '';
|
|
}
|
|
|
|
// the opening beat, if start was interrupted or the session was opened directly
|
|
if (beatNeeded) await offerBeat(id, seq);
|
|
|
|
// controls
|
|
$('session-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';
|
|
|
|
// models: the owner's per-run overrides
|
|
$('models-pane').hidden = !mine;
|
|
if (mine) {
|
|
const mlist = await modelList();
|
|
if (seq !== state.seq) return;
|
|
models.fill(detail.run.models, detail.run.modelDefaults, mlist);
|
|
}
|
|
|
|
// 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();
|
|
} else {
|
|
$('ask-modal').close();
|
|
}
|
|
|
|
// housekeeping state
|
|
const hk = await api(`/runs/${id}/housekeeping`);
|
|
if (seq !== state.seq) return;
|
|
renderHk(hk);
|
|
|
|
// the GM's notepad — skip the reload if a save failed (dirty wins)
|
|
await loadNotes(id, seq);
|
|
}
|
|
|
|
function showConflict(text) {
|
|
const c = $('conflict');
|
|
c.textContent = `conflict: ${text}`;
|
|
c.hidden = false;
|
|
}
|
|
|
|
// --- the GM's notepad: always on screen, auto-saved -------------------
|
|
//
|
|
// A debounced save (1s after the last keystroke, immediate on blur),
|
|
// flushed when leaving the play view or switching runs. gm.md never
|
|
// reaches any model — this is the GM's own notes.
|
|
|
|
let notesTimer = null;
|
|
let notesDirty = false;
|
|
|
|
async function loadNotes(id, seq) {
|
|
const notes = await api(`/runs/${id}/notes`).catch(() => null);
|
|
if (!notes || seq !== state.seq || notesDirty) return;
|
|
$('gm-notes').value = notes.content;
|
|
}
|
|
|
|
function notesInput() {
|
|
notesDirty = true;
|
|
$('notes-state').textContent = 'unsaved';
|
|
clearTimeout(notesTimer);
|
|
notesTimer = setTimeout(saveNotes, 1000);
|
|
}
|
|
|
|
async function saveNotes() {
|
|
clearTimeout(notesTimer);
|
|
if (!notesDirty || !state.runId) return;
|
|
const content = $('gm-notes').value;
|
|
try {
|
|
// keepalive: the flush must survive leaving the page entirely
|
|
await api(`/runs/${state.runId}/notes`, { method: 'PUT', body: { content }, keepalive: true });
|
|
notesDirty = false;
|
|
$('notes-state').textContent = 'saved';
|
|
} catch (e) {
|
|
$('notes-state').textContent = 'not saved';
|
|
banner(e.message);
|
|
}
|
|
}
|
|
|
|
async function offerBeat(id, seq) {
|
|
let hasTurn0 = true;
|
|
try {
|
|
const files = await api(`/runs/${id}/files`);
|
|
if (seq !== state.seq) return;
|
|
hasTurn0 = files.files['turn-0.md']?.exists === true;
|
|
} catch { /* try the endpoint anyway */ }
|
|
if (!hasTurn0) return;
|
|
const bar = el('div', 'beat');
|
|
bar.appendChild(el('span', null, 'the session is open; the opening beat has not been sent'));
|
|
const b = el('button', 'primary', 'send the opening beat');
|
|
b.addEventListener('click', async () => {
|
|
setBusy(true);
|
|
try {
|
|
await api(`/runs/${id}/turn0`, { method: 'POST', body: {} });
|
|
} catch (e) {
|
|
banner(e.message);
|
|
}
|
|
setBusy(false);
|
|
render();
|
|
});
|
|
bar.appendChild(b);
|
|
$('transcript').prepend(bar);
|
|
}
|
|
|
|
function setHk(stateText, cls) {
|
|
const h = $('hk-state');
|
|
h.textContent = stateText;
|
|
h.className = cls ?? '';
|
|
}
|
|
|
|
function renderHk(hk) {
|
|
if (hk.state === 'running') {
|
|
setHk('housekeeping…', '');
|
|
startPoll();
|
|
return;
|
|
}
|
|
stopPoll();
|
|
if (hk.state === 'applied') {
|
|
setHk(`applied — session ${hk.session ?? ''}\nnext session open`, 'applied');
|
|
loadLog(); // idempotent — also covers a refresh while applied
|
|
} else if (hk.state === 'rejected') {
|
|
setHk(`rejected — held, nothing applied:\n${hk.reason ?? ''}`, 'rejected');
|
|
} else {
|
|
setHk('idle', '');
|
|
}
|
|
}
|
|
|
|
function setInput(ok) {
|
|
$('gm-input').disabled = !ok;
|
|
$('gm-send').disabled = !ok;
|
|
}
|
|
|
|
// --- actions -----------------------------------------------------------
|
|
|
|
async function sendTurn() {
|
|
const line = $('gm-input').value.trim();
|
|
if (!line || !state.runId) return;
|
|
$('gm-input').value = '';
|
|
setInput(false);
|
|
setBusy(true);
|
|
try {
|
|
await api(`/runs/${state.runId}/turn`, { method: 'POST', body: { line } });
|
|
} catch (e) {
|
|
banner(e.message);
|
|
$('gm-input').value = line; // a failed send must not eat the line
|
|
}
|
|
setBusy(false);
|
|
render();
|
|
}
|
|
|
|
async function sendAnswer() {
|
|
const answer = $('ask-answer').value.trim();
|
|
if (!answer || !state.runId) return;
|
|
$('ask-answer').value = '';
|
|
setBusy(true);
|
|
try {
|
|
await api(`/runs/${state.runId}/ask`, { method: 'POST', body: { answer } });
|
|
} catch (e) {
|
|
banner(e.message);
|
|
$('ask-answer').value = answer;
|
|
}
|
|
setBusy(false);
|
|
render();
|
|
}
|
|
|
|
// 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 openSession() {
|
|
const override = $('hk-override').checked;
|
|
hideBanner();
|
|
try {
|
|
await api(`/runs/${state.runId}/sessions`, { method: 'POST', body: { override } });
|
|
$('hk-override').checked = false;
|
|
} catch (e) {
|
|
if (e.status === 409 && e.detail?.hint) {
|
|
banner(`${e.message}\n${e.detail.hint}`, 'info');
|
|
} else {
|
|
banner(e.message);
|
|
}
|
|
}
|
|
render();
|
|
}
|
|
|
|
// dry-run: the housekeeper reads the session log, the manifest lands
|
|
// in the pane — nothing applied, the session stays open
|
|
async function replayHousekeeping() {
|
|
setBusy(true, 'the housekeeper reads…');
|
|
try {
|
|
const r = await api(`/runs/${state.runId}/housekeeping/replay`, { method: 'POST', body: {} });
|
|
$('hk-replay-content').textContent = r.parsed
|
|
? JSON.stringify(r.manifest, null, 2)
|
|
: `${r.reason}\n\nraw output: ${r.file}`;
|
|
$('hk-replay-log').hidden = false;
|
|
$('hk-replay-log').open = true;
|
|
} catch (e) {
|
|
banner(e.message);
|
|
}
|
|
setBusy(false);
|
|
}
|
|
|
|
// --- housekeeping poll + log -------------------------------------------
|
|
|
|
let poll = null;
|
|
|
|
function startPoll() {
|
|
stopPoll();
|
|
poll = setInterval(async () => {
|
|
if (!state.runId || state.view !== 'play') return stopPoll();
|
|
const hk = await api(`/runs/${state.runId}/housekeeping`).catch(() => null);
|
|
if (hk && hk.state !== 'running') render();
|
|
}, 3000);
|
|
}
|
|
function stopPoll() {
|
|
if (poll) clearInterval(poll);
|
|
poll = null;
|
|
}
|
|
|
|
async function loadLog() {
|
|
try {
|
|
const log = await api(`/runs/${state.runId}/housekeeping/log`);
|
|
$('hk-log-content').textContent = log.content;
|
|
$('hk-log').hidden = false;
|
|
$('hk-log').open = true;
|
|
} catch {
|
|
$('hk-log').hidden = true;
|
|
}
|
|
}
|
|
|
|
// --- wiring ---
|
|
|
|
armedButton($('hk-run'), {
|
|
label: 'close session & housekeep',
|
|
confirm: 'sure? click again to close & housekeep',
|
|
fire: async () => {
|
|
hideBanner();
|
|
try {
|
|
await api(`/runs/${state.runId}/housekeeping`, { method: 'POST', body: {} });
|
|
setHk('housekeeping…', '');
|
|
startPoll();
|
|
} catch (e) {
|
|
banner(e.message);
|
|
}
|
|
render();
|
|
},
|
|
});
|
|
|
|
$('gm-send').addEventListener('click', sendTurn);
|
|
$('gm-input').addEventListener('keydown', (e) => {
|
|
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendTurn(); }
|
|
});
|
|
$('ask-send').addEventListener('click', sendAnswer);
|
|
$('ask-answer').addEventListener('keydown', (e) => {
|
|
if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendAnswer(); }
|
|
});
|
|
$('session-open').addEventListener('click', openSession);
|
|
$('hk-replay').addEventListener('click', replayHousekeeping);
|
|
$('fork-btn').addEventListener('click', forkRun);
|
|
$('gm-notes').addEventListener('input', notesInput);
|
|
$('gm-notes').addEventListener('blur', saveNotes);
|
|
window.addEventListener('pagehide', saveNotes); // tab close / reload mid-debounce
|