mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 04:45:33 -08:00
379 lines
18 KiB
JavaScript
379 lines
18 KiB
JavaScript
// Plan2Code Web Console - what the page reads off its state: the questions, the finish, the scan, who has the ball; defines only.
|
|
//
|
|
// Plain functions over `page` (state.js) that more than one screen asks the
|
|
// same question of, kept here so no screen has to import another to ask it.
|
|
|
|
import { page, redraw } from "./state.js";
|
|
import { boardAwaiting } from "./git-board.js";
|
|
import { defaultSpec, reviewOffer, dashboardOffer, submittedAwaiting, quietLimitMs } from "./answers.js";
|
|
import { isAgentless } from "./skills.js";
|
|
import { activityLabel, workingLine } from "./labels.js";
|
|
import { ASK_BUSY_MS, chatAnswering } from "./chat.js";
|
|
|
|
export const WORKING_GRACE_MS = 5 * 60 * 1000;
|
|
|
|
// Two minutes with the agent mid-turn, three when it is merely meant to be
|
|
// listening. The difference is the cost of being wrong: a working agent that
|
|
// goes quiet is worth mentioning early, whereas the gap between `wait`
|
|
// returning and the next patch landing is ordinary and must not be called a
|
|
// failure. `wait` pokes /health every five seconds, so either threshold is
|
|
// many missed pokes, not a slow one.
|
|
const ADRIFT_MS = 3 * 60 * 1000;
|
|
|
|
// 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 : []);
|
|
|
|
export const docs = () => (page.S && Array.isArray(page.S.docs) ? page.S.docs : []);
|
|
|
|
export const byId = (id) => items().find((i) => i.id === id);
|
|
|
|
export const isOpen = (i) => i.status === "open" || i.status === "reopened";
|
|
|
|
export const asked = () => items().filter((i) => i.kind !== "notice");
|
|
|
|
export const openItems = () => asked().filter(isOpen);
|
|
|
|
export const stagedCount = () => Object.keys(page.local.staged).length;
|
|
|
|
// The one thing the page could never know before: this session is OVER, and
|
|
// the agent said so rather than the page inferring it. Everything else here is
|
|
// a pause -- no open questions means "none right now", not "no more ever" --
|
|
// which is why the end of a session used to read as a lull that never lifted.
|
|
// A posted finish is the whole signal; its command is optional, because some
|
|
// sessions end with nothing left to run.
|
|
export const finish = () => (page.S && page.S.finish && typeof page.S.finish === "object" ? page.S.finish : null);
|
|
|
|
// The dashboard is the one workflow that is not a conversation: a menu of the
|
|
// skills, rendered from the page's own catalog, where a click IS the answer.
|
|
export const isDashboard = () => page.S && page.S.workflow === "dashboard";
|
|
|
|
// The git board is drawn by the page too, from the console's own read-only
|
|
// snapshot (state.git), with the agent's confirm and result cards above it.
|
|
export const isGitBoard = () => page.S && page.S.workflow === "git" && page.S.git;
|
|
|
|
// A board click or a card send stays with the agent until its next post
|
|
// (boardAwaiting in git-board.js), not just until `wait` collects it.
|
|
export function gitAwaiting() {
|
|
if (!isGitBoard()) return false;
|
|
return boardAwaiting({
|
|
sentAt: page.local.gitSentAt || null,
|
|
updatedAt: page.S.updatedAt || null,
|
|
cardsAwaiting: awaitingReply().length,
|
|
adrift: agentAdrift(),
|
|
});
|
|
}
|
|
|
|
// The server's scan of the repo — AGENTS.md plus every spec under specs/,
|
|
// classified by pipeline stage and sorted most-recently-touched first.
|
|
export const scan = () => (page.S && page.S.scan) || null;
|
|
|
|
export const specList = () => {
|
|
const sc = scan();
|
|
return sc && Array.isArray(sc.specs) ? sc.specs : [];
|
|
};
|
|
|
|
// The spec the picker currently targets. Absent `specSel` means the picker
|
|
// has not been touched, so it defaults to the most recently touched spec
|
|
// still in play (defaultSpec: the server's list is already sorted, and a
|
|
// fixed bug is skipped). An explicit "start from scratch" is stored as null,
|
|
// which is different.
|
|
export const selSpec = () => {
|
|
const specs = specList();
|
|
if (!specs.length) return null;
|
|
if (page.local.specSel === undefined) return defaultSpec(specs);
|
|
return specs.find((s) => s.dir === page.local.specSel) || null;
|
|
};
|
|
|
|
// This checkout's unused handoffs (scan.handoffs, newest first). A handoff is
|
|
// picked in the same chip row as a spec, stored as `specSel = "handoff:<id>"`;
|
|
// selSpec() then reads as "no spec", and selHandoff() is the handoff itself,
|
|
// or null once it is gone from the scan (which also drops the stale pick).
|
|
export const handoffList = () => {
|
|
const sc = scan();
|
|
return sc && Array.isArray(sc.handoffs) ? sc.handoffs : [];
|
|
};
|
|
|
|
export const selHandoff = () => {
|
|
if (typeof page.local.specSel !== "string" || !page.local.specSel.startsWith("handoff:")) return null;
|
|
const id = page.local.specSel.slice("handoff:".length);
|
|
const h = handoffList().find((x) => x.id === id) || null;
|
|
if (!h) delete page.local.specSel;
|
|
return h;
|
|
};
|
|
|
|
// The review a finished build offers, and where it has got to:
|
|
// "open" on offer, and a press would reach the agent
|
|
// "asked" pressed, and the agent has not taken it up yet
|
|
// null no offer, declined, or nobody left to take the press
|
|
// `local.afterBuild` remembers the press across a reload. It is cleared when
|
|
// the finish goes away, which is the agent taking the review up.
|
|
export function reviewPending() {
|
|
const fin = finish();
|
|
if (!fin || !reviewOffer(fin) || ["done", "dashboard", "commit", "changelog", "launch"].includes(page.local.afterBuild)) return null;
|
|
if (page.local.afterBuild === "review") return page.gone ? null : "asked";
|
|
return page.gone ? null : "open";
|
|
}
|
|
|
|
// The dashboard offer on a finish, unless the person already said they are
|
|
// done: that send closes the session, so a button after it would go nowhere.
|
|
export const dashboardLive = (fin) => dashboardOffer(fin) && page.local.afterBuild !== "done";
|
|
|
|
// Whether the agent has collected this card's send: carried by the last
|
|
// collected send (state.collected), or sent before that collection.
|
|
export const sendCollected = (i, sub = i && i.submitted) => {
|
|
const c = page.S && page.S.collected;
|
|
if (!c || !sub) return false;
|
|
if (Array.isArray(c.ids) && c.ids.includes(i.id)) return true;
|
|
return Boolean(c.at && sub.at && String(sub.at) <= String(c.at));
|
|
};
|
|
|
|
// The durable half of `local.sent`: the server writes every send onto the
|
|
// item itself (`submitted`), so the send survives a reload, a resume onto a
|
|
// new port, and a second tab. It also covers an agent that took the answer
|
|
// and moved on without marking the item settled, which used to hand the
|
|
// question back looking as though the send never happened. `local.retract`
|
|
// is the person's "take it back" against exactly that send.
|
|
export const submittedInFlight = (i) => {
|
|
const sub = submittedAwaiting(i);
|
|
if (!sub) return null;
|
|
// Collected, and the agent is back to waiting without settling it: it left
|
|
// the card open on purpose (a pick that still owes its recap), so the send
|
|
// is no longer with it, and nothing stays locked waiting on a reply.
|
|
// Any send at or before the last collection was collected too, not only the
|
|
// cards that last one carried.
|
|
if (!page.pendingResult && !agentWorking() && sendCollected(i, sub)) return null;
|
|
const r = page.local.retract && page.local.retract[i.id];
|
|
if (r === "any" || (r != null && r === sub.at)) return null;
|
|
return sub;
|
|
};
|
|
|
|
// Open questions whose send is with the agent: answers and notes alike. On a
|
|
// finished session there is nobody left to collect a send, so nothing is in
|
|
// flight either -- the item is a record of what was sent, not a live wait.
|
|
export const awaitingReply = () =>
|
|
finish()
|
|
? []
|
|
: openItems().filter((i) => (page.local.sent && page.local.sent[i.id]) || submittedInFlight(i));
|
|
|
|
// Open questions that are actually the person's to answer right now. An open
|
|
// question they have already sent is not one of those, and counting it as one
|
|
// is how the page ends up telling someone it is their turn while they are
|
|
// sitting waiting for a reply. A finished session ends everyone's turn:
|
|
// questions left open are moot, because a send can no longer go anywhere.
|
|
export const myTurn = () =>
|
|
finish()
|
|
? []
|
|
: openItems().filter((i) => !(page.local.sent && page.local.sent[i.id]) && !submittedInFlight(i));
|
|
|
|
export function agentWorking() {
|
|
return page.S && page.S.agent && page.S.agent.status === "working";
|
|
}
|
|
|
|
export function workingMs() {
|
|
if (!agentWorking() || !page.S.agent.since) return 0;
|
|
return Date.now() - Date.parse(page.S.agent.since);
|
|
}
|
|
|
|
// The three silence thresholds below, stretched while the agent has said a
|
|
// long quiet stretch is normal (a build task). See quietLimitMs.
|
|
export const patience = (baseMs) => quietLimitMs(page.S && page.S.agent, baseMs, isAgentless(page.S && page.S.workflow));
|
|
|
|
// What the agent says it is doing right now, when it has said: "Task 3 of 9:
|
|
// the user service". Only meaningful while it is working. A build's line is
|
|
// rewritten (activityLabel() in labels.js) because agents trained on the old
|
|
// wording still write "Task 4.3 of 9", phase-numbered beside a bar that counts
|
|
// within the phase; the page puts it right rather than every prompt having to.
|
|
export function activity() {
|
|
if (!agentWorking()) return "";
|
|
const a = page.S.agent.activity;
|
|
if (typeof a !== "string") return "";
|
|
return activityLabel(a.trim(), page.S.workflow);
|
|
}
|
|
|
|
export const doingNow = () => workingLine(page.S && page.S.agent, page.S && page.S.headline, page.S && page.S.workflow);
|
|
|
|
// The OTHER end of the wire, and the one that was invisible.
|
|
//
|
|
// There are two connections here, not one. The page talks to a little server
|
|
// on this machine (`gone` covers that), and the server is polled by the agent
|
|
// sitting in `wait` (this covers that). The second is the one that actually
|
|
// breaks: a page left open pings every five seconds, which keeps the server
|
|
// well clear of its idle deadline, so the server happily outlives the agent
|
|
// for hours. Until now nothing said so unless the agent had also declared
|
|
// itself "working", and the normal state while someone answers is "waiting".
|
|
//
|
|
// 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() {
|
|
// An agent-less session has nobody to be adrift: silence means nothing there.
|
|
if (isAgentless(page.S && page.S.workflow)) return false;
|
|
if (!page.agentLastSeen || page.gone || finish()) return false;
|
|
const silent = Date.now() - Date.parse(page.agentLastSeen);
|
|
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
|
|
// minute of silence means it is not there. One that said it is working (it
|
|
// asked and carried on) collects at its next `wait`, so it gets the plain
|
|
// three minutes, never the half hour a build task may have asked for.
|
|
const UNCOLLECTED_MS = 60 * 1000;
|
|
|
|
function uncollectedLimit() {
|
|
return agentWorking() ? ADRIFT_MS : UNCOLLECTED_MS;
|
|
}
|
|
|
|
// Answers that went nowhere: pressed Send, and nothing has collected them.
|
|
// They are safe -- the server wrote them to disk and the next session picks
|
|
// them up -- but "Sent. Waiting for Plan2Code." forever does not say that.
|
|
export const stranded = () => page.pendingResult && agentAdrift();
|
|
|
|
// A press on a finished screen (Commit it now, Update CHANGELOG first, the way
|
|
// back to the dashboard, Continue here, a review) that nothing has collected.
|
|
// agentAdrift() stays quiet after a finish, where no agent is the normal end,
|
|
// but a press sent to one means somebody is waiting on it: an agent still in
|
|
// `wait` pings every five seconds, so a minute of silence says it is gone (its
|
|
// turn ended while the person was away) and the press sits saved until it
|
|
// is woken.
|
|
export function pressStranded() {
|
|
if (isAgentless(page.S && page.S.workflow)) return false;
|
|
if (!finish() || page.gone || !page.pendingResult || !page.agentLastSeen) return false;
|
|
if (!page.local.afterBuild || page.local.afterBuild === "done") return false;
|
|
return Date.now() - Date.parse(page.agentLastSeen) > UNCOLLECTED_MS;
|
|
}
|
|
|
|
// The spec whose files the spec file tabs show: the dashboard picker's
|
|
// selection on the dashboard, the session's own spec everywhere else.
|
|
export const overviewSpec = () => (isDashboard() ? selSpec()?.dir || "" : (page.S && page.S.specDir) || "");
|
|
|
|
// The spec files a tab can show, in tab order: each a view id, which is also
|
|
// the server's ?file= kind. Document's overview stands for the whole spec
|
|
// once it exists; before that the dashboard offers Pathfinder's map and
|
|
// Plan's draft.
|
|
export const SPEC_FILES = [
|
|
{ id: "overview", label: "Overview" },
|
|
{ id: "map", label: "Map" },
|
|
{ id: "draft", label: "Plan draft" },
|
|
];
|
|
export const isSpecFileView = (v) => SPEC_FILES.some((f) => f.id === v);
|
|
|
|
// The spec file tabs to draw now: Overview alone when the spec has one, else
|
|
// the map and the draft that exist. Only for the spec in view, so a pick that
|
|
// moved on never shows the last spec's files.
|
|
export function specFileTabs() {
|
|
if (page.overview.key !== overviewSpec()) return [];
|
|
const has = (id) => Boolean(page.overview.files[id]);
|
|
if (has("overview")) return SPEC_FILES.filter((f) => f.id === "overview");
|
|
return SPEC_FILES.filter((f) => f.id !== "overview" && has(f.id));
|
|
}
|
|
|
|
async function fetchSpecFile(spec, kind) {
|
|
try {
|
|
const res = await fetch("/overview?spec=" + encodeURIComponent(spec) + "&file=" + kind, { cache: "no-store" });
|
|
if (res.status !== 200) return null;
|
|
const file = decodeURIComponent(res.headers.get("x-spec-file") || "") || kind;
|
|
return { file, text: await res.text() };
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// Fresh from disk every time, never cached: the files change under a build,
|
|
// and the tabs are only worth having if they show what is there now. Away
|
|
// from the dashboard only the overview is read: a session's own map or draft
|
|
// is the work already in front of it. Repaints only when a tab would appear,
|
|
// vanish or show different text.
|
|
export async function loadOverview() {
|
|
const spec = overviewSpec();
|
|
const kinds = isDashboard() ? SPEC_FILES.map((f) => f.id) : ["overview"];
|
|
const files = {};
|
|
if (spec) {
|
|
const found = await Promise.all(kinds.map((k) => fetchSpecFile(spec, k)));
|
|
kinds.forEach((k, i) => {
|
|
if (found[i]) files[k] = found[i];
|
|
});
|
|
}
|
|
// The selection moved on while this was in flight; its own fetch will land.
|
|
if (spec !== overviewSpec()) return;
|
|
const changed = page.overview.key !== spec || JSON.stringify(page.overview.files) !== JSON.stringify(files);
|
|
page.overview = { key: spec, files };
|
|
if (changed) redraw();
|
|
}
|
|
|
|
// The Dashboard's AGENTS.md tab: its view id, and whether it is on now (the
|
|
// dashboard, with an AGENTS.md the last read found).
|
|
export const AGENTS_VIEW = "agents-md";
|
|
export const agentsTabShown = () => isDashboard() && typeof page.agentsDoc.texts["AGENTS.md"] === "string";
|
|
|
|
// Read one agent-guide file fresh from disk (`rel` as the server names it) and
|
|
// keep its text; null when it is not there. Off the dashboard nothing is read.
|
|
async function fetchAgentsDoc(rel) {
|
|
try {
|
|
const res = await fetch("/agents-doc?file=" + encodeURIComponent(rel), { cache: "no-store" });
|
|
return res.status === 200 ? await res.text() : null;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
// Fresh from disk every time, like the spec file tabs: AGENTS.md changes under
|
|
// init-update, and the tab is only worth having if it shows what is there now.
|
|
// Reads AGENTS.md (does the tab exist?) and, when a linked file is open, that
|
|
// file too. Repaints only when a tab would appear or vanish or a text changed.
|
|
export async function loadAgentsDoc() {
|
|
if (!isDashboard()) {
|
|
if (Object.keys(page.agentsDoc.texts).length) page.agentsDoc = { open: "AGENTS.md", texts: {} };
|
|
return;
|
|
}
|
|
const open = page.agentsDoc.open;
|
|
const rels = open === "AGENTS.md" ? ["AGENTS.md"] : ["AGENTS.md", open];
|
|
const found = await Promise.all(rels.map(fetchAgentsDoc));
|
|
// The person moved on (Back to AGENTS.md) while this was in flight.
|
|
if (!isDashboard() || page.agentsDoc.open !== open) return;
|
|
const texts = {};
|
|
rels.forEach((rel, i) => {
|
|
if (typeof found[i] === "string") texts[rel] = found[i];
|
|
});
|
|
// A linked file that went missing: back to AGENTS.md itself.
|
|
const next = { open: texts[open] === undefined ? "AGENTS.md" : open, texts };
|
|
const changed = JSON.stringify(next) !== JSON.stringify(page.agentsDoc);
|
|
page.agentsDoc = next;
|
|
if (changed) redraw();
|
|
}
|
|
|
|
// The workspace's folders, original first, or none before a frame has them.
|
|
export const workspaceFolders = () => (page.wsFrame && Array.isArray(page.wsFrame.folders) ? page.wsFrame.folders : []);
|