Harden the shared console install, launcher, Loop staging, spec state and prompts

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-08 13:48:28 -08:00
1 parent 120c259d9c
commit 3ee96834bf
130 files changed
+5988 -1434

No files matched your search

+2 -3
View File
@@ -18,10 +18,9 @@ A quick-task finish carries `review` and `dashboard:true` and waits for whicheve
| `__done` | `stop` the server: the session is over |
| `wait` exit 20 | `open --resume <sid> --workflow <yours>`, give the new link, keep waiting |
**Read `references/review.md`** and run Review Mode with these overrides:
**Read `references/review.md`** and run the review as `references/review-in-build.md` says (on Finalize, Step 2.5 adds the whole feature's scope). Only what the page does differently is here:
- Scope is Focused and decided: the exact change set of this session (files created or modified by the phase or the quick task, or by the whole feature on Finalize, plus the tests and docs changed for it). Do not ask about scope. `overview.md` and the phase file give spec compliance; they do not widen scope.
- The helper rule applies: a fresh helper runs the analysis when available, you verify every finding, and the report carries its Reviewed by line.
- Scope is decided and not asked: the change set of this session. On Finalize it is the whole feature's (Step 2.5), not one phase.
- No commit instructions and no next-conversation routing mid-review; the way back out carries both.
- The page takes the whole report: the "top 10 of 15+" rule does not apply, and tables go in the doc.
+23 -6
View File
@@ -7,6 +7,7 @@ import { spawn } from "node:child_process";
import { HERE, HOME_DIR, SESSIONS_DIR, appendEvent, ensureDir, nowIso, readJson, updateState } from "./files.mjs";
import {
CONSOLE_VERSION_DIR,
appendLedger,
bindLoopback,
handOff,
@@ -93,6 +94,9 @@ function trace(what) {
// install dirs again. Written by `open` alone, which starts every session: a
// `wait` or a `post` every few seconds need not rewrite it each time.
function leavePointer() {
// Only an installed console (a version folder) leaves it: a source checkout or an old per-skill
// copy pointing console-dir at itself would leave every skill stub unable to find the shared one.
if (!CONSOLE_VERSION_DIR.test(path.basename(HERE))) return;
try {
ensureDir(HOME_DIR);
fs.writeFileSync(path.join(HOME_DIR, "console-dir"), HERE + "\n");
@@ -686,16 +690,23 @@ async function startServer(project, worktree, sid, dir, { handoff = true, noBrow
ensureDir(path.dirname(handlePath), 0o700);
fs.rmSync(handlePath, { force: true });
// The token never goes on the command line, where any process on the
// machine can read it (ps, Task Manager, /proc/<pid>/cmdline). It waits in a
// one-shot file in the private session folder, named afresh for each spawn
// so two opens racing on one session cannot read each other's, and the
// server deletes it as soon as it has read it.
const tokenName = `server-token-${newToken().slice(0, 12).replace(/[^A-Za-z0-9]/g, "x")}`;
const tokenPath = path.join(dir, tokenName);
fs.writeFileSync(tokenPath, token, { mode: 0o600 });
const logFd = fs.openSync(path.join(dir, "server.log"), "a");
const child = spawn(
process.execPath,
[
path.join(HERE, "server.mjs"),
// Always `--flag=value`, never two words: a base64url token can start
// with "--", and parseArgs would read it as the next flag and leave the
// server with `token: true`. The paths get the same form for the same reason.
// Always `--flag=value`, never two words: parseArgs would read a value
// that starts with "--" as the next flag.
`--session=${dir}`,
`--token=${token}`,
`--token-file=${tokenName}`,
`--project=${project}`,
// The checkout the session runs in, which the state does not hold yet
// on a fresh open. See WORKTREE in server.mjs.
@@ -721,8 +732,14 @@ async function startServer(project, worktree, sid, dir, { handoff = true, noBrow
);
fs.closeSync(logFd);
let exited = false;
child.on("exit", () => (exited = true));
child.on("error", () => (exited = true));
// A server that never started never took its token file: do not leave it.
const dropTokenFile = () => {
try {
fs.rmSync(tokenPath, { force: true });
} catch {}
};
child.on("exit", () => ((exited = true), dropTokenFile()));
child.on("error", () => ((exited = true), dropTokenFile()));
trace("open: server spawned");
let opened = null;
+10 -2
View File
@@ -1,8 +1,10 @@
// Plan2Code Web Console - `post` and `wait`: publish a patch, then collect what the person sent.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { CONSOLE_VERSION_DIR } from "./sessions.mjs";
import { HERE, appendEvent, fileStamp, nowIso, readJson, sleepSync, updateState, writeJsonAtomic } from "./files.mjs";
import {
appendLedger,
@@ -716,8 +718,14 @@ const HOP_ACTIONS = {
// flagged so the agent says so. In a
// source tree no skill sits beside the console, so nothing can be told to be
// missing and the stored skill stands.
// The console is shared (~/.plan2code/console/<version>/), so the skills are
// found in the agent skills store; the folder three levels up holds them only
// when a skill carries its own console.
function skillPath(skill) {
return path.resolve(HERE, "..", "..", "..", skill, "SKILL.md");
const candidates = [path.resolve(HERE, "..", "..", "..", skill, "SKILL.md")];
// Only an installed console (a version folder) looks in the store: a source tree names no skill file.
if (CONSOLE_VERSION_DIR.test(path.basename(HERE))) candidates.push(path.join(os.homedir(), ".agents", "skills", skill, "SKILL.md"));
return candidates.find((file) => fs.existsSync(file)) || candidates[0];
}
function pickupHop(action) {
@@ -742,7 +750,7 @@ function pickupHop(action) {
function handoffFor(result) {
const actions = (result && Array.isArray(result.actions) && result.actions) || [];
if (!actions.some((a) => a && a.type === "stop" && a.i === "__stop" && a.handoff === true)) return {};
const file = path.resolve(HERE, "..", "..", "..", "plan2code-handoff", "SKILL.md");
const file = skillPath("plan2code-handoff");
return fs.existsSync(file) ? { handoffSkill: file } : {};
}
+6 -5
View File
@@ -4,7 +4,7 @@ import fs from "node:fs";
import path from "node:path";
import { SESSIONS_DIR, appendEvent, readJson } from "./files.mjs";
import { attachmentName, healthOk, listHandles, pidAlive, projectRoot, repoRoots, sessionDir } from "./sessions.mjs";
import { SERVER_MAX_LIFE_MS, attachmentName, healthOk, listHandles, pidAlive, projectRoot, repoRoots, resultWaiting, sessionDir } from "./sessions.mjs";
import { removeSpec } from "./scan.mjs";
import { isOpen, rule } from "./patches.mjs";
import { pendingChatCount } from "./inbox.mjs";
@@ -19,9 +19,6 @@ export function useCli(cli) {
({ args, print, die, mustSession, sessionProject } = cli);
}
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
// still be one of our servers, so its pid gets no second look.
const MAX_SERVER_LIFE_MS = 4 * 60 * 60 * 1000;
/* ----------------------------------------------------------------- keep */
@@ -284,7 +281,11 @@ export async function cmdStop() {
// minute ago leaves exactly that behind for any process to inherit. A
// busy server gets a second, longer look, and still has to answer as
// ours; one that does not is left alone, and only its handle goes.
const young = Date.now() - Date.parse(h.startedAt || 0) < MAX_SERVER_LIFE_MS;
// A handle past the server's lifetime cap cannot still be one of our
// servers, so its pid gets no second look, unless the session holds
// answers nobody collected: the server outlives its cap for those.
const young =
Date.now() - Date.parse(h.startedAt || 0) < SERVER_MAX_LIFE_MS || (h.stateDir ? resultWaiting(h.stateDir) : false);
const ours = (await healthOk(h)) || (young && pidAlive(h.pid) && (await healthOk(h, 5000)));
if (!ours) {
skipped++;
+15 -6
View File
@@ -193,9 +193,10 @@ export function appendEvent(dir, event) {
// writes it back, so two of them overlapping lose whichever wrote first. Every
// read-modify-write of state.json therefore runs under this lock, a file
// created with O_EXCL beside it. The sections it guards are a read, a merge
// and a write, milliseconds long, so a lock older than LOCK_STALE_MS, or one
// whose holder has died, is a crash left behind and is broken. The wait runs
// past the stale age, so a writer always gets in eventually.
// and a write, milliseconds long, so a lock whose holder has died is a crash
// left behind and is broken; age alone breaks one only when no live holder is
// named (lockStale below). The wait runs past the stale age, so a writer
// always gets in once the holder is done or gone.
export const STATE_LOCK_FILE = "state.json.lock";
const LOCK_STALE_MS = 5000;
// A pile-up of many writers (a burst of concurrent `post`s) queues behind
@@ -204,12 +205,20 @@ const LOCK_STALE_MS = 5000;
// writer that was never going to be denied, just slow to get its turn.
const LOCK_WAIT_MS = 20000;
function lockStale(lock) {
// The holder's pid decides first: a lock whose holder is still running is
// held, however old it looks (a writer under a heavy machine can sit past the
// stale age, and breaking its lock lets two writers in at once), and one whose
// holder is gone is free at once. Age decides only when the pid cannot: an
// empty file (the holder is between its create and its write, or died there)
// or this process's own pid (a hold is synchronous, so a lock naming us while
// we wait for it is a leftover from a process that had our number).
export function lockStale(lock) {
try {
const st = fs.statSync(lock);
if (Date.now() - st.mtimeMs > LOCK_STALE_MS) return true;
const old = Date.now() - st.mtimeMs > LOCK_STALE_MS;
const pid = Number.parseInt(fs.readFileSync(lock, "utf8"), 10);
return Number.isInteger(pid) && pid > 0 && pid !== process.pid && !pidAlive(pid);
if (!Number.isInteger(pid) || pid <= 0 || pid === process.pid) return old;
return !pidAlive(pid);
} catch (err) {
// Gone between the failed create and this look: free, so try again.
return err.code === "ENOENT";
+12 -1
View File
@@ -19,8 +19,15 @@ export { prUrl };
/* ----------------------------------------------------------- running git */
// Every call here is a local read, milliseconds long. A git that hangs (a
// credential helper waiting on a prompt nobody sees, a network drive gone
// away, a hook or fsmonitor stuck) would otherwise hold the server's single
// thread, and every page with it, for good. A caller may pass its own limit;
// 0 means none.
export const GIT_TIMEOUT_MS = 10000;
/** Run git with an args array (never a shell). { ok, out, err }. */
export function git(args, cwd, { raw = false, timeout } = {}) {
export function git(args, cwd, { raw = false, timeout = GIT_TIMEOUT_MS } = {}) {
try {
const stdout = execFileSync("git", args, {
cwd,
@@ -34,6 +41,7 @@ export function git(args, cwd, { raw = false, timeout } = {}) {
});
return { ok: true, out: raw ? stdout : stdout.trim(), err: "" };
} catch (e) {
if (e?.code === "ETIMEDOUT") return { ok: false, out: "", err: `git did not finish within ${timeout / 1000}s` };
return { ok: false, out: "", err: String(e?.stderr || e?.message || "").trim() };
}
}
@@ -512,6 +520,9 @@ export function snapshot(worktree, { prHosts = {} } = {}) {
if (!floor.ok) return { at, repo: true, error: floor.message };
const status = git(["status", "--porcelain=v2", "-z", "--branch", "--untracked-files=normal"], worktree, { raw: true });
if (!status.ok && !git(["rev-parse", "--git-dir"], worktree).ok) return { at, repo: false };
// A repository whose status failed (or ran past git()'s time limit) has an
// unknown tree, never a clean one: say so rather than draw an empty board.
if (!status.ok) return { at, repo: true, error: status.err || "git status failed." };
const parsed = safe(() => parseStatusV2(status.out), parseStatusV2(""));
// The branch table's for-each-ref already reads every ref: the default
// branch comes off it instead of three more probes. When it is empty the
+1 -1
View File
@@ -41,7 +41,7 @@ On `show`, run the workflow's **Show me it working** paragraph. Save screenshots
Do what the workflow does on approval and print it in the terminal as usual, then:
```jsonc
{"settle":true,"run":{"event":"implement-phase","id":"phase-3","tasks":9},"finish":{"headline":"Phase 3 is done","body":"9 of 9 tasks, all on disk.\n\n| Phase | Tasks | Goal |\n| --- | --- | --- |\n| Phase 4: ... | 6 | ... |\n\nCommit it with:\n\n```\ngit add -A && git commit -m \"...\" -m \"AI Assisted\"\n```","command":"/plan2code-3-implement specs/lunch-vote/overview.md","doc":"report","commit":true,"dashboard":true}}
{"settle":true,"run":{"event":"implement-phase","id":"phase-3","tasks":9},"finish":{"headline":"Phase 3 is done","body":"9 of 9 tasks, all on disk.\n\n| Phase | Tasks | Goal |\n| --- | --- | --- |\n| Phase 4: ... | 6 | ... |\n\nCommit it with:\n\n```\ngit add -- src/vote.js && git commit -m \"...\" -m \"AI Assisted\"\n```","command":"/plan2code-3-implement specs/lunch-vote/overview.md","doc":"report","commit":true,"dashboard":true}}
```
`commit:true` only when the body prints a commit. `command` is the next step: `/plan2code-3-implement specs/<feature>/overview.md`, or `/plan2code-4-finalize specs/<feature>/overview.md` after the last phase. No `review` on the finish.
+14 -8
View File
@@ -689,11 +689,15 @@ const JARGON = [
const FORBIDDEN_TOKENS =
/\b(TASK_COMPLETE|PHASE_COMPLETE|ALL_TASKS_COMPLETE|IMPLEMENTATION_COMPLETE|SPEC_COMPLETE|WORK_COMPLETE)\b/;
// plan2code-metrics scrapes confidence with patterns that do NOT require a
// percent sign, so a bare "Requirements 22" in a rendered doc can poison a run's
// metrics. Keep those four words away from bare numbers. The skill scripts'
// copy is SCRAPE in src/skill-scripts/common.mjs; keep the two in step.
const METRICS_BAIT = /\b(Requirements?|Feasibility|Integration|Risk)[:\s|]+\d{1,2}\b/;
// plan2code-metrics scrapes the confidence breakdown from a rendered doc, so a
// label and score it reads must not appear in agent text. The shapes live in
// metrics-pattern.json beside this file; the skill scripts' copy is SCRAPE in
// src/skill-scripts/common.mjs and the collector's is
// plan2code-metrics/src/metrics-pattern.json. A test fails when they drift.
const METRICS_BAIT = JSON.parse(fs.readFileSync(new URL("./metrics-pattern.json", import.meta.url), "utf8")).breakdown.map((b) => ({
name: b.name,
re: new RegExp(b.source, b.flags),
}));
// The marker and metrics-bait scan on its own, for agent text that never
// reaches state.json (a post's `run` / `folderIssue`). Problems as sentences.
@@ -705,11 +709,13 @@ export function proseProblems(prose, subject = "text") {
rule("", subject, `contains a loop completion marker (${marker[0]}); these are reserved. Reword it`, marker[0].toLowerCase().replaceAll("_", " ")),
);
}
const bait = prose.match(METRICS_BAIT);
if (bait) {
for (const { name, re } of METRICS_BAIT) {
const bait = prose.match(re);
if (!bait) continue;
problems.push(
rule("", subject, `contains ${JSON.stringify(bait[0])}; the metrics collector scrapes that pattern. Hyphenate it or reword`, `${bait[1]}-score ${bait[0].match(/\d+$/)[0]}`),
rule("", subject, `contains ${JSON.stringify(bait[0].trim())}; the metrics collector scrapes that pattern. Hyphenate it or reword`, `${name}-score ${bait[1]}`),
);
break;
}
return problems;
}
+3
View File
@@ -700,6 +700,9 @@ export function cardAvailability(entry, scan, sel, lookup = stateFor) {
// Always on; a diagnosed bug is the one spec Quick Task is the next step for.
if (rule.states === "any") return next ? { ...ON, next } : ON;
// A building spec whose only unfinished tasks are blocked, each with a
// written reason (the scan's finalizeReady), is ready for Finalize too.
if (entry.skill === "plan2code-4-finalize" && state === "building" && sel.finalizeReady === true) return ON;
// A state the table does not know is treated like files on disk.
const taken = !sel || !sel.state ? "none" : lookup(sel.state) ? sel.state : "unrecognized";
if (rule.states.includes(taken)) return rule.marksNext ? { ...ON, next } : ON;
+8 -7
View File
@@ -1095,7 +1095,7 @@
it shuts itself down <span data-fact="closedTabMinutes">2</span> minutes
later. It also stops after <span data-fact="idleMinutes">30</span>
minutes without hearing from anyone, and after
<span data-fact="maxLifeHours">4</span> hours regardless. Reopening the same link brings everything back: nothing you
<span data-fact="maxLifeHours">4</span> hours unless answers you sent are still waiting for the agent. Reopening the same link brings everything back: nothing you
typed is kept in the browser alone.
</p>
<p class="for-app">
@@ -1103,7 +1103,7 @@
window and it shuts itself down <span data-fact="closedTabMinutes">2</span>
minutes later. It also stops after <span data-fact="idleMinutes">30</span>
minutes without hearing from anyone, and after
<span data-fact="maxLifeHours">4</span> hours regardless. When it
<span data-fact="maxLifeHours">4</span> hours unless answers you sent are still waiting for the agent. When it
stops, the app's own bar notices and brings it back on the same
session, or offers <strong>Reconnect the console</strong>: nothing you
typed is kept in the window alone.
@@ -1287,8 +1287,8 @@
from anyone, or
</li>
<li>
after <span data-fact="maxLifeHours">4</span> hours, whatever is
happening.
after <span data-fact="maxLifeHours">4</span> hours, unless answers
you sent are still waiting for the agent.
</li>
</ul>
<p id="help-stuck-reconnect-text">
@@ -3374,8 +3374,9 @@
<code>~/.plan2code</code> folder: sessions nobody has opened for
30 days, and files or folders that ended up there by mistake. It
also lists this project's <code>specs--completed/</code> folders
nobody has touched for 30 days; deleting one is permanent, since
that folder is usually gitignored and git can't restore it. It
nobody has touched for 30 days, and deletes one only when git
tracks it, so git can restore it; one git does not track (the
folder is usually gitignored) is kept, with the reason shown. It
shows each one with its size, and <strong>Delete these</strong>
removes exactly that list. Your preferences, saved folders, models,
the launcher and the session you are in always stay, and the
@@ -3641,7 +3642,7 @@
<section class="prefs-panel" data-tab="system">
<fieldset data-section="cleanup" class="modal-ranges">
<legend>Cleanup</legend>
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. It also lists this project's <code>specs--completed/</code> folders nobody has touched for 30 days; deleting one is permanent, since that folder is usually gitignored and git can't restore it. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. It also lists this project's <code>specs--completed/</code> folders nobody has touched for 30 days, and deletes one only when git tracks it, so git can restore it; one git does not track (the folder is usually gitignored) is kept, with the reason shown. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
<div class="models-actions">
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
+126 -61
View File
@@ -18,27 +18,44 @@
// editable surface, everything else on the host. field.el is the host div to
// append; host.field is the facade itself, so a page test or a helper can
// drive it.
import {
Compartment,
EditorState,
EditorView,
defaultKeymap,
history,
historyKeymap,
keymap,
markdown,
markdownLanguage,
placeholder,
redo,
} from "./vendor/codemirror.esm.js";
import { livePreview } from "./notepad-editor.js";
//
// CodeMirror (half a megabyte) is not part of the page's start: it is
// imported the first time a field is made, and every field after that gets
// its editor at once. A field made before the import lands keeps what is set
// on it (value, caret, disabled, aria-*, a focus asked for) and hands it to
// its editor when it arrives. destroy() ends the editor; renderMain() calls
// it, through destroyFields(), on every field it takes off the page.
// These listeners run as the editor's own DOM handlers, before its keymaps:
// a preventDefault there (the mention popover's keys, a pure-image paste)
// still beats CodeMirror's own handling.
const HANDLED = ["keydown", "keyup", "paste", "blur", "focus"];
// CodeMirror's exports plus the live preview, once loaded; the import itself
// while it is on its way. A failed import is forgotten, so the next field
// asks again.
let cm = null;
let loading = null;
function loadEditor() {
loading ??= Promise.all([import("./vendor/codemirror.esm.js"), import("./notepad-editor.js")]).then(
([lib, editor]) => (cm = { ...lib, livePreview: editor.livePreview }),
(err) => {
loading = null;
throw err;
}
);
return loading;
}
// Ends the editor of every Markdown field inside `root` (root included), for
// a caller about to drop that part of the page.
export function destroyFields(root) {
if (!root || typeof root.querySelectorAll !== "function") return;
if (root.field && typeof root.field.destroy === "function") root.field.destroy();
for (const host of root.querySelectorAll(".md-host")) if (host.field) host.field.destroy();
}
export function makeMdField({ id, className, value = "", placeholder: hint, label, disabled = false, maxLength = 0 } = {}) {
const host = document.createElement("div");
host.className = "md-host" + (className ? " " + className : "");
@@ -61,76 +78,110 @@ export function makeMdField({ id, className, value = "", placeholder: hint, labe
};
let off = Boolean(disabled);
const access = new Compartment();
// editable, not only readOnly: a disabled field cannot take the focus,
// which is the difference a textarea's own disabled attribute shows.
let view = null;
let gone = false;
// What the field holds until its editor arrives.
let text = String(value ?? "");
let sel = null;
let wantFocus = false;
const aria = new Map();
let access = null;
let stateOf = null;
const accessOf = (on) =>
on
? [
EditorState.readOnly.of(true),
EditorView.editable.of(false),
EditorView.contentAttributes.of({ "aria-disabled": "true" }),
cm.EditorState.readOnly.of(true),
cm.EditorView.editable.of(false),
cm.EditorView.contentAttributes.of({ "aria-disabled": "true" }),
]
: [];
const extensions = [
history(),
keymap.of([{ key: "Mod-Shift-z", run: redo, preventDefault: true }, ...defaultKeymap, ...historyKeymap]),
markdown({ base: markdownLanguage }),
livePreview,
EditorView.lineWrapping,
EditorView.contentAttributes.of({ "aria-label": label || "Markdown text", "aria-multiline": "true", spellcheck: "true" }),
EditorView.domEventHandlers(Object.fromEntries(HANDLED.map((type) => [type, (event) => fire(type, event)]))),
EditorView.updateListener.of((update) => {
if (update.docChanged) fire("input");
}),
...(hint ? [placeholder(hint)] : []),
...(maxLength
? [
EditorState.transactionFilter.of((tr) => {
if (!tr.docChanged || tr.newDoc.length <= maxLength) return tr;
return {
changes: { from: 0, to: tr.startState.doc.length, insert: tr.newDoc.sliceString(0, maxLength) },
selection: { anchor: Math.min(tr.newSelection.main.head, maxLength) },
};
}),
]
: []),
];
const stateOf = (text) => EditorState.create({ doc: text, extensions: [...extensions, access.of(accessOf(off))] });
const view = new EditorView({ state: stateOf(String(value ?? "")), parent: mount, root });
// The stylesheets arrive after the first measure: measure again once they
// have, or the lines would keep their unstyled height until the next edit.
for (const sheet of sheets) sheet.addEventListener("load", () => view.requestMeasure());
const build = () => {
const { Compartment, EditorState, EditorView, defaultKeymap, history, historyKeymap, keymap, markdown, markdownLanguage, placeholder, redo, livePreview } = cm;
access = new Compartment();
// editable, not only readOnly: a disabled field cannot take the focus,
// which is the difference a textarea's own disabled attribute shows.
const extensions = [
history(),
keymap.of([{ key: "Mod-Shift-z", run: redo, preventDefault: true }, ...defaultKeymap, ...historyKeymap]),
markdown({ base: markdownLanguage }),
livePreview,
EditorView.lineWrapping,
EditorView.contentAttributes.of({ "aria-label": label || "Markdown text", "aria-multiline": "true", spellcheck: "true" }),
EditorView.domEventHandlers(Object.fromEntries(HANDLED.map((type) => [type, (event) => fire(type, event)]))),
EditorView.updateListener.of((update) => {
if (update.docChanged) fire("input");
}),
...(hint ? [placeholder(hint)] : []),
...(maxLength
? [
EditorState.transactionFilter.of((tr) => {
if (!tr.docChanged || tr.newDoc.length <= maxLength) return tr;
return {
changes: { from: 0, to: tr.startState.doc.length, insert: tr.newDoc.sliceString(0, maxLength) },
selection: { anchor: Math.min(tr.newSelection.main.head, maxLength) },
};
}),
]
: []),
];
stateOf = (t) => EditorState.create({ doc: t, extensions: [...extensions, access.of(accessOf(off))] });
view = new EditorView({ state: stateOf(text), parent: mount, root });
// The stylesheets arrive after the first measure: measure again once they
// have, or the lines would keep their unstyled height until the next edit.
for (const sheet of sheets) sheet.addEventListener("load", () => view.requestMeasure());
if (sel) {
const end = view.state.doc.length;
view.dispatch({ selection: { anchor: Math.min(sel[0], end), head: Math.min(sel[1], end) } });
}
for (const [name, val] of aria) {
if (val == null) view.contentDOM.removeAttribute(name);
else view.contentDOM.setAttribute(name, val);
}
aria.clear();
if (wantFocus && host.isConnected) view.focus();
};
const field = {
el: host,
view,
get value() {
return view.state.doc.toString();
get view() {
return view;
},
set value(text) {
get value() {
return view ? view.state.doc.toString() : text;
},
set value(t) {
// setState neither reports a change nor keeps the undo steps, exactly
// the swap a textarea's value assignment makes. A fresh state parks its
// caret at 0; a textarea's collapses to the end, so callers that fill
// and focus (Autofill, quick answers, Reset to default) append as they
// used to.
view.setState(stateOf(String(text ?? "")));
if (!view) {
text = String(t ?? "");
sel = [text.length, text.length];
return;
}
view.setState(stateOf(String(t ?? "")));
view.dispatch({ selection: { anchor: view.state.doc.length } });
},
get selectionStart() {
if (!view) return sel ? Math.min(sel[0], sel[1]) : 0;
const m = view.state.selection.main;
return Math.min(m.anchor, m.head);
},
get selectionEnd() {
if (!view) return sel ? Math.max(sel[0], sel[1]) : 0;
const m = view.state.selection.main;
return Math.max(m.anchor, m.head);
},
setSelectionRange(a, b) {
view.dispatch({ selection: { anchor: a, head: b } });
if (!view) sel = [a, b ?? a];
else view.dispatch({ selection: { anchor: a, head: b } });
},
focus() {
view.focus();
if (view) view.focus();
else wantFocus = true;
},
get disabled() {
return off;
@@ -138,7 +189,7 @@ export function makeMdField({ id, className, value = "", placeholder: hint, labe
set disabled(on) {
off = Boolean(on);
host.classList.toggle("is-disabled", off);
view.dispatch({ effects: access.reconfigure(accessOf(off)) });
if (view) view.dispatch({ effects: access.reconfigure(accessOf(off)) });
},
get classList() {
return host.classList;
@@ -150,10 +201,14 @@ export function makeMdField({ id, className, value = "", placeholder: hint, labe
return host.getBoundingClientRect();
},
setAttribute(name, val) {
(name.startsWith("aria-") ? view.contentDOM : host).setAttribute(name, val);
if (!name.startsWith("aria-")) host.setAttribute(name, val);
else if (view) view.contentDOM.setAttribute(name, val);
else aria.set(name, String(val));
},
removeAttribute(name) {
(name.startsWith("aria-") ? view.contentDOM : host).removeAttribute(name);
if (!name.startsWith("aria-")) host.removeAttribute(name);
else if (view) view.contentDOM.removeAttribute(name);
else aria.set(name, null);
},
addEventListener(type, fn) {
if (!listeners.has(type)) listeners.set(type, new Set());
@@ -172,11 +227,21 @@ export function makeMdField({ id, className, value = "", placeholder: hint, labe
fire("input");
},
destroy() {
if (gone) return;
gone = true;
listeners.clear();
view.destroy();
if (view) view.destroy();
},
};
if (off) host.classList.add("is-disabled");
host.field = field;
if (cm) build();
else
loadEditor().then(
() => {
if (!gone) build();
},
() => {}
);
return field;
}
+34 -1
View File
@@ -305,13 +305,46 @@ function blockInto(parent, tokens) {
}
}
// The token trees of recent md() sources, newest last, so a redraw that draws
// the same Markdown again (every agent post redraws every card) skips the
// lexer. Only the tokens are kept, never the DOM: md() still builds fresh
// nodes with their own listeners each call, so a caller may change what it
// gets back. Bounded by count and by total source length; a source over the
// length cap on its own is never kept.
const MD_CACHE_ENTRIES = 200;
const MD_CACHE_CHARS = 2_000_000;
const mdCache = new Map();
let mdCacheChars = 0;
function lexed(text) {
const hit = mdCache.get(text);
if (hit) {
mdCache.delete(text);
mdCache.set(text, hit);
// A copy: drawing takes a task marker off its token (takeMarker), and the
// kept tree must stay as the lexer made it.
return structuredClone(hit);
}
const tokens = marked.lexer(text);
if (text.length <= MD_CACHE_CHARS) {
mdCache.set(text, structuredClone(tokens));
mdCacheChars += text.length;
for (const [key] of mdCache) {
if (mdCache.size <= MD_CACHE_ENTRIES && mdCacheChars <= MD_CACHE_CHARS) break;
mdCache.delete(key);
mdCacheChars -= key.length;
}
}
return tokens;
}
/** Render markdown into a fresh element. Returns the element. */
export function md(source, className = "md", options = {}) {
const host = el("div", className);
if (!source) return host;
let tokens;
try {
tokens = marked.lexer(String(source));
tokens = lexed(String(source));
} catch {
host.appendChild(el("p", "md-p", String(source)));
return host;
+89 -20
View File
@@ -8,7 +8,7 @@ import { startersFor } from "../starters.js";
import { looks } from "../looks.js";
import { thumbs, uploadUrl, docChip, attachTray, CHAT_IMAGES, attachFiles, incomingFiles, deleteUrl, sentAttachments, noteImages, attachRow, openPicview, refocusThumb } from "../uploads.js";
import { attachMentions } from "../mention-box.js";
import { makeMdField } from "../md-field.js";
import { destroyFields, makeMdField } from "../md-field.js";
import { pickerAccept, attachmentKind, noteAwaiting, threadWho, threadText } from "../answers.js";
import { postJson } from "../net.js";
import { reconnectOffer } from "../continue-button.js";
@@ -29,10 +29,19 @@ export const declineOpen = new Map();
const deciding = new Set();
// The Subagents dialog's instruction box, a Markdown field made once in
// wireAsk into its #subagents-instruction mount.
// The Subagents dialog's instruction box, a Markdown field made the first
// time the dialog needs it, into its #subagents-instruction mount: made at
// start-up, it would pull CodeMirror into every page load (md-field.js).
let instrField = null;
function instr() {
if (!instrField) {
instrField = makeMdField({ className: "subagents-instruction", label: "Instruction", maxLength: 2000 });
$("subagents-instruction").appendChild(instrField.el);
}
return instrField;
}
// The frame's chat block, with `offline` worked out now rather than when the
// frame was sent: the agent comes and goes between frames, and /ping keeps
// agentLastSeen current. The frame's own verdict stands when there is no clock.
@@ -66,7 +75,7 @@ export function askState() {
// frame for the moment after a 409 stale, before the new frame lands.
const askConversation = () => page.local.chat.conversation ?? askFrame().conversation;
export function renderAsk(main) {
export function renderAsk(main, held = null) {
const { frame, view: v, send: ss } = askState();
// Anything drawn here has been seen: no dot for it later.
const newest = newestReplyId(frame);
@@ -77,7 +86,6 @@ export function renderAsk(main) {
page.chatDot = false;
askPaintedOffline = ss.state === "offline";
const pane = el("section", "ask-pane");
const head = el("div", "ask-head");
head.appendChild(el("h2", null, "Quick question"));
head.appendChild(el("span", "ask-counter", v.counterText));
@@ -86,17 +94,42 @@ export function renderAsk(main) {
reset.disabled = ss.state === "offline" || chatResetting;
reset.addEventListener("click", newConversation);
head.appendChild(reset);
pane.appendChild(head);
const list = el("div", "ask-list");
list.setAttribute("role", "log");
list.setAttribute("aria-live", "polite");
if (!v.rows.length) list.appendChild(askStarters(ss));
// The list is a live region (role="log"): one taken up from the last render
// keeps every row that would draw the same, so a redraw announces nothing
// and a new message is one appended row, the only thing read out.
const kept = held && held.querySelector(":scope > .ask-list");
const list = kept || el("div", "ask-list");
if (!kept) {
list.setAttribute("role", "log");
list.setAttribute("aria-live", "polite");
}
const notes = new Map(v.rows.filter((r) => r.kind === "decision").map((r) => [r.re, r.text]));
for (const r of v.rows) list.appendChild(askRow(r, ss, notes));
pane.appendChild(list);
pane.appendChild(askComposer(ss));
main.appendChild(pane);
const wanted = v.rows.length
? v.rows.map((r) => [askRowKey(r, ss, notes), () => askRow(r, ss, notes)])
: [[askStartersKey(ss), () => askStarters(ss)]];
syncRows(list, wanted);
const composer = askComposer(ss);
if (kept) {
const oldHead = held.querySelector(":scope > .ask-head");
const oldComposer = held.querySelector(":scope > .ask-composer");
if (oldHead) oldHead.replaceWith(head);
else held.insertBefore(head, list);
if (oldComposer) {
destroyFields(oldComposer);
oldComposer.replaceWith(composer);
} else held.appendChild(composer);
if (held.parentNode !== main) main.appendChild(held);
} else {
if (held) {
destroyFields(held);
held.remove();
}
const pane = el("section", "ask-pane");
pane.append(head, list, composer);
main.appendChild(pane);
}
// Back where the person left the list, unless something new arrived (or it
// is the first look), which brings the newest row into view.
@@ -106,6 +139,44 @@ export function renderAsk(main) {
list.scrollTop = !saved || grew ? list.scrollHeight : saved.top;
}
// What a row draws from: the row itself and every outside fact askRow() reads,
// so two equal keys draw the same row and the one on the page can stay.
// Each outside fact counts only on the rows that read it, or a send in flight
// (chatSending) would redraw every row in the log.
function askRowKey(r, ss, notes) {
const offline = ss.state === "offline";
if (r.kind === "decision") return JSON.stringify([r]);
if (r.kind === "agent") {
const open = Boolean(r.proposal && !r.decided);
return JSON.stringify([r, notes.get(r.id) ?? null, open && [offline, deciding.has(r.id), declineOpen.has(r.id)]]);
}
return JSON.stringify([
r,
r.pending && r.failed ? [offline, chatSending] : null,
!r.pending && r.waiting && r.working ? [offline, agentAdrift()] : null,
(r.images || []).map((img) => thumbs.get(img.key) || ""),
]);
}
const askStartersKey = (ss) =>
JSON.stringify(["starters", ss.canType, page.S.workflow, looks.role, Boolean(page.local.chat.about)]);
// Brings the live list's children in line with `wanted` ([key, make] pairs,
// in order): a child whose key matches stays untouched, a changed one is
// redrawn in its place, new ones are appended and leftovers removed.
function syncRows(list, wanted) {
const have = [...list.children];
wanted.forEach(([key, make], i) => {
const cur = have[i];
if (cur && cur.dataset.rowKey === key) return;
const node = make();
node.dataset.rowKey = key;
if (cur) cur.replaceWith(node);
else list.appendChild(node);
});
for (const extra of have.slice(wanted.length)) extra.remove();
}
// An empty conversation offers a few questions for this step, the role's
// first. A click only fills the box: nothing is ever sent for the person.
function askStarters(ss) {
@@ -867,7 +938,7 @@ export function openSubagents() {
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) {
radio.checked = radio.value === (on ? "on" : "off");
}
instrField.value = page.subagentsFrame.instruction ?? defaultInstruction(page.S.workflow);
instr().value = page.subagentsFrame.instruction ?? defaultInstruction(page.S.workflow);
$("subagents-max").value = String(page.subagentsFrame.max);
const strength = STRENGTHS.includes(page.subagentsFrame.strength) ? page.subagentsFrame.strength : DEFAULT_STRENGTH;
for (const radio of document.querySelectorAll('input[name="subagents-strength"]')) radio.checked = radio.value === strength;
@@ -889,7 +960,7 @@ export function openSubagents() {
export function syncSubagentsFields() {
const picked = document.querySelector('input[name="subagents-on"]:checked');
const off = !picked || picked.value !== "on";
instrField.disabled = off;
instr().disabled = off;
for (const id of ["subagents-max", "subagents-default"]) $(id).disabled = off;
for (const radio of document.querySelectorAll('input[name="subagents-strength"]')) radio.disabled = off;
}
@@ -914,7 +985,7 @@ export async function saveSubagents() {
const save = $("subagents-save");
const status = $("subagents-status");
const picked = document.querySelector('input[name="subagents-on"]:checked');
const text = instrField.value.trim();
const text = instr().value.trim();
// The shipped default is stored as null, so a later release's wording
// reaches everyone who never changed it.
const instruction = text === defaultInstruction(page.S.workflow) ? null : text;
@@ -942,14 +1013,12 @@ export const askOfflineFlipped = () => (askState().send.state === "offline") !==
// The Subagents dialog's buttons, and dropping files onto the notes panel.
export function wireAsk() {
instrField = makeMdField({ className: "subagents-instruction", label: "Instruction", maxLength: 2000 });
$("subagents-instruction").appendChild(instrField.el);
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) radio.addEventListener("change", syncSubagentsFields);
for (const radio of document.querySelectorAll('input[name="subagents-strength"]')) radio.addEventListener("change", syncStrengthHelp);
lightDismiss($("subagents-modal"));
$("btn-subagents").addEventListener("click", openSubagents);
$("subagents-default").addEventListener("click", () => {
instrField.value = defaultInstruction(page.S.workflow);
instr().value = defaultInstruction(page.S.workflow);
});
$("subagents-save").addEventListener("click", saveSubagents);
$("subagents-cancel").addEventListener("click", () => $("subagents-modal").close());
+30 -4
View File
@@ -880,6 +880,23 @@ function buildChoice(card, item, staged) {
clearRow(card, item);
}
// A small eraser-style mark: a cross in a circle, drawn inline so it takes the
// button's text color in both themes. Hidden from readers; the aria-label names it.
function clearIcon() {
const ns = "http://www.w3.org/2000/svg";
const svg = document.createElementNS(ns, "svg");
svg.setAttribute("viewBox", "0 0 24 24");
svg.setAttribute("width", "14");
svg.setAttribute("height", "14");
svg.setAttribute("aria-hidden", "true");
for (const d of ["M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18z", "M9 9l6 6M15 9l-6 6"]) {
const path = document.createElementNS(ns, "path");
path.setAttribute("d", d);
svg.appendChild(path);
}
return svg;
}
// Takes a one-answer question back to how it arrived: no pick, and nothing in
// "Something else" (its draft too, or the render would put the words straight
// back). A radio group cannot be unticked by clicking it again, so without
@@ -887,8 +904,10 @@ function buildChoice(card, item, staged) {
// call it, and they only run for a form that has not been sent.
function clearRow(card, item) {
const row = el("div", "btn-row options-clear");
const b = el("button", "btn small ghost", "Clear");
const b = el("button", "btn small ghost clear-btn");
b.type = "button";
b.appendChild(clearIcon());
b.appendChild(el("span", null, "Clear answer"));
// An id so focus survives the render the click sets off (see withFocus).
b.id = "clear-" + item.id;
b.setAttribute("aria-label", "Clear your answer to this question");
@@ -1307,9 +1326,16 @@ function buildReview(card, item, staged) {
verdictText(v)
);
b.type = "button";
b.addEventListener("click", () =>
stage(item.id, withNote(item, on ? null : { type: "answer", kind: "review", verdict: v.id }))
);
// A toggle: a screen reader hears which verdict is picked, not only sees
// it in the fill. Set on the row at once, ahead of the redraw the stage
// sets off, so the state never lags the click.
b.setAttribute("aria-pressed", String(Boolean(on)));
b.addEventListener("click", () => {
for (const other of row.querySelectorAll("button[aria-pressed]")) {
other.setAttribute("aria-pressed", String(other === b && !on));
}
stage(item.id, withNote(item, on ? null : { type: "answer", kind: "review", verdict: v.id }));
});
row.appendChild(b);
}
card.appendChild(row);
+35 -14
View File
@@ -46,6 +46,12 @@ function cleanupSummary(items, bytes) {
return parts.join(", ") + " · " + formatBytes(bytes);
}
// A completed spec git does not track as it stands is never deleted (the
// server refuses it), so it is listed apart as kept, out of the total and out
// of what Delete these sends.
const keptBack = (item) => item.where === "completed" && item.tracked === false;
const deletable = () => ((cleanupFound && cleanupFound.items) || []).filter((i) => !keptBack(i));
function resetCleanup() {
cleanupGen++;
cleanupFound = null;
@@ -59,19 +65,28 @@ function resetCleanup() {
function renderCleanup() {
const list = $("cleanup-list");
list.replaceChildren();
const items = (cleanupFound && cleanupFound.items) || [];
const all = (cleanupFound && cleanupFound.items) || [];
const items = deletable();
const kept = all.filter(keptBack);
$("cleanup-delete").hidden = !items.length;
if (!items.length) return;
const rows = (some) => some.map((item) => {
const row = el("div", "cleanup-row");
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", formatBytes(item.bytes)));
return row;
});
list.append(el("p", "cleanup-summary", cleanupSummary(items, cleanupFound.bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
if (items.length > CLEANUP_SHOWN) {
const more = el("details", "cleanup-more");
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
list.appendChild(more);
if (items.length) {
const bytes = Math.max(0, cleanupFound.bytes - kept.reduce((n, i) => n + (i.bytes || 0), 0));
list.append(el("p", "cleanup-summary", cleanupSummary(items, bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
if (items.length > CLEANUP_SHOWN) {
const more = el("details", "cleanup-more");
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
list.appendChild(more);
}
}
for (const item of kept) {
const row = el("div", "cleanup-row cleanup-kept");
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", "kept: git does not track it as it stands"));
list.appendChild(row);
}
}
@@ -93,17 +108,20 @@ async function scanCleanup() {
renderCleanup();
// Left in the status line, not cleared: it is the live region, so this is
// what a screen reader hears when the scan finishes.
const found = cleanupFound.items.length;
setCleanupStatus(found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.", false);
const found = deletable().length;
const keptCount = cleanupFound.items.length - found;
const keptNote = keptCount ? ` ${keptCount} old completed ${keptCount === 1 ? "spec is" : "specs are"} kept: git does not track ${keptCount === 1 ? "it" : "them"} as ${keptCount === 1 ? "it stands" : "they stand"}.` : "";
setCleanupStatus((found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.") + keptNote, false);
}
async function deleteCleanup() {
if (!cleanupFound || !cleanupFound.items.length) return;
const ids = deletable().map((i) => i.id);
if (!ids.length) return;
const gen = ++cleanupGen;
$("cleanup-delete").disabled = true;
$("cleanup-scan").disabled = true;
setCleanupStatus("Deleting…", false);
const { status, body } = await postJson("/cleanup", { delete: cleanupFound.items.map((i) => i.id) });
const { status, body } = await postJson("/cleanup", { delete: ids });
if (gen !== cleanupGen) return;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
@@ -112,15 +130,18 @@ async function deleteCleanup() {
}
const removed = (body.removed || []).length;
const failed = (body.failed || []).length;
// A completed spec git does not track is refused, and the server says why.
const refused = (body.refused || []).length;
// The server re-checks every id and keeps anything that changed since the
// scan; say so, rather than let a count that came up short pass unremarked.
const asked = cleanupFound.items.length;
const kept = Math.max(0, asked - removed - failed);
const asked = ids.length;
const kept = Math.max(0, asked - removed - failed - refused);
cleanupFound = null;
renderCleanup();
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
const keptLine = kept ? ` ${kept} ${kept === 1 ? "was" : "were"} kept because ${kept === 1 ? "it" : "they"} changed since the scan.` : "";
setCleanupStatus((failed ? done + " " + failed + " could not be removed." : done) + keptLine, Boolean(failed));
const refusalLine = refused && body.refusal ? " " + body.refusal : "";
setCleanupStatus((failed ? done + " " + failed + " could not be removed." : done) + keptLine + refusalLine, Boolean(failed || refused));
}
// The Cleanup section's buttons, and starting over whenever Preferences closes.
+36 -12
View File
@@ -65,6 +65,7 @@ import { renderLoopSetup } from "./loop-setup.js";
import { renderLaunching, renderWaiting } from "./starting.js";
import { attachFiles, heldNotes, noteImages, pendingNotes, removeImage } from "../uploads.js";
import { closeMentions } from "../mention-box.js";
import { destroyFields } from "../md-field.js";
import { buildPager, fitGrowBox, markFor, markMore, renderCard, renderEndItem, renderNotice } from "./cards.js";
import { sendState, suggestState } from "../send-state.js";
import { renderAgentsDoc, renderBriefButton, renderDoc, renderOverview } from "./docs.js";
@@ -1608,16 +1609,31 @@ export function renderSidebar() {
}
}
// The Ask pane on screen when a render of the Ask tab began, held back from
// the clear like the pose pane, so renderAsk() can take it up again: its list
// is a live region, and a list rebuilt on every redraw would be announced
// over and over instead of only its new rows.
let heldAsk = null;
// Takes `node` off the page, ending the editor of every Markdown field in it.
function discard(node) {
destroyFields(node);
node.remove();
}
function renderMain() {
const main = $("main");
page.heldPose = main.querySelector(":scope > [data-pose]");
for (const child of [...main.children]) if (child !== page.heldPose) child.remove();
heldAsk = page.view === "ask" ? main.querySelector(":scope > .ask-pane") : null;
for (const child of [...main.children]) if (child !== page.heldPose && child !== heldAsk) discard(child);
try {
paintMain(main);
} finally {
// Nothing took it up: this screen is not the same pose.
page.heldPose?.remove();
if (page.heldPose) discard(page.heldPose);
page.heldPose = null;
if (heldAsk) discard(heldAsk);
heldAsk = null;
}
// Inside the render pass, before withFocus restores the card's scroll, so
// the restore is measured against the box's final height.
@@ -1636,7 +1652,11 @@ function paintMain(main) {
if (page.view.startsWith("doc:")) return renderDoc(main, page.view.slice(4));
if (isSpecFileView(page.view)) return renderOverview(main, page.view);
if (page.view === AGENTS_VIEW) return renderAgentsDoc(main);
if (page.view === "ask") return renderAsk(main);
if (page.view === "ask") {
const held = heldAsk;
heldAsk = null;
return renderAsk(main, held);
}
if (page.view === "subagents") return renderSubagents(main);
// The session's own page, reached from the PAUSED / SESSION ENDED item at
@@ -1771,20 +1791,23 @@ export function renderFooter() {
const summary = $("footer-summary");
const notes = pendingNotes();
const n = stagedCount();
summary.replaceChildren();
// Built off the page and swapped in only when it reads differently: the
// summary is a live region and the footer renders on every tick, so a
// rewrite with the same words would be announced again each time.
const next = document.createElement("div");
const sent = awaitingReply();
if (!n && !notes.length && sent.length) {
// "Answer a question above" is nonsense when everything answerable has
// already gone. Say what is actually outstanding instead: their own send.
summary.appendChild(el("strong", null, stranded() ? `${sent.length} saved, not picked up yet` : `${sent.length} with Plan2Code`));
summary.appendChild(document.createTextNode(" · " + sent.map((i) => i.title).join(" · ")));
next.appendChild(el("strong", null, stranded() ? `${sent.length} saved, not picked up yet` : `${sent.length} with Plan2Code`));
next.appendChild(document.createTextNode(" · " + sent.map((i) => i.title).join(" · ")));
} else if (finish()) {
// Not "nothing to send yet". There is no yet.
const fin = finish();
summary.appendChild(el("strong", null, finishPaused(fin) ? "Paused." : "All done."));
summary.appendChild(
next.appendChild(el("strong", null, finishPaused(fin) ? "Paused." : "All done."));
next.appendChild(
document.createTextNode(
n || notes.length
? " Anything still waiting here was never sent."
@@ -1796,7 +1819,7 @@ export function renderFooter() {
)
);
} else if (!n && !notes.length) {
summary.appendChild(
next.appendChild(
document.createTextNode(
myTurn().length
? "Nothing to send yet. Answer a question above, then press Send."
@@ -1805,7 +1828,7 @@ export function renderFooter() {
);
} else {
const strong = el("strong", null, `${n + notes.length} ready`);
summary.appendChild(strong);
next.appendChild(strong);
const bits = [];
for (const [id, v] of Object.entries(page.local.staged)) {
const item = byId(id);
@@ -1819,12 +1842,12 @@ export function renderFooter() {
const item = byId(note.id);
bits.push(`note on ${item ? item.title : "a question"}`);
}
summary.appendChild(document.createTextNode(" · " + bits.join(" · ")));
next.appendChild(document.createTextNode(" · " + bits.join(" · ")));
}
const held = finish() ? 0 : heldNotes().length;
if (held) {
summary.appendChild(
next.appendChild(
el(
"div",
"footer-held",
@@ -1834,6 +1857,7 @@ export function renderFooter() {
)
);
}
if (summary.innerHTML !== next.innerHTML) summary.replaceChildren(...next.childNodes);
const state = sendState();
const btn = $("btn-send");
+11 -2
View File
@@ -6,7 +6,8 @@
background: var(--panel);
border: 1px solid var(--rule);
border-radius: var(--radius);
padding: 24px 26px;
--card-pad-b: 24px;
padding: 24px 26px var(--card-pad-b);
max-width: min(var(--card-width), 100%);
box-shadow: var(--shadow);
margin: 0 auto 18px;
@@ -74,7 +75,15 @@
/* ------------------------------------------------------------ options */
.options { list-style: none; margin: 20px 0 0; padding: 0; display: grid; gap: 9px; }
.options-clear { margin-top: 10px; }
/* Pinned to the foot of the card's scroll area, so a question taller than the
window keeps its Clear in reach; it settles under the options at the end. */
.options-clear {
position: sticky; bottom: calc(var(--card-pad-b) * -1); z-index: 1;
margin: 10px 0 calc(var(--card-pad-b) * -1); padding: 8px 0 var(--card-pad-b);
background: linear-gradient(to bottom, transparent, var(--panel) 8px);
}
.clear-btn { display: inline-flex; align-items: center; gap: 6px; }
.clear-btn svg { flex: none; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
.option {
display: flex;
+1 -1
View File
@@ -30,7 +30,7 @@
.rail { border-right: 0; border-bottom: 1px solid var(--rule); }
.sidebar, .aside { border: 0; border-bottom: 1px solid var(--rule); max-height: 30vh; }
.main { padding: 18px 16px 30px; }
.card { padding: 18px 16px; border-radius: 8px; }
.card { --card-pad-b: 18px; padding: 18px 16px var(--card-pad-b); border-radius: 8px; }
.main > .card { padding-right: 22px; }
.card h2 { font-size: 21px; }
/* Back to a wrapping row: the summary and Send take two lines here and fill
+2 -1
View File
@@ -10,7 +10,8 @@
--panel-2: #fbf9f6;
--ink: #1d1a17;
--ink-2: #5d564d;
--ink-3: #8f8779;
/* Same hue as before, darkened to 4.56:1 on --bg (WCAG AA for body text). */
--ink-3: #756e62;
--rule: #e4ddd1;
--rule-2: #cfc6b6;
--accent: #206cc3;
+66 -35
View File
@@ -235,7 +235,7 @@ function handover(req, res, ctx) {
// The tab moved once; a second open in the same conversation is not a
// hand-over, so the caller can open a browser without a failure note.
if (state.setup.moved) return json(res, 409, { error: "moved" });
return readBody(req, (err, body) => {
return readBody(req, res, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "bad-url" });
const target = typeof body?.url === "string" ? body.url : "";
// Only another console's sign-in link is a legal destination.
@@ -506,7 +506,7 @@ function events(req, res, ctx, url) {
/* ---------------------------------------------------- settings and drafts */
function draft(req, res, ctx) {
return readBody(req, (err, body) => {
return readBody(req, res, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
// Debounced client-side; this is just the durable mirror. Twenty minutes
// of someone's structured answers must not die with a closed tab.
@@ -551,7 +551,7 @@ function looksGet(req, res) {
}
function looksPost(req, res) {
return readBody(req, (err, body) => {
return readBody(req, res, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
// `set` carries only the keys one tab changed, merged onto what is on
// disk, so a tab holding stale settings cannot undo another tab's change.
@@ -573,7 +573,7 @@ function looksPost(req, res) {
// is what console.mjs hands the agent at its next pickup. Never blocked by,
// and never blocking, a card send.
function subagentsPost(req, res, ctx) {
return readBody(req, (err, body) => {
return readBody(req, res, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
const state = ctx.readState();
if (!state || !offered(state.workflow)) return json(res, 400, { error: "not-offered" });
@@ -605,7 +605,7 @@ function subagentsPost(req, res, ctx) {
// The page follows it with a __git pr-host action, and the agent's reread
// rebuilds the link.
function prHost(req, res, ctx) {
return readBody(req, (err, body) => {
return readBody(req, res, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
const { host: raw, kind } = body && typeof body === "object" ? body : {};
if (typeof raw !== "string" || !raw || raw.length > 253 || !/^[a-z0-9.-]+$/i.test(raw)) {
@@ -762,7 +762,7 @@ function modelsGet(req, res) {
}
function modelsPost(req, res) {
return readBody(req, (err, body) => {
return readBody(req, res, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
const { models, error } = cleanModels(body && body.models);
if (error) return json(res, 400, { error });
@@ -829,7 +829,7 @@ function agentsGet(req, res) {
// entry) is refused with 409 unless the page says `replace: true`, so a save
// never silently drops what the person wrote there by hand.
function agentsPost(req, res) {
return readBody(req, (err, body) => {
return readBody(req, res, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
const { agents, error, index, field } = validateForSave(body && body.agents);
if (error) return json(res, 400, { error, index, field });
@@ -854,7 +854,7 @@ function agentsPost(req, res) {
// Where a command would run from, for the form's Test button. Only looks: it
// never runs the command.
function agentsTest(req, res) {
return readBody(req, (err, body) => {
return readBody(req, res, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
const command = typeof body?.command === "string" ? body.command.trim() : "";
if (!command || command.length > 1024) return json(res, 400, { error: "command must be 1 to 1024 characters" });
@@ -869,7 +869,7 @@ function agentsTest(req, res) {
// ever saved, never a path the request carried. A built-in is materialized
// as a new custom entry; a custom agent gets its command rewritten.
function agentsUsePath(req, res, ctx) {
return readBody(req, (err, body) => {
return readBody(req, res, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
const id = typeof body?.id === "string" ? body.id.trim() : "";
if (!id) return json(res, 400, { error: "id is required" });
@@ -944,7 +944,7 @@ function agentsUsePath(req, res, ctx) {
// removes those of the ids a fresh scan still finds. Never this session,
// never a path the page sent.
function cleanup(req, res, ctx) {
return readBody(req, (err, body) => {
return readBody(req, res, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
if (body && Array.isArray(body.delete)) {
return removeCleanup(body.delete, { skipSid: ctx.sid, project: ctx.worktree() || ctx.project })
@@ -990,7 +990,7 @@ function notepadTab(ctx, url, create) {
}
function notepadText(req, res, ctx, url) {
return readBody(req, (err, body) => {
return readBody(req, res, (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), notepadTab(ctx, url, true), body && body.text) });
@@ -1006,7 +1006,7 @@ function readJpeg(req, res, then) {
req.resume();
return json(res, 415, { error: "not-jpeg" });
}
return readRaw(req, MAX_BODY, (err, buf) => {
return readRaw(req, res, MAX_BODY, (err, buf) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too-large" : "bad" });
return then(buf);
});
@@ -1034,7 +1034,7 @@ function notepadThumb(req, res, ctx, url) {
}
function notepadDelete(req, res, ctx, url) {
return readBody(req, (err, body) => {
return readBody(req, res, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: "bad" });
try {
removeImage(notepadRoot(ctx), notepadTab(ctx, url, false), body && body.id);
@@ -1050,7 +1050,7 @@ function notepadDelete(req, res, ctx, url) {
// ctx.dir and add nothing to the event log.
function notepadTabRoute(act) {
return (req, res, ctx) =>
readBody(req, (err, body) => {
readBody(req, res, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: "bad" });
try {
return json(res, 200, { ok: true, ...act(notepadRoot(ctx), body && typeof body === "object" ? body : {}) });
@@ -1230,7 +1230,7 @@ function upload(req, res, ctx) {
};
if (contentType.startsWith("image/jpeg")) {
return readRaw(req, MAX_BODY, (err, buf) => {
return readRaw(req, res, MAX_BODY, (err, buf) => {
if (err) return err.tooBig ? json(res, 413, { error: "too large" }) : json(res, 400, { error: String(err.message) });
if (buf.length < 3 || buf[0] !== 0xff || buf[1] !== 0xd8 || buf[2] !== 0xff) {
return json(res, 415, { error: "JPEG only" });
@@ -1260,8 +1260,8 @@ function upload(req, res, ctx) {
const name = uploadLabel(req, "");
const ext = docExt(rawUploadName(req));
// Refused on its name alone, but drained first, so the page gets the 415.
if (!ext) return readRaw(req, 0, () => json(res, 415, { error: "type" }));
return readRaw(req, MAX_DOC_BYTES, (err, buf) => {
if (!ext) return readRaw(req, res, 0, () => json(res, 415, { error: "type" }));
return readRaw(req, res, MAX_DOC_BYTES, (err, buf) => {
if (err) return err.tooBig ? json(res, 413, { error: "too large" }) : json(res, 400, { error: String(err.message) });
if (checkDocument(buf, ext)) return json(res, 415, { error: "type" });
const saved = store(buf, ext);
@@ -1272,7 +1272,7 @@ function upload(req, res, ctx) {
});
}
return readRaw(req, 0, () => json(res, 415, { error: "type" }));
return readRaw(req, res, 0, () => json(res, 415, { error: "type" }));
}
// A note attachment the agent kept into the spec (`console.mjs keep`), so a
@@ -1412,7 +1412,7 @@ function recordSubmitted(state, actions) {
// A link the page inside the desktop app cannot open itself (open-link.mjs).
// http and https only; the page shows the link to paste when this says no.
function openLinkRoute(req, res) {
return readBody(req, (err, body) => {
return readBody(req, res, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
const href = linkToOpen(body && body.url);
if (!href) return json(res, 400, { error: "only http and https links open" });
@@ -1422,7 +1422,7 @@ function openLinkRoute(req, res) {
}
function submit(req, res, ctx) {
return readBody(req, (err, body) => {
return readBody(req, res, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
if (!body || !Array.isArray(body.actions) || body.actions.length === 0) {
return json(res, 400, { error: "actions must be a non-empty array" });
@@ -1528,7 +1528,7 @@ function submit(req, res, ctx) {
// this route never looks at result.json, so a card send waiting to be
// collected never holds up a question, and a question never holds up a card.
function chat(req, res, ctx) {
return readBody(req, (err, body) => {
return readBody(req, res, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const state = ctx.readState() || {};
@@ -1591,7 +1591,7 @@ function chat(req, res, ctx) {
// Approve or Decline on an edit the agent proposed in the chat. `re` is the
// proposing reply's id. Decisions never count toward the message limit.
function chatDecision(req, res, ctx) {
return readBody(req, (err, body) => {
return readBody(req, res, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
if (body.decision !== "approve" && body.decision !== "decline") return json(res, 400, { error: "bad" });
@@ -1705,7 +1705,7 @@ function loopSetupGet(req, res, ctx, url) {
}
function loopSetupPost(req, res, ctx) {
return readBody(req, (err, body) => {
return readBody(req, res, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { ok: false, problems: ["the setup must be a JSON object"] });
try {
@@ -1732,7 +1732,7 @@ function workspaceGet(req, res, ctx, url) {
}
function workspaceEdit(req, res, ctx, url) {
return readBody(req, (err, body) => {
return readBody(req, res, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
let answer;
@@ -1749,7 +1749,7 @@ function workspaceEdit(req, res, ctx, url) {
// The dashboard's picker sends it as the selection moves and before a
// launch, so a skill opens on the list of the spec it was launched for.
function workspaceScope(req, res, ctx) {
return readBody(req, (err, body) => {
return readBody(req, res, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const spec = typeof body.spec === "string" ? body.spec : "";
@@ -1765,7 +1765,7 @@ function workspaceScope(req, res, ctx) {
// Only ever returns a path: the page then adds it through /workspace/add.
function workspaceBrowse(req, res, ctx) {
return readBody(req, () => {
return readBody(req, res, () => {
ctx.workspace.browse().then(([code, body]) => json(res, code, body));
});
}
@@ -1893,7 +1893,35 @@ function originOk(req, port) {
const MAX_BODY = 4 * 1024 * 1024;
function readBody(req, cb) {
// The one way a body reader hands over: at most once, and a callback that
// throws still gets its request answered. Before this, readBody's catch fed
// a throw from the route's own callback back into that callback as a parse
// error (a second run, a second answer), an 'error' after 'end' called it
// again, and readRaw let the throw escape with the request left hanging. A
// throw now answers 400 if nothing went out yet, or ends what was started,
// and is rethrown on the next turn so the server's uncaughtException handler
// still records it in events.ndjson.
function deliverOnce(res, cb) {
let done = false;
return (err, value) => {
if (done) return;
done = true;
try {
cb(err, value);
} catch (e) {
try {
if (!res.headersSent) json(res, 400, { error: "bad request" });
else if (!res.writableEnded) res.end();
} catch {}
setImmediate(() => {
throw e;
});
}
};
}
export function readBody(req, res, cb) {
const deliver = deliverOnce(res, cb);
// Collect Buffers and decode once at the end. Appending each chunk to a
// string decodes it in isolation, so a multi-byte character split across a
// chunk boundary becomes U+FFFD. Rare, silent, and impossible to reproduce
@@ -1915,21 +1943,24 @@ function readBody(req, cb) {
chunks.push(c);
});
req.on("end", () => {
if (tooBig) return cb(Object.assign(new Error("too large"), { tooBig: true }));
if (tooBig) return deliver(Object.assign(new Error("too large"), { tooBig: true }));
let body;
try {
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
} catch (e) {
cb(e);
return deliver(e);
}
deliver(null, body);
});
req.on("error", (e) => cb(e));
req.on("error", (e) => deliver(e));
}
// The binary sibling of readBody, for image and document uploads, each with
// its own cap. Past the cap it stops keeping chunks but drains the rest
// instead of destroying the request: a destroyed socket reaches the page as a
// network error, never as the 413 that lets it say the file was too large.
function readRaw(req, limit, cb) {
export function readRaw(req, res, limit, cb) {
const deliver = deliverOnce(res, cb);
const chunks = [];
let size = 0;
let tooBig = false;
@@ -1943,8 +1974,8 @@ function readRaw(req, limit, cb) {
chunks.push(c);
});
req.on("end", () => {
if (tooBig) return cb(Object.assign(new Error("too large"), { tooBig: true }));
cb(null, Buffer.concat(chunks));
if (tooBig) return deliver(Object.assign(new Error("too large"), { tooBig: true }));
deliver(null, Buffer.concat(chunks));
});
req.on("error", (e) => cb(e));
req.on("error", (e) => deliver(e));
}
+12 -25
View File
@@ -7,7 +7,7 @@ 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";
import { deriveSpecState, pickPhaseFiles, 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.
@@ -88,7 +88,8 @@ function classifySpec(dir, names) {
const has = (re) => names.some((n) => re.test(n));
const pfDir = path.join(dir, "pathfinder");
const overview = names.includes("overview.md");
const phases = names.filter((n) => /^phase-.*\.md$/i.test(n));
const picked = pickPhaseFiles(names);
const phases = [...picked.keys()].sort((a, b) => a - b).map((n) => picked.get(n));
const drafts = names.filter((n) => /^PLAN-DRAFT.*\.md$/i.test(n));
const planDraft = drafts.length > 0;
const planConv = has(/^PLAN-CONVERSATION.*\.md$/i);
@@ -97,31 +98,17 @@ function classifySpec(dir, names) {
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 n = countTasks(readText(path.join(dir, f)));
done += n.done;
assumed += n.assumed;
open += n.open;
}
const finished = done + assumed;
const total = finished + open;
const suffix = assumed > 0 ? `, ${assumed} assumed` : "";
// deriveSpecState() is the one rule for a documented spec's state,
// shared with specs.mjs (status), so the two never disagree.
const derived = deriveSpecState({
overview: overview ? readText(path.join(dir, "overview.md")) : null,
phases: [...picked.keys()].map((n) => ({ number: n, text: readText(path.join(dir, picked.get(n))) })),
});
// Documented, building and built specs all land here: each says whether a
// Revise plan brief is waiting, and only when one is.
// Revise plan brief is waiting, and only when one is. finalizeReady rides
// along only when true (only blocked tasks left, each with a reason).
const brief = planChangeWaiting(dir, phases) ? { planChange: true } : {};
if (open === 0 && finished > 0) return { state: "built", detail: `all tasks done${suffix}`, ...brief };
if (finished > 0) return { state: "building", detail: `${finished} of ${total} tasks done${suffix}`, ...brief };
return {
state: "documented",
detail: `${phases.length} phase${phases.length === 1 ? "" : "s"}, ${total || "?"} tasks ready`,
...brief,
};
return { state: derived.state, detail: derived.detail, ...(derived.finalizeReady ? { finalizeReady: true } : {}), ...brief };
}
// An overview with no phase files means Document was interrupted mid-write;
// its next step is the same as a finished plan's.
+33 -10
View File
@@ -33,7 +33,7 @@ import {
readJson,
writeJsonAtomic,
} from "./files.mjs";
import { LEDGER_FILE, handleFile, readLedger } from "./sessions.mjs";
import { LEDGER_FILE, SERVER_MAX_LIFE_MS, handleFile, readLedger } from "./sessions.mjs";
import {
CHAT_CURSOR_FILE,
CHAT_FILE,
@@ -74,14 +74,32 @@ if (!DIR) {
}
const SID = path.basename(DIR);
// The session token. `open` leaves it in a one-shot file in the session
// folder (`--token-file=<name>`, a bare name inside DIR) so it never appears
// on this process's command line; it is read once and the file deleted at
// once. `--token=<token>` is kept for a server started by hand or by a test.
// No token, no server: authed() waves everything through on an empty one. A
// bare `--token` (or one whose value parseArgs took for a flag) arrives as
// `true`, so anything but a non-empty string is refused here, at boot.
if (typeof args.token !== "string" || !args.token) {
process.stderr.write("server: --token=<token> is required (a non-empty string)\n");
const TOKEN = (() => {
const name = args["token-file"];
if (typeof name === "string" && name && path.basename(name) === name) {
const file = path.join(DIR, name);
let text = "";
try {
text = fs.readFileSync(file, "utf8").trim();
} catch {}
try {
fs.rmSync(file, { force: true });
} catch {}
return text;
}
return typeof args.token === "string" ? args.token : "";
})();
if (!TOKEN) {
process.stderr.write("server: a token is required: --token-file=<name in the session folder> or --token=<token> (a non-empty string)\n");
process.exit(2);
}
const TOKEN = args.token;
const PROJECT = args.project || process.cwd();
// The checkout this session runs in, from `open`. PROJECT is the folder that
// holds .git, which for a linked worktree is the MAIN checkout: the wrong
@@ -90,7 +108,7 @@ const PROJECT = args.project || process.cwd();
// there this is the only place the worktree can come from.
const WORKTREE = typeof args.worktree === "string" ? args.worktree : "";
const IDLE_MS = Number(args["idle-ms"] || 30 * 60 * 1000);
const MAX_LIFE_MS = Number(args["max-life-ms"] || 4 * 60 * 60 * 1000);
const MAX_LIFE_MS = Number(args["max-life-ms"] || SERVER_MAX_LIFE_MS);
const STATE_FILE = path.join(DIR, "state.json");
const DRAFT_FILE = path.join(DIR, "draft.json");
@@ -526,16 +544,18 @@ setInterval(() => {
// the server deciding to stop. Do not "optimize" this away.
setInterval(() => {
const idle = Date.now() - lastContact;
// Answers nobody has collected yet keep the server up (bounded by MAX_LIFE_MS):
// exiting would strand the tab and the send it holds.
if (idle > IDLE_MS && !resultFlags().pending) {
// Answers nobody has collected yet keep the server up, past the idle limit
// and past MAX_LIFE_MS alike: exiting would strand the tab and the send it
// holds. Once a `wait` collects them (consumedAt) both limits apply again.
const pending = resultFlags().pending;
if (idle > IDLE_MS && !pending) {
// The log is advisory: a failed append must never keep an orphan server alive.
try {
appendEvent(DIR, { type: "exit", reason: "idle", idleMs: idle });
} catch {}
process.exit(0);
}
if (Date.now() - STARTED > MAX_LIFE_MS) {
if (Date.now() - STARTED > MAX_LIFE_MS && !pending) {
try {
appendEvent(DIR, { type: "exit", reason: "max-life" });
} catch {}
@@ -630,7 +650,10 @@ function onListening(port) {
try {
subagents.sync(readState());
} catch {}
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
// stdout is server.log (`open` points it there), so the ready line names
// the server without the token segment: the log is not a place for it. The
// full link lives only in the handle file, which is private to this user.
process.stdout.write(JSON.stringify({ type: "ready", url: `http://127.0.0.1:${port}/`, port, sid: SID }) + "\n");
try {
startUpdateCheck();
} catch {}
+68 -9
View File
@@ -6,7 +6,7 @@ import path from "node:path";
import crypto from "node:crypto";
import { execFileSync } from "node:child_process";
import { countPending } from "./git-repo.mjs";
import { countPending, git } from "./git-repo.mjs";
import { DOC_TYPES } from "./public/answers.js";
import { appendJsonLine, HOME_DIR, newestMtime, nowIso, PLAN2CODE_DIR, readJson, readJsonLines, readText, RUNTIME_DIR, SESSIONS_DIR } from "./files.mjs";
@@ -210,6 +210,24 @@ export function attachmentName({ upload, name }) {
// Sessions and their uploads age out on the same clock: a month untouched.
export const SESSION_MAX_AGE_MS = UPLOAD_MAX_AGE_MS;
// A server's lifetime cap, one number for the server (MAX_LIFE_MS in
// server.mjs) and for `stop`, which reasons about how old a server can be.
// A server past it stays up only while answers nobody collected wait in its
// session (resultWaiting below): exiting would strand them.
export const SERVER_MAX_LIFE_MS = 4 * 60 * 60 * 1000;
// Answers the person sent that no agent has collected yet: a result.json with
// no consumedAt. The server keeps its own cached reading of the same rule
// (resultFlags in server.mjs); this one is for the CLI side.
export function resultWaiting(dir) {
try {
const r = JSON.parse(fs.readFileSync(path.join(dir, "result.json"), "utf8"));
return Boolean(r && !r.consumedAt);
} catch {
return false;
}
}
const PDF_MAGIC = Buffer.from("%PDF-", "ascii");
/**
@@ -351,6 +369,10 @@ export async function removeScratch(consoleDir, names) {
// the desktop app (app/, which install.js fills, and app.json, its settings)
// and the custom agents the person added (agents.json).
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
// The shared console install: install.js copies one folder per version here
// (~/.plan2code/console/<version>/) and removes the old ones, so Cleanup never
// offers it.
export const CONSOLE_VERSION_DIR = /^\d+\.\d+\.\d+$/;
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "install.json", "models.json", "handoffs", "notepads", "app", "app.json", "agents.json"]);
// A stray must sit untouched this long before Cleanup lists it. The same
// folders hold files that live for milliseconds -- a held
@@ -384,7 +406,7 @@ function entryKind(entry) {
return entry.isDirectory() ? "folder" : "file";
}
function strayEntries(dir, kept, where, now) {
function strayEntries(dir, kept, where, now, keptPattern = null) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
@@ -393,14 +415,15 @@ function strayEntries(dir, kept, where, now) {
}
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
return entries
.filter((e) => !kept.has(e.name))
.filter((e) => !kept.has(e.name) && !(keptPattern && e.isDirectory() && keptPattern.test(e.name)))
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
.filter((e) => settled(e.path));
}
// Finalize's archive, `<project>/specs--completed/<feature>/`: each feature
// folder (or link) nobody has touched for `maxAgeMs`, judged by its newest
// file. Loose files at the top are not specs and stay.
// file. Loose files at the top are not specs and stay. `tracked` says whether
// git could give it back after a delete (removeCleanup refuses one it could not).
function completedSpecs(project, now, maxAgeMs) {
const dir = path.join(project, "specs--completed");
let entries;
@@ -412,7 +435,33 @@ function completedSpecs(project, now, maxAgeMs) {
return entries
.filter((e) => e.isDirectory() || e.isSymbolicLink())
.map((e) => ({ id: "completed:" + e.name, where: "completed", name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
.filter((e) => now - newestMtime(e.path) > maxAgeMs);
.filter((e) => now - newestMtime(e.path) > maxAgeMs)
.map((e) => ({ ...e, tracked: trackedByGit(dir, e.name) }));
}
// True only when git tracks `name` (under `dir`) and could give back every
// file in it as it stands: `git ls-files` lists something, and `git status`
// (untracked, ignored, modified and staged alike) lists nothing, since git can
// restore only what was committed. Outside a repository, or when git fails, it
// is not tracked. `specs--completed/` is gitignored by default, so most
// archives answer false. Nothing records a backup copy yet, so tracked and
// committed is the only way through.
function trackedByGit(dir, name) {
const run = (args) => git(["--literal-pathspecs", ...args, "--", name], dir, { raw: true });
const cached = run(["ls-files", "-z"]);
if (!cached.ok || !cached.out) return false;
const changed = run(["status", "--porcelain=v1", "-z", "--ignored", "--untracked-files=all"]);
return changed.ok && !changed.out;
}
// The line the page shows for completed specs Cleanup kept because deleting
// them would lose them for good. "" when none was refused.
function refusalLine(names) {
if (!names.length) return "";
const list = names.map((n) => "specs--completed/" + n + "/").join(", ");
return names.length === 1
? `Kept ${list}: git does not track it as it stands, so deleting it would lose it for good. Commit it first, or delete it yourself once it is backed up.`
: `Kept ${names.length} completed specs git does not track as they stand, so deleting them would lose them for good: ${list}. Commit them first, or delete them yourself once they are backed up.`;
}
/**
@@ -444,7 +493,7 @@ export async function cleanupFindings({
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
}
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now, CONSOLE_VERSION_DIR));
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
}
@@ -463,6 +512,7 @@ export async function cleanupFindings({
bytes += size;
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;
if (f.where === "completed") item.tracked = f.tracked;
items.push(item);
}
return { items, bytes };
@@ -472,8 +522,10 @@ export async function cleanupFindings({
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
* worked out afresh first and only ids on it are touched, so a name from the
* page is never a path, and anything that stopped qualifying since the scan
* (a session touched again) stays. A link is unlinked, never followed.
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
* (a session touched again) stays. A link is unlinked, never followed. A
* completed spec git does not track is refused, never deleted: it lands in
* `refused`, and `refusal` is the line the page shows ("" when none was).
* Resolves to `{ removed: [id], bytes, failed: [id], refused: [id], refusal }`.
*/
export async function removeCleanup(ids, opts = {}) {
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
@@ -481,9 +533,16 @@ export async function removeCleanup(ids, opts = {}) {
const { removeNotepad } = await import("./notepads.mjs");
const removed = [];
const failed = [];
const refused = [];
const refusedNames = [];
let bytes = 0;
for (const item of items) {
if (!wanted.has(item.id)) continue;
if (item.where === "completed" && !item.tracked) {
refused.push(item.id);
refusedNames.push(item.name);
continue;
}
try {
if (item.where === "notepad") removeNotepad(item.name);
else if (item.kind === "link") await fs.promises.unlink(item.path);
@@ -494,7 +553,7 @@ export async function removeCleanup(ids, opts = {}) {
failed.push(item.id);
}
}
return { removed, bytes, failed };
return { removed, bytes, failed, refused, refusal: refusalLine(refusedNames) };
}
/**
+97 -7
View File
@@ -2,7 +2,8 @@
//
// 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
// way, and deriveSpecState(), the one rule for a documented spec's state.
// 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.
@@ -72,24 +73,113 @@ export function phaseChecklist(overview) {
return rows;
}
/**
* A spec folder's phase files by phase number, from its file names: the
* `phase-<N>...md` files, one per number. When a number has several files
* the exact `phase-<N>.md` wins, else the first by name; the rest are listed
* in the map's `extra` (number -> names). The one rule for which files are a
* spec's phases, shared by the dashboard scan and specs.mjs.
*/
export function pickPhaseFiles(names) {
const files = new Map();
const extra = new Map();
for (const name of [...(names || [])].sort()) {
const m = name.match(/^phase-(\d+)\b[^/]*\.md$/i);
if (!m) continue;
const n = Number(m[1]);
const exact = new RegExp(`^phase-0*${n}\\.md$`, "i").test(name);
if (!files.has(n)) files.set(n, name);
else if (exact) {
(extra.get(n) || extra.set(n, []).get(n)).push(files.get(n));
files.set(n, name);
} else (extra.get(n) || extra.set(n, []).get(n)).push(name);
}
files.extra = extra;
return files;
}
// A written reason on a blocked task: "BLOCKED: <why>" (Implementation
// Mode's blocker format) or "Reason: <why>", on the task line or under it.
export const BLOCK_REASON_RE = /\b(?:blocked|reason)\s*:\s*\S/i;
/**
* 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.
* counted apart from `[x]`, `[!]` (blocked) apart from the open ones, and an
* unknown marker (`[~]`) is open: it is not done. `bare` counts the blocked
* tasks with no written reason (BLOCK_REASON_RE) on their line or under it.
*/
export function countTasks(text) {
const lines = (text || "").split(/\r?\n/);
const tasks = lines.filter((l) => TASK_LINE_RE.test(l));
const hasTasks = lines.some((l) => TASK_LINE_RE.test(l));
let done = 0;
let assumed = 0;
let open = 0;
for (const line of tasks.length ? tasks : lines) {
let blocked = 0;
let bare = 0;
lines.forEach((line, i) => {
if (hasTasks && !TASK_LINE_RE.test(line)) return;
const m = line.match(CHECKBOX_RE);
if (!m) continue;
if (!m) return;
if (m[1] === "x" || m[1] === "X") done++;
else if (m[1] === "?") assumed++;
else if (m[1] === " " || m[1] === "/" || m[1] === "!") open++;
else if (m[1] === "!") {
blocked++;
// The task's body runs to the next heading or checkbox.
let end = i + 1;
while (end < lines.length && !/^#{1,6}\s/.test(lines[end]) && !CHECKBOX_RE.test(lines[end])) end++;
if (!BLOCK_REASON_RE.test(line.replace(CHECKBOX_RE, "")) && !BLOCK_REASON_RE.test(lines.slice(i + 1, end).join("\n"))) bare++;
} else open++;
});
return { done, assumed, open, blocked, bare, total: done + assumed + open + blocked };
}
/**
* A documented spec's state, from its overview.md text (or null) and its
* phase files' texts (`[{ number, text }]`, one per phase number, as
* pickPhaseFiles() picks them). The one derivation the dashboard scan and
* specs.mjs both use, so they cannot drift:
*
* - `built`: no task is open or blocked, at least one is done, and every
* phase the Phase Checklist lists as not yet approved has a phase file with
* tasks in it.
* - `building`: some task is done but the spec is not built. Blocked tasks
* are named in `detail`; when they are all that is left and each carries a
* written reason, `finalizeReady` is true (the dashboard lights Finalize).
* - `documented`: nothing done yet.
*
* Returns { state, detail, done, assumed, open, blocked, bare, total,
* unwritten, finalizeReady }, where `unwritten` lists the phase numbers the
* checklist names as open with no phase file, or with a phase file holding
* no tasks.
*/
export function deriveSpecState({ overview = null, phases = [] } = {}) {
const rows = overview == null ? [] : phaseChecklist(overview);
const approved = (n) => rows.some((r) => r.number === n && (r.marker === "x" || r.marker === "X" || r.marker === "?"));
const sum = { done: 0, assumed: 0, open: 0, blocked: 0, bare: 0, total: 0 };
const unwritten = [];
const numbers = new Set();
for (const p of phases) {
numbers.add(p.number);
const n = countTasks(p.text);
for (const k of Object.keys(sum)) sum[k] += n[k];
if (n.total === 0 && !approved(p.number)) unwritten.push(p.number);
}
return { done, assumed, open, total: done + assumed + open };
for (const r of rows) if (!numbers.has(r.number) && !approved(r.number) && !unwritten.includes(r.number)) unwritten.push(r.number);
unwritten.sort((a, b) => a - b);
const finished = sum.done + sum.assumed;
const assumedNote = sum.assumed > 0 ? `, ${sum.assumed} assumed` : "";
const blockedNote = sum.blocked > 0 ? `, ${sum.blocked} blocked` : "";
const unwrittenNote = unwritten.length ? `, Phase ${unwritten.join(", ")} not written up` : "";
const base = { ...sum, unwritten, finalizeReady: false };
if (finished > 0 && sum.open === 0 && sum.blocked === 0 && !unwritten.length) {
return { ...base, state: "built", detail: `all tasks done${assumedNote}` };
}
if (finished > 0) {
const finalizeReady = sum.open === 0 && sum.blocked > 0 && sum.bare === 0 && !unwritten.length;
return { ...base, finalizeReady, state: "building", detail: `${finished} of ${sum.total} tasks done${assumedNote}${blockedNote}${unwrittenNote}` };
}
const count = phases.length;
return { ...base, state: "documented", detail: `${count} phase${count === 1 ? "" : "s"}, ${sum.total || "?"} tasks ready` };
}