Add the web console Notepad and shared skill tables, release v2.10.0

AI Assisted
This commit is contained in:
jparkerweb committed 2026-10-19 15:56:52 -07:00
1 parent 124beb46db
commit f8b54ef708
59 files changed
+12549 -321

No files matched your search

+21 -38
View File
@@ -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 */
+2 -1
View File
@@ -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();
+23
View File
@@ -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";
}
+81 -25
View File
@@ -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. -->
+13 -45
View File
@@ -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").
+201
View File
@@ -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;
}
+6 -1
View File
@@ -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);
}
+13 -9
View File
@@ -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",
+23 -5
View File
@@ -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));
+652
View File
@@ -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 = "";
});
}
+3 -2
View File
@@ -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"));
+44 -12
View File
@@ -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) {
+14 -12
View File
@@ -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();
}
File diff suppressed because it is too large. Load diff