${escapeHtml(title)}
v${escapeHtml(doc.version || 1)}${escapeHtml(doc.note)}
\n` : ""}${body.innerHTML}// Plan2Code Console - the client. // // Two objects, strictly separated by ownership: // S the server's truth (state.json). Never mutated here. // local what you have staged but not sent. Mirrored to localStorage on // every change, so a closed tab or a reload loses nothing. // // Nothing you do reaches the agent until you press Send. Everything before // that is local and reversible. For someone who has never used a tool like // this, that reversibility is the whole point. import { md, mdInto, el, copyButton, selectContents } from "./render.js"; import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, SOUND_EVENTS, cardWidth, soundKey, soundPrefs } from "./palette.js"; import { activityLabel, workingLine } from "./labels.js"; import { playWake } from "./boot.js"; import { answerLines, APPROVAL_TIP, ALL_DONE_LEAD, ALL_DONE_REST, approvalHint, briefPhrase, cardAvailability, cardPresentation, defaultSpec, CATALOG_GROUPS, choiceAnswer, DASHBOARD_COMMAND, DASHBOARD_NOTE, COMMIT_REPLY, DASHBOARD_REPLY, afterFinishButton, commitOffer, dashboardOffer, DONE_REPLY, finishPaused, fitWithin, handoffShape, handoffText, HOME_REPLY, homeButtonState, IMAGE_LONG_EDGE, IMAGE_QUALITY, lastOpenCard, launchReply, launchTarget, deleteAction, deleteReply, pickupAction, pickupReply, deleteHandoffAction, deleteHandoffReply, handoffCopyText, handoffAge, chipDetail, deleteSummary, isDeletableSpecDir, MAX_ATTACHMENTS, nextOpenAfter, MAX_DOC_BYTES, DOC_TYPES, docExt, pickerAccept, formatBytes, attachmentKind, sortAttachments, noteAction, noteReplyLines, progressTotal, staleLaunchFeedback, quietLimitMs, recordedAnswer, resumeCommand, REVIEW_REPLY, reviewOffer, SKILL_CATALOG, SPEC_STATE_LABELS, STALE_MS, startPose, STOP_REPLY, STOP_HANDOFF_REPLY, stopAction, sentAnswer, agentRepliedAfterSend, indentReply, showKey, submittedAwaiting, noteAwaiting, suggestionFrom, threadText, threadWho, THUMB_EDGE, turnGate, verdictText, workflowLabel, workflowTitle, } from "./answers.js"; // `sendState` is renamed on the way in: the card footer already has its own. import { chatOffline, chatView, newestReplyId, nextAbout, contextOptions, sendState as chatSendState, shouldChime, unreadDot, CHAT_MAX_CHARS, CHAT_MAX_ATTACHMENTS, } from "./chat.js"; import { HELP_TABS, helpTabFor, helpKeyTarget } from "./help.js"; import { ROLES, ROLE_NOT_SET, ROLE_NOT_SET_LABEL, normalizeRole, needsRoleNudge, TEMPLATE_WORKFLOWS, templatesFor, templateSwap, startersFor, } from "./starters.js"; import { FOOTER_TIERS, footerLabel, nameProblem } from "./workspace.js"; import { RED_BANNER } from "./meter.js"; import { applyMention, matchNames, mentionAt } from "./mentions.js"; import { faviconState, setFavicon } from "./favicon.js"; import { CHECKIN_LINE, PATHFINDER_RESEARCH_LINE, defaultInstruction, helperRows, showSwitch, showTab, switchLabel, } from "./subagents.js"; import { BRANCH_TYPES, GIT_TABS, boardAwaiting, busyMode, cleanupGroups, commitTicks, controlAllowed, createSources, gitReply, nextStep, pickTab, tabBadges, } from "./git-board.js"; import { activeTab, drawGitBoard } from "./git-board-view.js"; const $ = (id) => document.getElementById(id); // The first state, the saved looks and the draft, written into the page by // the server so the first real screen needs no round trip. A data block, never // run as script. Absent (an older server, a page opened some other way), the // page falls back to asking for each as it always did. const BOOT = (() => { try { return JSON.parse($("boot").textContent); } catch { return null; } })(); /* --------------------------------------------------------------- looks */ // How the page looks and sounds, which is the one preference that belongs to // the person rather than to the session. Kept per browser, applied before // anything else is drawn, and deliberately touching nothing but presentation: // a session opened in a different theme is the same session. // // The highlight colors live in palette.js, where the tests can reach them. const ACCENT_VARS = ["--accent", "--accent-soft", "--accent-ink", "--accent-line"]; const LOOKS_KEY = "p2c-console:looks"; // The per-event sound switches (SOUND_EVENTS) live in palette.js too. const DEFAULT_LOOKS = { theme: "system", accent: DEFAULT_ACCENT, sound: true, ...soundPrefs(null), width: DEFAULT_CARD_WIDTH, hideUnavailable: true, }; let looks = { ...DEFAULT_LOOKS }; let syncedLooks = null; let looksReady = false; function adoptLooks(saved) { looks = { ...DEFAULT_LOOKS, ...saved }; if (!ACCENTS[looks.accent]) looks.accent = DEFAULT_LOOKS.accent; if (!["system", "light", "dark"].includes(looks.theme)) looks.theme = DEFAULT_LOOKS.theme; if (typeof looks.sound !== "boolean") looks.sound = DEFAULT_LOOKS.sound; Object.assign(looks, soundPrefs(looks)); if (typeof looks.hideUnavailable !== "boolean") looks.hideUnavailable = DEFAULT_LOOKS.hideUnavailable; looks.width = cardWidth(looks.width); if (saved && typeof saved === "object" && Object.hasOwn(saved, "role")) looks.role = normalizeRole(saved.role); else delete looks.role; } // The localStorage copy is only a cache now. It exists so the first paint can // apply a theme synchronously rather than flashing the defaults while the // fetch below is in flight; the server's looks.json is the truth, because it // is the copy that follows the app when a new session lands on a new port. function loadLooks() { try { const raw = localStorage.getItem(LOOKS_KEY); if (raw) adoptLooks(JSON.parse(raw)); } catch {} } // Called once the page is up. Server wins: its copy is shared by every port, // while this origin's localStorage may be a leftover from a previous session // on this port or empty on a fresh one. A 404 means the server has never been // told -- including every install that predates the file -- so a browser that // DOES hold a setting seeds it, which is also the upgrade path. async function syncLooks() { let saved = null; // The server already put its copy in the page: no request, and no second // repaint a moment after the first. `looks: null` there is the 404 case. if (BOOT && "looks" in BOOT) saved = BOOT.looks ? { looks: BOOT.looks } : null; else { try { const res = await fetch("/looks"); if (res.ok) saved = await res.json(); } catch {} } if (saved && saved.looks && typeof saved.looks === "object") { adoptLooks(saved.looks); syncedLooks = { ...looks }; try { localStorage.setItem(LOOKS_KEY, JSON.stringify(looks)); } catch {} applyLooks(); renderSwatches(); } else { // Blocked storage throws on read, and that must not stop the page loading. let held = false; try { held = Boolean(localStorage.getItem(LOOKS_KEY)); } catch {} if (held) pushLooks(); } looksReady = true; // Not inline: with the server's copy in the page this runs before `S` exists. setTimeout(maybeWelcome, 0); } // Fire-and-forget mirror. A failed POST costs nothing the next session would // notice on this port; the localStorage copy still covers the reload case. function pushLooks() { try { // Only what this tab changed since it last synced, so a tab with stale // settings never overwrites another tab's change to a different key. const set = {}; for (const [k, v] of Object.entries(looks)) if (!syncedLooks || syncedLooks[k] !== v) set[k] = v; const before = syncedLooks; const partial = Boolean(before); if (partial && !Object.keys(set).length) return; syncedLooks = { ...looks }; const body = partial ? { set } : { looks }; // A write that did not land must be sent again with the next change. const undo = () => (syncedLooks = before); fetch("/looks", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), }) .then((res) => res.ok || undo()) .catch(undo); } catch {} } const systemDark = () => matchMedia("(prefers-color-scheme: dark)").matches; const effectiveTheme = () => (looks.theme === "system" ? (systemDark() ? "dark" : "light") : looks.theme); function applyLooks() { const root = document.documentElement; // The server's stand-in for the saved accent, which only has to last until // this runs. From here on the colors are set below, and a stale rule left // switched on would win over "Back to default". root.removeAttribute("data-looks-accent"); if (looks.theme === "system") root.removeAttribute("data-theme"); else root.setAttribute("data-theme", looks.theme); // Tell the browser too, so form controls, scrollbars and the date picker // follow the choice rather than staying on the system's idea of it. root.style.colorScheme = looks.theme === "system" ? "light dark" : looks.theme; // Before the accent's early return, so a default accent never skips it. if (looks.width === DEFAULT_CARD_WIDTH) root.removeAttribute("data-width"); else root.dataset.width = looks.width; // The default lives in the stylesheet, where it is written once per theme. // Clearing the override is how it gets its own values back. if (looks.accent === DEFAULT_LOOKS.accent) { for (const name of ACCENT_VARS) root.style.removeProperty(name); return; } const shades = ACCENTS[looks.accent][effectiveTheme()]; ACCENT_VARS.forEach((name, i) => root.style.setProperty(name, shades[i])); } function saveLooks() { try { localStorage.setItem(LOOKS_KEY, JSON.stringify(looks)); } catch {} pushLooks(); applyLooks(); // A width change reflows the card without resizing the column, so the // column's observer never hears of it: refit the growing box here. fitGrowBox(); renderSwatches(); } // Built once, repainted in place. Rebuilding the row on every choice destroyed // the button that had just been clicked, so focus fell to
and a keyboard // user lost their place in the dialog each time they tried a color. function renderSwatches() { const box = $("looks-swatches"); if (!box.children.length) { for (const [id, a] of Object.entries(ACCENTS)) { const b = el("button", "swatch"); b.type = "button"; b.dataset.accent = id; b.title = a.name; b.setAttribute("aria-label", a.name); b.addEventListener("click", () => { looks.accent = id; saveLooks(); }); box.appendChild(b); } } for (const b of box.children) { const id = b.dataset.accent; const [fill, , , line] = ACCENTS[id][effectiveTheme()]; b.setAttribute("aria-pressed", String(looks.accent === id)); // Fill and ring, so the swatch shows the pair the choice actually sets // rather than half of it. The chosen one is still told apart by its // double ring, which is drawn in ink and owes nothing to the accent. b.style.background = fill; b.style.borderColor = line; } for (const radio of document.querySelectorAll('input[name="looks-theme"]')) { radio.checked = radio.value === looks.theme; } for (const radio of document.querySelectorAll('input[name="looks-width"]')) { radio.checked = radio.value === looks.width; } $("looks-sound").checked = looks.sound; // Each cue keeps its own tick while the master switch is off, so turning // sound back on returns exactly the set that was chosen. $("looks-sound-events").classList.toggle("is-off", !looks.sound); for (const box of document.querySelectorAll("input[data-sound]")) { box.checked = looks[soundKey(box.dataset.sound)]; box.disabled = !looks.sound; } $("looks-role").value = looks.role ?? ROLE_NOT_SET; } // Following the system means following it as it changes, including the accent, // whose light and dark shades are different colors. matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => { if (looks.theme === "system") { applyLooks(); renderSwatches(); } }); loadLooks(); if (BOOT && BOOT.looks && typeof BOOT.looks === "object") adoptLooks(BOOT.looks); applyLooks(); syncLooks(); /* ------------------------------------------------------------- sounds The cues are the events in SOUND_EVENTS: a skill started from the dashboard, Planny snoring and waking, the session opening and ending, a new batch of questions, a launched skill ready, a reply on Ask, and a new tab joining the strip (a posted document, a spec's overview). Each plays only while both the master switch and its own switch are on. A browser will not let a page make noise before the person has touched it, so a cue that fires too early is held and let out by the first click or keypress rather than dropped. Only ever one at a time, never two overlapping or back to back. Cues asked for in the same task collapse to the highest-ranked one; a cue asked for while another is still playing is dropped unless it outranks it, in which case it cuts the quieter one off. The held cue is a single slot on the same rule, so the first click lets out one sound, not a queue of them. Made on first use, not at load: audio downloads racing the page's own scripts at start-up are bytes spent on sounds a browser will not play before the first click anyway. One Audio per file, shared by the events that use it. */ const SOUNDS = {}; let soundQueued = null; let soundHeld = null; let soundPlaying = null; const soundOn = (event) => looks.sound && looks[soundKey(event)]; const soundAudio = (event) => SOUNDS[SOUND_EVENTS[event].file]; const louderSound = (a, b) => (!b || SOUND_EVENTS[a].rank > SOUND_EVENTS[b].rank ? a : b); function sound(event) { if (!soundOn(event)) return; if (!soundQueued) queueMicrotask(flushSound); soundQueued = louderSound(event, soundQueued); } function flushSound() { const event = soundQueued; soundQueued = null; if (!soundOn(event)) return; const busy = soundPlaying && !soundAudio(soundPlaying).paused; if (busy && SOUND_EVENTS[event].rank <= SOUND_EVENTS[soundPlaying].rank) return; if (busy) soundAudio(soundPlaying).pause(); const { file } = SOUND_EVENTS[event]; const a = (SOUNDS[file] ||= new Audio(`/${file}.mp3`)); a.currentTime = 0; soundPlaying = event; a.play().catch(() => { if (soundPlaying === event) soundPlaying = null; soundHeld = louderSound(event, soundHeld); }); } // Fades a cue out over `ms` and stops it, so a long one never outlasts the // moment it belongs to. Timers, not frames: a background tab still finishes. function fadeSound(event, ms) { const a = soundAudio(event); if (!a || a.paused) return; const from = performance.now(); const timer = setInterval(() => { const left = 1 - (performance.now() - from) / ms; if (left > 0 && !a.paused) { a.volume = left; return; } clearInterval(timer); a.pause(); a.volume = 1; }, 25); } for (const evt of ["pointerdown", "keydown"]) { window.addEventListener(evt, () => { if (!soundHeld) return; const name = soundHeld; soundHeld = null; sound(name); }); } // The stars for Planny's flight, made once. Each gets its place and pace as // custom properties set through the CSSOM: the CSP forbids style attributes // in markup, and the stylesheet cannot roll dice. They sit still, invisible, // until the dock is `is-flying`. (function fillSky() { const sky = $("dock-sky"); const r = (a, b) => a + Math.random() * (b - a); for (let i = 0; i < 34; i++) { const star = document.createElement("i"); star.className = "star" + (i % 7 === 0 ? " hot" : ""); const dur = r(4, 12); star.style.setProperty("--y", r(3, 97).toFixed(1) + "%"); star.style.setProperty("--p", r(0, 1).toFixed(3)); star.style.setProperty("--s", r(1, 2.2).toFixed(2) + "px"); star.style.setProperty("--dur", dur.toFixed(2) + "s"); // Negative, so the field starts full rather than every star at the edge. star.style.setProperty("--delay", (-r(0, dur)).toFixed(2) + "s"); sky.appendChild(star); } })(); const GONE_AFTER_MS = 8000; // Named so a reconnect can clear only THIS banner: a bare banner(null) would // wipe an unrelated warning that landed while the page was gone (an upload // failure, a refused send). const GONE_BANNER = "Lost contact with Plan2Code. Nothing you have typed is lost. A blip clears by itself; if Plan2Code starts again, it gives you a new link, so open that one."; const WORKING_GRACE_MS = 5 * 60 * 1000; // Two minutes with the agent mid-turn, three when it is merely meant to be // listening. The difference is the cost of being wrong: a working agent that // goes quiet is worth mentioning early, whereas the gap between `wait` // returning and the next patch landing is ordinary and must not be called a // failure. `wait` pokes /health every five seconds, so either threshold is // many missed pokes, not a slow one. const ADRIFT_MS = 3 * 60 * 1000; let S = null; let rev = 0; let agentLastSeen = null; let pendingResult = false; // Set while a "still being picked up" banner is showing (see the frame handler). let pendingBannerUp = false; let pendingStop = false; let lastContact = Date.now(); let gone = false; let selected = null; let view = "questions"; // Where each tab was scrolled, keyed by view id, so switching away and back // lands where the person left it. Page-side only and never persisted: a reload // starts every tab at its top. `drawnView` is the tab the DOM currently shows, // which `view` stops naming the moment a tab click sets it. const scrollMemory = new Map(); let drawnView = null; // The tab ids the strip last drew, so a tab the agent or page adds (a posted // document, a spec's overview) can replay the runway chevrons. Null until the // first draw, which the load pulse already covers. let drawnTabs = null; // The spec's overview.md as last fetched: `key` is the spec dir it was read // for, `text` the file, or null when there is none. See loadOverview(). let overview = { key: null, text: null }; // The dashboard's first-open wake-up (boot.js), while it runs. `cards` turns // true at the glide, which lets the menu in; `entered` once its entrance has // played; `typed` is how many characters of the note show, or null once all // of them do. Page-local: the reload guard is sessionStorage (maybeWake). let wake = null; // Once per page, whatever storage allows: a re-render mid-run must never // start a second one. let wakeTried = false; // True when a wake-up is waiting on the first click: the page load's opening // chime then gives way to the boot-up sound, played as he powers on. let wakeHoldsChime = false; // His snore while he sleeps (an Audio on loop), or null. Usually silent until // the waking click, since browsers refuse sound before one. let snore = null; // The dashboard pick being looked at on the confirm pane, before START is // pressed. Page-local like `view` — a reload simply shows the menu again. let dashPick = null; let es = null; let esErrors = 0; // The server's name for the exact view this page last drew from. Handed back // when the stream opens, so the server can skip resending what is on screen. let lastHave = null; let pollTimer = null; // After the stream gives up, polling keeps the page alive and a good poll tries // the stream again, no sooner than `esRetryAt`. The wait doubles on each give-up // (capped) and resets once a stream opens, so a flaky server is not // thrashed with new connections. const ES_RETRY_MIN_MS = 3000; const ES_RETRY_MAX_MS = 60000; let esRetryMs = ES_RETRY_MIN_MS; let esRetryAt = 0; let draftTimer = null; // The Quick question chat. `chatFrame` is the server's view of the current // conversation (the frame's `chat` block); everything else here is page-local // and gone on a reload. `chatDot` is the Ask tab's dot as last drawn, so a // reply chimes once; `askRowCount` is how many rows the pane last showed, so // a new one scrolls into view; `docInView` is the doc block nearest the top. let chatFrame = null; // The frame's workspace ({ folders, missing, remote, issues }) and meter // ({ points, level, fraction, words, tooltip }), or null before a server that // sends them. let wsFrame = null; let meterFrame = null; // The frame's update ({ installed, latest }), present only when a newer // release is out; null otherwise. let updateFrame = null; // The frame's Subagents switch ({ offered, supported, on, instruction, max, // revision }), or null before a server that sends it. let subagentsFrame = null; let chatDot = false; let chatSending = false; let chatResetting = false; let chatError = ""; let askRowCount = 0; let askPaintedOffline = false; let docInView = null; let docObserver = null; const declineOpen = new Map(); const deciding = new Set(); // What the about tracker last saw, so only a change is an event. const aboutSeen = { view: null, selected: undefined, spec: undefined }; // The chat's images live under local.chat, not beside the notes: the card // send gathers every entry of local.images, and a chat picture is not a note. const CHAT_IMAGES = "__chat"; let local = fresh(); // The question card currently on screen, so the quiet staging path can find its // border and pill again without a DOM search. Replaced on every renderCard. let cardMarks = null; function fresh() { // `stopping` is set once a stop request has been accepted, and kept here so // a reload in the middle of wrapping up comes back to the same screen. // `afterBuild` is "review", "commit", "done" or "dashboard" once a finished session's // offer has been answered, so the buttons do not come back on a reload. // `homeward` is set once the top bar's Back to the dashboard request has // been accepted mid-workflow: { at }. The resume through the dashboard // resets `local` wholesale, which is what clears it. // `launching` is the dashboard's pick while the launched skill turns the // page: { skill, title, at }. Kept here so a reload mid-handoff comes back // to the getting-ready screen rather than the menu it already answered. // `specSel` is the dashboard picker's spec dir, or null for "start from // scratch". Left ABSENT until the picker is touched, which is how the // default (most recently touched spec) differs from a deliberate scratch. // `retract` marks a send the person took back, keyed to the send's `at` so // it suppresses exactly that `submitted` record and no later one. // `images` is each note's attachments, keyed by item id: // [{ key, id, path, url, name, status }], status "uploading" | "ready" | "failed". return { staged: {}, drafts: {}, images: {}, sent: {}, stopping: null, afterBuild: null, homeward: null, launching: null, // A picker Delete sent and not yet answered by a rescan: { dir, scanAt }. deleting: null, retract: {}, chat: freshChat(), }; } // The Ask pane's own corner of `local`: the composer's draft and pictures, // what the next message is about, sends still on their way, and the newest // reply already seen (the dot). `conversation` is the one these belong to. function freshChat() { return { draft: "", history: [], about: null, pending: [], lastSeenReplyId: null, images: [], conversation: null, }; } function storeKey() { return "p2c-console:" + (S ? S.sid : "pending"); } function save() { try { localStorage.setItem(storeKey(), JSON.stringify(local)); } catch {} clearTimeout(draftTimer); draftTimer = setTimeout(pushDraft, 600); } function load() { try { const raw = localStorage.getItem(storeKey()); if (raw) local = { ...fresh(), ...JSON.parse(raw) }; } catch { local = fresh(); } // Saved before context became a pick: an about set on its own must not // survive the upgrade. Asked of the saved copy, before freshChat() fills // in an empty history. const upgraded = !Array.isArray(local.chat && local.chat.history); local.chat = { ...freshChat(), ...(local.chat || {}) }; if (upgraded) { local.chat.history = []; local.chat.about = null; } delete local.chat.frozen; delete local.chat.dropped; // A "Skipped" beat is a moment, not something to come back to on a reload. delete local.skipFlash; // A chat send still on its way when the page went died with the old page: // offered for Retry, never left saying "Sending…". If it did land, the // frame's echo still hides it. for (const p of local.chat.pending) if (!p.seq) p.failed = true; settleStaleUploads(); } // An upload still marked in flight when the page loads died with the old page. function settleStaleUploads() { for (const list of [...Object.values(local.images || {}), local.chat.images]) { for (const img of list) if (img.status === "uploading") img.status = "failed"; } } async function pushDraft() { try { await fetch("/draft", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ staged: local.staged, drafts: local.drafts, images: local.images }), }); } catch {} } /* ------------------------------------------------------------ selectors */ const items = () => (S && Array.isArray(S.items) ? S.items : []); const topics = () => (S && Array.isArray(S.topics) ? S.topics : []); const docs = () => (S && Array.isArray(S.docs) ? S.docs : []); const byId = (id) => items().find((i) => i.id === id); const isOpen = (i) => i.status === "open" || i.status === "reopened"; const asked = () => items().filter((i) => i.kind !== "notice"); const openItems = () => asked().filter(isOpen); const stagedCount = () => Object.keys(local.staged).length; // The one thing the page could never know before: this session is OVER, and // the agent said so rather than the page inferring it. Everything else here is // a pause -- no open questions means "none right now", not "no more ever" -- // which is why the end of a session used to read as a lull that never lifted. // A posted finish is the whole signal; its command is optional, because some // sessions end with nothing left to run. const finish = () => (S && S.finish && typeof S.finish === "object" ? S.finish : null); // The dashboard is the one workflow that is not a conversation: a menu of the // skills, rendered from the page's own catalog, where a click IS the answer. const isDashboard = () => S && S.workflow === "dashboard"; // The git board is drawn by the page too, from the console's own read-only // snapshot (state.git), with the agent's confirm and result cards above it. const isGitBoard = () => S && S.workflow === "git" && S.git; // A board click or a card send stays with the agent until its next post // (boardAwaiting in git-board.js), not just until `wait` collects it. function gitAwaiting() { if (!isGitBoard()) return false; return boardAwaiting({ sentAt: local.gitSentAt || null, updatedAt: S.updatedAt || null, cardsAwaiting: awaitingReply().length, adrift: agentAdrift(), }); } // What the person has typed or ticked on the board. Every state frame redraws // the board from state.git, so this is what carries their place across it. // panel the open panel: "create", "commit" or "cleanup", or null // create the Create prompt's fields, while it is open // ticks the commit table's ticked paths; ignore, its .gitignore toggles // sweep the cleanup list's ticked branches // base the pull-request base the picker chose // settled cards the agent settled since the last click on the board // tab the tab on show: "changes", "branches" or "sync", or null before the first draw // scroll how far the column was scrolled on each tab, put back after each redraw // repickAt when their last board click went out (ms): the first agent post // after it moves the board to the new next step's tab const board = { tab: null, scroll: { changes: 0, branches: 0, sync: 0 }, repickAt: null, query: "", showAll: false, remoteOpen: null, panel: null, create: null, ticks: null, ignore: new Set(), sweep: null, base: null, settled: new Set(), }; // The search, ticks and open panel are also kept in `local`, so a reload (and // a skill hop back) restores them the way card drafts already do. Stale picks // are harmless: the next send re-checks every path against the snapshot. The // restore waits for the first draw: load() has not run when this module does. const boardBlank = { tab: null, scroll: { changes: 0, branches: 0, sync: 0 }, repickAt: null, query: "", showAll: false, remoteOpen: null, panel: null, create: null, ticks: null, sweep: null, base: null, }; // Each reset gets its own scroll memory: boardBlank's must never be the one written to. const resetBoard = () => { Object.assign(board, boardBlank, { scroll: { ...boardBlank.scroll } }); board.ignore.clear(); }; let boardHydrated = false; // True from hydration until the first draw has picked its tab: that draw is a reload. let boardReloaded = false; const hydrateBoard = () => { boardHydrated = true; const g = local.gitBoard; if (!g) return; boardReloaded = true; Object.assign(board, boardBlank, { tab: GIT_TABS.some((t) => t.id === g.tab) ? g.tab : null, scroll: { changes: 0, branches: 0, sync: 0, ...(g.scroll || {}) }, repickAt: typeof g.repickAt === "number" ? g.repickAt : null, query: g.query || "", showAll: Boolean(g.showAll), remoteOpen: g.remoteOpen ?? null, panel: g.panel || null, create: g.create || null, ticks: g.ticks ? new Set(g.ticks) : null, sweep: g.sweep ? new Set(g.sweep) : null, base: g.base || null, ignore: new Set(g.ignore || []), }); }; const persistBoard = () => { local.gitBoard = { tab: board.tab, scroll: { ...board.scroll }, repickAt: board.repickAt, query: board.query, showAll: board.showAll, remoteOpen: board.remoteOpen, panel: board.panel, create: board.create, ticks: board.ticks ? [...board.ticks] : null, sweep: board.sweep ? [...board.sweep] : null, base: board.base, ignore: [...board.ignore], }; save(); }; // The server's scan of the repo — AGENTS.md plus every spec under specs/, // classified by pipeline stage and sorted most-recently-touched first. const scan = () => (S && S.scan) || null; const specList = () => { const sc = scan(); return sc && Array.isArray(sc.specs) ? sc.specs : []; }; // The spec the picker currently targets. Absent `specSel` means the picker // has not been touched, so it defaults to the most recently touched spec // still in play (defaultSpec: the server's list is already sorted, and a // fixed bug is skipped). An explicit "start from scratch" is stored as null, // which is different. const selSpec = () => { const specs = specList(); if (!specs.length) return null; if (local.specSel === undefined) return defaultSpec(specs); return specs.find((s) => s.dir === local.specSel) || null; }; // This checkout's unused handoffs (scan.handoffs, newest first). A handoff is // picked in the same chip row as a spec, stored as `specSel = "handoff:, built as nodes like everything else here.
function approvalTip() {
return textWithCode("p", "approval-tip", APPROVAL_TIP);
}
function renderStarting(main) {
const elapsed = startingElapsed();
const pane = posePane(main, "launching starting", S.workflow);
pane.appendChild(el("p", "card-kicker", "Starting up"));
pane.appendChild(el("h2", "launch-title", `Starting ${workflowTitle(S.workflow)}`));
pane.appendChild(el("p", "launch-quip", START_QUIPS[Math.floor(elapsed / 2600) % START_QUIPS.length]));
pane.appendChild(el("p", "launch-hint", startingHint(elapsed)));
pane.appendChild(approvalTip());
startLaunchTicker();
}
// The quips rotate on their own clock rather than on render: state frames
// arrive whenever the agent posts, and a waiting screen pinned to them
// would sit on one line for most of the wait. The interval looks the
// elements up fresh each tick, so it survives the screen being rebuilt,
// and it stops itself when neither screen is up any more.
function startLaunchTicker() {
if (!launchTicker) {
launchTicker = setInterval(() => {
const kicker = document.querySelector(".launching .card-kicker");
const title = document.querySelector(".launch-title");
const q = document.querySelector(".launch-quip");
const hint = document.querySelector(".launch-hint");
const cur = local.launching;
const starting = !cur && document.querySelector(".launching.starting");
if ((!cur && !starting) || !q) {
clearInterval(launchTicker);
launchTicker = null;
return;
}
if (starting) {
const elapsed = startingElapsed();
q.textContent = START_QUIPS[Math.floor(elapsed / 2600) % START_QUIPS.length];
if (hint) hint.textContent = startingHint(elapsed);
return;
}
const elapsed = Date.now() - cur.at;
const stale = staleLaunchFeedback(cur.title, agentAdrift());
if (kicker) kicker.textContent = stale ? stale.kicker : "On it";
if (title) title.textContent = stale ? stale.title : `Waking up ${cur.title || "the next mode"}`;
q.textContent = stale ? stale.quip : LAUNCH_QUIPS[Math.floor(elapsed / 2600) % LAUNCH_QUIPS.length];
if (hint) {
hint.textContent = stale
? stale.hint
: elapsed > 90000
? "Still getting ready. Your terminal has the play-by-play if you want to watch it there."
: "This page turns into its home the moment it answers. No need to touch anything.";
}
}, 900);
}
}
// To one question, at its top, with focus on the column.
function goToItem(id) {
selected = id;
view = "questions";
render();
const m = $("main");
m.focus();
m.scrollTop = 0;
}
// "Skip this one": staged as skipped, "Skipped" for a beat, then on to the
// next card that still needs the person, or to Send when this was the last.
// Anything the person does first (a click, a key) cancels the move.
let skipTimer = null;
function cancelSkipMove() {
if (!skipTimer) return;
clearTimeout(skipTimer);
skipTimer = null;
local.skipFlash = null;
}
document.addEventListener("pointerdown", cancelSkipMove, true);
document.addEventListener("keydown", cancelSkipMove, true);
function skipAndMoveOn(id) {
cancelSkipMove();
local.skipFlash = id;
// A note already typed goes along: skipping the question is not retracting
// the comment. Dropping it would leave the text in the box but out of the
// send, which looks kept and is not.
const cur = local.staged[id];
stage(id, { type: "skip", skipped: true, ...(cur && cur.text ? { text: cur.text } : {}) });
skipTimer = setTimeout(() => {
skipTimer = null;
local.skipFlash = null;
const openIds = openItems().map((i) => i.id);
const sent = Object.fromEntries(awaitingReply().map((i) => [i.id, true]));
const next = lastOpenCard(openIds, local.staged, sent, id) ? null : nextOpenAfter(openIds, local.staged, sent, id);
if (next) return goToItem(next);
render();
$("btn-send").focus();
}, 250);
}
// Previous / next across the questions still waiting.
//
// The left rail already navigates, but it is a list of everything and it reads
// as a table of contents rather than as a way through. Someone working down
// three open questions should not have to aim at a 13px row to reach the next
// one. Settled questions are deliberately not in this walk: they are reference,
// not work, and the rail is where you go back to them.
function buildPager(item) {
// Once the session has ended nothing open can be sent, so a way "back to
// what is waiting" would lead somewhere that goes nowhere.
if (finish()) return null;
// Theirs to answer, not just unanswered by the agent: a sent question
// waiting on the other end is not a place this walk should stop.
const open = myTurn();
if (!open.length) return null;
const go = (target) => goToItem(target.id);
const row = el("nav", "pager");
row.setAttribute("aria-label", "Move between the questions waiting");
const at = open.findIndex((i) => i.id === item.id);
if (at === -1) {
// Reading something already settled. The only move that means anything
// here is back to the work.
const b = el("button", "btn small pager-btn next");
b.type = "button";
const box = el("span", "pager-label");
box.appendChild(el("span", "pager-kicker", "Back to what is waiting"));
box.appendChild(el("span", "pager-title", open[0].title));
b.appendChild(box);
b.appendChild(el("span", "pager-arrow", "→"));
b.addEventListener("click", () => go(open[0]));
row.className = "pager one";
row.appendChild(b);
return row;
}
if (open.length < 2) return null;
// Once this question is answered, the step is the next unanswered one, not
// Send. Send lighting up the moment a single answer is staged pulls people
// into sending one question at a time, which is three round trips where the
// workflow wanted one. So the emphasis moves to whichever neighbour still
// needs them, and Send goes quiet until nothing does.
const here = Boolean(local.staged[item.id]);
const nextT = open[at + 1];
const prevT = open[at - 1];
// "Still needs them" is not the same as "not staged": a question already sent
// is locked and waiting on the agent, so pointing at it as the step would
// walk someone into a card they cannot act on.
const needs = (t) => Boolean(t && !local.staged[t.id] && !(local.sent && local.sent[t.id]));
const leadNext = here && needs(nextT);
const leadPrev = here && !leadNext && needs(prevT);
// An end of the queue is an empty slot, not a disabled button. A greyed
// "Previous" pointing at nothing is a control that exists only to say no.
const mk = (target, back, lead) => {
if (!target) return el("span", "pager-slot");
const b = el(
"button",
"btn small pager-btn " + (back ? "prev" : "next") + (lead ? " lead" : " ghost")
);
b.type = "button";
const arrow = el("span", "pager-arrow", back ? "←" : "→");
const box = el("span", "pager-label");
box.appendChild(el("span", "pager-kicker", back ? "Previous" : "Next"));
box.appendChild(el("span", "pager-title", target.title));
if (back) {
b.appendChild(arrow);
b.appendChild(box);
} else {
b.appendChild(box);
b.appendChild(arrow);
}
b.addEventListener("click", () => go(target));
return b;
};
row.appendChild(mk(prevT, true, leadPrev));
row.appendChild(el("span", "pager-count", `${at + 1} of ${open.length} waiting`));
row.appendChild(mk(nextT, false, leadNext));
return row;
}
function renderWaiting(main) {
const doing = doingNow();
// Nothing asked and nothing said yet: the session is still starting.
if (!doing) return renderStarting(main);
// The same Planny the session started with, still at it: the spinner that
// stood here said less about what was going on than he does.
const pane = posePane(main, "waiting-pane", S.workflow);
// A build with nothing to ask yet. Say what is happening and where to
// watch it, instead of promising questions that may not come for a while.
const title = el("h2", null, (S.headline && S.headline.stage) || "Working on it");
// Once the agent stops answering nothing is turning, so neither is the ring
// (the adrift watcher redraws this pane on the flip).
if (!agentAdrift()) {
const spin = el("span", "spinner tiny waiting-spin");
spin.setAttribute("aria-hidden", "true");
title.prepend(spin);
}
pane.appendChild(title);
pane.appendChild(el("p", null, doing));
const ask = "If Plan2Code needs you, the question appears here on its own.";
if (!docs().length) {
pane.appendChild(el("p", null, ask));
return;
}
// "Task" and the tasks tab's own name both open that tab, so the pointer is
// one click from what it points at. A build posts it as `phase` ("Phase N
// tasks"); a quick task ticks the steps of its `plan` in place (an older
// agent may still post a separate `tasks` tab). A skill with no task list
// (Document, Plan) has nothing live to follow, so it gets no pointer at all.
const list =
docs().find((d) => d.id === "phase") ||
docs().find((d) => d.id === "tasks") ||
(S.workflow === "quick-task" && docs().find((d) => d.id === "plan")) ||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
if (!list) {
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
return;
}
const jump = (word) => {
const b = el("button", "waiting-jump", word);
b.type = "button";
b.addEventListener("click", () => {
view = "doc:" + list.id;
render();
});
return b;
};
const p = el("p");
p.append(
"The tabs above fill in as it goes. You can follow along with live ",
jump("Task"),
" updates in the ",
jump(list.title || "Phase tasks"),
" tab. " + ask
);
pane.appendChild(p);
}
// A notice is context for the question it sits beside, so it lives inside the
// one card rather than as a second one under it.
function renderNotice(item) {
const box = el("div", "card-note card-extra");
box.appendChild(el("p", "note-kicker", "Note"));
box.appendChild(el("h3", "note-title", item.title));
box.appendChild(md(item.body, "md"));
return box;
}
// An ANSWER that has been sent but not yet dealt with. Its controls are locked:
// the agent is mid-turn on exactly this question, so a change made now reaches
// nobody, and the change would then be deleted by the next state update.
//
// A send carrying only a note is not that. Someone who asks a question about
// the question before answering it has not answered it, and locking the form
// there leaves an open question that cannot be answered at all. The note is
// still shown as on its way, by the "Sent" pill and the rail mark.
function inFlightFor(item) {
if (!isOpen(item) || finish()) return null;
const sent = local.sent && local.sent[item.id];
if (sentAnswer(sent)) return sent;
// The send this tab no longer remembers (a reload, a resumed session, a
// second tab) or one the agent took without settling the question: the
// server's copy on the item is the same fact either way.
const sub = submittedInFlight(item);
return sub ? { value: sub, summary: "" } : null;
}
// A sent note's attachments as links: an image opens full size, a document
// opens in its own tab. The page serves both by the upload's own file name.
function sentAttachments(note) {
const entries = [
...(note.images || []).map((e) => ({ ...e, kind: "image" })),
...(note.files || []).map((e) => ({ ...e, kind: "file" })),
];
if (!entries.length) return null;
const tray = el("div", "attach-tray");
for (const e of entries) {
const a = el("a", "attach-link");
a.href = uploadUrl(e);
a.target = "_blank";
a.rel = "noopener";
a.title = e.name || "attachment";
if (e.kind === "image") {
const fig = el("figure", "attach-thumb is-ready");
const pic = el("img");
pic.src = a.href;
pic.alt = e.name || "image";
fig.appendChild(pic);
a.appendChild(fig);
} else a.appendChild(docChip({ name: e.name || "file" }, "ready"));
tray.appendChild(a);
}
return tray;
}
function renderCard(item) {
const staged = local.staged[item.id];
const flight = inFlightFor(item);
const card = el(
"article",
"card question" +
(!isOpen(item) || finish() ? " is-answered" : staged ? " is-staged" : "") +
(flight ? " is-inflight" : "")
);
// Which question this card is for, so a render can tell whether the card it
// is replacing is the same one (keep the scroll) or a different one (start
// at the top).
card.dataset.item = item.id;
const kicker = el("p", "card-kicker");
fillKicker(kicker, item);
card.appendChild(kicker);
// Held so the quiet staging path can repaint the border and the pill without
// rebuilding the card, which would take the textarea being typed into with it.
cardMarks = { id: item.id, card, kicker };
card.appendChild(el("h2", null, item.title));
if (item.body) card.appendChild(md(item.body, "md prompt"));
const link = docLink(item);
if (link) card.appendChild(link);
// An item still open on a finished session renders as the same record a
// settled one does: the send it carries is the final word on it, because a
// send can no longer go anywhere and the form would be a trap.
if (!isOpen(item) || finish()) {
renderSettled(card, item);
} else if (flight) {
renderInFlight(card, item, flight);
} else {
const build = BUILDERS[item.kind];
if (build) build(card, item, staged);
}
if (item.required === false && isOpen(item) && !flight && !finish()) {
const skipped = Boolean(staged && staged.skipped);
const skip = el("button", "linky", skipped ? "Do not skip" : "Skip this one");
skip.type = "button";
skip.style.marginTop = "16px";
skip.addEventListener("click", () => (skipped ? stage(item.id, null) : skipAndMoveOn(item.id)));
card.appendChild(skip);
if (local.skipFlash === item.id) {
card.classList.add("is-skip-flash");
const flash = el("span", "skip-flash", "Skipped");
flash.setAttribute("role", "status");
card.appendChild(flash);
}
}
if (isOpen(item) && !flight && !finish()) markGrowBox(card);
return card;
}
/* ------------------------------------------------------ settled answers */
// A settled question is a record, not a form. Everything below exists because
// a disabled radio still looks like a radio: people tried to change answers
// that were already recorded, and the page gave them no reason to believe they
// could not. So the answer is stated in words at the top, the controls are
// replaced by static marks rather than merely disabled, and the card says out
// loud that this one is closed.
function renderSettled(card, item) {
const v = recordedAnswer(item);
const lines = answerLines(item, v);
const text = v && typeof v.text === "string" ? v.text.trim() : "";
// Fall back to the last thing they said on this question, but only when there
// is nothing else at all. Attaching a side note to a pick they also made
// would misreport which of the two was the answer.
let prose = text;
let fromNote = false;
if (!prose && !lines.length) {
const mine = (item.thread || []).filter((m) => threadWho(m) === "user");
if (mine.length) prose = threadText(mine[mine.length - 1]).trim();
fromNote = Boolean(prose);
}
const nothing = !lines.length && !prose;
const box = el("div", "answered" + (nothing ? " is-empty" : ""));
const head = el("p", "answered-head");
head.appendChild(el("span", "answered-mark", nothing ? "·" : "✓"));
// A note is not an answer: say which it is.
head.appendChild(el("span", null, nothing ? "No answer recorded" : fromNote ? "Your last note" : "Your answer"));
box.appendChild(head);
if (lines.length) {
const ul = el("ul", "answered-values");
for (const line of lines) ul.appendChild(el("li", null, line));
box.appendChild(ul);
}
if (prose) box.appendChild(el("blockquote", "answered-text", prose));
if (nothing) {
box.appendChild(
el(
"p",
"answered-none",
isOpen(item)
? "The session ended before this was answered."
: "This was answered somewhere other than this page, so there is nothing to show."
)
);
}
box.appendChild(
el(
"p",
"answered-lock",
isOpen(item)
? nothing
? "The session is over."
: "The session is over, so this stands as it was sent."
: "Locked. If this needs to change, say so in a note on a question that is still open, or in the terminal."
)
);
card.appendChild(box);
const context = SETTLED_CONTEXT[item.kind];
if (context) context(card, item, v);
}
// The same record, in the moment between pressing Send and the agent replying.
//
// It is deliberately NOT an overlay over the page. The wait is when someone
// re-reads the document, looks ahead at what is coming, or catches up on a
// question they skimmed, and that reading is the whole reason this page beats
// the terminal. What has to stop is editing THIS question, because the agent is
// mid-turn on it: a change made now reaches nobody and is deleted by the next
// update. So the one card that cannot be acted on locks, and nothing else does.
function renderInFlight(card, item, flight) {
const v = flight.value || null;
const lines = answerLines(item, v);
const text = v && typeof v.text === "string" ? v.text.trim() : "";
const box = el("div", "answered is-sent");
const head = el("p", "answered-head");
head.appendChild(el("span", "answered-mark", "↑"));
head.appendChild(el("span", null, "Sent"));
box.appendChild(head);
if (lines.length) {
const ul = el("ul", "answered-values");
for (const line of lines) ul.appendChild(el("li", null, line));
box.appendChild(ul);
} else if (!text && flight.summary) {
// A send from an older page version, or a note with no answer attached.
const ul = el("ul", "answered-values");
ul.appendChild(el("li", null, flight.summary));
box.appendChild(ul);
}
if (text) box.appendChild(el("blockquote", "answered-text", text));
const note = noteAwaiting(item);
const sub = submittedAwaiting(item);
if (note && sub && note.at === sub.at) {
if (note.text) box.appendChild(el("blockquote", "answered-text", note.text));
const tray = sentAttachments(note);
if (tray) box.appendChild(tray);
}
// Say which of the two it actually is. Once the agent has collected the send,
// "waiting to be picked up" is no longer true, and a status line that lies is
// worse than none.
box.appendChild(
el(
"p",
"answered-lock",
pendingResult
? "Waiting for Plan2Code to pick this up. It unlocks by itself."
: "Plan2Code is working on it. This unlocks by itself when it answers."
)
);
card.appendChild(box);
const context = SETTLED_CONTEXT[item.kind];
if (context) context(card, item, v);
// A stuck agent must not lock someone out of their own answer forever. This
// is the card-level twin of the Send button's grace period, and it appears on
// the same terms -- a send could actually go through. sendState() is not the
// test here: it is also disabled for an empty payload, and clicking this is
// what stages the payload it would send.
const sendWouldGo =
!finish() && !gone && !pendingResult && (!agentWorking() || workingMs() > patience(WORKING_GRACE_MS));
if (sendWouldGo) {
const undo = el("button", "linky", "Take this back and answer again");
undo.type = "button";
undo.style.marginTop = "16px";
undo.addEventListener("click", () => {
// Put the answer back as a staged one, exactly the state they were in
// before they pressed Send. Sending clears `staged` and the field's
// draft, so without this the button empties the box it offered to let
// them edit, and a long answer has to be typed a second time.
const back = sentAnswer(local.sent[item.id]);
delete local.sent[item.id];
// The server also records every send on the item (`submitted`), and that
// record counts as in flight on its own: taking THIS send back has to
// retract it too, or the card stays locked. Its `at` names the send, so
// one made afterwards still counts.
const sub = submittedAwaiting(item);
if (sub) (local.retract = local.retract || {})[item.id] = sub.at || "any";
if (back) {
local.staged[item.id] = back;
} else if (sub) {
// The send came off the server's copy on the item, so its value goes
// back on the form to be edited and sent again.
const { at, ...rest } = sub;
local.staged[item.id] = { type: "answer", ...rest };
}
save();
render();
});
card.appendChild(undo);
}
}
// The question's own material, shown back as a record. No inputs at all: a
// disabled control still invites a click, a static mark does not.
function lockedOptions(card, item, keys) {
if (!(item.options || []).length) return;
const picked = new Set(keys);
const list = el("ul", "options");
for (const o of item.options) {
const on = picked.has(o.k);
const li = el("li", "option is-locked" + (on ? " is-recorded" : ""));
li.appendChild(el("span", "option-mark" + (on ? " on" : ""), on ? "✓" : "·"));
const body = el("div", "option-body");
const head = el("div", "option-label");
if (showKey(o.k, o.text)) head.appendChild(el("span", "option-key", o.k));
head.appendChild(el("span", null, o.text));
if (on) head.appendChild(el("span", "pill done", "Your answer"));
body.appendChild(head);
if (o.detail) body.appendChild(el("p", "option-detail", o.detail));
li.appendChild(body);
list.appendChild(li);
}
card.appendChild(list);
}
function lockedSteps(card, item, v) {
if (!(item.steps || []).length) return;
const done = new Set((v && v.done) || []);
const list = el("ol", "steps");
item.steps.forEach((step, i) => {
const li = el("li", "step is-locked");
li.appendChild(el("span", "step-num", String(i + 1)));
const on = done.has(i);
li.appendChild(el("span", "option-mark" + (on ? " on" : ""), on ? "✓" : "·"));
const body = el("div", "step-body");
body.appendChild(md(typeof step === "string" ? step : step.text, "md"));
li.appendChild(body);
list.appendChild(li);
});
card.appendChild(list);
}
function lockedRows(card, item, v) {
const rows = (v && Array.isArray(v.rows) && v.rows.length ? v.rows : item.rows) || [];
if (!rows.length) return;
const ul = el("ul", "rows");
rows.forEach((row, i) => {
const li = el("li", "row-item is-locked");
li.appendChild(el("span", "row-order", String(i + 1)));
const main = el("div", "row-main");
main.appendChild(el("p", "row-title-static", row.title || ""));
if (row.body) main.appendChild(el("div", "row-body", row.body));
li.appendChild(main);
ul.appendChild(li);
});
card.appendChild(ul);
}
function lockedSummary(card, item) {
if (!item.summary) return;
const box = el("div", "card-note");
box.appendChild(md(item.summary, "md"));
card.appendChild(box);
}
const SETTLED_CONTEXT = {
choice: (card, item, v) => lockedOptions(card, item, v && v.k ? [v.k] : []),
menu: (card, item, v) => lockedOptions(card, item, v && v.k ? [v.k] : []),
multi: (card, item, v) => lockedOptions(card, item, (v && v.ks) || []),
checklist: lockedSteps,
list: lockedRows,
recap: lockedSummary,
review: lockedSummary,
};
/* -------------------------------------------------------- the builders */
/**
* "Something else" as a real option in the radio group, for a single-choice
* question.
*
* It used to be a plain field below the list, and typing in it MERGED the text
* into whatever was already picked: choosing A and then writing why A is wrong
* sent `a; A is wrong`, the pick first, the contradiction second. Nothing on
* screen said that would happen, and the field's own words ("if none of the
* above fit") promise the opposite.
*
* On a one-answer question these are alternatives, so they share a radio group
* and the last thing touched wins. Qualifying a pick has its own home: the note
* box beside the question, which travels as a comment rather than an answer.
*
* `multi` keeps the additive field below, where naming a third thing alongside
* two ticked boxes is exactly right.
*/
function otherOption(list, item, staged, name) {
if (item.allowOther === false) return;
const id = "other-" + item.id;
const on = Boolean(staged && !staged.k && staged.text);
const li = el("li", "option is-other" + (on ? " is-picked" : ""));
const radio = el("input");
radio.type = "radio";
radio.name = name;
radio.checked = on;
radio.setAttribute("aria-label", "Something else, in your own words");
const body = el("div", "option-body");
const head = el("div", "option-label");
const label = el("label", null, "Something else, in your own words");
label.htmlFor = id;
head.appendChild(label);
body.appendChild(head);
const ta = el("textarea", "other-text");
ta.id = id;
ta.placeholder = "If none of the above fit, say what does.";
// A draft survives picking a listed option, so switching back and forth
// never costs someone the sentence they already wrote.
ta.value = (on && staged.text) || local.drafts[id] || "";
// Repaint the row highlights without a full render, which would rebuild this
// textarea mid-keystroke. Setting the radio marks the rest of the group off
// by itself; only the `is-picked` classes need saying out loud.
const pick = (chosen) => {
for (const node of list.children) node.classList.toggle("is-picked", node === chosen);
// The quiet path never re-renders, so the growing box follows the pick here.
markGrowBox(list.closest(".card"));
fitGrowBox();
};
ta.addEventListener("input", () => {
setDraft(id, ta.value);
const v = ta.value.trim();
if (v) {
radio.checked = true;
pick(li);
stageQuiet(item.id, choiceAnswer({ text: v }));
} else {
radio.checked = false;
pick(null);
const cur = local.staged[item.id];
if (cur && !cur.k) stageQuiet(item.id, null);
}
stagedChanged();
});
radio.addEventListener("change", () => {
const v = ta.value.trim();
pick(li);
// Nothing written yet: drop the previous pick, since they have just said it
// was not the answer, and put the cursor where the answer now goes.
stageQuiet(item.id, choiceAnswer({ text: v }));
stagedChanged();
ta.focus();
});
body.appendChild(ta);
li.appendChild(radio);
li.appendChild(body);
list.appendChild(li);
}
// The additive twin of otherOption, and the only caller left is `multi`, where
// naming a third thing alongside two ticked boxes is the point. The wording has
// to say that: "if none of the above fit" is the single-choice promise, and it
// would be a lie here, where what you write joins the ticks rather than
// replacing them.
function otherField(card, item, staged) {
if (item.allowOther === false) return;
const wrap = el("div", "field");
const id = "other-" + item.id;
const label = el("label", null, "Anything else, in your own words");
label.htmlFor = id;
wrap.appendChild(label);
const ta = el("textarea");
ta.id = id;
ta.placeholder = "Optional. This adds to the ones you picked above; it does not replace them.";
ta.value = (staged && staged.text) || local.drafts[id] || "";
ta.addEventListener("input", () => {
setDraft(id, ta.value);
const cur = local.staged[item.id];
if (ta.value.trim()) {
stageQuiet(item.id, { ...(cur || { type: "answer", kind: item.kind }), text: ta.value.trim() });
} else if (cur && cur.text) {
const { text, ...rest } = cur;
if (rest.k || (rest.ks && rest.ks.length)) stageQuiet(item.id, rest);
else stageQuiet(item.id, null);
}
stagedChanged();
});
wrap.appendChild(ta);
card.appendChild(wrap);
}
// Everything that has to catch up after a staged answer changed WITHOUT a full
// render, which is the path every text field takes.
//
// A full render is not an option here: renderMain() empties the column with
// replaceChildren(), and emptying a scrolled container resets its scrollTop, so
// the page would jump to the top on every keystroke. The pieces below are the
// ones that depend on a staged answer and hold no input, so they can be rebuilt
// mid-keystroke safely. Leaving them out is how the card sat with no border and
// the pager kept pointing the wrong way while the footer said "1 ready".
function stagedChanged() {
renderFooter();
renderSidebar();
renderStagedMarks();
}
// The topic line, and the one pill that says where this question has got to.
function fillKicker(kicker, item) {
const topic = topics().find((t) => t.id === item.topic);
kicker.replaceChildren(document.createTextNode(topic ? topic.title : "Question"));
let pill = null;
if (!isOpen(item)) pill = el("span", "pill done", item.status === "skipped" ? "Skipped" : "Answered");
// Frozen on a finished session: the send it carries is the record, and a
// staged leftover can no longer be sent, so it earns no pill.
else if (finish()) pill = recordedAnswer(item) ? el("span", "pill done", "Sent") : null;
else if (local.staged[item.id]) pill = el("span", "pill staged", "Ready to send");
else if ((local.sent && local.sent[item.id]) || submittedInFlight(item))
pill = el("span", "pill staged", "Sent");
if (!pill) return;
pill.style.marginLeft = "8px";
kicker.appendChild(pill);
}
function renderStagedMarks() {
const item = byId(selected);
if (!item || !cardMarks || cardMarks.id !== item.id || !cardMarks.card.isConnected) return;
cardMarks.card.classList.toggle("is-staged", isOpen(item) && !finish() && Boolean(local.staged[item.id]));
fillKicker(cardMarks.kicker, item);
const main = $("main");
const shown = main.querySelector(".pager");
const next = buildPager(item);
if (shown && next) shown.replaceWith(next);
else if (shown) shown.remove();
else if (next) {
// Under its card, not under whatever follows it (the git board).
const card = main.querySelector(":scope > .card, :scope > .git-board > .git-cards > .card");
if (card) card.after(next);
else main.appendChild(next);
}
}
// Update staged state without a full re-render, so typing is never interrupted.
function stageQuiet(id, value) {
if (value == null) delete local.staged[id];
else local.staged[id] = value;
save();
}
// The next answer for a click, carrying over the words typed on the card. Note
// boxes stage quietly, without a render, so the `staged` a builder closed over
// at render time can be missing everything typed since: read the live answer
// when the click lands instead. A click that clears the pick while text is
// still in the box keeps the text as a note on its own (`bare`), the same shape
// the note box stages when nothing is picked.
function withNote(item, value, bare = { type: "answer", kind: item.kind }) {
const cur = local.staged[item.id];
const text = cur && cur.text;
if (!text) return value;
return value ? { ...value, text } : { ...bare, text };
}
// Unique per question and option, and the same on every render.
const optionId = (item, o, i) => `pick-${item.id}-${o.k || i}`;
function buildChoice(card, item, staged) {
const list = el("ul", "options");
const name = "opt-" + item.id;
for (const [i, o] of (item.options || []).entries()) {
const picked = staged && staged.k === o.k;
const li = el("li", "option" + (picked ? " is-picked" : ""));
const label = el("label");
label.style.display = "contents";
const radio = el("input");
radio.type = "radio";
radio.name = name;
// An id so the control survives the render its own change() sets off:
// withFocus finds the focused input by id and has nothing to go on without
// one. Stable across renders because it is built from the question and the
// option, not from a counter.
radio.id = optionId(item, o, i);
radio.value = o.k;
radio.checked = Boolean(picked);
// Without this the group reads out as "A", "B", "on": the letter is the
// label's whole text content, and the last one has no label at all.
radio.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
// choiceAnswer drops any text that was typed below. On a one-answer
// question a listed option and something in your own words are
// alternatives, and sending both hands the agent an answer that argues
// with itself.
radio.addEventListener("change", () => stage(item.id, choiceAnswer({ k: o.k })));
const body = el("div", "option-body");
const head = el("div", "option-label");
if (showKey(o.k, o.text)) head.appendChild(el("span", "option-key", o.k));
head.appendChild(el("span", null, o.text));
if (o.recommended) head.appendChild(el("span", "pill suggested", "Suggested"));
body.appendChild(head);
if (o.detail) body.appendChild(el("p", "option-detail", o.detail));
label.appendChild(radio);
label.appendChild(body);
li.appendChild(label);
list.appendChild(li);
}
otherOption(list, item, staged, name);
card.appendChild(list);
}
function buildMulti(card, item, staged) {
const chosen = new Set((staged && staged.ks) || []);
const list = el("ul", "options");
for (const [i, o] of (item.options || []).entries()) {
const on = chosen.has(o.k);
const li = el("li", "option" + (on ? " is-picked" : ""));
const label = el("label");
label.style.display = "contents";
const box = el("input");
box.type = "checkbox";
box.id = optionId(item, o, i);
box.value = o.k;
box.checked = on;
box.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
box.addEventListener("change", () => {
const cur = local.staged[item.id];
const next = new Set((cur && cur.ks) || []);
if (box.checked) next.add(o.k);
else next.delete(o.k);
// Unticking the last box keeps what is written in "Anything else".
stage(
item.id,
withNote(item, next.size ? { type: "answer", kind: "multi", ks: [...next] } : null, {
type: "answer",
kind: "multi",
ks: [],
})
);
});
const body = el("div", "option-body");
const head = el("div", "option-label");
if (showKey(o.k, o.text)) head.appendChild(el("span", "option-key", o.k));
head.appendChild(el("span", null, o.text));
if (o.recommended) head.appendChild(el("span", "pill suggested", "Suggested"));
body.appendChild(head);
if (o.detail) body.appendChild(el("p", "option-detail", o.detail));
label.appendChild(box);
label.appendChild(body);
li.appendChild(label);
list.appendChild(li);
}
card.appendChild(list);
card.appendChild(el("p", "help", "Pick as many as apply."));
renderPresets(card, item, staged);
otherField(card, item, staged);
}
// Shortcuts that tick a named set in one go, for a long list where the usual
// answers are groups ("the serious ones", "all of them"): the review's fix
// list is the case it exists for. A preset only ticks boxes. The answer is
// still the ticks, so they can adjust after pressing one, and what reaches the
// agent is the same list it would have got from ticking by hand.
function renderPresets(card, item, staged) {
const known = new Set((item.options || []).map((o) => o.k));
const presets = (Array.isArray(item.presets) ? item.presets : [])
.map((p) => ({ label: String((p && p.label) || "").trim(), ks: ((p && p.ks) || []).filter((k) => known.has(k)) }))
.filter((p) => p.label && p.ks.length);
if (!presets.length) return;
const row = el("div", "btn-row presets");
row.appendChild(el("span", "presets-label", "Quick pick:"));
const now = new Set((staged && staged.ks) || []);
for (const p of presets) {
const on = p.ks.length === now.size && p.ks.every((k) => now.has(k));
const b = el("button", "btn small" + (on ? " primary" : " ghost"), p.label);
b.type = "button";
b.setAttribute("aria-pressed", String(on));
b.addEventListener("click", () =>
stage(
item.id,
withNote(item, on ? null : { type: "answer", kind: "multi", ks: [...p.ks] }, {
type: "answer",
kind: "multi",
ks: [],
})
)
);
row.appendChild(b);
}
card.appendChild(row);
}
function buildText(card, item, staged) {
const wrap = el("div", "field");
const id = "text-" + item.id;
const head = el("div", "field-head");
const label = el("label", null, item.inputLabel || "Your answer");
label.htmlFor = id;
head.appendChild(label);
wrap.appendChild(head);
// Compiled once, here: a pattern that does not compile is treated as no
// pattern at all, rather than throwing on every keystroke (and on Autofill)
// and leaving the answer impossible to stage.
let pattern = null;
if (item.pattern) {
try {
pattern = new RegExp(item.pattern);
} catch {}
}
const single = Boolean(pattern);
const input = el(single ? "input" : "textarea");
if (single) input.type = "text";
input.id = id;
input.placeholder = item.placeholder || "Type here. Plain language is fine.";
input.value = (staged && staged.text) || local.drafts[id] || "";
attachMentions(input);
const err = el("p", "field-error");
err.hidden = true;
const suggestion = suggestionFrom(item);
let fill = null;
const check = () => {
setDraft(id, input.value);
// The offer only stands while the box is empty. Overwriting something
// someone typed, from a button they meant to read rather than press, is
// exactly the kind of loss this page is built to avoid.
if (fill) fill.hidden = Boolean(input.value.trim());
const v = input.value.trim();
if (pattern && v) {
// Live validation a terminal simply cannot do. Most often a kebab-case name.
const ok = pattern.test(v);
input.classList.toggle("invalid", !ok);
err.hidden = ok;
err.textContent = item.patternHint || "That is not a valid value.";
if (!ok) {
stageQuiet(item.id, null);
stagedChanged();
return;
}
} else {
input.classList.remove("invalid");
err.hidden = true;
}
stageQuiet(item.id, v ? { type: "answer", kind: "text", text: v } : null);
stagedChanged();
};
input.addEventListener("input", check);
if (suggestion) {
fill = el("button", "btn tiny", "Autofill suggestion");
fill.type = "button";
fill.title = "Put the example into the box. It is yours to edit from there.";
fill.hidden = Boolean(input.value.trim());
fill.addEventListener("click", () => {
input.value = suggestion;
check();
input.focus();
try {
input.setSelectionRange(suggestion.length, suggestion.length);
} catch {}
});
head.appendChild(fill);
}
if (item.templates === "idea" && TEMPLATE_WORKFLOWS.includes(S.workflow)) {
wrap.appendChild(templateRow(item, input, templatesFor(S.workflow, looks.role), check));
}
wrap.appendChild(input);
// Fresh-idea boxes take files as context, the same ones the note pane holds.
if (!single && TEMPLATE_WORKFLOWS.includes(S.workflow)) {
input.addEventListener("paste", (e) => {
const files = incomingFiles(e.clipboardData && e.clipboardData.files);
if (!files.length) return;
if (!e.clipboardData.getData("text/plain")) e.preventDefault();
attachFiles(item.id, files);
});
const under = attachRow(item.id, "Add files to this answer");
under.classList.add("is-under");
wrap.appendChild(under);
const attached = noteImages(item.id);
if (attached.length) wrap.appendChild(attachTray(item.id, attached));
}
if (item.help) wrap.appendChild(el("p", "help", item.help));
wrap.appendChild(err);
card.appendChild(wrap);
}
// The starter templates above a fresh-idea box. The chip choice lives only in
// local.drafts: what gets staged and sent is the box's text, never the id.
function templateRow(item, input, entries, check) {
const key = "tpl-" + item.id;
const row = el("div", "tpl-row");
row.setAttribute("role", "group");
row.setAttribute("aria-label", "Starter templates");
let strip = null;
const selectedEntry = () => entries.find((e) => e.id === local.drafts[key]) || entries[0];
// The strip changes the card's height without resizing the column, so the
// column's observer never hears of it: refit the growing box here.
const dropStrip = () => {
if (!strip) return;
strip.remove();
strip = null;
fitGrowBox();
};
const chips = entries.map((entry) => {
const chip = el("button", "tpl-chip", entry.label);
chip.type = "button";
if (entry.forYou) chip.appendChild(el("span", "tpl-pill", "For your role"));
chip.addEventListener("click", () => pick(entry));
row.appendChild(chip);
return chip;
});
const paint = () => {
const selected = selectedEntry();
chips.forEach((chip, i) => chip.setAttribute("aria-pressed", String(entries[i] === selected)));
};
const apply = (entry, text) => {
dropStrip();
input.value = text;
local.drafts[key] = entry.id;
check();
save();
paint();
input.focus();
const start = text.indexOf("[");
const end = start < 0 ? -1 : text.indexOf("]", start);
try {
if (end > start) input.setSelectionRange(start, end + 1);
else input.setSelectionRange(text.length, text.length);
} catch {}
};
const pick = (entry) => {
const selected = selectedEntry();
if (entry === selected) return;
const sw = templateSwap({ selectedText: selected.text, boxText: input.value, nextText: entry.text });
if (!sw.confirm) {
apply(entry, sw.text);
return;
}
dropStrip();
strip = el("div", "tpl-replace");
strip.setAttribute("role", "alert");
strip.appendChild(el("span", null, "Replace what you typed?"));
const replace = el("button", "btn tiny primary", "Replace");
replace.type = "button";
replace.addEventListener("click", () => apply(entry, sw.text));
const keep = el("button", "btn tiny ghost", "Keep mine");
keep.type = "button";
keep.addEventListener("click", () => {
dropStrip();
input.focus();
});
strip.append(replace, keep);
row.after(strip);
fitGrowBox();
};
paint();
return row;
}
function buildConfirm(card, item, staged) {
const row = el("div", "btn-row");
const yesLabel = item.yesLabel || "Yes";
const noLabel = item.noLabel || "No";
const mk = (label, yes, danger) => {
const on = staged && staged.yes === yes;
const b = el("button", "btn" + (on ? " primary" : "") + (danger && !on ? " danger" : ""), label);
b.type = "button";
b.addEventListener("click", () =>
stage(item.id, withNote(item, on ? null : { type: "answer", kind: "confirm", yes }))
);
return b;
};
row.appendChild(mk(yesLabel, true, item.danger));
row.appendChild(mk(noLabel, false, false));
card.appendChild(row);
if (item.consequences) {
// "is-consequences": the command here is what Yes runs, so no "paste it
// into the Ask tab" nudge under it (app.css).
const note = el("div", "card-note is-consequences");
note.appendChild(md(item.consequences, "md"));
card.appendChild(note);
}
if (Array.isArray(item.files) && item.files.length) card.appendChild(filesTable(item.files));
commentField(card, item, "Anything to add?");
}
// A collapsed list of the files a confirm is about ({ path, state } rows), so
// "15 files" can be opened up and read before the person says yes.
function filesTable(files) {
const box = el("details", "card-files");
box.appendChild(el("summary", "", `Show the ${files.length} file${files.length === 1 ? "" : "s"}`));
const table = el("table", "md-table");
const head = el("tr");
head.appendChild(el("th", "", "State"));
head.appendChild(el("th", "", "File"));
table.appendChild(head);
for (const f of files) {
if (!f || typeof f.path !== "string") continue;
const row = el("tr");
row.appendChild(el("td", "", typeof f.state === "string" ? f.state : ""));
row.appendChild(el("td", "", f.path));
table.appendChild(row);
}
box.appendChild(table);
return box;
}
function buildRecap(card, item, staged) {
// The recap is not optional: a click captured the pick, this captures the
// agreement. Rendered as a document so it reads like a summary, not a form.
if (item.summary) {
const box = el("div", "card-note");
box.appendChild(md(item.summary, "md"));
card.appendChild(box);
}
const row = el("div", "btn-row");
const okOn = staged && staged.ok === true;
const fixOn = staged && staged.ok === false;
const ok = el("button", "btn" + (okOn ? " primary" : ""), item.yesLabel || "Yes, that is right");
ok.type = "button";
ok.addEventListener("click", () => stage(item.id, okOn ? null : { type: "answer", kind: "recap", ok: true }));
const fix = el("button", "btn" + (fixOn ? " primary" : ""), item.noLabel || "Not quite");
fix.type = "button";
fix.addEventListener("click", () =>
stage(item.id, fixOn ? null : { type: "answer", kind: "recap", ok: false })
);
row.appendChild(ok);
row.appendChild(fix);
card.appendChild(row);
if (fixOn) commentField(card, item, "What should it say instead?", true);
}
// A question that is about a document says so on the card, with a way to it.
// The tab row does the same job, but nobody reads a tab row as part of the
// question in front of them: people ticked the review's fix list blind, never
// having noticed the findings sat one tab over.
function docLink(item) {
const doc = item.doc && docs().find((d) => d.id === item.doc);
if (!doc) return null;
const open = el("button", "btn small", `Read “${doc.title || "the document"}” in full`);
open.type = "button";
open.style.marginTop = "14px";
open.addEventListener("click", () => {
view = "doc:" + doc.id;
render();
});
return open;
}
function buildReview(card, item, staged) {
if (item.summary) {
const box = el("div", "card-note");
box.appendChild(md(item.summary, "md"));
card.appendChild(box);
}
if (item.nothingYet !== false) {
const safe = el("p", "help");
safe.style.marginTop = "14px";
safe.textContent =
item.nothingYet || "Nothing has been changed yet. This only happens once you approve it.";
card.appendChild(safe);
}
const verdicts = item.verdicts || [
{ id: "approve", label: "Looks good, go ahead" },
{ id: "changes", label: "I want changes" },
];
const row = el("div", "btn-row");
for (const v of verdicts) {
const on = staged && staged.verdict === v.id;
// A picked danger verdict stays red (filled), so choosing "Abort" never
// reads like choosing the safe default. An unpicked approve or yes (Build
// it, Archive it) is outlined in the accent, so the main way forward
// stands out.
const forward = v.id === "approve" || v.id === "yes";
const b = el(
"button",
"btn" + (on ? (v.danger ? " danger is-on" : " primary") : v.danger ? " danger" : forward ? " is-approve" : ""),
verdictText(v)
);
b.type = "button";
b.addEventListener("click", () =>
stage(item.id, withNote(item, on ? null : { type: "answer", kind: "review", verdict: v.id }))
);
row.appendChild(b);
}
card.appendChild(row);
// Every gate in the workflow accepts "or describe any issues", so approval
// and feedback are one submit, never two.
commentField(card, item, "Notes, questions, or what to change");
}
function buildChecklist(card, item, staged) {
const doneSet = new Set((staged && staged.done) || []);
// Built from the live answer, so a note typed since the render rides along.
// Nothing ticked, no state and no note is no answer at all: stage nothing
// rather than an empty one that would still count as ready to send.
const commitList = (change) => {
const cur = local.staged[item.id];
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
// A tick or a state IS the answer, so it ends a skip staged earlier:
// left in place, `skipped` would collapse the reply to "skip" while the
// card showed ticked steps on their way.
delete next.skipped;
const empty = !(next.done && next.done.length) && !next.state && !next.text;
stage(item.id, empty ? null : next);
};
const list = el("ol", "steps");
(item.steps || []).forEach((step, i) => {
const li = el("li", "step");
const box = el("input");
box.type = "checkbox";
box.id = `step-${item.id}-${i}`;
box.checked = doneSet.has(i);
box.addEventListener("change", () => {
const cur = local.staged[item.id];
const next = new Set((cur && cur.done) || []);
if (box.checked) next.add(i);
else next.delete(i);
commitList({ done: [...next] });
});
const label = el("label");
label.htmlFor = box.id;
label.style.flex = "1";
label.appendChild(md(typeof step === "string" ? step : step.text, "md"));
li.appendChild(el("span", "step-num", String(i + 1)));
li.appendChild(box);
li.appendChild(label);
list.appendChild(li);
});
card.appendChild(list);
const states = [
{ id: "done", label: "All done" },
{ id: "blocked", label: "I am stuck" },
{ id: "help", label: "I need help" },
{ id: "defer", label: "Later" },
];
const row = el("div", "btn-row");
for (const s of states) {
const on = staged && staged.state === s.id;
const b = el("button", "btn" + (on ? " primary" : ""), s.label);
b.type = "button";
b.addEventListener("click", () => commitList({ state: on ? null : s.id }));
row.appendChild(b);
}
card.appendChild(row);
commentField(card, item, item.valuesLabel || "Anything you were asked to write down");
}
function buildMenu(card, item, staged) {
const list = el("ul", "options");
const name = "menu-" + item.id;
for (const [i, o] of (item.options || []).entries()) {
const picked = staged && staged.k === o.k;
const li = el("li", "option" + (picked ? " is-picked" : ""));
const label = el("label");
label.style.display = "contents";
const radio = el("input");
radio.type = "radio";
radio.name = name;
// The same id buildChoice gives its radios: withFocus finds the focused
// input by id after the render this change() sets off, and without one a
// keyboard user arrowing through the menu lands on every time.
radio.id = optionId(item, o, i);
radio.value = o.k;
radio.checked = Boolean(picked);
radio.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
const body = el("div", "option-body");
const head = el("div", "option-label");
head.appendChild(el("span", null, o.text));
if (o.recommended) head.appendChild(el("span", "pill suggested", "Suggested"));
body.appendChild(head);
if (o.detail) body.appendChild(el("p", "option-detail", o.detail));
label.appendChild(radio);
label.appendChild(body);
li.appendChild(label);
list.appendChild(li);
}
card.appendChild(list);
if (item.command) {
const note = el("div", "card-note");
note.appendChild(el("p", "help", "To pick this up in a fresh session, run:"));
note.appendChild(md("```\n" + handoffText({ command: item.command }) + "\n```", "md"));
card.appendChild(note);
}
}
function buildList(card, item, staged) {
// Reorder, rename, remove. The agent proposed a breakdown; this is where a
// person who knows the work fixes it before it becomes the plan.
//
// Every handler re-reads the rows at the moment it fires rather than closing
// over the array from render time. A reorder replaces that array, so a stale
// closure would quietly undo the reorder the next time a rename committed.
// A name still being typed counts too: the tool buttons below keep the
// field's focus (their mousedown is cancelled), so its `change` has not
// fired yet when they act, and the re-render would otherwise drop it.
const ul = el("ul", "rows");
const baseRows = () => {
const cur = local.staged[item.id];
return (cur && cur.rows) || (item.rows || []).map((r) => ({ ...r }));
};
const liveRows = () =>
baseRows().map((r) => {
const input = ul.querySelector(`input.row-title[data-row="${CSS.escape(String(r.id))}"]`);
const typed = input ? input.value.trim() : null;
return typed != null && typed !== r.title ? { ...r, title: typed } : r;
});
const rows = liveRows();
// The first click on a tool after a rename used to land on a node the
// rename's re-render had already replaced, and do nothing.
const keepFocus = (b) => b.addEventListener("mousedown", (e) => e.preventDefault());
let dragIndex = null;
const commit = (next) => stage(item.id, withNote(item, { type: "answer", kind: "list", rows: next }));
rows.forEach((row, i) => {
const li = el("li", "row-item");
li.draggable = true;
li.addEventListener("dragstart", () => {
dragIndex = i;
li.classList.add("dragging");
});
li.addEventListener("dragend", () => li.classList.remove("dragging"));
li.addEventListener("dragover", (e) => {
e.preventDefault();
li.classList.add("drop-target");
});
li.addEventListener("dragleave", () => li.classList.remove("drop-target"));
li.addEventListener("drop", (e) => {
e.preventDefault();
li.classList.remove("drop-target");
if (dragIndex === null || dragIndex === i) return;
const next = liveRows();
const [moved] = next.splice(dragIndex, 1);
next.splice(i, 0, moved);
commit(next);
});
const handle = el("button", "row-handle", "⠿");
handle.type = "button";
handle.title = "Drag to reorder";
handle.setAttribute("aria-label", `Move “${row.title}”`);
li.appendChild(handle);
li.appendChild(el("span", "row-order", String(i + 1)));
const main = el("div", "row-main");
// A real input rather than contenteditable: it is reachable by keyboard and
// by a screen reader, it has a stable id so withFocus() can restore the
// caret across a re-render, and `change` fires only when the value actually
// changed, which stops a rename from re-entering render on every blur.
const title = el("input", "row-title");
title.type = "text";
title.id = `row-${item.id}-${row.id}`;
title.value = row.title || "";
title.setAttribute("aria-label", "Name");
title.dataset.row = String(row.id);
// Staged as it is typed (quietly, no re-render, so the caret stays): a
// Ctrl+Enter, a Send, or an agent post landing mid-word all see the new
// name, where `change` alone only fired on blur and they did not.
title.addEventListener("input", () => {
const next = baseRows();
const at = next.findIndex((r) => r.id === row.id);
if (at === -1) return;
next[at] = { ...next[at], title: title.value.trim() };
const untouched =
next.length === (item.rows || []).length && next.every((r, i) => r.id === item.rows[i].id && r.title === item.rows[i].title);
stageQuiet(item.id, untouched && !local.staged[item.id] ? null : withNote(item, { type: "answer", kind: "list", rows: next }));
renderFooter();
renderStagedMarks();
});
title.addEventListener("change", () => {
const next = baseRows();
const at = next.findIndex((r) => r.id === row.id);
if (at === -1) return;
const value = title.value.trim();
if (value === next[at].title) return;
next[at] = { ...next[at], title: value };
commit(next);
});
main.appendChild(title);
if (row.body) main.appendChild(el("div", "row-body", row.body));
li.appendChild(main);
const tools = el("div", "row-tools");
const up = el("button", "btn ghost small", "↑");
up.type = "button";
up.title = "Move up";
up.disabled = i === 0;
up.addEventListener("click", () => {
const next = liveRows();
const at = next.findIndex((r) => r.id === row.id);
if (at <= 0) return;
[next[at - 1], next[at]] = [next[at], next[at - 1]];
commit(next);
});
const down = el("button", "btn ghost small", "↓");
down.type = "button";
down.title = "Move down";
down.disabled = i === rows.length - 1;
down.addEventListener("click", () => {
const next = liveRows();
const at = next.findIndex((r) => r.id === row.id);
if (at === -1 || at === next.length - 1) return;
[next[at + 1], next[at]] = [next[at], next[at + 1]];
commit(next);
});
const del = el("button", "btn ghost small", "×");
del.type = "button";
del.title = "Remove";
del.setAttribute("aria-label", `Remove “${row.title}”`);
del.addEventListener("click", () => commit(liveRows().filter((r) => r.id !== row.id)));
up.setAttribute("aria-label", `Move “${row.title}” up`);
down.setAttribute("aria-label", `Move “${row.title}” down`);
for (const b of [up, down, del]) keepFocus(b);
tools.appendChild(up);
tools.appendChild(down);
tools.appendChild(del);
li.appendChild(tools);
ul.appendChild(li);
});
card.appendChild(ul);
const row = el("div", "btn-row");
const add = el("button", "btn small", "Add one");
add.type = "button";
keepFocus(add);
add.addEventListener("click", () =>
commit([...liveRows(), { id: "new-" + Date.now(), title: "New item", body: "" }])
);
row.appendChild(add);
if (staged) {
const reset = el("button", "linky", "Put it back how it was");
reset.type = "button";
// Puts the rows back; a note typed below stays.
reset.addEventListener("click", () => stage(item.id, withNote(item, null)));
row.appendChild(reset);
}
card.appendChild(row);
card.appendChild(el("p", "help", "Drag to reorder, click a name to rename it."));
commentField(card, item, "Anything else about this breakdown?", false, "no changes");
}
function commentField(card, item, labelText, required, quickText) {
const wrap = el("div", "field");
const id = "note-" + item.id;
const label = el("label", null, labelText);
label.htmlFor = id;
wrap.appendChild(label);
let quick = null;
if (quickText) {
quick = el("button", "btn tiny", quickText.charAt(0).toUpperCase() + quickText.slice(1));
quick.type = "button";
quick.title = "Fill in \"" + quickText + "\"";
wrap.appendChild(quick);
}
const ta = el("textarea");
ta.id = id;
ta.placeholder = required ? "Tell Plan2Code what to change." : "Optional.";
ta.value = (local.staged[item.id] && local.staged[item.id].text) || local.drafts[id] || "";
attachMentions(ta);
ta.addEventListener("input", () => {
setDraft(id, ta.value);
const cur = local.staged[item.id];
if (cur) {
const next = { ...cur, text: ta.value.trim() || undefined };
// Emptying the box of a note-only answer leaves nothing to send, so it
// unstages rather than counting as ready.
const empty = (v) => v == null || v === "" || (Array.isArray(v) && !v.length);
const bare = Object.keys(next).every((k) => k === "type" || k === "kind" || empty(next[k]));
stageQuiet(item.id, bare ? null : next);
} else if (ta.value.trim())
stageQuiet(item.id, { type: "answer", kind: item.kind, text: ta.value.trim() });
stagedChanged();
});
wrap.appendChild(ta);
if (quick)
quick.addEventListener("click", () => {
ta.value = quickText;
ta.dispatchEvent(new Event("input", { bubbles: true }));
ta.focus();
});
card.appendChild(wrap);
}
// Every builder above may assume its question is OPEN and has no answer in
// flight. renderCard is the only caller and routes the other two states to
// renderSettled and renderInFlight, which draw a record rather than a form.
// The builders used to carry their own half of that job, in `!isOpen` branches
// that no longer run; keeping them would have meant two renderings of a settled
// answer, one of them untested and wrong.
const BUILDERS = {
choice: buildChoice,
multi: buildMulti,
text: buildText,
confirm: buildConfirm,
recap: buildRecap,
review: buildReview,
checklist: buildChecklist,
menu: buildMenu,
list: buildList,
};
/* ----------------------------------------------------------------- doc */
function renderDoc(main, id) {
const doc = docs().find((d) => d.id === id);
if (!doc) {
main.appendChild(el("p", "doc-empty", "That document is not ready yet."));
return;
}
const head = el("div", "doc-head");
head.appendChild(el("h2", null, doc.title || "Document"));
head.appendChild(el("span", "doc-version", "v" + (doc.version || 1)));
if (doc.stale) {
head.appendChild(el("span", "pill staged", "Out of date"));
}
const tools = el("div", "doc-tools");
// A brief is handed to people who were not in the room, so it gets a copy
// that opens in any browser, formatting and all.
if (doc.id === "brief") {
const html = el("button", "btn small", "Save as HTML");
html.type = "button";
html.addEventListener("click", () => downloadDocHtml(doc));
tools.appendChild(html);
}
tools.appendChild(printButton());
if (doc.saved) {
tools.appendChild(docSavedNote(doc));
} else {
const save = el("button", "btn small", "Download");
save.type = "button";
save.addEventListener("click", () => downloadDoc(doc));
tools.appendChild(save);
}
head.appendChild(tools);
main.appendChild(head);
if (doc.note) main.appendChild(el("p", "help", doc.note));
const blocks = doc.blocks || [];
if (!blocks.length) {
main.appendChild(el("p", "doc-empty", "Nothing written yet. It fills in as you answer."));
return;
}
// The block nearest the top of the column is the section + Add context
// offers after leaving this tab. Its label is its first heading.
docObserver?.disconnect();
if (docInView && docInView.docId !== doc.id) docInView = null;
const boxes = [];
const topmost = () => {
const top = main.getBoundingClientRect().top;
const box = boxes.find((x) => x.getBoundingClientRect().bottom > top + 1);
if (!box) return;
const heading = box.querySelector("h1, h2, h3, h4, h5, h6");
docInView = {
docId: doc.id,
blockId: box.dataset.block,
label: (heading && heading.textContent.trim()) || doc.title || "Document",
};
};
docObserver = typeof IntersectionObserver === "function" ? new IntersectionObserver(topmost, { root: main, threshold: [0, 0.25, 0.5, 0.75, 1] }) : null;
blocks.forEach((b, i) => {
const box = el("div", "block " + (b.state || "settled"));
box.dataset.block = b.id || String(i);
boxes.push(box);
docObserver?.observe(box);
if (b.state === "assumed") {
// Borrowed from grill-with-ui and the best idea in it: show plainly which
// parts are still a guess, so nobody mistakes a placeholder for a decision.
box.appendChild(el("span", "block-tag", "Assumed for now, still open"));
}
if (b.state === "draft") box.appendChild(el("span", "block-tag", "Draft"));
box.appendChild(blockBody(b));
main.appendChild(box);
});
}
// A block's content: its markdown, or for an image block (a screenshot the
// agent saved under the session's shots/ folder) a captioned picture.
function blockBody(b) {
if (typeof b.image !== "string") return md(b.md, "md");
const fig = el("figure", "doc-figure");
const img = el("img", "doc-img");
img.src = "/shots/" + b.image.split("/").pop();
// The caption already says it: an alt repeating it is read twice, and shows
// twice in an export whose picture would not load.
img.alt = "";
img.loading = "lazy";
fig.appendChild(img);
if (b.alt) fig.appendChild(el("figcaption", null, b.alt));
return fig;
}
function printButton() {
const print = el("button", "btn small", "Print");
print.type = "button";
// The print stylesheet drops everything that steers the session, so what
// comes out is the document alone. "Save as PDF" in that dialog is also the
// most portable save this page can offer.
print.addEventListener("click", () => window.print());
return print;
}
// The spec's overview.md, read-only and drawn through the same markdown path
// as every doc. No Download: the file is already on disk.
function renderOverview(main) {
const head = el("div", "doc-head");
head.appendChild(el("h2", null, "Overview"));
const tools = el("div", "doc-tools");
tools.appendChild(printButton());
head.appendChild(tools);
main.appendChild(head);
main.appendChild(el("p", "help", `${overview.key}/overview.md · read-only, straight from disk`));
const box = el("div", "block settled");
box.appendChild(md(overview.text, "md"));
main.appendChild(box);
}
// The helpers the agent reported, as it last posted them. Everything here is
// the agent's text, so it goes in as text, never as markup.
function renderSubagents(main) {
const card = el("section", "card sa-card");
card.appendChild(el("h2", null, "Subagents"));
card.appendChild(el("p", "help", CHECKIN_LINE));
const { alone, rows } = helperRows(S.helpers);
if (alone) {
card.appendChild(
el("p", "sa-alone", "Working alone: your agent has no way to start helpers here, so it is doing this skill's work itself.")
);
main.appendChild(card);
return;
}
const list = el("ul", "sa-list");
for (const row of rows) {
const item = el("li", "sa-row");
const head = el("div", "sa-head");
head.appendChild(el("strong", "sa-title", row.title));
const pill = el("span", "pill sa-pill is-" + row.state);
if (row.state === "running") {
const spin = el("span", "spinner tiny");
spin.setAttribute("aria-hidden", "true");
pill.appendChild(spin);
}
pill.appendChild(document.createTextNode(row.stateLabel));
head.appendChild(pill);
item.appendChild(head);
item.appendChild(el("p", "sa-ask", row.ask));
if (row.result) item.appendChild(el("p", "sa-result", row.result));
list.appendChild(item);
}
card.appendChild(list);
main.appendChild(card);
}
/* ---------------------------------------------------------------- ask */
// The frame's chat block, with `offline` worked out now rather than when the
// frame was sent: the agent comes and goes between frames, and /ping keeps
// agentLastSeen current. The frame's own verdict stands when there is no clock.
function askFrame() {
const base = chatFrame || { conversation: 0, messages: [], typed: 0, limit: 10, offline: false };
if (!S || !agentLastSeen) return base;
const offline = chatOffline({
finish: finish(),
agent: S.agent,
agentLastSeenMs: Date.parse(agentLastSeen),
now: Date.now(),
});
return { ...base, offline };
}
function askState() {
const frame = askFrame();
const shown = chatView(frame, { pendingSends: local.chat.pending, agentActivity: activity() });
const pendingSendCount = shown.rows.filter((r) => r.pending && !r.failed).length;
return { frame, view: shown, send: chatSendState({ frameChat: frame, gone, pendingSendCount }) };
}
// The conversation a send belongs to. The page's own record wins over the
// frame for the moment after a 409 stale, before the new frame lands.
const askConversation = () => local.chat.conversation ?? askFrame().conversation;
// An upload's server path is `/uploads/.`; the page serves
// it at /uploads/..
const uploadUrl = (img) => img.url || "/uploads/" + String(img.path || "").split(/[\\/]/).pop();
function renderAsk(main) {
const { frame, view: v, send: ss } = askState();
// Anything drawn here has been seen: no dot for it later.
const newest = newestReplyId(frame);
if (newest && local.chat.lastSeenReplyId !== newest) {
local.chat.lastSeenReplyId = newest;
save();
}
chatDot = false;
askPaintedOffline = ss.state === "offline";
const pane = el("section", "ask-pane");
const head = el("div", "ask-head");
head.appendChild(el("h2", null, "Quick question"));
head.appendChild(el("span", "ask-counter", v.counterText));
const reset = el("button", "btn small ghost", "New conversation");
reset.type = "button";
reset.disabled = ss.state === "offline" || chatResetting;
reset.addEventListener("click", newConversation);
head.appendChild(reset);
pane.appendChild(head);
const list = el("div", "ask-list");
list.setAttribute("role", "log");
list.setAttribute("aria-live", "polite");
if (!v.rows.length) list.appendChild(askStarters(ss));
const notes = new Map(v.rows.filter((r) => r.kind === "decision").map((r) => [r.re, r.text]));
for (const r of v.rows) list.appendChild(askRow(r, ss, notes));
pane.appendChild(list);
pane.appendChild(askComposer(ss));
main.appendChild(pane);
// Back where the person left the list, unless something new arrived (or it
// is the first look), which brings the newest row into view.
const saved = scrollMemory.get("ask");
const grew = v.rows.length > askRowCount;
askRowCount = v.rows.length;
list.scrollTop = !saved || grew ? list.scrollHeight : saved.top;
}
// An empty conversation offers a few questions for this step, the role's
// first. A click only fills the box: nothing is ever sent for the person.
function askStarters(ss) {
const box = el("div", "ask-starters");
box.appendChild(el("p", "ask-starters-lead", "Not sure what to ask? Try one of these:"));
for (const starter of startersFor(S.workflow, looks.role, { hasContext: Boolean(local.chat.about) })) {
const b = el("button", "ask-starter", starter.text);
b.type = "button";
b.disabled = !ss.canType;
b.addEventListener("click", () => {
local.chat.draft = starter.text;
save();
render();
const ta = $("ask-input");
if (!ta) return;
ta.focus();
ta.setSelectionRange(ta.value.length, ta.value.length);
});
box.appendChild(b);
}
return box;
}
function askRow(r, ss, notes) {
if (r.kind === "decision") {
const row = el("div", "ask-row decision");
row.appendChild(el("p", "ask-decision", r.decision !== "approve" ? "You declined the edit." : r.done ? "You approved the edit." : "You approved the edit, please wait..."));
if (r.text) row.appendChild(el("p", "ask-text", r.text));
return row;
}
if (r.kind === "agent") {
const row = el("div", "ask-row agent");
row.appendChild(el("div", "msg-who", "Plan2Code"));
row.appendChild(md(r.md, "md"));
if (r.proposal) row.appendChild(askProposal(r, ss, notes.get(r.id)));
if (Array.isArray(r.changed) && r.changed.length) {
const ul = el("ul", "ask-changed");
for (const c of r.changed) {
const li = el("li");
li.appendChild(el("code", null, c.file));
li.appendChild(el("span", "ask-changed-count", ` +${c.added} −${c.removed}`));
ul.appendChild(li);
}
row.appendChild(ul);
}
return row;
}
const row = el("div", "ask-row person" + (r.pending ? " pending" : ""));
if (r.about && r.about.label) row.appendChild(el("p", "ask-about", "About: " + r.about.label));
row.appendChild(el("p", "ask-text", r.text));
const hasImages = r.images && r.images.length;
const hasFiles = r.files && r.files.length;
if (hasImages || hasFiles) {
const tray = el("div", "attach-tray");
for (const img of r.images || []) {
const fig = el("figure", "attach-thumb is-ready");
const pic = el("img");
pic.src = thumbs.get(img.key) || uploadUrl(img);
pic.alt = img.name || "image";
fig.appendChild(pic);
tray.appendChild(fig);
}
for (const file of r.files || []) tray.appendChild(docChip(file, "ready"));
row.appendChild(tray);
}
if (r.pending && r.failed) {
const fail = el("p", "ask-waiting ask-failed", "Not sent — retry");
const retry = el("button", "btn tiny", "Retry");
retry.type = "button";
retry.disabled = ss.state === "offline" || chatSending;
retry.addEventListener("click", () => retryChat(r.tempId));
fail.appendChild(retry);
row.appendChild(fail);
} else if (r.pending) {
row.appendChild(el("p", "ask-waiting", "Sending…"));
} else if (r.waiting) {
const wait = el("p", "ask-waiting");
// Picked up and still answering: the ring says so, unless the agent has
// gone quiet, when a turning ring would pass a dead session for a slow one.
if (r.working && ss.state !== "offline" && !agentAdrift()) {
const spin = el("span", "spinner tiny");
spin.setAttribute("aria-hidden", "true");
wait.appendChild(spin);
}
wait.appendChild(el("span", null, r.waitingText));
row.appendChild(wait);
if (r.activity) row.appendChild(el("p", "ask-waiting", "Right now: " + r.activity));
}
return row;
}
function askProposal(r, ss, note) {
const box = el("div", "ask-proposal");
box.appendChild(el("p", "note-kicker", "Proposed change"));
box.appendChild(md(r.proposal.summary, "md"));
const files = el("ul", "ask-proposal-files");
for (const f of r.proposal.files || []) {
const li = el("li");
li.appendChild(el("code", null, f));
files.appendChild(li);
}
box.appendChild(files);
if (r.decided) {
box.appendChild(el("p", "ask-decided " + r.decided, r.decided === "approve" ? "Approved" : "Declined"));
if (note) box.appendChild(el("p", "help", note));
return box;
}
const busy = deciding.has(r.id) || ss.state === "offline";
const row = el("div", "ask-proposal-actions");
const approve = el("button", "btn small primary", "Approve");
approve.type = "button";
approve.disabled = busy;
approve.addEventListener("click", () => decideChat(r.id, "approve", ""));
row.appendChild(approve);
if (!declineOpen.has(r.id)) {
const decline = el("button", "btn small ghost", "Decline");
decline.type = "button";
decline.disabled = busy;
decline.addEventListener("click", () => {
declineOpen.set(r.id, "");
render();
$("decline-" + r.id)?.focus();
});
row.appendChild(decline);
} else {
const input = el("input");
input.type = "text";
input.id = "decline-" + r.id;
input.placeholder = "Why not? (optional)";
input.maxLength = CHAT_MAX_CHARS;
input.value = declineOpen.get(r.id) || "";
input.addEventListener("input", () => declineOpen.set(r.id, input.value));
input.addEventListener("keydown", (e) => {
if (e.key !== "Enter") return;
e.preventDefault();
e.stopPropagation();
decideChat(r.id, "decline", input.value);
});
row.appendChild(input);
const go = el("button", "btn small", "Send decline");
go.type = "button";
go.disabled = busy;
go.addEventListener("click", () => decideChat(r.id, "decline", declineOpen.get(r.id) || ""));
row.appendChild(go);
}
box.appendChild(row);
if (deciding.has(r.id)) box.appendChild(el("p", "help", "Sent. It will show here once Plan2Code has it."));
return box;
}
const COUNTER_FROM = 3500;
function askComposer(ss) {
const comp = el("div", "ask-composer");
const about = local.chat.about;
if (about) {
const chip = el("div", "ask-about-chip");
chip.appendChild(el("span", null, "About: " + about.label));
const x = el("button", "attach-remove", "×");
x.type = "button";
x.setAttribute("aria-label", "Send without this");
x.addEventListener("click", () => {
Object.assign(local.chat, nextAbout(local.chat, { type: "drop" }));
save();
render();
});
chip.appendChild(x);
comp.appendChild(chip);
}
if (local.chat.images.length) comp.appendChild(attachTray(CHAT_IMAGES, local.chat.images));
const ta = el("textarea");
ta.id = "ask-input";
ta.placeholder = "Ask anything about this project";
ta.value = local.chat.draft || "";
ta.disabled = !ss.canType;
ta.setAttribute("aria-label", "Your question");
attachMentions(ta);
comp.appendChild(ta);
const row = el("div", "ask-actions");
const add = el("button", "btn small ghost", "+ Attach file");
add.type = "button";
add.setAttribute("aria-label", "Add files to this question");
add.disabled = !ss.canType || local.chat.images.length >= CHAT_MAX_ATTACHMENTS;
const picker = el("input");
picker.type = "file";
picker.accept = pickerAccept();
picker.multiple = true;
picker.hidden = true;
add.addEventListener("click", () => picker.click());
picker.addEventListener("change", () => {
attachFiles(CHAT_IMAGES, picker.files);
picker.value = "";
});
row.appendChild(add);
row.appendChild(picker);
if (!local.chat.about) row.appendChild(addContext(ss));
// Where the counter sits, the reason Send is off when it cannot be typed in:
// the limit, the last question still waiting, or nobody there to answer.
const counter = el("span", "ask-count");
if (!ss.canType) {
const cls = ss.state === "offline" ? "is-offline" : ss.state === "limit" ? "is-limit" : "is-waiting";
row.appendChild(el("p", "ask-disabled-note " + cls, ss.text));
} else {
row.appendChild(counter);
const hint = el("span", "ask-send-hint");
hint.appendChild(el("kbd", null, isMac() ? "⌘" : "Ctrl"));
hint.appendChild(document.createTextNode(" + "));
hint.appendChild(el("kbd", null, "Enter"));
row.appendChild(hint);
}
const go = el("button", "btn small primary", "Send");
go.type = "button";
row.appendChild(go);
comp.appendChild(row);
if (chatError) comp.appendChild(el("p", "ask-error", chatError));
const held = () => local.chat.images.some((img) => img.status !== "ready");
const sync = () => {
const len = ta.value.length;
counter.textContent = len >= COUNTER_FROM ? `${len} / ${CHAT_MAX_CHARS}` : "";
counter.classList.toggle("is-over", len > CHAT_MAX_CHARS);
go.disabled = !ss.canType || chatSending || !ta.value.trim() || len > CHAT_MAX_CHARS || held();
};
sync();
ta.addEventListener("input", () => {
local.chat.draft = ta.value;
save();
sync();
});
// Ctrl/Cmd+Enter sends and a plain Enter is a line break. Every Enter stops
// here, so the page-wide Ctrl+Enter never sends the question cards from this box.
ta.addEventListener("keydown", (e) => {
if (e.key !== "Enter") return;
e.stopPropagation();
if (!(e.ctrlKey || e.metaKey) || e.isComposing) return;
e.preventDefault();
if (!go.disabled) sendChat();
});
ta.addEventListener("paste", (e) => {
const files = incomingFiles(e.clipboardData && e.clipboardData.files);
if (!files.length || !ss.canType) return;
if (!e.clipboardData.getData("text/plain")) e.preventDefault();
attachFiles(CHAT_IMAGES, files);
});
const canDrop = (e) => ss.canType && e.dataTransfer && [...e.dataTransfer.types].includes("Files");
const onOver = (e) => {
if (!canDrop(e)) return;
e.preventDefault();
comp.classList.add("is-dropping");
};
comp.addEventListener("dragenter", onOver);
comp.addEventListener("dragover", onOver);
comp.addEventListener("dragleave", (e) => {
if (!comp.contains(e.relatedTarget)) comp.classList.remove("is-dropping");
});
comp.addEventListener("drop", (e) => {
comp.classList.remove("is-dropping");
if (!canDrop(e)) return;
e.preventDefault();
attachFiles(CHAT_IMAGES, e.dataTransfer.files);
});
go.addEventListener("click", sendChat);
return comp;
}
const CONTEXT_KIND = { card: "Question", section: "Section", spec: "Spec" };
// + Add context: the only way a message gets an `about`. A menu of the last
// three places visited, then This spec, built fresh on every render.
function addContext(ss) {
const wrap = el("span", "ask-context");
const spec = isDashboard() ? selSpec() : S && S.specDir ? { dir: S.specDir } : null;
const options = contextOptions(local.chat, spec);
const btn = el("button", "btn small ghost", "+ Add context");
btn.type = "button";
btn.setAttribute("aria-haspopup", "menu");
btn.setAttribute("aria-expanded", "false");
btn.disabled = !ss.canType || !options.length;
if (!options.length) btn.title = "Visit a question or a document section first";
wrap.appendChild(btn);
let menu = null;
const outside = (e) => {
if (!wrap.contains(e.target)) close();
};
// Focus moves before the menu goes: removing the focused item fires a
// focusout of its own, which would otherwise re-enter here.
const close = (refocus) => {
if (!menu) return;
const gone = menu;
menu = null;
btn.setAttribute("aria-expanded", "false");
document.removeEventListener("pointerdown", outside, true);
if (refocus) btn.focus();
gone.remove();
};
const open = () => {
menu = el("div", "ask-context-menu");
menu.setAttribute("role", "menu");
menu.setAttribute("aria-label", "Add context");
for (const option of options) {
const item = el("button", "ask-context-item");
item.type = "button";
item.setAttribute("role", "menuitem");
item.appendChild(el("span", "ask-context-label", option.label));
item.appendChild(el("span", "ask-context-kind", CONTEXT_KIND[option.kind] || ""));
item.addEventListener("click", () => {
close();
Object.assign(local.chat, nextAbout(local.chat, { type: "pick", about: option }));
save();
render();
});
menu.appendChild(item);
}
// A press inside the menu never moves focus. Safari (and Firefox on
// macOS) do not focus a clicked button, so the press would blur the
// focused item to nowhere and the focusout below would close the menu
// before the click landed.
menu.addEventListener("mousedown", (e) => e.preventDefault());
menu.addEventListener("keydown", (e) => {
const items = [...menu.querySelectorAll('[role="menuitem"]')];
const at = items.indexOf(document.activeElement);
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
close(true);
} else if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
const step = e.key === "ArrowDown" ? 1 : -1;
items[(at + step + items.length) % items.length].focus();
} else if (e.key === "Home" || e.key === "End") {
e.preventDefault();
items[e.key === "Home" ? 0 : items.length - 1].focus();
}
});
wrap.appendChild(menu);
btn.setAttribute("aria-expanded", "true");
document.addEventListener("pointerdown", outside, true);
menu.querySelector('[role="menuitem"]').focus();
};
btn.addEventListener("click", () => (menu ? close() : open()));
wrap.addEventListener("focusout", (e) => {
if (menu && !wrap.contains(e.relatedTarget)) close();
});
return wrap;
}
const CHAT_ERRORS = {
stale: "A new conversation started. Your message is still here — press Send again.",
"too-long": `That message is over ${CHAT_MAX_CHARS.toLocaleString()} characters. Shorten it and send again.`,
image: "One of the images could not be attached. Remove it and try again.",
file: "One of the files could not be attached. Remove it and try again.",
};
async function sendChat() {
const text = (local.chat.draft || "").trim();
const { send: ss } = askState();
if (!text || chatSending || !ss.canType || text.length > CHAT_MAX_CHARS) return;
if (local.chat.images.some((img) => img.status !== "ready")) return;
const ofKind = (kind) => local.chat.images.filter((a) => attachmentKind(a) === kind);
const pend = {
tempId: crypto.randomUUID(),
text,
about: local.chat.about,
images: ofKind("image").map(({ key, path, name, url }) => ({ key, path, name, url })),
files: ofKind("file").map(({ key, path, name, size }) => ({ key, path, name, size })),
};
local.chat.pending.push(pend);
save();
await postChat(pend);
}
function retryChat(tempId) {
const pend = local.chat.pending.find((p) => p.tempId === tempId);
if (!pend || chatSending) return;
pend.failed = false;
save();
postChat(pend);
}
async function postChat(pend) {
chatSending = true;
chatError = "";
render();
let res = null;
let body = {};
try {
res = await fetch("/chat", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
text: pend.text,
about: pend.about || undefined,
images: pend.images.length ? pend.images.map(({ path, name }) => ({ path, name })) : undefined,
files: pend.files && pend.files.length ? pend.files.map(({ path, name }) => ({ path, name })) : undefined,
conversation: askConversation(),
}),
});
body = await res.json().catch(() => ({}));
} catch {
res = null;
}
chatSending = false;
const still = local.chat.pending.find((p) => p.tempId === pend.tempId);
if (!res) {
if (still) still.failed = true;
} else if (res.ok) {
if (still) still.seq = body.seq;
// What was sent leaves the composer, and the context leaves with it: a
// follow-up is a general question unless it is picked again.
Object.assign(local.chat, nextAbout(local.chat, { type: "sent" }));
if ((local.chat.draft || "").trim() === pend.text) {
local.chat.draft = "";
local.chat.images = [];
}
} else {
local.chat.pending = local.chat.pending.filter((p) => p.tempId !== pend.tempId);
if (body.error === "stale" && typeof body.conversation === "number") local.chat.conversation = body.conversation;
// A limit or offline refusal needs no words: the disabled composer says why.
if (body.error !== "limit" && body.error !== "offline") {
chatError = CHAT_ERRORS[body.error] || "That message could not be sent. Try again.";
}
}
save();
render();
}
async function newConversation() {
// One reset at a time: a second press would only come back stale and put
// an error under the clean conversation the first one opened.
if (chatResetting) return;
chatResetting = true;
render();
let res = null;
let body = {};
try {
res = await fetch("/chat", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ reset: true, conversation: askConversation() }),
});
body = await res.json().catch(() => ({}));
} catch {}
if (res && res.ok) {
// An explicit fresh start: the unsent draft and its pictures go too.
for (const img of local.chat.images) if (img.id) fetch(deleteUrl(img), { method: "DELETE" }).catch(() => {});
local.chat = { ...freshChat(), history: local.chat.history, about: null, conversation: body.conversation };
chatError = "";
askRowCount = 0;
declineOpen.clear();
} else if (body.error === "stale" && typeof body.conversation === "number") {
local.chat.conversation = body.conversation;
chatError = "A new conversation had already started.";
} else if (body.error !== "offline") {
chatError = "A new conversation could not be started. Try again.";
}
chatResetting = false;
save();
render();
}
async function decideChat(re, decision, text) {
if (deciding.has(re)) return;
deciding.add(re);
chatError = "";
render();
let ok = false;
let body = {};
try {
const res = await fetch("/chat/decision", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ re, decision, text: text.trim() || undefined, conversation: askConversation() }),
});
ok = res.ok;
body = await res.json().catch(() => ({}));
} catch {}
// Kept in `deciding` on success: the buttons stay off until the frame
// brings the decision back, rather than flashing live again in between.
if (ok) declineOpen.delete(re);
else {
deciding.delete(re);
chatError =
body.error === "stale"
? "That proposal belongs to an earlier conversation."
: "That decision could not be sent. Try again.";
}
render();
}
/* --------------------------------------------------------------- aside */
function renderAside() {
const aside = $("aside");
// Redrawing empties the panel, which drops its scroll to the top. An image
// upload redraws two or three times while the person watches its tray, so
// the place is kept while the same question stays on screen.
const place = aside.dataset.item === String(selected) ? aside.scrollTop : 0;
aside.replaceChildren();
aside.dataset.item = String(selected);
// The end page is about the session, not any one question: the notes that
// belong to a question stay on its own page.
const item = view === "end" ? null : byId(selected);
if (!item) {
// The menu has no questions, so no notes either: the pane stays empty.
if (!isDashboard()) aside.appendChild(el("p", "aside-empty", "Pick a question to see its notes."));
return;
}
// Off the question's own page (a doc tab, Ask) "this" points at nothing on
// screen, so the pane names the question a note here will go to.
const onQuestion = view === "questions" || view === "end";
aside.appendChild(el("h2", null, onQuestion ? "Notes on this" : `Notes on “${item.title || "this question"}”`));
const thread = item.thread || [];
if (!thread.length && !(isOpen(item) && !finish() && noteAwaiting(item))) {
aside.appendChild(
el(
"p",
"aside-empty",
isOpen(item) && !finish()
? "No back and forth yet. Anything you type here goes with your next send."
: "Nothing was said about this one."
)
);
}
// A note that has been sent but not yet picked up: marked as waiting, so the
// send is seen to have gone, until the agent replies. The server writes the
// note into the thread as it arrives; a session from before that has only
// `sentNote`, which gets a box of its own below.
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
let waitingShown = false;
for (const m of thread) {
const mine = threadWho(m) === "user";
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
if (pending) waitingShown = true;
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
const who = el("div", "msg-who");
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
box.appendChild(who);
const text = threadText(m);
if (text) box.appendChild(md(text, "md"));
const tray = mine ? sentAttachments(m) : null;
if (tray) box.appendChild(tray);
aside.appendChild(box);
}
if (waiting && !waitingShown) {
const box = el("div", "msg you pending");
const who = el("div", "msg-who");
who.appendChild(el("span", null, "You"));
who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
box.appendChild(who);
if (waiting.text) box.appendChild(md(waiting.text, "md"));
const tray = sentAttachments(waiting);
if (tray) box.appendChild(tray);
aside.appendChild(box);
}
// A finished session has nobody left for a note to reach, so the box would
// be a place to type words that go nowhere.
if (!isOpen(item) || finish()) {
aside.scrollTop = place;
return;
}
const wrap = el("div", "field");
const id = "thread-" + item.id;
const label = el("label", null, "Add a note, attach a file, or ask something");
label.htmlFor = id;
wrap.appendChild(label);
const attached = noteImages(item.id);
wrap.appendChild(attachRow(item.id, "Add files to this note"));
if (attached.length) wrap.appendChild(attachTray(item.id, attached));
const ta = el("textarea");
ta.id = id;
ta.placeholder = "Goes with your next send. It does not answer the question.";
ta.value = local.drafts[id] || "";
attachMentions(ta);
ta.addEventListener("input", () => {
setDraft(id, ta.value);
renderFooter();
});
ta.addEventListener("paste", (e) => {
const files = incomingFiles(e.clipboardData && e.clipboardData.files);
if (!files.length) return;
// A copy from some apps carries the picture and its text together; the
// text still pastes as it always did.
if (!e.clipboardData.getData("text/plain")) e.preventDefault();
attachFiles(item.id, files);
});
wrap.appendChild(ta);
aside.appendChild(wrap);
aside.scrollTop = place;
}
const SVG_NS = "http://www.w3.org/2000/svg";
// A page with its corner folded, drawn inline: the CSP allows no icon font.
function pageIcon() {
const svg = document.createElementNS(SVG_NS, "svg");
svg.setAttribute("class", "attach-chip-icon");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("width", "24");
svg.setAttribute("height", "24");
svg.setAttribute("aria-hidden", "true");
for (const d of ["M6 2.5h8.5L19 7v14.5H6z", "M14.5 2.5V7H19"]) {
const path = document.createElementNS(SVG_NS, "path");
path.setAttribute("d", d);
svg.appendChild(path);
}
return svg;
}
// A document in a tray: never an
, since a document is not a picture.
// Icon, extension badge, name and size; a sent one is wrapped in a link.
function docChip(entry, status) {
const ext = docExt(entry.name) || "";
const fig = el("figure", `attach-thumb attach-chip is-${status}`);
const size = typeof entry.size === "number" ? formatBytes(entry.size) : "";
const label = DOC_TYPES[ext] ? DOC_TYPES[ext].label : "";
fig.setAttribute("aria-label", [entry.name, label, size].filter(Boolean).join(", "));
fig.appendChild(pageIcon());
const text = el("div", "attach-chip-text");
if (ext) text.appendChild(el("span", "attach-chip-badge", ext.toUpperCase()));
text.appendChild(el("span", "attach-chip-name", entry.name));
if (size) text.appendChild(el("span", "attach-chip-size", size));
fig.appendChild(text);
return fig;
}
// The + Attach file control and its hidden picker, for a note's box or a
// card's own. Files go to the item's note attachments either way.
function attachRow(itemId, ariaLabel) {
const row = el("div", "attach-row");
const btn = el("button", "btn small ghost", "+ Attach file");
btn.type = "button";
btn.setAttribute("aria-label", ariaLabel);
btn.disabled = noteImages(itemId).length >= MAX_ATTACHMENTS;
const picker = el("input");
picker.type = "file";
picker.accept = pickerAccept();
picker.multiple = true;
picker.hidden = true;
btn.addEventListener("click", () => picker.click());
picker.addEventListener("change", () => {
attachFiles(itemId, picker.files);
picker.value = "";
});
row.appendChild(btn);
row.appendChild(picker);
return row;
}
function attachTray(itemId, attached) {
const tray = el("div", "attach-tray");
for (const img of attached) {
let fig;
if (attachmentKind(img) === "file") fig = docChip(img, img.status);
else {
fig = el("figure", "attach-thumb is-" + img.status);
const src = thumbs.get(img.key) || img.url;
if (src) {
const pic = el("img");
pic.src = src;
pic.alt = img.name;
fig.appendChild(pic);
}
}
const rm = el("button", "attach-remove", "×");
rm.type = "button";
rm.setAttribute("aria-label", `Remove ${img.name}`);
rm.addEventListener("click", () => removeImage(itemId, img.key));
fig.appendChild(rm);
if (img.status === "uploading") {
const over = el("div", "attach-overlay");
over.appendChild(el("span", "spinner tiny"));
fig.appendChild(over);
} else if (img.status === "failed") {
const over = el("div", "attach-overlay failed");
over.appendChild(el("span", null, "Upload failed"));
const retry = el("button", "btn tiny", "Retry");
retry.type = "button";
retry.addEventListener("click", () => retryImage(itemId, img.key));
const drop = el("button", "btn tiny", "Remove");
drop.type = "button";
drop.addEventListener("click", () => removeImage(itemId, img.key));
over.appendChild(retry);
over.appendChild(drop);
fig.appendChild(over);
}
tray.appendChild(fig);
}
return tray;
}
/* --------------------------------------------------------- attachments */
const MAX_UPLOAD_BYTES = 4 * 1024 * 1024;
// Three ways in, because browsers disagree: EXIF-aware bitmap decode, plain
// bitmap decode, then an
fed a data: URL. Not an object URL: the CSP
// allows `data:` images and refuses `blob:` ones.
async function decodeImage(file) {
try {
return await createImageBitmap(file, { imageOrientation: "from-image" });
} catch {}
try {
return await createImageBitmap(file);
} catch {}
try {
const url = await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
return await new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = url;
});
} catch {
throw new Error("That file could not be read as an image.");
}
}
function drawScaled(source, edge) {
const w0 = source.naturalWidth || source.width;
const h0 = source.naturalHeight || source.height;
const { w, h } = fitWithin(w0, h0, edge);
const canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext("2d");
// JPEG has no alpha: a transparent PNG would otherwise turn black.
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, w, h);
ctx.drawImage(source, 0, 0, w, h);
return canvas;
}
// The upload (a JPEG no longer than IMAGE_LONG_EDGE) and the tray's thumbnail
// (a small data: URL), from one decode.
async function reencode(file) {
const source = await decodeImage(file);
try {
const blob = await new Promise((resolve, reject) =>
drawScaled(source, IMAGE_LONG_EDGE).toBlob(
(b) => (b ? resolve(b) : reject(new Error("That image could not be converted."))),
"image/jpeg",
IMAGE_QUALITY
)
);
if (blob.size > MAX_UPLOAD_BYTES) throw new Error("That image is too large even after shrinking it.");
const thumb = drawScaled(source, THUMB_EDGE).toDataURL("image/jpeg", 0.7);
return { blob, thumb };
} finally {
if (typeof source.close === "function") source.close();
}
}
// Thumbnails and retry blobs, keyed by an attachment's local `key`. Kept out
// of `local`: both are large, and neither survives a reload anyway.
const thumbs = new Map();
const retryBlobs = new Map();
// A note's pictures, or the chat composer's (CHAT_IMAGES), which live apart.
const noteImages = (itemId) =>
itemId === CHAT_IMAGES ? local.chat.images : (local.images && local.images[itemId]) || [];
const findImage = (itemId, key) => noteImages(itemId).find((img) => img.key === key) || null;
function setNoteImages(itemId, list) {
if (itemId === CHAT_IMAGES) local.chat.images = list;
else if (list.length) local.images[itemId] = list;
else delete local.images[itemId];
}
// Where an attachment is deleted from. Documents have no `url`, so their
// route is built from the path, as uploadUrl does.
const deleteUrl = (entry) => entry.url || "/uploads/" + String(entry.path || "").split(/[\\/]/).pop();
// The files in a paste worth attaching: images and allowed documents. A paste
// with none of them is left to paste as text.
function incomingFiles(list) {
return Array.from(list || []).filter((f) => (f.type && f.type.startsWith("image/")) || docExt(f.name));
}
const notAllowedText = (name) => `"${name}" can't be attached: only images, text, code and PDF files.`;
const tooLargeText = (name) => `"${name}" is over ${formatBytes(MAX_DOC_BYTES)}.`;
async function uploadBlob(itemId, key, blob) {
const img = findImage(itemId, key);
if (!img) return;
const isFile = attachmentKind(img) === "file";
img.status = "uploading";
save();
render();
let body = null;
let status = 0;
try {
const res = await fetch("/upload", {
method: "POST",
headers: {
"content-type": isFile ? "application/octet-stream" : "image/jpeg",
"x-p2c-name": encodeURIComponent(img.name),
},
body: blob,
});
status = res.status;
if (res.ok) body = await res.json();
} catch {}
const now = findImage(itemId, key);
if (!now) {
// Removed while it was on its way: the file it just made belongs to nobody.
if (body && body.ok && body.id) fetch(deleteUrl(body), { method: "DELETE" }).catch(() => {});
return;
}
if (body && body.ok) {
Object.assign(now, { id: body.id, path: body.path, name: body.name, size: body.size, kind: body.kind, status: "ready" });
if (body.url) now.url = body.url;
retryBlobs.delete(key);
} else if (isFile && (status === 415 || status === 413)) {
// The server read the file and said no: Retry would only fail again.
setNoteImages(itemId, noteImages(itemId).filter((x) => x.key !== key));
retryBlobs.delete(key);
banner(status === 413 ? tooLargeText(now.name) : notAllowedText(now.name), "warn");
} else {
now.status = "failed";
retryBlobs.set(key, blob);
}
save();
render();
}
async function attachFiles(itemId, files) {
const given = Array.from(files || []);
const { images, docs, refused } = sortAttachments(given);
const chat = itemId === CHAT_IMAGES;
const room = Math.max(0, (chat ? CHAT_MAX_ATTACHMENTS : MAX_ATTACHMENTS) - noteImages(itemId).length);
const wanted = given.filter((f) => images.includes(f) || docs.includes(f));
const taken = wanted.slice(0, room);
// One banner at a time, so every refusal goes into it, each by name.
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
if (taken.length < wanted.length)
said.push(
chat ? `Up to ${CHAT_MAX_ATTACHMENTS} attachments per question.` : `Up to ${MAX_ATTACHMENTS} attachments per note.`
);
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
await Promise.all(
taken.map(async (file) => {
const key = crypto.randomUUID();
if (docs.includes(file)) {
setNoteImages(itemId, [
...noteImages(itemId),
{ key, kind: "file", name: file.name, size: file.size, status: "uploading" },
]);
save();
render();
await uploadBlob(itemId, key, file);
return;
}
setNoteImages(itemId, [
...noteImages(itemId),
{ key, kind: "image", name: file.name || "pasted-image.png", status: "uploading" },
]);
save();
render();
let encoded;
try {
encoded = await reencode(file);
} catch (err) {
setNoteImages(itemId, noteImages(itemId).filter((img) => img.key !== key));
save();
render();
banner(err.message, "warn");
return;
}
thumbs.set(key, encoded.thumb);
await uploadBlob(itemId, key, encoded.blob);
})
);
}
async function removeImage(itemId, key) {
const img = findImage(itemId, key);
setNoteImages(itemId, noteImages(itemId).filter((x) => x.key !== key));
thumbs.delete(key);
retryBlobs.delete(key);
save();
render();
// Errors are ignored: the 30-day sweep is the backstop.
if (img && img.id) fetch(deleteUrl(img), { method: "DELETE" }).catch(() => {});
}
async function retryImage(itemId, key) {
const blob = retryBlobs.get(key);
if (blob) return uploadBlob(itemId, key, blob);
await removeImage(itemId, key);
banner("Attach it again.", "info");
}
/* -------------------------------------------------------------- footer */
// Every note with something in it — text, attachments, or both — as
// { id, text, images, held }. `held` is a note with an image still uploading
// or failed: it stays drafted, and only it waits.
function draftedNotes() {
const ids = new Set();
for (const [key, text] of Object.entries(local.drafts)) {
if (key.startsWith("thread-") && text && text.trim()) ids.add(key.slice(7));
}
for (const [id, list] of Object.entries(local.images || {})) if (list.length) ids.add(id);
return [...ids].map((id) => {
const imgs = noteImages(id);
return {
id,
text: (local.drafts["thread-" + id] || "").trim(),
images: imgs.filter((img) => img.status === "ready"),
held: imgs.some((img) => img.status === "uploading" || img.status === "failed"),
};
});
}
function pendingNotes() {
return draftedNotes()
.filter((n) => !n.held && (n.text || n.images.length))
.map(({ id, text, images }) => ({ id, text, images }));
}
function heldNotes() {
return draftedNotes().filter((n) => n.held);
}
function sendState() {
// Before `gone`, and before the grace period that can re-enable a send. A
// finished session has nobody left to send to, whatever the socket says.
if (finish())
return finishPaused(finish())
? { disabled: true, why: "This session is paused.", short: "Session paused" }
: { disabled: true, why: "This session is finished.", short: "Session finished" };
if (gone) return { disabled: true, why: "Not connected right now.", short: "Not connected" };
// A send is still being collected. Blocking here is what keeps someone from
// writing over answers nobody has read yet.
if (pendingResult) {
// The server refuses a second submit while one is uncollected, so this
// stays disabled either way. Only the reason changes, and "one moment" is
// a promise the page cannot keep once nothing is coming to collect them.
return stranded()
? { disabled: true, why: "Saved, and waiting for Plan2Code to come back for them.", short: "Saved, not picked up" }
: { disabled: true, why: "Your last answers are on their way. One moment.", short: "" };
}
if (agentWorking()) {
// A question the agent left open while still working is still a question,
// and its answer has nowhere better to wait than the server, which holds
// a send until the agent next looks. The contract says to switch to
// "waiting" before asking, but an agent that asks and carries on ("while
// you decide") must not lock the person out of answering for up to an
// hour of quietMinutes.
if (myTurn().length && (stagedCount() || pendingNotes().length)) {
return {
disabled: false,
why: "Plan2Code is still working. Your answers wait for it to look.",
short: "Still working · it reads this next",
};
}
const ms = workingMs();
if (ms > patience(WORKING_GRACE_MS)) {
// A stuck agent must not lock someone out of their own session, so the
// hatch stays open -- but only once there is something to push through
// it. Enabled with an empty payload, Send clicks as a no-op, and the
// loud styling on a dead button reads as broken rather than available.
// "A while", not the clock: the footer only redraws on events, so a
// duration printed here freezes between them, and a frozen number
// beside "is it stuck?" makes the page look like the thing it is
// warning about. The exact time already ticks away in the dock.
if (stagedCount() || pendingNotes().length) {
return { disabled: false, why: "Plan2Code has been busy a while. You can send anyway.", short: "Busy · send anyway" };
}
return openItems().length
? {
disabled: true,
why: "Plan2Code has been busy a while. Answer something or add a note, and you can send anyway.",
short: "Busy · a note unlocks Send",
}
: { disabled: true, why: "Plan2Code has been busy a while.", short: "Busy a while" };
}
return { disabled: true, why: "Wait for Plan2Code to finish.", short: agentAdrift() ? "Gone quiet" : "" };
}
if (!stagedCount() && !pendingNotes().length) return { disabled: true, why: "" };
return { disabled: false, why: "" };
}
function renderFooter() {
// The dashboard has no Send: a card click is the answer and it goes on its
// own. An empty "Nothing to send yet" bar under a menu is noise, so only the
// workspace label stays.
const foot = document.querySelector(".footer");
if (foot) foot.classList.toggle("is-dash", Boolean(isDashboard() && !finish()));
// A finished dashboard keeps its summary line but still has nothing to send.
if (foot) foot.classList.toggle("is-dash-done", Boolean(isDashboard() && finish()));
const summary = $("footer-summary");
const notes = pendingNotes();
const n = stagedCount();
summary.replaceChildren();
const sent = awaitingReply();
if (!n && !notes.length && sent.length) {
// "Answer a question above" is nonsense when everything answerable has
// already gone. Say what is actually outstanding instead: their own send.
summary.appendChild(el("strong", null, stranded() ? `${sent.length} saved, not picked up yet` : `${sent.length} with Plan2Code`));
summary.appendChild(document.createTextNode(" · " + sent.map((i) => i.title).join(" · ")));
} else if (finish()) {
// Not "nothing to send yet". There is no yet.
const fin = finish();
summary.appendChild(el("strong", null, finishPaused(fin) ? "Paused." : "All done."));
summary.appendChild(
document.createTextNode(
n || notes.length
? " Anything still waiting here was never sent."
: finishPaused(fin)
? " Run the command above to pick this up."
: fin.command
? " The next step is above."
: " Nothing left to run."
)
);
} else if (!n && !notes.length) {
summary.appendChild(
document.createTextNode(
myTurn().length
? "Nothing to send yet. Answer a question above, then press Send."
: "Nothing to send yet."
)
);
} else {
const strong = el("strong", null, `${n + notes.length} ready`);
summary.appendChild(strong);
const bits = [];
for (const [id, v] of Object.entries(local.staged)) {
const item = byId(id);
if (!item) continue;
// The label the person clicked, not the id the agent reads.
const verdict = v.verdict && (item.verdicts || []).find((x) => x.id === v.verdict);
const said = v.k || (verdict ? verdictText(verdict) : v.verdict);
bits.push(item.title + (said ? ` → ${said}` : ""));
}
for (const note of notes) {
const item = byId(note.id);
bits.push(`note on ${item ? item.title : "a question"}`);
}
summary.appendChild(document.createTextNode(" · " + bits.join(" · ")));
}
const held = finish() ? 0 : heldNotes().length;
if (held) {
summary.appendChild(
el(
"div",
"footer-held",
held === 1
? "1 note is waiting on an upload and will not go with this send."
: `${held} notes are waiting on an upload and will not go with this send.`
)
);
}
const state = sendState();
const btn = $("btn-send");
btn.disabled = state.disabled;
// Filled accent means "this is the step". That is only true of Send once
// nothing is left to answer; before then it is the quieter of the two, so
// the next question wins the eye. Still one click either way: someone who
// means to send one answer on its own is not stopped, only not steered.
const sendIsStep = !state.disabled && !unanswered().length;
btn.classList.toggle("primary", state.disabled || sendIsStep);
btn.classList.toggle("standby", !state.disabled && !sendIsStep);
const hint = $("send-hint");
hint.replaceChildren();
hint.title = state.why;
// Something is turning while the turn is not theirs. A line of grey text
// saying "one moment" reads the same whether the agent is working on it or
// has quietly died; a spinner is the difference between the two at a glance.
// A spinner says "something is happening". Nothing is, once the other end
// has stopped answering, and a permanent one is how a dead session passes
// for a slow one.
if (!gone && !agentAdrift() && (pendingResult || agentWorking())) {
hint.appendChild(el("span", "spinner tiny"));
}
// An empty `short` means the spinner says it all: a routine wait, already
// spelled out with a live clock in the dock. The words are for states that
// want something from the person or have gone wrong.
if (state.short) {
hint.appendChild(el("span", "hint-text", state.short));
} else if (!state.disabled) {
hint.appendChild(document.createTextNode("or press "));
hint.appendChild(el("kbd", null, isMac() ? "⌘" : "Ctrl"));
hint.appendChild(document.createTextNode(" + "));
hint.appendChild(el("kbd", null, "Enter"));
}
$("btn-clear").hidden = !(n || notes.length || held);
if (foot) foot.hidden = false;
renderWhere();
if (foot) foot.hidden = foot.classList.contains("is-dash") && $("footer-where").hidden;
}
// The workspace's folders, original first, or none before a frame has them.
const workspaceFolders = () => (wsFrame && Array.isArray(wsFrame.folders) ? wsFrame.folders : []);
// The workspace label in the footer's middle: `plan2code + 2 folders ·
// branch`, falling back tier by tier (workspace.js) until it fits the slot.
// Before a frame carries the workspace it is today's `folder · branch`, and a
// session opened before the server wrote `worktree` has nothing to show, so
// the slot stays hidden. The footer renders on every tick, so the DOM is only
// touched when the labels change, or when a resize clears the key.
// The project's name: the workspace's original folder, or the session's
// worktree folder before a frame carries the workspace.
function projectName() {
const folders = workspaceFolders();
if (folders.length && folders[0].name) return folders[0].name;
const path = (S && S.worktree) || "";
return path ? path.split(/[\\/]/).filter(Boolean).pop() || path : "";
}
// The browser tab's title, led by the project so tabs from different
// projects are told apart. Called from the chrome and the footer, since the
// workspace frame can arrive after either.
function renderTabTitle() {
if (!S) return;
const name = projectName();
const title = S.title || "Session";
// A title that defaulted to the folder name says it once, not twice.
const lead = name && name !== title ? name + " · " : "";
document.title = lead + title + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
}
function renderWhere() {
const b = $("footer-where");
const folders = workspaceFolders();
const path = S.worktree || "";
renderTabTitle();
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
const labels = folders.length
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
: [path ? (path.split(/[\\/]/).filter(Boolean).pop() || path) + (S.branch ? " · " + S.branch : "") : ""];
const key = labels.join("\n") + (alert ? "\n!" : "");
if (b.dataset.key === key) return;
b.dataset.key = key;
b.hidden = !labels[0];
if (b.hidden) return;
let label = labels[0];
for (const text of labels) {
label = text;
// The project name takes the highlight color, so several consoles side by
// side tell apart at a glance; the rest of the label stays quiet.
const name = projectName();
b.textContent = "";
if (name && text.startsWith(name)) {
b.appendChild(el("span", "where-project", name));
b.appendChild(document.createTextNode(text.slice(name.length)));
} else {
b.textContent = text;
}
if (alert) {
const dot = el("span", "where-alert");
dot.setAttribute("aria-hidden", "true");
b.appendChild(dot);
}
if (b.scrollWidth <= b.clientWidth) break;
}
b.title = "Open workspace";
b.setAttribute("aria-label", "Open workspace: " + label + (alert ? " (a folder needs attention)" : ""));
}
let whereResizeTimer = null;
addEventListener("resize", () => {
clearTimeout(whereResizeTimer);
whereResizeTimer = setTimeout(() => {
if (!S) return;
delete $("footer-where").dataset.key;
renderWhere();
}, 100);
});
/* ------------------------------------------------------------ workspace */
// The Workspace dialog. The server is the only writer of workspace.json: the
// page asks through /workspace/*, and the new list comes back on the next
// frame, which redraws the dialog while it is open.
// POST a JSON body; the status and parsed answer, or status 0 when the
// server could not be reached.
async function postJson(url, body) {
try {
const res = await fetch(url, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body || {}),
});
let answer = {};
try {
answer = await res.json();
} catch {}
return { status: res.status, body: answer };
} catch {
return { status: 0, body: {} };
}
}
/* The workspace follows the dashboard's picker: the folders remembered for
the selected spec, or the project's own under "Start from scratch". The
server swaps the list and remembers every change after it. */
let scopeAsked = null;
// The scope this tab last asked for: its pick, not whatever the frame says.
let scopeMine = null;
// True from a launch's scope sync until its send has gone (or failed).
let launchScoping = false;
async function syncWorkspaceScope(spec) {
if (!S || S.workflow !== "dashboard" || gone || !wsFrame) return;
const want = spec === undefined ? (selSpec() && selSpec().dir) || "" : spec;
scopeMine = want;
if ((wsFrame.scope || "") === want || scopeAsked === want) return;
scopeAsked = want;
const { status, body } = await postJson("/workspace/scope", { spec: want });
if (status === 200 && body && Array.isArray(body.folders)) wsFrame = { ...wsFrame, ...body };
scopeAsked = null;
if ($("workspace-modal").open) renderWorkspace();
}
// The dialog's "Remembered for" line: whose list this is.
function workspaceScopeText() {
const scope = (wsFrame && wsFrame.scope) || "";
if (!scope) return "Remembered for this project, so your next console session here starts with these folders.";
const spec = specList().find((s) => s.dir === scope);
const name = spec ? spec.name : scope.split("/").pop();
return `Remembered for the ${name} spec, and loaded again whenever it is picked.`;
}
const NAME_RULE = "Names use lowercase letters, numbers and hyphens.";
const BROWSE_UNAVAILABLE = "Browse isn't available here — type or paste the path.";
// The folder whose Remove is waiting on its inline confirm, by id.
let wsConfirm = null;
let wsBusy = false;
async function openWorkspace() {
const dlg = $("workspace-modal");
try {
const res = await fetch("/workspace?check=1", { cache: "no-store" });
if (res.ok) wsFrame = await res.json();
} catch {}
wsConfirm = null;
setAddMsg("");
renderWorkspace();
if (!dlg.open) dlg.showModal();
$("workspace-path").focus();
}
function setAddMsg(text, kind, action) {
const p = $("workspace-add-msg");
p.className = "workspace-add-msg" + (kind ? " is-" + kind : "");
p.textContent = text;
if (action) p.appendChild(action);
}
// One per folder, original first. A frame that keeps the same folders in
// the same order is painted into the rows already there, so a box someone is
// typing in keeps its text, caret and focus; any other change rebuilds.
function renderWorkspace() {
const list = $("workspace-list");
const folders = workspaceFolders();
const ids = folders.map((f) => f.id).join("\n");
if (list.dataset.ids !== ids) {
list.dataset.ids = ids;
list.replaceChildren(...folders.map(workspaceRow));
}
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
$("workspace-browse").hidden = Boolean(wsFrame && wsFrame.remote);
$("workspace-scope").textContent = workspaceScopeText();
}
function workspaceRow(f) {
const li = el("li", "ws-entry");
li.dataset.fid = f.id;
const head = el("div", "ws-head");
head.appendChild(el("span", "ws-chip"));
if (f.original) head.appendChild(el("span", "ws-original", "started here — can't be removed"));
li.appendChild(head);
const pathRow = el("div", "ws-path-row");
const code = el("code", "ws-path");
pathRow.appendChild(code);
const copy = el("button", "btn small", "Copy path");
copy.type = "button";
copy.addEventListener("click", async () => {
const folder = workspaceFolders().find((x) => x.id === f.id);
if (!folder) return;
try {
await navigator.clipboard.writeText(folder.path);
copy.textContent = "Copied";
setTimeout(() => (copy.textContent = "Copy path"), 1500);
} catch {
// Refused: the path is selected instead, ready for Ctrl+C.
selectContents(code);
copy.textContent = "Press Ctrl+C";
}
});
pathRow.appendChild(copy);
if (!f.original) {
const remove = el("button", "btn small danger ws-remove", "Remove");
remove.type = "button";
remove.addEventListener("click", () => {
wsConfirm = f.id;
renderWorkspace();
li.querySelector(".ws-confirm .btn.danger")?.focus();
});
pathRow.appendChild(remove);
}
li.appendChild(pathRow);
li.appendChild(el("div", "ws-marks"));
li.appendChild(workspaceField(f, "name", "Name"));
li.appendChild(workspaceField(f, "description", "What is it?"));
return li;
}
// The Name and What-is-it boxes. Each saves on blur or Enter through
// /workspace/edit, and only when it holds something new.
function workspaceField(f, field, labelText) {
const wrap = el("div", "ws-field");
const id = `ws-${field}-${f.id}`;
const label = el("label", null, labelText);
label.htmlFor = id;
const input = el("input");
input.type = "text";
input.id = id;
input.dataset.field = field;
input.autocomplete = "off";
input.spellcheck = false;
if (field === "description") input.maxLength = 200;
const err = el("p", "field-error");
err.hidden = true;
const current = () => workspaceFolders().find((x) => x.id === f.id);
const saved = () => (current() ? current()[field] || "" : "");
const showError = (text) => {
err.textContent = text || "";
err.hidden = !text;
input.classList.toggle("invalid", Boolean(text));
};
if (field === "name") {
input.addEventListener("input", () => showError(nameProblem(input.value.trim()) ? NAME_RULE : ""));
}
const save = async (leaving) => {
const value = input.value.trim();
if (value === saved()) return showError("");
if (field === "name" && nameProblem(value)) {
if (!leaving) return showError(NAME_RULE);
input.value = saved();
return showError("");
}
const { status, body } = await postJson("/workspace/edit", { id: f.id, [field]: value });
// An earlier "Added as @x" is out of date once the list moves on.
if (status === 200) {
setAddMsg("");
return showError("");
}
if (body.reason === "name-taken") showError(`@${value} is taken — try @${body.suggest}.`);
else if (body.reason === "bad-name") showError(NAME_RULE);
else showError("That did not save. Try again.");
if (leaving) input.value = saved();
};
input.addEventListener("keydown", (e) => {
if (e.key !== "Enter") return;
e.preventDefault();
save(false);
});
input.addEventListener("blur", () => save(true));
wrap.append(label, input, err);
return wrap;
}
// Everything in a row that follows the frame. A box with focus is left as
// the person has it; every other box shows what is saved.
function paintWorkspaceRow(li, f) {
if (!li) return;
const missing = (wsFrame.missing || []).includes(f.id);
const issue = (wsFrame.issues || []).find((x) => x.name === f.name);
li.classList.toggle("is-missing", missing);
li.querySelector(".ws-chip").textContent = "@" + f.name;
li.querySelector(".ws-path").textContent = f.path;
for (const input of li.querySelectorAll("input[data-field]")) {
if (document.activeElement !== input) input.value = f[input.dataset.field] || "";
}
const marks = li.querySelector(".ws-marks");
marks.replaceChildren();
if (missing) marks.appendChild(el("p", "ws-mark is-missing", "This folder no longer exists"));
if (issue) {
marks.appendChild(el("p", "ws-mark is-issue", "The agent can't read this yet: " + issue.reason));
if (issue.hint) {
const row = el("div", "ws-hint-row");
const code = el("code", "ws-hint", issue.hint);
row.append(code, copyButton(issue.hint, "btn tiny", code));
marks.appendChild(row);
}
}
if (f.nested) marks.appendChild(el("p", "ws-mark is-nested", "Inside another folder in the list"));
marks.hidden = !marks.children.length;
// Built once per confirm, so a frame landing meanwhile keeps its focus.
const open = li.querySelector(".ws-confirm");
if (wsConfirm !== f.id) open?.remove();
else if (open) open.querySelector("span").textContent = `Remove @${f.name}? The agent is told.`;
else {
const box = el("div", "ws-confirm");
box.setAttribute("role", "alert");
box.appendChild(el("span", null, `Remove @${f.name}? The agent is told.`));
const keep = el("button", "btn small ghost", "Keep it");
keep.type = "button";
keep.addEventListener("click", () => {
wsConfirm = null;
renderWorkspace();
li.querySelector(".ws-remove")?.focus();
});
const go = el("button", "btn small danger", "Remove");
go.type = "button";
go.addEventListener("click", async () => {
go.disabled = true;
const { status } = await postJson("/workspace/remove", { id: f.id });
wsConfirm = null;
if (status === 200) setAddMsg("");
if (status !== 200) setAddMsg(`@${f.name} could not be removed. Try again.`, "error");
renderWorkspace();
$("workspace-path").focus();
});
box.append(keep, go);
li.appendChild(box);
}
}
// Add by typed path, or by a path Browse… came back with. `name` is only
// sent when the person took a suggested name after a clash.
async function addWorkspaceFolder(path, name) {
const trimmed = String(path || "").trim();
if (!trimmed || wsBusy) return;
wsBusy = true;
$("workspace-add").disabled = true;
const { status, body } = await postJson("/workspace/add", name ? { path: trimmed, name } : { path: trimmed });
wsBusy = false;
$("workspace-add").disabled = false;
if (status === 200) {
$("workspace-path").value = "";
setAddMsg(`Added as @${body.name}.` + (body.nested ? " It's inside another folder in the list." : ""), "good");
if (body.name && wsFrame && !workspaceFolders().some((f) => f.id === body.id)) {
wsFrame = { ...wsFrame, folders: [...workspaceFolders(), body] };
}
renderWorkspace();
renderWhere();
return;
}
switch (body.reason) {
case "not-a-folder":
return setAddMsg("That isn't a folder on this machine.", "error");
case "duplicate":
return setAddMsg(`Already in the workspace as @${body.name}.`, "error");
case "name-taken": {
const taken = name || String(body.suggest || "").replace(/-\d+$/, "");
const use = el("button", "btn tiny", `Use @${body.suggest}`);
use.type = "button";
use.addEventListener("click", () => addWorkspaceFolder(trimmed, body.suggest));
return setAddMsg(`@${taken} is taken — try @${body.suggest}.`, "error", use);
}
case "bad-name":
return setAddMsg(NAME_RULE, "error");
default:
return setAddMsg("That folder could not be added. Try again.", "error");
}
}
async function browseWorkspace() {
const b = $("workspace-browse");
if (b.disabled) return;
b.disabled = true;
setAddMsg("Waiting for the folder picker…");
const { status, body } = await postJson("/workspace/browse", {});
b.disabled = false;
if (status === 200 && body.path) {
setAddMsg("");
return addWorkspaceFolder(body.path);
}
if (status === 200 && body.cancelled) return setAddMsg("");
setAddMsg(BROWSE_UNAVAILABLE, "error");
}
$("workspace-add").addEventListener("click", () => addWorkspaceFolder($("workspace-path").value));
$("workspace-path").addEventListener("keydown", (e) => {
if (e.key !== "Enter") return;
e.preventDefault();
addWorkspaceFolder(e.currentTarget.value);
});
$("workspace-browse").addEventListener("click", browseWorkspace);
$("workspace-done").addEventListener("click", () => $("workspace-modal").close());
$("workspace-help").addEventListener("click", openHelp);
$("workspace-modal").addEventListener("close", () => {
wsConfirm = null;
$("footer-where").focus();
});
// As on Help: the page-wide Ctrl/Cmd+Enter stands down while a dialog is open,
// and this keeps the key inside the Workspace dialog as well.
$("workspace-modal").addEventListener("keydown", (e) => {
if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
e.preventDefault();
e.stopPropagation();
}
});
/* ------------------------------------------------------------- mentions */
// `@name` suggestions in the boxes people type in. One popover for the page,
// owned by whichever box last asked for it; the rules (where a mention starts,
// what matches, how a pick is spliced in) are mentions.js's. Attach before
// the box's own keydown listeners, so a key the list uses stops here.
let mentionPop = null;
function closeMentions() {
if (!mentionPop) return;
const { box, node } = mentionPop;
node.remove();
removeEventListener("scroll", placeMentions, true);
box.setAttribute("aria-expanded", "false");
box.removeAttribute("aria-activedescendant");
mentionPop = null;
}
// Under the box, as wide as it, fixed to the viewport so no card's overflow
// can clip it; above it when the window has no room below (the Ask box sits
// at the bottom). A box that has been redrawn away takes the list with it.
function placeMentions() {
if (!mentionPop) return;
if (!mentionPop.box.isConnected) return closeMentions();
const r = mentionPop.box.getBoundingClientRect();
const node = mentionPop.node;
node.style.left = Math.round(r.left) + "px";
node.style.width = Math.round(r.width) + "px";
const h = node.offsetHeight;
const top = r.bottom + 4 + h <= innerHeight ? r.bottom + 4 : Math.max(4, r.top - 4 - h);
node.style.top = Math.round(top) + "px";
}
function paintMentions() {
const { node, box, matches, query } = mentionPop;
node.replaceChildren();
if (!matches.length) {
node.appendChild(el("div", "mention-empty", `No folder called @${query} in the workspace`));
box.removeAttribute("aria-activedescendant");
return;
}
matches.forEach((name, i) => {
const opt = el("div", "mention-opt" + (i === mentionPop.at ? " is-active" : ""), "@" + name);
opt.id = "mention-opt-" + i;
opt.setAttribute("role", "option");
opt.setAttribute("aria-selected", String(i === mentionPop.at));
// Held on mousedown, so the box keeps focus and the click can land.
opt.addEventListener("mousedown", (e) => e.preventDefault());
opt.addEventListener("click", () => pickMention(name));
node.appendChild(opt);
});
box.setAttribute("aria-activedescendant", "mention-opt-" + mentionPop.at);
}
function pickMention(name) {
if (!mentionPop) return;
const { box, mention } = mentionPop;
const next = applyMention(box.value, box.selectionStart, mention, name);
closeMentions();
box.value = next.text;
box.setSelectionRange(next.caret, next.caret);
// Whatever the box does with typing (drafts, staging, the counter) runs.
box.dispatchEvent(new Event("input", { bubbles: true }));
}
function attachMentions(box) {
box.setAttribute("aria-autocomplete", "list");
box.setAttribute("aria-expanded", "false");
box.setAttribute("aria-controls", "mention-pop");
const update = () => {
const mention =
box.selectionStart === box.selectionEnd ? mentionAt(box.value, box.selectionStart) : null;
const names = workspaceFolders().map((f) => f.name);
const matches = mention ? matchNames(names, mention.query) : [];
// Nothing to offer with only the original folder and no match; a bigger
// workspace says plainly that the name is not in it.
if (!mention || (!matches.length && names.length < 2)) {
if (mentionPop && mentionPop.box === box) closeMentions();
return;
}
if (!mentionPop || mentionPop.box !== box) {
closeMentions();
const node = el("div", "mention-pop");
node.id = "mention-pop";
node.setAttribute("role", "listbox");
node.setAttribute("aria-label", "Workspace folders");
document.body.appendChild(node);
mentionPop = { box, node, at: 0, matches: [], mention: null, query: "" };
addEventListener("scroll", placeMentions, true);
box.setAttribute("aria-expanded", "true");
}
const same = mentionPop.matches.join("\n") === matches.join("\n");
Object.assign(mentionPop, { matches, mention, query: mention.query, at: same ? mentionPop.at : 0 });
paintMentions();
placeMentions();
};
box.addEventListener("input", update);
box.addEventListener("keyup", (e) => {
if (!["ArrowUp", "ArrowDown", "Enter", "Tab", "Escape"].includes(e.key)) update();
});
box.addEventListener("keydown", (e) => {
if (!mentionPop || mentionPop.box !== box || e.isComposing) return;
const { matches } = mentionPop;
const stop = () => {
e.preventDefault();
e.stopImmediatePropagation();
};
if (e.key === "Escape") {
stop();
return closeMentions();
}
if (!matches.length) return;
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
stop();
mentionPop.at = (mentionPop.at + (e.key === "ArrowDown" ? 1 : matches.length - 1)) % matches.length;
return paintMentions();
}
if ((e.key === "Enter" || e.key === "Tab") && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey) {
stop();
pickMention(matches[mentionPop.at]);
}
});
box.addEventListener("blur", () => {
if (mentionPop && mentionPop.box === box) closeMentions();
});
}
/* ------------------------------------------------------------ stopping */
// Ending a session from the page. The page cannot stop Plan2Code; it asks.
// The request rides the ordinary submit with whatever is staged, so the last
// answers go with it instead of being stranded, and the agent handles it the
// way it handles a brief: save its place, post a finish with the command to
// resume, stop the server. The finish is what ends the wait on this side --
// the hand-off card then takes over.
let stoppingHidden = false;
// A stop is under way if this browser sent one, or if the server is holding
// one nobody has collected: the second covers a reload on a resumed session,
// a second tab, another machine.
function stopInProgress() {
return local.stopping || (pendingStop ? { at: 0, answers: 0 } : null);
}
function renderStopButton() {
const b = $("btn-stop");
if (!S || finish()) {
b.hidden = true;
return;
}
b.hidden = false;
if (stopInProgress()) {
b.textContent = "Stopping…";
b.disabled = false;
b.title = "Show how the stop is going";
return;
}
b.textContent = "Stop session";
// Only on the person's turn, unless nothing is coming (see turnGate).
const gate = turnGate({ gone, pendingResult, waiting: agentHasTheBall() });
// A way home in flight holds Stop back too, unless the agent went quiet
// after collecting it: Stop's resume screen is then the only way out.
b.disabled = Boolean(gate) || (Boolean(local.homeward) && !agentAdrift());
b.title = {
gone: "Not connected right now.",
pending: "Your last answers are still being picked up. You can stop once they have been.",
waiting: "Plan2Code is working on your answers. You can stop once it replies.",
}[gate] || (stopWarning() ? "End this session. Work since the last save is not kept." : "Save your place and end this session. You get a command to pick it up later.");
}
// Plan2Code has the ball: it is working, or owes a reply to a send, and has
// not gone quiet. What both session buttons wait out.
function agentHasTheBall() {
return (agentWorking() || awaitingReply().length > 0) && !agentAdrift();
}
/* ------------------------------------------------ back to the dashboard */
// The triangle left of Stop session. Mid-workflow it is a stop that lands on
// the menu instead of a finish: the same staged answers ride along, the agent
// saves its place the same way, then resumes the session as the dashboard.
function renderHomeButton() {
const b = $("btn-home");
const st = homeButtonState({
workflow: S && S.workflow,
finished: Boolean(S && finish()),
stopping: Boolean(S && stopInProgress()),
homeward: Boolean(local.homeward),
adrift: Boolean(S) && agentAdrift(),
gone,
pendingResult,
waiting: Boolean(S) && agentHasTheBall(),
warned: Boolean(S) && Boolean(stopWarning()),
});
b.hidden = st.hidden;
b.disabled = st.disabled;
b.title = st.title;
}
function openHomeConfirm() {
const n = Object.keys(local.staged).length + pendingNotes().length;
const warn = stopWarning();
// With a warning, "your place is saved" is the one thing not true: the
// warning says what is lost, and the button says the choice is theirs.
$("home-blurb").textContent =
(n === 1 ? "The answer you have ready goes with it. " : n ? `The ${n} answers you have ready go with it. ` : "") +
(warn ? "Plan2Code takes you back to the dashboard." : "Your place is saved; you can resume it from the dashboard.");
$("home-go").textContent = warn ? "Leave anyway" : "Back to the dashboard";
$("home-warn").hidden = !warn;
$("home-warn").textContent = warn;
$("home-modal").showModal();
}
// The picker's Delete: a dialog in two steps. The first says what goes and
// that it is for good; "Delete this spec…" then reveals the second, which
// enables the final button only once the spec's name is typed exactly. A
// fixed bug skips the second step: its first press sends the delete.
// Cancel, Escape or a click on Keep it at either step changes nothing.
let deleteTarget = null;
// The spec warning as index.html writes it, kept so a fixed bug's wording
// never sticks for the next spec.
let deleteWarnDefault = null;
// A handoff's Delete reuses the same dialog in one step: no name to type, and
// the warning says where the file lives instead of what git does not track.
function openHandoffDelete(h) {
if (gone || pendingResult || local.launching || local.deleting) return;
deleteTarget = { handoff: h };
$("delete-title").textContent = "Delete this handoff?";
$("delete-blurb").textContent = "This handoff will be deleted from ~/.plan2code/handoffs/.";
$("delete-warn").hidden = true;
$("delete-warn-handoff").hidden = false;
const facts = $("delete-facts");
facts.replaceChildren();
const fact = (term, value) => {
if (!value) return;
facts.appendChild(el("dt", "", term));
facts.appendChild(el("dd", "", value));
};
const entry = SKILL_CATALOG.find((e) => e.skill === h.skill);
fact("Handoff", h.title || h.id);
fact("Written", h.written ? new Date(h.written).toLocaleString() : "");
fact("Spec", h.spec ? h.spec.replace(/^specs\//, "") : "");
fact("From", entry ? entry.title : h.skill);
$("delete-confirm").hidden = true;
const go = $("delete-go");
go.textContent = "Delete it";
go.classList.add("is-on");
go.disabled = false;
$("delete-modal").showModal();
}
function openDeleteConfirm(spec) {
if (!isDeletableSpecDir(spec.dir) || gone || pendingResult || local.launching || local.deleting) return;
deleteTarget = spec;
// A fixed bug is finished work: one confirm, and a warning that says so.
const fixed = spec.state === "fixed";
$("delete-title").textContent = "Delete this spec?";
const warn = $("delete-warn");
if (!deleteWarnDefault) deleteWarnDefault = [...warn.childNodes].map((n) => n.cloneNode(true));
warn.replaceChildren(
...(fixed
? ["The bug is fixed, so this only clears the write-up. ", el("code", "", "specs/"), " is not tracked by git, so it cannot be brought back."]
: deleteWarnDefault.map((n) => n.cloneNode(true)))
);
warn.hidden = false;
$("delete-warn-handoff").hidden = true;
const sum = deleteSummary(spec);
$("delete-blurb").textContent = `Everything in ${sum.folder} will be deleted from this project.`;
const facts = $("delete-facts");
facts.replaceChildren();
const fact = (term, value) => {
if (!value) return;
facts.appendChild(el("dt", "", term));
facts.appendChild(el("dd", "", value));
};
fact("Spec", spec.name);
fact("Folder", sum.folder);
fact("Stage", sum.stage);
fact("Files", sum.files);
fact("Last changed", sum.touched ? new Date(sum.touched).toLocaleString() : "");
$("delete-name-hint").textContent = spec.name;
$("delete-name").value = "";
$("delete-confirm").hidden = true;
const go = $("delete-go");
go.textContent = fixed ? "Delete it" : "Delete this spec…";
go.classList.toggle("is-on", fixed);
go.disabled = false;
$("delete-modal").showModal();
}
function deleteStep() {
const go = $("delete-go");
if (!deleteTarget) return;
if (deleteTarget.handoff) return sendDeleteHandoff(deleteTarget.handoff);
if (deleteTarget.state === "fixed") return sendDelete(deleteTarget);
if ($("delete-confirm").hidden) {
$("delete-confirm").hidden = false;
go.textContent = "Delete for good";
go.classList.add("is-on");
go.disabled = true;
$("delete-name").focus();
return;
}
if ($("delete-name").value.trim() !== deleteTarget.name) return;
sendDelete(deleteTarget);
}
async function sendDeleteHandoff(h) {
const go = $("delete-go");
go.disabled = true;
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: [deleteHandoffAction(h)], reply: deleteHandoffReply(h) }),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
const sc = scan();
local.deleting = { dir: "handoff:" + h.id, scanAt: sc ? sc.at : null };
if (local.specSel === "handoff:" + h.id) delete local.specSel;
pendingResult = true;
save();
$("delete-modal").close();
} catch (err) {
$("delete-modal").close();
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last pick is still being picked up, so that could not go yet. Nothing was deleted; try again in a moment."
: "That did not go through. Nothing was deleted; try again.",
"warn"
);
} finally {
deleteTarget = null;
render();
}
}
async function sendDelete(spec) {
const go = $("delete-go");
go.disabled = true;
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: [deleteAction(spec)], reply: deleteReply(spec) }),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
const sc = scan();
local.deleting = { dir: spec.dir, scanAt: sc ? sc.at : null };
// The selection must not outlive the folder: back to the default pick,
// which the agent's fresh menu recommends for.
if (local.specSel === spec.dir) delete local.specSel;
pendingResult = true;
save();
$("delete-modal").close();
} catch (err) {
$("delete-modal").close();
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last pick is still being picked up, so that could not go yet. Nothing was deleted; try again in a moment."
: "That did not go through. Nothing was deleted; try again.",
"warn"
);
} finally {
deleteTarget = null;
render();
}
}
async function goHome() {
const go = $("home-go");
go.disabled = true;
const payload = stagedPayload();
payload.actions.push({ i: "__dashboard", type: "dashboard" });
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: payload.actions, reply: [...payload.replyLines, HOME_REPLY].join("\n") }),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
markSent(payload);
local.homeward = { at: Date.now() };
save();
$("home-modal").close();
} catch (err) {
$("home-modal").close();
// The server is holding an uncollected result: Send, Home and Stop all
// need to read as busy until the frame or the ping says otherwise, same
// as send() and sendAfterBuild() do on a 409.
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
: "That did not go through. Nothing was lost; try again.",
"warn"
);
} finally {
go.disabled = false;
render();
}
}
// Stopping now can lose answers: Planning writes nothing until its plan is
// done, and Pathfinder nothing until its map exists. The agent knows where it
// is and says so in `stopWarning`; Planning is assumed to lose answers unless
// the agent says otherwise, because that is true of most of it.
function stopWarning() {
if (typeof S.stopWarning === "string") return S.stopWarning.trim();
if (S.workflow === "plan") {
return "Planning only saves at set points along the way. Answers since the last save will not be kept, though you can go over them again next time.";
}
return "";
}
function openStopConfirm() {
if (stopInProgress()) {
stoppingHidden = false;
return renderStopping();
}
const n = Object.keys(local.staged).length + pendingNotes().length;
const warn = stopWarning();
const dash = isDashboard();
$("stop-blurb").textContent =
(n === 1 ? "The answer you have ready goes with it. " : n ? `The ${n} answers you have ready go with it. ` : "") +
(dash ? "Nothing has started yet, so there is nothing to save: this just ends the console session." : "");
$("stop-blurb").hidden = !$("stop-blurb").textContent;
$("stop-warn").hidden = !warn;
$("stop-warn").textContent = warn;
// The dashboard has nothing to hand off: one plain Stop. Elsewhere both
// choices show, and "Just stop and save" turns into "Stop anyway" where
// nothing is saved yet.
$("stop-handoff").hidden = dash;
const title = $("stop-go").querySelector(".stop-choice-title");
const detail = $("stop-go").querySelector(".stop-choice-detail");
if (dash) {
title.textContent = "Stop";
detail.textContent = "Ends the console session.";
} else if (warn) {
title.textContent = "Stop anyway";
detail.textContent = "Ends the session now. What the warning above names is not kept.";
} else {
title.textContent = "Just stop and save";
detail.textContent = "Saves what this step keeps on disk and gives you a command to resume. What we talked about is not kept.";
}
$("stop-modal").showModal();
}
async function stopSession(handoff = false) {
const buttons = [$("stop-handoff"), $("stop-go")];
for (const b of buttons) b.disabled = true;
const payload = stagedPayload();
payload.actions.push(stopAction({ handoff }));
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: payload.actions, reply: [...payload.replyLines, handoff ? STOP_HANDOFF_REPLY : STOP_REPLY].join("\n") }),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
markSent(payload);
local.stopping = { at: Date.now(), answers: payload.sentIds.size };
save();
$("stop-modal").close();
stoppingHidden = false;
} catch (err) {
$("stop-modal").close();
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
: "The stop did not go through. Nothing was lost; try again.",
"warn"
);
} finally {
for (const b of buttons) b.disabled = false;
render();
}
}
// The wrapping-up screen, derived every render from what the page already
// tracks: whether the request is collected, whether anyone is listening, and
// whether the finish has landed.
function renderStopping() {
const dlg = $("stopping-modal");
const stopping = S && stopInProgress();
if (!stopping) {
if (dlg.open) dlg.close();
return;
}
// The finish is the end of it: the hand-off card on the page says the rest.
if (finish()) {
local.stopping = null;
save();
if (dlg.open) dlg.close();
return;
}
const sent = stopping.answers;
const collected = !pendingResult;
// Nobody is coming: the server stopped with no finish, or the agent has not
// checked in for minutes. The request and any answers are on disk either
// way, and the next session collects them.
const stuck = gone || agentAdrift();
const steps = [
{ text: sent ? `Sent your ${sent === 1 ? "answer" : sent + " answers"} and the stop` : "Sent the stop", state: "done" },
{
text: collected ? "Plan2Code picked it up" : stuck ? "Plan2Code has not picked it up" : "Waiting for Plan2Code to pick it up",
state: collected ? "done" : stuck ? "stuck" : "now",
},
{ text: "Saving your place and writing the command to pick it up", state: collected ? (stuck ? "stuck" : "now") : "later" },
];
const list = $("stop-steps");
list.replaceChildren(
...steps.map((s) => {
const li = el("li", "is-" + s.state);
li.appendChild(
s.state === "now"
? el("span", "spinner tiny")
: el("span", "stop-mark", s.state === "done" ? "✓" : s.state === "stuck" ? "!" : "·")
);
li.appendChild(el("span", null, s.text));
return li;
})
);
const extra = $("stop-extra");
extra.replaceChildren();
if (stuck) {
extra.appendChild(
el(
"p",
"stop-note",
gone
? "The session closed without saying how to pick it up. Your answers and the stop are saved, and the next session collects them. To carry on, run this in the terminal, in a new conversation (or alternatively run `/plan2code` to relaunch the dashboard):"
: "Plan2Code is not running right now, so nothing new has been saved yet. Your answers and the stop are held, and the next session collects them. To carry on, run this in the terminal, in a new conversation (or alternatively run `/plan2code` to relaunch the dashboard):"
)
);
const text = handoffText({ command: resumeCommand(S) });
const row = el("div", "handoff-command");
const code = el("code", "handoff-code", text);
row.appendChild(code);
row.appendChild(copyButton(text, "btn small handoff-copy", code));
extra.appendChild(row);
} else {
extra.appendChild(
el(
"p",
"stop-note",
agentWorking() && !collected
? "Plan2Code is in the middle of something. It stops as soon as that is done."
: "This usually takes a moment. You can close the tab if you need to: the command also appears in the terminal."
)
);
}
if (!stoppingHidden && !dlg.open) dlg.showModal();
}
/* ---------------------------------------------------------------- send */
// Everything staged, in the shape /submit takes. Shared by Send and by Stop
// session, which has to carry the same answers the same way: a stop that
// dropped someone's last answers on the floor would be worse than no button.
function stagedPayload() {
const actions = [];
const replyLines = [];
const sentIds = new Set();
const summaries = {};
// Kept so the card can state the answer back in words while it is in flight,
// the same way a settled one does. `staged` is cleared by the send itself.
const values = {};
for (const [id, v] of Object.entries(local.staged)) {
const item = byId(id);
if (!item) continue;
sentIds.add(id);
values[id] = v;
actions.push({ i: id, ...v });
// The literal token the terminal flow would have received. This is what
// lets the agent treat a click exactly like a typed word, so no workflow
// needs a second code path.
const tok = tokenFor(item, v);
summaries[id] = tok;
if (tok) replyLines.push(`${item.title}: ${indentReply(tok)}`);
}
// Which notes, and which of their images, went: markSent clears exactly
// those, so a note held back on an upload stays drafted.
const sentNotes = {};
for (const note of pendingNotes()) {
sentIds.add(note.id);
sentNotes[note.id] = new Set(note.images.map((img) => img.key));
actions.push(noteAction(note.id, note.text, note.images));
const item = byId(note.id);
replyLines.push(...noteReplyLines(item ? item.title : note.id, note.text, note.images));
}
return { actions, replyLines, sentIds, sentNotes, summaries, values };
}
// After /submit took it: what went is now in flight, and nothing of it stays
// staged or drafted to be sent a second time.
function markSent({ sentIds, sentNotes = {}, summaries, values }) {
// Clear every draft belonging to an item in this batch, not just the
// thread notes. A surviving draft re-populates the field with text that
// was already sent, and the next keystroke re-stages it WITHOUT the
// verdict that went with it, which is how an approval gets lost.
// A note held back on an image upload stays drafted, attachments and all,
// even when an answer on the same item went. The sent images' files stay
// on disk for the agent; the sweep cleans them up.
for (const id of sentIds) {
for (const prefix of ["other-", "text-", "note-"]) delete local.drafts[prefix + id];
if (sentNotes[id]) {
delete local.drafts["thread-" + id];
const rest = noteImages(id).filter((img) => !sentNotes[id].has(img.key));
if (rest.length) local.images[id] = rest;
else delete local.images[id];
} else if (!local.images[id]) {
delete local.drafts["thread-" + id];
}
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
}
local.staged = {};
save();
}
async function send() {
if (sendState().disabled) return;
const payload = stagedPayload();
const { actions, replyLines } = payload;
if (!actions.length) return;
const btn = $("btn-send");
btn.disabled = true;
btn.textContent = "Sending…";
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ actions, reply: replyLines.join("\n") }),
});
if (res.status === 409) {
const e = new Error("pending");
e.pending = true;
throw e;
}
if (!res.ok) throw new Error(String(res.status));
markSent(payload);
banner("Sent. Plan2Code is picking it up now.", "good");
setTimeout(() => banner(null), 4000);
} catch (err) {
if (err && err.pending) {
banner(
"Your last answers are still being picked up. Nothing is lost, and nothing was sent twice. Try again in a moment.",
"info"
);
pendingBannerUp = true;
pendingResult = true;
} else {
banner("That did not go through. Nothing was lost, try Send again.", "warn");
}
} finally {
btn.textContent = "Send to Plan2Code";
render();
}
}
const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", defer: "later" };
// Turn a staged answer into the words the person would have typed in the
// terminal. The agent reads `reply` as their message, so every part of an
// answer has to survive: a verdict AND its note, a checklist state AND what
// they wrote, a reordered list AND its new order. Anything dropped here is
// something the agent never hears.
function tokenFor(item, v) {
const map = item.token || {};
if (v.skipped) return v.text ? `skip; ${v.text}` : "skip";
const parts = [];
if (v.k) parts.push(map[v.k] || v.k);
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
if (v.verdict) parts.push(map[v.verdict] || v.verdict);
if (typeof v.yes === "boolean") parts.push(map[v.yes ? "yes" : "no"] || (v.yes ? "yes" : "no"));
if (typeof v.ok === "boolean") parts.push(v.ok ? "confirmed" : "needs changes");
if (v.state) parts.push(map[v.state] || STATE_WORDS[v.state] || v.state);
if (Array.isArray(v.done) && v.done.length) parts.push(`did steps ${v.done.map((n) => n + 1).join(", ")}`);
if (Array.isArray(v.rows)) {
// What changed against the agent's rows, said in words: `reply` is what
// the agent reads, and an order alone hides a rename or a removal. The
// whole list always comes too, called a new order only when one moved.
const before = new Map((item.rows || []).map((r) => [r.id, r]));
const after = new Set(v.rows.map((r) => r.id));
const kept = (item.rows || []).filter((r) => after.has(r.id)).map((r) => r.id);
const moved = v.rows.filter((r) => before.has(r.id)).some((r, i) => r.id !== kept[i]);
parts.push((moved ? "new order: " : "the list: ") + v.rows.map((r) => r.title).join(", then "));
const renamed = v.rows.filter((r) => before.has(r.id) && before.get(r.id).title !== r.title);
const added = v.rows.filter((r) => !before.has(r.id));
const removed = (item.rows || []).filter((r) => !after.has(r.id));
if (renamed.length) parts.push("renamed " + renamed.map((r) => `${before.get(r.id).title} to ${r.title}`).join(", "));
if (added.length) parts.push("added " + added.map((r) => r.title).join(", "));
if (removed.length) parts.push("removed " + removed.map((r) => r.title).join(", "));
}
if (v.text) parts.push(v.text);
return parts.join("; ");
}
/* ---------------------------------------------------------------- misc */
function fmtMs(ms) {
const s = Math.round(ms / 1000);
if (s < 60) return `${s}s`;
const m = Math.floor(s / 60);
return `${m}m ${s % 60}s`;
}
function shortTime(iso) {
try {
return new Date(iso).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
} catch {
return "";
}
}
function isMac() {
return /mac/i.test(navigator.platform || navigator.userAgent);
}
// Markdown rather than HTML: it is what the agent wrote, what the file under
// specs/ already holds, and what survives being pasted into Slack or a ticket.
function downloadDoc(doc) {
// The file keeps what the page shows: the title, and which parts are still
// assumptions or drafts. Without the marks a half-finished document reads,
// once it leaves the page, as a set of decisions.
const mark = { assumed: "> **Assumed for now, still open.**\n\n", draft: "> **Draft.**\n\n" };
const blocks = (doc.blocks || []).map((b) => (mark[b.state] || "") + (typeof b.image === "string" ? b.alt || "" : b.md || ""));
const first = (doc.blocks || [])[0];
const titled = first && /^\s*#\s/.test(first.md || "");
const body = [titled || !doc.title ? null : `# ${doc.title}`, ...blocks].filter((x) => x != null).join("\n\n");
saveFile(`${docFileName(doc)}.md`, body, "text/markdown");
}
function docFileName(doc) {
const name = (doc.title || "document").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
return name || "document";
}
function saveFile(name, body, type) {
const url = URL.createObjectURL(new Blob([body], { type }));
const a = document.createElement("a");
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
a.remove();
// Give the download a tick to start before the handle goes.
setTimeout(() => URL.revokeObjectURL(url), 30000);
}
// The page's own markdown styles, restated with the light palette baked in:
// the saved file has no app.css beside it and may be opened years from now,
// on any machine, so it carries everything it needs.
const DOC_HTML_CSS = `
:root { color-scheme: light; }
body { margin: 0; background: #f6f3ee; color: #1d1a17; font: 15.5px/1.6 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
main { max-width: 880px; margin: 0 auto; padding: 40px 28px 60px; background: #fff; min-height: 100vh; box-sizing: border-box; }
.doc-head { display: flex; gap: 12px; align-items: baseline; flex-wrap: wrap; margin-bottom: 16px; padding-bottom: 14px; border-bottom: 1px solid #e4ddd1; }
.doc-head h1 { font: 600 27px/1.2 "Iowan Old Style", Charter, Georgia, Cambria, serif; margin: 0; }
.doc-version, .doc-meta { font: 700 12px/1 ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace; color: #8f8779; }
.doc-note { color: #5d564d; margin: 0 0 16px; }
.block { border-left: 3px solid transparent; padding: 2px 0 2px 14px; margin: 0 0 4px; }
.block.assumed { border-left: 3px dashed #9a6a12; background: #fbf0d8; border-radius: 0 8px 8px 0; }
.block.draft { border-left-color: #cfc6b6; opacity: 0.72; }
.block.settled { border-left-color: #e4f0e8; }
.block-tag { font-size: 10.5px; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase; color: #9a6a12; display: block; margin-bottom: 4px; }
.md-h { font-family: "Iowan Old Style", Charter, Georgia, Cambria, serif; font-weight: 600; margin: 22px 0 9px; line-height: 1.25; }
h1.md-h { font-size: 25px; }
h2.md-h { font-size: 21px; }
h3.md-h { font-size: 17.5px; }
h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
.md-p { margin: 0 0 11px; }
.md-list { margin: 0 0 11px; padding-left: 22px; }
.md-li { margin-bottom: 5px; }
.md-task { display: inline-block; width: 16px; color: #8f8779; font-weight: 700; }
.md-task.is-done { color: #2f6b45; }
.md-li.is-task { list-style: none; margin-left: -18px; display: grid; grid-template-columns: 16px 1fr; column-gap: 4px; align-items: baseline; }
.md-li.is-task > :not(.md-task) { grid-column: 2; }
.md-li.is-task > .md-p:last-child { margin-bottom: 0; }
.md-quote { margin: 0 0 11px; padding: 2px 0 2px 15px; border-left: 3px solid #cfc6b6; color: #5d564d; }
.md-code { font: 0.88em ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace; background: #fbf9f6; border: 1px solid #e4ddd1; border-radius: 4px; padding: 1px 5px; }
.md-pre-wrap { margin: 0 0 13px; }
.md-pre { font: 13px/1.5 ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace; background: #fbf9f6; border: 1px solid #e4ddd1; border-radius: 8px; padding: 14px 16px; overflow-x: auto; margin: 0; }
.md-hr { border: 0; border-top: 1px solid #e4ddd1; margin: 20px 0; }
.md-table-wrap { overflow-x: auto; margin: 0 0 13px; }
.md-table { border-collapse: collapse; width: 100%; font-size: 13.5px; }
.md-table th, .md-table td { border: 1px solid #e4ddd1; padding: 8px 11px; text-align: left; }
.md-table th { background: #fbf9f6; font-weight: 600; }
.md-img { max-width: 100%; border-radius: 8px; }
.doc-figure { margin: 0 0 13px; }
.doc-img { display: block; max-width: 100%; border: 1px solid #e4ddd1; border-radius: 8px; }
.doc-figure figcaption { font-size: 13px; color: #5d564d; margin-top: 6px; }
.md a { color: #206cc3; }
@media print {
body { background: #fff; }
main { padding: 0; min-height: 0; }
.block { break-inside: avoid; }
}
`;
// Only this session's uploaded images may ride along in a saved file: any other
// address on this origin (/state, say) would copy session data into something
// meant to be shared. A remote image keeps its own address; anything else on
// this origin becomes its alt text.
const INLINE_UPLOAD = /^\/(?:uploads\/[0-9a-f-]{36}\.jpg|shots\/[A-Za-z0-9][A-Za-z0-9._-]{0,99}\.(?:png|jpe?g|webp))$/i;
function imageToAlt(img) {
const alt = img.getAttribute("alt") || "";
if (alt) img.replaceWith(document.createTextNode(alt));
else img.remove();
}
async function inlineImage(img) {
const src = img.getAttribute("src") || "";
if (!src || src.startsWith("data:")) return;
let url;
try {
url = new URL(src, location.href);
} catch {
return imageToAlt(img);
}
if (url.origin !== location.origin) {
img.setAttribute("src", url.href);
return;
}
if (!INLINE_UPLOAD.test(url.pathname) || url.search) return imageToAlt(img);
try {
const res = await fetch(url);
if (!res.ok) throw new Error(String(res.status));
const blob = await res.blob();
if (!blob.type.startsWith("image/")) throw new Error(blob.type);
img.setAttribute(
"src",
await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(blob);
})
);
} catch {
// Its console address would be a dead link once the server is gone.
imageToAlt(img);
}
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
}
// The document as its own web page: drawn through the same markdown path the
// tab uses, so what is saved is what was on screen, minus the page's controls.
async function downloadDocHtml(doc) {
const title = doc.title || "Document";
const body = el("div");
for (const b of doc.blocks || []) {
const box = el("div", "block " + (b.state || "settled"));
if (b.state === "assumed") box.appendChild(el("span", "block-tag", "Assumed for now, still open"));
if (b.state === "draft") box.appendChild(el("span", "block-tag", "Draft"));
box.appendChild(blockBody(b));
body.appendChild(box);
}
// Copy buttons only work inside the console.
for (const n of body.querySelectorAll(".md-copy")) n.remove();
// Images the console serves would be dead links once the server is gone, so
// they travel inside the file. One that will not load becomes its alt text.
await Promise.all([...body.querySelectorAll("img")].map(inlineImage));
const saved = new Date().toLocaleString();
const html = `
${escapeHtml(title)}
${escapeHtml(title)}
v${escapeHtml(doc.version || 1)}
${doc.note ? `${escapeHtml(doc.note)}
\n` : ""}${body.innerHTML}
`;
saveFile(`${docFileName(doc)}.html`, html, "text/html");
}
// A doc that mirrors a file the agent already wrote needs no download button
// -- the path is the useful thing to show instead of it.
function docSavedNote(doc) {
const path = typeof doc.saved === "string" ? doc.saved.trim() : "";
const note = el("span", "doc-saved", path ? "Saved as " : "Already saved");
if (path) note.appendChild(el("code", null, path));
return note;
}
// Whether the two halves are actually talking, in the one place someone goes
// when they are asking that question. Written on open rather than kept live,
// because a line that rewrites itself under a reader is worse than a stale one
// they can close and reopen.
function renderAbout() {
const line = $("about-live");
line.className = "about-live";
if (finish()) {
line.textContent = "Right now: the session is finished, and the command above is all that is left to do.";
} else if (gone) {
line.classList.add("is-bad");
line.textContent =
"Right now: this page cannot reach that program. Either it has stopped, or the machine went to sleep. The link from the terminal will bring it back.";
} else if (agentAdrift()) {
line.classList.add("is-bad");
line.textContent =
"Right now: this page is fine, but Plan2Code has not checked in for a few minutes. Have a look at the terminal; it may have finished its turn, hit an error, or be waiting on you there. If it is idle, type continue there to wake it.";
} else {
line.classList.add("is-good");
line.textContent = "Right now: both halves are talking to each other.";
}
}
let helpBuilt = false;
async function renderHelpVersion() {
const slot = $("help-version");
try {
const res = await fetch("/version", { cache: "no-store" });
const { version } = res.ok ? await res.json() : {};
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
slot.hidden = !version;
} catch {
slot.hidden = true;
}
}
const HELP_MOODS = [
["point", "Your turn"],
["work", "Working"],
["happy", "All caught up"],
["done", "Done"],
["adrift", "Not running"],
["gone", "Not connected"],
];
// The help content waits in its until the first time ? is pressed,
// so none of it costs the first paint. The tab buttons come from HELP_TABS.
function buildHelp() {
const content = $("help-content").content.cloneNode(true);
const modal = $("help-modal");
const tabs = $("help-tabs");
const panels = $("help-panels");
// In the dialog itself, so every