Update the web console server, screens, help, prefs and loop setup, with matching page and logic suites

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-02 12:00:12 -08:00
1 parent 2468027a5a
commit 8e34bf1005
119 files changed
+9957 -3728

No files matched your search

+14 -5
View File
@@ -10,7 +10,7 @@
// No DOM, no `local`, no fetch. If a function in here needs any of those, it
// belongs in app.js instead.
import { FIXED_REASON, SKILLS, labelFor, skillByName, skillFor } from "./skills.js";
import { FIXED_REASON, FLOW_SKILLS, SKILLS, labelFor, skillByName, skillFor } from "./skills.js";
import { SPEC_STATES, stateFor } from "./spec-states.js";
/* ----------------------------------------------------- the sent answer */
@@ -257,7 +257,7 @@ export function suggestionFrom(item) {
// The badge each workflow wears. Shared with the server, which writes it into
// the page it serves so the first paint already names the session instead of
// flashing a placeholder until the script arrives. Derived from skills.js.
export const WORKFLOW_LABEL = Object.fromEntries(SKILLS.map((s) => [s.workflow, s.label]));
export const WORKFLOW_LABEL = Object.fromEntries(FLOW_SKILLS.map((s) => [s.workflow, s.label]));
export function workflowLabel(workflow) {
return labelFor(workflow) || workflow || "Session";
@@ -267,7 +267,7 @@ export function workflowLabel(workflow) {
// skill as `additionalReferences`). Any other next step has no browser page
// to open, and asking for one would send the next session looking for
// something that is not there. Derived from skills.js: every entry is one.
export const CONSOLE_WORKFLOWS = SKILLS.map((s) => s.command);
export const CONSOLE_WORKFLOWS = FLOW_SKILLS.map((s) => s.command);
// Rides on the end of the command as part of the skill's argument. Every
// console skill takes it as the answer to "web console or terminal?" instead
@@ -550,7 +550,7 @@ export const CATALOG_GROUPS = [
// action so the launched skill knows which spec it was picked for. Derived from
// skills.js: the entries with a card, in their order, each card's fields
// beside the skill's name, command and workflow.
export const SKILL_CATALOG = SKILLS.filter((s) => s.card).map((s) => ({
export const SKILL_CATALOG = FLOW_SKILLS.filter((s) => s.card).map((s) => ({
skill: s.skill,
command: s.command,
workflow: s.workflow,
@@ -558,6 +558,15 @@ export const SKILL_CATALOG = SKILLS.filter((s) => s.card).map((s) => ({
...s.card,
}));
// The desktop app's Implementation Loop card: not a skill, so not in
// SKILL_CATALOG. The dashboard draws it after its group's other cards, and its
// click opens the setup screen instead of launching anything.
const LOOP_SKILL = SKILLS.find((s) => s.appOnly && s.card);
export const LOOP_ENTRY = LOOP_SKILL
? { skill: LOOP_SKILL.skill, command: "Desktop app only", workflow: null, appOnly: true, ...LOOP_SKILL.card }
: null;
export const OUTSIDE_APP_LINE = "Runs only in the Plan2Code desktop app.";
// A workflow by the name its dashboard card gives it ("Implement"), for the
// screens that speak of it as a thing being started rather than as a badge.
export function workflowTitle(workflow) {
@@ -674,7 +683,7 @@ export function cardAvailability(entry, scan, sel, lookup = stateFor) {
const hasAgents = Boolean(scan && scan.hasAgents);
const state = sel && sel.state && sel.state !== "unrecognized" ? sel.state : null;
const next = sel ? Boolean(state) && NEXT_FOR_STATE[state] === entry.skill : entry.skill === "plan2code-0-pathfinder";
const rule = skillByName(entry.skill);
const rule = skillByName(entry.skill) || (entry.appOnly ? LOOP_SKILL : null);
if (!rule || !rule.states) return ON;
// The three cards whose rules read the scan rather than the spec.
+34
View File
@@ -36,6 +36,40 @@ export function onAppMessage(kind, handler) {
});
}
/**
* Hear the app's answers to the Implementation Loop's named requests:
* `loop-facts` (what agent a loop would use), `loop-start-result`,
* `loop-notify-test-result` and the three stop-screen results. `store` is the page object and `redraw` its
* render; they are handed in so this file keeps importing nothing.
*/
export function wireLoopMessages(store, redraw) {
onAppMessage("loop-facts", (data) => {
store.loopFacts = data.facts && typeof data.facts === "object" ? data.facts : null;
redraw();
});
onAppMessage("loop-start-result", (data) => {
// Cancel in the app's confirm: nothing started, so the setup is as it was.
if (data.ok === true && data.started === false) {
store.loopStart = null;
if (store.loopSetup) store.loopSetup.starting = false;
redraw();
return;
}
store.loopStart = { ok: data.ok === true, error: data.ok === true ? null : String(data.error || "The app did not start the loop.") };
redraw();
});
onAppMessage("loop-notify-test-result", (data) => {
store.loopNotifyTest = { waiting: false, ok: data.ok === true, sent: data.sent === true, error: data.ok === true ? null : String(data.error || "The app could not send the test.") };
redraw();
});
for (const kind of ["loop-resume-result", "loop-fix-result", "loop-finalize-result"]) {
onAppMessage(kind, (data) => {
store.loopAction = { kind, ok: data.ok === true, error: data.ok === true ? null : String(data.error || "The app could not do that.") };
redraw();
});
}
}
/**
* Ask the app for what its bar's New Session button does, confirm and all.
* `command`, when there is one, goes on the clipboard first so it can be
+8 -2
View File
@@ -22,7 +22,8 @@ import {
adopt, banner, connect, fillSky, fitGrowBox, loadState, markSent, maybeWelcome, render, renderFooter,
renderSidebar, renderWhere, save, startClock, startLooks, stagedPayload, syncWorkspaceScope,
wakeHoldsChime, wireAsk, wireCards, wireChrome, wireCleanup, wireDashboard, wireDocs, wireEnding,
wireActivities, wireHelp, wireLooks, wireNotepad, wireWorkspace,
wireActivities, wireLoopSetup, wireHelp, launchSkill, openHelpOn, openLoopSetup, wireLooks, wireNotepad, wirePrefs, wireWorkspace,
openPrefs, markSaved, confirmUnsaved, loadAgentsView, wireAgentsView, hasUnsaved, unsavedName, saveOpen, discardOpen, focusOpen,
} from "./screens/core.js";
import { sound } from "./sound.js";
@@ -34,7 +35,10 @@ import { sound } from "./sound.js";
// last the session itself (its first state and the stream). The draft's save
// and the few calls a screen makes into another are handed to state.js first.
onSave(save);
useHooks({ banner, fitGrowBox, markSent, maybeWelcome, renderFooter, renderSidebar, renderWhere, stagedPayload, syncWorkspaceScope });
useHooks({
launchSkill, openHelpOn, openLoopSetup, banner, fitGrowBox, markSent, maybeWelcome, renderFooter, renderSidebar, renderWhere, stagedPayload, syncWorkspaceScope,
openPrefs, markSaved, confirmUnsaved, loadAgentsView, wireAgentsView, hasUnsaved, unsavedName, saveOpen, discardOpen, focusOpen,
});
const boot = bootData();
startLooks(boot);
@@ -46,11 +50,13 @@ wireHelp();
wireDashboard();
wireEnding();
wireLooks();
wirePrefs();
wireCleanup();
wireDocs();
wireAsk();
wireNotepad();
wireActivities();
wireLoopSetup();
wireChrome();
startClock();
+22 -4
View File
@@ -210,6 +210,24 @@ export function shouldChime(prevDot, nextDot) {
// The page's own "has drifted away" threshold for an agent that is waiting.
const ADRIFT_MS = 3 * 60 * 1000;
// How long an agent answering an Ask message may go without checking in. It
// is out of `wait` while it answers, and an approved edit can run for minutes.
export const ASK_BUSY_MS = 10 * 60 * 1000;
/**
* Whether the agent has picked up an Ask message (or an edit decision) and
* not replied to it yet: busy with it, not gone.
*/
export function chatAnswering(frameChat) {
const chat = chatOf(frameChat);
const messages = Array.isArray(chat.messages) ? chat.messages : [];
const pickedUp = Number.isInteger(chat.pickedUp) ? chat.pickedUp : 0;
for (const [seq, answered] of answeredFlags(messages)) {
if (!answered && seq <= pickedUp) return true;
}
return false;
}
/**
* Whether nobody is there to answer a chat message. A finished session's agent
* is often still listening through its last wait (the review and dashboard
@@ -217,10 +235,10 @@ const ADRIFT_MS = 3 * 60 * 1000;
* not end the chat — going quiet does. Offline once the agent has been silent
* longer than the page would tolerate before calling it stuck (working) or
* adrift (anything else), which is also the only signal left once the server
* is gone.
* is gone. An Ask message in hand (`answering`) stretches either to ASK_BUSY_MS.
*/
export function chatOffline({ finish, agent, agentLastSeenMs, now }) {
export function chatOffline({ finish, agent, agentLastSeenMs, now, answering = false }) {
const silent = now - agentLastSeenMs;
if (agent && agent.status === "working") return silent > quietLimitMs(agent, STALE_MS);
return silent > quietLimitMs(agent, ADRIFT_MS);
const limit = quietLimitMs(agent, agent && agent.status === "working" ? STALE_MS : ADRIFT_MS);
return silent > (answering ? Math.max(limit, ASK_BUSY_MS) : limit);
}
+4 -17
View File
@@ -22,6 +22,7 @@ export const HELP_TABS = Object.freeze([
tab("dashboard", "The dashboard", true),
tab("meter", "Session meter", false),
tab("build", "Watching a build", false),
tab("loop", "Implementation Loop", true),
tab("git", "The git board", false),
tab("subagents", "Helpers (subagents)", false),
tab("ask", "Ask a quick question", false),
@@ -53,20 +54,6 @@ export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow,
return "about";
}
// The tab index a key moves to, or -1 when the key is not a tab key.
export function helpKeyTarget(key, index, count) {
switch (key) {
case "ArrowDown":
case "ArrowRight":
return (index + 1) % count;
case "ArrowUp":
case "ArrowLeft":
return (index - 1 + count) % count;
case "Home":
return 0;
case "End":
return count - 1;
default:
return -1;
}
}
// The tab index a key moves to, or -1 when the key is not a tab key: the
// shared tab helper's, under the name Help and the git board import.
export { tabKeyTarget as helpKeyTarget } from "./tabs.js";
File diff suppressed because it is too large. Load diff
+64 -19
View File
@@ -9,7 +9,7 @@ import { normalizeRole, ROLE_NOT_SET } from "./starters.js";
import { bootData, hooks } from "./state.js";
import { el } from "./render.js";
import { tellApp } from "./app-bridge.js";
import { ACTIVITIES, bestKey, memoKey } from "./activities.js";
import { ACTIVITIES, bestKeys, memoKey, musicKey, musicLevel } from "./activities.js";
const $ = (id) => document.getElementById(id);
@@ -31,13 +31,20 @@ export const DEFAULT_LOOKS = {
...soundPrefs(null),
width: DEFAULT_CARD_WIDTH,
hideUnavailable: true,
// Activities: the top bar's die, the game last picked, and one best score
// per listed game (activityBestSnake), each a flat key for cleanLooks().
// Activities: the top bar's die, whether its games play sounds (under Play
// sounds, which silences them too), the game last picked, and one best score
// per listed game (activityBestSnake) or, for a game with courses, per
// course (activityBestGolfPirate), each a flat key for cleanLooks().
hideActivities: false,
activitySounds: true,
// Whether a game plays its chiptune music too: off until asked for.
gameMusic: false,
lastActivity: "",
...Object.fromEntries(ACTIVITIES.map((a) => [bestKey(a.id), 0])),
...Object.fromEntries(ACTIVITIES.flatMap((a) => bestKeys(a).map((key) => [key, 0]))),
// And one memo per game (activityMemoSnake): Snake's surprises found.
...Object.fromEntries(ACTIVITIES.map((a) => [memoKey(a.id), 0])),
// And, for a game with music, its music volume (activityMusicDrive), 0 to 100.
...Object.fromEntries(ACTIVITIES.filter((a) => a.music !== undefined).map((a) => [musicKey(a.id), a.music])),
};
export let looks = { ...DEFAULT_LOOKS };
@@ -55,14 +62,18 @@ export function adoptLooks(saved) {
if (typeof looks.hideUnavailable !== "boolean") looks.hideUnavailable = DEFAULT_LOOKS.hideUnavailable;
looks.width = cardWidth(looks.width);
if (typeof looks.hideActivities !== "boolean") looks.hideActivities = DEFAULT_LOOKS.hideActivities;
if (typeof looks.activitySounds !== "boolean") looks.activitySounds = DEFAULT_LOOKS.activitySounds;
if (typeof looks.gameMusic !== "boolean") looks.gameMusic = DEFAULT_LOOKS.gameMusic;
if (typeof looks.lastActivity !== "string") looks.lastActivity = DEFAULT_LOOKS.lastActivity;
// A best score is a whole number of points, never below none.
for (const a of ACTIVITIES) {
const key = bestKey(a.id);
const n = Number(looks[key]);
looks[key] = Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
for (const key of bestKeys(a)) {
const n = Number(looks[key]);
looks[key] = Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
}
const memo = Number(looks[memoKey(a.id)]);
looks[memoKey(a.id)] = Number.isFinite(memo) && memo > 0 ? Math.floor(memo) : 0;
if (a.music !== undefined) looks[musicKey(a.id)] = Math.round(musicLevel(a, looks[musicKey(a.id)]) * 100);
}
if (saved && typeof saved === "object" && Object.hasOwn(saved, "role")) looks.role = normalizeRole(saved.role);
else delete looks.role;
@@ -117,8 +128,9 @@ export async function syncLooks() {
setTimeout(hooks.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.
// The mirror on the server. A failed POST costs nothing the next session would
// notice on this port; the localStorage copy still covers the reload case. It
// resolves with whether the write landed, for Preferences' Saved mark.
function pushLooks() {
try {
// Only what this tab changed since it last synced, so a tab with stale
@@ -127,19 +139,29 @@ function pushLooks() {
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;
if (partial && !Object.keys(set).length) return Promise.resolve({ ok: true });
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", {
const failed = (error) => {
undo();
return { ok: false, error: error || "Could not save." };
};
return fetch("/looks", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
})
.then((res) => res.ok || undo())
.catch(undo);
} catch {}
.then(async (res) => {
if (res.ok) return { ok: true };
const reply = await res.json().catch(() => ({}));
return failed(reply.error);
})
.catch(() => failed());
} catch {
return Promise.resolve({ ok: false, error: "Could not save." });
}
}
const systemDark = () => matchMedia("(prefers-color-scheme: dark)").matches;
@@ -174,16 +196,26 @@ export function applyLooks() {
ACCENT_VARS.forEach((name, i) => root.style.setProperty(name, shades[i]));
}
// Resolves { ok: true } once the server has it (or there was nothing new to
// send), or { ok: false, error } when the write did not land.
export function saveLooks() {
try {
localStorage.setItem(LOOKS_KEY, JSON.stringify(looks));
} catch {}
pushLooks();
const pushed = 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.
hooks.fitGrowBox();
renderSwatches();
return pushed;
}
// Told of each swatch's save, for Preferences' Saved mark: set by the dialog's
// screen, since this module never imports one.
let swatchSaved = null;
export function onSwatchSaved(fn) {
swatchSaved = fn;
}
// Built once, repainted in place. Rebuilding the row on every choice destroyed
@@ -200,7 +232,8 @@ export function renderSwatches() {
b.setAttribute("aria-label", a.name);
b.addEventListener("click", () => {
looks.accent = id;
saveLooks();
const saved = saveLooks();
if (swatchSaved) swatchSaved(saved);
});
box.appendChild(b);
}
@@ -231,15 +264,27 @@ export function renderSwatches() {
}
$("looks-role").value = looks.role ?? ROLE_NOT_SET;
$("looks-activities").checked = !looks.hideActivities;
// Like a cue, the game sounds keep their tick while Play sounds is off.
$("looks-activity-sounds").checked = looks.activitySounds;
$("looks-activity-sounds").disabled = !looks.sound;
$("looks-game-music").checked = looks.gameMusic;
$("looks-game-music").disabled = !looks.sound;
}
// "Back to default": every look returns to its default, but the role is
// marked as asked, the welcome stays seen, and the Activities' best scores
// and last pick stay (only Reset best scores clears those).
export function resetLooks() {
// and last pick stay (only Reset best scores clears those). Given `keys` (one
// Preferences tab's, prefsResetScope() in prefs.js), only those change: the
// role is cleared but marked as asked, the rest take their defaults, and
// every other key stays as it is.
export function resetLooks(keys) {
if (keys) {
for (const key of keys) looks[key] = key === "role" ? ROLE_NOT_SET : DEFAULT_LOOKS[key];
return;
}
const kept = { lastActivity: looks.lastActivity };
for (const a of ACTIVITIES) {
kept[bestKey(a.id)] = looks[bestKey(a.id)];
for (const key of bestKeys(a)) kept[key] = looks[key];
kept[memoKey(a.id)] = looks[memoKey(a.id)];
}
looks = { ...DEFAULT_LOOKS, ...kept, role: ROLE_NOT_SET, welcomeSeen: looks.welcomeSeen };
+5 -5
View File
@@ -6,7 +6,7 @@
// access at module scope, and its one import is the data-only skills.js: the
// server, console.mjs, the page and `node --test` all import this file.
import { SKILLS, isMetered, isPhased } from "./skills.js";
import { FLOW_SKILLS, isMetered, isPhased } from "./skills.js";
// The weights (FR-12): the events that are not a skill's own launch live
// here, and each skill's weight is its `weight` in skills.js. Tune there or here.
@@ -24,7 +24,7 @@ const EVENT_WEIGHTS = {
"git-conflict": 1,
};
// A skill's fields as a table by workflow, leaving out the entries without one.
const bySkill = (field) => Object.fromEntries(SKILLS.filter((s) => s[field] !== null).map((s) => [s.workflow, s[field]]));
const bySkill = (field) => Object.fromEntries(FLOW_SKILLS.filter((s) => s[field] !== null).map((s) => [s.workflow, s[field]]));
export const WEIGHTS = Object.freeze({ ...EVENT_WEIGHTS, ...bySkill("weight") });
// Workflows whose launch itself scores WEIGHTS[workflow]. Pathfinder,
@@ -32,7 +32,7 @@ export const WEIGHTS = Object.freeze({ ...EVENT_WEIGHTS, ...bySkill("weight") })
// reports; dashboard and handoff never score; git, changelog, xray and diagnose score 1 on
// launch (Git then adds its commit tally and conflict help). Derived from
// skills.js (`metered`).
export const LAUNCH_COUNTED = Object.freeze(new Set(SKILLS.filter((s) => isMetered(s.workflow)).map((s) => s.workflow)));
export const LAUNCH_COUNTED = Object.freeze(new Set(FLOW_SKILLS.filter((s) => isMetered(s.workflow)).map((s) => s.workflow)));
// Git's commits weigh what they add up to: each `git-commits` run carries
// `commits`, and a skill run scores one point per COMMITS_PER_POINT commits,
@@ -65,7 +65,7 @@ export const MAX_TASKS = 999;
// bonus. The phase's `run` then takes the row over with its final score, so
// the total only ever climbs. Workflows whose headline counts tasks, derived
// from skills.js (`phased`):
export const PROGRESS_WORKFLOWS = Object.freeze(new Set(SKILLS.filter((s) => isPhased(s.workflow)).map((s) => s.workflow)));
export const PROGRESS_WORKFLOWS = Object.freeze(new Set(FLOW_SKILLS.filter((s) => isPhased(s.workflow)).map((s) => s.workflow)));
// Implement + Review reviews every phase as a stage of the build. A `review`
// run inside it is that stage, so it scores the phase's TASK_BONUS when it
@@ -120,7 +120,7 @@ export const ANSWERS_PER_POINT = 2;
// The skill names the answers row uses ("7 answers in Plan"), derived from
// skills.js (`name`).
const WORKFLOW_NAMES = Object.freeze(Object.fromEntries(SKILLS.map((s) => [s.workflow, s.name])));
const WORKFLOW_NAMES = Object.freeze(Object.fromEntries(FLOW_SKILLS.map((s) => [s.workflow, s.name])));
// The skill run an entry belongs to, from its ledger id ("L3:..." -> "L3").
const launchOf = (id) => (typeof id === "string" && id.includes(":") ? id.slice(0, id.indexOf(":")) : "L0");
+1
View File
@@ -240,6 +240,7 @@ export const CARD_WIDTHS = {
narrow: { label: "Narrow", px: 720 },
comfortable: { label: "Comfortable", px: 880 },
wide: { label: "Wide", px: 1080 },
ultrawide: { label: "Ultra wide", px: 1440 },
};
export const DEFAULT_CARD_WIDTH = "comfortable";
+31
View File
@@ -0,0 +1,31 @@
// Plan2Code Web Console - what the User Preferences dialog is.
//
// Its tabs in order, which one opens, and what Back to default resets on
// each. No DOM access at module scope, and its one import is the data-only
// palette.js: the page and `node --test` both import this file.
import { SOUND_EVENTS, soundKey } from "./palette.js";
const tab = (id, label, hint, sections) => Object.freeze({ id, label, hint, sections: Object.freeze(sections) });
// Each section id names one fieldset in the dialog (its data-section).
export const PREFS_TABS = Object.freeze([
tab("appearance", "Appearance", "Theme, width, color, role", ["theme", "width", "accent", "role"]),
tab("agents", "Agents & models", "Your CLIs and models", ["agents"]),
tab("system", "System", "Cleanup, desktop app", ["cleanup", "desktop"]),
tab("sounds", "Sounds & activities", "What plays", ["sounds", "activities"]),
]);
// The tab the dialog opens on: the one asked for when there is such a tab,
// else Appearance. Nothing is remembered between opens.
export function prefsOpenTab(asked) {
return PREFS_TABS.some((t) => t.id === asked) ? asked : "appearance";
}
// The looks keys Back to default resets on a tab, or null where it has
// nothing to reset (and is hidden).
export function prefsResetScope(tab) {
if (tab === "appearance") return ["theme", "width", "accent", "role"];
if (tab === "sounds") return ["sound", ...Object.keys(SOUND_EVENTS).map(soundKey), "hideActivities", "activitySounds", "gameMusic"];
return null;
}
+6 -2
View File
@@ -406,7 +406,7 @@ export function isMac() {
// backdrop is the <dialog> itself to the event, and so is its own padding, so
// the point has to fall outside its box -- for the press as well as the
// release, or selecting text inside and letting go outside would close it.
export function lightDismiss(dlg) {
export function lightDismiss(dlg, beforeClose) {
const outside = (e) => {
const r = dlg.getBoundingClientRect();
return e.target === dlg && (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom);
@@ -414,7 +414,11 @@ export function lightDismiss(dlg) {
let pressedOutside = false;
dlg.addEventListener("pointerdown", (e) => (pressedOutside = outside(e)));
dlg.addEventListener("click", (e) => {
if (pressedOutside && outside(e)) dlg.close();
if (pressedOutside && outside(e)) {
// `beforeClose` may hold the close: false, or a Promise of false.
if (!beforeClose) dlg.close();
else Promise.resolve(beforeClose()).then((go) => go !== false && dlg.close());
}
pressedOutside = false;
});
}
@@ -0,0 +1,713 @@
// Plan2Code Web Console - User Preferences' Agents & models tab.
//
// A summary table of every agent (the built-in CLIs, the ones the person
// added, and a row kept for the v3 orchestrator) whose Edit opens that agent's
// full form. Nothing saves as it changes: a form edits a draft, and its Save
// sends the saved list with only that draft swapped in, so a half-typed
// command line never reaches agents.json or models.json.
import { el } from "../render.js";
import { hooks } from "../state.js";
const $ = (id) => document.getElementById(id);
// The CLIs the launcher reads a model list for, in table order (routes.mjs MODEL_CLIS).
const MODEL_CLIS = ["claude", "devin", "codex"];
// What the table calls each built-in, and the command it runs (the launcher's CLIS ids).
const BUILT_IN = { claude: "Claude", devin: "Devin", codex: "Codex" };
// The last server reply for each list. Unknown keys on an agent ride along untouched.
let saved = { agents: [], user: emptyLists(), shipped: emptyLists() };
// At most one per form being edited: "cli:<cli>" for a built-in's own models,
// "agent:<id>" for an added agent, "agent:new" for one being added.
const drafts = new Map();
// The form on screen (a drafts key), or null while the summary shows.
let openKey = null;
// The server's complaint about the open form, { field, error }, and a 409's
// warnings while Save anyway is on offer.
let formError = null;
let formReplace = null;
// Delete agent waiting for its second click; the arguments fold's state, kept across redraws.
let confirming = false;
let argsOpen = false;
// The badge each summary row last showed, by row key: { command, state }.
const found = new Map();
// Each open of the tab loads afresh: only the newest load's answers are drawn.
let loadSeq = 0;
function emptyLists() {
return Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []]));
}
// Whether the status line says "Deleted.", which the next form opened clears
// (load warnings stay until the next open).
let deletedNote = false;
function setAgentsStatus(text, isError, { deleted = false } = {}) {
const status = $("agents-status");
status.textContent = text;
status.classList.toggle("error", Boolean(isError));
deletedNote = deleted;
}
function newAgent() {
return { name: "", command: "", args: [], prompt: "/plan2code", bypassArgs: [], modelArgs: ["--model", "{model}"], models: [] };
}
function normalizeAgent(agent) {
for (const key of ["args", "bypassArgs", "modelArgs", "models"]) if (!Array.isArray(agent[key])) agent[key] = [];
return agent;
}
const cliOf = (key) => key.slice("cli:".length);
const agentId = (key) => key.slice("agent:".length);
function savedEntry(key) {
if (key.startsWith("cli:")) return saved.user[cliOf(key)] || [];
if (key === "agent:new") return newAgent();
return saved.agents.find((a) => a.id === agentId(key));
}
// JSON with object keys sorted, so a label removed and typed back counts as unchanged.
function canonical(value) {
return JSON.stringify(value, (_, v) =>
v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, v[k]])) : v
);
}
function isDirty(key) {
return drafts.has(key) && canonical(drafts.get(key)) !== canonical(savedEntry(key));
}
function nameOf(key) {
if (key.startsWith("cli:")) return BUILT_IN[cliOf(key)];
const draft = drafts.get(key);
return String((draft && draft.name) || "").trim() || savedEntry(key)?.name || "a new agent";
}
const modelNames = (list) => list.map((m) => m.label || m.id);
/* ------------------------------------------------------------- summary */
// One row per agent, in order: the built-ins, the added agents, the orchestrator.
function summaryRows() {
return [
...MODEL_CLIS.map((cli) => ({
key: "cli:" + cli,
name: BUILT_IN[cli],
command: cli,
models: [...saved.shipped[cli], ...saved.user[cli]],
noneShip: saved.shipped[cli].length === 0,
})),
...saved.agents.map((a) => ({ key: "agent:" + a.id, name: a.name, command: a.command, models: a.models })),
];
}
function renderSummary() {
const body = $("agents-table").tBodies[0];
body.replaceChildren();
const check = [];
for (const row of summaryRows()) {
const tr = el("tr");
tr.dataset.key = row.key;
const name = el("td", "prefs-agents-name");
name.append(el("span", null, row.name), el("code", null, row.command));
if (row.noneShip) name.append(el("span", "help", `No models ship for ${row.name} yet; add your own in Edit.`));
const models = el("td", "prefs-agents-models");
const names = modelNames(row.models);
models.textContent = names.length ? `${names.length}: ${names.join(", ")}` : "None";
const badge = el("span", "prefs-badge");
const last = found.get(row.key);
if (last && last.command === row.command) drawBadge(badge, last.state);
else {
badge.textContent = "Checking...";
check.push(row);
}
const edit = el("button", "btn small", "Edit");
edit.type = "button";
edit.setAttribute("aria-label", "Edit " + row.name);
edit.addEventListener("click", () => openForm(row.key));
const editCell = el("td", "prefs-agents-edit");
editCell.append(edit);
const badgeCell = el("td");
badgeCell.append(badge);
tr.append(name, models, badgeCell, editCell);
body.appendChild(tr);
}
const soon = el("tr", "prefs-agents-soon");
const soonName = el("td", "prefs-agents-name");
soonName.append(el("span", null, "v3 orchestrator"), el("span", "help", "Nothing to set yet."));
soon.append(soonName, el("td", "prefs-agents-models"), el("td"), el("td"));
body.appendChild(soon);
if (check.length) checkFound(check, loadSeq);
}
const BADGES = {
ok: "Found",
missing: "Not found on PATH",
unknown: "Not checked",
};
function drawBadge(badge, state) {
badge.textContent = BADGES[state];
badge.classList.remove("ok", "missing");
if (state !== "unknown") badge.classList.add(state);
}
// Whether each row's command is on PATH, all at once. /agents/test only
// resolves the command and never runs it.
async function checkFound(rows, seq) {
await Promise.all(
rows.map(async (row) => {
let state = "unknown";
try {
const res = await fetch("/agents/test", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ command: row.command }),
});
if (res.ok) state = (await res.json()).found ? "ok" : "missing";
} catch {}
if (seq !== loadSeq) return;
found.set(row.key, { command: row.command, state });
const badge = $("agents-table").querySelector(`tr[data-key="${CSS.escape(row.key)}"] .prefs-badge`);
if (badge) drawBadge(badge, state);
})
);
}
/* ------------------------------------------------------------- the form */
function showSummary(on) {
$("agents-table").hidden = !on;
$("agents-add").hidden = !on;
$("agents-intro").hidden = !on;
$("agents-form").hidden = on;
}
function openForm(key) {
if (deletedNote) setAgentsStatus("", false);
openKey = key;
formError = null;
formReplace = null;
confirming = false;
argsOpen = key === "agent:new";
if (!drafts.has(key)) drafts.set(key, structuredClone(key === "agent:new" ? newAgent() : savedEntry(key)));
showSummary(false);
drawForm();
$("agents-form").querySelector("input")?.focus();
}
// Back on the summary, focus goes to the row just left (its Edit), or to Add
// agent when that row is gone (a new agent not saved, one just deleted).
function closeForm() {
const left = openKey;
if (openKey) drafts.delete(openKey);
openKey = null;
formError = null;
formReplace = null;
confirming = false;
$("agents-form").replaceChildren();
showSummary(true);
renderSummary();
const row = left && $("agents-table").querySelector(`tr[data-key="${CSS.escape(left)}"] .prefs-agents-edit button`);
(row || $("agents-add")).focus();
}
function edited() {
if (openKey) renderDirty(openKey);
}
function agentField(label, field, child) {
const wrap = el("div", "agent-field");
wrap.dataset.field = field;
wrap.append(el("span", null, label), child);
return wrap;
}
function agentInput(agent, key, label, placeholder, trim) {
const input = el("input");
input.value = agent[key] || "";
input.placeholder = placeholder;
input.setAttribute("aria-label", label);
input.dataset.field = key;
input.addEventListener("input", () => {
agent[key] = trim ? input.value.trim() : input.value;
edited();
});
return input;
}
// A list of text rows (arguments), with Remove on each and an Add under them.
function agentArgsEditor(agent, key, label, placeholder, addLabel) {
const box = el("div", "agent-rows");
box.dataset.field = key;
const draw = () => {
box.replaceChildren();
agent[key].forEach((value, i) => {
const row = el("div", "agent-row");
const input = el("input");
input.value = value;
input.placeholder = placeholder;
input.setAttribute("aria-label", label);
input.dataset.field = key;
input.addEventListener("input", () => {
agent[key][i] = input.value.trim();
edited();
});
const remove = el("button", "btn small ghost", "Remove");
remove.type = "button";
remove.addEventListener("click", () => {
agent[key].splice(i, 1);
draw();
edited();
});
row.append(input, remove);
box.appendChild(row);
});
const add = el("button", "btn small ghost", addLabel);
add.type = "button";
add.addEventListener("click", () => {
agent[key].push("");
draw();
edited();
box.querySelector(".agent-row:last-of-type input")?.focus();
});
box.appendChild(add);
};
draw();
return agentField(label, key, box);
}
// A models list: an id and a name for the menu on each row. An added agent's
// rows drop a blank name; a built-in's keep it, as models.json does.
function agentModelsEditor(list, { label: fieldLabel = "Models", optionalName = true } = {}) {
const box = el("div", "agent-rows");
box.dataset.field = "models";
const draw = () => {
box.replaceChildren();
list.forEach((m, i) => {
const row = el("div", "agent-row model");
const id = el("input");
id.value = m.id || "";
id.placeholder = optionalName ? "Model id, for {model}" : "Model id";
id.setAttribute("aria-label", "Model id");
id.dataset.field = "models";
const label = el("input");
label.value = m.label || "";
label.placeholder = optionalName ? "Name shown in the menu (optional)" : "Name shown in the menu";
label.setAttribute("aria-label", "Name shown in the menu");
label.dataset.field = "models";
const remove = el("button", "btn small ghost", "Remove");
remove.type = "button";
id.addEventListener("input", () => {
m.id = id.value.trim();
edited();
});
label.addEventListener("input", () => {
const text = label.value.trim();
if (text || !optionalName) m.label = text;
else delete m.label;
edited();
});
remove.addEventListener("click", () => {
list.splice(i, 1);
draw();
edited();
});
row.append(id, label, remove);
box.appendChild(row);
});
const add = el("button", "btn small ghost", "Add a model");
add.type = "button";
add.addEventListener("click", () => {
list.push(optionalName ? { id: "" } : { id: "", label: "" });
draw();
edited();
box.querySelector(".agent-row:last-of-type input")?.focus();
});
box.appendChild(add);
};
draw();
return agentField(fieldLabel, "models", box);
}
// The command's Test: where it would run from. Never saves.
function agentTest(agent) {
const wrap = el("div", "prefs-agents-test");
const test = el("button", "btn small", "Test");
test.type = "button";
const result = el("span", "help agent-test-result");
result.setAttribute("role", "status");
test.addEventListener("click", async () => {
const command = String(agent.command || "").trim();
if (!command) {
result.textContent = "Type a command first.";
return;
}
result.textContent = "Looking...";
try {
const res = await fetch("/agents/test", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ command }),
});
const body = await res.json();
if (!res.ok) result.textContent = body.error || "Could not test.";
else result.textContent = body.found ? "Found at " + body.path : "Not found on PATH";
} catch {
result.textContent = "Could not test.";
}
});
wrap.append(test, result);
return wrap;
}
function builtInFields(cli, draft) {
const shipped = el("div", "models-list prefs-agents-shipped");
shipped.setAttribute("aria-label", "Comes with Plan2Code");
for (const m of saved.shipped[cli]) {
const row = el("div", "models-row locked");
row.append(el("span", null, m.id), el("span", null, m.label || ""));
shipped.appendChild(row);
}
const note = el("div", "models-note");
note.innerHTML =
"<ul>" +
"<li>Restart <code>plan2code</code> to see a change in its model menu.</li>" +
"<li>At any time, run <code>plan2code --model &lt;id&gt;</code>, or pick your model inside your agent before running a skill.</li>" +
"<li>Updating Plan2Code refreshes the built-in list. Models you added stay, unless the built-in list now includes them.</li>" +
"<li>Devin models are limited to Low, Medium and High effort.</li>" +
"</ul>";
const comes = el("div", "agent-field");
comes.append(el("span", null, "Comes with Plan2Code"));
if (saved.shipped[cli].length) comes.append(shipped);
else comes.append(el("p", "help prefs-agents-none", `No models ship for ${BUILT_IN[cli]} yet; add your own below.`));
return [note, comes, agentModelsEditor(draft, { label: "Models you added", optionalName: false })];
}
function addedFields(draft) {
const command = agentField("Command", "command", agentInput(draft, "command", "Command", "Program to run, such as myagent", true));
command.append(agentTest(draft));
const fold = el("details", "prefs-agents-args");
fold.open = argsOpen;
fold.addEventListener("toggle", () => (argsOpen = fold.open));
fold.append(
el("summary", null, "Command-line arguments"),
agentArgsEditor(draft, "args", "Arguments", "--message={prompt}", "Add an argument"),
agentArgsEditor(draft, "bypassArgs", "Bypass arguments", "--yes-always", "Add an argument"),
agentArgsEditor(draft, "modelArgs", "Model arguments", "--model={model}", "Add an argument"),
);
return [
agentField("Name", "name", agentInput(draft, "name", "Name", "Name shown in the menu", true)),
command,
agentField("Start prompt", "prompt", agentInput(draft, "prompt", "Start prompt", "/plan2code (blank starts with nothing typed)", false)),
agentModelsEditor(draft.models),
fold,
];
}
// Save, Discard and the Unsaved badge (shown only while the draft differs),
// the Saved mark's spot, Save anyway after a 409, and Delete agent with its
// confirm on the form itself (never the browser's confirm()).
function formFoot(key) {
const foot = el("div", "agent-foot prefs-agents-foot");
const save = el("button", "btn small primary prefs-agents-save", "Save");
save.type = "button";
save.addEventListener("click", () => saveForm(key));
const discard = el("button", "btn small ghost prefs-agents-discard", "Discard");
discard.type = "button";
discard.addEventListener("click", () => discardOpen());
const badge = el("span", "prefs-unsaved-badge", "Unsaved");
foot.append(save, discard, badge);
if (formReplace) {
const anyway = el("button", "btn small danger prefs-agents-replace", "Save anyway");
anyway.type = "button";
anyway.addEventListener("click", () => saveForm(key, { replace: true }));
foot.append(anyway);
}
if (key.startsWith("agent:") && key !== "agent:new") {
if (confirming) {
const yes = el("button", "btn small danger", "Yes, delete");
yes.type = "button";
yes.addEventListener("click", () => deleteAgent(key));
const keep = el("button", "btn small ghost", "Keep");
keep.type = "button";
keep.addEventListener("click", () => {
confirming = false;
drawForm();
});
foot.append(el("span", "help", "Delete this agent?"), yes, keep);
} else {
const del = el("button", "btn small ghost danger prefs-agents-delete", "Delete agent");
del.type = "button";
del.addEventListener("click", () => {
confirming = true;
drawForm();
});
foot.append(del);
}
}
return foot;
}
function renderDirty(key) {
const foot = $("agents-form").querySelector(".prefs-agents-foot");
if (!foot || key !== openKey) return;
const dirty = isDirty(key);
for (const sel of [".prefs-agents-save", ".prefs-agents-discard", ".prefs-unsaved-badge"]) foot.querySelector(sel).hidden = !dirty;
}
// Which field or button has focus, so a redraw (an id assigned, an error
// marked) puts the person back where they were: { nth, start, end }. What
// they typed is already in the draft the redraw reads.
const FORM_FOCUSABLE = "input, button, summary";
function formFocus(form) {
const active = document.activeElement;
if (!active || !form.contains(active)) return null;
const at = { nth: [...form.querySelectorAll(FORM_FOCUSABLE)].indexOf(active) };
if (active instanceof HTMLInputElement) Object.assign(at, { start: active.selectionStart, end: active.selectionEnd });
return at;
}
function restoreFormFocus(form, at) {
if (!at) return;
const target = form.querySelectorAll(FORM_FOCUSABLE)[at.nth];
// A button the redraw hid (Save, once saved) hands focus to the heading.
if (!target || target.closest("[hidden]")) return form.querySelector(".prefs-agents-title")?.focus();
target.focus();
if (target instanceof HTMLInputElement && at.start !== undefined) {
try {
target.setSelectionRange(at.start, at.end);
} catch {}
}
}
function drawForm() {
const form = $("agents-form");
const key = openKey;
const draft = drafts.get(key);
const focus = formFocus(form);
form.replaceChildren();
const back = el("button", "btn small ghost prefs-agents-back", "Back to summary");
back.type = "button";
back.addEventListener("click", async () => {
if (await hooks.confirmUnsaved()) closeForm();
});
const title = el("h3", "prefs-agents-title");
title.tabIndex = -1;
if (key.startsWith("cli:")) title.append(el("span", null, BUILT_IN[cliOf(key)]), el("code", null, cliOf(key)));
else title.append(el("span", null, key === "agent:new" ? "New agent" : savedEntry(key).name));
const fields = el("div", "prefs-agents-fields");
fields.append(...(key.startsWith("cli:") ? builtInFields(cliOf(key), draft) : addedFields(draft)));
form.append(back, title, fields);
if (formError) {
for (const input of form.querySelectorAll("input")) {
if (input.dataset.field === formError.field) input.classList.add("invalid");
}
form.append(el("p", "agent-error", formError.error));
}
if (formReplace) form.append(el("p", "agent-error", formReplace.join(" ")));
form.append(formFoot(key));
renderDirty(key);
restoreFormFocus(form, focus);
}
/* ------------------------------------------------------------- saving */
// The list as the server wants it: blank rows and models without an id dropped.
function cleanAgent(a) {
return {
...a,
args: a.args.filter((v) => v !== ""),
bypassArgs: a.bypassArgs.filter((v) => v !== ""),
modelArgs: a.modelArgs.filter((v) => v !== ""),
models: a.models.filter((m) => m.id),
};
}
async function postJson(url, payload) {
const res = await fetch(url, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(payload),
});
return { res, body: await res.json() };
}
// The form's foot, for the Saved mark (or the error in its place).
const formMark = (result) => hooks.markSaved($("agents-form").querySelector(".prefs-agents-foot"), result);
// Fresh from what was just saved: the form redraws on a clean draft.
function savedAs(key) {
drafts.delete(openKey);
openKey = key;
drafts.set(key, structuredClone(savedEntry(key)));
formError = null;
formReplace = null;
drawForm();
}
async function saveModelsFor(cli) {
const sent = drafts.get("cli:" + cli).filter((m) => m.id);
try {
const { res, body } = await postJson("/models", { models: { ...saved.user, [cli]: sent } });
if (!res.ok) {
formMark({ ok: false, error: body.error || "Could not save." });
return false;
}
saved.user[cli] = (body.user && body.user[cli]) || sent;
} catch {
formMark({ ok: false, error: "Could not save." });
return false;
}
savedAs("cli:" + cli);
formMark({ ok: true, text: "Saved. Restart plan2code to use it." });
return true;
}
async function saveAgentFor(key, { replace = false } = {}) {
const draft = drafts.get(key);
const isNew = key === "agent:new";
if (isNew && (!String(draft.name || "").trim() || !String(draft.command || "").trim())) {
formError = { field: String(draft.name || "").trim() ? "command" : "name", error: "Give it a name and a command first." };
drawForm();
return false;
}
const at = isNew ? saved.agents.length : saved.agents.findIndex((a) => a.id === agentId(key));
const agents = saved.agents.map((a) => cleanAgent(a));
agents.splice(at, isNew ? 0 : 1, cleanAgent(draft));
try {
const { res, body } = await postJson("/agents", replace ? { agents, replace: true } : { agents });
if (res.status === 409) {
formError = { field: null, error: body.error || "Not saved." };
formReplace = Array.isArray(body.warnings) ? body.warnings : [];
drawForm();
return false;
}
if (!res.ok) {
formError = { field: body.index === at ? body.field : null, error: body.error || "Could not save." };
formReplace = null;
drawForm();
return false;
}
saved.agents = (Array.isArray(body.agents) ? body.agents : agents).map(normalizeAgent);
} catch {
formMark({ ok: false, error: "Could not save." });
return false;
}
const id = saved.agents[at].id;
found.delete(key);
found.delete("agent:" + id);
savedAs("agent:" + id);
formMark({ ok: true });
return true;
}
function saveForm(key, options) {
return key.startsWith("cli:") ? saveModelsFor(cliOf(key)) : saveAgentFor(key, options);
}
async function deleteAgent(key) {
const agents = saved.agents.filter((a) => a.id !== agentId(key)).map(cleanAgent);
confirming = false;
try {
const { res, body } = await postJson("/agents", { agents });
if (!res.ok) {
formError = { field: null, error: body.error || "Could not delete." };
drawForm();
return;
}
saved.agents = (Array.isArray(body.agents) ? body.agents : agents).map(normalizeAgent);
} catch {
formError = { field: null, error: "Could not delete." };
drawForm();
return;
}
found.delete(key);
closeForm();
setAgentsStatus("Deleted.", false, { deleted: true });
}
/* ------------------------------------------------------------- the dialog's side */
// An open form whose draft differs from what is saved.
export function hasUnsaved() {
return openKey !== null && isDirty(openKey);
}
// What the unsaved prompt calls the open form.
export function unsavedName() {
return openKey ? nameOf(openKey) : "";
}
export function saveOpen() {
return openKey ? saveForm(openKey) : Promise.resolve(true);
}
export function discardOpen() {
if (!openKey) return;
if (openKey === "agent:new") return closeForm();
drafts.set(openKey, structuredClone(savedEntry(openKey)));
formError = null;
formReplace = null;
confirming = false;
drawForm();
}
// Back into the form after Keep editing or a failed Save: the marked field, else the first.
export function focusOpen() {
const form = $("agents-form");
(form.querySelector("input.invalid") || form.querySelector("input"))?.focus();
}
// Each time the dialog opens: the summary, from the server.
export async function loadAgentsView() {
const seq = ++loadSeq;
openKey = null;
drafts.clear();
found.clear();
formError = null;
formReplace = null;
confirming = false;
$("agents-form").replaceChildren();
showSummary(true);
setAgentsStatus("", false);
const [agents, models] = await Promise.all([
fetch("/agents").then((r) => (r.ok ? r.json() : null)).catch(() => null),
fetch("/models").then((r) => (r.ok ? r.json() : null)).catch(() => null),
]);
if (seq !== loadSeq) return;
const problems = [];
if (agents) {
saved.agents = (Array.isArray(agents.agents) ? agents.agents : []).map(normalizeAgent);
if (Array.isArray(agents.warnings)) problems.push(...agents.warnings);
} else {
saved.agents = [];
problems.push("Agents could not be loaded.");
}
saved.user = emptyLists();
saved.shipped = emptyLists();
if (models) {
for (const cli of MODEL_CLIS) {
if (Array.isArray(models.user?.[cli])) saved.user[cli] = models.user[cli];
if (Array.isArray(models.shipped?.[cli])) saved.shipped[cli] = models.shipped[cli];
}
} else {
problems.push("Models could not be loaded.");
}
setAgentsStatus(problems.join(" "), problems.length > 0);
renderSummary();
}
export function wireAgentsView() {
$("agents-add").addEventListener("click", () => openForm("agent:new"));
}
+12 -4
View File
@@ -1,8 +1,8 @@
// Plan2Code Web Console - the Ask chat, the Subagents tab, and attaching files to notes.
import { page, saveNow, redraw, freshChat, hooks, scrollMemory, setDraft } from "../state.js";
import { chatOffline, chatView, sendState as chatSendState, newestReplyId, CHAT_MAX_CHARS, nextAbout, CHAT_MAX_ATTACHMENTS, contextOptions } from "../chat.js";
import { finish, activity, agentAdrift, isDashboard, selSpec, byId, isOpen } from "../selectors.js";
import { chatAnswering, chatOffline, chatView, sendState as chatSendState, newestReplyId, CHAT_MAX_CHARS, nextAbout, CHAT_MAX_ATTACHMENTS, contextOptions } from "../chat.js";
import { finish, activity, agentAdrift, isDashboard, selSpec, byId, isOpen, loopAskLocked, loopDriving } from "../selectors.js";
import { el, md, isMac, lightDismiss, shortTime } from "../render.js";
import { startersFor } from "../starters.js";
import { looks } from "../looks.js";
@@ -37,6 +37,7 @@ function askFrame() {
agent: page.S.agent,
agentLastSeenMs: Date.parse(page.agentLastSeen),
now: Date.now(),
answering: chatAnswering(base),
});
return { ...base, offline };
}
@@ -45,7 +46,13 @@ export function askState() {
const frame = askFrame();
const shown = chatView(frame, { pendingSends: page.local.chat.pending, agentActivity: activity() });
const pendingSendCount = shown.rows.filter((r) => r.pending && !r.failed).length;
return { frame, view: shown, send: chatSendState({ frameChat: frame, gone: page.gone, pendingSendCount }) };
const send = chatSendState({ frameChat: frame, gone: page.gone, pendingSendCount });
// The Implementation Loop locks Ask like everything else it drives (FR-15),
// unless a question waits for the person (FR-14).
if (send.canType && loopAskLocked()) {
return { frame, view: shown, send: { state: "ok", text: "Ask is off while the loop builds.", canType: false } };
}
return { frame, view: shown, send };
}
// The conversation a send belongs to. The page's own record wins over the
@@ -760,7 +767,8 @@ export function renderSubagentsButton() {
btn.setAttribute("aria-pressed", String(Boolean(page.subagentsFrame.on)));
btn.title = label;
btn.setAttribute("aria-label", label);
btn.disabled = page.gone;
// The Subagents switch is the person's setting for the next agent; the loop's phases are already started.
btn.disabled = page.gone || loopDriving();
}
// The Subagents dialog, filled from the frame each time it opens. A null
+54 -3
View File
@@ -16,6 +16,8 @@ import {
byId,
docs,
isGitBoard,
loopDriving,
loopWaiting,
} from "../selectors.js";
import {
lastOpenCard,
@@ -316,14 +318,38 @@ function inFlightFor(item) {
return sub ? { value: sub, summary: "" } : null;
}
// While the Implementation Loop drives, an open card is a record, not a form
// (FR-15): "handled" when the loop answers it itself, "locked" otherwise. The
// one exception (FR-14) is a required question the loop does not handle, which
// stays a live form while it waits for the person.
function loopLockFor(item) {
if (!loopDriving() || !isOpen(item) || finish()) return null;
if (item.handledBy === "loop") return "handled";
return loopWaiting() && item.required !== false ? null : "locked";
}
function renderLoopLocked(card, item, why) {
const box = el("div", "answered is-loop " + (why === "handled" ? "is-handled" : "is-locked"));
if (why === "handled") {
box.appendChild(el("p", "answered-head loop-tag", "The loop handles this"));
box.appendChild(el("p", "answered-lock", "The Implementation Loop answers this one itself, so there is nothing to do here."));
} else {
box.appendChild(el("p", "answered-lock", "The Implementation Loop is building. This unlocks by itself if it needs you."));
}
card.appendChild(box);
lockedOptions(card, item, []);
}
export function renderCard(item) {
const staged = page.local.staged[item.id];
const flight = inFlightFor(item);
const loopLock = loopLockFor(item);
const card = el(
"article",
"card question" +
(!isOpen(item) || finish() ? " is-answered" : staged ? " is-staged" : "") +
(flight ? " is-inflight" : "")
(flight ? " is-inflight" : "") +
(loopLock ? " is-loop-" + loopLock : "")
);
// Which question this card is for, so a render can tell whether the card it
@@ -348,6 +374,8 @@ export function renderCard(item) {
// send can no longer go anywhere and the form would be a trap.
if (!isOpen(item) || finish()) {
renderSettled(card, item);
} else if (loopLock) {
renderLoopLocked(card, item, loopLock);
} else if (flight) {
renderInFlight(card, item, flight);
} else {
@@ -355,7 +383,7 @@ export function renderCard(item) {
if (build) build(card, item, staged);
}
if (item.required === false && isOpen(item) && !flight && !finish()) {
if (item.required === false && isOpen(item) && !flight && !finish() && !loopLock) {
const skipped = Boolean(staged && staged.skipped);
// A small accent chip, like a comment box's quick answer ("No changes"),
// rather than an underlined link that reads as fine print.
@@ -372,7 +400,7 @@ export function renderCard(item) {
}
}
if (isOpen(item) && !flight && !finish()) markGrowBox(card);
if (isOpen(item) && !flight && !finish() && !loopLock) markGrowBox(card);
return card;
}
@@ -835,6 +863,28 @@ function buildChoice(card, item, staged) {
}
otherOption(list, item, staged, name);
card.appendChild(list);
clearRow(card, item);
}
// Takes a one-answer question back to how it arrived: no pick, and nothing in
// "Something else" (its draft too, or the render would put the words straight
// back). A radio group cannot be unticked by clicking it again, so without
// this a stray pick could only be swapped for another one. Only the builders
// call it, and they only run for a form that has not been sent.
function clearRow(card, item) {
const row = el("div", "btn-row options-clear");
const b = el("button", "btn small ghost", "Clear");
b.type = "button";
// An id so focus survives the render the click sets off (see withFocus).
b.id = "clear-" + item.id;
b.setAttribute("aria-label", "Clear your answer to this question");
b.addEventListener("click", () => {
const other = "other-" + item.id;
if (page.local.drafts[other]) setDraft(other, "");
stage(item.id, null);
});
row.appendChild(b);
card.appendChild(row);
}
function buildMulti(card, item, staged) {
@@ -1335,6 +1385,7 @@ function buildMenu(card, item, staged) {
list.appendChild(li);
}
card.appendChild(list);
clearRow(card, item);
if (item.command) {
const note = el("div", "card-note");
+2 -2
View File
@@ -1,4 +1,4 @@
// Plan2Code Web Console - User Preferences, Cleanup tab.
// Plan2Code Web Console - User Preferences, the Cleanup section on the System tab.
import { formatBytes } from "../answers.js";
import { el } from "../render.js";
@@ -123,7 +123,7 @@ async function deleteCleanup() {
setCleanupStatus((failed ? done + " " + failed + " could not be removed." : done) + keptLine, Boolean(failed));
}
// The Cleanup tab's buttons, and starting over whenever Preferences closes.
// The Cleanup section's buttons, and starting over whenever Preferences closes.
export function wireCleanup() {
$("cleanup-scan").addEventListener("click", scanCleanup);
$("cleanup-delete").addEventListener("click", deleteCleanup);
+61 -14
View File
@@ -50,7 +50,7 @@ import { faviconState, setFavicon } from "../favicon.js";
import { helperRows, showTab } from "../subagents.js";
import { FOOTER_TIERS, footerLabel } from "../workspace.js";
import {
activity, agentAdrift, agentWorking, asked, awaitingReply, byId, dashboardLive, docs, doingNow,
activity, agentAdrift, agentWorking, askBusy, loopDriving, loopWaiting, loopWaitingKey, asked, awaitingReply, byId, dashboardLive, docs, doingNow,
finish, gitAwaiting, isDashboard, isGitBoard, isOpen, isSpecFileView, items, loadOverview, myTurn, openItems,
patience, pressStranded, reviewPending, scan, selSpec, sendCollected, specFileTabs, stagedCount, stranded,
topics, workingMs, WORKING_GRACE_MS,
@@ -58,6 +58,7 @@ import {
} from "../selectors.js";
import { sound } from "../sound.js";
import { renderConfirm, renderDashboard } from "./dashboard.js";
import { renderLoopSetup } from "./loop-setup.js";
import { renderLaunching, renderWaiting } from "./starting.js";
import { attachFiles, heldNotes, noteImages, pendingNotes, removeImage } from "../uploads.js";
import { closeMentions } from "../mention-box.js";
@@ -69,13 +70,13 @@ import { renderWorkspace, tellFolderIssues } from "./workspace.js";
import { openHelpOn } from "./help-dialog.js";
import { linkLeavesPage, startNewSession, tellApp } from "../app-bridge.js";
import { askOfflineFlipped, askState, declineOpen, renderAside, renderAsk, renderSubagents, renderSubagentsButton } from "./ask.js";
import { renderHandoff, renderHomeButton, renderStopButton, renderStopControls, renderStopping, stopInProgress, stopWarning } from "./ending.js";
import { renderHandoff, renderLoopEnd, renderHomeButton, renderStopButton, renderStopControls, renderStopping, stopInProgress, stopWarning } from "./ending.js";
import { renderNotepadButton } from "./notepad.js";
import { renderActivities } from "./activities.js";
// What the entry needs from the screens at start-up, handed on from here: only
// the core imports a screen.
export { wakeHoldsChime, wireDashboard } from "./dashboard.js";
export { launchSkill, wakeHoldsChime, wireDashboard } from "./dashboard.js";
export { fillSky } from "./starting.js";
export { fitGrowBox, wireCards } from "./cards.js";
export { wireDocs } from "./docs.js";
@@ -84,9 +85,12 @@ export { syncWorkspaceScope, wireWorkspace } from "./workspace.js";
export { maybeWelcome, openHelpOn, wireHelp } from "./help-dialog.js";
export { wireCleanup } from "./cleanup.js";
export { startLooks, wireLooks } from "./looks.js";
export { confirmUnsaved, markSaved, openPrefs, wirePrefs } from "./prefs-dialog.js";
export { discardOpen, focusOpen, hasUnsaved, loadAgentsView, saveOpen, unsavedName, wireAgentsView } from "./agents-view.js";
export { wireEnding } from "./ending.js";
export { wireNotepad } from "./notepad.js";
export { wireActivities } from "./activities.js";
export { openLoopSetup, wireLoopSetup } from "./loop-setup.js";
const $ = (id) => document.getElementById(id);
@@ -293,6 +297,11 @@ export function adopt(body) {
page.inApp = Boolean(body.inApp);
// Help's `.for-app` / `.for-browser` wording switches on this (help.css).
document.documentElement.classList.toggle("in-app", page.inApp);
// The Implementation Loop's lock: `loop: { driving: true }` on the state,
// ended by the app's `loopEnd`. Screens ask loopDriving(); the class is for
// the stylesheet.
page.loop = (body.state && body.state.loop && body.state.loop.driving === true) || body.loop === true ? { driving: true } : null;
document.documentElement.classList.toggle("loop-driving", loopDriving());
// Always replaced: an absent key means no update.
page.updateFrame = body.update || null;
// Always replaced too: an older server sends none, and then there is no switch.
@@ -318,8 +327,9 @@ export function adopt(body) {
// 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.
// hand-off itself, so they stay, and so does the Ask tab: the conversation
// outlives the hop. A skill run inline from another (a quick task's review)
// keeps all of it.
if (startsClean(prevWorkflow, page.S.workflow)) {
// The pick rides into the skill it launched, never back home: arriving at
// the dashboard, the picker starts on the most recently touched spec still
@@ -331,13 +341,15 @@ export function adopt(body) {
const keepNote = Boolean(ns) && page.S.workflow !== "dashboard" && page.S.workflow === ns.workflow;
page.local = {
...fresh(),
chat: page.local.chat,
launching: page.local.launching,
...(keepPick ? { specSel: page.local.specSel } : {}),
...(keepNote ? { noteSend: ns } : {}),
};
save();
page.selected = null;
page.view = "questions";
// Someone reading the Ask tab across the hop stays on it.
if (page.view !== "ask") page.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();
@@ -394,7 +406,10 @@ export function adopt(body) {
// 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()) page.dashPick = null;
if (!isDashboard() || finish()) {
page.dashPick = null;
page.loopSetup = 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 (page.wake && (!isDashboard() || finish())) page.wake.abort.abort();
@@ -505,7 +520,7 @@ export function adopt(body) {
}
// 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
// any tab) 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.
@@ -515,8 +530,7 @@ function adoptChat() {
if (page.local.chat.conversation == null) page.local.chat.conversation = conv;
else if (conv > page.local.chat.conversation) {
// What they were typing, and what they had attached to it, is theirs:
// a new conversation started elsewhere (another tab, a skill switch)
// must not wipe a message they have not sent yet.
// a new conversation started elsewhere (another tab) must not wipe a message they have not sent yet.
page.local.chat = { ...freshChat(), history: page.local.chat.history, draft: page.local.chat.draft, images: page.local.chat.images, about: null, conversation: conv };
page.chatError = "";
page.askRowCount = 0;
@@ -996,13 +1010,20 @@ function renderMeter() {
// a command to copy into a new conversation.
const fresh = $("meter-fresh");
fresh.hidden = page.meterFrame.level === "green";
// The loop's agents run on; a new session mid-loop is the loop banner's Stop.
const built = fresh.querySelector(".meter-fresh-btn");
if (built) {
built.disabled = loopDriving();
built.title = loopDriving() ? "The loop is building. Stop it from the banner at the top of the window." : "";
}
if (fresh.hidden || fresh.dataset.built) return;
fresh.dataset.built = "1";
if (page.inApp) {
// The same press as the app bar's New Session, confirm and all.
const press = el("button", "btn small primary meter-fresh-btn", "Start a New Session");
press.type = "button";
press.addEventListener("click", () => tellApp("new-session"));
press.addEventListener("click", () => !loopDriving() && tellApp("new-session"));
press.disabled = loopDriving();
fresh.append(press);
return;
}
@@ -1050,7 +1071,9 @@ function renderChrome() {
// The menu has no questions to count: an empty bar there reads as a stall.
document.querySelector(".progress-block").hidden = (isDashboard() || page.S.workflow === "git") && !finish();
$("progress-text").textContent = total
? `${done} of ${total} ${building ? "done" : "answered"}`
? loopDriving() && building
? `${done} of ${total} tasks in this phase`
: `${done} of ${total} ${building ? "done" : "answered"}`
: h.stage || "Getting started";
$("confidence").textContent = h.confidence || "";
$("progress-fill").style.width = pct + "%";
@@ -1087,6 +1110,10 @@ let moodVar = 0;
const STRANDED_LINE =
"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.";
// The agent is out of `wait` answering an Ask message (askBusy()), so a send
// waits for it to finish that first.
const ASK_BUSY_LINE = "Plan2Code is answering your Ask message. Your answers are saved, and it picks them up after that.";
// A finished screen's press that nothing is collecting (pressStranded()).
const PRESS_STRANDED_LINE =
"Plan2Code is not running. Your choice is saved and waiting for it. If the terminal is idle, type **continue** there and it will pick it up; it may also be waiting for your permission approval.";
@@ -1252,6 +1279,9 @@ export function renderStatus() {
const hint = quiet && page.inApp ? APPROVAL_HINT_IN_APP : quiet;
return say("work", hint || activity() || "Plan2Code is thinking…", fmtMs(workingMs()), true, Boolean(hint));
}
// Only once something is waiting on it, and nothing else is theirs to answer:
// with a card still open, "Sent. N still for you" is the truer line.
if (askBusy() && !myTurn().length && (page.pendingResult || awaitingReply().length)) return say("work", ASK_BUSY_LINE, "", 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
@@ -1520,6 +1550,7 @@ function paintMain(main) {
// falls through to the ordinary path below, which hands it the card.
if (isDashboard() && !finish()) {
if (page.local.launching) renderLaunching(main);
else if (page.loopSetup) renderLoopSetup(main);
else if (page.dashPick) {
// A spec-switch under an open confirm can gray the pick out. Rather
// than offer START on a card that cannot launch, drop back to the
@@ -1559,6 +1590,15 @@ function paintMain(main) {
return;
}
// How the Implementation Loop ended, from the app's `loopEnd`: its own
// screen, ahead of any card the last phase left behind.
if (page.S.loopEnd && !finish()) {
const card = renderLoopEnd(page.S.loopEnd);
card.classList.add("is-primary");
main.appendChild(card);
return;
}
const list = asked();
if (!list.length) {
// A session can end before it asked anything at all (a build that needed
@@ -1620,6 +1660,9 @@ export function renderFooter() {
if (foot) foot.classList.toggle("is-dash", Boolean(isDashboard() && !finish()));
// A finished dashboard keeps its summary line but still has nothing to send.
if (foot) foot.classList.toggle("is-dash-done", Boolean(isDashboard() && finish()));
// A loop at work has nothing for the person to send, so no Send to suggest
// otherwise; it comes back the moment a question waits.
if (foot) foot.classList.toggle("is-loop-idle", loopDriving() && !loopWaiting() && !finish());
const summary = $("footer-summary");
const notes = pendingNotes();
@@ -1904,13 +1947,16 @@ export async function send() {
e.status = res.status;
throw e;
}
// Ask locks again once the loop's question is answered (FR-14); it opens
// for the next, different one.
if (loopWaiting()) page.local.askLockedAfterSend = loopWaitingKey();
markSent(payload);
banner("Sent. Plan2Code is picking it up now.", "good");
setTimeout(() => banner(null), 4000);
// A menu option the agent marked `fresh` is a clean start, which under the
// app is the bar's New Session; the agent still gets the pick, so a
// declined confirm carries on with its usual finish.
const freshMenu = page.inApp ? freshMenuPick(actions) : null;
const freshMenu = page.inApp && !loopDriving() ? freshMenuPick(actions) : null;
if (freshMenu) startNewSession(freshMenu.command ? handoffText({ command: freshMenu.command }) : "");
} catch (err) {
if (err && err.pending) {
@@ -2108,8 +2154,9 @@ export function wireChrome() {
// Escape is the confirm pane's Back — but not while a dialog has it. Native
// dialogs close themselves on the same key; backing out of the pick at the
// same time would be two undos for one press.
if (e.key === "Escape" && page.dashPick && isDashboard() && !finish() && !document.querySelector("dialog[open]")) {
if (e.key === "Escape" && (page.dashPick || page.loopSetup) && isDashboard() && !finish() && !document.querySelector("dialog[open]")) {
page.dashPick = null;
page.loopSetup = null;
redraw();
}
});
+55 -13
View File
@@ -9,11 +9,12 @@ import {
handoffList,
loadOverview,
finish,
loopDriving,
} from "../selectors.js";
import { hooks, page, redraw, saveNow } from "../state.js";
import { el, approvalTip, mdInto, releasesLink, copyButton, lightDismiss } from "../render.js";
import { needsRoleNudge, ROLE_NOT_SET } from "../starters.js";
import { looks, renderSwatches, saveLooks } from "../looks.js";
import { looks, saveLooks } from "../looks.js";
import { RED_BANNER, RED_BANNER_IN_APP } from "../meter.js";
import {
dashNoteKind,
@@ -23,6 +24,8 @@ import {
CATALOG_GROUPS,
SKILL_CATALOG,
catalogEntry,
LOOP_ENTRY,
OUTSIDE_APP_LINE,
launchVariant,
SPEC_STATE_LABELS,
chipDetail,
@@ -74,7 +77,6 @@ function roleNudge() {
const setUp = el("button", "btn small primary", "Set up preferences");
setUp.type = "button";
setUp.addEventListener("click", () => {
renderSwatches();
// Closed without a role is a "Not now" too: having been to the dialog,
// they were asked, and the banner does not come back (Help says so).
$("looks-modal").addEventListener(
@@ -88,7 +90,7 @@ function roleNudge() {
},
{ once: true }
);
$("looks-modal").showModal();
hooks.openPrefs("appearance");
});
const notNow = el("button", "btn tiny ghost", "Not now");
notNow.type = "button";
@@ -243,12 +245,16 @@ export function renderDashboard(main) {
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;
// The desktop app's Implementation Loop card closes its group. Outside the
// app it is always drawn, grayed, so the feature can be found.
const loopCard = LOOP_ENTRY && LOOP_ENTRY.group === g.id && (!page.inApp || !hide || available(LOOP_ENTRY));
if (!entries.length && !loopCard) continue;
shown += entries.length + (loopCard ? 1 : 0);
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));
if (loopCard) grid.appendChild(dashCard(LOOP_ENTRY, menu));
section.appendChild(grid);
wrap.appendChild(section);
}
@@ -664,7 +670,7 @@ async function readHandoff(h) {
}
function dashCard(entry, menu) {
const presentation = cardPresentation(entry, scan(), selSpec(), menu);
const presentation = entry.appOnly ? loopPresentation(entry, menu) : 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 grayed
@@ -675,7 +681,7 @@ function dashCard(entry, menu) {
"dash-card" + (presentation.recommended ? " is-suggested" : "") + (going ? " is-going" : "")
);
b.type = "button";
b.disabled = Boolean(page.local.launching) || page.gone || page.pendingResult || !presentation.on;
b.disabled = Boolean(page.local.launching) || page.gone || page.pendingResult || loopDriving() || !presentation.on;
if (!presentation.on && presentation.reason) b.title = presentation.reason;
const head = el("span", "dash-card-head");
@@ -693,12 +699,39 @@ function dashCard(entry, menu) {
b.appendChild(foot);
b.addEventListener("click", () => {
// The loop card opens its own setup screen instead of a confirm pane.
if (entry.appOnly) return hooks.openLoopSetup(selSpec());
page.dashPick = entry;
redraw();
});
if (entry.appOnly) b.appendChild(loopHelpLink());
return b;
}
// The loop card is lit only inside the desktop app and, there, by the same
// rule as Implement (a documented or building spec). Never recommended or
// pre-selected: a person opts into running unattended.
function loopPresentation(entry, menu) {
if (!page.inApp) return { on: false, reason: OUTSIDE_APP_LINE, recommended: false, detail: "" };
return { ...cardPresentation(entry, scan(), selSpec(), menu), recommended: false };
}
// "How the loop works" on the card: a link inside a button is not allowed, so
// it is a span that acts like one and keeps the click from opening the setup.
function loopHelpLink() {
const a = el("span", "dash-card-link", "How the loop works");
a.setAttribute("role", "link");
a.tabIndex = 0;
const open = (e) => {
e.stopPropagation();
e.preventDefault();
hooks.openHelpOn("loop");
};
a.addEventListener("click", open);
a.addEventListener("keydown", (e) => (e.key === "Enter" || e.key === " ") && open(e));
return a;
}
// "Start with a note from your Notebook": the switch a lit card's confirm
// pane offers when noteSwitchShows() says so. The pane is rebuilt on every
// state frame, so what the person did lives here, keyed to the card and the
@@ -806,8 +839,18 @@ function drawNoteBox(entry, box, cmdNote) {
again();
if (state.on && (state.tabs === null || state.failed)) refreshNoteTabs(state, true);
});
label.append(toggle, el("span", null, "Start with a note from your Notebook"));
box.appendChild(label);
label.append(toggle, el("span", "confirm-note-switch-text", "Start with a note from your Notebook"));
// A callout row, so the switch stands out under the card's long text; the
// hint sits outside the label to keep the checkbox's name short.
const head = el("div", "confirm-note-head" + (state.on ? " is-on" : ""));
head.appendChild(label);
if (!state.on) {
const hint = el("span", "confirm-note-hint", "Hand it a tab you wrote earlier, with its pictures.");
hint.id = "confirm-note-hint";
toggle.setAttribute("aria-describedby", hint.id);
head.appendChild(hint);
}
box.appendChild(head);
const picked = state.on && state.tabs ? state.tabs.find((t) => t.id === state.picked && t.read) : null;
cmdNote.textContent = picked ? " + note: " + picked.name : "";
@@ -834,11 +877,11 @@ function drawNoteBox(entry, box, cmdNote) {
b.setAttribute("aria-pressed", String(t.id === state.picked));
b.appendChild(el("span", "confirm-note-tab-name", t.name));
if (t.sent) {
const badge = el("span", "notepad-sent-badge", "sent");
const badge = el("span", "notepad-sent-badge", "previously sent");
badge.setAttribute("aria-hidden", "true");
b.appendChild(badge);
}
b.setAttribute("aria-label", t.name + (t.sent ? ", sent" : "") + (empty ? ", empty" : ""));
b.setAttribute("aria-label", t.name + (t.sent ? ", previously sent" : "") + (empty ? ", empty" : ""));
if (empty) b.title = t.read ? "This tab has no text or pictures." : "This tab could not be read.";
b.addEventListener("click", () => {
if (state.picked === t.id) return;
@@ -985,7 +1028,6 @@ export function renderConfirm(main, entry) {
const cmdNote = el("span", "confirm-cmd-note");
cmdNote.hidden = true;
if (noteSwitchShows(entry, scan(), selSpec())) {
pane.appendChild(el("hr", "confirm-rule"));
const box = el("div", "confirm-note-box");
// Which control in the box has the focus, so a rebuild of the whole pane
// can hand it back (see the end of this function).
@@ -1032,7 +1074,7 @@ export function renderConfirm(main, entry) {
// 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) {
export async function launchSkill(entry) {
if (page.gone || page.pendingResult || page.local.launching || finish()) return;
const target = launchTarget(entry, selSpec());
// The card was clickable, so this should never fire — but a spec picked in
+113 -5
View File
@@ -42,9 +42,14 @@ import {
agentWorking,
awaitingReply,
isDashboard,
loopDriving,
} from "../selectors.js";
// What the session buttons say while the Implementation Loop drives: its own
// strip in the app's top bar stops it, not this page.
const LOOP_LOCK_TITLE = "The loop is building. Stop it from the banner at the top of the window.";
import { docSavedNote, downloadDoc } from "../doc-files.js";
import { startNewSession } from "../app-bridge.js";
import { startNewSession, tellApp } from "../app-bridge.js";
import { pendingNotes } from "../uploads.js";
// The end of the session, and the only screen in this page whose job is to
@@ -152,7 +157,110 @@ function closeGuideHeld() {
return ["review", "commit", "changelog", "dashboard", "launch"].includes(page.local.afterBuild) || reviewPending() === "asked";
}
// Which stop-screen button was pressed and is waiting on the app's answer, so a
// second press cannot send the same request twice.
let loopPressed = null;
const LOOP_BUTTONS = [
["resume", "loop-resume", "Resume the loop", "primary"],
["fix", "loop-fix", "Fix it by hand", ""],
["finalize", "loop-finalize", "Finalize", "primary"],
];
function shortHash(h) {
return typeof h === "string" ? h.slice(0, 7) : "";
}
/**
* How the Implementation Loop ended, drawn from the app's `loopEnd`: a stop
* (why, what was committed, what is left uncommitted, what can be done next) or
* a finish (every phase built, its commit, and a count of each kind of decision
* its agent made; the report behind the button holds them all).
*/
export function renderLoopEnd(end) {
const card = el("article", "card handoff loop-end");
const finished = end.kind === "finished";
card.appendChild(el("p", "card-kicker", finished ? "Loop finished" : "Loop stopped"));
card.appendChild(el("h2", null, finished ? "Every phase is built" : end.line));
if (finished && end.line) card.appendChild(el("p", "loop-line", end.line));
const evidence = end.evidence && docs().find((d) => d.id === end.evidence);
if (evidence) {
const read = el("button", "btn small", finished ? "Read the full report" : "Read why, and the report so far");
read.type = "button";
read.addEventListener("click", () => {
page.view = "doc:" + evidence.id;
redraw();
});
card.appendChild(read);
}
const phases = Array.isArray(end.phases) ? end.phases : [];
if (phases.length) {
const table = el("table", "loop-end-phases");
const head = el("tr");
const cols = finished ? ["Phase", "Commit", "Fixed", "Not fixed", "Left open", "Assumed", "Other decisions", "Retries"] : ["Phase", "Commit"];
for (const c of cols) head.appendChild(el("th", null, c));
table.appendChild(head);
for (const ph of phases) {
const row = el("tr");
row.appendChild(el("td", null, `Phase ${ph.n}: ${ph.name}`));
const commit = el("td");
if (ph.commit) commit.appendChild(el("code", null, shortHash(ph.commit)));
else commit.textContent = "not committed";
row.appendChild(commit);
if (finished) {
for (const count of [ph.fixed, ph.skipped, ph.left, ph.assumed, ph.decisions, ph.retries]) {
row.appendChild(el("td", null, String(count ?? 0)));
}
}
table.appendChild(row);
}
card.appendChild(table);
}
const files = Array.isArray(end.uncommitted) ? end.uncommitted : [];
if (files.length) {
card.appendChild(el("h3", null, "Uncommitted in this phase"));
const list = el("ul", "loop-end-files");
const fill = (items, into) => items.forEach((f) => into.appendChild(el("li", null, f)));
fill(files.slice(0, 10), list);
if (files.length > 10) {
const more = el("details");
more.appendChild(el("summary", null, `${files.length - 10} more files`));
const rest = el("ul", "loop-end-files");
fill(files.slice(10), rest);
more.appendChild(rest);
card.append(list, more);
} else {
card.appendChild(list);
}
}
const can = Array.isArray(end.can) ? end.can : [];
const actions = el("div", "loop-end-actions");
for (const [key, message, label, kind] of LOOP_BUTTONS) {
if (!can.includes(key)) continue;
const b = el("button", "btn" + (kind ? " " + kind : ""), label);
b.type = "button";
b.disabled = page.gone || (loopPressed === message && !page.loopAction);
b.addEventListener("click", () => {
loopPressed = message;
page.loopAction = null;
tellApp(message);
redraw();
});
actions.appendChild(b);
}
if (actions.childElementCount) card.appendChild(actions);
if (page.loopAction && !page.loopAction.ok) {
card.appendChild(el("p", "loop-error", page.loopAction.error));
}
return card;
}
export function renderHandoff(fin) {
if (page.S && page.S.loopEnd) return renderLoopEnd(page.S.loopEnd);
const card = el("article", "card handoff");
card.appendChild(el("p", "card-kicker", finishPaused(fin) ? "Session paused" : "Session ended"));
card.appendChild(el("h2", null, fin.headline));
@@ -586,8 +694,8 @@ export function renderStopButton() {
const gate = turnGate({ gone: page.gone, pendingResult: page.pendingResult, waiting: agentHasTheBall() });
// A way home in flight holds Stop back too, unless the agent went quiet
// after collecting it: Stop's resume screen is then the only way out.
b.disabled = Boolean(gate) || (Boolean(page.local.homeward) && !agentAdrift());
b.title = {
b.disabled = Boolean(gate) || (Boolean(page.local.homeward) && !agentAdrift()) || loopDriving();
b.title = loopDriving() ? LOOP_LOCK_TITLE : {
gone: "Not connected right now.",
pending: "Your last answers are still being picked up. You can stop once they have been.",
waiting: "Plan2Code is working on your answers. You can stop once it replies.",
@@ -617,8 +725,8 @@ export function renderHomeButton() {
warned: Boolean(page.S) && Boolean(stopWarning()),
});
b.hidden = st.hidden;
b.disabled = st.disabled;
b.title = st.title;
b.disabled = st.disabled || loopDriving();
b.title = loopDriving() ? LOOP_LOCK_TITLE : st.title;
}
function openHomeConfirm() {
+25 -42
View File
@@ -4,7 +4,8 @@ import { looksReady, looks, saveLooks } from "../looks.js";
import { page } from "../state.js";
import { isDashboard, finish, agentAdrift } from "../selectors.js";
import { releasesLink, el, copyButton, lightDismiss } from "../render.js";
import { HELP_TABS, helpTabFor, helpKeyTarget } from "../help.js";
import { HELP_TABS, helpTabFor } from "../help.js";
import { wireTabs } from "../tabs.js";
import { CATALOG_GROUPS, SKILL_CATALOG } from "../answers.js";
const $ = (id) => document.getElementById(id);
@@ -196,6 +197,8 @@ function renderAppWording(root) {
}
let helpBuilt = false;
// The tabs, wired by tabs.js once the content is built.
let helpTabs = null;
async function renderHelpVersion() {
const slot = $("help-version");
@@ -261,43 +264,31 @@ function buildHelp() {
const code = row.querySelector("code");
row.appendChild(copyButton(code.textContent, "btn small handoff-copy", code));
}
for (const t of HELP_TABS) {
const btn = el("button", "help-tab");
btn.type = "button";
btn.id = "help-tab-" + t.id;
btn.setAttribute("role", "tab");
btn.setAttribute("aria-controls", "help-panel-" + t.id);
btn.setAttribute("aria-selected", "false");
btn.tabIndex = -1;
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("class", "help-tab-icon");
svg.setAttribute("aria-hidden", "true");
const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
use.setAttribute("href", "#hi-" + t.id);
svg.appendChild(use);
btn.appendChild(svg);
btn.appendChild(el("span", null, t.label));
btn.addEventListener("click", () => selectHelpTab(t.id));
tabs.appendChild(btn);
const panel = panels.querySelector(`section.help-panel[data-tab="${t.id}"]`);
panel.id = "help-panel-" + t.id;
panel.setAttribute("role", "tabpanel");
panel.setAttribute("aria-labelledby", "help-tab-" + t.id);
panel.tabIndex = 0;
panel.hidden = true;
}
helpTabs = wireTabs({
tabs: HELP_TABS,
list: tabs,
panels,
prefix: "help",
tabClass: "help-tab",
renderTab: (t, btn) => {
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
svg.setAttribute("class", "help-tab-icon");
svg.setAttribute("aria-hidden", "true");
const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
use.setAttribute("href", "#hi-" + t.id);
svg.appendChild(use);
btn.appendChild(svg);
btn.appendChild(el("span", null, t.label));
},
onSelect: () => {
$("help-panels").scrollTop = 0;
},
});
helpBuilt = true;
}
export function selectHelpTab(id) {
for (const t of HELP_TABS) {
const on = t.id === id;
const btn = $("help-tab-" + t.id);
btn.setAttribute("aria-selected", String(on));
btn.tabIndex = on ? 0 : -1;
$("help-panel-" + t.id).hidden = !on;
}
$("help-panels").scrollTop = 0;
helpTabs.select(id);
}
export function openHelp() {
@@ -372,14 +363,6 @@ export function wireHelp() {
if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
e.preventDefault();
e.stopPropagation();
return;
}
if (!e.target.classList || !e.target.classList.contains("help-tab")) return;
const current = HELP_TABS.findIndex((t) => "help-tab-" + t.id === e.target.id);
const n = helpKeyTarget(e.key, current, HELP_TABS.length);
if (n < 0) return;
e.preventDefault();
selectHelpTab(HELP_TABS[n].id);
$("help-tab-" + HELP_TABS[n].id).focus();
});
}
+34 -481
View File
@@ -1,444 +1,19 @@
// Plan2Code Web Console - User Preferences: looks, sounds and the launcher's model menus.
// Plan2Code Web Console - User Preferences: the look and sound controls. The
// Agents & models tab is agents-view.js's.
import { adoptLooks, applyLooks, loadLooks, looks, renderSwatches, resetLooks, saveLooks, syncLooks } from "../looks.js";
import { adoptLooks, applyLooks, loadLooks, looks, renderSwatches, saveLooks, syncLooks } from "../looks.js";
import { dropHeldSound, releaseHeldSound, sound, soundOn } from "../sound.js";
import { hushTones, tone, unlockTones } from "../tones.js";
import { hushMusic } from "../music.js";
import { SOUND_EVENTS, soundKey } from "../palette.js";
import { ROLES, ROLE_NOT_SET, ROLE_NOT_SET_LABEL, needsRoleNudge, normalizeRole } from "../starters.js";
import { isDashboard } from "../selectors.js";
import { el, lightDismiss } from "../render.js";
import { page, redraw } from "../state.js";
import { el } from "../render.js";
import { hooks, page, redraw } from "../state.js";
import { framed, onAppMessage, tellApp } from "../app-bridge.js";
const $ = (id) => document.getElementById(id);
function setModelsStatus(text, isError) {
const status = $("models-status");
status.textContent = text;
status.classList.toggle("error", Boolean(isError));
}
// Models: the launcher's menu. The built-in list ships with every install and is read-only
// here; what the person adds is saved to the server, which the launcher reads on its next run.
let modelsData = null;
// The CLIs the launcher reads a model list for, in tab order (routes.mjs MODEL_CLIS).
const MODEL_CLIS = ["claude", "devin", "codex"];
let modelsTab = "claude";
function renderModels() {
for (const cli of MODEL_CLIS) {
$("models-tab-" + cli).setAttribute("aria-pressed", String(cli === modelsTab));
}
const shipped = $("models-shipped");
const user = $("models-user");
shipped.replaceChildren();
user.replaceChildren();
if (!modelsData) {
setModelsStatus("Models could not be loaded.", true);
return;
}
for (const m of modelsData.shipped[modelsTab] || []) {
const row = el("div", "models-row locked");
row.append(el("span", null, m.id), el("span", null, m.label || ""));
shipped.appendChild(row);
}
const mine = modelsData.user[modelsTab];
mine.forEach((m, i) => {
const row = el("div", "models-row");
const id = el("input");
id.value = m.id;
id.placeholder = "Model id";
id.setAttribute("aria-label", "Model id");
const label = el("input");
label.value = m.label;
label.placeholder = "Name shown in the menu";
label.setAttribute("aria-label", "Name shown in the menu");
const remove = el("button", "btn small ghost", "Remove");
remove.type = "button";
id.addEventListener("change", () => { m.id = id.value.trim(); saveModels(); });
label.addEventListener("change", () => { m.label = label.value.trim(); saveModels(); });
remove.addEventListener("click", () => {
mine.splice(i, 1);
saveModels();
renderModels();
});
row.append(id, label, remove);
user.appendChild(row);
});
}
async function saveModels() {
try {
const res = await fetch("/models", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ models: modelsData.user }),
});
const body = await res.json();
if (!res.ok) return setModelsStatus(body.error || "Could not save.", true);
setModelsStatus("Saved. Restart plan2code to use it.", false);
} catch {
setModelsStatus("Could not save.", true);
}
}
async function loadModelsData() {
try {
const res = await fetch("/models");
if (res.ok) modelsData = await res.json();
} catch {}
renderModels();
}
// Agents: CLIs Plan2Code did not find on its own, saved whole to ~/.plan2code/agents.json.
// Each card edits its entry in place (unknown keys ride along untouched); every change
// saves the whole list. A new card is not sent until it has a name and a command.
let agentsData = [];
// The server's complaint about one card, drawn on it: { index, field, error } (index into agentsData).
let agentsError = null;
// The entry whose Delete is waiting for a second click.
let agentsConfirming = null;
// Every change saves, so two saves can be in flight at once: only the newest one's answer is drawn.
let agentsSaveSeq = 0;
// The list as last loaded or saved, as sent: a change that leaves it the same (a field of a new
// card still held back) sends nothing.
let agentsLastSent = null;
function setAgentsStatus(text, isError) {
const status = $("agents-status");
status.textContent = text;
status.classList.toggle("error", Boolean(isError));
}
function newAgent() {
return { name: "", command: "", args: [], prompt: "/plan2code", bypassArgs: [], modelArgs: ["--model", "{model}"], models: [] };
}
function agentField(label, field, child) {
const wrap = el("div", "agent-field");
wrap.dataset.field = field;
wrap.append(el("span", null, label), child);
return wrap;
}
function agentInput(agent, key, label, placeholder, trim) {
const input = el("input");
input.value = agent[key] || "";
input.placeholder = placeholder;
input.setAttribute("aria-label", label);
input.dataset.field = key;
input.addEventListener("change", () => {
agent[key] = trim ? input.value.trim() : input.value;
saveAgents();
});
return input;
}
// A list of text rows (arguments), with Remove on each and an Add under them.
function agentArgsEditor(agent, key, label, placeholder, addLabel) {
const box = el("div", "agent-rows");
box.dataset.field = key;
const draw = () => {
box.replaceChildren();
agent[key].forEach((value, i) => {
const row = el("div", "agent-row");
const input = el("input");
input.value = value;
input.placeholder = placeholder;
input.setAttribute("aria-label", label);
input.dataset.field = key;
input.addEventListener("change", () => { agent[key][i] = input.value.trim(); saveAgents(); });
const remove = el("button", "btn small ghost", "Remove");
remove.type = "button";
remove.addEventListener("click", () => {
agent[key].splice(i, 1);
draw();
saveAgents();
});
row.append(input, remove);
box.appendChild(row);
});
const add = el("button", "btn small ghost", addLabel);
add.type = "button";
add.addEventListener("click", () => {
agent[key].push("");
draw();
box.querySelector(".agent-row:last-of-type input")?.focus();
});
box.appendChild(add);
};
draw();
return agentField(label, key, box);
}
// The models list: an id and an optional name for the menu on each row.
function agentModelsEditor(agent) {
const box = el("div", "agent-rows");
box.dataset.field = "models";
const draw = () => {
box.replaceChildren();
agent.models.forEach((m, i) => {
const row = el("div", "agent-row model");
const id = el("input");
id.value = m.id || "";
id.placeholder = "Model id, for {model}";
id.setAttribute("aria-label", "Model id");
id.dataset.field = "models";
const label = el("input");
label.value = m.label || "";
label.placeholder = "Name shown in the menu (optional)";
label.setAttribute("aria-label", "Name shown in the menu");
label.dataset.field = "models";
const remove = el("button", "btn small ghost", "Remove");
remove.type = "button";
id.addEventListener("change", () => { m.id = id.value.trim(); saveAgents(); });
label.addEventListener("change", () => {
const text = label.value.trim();
if (text) m.label = text;
else delete m.label;
saveAgents();
});
remove.addEventListener("click", () => {
agent.models.splice(i, 1);
draw();
saveAgents();
});
row.append(id, label, remove);
box.appendChild(row);
});
const add = el("button", "btn small ghost", "Add a model");
add.type = "button";
add.addEventListener("click", () => {
agent.models.push({ id: "" });
draw();
box.querySelector(".agent-row:last-of-type input")?.focus();
});
box.appendChild(add);
};
draw();
return agentField("Models", "models", box);
}
// Test, and Delete with its confirm step on the card itself (never the browser's confirm()).
function agentFoot(agent) {
const foot = el("div", "agent-foot");
const test = el("button", "btn small", "Test");
test.type = "button";
const result = el("span", "help agent-test-result");
result.setAttribute("role", "status");
test.addEventListener("click", async () => {
const command = String(agent.command || "").trim();
if (!command) {
result.textContent = "Type a command first.";
return;
}
result.textContent = "Looking...";
try {
const res = await fetch("/agents/test", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ command }),
});
const body = await res.json();
if (!res.ok) result.textContent = body.error || "Could not test.";
else result.textContent = body.found ? "Found at " + body.path : "Not found on PATH";
} catch {
result.textContent = "Could not test.";
}
});
foot.append(test);
if (agentsConfirming === agent) {
const ask = el("span", "help", "Delete this agent?");
const yes = el("button", "btn small danger", "Yes, delete");
yes.type = "button";
const keep = el("button", "btn small ghost", "Keep");
keep.type = "button";
yes.addEventListener("click", async () => {
agentsConfirming = null;
agentsData.splice(agentsData.indexOf(agent), 1);
agentsError = null;
renderAgents();
await saveAgents();
});
keep.addEventListener("click", () => {
agentsConfirming = null;
renderAgents();
});
foot.append(ask, yes, keep);
} else {
const del = el("button", "btn small ghost danger", "Delete");
del.type = "button";
del.addEventListener("click", () => {
agentsConfirming = agent;
renderAgents();
});
foot.append(del);
}
foot.append(result);
return foot;
}
// Which field or button has focus, so a redraw (an id assigned, an error marked) puts the
// person back where they were, with what they had typed: { card, nth, value, start, end }.
const AGENT_FOCUSABLE = "input, button";
function agentsFocus(list) {
const active = document.activeElement;
const card = active && list.contains(active) ? active.closest(".agent-card") : null;
if (!card) return null;
const at = { card: [...list.children].indexOf(card), nth: [...card.querySelectorAll(AGENT_FOCUSABLE)].indexOf(active) };
if (active instanceof HTMLInputElement) Object.assign(at, { value: active.value, start: active.selectionStart, end: active.selectionEnd });
return at;
}
function restoreAgentsFocus(list, at) {
const card = at && list.children[at.card];
const target = card && card.querySelectorAll(AGENT_FOCUSABLE)[at.nth];
if (!target) return;
if (!(target instanceof HTMLInputElement) || at.value === undefined) {
target.focus();
return;
}
const drawn = target.value;
target.value = at.value;
target.focus();
try {
target.setSelectionRange(at.start, at.end);
} catch {}
// Text typed before the redraw is not in agentsData yet, and the browser fires no change
// for a value set from script, so leaving the field sends it on.
if (at.value !== drawn) target.addEventListener("blur", () => target.dispatchEvent(new Event("change")), { once: true });
}
function renderAgents() {
const list = $("agents-list");
const focus = agentsFocus(list);
list.replaceChildren();
agentsData.forEach((agent, i) => {
for (const key of ["args", "bypassArgs", "modelArgs", "models"]) {
if (!Array.isArray(agent[key])) agent[key] = [];
}
const card = el("div", "agent-card");
const top = el("div", "agent-top");
top.append(
agentField("Name", "name", agentInput(agent, "name", "Name", "Name shown in the menu", true)),
agentField("Command", "command", agentInput(agent, "command", "Command", "Program to run, such as myagent", true)),
);
card.append(
top,
agentArgsEditor(agent, "args", "Arguments", "--message={prompt}", "Add an argument"),
agentField("Start prompt", "prompt", agentInput(agent, "prompt", "Start prompt", "/plan2code (blank starts with nothing typed)", false)),
agentArgsEditor(agent, "bypassArgs", "Bypass arguments", "--yes-always", "Add an argument"),
agentArgsEditor(agent, "modelArgs", "Model arguments", "--model={model}", "Add an argument"),
agentModelsEditor(agent),
);
if (agentsError && agentsError.index === i) {
card.classList.add("invalid");
for (const input of card.querySelectorAll("input")) {
if (input.dataset.field === agentsError.field) input.classList.add("invalid");
}
card.appendChild(el("p", "agent-error", agentsError.error));
}
card.appendChild(agentFoot(agent));
list.appendChild(card);
});
restoreAgentsFocus(list, focus);
}
// The list as the server wants it: blank rows dropped, and a new card without both a name and
// a command (one still being typed) left out, so its first field is not refused as half an
// agent. `kept` maps each sent entry back to its place.
function agentsPayload() {
const kept = [];
const agents = [];
agentsData.forEach((a, i) => {
if (!a.id && (!String(a.name || "").trim() || !String(a.command || "").trim())) return;
kept.push(i);
agents.push({
...a,
args: a.args.filter((v) => v !== ""),
bypassArgs: a.bypassArgs.filter((v) => v !== ""),
modelArgs: a.modelArgs.filter((v) => v !== ""),
models: a.models.filter((m) => m.id),
});
});
return { kept, agents };
}
// `replace` is the person's Save anyway, over a file holding entries this page could not read.
async function saveAgents({ replace = false } = {}) {
const { kept, agents } = agentsPayload();
const sent = JSON.stringify(agents);
if (!replace && agentsError === null && sent === agentsLastSent) return;
const seq = ++agentsSaveSeq;
try {
const res = await fetch("/agents", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(replace ? { agents, replace: true } : { agents }),
});
const body = await res.json();
if (seq !== agentsSaveSeq) return;
if (res.status === 409) {
const warnings = Array.isArray(body.warnings) ? body.warnings : [];
setAgentsStatus([body.error || "Not saved.", ...warnings].join(" "), true);
$("agents-replace").hidden = false;
return;
}
$("agents-replace").hidden = true;
if (!res.ok) {
const at = Number.isInteger(body.index) ? kept[body.index] : undefined;
agentsError = at === undefined ? null : { index: at, field: body.field, error: body.error || "Could not save." };
setAgentsStatus(at === undefined ? body.error || "Could not save." : "Not saved. Fix the marked agent.", true);
renderAgents();
return;
}
// Ids are assigned on the first save: take the server's entries, and redraw only then
// (or to clear a mark), so typing in another card is not interrupted.
const fresh = agents.some((a) => !a.id) || agentsError !== null;
agentsError = null;
agentsLastSent = sent;
setAgentsStatus("Saved.", false);
if (fresh) {
kept.forEach((at, n) => { agentsData[at] = body.agents[n]; });
agentsLastSent = JSON.stringify(agentsPayload().agents);
renderAgents();
}
} catch {
if (seq === agentsSaveSeq) setAgentsStatus("Could not save.", true);
}
}
async function loadAgents() {
agentsError = null;
agentsConfirming = null;
agentsLastSent = null;
$("agents-replace").hidden = true;
try {
const res = await fetch("/agents");
if (res.ok) {
const body = await res.json();
agentsData = Array.isArray(body.agents) ? body.agents : [];
for (const agent of agentsData) {
for (const key of ["args", "bypassArgs", "modelArgs", "models"]) if (!Array.isArray(agent[key])) agent[key] = [];
}
agentsLastSent = JSON.stringify(agentsPayload().agents);
const warnings = Array.isArray(body.warnings) ? body.warnings : [];
setAgentsStatus(warnings.join(" "), warnings.length > 0);
} else {
setAgentsStatus("Agents could not be loaded.", true);
}
} catch {
setAgentsStatus("Agents could not be loaded.", true);
}
renderAgents();
}
// Following the system, the saved looks painted before anything is drawn, and
// the sound cues let go on the next touch. `boot` is the page's boot data.
export function startLooks(boot) {
@@ -461,25 +36,15 @@ export function startLooks(boot) {
}
}
// Preferences' buttons and fields.
// The fieldset a control sits in, for the Saved mark beside its legend.
const fieldsetOf = (node) => node.closest("fieldset");
// Preferences' look and sound fields. Opening and closing the dialog, its tabs
// and Back to default are prefs-dialog.js's.
export function wireLooks() {
lightDismiss($("looks-modal"));
$("btn-looks").addEventListener("click", () => {
renderSwatches();
setModelsStatus("", false);
loadModelsData();
loadAgents();
$("looks-modal").showModal();
});
$("looks-done").addEventListener("click", () => $("looks-modal").close());
$("looks-modal").addEventListener("close", () => {
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) redraw();
});
$("looks-reset").addEventListener("click", () => {
resetLooks();
saveLooks();
redraw();
});
for (const [value, label] of [[ROLE_NOT_SET, ROLE_NOT_SET_LABEL], ...ROLES.map((r) => [r.id, r.label])]) {
const option = el("option", null, label);
option.value = value;
@@ -487,7 +52,7 @@ export function wireLooks() {
}
$("looks-role").addEventListener("change", (e) => {
looks.role = normalizeRole(e.target.value);
saveLooks();
hooks.markSaved(fieldsetOf(e.target), saveLooks());
// The dashboard banner, and the starter templates and Ask starters on any
// page, all order themselves by the role.
if (page.S) redraw();
@@ -495,13 +60,13 @@ export function wireLooks() {
for (const radio of document.querySelectorAll('input[name="looks-theme"]')) {
radio.addEventListener("change", () => {
looks.theme = radio.value;
saveLooks();
hooks.markSaved(fieldsetOf(radio), saveLooks());
});
}
for (const radio of document.querySelectorAll('input[name="looks-width"]')) {
radio.addEventListener("change", () => {
looks.width = radio.value;
saveLooks();
hooks.markSaved(fieldsetOf(radio), saveLooks());
});
}
$("looks-sound").addEventListener("change", (e) => {
@@ -509,15 +74,31 @@ export function wireLooks() {
// Held cues are moments, not mail: muted, they are dropped rather than
// saved up to fire all at once the next time sound comes back on.
if (!looks.sound) dropHeldSound();
saveLooks();
hooks.markSaved(fieldsetOf(e.target), saveLooks());
// Turning them on is the one change you can hear: the question chime, or
// the first cue still ticked when that one is not.
const preview = ["question", ...Object.keys(SOUND_EVENTS)].find(soundOn);
if (preview) sound(preview);
});
// The games' sounds: off silences a game playing now; on plays a blip.
$("looks-activity-sounds").addEventListener("change", (e) => {
looks.activitySounds = e.target.checked;
if (!looks.activitySounds) hushTones();
hooks.markSaved(fieldsetOf(e.target), saveLooks());
if (looks.activitySounds) {
unlockTones();
tone("go");
}
});
// The games' music: off stops a track playing now.
$("looks-game-music").addEventListener("change", (e) => {
looks.gameMusic = e.target.checked;
if (!looks.gameMusic) hushMusic();
hooks.markSaved(fieldsetOf(e.target), saveLooks());
});
$("looks-activities").addEventListener("change", (e) => {
looks.hideActivities = !e.target.checked;
saveLooks();
hooks.markSaved(fieldsetOf(e.target), saveLooks());
// The die comes and goes with the next render, which also closes an open
// Activities window, paused.
redraw();
@@ -527,40 +108,12 @@ export function wireLooks() {
const event = box.dataset.sound;
looks[soundKey(event)] = box.checked;
if (!box.checked) dropHeldSound(event);
saveLooks();
hooks.markSaved(fieldsetOf(box), saveLooks());
// Ticking one plays it, so the label has a sound to go with it.
if (box.checked) sound(event);
});
}
for (const cli of MODEL_CLIS) {
$("models-tab-" + cli).addEventListener("click", () => {
modelsTab = cli;
renderModels();
});
}
$("models-add").addEventListener("click", () => {
if (!modelsData) return;
modelsData.user[modelsTab].push({ id: "", label: "" });
renderModels();
$("models-user").querySelector(".models-row:last-child input")?.focus();
});
$("agents-add").addEventListener("click", () => {
agentsData.push(newAgent());
renderAgents();
$("agents-list").querySelector(".agent-card:last-child input")?.focus();
});
$("agents-replace").addEventListener("click", () => {
$("agents-replace").hidden = true;
saveAgents({ replace: true });
});
$("models-reset").addEventListener("click", () => {
if (!modelsData) return;
modelsData.user = Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []]));
saveModels();
renderModels();
});
// Desktop app: the taskbar switch, kept by the app in its own app.json. The
// app says what it holds once the page is up; checked until it does.
if (framed()) {
@@ -0,0 +1,550 @@
// Plan2Code Web Console - the Implementation Loop's setup screen, drawn by the page from the console's saved setup and the app's facts; defines only.
//
// The dashboard's loop card opens this in place of the cards. Nothing here
// runs an agent: Start saves the setup through POST /loop-setup, then asks the
// desktop app (`loop-start { spec }`), which reads the setup itself and
// confirms in its own window. The quick check is typed text the page never
// runs or sends to the app.
import { el } from "../render.js";
import { hooks, page, redraw } from "../state.js";
import { SKILL_CATALOG } from "../answers.js";
import { postJson } from "../net.js";
import { tellApp, wireLoopMessages } from "../app-bridge.js";
const LEVELS = [
["critical", "Critical"],
["warning", "Warning"],
["suggestion", "Suggestion"],
];
const ON_QUESTION = [
["guess", "Take the agent's best guess", "The agent picks the likeliest answer and records the assumption."],
["pause", "Pause and wait for me", "The loop holds and calls you; nothing is lost while you are away."],
["stop", "Stop the loop", "The loop ends at that phase and tells you what it asked."],
];
const AFTER_LAST = [
["offer-finalize", "Stop and offer Finalize", "You press Finalize when you have looked it over."],
["run-finalize", "Run Finalize automatically", "Finalize starts by itself once every phase is built."],
];
const DEFAULT_NOTIFY_PARAM = "message";
// What the setup can send a notification to. `name` is the label for the field
// the person names, on the kinds that have one.
const NOTIFY_KINDS = [
{ id: "query", label: "A web address, with the message in its query string", placeholder: "https://example.com/hook", hint: "The app calls this address with a GET.", name: "Query string name for the message" },
{ id: "discord", label: "Discord webhook", placeholder: "https://discord.com/api/webhooks/...", hint: "In Discord: Edit Channel, Integrations, Webhooks, then Copy Webhook URL." },
{ id: "slack", label: "Slack webhook", placeholder: "https://hooks.slack.com/services/...", hint: "An Incoming Webhook URL from your Slack app's settings." },
{ id: "teams", label: "Microsoft Teams webhook", placeholder: "https://...", hint: 'In Teams: Workflows, the template "Post to a channel when a webhook request is received", then copy its URL.' },
{ id: "google-chat", label: "Google Chat webhook", placeholder: "https://chat.googleapis.com/v1/spaces/...", hint: "In the space: Apps & integrations, Webhooks, then copy the URL." },
{ id: "json", label: "A web address, with the message in a JSON body", placeholder: "https://example.com/hook", hint: "The app sends a POST with a JSON object holding the message, for any other service.", name: "JSON field name for the message" },
];
const SMART_DETAIL = "A fresh agent reads the review's findings and fixes the ones worth fixing. A skipped Critical stops the phase.";
/** Called by the page's start-up: hear the app's answers to the loop's requests. */
export function wireLoopSetup() {
wireLoopMessages(page, redraw);
}
/**
* Open the setup screen for `spec` (the picker's selected spec object). The
* saved setup and the read-only facts come from the console; the agent, model
* and permission facts come from the app.
*/
export async function openLoopSetup(spec) {
if (!spec || !spec.dir || page.gone || page.pendingResult || page.local.launching) return;
const dir = spec.dir;
page.loopStart = null;
page.loopNotifyTest = null;
page.loopSetup = { spec: dir, loaded: false, failed: false, form: null, facts: null, problems: [], starting: false };
tellApp("loop-facts");
redraw();
const mine = page.loopSetup;
let res;
try {
res = await fetch("/loop-setup?spec=" + encodeURIComponent(dir), { cache: "no-store" });
} catch {
res = null;
}
if (page.loopSetup !== mine) return;
if (!res || !res.ok) {
mine.failed = true;
redraw();
return;
}
const answer = await res.json().catch(() => null);
if (page.loopSetup !== mine) return;
if (!answer) {
mine.failed = true;
redraw();
return;
}
const { phasesLeft, branch, pending, suggestedQuickCheck, remembered, saved, ...setup } = answer;
mine.form = {
review: setup.review !== false,
fixMode: setup.fixMode === "levels" ? "levels" : "smart",
fix: Array.isArray(setup.fix) ? [...setup.fix] : LEVELS.map(([k]) => k),
commit: setup.commit !== false,
onQuestion: setup.onQuestion || "guess",
afterLast: setup.afterLast || "offer-finalize",
quickCheck: typeof setup.quickCheck === "string" ? setup.quickCheck : "",
retryOnce: setup.retryOnce !== false,
silenceMinutes: Number.isInteger(setup.silenceMinutes) ? setup.silenceMinutes : 20,
notifyKind: NOTIFY_KINDS.some((k) => k.id === setup.notifyKind) ? setup.notifyKind : "query",
notifyUrl: typeof setup.notifyUrl === "string" ? setup.notifyUrl : "",
notifyParam: setup.notifyParam || DEFAULT_NOTIFY_PARAM,
};
// A first visit with nothing typed starts from the project's own check.
if (!remembered && !mine.form.quickCheck && suggestedQuickCheck) mine.form.quickCheck = suggestedQuickCheck;
mine.facts = {
phasesLeft: Array.isArray(phasesLeft) ? phasesLeft : [],
branch: typeof branch === "string" ? branch : "",
pending: Number.isInteger(pending) ? pending : null,
};
mine.loaded = true;
redraw();
}
function close() {
page.loopSetup = null;
page.loopStart = null;
redraw();
}
/**
* Why Start is grayed, or "" when it can go (FR-5), in the spec's order.
* Exported for the page's unit tests.
*/
export function startBlock(form, facts, appFacts) {
if (!form || !facts) return "Loading the setup...";
if (form.commit && facts.pending !== null && facts.pending > 0) {
return `Commit each phase needs a clean tree: ${facts.pending} uncommitted ${facts.pending === 1 ? "change" : "changes"}.`;
}
if (!appFacts) return "Asking the app...";
if (appFacts.permissionMode === "checked") return "The loop needs permission checks off. Start a New Session with checks off first.";
if (appFacts.promptSupport === false) return "This agent cannot be started with a first prompt.";
if (!facts.phasesLeft.length) return "Nothing left to build in this spec.";
return "";
}
/**
* What is wrong with the web address fields as typed, or "". The server checks
* again on save; this is the line that shows while typing.
*/
export function notifyProblem(url, param, kind = "query") {
const address = url.trim();
if (!address) return "";
if (!/^https?:\/\//i.test(address)) return "The web address must start with http:// or https://.";
let good = /^https?:\/\/[^/?#@]+([/?#][!-~]*)?$/i.test(address) && !/[^!-~]/.test(address);
if (good) {
try {
good = Boolean(new URL(address).hostname);
} catch {
good = false;
}
}
if (!good) return "That is not a web address the app can call. Leave out any user name or password, and percent-encode spaces and accents.";
const named = NOTIFY_KINDS.some((k) => k.id === kind && k.name);
if (named && !/^[A-Za-z0-9._~-]{1,64}$/.test(param.trim() || DEFAULT_NOTIFY_PARAM)) return "The name can only use letters, digits, and - _ . ~";
return "";
}
/**
* The chat service a pasted address belongs to, or "". A webhook needs a POST:
* a GET to a Discord webhook answers 200 and posts nothing, so staying on the
* query string kind would look like it worked.
*/
export function kindForUrl(url) {
let parsed;
try {
parsed = new URL(url.trim());
} catch {
return "";
}
const host = parsed.hostname.toLowerCase();
const under = (domain) => host === domain || host.endsWith(`.${domain}`);
if ((under("discord.com") || under("discordapp.com")) && parsed.pathname.startsWith("/api/webhooks/")) return "discord";
if (host === "hooks.slack.com") return "slack";
if (host === "chat.googleapis.com") return "google-chat";
if (under("logic.azure.com") || under("powerplatform.com") || under("powerautomate.com")) return "teams";
return "";
}
function field(label, hint) {
const box = el("div", "loop-field");
box.appendChild(el("p", "loop-label", label));
if (hint) box.appendChild(el("p", "loop-hint", hint));
return box;
}
function toggle(id, text, checked, onChange) {
const label = el("label", "loop-switch");
const input = el("input");
input.type = "checkbox";
input.id = id;
input.checked = checked;
input.addEventListener("change", () => onChange(input.checked));
label.append(input, el("span", null, text));
return label;
}
function radios(name, options, current, onChange) {
const group = el("div", "loop-radios");
group.setAttribute("role", "radiogroup");
for (const [value, text, detail] of options) {
const label = el("label", "loop-radio");
const input = el("input");
input.type = "radio";
input.name = name;
input.id = `loop-${name}-${value}`;
input.checked = current === value;
input.addEventListener("change", () => input.checked && onChange(value));
const body = el("span", "loop-radio-body");
body.appendChild(el("span", "loop-radio-text", text));
if (detail) body.appendChild(el("span", "loop-radio-detail", detail));
label.append(input, body);
group.appendChild(label);
}
return group;
}
function factRow(list, label, value) {
const row = el("div", "loop-fact");
row.appendChild(el("dt", null, label));
row.appendChild(el("dd", null, value));
list.appendChild(row);
}
function agentLine(facts, doing) {
if (!facts) return "Asking the app...";
const bits = [facts.agentLabel || facts.agent || "the app's agent"];
bits.push(facts.model ? `model ${facts.model}` : "default model");
bits.push(facts.effort ? `effort ${facts.effort}` : "default effort");
return `${bits.join(", ")} (the app's launch choice, for ${doing})`;
}
export function renderLoopSetup(main) {
const s = page.loopSetup;
const pane = el("div", "dash-confirm loop-setup");
pane.appendChild(el("p", "card-kicker", "Step 3 · Implementation Loop"));
pane.appendChild(el("h2", "dash-title", "Set up the loop"));
const specLine = el("p", "confirm-spec");
specLine.append(el("span", null, "for "), el("code", null, s.spec));
pane.appendChild(specLine);
if (s.failed) {
pane.appendChild(el("p", "loop-error", "The setup could not be read. Go back and try again."));
} else if (!s.loaded) {
const wait = el("p", "dash-working");
wait.append(el("span", "spinner tiny"), el("span", null, "Loading the setup..."));
pane.appendChild(wait);
} else {
drawBody(pane, s);
}
const actions = el("div", "confirm-actions");
const back = el("button", "btn ghost", "Back");
back.type = "button";
back.addEventListener("click", close);
actions.appendChild(back);
const help = el("button", "linky loop-help", "How the loop works");
help.type = "button";
help.addEventListener("click", () => hooks.openHelpOn("loop"));
actions.appendChild(help);
pane.appendChild(actions);
main.appendChild(pane);
}
function drawBody(pane, s) {
const f = s.form;
const redo = () => {
s.problems = [];
redraw();
};
// What the app will do, in three plain lines (FR-3).
const lines = el("div", "loop-lines");
for (const text of [
"The app builds each remaining phase in a fresh agent session, one after another, while you are away.",
"After each phase it checks the work, marks it done and, if you chose, commits it to this branch. It never pushes.",
"You can watch, play an Activity or stop it at any time from the banner at the top of the window.",
]) {
lines.appendChild(el("p", "loop-line", text));
}
pane.appendChild(lines);
// The read-only facts (FR-3).
const facts = el("dl", "loop-facts");
const left = s.facts.phasesLeft;
factRow(facts, "Phases left", left.length ? left.map((p) => `Phase ${p.n}: ${p.name}`).join("\n") : "None");
factRow(facts, "Building", agentLine(page.loopFacts, "building"));
factRow(facts, "Reviewing", f.review ? agentLine(page.loopFacts, "reviewing") : "Review is off");
factRow(facts, "Branch", s.facts.branch || "unknown");
factRow(facts, "Uncommitted changes", s.facts.pending === null ? "unknown" : String(s.facts.pending));
pane.appendChild(facts);
// The fields (FR-2, FR-4).
const form = el("div", "loop-form");
const review = field("Review");
review.appendChild(toggle("loop-review", "Review each phase with a fresh agent before it counts", f.review, (v) => ((f.review = v), redo())));
form.appendChild(review);
if (f.review) {
const fix = field("Fix findings");
fix.appendChild(
radios(
"fixmode",
[
["smart", "Smart pick", SMART_DETAIL],
["levels", "By level", "The agent fixes every finding at the levels you tick."],
],
f.fixMode,
(v) => ((f.fixMode = v), redo())
)
);
if (f.fixMode === "levels") {
const row = el("div", "loop-ticks");
for (const [key, text] of LEVELS) {
row.appendChild(
toggle(`loop-fix-${key}`, text, f.fix.includes(key), (on) => {
f.fix = LEVELS.map(([k]) => k).filter((k) => (k === key ? on : f.fix.includes(k)));
redo();
})
);
}
fix.appendChild(row);
}
form.appendChild(fix);
}
const ask = field("When a phase asks something");
ask.appendChild(radios("onquestion", ON_QUESTION, f.onQuestion, (v) => ((f.onQuestion = v), redo())));
form.appendChild(ask);
const after = field("After the last phase");
after.appendChild(radios("afterlast", AFTER_LAST, f.afterLast, (v) => ((f.afterLast = v), redo())));
form.appendChild(after);
const notify = field(
"Send a notification",
"When the loop waits on your answer or ends, except when you stop it yourself, the app sends a short message saying which. Leave the address empty to send nothing."
);
const kindLabel = el("label", "loop-number");
kindLabel.appendChild(el("span", null, "Send to"));
const kindSelect = el("select", "loop-text");
kindSelect.id = "loop-notify-kind";
for (const kind of NOTIFY_KINDS) {
const option = el("option", null, kind.label);
option.value = kind.id;
kindSelect.appendChild(option);
}
kindSelect.value = f.notifyKind;
kindLabel.appendChild(kindSelect);
const kindHint = el("p", "loop-hint");
const notifyInput = el("input", "loop-text");
notifyInput.type = "text";
notifyInput.inputMode = "url";
notifyInput.id = "loop-notify-url";
notifyInput.value = f.notifyUrl;
notifyInput.maxLength = 2000;
notifyInput.setAttribute("aria-label", "Web address to call");
const paramRow = el("div");
const paramLabel = el("label", "loop-number");
const paramText = el("span");
paramLabel.appendChild(paramText);
const paramInput = el("input", "loop-text loop-param");
paramInput.type = "text";
paramInput.id = "loop-notify-param";
paramInput.value = f.notifyParam;
paramInput.placeholder = DEFAULT_NOTIFY_PARAM;
paramInput.maxLength = 64;
paramLabel.appendChild(paramInput);
paramRow.appendChild(paramLabel);
const notifyWarn = el("p", "loop-warn");
const testRow = el("div", "loop-test");
const testButton = el("button", "btn", "Send a test");
testButton.type = "button";
testButton.id = "loop-notify-test";
testButton.addEventListener("click", () => sendTest(s));
testRow.appendChild(testButton);
const testLine = notifyTestLine();
if (testLine) testRow.appendChild(testLine);
const showNotify = () => {
const kind = NOTIFY_KINDS.find((k) => k.id === f.notifyKind);
kindSelect.value = kind.id;
kindHint.textContent = kind.hint;
notifyInput.placeholder = kind.placeholder;
paramText.textContent = kind.name || "";
paramRow.hidden = !kind.name || f.notifyUrl.trim() === "";
const problem = notifyProblem(f.notifyUrl, f.notifyParam, kind.id);
notifyWarn.textContent = problem;
notifyWarn.hidden = !problem;
testButton.disabled = Boolean(problem) || f.notifyUrl.trim() === "" || Boolean(page.loopNotifyTest && page.loopNotifyTest.waiting) || s.starting;
};
// What a test said was about the address as it was.
const forgetTest = () => {
if (page.loopNotifyTest && !page.loopNotifyTest.waiting) {
page.loopNotifyTest = null;
testRow.querySelector("p")?.remove();
}
};
notifyInput.addEventListener("input", () => {
f.notifyUrl = notifyInput.value;
forgetTest();
// A pasted webhook picks its own kind, unless the person chose one here.
const service = kindForUrl(f.notifyUrl);
if (service && f.notifyKind === "query" && !s.notifyKindChosen) f.notifyKind = service;
showNotify();
});
kindSelect.addEventListener("change", () => {
f.notifyKind = kindSelect.value;
forgetTest();
s.notifyKindChosen = true;
showNotify();
});
paramInput.addEventListener("input", () => {
f.notifyParam = paramInput.value;
forgetTest();
showNotify();
});
showNotify();
notify.append(kindLabel, notifyInput, kindHint, paramRow, notifyWarn, testRow);
form.appendChild(notify);
const check = field("Quick check", "A command the app runs after each phase, such as npm run build. The page never runs it.");
const checkInput = el("input", "loop-text");
checkInput.type = "text";
checkInput.id = "loop-quickcheck";
checkInput.value = f.quickCheck;
checkInput.placeholder = "npm run build";
checkInput.maxLength = 500;
checkInput.setAttribute("aria-label", "Quick check command");
const checkWarn = el("p", "loop-warn", "No check runs after each phase.");
checkWarn.hidden = f.quickCheck.trim() !== "";
checkInput.addEventListener("input", () => {
f.quickCheck = checkInput.value.replace(/[\r\n]+/g, " ");
checkWarn.hidden = f.quickCheck.trim() !== "";
});
check.append(checkInput, checkWarn);
form.appendChild(check);
const retry = field("If a phase crashes or goes quiet");
retry.appendChild(toggle("loop-retry", "Retry it once", f.retryOnce, (v) => ((f.retryOnce = v), redo())));
const silence = el("label", "loop-number");
silence.appendChild(el("span", null, "Count the agent as stuck after this many minutes with no activity"));
const silenceInput = el("input", "loop-text loop-narrow");
silenceInput.type = "number";
silenceInput.id = "loop-silence";
silenceInput.min = "1";
silenceInput.max = "60";
silenceInput.step = "1";
silenceInput.value = String(f.silenceMinutes);
silenceInput.addEventListener("input", () => {
f.silenceMinutes = Number(silenceInput.value);
});
silence.appendChild(silenceInput);
retry.appendChild(silence);
retry.appendChild(el("p", "loop-hint", "No activity means no file changes, in the project or the agent's session, so allow for your slowest build or test run. Waiting on your answer does not count."));
form.appendChild(retry);
const commit = field("Commit");
commit.appendChild(toggle("loop-commit", "Commit each phase to the current branch", f.commit, (v) => ((f.commit = v), redo())));
form.appendChild(commit);
pane.appendChild(form);
// Start and the one line saying why it is grayed (FR-5).
const block = startBlock(f, s.facts, page.loopFacts);
const gated = Boolean(block);
const foot = el("div", "loop-start");
if (gated) {
const why = el("p", "loop-why", block);
why.setAttribute("role", "status");
foot.appendChild(why);
if (f.commit && s.facts.pending > 0) foot.appendChild(gitButton());
}
if (s.problems.length) {
const bad = el("ul", "loop-problems");
for (const p of s.problems) bad.appendChild(el("li", null, p));
foot.appendChild(bad);
}
const waiting = s.starting && !page.loopStart;
if (waiting) foot.appendChild(el("p", "loop-why", "Waiting for the app's confirm..."));
if (page.loopStart && !page.loopStart.ok) foot.appendChild(el("p", "loop-error", page.loopStart.error));
if (page.loopStart && page.loopStart.ok) foot.appendChild(el("p", "loop-why", "The loop is starting..."));
const start = el("button", "btn primary", "Start the loop");
start.type = "button";
start.id = "loop-start";
start.disabled = gated || waiting || page.gone || page.pendingResult || Boolean(page.loopStart && page.loopStart.ok);
start.addEventListener("click", () => startLoop(s));
foot.appendChild(start);
pane.appendChild(foot);
}
/** The line beside Send a test, or null with nothing to say. */
function notifyTestLine() {
const test = page.loopNotifyTest;
if (!test) return null;
if (test.waiting) return el("p", "loop-why", "Waiting for the app's confirm...");
if (!test.ok) return el("p", "loop-error", test.error);
if (test.sent) return el("p", "loop-why", "Sent, and the address answered OK. Check that the message arrived.");
return null;
}
function gitButton() {
const b = el("button", "btn", "Open the Git board");
b.type = "button";
b.addEventListener("click", () => {
const entry = SKILL_CATALOG.find((e) => e.skill === "plan2code-git");
if (entry) hooks.launchSkill(entry);
});
return b;
}
/** The form as the console saves it. */
function setupBody(f) {
return { ...f, quickCheck: f.quickCheck.trim(), notifyUrl: f.notifyUrl.trim(), notifyParam: f.notifyParam.trim() || DEFAULT_NOTIFY_PARAM };
}
/**
* Send a test: save, so the app can read what is on screen, then ask it. The
* message names nothing: the app takes the address from the saved setup and
* confirms it in its own dialog, as it does for Start.
*/
async function sendTest(s) {
const f = s.form;
if (!f.notifyUrl.trim() || notifyProblem(f.notifyUrl, f.notifyParam, f.notifyKind) || (page.loopNotifyTest && page.loopNotifyTest.waiting)) return;
s.problems = [];
page.loopNotifyTest = { waiting: true };
redraw();
const { status, body: answer } = await postJson("/loop-setup", setupBody(f));
if (page.loopSetup !== s) return;
if (status !== 200 || !answer || answer.ok !== true) {
page.loopNotifyTest = null;
s.problems = Array.isArray(answer && answer.problems) && answer.problems.length ? answer.problems : ["The setup could not be saved. Try again."];
redraw();
return;
}
tellApp("loop-notify-test");
}
async function startLoop(s) {
const f = s.form;
if (startBlock(f, s.facts, page.loopFacts) || (s.starting && !page.loopStart)) return;
s.problems = [];
page.loopStart = null;
s.starting = true;
redraw();
const { status, body: answer } = await postJson("/loop-setup", setupBody(f));
if (page.loopSetup !== s) return;
if (status !== 200 || !answer || answer.ok !== true) {
s.starting = false;
s.problems = Array.isArray(answer && answer.problems) && answer.problems.length ? answer.problems : ["The setup could not be saved. Try again."];
redraw();
return;
}
tellApp("loop-start", { spec: s.spec });
redraw();
}
@@ -0,0 +1,206 @@
// Plan2Code Web Console - the User Preferences dialog: its tabs, the one way
// to open and close it, the Saved mark, Back to default for the tab on screen
// and the prompt that stops an unsaved agent edit being lost.
import { onSwatchSaved, renderSwatches, resetLooks, saveLooks } from "../looks.js";
import { PREFS_TABS, prefsOpenTab, prefsResetScope } from "../prefs.js";
import { wireTabs } from "../tabs.js";
import { el, lightDismiss } from "../render.js";
import { hooks, redraw } from "../state.js";
const $ = (id) => document.getElementById(id);
let prefsTabs = null;
// Back to default only where the tab has looks to reset.
function showResetFor(id) {
$("looks-reset").hidden = prefsResetScope(id) === null;
}
// The small mark at the top right of a fieldset, level with its legend:
// "Saved", fading, or the error in its place, kept until that fieldset saves
// again. `result` is what saveLooks() resolves, or a Promise of it; a `text`
// in it replaces the word Saved.
const markTimers = new WeakMap();
function clearMark(mark) {
clearTimeout(markTimers.get(mark));
if (mark.classList.contains("is-saved")) mark.textContent = "";
}
export async function markSaved(fieldset, result) {
if (!fieldset) return;
let mark = fieldset.querySelector(":scope > .prefs-saved");
if (!mark) {
mark = el("span", "prefs-saved");
mark.setAttribute("role", "status");
// Gone after the fade, or after the same time when motion is reduced and
// no animation runs to say so (the timer below).
mark.addEventListener("animationend", () => clearMark(mark));
fieldset.appendChild(mark);
}
const { ok, error, text } = (await result) || { ok: true };
// A newer save owns the mark: an earlier one's timer must not blank it.
clearTimeout(markTimers.get(mark));
mark.classList.remove("is-saved", "error");
// Restart the fade when the same fieldset saves twice in a row.
void mark.offsetWidth;
if (ok) {
mark.textContent = text || "Saved";
mark.classList.add("is-saved");
markTimers.set(mark, setTimeout(() => clearMark(mark), 2200));
} else {
mark.textContent = error || "Could not save.";
mark.classList.add("error");
}
}
// Every way in: the gear, the dashboard's Set up preferences, or a caller
// naming the tab it wants. Agents and models load each time it opens.
export function openPrefs(tab) {
renderSwatches();
hooks.loadAgentsView();
prefsTabs.select(prefsOpenTab(tab));
$("looks-modal").showModal();
$("prefs-tab-" + prefsTabs.current()).focus();
}
// The unsaved prompt on screen: { resolve, promise, from }, or null. `from`
// is what had focus when it asked (the tab, Close, Back to summary, a field).
let asking = null;
// Everything in the dialog but the prompt, kept out of reach while it asks.
const behindPrompt = () => [$("looks-title"), $("looks-modal").querySelector(".prefs-body"), $("looks-modal").querySelector(".modal-actions")];
function endAsking(go) {
$("prefs-unsaved").hidden = true;
for (const node of behindPrompt()) node.inert = false;
const { resolve, from } = asking;
asking = null;
// Keep editing (or a failed Save) goes back into the form; going on hands
// focus back to what asked, so the action it carries on with owns it.
if (!go) hooks.focusOpen();
else if (from && from.isConnected && !from.closest("[hidden]")) from.focus();
resolve(go);
}
// Before anything leaves an agent form with an unsaved edit (Close, Esc, a
// backdrop click, another tab, Back to summary): Save, Discard or Keep
// editing, asked inside the dialog. Resolves true when it may go on.
export function confirmUnsaved() {
if (!hooks.hasUnsaved()) return Promise.resolve(true);
if (asking) return asking.promise;
let resolve;
const promise = new Promise((r) => (resolve = r));
asking = { resolve, promise, from: document.activeElement };
$("prefs-unsaved-name").textContent = hooks.unsavedName();
for (const node of behindPrompt()) node.inert = true;
$("prefs-unsaved").hidden = false;
$("prefs-unsaved-save").disabled = false;
$("prefs-unsaved-save").focus();
return promise;
}
// Plain true while nothing is unsaved, so a tab switch or a close happens in
// this same tick.
const guard = () => (hooks.hasUnsaved() || asking ? confirmUnsaved() : true);
async function closePrefs() {
if (await guard()) $("looks-modal").close();
}
function wireUnsaved() {
const box = el("div", "prefs-unsaved");
box.id = "prefs-unsaved";
box.hidden = true;
box.setAttribute("role", "alertdialog");
box.setAttribute("aria-labelledby", "prefs-unsaved-title");
box.setAttribute("aria-describedby", "prefs-unsaved-text");
const inner = el("div", "prefs-unsaved-box");
const title = el("h3", null, "Unsaved changes");
title.id = "prefs-unsaved-title";
const text = el("p");
text.id = "prefs-unsaved-text";
const name = el("strong");
name.id = "prefs-unsaved-name";
text.append("You have unsaved changes to ", name, ".");
const save = el("button", "btn small primary", "Save");
save.type = "button";
save.id = "prefs-unsaved-save";
const discard = el("button", "btn small ghost", "Discard");
discard.type = "button";
const keep = el("button", "btn small ghost", "Keep editing");
keep.type = "button";
save.addEventListener("click", async () => {
save.disabled = true;
const ok = await hooks.saveOpen();
save.disabled = false;
if (asking) endAsking(ok);
});
discard.addEventListener("click", () => {
hooks.discardOpen();
endAsking(true);
});
keep.addEventListener("click", () => endAsking(false));
const actions = el("div", "prefs-unsaved-actions");
actions.append(save, discard, keep);
inner.append(title, text, actions);
box.append(inner);
$("looks-modal").append(box);
}
export function wirePrefs() {
const dlg = $("looks-modal");
wireUnsaved();
lightDismiss(dlg, guard);
$("looks-done").addEventListener("click", closePrefs);
// Esc: held while a form has an unsaved edit, and Keep editing while the prompt asks.
dlg.addEventListener("keydown", (e) => {
if (e.key !== "Escape") return;
if (asking) {
e.preventDefault();
endAsking(false);
} else if (hooks.hasUnsaved()) {
e.preventDefault();
closePrefs();
}
});
dlg.addEventListener("cancel", (e) => {
if (!asking && !hooks.hasUnsaved()) return;
e.preventDefault();
if (!asking) closePrefs();
});
hooks.wireAgentsView();
prefsTabs = wireTabs({
tabs: PREFS_TABS,
list: $("prefs-tabs"),
panels: $("prefs-panels"),
prefix: "prefs",
tabClass: "prefs-tab",
beforeSelect: () => guard(),
// The hint describes the tab rather than naming it, so a screen reader's
// tab name stays the label, at any width.
renderTab: (t, btn) => {
const hint = el("span", "prefs-tab-hint", t.hint);
hint.id = "prefs-hint-" + t.id;
hint.setAttribute("aria-hidden", "true");
btn.append(el("span", "prefs-tab-label", t.label), hint);
btn.setAttribute("aria-describedby", hint.id);
},
onSelect: (id) => {
showResetFor(id);
$("looks-modal").querySelector(".prefs-body").scrollTop = 0;
},
});
$("btn-looks").addEventListener("click", () => openPrefs());
$("looks-reset").addEventListener("click", () => {
const tab = prefsTabs.current();
const keys = prefsResetScope(tab);
if (!keys) return;
resetLooks(keys);
const saved = saveLooks();
redraw();
markSaved($("prefs-panel-" + tab).querySelector("fieldset"), saved);
});
onSwatchSaved((saved) => markSaved($("looks-swatches").closest("fieldset"), saved));
}
+17 -4
View File
@@ -4,7 +4,7 @@ import { page, redraw } from "../state.js";
import { el, approvalTip } from "../render.js";
import { startPose, startingHint, staleLaunchFeedback, workflowTitle } from "../answers.js";
import { skillByName } from "../skills.js";
import { agentAdrift, doingNow, docs } from "../selectors.js";
import { agentAdrift, doingNow, docs, loopDriving } from "../selectors.js";
const $ = (id) => document.getElementById(id);
@@ -132,10 +132,12 @@ function renderStarting(main) {
const elapsed = startingElapsed();
const pane = posePane(main, "launching starting", page.S.workflow);
pane.appendChild(el("p", "card-kicker", "Starting up"));
pane.appendChild(el("h2", "launch-title", `Starting ${workflowTitle(page.S.workflow)}`));
const looping = loopDriving();
pane.appendChild(el("h2", "launch-title", looping ? "The loop is starting this phase" : `Starting ${workflowTitle(page.S.workflow)}`));
pane.appendChild(el("p", "launch-quip", START_QUIPS[Math.floor(elapsed / 2600) % START_QUIPS.length]));
pane.appendChild(el("p", "launch-hint", startingHint(elapsed)));
pane.appendChild(approvalTip());
// A loop runs with permission checks off, so no approval will come.
if (!looping) pane.appendChild(approvalTip());
startLaunchTicker();
}
@@ -180,8 +182,17 @@ function startLaunchTicker() {
}
}
// A phase that has reported is not starting: the app is checking the report,
// running the quick check and committing, which can take minutes.
function renderLoopChecking(main) {
const pane = posePane(main, "waiting-pane", page.S.workflow);
pane.appendChild(el("h2", null, "The loop is checking this phase"));
pane.appendChild(el("p", null, "The agent has reported. The app is checking that against the spec before it moves on, so you don't need to do anything."));
}
export function renderWaiting(main) {
const doing = doingNow();
if (!doing && loopDriving() && page.S.loopOutcome) return renderLoopChecking(main);
// Nothing asked and nothing said yet: the session is still starting.
if (!doing) return renderStarting(main);
// The same Planny the session started with, still at it: the spinner that
@@ -199,7 +210,9 @@ export function renderWaiting(main) {
}
pane.appendChild(title);
pane.appendChild(el("p", null, doing));
const ask = "If Plan2Code needs you, the question appears here on its own.";
const ask = loopDriving()
? "The loop is running this phase by itself, so you don't need to do anything. If it needs you, the question appears here."
: "If Plan2Code needs you, the question appears here on its own.";
if (!docs().length) {
pane.appendChild(el("p", null, ask));
return;
+9 -3
View File
@@ -2,7 +2,7 @@
import { hooks, page } from "../state.js";
import { copyButton, el, lightDismiss, selectContents } from "../render.js";
import { selSpec, specList, workspaceFolders } from "../selectors.js";
import { loopDriving, selSpec, specList, workspaceFolders } from "../selectors.js";
import { postJson } from "../net.js";
import { nameProblem } from "../workspace.js";
@@ -114,6 +114,12 @@ export function renderWorkspace() {
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
$("workspace-browse").hidden = Boolean(page.wsFrame && page.wsFrame.remote);
$("workspace-scope").textContent = workspaceScopeText();
// The loop's agents were started with this workspace; changing it now would
// reach nobody (FR-15). Reading and copying paths stays.
const locked = loopDriving();
for (const id of ["workspace-add", "workspace-browse", "workspace-path"]) $(id).disabled = locked || (id === "workspace-add" && wsBusy);
for (const rm of list.querySelectorAll(".ws-remove")) rm.disabled = locked;
if (locked) setAddMsg("The workspace is fixed while the loop builds.");
}
function workspaceRow(f) {
@@ -281,7 +287,7 @@ function paintWorkspaceRow(li, f) {
// sent when the person took a suggested name after a clash.
async function addWorkspaceFolder(path, name) {
const trimmed = String(path || "").trim();
if (!trimmed || wsBusy) return;
if (!trimmed || wsBusy || loopDriving()) return;
wsBusy = true;
$("workspace-add").disabled = true;
const { status, body } = await postJson("/workspace/add", name ? { path: trimmed, name } : { path: trimmed });
@@ -318,7 +324,7 @@ async function addWorkspaceFolder(path, name) {
async function browseWorkspace() {
const b = $("workspace-browse");
if (b.disabled) return;
if (b.disabled || loopDriving()) return;
b.disabled = true;
setAddMsg("Waiting for the folder picker…");
const { status, body } = await postJson("/workspace/browse", {});
+36 -1
View File
@@ -7,6 +7,7 @@ import { page, redraw } from "./state.js";
import { boardAwaiting } from "./git-board.js";
import { defaultSpec, reviewOffer, dashboardOffer, submittedAwaiting, quietLimitMs } from "./answers.js";
import { activityLabel, workingLine } from "./labels.js";
import { ASK_BUSY_MS, chatAnswering } from "./chat.js";
export const WORKING_GRACE_MS = 5 * 60 * 1000;
@@ -18,6 +19,33 @@ export const WORKING_GRACE_MS = 5 * 60 * 1000;
// many missed pokes, not a slow one.
const ADRIFT_MS = 3 * 60 * 1000;
// The Implementation Loop is driving this page: the app started the session
// with `open --loop`, and no `loopEnd` has been posted yet. Locks the page
// (FR-15); the stop and finish screens end it.
export const loopDriving = () => Boolean(page.S && page.S.loop && page.S.loop.driving === true && !page.S.loopEnd);
// Driving, and a required question the loop does not handle itself is open:
// the one case where its card (and Ask) unlock (FR-14).
export const loopWaiting = () =>
loopDriving() &&
openItems().some((i) => i.required !== false && i.handledBy !== "loop");
// The ids of the cards the loop is waiting on the person for, as one string:
// what `local.askLockedAfterSend` remembers, so Ask locks again after a Send
// and stays locked until a different question waits (FR-14).
export const loopWaitingKey = () =>
loopWaiting()
? openItems()
.filter((i) => i.required !== false && i.handledBy !== "loop")
.map((i) => i.id)
.sort()
.join("|")
: "";
// Ask is off while the loop drives, except while a question waits and no Send
// has answered that same question yet.
export const loopAskLocked = () => loopDriving() && !(loopWaiting() && page.local.askLockedAfterSend !== loopWaitingKey());
export const items = () => (page.S && Array.isArray(page.S.items) ? page.S.items : []);
export const topics = () => (page.S && Array.isArray(page.S.topics) ? page.S.topics : []);
@@ -200,12 +228,19 @@ export const doingNow = () => workingLine(page.S && page.S.agent, page.S && page
// 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".
//
// An agent answering an Ask message is out of `wait` too, and busy rather than
// gone, so it gets ASK_BUSY_MS before anything calls it adrift.
export function agentAdrift() {
if (!page.agentLastSeen || page.gone || finish()) return false;
const silent = Date.now() - Date.parse(page.agentLastSeen);
return silent > (page.pendingResult ? uncollectedLimit() : patience(ADRIFT_MS));
const limit = page.pendingResult ? uncollectedLimit() : patience(ADRIFT_MS);
return silent > (chatAnswering(page.chatFrame) ? Math.max(limit, ASK_BUSY_MS) : limit);
}
// Answering an Ask message, and not yet quiet for long enough to doubt it.
export const askBusy = () => chatAnswering(page.chatFrame) && !agentAdrift();
// With answers sent and nothing collecting them, the agent's quiet allowance
// stops counting: those answers are what it is meant to come back for. An
// agent that said it is waiting pings from `wait` every five seconds, so a
+7
View File
@@ -11,6 +11,8 @@ import {
WORKING_GRACE_MS,
openItems,
agentAdrift,
loopDriving,
loopWaiting,
} from "./selectors.js";
import { finishPaused } from "./answers.js";
import { page } from "./state.js";
@@ -24,6 +26,11 @@ export function sendState() {
? { disabled: true, why: "This session is paused.", short: "Session paused" }
: { disabled: true, why: "This session is finished.", short: "Session finished" };
if (page.gone) return { disabled: true, why: "Not connected right now.", short: "Not connected" };
// The Implementation Loop answers for the agent: nothing to send until it
// stops to ask the person something (FR-15, FR-14).
if (loopDriving() && !loopWaiting()) {
return { disabled: true, why: "The loop is building. Cards unlock when it needs you.", short: "The loop is building" };
}
// A send is still being collected. Blocking here is what keeps someone from
// writing over answers nobody has read yet.
if (page.pendingResult) {
+38 -3
View File
@@ -43,6 +43,11 @@
// `spec: true` when it takes the picked spec), or null; an
// optional `help` is Help's line for the card when it differs
// from `blurb`
// appOnly the entry is a card the desktop app alone offers (the
// Implementation Loop): no workflow, no installed skill, and no
// list derived from the workflows (WORKFLOWS, the meter, the
// resume command, Help's card list) holds it. `skill` is an id
// only; `workflow` is null. Use FLOW_SKILLS for those lists.
// Shared by Implement and Implement + Review.
const BUILD_HELPERS =
@@ -235,6 +240,32 @@ export const SKILLS = Object.freeze([
// No card of its own: Implement's card launches it when Review is ticked.
card: null,
}),
// The desktop app's Implementation Loop: a card, not a skill. It has no
// SKILL.md and no console workflow; it drives Implement (or Implement +
// Review) once per phase, each in a fresh agent. Drawn by the dashboard in
// the app only.
skill({
skill: "plan2code-loop",
workflow: null,
appOnly: true,
label: "Implementation Loop",
name: "Implementation Loop",
pose: null,
builds: false, phased: false, metered: false, templates: false,
weight: null, started: null, ran: null, resume: null,
subagents: null,
states: ["documented", "building"],
greyed: BUILD_GREYED,
card: {
group: "pipeline",
chip: "Step 3",
spec: true,
title: "Implementation Loop",
blurb: "Build every remaining phase unattended, one fresh agent per phase.",
about:
"Builds every remaining phase of the spec without you at the keyboard. Each phase gets a fresh agent that builds it and reviews it. The app checks the result against the spec, runs your quick check, commits, and moves on. It stops at the first phase that goes wrong and tells you why. Desktop app only.",
},
}),
skill({
skill: "plan2code-4-finalize",
workflow: "finalize",
@@ -413,11 +444,15 @@ export const SKILLS = Object.freeze([
}),
]);
const BY_WORKFLOW = new Map(SKILLS.map((s) => [s.workflow, s]));
const BY_SKILL = new Map(SKILLS.map((s) => [s.skill, s]));
// The entries that are skills with a workflow, in SKILLS order: what every
// list derived from the workflows is built from (an `appOnly` card is not one).
export const FLOW_SKILLS = Object.freeze(SKILLS.filter((s) => !s.appOnly));
const BY_WORKFLOW = new Map(FLOW_SKILLS.map((s) => [s.workflow, s]));
const BY_SKILL = new Map(FLOW_SKILLS.map((s) => [s.skill, s]));
// Every workflow name the console knows, in SKILLS order.
export const WORKFLOWS = Object.freeze(SKILLS.map((s) => s.workflow));
export const WORKFLOWS = Object.freeze(FLOW_SKILLS.map((s) => s.workflow));
/** Whether a name is one of WORKFLOWS (`open --workflow`, `handoff new --workflow`). */
export function isWorkflow(name) {
+15
View File
@@ -111,6 +111,21 @@ export const page = {
// false until the first frame lands, same as every other flag here, and
// from an older server that sends none.
inApp: false,
// The Implementation Loop, as the desktop app drives it: `loop` is the
// state's `{ driving: true }` or null (it locks the page, selectors.js
// loopDriving); `loopFacts` is what the app answered to `loop-facts`
// (agent, model, effort, permission mode, prompt support); `loopStart` is
// `{ ok, error }` once the app answered a `loop-start`; `loopAction` is the
// same for the stop screen's Resume, Fix and Finalize; `loopNotifyTest` is
// Send a test's `{ waiting }`, then `{ ok, sent, error }` once the app answered.
loop: null,
// The setup screen the dashboard's Implementation Loop card opened, or null
// (screens/loop-setup.js owns the shape).
loopSetup: null,
loopFacts: null,
loopStart: null,
loopNotifyTest: null,
loopAction: null,
// The frame's Subagents switch ({ offered, supported, on, instruction, max,
// revision }), or null before a server that sends it.
subagentsFrame: null,
+76 -9
View File
@@ -7,7 +7,8 @@
rule, so it needs saying here. */
.footer[hidden] { display: none; }
.dash { max-width: 860px; padding-top: 8px; }
/* The menu follows the Card width setting like the question column does. */
.dash { max-width: min(var(--card-width), 100%); padding-top: 8px; }
.dash-title { margin: 6px 0 8px; font: 600 clamp(26px, 4vw, 36px)/1.1 var(--serif); }
.dash-note { margin: 0 0 26px; font-size: 14.5px; color: var(--ink-2); }
/* The first-run role nudge: one line above the title, wrapping on a narrow
@@ -379,10 +380,10 @@
/* ------------------------------------------------- dashboard confirm */
/* The beat between "I clicked a card" and "it is running": what the pick is,
what it will do, and a START that means it. Narrower than the menu, centered
like the launching pane it precedes. */
what it will do, and a START that means it. As wide as the menu (the page
width setting), centered like the launching pane it precedes. */
.dash-confirm {
max-width: 560px;
max-width: min(var(--card-width), 100%);
margin: 3vh auto 0;
display: grid;
gap: 10px;
@@ -406,6 +407,9 @@
.confirm-head { display: flex; align-items: center; gap: 8px; margin-top: 4px; }
.dash-confirm .dash-title { margin: 2px 0 0; }
/* The pane is as wide as the menu, but prose is not: its lines stop at a
readable measure while the controls below keep the full width. */
.confirm-about, .confirm-detail, .confirm-spec { max-width: 70ch; }
.confirm-about { margin: 0; font-size: 14.5px; line-height: 1.55; color: var(--ink-2); }
.confirm-detail { margin: 0; font-size: 13px; color: var(--accent); }
.confirm-spec { margin: 0; font-size: 13px; color: var(--ink-2); }
@@ -428,9 +432,23 @@
/* "Start with a note from your Notebook": the switch, then the tabs beside a
preview of the picked one, its pictures each with a tick. */
.confirm-note-box { display: grid; gap: 8px; }
.confirm-note-switch { display: flex; gap: 8px; align-items: center; color: var(--ink-2); cursor: pointer; }
.confirm-note-switch input { accent-color: var(--accent, currentColor); }
/* Stretched past the confirm's centering, and left aligned: a note reads as
a document, not a caption. */
/* Its own frame sets it apart from the text above, so no rule: just room. */
.confirm-note-box { display: grid; gap: 8px; justify-self: stretch; text-align: left; margin-top: 12px; }
.confirm-note-head {
display: grid;
gap: 2px;
padding: 10px 12px;
border: 1px solid var(--accent-line);
border-left: 3px solid var(--accent);
border-radius: 8px;
background: var(--accent-soft);
}
.confirm-note-head.is-on { padding: 8px 12px; }
.confirm-note-switch { display: flex; gap: 10px; align-items: center; color: var(--ink); font-weight: 600; cursor: pointer; }
.confirm-note-switch input { width: 18px; height: 18px; margin: 0; flex: none; accent-color: var(--accent, currentColor); }
.confirm-note-hint { padding-left: 28px; font-size: 12.5px; color: var(--ink-2); }
.confirm-note { display: grid; grid-template-columns: minmax(130px, 200px) minmax(0, 1fr); gap: 10px; }
.confirm-note > .confirm-note-msg { grid-column: 1 / -1; }
.confirm-note-msg { margin: 0; font-size: 13px; color: var(--ink-3); }
@@ -480,7 +498,7 @@
/* ------------------------------------------------------- launching pane */
.launching {
max-width: 560px;
max-width: min(var(--card-width), 100%);
margin: 4vh auto 0;
text-align: center;
display: grid;
@@ -539,5 +557,54 @@
}
.launch-hint { margin: 0; font-size: 12.5px; color: var(--ink-3); max-width: 46ch; }
/* A line, never a banner: no border, no background, no icon. */
.approval-tip { margin: 18px 0 0; font-size: 12.5px; line-height: 1.5; color: var(--ink-3); }
.approval-tip { max-width: 70ch; margin: 18px 0 0; font-size: 12.5px; line-height: 1.5; color: var(--ink-3); }
/* --------------------------------------------- the Implementation Loop */
/* The card's own link; a span, since a link may not sit inside a button. */
.dash-card-link { font-size: 12px; color: var(--accent); text-decoration: underline; cursor: pointer; justify-self: start; }
/* The setup screen: the confirm pane's width, with a left-aligned form. */
.loop-setup { justify-items: stretch; text-align: left; gap: 14px; }
.loop-setup .card-kicker, .loop-setup .dash-title, .loop-setup .confirm-spec { justify-self: start; }
.loop-lines { display: grid; gap: 4px; }
.loop-line { margin: 0; font-size: 14px; line-height: 1.5; color: var(--ink-2); max-width: 75ch; }
.loop-facts { display: grid; gap: 6px; margin: 0; padding: 12px 14px; background: var(--panel-2); border: 1px solid var(--rule); border-radius: 8px; }
.loop-fact { display: grid; grid-template-columns: minmax(130px, 200px) 1fr; gap: 10px; font-size: 13px; }
.loop-fact dt { color: var(--ink-3); }
.loop-fact dd { margin: 0; color: var(--ink); overflow-wrap: anywhere; white-space: pre-line; }
.loop-form { display: grid; gap: 16px; }
.loop-field { display: grid; gap: 6px; }
.loop-label { margin: 0; font-weight: 600; font-size: 13.5px; }
.loop-hint { margin: 0; font-size: 12.5px; color: var(--ink-3); }
.loop-switch, .loop-radio { display: flex; gap: 8px; align-items: flex-start; cursor: pointer; font-size: 14px; color: var(--ink-2); }
.loop-switch input, .loop-radio input { accent-color: var(--accent, currentColor); margin-top: 3px; }
.loop-radios { display: grid; gap: 6px; }
.loop-radio-body { display: grid; gap: 1px; }
.loop-radio-detail { font-size: 12.5px; color: var(--ink-3); }
.loop-ticks { display: flex; flex-wrap: wrap; gap: 6px 18px; margin-left: 4px; }
.loop-text { font: inherit; font-size: 14px; padding: 6px 10px; color: var(--ink); background: var(--panel-2); border: 1px solid var(--rule); border-radius: 6px; max-width: 520px; width: 100%; }
.loop-text.loop-narrow { width: 90px; }
.loop-text.loop-param { width: 180px; }
.loop-test { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }
.loop-test p { margin: 0; font-size: 12.5px; }
.loop-number { display: flex; align-items: center; gap: 10px; font-size: 14px; color: var(--ink-2); }
.loop-warn { margin: 0; font-size: 12.5px; color: var(--warn); }
.loop-start { display: grid; gap: 8px; justify-items: start; }
.loop-why { margin: 0; font-size: 13px; color: var(--ink-2); }
.loop-error { margin: 0; font-size: 13px; color: var(--warn); }
.loop-problems { margin: 0; padding-left: 18px; font-size: 13px; color: var(--warn); }
.loop-help { margin-left: auto; }
/* A card the loop holds: a record with a tag, no inputs. */
.card.is-loop-handled .loop-tag { margin: 0 0 4px; font-weight: 600; color: var(--accent); }
.card.is-loop-locked .answered { opacity: 0.85; }
/* The stop and finish screens the loop's end draws. */
.loop-end { display: grid; gap: 14px; }
.loop-end-phases { width: 100%; border-collapse: collapse; font-size: 13.5px; }
.loop-end-phases th, .loop-end-phases td { text-align: left; padding: 5px 10px 5px 0; border-bottom: 1px solid var(--rule); vertical-align: top; }
.loop-end-phases code { font-family: var(--mono); font-size: 12px; }
.loop-end-files { margin: 0; padding-left: 18px; font-family: var(--mono); font-size: 12px; color: var(--ink-2); }
.loop-end-actions { display: flex; flex-wrap: wrap; gap: 10px; }
+3 -3
View File
@@ -6,8 +6,8 @@
appearance: none;
flex: none;
margin-left: 14px;
width: 30px;
height: 30px;
width: 36px;
height: 36px;
padding: 0;
display: grid;
place-items: center;
@@ -17,7 +17,7 @@
cursor: pointer;
}
.icon-btn:hover { background: var(--panel-2); border-color: var(--rule); }
.icon-btn svg { width: 17px; height: 17px; }
.icon-btn svg { width: 22px; height: 22px; }
.icon-btn .ab-ring { fill: none; stroke: var(--ink-3); stroke-width: 1.4; }
.icon-btn .ab-mark { fill: none; stroke: var(--ink-2); stroke-width: 1.5; stroke-linecap: round; }
.icon-btn .ab-dot { fill: var(--ink-2); }
+4 -2
View File
@@ -210,10 +210,12 @@
flex: none;
margin: 0 2px 0 2px;
padding: 1px 5px;
border: 1px solid var(--rule-2);
border: 1px solid var(--accent-line);
border-radius: 999px;
color: var(--ink-3);
background: var(--accent-soft);
color: var(--accent);
font-size: 10.5px;
font-weight: 600;
line-height: 1.3;
white-space: nowrap;
}
+3 -1
View File
@@ -74,6 +74,7 @@
/* ------------------------------------------------------------ options */
.options { list-style: none; margin: 20px 0 0; padding: 0; display: grid; gap: 9px; }
.options-clear { margin-top: 10px; }
.option {
display: flex;
@@ -772,6 +773,7 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
.modal.looks { max-width: 720px; }
.modal.looks .modal-ranges + .modal-ranges { margin-top: 18px; }
.looks-row { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.looks-row.four { grid-template-columns: repeat(4, minmax(0, 1fr)); }
.looks-row .help { grid-column: 1 / -1; }
/* The Desktop app group exists only inside the app; elsewhere it stays hidden
in spite of the grid above. */
@@ -783,7 +785,7 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
.looks-sound-events.is-off label { cursor: default; }
.looks-sound-events.is-off label:hover { border-color: var(--rule-2); }
@media (max-width: 720px) {
.looks-row { grid-template-columns: 1fr; }
.looks-row, .looks-row.four { grid-template-columns: 1fr; }
}
/* User Preferences itself (not the dialogs borrowing .looks): wider, and only
the body scrolls, so Back to default and Done never leave the screen. */
+188
View File
@@ -0,0 +1,188 @@
/* prefs.css: User Preferences' tabs (the side list, the narrow strip), the Saved
mark, the Agents & models table and form, and the unsaved prompt. */
/* --------------------------------------------------------- tabs and panels */
.prefs-layout {
display: grid;
grid-template-columns: 200px minmax(0, 1fr);
gap: 20px;
align-items: start;
}
.prefs-tabs {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
}
.prefs-tab {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 2px;
width: 100%;
padding: 8px 10px;
border: 0;
border-left: 3px solid transparent;
border-radius: 6px;
background: transparent;
color: var(--ink-2);
font: inherit;
font-size: 13.5px;
text-align: left;
cursor: pointer;
}
.prefs-tab:hover { background: var(--panel-2); color: var(--ink); }
.prefs-tab[aria-selected="true"] { background: var(--accent-soft); color: var(--accent); border-left-color: var(--accent); font-weight: 600; }
.prefs-tab:focus-visible { outline: 2px solid var(--focus); outline-offset: 1px; }
.prefs-tab-label { display: block; line-height: 1.3; }
.prefs-tab-hint { display: block; font-size: 12px; line-height: 1.35; color: var(--ink-3); }
.prefs-panels { min-width: 0; }
.prefs-panel[hidden] { display: none; }
/* --------------------------------------------------------- Saved mark */
/* At the fieldset's top right, level with its legend. Out of the flow: the
fieldsets are grids (the shared range and row classes), where an in-flow mark
would take a cell and push the choices about. It fades out after about
2 s when the JS adds `is-saved`; an `error` stays put and never fades. */
.prefs-panel fieldset { position: relative; }
.prefs-saved {
position: absolute;
top: 0;
right: 0;
max-width: 60%;
font-size: 12px;
line-height: 1.3;
text-align: right;
color: var(--ok);
opacity: 0;
}
.prefs-saved.is-saved { opacity: 1; }
.prefs-saved.error { color: var(--danger, #d64545); opacity: 1; }
@media (prefers-reduced-motion: no-preference) {
@keyframes prefs-saved-fade {
0%, 70% { opacity: 1; }
100% { opacity: 0; }
}
.prefs-saved.is-saved { animation: prefs-saved-fade 2s ease-out forwards; }
}
@media (prefers-reduced-motion: reduce) {
.prefs-saved.is-saved { opacity: 1; }
}
/* --------------------------------------------------------- Agents & models */
.prefs-agents { display: grid; gap: 10px; }
.prefs-agents > .help { margin: 0; }
.prefs-agents [hidden] { display: none; }
#agents-status:empty { display: none; }
#agents-status.error { color: var(--danger, #d64545); }
#agents-add { justify-self: start; }
.prefs-agents-table { width: 100%; border-collapse: collapse; font-size: 13.5px; }
.prefs-agents-table th {
text-align: left;
font-weight: 600;
font-size: 12px;
color: var(--ink-3);
padding: 4px 8px;
border-bottom: 1px solid var(--rule-2);
}
.prefs-agents-table td { padding: 8px; border-bottom: 1px solid var(--rule-2); vertical-align: top; }
.prefs-agents-name span, .prefs-agents-name code { display: block; }
.prefs-agents-name code { font-size: 12px; color: var(--ink-3); }
.prefs-agents-name .help { margin-top: 2px; font-size: 12px; }
.prefs-agents-models { color: var(--ink-2); overflow-wrap: anywhere; }
.prefs-agents-edit { text-align: right; }
.prefs-agents-soon td { color: var(--ink-3); font-style: italic; }
.prefs-badge, .prefs-unsaved-badge {
display: inline-block;
font-size: 11.5px;
line-height: 1.5;
padding: 0 7px;
border-radius: 10px;
background: var(--panel-2);
color: var(--ink-3);
white-space: nowrap;
}
.prefs-badge.ok { color: var(--ok); }
.prefs-badge.missing { color: var(--warn); }
.prefs-unsaved-badge { background: none; border: 1px solid var(--warn); color: var(--warn); }
.prefs-agents-form { display: grid; gap: 10px; }
.prefs-agents-back { justify-self: start; }
.prefs-agents-title { display: flex; align-items: baseline; gap: 8px; margin: 0; font-size: 15px; }
.prefs-agents-title code { font-size: 12px; color: var(--ink-3); }
.prefs-agents-title:focus { outline: none; }
.prefs-agents-fields { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 10px 14px; }
.prefs-agents-fields > .models-note,
.prefs-agents-fields > [data-field="models"],
.prefs-agents-fields > .prefs-agents-args,
.prefs-agents-fields > .agent-field:has(> .models-list),
.prefs-agents-fields > .agent-field:has(> .prefs-agents-none) { grid-column: 1 / -1; }
.prefs-agents-form input { min-width: 0; }
.prefs-agents-form input.invalid { border-color: var(--danger, #d64545); }
.prefs-agents-test { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.prefs-agents-test .help { margin: 0; }
.prefs-agents-none { margin: 0; }
.prefs-agents-args { display: grid; gap: 8px; }
.prefs-agents-args > summary { cursor: pointer; color: var(--accent); font-size: 13px; }
.prefs-agents-args[open] > summary { margin-bottom: 4px; }
.prefs-agents-args > .agent-field + .agent-field { margin-top: 8px; }
/* The Saved mark sits in the form's foot, in the flow, after the buttons. */
.prefs-agents-foot > .prefs-saved { position: static; max-width: none; text-align: left; }
/* --------------------------------------------------------- unsaved prompt */
/* Over the dialog, inside it: never the browser's confirm(). */
.prefs-unsaved {
position: absolute;
inset: 0;
z-index: 5;
display: grid;
place-items: center;
padding: 16px;
background: color-mix(in srgb, var(--bg, #000) 55%, transparent);
}
.prefs-unsaved[hidden] { display: none; }
.prefs-unsaved-box {
max-width: 380px;
padding: 16px 18px;
border: 1px solid var(--rule-2);
border-radius: 10px;
background: var(--panel);
box-shadow: 0 8px 30px rgb(0 0 0 / 0.25);
}
.prefs-unsaved-box h3 { margin: 0 0 6px; font-size: 15px; }
.prefs-unsaved-box p { margin: 0 0 12px; }
.prefs-unsaved-actions { display: flex; flex-wrap: wrap; gap: 8px; }
/* --------------------------------------------------------- narrow screens */
@media (max-width: 720px) {
.prefs-layout { grid-template-columns: 1fr; gap: 12px; }
.prefs-tabs {
flex-direction: row;
overflow-x: auto;
overflow-y: hidden;
padding: 0 0 4px;
-webkit-mask-image: linear-gradient(to right, #000 calc(100% - 32px), transparent);
mask-image: linear-gradient(to right, #000 calc(100% - 32px), transparent);
}
.prefs-tab {
width: auto;
flex: none;
white-space: nowrap;
border-left: 0;
border-bottom: 3px solid transparent;
border-radius: 6px 6px 0 0;
}
.prefs-tab[aria-selected="true"] { border-bottom-color: var(--accent); }
.prefs-tab-hint { display: none; }
.prefs-agents-models { display: none; }
.prefs-agents-fields { grid-template-columns: 1fr; }
}
@@ -96,8 +96,6 @@
}
/* User Preferences: the launcher's model menu. */
.models-tabs { display: flex; gap: 6px; }
.models-tabs .btn[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); }
.models-note { font-size: 0.9em; opacity: 0.85; }
.models-note p, .models-note ul { margin: 0 0 6px; }
.models-note ul { padding-left: 18px; }
@@ -108,13 +106,6 @@
.models-row input { min-width: 0; }
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.models-actions .help.error { color: var(--danger, #d64545); }
.agents-list { display: grid; gap: 10px; }
.agents-list:empty { display: none; }
.agent-card { display: grid; gap: 8px; padding: 10px; border: 1px solid var(--rule-2); border-radius: 8px; }
.agent-card.invalid { border-color: var(--danger, #d64545); }
.agent-card input { min-width: 0; }
.agent-card input.invalid { border-color: var(--danger, #d64545); }
.agent-top { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 6px; }
.agent-field { display: grid; gap: 4px; min-width: 0; }
.agent-field > span, .agent-field > label { font-size: 0.85em; opacity: 0.85; }
.agent-rows { display: grid; gap: 4px; }
@@ -124,7 +115,6 @@
.agent-foot .help { margin: 0; }
.agent-foot .agent-test-result { flex: 1 1 auto; }
.agent-error { margin: 0; color: var(--danger, #d64545); font-size: 0.9em; }
#agents-replace[hidden] { display: none; }
/* User Preferences: Cleanup's list of what would go, shown before anything
is deleted. */
+4 -2
View File
@@ -178,7 +178,7 @@ h1 {
grows to fill the row, so the icon buttons would sit beside the title. The
first takes the slack instead; with the block shown its flex already eats
the space, so this costs nothing. */
#btn-about { margin-left: auto; }
#btn-looks { margin-left: auto; }
.progress-label {
display: flex;
@@ -516,6 +516,8 @@ h1 {
.footer.is-dash .footer-actions { display: none; }
.footer.is-dash .footer-where { grid-column: 2; }
.footer.is-dash-done .footer-actions { display: none; }
.footer.is-loop-idle .footer-summary,
.footer.is-loop-idle .footer-actions { visibility: hidden; }
.hint { font-size: 12.5px; color: var(--ink-3); display: flex; align-items: center; gap: 7px; }
/* A label, not a sentence: the full reason rides in the hint's tooltip, and
the dock already carries the ticking clock this would otherwise repeat. */
@@ -544,7 +546,7 @@ kbd {
justify-items: center;
}
.waiting-pane h2 { font: 600 23px/1.3 var(--serif); color: var(--ink); margin: 0; }
.waiting-pane p { margin: 0; }
.waiting-pane p { max-width: 70ch; margin: 0; }
/* The words that open the tasks tab: bold in the highlight color, a button
that reads as part of the sentence. */
.waiting-jump {
+1
View File
@@ -46,6 +46,7 @@
which validates the saved choice and paints data-width on first load. */
:root[data-width="narrow"] { --card-width: 720px; }
:root[data-width="wide"] { --card-width: 1080px; }
:root[data-width="ultrawide"] { --card-width: 1440px; }
/* Dark is written twice on purpose, and the duplication is the whole mechanism.
The first copy follows the system unless the person has explicitly asked for
+10 -8
View File
@@ -89,7 +89,9 @@ export function cleanSetting(input) {
/* ------------------------------------------------------------ the lines */
// The non-editable part of every "on" block (FR-8).
// The non-editable part an "on" block used to carry (FR-8). The block now says
// state, strength and limit in one line; these sentences move to
// console-subagents.md (Phase 5). Still exported for the suites that read them.
export const FRAME_LINES = Object.freeze([
"Hand independent work to helpers if your tools allow it; otherwise carry on alone.",
"Report each helper on the page (console-subagents.md); questions for the person stay with you.",
@@ -99,7 +101,7 @@ export const FRAME_LINES = Object.freeze([
export const PATHFINDER_RESEARCH_LINE = "Research questions always use helpers, whatever this switch says.";
// The profile line each strength adds to an "on" block.
// The profile sentence each strength used to add to an "on" block; see FRAME_LINES.
export const STRENGTH_LINES = Object.freeze({
balanced: "Helper strength: balanced (the table in helper-strength.md as written).",
thrifty: "Helper strength: thrifty (one step lighter in strength and effort than the table; reviews never below standard).",
@@ -109,20 +111,20 @@ export const STRENGTH_LINES = Object.freeze({
// Only the first line of a block starts at column 0, so no line inside it can
// be read as an entry of its own (NFR-5).
export function onLines({ revision, replaces, max, instruction, strength }) {
const label = replaces ? `revision ${revision}, replaces revision ${replaces}` : `revision ${revision}`;
export function onLines({ max, instruction, strength }) {
const own = String(instruction || "")
.split("\n")
.map((line) => line.trimEnd())
.filter((line) => line.trim());
const word = STRENGTHS.includes(strength) ? strength : DEFAULT_STRENGTH;
return [
`Subagents: on (${label}) — a console setting, not typed by the person.`,
...[...FRAME_LINES, ...own, STRENGTH_LINES[strength] || STRENGTH_LINES[DEFAULT_STRENGTH], `At most ${max} helpers at once.`].map((line) => " " + line),
`Subagents: on, ${word} strength, at most ${max} helpers at once (a console setting, not typed by the person).`,
...own.map((line) => " " + line),
];
}
export function offLine(revision) {
return `Subagents: off (revision ${revision}) — don't start new helpers for the rest of this session.`;
export function offLine() {
return "Subagents: off. Start no new helpers for the rest of this session.";
}
/**
+103
View File
@@ -0,0 +1,103 @@
// Plan2Code Web Console - tabs shared by Help and User Preferences.
//
// The WAI-ARIA tabs pattern over panels built once in the markup and shown or
// hidden: role="tab" buttons linked to their role="tabpanel", roving
// tabindex, automatic activation, arrow keys plus Home and End. No DOM access
// at module scope: `node --test` imports tabKeyTarget from here.
// The tab index a key moves to, or -1 when the key is not a tab key.
export function tabKeyTarget(key, index, count) {
switch (key) {
case "ArrowDown":
case "ArrowRight":
return (index + 1) % count;
case "ArrowUp":
case "ArrowLeft":
return (index - 1 + count) % count;
case "Home":
return 0;
case "End":
return count - 1;
default:
return -1;
}
}
// Below Help's breakpoint the side list becomes a strip across the top.
const NARROW = "(max-width: 720px)";
// `tabs` is [{ id, label, hint? }], `list` the role="tablist" element and
// `panels` the element holding one child per tab marked data-tab="<id>".
// `beforeSelect(from, to)` returning false, or a Promise of false, holds the
// switch; `onSelect(id)` runs after one.
export function wireTabs({ tabs, list, panels, prefix, tabClass, renderTab, beforeSelect, onSelect }) {
const tabId = (id) => `${prefix}-tab-${id}`;
const panelId = (id) => `${prefix}-panel-${id}`;
let selected = null;
for (const t of tabs) {
const btn = document.createElement("button");
btn.type = "button";
btn.className = tabClass;
btn.id = tabId(t.id);
btn.setAttribute("role", "tab");
btn.setAttribute("aria-controls", panelId(t.id));
btn.setAttribute("aria-selected", "false");
btn.tabIndex = -1;
if (renderTab) renderTab(t, btn);
else {
const label = document.createElement("span");
label.textContent = t.label;
btn.appendChild(label);
}
btn.addEventListener("click", () => select(t.id));
list.appendChild(btn);
const panel = panels.querySelector(`[data-tab="${t.id}"]`);
panel.id = panelId(t.id);
panel.setAttribute("role", "tabpanel");
panel.setAttribute("aria-labelledby", tabId(t.id));
panel.tabIndex = 0;
panel.hidden = true;
}
list.addEventListener("keydown", (e) => {
const current = tabs.findIndex((t) => tabId(t.id) === e.target.id);
if (current < 0) return;
const n = tabKeyTarget(e.key, current, tabs.length);
if (n < 0) return;
e.preventDefault();
select(tabs[n].id, { focus: true });
});
const narrow = matchMedia(NARROW);
const orient = () => list.setAttribute("aria-orientation", narrow.matches ? "horizontal" : "vertical");
orient();
narrow.addEventListener("change", orient);
async function select(id, { focus = false } = {}) {
if (beforeSelect && selected !== null && selected !== id) {
// Awaited only when it is a Promise, so a plain answer switches in this
// same tick and a caller can focus the new tab straight after.
let go = beforeSelect(selected, id);
if (go && typeof go.then === "function") go = await go;
if (go === false) {
// Held: focus stays on the tab still selected.
if (focus) document.getElementById(tabId(selected)).focus();
return false;
}
}
for (const t of tabs) {
const on = t.id === id;
const btn = document.getElementById(tabId(t.id));
btn.setAttribute("aria-selected", String(on));
btn.tabIndex = on ? 0 : -1;
document.getElementById(panelId(t.id)).hidden = !on;
}
selected = id;
if (onSelect) onSelect(id);
if (focus) document.getElementById(tabId(id)).focus();
return true;
}
return { select, current: () => selected };
}
+611 -7
View File
@@ -1,6 +1,18 @@
// Plan2Code Web Console - the tones: short synthesized blips for the activities, silent when Play sounds is off; defines only.
import { looks } from "./looks.js";
import snakeSfx from "./activities/snake-sfx.js";
import golfSfx from "./activities/golf-sfx.js";
import trailsSfx from "./activities/trails-sfx.js";
import bugsSfx from "./activities/bugs-sfx.js";
import driveSfx from "./activities/drive-sfx.js";
import stackSfx from "./activities/stack-sfx.js";
import bumperSfx from "./activities/bumper-sfx.js";
import rapidsSfx from "./activities/rapids-sfx.js";
import fuseSfx from "./activities/fuse-sfx.js";
import hopSfx from "./activities/hop-sfx.js";
import bounceSfx from "./activities/bounce-sfx.js";
import ghoulSfx from "./activities/ghoul-sfx.js";
/* ------------------------------------------------------------- tones
@@ -14,7 +26,7 @@ import { looks } from "./looks.js";
Every sound here is short (a quarter second at most) and quiet, so a cue
never outlasts the moment it belongs to. A tone either sweeps from one
pitch to another, or plays `notes` one after another in its time. */
const TONES = Object.freeze({
const BLIPS = Object.freeze({
eat: Object.freeze({ type: "triangle", from: 660, to: 880, seconds: 0.12 }),
crash: Object.freeze({ type: "sawtooth", from: 220, to: 80, seconds: 0.2 }),
// The 3, 2, 1 before a round starts or plays on: a tick per number, then a
@@ -52,8 +64,337 @@ const TONES = Object.freeze({
shield: Object.freeze({ type: "sine", from: 1200, to: 500, seconds: 0.14 }),
zap: Object.freeze({ type: "sawtooth", from: 1400, to: 200, seconds: 0.15 }),
best: Object.freeze({ type: "triangle", notes: Object.freeze([784, 988, 1175, 1568]), seconds: 0.25 }),
// Stack Deploy: a block landing (a low thunk), the overhang sliced off,
// and a perfect drop's chime. The game pitches the thunk and the chime up
// a step of a scale for each perfect in a row.
thunk: Object.freeze({ type: "triangle", from: 240, to: 110, seconds: 0.1 }),
slice: Object.freeze({ type: "square", from: 560, to: 280, seconds: 0.06 }),
perfect: Object.freeze({ type: "triangle", notes: Object.freeze([660, 990]), seconds: 0.14 }),
// Bumper Ring: two cars meeting (a short thud the game pitches up and
// makes louder the harder the hit) and a rival revving up a dash.
ram: Object.freeze({ type: "square", from: 190, to: 70, seconds: 0.09 }),
rev: Object.freeze({ type: "sawtooth", from: 90, to: 260, seconds: 0.18 }),
// Hot Potato: the fuse's tick (the game ticks it quicker and pitches it
// up as the fuse burns down) and the pop of the bomb changing hands.
tick: Object.freeze({ type: "square", from: 1500, to: 1100, seconds: 0.03 }),
pop: Object.freeze({ type: "sine", from: 480, to: 1400, seconds: 0.07 }),
// Crossing Rush: a hop (the game pitches it up a step for each quick hop
// forward in a row), the boing of being sent back, a crossing's bell while
// a train is coming, and the Horn.
hop: Object.freeze({ type: "triangle", from: 520, to: 780, seconds: 0.05 }),
boing: Object.freeze({ type: "sine", from: 260, to: 720, seconds: 0.2 }),
bell: Object.freeze({ type: "triangle", notes: Object.freeze([1320, 990]), seconds: 0.16 }),
horn: Object.freeze({ type: "square", notes: Object.freeze([370, 466]), seconds: 0.22 }),
// Bounce Road: the engine's hum (a soft, low blip the game plays every few
// frames while you pick up speed, pitched up with your speed: a triangle,
// since a sawtooth blipped that often is a buzz), a jump's spring (pitched
// with your speed) and a rival flattened under your wheels (pitched up a
// step for each in a chain); all soft triangles, never a buzz. A low
// thump rumbles while your wheels run on the verge.
beat: Object.freeze({ type: "sine", from: 95, to: 55, seconds: 0.11 }),
engine: Object.freeze({ type: "triangle", from: 82, to: 90, seconds: 0.08 }),
spring: Object.freeze({ type: "triangle", from: 330, to: 990, seconds: 0.14 }),
squash: Object.freeze({ type: "triangle", from: 620, to: 150, seconds: 0.13 }),
// Rapids Run: a shot (a short, soft triangle, since it repeats about seven
// times a second while fire is held, and the game plays it quietly), a
// charge buoy taken (a rising sine), the low battery's two-note beep (the
// game beeps quicker the lower it runs), a dam bursting open (a low
// triangle rumble) and a bank skimmed at speed (a quick sine whoosh the
// game pitches up the more you have skimmed); all soft triangles and
// sines, never a buzz.
pew: Object.freeze({ type: "triangle", from: 1320, to: 880, seconds: 0.04 }),
charge: Object.freeze({ type: "sine", from: 440, to: 1320, seconds: 0.14 }),
lowcell: Object.freeze({ type: "sine", notes: Object.freeze([660, 440]), seconds: 0.16 }),
dambreak: Object.freeze({ type: "triangle", from: 300, to: 60, seconds: 0.25 }),
skim: Object.freeze({ type: "sine", from: 1500, to: 1800, seconds: 0.05 }),
// Ghoul Rush: the flashlight blaster's bolt (a short, soft triangle, since
// it repeats every 100 ms while fire is held; the game nudges its pitch a
// little each time), a ghoul torn apart (pitched up a step for each kill
// in the chain), a stomp's crunch, a ghost's moan, a boss's low roar, a
// soul's thin whisper (pitched up for souls taken in quick succession), a
// zombie groaning behind a wall door, a bat's screech, the key turning
// (a minor rise), the door through to the next room (a falling minor
// run), a board creaking (a crawler coming up, a chandelier or a crumbling
// board about to go), a hellhound's growl, a wraith's shriek, a widow's
// skitter, a bloater's wet spit, and thunder rolling outside.
ghoulBlast: Object.freeze({ type: "triangle", from: 980, to: 620, seconds: 0.05 }),
ghoulStomp: Object.freeze({ type: "sawtooth", from: 220, to: 70, seconds: 0.09 }),
ghoulBoo: Object.freeze({ type: "sine", from: 330, to: 196, seconds: 0.25 }),
ghoulRoar: Object.freeze({ type: "sawtooth", from: 120, to: 48, seconds: 0.25 }),
ghoulCandy: Object.freeze({ type: "sine", from: 1480, to: 1760, seconds: 0.09 }),
zombiePop: Object.freeze({ type: "sawtooth", from: 260, to: 60, seconds: 0.12 }),
zombieGroan: Object.freeze({ type: "sawtooth", from: 110, to: 72, seconds: 0.25 }),
batSwoop: Object.freeze({ type: "square", from: 2200, to: 1400, seconds: 0.08 }),
doorUnlock: Object.freeze({ type: "triangle", notes: Object.freeze([494, 587, 740]), seconds: 0.2 }),
doorThrough: Object.freeze({ type: "triangle", notes: Object.freeze([659, 587, 494, 440]), seconds: 0.25 }),
creakBoard: Object.freeze({ type: "triangle", from: 180, to: 120, seconds: 0.18 }),
ghoulGrowl: Object.freeze({ type: "sawtooth", from: 95, to: 70, seconds: 0.22 }),
ghoulShriek: Object.freeze({ type: "sawtooth", from: 1900, to: 2600, seconds: 0.2 }),
ghoulSkitter: Object.freeze({ type: "square", notes: Object.freeze([2400, 2100, 2500, 2200]), seconds: 0.1 }),
ghoulSpit: Object.freeze({ type: "square", from: 340, to: 110, seconds: 0.1 }),
ghoulThunder: Object.freeze({ type: "sawtooth", from: 70, to: 30, seconds: 0.25 }),
});
/* --------------------------------------------------------- rich tones
The shared sound kit every game may borrow, richer than a single blip:
a spec here may be `layers`, parts that play together (each its own
`delay` and `gain`), and a part may be noise ("noise" is white, "pink"
and "brown" darker) shaped by a `filter` ({ type, from, to, q }) that
sweeps its cutoff, wobble with `vibrato` ({ rate, depth }, depth a share
of the pitch) or swell in over `attack` seconds. Noise is what makes a
crash, a splash, a skid or an explosion sound like one rather than like
a beep. These run up to a second, still quiet, and a game's own extras
live in its `activities/<id>-sfx.js` (merged in below). */
const part = (spec) => Object.freeze({ ...spec, ...(spec.notes ? { notes: Object.freeze(spec.notes) } : {}), ...(spec.filter ? { filter: Object.freeze(spec.filter) } : {}), ...(spec.vibrato ? { vibrato: Object.freeze(spec.vibrato) } : {}) });
const layered = (...parts) => Object.freeze({ layers: Object.freeze(parts.map(part)) });
const RICH = Object.freeze({
// Hits, crashes and explosions.
explode: layered(
{ type: "brown", seconds: 0.8, filter: { type: "lowpass", from: 2400, to: 90, q: 0.7 } },
{ type: "sine", from: 140, to: 32, seconds: 0.55, gain: 0.9 },
{ type: "noise", seconds: 0.12, gain: 0.35, filter: { type: "highpass", from: 3000, to: 1500 } },
),
blast: layered(
{ type: "brown", seconds: 0.38, filter: { type: "lowpass", from: 1800, to: 140 } },
{ type: "sine", from: 110, to: 40, seconds: 0.26, gain: 0.8 },
),
smash: layered(
{ type: "noise", seconds: 0.36, filter: { type: "bandpass", from: 1800, to: 500, q: 1.1 } },
{ type: "square", from: 180, to: 55, seconds: 0.2, gain: 0.45, filter: { type: "lowpass", from: 1400, to: 300 } },
{ type: "noise", seconds: 0.28, delay: 0.04, gain: 0.25, filter: { type: "highpass", from: 5000, to: 3000 } },
),
thud: layered(
{ type: "sine", from: 130, to: 48, seconds: 0.14 },
{ type: "brown", seconds: 0.09, gain: 0.6, filter: { type: "lowpass", from: 500, to: 150 } },
),
clank: layered(
{ type: "square", from: 820, to: 790, seconds: 0.08, gain: 0.45, filter: { type: "lowpass", from: 3000, to: 1500 } },
{ type: "triangle", from: 1230, to: 1210, seconds: 0.22, gain: 0.5 },
{ type: "noise", seconds: 0.04, gain: 0.4, filter: { type: "bandpass", from: 3200, to: 2600, q: 2 } },
),
crunch: layered(
{ type: "noise", seconds: 0.18, filter: { type: "bandpass", from: 900, to: 280, q: 1.8 } },
{ type: "sawtooth", from: 150, to: 60, seconds: 0.12, gain: 0.4, filter: { type: "lowpass", from: 900, to: 200 } },
),
squish: layered(
{ type: "noise", seconds: 0.13, filter: { type: "lowpass", from: 1600, to: 200, q: 3 } },
{ type: "sine", from: 420, to: 110, seconds: 0.11, gain: 0.6 },
),
splat: layered(
{ type: "pink", seconds: 0.16, filter: { type: "bandpass", from: 1300, to: 380, q: 1.4 } },
{ type: "sine", from: 300, to: 85, seconds: 0.12, gain: 0.6 },
),
hit: layered(
{ type: "square", from: 320, to: 120, seconds: 0.07, gain: 0.6, filter: { type: "lowpass", from: 2400, to: 600 } },
{ type: "noise", seconds: 0.05, gain: 0.5, filter: { type: "bandpass", from: 2200, to: 1400, q: 1.5 } },
),
// Movement: air, tires and landings.
whoosh: layered({ type: "pink", seconds: 0.3, attack: 0.08, filter: { type: "bandpass", from: 400, to: 2600, q: 1.4 } }),
swoosh: layered({ type: "pink", seconds: 0.26, attack: 0.04, filter: { type: "bandpass", from: 2600, to: 450, q: 1.4 } }),
skid: layered(
{ type: "noise", seconds: 0.38, attack: 0.02, filter: { type: "bandpass", from: 2300, to: 1700, q: 7 } },
{ type: "triangle", from: 1500, to: 1280, seconds: 0.34, gain: 0.25, vibrato: { rate: 31, depth: 0.02 } },
),
brake: layered({ type: "noise", seconds: 0.3, attack: 0.03, filter: { type: "bandpass", from: 3100, to: 2500, q: 10 } }),
zoom: layered(
{ type: "sawtooth", from: 240, to: 130, seconds: 0.5, attack: 0.2, gain: 0.5, filter: { type: "lowpass", from: 1100, to: 380 } },
{ type: "pink", seconds: 0.5, attack: 0.2, gain: 0.6, filter: { type: "bandpass", from: 900, to: 380, q: 1.2 } },
),
jump: layered(
{ type: "triangle", from: 300, to: 760, seconds: 0.13 },
{ type: "pink", seconds: 0.12, gain: 0.3, filter: { type: "highpass", from: 1400, to: 2600 } },
),
land: layered(
{ type: "sine", from: 170, to: 60, seconds: 0.1 },
{ type: "brown", seconds: 0.1, gain: 0.6, filter: { type: "lowpass", from: 700, to: 200 } },
),
shift: layered(
{ type: "noise", seconds: 0.035, gain: 0.5, filter: { type: "bandpass", from: 2400, to: 2000, q: 3 } },
{ type: "square", from: 160, to: 140, seconds: 0.05, gain: 0.4, filter: { type: "lowpass", from: 900, to: 500 } },
),
boost: layered(
{ type: "sawtooth", from: 110, to: 460, seconds: 0.48, gain: 0.6, filter: { type: "lowpass", from: 400, to: 3200, q: 4 } },
{ type: "pink", seconds: 0.48, gain: 0.45, filter: { type: "highpass", from: 1200, to: 4200 } },
),
riser: layered(
{ type: "sawtooth", from: 200, to: 1200, seconds: 0.62, attack: 0.3, gain: 0.5, filter: { type: "lowpass", from: 600, to: 4200 } },
{ type: "noise", seconds: 0.62, attack: 0.3, gain: 0.35, filter: { type: "bandpass", from: 500, to: 4000, q: 1 } },
),
honk: layered(
{ type: "square", from: 392, to: 388, seconds: 0.24, gain: 0.55, filter: { type: "lowpass", from: 1600, to: 1400 } },
{ type: "square", from: 494, to: 490, seconds: 0.24, gain: 0.55, filter: { type: "lowpass", from: 1600, to: 1400 } },
),
trainHorn: layered(
{ type: "sawtooth", from: 311, to: 305, seconds: 0.85, attack: 0.05, gain: 0.4, filter: { type: "lowpass", from: 1500, to: 1200 } },
{ type: "sawtooth", from: 370, to: 364, seconds: 0.85, attack: 0.05, gain: 0.4, filter: { type: "lowpass", from: 1500, to: 1200 } },
{ type: "sawtooth", from: 466, to: 458, seconds: 0.85, attack: 0.05, gain: 0.3, filter: { type: "lowpass", from: 1500, to: 1200 } },
),
rumble: layered({ type: "brown", seconds: 0.06, filter: { type: "lowpass", from: 320, to: 200 } }),
rumbleLong: layered(
{ type: "brown", seconds: 1, attack: 0.2, filter: { type: "lowpass", from: 420, to: 160 } },
{ type: "sine", from: 52, to: 44, seconds: 1, attack: 0.2, gain: 0.6 },
),
// Water.
splashBig: layered(
{ type: "noise", seconds: 0.42, filter: { type: "bandpass", from: 3200, to: 700, q: 0.7 } },
{ type: "sine", from: 380, to: 95, seconds: 0.16, gain: 0.45 },
{ type: "pink", seconds: 0.3, delay: 0.08, gain: 0.35, filter: { type: "highpass", from: 2500, to: 1500 } },
),
bubble: layered({ type: "sine", from: 300, to: 950, seconds: 0.06 }),
slap: layered({ type: "pink", seconds: 0.15, filter: { type: "bandpass", from: 950, to: 480, q: 1.5 } }),
// Rewards and the round.
coinUp: layered(
{ type: "square", notes: [988, 1319], seconds: 0.11, gain: 0.55, filter: { type: "lowpass", from: 5000, to: 5000 } },
{ type: "triangle", from: 2637, to: 2637, seconds: 0.26, delay: 0.05, gain: 0.3 },
),
sparkle: layered(
{ type: "triangle", notes: [1568, 2093, 2637, 3136], seconds: 0.22, gain: 0.5 },
{ type: "noise", seconds: 0.22, gain: 0.15, filter: { type: "highpass", from: 6000, to: 8000 } },
),
powerUp: layered(
{ type: "square", notes: [523, 659, 784, 1047, 1319], seconds: 0.36, gain: 0.45, filter: { type: "lowpass", from: 3000, to: 3000 } },
{ type: "triangle", notes: [262, 330, 392, 523, 659], seconds: 0.36, gain: 0.6 },
),
powerDown: layered(
{ type: "square", notes: [784, 659, 523, 392], seconds: 0.36, gain: 0.45, filter: { type: "lowpass", from: 2400, to: 1200 } },
),
extraLife: layered(
{ type: "triangle", notes: [659, 784, 1319, 1047, 1175, 1568], seconds: 0.48 },
{ type: "square", notes: [330, 392, 659, 523, 587, 784], seconds: 0.48, gain: 0.25, filter: { type: "lowpass", from: 2000, to: 2000 } },
),
fanfare: layered(
{ type: "square", notes: [523, 523, 523, 659, 784, 784], seconds: 0.6, gain: 0.4, filter: { type: "lowpass", from: 2600, to: 2600 } },
{ type: "triangle", notes: [262, 262, 262, 330, 392, 392], seconds: 0.6, gain: 0.7 },
),
victory: layered(
{ type: "triangle", notes: [784, 988, 1175, 1568], seconds: 0.44 },
{ type: "square", notes: [392, 494, 587, 784], seconds: 0.44, gain: 0.3, filter: { type: "lowpass", from: 2400, to: 2400 } },
{ type: "noise", seconds: 0.3, delay: 0.3, gain: 0.12, filter: { type: "highpass", from: 7000, to: 9000 } },
),
gameOver: layered(
{ type: "triangle", notes: [392, 370, 349, 330], seconds: 0.9 },
{ type: "sawtooth", notes: [196, 185, 175, 165], seconds: 0.9, gain: 0.35, filter: { type: "lowpass", from: 900, to: 500 } },
),
lifeLost: layered(
{ type: "square", from: 520, to: 120, seconds: 0.42, gain: 0.6, vibrato: { rate: 12, depth: 0.04 }, filter: { type: "lowpass", from: 2000, to: 600 } },
),
click: layered({ type: "square", from: 1200, to: 1150, seconds: 0.02, gain: 0.4 }),
tickSoft: layered({ type: "noise", seconds: 0.025, filter: { type: "bandpass", from: 4200, to: 3800, q: 4 } }),
warn: layered(
{ type: "square", notes: [880, 660, 880, 660], seconds: 0.42, gain: 0.5, filter: { type: "lowpass", from: 2000, to: 2000 } },
),
// Sci-fi and combat.
laser: layered(
{ type: "square", from: 1800, to: 280, seconds: 0.12, gain: 0.5, filter: { type: "lowpass", from: 4500, to: 1200 } },
{ type: "sawtooth", from: 900, to: 140, seconds: 0.12, gain: 0.3, filter: { type: "lowpass", from: 3000, to: 800 } },
),
zapBig: layered(
{ type: "sawtooth", from: 2400, to: 80, seconds: 0.26, gain: 0.55, filter: { type: "lowpass", from: 5000, to: 600 } },
{ type: "noise", seconds: 0.2, gain: 0.4, filter: { type: "bandpass", from: 3000, to: 500, q: 1 } },
),
shieldUp: layered(
{ type: "sine", from: 300, to: 1200, seconds: 0.32, vibrato: { rate: 18, depth: 0.05 } },
{ type: "triangle", from: 600, to: 2400, seconds: 0.32, gain: 0.3 },
),
warp: layered(
{ type: "sine", from: 400, to: 1600, seconds: 0.34, vibrato: { rate: 24, depth: 0.08 } },
{ type: "pink", seconds: 0.34, gain: 0.3, filter: { type: "bandpass", from: 600, to: 3600, q: 3 } },
),
bossIntro: layered(
{ type: "sawtooth", from: 55, to: 52, seconds: 1, attack: 0.25, gain: 0.6, filter: { type: "lowpass", from: 300, to: 900, q: 3 } },
{ type: "brown", seconds: 1, attack: 0.25, gain: 0.6, filter: { type: "lowpass", from: 220, to: 160 } },
{ type: "square", notes: [110, 104, 98], seconds: 1, gain: 0.3, filter: { type: "lowpass", from: 600, to: 600 } },
),
// Spooky.
doorCreak: layered(
{ type: "sawtooth", from: 150, to: 92, seconds: 0.62, attack: 0.05, gain: 0.5, vibrato: { rate: 23, depth: 0.09 }, filter: { type: "bandpass", from: 900, to: 700, q: 3 } },
),
gust: layered({ type: "pink", seconds: 0.9, attack: 0.35, filter: { type: "bandpass", from: 300, to: 850, q: 1.2 } }),
heartbeat: layered(
{ type: "sine", from: 72, to: 45, seconds: 0.1 },
{ type: "sine", from: 66, to: 42, seconds: 0.11, delay: 0.18, gain: 0.8 },
),
wail: layered({ type: "sine", from: 560, to: 880, seconds: 0.65, attack: 0.15, vibrato: { rate: 6, depth: 0.03 } }),
// Crowds and wood.
rattle: layered(
{ type: "triangle", notes: [1200, 900, 1100, 820], seconds: 0.16, gain: 0.6 },
{ type: "noise", seconds: 0.12, gain: 0.3, filter: { type: "bandpass", from: 3200, to: 2400, q: 2 } },
),
cheer: layered(
{ type: "pink", seconds: 1, attack: 0.25, filter: { type: "bandpass", from: 900, to: 1400, q: 0.8 } },
{ type: "noise", seconds: 1, attack: 0.25, gain: 0.2, filter: { type: "highpass", from: 3000, to: 3500 } },
),
aww: layered({ type: "pink", seconds: 0.85, attack: 0.1, filter: { type: "bandpass", from: 950, to: 480, q: 1.3 } }),
applause: layered(
...[0, 0.05, 0.11, 0.14, 0.2, 0.27, 0.31, 0.38, 0.43, 0.5].map((delay, i) => ({ type: "noise", seconds: 0.035, delay, gain: 0.6 + (i % 3) * 0.15, filter: { type: "bandpass", from: 1400 + (i % 4) * 300, to: 1200, q: 1.5 } })),
),
knock: layered(
{ type: "triangle", from: 600, to: 560, seconds: 0.06 },
{ type: "noise", seconds: 0.03, gain: 0.5, filter: { type: "bandpass", from: 1800, to: 1500, q: 2 } },
),
crumble: layered(
{ type: "brown", seconds: 0.55, filter: { type: "lowpass", from: 900, to: 100 } },
...[0, 0.07, 0.15, 0.24].map((delay) => ({ type: "noise", seconds: 0.04, delay, gain: 0.35, filter: { type: "bandpass", from: 1600, to: 900, q: 2 } })),
),
hiss: layered({ type: "noise", seconds: 0.4, attack: 0.03, gain: 0.6, filter: { type: "highpass", from: 3000, to: 5200 } }),
squeak: layered({ type: "sine", from: 1800, to: 2400, seconds: 0.05 }),
});
/* --------------------------------------------------------------- hums
A hum is a sound that runs for as long as a game keeps asking for it: a
car's engine, a boat's outboard, the river, a light cycle, a fuse's hiss.
A game calls hum(id, name, level, pitch) every frame it wants it, `id`
telling one voice from another (your car and a rival's), and pitch
following its speed. A hum not asked for again within HUM_HOLD_MS fades
out by itself, so a paused, closed or finished game falls quiet without
saying so; hushTones() quiets them all at once. Each hum is oscillators
(`parts`, each its own frequency and gain) and noise (`noise`) through one
filter whose cutoff follows the pitch by `follow` (1 tracks it exactly, 0
holds still), pulsed by `pulse` ({ rate, depth }, the rate following the
pitch): an engine's firing strokes or a train's clatter. */
const hums = (table) => Object.freeze(Object.fromEntries(Object.entries(table).map(([k, v]) => [k, Object.freeze(v)])));
const HUMS = hums({
car: { parts: [{ type: "sawtooth", freq: 46 }, { type: "sawtooth", freq: 46.5, gain: 0.7 }, { type: "square", freq: 23, gain: 0.5 }], noise: { color: "brown", gain: 0.2 }, filter: { type: "lowpass", freq: 360, q: 4, follow: 0.9 }, pulse: { rate: 11, depth: 0.45 }, peak: 0.06 },
toycar: { parts: [{ type: "square", freq: 90 }, { type: "square", freq: 90.8, gain: 0.5 }], filter: { type: "lowpass", freq: 850, q: 2, follow: 1 }, pulse: { rate: 20, depth: 0.5 }, peak: 0.04 },
electric: { parts: [{ type: "sawtooth", freq: 60 }, { type: "sine", freq: 120, gain: 0.5 }, { type: "sine", freq: 620, gain: 0.12 }], filter: { type: "lowpass", freq: 520, q: 2, follow: 0.8 }, peak: 0.045 },
outboard: { parts: [{ type: "sawtooth", freq: 38 }, { type: "square", freq: 76, gain: 0.4 }], noise: { color: "brown", gain: 0.35 }, filter: { type: "lowpass", freq: 430, q: 3, follow: 0.9 }, pulse: { rate: 16, depth: 0.6 }, peak: 0.06 },
river: { noise: { color: "brown", gain: 1 }, filter: { type: "lowpass", freq: 650, q: 0.5, follow: 1 }, pulse: { rate: 0.4, depth: 0.3 }, peak: 0.05 },
wind: { noise: { color: "pink", gain: 1 }, filter: { type: "bandpass", freq: 600, q: 0.8, follow: 1 }, pulse: { rate: 0.3, depth: 0.4 }, peak: 0.04 },
cycle: { parts: [{ type: "sawtooth", freq: 98 }, { type: "sawtooth", freq: 98.6 }, { type: "sawtooth", freq: 196.3, gain: 0.3 }], filter: { type: "lowpass", freq: 1100, q: 6, follow: 0.8 }, peak: 0.03 },
fuse: { noise: { color: "noise", gain: 1 }, filter: { type: "highpass", freq: 3500, q: 0.7, follow: 0.5 }, pulse: { rate: 23, depth: 0.55 }, peak: 0.03 },
haunt: { parts: [{ type: "sine", freq: 55 }, { type: "sine", freq: 55.8 }, { type: "triangle", freq: 82.4, gain: 0.3 }], filter: { type: "lowpass", freq: 400, q: 1, follow: 0.5 }, pulse: { rate: 0.3, depth: 0.5 }, peak: 0.045 },
squeal: { parts: [{ type: "triangle", freq: 1450, gain: 0.2 }], noise: { color: "noise", gain: 1 }, filter: { type: "bandpass", freq: 1900, q: 9, follow: 1 }, peak: 0.035 },
meter: { parts: [{ type: "triangle", freq: 220 }, { type: "square", freq: 220.5, gain: 0.25 }], filter: { type: "lowpass", freq: 1200, q: 1, follow: 1 }, peak: 0.025 },
swarm: { parts: [{ type: "sawtooth", freq: 180 }, { type: "sawtooth", freq: 183 }, { type: "sawtooth", freq: 177 }], filter: { type: "bandpass", freq: 900, q: 2, follow: 1 }, pulse: { rate: 30, depth: 0.5 }, peak: 0.02 },
train: { parts: [{ type: "square", freq: 60, gain: 0.4 }], noise: { color: "brown", gain: 1 }, filter: { type: "lowpass", freq: 520, q: 1, follow: 0.7 }, pulse: { rate: 4, depth: 0.7 }, peak: 0.05 },
crowd: { noise: { color: "pink", gain: 1 }, filter: { type: "bandpass", freq: 1100, q: 0.6, follow: 0.6 }, pulse: { rate: 0.5, depth: 0.4 }, peak: 0.02 },
});
// Every game's own extras, merged after the shared kit; a name may be
// defined only once across them all (the activities suite checks).
const GAME_SFX = Object.freeze([snakeSfx, golfSfx, trailsSfx, bugsSfx, driveSfx, stackSfx, bumperSfx, rapidsSfx, fuseSfx, hopSfx, bounceSfx, ghoulSfx]);
// A game file holds plain objects; they are frozen here, all the way down.
const deepFreeze = (o) => {
if (o && typeof o === "object") Object.values(o).forEach(deepFreeze);
return Object.freeze(o);
};
export const TONE_TABLES = Object.freeze([BLIPS, RICH, ...GAME_SFX.map((s) => deepFreeze(s.tones || {}))]);
export const HUM_TABLES = Object.freeze([HUMS, ...GAME_SFX.map((s) => deepFreeze(s.hums || {}))]);
// And each game's chiptune tracks, which music.js plays.
export const MUSIC_TABLES = Object.freeze(GAME_SFX.map((s) => deepFreeze(s.music || {})));
const TONES = Object.freeze(Object.assign({}, ...TONE_TABLES));
const ALL_HUMS = Object.freeze(Object.assign({}, ...HUM_TABLES));
export const toneNames = () => Object.keys(TONES);
export const humNames = () => Object.keys(ALL_HUMS);
// Peak gain, kept modest so a blip sits under the page rather than over it.
const PEAK = 0.08;
@@ -62,8 +403,18 @@ const PEAK = 0.08;
const ATTACK = 0.01;
const FLOOR = 0.0001;
// At most this many parts of rich tones sounding at once: a frantic moment
// drops one rather than piling up enough voices to stutter the page.
const MAX_VOICES = 48;
let ctx = null;
let bus = null;
const noiseBuffers = new Map();
let voiceEnds = [];
// Made on first use, not at load, so importing this file in Node is harmless.
// A missing AudioContext or a constructor that throws both give null.
function audioContext() {
@@ -77,6 +428,68 @@ function audioContext() {
return ctx;
}
// Everything plays through one gentle compressor, so an explosion over an
// engine over a shot never clips; a context without one plays straight out.
function out(c) {
if (bus) return bus;
if (typeof c.createDynamicsCompressor !== "function") return c.destination;
const comp = c.createDynamicsCompressor();
comp.threshold.value = -20;
comp.knee.value = 12;
comp.ratio.value = 4;
comp.attack.value = 0.003;
comp.release.value = 0.2;
comp.connect(c.destination);
bus = comp;
return bus;
}
// Two seconds of noise per color, made once and looped from a random point.
function noiseBuffer(c, color) {
if (noiseBuffers.has(color)) return noiseBuffers.get(color);
const length = Math.floor(c.sampleRate * 2);
const buf = c.createBuffer(1, length, c.sampleRate);
const data = buf.getChannelData(0);
let b0 = 0, b1 = 0, b2 = 0, last = 0;
for (let i = 0; i < length; i++) {
const w = Math.random() * 2 - 1;
if (color === "pink") {
b0 = 0.99765 * b0 + w * 0.099046;
b1 = 0.963 * b1 + w * 0.2965164;
b2 = 0.57 * b2 + w * 1.0526913;
data[i] = (b0 + b1 + b2 + w * 0.1848) * 0.2;
} else if (color === "brown") {
last = (last + 0.02 * w) / 1.02;
data[i] = last * 3.5;
} else data[i] = w;
}
noiseBuffers.set(color, buf);
return buf;
}
const NOISES = new Set(["noise", "pink", "brown"]);
// Room for `n` more parts that end at `end`, or false while the page is busy.
function room(c, n, end) {
const now = c.currentTime;
voiceEnds = voiceEnds.filter((t) => t > now);
if (voiceEnds.length + n > MAX_VOICES) return false;
for (let i = 0; i < n; i++) voiceEnds.push(end);
return true;
}
// The running context, its output and its noise, for music.js, which plays
// through the same compressor; null while audio cannot play.
export function audioOut() {
try {
const c = audioContext();
if (!c || c.state !== "running") return null;
return { c, out: out(c), noise: (color) => noiseBuffer(c, color) };
} catch {
return null;
}
}
// Called from the click that opens Activities. A browser keeps a new context
// suspended until a gesture, and a rejected resume is not an error the page
// can act on, so every failure is swallowed.
@@ -99,15 +512,70 @@ function blip(c, type, from, to, t0, seconds, peak) {
gain.gain.exponentialRampToValueAtTime(peak, t0 + ATTACK);
gain.gain.exponentialRampToValueAtTime(FLOOR, end);
osc.connect(gain);
gain.connect(c.destination);
gain.connect(out(c));
osc.start(t0);
osc.stop(end);
}
// One part of a rich tone from t0: an oscillator (sweeping, or stepping
// through `notes`) or a noise, through its filter if it has one, under an
// envelope that swells in over `attack` and dies away by its end.
function voice(c, p, t0, peak, k) {
const end = t0 + p.seconds;
const gain = c.createGain();
const top = Math.max(FLOOR * 10, peak * (p.gain ?? 1));
gain.gain.setValueAtTime(FLOOR, t0);
gain.gain.exponentialRampToValueAtTime(top, t0 + Math.min(p.attack ?? ATTACK, p.seconds * 0.8));
gain.gain.exponentialRampToValueAtTime(FLOOR, end);
let src;
if (NOISES.has(p.type)) {
src = c.createBufferSource();
src.buffer = noiseBuffer(c, p.type);
src.loop = true;
} else {
src = c.createOscillator();
src.type = p.type;
if (p.notes) {
const each = p.seconds / p.notes.length;
p.notes.forEach((f, i) => src.frequency.setValueAtTime(f * k, t0 + i * each));
} else {
src.frequency.setValueAtTime(p.from * k, t0);
src.frequency.exponentialRampToValueAtTime(p.to * k, end);
}
if (p.vibrato) {
const lfo = c.createOscillator();
const depth = c.createGain();
lfo.frequency.value = p.vibrato.rate;
depth.gain.value = (p.notes ? p.notes[0] : p.from) * k * p.vibrato.depth;
lfo.connect(depth);
depth.connect(src.frequency);
lfo.start(t0);
lfo.stop(end);
}
}
let head = src;
if (p.filter) {
const f = c.createBiquadFilter();
f.type = p.filter.type;
f.Q.value = p.filter.q ?? 1;
f.frequency.setValueAtTime(Math.min(20000, p.filter.from * k), t0);
f.frequency.exponentialRampToValueAtTime(Math.min(20000, (p.filter.to ?? p.filter.from) * k), end);
head.connect(f);
head = f;
}
head.connect(gain);
gain.connect(out(c));
if (NOISES.has(p.type)) src.start(t0, Math.random() * 1.5);
else src.start(t0);
src.stop(end);
}
// Plays one named blip, at `level` (0 to 1) of the usual loudness: a soft
// putt sounds soft. An unknown name, Play sounds off, or a context that is
// missing, suspended or closed all mean silence, not an error.
export function tone(name, level = 1) {
// putt sounds soft. `pitch` scales every frequency (2 is an octave up, kept
// between two octaves down and two up), so a game can climb a scale on one
// blip. An unknown name, Play sounds off, or a context that is missing,
// suspended or closed all mean silence, not an error.
export function tone(name, level = 1, pitch = 1) {
try {
const spec = Object.hasOwn(TONES, name) ? TONES[name] : null;
if (!spec || !looks.sound) return;
@@ -115,8 +583,144 @@ export function tone(name, level = 1) {
if (!c || c.state !== "running") return;
const peak = Math.max(FLOOR * 10, PEAK * Math.min(1, Number(level) || 0));
const t0 = c.currentTime;
if (!spec.notes) return blip(c, spec.type, spec.from, spec.to, t0, spec.seconds, peak);
const k = Math.min(4, Math.max(0.25, Number(pitch) || 1));
if (spec.layers) {
const last = Math.max(...spec.layers.map((p) => (p.delay || 0) + p.seconds));
if (!room(c, spec.layers.length, t0 + last)) return;
return spec.layers.forEach((p) => voice(c, p, t0 + (p.delay || 0), peak, k));
}
if (!spec.notes) return blip(c, spec.type, spec.from * k, spec.to * k, t0, spec.seconds, peak);
const each = spec.seconds / spec.notes.length;
spec.notes.forEach((f, i) => blip(c, spec.type, f, f, t0 + i * each, each, peak));
spec.notes.forEach((f, i) => blip(c, spec.type, f * k, f * k, t0 + i * each, each, peak));
} catch {}
}
/* ------------------------------------------------------ the hum voices */
// A hum not asked for again within this long fades out by itself.
const HUM_HOLD_MS = 150;
// At most this many hums at once; a new one past it is not started.
const MAX_HUMS = 6;
// How quickly a hum's pitch and loudness follow what the game asks, in
// seconds: quick enough to rev, slow enough never to zipper.
const GLIDE = 0.05;
const live = new Map();
let watchdog = null;
function startHum(c, spec) {
const amp = c.createGain();
const level = c.createGain();
level.gain.value = 0;
amp.connect(level);
level.connect(out(c));
let head = amp;
let filter = null;
if (spec.filter) {
filter = c.createBiquadFilter();
filter.type = spec.filter.type;
filter.Q.value = spec.filter.q ?? 1;
filter.frequency.value = spec.filter.freq;
filter.connect(amp);
head = filter;
}
const oscs = (spec.parts || []).map((p) => {
const o = c.createOscillator();
const g = c.createGain();
o.type = p.type;
o.frequency.value = p.freq;
g.gain.value = p.gain ?? 1;
o.connect(g);
g.connect(head);
o.start();
return o;
});
const sources = [...oscs];
if (spec.noise) {
const n = c.createBufferSource();
const g = c.createGain();
n.buffer = noiseBuffer(c, spec.noise.color);
n.loop = true;
g.gain.value = spec.noise.gain ?? 1;
n.connect(g);
g.connect(head);
n.start(0, Math.random() * 1.5);
sources.push(n);
}
let lfo = null;
if (spec.pulse) {
lfo = c.createOscillator();
const depth = c.createGain();
lfo.frequency.value = spec.pulse.rate;
depth.gain.value = spec.pulse.depth / 2;
amp.gain.value = 1 - spec.pulse.depth / 2;
lfo.connect(depth);
depth.connect(amp.gain);
lfo.start();
sources.push(lfo);
}
return { spec, level, filter, oscs, lfo, sources, seen: 0 };
}
function stopHum(c, id, v) {
live.delete(id);
try {
const t = c.currentTime;
v.level.gain.cancelScheduledValues(t);
v.level.gain.setTargetAtTime(0, t, 0.06);
v.sources.forEach((s) => s.stop(t + 0.5));
} catch {}
}
function watch() {
if (watchdog) return;
watchdog = setInterval(() => {
const now = performance.now();
for (const [id, v] of live) if (!looks.sound || now - v.seen > HUM_HOLD_MS) stopHum(ctx, id, v);
if (!live.size) {
clearInterval(watchdog);
watchdog = null;
}
}, 50);
}
// Keeps the hum `id` sounding as `name` for another moment, at `level` (0 to
// 1) of its loudness and `pitch` (1 is its own, kept between 0.25 and 4).
// Asking under a different name restarts it as that one. Like tone(), it is
// silence, never an error, while Play sounds is off or the audio is not
// running.
export function hum(id, name, level = 1, pitch = 1) {
try {
const spec = Object.hasOwn(ALL_HUMS, name) ? ALL_HUMS[name] : null;
const c = audioContext();
if (!spec || !looks.sound || !c || c.state !== "running") return;
let v = live.get(id);
if (v && v.spec !== spec) {
stopHum(c, id, v);
v = null;
}
if (!v) {
if (live.size >= MAX_HUMS) return;
v = startHum(c, spec);
live.set(id, v);
watch();
}
v.seen = performance.now();
const t = c.currentTime;
const k = Math.min(4, Math.max(0.25, Number(pitch) || 1));
const loud = spec.peak * Math.min(1, Math.max(0, Number(level) || 0));
v.level.gain.setTargetAtTime(loud, t, GLIDE);
v.oscs.forEach((o, i) => o.frequency.setTargetAtTime(spec.parts[i].freq * k, t, GLIDE));
if (v.filter) v.filter.frequency.setTargetAtTime(Math.min(18000, spec.filter.freq * k ** (spec.filter.follow ?? 1)), t, GLIDE);
if (v.lfo) v.lfo.frequency.setTargetAtTime(spec.pulse.rate * k, t, GLIDE);
} catch {}
}
// Quiets every hum at once: the window stopped ticking a game.
export function hushTones() {
if (!ctx) return;
for (const [id, v] of live) stopHum(ctx, id, v);
}