Sync upstream v2.4.0 into v2.4.1: welcome dialog, bug/idea button with issue templates, version in Help, gear preferences and ocean default accent, plus web console screenshots, new landing page and web-console-first docs

AI Assisted
This commit is contained in:
jparkerweb committed 2026-10-02 20:51:34 -07:00
1 parent 8dc2f5d15d
commit 4a5f759173
288 files changed
+25222 -4767

No files matched your search

+1 -1
View File
@@ -20,7 +20,7 @@ Interactive Q&A flow to update an existing `AGENTS.md` with new learnings and pr
## Interface
The FIRST thing you do, before anything else in this file — before the Awareness Context: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow init-update` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-init-update/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md. Every question in the Q&A flow and the restructure offer go through it. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console.md → Launches), then Awareness Context. On the console, a `__stop` action is the person ending the session (console.md → Stop requests); at every session end post `finish` BEFORE `stop`.
The FIRST thing you do, before anything else in this file — before the Awareness Context: ask **web console** (browser page, suggested) or **terminal**? Console → run `node "<D>/console.mjs" open --workflow init-update` before reading (<D>: references/web-console/ beside this SKILL.md — ~/.agents/skills/plan2code-init-update/references/web-console/ globally — or the dir in ~/.plan2code/console/console-dir), then read <D>/console.md. Every question in the Q&A flow and the restructure offer go through it. Switchable anytime. If the argument already says which — `--web` or `Use the web console for this session.` — take it and do not ask; drop the flag. Launched by the dashboard? Its session is already open — resume it (console.md → Launches), then Awareness Context. On the console, a `__stop` action is the person ending the session (console.md → Stop requests); at every session end post `finish` BEFORE `stop`; unless it is a pause, the finish carries `"dashboard": true` (the Back to the dashboard button) and you keep waiting for the press (console.md → Finishing).
---
@@ -273,7 +273,7 @@ for whichever comes first:
| An action `{ "i": "__review", "type": "review" }` | Take the review up (below). |
| An action `{ "i": "__dashboard", "type": "dashboard" }` | Take the session back as the dashboard (console.md → Finishing). |
| An action `{ "i": "__done", "type": "done" }` | `stop` the server. The session is over. |
| `wait` exit `20` | They closed the tab. Do not resume: the session is over. |
| `wait` exit `20` | The server is gone, not necessarily the tab. Resume it (`open --resume <sid> --no-open --workflow <yours>`) and keep waiting. |
| Nothing after about ten minutes | `stop` the server. The page then shows the terminal command for a review instead of a button that would go nowhere. |
**Read references/review.md** and run Review Mode with these overrides:
@@ -406,15 +406,38 @@ post carries `"run": { "event": "implement-review-phase", "id": "phase-N" }`.
("Change the plan"), `escalate` ("Plan it properly instead") and `abort`
("Stop here", `"danger": true`), token equal to the ids.
- **Building** after `yes`: settle the verdict (`"status": "answered"` plus
`"answer": { "verdict": "yes" }`) in the post that starts the build, then
exactly as "While you build", with the plan's steps
as the task list and `total` = the number of steps.
`"answer": { "verdict": "yes" }`) in the post that starts the build, and
open a **Build progress** tab in that same post, the way an Implement phase
gets its tasks tab. The plan's steps are the task list and `total` is their
number:
```jsonc
{
"stopWarning": "",
"items": [{ "id": "<the Build this plan? item's id>", "status": "answered", "answer": { "verdict": "yes" } }],
"headline": { "stage": "Building", "cleared": 0, "total": 4 },
"docs": [{ "id": "tasks", "title": "Build progress", "version": 1, "blocks": [
{ "id": "tasks", "state": "settled", "md": "- [ ] Step one\n- [ ] Step two\n- [ ] Step three\n- [ ] Step four" }
]}],
"agent": { "status": "working", "activity": "Step 1 of 4: step one", "quietMinutes": 10 }
}
```
Then post after every step, exactly as "While you build": bump the doc's
`version` and repost the whole list with that step ticked, raise
`headline.cleared`, and set `agent.activity` to the next step ("Step 2 of 4:
step two"). Never go silent for the whole build: a quick task with many steps
is the case this tab is for. Check for a Quick question between steps, and do
not call `wait` until the build is done.
- **The finish after the build:** `command` is the commit command, filled in,
in the project's commit format (AGENTS.md), with
`"where": "When you are happy with it, commit it from your terminal:"`, and
`review` on offer — the **Review it now** button, since a quick task has no
sign-off card to put it on. Keep waiting for the answer, and everything
after that is "The review, mid-session" above.
sign-off card to put it on — and `"dashboard": true`, so the finished screen
also offers **Back to the dashboard**. Both are required: a finish without
`dashboard` leaves the person on a dead end. Keep waiting for whichever
button is pressed, and everything after that is "The review, mid-session"
above.
- **Escalated / aborted:** settle the verdict the same way in the finish post —
finish with `"command": "/plan2code-1-plan"` and the
PLAN-DRAFT's path in `body`, no review; or `"command": "/plan2code-quick-task"`.
@@ -27,6 +27,12 @@ workflow still applies: the same questions, the same order, the same gates, the
same cap of three questions at a time, the same recap before anything is recorded.
You are not allowed to answer your own questions just because a form makes it easy.
> **The one rule that keeps the page alive: while the session is open, every
> turn ends on a `wait` call, never on text.** `wait` exit `10` means "nobody
> has answered yet", not "done": relay one line and run `wait` again in the
> same turn, as many times as it takes. A turn that ends without a `wait`
> running strands the person's next click. Details: The wait loop, below.
---
## Deciding whether to use it
@@ -172,7 +178,19 @@ so even a kill at the worst possible moment costs you a repeat, never an answer.
Do not poll faster than this. Do not spin on `status`. Exit 10 is not a finished
turn: never emit a final response or stop after an arbitrary number of slices;
relay one line and immediately call `wait` again. Do not give up: people step
away from a session and come back.
away from a session and come back. The same holds after a `finish`: keep
waiting (resuming the server on exit `20`) until the dashboard or done press
or about ten minutes with nothing, because the Ask tab stays live and its
messages only arrive through `wait`. Ending your turn earlier strands them.
**The turn never ends on a wait.** While a console session is open, including
after a finish that offers a button (Back to the dashboard, Review it now), the
last thing in every turn you take is a `wait` call, never a line of text. The
line you relay after exit `10` goes in the same turn as the next `wait`, so
write it and call `wait` straight after. A turn that ends with the session open
and no `wait` running is a bug the person feels at once: their button press
sits unread until they ask why. If you catch yourself about to write a closing
summary while the page is still open, call `wait` first.
**Collect promptly.** A question someone has sent is locked on the page for as
long as you are mid-turn on it: they can read, move around and answer the other
@@ -453,6 +471,14 @@ messages, `offline` when no agent is connected or the session has finished,
### Answering
**Every message gets a reply, always.** The Ask tab is the person talking to
you, and the page shows "working on the answer" until a reply lands. Never
leave one unanswered, whatever it asks and whatever mid-task you are in. When
a message asks you to do something, do it if you can, then say what happened; if
you will not, the reply says so and why. `post` and `wait` print
`unansweredChat` with a `warning` for every message handed over and not yet
replied to: treat that as a stop-and-reply.
1. Handle any card answers first, under the workflow's own rules.
2. Write the chat replies, in inbox order.
3. Send **one** `post` with the card updates and `chat: { replies: [...] }`.
@@ -510,8 +536,9 @@ enforces it, so never tell someone to keep asking past it.
proposal is a new reply.
- Hard limits: never touch the running skill's own files under
`specs/<idea>/` (`post` rejects a proposal that names them); run no commands
beyond read-only lookups; never commit; refuse a request outside these and
say why.
beyond read-only lookups, except one the person plainly asks you to run in
their message (a commit they spell out, a test run): run it, then report the
result in the reply; refuse anything else and say why, in the reply.
- Edits happen only at check-ins, never mid-task in a build.
```jsonc
@@ -715,8 +742,10 @@ review run from a build's review button stays in the build's session, under
its workflow: `building.md` → The review, mid-session. On completion the finish's `command` is the suggested
commit when fixes landed — filled in, in the AGENTS.md format, with
`"where": "When you are happy with it, commit it from your terminal:"` —
otherwise leave `command` out. A stop mid-review loses nothing on disk, so its
finish is the bare `/plan2code-review`.
otherwise leave `command` out. The completion finish carries `"dashboard": true`
so the finished screen offers **Back to the dashboard**; keep waiting for the
press. A stop mid-review loses nothing on disk, so its finish is the bare
`/plan2code-review` (a pause, so no dashboard button).
### Handoff (`handoff`)
@@ -892,6 +921,8 @@ Session meter) and `folderIssue` (Workspace → When a folder cannot be read).
### Every item
**Give every new question a new `id`.** An id names one question for the whole session. The server drops a stale `submitted` record if you reword a question under an old id, but never rely on it: a fresh id is the only unambiguous way to ask something new.
```jsonc
{
"id": "q7",
@@ -1141,7 +1172,7 @@ usual slices for up to about ten minutes:
| --- | --- |
| An action `{ "i": "__dashboard", "type": "dashboard" }` | `open --resume <sid> --no-open --workflow dashboard` (the resume re-runs the project scan), then ONE post with `"finish": null`, the `menu` payload and `"agent": { "status": "waiting" }`. Then read the dashboard skill (`~/.agents/skills/plan2code/SKILL.md`) and carry on as the dashboard from its "The menu" section, in this same conversation. The same action can also arrive before any finish, from the top bar's triangle: see Stop requests → "Back to the dashboard, mid-workflow". |
| An action `__review` or `__done` | As `building.md` says (quick task only). |
| `wait` exit `20` | They closed the tab. Do not resume: the session is over. |
| `wait` exit `20` | The server is gone, not necessarily the tab. `open --resume <sid> --no-open --workflow <yours>`, then keep waiting: their Ask messages and the dashboard button still need you. Give up only when the resume itself fails. |
| Nothing after about ten minutes | `stop` the server. The page swaps the button for the `/plan2code` command. |
### 2. Stop the server
@@ -54,6 +54,7 @@ import {
nowIso,
parseArgs,
pendingChatCount,
unansweredChat,
pendingWorkspaceChanges,
pidAlive,
print,
@@ -77,6 +78,7 @@ import {
sweepUploads,
switchWorkflow,
terminalLine,
updateState,
UPLOAD_MAX_AGE_MS,
validate,
validateChat,
@@ -88,6 +90,10 @@ import {
import { RUN_EVENTS } from "./public/meter.js";
import { changeLine } from "./public/workspace.js";
// 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;
const argv = process.argv.slice(2);
const cmd = argv[0];
const args = parseArgs(argv.slice(1));
@@ -102,8 +108,24 @@ function trace(what) {
/* ----------------------------------------------------------------- open */
// Cache this console's directory where a later agent session can find it.
// HOME_DIR is fixed (~/.plan2code/console, or $PLAN2CODE_CONSOLE_HOME), so
// console-dir there is a stable place to look: the next skill that offers the
// console points its agent at the file rather than making it search the skill
// install dirs again. Written by `open` alone, which starts every session: a
// `wait` or a `post` every few seconds need not rewrite it each time.
function leavePointer() {
try {
ensureDir(HOME_DIR);
fs.writeFileSync(path.join(HOME_DIR, "console-dir"), HERE + "\n");
} catch {
/* a pointer we cannot leave costs nothing */
}
}
async function cmdOpen() {
trace("open: start");
leavePointer();
const { project, worktree, branch } = repoRoots();
reapHandles(project);
trace("open: project found");
@@ -113,6 +135,11 @@ async function cmdOpen() {
let state;
// A new skill run for the meter: a fresh open, or a resume into another workflow.
let launched = true;
// Everything `open` does to a stored state, as a step it can take twice:
// once now, on the read below, so a bad payload is refused before anything
// starts, and again on a fresh read under the state lock when it writes, so
// a send the person made in between is kept rather than written over.
let reshape = (s) => s;
if (sid) {
sid = path.basename(sid);
@@ -120,27 +147,6 @@ async function cmdOpen() {
if (!fs.existsSync(dir)) die(`no session "${sid}" to resume`, 1);
state = readJson(path.join(dir, "state.json"));
if (!state) die(`session "${sid}" has no state`, 1);
// Resuming takes a pause back down. A paused finish is a bookmark --
// "saved here, pick it up later" -- and picking it up is exactly what
// this is. Left in place, the page keeps saying PAUSED over every
// question the resumed session asks, because `finish` is a scalar and
// only an explicit `finish: null` patch clears it. A real ending is
// different: re-sharing a finished session's link should still show its
// card, so only a headline that says "paused" comes down. Done before
// --file applies, so a patch can still post a finish of its own.
if (state.finish && /^\s*paused\b/i.test(String(state.finish.headline || ""))) {
delete state.finish;
// The questions still open at the pause were the old session's asks,
// already narrated in the finish body so the next session can name
// them. Whatever the resumed session still needs it asks again, in its
// own words -- kept, the leftovers sit beside the new asks as
// duplicates nobody owns. Settled items stay: they are the record.
state.items = (state.items || []).filter((i) => !isOpen(i));
// And the topics that only the dropped items lived under, so a new
// item reusing an old topic id does not inherit a stale title.
const liveTopics = new Set(state.items.map((i) => i.topic));
state.topics = (state.topics || []).filter((t) => liveTopics.has(t.id));
}
// A resume can also be a hand-off: the dashboard launches another skill
// into its own session, and the first thing that skill needs is for the
// page to stop being a dashboard. Letting the flags restate these fields
@@ -148,26 +154,51 @@ async function cmdOpen() {
// rather than a resume plus a whole extra post.
const switching = args.workflow && args.workflow !== state.workflow;
launched = Boolean(switching);
if (switching && (args.workflow === "dashboard" || state.workflow === "dashboard")) {
// Going through the dashboard is a fresh start: a skill launched from
// the menu gets a clean page, not the last skill's questions and tabs
// under its own name. The staged draft goes too, since its item ids
// belonged to the old questions. A skill run inline from another (a
// quick task's review) never passes the dashboard, so it keeps the page.
state = switchWorkflow(state, {
workflow: args.workflow,
title: typeof args.title === "string" ? args.title : path.basename(worktree),
specDir: args.spec,
});
fs.rmSync(path.join(dir, "draft.json"), { force: true });
} else if (switching) state.workflow = args.workflow;
if (args.title) state.title = args.title;
if (args.spec) state.specDir = args.spec;
// Every resume clears the wake-up flag: a server restart, a launch from
// the dashboard, a Back-to-dashboard return. Cleared here rather than by
// the page because the page cannot write state, and a replay on a return
// is exactly what the decision rules out.
delete state.wake;
// Going through the dashboard is a fresh start: a skill launched from
// the menu gets a clean page, not the last skill's questions and tabs
// under its own name. The staged draft goes too, since its item ids
// belonged to the old questions. A skill run inline from another (a
// quick task's review) never passes the dashboard, so it keeps the page.
const hop = switching && (args.workflow === "dashboard" || state.workflow === "dashboard");
if (hop) fs.rmSync(path.join(dir, "draft.json"), { force: true });
reshape = (s) => {
// Resuming takes a pause back down. A paused finish is a bookmark --
// "saved here, pick it up later" -- and picking it up is exactly what
// this is. Left in place, the page keeps saying PAUSED over every
// question the resumed session asks, because `finish` is a scalar and
// only an explicit `finish: null` patch clears it. A real ending is
// different: re-sharing a finished session's link should still show its
// card, so only a headline that says "paused" comes down. Done before
// --file applies, so a patch can still post a finish of its own.
if (s.finish && /^\s*paused\b/i.test(String(s.finish.headline || ""))) {
delete s.finish;
// The questions still open at the pause were the old session's asks,
// already narrated in the finish body so the next session can name
// them. Whatever the resumed session still needs it asks again, in its
// own words -- kept, the leftovers sit beside the new asks as
// duplicates nobody owns. Settled items stay: they are the record.
s.items = (s.items || []).filter((i) => !isOpen(i));
// And the topics that only the dropped items lived under, so a new
// item reusing an old topic id does not inherit a stale title.
const liveTopics = new Set(s.items.map((i) => i.topic));
s.topics = (s.topics || []).filter((t) => liveTopics.has(t.id));
}
if (hop) {
s = switchWorkflow(s, {
workflow: args.workflow,
title: typeof args.title === "string" ? args.title : path.basename(worktree),
specDir: args.spec,
});
} else if (switching) s.workflow = args.workflow;
if (args.title) s.title = args.title;
if (args.spec) s.specDir = args.spec;
// Every resume clears the wake-up flag: a server restart, a launch from
// the dashboard, a Back-to-dashboard return. Cleared here rather than by
// the page because the page cannot write state, and a replay on a return
// is exactly what the decision rules out.
delete s.wake;
return s;
};
} else {
sid = newSessionId();
// Named, not made: the folder is created once --file has passed, so a
@@ -185,22 +216,36 @@ async function cmdOpen() {
// Only a freshly opened dashboard plays Planny's wake-up.
if (args.workflow === "dashboard") state.wake = true;
}
// On every open, so a resume from another worktree refreshes both.
state.worktree = worktree;
state.branch = branch;
// A first payload's meter and folder reports, as `post` takes them: checked
// now, before anything is written, and appended once the launch is.
let openRun;
let openIssue;
let patch = null;
if (args.file) {
const patch = readJson(path.resolve(args.file));
patch = readJson(path.resolve(args.file));
if (!patch) die(`could not read --file ${args.file} as JSON`, 2);
({ run: openRun, folderIssue: openIssue } = patch);
delete patch.run;
delete patch.folderIssue;
}
const base = reshape;
const settle = (s) => {
s = base(s);
// On every open, so a resume from another worktree refreshes both.
s.worktree = worktree;
s.branch = branch;
return s;
};
reshape = (s) => (patch ? applyPatch(settle(s), patch) : settle(s));
state = settle(state);
if (patch) {
ledgerFromPost(dir, openRun, openIssue, state.workflow);
state = applyPatch(state, patch);
try {
state = applyPatch(state, patch);
} catch (e) {
die(e.message, 3);
}
const problems = validate(state);
if (problems.length) return failValidation(problems);
}
@@ -209,13 +254,15 @@ async function cmdOpen() {
// A fresh session needs a fresh server, and a server is a whole Node boot:
// the slowest thing `open` does, bar the browser. Start both now, before
// the scan and the state write, so their start-up runs alongside them
// instead of after. Neither can reach a page before the server is up, and
// the state is on disk long before that; the server reads it per request,
// never at boot.
// instead of after. The server does look at the state as it boots, and on
// a fresh session finds none yet: it takes the worktree from its command
// line, not from the state, and picks the state up on its first request or
// poll tick. No page can reach it before it is listening, and the state is
// on disk long before a browser gets there.
const existing = sid && (args.resume || args.session) ? listHandles(project).find((h) => h.sid === sid) : null;
const reusable = existing && pidAlive(existing.pid) ? healthOk(existing) : Promise.resolve(false);
let boot = null;
if (!existing) boot = await startServer(project, sid, dir);
if (!existing) boot = await startServer(project, worktree, sid, dir);
// The dashboard's spec picker reads its inventory straight off the session
// state, so the scan belongs to `open` rather than to the agent: filesystem
@@ -223,23 +270,43 @@ async function cmdOpen() {
// never something a model has to remember to fetch. Rooted at the worktree's
// own top level: `project` is the common-dir key so linked worktrees share
// sessions, but each shows the specs on its own disk.
if (state.workflow === "dashboard") state.scan = scanProject(worktree);
const scan = state.workflow === "dashboard" ? scanProject(worktree) : null;
// Clear a result the agent already collected, and ONLY that one.
//
// An unconsumed result is answers a person pressed Send on that nobody has
// picked up yet. Deleting it here is exactly the documented crash-recovery
// case ("your session died, press Send anyway, the next session picks it
// up") and deleting it destroys their work silently.
const resultPath = path.join(dir, "result.json");
const waiting = readJson(resultPath);
if (waiting && waiting.consumedAt) fs.rmSync(resultPath, { force: true });
const carried = Boolean(waiting && !waiting.consumedAt);
// Under the state lock, which a send on the page takes too: the result and
// the state are read fresh here and the state is rebuilt from that read, so
// nothing the person sent since the read above is lost or stamped over.
let carried = false;
let written;
try {
written = updateState(dir, (fresh) => {
const next = fresh ? reshape(fresh) : state;
if (scan) next.scan = scan;
// Do not stamp over "submitted" either: the phase is how the page knows a
// send is still in flight.
if (!carried) state.phase = "collecting";
writeJsonAtomic(path.join(dir, "state.json"), state);
// Clear a result the agent already collected, and ONLY that one.
//
// An unconsumed result is answers a person pressed Send on that nobody has
// picked up yet. Deleting it here is exactly the documented crash-recovery
// case ("your session died, press Send anyway, the next session picks it
// up") and deleting it destroys their work silently.
const resultPath = path.join(dir, "result.json");
const waiting = readJson(resultPath);
if (waiting && waiting.consumedAt) fs.rmSync(resultPath, { force: true });
carried = Boolean(waiting && !waiting.consumedAt);
// Do not stamp over "submitted" either: the phase is how the page knows a
// send is still in flight.
if (!carried) next.phase = "collecting";
return next;
});
} catch (e) {
written = { error: e.message };
}
if (!written || written.error) {
// A server just started for this state would only serve a page that never starts.
if (boot) boot.kill();
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
}
state = written.state;
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
trace("open: state written");
@@ -288,14 +355,14 @@ async function cmdOpen() {
// A handle whose pid is alive but is not ours (the pid was reused) leaves
// this for last: nothing could be started until that was known.
let started = boot || (await startServer(project, sid, dir));
let started = boot || (await startServer(project, worktree, sid, dir));
let handle = await awaitHandle(started);
if (!handle && started.handoff) {
// The handover went wrong somewhere (a platform that will not pass the
// socket, a server that died taking it). Once more the old way, where
// the server binds its own port: slower, and certain.
started.kill();
started = await startServer(project, sid, dir, { handoff: false });
started = await startServer(project, worktree, sid, dir, { handoff: false });
handle = await awaitHandle(started);
}
if (!handle) {
@@ -372,7 +439,7 @@ function isFolder(p) {
* boot: a process's first listen() blocks for ~50ms on Windows while the
* socket stack loads, which is time the server spends booting anyway.
*/
async function startServer(project, sid, dir, { handoff = true } = {}) {
async function startServer(project, worktree, sid, dir, { handoff = true } = {}) {
const token = newToken();
const handlePath = handleFile(project, sid);
ensureDir(path.dirname(handlePath));
@@ -389,6 +456,9 @@ async function startServer(project, sid, dir, { handoff = true } = {}) {
`--session=${dir}`,
`--token=${token}`,
`--project=${project}`,
// The checkout the session runs in, which the state does not hold yet
// on a fresh open. See WORKTREE in server.mjs.
`--worktree=${worktree}`,
...(handoff ? ["--handoff"] : []),
...(args["idle-ms"] ? [`--idle-ms=${args["idle-ms"]}`] : []),
],
@@ -487,20 +557,37 @@ function cmdPost() {
delete patch.folderIssue;
const ledgerLines = ledgerFromPost(dir, run, folderIssue, before.workflow);
let next;
// The patch is applied to a fresh read under the state lock, never to the
// read above: a send the person made in between is in the file, and a write
// built on the older read would take it away. Nothing in here may exit, so
// the lock is always let go; a refusal is carried out and reported after.
let refused = null;
let problems = [];
let written;
try {
next = applyPatch(before, patch);
written = updateState(dir, (fresh) => {
if (!fresh) {
refused = ["that session has no state", 1];
return null;
}
let next;
try {
next = applyPatch(fresh, patch);
} catch (e) {
refused = [e.message, 3];
return null;
}
problems = validate(next);
if (!problems.length && patch.chat) problems = validateChat(next, readChat(dir));
return problems.length ? null : next;
});
} catch (e) {
die(e.message, 3);
die(e.message, 1);
}
const problems = validate(next);
if (refused) die(...refused);
if (problems.length) return failValidation(problems);
if (patch.chat) {
const chatProblems = validateChat(next, readChat(dir));
if (chatProblems.length) return failValidation(chatProblems);
}
const next = written.state;
writeJsonAtomic(statePath, next);
for (const line of ledgerLines) appendLedger(dir, line);
appendEvent(dir, { type: "post", items: (patch.items || []).length });
@@ -512,6 +599,7 @@ function cmdPost() {
items: next.items.length,
open,
phase: next.phase,
...unansweredNote(dir, next),
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
});
}
@@ -554,13 +642,15 @@ function ledgerFromPost(dir, run, issue, workflow) {
async function cmdWait() {
const dir = mustSession();
// A --seconds that is not a number would make the deadline NaN, and the
// slice would end at once with exit 10: a busy loop, not a wait.
// "240s" reads as 240. A --seconds with no number in it at all would make
// the deadline NaN, and the slice would end at once with exit 10: a busy
// loop, not a wait. So that is refused rather than guessed at.
const given = args.seconds;
if (given !== undefined && (typeof given !== "string" || !given.trim() || !Number.isFinite(Number(given)))) {
const asked = typeof given === "string" ? Number.parseFloat(given) : NaN;
if (given !== undefined && !Number.isFinite(asked)) {
die(`--seconds must be a number, got "${args.seconds}"`, 2);
}
const seconds = Math.max(5, Number(args.seconds || 240));
const seconds = Math.max(5, given === undefined ? 240 : asked);
const sid = path.basename(dir);
const project = projectRoot();
const resultPath = path.join(dir, "result.json");
@@ -580,6 +670,11 @@ async function cmdWait() {
// was a full read and parse every 400ms, which put up to 0.4s between the
// person pressing Send and the agent starting on it, on every single send.
let healthAt = 0;
// A busy server (right after a post, say) can miss one health check without
// being gone. Only a missing handle or dead pid is proof at once; a server
// that merely does not answer must fail three checks in a row, each with a
// longer look, before the slice ends with exit 20.
let healthMisses = 0;
// Null, not the current stamp: a result written between the check above and
// this line would otherwise read as already seen and wait out the slice.
let seen = null;
@@ -605,11 +700,17 @@ async function cmdWait() {
if (Date.now() - healthAt > 5000) {
healthAt = Date.now();
const handle = listHandles(project).find((h) => h.sid === sid);
if (!handle || !pidAlive(handle.pid) || !(await healthOk(handle))) {
if (!handle || !pidAlive(handle.pid)) {
print(serverGone(sid));
process.exitCode = 20;
return;
}
if (await healthOk(handle, 4000)) healthMisses = 0;
else if (++healthMisses >= 3) {
print(serverGone(sid));
process.exitCode = 20;
return;
} else healthAt = Date.now() - 3000; // look again in about 2s, not 5s
}
sleepSync(50);
}
@@ -630,7 +731,9 @@ async function cmdWait() {
staged,
url: handle ? handle.url : "",
message: "Waiting on your answer in the web console",
next: "NOT FINISHED, do not end your turn or write a summary: relay the message in one line, then run this same wait command again right now. Repeat until the exit code is not 10.",
pendingChat: 0,
...unansweredNote(dir, state),
// A workspace change alone never ends a slice: it rides on the next send.
pendingWorkspace: pendingWorkspaceChanges(dir).length,
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
@@ -638,11 +741,19 @@ async function cmdWait() {
process.exitCode = 10;
}
// Quick questions already handed over with no reply yet. Always empty when all are answered.
function unansweredNote(dir, state) {
const seqs = unansweredChat(dir, state);
return seqs.length
? { unansweredChat: seqs, warning: "Quick questions " + seqs.join(", ") + " have no reply yet and the page still shows them as pending. Reply to each now (chat.replies, re = seq): do what was asked when you can, or say why you will not." }
: {};
}
function serverGone(sid) {
return {
status: "server-gone",
sid,
message: "The console server is not running. Start it again with `open --resume` and give the person the new link.",
message: "The console server is not running. Start it again with `open --resume <sid> --no-open`, then keep waiting: at a finished screen too, since the person's Ask messages and the dashboard button still need you.",
};
}
@@ -943,10 +1054,13 @@ async function cmdStop() {
// reboot in the system temp directory, and PIDs get reused; without this
// check `stop --all` can kill an unrelated program that happens to have
// inherited the number. /health returning our own sid is the only proof:
// a young handle with a live pid is not, since the server may have died
// minutes ago and its number gone straight to something else. A server
// too wedged to answer /health still meets its own idle deadline.
if (!(await healthOk(h))) {
// a live pid and a young handle are not, since a server that died a
// minute ago leaves exactly that behind for any process to inherit. A
// busy server gets a second, longer look, and still has to answer as
// ours; one that does not is left alone, and only its handle goes.
const young = Date.now() - Date.parse(h.startedAt || 0) < MAX_SERVER_LIFE_MS;
const ours = (await healthOk(h)) || (young && pidAlive(h.pid) && (await healthOk(h, 5000)));
if (!ours) {
skipped++;
try {
fs.rmSync(h.handlePath, { force: true });
@@ -1074,18 +1188,6 @@ const COMMANDS = {
help: cmdHelp,
};
// Cache this console's directory where a later agent session can find it.
// HOME_DIR is fixed (~/.plan2code/console, or $PLAN2CODE_CONSOLE_HOME), so
// console-dir there is a stable place to look: the next skill that offers the
// console points its agent at the file rather than making it search the skill
// install dirs again. Written on every invocation, help and errors included.
try {
ensureDir(HOME_DIR);
fs.writeFileSync(path.join(HOME_DIR, "console-dir"), HERE + "\n");
} catch {
/* a pointer we cannot leave costs nothing */
}
// Say which Node is too old, rather than dying later inside a health check with
// "fetch is not defined". Whatever agent is driving this has to be able to read
// the failure, tell the person in one line, and carry on in the terminal.
@@ -1105,4 +1207,12 @@ if (!cmd || !Object.hasOwn(COMMANDS, cmd)) {
process.exit(2);
}
// A flag given with no value parses as `true`, and a boolean handed on as a
// path or a name crashes somewhere deep (path.basename(true) throws). Every
// flag that takes a value is checked once, here, and refused as bad usage.
const VALUE_FLAGS = ["session", "sid", "resume", "file", "spec", "title", "workflow", "upload", "name", "from", "seconds", "limit", "idle-ms"];
for (const flag of VALUE_FLAGS) {
if (flag in args && typeof args[flag] !== "string") die(`--${flag} needs a value`, 2);
}
await COMMANDS[cmd]();
@@ -39,6 +39,13 @@ export const SESSIONS_DIR = path.join(HOME_DIR, "sessions");
// state: a browser ties localStorage to the origin, and the origin carries the
// ephemeral port, so the file under this dir is the only copy of a preference
// that survives the next session's new port.
// Model menus for the `plan2code` launcher. The shipped list (bin/models.json) is the
// authors' and is overwritten by every install; the user's additions (models.json) are
// theirs. The launcher reads both. PLAN2CODE_MODELS_DIR moves them, for tests.
const PLAN2CODE_DIR = process.env.PLAN2CODE_MODELS_DIR || path.join(os.homedir(), ".plan2code");
export const SHIPPED_MODELS_FILE = path.join(PLAN2CODE_DIR, "bin", "models.json");
export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
@@ -141,6 +148,91 @@ export function appendEvent(dir, event) {
return line;
}
/* ----------------------------------------------------- the state lock */
// state.json has two writers in two processes: console.mjs (`open` and `post`,
// the agent's side) and the server (`/submit` stamps the phase and records
// what was sent on each item). Each writer reads the file, changes it and
// writes it back, so two of them overlapping lose whichever wrote first. Every
// read-modify-write of state.json therefore runs under this lock, a file
// created with O_EXCL beside it. The sections it guards are a read, a merge
// and a write, milliseconds long, so a lock older than LOCK_STALE_MS, or one
// whose holder has died, is a crash left behind and is broken. The wait runs
// past the stale age, so a writer always gets in eventually.
export const STATE_LOCK_FILE = "state.json.lock";
const LOCK_STALE_MS = 5000;
const LOCK_WAIT_MS = 7000;
function lockStale(lock) {
try {
const st = fs.statSync(lock);
if (Date.now() - st.mtimeMs > LOCK_STALE_MS) return true;
const pid = Number.parseInt(fs.readFileSync(lock, "utf8"), 10);
return Number.isInteger(pid) && pid > 0 && pid !== process.pid && !pidAlive(pid);
} catch (err) {
// Gone between the failed create and this look: free, so try again.
return err.code === "ENOENT";
}
}
// Run fn while holding the session's state lock, and release it however fn
// ends. fn must not call process.exit(): the release would never run, and the
// next writer would wait out the stale age.
export function withStateLock(dir, fn) {
const lock = path.join(dir, STATE_LOCK_FILE);
const deadline = Date.now() + LOCK_WAIT_MS;
let fd = null;
for (let attempt = 0; fd === null; attempt++) {
try {
fd = fs.openSync(lock, "wx");
} catch (err) {
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
if (Date.now() > deadline) throw new Error("state.json is busy with another writer; try again");
if (err.code === "EEXIST" && lockStale(lock)) {
try {
fs.rmSync(lock, { force: true });
} catch {}
continue;
}
sleepSync(Math.min(5 * (attempt + 1), 50));
}
}
try {
try {
fs.writeSync(fd, String(process.pid));
} finally {
fs.closeSync(fd);
}
return fn();
} finally {
try {
fs.rmSync(lock, { force: true });
} catch {}
}
}
// The one way to change state.json: under the lock, read it fresh, hand it to
// fn (null when there is no state yet, with the raw text beside it), and write
// back whatever fn returns. A null return writes nothing. Returns the written
// state and its text, or null.
export function updateState(dir, fn) {
const file = path.join(dir, "state.json");
return withStateLock(dir, () => {
let text = null;
try {
text = fs.readFileSync(file, "utf8");
} catch {}
let state = null;
try {
state = text === null ? null : JSON.parse(text);
} catch {}
const next = fn(state, text);
if (!next) return null;
return { state: next, text: writeJsonAtomic(file, next) };
});
}
export function sleepSync(ms) {
// Node built-ins only, and this runs in short one-shot CLI commands.
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
@@ -827,6 +919,41 @@ const ITEM_DEFAULTS = {
thread: [],
};
// The question a card asks. If a patch rewrites any of these on a known id, it
// is a new question wearing an old id.
const QUESTION_FIELDS = ["kind", "title", "body", "options", "steps", "rows", "summary", "doc", "verdicts"];
/**
* Merge item patches by id, and keep a reused id from inheriting the person's
* old answer. `submitted` is the server's record of what they sent to the
* PREVIOUS question. When a patch changes what an item asks and doesn't itself
* settle it, that record (and any stale `answer`) is dropped, so the page shows
* the new question as open instead of "Sent, waiting for Plan2Code" forever.
*/
function dropStaleSubmissions(currentItems, before, patchList) {
const merged = mergeKeyed(currentItems, patchList, "id", ITEM_DEFAULTS, "items");
for (const entry of patchList) {
const prev = (before || []).find((x) => x.id === entry.id);
if (!prev || (prev.submitted === undefined && prev.answer === undefined)) continue;
const rewritten = QUESTION_FIELDS.some(
(f) => f in entry && JSON.stringify(entry[f]) !== JSON.stringify(prev[f]),
);
const settles = entry.status === "answered" || entry.status === "skipped" || "answer" in entry;
// A settled question edited in place (a typo in its body) stays settled; only an
// explicit reopen turns it into a new question.
const wasSettled = prev.status === "answered" || prev.status === "skipped";
// A different kind is never a typo fix: a multi turned confirm is another question.
const kindChanged = "kind" in entry && entry.kind !== prev.kind;
const reopens = entry.status === "open" || entry.status === "reopened" || kindChanged;
if (!rewritten || settles || (wasSettled && !reopens)) continue;
const item = merged.find((x) => x.id === entry.id);
if (wasSettled && !("status" in entry)) item.status = "open";
if (!("submitted" in entry)) delete item.submitted;
delete item.answer;
}
return merged;
}
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
@@ -868,7 +995,7 @@ export function applyPatch(state, patch) {
break;
case "items":
if (!Array.isArray(v)) throw new Error('"items" must be an array');
next.items = mergeKeyed(next.items, v, "id", ITEM_DEFAULTS, "items");
next.items = dropStaleSubmissions(next.items, state.items, v);
break;
case "topics":
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
@@ -1033,6 +1160,17 @@ export function validate(state) {
if ((item.kind === "choice" || item.kind === "multi") && !Array.isArray(item.options)) {
problems.push(`item "${item.id}" is a ${item.kind} and needs "options"`);
}
if ((item.kind === "choice" || item.kind === "multi") && Array.isArray(item.options)) {
for (const o of item.options) {
if (!o || typeof o.k !== "string" || !o.k.trim()) {
problems.push(`item "${item.id}" has an option with no "k" (its key, like "A")`);
} else if (typeof o.text !== "string" || !o.text.trim()) {
problems.push(
`item "${item.id}" option "${o.k}" needs "text" (the label) and optionally "detail". Options use "text"/"detail", not "label"/"desc".`
);
}
}
}
if (item.verdicts != null) {
if (!Array.isArray(item.verdicts) || !item.verdicts.length) {
problems.push(`item "${item.id}" "verdicts" must be a non-empty array of { id, label }`);
@@ -1051,16 +1189,18 @@ export function validate(state) {
if (item.templates != null && (item.kind !== "text" || item.templates !== "idea")) {
problems.push(`item "${item.id}" has "templates": only a text item can carry it, and its only value is "idea".`);
}
// The page compiles this to check the answer. One that will not compile
// is dropped there, so the check the agent asked for would silently not run.
// The page compiles it as the person types, and a pattern that does not
// compile throws there, on every keystroke, with nothing on screen to say why.
if (item.pattern != null) {
let compiles = typeof item.pattern === "string";
try {
if (compiles) new RegExp(item.pattern);
} catch {
compiles = false;
if (typeof item.pattern !== "string") {
problems.push(`item "${item.id}" "pattern" must be a string holding a JavaScript regular expression`);
} else {
try {
new RegExp(item.pattern);
} catch (e) {
problems.push(`item "${item.id}" "pattern" is not a valid JavaScript regular expression: ${e.message}`);
}
}
if (!compiles) problems.push(`item "${item.id}" "pattern" must be a string holding a valid JavaScript regular expression`);
}
const recs = (item.options || []).filter((o) => o.recommended);
if (recs.length > 1) problems.push(`item "${item.id}" marks ${recs.length} options recommended; at most one`);
@@ -1148,7 +1288,7 @@ export function validate(state) {
// server's record of an answer someone pressed Send on; if their own words
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
// would be rejected and the session would wedge with no way out.
const authored = state.items.map(({ submitted, ...rest }) => rest);
const authored = state.items.map(({ submitted, sentNote, ...rest }) => rest);
const prose =
JSON.stringify(authored) +
JSON.stringify(state.docs || []) +
@@ -1203,6 +1343,8 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
// chat.ndjson the server. One JSON line per entry: message / decision / reset.
// chat-cursor.json console.mjs. The last seq the agent was handed.
// state.json console.mjs `post`. The agent's replies, under chat.replies.
// (state.json as a whole has a second writer, the server's
// /submit, so every change to it goes through updateState().)
//
// The Workspace and the session meter follow the same rule, in files that
// switchWorkflow() never touches, so they carry across dashboard hops:
@@ -1351,6 +1493,19 @@ export function deliverableChat(entries) {
return entries.some((e) => e.kind !== "reset") ? entries : [];
}
// Things the person said that were handed over but never answered. The page keeps
// showing "working on the answer" for each until a reply lands, so the agent is
// told on every post and every wait slice until it has replied (a refusal is a reply).
export function unansweredChat(dir, state) {
const { conversation } = currentConversation(readChat(dir, 0));
const replied = new Set((state?.chat?.replies || []).map((r) => r && r.re));
const cursor = readCursor(dir);
return readChat(dir, 0)
.filter((e) => (e.kind === "message" || e.kind === "decision") && e.conversation === conversation)
.filter((e) => e.seq <= cursor && !replied.has(e.seq))
.map((e) => e.seq);
}
// How many things the person said are still waiting to be collected.
export function pendingChatCount(dir, state) {
return collectChat(dir, state).filter((e) => e.kind !== "reset").length;
@@ -25,6 +25,7 @@ export const WORKSPACE_PICKER_PROMPT = "Choose a folder to add to the workspace"
export const WINDOWS_PICKER_SOURCE = `
using System;
using System.Runtime.InteropServices;
using System.Threading;
public static class Plan2CodeFolderPicker {
[ComImport, Guid("DC1C5A9C-E88A-4DDE-A5A1-60F82A20AEF7")]
@@ -62,12 +63,40 @@ public static class Plan2CodeFolderPicker {
[DllImport("shell32.dll", CharSet = CharSet.Unicode, PreserveSig = false)]
private static extern void SHCreateItemFromParsingName(string path, IntPtr bindContext, ref Guid iid, out IShellItem item);
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr FindWindow(string className, string title);
[DllImport("user32.dll")]
private static extern bool SetWindowPos(IntPtr hWnd, IntPtr after, int x, int y, int w, int h, uint flags);
[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
private static extern int GetSystemMetrics(int index);
private const uint FOS_PICKFOLDERS = 0x20;
private const uint FOS_FORCEFILESYSTEM = 0x40;
private const uint FOS_PATHMUSTEXIST = 0x800;
private const uint SIGDN_FILESYSPATH = 0x80058000;
private const int ERROR_CANCELLED = unchecked((int)0x800704C7);
private static void Raise(string title) {
for (int i = 0; i < 100; i++) {
IntPtr hwnd = FindWindow(null, title);
if (hwnd != IntPtr.Zero) {
int w = Math.Min(1100, GetSystemMetrics(0) - 80);
int h = Math.Min(750, GetSystemMetrics(1) - 80);
int x = (GetSystemMetrics(0) - w) / 2 + 40;
int y = (GetSystemMetrics(1) - h) / 2 + 40;
SetWindowPos(hwnd, new IntPtr(-1), x, y, w, h, 0x40);
SetForegroundWindow(hwnd);
return;
}
Thread.Sleep(50);
}
}
public static string Pick(IntPtr owner, string title, string start) {
IFileOpenDialog dialog = (IFileOpenDialog)new FileOpenDialog();
try {
@@ -83,6 +112,9 @@ public static class Plan2CodeFolderPicker {
dialog.SetFolder(folder);
} catch (Exception) {}
}
Thread raiser = new Thread(delegate() { Raise(title); });
raiser.IsBackground = true;
raiser.Start();
int hr = dialog.Show(owner);
if (hr == ERROR_CANCELLED) return null;
Marshal.ThrowExceptionForHR(hr);
@@ -69,6 +69,22 @@ export function submittedAwaiting(item) {
return replied ? null : s;
}
/**
* The note (and its attachments) the person last sent on an item, while the
* agent has yet to say anything after it. The server records it as `sentNote`
* on every send, so the page can show it in the Notes pane and in the Sent
* box instead of letting it vanish into a send that shows no sign of arriving.
* Any thread message from the send onwards, or none with a clock to compare,
* means it has been picked up.
*/
export function noteAwaiting(item) {
const n = item && item.sentNote;
if (!n || typeof n !== "object") return null;
const thread = Array.isArray(item.thread) ? item.thread : [];
const picked = thread.some((m) => m && (!n.at || !m.at || m.at >= n.at));
return picked ? null : n;
}
/* -------------------------------------------------------------- labels */
export function optionLabel(item, k) {
@@ -11,10 +11,10 @@
--ink-3: #8f8779;
--rule: #e4ddd1;
--rule-2: #cfc6b6;
--accent: #ae4f2b;
--accent-soft: #fbeee7;
--accent: #206cc3;
--accent-soft: #ecf2f9;
--accent-ink: #ffffff;
--accent-line: #dd9b7e;
--accent-line: #9ab4d3;
--ok: #2f6b45;
--ok-soft: #e4f0e8;
--stage: #9a6a12;
@@ -49,10 +49,10 @@
--ink-3: #8b8376;
--rule: #332e29;
--rule-2: #46403a;
--accent: #e8825a;
--accent-soft: #34211a;
--accent-ink: #1a120e;
--accent-line: #8a4f36;
--accent: #619fe5;
--accent-soft: #1a2533;
--accent-ink: #0c1117;
--accent-line: #3d5978;
--ok: #74c28f;
--ok-soft: #1c2d22;
--stage: #e0ab4c;
@@ -73,10 +73,10 @@
--ink-3: #8b8376;
--rule: #332e29;
--rule-2: #46403a;
--accent: #e8825a;
--accent-soft: #34211a;
--accent-ink: #1a120e;
--accent-line: #8a4f36;
--accent: #619fe5;
--accent-soft: #1a2533;
--accent-ink: #0c1117;
--accent-line: #3d5978;
--ok: #74c28f;
--ok-soft: #1c2d22;
--stage: #e0ab4c;
@@ -241,6 +241,19 @@ body {
}
.meter-pop[hidden] { display: none; }
.meter-tip { margin: 0 0 6px; font-size: 13px; color: var(--ink-2); }
.meter-list {
list-style: none; margin: 0 0 8px; padding: 6px 0 0;
border-top: 1px solid var(--rule);
max-height: 40vh; overflow-y: auto;
font-size: 12px; color: var(--ink-2);
}
.meter-list[hidden] { display: none; }
.meter-list li { display: flex; justify-content: space-between; gap: 16px; padding: 2px 0; }
.meter-fresh { margin: 0 0 8px; padding-top: 6px; border-top: 1px solid var(--rule); }
.meter-fresh[hidden] { display: none; }
.meter-fresh-text { margin: 0 0 6px; font-size: 12px; color: var(--ink-2); }
.meter-fresh-row .handoff-code { flex-basis: 180px; font-size: 12px; padding: 6px 10px; }
.meter-item-points { flex: none; font-weight: 600; color: var(--ink); font-variant-numeric: tabular-nums; }
.badge {
font-size: 11px;
@@ -652,6 +665,16 @@ h1 {
}
.wake.dormant .wake-hint { opacity: 1; }
/* Skip: muted, bottom right, so it never competes with the animation. */
.wake-skip {
position: absolute; right: 14px; bottom: 14px;
padding: 4px 12px; border: 1px solid var(--ink-3); border-radius: 4px;
background: transparent; color: var(--ink-3);
font: inherit; font-size: 0.8rem; letter-spacing: 0.08em; text-transform: uppercase;
cursor: pointer; opacity: 0.7;
}
.wake-skip:hover, .wake-skip:focus-visible { opacity: 1; color: var(--ink); border-color: var(--ink); }
/* 0.0 s, powered down: the resting state every beat starts from. Arms hang
slack against his sides, the star is shut and the smile not yet drawn. */
.wake-bot { filter: grayscale(1); opacity: 0.55; }
@@ -1132,6 +1155,20 @@ h1 {
.rail-mark { flex: none; width: 15px; text-align: center; font-size: 12px; color: var(--ink-3); margin-top: 1px; }
.rail-mark.done { color: var(--ok); }
.rail-mark.staged { color: var(--stage); font-weight: 700; }
/* Echoes the center pane's "Suggested" pill, which can scroll out of view;
the dot keeps the call-out visible while just scanning the rail. The
title grows to push the dot flush with the row's right edge. */
.rail-item > span:not(.rail-mark):not(.rail-suggested-dot) { flex: 1 1 auto; }
.rail-suggested-dot {
flex: none;
width: 7px;
height: 7px;
border-radius: 50%;
margin-top: 5px;
background: var(--accent);
}
.rail-item.is-suggested:not([aria-current="true"]) { color: var(--ink); }
.rail-mark.open { color: var(--accent); }
/* The session's own page, above the topic groups. It names the state it is
@@ -1618,7 +1655,7 @@ input[type="text"].invalid { border-color: var(--warn); }
0% { box-shadow: 0 0 0 0 var(--accent-line); }
100% { box-shadow: 0 0 0 6px transparent; }
}
#btn-send:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
.btn.ghost:hover { background: var(--panel-2); color: var(--ink); }
.btn.danger { border-color: var(--warn); color: var(--warn); }
@@ -1734,6 +1771,7 @@ input[type="text"].invalid { border-color: var(--warn); }
}
.attach-row { display: flex; align-items: center; margin: -4px 0 6px -13px; }
.attach-row.is-under { margin: 6px 0 4px -13px; }
.attach-tray { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 10px; }
.attach-thumb {
position: relative;
@@ -1784,6 +1822,10 @@ input[type="text"].invalid { border-color: var(--warn); }
font-size: 12.5px; font-weight: 600; color: var(--ink);
}
.attach-chip-size { color: var(--ink-2); font-size: 11.5px; }
.attach-link { color: inherit; text-decoration: none; border-radius: 8px; }
.attach-link:hover .attach-thumb, .attach-link:focus-visible .attach-thumb { border-color: var(--accent); }
.attach-link:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.msg.pending { border-style: dashed; border-color: var(--stage); background: transparent; }
.ask-row .attach-chip { padding-right: 10px; }
.footer-held { margin-top: 3px; color: var(--ink-2); font-size: 12.5px; }
@@ -1863,6 +1905,23 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
transition: opacity 0.12s;
}
.md-pre-wrap:hover .md-copy, .md-copy:focus { opacity: 1; }
/* Run it, on git blocks: Copy's twin, tucked under it so the wider
"Press Ctrl+C" fallback label can never collide. */
.md-run {
position: absolute; top: 34px; right: 8px;
font: 600 11.5px var(--sans);
background: var(--panel); color: var(--ink-2);
border: 1px solid var(--rule-2); border-radius: 6px;
padding: 4px 9px; cursor: pointer; opacity: 0;
transition: opacity 0.12s;
}
.md-pre-wrap:hover .md-run, .md-run:focus { opacity: 1; }
/* The muted nudge on other command-looking blocks, a caption under the block. */
.md-run-hint {
margin: -6px 2px 0;
font: 11px var(--sans); color: var(--ink-3);
opacity: 0.8;
}
.md-hr { border: 0; border-top: 1px solid var(--rule); margin: 20px 0; }
.md-table-wrap { overflow-x: auto; margin: 0 0 13px; }
.md-table { border-collapse: collapse; width: 100%; font-size: 13.5px; }
@@ -1996,9 +2055,15 @@ kbd {
.icon-btn:hover .ab-mark, .icon-btn:hover .ab-dot { stroke: var(--accent); fill: none; }
.icon-btn:hover .ab-dot { fill: var(--accent); }
.icon-btn .sw-a { fill: var(--accent); }
.icon-btn .sw-b { fill: var(--ok); }
.icon-btn .sw-c { fill: var(--stage); }
a.icon-btn { box-sizing: border-box; text-decoration: none; }
.icon-btn .mg-body { fill: none; stroke: var(--ink-3); stroke-width: 1.4; stroke-linejoin: round; }
.icon-btn .mg-line { fill: none; stroke: var(--ink-2); stroke-width: 1.4; stroke-linecap: round; stroke-linejoin: round; }
.icon-btn:hover .mg-body, .icon-btn:hover .mg-line { stroke: var(--accent); }
.icon-btn .gr-teeth { fill: none; stroke: var(--ink-3); stroke-width: 2.2; }
.icon-btn .gr-ring { fill: none; stroke: var(--ink-3); stroke-width: 1.6; }
.icon-btn .gr-hub { fill: none; stroke: var(--ink-2); stroke-width: 1.4; }
.icon-btn:hover .gr-teeth, .icon-btn:hover .gr-ring, .icon-btn:hover .gr-hub { stroke: var(--accent); }
/* ------------------------------------------------------------ swatches */
@@ -2132,7 +2197,8 @@ kbd {
flex-direction: column;
}
.modal.help[open] { display: flex; }
.modal.help .modal-actions { flex: none; margin-top: 16px; }
.modal.help .modal-actions { flex: none; margin-top: 16px; align-items: center; }
.help-version { margin-right: auto; font-size: 12.5px; color: var(--ink-3); }
.help-layout {
display: grid;
@@ -2288,6 +2354,111 @@ kbd {
}
.modal::backdrop { background: rgba(0, 0, 0, 0.45); }
.modal h2 { font: 600 21px/1.25 var(--serif); margin: 0 0 10px; }
/* The Welcome: a dark poster with Planny, four columns, one button. */
.modal.welcome {
width: min(840px, calc(100vw - 32px));
max-width: none;
padding: 0;
overflow: hidden;
}
.modal.welcome[open] { display: flex; flex-direction: column; max-height: calc(100vh - 96px); }
.welcome-poster {
position: relative;
flex: none;
overflow: hidden;
padding: 52px 48px 40px;
text-align: center;
color: #fff;
background:
radial-gradient(circle at 50% 125%, color-mix(in srgb, var(--accent) 85%, #fff) 0, transparent 58%),
linear-gradient(180deg, #16181d, color-mix(in srgb, var(--accent) 50%, #16181d));
}
.welcome-sky i { position: absolute; width: 3px; height: 3px; border-radius: 50%; background: #fff; opacity: 0.55; }
.welcome-sky i:nth-child(1) { top: 18%; left: 11%; }
.welcome-sky i:nth-child(2) { top: 34%; left: 84%; }
.welcome-sky i:nth-child(3) { top: 12%; left: 66%; }
.welcome-sky i:nth-child(4) { top: 56%; left: 20%; }
.welcome-sky i:nth-child(5) { top: 62%; left: 91%; }
.welcome-sky i:nth-child(6) { top: 26%; left: 32%; width: 2px; height: 2px; }
.welcome-bot { display: flex; justify-content: center; }
/* The dock's own Planny, larger and in light ink for the dark poster. */
.welcome-bot .planny { width: 70px; height: 96px; }
.welcome-bot .planny .shell,
.welcome-bot .planny .smile,
.welcome-bot .planny .arm path { stroke: #f0ece5; }
.welcome-bot .planny .shell { fill: #1e2127; }
.welcome-bot .planny .arm circle,
.welcome-bot .planny .foot { fill: #f0ece5; }
.welcome-kicker {
margin: 20px 0 6px;
font-size: 12px;
letter-spacing: 0.14em;
text-transform: uppercase;
color: rgba(255, 255, 255, 0.75);
}
.modal.welcome h2 { font: 600 38px/1.15 var(--serif); margin: 0 0 12px; color: #fff; }
.welcome-lead { margin: 0 auto; max-width: 52ch; font-size: 15px; line-height: 1.55; color: rgba(255, 255, 255, 0.85); }
.welcome-cols {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 20px;
min-height: 0;
overflow-y: auto;
padding: 34px 36px 8px;
text-align: center;
}
.welcome-col h3 { font: 600 15px/1.3 var(--sans); margin: 12px 0 4px; color: var(--ink); }
.welcome-col p { margin: 0; font-size: 13px; line-height: 1.5; color: var(--ink-2); }
.welcome-col strong { color: var(--ink); }
.welcome-col code {
font: 600 12px var(--mono);
padding: 1px 6px;
border-radius: 5px;
background: var(--accent-soft);
color: var(--accent);
}
.welcome-col kbd {
font: 600 11.5px var(--mono);
padding: 0 6px;
border-radius: 5px;
border: 1px solid var(--rule-2);
border-bottom-width: 2px;
background: var(--panel-2);
color: var(--ink);
}
.welcome-dot { display: inline-grid; place-items: center; width: 50px; height: 50px; border-radius: 50%; }
.welcome-dot svg {
width: 22px;
height: 22px;
fill: none;
stroke: currentColor;
stroke-width: 1.8;
stroke-linecap: round;
stroke-linejoin: round;
}
.welcome-dot.is-accent { background: var(--accent-soft); color: var(--accent); }
.welcome-dot.is-stage { background: var(--stage-soft); color: var(--stage); }
.welcome-dot.is-plain { background: var(--panel-2); color: var(--ink-2); border: 1px solid var(--rule); }
.welcome-dot.is-ok { background: var(--ok-soft); color: var(--ok); }
.welcome-dot.is-bare { background: none; color: var(--ok); }
.welcome-dot.is-bare svg { width: 30px; height: 30px; }
.modal.welcome .modal-actions { flex: none; justify-content: center; margin: 0; padding: 24px 36px 36px; }
.modal.welcome .modal-actions .btn { padding: 12px 40px; font-size: 15px; border-radius: 999px; }
@media (max-width: 720px) {
.welcome-poster { padding: 36px 24px 28px; }
.modal.welcome h2 { font-size: 28px; }
.welcome-cols { grid-template-columns: 1fr 1fr; padding: 24px 20px 8px; }
}
.help-link {
background: none;
border: 0;
padding: 0;
font: inherit;
color: var(--accent);
text-decoration: underline;
cursor: pointer;
}
.help-link:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; border-radius: 2px; }
.modal-blurb { margin: 0 0 18px; color: var(--ink-2); font-size: 13.5px; }
.modal-ranges { border: 0; margin: 0; padding: 0; display: grid; gap: 8px; }
@@ -3190,3 +3361,24 @@ kbd {
.help-mood-bot, .help-mood-bot *, .help-mood-bot.is-work .eye { animation: none !important; }
#btn-send { animation: none; }
}
/* User Preferences: the launcher's model menu. */
.models-tabs { display: flex; gap: 6px; }
.models-tabs .btn[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); }
.models-note { font-size: 0.9em; opacity: 0.85; }
.models-note p, .models-note ul { margin: 0 0 6px; }
.models-note ul { padding-left: 18px; }
.models-list { display: grid; gap: 4px; max-height: 160px; overflow: auto; }
.models-list:empty { display: none; }
.models-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; gap: 6px; align-items: center; }
.models-row.locked { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); font-size: 0.88em; opacity: 0.75; }
.models-row input { min-width: 0; }
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.models-actions .help.error { color: var(--danger, #d64545); }
/* A word the person has to type, bold and in their highlight color so it
does not get lost in the status sentence. */
.agent-key {
color: var(--accent);
font-weight: 700;
}
@@ -10,7 +10,7 @@
// this, that reversibility is the whole point.
import { md, el, copyButton, selectContents } from "./render.js";
import { ACCENTS, DEFAULT_CARD_WIDTH, SOUND_EVENTS, cardWidth, soundKey, soundPrefs } from "./palette.js";
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, SOUND_EVENTS, cardWidth, soundKey, soundPrefs } from "./palette.js";
import { activityLabel, workingLine } from "./labels.js";
import { playWake } from "./boot.js";
import {
@@ -64,6 +64,7 @@ import {
STOP_REPLY,
sentAnswer,
submittedAwaiting,
noteAwaiting,
suggestionFrom,
THUMB_EDGE,
turnGate,
@@ -128,7 +129,7 @@ const LOOKS_KEY = "p2c-console:looks";
// The per-event sound switches (SOUND_EVENTS) live in palette.js too.
const DEFAULT_LOOKS = {
theme: "system",
accent: "rust",
accent: DEFAULT_ACCENT,
sound: true,
...soundPrefs(null),
width: DEFAULT_CARD_WIDTH,
@@ -136,6 +137,8 @@ const DEFAULT_LOOKS = {
};
let looks = { ...DEFAULT_LOOKS };
let syncedLooks = null;
let looksReady = false;
function adoptLooks(saved) {
looks = { ...DEFAULT_LOOKS, ...saved };
@@ -178,25 +181,47 @@ async function syncLooks() {
}
if (saved && saved.looks && typeof saved.looks === "object") {
adoptLooks(saved.looks);
syncedLooks = { ...looks };
try {
localStorage.setItem(LOOKS_KEY, JSON.stringify(looks));
} catch {}
applyLooks();
renderSwatches();
} else if (localStorage.getItem(LOOKS_KEY)) {
pushLooks();
} else {
// Blocked storage throws on read, and that must not stop the page loading.
let held = false;
try {
held = Boolean(localStorage.getItem(LOOKS_KEY));
} catch {}
if (held) pushLooks();
}
looksReady = true;
// Not inline: with the server's copy in the page this runs before `S` exists.
setTimeout(maybeWelcome, 0);
}
// Fire-and-forget mirror. A failed POST costs nothing the next session would
// notice on this port; the localStorage copy still covers the reload case.
function pushLooks() {
try {
// Only what this tab changed since it last synced, so a tab with stale
// settings never overwrites another tab's change to a different key.
const set = {};
for (const [k, v] of Object.entries(looks)) if (!syncedLooks || syncedLooks[k] !== v) set[k] = v;
const before = syncedLooks;
const partial = Boolean(before);
if (partial && !Object.keys(set).length) return;
syncedLooks = { ...looks };
const body = partial ? { set } : { looks };
// A write that did not land must be sent again with the next change.
const undo = () => (syncedLooks = before);
fetch("/looks", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ looks }),
}).catch(() => {});
body: JSON.stringify(body),
})
.then((res) => res.ok || undo())
.catch(undo);
} catch {}
}
@@ -380,6 +405,24 @@ for (const evt of ["pointerdown", "keydown"]) {
});
}
// Run it, on a fenced git block (render.js): stage the block as the Ask
// draft and open the chat. The person still presses Send, so nothing runs
// on a stray click — the same fill-the-box pattern as the Ask starters.
document.addEventListener("click", (e) => {
const run = e.target.closest(".md-run");
if (!run) return;
const code = run.closest(".md-pre-wrap")?.querySelector("code");
if (!code || !code.textContent.trim()) return;
local.chat.draft = `run:\n${code.textContent}`;
view = "ask";
save();
render();
const ta = $("ask-input");
if (!ta) return;
ta.focus();
ta.setSelectionRange(ta.value.length, ta.value.length);
});
// The stars for Planny's flight, made once. Each gets its place and pace as
// custom properties set through the CSSOM: the CSP forbids style attributes
// in markup, and the stylesheet cannot roll dice. They sit still, invisible,
@@ -795,13 +838,16 @@ async function loadState() {
const res = await fetch("/state", { cache: "no-store" });
if (!res.ok) throw new Error(String(res.status));
const body = await res.json();
adopt(body);
// The server answers again: back to the stream, once the wait is up.
if (!es && pollTimer && Date.now() >= esRetryAt) {
clearInterval(pollTimer);
pollTimer = null;
connect();
// The same rev is the same state: adopting it again would redraw the page
// every few seconds while polling for nothing. Still proof of life, though.
if (S && typeof body.rev === "number" && body.rev === rev) {
lastContact = Date.now();
agentLastSeen = body.agentLastSeen || agentLastSeen;
markGone();
} else {
adopt(body);
}
retryStream();
} catch {
markGone();
}
@@ -1158,6 +1204,11 @@ function connect() {
esErrors = 0;
esRetryMs = ES_RETRY_MIN_MS;
lastContact = Date.now();
// Back on the stream: polling was only ever the stand-in.
if (pollTimer) {
clearInterval(pollTimer);
pollTimer = null;
}
};
es.onerror = () => {
esErrors++;
@@ -1179,6 +1230,18 @@ function startPolling() {
pollTimer = setInterval(loadState, 3000);
}
// While polling, every answer from the server is a cue to try the stream
// again, so polling lasts only as long as the outage did. Polling carries on
// while an attempt is open, so startPolling() never runs for a failed one; the
// wait is pushed back here instead, or a dead stream would be retried on every
// poll. One attempt at a time, since `es` is set while it is trying.
function retryStream() {
if (!pollTimer || es || Date.now() < esRetryAt) return;
esRetryAt = Date.now() + esRetryMs;
esRetryMs = Math.min(esRetryMs * 2, ES_RETRY_MAX_MS);
connect();
}
setInterval(() => {
fetch("/ping", { method: "POST" })
.then((r) => (r.ok ? r.json() : null))
@@ -1186,6 +1249,7 @@ setInterval(() => {
if (!body) return;
lastContact = Date.now();
agentLastSeen = body.agentLastSeen || agentLastSeen;
retryStream();
// A rev we have not seen means a state frame went missing -- a dropped
// SSE reconnect, a tab asleep in a background window. Ask for it rather
// than waiting for the next change to come along.
@@ -1442,6 +1506,31 @@ function renderMeter() {
$("meter-words").textContent = meterFrame.words;
pill.title = meterFrame.tooltip;
$("meter-tip").textContent = meterFrame.tooltip;
// What the points are made of: one row per piece of work that scored.
const list = $("meter-list");
const rows = Array.isArray(meterFrame.items) ? meterFrame.items : [];
list.hidden = !rows.length;
list.replaceChildren(
...rows.map((row) => {
const li = el("li");
li.appendChild(el("span", "meter-item-label", row.label));
li.appendChild(el("span", "meter-item-points", "+" + row.points));
return li;
})
);
// Once the session is past fresh, say how to start a new one.
const fresh = $("meter-fresh");
fresh.hidden = meterFrame.level === "green";
if (fresh.hidden || fresh.dataset.built) return;
fresh.dataset.built = "1";
const text = handoffText({ command: DASHBOARD_COMMAND });
const code = el("code", "handoff-code", text);
const row = el("div", "handoff-command meter-fresh-row");
row.append(code, copyButton(text, "btn small ghost handoff-copy", code));
fresh.append(
textWithCode("p", "meter-fresh-text", `To start a new session, run \`${DASHBOARD_COMMAND}\` in a new conversation:`),
row
);
}
function toggleMeterPop(open) {
@@ -1469,7 +1558,7 @@ function renderChrome() {
renderMeter();
$("title").textContent = S.title || "Session";
$("badge").textContent = workflowLabel(S.workflow);
document.title = (S.title || "Session") + " · Plan2Code";
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
const h = S.headline || {};
// On a finished session an open item is frozen: the send on it counts as
@@ -1529,7 +1618,18 @@ function renderStatus() {
moodVar = Math.floor(Math.random() * MOOD_VARIANTS[mood]);
}
bot.setAttribute("class", `planny is-${mood} v${moodVar}`);
if (text.textContent !== line) text.textContent = line;
if (text.dataset.line !== line) {
text.dataset.line = line;
text.replaceChildren(
...line.split(/\*\*(.+?)\*\*/).map((part, i) => {
if (i % 2 === 0) return document.createTextNode(part);
const key = document.createElement("strong");
key.className = "agent-key";
key.textContent = part;
return key;
})
);
}
tick.textContent = count || "";
$("agent-spin").hidden = !spin;
$("dock").classList.toggle("is-flying", Boolean(spin));
@@ -1584,7 +1684,7 @@ function renderStatus() {
if (agentStale()) {
return say(
"work",
"Plan2Code has not checked in for a few minutes. Your answers are saved. Have a look at your terminal (it may be happily working away, or waiting for your permission approval)."
"Still working on it. Longer tasks can go a few minutes between updates. Your answers are saved. If it stays quiet for a long while, check your terminal (it may be waiting on a permission approval)."
);
}
// Same clock as agentStale(), so the soft line at 30 s hands over to the
@@ -1602,8 +1702,8 @@ function renderStatus() {
return say(
"adrift",
stranded()
? "Plan2Code is not running. Your answers are saved and waiting for it. The terminal may be waiting for your permission approval."
: "Plan2Code is not running right now. Anything you answer here is saved. The terminal may be waiting for your permission approval."
? "Plan2Code is not running. Your answers are saved and waiting for it. If the terminal is idle, type **continue** there and it will pick them up; it may also be waiting for your permission approval."
: "Plan2Code is not running right now. Anything you answer here is saved. If the terminal is idle, type **continue** there to wake it; it may also be waiting for your permission approval."
);
}
@@ -1740,7 +1840,7 @@ function renderViews() {
for (const t of tabs) {
const b = el("button", "view-tab", t.label);
b.type = "button";
b.setAttribute("aria-current", String(view === t.id));
b.setAttribute("aria-current", String(view === t.id || (t.id === "questions" && view === "end")));
if (t.count) {
const c = el("span", "tab-count", String(t.count));
b.appendChild(c);
@@ -1756,7 +1856,7 @@ function renderViews() {
chatDot = false;
save();
}
view = t.id;
view = t.id === "questions" && finish() ? "end" : t.id;
// The cached text paints at once; the fresh read repaints if the file
// changed on disk since.
render();
@@ -1821,16 +1921,20 @@ function renderSidebar() {
// session outline usually lives. The card that is mid-launch gets the
// half-filled mark the page uses for "sent, on its way".
if (isDashboard() && !fin) {
const menu = (S && S.menu) || {};
for (const g of CATALOG_GROUPS) {
const box = el("div", "rail-group");
const head = el("p", "rail-title");
head.appendChild(el("span", null, g.title));
box.appendChild(head);
for (const e of SKILL_CATALOG.filter((x) => x.group === g.id)) {
const av = cardAvailability(e, scan(), selSpec());
const av = cardPresentation(e, scan(), selSpec(), menu);
// Unavailable for the selected spec fades hard; the brief greying
// while a launch is in flight or the server is away does not.
const b = el("button", "rail-item" + (av.on ? "" : " is-unavailable"));
const b = el(
"button",
"rail-item" + (av.on ? "" : " is-unavailable") + (av.recommended ? " is-suggested" : "")
);
b.type = "button";
b.disabled = Boolean(local.launching) || gone || pendingResult || !av.on;
if (!av.on && av.reason) b.title = av.reason;
@@ -1845,6 +1949,13 @@ function renderSidebar() {
mark.title = isGoing ? "starting" : isPicked ? "picked" : "pick to start";
b.appendChild(mark);
b.appendChild(el("span", null, e.title));
// The center pane's own "Suggested" pill scrolls out of view, so the
// rail repeats the call-out here as a small dot next to the title.
if (av.recommended) {
const dot = el("span", "rail-suggested-dot", "");
dot.title = "Suggested next step";
b.appendChild(dot);
}
// Same as a card click: the pick goes to the confirm pane, never
// straight to a launch. From the Overview tab too, so the pane shows.
b.addEventListener("click", () => {
@@ -2465,6 +2576,34 @@ function renderDashboard(main) {
if (note) revealNote(note, wake.typed);
}
main.appendChild(wrap);
// Deferred: this runs inside render(), and the dialog is not part of it.
queueMicrotask(maybeWelcome);
}
/* ------------------------------------------------------------- welcome */
// The first dashboard a person ever sees gets a Welcome dialog. Closing it by
// any route (button, Esc, backdrop) saves looks.welcomeSeen, which rides in
// looks.json like every other preference. Waits out the wake-up animation and
// never lands on top of another open dialog.
function maybeWelcome() {
if (!looksReady || looks.welcomeSeen === true || !S || !isDashboard() || finish() || wake) return;
if (document.querySelector("dialog[open]")) return;
openWelcome();
}
function openWelcome() {
if ($("help-modal").open) $("help-modal").close();
const slot = $("welcome-bot");
if (!slot.firstElementChild) {
const bot = $("planny").cloneNode(true);
bot.removeAttribute("id");
bot.setAttribute("class", "planny is-point v1");
slot.appendChild(bot);
}
const dlg = $("welcome-modal");
if (!dlg.open) dlg.showModal();
$("welcome-done").focus();
}
/* ------------------------------------------------------------- wake-up */
@@ -2505,10 +2644,12 @@ function maybeWake() {
playWake({
stage,
bot: stage.querySelector(".wake-bot"),
skipEl: stage.querySelector(".wake-skip"),
target: $("planny"),
stir: stirWake,
onStart: () => sound("bootup"),
onGlide: wakeGlide,
onSkip: skipWakeSounds,
signal: wake.abort.signal,
}).then(({ skipped }) => {
stopSnore();
@@ -2541,6 +2682,14 @@ function stopSnore() {
snore = null;
}
// The Skip button: silence anything the intro already queued or started. The
// promise's .then does the snore and the bootup fade; this only clears cues
// still waiting to play.
function skipWakeSounds() {
soundQueued = null;
soundHeld = null;
}
// The glide: the menu rises in and the note starts typing. On a skip the run
// is already ending and its promise settles everything, so nothing here.
function wakeGlide({ instant }) {
@@ -2575,7 +2724,10 @@ function typeNote() {
// Done once the entrance has played and the note is all there. Nothing to
// redraw: what is on screen already is the finished dashboard.
function settleWake() {
if (wake && wake.entered && wake.typed == null) wake = null;
if (wake && wake.entered && wake.typed == null) {
wake = null;
maybeWelcome();
}
}
function finishWake() {
@@ -3206,6 +3358,34 @@ function inFlightFor(item) {
return sub ? { value: sub, summary: "" } : null;
}
// A sent note's attachments as links: an image opens full size, a document
// opens in its own tab. The page serves both by the upload's own file name.
function sentAttachments(note) {
const entries = [
...(note.images || []).map((e) => ({ ...e, kind: "image" })),
...(note.files || []).map((e) => ({ ...e, kind: "file" })),
];
if (!entries.length) return null;
const tray = el("div", "attach-tray");
for (const e of entries) {
const a = el("a", "attach-link");
a.href = uploadUrl(e);
a.target = "_blank";
a.rel = "noopener";
a.title = e.name || "attachment";
if (e.kind === "image") {
const fig = el("figure", "attach-thumb is-ready");
const pic = el("img");
pic.src = a.href;
pic.alt = e.name || "image";
fig.appendChild(pic);
a.appendChild(fig);
} else a.appendChild(docChip({ name: e.name || "file" }, "ready"));
tray.appendChild(a);
}
return tray;
}
function renderCard(item) {
const staged = local.staged[item.id];
const flight = inFlightFor(item);
@@ -3357,6 +3537,13 @@ function renderInFlight(card, item, flight) {
box.appendChild(ul);
}
if (text) box.appendChild(el("blockquote", "answered-text", text));
const note = noteAwaiting(item);
const sub = submittedAwaiting(item);
if (note && sub && note.at === sub.at) {
if (note.text) box.appendChild(el("blockquote", "answered-text", note.text));
const tray = sentAttachments(note);
if (tray) box.appendChild(tray);
}
// Say which of the two it actually is. Once the agent has collected the send,
// "waiting to be picked up" is no longer true, and a status line that lies is
@@ -3660,6 +3847,19 @@ function stageQuiet(id, value) {
save();
}
// The next answer for a click, carrying over the words typed on the card. Note
// boxes stage quietly, without a render, so the `staged` a builder closed over
// at render time can be missing everything typed since: read the live answer
// when the click lands instead. A click that clears the pick while text is
// still in the box keeps the text as a note on its own (`bare`), the same shape
// the note box stages when nothing is picked.
function withNote(item, value, bare = { type: "answer", kind: item.kind }) {
const cur = local.staged[item.id];
const text = cur && cur.text;
if (!text) return value;
return value ? { ...value, text } : { ...bare, text };
}
// Unique per question and option, and the same on every render.
const optionId = (item, o, i) => `pick-${item.id}-${o.k || i}`;
@@ -3724,12 +3924,18 @@ function buildMulti(card, item, staged) {
box.checked = on;
box.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
box.addEventListener("change", () => {
const next = new Set(chosen);
const cur = local.staged[item.id];
const next = new Set((cur && cur.ks) || []);
if (box.checked) next.add(o.k);
else next.delete(o.k);
// Unticking the last box keeps what is written in "Anything else".
stage(
item.id,
next.size ? { type: "answer", kind: "multi", ks: [...next], text: staged && staged.text } : null
withNote(item, next.size ? { type: "answer", kind: "multi", ks: [...next] } : null, {
type: "answer",
kind: "multi",
ks: [],
})
);
});
@@ -3772,7 +3978,14 @@ function renderPresets(card, item, staged) {
b.type = "button";
b.setAttribute("aria-pressed", String(on));
b.addEventListener("click", () =>
stage(item.id, on ? null : { type: "answer", kind: "multi", ks: [...p.ks], text: staged && staged.text })
stage(
item.id,
withNote(item, on ? null : { type: "answer", kind: "multi", ks: [...p.ks] }, {
type: "answer",
kind: "multi",
ks: [],
})
)
);
row.appendChild(b);
}
@@ -3858,6 +4071,20 @@ function buildText(card, item, staged) {
wrap.appendChild(templateRow(item, input, templatesFor(S.workflow, looks.role), check));
}
wrap.appendChild(input);
// Fresh-idea boxes take files as context, the same ones the note pane holds.
if (!single && TEMPLATE_WORKFLOWS.includes(S.workflow)) {
input.addEventListener("paste", (e) => {
const files = incomingFiles(e.clipboardData && e.clipboardData.files);
if (!files.length) return;
if (!e.clipboardData.getData("text/plain")) e.preventDefault();
attachFiles(item.id, files);
});
const under = attachRow(item.id, "Add files to this answer");
under.classList.add("is-under");
wrap.appendChild(under);
const attached = noteImages(item.id);
if (attached.length) wrap.appendChild(attachTray(item.id, attached));
}
if (item.help) wrap.appendChild(el("p", "help", item.help));
wrap.appendChild(err);
card.appendChild(wrap);
@@ -3946,7 +4173,9 @@ function buildConfirm(card, item, staged) {
const on = staged && staged.yes === yes;
const b = el("button", "btn" + (on ? " primary" : "") + (danger && !on ? " danger" : ""), label);
b.type = "button";
b.addEventListener("click", () => stage(item.id, on ? null : { type: "answer", kind: "confirm", yes }));
b.addEventListener("click", () =>
stage(item.id, withNote(item, on ? null : { type: "answer", kind: "confirm", yes }))
);
return b;
};
row.appendChild(mk(yesLabel, true, item.danger));
@@ -4031,7 +4260,7 @@ function buildReview(card, item, staged) {
const b = el("button", "btn" + (on ? " primary" : "") + (v.danger && !on ? " danger" : ""), verdictText(v));
b.type = "button";
b.addEventListener("click", () =>
stage(item.id, on ? null : { type: "answer", kind: "review", verdict: v.id, text: staged && staged.text })
stage(item.id, withNote(item, on ? null : { type: "answer", kind: "review", verdict: v.id }))
);
row.appendChild(b);
}
@@ -4044,6 +4273,15 @@ function buildReview(card, item, staged) {
function buildChecklist(card, item, staged) {
const doneSet = new Set((staged && staged.done) || []);
// Built from the live answer, so a note typed since the render rides along.
// Nothing ticked, no state and no note is no answer at all: stage nothing
// rather than an empty one that would still count as ready to send.
const commitList = (change) => {
const cur = local.staged[item.id];
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
const empty = !(next.done && next.done.length) && !next.state && !next.text;
stage(item.id, empty ? null : next);
};
const list = el("ol", "steps");
(item.steps || []).forEach((step, i) => {
const li = el("li", "step");
@@ -4052,10 +4290,11 @@ function buildChecklist(card, item, staged) {
box.id = `step-${item.id}-${i}`;
box.checked = doneSet.has(i);
box.addEventListener("change", () => {
const next = new Set(doneSet);
const cur = local.staged[item.id];
const next = new Set((cur && cur.done) || []);
if (box.checked) next.add(i);
else next.delete(i);
stage(item.id, { ...(staged || { type: "answer", kind: "checklist" }), done: [...next] });
commitList({ done: [...next] });
});
const label = el("label");
label.htmlFor = box.id;
@@ -4079,14 +4318,7 @@ function buildChecklist(card, item, staged) {
const on = staged && staged.state === s.id;
const b = el("button", "btn" + (on ? " primary" : ""), s.label);
b.type = "button";
b.addEventListener("click", () =>
stage(item.id, {
...(staged || { type: "answer", kind: "checklist" }),
type: "answer",
kind: "checklist",
state: on ? null : s.id,
})
);
b.addEventListener("click", () => commitList({ state: on ? null : s.id }));
row.appendChild(b);
}
card.appendChild(row);
@@ -4142,7 +4374,7 @@ function buildList(card, item, staged) {
const ul = el("ul", "rows");
let dragIndex = null;
const commit = (next) => stage(item.id, { type: "answer", kind: "list", rows: next });
const commit = (next) => stage(item.id, withNote(item, { type: "answer", kind: "list", rows: next }));
rows.forEach((row, i) => {
const li = el("li", "row-item");
@@ -4245,7 +4477,8 @@ function buildList(card, item, staged) {
if (staged) {
const reset = el("button", "linky", "Put it back how it was");
reset.type = "button";
reset.addEventListener("click", () => stage(item.id, null));
// Puts the rows back; a note typed below stays.
reset.addEventListener("click", () => stage(item.id, withNote(item, null)));
row.appendChild(reset);
}
card.appendChild(row);
@@ -4267,8 +4500,14 @@ function commentField(card, item, labelText, required) {
ta.addEventListener("input", () => {
setDraft(id, ta.value);
const cur = local.staged[item.id];
if (cur) stageQuiet(item.id, { ...cur, text: ta.value.trim() || undefined });
else if (ta.value.trim())
if (cur) {
const next = { ...cur, text: ta.value.trim() || undefined };
// Emptying the box of a note-only answer leaves nothing to send, so it
// unstages rather than counting as ready.
const empty = (v) => v == null || v === "" || (Array.isArray(v) && !v.length);
const bare = Object.keys(next).every((k) => k === "type" || k === "kind" || empty(next[k]));
stageQuiet(item.id, bare ? null : next);
} else if (ta.value.trim())
stageQuiet(item.id, { type: "answer", kind: item.kind, text: ta.value.trim() });
stagedChanged();
});
@@ -4424,8 +4663,8 @@ function askState() {
// frame for the moment after a 409 stale, before the new frame lands.
const askConversation = () => local.chat.conversation ?? askFrame().conversation;
// An upload's server path is `<session>/uploads/<uuid>.jpg`; the page serves
// it at /uploads/<uuid>.jpg.
// An upload's server path is `<session>/uploads/<uuid>.<ext>`; the page serves
// it at /uploads/<uuid>.<ext>.
const uploadUrl = (img) => img.url || "/uploads/" + String(img.path || "").split(/[\\/]/).pop();
function renderAsk(main) {
@@ -4983,7 +5222,7 @@ function renderAside() {
aside.appendChild(el("h2", null, "Notes on this"));
const thread = item.thread || [];
if (!thread.length) {
if (!thread.length && !(isOpen(item) && !finish() && noteAwaiting(item))) {
aside.appendChild(
el(
"p",
@@ -5004,6 +5243,21 @@ function renderAside() {
aside.appendChild(box);
}
// A note that has been sent but not yet picked up: shown at once, so the
// send is seen to have gone, and gone when the agent replies.
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
if (waiting) {
const box = el("div", "msg you pending");
const who = el("div", "msg-who");
who.appendChild(el("span", null, "You"));
who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
box.appendChild(who);
if (waiting.text) box.appendChild(md(waiting.text, "md"));
const tray = sentAttachments(waiting);
if (tray) box.appendChild(tray);
aside.appendChild(box);
}
// A finished session has nobody left for a note to reach, so the box would
// be a place to type words that go nowhere.
if (!isOpen(item) || finish()) {
@@ -5018,24 +5272,7 @@ function renderAside() {
wrap.appendChild(label);
const attached = noteImages(item.id);
const addRow = el("div", "attach-row");
const addBtn = el("button", "btn small ghost", "+ Attach file");
addBtn.type = "button";
addBtn.setAttribute("aria-label", "Add files to this note");
addBtn.disabled = attached.length >= MAX_ATTACHMENTS;
const picker = el("input");
picker.type = "file";
picker.accept = pickerAccept();
picker.multiple = true;
picker.hidden = true;
addBtn.addEventListener("click", () => picker.click());
picker.addEventListener("change", () => {
attachFiles(item.id, picker.files);
picker.value = "";
});
addRow.appendChild(addBtn);
addRow.appendChild(picker);
wrap.appendChild(addRow);
wrap.appendChild(attachRow(item.id, "Add files to this note"));
if (attached.length) wrap.appendChild(attachTray(item.id, attached));
@@ -5079,8 +5316,8 @@ function pageIcon() {
return svg;
}
// A document in a tray: never an <img>, since documents are never served
// back. Icon, extension badge, name and size, and nothing to click but ×.
// A document in a tray: never an <img>, since a document is not a picture.
// Icon, extension badge, name and size; a sent one is wrapped in a link.
function docChip(entry, status) {
const ext = docExt(entry.name) || "";
const fig = el("figure", `attach-thumb attach-chip is-${status}`);
@@ -5096,6 +5333,29 @@ function docChip(entry, status) {
return fig;
}
// The + Attach file control and its hidden picker, for a note's box or a
// card's own. Files go to the item's note attachments either way.
function attachRow(itemId, ariaLabel) {
const row = el("div", "attach-row");
const btn = el("button", "btn small ghost", "+ Attach file");
btn.type = "button";
btn.setAttribute("aria-label", ariaLabel);
btn.disabled = noteImages(itemId).length >= MAX_ATTACHMENTS;
const picker = el("input");
picker.type = "file";
picker.accept = pickerAccept();
picker.multiple = true;
picker.hidden = true;
btn.addEventListener("click", () => picker.click());
picker.addEventListener("change", () => {
attachFiles(itemId, picker.files);
picker.value = "";
});
row.appendChild(btn);
row.appendChild(picker);
return row;
}
function attachTray(itemId, attached) {
const tray = el("div", "attach-tray");
for (const img of attached) {
@@ -5220,8 +5480,8 @@ function setNoteImages(itemId, list) {
else delete local.images[itemId];
}
// Where an attachment is deleted from. Documents are never served back, so
// they have no `url`; their route is built from the path, as uploadUrl does.
// Where an attachment is deleted from. Documents have no `url`, so their
// route is built from the path, as uploadUrl does.
const deleteUrl = (entry) => entry.url || "/uploads/" + String(entry.path || "").split(/[\\/]/).pop();
// The files in a paste worth attaching: images and allowed documents. A paste
@@ -6461,7 +6721,7 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
.md-table th, .md-table td { border: 1px solid #e4ddd1; padding: 8px 11px; text-align: left; }
.md-table th { background: #fbf9f6; font-weight: 600; }
.md-img { max-width: 100%; border-radius: 8px; }
.md a { color: #ae4f2b; }
.md a { color: #206cc3; }
@media print {
body { background: #fff; }
main { padding: 0; min-height: 0; }
@@ -6585,7 +6845,7 @@ function renderAbout() {
} else if (agentAdrift()) {
line.classList.add("is-bad");
line.textContent =
"Right now: this page is fine, but Plan2Code has not checked in for a few minutes. Have a look at the terminal; it may have finished its turn, hit an error, or be waiting on you there.";
"Right now: this page is fine, but Plan2Code has not checked in for a few minutes. Have a look at the terminal; it may have finished its turn, hit an error, or be waiting on you there. If it is idle, type continue there to wake it.";
} else {
line.classList.add("is-good");
line.textContent = "Right now: both halves are talking to each other.";
@@ -6594,6 +6854,18 @@ function renderAbout() {
let helpBuilt = false;
async function renderHelpVersion() {
const el = $("help-version");
try {
const res = await fetch("/version", { cache: "no-store" });
const { version } = res.ok ? await res.json() : {};
el.textContent = version ? "Plan2Code v" + version : "";
el.hidden = !version;
} catch {
el.hidden = true;
}
}
const HELP_MOODS = [
["point", "Your turn"],
["work", "Working"],
@@ -6683,6 +6955,7 @@ function openHelp() {
});
selectHelpTab(id);
renderAbout();
renderHelpVersion();
$("help-modal").showModal();
$("help-tab-" + id).focus();
}
@@ -6729,6 +7002,19 @@ function lightDismiss(dlg) {
lightDismiss($("looks-modal"));
lightDismiss($("help-modal"));
lightDismiss($("workspace-modal"));
lightDismiss($("welcome-modal"));
$("welcome-done").addEventListener("click", () => $("welcome-modal").close());
$("welcome-modal").addEventListener("close", () => {
if (looks.welcomeSeen !== true) {
looks.welcomeSeen = true;
saveLooks();
}
$("btn-about").focus();
});
$("help-panels").addEventListener("click", (e) => {
if (e.target.closest && e.target.closest('[data-action="welcome"]')) openWelcome();
});
$("btn-about").addEventListener("click", () => {
openHelp();
@@ -6757,6 +7043,8 @@ $("help-modal").addEventListener("keydown", (e) => {
$("btn-looks").addEventListener("click", () => {
renderSwatches();
setModelsStatus("", false);
loadModelsData();
$("looks-modal").showModal();
});
$("looks-done").addEventListener("click", () => $("looks-modal").close());
@@ -6764,7 +7052,7 @@ $("looks-modal").addEventListener("close", () => {
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
});
$("looks-reset").addEventListener("click", () => {
looks = { ...DEFAULT_LOOKS, role: ROLE_NOT_SET };
looks = { ...DEFAULT_LOOKS, role: ROLE_NOT_SET, welcomeSeen: looks.welcomeSeen };
saveLooks();
render();
});
@@ -6812,6 +7100,101 @@ for (const box of document.querySelectorAll("input[data-sound]")) {
});
}
// Models: the launcher's menu. The built-in list ships with every install and is read-only
// here; what the person adds is saved to the server, which the launcher reads on its next run.
let modelsData = null;
let modelsTab = "claude";
function setModelsStatus(text, isError) {
const status = $("models-status");
status.textContent = text;
status.classList.toggle("error", Boolean(isError));
}
function renderModels() {
for (const cli of ["claude", "devin"]) {
$("models-tab-" + cli).setAttribute("aria-pressed", String(cli === modelsTab));
}
const shipped = $("models-shipped");
const user = $("models-user");
shipped.replaceChildren();
user.replaceChildren();
if (!modelsData) {
setModelsStatus("Models could not be loaded.", true);
return;
}
for (const m of modelsData.shipped[modelsTab] || []) {
const row = el("div", "models-row locked");
row.append(el("span", null, m.id), el("span", null, m.label || ""));
shipped.appendChild(row);
}
const mine = modelsData.user[modelsTab];
mine.forEach((m, i) => {
const row = el("div", "models-row");
const id = el("input");
id.value = m.id;
id.placeholder = "Model id";
id.setAttribute("aria-label", "Model id");
const label = el("input");
label.value = m.label;
label.placeholder = "Name shown in the menu";
label.setAttribute("aria-label", "Name shown in the menu");
const remove = el("button", "btn small ghost", "Remove");
remove.type = "button";
id.addEventListener("change", () => { m.id = id.value.trim(); saveModels(); });
label.addEventListener("change", () => { m.label = label.value.trim(); saveModels(); });
remove.addEventListener("click", () => {
mine.splice(i, 1);
saveModels();
renderModels();
});
row.append(id, label, remove);
user.appendChild(row);
});
}
async function saveModels() {
try {
const res = await fetch("/models", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ models: modelsData.user }),
});
const body = await res.json();
if (!res.ok) return setModelsStatus(body.error || "Could not save.", true);
setModelsStatus("Saved. Restart plan2code to use it.", false);
} catch {
setModelsStatus("Could not save.", true);
}
}
async function loadModelsData() {
try {
const res = await fetch("/models");
if (res.ok) modelsData = await res.json();
} catch {}
renderModels();
}
for (const cli of ["claude", "devin"]) {
$("models-tab-" + cli).addEventListener("click", () => {
modelsTab = cli;
renderModels();
});
}
$("models-add").addEventListener("click", () => {
if (!modelsData) return;
modelsData.user[modelsTab].push({ id: "", label: "" });
renderModels();
$("models-user").querySelector(".models-row:last-child input")?.focus();
});
$("models-reset").addEventListener("click", () => {
if (!modelsData) return;
modelsData.user = { claude: [], devin: [] };
saveModels();
renderModels();
});
$("btn-brief").addEventListener("click", openBrief);
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
$("brief-go").addEventListener("click", sendBrief);
@@ -24,10 +24,13 @@ export const DONE_AT_MS = 5000;
// sound. `onGlide({ instant })` is the page's cue to bring the menu in: called
// at the glide, or with `instant: true` if the run ends before one (a skip).
// From the nudge on, clicks and keys are swallowed, so the run always plays
// out to the end with its sound; only `signal` aborting (the page leaving the
// dashboard, dormant or mid-run) cuts it short, as a skip. Under reduced
// motion nothing is shown and it resolves at once.
export function playWake({ stage, bot, target, stir, onStart, onGlide, signal }) {
// out to the end with its sound; only `skipEl` (the muted Skip button, or the
// Escape key, for anyone without a mouse) and `signal` aborting (the page
// leaving the dashboard, dormant or mid-run) cut it short, as a skip.
// `onSkip` is the page's cue to silence the intro sounds
// once a skip lands. Under reduced motion nothing is shown and it resolves at
// once.
export function playWake({ stage, bot, target, skipEl, stir, onStart, onGlide, onSkip, signal }) {
return new Promise((resolve) => {
if (matchMedia("(prefers-reduced-motion: reduce)").matches || signal?.aborted) {
resolve({ skipped: false });
@@ -41,8 +44,18 @@ export function playWake({ stage, bot, target, stir, onStart, onGlide, signal })
if (e.target === bot && e.propertyName === "transform") end(false);
};
const skip = () => end(true);
// Browser and OS shortcuts (reload, tab switch, devtools) still go through.
// The Skip button's events must reach it: the document handlers below run
// in the capture phase, ahead of the button's own click.
const hitsSkip = (e) => Boolean(skipEl && e.target instanceof Node && skipEl.contains(e.target));
const onSkipClick = () => end(true);
// Browser and OS shortcuts (reload, tab switch, devtools) still go through;
// Escape skips, so the run can be left by keyboard too.
const swallow = (e) => {
if (hitsSkip(e)) return;
if (e.key === "Escape") {
onSkipClick();
return;
}
if (e.ctrlKey || e.metaKey || e.altKey) return;
e.preventDefault();
e.stopPropagation();
@@ -79,6 +92,8 @@ export function playWake({ stage, bot, target, stir, onStart, onGlide, signal })
document.removeEventListener("keydown", swallow, true);
bot.removeEventListener("transitionend", onGlideEnd);
signal?.removeEventListener("abort", skip);
skipEl?.removeEventListener("click", onSkipClick);
if (skipped) onSkip?.();
stage.hidden = true;
stage.classList.remove("dormant", "stirring", "booting", "gliding");
bot.style.removeProperty("--wake-glide");
@@ -89,6 +104,11 @@ export function playWake({ stage, bot, target, stir, onStart, onGlide, signal })
// The waking click is the only input the run takes: from here on every
// click and key is swallowed until it ends.
function start(e) {
if (hitsSkip(e)) return;
if (e.key === "Escape") {
onSkipClick();
return;
}
e.preventDefault();
document.removeEventListener("pointerdown", start, true);
document.removeEventListener("keydown", start, true);
@@ -110,6 +130,7 @@ export function playWake({ stage, bot, target, stir, onStart, onGlide, signal })
document.addEventListener("pointerdown", start, true);
document.addEventListener("keydown", start, true);
skipEl?.addEventListener("click", onSkipClick);
signal?.addEventListener("abort", skip);
stage.hidden = false;
stage.classList.add("dormant");
@@ -211,13 +211,15 @@ export function shouldChime(prevDot, nextDot) {
const ADRIFT_MS = 3 * 60 * 1000;
/**
* Whether nobody is there to answer a chat message. A finished or paused
* session has no agent coming back to it; otherwise the agent is offline once
* it has been silent longer than the page would tolerate before calling it
* stuck (working) or adrift (anything else).
* Whether nobody is there to answer a chat message. A finished session's agent
* is often still listening through its last wait (the review and dashboard
* buttons on the hand-off card live as long as it does), so finish alone does
* not end the chat — going quiet does. Offline once the agent has been silent
* longer than the page would tolerate before calling it stuck (working) or
* adrift (anything else), which is also the only signal left once the server
* is gone.
*/
export function chatOffline({ finish, agent, agentLastSeenMs, now }) {
if (finish) return true;
const silent = now - agentLastSeenMs;
if (agent && agent.status === "working") return silent > quietLimitMs(agent, STALE_MS);
return silent > quietLimitMs(agent, ADRIFT_MS);
@@ -57,6 +57,7 @@
</g>
</svg>
<p class="wake-hint">Click to wake Planny</p>
<button class="wake-skip" type="button">Skip</button>
</div>
<header class="topbar">
@@ -94,6 +95,8 @@
</button>
<div class="meter-pop" id="meter-pop" role="dialog" aria-label="Session meter" hidden>
<p class="meter-tip" id="meter-tip"></p>
<ul class="meter-list" id="meter-list" aria-label="What the points are made of" hidden></ul>
<div class="meter-fresh" id="meter-fresh" hidden></div>
<button type="button" class="linky" id="meter-help">What is this?</button>
</div>
</span>
@@ -128,13 +131,28 @@
title="Colors, theme and sound"
aria-label="Colors, theme and sound"
>
<!-- Three swatches, so the button says what it opens without a word. -->
<!-- A gear: ring, hub and eight teeth. -->
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
<circle cx="5" cy="5.5" r="3.1" class="sw-a" />
<circle cx="11" cy="5.5" r="3.1" class="sw-b" />
<circle cx="8" cy="11" r="3.1" class="sw-c" />
<path class="gr-teeth" d="M12 8h2.6M8 12v2.6M4 8H1.4M8 4V1.4M10.83 10.83l1.84 1.84M5.17 10.83l-1.84 1.84M5.17 5.17L3.33 3.33M10.83 5.17l1.84-1.84" />
<circle cx="8" cy="8" r="4.2" class="gr-ring" />
<circle cx="8" cy="8" r="1.6" class="gr-hub" />
</svg>
</button>
<a
class="icon-btn"
id="btn-feedback"
href="https://github.com/jparkerweb/plan2code/issues/new/choose"
target="_blank"
rel="noopener noreferrer"
title="Report a bug or suggest an idea"
aria-label="Report a bug or suggest an idea (opens GitHub in a new tab)"
>
<!-- A megaphone: horn, handle and two sound waves. -->
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
<path class="mg-body" d="M1.8 6.2h2.8L10.4 3v10L4.6 9.8H1.8z" />
<path class="mg-line" d="M4.6 9.8l.9 3.4h1.6l-.6-2.7M12.4 6.1a2.6 2.6 0 0 1 0 3.8M13.8 4.5a5 5 0 0 1 0 7" />
</svg>
</a>
</div>
<div class="topbar-row second">
<div class="row-left">
@@ -595,6 +613,9 @@
written and approving things, instead of typing it all into the
terminal.
</p>
<p>
New here? <button type="button" class="help-link" data-action="welcome">Show the welcome again</button>
</p>
<figure class="help-figure" data-figure="about">
<svg class="help-diagram" viewBox="0 0 560 160" role="img" aria-labelledby="hd-about-title hd-about-desc">
<title id="hd-about-title">You, this page, its program and Plan2Code, all on your machine</title>
@@ -680,7 +701,7 @@
A simplified outline of this page with six numbered areas, in the
same order as the sections below: 1, the top bar, with the title on
the left, the progress bar in the middle, the question mark and
swatch buttons on the right, and Stop session under the title;
gear buttons on the right, and Stop session under the title;
2, Planny and the outline down the left; 3, the view tabs, on the
top bar's second row at the right; 4, the question card in the
middle with Previous and Next under it; 5, the notes panel on the
@@ -738,10 +759,14 @@
"4 of 9 done" while something is being built.
</li>
<li>
The <strong>?</strong> button opens this Help, and the swatch button
The <strong>?</strong> button opens this Help, and the gear button
beside it opens <strong>User Preferences</strong>: your role first,
then your colors, theme, card width and sounds.
</li>
<li>
The <strong>megaphone</strong> button at the far right opens GitHub in a
new tab, where you can report a bug or suggest an idea.
</li>
<li>
<strong>Stop session</strong> ends the session and saves your place.
See "Stopping and finishing".
@@ -1339,7 +1364,8 @@
<p>
Each step you run here adds points: a plan or a set of documents
weighs more than a single answered question, and a built phase more
still. Click the ring to see the count. It is a rule of thumb, not a
still. Click the ring to see the count and a list of each step that added
points, with what it added. It is a rule of thumb, not a
reading of Plan2Code's real memory: long sessions tend to make it
miss things, and the ring is there to remind you.
</p>
@@ -1675,7 +1701,8 @@
</p>
<p>
If it stays quiet a couple of minutes longer, the line changes to
"Plan2Code has not checked in for a few minutes", with Planny still
"Still working on it. Longer tasks can go a few minutes between
updates", with Planny still
in his working pose. It may be busy, or still waiting on you in the
terminal; the terminal is where to look. A build that said a task may
take longer gets that long before the line changes.
@@ -1721,7 +1748,7 @@
<section class="help-panel" data-tab="prefs">
<h3>Keyboard and preferences</h3>
<p class="help-lead">
Everything on the page works from the keyboard, and the swatch button
Everything on the page works from the keyboard, and the gear button
lets you make it look and sound the way you like.
</p>
<h4>Keyboard shortcuts</h4>
@@ -1761,7 +1788,7 @@
</p>
<h4>Your preferences</h4>
<p>
The swatch button at the top, beside <strong>?</strong>, opens
The gear button at the top, beside <strong>?</strong>, opens
<strong>User Preferences</strong>:
</p>
<ul>
@@ -1786,7 +1813,7 @@
</li>
<li>
<strong>Highlight color</strong>: one of
<span data-fact="accentCount">32</span>, rust to begin with. It marks
<span data-fact="accentCount">32</span>, ocean blue to begin with. It marks
what is yours to do, and Planny's star uses it while he works.
</li>
<li>
@@ -1936,6 +1963,29 @@
</div>
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
</fieldset>
<fieldset class="modal-ranges looks-models">
<legend>Models</legend>
<div class="models-tabs" role="group" aria-label="Which agent">
<button type="button" class="btn small ghost" id="models-tab-claude" aria-pressed="true">Claude</button>
<button type="button" class="btn small ghost" id="models-tab-devin" aria-pressed="false">Devin</button>
</div>
<div class="models-note">
<p><strong>You usually don't need to change this.</strong> Plan2Code ships an up-to-date model list with every release. Add a model here only when a new one comes out before Plan2Code has been updated.</p>
<ul>
<li>Restart <code>plan2code</code> to see a change in its model menu.</li>
<li>At any time, run <code>plan2code --model &lt;id&gt;</code>, or pick your model inside your agent before running a skill.</li>
<li>Updating Plan2Code refreshes the built-in list. Models you added stay, unless the built-in list now includes them.</li>
<li>Devin models are limited to Low, Medium and High effort.</li>
</ul>
</div>
<div class="models-list" id="models-shipped" aria-label="Built-in models"></div>
<div class="models-list" id="models-user" aria-label="Models you added"></div>
<div class="models-actions">
<button type="button" class="btn small" id="models-add">Add a model</button>
<button type="button" class="btn small ghost" id="models-reset">Reset to default</button>
<span class="help" id="models-status" role="status"></span>
</div>
</fieldset>
<div class="modal-actions">
<button type="button" class="btn ghost" id="looks-reset">Back to default</button>
<button type="button" class="btn primary" id="looks-done">Done</button>
@@ -1994,10 +2044,61 @@
<div id="help-panels" class="help-panels"></div>
</div>
<div class="modal-actions">
<span class="help-version" id="help-version" hidden></span>
<button type="button" class="btn primary" id="help-done">Close</button>
</div>
</dialog>
<!-- Shown once, on the first dashboard a person sees. Closing it by any
route saves looks.welcomeSeen; Help's first tab reopens it. -->
<dialog class="modal welcome" id="welcome-modal" aria-labelledby="welcome-title">
<div class="welcome-poster">
<div class="welcome-sky" aria-hidden="true"><i></i><i></i><i></i><i></i><i></i><i></i></div>
<!-- Planny is cloned in from #planny by app.js, so he is always the
same robot as the one in the dock. -->
<div class="welcome-bot" id="welcome-bot" aria-hidden="true"></div>
<p class="welcome-kicker">Plan2Code Web Console</p>
<h2 id="welcome-title">Ideas in. Working code out.</h2>
<p class="welcome-lead">
Answer questions, read what gets written and approve each step here,
instead of in the terminal. It runs on this machine only.
</p>
</div>
<div class="welcome-cols">
<div class="welcome-col">
<span class="welcome-dot is-accent">
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="3.5" y="9" width="12" height="9" rx="1.6" transform="rotate(-12 9.5 13.5)" /><rect x="8.5" y="6" width="12" height="9" rx="1.6" /></svg>
</span>
<h3>Pick a card</h3>
<p>Start with <strong>Suggested</strong>. Pathfinder for a foggy idea, Quick Task for something small.</p>
</div>
<div class="welcome-col">
<span class="welcome-dot is-stage">
<svg viewBox="0 0 20 20" aria-hidden="true" focusable="false"><circle cx="10" cy="10" r="7" opacity="0.35" /><circle cx="10" cy="10" r="7" pathLength="100" stroke-dasharray="50 100" stroke-dashoffset="25" transform="rotate(-90 10 10)" /></svg>
</span>
<h3>Refresh at half way</h3>
<p>Once the session meter passes half, finish the step and start a new conversation.</p>
</div>
<div class="welcome-col">
<span class="welcome-dot is-bare">
<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><rect x="3.5" y="5" width="17" height="14" rx="2" /><path d="M7.5 10l3 2-3 2M12.5 14.5h4" /></svg>
</span>
<h3>Come back</h3>
<p><code>/plan2code</code> in your agent, or <code>plan2code</code> in any folder.</p>
</div>
<div class="welcome-col">
<span class="welcome-dot is-plain">
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false"><path d="M12 8h2.6M8 12v2.6M4 8H1.4M8 4V1.4M10.83 10.83l1.84 1.84M5.17 10.83l-1.84 1.84M5.17 5.17L3.33 3.33M10.83 5.17l1.84-1.84" /><circle cx="8" cy="8" r="4.2" /><circle cx="8" cy="8" r="1.6" /></svg>
</span>
<h3>Get help</h3>
<p><kbd>?</kbd> opens Help. The gear holds your role, theme and sounds.</p>
</div>
</div>
<div class="modal-actions">
<button type="button" class="btn primary" id="welcome-done">Start building</button>
</div>
</dialog>
<dialog class="modal" id="stop-modal" aria-labelledby="stop-title">
<h2 id="stop-title">Stop this session?</h2>
<p class="modal-blurb" id="stop-blurb"></p>
@@ -35,23 +35,68 @@ export const RUN_EVENTS = new Set(Object.keys(WEIGHTS));
const weightOf = (key) => (Object.prototype.hasOwnProperty.call(WEIGHTS, key) ? WEIGHTS[key] : 0);
// 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",
});
const RUN_LABELS = Object.freeze({
"pathfinder-chart": "Pathfinder map written",
"pathfinder-question": "Pathfinder question settled",
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",
});
// The unit a run names, from its ledger id ("L3:phase-2" -> "phase-2").
const unitOf = (id) => (typeof id === "string" && id.includes(":") ? id.slice(id.indexOf(":") + 1) : "");
/**
* The session's points, folded from ledger entries in order. An id seen
* before is skipped, so a repeated `post` never counts twice.
* What the count is made of: one { label, points } per ledger entry that
* scored, in order. An id seen before is skipped, so a repeated `post` never
* counts twice. Entries that weigh nothing are left out.
*/
export function pointsFrom(entries) {
export function breakdownFrom(entries) {
const seen = new Set();
let points = 0;
const rows = [];
for (const entry of Array.isArray(entries) ? entries : []) {
if (!entry || typeof entry !== "object") continue;
if (entry.id !== undefined) {
if (seen.has(entry.id)) continue;
seen.add(entry.id);
}
if (entry.kind === "launch" && LAUNCH_COUNTED.has(entry.workflow)) points += weightOf(entry.workflow);
else if (entry.kind === "run") points += weightOf(entry.event);
let points = 0;
let label = "";
if (entry.kind === "launch" && LAUNCH_COUNTED.has(entry.workflow)) {
points = weightOf(entry.workflow);
label = LAUNCH_LABELS[entry.workflow] || entry.workflow;
} else if (entry.kind === "run") {
points = weightOf(entry.event);
const unit = unitOf(entry.id);
label = (RUN_LABELS[entry.event] || entry.event) + (unit ? `: ${unit}` : "");
}
if (points > 0) rows.push({ label, points });
}
return points;
return rows;
}
/** The session's points, folded from ledger entries in order. */
export function pointsFrom(entries) {
return breakdownFrom(entries).reduce((sum, row) => sum + row.points, 0);
}
export const YELLOW_AT = 4;
@@ -94,5 +139,12 @@ export const RED_BANNER =
export function meterView(entries) {
const points = pointsFrom(entries);
const level = levelFor(points);
return { points, level, fraction: ringFraction(points), words: WORDS[level], tooltip: tooltipFor(points) };
return {
points,
level,
fraction: ringFraction(points),
words: WORDS[level],
tooltip: tooltipFor(points),
items: breakdownFrom(entries),
};
}
@@ -187,7 +187,7 @@ export const ACCENTS = {
},
};
export const DEFAULT_ACCENT = "rust";
export const DEFAULT_ACCENT = "ocean";
// The card-width presets. Here for the same reason the accents are: the page
// validates a saved `looks.width` with cardWidth(), and the server uses it to
@@ -23,7 +23,8 @@ const SAFE_PROTOCOL = /^(https?:|mailto:|#|\/(?![/\\]))/i;
function safeHref(href) {
if (!href) return null;
const trimmed = String(href).trim();
// Blocks javascript: and data: hrefs before they can reach the DOM.
// Blocks javascript: and data: hrefs before they can reach the DOM, and a
// protocol-relative `//host` (or `/\host`), which leaves the page for another site.
return SAFE_PROTOCOL.test(trimmed) ? trimmed : null;
}
@@ -103,6 +104,26 @@ function inlineInto(parent, tokens) {
}
}
// What a fenced code block offers beside Copy, from its first non-empty line:
// `'run'` gets a Run it button (git commands — the one kind a person keeps
// copying into Ask by hand), `'hint'` a muted note that pasting it into Ask
// may get the agent to run it, and `null` nothing extra. A leading `/` is a
// skill command for a new conversation, never a terminal command, so it gets
// neither.
const COMMAND_WORDS =
/^(git|node|npm|npx|pnpm|yarn|bun|deno|python3?|pip3?|brew|curl|wget|docker|kubectl|terraform|make|cmake|cargo|go|java|mvn|gradle|gh|aws|az|gcloud|jq|ssh|scp|rsync|chmod|chown|mkdir|cp|mv|rm|ls|cd|cat|echo|export|source|bash|sh|zsh|fish|pwsh|powershell|cmd|systemctl|service|apt|apt-get|dnf|yum|pacman|tar|unzip|zip)\b/i;
export function runHint(text) {
const firstLine = (text || "")
.split("\n")
.map((line) => line.trim())
.find((line) => line.length > 0);
if (!firstLine || firstLine.startsWith("/")) return null;
if (/^git(\s|$)/.test(firstLine)) return "run";
if (firstLine.startsWith("#!")) return "hint";
return COMMAND_WORDS.test(firstLine) ? "hint" : null;
}
function blockInto(parent, tokens) {
for (const t of tokens || []) {
switch (t.type) {
@@ -140,7 +161,16 @@ function blockInto(parent, tokens) {
// textContent, so a fenced block containing markup is inert.
pre.appendChild(el("code", null, t.text));
wrap.appendChild(copyButton(t.text, "md-copy"));
const hint = runHint(t.text);
if (hint === "run") {
const run = el("button", "md-run", "Run it");
run.type = "button";
wrap.appendChild(run);
}
wrap.appendChild(pre);
if (hint === "hint") {
wrap.appendChild(el("p", "md-run-hint", "The agent may be able to run this — paste it into the Ask tab"));
}
parent.appendChild(wrap);
break;
}
@@ -21,8 +21,11 @@ import {
CHAT_CURSOR_FILE,
CHAT_FILE,
LEDGER_FILE,
HERE,
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
USER_MODELS_FILE,
WORKSPACE_FILE,
appendChat,
appendEvent,
@@ -44,6 +47,7 @@ import {
readWorkspace,
remoteWarning,
typedCount,
withStateLock,
writeJsonAtomic,
writeWorkspace,
} from "./lib.mjs";
@@ -84,6 +88,12 @@ if (typeof args.token !== "string" || !args.token) {
}
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
// folder to seed the workspace with or resolve a typed path against. A fresh
// `open` starts this server before it writes the state, so until the state is
// 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);
@@ -96,12 +106,12 @@ const CURSOR_PATH = path.join(DIR, CHAT_CURSOR_FILE);
// Images and documents attached to notes and quick questions. Only ever named
// by the server (a UUID, plus `jpg` or an extension from DOC_TYPES), and only
// ever resolved inside this directory: the client's file name is a label.
// Only images are served back; a document is written, read by the agent from
// disk, and deleted, never handed to a browser.
// Images are served back as JPEG. A document is served under a fixed type
// (PDF, or text/plain for everything else, sandboxed and never sniffed), so
// the page can link it without ever letting a browser run it.
const UPLOADS_DIR = path.join(DIR, "uploads");
const UPLOAD_EXTS = ["jpg", ...Object.keys(DOC_TYPES)];
const EXT_ALT = UPLOAD_EXTS.join("|");
const UPLOAD_ROUTE = /^\/uploads\/([0-9a-f-]{36})\.jpg$/;
const UPLOAD_ANY_ROUTE = new RegExp(`^/uploads/([0-9a-f-]{36})\\.(${EXT_ALT})$`);
const UPLOAD_NAME = new RegExp(`^[0-9a-f-]{36}\\.(${EXT_ALT})$`);
@@ -216,7 +226,7 @@ const SERVABLE = new Set([
// live in it). A stat says whether anything moved; refreshing through
// checkState also means a request that sees a new state first still counts
// it as a new revision and tells every other tab. Callers must not mutate
// what this returns -- /submit clones before it edits.
// what this returns -- /submit edits a fresh read of its own, under the lock.
function readState() {
checkState();
return stateNow;
@@ -302,6 +312,10 @@ const foldPath = (p) => (FOLD_CASE ? p.toLowerCase() : p);
let workspaceSeen = { stamp: null, ws: null };
// The folder the session runs in: the state's own once it is written, else
// the one `open` passed on the command line. Null while neither is known.
const sessionWorktree = () => stateNow?.worktree || WORKTREE || null;
// The session's workspace, created with just the original folder when absent.
function workspaceNow() {
const stamp = fileStamp(WORKSPACE_PATH);
@@ -311,10 +325,15 @@ function workspaceNow() {
workspaceSeen = { stamp, ws };
return ws;
}
const fresh = initialWorkspace(stateNow?.worktree || PROJECT);
const root = sessionWorktree();
const fresh = { ...initialWorkspace(root || PROJECT), remote: remoteWarning().remote || "" };
// There but unreadable for now (a scanner's lock): never written over, and
// never cached, so the next call reads it again.
if (stamp) return workspaceSeen.ws || fresh;
// Nor saved while the session's folder is unknown: PROJECT is only a guess
// (the main checkout, for a linked worktree), and the file, once written,
// is what every later read trusts.
if (!root) return fresh;
try {
saveWorkspace(fresh);
} catch {}
@@ -405,7 +424,7 @@ function nextFolderId(ws) {
function addFolder(ws, body) {
const raw = typeof body.path === "string" ? body.path.trim().replace(/^(["'])(.*)\1$/, "$2").trim() : "";
const input = raw.replace(/^~(?=$|[\\/])/, () => os.homedir());
const resolved = raw ? path.resolve(stateNow?.worktree || PROJECT, input) : "";
const resolved = raw ? path.resolve(sessionWorktree() || PROJECT, input) : "";
if (!resolved || !isFolder(resolved)) return [400, { reason: "not-a-folder" }];
const same = ws.folders.find((f) => foldPath(path.resolve(f.path)) === foldPath(resolved));
if (same) return [400, { reason: "duplicate", name: same.name }];
@@ -455,7 +474,7 @@ function removeFolder(ws, body) {
// Where the picker opens: beside the last folder added, else the original.
function pickerStart(ws) {
const added = ws.folders.filter((f) => !f.original);
return added.length ? path.dirname(added[added.length - 1].path) : ws.folders[0]?.path || PROJECT;
return added.length ? path.dirname(added[added.length - 1].path) : ws.folders[0]?.path || sessionWorktree() || PROJECT;
}
// One picker at a time. Spawned, never spawnSync: the dialog can sit open for
@@ -464,6 +483,8 @@ function pickerStart(ws) {
let pickerBusy = false;
function bootWorkspace() {
// Nothing to check yet: the first read once the state is written makes it.
if (!sessionWorktree() && !fileStamp(WORKSPACE_PATH)) return;
const ws = workspaceNow();
const remote = remoteWarning().remote || "";
if ((ws.remote || "") !== remote) {
@@ -541,9 +562,14 @@ function recordSubmitted(state, actions) {
if (!Array.isArray(state.items)) return;
const at = nowIso();
for (const action of actions) {
if (!action || typeof action !== "object" || action.type === "comment") continue;
if (!action || typeof action !== "object") continue;
const item = state.items.find((i) => i && i.id === action.i);
if (!item) continue;
if (action.type === "comment") {
const pick = (list) => (Array.isArray(list) ? list.map(({ path, name }) => ({ path, name })) : []);
item.sentNote = { at, text: String(action.text || ""), images: pick(action.images), files: pick(action.files) };
continue;
}
const { i, type, ...rest } = action;
// JSON.parse makes "__proto__" an own property, and it would then be
// written back into state.json and re-read forever.
@@ -577,12 +603,13 @@ function timingSafeEq(a, b) {
return crypto.timingSafeEqual(ab, bb);
}
// Named per port. Cookies ignore the port, so every console on 127.0.0.1 shares
// one jar: under a single name, opening a second session overwrote the first
// one's cookie and locked its tab out.
function cookieName(port = PORT) {
return `p2c_console_${port}`;
}
// One cookie per port. Browsers scope cookies by host and ignore the port, so
// with one shared name every session on 127.0.0.1 wrote over the one before
// it, and the first session's tab went on sending the second one's token and
// got nothing but 403s. The port is what makes a session's origin its own, and
// a resumed server on a new port is reached again only through its /s/ link,
// which sets the cookie under the new name.
const cookieName = () => `p2c_console_${PORT}`;
function cookieToken(req) {
const raw = req.headers.cookie || "";
@@ -623,6 +650,47 @@ function touch() {
lastContact = Date.now();
}
const MODEL_CLIS = ["claude", "devin"];
const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,99}$/;
// Devin's XHigh and Max efforts are never offered, curated or added.
const MODEL_EFFORT_BLOCKED = /-(xhigh|max)$/i;
/**
* The user's added models: { claude: [{id,label}], devin: [...] }. Returns { models } or
* { error }. Blank rows are dropped; ids are trimmed and made unique per CLI; a label
* defaults to the id. Nothing else in the body survives.
*/
function cleanModels(input) {
if (!input || typeof input !== "object" || Array.isArray(input)) return { error: "models must be an object" };
const models = {};
for (const cli of MODEL_CLIS) {
const list = input[cli] == null ? [] : input[cli];
if (!Array.isArray(list) || list.length > 50) return { error: `${cli} must be a list of at most 50 models` };
const seen = new Set();
models[cli] = [];
for (const row of list) {
const id = String((row && row.id) ?? "").trim();
if (!id) continue;
if (!MODEL_ID.test(id)) return { error: `"${id}" is not a valid model id` };
if (MODEL_EFFORT_BLOCKED.test(id)) return { error: `"${id}": only Low, Medium and High efforts are allowed` };
if (seen.has(id)) continue;
seen.add(id);
const label = String((row && row.label) ?? "").trim().slice(0, 80) || id;
models[cli].push({ id, label });
}
}
return { models };
}
function shippedModels() {
const file = readJson(SHIPPED_MODELS_FILE, null) || {};
const out = {};
for (const cli of MODEL_CLIS) {
out[cli] = (Array.isArray(file[cli]) ? file[cli] : []).filter((m) => m && typeof m.id === "string");
}
return out;
}
/**
* Whittle a POSTed settings object down to what a settings file may hold.
* The page only sends { theme, accent } today, but the file is shared and
@@ -668,8 +736,8 @@ function asset(rel) {
// The saved highlight color, painted from the very first frame. The page's
// script owns the colors once it runs (applyLooks clears the attribute these
// hang off), but until then the only way to avoid flashing the default rust
// at someone who picked ocean is a stylesheet rule the server can switch on
// hang off), but until then the only way to avoid flashing the default ocean
// at someone who picked violet is a stylesheet rule the server can switch on
// with an attribute: the CSP forbids inline styles, and the colors live in
// palette.js, so they are generated from there rather than copied into CSS.
function accentCss() {
@@ -742,7 +810,10 @@ function renderIndex() {
// `$'` in the inserted text as patterns, and titles and state are free text.
return indexTemplate
.replace('<html lang="en">', () => `<html lang="en"${htmlAttrs}>`)
.replace("<title>Plan2Code Console</title>", () => `<title>${escHtml(title)} · Plan2Code</title>`)
.replace(
"<title>Plan2Code Console</title>",
() => `<title>${escHtml(title)} · #${escHtml(String(SID).slice(-6))} · Plan2Code</title>`
)
.replace('<h1 id="title">Plan2Code Console</h1>', () => `<h1 id="title">${escHtml(title)}</h1>`)
.replace(
'<span class="badge" id="badge">Pathfinder</span>',
@@ -821,7 +892,7 @@ const server = http.createServer((req, res) => {
302,
baseHeaders({
location: "/",
"set-cookie": `${cookieName(port)}=${TOKEN}; HttpOnly; SameSite=Strict; Path=/`,
"set-cookie": `${cookieName()}=${TOKEN}; HttpOnly; SameSite=Strict; Path=/`,
})
);
return res.end();
@@ -887,6 +958,14 @@ const server = http.createServer((req, res) => {
return;
}
if (pathname === "/version" && req.method === "GET") {
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
const version = readJson(file, {}).version;
if (typeof version === "string" && version) return json(res, 200, { version });
}
return json(res, 404, { error: "no version" });
}
if (pathname === "/state" && req.method === "GET") {
const state = readState();
if (!state) return json(res, 404, { error: "no state" });
@@ -957,7 +1036,10 @@ const server = http.createServer((req, res) => {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err) return json(res, 400, { error: "body must be JSON" });
const looks = cleanLooks(body && body.looks);
// `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.
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
const looks = set ? { ...(readJson(LOOKS_FILE, null)?.looks || {}), ...set } : cleanLooks(body && body.looks);
if (!looks) return json(res, 400, { error: "looks must be an object of simple settings" });
try {
ensureDir(path.dirname(LOOKS_FILE));
@@ -969,6 +1051,29 @@ const server = http.createServer((req, res) => {
});
}
// The launcher's model menu: what ships (read-only here) and what the user added.
if (pathname === "/models" && req.method === "GET") {
const saved = readJson(USER_MODELS_FILE, null) || {};
const { models } = cleanModels(saved);
return json(res, 200, { shipped: shippedModels(), user: models || { claude: [], devin: [] } });
}
if (pathname === "/models" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err) return json(res, 400, { error: "body must be JSON" });
const { models, error } = cleanModels(body && body.models);
if (error) return json(res, 400, { error });
try {
ensureDir(path.dirname(USER_MODELS_FILE));
writeJsonAtomic(USER_MODELS_FILE, models);
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
return json(res, 200, { ok: true, user: models });
});
}
if (pathname === "/upload" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
const contentType = String(req.headers["content-type"] || "");
@@ -1008,8 +1113,8 @@ const server = http.createServer((req, res) => {
}
// A document: the extension comes from the allow-list via its name, and
// the bytes have to agree with it. No `url` comes back, because a
// document is never served.
// the bytes have to agree with it. No `url` comes back: the page builds
// the link from the path, as it does for the delete route.
if (contentType.startsWith("application/octet-stream")) {
// The extension comes from the whole name: the label is cut at 200
// characters, and a long name would lose it there.
@@ -1033,11 +1138,11 @@ const server = http.createServer((req, res) => {
// Matched on the raw request line as well as the parsed path: URL parsing
// folds `..` segments away, and nothing that needed folding is an upload.
// GET serves images only; DELETE takes documents too.
// GET and DELETE take images and documents alike.
if (pathname.startsWith("/uploads/") || req.url.startsWith("/uploads/")) {
if (req.method === "GET") {
const m = UPLOAD_ROUTE.exec(req.url);
const file = m && m[0] === pathname ? uploadPath(m[1]) : null;
const m = UPLOAD_ANY_ROUTE.exec(req.url);
const file = m && m[0] === pathname ? uploadPath(m[1], m[2]) : null;
if (!file) return json(res, 404, { error: "not found" });
let buf;
try {
@@ -1045,7 +1150,15 @@ const server = http.createServer((req, res) => {
} catch {
return json(res, 404, { error: "not found" });
}
return send(res, 200, buf, "image/jpeg", { "cache-control": "private, max-age=86400" });
const ext = m[2];
if (ext === "jpg") return send(res, 200, buf, "image/jpeg", { "cache-control": "private, max-age=86400" });
const pdf = DOC_TYPES[ext].kind === "pdf";
// A sandboxed PDF cannot load the browser's viewer, and one needs no
// sandbox: text is the only thing a browser might otherwise run.
return send(res, 200, buf, pdf ? "application/pdf" : "text/plain; charset=utf-8", {
...(pdf ? {} : { "content-security-policy": "sandbox" }),
"cache-control": "private, max-age=86400",
});
}
if (req.method === "DELETE") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
@@ -1079,16 +1192,6 @@ const server = http.createServer((req, res) => {
if (badAttachments) {
return json(res, 400, { error: "a comment carries at most 5 attachments, each uploaded to this session" });
}
// One send is one agent turn. Writing over a result the agent has not
// collected yet destroys everything in it, and the loss is silent: two
// tabs, or one impatient second press, and an approval disappears.
if (pendingResult()) {
return json(res, 409, {
error: "pending",
message:
"Your last answers have not been picked up yet. Nothing is lost, they are still on their way.",
});
}
const result = {
type: "submit",
at: nowIso(),
@@ -1097,26 +1200,68 @@ const server = http.createServer((req, res) => {
actions: body.actions,
reply: body.reply || "",
};
// The result and the state change together, under the state lock: a
// `post` or an `open` landing in the middle of a send would otherwise
// write back a state read before it, and the send's record would go, or
// this write would carry an older state over the agent's new one.
let refused = null;
let written = null;
let agentWrote = false;
try {
// Atomic: the waiter polls this file and will land mid-write eventually.
writeJsonAtomic(RESULT_FILE, result);
written = withStateLock(DIR, () => {
// One send is one agent turn. Writing over a result the agent has not
// collected yet destroys everything in it, and the loss is silent: two
// tabs, or one impatient second press, and an approval disappears.
if (pendingResult()) {
refused = "pending";
return null;
}
try {
// Atomic: the waiter polls this file and will land mid-write eventually.
writeJsonAtomic(RESULT_FILE, result);
} catch (e) {
refused = String(e.message);
return null;
}
try {
// Read fresh from disk, never from the cache: an agent write the
// watcher has not reached yet is in the file and must be kept.
const text = fs.readFileSync(STATE_FILE, "utf8");
const state = JSON.parse(text);
agentWrote = text !== lastStateText;
state.phase = "submitted";
recordSubmitted(state, body.actions);
return { state, text: writeJsonAtomic(STATE_FILE, state) };
} catch {
// The answers are safe in result.json; the stamp is only a courtesy.
return null;
}
});
} catch (e) {
return json(res, 500, { error: String(e.message) });
refused = String(e.message);
}
if (refused === "pending") {
return json(res, 409, {
error: "pending",
message:
"Your last answers have not been picked up yet. Nothing is lost, they are still on their way.",
});
}
if (refused) return json(res, 500, { error: refused });
appendEvent(DIR, { type: "submit", rev, count: body.actions.length });
const current = readState();
if (current) {
// A copy: the cached state is what every other reader is handed.
const state = structuredClone(current);
state.phase = "submitted";
recordSubmitted(state, body.actions);
try {
// Account for our own write here rather than letting the watcher find
// it: the watcher reads a changed state.json as proof the AGENT is
// alive, and this write is not that.
adoptStateText(writeJsonAtomic(STATE_FILE, state), state);
rev++;
} catch {}
if (written) {
// Account for our own write here rather than letting the watcher find
// it: the watcher reads a changed state.json as proof the AGENT is
// alive, and this write is not that. An agent write it swept up on the
// way is, and is handled as the watcher would have handled it.
adoptStateText(written.text, written.state);
rev++;
if (agentWrote) {
agentSeenAt = Date.now();
try {
ensureConversation(written.state);
} catch {}
}
}
// Name the items that went. A page with OTHER answers staged should drop
// only what was sent, and a brief request is a submit carrying no answers
@@ -1282,15 +1427,21 @@ const server = http.createServer((req, res) => {
if (pathname === "/cancel" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
if (pendingResult()) return json(res, 409, { error: "pending", message: "A send is still on its way." });
const result = { type: "cancel", at: nowIso(), sid: SID, rev, actions: [], reply: "" };
// As /submit: a cancel that never reached disk must not tell the page it
// did, or the page stands down while the agent waits on forever.
// Under the state lock like a send, so `open` clearing a collected result
// can never take this one with it. As /submit: a cancel that never reached
// disk must not tell the page it did, or the page stands down while the
// agent waits on forever.
let pending = false;
try {
writeJsonAtomic(RESULT_FILE, result);
withStateLock(DIR, () => {
pending = pendingResult();
if (!pending) writeJsonAtomic(RESULT_FILE, result);
});
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
if (pending) return json(res, 409, { error: "pending", message: "A send is still on its way." });
appendEvent(DIR, { type: "cancel", rev });
broadcast("cancelled", { rev });
return json(res, 200, { ok: true });
@@ -1319,6 +1470,8 @@ const server = http.createServer((req, res) => {
// Treat a departure as "shorten the deadline", never as "exit now": the user
// may simply be reloading.
if (pathname === "/bye") {
// It moves the shutdown deadline, so only the page itself may send it.
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
if (clients.size === 0) lastContact = Date.now() - (IDLE_MS - 2 * 60 * 1000);
return json(res, 200, { ok: true });
}
@@ -1382,7 +1535,9 @@ function readRaw(req, limit, cb) {
/* ------------------------------------------------------- state watching */
// The agent writes state.json through `console.mjs post`. Watch the DIRECTORY,
// The agent writes state.json through `console.mjs post`, and the server only
// through /submit; both under the state lock (updateState() in lib.mjs), so
// neither can write back a state read before the other's. Watch the DIRECTORY,
// not the file: on Windows a watch on a file breaks the moment that file is
// replaced by rename, which is exactly what an atomic write does.
let watchTimer = null;
@@ -1490,7 +1645,9 @@ setInterval(() => {
// the server deciding to stop. Do not "optimise" this away.
setInterval(() => {
const idle = Date.now() - lastContact;
if (idle > IDLE_MS) {
// 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) {
appendEvent(DIR, { type: "exit", reason: "idle", idleMs: idle });
process.exit(0);
}
@@ -0,0 +1,22 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
"workflow",
"development",
"planning",
"implementation",
"plan"
],
"author": "Justin Parker",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-02",
"mode": "utility"
}