mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 20:45:33 -08:00
Add the web console Notepad and shared skill tables, release v2.10.0
AI Assisted
This commit is contained in:
1 parent
124beb46db
commit
f8b54ef708
59 files changed
+12549
-321
No files matched your search
@@ -4,6 +4,7 @@ import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { HERE } from "./files.mjs";
|
||||
import { WORKFLOWS, isBuild } from "./public/skills.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.
|
||||
@@ -14,6 +15,25 @@ export function useCli(cli) {
|
||||
|
||||
/* ----------------------------------------------------------------- help */
|
||||
|
||||
// The usage's workflow list, from skills.js: wrapped at the usage's width,
|
||||
// continuation lines indented under the first name.
|
||||
function workflowLines(width = 78) {
|
||||
const lead = " workflows: ";
|
||||
const pad = " ".repeat(lead.length);
|
||||
const lines = [];
|
||||
let line = "";
|
||||
WORKFLOWS.forEach((w, i) => {
|
||||
const piece = i < WORKFLOWS.length - 1 ? `${w} ·` : w;
|
||||
const start = lines.length ? pad : lead;
|
||||
if (line && (start + line + " " + piece).length > width) {
|
||||
lines.push(start + line);
|
||||
line = piece;
|
||||
} else line = line ? `${line} ${piece}` : piece;
|
||||
});
|
||||
lines.push((lines.length ? pad : lead) + line);
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export function cmdHelp() {
|
||||
const topic = args._[0];
|
||||
if (topic !== undefined) return helpTopic(String(topic));
|
||||
@@ -103,9 +123,7 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
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
|
||||
${workflowLines()}
|
||||
|
||||
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
|
||||
@@ -113,7 +131,7 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
|
||||
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
|
||||
them. Build sessions (${WORKFLOWS.filter(isBuild).join(", ")}) also read
|
||||
building.md.
|
||||
`);
|
||||
}
|
||||
|
||||
@@ -48,6 +48,8 @@ import {
|
||||
writeWorkspaceCursor,
|
||||
} from "./workspace.mjs";
|
||||
import { readPrHosts, resetSubagentCursor } from "./settings.mjs";
|
||||
import { WORKFLOWS, isWorkflow } from "./public/skills.js";
|
||||
import { startsClean } from "./public/hops.js";
|
||||
import { snapshot } from "./git-repo.mjs";
|
||||
import { handoffsDir, listHandoffs, removeHandoffs, staleHandoffs } from "./handoffs.mjs";
|
||||
import {
|
||||
@@ -95,6 +97,13 @@ function leavePointer() {
|
||||
|
||||
export async function cmdOpen() {
|
||||
trace("open: start");
|
||||
// A workflow the console does not know is refused first, before the pointer,
|
||||
// the reap or any session folder: a fresh open would otherwise make a
|
||||
// session under a name no page or skill can show, and a resume would write
|
||||
// that name over a good one. No --workflow at all is still fine (FR-5).
|
||||
if (args.workflow !== undefined && !isWorkflow(args.workflow)) {
|
||||
die(`unknown workflow "${args.workflow}"; one of: ${WORKFLOWS.join(", ")}`, 2);
|
||||
}
|
||||
leavePointer();
|
||||
const { project, worktree, branch } = repoRoots();
|
||||
reapHandles(project);
|
||||
@@ -124,22 +133,11 @@ export async function cmdOpen() {
|
||||
// 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");
|
||||
// A hop starts the new skill on a clean page, by the rule in
|
||||
// public/hops.js (the page applies the same one). The staged draft goes
|
||||
// too, since its item ids belonged to the old questions, and so does the
|
||||
// last run's state.git, since switchWorkflow() starts from a blank state.
|
||||
const hop = startsClean(state.workflow, args.workflow);
|
||||
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 --
|
||||
|
||||
@@ -10,6 +10,7 @@ import { isOpen } from "./patches.mjs";
|
||||
import { pendingChatCount } from "./inbox.mjs";
|
||||
import { forgetWorkspace, specKey } from "./workspace.mjs";
|
||||
import { newHandoff, removeHandoff } from "./handoffs.mjs";
|
||||
import { WORKFLOWS, isWorkflow } from "./public/skills.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.
|
||||
@@ -153,6 +154,9 @@ 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);
|
||||
// newHandoff() takes any lowercase name; a handoff is only useful to a
|
||||
// workflow the console can launch, so the name must be one it knows (FR-5).
|
||||
if (!isWorkflow(args.workflow)) die(`unknown workflow "${args.workflow}"; one of: ${WORKFLOWS.join(", ")}`, 2);
|
||||
if ("from-stop" in args && args["from-stop"] !== true) die("--from-stop takes no value", 2);
|
||||
const { worktree, project } = repoRoots();
|
||||
try {
|
||||
|
||||
@@ -56,7 +56,7 @@ The same closer you are about to print in the terminal, as data:
|
||||
| `review` | optional | A finished `quick-task` only: `true` or `{ "label": "..." }` puts a **Review it now** button on the finished screen (`notes/quick-task.md`, `building-review.md`). `implement` offers the review on its sign-off card instead — before approval, where it can still change the outcome. |
|
||||
|
||||
**Write the bare command.** Every Plan2Code skill has a console — the
|
||||
dashboard and all twelve skills behind it — so for any of them the page
|
||||
dashboard and every skill behind it — so for any of them the page
|
||||
appends ` --web` to what it shows and copies, so someone who worked here
|
||||
lands back here instead of being asked the interface question as though
|
||||
they were new. Every one of those skills takes that flag in its argument as
|
||||
|
||||
@@ -86,20 +86,28 @@ export function ensureDir(dir) {
|
||||
// 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);
|
||||
writeTextAtomic(file, body);
|
||||
return body;
|
||||
}
|
||||
|
||||
// The same write for plain text, as UTF-8 (a Buffer is written as is): a temp
|
||||
// file beside the target, fsync, then a rename, retried while Windows still
|
||||
// holds the old file.
|
||||
export function writeTextAtomic(file, text) {
|
||||
const tmp = file + "." + process.pid + ".tmp";
|
||||
let lastErr;
|
||||
for (let attempt = 0; attempt < 4; attempt++) {
|
||||
try {
|
||||
const fd = fs.openSync(tmp, "w");
|
||||
try {
|
||||
fs.writeFileSync(fd, body);
|
||||
fs.writeFileSync(fd, text, "utf8");
|
||||
fs.fsyncSync(fd);
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
fs.renameSync(tmp, file);
|
||||
return body;
|
||||
return;
|
||||
} catch (err) {
|
||||
lastErr = err;
|
||||
if (err.code !== "EPERM" && err.code !== "EBUSY" && err.code !== "EACCES") break;
|
||||
@@ -124,6 +132,31 @@ export function fileStamp(file) {
|
||||
}
|
||||
}
|
||||
|
||||
// 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. Cleanup ages
|
||||
// sessions, strays, completed specs and notepads by it.
|
||||
export 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;
|
||||
}
|
||||
|
||||
export function readJson(file, fallback = null) {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(file, "utf8"));
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
// Plan2Code Web Console - the notepad store.
|
||||
//
|
||||
// One notepad per folder Plan2Code runs in (the session's worktree, else its
|
||||
// project), outside every repo and every session:
|
||||
//
|
||||
// ~/.plan2code/notepads/<folder-name>-<12 hex>/
|
||||
// meta.json { v: 1, folder, created }, written once
|
||||
// note.md the text, UTF-8, written atomically
|
||||
// images/<uuid>.jpg a picture, JPEG from the page
|
||||
// images/<uuid>.thumb.jpg its thumbnail, when the page sent one
|
||||
//
|
||||
// This module is the only code that names, reads, writes, lists and removes
|
||||
// them. The page reaches it through the /notepad routes; the agent CLI never
|
||||
// imports it, so nothing in a notepad can reach the agent. Reading never
|
||||
// creates or touches a file, so only a person's own edits age a notepad.
|
||||
// PLAN2CODE_NOTEPADS_DIR moves the folder, for tests.
|
||||
//
|
||||
// Node built-ins only. No build step.
|
||||
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { ensureDir, newestMtime, nowIso, readJson, withStateLock, writeJsonAtomic, writeTextAtomic } from "./files.mjs";
|
||||
import { foldKey } from "./workspace.mjs";
|
||||
|
||||
// Read at call time, so a test that sets the variable after import sees it.
|
||||
export function notepadsDir() {
|
||||
return process.env.PLAN2CODE_NOTEPADS_DIR || path.join(os.homedir(), ".plan2code", "notepads");
|
||||
}
|
||||
|
||||
export const NOTE_MAX_BYTES = 1024 * 1024;
|
||||
export const NOTEPAD_MAX_IMAGES = 200;
|
||||
export const IMAGE_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
||||
export const NOTEPAD_KEY_RE = /^[a-z0-9-]{1,40}-[0-9a-f]{12}$/;
|
||||
|
||||
// A refusal the routes turn into `{ error: code }` with this status.
|
||||
export class NotepadError extends Error {
|
||||
constructor(code, status) {
|
||||
super(code);
|
||||
this.code = code;
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ names */
|
||||
|
||||
// `<folder-name>-<first 12 hex of sha256(foldKey(folder))>`: recognisable in a
|
||||
// file browser, safe on every OS, and one notepad per folder however its case
|
||||
// is typed where the file system ignores case.
|
||||
export function notepadKey(folder) {
|
||||
const slug =
|
||||
path
|
||||
.basename(path.resolve(String(folder || "")))
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 40)
|
||||
.replace(/-+$/, "") || "folder";
|
||||
const hash = crypto.createHash("sha256").update(foldKey(folder)).digest("hex").slice(0, 12);
|
||||
return slug + "-" + hash;
|
||||
}
|
||||
|
||||
export function notepadFolder(folder) {
|
||||
return path.join(notepadsDir(), notepadKey(folder));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ write */
|
||||
|
||||
// Every write goes through here: the folder, its images/ and meta.json come
|
||||
// into being on the first one, and each runs under the notepad's own lock so
|
||||
// two pages on one folder never interleave. Nothing that only reads calls it.
|
||||
function withNotepad(folder, fn) {
|
||||
const dir = notepadFolder(folder);
|
||||
ensureDir(path.join(dir, "images"));
|
||||
const meta = path.join(dir, "meta.json");
|
||||
if (!fs.existsSync(meta)) writeJsonAtomic(meta, { v: 1, folder: path.resolve(String(folder)), created: nowIso() });
|
||||
return withStateLock(dir, () => fn(dir), "notepad.lock");
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------- read */
|
||||
|
||||
const fullImage = (name) => name.endsWith(".jpg") && !name.endsWith(".thumb.jpg") && IMAGE_ID_RE.test(name.slice(0, -4));
|
||||
|
||||
function mtimeOf(file) {
|
||||
try {
|
||||
return fs.statSync(file).mtimeMs;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// The full images' ids, oldest first (an image is never rewritten after it is
|
||||
// added, so its mtime is when it arrived).
|
||||
function imageIds(dir) {
|
||||
let names;
|
||||
try {
|
||||
names = fs.readdirSync(path.join(dir, "images"));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return names
|
||||
.filter(fullImage)
|
||||
.map((name) => ({ id: name.slice(0, -4), at: mtimeOf(path.join(dir, "images", name)) ?? 0 }))
|
||||
.sort((a, b) => a.at - b.at || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
|
||||
.map((e) => e.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the page shows: `{ text, savedAt, images: [{ id, url, thumb }] }`.
|
||||
* Never creates or writes anything; a folder with no notepad yet reads empty.
|
||||
*/
|
||||
export function readNotepad(folder) {
|
||||
const dir = notepadFolder(folder);
|
||||
if (!fs.existsSync(dir)) return { text: "", savedAt: null, images: [] };
|
||||
const note = path.join(dir, "note.md");
|
||||
let text = "";
|
||||
try {
|
||||
text = fs.readFileSync(note, "utf8");
|
||||
} catch {}
|
||||
const at = mtimeOf(note);
|
||||
const images = imageIds(dir).map((id) => ({
|
||||
id,
|
||||
url: "/notepad/images/" + id + ".jpg",
|
||||
thumb: fs.existsSync(path.join(dir, "images", id + ".thumb.jpg")) ? "/notepad/images/" + id + ".thumb.jpg" : null,
|
||||
}));
|
||||
return { text, savedAt: at === null ? null : new Date(at).toISOString(), images };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ change */
|
||||
|
||||
const isJpeg = (buf) => Buffer.isBuffer(buf) && buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff;
|
||||
const isImageId = (id) => typeof id === "string" && IMAGE_ID_RE.test(id);
|
||||
|
||||
/** Replace the note's text. Resolves to `{ savedAt }`, the written file's time. */
|
||||
export function saveNote(folder, text) {
|
||||
if (typeof text !== "string") throw new NotepadError("bad", 400);
|
||||
if (Buffer.byteLength(text, "utf8") > NOTE_MAX_BYTES) throw new NotepadError("too-long", 413);
|
||||
return withNotepad(folder, (dir) => {
|
||||
const note = path.join(dir, "note.md");
|
||||
writeTextAtomic(note, text);
|
||||
return { savedAt: new Date(fs.statSync(note).mtimeMs).toISOString() };
|
||||
});
|
||||
}
|
||||
|
||||
/** Add a picture (JPEG bytes). Resolves to `{ id, url }`. */
|
||||
export function addImage(folder, buf) {
|
||||
if (!isJpeg(buf)) throw new NotepadError("not-jpeg", 415);
|
||||
return withNotepad(folder, (dir) => {
|
||||
if (imageIds(dir).length >= NOTEPAD_MAX_IMAGES) throw new NotepadError("too-many", 409);
|
||||
const id = crypto.randomUUID();
|
||||
fs.writeFileSync(path.join(dir, "images", id + ".jpg"), buf, { flag: "wx" });
|
||||
return { id, url: "/notepad/images/" + id + ".jpg" };
|
||||
});
|
||||
}
|
||||
|
||||
/** Set (or replace) a picture's thumbnail. */
|
||||
export function addThumb(folder, id, buf) {
|
||||
if (!isImageId(id) || !fs.existsSync(path.join(notepadFolder(folder), "images", id + ".jpg"))) {
|
||||
throw new NotepadError("not-found", 404);
|
||||
}
|
||||
if (!isJpeg(buf)) throw new NotepadError("not-jpeg", 415);
|
||||
return withNotepad(folder, (dir) => {
|
||||
if (!fs.existsSync(path.join(dir, "images", id + ".jpg"))) throw new NotepadError("not-found", 404);
|
||||
// Replacing a file is the rename Windows can refuse for a moment, so it
|
||||
// takes the retrying write (a Buffer is written as is).
|
||||
writeTextAtomic(path.join(dir, "images", id + ".thumb.jpg"), buf);
|
||||
return {};
|
||||
});
|
||||
}
|
||||
|
||||
/** Remove a picture and its thumbnail. */
|
||||
export function removeImage(folder, id) {
|
||||
// Checked before the lock too, so a refused delete never brings an empty
|
||||
// notepad into being.
|
||||
if (!isImageId(id) || !fs.existsSync(path.join(notepadFolder(folder), "images", id + ".jpg"))) {
|
||||
throw new NotepadError("not-found", 404);
|
||||
}
|
||||
return withNotepad(folder, (dir) => {
|
||||
const full = path.join(dir, "images", id + ".jpg");
|
||||
if (!fs.existsSync(full)) throw new NotepadError("not-found", 404);
|
||||
fs.rmSync(full, { force: true });
|
||||
fs.rmSync(path.join(dir, "images", id + ".thumb.jpg"), { force: true });
|
||||
return {};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The file behind `/notepad/images/<id>[.thumb].jpg`, or null: the id must be
|
||||
* a UUID, the file a regular file (never a link) whose real path sits inside
|
||||
* the notepads folder's.
|
||||
*/
|
||||
export function imagePath(folder, id, thumb) {
|
||||
if (!isImageId(id)) return null;
|
||||
const file = path.join(notepadFolder(folder), "images", id + (thumb ? ".thumb.jpg" : ".jpg"));
|
||||
try {
|
||||
if (!fs.lstatSync(file).isFile()) return null;
|
||||
const [realFile, realRoot] = [fs.realpathSync(file), fs.realpathSync(notepadsDir())];
|
||||
// path.relative, not a prefix test, as readOverview() in sessions.mjs does.
|
||||
const rel = path.relative(realRoot, realFile);
|
||||
if (!rel || rel === ".." || rel.startsWith(".." + path.sep) || path.isAbsolute(rel)) return null;
|
||||
return realFile;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- cleanup */
|
||||
|
||||
/**
|
||||
* The notepads nobody has touched for `maxAgeMs`, judged by the newest file in
|
||||
* each, as `[{ key, folder, path }]`: only real folders directly under the
|
||||
* notepads folder whose name is a notepad key (never a link, never a file).
|
||||
* `folder` is the one `meta.json` names, or null when it is missing or
|
||||
* unreadable. User Preferences, Cleanup is the only caller: no sweep ever
|
||||
* removes a notepad.
|
||||
*/
|
||||
export function staleNotepads(now = Date.now(), maxAgeMs) {
|
||||
const root = notepadsDir();
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(root, { withFileTypes: true });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return entries
|
||||
.filter((e) => e.isDirectory() && NOTEPAD_KEY_RE.test(e.name))
|
||||
.map((e) => ({ key: e.name, path: path.join(root, e.name) }))
|
||||
.filter((e) => now - newestMtime(e.path) >= maxAgeMs)
|
||||
.map((e) => {
|
||||
const meta = readJson(path.join(e.path, "meta.json"));
|
||||
const folder = meta && typeof meta.folder === "string" && meta.folder ? meta.folder : null;
|
||||
return { key: e.key, folder, path: e.path };
|
||||
});
|
||||
}
|
||||
|
||||
/** Remove a whole notepad by its key: never a bad key, a link or anything outside the notepads folder. */
|
||||
export function removeNotepad(key) {
|
||||
if (typeof key !== "string" || !NOTEPAD_KEY_RE.test(key)) throw new NotepadError("bad", 400);
|
||||
const root = path.resolve(notepadsDir());
|
||||
const dir = path.resolve(root, key);
|
||||
// path.relative, not a prefix test, as imagePath() does.
|
||||
const rel = path.relative(root, dir);
|
||||
if (!rel || rel === ".." || rel.startsWith(".." + path.sep) || path.isAbsolute(rel)) throw new NotepadError("bad", 400);
|
||||
let st;
|
||||
try {
|
||||
st = fs.lstatSync(dir);
|
||||
} catch {
|
||||
throw new NotepadError("not-found", 404);
|
||||
}
|
||||
if (!st.isDirectory()) throw new NotepadError("bad", 400);
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
@@ -6,7 +6,7 @@ Revision is a short run of gates, and each maps onto a kind you already know:
|
||||
|
||||
| Step | On the page |
|
||||
| --- | --- |
|
||||
| 1, Change Analysis | A `recap` item, "Is this the change?", with the affected-areas table in `summary`. |
|
||||
| 1, Change Analysis | A `recap` item, "Is this the change?", with the affected-areas table in `summary`. Found a waiting `**Plan change:**` brief? Quote it at the top of that `summary` and post no open "what should change" card first. |
|
||||
| 2, Impact Assessment | The Revision Impact Summary as a doc (`id: "impact"`), and a `review` item "Approve the spec changes" pointing at it: verdicts `approve` ("Approve these spec changes"), `refine` ("Refine the plan") and `abort` ("Abort", `"danger": true`), `nothingYet`: "No spec file changes until you approve." |
|
||||
| 3 to 5 | Nothing to ask. Post `activity` while you edit, then the Revision Complete summary as a doc. |
|
||||
| 6, Cleanup | A `confirm` per rename or removal, the paths in `consequences`. |
|
||||
|
||||
@@ -5,7 +5,7 @@ import path from "node:path";
|
||||
|
||||
import { checkHelpers } from "./public/subagents.js";
|
||||
import { nowIso, SCHEMA } from "./files.mjs";
|
||||
import { TASK_LINE_RE } from "./scan.mjs";
|
||||
import { TASK_LINE_RE } from "./spec-files.mjs";
|
||||
|
||||
/* ----------------------------------------------------------- patch merge */
|
||||
|
||||
|
||||
+35
-11
@@ -75,26 +75,50 @@ public static class Plan2CodeFolderPicker {
|
||||
[DllImport("user32.dll")]
|
||||
private static extern int GetSystemMetrics(int index);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool IsWindowVisible(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr GetForegroundWindow();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern void SwitchToThisWindow(IntPtr hWnd, bool altTab);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern void keybd_event(byte vk, byte scan, uint flags, UIntPtr extra);
|
||||
|
||||
private const uint FOS_PICKFOLDERS = 0x20;
|
||||
private const uint FOS_FORCEFILESYSTEM = 0x40;
|
||||
private const uint FOS_PATHMUSTEXIST = 0x800;
|
||||
private const uint SIGDN_FILESYSPATH = 0x80058000;
|
||||
private const int ERROR_CANCELLED = unchecked((int)0x800704C7);
|
||||
|
||||
// Windows refuses SetForegroundWindow from a background process (this one is spawned
|
||||
// by the detached console server), so the dialog opened behind the browser. A tap of
|
||||
// Alt counts as input from this process and lifts the lock for the call after it. The
|
||||
// topmost flag below is ignored by this dialog (SetWindowPos succeeds, the bit stays
|
||||
// off), so taking the foreground is what puts it in front.
|
||||
private static void Raise(string title) {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
IntPtr hwnd = FindWindow(null, title);
|
||||
if (hwnd != IntPtr.Zero) {
|
||||
int w = Math.Min(1100, GetSystemMetrics(0) - 80);
|
||||
int h = Math.Min(750, GetSystemMetrics(1) - 80);
|
||||
int x = (GetSystemMetrics(0) - w) / 2 + 40;
|
||||
int y = (GetSystemMetrics(1) - h) / 2 + 40;
|
||||
SetWindowPos(hwnd, new IntPtr(-1), x, y, w, h, 0x40);
|
||||
SetForegroundWindow(hwnd);
|
||||
return;
|
||||
}
|
||||
IntPtr hwnd = IntPtr.Zero;
|
||||
for (int i = 0; i < 200; i++) {
|
||||
hwnd = FindWindow(null, title);
|
||||
if (hwnd != IntPtr.Zero && IsWindowVisible(hwnd)) break;
|
||||
hwnd = IntPtr.Zero;
|
||||
Thread.Sleep(50);
|
||||
}
|
||||
if (hwnd == IntPtr.Zero) return;
|
||||
int w = Math.Min(1100, GetSystemMetrics(0) - 80);
|
||||
int h = Math.Min(750, GetSystemMetrics(1) - 80);
|
||||
int x = (GetSystemMetrics(0) - w) / 2 + 40;
|
||||
int y = (GetSystemMetrics(1) - h) / 2 + 40;
|
||||
SetWindowPos(hwnd, new IntPtr(-1), x, y, w, h, 0x40);
|
||||
for (int i = 0; i < 20 && GetForegroundWindow() != hwnd; i++) {
|
||||
keybd_event(0x12, 0, 0, UIntPtr.Zero);
|
||||
keybd_event(0x12, 0, 2, UIntPtr.Zero);
|
||||
SetForegroundWindow(hwnd);
|
||||
SwitchToThisWindow(hwnd, true);
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
}
|
||||
|
||||
public static string Pick(IntPtr owner, string title, string start) {
|
||||
|
||||
@@ -416,43 +416,12 @@ export function resumeCommand({ workflow, specDir } = {}) {
|
||||
// Only a real relative specs/ path. Anything else would be run verbatim by
|
||||
// someone with no way to tell it was wrong.
|
||||
const dir = /^specs\/[a-z0-9][a-z0-9._-]*$/i.test(raw) ? raw : "";
|
||||
const withOverview = (cmd) => (dir ? `${cmd} ${dir}/overview.md` : cmd);
|
||||
switch (workflow) {
|
||||
case "dashboard":
|
||||
return "/plan2code";
|
||||
case "init":
|
||||
return "/plan2code-init";
|
||||
case "init-update":
|
||||
return "/plan2code-init-update";
|
||||
case "plan":
|
||||
return "/plan2code-1-plan";
|
||||
case "quick-task":
|
||||
return "/plan2code-quick-task";
|
||||
case "document":
|
||||
return withOverview("/plan2code-2-document");
|
||||
case "implement":
|
||||
return withOverview("/plan2code-3-implement");
|
||||
case "implement-review":
|
||||
return withOverview("/plan2code-3-implement-review");
|
||||
case "review":
|
||||
return "/plan2code-review";
|
||||
case "revise-plan":
|
||||
return withOverview("/plan2code-1b-revise-plan");
|
||||
case "finalize":
|
||||
return withOverview("/plan2code-4-finalize");
|
||||
case "handoff":
|
||||
return "/plan2code-handoff";
|
||||
case "git":
|
||||
return "/plan2code-git";
|
||||
case "changelog":
|
||||
return "/plan2code-changelog";
|
||||
case "xray":
|
||||
return "/plan2code-xray";
|
||||
case "diagnose":
|
||||
return "/plan2code-diagnose";
|
||||
default:
|
||||
return dir ? `/plan2code-0-pathfinder ${dir}/pathfinder` : "/plan2code-0-pathfinder";
|
||||
}
|
||||
// What follows the command is the entry's `resume` (skills.js). A workflow
|
||||
// the console does not know (an old session's) resumes as Pathfinder.
|
||||
const entry = skillFor(workflow) || skillFor("pathfinder");
|
||||
if (dir && entry.resume === "overview") return `${entry.command} ${dir}/overview.md`;
|
||||
if (dir && entry.resume === "folder") return `${entry.command} ${dir}/pathfinder`;
|
||||
return entry.command;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------ after a build is done */
|
||||
@@ -541,6 +510,7 @@ export const SKILL_CATALOG = SKILLS.filter((s) => s.card).map((s) => ({
|
||||
skill: s.skill,
|
||||
command: s.command,
|
||||
workflow: s.workflow,
|
||||
...(s.review ? { review: s.review } : {}),
|
||||
...s.card,
|
||||
}));
|
||||
|
||||
@@ -563,7 +533,20 @@ export function startPose(workflow) {
|
||||
|
||||
export function catalogEntry(skill) {
|
||||
const entry = skillByName(skill);
|
||||
return entry && entry.card ? SKILL_CATALOG.find((e) => e.skill === entry.skill) : null;
|
||||
if (!entry) return null;
|
||||
// A skill with no card of its own is launched from another's (Implement +
|
||||
// Review from Implement's Review box).
|
||||
const owner = entry.card ? entry : SKILLS.find((s) => s.review === entry.skill);
|
||||
return owner ? SKILL_CATALOG.find((e) => e.skill === owner.skill) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a card launches: the card itself, or, when it has a Review box and the
|
||||
* box is ticked, the review skill's entry under the card's title.
|
||||
*/
|
||||
export function launchVariant(entry, withReview) {
|
||||
const alt = withReview && entry.review ? skillByName(entry.review) : null;
|
||||
return alt ? { ...entry, skill: alt.skill, workflow: alt.workflow, command: alt.command, title: alt.name } : entry;
|
||||
}
|
||||
|
||||
/* ------------------------------------------- dashboard card availability */
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
adopt, banner, connect, fillSky, fitGrowBox, loadState, markSent, maybeWelcome, render, renderFooter,
|
||||
renderSidebar, renderWhere, save, startClock, startLooks, stagedPayload, syncWorkspaceScope,
|
||||
wakeHoldsChime, wireAsk, wireCards, wireChrome, wireCleanup, wireDashboard, wireDocs, wireEnding,
|
||||
wireHelp, wireLooks, wireWorkspace,
|
||||
wireHelp, wireLooks, wireNotepad, wireWorkspace,
|
||||
} from "./screens/core.js";
|
||||
import { sound } from "./sound.js";
|
||||
|
||||
@@ -49,6 +49,7 @@ wireLooks();
|
||||
wireCleanup();
|
||||
wireDocs();
|
||||
wireAsk();
|
||||
wireNotepad();
|
||||
wireChrome();
|
||||
startClock();
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
// Plan2Code Web Console - the hop rule.
|
||||
//
|
||||
// Which hops from one workflow to another start the new skill on a clean
|
||||
// page. One rule, called by both sides that act on it: the server
|
||||
// (cmd-open.mjs blanks the stored session and drops the staged draft) and the
|
||||
// page (screens/core.js drops what it kept for the last skill: the question
|
||||
// on screen, the open tab, anything staged against its item ids). No imports
|
||||
// and no DOM access: nothing runs at load.
|
||||
|
||||
// True when a hop from workflow `from` to workflow `to` starts clean:
|
||||
// - a launch from the dashboard menu gets a clean page, not the last
|
||||
// skill's questions and tabs under its own name;
|
||||
// - going back to the dashboard clears the last skill;
|
||||
// - 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 board.
|
||||
// A skill run inline from another (a quick task's review) never switches
|
||||
// workflow, so it keeps the page; nor does a resume into the same workflow.
|
||||
export function startsClean(from, to) {
|
||||
if (typeof from !== "string" || typeof to !== "string" || !from || !to || from === to) return false;
|
||||
return from === "dashboard" || to === "dashboard" || to === "git";
|
||||
}
|
||||
@@ -34,6 +34,7 @@
|
||||
<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="/screens/notepad.js" />
|
||||
<link rel="modulepreload" href="/net.js" />
|
||||
<link rel="modulepreload" href="/render.js" />
|
||||
<link rel="modulepreload" href="/palette.js" />
|
||||
@@ -51,6 +52,8 @@
|
||||
<link rel="modulepreload" href="/git-board-view.js" />
|
||||
<link rel="modulepreload" href="/pr-url.js" />
|
||||
<link rel="modulepreload" href="/vendor/marked.esm.js" />
|
||||
<link rel="modulepreload" href="/notepad.js" />
|
||||
<link rel="modulepreload" href="/vendor/overtype.esm.js" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="icon" type="image/png" sizes="192x192" href="/favicon.png" />
|
||||
</head>
|
||||
@@ -211,6 +214,16 @@
|
||||
<circle cx="12.4" cy="13" r="1.5" class="sa-node" />
|
||||
</svg>
|
||||
</button>
|
||||
<!-- Notepad: every screen, never hidden. The person's private notes for this
|
||||
folder; nothing in it reaches the agent. -->
|
||||
<button type="button" class="btn ghost small notepad-btn" id="btn-notepad" title="Notepad" aria-label="Notepad">
|
||||
<!-- A notepad: a page bound at the top by three rings, with three lines. -->
|
||||
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
||||
<rect class="np-page" x="3" y="2.5" width="10" height="12" rx="1.3" />
|
||||
<path class="np-ring" d="M5.5 1.2v2.6M8 1.2v2.6M10.5 1.2v2.6" />
|
||||
<path class="np-line" d="M5.5 7h5M5.5 9.5h5M5.5 12h3.2" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="views-group">
|
||||
<span class="views-arrow" aria-hidden="true">
|
||||
@@ -1160,6 +1173,42 @@
|
||||
right. See "Sending and what happens next".
|
||||
</li>
|
||||
</ul>
|
||||
<h4>Your notepad</h4>
|
||||
<p>
|
||||
The <strong>Notepad</strong> button, a page with three rings at the
|
||||
top, sits beside Stop session on every screen. It opens a notepad of
|
||||
your own for this folder, somewhere to jot things down as you go.
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
Text is styled as you type. Write Markdown, such as
|
||||
<code>**bold**</code> or <code># Heading</code>, and it shows that
|
||||
way at once.
|
||||
</li>
|
||||
<li>
|
||||
Images go in the strip under the text. Paste one, drop one on the
|
||||
notepad or press <strong>Add image</strong>. Click a picture to see
|
||||
it full screen: the arrow keys step through them and
|
||||
<kbd>Esc</kbd> closes it. The <strong>×</strong> on a picture asks
|
||||
before it deletes it.
|
||||
</li>
|
||||
<li>
|
||||
Everything saves as you go, one notepad per project folder. There is
|
||||
no Save button.
|
||||
</li>
|
||||
<li>
|
||||
It is private to this machine and never sent to Plan2Code. Nothing
|
||||
in it is shown to the agent.
|
||||
</li>
|
||||
<li>
|
||||
Two open pages on the same folder share one notepad. If both change
|
||||
it, the last save wins.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Cleanup</strong>, in User Preferences, offers to remove a
|
||||
notepad only after a month untouched. Nothing removes it on its own.
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- Tab 4: Your workspace -->
|
||||
@@ -1644,31 +1693,7 @@
|
||||
</p>
|
||||
<h4>The cards</h4>
|
||||
<p>They come in three groups.</p>
|
||||
<p><strong>First, the project</strong></p>
|
||||
<ul>
|
||||
<li><strong>Set up this project.</strong> Reads your project and writes AGENTS.md, the guide every later step works from.</li>
|
||||
<li><strong>Refresh AGENTS.md.</strong> Brings AGENTS.md and its notes up to date with what the project has learned lately.</li>
|
||||
</ul>
|
||||
<p><strong>The steps, in order</strong></p>
|
||||
<ul>
|
||||
<li><strong>Pathfinder.</strong> A foggy idea becomes a clear list of decisions, settled one question at a time.</li>
|
||||
<li><strong>Plan.</strong> Requirements, technical design and your approval: the shape of what gets built.</li>
|
||||
<li><strong>Revise the plan.</strong> Requirements changed mid-build? Adjust the plan without starting over.</li>
|
||||
<li><strong>Document.</strong> The plan becomes a checklist of small tasks, grouped into phases, that a developer can just do.</li>
|
||||
<li><strong>Implement.</strong> Builds the next phase, task by task, with a report and your sign-off at the end.</li>
|
||||
<li><strong>Implement + review.</strong> One phase built, then a careful review of the changes, then your sign-off. All in one run.</li>
|
||||
<li><strong>Finalize.</strong> Checks the work, writes the summary, files the specs away and suggests the commit message.</li>
|
||||
</ul>
|
||||
<p><strong>Useful any time</strong></p>
|
||||
<ul>
|
||||
<li><strong>Quick task.</strong> Too small for the full process? A quick plan, then it just builds it.</li>
|
||||
<li><strong>Review.</strong> A second opinion on the changes. Problems ranked, and you pick what gets fixed.</li>
|
||||
<li><strong>Handoff.</strong> Pack the current session into a document a fresh session can pick up cold.</li>
|
||||
<li><strong>Changelog.</strong> Checks the CHANGELOG version against the main branch and suggests entries for what is new.</li>
|
||||
<li><strong>Git.</strong> Branches, pull, push and commits on one board, asking before anything leaves your machine. See "The git board".</li>
|
||||
<li><strong>Codebase X-ray.</strong> Explains how and why an area of the code works, or finds the rough spots worth fixing.</li>
|
||||
<li><strong>Diagnose a bug.</strong> Finds a bug's cause and writes it up without fixing it, ready to hand to Quick Task or Plan.</li>
|
||||
</ul>
|
||||
<div class="help-cards"></div>
|
||||
<h4>Picking a spec</h4>
|
||||
<p>
|
||||
Once your project has specs, <strong>Pick up a spec, or start
|
||||
@@ -2530,6 +2555,37 @@
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- The Notepad: the person's own notes for this folder, autosaved under
|
||||
~/.plan2code/notepads/ by the /notepad routes. Never part of the
|
||||
session, so nothing in it reaches the agent. screens/notepad.js fills
|
||||
the editor on open. -->
|
||||
<dialog class="modal notepad" id="notepad-modal" aria-labelledby="notepad-title">
|
||||
<h2 id="notepad-title">Notepad</h2>
|
||||
<p class="modal-blurb">Private to this machine and this folder. Never sent to Plan2Code.</p>
|
||||
<div class="notepad-editor" id="notepad-editor"></div>
|
||||
<div class="notepad-images" id="notepad-images">
|
||||
<button type="button" class="btn small ghost notepad-add" id="notepad-add">Add image</button>
|
||||
<input type="file" accept="image/*" multiple id="notepad-file" hidden />
|
||||
<ul class="notepad-strip" id="notepad-strip" role="list" aria-label="Notepad images"></ul>
|
||||
</div>
|
||||
<div class="modal-actions notepad-actions">
|
||||
<p class="help notepad-status" id="notepad-status" aria-live="polite"></p>
|
||||
<button type="button" class="btn ghost" id="notepad-close">Close</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- The Notepad's full-screen picture preview, opened over the Notepad
|
||||
from a thumbnail by screens/notepad.js. -->
|
||||
<dialog class="modal notepad-preview" id="notepad-preview" aria-label="Image preview">
|
||||
<img class="notepad-preview-img" id="notepad-preview-img" alt="" />
|
||||
<button type="button" class="notepad-preview-step is-prev" id="notepad-preview-prev" aria-label="Previous image">‹</button>
|
||||
<button type="button" class="notepad-preview-step is-next" id="notepad-preview-next" aria-label="Next image">›</button>
|
||||
<div class="notepad-preview-bar">
|
||||
<p class="notepad-preview-count" id="notepad-preview-count" aria-live="polite"></p>
|
||||
<button type="button" class="btn small notepad-preview-close" id="notepad-preview-close">Close</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- The Workspace: the folder this session started in plus any added as
|
||||
context. The list is drawn by app.js from the frame's `workspace`;
|
||||
every change goes through the server's /workspace routes. -->
|
||||
|
||||
@@ -8,33 +8,24 @@
|
||||
|
||||
import { SKILLS, isMetered, isPhased } from "./skills.js";
|
||||
|
||||
// The one place the weights live (FR-12). Tune here.
|
||||
export const WEIGHTS = Object.freeze({
|
||||
// The weights (FR-12): the events that are not a skill's own launch live
|
||||
// here, and each skill's weight is its `weight` in skills.js. Tune there or here.
|
||||
const EVENT_WEIGHTS = {
|
||||
"pathfinder-chart": 2,
|
||||
// Scores 0: a Pathfinder question now counts through its answers (below).
|
||||
"pathfinder-question": 0,
|
||||
// Research reads sources and hands its findings back into the context, with
|
||||
// nobody answering anything, so each research question scores on its own.
|
||||
"pathfinder-research": 1,
|
||||
plan: 2,
|
||||
"revise-plan": 1,
|
||||
document: 2,
|
||||
"implement-phase": 2,
|
||||
"implement-review-phase": 3,
|
||||
review: 2,
|
||||
"quick-task": 1,
|
||||
init: 2,
|
||||
"init-update": 2,
|
||||
finalize: 1,
|
||||
handoff: 0,
|
||||
git: 1,
|
||||
// Scores 0 itself: Git's commits are tallied per run (COMMITS_PER_POINT).
|
||||
"git-commits": 0,
|
||||
"git-conflict": 1,
|
||||
changelog: 1,
|
||||
xray: 1,
|
||||
diagnose: 1,
|
||||
});
|
||||
};
|
||||
// A skill's fields as a table by workflow, leaving out the entries without one.
|
||||
const bySkill = (field) => Object.fromEntries(SKILLS.filter((s) => s[field] !== null).map((s) => [s.workflow, s[field]]));
|
||||
export const WEIGHTS = Object.freeze({ ...EVENT_WEIGHTS, ...bySkill("weight") });
|
||||
|
||||
// Workflows whose launch itself scores WEIGHTS[workflow]. Pathfinder,
|
||||
// implement and implement-review score only through the agent's `run`
|
||||
@@ -134,42 +125,19 @@ const WORKFLOW_NAMES = Object.freeze(Object.fromEntries(SKILLS.map((s) => [s.wor
|
||||
// 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");
|
||||
|
||||
// What each scoring event is called in the meter's list of contributions.
|
||||
const LAUNCH_LABELS = Object.freeze({
|
||||
plan: "Plan started",
|
||||
"revise-plan": "Revise plan started",
|
||||
document: "Document started",
|
||||
review: "Review started",
|
||||
"quick-task": "Quick task started",
|
||||
init: "Init started",
|
||||
"init-update": "Init update started",
|
||||
finalize: "Finalize started",
|
||||
git: "Git started",
|
||||
changelog: "Changelog started",
|
||||
xray: "X-ray started",
|
||||
diagnose: "Diagnose started",
|
||||
});
|
||||
const RUN_LABELS = Object.freeze({
|
||||
// What each scoring event is called in the meter's list of contributions: a
|
||||
// skill's launch and run labels are its `started` and `ran` in skills.js, and
|
||||
// the events that are not a skill's own are named here.
|
||||
export const LAUNCH_LABELS = Object.freeze(bySkill("started"));
|
||||
export const RUN_LABELS = Object.freeze({
|
||||
"pathfinder-chart": "Pathfinder map written",
|
||||
"pathfinder-question": "Pathfinder question settled",
|
||||
"pathfinder-research": "Pathfinder research done",
|
||||
plan: "Plan drafted",
|
||||
"revise-plan": "Plan revised",
|
||||
document: "Spec documented",
|
||||
"implement-phase": "Implement phase built",
|
||||
"implement-review-phase": "Implement + Review phase built",
|
||||
review: "Code review run",
|
||||
"quick-task": "Quick task built",
|
||||
init: "Init run",
|
||||
"init-update": "Init update run",
|
||||
finalize: "Finalize run",
|
||||
handoff: "Handoff written",
|
||||
git: "Git run",
|
||||
"git-commits": "Commits in Git",
|
||||
"git-conflict": "Git conflict help",
|
||||
changelog: "Changelog run",
|
||||
xray: "X-ray run",
|
||||
diagnose: "Diagnose run",
|
||||
...bySkill("ran"),
|
||||
});
|
||||
|
||||
// The unit a run names, from its ledger id ("L3:phase-2" -> "phase-2").
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
// Plan2Code Web Console - the Notepad's save rules, status words and error sentences.
|
||||
//
|
||||
// The source of truth for when the page saves the note, how it retries, what
|
||||
// the status line says and the sentence each server refusal becomes. The
|
||||
// Notepad screen only runs timers and requests on what these return. No DOM
|
||||
// access at module scope and no imports: the page and `node --test` both
|
||||
// import this file. The limits mirror notepads.mjs (a test keeps them equal),
|
||||
// copied rather than imported because the page cannot load server modules.
|
||||
|
||||
export const SAVE_DEBOUNCE_MS = 800;
|
||||
export const RETRY_STEPS_MS = Object.freeze([1000, 2000, 4000, 8000, 16000, 30000]);
|
||||
export const NOTE_MAX_BYTES = 1024 * 1024;
|
||||
export const NOTEPAD_MAX_IMAGES = 200;
|
||||
export const IMAGE_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
||||
|
||||
// The codes the /notepad routes send as `{ error: code }`.
|
||||
export const ERROR_CODES = Object.freeze(["bad", "too-long", "not-jpeg", "too-large", "too-many", "not-found"]);
|
||||
|
||||
// UTF-8 bytes, the unit the server's cap is in (a character count would let
|
||||
// non-ASCII text past the page's check and into a 413).
|
||||
export function noteBytes(text) {
|
||||
return new TextEncoder().encode(typeof text === "string" ? text : "").length;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ saving */
|
||||
|
||||
const STATUSES = Object.freeze(["idle", "pending", "saving", "saved", "failed", "too-long"]);
|
||||
|
||||
export const SAVE_START = Object.freeze({ status: "idle", attempt: 0 });
|
||||
|
||||
const known = (state) => !!state && typeof state === "object" && STATUSES.includes(state.status);
|
||||
const attemptOf = (state) => (Number.isInteger(state.attempt) && state.attempt > 0 ? state.attempt : 0);
|
||||
const stay = (state) => ({ state, timer: null });
|
||||
const to = (status, attempt, timer) => ({ state: { status, attempt }, timer });
|
||||
|
||||
/**
|
||||
* The save state after `event`, plus `timer`: the delay in ms the screen arms
|
||||
* before dispatching `due`, or null for no timer. Pure: never mutates `state`,
|
||||
* runs no clock and sends nothing.
|
||||
*/
|
||||
export function nextSave(state, event) {
|
||||
if (!known(state)) return stay(state);
|
||||
const type = event && typeof event === "object" ? event.type : event;
|
||||
const { status } = state;
|
||||
switch (type) {
|
||||
case "typed": {
|
||||
const bytes = event && typeof event.bytes === "number" ? event.bytes : 0;
|
||||
// Over the cap nothing is sent: the server would only refuse it.
|
||||
if (bytes > NOTE_MAX_BYTES) return to("too-long", 0, null);
|
||||
return to("pending", 0, SAVE_DEBOUNCE_MS);
|
||||
}
|
||||
case "due":
|
||||
if (status === "pending" || status === "failed") return to("saving", attemptOf(state), null);
|
||||
return stay(state);
|
||||
case "sent":
|
||||
return stay(state);
|
||||
case "ok":
|
||||
// A change typed while the request was out comes back as a fresh
|
||||
// `typed` from the screen, so `ok` can always land on saved.
|
||||
return to("saved", 0, null);
|
||||
case "error": {
|
||||
// Retrying a size the server refused would never succeed.
|
||||
if (event && event.code === "too-long") return to("too-long", 0, null);
|
||||
const attempt = attemptOf(state);
|
||||
return to("failed", attempt + 1, RETRY_STEPS_MS[Math.min(attempt, RETRY_STEPS_MS.length - 1)]);
|
||||
}
|
||||
case "retry":
|
||||
if (status === "failed") return to("saving", attemptOf(state), null);
|
||||
return stay(state);
|
||||
default:
|
||||
return stay(state);
|
||||
}
|
||||
}
|
||||
|
||||
// "1 MB", "512 KB", "300 bytes": the cap in words for the status line.
|
||||
function sizeWords(bytes) {
|
||||
const trim = (n) => String(Math.round(n * 10) / 10);
|
||||
if (bytes >= 1024 * 1024) return trim(bytes / (1024 * 1024)) + " MB";
|
||||
if (bytes >= 1024) return trim(bytes / 1024) + " KB";
|
||||
return bytes + " bytes";
|
||||
}
|
||||
|
||||
const STATUS_WORDS = Object.freeze({
|
||||
idle: "",
|
||||
pending: "Saving",
|
||||
saving: "Saving",
|
||||
saved: "Saved",
|
||||
failed: "Not saved (retrying)",
|
||||
"too-long": `Too long to save (over ${sizeWords(NOTE_MAX_BYTES)})`,
|
||||
});
|
||||
|
||||
const statusOf = (state) => (typeof state === "string" ? state : state && typeof state === "object" ? state.status : undefined);
|
||||
|
||||
// The status line's words for a state object or a bare status.
|
||||
export function saveStatus(state) {
|
||||
const status = statusOf(state);
|
||||
return Object.prototype.hasOwnProperty.call(STATUS_WORDS, status) ? STATUS_WORDS[status] : "";
|
||||
}
|
||||
|
||||
// True while text on screen may not be on disk yet: the page only asks
|
||||
// before closing then. A too-long note is not asked about, the status line
|
||||
// already says it cannot be saved.
|
||||
export function unsaved(state) {
|
||||
const status = statusOf(state);
|
||||
return status === "pending" || status === "saving" || status === "failed";
|
||||
}
|
||||
|
||||
// True while the editor holds text the stored note must not replace when the
|
||||
// notepad is opened again: anything unsaved, and a note too long to save,
|
||||
// which would otherwise lose everything typed since its last save.
|
||||
export function keepsText(state) {
|
||||
return unsaved(state) || statusOf(state) === "too-long";
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ errors */
|
||||
|
||||
const ERROR_SENTENCES = Object.freeze({
|
||||
bad: "Plan2Code could not read that request, so nothing was changed.",
|
||||
"too-long": `This note is too long to save. Notes can be up to ${sizeWords(NOTE_MAX_BYTES)}.`,
|
||||
"not-jpeg": "That picture could not be added. Try a PNG, JPEG or a screenshot.",
|
||||
"too-large": "That picture is too large to add. Try a smaller one.",
|
||||
"too-many": `This notepad already holds ${NOTEPAD_MAX_IMAGES} pictures, the most it can keep. Delete one to add another.`,
|
||||
"not-found": "That picture is no longer in this notepad.",
|
||||
});
|
||||
|
||||
const LOST_CONTACT = "Lost contact with Plan2Code. Your text is kept here and will be saved once it's back.";
|
||||
|
||||
// The status line when the note could not be read on first open: the editor
|
||||
// stays read-only, since anything typed would be saved over the real note.
|
||||
export const NOT_LOADED = "Could not read the note. Close the notepad and open it again.";
|
||||
|
||||
// One plain sentence for a server refusal; anything else (status 0, an
|
||||
// unknown code) is treated as a lost connection.
|
||||
export function errorSentence(code) {
|
||||
return typeof code === "string" && Object.prototype.hasOwnProperty.call(ERROR_SENTENCES, code) ? ERROR_SENTENCES[code] : LOST_CONTACT;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ editor */
|
||||
|
||||
// OverType's HTML without its inline style attributes, which the page's
|
||||
// policy refuses. A link's `anchor-name` (what OverType's link tooltip finds
|
||||
// the link by) moves to `data-anchor`; any other style attribute is dropped,
|
||||
// and the tooltip's own look comes from notepad.css instead. Typed text never
|
||||
// matches: OverType escapes the quotes in it.
|
||||
const STYLE_ATTR = / style="([^"]*)"/g;
|
||||
const ANCHOR_NAME = /^anchor-name: (--link-\d+)$/;
|
||||
|
||||
export function withoutStyleAttrs(html) {
|
||||
return html.replace(STYLE_ATTR, (_, css) => {
|
||||
const anchor = ANCHOR_NAME.exec(css);
|
||||
return anchor ? ` data-anchor="${anchor[1]}"` : "";
|
||||
});
|
||||
}
|
||||
|
||||
// OverType's HTML cut into its top-level elements (one per line, or one per
|
||||
// run of list items), as strings, so the page can tell which lines changed
|
||||
// without parsing the whole note into elements on every key. Tags are
|
||||
// counted, not parsed: OverType escapes `<` and `>` in text and attribute
|
||||
// values, so every `<` here starts a real tag. null when the HTML does not
|
||||
// end balanced, so the caller redraws everything instead.
|
||||
const TAG = /<(\/?)([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*?(\/?)>/g;
|
||||
const VOID_TAGS = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
|
||||
|
||||
export function topLevelParts(html) {
|
||||
const parts = [];
|
||||
let depth = 0;
|
||||
let start = 0;
|
||||
TAG.lastIndex = 0;
|
||||
for (let m; (m = TAG.exec(html)); ) {
|
||||
if (depth === 0 && m.index > start) return null;
|
||||
const [, closing, name, selfClosing] = m;
|
||||
if (closing) depth -= 1;
|
||||
else if (!selfClosing && !VOID_TAGS.has(name.toLowerCase())) depth += 1;
|
||||
if (depth < 0) return null;
|
||||
if (depth === 0) {
|
||||
parts.push(html.slice(start, TAG.lastIndex));
|
||||
start = TAG.lastIndex;
|
||||
}
|
||||
}
|
||||
return depth === 0 && start === html.length ? parts : null;
|
||||
}
|
||||
|
||||
// How many parts at the start (`head`) and at the end (`tail`) are the same
|
||||
// in both lists, never overlapping: everything between them changed.
|
||||
export function changedRange(before, after) {
|
||||
const most = Math.min(before.length, after.length);
|
||||
let head = 0;
|
||||
while (head < most && before[head] === after[head]) head++;
|
||||
let tail = 0;
|
||||
while (tail < most - head && before[before.length - 1 - tail] === after[after.length - 1 - tail]) tail++;
|
||||
return { head, tail };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ viewer */
|
||||
|
||||
// The next index when stepping through `count` pictures, wrapping at both
|
||||
// ends; -1 when there is nothing to step through.
|
||||
export function step(index, delta, count) {
|
||||
if (!(count > 0)) return -1;
|
||||
return (((index + delta) % count) + count) % count;
|
||||
}
|
||||
@@ -27,16 +27,21 @@ const CLEANUP_WHERE = { root: "~/.plan2code/", console: "~/.plan2code/console/",
|
||||
|
||||
function cleanupLabel(item) {
|
||||
if (item.where === "session") return "Session " + item.name;
|
||||
// One notepad is one item, named by the folder it belongs to; its key only
|
||||
// when its meta.json is gone.
|
||||
if (item.where === "notepad") return "Notepad for " + (item.folder || 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 notepads = items.filter((i) => i.where === "notepad").length;
|
||||
const strays = items.length - sessions - completed - notepads;
|
||||
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 (notepads) parts.push(notepads + (notepads === 1 ? " old notepad" : " old notepads"));
|
||||
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
|
||||
return parts.join(", ") + " · " + formatBytes(bytes);
|
||||
}
|
||||
|
||||
@@ -44,6 +44,7 @@ import {
|
||||
} from "../chat.js";
|
||||
import { copyButton, el, isMac, textWithCode } from "../render.js";
|
||||
import { isBuild } from "../skills.js";
|
||||
import { startsClean } from "../hops.js";
|
||||
import { faviconState, setFavicon } from "../favicon.js";
|
||||
import { helperRows, showTab } from "../subagents.js";
|
||||
import { FOOTER_TIERS, footerLabel } from "../workspace.js";
|
||||
@@ -67,6 +68,7 @@ import { renderWorkspace, tellFolderIssues } from "./workspace.js";
|
||||
import { openHelpOn } from "./help-dialog.js";
|
||||
import { askOfflineFlipped, askState, declineOpen, renderAside, renderAsk, renderSubagents, renderSubagentsButton } from "./ask.js";
|
||||
import { renderHandoff, renderHomeButton, renderStopButton, renderStopControls, renderStopping, stopInProgress, stopWarning } from "./ending.js";
|
||||
import { renderNotepadButton } from "./notepad.js";
|
||||
|
||||
// What the entry needs from the screens at start-up, handed on from here: only
|
||||
// the core imports a screen.
|
||||
@@ -80,6 +82,7 @@ export { maybeWelcome, openHelpOn, wireHelp } from "./help-dialog.js";
|
||||
export { wireCleanup } from "./cleanup.js";
|
||||
export { startLooks, wireLooks } from "./looks.js";
|
||||
export { wireEnding } from "./ending.js";
|
||||
export { wireNotepad } from "./notepad.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -255,14 +258,14 @@ export function adopt(body) {
|
||||
settleStaleUploads();
|
||||
}
|
||||
}
|
||||
// The page passed through the dashboard (a launch from its menu, or back to
|
||||
// it). The server already blanked the session; what this page kept for the
|
||||
// last skill -- the question on screen, the open tab, anything staged or
|
||||
// typed against its item ids -- goes too. The launch in flight and the
|
||||
// dashboard's spec pick are about the hand-off itself, so they stay. A skill
|
||||
// run inline from another (a quick task's review) keeps all of it.
|
||||
const viaDashboard = prevWorkflow === "dashboard" || page.S.workflow === "dashboard";
|
||||
if (prevWorkflow && prevWorkflow !== page.S.workflow && viaDashboard) {
|
||||
// A hop that starts clean (hops.js: a launch from the dashboard menu, back
|
||||
// to it, or into Git from anywhere). The server already blanked the
|
||||
// session; what this page kept for the last skill -- the question on
|
||||
// screen, the open tab, anything staged or typed against its item ids --
|
||||
// goes too. The launch in flight and the dashboard's spec pick are about the
|
||||
// hand-off itself, so they stay. A skill run inline from another (a quick
|
||||
// task's review) keeps all of it.
|
||||
if (startsClean(prevWorkflow, page.S.workflow)) {
|
||||
// The pick rides into the skill it launched, never back home: arriving at
|
||||
// the dashboard, the picker starts on the most recently touched spec still
|
||||
// in play, the one the agent's fresh menu recommends for.
|
||||
@@ -697,6 +700,7 @@ export function render() {
|
||||
renderBriefButton();
|
||||
renderSubagentsButton();
|
||||
renderStopButton();
|
||||
renderNotepadButton();
|
||||
renderHomeButton();
|
||||
tabAdded = renderViews();
|
||||
renderSidebar();
|
||||
@@ -1270,7 +1274,7 @@ export function renderSidebar() {
|
||||
b.disabled = Boolean(page.local.launching) || page.gone || page.pendingResult || !av.on;
|
||||
if (!av.on && av.reason) b.title = av.reason;
|
||||
b.setAttribute("aria-current", String(Boolean(page.dashPick && page.dashPick.skill === e.skill)));
|
||||
const isGoing = page.local.launching && page.local.launching.skill === e.skill;
|
||||
const isGoing = page.local.launching && (page.local.launching.skill === e.skill || page.local.launching.skill === e.review);
|
||||
const isPicked = page.dashPick && page.dashPick.skill === e.skill;
|
||||
const mark = el(
|
||||
"span",
|
||||
|
||||
@@ -22,6 +22,8 @@ import {
|
||||
cardPresentation,
|
||||
CATALOG_GROUPS,
|
||||
SKILL_CATALOG,
|
||||
catalogEntry,
|
||||
launchVariant,
|
||||
SPEC_STATE_LABELS,
|
||||
chipDetail,
|
||||
isDeletableSpecDir,
|
||||
@@ -534,7 +536,7 @@ function settleDeleting() {
|
||||
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 entry = catalogEntry(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",
|
||||
@@ -637,7 +639,7 @@ function dashCard(entry, menu) {
|
||||
// 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 going = page.local.launching && (page.local.launching.skill === entry.skill || page.local.launching.skill === entry.review);
|
||||
const b = el(
|
||||
"button",
|
||||
"dash-card" + (presentation.recommended ? " is-suggested" : "") + (going ? " is-going" : "")
|
||||
@@ -719,15 +721,31 @@ export function renderConfirm(main, entry) {
|
||||
pane.appendChild(specLine);
|
||||
}
|
||||
|
||||
// Implement's card reviews the phase before sign-off unless this is unticked.
|
||||
let review = null;
|
||||
if (entry.review) {
|
||||
const label = el("label", "confirm-review");
|
||||
review = el("input");
|
||||
review.type = "checkbox";
|
||||
review.checked = page.dashReview !== false;
|
||||
review.addEventListener("change", () => {
|
||||
page.dashReview = review.checked;
|
||||
cmdCode.textContent = launchVariant(entry, review.checked).command;
|
||||
});
|
||||
label.append(review, el("span", null, "Review: a fresh pass over the phase's changes before sign-off"));
|
||||
pane.appendChild(label);
|
||||
}
|
||||
|
||||
const cmd = el("p", "confirm-cmd");
|
||||
cmd.appendChild(el("code", null, entry.command));
|
||||
const cmdCode = el("code", null, launchVariant(entry, !review || review.checked).command);
|
||||
cmd.appendChild(cmdCode);
|
||||
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));
|
||||
start.addEventListener("click", () => launchSkill(launchVariant(entry, Boolean(review) && review.checked)));
|
||||
const back = el("button", "btn ghost", "Back");
|
||||
back.type = "button";
|
||||
back.addEventListener("click", () => {
|
||||
@@ -830,7 +848,7 @@ function openHandoffDelete(h) {
|
||||
facts.appendChild(el("dt", "", term));
|
||||
facts.appendChild(el("dd", "", value));
|
||||
};
|
||||
const entry = SKILL_CATALOG.find((e) => e.skill === h.skill);
|
||||
const entry = catalogEntry(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\//, "") : "");
|
||||
|
||||
@@ -5,6 +5,7 @@ import { page } from "../state.js";
|
||||
import { isDashboard, finish, agentAdrift } from "../selectors.js";
|
||||
import { releasesLink, el, copyButton, lightDismiss } from "../render.js";
|
||||
import { HELP_TABS, helpTabFor, helpKeyTarget } from "../help.js";
|
||||
import { CATALOG_GROUPS, SKILL_CATALOG } from "../answers.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -101,6 +102,22 @@ function buildHelp() {
|
||||
cell.appendChild(el("span", null, label));
|
||||
moods.appendChild(cell);
|
||||
}
|
||||
// The dashboard topic lists the cards from the catalog, grouped and in the
|
||||
// dashboard's order, so Help can never name a card the dashboard lacks.
|
||||
// A card's help line, when it has one, says more than its blurb.
|
||||
const cards = panels.querySelector(".help-cards");
|
||||
for (const g of CATALOG_GROUPS) {
|
||||
const head = el("p");
|
||||
head.appendChild(el("strong", null, g.title));
|
||||
const list = el("ul");
|
||||
for (const e of SKILL_CATALOG.filter((x) => x.group === g.id)) {
|
||||
const li = el("li");
|
||||
li.appendChild(el("strong", null, e.title + "."));
|
||||
li.appendChild(document.createTextNode(" " + (e.help || e.blurb)));
|
||||
list.appendChild(li);
|
||||
}
|
||||
cards.append(head, list);
|
||||
}
|
||||
for (const row of panels.querySelectorAll("[data-copy]")) {
|
||||
const code = row.querySelector("code");
|
||||
row.appendChild(copyButton(code.textContent, "btn small handoff-copy", code));
|
||||
|
||||
@@ -0,0 +1,652 @@
|
||||
// Plan2Code Web Console - the Notepad: the top bar's icon, its dialog, the editor and autosave.
|
||||
//
|
||||
// The person's own notes for the folder this session runs in, kept by the
|
||||
// server under ~/.plan2code/notepads/ through the /notepad routes, never in
|
||||
// the session, so nothing typed here reaches the agent. The editor is the
|
||||
// vendored OverType, which styles Markdown in place over a real textarea. Its
|
||||
// CSS ships in styles/notepad.css, because the page's policy blocks the
|
||||
// <style> OverType would inject. When to save and what the status line says
|
||||
// are notepad.js's pure rules; this file only runs the timers and requests.
|
||||
|
||||
import { page } from "../state.js";
|
||||
import {
|
||||
IMAGE_ID_RE,
|
||||
NOTEPAD_MAX_IMAGES,
|
||||
NOT_LOADED,
|
||||
SAVE_START,
|
||||
changedRange,
|
||||
errorSentence,
|
||||
keepsText,
|
||||
nextSave,
|
||||
noteBytes,
|
||||
saveStatus,
|
||||
step,
|
||||
topLevelParts,
|
||||
unsaved,
|
||||
withoutStyleAttrs,
|
||||
} from "../notepad.js";
|
||||
import { el, lightDismiss } from "../render.js";
|
||||
import { postJson } from "../net.js";
|
||||
import { reencode } from "../uploads.js";
|
||||
import { OverType } from "../vendor/overtype.esm.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
const NOT_CONNECTED = "Not connected right now.";
|
||||
|
||||
// One editor for the page's life, made on first open.
|
||||
let editor = null;
|
||||
|
||||
// The save state (notepad.js), the one timer it arms, and the request in
|
||||
// flight. `rev` counts changes, so an answer to an older text never marks a
|
||||
// newer one saved.
|
||||
let save = SAVE_START;
|
||||
let timer = null;
|
||||
let sending = false;
|
||||
let rev = 0;
|
||||
let problem = "";
|
||||
|
||||
// True while the page itself sets the editor's text: OverType reports that as
|
||||
// a change, and it is not the person typing.
|
||||
let loading = false;
|
||||
|
||||
// Whether the note has been read into the editor yet. Until it has, the
|
||||
// editor is read-only: text typed into the empty editor would be saved over
|
||||
// the real note.
|
||||
let loaded = false;
|
||||
|
||||
// Drawn from the render pass beside Stop: always shown, unusable while the
|
||||
// server is gone (nothing could load or save).
|
||||
export function renderNotepadButton() {
|
||||
const btn = $("btn-notepad");
|
||||
btn.disabled = Boolean(page.gone);
|
||||
btn.title = page.gone ? NOT_CONNECTED : "Notepad";
|
||||
}
|
||||
|
||||
// The last thing a picture went wrong with, said after the save words until
|
||||
// the next batch of pictures starts or the notepad is opened again; and the
|
||||
// picture it was about, if one, whose Retry landing clears it.
|
||||
let notice = "";
|
||||
let noticeKey = null;
|
||||
|
||||
function paintStatus() {
|
||||
const line = $("notepad-status");
|
||||
const words = saveStatus(save);
|
||||
const failed = save.status === "failed" || save.status === "too-long";
|
||||
const saving = save.status === "failed" && problem ? `${words}. ${problem}` : words;
|
||||
line.textContent = [saving, notice].filter(Boolean).join(" ");
|
||||
line.classList.toggle("is-problem", failed || Boolean(notice));
|
||||
}
|
||||
|
||||
function tell(sentence, key = null) {
|
||||
notice = sentence;
|
||||
noticeKey = key;
|
||||
paintStatus();
|
||||
}
|
||||
|
||||
function arm(ms) {
|
||||
clearTimeout(timer);
|
||||
timer = ms == null ? null : setTimeout(() => dispatch(save.status === "failed" ? "retry" : "due"), ms);
|
||||
}
|
||||
|
||||
function dispatch(event) {
|
||||
const next = nextSave(save, event);
|
||||
save = next.state;
|
||||
arm(next.timer);
|
||||
paintStatus();
|
||||
if (save.status === "saving") send();
|
||||
}
|
||||
|
||||
// One save at a time. A save that comes due while another is out goes as
|
||||
// soon as that one answers.
|
||||
async function send() {
|
||||
if (sending || !editor) return;
|
||||
sending = true;
|
||||
const sent = rev;
|
||||
const res = await postJson("/notepad/text", { text: editor.getValue() });
|
||||
sending = false;
|
||||
if (rev !== sent) {
|
||||
// Typed while it was out: the newer text has its own debounce running, or
|
||||
// is already due and waiting for this request to finish.
|
||||
if (save.status === "saving") send();
|
||||
return;
|
||||
}
|
||||
if (res.status === 200) {
|
||||
problem = "";
|
||||
return dispatch("ok");
|
||||
}
|
||||
const code = res.body && res.body.error;
|
||||
problem = errorSentence(res.status === 0 ? null : code);
|
||||
dispatch({ type: "error", code });
|
||||
}
|
||||
|
||||
function changed(text) {
|
||||
if (loading) return;
|
||||
rev += 1;
|
||||
dispatch({ type: "typed", bytes: noteBytes(text) });
|
||||
}
|
||||
|
||||
// Save now rather than after the debounce: closing, the tab going hidden.
|
||||
function flush() {
|
||||
if (save.status === "pending" || save.status === "failed") dispatch("due");
|
||||
}
|
||||
|
||||
function setText(text) {
|
||||
loading = true;
|
||||
try {
|
||||
editor.setValue(text);
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
// OverType writes inline style attributes into the HTML it sets: one on every
|
||||
// link it draws (its tooltip's anchor name) and two in the link tooltip. The
|
||||
// page's policy refuses each one with a report, on every keystroke. While the
|
||||
// editor is built, the elements it makes get an innerHTML that drops them
|
||||
// (withoutStyleAttrs); the preview and the tooltip are among them, so this
|
||||
// holds for every later render too. The tooltip then finds a link by the data
|
||||
// attribute its anchor name moved to.
|
||||
function buildWithoutStyleAttrs(build) {
|
||||
const create = document.createElement;
|
||||
const inner = Object.getOwnPropertyDescriptor(Element.prototype, "innerHTML");
|
||||
document.createElement = function (...args) {
|
||||
const node = create.apply(this, args);
|
||||
Object.defineProperty(node, "innerHTML", {
|
||||
configurable: true,
|
||||
get() {
|
||||
return inner.get.call(this);
|
||||
},
|
||||
set(html) {
|
||||
const clean = withoutStyleAttrs(String(html));
|
||||
if (this.classList.contains("overtype-preview")) patchPreview(this, clean);
|
||||
else inner.set.call(this, clean);
|
||||
},
|
||||
});
|
||||
return node;
|
||||
};
|
||||
try {
|
||||
return build();
|
||||
} finally {
|
||||
document.createElement = create;
|
||||
}
|
||||
}
|
||||
|
||||
// The styled layer as OverType last drew it, one HTML string per top-level
|
||||
// element (topLevelParts), matching the preview's children one for one.
|
||||
let drawn = [];
|
||||
|
||||
const parseParts = (html) => {
|
||||
const tpl = document.createElement("template");
|
||||
tpl.innerHTML = html;
|
||||
return [...tpl.content.childNodes];
|
||||
};
|
||||
|
||||
// OverType redraws the whole styled layer on every key: about 43,000 elements
|
||||
// in a 200 KB note, and parsing and laying those out is most of the wait for a
|
||||
// key to show. Only the lines between the first and the last that differ from
|
||||
// the last drawing are parsed and swapped; the rest stays as it was.
|
||||
function patchPreview(preview, html) {
|
||||
const parts = topLevelParts(html);
|
||||
const shown = [...preview.childNodes];
|
||||
const redraw = () => {
|
||||
preview.replaceChildren(...parseParts(html));
|
||||
drawn = parts && preview.childNodes.length === parts.length ? parts : [];
|
||||
};
|
||||
if (!parts || shown.length !== drawn.length) return redraw();
|
||||
const { head, tail } = changedRange(drawn, parts);
|
||||
const changed = parts.slice(head, parts.length - tail);
|
||||
const fresh = parseParts(changed.join(""));
|
||||
// One element per part, or the cut was wrong: draw it all.
|
||||
if (fresh.length !== changed.length) return redraw();
|
||||
const after = shown[shown.length - tail] || null;
|
||||
for (const old of shown.slice(head, shown.length - tail)) old.remove();
|
||||
for (const node of fresh) preview.insertBefore(node, after);
|
||||
drawn = parts;
|
||||
// OverType shades each pair of code fences right after this, and never
|
||||
// takes the shading off: a kept line whose fence lost its partner would keep
|
||||
// it. Cleared here (the attributes removed outright, so a cleared line is
|
||||
// the line OverType drew), and OverType marks only the pairs that still are.
|
||||
for (const line of preview.querySelectorAll(".code-block-line")) {
|
||||
line.classList.remove("code-block-line");
|
||||
if (!line.classList.length) line.removeAttribute("class");
|
||||
}
|
||||
for (const fence of preview.querySelectorAll(".code-fence")) fence.removeAttribute("style");
|
||||
}
|
||||
|
||||
function makeEditor() {
|
||||
// Before the first instance, or it injects its <style> (which the policy
|
||||
// blocks) and the flag would come too late.
|
||||
OverType.stylesInjected = true;
|
||||
// OverType reports its first, empty value as a change: not the person typing,
|
||||
// and saved it would wipe the note.
|
||||
loading = true;
|
||||
try {
|
||||
[editor] = buildWithoutStyleAttrs(
|
||||
() =>
|
||||
new OverType($("notepad-editor"), {
|
||||
toolbar: false,
|
||||
textareaProps: { "aria-label": "Notepad text" },
|
||||
onChange: changed,
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
editor.linkTooltip.findAnchorElement = (index) => editor.preview.querySelector(`a[data-anchor="--link-${index}"]`);
|
||||
}
|
||||
|
||||
// The stored note (`{ text, images }`), or null when it could not be read.
|
||||
async function readNote() {
|
||||
try {
|
||||
const res = await fetch("/notepad", { cache: "no-store" });
|
||||
if (!res.ok) return null;
|
||||
const body = await res.json();
|
||||
return body && typeof body.text === "string" ? body : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ pictures */
|
||||
|
||||
// The strip's pictures, oldest first, as { key, id, url, thumb, status }:
|
||||
// `key` is the page's own handle, `id` and `url` come from the server once
|
||||
// the upload lands, `thumb` is the stored thumbnail's URL or, for one added
|
||||
// here, the data: URL reencode() made. `status` is ready, uploading or failed.
|
||||
let images = [];
|
||||
|
||||
// What a failed upload needs to go again, by key: the re-encoded picture and
|
||||
// its thumbnail. Kept out of `images`, since both are large.
|
||||
const pending = new Map();
|
||||
|
||||
// Raw JPEG bytes to a /notepad route; the status and parsed answer, or status
|
||||
// 0 when the server could not be reached (as postJson).
|
||||
async function postJpeg(url, blob) {
|
||||
try {
|
||||
const res = await fetch(url, { method: "POST", headers: { "content-type": "image/jpeg" }, body: blob });
|
||||
let answer = {};
|
||||
try {
|
||||
answer = await res.json();
|
||||
} catch {}
|
||||
return { status: res.status, body: answer };
|
||||
} catch {
|
||||
return { status: 0, body: {} };
|
||||
}
|
||||
}
|
||||
|
||||
const imageFiles = (list) => Array.from(list || []).filter((f) => f && f.type && f.type.startsWith("image/"));
|
||||
|
||||
const drop = (key) => {
|
||||
images = images.filter((img) => img.key !== key);
|
||||
pending.delete(key);
|
||||
};
|
||||
|
||||
// The picture, then its thumbnail. One whose picture already landed (only
|
||||
// the thumbnail failed) sends just the thumbnail again.
|
||||
async function upload(entry) {
|
||||
const encoded = pending.get(entry.key);
|
||||
if (!encoded) return;
|
||||
entry.status = "uploading";
|
||||
drawStrip();
|
||||
if (!entry.id) {
|
||||
const res = await postJpeg("/notepad/image", encoded.blob);
|
||||
const id = res.body && res.body.id;
|
||||
if (res.status !== 200 || !IMAGE_ID_RE.test(String(id))) return failed(entry, res);
|
||||
entry.id = id;
|
||||
entry.url = "/notepad/images/" + id + ".jpg";
|
||||
}
|
||||
const res = await postJpeg("/notepad/thumb?id=" + entry.id, encoded.thumbBlob);
|
||||
if (res.status !== 200) return failed(entry, res);
|
||||
pending.delete(entry.key);
|
||||
entry.status = "ready";
|
||||
// Only this picture's own failure goes: a sentence about the batch (the
|
||||
// cap) or another picture stays up while the rest land.
|
||||
if (noticeKey === entry.key) tell("");
|
||||
drawStrip();
|
||||
}
|
||||
|
||||
function failed(entry, res) {
|
||||
const code = res.status === 0 ? null : res.body && res.body.error;
|
||||
// The server said no for good: going again would only be refused again.
|
||||
if (code === "too-many" || code === "not-jpeg" || code === "too-large" || code === "not-found") drop(entry.key);
|
||||
else entry.status = "failed";
|
||||
drawStrip();
|
||||
tell(errorSentence(code), entry.key);
|
||||
}
|
||||
|
||||
export async function addNotepadImages(files) {
|
||||
const given = imageFiles(files);
|
||||
if (!given.length) return;
|
||||
const room = Math.max(0, NOTEPAD_MAX_IMAGES - images.length);
|
||||
tell(given.length > room ? errorSentence("too-many") : "");
|
||||
await Promise.all(
|
||||
given.slice(0, room).map(async (file) => {
|
||||
const entry = { key: crypto.randomUUID(), id: null, url: null, thumb: null, status: "uploading" };
|
||||
images.push(entry);
|
||||
drawStrip();
|
||||
let encoded;
|
||||
try {
|
||||
encoded = await reencode(file);
|
||||
} catch (err) {
|
||||
drop(entry.key);
|
||||
drawStrip();
|
||||
return tell(err.message);
|
||||
}
|
||||
entry.thumb = encoded.thumb;
|
||||
pending.set(entry.key, encoded);
|
||||
await upload(entry);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// One thumbnail, the `n`th: the picture (its thumbnail, else the picture
|
||||
// itself) as a button, and the X in its corner. A placeholder with a spinner
|
||||
// while it uploads, Retry when it failed.
|
||||
function thumbItem(entry, n) {
|
||||
const item = el("li", `attach-thumb notepad-thumb is-${entry.status}`);
|
||||
item.dataset.key = entry.key;
|
||||
const open = el("button", "notepad-thumb-open");
|
||||
open.type = "button";
|
||||
const src = entry.thumb || entry.url;
|
||||
if (src) {
|
||||
const pic = el("img");
|
||||
pic.src = src;
|
||||
pic.alt = `Notepad image ${n}`;
|
||||
open.appendChild(pic);
|
||||
} else open.setAttribute("aria-label", `Notepad image ${n}`);
|
||||
// Never `disabled`, which would push the focus out of the strip while the
|
||||
// picture uploads: it only does nothing until there is a picture to show.
|
||||
const viewable = Boolean(entry.url) && entry.status !== "uploading";
|
||||
if (!viewable) open.setAttribute("aria-disabled", "true");
|
||||
open.addEventListener("click", () => {
|
||||
if (viewable) openPreview(entry);
|
||||
});
|
||||
item.appendChild(open);
|
||||
if (entry.status !== "uploading" && !entry.asking) {
|
||||
const x = el("button", "attach-remove notepad-thumb-delete", "×");
|
||||
x.type = "button";
|
||||
x.setAttribute("aria-label", `Delete image ${n}`);
|
||||
x.addEventListener("click", () => ask(entry));
|
||||
item.appendChild(x);
|
||||
}
|
||||
if (entry.asking) {
|
||||
// Keep comes first and takes the focus, so Enter keeps the picture.
|
||||
const over = el("div", "attach-overlay notepad-ask");
|
||||
over.appendChild(el("p", null, "Delete this image?"));
|
||||
const row = el("div", "notepad-ask-row");
|
||||
const keep = el("button", "btn tiny notepad-ask-keep", "Keep");
|
||||
keep.type = "button";
|
||||
keep.addEventListener("click", () => {
|
||||
entry.asking = false;
|
||||
drawStrip();
|
||||
focusIn(entry.key, ".notepad-thumb-delete");
|
||||
});
|
||||
const del = el("button", "btn tiny notepad-ask-delete", "Delete");
|
||||
del.type = "button";
|
||||
del.addEventListener("click", () => remove(entry));
|
||||
keep.disabled = del.disabled = Boolean(entry.deleting);
|
||||
row.appendChild(keep);
|
||||
row.appendChild(del);
|
||||
over.appendChild(row);
|
||||
item.appendChild(over);
|
||||
} else if (entry.status === "uploading") {
|
||||
const over = el("div", "attach-overlay");
|
||||
over.appendChild(el("span", "spinner tiny"));
|
||||
item.appendChild(over);
|
||||
} else if (entry.status === "failed") {
|
||||
const over = el("div", "attach-overlay failed");
|
||||
over.appendChild(el("p", null, "Upload failed"));
|
||||
const again = el("button", "btn tiny notepad-retry", "Retry");
|
||||
again.type = "button";
|
||||
again.addEventListener("click", () => upload(entry));
|
||||
over.appendChild(again);
|
||||
item.appendChild(over);
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
// The controls a thumbnail can hold the focus on, by class.
|
||||
const THUMB_CONTROLS = ["notepad-thumb-open", "notepad-thumb-delete", "notepad-ask-keep", "notepad-ask-delete", "notepad-retry"];
|
||||
|
||||
// Every redraw rebuilds the thumbnails, which would drop a focused button
|
||||
// out of the page: the focus goes back to the same control, or to that
|
||||
// thumbnail's picture when the control is gone (Retry became a spinner), or
|
||||
// to Add image when the thumbnail itself is gone.
|
||||
function drawStrip() {
|
||||
const strip = $("notepad-strip");
|
||||
const active = document.activeElement;
|
||||
const was = active && strip.contains(active) ? active.closest("li") : null;
|
||||
const control = was && THUMB_CONTROLS.find((cls) => active.classList.contains(cls));
|
||||
strip.replaceChildren(...images.map((entry, i) => thumbItem(entry, i + 1)));
|
||||
if (!was) return;
|
||||
if (!(control && focusIn(was.dataset.key, "." + control)) && !focusIn(was.dataset.key, ".notepad-thumb-open")) {
|
||||
$("notepad-add").focus();
|
||||
}
|
||||
}
|
||||
|
||||
// Focus a control in the thumbnail with this key; whether it could.
|
||||
function focusIn(key, selector) {
|
||||
const item = Array.from($("notepad-strip").children).find((li) => li.dataset.key === key);
|
||||
const target = item && item.querySelector(selector);
|
||||
if (!target || target.disabled) return false;
|
||||
target.focus();
|
||||
return true;
|
||||
}
|
||||
|
||||
// The X asks first, on the thumbnail itself; one question at a time.
|
||||
function ask(entry) {
|
||||
for (const img of images) img.asking = img === entry;
|
||||
drawStrip();
|
||||
focusIn(entry.key, ".notepad-ask-keep");
|
||||
}
|
||||
|
||||
// Delete for good, then hand the focus to the picture that took its place.
|
||||
// One never stored (its upload failed) is only taken off the strip.
|
||||
async function remove(entry) {
|
||||
if (entry.id) {
|
||||
entry.deleting = true;
|
||||
drawStrip();
|
||||
const res = await postJson("/notepad/image/delete", { id: entry.id });
|
||||
entry.deleting = false;
|
||||
const code = res.status === 0 ? null : res.body && res.body.error;
|
||||
if (res.status !== 200 && code !== "not-found") {
|
||||
entry.asking = false;
|
||||
drawStrip();
|
||||
focusIn(entry.key, ".notepad-thumb-delete");
|
||||
return tell(errorSentence(code));
|
||||
}
|
||||
// Already gone (deleted from another page): off the strip too, with why.
|
||||
if (code === "not-found") tell(errorSentence(code));
|
||||
}
|
||||
const at = images.indexOf(entry);
|
||||
drop(entry.key);
|
||||
drawStrip();
|
||||
const next = images[at] || images[at - 1];
|
||||
if (next) focusIn(next.key, ".notepad-thumb-open");
|
||||
else $("notepad-add").focus();
|
||||
}
|
||||
|
||||
// The stored pictures from GET /notepad, oldest first, then any added here
|
||||
// that are still on their way or waiting for Retry.
|
||||
function takeStored(list) {
|
||||
const stored = (Array.isArray(list) ? list : [])
|
||||
.filter((img) => img && IMAGE_ID_RE.test(String(img.id)))
|
||||
.map((img) => ({ key: img.id, id: img.id, url: img.url, thumb: img.thumb || null, status: "ready" }));
|
||||
const ids = new Set(stored.map((img) => img.id));
|
||||
const local = images.filter((img) => img.status !== "ready" && !(img.id && ids.has(img.id)));
|
||||
for (const key of pending.keys()) if (!local.some((img) => img.key === key)) pending.delete(key);
|
||||
images = [...stored, ...local];
|
||||
drawStrip();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ preview */
|
||||
|
||||
// What the preview steps through (the pictures with a stored copy, as they
|
||||
// stood when it opened), which one shows, and the thumbnail it opened from.
|
||||
let viewing = { list: [], index: -1, from: null };
|
||||
|
||||
function showAt(index) {
|
||||
const { list } = viewing;
|
||||
const entry = list[index];
|
||||
viewing.index = index;
|
||||
const pic = $("notepad-preview-img");
|
||||
pic.src = entry.url;
|
||||
pic.alt = `Notepad image ${images.indexOf(entry) + 1}`;
|
||||
$("notepad-preview-count").textContent = `${index + 1} of ${list.length}`;
|
||||
$("notepad-preview-prev").hidden = $("notepad-preview-next").hidden = list.length < 2;
|
||||
}
|
||||
|
||||
function openPreview(entry) {
|
||||
const list = images.filter((img) => img.url);
|
||||
const index = list.indexOf(entry);
|
||||
if (index < 0) return;
|
||||
viewing = { list, index, from: entry.key };
|
||||
showAt(index);
|
||||
const dlg = $("notepad-preview");
|
||||
if (!dlg.open) dlg.showModal();
|
||||
$("notepad-preview-close").focus();
|
||||
}
|
||||
|
||||
function move(delta) {
|
||||
const index = step(viewing.index, delta, viewing.list.length);
|
||||
if (index >= 0) showAt(index);
|
||||
}
|
||||
|
||||
// Esc is taken here and closes the preview alone: left to the browser, it
|
||||
// could reach the Notepad underneath too.
|
||||
function wirePreview() {
|
||||
const dlg = $("notepad-preview");
|
||||
$("notepad-preview-prev").addEventListener("click", () => move(-1));
|
||||
$("notepad-preview-next").addEventListener("click", () => move(1));
|
||||
$("notepad-preview-close").addEventListener("click", () => dlg.close());
|
||||
dlg.addEventListener("keydown", (e) => {
|
||||
if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
|
||||
e.preventDefault();
|
||||
move(e.key === "ArrowLeft" ? -1 : 1);
|
||||
} else if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
dlg.close();
|
||||
}
|
||||
});
|
||||
dlg.addEventListener("close", () => {
|
||||
$("notepad-preview-img").removeAttribute("src");
|
||||
focusIn(viewing.from, ".notepad-thumb-open");
|
||||
});
|
||||
}
|
||||
|
||||
// A paste is a picture paste when it carries image files and no plain text:
|
||||
// a spreadsheet's cells come with a picture of themselves too, and are text.
|
||||
function pastedImages(data) {
|
||||
if (!data || (data.types && Array.from(data.types).includes("text/plain"))) return [];
|
||||
const items = Array.from(data.items || [])
|
||||
.filter((item) => item.kind === "file" && item.type.startsWith("image/"))
|
||||
.map((item) => item.getAsFile())
|
||||
.filter(Boolean);
|
||||
return items.length ? items : imageFiles(data.files);
|
||||
}
|
||||
|
||||
const draggingFiles = (e) => Boolean(e.dataTransfer && Array.from(e.dataTransfer.types || []).includes("Files"));
|
||||
|
||||
// The three ways in: the Add image button, a paste and a drop anywhere on the
|
||||
// dialog. Captured on the dialog, ahead of the editor's own handling, and
|
||||
// only for pictures: text pastes and text drags reach the editor as usual.
|
||||
function wireImages(dlg) {
|
||||
const picker = $("notepad-file");
|
||||
$("notepad-add").addEventListener("click", () => picker.click());
|
||||
picker.addEventListener("change", () => {
|
||||
addNotepadImages(picker.files);
|
||||
picker.value = "";
|
||||
});
|
||||
dlg.addEventListener(
|
||||
"paste",
|
||||
(e) => {
|
||||
const files = pastedImages(e.clipboardData);
|
||||
if (!files.length) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
addNotepadImages(files);
|
||||
},
|
||||
true,
|
||||
);
|
||||
dlg.addEventListener(
|
||||
"dragover",
|
||||
(e) => {
|
||||
if (!draggingFiles(e)) return;
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = "copy";
|
||||
dlg.classList.add("is-drop");
|
||||
},
|
||||
true,
|
||||
);
|
||||
dlg.addEventListener("dragleave", (e) => {
|
||||
if (!e.relatedTarget || !dlg.contains(e.relatedTarget)) dlg.classList.remove("is-drop");
|
||||
});
|
||||
dlg.addEventListener(
|
||||
"drop",
|
||||
(e) => {
|
||||
dlg.classList.remove("is-drop");
|
||||
if (!draggingFiles(e)) return;
|
||||
// Taken even when none is a picture, or the browser opens the file.
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
addNotepadImages(e.dataTransfer.files);
|
||||
},
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
// Read again on every open, so saves from another page on the same folder
|
||||
// show up. Text typed here and not yet saved (or too long to save) is never
|
||||
// replaced.
|
||||
async function load() {
|
||||
const note = await readNote();
|
||||
if (note === null) {
|
||||
if (loaded) return;
|
||||
const line = $("notepad-status");
|
||||
line.textContent = NOT_LOADED;
|
||||
line.classList.add("is-problem");
|
||||
return;
|
||||
}
|
||||
takeStored(note.images);
|
||||
if (keepsText(save)) return;
|
||||
setText(note.text);
|
||||
save = SAVE_START;
|
||||
loaded = true;
|
||||
editor.textarea.readOnly = false;
|
||||
paintStatus();
|
||||
}
|
||||
|
||||
export async function openNotepad() {
|
||||
if ($("btn-notepad").disabled) return;
|
||||
const dlg = $("notepad-modal");
|
||||
if (!editor) makeEditor();
|
||||
editor.textarea.readOnly = !loaded;
|
||||
tell("");
|
||||
if (!dlg.open) dlg.showModal();
|
||||
editor.textarea.focus();
|
||||
await load();
|
||||
}
|
||||
|
||||
export function wireNotepad() {
|
||||
const dlg = $("notepad-modal");
|
||||
lightDismiss(dlg);
|
||||
wireImages(dlg);
|
||||
wirePreview();
|
||||
$("btn-notepad").addEventListener("click", openNotepad);
|
||||
$("notepad-close").addEventListener("click", () => dlg.close());
|
||||
dlg.addEventListener("close", () => {
|
||||
flush();
|
||||
$("btn-notepad").focus();
|
||||
});
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.visibilityState === "hidden") flush();
|
||||
});
|
||||
// Only while something typed may not be on disk yet.
|
||||
window.addEventListener("beforeunload", (e) => {
|
||||
if (!unsaved(save)) return;
|
||||
e.preventDefault();
|
||||
e.returnValue = "";
|
||||
});
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import { page, redraw } from "../state.js";
|
||||
import { el, approvalTip } from "../render.js";
|
||||
import { startPose, startingHint, SKILL_CATALOG, staleLaunchFeedback, workflowTitle } from "../answers.js";
|
||||
import { startPose, startingHint, staleLaunchFeedback, workflowTitle } from "../answers.js";
|
||||
import { skillByName } from "../skills.js";
|
||||
import { agentAdrift, doingNow, docs } from "../selectors.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
@@ -92,7 +93,7 @@ function posePane(main, cls, workflow) {
|
||||
// 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 pane = posePane(main, "launching", l.skill && skillByName(l.skill)?.workflow);
|
||||
|
||||
const stale = staleLaunchFeedback(l.title, agentAdrift());
|
||||
pane.appendChild(el("p", "card-kicker", stale ? stale.kicker : "On it"));
|
||||
|
||||
@@ -19,6 +19,13 @@
|
||||
// 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
|
||||
// weight what the launch and its `run` event score on the session
|
||||
// meter (meter.js WEIGHTS), or null when it has no weight there
|
||||
// started the meter's label for the launch ("Plan started"), or null
|
||||
// ran the meter's label for its `run` event ("Plan drafted"), or null
|
||||
// resume what the resume command takes after the skill's command:
|
||||
// "overview" for <specDir>/overview.md, "folder" for
|
||||
// <specDir>/pathfinder, null for no argument
|
||||
// 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,
|
||||
@@ -30,8 +37,12 @@
|
||||
// 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
|
||||
// review the skill the card launches instead when its Review box is
|
||||
// ticked (Implement's card, which draws the box), or absent
|
||||
// card the dashboard card (group, chip, title, blurb, about, and
|
||||
// `spec: true` when it takes the picked spec), or null
|
||||
// `spec: true` when it takes the picked spec), or null; an
|
||||
// optional `help` is Help's line for the card when it differs
|
||||
// from `blurb`
|
||||
|
||||
// Shared by Implement and Implement + Review.
|
||||
const BUILD_HELPERS =
|
||||
@@ -58,6 +69,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Init",
|
||||
pose: "init",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 2, started: "Init started", ran: "Init run", resume: null,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: { default: "AGENTS.md is already written. Refresh it instead." },
|
||||
@@ -77,6 +89,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Init update",
|
||||
pose: "init",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 2, started: "Init update started", ran: "Init update run", resume: null,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: { default: "Needs an AGENTS.md. Set the project up first." },
|
||||
@@ -96,6 +109,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Pathfinder",
|
||||
pose: "pathfinder",
|
||||
builds: false, phased: false, metered: false, templates: true,
|
||||
weight: null, started: null, ran: null, resume: "folder",
|
||||
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: {
|
||||
@@ -120,6 +134,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Plan",
|
||||
pose: "plan",
|
||||
builds: false, phased: false, metered: true, templates: true,
|
||||
weight: 2, started: "Plan started", ran: "Plan drafted", resume: null,
|
||||
subagents: null,
|
||||
states: ["none", "unrecognized", "diagnosed", "mapped", "planned"], marksNext: true,
|
||||
greyed: {
|
||||
@@ -144,6 +159,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Revise plan",
|
||||
pose: "plan",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 1, started: "Revise plan started", ran: "Plan revised", resume: "overview",
|
||||
subagents: null,
|
||||
states: ["documented", "building"],
|
||||
greyed: { default: "Needs a spec that is already written up", built: "The spec is fully built" },
|
||||
@@ -164,6 +180,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Document",
|
||||
pose: "document",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 2, started: "Document started", ran: "Spec documented", resume: "overview",
|
||||
subagents: null,
|
||||
states: ["planned"], marksNext: true,
|
||||
greyed: {
|
||||
@@ -189,7 +206,9 @@ export const SKILLS = Object.freeze([
|
||||
name: "Implement",
|
||||
pose: "implement",
|
||||
builds: true, phased: true, metered: false, templates: false,
|
||||
weight: null, started: null, ran: null, resume: "overview",
|
||||
subagents: BUILD_HELPERS,
|
||||
review: "plan2code-3-implement-review",
|
||||
states: ["documented", "building"], marksNext: true,
|
||||
greyed: BUILD_GREYED,
|
||||
card: {
|
||||
@@ -197,9 +216,9 @@ export const SKILLS = Object.freeze([
|
||||
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.",
|
||||
blurb: "Builds the next phase, task by task, then reviews it, with 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.",
|
||||
"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. With Review ticked, a fresh pass then hunts for problems in exactly what changed and you pick what gets fixed. It ends with a report of what was built and a sign-off card you approve before the phase counts as done.",
|
||||
},
|
||||
}),
|
||||
skill({
|
||||
@@ -209,18 +228,12 @@ export const SKILLS = Object.freeze([
|
||||
name: "Implement + Review",
|
||||
pose: "implement",
|
||||
builds: true, phased: true, metered: false, templates: false,
|
||||
weight: null, started: null, ran: null, resume: "overview",
|
||||
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.",
|
||||
},
|
||||
// No card of its own: Implement's card launches it when Review is ticked.
|
||||
card: null,
|
||||
}),
|
||||
skill({
|
||||
skill: "plan2code-4-finalize",
|
||||
@@ -229,6 +242,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Finalize",
|
||||
pose: "finalize",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 1, started: "Finalize started", ran: "Finalize run", resume: "overview",
|
||||
subagents: null,
|
||||
states: ["built"], marksNext: true,
|
||||
greyed: { default: "Needs a spec that is fully built" },
|
||||
@@ -249,6 +263,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Quick task",
|
||||
pose: "quick-task",
|
||||
builds: true, phased: false, metered: true, templates: true,
|
||||
weight: 1, started: "Quick task started", ran: "Quick task built", resume: null,
|
||||
subagents: "Use helpers for side lookups, such as reading unfamiliar code or checking documentation, while you make the change yourself.",
|
||||
states: "any",
|
||||
greyed: null,
|
||||
@@ -268,6 +283,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Review",
|
||||
pose: "review",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 2, started: "Review started", ran: "Code review run", resume: null,
|
||||
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,
|
||||
@@ -287,6 +303,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "X-ray",
|
||||
pose: "xray",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 1, started: "X-ray started", ran: "X-ray run", resume: null,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: null,
|
||||
@@ -306,6 +323,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Diagnose",
|
||||
pose: "diagnose",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 1, started: "Diagnose started", ran: "Diagnose run", resume: null,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: null,
|
||||
@@ -314,6 +332,7 @@ export const SKILLS = Object.freeze([
|
||||
chip: "Utility",
|
||||
title: "Diagnose a bug",
|
||||
blurb: "Find a bug's cause and write it up, without fixing it.",
|
||||
help: "Finds a bug's cause and writes it up without fixing it, ready to hand to Quick Task or Plan.",
|
||||
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.",
|
||||
},
|
||||
@@ -325,6 +344,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Changelog",
|
||||
pose: "changelog",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 1, started: "Changelog started", ran: "Changelog run", resume: null,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: null,
|
||||
@@ -344,6 +364,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Git",
|
||||
pose: "git",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 1, started: "Git started", ran: "Git run", resume: null,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: null,
|
||||
@@ -352,6 +373,7 @@ export const SKILLS = Object.freeze([
|
||||
chip: "Utility",
|
||||
title: "Git",
|
||||
blurb: "Branches, pull, push and commits on one board that stays open while you work.",
|
||||
help: "Branches, pull, push and commits on one board, asking before anything leaves your machine. See \"The git board\".",
|
||||
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.",
|
||||
},
|
||||
@@ -363,6 +385,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Handoff",
|
||||
pose: "handoff",
|
||||
builds: false, phased: false, metered: false, templates: false,
|
||||
weight: 0, started: null, ran: "Handoff written", resume: null,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: null,
|
||||
@@ -382,6 +405,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "the dashboard",
|
||||
pose: null,
|
||||
builds: false, phased: false, metered: false, templates: false,
|
||||
weight: null, started: null, ran: null, resume: null,
|
||||
subagents: null,
|
||||
states: null,
|
||||
greyed: null,
|
||||
@@ -392,6 +416,14 @@ export const SKILLS = Object.freeze([
|
||||
const BY_WORKFLOW = new Map(SKILLS.map((s) => [s.workflow, s]));
|
||||
const BY_SKILL = new Map(SKILLS.map((s) => [s.skill, s]));
|
||||
|
||||
// Every workflow name the console knows, in SKILLS order.
|
||||
export const WORKFLOWS = Object.freeze(SKILLS.map((s) => s.workflow));
|
||||
|
||||
/** Whether a name is one of WORKFLOWS (`open --workflow`, `handoff new --workflow`). */
|
||||
export function isWorkflow(name) {
|
||||
return typeof name === "string" && BY_WORKFLOW.has(name);
|
||||
}
|
||||
|
||||
/** The entry for a workflow ("implement"), or null. */
|
||||
export function skillFor(workflow) {
|
||||
return BY_WORKFLOW.get(workflow) || null;
|
||||
|
||||
@@ -409,6 +409,8 @@
|
||||
.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-review { display: flex; gap: 8px; align-items: center; margin: 4px 0 8px; color: var(--ink-2); cursor: pointer; }
|
||||
.confirm-review input { accent-color: var(--accent, currentColor); }
|
||||
.confirm-cmd { margin: 2px 0 0; }
|
||||
.confirm-cmd code {
|
||||
font-family: var(--mono);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -52,6 +52,19 @@
|
||||
the one that is only nice to have. */
|
||||
.pager { gap: 8px; }
|
||||
.pager-count { display: none; }
|
||||
/* The Notepad takes the whole screen, and every control in it is a
|
||||
fingertip wide. The pictures go under Add image rather than beside it, so
|
||||
the strip gets the full width, and the preview's side columns narrow to
|
||||
give the picture their room. */
|
||||
.btn.notepad-btn { min-width: 44px; }
|
||||
.modal.notepad { width: 100%; height: 100%; margin: 0; padding: 18px 16px 16px; border: 0; border-radius: 0; }
|
||||
.modal.notepad .notepad-add,
|
||||
.modal.notepad .modal-actions .btn,
|
||||
.btn.notepad-preview-close { min-height: 44px; }
|
||||
.notepad-images { flex-direction: column; align-items: stretch; }
|
||||
.notepad-add { align-self: flex-start; }
|
||||
.notepad-thumb .notepad-thumb-delete { width: 30px; height: 30px; font-size: 18px; }
|
||||
.modal.notepad-preview[open] { grid-template-columns: 52px minmax(0, 1fr) 52px; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
|
||||
@@ -171,21 +171,23 @@ function drawScaled(source, edge) {
|
||||
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 toJpeg = (canvas, quality) =>
|
||||
new Promise((resolve, reject) =>
|
||||
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("That image could not be converted."))), "image/jpeg", quality)
|
||||
);
|
||||
|
||||
// The upload (a JPEG no longer than IMAGE_LONG_EDGE) and its thumbnail, as a
|
||||
// small data: URL for a tray (`thumb`) and as a JPEG for a server that keeps
|
||||
// one (`thumbBlob`, the Notepad's), from one decode.
|
||||
export 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
|
||||
)
|
||||
);
|
||||
const blob = await toJpeg(drawScaled(source, IMAGE_LONG_EDGE), 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 };
|
||||
const small = drawScaled(source, THUMB_EDGE);
|
||||
const thumb = small.toDataURL("image/jpeg", 0.7);
|
||||
const thumbBlob = await toJpeg(small, 0.7);
|
||||
return { blob, thumb, thumbBlob };
|
||||
} finally {
|
||||
if (typeof source.close === "function") source.close();
|
||||
}
|
||||
|
||||
+7528
File diff suppressed because it is too large.
Load diff
@@ -42,6 +42,7 @@ import { cleanSetting, offered } from "./public/subagents.js";
|
||||
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
|
||||
import { SERVABLE, TYPES, asset } from "./static.mjs";
|
||||
import { handoffsDir, isHandoffId } from "./handoffs.mjs";
|
||||
import { NotepadError, addImage, addThumb, imagePath, readNotepad, removeImage, saveNote } from "./notepads.mjs";
|
||||
|
||||
/* ---------------------------------------------------------------- routes */
|
||||
|
||||
@@ -69,6 +70,12 @@ const ROUTES = [
|
||||
{ path: "/models", method: "POST", origin: true, run: modelsPost },
|
||||
{ path: "/cleanup", method: "POST", origin: true, run: cleanup },
|
||||
{ path: "/upload", method: "POST", origin: true, run: upload },
|
||||
{ path: "/notepad", method: "GET", run: notepadGet },
|
||||
{ path: "/notepad/text", method: "POST", origin: true, run: notepadText },
|
||||
{ path: "/notepad/image", method: "POST", origin: true, run: notepadImage },
|
||||
{ path: "/notepad/thumb", method: "POST", origin: true, run: notepadThumb },
|
||||
{ path: "/notepad/image/delete", method: "POST", origin: true, run: notepadDelete },
|
||||
{ match: (p, req) => p.startsWith("/notepad/images/") || req.url.startsWith("/notepad/images/"), method: "GET", run: notepadImageGet },
|
||||
{ match: (p, req) => p.startsWith("/attachments/") || req.url.startsWith("/attachments/"), run: attachment },
|
||||
{ match: (p, req) => p.startsWith("/shots/") || req.url.startsWith("/shots/"), run: shot },
|
||||
{ match: (p, req) => p.startsWith("/uploads/") || req.url.startsWith("/uploads/"), run: uploads },
|
||||
@@ -539,6 +546,99 @@ function cleanup(req, res, ctx) {
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- notepad */
|
||||
|
||||
// The person's private notepad for the folder this session runs in, kept by
|
||||
// notepads.mjs outside the session. Nothing here writes to ctx.dir or the
|
||||
// event log: the agent reads both, and the notepad is never the agent's.
|
||||
const notepadRoot = (ctx) => ctx.worktree() || ctx.project;
|
||||
|
||||
function notepadFail(res, e) {
|
||||
if (e instanceof NotepadError) return json(res, e.status, { error: e.code });
|
||||
return json(res, 500, { error: "bad" });
|
||||
}
|
||||
|
||||
function notepadGet(req, res, ctx) {
|
||||
try {
|
||||
return json(res, 200, readNotepad(notepadRoot(ctx)));
|
||||
} catch (e) {
|
||||
return notepadFail(res, e);
|
||||
}
|
||||
}
|
||||
|
||||
function notepadText(req, res, ctx) {
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too-long" : "bad" });
|
||||
try {
|
||||
return json(res, 200, { ok: true, ...saveNote(notepadRoot(ctx), body && body.text) });
|
||||
} catch (e) {
|
||||
return notepadFail(res, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// A picture's bytes, raw: JPEG only (the page re-encodes everything first).
|
||||
function readJpeg(req, res, then) {
|
||||
if (!String(req.headers["content-type"] || "").startsWith("image/jpeg")) {
|
||||
req.resume();
|
||||
return json(res, 415, { error: "not-jpeg" });
|
||||
}
|
||||
return readRaw(req, MAX_BODY, (err, buf) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too-large" : "bad" });
|
||||
return then(buf);
|
||||
});
|
||||
}
|
||||
|
||||
function notepadImage(req, res, ctx) {
|
||||
return readJpeg(req, res, (buf) => {
|
||||
try {
|
||||
return json(res, 200, { ok: true, ...addImage(notepadRoot(ctx), buf) });
|
||||
} catch (e) {
|
||||
return notepadFail(res, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function notepadThumb(req, res, ctx, url) {
|
||||
return readJpeg(req, res, (buf) => {
|
||||
try {
|
||||
addThumb(notepadRoot(ctx), url.searchParams.get("id"), buf);
|
||||
return json(res, 200, { ok: true });
|
||||
} catch (e) {
|
||||
return notepadFail(res, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function notepadDelete(req, res, ctx) {
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: "bad" });
|
||||
try {
|
||||
removeImage(notepadRoot(ctx), body && body.id);
|
||||
return json(res, 200, { ok: true });
|
||||
} catch (e) {
|
||||
return notepadFail(res, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Matched on the raw request line too, as /uploads/ is: URL parsing folds
|
||||
// `..` away, and nothing that needed folding is a notepad picture.
|
||||
const NOTEPAD_IMAGE_ROUTE = /^\/notepad\/images\/([0-9a-f-]{36})(\.thumb)?\.jpg$/;
|
||||
|
||||
function notepadImageGet(req, res, ctx, url) {
|
||||
const m = NOTEPAD_IMAGE_ROUTE.exec(req.url);
|
||||
const file = m && m[0] === url.pathname ? imagePath(notepadRoot(ctx), m[1], Boolean(m[2])) : null;
|
||||
if (!file) return json(res, 404, { error: "not-found" });
|
||||
let buf;
|
||||
try {
|
||||
buf = fs.readFileSync(file);
|
||||
} catch {
|
||||
return json(res, 404, { error: "not-found" });
|
||||
}
|
||||
return send(res, 200, buf, "image/jpeg");
|
||||
}
|
||||
|
||||
/* ------------------------------------------- uploads, shots, attachments */
|
||||
|
||||
// Images and documents attached to notes and quick questions. Only ever named
|
||||
|
||||
+21
-28
@@ -7,6 +7,11 @@ 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";
|
||||
import { countTasks, statusOf } from "./spec-files.mjs";
|
||||
|
||||
// The task-line pattern lives in spec-files.mjs; re-exported for any importer
|
||||
// that still takes it from here.
|
||||
export { TASK_LINE_RE } from "./spec-files.mjs";
|
||||
|
||||
/* ---------------------------------------------------------- project scan */
|
||||
|
||||
@@ -53,20 +58,6 @@ function maxMtime(dir, depth = 4, budget = { n: 400 }, tally = null) {
|
||||
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.
|
||||
@@ -79,25 +70,27 @@ function classifySpec(dir, names) {
|
||||
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 draftStatus = liveDraft ? statusOf(readText(path.join(dir, liveDraft))) || "" : "";
|
||||
const resumeAt = draftStatus.match(/Resume at Phase\s*(\d+)/i);
|
||||
|
||||
if (phases.length) {
|
||||
// countTasks() counts a file's task lines (every checkbox in a file
|
||||
// written before that format). An assumed-done task (`[?]`) counts as
|
||||
// done, and the detail names how many there are.
|
||||
let done = 0;
|
||||
let assumed = 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 n = countTasks(readText(path.join(dir, f)));
|
||||
done += n.done;
|
||||
assumed += n.assumed;
|
||||
open += n.open;
|
||||
}
|
||||
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` };
|
||||
const finished = done + assumed;
|
||||
const total = finished + open;
|
||||
const suffix = assumed > 0 ? `, ${assumed} assumed` : "";
|
||||
if (open === 0 && finished > 0) return { state: "built", detail: `all tasks done${suffix}` };
|
||||
if (finished > 0) return { state: "building", detail: `${finished} of ${total} tasks done${suffix}` };
|
||||
return {
|
||||
state: "documented",
|
||||
detail: `${phases.length} phase${phases.length === 1 ? "" : "s"}, ${total || "?"} tasks ready`,
|
||||
@@ -115,14 +108,14 @@ function classifySpec(dir, names) {
|
||||
// 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() : "";
|
||||
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();
|
||||
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;
|
||||
|
||||
@@ -47,6 +47,7 @@ import { serverWorkspace } from "./workspace.mjs";
|
||||
import { serverSubagents } from "./settings.mjs";
|
||||
import { chatOffline } from "./public/chat.js";
|
||||
import { meterView } from "./public/meter.js";
|
||||
import { startsClean } from "./public/hops.js";
|
||||
import { SERVABLE, asset } from "./static.mjs";
|
||||
import { handle } from "./routes.mjs";
|
||||
import { checkForUpdate } from "./update-check.mjs";
|
||||
@@ -224,12 +225,10 @@ function ensureConversation(state) {
|
||||
if (!last.conversation) {
|
||||
entry = appendChat(DIR, { kind: "reset", conversation: 1, workflow: state.workflow, reason: "start" });
|
||||
} else if (
|
||||
last.workflow !== state.workflow &&
|
||||
// The same switches `open --resume` treats as a hop (a blank page, the
|
||||
// agent's replies included): through the dashboard, or into git from
|
||||
// anywhere (Commit it now, Changelog's "Commit this now?"). Without a new
|
||||
// conversation, the old questions would show as unanswered again.
|
||||
(last.workflow === "dashboard" || state.workflow === "dashboard" || state.workflow === "git")
|
||||
// The same hops `open --resume` treats as a fresh start, by the rule in
|
||||
// public/hops.js (a blank page, the agent's replies included). Without a
|
||||
// new conversation, the old questions would show as unanswered again.
|
||||
startsClean(last.workflow, state.workflow)
|
||||
) {
|
||||
entry = appendChat(DIR, {
|
||||
kind: "reset",
|
||||
|
||||
@@ -8,7 +8,7 @@ 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";
|
||||
import { appendJsonLine, HOME_DIR, newestMtime, nowIso, PLAN2CODE_DIR, readJson, readJsonLines, readText, RUNTIME_DIR, SESSIONS_DIR } from "./files.mjs";
|
||||
|
||||
/* -------------------------------------------------------------- sessions */
|
||||
|
||||
@@ -343,9 +343,10 @@ export async function removeScratch(consoleDir, names) {
|
||||
// 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).
|
||||
// the handoffs (old ones go one by one, by age, on open: handoffs.mjs) and
|
||||
// the notepads, removed only one at a time through Cleanup (notepads.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"]);
|
||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "install.json", "models.json", "handoffs", "notepads"]);
|
||||
// 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
|
||||
@@ -372,29 +373,6 @@ async function diskBytes(p) {
|
||||
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";
|
||||
@@ -441,8 +419,11 @@ function completedSpecs(project, now, maxAgeMs) {
|
||||
* `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 }`.
|
||||
* Given a `project`, also its completed specs untouched for `maxAgeMs`. Every
|
||||
* notepad whose newest file is `maxAgeMs` old is listed too, one item per
|
||||
* folder carrying the `folder` it belongs to (null when its meta.json is gone):
|
||||
* this is the only way a notepad is ever removed.
|
||||
* Resolves to `{ items: [{ id, where, name, kind, bytes, folder? }], bytes }`.
|
||||
*/
|
||||
export async function cleanupFindings({
|
||||
consoleDir = HOME_DIR,
|
||||
@@ -463,12 +444,21 @@ export async function cleanupFindings({
|
||||
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
|
||||
}
|
||||
if (project) found.push(...completedSpecs(project, now, maxAgeMs));
|
||||
// Loaded here, not at the top: notepads.mjs reaches files.mjs through
|
||||
// workspace.mjs, and files.mjs imports this module, so a static import
|
||||
// would run workspace.mjs before files.mjs has defined HOME_DIR.
|
||||
const { staleNotepads } = await import("./notepads.mjs");
|
||||
for (const n of staleNotepads(now, maxAgeMs)) {
|
||||
found.push({ id: "notepad:" + n.key, where: "notepad", name: n.key, kind: "folder", path: n.path, folder: n.folder });
|
||||
}
|
||||
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 });
|
||||
const item = { id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path };
|
||||
if (f.where === "notepad") item.folder = f.folder;
|
||||
items.push(item);
|
||||
}
|
||||
return { items, bytes };
|
||||
}
|
||||
@@ -483,13 +473,15 @@ export async function cleanupFindings({
|
||||
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 { removeNotepad } = await import("./notepads.mjs");
|
||||
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);
|
||||
if (item.where === "notepad") removeNotepad(item.name);
|
||||
else 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;
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// Plan2Code Web Console - how a spec's markdown files are read.
|
||||
//
|
||||
// The task markers and the task-line, checkbox and Status-line patterns, in
|
||||
// one place, so every reader of a spec counts and names its tasks the same
|
||||
// way. Imported by scan.mjs (the dashboard's spec states), patches.mjs (a doc
|
||||
// block's `select: "tasks"`) and src/skill-scripts/specs.mjs (through
|
||||
// consoleModule(), so the installed skill reads with this same copy). No
|
||||
// imports and nothing runs at load but building the patterns.
|
||||
|
||||
// What each checkbox marker means on a task line.
|
||||
export const MARKERS = Object.freeze({ " ": "pending", "/": "in-progress", x: "complete", X: "complete", "!": "blocked", "?": "assumed" });
|
||||
|
||||
// A phase file's task line (`- [ ] **Task 1.2:**`, `* [x] **Task 1.2:**` or
|
||||
// `1. [/] **Task 1.2:**`). The scan counts by it, and patches.mjs keeps only
|
||||
// these lines for a doc block's `select: "tasks"`. Same line shape as
|
||||
// TASK_ID_RE and CHECKBOX_RE (one space before the box, a capital Task), so a
|
||||
// line the scan counts is one specs.mjs counts too.
|
||||
export const TASK_LINE_RE = /^\s*(?:[-*]|\d+\.) \[.\]\s+\*\*Task\s/;
|
||||
|
||||
// A task line taken apart: the marker, the phase number, the task (2.3, a
|
||||
// lettered sub-task 3.6a, or a named one such as a testing task 1.T) and the
|
||||
// sub-task suffix.
|
||||
export const TASK_ID_RE = /^\s*(?:[-*]|\d+\.) \[(.)\]\s+\*\*Task\s+(\d+)\.(\d+|[A-Za-z]+)([a-z]*)\b/;
|
||||
|
||||
// Any checkbox list item, task or not; group 1 is the marker.
|
||||
export const CHECKBOX_RE = /^\s*(?:[-*]|\d+\.) \[(.)\]/;
|
||||
|
||||
// The Status line in any of the forms people write it: **Status:**, **Status**:
|
||||
// or a plain Status:, optionally as a list item. Groups: everything up to the
|
||||
// value (kept as written when the value is rewritten), the value, trailing
|
||||
// blanks. A CRLF file's `\r` is never in the value: a multiline `$` stops
|
||||
// before it.
|
||||
export const STATUS_RE = /^([ \t]*(?:[-*][ \t]*)?(?:\*\*Status:\*\*|\*\*Status\*\*:|Status:)[ \t]*)(.+?)([ \t]*)$/m;
|
||||
|
||||
/** A spec file's Status line value, or null when it has none. */
|
||||
export function statusOf(text) {
|
||||
const m = (text || "").match(STATUS_RE);
|
||||
return m ? m[2] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A phase file's tasks by where they stand. The task lines when the file has
|
||||
* them, so an Acceptance Criteria checkbox is not counted as a task; every
|
||||
* checkbox in a file written before that format. `[?]` (assumed done) is
|
||||
* counted apart from `[x]`; an unknown marker is not counted at all.
|
||||
*/
|
||||
export function countTasks(text) {
|
||||
const lines = (text || "").split(/\r?\n/);
|
||||
const tasks = lines.filter((l) => TASK_LINE_RE.test(l));
|
||||
let done = 0;
|
||||
let assumed = 0;
|
||||
let open = 0;
|
||||
for (const line of tasks.length ? tasks : lines) {
|
||||
const m = line.match(CHECKBOX_RE);
|
||||
if (!m) continue;
|
||||
if (m[1] === "x" || m[1] === "X") done++;
|
||||
else if (m[1] === "?") assumed++;
|
||||
else if (m[1] === " " || m[1] === "/" || m[1] === "!") open++;
|
||||
}
|
||||
return { done, assumed, open, total: done + assumed + open };
|
||||
}
|
||||
@@ -23,6 +23,7 @@ export const SERVABLE = new Set([
|
||||
"app.js",
|
||||
"answers.js",
|
||||
"skills.js",
|
||||
"hops.js",
|
||||
"spec-states.js",
|
||||
"state.js",
|
||||
"doc-files.js",
|
||||
@@ -68,8 +69,11 @@ export const SERVABLE = new Set([
|
||||
"screens/help-dialog.js",
|
||||
"screens/workspace.js",
|
||||
"screens/ask.js",
|
||||
"screens/notepad.js",
|
||||
"net.js",
|
||||
"notepad.js",
|
||||
"vendor/marked.esm.js",
|
||||
"vendor/overtype.esm.js",
|
||||
]);
|
||||
|
||||
/* ------------------------------------------------------------ stylesheet */
|
||||
@@ -79,7 +83,7 @@ export const SERVABLE = new Set([
|
||||
// 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"];
|
||||
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", "notepad.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
|
||||
|
||||
Reference in new issue
Block a user