// 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, 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, CATALOG_GROUPS, choiceAnswer, DASHBOARD_COMMAND, DASHBOARD_NOTE, DASHBOARD_REPLY, dashboardOffer, DONE_REPLY, finishPaused, fitWithin, handoffShape, handoffText, HOME_REPLY, homeButtonState, IMAGE_LONG_EDGE, IMAGE_QUALITY, lastOpenCard, launchReply, 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, sentAnswer, submittedAwaiting, noteAwaiting, suggestionFrom, 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"; 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); }); } // Run it, on a fenced git block (render.js): stage the block as the Ask // draft and open the chat. The person still presses Send, so nothing runs // on a stray click — the same fill-the-box pattern as the Ask starters. document.addEventListener("click", (e) => { const run = e.target.closest(".md-run"); if (!run) return; const code = run.closest(".md-pre-wrap")?.querySelector("code"); if (!code || !code.textContent.trim()) return; local.chat.draft = `run:\n${code.textContent}`; view = "ask"; save(); render(); const ta = $("ask-input"); if (!ta) return; ta.focus(); ta.setSelectionRange(ta.value.length, ta.value.length); }); // 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; 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; 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; 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", "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: {}, sentAt: null, stopping: null, afterBuild: null, homeward: null, launching: 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 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 — // the first entry of the server's already-sorted list. 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 specs[0]; return specs.find((s) => s.dir === local.specSel) || null; }; // The review a finished build offers, and where it has got to: // "open" on offer, and a press would reach the agent // "asked" pressed, and the agent has not taken it up yet // null no offer, declined, or nobody left to take the press // `local.afterBuild` remembers the press across a reload. It is cleared when // the finish goes away, which is the agent taking the review up. function reviewPending() { const fin = finish(); if (!fin || !reviewOffer(fin) || local.afterBuild === "done" || local.afterBuild === "dashboard") return null; if (local.afterBuild === "review") return gone ? null : "asked"; return gone ? null : "open"; } // The dashboard offer on a finish, unless the person already said they are // done: that send closes the session, so a button after it would go nowhere. const dashboardLive = (fin) => dashboardOffer(fin) && local.afterBuild !== "done"; // The durable half of `local.sent`: the server writes every send onto the // item itself (`submitted`), so the send survives a reload, a resume onto a // new port, and a second tab. It also covers an agent that took the answer // and moved on without marking the item settled, which used to hand the // question back looking as though the send never happened. `local.retract` // is the person's "take it back" against exactly that send. const submittedInFlight = (i) => { const sub = submittedAwaiting(i); if (!sub) return null; const r = local.retract && local.retract[i.id]; if (r === "any" || (r != null && r === sub.at)) return null; return sub; }; // Open questions whose send is with the agent: answers and notes alike. On a // finished session there is nobody left to collect a send, so nothing is in // flight either -- the item is a record of what was sent, not a live wait. const awaitingReply = () => finish() ? [] : openItems().filter((i) => (local.sent && local.sent[i.id]) || submittedInFlight(i)); // Open questions that are actually the person's to answer right now. An open // question they have already sent is not one of those, and counting it as one // is how the page ends up telling someone it is their turn while they are // sitting waiting for a reply. A finished session ends everyone's turn: // questions left open are moot, because a send can no longer go anywhere. const myTurn = () => finish() ? [] : openItems().filter((i) => !(local.sent && local.sent[i.id]) && !submittedInFlight(i)); // Questions that are theirs and still have no answer on them. This is what // decides which control is the loud one: while this is non-empty the next // question is the step, and Send is merely available. const unanswered = () => myTurn().filter((i) => !local.staged[i.id]); function agentWorking() { return S && S.agent && S.agent.status === "working"; } function workingMs() { if (!agentWorking() || !S.agent.since) return 0; return Date.now() - Date.parse(S.agent.since); } // The three silence thresholds below, stretched while the agent has said a // long quiet stretch is normal (a build task). See quietLimitMs. const patience = (baseMs) => quietLimitMs(S && S.agent, baseMs); // What the agent says it is doing right now, when it has said: "Task 3 of 9: // the user service". Only meaningful while it is working. A build's line is // rewritten (activityLabel() in labels.js) because agents trained on the old // wording still write "Task 4.3 of 9", phase-numbered beside a bar that counts // within the phase; the page puts it right rather than every prompt having to. function activity() { if (!agentWorking()) return ""; const a = S.agent.activity; if (typeof a !== "string") return ""; return activityLabel(a.trim(), S.workflow); } const doingNow = () => workingLine(S && S.agent, S && S.headline, S && S.workflow); function agentStale() { if (!agentLastSeen) return false; return Date.now() - Date.parse(agentLastSeen) > patience(STALE_MS); } // The OTHER end of the wire, and the one that was invisible. // // There are two connections here, not one. The page talks to a little server // on this machine (`gone` covers that), and the server is polled by the agent // sitting in `wait` (this covers that). The second is the one that actually // breaks: a page left open pings every five seconds, which keeps the server // well clear of its idle deadline, so the server happily outlives the agent // for hours. Until now nothing said so unless the agent had also declared // itself "working", and the normal state while someone answers is "waiting". function agentAdrift() { if (!agentLastSeen || gone || finish()) return false; return Date.now() - Date.parse(agentLastSeen) > patience(ADRIFT_MS); } // Answers that went nowhere: pressed Send, and nothing has collected them. // They are safe -- the server wrote them to disk and the next session picks // them up -- but "Sent. Waiting for Plan2Code." forever does not say that. const stranded = () => pendingResult && agentAdrift(); // The spec whose overview.md the Overview tab shows: the dashboard picker's // selection on the dashboard, the session's own spec everywhere else. const overviewSpec = () => (isDashboard() ? selSpec()?.dir || "" : (S && S.specDir) || ""); // Fresh from disk every time, never cached: the file changes under a build, // and the tab is only worth having if it shows what is there now. Repaints // only when the tab would appear, vanish or show different text. async function loadOverview() { const spec = overviewSpec(); let text = null; if (spec) { try { const res = await fetch("/overview?spec=" + encodeURIComponent(spec), { cache: "no-store" }); if (res.status === 200) text = await res.text(); } catch {} } // The selection moved on while this was in flight; its own fetch will land. if (spec !== overviewSpec()) return; const changed = overview.key !== spec || overview.text !== text; overview = { key: spec, text }; if (changed) render(); } /* --------------------------------------------------------------- input */ function stage(id, value) { if (value == null) delete local.staged[id]; else local.staged[id] = value; save(); render(); } function setDraft(id, text) { local.drafts[id] = text; save(); } /* --------------------------------------------------------------- fetch */ async function loadState() { try { const res = await fetch("/state", { cache: "no-store" }); if (!res.ok) throw new Error(String(res.status)); const body = await res.json(); // The same rev is the same state: adopting it again would redraw the page // every few seconds while polling for nothing. Still proof of life, though. if (S && typeof body.rev === "number" && body.rev === rev) { lastContact = Date.now(); agentLastSeen = body.agentLastSeen || agentLastSeen; markGone(); } else { adopt(body); } retryStream(); } catch { markGone(); } } function adopt(body) { const firstLoad = S === null; // What was already theirs to answer, measured BEFORE the new state lands, // so what is theirs afterwards can be told apart from what just arrived. const before = firstLoad ? null : new Set(myTurn().map((i) => i.id)); const wasFinished = Boolean(finish()); const prevWorkflow = S ? S.workflow : null; const prevSpecDir = S ? S.specDir : null; rev = body.rev; lastHave = body.have || null; S = body.state; agentLastSeen = body.agentLastSeen || null; pendingResult = Boolean(body.pendingResult); pendingStop = Boolean(body.pendingStop); chatFrame = body.chat || null; if (body.workspace) wsFrame = body.workspace; if (body.meter) meterFrame = body.meter; lastContact = Date.now(); if (gone) { gone = false; banner(null); } if (firstLoad) { load(); // A draft the server kept wins if this browser has nothing, which is how a // second device or a cleared profile still picks up where you left off. if (!Object.keys(local.staged).length && body.draft && body.draft.staged) { local.staged = body.draft.staged; local.drafts = body.draft.drafts || {}; local.images = body.draft.images || {}; settleStaleUploads(); } } // The page passed through the dashboard (a launch from its menu, or back to // it). The server already blanked the session; what this page kept for the // last skill -- the question on screen, the open tab, anything staged or // typed against its item ids -- goes too. The launch in flight and the // dashboard's spec pick are about the hand-off itself, so they stay. A skill // run inline from another (a quick task's review) keeps all of it. const viaDashboard = prevWorkflow === "dashboard" || S.workflow === "dashboard"; if (prevWorkflow && prevWorkflow !== S.workflow && viaDashboard) { local = { ...fresh(), launching: local.launching, ...("specSel" in local ? { specSel: local.specSel } : {}) }; save(); selected = null; view = "questions"; // And forget which tab is drawn, or the next render would store the old // skill's offset straight back under a tab id the new one may reuse. scrollMemory.clear(); drawnView = null; drawnTabs = null; } adoptChat(); // The finish a review was asked from has gone: the agent took the review // up. A later finish (after the review, or after a second phase) starts // with its own offer unanswered. if (!finish() && local.afterBuild) { local.afterBuild = null; save(); } // A way home that ended in a finish instead (the agent paused rather than // resuming as the dashboard) is over: the finish screen says the rest. if (finish() && local.homeward) { local.homeward = null; save(); } // The end of the session is a page of its own in the rail. Landing there // the moment the finish arrives keeps it where the current design already // put it: on top. A finish that goes away (a review taken up) drops the // page back to the questions with it. const endLanded = Boolean(finish()) && !wasFinished; if (endLanded) { view = "end"; // The closing chime -- unless this page only just loaded into an already // finished session, in which case the opening one IS this sound. if (!firstLoad) sound("sessionEnd"); } if (!finish() && view === "end") view = "questions"; // A launch ends the moment the launched skill turns the page: it resumes the // session under its own workflow, so `dashboard` stops being what the state // says it is. A finish while still on the dashboard is the launch declined // or the session ended; either way the menu is not mid-handoff any more. if (!isDashboard() || finish()) dashPick = null; // A launch (or an ending) mid wake-up: cut it short rather than play on // over a page that is no longer the menu. if (wake && (!isDashboard() || finish())) wake.abort.abort(); if (local.launching && (!isDashboard() || finish())) { const was = local.launching; local.launching = null; save(); // A resume that lands before the skill has said anything turns the page // into its starting screen, which is not "ready" yet: the chime and the // banner wait for the first thing it actually puts on the page. if (!finish() && (asked().length || doingNow() || docs().length)) { sound("skillReady"); banner(`${was.title} is ready.`, "good"); clearTimeout(arrivalBannerTimer); arrivalBannerTimer = setTimeout(() => !gone && banner(null), 4000); } } // Anything the agent has now recorded is no longer "staged" or in flight. for (const id of Object.keys(local.staged)) { const item = byId(id); if (!item || !isOpen(item)) delete local.staged[id]; } // A question stops being in flight when the agent has dealt with it: either // it settled the question, or it has replied and left it open, which means it // is asking again and the person may answer again. const replied = !pendingResult && !agentWorking(); for (const id of Object.keys(local.sent || {})) { const item = byId(id); if (!item || !isOpen(item) || replied) delete local.sent[id]; } // A retracted send suppresses exactly that send. Once the item moves -- // settled, sent again (a new `at`), or answered by an agent reply -- the // mark is stale and keeping it would hide a send that is not that one. for (const id of Object.keys(local.retract || {})) { const item = byId(id); const r = local.retract[id]; const live = item && isOpen(item) && submittedAwaiting(item) && (r === "any" || (item.submitted && item.submitted.at === r)); if (!live) delete local.retract[id]; } // New work: a question that is theirs to answer now and was not a moment ago. // That covers a brand new question and one the agent reopened or answered // with a follow-up, and not the first load, which has nothing to compare to. const arrived = before && !finish() ? myTurn().filter((i) => !before.has(i.id)) : []; let announce = null; if (arrived.length) { // Their turn again, announced by ear as well as by eye: the chime matters // most exactly when the banner is the fallback, because they are busy // somewhere else on the page. sound("question"); if (typingHere()) { // Mid-sentence somewhere. Moving the page under their cursor would lose // their place for the sake of telling them something that can wait. banner( arrived.length === 1 ? "A new question from Plan2Code. It is in the list on the left." : `${arrived.length} new questions from Plan2Code. They are in the list on the left.`, "info" ); clearTimeout(arrivalBannerTimer); arrivalBannerTimer = setTimeout(() => !gone && banner(null), 8000); } else { selected = arrived[0].id; view = "questions"; announce = arrived; } } if (!selected || !byId(selected)) selected = pickDefault(); // A reply that lands while another tab is open: a dot on Ask, and one chime. // Not on the first load, which has nothing new to announce. const dot = unreadDot({ lastSeenReplyId: local.chat.lastSeenReplyId, frameChat: chatFrame, viewIsAsk: view === "ask" }); if (!firstLoad && shouldChime(chatDot, dot)) sound("chatReply"); chatDot = dot; render(); if ($("workspace-modal").open) renderWorkspace(); tellFolderIssues(); if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow) loadOverview(); if (announce) showArrival(announce); // New entries land at the bottom of the rail. Gliding down to them beats // leaving the list parked where it was while it grew underneath. if (arrived.length) scrollRail("end"); // The ending item lands at the TOP of the rail, above a list that may be // scrolled well down, so the rail goes up to show the page now on screen. if (endLanded) scrollRail("top"); } // The chat's half of adopt(). A new conversation (New conversation pressed in // any tab, or a skill switch) is a clean page: nothing typed or waiting for // the old one carries over. Conversations only ever count up, so a frame that // names an older one than this page already moved to is a late frame, not a // switch. Sends the server has now echoed stop being pending. function adoptChat() { const conv = chatFrame ? chatFrame.conversation : null; if (conv != null && conv !== local.chat.conversation) { if (local.chat.conversation == null) local.chat.conversation = conv; else if (conv > local.chat.conversation) { local.chat = { ...freshChat(), history: local.chat.history, about: null, conversation: conv }; chatError = ""; askRowCount = 0; declineOpen.clear(); } save(); } if (local.chat.pending.length) { const shown = new Set( chatView(chatFrame, { pendingSends: local.chat.pending }) .rows.filter((r) => r.pending) .map((r) => r.tempId) ); const still = local.chat.pending.filter((p) => shown.has(p.tempId)); if (still.length !== local.chat.pending.length) { local.chat.pending = still; save(); } } } // Top or bottom of the session outline, smoothly unless the person has asked // the browser for less motion. function scrollRail(where) { const rail = $("sidebar"); rail.scrollTo({ top: where === "top" ? 0 : rail.scrollHeight, behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth", }); } let arrivalBannerTimer = null; // Typing in any text field, the question's own or the notes beside it. function typingHere() { const a = document.activeElement; if (!a) return false; return a.tagName === "TEXTAREA" || (a.tagName === "INPUT" && (a.type === "text" || a.type === "date")); } // The moment the ball comes back. // // After Send the person has usually looked away: to the terminal, to another // window, to the doc tab. The page has already moved them to the first new // question; this is what makes the move legible instead of a page that // silently changed while they were not looking. It covers everything // for a beat, says what happened, and gets out of the way by itself. Any // click or key dismisses it at once, and it never takes focus from a dialog. function showArrival(arrived) { // A dialog is in the browser's top layer, above anything this could draw, // so the overlay would play unseen behind it. The move has still happened. if (document.querySelector("dialog[open]")) return; const old = document.querySelector(".arrival"); if (old) old.remove(); const layer = el("div", "arrival"); layer.setAttribute("aria-hidden", "true"); // the status line announces it const box = el("div", "arrival-box"); box.appendChild(el("p", "arrival-kicker", "Plan2Code is back")); box.appendChild(el("p", "arrival-title", arrived.length === 1 ? "Next question" : "Next questions")); box.appendChild(el("p", "arrival-what", arrived[0].title)); if (arrived.length > 1) { const more = arrived.length - 1; box.appendChild(el("p", "arrival-more", `and ${more} more after it`)); } layer.appendChild(box); document.body.appendChild(layer); let done = false; const close = () => { if (done) return; done = true; layer.classList.add("is-leaving"); removeEventListener("keydown", close, true); setTimeout(() => layer.remove(), 320); // Where the eye goes next. Not the first field: that would scroll and // put a caret in front of someone who has not read the question yet. if (!document.querySelector("dialog[open]")) $("main").focus({ preventScroll: true }); }; layer.addEventListener("click", close); addEventListener("keydown", close, true); setTimeout(close, 1900); } function pickDefault() { // What is theirs first: an open question whose answer is already with the // agent is reference, not work, and landing on it buries the one that // still needs them. const open = myTurn().length ? myTurn() : openItems(); if (open.length) return open[0].id; const all = asked(); return all.length ? all[all.length - 1].id : null; } // An open EventSource is itself proof of life. Without this the page would // declare itself offline during any quiet stretch, since a healthy session // sends no state events while the agent is thinking. function connected() { if (es && es.readyState === EventSource.OPEN) return true; return Date.now() - lastContact <= GONE_AFTER_MS; } function markGone() { const bad = !connected(); if (bad && !gone) { gone = true; // After a finish the server going away IS the ending: the agent stops it // on its way out. Saying "lost contact" and promising to reconnect would // dress the expected last step of a session up as a fault, and it would // land on top of the hand-off a few seconds after they got there. // Same for a stop in progress: the wrapping-up screen says what the loss // of the server means there, and a banner promising a reconnect would // argue with it. if (!finish() && !stopInProgress()) { banner( "Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.", "warn" ); } render(); } else if (!bad && gone) { gone = false; banner(null); render(); } } /* ----------------------------------------------------------------- SSE */ // Exactly one EventSource for the life of the page. Browsers cap HTTP/1.1 at // about six connections per origin and a stream holds one permanently, so a // second stream per tab across a few tabs wedges the origin with no error. function connect() { esErrors = 0; try { es = new EventSource(lastHave ? "/events?have=" + encodeURIComponent(lastHave) : "/events"); } catch { es = null; return startPolling(); } es.addEventListener("state", (e) => { esErrors = 0; try { adopt(JSON.parse(e.data)); } catch {} }); es.addEventListener("submitted", (e) => { local.sentAt = Date.now(); // Drop only what was actually sent. // // This event fires for a send from ANY tab of this session, which is why it // clears anything at all: a second tab must not keep offering answers that // have already gone. But it also fires for a brief request, which carries // no answers, and the blanket clear threw away everything the person had // staged and not yet sent. A missing `ids` means an older server, where // clearing everything is still the best guess available. let ids = null; try { ids = JSON.parse(e.data).ids; } catch {} if (Array.isArray(ids)) for (const id of ids) delete local.staged[id]; else local.staged = {}; save(); render(); }); es.onopen = () => { esErrors = 0; esRetryMs = ES_RETRY_MIN_MS; lastContact = Date.now(); // Back on the stream: polling was only ever the stand-in. if (pollTimer) { clearInterval(pollTimer); pollTimer = null; } }; es.onerror = () => { esErrors++; if (esErrors >= 3) { try { es.close(); } catch {} es = null; startPolling(); } markGone(); }; } function startPolling() { if (pollTimer) return; esRetryAt = Date.now() + esRetryMs; esRetryMs = Math.min(esRetryMs * 2, ES_RETRY_MAX_MS); pollTimer = setInterval(loadState, 3000); } // While polling, every answer from the server is a cue to try the stream // again, so polling lasts only as long as the outage did. Polling carries on // while an attempt is open, so startPolling() never runs for a failed one; the // wait is pushed back here instead, or a dead stream would be retried on every // poll. One attempt at a time, since `es` is set while it is trying. function retryStream() { if (!pollTimer || es || Date.now() < esRetryAt) return; esRetryAt = Date.now() + esRetryMs; esRetryMs = Math.min(esRetryMs * 2, ES_RETRY_MAX_MS); connect(); } setInterval(() => { fetch("/ping", { method: "POST" }) .then((r) => (r.ok ? r.json() : null)) .then((body) => { if (!body) return; lastContact = Date.now(); agentLastSeen = body.agentLastSeen || agentLastSeen; retryStream(); // A rev we have not seen means a state frame went missing -- a dropped // SSE reconnect, a tab asleep in a background window. Ask for it rather // than waiting for the next change to come along. if (typeof body.rev === "number" && body.rev !== rev) return loadState(); if (body.pendingResult !== pendingResult || Boolean(body.pendingStop) !== pendingStop) { pendingResult = body.pendingResult; pendingStop = Boolean(body.pendingStop); render(); } }) .catch(() => {}) .finally(() => { markGone(); renderStatus(); }); }, 5000); addEventListener("pagehide", () => { try { navigator.sendBeacon("/bye"); } catch {} }); /* -------------------------------------------------------------- render */ let rendering = false; function render() { if (!S) return; // A handler that fires while the DOM is being replaced (a blur as its element // is removed, say) must not start a second render inside the first. if (rendering) return; rendering = true; try { trackAbout(); const enteringAsk = view === "ask" && drawnView !== "ask"; const switchingTab = drawnView !== null && view !== drawnView; let tabAdded = false; rememberScroll(); withFocus(() => { renderChrome(); renderStatus(); renderBriefButton(); renderStopButton(); renderHomeButton(); tabAdded = renderViews(); renderSidebar(); renderMain(); restoreScroll(); renderAside(); renderFooter(); }); // The box an `@` list belonged to was just redrawn away. if (mentionPop && !mentionPop.box.isConnected) closeMentions(); if (enteringAsk) { const box = $("ask-input"); if (box && !box.disabled) box.focus({ preventScroll: true }); } if (switchingTab || tabAdded) replayViewsArrow(); if (tabAdded) sound("newTab"); renderStopping(); } finally { rendering = false; } } // The runway chevrons beside the tabs pulse a few times on load and then rest. // Moving to another tab, or a new tab turning up, runs them again: clearing // the animation, forcing a reflow, then handing it back restarts it from the // top. The CSS still gates the animation on prefers-reduced-motion, so this is // a no-op there. function replayViewsArrow() { const arrows = document.querySelectorAll(".views-arrow svg"); for (const svg of arrows) svg.style.animation = "none"; void document.querySelector(".views-arrow")?.offsetWidth; for (const svg of arrows) svg.style.animation = ""; } // The places + Add context offers, fed from where the person has been: the // question card on screen, the doc block they left, the dashboard's spec. // Only changes are events, and they only ever feed history: nothing here sets // what a message is about. function trackAbout() { const before = local.chat; let st = { history: before.history, about: before.about }; const apply = (event) => (st = nextAbout(st, event)); const moved = aboutSeen.view !== view; if (moved && aboutSeen.view && aboutSeen.view.startsWith("doc:") && docInView?.docId === aboutSeen.view.slice(4)) { apply({ type: "section", ...docInView }); } if (isDashboard()) { const spec = selSpec(); const dir = spec ? spec.dir : null; if (dir !== aboutSeen.spec) { aboutSeen.spec = dir; if (spec) apply({ type: "spec", dir: spec.dir, label: spec.name }); } } else if (selected !== aboutSeen.selected) { aboutSeen.selected = selected; const item = byId(selected); if (item && item.kind !== "notice") apply({ type: "card", id: item.id, label: item.title }); } if (moved) aboutSeen.view = view; if (st.history !== before.history || st.about !== before.about) { Object.assign(local.chat, st); save(); } } // Keeping the person's place across a full render: what had focus, where the // text cursor sat, and how far down the card they had scrolled. // // A re-render replaces the card wholesale, and the card is the thing that // scrolls. Ticking the fifth box in a long list threw the list back to the top // with the box just aimed at now off screen, and dropped focus off the control // that was pressed, which is worse for a keyboard user than for a mouse: they // lose their position in the group as well as on the page. Every control that // stages an answer went through this path -- checkboxes, radios, the Yes/No // buttons -- because staging an answer is a full render. // // The scroll is restored only while the same question is on screen. Moving to // another one should start at its top, not part-way down it. function withFocus(fn) { const a = document.activeElement; const keep = a && (a.tagName === "TEXTAREA" || a.tagName === "INPUT") && a.id ? { id: a.id, start: a.selectionStart, end: a.selectionEnd } : null; const before = $("main").querySelector(".card.question"); const place = before && before.scrollTop ? { of: before.dataset.item, top: before.scrollTop } : null; fn(); // Scroll first, then focus: focusing an element that is off screen scrolls it // into view, which would undo the restore we just did. const after = $("main").querySelector(".card.question"); // Which question the card on screen HOLDS, asked of the card itself. The // `selected` variable is no use here: the rail and the pager both set it and // then call render, so by now it already names where we are going. if (place && after && after.dataset.item === place.of) after.scrollTop = place.top; if (keep) { const n = $(keep.id); if (n) { n.focus(); try { n.setSelectionRange(keep.start, keep.end); } catch {} } } } // Scroll memory across tab switches. withFocus() above keeps a card's place // while the SAME tab re-renders; these two cover moving BETWEEN tabs, which // withFocus() cannot see, because by the time it measures, the old tab's // content is already gone. A re-render within one tab leaves `drawnView` // equal to `view`, so restoreScroll() stands aside and withFocus() does it. // // The element that scrolls: the main column on a doc or the Overview, the // question card on the questions tab, and nothing worth keeping elsewhere // (the dashboard menu, the end page). function currentScroller() { if (!drawnView) return null; if (drawnView.startsWith("doc:") || drawnView === "overview") return $("main"); if (drawnView === "questions") return $("main").querySelector(":scope > .card.question"); if (drawnView === "ask") return $("main").querySelector(".ask-list"); return null; } function rememberScroll() { const scroller = currentScroller(); if (scroller) scrollMemory.set(drawnView, { top: scroller.scrollTop, item: scroller.dataset.item }); } // A question card comes back to its place only while it is the same question: // moving to another one still starts at its top. A doc with nothing stored // starts at the top too, rather than inheriting the last doc's offset from the // main column they share. function restoreScroll() { if (view === drawnView) return; drawnView = view; // The chat places its own list: back where it was, or at the newest row. if (view === "ask") return; const scroller = currentScroller(); if (!scroller) return; const saved = scrollMemory.get(view); if (view === "questions") { if (saved && saved.item === scroller.dataset.item) scroller.scrollTop = saved.top; return; } scroller.scrollTop = saved ? saved.top : 0; } // `extras` are nodes shown after the text: a copyable hint, an action. function banner(text, kind, extras) { const n = $("banner"); if (!text) { n.hidden = true; n.textContent = ""; return; } n.hidden = false; n.className = "banner " + (kind || ""); n.textContent = text; for (const node of extras || []) n.appendChild(node); } // Folders the agent reported it cannot read, each told once per page load // and launch. The server keeps only the current launch's reports, so a name // that drops out of the list may be told again after the next launch. const issuesTold = new Set(); let issueBannerTimer = null; function tellFolderIssues() { const issues = (wsFrame && wsFrame.issues) || []; const names = new Set(issues.map((i) => i.name)); for (const name of [...issuesTold]) if (!names.has(name)) issuesTold.delete(name); const fresh = issues.find((i) => !issuesTold.has(i.name)); if (!fresh) return; issuesTold.add(fresh.name); const extras = []; if (fresh.hint) { extras.push(document.createTextNode(" ")); extras.push(el("code", "banner-hint", fresh.hint)); } const open = el("button", "btn tiny banner-action", "Open workspace"); open.type = "button"; open.addEventListener("click", () => { banner(null); openWorkspace(); }); extras.push(open); banner(`The agent can't read @${fresh.name}: ${fresh.reason}`, "warn", extras); clearTimeout(issueBannerTimer); // Then the next folder waiting to be told, if several came at once. issueBannerTimer = setTimeout(() => { if (gone) return; banner(null); tellFolderIssues(); }, 15000); } // The session meter's pill, straight from the frame's `meter` (meter.js did // the counting). Hidden until a frame carries it. function renderMeter() { const pill = $("meter-pill"); if (!meterFrame) { pill.hidden = true; return; } pill.hidden = false; pill.dataset.level = meterFrame.level; const fraction = Math.max(0, Math.min(1, Number(meterFrame.fraction) || 0)); $("meter-fill").setAttribute("stroke-dashoffset", String(Math.round((1 - fraction) * 1000) / 10)); $("meter-words").textContent = meterFrame.words; pill.title = meterFrame.tooltip; $("meter-tip").textContent = meterFrame.tooltip; // What the points are made of: one row per piece of work that scored. const list = $("meter-list"); const rows = Array.isArray(meterFrame.items) ? meterFrame.items : []; list.hidden = !rows.length; list.replaceChildren( ...rows.map((row) => { const li = el("li"); li.appendChild(el("span", "meter-item-label", row.label)); li.appendChild(el("span", "meter-item-points", "+" + row.points)); return li; }) ); // Once the session is past fresh, say how to start a new one. const fresh = $("meter-fresh"); fresh.hidden = meterFrame.level === "green"; if (fresh.hidden || fresh.dataset.built) return; fresh.dataset.built = "1"; const text = handoffText({ command: DASHBOARD_COMMAND }); const code = el("code", "handoff-code", text); const row = el("div", "handoff-command meter-fresh-row"); row.append(code, copyButton(text, "btn small ghost handoff-copy", code)); fresh.append( textWithCode("p", "meter-fresh-text", `To start a new session, run \`${DASHBOARD_COMMAND}\` in a new conversation:`), row ); } function toggleMeterPop(open) { const pop = $("meter-pop"); const show = open ?? pop.hidden; pop.hidden = !show; $("meter-pill").setAttribute("aria-expanded", String(show)); } $("meter-pill").addEventListener("click", () => toggleMeterPop()); $("meter-help").addEventListener("click", () => { toggleMeterPop(false); openHelpOn("meter"); }); document.addEventListener("keydown", (e) => { if (e.key !== "Escape" || $("meter-pop").hidden) return; toggleMeterPop(false); $("meter-pill").focus(); }); document.addEventListener("click", (e) => { if (!$("meter-pop").hidden && !e.target.closest(".meter-slot")) toggleMeterPop(false); }); function renderChrome() { renderMeter(); $("title").textContent = S.title || "Session"; $("badge").textContent = workflowLabel(S.workflow); document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code"; const h = S.headline || {}; // On a finished session an open item is frozen: the send on it counts as // done, and only a question that was never touched stays outstanding. const done = Number(h.cleared) || asked().filter((i) => !isOpen(i) || (finish() && Boolean(recordedAnswer(i)))).length; const total = progressTotal(done, Number(h.total) || asked().length); const pct = total ? Math.round((done / total) * 100) : 0; // A build counts tasks, which get done rather than answered. const building = ["implement", "implement-review", "quick-task"].includes(S.workflow); $("progress-text").textContent = total ? `${done} of ${total} ${building ? "done" : "answered"}` : h.stage || "Getting started"; $("confidence").textContent = h.confidence || ""; $("progress-fill").style.width = pct + "%"; const bar = $("progress-bar"); bar.setAttribute("aria-valuenow", String(done)); bar.setAttribute("aria-valuemin", "0"); bar.setAttribute("aria-valuemax", String(total)); } // Planny and the line beside him are one surface, and this is the only thing // that writes to it. He carries four moods: // // point something is yours to do, and the line says what // work the agent has it, star turning, feet walking // happy nothing outstanding // done the session is over, and there is one thing left to do elsewhere // adrift the server is up but nothing is listening at the other end // gone no server, eye shut // // Each mood is a family: v0 is the plain drawing and the rest are alternates // (a hop, star-scanning, sparkles, Z's -- see the "mood variants" // section of app.css). A new variant is rolled only when the mood CHANGES, so // the once-a-second status tick does not restart his animation every time it // runs, and the same state keeps the same face until the state itself moves. const MOOD_VARIANTS = { point: 3, work: 3, happy: 3, done: 2, adrift: 2, gone: 2 }; let moodNow = null; let moodVar = 0; function renderStatus() { if (!S) return; const bot = $("planny"); const text = $("agent-text"); const tick = $("agent-tick"); // SVG className is not a plain string, so setAttribute is the way in. // `line` goes in the live region and changes rarely; `count` is the running // clock and is kept out of it, or the page reads the seconds aloud. // `spin` marks the lines where something really is happening at the other // end right now, and it flies too: the ring and the stars mean the same // thing. Never on the stale or adrift lines: a turning ring beside // "has not checked in" would contradict the sentence it sits next to. const say = (mood, line, count, spin) => { if (mood !== moodNow) { moodNow = mood; moodVar = Math.floor(Math.random() * MOOD_VARIANTS[mood]); } bot.setAttribute("class", `planny is-${mood} v${moodVar}`); if (text.dataset.line !== line) { text.dataset.line = line; text.replaceChildren( ...line.split(/\*\*(.+?)\*\*/).map((part, i) => { if (i % 2 === 0) return document.createTextNode(part); const key = document.createElement("strong"); key.className = "agent-key"; key.textContent = part; return key; }) ); } tick.textContent = count || ""; $("agent-spin").hidden = !spin; $("dock").classList.toggle("is-flying", Boolean(spin)); // The tab icon's bar says the same thing from another tab (favicon.js). setFavicon(faviconState({ mood, spin, finished: Boolean(finish()) })); }; // Before `gone`, deliberately. Once a session has finished, no server is the // expected state, and Planny shutting his eye over it reads as a breakage. if (finish()) { // A finish with the review or the way back to the dashboard still on // offer has something left to press here, and only while the server is // there to take the press. if (local.afterBuild === "dashboard" && !gone) return say("work", "Opening the dashboard…", "", true); const offer = reviewPending(); if (dashboardLive(finish()) && !gone && !offer) { return say("point", "Done. Head back to the dashboard, or close this tab."); } if (offer === "asked") return say("work", "Review requested. Plan2Code is starting it.", "", true); if (offer === "open") return say("point", "Done. Review it here first, or close this tab."); return say("done", "All done. You can close this tab."); } if (gone) return say("gone", "Not connected. Your answers are saved."); // On the way home: the request is sent, and the page stays this skill's // until the agent resumes the session as the dashboard. if (local.homeward && !isDashboard()) { return agentAdrift() ? say("adrift", "Your way back to the dashboard is saved and waiting for Plan2Code.") : say("work", "Saving your place and opening the dashboard…", "", true); } // The dashboard's three states, ahead of the question logic it never // reaches: the pick is theirs to make, it is being looked at, or it is on // its way to becoming a skill. if (isDashboard()) { if (local.launching) { const stale = staleLaunchFeedback(local.launching.title, agentAdrift()); return stale ? say("adrift", `${local.launching.title} is saved and waiting for Plan2Code.`) : say("work", `Waking up ${local.launching.title}…`, "", true); } if (dashPick) return say("point", `Start ${dashPick.title} when you're ready.`); return say("point", "Your move: pick what we are doing today."); } // A build can run a long while before it has anything to ask. Once the agent // says what it is doing, the working line below says that instead, rather // than promising questions that may never come. if (!asked().length && !doingNow()) return say("work", `Starting ${workflowTitle(S.workflow)}…`, "", true); // Show the AGENT's liveness, not the server's: if the agent's turn crashed // the server is still happily up, and a plain spinner would lie forever. if (agentWorking()) { if (agentStale()) { return say( "work", "Still working on it. Longer tasks can go a few minutes between updates. Your answers are saved. If it stays quiet for a long while, check your terminal (it may be waiting on a permission approval)." ); } // Same clock as agentStale(), so the soft line at 30 s hands over to the // stale message at two minutes on one timeline. const hint = agentLastSeen ? approvalHint(S.agent, Date.now() - Date.parse(agentLastSeen)) : ""; return say("work", hint || activity() || "Plan2Code is thinking…", fmtMs(workingMs()), true); } // Between pressing Send and the agent picking it up, the agent's own status // is still "waiting" because it has not started yet. Reading that as "your // turn" told someone who had just answered everything that the ball was back // with them. Their own send is the thing that has moved. // Before the ordinary "sent, waiting" line, which is true for a minute and // a lie after twenty. if (agentAdrift()) { return say( "adrift", stranded() ? "Plan2Code is not running. Your answers are saved and waiting for it. If the terminal is idle, type **continue** there and it will pick them up; it may also be waiting for your permission approval." : "Plan2Code is not running right now. Anything you answer here is saved. If the terminal is idle, type **continue** there to wake it; it may also be waiting for your permission approval." ); } const mine = myTurn().length; if (awaitingReply().length) { return mine ? say("point", `Sent. ${mine} question${mine === 1 ? "" : "s"} still for you.`) : say("work", "Sent. Waiting for Plan2Code.", "", true); } if (!mine) return say("happy", "All caught up."); // Everything in front of them is answered and only Send is left. This is the // one moment the page can name the next step and be certain it is right. if (!unanswered().length) return say("point", "That is all of them. Send it over."); const todo = unanswered().length; return say( "point", todo === mine ? `Your turn: ${mine} question${mine === 1 ? "" : "s"} waiting.` : `${todo} still to answer, then send.` ); } /* ---------------------------------------------------------------- brief */ // A brief is a Pathfinder thing: a plain-English report of the decisions made // in a date range, the ones still open, and what happens next. It is the // artifact someone takes to a meeting, and the reason a non-engineer is in this // session at all, so it should not need knowing that you can type "brief" at a // terminal to get one. // // The request travels as an ordinary send. The agent's own wait loop returns // it, `reply` carries the range in the grammar its playbook already parses, and // the finished brief comes back as a doc like any other. const BRIEF_RANGES = { today: "today", "this week": "this week", full: "full", }; function briefRange() { const picked = document.querySelector('input[name="brief-range"]:checked'); const value = picked ? picked.value : "today"; if (value !== "since") return { range: BRIEF_RANGES[value] || "today" }; const on = $("brief-since").value; if (!on) return { problem: "Pick the date to count from, or choose another range." }; return { range: `since ${on}` }; } function openBrief() { const why = $("brief-why"); why.textContent = ""; syncBriefDate(); $("brief-modal").showModal(); } // The date only means anything for "since", so it is dimmed and inert until // that is the choice, rather than sitting there inviting a value it will ignore. function syncBriefDate() { const picked = document.querySelector('input[name="brief-range"]:checked'); const on = Boolean(picked && picked.value === "since"); const row = document.querySelector(".since-row"); const input = $("brief-since"); row.classList.toggle("is-off", !on); input.disabled = !on; } async function sendBrief() { const choice = briefRange(); const why = $("brief-why"); if (choice.problem) { why.textContent = choice.problem; return; } const state = sendState(); // The same guard the Send button uses. A brief is a turn like any other, and // two turns in flight is the one thing this protocol will not do. if (gone || pendingResult || (agentWorking() && workingMs() <= patience(WORKING_GRACE_MS))) { why.textContent = state.why || "Wait for Plan2Code to finish, then ask again."; return; } const go = $("brief-go"); go.disabled = true; go.textContent = "Asking…"; try { const res = await fetch("/submit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ actions: [{ i: "__brief", type: "brief", range: choice.range }], reply: briefPhrase(choice.range), }), }); if (!res.ok) throw new Error(String(res.status)); $("brief-modal").close(); banner("Asked for a brief. It will appear as a tab when it is written.", "good"); setTimeout(() => banner(null), 5000); pendingResult = true; render(); } catch { why.textContent = "That did not go through. Try again in a moment."; } finally { go.disabled = false; go.textContent = "Write the brief"; } } function renderBriefButton() { const btn = $("btn-brief"); // Only Pathfinder has a brief playbook. Offering the button anywhere else // would send the agent a request it has no procedure for. const offer = S && S.workflow === "pathfinder"; btn.hidden = !offer; if (offer) btn.disabled = gone || pendingResult; } function renderViews() { const nav = $("views"); nav.replaceChildren(); // Sent and not yet picked up: the same ring as Ask, until Plan2Code moves on // or goes quiet (a turning ring would pass a dead session for a slow one). const sentBusy = pendingResult && !gone && !agentAdrift(); const tabs = [ { id: "questions", label: isDashboard() ? "Dashboard" : "Questions", count: myTurn().length, busy: sentBusy }, ]; // Built in rather than posted: present exactly while the spec in view has // an overview.md. A tab that vanishes under the person sends them home. const hasOverview = typeof overview.text === "string" && overview.key === overviewSpec(); if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 }); else if (view === "overview") view = "questions"; for (const d of docs()) tabs.push({ id: "doc:" + d.id, label: d.title || "Document", count: 0 }); // Always last, on every workflow and after a finish: the Quick question chat. // The ring left of "Ask" shows exactly when the conversation's own ring does: // a question the agent picked up and has not answered yet. const ask = askState(); const askBusy = ask.view.rows.some((r) => r.working) && ask.send.state !== "offline" && !agentAdrift(); tabs.push({ id: "ask", label: "Ask", count: 0, dot: chatDot, busy: askBusy }); for (const t of tabs) { const b = el("button", "view-tab", t.label); b.type = "button"; if (t.busy) { const spin = el("span", "spinner tiny tab-spin"); spin.setAttribute("aria-hidden", "true"); b.prepend(spin); b.title = t.id === "ask" ? "Plan2Code is working on an answer" : "Sent. Waiting for Plan2Code"; } b.setAttribute("aria-current", String(view === t.id || (t.id === "questions" && view === "end"))); if (t.count) { const c = el("span", "tab-count", String(t.count)); b.appendChild(c); } if (t.dot) { const dot = el("span", "tab-dot"); dot.setAttribute("aria-label", "New reply"); b.appendChild(dot); } b.addEventListener("click", () => { if (t.id === "ask") { local.chat.lastSeenReplyId = newestReplyId(chatFrame); chatDot = false; save(); } view = t.id === "questions" && finish() ? "end" : t.id; // The cached text paints at once; the fresh read repaints if the file // changed on disk since. render(); if (t.id === "overview") loadOverview(); }); nav.appendChild(b); } // Reports whether a tab appeared that the last draw did not have. const ids = new Set(tabs.map((t) => t.id)); const added = drawnTabs !== null && [...ids].some((id) => !drawnTabs.has(id)); drawnTabs = ids; return added; } function markFor(item) { // On a finished session an open item is frozen, not waiting: its send went // and can no longer be added to, or it was never answered and never can be. if (isOpen(item) && finish()) { return recordedAnswer(item) ? { glyph: "✓", cls: "done", label: "sent" } : { glyph: "○", cls: "open", label: "left unanswered" }; } if (local.staged[item.id]) return { glyph: "●", cls: "staged", label: "ready to send" }; if (isOpen(item) && ((local.sent && local.sent[item.id]) || submittedInFlight(item))) return { glyph: "◐", cls: "staged", label: "sent, waiting for Plan2Code" }; if (!isOpen(item)) return { glyph: "✓", cls: "done", label: "answered" }; return { glyph: "○", cls: "open", label: "waiting for you" }; } // The session's own ending, as a page of its own at the top of the rail. // A pause and a finish share the screen -- the hand-off card -- but not the // name: "paused" is the word the stop playbook asks for in the headline, and // it is the word the person was told to expect. function renderEndItem(fin) { const paused = finishPaused(fin); const box = el("div", "rail-group rail-end"); const b = el("button", "rail-item"); b.type = "button"; b.setAttribute("aria-current", String(view === "end")); const mark = el("span", "rail-mark " + (paused ? "staged" : "done"), paused ? "❚❚" : "✓"); mark.title = paused ? "session paused" : "session ended"; b.appendChild(mark); b.appendChild(el("span", "rail-end-label", paused ? "Paused" : "Session ended")); b.addEventListener("click", () => { view = "end"; render(); $("main").focus(); }); box.appendChild(b); return box; } function renderSidebar() { const rail = $("sidebar"); rail.replaceChildren(); const fin = finish(); if (fin) rail.appendChild(renderEndItem(fin)); // On the dashboard the rail is the same menu in outline form, so a person // who learned the page on a workflow session finds the picks where the // session outline usually lives. The card that is mid-launch gets the // half-filled mark the page uses for "sent, on its way". if (isDashboard() && !fin) { const menu = (S && S.menu) || {}; for (const g of CATALOG_GROUPS) { const box = el("div", "rail-group"); const head = el("p", "rail-title"); head.appendChild(el("span", null, g.title)); box.appendChild(head); for (const e of SKILL_CATALOG.filter((x) => x.group === g.id)) { const av = cardPresentation(e, scan(), selSpec(), menu); // Unavailable for the selected spec fades hard; the brief greying // while a launch is in flight or the server is away does not. const b = el( "button", "rail-item" + (av.on ? "" : " is-unavailable") + (av.recommended ? " is-suggested" : "") ); b.type = "button"; b.disabled = Boolean(local.launching) || gone || pendingResult || !av.on; if (!av.on && av.reason) b.title = av.reason; b.setAttribute("aria-current", String(Boolean(dashPick && dashPick.skill === e.skill))); const isGoing = local.launching && local.launching.skill === e.skill; const isPicked = dashPick && dashPick.skill === e.skill; const mark = el( "span", "rail-mark " + (isGoing || isPicked ? "staged" : "open"), isGoing ? "◐" : isPicked ? "●" : "○" ); mark.title = isGoing ? "starting" : isPicked ? "picked" : "pick to start"; b.appendChild(mark); b.appendChild(el("span", null, e.title)); // The center pane's own "Suggested" pill scrolls out of view, so the // rail repeats the call-out here as a small dot next to the title. if (av.recommended) { const dot = el("span", "rail-suggested-dot", ""); dot.title = "Suggested next step"; b.appendChild(dot); } // Same as a card click: the pick goes to the confirm pane, never // straight to a launch. From the Overview tab too, so the pane shows. b.addEventListener("click", () => { dashPick = e; view = "questions"; render(); }); box.appendChild(b); } rail.appendChild(box); } return; } const list = asked(); if (!list.length) { rail.appendChild(el("p", "rail-empty", "Nothing here yet.")); return; } const groups = new Map(); for (const item of list) { const key = item.topic || "_"; if (!groups.has(key)) groups.set(key, []); groups.get(key).push(item); } for (const [key, group] of groups) { const topic = topics().find((t) => t.id === key); const box = el("div", "rail-group"); const head = el("p", "rail-title"); head.appendChild(el("span", null, topic ? topic.title : "Questions")); const settled = group.filter((i) => !isOpen(i) || (finish() && Boolean(recordedAnswer(i)))).length; head.appendChild(el("span", null, `${settled}/${group.length}`)); box.appendChild(head); for (const item of group) { const b = el("button", "rail-item"); b.type = "button"; // Only while the questions view is actually on screen: on the end page // the question that was last selected is not the thing being looked at. b.setAttribute("aria-current", String(view === "questions" && selected === item.id)); const m = markFor(item); const mark = el("span", "rail-mark " + m.cls, m.glyph); mark.title = m.label; b.appendChild(mark); b.appendChild(el("span", null, item.title)); b.addEventListener("click", () => { selected = item.id; view = "questions"; render(); $("main").focus(); }); box.appendChild(b); } rail.appendChild(box); } } /* ---------------------------------------------------------------- main */ // The pose pane on screen when a render began, held back from the clear so // posePane() can take it up again. See posePane. let heldPose = null; function renderMain() { const main = $("main"); heldPose = main.querySelector(":scope > [data-pose]"); for (const child of [...main.children]) if (child !== heldPose) child.remove(); try { paintMain(main); } finally { // Nothing took it up: this screen is not the same pose. heldPose?.remove(); heldPose = null; } // Inside the render pass, before withFocus restores the card's scroll, so // the restore is measured against the box's final height. fitGrowBox(); } /* ------------------------------------------------------ growing answer box */ // One answer box per card grows into the card's free height: the text // question's box, else a picked "Something else" box, else the card's note. // Every other box keeps its ordinary height, and the notes panel beside the // card is never a candidate. function markGrowBox(card) { if (!card) return; const id = card.dataset.item; const areas = [...card.querySelectorAll("textarea")]; const box = areas.find((t) => t.id === "text-" + id) || card.querySelector(".option.is-other.is-picked textarea.other-text") || areas.find((t) => t.id === "note-" + id); // Only a box that stops being the one gives its fill back, so a keystroke // that re-marks the same box leaves its height alone. for (const n of areas) { if (n === box || !n.classList.contains("grow")) continue; n.classList.remove("grow"); n.style.minHeight = ""; } if (box) box.classList.add("grow"); card.classList.toggle("has-grow", Boolean(box)); } // The height the card's contents would take if nothing stretched them. Not // scrollHeight: that never reads less than the card's own height, so a box // shorter than the fill could never be told how much room it has. function naturalHeight(card) { const last = card.lastElementChild; if (!last) return 0; const top = card.getBoundingClientRect().top + card.clientTop; return ( last.getBoundingClientRect().bottom - top + card.scrollTop + parseFloat(getComputedStyle(last).marginBottom || "0") + parseFloat(getComputedStyle(card).paddingBottom || "0") ); } // The fill is written as the box's min-height, which is what lets the drag // handle only ever make it taller: resize: vertical alone cannot hold a floor // that moves with the window. Below a 160px fill the card scrolls instead. function fitGrowBox() { const box = $("main").querySelector(":scope > .card.has-grow textarea.grow"); if (!box) return; const card = box.closest(".card"); const other = naturalHeight(card) - box.offsetHeight; const fill = Math.max(160, Math.floor(card.clientHeight - other)); const now = parseFloat(box.style.minHeight) || 0; if (Math.abs(now - fill) > 1) box.style.minHeight = fill + "px"; } // It watches the column, not the box. The box growing changes what the card // scrolls, never the column's size, so resizing the box here can never set // off another callback: the loop a box-watching observer would feed. const growObserver = typeof ResizeObserver === "function" ? new ResizeObserver(() => fitGrowBox()) : null; growObserver?.observe($("main")); function paintMain(main) { main.classList.toggle("is-doc", view.startsWith("doc:") || view === "overview"); main.classList.toggle("is-ask", view === "ask"); if (view.startsWith("doc:")) return renderDoc(main, view.slice(4)); if (view === "overview") return renderOverview(main); if (view === "ask") return renderAsk(main); // The session's own page, reached from the PAUSED / SESSION ENDED item at // the top of the rail. The hand-off lives here alone now, rather than // sitting on top of whatever question happens to be selected. if (view === "end" && finish()) { const card = renderHandoff(finish()); card.classList.add("is-primary"); main.appendChild(card); return; } // The dashboard has no questions to walk: its whole main column is the menu, // or the getting-ready screen while a pick turns into a session. A finish // falls through to the ordinary path below, which hands it the card. if (isDashboard() && !finish()) { if (local.launching) renderLaunching(main); else if (dashPick) { // A spec-switch under an open confirm can grey the pick out. Rather // than offer START on a card that cannot launch, drop back to the // menu — the picker's new selection speaks for itself there. if (cardAvailability(dashPick, scan(), selSpec()).on) renderConfirm(main, dashPick); else { dashPick = null; renderDashboard(main); } } else renderDashboard(main); return; } const list = asked(); if (!list.length) { // A session can end before it asked anything at all (a build that needed // nobody), and the hand-off still has to be somewhere they can see it. if (finish()) { const card = renderHandoff(finish()); card.classList.add("is-primary"); main.appendChild(card); return; } return renderWaiting(main); } const item = byId(selected) || list[0]; if (!item) return renderWaiting(main); // One card is all a page shows. Anything the column used to stack as extra // cards -- the "all caught up" lull above and the session notes below -- // folds into this one, because two boxes on one page read as two things // needing attention where there is only ever one. const card = renderCard(item); // No lull note on a finished session: "leave this tab open, the next // question will appear" is true of a pause between questions and false of // an ending, and until there was a way to tell the two apart the page said // it in both. The ending has its own page now, reached from the rail. if (!finish() && !myTurn().length && !stagedCount()) { const lull = el("div", "card-note card-lead"); lull.appendChild(el("p", "note-kicker", "All caught up")); lull.appendChild(el("h3", "note-title", "Nothing needs you right now")); lull.appendChild( el( "p", null, "Plan2Code has everything it asked for. Leave this tab open: the next question will appear here on its own." ) ); // Between questions in a build, the answer to "what now?" is what it is // building. if (activity()) lull.appendChild(el("p", "help", "Right now: " + activity())); card.insertBefore(lull, card.firstChild); } for (const n of items().filter((i) => i.kind === "notice")) { card.appendChild(renderNotice(n)); } card.classList.add("is-primary"); main.appendChild(card); const pager = buildPager(item); if (pager) main.appendChild(pager); } // The end of the session, and the only screen in this page whose job is to // send someone somewhere else. // // It reads in three beats, because that is the order the questions arrive in: // what just happened, the one thing to run, and where to run it. The command // is the whole point, so its Copy button is always on show -- the one on a // fenced code block only appears on hover, which is right for a sample buried // in prose and useless for the single action a screen exists to offer. A // finish with nothing left to run skips the last two beats: it gets a quiet // pointer at the dashboard instead of a Next step block. function renderHandoff(fin) { const card = el("article", "card handoff"); card.appendChild(el("p", "card-kicker", "Session ended")); card.appendChild(el("h2", null, fin.headline)); if (fin.body) card.appendChild(md(fin.body, "md prompt")); // A finished build offers its review first, above the next step, because it // is the one thing on this screen that has to happen before they leave. const offer = reviewOffer(fin); if (offer && local.afterBuild !== "done" && local.afterBuild !== "dashboard") { card.appendChild(renderReviewOffer(offer)); } // Three shapes: a next step to run, a pause with its resume command, or a // session with nothing left to run, which gets a quiet pointer at the // dashboard instead of a Next step block. const shape = handoffShape(fin); if (shape === "all-done") { const done = el("div", "handoff-done"); done.appendChild(md(`${ALL_DONE_LEAD} ${ALL_DONE_REST}`, "md handoff-done-text")); const text = handoffText({ command: DASHBOARD_COMMAND }); const row = el("div", "handoff-command"); const code = el("code", "handoff-code", text); row.appendChild(code); row.appendChild(copyButton(text, "btn small ghost handoff-copy", code)); done.appendChild(row); // Once the server is gone, the row above already is the offer's fallback. if (dashboardLive(fin) && !gone) done.appendChild(renderDashboardOffer(true)); card.appendChild(done); } else { // A pause always offers its resume command, even when the agent left it out. const command = String(fin.command || "").trim() || resumeCommand({ workflow: S.workflow, specDir: S.specDir }); const step = el("div", "handoff-step"); step.appendChild(el("p", "handoff-label", "Next step")); step.appendChild( el( "p", "handoff-where", fin.where || "Run this in the terminal where you started Plan2Code, in a new conversation:" ) ); // Shown exactly as copied. Nothing goes on the clipboard that they cannot // read first: it is about to be pasted into a program with their files. const text = handoffText({ ...fin, command }); 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)); step.appendChild(row); if (text !== command) { step.appendChild( el( "p", "handoff-note", "The last sentence asks Plan2Code to open this page again, so you carry on here rather than in the terminal." ) ); } card.appendChild(step); // A finished (never paused) screen always names the way to the dashboard // from a new conversation, unless the offer's own fallback already does. if (shape === "next") { const offerDash = dashboardLive(fin); if (offerDash) card.appendChild(renderDashboardOffer(false)); if (!(offerDash && gone)) { card.appendChild( textWithCode( "p", "handoff-fresh", `To start something else, run \`${DASHBOARD_COMMAND}\` in a new conversation.` ) ); const freshText = handoffText({ command: DASHBOARD_COMMAND }); const freshRow = el("div", "handoff-command handoff-fresh-row"); const freshCode = el("code", "handoff-code", freshText); freshRow.appendChild(freshCode); freshRow.appendChild(copyButton(freshText, "btn small ghost handoff-copy", freshCode)); card.appendChild(freshRow); } } } card.appendChild( el( "p", "handoff-close", reviewPending() === "open" ? "The review is optional. Skip it and you can close this tab: nothing else here needs you." : "Then you can close this tab. Nothing here needs you any more." ) ); // What they were working on is on disk, but only the agent's copy is. This // is the last moment anyone is looking at this page, so the way to take the // document with them belongs here and not only behind a tab they may never // open again — unless the doc is `saved`, in which case the file itself is // already on disk and a download would be a second copy of it. const keep = docs().find((d) => d.id === fin.doc) || docs()[0]; if (keep && (keep.blocks || []).length) { const tools = el("div", "handoff-tools"); if (keep.saved) { tools.appendChild(docSavedNote(keep)); } else { const save = el("button", "btn small", `Download ${keep.title || "the document"}`); save.type = "button"; save.addEventListener("click", () => downloadDoc(keep)); tools.appendChild(save); } card.appendChild(tools); } // Answers staged and never sent are lost the moment this page closes, and // this page's one promise is that nothing gets lost. Say so plainly rather // than letting them walk away from work they thought was safe. const stuck = Object.keys(local.staged).length; if (stuck) { card.appendChild( el( "p", "handoff-unsent", `${stuck} answer${stuck === 1 ? "" : "s"} here ${stuck === 1 ? "was" : "were"} never sent, ` + `and Plan2Code has finished. If ${stuck === 1 ? "it" : "they"} still matter, say so in the ` + `next session: nothing on this page will reach it now.` ) ); } return card; } // The review button, on the hand-off of a finished build (a finished quick // task; an implementation phase gets its review offer earlier, as a verdict // on the sign-off card). // // It is a request, not a command: the page cannot run a review, it asks the // agent that is still sitting in its wait loop, the same way "Write a brief" // does. So it is only offered while there is a server to carry the press, and // once there is not, it turns into the command that does the same thing from // the terminal instead of a button that would go nowhere. function renderReviewOffer(offer) { const box = el("section", "review-offer"); box.appendChild(el("p", "handoff-label", "Before you go")); box.appendChild(el("h3", "review-offer-title", offer.label)); const asked = local.afterBuild === "review"; if (gone) { box.appendChild( el( "p", "review-offer-text", asked ? "The session closed before the review could start. To run it now, use this in the terminal, in a new conversation:" : "This session has closed, so the review cannot start from here any more. To run it, use this in the terminal, in a new conversation:" ) ); const text = "/plan2code-review"; 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)); box.appendChild(row); return box; } box.appendChild( el( "p", "review-offer-text", "A careful review of the files this session changed: bugs, gaps against the spec, and anything risky. " + "The findings come back on this page and you choose which ones get fixed. Nothing changes until you do." ) ); const row = el("div", "btn-row"); const go = el("button", "btn primary review-go", asked ? "Review requested…" : "Review it now"); go.type = "button"; go.disabled = asked || pendingResult; go.addEventListener("click", () => sendAfterBuild("review")); row.appendChild(go); if (!asked) { const no = el("button", "btn ghost", "No thanks, I am done"); no.type = "button"; no.disabled = pendingResult; no.addEventListener("click", () => sendAfterBuild("done")); row.appendChild(no); } box.appendChild(row); return box; } // The way back to the dashboard, on a finished screen whose agent opted in // with `finish.dashboard`. Like the review button it is a request to an agent // still in its wait loop, so once the server is gone it turns into the // command that opens the dashboard from a new conversation instead. function renderDashboardOffer(primary) { const box = el("section", "dashboard-offer"); if (gone) { box.appendChild( el( "p", null, "This session has closed, so the button cannot reach Plan2Code any more. To open the dashboard, run this in a new conversation:" ) ); const text = handoffText({ command: DASHBOARD_COMMAND }); 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)); box.appendChild(row); return box; } const asked = local.afterBuild === "dashboard"; const go = el( "button", primary ? "btn primary" : "btn", asked ? "Opening the dashboard…" : "Back to the dashboard" ); go.type = "button"; go.disabled = asked || pendingResult; go.addEventListener("click", () => sendAfterBuild("dashboard")); box.appendChild(go); box.appendChild(textWithCode("p", "dashboard-note", DASHBOARD_NOTE)); return box; } // A line whose backticked commands read as code; everything else is text. function textWithCode(tag, className, text) { const node = el(tag, className); text.split("`").forEach((part, n) => { if (part) node.appendChild(n % 2 ? el("code", "md-code", part) : document.createTextNode(part)); }); return node; } // Any answer to a finished session's offers, as one send through the ordinary // submit. Like a brief, it names no question: `__review`, `__done` and // `__dashboard` are about the session. const AFTER_FINISH_REPLIES = { review: REVIEW_REPLY, done: DONE_REPLY, dashboard: DASHBOARD_REPLY }; async function sendAfterBuild(kind) { if (gone || pendingResult || local.afterBuild) return; try { const res = await fetch("/submit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ actions: [{ i: `__${kind}`, type: kind }], reply: AFTER_FINISH_REPLIES[kind], }), }); if (res.status === 409) { pendingResult = true; banner("Your last answers are still being picked up. Try again in a moment.", "info"); return; } if (!res.ok) throw new Error(String(res.status)); local.afterBuild = kind; pendingResult = true; save(); const started = { review: "Review requested. It starts here in a moment.", dashboard: "Opening the dashboard. It appears here in a moment.", }[kind]; if (started) { banner(started, "good"); setTimeout(() => banner(null), 5000); } } catch { banner("That did not go through. Nothing was lost; try again.", "warn"); } finally { render(); } } /* ------------------------------------------------------------- dashboard */ // The menu a `dashboard` session exists to show. The cards come from the // page's own catalog (answers.js), never from the agent's payload — a fixed // product list does not belong in a patch channel. What the agent CAN say // rides in `state.menu`: a `note` line under the title, a `recommend` skill // to flag, and a `details` one-liner per card ("Phase 2 of 4 is next"). function roleNudge() { const nudge = el("div", "dash-nudge"); nudge.setAttribute("role", "status"); nudge.appendChild(el("span", "dash-nudge-text", "Pick your role to get starter templates ordered for you.")); const actions = el("div", "dash-nudge-actions"); const setUp = el("button", "btn small primary", "Set up preferences"); setUp.type = "button"; setUp.addEventListener("click", () => { renderSwatches(); $("looks-modal").showModal(); }); const notNow = el("button", "btn tiny ghost", "Not now"); notNow.type = "button"; notNow.addEventListener("click", () => { looks.role = ROLE_NOT_SET; saveLooks(); render(); }); actions.append(setUp, notNow); nudge.appendChild(actions); return nudge; } function renderDashboard(main) { maybeWake(); const menu = (S && S.menu) || {}; const wrap = el("div", "dash"); if (needsRoleNudge(looks)) wrap.appendChild(roleNudge()); // Advice only: words, never a button, and nothing is blocked. if (meterFrame && meterFrame.level === "red") { const warn = el("div", "dash-nudge meter-banner", RED_BANNER); warn.setAttribute("role", "status"); wrap.appendChild(warn); } wrap.appendChild(el("p", "card-kicker", "Plan2Code")); wrap.appendChild(el("h2", "dash-title", "What are we doing today?")); if (typeof menu.note === "string" && menu.note.trim()) { wrap.appendChild(el("p", "dash-note", menu.note)); } else if (!S.menu && agentWorking()) { // The cards work from the first paint; the agent's read of the // project arrives a moment later, and this says so meanwhile. const note = el("p", "dash-note"); note.appendChild(document.createTextNode("Pick what to do next. ")); const working = el("span", "dash-working"); working.appendChild(el("span", "spinner tiny")); working.appendChild( el( "span", null, "Plan2Code is still looking over the project and will flag where it would start when it is done." ) ); note.appendChild(working); wrap.appendChild(note); } else { wrap.appendChild( el("p", "dash-note", "Pick what to do next. It starts right here, and this page becomes its home.") ); } const specs = specList(); if (specs.length) wrap.appendChild(renderSpecPicker(specs)); wrap.appendChild(hideUnavailableToggle()); if (!local.launching && !launchScoping) syncWorkspaceScope(); // "Unavailable" is the scan's verdict for the selected spec, not the // momentary greying while a launch is in flight or the server is away, so // cards never blink out of the menu mid-handoff. const hide = looks.hideUnavailable; const sel = selSpec(); const available = (e) => cardPresentation(e, scan(), sel, menu).on; let shown = 0; for (const g of CATALOG_GROUPS) { const entries = SKILL_CATALOG.filter((e) => e.group === g.id && (!hide || available(e))); if (!entries.length) continue; shown += entries.length; const section = el("section", "dash-group"); section.appendChild(el("h3", "dash-group-title", g.title)); const grid = el("div", "dash-grid"); for (const e of entries) grid.appendChild(dashCard(e, menu)); section.appendChild(grid); wrap.appendChild(section); } if (!shown) { wrap.appendChild( el("p", "dash-empty", "Nothing fits this pick right now. Turn off the toggle above to see every workflow.") ); } wrap.appendChild(approvalTip()); // Mid wake-up: the groups wait hidden until the glide lets them rise in, // and the note shows only as far as it has been typed. Once the entrance // has played, a re-render draws the menu plainly, never replaying it. if (wake && !wake.entered) wrap.classList.add("waking", ...(wake.cards ? ["is-in"] : [])); if (wake && wake.typed != null) { const note = wrap.querySelector(".dash-note"); if (note) revealNote(note, wake.typed); } main.appendChild(wrap); // Deferred: this runs inside render(), and the dialog is not part of it. queueMicrotask(maybeWelcome); } /* ------------------------------------------------------------- welcome */ // The first dashboard a person ever sees gets a Welcome dialog. Closing it by // any route (button, Esc, backdrop) saves looks.welcomeSeen, which rides in // looks.json like every other preference. Waits out the wake-up animation and // never lands on top of another open dialog. function maybeWelcome() { if (!looksReady || looks.welcomeSeen === true || !S || !isDashboard() || finish() || wake) return; if (document.querySelector("dialog[open]")) return; openWelcome(); } function openWelcome() { if ($("help-modal").open) $("help-modal").close(); const slot = $("welcome-bot"); if (!slot.firstElementChild) { const bot = $("planny").cloneNode(true); bot.removeAttribute("id"); bot.setAttribute("class", "planny is-point v1"); slot.appendChild(bot); } const dlg = $("welcome-modal"); if (!dlg.open) dlg.showModal(); $("welcome-done").focus(); } /* ------------------------------------------------------------- wake-up */ const WAKE_TYPE_DELAY_MS = 350; const WAKE_TYPE_EVERY_MS = 14; const WAKE_ENTRANCE_MS = 900; // One snore, for a nudge with no sound to time it (sounds off, or refused). const SNORE_MS = 2600; // The longest a nudge waits on the snore ending: a hidden tab may never say. const SNORE_MAX_MS = 6000; const BOOTUP_FADE_MS = 500; const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); // Only a newly opened dashboard carries `wake` (console.mjs deletes it on // every resume), and only the first page load in this tab plays it. function maybeWake() { if (wakeTried || S.wake !== true || finish()) return; wakeTried = true; const key = "p2c-console:woke:" + S.sid; try { if (sessionStorage.getItem(key)) return; sessionStorage.setItem(key, "1"); } catch { // Blocked storage only costs the reload guard. } const stage = $("wake"); const pilot = $("planny").closest(".pilot"); wake = { cards: false, entered: false, typed: 0, timers: [], abort: new AbortController() }; wakeHoldsChime = !matchMedia("(prefers-reduced-motion: reduce)").matches; if (wakeHoldsChime && soundOn("snore")) { snore = new Audio("/sleeping.mp3"); snore.loop = true; snore.play().catch(() => {}); } pilot.classList.add("is-waking"); playWake({ stage, bot: stage.querySelector(".wake-bot"), skipEl: stage.querySelector(".wake-skip"), target: $("planny"), stir: stirWake, onStart: () => sound("bootup"), onGlide: wakeGlide, onSkip: skipWakeSounds, signal: wake.abort.signal, }).then(({ skipped }) => { stopSnore(); fadeSound("bootup", BOOTUP_FADE_MS); pilot.classList.remove("is-waking"); // An abort or reduced motion jumps straight to the finished // dashboard. A run that reached its end leaves the note typing on. if (skipped || (wake && !wake.cards)) finishWake(); }); } // The nudge: one whole snore from the top, however far the loop had got (or // the first one heard, since the loop is usually refused until this click). // Called inside the click, so the browser lets it play. Settles when it ends, // and never rejects: a refused or silent snore just takes one snore's time. function stirWake() { if (!snore) return delay(SNORE_MS); const heard = new Promise((resolve) => snore.addEventListener("ended", resolve, { once: true })); snore.loop = false; snore.currentTime = 0; return snore.play().then( () => Promise.race([heard, delay(SNORE_MAX_MS)]), () => delay(SNORE_MS) ); } function stopSnore() { if (!snore) return; snore.pause(); snore = null; } // The Skip button: silence anything the intro already queued or started. The // promise's .then does the snore and the bootup fade; this only clears cues // still waiting to play. function skipWakeSounds() { soundQueued = null; soundHeld = null; } // The glide: the menu rises in and the note starts typing. On a skip the run // is already ending and its promise settles everything, so nothing here. function wakeGlide({ instant }) { if (!wake) return; wake.cards = true; if (instant) return; wake.timers.push( setTimeout(() => { wake.entered = true; settleWake(); }, WAKE_ENTRANCE_MS), setTimeout(typeNote, WAKE_TYPE_DELAY_MS) ); render(); } // One more character of the note on the live element. Whatever the note says // right now is what gets typed, so a `menu` note that lands mid-way simply // carries on from the same count. function typeNote() { if (!wake || wake.typed == null) return; wake.typed += 1; const note = $("main").querySelector(":scope > .dash .dash-note"); if (!note || wake.typed >= revealNote(note, wake.typed)) { wake.typed = null; if (note) revealNote(note, Infinity); return settleWake(); } wake.timers.push(setTimeout(typeNote, WAKE_TYPE_EVERY_MS)); } // Done once the entrance has played and the note is all there. Nothing to // redraw: what is on screen already is the finished dashboard. function settleWake() { if (wake && wake.entered && wake.typed == null) { wake = null; maybeWelcome(); } } function finishWake() { if (!wake) return; for (const t of wake.timers) clearTimeout(t); wake = null; render(); } // Shows the first `count` characters of a note's text, across its text nodes, // and returns how many there are in all. The full text is kept per node the // first time it is cut, so later calls can grow it back. An element the // typing has not reached yet (the "still looking" pill and its spinner) is // kept out of sight, rather than showing as an empty box. const noteFullText = new WeakMap(); function revealNote(note, count) { const walker = document.createTreeWalker(note, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT); let total = 0; for (let n = walker.nextNode(); n; n = walker.nextNode()) { if (n.nodeType === Node.ELEMENT_NODE) { n.classList.toggle("is-untyped", total >= count); continue; } if (!noteFullText.has(n)) noteFullText.set(n, n.data); const full = noteFullText.get(n); n.data = full.slice(0, Math.max(0, count - total)); total += full.length; } return total; } // A page-wide preference, so it rides in `looks` (looks.json) and follows the // person to every session and port rather than resetting per dashboard. function hideUnavailableToggle() { const label = el("label", "dash-toggle"); const box = el("input"); box.type = "checkbox"; // The id is what lets withFocus hand focus back after the rebuild. box.id = "dash-hide-unavailable"; box.setAttribute("role", "switch"); box.checked = looks.hideUnavailable; box.addEventListener("change", () => { looks.hideUnavailable = box.checked; saveLooks(); render(); }); label.appendChild(box); label.appendChild(el("span", "dash-toggle-track")); label.appendChild(el("span", "dash-toggle-text", "Hide unavailable workflows")); return label; } /* The spec picker: every spec the server found under specs/, plus "start from scratch". The selection decides which cards below are lit, and rides along on the launch of any card that takes a spec. Picking is page-local — no send — so it costs nothing to change your mind. */ function renderSpecPicker(specs) { const sel = selSpec(); const box = el("section", "spec-pick"); box.appendChild(el("h3", "dash-group-title", "Pick up a spec, or start fresh")); const row = el("div", "spec-row"); const scratch = el("button", "spec-chip" + (sel ? "" : " is-sel")); scratch.type = "button"; scratch.setAttribute("aria-current", String(!sel)); scratch.appendChild(el("span", "spec-chip-name", "Start from scratch")); scratch.appendChild(el("span", "spec-chip-state", "a new idea")); scratch.addEventListener("click", () => { local.specSel = null; save(); render(); loadOverview(); }); row.appendChild(scratch); for (const spec of specs) { const on = sel && sel.dir === spec.dir; const b = el("button", "spec-chip" + (on ? " is-sel" : "")); b.type = "button"; b.setAttribute("aria-current", String(Boolean(on))); b.appendChild(el("span", "spec-chip-name", spec.name)); b.appendChild(el("span", "spec-chip-state", SPEC_STATE_LABELS[spec.state] || spec.state)); if (spec.detail) b.appendChild(el("span", "spec-chip-detail", spec.detail)); b.addEventListener("click", () => { local.specSel = spec.dir; save(); render(); loadOverview(); }); row.appendChild(b); } box.appendChild(row); return box; } function dashCard(entry, menu) { const presentation = cardPresentation(entry, scan(), selSpec(), menu); // The agent's `recommend` and detail describe the initially selected spec. // Other picker choices derive both from the scan, so stale context never // follows a person to a different spec or to "start from scratch". A greyed // recommendation also yields to the selected spec's actual next step. const going = local.launching && local.launching.skill === entry.skill; const b = el( "button", "dash-card" + (presentation.recommended ? " is-suggested" : "") + (going ? " is-going" : "") ); b.type = "button"; b.disabled = Boolean(local.launching) || gone || pendingResult || !presentation.on; if (!presentation.on && presentation.reason) b.title = presentation.reason; const head = el("span", "dash-card-head"); head.appendChild(el("span", "dash-chip", entry.chip)); if (presentation.recommended) head.appendChild(el("span", "pill suggested", "Suggested")); b.appendChild(head); b.appendChild(el("span", "dash-card-title", entry.title)); b.appendChild(el("span", "dash-card-blurb", entry.blurb)); if (presentation.detail) b.appendChild(el("span", "dash-card-detail", presentation.detail)); if (!presentation.on && presentation.reason) b.appendChild(el("span", "dash-card-off", presentation.reason)); const foot = el("span", "dash-card-foot"); foot.appendChild(el("code", "dash-card-cmd", entry.command)); foot.appendChild(el("span", "dash-card-go", going ? "…" : "→")); b.appendChild(foot); b.addEventListener("click", () => { dashPick = entry; render(); }); return b; } /* The confirm pane. A card or rail click lands here rather than launching straight away: picking a skill is the one irreversible-feeling click on the dashboard, and it deserves a beat — what it is, what it will do, and a START that means it. Planny turns up leaning (his "this way" pose) in a small sky, because a bare paragraph with two buttons is a dialog, not a moment. BACK returns to the menu; Escape does the same (see the global keydown). */ function renderConfirm(main, entry) { const menu = (S && S.menu) || {}; const presentation = cardPresentation(entry, scan(), selSpec(), menu); const pane = el("div", "dash-confirm"); const stage = el("div", "launch-stage confirm-stage"); const sky = el("div", "sky launch-sky"); const r = (a, b) => a + Math.random() * (b - a); for (let i = 0; i < 16; i++) { const star = el("i", "star" + (i % 5 === 0 ? " hot" : "")); const dur = r(4, 10); star.style.setProperty("--y", r(2, 98).toFixed(1) + "%"); star.style.setProperty("--p", r(0, 1).toFixed(3)); star.style.setProperty("--s", r(1.2, 2.4).toFixed(2) + "px"); star.style.setProperty("--dur", dur.toFixed(2) + "s"); star.style.setProperty("--delay", (-r(0, dur)).toFixed(2) + "s"); sky.appendChild(star); } stage.appendChild(sky); const bot = $("planny").cloneNode(true); bot.removeAttribute("id"); bot.setAttribute("class", "planny is-point v0 confirm-planny"); stage.appendChild(bot); pane.appendChild(stage); const head = el("div", "confirm-head"); head.appendChild(el("span", "dash-chip", entry.chip)); if (presentation.recommended) head.appendChild(el("span", "pill suggested", "Suggested")); pane.appendChild(head); pane.appendChild(el("h2", "dash-title", entry.title)); pane.appendChild(el("p", "confirm-about", entry.about || entry.blurb)); if (presentation.detail) pane.appendChild(el("p", "confirm-detail", presentation.detail)); // A card that takes a spec names the one the picker is holding, so START // reads as "build THIS spec", not the skill in the abstract. const target = entry.spec ? selSpec() : null; if (target) { const specLine = el("p", "confirm-spec"); specLine.appendChild(el("span", null, "for ")); specLine.appendChild(el("code", null, target.dir)); specLine.appendChild(el("span", null, ` · ${SPEC_STATE_LABELS[target.state] || target.state}`)); pane.appendChild(specLine); } const cmd = el("p", "confirm-cmd"); cmd.appendChild(el("code", null, entry.command)); pane.appendChild(cmd); const actions = el("div", "confirm-actions"); const start = el("button", "btn primary", "Start " + entry.title); start.type = "button"; start.disabled = gone || pendingResult; start.addEventListener("click", () => launchSkill(entry)); const back = el("button", "btn ghost", "Back"); back.type = "button"; back.addEventListener("click", () => { dashPick = null; render(); }); actions.appendChild(back); actions.appendChild(start); pane.appendChild(actions); main.appendChild(pane); // Focus lands on START after a pick (the clicked control was rebuilt away, // leaving focus on ), but never yanked back from a deliberate click // elsewhere: a state frame can re-render this pane at any time. if (document.activeElement === document.body) start.focus(); } // A pick is a send like a brief or a stop: it names no question, so `__launch` // marks the action as being about the session, and it reaches the agent // through the same wait loop. The dashboard reads `skill` off it. async function launchSkill(entry) { if (gone || pendingResult || local.launching || finish()) return; const target = entry.spec ? selSpec() : null; // The card was clickable, so this should never fire — but a spec picked in // one tab could have shifted the ground under a stale render in another. if (!cardAvailability(entry, scan(), selSpec()).on) { banner("That card is not available for the spec you picked.", "warn"); render(); return; } dashPick = null; const action = { i: "__launch", type: "launch", skill: entry.skill, workflow: entry.workflow, title: entry.title, }; // The picker's spec goes to the skill being launched, not to the card: // cards that take no spec (utilities, setup) launch untargeted even while // a spec is selected. if (target) action.spec = target.dir; // The skill opens on the folders remembered for what it was launched for. // Held until the launch is in flight: the swap's own frame re-renders the // dashboard, which would otherwise sync back to the picker's spec. launchScoping = true; await syncWorkspaceScope(target ? target.dir : ""); try { const res = await fetch("/submit", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ actions: [action], reply: launchReply(entry, target), }), }); if (res.status === 409) { launchScoping = false; pendingResult = true; banner("Your last pick is still being picked up. One moment.", "info"); return; } if (!res.ok) throw new Error(String(res.status)); sound("startSkill"); local.launching = { skill: entry.skill, title: entry.title, at: Date.now() }; launchScoping = false; pendingResult = true; save(); render(); } catch { launchScoping = false; banner("That did not go through. Nothing was lost; try again.", "warn"); } } /* The getting-ready screen. The pick is sent and the dashboard agent is turning it into a live skill: it resumes this session under the skill's workflow, which flips `S.workflow` off "dashboard" and ends this screen (adopt() clears `local.launching` on exactly that change). It is deliberately fun rather than a spinner with a shrug: a launch takes a few honest seconds — the skill file is read, the session resumed, the first payload composed — and a dead-quiet wait is when people wonder whether the click worked. Planny flies, the quips rotate, and after a while the hint points at the terminal, which narrates the same hand-off. */ const LAUNCH_QUIPS = [ "Passing Planny the baton…", "Reading the manual…", "Polishing the star…", "Warming up the engines…", "Laying out the good pens…", "Consulting the map…", "Putting the kettle on…", "Rolling out the checklist…", ]; let launchTicker = null; // Planny flies centre stage: the same drawing as the dock's, cloned so the // markup stays the single source of him, and the same sky the dock fills. function flightStage() { const stage = el("div", "launch-stage"); const sky = el("div", "sky launch-sky"); const r = (a, b) => a + Math.random() * (b - a); for (let i = 0; i < 30; i++) { const star = el("i", "star" + (i % 6 === 0 ? " hot" : "")); const dur = r(3, 9); star.style.setProperty("--y", r(2, 98).toFixed(1) + "%"); star.style.setProperty("--p", r(0, 1).toFixed(3)); star.style.setProperty("--s", r(1.2, 2.6).toFixed(2) + "px"); star.style.setProperty("--dur", dur.toFixed(2) + "s"); star.style.setProperty("--delay", (-r(0, dur)).toFixed(2) + "s"); sky.appendChild(star); } stage.appendChild(sky); const bot = $("planny").cloneNode(true); bot.removeAttribute("id"); bot.setAttribute("class", "planny is-work v1 launch-planny"); stage.appendChild(bot); return stage; } // A skill's own Planny, acting out the skill while it starts and works: the // pose is cloned from its