spa modules and terminology: app.mjs split into flat es modules (router lifecycle, shared widgets, views own their state), mock smoke in test/; DICTIONARY.md rules the terms, four renames swept clean through the machinery - paper->status (run summary command is report now), window->session, wrap->housekeeping, context window->contwin; no dual-accepts by ruling, old data migrates once in the clerk (restore self-heals old dumps)
This commit is contained in:
@@ -0,0 +1,319 @@
|
||||
// web/view-setup.mjs — the draft editor: the full assembly in bundle
|
||||
// order (the repo-fed prompts read-only, the run's craft editable,
|
||||
// config read-only), the prompt-declared $TOKEN inputs, per-run
|
||||
// models, and the two exits — save as package (publishes it) or
|
||||
// start (opens the session, sends turn-0).
|
||||
|
||||
import { $, el } from './dom.mjs';
|
||||
import { api } from './client.mjs';
|
||||
import { state } from './state.mjs';
|
||||
import { banner } from './chrome.mjs';
|
||||
import { navigate, runGone } from './router.mjs';
|
||||
import { armedButton, modelList, modelsBox } from './widgets.mjs';
|
||||
|
||||
// one list, in bundle-assembly order: the repo-fed system message
|
||||
// parts (read-only — the user should understand how the model is
|
||||
// prompted), the craft tail and GM messages (editable), then the
|
||||
// initial state, then run config (read-only). Everything the run
|
||||
// sends, nothing it doesn't.
|
||||
const EDIT_LIST = [
|
||||
{ name: 'system.md', mode: 'ro', source: 'repo' },
|
||||
{ name: 'invariants.md', mode: 'ro', source: 'repo' },
|
||||
{ name: 'reminder.md', mode: 'ro', source: 'repo' }, // rides every turn as its own system chunk
|
||||
{ name: 'handbook.md', mode: 'rw', source: 'run' },
|
||||
{ name: 'backdrop.md', mode: 'rw', source: 'run' },
|
||||
{ name: 'character.md', mode: 'rw', source: 'run' },
|
||||
{ name: 'seed.json', mode: 'rw', source: 'run' }, // the rings it seeds — turn-0 wakes into them
|
||||
{ name: 'turn-0.md', mode: 'rw', source: 'run' },
|
||||
{ name: 'settings.json', mode: 'ro', source: 'run' },
|
||||
{ name: 'run.json', mode: 'ro', source: 'run' },
|
||||
];
|
||||
|
||||
// the editor's working set — module-local, reset on every enter
|
||||
let files = null; // { name: { content, exists } }
|
||||
let drafts = {}; // unsaved edits by file name
|
||||
let currentFile = null;
|
||||
let fileSpecs = {};
|
||||
let repoPrompts = {};
|
||||
|
||||
const models = modelsBox('setup-models', { title: 'models — per-run, over the deployment defaults' });
|
||||
|
||||
export async function enter(id, seq) {
|
||||
state.runId = id;
|
||||
drafts = {};
|
||||
currentFile = null;
|
||||
let detail, filesResp, prompts;
|
||||
try {
|
||||
[detail, filesResp, prompts] = await Promise.all([
|
||||
api(`/runs/${id}`),
|
||||
api(`/runs/${id}/files`),
|
||||
api('/prompts'),
|
||||
]);
|
||||
} 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;
|
||||
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
|
||||
|
||||
files = filesResp.files;
|
||||
repoPrompts = {
|
||||
'system.md': prompts.system ?? '',
|
||||
'invariants.md': prompts.invariants ?? '',
|
||||
'reminder.md': prompts.reminder ?? '',
|
||||
};
|
||||
$('setup-title').textContent = detail.display;
|
||||
$('setup-state').textContent = `${detail.run.package} · ${id} — draft; edits land when the session opens`;
|
||||
$('setup-start').disabled = false;
|
||||
$('setup-start').textContent = 'start';
|
||||
|
||||
// prompt vars: the $TOKENS the prompts declare, filled per run
|
||||
const vars = scanVars(prompts, files);
|
||||
let currentVars = {};
|
||||
try { currentVars = JSON.parse(files['settings.json']?.content ?? '{}').vars ?? {}; } catch { /* unreadable settings — empty vars */ }
|
||||
const varsList = $('setup-vars-list');
|
||||
varsList.textContent = '';
|
||||
$('setup-vars').hidden = !vars.length;
|
||||
$('setup-vars-state').textContent = '';
|
||||
for (const tok of vars) {
|
||||
const row = el('label', 'field', `$${tok}`);
|
||||
const inp = el('input');
|
||||
inp.dataset.token = tok;
|
||||
inp.value = currentVars[tok] ?? '';
|
||||
row.appendChild(inp);
|
||||
varsList.appendChild(row);
|
||||
}
|
||||
|
||||
// models: per-run overrides, selected from the upstream listing
|
||||
const mlist = await modelList();
|
||||
if (seq !== state.seq) return;
|
||||
models.fill(detail.run.models, detail.run.modelDefaults, mlist);
|
||||
|
||||
const nav = $('setup-files');
|
||||
nav.textContent = '';
|
||||
fileSpecs = {};
|
||||
for (const e of EDIT_LIST) {
|
||||
const runFile = files[e.name];
|
||||
const spec = {
|
||||
...e,
|
||||
exists: e.source === 'repo' ? true : !!runFile?.exists,
|
||||
content: e.source === 'repo' ? repoPrompts[e.name] : (runFile?.content ?? ''),
|
||||
};
|
||||
fileSpecs[e.name] = spec;
|
||||
const item = el('button', `file-item${e.mode === 'ro' ? ' ro' : ''}${spec.exists ? '' : ' absent'}`);
|
||||
item.appendChild(el('span', 'file-name', e.name + (spec.exists ? '' : ' (new)')));
|
||||
item.appendChild(el('span', 'file-dirty', ''));
|
||||
item.addEventListener('click', () => selectFile(e.name));
|
||||
nav.appendChild(item);
|
||||
}
|
||||
selectFile('system.md'); // how the model is prompted, first thing
|
||||
$('savepkg-state').textContent = '';
|
||||
$('savepkg-name').value = '';
|
||||
}
|
||||
|
||||
// the prompts declare their own inputs: every $TOKEN in any prompt
|
||||
// file (repo-fed or run copy) becomes a fillable input in setup
|
||||
function scanVars(prompts, files) {
|
||||
const texts = [
|
||||
prompts.system, prompts.invariants, prompts.reminder,
|
||||
files['handbook.md']?.content,
|
||||
files['backdrop.md']?.content, files['character.md']?.content, files['turn-0.md']?.content,
|
||||
];
|
||||
const found = new Set();
|
||||
for (const t of texts) {
|
||||
if (!t) continue;
|
||||
for (const m of t.matchAll(/\$([A-Za-z][A-Za-z0-9_]*)/g)) found.add(m[1]);
|
||||
}
|
||||
return [...found].sort();
|
||||
}
|
||||
|
||||
function collectVars() {
|
||||
const vars = {};
|
||||
for (const inp of $('setup-vars-list').querySelectorAll('input')) vars[inp.dataset.token] = inp.value.trim();
|
||||
return vars;
|
||||
}
|
||||
|
||||
async function saveVars() {
|
||||
const vars = collectVars();
|
||||
if (!Object.keys(vars).length) return;
|
||||
await api(`/runs/${state.runId}/vars`, { method: 'POST', body: { vars } });
|
||||
$('setup-vars-state').textContent = 'saved';
|
||||
}
|
||||
|
||||
function selectFile(f) {
|
||||
const prev = currentFile;
|
||||
if (prev === f) return;
|
||||
if (prev && fileSpecs[prev]?.mode === 'rw') stashDraft(prev);
|
||||
currentFile = f;
|
||||
const spec = fileSpecs[f] ?? { mode: 'rw', source: 'run', exists: false };
|
||||
const content = spec.source === 'repo'
|
||||
? (repoPrompts[f] ?? '')
|
||||
: (drafts[f] ?? spec.content ?? '');
|
||||
$('setup-edit').value = content;
|
||||
$('setup-edit').disabled = spec.mode !== 'rw';
|
||||
$('setup-save').hidden = spec.mode !== 'rw';
|
||||
$('setup-edit-state').textContent = spec.mode === 'rw' ? '' : 'read-only';
|
||||
renderHighlight();
|
||||
markNav();
|
||||
}
|
||||
|
||||
// the highlight overlay: known sigils (gold) and every $VAR (green)
|
||||
// light up in place; unknown @-words are the author's own text and
|
||||
// stay plain — @ syntax is not owned here
|
||||
const SIGIL_RE = /@(PC|Package)\b/g;
|
||||
const VAR_RE = /\$([A-Za-z_][A-Za-z0-9_]*)/g;
|
||||
function renderHighlight() {
|
||||
const ta = $('setup-edit');
|
||||
const hl = $('edit-hl');
|
||||
const esc = ta.value.replace(/[&<>]/g, (c) => ({ '&': '&', '<': '<', '>': '>' }[c]));
|
||||
hl.innerHTML = esc
|
||||
.replace(VAR_RE, '<span class="tok-var">$&</span>')
|
||||
.replace(SIGIL_RE, '<span class="tok-sigil">$&</span>')
|
||||
+ '\n\u200b'; // keep the trailing empty line's height honest
|
||||
hl.scrollTop = ta.scrollTop;
|
||||
hl.scrollLeft = ta.scrollLeft;
|
||||
}
|
||||
|
||||
function stashDraft(f) {
|
||||
if (fileSpecs[f]?.mode !== 'rw') return; // read-only and repo-fed files never become drafts
|
||||
const v = $('setup-edit').value;
|
||||
if (v === (files[f]?.content ?? '')) { delete drafts[f]; markNav(); return; }
|
||||
drafts[f] = v;
|
||||
markNav();
|
||||
}
|
||||
|
||||
function markNav() {
|
||||
const items = $('setup-files').children;
|
||||
for (const item of items) {
|
||||
const name = item.querySelector('.file-name').textContent.replace(' (new)', '');
|
||||
item.classList.toggle('dirty', drafts[name] !== undefined);
|
||||
item.classList.toggle('current', name === currentFile);
|
||||
}
|
||||
}
|
||||
|
||||
async function saveFile() {
|
||||
const f = currentFile;
|
||||
if (!f) return;
|
||||
$('setup-save').disabled = true;
|
||||
try {
|
||||
await api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { content: $('setup-edit').value } });
|
||||
files[f].content = $('setup-edit').value;
|
||||
files[f].exists = true;
|
||||
delete drafts[f];
|
||||
$('setup-edit-state').textContent = 'saved';
|
||||
markNav();
|
||||
} catch (e) {
|
||||
banner(e.message);
|
||||
$('setup-edit-state').textContent = 'not saved';
|
||||
}
|
||||
$('setup-save').disabled = false;
|
||||
}
|
||||
|
||||
async function saveDirty() {
|
||||
stashDraft(currentFile);
|
||||
for (const [f, content] of Object.entries({ ...drafts })) {
|
||||
await api(`/runs/${state.runId}/files/${f}`, { method: 'PUT', body: { content } });
|
||||
files[f].content = content;
|
||||
files[f].exists = true;
|
||||
delete drafts[f];
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
async function startRun() {
|
||||
const id = state.runId;
|
||||
const btn = $('setup-start');
|
||||
// the prompts' own inputs must be filled — the guard at session-open
|
||||
// is the backstop, not the first line of defense
|
||||
for (const [tok, v] of Object.entries(collectVars())) {
|
||||
if (!v) {
|
||||
banner(`$${tok} is unfilled — a prompt declares it, the run needs it`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
btn.disabled = true;
|
||||
btn.textContent = 'starting…';
|
||||
try {
|
||||
await saveVars();
|
||||
await saveDirty();
|
||||
} catch (e) {
|
||||
banner(`did not start — ${e.message}`);
|
||||
btn.disabled = false;
|
||||
btn.textContent = 'start';
|
||||
return;
|
||||
}
|
||||
let opened = false;
|
||||
try {
|
||||
await api(`/runs/${id}/sessions`, { method: 'POST', body: {} });
|
||||
opened = true;
|
||||
} catch (e) {
|
||||
banner(e.message);
|
||||
}
|
||||
if (opened && files['turn-0.md']?.exists) {
|
||||
try {
|
||||
await api(`/runs/${id}/turn0`, { method: 'POST', body: {} });
|
||||
} catch (e) {
|
||||
banner(`${e.message} — the beat can be sent from the play view`);
|
||||
}
|
||||
}
|
||||
navigate(`/runs/${id}`);
|
||||
}
|
||||
|
||||
// --- wiring ---
|
||||
|
||||
// delete this draft: two-click armed (destructive), then home.
|
||||
// A played run refuses server-side — stories are deleted by hand.
|
||||
armedButton($('setup-delete'), {
|
||||
label: 'delete draft',
|
||||
confirm: 'sure? click again to delete',
|
||||
fire: async () => {
|
||||
try {
|
||||
await api(`/runs/${state.runId}`, { method: 'DELETE' });
|
||||
navigate('/');
|
||||
} catch (e) {
|
||||
banner(e.message);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
$('setup-vars-save').addEventListener('click', async () => {
|
||||
try {
|
||||
await saveVars();
|
||||
} catch (e) {
|
||||
banner(e.message);
|
||||
$('setup-vars-state').textContent = 'not saved';
|
||||
}
|
||||
});
|
||||
$('setup-save').addEventListener('click', saveFile);
|
||||
$('setup-edit').addEventListener('input', () => {
|
||||
if (currentFile) stashDraft(currentFile);
|
||||
$('setup-edit-state').textContent = 'unsaved';
|
||||
renderHighlight();
|
||||
});
|
||||
$('setup-edit').addEventListener('scroll', () => {
|
||||
$('edit-hl').scrollTop = $('setup-edit').scrollTop;
|
||||
$('edit-hl').scrollLeft = $('setup-edit').scrollLeft;
|
||||
});
|
||||
$('setup-start').addEventListener('click', startRun);
|
||||
$('savepkg-btn').addEventListener('click', saveAsPackage);
|
||||
Reference in New Issue
Block a user