Split the web console into by-job files, add page tests and a docs-table test, plus docs

AI Assisted
This commit is contained in:
jparkerweb committed 2026-10-18 15:39:24 -07:00
1 parent 699a827cae
commit 3edb4468a8
121 files changed
+25603 -20145

No files matched your search

+1 -1
View File
@@ -51,7 +51,7 @@ const UPDATE_COMMAND = 'update';
// nothing but Node built-ins (and update-check.mjs is ESM), so it keeps its own copy.
const REPO_URL = 'https://github.com/jparkerweb/plan2code.git';
// The web console's cached release check, and how long it counts as fresh (update-check.mjs
// CACHE_MS). PLAN2CODE_CONSOLE_HOME moves the console's files, as in lib.mjs.
// CACHE_MS). PLAN2CODE_CONSOLE_HOME moves the console's files, as in files.mjs.
const CONSOLE_HOME = process.env.PLAN2CODE_CONSOLE_HOME || path.join(os.homedir(), '.plan2code', 'console');
const UPDATE_CACHE_FILE = path.join(CONSOLE_HOME, 'update-check.json');
const UPDATE_CACHE_MS = 60 * 60 * 1000;
+2 -2
View File
@@ -15,7 +15,7 @@ import os from "node:os";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { EXIT, consoleLib, fail, gitRepo, out, parseArgs, readText, run } from "./common.mjs";
import { EXIT, consoleModule, fail, gitRepo, out, parseArgs, readText, run } from "./common.mjs";
const USAGE = `
git.mjs: read-only facts and exact commands for the Git skill. JSON on stdout.
@@ -182,7 +182,7 @@ const remoteNames = (root) => g(["remote"], root).out.split(/\r?\n/).filter(Bool
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
async function prHosts() {
return (await consoleLib()).readPrHosts();
return (await consoleModule("settings.mjs")).readPrHosts();
}
function readStatus(root) {
+6
View File
@@ -33,6 +33,12 @@ The page draws the cards itself — you never send the list. It also knows the r
- No AGENTS.md → `recommend: "plan2code-init"`; the note says why.
- A spec mid-pipeline → recommend its next step; that card's `details` names where it stands ("Plan drafted", "Phase 2 of 4 is next"). The picker pre-selects the most recently touched spec that is not `fixed` — recommend for THAT one.
- `exploring` ("Exploring"): Pathfinder is next.
- `mapped` ("Ready to plan"): Plan is next.
- `planned` ("Ready to document"): Document is next.
- `documented` ("Ready to build"): Implement is next.
- `building` ("Building"): Implement is next.
- `built` ("Ready to finalize"): Finalize is next.
- A spec that scans `unrecognized` ("files on disk") is input, not progress: its folder rides along on a Pathfinder or Plan launch as reference, and those are the only pipeline cards it lights. Read the files and recommend the fit — a settled design doc the person wrote is Plan's brief, loose notes are Pathfinder's. No skill generates such a doc; see the table below for what each one does write. Never flag Document or anything downstream of it for such a spec.
- A `diagnosed` spec ("Bug diagnosed") is a bug Diagnose wrote up: recommend Quick Task, or Plan when its `DIAGNOSIS-<date>.md` sizes the fix as big; its folder rides along on either launch.
- A `fixed` spec ("Bug fixed") is a diagnosed bug Quick Task fixed but did not archive: finished, so never recommend for it or name it in the note; the picker never pre-selects one and hides it while unavailable workflows are hidden. The person archives it (Quick Task offers that once the bug is fixed) or deletes it with the picker's ✕.
+27 -19
View File
@@ -240,30 +240,38 @@ export function scrapeHits(text) {
// The web console ships beside these scripts in every installed skill
// (references/web-console/), and in this repo it sits at src/web-console/. Its
// lib.mjs is the one home of the spec-state classifier and the loop-marker /
// metrics-bait scan, so the scripts import it rather than keep a second copy.
const CONSOLE_LIB_CANDIDATES = [
path.join(HERE, "..", "references", "web-console", "lib.mjs"), // installed skill
path.join(HERE, "..", "web-console", "lib.mjs"), // src/skill-scripts in the repo
// scan.mjs is the one home of the spec-state classifier, and its settings.mjs
// of the pull-request host store, so the scripts import them rather than keep
// a second copy.
const CONSOLE_DIR_CANDIDATES = [
path.join(HERE, "..", "references", "web-console"), // installed skill
path.join(HERE, "..", "web-console"), // src/skill-scripts in the repo
];
let consoleLibPromise;
export function consoleLib() {
consoleLibPromise ||= (async () => {
for (const candidate of CONSOLE_LIB_CANDIDATES) {
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
}
fail(
EXIT.NOT_FOUND,
"console-lib-missing",
`The web console's lib.mjs is not beside this script (looked in ${CONSOLE_LIB_CANDIDATES.join(", ")}).`,
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
const consoleModules = new Map();
/** One of the web console's modules by file name ("scan.mjs"), imported once. */
export function consoleModule(file) {
if (!consoleModules.has(file)) {
consoleModules.set(
file,
(async () => {
const candidates = CONSOLE_DIR_CANDIDATES.map((dir) => path.join(dir, file));
for (const candidate of candidates) {
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
}
fail(
EXIT.NOT_FOUND,
"console-module-missing",
`The web console's ${file} is not beside this script (looked in ${candidates.join(", ")}).`,
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
);
})()
);
})();
return consoleLibPromise;
}
return consoleModules.get(file);
}
// The one read-only git reader (git-repo.mjs) ships beside lib.mjs, so the git
// The one read-only git reader (git-repo.mjs) ships beside scan.mjs, so the git
// skill's scripts read the repository with exactly the code the console uses.
const GIT_REPO_CANDIDATES = [
path.join(HERE, "..", "references", "web-console", "git-repo.mjs"), // installed skill
+2 -2
View File
@@ -14,7 +14,7 @@
import fs from "node:fs";
import path from "node:path";
import { EXIT, fail, out, parseArgs, run, readText, isDir, rel, eol, consoleLib, isoDate, phaseFiles, LOOP_TOKENS, scrapeHits } from "./common.mjs";
import { EXIT, fail, out, parseArgs, run, readText, isDir, rel, eol, consoleModule, isoDate, phaseFiles, LOOP_TOKENS, scrapeHits } from "./common.mjs";
const USAGE = `
specs.mjs: spec state for the Plan2Code pipeline skills. JSON on stdout.
@@ -500,7 +500,7 @@ function nextPhase(phases, groups, haveChecklist, leftovers = []) {
async function cmdList(args) {
const root = path.resolve(args.root || ".");
const { scanProject } = await consoleLib();
const { scanProject } = await consoleModule("scan.mjs");
const scan = scanProject(root);
const specs = scan.specs.map((s) => {
const dir = path.join(root, s.dir);
+46
View File
@@ -0,0 +1,46 @@
// Plan2Code Web Console - the `chat` command: hand over Quick questions now, never waiting.
import path from "node:path";
import { readJson } from "./files.mjs";
import { healthOk, listHandles, pidAlive, terminalLine } from "./sessions.mjs";
import { chatReplyLines, collectChat, deliverableChat } from "./inbox.mjs";
import { pendingWorkspaceChanges } from "./workspace.mjs";
import { changeLine } from "./public/workspace.js";
import { withSubagents, advanceSubagents, serverGone, advanceCursor, advanceWorkspace } from "./cmd-post-wait.mjs";
// The CLI's own pieces, handed over by console.mjs through useCli() before
// any command runs: console.mjs runs on import, so it cannot be imported back.
let print, mustSession, sessionProject;
export function useCli(cli) {
({ print, mustSession, sessionProject } = cli);
}
/* ----------------------------------------------------------------- chat */
// The instant check a build makes between tasks. Never sleeps, and never
// touches result.json: card sends stay with `wait`.
export async function cmdChat() {
const dir = mustSession();
const sid = path.basename(dir);
const handle = listHandles(sessionProject(dir)).find((h) => h.sid === sid);
if (!handle || !pidAlive(handle.pid) || !(await healthOk(handle))) {
print(serverGone(sid));
process.exitCode = 20;
return;
}
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
const changes = pendingWorkspaceChanges(dir);
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
if (!entries.length && !changes.length && !subCursor) {
print({ chat: [] });
process.exitCode = 10;
return;
}
print({ ...out, terminalLine: terminalLine(handle.url) });
advanceCursor(dir, entries);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = 0;
}
+153
View File
@@ -0,0 +1,153 @@
// Plan2Code Web Console - the `help` command: the CLI's usage and the contract's topic files.
import fs from "node:fs";
import path from "node:path";
import { HERE } from "./files.mjs";
// The CLI's own pieces, handed over by console.mjs through useCli() before
// any command runs: console.mjs runs on import, so it cannot be imported back.
let args, print, die;
export function useCli(cli) {
({ args, print, die } = cli);
}
/* ----------------------------------------------------------------- help */
export function cmdHelp() {
const topic = args._[0];
if (topic !== undefined) return helpTopic(String(topic));
process.stdout.write(`console.mjs — the Plan2Code web console. A detached server, a loopback
port, and the filesystem as transport; this CLI is the whole agent surface.
open [--file <payload.json>] [--workflow <w>] [--title "<t>"] [--spec <dir>]
[--session|--resume <sid>] [--no-open] [--idle-ms <ms>]
Start or resume a session and its server. Prints { ok, sid, session,
url, terminalLine }, plus swept { sessions, scratch, handoffs } when
old sessions, scratch files or handoffs were removed. Run it FIRST, before
reading anything: the page shows a starting screen until your
first post. --file is optional, and --title defaults to the
project's folder name. Also prints workspace: { folders: [{ name,
path, description?, original? }], missing? }, the folders this
console session reads as context, addressed as @name. The list is
remembered per folder and spec in workspaces.json beside looks.json.
May also print subagents: { state, revision, max, instruction } and
a reply holding only its "Subagents: ..." lines, when a standing
instruction (the page's Subagents switch) is owed to you.
post --session <sid> --file <patch.json | -> [--wait <N>]
Merge a patch into the session. Prints terminalLine while the
server is live. Exit 3 = rejected; stderr says why. --wait <N>
then waits up to N seconds in the same command (two JSON lines;
the exit code is the wait's). The patch may carry settle: true
(or a list of item ids) to mark the latest send's cards answered
with what was sent; doc blocks may carry file: "<path>" (and
select: "tasks"), read from the project, and a doc refresh: true
re-reads them. A doc's version moves up by itself. A patch may
carry run: { event, id, tasks? } (session meter points) and folderIssue:
{ name, reason, hint? } (a workspace folder you could not read);
both go to the ledger, never into the state. A patch may also
carry helpers: [{ id, title, ask, state, result? }] or one
{ id: "alone", alone: true }, merged by id, for the Subagents tab
(help subagents).
wait --session <sid> [--seconds <N>]
A bounded wait slice, sized below your shell timeout. Exit 0 = the
result is on stdout, 10 = still waiting ("Waiting on your answer
in the web console"; call again), 20 = server gone (open --resume
<sid>), 30 = cancelled. Exits 0 and 10 carry terminalLine.
Exit 0 may carry "chat" (Quick questions); with no card send it
is type: "chat" and actions is empty. Exit 0 may also carry
"workspace" (changes since you last heard, each once, with a
"Workspace: ..." line in reply); exit 10 counts them as
pendingWorkspace, and a change alone never ends a slice.
Exit 0 may also carry "subagents" (a console setting, not typed
by the person, with its "Subagents: ..." lines last in reply); a
setting change alone never ends a slice either. A hop
(__launch, __dashboard, __commit) carries resume, the exact
open --resume command, and skillFile when installed. Collecting
a send sets the page to working; a wait with a question open
hands the turn back.
chat --session <sid>
Collect Quick questions, workspace changes and a Subagents
setting change now, never waiting, never touching card sends.
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
10 = none, 20 = server gone.
terminalLine is "→ Look at the web console: <url>": end your terminal
messages with it during a console session.
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
Copy a cited note attachment into specs/<idea>/attachments/. Prints
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
missing. Paste link as it is.
forget --spec specs/<idea>
Drop the workspace folders remembered for that spec, in this
folder (Finalize, after archiving it). Prints { ok, spec, forgot };
forgot is false when nothing was saved. Exit 2 = bad usage.
delete-spec --spec specs/<name>
Delete that spec folder for good (the dashboard's Delete button, a
__delete action). Only an existing specs/<name> folder inside this
worktree: never a link, never deeper, never specs--completed/.
Prints { ok, removed }; exit 2 = bad usage, 3 = refused, with
{ ok: false, message } saying why. Nothing is touched on a refusal.
handoff new --workflow <w> --skill <s> [--spec specs/<name>] [--title "<t>"] [--from-stop]
Claim a handoff for this checkout in ~/.plan2code/handoffs/ (Stop
with a handoff, the Handoff skill). Writes only <id>.json; you write
the document at path. Prints { ok, id, path, meta }; exit 2 = bad
usage, 3 = a bad value, with { ok: false, message } saying why.
delete-handoff --handoff <id>
Delete that handoff for good (a Handoff chip's Delete, a __delete
action): <id>.md and <id>.json, only in ~/.plan2code/handoffs/,
never a link. Prints { ok, removed }; exit 2 = bad usage, 3 =
refused, with { ok: false, message } saying why. Nothing is touched
on a refusal.
status [--session <sid>] [--all]
One session, or (--all) every session on this machine, every project.
stop --session <sid> | --all
Shut a session's server down. Always post finish first.
workflows: dashboard · init · init-update · pathfinder · quick-task · plan ·
revise-plan · document · implement · implement-review · review ·
finalize · handoff · git · changelog · xray · diagnose
A session handed to you by the dashboard (a --session id): resume it with
"open --resume <sid> --no-open --workflow <yours>" (the resume it carries) -- never a
fresh "open", which would strand the page the person is watching.
The contract is console.md beside this file, read once; the rest is
read when its moment comes. help <topic> prints one; help topics lists
them. Build sessions (implement, implement-review, quick-task) also read
building.md.
`);
}
// The contract's topic files, by the name console.md's index gives them.
// Printing one saves an agent the path hunt: it already runs this CLI.
export const HELP_TOPICS = {
console: "console.md",
building: "building.md",
"building-review": "building-review.md",
finish: "console-finish.md",
stop: "console-stop.md",
attachments: "console-attachments.md",
chat: "console-chat.md",
workspace: "console-workspace.md",
subagents: "console-subagents.md",
launches: "console-launches.md",
dashboard: "console-launches.md",
meter: "console-meter.md",
trouble: "console-trouble.md",
};
for (const f of fs.existsSync(path.join(HERE, "notes")) ? fs.readdirSync(path.join(HERE, "notes")) : []) {
if (f.endsWith(".md")) HELP_TOPICS[f.slice(0, -3)] ??= `notes/${f}`;
}
HELP_TOPICS["init-update"] ??= HELP_TOPICS.init;
HELP_TOPICS["implement-review"] ??= HELP_TOPICS.implement;
function helpTopic(topic) {
const names = Object.keys(HELP_TOPICS).sort();
if (topic === "topics") {
print({ topics: Object.fromEntries(names.map((n) => [n, HELP_TOPICS[n]])) });
return;
}
const file = Object.hasOwn(HELP_TOPICS, topic) ? HELP_TOPICS[topic] : null;
if (!file) die(`no help topic "${topic}". Topics: ${names.join(", ")}`, 2);
process.stdout.write(fs.readFileSync(path.join(HERE, file), "utf8"));
}
+650
View File
@@ -0,0 +1,650 @@
// Plan2Code Web Console - the `open` command: start or resume a session, its server and the browser.
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
import { HERE, HOME_DIR, SESSIONS_DIR, appendEvent, ensureDir, nowIso, readJson, updateState } from "./files.mjs";
import {
appendLedger,
bindLoopback,
handOff,
handleFile,
healthOk,
listHandles,
newSessionId,
newToken,
nextLaunchId,
pidAlive,
readLedger,
reapHandles,
remoteWarning,
removeScratch,
removeSessions,
repoRoots,
SESSION_MAX_AGE_MS,
sessionDir,
staleScratch,
staleSessions,
sweepUploads,
terminalLine,
UPLOAD_MAX_AGE_MS,
} from "./sessions.mjs";
import { scanProject } from "./scan.mjs";
import {
applyPatch,
blankState,
isOpen,
switchWorkflow,
resolveDocFiles,
resolveDocImages,
validate,
} from "./patches.mjs";
import {
initialWorkspace,
readWorkspace,
rememberedWorkspace,
workspaceForAgent,
writeWorkspaceCursor,
} from "./workspace.mjs";
import { readPrHosts, resetSubagentCursor } from "./settings.mjs";
import { snapshot } from "./git-repo.mjs";
import { handoffsDir, listHandoffs, removeHandoffs, staleHandoffs } from "./handoffs.mjs";
import {
readPatch,
failValidation,
liftReread,
gitBlock,
ledgerFromPost,
awaitSubagentSync,
withSubagents,
advanceSubagents,
} from "./cmd-post-wait.mjs";
// The CLI's own pieces, handed over by console.mjs through useCli() before
// any command runs: console.mjs runs on import, so it cannot be imported back.
let args, print, die;
export function useCli(cli) {
({ args, print, die } = cli);
}
// PLAN2CODE_CONSOLE_TRACE=1 prints where the time goes, to stderr: the
// start path is what stands between someone and their first look at the page,
// and it is only worth optimising with numbers in hand.
const TRACE = Boolean(process.env.PLAN2CODE_CONSOLE_TRACE);
function trace(what) {
if (TRACE) process.stderr.write(`trace ${Math.round(performance.now())}ms ${what}\n`);
}
/* ----------------------------------------------------------------- open */
// Cache this console's directory where a later agent session can find it.
// HOME_DIR is fixed (~/.plan2code/console, or $PLAN2CODE_CONSOLE_HOME), so
// console-dir there is a stable place to look: the next skill that offers the
// console points its agent at the file rather than making it search the skill
// install dirs again. Written by `open` alone, which starts every session: a
// `wait` or a `post` every few seconds need not rewrite it each time.
function leavePointer() {
try {
ensureDir(HOME_DIR);
fs.writeFileSync(path.join(HOME_DIR, "console-dir"), HERE + "\n");
} catch {
/* a pointer we cannot leave costs nothing */
}
}
export async function cmdOpen() {
trace("open: start");
leavePointer();
const { project, worktree, branch } = repoRoots();
reapHandles(project);
trace("open: project found");
let sid = args.resume || args.session;
let dir;
let state;
// A new skill run for the meter: a fresh open, or a resume into another workflow.
let launched = true;
// Everything `open` does to a stored state, as a step it can take twice:
// once now, on the read below, so a bad payload is refused before anything
// starts, and again on a fresh read under the state lock when it writes, so
// a send the person made in between is kept rather than written over.
let reshape = (s) => s;
if (sid) {
sid = path.basename(sid);
dir = sessionDir(sid);
if (!fs.existsSync(dir)) die(`no session "${sid}" to resume`, 1);
state = readJson(path.join(dir, "state.json"));
if (!state) die(`session "${sid}" has no state`, 1);
// A resume can also be a hand-off: the dashboard launches another skill
// into its own session, and the first thing that skill needs is for the
// page to stop being a dashboard. Letting the flags restate these fields
// on resume means one command both reuses the server and turns the page,
// rather than a resume plus a whole extra post.
const switching = args.workflow && args.workflow !== state.workflow;
launched = Boolean(switching);
// Going through the dashboard is a fresh start: a skill launched from
// the menu gets a clean page, not the last skill's questions and tabs
// under its own name. The staged draft goes too, since its item ids
// belonged to the old questions. Git counts as a launch from anywhere:
// Commit it now on a finished screen and Changelog's "Commit this now?"
// both stand in for its dashboard card, and a finish left
// behind would keep the page on the old ending above the new questions
// (or the new board). A hop also drops the last run's state.git, since
// switchWorkflow() starts from a blank state.
// A skill run inline from another (a quick task's review) never switches
// through here, so it keeps the page.
const hop =
switching &&
(args.workflow === "dashboard" ||
state.workflow === "dashboard" ||
args.workflow === "git");
if (hop) fs.rmSync(path.join(dir, "draft.json"), { force: true });
reshape = (s) => {
// Resuming takes a pause back down. A paused finish is a bookmark --
// "saved here, pick it up later" -- and picking it up is exactly what
// this is. Left in place, the page keeps saying PAUSED over every
// question the resumed session asks, because `finish` is a scalar and
// only an explicit `finish: null` patch clears it. A real ending is
// different: re-sharing a finished session's link should still show its
// card, so only a headline that says "paused" comes down. Done before
// --file applies, so a patch can still post a finish of its own.
if (s.finish && /^\s*paused\b/i.test(String(s.finish.headline || ""))) {
delete s.finish;
// A new agent picking the session up: its own working turn, timed
// from now, not the paused run's last status.
s.agent = { status: "working", since: nowIso() };
// The old run's warning about what a stop would lose is about its
// unsaved work; the new run posts its own when it has some.
delete s.stopWarning;
// So is its count: the open questions it counted are dropped below,
// and the page falls back to its own tally until the new run posts.
s.headline = { stage: "", cleared: 0, total: 0, confidence: "", note: "" };
// The questions still open at the pause were the old session's asks,
// already narrated in the finish body so the next session can name
// them. Whatever the resumed session still needs it asks again, in its
// own words -- kept, the leftovers sit beside the new asks as
// duplicates nobody owns. Settled items stay: they are the record.
s.items = (s.items || []).filter((i) => !isOpen(i));
// And the topics that only the dropped items lived under, so a new
// item reusing an old topic id does not inherit a stale title.
const liveTopics = new Set(s.items.map((i) => i.topic));
s.topics = (s.topics || []).filter((t) => liveTopics.has(t.id));
}
if (hop) {
s = switchWorkflow(s, {
workflow: args.workflow,
title: typeof args.title === "string" ? args.title : path.basename(worktree),
specDir: args.spec,
});
} else if (switching) s.workflow = args.workflow;
if (args.title) s.title = args.title;
if (args.spec) s.specDir = args.spec;
// Every resume clears the wake-up flag: a server restart, a launch from
// the dashboard, a Back-to-dashboard return. Cleared here rather than by
// the page because the page cannot write state, and a replay on a return
// is exactly what the decision rules out.
delete s.wake;
return s;
};
} else {
sid = newSessionId();
// Named, not made: the folder is created once --file has passed, so a
// rejected first payload leaves no empty session behind for nothing to sweep.
dir = sessionDir(sid);
state = blankState({
sid,
project,
workflow: args.workflow,
// Until the agent knows what the session is about, the folder it runs
// in is the honest name, and it lets `open` go before any thinking.
title: typeof args.title === "string" ? args.title : path.basename(worktree),
specDir: args.spec,
});
// Only a freshly opened dashboard plays Planny's wake-up.
if (args.workflow === "dashboard") state.wake = true;
}
// A first payload's meter and folder reports, as `post` takes them: checked
// now, before anything is written, and appended once the launch is.
let openRun;
let openIssue;
let openReread;
let patch = null;
if (args.file) {
patch = readPatch(args.file);
if (!patch) die(`could not read --file ${args.file} as one JSON object`, 2);
({ run: openRun, folderIssue: openIssue } = patch);
delete patch.run;
delete patch.folderIssue;
openReread = liftReread(patch, args.workflow || state.workflow);
}
const base = reshape;
if (patch) {
// Against the page as this open leaves it (a hop starts blank), so a
// refresh never re-reads the last skill's files into the new page.
try {
patch = resolveDocFiles(patch, base(structuredClone(state)), worktree);
patch = resolveDocImages(patch, base(structuredClone(state)), dir);
} catch (e) {
die(e.message, 3);
}
}
const settle = (s) => {
s = base(s);
// On every open, so a resume from another worktree refreshes both.
s.worktree = worktree;
s.branch = branch;
return s;
};
reshape = (s) => (patch ? applyPatch(settle(s), patch) : settle(s));
state = settle(state);
if (patch) {
ledgerFromPost(dir, openRun, openIssue, state.workflow);
try {
state = applyPatch(state, patch);
} catch (e) {
die(e.message, 3);
}
const problems = validate(state);
if (problems.length) return failValidation(problems);
}
ensureDir(dir);
// A fresh session needs a fresh server, and a server is a whole Node boot:
// the slowest thing `open` does, bar the browser. Start both now, before
// the scan and the state write, so their start-up runs alongside them
// instead of after. The server does look at the state as it boots, and on
// a fresh session finds none yet: it takes the worktree from its command
// line, not from the state, and picks the state up on its first request or
// poll tick. No page can reach it before it is listening, and the state is
// on disk long before a browser gets there.
const existing = sid && (args.resume || args.session) ? listHandles(project).find((h) => h.sid === sid) : null;
// A live pid gets a second, longer look before it is given up on, as `stop`
// gives one: a server busy right after a post can miss the first, and a
// second server for the same session strands the page on the first.
const reusable =
existing && pidAlive(existing.pid)
? healthOk(existing).then((ok) => ok || healthOk(existing, 5000))
: Promise.resolve(false);
let boot = null;
if (!existing) boot = await startServer(project, worktree, sid, dir);
// The dashboard's spec picker reads its inventory straight off the session
// state, so the scan belongs to `open` rather than to the agent: filesystem
// facts, recomputed every time the session becomes (or stays) a dashboard,
// never something a model has to remember to fetch. Rooted at the worktree's
// own top level: `project` is the common-dir key so linked worktrees share
// sessions, but each shows the specs on its own disk.
const scan = state.workflow === "dashboard" ? scanProject(worktree) : null;
// This checkout's unused handoffs live outside every repo (handoffs.mjs), so
// they join the scan here and not in scanProject(), which also serves
// `specs.mjs list`. handoffsDir rides along so the page never guesses it.
if (scan) {
scan.handoffs = listHandoffs(worktree);
scan.handoffsDir = handoffsDir();
}
// The git board's data, the same way: the console's own read-only snapshot
// (git-repo.mjs), taken before the lock so no git process runs under it.
const gitSnap = state.workflow === "git" ? snapshot(worktree, { prHosts: readPrHosts() }) : null;
// Under the state lock, which a send on the page takes too: the result and
// the state are read fresh here and the state is rebuilt from that read, so
// nothing the person sent since the read above is lost or stamped over.
let carried = false;
let written;
try {
written = updateState(dir, (fresh) => {
const next = fresh ? reshape(fresh) : state;
if (scan) next.scan = scan;
// A launch or hop starts the board fresh; a plain resume (a server
// restart) keeps the last word on whether a Refresh failed.
if (gitSnap) next.git = launched ? gitBlock(gitSnap, openReread ?? { refreshFailed: false }) : gitBlock(gitSnap, openReread, fresh?.git);
// Clear a result the agent already collected, and ONLY that one.
//
// An unconsumed result is answers a person pressed Send on that nobody has
// picked up yet. Deleting it here is exactly the documented crash-recovery
// case ("your session died, press Send anyway, the next session picks it
// up") and deleting it destroys their work silently.
const resultPath = path.join(dir, "result.json");
const waiting = readJson(resultPath);
if (waiting && waiting.consumedAt) fs.rmSync(resultPath, { force: true });
carried = Boolean(waiting && !waiting.consumedAt);
// Do not stamp over "submitted" either: the phase is how the page knows a
// send is still in flight.
if (!carried) next.phase = "collecting";
return next;
});
} catch (e) {
written = { error: e.message };
}
if (!written || written.error) {
// A server just started for this state would only serve a page that never starts.
if (boot) boot.kill();
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
}
state = written.state;
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
// A new agent conversation has been told nothing yet (FR-6).
try {
resetSubagentCursor(dir);
} catch {}
trace("open: state written");
// Dashboard launches are recorded too (they score nothing), so the folder
// issues the page shows reset with every skill run. Never fatal: the meter
// is advice, and the page must not wait on it.
try {
if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow });
for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line);
} catch {}
const workspace = workspaceOnOpen(dir, worktree, state.specDir);
// Month-old sessions and scratch files: listed before the print so the
// agent can see what went, removed after it so the page waits for nothing.
// Nothing about this reaches the page.
const sweptSessions = staleSessions(SESSIONS_DIR, Date.now(), SESSION_MAX_AGE_MS, sid);
const sweptScratch = staleScratch(HOME_DIR, Date.now(), SESSION_MAX_AGE_MS);
const sweptHandoffs = staleHandoffs(Date.now(), SESSION_MAX_AGE_MS);
const swept =
sweptSessions.length || sweptScratch.length || sweptHandoffs.length
? { swept: { sessions: sweptSessions, scratch: sweptScratch, handoffs: sweptHandoffs } }
: {};
const sweep = () => {
sweepUploads(SESSIONS_DIR, Date.now(), UPLOAD_MAX_AGE_MS, sid).catch(() => {});
removeSessions(SESSIONS_DIR, sweptSessions).catch(() => {});
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
removeHandoffs(sweptHandoffs).catch(() => {});
};
// A standing instruction the new agent is owed, as `subagents` and a
// `reply` holding only its lines; neither key when nothing is owed.
const subagentsOwed = () => {
awaitSubagentSync(dir, state.workflow);
const [out, cursor] = withSubagents(dir, { reply: "" });
return [out.subagents ? out : {}, cursor];
};
// Reuse a live server if one is already serving this session.
if (existing && (await reusable)) {
if (!args["no-open"]) openBrowser(existing.url);
const [owed, subCursor] = subagentsOwed();
print({
ok: true,
sid,
session: dir,
url: existing.url,
reused: true,
pendingResult: carried,
terminalLine: terminalLine(existing.url),
workspace,
...owed,
...swept,
...remoteWarning(),
});
advanceSubagents(dir, subCursor);
sweep();
return;
}
// A handle whose pid is alive but is not ours (the pid was reused) leaves
// this for last: nothing could be started until that was known.
let started = boot || (await startServer(project, worktree, sid, dir));
let handle = await awaitHandle(started);
if (!handle && started.handoff) {
// The handover went wrong somewhere (a platform that will not pass the
// socket, a server that died taking it). Once more the old way, where
// the server binds its own port: slower, and certain.
started.kill();
started = await startServer(project, worktree, sid, dir, { handoff: false });
handle = await awaitHandle(started);
}
if (!handle) {
const log = tail(path.join(dir, "server.log"), 12);
die(`the console server did not start within 8s.\n${log}`, 1);
}
trace("open: server listening");
// Unref'd, or the cap itself would hold the process open for its full span.
await Promise.race([started.released, new Promise((r) => setTimeout(r, 2000).unref())]);
trace("open: socket handed over");
// The early tab went to the port `open` bound. If the server ended up
// anywhere else, that tab is a dead end, so send the browser to the real one.
if (!args["no-open"] && handle.url !== started.opened) openBrowser(handle.url);
const remote = remoteWarning();
const notes = [];
if (remote.note) notes.push(remote.note);
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
const [owed, subCursor] = subagentsOwed();
print({
ok: true,
sid,
session: dir,
url: handle.url,
port: handle.port,
pid: handle.pid,
pendingResult: carried,
terminalLine: terminalLine(handle.url),
workspace,
...owed,
...swept,
...(remote.remote ? { remote: remote.remote } : {}),
...(notes.length ? { note: notes.join(" ") } : {}),
});
advanceSubagents(dir, subCursor);
// After the print, never before it: the page and the link wait for nothing.
sweep();
}
/**
* The workspace as `open` hands it to the agent, and the cursor seeded to
* match: the agent now has the whole list, so no change up to here is owed.
* Read-only on workspace.json, which only the server writes; on a fresh
* session the server has not made it yet, so what was remembered for this
* folder and spec stands in, the same list the server is about to make.
*/
function workspaceOnOpen(dir, worktree, specDir) {
const ws = readWorkspace(dir) || initialWorkspace(worktree, rememberedWorkspace(worktree, specDir).entry);
const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id);
try {
writeWorkspaceCursor(dir, ws.version || 0);
} catch {}
return workspaceForAgent({ ...ws, missing });
}
function isFolder(p) {
try {
return fs.statSync(p).isDirectory();
} catch {
return false;
}
}
/**
* Start a detached server for the session, and the browser with it.
*
* The browser is the slowest thing in the whole start: from `start <url>` to
* its first request is most of a second on Windows, far longer than the
* server takes to boot. So the port is bound HERE, the link exists while the
* server is still booting, and the browser is sent at once. The bound socket
* is then handed to the server over an IPC channel; a request that arrives
* before the handover waits in the socket's queue, and one this process
* happened to accept is passed across as a socket of its own. Nothing the
* browser sends is refused or lost on the way.
*
* The order is timed. The server is spawned first, because its boot is the
* longest step the agent waits on. The bind comes next and overlaps that
* boot: a process's first listen() blocks for ~50ms on Windows while the
* socket stack loads, which is time the server spends booting anyway.
*/
async function startServer(project, worktree, sid, dir, { handoff = true } = {}) {
const token = newToken();
const handlePath = handleFile(project, sid);
ensureDir(path.dirname(handlePath));
fs.rmSync(handlePath, { force: true });
const logFd = fs.openSync(path.join(dir, "server.log"), "a");
const child = spawn(
process.execPath,
[
path.join(HERE, "server.mjs"),
// Always `--flag=value`, never two words: a base64url token can start
// with "--", and parseArgs would read it as the next flag and leave the
// server with `token: true`. The paths get the same form for the same reason.
`--session=${dir}`,
`--token=${token}`,
`--project=${project}`,
// The checkout the session runs in, which the state does not hold yet
// on a fresh open. See WORKTREE in server.mjs.
`--worktree=${worktree}`,
...(handoff ? ["--handoff"] : []),
...(args["idle-ms"] ? [`--idle-ms=${args["idle-ms"]}`] : []),
],
{
// Detached, because harness-managed background tasks get killed at
// assorted timeouts and on compaction, which would take the human's
// half-finished answers with them. Detached processes are immune.
detached: true,
// Redirecting stdio to a file is what lets the child outlive us. The
// IPC channel is only for the handover, and is closed straight after.
stdio: ["ignore", logFd, logFd, ...(handoff ? ["ipc"] : [])],
// windowsHide defaults to FALSE, and `detached` on Windows gives the
// child its own console window which "once enabled, cannot be disabled".
// Omit this and every handoff flashes a black box at the user.
windowsHide: true,
}
);
fs.closeSync(logFd);
let exited = false;
child.on("exit", () => (exited = true));
child.on("error", () => (exited = true));
trace("open: server spawned");
let opened = null;
let released = Promise.resolve();
if (handoff) {
const pre = await bindLoopback();
trace("open: port bound");
// No socket to give (the bind failed): the server binds its own, and the
// channel is let go once it has.
released = handOff(child, pre);
if (pre && !args["no-open"]) opened = `http://127.0.0.1:${pre.address().port}/s/${token}/`;
} else child.unref();
// Each spawn blocks for a moment (tens of ms for cmd.exe on Windows), so
// the browser's comes after the server's: the server's boot is what the
// agent waits on, and the browser's lead is most of a second regardless.
if (opened) {
openBrowser(opened);
trace("open: browser sent");
}
return {
handlePath,
handoff,
opened,
released,
dead: () => exited,
kill: () => {
try {
child.kill();
} catch {}
},
};
}
// Learn the port by waiting for the handle file, not by parsing stdout:
// stdout went to the log file, and the file handshake is race-free and is
// the same code path the reap sweep uses. Checked every 10ms: the file is
// tiny, and a coarse tick here is dead time added to every first paint.
// Null when the server died first, or never showed up.
async function awaitHandle(started) {
const deadline = Date.now() + 8000;
while (Date.now() < deadline) {
const handle = readJson(started.handlePath);
if (handle && handle.url) return handle;
if (started.dead()) return null;
await new Promise((r) => setTimeout(r, 10));
}
return null;
}
function tail(file, lines) {
try {
return fs.readFileSync(file, "utf8").split("\n").slice(-lines).join("\n");
} catch {
return "(no server log)";
}
}
/**
* Best-effort, never fatal. If we cannot open a browser we still printed the URL,
* and the URL is the primary channel.
*/
function openBrowser(url) {
try {
if (process.env.NO_BROWSER || process.env.PLAN2CODE_NO_BROWSER) return;
// Do not try from a place where there is no browser to open.
if (process.env.SSH_CONNECTION || process.env.REMOTE_CONTAINERS) return;
// A browser of their choosing: a command line, run through the shell,
// with the link appended. The token is base64url, so the quoted link
// carries nothing a shell would read.
const custom = process.env.PLAN2CODE_BROWSER;
if (custom) {
spawn(`${custom} "${url}"`, { shell: true, detached: true, stdio: "ignore", windowsHide: true }).unref();
return;
}
const plat = process.platform;
if (plat === "win32") {
// The empty "" is the mandatory window-title argument: omit it and
// `start` treats a quoted URL as the title and opens nothing.
spawn(process.env.COMSPEC || "cmd.exe", ["/d", "/s", "/c", "start", '""', `"${url}"`], {
windowsVerbatimArguments: true,
detached: true,
stdio: "ignore",
windowsHide: true,
}).unref();
return;
}
if (plat === "darwin") {
spawn("open", [url], { detached: true, stdio: "ignore" }).unref();
return;
}
// Linux and friends. WSL first: xdg-open there either is absent or opens a
// Linux browser that cannot reach the Windows host.
if (isWsl()) {
const exe = which("wslview") ? "wslview" : "powershell.exe";
const argsFor = exe === "wslview" ? [url] : ["-NoProfile", "-Command", "Start-Process", `"${url}"`];
spawn(exe, argsFor, { detached: true, stdio: "ignore" }).unref();
return;
}
if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return; // headless
spawn(process.env.BROWSER || "xdg-open", [url], { detached: true, stdio: "ignore" }).unref();
} catch {
/* never fatal */
}
}
function isWsl() {
if (process.platform !== "linux") return false;
try {
return /microsoft/i.test(fs.readFileSync("/proc/version", "utf8"));
} catch {
return false;
}
}
function which(bin) {
const dirs = (process.env.PATH || "").split(path.delimiter);
return dirs.some((d) => {
try {
fs.accessSync(path.join(d, bin), fs.constants.X_OK);
return true;
} catch {
return false;
}
});
}
+676
View File
@@ -0,0 +1,676 @@
// Plan2Code Web Console - `post` and `wait`: publish a patch, then collect what the person sent.
import fs from "node:fs";
import path from "node:path";
import { HERE, appendEvent, fileStamp, nowIso, readJson, sleepSync, updateState, writeJsonAtomic } from "./files.mjs";
import {
appendLedger,
healthOk,
lastLaunchId,
listHandles,
pidAlive,
readLedger,
repoRoots,
terminalLine,
} from "./sessions.mjs";
import { applyPatch, isOpen, proseProblems, resolveDocFiles, resolveDocImages, validate } from "./patches.mjs";
import {
CHAT_FILE,
chatReplyLines,
collectChat,
deliverableChat,
unansweredChat,
readChat,
validateChat,
writeCursor,
} from "./inbox.mjs";
import { pendingWorkspaceChanges, writeWorkspaceCursor } from "./workspace.mjs";
import { readPrHosts, readSubagentCursor, readSubagentSetting, writeSubagentCursor } from "./settings.mjs";
import { snapshot } from "./git-repo.mjs";
import { handoffsDir, isHandoffId, markHandoffUsed, readHandoffMeta } from "./handoffs.mjs";
import { RUN_EVENTS, TASK_EVENTS, MAX_COMMITS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
import { blockFor, offered } from "./public/subagents.js";
import { changeLine } from "./public/workspace.js";
// The CLI's own pieces, handed over by console.mjs through useCli() before
// any command runs: console.mjs runs on import, so it cannot be imported back.
let args, print, die, mustSession, sessionProject;
export function useCli(cli) {
({ args, print, die, mustSession, sessionProject } = cli);
}
/* ----------------------------------------------------------------- post */
// A patch from a file, or from stdin with `--file -`: a heredoc piped into
// the command saves the agent writing a file first, one tool call a turn.
// A file PowerShell wrote comes with a BOM (Out-File / Set-Content in 5.1) or
// in UTF-16 (its `>`), and both are the documented Windows route, so both read.
export function readPatch(file) {
try {
const buf = fs.readFileSync(file === "-" ? 0 : path.resolve(file));
let text;
if (buf[0] === 0xff && buf[1] === 0xfe) text = buf.subarray(2).toString("utf16le");
else if (buf[0] === 0xfe && buf[1] === 0xff) text = Buffer.from(buf.subarray(2)).swap16().toString("utf16le");
else text = buf.toString("utf8");
// A patch is one JSON object: an array, string or number would merge
// into the state as junk keys ("0", "1"...) and still report ok.
const patch = JSON.parse(text.replace(/^\uFEFF/, ""));
return patch && typeof patch === "object" && !Array.isArray(patch) ? patch : null;
} catch {
return null;
}
}
export function failValidation(problems) {
process.stderr.write("console: the payload was rejected, nothing was written.\n");
for (const p of problems) process.stderr.write(" - " + p + "\n");
// exitCode, not exit(): the agent has to read these lines to fix the patch,
// and process.exit() can truncate a pipe Node has not flushed.
process.exitCode = 3;
}
export async function cmdPost() {
// `post --wait <seconds>` is a post and then a wait in one command: one tool
// call per turn instead of two. A rejected post never waits (exit 3).
if (args.wait !== undefined && args.wait !== true && !Number.isFinite(Number.parseFloat(args.wait))) {
die("post --wait takes the slice in seconds, as wait --seconds does", 2);
}
if (!postOnce()) return;
if (args.wait === undefined) return;
// A bare --wait takes the slice from --seconds, as wait does.
args.seconds = args.wait === true ? args.seconds : args.wait;
return cmdWait();
}
function postOnce() {
const dir = mustSession();
const file = args.file;
if (!file) die("post needs --file <path to a JSON patch>", 2);
let patch = readPatch(file);
if (!patch) die(`could not read --file ${file} as one JSON object`, 2);
const statePath = path.join(dir, "state.json");
const before = readJson(statePath);
if (!before) die("that session has no state", 1);
try {
patch = resolveDocFiles(patch, before, before.worktree || repoRoots().worktree);
patch = resolveDocImages(patch, before, dir);
} catch (e) {
die(e.message, 3);
}
// Meter and folder reports go to the ledger, never into state.json. Checked
// here, before anything is written: a rejected post appends nothing.
const { run, folderIssue } = patch;
delete patch.run;
delete patch.folderIssue;
const reread = liftReread(patch, before.workflow);
const ledgerLines = ledgerFromPost(dir, run, folderIssue, before.workflow);
// Taken before the lock: git processes must not run while it is held.
const snap = reread === undefined ? null : snapshot(before.worktree || repoRoots().worktree, { prHosts: readPrHosts() });
// The patch is applied to a fresh read under the state lock, never to the
// read above: a send the person made in between is in the file, and a write
// built on the older read would take it away. Nothing in here may exit, so
// the lock is always let go; a refusal is carried out and reported after.
let refused = null;
let problems = [];
let written;
try {
written = updateState(dir, (fresh) => {
if (!fresh) {
refused = ["that session has no state", 1];
return null;
}
let next;
try {
next = applyPatch(fresh, patch);
} catch (e) {
refused = [e.message, 3];
return null;
}
// The result card and the fresh board land in this one write.
if (snap) {
next.git = gitBlock(snap, reread, fresh.git);
// The footer names the branch too: after a switch or a create it is
// the new one, and mid-rebase the one being rebased.
const onBranch = snap.head && (snap.head.branch || snap.head.rebasing);
if (onBranch) next.branch = onBranch;
}
problems = validate(next);
if (!problems.length && patch.chat) problems = validateChat(next, readChat(dir));
return problems.length ? null : next;
});
} catch (e) {
die(e.message, 1);
}
if (refused) die(...refused);
if (problems.length) return failValidation(problems);
const next = written.state;
for (const line of ledgerLines) appendLedger(dir, line);
// A build scores its tasks as it clears them (meter.js, PROGRESS_WORKFLOWS),
// after any `run` in the same post, so a phase finished here ends its count.
if (patch.headline && typeof patch.headline === "object") {
const ledger = readLedger(dir);
const progress = progressEntry(ledger, lastLaunchId(ledger), next.workflow, patch.headline.cleared);
if (progress) appendLedger(dir, progress);
}
appendEvent(dir, { type: "post", items: (patch.items || []).length });
const open = next.items.filter((i) => isOpen(i) && i.required !== false && i.kind !== "notice").length;
// Only a live server's link: no handle, no line, never a dead link.
const handle = listHandles(sessionProject(dir)).find((h) => h.sid === path.basename(dir));
print({
ok: true,
items: next.items.length,
open,
phase: next.phase,
...unansweredNote(dir, next),
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
});
return true;
}
/**
* A patch's `reread`, the agent's "re-read the repo" signal on the git board
* (FR-10), lifted out of the patch, or exit 3 when it is malformed or not on a
* git session. state.git itself is the console's own: a patch never carries it.
*/
export function liftReread(patch, workflow) {
if (Object.hasOwn(patch, "git")) die("state.git is the console's own: post reread instead", 3);
const { reread } = patch;
delete patch.reread;
if (reread === undefined) return undefined;
const flagOnly =
reread && typeof reread === "object" && !Array.isArray(reread) && Object.keys(reread).length === 1 && typeof reread.refreshFailed === "boolean";
if (reread !== true && !flagOnly) die("reread must be true or { refreshFailed: true|false }", 3);
if (workflow !== "git") die("reread only goes with the git workflow", 3);
return reread;
}
/**
* The new state.git from a snapshot. The agent's refreshFailed wins; without
* one, a newer FETCH_HEAD means a refresh worked, and anything else keeps the
* last word on it.
*/
export function gitBlock(snap, reread, previous) {
let refreshFailed;
if (reread && typeof reread === "object") refreshFailed = reread.refreshFailed;
else if (snap.lastFetch && (!previous?.lastFetch || Date.parse(snap.lastFetch) > Date.parse(previous.lastFetch))) refreshFailed = false;
else refreshFailed = Boolean(previous?.refreshFailed);
// A failed fetch still touches FETCH_HEAD, so its time is not a refresh:
// the board keeps saying when the last one that worked was.
if (refreshFailed === true && reread && typeof reread === "object") return { ...snap, lastFetch: previous?.lastFetch ?? null, refreshFailed };
return { ...snap, refreshFailed };
}
/**
* The ledger lines a post's `run` and `folderIssue` stand for, or exit 3 on
* the first bad one. Ids are scoped by the skill run in progress, so the same
* `run` posted twice counts once, and `phase-2` in one Implement run never
* collides with `phase-2` in the next.
*/
export function ledgerFromPost(dir, run, issue, workflow) {
if (run === undefined && issue === undefined) return [];
const launch = lastLaunchId(readLedger(dir));
const lines = [];
if (run !== undefined) {
const event = run && typeof run === "object" ? run.event : undefined;
if (!RUN_EVENTS.has(event)) die(`run: unknown event "${event}"`, 3);
if (typeof run.id !== "string" || !run.id.trim()) die("run: id required", 3);
if (run.tasks !== undefined) {
if (!TASK_EVENTS.has(event)) die(`run: tasks only goes with ${[...TASK_EVENTS].join(" or ")}`, 3);
if (!isTaskCount(run.tasks)) die(`run: tasks must be a whole number from 1 to ${MAX_TASKS}`, 3);
}
if (run.commits !== undefined) {
if (event !== "git-commits") die("run: commits only goes with git-commits", 3);
const ok = Number.isInteger(run.commits) && run.commits >= 1 && run.commits <= MAX_COMMITS;
if (!ok) die(`run: commits must be a whole number from 1 to ${MAX_COMMITS}`, 3);
}
lines.push({
kind: "run",
id: `${launch}:${run.id}`,
event,
workflow,
...(run.tasks !== undefined ? { tasks: run.tasks } : {}),
...(run.commits !== undefined ? { commits: run.commits } : {}),
});
}
if (issue !== undefined) {
const text = (v) => typeof v === "string" && v.trim() !== "";
const ok =
issue && typeof issue === "object" && text(issue.name) && text(issue.reason) && (issue.hint === undefined || text(issue.hint));
if (!ok) die("folderIssue must be { name, reason, hint? }, each a non-empty string", 3);
const problems = proseProblems(JSON.stringify([issue.reason, issue.hint || ""]), "folderIssue");
if (problems.length) die(problems.join("\n "), 3);
lines.push({
kind: "folder-issue",
id: `${launch}:${issue.name}`,
name: issue.name,
reason: issue.reason,
...(issue.hint ? { hint: issue.hint } : {}),
});
}
return lines;
}
/* ----------------------------------------------------------------- wait */
export async function cmdWait() {
const dir = mustSession();
// "240s" reads as 240. A --seconds with no number in it at all would make
// the deadline NaN, and the slice would end at once with exit 10: a busy
// loop, not a wait. So that is refused rather than guessed at.
const given = args.seconds;
const asked = typeof given === "string" ? Number.parseFloat(given) : NaN;
if (given !== undefined && !Number.isFinite(asked)) {
die(`--seconds must be a number, got "${args.seconds}"`, 2);
}
const seconds = Math.max(5, given === undefined ? 240 : asked);
const sid = path.basename(dir);
const project = sessionProject(dir);
const resultPath = path.join(dir, "result.json");
const chatPath = path.join(dir, CHAT_FILE);
const deadline = Date.now() + seconds * 1000;
const pendingChat = () => deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
// A result may already be sitting there: the person can finish the form even
// when the agent's session died, and a fresh agent picks it up here.
const liveUrl = () => listHandles(project).find((h) => h.sid === sid)?.url || "";
const existing = readJson(resultPath);
if (existing && !existing.consumedAt) return consume(dir, resultPath, existing, liveUrl(), pendingChat());
const earlyChat = pendingChat();
if (earlyChat.length) return deliverChat(dir, sid, earlyChat, liveUrl());
markWaiting(dir);
// A stat every 50ms, and a read only when the file has moved. The old tick
// was a full read and parse every 400ms, which put up to 0.4s between the
// person pressing Send and the agent starting on it, on every single send.
let healthAt = 0;
// A busy server (right after a post, say) can miss one health check without
// being gone. Only a missing handle or dead pid is proof at once; a server
// that merely does not answer must fail three checks in a row, each with a
// longer look, before the slice ends with exit 20.
let healthMisses = 0;
// The check in flight, if any. Aborted on every way out, so a fetch left
// running never holds the process (and the agent) past the print.
let health = null;
const healthStop = new AbortController();
try {
return await pollSlice();
} finally {
healthStop.abort();
}
async function pollSlice() {
// Null, not the current stamp: a result written between the check above and
// this line would otherwise read as already seen and wait out the slice.
let seen = null;
let chatSeen = null;
while (Date.now() < deadline) {
const stamp = fileStamp(resultPath);
if (stamp && stamp !== seen) {
const result = readJson(resultPath);
if (result && !result.consumedAt) return consume(dir, resultPath, result, liveUrl(), pendingChat());
// Unreadable for a moment (a lock, a scanner): look again next tick.
seen = result ? stamp : null;
}
// The chat inbox beside it, on the same tick: a Quick question ends the
// slice as surely as a card send does.
const chatStamp = fileStamp(chatPath);
if (chatStamp !== chatSeen) {
chatSeen = chatStamp;
const entries = pendingChat();
if (entries.length) return deliverChat(dir, sid, entries, liveUrl());
}
// The health check runs beside the polling, never in its way: awaited
// inline, a slow /health (a busy server, just after a send) held a
// finished send back for up to the whole fetch timeout.
if (!health && Date.now() - healthAt > 5000) {
healthAt = Date.now();
const handle = listHandles(project).find((h) => h.sid === sid);
if (!handle || !pidAlive(handle.pid)) {
print(serverGone(sid));
process.exitCode = 20;
return;
}
const check = { done: false, ok: false };
health = check;
healthOk(handle, 4000, healthStop.signal).then((ok) => Object.assign(check, { done: true, ok }));
}
if (health && health.done) {
const { ok } = health;
health = null;
if (ok) healthMisses = 0;
else if (++healthMisses >= 3) {
print(serverGone(sid));
process.exitCode = 20;
return;
} else healthAt = Date.now() - 3000; // look again in about 2s, not 5s
}
await new Promise((r) => setTimeout(r, 50));
}
const state = readJson(path.join(dir, "state.json")) || {};
const items = (state.items || []).filter((i) => i.required !== false && i.kind !== "notice");
const answered = items.filter((i) => !isOpen(i)).length;
const draft = readJson(path.join(dir, "draft.json"), {});
const staged = Object.keys(draft.staged || {}).length;
const handle = listHandles(project).find((h) => h.sid === sid);
print({
status: "waiting",
sid,
elapsed: fmtMs(Date.now() - Date.parse(state.created || nowIso())),
answered,
total: items.length,
staged,
url: handle ? handle.url : "",
message: "Waiting on your answer in the web console",
next: "NOT FINISHED, do not end your turn or write a summary: relay the message in one line, then run this same wait command again right now. Repeat until the exit code is not 10.",
...unansweredNote(dir, state),
// A workspace change alone never ends a slice: it rides on the next send.
pendingWorkspace: pendingWorkspaceChanges(dir).length,
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
});
process.exitCode = 10;
}
}
// Quick questions already handed over with no reply yet. Always empty when all are answered.
function unansweredNote(dir, state) {
const seqs = unansweredChat(dir, state);
return seqs.length
? { unansweredChat: seqs, warning: "Quick questions " + seqs.join(", ") + " have no reply yet and the page still shows them as pending. Reply to each now (chat.replies, re = seq): do what was asked when you can, or say why you will not." }
: {};
}
export function serverGone(sid) {
return {
status: "server-gone",
sid,
message: "The console server is not running. Start it again with `open --resume <sid> --workflow <yours>` (it gets a new link: give it to the person; without --no-open the browser opens it), then keep waiting: at a finished screen too, since the person's Ask messages and the dashboard button still need you.",
};
}
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
function deliverChat(dir, sid, entries, url) {
const [withWs, changes] = withWorkspace(dir, {
type: "chat",
at: nowIso(),
sid,
actions: [],
chat: entries,
reply: chatReplyLines(entries),
});
const [out, subCursor] = withSubagents(dir, withWs);
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
advanceCursor(dir, entries);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = 0;
}
// The workspace changes the agent is owed, added to what it is about to read:
// the list as `workspace`, and one line each at the end of `reply`.
function withWorkspace(dir, out) {
const changes = pendingWorkspaceChanges(dir);
if (!changes.length) return [out, changes];
const reply = [out.reply, ...changes.map(changeLine)].filter(Boolean).join("\n");
return [{ ...out, workspace: changes, reply }, changes];
}
// Print first, then this, as with the chat cursor: a kill in between can only
// hand the same change over again, never skip one.
export function advanceWorkspace(dir, changes) {
if (!changes.length) return;
try {
writeWorkspaceCursor(dir, Math.max(...changes.map((c) => c.version)));
} catch {}
}
// The server rewrites the session's setting for a new workflow only once its
// watcher sees the state `open` just wrote, so a launch or hop that read the
// file at once would find the old workflow's and owe the agent nothing until
// its next pickup. Give the server a moment to catch up instead, never
// writing the file ourselves (FR-7). A session with no setting file at all is
// an older server, which never writes one: a short look, not the full wait.
const SUBAGENT_SYNC_WAIT_MS = 1500;
const SUBAGENT_SYNC_MISSING_MS = 250;
export function awaitSubagentSync(dir, workflow) {
if (!offered(workflow)) return;
const start = Date.now();
for (;;) {
const setting = readSubagentSetting(dir);
if (setting && setting.workflow === workflow) return;
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
if (Date.now() - start >= budget) return;
sleepSync(25);
}
}
// The Subagents switch the agent is owed, added to what it is about to read:
// the setting as `subagents`, and its lines last in `reply`, after card lines,
// Quick questions and Workspace lines (FR-9). Read from the session's own
// setting file only, which only the server writes (FR-7). A setting for
// another workflow is the server not having caught up with a hop yet: it
// rides on the next pickup instead.
export function withSubagents(dir, out) {
const setting = readSubagentSetting(dir);
if (!setting) return [out, null];
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
if (setting.workflow !== workflow) return [out, null];
const block = blockFor(setting, readSubagentCursor(dir));
if (!block) return [out, null];
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
return [{ ...out, subagents: block.field, reply }, block.cursor];
}
// After the print, like advanceWorkspace(): a kill in between repeats the
// block at the next pickup, never loses it.
export function advanceSubagents(dir, cursor) {
if (!cursor) return;
try {
writeSubagentCursor(dir, cursor);
} catch {}
}
// Print first, then this, exactly as consume() stamps a result: a kill in
// between can only hand the same chat over again, and collectChat() drops
// anything that already has a reply.
export function advanceCursor(dir, entries) {
if (!entries.length) return;
try {
writeCursor(dir, Math.max(...entries.map((e) => e.seq)));
} catch {}
appendEvent(dir, { type: "chat-collect", count: entries.length });
}
/**
* Hand a result to the agent, then mark it collected. In that order.
*
* Both halves of this guard the same thing, and it matters most in agents other
* than the one this was built against: plenty of harnesses cap a single shell
* call well below a wait slice and kill it at their own timeout.
*
* Printing before stamping means such a kill can only ever cause the NEXT wait
* to hand the same result over twice, which the agent can absorb. The other
* order loses answers someone pressed Send on, silently and permanently.
*
* And exiting by setting `exitCode` rather than calling process.exit(): stdout
* to a pipe is asynchronous, and process.exit() truncates whatever Node has not
* flushed. That would throw the result away just as thoroughly.
*/
function consume(dir, resultPath, result, url, chat = []) {
const collected = { ...result, consumedAt: nowIso() };
// The link, any chat and any workspace change ride on what the agent reads,
// never on result.json itself.
const withChat = { ...collected, chat };
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
const [withWs, changes] = withWorkspace(dir, withChat);
const [out, subCursor] = withSubagents(dir, withWs);
const hop = hopFor(path.basename(dir), result);
markPickedUp(result);
print({ ...out, ...hop, ...handoffFor(result), ...(url ? { terminalLine: terminalLine(url) } : {}) });
try {
writeJsonAtomic(resultPath, collected);
} catch {}
markWorking(dir, result);
appendEvent(dir, { type: "consume", kind: result.type });
ledgerAnswers(dir, result);
advanceCursor(dir, chat);
advanceWorkspace(dir, changes);
advanceSubagents(dir, subCursor);
process.exitCode = result.type === "cancel" ? 30 : 0;
}
// A collected send is the agent's turn: the page says so at once, without the
// agent spending a whole post on "working" before it starts. The activity
// line belonged to the last stretch of work, so it goes; quietMinutes stays,
// since the page only counts it while working. Never fatal.
// The send is no longer waiting to be picked up either, so the phase the
// server set on it goes back to collecting (status and post report it).
function markWorking(dir, result) {
if (!result) return;
try {
updateState(dir, (s) => {
if (!s) return null;
if (result.type !== "submit") return s.phase === "submitted" ? { ...s, phase: "collecting" } : null;
// The cards this send carried, so `settle: true` settles what the agent
// was handed and never a later send still waiting to be collected.
const ids = [...new Set((result.actions || []).filter((a) => a && (a.type === "answer" || a.type === "skip") && typeof a.i === "string" && !a.i.startsWith("__")).map((a) => a.i))];
return applyPatch({ ...s, phase: "collecting", collected: { at: result.consumedAt || nowIso(), ids } }, { agent: { status: "working", activity: null } });
});
} catch {}
}
// Waiting on an open question (or a finished screen's buttons) is the
// person's turn, whatever the last post said: an agent that replied to a note
// and went back to `wait` without restating its status left the page on
// "working" with nobody working. With nothing open it stays as it is: an
// agent waiting out its research subagents is still working. Only a change
// is written.
function markWaiting(dir) {
try {
updateState(dir, (s) => {
if (!s || !s.agent || s.agent.status !== "working") return null;
// The dashboard's menu and the git board are the page's own, and theirs
// to click whenever the agent is waiting.
const theirTurn =
s.finish || s.workflow === "dashboard" || s.workflow === "git" || (s.items || []).some((i) => isOpen(i) && i.kind !== "notice");
return theirTurn ? applyPatch(s, { agent: { status: "waiting" } }) : null;
});
} catch {}
}
// The session hops a send can ask for, each with the one command that makes
// it and the skill file to follow after, so the agent copies instead of
// assembling `open --resume …` from the action's fields.
const HOP_ACTIONS = {
launch: (a) => ({ workflow: a.workflow, spec: a.spec, skill: a.skill }),
dashboard: () => ({ workflow: "dashboard", skill: "plan2code" }),
commit: () => ({ workflow: "git", skill: "plan2code-git" }),
pickup: pickupHop,
};
// A pick-up hops into the skill and spec the handoff's `.json` names (the page
// sends only the id). When the skill is no longer installed, the spec folder
// is gone, or the Handoff skill wrote it, Quick Task picks it up instead,
// flagged so the agent says so. In a
// source tree no skill sits beside the console, so nothing can be told to be
// missing and the stored skill stands.
function skillPath(skill) {
return path.resolve(HERE, "..", "..", "..", skill, "SKILL.md");
}
function pickupHop(action) {
const id = action.handoff;
const meta = isHandoffId(id) ? readHandoffMeta(id) : null;
const handoffFile = isHandoffId(id) ? path.join(handoffsDir(), id + ".md") : undefined;
const quick = { workflow: "quick-task", spec: undefined, skill: "plan2code-quick-task", handoffFile, fallback: true };
if (!meta) return quick;
if (typeof meta.workflow !== "string" || !/^[a-z-]+$/.test(meta.workflow)) return quick;
// The Handoff skill's own handoff: resuming it would only write another one.
if (meta.workflow === "handoff") return quick;
if (typeof meta.skill !== "string" || !/^[a-z0-9-]+$/.test(meta.skill)) return quick;
const specGone =
typeof meta.spec === "string" && meta.spec && (!SAFE_SPEC.test(meta.spec) || !fs.existsSync(path.join(meta.worktree || "", meta.spec)));
const skillGone = !fs.existsSync(skillPath(meta.skill)) && fs.existsSync(skillPath("plan2code-quick-task"));
if (specGone || skillGone) return quick;
return { workflow: meta.workflow, spec: meta.spec || undefined, skill: meta.skill, handoffFile };
}
// A stop that asked for a handoff gets the Handoff skill's file beside it, so
// the agent opens it instead of locating it. Only a built skill has one.
function handoffFor(result) {
const actions = (result && Array.isArray(result.actions) && result.actions) || [];
if (!actions.some((a) => a && a.type === "stop" && a.i === "__stop" && a.handoff === true)) return {};
const file = path.resolve(HERE, "..", "..", "..", "plan2code-handoff", "SKILL.md");
return fs.existsSync(file) ? { handoffSkill: file } : {};
}
// A pick-up uses its handoff up as its hop is printed, so the next dashboard
// scan no longer lists it. Never fatal; a repeat delivery marks it again.
function markPickedUp(result) {
const actions = (result && Array.isArray(result.actions) && result.actions) || [];
for (const a of actions) {
if (a && a.type === "pickup" && typeof a.i === "string" && a.i.startsWith("__") && isHandoffId(a.handoff)) {
try {
markHandoffUsed(a.handoff);
} catch {}
}
}
}
// A spec name that is safe to put in the `resume` command: `specs/<name>` with
// nothing a shell would act on. A handoff's `.json` and a page's send are both
// data off disk or the wire, so the name is checked here and not trusted.
const SAFE_SPEC = /^specs\/[^/\\"'`$;&|<>(){}*?!#~\r\n]+$/;
function hopFor(sid, result) {
const actions = (result && Array.isArray(result.actions) && result.actions) || [];
const action = actions.find((a) => a && Object.hasOwn(HOP_ACTIONS, a.type) && typeof a.i === "string" && a.i.startsWith("__"));
if (!action) return {};
const { workflow, spec, skill, handoffFile, fallback } = HOP_ACTIONS[action.type](action);
if (typeof workflow !== "string" || !/^[a-z-]+$/.test(workflow)) return {};
const quote = (v) => (/[\s"]/.test(v) ? `"${v.replace(/"/g, '\\"')}"` : v);
const specArg = typeof spec === "string" && SAFE_SPEC.test(spec) ? ` --spec ${quote(spec)}` : "";
const out = { resume: `node "${path.join(HERE, "console.mjs")}" open --resume ${sid} --no-open --workflow ${workflow}${specArg}` };
if (typeof skill === "string" && /^[a-z0-9-]+$/.test(skill)) {
const file = skillPath(skill);
if (fs.existsSync(file)) out.skillFile = file;
}
if (typeof handoffFile === "string") out.handoffFile = handoffFile;
if (fallback) out.fallback = true;
return out;
}
// One `answer` ledger line per item the person answered in this send, for
// the session meter. The id carries the send's stamp, so a send collected
// twice (a kill before consumedAt was written) still counts once, while the
// same question answered again in a later round counts again: that round was
// real back-and-forth. Never fatal: the meter is advice.
function ledgerAnswers(dir, result) {
if (!result || result.type !== "submit" || !Array.isArray(result.actions)) return;
try {
const launch = lastLaunchId(readLedger(dir));
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
const items = new Set();
for (const a of result.actions) {
if (a && a.type === "answer" && typeof a.i === "string" && !a.i.startsWith("__")) items.add(a.i);
}
for (const i of items) appendLedger(dir, { kind: "answer", id: `${launch}:answer:${result.at}:${i}`, workflow });
} catch {}
}
function fmtMs(ms) {
if (!Number.isFinite(ms) || ms < 0) return "0s";
const s = Math.round(ms / 1000);
if (s < 60) return `${s}s`;
const m = Math.floor(s / 60);
return `${m}m ${s % 60}s`;
}
+283
View File
@@ -0,0 +1,283 @@
// Plan2Code Web Console - the small commands: keep, forget, delete-spec, handoff, delete-handoff, status and stop.
import fs from "node:fs";
import path from "node:path";
import { SESSIONS_DIR, appendEvent, readJson } from "./files.mjs";
import { attachmentName, healthOk, listHandles, pidAlive, projectRoot, repoRoots, sessionDir } from "./sessions.mjs";
import { removeSpec } from "./scan.mjs";
import { isOpen } from "./patches.mjs";
import { pendingChatCount } from "./inbox.mjs";
import { forgetWorkspace, specKey } from "./workspace.mjs";
import { newHandoff, removeHandoff } from "./handoffs.mjs";
// The CLI's own pieces, handed over by console.mjs through useCli() before
// any command runs: console.mjs runs on import, so it cannot be imported back.
let args, print, die, mustSession, sessionProject;
export function useCli(cli) {
({ args, print, die, mustSession, sessionProject } = cli);
}
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
// still be one of our servers, so its pid gets no second look.
const MAX_SERVER_LIFE_MS = 4 * 60 * 60 * 1000;
/* ----------------------------------------------------------------- keep */
// Copy one of the session's note attachments into specs/<idea>/attachments/, so
// a spec file can cite it after the session is swept. Run by the agent, never
// the server: the server still never writes into a project.
export function cmdKeep() {
const usage = "keep needs --session <sid> --upload <path> --name <name> --spec specs/<idea>";
if ([args.upload, args.name, args.spec].some((v) => typeof v !== "string")) die(usage, 2);
const dir = mustSession();
const state = readJson(path.join(dir, "state.json"));
if (!state) die("that session has no state", 1);
const project = state.project;
const upload = path.resolve(args.upload);
// Compared as real paths: Windows hands the same folder out both long
// (C:\Users\Justin.Parker) and 8.3 (C:\Users\JUSTIN~1.PAR), and the reply's
// path need not be spelled the way this session's directory is.
// A path that does not exist (yet) resolves through its nearest real parent,
// so a missing upload still reads as missing, not as somewhere else.
const real = (p) => {
try {
return fs.realpathSync.native(p);
} catch {
const parent = path.dirname(path.resolve(p));
return parent === path.resolve(p) ? path.resolve(p) : path.join(real(parent), path.basename(p));
}
};
if (!inside(real(path.join(dir, "uploads")), real(upload))) die("upload is not in this session's uploads folder", 3);
const spec = path.resolve(project, args.spec);
const attachments = path.join(spec, "attachments");
if (!inside(project, spec) || !inside(fs.realpathSync(project), realNearest(attachments))) {
die("spec folder is outside the project", 3);
}
if (!fs.existsSync(upload) || !fs.statSync(upload).isFile()) die("no such upload", 3);
// The file the link is written for has to be in the project too, or the
// relative link would point out of it.
if (typeof args.from === "string" && !inside(project, path.resolve(project, args.from))) {
die("--from is outside the project", 3);
}
// One upload, one copy: kept again under another name, the copy it already
// has (named for the same upload id) is the one reused.
// Named from the real path: an 8.3 spelling (7CF881~1.JPG) would name the
// copy after the short form and miss the copy this upload already has.
const named = attachmentName({ upload: real(upload), name: args.name });
const suffix = named.slice(named.lastIndexOf("-"));
let existing = null;
try {
existing = fs.readdirSync(attachments).find((f) => f.endsWith(suffix));
} catch {}
const file = existing || named;
const target = path.join(attachments, file);
fs.mkdirSync(attachments, { recursive: true });
let reused = false;
try {
fs.copyFileSync(upload, target, fs.constants.COPYFILE_EXCL);
} catch (err) {
if (err.code !== "EEXIST") throw err;
reused = true;
}
const slashes = (p) => p.split(path.sep).join("/");
const linkBase = typeof args.from === "string" ? path.dirname(path.resolve(project, args.from)) : spec;
const kept = slashes(path.relative(project, target));
print({
ok: true,
path: kept,
link: slashes(path.relative(linkBase, target)),
image: path.extname(target) === ".jpg",
reused,
});
appendEvent(dir, { type: "keep", id: path.basename(upload, path.extname(upload)), path: kept });
}
// Whether child sits strictly under parent. path.relative handles drive
// letters and POSIX alike; Windows paths fold case, as the server's do.
function inside(parent, child) {
const fold = (s) => (process.platform === "win32" ? s.toLowerCase() : s);
const rel = path.relative(fold(path.resolve(parent)), fold(path.resolve(child)));
return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
}
// p with its nearest existing ancestor's symlinks and junctions resolved, so a
// linked specs/, spec or attachments/ folder cannot carry a copy out of the project.
function realNearest(p) {
let existing = p;
while (!fs.existsSync(existing)) existing = path.dirname(existing);
return path.join(fs.realpathSync(existing), path.relative(existing, p));
}
/* --------------------------------------------------------------- forget */
// Drop the folder list remembered for one spec (Finalize, once the spec is
// archived). The project's own list and every other spec's are untouched.
export function cmdForget() {
if (typeof args.spec !== "string" || !args.spec.trim()) die("forget needs --spec specs/<idea>", 2);
let spec = specKey(args.spec);
if (/\.md$/i.test(spec)) spec = spec.slice(0, spec.lastIndexOf("/"));
const worktree = repoRoots().worktree;
print({ ok: true, spec, forgot: forgetWorkspace(worktree, spec) });
}
/* ---------------------------------------------------------- delete-spec */
// The dashboard's Delete button, carried out by the agent: the page never
// writes into a project. removeSpec() does every check; a refusal is exit 3
// with the reason, and the remembered workspace for the spec goes with it.
export function cmdDeleteSpec() {
if (typeof args.spec !== "string" || !args.spec.trim()) die("delete-spec needs --spec specs/<name>", 2);
const worktree = repoRoots().worktree;
try {
const done = removeSpec(worktree, args.spec);
forgetWorkspace(worktree, args.spec);
print(done);
} catch (err) {
print({ ok: false, message: err.message });
process.exit(3);
}
}
/* --------------------------------------------------------------- handoff */
// A handoff the agent is about to write, claimed in ~/.plan2code/handoffs/
// (handoffs.mjs) for this checkout: the Stop flow's "Stop with a handoff" and
// the Handoff skill both start here. Only the .json is written; the agent
// writes the document at the printed path.
export function cmdHandoff() {
const usage = "handoff needs: handoff new --workflow <w> --skill <s> [--spec specs/<x>] [--title <t>] [--from-stop]";
if (args._[0] !== "new" || args._.length > 1) die(usage, 2);
if (typeof args.workflow !== "string" || typeof args.skill !== "string") die(usage, 2);
if ("from-stop" in args && args["from-stop"] !== true) die("--from-stop takes no value", 2);
const { worktree, project } = repoRoots();
try {
const { id, path: file, meta } = newHandoff({
worktree,
project,
spec: args.spec,
workflow: args.workflow,
skill: args.skill,
title: args.title,
fromStop: args["from-stop"] === true,
});
print({ ok: true, id, path: file, meta });
} catch (err) {
print({ ok: false, message: err.message });
process.exit(3);
}
}
// The dashboard's Delete on a Handoff chip, carried out by the agent, the
// same shape as delete-spec: removeHandoff() does every check.
export function cmdDeleteHandoff() {
if (typeof args.handoff !== "string" || !args.handoff.trim()) die("delete-handoff needs --handoff <id>", 2);
try {
print(removeHandoff(args.handoff));
} catch (err) {
print({ ok: false, message: err.message });
process.exit(3);
}
}
/* --------------------------------------------------------------- status */
export async function cmdStatus() {
const project = projectRoot();
if (args.session || args.sid) {
const dir = mustSession();
const state = readJson(path.join(dir, "state.json")) || {};
const handle = listHandles(sessionProject(dir)).find((h) => h.sid === path.basename(dir));
const result = readJson(path.join(dir, "result.json"));
return print({
sid: state.sid,
session: dir,
workflow: state.workflow,
title: state.title,
phase: state.phase,
items: (state.items || []).length,
open: (state.items || []).filter(isOpen).length,
url: handle ? handle.url : "",
live: handle ? pidAlive(handle.pid) : false,
pendingResult: Boolean(result && !result.consumedAt),
pendingChat: pendingChatCount(dir, state),
});
}
let sids = [];
try {
sids = fs.readdirSync(SESSIONS_DIR).sort().reverse();
} catch {
return print({ sessions: [] });
}
const handles = listHandles(project);
const rows = [];
for (const sid of sids.slice(0, Number(args.limit || 20))) {
const dir = sessionDir(sid);
const state = readJson(path.join(dir, "state.json"));
if (!state) continue;
if (!args.all && state.project !== project) continue;
const handle = handles.find((h) => h.sid === sid);
const result = readJson(path.join(dir, "result.json"));
rows.push({
sid,
workflow: state.workflow,
title: state.title,
phase: state.phase,
created: state.created,
live: handle ? pidAlive(handle.pid) : false,
url: handle ? handle.url : "",
pendingResult: Boolean(result && !result.consumedAt),
pendingChat: pendingChatCount(dir, state),
});
}
print({ sessions: rows });
}
/* ----------------------------------------------------------------- stop */
export async function cmdStop() {
// --all is this folder's sessions; one named session is found wherever
// the command runs from.
const named = !args.all && (args.session || args.sid) ? sessionDir(path.basename(args.session || args.sid)) : null;
const project = named && fs.existsSync(named) ? sessionProject(named) : projectRoot();
const handles = listHandles(project);
const targets = args.all
? handles
: handles.filter((h) => h.sid === path.basename(args.session || args.sid || ""));
if (!targets.length) return print({ ok: true, stopped: 0 });
let stopped = 0;
let skipped = 0;
for (const h of targets) {
// Identify the process before killing it. A handle file can outlive a
// reboot in the system temp directory, and PIDs get reused; without this
// check `stop --all` can kill an unrelated program that happens to have
// inherited the number. /health returning our own sid is the only proof:
// a live pid and a young handle are not, since a server that died a
// minute ago leaves exactly that behind for any process to inherit. A
// busy server gets a second, longer look, and still has to answer as
// ours; one that does not is left alone, and only its handle goes.
const young = Date.now() - Date.parse(h.startedAt || 0) < MAX_SERVER_LIFE_MS;
const ours = (await healthOk(h)) || (young && pidAlive(h.pid) && (await healthOk(h, 5000)));
if (!ours) {
skipped++;
try {
fs.rmSync(h.handlePath, { force: true });
} catch {}
continue;
}
try {
process.kill(h.pid);
stopped++;
} catch {}
try {
fs.rmSync(h.handlePath, { force: true });
} catch {}
}
print({ ok: true, stopped, ...(skipped ? { skippedStaleHandles: skipped } : {}) });
}
+3 -1
View File
@@ -22,7 +22,9 @@ free to close that terminal and kill them mid-write. While you wait, post
and update the count as each returns. Never write a `finish.body` that says
work "is running in the background" or "will finish on its own". Mark every
reported helper `done` or `failed` before the finish, so the Subagents tab
never ends on a row still running.
never ends on a row still running: post each one's `done` in the same turn its
notice arrives, and a `finish` is refused (exit `3`, naming the helper) while
any row is still `running`.
## 1. Post the finish
File diff suppressed because it is too large. Load diff
+294
View File
@@ -0,0 +1,294 @@
// Plan2Code Web Console - where the console's files live, how they are written safely, and the argument parser both command lines share.
//
// Two directories with deliberately different durability:
//
// runtime handle os.tmpdir()/plan2code-console/<cwd-hash>/<sid>.json
// port, pid, token, url. Losing it on reboot is correct,
// because the server is gone too. (Jupyter's jpserver-<pid>.json pattern.)
//
// session state ~/.plan2code/console/sessions/<sid>/
// the request, the human's draft, the result, the event log.
// Deliberately NOT under specs/: that keeps the console clear of
// the metrics confidence scraper and the loop's completion-marker
// parser, and it survives a `git clean`.
//
// Node built-ins only. No build step.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { pidAlive } from "./sessions.mjs";
export const HERE = path.dirname(fileURLToPath(import.meta.url));
export const PUBLIC_DIR = path.join(HERE, "public");
export const HOME_DIR =
process.env.PLAN2CODE_CONSOLE_HOME ||
path.join(os.homedir(), ".plan2code", "console");
export const SESSIONS_DIR = path.join(HOME_DIR, "sessions");
// The person's own settings (colors, theme), shared by every session. Lives in
// HOME_DIR rather than beside a session precisely because it is NOT session
// state: a browser ties localStorage to the origin, and the origin carries the
// ephemeral port, so the file under this dir is the only copy of a preference
// that survives the next session's new port.
// Model menus for the `plan2code` launcher. The shipped list (bin/models.json) is the
// authors' and is overwritten by every install; the user's additions (models.json) are
// theirs. The launcher reads both. PLAN2CODE_MODELS_DIR moves them, for tests.
export const PLAN2CODE_DIR = process.env.PLAN2CODE_MODELS_DIR || path.join(os.homedir(), ".plan2code");
export const SHIPPED_MODELS_FILE = path.join(PLAN2CODE_DIR, "bin", "models.json");
export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
// so every session within the hour reuses one lookup.
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
// test run (or a second sandboxed instance) shares one handle directory with
// the real thing, and `stop --all` reaches outside its own world and kills a
// session someone is actually using.
export const RUNTIME_DIR = process.env.PLAN2CODE_CONSOLE_HOME
? path.join(process.env.PLAN2CODE_CONSOLE_HOME, "runtime")
: path.join(os.tmpdir(), "plan2code-console");
export const SCHEMA = 1;
/* ------------------------------------------------------------------ args */
export function parseArgs(argv) {
const out = { _: [] };
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a.startsWith("--")) {
const eq = a.indexOf("=");
if (eq > -1) out[a.slice(2, eq)] = a.slice(eq + 1);
else if (argv[i + 1] && !argv[i + 1].startsWith("--")) out[a.slice(2)] = argv[++i];
else out[a.slice(2)] = true;
} else out._.push(a);
}
return out;
}
/* ------------------------------------------------------------------- fs */
export function ensureDir(dir) {
fs.mkdirSync(dir, { recursive: true });
return dir;
}
// Atomic replace. The waiter polls result.json and WILL land mid-write eventually.
//
// The retry loop is not paranoia: on Windows, antivirus and the search indexer
// hold transient locks that surface as EPERM/EBUSY from rename. It is intermittent,
// unreproducible on demand, and looks exactly like a logic bug. Retry from day one.
export function writeJsonAtomic(file, data) {
const tmp = file + "." + process.pid + ".tmp";
const body = JSON.stringify(data, null, 2);
let lastErr;
for (let attempt = 0; attempt < 4; attempt++) {
try {
const fd = fs.openSync(tmp, "w");
try {
fs.writeFileSync(fd, body);
fs.fsyncSync(fd);
} finally {
fs.closeSync(fd);
}
fs.renameSync(tmp, file);
return body;
} catch (err) {
lastErr = err;
if (err.code !== "EPERM" && err.code !== "EBUSY" && err.code !== "EACCES") break;
sleepSync(40 * (attempt + 1));
}
}
try {
fs.rmSync(tmp, { force: true });
} catch {}
throw lastErr;
}
// A cheap "has this file changed?" fingerprint: one stat instead of a read and
// a parse. An atomic write replaces the file, so a new write always moves at
// least one of these. "" for a file that is not there.
export function fileStamp(file) {
try {
const st = fs.statSync(file, { throwIfNoEntry: false });
return st ? `${st.mtimeMs}:${st.size}:${st.ino}` : "";
} catch {
return "";
}
}
export function readJson(file, fallback = null) {
try {
return JSON.parse(fs.readFileSync(file, "utf8"));
} catch {
return fallback;
}
}
export function readText(file) {
try {
return fs.readFileSync(file, "utf8");
} catch {
return "";
}
}
export function appendEvent(dir, event) {
const line = JSON.stringify({ at: nowIso(), ...event });
fs.appendFileSync(path.join(dir, "events.ndjson"), line + "\n");
return line;
}
/* ----------------------------------------------------- the state lock */
// state.json has two writers in two processes: console.mjs (`open` and `post`,
// the agent's side) and the server (`/submit` stamps the phase and records
// what was sent on each item). Each writer reads the file, changes it and
// writes it back, so two of them overlapping lose whichever wrote first. Every
// read-modify-write of state.json therefore runs under this lock, a file
// created with O_EXCL beside it. The sections it guards are a read, a merge
// and a write, milliseconds long, so a lock older than LOCK_STALE_MS, or one
// whose holder has died, is a crash left behind and is broken. The wait runs
// past the stale age, so a writer always gets in eventually.
export const STATE_LOCK_FILE = "state.json.lock";
const LOCK_STALE_MS = 5000;
const LOCK_WAIT_MS = 7000;
function lockStale(lock) {
try {
const st = fs.statSync(lock);
if (Date.now() - st.mtimeMs > LOCK_STALE_MS) return true;
const pid = Number.parseInt(fs.readFileSync(lock, "utf8"), 10);
return Number.isInteger(pid) && pid > 0 && pid !== process.pid && !pidAlive(pid);
} catch (err) {
// Gone between the failed create and this look: free, so try again.
return err.code === "ENOENT";
}
}
// Run fn while holding the session's state lock, and release it however fn
// ends. fn must not call process.exit(): the release would never run, and the
// next writer would wait out the stale age.
export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) {
const lock = path.join(dir, lockName);
const deadline = Date.now() + LOCK_WAIT_MS;
let fd = null;
for (let attempt = 0; fd === null; attempt++) {
try {
fd = fs.openSync(lock, "wx");
} catch (err) {
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
if (Date.now() > deadline) throw new Error(`${lockName.replace(/.lock$/, "")} is busy with another writer; try again`);
if (err.code === "EEXIST" && lockStale(lock)) {
try {
fs.rmSync(lock, { force: true });
} catch {}
continue;
}
sleepSync(Math.min(5 * (attempt + 1), 50));
}
}
try {
try {
fs.writeSync(fd, String(process.pid));
} finally {
fs.closeSync(fd);
}
return fn();
} finally {
try {
fs.rmSync(lock, { force: true });
} catch {}
}
}
// The one way to change state.json: under the lock, read it fresh, hand it to
// fn (null when there is no state yet, with the raw text beside it), and write
// back whatever fn returns. A null return writes nothing. Returns the written
// state and its text, or null.
export function updateState(dir, fn) {
const file = path.join(dir, "state.json");
return withStateLock(dir, () => {
let text = null;
try {
text = fs.readFileSync(file, "utf8");
} catch {}
let state = null;
try {
state = text === null ? null : JSON.parse(text);
} catch {}
const next = fn(state, text);
if (!next) return null;
return { state: next, text: writeJsonAtomic(file, next) };
});
}
export function sleepSync(ms) {
// Node built-ins only, and this runs in short one-shot CLI commands.
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
}
export function nowIso() {
return new Date().toISOString();
}
// Every whole, parsable object line of an ndjson file, in order.
export function readJsonLines(file) {
let text;
try {
text = fs.readFileSync(file, "utf8");
} catch {
return [];
}
const lines = text.split("\n");
lines.pop(); // "" after a complete last line, or the half-written one
const out = [];
for (const line of lines) {
if (!line.trim()) continue;
try {
const entry = JSON.parse(line);
if (entry && typeof entry === "object") out.push(entry);
} catch {}
}
return out;
}
// Append one JSON line to an ndjson file, returning what was stored.
export function appendJsonLine(file, stored) {
let lead = "";
try {
const st = fs.statSync(file);
// A fragment left by a crash mid-append must not swallow this line too.
if (st.size > 0) {
const fd = fs.openSync(file, "r");
try {
const b = Buffer.alloc(1);
fs.readSync(fd, b, 0, 1, st.size - 1);
if (b[0] !== 0x0a) lead = "\n";
} finally {
fs.closeSync(fd);
}
}
} catch {}
const line = lead + JSON.stringify(stored) + "\n";
let lastErr;
for (let attempt = 0; attempt < 4; attempt++) {
try {
fs.appendFileSync(file, line);
return stored;
} catch (err) {
lastErr = err;
if (err.code !== "EPERM" && err.code !== "EBUSY" && err.code !== "EACCES") break;
sleepSync(40 * (attempt + 1));
}
}
throw lastErr;
}
+237
View File
@@ -0,0 +1,237 @@
// Plan2Code Web Console - the Quick question chat's inbox beside the card slot.
import path from "node:path";
import { CHAT_LIMIT } from "./public/chat.js";
import { appendJsonLine, nowIso, readJson, readJsonLines, writeJsonAtomic } from "./files.mjs";
import { isPlainObject, proseProblems } from "./patches.mjs";
/* ------------------------------------------------------- the chat inbox */
// The Quick question chat rides its own channel beside the card slot, so the
// two never contend: a chat message never waits on an uncollected card send,
// and a card send never waits on chat. Every file has exactly one writer:
//
// chat.ndjson the server. One JSON line per entry: message / decision / reset.
// chat-cursor.json console.mjs. The last seq the agent was handed.
// state.json console.mjs `post`. The agent's replies, under chat.replies.
// (state.json as a whole has a second writer, the server's
// /submit, so every change to it goes through updateState().)
//
// The Workspace and the session meter follow the same rule, in files that
// switchWorkflow() never touches, so they carry across dashboard hops:
//
// workspace.json the server. Folders, version, change log, missing, remote.
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
export const CHAT_FILE = "chat.ndjson";
export const CHAT_CURSOR_FILE = "chat-cursor.json";
/**
* The inbox's entries with `seq > afterSeq`. A final segment with no newline
* is a line still being written: it is left for the next read, never parsed
* half-way. A line that will not parse is skipped rather than thrown on.
*/
export function readChat(dir, afterSeq = 0) {
return readJsonLines(path.join(dir, CHAT_FILE)).filter((e) => Number.isInteger(e.seq) && e.seq > afterSeq);
}
// Single-writer rule: only the server may call this (server.mjs and its routes).
export function appendChat(dir, entry) {
const last = readChat(dir).reduce((max, e) => Math.max(max, e.seq), 0);
return appendJsonLine(path.join(dir, CHAT_FILE), { ...entry, seq: last + 1, at: nowIso() });
}
export function readCursor(dir) {
const saved = readJson(path.join(dir, CHAT_CURSOR_FILE), { seq: 0 });
const n = Number(saved && saved.seq);
return Number.isInteger(n) && n > 0 ? n : 0;
}
// Never backwards: a slow collector finishing after a faster one must not
// hand the faster one's entries over again.
export function writeCursor(dir, seq) {
writeJsonAtomic(path.join(dir, CHAT_CURSOR_FILE), { seq: Math.max(readCursor(dir), seq) });
}
// The conversation the inbox is on: the one its last reset opened.
export function currentConversation(entries) {
for (let i = entries.length - 1; i >= 0; i--) {
const e = entries[i];
if (e.kind === "reset") return { conversation: e.conversation, workflow: e.workflow || "", sinceSeq: e.seq };
}
return { conversation: 0, workflow: "", sinceSeq: 0 };
}
// Typed messages only: Approve / Decline and resets never count to the limit.
export function typedCount(entries, conversation) {
return entries.filter((e) => e.kind === "message" && e.conversation === conversation).length;
}
/**
* The chat block of a page frame: the current conversation's person entries
* from the inbox and the agent's replies from the state, as one list. A reply
* sits straight after the entry it answers; one naming nothing here goes last.
*/
export function chatForFrame(entries, state) {
const { conversation } = currentConversation(entries);
const person = entries
.filter((e) => (e.kind === "message" || e.kind === "decision") && e.conversation === conversation)
.sort((a, b) => a.seq - b.seq);
const replies = (state?.chat?.replies || []).filter((r) => r && r.conversation === conversation);
const messages = [];
const placed = new Set();
for (const p of person) {
messages.push({ from: "person", ...p });
replies.forEach((r, i) => {
if (r.re !== p.seq) return;
messages.push({ from: "agent", ...r });
placed.add(i);
});
}
replies.forEach((r, i) => placed.has(i) || messages.push({ from: "agent", ...r }));
return { conversation, messages, typed: typedCount(entries, conversation), limit: CHAT_LIMIT };
}
/**
* What the agent has not been handed yet: entries past the cursor, minus any
* message or decision that already has a reply. The second half is what keeps
* a lost cursor from ever causing a second answer. Resets always go through.
*/
export function collectChat(dir, state) {
const replied = new Set((state?.chat?.replies || []).map((r) => r && r.re));
return readChat(dir, readCursor(dir)).filter((e) => e.kind === "reset" || !replied.has(e.seq));
}
// What is worth handing over: the collected entries once one of them is
// something the person said. A reset alone (every session opens with one)
// waits and rides along with the next message, or `wait` would return on the
// opening line of every session and every first card reply would carry it.
// A run of resets (the session's opening one, then one per skill switch)
// says one thing, so only the last of each run is handed over; it carries the
// highest seq of the run, so the cursor still moves past all of them.
export function deliverableChat(entries) {
if (!entries.some((e) => e.kind !== "reset")) return [];
return entries.filter((e, i) => !(e.kind === "reset" && entries[i + 1] && entries[i + 1].kind === "reset"));
}
// Things the person said that were handed over but never answered. The page keeps
// showing "working on the answer" for each until a reply lands, so the agent is
// told on every post and every wait slice until it has replied (a refusal is a reply).
export function unansweredChat(dir, state) {
const { conversation } = currentConversation(readChat(dir, 0));
const replied = new Set((state?.chat?.replies || []).map((r) => r && r.re));
const cursor = readCursor(dir);
return readChat(dir, 0)
.filter((e) => (e.kind === "message" || e.kind === "decision") && e.conversation === conversation)
.filter((e) => e.seq <= cursor && !replied.has(e.seq))
.map((e) => e.seq);
}
// How many things the person said are still waiting to be collected.
export function pendingChatCount(dir, state) {
return collectChat(dir, state).filter((e) => e.kind !== "reset").length;
}
// The chat entries as the lines appended to `reply`, in the note's shape.
// Whatever the person typed is indented past its first line, so only a real
// entry ever starts a line: a typed "Approved: edit p1" must not read as one.
export function chatReplyLines(entries) {
const indent = (s, pad) => String(s).replace(/\r?\n/g, "\n" + pad);
const lines = [];
for (const e of entries) {
if (e.kind === "message") {
lines.push(`Quick question: ${indent(e.text, " ")}`);
if (e.about && e.about.label) lines.push(` About: ${indent(e.about.label, " ")}`);
for (const img of e.images || []) lines.push(` Image: ${img.path} (${img.name})`);
for (const f of e.files || []) lines.push(` File: ${f.path} (${f.name})`);
} else if (e.kind === "decision") {
lines.push(`${e.decision === "approve" ? "Approved" : "Declined"}: edit ${e.re}`);
if (e.text) lines.push(` Note: ${indent(e.text, " ")}`);
} else if (e.kind === "reset") {
lines.push("New conversation started. Treat earlier chat as closed.");
}
}
return lines.join("\n");
}
// A project-relative path: no root, no drive letter, no step outside.
function projectRelative(p) {
if (typeof p !== "string" || !p.trim()) return false;
if (/^[\\/]/.test(p) || /^[A-Za-z]:/.test(p)) return false;
return !p.split(/[\\/]/).includes("..");
}
function underSpec(file, specDir) {
const norm = (s) => {
const t = s.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
return process.platform === "win32" ? t.toLowerCase() : t;
};
const f = norm(file);
const spec = norm(specDir);
return Boolean(spec) && (f === spec || f.startsWith(spec + "/"));
}
/**
* The house rules for the agent's chat replies, checked against the inbox
* they answer. Same shape as validate(): problems as sentences, [] when fine.
*/
export function validateChat(state, entries) {
const replies = state?.chat?.replies;
if (replies == null) return [];
if (!Array.isArray(replies)) return ['"chat.replies" must be an array'];
const problems = [];
const targets = new Set(
entries.filter((e) => e.kind === "message" || e.kind === "decision").map((e) => e.seq)
);
const ids = new Set();
for (const r of replies) {
if (!isPlainObject(r)) {
problems.push("every chat reply must be an object");
continue;
}
const name = typeof r.id === "string" && r.id.trim() ? r.id : "(no id)";
if (name === "(no id)") problems.push('every chat reply needs a non-empty string "id"');
else if (ids.has(r.id)) problems.push(`duplicate chat reply id "${r.id}"`);
ids.add(r.id);
if (!Number.isInteger(r.re) || !targets.has(r.re)) {
problems.push(`chat reply "${name}" needs "re": the seq of the message or decision it answers`);
}
if (!Number.isInteger(r.conversation)) problems.push(`chat reply "${name}" needs an integer "conversation"`);
if (typeof r.md !== "string" || !r.md.trim()) problems.push(`chat reply "${name}" needs its answer in "md"`);
const p = r.proposal;
if (p != null) {
if (!isPlainObject(p)) problems.push(`chat reply "${name}" "proposal" must be an object`);
else {
if (typeof p.summary !== "string" || !p.summary.trim()) {
problems.push(`chat reply "${name}" proposal needs a plain-English "summary"`);
}
if (!Array.isArray(p.files) || !p.files.length) {
problems.push(`chat reply "${name}" proposal needs "files": the project files it would change`);
} else {
for (const f of p.files) {
if (!projectRelative(f)) {
problems.push(`chat reply "${name}" proposal file "${f}" must be a project-relative path`);
} else if (state.specDir && underSpec(f, state.specDir)) {
problems.push(`a chat edit cannot touch the running skill's own files under ${state.specDir}/`);
}
}
}
}
}
if (r.changed != null) {
const count = (n) => Number.isInteger(n) && n >= 0;
if (!Array.isArray(r.changed) || !r.changed.every((c) => isPlainObject(c) && typeof c.file === "string" && count(c.added) && count(c.removed))) {
problems.push(`chat reply "${name}" "changed" must be a list of { file, added, removed }`);
}
}
}
const prose = JSON.stringify(replies.map((r) => [r && r.md, r && r.proposal && r.proposal.summary]));
problems.push(...proseProblems(prose, "a chat reply"));
return problems;
}
File diff suppressed because it is too large. Load diff
+858
View File
@@ -0,0 +1,858 @@
// Plan2Code Web Console - checking and merging an agent's patch into the session state.
import fs from "node:fs";
import path from "node:path";
import { checkHelpers } from "./public/subagents.js";
import { nowIso, SCHEMA } from "./files.mjs";
import { TASK_LINE_RE } from "./scan.mjs";
/* ----------------------------------------------------------- patch merge */
const APPEND_KEYS = new Set(["thread"]);
export function isPlainObject(v) {
return v !== null && typeof v === "object" && !Array.isArray(v);
}
// Reject prototype-pollution attempts before they reach the merge.
function guard(obj, where) {
if (isPlainObject(obj) && Object.prototype.hasOwnProperty.call(obj, "__proto__")) {
throw new Error(`"__proto__" is not a valid key (in ${where})`);
}
return obj;
}
function mergeOne(target, patch, where) {
const out = { ...(target || {}) };
for (const [k, v] of Object.entries(guard(patch, where))) {
if (v === null) delete out[k];
else if (APPEND_KEYS.has(k) && Array.isArray(v)) out[k] = [...(out[k] || []), ...v];
else out[k] = v;
}
return out;
}
// Merge a keyed collection: a known id merges one level, an unknown id appends.
// Named fields are replaced whole; thread appends.
function mergeKeyed(current, patchList, idKey, defaults, where) {
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
for (const entry of patchList) {
guard(entry, where);
const id = entry[idKey];
if (!id) throw new Error(`every ${where} entry needs "${idKey}"`);
const i = out.findIndex((x) => x[idKey] === id);
if (entry._delete) {
if (i !== -1) out.splice(i, 1);
} else if (i === -1) out.push(mergeOne({ ...defaults, [idKey]: id }, entry, where));
else out[i] = mergeOne(out[i], entry, where);
}
return out;
}
const ITEM_DEFAULTS = {
status: "open",
required: true,
allowOther: true,
options: [],
thread: [],
};
// The question a card asks. If a patch rewrites any of these on a known id, it
// is a new question wearing an old id.
const QUESTION_FIELDS = ["kind", "title", "body", "options", "steps", "rows", "summary", "doc", "verdicts"];
/**
* Merge item patches by id, and keep a reused id from inheriting the person's
* old answer. `submitted` is the server's record of what they sent to the
* PREVIOUS question. When a patch changes what an item asks and doesn't itself
* settle it, that record (and any stale `answer`) is dropped, so the page shows
* the new question as open instead of "Sent, waiting for Plan2Code" forever.
*/
function dropStaleSubmissions(currentItems, before, patchList) {
const merged = mergeKeyed(currentItems, patchList, "id", ITEM_DEFAULTS, "items");
for (const entry of patchList) {
const prev = (before || []).find((x) => x.id === entry.id);
if (!prev || (prev.submitted === undefined && prev.answer === undefined)) continue;
const rewritten = QUESTION_FIELDS.some(
(f) => f in entry && JSON.stringify(entry[f]) !== JSON.stringify(prev[f]),
);
const settles = entry.status === "answered" || entry.status === "skipped" || "answer" in entry;
// A settled question edited in place (a typo in its body) stays settled; only an
// explicit reopen turns it into a new question.
const wasSettled = prev.status === "answered" || prev.status === "skipped";
// A different kind is never a typo fix: a multi turned confirm is another question.
const kindChanged = "kind" in entry && entry.kind !== prev.kind;
const reopens = entry.status === "open" || entry.status === "reopened" || kindChanged;
// An explicit reopen counts as asking again even with the question's
// words unchanged (the notes reopen with a status and a thread reply):
// the last send stops being in flight, and its note moves to the thread.
if ((!rewritten && !reopens) || settles || (wasSettled && !reopens)) continue;
const item = merged.find((x) => x.id === entry.id);
if (wasSettled && !("status" in entry)) item.status = "open";
// What they wrote with that answer ("I want changes: rename tally") is the
// context for the question being asked again, so it moves into the thread
// rather than leaving with the record.
const said = prev.submitted && typeof prev.submitted.text === "string" ? prev.submitted.text.trim() : "";
const thread = Array.isArray(item.thread) ? item.thread : [];
if (said && !thread.some((m) => m && m.who === "user" && String(m.text || "").trim() === said)) {
item.thread = [...thread.filter((m) => !(m && m.who === "agent" && m.at === undefined)), { who: "user", text: said, at: prev.submitted.at }, ...thread.filter((m) => m && m.who === "agent" && m.at === undefined)];
}
if (!("submitted" in entry)) delete item.submitted;
delete item.answer;
}
return merged;
}
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
// borrow the shape of the replies and doc blocks they also write, so `from` /
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
// at all is refused. The person's own notes are recorded by the server when
// they send, so an agent that echoes one back is not shown it twice.
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
function normalizeThreads(patchList, currentItems) {
return patchList.map((entry) => {
if (!isPlainObject(entry) || entry.thread == null) return entry;
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
const said = new Set(
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
);
const thread = [];
for (const m of entry.thread) {
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
guard(m, "thread");
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
if (!key) {
throw new Error(
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
);
}
const { from, role, md, body, content, ...rest } = m;
const who = (m.who || from || role) === "user" ? "user" : "agent";
const text = m[key];
if (who === "user" && said.has(text.trim())) continue;
thread.push({ ...rest, who, text });
}
return { ...entry, thread };
});
}
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
// state keeps its text. Blocks left out of the patch stay as they are.
function mergeDocs(current, patchList) {
// A doc's version only moves forward. One going back is a stale or copied
// payload (last phase's progress script, say), and the page would quietly
// show the old content under the new run's name.
for (const entry of patchList) {
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
const prev = (current || []).find((d) => d && d.id === entry.id);
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
throw new Error(
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
"Versions only go up: bump it, and check the payload is the current one."
);
}
}
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
for (const entry of patchList) {
if (!Array.isArray(entry.blocks)) continue;
const doc = merged.find((d) => d.id === entry.id);
if (!doc) continue;
const prev = (current || []).find((d) => d.id === entry.id);
doc.blocks = mergeKeyed(prev?.blocks, entry.blocks, "id", {}, "blocks");
// A known doc whose content moved, sent with no version, is the next
// version: the agent no longer has to track what the page holds, and a
// repost of unchanged content is not a new version.
if (prev && typeof entry.version !== "number" && typeof prev.version === "number") {
const text = (blocks) => JSON.stringify((blocks || []).map((b) => [b.id, b.md, b.state, b.image, b.alt]));
if (text(prev.blocks) !== text(doc.blocks)) doc.version = prev.version + 1;
}
}
return merged;
}
/**
* `settle` in a patch: the cards the person just answered, marked answered
* with what they sent as the answer. `true` takes every open card from the
* latest send (one send stamps every card it carries with the same `at`); a
* list names the cards. An item the same patch settles itself keeps the
* agent's own answer: settle only fills in what the patch left out.
*/
function settleItems(items, settle, patchItems, collected) {
if (settle === undefined || settle === false) return items;
if (settle !== true && !(Array.isArray(settle) && settle.every((id) => typeof id === "string"))) {
throw new Error('"settle" must be true or a list of item ids');
}
const sent = (items || []).filter((i) => i && i.submitted && typeof i.submitted === "object");
let ids;
if (settle === true && collected && Array.isArray(collected.ids)) {
// The send `wait` last handed over (state.collected, written as it was
// collected): a later send the person made meanwhile is not the agent's yet.
ids = sent.filter((i) => isOpen(i) && collected.ids.includes(i.id)).map((i) => i.id);
} else if (settle === true) {
const latest = sent.filter(isOpen).map((i) => String(i.submitted.at || "")).sort().pop();
ids = sent.filter((i) => isOpen(i) && String(i.submitted.at || "") === latest).map((i) => i.id);
} else {
for (const id of settle) {
// The same patch reopening it has already let go of what was sent; the
// reopen wins below, so naming it is not an error.
const reopening = (patchItems || []).some((e) => e && e.id === id && (e.status === "open" || e.status === "reopened"));
if (!reopening && !sent.some((i) => i.id === id)) throw new Error(`settle: "${id}" has nothing sent to settle`);
}
ids = settle;
}
const own = new Map((patchItems || []).filter(isPlainObject).map((e) => [e.id, e]));
return items.map((item) => {
if (!ids.includes(item.id)) return item;
const entry = own.get(item.id) || {};
// The same patch reopening it (a `changes` verdict answered by a reworked
// report) means it is not settled: no answer is recorded over the reopen.
if (entry.status === "open" || entry.status === "reopened") return item;
const { at, kind, ...answer } = item.submitted;
return {
...item,
// A "Skip this one" send settles as skipped, not as an answer.
status: "status" in entry ? item.status : answer.skipped === true ? "skipped" : "answered",
...("answer" in entry ? {} : { answer }),
};
});
}
// A question the patch puts in front of the person: new, or reopened.
function asksSomething(patchItems, before) {
return (patchItems || []).some((e) => {
if (!isPlainObject(e) || e._delete || e.kind === "notice") return false;
const prev = (before || []).find((x) => x && x.id === e.id);
if (!prev) return e.kind !== undefined && (e.status === undefined || e.status === "open");
return e.status === "reopened" || (e.status === "open" && !isOpen(prev));
});
}
/**
* The agent block after a patch, with the rule kept here rather than in every
* prompt: a patch that asks a question and says nothing of the status hands
* the turn over (a question stops the work). `quietMinutes` stays put: the
* page only counts it while working, and a build that asked a question goes
* back to the same long tasks once it is answered.
*/
function settleAgent(next, patch, before) {
const said = isPlainObject(patch.agent) ? patch.agent : null;
const saidStatus = said && "status" in said;
// A finish ends the working stretch too (nothing may still be running at
// one): a pause posted without a wait would otherwise sit at "working".
const finishes = isPlainObject(patch.finish);
if (!saidStatus && (finishes || asksSomething(patch.items, before.items))) {
next.agent = { ...(next.agent || {}), status: "waiting" };
}
return next;
}
/**
* Doc blocks that name a file get their `md` from disk: a build's phase file
* re-posted after every task was the biggest thing an agent typed, and every
* word of it was already on disk. `{ "id": "body", "file": "specs/x/phase-3.md" }`
* reads the file; `"select": "tasks"` keeps only its task checkbox lines; a doc
* with `"refresh": true` re-reads every file block it already has. Paths are
* relative to the worktree and must stay inside it. Runs in the CLI before
* the merge, so applyPatch itself never touches the disk.
*/
export const DOC_FILE_MAX = 512 * 1024;
export function resolveDocFiles(patch, state, worktree) {
if (!isPlainObject(patch) || !Array.isArray(patch.docs)) return patch;
const root = path.resolve(worktree || state.worktree || process.cwd());
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
const read = (file, select, docId) => {
if (typeof file !== "string" || !file.trim()) throw new Error(`doc "${docId}": a block's "file" must be a path`);
const abs = path.resolve(root, file);
let real;
try {
real = fs.realpathSync.native(abs);
} catch {
throw new Error(`doc "${docId}": no file at ${file}`);
}
const rootReal = (() => {
try {
return fs.realpathSync.native(root);
} catch {
return root;
}
})();
// path.relative, not a prefix test: a worktree at a drive root ends in a
// separator already, and win32's relative() folds case itself.
const rel = path.relative(fold(rootReal), fold(real));
if (rel.startsWith("..") || path.isAbsolute(rel)) throw new Error(`doc "${docId}": ${file} is outside the project`);
const stat = fs.statSync(real);
if (!stat.isFile()) throw new Error(`doc "${docId}": ${file} is not a file`);
if (stat.size > DOC_FILE_MAX) throw new Error(`doc "${docId}": ${file} is larger than ${DOC_FILE_MAX / 1024} KB`);
const text = fs.readFileSync(real, "utf8").replace(/\r\n/g, "\n");
if (select === undefined) return text;
if (select !== "tasks") throw new Error(`doc "${docId}": "select" only takes "tasks"`);
const tasks = text.split("\n").filter((l) => TASK_LINE_RE.test(l)).map((l) => l.trim());
if (!tasks.length) throw new Error(`doc "${docId}": ${file} has no task lines to select`);
return tasks.join("\n");
};
const docs = patch.docs.map((entry) => {
if (!isPlainObject(entry)) return entry;
const { refresh, ...rest } = entry;
let blocks = Array.isArray(rest.blocks) ? rest.blocks : undefined;
if (refresh === true) {
const prev = (state.docs || []).find((d) => d && d.id === entry.id);
const named = new Set((blocks || []).map((b) => b && b.id));
const again = ((prev && prev.blocks) || [])
.filter((b) => b && typeof b.file === "string" && !named.has(b.id))
.map((b) => ({ id: b.id, file: b.file, ...(b.select ? { select: b.select } : {}) }));
if (!again.length && !blocks) throw new Error(`doc "${entry.id}": "refresh" found no file blocks to re-read`);
blocks = [...(blocks || []), ...again];
} else if (refresh !== undefined) throw new Error(`doc "${entry.id}": "refresh" must be true`);
if (!blocks) return rest;
const prevBlocks = (state.docs || []).find((d) => d && d.id === entry.id)?.blocks || [];
return {
...rest,
blocks: blocks.map((b) => {
if (!isPlainObject(b)) return b;
const prevBlock = prevBlocks.find((x) => x && x.id === b.id);
if (b.file === undefined || b.file === null) {
// Typed text over a block that was a file: it stops being one, so a
// later refresh cannot overwrite it and the prose scan sees it.
return "md" in b && prevBlock && typeof prevBlock.file === "string" ? { ...b, file: null, select: null } : b;
}
// A file named again without `select` is the whole file, now and on
// every refresh: an older select must not linger in the merge.
const select = "select" in b ? b.select : null;
return { state: prevBlock?.state || "settled", ...b, select, md: read(b.file, select ?? undefined, entry.id) };
}),
};
});
return { ...patch, docs };
}
/**
* Image blocks: `{ "id", "image": "shots/run.png", "alt": "..." }` shows a
* screenshot the agent saved under the session's `shots/` folder (Show me it
* working). The path resolves against the session folder and must land, after
* `realpath`, directly inside `<session>/shots/` under a plain name, so the page
* can only ever be pointed at the agent's own pictures. The bytes decide the
* type, as checkDocument() does for documents: a text file renamed `.png` is
* refused. Stored session-relative; an image block never carries `md` or `file`.
* Runs in the CLI beside resolveDocFiles(), so applyPatch never touches the disk.
*/
export const SHOTS_DIR_NAME = "shots";
export const SHOT_MAX = 5 * 1024 * 1024;
export const SHOT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}\.(png|jpe?g|webp)$/i;
// What an image's first bytes say it is ("png", "jpeg", "webp"), or null.
export function shotType(buf) {
if (buf.length >= 8 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return "png";
if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return "jpeg";
if (buf.length >= 12 && buf.toString("ascii", 0, 4) === "RIFF" && buf.toString("ascii", 8, 12) === "WEBP") return "webp";
return null;
}
export function resolveDocImages(patch, state, dir) {
if (!isPlainObject(patch) || !Array.isArray(patch.docs)) return patch;
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
const shotsDir = path.join(path.resolve(dir), SHOTS_DIR_NAME);
const check = (image, docId) => {
if (typeof image !== "string" || !image.trim()) throw new Error(`doc "${docId}": an image block's "image" must be a path`);
const where = `doc "${docId}": image ${image}`;
let real;
try {
real = fs.realpathSync.native(path.resolve(dir, image));
} catch {
throw new Error(`${where} does not exist. Save it under the session's ${SHOTS_DIR_NAME}/ folder first.`);
}
let realShots;
try {
realShots = fs.realpathSync.native(shotsDir);
} catch {
realShots = shotsDir;
}
const name = path.basename(real);
if (fold(path.dirname(real)) !== fold(realShots)) {
throw new Error(`${where} is outside the session's ${SHOTS_DIR_NAME}/ folder (${shotsDir}); only pictures saved there can be shown.`);
}
if (!SHOT_NAME.test(name)) throw new Error(`${where}: name it with letters, digits, dots, dashes or underscores, ending .png, .jpg, .jpeg or .webp`);
const stat = fs.statSync(real);
if (!stat.isFile()) throw new Error(`${where} is not a file`);
if (stat.size > SHOT_MAX) throw new Error(`${where} is larger than ${SHOT_MAX / 1024 / 1024} MB`);
const ext = path.extname(name).slice(1).toLowerCase();
const want = ext === "jpg" ? "jpeg" : ext;
if (shotType(fs.readFileSync(real)) !== want) throw new Error(`${where} is not a ${want.toUpperCase()} image (its bytes say otherwise)`);
return `${SHOTS_DIR_NAME}/${name}`;
};
const docs = patch.docs.map((entry) => {
if (!isPlainObject(entry) || !Array.isArray(entry.blocks)) return entry;
const prevBlocks = (state.docs || []).find((d) => d && d.id === entry.id)?.blocks || [];
return {
...entry,
blocks: entry.blocks.map((b) => {
if (!isPlainObject(b)) return b;
const prevBlock = prevBlocks.find((x) => x && x.id === b.id);
if (b.image === undefined || b.image === null) {
// Text or a file over what was an image: it stops being one.
return ("md" in b || "file" in b) && prevBlock && typeof prevBlock.image === "string" ? { ...b, image: null, alt: null } : b;
}
if (("md" in b && b.md != null) || ("file" in b && b.file != null)) {
throw new Error(`doc "${entry.id}": block "${b.id}" is an image; it cannot also carry "md" or "file"`);
}
if (b.alt != null && typeof b.alt !== "string") throw new Error(`doc "${entry.id}": block "${b.id}" "alt" must be text`);
return { state: prevBlock?.state || "settled", ...b, image: check(b.image, entry.id), md: null, file: null };
}),
};
});
return { ...patch, docs };
}
/**
* Apply an agent patch to the session state.
*
* Scalars replace, `null` deletes, `agent`/`headline` merge one level,
* `items`/`topics`/`docs` merge by id, and so do a doc's `blocks`. The agent
* sends only what changed: a whole-file rewrite would put the entire state
* back into the agent's context on every turn, and the state grows with the
* session.
*/
export function applyPatch(state, patch) {
guard(patch, "patch");
patch = liftActivity(patch);
const { settle, ...rest } = patch;
patch = rest;
const next = { ...state };
for (const [k, v] of Object.entries(patch)) {
if (v === null) {
delete next[k];
continue;
}
switch (k) {
case "agent":
case "headline":
next[k] = mergeOne(next[k], v, k);
break;
case "items":
if (!Array.isArray(v)) throw new Error('"items" must be an array');
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
break;
case "topics":
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
break;
case "helpers":
// The agent's report of its helpers, for the page's Subagents tab.
// Only `post` writes it; the server's /submit never touches it.
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
// A real helper report supersedes the working-alone marker, whether it
// arrives after one or beside one.
if (next.helpers.some((h) => isPlainObject(h) && h.alone !== true))
next.helpers = next.helpers.filter((h) => !(isPlainObject(h) && h.alone === true));
break;
case "docs":
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
next.docs = mergeDocs(next.docs, v);
break;
case "chat": {
// The agent's side of the Quick question chat. The person's side is
// the inbox, which only the server writes; nothing else lives here.
if (!isPlainObject(v)) throw new Error('"chat" must be an object');
guard(v, "chat");
const extra = Object.keys(v).filter((key) => key !== "replies");
if (extra.length) throw new Error(`"chat" only takes "replies" (not ${extra.map((key) => `"${key}"`).join(", ")})`);
const chat = { ...(next.chat || {}) };
if (v.replies != null) {
if (!Array.isArray(v.replies)) throw new Error('"chat.replies" must be an array');
// A reply with no id is named for the message it answers (`r<seq>`),
// so a repeat delivery re-posted the same way replaces, never doubles.
const named = v.replies.map((r) =>
isPlainObject(r) && (r.id === undefined || r.id === "") && Number.isInteger(r.re) ? { ...r, id: `r${r.re}` } : r,
);
chat.replies = mergeKeyed(chat.replies, named, "id", {}, "chat.replies");
}
next.chat = chat;
break;
}
default:
next[k] = v;
}
}
if (settle !== undefined) next.items = settleItems(next.items || [], settle, patch.items, state.collected);
return stampTimes(state, settleAgent(next, patch, state));
}
// `activity` belongs under `agent`, which is the only place the page reads it.
// Sent at the top level it would be stored where nothing looks, and the page
// would sit on its starting screen while the skill works.
function liftActivity(patch) {
if (!Object.prototype.hasOwnProperty.call(patch, "activity")) return patch;
const { activity, ...rest } = patch;
if (rest.agent === null) return rest;
const agent = isPlainObject(rest.agent) ? rest.agent : {};
return { ...rest, agent: "activity" in agent ? agent : { ...agent, activity } };
}
// The agent never writes a timestamp. Models do not reliably know the time,
// and a wrong `since` makes the page's elapsed counters nonsense.
function stampTimes(before, next) {
const now = nowIso();
if (next.agent) {
// A status change starts its own clock: `since` merged along from the
// last status would date a fresh working turn to when the session opened.
const changed = !before.agent || before.agent.status !== next.agent.status;
if (changed) next.agent = { ...next.agent, since: now };
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
}
if (Array.isArray(next.items)) {
for (const entry of next.items) {
if (Array.isArray(entry.thread)) {
for (const m of entry.thread) if (!m.at) m.at = now;
}
}
}
if (Array.isArray(next.docs)) {
for (const d of next.docs) {
const prev = (before.docs || []).find((x) => x.id === d.id);
if (!prev || prev.version !== d.version) d.at = d.at || now;
}
}
next.updatedAt = now;
return next;
}
/* --------------------------------------------------------- house rules */
export const ITEM_KINDS = new Set([
"choice",
"multi",
"text",
"confirm",
"recap",
"review",
"checklist",
"menu",
"list",
"notice",
]);
// grilling.md keeps an explicit do-not-say list: this bookkeeping vocabulary is
// internal and must never reach the human. In the terminal that is a prompt rule
// the model can drift from. Routing through a server makes it mechanical.
const JARGON = [
/\bgrill(ing|ed)?\b/i,
/\bfrontier\b/i,
/\bfog\b/i,
/\bHITL\b/,
/\bAFK\b/,
/\bdurable\b/i,
/Locked:/,
/Blocked by:/,
/\bState:\s/,
];
// The loop parses these out of agent output; pathfinder forbids them under specs/.
// The other copy is LOOP_TOKENS in src/skill-scripts/common.mjs: the console is
// not a skill script and cannot import it, so keep the two in step.
const FORBIDDEN_TOKENS =
/\b(TASK_COMPLETE|PHASE_COMPLETE|ALL_TASKS_COMPLETE|IMPLEMENTATION_COMPLETE|SPEC_COMPLETE|WORK_COMPLETE)\b/;
// plan2code-metrics scrapes confidence with patterns that do NOT require a
// percent sign, so a bare "Requirements 22" in a rendered doc can poison a run's
// metrics. Keep those four words away from bare numbers. The skill scripts'
// copy is SCRAPE in src/skill-scripts/common.mjs; keep the two in step.
const METRICS_BAIT = /\b(Requirements?|Feasibility|Integration|Risk)[:\s|]+\d{1,2}\b/;
// The marker and metrics-bait scan on its own, for agent text that never
// reaches state.json (a post's `run` / `folderIssue`). Problems as sentences.
export function proseProblems(prose, subject = "text") {
const problems = [];
if (FORBIDDEN_TOKENS.test(prose)) {
problems.push(`${subject} contains a loop completion marker (${prose.match(FORBIDDEN_TOKENS)[0]}); the loop scans for these`);
}
if (METRICS_BAIT.test(prose)) {
problems.push(
`${subject} contains "${prose.match(METRICS_BAIT)[0]}" — the metrics collector scrapes that pattern. ` +
`Hyphenate it (Requirements-clarity 22/25) or reword.`
);
}
return problems;
}
export const MAX_OPEN_REQUIRED = 3;
/**
* Validate a merged state before it is written.
*
* Returns an array of human-readable problems. An empty array means the patch
* is good. These checks turn four prose rules into mechanical ones.
*/
export function validate(state) {
const problems = [];
if (!Array.isArray(state.items)) return ['"items" must be an array'];
const ids = new Set();
for (const item of state.items) {
if (!item.id) problems.push("every item needs an id");
if (ids.has(item.id)) problems.push(`duplicate item id "${item.id}"`);
ids.add(item.id);
if (!ITEM_KINDS.has(item.kind)) {
problems.push(`item "${item.id}" has unknown kind "${item.kind}" (one of: ${[...ITEM_KINDS].join(", ")})`);
}
if (typeof item.title !== "string" || !item.title.trim()) {
problems.push(`item "${item.id}" needs a plain-English title`);
} else {
for (const re of JARGON) {
if (re.test(item.title)) {
problems.push(
`item "${item.id}" title contains internal vocabulary (${re.source}). Titles are read by people who have never seen this workflow.`
);
break;
}
}
}
if ((item.kind === "choice" || item.kind === "multi") && !Array.isArray(item.options)) {
problems.push(`item "${item.id}" is a ${item.kind} and needs "options"`);
}
if ((item.kind === "choice" || item.kind === "multi") && Array.isArray(item.options)) {
for (const o of item.options) {
if (!o || typeof o.k !== "string" || !o.k.trim()) {
problems.push(`item "${item.id}" has an option with no "k" (its key, like "A")`);
} else if (typeof o.text !== "string" || !o.text.trim()) {
problems.push(
`item "${item.id}" option "${o.k}" needs "text" (the label) and optionally "detail". Options use "text"/"detail", not "label"/"desc".`
);
}
}
}
if (item.verdicts != null) {
if (!Array.isArray(item.verdicts) || !item.verdicts.length) {
problems.push(`item "${item.id}" "verdicts" must be a non-empty array of { id, label }`);
} else {
for (const v of item.verdicts) {
if (!v || typeof v.id !== "string" || !v.id.trim()) {
problems.push(`item "${item.id}" has a verdict with no "id"`);
} else if (typeof v.label !== "string" || !v.label.trim()) {
problems.push(
`item "${item.id}" verdict "${v.id}" needs a "label" (the button text). Verdicts use "label", not "text".`
);
}
}
}
}
if (item.templates != null && (item.kind !== "text" || item.templates !== "idea")) {
problems.push(`item "${item.id}" has "templates": only a text item can carry it, and its only value is "idea".`);
}
// The page compiles it as the person types, and a pattern that does not
// compile throws there, on every keystroke, with nothing on screen to say why.
if (item.pattern != null) {
if (typeof item.pattern !== "string") {
problems.push(`item "${item.id}" "pattern" must be a string holding a JavaScript regular expression`);
} else {
try {
new RegExp(item.pattern);
} catch (e) {
problems.push(`item "${item.id}" "pattern" is not a valid JavaScript regular expression: ${e.message}`);
}
}
}
const recs = (item.options || []).filter((o) => o.recommended);
if (recs.length > 1) problems.push(`item "${item.id}" marks ${recs.length} options recommended; at most one`);
}
// The dashboard's page is the menu: a card posted there is drawn nowhere,
// yet counts as open (and keeps Stop live for a question nobody can see).
if (state.workflow === "dashboard" && state.items.some((i) => isOpen(i))) {
problems.push(
'The dashboard draws no question cards: post its "menu" (and "agent"), and launch the skill a question belongs to.'
);
}
// A notice asks nothing (the git board keeps its result line open all
// session), so it never takes one of the three slots.
const openRequired = state.items.filter((i) => i.required !== false && i.kind !== "notice" && isOpen(i));
if (openRequired.length > MAX_OPEN_REQUIRED) {
problems.push(
`${openRequired.length} questions are open at once. The cap is ${MAX_OPEN_REQUIRED} ` +
`(the ceiling is the person's attention, not the screen's). ` +
`Send the rest after these are answered, or mark some "required": false.`
);
}
// The session's own ending. Absent for every session that is still running,
// so only its shape is checked, never its presence. The command is optional:
// a finish with no command is a finished session with nothing left to run,
// and the page points at the dashboard instead of a next step.
const fin = state.finish;
if (fin != null) {
if (typeof fin !== "object" || Array.isArray(fin)) {
problems.push('"finish" must be an object');
} else {
if (typeof fin.headline !== "string" || !fin.headline.trim()) {
problems.push('"finish" needs a plain-English "headline" saying what just happened');
}
if (fin.command != null && (typeof fin.command !== "string" || !fin.command.trim())) {
problems.push('"finish.command" must be a non-empty string, or left out when there is nothing to run');
} else if (fin.command != null && (fin.command.includes("<") || fin.command.includes(">"))) {
// A rendered command is copied and run verbatim. A leftover
// placeholder reaches someone who has no way to know what fills it.
problems.push(`"finish.command" still has a placeholder in it ("${fin.command}"). Fill it in.`);
}
if (fin.console != null && typeof fin.console !== "boolean") {
problems.push('"finish.console" must be true or false (or left out, to follow the command)');
}
if (fin.dashboard != null && typeof fin.dashboard !== "boolean") {
problems.push('"finish.dashboard" must be true or false (or left out: no dashboard button)');
}
if (fin.commit != null && typeof fin.commit !== "boolean") {
problems.push('"finish.commit" must be true or false (or left out: no commit button)');
}
// The review offer on a finished build: true, or an object carrying the
// button's heading. The heading is read by the person, so it faces the
// same vocabulary check as a title.
if (fin.review != null && typeof fin.review !== "boolean") {
if (typeof fin.review !== "object" || Array.isArray(fin.review)) {
problems.push('"finish.review" must be true, false, or { "label": "..." }');
} else if (fin.review.label != null) {
if (typeof fin.review.label !== "string") {
problems.push('"finish.review.label" must be a string');
} else {
const hit = JARGON.find((re) => re.test(fin.review.label));
if (hit) problems.push(`"finish.review.label" contains internal vocabulary (${hit.source})`);
}
}
}
for (const re of JARGON) {
if (typeof fin.headline === "string" && re.test(fin.headline)) {
problems.push(`"finish.headline" contains internal vocabulary (${re.source})`);
break;
}
}
}
}
// How long a silence is normal while the agent works (a build task). Bounded,
// because the page stops calling a quiet agent stuck for this long, and a
// huge number would hide a session that really has died.
const quiet = state.agent && state.agent.quietMinutes;
if (quiet != null && (typeof quiet !== "number" || !(quiet > 0) || quiet > 60)) {
problems.push('"agent.quietMinutes" must be a number of minutes between 1 and 60 (or null to clear it)');
}
// The page reads exactly two: anything else would leave it guessing whose
// turn it is.
if (state.agent && state.agent.status != null && !["working", "waiting"].includes(state.agent.status)) {
problems.push(`"agent.status" must be "working" or "waiting" (not "${state.agent.status}")`);
}
if (state.agent && state.agent.activity != null && typeof state.agent.activity !== "string") {
problems.push('"agent.activity" must be a short sentence saying what you are doing');
}
// Open gates only: an approval already given (last phase's sign-off) is a
// record, and must not stop the next phase from asking for its own.
const gates = state.items.filter((i) => i.gate && i.gate.authoritative && isOpen(i));
if (gates.length > 1) {
problems.push(
`${gates.length} authoritative approval gates are open (${gates
.map((g) => g.id)
.join(", ")}). Only one workflow may own sign-off at a time.`
);
}
// An image block's alt text is its caption, read by the same newcomers a
// title is.
for (const d of state.docs || []) {
for (const b of (isPlainObject(d) && Array.isArray(d.blocks) ? d.blocks : [])) {
if (!isPlainObject(b) || typeof b.image !== "string" || typeof b.alt !== "string") continue;
const hit = JARGON.find((re) => re.test(b.alt));
if (hit) problems.push(`doc "${d.id}" image "${b.id}" alt text contains internal vocabulary (${hit.source})`);
}
}
// Scan what the AGENT wrote, never what the person typed. `submitted` is the
// server's record of an answer someone pressed Send on; if their own words
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
// would be rejected and the session would wedge with no way out.
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
...rest,
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
}));
// A doc block read from a file (`file`) is the file's own words, already on
// disk: the agent cannot reword it, and refusing it would wedge every post
// that refreshes it. Only what the agent typed is scanned.
const typedDocs = (state.docs || []).map((d) =>
isPlainObject(d) && Array.isArray(d.blocks) ? { ...d, blocks: d.blocks.filter((b) => !(isPlainObject(b) && typeof b.file === "string")) } : d
);
const prose =
JSON.stringify(authored) +
JSON.stringify(typedDocs) +
JSON.stringify(state.finish || {}) +
JSON.stringify(state.menu || {});
problems.push(...proseProblems(prose));
// The agent's report of its helpers: the shape the page draws from
// (subagents.js), then the same prose scan as everything else it writes.
if (state.helpers != null) {
problems.push(...checkHelpers(state.helpers));
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
if (!isPlainObject(helper)) continue;
for (const field of ["title", "ask", "result"]) {
if (typeof helper[field] === "string") {
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
}
}
}
}
// A finish ends the session, and a helper still shown as running would sit
// on the Subagents tab, spinning, after everything is over.
if (state.finish != null && Array.isArray(state.helpers)) {
const running = state.helpers.filter((h) => isPlainObject(h) && h.state === "running").map((h) => `"${h.id}"`);
if (running.length) {
problems.push(`"finish" while helper ${running.join(", ")} still shows as running: post each one as done or failed first, or in the same patch`);
}
}
return problems;
}
export function isOpen(item) {
return item.status === "open" || item.status === "reopened";
}
export function blankState({ sid, workflow, title, project, specDir }) {
return {
schema: SCHEMA,
sid,
workflow: workflow || "pathfinder",
title: title || "Session",
project,
specDir: specDir || "",
created: nowIso(),
phase: "collecting",
agent: { status: "working", since: nowIso() },
headline: { stage: "", cleared: 0, total: 0, confidence: "", note: "" },
topics: [],
items: [],
docs: [],
};
}
/**
* A resume that passes through the dashboard (a finished skill going back to
* it, or a launch from its menu), or into Git from any skill
* (Commit it now, Changelog's hand-off), is a new skill taking the page over, so it
* starts from a blank page: the last skill's questions, sections, docs,
* helpers, headline and ending are its record on disk, not the next skill's
* opening.
* Only the session's identity carries across. `workspace.json`,
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
* and the meter outlive every hop.
*/
export function switchWorkflow(state, { workflow, title, specDir }) {
return { ...blankState({ sid: state.sid, project: state.project, workflow, title, specDir }), created: state.created };
}
+93 -327
View File
@@ -10,6 +10,9 @@
// 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 { SPEC_STATES, stateFor } from "./spec-states.js";
/* ----------------------------------------------------- the sent answer */
/**
@@ -253,54 +256,18 @@ 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.
export const WORKFLOW_LABEL = {
dashboard: "Dashboard",
init: "Setting up",
"init-update": "Refreshing",
pathfinder: "Pathfinder",
plan: "Planning",
"revise-plan": "Revising the plan",
document: "Documenting",
implement: "Building",
"implement-review": "Building + review",
review: "Review",
"quick-task": "Quick task",
finalize: "Wrapping up",
handoff: "Handoff",
git: "Git",
changelog: "Changelog",
xray: "X-ray",
diagnose: "Diagnosing",
};
// 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 function workflowLabel(workflow) {
return WORKFLOW_LABEL[workflow] || workflow || "Session";
return labelFor(workflow) || workflow || "Session";
}
// The workflows that ship the console (install.js bundles it into every
// 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.
export const CONSOLE_WORKFLOWS = [
"/plan2code",
"/plan2code-init",
"/plan2code-init-update",
"/plan2code-0-pathfinder",
"/plan2code-quick-task",
"/plan2code-1-plan",
"/plan2code-1b-revise-plan",
"/plan2code-2-document",
"/plan2code-3-implement",
"/plan2code-3-implement-review",
"/plan2code-review",
"/plan2code-4-finalize",
"/plan2code-handoff",
"/plan2code-git",
"/plan2code-changelog",
"/plan2code-xray",
"/plan2code-diagnose",
];
// something that is not there. Derived from skills.js: every entry is one.
export const CONSOLE_WORKFLOWS = 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
@@ -567,192 +534,15 @@ export const CATALOG_GROUPS = [
// `spec: true` marks the cards that take a spec folder as their target: when
// the picker has a spec selected, its `dir` rides along in the `__launch`
// action so the launched skill knows which spec it was picked for.
export const SKILL_CATALOG = [
{
skill: "plan2code-init",
command: "/plan2code-init",
workflow: "init",
group: "setup",
chip: "Set up",
title: "Set up this project",
blurb: "Reads your project and writes AGENTS.md, the guide every later step works from.",
about:
"Plan2Code reads the whole project: how it is organized, how it runs, and where the sharp edges are. Then it writes AGENTS.md, the guide every later step steers by. It asks a few questions as it goes, so nothing important gets guessed. Run this once per project, or again when the project has moved on.",
},
{
skill: "plan2code-init-update",
command: "/plan2code-init-update",
workflow: "init-update",
group: "setup",
chip: "Set up",
title: "Refresh AGENTS.md",
blurb: "Brings AGENTS.md and its notes up to date with what the project has learned lately.",
about:
"The project moved on since AGENTS.md was written: new commands, new habits, new gotchas. This re-reads the project, asks what changed, and folds it into AGENTS.md and the notes beside it. Cheaper than a fresh setup, and whatever is still right is kept.",
},
{
skill: "plan2code-0-pathfinder",
command: "/plan2code-0-pathfinder",
workflow: "pathfinder",
group: "pipeline",
chip: "Step 0",
spec: true,
title: "Pathfinder",
blurb: "A foggy idea becomes a clear list of decisions, settled one question at a time.",
about:
"You have a rough idea and a lot of unknowns. Pathfinder asks one question at a time: who it is for, what it must do, what could go wrong. Each answer is written down in a spec folder. It ends with a list of decisions clear enough to plan from, and nothing gets built yet.",
},
{
skill: "plan2code-1-plan",
command: "/plan2code-1-plan",
workflow: "plan",
group: "pipeline",
chip: "Step 1",
spec: true,
title: "Plan",
blurb: "Requirements, technical design and your approval: the shape of what gets built.",
about:
"Turns what you bring into a real plan: a finished Pathfinder map, a folder of design notes, or just the idea in your head. You get requirements, a technical design, a phase-by-phase breakdown, and a final version to approve before anything is built. This is where 'what are we building' becomes 'how it gets built'.",
},
{
skill: "plan2code-1b-revise-plan",
command: "/plan2code-1b-revise-plan",
workflow: "revise-plan",
group: "pipeline",
chip: "Step 1b",
spec: true,
title: "Revise the plan",
blurb: "Requirements changed mid-build? Adjust the plan without starting over.",
about:
"Requirements moved mid-build: a feature added, a rule dropped, a deadline pulled in. This adjusts the existing spec for the change, shows you what it affects, and only rewrites what actually has to move. The approved plan stays the plan.",
},
{
skill: "plan2code-2-document",
command: "/plan2code-2-document",
workflow: "document",
group: "pipeline",
chip: "Step 2",
spec: true,
title: "Document",
blurb: "The plan becomes a checklist of small tasks, grouped into phases, that a developer can just do.",
about:
"Writes the plan as numbered phase files. Each phase is a checklist of tasks small enough to just do, with the details a builder needs right there. This is the file the build step works from, and the thing a later session can pick up cold.",
},
{
skill: "plan2code-3-implement",
command: "/plan2code-3-implement",
workflow: "implement",
group: "pipeline",
chip: "Step 3",
spec: true,
title: "Implement",
blurb: "Builds the next phase, task by task, with a report and your sign-off at the end.",
about:
"Builds the next phase of the spec. Tasks get checked off one by one, with progress and the occasional decision landing on this page as it goes. It ends with a report of what was built and a sign-off card you approve before the phase counts as done.",
},
{
skill: "plan2code-3-implement-review",
command: "/plan2code-3-implement-review",
workflow: "implement-review",
group: "pipeline",
chip: "Step 3",
spec: true,
title: "Implement + review",
blurb: "One phase built, then a careful review of the changes, then your sign-off. All in one run.",
about:
"The same build as Implement, with a review folded in before sign-off. The phase is built, then a fresh pass hunts for problems in exactly what changed, you pick what gets fixed, and only then does the sign-off card arrive.",
},
{
skill: "plan2code-4-finalize",
command: "/plan2code-4-finalize",
workflow: "finalize",
group: "pipeline",
chip: "Step 4",
spec: true,
title: "Finalize",
blurb: "Checks the work, writes the summary, files the specs away and suggests the commit message.",
about:
"The closer. Checks every task against the spec, makes sure the build actually works, writes the summary into overview.md, updates the project docs, and suggests the commit message. Run it when the feature is done. It leaves the project tidy behind it.",
},
{
skill: "plan2code-quick-task",
command: "/plan2code-quick-task",
workflow: "quick-task",
group: "extra",
chip: "Utility",
title: "Quick task",
blurb: "Too small for the full process? A quick plan, then it just builds it.",
about:
"A fix, a tweak, a small feature. Not worth a spec folder. Describe it, confirm the one-line plan, and it builds it right there, with a report at the end. The fast lane for work the full process would over-plan.",
},
{
skill: "plan2code-review",
command: "/plan2code-review",
workflow: "review",
group: "extra",
chip: "Utility",
title: "Review",
blurb: "A second opinion on the changes. Problems ranked, and you pick what gets fixed.",
about:
"A fresh-eyes pass over what changed: bugs, gaps, and the things the builder was too close to see. Problems come back ranked with a suggestion each, you pick which ones get fixed, and it fixes them.",
},
{
skill: "plan2code-xray",
command: "/plan2code-xray",
workflow: "xray",
group: "extra",
chip: "Utility",
title: "Codebase X-ray",
blurb: "Explain how and why an area works, or find the rough spots worth fixing.",
about:
"Two ways into code you did not write. Explain an area: how it works, step by step, and why it is that way, citing the files and the commits and pull requests behind it. Or find the rough spots: files that always change together, thin layers, tangled boundaries and busy code with no tests, ranked with a concrete example each. You tick the ones worth fixing and they become a brief for Pathfinder or Plan. It never changes code.",
},
{
skill: "plan2code-diagnose",
command: "/plan2code-diagnose",
workflow: "diagnose",
group: "extra",
chip: "Utility",
title: "Diagnose a bug",
blurb: "Find a bug's cause and write it up, without fixing it.",
about:
"Something is broken and nobody knows why. Diagnose asks what goes wrong and how to see it, then builds a command that fails on the bug before it forms a theory. It narrows the cause down to a file and a function, says how sure it is, and sizes the fix. The write-up lands in a spec folder, and the dashboard then offers Quick Task to fix it, or Plan when the fix is big. It never changes code.",
},
{
skill: "plan2code-changelog",
command: "/plan2code-changelog",
workflow: "changelog",
group: "extra",
chip: "Utility",
title: "Changelog",
blurb: "Checks the CHANGELOG version against the main branch and suggests entries for what is new.",
about:
"Works out the right version from the default branch, then compares your branch with the latest CHANGELOG entry and suggests the entries it is missing. You edit them before anything is written, it keeps package.json in step, and it offers to commit the result in Git. If the newest version is not released or on another branch yet, it adds to that entry instead of starting a new one.",
},
{
skill: "plan2code-git",
command: "/plan2code-git",
workflow: "git",
group: "extra",
chip: "Utility",
title: "Git",
blurb: "Branches, pull, push and commits on one board that stays open while you work.",
about:
"Shows your branch, what is ahead or behind, and every local and remote branch. Switch, create, delete or clean up branches, pull (rebasing when they have split, with help on conflicts), push or publish, and commit with a clear message. It asks before every push, publish and delete, and never force-pushes.",
},
{
skill: "plan2code-handoff",
command: "/plan2code-handoff",
workflow: "handoff",
group: "extra",
chip: "Utility",
title: "Handoff",
blurb: "Pack the current session into a document a fresh session can pick up cold.",
about:
"Writes down everything a new session would need, as a single document: what was decided, what is done, what is left. Use it when a conversation got long, a machine changed, or tomorrow-you deserves the context today-you has.",
},
];
// 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) => ({
skill: s.skill,
command: s.command,
workflow: s.workflow,
...s.card,
}));
// 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.
@@ -764,74 +554,79 @@ export function workflowTitle(workflow) {
// Every skill gets its own Planny on the starting and waiting screens, drawn
// as a <template data-pose> in index.html. A skill that is a variant of
// another borrows its pose. Anything else (the dashboard) keeps the flight.
export const START_POSES = [
"init",
"pathfinder",
"plan",
"document",
"implement",
"finalize",
"quick-task",
"review",
"handoff",
"git",
"changelog",
"xray",
"diagnose",
];
const POSE_ALIASES = { "init-update": "init", "revise-plan": "plan", "implement-review": "implement" };
// Derived from skills.js: every pose an entry names, once.
export const START_POSES = [...new Set(SKILLS.map((s) => s.pose).filter(Boolean))];
export function startPose(workflow) {
const pose = POSE_ALIASES[workflow] || workflow;
return START_POSES.includes(pose) ? pose : null;
return skillFor(workflow)?.pose || null;
}
export function catalogEntry(skill) {
return SKILL_CATALOG.find((e) => e.skill === skill) || null;
const entry = skillByName(skill);
return entry && entry.card ? SKILL_CATALOG.find((e) => e.skill === entry.skill) : null;
}
/* ------------------------------------------- dashboard card availability */
// What the picker shows next to a spec's name — the pipeline position the
// server's scan worked out, in plain words.
export const SPEC_STATE_LABELS = {
diagnosed: "Bug diagnosed",
fixed: "Bug fixed",
exploring: "Exploring",
mapped: "Ready to plan",
planned: "Ready to document",
documented: "Ready to build",
building: "Building",
built: "Ready to finalize",
unrecognized: "Files on disk",
};
// server's scan worked out, in plain words. Derived from spec-states.js.
export const SPEC_STATE_LABELS = Object.fromEntries(Object.entries(SPEC_STATES).map(([name, s]) => [name, s.label]));
// The card each spec state exists to light up. Used as the fallback for the
// "Suggested" pill when the agent's menu payload names nothing.
const NEXT_FOR_STATE = {
diagnosed: "plan2code-quick-task",
exploring: "plan2code-0-pathfinder",
mapped: "plan2code-1-plan",
planned: "plan2code-2-document",
documented: "plan2code-3-implement",
building: "plan2code-3-implement",
built: "plan2code-4-finalize",
};
// "Suggested" pill when the agent's menu payload names nothing. Derived from
// spec-states.js: the states that have one.
const NEXT_FOR_STATE = Object.fromEntries(
Object.entries(SPEC_STATES)
.filter(([, s]) => s.next)
.map(([name, s]) => [name, s.next])
);
const ON = { on: true };
export const GIT_INIT_NOTE = "Not a git repository yet: it offers to start one";
export const pendingNote = (n) => `${n} file${n === 1 ? "" : "s"} to commit`;
const off = (reason) => ({ on: false, reason });
export const FIXED_REASON = "This bug is fixed. Delete it with the Delete button on its chip, or move it to specs--completed/.";
// Pathfinder's and Plan's reason on a fixed bug, kept on skills.js.
export { FIXED_REASON };
/**
* The spec the picker opens on: the most recently touched one that is still
* in play. A fixed bug is finished, so it is never the default; with nothing
* else on disk the picker opens on "start from scratch" (null).
* in play. A finished spec (a fixed bug) is never the default; with nothing
* else on disk the picker opens on "start from scratch" (null). `lookup` is
* stateFor unless a test hands in its own table.
*/
export function defaultSpec(specs) {
return (Array.isArray(specs) ? specs : []).find((s) => s && s.state !== "fixed") || null;
export function defaultSpec(specs, lookup = stateFor) {
return (Array.isArray(specs) ? specs : []).find((s) => s && !lookup(s.state)?.finished) || null;
}
/**
* The reassurance under "Starting up": a calm line at first, a pointer to the
* terminal once the start has taken longer than ninety seconds.
*/
export function startingHint(elapsedMs) {
return elapsedMs > 90000
? "Still getting ready. Your terminal has the play-by-play if you want to watch it there."
: "This page fills in by itself the moment Plan2Code has something for you. No need to touch anything.";
}
/**
* Whether the picker still shows the spec it opened on: `picked` is the
* selected spec (or null for "start from scratch"), `first` the default one.
* The agent's menu note describes that spec only, so another pick gets the
* neutral line.
*/
export function onInitialPick(first, picked) {
return first ? Boolean(picked && picked.dir === first.dir) : !picked;
}
/**
* Which line the dashboard shows under its title: "agent" (the note the agent
* posted), "looking" (the agent has not posted its menu yet and is working)
* or "neutral".
*/
export function dashNoteKind({ menu, hasMenu, onInitial, working }) {
if (menu && typeof menu.note === "string" && menu.note.trim() && onInitial) return "agent";
if (!hasMenu && working) return "looking";
return "neutral";
}
/**
@@ -845,61 +640,32 @@ export function defaultSpec(specs) {
*
* Returns { on, reason?, note?, next? } — `reason` is the one line a greyed card
* shows, `note` the one line a clickable card shows when there is something to
* know before launching it, `next` marks the state's natural step.
* know before launching it, `next` marks the state's natural step. `lookup` is
* stateFor unless a test hands in its own table.
*/
export function cardAvailability(entry, scan, sel) {
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);
if (!rule || !rule.states) return ON;
switch (entry.skill) {
case "plan2code-init":
return hasAgents ? off("AGENTS.md is already written. Refresh it instead.") : ON;
case "plan2code-init-update":
return hasAgents ? ON : off("Needs an AGENTS.md. Set the project up first.");
case "plan2code-quick-task":
// Always on; a diagnosed bug is the one spec it is the next step for.
return next ? { ...ON, next } : ON;
case "plan2code-review":
case "plan2code-handoff":
case "plan2code-changelog":
case "plan2code-xray":
case "plan2code-diagnose":
return ON;
case "plan2code-git":
// Never greyed: a clean tree still has branches to switch, pull and push.
if (scan && scan.isGit === false) return { on: true, note: GIT_INIT_NOTE };
if (scan && Number.isInteger(scan.pending) && scan.pending > 0) return { on: true, note: pendingNote(scan.pending) };
return ON;
case "plan2code-0-pathfinder":
if (!state || state === "exploring") return { ...ON, next };
if (state === "diagnosed") return off("The cause is found. Fix it in a quick task, or plan it.");
if (state === "fixed") return off(FIXED_REASON);
return off("This spec is already past the questions");
case "plan2code-1-plan":
if (state === "exploring") return off("Pathfinder is not finished with this spec yet");
if (state === "fixed") return off(FIXED_REASON);
if (state === "documented" || state === "building" || state === "built")
return off("The plan is written. Revise it instead if it moved.");
return { ...ON, next };
case "plan2code-1b-revise-plan":
if (state === "documented" || state === "building") return ON;
return off(state === "built" ? "The spec is fully built" : "Needs a spec that is already written up");
case "plan2code-2-document":
if (state === "planned") return { ...ON, next };
if (state === "documented" || state === "building" || state === "built")
return off("The phases are already written up");
return off("Needs a drafted plan first");
case "plan2code-3-implement":
case "plan2code-3-implement-review":
if (state === "documented" || state === "building") return { ...ON, next };
return off(state === "built" ? "All tasks are already done" : "Needs the phase checklists written up first");
case "plan2code-4-finalize":
if (state === "built") return { ...ON, next };
return off("Needs a spec that is fully built");
default:
return ON;
// The three cards whose rules read the scan rather than the spec.
if (entry.skill === "plan2code-init") return hasAgents ? off(rule.greyed.default) : ON;
if (entry.skill === "plan2code-init-update") return hasAgents ? ON : off(rule.greyed.default);
if (entry.skill === "plan2code-git") {
// Never greyed: a clean tree still has branches to switch, pull and push.
if (scan && scan.isGit === false) return { on: true, note: GIT_INIT_NOTE };
if (scan && Number.isInteger(scan.pending) && scan.pending > 0) return { on: true, note: pendingNote(scan.pending) };
return ON;
}
// Always on; a diagnosed bug is the one spec Quick Task is the next step for.
if (rule.states === "any") return next ? { ...ON, next } : ON;
// A state the table does not know is treated like files on disk.
const taken = !sel || !sel.state ? "none" : lookup(sel.state) ? sel.state : "unrecognized";
if (rule.states.includes(taken)) return rule.marksNext ? { ...ON, next } : ON;
return off(rule.greyed[taken] || (lookup(taken)?.finished && rule.greyed.finished) || rule.greyed.default);
}
/**
@@ -946,7 +712,7 @@ export function launchReply(entry, spec) {
/**
* Deleting a spec from the picker. The page only names the folder; the agent
* deletes it (`console.mjs delete-spec`, which runs lib.mjs's removeSpec() on
* deletes it (`console.mjs delete-spec`, which runs scan.mjs's removeSpec() on
* this same rule), because the console never writes into a project. A
* deletable dir is exactly `specs/<one name>`: no deeper path, no `.` or `..`,
* no dotfolder, no backslash, never specs--completed/.
@@ -996,10 +762,10 @@ export function handoffAge(written, now = Date.now()) {
return `${days} day${days === 1 ? "" : "s"} ago`;
}
// The line under a spec's name on its chip. A fixed bug's label already says
// "Bug fixed", so the scan's "bug fixed" detail would only repeat it.
// The line under a spec's name on its chip. A finished spec's label already
// says it ("Bug fixed"), so the scan's "bug fixed" detail would only repeat it.
export function chipDetail(spec) {
return spec.state === "fixed" ? "" : spec.detail || "";
return stateFor(spec.state)?.finished ? "" : spec.detail || "";
}
export function deleteSummary(spec) {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+202
View File
@@ -0,0 +1,202 @@
// Plan2Code Web Console - a document as the page shows it, and as a file: blocks, Markdown and HTML download; defines only.
//
// Shared by the documents tab and the finished screen, so neither imports the other.
import { el, md } from "./render.js";
// A block's content: its markdown, or for an image block (a screenshot the
// agent saved under the session's shots/ folder) a captioned picture.
export function blockBody(b) {
if (typeof b.image !== "string") return md(b.md, "md");
const fig = el("figure", "doc-figure");
const img = el("img", "doc-img");
img.src = "/shots/" + b.image.split("/").pop();
// The caption already says it: an alt repeating it is read twice, and shows
// twice in an export whose picture would not load.
img.alt = "";
img.loading = "lazy";
fig.appendChild(img);
if (b.alt) fig.appendChild(el("figcaption", null, b.alt));
return fig;
}
// Markdown rather than HTML: it is what the agent wrote, what the file under
// specs/ already holds, and what survives being pasted into Slack or a ticket.
export function downloadDoc(doc) {
// The file keeps what the page shows: the title, and which parts are still
// assumptions or drafts. Without the marks a half-finished document reads,
// once it leaves the page, as a set of decisions.
const mark = { assumed: "> **Assumed for now, still open.**\n\n", draft: "> **Draft.**\n\n" };
const blocks = (doc.blocks || []).map((b) => (mark[b.state] || "") + (typeof b.image === "string" ? b.alt || "" : b.md || ""));
const first = (doc.blocks || [])[0];
const titled = first && /^\s*#\s/.test(first.md || "");
const body = [titled || !doc.title ? null : `# ${doc.title}`, ...blocks].filter((x) => x != null).join("\n\n");
saveFile(`${docFileName(doc)}.md`, body, "text/markdown");
}
function docFileName(doc) {
const name = (doc.title || "document").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
return name || "document";
}
function saveFile(name, body, type) {
const url = URL.createObjectURL(new Blob([body], { type }));
const a = document.createElement("a");
a.href = url;
a.download = name;
document.body.appendChild(a);
a.click();
a.remove();
// Give the download a tick to start before the handle goes.
setTimeout(() => URL.revokeObjectURL(url), 30000);
}
// The page's own markdown styles, restated with the light palette baked in:
// the saved file has no app.css beside it and may be opened years from now,
// on any machine, so it carries everything it needs.
const DOC_HTML_CSS = `
:root { color-scheme: light; }
body { margin: 0; background: #f6f3ee; color: #1d1a17; font: 15.5px/1.6 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
main { max-width: 880px; margin: 0 auto; padding: 40px 28px 60px; background: #fff; min-height: 100vh; box-sizing: border-box; }
.doc-head { display: flex; gap: 12px; align-items: baseline; flex-wrap: wrap; margin-bottom: 16px; padding-bottom: 14px; border-bottom: 1px solid #e4ddd1; }
.doc-head h1 { font: 600 27px/1.2 "Iowan Old Style", Charter, Georgia, Cambria, serif; margin: 0; }
.doc-version, .doc-meta { font: 700 12px/1 ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace; color: #8f8779; }
.doc-note { color: #5d564d; margin: 0 0 16px; }
.block { border-left: 3px solid transparent; padding: 2px 0 2px 14px; margin: 0 0 4px; }
.block.assumed { border-left: 3px dashed #9a6a12; background: #fbf0d8; border-radius: 0 8px 8px 0; }
.block.draft { border-left-color: #cfc6b6; opacity: 0.72; }
.block.settled { border-left-color: #e4f0e8; }
.block-tag { font-size: 10.5px; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase; color: #9a6a12; display: block; margin-bottom: 4px; }
.md-h { font-family: "Iowan Old Style", Charter, Georgia, Cambria, serif; font-weight: 600; margin: 22px 0 9px; line-height: 1.25; }
h1.md-h { font-size: 25px; }
h2.md-h { font-size: 21px; }
h3.md-h { font-size: 17.5px; }
h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
.md-p { margin: 0 0 11px; }
.md-list { margin: 0 0 11px; padding-left: 22px; }
.md-li { margin-bottom: 5px; }
.md-task { display: inline-block; width: 16px; color: #8f8779; font-weight: 700; }
.md-task.is-done { color: #2f6b45; }
.md-li.is-task { list-style: none; margin-left: -18px; display: grid; grid-template-columns: 16px 1fr; column-gap: 4px; align-items: baseline; }
.md-li.is-task > :not(.md-task) { grid-column: 2; }
.md-li.is-task > .md-p:last-child { margin-bottom: 0; }
.md-quote { margin: 0 0 11px; padding: 2px 0 2px 15px; border-left: 3px solid #cfc6b6; color: #5d564d; }
.md-code { font: 0.88em ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace; background: #fbf9f6; border: 1px solid #e4ddd1; border-radius: 4px; padding: 1px 5px; }
.md-pre-wrap { margin: 0 0 13px; }
.md-pre { font: 13px/1.5 ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace; background: #fbf9f6; border: 1px solid #e4ddd1; border-radius: 8px; padding: 14px 16px; overflow-x: auto; margin: 0; }
.md-hr { border: 0; border-top: 1px solid #e4ddd1; margin: 20px 0; }
.md-table-wrap { overflow-x: auto; margin: 0 0 13px; }
.md-table { border-collapse: collapse; width: 100%; font-size: 13.5px; }
.md-table th, .md-table td { border: 1px solid #e4ddd1; padding: 8px 11px; text-align: left; }
.md-table th { background: #fbf9f6; font-weight: 600; }
.md-img { max-width: 100%; border-radius: 8px; }
.doc-figure { margin: 0 0 13px; }
.doc-img { display: block; max-width: 100%; border: 1px solid #e4ddd1; border-radius: 8px; }
.doc-figure figcaption { font-size: 13px; color: #5d564d; margin-top: 6px; }
.md a { color: #206cc3; }
@media print {
body { background: #fff; }
main { padding: 0; min-height: 0; }
.block { break-inside: avoid; }
}
`;
// Only this session's uploaded images may ride along in a saved file: any other
// address on this origin (/state, say) would copy session data into something
// meant to be shared. A remote image keeps its own address; anything else on
// this origin becomes its alt text.
const INLINE_UPLOAD = /^\/(?:uploads\/[0-9a-f-]{36}\.jpg|shots\/[A-Za-z0-9][A-Za-z0-9._-]{0,99}\.(?:png|jpe?g|webp))$/i;
function imageToAlt(img) {
const alt = img.getAttribute("alt") || "";
if (alt) img.replaceWith(document.createTextNode(alt));
else img.remove();
}
async function inlineImage(img) {
const src = img.getAttribute("src") || "";
if (!src || src.startsWith("data:")) return;
let url;
try {
url = new URL(src, location.href);
} catch {
return imageToAlt(img);
}
if (url.origin !== location.origin) {
img.setAttribute("src", url.href);
return;
}
if (!INLINE_UPLOAD.test(url.pathname) || url.search) return imageToAlt(img);
try {
const res = await fetch(url);
if (!res.ok) throw new Error(String(res.status));
const blob = await res.blob();
if (!blob.type.startsWith("image/")) throw new Error(blob.type);
img.setAttribute(
"src",
await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(blob);
})
);
} catch {
// Its console address would be a dead link once the server is gone.
imageToAlt(img);
}
}
function escapeHtml(s) {
return String(s).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
}
// The document as its own web page: drawn through the same markdown path the
// tab uses, so what is saved is what was on screen, minus the page's controls.
export async function downloadDocHtml(doc) {
const title = doc.title || "Document";
const body = el("div");
for (const b of doc.blocks || []) {
const box = el("div", "block " + (b.state || "settled"));
if (b.state === "assumed") box.appendChild(el("span", "block-tag", "Assumed for now, still open"));
if (b.state === "draft") box.appendChild(el("span", "block-tag", "Draft"));
box.appendChild(blockBody(b));
body.appendChild(box);
}
// Copy buttons only work inside the console.
for (const n of body.querySelectorAll(".md-copy")) n.remove();
// Images the console serves would be dead links once the server is gone, so
// they travel inside the file. One that will not load becomes its alt text.
await Promise.all([...body.querySelectorAll("img")].map(inlineImage));
const saved = new Date().toLocaleString();
const html = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${escapeHtml(title)}</title>
<style>${DOC_HTML_CSS}</style>
</head>
<body>
<main>
<header class="doc-head">
<h1>${escapeHtml(title)}</h1>
<span class="doc-version">v${escapeHtml(doc.version || 1)}</span>
<span class="doc-meta">Saved ${escapeHtml(saved)}</span>
</header>
${doc.note ? `<p class="doc-note">${escapeHtml(doc.note)}</p>\n` : ""}${body.innerHTML}
</main>
</body>
</html>
`;
saveFile(`${docFileName(doc)}.html`, html, "text/html");
}
// A doc that mirrors a file the agent already wrote needs no download button
// -- the path is the useful thing to show instead of it.
export function docSavedNote(doc) {
const path = typeof doc.saved === "string" ? doc.saved.trim() : "";
const note = el("span", "doc-saved", path ? "Saved as " : "Already saved");
if (path) note.appendChild(el("code", null, path));
return note;
}
+6 -4
View File
@@ -2,8 +2,10 @@
//
// The source of truth for which tabs Help has, in what order, and which one
// opens. The content itself is HTML in <template id="help-content">
// in index.html. No DOM access at module scope and no imports: the page and
// `node --test` both import this file.
// in index.html. No DOM access at module scope, and its one import is the
// data-only skills.js: the page and `node --test` both import this file.
import { SKILLS, isBuild } from "./skills.js";
const tab = (id, label, diagram) => Object.freeze({ id, label, diagram });
@@ -29,8 +31,8 @@ export const HELP_TABS = Object.freeze([
]);
// Not labels.js's BUILD_WORKFLOWS: that one leaves out quick-task, which is a
// build as far as the person watching it is concerned.
const HELP_BUILD_WORKFLOWS = new Set(["implement", "implement-review", "quick-task"]);
// build as far as the person watching it is concerned. Every build in skills.js.
const HELP_BUILD_WORKFLOWS = new Set(SKILLS.filter((s) => isBuild(s.workflow)).map((s) => s.workflow));
// Which tab Help opens on, from where the person is. First match wins.
export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow, workspace, meterRed } = {}) {
+23
View File
@@ -12,6 +12,29 @@
can draw anything real. -->
<link rel="modulepreload" href="/app.js" />
<link rel="modulepreload" href="/answers.js" />
<link rel="modulepreload" href="/skills.js" />
<link rel="modulepreload" href="/spec-states.js" />
<link rel="modulepreload" href="/state.js" />
<link rel="modulepreload" href="/doc-files.js" />
<link rel="modulepreload" href="/send-state.js" />
<link rel="modulepreload" href="/mention-box.js" />
<link rel="modulepreload" href="/uploads.js" />
<link rel="modulepreload" href="/sound.js" />
<link rel="modulepreload" href="/looks.js" />
<link rel="modulepreload" href="/selectors.js" />
<link rel="modulepreload" href="/screens/core.js" />
<link rel="modulepreload" href="/screens/ending.js" />
<link rel="modulepreload" href="/screens/docs.js" />
<link rel="modulepreload" href="/screens/cards.js" />
<link rel="modulepreload" href="/screens/starting.js" />
<link rel="modulepreload" href="/screens/dashboard.js" />
<link rel="modulepreload" href="/screens/git-host.js" />
<link rel="modulepreload" href="/screens/looks.js" />
<link rel="modulepreload" href="/screens/cleanup.js" />
<link rel="modulepreload" href="/screens/help-dialog.js" />
<link rel="modulepreload" href="/screens/workspace.js" />
<link rel="modulepreload" href="/screens/ask.js" />
<link rel="modulepreload" href="/net.js" />
<link rel="modulepreload" href="/render.js" />
<link rel="modulepreload" href="/palette.js" />
<link rel="modulepreload" href="/labels.js" />
+7 -3
View File
@@ -1,12 +1,16 @@
// Activity-line wording the page corrects on the way in. Kept out of app.js so
// `node --test` can import it: no DOM access at module scope.
// `node --test` can import it: no DOM access at module scope, and its one
// import is the data-only skills.js.
//
// A build numbers its tasks "Task 4.2" after the phase, but a person watching
// the page counts within the phase, so "Task 4.2 of 6" reads as nonsense
// beside a progress bar that says 2 of 6.
// The only workflows whose activity lines get rewritten.
export const BUILD_WORKFLOWS = new Set(["implement", "implement-review"]);
import { SKILLS, isPhased } from "./skills.js";
// The only workflows whose activity lines get rewritten: the phased builds,
// from skills.js.
export const BUILD_WORKFLOWS = new Set(SKILLS.filter((s) => isPhased(s.workflow)).map((s) => s.workflow));
const PHASE_TASK = /^Task (\d+)\.(\d+) of (\d+)/;
+217
View File
@@ -0,0 +1,217 @@
// Plan2Code Web Console - how the page looks and sounds: the saved looks, their sync, and the preferences dialog's swatches; defines only.
//
// The one preference that belongs to the person rather than to the session.
// `looks` is a live binding: every file reads the current object, and only
// this file replaces it.
import { DEFAULT_ACCENT, soundPrefs, DEFAULT_CARD_WIDTH, ACCENTS, cardWidth, soundKey } from "./palette.js";
import { normalizeRole, ROLE_NOT_SET } from "./starters.js";
import { bootData, hooks } from "./state.js";
import { el } from "./render.js";
const $ = (id) => document.getElementById(id);
// How the page looks and sounds, which is the one preference that belongs to
// the person rather than to the session. Kept per browser, applied before
// anything else is drawn, and deliberately touching nothing but presentation:
// a session opened in a different theme is the same session.
//
// The highlight colors live in palette.js, where the tests can reach them.
const ACCENT_VARS = ["--accent", "--accent-soft", "--accent-ink", "--accent-line"];
const LOOKS_KEY = "p2c-console:looks";
// The per-event sound switches (SOUND_EVENTS) live in palette.js too.
export const DEFAULT_LOOKS = {
theme: "system",
accent: DEFAULT_ACCENT,
sound: true,
...soundPrefs(null),
width: DEFAULT_CARD_WIDTH,
hideUnavailable: true,
};
export let looks = { ...DEFAULT_LOOKS };
let syncedLooks = null;
export let looksReady = false;
export function adoptLooks(saved) {
looks = { ...DEFAULT_LOOKS, ...saved };
if (!ACCENTS[looks.accent]) looks.accent = DEFAULT_LOOKS.accent;
if (!["system", "light", "dark"].includes(looks.theme)) looks.theme = DEFAULT_LOOKS.theme;
if (typeof looks.sound !== "boolean") looks.sound = DEFAULT_LOOKS.sound;
Object.assign(looks, soundPrefs(looks));
if (typeof looks.hideUnavailable !== "boolean") looks.hideUnavailable = DEFAULT_LOOKS.hideUnavailable;
looks.width = cardWidth(looks.width);
if (saved && typeof saved === "object" && Object.hasOwn(saved, "role")) looks.role = normalizeRole(saved.role);
else delete looks.role;
}
// The localStorage copy is only a cache now. It exists so the first paint can
// apply a theme synchronously rather than flashing the defaults while the
// fetch below is in flight; the server's looks.json is the truth, because it
// is the copy that follows the app when a new session lands on a new port.
export function loadLooks() {
try {
const raw = localStorage.getItem(LOOKS_KEY);
if (raw) adoptLooks(JSON.parse(raw));
} catch {}
}
// Called once the page is up. Server wins: its copy is shared by every port,
// while this origin's localStorage may be a leftover from a previous session
// on this port or empty on a fresh one. A 404 means the server has never been
// told -- including every install that predates the file -- so a browser that
// DOES hold a setting seeds it, which is also the upgrade path.
export async function syncLooks() {
let saved = null;
// The server already put its copy in the page: no request, and no second
// repaint a moment after the first. `looks: null` there is the 404 case.
const boot = bootData();
if (boot && "looks" in boot) saved = boot.looks ? { looks: boot.looks } : null;
else {
try {
const res = await fetch("/looks");
if (res.ok) saved = await res.json();
} catch {}
}
if (saved && saved.looks && typeof saved.looks === "object") {
adoptLooks(saved.looks);
syncedLooks = { ...looks };
try {
localStorage.setItem(LOOKS_KEY, JSON.stringify(looks));
} catch {}
applyLooks();
renderSwatches();
} else {
// Blocked storage throws on read, and that must not stop the page loading.
let held = false;
try {
held = Boolean(localStorage.getItem(LOOKS_KEY));
} catch {}
if (held) pushLooks();
}
looksReady = true;
// Not inline: with the server's copy in the page this runs before `S` exists.
setTimeout(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.
function pushLooks() {
try {
// Only what this tab changed since it last synced, so a tab with stale
// settings never overwrites another tab's change to a different key.
const set = {};
for (const [k, v] of Object.entries(looks)) if (!syncedLooks || syncedLooks[k] !== v) set[k] = v;
const before = syncedLooks;
const partial = Boolean(before);
if (partial && !Object.keys(set).length) return;
syncedLooks = { ...looks };
const body = partial ? { set } : { looks };
// A write that did not land must be sent again with the next change.
const undo = () => (syncedLooks = before);
fetch("/looks", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
})
.then((res) => res.ok || undo())
.catch(undo);
} catch {}
}
const systemDark = () => matchMedia("(prefers-color-scheme: dark)").matches;
const effectiveTheme = () => (looks.theme === "system" ? (systemDark() ? "dark" : "light") : looks.theme);
export function applyLooks() {
const root = document.documentElement;
// The server's stand-in for the saved accent, which only has to last until
// this runs. From here on the colors are set below, and a stale rule left
// switched on would win over "Back to default".
root.removeAttribute("data-looks-accent");
if (looks.theme === "system") root.removeAttribute("data-theme");
else root.setAttribute("data-theme", looks.theme);
// Tell the browser too, so form controls, scrollbars and the date picker
// follow the choice rather than staying on the system's idea of it.
root.style.colorScheme = looks.theme === "system" ? "light dark" : looks.theme;
// Before the accent's early return, so a default accent never skips it.
if (looks.width === DEFAULT_CARD_WIDTH) root.removeAttribute("data-width");
else root.dataset.width = looks.width;
// The default lives in the stylesheet, where it is written once per theme.
// Clearing the override is how it gets its own values back.
if (looks.accent === DEFAULT_LOOKS.accent) {
for (const name of ACCENT_VARS) root.style.removeProperty(name);
return;
}
const shades = ACCENTS[looks.accent][effectiveTheme()];
ACCENT_VARS.forEach((name, i) => root.style.setProperty(name, shades[i]));
}
export function saveLooks() {
try {
localStorage.setItem(LOOKS_KEY, JSON.stringify(looks));
} catch {}
pushLooks();
applyLooks();
// A width change reflows the card without resizing the column, so the
// column's observer never hears of it: refit the growing box here.
hooks.fitGrowBox();
renderSwatches();
}
// Built once, repainted in place. Rebuilding the row on every choice destroyed
// the button that had just been clicked, so focus fell to <body> and a keyboard
// user lost their place in the dialog each time they tried a color.
export function renderSwatches() {
const box = $("looks-swatches");
if (!box.children.length) {
for (const [id, a] of Object.entries(ACCENTS)) {
const b = el("button", "swatch");
b.type = "button";
b.dataset.accent = id;
b.title = a.name;
b.setAttribute("aria-label", a.name);
b.addEventListener("click", () => {
looks.accent = id;
saveLooks();
});
box.appendChild(b);
}
}
for (const b of box.children) {
const id = b.dataset.accent;
const [fill, , , line] = ACCENTS[id][effectiveTheme()];
b.setAttribute("aria-pressed", String(looks.accent === id));
// Fill and ring, so the swatch shows the pair the choice actually sets
// rather than half of it. The chosen one is still told apart by its
// double ring, which is drawn in ink and owes nothing to the accent.
b.style.background = fill;
b.style.borderColor = line;
}
for (const radio of document.querySelectorAll('input[name="looks-theme"]')) {
radio.checked = radio.value === looks.theme;
}
for (const radio of document.querySelectorAll('input[name="looks-width"]')) {
radio.checked = radio.value === looks.width;
}
$("looks-sound").checked = looks.sound;
// Each cue keeps its own tick while the master switch is off, so turning
// sound back on returns exactly the set that was chosen.
$("looks-sound-events").classList.toggle("is-off", !looks.sound);
for (const box of document.querySelectorAll("input[data-sound]")) {
box.checked = looks[soundKey(box.dataset.sound)];
box.disabled = !looks.sound;
}
$("looks-role").value = looks.role ?? ROLE_NOT_SET;
}
// "Back to default": every look returns to its default, but the role is
// marked as asked and the welcome stays seen.
export function resetLooks() {
looks = { ...DEFAULT_LOOKS, role: ROLE_NOT_SET, welcomeSeen: looks.welcomeSeen };
}
+127
View File
@@ -0,0 +1,127 @@
// Plan2Code Web Console - the @name suggestions popover under a text box; defines only.
//
// Shared by the question cards and the Ask pane, so neither imports the other.
import { page } from "./state.js";
import { el } from "./render.js";
import { applyMention, mentionAt, matchNames } from "./mentions.js";
import { workspaceFolders } from "./selectors.js";
export function closeMentions() {
if (!page.mentionPop) return;
const { box, node } = page.mentionPop;
node.remove();
removeEventListener("scroll", placeMentions, true);
box.setAttribute("aria-expanded", "false");
box.removeAttribute("aria-activedescendant");
page.mentionPop = null;
}
// Under the box, as wide as it, fixed to the viewport so no card's overflow
// can clip it; above it when the window has no room below (the Ask box sits
// at the bottom). A box that has been redrawn away takes the list with it.
function placeMentions() {
if (!page.mentionPop) return;
if (!page.mentionPop.box.isConnected) return closeMentions();
const r = page.mentionPop.box.getBoundingClientRect();
const node = page.mentionPop.node;
node.style.left = Math.round(r.left) + "px";
node.style.width = Math.round(r.width) + "px";
const h = node.offsetHeight;
const top = r.bottom + 4 + h <= innerHeight ? r.bottom + 4 : Math.max(4, r.top - 4 - h);
node.style.top = Math.round(top) + "px";
}
function paintMentions() {
const { node, box, matches, query } = page.mentionPop;
node.replaceChildren();
if (!matches.length) {
node.appendChild(el("div", "mention-empty", `No folder called @${query} in the workspace`));
box.removeAttribute("aria-activedescendant");
return;
}
matches.forEach((name, i) => {
const opt = el("div", "mention-opt" + (i === page.mentionPop.at ? " is-active" : ""), "@" + name);
opt.id = "mention-opt-" + i;
opt.setAttribute("role", "option");
opt.setAttribute("aria-selected", String(i === page.mentionPop.at));
// Held on mousedown, so the box keeps focus and the click can land.
opt.addEventListener("mousedown", (e) => e.preventDefault());
opt.addEventListener("click", () => pickMention(name));
node.appendChild(opt);
});
box.setAttribute("aria-activedescendant", "mention-opt-" + page.mentionPop.at);
}
function pickMention(name) {
if (!page.mentionPop) return;
const { box, mention } = page.mentionPop;
const next = applyMention(box.value, box.selectionStart, mention, name);
closeMentions();
box.value = next.text;
box.setSelectionRange(next.caret, next.caret);
// Whatever the box does with typing (drafts, staging, the counter) runs.
box.dispatchEvent(new Event("input", { bubbles: true }));
}
export function attachMentions(box) {
box.setAttribute("aria-autocomplete", "list");
box.setAttribute("aria-expanded", "false");
box.setAttribute("aria-controls", "mention-pop");
const update = () => {
const mention =
box.selectionStart === box.selectionEnd ? mentionAt(box.value, box.selectionStart) : null;
const names = workspaceFolders().map((f) => f.name);
const matches = mention ? matchNames(names, mention.query) : [];
// Nothing to offer with only the original folder and no match; a bigger
// workspace says plainly that the name is not in it.
if (!mention || (!matches.length && names.length < 2)) {
if (page.mentionPop && page.mentionPop.box === box) closeMentions();
return;
}
if (!page.mentionPop || page.mentionPop.box !== box) {
closeMentions();
const node = el("div", "mention-pop");
node.id = "mention-pop";
node.setAttribute("role", "listbox");
node.setAttribute("aria-label", "Workspace folders");
document.body.appendChild(node);
page.mentionPop = { box, node, at: 0, matches: [], mention: null, query: "" };
addEventListener("scroll", placeMentions, true);
box.setAttribute("aria-expanded", "true");
}
const same = page.mentionPop.matches.join("\n") === matches.join("\n");
Object.assign(page.mentionPop, { matches, mention, query: mention.query, at: same ? page.mentionPop.at : 0 });
paintMentions();
placeMentions();
};
box.addEventListener("input", update);
box.addEventListener("keyup", (e) => {
if (!["ArrowUp", "ArrowDown", "Enter", "Tab", "Escape"].includes(e.key)) update();
});
box.addEventListener("keydown", (e) => {
if (!page.mentionPop || page.mentionPop.box !== box || e.isComposing) return;
const { matches } = page.mentionPop;
const stop = () => {
e.preventDefault();
e.stopImmediatePropagation();
};
if (e.key === "Escape") {
stop();
return closeMentions();
}
if (!matches.length) return;
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
stop();
page.mentionPop.at = (page.mentionPop.at + (e.key === "ArrowDown" ? 1 : matches.length - 1)) % matches.length;
return paintMentions();
}
if ((e.key === "Enter" || e.key === "Tab") && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey) {
stop();
pickMention(matches[page.mentionPop.at]);
}
});
box.addEventListener("blur", () => {
if (page.mentionPop && page.mentionPop.box === box) closeMentions();
});
}
+13 -28
View File
@@ -3,8 +3,10 @@
// The source of truth for how much each piece of work weighs, how the count
// is folded out of ledger.ndjson, and what the pill says at each level. The
// count is never stored: it is always pointsFrom() over the ledger. No DOM
// access at module scope and no imports: the server, console.mjs, the page
// and `node --test` all import this file.
// 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";
// The one place the weights live (FR-12). Tune here.
export const WEIGHTS = Object.freeze({
@@ -37,10 +39,9 @@ export const WEIGHTS = Object.freeze({
// Workflows whose launch itself scores WEIGHTS[workflow]. Pathfinder,
// implement and implement-review score only through the agent's `run`
// reports; dashboard and handoff never score; git, changelog, xray and diagnose score 1 on
// launch (Git then adds its commit tally and conflict help).
export const LAUNCH_COUNTED = Object.freeze(
new Set(["plan", "revise-plan", "document", "review", "quick-task", "init", "init-update", "finalize", "git", "changelog", "xray", "diagnose"])
);
// 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)));
// 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,
@@ -71,8 +72,9 @@ export const MAX_TASKS = 999;
// writes a `progress` ledger entry whenever a build's `headline.cleared`
// rises, and the build's row scores those tasks at TASKS_PER_POINT with no
// 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:
export const PROGRESS_WORKFLOWS = Object.freeze(new Set(["implement", "implement-review"]));
// 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)));
// 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
@@ -125,26 +127,9 @@ export function runPoints(event, tasks, { bonus = true } = {}) {
// ANSWERS_PER_POINT answers, rounded down. Tune here.
export const ANSWERS_PER_POINT = 2;
// The skill names the answers row uses ("7 answers in Plan").
const WORKFLOW_NAMES = Object.freeze({
dashboard: "the dashboard",
pathfinder: "Pathfinder",
plan: "Plan",
"revise-plan": "Revise plan",
document: "Document",
implement: "Implement",
"implement-review": "Implement + Review",
review: "Review",
"quick-task": "Quick task",
init: "Init",
"init-update": "Init update",
finalize: "Finalize",
handoff: "Handoff",
git: "Git",
changelog: "Changelog",
xray: "X-ray",
diagnose: "Diagnose",
});
// 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])));
// 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");
+22
View File
@@ -0,0 +1,22 @@
// Plan2Code Web Console - the page talking to its own server.
//
// Only defines.
// POST a JSON body; the status and parsed answer, or status 0 when the
// server could not be reached.
export async function postJson(url, body) {
try {
const res = await fetch(url, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body || {}),
});
let answer = {};
try {
answer = await res.json();
} catch {}
return { status: res.status, body: answer };
} catch {
return { status: 0, body: {} };
}
}
+59
View File
@@ -15,6 +15,7 @@
// bypass. `html` tokens render as visible text, on purpose.
import { marked } from "./vendor/marked.esm.js";
import { APPROVAL_TIP } from "./answers.js";
// A bare `/` path stays on this origin; `//host` (and `/\host`, which browsers
// read the same way) is protocol-relative and would not, so it is refused.
@@ -359,3 +360,61 @@ function copyButton(text, className, source) {
}
export { el, copyButton, copyText, selectContents };
// A line whose backticked commands read as code; everything else is text.
export function textWithCode(tag, className, text) {
const node = el(tag, className);
text.split("`").forEach((part, n) => {
if (part) node.appendChild(n % 2 ? el("code", "md-code", part) : document.createTextNode(part));
});
return node;
}
export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
export function releasesLink(text) {
const a = el("a", null, text);
a.href = RELEASES_URL;
a.target = "_blank";
a.rel = "noopener noreferrer";
return a;
}
// A quiet line under the menu and the starting screen: the page cannot see a
// terminal approval prompt, so it says up front how to avoid one. Backticked
// spans become <code>, built as nodes like everything else here.
export function approvalTip() {
return textWithCode("p", "approval-tip", APPROVAL_TIP);
}
export const SVG_NS = "http://www.w3.org/2000/svg";
// A time of day for a chat message; empty when the stamp does not parse.
export function shortTime(iso) {
try {
return new Date(iso).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
} catch {
return "";
}
}
export function isMac() {
return /mac/i.test(navigator.platform || navigator.userAgent);
}
// A click on the backdrop closes a dialog that holds nothing to lose. The
// 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) {
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);
};
let pressedOutside = false;
dlg.addEventListener("pointerdown", (e) => (pressedOutside = outside(e)));
dlg.addEventListener("click", (e) => {
if (pressedOutside && outside(e)) dlg.close();
pressedOutside = false;
});
}
+855
View File
@@ -0,0 +1,855 @@
// 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 { el, md, isMac, lightDismiss, shortTime } from "../render.js";
import { startersFor } from "../starters.js";
import { looks } from "../looks.js";
import { thumbs, uploadUrl, docChip, attachTray, CHAT_IMAGES, attachFiles, incomingFiles, deleteUrl, sentAttachments, noteImages, attachRow } from "../uploads.js";
import { attachMentions } from "../mention-box.js";
import { pickerAccept, attachmentKind, noteAwaiting, threadWho, threadText } from "../answers.js";
import { postJson } from "../net.js";
import { CHECKIN_LINE, helperRows, showSwitch, switchLabel, defaultInstruction, PATHFINDER_RESEARCH_LINE } from "../subagents.js";
const $ = (id) => document.getElementById(id);
// The Quick question chat's page-local state, gone on a reload (the frame's
// own `chat` block, the Ask tab's dot and the rest are on `page`, state.js).
let chatSending = false;
let chatResetting = false;
let askPaintedOffline = false;
export const declineOpen = new Map();
const deciding = new Set();
// The frame's chat block, with `offline` worked out now rather than when the
// frame was sent: the agent comes and goes between frames, and /ping keeps
// agentLastSeen current. The frame's own verdict stands when there is no clock.
function askFrame() {
const base = page.chatFrame || { conversation: 0, messages: [], typed: 0, limit: 10, offline: false };
if (!page.S || !page.agentLastSeen) return base;
const offline = chatOffline({
finish: finish(),
agent: page.S.agent,
agentLastSeenMs: Date.parse(page.agentLastSeen),
now: Date.now(),
});
return { ...base, offline };
}
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 }) };
}
// The conversation a send belongs to. The page's own record wins over the
// frame for the moment after a 409 stale, before the new frame lands.
const askConversation = () => page.local.chat.conversation ?? askFrame().conversation;
export function renderAsk(main) {
const { frame, view: v, send: ss } = askState();
// Anything drawn here has been seen: no dot for it later.
const newest = newestReplyId(frame);
if (newest && page.local.chat.lastSeenReplyId !== newest) {
page.local.chat.lastSeenReplyId = newest;
saveNow();
}
page.chatDot = false;
askPaintedOffline = ss.state === "offline";
const pane = el("section", "ask-pane");
const head = el("div", "ask-head");
head.appendChild(el("h2", null, "Quick question"));
head.appendChild(el("span", "ask-counter", v.counterText));
const reset = el("button", "btn small ghost", "New conversation");
reset.type = "button";
reset.disabled = ss.state === "offline" || chatResetting;
reset.addEventListener("click", newConversation);
head.appendChild(reset);
pane.appendChild(head);
const list = el("div", "ask-list");
list.setAttribute("role", "log");
list.setAttribute("aria-live", "polite");
if (!v.rows.length) list.appendChild(askStarters(ss));
const notes = new Map(v.rows.filter((r) => r.kind === "decision").map((r) => [r.re, r.text]));
for (const r of v.rows) list.appendChild(askRow(r, ss, notes));
pane.appendChild(list);
pane.appendChild(askComposer(ss));
main.appendChild(pane);
// Back where the person left the list, unless something new arrived (or it
// is the first look), which brings the newest row into view.
const saved = scrollMemory.get("ask");
const grew = v.rows.length > page.askRowCount;
page.askRowCount = v.rows.length;
list.scrollTop = !saved || grew ? list.scrollHeight : saved.top;
}
// An empty conversation offers a few questions for this step, the role's
// first. A click only fills the box: nothing is ever sent for the person.
function askStarters(ss) {
const box = el("div", "ask-starters");
box.appendChild(el("p", "ask-starters-lead", "Not sure what to ask? Try one of these:"));
for (const starter of startersFor(page.S.workflow, looks.role, { hasContext: Boolean(page.local.chat.about) })) {
const b = el("button", "ask-starter", starter.text);
b.type = "button";
b.disabled = !ss.canType;
b.addEventListener("click", () => {
page.local.chat.draft = starter.text;
saveNow();
redraw();
const ta = $("ask-input");
if (!ta) return;
ta.focus();
ta.setSelectionRange(ta.value.length, ta.value.length);
});
box.appendChild(b);
}
return box;
}
function askRow(r, ss, notes) {
if (r.kind === "decision") {
const row = el("div", "ask-row decision");
row.appendChild(el("p", "ask-decision", r.decision !== "approve" ? "You declined the edit." : r.done ? "You approved the edit." : "You approved the edit, please wait..."));
if (r.text) row.appendChild(el("p", "ask-text", r.text));
return row;
}
if (r.kind === "agent") {
const row = el("div", "ask-row agent");
row.appendChild(el("div", "msg-who", "Plan2Code"));
row.appendChild(md(r.md, "md"));
if (r.proposal) row.appendChild(askProposal(r, ss, notes.get(r.id)));
if (Array.isArray(r.changed) && r.changed.length) {
const ul = el("ul", "ask-changed");
for (const c of r.changed) {
const li = el("li");
li.appendChild(el("code", null, c.file));
li.appendChild(el("span", "ask-changed-count", ` +${c.added} −${c.removed}`));
ul.appendChild(li);
}
row.appendChild(ul);
}
return row;
}
const row = el("div", "ask-row person" + (r.pending ? " pending" : ""));
if (r.about && r.about.label) row.appendChild(el("p", "ask-about", "About: " + r.about.label));
row.appendChild(el("p", "ask-text", r.text));
const hasImages = r.images && r.images.length;
const hasFiles = r.files && r.files.length;
if (hasImages || hasFiles) {
const tray = el("div", "attach-tray");
for (const img of r.images || []) {
const fig = el("figure", "attach-thumb is-ready");
const pic = el("img");
pic.src = thumbs.get(img.key) || uploadUrl(img);
pic.alt = img.name || "image";
fig.appendChild(pic);
tray.appendChild(fig);
}
for (const file of r.files || []) tray.appendChild(docChip(file, "ready"));
row.appendChild(tray);
}
if (r.pending && r.failed) {
const fail = el("p", "ask-waiting ask-failed", "Not sent — retry");
const retry = el("button", "btn tiny", "Retry");
retry.type = "button";
retry.disabled = ss.state === "offline" || chatSending;
retry.addEventListener("click", () => retryChat(r.tempId));
fail.appendChild(retry);
row.appendChild(fail);
} else if (r.pending) {
row.appendChild(el("p", "ask-waiting", "Sending…"));
} else if (r.waiting) {
const wait = el("p", "ask-waiting");
// Picked up and still answering: the ring says so, unless the agent has
// gone quiet, when a turning ring would pass a dead session for a slow one.
if (r.working && ss.state !== "offline" && !agentAdrift()) {
const spin = el("span", "spinner tiny");
spin.setAttribute("aria-hidden", "true");
wait.appendChild(spin);
}
wait.appendChild(el("span", null, r.waitingText));
row.appendChild(wait);
if (r.activity) row.appendChild(el("p", "ask-waiting", "Right now: " + r.activity));
}
return row;
}
function askProposal(r, ss, note) {
const box = el("div", "ask-proposal");
box.appendChild(el("p", "note-kicker", "Proposed change"));
box.appendChild(md(r.proposal.summary, "md"));
const files = el("ul", "ask-proposal-files");
for (const f of r.proposal.files || []) {
const li = el("li");
li.appendChild(el("code", null, f));
files.appendChild(li);
}
box.appendChild(files);
if (r.decided) {
box.appendChild(el("p", "ask-decided " + r.decided, r.decided === "approve" ? "Approved" : "Declined"));
if (note) box.appendChild(el("p", "help", note));
return box;
}
const busy = deciding.has(r.id) || ss.state === "offline";
const row = el("div", "ask-proposal-actions");
const approve = el("button", "btn small primary", "Approve");
approve.type = "button";
approve.disabled = busy;
approve.addEventListener("click", () => decideChat(r.id, "approve", ""));
row.appendChild(approve);
if (!declineOpen.has(r.id)) {
const decline = el("button", "btn small ghost", "Decline");
decline.type = "button";
decline.disabled = busy;
decline.addEventListener("click", () => {
declineOpen.set(r.id, "");
redraw();
$("decline-" + r.id)?.focus();
});
row.appendChild(decline);
} else {
const input = el("input");
input.type = "text";
input.id = "decline-" + r.id;
input.placeholder = "Why not? (optional)";
input.maxLength = CHAT_MAX_CHARS;
input.value = declineOpen.get(r.id) || "";
input.addEventListener("input", () => declineOpen.set(r.id, input.value));
input.addEventListener("keydown", (e) => {
if (e.key !== "Enter") return;
e.preventDefault();
e.stopPropagation();
decideChat(r.id, "decline", input.value);
});
row.appendChild(input);
const go = el("button", "btn small", "Send decline");
go.type = "button";
go.disabled = busy;
go.addEventListener("click", () => decideChat(r.id, "decline", declineOpen.get(r.id) || ""));
row.appendChild(go);
}
box.appendChild(row);
if (deciding.has(r.id)) box.appendChild(el("p", "help", "Sent. It will show here once Plan2Code has it."));
return box;
}
const COUNTER_FROM = 3500;
function askComposer(ss) {
const comp = el("div", "ask-composer");
const about = page.local.chat.about;
if (about) {
const chip = el("div", "ask-about-chip");
chip.appendChild(el("span", null, "About: " + about.label));
const x = el("button", "attach-remove", "×");
x.type = "button";
x.setAttribute("aria-label", "Send without this");
x.addEventListener("click", () => {
Object.assign(page.local.chat, nextAbout(page.local.chat, { type: "drop" }));
saveNow();
redraw();
});
chip.appendChild(x);
comp.appendChild(chip);
}
if (page.local.chat.images.length) comp.appendChild(attachTray(CHAT_IMAGES, page.local.chat.images));
const ta = el("textarea");
ta.id = "ask-input";
ta.placeholder = "Ask anything about this project";
ta.value = page.local.chat.draft || "";
ta.disabled = !ss.canType;
ta.setAttribute("aria-label", "Your question");
attachMentions(ta);
comp.appendChild(ta);
const row = el("div", "ask-actions");
const add = el("button", "btn small ghost", "+ Attach file");
add.type = "button";
add.setAttribute("aria-label", "Add files to this question");
add.disabled = !ss.canType || page.local.chat.images.length >= CHAT_MAX_ATTACHMENTS;
const picker = el("input");
picker.type = "file";
picker.accept = pickerAccept();
picker.multiple = true;
picker.hidden = true;
add.addEventListener("click", () => picker.click());
picker.addEventListener("change", () => {
attachFiles(CHAT_IMAGES, picker.files);
picker.value = "";
});
row.appendChild(add);
row.appendChild(picker);
if (!page.local.chat.about) row.appendChild(addContext(ss));
// Where the counter sits, the reason Send is off when it cannot be typed in:
// the limit, the last question still waiting, or nobody there to answer.
const counter = el("span", "ask-count");
if (!ss.canType) {
const cls = ss.state === "offline" ? "is-offline" : ss.state === "limit" ? "is-limit" : "is-waiting";
row.appendChild(el("p", "ask-disabled-note " + cls, ss.text));
} else {
row.appendChild(counter);
const hint = el("span", "ask-send-hint");
hint.appendChild(el("kbd", null, isMac() ? "⌘" : "Ctrl"));
hint.appendChild(document.createTextNode(" + "));
hint.appendChild(el("kbd", null, "Enter"));
row.appendChild(hint);
}
const go = el("button", "btn small primary", "Send");
go.type = "button";
row.appendChild(go);
comp.appendChild(row);
if (page.chatError) comp.appendChild(el("p", "ask-error", page.chatError));
const held = () => page.local.chat.images.some((img) => img.status !== "ready");
const sync = () => {
const len = ta.value.length;
counter.textContent = len >= COUNTER_FROM ? `${len} / ${CHAT_MAX_CHARS}` : "";
counter.classList.toggle("is-over", len > CHAT_MAX_CHARS);
go.disabled = !ss.canType || chatSending || !ta.value.trim() || len > CHAT_MAX_CHARS || held();
};
sync();
ta.addEventListener("input", () => {
page.local.chat.draft = ta.value;
saveNow();
sync();
});
// Ctrl/Cmd+Enter sends and a plain Enter is a line break. Every Enter stops
// here, so the page-wide Ctrl+Enter never sends the question cards from this box.
ta.addEventListener("keydown", (e) => {
if (e.key !== "Enter") return;
e.stopPropagation();
if (!(e.ctrlKey || e.metaKey) || e.isComposing) return;
e.preventDefault();
if (!go.disabled) sendChat();
});
ta.addEventListener("paste", (e) => {
const files = incomingFiles(e.clipboardData && e.clipboardData.files);
if (!files.length || !ss.canType) return;
if (!e.clipboardData.getData("text/plain")) e.preventDefault();
attachFiles(CHAT_IMAGES, files);
});
const canDrop = (e) => ss.canType && e.dataTransfer && [...e.dataTransfer.types].includes("Files");
const onOver = (e) => {
if (!canDrop(e)) return;
e.preventDefault();
comp.classList.add("is-dropping");
};
comp.addEventListener("dragenter", onOver);
comp.addEventListener("dragover", onOver);
comp.addEventListener("dragleave", (e) => {
if (!comp.contains(e.relatedTarget)) comp.classList.remove("is-dropping");
});
comp.addEventListener("drop", (e) => {
comp.classList.remove("is-dropping");
if (!canDrop(e)) return;
e.preventDefault();
attachFiles(CHAT_IMAGES, e.dataTransfer.files);
});
go.addEventListener("click", sendChat);
return comp;
}
const CONTEXT_KIND = { card: "Question", section: "Section", spec: "Spec" };
// + Add context: the only way a message gets an `about`. A menu of the last
// three places visited, then This spec, built fresh on every render.
function addContext(ss) {
const wrap = el("span", "ask-context");
const spec = isDashboard() ? selSpec() : page.S && page.S.specDir ? { dir: page.S.specDir } : null;
const options = contextOptions(page.local.chat, spec);
const btn = el("button", "btn small ghost", "+ Add context");
btn.type = "button";
btn.setAttribute("aria-haspopup", "menu");
btn.setAttribute("aria-expanded", "false");
btn.disabled = !ss.canType || !options.length;
if (!options.length) btn.title = "Visit a question or a document section first";
wrap.appendChild(btn);
let menu = null;
const outside = (e) => {
if (!wrap.contains(e.target)) close();
};
// Focus moves before the menu goes: removing the focused item fires a
// focusout of its own, which would otherwise re-enter here.
const close = (refocus) => {
if (!menu) return;
const gone = menu;
menu = null;
btn.setAttribute("aria-expanded", "false");
document.removeEventListener("pointerdown", outside, true);
if (refocus) btn.focus();
gone.remove();
};
const open = () => {
menu = el("div", "ask-context-menu");
menu.setAttribute("role", "menu");
menu.setAttribute("aria-label", "Add context");
for (const option of options) {
const item = el("button", "ask-context-item");
item.type = "button";
item.setAttribute("role", "menuitem");
item.appendChild(el("span", "ask-context-label", option.label));
item.appendChild(el("span", "ask-context-kind", CONTEXT_KIND[option.kind] || ""));
item.addEventListener("click", () => {
close();
Object.assign(page.local.chat, nextAbout(page.local.chat, { type: "pick", about: option }));
saveNow();
redraw();
});
menu.appendChild(item);
}
// A press inside the menu never moves focus. Safari (and Firefox on
// macOS) do not focus a clicked button, so the press would blur the
// focused item to nowhere and the focusout below would close the menu
// before the click landed.
menu.addEventListener("mousedown", (e) => e.preventDefault());
menu.addEventListener("keydown", (e) => {
const items = [...menu.querySelectorAll('[role="menuitem"]')];
const at = items.indexOf(document.activeElement);
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
close(true);
} else if (e.key === "ArrowDown" || e.key === "ArrowUp") {
e.preventDefault();
const step = e.key === "ArrowDown" ? 1 : -1;
items[(at + step + items.length) % items.length].focus();
} else if (e.key === "Home" || e.key === "End") {
e.preventDefault();
items[e.key === "Home" ? 0 : items.length - 1].focus();
}
});
wrap.appendChild(menu);
btn.setAttribute("aria-expanded", "true");
document.addEventListener("pointerdown", outside, true);
menu.querySelector('[role="menuitem"]').focus();
};
btn.addEventListener("click", () => (menu ? close() : open()));
wrap.addEventListener("focusout", (e) => {
if (menu && !wrap.contains(e.relatedTarget)) close();
});
return wrap;
}
const CHAT_ERRORS = {
stale: "A new conversation started. Your message is still here — press Send again.",
"too-long": `That message is over ${CHAT_MAX_CHARS.toLocaleString()} characters. Shorten it and send again.`,
image: "One of the images could not be attached. Remove it and try again.",
file: "One of the files could not be attached. Remove it and try again.",
};
async function sendChat() {
const text = (page.local.chat.draft || "").trim();
const { send: ss } = askState();
if (!text || chatSending || !ss.canType || text.length > CHAT_MAX_CHARS) return;
if (page.local.chat.images.some((img) => img.status !== "ready")) return;
const ofKind = (kind) => page.local.chat.images.filter((a) => attachmentKind(a) === kind);
const pend = {
tempId: crypto.randomUUID(),
text,
about: page.local.chat.about,
images: ofKind("image").map(({ key, path, name, url }) => ({ key, path, name, url })),
files: ofKind("file").map(({ key, path, name, size }) => ({ key, path, name, size })),
};
page.local.chat.pending.push(pend);
saveNow();
await postChat(pend);
}
function retryChat(tempId) {
const pend = page.local.chat.pending.find((p) => p.tempId === tempId);
if (!pend || chatSending) return;
pend.failed = false;
saveNow();
postChat(pend);
}
async function postChat(pend) {
chatSending = true;
page.chatError = "";
redraw();
let res = null;
let body = {};
try {
res = await fetch("/chat", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
text: pend.text,
about: pend.about || undefined,
images: pend.images.length ? pend.images.map(({ path, name }) => ({ path, name })) : undefined,
files: pend.files && pend.files.length ? pend.files.map(({ path, name }) => ({ path, name })) : undefined,
conversation: askConversation(),
}),
});
body = await res.json().catch(() => ({}));
} catch {
res = null;
}
chatSending = false;
const still = page.local.chat.pending.find((p) => p.tempId === pend.tempId);
if (!res) {
if (still) still.failed = true;
} else if (res.ok) {
if (still) still.seq = body.seq;
// What was sent leaves the composer, and the context leaves with it: a
// follow-up is a general question unless it is picked again.
Object.assign(page.local.chat, nextAbout(page.local.chat, { type: "sent" }));
if ((page.local.chat.draft || "").trim() === pend.text) {
page.local.chat.draft = "";
page.local.chat.images = [];
}
} else {
page.local.chat.pending = page.local.chat.pending.filter((p) => p.tempId !== pend.tempId);
if (body.error === "stale" && typeof body.conversation === "number") page.local.chat.conversation = body.conversation;
// A limit or offline refusal needs no words: the disabled composer says why.
if (body.error !== "limit" && body.error !== "offline") {
page.chatError = CHAT_ERRORS[body.error] || "That message could not be sent. Try again.";
}
}
saveNow();
redraw();
}
async function newConversation() {
// One reset at a time: a second press would only come back stale and put
// an error under the clean conversation the first one opened.
if (chatResetting) return;
chatResetting = true;
redraw();
let res = null;
let body = {};
try {
res = await fetch("/chat", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ reset: true, conversation: askConversation() }),
});
body = await res.json().catch(() => ({}));
} catch {}
if (res && res.ok) {
// An explicit fresh start: the unsent draft and its pictures go too.
for (const img of page.local.chat.images) if (img.id) fetch(deleteUrl(img), { method: "DELETE" }).catch(() => {});
page.local.chat = { ...freshChat(), history: page.local.chat.history, about: null, conversation: body.conversation };
page.chatError = "";
page.askRowCount = 0;
declineOpen.clear();
} else if (body.error === "stale" && typeof body.conversation === "number") {
page.local.chat.conversation = body.conversation;
page.chatError = "A new conversation had already started.";
} else if (body.error !== "offline") {
page.chatError = "A new conversation could not be started. Try again.";
}
chatResetting = false;
saveNow();
redraw();
}
async function decideChat(re, decision, text) {
if (deciding.has(re)) return;
deciding.add(re);
page.chatError = "";
redraw();
let ok = false;
let body = {};
try {
const res = await fetch("/chat/decision", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ re, decision, text: text.trim() || undefined, conversation: askConversation() }),
});
ok = res.ok;
body = await res.json().catch(() => ({}));
} catch {}
// Kept in `deciding` on success: the buttons stay off until the frame
// brings the decision back, rather than flashing live again in between.
if (ok) declineOpen.delete(re);
else {
deciding.delete(re);
page.chatError =
body.error === "stale"
? "That proposal belongs to an earlier conversation."
: "That decision could not be sent. Try again.";
}
redraw();
}
export function renderAside() {
const aside = $("aside");
// Redrawing empties the panel, which drops its scroll to the top. An image
// upload redraws two or three times while the person watches its tray, so
// the place is kept while the same question stays on screen.
const place = aside.dataset.item === String(page.selected) ? aside.scrollTop : 0;
aside.replaceChildren();
aside.dataset.item = String(page.selected);
// The end page is about the session, not any one question: the notes that
// belong to a question stay on its own page.
const item = page.view === "end" ? null : byId(page.selected);
if (!item) {
// The menu has no questions, so no notes either: the pane stays empty.
if (!isDashboard()) aside.appendChild(el("p", "aside-empty", "Pick a question to see its notes."));
return;
}
// Off the question's own page (a doc tab, Ask) "this" points at nothing on
// screen, so the pane names the question a note here will go to.
const onQuestion = page.view === "questions" || page.view === "end";
aside.appendChild(el("h2", null, onQuestion ? "Notes on this" : `Notes on “${item.title || "this question"}”`));
const thread = item.thread || [];
if (!thread.length && !(isOpen(item) && !finish() && noteAwaiting(item))) {
aside.appendChild(
el(
"p",
"aside-empty",
isOpen(item) && !finish()
? "No back and forth yet. Anything you type here goes with your next send."
: "Nothing was said about this one."
)
);
}
// A note that has been sent but not yet picked up: marked as waiting, so the
// send is seen to have gone, until the agent replies. The server writes the
// note into the thread as it arrives; a session from before that has only
// `sentNote`, which gets a box of its own below.
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
let waitingShown = false;
for (const m of thread) {
const mine = threadWho(m) === "user";
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
if (pending) waitingShown = true;
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
const who = el("div", "msg-who");
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
box.appendChild(who);
const text = threadText(m);
if (text) box.appendChild(md(text, "md"));
const tray = mine ? sentAttachments(m) : null;
if (tray) box.appendChild(tray);
aside.appendChild(box);
}
if (waiting && !waitingShown) {
const box = el("div", "msg you pending");
const who = el("div", "msg-who");
who.appendChild(el("span", null, "You"));
who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
box.appendChild(who);
if (waiting.text) box.appendChild(md(waiting.text, "md"));
const tray = sentAttachments(waiting);
if (tray) box.appendChild(tray);
aside.appendChild(box);
}
// A finished session has nobody left for a note to reach, so the box would
// be a place to type words that go nowhere.
if (!isOpen(item) || finish()) {
aside.scrollTop = place;
return;
}
const wrap = el("div", "field");
const id = "thread-" + item.id;
const label = el("label", null, "Add a note, attach a file, or ask something");
label.htmlFor = id;
wrap.appendChild(label);
const attached = noteImages(item.id);
wrap.appendChild(attachRow(item.id, "Add files to this note"));
if (attached.length) wrap.appendChild(attachTray(item.id, attached));
const ta = el("textarea");
ta.id = id;
ta.placeholder = "Goes with your next send. It does not answer the question.";
ta.value = page.local.drafts[id] || "";
attachMentions(ta);
ta.addEventListener("input", () => {
setDraft(id, ta.value);
hooks.renderFooter();
});
ta.addEventListener("paste", (e) => {
const files = incomingFiles(e.clipboardData && e.clipboardData.files);
if (!files.length) return;
// A copy from some apps carries the picture and its text together; the
// text still pastes as it always did.
if (!e.clipboardData.getData("text/plain")) e.preventDefault();
attachFiles(item.id, files);
});
wrap.appendChild(ta);
aside.appendChild(wrap);
aside.scrollTop = place;
}
// The helpers the agent reported, as it last posted them. Everything here is
// the agent's text, so it goes in as text, never as markup.
export function renderSubagents(main) {
const card = el("section", "card sa-card");
card.appendChild(el("h2", null, "Subagents"));
card.appendChild(el("p", "help", CHECKIN_LINE));
const { alone, rows } = helperRows(page.S.helpers);
if (alone) {
card.appendChild(
el("p", "sa-alone", "Working alone: your agent has no way to start helpers here, so it is doing this skill's work itself.")
);
main.appendChild(card);
return;
}
const list = el("ul", "sa-list");
for (const row of rows) {
const item = el("li", "sa-row");
const head = el("div", "sa-head");
head.appendChild(el("strong", "sa-title", row.title));
const pill = el("span", "pill sa-pill is-" + row.state);
if (row.state === "running") {
const spin = el("span", "spinner tiny");
spin.setAttribute("aria-hidden", "true");
pill.appendChild(spin);
}
pill.appendChild(document.createTextNode(row.stateLabel));
head.appendChild(pill);
item.appendChild(head);
item.appendChild(el("p", "sa-ask", row.ask));
if (row.result) item.appendChild(el("p", "sa-result", row.result));
list.appendChild(item);
}
card.appendChild(list);
main.appendChild(card);
}
// Shown only where the skill opts in and the agent's console copy can deliver
// it. Lit while helpers are on; a click opens the dialog, never toggles.
export function renderSubagentsButton() {
const btn = $("btn-subagents");
const offer = showSwitch(page.subagentsFrame);
btn.hidden = !offer;
if (!offer) return;
const label = switchLabel(page.subagentsFrame);
btn.setAttribute("aria-pressed", String(Boolean(page.subagentsFrame.on)));
btn.title = label;
btn.setAttribute("aria-label", label);
btn.disabled = page.gone;
}
// The Subagents dialog, filled from the frame each time it opens. A null
// instruction is the shipped default, shown as its text so it can be edited.
export function openSubagents() {
if (!showSwitch(page.subagentsFrame)) return;
const on = Boolean(page.subagentsFrame.on);
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) {
radio.checked = radio.value === (on ? "on" : "off");
}
$("subagents-instruction").value = page.subagentsFrame.instruction ?? defaultInstruction(page.S.workflow);
$("subagents-max").value = String(page.subagentsFrame.max);
$("subagents-checkin").textContent = CHECKIN_LINE;
const research = $("subagents-research");
research.textContent = PATHFINDER_RESEARCH_LINE;
research.hidden = page.S.workflow !== "pathfinder";
$("subagents-status").textContent = "";
$("subagents-save").disabled = false;
syncSubagentsFields();
$("subagents-modal").showModal();
const checked = document.querySelector('input[name="subagents-on"]:checked');
if (checked) checked.focus();
}
// Instruction and "at most" only mean anything with helpers on, so they are
// inert under Work alone (kept as typed, for when helpers go back on).
export function syncSubagentsFields() {
const picked = document.querySelector('input[name="subagents-on"]:checked');
const off = !picked || picked.value !== "on";
for (const id of ["subagents-instruction", "subagents-max", "subagents-default"]) $(id).disabled = off;
}
const SUBAGENTS_ERRORS = {
max: "Pick a number from 1 to 20.",
"too-long": "The instruction is over 2,000 characters.",
"not-offered": "This skill doesn't use helpers.",
bad: "That didn't save. Try again.",
};
const SUBAGENTS_LOST = "Lost contact with Plan2Code. Try again once it's back.";
export async function saveSubagents() {
const save = $("subagents-save");
const status = $("subagents-status");
const picked = document.querySelector('input[name="subagents-on"]:checked');
const text = $("subagents-instruction").value.trim();
// The shipped default is stored as null, so a later release's wording
// reaches everyone who never changed it.
const instruction = text === defaultInstruction(page.S.workflow) ? null : text;
const body = { on: Boolean(picked && picked.value === "on"), instruction, max: Number($("subagents-max").value) };
save.disabled = true;
status.textContent = "";
const res = await postJson("/subagents", body);
save.disabled = false;
// The next state frame redraws the button.
if (res.status === 200) return $("subagents-modal").close();
if (res.status === 400) status.textContent = SUBAGENTS_ERRORS[res.body && res.body.error] || SUBAGENTS_ERRORS.bad;
else if (res.status === 403 || res.status === 0) status.textContent = SUBAGENTS_LOST;
else status.textContent = SUBAGENTS_ERRORS.bad;
}
// Whether the agent coming or going has changed what the Ask pane painted,
// with no frame to say so (the page's clock asks, once a second).
export const askOfflineFlipped = () => (askState().send.state === "offline") !== askPaintedOffline;
// The Subagents dialog's buttons, and dropping files onto the notes panel.
export function wireAsk() {
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) radio.addEventListener("change", syncSubagentsFields);
lightDismiss($("subagents-modal"));
$("btn-subagents").addEventListener("click", openSubagents);
$("subagents-default").addEventListener("click", () => {
$("subagents-instruction").value = defaultInstruction(page.S.workflow);
});
$("subagents-save").addEventListener("click", saveSubagents);
$("subagents-cancel").addEventListener("click", () => $("subagents-modal").close());
$("subagents-modal").addEventListener("close", () => $("btn-subagents").focus());
// Dropping files onto the notes panel attaches them to the selected
// question's note. Bound once here: the panel's contents are redrawn on every
// render, the panel itself is not.
{
const aside = $("aside");
const canDrop = (e) => {
const item = page.view === "end" ? null : byId(page.selected);
return (
Array.from((e.dataTransfer && e.dataTransfer.types) || []).includes("Files") &&
item &&
isOpen(item) &&
!finish()
);
};
const onOver = (e) => {
if (!canDrop(e)) return;
e.preventDefault();
aside.classList.add("is-dropping");
};
aside.addEventListener("dragenter", onOver);
aside.addEventListener("dragover", onOver);
aside.addEventListener("dragleave", (e) => {
// Moving between children fires dragleave too; only leaving the panel counts.
if (!aside.contains(e.relatedTarget)) aside.classList.remove("is-dropping");
});
aside.addEventListener("drop", (e) => {
aside.classList.remove("is-dropping");
if (!canDrop(e)) return;
e.preventDefault();
attachFiles(page.selected, e.dataTransfer.files);
});
}
}
File diff suppressed because it is too large. Load diff
+126
View File
@@ -0,0 +1,126 @@
// Plan2Code Web Console - User Preferences, Cleanup tab.
import { formatBytes } from "../answers.js";
import { el } from "../render.js";
import { postJson } from "../net.js";
const $ = (id) => document.getElementById(id);
// Cleanup: the server works out what in ~/.plan2code is not needed and
// shows it first; Delete these sends back only the ids it was shown, and the
// server re-checks every one before removing it.
let cleanupFound = null;
// Bumped by every scan, delete and reset: a response from an older one is
// dropped, so a scan still in flight when Preferences closes cannot refill it.
let cleanupGen = 0;
const CLEANUP_SHOWN = 8;
function setCleanupStatus(text, isError) {
const status = $("cleanup-status");
status.textContent = text;
status.classList.toggle("error", Boolean(isError));
}
const CLEANUP_WHERE = { root: "~/.plan2code/", console: "~/.plan2code/console/", completed: "specs--completed/" };
function cleanupLabel(item) {
if (item.where === "session") return "Session " + item.name;
return CLEANUP_WHERE[item.where] + item.name + (item.kind === "folder" ? "/" : "");
}
function cleanupSummary(items, bytes) {
const sessions = items.filter((i) => i.where === "session").length;
const completed = items.filter((i) => i.where === "completed").length;
const strays = items.length - sessions - completed;
const parts = [];
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
if (completed) parts.push(completed + (completed === 1 ? " old completed spec" : " old completed specs"));
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
return parts.join(", ") + " · " + formatBytes(bytes);
}
function resetCleanup() {
cleanupGen++;
cleanupFound = null;
$("cleanup-list").replaceChildren();
$("cleanup-delete").hidden = true;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
setCleanupStatus("", false);
}
function renderCleanup() {
const list = $("cleanup-list");
list.replaceChildren();
const items = (cleanupFound && cleanupFound.items) || [];
$("cleanup-delete").hidden = !items.length;
if (!items.length) return;
const rows = (some) => some.map((item) => {
const row = el("div", "cleanup-row");
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", formatBytes(item.bytes)));
return row;
});
list.append(el("p", "cleanup-summary", cleanupSummary(items, cleanupFound.bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
if (items.length > CLEANUP_SHOWN) {
const more = el("details", "cleanup-more");
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
list.appendChild(more);
}
}
async function scanCleanup() {
const gen = ++cleanupGen;
$("cleanup-scan").disabled = true;
$("cleanup-delete").disabled = true;
setCleanupStatus("Looking…", false);
const { status, body } = await postJson("/cleanup", { scan: true });
if (gen !== cleanupGen) return;
$("cleanup-scan").disabled = false;
$("cleanup-delete").disabled = false;
if (status !== 200 || !body.ok) {
cleanupFound = null;
renderCleanup();
return setCleanupStatus(status ? body.error || "Could not look." : "Plan2Code isn't reachable.", true);
}
cleanupFound = { items: body.items || [], bytes: body.bytes || 0 };
renderCleanup();
// Left in the status line, not cleared: it is the live region, so this is
// what a screen reader hears when the scan finishes.
const found = cleanupFound.items.length;
setCleanupStatus(found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.", false);
}
async function deleteCleanup() {
if (!cleanupFound || !cleanupFound.items.length) return;
const gen = ++cleanupGen;
$("cleanup-delete").disabled = true;
$("cleanup-scan").disabled = true;
setCleanupStatus("Deleting…", false);
const { status, body } = await postJson("/cleanup", { delete: cleanupFound.items.map((i) => i.id) });
if (gen !== cleanupGen) return;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
if (status !== 200 || !body.ok) {
return setCleanupStatus(status ? body.error || "Could not delete." : "Plan2Code isn't reachable.", true);
}
const removed = (body.removed || []).length;
const failed = (body.failed || []).length;
// The server re-checks every id and keeps anything that changed since the
// scan; say so, rather than let a count that came up short pass unremarked.
const asked = cleanupFound.items.length;
const kept = Math.max(0, asked - removed - failed);
cleanupFound = null;
renderCleanup();
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
const keptLine = kept ? ` ${kept} ${kept === 1 ? "was" : "were"} kept because ${kept === 1 ? "it" : "they"} changed since the scan.` : "";
setCleanupStatus((failed ? done + " " + failed + " could not be removed." : done) + keptLine, Boolean(failed));
}
// The Cleanup tab's buttons, and starting over whenever Preferences closes.
export function wireCleanup() {
$("cleanup-scan").addEventListener("click", scanCleanup);
$("cleanup-delete").addEventListener("click", deleteCleanup);
$("looks-modal").addEventListener("close", resetCleanup);
}
File diff suppressed because it is too large. Load diff
+987
View File
@@ -0,0 +1,987 @@
// Plan2Code Web Console - the dashboard: cards, the spec picker, handoff chips, delete, and the first-open wake-up; defines only.
import {
selHandoff,
scan,
selSpec,
agentWorking,
specList,
handoffList,
loadOverview,
finish,
} from "../selectors.js";
import { hooks, page, redraw, saveNow } from "../state.js";
import { el, approvalTip, mdInto, releasesLink, copyButton } from "../render.js";
import { needsRoleNudge, ROLE_NOT_SET } from "../starters.js";
import { looks, renderSwatches, saveLooks } from "../looks.js";
import { RED_BANNER } from "../meter.js";
import {
dashNoteKind,
defaultSpec,
onInitialPick,
cardPresentation,
CATALOG_GROUPS,
SKILL_CATALOG,
SPEC_STATE_LABELS,
chipDetail,
isDeletableSpecDir,
handoffAge,
handoffCopyText,
pickupAction,
pickupReply,
launchTarget,
cardAvailability,
launchReply,
deleteSummary,
deleteHandoffAction,
deleteHandoffReply,
deleteAction,
deleteReply,
} from "../answers.js";
import { stateFor } from "../spec-states.js";
import { sound, soundOn, fadeSound, dropSounds } from "../sound.js";
import { playWake } from "../boot.js";
const $ = (id) => document.getElementById(id);
// The dashboard's first-open wake-up itself is page.wake (state.js). Once per
// page, whatever storage allows: a re-render mid-run must never start a
// second one.
let wakeTried = false;
// True when a wake-up is waiting on the first click: the page load's opening
// chime then gives way to the boot-up sound, played as he powers on.
export let wakeHoldsChime = false;
// His snore while he sleeps (an Audio on loop), or null. Usually silent until
// the waking click, since browsers refuse sound before one.
let snore = null;
function roleNudge() {
const nudge = el("div", "dash-nudge");
nudge.setAttribute("role", "status");
nudge.appendChild(el("span", "dash-nudge-text", "Pick your role to get starter templates ordered for you."));
const actions = el("div", "dash-nudge-actions");
const setUp = el("button", "btn small primary", "Set up preferences");
setUp.type = "button";
setUp.addEventListener("click", () => {
renderSwatches();
// 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(
"close",
() => {
if (looks.role === undefined) {
looks.role = ROLE_NOT_SET;
saveLooks();
redraw();
}
},
{ once: true }
);
$("looks-modal").showModal();
});
const notNow = el("button", "btn tiny ghost", "Not now");
notNow.type = "button";
notNow.addEventListener("click", () => {
looks.role = ROLE_NOT_SET;
saveLooks();
redraw();
});
actions.append(setUp, notNow);
nudge.appendChild(actions);
return nudge;
}
// × on the update banner hides it for this console session only, and only
// for the release it named. Blocked storage means "not dismissed".
function updateDismissKey() {
try {
return "p2c-update-dismissed:" + page.S.sid;
} catch {
return "p2c-update-dismissed:";
}
}
function updateDismissed() {
try {
return sessionStorage.getItem(updateDismissKey()) === page.updateFrame.latest;
} catch {
return false;
}
}
const UPDATE_COMMAND = "plan2code update";
// For a machine without the plan2code command: the full installer, menu and all.
const UPDATE_FALLBACK_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
function openUpdateModal() {
if (!page.updateFrame) return;
const versions = $("update-versions");
versions.replaceChildren(
document.createTextNode("Version "),
releasesLink("v" + page.updateFrame.latest),
document.createTextNode(" is out — you have "),
el("code", null, page.updateFrame.installed),
document.createTextNode(".")
);
const row = $("update-command");
const code = el("code", null, UPDATE_COMMAND);
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
const fallbackRow = $("update-fallback");
const fallback = el("code", null, UPDATE_FALLBACK_COMMAND);
fallbackRow.replaceChildren(fallback, copyButton(UPDATE_FALLBACK_COMMAND, "btn small ghost handoff-copy", fallback));
$("update-modal").showModal();
}
export function renderDashboard(main) {
maybeWake();
// First, so nothing below reads a pick whose handoff has left the scan, and
// a delete the agent's rescan has finished stops holding the buttons.
selHandoff();
settleDeleting();
const menu = (page.S && page.S.menu) || {};
const wrap = el("div", "dash");
if (needsRoleNudge(looks)) wrap.appendChild(roleNudge());
// Advice only: words, never a button, and nothing is blocked.
if (page.meterFrame && page.meterFrame.level === "red") {
const warn = el("div", "dash-nudge meter-banner", RED_BANNER);
warn.setAttribute("role", "status");
wrap.appendChild(warn);
}
// Built here only, so no other workflow's page ever shows it.
if (page.updateFrame && !updateDismissed()) {
const notice = el("div", "dash-nudge update-banner");
notice.setAttribute("role", "status");
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + page.updateFrame.latest);
open.type = "button";
open.addEventListener("click", openUpdateModal);
const dismiss = el("button", "update-banner-dismiss", "×");
dismiss.type = "button";
dismiss.setAttribute("aria-label", "Dismiss until next time");
dismiss.addEventListener("click", () => {
try {
sessionStorage.setItem(updateDismissKey(), page.updateFrame.latest);
} catch {}
redraw();
});
notice.append(open, dismiss);
wrap.appendChild(notice);
}
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
// The agent's note reads the spec the picker opened on (the same "initial"
// test cardPresentation uses): another pick, or Start from scratch, gets
// the neutral line rather than context about a spec no longer shown.
const first = defaultSpec(scan() && scan().specs);
const picked = selSpec();
const noteKind = dashNoteKind({ menu, hasMenu: Boolean(page.S.menu), onInitial: onInitialPick(first, picked), working: agentWorking() });
if (noteKind === "agent") {
wrap.appendChild(el("p", "dash-note", menu.note));
} else if (noteKind === "looking") {
// The cards work from the first paint; the agent's read of the
// project arrives a moment later, and this says so meanwhile.
const note = el("p", "dash-note");
note.appendChild(document.createTextNode("Pick what to do next. "));
const working = el("span", "dash-working");
working.appendChild(el("span", "spinner tiny"));
working.appendChild(
el(
"span",
null,
"Plan2Code is still looking over the project and will flag where it would start when it is done."
)
);
note.appendChild(working);
wrap.appendChild(note);
} else {
wrap.appendChild(
el("p", "dash-note", "Pick what to do next. It starts right here, and this page becomes its home.")
);
}
const specs = specList();
if (specs.length || handoffList().length) wrap.appendChild(renderSpecPicker(specs));
const handoff = selHandoff();
if (handoff) {
// A handoff is picked up, not launched: its skill and spec come from its
// own record, so the skill cards and their toggle have nothing to say.
if (!page.local.launching && !page.launchScoping && page.scopeMine !== "") hooks.syncWorkspaceScope();
wrap.appendChild(renderHandoffPreview(handoff));
main.appendChild(wrap);
queueMicrotask(hooks.maybeWelcome);
return;
}
wrap.appendChild(hideUnavailableToggle());
// Only when this tab's own pick moved: another tab changing the scope
// sends a frame here too, and re-asserting this tab's pick on every render
// had two dashboards trade the workspace back and forth without end.
const wantScope = (selSpec() && selSpec().dir) || "";
if (!page.local.launching && !page.launchScoping && wantScope !== page.scopeMine) hooks.syncWorkspaceScope();
// "Unavailable" is the scan's verdict for the selected spec, not the
// momentary greying while a launch is in flight or the server is away, so
// cards never blink out of the menu mid-handoff.
const hide = looks.hideUnavailable;
const sel = selSpec();
const available = (e) => cardPresentation(e, scan(), sel, menu).on;
let shown = 0;
for (const g of CATALOG_GROUPS) {
const entries = SKILL_CATALOG.filter((e) => e.group === g.id && (!hide || available(e)));
if (!entries.length) continue;
shown += entries.length;
const section = el("section", "dash-group");
section.appendChild(el("h3", "dash-group-title", g.title));
const grid = el("div", "dash-grid");
for (const e of entries) grid.appendChild(dashCard(e, menu));
section.appendChild(grid);
wrap.appendChild(section);
}
if (!shown) {
wrap.appendChild(
el("p", "dash-empty", "Nothing fits this pick right now. Turn off the toggle above to see every workflow.")
);
}
wrap.appendChild(approvalTip());
// Mid wake-up: the groups wait hidden until the glide lets them rise in,
// and the note shows only as far as it has been typed. Once the entrance
// has played, a re-render draws the menu plainly, never replaying it.
if (page.wake && !page.wake.entered) wrap.classList.add("waking", ...(page.wake.cards ? ["is-in"] : []));
if (page.wake && page.wake.typed != null) {
const note = wrap.querySelector(".dash-note");
if (note) revealNote(note, page.wake.typed);
}
main.appendChild(wrap);
// Deferred: this runs inside render(), and the dialog is not part of it.
queueMicrotask(hooks.maybeWelcome);
}
const WAKE_TYPE_DELAY_MS = 350;
const WAKE_TYPE_EVERY_MS = 14;
const WAKE_ENTRANCE_MS = 900;
// One snore, for a nudge with no sound to time it (sounds off, or refused).
const SNORE_MS = 2600;
// The longest a nudge waits on the snore ending: a hidden tab may never say.
const SNORE_MAX_MS = 6000;
const BOOTUP_FADE_MS = 500;
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// Only a newly opened dashboard carries `wake` (console.mjs deletes it on
// every resume), and only the first page load in this tab plays it.
function maybeWake() {
if (wakeTried || page.S.wake !== true || finish()) return;
wakeTried = true;
const key = "p2c-console:woke:" + page.S.sid;
try {
if (sessionStorage.getItem(key)) return;
sessionStorage.setItem(key, "1");
} catch {
// Blocked storage only costs the reload guard.
}
const stage = $("wake");
const pilot = $("planny").closest(".pilot");
page.wake = { cards: false, entered: false, typed: 0, timers: [], abort: new AbortController() };
wakeHoldsChime = !matchMedia("(prefers-reduced-motion: reduce)").matches;
if (wakeHoldsChime && soundOn("snore")) {
snore = new Audio("/sleeping.mp3");
snore.loop = true;
snore.play().catch(() => {});
}
pilot.classList.add("is-waking");
playWake({
stage,
bot: stage.querySelector(".wake-bot"),
skipEl: stage.querySelector(".wake-skip"),
target: $("planny"),
stir: stirWake,
onStart: () => sound("bootup"),
onGlide: wakeGlide,
onSkip: skipWakeSounds,
signal: page.wake.abort.signal,
}).then(({ skipped }) => {
stopSnore();
fadeSound("bootup", BOOTUP_FADE_MS);
pilot.classList.remove("is-waking");
// An abort or reduced motion jumps straight to the finished
// dashboard. A run that reached its end leaves the note typing on.
if (skipped || (page.wake && !page.wake.cards)) finishWake();
});
}
// The nudge: one whole snore from the top, however far the loop had got (or
// the first one heard, since the loop is usually refused until this click).
// Called inside the click, so the browser lets it play. Settles when it ends,
// and never rejects: a refused or silent snore just takes one snore's time.
function stirWake() {
if (!snore) return delay(SNORE_MS);
const heard = new Promise((resolve) => snore.addEventListener("ended", resolve, { once: true }));
snore.loop = false;
snore.currentTime = 0;
return snore.play().then(
() => Promise.race([heard, delay(SNORE_MAX_MS)]),
() => delay(SNORE_MS)
);
}
function stopSnore() {
if (!snore) return;
snore.pause();
snore = null;
}
// The Skip button: silence anything the intro already queued or started. The
// promise's .then does the snore and the bootup fade; this only clears cues
// still waiting to play.
function skipWakeSounds() {
dropSounds();
}
// The glide: the menu rises in and the note starts typing. On a skip the run
// is already ending and its promise settles everything, so nothing here.
function wakeGlide({ instant }) {
if (!page.wake) return;
page.wake.cards = true;
if (instant) return;
page.wake.timers.push(
setTimeout(() => {
page.wake.entered = true;
settleWake();
}, WAKE_ENTRANCE_MS),
setTimeout(typeNote, WAKE_TYPE_DELAY_MS)
);
redraw();
}
// One more character of the note on the live element. Whatever the note says
// right now is what gets typed, so a `menu` note that lands mid-way simply
// carries on from the same count.
function typeNote() {
if (!page.wake || page.wake.typed == null) return;
page.wake.typed += 1;
const note = $("main").querySelector(":scope > .dash .dash-note");
if (!note || page.wake.typed >= revealNote(note, page.wake.typed)) {
page.wake.typed = null;
if (note) revealNote(note, Infinity);
return settleWake();
}
page.wake.timers.push(setTimeout(typeNote, WAKE_TYPE_EVERY_MS));
}
// Done once the entrance has played and the note is all there. Nothing to
// redraw: what is on screen already is the finished dashboard.
function settleWake() {
if (page.wake && page.wake.entered && page.wake.typed == null) {
page.wake = null;
hooks.maybeWelcome();
}
}
function finishWake() {
if (!page.wake) return;
for (const t of page.wake.timers) clearTimeout(t);
page.wake = null;
redraw();
}
// Shows the first `count` characters of a note's text, across its text nodes,
// and returns how many there are in all. The full text is kept per node the
// first time it is cut, so later calls can grow it back. An element the
// typing has not reached yet (the "still looking" pill and its spinner) is
// kept out of sight, rather than showing as an empty box.
const noteFullText = new WeakMap();
function revealNote(note, count) {
const walker = document.createTreeWalker(note, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
let total = 0;
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
if (n.nodeType === Node.ELEMENT_NODE) {
n.classList.toggle("is-untyped", total >= count);
continue;
}
if (!noteFullText.has(n)) noteFullText.set(n, n.data);
const full = noteFullText.get(n);
n.data = full.slice(0, Math.max(0, count - total));
total += full.length;
}
return total;
}
// A page-wide preference, so it rides in `looks` (looks.json) and follows the
// person to every session and port rather than resetting per dashboard.
function hideUnavailableToggle() {
const label = el("label", "dash-toggle");
const box = el("input");
box.type = "checkbox";
// The id is what lets withFocus hand focus back after the rebuild.
box.id = "dash-hide-unavailable";
box.setAttribute("role", "switch");
box.checked = looks.hideUnavailable;
box.addEventListener("change", () => {
looks.hideUnavailable = box.checked;
saveLooks();
redraw();
});
label.appendChild(box);
label.appendChild(el("span", "dash-toggle-track"));
label.appendChild(el("span", "dash-toggle-text", "Hide unavailable workflows"));
return label;
}
/* The spec picker: every spec the server found under specs/, plus "start
from scratch". The selection decides which cards below are lit, and rides
along on the launch of any card that takes a spec. Picking is page-local —
no send — so it costs nothing to change your mind. */
function renderSpecPicker(specs) {
const sel = selSpec();
const handoffs = handoffList();
const pickedHandoff = selHandoff();
const box = el("section", "spec-pick");
box.appendChild(
el("h3", "dash-group-title", handoffs.length ? "Pick up a spec or a handoff, or start fresh" : "Pick up a spec, or start fresh")
);
const row = el("div", "spec-row");
const scratchOn = !sel && !pickedHandoff;
const scratch = el("button", "spec-chip" + (scratchOn ? " is-sel" : ""));
scratch.type = "button";
scratch.setAttribute("aria-current", String(scratchOn));
scratch.appendChild(el("span", "spec-chip-name", "Start from scratch"));
scratch.appendChild(el("span", "spec-chip-state", "a new idea"));
scratch.addEventListener("click", () => {
page.local.specSel = null;
saveNow();
redraw();
loadOverview();
});
row.appendChild(scratch);
for (const spec of specs) {
const on = sel && sel.dir === spec.dir;
// A finished spec (a fixed bug) is hidden while unavailable workflows
// are, dimmed otherwise. A pick already on it stays visible, so it is
// never lost.
const fixed = Boolean(stateFor(spec.state)?.finished);
if (fixed && looks.hideUnavailable && !on) continue;
const deleting = Boolean(page.local.deleting && page.local.deleting.dir === spec.dir);
const wrap = el("div", "spec-chip-wrap" + (deleting ? " is-deleting" : "") + (fixed ? " is-fixed" : ""));
const b = el("button", "spec-chip" + (on ? " is-sel" : ""));
b.type = "button";
b.setAttribute("aria-current", String(Boolean(on)));
b.appendChild(el("span", "spec-chip-name", spec.name));
b.appendChild(el("span", "spec-chip-state", deleting ? "Deleting…" : SPEC_STATE_LABELS[spec.state] || spec.state));
const detail = chipDetail(spec);
if (detail) b.appendChild(el("span", "spec-chip-detail", detail));
b.addEventListener("click", () => {
page.local.specSel = spec.dir;
saveNow();
redraw();
loadOverview();
});
wrap.appendChild(b);
if (isDeletableSpecDir(spec.dir)) {
// A fixed bug is done with, so its Delete is a visible button rather
// than the hover ✕ every other spec has.
const del = fixed ? el("button", "spec-chip-del-label", "Delete") : el("button", "spec-chip-del", "✕");
del.type = "button";
del.title = `Delete ${spec.dir}/`;
del.setAttribute("aria-label", `Delete the spec ${spec.name}`);
del.disabled = deleting || Boolean(page.local.deleting) || page.gone || page.pendingResult || Boolean(page.local.launching);
del.addEventListener("click", () => openDeleteConfirm(spec));
wrap.appendChild(del);
}
row.appendChild(wrap);
}
// Handoffs follow the specs: dashed chips, the state word is "Handoff".
for (const h of handoffs) {
const on = Boolean(pickedHandoff && pickedHandoff.id === h.id);
const deleting = Boolean(page.local.deleting && page.local.deleting.dir === "handoff:" + h.id);
const b = el("button", "spec-chip is-handoff" + (on ? " is-sel" : "") + (deleting ? " is-deleting" : ""));
b.type = "button";
b.setAttribute("aria-current", String(on));
b.appendChild(el("span", "spec-chip-name", h.title || "Handoff"));
b.appendChild(el("span", "spec-chip-state", deleting ? "Deleting…" : "Handoff"));
b.appendChild(el("span", "spec-chip-detail", handoffAge(h.written)));
b.addEventListener("click", () => {
page.local.specSel = "handoff:" + h.id;
saveNow();
redraw();
});
row.appendChild(b);
}
box.appendChild(row);
return box;
}
// A delete in flight ends when the agent's rescan lands (a new scan), gone
// or refused: either way the picker is the truth again.
function settleDeleting() {
const sc = scan();
if (page.local.deleting && sc && sc.at !== page.local.deleting.scanAt) {
page.local.deleting = null;
saveNow();
}
}
// What a picked handoff shows: where it came from and its Next task, with the
// four things to do with it.
function renderHandoffPreview(h) {
const box = el("section", "handoff-preview");
box.appendChild(el("h3", "handoff-preview-title", h.title || "Handoff"));
const entry = SKILL_CATALOG.find((e) => e.skill === h.skill);
const meta = [
"Written " + (h.written ? new Date(h.written).toLocaleString() : "at an unknown time"),
h.spec ? "spec " + h.spec.replace(/^specs\//, "") : "no spec",
"from " + (entry ? entry.title : h.skill),
];
box.appendChild(el("p", "handoff-preview-meta", meta.join(" · ")));
if (h.next) {
box.appendChild(el("p", "handoff-preview-label", "Next task"));
box.appendChild(el("p", "handoff-preview-next", h.next));
}
const busy = Boolean(page.local.launching || page.local.deleting) || page.gone || page.pendingResult;
const actions = el("div", "handoff-preview-actions");
const go = el("button", "btn primary", "Pick it up here");
go.type = "button";
go.disabled = busy;
go.addEventListener("click", () => pickUpHandoff(h));
const read = el("button", "btn", "Read it all");
read.type = "button";
read.addEventListener("click", () => readHandoff(h));
const copy = el("button", "btn", "Copy for a new conversation");
copy.type = "button";
copy.addEventListener("click", () => {
const dir = (scan() && scan().handoffsDir) || "";
const sep = dir.includes("\\") ? "\\" : "/";
const file = dir ? dir.replace(/[\\/]+$/, "") + sep + h.id + ".md" : h.id + ".md";
copyHandoffText(handoffCopyText(file), copy);
});
const del = el("button", "btn danger", "Delete");
del.type = "button";
del.disabled = busy;
del.addEventListener("click", () => openHandoffDelete(h));
actions.append(go, read, copy, del);
box.appendChild(actions);
return box;
}
// The prompt that sends a new conversation to the handoff. A refused
// clipboard gets a plain word on the button instead of a silent nothing.
async function copyHandoffText(text, button) {
try {
await navigator.clipboard.writeText(text);
button.textContent = "Copied";
} catch {
button.textContent = "Copy was refused";
}
setTimeout(() => (button.textContent = "Copy for a new conversation"), 1500);
}
// Pick it up here: a hop like a card launch. The page sends only the id; the
// CLI reads the stored skill and spec, marks the handoff used and falls back
// to Quick Task if either is gone.
async function pickUpHandoff(h) {
if (page.gone || page.pendingResult || page.local.launching || finish()) return;
page.launchScoping = true;
await hooks.syncWorkspaceScope(h.spec || "");
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: [pickupAction(h)], reply: pickupReply(h) }),
});
if (res.status === 409) {
page.launchScoping = false;
page.pendingResult = true;
hooks.banner("Your last pick is still being picked up. One moment.", "info");
return;
}
if (!res.ok) throw new Error(String(res.status));
sound("startSkill");
page.local.launching = { skill: h.skill, title: h.title || "the handoff", at: Date.now() };
page.launchScoping = false;
page.pendingResult = true;
saveNow();
redraw();
} catch {
page.launchScoping = false;
hooks.banner("That did not go through. Nothing was lost; try again.", "warn");
}
}
// Read it all: the document, in a dialog, from /handoff?id= (served only for
// an id the dashboard's own scan listed).
async function readHandoff(h) {
$("handoff-title").textContent = h.title || "Handoff";
const body = $("handoff-body");
body.replaceChildren(el("p", "md-p", "Reading…"));
$("handoff-modal").showModal();
try {
const res = await fetch("/handoff?id=" + encodeURIComponent(h.id), { cache: "no-store" });
if (res.status !== 200) throw new Error(String(res.status));
mdInto(body, await res.text());
} catch {
body.replaceChildren(el("p", "md-p", "This handoff could not be read."));
}
}
function dashCard(entry, menu) {
const presentation = cardPresentation(entry, scan(), selSpec(), menu);
// The agent's `recommend` and detail describe the initially selected spec.
// Other picker choices derive both from the scan, so stale context never
// follows a person to a different spec or to "start from scratch". A greyed
// recommendation also yields to the selected spec's actual next step.
const going = page.local.launching && page.local.launching.skill === entry.skill;
const b = el(
"button",
"dash-card" + (presentation.recommended ? " is-suggested" : "") + (going ? " is-going" : "")
);
b.type = "button";
b.disabled = Boolean(page.local.launching) || page.gone || page.pendingResult || !presentation.on;
if (!presentation.on && presentation.reason) b.title = presentation.reason;
const head = el("span", "dash-card-head");
head.appendChild(el("span", "dash-chip", entry.chip));
if (presentation.recommended) head.appendChild(el("span", "pill suggested", "Suggested"));
b.appendChild(head);
b.appendChild(el("span", "dash-card-title", entry.title));
b.appendChild(el("span", "dash-card-blurb", entry.blurb));
if (presentation.detail) b.appendChild(el("span", "dash-card-detail", presentation.detail));
if (!presentation.on && presentation.reason) b.appendChild(el("span", "dash-card-off", presentation.reason));
const foot = el("span", "dash-card-foot");
foot.appendChild(el("code", "dash-card-cmd", entry.command));
foot.appendChild(el("span", "dash-card-go", going ? "…" : "→"));
b.appendChild(foot);
b.addEventListener("click", () => {
page.dashPick = entry;
redraw();
});
return b;
}
// The confirm pane. A card or rail click lands here rather than launching
// straight away: picking a skill is the one irreversible-feeling click on the
// dashboard, and it deserves a beat: what it is, what it will do, and a
// START that means it. Planny turns up leaning (his "this way" pose) in a
// small sky, because a bare paragraph with two buttons is a dialog, not a
// moment. BACK returns to the menu; Escape does the same (see the global
// keydown in core.js).
export function renderConfirm(main, entry) {
const menu = (page.S && page.S.menu) || {};
const presentation = cardPresentation(entry, scan(), selSpec(), menu);
const pane = el("div", "dash-confirm");
const stage = el("div", "launch-stage confirm-stage");
const sky = el("div", "sky launch-sky");
const r = (a, b) => a + Math.random() * (b - a);
for (let i = 0; i < 16; i++) {
const star = el("i", "star" + (i % 5 === 0 ? " hot" : ""));
const dur = r(4, 10);
star.style.setProperty("--y", r(2, 98).toFixed(1) + "%");
star.style.setProperty("--p", r(0, 1).toFixed(3));
star.style.setProperty("--s", r(1.2, 2.4).toFixed(2) + "px");
star.style.setProperty("--dur", dur.toFixed(2) + "s");
star.style.setProperty("--delay", (-r(0, dur)).toFixed(2) + "s");
sky.appendChild(star);
}
stage.appendChild(sky);
const bot = $("planny").cloneNode(true);
bot.removeAttribute("id");
bot.setAttribute("class", "planny is-point v0 confirm-planny");
stage.appendChild(bot);
pane.appendChild(stage);
const head = el("div", "confirm-head");
head.appendChild(el("span", "dash-chip", entry.chip));
if (presentation.recommended) head.appendChild(el("span", "pill suggested", "Suggested"));
pane.appendChild(head);
pane.appendChild(el("h2", "dash-title", entry.title));
pane.appendChild(el("p", "confirm-about", entry.about || entry.blurb));
if (presentation.detail) pane.appendChild(el("p", "confirm-detail", presentation.detail));
// A card that takes a spec names the one the picker is holding, so START
// reads as "build THIS spec", not the skill in the abstract.
const target = launchTarget(entry, selSpec());
if (target) {
const specLine = el("p", "confirm-spec");
specLine.appendChild(el("span", null, "for "));
specLine.appendChild(el("code", null, target.dir));
specLine.appendChild(el("span", null, ` · ${SPEC_STATE_LABELS[target.state] || target.state}`));
pane.appendChild(specLine);
}
const cmd = el("p", "confirm-cmd");
cmd.appendChild(el("code", null, entry.command));
pane.appendChild(cmd);
const actions = el("div", "confirm-actions");
const start = el("button", "btn primary", "Start " + entry.title);
start.type = "button";
start.disabled = page.gone || page.pendingResult;
start.addEventListener("click", () => launchSkill(entry));
const back = el("button", "btn ghost", "Back");
back.type = "button";
back.addEventListener("click", () => {
page.dashPick = null;
redraw();
});
actions.appendChild(back);
actions.appendChild(start);
pane.appendChild(actions);
main.appendChild(pane);
// Focus lands on START after a pick (the clicked control was rebuilt away,
// leaving focus on <body>), but never yanked back from a deliberate click
// elsewhere: a state frame can re-render this pane at any time.
if (document.activeElement === document.body) start.focus();
}
// A pick is a send like a brief or a stop: it names no question, so `__launch`
// marks the action as being about the session, and it reaches the agent
// through the same wait loop. The dashboard reads `skill` off it.
async function launchSkill(entry) {
if (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
// one tab could have shifted the ground under a stale render in another.
if (!cardAvailability(entry, scan(), selSpec()).on) {
hooks.banner("That card is not available for the spec you picked.", "warn");
redraw();
return;
}
page.dashPick = null;
const action = {
i: "__launch",
type: "launch",
skill: entry.skill,
workflow: entry.workflow,
title: entry.title,
};
// The picker's spec goes to the skill being launched, not to the card:
// cards that take no spec (utilities, setup) launch untargeted even while
// a spec is selected, save Quick Task on a diagnosed bug.
if (target) action.spec = target.dir;
// The skill opens on the folders remembered for what it was launched for.
// Held until the launch is in flight: the swap's own frame re-renders the
// dashboard, which would otherwise sync back to the picker's spec.
page.launchScoping = true;
await hooks.syncWorkspaceScope(target ? target.dir : "");
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
actions: [action],
reply: launchReply(entry, target),
}),
});
if (res.status === 409) {
page.launchScoping = false;
page.pendingResult = true;
hooks.banner("Your last pick is still being picked up. One moment.", "info");
return;
}
if (!res.ok) throw new Error(String(res.status));
sound("startSkill");
page.local.launching = { skill: entry.skill, title: entry.title, at: Date.now() };
page.launchScoping = false;
page.pendingResult = true;
saveNow();
redraw();
} catch {
page.launchScoping = false;
hooks.banner("That did not go through. Nothing was lost; try again.", "warn");
}
}
// The picker's Delete: a dialog in two steps. The first says what goes and
// that it is for good; "Delete this spec…" then reveals the second, which
// enables the final button only once the spec's name is typed exactly. A
// fixed bug skips the second step: its first press sends the delete.
// Cancel, Escape or a click on Keep it at either step changes nothing.
let deleteTarget = null;
// The spec warning as index.html writes it, kept so a fixed bug's wording
// never sticks for the next spec.
let deleteWarnDefault = null;
// A handoff's Delete reuses the same dialog in one step: no name to type, and
// the warning says where the file lives instead of what git does not track.
function openHandoffDelete(h) {
if (page.gone || page.pendingResult || page.local.launching || page.local.deleting) return;
deleteTarget = { handoff: h };
$("delete-title").textContent = "Delete this handoff?";
$("delete-blurb").textContent = "This handoff will be deleted from ~/.plan2code/handoffs/.";
$("delete-warn").hidden = true;
$("delete-warn-handoff").hidden = false;
const facts = $("delete-facts");
facts.replaceChildren();
const fact = (term, value) => {
if (!value) return;
facts.appendChild(el("dt", "", term));
facts.appendChild(el("dd", "", value));
};
const entry = SKILL_CATALOG.find((e) => e.skill === h.skill);
fact("Handoff", h.title || h.id);
fact("Written", h.written ? new Date(h.written).toLocaleString() : "");
fact("Spec", h.spec ? h.spec.replace(/^specs\//, "") : "");
fact("From", entry ? entry.title : h.skill);
$("delete-confirm").hidden = true;
const go = $("delete-go");
go.textContent = "Delete it";
go.classList.add("is-on");
go.disabled = false;
$("delete-modal").showModal();
}
function openDeleteConfirm(spec) {
if (!isDeletableSpecDir(spec.dir) || page.gone || page.pendingResult || page.local.launching || page.local.deleting) return;
deleteTarget = spec;
// A finished spec (a fixed bug): one confirm, and a warning that says so.
const fixed = Boolean(stateFor(spec.state)?.finished);
$("delete-title").textContent = "Delete this spec?";
const warn = $("delete-warn");
if (!deleteWarnDefault) deleteWarnDefault = [...warn.childNodes].map((n) => n.cloneNode(true));
warn.replaceChildren(
...(fixed
? ["The bug is fixed, so this only clears the write-up. ", el("code", "", "specs/"), " is not tracked by git, so it cannot be brought back."]
: deleteWarnDefault.map((n) => n.cloneNode(true)))
);
warn.hidden = false;
$("delete-warn-handoff").hidden = true;
const sum = deleteSummary(spec);
$("delete-blurb").textContent = `Everything in ${sum.folder} will be deleted from this project.`;
const facts = $("delete-facts");
facts.replaceChildren();
const fact = (term, value) => {
if (!value) return;
facts.appendChild(el("dt", "", term));
facts.appendChild(el("dd", "", value));
};
fact("Spec", spec.name);
fact("Folder", sum.folder);
fact("Stage", sum.stage);
fact("Files", sum.files);
fact("Last changed", sum.touched ? new Date(sum.touched).toLocaleString() : "");
$("delete-name-hint").textContent = spec.name;
$("delete-name").value = "";
$("delete-confirm").hidden = true;
const go = $("delete-go");
go.textContent = fixed ? "Delete it" : "Delete this spec…";
go.classList.toggle("is-on", fixed);
go.disabled = false;
$("delete-modal").showModal();
}
function deleteStep() {
const go = $("delete-go");
if (!deleteTarget) return;
if (deleteTarget.handoff) return sendDeleteHandoff(deleteTarget.handoff);
if (stateFor(deleteTarget.state)?.finished) return sendDelete(deleteTarget);
if ($("delete-confirm").hidden) {
$("delete-confirm").hidden = false;
go.textContent = "Delete for good";
go.classList.add("is-on");
go.disabled = true;
$("delete-name").focus();
return;
}
if ($("delete-name").value.trim() !== deleteTarget.name) return;
sendDelete(deleteTarget);
}
async function sendDeleteHandoff(h) {
const go = $("delete-go");
go.disabled = true;
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: [deleteHandoffAction(h)], reply: deleteHandoffReply(h) }),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
const sc = scan();
page.local.deleting = { dir: "handoff:" + h.id, scanAt: sc ? sc.at : null };
if (page.local.specSel === "handoff:" + h.id) delete page.local.specSel;
page.pendingResult = true;
saveNow();
$("delete-modal").close();
} catch (err) {
$("delete-modal").close();
if (err && err.pending) page.pendingResult = true;
hooks.banner(
err && err.pending
? "Your last pick is still being picked up, so that could not go yet. Nothing was deleted; try again in a moment."
: "That did not go through. Nothing was deleted; try again.",
"warn"
);
} finally {
deleteTarget = null;
redraw();
}
}
async function sendDelete(spec) {
const go = $("delete-go");
go.disabled = true;
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: [deleteAction(spec)], reply: deleteReply(spec) }),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
const sc = scan();
page.local.deleting = { dir: spec.dir, scanAt: sc ? sc.at : null };
// The selection must not outlive the folder: back to the default pick,
// which the agent's fresh menu recommends for.
if (page.local.specSel === spec.dir) delete page.local.specSel;
page.pendingResult = true;
saveNow();
$("delete-modal").close();
} catch (err) {
$("delete-modal").close();
if (err && err.pending) page.pendingResult = true;
hooks.banner(
err && err.pending
? "Your last pick is still being picked up, so that could not go yet. Nothing was deleted; try again in a moment."
: "That did not go through. Nothing was deleted; try again.",
"warn"
);
} finally {
deleteTarget = null;
redraw();
}
}
// The dialogs' buttons, wired once at start-up: the update notice's Done, the
// handoff preview's close, and the delete dialog's Cancel, name box and go.
export function wireDashboard() {
$("update-done").addEventListener("click", () => $("update-modal").close());
$("delete-cancel").addEventListener("click", () => $("delete-modal").close());
$("handoff-close").addEventListener("click", () => $("handoff-modal").close());
$("delete-go").addEventListener("click", deleteStep);
$("delete-name").addEventListener("input", () => {
$("delete-go").disabled = !deleteTarget || $("delete-name").value.trim() !== deleteTarget.name;
});
$("delete-name").addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
deleteStep();
}
});
$("delete-modal").addEventListener("close", () => {
deleteTarget = null;
});
}
+229
View File
@@ -0,0 +1,229 @@
// Plan2Code Web Console - documents: tabs, blocks, print and download, and the brief button; defines only.
import { docs, agentWorking, workingMs, patience, WORKING_GRACE_MS, finish } from "../selectors.js";
import { el, md } from "../render.js";
import { downloadDocHtml, docSavedNote, downloadDoc, blockBody } from "../doc-files.js";
import { hooks, page, redraw } from "../state.js";
const $ = (id) => document.getElementById(id);
import { sendState } from "../send-state.js";
import { briefPhrase } from "../answers.js";
let docObserver = null;
// A brief is a Pathfinder thing: a plain-English report of the decisions made
// in a date range, the ones still open, and what happens next. It is the
// artifact someone takes to a meeting, and the reason a non-engineer is in this
// session at all, so it should not need knowing that you can type "brief" at a
// terminal to get one.
//
// The request travels as an ordinary send. The agent's own wait loop returns
// it, `reply` carries the range in the grammar its playbook already parses, and
// the finished brief comes back as a doc like any other.
const BRIEF_RANGES = {
today: "today",
"this week": "this week",
full: "full",
};
function briefRange() {
const picked = document.querySelector('input[name="brief-range"]:checked');
const value = picked ? picked.value : "today";
if (value !== "since") return { range: BRIEF_RANGES[value] || "today" };
const on = $("brief-since").value;
if (!on) return { problem: "Pick the date to count from, or choose another range." };
if (on > localDay()) return { problem: "Pick a date that has already happened: a brief covers what was decided since then." };
return { range: `since ${on}` };
}
function openBrief() {
const why = $("brief-why");
why.textContent = "";
syncBriefDate();
$("brief-modal").showModal();
}
// The date only means anything for "since", so it is dimmed and inert until
// that is the choice, rather than sitting there inviting a value it will ignore.
function syncBriefDate() {
const picked = document.querySelector('input[name="brief-range"]:checked');
const on = Boolean(picked && picked.value === "since");
const row = document.querySelector(".since-row");
const input = $("brief-since");
row.classList.toggle("is-off", !on);
input.disabled = !on;
input.max = localDay();
}
// Today as YYYY-MM-DD in the person's own time zone, the shape a date input uses.
function localDay(d = new Date()) {
const p = (n) => String(n).padStart(2, "0");
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
}
export async function sendBrief() {
const choice = briefRange();
const why = $("brief-why");
if (choice.problem) {
why.textContent = choice.problem;
return;
}
const state = sendState();
// The same guard the Send button uses. A brief is a turn like any other, and
// two turns in flight is the one thing this protocol will not do.
if (page.gone || page.pendingResult || (agentWorking() && workingMs() <= patience(WORKING_GRACE_MS))) {
why.textContent = state.why || "Wait for Plan2Code to finish, then ask again.";
return;
}
const go = $("brief-go");
go.disabled = true;
go.textContent = "Asking…";
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
actions: [{ i: "__brief", type: "brief", range: choice.range }],
reply: briefPhrase(choice.range),
}),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
$("brief-modal").close();
hooks.banner("Asked for a brief. It will appear as a tab when it is written.", "good");
setTimeout(() => hooks.banner(null), 5000);
page.pendingResult = true;
redraw();
} catch (err) {
if (err && err.pending) page.pendingResult = true;
why.textContent =
err && err.pending
? "Your last answers are still being picked up. Try again in a moment."
: "That did not go through. Try again in a moment.";
} finally {
go.disabled = false;
go.textContent = "Write the brief";
}
}
export function renderBriefButton() {
const btn = $("btn-brief");
// Only Pathfinder has a brief playbook. Offering the button anywhere else
// would send the agent a request it has no procedure for.
const offer = page.S && page.S.workflow === "pathfinder";
btn.hidden = !offer;
// A finished (or paused) session has nobody to write it: the request would
// wait on disk for a session that may never come.
if (offer) btn.disabled = page.gone || page.pendingResult || Boolean(finish());
}
export function renderDoc(main, id) {
const doc = docs().find((d) => d.id === id);
if (!doc) {
main.appendChild(el("p", "doc-empty", "That document is not ready yet."));
return;
}
const head = el("div", "doc-head");
head.appendChild(el("h2", null, doc.title || "Document"));
head.appendChild(el("span", "doc-version", "v" + (doc.version || 1)));
if (doc.stale) {
head.appendChild(el("span", "pill staged", "Out of date"));
}
const tools = el("div", "doc-tools");
// A brief is handed to people who were not in the room, so it gets a copy
// that opens in any browser, formatting and all.
if (doc.id === "brief") {
const html = el("button", "btn small", "Save as HTML");
html.type = "button";
html.addEventListener("click", () => downloadDocHtml(doc));
tools.appendChild(html);
}
tools.appendChild(printButton());
if (doc.saved) {
tools.appendChild(docSavedNote(doc));
} else {
const save = el("button", "btn small", "Download");
save.type = "button";
save.addEventListener("click", () => downloadDoc(doc));
tools.appendChild(save);
}
head.appendChild(tools);
main.appendChild(head);
if (doc.note) main.appendChild(el("p", "help", doc.note));
const blocks = doc.blocks || [];
if (!blocks.length) {
main.appendChild(el("p", "doc-empty", "Nothing written yet. It fills in as you answer."));
return;
}
// The block nearest the top of the column is the section + Add context
// offers after leaving this tab. Its label is its first heading.
docObserver?.disconnect();
if (page.docInView && page.docInView.docId !== doc.id) page.docInView = null;
const boxes = [];
const topmost = () => {
const top = main.getBoundingClientRect().top;
const box = boxes.find((x) => x.getBoundingClientRect().bottom > top + 1);
if (!box) return;
const heading = box.querySelector("h1, h2, h3, h4, h5, h6");
page.docInView = {
docId: doc.id,
blockId: box.dataset.block,
label: (heading && heading.textContent.trim()) || doc.title || "Document",
};
};
docObserver = typeof IntersectionObserver === "function" ? new IntersectionObserver(topmost, { root: main, threshold: [0, 0.25, 0.5, 0.75, 1] }) : null;
blocks.forEach((b, i) => {
const box = el("div", "block " + (b.state || "settled"));
box.dataset.block = b.id || String(i);
boxes.push(box);
docObserver?.observe(box);
if (b.state === "assumed") {
// Borrowed from grill-with-ui and the best idea in it: show plainly which
// parts are still a guess, so nobody mistakes a placeholder for a decision.
box.appendChild(el("span", "block-tag", "Assumed for now, still open"));
}
if (b.state === "draft") box.appendChild(el("span", "block-tag", "Draft"));
box.appendChild(blockBody(b));
main.appendChild(box);
});
}
function printButton() {
const print = el("button", "btn small", "Print");
print.type = "button";
// The print stylesheet drops everything that steers the session, so what
// comes out is the document alone. "Save as PDF" in that dialog is also the
// most portable save this page can offer.
print.addEventListener("click", () => window.print());
return print;
}
// The spec's overview.md, read-only and drawn through the same markdown path
// as every doc. No Download: the file is already on disk.
export function renderOverview(main) {
const head = el("div", "doc-head");
head.appendChild(el("h2", null, "Overview"));
const tools = el("div", "doc-tools");
tools.appendChild(printButton());
head.appendChild(tools);
main.appendChild(head);
main.appendChild(el("p", "help", `${page.overview.key}/overview.md · read-only, straight from disk`));
const box = el("div", "block settled");
box.appendChild(md(page.overview.text, "md"));
main.appendChild(box);
}
// The brief dialog's buttons, wired once at start-up.
export function wireDocs() {
$("btn-brief").addEventListener("click", openBrief);
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
$("brief-go").addEventListener("click", sendBrief);
for (const radio of document.querySelectorAll('input[name="brief-range"]')) {
radio.addEventListener("change", syncBriefDate);
}
}
+726
View File
@@ -0,0 +1,726 @@
// Plan2Code Web Console - how a session ends: the finished screen, its offers, Stop and the way home; defines only.
import { el, md, copyButton, textWithCode, SVG_NS } from "../render.js";
import {
finishPaused,
reviewOffer,
commitOffer,
handoffShape,
ALL_DONE_LEAD,
ALL_DONE_REST,
handoffText,
DASHBOARD_COMMAND,
resumeCommand,
afterFinishButton,
DASHBOARD_NOTE,
turnGate,
homeButtonState,
HOME_REPLY,
stopAction,
STOP_HANDOFF_REPLY,
STOP_REPLY,
REVIEW_REPLY,
DONE_REPLY,
DASHBOARD_REPLY,
COMMIT_REPLY,
} from "../answers.js";
import { hooks, page, saveNow, redraw } from "../state.js";
const $ = (id) => document.getElementById(id);
import {
dashboardLive,
reviewPending,
docs,
finish,
agentAdrift,
agentWorking,
awaitingReply,
isDashboard,
} from "../selectors.js";
import { docSavedNote, downloadDoc } from "../doc-files.js";
import { pendingNotes } from "../uploads.js";
// The end of the session, and the only screen in this page whose job is to
// send someone somewhere else.
//
// It reads in three beats, because that is the order the questions arrive in:
// what just happened, the one thing to run, and where to run it. The command
// is the whole point, so its Copy button is always on show -- the one on a
// fenced code block only appears on hover, which is right for a sample buried
// in prose and useless for the single action a screen exists to offer. A
// finish with nothing left to run skips the last two beats: it gets a quiet
// pointer at the dashboard instead of a Next step block.
// "Before you close this": the three things someone looking at a finished
// screen wonders. Every finish shape gets it; a pause says where the place is
// kept, and a session with nothing left to run points at the dashboard alone.
const GUIDE_ICONS = {
safe: ["M5 12.5 10 17.5 19 7"],
fresh: ["M19.5 12a7.5 7.5 0 1 1-2.4-5.5", "M19.5 4v4.5H15"],
carry: ["M5 12h13", "M13 6.5 18.5 12 13 17.5"],
};
function guideIcon(kind) {
const wrap = el("span", `handoff-guide-icon is-${kind}`);
wrap.setAttribute("aria-hidden", "true");
const svg = document.createElementNS(SVG_NS, "svg");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("width", "16");
svg.setAttribute("height", "16");
for (const d of GUIDE_ICONS[kind]) {
const path = document.createElementNS(SVG_NS, "path");
path.setAttribute("d", d);
svg.appendChild(path);
}
wrap.appendChild(svg);
return wrap;
}
function renderCloseGuide(shape, fin = {}) {
// A command that is not a skill (a finish's git commit) runs in a terminal,
// not "in the new session".
const shell = typeof fin.command === "string" && Boolean(fin.command.trim()) && !fin.command.trim().startsWith("/");
const panel = el("section", "handoff-guide");
panel.setAttribute("aria-labelledby", "handoff-guide-title");
const title = el("h3", "handoff-guide-title", "Before you close this");
title.id = "handoff-guide-title";
panel.appendChild(title);
const rows = [
["safe", "Safe to close", "This tab is only a window: whatever this session wrote is on disk, and nothing here needs you."],
[
"fresh",
"Start fresh",
shape === "paused"
? stopWarning()
? "Restart your agent window, or close the old session and start a new one. The command above starts it again."
: "Restart your agent window, or close the old session and start a new one. Your saved place is picked up by the resume command above."
: "Restart your agent window, or close the old session and start a new one. A new session starts from clean context. This one is full of this step's instructions, so continuing in it is slower and can confuse the next step.",
],
[
"carry",
"Carry on",
shape === "all-done"
? `In the new session, start from the dashboard with \`${DASHBOARD_COMMAND}\`.`
: shell
? `Run the command above in your terminal, then start the next step from the dashboard with \`${DASHBOARD_COMMAND}\`.`
: `Paste the command above in the new session, or start from the dashboard with \`${DASHBOARD_COMMAND}\`.`,
],
];
const list = el("ul", "handoff-guide-rows");
for (const [kind, label, text] of rows) {
const row = el("li", "handoff-guide-row");
row.appendChild(guideIcon(kind));
const body = el("div", "handoff-guide-text");
body.appendChild(el("strong", "handoff-guide-label", label));
body.appendChild(document.createTextNode(" "));
body.appendChild(textWithCode("span", "handoff-guide-line", text));
row.appendChild(body);
list.appendChild(row);
}
panel.appendChild(list);
return panel;
}
// A review, a commit in Git or the dashboard the person just asked for is starting
// here, so the page is about to carry on rather than end.
function closeGuideHeld() {
if (page.gone) return false;
return ["review", "commit", "dashboard"].includes(page.local.afterBuild) || reviewPending() === "asked";
}
export function renderHandoff(fin) {
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));
if (fin.body) card.appendChild(md(fin.body, "md prompt"));
// A finished build offers its review first, above the next step, because it
// is the one thing on this screen that has to happen before they leave.
const offer = reviewOffer(fin);
if (offer && !["done", "dashboard", "commit"].includes(page.local.afterBuild)) {
card.appendChild(renderReviewOffer(offer));
}
// The commit, right after the review: one press starts Git's commit flow here.
if (commitOffer(fin) && !page.gone && page.local.afterBuild !== "done" && page.local.afterBuild !== "dashboard") {
card.appendChild(renderCommitOffer());
}
// Three shapes: a next step to run, a pause with its resume command, or a
// session with nothing left to run, which gets a quiet pointer at the
// dashboard instead of a Next step block.
const shape = handoffShape(fin);
if (shape === "all-done") {
const done = el("div", "handoff-done");
done.appendChild(md(`${ALL_DONE_LEAD} ${ALL_DONE_REST}`, "md handoff-done-text"));
const text = handoffText({ command: DASHBOARD_COMMAND });
const row = el("div", "handoff-command");
const code = el("code", "handoff-code", text);
row.appendChild(code);
row.appendChild(copyButton(text, "btn small ghost handoff-copy", code));
done.appendChild(row);
// Once the server is gone, the row above already is the offer's fallback.
if (dashboardLive(fin) && !page.gone) done.appendChild(renderDashboardOffer(true));
card.appendChild(done);
} else {
// A pause always offers its resume command, even when the agent left it out.
const command =
String(fin.command || "").trim() || resumeCommand({ workflow: page.S.workflow, specDir: page.S.specDir });
const step = el("div", "handoff-step");
step.appendChild(el("p", "handoff-label", "Next step"));
step.appendChild(
el(
"p",
"handoff-where",
fin.where ||
(command.startsWith("/")
? "Run this in the terminal where you started Plan2Code, in a new conversation:"
: "Run this in your terminal:")
)
);
// Shown exactly as copied. Nothing goes on the clipboard that they cannot
// read first: it is about to be pasted into a program with their files.
const text = handoffText({ ...fin, command });
const row = el("div", "handoff-command");
const code = el("code", "handoff-code", text);
row.appendChild(code);
row.appendChild(copyButton(text, "btn small handoff-copy", code));
step.appendChild(row);
if (text !== command) {
step.appendChild(
el(
"p",
"handoff-note",
"The --web at the end asks Plan2Code to open this page again, so you carry on here rather than in the terminal."
)
);
}
card.appendChild(step);
// A finished (never paused) screen always names the way to the dashboard
// from a new conversation, unless the offer's own fallback already does.
if (shape === "next") {
const offerDash = dashboardLive(fin);
if (offerDash) card.appendChild(renderDashboardOffer(false));
if (!(offerDash && page.gone)) {
card.appendChild(
textWithCode(
"p",
"handoff-fresh",
`To start something else, run \`${DASHBOARD_COMMAND}\` in a new conversation.`
)
);
const freshText = handoffText({ command: DASHBOARD_COMMAND });
const freshRow = el("div", "handoff-command handoff-fresh-row");
const freshCode = el("code", "handoff-code", freshText);
freshRow.appendChild(freshCode);
freshRow.appendChild(copyButton(freshText, "btn small ghost handoff-copy", freshCode));
card.appendChild(freshRow);
}
}
}
// Not while a hand-off they just asked for is starting on this page: "Safe
// to close" and "start a new one" would contradict the line above it. The
// press re-renders the page, and so does the agent taking it up.
if (!closeGuideHeld()) card.appendChild(renderCloseGuide(shape, fin));
card.appendChild(
el(
"p",
"handoff-close",
reviewPending() === "open"
? "The review is optional. Skip it and nothing else here needs you."
: "That is everything on this page."
)
);
// What they were working on is on disk, but only the agent's copy is. This
// is the last moment anyone is looking at this page, so the way to take the
// document with them belongs here and not only behind a tab they may never
// open again — unless the doc is `saved`, in which case the file itself is
// already on disk and a download would be a second copy of it.
const keep = docs().find((d) => d.id === fin.doc) || docs()[0];
if (keep && (keep.blocks || []).length) {
const tools = el("div", "handoff-tools");
if (keep.saved) {
tools.appendChild(docSavedNote(keep));
} else {
const save = el("button", "btn small", `Download ${keep.title || "the document"}`);
save.type = "button";
save.addEventListener("click", () => downloadDoc(keep));
tools.appendChild(save);
}
card.appendChild(tools);
}
// Answers staged and never sent are lost the moment this page closes, and
// this page's one promise is that nothing gets lost. Say so plainly rather
// than letting them walk away from work they thought was safe.
const stuck = Object.keys(page.local.staged).length;
if (stuck) {
card.appendChild(
el(
"p",
"handoff-unsent",
`${stuck} answer${stuck === 1 ? "" : "s"} here ${stuck === 1 ? "was" : "were"} never sent, ` +
`and Plan2Code has finished. If ${stuck === 1 ? "it" : "they"} still matter, say so in the ` +
`next session: nothing on this page will reach it now.`
)
);
}
return card;
}
// The review button, on the hand-off of a finished build (a finished quick
// task; an implementation phase gets its review offer earlier, as a verdict
// on the sign-off card).
//
// It is a request, not a command: the page cannot run a review, it asks the
// agent that is still sitting in its wait loop, the same way "Write a brief"
// does. So it is only offered while there is a server to carry the press, and
// once there is not, it turns into the command that does the same thing from
// the terminal instead of a button that would go nowhere.
function renderReviewOffer(offer) {
const box = el("section", "review-offer");
box.appendChild(el("p", "handoff-label", "Before you go"));
box.appendChild(el("h3", "review-offer-title", offer.label));
const { asked, disabled } = afterFinishButton(page.local.afterBuild, "review", page.pendingResult);
if (page.gone) {
box.appendChild(
el(
"p",
"review-offer-text",
asked
? "The session closed before the review could start. To run it now, use this in the terminal, in a new conversation:"
: "This session has closed, so the review cannot start from here any more. To run it, use this in the terminal, in a new conversation:"
)
);
const text = "/plan2code-review";
const row = el("div", "handoff-command");
const code = el("code", "handoff-code", text);
row.appendChild(code);
row.appendChild(copyButton(text, "btn small handoff-copy", code));
box.appendChild(row);
return box;
}
box.appendChild(
el(
"p",
"review-offer-text",
"A careful review of the files this session changed: bugs, gaps against what was asked for, and anything risky. " +
"The findings come back on this page and you choose which ones get fixed. Nothing changes until you do."
)
);
const row = el("div", "btn-row");
const go = el("button", "btn primary review-go", asked ? "Review requested…" : "Review it now");
go.type = "button";
go.disabled = disabled;
go.addEventListener("click", () => sendAfterBuild("review"));
row.appendChild(go);
if (!asked) {
const no = el("button", "btn ghost", "No thanks, I am done");
no.type = "button";
no.disabled = disabled;
no.addEventListener("click", () => sendAfterBuild("done"));
row.appendChild(no);
}
box.appendChild(row);
return box;
}
// Commit what was just built without leaving the page. Like the review button
// it is a request to an agent still in its wait loop, so it is only drawn
// while the server is there; the command printed below stays for the terminal.
function renderCommitOffer() {
const box = el("section", "review-offer");
box.appendChild(el("p", "handoff-label", "Commit it"));
box.appendChild(
el(
"p",
"review-offer-text",
"Git reads what changed, drafts the message and asks before it commits. It opens right here, on the git board."
)
);
const { asked, disabled } = afterFinishButton(page.local.afterBuild, "commit", page.pendingResult);
const row = el("div", "btn-row");
const go = el("button", "btn primary", asked ? "Opening Git…" : "Commit it now");
go.type = "button";
go.disabled = disabled;
go.addEventListener("click", () => sendAfterBuild("commit"));
row.appendChild(go);
box.appendChild(row);
return box;
}
// The way back to the dashboard, on a finished screen whose agent opted in
// with `finish.dashboard`. Like the review button it is a request to an agent
// still in its wait loop, so once the server is gone it turns into the
// command that opens the dashboard from a new conversation instead.
function renderDashboardOffer(primary) {
const box = el("section", "dashboard-offer");
if (page.gone) {
box.appendChild(
el(
"p",
null,
"This session has closed, so the button cannot reach Plan2Code any more. To open the dashboard, run this in a new conversation:"
)
);
const text = handoffText({ command: DASHBOARD_COMMAND });
const row = el("div", "handoff-command");
const code = el("code", "handoff-code", text);
row.appendChild(code);
row.appendChild(copyButton(text, "btn small handoff-copy", code));
box.appendChild(row);
return box;
}
const { asked, disabled } = afterFinishButton(page.local.afterBuild, "dashboard", page.pendingResult);
const go = el(
"button",
primary ? "btn primary" : "btn",
asked ? "Opening the dashboard…" : "Back to the dashboard"
);
go.type = "button";
go.disabled = disabled;
go.addEventListener("click", () => sendAfterBuild("dashboard"));
box.appendChild(go);
box.appendChild(textWithCode("p", "dashboard-note", DASHBOARD_NOTE));
return box;
}
// Any answer to a finished session's offers, as one send through the ordinary
// submit. Like a brief, it names no question: `__review`, `__commit`, `__done`
// and `__dashboard` are about the session.
const AFTER_FINISH_REPLIES = { review: REVIEW_REPLY, done: DONE_REPLY, dashboard: DASHBOARD_REPLY, commit: COMMIT_REPLY };
async function sendAfterBuild(kind) {
if (page.gone || page.pendingResult || page.local.afterBuild) return;
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
actions: [{ i: `__${kind}`, type: kind }],
reply: AFTER_FINISH_REPLIES[kind],
}),
});
if (res.status === 409) {
page.pendingResult = true;
hooks.banner("Your last answers are still being picked up. Try again in a moment.", "info");
return;
}
if (!res.ok) throw new Error(String(res.status));
page.local.afterBuild = kind;
page.pendingResult = true;
saveNow();
const started = {
review: "Review requested. It starts here in a moment.",
dashboard: "Opening the dashboard. It appears here in a moment.",
commit: "Opening Git. It appears here in a moment.",
}[kind];
if (started) {
hooks.banner(started, "good");
setTimeout(() => hooks.banner(null), 5000);
}
} catch {
hooks.banner("That did not go through. Nothing was lost; try again.", "warn");
} finally {
redraw();
}
}
let stoppingHidden = false;
// A stop is under way if this browser sent one, or if the server is holding
// one nobody has collected: the second covers a reload on a resumed session,
// a second tab, another machine.
export function stopInProgress() {
return page.local.stopping || (page.pendingStop ? { at: 0, answers: 0 } : null);
}
export function renderStopButton() {
const b = $("btn-stop");
if (!page.S || finish()) {
b.hidden = true;
return;
}
b.hidden = false;
if (stopInProgress()) {
b.textContent = "Stopping…";
b.disabled = false;
b.title = "Show how the stop is going";
return;
}
b.textContent = "Stop session";
// Only on the person's turn, unless nothing is coming (see turnGate).
const gate = turnGate({ gone: 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 = {
gone: "Not connected right now.",
pending: "Your last answers are still being picked up. You can stop once they have been.",
waiting: "Plan2Code is working on your answers. You can stop once it replies.",
}[gate] || (stopWarning() ? "End this session. Work since the last save is not kept." : "Save your place and end this session. You get a command to pick it up later.");
}
// Plan2Code has the ball: it is working, or owes a reply to a send, and has
// not gone quiet. What both session buttons wait out.
function agentHasTheBall() {
return (agentWorking() || awaitingReply().length > 0) && !agentAdrift();
}
// The triangle left of Stop session. Mid-workflow it is a stop that lands on
// the menu instead of a finish: the same staged answers ride along, the agent
// saves its place the same way, then resumes the session as the dashboard.
export function renderHomeButton() {
const b = $("btn-home");
const st = homeButtonState({
workflow: page.S && page.S.workflow,
finished: Boolean(page.S && finish()),
stopping: Boolean(page.S && stopInProgress()),
homeward: Boolean(page.local.homeward),
adrift: Boolean(page.S) && agentAdrift(),
gone: page.gone,
pendingResult: page.pendingResult,
waiting: Boolean(page.S) && agentHasTheBall(),
warned: Boolean(page.S) && Boolean(stopWarning()),
});
b.hidden = st.hidden;
b.disabled = st.disabled;
b.title = st.title;
}
function openHomeConfirm() {
const n = Object.keys(page.local.staged).length + pendingNotes().length;
const warn = stopWarning();
// With a warning, "your place is saved" is the one thing not true: the
// warning says what is lost, and the button says the choice is theirs.
$("home-blurb").textContent =
(n === 1 ? "The answer you have ready goes with it. " : n ? `The ${n} answers you have ready go with it. ` : "") +
(warn ? "Plan2Code takes you back to the dashboard." : "Your place is saved; you can resume it from the dashboard.");
$("home-go").textContent = warn ? "Leave anyway" : "Back to the dashboard";
$("home-warn").hidden = !warn;
$("home-warn").textContent = warn;
$("home-modal").showModal();
}
async function goHome() {
const go = $("home-go");
go.disabled = true;
const payload = hooks.stagedPayload();
payload.actions.push({ i: "__dashboard", type: "dashboard" });
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: payload.actions, reply: [...payload.replyLines, HOME_REPLY].join("\n") }),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
hooks.markSent(payload);
page.local.homeward = { at: Date.now() };
saveNow();
$("home-modal").close();
} catch (err) {
$("home-modal").close();
// The server is holding an uncollected result: Send, Home and Stop all
// need to read as busy until the frame or the ping says otherwise, same
// as send() and sendAfterBuild() do on a 409.
if (err && err.pending) page.pendingResult = true;
hooks.banner(
err && err.pending
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
: "That did not go through. Nothing was lost; try again.",
"warn"
);
} finally {
go.disabled = false;
redraw();
}
}
// Stopping now can lose answers: Planning writes nothing until its plan is
// done, and Pathfinder nothing until its map exists. The agent knows where it
// is and says so in `stopWarning`; Planning is assumed to lose answers unless
// the agent says otherwise, because that is true of most of it.
export function stopWarning() {
if (typeof page.S.stopWarning === "string") return page.S.stopWarning.trim();
if (page.S.workflow === "plan") {
return "Planning only saves at set points along the way. Answers since the last save will not be kept, though you can go over them again next time.";
}
return "";
}
function openStopConfirm() {
if (stopInProgress()) {
stoppingHidden = false;
return renderStopping();
}
const n = Object.keys(page.local.staged).length + pendingNotes().length;
const warn = stopWarning();
const dash = isDashboard();
$("stop-blurb").textContent =
(n === 1 ? "The answer you have ready goes with it. " : n ? `The ${n} answers you have ready go with it. ` : "") +
(dash ? "Nothing has started yet, so there is nothing to save: this just ends the console session." : "");
$("stop-blurb").hidden = !$("stop-blurb").textContent;
$("stop-warn").hidden = !warn;
$("stop-warn").textContent = warn;
// The dashboard has nothing to hand off: one plain Stop. Elsewhere both
// choices show, and "Just stop and save" turns into "Stop anyway" where
// nothing is saved yet.
$("stop-handoff").hidden = dash;
const title = $("stop-go").querySelector(".stop-choice-title");
const detail = $("stop-go").querySelector(".stop-choice-detail");
if (dash) {
title.textContent = "Stop";
detail.textContent = "Ends the console session.";
} else if (warn) {
title.textContent = "Stop anyway";
detail.textContent = "Ends the session now. What the warning above names is not kept.";
} else {
title.textContent = "Just stop and save";
detail.textContent = "Saves what this step keeps on disk and gives you a command to resume. What we talked about is not kept.";
}
$("stop-modal").showModal();
}
async function stopSession(handoff = false) {
const buttons = [$("stop-handoff"), $("stop-go")];
for (const b of buttons) b.disabled = true;
const payload = hooks.stagedPayload();
payload.actions.push(stopAction({ handoff }));
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: payload.actions, reply: [...payload.replyLines, handoff ? STOP_HANDOFF_REPLY : STOP_REPLY].join("\n") }),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
hooks.markSent(payload);
page.local.stopping = { at: Date.now(), answers: payload.sentIds.size };
saveNow();
$("stop-modal").close();
stoppingHidden = false;
} catch (err) {
$("stop-modal").close();
if (err && err.pending) page.pendingResult = true;
hooks.banner(
err && err.pending
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
: "The stop did not go through. Nothing was lost; try again.",
"warn"
);
} finally {
for (const b of buttons) b.disabled = false;
redraw();
}
}
// The wrapping-up screen, derived every render from what the page already
// tracks: whether the request is collected, whether anyone is listening, and
// whether the finish has landed.
export function renderStopping() {
const dlg = $("stopping-modal");
const stopping = page.S && stopInProgress();
if (!stopping) {
if (dlg.open) dlg.close();
return;
}
// The finish is the end of it: the hand-off card on the page says the rest.
if (finish()) {
page.local.stopping = null;
saveNow();
if (dlg.open) dlg.close();
return;
}
const sent = stopping.answers;
const collected = !page.pendingResult;
// Nobody is coming: the server stopped with no finish, or the agent has not
// checked in for minutes. The request and any answers are on disk either
// way, and the next session collects them.
const stuck = page.gone || agentAdrift();
const steps = [
{ text: sent ? `Sent your ${sent === 1 ? "answer" : sent + " answers"} and the stop` : "Sent the stop", state: "done" },
{
text: collected ? "Plan2Code picked it up" : stuck ? "Plan2Code has not picked it up" : "Waiting for Plan2Code to pick it up",
state: collected ? "done" : stuck ? "stuck" : "now",
},
{ text: "Saving your place and writing the command to pick it up", state: collected ? (stuck ? "stuck" : "now") : "later" },
];
const list = $("stop-steps");
list.replaceChildren(
...steps.map((s) => {
const li = el("li", "is-" + s.state);
li.appendChild(
s.state === "now"
? el("span", "spinner tiny")
: el("span", "stop-mark", s.state === "done" ? "✓" : s.state === "stuck" ? "!" : "·")
);
li.appendChild(el("span", null, s.text));
return li;
})
);
const extra = $("stop-extra");
extra.replaceChildren();
if (stuck) {
extra.appendChild(
el(
"p",
"stop-note",
page.gone
? "The session closed without saying how to pick it up. Your answers and the stop are saved, and the next session collects them. To carry on, run this in the terminal, in a new conversation (or alternatively run `/plan2code` to relaunch the dashboard):"
: "Plan2Code is not running right now, so nothing new has been saved yet. Your answers and the stop are held, and the next session collects them. To carry on, run this in the terminal, in a new conversation (or alternatively run `/plan2code` to relaunch the dashboard):"
)
);
const text = handoffText({ command: resumeCommand(page.S) });
const row = el("div", "handoff-command");
const code = el("code", "handoff-code", text);
row.appendChild(code);
row.appendChild(copyButton(text, "btn small handoff-copy", code));
extra.appendChild(row);
} else {
extra.appendChild(
el(
"p",
"stop-note",
agentWorking() && !collected
? "Plan2Code is in the middle of something. It stops as soon as that is done."
: "This usually takes a moment. You can close the tab if you need to: the command also appears in the terminal."
)
);
}
if (!stoppingHidden && !dlg.open) dlg.showModal();
}
// The top bar's way home and Stop, wired once at start-up.
export function wireEnding() {
$("btn-home").addEventListener("click", openHomeConfirm);
$("home-cancel").addEventListener("click", () => $("home-modal").close());
$("home-go").addEventListener("click", goHome);
$("btn-stop").addEventListener("click", openStopConfirm);
$("stop-cancel").addEventListener("click", () => $("stop-modal").close());
$("stop-handoff").addEventListener("click", () => stopSession(true));
$("stop-go").addEventListener("click", () => stopSession(false));
$("stopping-hide").addEventListener("click", () => {
stoppingHidden = true;
$("stopping-modal").close();
});
// Esc on a native dialog closes it without our say; count that as hiding, or
// the next render would open it straight back up.
$("stopping-modal").addEventListener("cancel", () => (stoppingHidden = true));
}
// The three stop-related controls, drawn again when the agent comes or goes.
export function renderStopControls() {
renderStopButton();
renderHomeButton();
renderStopping();
}
+370
View File
@@ -0,0 +1,370 @@
// Plan2Code Web Console - hosts the git board: tabs, panels and what each click sends.
import { hooks, page, saveNow, redraw } from "../state.js";
import { GIT_TABS, busyMode, gitReply, pickTab, nextStep, tabBadges, createSources, BRANCH_TYPES, commitTicks, cleanupGroups } from "../git-board.js";
import { finish, agentWorking, agentAdrift, gitAwaiting, myTurn, byId, activity } from "../selectors.js";
import { drawGitBoard, activeTab } from "../git-board-view.js";
import { el, md, copyButton } from "../render.js";
import { helpKeyTarget } from "../help.js";
import { postJson } from "../net.js";
// The git board: drawn from state.git, which only console.mjs writes. A click
// never runs git here. It sends one `__git` action through /submit, and the
// agent confirms by card, runs the command and posts a `reread`, whose frame
// redraws the board. The rules live in git-board.js and the drawing in
// git-board-view.js; this is the host: the busy mode, the tab, the scroll,
// the keys, and the panels' state.
const $ = (id) => document.getElementById(id);
// What the person has typed or ticked on the board. Every state frame redraws
// the board from state.git, so this is what carries their place across it.
// panel the open panel: "create", "commit" or "cleanup", or null
// create the Create prompt's fields, while it is open
// ticks the commit table's ticked paths; ignore, its .gitignore toggles
// sweep the cleanup list's ticked branches
// base the pull-request base the picker chose
// settled cards the agent settled since the last click on the board
// tab the tab on show: "changes", "branches" or "sync", or null before the first draw
// scroll how far the column was scrolled on each tab, put back after each redraw
// repickAt when their last board click went out (ms): the first agent post
// after it moves the board to the new next step's tab
export const board = {
tab: null,
scroll: { changes: 0, branches: 0, sync: 0 },
repickAt: null,
query: "",
showAll: false,
remoteOpen: null,
panel: null,
create: null,
ticks: null,
ignore: new Set(),
sweep: null,
base: null,
settled: new Set(),
};
// The search, ticks and open panel are also kept in `local`, so a reload (and
// a skill hop back) restores them the way card drafts already do. Stale picks
// are harmless: the next send re-checks every path against the snapshot. The
// restore waits for the first draw: load() has not run when this module does.
const boardBlank = {
tab: null,
scroll: { changes: 0, branches: 0, sync: 0 },
repickAt: null,
query: "",
showAll: false,
remoteOpen: null,
panel: null,
create: null,
ticks: null,
sweep: null,
base: null,
};
// Each reset gets its own scroll memory: boardBlank's must never be the one written to.
export const resetBoard = () => {
Object.assign(board, boardBlank, { scroll: { ...boardBlank.scroll } });
board.ignore.clear();
};
let boardHydrated = false;
// True from hydration until the first draw has picked its tab: that draw is a reload.
let boardReloaded = false;
const hydrateBoard = () => {
boardHydrated = true;
const g = page.local.gitBoard;
if (!g) return;
boardReloaded = true;
Object.assign(board, boardBlank, {
tab: GIT_TABS.some((t) => t.id === g.tab) ? g.tab : null,
scroll: { changes: 0, branches: 0, sync: 0, ...(g.scroll || {}) },
repickAt: typeof g.repickAt === "number" ? g.repickAt : null,
query: g.query || "",
showAll: Boolean(g.showAll),
remoteOpen: g.remoteOpen ?? null,
panel: g.panel || null,
create: g.create || null,
ticks: g.ticks ? new Set(g.ticks) : null,
sweep: g.sweep ? new Set(g.sweep) : null,
base: g.base || null,
ignore: new Set(g.ignore || []),
});
};
const persistBoard = () => {
page.local.gitBoard = {
tab: board.tab,
scroll: { ...board.scroll },
repickAt: board.repickAt,
query: board.query,
showAll: board.showAll,
remoteOpen: board.remoteOpen,
panel: board.panel,
create: board.create,
ticks: board.ticks ? [...board.ticks] : null,
sweep: board.sweep ? [...board.sweep] : null,
base: board.base,
ignore: [...board.ignore],
};
saveNow();
};
// How busy the board is (busyMode in git-board.js). Running while a send is
// uncollected or the agent is mid-turn, and nothing queues. A "working" agent
// that has gone adrift lets go, as gitAwaiting() does: collecting a click
// marks it working, and an agent that died there must not leave the board
// locked for good. A question card of the agent's open in the card slot holds
// the board too: the card is the turn, and a board click sent beside it went
// alone while the staged answer waited for some later, unrelated send.
const gitMode = () =>
busyMode({
gone: page.gone,
pending: page.pendingResult,
running: Boolean(finish()) || (agentWorking() && !agentAdrift()) || gitAwaiting(),
cardWaiting: myTurn().some((i) => i.kind !== "notice"),
});
const gitLocked = () => gitMode() !== "idle";
// `wording` only shapes the sentence (the operation an Abort names, say); it
// is not part of the action.
async function sendGit(op, fields = {}, wording = {}) {
if (page.gone || finish()) return;
if (page.pendingResult) {
hooks.banner("Your last click is still being picked up. One moment.", "info");
page.pendingBannerUp = true;
return;
}
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({
actions: [{ i: "__git", type: "git", op, ...fields }],
reply: gitReply(op, { ...fields, ...wording }),
}),
});
if (res.status === 409) {
page.pendingResult = true;
hooks.banner("Your last click is still being picked up. One moment.", "info");
page.pendingBannerUp = true;
redraw();
return;
}
if (!res.ok) throw new Error(String(res.status));
board.settled.clear();
board.panel = null;
board.create = null;
board.sweep = null;
// The commit table is always on show: a click drops its picks, and the
// redraw that follows re-seeds them from the snapshot the page already has.
board.ticks = null;
board.ignore = new Set();
page.pendingResult = true;
page.local.gitSentAt = Date.now();
saveNow();
// The draw after this persists it with the rest of the board.
board.repickAt = page.local.gitSentAt;
redraw();
} catch {
hooks.banner("That did not go through. Nothing was lost; try again.", "warn");
}
}
// What the view may ask of the page. Built once: every handler reads the
// board and state.git at the moment of the click, not at the draw.
const gitOn = {
send: sendGit,
redraw: () => redraw(),
pickTab: (id) => {
board.tab = id;
persistBoard();
redraw();
},
openPanel: (name, opts) => openPanel(name, opts),
closePanel: () => closePanel(),
pickPrHost: (host, kind) => pickPrHost(host, kind),
persist: () => persistBoard(),
};
// The tab drawn last, which the scroll listener files the column's place under.
let gitTabDrawn = null;
// FR-9: their own click that landed (an agent post after it went out) and
// arriving at the board go to the next step's tab; a reload and a change they
// did not click for keep the tab they had. A frame with no updatedAt has not
// landed: never re-pick on a guess.
function resolveGitTab(step) {
const before = board.tab;
let reason = "background";
if (board.repickAt && page.S.updatedAt && Date.parse(page.S.updatedAt) > board.repickAt) {
reason = "landed";
board.repickAt = null;
} else if (board.tab == null) reason = "arrival";
else if (boardReloaded) reason = "reload";
boardReloaded = false;
board.tab = pickTab({ current: board.tab, stepTab: step.tab, reason });
if (board.tab !== before || reason === "landed") persistBoard();
}
export function renderGitBoard(main, card = null, pager = null) {
if (!boardHydrated) hydrateBoard();
const git = page.S.git;
const step = nextStep(git);
resolveGitTab(step);
const result = byId("git-result");
const { node, cardSlot } = drawGitBoard({
git,
board,
now: Date.now(),
mode: gitMode(),
offlineReason: page.gone ? "gone" : page.pendingResult ? "pending" : null,
step,
badges: tabBadges(git, { stepTab: step.tab }),
notice: result && result.kind === "notice" ? result : null,
activity: activity(),
hasCard: Boolean(card),
h: { el, md, copyButton },
on: gitOn,
});
if (card) cardSlot.appendChild(card);
if (pager) cardSlot.appendChild(pager);
const tabs = node.querySelector(".git-tabs");
if (tabs) tabs.addEventListener("keydown", gitTabKeys);
// The column scrolls, not the board, and every redraw rebuilds the board,
// so the column would land back at the top. Each tab keeps its own place,
// so a tab switch opens where that tab was left.
const tab = activeTab({ board, step });
gitTabDrawn = tab;
main.addEventListener("scroll", rememberGitTabScroll, { passive: true });
main.appendChild(node);
main.scrollTop = board.scroll[tab] || 0;
persistBoard();
}
// The scroll listener on `main` for each tab's place, kept as a named function
// because renderGitBoard re-adds it on every redraw: adding the same listener
// twice is a no-op, where a fresh closure would pile up.
function rememberGitTabScroll() {
const main = $("main");
if (!gitTabDrawn || !main || !main.querySelector(":scope > .git-board")) return;
board.scroll[gitTabDrawn] = main.scrollTop;
}
// Arrow keys, Home and End move between the tabs, as in the Help dialog. The
// board is redrawn, so focus goes to the new tab after the render.
function gitTabKeys(e) {
const index = GIT_TABS.findIndex((t) => t.id === gitTabDrawn);
const to = helpKeyTarget(e.key, Math.max(0, index), GIT_TABS.length);
if (to < 0) return;
e.preventDefault();
board.tab = GIT_TABS[to].id;
persistBoard();
redraw();
$(`git-tab-${board.tab}`)?.focus();
}
// The host is remembered for every project by the server (pr-hosts.json);
// the action that follows has the agent re-read, which rebuilds the link.
async function pickPrHost(host, kind) {
if (gitLocked()) return;
const res = await postJson("/pr-host", { host, kind });
if (res.status !== 200) {
hooks.banner("That could not be saved. Try again in a moment.", "warn");
return;
}
// The save is durable; a state frame that landed mid-POST still wins.
if (gitLocked()) return;
sendGit("pr-host", { host, kind });
}
// Opening a panel moves to the tab that draws it, so a panel is never open
// on a hidden tab. `opts.ticks` / `opts.ignore` set the commit panel's picks
// (the held-back .gitignore offer opens it with nothing ticked).
function openPanel(name, opts = {}) {
if (gitLocked()) return;
const git = page.S.git;
if (name === "commit") {
board.tab = "changes";
if (opts.ticks) board.ticks = new Set(opts.ticks);
if (opts.ignore) board.ignore = new Set(opts.ignore);
if (board.panel !== "commit") return openCommit(git);
persistBoard();
return redraw();
}
if (name === "create") {
board.tab = opts.commit ? "changes" : "branches";
// A branch for the commit takes what the commit table has ticked, not a fresh default.
if (opts.commit && !opts.files) return openCreate(git, { ...opts, ...tablePicks(git) });
return openCreate(git, opts);
}
if (name === "cleanup") {
board.tab = "branches";
return openCleanup(git);
}
}
const closePanel = () => {
board.panel = null;
board.create = null;
redraw();
};
// In commit mode the commit panel hands over what it would have sent (its
// ticked files and .gitignore picks, already checked against the snapshot);
// a detached commit, which never shows the panel, starts from commitTicks().
function openCreate(git, { commit = false, files = null, ignore = [] } = {}) {
if (gitLocked()) return;
// The agent's description is of the changes waiting: with none left (they
// were committed since), it describes nothing on this tree.
const pending = Number(page.S.git && page.S.git.changes && page.S.git.changes.count) || 0;
const describe = pending && page.S.board && typeof page.S.board.describe === "string" ? page.S.board.describe : "";
board.create = {
from: createSources(git, commit).preset,
type: BRANCH_TYPES[0],
description: describe,
name: null,
commit,
files: commit ? files || [...commitTicks(git.changes)] : null,
ignore: commit ? ignore : [],
};
board.panel = "create";
redraw();
$("git-new-desc")?.focus();
}
// The commit table's picks, checked against the snapshot: `{ files, ignore }`.
// Seeded from commitTicks() when the table has not been drawn yet.
function tablePicks(git) {
const ch = git.changes || {};
const known = new Set([...(ch.files || []), ...(ch.untrackedDirs || [])].map((f) => f.path));
const ticks = board.ticks || (board.ticks = commitTicks(ch));
return { files: [...ticks].filter((p) => known.has(p)), ignore: [...board.ignore].filter((p) => known.has(p)) };
}
// The commit table is always on show, so opening its panel keeps what the
// person has already ticked; sendGit() re-seeds the picks after each click.
function openCommit(git) {
if (gitLocked()) return;
if (board.panel === "commit") return closePanel();
const picks = tablePicks(git);
// Detached: there is no branch to commit on, so the commit makes one.
if (git.hasCommits !== false && !(git.head || {}).branch) return openCreate(git, { commit: true, ...picks });
board.panel = "commit";
board.create = null;
redraw();
}
function openCleanup(git) {
if (gitLocked()) return;
if (board.panel === "cleanup") return closePanel();
const { merged, gone } = cleanupGroups(git);
board.sweep = new Set([...merged, ...gone].map((b) => b.name));
board.panel = "cleanup";
board.create = null;
redraw();
}
@@ -0,0 +1,217 @@
// Plan2Code Web Console - the Help dialog and the first-run Welcome (named so it is never confused with the pure help.js).
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";
const $ = (id) => document.getElementById(id);
// The first dashboard a person ever sees gets a Welcome dialog. Closing it by
// any route (button, Esc, backdrop) saves looks.welcomeSeen, which rides in
// looks.json like every other preference. Waits out the wake-up animation and
// never lands on top of another open dialog.
export function maybeWelcome() {
if (!looksReady || looks.welcomeSeen === true || !page.S || !isDashboard() || finish() || page.wake) return;
if (document.querySelector("dialog[open]")) return;
openWelcome();
}
export function openWelcome() {
if ($("help-modal").open) $("help-modal").close();
const slot = $("welcome-bot");
if (!slot.firstElementChild) {
const bot = $("planny").cloneNode(true);
bot.removeAttribute("id");
bot.setAttribute("class", "planny is-point v1");
slot.appendChild(bot);
}
const dlg = $("welcome-modal");
if (!dlg.open) dlg.showModal();
$("welcome-done").focus();
}
// Whether the two halves are actually talking, in the one place someone goes
// when they are asking that question. Written on open rather than kept live,
// because a line that rewrites itself under a reader is worse than a stale one
// they can close and reopen.
function renderAbout() {
const line = $("about-live");
line.className = "about-live";
if (finish()) {
line.textContent = "Right now: the session is finished, and the command above is all that is left to do.";
} else if (page.gone) {
line.classList.add("is-bad");
line.textContent =
"Right now: this page cannot reach that program. Either it has stopped, or the machine went to sleep. The link from the terminal will bring it back.";
} else if (agentAdrift()) {
line.classList.add("is-bad");
line.textContent =
"Right now: this page is fine, but Plan2Code has not checked in for a few minutes. Have a look at the terminal; it may have finished its turn, hit an error, or be waiting on you there. If it is idle, type continue there to wake it.";
} else {
line.classList.add("is-good");
line.textContent = "Right now: both halves are talking to each other.";
}
}
let helpBuilt = false;
async function renderHelpVersion() {
const slot = $("help-version");
try {
const res = await fetch("/version", { cache: "no-store" });
const { version } = res.ok ? await res.json() : {};
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
slot.hidden = !version;
} catch {
slot.hidden = true;
}
}
const HELP_MOODS = [
["point", "Your turn"],
["work", "Working"],
["happy", "All caught up"],
["done", "Done"],
["adrift", "Not running"],
["gone", "Not connected"],
];
// The help content waits in its <template> until the first time ? is pressed,
// so none of it costs the first paint. The tab buttons come from HELP_TABS.
function buildHelp() {
const content = $("help-content").content.cloneNode(true);
const modal = $("help-modal");
const tabs = $("help-tabs");
const panels = $("help-panels");
// In the dialog itself, so every <use href="#hi-..."> resolves.
modal.appendChild(content.querySelector(".help-icons"));
for (const panel of content.querySelectorAll("section.help-panel")) panels.appendChild(panel);
// Tab 3 shows the real Planny in each mood, cloned the way the dashboard's
// confirm pane does, so the moods can never drift from the drawing.
const moods = panels.querySelector(".help-moods-row");
for (const [mood, label] of HELP_MOODS) {
const bot = $("planny").cloneNode(true);
bot.removeAttribute("id");
bot.setAttribute("class", `planny is-${mood} v0 help-mood-bot`);
bot.setAttribute("aria-hidden", "true");
const cell = el("div", "help-mood");
cell.appendChild(bot);
cell.appendChild(el("span", null, label));
moods.appendChild(cell);
}
for (const row of panels.querySelectorAll("[data-copy]")) {
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;
}
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;
}
export function openHelp() {
if (!helpBuilt) buildHelp();
const id = helpTabFor({
view: page.view,
dashboard: isDashboard(),
gone: page.gone,
adrift: agentAdrift(),
finished: !!finish(),
workflow: page.S && page.S.workflow,
workspace: $("workspace-modal").open,
meterRed: page.meterFrame?.level === "red",
});
selectHelpTab(id);
renderAbout();
renderHelpVersion();
$("help-modal").showModal();
$("help-tab-" + id).focus();
}
// Help opened straight on one topic, when Help has that topic; otherwise it
// stays wherever openHelp() landed.
export function openHelpOn(id) {
openHelp();
if (!HELP_TABS.some((t) => t.id === id)) return;
selectHelpTab(id);
$("help-tab-" + id).focus();
}
// Help's and Welcome's buttons and keys, and the Workspace dialog's link to Help.
export function wireHelp() {
$("workspace-help").addEventListener("click", openHelp);
lightDismiss($("help-modal"));
lightDismiss($("welcome-modal"));
$("welcome-done").addEventListener("click", () => $("welcome-modal").close());
$("welcome-modal").addEventListener("close", () => {
if (looks.welcomeSeen !== true) {
looks.welcomeSeen = true;
saveLooks();
}
$("btn-about").focus();
});
$("help-panels").addEventListener("click", (e) => {
if (e.target.closest && e.target.closest('[data-action="welcome"]')) openWelcome();
});
$("btn-about").addEventListener("click", () => {
openHelp();
});
$("help-done").addEventListener("click", () => $("help-modal").close());
// Opened from inside the Workspace dialog, focus goes back there.
$("help-modal").addEventListener("close", () =>
($("workspace-modal").open ? $("workspace-help") : $("btn-about")).focus()
);
$("help-modal").addEventListener("keydown", (e) => {
// The page-wide Ctrl/Cmd+Enter already stands down while any dialog is open;
// this keeps the key inside Help as well.
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();
});
}
+197
View File
@@ -0,0 +1,197 @@
// Plan2Code Web Console - User Preferences: looks, sounds and the launcher's model menus.
import { adoptLooks, applyLooks, loadLooks, looks, renderSwatches, resetLooks, saveLooks, syncLooks } from "../looks.js";
import { dropHeldSound, releaseHeldSound, sound, soundOn } from "../sound.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";
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();
}
// 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) {
// Following the system means following it as it changes, including the accent,
// whose light and dark shades are different colors.
matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
if (looks.theme === "system") {
applyLooks();
renderSwatches();
}
});
loadLooks();
if (boot && boot.looks && typeof boot.looks === "object") adoptLooks(boot.looks);
applyLooks();
syncLooks();
for (const evt of ["pointerdown", "keydown"]) {
window.addEventListener(evt, releaseHeldSound);
}
}
// Preferences' buttons and fields.
export function wireLooks() {
lightDismiss($("looks-modal"));
$("btn-looks").addEventListener("click", () => {
renderSwatches();
setModelsStatus("", false);
loadModelsData();
$("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;
$("looks-role").appendChild(option);
}
$("looks-role").addEventListener("change", (e) => {
looks.role = normalizeRole(e.target.value);
saveLooks();
// The dashboard banner, and the starter templates and Ask starters on any
// page, all order themselves by the role.
if (page.S) redraw();
});
for (const radio of document.querySelectorAll('input[name="looks-theme"]')) {
radio.addEventListener("change", () => {
looks.theme = radio.value;
saveLooks();
});
}
for (const radio of document.querySelectorAll('input[name="looks-width"]')) {
radio.addEventListener("change", () => {
looks.width = radio.value;
saveLooks();
});
}
$("looks-sound").addEventListener("change", (e) => {
looks.sound = e.target.checked;
// 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();
// 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);
});
for (const box of document.querySelectorAll("input[data-sound]")) {
box.addEventListener("change", () => {
const event = box.dataset.sound;
looks[soundKey(event)] = box.checked;
if (!box.checked) dropHeldSound(event);
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();
});
$("models-reset").addEventListener("click", () => {
if (!modelsData) return;
modelsData.user = Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []]));
saveModels();
renderModels();
});
}
+259
View File
@@ -0,0 +1,259 @@
// Plan2Code Web Console - the launching, starting and waiting screens, with Planny's poses; defines only.
import { page, redraw } from "../state.js";
import { el, approvalTip } from "../render.js";
import { startPose, startingHint, SKILL_CATALOG, staleLaunchFeedback, workflowTitle } from "../answers.js";
import { agentAdrift, doingNow, docs } from "../selectors.js";
const $ = (id) => document.getElementById(id);
const LAUNCH_QUIPS = [
"Passing Planny the baton…",
"Reading the manual…",
"Polishing the star…",
"Warming up the engines…",
"Laying out the good pens…",
"Consulting the map…",
"Putting the kettle on…",
"Rolling out the checklist…",
];
let launchTicker = null;
// Planny flies centre stage: the same drawing as the dock's, cloned so the
// markup stays the single source of him, and the same sky the dock fills.
function flightStage() {
const stage = el("div", "launch-stage");
const sky = el("div", "sky launch-sky");
const r = (a, b) => a + Math.random() * (b - a);
for (let i = 0; i < 30; i++) {
const star = el("i", "star" + (i % 6 === 0 ? " hot" : ""));
const dur = r(3, 9);
star.style.setProperty("--y", r(2, 98).toFixed(1) + "%");
star.style.setProperty("--p", r(0, 1).toFixed(3));
star.style.setProperty("--s", r(1.2, 2.6).toFixed(2) + "px");
star.style.setProperty("--dur", dur.toFixed(2) + "s");
star.style.setProperty("--delay", (-r(0, dur)).toFixed(2) + "s");
sky.appendChild(star);
}
stage.appendChild(sky);
const bot = $("planny").cloneNode(true);
bot.removeAttribute("id");
bot.setAttribute("class", "planny is-work v1 launch-planny");
stage.appendChild(bot);
return stage;
}
// A skill's own Planny, acting out the skill while it starts and works: the
// pose is cloned from its <template> in index.html, so the drawing stays
// markup and the motion stays in app.css. A skill with none keeps the flight.
function startStage(workflow) {
const pose = startPose(workflow);
const art = pose && $("start-poses")?.content.querySelector(`[data-pose="${pose}"]`);
if (!art) return flightStage();
const stage = el("div", "launch-stage pose-stage");
stage.appendChild(art.cloneNode(true));
return stage;
}
// The pane Planny's stage sits in, for the launching, starting and waiting
// screens alike. A render empties the column, and a stage taken off the page
// restarts every animation in it, which a build posting every few seconds
// (and the heartbeat pulling what it missed) would turn into a stutter. So
// the pane already on screen is reused when the next screen shows the same
// pose: its words are rebuilt around a stage that never leaves the page.
// That is also what carries him from "Starting…" into the work unbroken.
function posePane(main, cls, workflow) {
const pose = startPose(workflow) || "flight";
const held = page.heldPose;
page.heldPose = null;
if (held && held.dataset.pose === pose) {
held.className = cls;
for (const child of [...held.children]) if (!child.classList.contains("launch-stage")) child.remove();
return held;
}
const pane = el("div", cls);
pane.dataset.pose = pose;
pane.appendChild(startStage(workflow));
if (held) main.insertBefore(pane, held);
else main.appendChild(pane);
return pane;
}
// The getting-ready screen. The pick is sent and the dashboard agent is
// turning it into a live skill: it resumes this session under the skill's
// workflow, which flips `S.workflow` off "dashboard" and ends this screen
// (adopt() clears `local.launching` on exactly that change).
//
// It is deliberately fun rather than a spinner with a shrug: a launch takes
// a few honest seconds (the skill file is read, the session resumed, the
// first payload composed) and a dead-quiet wait is when people wonder
// whether the click worked. Planny flies, the quips rotate, and after a
// while the hint points at the terminal, which narrates the same hand-off.
export function renderLaunching(main) {
const l = page.local.launching || {};
const pane = posePane(main, "launching", l.skill && SKILL_CATALOG.find((e) => e.skill === l.skill)?.workflow);
const stale = staleLaunchFeedback(l.title, agentAdrift());
pane.appendChild(el("p", "card-kicker", stale ? stale.kicker : "On it"));
pane.appendChild(el("h2", "launch-title", stale ? stale.title : `Waking up ${l.title || "the next mode"}`));
pane.appendChild(el("p", "launch-quip", stale ? stale.quip : LAUNCH_QUIPS[0]));
pane.appendChild(
el(
"p",
"launch-hint",
stale ? stale.hint : "This page turns into its home the moment it answers. No need to touch anything."
)
);
startLaunchTicker();
}
/* The starting screen: a session is open but the agent has not put anything
on it yet. It is what the person looks at while the skill reads the
project, finds its files and composes the first questions, so it gets the
same flight as a launch rather than a bare spinner, and says which skill
is on its way. */
const START_QUIPS = [
"Reading the project…",
"Checking what is already written down…",
"Lining up the first questions…",
"Polishing the star…",
"Laying out the good pens…",
"Consulting the map…",
];
function startingElapsed() {
const since = page.S && page.S.agent ? Date.parse(page.S.agent.since) : NaN;
return Number.isFinite(since) ? Date.now() - since : 0;
}
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)}`));
pane.appendChild(el("p", "launch-quip", START_QUIPS[Math.floor(elapsed / 2600) % START_QUIPS.length]));
pane.appendChild(el("p", "launch-hint", startingHint(elapsed)));
pane.appendChild(approvalTip());
startLaunchTicker();
}
// The quips rotate on their own clock rather than on render: state frames
// arrive whenever the agent posts, and a waiting screen pinned to them
// would sit on one line for most of the wait. The interval looks the
// elements up fresh each tick, so it survives the screen being rebuilt,
// and it stops itself when neither screen is up any more.
function startLaunchTicker() {
if (!launchTicker) {
launchTicker = setInterval(() => {
const kicker = document.querySelector(".launching .card-kicker");
const title = document.querySelector(".launch-title");
const q = document.querySelector(".launch-quip");
const hint = document.querySelector(".launch-hint");
const cur = page.local.launching;
const starting = !cur && document.querySelector(".launching.starting");
if ((!cur && !starting) || !q) {
clearInterval(launchTicker);
launchTicker = null;
return;
}
if (starting) {
const elapsed = startingElapsed();
q.textContent = START_QUIPS[Math.floor(elapsed / 2600) % START_QUIPS.length];
if (hint) hint.textContent = startingHint(elapsed);
return;
}
const elapsed = Date.now() - cur.at;
const stale = staleLaunchFeedback(cur.title, agentAdrift());
if (kicker) kicker.textContent = stale ? stale.kicker : "On it";
if (title) title.textContent = stale ? stale.title : `Waking up ${cur.title || "the next mode"}`;
q.textContent = stale ? stale.quip : LAUNCH_QUIPS[Math.floor(elapsed / 2600) % LAUNCH_QUIPS.length];
if (hint) {
hint.textContent = stale
? stale.hint
: elapsed > 90000
? "Still getting ready. Your terminal has the play-by-play if you want to watch it there."
: "This page turns into its home the moment it answers. No need to touch anything.";
}
}, 900);
}
}
export function renderWaiting(main) {
const doing = doingNow();
// Nothing asked and nothing said yet: the session is still starting.
if (!doing) return renderStarting(main);
// The same Planny the session started with, still at it: the spinner that
// stood here said less about what was going on than he does.
const pane = posePane(main, "waiting-pane", page.S.workflow);
// A build with nothing to ask yet. Say what is happening and where to
// watch it, instead of promising questions that may not come for a while.
const title = el("h2", null, (page.S.headline && page.S.headline.stage) || "Working on it");
// Once the agent stops answering nothing is turning, so neither is the ring
// (the adrift watcher redraws this pane on the flip).
if (!agentAdrift()) {
const spin = el("span", "spinner tiny waiting-spin");
spin.setAttribute("aria-hidden", "true");
title.prepend(spin);
}
pane.appendChild(title);
pane.appendChild(el("p", null, doing));
const ask = "If Plan2Code needs you, the question appears here on its own.";
if (!docs().length) {
pane.appendChild(el("p", null, ask));
return;
}
// "Task" and the tasks tab's own name both open that tab, so the pointer is
// one click from what it points at. A build posts it as `phase` ("Phase N
// tasks"); a quick task ticks the steps of its `plan` in place (an older
// agent may still post a separate `tasks` tab). A skill with no task list
// (Document, Plan) has nothing live to follow, so it gets no pointer at all.
const list =
docs().find((d) => d.id === "phase") ||
docs().find((d) => d.id === "tasks") ||
(page.S.workflow === "quick-task" && docs().find((d) => d.id === "plan")) ||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
if (!list) {
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
return;
}
const jump = (word) => {
const b = el("button", "waiting-jump", word);
b.type = "button";
b.addEventListener("click", () => {
page.view = "doc:" + list.id;
redraw();
});
return b;
};
const p = el("p");
p.append(
"The tabs above fill in as it goes. You can follow along with live ",
jump("Task"),
" updates in the ",
jump(list.title || "Phase tasks"),
" tab. " + ask
);
pane.appendChild(p);
}
// The stars for Planny's flight, made once. Each gets its place and pace as
// custom properties set through the CSSOM: the CSP forbids style attributes
// in markup, and the stylesheet cannot roll dice. They sit still, invisible,
// until the dock is `is-flying`.
export function fillSky() {
const sky = $("dock-sky");
const r = (a, b) => a + Math.random() * (b - a);
for (let i = 0; i < 34; i++) {
const star = document.createElement("i");
star.className = "star" + (i % 7 === 0 ? " hot" : "");
const dur = r(4, 12);
star.style.setProperty("--y", r(3, 97).toFixed(1) + "%");
star.style.setProperty("--p", r(0, 1).toFixed(3));
star.style.setProperty("--s", r(1, 2.2).toFixed(2) + "px");
star.style.setProperty("--dur", dur.toFixed(2) + "s");
// Negative, so the field starts full rather than every star at the edge.
star.style.setProperty("--delay", (-r(0, dur)).toFixed(2) + "s");
sky.appendChild(star);
}
}
+360
View File
@@ -0,0 +1,360 @@
// Plan2Code Web Console - the read-only Workspace of extra folders, and @mentions.
import { hooks, page } from "../state.js";
import { copyButton, el, lightDismiss, selectContents } from "../render.js";
import { selSpec, specList, workspaceFolders } from "../selectors.js";
import { postJson } from "../net.js";
import { nameProblem } from "../workspace.js";
// The Workspace dialog. The server is the only writer of workspace.json: the
// page asks through /workspace/*, and the new list comes back on the next
// frame, which redraws the dialog while it is open.
const $ = (id) => document.getElementById(id);
// Folders the agent reported it cannot read, each told once per page load
// and launch. The server keeps only the current launch's reports, so a name
// that drops out of the list may be told again after the next launch.
const issuesTold = new Set();
let issueBannerTimer = null;
export function tellFolderIssues() {
const issues = (page.wsFrame && page.wsFrame.issues) || [];
const names = new Set(issues.map((i) => i.name));
for (const name of [...issuesTold]) if (!names.has(name)) issuesTold.delete(name);
const fresh = issues.find((i) => !issuesTold.has(i.name));
if (!fresh) return;
issuesTold.add(fresh.name);
const extras = [];
if (fresh.hint) {
extras.push(document.createTextNode(" "));
extras.push(el("code", "banner-hint", fresh.hint));
}
const open = el("button", "btn tiny banner-action", "Open workspace");
open.type = "button";
open.addEventListener("click", () => {
hooks.banner(null);
openWorkspace();
});
extras.push(open);
hooks.banner(`The agent can't read @${fresh.name}: ${fresh.reason}`, "warn", extras);
clearTimeout(issueBannerTimer);
// Then the next folder waiting to be told, if several came at once.
issueBannerTimer = setTimeout(() => {
if (page.gone) return;
hooks.banner(null);
tellFolderIssues();
}, 15000);
}
export async function syncWorkspaceScope(spec) {
if (!page.S || page.S.workflow !== "dashboard" || page.gone || !page.wsFrame) return;
const want = spec === undefined ? (selSpec() && selSpec().dir) || "" : spec;
page.scopeMine = want;
if ((page.wsFrame.scope || "") === want || scopeAsked === want) return;
scopeAsked = want;
const { status, body } = await postJson("/workspace/scope", { spec: want });
if (status === 200 && body && Array.isArray(body.folders)) page.wsFrame = { ...page.wsFrame, ...body };
scopeAsked = null;
if ($("workspace-modal").open) renderWorkspace();
}
let scopeAsked = null;
// The dialog's "Remembered for" line: whose list this is.
function workspaceScopeText() {
const scope = (page.wsFrame && page.wsFrame.scope) || "";
if (!scope) return "Remembered for this project, so your next console session here starts with these folders.";
const spec = specList().find((s) => s.dir === scope);
const name = spec ? spec.name : scope.split("/").pop();
return `Remembered for the ${name} spec, and loaded again whenever it is picked.`;
}
const NAME_RULE = "Names use lowercase letters, numbers and hyphens.";
const BROWSE_UNAVAILABLE = "Browse isn't available here — type or paste the path.";
// The folder whose Remove is waiting on its inline confirm, by id.
let wsConfirm = null;
let wsBusy = false;
export async function openWorkspace() {
const dlg = $("workspace-modal");
try {
const res = await fetch("/workspace?check=1", { cache: "no-store" });
if (res.ok) page.wsFrame = await res.json();
} catch {}
wsConfirm = null;
setAddMsg("");
renderWorkspace();
if (!dlg.open) dlg.showModal();
$("workspace-path").focus();
}
function setAddMsg(text, kind, action) {
const p = $("workspace-add-msg");
p.className = "workspace-add-msg" + (kind ? " is-" + kind : "");
p.textContent = text;
if (action) p.appendChild(action);
}
// One <li> per folder, original first. A frame that keeps the same folders in
// the same order is painted into the rows already there, so a box someone is
// typing in keeps its text, caret and focus; any other change rebuilds.
export function renderWorkspace() {
const list = $("workspace-list");
const folders = workspaceFolders();
const ids = folders.map((f) => f.id).join("\n");
if (list.dataset.ids !== ids) {
list.dataset.ids = ids;
list.replaceChildren(...folders.map(workspaceRow));
}
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
$("workspace-browse").hidden = Boolean(page.wsFrame && page.wsFrame.remote);
$("workspace-scope").textContent = workspaceScopeText();
}
function workspaceRow(f) {
const li = el("li", "ws-entry");
li.dataset.fid = f.id;
const head = el("div", "ws-head");
head.appendChild(el("span", "ws-chip"));
if (f.original) head.appendChild(el("span", "ws-original", "started here — can't be removed"));
li.appendChild(head);
const pathRow = el("div", "ws-path-row");
const code = el("code", "ws-path");
pathRow.appendChild(code);
const copy = el("button", "btn small", "Copy path");
copy.type = "button";
copy.addEventListener("click", async () => {
const folder = workspaceFolders().find((x) => x.id === f.id);
if (!folder) return;
try {
await navigator.clipboard.writeText(folder.path);
copy.textContent = "Copied";
setTimeout(() => (copy.textContent = "Copy path"), 1500);
} catch {
// Refused: the path is selected instead, ready for Ctrl+C.
selectContents(code);
copy.textContent = "Press Ctrl+C";
}
});
pathRow.appendChild(copy);
if (!f.original) {
const remove = el("button", "btn small danger ws-remove", "Remove");
remove.type = "button";
remove.addEventListener("click", () => {
wsConfirm = f.id;
renderWorkspace();
li.querySelector(".ws-confirm .btn.danger")?.focus();
});
pathRow.appendChild(remove);
}
li.appendChild(pathRow);
li.appendChild(el("div", "ws-marks"));
li.appendChild(workspaceField(f, "name", "Name"));
li.appendChild(workspaceField(f, "description", "What is it?"));
return li;
}
// The Name and What-is-it boxes. Each saves on blur or Enter through
// /workspace/edit, and only when it holds something new.
function workspaceField(f, field, labelText) {
const wrap = el("div", "ws-field");
const id = `ws-${field}-${f.id}`;
const label = el("label", null, labelText);
label.htmlFor = id;
const input = el("input");
input.type = "text";
input.id = id;
input.dataset.field = field;
input.autocomplete = "off";
input.spellcheck = false;
if (field === "description") input.maxLength = 200;
const err = el("p", "field-error");
err.hidden = true;
const current = () => workspaceFolders().find((x) => x.id === f.id);
const saved = () => (current() ? current()[field] || "" : "");
const showError = (text) => {
err.textContent = text || "";
err.hidden = !text;
input.classList.toggle("invalid", Boolean(text));
};
if (field === "name") {
input.addEventListener("input", () => showError(nameProblem(input.value.trim()) ? NAME_RULE : ""));
}
const save = async (leaving) => {
const value = input.value.trim();
if (value === saved()) return showError("");
if (field === "name" && nameProblem(value)) {
if (!leaving) return showError(NAME_RULE);
input.value = saved();
return showError("");
}
const { status, body } = await postJson("/workspace/edit", { id: f.id, [field]: value });
// An earlier "Added as @x" is out of date once the list moves on.
if (status === 200) {
setAddMsg("");
return showError("");
}
if (body.reason === "name-taken") showError(`@${value} is taken — try @${body.suggest}.`);
else if (body.reason === "bad-name") showError(NAME_RULE);
else showError("That did not save. Try again.");
if (leaving) input.value = saved();
};
input.addEventListener("keydown", (e) => {
if (e.key !== "Enter") return;
e.preventDefault();
save(false);
});
input.addEventListener("blur", () => save(true));
wrap.append(label, input, err);
return wrap;
}
// Everything in a row that follows the frame. A box with focus is left as
// the person has it; every other box shows what is saved.
function paintWorkspaceRow(li, f) {
if (!li) return;
const missing = (page.wsFrame.missing || []).includes(f.id);
const issue = (page.wsFrame.issues || []).find((x) => x.name === f.name);
li.classList.toggle("is-missing", missing);
li.querySelector(".ws-chip").textContent = "@" + f.name;
li.querySelector(".ws-path").textContent = f.path;
for (const input of li.querySelectorAll("input[data-field]")) {
if (document.activeElement !== input) input.value = f[input.dataset.field] || "";
}
const marks = li.querySelector(".ws-marks");
marks.replaceChildren();
if (missing) marks.appendChild(el("p", "ws-mark is-missing", "This folder no longer exists"));
if (issue) {
marks.appendChild(el("p", "ws-mark is-issue", "The agent can't read this yet: " + issue.reason));
if (issue.hint) {
const row = el("div", "ws-hint-row");
const code = el("code", "ws-hint", issue.hint);
row.append(code, copyButton(issue.hint, "btn tiny", code));
marks.appendChild(row);
}
}
if (f.nested) marks.appendChild(el("p", "ws-mark is-nested", "Inside another folder in the list"));
marks.hidden = !marks.children.length;
// Built once per confirm, so a frame landing meanwhile keeps its focus.
const open = li.querySelector(".ws-confirm");
if (wsConfirm !== f.id) open?.remove();
else if (open) open.querySelector("span").textContent = `Remove @${f.name}? The agent is told.`;
else {
const box = el("div", "ws-confirm");
box.setAttribute("role", "alert");
box.appendChild(el("span", null, `Remove @${f.name}? The agent is told.`));
const keep = el("button", "btn small ghost", "Keep it");
keep.type = "button";
keep.addEventListener("click", () => {
wsConfirm = null;
renderWorkspace();
li.querySelector(".ws-remove")?.focus();
});
const go = el("button", "btn small danger", "Remove");
go.type = "button";
go.addEventListener("click", async () => {
go.disabled = true;
const { status } = await postJson("/workspace/remove", { id: f.id });
wsConfirm = null;
if (status === 200) setAddMsg("");
if (status !== 200) setAddMsg(`@${f.name} could not be removed. Try again.`, "error");
renderWorkspace();
$("workspace-path").focus();
});
box.append(keep, go);
li.appendChild(box);
}
}
// Add by typed path, or by a path Browse… came back with. `name` is only
// sent when the person took a suggested name after a clash.
async function addWorkspaceFolder(path, name) {
const trimmed = String(path || "").trim();
if (!trimmed || wsBusy) return;
wsBusy = true;
$("workspace-add").disabled = true;
const { status, body } = await postJson("/workspace/add", name ? { path: trimmed, name } : { path: trimmed });
wsBusy = false;
$("workspace-add").disabled = false;
if (status === 200) {
$("workspace-path").value = "";
setAddMsg(`Added as @${body.name}.` + (body.nested ? " It's inside another folder in the list." : ""), "good");
if (body.name && page.wsFrame && !workspaceFolders().some((f) => f.id === body.id)) {
page.wsFrame = { ...page.wsFrame, folders: [...workspaceFolders(), body] };
}
renderWorkspace();
hooks.renderWhere();
return;
}
switch (body.reason) {
case "not-a-folder":
return setAddMsg("That isn't a folder on this machine.", "error");
case "duplicate":
return setAddMsg(`Already in the workspace as @${body.name}.`, "error");
case "name-taken": {
const taken = name || String(body.suggest || "").replace(/-\d+$/, "");
const use = el("button", "btn tiny", `Use @${body.suggest}`);
use.type = "button";
use.addEventListener("click", () => addWorkspaceFolder(trimmed, body.suggest));
return setAddMsg(`@${taken} is taken — try @${body.suggest}.`, "error", use);
}
case "bad-name":
return setAddMsg(NAME_RULE, "error");
default:
return setAddMsg("That folder could not be added. Try again.", "error");
}
}
async function browseWorkspace() {
const b = $("workspace-browse");
if (b.disabled) return;
b.disabled = true;
setAddMsg("Waiting for the folder picker…");
const { status, body } = await postJson("/workspace/browse", {});
b.disabled = false;
if (status === 200 && body.path) {
setAddMsg("");
return addWorkspaceFolder(body.path);
}
if (status === 200 && body.cancelled) return setAddMsg("");
setAddMsg(BROWSE_UNAVAILABLE, "error");
}
// The dialog's buttons, and the footer label that opens it.
export function wireWorkspace() {
lightDismiss($("workspace-modal"));
$("workspace-add").addEventListener("click", () => addWorkspaceFolder($("workspace-path").value));
$("workspace-path").addEventListener("keydown", (e) => {
if (e.key !== "Enter") return;
e.preventDefault();
addWorkspaceFolder(e.currentTarget.value);
});
$("workspace-browse").addEventListener("click", browseWorkspace);
$("workspace-done").addEventListener("click", () => $("workspace-modal").close());
$("workspace-modal").addEventListener("close", () => {
wsConfirm = null;
$("footer-where").focus();
});
// As on Help: the page-wide Ctrl/Cmd+Enter stands down while a dialog is open,
// and this keeps the key inside the Workspace dialog as well.
$("workspace-modal").addEventListener("keydown", (e) => {
if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
e.preventDefault();
e.stopPropagation();
}
});
// The workspace label opens the Workspace dialog; each folder's Copy path
// lives in there now.
$("footer-where").addEventListener("click", openWorkspace);
}
+237
View File
@@ -0,0 +1,237 @@
// 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 { activityLabel, workingLine } from "./labels.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;
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"].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);
// 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".
export function agentAdrift() {
if (!page.agentLastSeen || page.gone || finish()) return false;
return Date.now() - Date.parse(page.agentLastSeen) > patience(ADRIFT_MS);
}
// Answers that went nowhere: pressed Send, and nothing has collected them.
// They are safe -- the server wrote them to disk and the next session picks
// them up -- but "Sent. Waiting for Plan2Code." forever does not say that.
export const stranded = () => page.pendingResult && agentAdrift();
// The spec whose overview.md the Overview tab shows: the dashboard picker's
// selection on the dashboard, the session's own spec everywhere else.
export const overviewSpec = () => (isDashboard() ? selSpec()?.dir || "" : (page.S && page.S.specDir) || "");
// Fresh from disk every time, never cached: the file changes under a build,
// and the tab is only worth having if it shows what is there now. Repaints
// only when the tab would appear, vanish or show different text.
export async function loadOverview() {
const spec = overviewSpec();
let text = null;
if (spec) {
try {
const res = await fetch("/overview?spec=" + encodeURIComponent(spec), { cache: "no-store" });
if (res.status === 200) text = await res.text();
} catch {}
}
// The selection moved on while this was in flight; its own fetch will land.
if (spec !== overviewSpec()) return;
const changed = page.overview.key !== spec || page.overview.text !== text;
page.overview = { key: spec, text };
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 : []);
+76
View File
@@ -0,0 +1,76 @@
// Plan2Code Web Console - whether Send is available, and what its button says; defines only.
import {
finish,
stranded,
agentWorking,
myTurn,
stagedCount,
workingMs,
patience,
WORKING_GRACE_MS,
openItems,
agentAdrift,
} from "./selectors.js";
import { finishPaused } from "./answers.js";
import { page } from "./state.js";
import { pendingNotes } from "./uploads.js";
export function sendState() {
// Before `gone`, and before the grace period that can re-enable a send. A
// finished session has nobody left to send to, whatever the socket says.
if (finish())
return finishPaused(finish())
? { disabled: true, why: "This session is paused.", short: "Session paused" }
: { disabled: true, why: "This session is finished.", short: "Session finished" };
if (page.gone) return { disabled: true, why: "Not connected right now.", short: "Not connected" };
// A send is still being collected. Blocking here is what keeps someone from
// writing over answers nobody has read yet.
if (page.pendingResult) {
// The server refuses a second submit while one is uncollected, so this
// stays disabled either way. Only the reason changes, and "one moment" is
// a promise the page cannot keep once nothing is coming to collect them.
return stranded()
? { disabled: true, why: "Saved, and waiting for Plan2Code to come back for them.", short: "Saved, not picked up" }
: { disabled: true, why: "Your last answers are on their way. One moment.", short: "" };
}
if (agentWorking()) {
// A question the agent left open while still working is still a question,
// and its answer has nowhere better to wait than the server, which holds
// a send until the agent next looks. The contract says to switch to
// "waiting" before asking, but an agent that asks and carries on ("while
// you decide") must not lock the person out of answering for up to an
// hour of quietMinutes.
if (myTurn().length && (stagedCount() || pendingNotes().length)) {
return {
disabled: false,
why: "Plan2Code is still working. Your answers wait for it to look.",
short: "Still working · it reads this next",
};
}
const ms = workingMs();
if (ms > patience(WORKING_GRACE_MS)) {
// A stuck agent must not lock someone out of their own session, so the
// hatch stays open -- but only once there is something to push through
// it. Enabled with an empty payload, Send clicks as a no-op, and the
// loud styling on a dead button reads as broken rather than available.
// "A while", not the clock: the footer only redraws on events, so a
// duration printed here freezes between them, and a frozen number
// beside "is it stuck?" makes the page look like the thing it is
// warning about. The exact time already ticks away in the dock.
if (stagedCount() || pendingNotes().length) {
return { disabled: false, why: "Plan2Code has been busy a while. You can send anyway.", short: "Busy · send anyway" };
}
return openItems().length
? {
disabled: true,
why: "Plan2Code has been busy a while. Answer something or add a note, and you can send anyway.",
short: "Busy · a note unlocks Send",
}
: { disabled: true, why: "Plan2Code has been busy a while.", short: "Busy a while" };
}
return { disabled: true, why: "Wait for Plan2Code to finish.", short: agentAdrift() ? "Gone quiet" : "" };
}
if (!stagedCount() && !pendingNotes().length) return { disabled: true, why: "" };
return { disabled: false, why: "" };
}
+418
View File
@@ -0,0 +1,418 @@
// Plan2Code Web Console - the skill list.
//
// Every per-skill fact the console uses; data only, imported by the page and
// by Node. One entry per workflow: the dashboard's cards first, in their
// order on the page, then the workflows with no card (the dashboard itself).
// The older tables (SKILL_CATALOG, START_POSES, LAUNCH_COUNTED and the rest)
// are lookups on this list. No imports and no DOM access: nothing runs at
// load but building the frozen data.
//
// Per entry:
// skill the installed skill's name; `command` is "/" + skill
// workflow the console's name for it (`open --workflow`)
// label the badge the page header wears
// name how the session meter's rows name it ("7 answers in Plan")
// pose the Planny drawn on its starting screen (index.html's
// <template id="start-poses">), or null for the flight
// builds a build: the header counts tasks done, Help opens on Building
// phased a phased build: tasks numbered "Task 4.2" and counted on the
// meter as the headline's `cleared` rises
// metered the launch itself scores on the session meter
// templates the first "What's the idea?" card offers starter templates
// subagents the Subagents switch's standing instruction, or null when the
// switch is not offered
// states the spec states its card takes, as spec-states.js names them,
// plus "none" for no spec picked; "any" for a card that is
// always on whatever is picked; null for no card
// marksNext the card can be a state's natural next step, so its answer
// always says whether it is (`next`)
// greyed its greyed reasons: `default`, plus one per state whose
// wording differs, and `finished` for any finished state
// (spec-states.js); Init and Init update use `default` for the
// AGENTS.md check, which is a rule on the scan, not on the spec
// card the dashboard card (group, chip, title, blurb, about, and
// `spec: true` when it takes the picked spec), or null
// Shared by Implement and Implement + Review.
const BUILD_HELPERS =
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.";
// Pathfinder's and Plan's reason on a finished spec (a fixed bug).
export const FIXED_REASON = "This bug is fixed. Delete it with the Delete button on its chip, or move it to specs--completed/.";
// Shared by Implement and Implement + Review.
const BUILD_GREYED = { default: "Needs the phase checklists written up first", built: "All tasks are already done" };
function skill(entry) {
const card = entry.card ? Object.freeze({ ...entry.card }) : null;
const states = Array.isArray(entry.states) ? Object.freeze([...entry.states]) : entry.states;
const greyed = entry.greyed ? Object.freeze({ ...entry.greyed }) : null;
return Object.freeze({ marksNext: false, ...entry, command: "/" + entry.skill, states, greyed, card });
}
export const SKILLS = Object.freeze([
skill({
skill: "plan2code-init",
workflow: "init",
label: "Setting up",
name: "Init",
pose: "init",
builds: false, phased: false, metered: true, templates: false,
subagents: null,
states: "any",
greyed: { default: "AGENTS.md is already written. Refresh it instead." },
card: {
group: "setup",
chip: "Set up",
title: "Set up this project",
blurb: "Reads your project and writes AGENTS.md, the guide every later step works from.",
about:
"Plan2Code reads the whole project: how it is organized, how it runs, and where the sharp edges are. Then it writes AGENTS.md, the guide every later step steers by. It asks a few questions as it goes, so nothing important gets guessed. Run this once per project, or again when the project has moved on.",
},
}),
skill({
skill: "plan2code-init-update",
workflow: "init-update",
label: "Refreshing",
name: "Init update",
pose: "init",
builds: false, phased: false, metered: true, templates: false,
subagents: null,
states: "any",
greyed: { default: "Needs an AGENTS.md. Set the project up first." },
card: {
group: "setup",
chip: "Set up",
title: "Refresh AGENTS.md",
blurb: "Brings AGENTS.md and its notes up to date with what the project has learned lately.",
about:
"The project moved on since AGENTS.md was written: new commands, new habits, new gotchas. This re-reads the project, asks what changed, and folds it into AGENTS.md and the notes beside it. Cheaper than a fresh setup, and whatever is still right is kept.",
},
}),
skill({
skill: "plan2code-0-pathfinder",
workflow: "pathfinder",
label: "Pathfinder",
name: "Pathfinder",
pose: "pathfinder",
builds: false, phased: false, metered: false, templates: true,
subagents: "Use helpers for codebase recon, sketches and lookups beside the conversation. Keep every question for the person with you.",
states: ["none", "unrecognized", "exploring"], marksNext: true,
greyed: {
default: "This spec is already past the questions",
diagnosed: "The cause is found. Fix it in a quick task, or plan it.",
finished: FIXED_REASON,
},
card: {
group: "pipeline",
chip: "Step 0",
spec: true,
title: "Pathfinder",
blurb: "A foggy idea becomes a clear list of decisions, settled one question at a time.",
about:
"You have a rough idea and a lot of unknowns. Pathfinder asks one question at a time: who it is for, what it must do, what could go wrong. Each answer is written down in a spec folder. It ends with a list of decisions clear enough to plan from, and nothing gets built yet.",
},
}),
skill({
skill: "plan2code-1-plan",
workflow: "plan",
label: "Planning",
name: "Plan",
pose: "plan",
builds: false, phased: false, metered: true, templates: true,
subagents: null,
states: ["none", "unrecognized", "diagnosed", "mapped", "planned"], marksNext: true,
greyed: {
default: "The plan is written. Revise it instead if it moved.",
exploring: "Pathfinder is not finished with this spec yet",
finished: FIXED_REASON,
},
card: {
group: "pipeline",
chip: "Step 1",
spec: true,
title: "Plan",
blurb: "Requirements, technical design and your approval: the shape of what gets built.",
about:
"Turns what you bring into a real plan: a finished Pathfinder map, a folder of design notes, or just the idea in your head. You get requirements, a technical design, a phase-by-phase breakdown, and a final version to approve before anything is built. This is where 'what are we building' becomes 'how it gets built'.",
},
}),
skill({
skill: "plan2code-1b-revise-plan",
workflow: "revise-plan",
label: "Revising the plan",
name: "Revise plan",
pose: "plan",
builds: false, phased: false, metered: true, templates: false,
subagents: null,
states: ["documented", "building"],
greyed: { default: "Needs a spec that is already written up", built: "The spec is fully built" },
card: {
group: "pipeline",
chip: "Step 1b",
spec: true,
title: "Revise the plan",
blurb: "Requirements changed mid-build? Adjust the plan without starting over.",
about:
"Requirements moved mid-build: a feature added, a rule dropped, a deadline pulled in. This adjusts the existing spec for the change, shows you what it affects, and only rewrites what actually has to move. The approved plan stays the plan.",
},
}),
skill({
skill: "plan2code-2-document",
workflow: "document",
label: "Documenting",
name: "Document",
pose: "document",
builds: false, phased: false, metered: true, templates: false,
subagents: null,
states: ["planned"], marksNext: true,
greyed: {
default: "Needs a drafted plan first",
documented: "The phases are already written up",
building: "The phases are already written up",
built: "The phases are already written up",
},
card: {
group: "pipeline",
chip: "Step 2",
spec: true,
title: "Document",
blurb: "The plan becomes a checklist of small tasks, grouped into phases, that a developer can just do.",
about:
"Writes the plan as numbered phase files. Each phase is a checklist of tasks small enough to just do, with the details a builder needs right there. This is the file the build step works from, and the thing a later session can pick up cold.",
},
}),
skill({
skill: "plan2code-3-implement",
workflow: "implement",
label: "Building",
name: "Implement",
pose: "implement",
builds: true, phased: true, metered: false, templates: false,
subagents: BUILD_HELPERS,
states: ["documented", "building"], marksNext: true,
greyed: BUILD_GREYED,
card: {
group: "pipeline",
chip: "Step 3",
spec: true,
title: "Implement",
blurb: "Builds the next phase, task by task, with a report and your sign-off at the end.",
about:
"Builds the next phase of the spec. Tasks get checked off one by one, with progress and the occasional decision landing on this page as it goes. It ends with a report of what was built and a sign-off card you approve before the phase counts as done.",
},
}),
skill({
skill: "plan2code-3-implement-review",
workflow: "implement-review",
label: "Building + review",
name: "Implement + Review",
pose: "implement",
builds: true, phased: true, metered: false, templates: false,
subagents: BUILD_HELPERS,
states: ["documented", "building"], marksNext: true,
greyed: BUILD_GREYED,
card: {
group: "pipeline",
chip: "Step 3",
spec: true,
title: "Implement + review",
blurb: "One phase built, then a careful review of the changes, then your sign-off. All in one run.",
about:
"The same build as Implement, with a review folded in before sign-off. The phase is built, then a fresh pass hunts for problems in exactly what changed, you pick what gets fixed, and only then does the sign-off card arrive.",
},
}),
skill({
skill: "plan2code-4-finalize",
workflow: "finalize",
label: "Wrapping up",
name: "Finalize",
pose: "finalize",
builds: false, phased: false, metered: true, templates: false,
subagents: null,
states: ["built"], marksNext: true,
greyed: { default: "Needs a spec that is fully built" },
card: {
group: "pipeline",
chip: "Step 4",
spec: true,
title: "Finalize",
blurb: "Checks the work, writes the summary, files the specs away and suggests the commit message.",
about:
"The closer. Checks every task against the spec, makes sure the build actually works, writes the summary into overview.md, updates the project docs, and suggests the commit message. Run it when the feature is done. It leaves the project tidy behind it.",
},
}),
skill({
skill: "plan2code-quick-task",
workflow: "quick-task",
label: "Quick task",
name: "Quick task",
pose: "quick-task",
builds: true, phased: false, metered: true, templates: true,
subagents: "Use helpers for side lookups, such as reading unfamiliar code or checking documentation, while you make the change yourself.",
states: "any",
greyed: null,
card: {
group: "extra",
chip: "Utility",
title: "Quick task",
blurb: "Too small for the full process? A quick plan, then it just builds it.",
about:
"A fix, a tweak, a small feature. Not worth a spec folder. Describe it, confirm the one-line plan, and it builds it right there, with a report at the end. The fast lane for work the full process would over-plan.",
},
}),
skill({
skill: "plan2code-review",
workflow: "review",
label: "Review",
name: "Review",
pose: "review",
builds: false, phased: false, metered: true, templates: false,
subagents: "Run the review's analysis in one fresh helper briefed only with the spec and the change set (references/reviewer-brief.md); verify every finding yourself before you report.",
states: "any",
greyed: null,
card: {
group: "extra",
chip: "Utility",
title: "Review",
blurb: "A second opinion on the changes. Problems ranked, and you pick what gets fixed.",
about:
"A fresh-eyes pass over what changed: bugs, gaps, and the things the builder was too close to see. Problems come back ranked with a suggestion each, you pick which ones get fixed, and it fixes them.",
},
}),
skill({
skill: "plan2code-xray",
workflow: "xray",
label: "X-ray",
name: "X-ray",
pose: "xray",
builds: false, phased: false, metered: true, templates: false,
subagents: null,
states: "any",
greyed: null,
card: {
group: "extra",
chip: "Utility",
title: "Codebase X-ray",
blurb: "Explain how and why an area works, or find the rough spots worth fixing.",
about:
"Two ways into code you did not write. Explain an area: how it works, step by step, and why it is that way, citing the files and the commits and pull requests behind it. Or find the rough spots: files that always change together, thin layers, tangled boundaries and busy code with no tests, ranked with a concrete example each. You tick the ones worth fixing and they become a brief for Pathfinder or Plan. It never changes code.",
},
}),
skill({
skill: "plan2code-diagnose",
workflow: "diagnose",
label: "Diagnosing",
name: "Diagnose",
pose: "diagnose",
builds: false, phased: false, metered: true, templates: false,
subagents: null,
states: "any",
greyed: null,
card: {
group: "extra",
chip: "Utility",
title: "Diagnose a bug",
blurb: "Find a bug's cause and write it up, without fixing it.",
about:
"Something is broken and nobody knows why. Diagnose asks what goes wrong and how to see it, then builds a command that fails on the bug before it forms a theory. It narrows the cause down to a file and a function, says how sure it is, and sizes the fix. The write-up lands in a spec folder, and the dashboard then offers Quick Task to fix it, or Plan when the fix is big. It never changes code.",
},
}),
skill({
skill: "plan2code-changelog",
workflow: "changelog",
label: "Changelog",
name: "Changelog",
pose: "changelog",
builds: false, phased: false, metered: true, templates: false,
subagents: null,
states: "any",
greyed: null,
card: {
group: "extra",
chip: "Utility",
title: "Changelog",
blurb: "Checks the CHANGELOG version against the main branch and suggests entries for what is new.",
about:
"Works out the right version from the default branch, then compares your branch with the latest CHANGELOG entry and suggests the entries it is missing. You edit them before anything is written, it keeps package.json in step, and it offers to commit the result in Git. If the newest version is not released or on another branch yet, it adds to that entry instead of starting a new one.",
},
}),
skill({
skill: "plan2code-git",
workflow: "git",
label: "Git",
name: "Git",
pose: "git",
builds: false, phased: false, metered: true, templates: false,
subagents: null,
states: "any",
greyed: null,
card: {
group: "extra",
chip: "Utility",
title: "Git",
blurb: "Branches, pull, push and commits on one board that stays open while you work.",
about:
"Shows your branch, what is ahead or behind, and every local and remote branch. Switch, create, delete or clean up branches, pull (rebasing when they have split, with help on conflicts), push or publish, and commit with a clear message. It asks before every push, publish and delete, and never force-pushes.",
},
}),
skill({
skill: "plan2code-handoff",
workflow: "handoff",
label: "Handoff",
name: "Handoff",
pose: "handoff",
builds: false, phased: false, metered: false, templates: false,
subagents: null,
states: "any",
greyed: null,
card: {
group: "extra",
chip: "Utility",
title: "Handoff",
blurb: "Pack the current session into a document a fresh session can pick up cold.",
about:
"Writes down everything a new session would need, as a single document: what was decided, what is done, what is left. Use it when a conversation got long, a machine changed, or tomorrow-you deserves the context today-you has.",
},
}),
skill({
skill: "plan2code",
workflow: "dashboard",
label: "Dashboard",
name: "the dashboard",
pose: null,
builds: false, phased: false, metered: false, templates: false,
subagents: null,
states: null,
greyed: null,
card: null,
}),
]);
const BY_WORKFLOW = new Map(SKILLS.map((s) => [s.workflow, s]));
const BY_SKILL = new Map(SKILLS.map((s) => [s.skill, s]));
/** The entry for a workflow ("implement"), or null. */
export function skillFor(workflow) {
return BY_WORKFLOW.get(workflow) || null;
}
/** The entry for an installed skill's name ("plan2code-3-implement"), or null. */
export function skillByName(name) {
return BY_SKILL.get(name) || null;
}
export const isBuild = (workflow) => Boolean(skillFor(workflow)?.builds);
export const isPhased = (workflow) => Boolean(skillFor(workflow)?.phased);
export const isMetered = (workflow) => Boolean(skillFor(workflow)?.metered);
export const takesTemplates = (workflow) => Boolean(skillFor(workflow)?.templates);
/** The Subagents switch's instruction for a workflow, or null when it is not offered. */
export function subagentsFor(workflow) {
return skillFor(workflow)?.subagents || null;
}
/** The badge a workflow wears, or null for one the console does not know. */
export function labelFor(workflow) {
return skillFor(workflow)?.label || null;
}
+99
View File
@@ -0,0 +1,99 @@
// Plan2Code Web Console - the sound cues: which plays, one at a time, held until the first click; defines only.
import { looks } from "./looks.js";
import { soundKey, SOUND_EVENTS } from "./palette.js";
/* ------------------------------------------------------------- sounds
The cues are the events in SOUND_EVENTS: a skill started from the
dashboard, Planny snoring and waking, the session opening and ending, a
new batch of questions, a launched skill ready, a reply on Ask, and a new
tab joining the strip (a posted document, a spec's overview). Each plays
only while both the master switch and its own switch are on. A browser will
not let a page make noise before the person has touched it, so a cue that
fires too early is held and let out by the first click or keypress rather
than dropped.
Only ever one at a time, never two overlapping or back to back. Cues asked
for in the same task collapse to the highest-ranked one; a cue asked for
while another is still playing is dropped unless it outranks it, in which
case it cuts the quieter one off. The held cue is a single slot on the same
rule, so the first click lets out one sound, not a queue of them.
Made on first use, not at load: audio downloads racing the page's own
scripts at start-up are bytes spent on sounds a browser will not play
before the first click anyway. One Audio per file, shared by the events
that use it. */
const SOUNDS = {};
let soundQueued = null;
let soundHeld = null;
let soundPlaying = null;
export const soundOn = (event) => looks.sound && looks[soundKey(event)];
const soundAudio = (event) => SOUNDS[SOUND_EVENTS[event].file];
const louderSound = (a, b) => (!b || SOUND_EVENTS[a].rank > SOUND_EVENTS[b].rank ? a : b);
export function sound(event) {
if (!soundOn(event)) return;
if (!soundQueued) queueMicrotask(flushSound);
soundQueued = louderSound(event, soundQueued);
}
function flushSound() {
const event = soundQueued;
soundQueued = null;
if (!soundOn(event)) return;
const busy = soundPlaying && !soundAudio(soundPlaying).paused;
if (busy && SOUND_EVENTS[event].rank <= SOUND_EVENTS[soundPlaying].rank) return;
if (busy) soundAudio(soundPlaying).pause();
const { file } = SOUND_EVENTS[event];
const a = (SOUNDS[file] ||= new Audio(`/${file}.mp3`));
a.currentTime = 0;
soundPlaying = event;
a.play().catch(() => {
if (soundPlaying === event) soundPlaying = null;
soundHeld = louderSound(event, soundHeld);
});
}
// Fades a cue out over `ms` and stops it, so a long one never outlasts the
// moment it belongs to. Timers, not frames: a background tab still finishes.
export function fadeSound(event, ms) {
const a = soundAudio(event);
if (!a || a.paused) return;
const from = performance.now();
const timer = setInterval(() => {
const left = 1 - (performance.now() - from) / ms;
if (left > 0 && !a.paused) {
a.volume = left;
return;
}
clearInterval(timer);
a.pause();
a.volume = 1;
}, 25);
}
// Drops anything queued or held, for a Skip that wants silence.
export function dropSounds() {
soundQueued = null;
soundHeld = null;
}
// The first click or keypress lets out the one cue that was held.
export function releaseHeldSound() {
if (!soundHeld) return;
const name = soundHeld;
soundHeld = null;
sound(name);
}
// Drops the held cue: any of them, or only `event`'s.
export function dropHeldSound(event) {
if (event === undefined || soundHeld === event) soundHeld = null;
}
+39
View File
@@ -0,0 +1,39 @@
// Plan2Code Web Console - the spec states.
//
// Each spec state the dashboard scan can report; data only, imported by the
// page and by Node. In the order the scan's SPEC_STATES lists them. Which
// cards a state lights or greys lives on the skill list (skills.js), and how
// a folder's files map to a state stays with the scan (classifySpec in
// scan.mjs). No imports and no DOM access: nothing runs at load but building
// the frozen data.
//
// Per state:
// label what the picker shows next to the spec's name
// next the card the state is the natural next step for (the
// "Suggested" fallback when the agent's menu names nothing), or
// null when it has none
// finished the work is done: the spec is hidden while unavailable
// workflows are, never the picker's default, deleted after one
// confirm, and greyed with the card's `finished` reason
// (skills.js) on the cards that would otherwise take it
function state(label, next, finished = false) {
return Object.freeze({ label, next, finished });
}
export const SPEC_STATES = Object.freeze({
diagnosed: state("Bug diagnosed", "plan2code-quick-task"),
fixed: state("Bug fixed", null, true),
exploring: state("Exploring", "plan2code-0-pathfinder"),
mapped: state("Ready to plan", "plan2code-1-plan"),
planned: state("Ready to document", "plan2code-2-document"),
documented: state("Ready to build", "plan2code-3-implement"),
building: state("Building", "plan2code-3-implement"),
built: state("Ready to finalize", "plan2code-4-finalize"),
unrecognized: state("Files on disk", null),
});
/** The entry for a state's name ("planned"), or null. */
export function stateFor(name) {
return Object.hasOwn(SPEC_STATES, name) ? SPEC_STATES[name] : null;
}
+6 -3
View File
@@ -3,8 +3,10 @@
// The source of truth for the Role list in User Preferences, the starter
// templates on the first "What's the idea?" card of Pathfinder, Plan and Quick
// Task, the order each role sees them in, and the starter questions an empty
// Ask conversation offers. No DOM access at module scope and no imports: the
// page and `node --test` both import this file.
// Ask conversation offers. No DOM access at module scope, and its one import is
// the data-only skills.js: the page and `node --test` both import this file.
import { SKILLS, takesTemplates } from "./skills.js";
const role = (id, label) => Object.freeze({ id, label });
@@ -20,7 +22,8 @@ export const ROLES = Object.freeze([
export const ROLE_NOT_SET = "none";
export const ROLE_NOT_SET_LABEL = "Not set / none of these";
export const TEMPLATE_WORKFLOWS = Object.freeze(["pathfinder", "plan", "quick-task"]);
// The workflows whose first idea card offers templates, from skills.js.
export const TEMPLATE_WORKFLOWS = Object.freeze(SKILLS.filter((s) => takesTemplates(s.workflow)).map((s) => s.workflow));
const ROLE_IDS = new Set(ROLES.map((r) => r.id));
+201
View File
@@ -0,0 +1,201 @@
// Plan2Code Web Console - the page's shared state and the redraw hook; defines only.
//
// `page` is the one object the page's state lives on, so every file that
// draws reads and writes the same thing:
// page.S the server's truth (state.json). Never mutated by the page.
// page.local what the person has staged but not sent. Mirrored to
// localStorage on every change, so a closed tab or a reload
// loses nothing.
// page.selected the question on screen, by id.
// page.view the tab on screen.
// and below them the rest of what more than one file reads or writes: the
// server's word on the agent and on sends in flight, the frame's other
// blocks, and the few page-local things a screen and the core share.
//
// A screen never calls the render loop or the draft's save itself: it calls
// redraw() and saveNow(), which app.js points at screens/core.js at start-up.
// Nothing here touches the page, so `node --test` imports this file and sets
// the state directly.
export function fresh() {
// `stopping` is set once a stop request has been accepted, and kept here so
// a reload in the middle of wrapping up comes back to the same screen.
// `afterBuild` is "review", "commit", "done" or "dashboard" once a finished session's
// offer has been answered, so the buttons do not come back on a reload.
// `homeward` is set once the top bar's Back to the dashboard request has
// been accepted mid-workflow: { at }. The resume through the dashboard
// resets `local` wholesale, which is what clears it.
// `launching` is the dashboard's pick while the launched skill turns the
// page: { skill, title, at }. Kept here so a reload mid-handoff comes back
// to the getting-ready screen rather than the menu it already answered.
// `specSel` is the dashboard picker's spec dir, or null for "start from
// scratch". Left ABSENT until the picker is touched, which is how the
// default (most recently touched spec) differs from a deliberate scratch.
// `retract` marks a send the person took back, keyed to the send's `at` so
// it suppresses exactly that `submitted` record and no later one.
// `images` is each note's attachments, keyed by item id:
// [{ key, id, path, url, name, status }], status "uploading" | "ready" | "failed".
return {
staged: {},
drafts: {},
images: {},
sent: {},
stopping: null,
afterBuild: null,
homeward: null,
launching: null,
// A picker Delete sent and not yet answered by a rescan: { dir, scanAt }.
deleting: null,
retract: {},
chat: freshChat(),
};
}
// The Ask pane's own corner of `local`: the composer's draft and pictures,
// what the next message is about, sends still on their way, and the newest
// reply already seen (the dot). `conversation` is the one these belong to.
export function freshChat() {
return {
draft: "",
history: [],
about: null,
pending: [],
lastSeenReplyId: null,
images: [],
conversation: null,
};
}
export const page = {
S: null,
local: fresh(),
selected: null,
view: "questions",
// What the server says around the state, from the last frame or ping: when
// the agent last touched it, and whether a send or a stop is still waiting
// to be picked up.
agentLastSeen: null,
pendingResult: false,
pendingStop: false,
// Set while a "still being picked up" banner is showing (see the frame handler).
pendingBannerUp: false,
// No contact with the server: the page is offline.
gone: false,
// The Quick question chat: the server's view of the current conversation
// (the frame's `chat` block). The rest is page-local and gone on a reload:
// `chatDot` is the Ask tab's dot as last drawn, so a reply chimes once;
// `chatError` the line under the composer; `askRowCount` how many rows the
// pane last showed, so a new one scrolls into view; `docInView` the doc
// block nearest the top.
chatFrame: null,
chatDot: false,
chatError: "",
askRowCount: 0,
docInView: null,
// The frame's workspace ({ folders, missing, remote, issues }) and meter
// ({ points, level, fraction, words, tooltip }), or null before a server that
// sends them.
wsFrame: null,
meterFrame: null,
// The frame's update ({ installed, latest }), present only when a newer
// release is out; null otherwise.
updateFrame: null,
// The frame's Subagents switch ({ offered, supported, on, instruction, max,
// revision }), or null before a server that sends it.
subagentsFrame: null,
// The spec's overview.md as last fetched: `key` is the spec dir it was read
// for, `text` the file, or null when there is none. See loadOverview().
overview: { key: null, text: null },
// The dashboard's first-open wake-up (boot.js), while it runs. `cards` turns
// true at the glide, which lets the menu in; `entered` once its entrance has
// played; `typed` is how many characters of the note show, or null once all
// of them do. Page-local: the reload guard is sessionStorage (maybeWake).
wake: null,
// The dashboard pick being looked at on the confirm pane, before START is
// pressed. Page-local like `view`: a reload simply shows the menu again.
dashPick: null,
// The `@name` suggestions popover, owned by whichever box last asked for it.
mentionPop: null,
// The pose pane on screen when a render began, held back from the clear so
// posePane() can take it up again. See posePane.
heldPose: null,
// The workspace scope (a spec dir, "" for the project) this tab last asked
// for: its own pick, not whatever the frame says. And true from a launch's
// scope sync until its send has gone (or failed).
scopeMine: null,
launchScoping: false,
};
let redrawHook = null;
let saveHook = null;
// Draw the page again from `page`. A no-op until start-up sets the hook.
export function redraw() {
if (redrawHook) redrawHook();
}
export function onRedraw(fn) {
redrawHook = fn;
}
// Keep `page.local` (this browser's copy, and the server's draft). A no-op
// until start-up sets the hook.
export function saveNow() {
if (saveHook) saveHook();
}
export function onSave(fn) {
saveHook = fn;
}
// What a screen needs from the core or from another screen: a function the
// entry hands over once at start-up (useHooks) and the screen calls by name,
// never by importing the file that defines it. Calling one before start-up
// is a mistake the test suite catches, so it throws rather than doing nothing.
const registered = {};
export const hooks = new Proxy(registered, {
get(target, name) {
if (typeof name !== "string") return undefined;
if (typeof target[name] !== "function") throw new Error(`hooks.${name} was called before start-up set it`);
return target[name];
},
});
export function useHooks(fns) {
Object.assign(registered, fns);
}
// Stage an answer for a card (or take it back with null), keep the draft, draw.
export function stage(id, value) {
if (value == null) delete page.local.staged[id];
else page.local.staged[id] = value;
saveNow();
redraw();
}
export function setDraft(id, text) {
page.local.drafts[id] = text;
saveNow();
}
// The first state, the saved looks and the draft, written into the page by the
// server so the first real screen needs no round trip. A data block, never run
// as script; read once, on first ask. Null when absent (an older server, a page
// opened some other way): the page then asks for each as it always did.
let bootBlock;
export function bootData() {
if (bootBlock === undefined) {
try {
bootBlock = JSON.parse(document.getElementById("boot").textContent);
} catch {
bootBlock = null;
}
}
return bootBlock;
}
// Where each tab was scrolled, keyed by view id, so switching away and back
// lands where the person left it. Page-side only and never persisted: a reload
// starts every tab at its top.
export const scrollMemory = new Map();
+179
View File
@@ -0,0 +1,179 @@
/* ask.css: The Ask pane and its Quick question chat. */
/* ------------------------------------------------------------ ask pane */
/* The Quick question chat: one card-framed pane that fills the column. The
conversation scrolls; the header and the composer stay put, so the counter,
New conversation and Send are always in reach. */
.main > .ask-pane {
flex: 1 1 auto;
min-height: 0;
display: flex;
flex-direction: column;
background: var(--panel);
border: 1px solid var(--rule);
border-radius: var(--radius);
box-shadow: var(--shadow);
overflow: hidden;
}
.ask-head {
flex: none;
display: flex; align-items: center; gap: 12px;
padding: 16px 22px 14px;
border-bottom: 1px solid var(--rule);
}
.ask-head h2 { font: 600 21px/1.2 var(--serif); margin: 0; flex: 1; }
.ask-counter { font: 700 12px/1 var(--mono); color: var(--ink-3); }
.ask-list {
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
overscroll-behavior: contain;
padding: 18px 22px;
display: flex; flex-direction: column; gap: 10px;
}
/* An empty conversation's starter questions, centred where the list is empty. */
.ask-starters { display: flex; flex-direction: column; gap: 6px; margin: auto 0; width: 100%; max-width: 520px; align-self: center; }
.ask-starters-lead { color: var(--ink-3); font-size: 13.5px; margin: 0 0 4px; text-align: center; }
.ask-starter {
width: 100%;
padding: 9px 13px;
border: 1px solid var(--rule);
border-radius: var(--radius);
background: var(--panel);
font: inherit;
font-size: 13.5px;
color: var(--ink-2);
text-align: left;
cursor: pointer;
}
.ask-starter:hover:not(:disabled) { background: var(--accent-soft); border-color: var(--accent-line); color: var(--ink); }
.ask-starter:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
.ask-starter:disabled { opacity: 0.55; cursor: not-allowed; }
.ask-row {
max-width: 86%;
border-radius: var(--radius);
padding: 10px 14px;
font-size: 14px;
border: 1px solid var(--rule);
}
.ask-row.person { align-self: flex-end; background: var(--accent-soft); border-color: var(--accent-line); }
.ask-row.pending { border-style: dashed; background: transparent; }
.ask-row.agent { align-self: flex-start; background: var(--panel-2); }
.ask-row.decision { align-self: flex-end; background: transparent; border-style: dashed; color: var(--ink-2); font-size: 13px; }
.ask-row .md { max-width: none; }
.ask-row .md > :first-child { margin-top: 0; }
.ask-row .md > :last-child { margin-bottom: 0; }
.ask-row .attach-tray { margin: 8px 0 0; }
.ask-text { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
.ask-about { margin: 0 0 4px; font-size: 11.5px; font-weight: 600; color: var(--accent); }
.ask-decision { margin: 0; font-weight: 600; }
.ask-waiting { margin: 6px 0 0; font-size: 12px; color: var(--ink-3); display: flex; align-items: center; gap: 8px; }
.ask-failed { color: var(--warn); }
.ask-proposal {
margin-top: 10px; padding: 10px 12px;
border: 1px solid var(--stage); border-radius: 8px;
background: var(--stage-soft);
}
.ask-proposal .note-kicker { margin-bottom: 4px; }
.ask-proposal-files, .ask-changed { margin: 6px 0 0; padding-left: 18px; font-size: 12.5px; }
.ask-proposal-actions { display: flex; gap: 8px; align-items: center; margin-top: 10px; flex-wrap: wrap; }
.ask-proposal-actions input[type="text"] { flex: 1 1 200px; width: auto; padding: 7px 10px; }
.ask-decided { margin: 8px 0 0; font-weight: 700; font-size: 13px; }
.ask-decided.approve { color: var(--ok); }
.ask-decided.decline { color: var(--ink-2); }
.ask-changed-count { font: 12px/1 var(--mono); color: var(--ink-3); }
.ask-composer {
flex: none;
padding: 12px 22px 16px;
border-top: 1px solid var(--rule);
background: var(--panel);
}
.ask-composer.is-dropping { outline: 2px dashed var(--accent); outline-offset: -6px; background: var(--accent-soft); }
.ask-composer textarea { min-height: 64px; max-height: 40vh; }
.ask-composer textarea:disabled { opacity: 0.6; cursor: not-allowed; }
.ask-about-chip {
display: inline-flex; align-items: center; gap: 8px;
margin-bottom: 8px; padding: 3px 4px 3px 11px;
border: 1px solid var(--accent-line); border-radius: 99px;
background: var(--accent-soft); color: var(--accent);
font-size: 12px; font-weight: 600;
max-width: 100%;
}
.ask-about-chip > span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.ask-about-chip .attach-remove { position: static; flex: none; }
.ask-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin-top: 8px; }
/* + Add context and its menu. It opens upward, over the list: the composer
sits at the bottom of a pane that clips anything hanging below it. */
.ask-context { position: relative; }
.ask-context-menu {
position: absolute;
left: 0;
bottom: calc(100% + 4px);
z-index: 20;
display: flex;
flex-direction: column;
min-width: 220px;
max-width: 340px;
max-height: 240px;
overflow-y: auto;
padding: 4px;
border: 1px solid var(--rule-2);
border-radius: var(--radius);
background: var(--panel);
box-shadow: var(--shadow);
}
.ask-context-item {
display: flex;
align-items: baseline;
gap: 10px;
padding: 7px 10px;
border: 0;
border-radius: 6px;
background: transparent;
font: inherit;
font-size: 13px;
color: var(--ink);
text-align: left;
cursor: pointer;
}
.ask-context-item:hover,
.ask-context-item:focus-visible { background: var(--accent-soft); outline: none; }
.ask-context-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.ask-context-kind { flex: none; font-size: 11px; color: var(--ink-3); }
.ask-actions .btn.primary { margin-left: auto; }
.ask-send-hint { margin-left: auto; font-size: 12px; color: var(--ink-3); white-space: nowrap; }
.ask-send-hint + .btn.primary { margin-left: 0; }
.ask-count { font: 12px/1 var(--mono); color: var(--ink-3); }
.ask-count.is-over { color: var(--warn); font-weight: 700; }
.ask-error { color: var(--warn); font-size: 13px; margin: 8px 0 0; }
/* The two reasons Send is off read differently, as their wording does: the
limit is a plain fact, the missing agent is something to fix. */
.ask-disabled-note { margin: 0; font-size: 12.5px; line-height: 1.35; padding: 6px 10px; border-radius: 8px; }
.ask-disabled-note.is-limit, .ask-disabled-note.is-waiting { color: var(--ink-2); background: var(--panel-2); border: 1px solid var(--rule); }
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
the tiny ring, left of the label. The extra .spinner is for specificity:
.spinner.tiny comes later and zeroes the margin otherwise. */
.view-tab .spinner.tab-spin {
display: inline-block;
margin-right: 7px;
vertical-align: -1px;
}
/* A reply landed while another tab was open. */
.view-tab .tab-dot {
display: inline-block;
width: 7px; height: 7px;
margin-left: 6px;
border-radius: 50%;
background: var(--accent);
vertical-align: middle;
}
+487
View File
@@ -0,0 +1,487 @@
/* dashboard.css: The dashboard: the menu, the spec picker, its confirm and the launching pane. */
/* ------------------------------------------------------------ dashboard */
/* The dashboard replaces the question column with a menu, and the send bar
with a click on a card. `hidden` alone loses to the bar's own display
rule, so it needs saying here. */
.footer[hidden] { display: none; }
.dash { max-width: 860px; 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
window, until looks.json carries a role. */
.dash-nudge {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 10px 14px;
margin: 0 0 18px;
padding: 10px 14px;
background: var(--accent-soft);
border: 1px solid var(--accent-line);
border-radius: var(--radius);
color: var(--ink);
font-size: 14px;
}
.dash-nudge-text { flex: 1 1 16em; }
/* The session meter at red: the same slot, in the careful colour. */
.dash-nudge.meter-banner {
background: var(--warn-soft);
border-color: var(--warn);
border-left-width: 4px;
color: var(--ink);
}
/* A newer release: the same slot, in the accent, with the label as the way
into the update modal and a small × that hides it for this session. */
.dash-nudge.update-banner {
position: relative;
padding-left: 40px;
padding-right: 40px;
border-left-width: 4px;
border-left-color: var(--accent-line);
color: var(--ink);
box-shadow: var(--glow);
}
.update-banner-open {
flex: 1 1 16em;
padding: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
font-weight: 600;
letter-spacing: 0.02em;
text-align: center;
cursor: pointer;
}
.update-banner-open:hover { text-decoration: underline; }
/* Pinned to the right edge, out of the flow, so the label centres on the
whole banner rather than on what the × leaves of it. */
.update-banner-dismiss {
position: absolute;
top: 50%;
right: 10px;
transform: translateY(-50%);
padding: 0 6px;
border: 0;
border-radius: var(--radius);
background: none;
color: inherit;
font: inherit;
font-size: 16px;
line-height: 1;
cursor: pointer;
}
.update-banner-dismiss:hover { background: var(--accent-line); }
/* Wide enough that the update command sits on one line beside Copy; a
narrow window still wraps it rather than overflowing. */
#update-modal { max-width: 720px; }
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
.update-steps li { margin: 4px 0; }
/* The hand-off copy row, in the modal's first step: the command and its Copy
side by side. */
.update-command {
margin: 6px 0 4px;
display: flex;
align-items: stretch;
gap: 10px;
flex-wrap: wrap;
}
.update-command code {
flex: 1 1 260px;
min-width: 0;
font: 13px/1.5 var(--mono);
color: var(--ink);
background: var(--panel);
border: 1px solid var(--rule-2);
border-radius: 8px;
padding: 10px 12px;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
.dash-working {
display: flex;
align-items: center;
gap: 10px;
width: fit-content;
margin-top: 10px;
padding: 7px 14px;
color: var(--accent);
background: var(--accent-soft);
border: 1px solid var(--accent-line);
border-radius: 10px;
font-weight: 600;
}
.dash-group { margin-bottom: 30px; }
/* A switch, not a checkbox look: it filters the menu live rather than being
an answer. The real checkbox stays in the tree (visually hidden) so the
keyboard, focus ring and screen readers all work as for any input. */
.dash-toggle {
position: relative;
display: inline-flex;
align-items: center;
gap: 10px;
margin: -12px 0 26px;
font-size: 13px;
color: var(--ink-2);
cursor: pointer;
user-select: none;
}
.dash-toggle input { position: absolute; opacity: 0; width: 1px; height: 1px; pointer-events: none; }
.dash-toggle-track {
position: relative;
flex: none;
width: 34px;
height: 20px;
border-radius: 999px;
background: var(--panel-2);
border: 1px solid var(--rule-2);
transition: background 0.15s ease, border-color 0.15s ease;
}
.dash-toggle-track::after {
content: "";
position: absolute;
top: 2px;
left: 2px;
width: 14px;
height: 14px;
border-radius: 50%;
background: var(--ink-3);
transition: transform 0.15s ease, background 0.15s ease;
}
.dash-toggle input:checked + .dash-toggle-track { background: var(--accent); border-color: var(--accent); }
.dash-toggle input:checked + .dash-toggle-track::after { transform: translateX(14px); background: var(--accent-ink); }
.dash-toggle input:focus-visible + .dash-toggle-track { outline: 2px solid var(--accent); outline-offset: 2px; }
.dash-toggle:hover .dash-toggle-track { border-color: var(--accent-line); }
.dash-empty { margin: 0 0 30px; font-size: 13.5px; color: var(--ink-3); font-style: italic; }
.dash-group-title {
margin: 0 0 12px;
font-size: 11.5px;
font-weight: 700;
letter-spacing: 0.09em;
text-transform: uppercase;
color: var(--ink-3);
border-bottom: 1px solid var(--rule);
padding-bottom: 8px;
}
.dash-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 12px; }
/* A card IS a button, so it carries the reset the page's other big clickable
surfaces do; the look is the panel look with a lift on hover, and the
accent border that elsewhere means "the thing in play". */
.dash-card {
display: flex;
flex-direction: column;
gap: 8px;
padding: 16px;
border: 1px solid var(--rule-2);
border-radius: var(--radius);
background: var(--panel);
font: inherit;
text-align: left;
color: var(--ink);
cursor: pointer;
transition: transform 0.15s ease, box-shadow 0.15s ease, border-color 0.15s ease;
}
.dash-card:hover:not(:disabled) {
transform: translateY(-2px);
border-color: var(--accent-line);
box-shadow: var(--shadow);
}
.dash-card:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.dash-card:disabled { cursor: default; opacity: 0.55; }
.dash-card.is-suggested { border-color: var(--accent); }
.dash-card.is-going { border-color: var(--accent); opacity: 1; }
.dash-card-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
.dash-chip {
font-size: 10.5px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--ink-3);
border: 1px solid var(--rule-2);
border-radius: 999px;
padding: 2px 8px;
}
.dash-card.is-suggested .dash-chip { color: var(--accent); border-color: var(--accent-line); }
.dash-card-title { font-size: 15px; font-weight: 650; }
.dash-card-blurb { font-size: 13px; color: var(--ink-2); flex: 1; }
.dash-card-detail { font-size: 12px; color: var(--accent); }
.dash-card-foot {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-top: 4px;
padding-top: 10px;
border-top: 1px solid var(--rule);
}
/* Wraps at the dashes rather than cut off: a command missing its end
("/plan2code-3-implement-revi…") is no command at all. */
.dash-card-cmd {
font-family: var(--mono);
font-size: 11.5px;
color: var(--ink-3);
min-width: 0;
overflow-wrap: anywhere;
}
.dash-card-go { color: var(--accent); font-weight: 700; transition: transform 0.15s ease; }
.dash-card:hover:not(:disabled) .dash-card-go { transform: translateX(3px); }
/* The reason a card is off. The card greys via :disabled; this line is why,
so the menu teaches the pipeline instead of just refusing clicks. */
.dash-card-off { font-size: 12px; color: var(--ink-3); font-style: italic; }
/* -------------------------------------------------------- spec picker */
/* The picker's chips are the same vocabulary as the rail's items: a bordered
lozenge that lights up on the current one. */
.spec-pick { margin-bottom: 30px; }
.spec-row { display: flex; flex-wrap: wrap; gap: 10px; }
.spec-chip {
display: flex;
flex-direction: column;
gap: 3px;
padding: 10px 14px;
border: 1px solid var(--rule-2);
border-radius: var(--radius);
background: var(--panel);
font: inherit;
text-align: left;
color: var(--ink);
cursor: pointer;
transition: border-color 0.15s ease, box-shadow 0.15s ease;
}
.spec-chip:hover { border-color: var(--accent-line); }
.spec-chip:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.spec-chip.is-sel { border-color: var(--accent); box-shadow: var(--shadow); }
.spec-chip-name { font-size: 13.5px; font-weight: 650; }
.spec-chip-state {
font-size: 10.5px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--accent);
}
.spec-chip:not(.is-sel) .spec-chip-state { color: var(--ink-3); }
.spec-chip-detail { font-size: 11.5px; color: var(--ink-3); }
/* A handoff in the picker: the same lozenge, dashed, in the stage colour. */
.spec-chip.is-handoff { border-style: dashed; }
.spec-chip.is-handoff .spec-chip-state, .spec-chip.is-handoff:not(.is-sel) .spec-chip-state { color: var(--stage); }
.spec-chip.is-handoff.is-sel { border-style: solid; border-color: var(--stage); }
.spec-chip.is-handoff.is-deleting { opacity: 0.5; }
/* What a picked handoff shows under the picker. */
.handoff-preview {
margin: 0 0 30px;
padding: 18px 20px;
background: var(--panel);
border: 1px solid var(--stage);
border-radius: var(--radius);
}
.handoff-preview-title { font: 600 20px/1.25 var(--serif); margin: 0 0 4px; }
.handoff-preview-meta { margin: 0 0 14px; font-size: 12.5px; color: var(--ink-3); }
.handoff-preview-label {
margin: 0 0 3px;
font-size: 10.5px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--stage);
}
.handoff-preview-next { margin: 0 0 16px; font-size: 14px; color: var(--ink); }
.handoff-preview-actions { display: flex; flex-wrap: wrap; gap: 10px; }
.handoff-preview-actions .btn.danger { margin-left: auto; }
.modal.handoff-read { max-width: 720px; }
.modal.handoff-read[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
.handoff-body { flex: 1; min-height: 0; overflow-y: auto; margin-top: 8px; }
.modal.handoff-read .modal-actions { flex: none; }
/* A spec's Delete button sits beside its chip, not inside it: a button cannot
hold a button. Quiet until the chip is hovered or focused. */
.spec-chip-wrap { position: relative; display: flex; }
.spec-chip-wrap.is-fixed .spec-chip:not(.is-sel) { opacity: 0.6; }
.spec-chip-wrap .spec-chip { padding-right: 36px; }
.spec-chip-del {
position: absolute;
top: 6px;
right: 6px;
width: 24px;
height: 24px;
display: grid;
place-items: center;
padding: 0;
border: 1px solid transparent;
border-radius: 6px;
background: transparent;
color: var(--ink-3);
font: inherit;
font-size: 15px;
line-height: 1;
cursor: pointer;
opacity: 0.55;
}
.spec-chip-wrap:hover .spec-chip-del,
.spec-chip-del:focus-visible { opacity: 1; }
.spec-chip-del:hover { color: var(--warn); border-color: var(--warn); opacity: 1; }
.spec-chip-del:focus-visible { outline: 2px solid var(--warn); outline-offset: 1px; }
.spec-chip-del:disabled { cursor: default; opacity: 0.3; }
/* A fixed bug's Delete is always shown, as a pill at the chip's bottom right;
the chip makes room below its lines so the pill never covers the name. The
chip's is-fixed dimming targets .spec-chip, so the pill keeps full strength. */
.spec-chip-wrap.is-fixed .spec-chip { padding-right: 14px; padding-bottom: 36px; }
.spec-chip-del-label {
position: absolute;
right: 8px;
bottom: 8px;
padding: 2px 10px;
border: 1px solid var(--warn);
border-radius: 999px;
background: var(--panel);
color: var(--warn);
font: inherit;
font-size: 12.5px;
font-weight: 600;
line-height: 1.5;
cursor: pointer;
}
.spec-chip-del-label:hover:not(:disabled) { background: var(--warn-soft); }
.spec-chip-del-label:focus-visible { outline: 2px solid var(--warn); outline-offset: 1px; }
.spec-chip-del-label:disabled { cursor: default; opacity: 0.4; }
.spec-chip-wrap.is-deleting .spec-chip { opacity: 0.5; }
.delete-facts { display: grid; grid-template-columns: auto 1fr; gap: 6px 14px; margin: 14px 0 0; font-size: 13.5px; }
.delete-facts dt { color: var(--ink-3); }
.delete-facts dd { margin: 0; overflow-wrap: anywhere; }
.delete-confirm { margin-top: 16px; display: flex; flex-direction: column; gap: 8px; font-size: 13.5px; }
.delete-confirm[hidden] { display: none; }
.delete-confirm input {
padding: 8px 10px;
border: 1px solid var(--rule-2);
border-radius: var(--radius);
background: var(--panel);
color: var(--ink);
font: inherit;
}
.delete-confirm input:focus-visible { outline: 2px solid var(--warn); outline-offset: 1px; }
/* ------------------------------------------------- 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, centred
like the launching pane it precedes. */
.dash-confirm {
max-width: 560px;
margin: 3vh auto 0;
display: grid;
gap: 10px;
justify-items: center;
text-align: center;
}
/* A smaller stage than the launching hero: the same sky, a moment shorter. */
.confirm-stage { height: 130px; }
.confirm-stage .sky .star { animation: star-fly var(--dur, 5s) linear var(--delay, 0s) infinite; }
.confirm-planny {
position: absolute;
left: 50%;
bottom: 12px;
width: 58px;
height: 80px;
transform: translateX(-50%);
filter: drop-shadow(0 6px 12px rgba(0, 0, 0, 0.35));
}
.confirm-head { display: flex; align-items: center; gap: 8px; margin-top: 4px; }
.dash-confirm .dash-title { margin: 2px 0 0; }
.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); }
.confirm-spec code { font-family: var(--mono); font-size: 12px; }
.confirm-cmd { margin: 2px 0 0; }
.confirm-cmd code {
font-family: var(--mono);
font-size: 12.5px;
color: var(--ink-2);
background: var(--panel-2);
border: 1px solid var(--rule);
border-radius: 6px;
padding: 4px 10px;
}
.confirm-actions { display: flex; gap: 10px; margin-top: 10px; }
/* ------------------------------------------------------- launching pane */
.launching {
max-width: 560px;
margin: 4vh auto 0;
text-align: center;
display: grid;
gap: 12px;
justify-items: center;
}
/* The same sky the dock fills behind Planny, here in a stage sized for a
hero: the mask fades the stars at the edges exactly the way it does in
the aside. */
.launch-stage {
position: relative;
width: 100%;
height: 180px;
overflow: hidden;
-webkit-mask-image: radial-gradient(120% 100% at 50% 40%, #000 42%, transparent 78%);
mask-image: radial-gradient(120% 100% at 50% 40%, #000 42%, transparent 78%);
}
.launch-sky { opacity: 0.9; }
/* The dock only animates its stars while .is-flying; centre stage they are
the show, so the flight runs unconditionally. */
.launch-stage .sky .star { animation: star-fly var(--dur, 5s) linear var(--delay, 0s) infinite; }
.launch-planny {
position: absolute;
left: 50%;
bottom: 26px;
width: 74px;
height: 102px;
margin-left: -37px;
/* The dock's flight keyframes carry the forward lean; a second, slower bob
on top keeps a long wait from reading as a loop on rails. */
animation:
planny-fly 1.7s ease-in-out infinite,
launch-bob 3.4s ease-in-out infinite;
}
@keyframes launch-bob {
0%, 100% { margin-bottom: 0; }
50% { margin-bottom: 10px; }
}
.launch-title { margin: 0; font: 600 clamp(24px, 4vw, 34px)/1.12 var(--serif); }
.launch-quip {
margin: 0;
font-size: 14.5px;
font-weight: 600;
color: var(--accent);
/* The line swaps on a timer; a minimum keeps the hint under it from
hopping around as the words change length. */
min-height: 1.4em;
animation: launch-quip-in 0.35s ease-out;
}
@keyframes launch-quip-in {
from { opacity: 0; transform: translateY(5px); }
to { opacity: 1; transform: none; }
}
.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); }
+36
View File
@@ -0,0 +1,36 @@
/* docs.css: Documents and the doc tools. */
/* --------------------------------------------------------------- docs */
.doc-head {
max-width: min(var(--card-width), 100%);
display: flex; gap: 12px; align-items: center; flex-wrap: wrap;
margin-bottom: 16px; padding-bottom: 14px; border-bottom: 1px solid var(--rule);
}
.doc-version { font: 700 12px/1 var(--mono); color: var(--ink-3); }
.block { max-width: min(var(--card-width), 100%); border-left: 3px solid transparent; padding: 2px 0 2px 14px; margin: 0 auto 4px; position: relative; }
.block.assumed {
border-left-color: var(--stage);
border-left-style: dashed;
background: var(--stage-soft);
border-radius: 0 8px 8px 0;
}
.block.draft { border-left-color: var(--rule-2); opacity: 0.72; }
.block.settled { border-left-color: var(--ok-soft); }
.block .md { max-width: none; }
.block-tag {
font-size: 10.5px; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase;
color: var(--stage); display: block; margin-bottom: 4px;
}
.doc-empty { color: var(--ink-3); font-style: italic; }
/* ----------------------------------------------------------- doc tools */
.doc-tools { display: flex; gap: 8px; margin-left: auto; flex: none; align-items: center; }
.doc-saved { font-size: 12px; color: var(--ink-3); }
.doc-saved code { font-family: var(--mono); font-size: 11.5px; color: var(--ink-2); }
.doc-head { align-items: center; }
+133
View File
@@ -0,0 +1,133 @@
/* ending.css: The end of a session: the hand-off and the stopping screen. */
/* ----------------------------------------------------------- hand-off */
/* The end of the session. Accented edge because it is the one card on the
page that is not a question and not a note: it is the way out. */
.card.handoff { border-color: var(--accent-line); }
.handoff-step {
margin: 20px 0 0;
padding: 16px 18px;
background: var(--accent-soft);
border: 1px solid var(--accent-line);
border-radius: var(--radius);
}
.handoff-label {
margin: 0 0 6px;
font-size: 11px;
font-weight: 700;
letter-spacing: 0.07em;
text-transform: uppercase;
color: var(--accent);
}
.handoff-where { margin: 0 0 10px; font-size: 13.5px; color: var(--ink-2); }
/* The command and its Copy share a row until the row will not take them.
The text itself wraps: with the continue-in-the-browser sentence on the end
it rarely fits one line, and a sideways scroll would hide exactly the part
someone needs to read before pasting. Nobody retypes it; that is what Copy
is for. */
.handoff-command {
display: flex;
align-items: stretch;
gap: 10px;
flex-wrap: wrap;
}
.handoff-code {
flex: 1 1 260px;
min-width: 0;
font: 13px/1.5 var(--mono);
color: var(--ink);
background: var(--panel);
border: 1px solid var(--rule-2);
border-radius: 8px;
padding: 10px 12px;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
/* Always on show, unlike the Copy on a fenced code block, which waits for a
hover it may never get. This one IS the screen's reason to exist. */
.handoff-copy { flex: none; }
.handoff-note { margin: 8px 0 0; font-size: 12.5px; color: var(--ink-3); }
/* A session with nothing left to run. Quieter than a real next step: no
accented box, plain body text and a small command, because there is
nothing they need to do. */
.handoff-done { margin: 18px 0 0; color: var(--ink-2); }
.handoff-done-text p { margin: 0 0 10px; }
.handoff-done .handoff-code { flex-basis: 180px; font-size: 12px; padding: 6px 10px; }
/* The review offer on a finished build. Louder than the next step, on
purpose: it has to happen here, before they leave, while the next step can
wait for a terminal. A solid accent edge and the big button carry that. */
.review-offer {
margin: 20px 0 0;
padding: 18px 20px;
border: 2px solid var(--accent);
border-radius: var(--radius);
background: var(--panel);
}
.review-offer-title { margin: 0 0 6px; font-size: 18px; }
.review-offer-text { margin: 0; color: var(--ink-2); font-size: 14px; }
.review-offer .btn-row { margin-top: 14px; }
.review-offer .review-go { padding: 12px 26px; font-size: 15.5px; }
.review-offer .handoff-command { margin-top: 10px; }
/* The way back to the dashboard on a finished screen. Quieter than the review
offer: no box, just the button and a small note about the conversation. */
.dashboard-offer { margin: 20px 0 0; }
.dashboard-offer > p:first-child { margin: 0; color: var(--ink-2); font-size: 14px; }
.dashboard-offer .handoff-command { margin-top: 10px; }
.dashboard-note { margin: 8px 0 0; font-size: 12.5px; color: var(--ink-3); }
.handoff-fresh { margin: 16px 0 6px; font-size: 12.5px; color: var(--ink-2); }
.handoff-fresh-row .handoff-code { flex-basis: 180px; font-size: 12px; padding: 6px 10px; }
/* Quick picks under a long multi-select, the review's fix list above all. */
.presets { margin-top: 12px; gap: 8px; }
.presets-label { font-size: 12.5px; color: var(--ink-3); }
/* "Before you close this": three rows on every finished screen. The icon sits
in a coloured circle and the label says the same thing, so no meaning rests
on colour alone. */
.handoff-guide {
margin: 20px 0 0; padding: 14px 16px;
background: var(--panel-2); border: 1px solid var(--rule-2); border-radius: var(--radius);
}
.handoff-guide-title { margin: 0 0 10px; font: 600 15px/1.3 var(--serif); color: var(--ink); }
.handoff-guide-rows { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
.handoff-guide-row { display: flex; align-items: flex-start; gap: 12px; font-size: 14px; color: var(--ink-2); }
.handoff-guide-text { min-width: 0; overflow-wrap: anywhere; }
.handoff-guide-label { color: var(--ink); }
.handoff-guide-icon {
flex: none; display: inline-flex; align-items: center; justify-content: center;
width: 28px; height: 28px; border-radius: 50%; border: 1.5px solid currentColor;
}
.handoff-guide-icon svg { fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
.handoff-guide-icon.is-safe { color: var(--ok); background: var(--ok-soft); }
.handoff-guide-icon.is-fresh { color: var(--accent-ink); background: var(--accent); border-color: var(--accent); }
.handoff-guide-icon.is-carry { color: var(--accent); background: var(--accent-soft); }
.handoff-close { margin: 16px 0 0; color: var(--ink-2); }
.handoff-tools { margin-top: 16px; }
.handoff-unsent {
margin: 14px 0 0;
padding: 10px 14px;
border-radius: 8px;
background: var(--stage-soft);
color: var(--stage);
font-size: 13.5px;
}
/* ----------------------------------------------------------- stopping */
.stop-steps { list-style: none; margin: 4px 0 16px; padding: 0; display: grid; gap: 10px; }
.stop-steps li { display: flex; align-items: center; gap: 10px; font-size: 14px; color: var(--ink-2); }
.stop-steps li.is-done { color: var(--ink); }
.stop-steps li.is-later { color: var(--ink-3); }
.stop-steps li.is-stuck { color: var(--stage); }
.stop-mark { width: 13px; flex: none; text-align: center; font-weight: 700; }
.stop-steps li.is-done .stop-mark { color: var(--ok); }
.stop-note { margin: 0 0 12px; font-size: 13.5px; color: var(--ink-2); }
.stopping .handoff-command { margin-bottom: 4px; }
+253
View File
@@ -0,0 +1,253 @@
/* git.css: The git board. */
/* ------------------------------------------------------------ git board */
/* The git workflow's main column holds the board, and the agent's card sits
inside it, in the card slot under the tab strip. A card that scrolled inside
a scrolling board would put a scrollbar inside a scrollbar, so here the
column takes the one scroll and both flow through it at natural height. */
.main:has(> .git-board) {
overflow-y: auto;
overscroll-behavior: contain;
scrollbar-gutter: stable;
}
/* Listed with .is-primary.has-grow too: that rule (a card with a growing note
box takes the column's height and shrinks into it) outranks a plain .card
here, and a card shrunk under the board spilled its buttons beneath it. */
.git-cards > .card,
.git-cards > .card.is-primary.has-grow,
.main:has(> .git-board) > .git-board {
flex: none;
overflow-y: visible;
min-height: 0;
}
/* In the board's card slot a card's boxes cannot fill the column (it flows,
it does not stretch), so a note box grows with what is typed instead, where
the browser can, rather than scrolling inside a 96px box. */
.git-cards > .card textarea { field-sizing: content; max-height: 50vh; }
/* The card and the pager centre themselves with auto inline margins, and a
grid item with auto margins shrinks to its content, so a short confirm sat
narrow in the middle of the board. In the slot both fill the board's width
instead; the slot's gap spaces them. */
.git-cards > .card,
.git-cards > .pager { margin: 0; }
.main > .git-board {
padding-right: 32px;
display: grid;
/* minmax(0, …): the column never takes the branch table's no-wrap width. */
grid-template-columns: minmax(0, 1fr);
align-content: start;
gap: 14px;
max-width: var(--card-width);
}
/* The board is sized by its column, not the window: the narrow layout keys
off the board's own width. */
.git-board { container-type: inline-size; container-name: git-board; }
/* Plan2Code's card, between the tab strip and the tab's content. */
.git-cards { display: grid; grid-template-columns: minmax(0, 1fr); gap: 10px; }
.git-cards:empty { display: none; }
/* The tab strip: three tabs, Done with git on the right. */
.git-tab-bar {
display: flex;
align-items: flex-end;
gap: 8px;
border-bottom: 1px solid var(--rule);
}
.git-tabs { display: flex; gap: 2px; }
.git-tab {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 8px 14px;
border: 0;
border-bottom: 3px solid transparent;
border-radius: 6px 6px 0 0;
background: transparent;
color: var(--ink-2);
font: inherit;
font-size: 14px;
cursor: pointer;
}
.git-tab:hover { background: var(--panel-2); color: var(--ink); }
.git-tab[aria-selected="true"] { background: var(--accent-soft); color: var(--accent); border-bottom-color: var(--accent); font-weight: 600; }
.git-tab:focus-visible { outline: 2px solid var(--focus); outline-offset: 1px; }
.git-tab-badge {
min-width: 18px;
padding: 0 6px;
border: 1px solid var(--rule-2);
border-radius: 999px;
font-family: var(--mono);
font-size: 11.5px;
line-height: 17px;
text-align: center;
color: var(--ink-2);
}
.git-tab-badge.is-dot { min-width: 0; font-weight: 700; }
.git-tab-badge.is-warn { color: var(--warn); background: var(--warn-soft); border-color: var(--warn); }
.git-tab-badge.is-next { color: var(--accent-ink); background: var(--accent); border-color: var(--accent); }
.git-tab-badge.is-warn.is-next { color: var(--accent-ink); background: var(--warn); border-color: var(--warn); }
.git-done { margin: 0 0 6px auto; }
/* The next step: one primary button, at most one quieter one. */
.git-step {
display: grid;
gap: 6px;
padding: 14px 18px;
background: var(--panel);
border: 1px solid var(--accent-line);
border-left-width: 4px;
border-radius: var(--radius);
}
.git-step.is-warn { border-color: var(--stage); background: var(--stage-soft); }
.git-step.is-calm { border-color: var(--ok); background: var(--ok-soft); }
.git-step-kicker { font-size: 12px; font-weight: 600; letter-spacing: 0.04em; text-transform: uppercase; color: var(--ink-2); }
.git-step.is-calm .git-step-kicker { color: var(--ok); }
.git-step-title, .git-op-title { margin: 0; font: 600 18px/1.25 var(--serif); }
.git-step-why, .git-step-label { margin: 0; font-size: 14px; color: var(--ink-2); }
.git-step-label { font-weight: 600; color: var(--ink); }
.git-step-actions, .git-sync-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.git-hint {
justify-self: start;
padding: 8px 12px;
border: 1px dashed var(--accent-line);
border-radius: var(--radius);
background: transparent;
color: var(--accent);
font: inherit;
font-size: 14px;
cursor: pointer;
}
.git-hint:hover { background: var(--accent-soft); }
.git-hint:focus-visible { outline: 2px solid var(--focus); outline-offset: 1px; }
.git-stale { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin: 0; font-size: 13.5px; color: var(--stage); }
.git-held { font-size: 13.5px; color: var(--ink-2); }
.git-held .md-p { margin: 0; }
.git-wait { margin: 0; font-size: 13.5px; color: var(--stage); }
.git-fresh { margin: 0; font-size: 13px; color: var(--ink-3); }
.git-fresh.is-stale { color: var(--stage); }
.git-panel-tab { display: grid; grid-template-columns: minmax(0, 1fr); gap: 12px; }
.git-changes, .git-sync { display: grid; grid-template-columns: minmax(0, 1fr); gap: 10px; }
.git-sweep-offer { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 0; font-size: 14px; color: var(--ink-2); }
.git-pr-open.is-disabled { opacity: 0.5; cursor: not-allowed; }
/* The board's header is a section lead, not a card: the framed elements are
the agent's card in the slot and the next step under it. */
.git-head {
display: grid;
gap: 6px;
padding: 0 0 10px;
border-bottom: 1px solid var(--rule);
}
.git-head-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: 8px 14px; }
.git-branch { margin: 0; font: 600 22px/1.2 var(--serif); overflow-wrap: anywhere; }
.git-track { font-family: var(--mono); font-size: 14px; color: var(--ink-2); }
.git-head-meta { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; font-size: 13.5px; color: var(--ink-2); }
.git-noremote { font-weight: 600; color: var(--stage); }
.git-activity { color: var(--accent); }
.git-pr { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding-top: 6px; border-top: 1px solid var(--rule); }
.git-pr-open { text-decoration: none; }
.git-pr-ask { font-size: 14px; color: var(--ink); }
.git-pr-base { font-size: 13.5px; color: var(--ink-2); }
.git-pr-base select, .git-field select, .git-field input, .git-search {
font: inherit;
font-size: 14px;
padding: 6px 10px;
color: var(--ink);
background: var(--panel);
border: 1px solid var(--rule-2);
border-radius: 8px;
}
.git-warn, .git-op {
padding: 12px 16px;
border: 1px solid var(--warn);
border-left-width: 4px;
border-radius: var(--radius);
background: var(--warn-soft);
color: var(--ink);
}
.git-op { display: grid; gap: 8px; border-color: var(--stage); background: var(--stage-soft); }
.git-op-files { margin: 0; padding-left: 20px; font-size: 13.5px; }
.git-op-left { color: var(--warn); }
.git-op-clear { color: var(--ok); }
.git-op-actions, .git-panel-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.git-note { margin: 0; color: var(--ink-2); }
.git-result {
padding: 10px 16px;
border: 1px solid var(--accent-line);
border-radius: var(--radius);
background: var(--accent-soft);
font-size: 14px;
}
.git-result-body .md-p { margin: 4px 0 0; }
/* The result box is the line length here: git's stderr runs the full width. */
.git-result-body.md { max-width: none; }
.git-panel {
display: grid;
gap: 10px;
padding: 14px 18px;
background: var(--panel);
border: 1px solid var(--accent-line);
border-radius: var(--radius);
}
.git-panel-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
.git-panel-title { margin: 0; font-size: 16px; }
.git-group-title { margin: 4px 0 0; font-size: 13.5px; color: var(--ink-2); }
.git-field-row { display: flex; flex-wrap: wrap; align-items: end; gap: 10px; }
.git-field { display: grid; gap: 4px; font-size: 13px; color: var(--ink-2); }
.git-field.is-wide { flex: 1 1 16em; }
.git-new-name { font-family: var(--mono); }
.git-name-status { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 0; font-size: 13.5px; color: var(--ink-2); }
.git-name-status.is-free { color: var(--ok); }
.git-name-status.is-invalid, .git-name-status.is-nested { color: var(--warn); }
.git-name-status.is-local, .git-name-status.is-remote { color: var(--stage); }
.git-offer { margin: 0 auto 0 0; font-size: 14px; }
.git-sweep { margin: 0; padding: 0; list-style: none; display: grid; gap: 4px; font-family: var(--mono); font-size: 13.5px; }
.git-ignore { margin-left: 8px; white-space: nowrap; }
.git-tools { display: flex; gap: 8px; align-items: center; margin-bottom: 8px; }
.git-search { flex: 1 1 auto; }
.git-branches { display: grid; grid-template-columns: minmax(0, 1fr); gap: 10px; }
.git-table-wrap { overflow-x: auto; }
.git-table { width: 100%; border-collapse: collapse; font-size: 13.5px; }
.git-table th {
text-align: left;
font-size: 11.5px;
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
color: var(--ink-3);
padding: 6px 8px;
border-bottom: 1px solid var(--rule);
}
.git-table td { padding: 7px 8px; border-bottom: 1px solid var(--rule); vertical-align: top; }
.git-table tr.is-current td { background: var(--accent-soft); }
.git-table tr.is-held td { color: var(--ink-2); }
.git-cell-name { overflow-wrap: anywhere; }
/* A branch name stays whole beside its badges (feature/export-csv never splits
as feature/export- / csv), and the headers stay on one line: a narrow column
scrolls the table sideways instead. */
.git-cell-name .git-name { white-space: nowrap; }
.git-table th { white-space: nowrap; }
.git-name, .git-path { font-family: var(--mono); }
.git-badge { margin-left: 6px; font-size: 10px; padding: 2px 6px; }
.git-badge.is-merged { color: var(--ok); background: var(--ok-soft); border-color: var(--ok); }
.git-badge.is-gone, .git-badge.is-held { color: var(--stage); background: var(--stage-soft); border-color: var(--stage); }
.git-cell-track { font-family: var(--mono); white-space: nowrap; color: var(--ink-2); }
/* Stacked with blocks, not `display: grid`: a grid <td> stops being a table
cell, and its row's separator no longer lines up with the others. */
.git-cell-last > span { display: block; }
.git-cell-last > .git-by { margin-top: 2px; }
.git-by { font-size: 12px; color: var(--ink-3); }
.git-cell-actions { white-space: nowrap; text-align: right; }
.git-cell-actions .btn + .btn { margin-left: 6px; }
.git-remote-only summary { cursor: pointer; font-weight: 600; color: var(--ink-2); padding: 4px 0; }
.git-empty { margin: 0; font-size: 13.5px; color: var(--ink-3); }
/* Last on purpose: the narrow layout overrides the board rules above it. */
@container git-board (max-width: 720px) {
.git-tab-bar { flex-wrap: wrap; }
.git-tabs { flex-wrap: wrap; }
.git-done { margin: 0 0 6px; }
.git-head-meta { flex-direction: column; align-items: flex-start; }
.git-step-actions, .git-sync-actions, .git-op-actions, .git-panel-actions { flex-wrap: wrap; }
.git-step-actions .btn, .git-op-actions .btn { flex: 1 1 auto; }
}
+177
View File
@@ -0,0 +1,177 @@
/* help.css: The help dialog, its diagrams and its tabs. */
/* --------------------------------------------------------- help dialog */
/* Header and Close stay put; only the panel scrolls. */
.modal.help {
width: min(960px, calc(100vw - 32px));
height: min(640px, calc(100vh - 32px));
max-width: none;
max-height: none;
flex-direction: column;
}
.modal.help[open] { display: flex; }
.modal.help .modal-actions { flex: none; margin-top: 16px; align-items: center; }
.help-version { margin-right: auto; font-size: 12.5px; color: var(--ink-3); }
.help-version a { color: inherit; }
.help-layout {
display: grid;
grid-template-columns: 230px 1fr;
gap: 20px;
flex: 1;
min-height: 0;
}
.help-tabs {
display: flex;
flex-direction: column;
gap: 2px;
min-height: 0;
overflow-y: auto;
padding-right: 4px;
}
.help-panels { min-height: 0; min-width: 0; overflow-y: auto; overflow-x: hidden; padding-right: 6px; }
.help-tab {
display: flex;
align-items: center;
gap: 10px;
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;
}
.help-tab:hover { background: var(--panel-2); color: var(--ink); }
.help-tab[aria-selected="true"] { background: var(--accent-soft); color: var(--accent); border-left-color: var(--accent); font-weight: 600; }
.help-tab:focus-visible { outline: 2px solid var(--focus); outline-offset: 1px; }
.help-tab-icon {
width: 18px;
height: 18px;
flex: none;
fill: none;
stroke: currentColor;
stroke-width: 1.8;
stroke-linecap: round;
stroke-linejoin: round;
}
.help-tab:hover .help-tab-icon { stroke: var(--accent); }
.help-panel:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; border-radius: 4px; }
.help-panel h3 { font: 600 18px/1.3 var(--serif); margin: 0 0 12px; color: var(--accent); }
.help-panel p { margin: 0 0 12px; font-size: 13.5px; color: var(--ink-2); }
.help-panel p:last-child { margin-bottom: 0; }
.help-panel strong { color: var(--ink); }
.help-panel .help-lead { font-size: 14.5px; color: var(--ink); margin-bottom: 16px; }
.help-panel h4 { font: 600 14px/1.35 var(--sans); margin: 18px 0 6px; color: var(--ink); }
.help-panel ul,
.help-panel ol { margin: 0 0 12px; padding-left: 20px; font-size: 13.5px; color: var(--ink-2); }
.help-panel li { margin-bottom: 5px; }
.help-panel li:last-child { margin-bottom: 0; }
.help-panel table { border-collapse: collapse; width: 100%; margin: 0 0 12px; font-size: 13.5px; color: var(--ink-2); }
.help-panel th,
.help-panel td { border: 1px solid var(--rule); padding: 7px 10px; text-align: left; vertical-align: top; }
.help-panel th { background: var(--panel-2); font-weight: 600; color: var(--ink); }
.help-panel code {
font: 0.88em var(--mono);
background: var(--panel-2);
border: 1px solid var(--rule);
border-radius: 4px;
padding: 1px 5px;
overflow-wrap: anywhere;
}
/* Help, "When something looks stuck": a calm callout and a symptom / cause / action list. */
.help-panel .help-callout {
display: flex; align-items: flex-start; gap: 12px;
margin: 0 0 16px; padding: 12px 14px;
background: var(--stage-soft); border: 1px solid var(--stage); border-left-width: 4px; border-radius: var(--radius);
}
.help-callout-icon { flex: none; width: 22px; height: 22px; margin-top: 1px; fill: none; stroke: var(--stage); stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
.help-panel .help-callout-label { display: block; margin-bottom: 2px; font-size: 14px; color: var(--ink); }
.help-panel .help-callout p { margin: 0; color: var(--ink); }
.help-panel ol.help-rows { list-style: none; margin: 0 0 12px; padding: 0; }
.help-row { margin: 0 0 8px; padding: 10px 12px; background: var(--panel-2); border: 1px solid var(--rule); border-radius: var(--radius); }
.help-panel .help-row:last-child { margin-bottom: 0; }
.help-row dl { display: grid; grid-template-columns: max-content 1fr; gap: 3px 12px; margin: 0; }
.help-row dt { font-size: 12px; font-weight: 700; letter-spacing: 0.02em; text-transform: uppercase; color: var(--ink-2); padding-top: 1px; }
.help-row dd { margin: 0; font-size: 13.5px; color: var(--ink); min-width: 0; overflow-wrap: anywhere; }
@media (max-width: 520px) {
.help-row dl { grid-template-columns: 1fr; gap: 0; }
.help-row dt { margin-top: 6px; }
.help-row dt:first-child { margin-top: 0; }
}
.help-panel .handoff-command { margin: 0 0 12px; }
.help-panel .handoff-command:last-child { margin-bottom: 0; }
.help-panel .handoff-code {
font: 13px/1.5 var(--mono);
background: var(--panel);
border: 1px solid var(--rule-2);
border-radius: 8px;
padding: 10px 12px;
}
/* The icon sheet: present for <use href>, never drawn itself. */
.help-icons { position: absolute; width: 0; height: 0; overflow: hidden; }
/* The diagrams. Colors only from variables, so each drawing follows the
theme and the chosen highlight without a line of script. */
.help-figure { margin: 4px 0 16px; }
.help-figure figcaption,
.help-moods-title { display: block; margin-top: 4px; font-size: 12.5px; color: var(--ink-2); }
.help-diagram { display: block; width: 100%; max-width: 560px; height: auto; margin: 8px 0 4px; }
.hd-box { fill: var(--panel-2); stroke: var(--rule-2); stroke-width: 1.2; }
.hd-line { fill: none; stroke: var(--ink-3); stroke-width: 1.4; }
.hd-dash { stroke-dasharray: 4 4; }
.hd-label { fill: var(--ink); font: 13px var(--sans); }
.hd-label.small { fill: var(--ink-2); font-size: 12px; }
.hd-accent { fill: var(--accent-soft); stroke: var(--accent); stroke-width: 1.4; }
.hd-label.hd-accent { fill: var(--accent); stroke: none; font-weight: 600; }
.hd-flow { fill: none; stroke: var(--accent); stroke-width: 2; stroke-dasharray: 6 10; stroke-linecap: round; }
.hd-arrow { fill: var(--ink-3); }
/* Tab 3: six live clones of Planny, one per mood. */
.help-moods-row { display: grid; grid-template-columns: repeat(3, 1fr); gap: 14px 8px; max-width: 560px; }
@media (min-width: 900px) {
.help-moods-row { grid-template-columns: repeat(6, 1fr); }
}
.help-mood { display: flex; flex-direction: column; align-items: center; gap: 6px; }
.help-mood-bot { width: 40px; height: 56px; }
.help-mood span { font-size: 12.5px; color: var(--ink-2); text-align: center; }
/* The travelling highlight on the flow diagrams: only on the visible panel,
only while the dialog is open, and only when the system allows motion.
Otherwise the dashes simply sit still. */
@media (prefers-reduced-motion: no-preference) {
@keyframes hd-travel { to { stroke-dashoffset: -32; } }
.help-panel:not([hidden]) .hd-flow { animation: hd-travel 1.6s linear infinite; }
}
@media (max-width: 720px) {
.help-layout { grid-template-columns: 1fr; grid-template-rows: auto 1fr; gap: 12px; }
.help-tabs { flex-direction: row; overflow-x: auto; overflow-y: hidden; padding: 0 0 4px; }
.help-tab {
width: auto;
flex: none;
white-space: nowrap;
border-left: 0;
border-bottom: 3px solid transparent;
border-radius: 6px 6px 0 0;
}
.help-tab[aria-selected="true"] { border-bottom-color: var(--accent); }
}
.about-live {
padding: 9px 12px;
border-radius: 8px;
background: var(--panel-2);
border: 1px solid var(--rule);
}
.about-live.is-good { background: var(--ok-soft); border-color: var(--ok); color: var(--ok); }
.about-live.is-bad { background: var(--stage-soft); border-color: var(--stage); color: var(--stage); }
+65
View File
@@ -0,0 +1,65 @@
/* looks.css: The looks button and the highlight swatches. */
/* ------------------------------------------------------- looks button */
.icon-btn {
appearance: none;
flex: none;
margin-left: 14px;
width: 30px;
height: 30px;
padding: 0;
display: grid;
place-items: center;
border: 1px solid transparent;
border-radius: 8px;
background: transparent;
cursor: pointer;
}
.icon-btn:hover { background: var(--panel-2); border-color: var(--rule); }
.icon-btn svg { width: 17px; height: 17px; }
.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); }
.icon-btn:hover .ab-ring { stroke: var(--accent); }
.icon-btn:hover .ab-mark, .icon-btn:hover .ab-dot { stroke: var(--accent); fill: none; }
.icon-btn:hover .ab-dot { fill: var(--accent); }
a.icon-btn { box-sizing: border-box; text-decoration: none; }
/* A link in a dialog (the update modal's release, Help's version) keeps the
accent once visited: the browser's purple is unreadable on the dark theme. */
.modal a:not(.btn), .modal a:not(.btn):visited { color: var(--accent); }
.icon-btn .mg-body { fill: none; stroke: var(--ink-3); stroke-width: 1.4; stroke-linejoin: round; }
.icon-btn .mg-line { fill: none; stroke: var(--ink-2); stroke-width: 1.4; stroke-linecap: round; stroke-linejoin: round; }
.icon-btn:hover .mg-body, .icon-btn:hover .mg-line { stroke: var(--accent); }
.icon-btn .gr-teeth { fill: none; stroke: var(--ink-3); stroke-width: 2.2; }
.icon-btn .gr-ring { fill: none; stroke: var(--ink-3); stroke-width: 1.6; }
.icon-btn .gr-hub { fill: none; stroke: var(--ink-2); stroke-width: 1.4; }
.icon-btn:hover .gr-teeth, .icon-btn:hover .gr-ring, .icon-btn:hover .gr-hub { stroke: var(--accent); }
/* ------------------------------------------------------------ swatches */
/* Thirty-two of them: a fixed sixteen-column grid so they sit in two even
rows in the wide dialog, and four even rows of eight on a narrow window,
rather than leaving a straggler alone on the last line. */
.swatches { display: grid; grid-template-columns: repeat(16, minmax(0, 34px)); gap: 8px; }
@media (max-width: 720px) {
.swatches { grid-template-columns: repeat(8, minmax(0, 34px)); }
}
.swatch {
appearance: none;
width: 100%;
aspect-ratio: 1;
padding: 0;
border-radius: 50%;
border: 2px solid var(--rule-2);
cursor: pointer;
}
.swatch:hover { border-color: var(--ink-3); }
.swatch[aria-pressed="true"] {
border-color: var(--ink);
box-shadow: 0 0 0 2px var(--panel), 0 0 0 4px var(--ink);
}
+896
View File
@@ -0,0 +1,896 @@
/* pieces.css: Shared pieces: cards, options, settled answers, pager, forms, checklist, markdown and the modal. */
/* --------------------------------------------------------------- card */
.card {
background: var(--panel);
border: 1px solid var(--rule);
border-radius: var(--radius);
padding: 24px 26px;
max-width: min(var(--card-width), 100%);
box-shadow: var(--shadow);
margin: 0 auto 18px;
}
.card.is-answered { border-color: var(--ok); }
.card.is-staged { border-color: var(--stage); }
.card-kicker {
font-size: 11.5px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--ink-3);
margin-bottom: 7px;
}
.card h2 { font: 600 25px/1.22 var(--serif); margin: 0 0 12px; }
.card .prompt { color: var(--ink-2); max-width: 62ch; }
/* Text inside the card runs the card's width. The prompt carries both
classes, so both measure caps come off here; documents keep .md's 68ch. */
.card .md, .card .prompt { max-width: none; }
.card .prompt p:first-child { margin-top: 0; }
.card-files {
margin-top: 10px;
font-size: 0.9em;
}
.card-files summary {
cursor: pointer;
color: var(--ink-2);
}
.card-files table {
margin-top: 6px;
}
.card-files td:last-child {
word-break: break-all;
}
.card-note {
background: var(--accent-soft);
border: 1px solid var(--accent-line);
border-radius: 8px;
padding: 10px 14px;
font-size: 13.5px;
color: var(--ink-2);
margin: 14px 0 0;
}
/* Folded-in sections. A page holds one card; what used to be cards of their
own (the "all caught up" lull, the session notes) is a labelled section
inside it instead. */
.card-lead { margin: 0 0 16px; }
.card-extra { margin: 18px 0 0; }
.note-kicker {
font-size: 11px;
font-weight: 700;
letter-spacing: 0.07em;
text-transform: uppercase;
color: var(--ink-3);
margin: 0 0 4px;
}
.note-title { font: 600 16px/1.3 var(--serif); color: var(--ink); margin: 0 0 6px; }
/* ------------------------------------------------------------ options */
.options { list-style: none; margin: 20px 0 0; padding: 0; display: grid; gap: 9px; }
.option {
display: flex;
gap: 12px;
align-items: flex-start;
border: 1px solid var(--rule-2);
border-radius: var(--radius);
padding: 13px 15px;
cursor: pointer;
background: var(--panel);
transition: border-color 0.12s, background 0.12s;
}
.option:hover { border-color: var(--accent-line); background: var(--panel-2); }
.option:focus-within { outline: 2px solid var(--focus); outline-offset: 2px; }
.option input { margin: 3px 0 0; accent-color: var(--accent); width: 17px; height: 17px; flex: none; }
.option.is-picked { border-color: var(--stage); background: var(--stage-soft); }
.option.is-recorded { border-color: var(--ok); background: var(--ok-soft); }
/* A settled question is a record. Nothing in it may look pressable. */
.option.is-locked {
cursor: default;
background: var(--panel-2);
border-color: var(--rule);
opacity: 0.7;
}
.option.is-locked:hover { border-color: var(--rule); background: var(--panel-2); }
.option.is-locked.is-recorded {
opacity: 1;
border-color: var(--ok);
background: var(--ok-soft);
}
.option.is-locked.is-recorded:hover { border-color: var(--ok); background: var(--ok-soft); }
.option-mark {
flex: none;
width: 17px;
text-align: center;
font-size: 13px;
line-height: 1.5;
color: var(--ink-3);
margin-top: 2px;
}
.option-mark.on { color: var(--ok); font-weight: 700; }
/* "Something else" is one of the choices, so it sits in the list wearing the
same clothes. Only the box inside it is clickable, hence the plain cursor. */
.option.is-other { cursor: default; }
.option.is-other .option-label label { cursor: pointer; }
.other-text { margin-top: 9px; min-height: 76px; }
.option-body { min-width: 0; flex: 1; }
.option-label { font-weight: 600; display: flex; gap: 9px; align-items: baseline; flex-wrap: wrap; }
.option-key {
font: 700 12px/1 var(--mono);
color: var(--ink-3);
border: 1px solid var(--rule-2);
border-radius: 4px;
padding: 3px 5px;
}
.option-detail { color: var(--ink-2); font-size: 13.5px; margin-top: 4px; }
.pill {
font-size: 10.5px;
font-weight: 700;
letter-spacing: 0.05em;
text-transform: uppercase;
border: 1px solid transparent;
border-radius: 99px;
padding: 2px 7px;
white-space: nowrap;
}
.pill.suggested { background: var(--accent-soft); color: var(--accent); border-color: var(--accent-line); }
.pill.done { background: var(--ok-soft); color: var(--ok); }
.pill.staged { background: var(--stage-soft); color: var(--stage); }
/* The Subagents tab: one row per reported helper, newest state in a pill. */
.sa-card h2 { margin: 0 0 6px; }
.sa-card > .help { margin: 0 0 16px; }
.sa-alone { margin: 0; color: var(--ink-2); }
.sa-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }
.sa-row { border: 1px solid var(--rule); border-radius: 8px; background: var(--panel-2); padding: 12px 14px; }
.sa-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
.sa-title { min-width: 0; overflow-wrap: anywhere; }
.sa-ask {
margin: 4px 0 0; color: var(--ink-2); font-size: 13.5px;
display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden;
}
.sa-result { margin: 8px 0 0; padding-top: 8px; border-top: 1px solid var(--rule); font-size: 13.5px; }
.sa-pill { display: inline-flex; align-items: center; gap: 6px; flex: none; }
.sa-pill.is-running { background: var(--accent-soft); color: var(--accent); border-color: var(--accent-line); }
.sa-pill.is-done { background: var(--ok-soft); color: var(--ok); }
.sa-pill.is-failed { background: var(--warn-soft); color: var(--warn); }
.sa-pill .spinner.tiny { width: 10px; height: 10px; }
/* The dialog's number box, themed like the page's other inputs. */
.subagents input[type="number"] {
width: 5em; font: inherit; color: var(--ink); background: var(--panel-2);
border: 1px solid var(--rule-2); border-radius: 6px; padding: 4px 8px;
}
/* ------------------------------------------------------ settled answer */
.answered {
margin-top: 20px;
border: 1px solid var(--ok);
border-radius: var(--radius);
background: var(--ok-soft);
padding: 14px 16px;
}
.answered-head {
display: flex;
align-items: center;
gap: 8px;
margin: 0;
font-size: 11.5px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--ok);
}
.answered-mark {
flex: none;
width: 18px; height: 18px;
border-radius: 50%;
background: var(--ok);
color: var(--panel);
font: 700 11px/18px var(--sans);
text-align: center;
}
.answered-values { list-style: none; margin: 9px 0 0; padding: 0; display: grid; gap: 4px; }
.answered-values li { font-weight: 600; font-size: 15.5px; color: var(--ink); }
.answered-text {
margin: 9px 0 0;
padding: 2px 0 2px 13px;
border-left: 3px solid var(--ok);
color: var(--ink);
white-space: pre-wrap;
}
/* In flight is not settled. Same shape, the color of work in progress. */
.answered.is-sent { border-color: var(--stage); background: var(--stage-soft); }
.answered.is-sent .answered-head { color: var(--stage); }
.answered.is-sent .answered-mark { background: var(--stage); }
.answered.is-sent .answered-text { border-left-color: var(--stage); }
.card.is-inflight { border-color: var(--stage); }
.card.is-inflight .option.is-locked.is-recorded {
border-color: var(--stage);
background: var(--stage-soft);
}
.card.is-inflight .option.is-locked.is-recorded:hover {
border-color: var(--stage);
background: var(--stage-soft);
}
.card.is-inflight .option-mark.on { color: var(--stage); }
.card.is-inflight .pill.done { background: var(--stage-soft); color: var(--stage); }
/* Nothing to show is not an achievement: drop the green. */
.answered.is-empty { border-color: var(--rule); background: var(--panel-2); }
.answered.is-empty .answered-head { color: var(--ink-3); }
.answered.is-empty .answered-mark { background: var(--ink-3); }
.answered-none { margin: 9px 0 0; color: var(--ink-2); font-style: italic; }
.answered-lock { margin: 11px 0 0; font-size: 12.5px; color: var(--ink-2); }
.step.is-locked { opacity: 0.85; }
.step-body { flex: 1; min-width: 0; }
.row-item.is-locked { background: var(--panel-2); }
.row-title-static { font-weight: 600; margin: 0; }
/* -------------------------------------------------------------- pager */
.pager {
display: flex;
align-items: center;
gap: 12px;
/* No bottom margin: the pager is the last thing in the column, so a margin
here only adds to the column's own bottom padding. */
margin: 0 auto;
max-width: min(var(--card-width), 100%);
}
.pager.one { justify-content: flex-end; }
.pager.one .pager-btn { flex: 0 1 auto; }
/* The button is as wide as its label, not as wide as its share of the row.
Filled accent stretched across half the page read as a banner rather than as
a button. The empty slot and the counter take the slack instead. */
.pager-btn {
flex: 0 1 auto;
min-width: 0;
max-width: 42%;
display: flex;
align-items: center;
gap: 10px;
}
.pager-slot { flex: 1 1 0; min-width: 0; }
/* Which end it points at, not where it happens to sit. `:last-of-type` was
wrong at the end of the queue, where "Previous" is the only button and so is
also the last one: its label drifted into the middle of the row. */
.pager-btn.next { justify-content: flex-end; text-align: right; }
.pager-label { display: grid; min-width: 0; }
.pager-kicker {
font-size: 10.5px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--ink-3);
}
/* The one the answer just handed you to. Its label is --accent-ink, never a
flat white: half the accents are light shades in dark mode, where white on
the fill drops to about 2:1 and the kicker above the title disappears. */
.pager-btn.lead {
background: var(--accent);
border-color: var(--accent);
color: var(--accent-ink);
}
.pager-btn.lead:hover:not(:disabled) { background: var(--accent); filter: brightness(1.08); }
/* 0.9, not the 0.78 that reads as quiet furniture: at 10.5px this is small
text, and the lighter fills drop it under 4.5:1 well before it looks faint. */
.pager-btn.lead .pager-kicker { color: var(--accent-ink); opacity: 0.9; }
.pager-btn.lead .pager-arrow { color: var(--accent-ink); }
.pager-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pager-arrow { flex: none; color: var(--ink-3); font-size: 15px; }
.pager-count { flex: 1 1 0; text-align: center; font-size: 12.5px; color: var(--ink-3); white-space: nowrap; }
/* -------------------------------------------------------------- forms */
.field { margin-top: 18px; }
.field > label,
.field-head > label { display: block; font-weight: 600; font-size: 13.5px; margin-bottom: 6px; }
.field .help { color: var(--ink-3); font-size: 13px; margin: 0 0 8px; }
/* The label and the offer to fill the box sit on one line. */
.field-head {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
}
textarea, input[type="text"] {
width: 100%;
font: inherit;
color: var(--ink);
background: var(--panel-2);
border: 1px solid var(--rule-2);
border-radius: 8px;
padding: 11px 13px;
resize: vertical;
}
textarea { min-height: 96px; }
/* No max-height: the handle can pull the box past the fill, and the card then
scrolls. Its min-height is the fill, written by app.js. */
textarea.grow { resize: vertical; }
/* The border going accent IS the focus signal here, so the page-wide blue
:focus-visible outline comes off: on a bordered field it reads as a second,
clashing ring. */
textarea:focus, input[type="text"]:focus { border-color: var(--accent); outline: none; }
input[type="text"].invalid { border-color: var(--warn); }
.field-error { color: var(--warn); font-size: 13px; margin-top: 6px; }
.field-ok { color: var(--ok); font-size: 13px; margin-top: 6px; }
/* Starter templates on a fresh-idea box: Blank plus the skill's set, between
the label row and the box. The pressed chip wears the accent. */
.tpl-row { display: flex; flex-wrap: wrap; gap: 6px; margin: 0 0 10px; }
.tpl-chip {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 5px 12px;
border: 1px solid var(--rule-2);
border-radius: 999px;
background: var(--panel);
font: inherit;
font-size: 13px;
color: var(--ink);
cursor: pointer;
transition: border-color 0.15s ease, background 0.15s ease;
}
.tpl-chip:hover { border-color: var(--accent-line); }
.tpl-chip:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
.tpl-chip[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
.tpl-pill {
padding: 1px 7px;
border: 1px solid var(--accent-line);
border-radius: 999px;
background: var(--accent-soft);
color: var(--accent);
font-size: 11px;
font-weight: 600;
}
/* Swapping over typed text asks first, in the page's staged/careful amber. */
.tpl-replace {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin: 0 0 10px;
padding: 6px 12px;
border: 1px solid var(--stage);
border-radius: 8px;
background: var(--stage-soft);
color: var(--stage);
font-size: 13px;
}
.tpl-replace span { margin-right: auto; }
.tpl-replace .btn.tiny { margin-bottom: 0; }
.btn {
appearance: none;
font: inherit;
font-weight: 600;
border-radius: 8px;
padding: 10px 18px;
cursor: pointer;
border: 1px solid var(--rule-2);
background: var(--panel);
color: var(--ink);
transition: filter 0.12s, background 0.12s;
}
.btn:hover:not(:disabled) { background: var(--panel-2); }
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
/* A review card's approve verdict, before it is picked: the accent outline
marks it as the main way forward. */
.btn.is-approve { border-color: var(--accent); }
/* Send glows and breathes while there is something to send: the steady
--glow, plus a soft accent ring that spreads and fades. The ring is off
under reduced motion, below; the glow stays. */
#btn-send:not(:disabled) { box-shadow: var(--glow); }
@keyframes send-pulse {
0% { box-shadow: var(--glow), 0 0 0 0 var(--accent-line); }
100% { box-shadow: var(--glow), 0 0 0 6px transparent; }
}
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
.btn.ghost:hover { background: var(--panel-2); color: var(--ink); }
.btn.danger { border-color: var(--warn); color: var(--warn); }
.btn.danger.is-on { background: var(--warn); color: #fff; }
.btn.small { padding: 7px 13px; font-size: 13.5px; }
/* Available, but not the step. Reads as a button, does not shout like one. */
.btn.standby {
background: transparent;
border-color: var(--accent-line);
color: var(--accent);
}
.btn.standby:hover:not(:disabled) { background: var(--accent-soft); }
.btn.tiny {
padding: 3px 9px;
font-size: 12px;
font-weight: 600;
color: var(--accent);
border-color: var(--accent-line);
background: var(--accent-soft);
margin-bottom: 6px;
}
.btn.tiny:hover:not(:disabled) { background: var(--accent-soft); filter: brightness(1.04); }
.btn-row { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 18px; align-items: center; }
.linky {
appearance: none; border: 0; background: none; padding: 0;
color: var(--ink-3); font: inherit; font-size: 13px;
text-decoration: underline; cursor: pointer;
}
.linky:hover { color: var(--accent); }
/* The beat between "Skip this one" and the move to the next card. */
.skip-flash {
display: inline-block; margin: 16px 0 0 12px;
font-size: 13px; font-weight: 600; color: var(--stage);
animation: skip-flash-in 0.15s ease;
}
@keyframes skip-flash-in { from { opacity: 0; } }
.card.question.is-skip-flash { border-color: var(--stage); }
@media (prefers-reduced-motion: reduce) {
.skip-flash { animation: none; }
}
/* ---------------------------------------------------------- checklist */
.steps { list-style: none; margin: 18px 0 0; padding: 0; display: grid; gap: 8px; counter-reset: step; }
.step {
display: flex; gap: 12px; align-items: flex-start;
border: 1px solid var(--rule); border-radius: 8px; padding: 11px 14px;
background: var(--panel-2);
}
.step input { margin-top: 3px; accent-color: var(--ok); width: 17px; height: 17px; flex: none; }
.step-num {
flex: none; width: 22px; height: 22px; border-radius: 50%;
background: var(--accent-soft); color: var(--accent);
font: 700 12px/22px var(--sans); text-align: center;
}
/* --------------------------------------------------------- orderable */
.rows { list-style: none; margin: 18px 0 0; padding: 0; display: grid; gap: 8px; }
.row-item {
display: flex; gap: 12px; align-items: flex-start;
border: 1px solid var(--rule-2); border-radius: 8px; padding: 12px 14px;
background: var(--panel);
}
.row-item.dragging { opacity: 0.4; }
.row-item.drop-target { border-color: var(--accent-line); border-style: dashed; }
.row-handle {
flex: none; cursor: grab; color: var(--ink-3); font-size: 15px; line-height: 1.4;
background: none; border: 0; padding: 2px 4px;
}
.row-handle:active { cursor: grabbing; }
.row-main { flex: 1; min-width: 0; }
.row-title { font-weight: 600; width: 100%; background: transparent; border: 1px solid transparent; border-radius: 6px; padding: 3px 6px; margin: -3px -6px; color: var(--ink); font-family: inherit; font-size: inherit; }
.row-title:hover:not(:disabled) { border-color: var(--rule); }
.row-title:focus { border-color: var(--accent); background: var(--panel-2); }
.row-title:disabled { opacity: 1; }
.row-body { color: var(--ink-2); font-size: 13.5px; margin-top: 3px; }
.row-order { font: 700 12px/1 var(--mono); color: var(--ink-3); flex: none; margin-top: 4px; }
.row-tools { display: flex; gap: 4px; flex: none; }
/* ----------------------------------------------------------- markdown */
/* A word or path longer than the line breaks instead of widening the page;
code blocks and tables keep their own scroll. */
.md { max-width: 68ch; overflow-wrap: anywhere; }
.md pre, .md .md-table { overflow-wrap: normal; }
.md-h { font-family: var(--serif); font-weight: 600; margin: 22px 0 9px; line-height: 1.25; }
h2.md-h { font-size: 21px; }
h3.md-h { font-size: 17.5px; }
h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
.md-p { margin: 0 0 11px; }
.md-list { margin: 0 0 11px; padding-left: 22px; }
.md-li { margin-bottom: 5px; }
.md-task { display: inline-block; width: 16px; color: var(--ink-3); font-weight: 700; }
.md-task.is-done { color: var(--ok); }
.md-task.is-blocked { color: var(--warn); }
.md-task.is-doing { color: var(--accent); }
.md-task.is-assumed { color: var(--stage); }
.md-li.is-task {
list-style: none; margin-left: -18px;
display: grid; grid-template-columns: 16px minmax(0, 1fr); column-gap: 4px; align-items: baseline;
}
.md-li.is-task > :not(.md-task) { grid-column: 2; }
.md-li.is-task > .md-p:last-child { margin-bottom: 0; }
.md-quote {
margin: 0 0 11px; padding: 2px 0 2px 15px;
border-left: 3px solid var(--rule-2); color: var(--ink-2);
}
.md-code {
font: 0.88em var(--mono);
background: var(--panel-2);
border: 1px solid var(--rule);
border-radius: 4px;
padding: 1px 5px;
}
.md-pre-wrap { position: relative; margin: 0 0 13px; }
.md-pre {
font: 13px/1.5 var(--mono);
background: var(--panel-2);
border: 1px solid var(--rule);
border-radius: 8px;
padding: 14px 16px;
overflow-x: auto;
margin: 0;
}
.md-copy {
position: absolute; top: 8px; right: 8px;
font: 600 11.5px var(--sans);
background: var(--panel); color: var(--ink-2);
border: 1px solid var(--rule-2); border-radius: 6px;
padding: 4px 9px; cursor: pointer; opacity: 0;
transition: opacity 0.12s;
}
.md-pre-wrap:hover .md-copy, .md-copy:focus { opacity: 1; }
/* The muted nudge on command-looking blocks, a caption under the block. */
.md-run-hint {
margin: 4px 2px 0;
font: 11px var(--sans); color: var(--ink-3);
opacity: 0.8;
}
/* No "paste it into the Ask tab" nudge where the command is the card's own
action (a confirm's consequences, a finished screen's commit beside its
Commit it now button). */
.is-consequences .md-run-hint,
.handoff .md-run-hint { display: none; }
.md-hr { border: 0; border-top: 1px solid var(--rule); margin: 20px 0; }
.md-table-wrap { overflow-x: auto; margin: 0 0 13px; }
.md-table { border-collapse: collapse; width: 100%; font-size: 13.5px; }
.md-table th, .md-table td { border: 1px solid var(--rule); padding: 8px 11px; text-align: left; }
.md-table th { background: var(--panel-2); font-weight: 600; }
.md-img { max-width: 100%; border-radius: 8px; }
.doc-figure { margin: 0 0 13px; }
.doc-img { display: block; max-width: 100%; height: auto; border: 1px solid var(--rule); border-radius: 8px; }
.doc-figure figcaption { font-size: 13px; color: var(--ink-2); margin-top: 6px; }
.md a { color: var(--accent); }
/* -------------------------------------------------------------- modal */
.modal {
border: 1px solid var(--rule-2);
border-radius: var(--radius);
background: var(--panel);
color: var(--ink);
padding: 24px 26px;
max-width: 440px;
width: calc(100vw - 32px);
box-shadow: var(--shadow);
}
.modal::backdrop { background: rgba(0, 0, 0, 0.45); }
.modal h2 { font: 600 21px/1.25 var(--serif); margin: 0 0 10px; }
/* The Welcome: a dark poster with Planny, four columns, one button. */
.modal.welcome {
width: min(840px, calc(100vw - 32px));
max-width: none;
padding: 0;
overflow: hidden;
}
.modal.welcome[open] { display: flex; flex-direction: column; max-height: calc(100vh - 96px); }
.welcome-poster {
position: relative;
flex: none;
overflow: hidden;
padding: 52px 48px 40px;
text-align: center;
color: #fff;
background:
radial-gradient(circle at 50% 125%, color-mix(in srgb, var(--accent) 85%, #fff) 0, transparent 58%),
linear-gradient(180deg, #16181d, color-mix(in srgb, var(--accent) 50%, #16181d));
}
.welcome-sky i { position: absolute; width: 3px; height: 3px; border-radius: 50%; background: #fff; opacity: 0.55; }
.welcome-sky i:nth-child(1) { top: 18%; left: 11%; }
.welcome-sky i:nth-child(2) { top: 34%; left: 84%; }
.welcome-sky i:nth-child(3) { top: 12%; left: 66%; }
.welcome-sky i:nth-child(4) { top: 56%; left: 20%; }
.welcome-sky i:nth-child(5) { top: 62%; left: 91%; }
.welcome-sky i:nth-child(6) { top: 26%; left: 32%; width: 2px; height: 2px; }
.welcome-bot { display: flex; justify-content: center; }
/* The dock's own Planny, larger and in light ink for the dark poster. */
.welcome-bot .planny { width: 70px; height: 96px; }
.welcome-bot .planny .shell,
.welcome-bot .planny .smile,
.welcome-bot .planny .arm path { stroke: #f0ece5; }
.welcome-bot .planny .shell { fill: #1e2127; }
.welcome-bot .planny .arm circle,
.welcome-bot .planny .foot { fill: #f0ece5; }
.welcome-kicker {
margin: 20px 0 6px;
font-size: 12px;
letter-spacing: 0.14em;
text-transform: uppercase;
color: rgba(255, 255, 255, 0.75);
}
.modal.welcome h2 { font: 600 38px/1.15 var(--serif); margin: 0 0 12px; color: #fff; }
.welcome-lead { margin: 0 auto; max-width: 52ch; font-size: 15px; line-height: 1.55; color: rgba(255, 255, 255, 0.85); }
.welcome-cols {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 20px;
min-height: 0;
overflow-y: auto;
padding: 34px 36px 8px;
text-align: center;
}
.welcome-col h3 { font: 600 15px/1.3 var(--sans); margin: 12px 0 4px; color: var(--ink); }
.welcome-col p { margin: 0; font-size: 13px; line-height: 1.5; color: var(--ink-2); }
.welcome-col strong { color: var(--ink); }
.welcome-col code {
font: 600 12px var(--mono);
padding: 1px 6px;
border-radius: 5px;
background: var(--accent-soft);
color: var(--accent);
}
.welcome-col kbd {
font: 600 11.5px var(--mono);
padding: 0 6px;
border-radius: 5px;
border: 1px solid var(--rule-2);
border-bottom-width: 2px;
background: var(--panel-2);
color: var(--ink);
}
.welcome-dot { display: inline-grid; place-items: center; width: 50px; height: 50px; border-radius: 50%; }
.welcome-dot svg {
width: 22px;
height: 22px;
fill: none;
stroke: currentColor;
stroke-width: 1.8;
stroke-linecap: round;
stroke-linejoin: round;
}
.welcome-dot.is-accent { background: var(--accent-soft); color: var(--accent); }
.welcome-dot.is-stage { background: var(--stage-soft); color: var(--stage); }
.welcome-dot.is-plain { background: var(--panel-2); color: var(--ink-2); border: 1px solid var(--rule); }
.welcome-dot.is-ok { background: var(--ok-soft); color: var(--ok); }
.welcome-dot.is-bare { background: none; color: var(--ok); }
.welcome-dot.is-bare svg { width: 30px; height: 30px; }
.modal.welcome .modal-actions { flex: none; justify-content: center; margin: 0; padding: 24px 36px 36px; }
.modal.welcome .modal-actions .btn { padding: 12px 40px; font-size: 15px; border-radius: 999px; }
@media (max-width: 720px) {
.welcome-poster { padding: 36px 24px 28px; }
.modal.welcome h2 { font-size: 28px; }
.welcome-cols { grid-template-columns: 1fr 1fr; padding: 24px 20px 8px; }
}
.help-link {
background: none;
border: 0;
padding: 0;
font: inherit;
color: var(--accent);
text-decoration: underline;
cursor: pointer;
}
.help-link:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; border-radius: 2px; }
.modal-blurb { margin: 0 0 18px; color: var(--ink-2); font-size: 13.5px; }
.modal-ranges { border: 0; margin: 0; padding: 0; display: grid; gap: 8px; }
.modal-ranges legend {
font-size: 11.5px;
font-weight: 700;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--ink-3);
padding: 0 0 8px;
}
.modal-ranges label {
display: flex;
align-items: center;
gap: 10px;
border: 1px solid var(--rule-2);
border-radius: 8px;
padding: 10px 13px;
cursor: pointer;
}
.modal-ranges label:hover { border-color: var(--accent-line); }
.modal-ranges input[type="radio"],
.modal-ranges input[type="checkbox"] { accent-color: var(--accent); width: 17px; height: 17px; flex: none; }
/* Preferences gets the room the swatch grid needs, and spends it laying each
set of choices out side by side instead of stacking them into a tall
scroll. Back to a stack on a narrow window. */
.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 .help { grid-column: 1 / -1; }
/* The per-cue boxes sit under the master switch, greyed and locked while it
is off rather than hidden, so the picks stay visible. */
.looks-sound-events { display: grid; gap: 8px; }
.looks-sound-events.is-off { opacity: 0.45; }
.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; }
}
/* User Preferences itself (not the dialogs borrowing .looks): wider, and only
the body scrolls, so Back to default and Done never leave the screen. */
.modal.prefs { max-width: 880px; }
.modal.prefs[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
.prefs-body { overflow-y: auto; min-height: 0; flex: 1 1 auto; margin-right: -12px; padding-right: 12px; padding-top: 10px; }
/* A line scrolled up under the title fades out rather than being sliced. */
.prefs-body { -webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 12px); mask-image: linear-gradient(to bottom, transparent 0, #000 12px); }
.modal.prefs .modal-actions { flex: none; margin-top: 16px; padding-top: 14px; border-top: 1px solid var(--rule); }
/* The Workspace dialog: one entry per folder, the original first, then the
Add row. Wide enough for a real path; the list scrolls, the Add row and the
actions stay put. */
.modal.workspace { max-width: 680px; }
.modal.workspace[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
.workspace .modal-blurb { margin-bottom: 6px; }
.workspace-scope { margin: 0 0 16px; color: var(--ink-3, var(--ink-2)); font-size: 12.5px; }
.workspace-list {
list-style: none; margin: 0; padding: 0;
display: grid; gap: 12px;
overflow-y: auto; min-height: 0; flex: 0 1 auto;
}
.ws-entry {
border: 1px solid var(--rule-2); border-radius: 8px;
padding: 12px 14px; background: var(--panel-2);
display: grid; gap: 8px;
}
.ws-entry.is-missing { border-color: var(--warn); }
.ws-head { display: flex; align-items: center; flex-wrap: wrap; gap: 6px 10px; }
.ws-chip {
font: 600 12.5px var(--mono);
color: var(--accent); background: var(--accent-soft);
border: 1px solid var(--accent-line); border-radius: 99px;
padding: 1px 9px;
}
.ws-original { font-size: 12.5px; color: var(--ink-3); }
.ws-path-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.ws-path {
flex: 1 1 14em; min-width: 0;
font: 12.5px var(--mono); color: var(--ink-2);
overflow-wrap: anywhere;
}
.ws-path-row .btn { flex: none; }
.ws-field { display: grid; grid-template-columns: 7.5em 1fr; align-items: center; gap: 4px 10px; font-size: 13px; }
.ws-field label { color: var(--ink-2); font-weight: 600; }
.ws-field input[type="text"] { padding: 6px 10px; font-size: 13.5px; background: var(--panel); }
.ws-field .field-error { grid-column: 2; margin: 0; }
.ws-mark { margin: 0; font-size: 13px; }
.ws-mark.is-missing, .ws-mark.is-issue { color: var(--warn); }
.ws-mark.is-nested { color: var(--ink-3); }
.ws-hint-row { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
.ws-hint-row .btn.tiny { margin-bottom: 0; }
.ws-hint, .banner-hint {
font: 12.5px var(--mono);
background: var(--panel); border: 1px solid var(--rule-2); border-radius: 4px;
padding: 1px 6px; user-select: all; overflow-wrap: anywhere;
}
.ws-confirm {
display: flex; align-items: center; flex-wrap: wrap; gap: 8px 10px;
padding: 8px 10px; border-radius: 8px;
background: var(--warn-soft); color: var(--warn); font-size: 13px; font-weight: 600;
}
.ws-confirm span { margin-right: auto; }
.workspace-add { margin-top: 16px; flex: none; }
.workspace-add-label { display: block; font-size: 13px; font-weight: 600; color: var(--ink-2); margin-bottom: 6px; }
.workspace-add-row { display: flex; gap: 8px; align-items: center; }
.workspace-add-row input[type="text"] { flex: 1 1 auto; min-width: 0; padding: 8px 11px; }
.workspace-add-row .btn { flex: none; }
.workspace-add-row .btn[hidden] { display: none; }
.workspace-add-msg { margin: 6px 0 0; min-height: 1.4em; font-size: 13px; color: var(--ink-2); }
.workspace-add-msg.is-error { color: var(--warn); }
.workspace-add-msg.is-good { color: var(--ok); }
.workspace-add-msg .btn.tiny { margin: 0 0 0 8px; }
.modal.workspace .modal-actions { flex: none; align-items: center; }
.workspace-help { margin-right: auto; }
@media (max-width: 560px) {
.ws-field { grid-template-columns: 1fr; }
.ws-field .field-error { grid-column: 1; }
.workspace-add-row { flex-wrap: wrap; }
}
/* The `@name` list under a text box. Fixed to the viewport and placed by
app.js from the box's own rectangle, so no scrolling card clips it. */
.mention-pop {
position: fixed; z-index: 60;
max-width: 420px; max-height: 220px; overflow-y: auto;
padding: 4px;
background: var(--panel); color: var(--ink);
border: 1px solid var(--rule-2); border-radius: 8px;
box-shadow: var(--shadow);
}
.mention-opt {
padding: 6px 10px; border-radius: 6px;
font: 13px var(--mono); cursor: pointer;
}
.mention-opt:hover { background: var(--panel-2); }
.mention-opt.is-active { background: var(--accent-soft); color: var(--accent); }
.mention-empty { padding: 6px 10px; font-size: 13px; color: var(--ink-3); }
/* Only meaningful once "Since a date" is the choice, so it is disabled until
then rather than sitting there looking like it wants filling in. */
.since-row { margin-left: 27px; }
.since-row.is-off { opacity: 0.45; }
.since-label { font-size: 12.5px; color: var(--ink-3); }
.since-row input[type="date"] {
font: inherit;
font-size: 13.5px;
color: var(--ink);
background: var(--panel-2);
border: 1px solid var(--rule-2);
border-radius: 6px;
padding: 5px 8px;
}
.modal-why { margin: 14px 0 0; font-size: 13px; color: var(--warn); min-height: 1px; }
.modal-actions { display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px; }
/* The Stop dialog's two ways out, stacked: the handoff first (the suggested
one), the plain stop second, "Keep going" alone below. */
.stop-choices { display: grid; gap: 10px; margin-top: 16px; }
.stop-choice {
display: flex;
align-items: flex-start;
gap: 12px;
width: 100%;
padding: 12px 14px;
text-align: left;
font: inherit;
color: var(--ink);
background: var(--panel-2);
border: 1px solid var(--rule-2);
border-radius: var(--radius);
cursor: pointer;
}
.stop-choice:hover, .stop-choice.suggested { border-color: var(--accent); }
.stop-choice:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.stop-choice:disabled { opacity: 0.6; cursor: default; }
.stop-choice[hidden] { display: none; }
.stop-choice-icon {
flex: none;
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border-radius: 50%;
border: 1px solid var(--rule-2);
font-size: 13px;
color: var(--accent);
}
.stop-choice-text { display: grid; gap: 2px; min-width: 0; }
.stop-choice-title { font-weight: 600; font-size: 14px; }
.stop-choice-detail { font-size: 12.5px; color: var(--ink-2); }
.modal-actions:has(#stop-cancel) { justify-content: center; margin-top: 14px; }
@media (max-width: 560px) {
.modal-actions:has(#stop-cancel) .btn { width: 100%; }
}
+549
View File
@@ -0,0 +1,549 @@
/* planny.css: Planny the mascot: the flight, his moods and variants, and the wake-up. */
/* ---------------------------------------------------------- the flight
While Plan2Code is thinking, stars stream past and Planny leans into it:
tilted forward, bobbing, with speed lines behind him. The motion belongs to
him, so it reads as "he is off working on it" rather than as a background
effect. Chosen from ten prototypes (prototypes/thinking-starfield.html).
The flight and the spinner are one signal: every line that turns the ring
also flies. Every other state keeps the dock still, so the motion itself
carries meaning. */
.sky {
position: absolute;
inset: 0;
z-index: 0;
pointer-events: none;
opacity: 0;
transition: opacity 0.7s ease;
-webkit-mask-image: linear-gradient(90deg, transparent, #000 12%, #000 88%, transparent);
mask-image: linear-gradient(90deg, transparent, #000 12%, #000 88%, transparent);
}
.dock.is-flying .sky { opacity: 0.85; }
/* Each star rides a track as wide as the dock and moves by a percentage of
it, so the field fills whatever width the dock has: 250px, 210px on a
narrower window, the full width on a phone. The dot sits at the track's
right-hand end. */
.sky .star {
position: absolute;
left: 0;
top: var(--y);
width: 100%;
height: 0;
transform: translateX(calc(var(--p) * -100%));
}
.sky .star::before {
content: "";
position: absolute;
left: 100%;
width: var(--s);
height: var(--s);
border-radius: 50%;
background: var(--ink-2);
}
.sky .star.hot::before { background: var(--accent); }
.dock.is-flying .sky .star { animation: star-fly var(--dur) linear var(--delay) infinite; }
@keyframes star-fly {
from { transform: translateX(10px); }
to { transform: translateX(calc(-100% - 20px)); }
}
.pilot { display: block; flex: none; line-height: 0; }
.dock.is-flying .planny { transform: rotate(7deg); transform-origin: 50% 60%; animation: planny-fly 1.7s ease-in-out infinite; }
@keyframes planny-fly {
0%, 100% { transform: translateY(0) rotate(8deg); }
50% { transform: translateY(-3px) rotate(6deg); }
}
/* Speed lines, trailing off his back. Hung off Planny rather than off the
dock, so they follow him into the phone layout, where he sits beside the
text instead of above it. */
.trail { position: absolute; right: 100%; top: 0; width: 40px; height: 100%; margin-right: 4px; opacity: 0; transition: opacity 0.5s; pointer-events: none; }
.dock.is-flying .trail { opacity: 1; }
.trail i { position: absolute; right: 0; height: 1.5px; border-radius: 1px; background: linear-gradient(90deg, transparent, var(--ink-3)); }
.trail i:nth-child(1) { top: 38%; width: 26px; }
.trail i:nth-child(2) { top: 52%; width: 36px; }
.trail i:nth-child(3) { top: 66%; width: 22px; }
.dock.is-flying .trail i { animation: trail-streak 0.7s linear infinite; }
.dock.is-flying .trail i:nth-child(2) { animation-delay: -0.25s; }
.dock.is-flying .trail i:nth-child(3) { animation-delay: -0.5s; }
@keyframes trail-streak {
from { transform: translateX(6px); opacity: 1; }
to { transform: translateX(-22px); opacity: 0; }
}
/* The line under him stays readable with stars passing behind it. */
.dock.is-flying .dock-say { text-shadow: 0 0 3px var(--panel-2), 0 0 6px var(--panel-2), 0 0 10px var(--panel-2); }
.dock-say {
margin: 0;
font-size: 13px;
line-height: 1.45;
color: var(--ink-2);
text-wrap: balance;
}
/* ------------------------------------------------------------ Planny */
/* The mascot is the page's state, not decoration on top of it: his star eye
lights up when something is yours and turns while the agent works, his arms
take a pose for each mood, and he fades and shuts his eye when the
connection drops. One class from app.js switches all of it. */
.planny { width: 46px; height: 63px; flex: none; overflow: visible; }
.planny .shell,
.planny .smile,
.planny .arm path {
fill: none;
stroke: var(--ink-2);
stroke-width: 1.3;
stroke-linecap: round;
stroke-linejoin: round;
}
/* The mouth is a lip, not a grin: at the body's own 1.3 it reads as lipstick. */
.planny .smile { stroke-width: 0.9; }
.planny .arm path { stroke-width: 1.2; }
.planny .arm circle,
.planny .foot { fill: var(--ink-2); stroke: none; }
.planny .shell { fill: var(--panel-2); }
.planny .eye,
.planny .foot {
transform-box: fill-box;
transform-origin: center;
}
.planny .eye {
fill: var(--ink);
stroke: none;
animation: planny-blink 6.5s ease-in-out infinite;
}
/* Arms: one set per mood, and only that set shows. Moods without a set of
their own (happy) keep the resting arms; adrift has none at all, which is
most of what makes him look lost. Arms that move pivot at the shoulder, so
they carry view-box origins rather than their own boxes. */
.planny .arms { display: none; }
.planny .a-rest { display: inline; }
.planny:is(.is-point, .is-work, .is-done, .is-gone, .is-adrift) .a-rest { display: none; }
.planny.is-point .a-point,
.planny.is-work .a-work,
.planny.is-done .a-done,
.planny.is-gone .a-gone { display: inline; }
.planny .arm.wave,
.planny .arm.pump-l,
.planny .arm.pump-r { transform-box: view-box; }
.planny .arm.wave { transform-origin: 19px 17.5px; animation: arm-wave 0.55s ease-in-out infinite alternate; }
.planny .arm.pump-l { transform-origin: 3px 18px; animation: arm-pump-l 0.7s ease-in-out infinite; }
.planny .arm.pump-r { transform-origin: 19px 18px; animation: arm-pump-r 0.7s ease-in-out infinite; }
@keyframes planny-blink {
0%, 93%, 100% { transform: scaleY(1); }
96% { transform: scaleY(0.1); }
}
@keyframes planny-lean {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-1.6px); }
}
@keyframes planny-spin { to { transform: rotate(360deg); } }
@keyframes arm-wave { from { transform: rotate(-16deg); } to { transform: rotate(14deg); } }
@keyframes arm-pump-l { 0%, 100% { transform: rotate(-20deg); } 50% { transform: rotate(18deg); } }
@keyframes arm-pump-r { 0%, 100% { transform: rotate(18deg); } 50% { transform: rotate(-20deg); } }
@keyframes foot-step-a { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-1.1px); } }
@keyframes foot-step-b { 0%, 100% { transform: translateY(-1.1px); } 50% { transform: translateY(0); } }
/* Something for you to do: star lit in the highlight colour, a wave. */
.planny.is-point { animation: planny-lean 2.6s ease-in-out infinite; }
.planny.is-point .eye { fill: var(--accent); }
/* The agent has it: the star turns, arms pump and his feet walk on the spot. */
.planny.is-work .eye { fill: var(--accent); animation: planny-spin 2.6s linear infinite; }
.planny.is-work .foot.f1 { animation: foot-step-a 0.7s ease-in-out infinite; }
.planny.is-work .foot.f2 { animation: foot-step-b 0.7s ease-in-out infinite; }
/* Nothing outstanding. */
.planny.is-happy .eye { fill: var(--ok); }
/* The server is up, but nothing is answering at the other end of it. Not the
faded, eye-shut `gone` look: this page is working perfectly, and the thing
that is not is somewhere else. Grey, still, and no arms: he has nothing to
do with them until someone answers. */
.planny.is-adrift .eye { fill: var(--ink-3); animation: none; }
.planny.is-adrift .smile { opacity: 0.6; }
/* Finished. Settled rather than switched off: green star, arms up, eye open.
The `gone` look below would be wrong here -- the server IS about to go away,
and a faded Planny with his eye shut reads as a breakage. */
.planny.is-done .eye { fill: var(--ok); animation: none; }
.planny.is-done .smile { stroke-width: 1.5; }
/* No server: faded, eye shut in the warning colour, arms hanging. */
.planny.is-gone { opacity: 0.5; }
.planny.is-gone .eye { fill: var(--warn); animation: none; transform: scaleY(0.12); }
/* ------------------------------------------------------ mood variants
Each mood above is a family, not a single drawing: app.js rolls a v0/v1/v2
every time the mood CHANGES, so "your turn" does not look identical every
time it comes around. v0 is always the plain version written above; the
variants below are the alternates. Rules stay on the parts (arms, eye,
feet) rather than on the svg where a variant can help it, so the flight
transform can keep owning the svg itself while the agent works. */
/* Parts only the alternates use. Hidden here, woken by the variant. */
.planny .spark { opacity: 0; }
.planny .spark path {
fill: var(--accent);
transform-box: fill-box;
transform-origin: center;
}
.planny .zzz path {
fill: none;
stroke: var(--ink-3);
stroke-width: 1.1;
stroke-linecap: round;
stroke-linejoin: round;
opacity: 0;
transform-box: fill-box;
}
@keyframes eye-dart {
0%, 12%, 32%, 52%, 100% { transform: translateX(0); }
20% { transform: translateX(-1.7px); }
44% { transform: translateX(1.7px); }
}
@keyframes eye-scan {
0%, 100% { transform: translateX(-1.9px); }
50% { transform: translateX(1.9px); }
}
@keyframes eye-up {
0%, 30%, 100% { transform: translateY(0); }
50%, 72% { transform: translateY(-1.5px); }
}
@keyframes planny-float {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-2.6px); }
}
@keyframes planny-sway {
0%, 100% { transform: rotate(-2.6deg); }
50% { transform: rotate(2.6deg); }
}
@keyframes planny-nod {
0%, 55%, 100% { transform: rotate(0deg); }
65% { transform: rotate(5deg); }
80% { transform: rotate(-2deg); }
}
@keyframes star-throb {
0%, 100% { scale: 1; }
50% { scale: 1.18; }
}
@keyframes spark-pop {
0%, 12%, 46%, 100% { opacity: 0; transform: scale(0.3) rotate(0deg); }
22% { opacity: 1; transform: scale(1) rotate(18deg); }
36% { opacity: 0.9; transform: scale(0.7) rotate(38deg); }
}
@keyframes zzz-rise {
0% { opacity: 0; transform: translate(0, 0); }
25% { opacity: 0.9; }
100% { opacity: 0; transform: translate(2.5px, -5.5px); }
}
/* point -- something is yours to do. */
/* v1: an eager little hop while he waves. */
.planny.is-point.v1 { animation: planny-float 1.4s ease-in-out infinite; }
/* v2: still leaning, but his star darts like he is pointing things out. */
.planny.is-point.v2 { animation: planny-lean 3.2s ease-in-out infinite; }
.planny.is-point.v2 .eye { animation: eye-dart 3.4s ease-in-out infinite; }
/* work -- the agent has it. The flight already owns the svg, so every work
variant plays on his parts only. */
/* v1: reading. The star sweeps back and forth instead of turning. */
.planny.is-work.v1 .eye { animation: eye-scan 1.6s ease-in-out infinite; }
/* v2: full tilt. The star turns faster and throbs while he runs. */
.planny.is-work.v2 .eye { animation: planny-spin 1.4s linear infinite, star-throb 0.7s ease-in-out infinite; }
.planny.is-work.v2 .arm.pump-l,
.planny.is-work.v2 .arm.pump-r,
.planny.is-work.v2 .foot { animation-duration: 0.45s; }
/* happy -- nothing outstanding. */
/* v1: a quiet float. */
.planny.is-happy.v1 { animation: planny-float 3.6s ease-in-out infinite; }
/* v2: sparkles off his corners. */
.planny.is-happy.v2 .spark { opacity: 1; }
.planny.is-happy.v2 .spark path { animation: spark-pop 3s ease-in-out infinite; }
.planny.is-happy.v2 .spark g + g path { animation-delay: 1.5s; }
/* done -- session over. */
/* v1: a small satisfied nod, on a long leash so it reads as occasional. */
.planny.is-done.v1 { animation: planny-nod 4.4s ease-in-out infinite; transform-origin: 50% 92%; }
.planny.is-done.v1 .spark { opacity: 1; }
.planny.is-done.v1 .spark path { animation: spark-pop 4.4s ease-in-out infinite; }
/* adrift -- the page is fine, the other end is not. */
/* v1: a slow lost sway, star drifting up to look for him. */
.planny.is-adrift.v1 { animation: planny-sway 5.4s ease-in-out infinite; transform-origin: 50% 100%; }
.planny.is-adrift.v1 .eye { animation: eye-up 5.4s ease-in-out infinite; }
/* gone -- no server. */
/* v1: asleep at the post. */
.planny.is-gone.v1 .zzz path { animation: zzz-rise 3.2s ease-in infinite; }
.planny.is-gone.v1 .zzz path:nth-of-type(2) { animation-delay: 1.05s; }
.planny.is-gone.v1 .zzz path:nth-of-type(3) { animation-delay: 2.1s; }
/* ------------------------------------------------------------ wake-up
A freshly opened dashboard: Planny powers on centre stage, then glides
into the rail (boot.js). Each beat is a keyframe on a delay under
`.booting`, one class for the whole run; the glide's target depends on
where the rail sits, so boot.js hands it over as --wake-glide. The layer
takes clicks so none lands on a card underneath while he wakes. */
.wake { position: fixed; inset: 0; z-index: 45; pointer-events: auto; }
/* Solid page colour behind the sleeping bot, following light/dark via --bg. */
.wake::before { content: ""; position: absolute; inset: 0; background: var(--bg); }
.wake[hidden] { display: none; }
.wake-bot {
position: absolute; left: 50%; top: 50%;
width: 180px; height: 246px; margin: -123px 0 0 -90px;
overflow: visible; transform-origin: 0 0;
}
.wake-bot .shell,
.wake-bot .smile,
.wake-bot .limb path { fill: none; stroke: var(--ink-2); stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round; }
.wake-bot .smile { stroke-width: 0.9; }
.wake-bot .limb path { stroke-width: 1.2; }
.wake-bot .limb circle { fill: var(--ink-2); }
.wake-bot .shell { fill: var(--panel-2); }
.wake-bot .foot { fill: var(--ink-3); }
.wake-bot .eye { fill: var(--ink); transform-box: fill-box; transform-origin: center; }
/* The star and its scan sit in .look, so the glance moves them together
without fighting the star's own open-and-light transform. */
.wake-bot .look { transform-box: view-box; }
.wake-bot .scan { fill: none; stroke: var(--accent); stroke-width: 0.5; opacity: 0; }
.wake-bot .body { transform-box: view-box; transform-origin: 11px 28.8px; }
/* Arms pivot at the shoulder, so rotating one swings it from the body. */
.wake-bot .limb { transform-box: view-box; }
.wake-bot .limb.l { transform-origin: 3px 18px; }
.wake-bot .limb.r { transform-origin: 19px 18px; }
/* His Z's sit outside .body, so neither the breathing nor the hop moves them. */
.wake-bot .zzz { transform-box: view-box; transform-origin: 18px 1px; }
.wake-bot .zzz path {
fill: none; stroke: var(--ink-3); stroke-width: 0.8; stroke-linecap: round; stroke-linejoin: round;
opacity: 0; transform-box: fill-box;
}
/* Dormant, before the first click: the one line telling them to wake him. */
.wake.dormant { cursor: pointer; }
.wake-hint {
position: absolute; left: 0; right: 0; top: 50%; margin: 147px 0 0;
text-align: center; color: var(--ink-3); font-size: 0.95rem; letter-spacing: 0.02em;
opacity: 0; transition: opacity 0.3s ease;
}
.wake.dormant .wake-hint { opacity: 1; }
/* Skip: bottom right, out of the animation's way but big enough to find. */
.wake-skip {
position: absolute; right: 24px; bottom: 24px;
min-width: 120px; padding: 10px 26px; border: 1.5px solid var(--ink-2); border-radius: 6px;
background: var(--panel-2); color: var(--ink-2);
font: inherit; font-size: 1rem; font-weight: 600; letter-spacing: 0.1em; text-transform: uppercase;
cursor: pointer; opacity: 0.9;
}
.wake-skip:hover, .wake-skip:focus-visible { opacity: 1; color: var(--ink); border-color: var(--ink); }
/* 0.0 s, powered down: the resting state every beat starts from. Arms hang
slack against his sides, the star is shut and the smile not yet drawn. */
.wake-bot { filter: grayscale(1); opacity: 0.55; }
.wake-bot .limb.l { transform: rotate(-14deg); }
.wake-bot .limb.r { transform: rotate(14deg); }
.wake-bot .eye { transform: scaleY(0.1); }
.wake-bot .smile { stroke-dasharray: 7; stroke-dashoffset: 7; }
@media (prefers-reduced-motion: no-preference) {
/* Asleep until the click, on loop: Z's drift up, he breathes, his slack
arms sway out of step, and his feet pulse like a standby light. Each
stops the moment .booting swaps in and hands the part to its beat below.
The Z's keep rising through the pop, so they never jump back. */
.wake:is(.dormant, .stirring, .booting) .wake-bot .zzz path { animation: zzz-rise 3.2s ease-in infinite; }
.wake:is(.dormant, .stirring, .booting) .wake-bot .zzz path:nth-of-type(2) { animation-delay: 1.05s; }
.wake:is(.dormant, .stirring, .booting) .wake-bot .zzz path:nth-of-type(3) { animation-delay: 2.1s; }
.wake.dormant .wake-bot .body { animation: wake-breathe 4s ease-in-out infinite; }
.wake:is(.dormant, .stirring) .wake-bot .limb.l { animation: wake-doze-l 3.6s ease-in-out infinite; }
.wake:is(.dormant, .stirring) .wake-bot .limb.r { animation: wake-doze-r 4.1s ease-in-out infinite; }
.wake:is(.dormant, .stirring) .wake-bot .foot { animation: wake-standby 2.8s ease-in-out infinite; }
/* Nudged, for one snore (app.js stir): still asleep, rocked gently side to
side about his feet, a pair of rocks then a pause, as if being shaken. */
.wake.stirring .wake-bot .body { animation: wake-nudge 1.3s ease-in-out infinite; }
/* Startled awake: the Z's blow outward and are gone. */
.wake.booting .wake-bot .zzz { animation: wake-zzz-pop 0.3s ease-out both; }
/* 0.4 s power-on and feet blink · 1.35 s feet plant · 1.5 s / 1.9 s arms
lift off his sides · 2.5 s star opens with the scan, lit · 2.85 s he
looks left, then right, then ahead · 3.2 s smile · 3.6 s hop, arms up in
a cheer, star back to ink. */
.wake.booting .wake-bot { animation: wake-power 0.3s ease 0.4s both; }
.wake.booting .wake-bot .foot { animation: wake-feet 0.5s steps(1) 0.4s both, wake-plant 0.2s ease 1.35s both; }
.wake.booting .wake-bot .limb.l { animation: wake-lift-l 0.45s cubic-bezier(.3,1.6,.5,1) 1.5s both, wake-cheer-l 0.5s ease-out 3.6s both; }
.wake.booting .wake-bot .limb.r { animation: wake-lift-r 0.45s cubic-bezier(.3,1.6,.5,1) 1.9s both, wake-cheer-r 0.5s ease-out 3.6s both; }
.wake.booting .wake-bot .eye { animation: wake-eye 0.35s ease-out 2.5s both, wake-star 0.9s ease-in-out 2.5s both; }
.wake.booting .wake-bot .scan { animation: wake-scan 0.6s ease-in-out 2.5s both; }
.wake.booting .wake-bot .look { animation: wake-look 0.8s ease-in-out 2.85s both; }
.wake.booting .wake-bot .smile { animation: wake-smile 0.4s ease-out 3.2s both; }
.wake.booting .wake-bot .body { animation: wake-hop 0.5s ease-out 3.6s both; }
/* 4.3 s, into the rail. The power-on is long finished by now and holds its
last frame, so the transition owns the transform alone. */
.wake.gliding .wake-bot { transform: var(--wake-glide); transition: transform 0.6s cubic-bezier(.6,0,.2,1); }
.wake.gliding::before { opacity: 0; transition: opacity 0.6s ease; }
/* The menu comes in as he leaves: pre-hidden while he wakes, then each
group rises in, a beat after the one above it. */
.dash.waking .dash-group { opacity: 0; transform: translateY(8px); }
.dash.waking.is-in .dash-group { animation: dash-rise 0.5s ease both; }
.dash.waking.is-in .dash-group:nth-child(2 of .dash-group) { animation-delay: 0.06s; }
.dash.waking.is-in .dash-group:nth-child(3 of .dash-group) { animation-delay: 0.12s; }
.dash.waking.is-in .dash-group:nth-child(4 of .dash-group) { animation-delay: 0.18s; }
.dash.waking.is-in .dash-group:nth-child(5 of .dash-group) { animation-delay: 0.24s; }
.dash.waking.is-in .dash-group:nth-child(6 of .dash-group) { animation-delay: 0.3s; }
}
/* One Planny on screen: the rail's waits out of sight (keeping its place,
so the glide can measure it) until the big one lands on it. */
.pilot.is-waking { visibility: hidden; }
/* The note types in (app.js revealNote): what it has not reached waits. */
.dash-note .is-untyped { visibility: hidden; }
@keyframes wake-power { from { filter: grayscale(1); opacity: 0.55; } to { filter: none; opacity: 1; } }
/* Off for the delay, then on-off-on-off-on, like a standby light waking. */
@keyframes wake-feet {
0% { fill: var(--ink-3); }
0.1% { fill: var(--accent); }
25% { fill: var(--ink-3); }
50% { fill: var(--accent); }
75% { fill: var(--ink-3); }
100% { fill: var(--accent); }
}
@keyframes wake-plant { from { fill: var(--accent); } to { fill: var(--ink-2); } }
@keyframes wake-lift-l { from { transform: rotate(-14deg); } to { transform: rotate(0); } }
@keyframes wake-lift-r { from { transform: rotate(14deg); } to { transform: rotate(0); } }
/* Up and back down: the arms end on the rest pose the rail draws, so the
glide hands over to an identical drawing. */
@keyframes wake-cheer-l {
0%, 100% { transform: rotate(0); }
45%, 60% { transform: rotate(116deg); }
}
@keyframes wake-cheer-r {
0%, 100% { transform: rotate(0); }
45%, 60% { transform: rotate(-116deg); }
}
@keyframes wake-eye { from { transform: scaleY(0.1); } to { transform: scaleY(1); } }
/* The star comes on lit, then settles to ink by the hop. */
@keyframes wake-star {
0%, 60% { fill: var(--accent); }
100% { fill: var(--ink); }
}
@keyframes wake-scan {
0% { opacity: 0; transform: translateX(-3px); }
20%, 80% { opacity: 1; }
100% { opacity: 0; transform: translateX(3px); }
}
/* A glance each way, then eyes front before the hop: he ends where the rail
draws him, so the glide still lands on an identical drawing. */
@keyframes wake-look {
0%, 100% { transform: translateX(0); }
17.5%, 42.5% { transform: translateX(-2.2px); }
61%, 82.5% { transform: translateX(2.2px); }
}
@keyframes wake-smile { from { stroke-dashoffset: 7; } to { stroke-dashoffset: 0; } }
@keyframes wake-hop {
0%, 100% { transform: translateY(0) scaleY(1); }
20% { transform: translateY(0) scaleY(0.92); }
55% { transform: translateY(-3px) scaleY(1.04); }
}
@keyframes wake-breathe {
0%, 100% { transform: scaleY(1); }
50% { transform: scaleY(1.03); }
}
@keyframes wake-nudge {
0%, 60%, 100% { transform: rotate(0); }
12% { transform: rotate(-4deg); }
27% { transform: rotate(4deg); }
42% { transform: rotate(-3deg); }
52% { transform: rotate(2deg); }
}
@keyframes wake-doze-l {
0%, 100% { transform: rotate(-14deg); }
50% { transform: rotate(-7deg); }
}
@keyframes wake-doze-r {
0%, 100% { transform: rotate(14deg); }
50% { transform: rotate(7deg); }
}
@keyframes wake-standby {
0%, 100% { fill: var(--ink-3); }
50% { fill: var(--ink); }
}
@keyframes wake-zzz-pop {
from { opacity: 1; transform: scale(1); }
to { opacity: 0; transform: scale(1.8); }
}
@keyframes dash-rise { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
.views { display: flex; gap: 4px; flex-wrap: wrap; }
.views-group { display: flex; align-items: flex-start; min-width: 0; }
.views-arrow {
display: flex;
align-items: center;
flex: none;
margin: 9.5px 18px 0 0;
color: var(--accent);
pointer-events: none;
}
.views-arrow:has(+ .views:empty) { visibility: hidden; }
.views-arrow svg {
width: 10px;
height: 16px;
fill: none;
stroke: currentColor;
stroke-width: 2.2;
stroke-linecap: round;
stroke-linejoin: round;
opacity: 0.35;
}
.views-arrow svg:last-child { opacity: 0.55; }
@media (prefers-reduced-motion: no-preference) {
@keyframes views-runway { 0%, 100% { opacity: 0.25; } 30% { opacity: 0.95; } }
.views-arrow svg { animation: views-runway 1.2s ease-in-out 0.5s 3; }
.views-arrow svg:nth-child(2) { animation-delay: 0.7s; }
.views-arrow svg:nth-child(3) { animation-delay: 0.9s; }
}
.view-tab {
appearance: none;
border: 1px solid transparent;
background: transparent;
color: var(--ink-2);
font: inherit;
font-size: 13.5px;
padding: 6px 13px;
border-radius: 99px;
cursor: pointer;
/* A doc titled with a sentence keeps the tab row to one line. */
max-width: 22ch;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.view-tab:hover { background: var(--panel-2); color: var(--ink); }
.view-tab[aria-current="true"] {
background: var(--accent-soft);
border-color: var(--accent-line);
color: var(--accent);
font-weight: 600;
}
.view-tab .tab-count {
font-size: 11px;
opacity: 0.75;
margin-left: 5px;
}
+432
View File
@@ -0,0 +1,432 @@
/* poses.css: The start-screen poses, one per skill. After the dashboard on purpose: its narrow-window rules override the dashboard's. */
/* ------------------------------------------------------- skill poses
The starting and waiting screens of each skill swap the flight for Planny
acting the skill out (drawings in <template id="start-poses">, index.html). Drawn
in the page's own ink and highlight color, so the theme and the accent the
person picked carry through. Every part that moves sits in its own group,
because a CSS transform animation replaces a transform attribute. */
.pose-stage {
height: 200px;
-webkit-mask-image: none;
mask-image: none;
}
.pose { display: block; height: 100%; width: auto; margin: 0 auto; overflow: visible; }
.pose .ln, .pose .lt, .pose .sh, .pose .es, .pose .as { fill: none; stroke-linecap: round; stroke-linejoin: round; }
.pose .ln, .pose .sh { stroke: var(--ink-2); stroke-width: 6; }
.pose .lt { stroke: var(--ink-2); stroke-width: 4; }
.pose .sh { fill: var(--panel-2); }
.pose .fl { fill: var(--ink-2); }
.pose .ac { fill: var(--accent); }
.pose .as { stroke: var(--accent); stroke-width: 4; }
.pose .ey { fill: var(--ink); }
.pose .es { stroke: var(--ink); stroke-width: 4; }
.pose .shadow { fill: var(--ink-2); opacity: 0.16; }
/* Not on anything carrying a transform attribute: transform-origin moves
that too, and the lean and lift drawn into the markup would shift. */
.pose :where([class]:not([transform])) { transform-box: fill-box; transform-origin: center; }
@keyframes pose-pulse {
0%, 100% { transform: scale(1); opacity: 1; }
50% { transform: scale(1.25); opacity: 0.7; }
}
@keyframes pose-blink {
0%, 94%, 100% { transform: scaleY(1); }
97% { transform: scaleY(0.1); }
}
@keyframes pose-bob {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-4px); }
}
.pose .blink { animation: pose-blink 5.2s infinite; }
/* The star turns slowly in every pose, as it does in the rail while the agent
works. `rotate` is its own property, so it never fights the blink's transform. */
.pose .ey.blink { animation: pose-blink 5.2s infinite, pose-turn 7s linear infinite; }
@keyframes pose-turn { to { rotate: 360deg; } }
/* Quick Task runs: his feet step in time with the dash. */
.pose-quick-task .foot.f1 { animation: pose-step-a 0.5s ease-in-out infinite; }
.pose-quick-task .foot.f2 { animation: pose-step-b 0.5s ease-in-out infinite; }
@keyframes pose-step-a { 0%, 100% { transform: translateY(0); } 50% { transform: translateY(-6px); } }
@keyframes pose-step-b { 0%, 100% { transform: translateY(-6px); } 50% { transform: translateY(0); } }
.pose .bob { animation: pose-bob 3.4s ease-in-out infinite; }
.pose .prop { animation: pose-bob 3s ease-in-out infinite; }
.pose .prop.p2 { animation-delay: 0.5s; }
/* 0 Pathfinder -- the ground rolls by, the spyglass sweeps, the eye follows. */
.pose .pf-trail { fill: none; stroke: var(--ink-3); stroke-width: 4; stroke-linecap: round; stroke-dasharray: 0.1 14; animation: pf-walk 1.1s linear infinite; }
@keyframes pf-walk { to { stroke-dashoffset: 14.1; } }
.pose .pf-glass { transform-origin: 0% 100%; animation: pf-sweep 4s ease-in-out infinite; }
@keyframes pf-sweep {
0%, 100% { transform: rotate(-7deg); }
50% { transform: rotate(5deg); }
}
.pose .pf-look { animation: pf-look 4s ease-in-out infinite; }
@keyframes pf-look {
0%, 100% { transform: translate(-1px, 1px); }
50% { transform: translate(3px, -2px); }
}
.pose .twinkle { animation: pose-twinkle 2.2s ease-in-out infinite; }
.pose .twinkle.t2 { animation-delay: 0.7s; }
.pose .twinkle.t3 { animation-delay: 1.4s; }
@keyframes pose-twinkle {
0%, 100% { transform: scale(0.4); opacity: 0.3; }
50% { transform: scale(1.3); opacity: 1; }
}
/* 1 Plan -- the question mark bounces while the list ticks itself off. */
.pose-plan .bob { transform-origin: 50% 100%; animation: pl-ponder 4.8s ease-in-out infinite; }
@keyframes pl-ponder {
0%, 100% { transform: rotate(-1.5deg); }
50% { transform: rotate(1.5deg); }
}
.pose .pl-q { animation: pl-q 1.6s ease-in-out infinite; }
@keyframes pl-q {
0%, 100% { transform: translateY(0); }
40% { transform: translateY(-6px); }
60% { transform: translateY(-5px); }
}
.pose .pl-look { animation: pl-look 4.8s ease-in-out infinite; }
@keyframes pl-look {
0%, 15%, 90%, 100% { transform: translate(0, 0); }
25%, 80% { transform: translate(-3px, 2px); }
}
.pose .pl-check { stroke-dasharray: 1; animation: 4.8s ease-out infinite; }
.pose .pl-check.c1 { animation-name: pl-check-1; }
.pose .pl-check.c2 { animation-name: pl-check-2; }
.pose .pl-check.c3 { animation-name: pl-check-3; }
@keyframes pl-check-1 {
0%, 25% { stroke-dashoffset: 1; opacity: 1; }
33%, 85% { stroke-dashoffset: 0; opacity: 1; }
95%, 100% { stroke-dashoffset: 0; opacity: 0; }
}
@keyframes pl-check-2 {
0%, 42% { stroke-dashoffset: 1; opacity: 1; }
50%, 85% { stroke-dashoffset: 0; opacity: 1; }
95%, 100% { stroke-dashoffset: 0; opacity: 0; }
}
@keyframes pl-check-3 {
0%, 59% { stroke-dashoffset: 1; opacity: 1; }
67%, 85% { stroke-dashoffset: 0; opacity: 1; }
95%, 100% { stroke-dashoffset: 0; opacity: 0; }
}
/* 2 Document -- the pencil walks each line and the line appears behind it. */
.pose .dc-look { animation: dc-look 6s ease-in-out infinite; }
@keyframes dc-look {
0%, 100% { transform: translate(1px, 1px); }
20%, 55% { transform: translate(3px, 1px); }
37%, 71% { transform: translate(4px, 2px); }
}
.pose .dc-line { stroke-dasharray: 1; animation: 6s linear infinite; }
.pose .dc-line.d1 { animation-name: dc-line-1; }
.pose .dc-line.d2 { animation-name: dc-line-2; }
.pose .dc-line.d3 { animation-name: dc-line-3; }
.pose .dc-line.d4 { animation-name: dc-line-4; }
@keyframes dc-line-1 {
0%, 5% { stroke-dashoffset: 1; opacity: 1; }
20%, 88% { stroke-dashoffset: 0; opacity: 1; }
95%, 100% { stroke-dashoffset: 0; opacity: 0; }
}
@keyframes dc-line-2 {
0%, 22% { stroke-dashoffset: 1; opacity: 1; }
37%, 88% { stroke-dashoffset: 0; opacity: 1; }
95%, 100% { stroke-dashoffset: 0; opacity: 0; }
}
@keyframes dc-line-3 {
0%, 39% { stroke-dashoffset: 1; opacity: 1; }
54%, 88% { stroke-dashoffset: 0; opacity: 1; }
95%, 100% { stroke-dashoffset: 0; opacity: 0; }
}
@keyframes dc-line-4 {
0%, 56% { stroke-dashoffset: 1; opacity: 1; }
71%, 88% { stroke-dashoffset: 0; opacity: 1; }
95%, 100% { stroke-dashoffset: 0; opacity: 0; }
}
/* The pencil's tip rests at (186,130); each stop puts it at a line's start
or end, timed to the line keyframes above. */
.pose .dc-pencil { animation: dc-pencil 6s ease-in-out infinite; }
@keyframes dc-pencil {
0%, 88%, 100% { transform: translate(0, 0); }
5% { transform: translate(-2px, -32px); }
20% { transform: translate(14px, -32px); }
22% { transform: translate(-2px, -24px); }
37% { transform: translate(22px, -24px); }
39% { transform: translate(-2px, -16px); }
54% { transform: translate(18px, -16px); }
56% { transform: translate(-2px, -8px); }
71% { transform: translate(10px, -8px); }
78% { transform: translate(6px, -4px); }
}
/* 3 Implement -- crank, spark, jolt, on one 1.4s beat. */
.pose-implement .bob { animation: im-jolt 1.4s ease-in-out infinite; }
@keyframes im-jolt {
0%, 40%, 100% { transform: translateY(0); }
22% { transform: translateY(2px); }
}
.pose .im-wrench { transform-origin: 100% 100%; animation: im-crank 1.4s ease-in-out infinite; }
@keyframes im-crank {
0%, 45%, 100% { transform: rotate(0deg); }
20% { transform: rotate(-24deg); }
28% { transform: rotate(-20deg); }
}
.pose .im-spark { transform-origin: 100% 50%; animation: im-spark 1.4s ease-out infinite; }
@keyframes im-spark {
0%, 16%, 55%, 100% { opacity: 0; transform: scale(0.6); }
24% { opacity: 1; transform: scale(1.15); }
}
.pose .im-lt { animation: im-lt 1.4s ease-in-out infinite; }
.pose .im-gt { animation: im-gt 1.4s ease-in-out infinite; }
@keyframes im-lt { 50% { transform: translateX(-2px); } }
@keyframes im-gt { 50% { transform: translateX(2px); } }
.pose .im-slash { animation: im-slash 1.4s steps(1) infinite; }
@keyframes im-slash { 50% { opacity: 0.35; } }
/* 4 Finalize -- a happy hop with a squash on landing, the flag waving,
confetti drifting down past him. */
.pose .fz-hop { transform-origin: 50% 100%; animation: fz-hop 1.6s ease-in-out infinite; }
@keyframes fz-hop {
0%, 100% { transform: translateY(0) scale(1.04, 0.96); }
15%, 75% { transform: translateY(0) scale(1); }
45% { transform: translateY(-14px) scale(0.98, 1.02); }
85% { transform: translateY(0) scale(1.03, 0.97); }
}
.pose .fz-shadow { animation: fz-shadow 1.6s ease-in-out infinite; }
@keyframes fz-shadow {
0%, 15%, 75%, 100% { transform: scale(1); opacity: 0.16; }
45% { transform: scale(0.7); opacity: 0.08; }
}
.pose .fz-tick { stroke: var(--accent-ink); }
.pose .fz-flag { transform-origin: 0% 50%; animation: fz-wave 1.2s ease-in-out infinite; }
@keyframes fz-wave {
0%, 100% { transform: skewY(0deg) scaleX(1); }
33% { transform: skewY(-7deg) scaleX(0.94); }
66% { transform: skewY(5deg) scaleX(1.02); }
}
.pose .cf { animation: fz-fall 3.2s linear infinite; }
.pose .cf:nth-child(2) { animation-delay: -0.4s; }
.pose .cf:nth-child(3) { animation-delay: -2.1s; }
.pose .cf:nth-child(4) { animation-delay: -1.2s; }
.pose .cf:nth-child(5) { animation-delay: -2.7s; }
.pose .cf:nth-child(6) { animation-delay: -0.9s; }
.pose .cf:nth-child(7) { animation-delay: -1.8s; }
.pose .cf:nth-child(8) { animation-delay: -3s; }
.pose .cf:nth-child(9) { animation-delay: -1.5s; }
.pose .cf:nth-child(10) { animation-delay: -2.4s; }
@keyframes fz-fall {
0% { transform: translateY(-10px) rotate(0deg); opacity: 0; }
15%, 80% { opacity: 1; }
100% { transform: translateY(30px) rotate(200deg); opacity: 0; }
}
/* Init -- the foundation goes down a block at a time, each landing with a
squash, and he watches every one of them come down. */
.pose .blk {
fill: var(--panel-2);
stroke: var(--ink-2);
stroke-width: 4;
stroke-linejoin: round;
transform-origin: 50% 100%;
animation: 4.8s ease-in infinite;
}
.pose .blk.ac { fill: var(--accent); stroke: var(--accent); }
.pose .in-b1 { animation-name: in-drop-1; }
.pose .in-b2 { animation-name: in-drop-2; }
.pose .in-b3 { animation-name: in-drop-3; }
@keyframes in-drop-1 {
0% { transform: translateY(-48px); opacity: 0; }
4% { opacity: 1; }
14% { transform: translateY(0) scale(1.08, 0.86); }
19%, 86% { transform: none; opacity: 1; }
94%, 100% { transform: none; opacity: 0; }
}
@keyframes in-drop-2 {
0%, 22% { transform: translateY(-48px); opacity: 0; }
26% { opacity: 1; }
36% { transform: translateY(0) scale(1.08, 0.86); }
41%, 86% { transform: none; opacity: 1; }
94%, 100% { transform: none; opacity: 0; }
}
@keyframes in-drop-3 {
0%, 44% { transform: translateY(-48px); opacity: 0; }
48% { opacity: 1; }
58% { transform: translateY(0) scale(1.08, 0.86); }
63%, 86% { transform: none; opacity: 1; }
94%, 100% { transform: none; opacity: 0; }
}
.pose .in-look { animation: in-look 4.8s ease-in-out infinite; }
@keyframes in-look {
0%, 22%, 44%, 96%, 100% { transform: translate(3px, -3px); }
14%, 36%, 58%, 86% { transform: translate(4px, 2px); }
}
/* Quick Task -- a dash: a quick bob, the streaks pouring off behind him and
the bolt ahead crackling. */
.pose-quick-task .bob { animation: qt-dash 0.5s ease-in-out infinite; }
@keyframes qt-dash {
0%, 100% { transform: translateY(0); }
50% { transform: translateY(-3px); }
}
.pose .qt-shadow { animation: qt-shadow 0.5s ease-in-out infinite; }
@keyframes qt-shadow {
0%, 100% { transform: scaleX(1); }
50% { transform: scaleX(0.92); }
}
.pose .qt-line { animation: qt-streak 0.9s linear infinite; }
.pose .qt-line.l2 { animation-delay: -0.3s; }
.pose .qt-line.l3 { animation-delay: -0.6s; }
.pose .qt-line.l4 { animation-delay: -0.15s; }
@keyframes qt-streak {
0% { transform: translateX(10px); opacity: 0; }
25% { opacity: 1; }
100% { transform: translateX(-26px); opacity: 0; }
}
.pose .qt-zap { animation: qt-zap 1.8s ease-out infinite; }
@keyframes qt-zap {
0%, 20%, 50%, 58%, 100% { transform: scale(1); opacity: 1; }
8% { opacity: 0.35; }
12% { transform: scale(1.12); opacity: 1; }
54% { opacity: 0.5; }
}
/* Review -- the glass works down the page, lingers on the bad line while
it lights up and a pin pops beside it, then goes back to the top. */
.pose .rv-glass { animation: rv-scan 5s ease-in-out infinite; }
@keyframes rv-scan {
0%, 6%, 94%, 100% { transform: translate(0, 0); }
18%, 24% { transform: translate(4px, 12px); }
36% { transform: translate(-2px, 24px); }
42% { transform: translate(2px, 24px); }
48%, 60% { transform: translate(0, 24px); }
74%, 80% { transform: translate(-4px, 36px); }
}
.pose .rv-flag { animation: rv-flag 5s ease-out infinite; }
@keyframes rv-flag {
0%, 38% { opacity: 0; }
44%, 88% { opacity: 1; }
96%, 100% { opacity: 0; }
}
.pose .rv-pin { animation: rv-pin 5s ease-out infinite; }
@keyframes rv-pin {
0%, 38% { opacity: 0; transform: scale(0.3); }
44% { opacity: 1; transform: scale(1.4); }
50%, 88% { opacity: 1; transform: scale(1); }
96%, 100% { opacity: 0; transform: scale(1); }
}
.pose .rv-look { animation: rv-look 5s ease-in-out infinite; }
@keyframes rv-look {
0%, 6%, 94%, 100% { transform: translate(4px, -1px); }
18%, 24% { transform: translate(4px, 1px); }
36%, 60% { transform: translate(4px, 2px); }
74%, 80% { transform: translate(4px, 3px); }
}
/* Handoff -- the arms reach, the parcel goes with them, and the arrow keeps
pointing the way it is headed. */
.pose .ho-reach { transform-origin: 0% 50%; animation: ho-reach 2.4s ease-in-out infinite; }
@keyframes ho-reach {
0%, 100% { transform: scaleX(1); }
50% { transform: scaleX(1.2); }
}
.pose .ho-give { animation: ho-give 2.4s ease-in-out infinite; }
@keyframes ho-give {
0%, 100% { transform: translateX(0); }
50% { transform: translateX(5px); }
}
.pose .ho-arrow { animation: ho-arrow 1.2s ease-in-out infinite; }
@keyframes ho-arrow {
0% { transform: translateX(-4px); opacity: 0.35; }
60% { transform: translateX(4px); opacity: 1; }
100% { transform: translateX(8px); opacity: 0; }
}
/* Git -- the arm reaches out and a new commit settles onto the branch line in
step with it. */
.pose .gc-reach { transform-origin: 0% 50%; animation: gc-reach 2.4s ease-in-out infinite; }
@keyframes gc-reach {
0%, 100% { transform: scaleX(0.9); }
50% { transform: scaleX(1); }
}
.pose .gc-dot { animation: gc-dot 2.4s ease-in-out infinite; }
@keyframes gc-dot {
0%, 15% { opacity: 0; transform: translateY(-8px); }
50%, 85% { opacity: 1; transform: translateY(0); }
100% { opacity: 0; transform: translateY(0); }
}
/* Changelog -- the arm reaches the page and the newest line is written in step. */
.pose .cl-line { animation: gc-dot 2.4s ease-in-out infinite; }
/* Codebase X-ray -- the scan line sweeps down the file, the rough spot lights
up as it passes, and the lens and his star follow it down. */
.pose .xr-scan { animation: xr-scan 4s ease-in-out infinite; }
@keyframes xr-scan {
0%, 10% { opacity: 0; transform: translateY(0); }
16% { opacity: 1; }
74% { opacity: 1; }
80%, 100% { opacity: 0; transform: translateY(88px); }
}
.pose .xr-spot { animation: xr-spot 4s ease-out infinite; }
@keyframes xr-spot {
0%, 50% { opacity: 0; transform: scale(0.3); }
56% { opacity: 1; transform: scale(1.3); }
62%, 90% { opacity: 1; transform: scale(1); }
100% { opacity: 0; transform: scale(1); }
}
.pose .xr-lens { animation: xr-lens 4s ease-in-out infinite; }
@keyframes xr-lens {
0%, 10%, 100% { transform: translate(0, -3px); }
56%, 80% { transform: translate(0, 4px); }
}
.pose .xr-look { animation: xr-look 4s ease-in-out infinite; }
@keyframes xr-look {
0%, 10%, 100% { transform: translate(4px, -1px); }
56%, 80% { transform: translate(4px, 2px); }
}
/* Diagnose a bug -- the bug scuttles along its line, the magnifier and his
star follow it until it is caught, and the red mark under the line shows
once it holds still. Held still, the bug sits caught under the lens. */
.pose .dg-mark { fill: none; stroke: var(--warn); stroke-width: 3; stroke-linecap: round; stroke-linejoin: round; }
.pose .dg-leg { fill: none; stroke: var(--ink); stroke-width: 2; stroke-linecap: round; }
.pose .dg-body { fill: var(--warn); }
.pose .dg-head { fill: var(--ink); }
.pose .dg-bug { animation: dg-bug 4s ease-in-out infinite; }
@keyframes dg-bug {
0%, 100% { transform: translate(-7px, 0) rotate(-12deg); }
14% { transform: translate(-2px, 0) rotate(10deg); }
26% { transform: translate(4px, 0) rotate(-10deg); }
36% { transform: translate(1px, 0) rotate(8deg); }
44%, 88% { transform: translate(0, 0) rotate(0deg); }
}
.pose .dg-lens { animation: dg-lens 4s ease-in-out infinite; }
@keyframes dg-lens {
0%, 100% { transform: translate(-9px, -2px); }
18% { transform: translate(-3px, -1px); }
30% { transform: translate(3px, 0); }
44%, 88% { transform: translate(0, 0); }
}
.pose .dg-mark { animation: dg-mark 4s ease-out infinite; }
@keyframes dg-mark {
0%, 44% { opacity: 0; }
52%, 88% { opacity: 1; }
96%, 100% { opacity: 0; }
}
.pose .dg-look { animation: dg-look 4s ease-in-out infinite; }
@keyframes dg-look {
0%, 100% { transform: translate(2px, 0); }
30% { transform: translate(5px, 0); }
44%, 88% { transform: translate(4px, 1px); }
}
@media (max-width: 720px) {
.dash { padding-top: 0; }
.launch-stage { height: 140px; }
.pose-stage { height: 150px; }
.waiting-pane .pose-stage { height: 100px; }
.launch-planny { width: 58px; height: 80px; margin-left: -29px; }
}
@@ -0,0 +1,120 @@
/* responsive.css: Print, then the narrow-window rules: last, so its overrides come after everything they override. */
/* ---------------------------------------------------------------- print */
/* What gets printed is the document being read, on its own. Everything that
steers the session is furniture and has no business on paper. */
@media print {
.topbar, .rail, .aside, .footer, .banner, .skip, .doc-tools, .pager, .modal, .arrival, .review-offer { display: none !important; }
html, body { height: auto; background: #fff; color: #000; }
body { display: block; }
.layout { display: block; overflow: visible; }
.main { overflow: visible; padding: 0; max-width: none; }
.main > * { max-width: none; }
.block, .card { break-inside: avoid; box-shadow: none; }
.doc-head { border-bottom: 1px solid #ccc; }
.md a { color: #000; }
.md-pre, .md-code { background: #f4f4f4; border-color: #ddd; }
}
/* ------------------------------------------------------------ responsive */
@media (max-width: 1080px) {
.layout { grid-template-columns: 210px minmax(0, 1fr); }
.aside { grid-column: 1 / -1; border-left: 0; border-top: 1px solid var(--rule); }
}
@media (max-width: 720px) {
body { display: block; }
.layout { display: block; }
.rail { border-right: 0; border-bottom: 1px solid var(--rule); }
.sidebar, .aside { border: 0; border-bottom: 1px solid var(--rule); max-height: 30vh; }
.main { padding: 18px 16px 30px; }
.card { padding: 18px 16px; border-radius: 8px; }
.main > .card { padding-right: 22px; }
.card h2 { font-size: 21px; }
/* Back to a wrapping row: the summary and Send take two lines here and fill
the bar's middle, so the where slot has no room and goes. */
.footer { display: flex; flex-wrap: wrap; position: sticky; bottom: 0; z-index: 20; box-shadow: 0 -4px 14px rgba(0,0,0,0.07); }
.footer-summary { flex: 1; }
.footer-actions { white-space: normal; }
.footer-where { display: none; }
.footer.is-dash { justify-content: center; }
.footer.is-dash .footer-where:not([hidden]) { display: block; max-width: 100%; }
.progress-block { margin-left: 0; max-width: none; }
.topbar { padding: 12px 16px 0; }
.topbar-row.second { gap: 9px; }
.views-arrow { display: none; }
/* Side by side, because vertical space is the scarce thing here. */
.dock { flex-direction: row; text-align: left; gap: 12px; padding: 12px 16px; }
.planny { width: 32px; height: 44px; }
/* Three items on one line is one too many at this width, and the count is
the one that is only nice to have. */
.pager { gap: 8px; }
.pager-count { display: none; }
}
@media (prefers-reduced-motion: reduce) {
* { animation-duration: 0.01ms !important; animation-iteration-count: 1 !important; transition-duration: 0.01ms !important; }
/* Re-enable the indicators whose whole job is to show that time is passing.
Frozen, the spinner reads as a broken ring and Planny's star as a dead
light, so the star keeps turning, slowly. His lean, blink, arms and feet
are decoration and stay off. */
.spinner { animation: spin 1.6s linear infinite !important; }
.planny.is-work .eye { animation: planny-spin 4s linear infinite !important; }
/* The flight holds still rather than collapsing. Collapsed to its last
frame every star would sit off the left edge and the sky would be empty;
stopped, the field stays and Planny keeps his forward lean. */
.sky .star, .trail i, .dock.is-flying .planny { animation: none !important; }
/* The step poses hold their finished drawing -- every tick and line
written, confetti where it was drawn -- and keep only the star's pulse. */
.pose, .pose * { animation: none !important; }
.pose .ey.blink { animation: pose-pulse 2.4s ease-in-out infinite !important; }
/* Help's Planny moods are pictures, not indicators: all of them hold
still, the working star included. */
.help-mood-bot, .help-mood-bot *, .help-mood-bot.is-work .eye { animation: none !important; }
#btn-send { animation: none; }
}
/* 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; }
.models-list { display: grid; gap: 4px; max-height: 160px; overflow: auto; }
.models-list:empty { display: none; }
.models-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; gap: 6px; align-items: center; }
.models-row.locked { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); font-size: 0.88em; opacity: 0.75; }
.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); }
/* User Preferences: Cleanup's list of what would go, shown before anything
is deleted. */
.cleanup-list { display: grid; gap: 4px; max-height: 200px; overflow: auto; font-size: 0.88em; }
.cleanup-list:empty { display: none; }
.cleanup-summary { margin: 0 0 2px; font-weight: 600; }
.cleanup-row { display: flex; justify-content: space-between; gap: 12px; }
.cleanup-row span:first-child { min-width: 0; overflow-wrap: anywhere; font-family: var(--mono); }
.cleanup-size { flex: none; color: var(--ink-3); }
.cleanup-more { display: grid; gap: 4px; }
.cleanup-more summary { cursor: pointer; color: var(--ink-2); }
#cleanup-delete[hidden] { display: none; }
/* A word the person has to type, bold and in their highlight color so it
does not get lost in the status sentence. */
.agent-key {
color: var(--accent);
font-weight: 700;
}
/* "What to check", beside the quiet and Not running lines. A link in a button's clothes. */
.status-help {
font: inherit; font-size: 0.92em; font-weight: 600;
color: var(--accent); background: none; border: 0; padding: 0 2px;
text-decoration: underline; text-underline-offset: 2px; cursor: pointer;
}
.status-help:hover { text-decoration-thickness: 2px; }
.status-help:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; border-radius: 3px; }
+674
View File
@@ -0,0 +1,674 @@
/* shell.css: The page shell: banner, top bar and meter, layout, sidebar, aside, footer, waiting and arrival. */
/* ------------------------------------------------------------- banner */
/* A pill floated over the footer, centred on the bar. It used to be the top
grid row, and every time it appeared it pushed the whole page down a track;
overlaying it means the message lands without the layout moving under the
reader's cursor. It covers the footer's middle while it is up, which is
safe: the messages it carries are the reason nothing there needs pressing. */
.banner {
position: fixed;
left: 50%;
bottom: 10px;
transform: translateX(-50%);
z-index: 46;
max-width: min(680px, calc(100vw - 32px));
padding: 9px 22px;
border: 1px solid var(--rule-2);
border-radius: 99px;
box-shadow: var(--shadow);
text-align: center;
font-weight: 600;
font-size: 14px;
background: var(--warn-soft);
color: var(--warn);
animation: banner-in 0.22s ease;
}
@keyframes banner-in {
from { opacity: 0; transform: translateX(-50%) translateY(7px); }
}
.banner.good { background: var(--ok-soft); color: var(--ok); }
.banner .banner-hint { font-weight: 400; margin-right: 4px; }
.banner .banner-action { margin: 0 0 0 10px; }
.banner.info { background: var(--accent-soft); color: var(--accent); border-color: var(--accent-line); }
/* ------------------------------------------------------------- topbar */
.topbar {
background: var(--panel);
border-bottom: 1px solid var(--rule);
padding: 14px 20px 0;
}
.topbar-row {
display: flex;
align-items: center;
gap: 24px;
flex-wrap: wrap;
}
.topbar-row.second {
display: flex;
align-items: center;
justify-content: space-between;
border-top: 1px solid var(--rule);
padding-top: 0;
gap: 16px;
min-height: 42px;
}
.row-left { display: flex; align-items: center; gap: 8px; }
.brief-btn { border-color: var(--rule-2); color: var(--ink-2); }
/* Back to the dashboard: a filled triangle in the highlight color, so it
recolors with the swatch like everything else that is the person's to use. */
.home-btn { border-color: var(--rule-2); display: inline-flex; align-items: center; justify-content: center; }
/* As tall as Stop session beside it, with an icon's narrower sides. */
.btn.home-btn { padding: 0 6px; align-self: stretch; margin-right: -8px; }
.home-btn[hidden] { display: none; }
.home-btn svg { width: 16px; height: 16px; display: block; }
.home-btn path { fill: var(--accent); }
.home-btn:hover:not(:disabled) { border-color: var(--accent-line); background: var(--accent-soft); }
.home-btn:disabled path { fill: var(--ink-3); }
/* Ending the session. Quiet, because it is the one control on the page that
is never the next step, and red only on hover, because it is not dangerous:
it saves, then stops. */
.stop-btn { border-color: var(--rule-2); color: var(--ink-2); }
.stop-btn:hover:not(:disabled) { color: var(--warn); border-color: var(--warn); }
.brief-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
/* Subagents: an orchestrator and its helpers. Unlit is a hollow outline in
the quiet ink; lit fills the nodes with the highlight color. */
.subagents-btn { border-color: var(--rule-2); color: var(--ink-2); display: inline-flex; align-items: center; justify-content: center; }
.btn.subagents-btn { padding: 0 6px; align-self: stretch; }
.subagents-btn[hidden] { display: none; }
.subagents-btn svg { width: 16px; height: 16px; display: block; }
.subagents-btn .sa-link { fill: none; stroke: var(--ink-2); stroke-width: 1.2; stroke-linecap: round; }
.subagents-btn .sa-hub { fill: none; stroke: var(--ink-2); stroke-width: 1.4; }
.subagents-btn .sa-node { fill: none; stroke: var(--ink-2); stroke-width: 1.2; }
.subagents-btn[aria-pressed="true"] .sa-hub,
.subagents-btn[aria-pressed="true"] .sa-node { fill: var(--accent); stroke: var(--accent); }
.subagents-btn[aria-pressed="true"] .sa-link { stroke: var(--accent); }
.subagents-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
.subagents-btn:hover:not(:disabled) .sa-link,
.subagents-btn:hover:not(:disabled) .sa-hub,
.subagents-btn:hover:not(:disabled) .sa-node { stroke: var(--accent); }
.subagents-btn:disabled .sa-link,
.subagents-btn:disabled .sa-hub,
.subagents-btn:disabled .sa-node { stroke: var(--ink-3); fill: none; }
.ident { display: flex; align-items: baseline; gap: 12px; min-width: 0; }
/* The session meter: a ring that fills with the points and a few words, in
the level's colour. Green, amber and red are the page's own done / staged /
careful colours, so both themes are covered by the variables. */
.meter-slot { position: relative; flex: none; align-self: center; }
.meter-pill {
--m: var(--ok);
display: inline-flex; align-items: center; gap: 7px;
padding: 2px 10px 2px 3px;
border: 1px solid color-mix(in srgb, var(--m) 40%, transparent);
border-radius: 99px;
background: var(--panel);
color: var(--m);
font: inherit; font-size: 12px; font-weight: 600;
white-space: nowrap; cursor: pointer;
}
.meter-pill[hidden] { display: none; }
.meter-pill[data-level="yellow"] { --m: var(--stage); }
.meter-pill[data-level="red"] { --m: var(--warn); background: var(--warn-soft); }
.meter-pill:hover { background: color-mix(in srgb, var(--m) 10%, var(--panel)); }
.meter-ring { width: 20px; height: 20px; transform: rotate(-90deg); flex: none; }
.meter-ring circle { fill: none; stroke-width: 3; }
.meter-track { stroke: var(--rule); }
.meter-fill { stroke: var(--m); transition: stroke-dashoffset 0.2s ease; }
@media (prefers-reduced-motion: reduce) {
.meter-fill { transition: none; }
}
.meter-pop {
position: absolute; top: calc(100% + 6px); left: 0; z-index: 40;
width: max-content; max-width: min(320px, calc(100vw - 32px));
padding: 10px 12px;
background: var(--panel); color: var(--ink);
border: 1px solid var(--rule-2); border-radius: 8px;
box-shadow: var(--shadow);
}
.meter-pop[hidden] { display: none; }
.meter-tip { margin: 0 0 6px; font-size: 13px; color: var(--ink-2); }
.meter-list {
list-style: none; margin: 0 0 8px; padding: 6px 0 0;
border-top: 1px solid var(--rule);
max-height: 40vh; overflow-y: auto;
font-size: 12px; color: var(--ink-2);
}
.meter-list[hidden] { display: none; }
.meter-list li { display: flex; justify-content: space-between; gap: 16px; padding: 2px 0; }
.meter-fresh { margin: 0 0 8px; padding-top: 6px; border-top: 1px solid var(--rule); }
.meter-fresh[hidden] { display: none; }
.meter-fresh-text { margin: 0 0 6px; font-size: 12px; color: var(--ink-2); }
.meter-fresh-row .handoff-code { flex-basis: 180px; font-size: 12px; padding: 6px 10px; }
.meter-item-points { flex: none; font-weight: 600; color: var(--ink); font-variant-numeric: tabular-nums; }
.badge {
font-size: 11px;
font-weight: 700;
letter-spacing: 0.07em;
text-transform: uppercase;
color: var(--accent);
background: var(--accent-soft);
border: 1px solid var(--accent-line);
padding: 3px 8px;
border-radius: 99px;
white-space: nowrap;
}
h1 {
font: 600 19px/1.2 var(--serif);
margin: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.progress-block { flex: 1 1 260px; min-width: 200px; max-width: 460px; margin-left: auto; }
/* When the progress block is hidden (the dashboard, the git board) nothing
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; }
.progress-label {
display: flex;
justify-content: space-between;
gap: 12px;
font-size: 12.5px;
color: var(--ink-2);
margin-bottom: 5px;
}
#progress-text { font-weight: 600; color: var(--ink); }
.confidence { color: var(--ink-3); text-align: right; }
.progress-track {
height: 7px;
background: var(--rule);
border-radius: 99px;
overflow: hidden;
}
.progress-fill {
height: 100%;
width: 0%;
background: var(--ok);
border-radius: 99px;
transition: width 0.5s ease;
}
.tick { color: var(--ink-3); font-variant-numeric: tabular-nums; }
/* Planny's own corner. He was 23px in a title bar, which is a logo, not a
guide: too small to read a mood off and too small to look at. Here he has
room, he sits above the question list where the eye starts, and his line
wraps instead of squeezing the view tabs. */
.dock {
flex: none;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
padding: 18px 16px 16px;
border-bottom: 1px solid var(--rule);
background: var(--panel-2);
text-align: center;
position: relative;
overflow: hidden;
isolation: isolate;
}
.dock > :not(.sky) { position: relative; z-index: 1; }
/* ------------------------------------------------------------- layout */
.layout {
display: grid;
grid-template-columns: 250px minmax(0, 1fr) 320px;
min-height: 0;
overflow: hidden;
}
.rail {
display: flex;
flex-direction: column;
min-height: 0;
border-right: 1px solid var(--rule);
}
.sidebar, .main, .aside { overflow-y: auto; padding: 20px; min-height: 0; }
.sidebar { flex: 1; }
.aside { border-left: 1px solid var(--rule); background: var(--panel-2); }
/* The question column does not scroll: the CARD does.
A long question used to push Previous / Next below the fold, so the way on
disappeared exactly when the question was big enough to need it. The card is
the only thing here that shrinks, so it takes the squeeze and scrolls its own
contents while its frame, and the pager under it, stay put. */
.main {
padding: 24px 28px;
overflow: hidden;
display: flex;
flex-direction: column;
align-items: center;
}
.main > * { width: 100%; max-width: min(var(--card-width), 100%); margin-left: auto; margin-right: auto; }
/* The card is the column's only framed child: a page holds ONE, with notes
and lulls folded into it as sections. It takes the squeeze and scrolls its
own contents while its frame, and the pager under it, stay put. */
.main > .card {
flex: 0 1 auto;
overflow-y: auto;
overscroll-behavior: contain;
scrollbar-gutter: stable;
padding-right: 32px;
}
/* The dashboard's menu and the launching pane play by the card's rule too:
they are not .card, but they are the column's whole contents, so they take
the squeeze and scroll themselves while the column frame stays put. Without
this the catalog is clipped at the fold with no way to reach it. */
.main > .dash, .main > .launching, .main > .dash-confirm, .main > .waiting-pane {
flex: 0 1 auto;
overflow-y: auto;
overscroll-behavior: contain;
scrollbar-gutter: stable;
padding-right: 32px;
}
/* The column itself never scrolls; the card does. The git board is the one
exception, below: its card sits in the board's card slot, so the column
takes the scroll there and card and board flow through it at natural height. */
.main > .card:not(.is-primary) { flex-shrink: 100; min-height: 104px; }
.main > .card.is-primary { flex-shrink: 1; min-height: 0; }
/* A card with a growing answer box takes the column's full height above the
pager, and still scrolls its own contents. app.js sizes the box to fill it. */
.main > .card.is-primary.has-grow { flex: 1 1 auto; }
/* More below the fold (app.js markMore): the bottom edge fades, so a card
cut by the window never reads as finished. */
.main > .card.has-more {
-webkit-mask-image: linear-gradient(to bottom, #000 calc(100% - 56px), transparent);
mask-image: linear-gradient(to bottom, #000 calc(100% - 56px), transparent);
}
.pager { flex: none; }
/* A document is read top to bottom and has no pinned furniture, so it goes back
to being an ordinary scrolling column. */
/* The tail the column no longer carries: a document IS the scroll, so it wants
room after its last line. The question column does not, because the pager is
pinned to the bottom of it and anything under the pager is dead space the
card could have been scrolling through. */
.main.is-doc { display: block; overflow-y: auto; padding-bottom: 40px; }
/* ------------------------------------------------------------ sidebar */
.rail-group { margin-bottom: 22px; }
.rail-title {
font-size: 11px;
font-weight: 700;
letter-spacing: 0.07em;
text-transform: uppercase;
color: var(--ink-3);
margin: 0 0 8px;
display: flex;
justify-content: space-between;
gap: 8px;
}
.rail-item {
display: flex;
gap: 9px;
align-items: flex-start;
width: 100%;
text-align: left;
appearance: none;
border: 0;
background: transparent;
color: var(--ink-2);
font: inherit;
font-size: 13.5px;
padding: 7px 9px;
border-radius: 8px;
cursor: pointer;
line-height: 1.35;
}
.rail-item:hover:not(:disabled) { background: var(--panel-2); color: var(--ink); }
.rail-item:disabled { cursor: default; }
/* The dashboard lists every skill in the rail; the ones the selected spec
rules out should read as out of reach at a glance, not as one more link. */
.rail-item.is-unavailable { opacity: 0.35; cursor: not-allowed; }
.rail-item.is-unavailable .rail-mark { color: var(--ink-3); }
.rail-item[aria-current="true"] {
background: var(--accent-soft);
color: var(--ink);
font-weight: 600;
box-shadow: inset 2px 0 0 var(--accent);
}
.rail-mark { flex: none; width: 15px; text-align: center; font-size: 12px; color: var(--ink-3); margin-top: 1px; }
.rail-mark.done { color: var(--ok); }
.rail-mark.staged { color: var(--stage); font-weight: 700; }
/* Echoes the center pane's "Suggested" pill, which can scroll out of view;
the dot keeps the call-out visible while just scanning the rail. The
title grows to push the dot flush with the row's right edge. */
.rail-item > span:not(.rail-mark):not(.rail-suggested-dot) { flex: 1 1 auto; }
.rail-suggested-dot {
flex: none;
width: 7px;
height: 7px;
border-radius: 50%;
margin-top: 5px;
background: var(--accent);
}
.rail-item.is-suggested:not([aria-current="true"]) { color: var(--ink); }
.rail-mark.open { color: var(--accent); }
/* The session's own page, above the topic groups. It names the state it is
-- PAUSED, SESSION ENDED -- in the same small caps the group titles use,
because it is a peer of theirs, not another question in the list. */
.rail-end-label {
font-size: 11px;
font-weight: 700;
letter-spacing: 0.07em;
text-transform: uppercase;
}
.rail-empty { color: var(--ink-3); font-size: 13px; font-style: italic; }
/* -------------------------------------------------------------- aside */
.aside h2 {
font-size: 11px; font-weight: 700; letter-spacing: 0.07em; text-transform: uppercase;
color: var(--ink-3); margin: 0 0 12px;
}
.msg {
border-radius: 8px; padding: 10px 13px; margin-bottom: 9px; font-size: 13.5px;
background: var(--panel); border: 1px solid var(--rule);
}
.msg.you { background: var(--stage-soft); border-color: transparent; }
.msg.staged { border-style: dashed; border-color: var(--stage); background: transparent; }
.msg-who {
font-size: 10.5px; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase;
color: var(--ink-3); margin-bottom: 4px; display: flex; justify-content: space-between; gap: 8px;
}
.aside-empty { color: var(--ink-3); font-size: 13px; font-style: italic; }
/* The note box takes whatever height the panel has left, never under 160px.
Scoped here so the page-wide textarea minimum still holds everywhere else. */
.aside { display: flex; flex-direction: column; }
.aside > .field { flex: 1 0 auto; display: flex; flex-direction: column; min-height: 0; }
.aside textarea { flex: 1 1 auto; min-height: 160px; resize: vertical; }
.aside.is-dropping {
outline: 2px dashed var(--accent);
outline-offset: -8px;
background: var(--accent-soft);
}
.attach-row { display: flex; align-items: center; margin: -4px 0 6px -13px; }
.attach-row.is-under { margin: 6px 0 4px -13px; }
.attach-tray { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 10px; }
.attach-thumb {
position: relative;
width: 72px; height: 72px; margin: 0;
border: 1px solid var(--rule); border-radius: 8px;
overflow: hidden; background: var(--panel);
flex: none;
}
.attach-thumb img { width: 100%; height: 100%; object-fit: cover; display: block; }
.attach-remove {
position: absolute; top: 3px; right: 3px; z-index: 2;
width: 20px; height: 20px; padding: 0;
display: grid; place-items: center;
font: 700 14px/1 var(--sans);
color: var(--ink); background: var(--panel);
border: 1px solid var(--rule-2); border-radius: 50%;
cursor: pointer; opacity: 0.9;
}
.attach-remove:hover { opacity: 1; border-color: var(--accent); }
.attach-overlay {
position: absolute; inset: 0; z-index: 1;
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px;
background: color-mix(in srgb, var(--panel) 70%, transparent);
}
.attach-overlay.failed {
background: color-mix(in srgb, var(--panel) 88%, transparent);
color: var(--ink-2); font-size: 10.5px; font-weight: 600; text-align: center;
}
.attach-overlay.failed .btn.tiny { margin: 0; padding: 1px 6px; font-size: 10.5px; }
.attach-chip {
width: 180px;
display: flex; align-items: center; gap: 8px;
padding: 0 26px 0 10px;
}
.attach-chip-icon {
flex: none; width: 24px; height: 24px;
fill: none; stroke: var(--ink-2); stroke-width: 1.5; stroke-linejoin: round;
}
.attach-chip-text { min-width: 0; display: flex; flex-direction: column; align-items: flex-start; gap: 2px; }
.attach-chip-badge {
padding: 0 5px; border-radius: 4px;
font: 700 10px/1.5 var(--sans); letter-spacing: 0.04em; font-variant: small-caps;
color: var(--ink); background: var(--accent-soft);
}
.attach-chip-name {
max-width: 100%;
overflow: hidden; white-space: nowrap; text-overflow: ellipsis;
font-size: 12.5px; font-weight: 600; color: var(--ink);
}
.attach-chip-size { color: var(--ink-2); font-size: 11.5px; }
.attach-link { color: inherit; text-decoration: none; border-radius: 8px; }
.attach-link:hover .attach-thumb, .attach-link:focus-visible .attach-thumb { border-color: var(--accent); }
.attach-link:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.msg.pending { border-style: dashed; border-color: var(--stage); background: transparent; }
.ask-row .attach-chip { padding-right: 10px; }
.footer-held { margin-top: 3px; color: var(--ink-2); font-size: 12.5px; }
/* ------------------------------------------------------------- footer */
/* Three columns: summary, where, actions. Equal side tracks keep the middle
centred on the bar, and because they are tracks rather than an overlay, a
long summary wraps and a wide actions block nudges the centre over instead
of either running underneath it. The middle track gives way first: it can
shrink to an ellipsis, the summary and Send never do. */
.footer {
display: grid; grid-template-columns: 1fr minmax(0, auto) 1fr; align-items: center; gap: 18px;
padding: 13px 20px;
background: var(--panel);
border-top: 1px solid var(--rule);
}
.footer-summary { min-width: 200px; font-size: 13.5px; color: var(--ink-2); }
.footer-summary strong { color: var(--ink); }
/* Where this session is running: the workspace label, centred on the bar. A
click opens the Workspace dialog. The notification pill sits over the same
spot and covers it while it shows. */
.footer-where {
max-width: 30vw; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
padding: 2px 6px; border: 0; background: none;
font: inherit; font-size: 12px; color: var(--ink-3);
cursor: pointer;
}
.footer-where:hover { text-decoration: underline; }
/* The project name, in the person's highlight color. */
.where-project { color: var(--accent); font-weight: 600; }
/* A folder is missing or the agent could not read one: the dialog says which. */
.where-alert {
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
border-radius: 50%; background: var(--warn); vertical-align: 1px;
}
.footer-where:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; border-radius: 4px; }
/* One line, so the grid sizes this track to the whole row and takes the room
from the middle instead of folding Send in two. */
.footer-actions { display: flex; gap: 10px; align-items: center; grid-column: 3; justify-self: end; white-space: nowrap; }
/* The dashboard: no summary, no Send, just the workspace label. */
.footer.is-dash .footer-summary,
.footer.is-dash .footer-actions { display: none; }
.footer.is-dash .footer-where { grid-column: 2; }
.footer.is-dash-done .footer-actions { display: none; }
.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. */
.hint-text { max-width: 26ch; overflow: hidden; text-overflow: ellipsis; }
kbd {
font: 11.5px var(--mono);
background: var(--panel-2);
border: 1px solid var(--rule-2);
border-bottom-width: 2px;
border-radius: 4px;
padding: 2px 5px;
}
/* ------------------------------------------------------------ waiting */
/* Laid out like the starting screen, so when a session goes from one to the
other Planny stays put and only the words under him change. */
.waiting-pane {
max-width: 560px;
margin: 4vh auto 0 !important;
text-align: center;
color: var(--ink-2);
display: grid;
gap: 12px;
justify-items: center;
}
.waiting-pane h2 { font: 600 23px/1.3 var(--serif); color: var(--ink); margin: 0; }
.waiting-pane p { 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 {
font: inherit;
font-weight: 700;
color: var(--accent);
background: none;
border: 0;
padding: 0;
}
button.waiting-jump { cursor: pointer; text-decoration: underline; text-decoration-color: var(--accent-line); text-underline-offset: 3px; }
button.waiting-jump:hover { text-decoration-color: var(--accent); }
/* Once the work is under way Planny steps back a size, and the ring in
front of the stage name carries the "still going" signal instead. */
.waiting-pane .pose-stage { height: 130px; transition: height 0.35s ease; }
.waiting-pane h2 .waiting-spin { display: inline-block; width: 16px; height: 16px; vertical-align: 1px; margin-right: 10px; }
.spinner {
width: 30px; height: 30px; margin: 0 auto 20px;
border: 3px solid var(--rule);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 0.9s linear infinite;
}
@keyframes spin { to { transform: rotate(360deg); } }
/* The footer's "waiting on the agent" tell. Same ring, sized to sit on a line
of text. It inherits the reduced-motion exception below, which is deliberate:
a frozen spinner reads as a broken app, which is the opposite of the point. */
.spinner.tiny {
width: 13px;
height: 13px;
border-width: 2px;
margin: 0;
flex: none;
}
/* The same ring again, in front of Planny's line while the agent has the
ball. Inline so it sits on the first line of a wrapped sentence. The
[hidden] rule is needed because display here outranks the browser's own. */
.dock-spin { display: inline-block; vertical-align: -2px; margin-right: 6px; }
.dock-spin[hidden] { display: none; }
.robot { font: 12px/1.25 var(--mono); color: var(--ink-3); white-space: pre; margin: 0 0 16px; }
/* ------------------------------------------------------------ arrival */
/* The beat when new questions land. Covers the whole page, says what just
happened, and leaves by itself in under two seconds. Built from the page's
own tokens so it follows the theme and the chosen highlight color. */
.arrival {
position: fixed;
inset: 0;
z-index: 50;
display: grid;
place-items: center;
background: color-mix(in srgb, var(--bg) 72%, transparent);
backdrop-filter: blur(3px);
cursor: pointer;
animation: arrival-in 0.28s ease-out both;
}
.arrival.is-leaving { animation: arrival-out 0.3s ease-in both; }
.arrival-box { text-align: center; padding: 24px; max-width: min(640px, 100vw - 32px); }
.arrival-kicker {
margin: 0 0 10px;
font-size: 12px;
font-weight: 700;
letter-spacing: 0.14em;
text-transform: uppercase;
color: var(--accent);
animation: arrival-rise 0.45s 0.05s ease-out both;
}
/* The words themselves are the effect: they sweep in on a band of the
highlight color, the way a page turns, rather than anything spinning. */
.arrival-title {
margin: 0;
font: 600 clamp(38px, 7vw, 64px)/1.05 var(--serif);
color: transparent;
background: linear-gradient(100deg, var(--ink) 0 40%, var(--accent) 50%, var(--ink) 60% 100%);
background-size: 250% 100%;
-webkit-background-clip: text;
background-clip: text;
animation:
arrival-rise 0.5s 0.1s cubic-bezier(0.2, 0.8, 0.2, 1) both,
arrival-sweep 1.3s 0.25s ease-in-out both;
}
/* A rule that draws itself under the title, from the middle out. */
.arrival-title::after {
content: "";
display: block;
height: 3px;
width: 96px;
margin: 14px auto 0;
border-radius: 99px;
background: var(--accent);
transform-origin: center;
animation: arrival-draw 0.5s 0.45s ease-out both;
}
.arrival-what {
margin: 16px 0 0;
font-size: 17px;
font-weight: 600;
color: var(--ink-2);
animation: arrival-rise 0.45s 0.35s ease-out both;
}
.arrival-more {
margin: 4px 0 0;
font-size: 13.5px;
color: var(--ink-3);
animation: arrival-rise 0.45s 0.45s ease-out both;
}
@keyframes arrival-in { from { opacity: 0; } to { opacity: 1; } }
@keyframes arrival-out { from { opacity: 1; } to { opacity: 0; transform: scale(1.02); } }
@keyframes arrival-rise {
from { opacity: 0; transform: translateY(14px); }
to { opacity: 1; transform: none; }
}
@keyframes arrival-sweep {
from { background-position: 100% 0; }
to { background-position: 0 0; }
}
@keyframes arrival-draw { from { transform: scaleX(0); } to { transform: scaleX(1); } }
+135
View File
@@ -0,0 +1,135 @@
/* tokens.css: Colours, type, sizes and the light and dark themes: the variables every other file reads. */
/* Plan2Code Console.
Light by default, dark when the system asks. No external fonts: the page must
work offline and under a CSP with no 'unsafe-inline'. */
:root {
--bg: #f6f3ee;
--panel: #ffffff;
--panel-2: #fbf9f6;
--ink: #1d1a17;
--ink-2: #5d564d;
--ink-3: #8f8779;
--rule: #e4ddd1;
--rule-2: #cfc6b6;
--accent: #206cc3;
--accent-soft: #ecf2f9;
--accent-ink: #ffffff;
--accent-line: #9ab4d3;
--ok: #2f6b45;
--ok-soft: #e4f0e8;
--stage: #9a6a12;
--stage-soft: #fbf0d8;
--warn: #9c3327;
--warn-soft: #fbe7e3;
--focus: #1f6feb;
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
/* A soft accent halo for the things that want noticing: the update banner
and an enabled Send. Built from --accent, so a picked accent glows too. */
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
--radius: 10px;
/* The column's width: the card, the pager and the documents. */
--card-width: 880px;
}
/* The card-width presets. These must agree with CARD_WIDTHS in palette.js,
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; }
/* 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
light; the second is the explicit ask. Without the `:not()` a system-dark
browser would win over someone who chose light in the settings panel. */
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--bg: #171513;
--panel: #201d1a;
--panel-2: #262220;
--ink: #f0ece5;
--ink-2: #b6afa3;
--ink-3: #8b8376;
--rule: #332e29;
--rule-2: #46403a;
--accent: #619fe5;
--accent-soft: #1a2533;
--accent-ink: #0c1117;
--accent-line: #3d5978;
--ok: #74c28f;
--ok-soft: #1c2d22;
--stage: #e0ab4c;
--stage-soft: #332a17;
--warn: #f0897a;
--warn-soft: #34201d;
--focus: #6aa3ff;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
}
}
:root[data-theme="dark"] {
--bg: #171513;
--panel: #201d1a;
--panel-2: #262220;
--ink: #f0ece5;
--ink-2: #b6afa3;
--ink-3: #8b8376;
--rule: #332e29;
--rule-2: #46403a;
--accent: #619fe5;
--accent-soft: #1a2533;
--accent-ink: #0c1117;
--accent-line: #3d5978;
--ok: #74c28f;
--ok-soft: #1c2d22;
--stage: #e0ab4c;
--stage-soft: #332a17;
--warn: #f0897a;
--warn-soft: #34201d;
--focus: #6aa3ff;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
}
* { box-sizing: border-box; }
html, body { height: 100%; }
body {
margin: 0;
background: var(--bg);
color: var(--ink);
font: 15px/1.55 var(--sans);
display: grid;
grid-template-rows: auto 1fr auto;
min-height: 100vh;
}
:focus-visible {
outline: 2px solid var(--focus);
outline-offset: 2px;
border-radius: 4px;
}
.skip {
position: absolute;
left: -9999px;
top: 0;
background: var(--panel);
color: var(--ink);
padding: 10px 16px;
z-index: 50;
border-radius: 0 0 var(--radius) 0;
}
.skip:focus { left: 0; }
/* Pin each region to its own row rather than relying on order: the banner
is fixed now and never a grid item, but keeping the rows explicit means a
future element that hides the same way cannot shuffle the tracks. */
.topbar { grid-row: 1; }
.layout { grid-row: 2; }
.footer { grid-row: 3; }
+14 -27
View File
@@ -3,34 +3,21 @@
// The source of truth for which workflows offer the switch, the instruction
// each one ships with, the fixed frame every "on" block carries, the exact
// lines the agent reads at a pickup (blockFor()), and the house rules for the
// helpers an agent reports back (checkHelper()). No DOM access at module scope
// and no imports: the server, console.mjs, the page and `node --test` all
// import this file.
// helpers an agent reports back (checkHelper()). No DOM 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.
// The one place a skill opts in (FR-1). Wording is behaviour-level and names
// no harness tool, so any agent can follow it or harmlessly ignore it.
export const SUBAGENT_WORKFLOWS = Object.freeze({
implement: Object.freeze({
instruction:
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
}),
"implement-review": Object.freeze({
instruction:
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
}),
"quick-task": Object.freeze({
instruction:
"Use helpers for side lookups, such as reading unfamiliar code or checking documentation, while you make the change yourself.",
}),
review: Object.freeze({
instruction:
"Run the review's analysis in one fresh helper briefed only with the spec and the change set (references/reviewer-brief.md); verify every finding yourself before you report.",
}),
pathfinder: Object.freeze({
instruction:
"Use helpers for codebase recon, sketches and lookups beside the conversation. Keep every question for the person with you.",
}),
});
import { SKILLS, subagentsFor } from "./skills.js";
// The skills that offer the switch, each with its instruction: an entry's
// `subagents` in skills.js is the one place a skill opts in (FR-1). Wording is
// behaviour-level and names no harness tool, so any agent can follow it or
// harmlessly ignore it.
export const SUBAGENT_WORKFLOWS = Object.freeze(
Object.fromEntries(
SKILLS.filter((s) => subagentsFor(s.workflow)).map((s) => [s.workflow, Object.freeze({ instruction: subagentsFor(s.workflow) })])
)
);
export function offered(workflow) {
return typeof workflow === "string" && Object.prototype.hasOwnProperty.call(SUBAGENT_WORKFLOWS, workflow);
+393
View File
@@ -0,0 +1,393 @@
// Plan2Code Web Console - pictures and documents attached to a note: chips, trays, re-encoding, upload, retry; defines only.
//
// Shared by the question cards and the Ask pane, so neither imports the other.
import { SVG_NS, el } from "./render.js";
import {
docExt,
formatBytes,
DOC_TYPES,
MAX_ATTACHMENTS,
pickerAccept,
attachmentKind,
fitWithin,
IMAGE_LONG_EDGE,
IMAGE_QUALITY,
THUMB_EDGE,
MAX_DOC_BYTES,
sortAttachments,
} from "./answers.js";
import { hooks, page, saveNow, redraw } from "./state.js";
import { CHAT_MAX_ATTACHMENTS } from "./chat.js";
// The chat's images live under local.chat, not beside the notes: the card
// send gathers every entry of local.images, and a chat picture is not a note.
export const CHAT_IMAGES = "__chat";
// An upload's server path is `<session>/uploads/<uuid>.<ext>`; the page serves
// it at /uploads/<uuid>.<ext>.
export const uploadUrl = (img) => img.url || "/uploads/" + String(img.path || "").split(/[\\/]/).pop();
// A page with its corner folded, drawn inline: the CSP allows no icon font.
function pageIcon() {
const svg = document.createElementNS(SVG_NS, "svg");
svg.setAttribute("class", "attach-chip-icon");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("width", "24");
svg.setAttribute("height", "24");
svg.setAttribute("aria-hidden", "true");
for (const d of ["M6 2.5h8.5L19 7v14.5H6z", "M14.5 2.5V7H19"]) {
const path = document.createElementNS(SVG_NS, "path");
path.setAttribute("d", d);
svg.appendChild(path);
}
return svg;
}
// A document in a tray: never an <img>, since a document is not a picture.
// Icon, extension badge, name and size; a sent one is wrapped in a link.
export function docChip(entry, status) {
const ext = docExt(entry.name) || "";
const fig = el("figure", `attach-thumb attach-chip is-${status}`);
const size = typeof entry.size === "number" ? formatBytes(entry.size) : "";
const label = DOC_TYPES[ext] ? DOC_TYPES[ext].label : "";
fig.setAttribute("aria-label", [entry.name, label, size].filter(Boolean).join(", "));
fig.appendChild(pageIcon());
const text = el("div", "attach-chip-text");
if (ext) text.appendChild(el("span", "attach-chip-badge", ext.toUpperCase()));
text.appendChild(el("span", "attach-chip-name", entry.name));
if (size) text.appendChild(el("span", "attach-chip-size", size));
fig.appendChild(text);
return fig;
}
// The + Attach file control and its hidden picker, for a note's box or a
// card's own. Files go to the item's note attachments either way.
export function attachRow(itemId, ariaLabel) {
const row = el("div", "attach-row");
const btn = el("button", "btn small ghost", "+ Attach file");
btn.type = "button";
btn.setAttribute("aria-label", ariaLabel);
btn.disabled = noteImages(itemId).length >= MAX_ATTACHMENTS;
const picker = el("input");
picker.type = "file";
picker.accept = pickerAccept();
picker.multiple = true;
picker.hidden = true;
btn.addEventListener("click", () => picker.click());
picker.addEventListener("change", () => {
attachFiles(itemId, picker.files);
picker.value = "";
});
row.appendChild(btn);
row.appendChild(picker);
return row;
}
export function attachTray(itemId, attached) {
const tray = el("div", "attach-tray");
for (const img of attached) {
let fig;
if (attachmentKind(img) === "file") fig = docChip(img, img.status);
else {
fig = el("figure", "attach-thumb is-" + img.status);
const src = thumbs.get(img.key) || img.url;
if (src) {
const pic = el("img");
pic.src = src;
pic.alt = img.name;
fig.appendChild(pic);
}
}
const rm = el("button", "attach-remove", "×");
rm.type = "button";
rm.setAttribute("aria-label", `Remove ${img.name}`);
rm.addEventListener("click", () => removeImage(itemId, img.key));
fig.appendChild(rm);
if (img.status === "uploading") {
const over = el("div", "attach-overlay");
over.appendChild(el("span", "spinner tiny"));
fig.appendChild(over);
} else if (img.status === "failed") {
const over = el("div", "attach-overlay failed");
over.appendChild(el("span", null, "Upload failed"));
const retry = el("button", "btn tiny", "Retry");
retry.type = "button";
retry.addEventListener("click", () => retryImage(itemId, img.key));
const drop = el("button", "btn tiny", "Remove");
drop.type = "button";
drop.addEventListener("click", () => removeImage(itemId, img.key));
over.appendChild(retry);
over.appendChild(drop);
fig.appendChild(over);
}
tray.appendChild(fig);
}
return tray;
}
const MAX_UPLOAD_BYTES = 4 * 1024 * 1024;
// Three ways in, because browsers disagree: EXIF-aware bitmap decode, plain
// bitmap decode, then an <img> fed a data: URL. Not an object URL: the CSP
// allows `data:` images and refuses `blob:` ones.
async function decodeImage(file) {
try {
return await createImageBitmap(file, { imageOrientation: "from-image" });
} catch {}
try {
return await createImageBitmap(file);
} catch {}
try {
const url = await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
return await new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.src = url;
});
} catch {
throw new Error("That file could not be read as an image.");
}
}
function drawScaled(source, edge) {
const w0 = source.naturalWidth || source.width;
const h0 = source.naturalHeight || source.height;
const { w, h } = fitWithin(w0, h0, edge);
const canvas = document.createElement("canvas");
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext("2d");
// JPEG has no alpha: a transparent PNG would otherwise turn black.
ctx.fillStyle = "#fff";
ctx.fillRect(0, 0, w, h);
ctx.drawImage(source, 0, 0, w, h);
return canvas;
}
// The upload (a JPEG no longer than IMAGE_LONG_EDGE) and the tray's thumbnail
// (a small data: URL), from one decode.
async function reencode(file) {
const source = await decodeImage(file);
try {
const blob = await new Promise((resolve, reject) =>
drawScaled(source, IMAGE_LONG_EDGE).toBlob(
(b) => (b ? resolve(b) : reject(new Error("That image could not be converted."))),
"image/jpeg",
IMAGE_QUALITY
)
);
if (blob.size > MAX_UPLOAD_BYTES) throw new Error("That image is too large even after shrinking it.");
const thumb = drawScaled(source, THUMB_EDGE).toDataURL("image/jpeg", 0.7);
return { blob, thumb };
} finally {
if (typeof source.close === "function") source.close();
}
}
// Thumbnails and retry blobs, keyed by an attachment's local `key`. Kept out
// of `local`: both are large, and neither survives a reload anyway.
export const thumbs = new Map();
const retryBlobs = new Map();
// A note's pictures, or the chat composer's (CHAT_IMAGES), which live apart.
export const noteImages = (itemId) =>
itemId === CHAT_IMAGES ? page.local.chat.images : (page.local.images && page.local.images[itemId]) || [];
const findImage = (itemId, key) => noteImages(itemId).find((img) => img.key === key) || null;
function setNoteImages(itemId, list) {
if (itemId === CHAT_IMAGES) page.local.chat.images = list;
else if (list.length) page.local.images[itemId] = list;
else delete page.local.images[itemId];
}
// Where an attachment is deleted from. Documents have no `url`, so their
// route is built from the path, as uploadUrl does.
export const deleteUrl = (entry) => entry.url || "/uploads/" + String(entry.path || "").split(/[\\/]/).pop();
// The files in a paste worth attaching: images and allowed documents. A paste
// with none of them is left to paste as text.
export function incomingFiles(list) {
return Array.from(list || []).filter((f) => (f.type && f.type.startsWith("image/")) || docExt(f.name));
}
const notAllowedText = (name) => `"${name}" can't be attached: only images, text, code and PDF files.`;
const tooLargeText = (name) => `"${name}" is over ${formatBytes(MAX_DOC_BYTES)}.`;
async function uploadBlob(itemId, key, blob) {
const img = findImage(itemId, key);
if (!img) return;
const isFile = attachmentKind(img) === "file";
img.status = "uploading";
saveNow();
redraw();
let body = null;
let status = 0;
try {
const res = await fetch("/upload", {
method: "POST",
headers: {
"content-type": isFile ? "application/octet-stream" : "image/jpeg",
"x-p2c-name": encodeURIComponent(img.name),
},
body: blob,
});
status = res.status;
if (res.ok) body = await res.json();
} catch {}
const now = findImage(itemId, key);
if (!now) {
// Removed while it was on its way: the file it just made belongs to nobody.
if (body && body.ok && body.id) fetch(deleteUrl(body), { method: "DELETE" }).catch(() => {});
return;
}
if (body && body.ok) {
Object.assign(now, { id: body.id, path: body.path, name: body.name, size: body.size, kind: body.kind, status: "ready" });
if (body.url) now.url = body.url;
retryBlobs.delete(key);
} else if (isFile && (status === 415 || status === 413)) {
// The server read the file and said no: Retry would only fail again.
setNoteImages(itemId, noteImages(itemId).filter((x) => x.key !== key));
retryBlobs.delete(key);
hooks.banner(status === 413 ? tooLargeText(now.name) : notAllowedText(now.name), "warn");
} else {
now.status = "failed";
retryBlobs.set(key, blob);
}
saveNow();
redraw();
}
export async function attachFiles(itemId, files) {
const given = Array.from(files || []);
const { images, docs, refused } = sortAttachments(given);
const chat = itemId === CHAT_IMAGES;
const room = Math.max(0, (chat ? CHAT_MAX_ATTACHMENTS : MAX_ATTACHMENTS) - noteImages(itemId).length);
const wanted = given.filter((f) => images.includes(f) || docs.includes(f));
const taken = wanted.slice(0, room);
// One banner at a time, so every refusal goes into it, each by name.
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
if (taken.length < wanted.length)
said.push(
chat ? `Up to ${CHAT_MAX_ATTACHMENTS} attachments per question.` : `Up to ${MAX_ATTACHMENTS} attachments per note.`
);
if (said.length) hooks.banner(said.join(" "), refused.length ? "warn" : "info");
await Promise.all(
taken.map(async (file) => {
const key = crypto.randomUUID();
if (docs.includes(file)) {
setNoteImages(itemId, [
...noteImages(itemId),
{ key, kind: "file", name: file.name, size: file.size, status: "uploading" },
]);
saveNow();
redraw();
await uploadBlob(itemId, key, file);
return;
}
setNoteImages(itemId, [
...noteImages(itemId),
{ key, kind: "image", name: file.name || "pasted-image.png", status: "uploading" },
]);
saveNow();
redraw();
let encoded;
try {
encoded = await reencode(file);
} catch (err) {
setNoteImages(itemId, noteImages(itemId).filter((img) => img.key !== key));
saveNow();
redraw();
hooks.banner(err.message, "warn");
return;
}
thumbs.set(key, encoded.thumb);
await uploadBlob(itemId, key, encoded.blob);
})
);
}
export async function removeImage(itemId, key) {
const img = findImage(itemId, key);
setNoteImages(itemId, noteImages(itemId).filter((x) => x.key !== key));
thumbs.delete(key);
retryBlobs.delete(key);
saveNow();
redraw();
// Errors are ignored: the 30-day sweep is the backstop.
if (img && img.id) fetch(deleteUrl(img), { method: "DELETE" }).catch(() => {});
}
async function retryImage(itemId, key) {
const blob = retryBlobs.get(key);
if (blob) return uploadBlob(itemId, key, blob);
await removeImage(itemId, key);
hooks.banner("Attach it again.", "info");
}
// Every note with something in it — text, attachments, or both — as
// { id, text, images, held }. `held` is a note with an image still uploading
// or failed: it stays drafted, and only it waits.
function draftedNotes() {
const ids = new Set();
for (const [key, text] of Object.entries(page.local.drafts)) {
if (key.startsWith("thread-") && text && text.trim()) ids.add(key.slice(7));
}
for (const [id, list] of Object.entries(page.local.images || {})) if (list.length) ids.add(id);
return [...ids].map((id) => {
const imgs = noteImages(id);
return {
id,
text: (page.local.drafts["thread-" + id] || "").trim(),
images: imgs.filter((img) => img.status === "ready"),
held: imgs.some((img) => img.status === "uploading" || img.status === "failed"),
};
});
}
export function pendingNotes() {
return draftedNotes()
.filter((n) => !n.held && (n.text || n.images.length))
.map(({ id, text, images }) => ({ id, text, images }));
}
export function heldNotes() {
return draftedNotes().filter((n) => n.held);
}
// A sent note's attachments as links: an image opens full size, a document
// opens in its own tab. The page serves both by the upload's own file name.
export function sentAttachments(note) {
const entries = [
...(note.images || []).map((e) => ({ ...e, kind: "image" })),
...(note.files || []).map((e) => ({ ...e, kind: "file" })),
];
if (!entries.length) return null;
const tray = el("div", "attach-tray");
for (const e of entries) {
const a = el("a", "attach-link");
a.href = uploadUrl(e);
a.target = "_blank";
a.rel = "noopener";
a.title = e.name || "attachment";
if (e.kind === "image") {
const fig = el("figure", "attach-thumb is-ready");
const pic = el("img");
pic.src = a.href;
pic.alt = e.name || "image";
fig.appendChild(pic);
a.appendChild(fig);
} else a.appendChild(docChip({ name: e.name || "file" }, "ready"));
tray.appendChild(a);
}
return tray;
}
+1 -1
View File
@@ -2,7 +2,7 @@
//
// The source of truth for what a folder may be called, the name a new folder
// gets by default, and the suggestion offered when a name is taken. Imported
// by the server (its guards), lib.mjs and the page, so they can never disagree.
// by the server (its guards), workspace.mjs and the page, so they can never disagree.
// No DOM access at module scope and no imports: the page and `node --test`
// both import this file.
File diff suppressed because it is too large. Load diff
+232
View File
@@ -0,0 +1,232 @@
// Plan2Code Web Console - what the dashboard knows about the repo: AGENTS.md, and each spec's state.
import fs from "node:fs";
import path from "node:path";
import { isDeletableSpecDir } from "./public/answers.js";
import { SPEC_STATES as STATE_TABLE } from "./public/spec-states.js";
import { nowIso, readText } from "./files.mjs";
import { insideGitRepo, pendingFiles } from "./sessions.mjs";
/* ---------------------------------------------------------- project scan */
// What the dashboard needs to know about the repo it was opened in: whether
// AGENTS.md exists, and where every spec under specs/ sits in the pipeline.
// These are filesystem facts, not agent judgment, so the console computes
// them itself on every `open` (and every resume back to the dashboard) and
// puts them on the session state. The page lights the right cards straight
// from it; the agent keeps only the opinion (note / recommend / details).
// Where a spec folder stands, named after the step its files are ready for.
// "unrecognized" is a folder with files but no pipeline shape: it launches
// Pathfinder or Plan (the files may be reference docs) but unlocks nothing
// else, exactly like picking no spec at all. "diagnosed" is a bug Diagnose
// wrote up and nobody has fixed or planned yet: it lights Quick Task and Plan.
// "fixed" is that bug once Quick Task marked it Fixed: finished, so the
// dashboard never picks or suggests it, and Quick Task offers to archive it.
// The states themselves, with their labels and flags, are public/spec-states.js.
export const SPEC_STATES = new Set(Object.keys(STATE_TABLE));
// The newest mtime under dir. `tally.files` counts the files the same walk
// sees (within its depth and budget), for the dashboard's delete dialog.
function maxMtime(dir, depth = 4, budget = { n: 400 }, tally = null) {
let best = 0;
if (depth < 0 || budget.n <= 0) return best;
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return best;
}
for (const e of entries) {
if (budget.n-- <= 0) break;
if (e.name.startsWith(".")) continue;
const p = path.join(dir, e.name);
try {
if (e.isDirectory()) best = Math.max(best, maxMtime(p, depth - 1, budget, tally));
else {
best = Math.max(best, fs.statSync(p).mtimeMs);
if (tally) tally.files++;
}
} catch {}
}
return best;
}
// A spec file's Status line value, in any of the forms the skill scripts
// accept (`**Status:**`, `**Status**:`, `Status:`). Same pattern as STATUS_RE
// in src/skill-scripts/specs.mjs; the console cannot import it, so keep the
// two copies in step. A CRLF file's trailing `\r` is dropped.
const STATUS_LINE_RE = /^[ \t]*(?:[-*][ \t]*)?(?:\*\*Status:\*\*|\*\*Status\*\*:|Status:)[ \t]*(.+?)[ \t\r]*$/m;
// A phase file's task line (`- [ ] **Task 1.2:**`). The scan counts by it,
// and patches.mjs keeps only these lines for a doc block's `select: "tasks"`.
export const TASK_LINE_RE = /^\s*(?:[-*]|\d+\.)\s+\[.\]\s+\*\*Task\s/i;
function statusOf(text) {
const m = text.match(STATUS_LINE_RE);
return m ? m[1] : "";
}
// A spec folder's pipeline position, from its files alone. Furthest artifact
// wins: an overview beats a draft beats a map, so a spec mid-way through two
// stages reports the later one.
function classifySpec(dir, names) {
const has = (re) => names.some((n) => re.test(n));
const pfDir = path.join(dir, "pathfinder");
const overview = names.includes("overview.md");
const phases = names.filter((n) => /^phase-.*\.md$/i.test(n));
const drafts = names.filter((n) => /^PLAN-DRAFT.*\.md$/i.test(n));
const planDraft = drafts.length > 0;
const planConv = has(/^PLAN-CONVERSATION.*\.md$/i);
const liveDraft = drafts.filter((n) => !/-prev\.md$/i.test(n)).sort().reverse()[0] || drafts[0];
const draftStatus = liveDraft ? statusOf(readText(path.join(dir, liveDraft))) : "";
const resumeAt = draftStatus.match(/Resume at Phase\s*(\d+)/i);
if (phases.length) {
let done = 0;
let open = 0;
for (const f of phases) {
const text = readText(path.join(dir, f));
// The task lines when the file has them (`- [ ] **Task 1.2:**`), so an
// Acceptance Criteria checkbox is not counted as a task; every checkbox
// in a file written before that format.
const tasks = text.split(/\r?\n/).filter((l) => TASK_LINE_RE.test(l));
const lines = tasks.length ? tasks.join("\n") : text;
done += (lines.match(/^\s*[-*] \[[xX]\]/gm) || []).length;
open += (lines.match(/^\s*[-*] \[[ /!]\]/gm) || []).length;
}
const total = done + open;
if (open === 0 && done > 0) return { state: "built", detail: "all tasks done" };
if (done > 0) return { state: "building", detail: `${done} of ${total} tasks done` };
return {
state: "documented",
detail: `${phases.length} phase${phases.length === 1 ? "" : "s"}, ${total || "?"} tasks ready`,
};
}
// An overview with no phase files means Document was interrupted mid-write;
// its next step is the same as a finished plan's.
if (overview) return { state: "planned", detail: "plan drafted" };
// A draft Pathfinder (or an interrupted Plan) left mid-way says so in its
// Status line: Plan still has phases to run before Document can start.
if (resumeAt) return { state: "mapped", detail: `plan draft, resume at Phase ${resumeAt[1]}` };
if (planDraft) return { state: "planned", detail: "plan drafted" };
// A bug Diagnose wrote up, with nothing after it yet. A pathfinder map or a
// plan conversation means planning has started, so the usual states win.
// Quick Task marks the write-up Fixed once the bug is gone: then the bug is
// done, and the folder waits only to be archived.
const diagnosis = names.filter((n) => /^DIAGNOSIS-.*\.md$/i.test(n)).sort().reverse()[0];
const diagnosisStatus = diagnosis ? statusOf(readText(path.join(dir, diagnosis))).replace(/\*+/g, "").trim() : "";
if (diagnosis && !planConv && !fs.existsSync(path.join(pfDir, "map.md")))
return /^fixed/i.test(diagnosisStatus)
? { state: "fixed", detail: "bug fixed" }
: { state: "diagnosed", detail: "bug diagnosed, not fixed" };
if (isDir(pfDir)) {
const mapText = readText(path.join(pfDir, "map.md"));
const status = statusOf(mapText).replace(/\*+/g, "").trim();
if (/^cleared/i.test(status)) return { state: "mapped", detail: "all decisions made" };
let qTotal = 0;
let qDone = 0;
const qDir = path.join(pfDir, "questions");
try {
for (const q of fs.readdirSync(qDir)) {
if (!q.endsWith(".md")) continue;
qTotal++;
if (/^State:\s*resolved/m.test(readText(path.join(qDir, q)))) qDone++;
}
} catch {}
return {
state: "exploring",
detail: qTotal ? `${qDone} of ${qTotal} decisions made` : "getting started",
};
}
// A conversation log with no draft is a plan session interrupted before it
// wrote anything: Plan resumes it, same as a cleared map.
if (planConv) return { state: "mapped", detail: "planning in progress" };
return { state: "unrecognized", detail: "no pipeline files yet" };
}
function isDir(p) {
try {
return fs.statSync(p).isDirectory();
} catch {
return false;
}
}
/**
* Scan <root>/specs into picker entries, most recently touched first.
* `touched` is the newest file mtime inside the folder — last write wins,
* which is the honest reading of "the one you were working on".
* `isGit` says whether `root` sits inside a git repository (no git process);
* `pending` is how many paths a commit would take, or null when unknown.
*/
export function scanProject(root) {
const specsDir = path.join(root, "specs");
const specs = [];
let names = [];
try {
names = fs.readdirSync(specsDir);
} catch {}
for (const name of names) {
if (name.startsWith(".")) continue;
const dir = path.join(specsDir, name);
if (!isDir(dir)) continue;
// A spec deleted mid-scan (or unreadable) must not kill `open`: the
// picker just never shows it.
let files;
try {
files = fs.readdirSync(dir);
} catch {
continue;
}
const tally = { files: 0 };
specs.push({
dir: `specs/${name}`,
name,
...classifySpec(dir, files),
touched: maxMtime(dir, 4, { n: 400 }, tally),
files: tally.files,
});
}
specs.sort((a, b) => b.touched - a.touched || a.name.localeCompare(b.name));
const isGit = insideGitRepo(root);
return {
at: nowIso(),
hasAgents: fs.existsSync(path.join(root, "AGENTS.md")),
isGit,
pending: isGit ? pendingFiles(root) : null,
specs,
};
}
/**
* Delete one spec folder, for the dashboard's Delete button (`delete-spec`).
* Only an existing `specs/<name>` folder, as isDeletableSpecDir() spells it,
* whose real path sits directly in the worktree's own specs/: never a link to
* somewhere else, never specs--completed/, never anything deeper. specs/ is
* gitignored, so a mistake here cannot be undone; every refusal throws with
* the reason, and nothing is touched.
*/
export function removeSpec(worktree, dir) {
if (!isDeletableSpecDir(dir)) throw new Error(`"${dir}" is not a spec folder: only specs/<name> can be deleted`);
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
const root = path.resolve(worktree);
const target = path.join(root, dir);
let st;
try {
st = fs.lstatSync(target);
} catch {
throw new Error(`there is no ${dir} to delete`);
}
if (st.isSymbolicLink()) throw new Error(`${dir} is a link to another folder, so it is not deleted from here`);
if (!st.isDirectory()) throw new Error(`${dir} is not a folder`);
const real = fs.realpathSync.native(target);
const realSpecs = fs.realpathSync.native(path.join(root, "specs"));
const realRoot = fs.realpathSync.native(root);
const rel = path.relative(fold(realRoot), fold(realSpecs));
if (rel !== "specs" || fold(path.dirname(real)) !== fold(realSpecs)) {
throw new Error(`${dir} resolves outside the project's specs/ folder, so it is not deleted`);
}
fs.rmSync(real, { recursive: true });
return { ok: true, removed: dir };
}
+103 -1647
View File
File diff suppressed because it is too large. Load diff
+731
View File
@@ -0,0 +1,731 @@
// Plan2Code Web Console - finding a session's roots, and keeping the console folder tidy.
import fs from "node:fs";
import net from "node:net";
import path from "node:path";
import crypto from "node:crypto";
import { execFileSync } from "node:child_process";
import { countPending } from "./git-repo.mjs";
import { DOC_TYPES } from "./public/answers.js";
import { appendJsonLine, HOME_DIR, nowIso, PLAN2CODE_DIR, readJson, readJsonLines, readText, RUNTIME_DIR, SESSIONS_DIR } from "./files.mjs";
/* -------------------------------------------------------------- sessions */
// Both roots a session needs, found the way git discovers a repository: walk
// up to the first `.git`, follow a `gitdir:` file (a linked worktree or a
// submodule) and its `commondir`. Read off the filesystem rather than asked of
// `git rev-parse`, because on Windows each git process costs 150ms or more
// and `open` sits between the person and their first look at the page.
//
// project the COMMON dir's parent, so every worktree shares a project key
// worktree the checkout's own top level, where its specs/ lives
// branch the checkout's current branch, read from its own git dir's HEAD
// (so a linked worktree reports its own branch, not the main
// checkout's); "" on a detached HEAD or outside a repository
//
// The environment variables that relocate a repository are git's business,
// so when one is set this asks git, exactly as it used to.
const rootsCache = new Map();
export function repoRoots(cwd = process.cwd()) {
const key = path.resolve(cwd);
if (!rootsCache.has(key)) rootsCache.set(key, findRoots(key));
return rootsCache.get(key);
}
function findRoots(cwd) {
// The native realpath, like git, spells the path out in full: an 8.3 short
// name in the cwd (C:\Users\JUSTIN~1.PAR) must key the same project as the
// long one, or two spellings of one checkout get separate handle spaces.
const real = (p) => {
for (const fn of [fs.realpathSync.native, fs.realpathSync]) {
try {
return fn(p);
} catch {}
}
return p;
};
if (process.env.GIT_DIR || process.env.GIT_WORK_TREE || process.env.GIT_COMMON_DIR) {
try {
// The branch comes off the git dir's HEAD, as in the walk below, not
// from `--abbrev-ref HEAD`: that fails the whole call on a repository
// with no commits yet, and cannot name an unborn branch anyway.
const [common, top, gitDir] = execFileSync(
"git",
["rev-parse", "--path-format=absolute", "--git-common-dir", "--show-toplevel", "--absolute-git-dir"],
{ cwd, stdio: ["ignore", "pipe", "ignore"], encoding: "utf8" }
)
.trim()
.split(/\r?\n/);
if (common) {
return {
project: real(path.dirname(common)),
worktree: real(top || cwd),
branch: gitDir ? branchAt(gitDir) : "",
};
}
} catch {}
return { project: real(cwd), worktree: real(cwd), branch: "" };
}
for (let dir = cwd; ; ) {
const git = gitDirAt(dir);
if (git) {
const common = readText(path.join(git, "commondir")).trim();
const commonDir = common ? path.resolve(git, common) : git;
return { project: real(path.dirname(commonDir)), worktree: real(dir), branch: branchAt(git) };
}
const up = path.dirname(dir);
if (up === dir) return { project: real(cwd), worktree: real(cwd), branch: "" };
dir = up;
}
}
// The branch a git dir's HEAD names: `ref: refs/heads/<name>` gives <name>.
// A bare hash (a detached HEAD) or an unreadable file gives "".
function branchAt(gitDir) {
const m = /^ref:\s*refs\/heads\/(.+?)\s*$/m.exec(readText(path.join(gitDir, "HEAD")));
return m ? m[1] : "";
}
// The git dir that `<dir>/.git` names, or null when there is no usable one.
// A directory without HEAD is not a repository, and git keeps walking past it.
function gitDirAt(dir) {
const dotGit = path.join(dir, ".git");
let st;
try {
st = fs.statSync(dotGit);
} catch {
return null;
}
let git = dotGit;
if (st.isFile()) {
const m = /^gitdir:\s*(.+?)\s*$/m.exec(readText(dotGit));
if (!m) return null;
git = path.resolve(dir, m[1]);
}
return fs.existsSync(path.join(git, "HEAD")) ? git : null;
}
// Whether `dir` is inside a git repository, found without a git process: the
// same walk findRoots() does. A set GIT_DIR / GIT_WORK_TREE / GIT_COMMON_DIR
// means git decides, so it counts as a repository. A `gitdir:` file (a linked
// worktree or a submodule) counts like a `.git` folder.
export function insideGitRepo(dir) {
if (process.env.GIT_DIR || process.env.GIT_WORK_TREE || process.env.GIT_COMMON_DIR) return true;
for (let d = path.resolve(dir); ; ) {
if (gitDirAt(d)) return true;
const up = path.dirname(d);
if (up === d) return false;
d = up;
}
}
// How many paths git would commit from `dir`: modified, staged, deleted and
// untracked (an untracked folder counts once), from one bounded `git status`.
// null when git cannot say (not installed, not a repository, too slow), which
// the page reads as "unknown", never as a clean tree. GIT_OPTIONAL_LOCKS=0 (set
// by git-repo.mjs) keeps this background look from taking the index lock out
// from under a commit.
export function pendingFiles(dir) {
return countPending(dir);
}
export function projectRoot(cwd = process.cwd()) {
return repoRoots(cwd).project;
}
// The worktree's own top level. projectRoot() keys sessions on the COMMON git
// dir so every worktree shares one handle space -- but the specs a dashboard
// shows are the ones on disk under the caller, so the scan roots here instead.
export function worktreeRoot(cwd = process.cwd()) {
return repoRoots(cwd).worktree;
}
export function cwdHash(dir) {
return crypto.createHash("sha1").update(dir.toLowerCase()).digest("hex").slice(0, 8);
}
export function newSessionId() {
const d = new Date();
const p = (n) => String(n).padStart(2, "0");
const stamp = `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(
d.getMinutes()
)}${p(d.getSeconds())}`;
return `${stamp}-${crypto.randomBytes(3).toString("hex")}`;
}
export function sessionDir(sid) {
return path.join(SESSIONS_DIR, sid);
}
export const UPLOAD_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
const SESSION_ID = /^\d{8}-\d{6}-[0-9a-f]{6}$/;
/**
* Remove the attachments uploaded in sessions nobody has touched for a month.
*
* "Touched" is state.json's mtime: every agent post and every page send writes
* it. Only the `uploads` child of a directory shaped like a session id is ever
* removed -- session text (state, drafts, results, events) is never touched --
* and the path is built from `sessionsDir` plus that validated name, never from
* anything a client sent. Resolves to the sids swept.
*/
export async function sweepUploads(sessionsDir, now, maxAgeMs, skipSid) {
let entries;
try {
entries = await fs.promises.readdir(sessionsDir, { withFileTypes: true });
} catch {
return [];
}
const swept = [];
for (const entry of entries) {
if (!entry.isDirectory() || entry.name === skipSid || !SESSION_ID.test(entry.name)) continue;
const dir = path.join(sessionsDir, entry.name);
try {
const { mtimeMs } = await fs.promises.stat(path.join(dir, "state.json"));
if (now - mtimeMs <= maxAgeMs) continue;
await fs.promises.rm(path.join(dir, "uploads"), { recursive: true, force: true });
swept.push(entry.name);
} catch {}
}
return swept;
}
// The name a kept attachment gets under specs/<idea>/attachments/: the same upload always yields the same name.
export function attachmentName({ upload, name }) {
const label = typeof name === "string" ? name : "";
const slug =
label
.slice(0, label.length - path.extname(label).length)
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 40)
.replace(/-+$/, "") || "attachment";
const base = path.basename(String(upload || ""));
return `${slug}-${base.slice(0, 8)}${path.extname(base).toLowerCase()}`;
}
// Sessions and their uploads age out on the same clock: a month untouched.
export const SESSION_MAX_AGE_MS = UPLOAD_MAX_AGE_MS;
const PDF_MAGIC = Buffer.from("%PDF-", "ascii");
/**
* Whether an uploaded document is what its extension says: null when it is,
* "type" when it is not. The browser's MIME type and the file name are both
* claims the client makes; only the bytes are evidence. A PDF must open with
* `%PDF-`; a text file must be strict UTF-8 with no NUL byte, which is what
* keeps a renamed binary out. An empty text file is fine.
*/
export function checkDocument(buf, ext) {
const type = Object.prototype.hasOwnProperty.call(DOC_TYPES, ext) ? DOC_TYPES[ext] : null;
if (!type) return "type";
if (type.kind === "pdf") {
return buf.length >= PDF_MAGIC.length && buf.subarray(0, PDF_MAGIC.length).equals(PDF_MAGIC) ? null : "type";
}
if (buf.includes(0)) return "type";
try {
new TextDecoder("utf-8", { fatal: true }).decode(buf);
} catch {
return "type";
}
return null;
}
/**
* The sessions nobody has touched for `maxAgeMs`: names of directories shaped
* like a session id (never `skipSid`) whose state.json mtime is that old.
* A directory with no readable state.json is skipped, never guessed at.
*
* Synchronous, because `open` reports the list before it prints and deletes
* after. No exceptions for paused sessions or unread sends: a month-old
* session is gone whole (a locked decision).
*/
export function staleSessions(sessionsDir, now, maxAgeMs, skipSid) {
let entries;
try {
entries = fs.readdirSync(sessionsDir, { withFileTypes: true });
} catch {
return [];
}
const stale = [];
for (const entry of entries) {
if (!entry.isDirectory() || entry.name === skipSid || !SESSION_ID.test(entry.name)) continue;
try {
const { mtimeMs } = fs.statSync(path.join(sessionsDir, entry.name, "state.json"));
if (now - mtimeMs > maxAgeMs) stale.push(entry.name);
} catch {}
}
return stale;
}
/**
* Remove whole session directories. Every name is re-checked against the
* session-id pattern, and the path is built only from `sessionsDir` plus that
* validated name. Resolves to the sids actually removed.
*/
export async function removeSessions(sessionsDir, sids) {
const removed = [];
for (const sid of sids) {
if (typeof sid !== "string" || !SESSION_ID.test(sid)) continue;
try {
await fs.promises.rm(path.join(sessionsDir, sid), { recursive: true, force: true });
removed.push(sid);
} catch {}
}
return removed;
}
// The console folder's own files that no sweep may ever remove: the person's
// looks, the folders remembered per project and spec, the Subagents switch
// saved per project and workflow, what each unknown git host is, the pointer
// to this console's directory, and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set([
"looks.json",
"workspaces.json",
"subagents.json",
"pr-hosts.json",
"console-dir",
"update-check.json",
]);
function isScratchName(name) {
return (
typeof name === "string" &&
name === path.basename(name) &&
/\.(json|mjs)$/.test(name) &&
!PROTECTED_CONSOLE_FILES.has(name)
);
}
/**
* Leftover scratch files (agent patches, helper scripts) at the top of the
* console folder: regular files ending in .json or .mjs, never a protected
* name, a directory or a symlink, whose mtime is older than `maxAgeMs`.
*/
export function staleScratch(consoleDir, now, maxAgeMs) {
let entries;
try {
entries = fs.readdirSync(consoleDir, { withFileTypes: true });
} catch {
return [];
}
const stale = [];
for (const entry of entries) {
if (!entry.isFile() || !isScratchName(entry.name)) continue;
try {
const st = fs.lstatSync(path.join(consoleDir, entry.name));
if (st.isFile() && now - st.mtimeMs > maxAgeMs) stale.push(entry.name);
} catch {}
}
return stale;
}
// Every name re-checked against the same rule before anything is removed.
export async function removeScratch(consoleDir, names) {
const removed = [];
for (const name of names) {
if (!isScratchName(name)) continue;
try {
await fs.promises.rm(path.join(consoleDir, name), { force: true });
removed.push(name);
} catch {}
}
return removed;
}
/* ------------------------------------------------------------- cleanup */
// What User Preferences -> Cleanup never removes. The console folder keeps its
// protected files, its sessions dir (old sessions go one by one, by age) and,
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
// console, the launcher (bin/, launcher.json), the install record that
// `plan2code update` reads (install.json), the models the person added and
// the handoffs (old ones go one by one, by age, on open: handoffs.mjs).
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "install.json", "models.json", "handoffs"]);
// A stray must sit untouched this long before Cleanup lists it. The same
// folders hold files that live for milliseconds -- a held
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
// rename -- and removing one mid-write loses another session's change.
export const STRAY_GRACE_MS = 60 * 60 * 1000;
// Bytes under `p`, never following a symlink: a link counts as itself.
async function diskBytes(p) {
let st;
try {
st = await fs.promises.lstat(p);
} catch {
return 0;
}
if (!st.isDirectory()) return st.size;
let entries;
try {
entries = await fs.promises.readdir(p);
} catch {
return 0;
}
let total = 0;
for (const name of entries) total += await diskBytes(path.join(p, name));
return total;
}
// The newest mtime of anything under `p`, never following a symlink. A folder
// counts by its files, since rewriting a file never touches its folder's
// mtime; an empty folder counts by its own. Anything unreadable on the way
// down answers Infinity, so it reads as just touched and stays.
function newestMtime(p) {
let st;
try {
st = fs.lstatSync(p);
} catch {
return Infinity;
}
if (!st.isDirectory()) return st.mtimeMs;
let entries;
try {
entries = fs.readdirSync(p);
} catch {
return Infinity;
}
if (!entries.length) return st.mtimeMs;
let newest = 0;
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
return newest;
}
function entryKind(entry) {
if (entry.isSymbolicLink()) return "link";
return entry.isDirectory() ? "folder" : "file";
}
function strayEntries(dir, kept, where, now) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return [];
}
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
return entries
.filter((e) => !kept.has(e.name))
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
.filter((e) => settled(e.path));
}
// Finalize's archive, `<project>/specs--completed/<feature>/`: each feature
// folder (or link) nobody has touched for `maxAgeMs`, judged by its newest
// file. Loose files at the top are not specs and stay.
function completedSpecs(project, now, maxAgeMs) {
const dir = path.join(project, "specs--completed");
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return [];
}
return entries
.filter((e) => e.isDirectory() || e.isSymbolicLink())
.map((e) => ({ id: "completed:" + e.name, where: "completed", name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
.filter((e) => now - newestMtime(e.path) > maxAgeMs);
}
/**
* Everything Cleanup would remove, worked out on the server and never taken
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
* `open` sweeps by, plus every file in the folder that old, so a resumed
* session or a saved draft keeps it), anything at the top of the console folder that is
* not kept, and -- only when the console runs from its default home inside
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
* touched within `STRAY_GRACE_MS` are left for a later scan. A
* console running from another home (tests, dev) never reaches ~/.plan2code.
* Given a `project`, also its completed specs untouched for `maxAgeMs`.
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
*/
export async function cleanupFindings({
consoleDir = HOME_DIR,
plan2codeDir = PLAN2CODE_DIR,
now = Date.now(),
maxAgeMs = SESSION_MAX_AGE_MS,
skipSid,
project,
} = {}) {
const found = [];
const sessionsDir = path.join(consoleDir, "sessions");
for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) {
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
}
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
}
if (project) found.push(...completedSpecs(project, now, maxAgeMs));
const items = [];
let bytes = 0;
for (const f of found) {
const size = await diskBytes(f.path);
bytes += size;
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
}
return { items, bytes };
}
/**
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
* worked out afresh first and only ids on it are touched, so a name from the
* page is never a path, and anything that stopped qualifying since the scan
* (a session touched again) stays. A link is unlinked, never followed.
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
*/
export async function removeCleanup(ids, opts = {}) {
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
const { items } = await cleanupFindings(opts);
const removed = [];
const failed = [];
let bytes = 0;
for (const item of items) {
if (!wanted.has(item.id)) continue;
try {
if (item.kind === "link") await fs.promises.unlink(item.path);
else await fs.promises.rm(item.path, { recursive: true, force: true });
removed.push(item.id);
bytes += item.bytes;
} catch {
failed.push(item.id);
}
}
return { removed, bytes, failed };
}
/**
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
* the file's realpath must sit inside the root's, so `../`, an absolute path
* and a symlink pointing outside all come back null.
*/
export async function readOverview(root, specDir) {
if (!root || !specDir || typeof specDir !== "string" || path.isAbsolute(specDir)) return null;
try {
const file = path.resolve(root, specDir, "overview.md");
const [realFile, realRoot] = await Promise.all([fs.promises.realpath(file), fs.promises.realpath(root)]);
// path.relative, not a prefix test: a root of `C:\` or `/` already ends
// in the separator, and `root + sep` would then match nothing at all.
const rel = path.relative(realRoot, realFile);
if (!rel || rel === ".." || rel.startsWith(".." + path.sep) || path.isAbsolute(rel)) return null;
return await fs.promises.readFile(realFile, "utf8");
} catch {
return null;
}
}
// The line every CLI command hands the agent to end its terminal messages with.
export function terminalLine(url) {
return `→ Look at the web console: ${url}`;
}
export function runtimeDirFor(project) {
return path.join(RUNTIME_DIR, cwdHash(project));
}
export function handleFile(project, sid) {
return path.join(runtimeDirFor(project), sid + ".json");
}
export function newToken() {
return crypto.randomBytes(16).toString("base64url");
}
/* -------------------------------------------------------------- liveness */
// PID reuse is real, so process.kill(pid, 0) is necessary but not sufficient.
// The /health check whose sid matches the handle is the authoritative test:
// it is what distinguishes "our server" from "some process that inherited the PID".
export function pidAlive(pid) {
if (!pid) return false;
try {
process.kill(pid, 0);
return true;
} catch (err) {
return err.code === "EPERM";
}
}
export async function healthOk(handle, timeoutMs = 1500, signal) {
if (!handle || !handle.url) return false;
const ctrl = new AbortController();
const timer = setTimeout(() => ctrl.abort(), timeoutMs);
// The caller's own abort ends the check at once (a wait that is done).
if (signal) {
if (signal.aborted) ctrl.abort();
else signal.addEventListener("abort", () => ctrl.abort(), { once: true });
}
try {
// No explicit Host header: it is a forbidden header name, so fetch drops it
// silently. Requesting 127.0.0.1 directly sets the right one anyway, which
// is what the server's allow-list checks.
const res = await fetch(`http://127.0.0.1:${handle.port}/health`, { signal: ctrl.signal });
if (!res.ok) return false;
const body = await res.json();
return body && body.sid === handle.sid;
} catch {
return false;
} finally {
clearTimeout(timer);
}
}
export function listHandles(project) {
const dir = runtimeDirFor(project);
let names = [];
try {
names = fs.readdirSync(dir).filter((n) => n.endsWith(".json"));
} catch {
return [];
}
return names
.map((n) => readJson(path.join(dir, n)))
.filter(Boolean)
.map((h) => ({ ...h, handlePath: path.join(dir, h.sid + ".json") }));
}
// Delete handle files whose process is gone. Runs on every `open`, so stale
// entries never accumulate. Windows gives us no reliable shutdown signal, so
// sweeping on startup is how the tmp dir stays clean.
export function reapHandles(project) {
let reaped = 0;
for (const h of listHandles(project)) {
if (!pidAlive(h.pid)) {
try {
fs.rmSync(h.handlePath, { force: true });
reaped++;
} catch {}
}
}
return reaped;
}
/* -------------------------------------------------------------- handover */
// A loopback socket, bound and listening, for `open` to hand to the server it
// spawns (see startServer in console.mjs). Null if the bind fails.
export function bindLoopback() {
return new Promise((resolve) => {
// pauseOnConnect: a connection that lands here before the handover is
// passed on untouched, not read from. Collected from the first moment,
// so none can arrive before anybody is listening for it.
const srv = net.createServer({ pauseOnConnect: true });
srv.early = [];
srv.on("connection", (sock) => srv.early.push(sock));
srv.once("error", () => resolve(null));
srv.listen(0, "127.0.0.1", () => resolve(srv));
});
}
// Give the bound socket to the server, pass on anything that connected in the
// meantime, then let go of both the socket and the channel. With no socket
// (`pre` null) the server is told to bind its own. Settles either way; a
// server that never takes the socket is caught by whoever waits on its handle.
export function handOff(child, pre) {
const early = pre ? pre.early : [];
return new Promise((resolve) => {
let done = false;
const finish = async () => {
if (done) return;
done = true;
try {
pre?.close();
} catch {}
// Each passed-on socket is acknowledged by the server once it holds it.
// Letting go of the channel before that drops the socket in transit,
// and with it the browser's first request.
let owed = 0;
let settle = null;
const held = new Promise((r) => (settle = r));
const onAck = (m) => m && m.type === "conn-held" && --owed <= 0 && settle();
child.on("message", onAck);
for (const sock of early) {
try {
child.send({ type: "conn" }, sock);
owed++;
} catch {}
}
if (owed > 0 && !child.exitCode) {
await Promise.race([held, new Promise((r) => setTimeout(r, 2000).unref())]);
}
child.off("message", onAck);
try {
child.disconnect();
} catch {}
child.unref();
resolve();
};
child.on("message", (m) => m && m.type === "listening" && finish());
child.on("exit", finish);
child.on("error", finish);
try {
if (pre) child.send({ type: "listen", port: pre.address().port }, pre, (err) => err && finish());
else child.send({ type: "own" });
} catch {
finish();
}
});
}
/* ------------------------------------------------------ the meter ledger */
export const LEDGER_FILE = "ledger.ndjson";
/**
* Every ledger entry, in order. As with readChat(), a final segment with no
* newline is still being written and is left for the next read, and a line
* that will not parse is skipped.
*/
export function readLedger(dir) {
return readJsonLines(path.join(dir, LEDGER_FILE));
}
// Single-writer rule: only console.mjs may call this.
export function appendLedger(dir, entry) {
return appendJsonLine(path.join(dir, LEDGER_FILE), { ...entry, at: nowIso() });
}
// The id of the skill run in progress: the last launch's, or "L0" before any.
export function lastLaunchId(entries) {
for (let i = entries.length - 1; i >= 0; i--) if (entries[i].kind === "launch") return entries[i].id;
return "L0";
}
export function nextLaunchId(entries) {
return "L" + (entries.filter((e) => e.kind === "launch").length + 1);
}
/**
* Flag the case where the link cannot be opened by the person it is for.
*
* The page is served on 127.0.0.1, which is only their machine if the agent is
* ON their machine. An agent in a cloud VM, a remote sandbox or an SSH session
* hands over a link to its own loopback, and the person sees nothing.
*
* Reported rather than refused, on purpose: a devcontainer or a Codespace
* usually forwards the port automatically and works perfectly. What the agent
* needs is to know that it might not, so it can ask instead of insisting.
*/
export function remoteWarning() {
const signals = [
["SSH_CONNECTION", "an SSH session"],
["SSH_CLIENT", "an SSH session"],
["REMOTE_CONTAINERS", "a dev container"],
["CODESPACES", "a GitHub Codespace"],
["GITPOD_WORKSPACE_ID", "a Gitpod workspace"],
];
const hit = signals.find(([key]) => process.env[key]);
if (!hit) return {};
return {
remote: hit[0],
note:
`This looks like ${hit[1]}, so http://127.0.0.1 is this machine, not necessarily theirs. ` +
`Give them the link, ask whether it opens, and go back to the terminal if it does not.`,
};
}
+193
View File
@@ -0,0 +1,193 @@
// Plan2Code Web Console - the person's saved console settings: Subagents and pull-request hosts.
import path from "node:path";
import { cleanSetting, defaultSetting, offered } from "./public/subagents.js";
import { ensureDir, fileStamp, HOME_DIR, readJson, readJsonLines, withStateLock, writeJsonAtomic } from "./files.mjs";
import { foldKey } from "./workspace.mjs";
/* ------------------------------------------------------ the Subagents switch */
// The person's Subagents switch, remembered per project folder and workflow:
//
// { "<folded project path>": { "<workflow>": { on, instruction, max } } }
//
// Keyed with foldKey(), as workspaces.json is. `instruction: null` is the
// workflow's shipped default.
export const SUBAGENTS_FILE = path.join(HOME_DIR, "subagents.json");
const SUBAGENTS_LOCK = "subagents.json.lock";
function readSubagentStore() {
const saved = readJson(SUBAGENTS_FILE, null);
return saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
}
// The saved `{ on, instruction, max }` for this folder and workflow, or the
// default's when nothing (or something malformed) is saved.
export function subagentStoreEntry(worktree, workflow) {
const { on, instruction, max } = defaultSetting(workflow);
const project = offered(workflow) ? readSubagentStore()[foldKey(worktree)] : null;
const saved = project && typeof project === "object" ? cleanSetting(project[workflow]) : null;
return saved && !saved.error ? saved : { on, instruction, max };
}
// Single-writer rule: only the server may call this (its routes).
export function saveSubagentStoreEntry(worktree, workflow, value) {
ensureDir(path.dirname(SUBAGENTS_FILE));
withStateLock(
path.dirname(SUBAGENTS_FILE),
() => {
const store = readSubagentStore();
const key = foldKey(worktree);
const project = store[key] && typeof store[key] === "object" ? store[key] : {};
store[key] = { ...project, [workflow]: { on: value.on, instruction: value.instruction, max: value.max } };
writeJsonAtomic(SUBAGENTS_FILE, store);
},
SUBAGENTS_LOCK
);
}
/* ------------------------------------------------------- the PR host store */
// What kind of git host an unknown host is, so the git board can build its
// pull-request link. One answer per host, for every project:
//
// { "<host>": "github" | "gitlab" | "bitbucket" | "azure" | "none" }
export const PR_HOSTS_FILE = path.join(HOME_DIR, "pr-hosts.json");
export const PR_HOST_KINDS = new Set(["github", "gitlab", "bitbucket", "azure", "none"]);
const PR_HOSTS_LOCK = "pr-hosts.json.lock";
// The saved hosts as a plain object; malformed → {}, unknown kinds dropped.
export function readPrHosts() {
const saved = readJson(PR_HOSTS_FILE, null);
if (!saved || typeof saved !== "object" || Array.isArray(saved)) return {};
return Object.fromEntries(Object.entries(saved).filter(([, kind]) => PR_HOST_KINDS.has(kind)));
}
// Single-writer rule: only the server may call this (its routes).
export function savePrHost(host, kind) {
ensureDir(path.dirname(PR_HOSTS_FILE));
withStateLock(
path.dirname(PR_HOSTS_FILE),
() => writeJsonAtomic(PR_HOSTS_FILE, { ...readPrHosts(), [host]: kind }),
PR_HOSTS_LOCK
);
}
export const SUBAGENTS_SETTING_FILE = "subagents-setting.json";
const isCount = (n) => Number.isInteger(n) && n >= 0;
// This session's switch, `{ workflow, on, instruction, max, revision }`, or
// null when there is none or it is malformed.
export function readSubagentSetting(dir) {
const s = readJson(path.join(dir, SUBAGENTS_SETTING_FILE), null);
if (!s || typeof s !== "object") return null;
if (typeof s.workflow !== "string" || typeof s.on !== "boolean" || !Number.isInteger(s.max) || !isCount(s.revision)) return null;
return s;
}
// Single-writer rule: only the server may call this (its routes, and
// serverSubagents() below). The revision never goes backwards within a session.
export function writeSubagentSetting(dir, setting) {
const previous = readSubagentSetting(dir);
const revision = Math.max(previous ? previous.revision : 0, setting.revision);
return writeJsonAtomic(path.join(dir, SUBAGENTS_SETTING_FILE), { ...setting, revision });
}
export const SUBAGENTS_CURSOR_FILE = "subagents-cursor.json";
const CURSOR_STATES = new Set(["none", "on", "off"]);
// What the agent was last told: `{ revision, state }`.
export function readSubagentCursor(dir) {
const saved = readJson(path.join(dir, SUBAGENTS_CURSOR_FILE), null);
if (!saved || !isCount(saved.revision) || !CURSOR_STATES.has(saved.state)) return { revision: 0, state: "none" };
return { revision: saved.revision, state: saved.state };
}
// Single-writer rule: only console.mjs may call this. Never backwards, like
// writeWorkspaceCursor(): a killed `wait` may repeat a change, never skip one.
export function writeSubagentCursor(dir, cursor) {
const old = readSubagentCursor(dir);
const next = cursor.revision < old.revision ? old : { revision: cursor.revision, state: cursor.state };
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), next);
}
// The one place the cursor may go back: `open`, which starts a fresh agent.
export function resetSubagentCursor(dir) {
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), { revision: 0, state: "none" });
}
// The `caps` of the last `open` event: what the agent's console copy can do.
export function latestOpenCaps(dir) {
const opens = readJsonLines(path.join(dir, "events.ndjson")).filter((e) => e.type === "open");
const last = opens[opens.length - 1];
return last && Array.isArray(last.caps) ? last.caps : [];
}
/* ------------------------------------------------- the server's Subagents */
export const sameSetting = (a, b) => a.workflow === b.workflow && a.on === b.on && a.instruction === b.instruction && a.max === b.max;
/**
* The Subagents switch as the server keeps it. subagents-setting.json has one
* writer, the server, and the agent hears of it only through what console.mjs
* reads there; events.ndjson's latest `open` says whether the agent's console
* copy can carry it. Both re-read only when their file has moved.
*
* `ctx` is `dir` and `worktree()` (the session's folder, null while unknown).
*/
export function serverSubagents(ctx) {
const { dir } = ctx;
const SETTING_PATH = path.join(dir, SUBAGENTS_SETTING_FILE);
const EVENTS_PATH = path.join(dir, "events.ndjson");
let settingSeen = { stamp: null, setting: null };
function settingNow() {
const stamp = fileStamp(SETTING_PATH);
if (stamp !== settingSeen.stamp) settingSeen = { stamp, setting: readSubagentSetting(dir) };
return settingSeen.setting;
}
let capsSeen = { stamp: null, caps: [] };
function capsNow() {
const stamp = fileStamp(EVENTS_PATH);
if (stamp !== capsSeen.stamp) capsSeen = { stamp, caps: latestOpenCaps(dir) };
return capsSeen.caps;
}
/**
* Turn the per-project store into this session's setting, for the workflow
* the session is in now. The only place that happens (FR-7): a session an
* older server ran has no setting file, so nothing is ever injected into it.
* A record that already matches is left alone, revision and all, so a
* restart alone never re-tells the agent anything.
*/
function sync(state) {
if (!state || typeof state.workflow !== "string") return;
const { workflow } = state;
const { on, instruction, max } = offered(workflow) ? subagentStoreEntry(ctx.worktree(), workflow) : defaultSetting(workflow);
const target = { workflow, on, instruction, max };
const current = readSubagentSetting(dir);
if (current && sameSetting(current, target)) return;
writeSubagentSetting(dir, { ...target, revision: (current ? current.revision : 0) + 1 });
}
// The page shows the switch only when `offered && supported` (FR-3); the
// frame says both and leaves combining them to the page. `instruction: null`
// is the shipped default, which the page reads from subagents.js itself.
function view(state) {
const workflow = state && state.workflow;
const { on, instruction, max, revision } = settingNow() || { ...defaultSetting(workflow), revision: 0 };
return { offered: offered(workflow), supported: capsNow().includes("subagents"), on, instruction, max, revision };
}
return {
settingNow,
capsNow,
sync,
view,
// The stamps of the reads the caches hold, for the frame's `have` key.
stamps: () => `${settingSeen.stamp || ""}.${capsSeen.stamp || ""}`,
};
}
+136
View File
@@ -0,0 +1,136 @@
// Plan2Code Web Console - serving the page's own files: the allow-list, types, caching and the accent colours.
import fs from "node:fs";
import path from "node:path";
import crypto from "node:crypto";
import { PUBLIC_DIR } from "./files.mjs";
import { ACCENTS, DEFAULT_ACCENT } from "./public/palette.js";
/* ------------------------------------------------------------ mime types */
export const TYPES = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".svg": "image/svg+xml",
".mp3": "audio/mpeg",
".png": "image/png",
};
// A hardcoded allow-list, not a filesystem lookup. Nothing to traverse.
export const SERVABLE = new Set([
"app.js",
"answers.js",
"skills.js",
"spec-states.js",
"state.js",
"doc-files.js",
"send-state.js",
"mention-box.js",
"uploads.js",
"sound.js",
"looks.js",
"selectors.js",
"app.css",
"render.js",
"palette.js",
"labels.js",
"boot.js",
"chat.js",
"help.js",
"starters.js",
"workspace.js",
"meter.js",
"subagents.js",
"mentions.js",
"favicon.js",
"git-board.js",
"git-board-view.js",
"pr-url.js",
"start-stop.mp3",
"next.mp3",
"insert.mp3",
"sleeping.mp3",
"bootup.mp3",
"start-skill.mp3",
"favicon.svg",
"favicon.png",
"screens/core.js",
"screens/ending.js",
"screens/docs.js",
"screens/cards.js",
"screens/starting.js",
"screens/dashboard.js",
"screens/git-host.js",
"screens/looks.js",
"screens/cleanup.js",
"screens/help-dialog.js",
"screens/workspace.js",
"screens/ask.js",
"net.js",
"vendor/marked.esm.js",
]);
/* ------------------------------------------------------------ stylesheet */
// The page asks for one /app.css; it is these files under public/styles/,
// joined in this order, which is the one place the cascade order is stated.
// Layers first, then one file per screen, then responsive and print last so
// its overrides still come after everything they override. The files are not
// on SERVABLE: they reach the page only through /app.css.
export const CSS_ORDER = ["tokens.css", "shell.css", "planny.css", "pieces.css", "dashboard.css", "poses.css", "docs.css", "ask.css", "ending.css", "help.css", "looks.css", "git.css", "responsive.css"];
// The files joined with one newline between them (each file's own last newline
// is that one), as the server serves them before the accent rules. The test
// helper joins through this too, so a test can never read a different order.
export function joinedStyles() {
const parts = CSS_ORDER.map((f) => fs.readFileSync(path.join(PUBLIC_DIR, "styles", f), "utf8").replace(/\n$/, ""));
return Buffer.from(parts.join("\n") + "\n");
}
/* ---------------------------------------------------------------- assets */
// Read once per server, from memory after that. Held for the server's whole
// life on purpose: a skill reinstalled under a running session must not hand
// one page a new app.js beside the old answers.js it imports.
//
// Revalidated rather than stored: `no-cache` plus an ETag makes a reload a
// round of 304s instead of 400KB again. Every session is a new port, and so a
// new origin with a cold cache, which is why the first load is made cheap by
// other means (preload hints, the inline boot state) rather than by caching.
const assets = new Map();
export const etagOf = (body) => `"${crypto.createHash("sha1").update(body).digest("base64url").slice(0, 20)}"`;
export function asset(rel) {
let a = assets.get(rel);
if (!a) {
let body = rel === "app.css" ? joinedStyles() : fs.readFileSync(path.join(PUBLIC_DIR, rel));
if (rel === "app.css") body = Buffer.concat([body, Buffer.from(accentCss())]);
const etag = etagOf(body);
a = { body, etag, type: TYPES[path.extname(rel)] || "application/octet-stream" };
assets.set(rel, a);
}
return a;
}
// The saved highlight color, painted from the very first frame. The page's
// script owns the colors once it runs (applyLooks clears the attribute these
// hang off), but until then the only way to avoid flashing the default ocean
// at someone who picked violet is a stylesheet rule the server can switch on
// with an attribute: the CSP forbids inline styles, and the colors live in
// palette.js, so they are generated from there rather than copied into CSS.
function accentCss() {
const vars = (shades) =>
["--accent", "--accent-soft", "--accent-ink", "--accent-line"].map((n, i) => `${n}:${shades[i]}`).join(";");
let css = "\n/* Generated by server.mjs from palette.js: the saved accent before app.js runs. */\n";
for (const [id, a] of Object.entries(ACCENTS)) {
if (id === DEFAULT_ACCENT) continue;
const sel = `:root[data-looks-accent="${id}"]`;
css += `${sel}{${vars(a.light)}}\n`;
css += `@media (prefers-color-scheme: dark){${sel}:not([data-theme="light"]){${vars(a.dark)}}}\n`;
css += `${sel}[data-theme="dark"]{${vars(a.dark)}}\n`;
}
return css;
}
+486
View File
@@ -0,0 +1,486 @@
// Plan2Code Web Console - the session's extra folders, and the folders remembered per project and spec.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
import { ensureDir, fileStamp, HOME_DIR, nowIso, readJson, withStateLock, writeJsonAtomic } from "./files.mjs";
import { remoteWarning } from "./sessions.mjs";
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
export const WORKSPACE_FILE = "workspace.json";
/* -------------------------------------------------------- the workspace */
// The session's workspace.json, or null when the server has not made it yet.
export function readWorkspace(dir) {
return readJson(path.join(dir, WORKSPACE_FILE), null);
}
// A fresh workspace: the original folder, named after itself, plus whatever
// was remembered for this folder and spec (rememberedWorkspace() below).
export function initialWorkspace(worktree, remembered = null) {
const original = { id: "f0", path: worktree, name: defaultName(worktree), description: "", original: true };
if (remembered && remembered.original) {
if (remembered.original.name) original.name = remembered.original.name;
if (remembered.original.description) original.description = remembered.original.description;
}
const added = ((remembered && remembered.folders) || []).map((f, i) => ({
id: "f" + (i + 1),
path: f.path,
name: f.name,
description: f.description || "",
...(f.nested ? { nested: true } : {}),
}));
return { version: 0, folders: [original, ...added], missing: [], changes: [], remote: "" };
}
/* ------------------------------------------------ remembered workspaces */
// The folder list outlives the console session: one file for the person,
// beside looks.json, keyed by the folder a session runs in and then by spec.
// Never under specs/: the paths are this machine's, and the server never
// writes into a project.
//
// { "projects": { "<folded worktree>": {
// "path": "<worktree>",
// "project": { original, folders, at }, // no spec picked
// "specs": { "specs/<name>": { original, folders, at } } } } }
//
// `original` holds the first folder's name and description only (its path is
// always the session's own); `folders` the added ones as { path, name,
// description, nested? }. Two writers, the server on every change and
// `console.mjs forget`, each a read-modify-write of one key.
export const WORKSPACES_FILE = path.join(HOME_DIR, "workspaces.json");
export const foldKey = (p) => {
const resolved = path.resolve(String(p || ""));
return process.platform === "win32" || process.platform === "darwin" ? resolved.toLowerCase() : resolved;
};
// `specs/<name>` with forward slashes and no trailing slash, or "" for none.
export function specKey(specDir) {
return String(specDir || "")
.trim()
.replace(/\\/g, "/")
.replace(/^\.\//, "")
.replace(/\/+$/, "");
}
function readStore() {
const saved = readJson(WORKSPACES_FILE, null);
return saved && typeof saved.projects === "object" && saved.projects ? saved : { projects: {} };
}
/**
* What was remembered for this folder and spec: `{ entry, from }`, where
* `from` is "spec" when the spec has its own list, "project" when it falls
* back to the project's (a spec's list starts as a copy of it), and null
* when nothing was ever saved.
*/
export function rememberedWorkspace(worktree, specDir) {
const project = readStore().projects[foldKey(worktree)];
if (!project) return { entry: null, from: null };
const spec = specKey(specDir);
if (spec && project.specs && project.specs[spec]) return { entry: project.specs[spec], from: "spec" };
return project.project ? { entry: project.project, from: "project" } : { entry: null, from: null };
}
// The workspace's folders as the store keeps them.
export function rememberable(ws) {
const folders = (ws && ws.folders) || [];
const first = folders.find((f) => f.original) || {};
return {
original: { name: first.name || "", description: first.description || "" },
folders: folders
.filter((f) => !f.original)
.map((f) => ({ path: f.path, name: f.name, description: f.description || "", ...(f.nested ? { nested: true } : {}) })),
at: nowIso(),
};
}
// Every server and `console.mjs forget` writes the one file, so each
// read-modify-write holds this lock beside it.
const WORKSPACES_LOCK = "workspaces.json.lock";
// Save the list for this folder and spec ("" for the project's own).
export function rememberWorkspace(worktree, specDir, ws) {
ensureDir(path.dirname(WORKSPACES_FILE));
withStateLock(path.dirname(WORKSPACES_FILE), () => saveRemembered(worktree, specDir, ws), WORKSPACES_LOCK);
}
function saveRemembered(worktree, specDir, ws) {
const store = readStore();
const key = foldKey(worktree);
const project = store.projects[key] || { path: path.resolve(worktree) };
const spec = specKey(specDir);
if (spec) project.specs = { ...(project.specs || {}), [spec]: rememberable(ws) };
else project.project = rememberable(ws);
store.projects[key] = project;
writeJsonAtomic(WORKSPACES_FILE, store);
}
// Drop one spec's list (Finalize, once the spec is archived). True when there was one.
export function forgetWorkspace(worktree, specDir) {
const spec = specKey(specDir);
if (!spec || !fs.existsSync(WORKSPACES_FILE)) return false;
return withStateLock(path.dirname(WORKSPACES_FILE), () => dropRemembered(worktree, spec), WORKSPACES_LOCK);
}
function dropRemembered(worktree, spec) {
const store = readStore();
const project = store.projects[foldKey(worktree)];
if (!spec || !project || !project.specs || !project.specs[spec]) return false;
delete project.specs[spec];
writeJsonAtomic(WORKSPACES_FILE, store);
return true;
}
// Single-writer rule: only the server may call this (server.mjs, through
// serverWorkspace() below).
export function writeWorkspace(dir, ws) {
return writeJsonAtomic(path.join(dir, WORKSPACE_FILE), ws);
}
// What `open` hands the agent: names, paths and descriptions, nothing
// internal. `missing` names the folders that are gone, by their @name.
export function workspaceForAgent(ws) {
const all = (ws && ws.folders) || [];
const folders = all.map((f) => {
const out = { name: f.name, path: f.path };
if (f.description) out.description = f.description;
if (f.original) out.original = true;
return out;
});
const missing = ((ws && ws.missing) || []).map((id) => (all.find((f) => f.id === id) || {}).name).filter(Boolean);
return missing.length ? { folders, missing } : { folders };
}
/* ---------------------------------------------------- the workspace cursor */
export const WORKSPACE_CURSOR_FILE = "workspace-cursor.json";
export function readWorkspaceCursor(dir) {
const saved = readJson(path.join(dir, WORKSPACE_CURSOR_FILE), { version: 0 });
const n = Number(saved && saved.version);
return Number.isInteger(n) && n > 0 ? n : 0;
}
// Never backwards, like writeCursor(): a killed `wait` may hand a change over
// twice, but never skips one.
export function writeWorkspaceCursor(dir, version) {
writeJsonAtomic(path.join(dir, WORKSPACE_CURSOR_FILE), { version: Math.max(readWorkspaceCursor(dir), version) });
}
// The workspace changes the agent has not been handed yet.
export function pendingWorkspaceChanges(dir) {
const cursor = readWorkspaceCursor(dir);
return (readWorkspace(dir)?.changes || []).filter((c) => c.version > cursor);
}
/* ------------------------------------------------- the server's workspace */
/**
* The workspace as the server keeps it: the cached read, every change the
* page makes through the /workspace routes, the scope the dashboard picker
* sets, and the missing-folder check. workspace.json has one writer, the
* server; ledger.ndjson has one, console.mjs. Both are re-read only when
* their file has moved.
*
* `ctx` is what this reads from the server: `dir` and `project` (fixed),
* `worktree()` (the session's folder, null while unknown), `state()` (the
* state as last read), `ledger()` (the ledger's entries) and `pushState()`.
*/
export function serverWorkspace(ctx) {
const { dir, project } = ctx;
const WORKSPACE_PATH = path.join(dir, WORKSPACE_FILE);
const FOLD_CASE = process.platform === "win32" || process.platform === "darwin";
const foldPath = (p) => (FOLD_CASE ? p.toLowerCase() : p);
let workspaceSeen = { stamp: null, ws: null };
// The folder the session runs in: the state's own once it is written, else
// the one `open` passed on the command line. Null while neither is known.
const sessionWorktree = ctx.worktree;
// The session's workspace, created with just the original folder when absent.
function workspaceNow() {
const stamp = fileStamp(WORKSPACE_PATH);
if (stamp && stamp === workspaceSeen.stamp) return workspaceSeen.ws;
const ws = (stamp && readWorkspace(dir)) || null;
if (ws) {
workspaceSeen = { stamp, ws };
return ws;
}
const root = sessionWorktree();
const scope = specKey(ctx.state()?.specDir);
const remembered = root ? rememberedWorkspace(root, scope).entry : null;
const fresh = { ...initialWorkspace(root || project, remembered), scope, remote: remoteWarning().remote || "" };
// There but unreadable for now (a scanner's lock): never written over, and
// never cached, so the next call reads it again.
if (stamp) return workspaceSeen.ws || fresh;
// Nor saved while the session's folder is unknown: the project is only a
// guess (the main checkout, for a linked worktree), and the file, once
// written, is what every later read trusts.
if (!root) return fresh;
try {
saveWorkspace(fresh);
} catch {}
return fresh;
}
function saveWorkspace(ws) {
writeWorkspace(dir, ws);
workspaceSeen = { stamp: fileStamp(WORKSPACE_PATH), ws };
}
// One change: a new version, an entry in the change log the agent is handed,
// the file, and every open page.
function bumpWorkspace(ws, change, { remember = true } = {}) {
ws.version = (ws.version || 0) + 1;
ws.changes = [...(ws.changes || []), { ...change, version: ws.version }];
saveWorkspace(ws);
// Remembered for the next console session too. A folder gone missing or
// found again is not a change of mind, so it is not saved.
if (remember) rememberNow(ws);
ctx.pushState();
}
function rememberNow(ws) {
const root = sessionWorktree();
if (!root) return;
try {
rememberWorkspace(root, ws.scope || "", ws);
} catch {}
}
/**
* Point the workspace at another spec ("" for the project's own list) and
* swap in what was remembered there, logging each difference as a change so
* the agent's cursor stays truthful. A spec with nothing saved starts from
* the project's list (`seed: "project"`, the dashboard picker) or keeps the
* list it has and saves it as the spec's (`seed: "current"`, a spec created
* mid-run). Folders keep their ids when their path stays.
*/
function setScope(ws, spec, seed = "project") {
const root = sessionWorktree();
const next = specKey(spec);
if (!root || (ws.scope || "") === next) return false;
const found = rememberedWorkspace(root, next);
ws.scope = next;
if (next && found.from !== "spec" && seed === "current") {
saveWorkspace(ws);
rememberNow(ws);
ctx.pushState();
return true;
}
const want = initialWorkspace(root, found.entry).folders;
const byPath = new Map(ws.folders.map((f) => [foldPath(path.resolve(f.path)), f]));
const kept = new Set();
const folders = [];
const changes = [];
for (const w of want) {
const have = w.original ? ws.folders.find((f) => f.original) : byPath.get(foldPath(path.resolve(w.path)));
if (!have) {
folders.push({ ...w, id: "pending" });
changes.push({ kind: "added", name: w.name, path: w.path, description: w.description });
continue;
}
kept.add(have);
if (have.name !== w.name) changes.push({ kind: "renamed", from: have.name, name: w.name, path: have.path });
if ((have.description || "") !== (w.description || "")) {
changes.push({ kind: "described", name: w.name, path: have.path, description: w.description || "" });
}
folders.push({ ...have, name: w.name, description: w.description || "" });
}
for (const f of ws.folders) {
if (!kept.has(f)) changes.unshift({ kind: "removed", name: f.name, path: f.path });
}
ws.folders = folders.filter((f) => f.id !== "pending");
for (const f of folders.filter((f) => f.id === "pending")) ws.folders.push({ ...f, id: nextFolderId(ws) });
ws.missing = (ws.missing || []).filter((id) => ws.folders.some((f) => f.id === id));
if (!changes.length) {
saveWorkspace(ws);
ctx.pushState();
}
for (const c of changes) bumpWorkspace(ws, c, { remember: false });
checkFolders(ws);
return true;
}
// A spec posted mid-run (Pathfinder or Plan making its folder, a skill that
// learns its spec late) takes the workspace with it.
function followSpecDir(state) {
const spec = specKey(state && state.specDir);
if (!spec || !fileStamp(WORKSPACE_PATH)) return;
const ws = workspaceNow();
if ((ws.scope || "") !== spec) setScope(ws, spec, "current");
}
function isFolder(p) {
try {
return fs.statSync(p).isDirectory();
} catch {
return false;
}
}
// A folder deleted on disk is marked missing, and unmarked when it comes back.
function checkFolders(ws) {
ws.missing = ws.missing || [];
for (const f of ws.folders) {
const there = isFolder(f.path);
const marked = ws.missing.includes(f.id);
if (!there && !marked) {
ws.missing = [...ws.missing, f.id];
bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path }, { remember: false });
} else if (there && marked) {
ws.missing = ws.missing.filter((id) => id !== f.id);
bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path }, { remember: false });
}
}
}
// What the agent reported it could not read during the current skill run:
// folder-issue entries after the last launch, the latest per folder name.
function folderIssues(entries) {
let from = 0;
entries.forEach((e, i) => e.kind === "launch" && (from = i + 1));
const latest = new Map();
for (const e of entries.slice(from)) {
if (e.kind !== "folder-issue") continue;
latest.set(e.name, { name: e.name, reason: e.reason, ...(e.hint ? { hint: e.hint } : {}) });
}
return [...latest.values()];
}
function workspaceView() {
const { folders, missing, remote, scope } = workspaceNow();
return { folders, missing: missing || [], remote: remote || "", scope: scope || "", issues: folderIssues(ctx.ledger()) };
}
// Whether child sits strictly under parent.
function within(parent, child) {
const rel = path.relative(foldPath(parent), foldPath(child));
return rel !== "" && rel !== ".." && !rel.startsWith(".." + path.sep) && !path.isAbsolute(rel);
}
const cleanDescription = (d) => (typeof d === "string" ? d.trim().slice(0, 200) : "");
function nextFolderId(ws) {
const ns = ws.folders.map((f) => Number.parseInt(String(f.id).slice(1), 10)).filter(Number.isInteger);
return "f" + (Math.max(-1, ...ns) + 1);
}
// Each route below answers with [status, body]; validation always comes
// before any change, so a refusal leaves the file as it was.
function addFolder(ws, body) {
const raw = typeof body.path === "string" ? body.path.trim().replace(/^(["'])(.*)\1$/, "$2").trim() : "";
const input = raw.replace(/^~(?=$|[\\/])/, () => os.homedir());
const resolved = raw ? path.resolve(sessionWorktree() || project, input) : "";
if (!resolved || !isFolder(resolved)) return [400, { reason: "not-a-folder" }];
const same = ws.folders.find((f) => foldPath(path.resolve(f.path)) === foldPath(resolved));
if (same) return [400, { reason: "duplicate", name: same.name }];
const nested = ws.folders.some((f) => within(f.path, resolved));
const name = typeof body.name === "string" && body.name ? body.name : defaultName(resolved);
if (nameProblem(name)) return [400, { reason: "bad-name" }];
const taken = new Set(ws.folders.map((f) => f.name));
if (taken.has(name)) return [400, { reason: "name-taken", suggest: freeName(name, taken) }];
const entry = { id: nextFolderId(ws), path: resolved, name, description: cleanDescription(body.description), nested };
ws.folders = [...ws.folders, entry];
bumpWorkspace(ws, { kind: "added", name, path: resolved, description: entry.description });
return [200, entry];
}
function editFolder(ws, body) {
const entry = ws.folders.find((f) => f.id === body.id);
if (!entry) return [404, { reason: "unknown" }];
const rename = typeof body.name === "string" && body.name !== entry.name;
if (rename) {
if (nameProblem(body.name)) return [400, { reason: "bad-name" }];
const taken = new Set(ws.folders.filter((f) => f !== entry).map((f) => f.name));
if (taken.has(body.name)) return [400, { reason: "name-taken", suggest: freeName(body.name, taken) }];
}
const description = typeof body.description === "string" ? cleanDescription(body.description) : entry.description;
if (rename) {
const from = entry.name;
entry.name = body.name;
bumpWorkspace(ws, { kind: "renamed", from, name: entry.name, path: entry.path });
}
if (description !== entry.description) {
entry.description = description;
bumpWorkspace(ws, { kind: "described", name: entry.name, path: entry.path, description });
}
return [200, entry];
}
function removeFolder(ws, body) {
const entry = ws.folders.find((f) => f.id === body.id);
if (entry && entry.original) return [400, { reason: "original" }];
if (!entry) return [404, { reason: "unknown" }];
ws.folders = ws.folders.filter((f) => f !== entry);
ws.missing = (ws.missing || []).filter((id) => id !== entry.id);
bumpWorkspace(ws, { kind: "removed", name: entry.name, path: entry.path });
return [200, { ok: true }];
}
// Where the picker opens: beside the last folder added, else the original.
function pickerStart(ws) {
const added = ws.folders.filter((f) => !f.original);
return added.length ? path.dirname(added[added.length - 1].path) : ws.folders[0]?.path || sessionWorktree() || project;
}
// One picker at a time. Spawned, never spawnSync: the dialog can sit open for
// minutes, and every poll, chat message and `wait` health check has to keep
// being answered meanwhile.
let pickerBusy = false;
// Only ever answers with a path, as [status, body]: the page then adds it
// through /workspace/add.
function browse() {
const ws = workspaceNow();
if (ws.remote) return Promise.resolve([404, { reason: "no-picker" }]);
if (pickerBusy) return Promise.resolve([409, { reason: "busy" }]);
// Tests only: stands in for the person, so no dialog ever opens.
const echo = process.env.PLAN2CODE_PICKER_ECHO;
if (echo) return Promise.resolve([200, echo === "-" ? { cancelled: true } : { path: echo }]);
const start = pickerStart(ws);
if (!pickerCommand(start, WORKSPACE_PICKER_PROMPT)) return Promise.resolve([404, { reason: "no-picker" }]);
pickerBusy = true;
return pickFolder(start, WORKSPACE_PICKER_PROMPT)
.then((picked) => (picked.error ? [500, { reason: "picker-failed" }] : [200, picked]))
.catch(() => [500, { reason: "picker-failed" }])
.finally(() => {
pickerBusy = false;
});
}
function bootWorkspace() {
// Nothing to check yet: the first read once the state is written makes it.
if (!sessionWorktree() && !fileStamp(WORKSPACE_PATH)) return;
const ws = workspaceNow();
const remote = remoteWarning().remote || "";
if ((ws.remote || "") !== remote) {
ws.remote = remote;
saveWorkspace(ws);
}
checkFolders(ws);
followSpecDir(ctx.state());
}
return {
workspaceNow,
workspaceView,
setScope,
followSpecDir,
checkFolders,
addFolder,
editFolder,
removeFolder,
browse,
bootWorkspace,
// The stamp of the read the cache holds, for the frame's `have` key.
stamp: () => workspaceSeen.stamp,
};
}