50 KiB
Architecture: web console design points
Part of AGENTS.md and the Architecture index: project guidance for AI coding agents.
Key design points:
-
First-run Welcome. The first dashboard a person sees (after the wake-up finishes) opens
#welcome-modal. Any close (button, Esc, backdrop) saveslooks.welcomeSeen: truetolooks.json, which survives "Back to default". Help's first tab has a Show the welcome again link (data-action="welcome"). Logic:maybeWelcome()/openWelcome()inscreens/help-dialog.js. -
Top-bar icons.
#btn-looks(gear) opens#looks-modal, titled User Preferences (see User Preferences below).#btn-feedback(megaphone) is a plain link tohttps://github.com/jparkerweb/plan2code/issues/new/choose, backed by.github/ISSUE_TEMPLATE/bug.ymlandidea.yml(config.ymlsetsblank_issues_enabled: false).DEFAULT_ACCENTinpalette.jsisocean. -
Version in Help.
GET /versionreadsversion.jsonbesideserver.mjs, falling back to../../version.jsonfor a run fromsrc/(the/versionroute inroutes.mjs).renderHelpVersion()inscreens/help-dialog.jsfills#help-version.computeExpectedSkills()ininstall.jsinjects the rootversion.jsoninto everyreferences/web-console/, so a version bump changes every skill. -
User Preferences is four tabs in a side list. Appearance (Theme, Card width, Highlight color, Role), Agents & models, System (Cleanup, and Desktop app inside the app only) and Sounds & activities (Sounds, Activities), a sideways strip below 720 px. The tabs are the static
<section class="prefs-panel">panels in#looks-modal, each fieldset in exactly one (itsdata-section, listed inPREFS_TABS), wired by the sharedpublic/tabs.js(wireTabs(), the same helper Help uses:helpKeyTarget()re-exports itstabKeyTarget()).public/prefs.jsis the pure part:PREFS_TABS,prefsOpenTab()(the gear and the dashboard's Set up preferences both open Appearance; nothing is remembered between opens) andprefsResetScope()(Back to default resets only the shown tab's looks keys, and is hidden on Agents & models and System).screens/prefs-dialog.jsownsopenPrefs(tab), the one way in, the Saved mark and the unsaved prompt;screens/looks.jskeeps the look and sound controls, which save tolooks.jsonas they change;screens/agents-view.jsmounts the Agents & models tab, a master-detail split over today'smodels.jsonandagents.json(formats unchanged) whose per-agent form has its own Save and Discard: Save sends the last saved list with only that form's draft swapped in, so another form's half-typed edit is never written. The split's components live underscreens/agents/(data, list editor, summary, form); the mount owns all state and every fetch and hands them onectx. -
Models in User Preferences.
GET/POST /modelsinroutes.mjsread the shipped~/.plan2code/bin/models.jsonand read/write the user's~/.plan2code/models.json(SHIPPED_MODELS_FILE/USER_MODELS_FILEinfiles.mjs), edited from each built-in agent's form on the Agents & models tab.PLAN2CODE_MODELS_DIRrelocates both for tests. The launcher reads the same two files for its model menu. -
The wait is bounded.
wait --seconds 240exits0(answers),10(still waiting,message: "Waiting on your answer in the web console"to relay),20(server gone, resume it) or30(canceled). The agent loops. Nothing blocks for the whole time a person takes. -
A turn is one command, and the CLI does the bookkeeping. Agent speed is model round trips and typed tokens, not the console (
bench-web-console.mjs --roundtrip: Send→agent ~70 ms, post→page ~180 ms), so the CLI absorbs every step with one right answer:consume()marks the agentworkingwhen it hands over a submit (markWorking()), andwaithands the turn back (markWaiting()) when it starts with an open question, a finish, or on the dashboard or git board;post --wait <N>posts and waits in one process;settle: true | [ids](settleItems()inpatches.mjs) records the latest send's cards as answered from theirsubmitted; a new or reopened question with no stated status setswaitingand waiting dropsquietMinutes(settleAgent()); a doc whose content changed with noversionmoves up one (mergeDocs()); a chat reply with noidisr<re>; doc blocks withfile(andselect: "tasks", doc-levelrefresh: true) are read from the worktree byresolveDocFiles()before the merge, refusing paths outside it; and a hop (__launch,__dashboard,__commit,__pickup) comes withresume(the exactopen --resumecommand) andskillFile(hopFor()), a pick-up also withhandoffFile. The wait loop's health check runs beside the 50 ms polling instead of blocking it, and is aborted on exit.help <topic>prints any contract file;help topicslists them.tokendefaults to the option key in the page'stokenFor(), and nothing readsfallbackText, so the contract no longer asks for either. -
The CLI hands the agent its terminal line.
open,postandwait(exits0and10) printterminalLine: "→ Look at the web console: <url>"(terminalLine()insessions.mjs), andconsole.mdasks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. Inwaitit is added to the printed result only; the collectedresult.jsonon disk never carries it.openalso printsswept: { sessions, scratch, handoffs }when it found anything to clean. -
State fields written by
open, not the agent. Everyopen(fresh or resume) recordsstate.worktreeandstate.branchfromrepoRoots()— the branch is read off<gitdir>/HEADon the walk that already finds the gitdir (""on a detached HEAD or outside git; env-relocated repos ask git, as before) — and the page shows them in the footer as the workspace label (footerLabel():folder · branch, orfolder + N folders · branchonce folders are added, stepping down through narrower tiers); a click opens the Workspace dialog.state.wake = trueis set only by a freshopen --workflow dashboardand deleted by every resume (server restart, launch, Back to the dashboard); the page also keeps a per-sidsessionStorageguard so a reload never replays it. -
looks.widthis a person-level preference alongside theme, accent and sounds inlooks.json.CARD_WIDTHSinpublic/palette.js(narrow720,comfortable880 — default —wide1080,ultrawide1440) is read by the page (cardWidth()validates a saved value) and byroutes.mjs, which paintsdata-widthon first load;styles/tokens.cssmapsdata-widthonto the single--card-widthvariable that every column rule uses. -
GET /agents-docis the other route that reads a project file (the dashboard's AGENTS.md tab, right after Dashboard, shown while the project has anAGENTS.md). A dashboard session only; it servesAGENTS.mdor one markdown file directly under.agents-docs/(?file=, defaultAGENTS.md;readAgentsDoc()insessions.mjsallows exactly those two shapes andrealpaths the file inside the root), astext/markdownwithno-store, or a204for anything else. The page links.agents-docs/files in place throughmd()'slinkoption (renderAgentsDoc()inscreens/docs.js). -
GET /overviewreads a project file too. It serves<spec>/overview.mdastext/markdownwithcache-control: no-store(so the Overview tab is always fresh), or with?file=map/?file=draftthe spec'spathfinder/map.md/ livePLAN-DRAFT-*.md(the dashboard's Map and Plan draft tabs, shown only while the spec has no overview;readSpecFile()picks the file and names it inx-spec-file), or an empty204when there is no such file (normal for most specs, and no failed request in the browser console). A dashboard session honors?spec=only when it equals adirinstate.scan.specs; every other workflow usesstate.specDirand ignores the query. The root isstate.worktree(fallbackstate.project), andreadSpecFile()(whichreadOverview()wraps) resolves andrealpaths the file and refuses anything outside the root's realpath, so../, absolute paths and outward symlinks all get the same 204, as do an unscanned?spec=and an unknown?file=. -
The Prototypes tab reads a spec's
prototypes/folder.GET /prototypeslists its.mdand.htmlfiles (204 when none),GET /prototype?name=serves one.md, andPOST /open-prototype(origin-checked) hands one.htmlto the system's default opener throughopenFile()inopen-link.mjs(one argument, no shell). The spec is chosen as/overviewchooses it (specInView());listPrototypes(),readPrototype()andprototypeHtmlPath()insessions.mjstake a bare file name only and refuse any file whose realpath is not directly in the folder. The page shows the tab after the spec file tabs, on the dashboard and in a session alike (loadPrototypes(), called fromloadOverview()). -
Month-old sessions are deleted whole.
openlistsstaleSessions()(directories matching the session-id pattern whosestate.jsonmtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) andstaleScratch()(top-level regular.json/.mjsfiles in the console folder older than 30 days, neverlooks.jsonorconsole-dir—PROTECTED_CONSOLE_FILES— never a directory or symlink) before it prints, and removes them after;removeSessions()/removeScratch()re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which thestale*listing already decided, so never hand them names that did not come from it.console.mdtells agents to write temporary payload files into the session's own folder so they go with it. -
User Preferences → System → Cleanup deletes on demand, from a list the server makes.
POST /cleanup(origin-checked) with{ scan: true }returnscleanupFindings():{ items: [{ id, where, name, kind, bytes, folder? }], bytes }(folderonnotepad:items only), idssession:<sid>(thestaleSessions()rule, and every file in the folder that old too, never the serving sid),console:<name>(anything at the top of the console home butPROTECTED_CONSOLE_FILES,sessionsandruntime, directories too) androot:<name>(anything at the top of~/.plan2codebutKEPT_PLAN2CODE_ENTRIES:console,bin,launcher.json,install.json,models.json,handoffs,notepads,app,app.json,agents.json,prototypes,learning),notepad:<key>(a month-old notepad, whole; see Notebook below) andcompleted:<name>(each folder or link directly under the session worktree'sspecs--completed/whose newest mtime is older than the session age, 30 days; loose files there stay; the server passesproject: sessionWorktree() || PROJECT, and without aprojectthe archive is never scanned). Both stray kinds must be untouched forSTRAY_GRACE_MS(an hour, by the newestlstatmtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders holdworkspaces.json.lockandwriteJsonAtomic()'s<file>.<pid>.tmp, which live for milliseconds.root:is only scanned when the console home is<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console, so a test or dev home never reaches the real folder. Paths never go to the page.{ delete: [id] }runsremoveCleanup(), which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning{ removed, bytes, failed, refused, refusal }. So Cleanup is the one place the server deletes in a project, and it keeps a completed spec git could not give back:completedSpecs()marks eachcompleted:itemtrackedonly whengit ls-fileslists it andgit ls-files --otherslists nothing inside (outside a repository, or gitignored asspecs--completed/is by default, it is untracked), andremoveCleanup()refuses an untracked one intorefused, withrefusalthe line the page's status shows. Nothing records a backup copy, so tracked by git is the only way through. The page always shows the list before Delete these. -
The console's path is stated, not searched for. Each Interface line names
references/web-console/beside the SKILL.md and the~/.plan2code/console/console-dirfallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path~/.agents/skills/<skill>/references/web-console/(the skills CLI's real store; every agent dir links into it), and everyconsole.mjs openwritesHEREto~/.plan2code/console/console-dir(onlyopen, so ahelpor dev run fromsrc/never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session. -
openneeds no payload, and runs first.--fileand--titleare optional (the title defaults to the folder name). Every skill's Interface line putsnode "<D>/console.mjs" open --workflow <w>BEFORE reading console.md or the project, and a test (every skill opens the console before it reads anything) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned bystartStage()inscreens/starting.jsfrom<template id="start-poses">inindex.htmland animated under.poseinstyles/poses.css; eachSKILLSentry'sposeinskills.jsis the list (START_POSES/startPose()inanswers.jsread it), and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (.waiting-pane, agent working with anactivityand nothing to ask).posePane()keeps the pane on screen across renders when the pose is unchanged —renderMain()holds any:scope > [data-pose]child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after. -
The dashboard scan knows whether the folder is a git repository.
scanProject()returns{ hasAgents, isGit, pending, specs };isGitcomes frominsideGitRepo(), the same filesystem walkfindRoots()does (nogitprocess, linked worktrees and submodules count, a setGIT_DIR/GIT_WORK_TREE/GIT_COMMON_DIRcounts as a repo). The Git card is never grayed, since a clean tree still has branches to switch, pull and push. WhenisGitisfalsethe card showsGIT_INIT_NOTE("Not a git repository yet: it offers to start one") as its detail line; a scan with noisGitcounts as a repo. In a repo,pendingispendingFiles()insessions.mjs, which callscountPending()ingit-repo.mjs: one boundedgit status --porcelain -zunderGIT_OPTIONAL_LOCKS=0(nullwhen git cannot say) counting modified, staged, deleted and untracked paths. Above0the detail line ispendingNote(n)("3 files to commit");0andnullshow no note. A finish withcommit: trueputs a Commit it now button on the finished screen (commitOffer(),renderCommitOffer()); its__commitpress makes the agent resume asgitin the same session and run the commit flow above the board.open --resumetreats any switch intogit(this press, or Changelog's "Commit this now?") as a hop, like a dashboard launch:switchWorkflow()blanks the page, finish and the last run'sstate.gitincluded, anddraft.jsongoes. Without that, the old finish outlived the switch, and the page sat on the old ending above the new questions and the board. A confirm item may carryfiles: [{ path, state }], drawn as a collapsed table byfilesTable(). Subagents is on by default for the sixteen opted-in skills (defaultSetting()); a saved Off stays off. -
The start path is timed, and
openis built around it. Measure withnode scripts/bench-web-console.mjs(--browser-delay 900for a real Chrome launch,--roundtripfor Send→agent and post→page,PLAN2CODE_CONSOLE_TRACE=1onopenfor a step timeline). Four things make it fast, and each is load-bearing:- No git process.
repoRoots()insessions.mjsfinds the common dir and worktree top by walking to.git(followinggitdir:andcommondirfiles) — eachgit rev-parsecost 150ms+ on Windows. It asks git only whenGIT_DIR/GIT_WORK_TREE/GIT_COMMON_DIRrelocate the repo, and uses the native realpath so an 8.3 short name keys the same project git would. - The socket handover.
openspawns the server first, then binds the loopback port itself (the firstlisten()blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome viastarttakes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (bindLoopback()/handOff()insessions.mjs,--handoffinserver.mjs). Requests queue in the socket until the server takes it; oneopenalready accepted is passed across as a socket and acknowledged (conn-held) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port;openthen opens the real URL. - The first paint needs no fetch.
routes.mjs(renderIndex()) rendersindex.htmlwith the session's title, badge and saved theme (data-theme,data-looks-accent, matched by accent rules generated frompalette.jsand appended to the joined stylesheet bystatic.mjs) and the whole first state as an inline<script type="application/json" id="boot">(every<escaped; data blocks are not executed, so the CSP is unchanged).modulepreloadhints fetch every module in parallel, the page draws in the same task as the script runs, and/events?have=<key>skips the opening frame when the page already holds that exact state. The chimes load on first use, not at start-up. - Reads are stat-gated.
fileStamp()(mtime:size:ino) decides whetherstate.json,result.jsonandlooks.jsonchanged before anything reads or parses them — per request, per heartbeat and in the 1s poll; the parsed state is cached (readState()returns it;/submitclones before editing).waitstatsresult.jsonevery 50ms instead of parsing it every 400ms. Static assets are held in memory for the server's life and revalidate by ETag.
- No git process.
-
The Workspace and the session meter live beside
state.json, one writer each, and outlive every hop. Three session files, none of whichswitchWorkflow()ever touches, so both survive dashboard → skill → dashboard (a new console session starts with a count of 0, and with the folders remembered for its folder and spec, below):File Writer Holds workspace.jsonthe server ( workspace.mjs)the folders ( id,path,name,description,original,nested),version, thechangeslog,missingids, andremote(remoteWarning()insessions.mjs, computed by the server at boot)ledger.ndjsonconsole.mjsappend-only, one JSON line per entry. Meter events: launch(every freshopenand every resume into another workflow),run(a post'srun, id scoped by launch, withtaskswhen a built phase reports one) andanswer(one per item the person answered in a collected send, written byledgerAnswers(), id<launch>:answer:<send stamp>:<item>). Alsofolder-issuereportsworkspace-cursor.jsonconsole.mjsthe last workspace versionhanded to the agent; advanced after the print, never backwardsThe page changes the workspace only through five routes:
GET /workspace(?check=1re-stats every folder first),POST /workspace/add(path resolved againststate.worktree,~expanded, case-insensitive duplicate check on win32/darwin;not-a-folder,duplicate,bad-name,name-taken+suggest),POST /workspace/edit,POST /workspace/remove(the original folder refuses) andPOST /workspace/browse(one picker at a time, 409busy; 404no-pickerwhenremoteis set or no picker exists;PLAN2CODE_PICKER_ECHOstands in for the dialog in tests).stateFrame()carriesworkspace(folders,missing,remote, the current launch's folderissues) andmeter(meterView()over the ledger), and both files are on the 1s poll; it also carries an optionalupdateonce the boot-time release check (update-check.mjs) finds a newer release. The agent hears of the workspace throughopenoutput (workspace: { folders, missing? }, which also seeds the cursor) and then each change once, asworkspace: [...]plusWorkspace: …reply lines onwaitexit 0 orchat; a change alone never ends awaitslice (pendingWorkspaceChanges()inworkspace.mjson exit 10).postandopen --fileliftrunandfolderIssueout of the patch into the ledger, never intostate.json; an unknown event or a malformed issue is exit 3. Remembered workspaces.workspace.mjskeeps~/.plan2code/console/workspaces.json(WORKSPACES_FILE, underPLAN2CODE_CONSOLE_HOMEin tests):projects[<case-folded worktree>] = { path, project, specs: { "specs/<name>": … } }, each entry{ original: { name, description }, folders: [{ path, name, description, nested? }], at }.rememberedWorkspace()answers spec, else project, else nothing;initialWorkspace(worktree, entry)builds from it, both in the server's firstworkspaceNow()and inopen's read-onlyworkspaceOnOpen(), so they agree.workspace.jsoncarriesscope(the spec key or""). Every user change (bumpWorkspace, notmissing/found) callsrememberWorkspace().setScope()swaps the list, loggingremoved/added/renamed/describedchanges so the cursor stays truthful;POST /workspace/scope { spec }(the dashboard picker, on selection and before a launch) seeds an unsaved spec from the project's list, andfollowSpecDir()(state poll, boot) moves the scope to a postedspecDir, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server andconsole.mjs forget --spec(Finalize Step 6). The contract is inconsole-workspace.mdandconsole-meter.md, andbuilding.md(per-phaserun), so the skill prompts stay unchanged. -
The Subagents switch is a standing instruction, injected only on change. The page's icon button (
#btn-subagents, after Write a brief) and#subagents-modalshow only when the frame'ssubagentsblock saysoffered && supported.offeredcomes frompublic/subagents.js;supportedmeans the latest{ "type": "open" }line inevents.ndjsoncarriescaps: ["subagents"](latestOpenCaps()), so an older skill copy'sopenhides the button. Four places hold it, one writer each:File Writer Holds ~/.plan2code/console/subagents.jsonserver.mjsper project folder → workflow: { on, instruction, max },instruction: nullbeing the shipped default; onPROTECTED_CONSOLE_FILES<session>/subagents-setting.jsonthe server ( settings.mjs){ workflow, on, instruction, max, revision }: synced from the store at boot and on any workflow change (serverSubagents().syncinsettings.mjs),revisionbumped only by a real change<session>/subagents-cursor.jsonconsole.mjs{ revision, state }, the last block handed over;openresets it, and it moves only after the printstate.json→helpersconsole.mjs postthe helpers the agent reports, merged by id, checked bycheckHelpers()plus the prose scan; dropped byswitchWorkflow()on a dashboard hopPOST /subagents(origin-checked;400not-offered/bad/too-long/max) saves the store and bumps the session setting.consume(),cmdChat(),deliverChat()andopenappendblockFor()'s lines last inreplyand thesubagentsfield; a change alone never ends awaitslice. The page's Subagents tab (before Ask) drawsstate.helpersthroughhelperRows(). Helpers never reach the meter ledger. Contract:console-subagents.md. -
The filesystem is the transport. Sessions live in
~/.plan2code/console/sessions/<sid>/, deliberately not underspecs/, so the console cannot trip the metrics scraper or any marker parser, and survivesgit clean. A result written after the agent dies is picked up by the next session. -
Attachments on notes and quick questions live in
<sid>/uploads/, never in the project: images as<uuid>.jpg, documents as<uuid>.<ext>withextfromDOC_TYPESinanswers.js(text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes toPOST /uploadasimage/jpeg; documents go as-is asapplication/octet-stream, the extension taken bydocExt()from the uncutx-p2c-name.readRaw(req, limit, cb)inroutes.mjscaps images atMAX_BODY(4 MB) and documents atMAX_DOC_BYTES(10 MB), and drains rather than destroys so the client gets its 413. Images need theFF D8 FFmagic; documents passcheckDocument()insessions.mjs(%PDF-for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file withcrypto.randomUUID().GET /uploads/<id>.<ext>serves images asimage/jpegand documents under a fixed type (application/pdf, elsetext/plain) withnosniffand, on text, CSPsandbox(a sandboxed PDF cannot open in the viewer), so a browser can show but never run one;recordSubmitted()writes every send's note onto its item assentNote { at, text, images, files, suggest? }(paths and names only;suggestonly when the action's is exactlytrue, the Ask for suggestions chip, which always writes a thread entry, note or not, and is left out of thesubmittedevent'sidsso the card's staged pick stays), whichnoteAwaiting()inanswers.jsturns into the Sent box's attachment links and the Notes pane's pending note until the agent's next thread message;DELETE /uploads/<id>.<ext>takes any allowed extension; both stay contained underuploads/.isOwnUpload()returns the kind ("image"/"file"/false), andattachmentsOk()makes/submitcomments and/chatmessages carry images only inimages[]and documents only infiles[], this session's uploads only, at most 5 together (MAX_ATTACHMENTS). A comment'sreplygains oneImage: <path> (<name>)orFile: <path> (<name>)line per attachment, in attach order; a chat entry's lines come fromchatReplyLines(), its images first, then its files.sweepUploads()bounds disk growth, and the session sweep removes the whole session a month after that. A note attachment a spec file cites is copied out first byconsole.mjs keep(--session --upload --name --spec [--from]): it checks both paths (the upload must sit under the session'suploads/, and the spec folder understate.project, real paths included, so a symlinked folder cannot carry the copy outside), copies withCOPYFILE_EXCLand reuses an existing copy, prints{ ok, path, link, image, reused }with a forward-slash link relative to--from, and logs akeepevent. It is the agent's hand, not the server's: it runs in the agent's shell only when the agent decides to cite a file, so the server still never writes into a project. -
Answers carry their terminal token. Each item ships
fallbackTextandtoken, so a click resolves to the literal word the prompt already expects (approved,a,skip). No workflow needs a second code path, and declining the console degrades to prose with nothing lost. -
A build tells the page how long silence is normal. The page calls a working agent stuck after two minutes without a post, which is right for a conversation and wrong for a twenty-minute build task.
agent.quietMinutes(1 to 60, counted only whileworking) stretches the stuck, adrift and Send-grace thresholds;quietLimitMs()inanswers.jsis the one rule. -
A finished quick task's review button is a request through the wait loop, like the brief:
{ "i": "__review" }or{ "i": "__done" }. The agent keeps waiting after posting a finish that carriesreview, and takes the review up by posting"finish": null, which puts the session back to work. Implementation's review needs no such machinery: it is a verdict on the sign-off card, asked before approval, so the session never left work to take it up. -
Back to the dashboard is the same kind of post-finish request. A finish with
finish.dashboard: trueshows the button; a press arrives as{ "i": "__dashboard", "type": "dashboard" }, and the agent runsopen --resume <sid> --no-open --workflow dashboardthen posts"finish": nullwith a freshmenu. The agent waits ~10 minutes after the finish for it (alongside__review/__doneon a quick task); after that the page swaps the button for the/plan2codecommand.finish.commandis optional — without one the page shows the "All done" line — andvalidate()rejects a<placeholder>command and a non-booleandashboard. The session-level actions are therefore__brief,__stop,__launch,__review,__doneand__dashboard; a new post-finish button should copy this precedent. -
Continue here, Update CHANGELOG first and Ask prompt blocks. Three small additions on the same pattern. Continue here is page-only:
continueOffer(fin)(public/answers.js) readsfinish.command, and when it starts with a Plan2Code skill (and the finish is not a pause)screens/ending.jsdraws a button beside the Next step block, hidden when the session meter is red; the press is the dashboard's own{ "i": "__launch", ... }throughsendAfterBuild("launch", offer), so the agent writes nothing new (startsClean()cleans the page for the hop, except out of Git and into Review; a same-skill next step keeps the workflow, so the agent posts"finish": null). Update CHANGELOG first isfinish.changelog: true, accepted byvalidate()only onquick-taskandfinalize(a paused finish is exempt from that check and the page ignores the flag), and it belongs withcommit: true; the press is__changelog, aHOP_ACTIONSentry incmd-post-wait.mjsthat resumes aschangelog, whose "Commit this now?" yes carries on to Git. Ask prompt blocks are contract only (console-chat.md→ Prompts to carry away): the page already draws a Copy button on every fenced block. -
__dashboardalso arrives mid-workflow. A left-pointing triangle (#btn-home, filled with--accent) sits left of Stop session on every non-dashboard page. Its state comes from the purehomeButtonState()inanswers.js: hidden on the dashboard, on a finish and during a stop, and otherwise gated by the sameturnGate()Stop now uses (the person's turn, unless the agent has gone adrift). The confirm (#home-modal) reusesstopWarning(), and the submit carries the staged answers plus__dashboard, withHOME_REPLY. With no finish on the page, the agent treats it as a stop that lands on the menu: it saves its place as for__stop, then resumes as the dashboard with"finish": null+menu, with no finish and no stop in between (console-stop.md → "Back to the dashboard, mid-workflow"; building.md for builds).local.homewarddrives Planny's "Saving your place and opening the dashboard…" line until the through-the-dashboard reset clears it. -
Handoffs live outside every repo, in
~/.plan2code/handoffs/, and the console owns them (handoffs.mjs; the console ships in every skill, so the Stop flow, the Handoff skill and the dashboard all reach it throughconsole.mjs).handoff new --workflow <w> --skill <s> [--spec specs/<x>] [--title <t>] [--from-stop]claims one for this checkout and prints{ ok, id, path, meta }(exit 2 bad usage, 3 a bad value). Off the dashboard the Stop modal offers Stop with a handoff (#stop-handoff, suggested) above Just stop and save (#stop-go); the first sends__stopwithhandoff: trueandSTOP_HANDOFF_REPLY, andwaitaddshandoffSkill(the built Handoff skill'sSKILL.md,handoffFor()); console-stop.md gives the order (answers, save,handoff new --from-stop, write, paused finish naming the file,stop). On a dashboard,cmdOpen()addsscan.handoffs(listHandoffs(worktree)) andscan.handoffsDirafterscanProject(), which stays handoff-free becausespecs.mjs listshares it. The picker draws them as dashed.spec-chip.is-handoffchips after the specs (specSel = "handoff:<id>"); a picked one replaces the skill cards withrenderHandoffPreview(): Pick it up here, Read it all (GET /handoff?id=, served only for an id in the dashboard's ownstate.scan.handoffs), Copy for a new conversation (handoffCopyText()) and Delete (openHandoffDelete(), one step). Pick it up sends{ "i": "__pickup", "type": "pickup", "handoff": <id> };HOP_ACTIONS.pickup(pickupHop()) reads the stored.jsononly, never the page, and falls back to Quick Task withfallback: truewhen the record, its skill or its spec is gone, or the Handoff skill wrote it (resuming that skill would only write another handoff);markPickedUp()stampsusedAtas the hop is printed, so the next scan drops the chip. Delete sends__deletewithhandoffin place ofspec, and the agent runsdelete-handoff --handoff <id>(removeHandoff(), exit 3 on a refusal, nothing touched).opensweeps handoffs untouched for 30 days (staleHandoffs(), the.json's mtime, else the.md's), picked up or not, and reports them inswept.handoffs; Cleanup never lists the folder (KEPT_PLAN2CODE_ENTRIES). -
Notebook: the person's, one per folder, in
~/.plan2code/notepads/, in named tabs, and the agent's only when the person sends a tab.notepads.mjsis the store's one owner (PLAN2CODE_NOTEPADS_DIRmoves it for tests). The folder is the session's worktree, else its project (notepadRoot()inroutes.mjs), keyed<folder-name>-<12 hex>bynotepadKey()(the hash overfoldKey(), so case-only path differences match on Windows and macOS, and two worktrees get two notepads). Layout:meta.json({ v: 2, folder, created }),tabs.json({ v: 1, order: [id], last, tabs: { id: { name, created, sent? } } }, the index and the only place order and the last tab live) and, per tab,tabs/<id>/note.mdwithtabs/<id>/images/<uuid>.jpgand<uuid>.thumb.jpg; a tab id is 12 hex. Every write takes the folder'snotepad.lock; a read never creates a file, so only the person's edits age a notepad. A delete removes the tab from the index first, then its folder, and the next write sweeps away a tab folder the index no longer names (a delete that crashed half way). Migration: the first shape (v: 1, onenote.mdandimages/at the top) reads as one virtual tab, Notes, with the fixed idLEGACY_TAB_ID, and a read writes nothing; the first write moves the files intotabs/<LEGACY_TAB_ID>/and writestabs.jsonlast, so a crash in the middle is finished by the next write and never loses a file. Atabs.jsonthat does not hold up is set aside astabs.json.corruptand rebuilt from the tab folders. Routes: twelve, placed after/uploadinROUTES(the shape test pins the order):GET /notepad[?tab=<id>]({ tabs, last, tab: { id, text, savedAt, images } }, with the tab'stext,savedAtandimagesrepeated at the top),POST /notepad/text?tab=({ text }, 1 MB, 413too-long),POST /notepad/image?tab=andPOST /notepad/thumb?id=<uuid>&tab=(rawimage/jpegthe page re-encoded withreencode(), 4 MB, 200 pictures per tab: 415not-jpeg, 413too-large, 409too-many),POST /notepad/image/delete?tab=({ id }),POST /notepad/tab({ name }),/notepad/tab/rename({ id, name }),/notepad/tab/delete({ id }),/notepad/tab/order({ order }, every id once)/notepad/tab/last({ id }) and/notepad/tab/sent({ id, workflow, spec? },markTabSent(): setssent: { workflow, spec?, at }on the tab, replacing an earlier one;workflowone ofpathfinder,plan,quick-task,revise-plan,specmatching^specs/[A-Za-z0-9._-]+$, else 400bad-sent), andGET /notepad/images/<tab>/<uuid>[.thumb].jpg(matched on the raw request line like/uploads/, served throughimagePath()'s realpath containment,no-store). A text or picture request with no?tabmeans the last tab used (and makes Notes when there is none), so an unchanged client keeps working. The ten POSTs are origin-checked, and every refusal is aNotepadErrorturned into{ error }(bad-name,duplicate-name,too-many-tabs,no-such-tabbeside the picture and text codes). None of them writes to the session folder orevents.ndjson, andconsole.mjsand thecmd-*.mjsfiles never importnotepads.mjs(a source test pins it;sessions.mjsloads it lazily for Cleanup only, listing and removing whole notepads), so nothing in a notepad reachesstate.jsonor anythingwaitprints except a tab the person sends (see Send to a skill). The editor, and the CSP. CodeMirror 6 replaced OverType 2.6.1 after a spike (typing at 200 KB measured about 24 ms a key against about 99 ms, and real heading sizes):public/vendor/codemirror.esm.jsis one minified file (about 500 KB) made by the dev-onlyscripts/vendor-codemirror.mjsfromscripts/vendor-codemirror-lock.json, never installed in the repo, and loaded by a dynamic import only when the Notebook first opens. CodeMirror writes its rules as a<style>element, whichstyle-src 'self'refuses, so the editor lives in the open shadow root of.notepad-cm-hostwhere it adopts them as a constructed stylesheet, and its own look ispublic/notepad-editor.css, a<link>inside the root. Custom properties inherit across the boundary, so both themes work; page tests reach the editor with Playwright's CSS locators (they pierce open shadow roots) and read its text fromEditorView.findFromDOM(), since lines the cursor is not on draw without their Markdown marks. CodeMirror's own rules win a tie in specificity (they are adopted after the linked sheet), sonotepad-editor.csswritesdiv.cm-editor .cm-scrollerfor the few it overrides.scripts/test-web-console-page-notepad.mjsfails on anysecuritypolicyviolationwith the notepad open. Upgrading CodeMirror: change a version inscripts/vendor-codemirror.mjs, runnode scripts/vendor-codemirror.mjs --update-lock(npm and network; it installs in a temp folder), update the sha256 in the files-table row, then run the two notepad test files. Tabs on the page:screens/notepad.jsbinds every save and picture to the tab it was made in (a switch waits for the save, and stays put when it cannot),public/notepad-tabs.jsdraws the bar, andpublic/notepad.jsholds the name, order and delete rules as pure code. Send to a skill (page-only, so the agent reads a tab only when the person sends the box it fills).noteSwitchShows(entry, scan, sel)inpublic/answers.jsdecides whether a lit card's confirm pane offers "Start with a note from your Notebook":cardAvailability().onand either Pathfinder, Plan or Quick Task with no spec picked (Start fresh), or Revise plan with a spec picked whose scan entry has noplanChange(scan.mjssets it from a**Plan change:**line in the active phase file not followed by(applied <date>):or(dropped <date>):). Switched on,screens/dashboard.jsreadsGET /notepadandGET /notepad?tab=, lists the tabs (empty ones grayed,sentbadge), previews the whole tab and ticks pictures (defaultNoteTicks(), firstMAX_ATTACHMENTS= 5 ticked,toggleNoteTick()allows no more), notes a text overNOTE_LONG_BYTES(51200) as a "Long tab" and adds+ note: <tab>to the command line. At Start,launchSkill()keepspage.local.noteSend = { tab, text, pictures, workflow, spec? }; the__launchaction andlaunchReply()carry nothing of the tab, andscreens/core.jskeepsnoteSendover the clean hop only for the launched workflow. The skill's notes (notes/pathfinder.md,plan.md,quick-task.md,revise-plan.md) mark the idea box (Revise plan's "What should change" box)"fill": "note", a fieldpatches.mjsaccepts ontextitems only and with that value only (exit 3 otherwise). When the first open such card appears, the page fills it once (draft and staged answer fromnoteSend.text, pictures fetched from/notepad/images/intoattachFiles(), a 404 picture skipped, a missing tab leaves the box empty with a banner) and clearsnoteSend;console.mddocumentsfill. The sent mark follows whatever send carried the filled box:markSent()posts/notepad/tab/sentwithpage.local.noteSent, so Send, and Stop or Back to the dashboard (screens/ending.jssends staged answers with them), all mark it, while Start alone records nothing. Once filled, the box is an ordinary draft (its text in the session'sdraft.jsonthroughpushDraft(), its pictures inuploads/), which the agent never reads before a send. The Notebook showssentas a badge after the tab's name (notepad-tabs.js) and a muted "Sent to · " line under the editor (screens/notepad.js). Cleanup. No sweep atopentouches a notepad, andnotepadsis inKEPT_PLAN2CODE_ENTRIES, so the folder is never a stray.cleanupFindings()lists a notepad as onenotepad:<key>item (withfolderfrommeta.json, labeled "Notebook for " byscreens/cleanup.js, the key when it is missing) only whenstaleNotepads()finds the newest file in it (newestMtime()infiles.mjs, which recurses to any depth, so tab folders count)SESSION_MAX_AGE_MS(30 days) old or more;removeCleanup()removes the whole folder throughremoveNotepad()(key checked againstNOTEPAD_KEY_RE, contained innotepadsDir(), a link refused). -
A Bug fixed spec deletes in one step. Its chip shows a visible Delete (
.spec-chip-del-label) instead of the hover ✕,openDeleteConfirm()gives it a fixed-bug warning and a Delete it button, anddeleteStep()sends__deleteon the first press, with no name to type.chipDetail()drops the scan's repeated "bug fixed" detail under the label. -
The Quick question chat is a second, append-only channel beside the card slot. The page's Ask tab (always last, every workflow, still there after a finish) posts to
POST /chat(a message, or{ reset: true }for New conversation) andPOST /chat/decision(Approve / Decline on an edit the agent proposed). The server is the only writer of<sid>/chat.ndjson(one JSON line permessage/decision/reset, each with aseq;appendChat()ininbox.mjs);console.mjsis the only writer of<sid>/chat-cursor.json(the last seq handed over, advanced only after printing) and of the agent's replies instate.json→chat.replies(merged byid, checked byvalidateChat(): realre, proposal paths outside the runningspecs/<idea>/). The server never writes chat intostate.json—postread-modify-writes it underwithStateLock()— andstateFrame()merges inbox and replies into the frame'schatblock (conversation,messages,typed,limit,offline) in memory./chatnever checkspendingResult(), so neither channel can block the other.waitkeeps its exit codes 0/10/20/30: exit 0 gainschat(or istype: "chat"with no actions), and the instantconsole.mjs chatanswers 0/10/20 without touchingresult.json, which builds run after every task. Guards: 10 typed messages per conversation (409 limit), 4,000 characters (400 too-long), own uploads only, of the right kind (400 image,400 file),409 offlinewhenchatOffline()says no agent is there,409 stalefor an old conversation. A hop through the dashboard keeps the conversation:switchWorkflow()carrieschat.repliesacross and the page keeps its Ask state, so only New conversation appends aresetafter the opening one. A lone reset never ends awaitslice (deliverableChat()); it rides along with the next message. -
A loop stop leads with why and what to do next, in two places.
evidence_markdowninloop_driver.rsopens the report doc with a> [!CAUTION]box (the reason, then the stop line) and a> [!TIP]box (the advice);render.jsdraws a blockquote that opens with either marker as a coloredmd-alertand hides the marker. The stop card shows the same two as.loop-whyand.loop-advicefromloopEnd.advice. The advice is the failed phase's ownloopOutcome.nextStep(one line, 300 characters, optional, only for afailedreport that refused the phase), elsestop_advice()'s words for the cause.failed_wordsputs the reason before the agent's summary, since a failed report's summary often reads like success. -
validate()inpatches.mjsenforces four workflow rules mechanically: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait. -
The palette is written twice for dark, and that duplication is the mechanism.
@media (prefers-color-scheme: dark) :root:not([data-theme="light"])follows the system;:root[data-theme="dark"]is the explicit choice from the colors panel. Drop the:not()and a system-dark browser overrides someone who asked for light. A chosen accent is applied as an inline custom property on:root(CSSOM, which the CSP allows), and the default is applied by REMOVING that override so the stylesheet's own per-theme values win. The server'sdata-looks-accentstand-in only lasts untilapplyLooks()runs, which removes it first thing — left on, its rule would beat "Back to default". -
Help is in the page, built on first open. The ? button (
#btn-about) opens<dialog id="help-modal">, which replaced the old "What this page is" About dialog. Its 22 panels and their icon sheet are hand-written HTML and SVG in<template id="help-content">inindex.html(after#start-poses), cloned into#help-panelsthe first time ? is pressed (except the dashboard topic's card list:buildHelp()fills its.help-cardsfromSKILL_CATALOGandCATALOG_GROUPSat that moment, in the dashboard's order), so first load builds nothing and Help still reads fully once the server is gone.help.jssupplies the tab list and rules,screens/help-dialog.jsthe wiring (tab buttons, roving focus,renderAbout()for the live connection line on tab 1,lightDismiss(), and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — astyle=attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in adata-factspan a test checks against the constant it comes from. -
Stuck sessions are explained twice, in Help and on the status line.
stuck("When something looks stuck") is the second tab inHELP_TABS; its panel opens with ahelp-callout("Check this first": Plan2Code often waits for a permission in the terminal, which the page cannot see) and four You see / Likely cause / Do this rows before the diagram. The quiet and Not running status lines carry a "What to check" button (openHelpOn("stuck")) inside the existingrole="status"element, so it exists only while the symptom shows. Every finished and paused screen gets a "Before you close this" panel fromrenderCloseGuide()inrenderHandoff()(Safe to close, Start fresh, Carry on). Tests inscripts/test-web-console-source.mjscheck the tab order, the callout and rows, and therenderCloseGuidecall. -
Markdown is rendered to DOM nodes, never to an HTML string (
public/render.js), so agent-authored text that quotes a hostile source cannot execute. Onlymarked.lexer()is used.
Tests: npm test runs, in order, validate-char-count.js, install.js --build-skills, parse-check.mjs, check-skill-table.mjs, then one node --test over the skill-script tests (test-skill-scripts.mjs, test-script-*.mjs, test-git-repo.mjs), test-launcher.mjs, test-getting-started.mjs and the web console's test-web-console-*.mjs, so they run in parallel, one process each. The console tests are split by area (-session, -lifecycle, -logic, -server, -chat, -chat-stress, -workspace, -subagents, -concurrency, -source, -shape, -git, -git-board, -qa, -speed, -hardening, -embed, -handoffs, -in-app, -loop, -notepad, -pointers, -skills, -spec-states, -state, -tones), plus the -page-* browser suites and the per-game -activities* suites. Their shared setup is scripts/web-console-test-helpers.mjs: importing it gives the file its own console home (so workspaces.json, subagents.json, looks.json and sessions never collide across files) and registers the stop --all cleanup. -session and -lifecycle each run an ordered chain of tests on one session of their own; everything else opens a session per test. A new test goes in the file for its area, after the tests it depends on. The parse check exists because node --check parses a .js file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in scripts/, not src/web-console/, because everything under the latter ships into every skill.
Adding a file under public/: a page module needs SERVABLE in static.mjs and a <link rel="modulepreload"> in index.html. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a module missing from it 404s and the page dies at import with no useful error (the import-fetch test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after app.js and slows the first paint. A screen goes in public/screens/, imports only state.js and the pure modules (never another screen), and is imported by screens/core.js; the import guard in scripts/test-web-console-shape.mjs fails naming a screen that breaks either rule. A stylesheet goes in public/styles/ and on CSS_ORDER in static.mjs, never on SERVABLE; the joined-stylesheet test fails when the folder and the list disagree. Every new file also needs its row in the files tables (the server and contract in the console file, a public/ file in the page file, a game file in Activities or the Ghoul Rush files), which the docs-table test (same file) checks.