Compare commits

..
101 Commits
Author SHA1 Message Date
jparkerweb 57134cf36e Merge pull request #7 from jparkerweb/sync/upstream-v2.4.5
v2.4.2: upstream web console updates (Cleanup, update banner, launcher banner, Notes threads)
2026-10-05 19:11:56 -07:00
jparkerweb c19a072a3a Sync upstream web console updates into v2.4.2: on-demand Cleanup of unused ~/.plan2code files, an UPDATE AVAILABLE banner from the release tags, a colored launcher with a Planny banner, Notes threads that keep the person's notes and read older reply shapes, the repo-local plan2code-model-update maintainer skill, and review fixes (413 for oversize bodies, notes kept on skip, scoped reconnect banner, live Overview tab, busy state on 409, menu keyboard focus, case-insensitive mentions) 2026-10-05 19:10:45 -07:00
jparkerweb cd8a1be568 Change image alt text for banner in README
Updated image alt text in README.md.
2026-10-05 18:56:03 -07:00
jparkerweb f968aeded8 Show a small spinner left of the web console's Questions and Ask tab names while Plan2Code is on it: Questions spins from Send until the answers are picked up, Ask while a picked-up question has no answer yet, and neither turns once the agent goes quiet or offline 2026-10-04 20:14:53 -07:00
jparkerweb fb71a02756 Hoist the Phase Checklist and Parallel Execution Groups to directly under the Summary in Document's overview.md template, so the phases are found without scrolling
AI Assisted
2026-10-04 18:44:23 -07:00
jparkerweb c8e65f12a6 Count a build on the web console's session meter while it runs, and score Implement + Review's built-in review once instead of twice
AI Assisted
2026-10-04 18:44:23 -07:00
jparkerweb 739e56c5cf Make the web console waiting screen's tasks pointer clickable: while a build runs, Task and the tasks tab's own name (Phase N tasks) show bold in the highlight color and open that phase's tasks tab 2026-10-04 15:52:20 -07:00
jparkerweb ade74cd636 Merge pull request #6 from jparkerweb/develop
Let Send through when an agent asks a question mid-build while still …
2026-10-04 14:24:23 -07:00
jparkerweb 48830c1afb Let Send through when an agent asks a question mid-build while still marked working: once an open question has an answer or note staged the web console unlocks Send at once instead of waiting out quietMinutes, and building.md now says a question stops the build (set waiting in the same post and wait) 2026-10-04 14:12:52 -07:00
jparkerweb b65481cb24 Merge pull request #5 from jparkerweb/develop
update web console, dashboard, implement-review, global launcher
2026-10-04 12:20:55 -07:00
jparkerweb 7d54941b75 Port upstream skill scripts into v2.4.1: deterministic workflow steps run as Node scripts beside each SKILL.md (specs, pathfinder, feedback payload, commit message, review scope, agent files, handoff path) with tests, the prompt limit rises to 20,000 chars, upstream review fixes are folded in (linked agent files never overwrite AGENTS.md, review stops with no base, paste-safe commit commands, Pathfinder number high-water mark and dry runs), and web console workspace folders are remembered per project and spec, with Finalize forgetting an archived spec's list
AI Assisted
2026-10-04 12:17:05 -07:00
jparkerweb 5cbc6edce2 Add the session meter rescale to the v2.4.1 CHANGELOG 2026-10-04 07:40:29 -07:00
jparkerweb 6b93bcb4c5 Scale the web console session meter with the work done: built phases score one point per 3 completed tasks (reported as run.tasks), every 2 answered questions add a point to their skill run, each Pathfinder research question adds 1 via the new pathfinder-research event, and thresholds move to yellow at 5, red at 10, ring full at 15 2026-10-03 22:31:14 -07:00
jparkerweb d49f2d5792 Keep Pathfinder from ending a session while its research subagents are still running: wait for every one, show a running count in the web console, mark finished research with a completion line, and re-run interrupted research on resume
AI Assisted
2026-10-03 10:23:38 -07:00
jparkerweb bfb47f3a8e Refresh agent docs, README and quick reference for v2.4.x: document plan2code-bot, launcher model menu, test/dev env vars, full npm test pipeline, GitHub-issues pathfinder backend, and dedupe command lists in favor of the README
AI Assisted
2026-10-03 09:38:55 -07:00
jparkerweb cb86034de9 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
2026-10-02 20:51:34 -07:00
jparkerweb 0d7c2e140b Sync upstream v2.4.0 (web console, dashboard skill, implement-review, global launcher) with 24 review fixes and a look-around wake-up for Planny
AI Assisted
2026-09-28 19:37:41 -07:00
jparkerweb eefa7082ed Add pathfinder BRIEF mode, resolved-date tracking, and decide-menu-checkpoint cadence (v2.3.0)
AI Assisted
2026-09-03 07:18:34 -07:00
jparkerweb 8acd7b9d9f Modify image tag in README for better display
Updated image tag to include 'object-fit' style.
2026-08-26 22:24:02 -07:00
jparkerweb f026d3eebc Change banner image source to direct URL
Updated image source in README to use a direct URL.
2026-08-26 22:18:20 -07:00
jparkerweb 1b3360dc99 Add clipboard copy functionality for installation command in index.html 2026-08-22 10:10:06 -07:00
jparkerweb 16a736a2a9 Change alt text for banner image in README
Updated image alt text in README.
2026-08-22 09:58:20 -07:00
jparkerwebandDevin 8663eba113 Update the protected repository sync workflow
Keep the encrypted maintainer instructions current without mixing the opaque payload into the installer migration commits.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-08-20 13:42:56 -07:00
jparkerwebandDevin f40ddf5f8e Document the v2.2.0 skills-based distribution
Align release notes, version metadata, installation guidance, and maintainer documentation with the canonical skills workflow.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-08-20 13:42:43 -07:00
jparkerwebandDevin 57e32ab64f Delegate workflow installation to the skills CLI
Replace per-tool distribution generation with a canonical committed skills build so installation and updates share one format.

Generated with [Devin](https://devin.ai)

Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-08-20 13:42:31 -07:00
jparkerweb 483c3055b2 v2.1.1 - Failure Log convention in the init prompts 2026-08-12 13:54:43 -07:00
jparkerweb ca1e137a54 update init instructions 2026-08-12 13:15:50 -07:00
jparkerweb a7506952c8 Add a GitHub Issues backend to Pathfinder
Chart Step 1 now asks where the map should live: local files under
gitignored specs/ (the default) or a pathfinder:map issue whose decision
questions are its sub-issues, driven by gh. The pick is recorded as the
first Ground rules bullet and never re-asked; Auto-Discovery resolves
either backend, and an issue URL routes straight to github.

On github the local model maps onto the tracker's own primitives rather
than being simulated in issue bodies: sub-issues, native issue
dependencies for blocking, the assignee as the claim, one
pathfinder:<type>-<mode> label so type and mode cannot drift, and an
Answer comment plus a close reason that distinguishes a decision from a
question ruled out of scope. Both wiring calls key on the database id,
not the number. The map body therefore carries no checklist at all.

Sketches, secrets and the PLAN-DRAFT stay on local disk regardless --
plan2code-1-plan discovers its input with ls specs/ and has no notion of
a tracker. github is only offered after a five-check preflight, and the
offer names the repo's visibility, because a map on a public tracker
publishes the destination and the codebase recon. The Step 3 recon is
held until Step 6 so the no-fog off-ramp leaves no litter.

Depth lives in a seventh reference file; the orchestrator was
recompressed to absorb the new section within the 11,000 char limit by
removing duplication with its references. Adapted from the GitHub
tracker doc behind Matt Pocock's wayfinder skill (MIT).

AI Assisted
2026-08-08 19:00:26 -07:00
jparkerweb dd7d8eff2d Point plan2code-bot at the GitHub repo URL
AI Assisted
2026-08-08 12:39:52 -07:00
jparkerweb b9c6d87a2d Release v2.0.0
Ports upstream v1.17.0 and v2.0.0. Breaking: Gemini CLI is no longer an
install target. Adds Pathfinder Step 0, community feedback submission and
ingestion, and Devin CLI as an agent backend.

AI Assisted
2026-08-08 12:39:37 -07:00
jparkerweb 94d53d1152 Update the Claude Code status line
AI Assisted
2026-08-08 12:39:29 -07:00
jparkerweb 0037bde2aa Document Pathfinder and community feedback across the contributor docs
Moves the README's deep material into .readme/ (walkthrough, autonomous
loop, status line, metrics, test bot) and brings AGENTS.md, the .agents-docs
set and QUICK-REFERENCE.md in line with Step 0 and the metrics ingestion
flow.

AI Assisted
2026-08-08 12:39:29 -07:00
jparkerweb 1d88d787a3 Ingest community feedback submissions in plan2code-metrics
Adds a CLI flow that lists open community-feedback issues via gh, validates
and parses each METRICS_JSON payload, imports them deduped by run_id,
re-aggregates and closes the issue. Community runs cohort by Plan2Code
version rather than prompt fingerprint, and local cohorts stay preferred so
ingested feedback never displaces the maintainer's current generation. Adds
Devin CLI as an AI backend.

AI Assisted
2026-08-08 12:39:28 -07:00
jparkerweb 987f7b8b04 Add Devin CLI as a selectable agent backend in plan2code-loop
Upstream replaced GitHub Copilot CLI with Devin; Plan2Code keeps both, so
Claude Code, Copilot CLI and Devin are all selectable and existing Copilot
selections keep working.

AI Assisted
2026-08-08 12:39:28 -07:00
jparkerweb 9bc0cfe652 Drop Gemini CLI as an install target and register Pathfinder
Removes the .gemini/commands/*.toml surface and the build-time inlining it
required; every remaining target resolves reference directives at runtime.
The uninstall entry is retained behind an uninstallOnly flag so .toml files
from earlier versions can still be cleaned up.

AI Assisted
2026-08-08 12:39:13 -07:00
jparkerweb 044d41ad06 Add Pathfinder as an optional Step 0 and offload prompt depth to references
Pathfinder charts an idea that is too big to plan as a map of decision
questions under specs/<idea>/pathfinder/, clearing one per session until it
can hand a PLAN-DRAFT to Step 1. Finalize now archives pathfinder/ with the
spec and revise-plan no longer deletes it — both previously described the
cleanup target in wording that pointed at questions/. Init-update Step 7 and
review Session End move to reference files with inline fallbacks.

AI Assisted
2026-08-08 12:39:13 -07:00
jparkerweb b08b385e76 Pin LF line endings and renormalize the working tree
scripts/validate-char-count.js measures characters on disk, so a CRLF
checkout added ~1 char per line and pushed the 11k-budget prompt files over
the limit depending on how the repo was cloned. Pins eol=lf, marks binaries,
and renormalizes the files that had CRLF.

AI Assisted
2026-08-08 12:38:58 -07:00
jparkerweb 61b3050174 Redesign docs site and README around an airmail postcard theme
Adds a postage-stamp favicon set and banner, removes three orphaned images,
and records the site and README as protected divergences so an upstream sync
can't revert them.

AI Assisted
2026-08-08 12:32:17 -07:00
jparkerweb 7b57d70e31 URL updates 2026-08-01 13:04:39 -07:00
jparkerweb 832cb1637b update URLs 2026-08-01 12:56:52 -07:00
jparkerweb 6290f66d03 Merge pull request #3 from jparkerweb/statusline-worktree
Add git worktree awareness to status line (v1.16.1)
2026-07-31 22:24:02 -07:00
jparkerweb f8f9896d38 Bump to v1.16.1 for status line git worktree awareness 2026-07-31 22:20:38 -07:00
jparkerweb be24b0a8dc Add git worktree awareness to status line
Sessions in a linked worktree previously showed only the worktree's
directory name, so the underlying repository was unidentifiable and the
session looked like an unrelated project.

The project segment now renders as "repo | worktree". Repo identity comes
from git rev-parse --git-common-dir, so it is correct regardless of how the
worktree directory was named. A leading repo prefix is stripped from the
worktree name, and the name collapses to a bare marker when it merely
restates the branch already on screen -- matched across / _ . - separators
and type prefixes like feature/, and only when the branch is displayed.

Gated behind the new items.worktree config flag (default on). Costs one
extra timeout-bounded git call, skipped entirely outside git repos.
2026-07-31 22:20:38 -07:00
jparkerweb 34204d9993 Merge pull request #2 from jparkerweb/handoff
Release v1.16.0: install handoff skill, add publish skill, sync upstream
2026-07-20 22:39:25 -07:00
jparkerweb 3e6566af4f Address PR review feedback: update step label + release-list limit 2026-07-20 22:36:35 -07:00
jparkerweb 1183919964 Set v1.16.0 releaseDate to 2026-07-20 2026-07-20 22:33:24 -07:00
jparkerweb f0a60da2e2 Release v1.16.0: install handoff skill, add publish skill, sync upstream
- Make plan2code-handoff an installed workflow prompt: move to src/,
  register in install.js SOURCE_PROMPTS, remove repo-local-only copy
- Add repo-local maintainer /plan2code-publish skill (cuts GitHub Releases;
  excluded from install.js)
- Review workflow next-step suggestion made context-aware (upstream v1.15.4)
- Doc updates: list handoff in README, QUICK-REFERENCE, architecture table;
  add "Adding a New Workflow Prompt / Skill" checklist to dev-commands
- Fix broken AGENTS.md index links: rename .agents-docs loop/metrics files
  to plan2code-* to match references
- Bump version.json to 1.16.0 to align with package.json and CHANGELOG
2026-07-20 22:31:37 -07:00
jparkerweb 5d0f2c6380 Merge pull request #1 from jparkerweb/handoff
Add plan2code-handoff skill for conversation handoff documents
2026-07-20 22:09:45 -07:00
jparkerweb 495f0cc3f6 Add plan2code-handoff skill for conversation handoff documents
AI Assisted
2026-07-20 22:07:21 -07:00
jparkerweb ed220c3c7d Bump to v1.15.4 for status line reasoning effort and context token count
AI Assisted
2026-07-19 21:22:54 -07:00
jparkerweb 8e700d485c Add reasoning effort label and context token count to status line
AI Assisted
2026-07-19 21:18:10 -07:00
jparkerweb 8f87dcce67 Sync upstream workflow improvements (v1.15.3): session-end summaries, Sync & Maintain in init-update, plan research steps, ls-based spec discovery, revision/commit guardrails; bump version to v1.15.3
AI Assisted
2026-06-28 11:46:40 -07:00
jparkerweb 9e6949ec60 sync update 2026-06-01 20:44:05 -07:00
jparkerweb 36ee3343a0 Stop ignoring CLAUDE.md
AI Assisted
2026-06-01 19:42:19 -07:00
jparkerweb f1e0de5f2d Add password-protected sync-repo skill with encrypted body
Adds a project-local /sync-repo skill whose real instructions are encrypted
at rest (AES-256-GCM + scrypt) in sync-repo.enc and only revealed in-session
after the user supplies the correct passphrase. Plaintext SYNC.md is gitignored
and never committed; *.enc is marked binary to protect the ciphertext bytes.

AI Assisted
2026-06-01 19:41:34 -07:00
jparkerweb b941c3fdb8 v1.15.2 — add Claude CLI status line, Zed support, rename 3b-review to review
- Status line: new src/statusline-claude/ (Planny box-star mascot icon),
  install/uninstall wiring in install.js, Install All (A) + Custom (S)
- Zed agent support across README, AGENTS, docs, init prompt, installer
- Rename /plan2code-3b-review to /plan2code-review (now a standalone
  utility workflow); update file, reference dir, and all cross-references
- install.js: fs.rmSync simplifications, async install, summary cleanup
- Bump to v1.15.2; CHANGELOG entries for v1.15.0/1/2
2026-06-01 16:39:35 -07:00
jparkerweb b79aed8569 v1.14.0 — add Step 3b review workflow, unify file naming, resilient code references
- Add /plan2code-3b-review: 5-step post-implementation review with adaptive
  scope, 11 dimensions, reference-file architecture, and Plan/Apply/Verify fixes
- Unify workflow/skill file naming to single-dash (drop -- and --- conventions)
- Add Devin platform support and CLAUDE.md MANDATORY FIRST STEP template
- Guide agents to use semantic anchors over line numbers in workflow prompts
- Bump version to 1.14.0
2026-05-23 06:58:20 -07:00
jparkerweb ec61e9c2ca v1.11.1 — installer 'A' option and bot evaluation notes
- install.js: split into 'I' (prompts + loop) and new 'A' (everything
  including bot + metrics); update prompt to (I, A, U, C, Q).
- CHANGELOG: document complexity check (1.11.1) and expand 1.11.0
  notes for the LLM-as-judge evaluation system.
- version.json: 1.10.0 -> 1.11.1.
2026-05-11 13:14:35 -07:00
jparkerweb 1d75934e45 plan2code-bot: replace auto-responder with LLM-as-judge evaluation
Bot now acts as an authentic QA agent instead of rubber-stamping every
question and step.

- intelligent-responder answers AskUserQuestion via LLM using current
  observations (tools used, files created, errors) instead of keyword
  matching; auto-responder removed.
- evaluator runs after each step with step-specific criteria
  (prompts/evaluation-criteria.ts), produces 0-100 score plus
  strengths/weaknesses/critical issues. Avg <60 blocks finalization.
- observation-collector captures tool_use, file writes, errors, and
  question reasoning; session-runner falls back to scraping tool_use
  blocks when canUseTool doesn't fire and dedupes both sources.
- Bot writes BOT-EVALUATION.md and BOT-NOTES.md for metrics analysis.
- Idea generator: 12 categories instead of CLI/web-app coin flip,
  stronger seed adherence, less developer-tool bias.
- Init step now writes a minimal AGENTS.md stub instead of running
  the full init skill, avoiding hallucinated architecture before plan.
- Implement step uses Read/Write/Edit/Glob/Grep directly instead of
  a Skill sub-session that produced no visible tool observations.
- bin: add --help, accept --idea="value" form, strip surrounding
  quotes; evaluator maxTurns 3 -> 30; warn when parser misses SCORE.
2026-05-11 13:14:28 -07:00
jparkerweb 882caa1d12 metrics: adopt METRICS_JSON HTML comment as primary format
Plan, document, and finalize prompts now emit a single
<!-- METRICS_JSON {...} --> block with all structured fields. Collector
parses these directly and keeps the old prose/table parsing as fallback.

Also adds a per-task complexity check to the document prompt:
split tasks with 3+ complexity signals (5+ logic branches, 2+
integration points, shared interface mutation, etc.), combine
adjacent trivial tasks.
2026-05-11 13:14:15 -07:00
jparkerweb 1301aa1b40 prompts: drop Git Commit Messages section from AGENTS.md and init flows
Project-specific commit conventions don't belong in the generic init
templates. AGENTS.md, init, and init-update no longer mention or audit
a Git Commit Messages section.
2026-05-11 13:14:08 -07:00
jparkerweb e3ed8e80f2 v1.11.0 — add plan2code-bot to root changelog 2026-03-01 21:33:57 -08:00
jparkerweb 7b3266e7d8 feat: add plan2code-bot with --resume capability and state cleanup
Add the autonomous workflow test runner (plan2code-bot) that uses the
Claude Agent SDK to run plan2code end-to-end. Includes --resume flag
to continue incomplete runs from saved state, and automatic state file
cleanup on successful completion.
2026-03-01 21:30:45 -08:00
jparkerweb bc6e2863dc v1.10.0 2026-03-01 12:24:11 -08:00
jparkerweb da51a8b7fa Planny hit the gym and lost some weight
Trimmed the mascot ASCII art across all prompts and installer.
Planny is now more aerodynamic and 40% less chunky.
2026-02-22 21:48:13 -08:00
jparkerweb 46f96f7fc8 docs: update AGENTS.md with plan2code-metrics section and corrections
- Add plan2code-metrics to architecture tree, dev commands, installer menu
- Add full metrics section (data flow, CLI menu, key files, feedback format, metric targets)
- Fix Code Style: split install.js (CommonJS) vs loop/metrics (TypeScript+ESM)
- Update finalize prompt description to reflect 7 steps
- Add metrics-specific gotchas (internal prompts, feedback table format)
2026-02-22 21:47:45 -08:00
jparkerweb 0e3651b475 v1.8.1 — add user feedback collection to plan2code-metrics 2026-02-22 21:41:16 -08:00
jparkerweb b228f2f9fe feat: add user feedback collection to plan2code-metrics
- Add UserFeedback type (rating 1-10, reason, went well, went poorly)
- Collector parses ## User Feedback table from overview.md
- Aggregator computes avg_user_rating and feedback_count per cohort
- CLI offers interactive feedback collection with pipe-safe escaping
- Finalize prompt collects optional feedback as Step 5 (before archival)
- Analysis/improvement prompts reference avg_user_rating metric target
2026-02-22 21:38:58 -08:00
jparkerweb 9d5dc75eca v1.8.0 — add plan2code-metrics recursive self-improvement toolchain
New package for contributors to collect, aggregate, analyze, and improve
workflow prompts based on real project data. Includes unit tests (vitest),
installer integration, and loop/finalize hints.
2026-02-22 19:57:40 -08:00
jparkerweb 7cb3e81890 v1.7.0 2026-02-22 12:58:08 -08:00
jparkerweb 968bad2548 v1.6.1 2026-02-18 15:16:11 -08:00
jparkerweb b942b2b9f0 v1.5.4 2026-02-17 09:13:23 -08:00
jparkerweb 725af08c90 spacing 2026-02-03 20:32:18 -08:00
jparkerweb c10354abff v1.5.2 2026-01-27 12:11:00 -08:00
jparkerweb b1502edfb2 v1.3.3: Learning Capture Protocol and improved session instructions 2025-12-31 13:07:27 -08:00
jparkerweb 87b6b643f0 naming and prompt cleanup 2025-12-25 22:02:24 -08:00
jparkerweb d6354099a9 docs 2025-12-25 21:45:41 -08:00
jparkerweb 582cfccdf5 docs
Updated README to include new workflow details and installation instructions.
2025-12-25 21:45:05 -08:00
jparkerweb b3369e5f76 docs 2025-12-23 17:23:23 -08:00
jparkerweb 0cbacb2a37 improved build and install process 2025-12-23 15:42:35 -08:00
jparkerweb 1eeab9cbb3 Delete .windsurf directory 2025-12-22 09:11:18 -08:00
jparkerweb 7ec47ba7b1 Delete .github directory 2025-12-22 09:11:10 -08:00
jparkerweb 61bad114ec Delete .cursor directory 2025-12-22 09:11:00 -08:00
jparkerweb d8369a0b8c Delete .continue directory 2025-12-22 09:10:49 -08:00
jparkerweb bdebbe30ae Delete .claude directory 2025-12-22 09:10:40 -08:00
jparkerweb bb76590667 Delete .agent directory 2025-12-22 09:10:27 -08:00
jparkerweb e88f467b40 v1.0.4 - Added explicit transition check to Planning Phase 6 2025-12-07 17:52:40 -08:00
jparkerweb 6c04256274 v1.0.3 2025-12-05 21:44:21 -08:00
jparkerweb b2a2ddfc43 v1.0.2 2025-12-05 15:41:23 -08:00
jparkerweb ef30ff0858 - Added Initial Context Check to Planning Phase 1 - Model now asks about additional files, reference materials, and external integrations before
analyzing requirements
- Added user verification checklist and git checkpoint to `Implementation Phase 3` - Phase completion reports now guide users through verification and git checkpointing before starting the next phase
2025-12-05 10:43:58 -08:00
jparkerweb 06f8f78e89 docs 2025-12-04 21:30:41 -08:00
jparkerweb 3dc6681151 docs 2025-12-04 20:51:05 -08:00
jparkerweb 0727988616 docs 2025-12-04 20:28:25 -08:00
jparkerweb 5703ecf8bd update website 2025-12-04 20:23:33 -08:00
jparkerweb fb945f3084 Revise README for Plan2Code workflow updates
Updated the README to reflect changes in the Plan2Code workflow, including new file references and installation instructions.
2025-12-04 18:10:42 -08:00
jparkerweb 47574f78cb docs 2025-12-04 18:09:23 -08:00
jparkerweb 7888f06f11 Create CNAME 2025-12-04 17:47:20 -08:00
jparkerweb 38bd676afa Update and rename plan2code.html to index.html 2025-12-04 17:42:27 -08:00
jparkerweb 7bca4bf9b7 docs 2025-12-04 17:36:20 -08:00
jparkerweb 1bd05b2fe5 v1.0.0 2025-12-04 17:34:22 -08:00
jparkerweb 89437d36b4 Initial commit 2025-12-02 20:59:19 -08:00
180 changed files with 13055 additions and 1264 deletions

No files matched your search

+7 -4
View File
@@ -59,7 +59,7 @@ plan2code/
├── .husky/ # Git hooks (husky)
│ └── pre-commit # Runs character count validation
├── .claude/ # Repo-local Claude Code config (NOT installed by install.js)
│ └── skills/ # Maintainer-only dev skills, e.g. plan2code-publish/
│ └── skills/ # Maintainer-only dev skills, e.g. plan2code-publish/, plan2code-model-update/
├── .github/ISSUE_TEMPLATE/ # bug.yml, idea.yml, config.yml (target of the console's feedback button)
├── .readme/ # User guides linked from README (web-console.md, web-console-design.md, walkthrough.md, autonomous-loop.md, metrics.md, status-line.md, test-bot.md)
├── docs/ # Landing page `index.html` served at plan2code.jparkerweb.com (GitHub Pages, `CNAME`) and assets
@@ -159,6 +159,7 @@ Maintainer-only skills committed to the repo but deliberately excluded from the
- `plan2code-publish/` — publishes a GitHub Release after version files agree.
- `plan2code-changelog/` — validates release classification and keeps version files synchronized.
- `plan2code-model-update/` — refreshes the launcher's curated model menu (`src/launcher/models.json`) from `devin models list` and Claude Code's documented model aliases: shows a diff, applies only the changes the maintainer approves, validates the file and runs `npm test`. Terminal only, and it never commits.
- `sync-repo/` — decrypts the protected upstream-sync workflow in memory.
Do not run `skills add` against the repository root: recursive discovery also finds these maintainer skills. `install.js` targets `skills/` and passes explicit workflow names instead. Global install/uninstall cleanup removes `plan2code-*` workflow skills from user skill directories; it never operates on this repository's `.claude/skills/` directory, and `sync-repo` intentionally has no `plan2code-` prefix.
@@ -171,7 +172,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|---|---|
| `console.mjs` | the CLI the agent drives: `open`, `post`, `wait`, `chat` (the instant Quick question check), `keep` (copy a cited note attachment into `specs/<idea>/attachments/`), `status`, `stop`, `help` (a compact summary for an agent that found the binary but not `console.md`) |
| `server.mjs` | HTTP server, spawned **detached** by `open` (never as a harness background task, which get killed on compaction and at assorted timeouts) |
| `lib.mjs` | session paths, atomic writes, the patch merge, `validate()` (which also allows `templates` only as `"idea"` on a `text` item; anything else exits 3), `attachmentName()` (the kept-file name `<slug>-<id8>.<ext>`: the same upload always gets the same name), `repoRoots()` (returns `{ project, worktree, branch }`), `readOverview()`, and the three sweeps `open` runs fire-and-forget after it prints (see the cleanup design point below): `sweepUploads()`, `staleSessions()` / `removeSessions()` and `staleScratch()` / `removeScratch()` |
| `lib.mjs` | session paths, atomic writes, the patch merge, `validate()` (which also allows `templates` only as `"idea"` on a `text` item; anything else exits 3), `attachmentName()` (the kept-file name `<slug>-<id8>.<ext>`: the same upload always gets the same name), `repoRoots()` (returns `{ project, worktree, branch }`), `readOverview()`, and the three sweeps `open` runs fire-and-forget after it prints (see the cleanup design point below): `sweepUploads()`, `staleSessions()` / `removeSessions()` and `staleScratch()` / `removeScratch()`; plus `cleanupFindings()` / `removeCleanup()` for User Preferences → Cleanup |
| `public/` | `index.html`, `app.js`, `answers.js`, `labels.js`, `boot.js`, `chat.js`, `help.js`, `starters.js`, `workspace.js`, `meter.js`, `mentions.js`, `favicon.js`, `app.css`, `render.js`, `palette.js`, `favicon.svg` (Planny peeking up from the tab bar, served as `image/svg+xml`) with `favicon.png` (the same icon at 192 px, served as `image/png`) as the fallback, `vendor/marked.esm.js`, the chimes (`start-skill.mp3`, `bootup.mp3`, `start-stop.mp3`, `next.mp3`, `insert.mp3`, `sleeping.mp3`; which moment plays which is `SOUND_EVENTS` in `palette.js`, one switch per event saved in `looks.json`), and a `package.json` that only says `"type": "module"`, so Node (the server, `console.mjs`, `lib.mjs` and the tests import several `public/*.js` modules) parses them as ES modules without a reparse warning |
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (16 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping). No module-scope DOM, so `node --test` covers it |
| `public/workspace.js` | PURE, no imports: the Workspace's name rules (`nameProblem()`, `NAME_MAX`, `defaultName()`, `freeName()` for the `-2` suggestion), the footer label and its width tiers (`footerLabel()`, `FOOTER_TIERS`) and `changeLine()`, the `Workspace: …` reply line an agent is handed per change. Imported by the server, `console.mjs`, `lib.mjs` and the page |
@@ -179,6 +180,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `public/mentions.js` | PURE, no imports: the `@name` popover's logic — `mentionAt()` finds an `@partial` at the caret, `matchNames()` filters the workspace names, `applyMention()` splices a pick in and returns the new caret. Used by the Ask box, notes and text answers |
| `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin, finished })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (finished, `happy`); `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `<link rel=icon>` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second |
| `picker.mjs` | the per-OS native folder picker behind **Browse…** (`pickerCommand()` → `{ command, args, env }` or `null`; `pickFolder()` runs it with async `spawn`, so the server keeps serving while the dialog is open). Copied from `src/launcher/plan2code.js` (self-contained CommonJS, so it cannot be shared) with the prompt as a parameter; a drift test keeps the two in step |
| `update-check.mjs` | the dashboard's release check, server-only (never in `SERVABLE`): `compareVersions()` (numeric X.Y.Z, `null` otherwise), `latestTag()` (the highest `refs/tags/vX.Y.Z`, peeled `^{}` and pre-release tags skipped), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags` on the repo: no shell, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, SSH `BatchMode` when `GIT_SSH_COMMAND` is unset, `windowsHide`, killed at 10 s; git authenticates itself, the console never touches a credential). The answer, failures included, is cached for an hour in `~/.plan2code/console/update-check.json` (`UPDATE_CHECK_FILE`, in `PROTECTED_CONSOLE_FILES` so no sweep removes it). `server.mjs` starts it after the ready line and never awaits it; `stateFrame()` carries `update: { installed, latest }` only when a newer release exists (its `latest` is part of `haveKey()`, so a page that connected first still gets it), and `GET /version` returns `{ version, latest }`. Tests seed a fresh cached failure in every console home, so no test server reaches the network |
| `public/chat.js` | the Quick question chat's PURE rules, shared by the server and the page: `CHAT_LIMIT` / `CHAT_MAX_CHARS` / `CHAT_MAX_ATTACHMENTS` (the combined image + document cap; `CHAT_MAX_IMAGES` is kept as an alias of it), `chatOffline()` (the server's `409 offline` guard), and the page's view model (`chatView`, `sendState`, `nextAbout`, `contextOptions`, `unreadDot` / `shouldChime`). Ask context is the `{ history, about }` model: `nextAbout()` records the last 3 places visited in `history` and sets `about` only when the person picks one from **+ Add context** (`contextOptions()` lists that history plus *This spec*); dropping it or a successful send clears it, so the page never attaches context on its own. Imports only `answers.js`, no module-scope DOM, so `node --test` covers it |
| `public/starters.js` | PURE, no imports: the Role list (`ROLES`, `ROLE_NOT_SET`, `normalizeRole()`, `needsRoleNudge()`: the dashboard banner shows until `looks.json` carries any `role`), the 13 starter templates and their per-role orders (`TEMPLATES`, `TEMPLATE_ORDERS`, `templatesFor()`, `templateSwap()` for the replace prompt), and the Ask starter sets (`STARTER_SETS`, `STARTER_SET_FOR`, `startersFor()`). Imported by `app.js` and the tests; in `SERVABLE`, preloaded by `index.html` and parse-checked. The page owns the wording; a skill only flags its fresh-idea `text` card with `"templates": "idea"` |
| `public/answers.js` | the page's PURE answer-shaping logic (what an answer reads as, what a placeholder offers, whether a send carries an answer at all). Split out of `app.js` because `app.js` cannot be imported outside a browser, so anything left in it is untestable. `scripts/test-web-console.mjs` imports this directly. |
@@ -199,6 +201,7 @@ Key design points:
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `server.mjs`, which paints `data-width` on first load; `app.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
- **`GET /overview` is the one route that reads a project file.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or `404 { "error": "no overview" }`. A dashboard session honours `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readOverview()` resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all 404.
- **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-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 the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it.
- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes }], bytes }`, ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `models.json`). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'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] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. 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-dir` fallback; 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 every `console.mjs open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` 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.
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<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 by `startStage()` in `app.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `app.css`; `START_POSES`/`startPose()` in `answers.js` is the list, 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 an `activity` and 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 start path is timed, and `open` is built around it.** Measure with `node scripts/bench-web-console.mjs` (`--browser-delay 900` for a real Chrome launch, `--roundtrip` for Send→agent and post→page, `PLAN2CODE_CONSOLE_TRACE=1` on `open` for a step timeline). Four things make it fast, and each is load-bearing:
@@ -214,7 +217,7 @@ Key design points:
| `ledger.ndjson` | `console.mjs` | append-only, one JSON line per entry. Meter events: `launch` (every fresh `open` and every resume into another workflow), `run` (a post's `run`, id scoped by launch, with `tasks` when a built phase reports one) and `answer` (one per item the person answered in a collected send, written by `ledgerAnswers()`, id `<launch>:answer:<send stamp>:<item>`). Also `folder-issue` reports |
| `workspace-cursor.json` | `console.mjs` | the last workspace `version` handed to the agent; advanced after the print, never backwards |
The page changes the workspace only through five routes: `GET /workspace` (`?check=1` re-stats every folder first), `POST /workspace/add` (path resolved against `state.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) and `POST /workspace/browse` (one picker at a time, 409 `busy`; 404 `no-picker` when `remote` is set or no picker exists; `PLAN2CODE_PICKER_ECHO` stands in for the dialog in tests). `stateFrame()` carries `workspace` (folders, `missing`, `remote`, the current launch's folder `issues`) and `meter` (`meterView()` over the ledger), and both files are on the 1s poll. The agent hears of the workspace through `open` output (`workspace: { folders, missing? }`, which also seeds the cursor) and then each change once, as `workspace: [...]` plus `Workspace: …` reply lines on `wait` exit 0 or `chat`; a change alone never ends a `wait` slice (`pendingWorkspace` on exit 10). `post` and `open --file` lift `run` and `folderIssue` out of the patch into the ledger, never into `state.json`; an unknown event or a malformed issue is exit 3. **Remembered workspaces.** `lib.mjs` keeps `~/.plan2code/console/workspaces.json` (`WORKSPACES_FILE`, under `PLAN2CODE_CONSOLE_HOME` in 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 first `workspaceNow()` and in `open`'s read-only `workspaceOnOpen()`, so they agree. `workspace.json` carries `scope` (the spec key or `""`). Every user change (`bumpWorkspace`, not `missing`/`found`) calls `rememberWorkspace()`. `setScope()` swaps the list, logging `removed`/`added`/`renamed`/`described` changes 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, and `followSpecDir()` (state poll, boot) moves the scope to a posted `specDir`, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server and `console.mjs forget --spec` (Finalize Step 6). The contract is in `console.md` (Workspace; Posting an update → Session meter) and `building.md` (per-phase `run`), so the skill prompts stay unchanged.
The page changes the workspace only through five routes: `GET /workspace` (`?check=1` re-stats every folder first), `POST /workspace/add` (path resolved against `state.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) and `POST /workspace/browse` (one picker at a time, 409 `busy`; 404 `no-picker` when `remote` is set or no picker exists; `PLAN2CODE_PICKER_ECHO` stands in for the dialog in tests). `stateFrame()` carries `workspace` (folders, `missing`, `remote`, the current launch's folder `issues`) and `meter` (`meterView()` over the ledger), and both files are on the 1s poll; it also carries an optional `update` once the boot-time release check (`update-check.mjs`) finds a newer release. The agent hears of the workspace through `open` output (`workspace: { folders, missing? }`, which also seeds the cursor) and then each change once, as `workspace: [...]` plus `Workspace: …` reply lines on `wait` exit 0 or `chat`; a change alone never ends a `wait` slice (`pendingWorkspace` on exit 10). `post` and `open --file` lift `run` and `folderIssue` out of the patch into the ledger, never into `state.json`; an unknown event or a malformed issue is exit 3. **Remembered workspaces.** `lib.mjs` keeps `~/.plan2code/console/workspaces.json` (`WORKSPACES_FILE`, under `PLAN2CODE_CONSOLE_HOME` in 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 first `workspaceNow()` and in `open`'s read-only `workspaceOnOpen()`, so they agree. `workspace.json` carries `scope` (the spec key or `""`). Every user change (`bumpWorkspace`, not `missing`/`found`) calls `rememberWorkspace()`. `setScope()` swaps the list, logging `removed`/`added`/`renamed`/`described` changes 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, and `followSpecDir()` (state poll, boot) moves the scope to a posted `specDir`, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server and `console.mjs forget --spec` (Finalize Step 6). The contract is in `console.md` (Workspace; Posting an update → Session meter) and `building.md` (per-phase `run`), so the skill prompts stay unchanged.
- **The filesystem is the transport.** Sessions live in `~/.plan2code/console/sessions/<sid>/`, deliberately not under `specs/`, so the console cannot trip the metrics scraper or the loop's marker parser, and survives `git 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>` with `ext` from `DOC_TYPES` in `answers.js` (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to `POST /upload` as `image/jpeg`; documents go as-is as `application/octet-stream`, the extension taken by `docExt()` from the uncut `x-p2c-name`. `readRaw(req, limit, cb)` in `server.mjs` caps images at `MAX_BODY` (4 MB) and documents at `MAX_DOC_BYTES` (10 MB), and drains rather than destroys so the client gets its 413. Images need the `FF D8 FF` magic; documents pass `checkDocument()` in `lib.mjs` (`%PDF-` for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with `crypto.randomUUID()`. `GET /uploads/<id>.<ext>` serves images as `image/jpeg` and documents under a fixed type (`application/pdf`, else `text/plain`) with `nosniff` and, on text, CSP `sandbox` (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 as `sentNote { at, text, images, files }` (paths and names only), which `noteAwaiting()` in `answers.js` turns 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 under `uploads/`. `isOwnUpload()` returns the kind (`"image"` / `"file"` / `false`), and `attachmentsOk()` makes `/submit` comments and `/chat` messages carry images only in `images[]` and documents only in `files[]`, this session's uploads only, at most 5 together (`MAX_ATTACHMENTS`). A comment's `reply` gains one ` Image: <path> (<name>)` or ` File: <path> (<name>)` line per attachment, in attach order; a chat entry's lines come from `chatReplyLines()`, 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 by `console.mjs keep` (`--session --upload --name --spec [--from]`): it checks both paths (the upload must sit under the session's `uploads/`, and the spec folder under `state.project`, real paths included, so a symlinked folder cannot carry the copy outside), copies with `COPYFILE_EXCL` and reuses an existing copy, prints `{ ok, path, link, image, reused }` with a forward-slash link relative to `--from`, and logs a `keep` event. 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 `fallbackText` and `token`, 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.
@@ -265,7 +268,7 @@ Typing `plan2code` in any directory opens the dashboard skill against the curren
| Claude Code | `claude /plan2code --permission-mode bypassPermissions [args]` |
| Devin | `devin --permission-mode bypass [args] -- /plan2code` |
With both on `PATH` it asks `Which CLI should open Plan2Code?` as a numbered menu, the last pick pre-selected (Enter keeps it; a number, `claude` or `devin` also work); with one installed it uses that without asking; with neither it exits 127 naming both. `--cli claude` / `--cli devin` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`. Before spawning, unless the forwarded args carry `--model` / `--model=`, it asks `Which model should <CLI> use?` from the curated `src/launcher/models.json` (copied to `~/.plan2code/bin/models.json`, overwritten by every install) merged with the user's additions in `~/.plan2code/models.json` (edited in the console's User Preferences → Models). Enter keeps the model the CLI last used; a pick appends `--model <id>`. Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed), and it only prints which model will be used. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin` commands and a temp home.
On a terminal it first prints a Planny banner (`renderBanner()`). With both on `PATH` it asks `Plan2Code opens inside an AI coding agent. Pick which one to use:` as a numbered menu, the last pick pre-selected and marked `(last used)` (Enter keeps it; a number, `claude` or `devin` also work); with one installed it uses that without asking, printing `Opening with <CLI>…` (as does a `--cli` pick); with neither it exits 127 naming both. `--cli claude` / `--cli devin` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`. Before spawning, unless the forwarded args carry `--model` / `--model=`, it asks `Which model should <CLI> use?` from the curated `src/launcher/models.json` (copied to `~/.plan2code/bin/models.json`, overwritten by every install) merged with the user's additions in `~/.plan2code/models.json` (edited in the console's User Preferences → Models). Enter keeps the model the CLI last used; a pick appends `--model <id>`. Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed) and no model question: it prints that the CLI will use the model last used in it (switch it in that CLI on its own, or pass `--model <name>`). Headings, numbers, defaults, retry lines and the `plan2code:` error prefixes are colored with `paint()` (the escape values of `install.js`'s `COLORS`, copied), stdout only when stdout is a TTY and stderr only when stderr is, and never when `NO_COLOR` is set; piped runs print plain text and no banner. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin` commands and a temp home.
**Design constraints:**
- **Stable copy, not the package dir** — the installer normally runs from an npx cache directory npm may delete, so `installLauncher()` copies `src/launcher/plan2code.js` to `~/.plan2code/bin/plan2code.js` and the shims point there. (The loop/metrics/bot wrappers point into `__dirname` and don't have this protection.)
@@ -0,0 +1,116 @@
---
name: plan2code-model-update
description: "Refresh the plan2code launcher's curated model menu in src/launcher/models.json from `devin models list` and Claude Code's documented model aliases, with the maintainer approving every change before anything is written. Use this skill when the user says 'update the models', 'refresh models.json', 'new Claude model', 'devin models changed', or otherwise asks to bring the launcher's model list up to date."
---
# Plan2Code Model Update
Bring the launcher's curated model menu (`src/launcher/models.json`) up to date with the models each CLI offers today. Discover what Devin and Claude Code currently offer, show the maintainer a diff against the shipped file, apply only the changes they approve, validate the file, and run `npm test`. This skill never commits.
**Repo-local by design.** This skill lives in the repo's `.claude/skills/` and is intentionally NOT wired into `install.js` — it is a maintainer dev tool, not part of the shipped product, so it is never installed to `~/.claude/skills/`. Do **not** copy it there: the uninstaller (`uninstallSkills()` in `install.js`) and every re-install (`install()`) both run `cleanLegacyPaths()`, which deletes every entry matching `/^plan2code-/` under `~/.claude/skills/` (the `LEGACY_PATHS` row for Claude Code skills), so a copy placed there would be silently removed.
**Terminal only.** This skill runs in the terminal, with no web console session. Ask every question here.
## Workflow
### Step 1 — Preflight
Run from the repo root (the folder holding `install.js` and `src/launcher/`). Run `git status --porcelain -- src/launcher/models.json`. If it prints anything, warn — do not stop:
> `src/launcher/models.json` already has uncommitted changes. The diff below compares against the file as it stands on disk, including those changes.
### Step 2 — Read the current file
Read `src/launcher/models.json`. It has three keys: `_note` (a string), `claude` and `devin` (each an array of `{ "id", "label" }`). Keep the `_note` text exactly as read — Step 7 writes it back verbatim and the Validation rules check it.
### Step 3 — Discover Devin's models
If `devin` is on PATH (`command -v devin` in bash, `Get-Command devin` in PowerShell), run:
```bash
devin models list
```
Show its raw output to the maintainer before any interpretation — the format is not a stable contract. The output is long (hundreds of ids across about twenty families), so save it to a scratch file outside the repo, say where, and show the family headings in full. From it, take the explicit ids at Low, Medium and High effort only, plus `adaptive`. Skip every id the Validation rules forbid (`xhigh`, `max`, `fast`, `priority` endings), and also skip `none`-effort ids, ids with no effort suffix (such as `swe-1-7`, which is a Max model), and `fusion-*` combinations.
The 30-entry cap means the file can never hold every family at three efforts. Propose additions by family — newest and most-used first — and say how many entries that leaves.
If `devin` is not on PATH or the command fails, say so with the error, and switch to **guided manual edits** for Devin: ask the maintainer which ids to add, remove or relabel, one at a time, and carry those into Step 5 as the proposed list.
### Step 4 — Discover Claude Code's models
Look up Claude Code's current model documentation — the model configuration page in the Claude Code docs. Locate it on each run (search the Claude Code docs for model configuration) rather than using a remembered URL; docs move. List the documented model aliases (for example `default`, `sonnet`, `opus`, `haiku`, `opusplan`) and what each one means, and name the page you used. Keep `default` as the file's first entry even though the docs call it a special value rather than an alias. Bracketed aliases such as `opus[1m]` are valid ids; propose them only when the maintainer wants them in the menu.
If the lookup fails or the page does not list aliases, say so, and switch to **guided manual edits** for Claude, exactly as in Step 3.
### Step 5 — Show the diff
For each CLI, compare the discovered list with the current one by `id` and show one table:
| Change | id | Current label | Proposed label | Source |
| --- | --- | --- | --- | --- |
| added | `new-id` | — | New label | `devin models list` |
| gone | `old-id` | Old label | — | not in `devin models list` |
| relabelled | `same-id` | Old label | New label | Claude Code docs: <page> |
- **added:** offered by the CLI, not in the file.
- **gone:** in the file, no longer offered.
- **relabelled:** same `id`, a better or changed label. Propose a label in the file's existing style.
Summarise unchanged entries as a count under the table ("19 Devin entries unchanged") instead of listing them. If approving every **added** Devin row would take the list past 30 entries, say so above the table and by how many. Call out any likely rename before approval (see the rename warning under Validation rules). If both tables are empty, say the file is current and stop.
### Step 6 — Approve each change
Ask about each row, one at a time: **yes**, **no**, or **edit the label** (they type the label to use). Write nothing until every row has an answer. A "no" leaves that entry exactly as it is today.
### Step 7 — Edit `models.json`
Apply only the approved rows:
- Keep `_note` verbatim.
- Keep the existing order. Remove a **gone** entry where it stands, change a **relabelled** label in place, and append each **added** entry at the end of its list.
- Write two-space-indented JSON with a trailing newline, matching the file's current formatting.
### Step 8 — Validate
Check the edited file against every rule under Validation rules. On a failure, show the rule and the entry that broke it, and go back to Step 6 for the affected rows. Do not run tests on a file that fails validation.
### Step 9 — Test
Run `npm test` from the repo root and report the result honestly: pass, or the failing suite and its output. Never describe a failing run as passing.
### Step 10 — Remind about the release
A launcher model change reaches people only with the next release. Remind the maintainer to add a `CHANGELOG.md` line and keep `CHANGELOG.md`, `version.json` and `package.json` on the same version — `/plan2code-changelog` does both.
### Step 11 — Suggest a commit
Suggest a one-line commit message that says what changed, and do not run it:
```bash
git add src/launcher/models.json
git commit -m "Refresh the launcher's model menu"
```
Give `add` and `commit` as two separate commands (Windows PowerShell 5.1 has no `&&`).
## Validation rules
Check every rule before `npm test` (Step 8). They mirror the shipped-file test in `scripts/test-launcher.mjs` ("the shipped models.json is curated Devin at low/medium/high only") plus the menu's own needs:
- The file is valid JSON.
- `_note` is present and unchanged from what Step 2 read.
- `claude` and `devin` are both non-empty arrays.
- `devin` has at most 30 entries.
- Every entry has a non-empty string `id` and a non-empty string `label`.
- Ids are unique within each list, and labels are unique within each list.
- No Devin id ends in `xhigh`, `max`, `fast` or `priority`.
**Warn on renames.** When an entry is **gone** and a near-identical id is **added** in the same list (a changed version number or suffix, say `glm-5-3-high` → `glm-5-4-high`), call the pair out before approval as a likely rename. People's own lists in `~/.plan2code/models.json` merge with the shipped one by id (`mergeModels()` in `src/launcher/plan2code.js`), so a renamed id can bring back a user's old copy of the entry beside the new one. Approve the pair knowingly, or keep the old id.
## Rules
- **Never commit and never push** — Step 11 suggests the commit; the maintainer runs it.
- **Touch only `src/launcher/models.json`**, plus `CHANGELOG.md` only if the maintainer asks for the release line.
- **Nothing is written before every row is answered** (Step 6).
- **Never install this skill** — never add it to `install.js`, and never copy it to `~/.claude/skills/` (the uninstaller deletes `plan2code-*` entries there).
+1 -1
View File
@@ -1 +1 @@
U0VOQwGHvlBAKBpANryoCdXbfPtfW6rftbEVcNYHSx1rwcmt5mK1z/0SJkc5SXJbEZQl6q639HxyFiGyLv13negwgwNcvEFOSnlhqVcClGqjZMXz0vavtWKpCqZP4B+OudqsaKbx7q4dd8FM6UWpP1h6lTlTG7DyNBgpWgfE9BQuOMJ0iE1L8xLoW49+hQh4of0T23jz1l00GHzaZwtaK1fH8QKV8SU2ENQGqMgY/WcJqoBcgq4yi+P5RHKdT2QxTuK8Hph9mFjaEbh5jbkmtuwrl5lzty3bqSHBFILZ+lJcicjKwrfbKowhYEEpK6LFrODIWCr/IhOoXfxVGzg1rwGVoAoEphjEq1S+LhnUciWJoghHfwPZtrDWnpoUSJ7SBLCKcDew8zPXUre3A9NHmd3G+FrDYKybDts8zGCKovJtOIff3U+6h0T3wy4UmKai4RSWR+LOvCFaPgHxGI49PtR5Bqtv9bhcW1LBUzjcv00vLsUQRcOqV7q5Dj6mq+pzm3ReD3J0HgUzFwE2sZPENtUJhTjPsWPI3llQlgcNT0u5knKvT2ERy5OVrSJK963Pl9vRqCGtVcBRPWidRY8EeH6vOFFuzS/FqsFGcLYPK6MGks9W/RNI/aQQN1eTANJgsnuKIT/RAlABgwh+l2X8JKTsH97/8DCakJVw4qPKWccysIYPNc3Ra4szlz/B71Z96FmgOA1xFE2S+j74vAKKwEmguFhdVIvjw16OQY0CIMpaK1rDl9MVfvRVVKHd8mDZI6I8jZr2MulFBpvWCpoUWFMGdfmNTfbvUFEt1Bd6idKFvy+E/chg54K+CdY7Ua4sOdTC3sx2+uIUYAPa40N42f8Nvi6gnmtMQK5+f4anQ7b5HrQ/PkVcrXEiG6VzMcd6s5wuPi0mqJ1P1g0Tqg15uIhu5fIr8YdbdouuWX59yptkPCTEVwkvYSS1UrpH2Zuhm7EHU6o008Iw0EpH2/V0IZxNGrbw8YvzeGBSg3yB2z5rZ5Mpw5NXzf1mtPaUAGQwRfL3gF5u863lqZYtDm4t10mYQ8Mq/SolCUelkiagpxG/MdAo5tA9Bql+8sRUbCxXEl7WGLrW8Skm5ls2y9mJ4pluw6N9vByyGUmHCB6Tr48rFzdEH5OMA4IRrIrXm99p/KamebSksoX1ahi2/Vf19Osq6sENF/sOHJSMxj+BOi4oIjaLlefIM35KsymXCzB3Nr+OLAXWkpjMAmt3ve8cvNYhXS85t+LqtCLhv8h38wmA1Sx+VSKqoMF9cjBlAhXo59flIMaxV5c1PGZc4+lPtWtb9SlK6xE5OKweehe49KZOCIKJxhO6yy9kAJC6CexnbfjYfWz0tFn98SYagZt4V55nqSp+6xtAUSp2CeIjlaBoKWQjD8xLALSxeZJO2HYfgJ/+acwEFKTnDdxYEVzhHOENpc5DD8IPeqUEHMEzzIuR4iTq75XGmPREmltAWq3xVulYHMjTc9svXi4S2ZeA8RzXvTx+wH5hPQ5lu1w9OaAxpqfHbxSRqM5tgEwhc1FoielbBdDpbg5kzHLP3sEi8fYWbBwcb5muWtz2d59ldGLM0XSSCojQC9Jpq4QpEeq0ziK9tTAELziJ/lFf9FpPPN9n+b6WBCgGgLX5yXt9FD+kNTR6rRgXY+YvTpSJLGZtXT0mwV7ejq0AqG59s+2mc1Cn/SwdKYnYTgaofnZDKDbGRVuoeC7i00DOaa2xL1Lpm1UA7pQRbvAh1C7lFc5P/ThdU9KVSFnW3nip6WSBYsKnAV82Q6yPVPWwoWaTsxAmpwMk7fRnZ+UdvmRgpYxr0XQYXa01twCxb38otzXf/BGQ9d+yGUVRjFtKbzPuFvRMIdJ1ZIpXXUedvifPOTay1KPps7DCfv+0BMaDPMQBnDH+WU4tQ4qgG/5PSxS0LVK1Em3+4C1pIe3j/nDmENRrdZA4a23pG2Pdexzi6tXWNq2a/jWyVKtyKnamJj245MegILjDiePkjGUgcCXty1/fRd72b480CWBqLt6zqARI7javJ/Q7bZuLIvZRxCMMq0SACnDq7eFj4Lhf59sg4qtMIay/55tS/lkcebGc/WSA4VeP7/A8R/f3OpCQ1UuBz4KkSDS/HE5TMCXIHOQ9dVGCJCPPAcxWtz8DiNBmOm3UoxQXo3C3on4eznlDd9/NLt1bE6chFXSwxRXf2zMVWymXQh7MCx4iijgMJN/V+zFag3aT8BZKFnPb7cSxJwSEmZRph/xLNctcyDmdOMpJSdYKN6LyRacfb6JohC1oNQVFrgCETWhmXbPfIf+ERCH4w/JycXO433CrRRWXVcGRidhMIZ5xeOzCWjz9uRpDuzKJfQFU71eBMZM5hubHGB65fYCBKJ9DllzdFQSbPtUq2RLPFTUHsIIyt3YIJy+/MR51U1Almf7lGqM5N4tZwU228H1g4lzxO53mul8c7p1T8/uZCM2bB6BOVmMXrunOeD5nvHm1CYP3Sd4iBBtORyEkEMaf+hKy5ZGfexP6xhWzU8LzsvRbIig87WvM0kkMW8plIN/g75HjlEycDhAuf+3QYp7vvb8FxF7gq9t67bkivMPqfj2YacL2Ip3GEJ8nJJZMtFePWDsThDI2BcvLfZPwEK/szxKBjJjz0r9HxU2rebpq4a7KnnayBg5Mr0l+iHTvx5bCfq74NYWcmrwp7kT45OhsA8lmO6I2dBFpq7nUUkGl3mNzGlJJzAWVdKWhQcGJJ19tT8AsKOXE7gED3hzcn89DqgW59mO5xpwdvmZOu5jdQ6kEpT2+sQqa7Y1Lrfa5EqG3hT1vByYuM7K8syo7ftO0qSi8NIO/h/9qY5oJWrS6GaDmKZZGvrSDDsM1A47dy/kavqYEszIeQUlg4VGFWXmP2WqRNRV/Kiee2P0ri9AysQY4gj8cknljNV8kKwIPpZNl4Vk+mx5rCEHFLG5C0CnvEq0UprzObyUaJ+jTHcURf12kqvWYiDCzpU4E8+GqqsEfknyLgWPn7YODJH7Elx9XxkRvoGSg5BM4OwN9mrBdpHmy6OYF/QGKc2tHBxD3B9cxT3auNA7Z0uyUi+erq1DrjIbpEukatpp8P0iIeQNsIDuJWBTz/Ybfw/ZhwPNbd85Y+QqviPPfhEFjYjFqZD1j/zHe68q6cR4ke50f9DYxzzZ1jyAdKYP2vRqTi8yggrtTEcQcXdY6OG6ckhwiV3ygaHLFLY+xrfONaWKHsPW5t5apn6VZV1jIpX+jEZIkDgkAWZAx8skZ/2eVUnElZ4I+gM+ButsUZeCX7qfpXsaI6P76P0bzOP88Yg+68spjxKZRef3qCaeVW3kEF+nSXk0L2fY552uwJDz4GA28U8LOWtALa/kHoA5zdisUndqF6PKmb7y2Xw+TgaY41M/Eqrolv9jka3WRi2WxRXj9LvmsUPUydgKltww9G3dnqEA4IuPDwLWB73oENQA5tz4FZ1IIZg3ccf2Zl12mrdSUTo7D5G+W7o2NQERSdby3T75CjAcOkAzKxngF7dhVtEBAWLdb4wsnhvE//R0qVKIWCm4iQ7SJDsejgHeYNMhZQh8EKGDQjBwA8MT9tgHsT/W1ycowsWoWleZ0F9KkGCOLVeUmFkJCi8Fzb980fF/LwwR3mvC9UB0ztDK7A5tsUA9/iczy+nAQz4DJatowGAEHzgr3hsJl1InH7dXdpdi53CstfqUf58DfQI3Ax5pJqvLVr6J5tZJe8ZkmcZAoqrDveizHlwZkE3voTB9HbwTDXr7KeEv0xB6muFrta07KAgrMS15EBSiGVKsguw4/UYUMOtF/Sh4nJVF0F6cPkFldBZnW5c2oKcy0dtMrtspdgBkXCDjAKp6bJoFocxmiwlGrkBUhN55H7dlyAyoG1ddAcAL8861QCSEbldHbBLKIKblGroTQzFMrX1XGwU/UYyGrkGf+1u/rYq0lJt3Nm6ozQGszpnQ5Bi4UrLyScY5vLYuYvzNEoIM0vrQ2T75TneK06CP4NlyoRqzuBm50ufCnTpWbH/NNmjB1M1w4bgU0QAuQQISqCqSSyROE/klQCde7vB9ogHBgestE/+wWOC7zJxleraQCGYwtQTzuSxJyiQzKcVxDSgcBI8As1Ksf/g1kpUbeOQjdnCVgERRYSOQzuLt4KBMkiplpWf0TeV7/05puNKijIpLoiQQYWYMLMaUBSQyjdQfF+TNJSeUfX86yI68iXtkwD1M46oDmzc0T9Yk5HfCEYKU8jfe679JoKg3F4axRHzi7M9VUi8gP03ovKzXicl/ajNQUXr951aqWHSDYyiRAhLU+ZwJC1l1ku71YrHFrkBi/tZEjhdbFSq2Oiu9118S9zMEKvO7Q96bg7BJztH2aygOW5TiTwM1Vm+Z5/KhSM4K70HVQZoTn8xu7wJeWLwteV7ZQrlE19WT2dpHnrqgiLvpOzZP++2N1ls3vulvrfDvF+GPlSqiCPr5qJ/m1liqkfl+f6ataFtljNnRXxrFu0MuoKTmensfrTT/RcFAcCZe7NmA0UqAQTTPlazmUMDapSYkyQ8lWlF5AoxpsfiwD82MxCbpfCVBSundpwfAQQQgGVQ+HVUhgsus9QIqTchOzZxxGfJ5Wk9GJCNKvzDz03svzwb1q7R3r6RBakU52jl/diFbPXVwqRC/TeiDSJGSqyBhWXOmpjO8NlrLVV4BhNhHTtB6Z0wukA0aixVkBzozTvmgEk0b2NLCy4a0CQ0pqhLsviq+/NSH5l2rzfQZxVllgo7mcv+FCKYQRbIXjNjfeSkgq+pGq7+qbUhL0c2cPLiIZ5sy7AQNLixBbdeowQCqYJZNUxy8Bt7zfo0Gbdjnt3CoaUFiPk0WjLu45/FvpQgL3LE8ML7SbAmto1LadKhK9WsgC7sBa0PR8SeT80tUu/Yz/hdiHfZgYpArE2K8J7ZZFF2W9+9+DVFNeCJZduqNoj73/rZGxtxQcFu0qAGkbVbP8FKV9VX16RGexD6En5Sx89MjdkGDIdAcnSUFkXjRh62ZLine truncated
U0VOQwGE6gnFffEC/Dv8DbPj9gXzCNp4DSPL7X9/2NPC3i0bN8rPSi2rJ11aKFhGw6Y5eM6b8K4kShUQWLdEM2KSSBwkW90P18Xqv/W+ffeHPf+f+M9uYFheUeHqI9UytwiDNsnurdFtB69qGIlx2svo0CgoWmOPGloXxZckNqzgJsvukbIsLOfDtP/eFYRtzctXOwYLPwQ7uxwpQ7vbgxEp+fomem4tNPh2VdRuFXWdQ6XCVUjilAGMx7JCdAtvfYTkAnws1DDIcR5q9rMF/TJNWIJwMoQqs/FGCuPbGfAvX1jINqkY09ez8As+lGDeL3a45KPubcYNHSXHob0RLartkHfBoUDlTxP45rGpY1cwrnBmydDXpNLWo/+NtV+KeDKgLYtEndbuUIIV2V4zRJRLsdSaybrwkMNDxihXMFaUDE/ebezvBYcf+5UcxsH6WIaEGLn/LvwQxjZaLFHTF1tCHz6U15dJYKB0IwGU1eebt9slJM49c3Y213mPAvhiJkZhRispeExo+cvdTCxQzciUr8+vy+/5h+30ZYpeRGVP072uQYgmS3UIMDbcJNGhrHaES1SPB2YI934unEVNvwNZtOKsDuT18d7DI9nzLaOORWXd6F4xv7r+/sNzRz1IUhVQ9gNUejKJd6G92SyBvepevX+DCGFNuR2aE3cMmfzgxAK+/Nsmt0aMaSf5GwNX4xG1uAHMPyopYfLHvvMrQ6HiZDk0lcxoHclqRMgLQ/fdMFUtbOOSRArwE/aHPbwHE45JSKWZZHkU1JGQtUmPSAH55lpxukSt3gfnl0DZY0ApCQAcMTUE6HNSWRdeXROXCJc6UibjrlU4mBjbb6RDGQfs6X4NZ2WSuX7Gj0W35z7++LCqZ7cYRmIYXweaJc2rxnmZim0bUnJkzCjAS3sfUMakTFlJIzDnxZRhKGWsPukyl39axdQ6zTjj5hAkqTnlajNU7flHHXe80rwNzWlNhOERRB6su2wyrHcI8rgLFmVfSivQ9zw00wi5soqXjaYgGoXDxkzd9+vtMScfXcdJl5LtEWUrvKcP/Q+FpMnxf66SnpwOEHYL61ciAMw3zggJvAo9xyd9g9DySbaRgqVZBGPEI7+s7bTSLWv4lXcgIwAnFFchvK2wKxb+r5Dn6lcZPghWuLBYHhnloPmheCog5go19ANK9ik3xjmo8PFNUxdGPGTS/QCmYzrPpPhyCi5m41kYupPoPbH3gcTCQhQwQJ/A/nS9qnr9CkDsRXD4gpjEyRaMx0Ad3xxQ/aQFnZzqjo0RwpKs4L6qbXBJRRoZAMtXL+J3vLh9EBUfWig71poLLIDzsGS2m3D71ggPQBFlxxelv80IJ9MgEtFga9CWc/NsLark8dTzZyZnOOzvT0ikxzuY5tadrXiVZbunTNP+Alzf6mNPIuTZT1FGC7S3deLQz8i0mqGFRV9JIFzq1/Z3HkmK5HVWrRHZXCkcyueeF++N5rCHnIVJEsXLKLhr4e7OBLEIq38qv4b3NmTP46WvgGOeuGbNRhfHbh1+vfk2buGqdS7hdgNBTaNpaEaOsO3Uhq1y4HFN73861mlLUF0xr5GYCLjoQIleD0RiPF3oNw0GdOfJGmRXzV/u//XSU9DYi3yjyv+aqA5XoWduBFS6dBUDQN4k006ThqpOAMu8tXNvGQVsLv/ORifyWyZYfJFxkG3uB4qiAr1sMNhpzWlhOlb2JjrraRzQeHF9bp/DfrE5LcjMPl4XbhbcvxgyLtWAHjZRWjeglmJFdWXhgynMfyn2Zt4AShRY8Ou9CMOO/iy+ddiREje4ExLrl7bq6hboPi3BDuX95QPRKEBbtCwoLikTK5nDP43CaIGDpMu/i03f05UrGC6NNqblidP29XvCKXpY3ZqoX3yVG5p4nstRbtr+sacqKl0JguXwiG0xMEDS3VVnYkV0W+Kk/H0HkT2MfsJr6ppqjWY1l8mzmoqLkC9YluOskzEc7bWOmUOi7vbbghheQDmT0YmNFIJ+eqz4raXW2SkyTCQZKZuGlmrn7o6ApXamwzpacjYxe7/72xvMPUBWYYmwMRpK745ebNwVihtnks6cn/XWFKUz0wtrWSUYY+tEU/qrOQ7L8gznM53p0mjkVeWRMzqnBydwOdBPkjHtLU784u4BSTm3PgglLYJBM9jfSMFBh79srn99J7GqyBaT2QDZE/PNwOybcd+ap+l2jDV442UuqWSwMEV8xs5v/Bk/5kDnW7A2bN0xI6rdpfibJLs3c9i8M0+XM1yNlesPJAR5nDA/v19sP+wKYZSMO5jIrQLLCKA3Tsq07ujeAbOd62wGIJU4vjHfHAO8I2Hw38HbAM2SVzG6g8zMzEqm36Rl027Fdons3EBwqtMJ6hrx3nHvR96JOwJ866KmlPqT+vjoCh+2HYNLmsS4ipzAUkMYqVnPvnGICDPXX/WkL+0buKXu70jcaW+5Mys/ke41/IH8OJUf6ztLKclO4bBwtfUfE0vxXotj+6x8QNBEsdZl+OHXYemQ+fKd7jhqSTarJRx+cYtwOSUVzEWDxDt+zUp4EF06hfW5kyeY/0OW2t36rx9VULfG78ELo/zH2TXWQWgS2wEdmeXYJ5lzDtPW+XFxSRnYxr+qpceFXAVeMas9sFyG0hG8ey6pth6dPudgcD3fvfzobzaLtMgHiuCSEwHwwQptQ/YprDc2MV20UDW2IlG1yS9D3WgDuRBgQafJegjsDAPFvcpuBwf5JFdFRVBTEUv85GqZ91MNME2vPgo46amuNK3+OerpBitXChDDIw5RCcHIGdXu1+xqshgxvv0xahqRzYRmZr0mLg0jHoSYD3dyzX00//0ApefiRkKgw0yWfgJywQabrXv/NPrgaaK5+d6bwl7BnBAJfNHCDJ5R5CdbWRdkTw1XhD2QADZtURJ9yvnUDX1G2ftLZ/hmnlXGu1Kyin4snhMsnxwhX7mTaFUanY4u9QOGU+jUzbDqqDCHOfPWNDXYhaz4igr34MtAry+PM1LUHIV4UKM6ckI7q2k82LrG1UzfzjDUqtaXaTMeNEI72Gj8D+/jQPfFZeWvO3zvFYlRjSSGy3oIJnXz54TJLb2vpxFvjPDoQZ51V4VZm480b41f3EoX+iWC3Qejf6H0AGut+TSiO7mDStG9MqNApYS0DFubDokwvHNouZRRA2N5RMAnRkYWrLmvZ2MyVPpyU4SS5uiXY2EaV2Ld3RTmf3vGH3vR8I6fzcmcgGw0pkaTqeH/Z0p1Tn1hH9MqfEWMdFCCtOCZm2D9xa/OYI/0ZjkXQxYLjcPhZkMX7XyU/vuuhGkrPbAOWfO03qwx6b/1LCbXa3nM4zgdLR4oBc0wm2q1oHN2ahTT1G2kTxAqz+zeAn7WI2g7Di6X0lJ1b131MmO8Y9fgmXTiSO6FXmMQmddr6JaBHPl/0oUdA3+/m2smVuYuxtBhYVV4BlDRexfd5vm+fnqY1A3tAKJnI0cMzy86idcAIjnobpcJmnqwmIQ3rJGvz5+azOLPtckxeTyaoe2654lU4OBT3k2+tm+vYVJPDSobCrsxWIht1ij0Z6NvLjjy+yx+EYgNLNFPZ4Q1xEb0MYH3R4dyCC7zAlzzzxiofey1hZGvplsttyYlZVhKOuMuZbCtUmj90p6k85UeDhme+c6qVdz/hUhbnd8Lo4acV1HIWoj794XnsOSKME5ITGK8tx692eEbc9C+zEbycZ+u9zAcFhL8+5H1F0R4H+ByLArSHp48oEupL3fye4uBXH+m1cMXlc8lE0UzzD9lICvKWNlCyWfhSD8CVGtshVu7hwhRbgJUvkzxNSyhDhvk3x6XZtifBH6dYekmWJrjSPOWFjAJe349/fALLPJRobmyDywS0pZ/tWaGlezfI6q18w8ldvJulRn36rr7yQonNq8QZbtvj24QnIWgBoAEW4l3w+0TDcJsmKSQ7tg0oGfmgtcpULH8gry01h50abpI17enIY7UVt1+gvJKAg2Foyt4S+v0yBMZWA7C7VCh0LZJmHbHmR6qkB90McDyq/zp3Bc5PqVFaltyujbZP8XMN3pM9714hyqhA0F37ox2m7moIRB1XflyIB3D1tOUvLE16djurt6ew8GzeFDIMqph+h97Ufb8pgfVCzBfatCG0iDwBe2ETEkNLwRUDN/uVwl0Pr6pbILVEaOAS1xPebIK89eDaX6mlS/m0aWWaqt/xGncGPTVlSNWn6V9sB2WVgGz1IJqS2i0A/YwA0Qi6dW37BpS2rpQdD2BHniImTeSMQe6oJDZSOBf3iAAZnExl8PcAgEB/Dwc+RrQUHYtSIk5BJCtTFjEXcY/08lUix9C3o0uIGRIDTdTwN4smBokFawcSo3OPjFAiPZcLU0K0ppfpF7/AkWqYIV5weLd9ElFT6ajcNjdqm2PXrhtEu72TmiKKfioZHfanlB3PUjsOPm1+s7X5AwWWhJerScXfHpFPhX4GFBPe3GVGbZ6yWfpG4rjd166HBDFbRbRB0Pbe+AiQNJHBLcErss6mTOVMdy2uAKVyHStKWRPR1cMHy/pcLKsxYRKtBu4I0KWcdHLMtZ02f4wbapiKVAn2W8tN8J/m7f7yBvvrHFdj3eOlE6F8LBVtMNL3A5kCKQa4BBhMF0gmmWc/idHKLPu73hELAHmr4uI37ehgX5prXfB/wJ6jqPH+nu5El5MGGy8SYAQrQDL6tzooXqQoSO1txwMeCY/KTRMXAGdWLJGUiXzXLykZrEx6b3WvHhC9PcN7JGGmNgZ6oXNCzDPnan4UDfFyMW/PGFgoUBptZ2rLbkjeBVe/GQ9xTOuiOVcr1CpVPGv4FQCeKQmeH+08R7zTvuQA9iqngLE0o3g0WLioaMYVBkKFva3xw0TOPMv7Sj+NGPqeilr6QkcoVSxxf3H+wVBTPJForIutmbCOjvsrms7Vo6yaALIfeE4P9QvBthQ1lI52GbtvUhxSmUv7OZcw/QgYWg4R+MKkZxp8/Ombst1wUjIqraX2hac7iwdk81uroMLine truncated
+1 -1
View File
@@ -15,7 +15,7 @@ background processes.** Optional, and unrelated to the workflow itself.
On Pro / Max / Teams accounts, where rate limits are available:
```
╭───╮ Opus 5 / high │ plan2code │ feature/PCWEB-11702-pathfinder │ +12 -3
╭───╮ Opus 5 / high │ plan2code │ feature/pathfinder-github-iss │ +12 -3
│ ★ │ ┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
╰┬─┬╯ 3h 5m ($4.62) │ ▰▰▰▰▰▱▱▱▱▱▱▱ 42% (84K) │ 5h: 28% · 7d: 61%
```
+25 -1
View File
@@ -523,6 +523,19 @@ send never holds up a question.
A reply that lands while you are on another tab puts a dot on **Ask** and
chimes once (if sounds are on).
### When an update is out
When a newer Plan2Code release is out, the dashboard shows an **UPDATE
AVAILABLE** banner at the top. Click it for the details: the version you
have, the new one (linked to its Releases page) and the exact command that
updates you, with a Copy button. **×** hides the banner for this session; the
next dashboard shows it again until you update.
The check uses your own git login to read the repo's release tags, once an
hour at most. If git cannot reach the repo (no git, no access, offline), you
simply see no banner, and nothing waits on it. The version in Help always
links to the Releases page.
### Keyboard
| Key | Does |
@@ -538,7 +551,7 @@ keyboard-only navigation work.
## Models in User Preferences
The `plan2code` launcher's model menu comes from `models.json`, which every install overwrites with the authors' curated list. **User Preferences → Models** (Claude and Devin tabs) lets you add a model that came out before Plan2Code was updated; additions are kept in `~/.plan2code/models.json`, and **Reset to default** removes them. Restart `plan2code` to see a change. You can always run `plan2code --model <id>`, or switch model inside your agent before running a skill. Devin ids ending `-xhigh` or `-max` are refused.
The `plan2code` launcher's model menu comes from `models.json`, which every install overwrites with the authors' curated list. **User Preferences → Models** (Claude and Devin tabs) lets you add a model that came out before Plan2Code was updated; additions are kept in `~/.plan2code/models.json`, and **Reset to default** removes them. Restart `plan2code` to see a change. You can always run `plan2code --model <id>`, or switch model inside your agent before running a skill. Devin ids ending `-xhigh` or `-max` are refused. Maintainers refresh the curated list with the repo-local `/plan2code-model-update` skill, which shows a diff and changes only what they approve.
---
@@ -629,6 +642,17 @@ Your `looks.json` and the `console-dir` pointer are never touched, and neither
is the session being opened. Nothing of value goes with them: the page is
never the record, `specs/` in your project is.
**Or clean up on demand.** *User Preferences → Cleanup* → **Find files to
clean up** lists, with sizes, everything in `~/.plan2code/` that is not
needed: sessions untouched for 30 days (never the one you are in), anything at
the top of `~/.plan2code/console/` other than `sessions/`, `looks.json`,
`workspaces.json`, `console-dir` and `update-check.json`, and anything at the top of `~/.plan2code/` other than
`console/`, `bin/`, `launcher.json` and `models.json`. A stray is listed once
it has sat untouched for an hour, so a lock or temp file another session is
writing right now is never caught. **Delete these** removes
that list and nothing else. A console running from another home
(`PLAN2CODE_CONSOLE_HOME`) only ever looks inside that home.
---
## Security
+1 -1
View File
@@ -92,4 +92,4 @@ When you make a mistake, get corrected, or discover something about this codebas
- Sync upstream only through `/sync-repo`, and verify its baseline against the real tree before porting: an earlier sync silently skipped a whole upstream release (the `3-implement-review` skill) while the recorded version froze. Update the baseline with `.claude/skills/sync-repo/set-synced.mjs`, never with a shell pipe over the decrypted body.
- After a sync merge, run `npm test` before trusting a "clean" file: when upstream and plan2code fixed the same bug, `git merge-file` keeps both copies without a conflict (a sync once left `let pattern` declared twice in `app.js`, caught only by `parse-check`).
- When extracting upstream files in Git Bash, run `git show <ref>:<path>` with `MSYS_NO_PATHCONV=1` and `C:/` style paths (never `/c/`): path conversion rewrites `origin/main:.readme/x.md` into `origin\main;.readme\x.md`, the show fails, and the merge silently runs against an empty "theirs". Check every extracted file is non-empty before merging.
- After a sync, grep for a bare `Smarsh/` owner slug as well as `github.com/smarsh/...` URLs: the rebrand map only rewrites URLs, so `gh --repo Smarsh/smarsh2code` became `Smarsh/plan2code` in `feedback-payload.mjs` (and its test) until it was fixed by hand to `jparkerweb/plan2code`.
- After a sync, grep the result for the upstream owner slug and company name in any case (the `/sync-repo` body lists them): the rebrand map only rewrites URLs, so a bare owner slug once slipped through into `feedback-payload.mjs` (and its test) until it was fixed by hand to `jparkerweb/plan2code`. No upstream name may appear in plain text anywhere in this repo.
+36 -6
View File
@@ -2,6 +2,42 @@
All notable changes to Plan2Code will be documented in this file.
## v2.4.2
### ✨ Added
- **web-console**: the Questions and Ask tabs show a small spinner left of their name while Plan2Code is on it. Questions (Dashboard on the dashboard) spins from Send until the answers are picked up, the same wait as *Sent. Waiting for Plan2Code.*; Ask spins while a question the agent picked up has no answer yet, exactly when the conversation's own ring does. Neither turns once the agent goes quiet or offline, so a dead session never reads as a slow one.
- **web-console**: **User Preferences → Cleanup**, above Models. **Find files to clean up** lists, with sizes, what `~/.plan2code` does not need: sessions untouched for 30 days (never the one serving the page), anything at the top of `~/.plan2code/console/` but `sessions/`, `looks.json`, `workspaces.json`, `console-dir` and `update-check.json`, and anything at the top of `~/.plan2code/` but `console/`, `bin/`, `launcher.json` and `models.json`. A stray is listed only after an hour untouched (`STRAY_GRACE_MS`), so a held lock or a temp file mid-rename never is. **Delete these** removes exactly that list and reports what went and the space freed. The server builds the list (`POST /cleanup`, `cleanupFindings()` in `lib.mjs`), sends no paths to the page, and on delete re-scans and removes only ids still found (`removeCleanup()`), unlinking symlinks without following them. A console running from `PLAN2CODE_CONSOLE_HOME` never looks outside that home. Help's User Preferences topic describes it.
- **web-console**: the dashboard shows an **UPDATE AVAILABLE · v<latest>** banner when a newer release is out. The console server finds the newest `vX.Y.Z` tag with `git ls-remote --tags` when it starts (no shell, prompts off, a 10 s limit, never waited on), caches the answer for an hour in `~/.plan2code/console/update-check.json`, and adds `update` to the state frame only when that release is newer. The banner opens a dialog with both versions, a Releases link and the update command with Copy; × hides it for that session. `GET /version` also returns `latest`, and the version in Help links to the Releases page.
- **launcher**: `plan2code` opens with a colored Planny banner and a plain-English intro, then the agent menu with cyan numbers, a `(last used)` marker on the remembered pick and a green default. With one CLI installed, or a `--cli` pick, it prints `Opening with <CLI>…` instead. The model menu, the folder prompt and every `plan2code:` error get the same styling. Color is used only on a terminal with `NO_COLOR` unset, so piped runs print plain text and no banner.
- **maintainer**: a repo-local `/plan2code-model-update` skill (`.claude/skills/`, never installed) refreshes `src/launcher/models.json` from `devin models list` and Claude Code's documented model aliases. It shows a diff, applies only the changes the maintainer approves, checks the file against the launcher's rules, runs `npm test` and never commits.
- **tests**: `scripts/test-web-console.mjs` covers Cleanup, the update check and the note thread; `scripts/test-launcher.mjs` covers the banner and color handling.
### 🔧 Changed
- **document**: `overview.md` puts the Phase Checklist and Parallel Execution Groups directly under the Summary, ahead of the Tech Stack, Architecture, Risks and Success Criteria, so the phases are found without scrolling. Every script finds these sections by heading, so specs written in the old order keep working.
- **web-console**: while a build runs, the waiting screen's pointer to the tasks list is now clickable. **Task** and the tab's own name (say **Phase 6 tasks**) show bold in the highlight color, and either one opens that phase's tasks tab.
- **web-console**: the session meter counts a build while it runs instead of only once the phase is approved. `console.mjs` writes a `progress` ledger entry whenever an Implement or Implement + Review post raises `headline.cleared`, and the build's row (*Implement + Review: 9 tasks built so far*) scores one point per 3 tasks done. The phase's final `run` takes that row over in place, so nothing counts twice and the meter never drops. A second phase in the same run starts its own count once its headline is back at `cleared: 0`.
- **web-console**: the **UPDATE AVAILABLE** banner and **Send to Plan2Code** (while enabled) carry a soft glow in the picked highlight color; with reduced motion Send's pulse stops and the glow stays.
- **web-console**: a request body over the size cap now gets `413 too large` from every JSON route instead of a connection reset or a `400`.
### 🐛 Fixed
- **web-console**: Implement + Review's built-in review no longer scores twice on the session meter. Its `review` run now scores the phase's 1-point review bonus as the review starts (not a standalone Review's 2), and the phase's final `run` leaves that point out. A 17-task phase now ends at 7 points, not 9. The breakdown also stops repeating the unit in "Code review run: review".
- **web-console**: Send no longer stays disabled when an agent posts a question mid-build while still marked `working` (seen on Implement + Review, where the question said "I'm carrying on while you decide"). Once an open question has an answer or a note staged, Send unlocks at once with "Still working · it reads this next", instead of waiting out the agent's `quietMinutes` (up to an hour); the server holds the send until the agent next looks. `building.md` now says a question stops the build: set `waiting` in the same post as the question and wait, never keep working with a question open.
- **web-console**: **Notes on this** showed the agent's replies as empty "Plan2Code" bubbles and dropped the person's own notes once they were picked up. The server now writes every note into the item's `thread` as it arrives, `post` lifts `from` / `role` and `md` / `body` / `content` into `{ who, text }` (and drops an echoed copy of the person's note), and an entry with no text is rejected with exit 3. Older `{ from, md }` entries still render. `console.md` gains a **Replying to a note** section.
- **web-console**: dropped the `comments` list on docs, which `post` appended and time-stamped but nothing ever displayed.
- **web-console**: a dashboard launch could strand the hand-off when the agent called a skill-invocation tool on the picked skill instead of reading its `SKILL.md` (every skill below the dashboard ships `disable-model-invocation: true`). `plan2code.md` and `console.md` now say to open the next skill's file with a file-read tool.
- **web-console**: the waiting pane pointed Document and other skills with no task list at a tasks tab that never exists there. The pointer now appears only when a build's `phase` or a quick task's `tasks` tab is posted. The nav tab spinner also gets its 7px gap back from the tab's name.
- **web-console**: skipping a question dropped a note already typed for it; the note now goes with the skip as `skip; <note>`. Ticking a checklist step after a skip now ends the skip instead of still sending `skip`.
- **web-console**: reconnecting cleared every banner, including a warning that arrived while offline; it now clears only the *Lost contact* banner. An open Overview tab now refreshes during a build.
- **web-console**: a `409` on Home, Stop or **Write the brief** now marks the page busy the way Send does, and the brief dialog says why it could not go.
- **web-console**: arrowing through a menu question kept dropping keyboard focus to the page body; menu radios now carry stable ids, a `value` and an `aria-label`. `@` mentions typed with a capital letter now match, and the attachment-limit banner uses `MAX_ATTACHMENTS` / `CHAT_MAX_ATTACHMENTS` instead of a hard-coded 5.
### 📚 Documentation
- **web console guide**: new *When an update is out* section, Cleanup under the session cleanup notes, and a pointer to `/plan2code-model-update` for the curated model list.
## v2.4.1
### ✨ Added
@@ -19,7 +55,6 @@ All notable changes to Plan2Code will be documented in this file.
- **commit-msg.mjs**, **review-scope.mjs**, **agents-md.mjs**, **agent-files.mjs**, **handoff-path.mjs**: the commit command from the branch's ticket, Review's git scope and doc share, AGENTS.md's structure and orphans, the AI agent file sync, and the handoff's timestamped path and git ignore check.
- **tests**: `scripts/test-skill-scripts.mjs` and `scripts/test-script-<skill>.mjs`, run by `npm test` against the built `skills/` tree. One test fails if a `SKILL.md` names a script its skill does not ship.
- **web console**: the Workspace dialog's folders are remembered across console sessions, in `~/.plan2code/console/workspaces.json` beside `looks.json` (never in the project), keyed by the folder a session runs in and then by spec. Every change is saved. *Start from scratch* on the dashboard shows the project's list; picking a spec loads its own, which starts as a copy of the project's and is separate after that, and a spec created mid-run takes the list in force with it. The dialog says whose list it is. New `console.mjs forget --spec specs/<name>`, which Finalize's Spec Cleanup runs after archiving a spec.
- **web-console**: the Questions and Ask tabs show a small spinner left of their name while Plan2Code is on it. Questions (Dashboard on the dashboard) spins from Send until the answers are picked up, the same wait as *Sent. Waiting for Plan2Code.*; Ask spins while a question the agent picked up has no answer yet, exactly when the conversation's own ring does. Neither turns once the agent goes quiet or offline, so a dead session never reads as a slow one.
### 🔧 Changed
@@ -38,7 +73,6 @@ All notable changes to Plan2Code will be documented in this file.
- **finalize**: `feedback-payload.mjs` counts the same phase files `specs.mjs` does, `submit` refuses an oversize URL when `gh` is unavailable (`oversize`), and a bare spec name present in both `specs/` and `specs--completed/` is refused as ambiguous.
- Every script was checked against real specs and Pathfinder maps in other repositories and by four independent reviews; each issue found has a regression test.
- **document**: `overview.md` puts the Phase Checklist and Parallel Execution Groups directly under the Summary, ahead of the Tech Stack, Architecture, Risks and Success Criteria, so the phases are found without scrolling. Every script finds these sections by heading, so specs written in the old order keep working.
- **install.js**: the closing message beside Planny now names the dashboard first: `plan2code` from any project, or `/plan2code` in your agent when the command could not be installed. The docs link moves to the line under it.
- **web-console**: User Preferences opens from a gear button instead of the three swatches, and the default highlight color is now ocean blue instead of rust.
- **web-console**: the dashboard rail marks the suggested next step with a small dot, since the center pane's Suggested pill can scroll out of view. Send pulses only while it is the primary button.
@@ -48,15 +82,11 @@ All notable changes to Plan2Code will be documented in this file.
- **Windows**: the folder picker (the launcher's desktop shortcut and the Workspace **Browse…** button) now opens centred and in front of other windows instead of behind the terminal.
- **Launcher**: before asking which CLI to use, `plan2code` says what it is about to do and that running `/plan2code` inside your agent works too.
- **web-console**: the session meter now weighs the work a session actually did instead of a flat amount per step. A built phase scores one point per 3 tasks it completed (rounded up), plus 1 for Implement + Review, so a twelve-task phase weighs four times a three-task one; the agent reports the count as `run.tasks`. Every 2 questions you answer on the page add a point to the skill you answered them in, so a long back-and-forth in Plan or Pathfinder counts for more than a short one. Each Pathfinder research question adds 1 through a new `pathfinder-research` event, since research fills the context with nobody answering anything. The levels move to match: yellow from 5 points, red from 10, and the ring is full at 15.
- **web-console**: while a build runs, the waiting screen's pointer to the tasks list is now clickable. **Task** and the tab's own name (say **Phase 6 tasks**) show bold in the highlight color, and either one opens that phase's tasks tab.
- **web-console**: the session meter counts a build while it runs instead of only once the phase is approved. `console.mjs` writes a `progress` ledger entry whenever an Implement or Implement + Review post raises `headline.cleared`, and the build's row (*Implement + Review: 9 tasks built so far*) scores one point per 3 tasks done. The phase's final `run` takes that row over in place, so nothing counts twice and the meter never drops. A second phase in the same run starts its own count once its headline is back at `cleared: 0`.
### 🐛 Fixed
- **web-console**: Implement + Review's built-in review no longer scores twice on the session meter. Its `review` run now scores the phase's 1-point review bonus as the review starts (not a standalone Review's 2), and the phase's final `run` leaves that point out. A 17-task phase now ends at 7 points, not 9. The breakdown also stops repeating the unit in "Code review run: review".
- **pathfinder**: charting no longer ends the session, or shows "Session ended" in the web console, while its research subagents are still running. They live in the terminal's process, so closing it on a "done" page killed them mid-write. The session now waits for every one (the page shows a running count), each subagent ends `## Evidence` with a `**Research complete:**` line, and Work Step 2 re-fires any research question missing it. `console.md` makes the same rule general: no `finish` while any subagent or background job is still out.
- **web-console**: reusing a settled question id for a different kind of question (say a multi-select turned confirm) now opens it as a new question instead of keeping the old answer.
- **web-console**: Send no longer stays disabled when an agent posts a question mid-build while still marked `working` (seen on Implement + Review, where the question said "I'm carrying on while you decide"). Once an open question has an answer or a note staged, Send unlocks at once with "Still working · it reads this next", instead of waiting out the agent's `quietMinutes` (up to an hour); the server holds the send until the agent next looks. `building.md` now says a question stops the build: set `waiting` in the same post as the question and wait, never keep working with a question open.
### 📚 Documentation
+2 -2
View File
@@ -3,7 +3,7 @@
**A spec-driven workflow for AI coding agents.**
<img src="docs/banner.jpg" alt="Plan2Code: plan and build with your AI agent, on one page. Planny, the mascot, acts out the five steps: Pathfinder, Plan, Document, Implement and Finalize." data="object-fit:contain;" style="max-width:1024px;">
<img src="docs/banner.jpg" alt="banner" data="object-fit:contain;" style="max-width:1024px;">
You work through Plan2Code on a page in your browser. The dashboard lists every step as a card, and
each step's questions, progress and sign-offs arrive on that same page while your agent does the
@@ -13,7 +13,7 @@ the next engineer all start from the same specs.
One command opens it, every step is a card, and the terminal is always there if you prefer it.
Version 2.4.1 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
Version 2.4.2 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
---
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "plan2code",
"version": "2.4.1",
"version": "2.4.2",
"private": true,
"bin": {
"plan2code-install": "./install.js"
+3
View File
@@ -40,6 +40,9 @@ const CWD = path.resolve(args.cwd || ROOT);
const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-bench-"));
const ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NO_BROWSER: "1" };
// A fresh cached failure: the boot-time release check stays off the network,
// so a slow GitHub never colours the timings.
fs.writeFileSync(path.join(HOME, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest: null }));
function findBrowser() {
if (args.browser === "none") return null;
+32
View File
@@ -174,3 +174,35 @@ test("launcher: the CLI's non-zero exit code is passed through", (t) => {
assert.equal(result.status, 7, result.stderr);
assert.notEqual(box.argsOf("claude"), null);
});
test("launcher: renderBanner draws Planny and the name, colored only through paint", () => {
const { renderBanner, paint } = require(LAUNCHER);
const plain = renderBanner(paint(false));
assert.doesNotMatch(plain, /\x1b/);
for (const part of ["╭───╮", "╰┬─┬╯", "★", "Plan2Code"]) assert.ok(plain.includes(part), part);
assert.ok(plain.split("\n").length >= 4);
const colored = renderBanner(paint(true));
assert.ok(colored.includes("\x1b["));
assert.ok(colored.includes("\x1b[0m"));
});
test("launcher: paint wraps text in the escape codes only when color is on", () => {
const { paint } = require(LAUNCHER);
assert.equal(paint(false).red("x"), "x");
assert.equal(paint(true).red("x"), "\x1b[31mx\x1b[0m");
});
test("launcher: a piped run prints no escape codes, with or without NO_COLOR", (t) => {
const box = sandbox(["claude"]);
t.after(box.cleanup);
const none = sandbox([]);
t.after(none.cleanup);
for (const env of [{}, { NO_COLOR: "1" }]) {
const runs = [box.run([], env), box.run(["--cli", "bogus"], env), none.run([], env)];
assert.deepEqual(runs.map((r) => r.status), [0, 2, 127]);
for (const r of runs) {
assert.doesNotMatch(r.stdout, /\x1b/);
assert.doesNotMatch(r.stderr, /\x1b/);
}
}
});
+8 -8
View File
@@ -230,16 +230,16 @@ test("specs archive: dry-run, move, refuse to clobber", () => {
test("commit-msg: ticket from the branch, the three -m flags, subject rules", () => {
const repo = tmp("commit");
const g = gitInit(repo, "feature/PCWEB-10968-export-csv");
const g = gitInit(repo, "feature/ABC-10968-export-csv");
write(repo, "a.txt", "a");
g("add", "-A");
g("commit", "-q", "-m", "init");
const C = (...a) => runScript("plan2code-review", "commit-msg.mjs", a, { cwd: repo });
const ok = C("--subject", "Add the export endpoint", "--add-all");
assert.equal(ok.code, 0, ok.stderr);
assert.equal(ok.json.ticket, "PCWEB-10968");
assert.equal(ok.json.command, 'git add -A && git commit -m "Add the export endpoint" -m "PCWEB-10968" -m "AI Assisted"');
assert.equal(ok.json.message, "Add the export endpoint\n\nPCWEB-10968\nAI Assisted");
assert.equal(ok.json.ticket, "ABC-10968");
assert.equal(ok.json.command, 'git add -A && git commit -m "Add the export endpoint" -m "ABC-10968" -m "AI Assisted"');
assert.equal(ok.json.message, "Add the export endpoint\n\nABC-10968\nAI Assisted");
assert.equal(C("--subject", "x".repeat(101)).code, 4);
assert.equal(C("--subject", 'say "hi"').code, 4);
assert.equal(C("--subject", "costs $5").code, 4);
@@ -425,9 +425,9 @@ test("specs: --set cannot override computed fields; empty overview exists; uncou
test("commit-msg: a repo with no commits, stray arguments, and paths quoted for every shell", () => {
const repo = tmp("commit2");
gitInit(repo, "feature/PCWEB-12-x");
gitInit(repo, "feature/ABC-12-x");
const C = (...a) => runScript("plan2code-review", "commit-msg.mjs", a, { cwd: repo });
assert.equal(C("--subject", "Add x").json.ticket, "PCWEB-12", "no commits yet");
assert.equal(C("--subject", "Add x").json.ticket, "ABC-12", "no commits yet");
const stray = C("--subject", "Fix", "--files", "a.js", "b.js");
assert.equal(stray.code, 2);
assert.equal(stray.json.error, "stray-argument");
@@ -572,12 +572,12 @@ test("specs: an em dash in a group range expands like a hyphen", () => {
test("commit-msg: @ and - paths are quoted, git add ends its options, risky subjects are refused, add and commit apart", () => {
const repo = tmp("commit3");
gitInit(repo, "feature/PCWEB-12-x");
gitInit(repo, "feature/ABC-12-x");
const C = (...a) => runScript("plan2code-review", "commit-msg.mjs", a, { cwd: repo });
const files = C("--subject", "Fix", "--files", "@types/x.d.ts", "--files", "-weird.md", "--files", "src/a@b.js");
assert.equal(files.code, 0, files.stderr);
assert.equal(files.json.add, "git add -- '@types/x.d.ts' '-weird.md' src/a@b.js");
assert.equal(files.json.commit, 'git commit -m "Fix" -m "PCWEB-12" -m "AI Assisted"');
assert.equal(files.json.commit, 'git commit -m "Fix" -m "ABC-12" -m "AI Assisted"');
assert.equal(files.json.command, `${files.json.add} && ${files.json.commit}`);
assert.equal(C("--subject", "Fix", "--add-all").json.add, "git add -A");
const bare = C("--subject", "Fix").json;
+338 -7
View File
@@ -76,6 +76,8 @@ import {
sentAnswer,
submittedAwaiting,
noteAwaiting,
threadText,
threadWho,
suggestionFrom,
turnGate,
verdictLabel,
@@ -151,14 +153,17 @@ import {
} from "../src/web-console/public/meter.js";
import { applyMention, matchNames, mentionAt } from "../src/web-console/public/mentions.js";
import { FAVICON_BODY, FAVICON_COLORS, faviconState, faviconSvg } from "../src/web-console/public/favicon.js";
import { CACHE_MS, RELEASES_URL, REPO_URL, checkForUpdate, compareVersions, latestTag } from "../src/web-console/update-check.mjs";
import { runHint } from "../src/web-console/public/render.js";
import { pickerCommand, pickFolder, WINDOWS_PICKER_SOURCE, WORKSPACE_PICKER_PROMPT } from "../src/web-console/picker.mjs";
import {
appendLedger,
applyPatch,
attachmentName,
bindLoopback,
chatReplyLines,
checkDocument,
cleanupFindings,
cwdHash,
handOff,
initialWorkspace,
@@ -169,6 +174,7 @@ import {
readLedger,
readWorkspaceCursor,
readOverview,
removeCleanup,
removeScratch,
removeSessions,
repoRoots,
@@ -176,6 +182,7 @@ import {
SESSION_MAX_AGE_MS,
SPEC_STATES,
staleScratch,
STRAY_GRACE_MS,
staleSessions,
STATE_LOCK_FILE,
sweepUploads,
@@ -192,6 +199,9 @@ const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-console-test-"));
const MODELS_DIR = path.join(HOME, "plan2code");
const ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_MODELS_DIR: MODELS_DIR, PLAN2CODE_NO_BROWSER: "1" };
// Every server these tests start runs the release check at boot. A fresh
// cached failure keeps the whole suite off the network and bannerless.
fs.writeFileSync(path.join(HOME, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest: null }));
// The session cookie is named for the server's port: browsers ignore the port
// when they scope a cookie, so one shared name let each session's server
@@ -1370,6 +1380,11 @@ test("a send records its note and attachments on the item, so the page can show
assert.equal(q1.sentNote.text, "see these");
assert.deepEqual(q1.sentNote.images, [{ path: j.path, name: j.name }]);
assert.deepEqual(q1.sentNote.files, [{ path: d.path, name: d.name }]);
// Earlier tests in this session sent notes on q1 too: the newest is this one.
const mine = q1.thread.filter((m) => m.who === "user").at(-1);
assert.equal(mine.text, "see these", "the note goes into the Notes thread, where the agent's reply will sit under it");
assert.equal(mine.at, q1.sentNote.at);
assert.deepEqual(mine.images, [{ path: j.path, name: j.name }]);
assert.equal(cli(["wait", "--session", sid, "--seconds", "10"]).status, 0);
const only = await post("/submit", { actions: [noteAction("q1", "just a note", [])], reply: "y" });
@@ -1377,6 +1392,11 @@ test("a send records its note and attachments on the item, so the page can show
const after = readState().items.find((i) => i.id === "q1");
assert.equal(after.sentNote.text, "just a note");
assert.deepEqual(after.sentNote.images ?? [], []);
assert.deepEqual(
after.thread.filter((m) => m.who === "user").map((m) => m.text).slice(-2),
["see these", "just a note"],
"every note stays in the thread, not just the latest one",
);
assert.equal(cli(["wait", "--session", sid, "--seconds", "10"]).status, 0);
});
@@ -1543,8 +1563,35 @@ test("patches merge by id and append threads", () => {
const q1 = state.items.find((i) => i.id === "q1");
assert.equal(q1.status, "answered");
assert.equal(q1.title, "Export format", "untouched fields survive a merge");
assert.equal(q1.thread.length, 1);
assert.ok(q1.thread[0].at, "the server stamps the time the agent left out");
const replies = q1.thread.filter((m) => m.who === "agent");
assert.equal(replies.length, 1);
assert.ok(replies[0].at, "the server stamps the time the agent left out");
});
test("a thread reply in another shape is lifted into { who, text }, and an empty one is refused", () => {
const base = { items: [{ id: "n1", kind: "text", title: "Name", status: "open", thread: [{ who: "user", text: "why?", at: "2026-10-05T10:00:00Z" }] }] };
const next = applyPatch(base, {
items: [{ id: "n1", thread: [
{ from: "agent", md: "Because." },
{ role: "assistant", content: "Also this." },
{ who: "user", text: "why?" },
] }],
});
const thread = next.items[0].thread;
assert.deepEqual(thread.map((m) => [m.who, m.text]), [["user", "why?"], ["agent", "Because."], ["agent", "Also this."]],
"aliases lifted, and the echoed note is not shown twice");
assert.equal(thread[1].md, undefined);
assert.equal(thread[1].from, undefined);
assert.throws(() => applyPatch(base, { items: [{ id: "n1", thread: [{ who: "agent" }] }] }), /thread entry has no "text"/);
assert.throws(() => applyPatch(base, { items: [{ id: "n1", thread: [{ who: "agent", md: " " }] }] }), /no "text"/);
});
test("the page reads older { from, md } thread entries", () => {
assert.equal(threadWho({ from: "agent", md: "x" }), "agent");
assert.equal(threadWho({ who: "user", text: "x" }), "user");
assert.equal(threadText({ from: "agent", md: "Older shape." }), "Older shape.");
assert.equal(threadText({ who: "agent", text: "Now." }), "Now.");
assert.equal(threadText({ who: "agent" }), "");
});
/* ------------------------------------------- result handoff (regressions) */
@@ -1923,6 +1970,27 @@ test("models: the user's additions round-trip, XHigh and Max are refused, and th
assert.deepEqual((await get()).user, { claude: [], devin: [] });
});
test("cleanup over HTTP: a scan lists strays in the console home, and a delete removes only what the scan found", async () => {
const stray = path.join(HOME, "stray-cleanup.json");
fs.writeFileSync(stray, "{}");
backdate(stray);
const res = await post("/cleanup", { scan: true });
assert.equal(res.status, 200);
const scan = await res.json();
const ids = scan.items.map((i) => i.id);
assert.ok(ids.includes("console:stray-cleanup.json"), ids.join(", "));
for (const id of ["console:looks.json", "console:update-check.json", "console:sessions", "console:runtime"]) assert.ok(!ids.includes(id), id);
assert.ok(!ids.includes("session:" + sid), "never the session serving the page");
assert.ok(scan.items.every((i) => !("path" in i)), "no paths go to the page");
assert.ok(!scan.items.some((i) => i.where === "root"), "a console from another home never reaches ~/.plan2code");
const done = await post("/cleanup", { delete: ["console:stray-cleanup.json", "console:looks.json", "session:" + sid] });
assert.equal(done.status, 200);
assert.deepEqual((await done.json()).removed, ["console:stray-cleanup.json"]);
assert.equal(fs.existsSync(stray), false);
assert.ok(fs.existsSync(path.join(HOME, "update-check.json")));
});
test("stop leaves a process it cannot identify as ours alone", () => {
// A handle file can outlive a reboot in the system temp dir and its pid can
// be reused. Killing on the strength of a number alone can hit anything.
@@ -2212,7 +2280,12 @@ test("a note the agent has not answered yet is still on its way", () => {
assert.equal(noteAwaiting({ sentNote: note }), note);
assert.equal(noteAwaiting({ sentNote: note, thread: [{ who: "agent", text: "Earlier.", at: "2026-09-23T02:00:00Z" }] }), note);
assert.equal(noteAwaiting({ sentNote: note, thread: [{ who: "agent", text: "Seen.", at: "2026-09-23T03:01:00Z" }] }), null);
assert.equal(noteAwaiting({ sentNote: note, thread: [{ who: "user", text: "look at this", at: "2026-09-23T03:00:00Z" }] }), null);
assert.equal(
noteAwaiting({ sentNote: note, thread: [{ who: "user", text: "look at this", at: "2026-09-23T03:00:00Z" }] }),
note,
"the person's own note in the thread is not a reply to it",
);
assert.equal(noteAwaiting({ sentNote: note, thread: [{ from: "agent", md: "Older shape.", at: "2026-09-23T03:01:00Z" }] }), null);
assert.equal(noteAwaiting({ sentNote: note, thread: [{ who: "agent", text: "No clock." }] }), null);
});
@@ -3375,7 +3448,7 @@ test("the session sweep removes only month-old session dirs, never the one being
}
});
test("the scratch sweep removes old patches and helpers, never looks, the pointer or a directory", async () => {
test("the scratch sweep removes old patches and helpers, never looks, the pointer, the update cache or a directory", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-scratch-"));
try {
const file = (name, stale = true) => {
@@ -3385,7 +3458,7 @@ test("the scratch sweep removes old patches and helpers, never looks, the pointe
return p;
};
const removable = [file("p2.json"), file("helper.mjs")];
const kept = [file("looks.json"), file("workspaces.json"), file("console-dir"), file("notes.txt"), file("p3.json", false)];
const kept = [file("looks.json"), file("workspaces.json"), file("console-dir"), file("update-check.json"), file("notes.txt"), file("p3.json", false)];
const subdir = path.join(dir, "x.json");
fs.mkdirSync(subdir);
backdate(subdir);
@@ -3394,17 +3467,104 @@ test("the scratch sweep removes old patches and helpers, never looks, the pointe
const stale = staleScratch(dir, Date.now(), SESSION_MAX_AGE_MS).sort();
assert.deepEqual(stale, ["helper.mjs", "p2.json"]);
assert.deepEqual(
(await removeScratch(dir, [...stale, "looks.json", "workspaces.json", "../p.json", "console-dir"])).sort(),
(await removeScratch(dir, [...stale, "looks.json", "workspaces.json", "../p.json", "console-dir", "update-check.json"])).sort(),
["helper.mjs", "p2.json"]
);
for (const p of removable) assert.equal(fs.existsSync(p), false, p);
for (const p of kept) assert.ok(fs.existsSync(p), p);
assert.deepEqual([...PROTECTED_CONSOLE_FILES].sort(), ["console-dir", "looks.json", "workspaces.json"]);
assert.deepEqual([...PROTECTED_CONSOLE_FILES].sort(), ["console-dir", "looks.json", "update-check.json", "workspaces.json"]);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("cleanup finds old sessions and strays in both folders, and keeps every protected name and this session", async () => {
const plan2code = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-cleanup-"));
const consoleDir = path.join(plan2code, "console");
try {
// Strays count only once they have sat for the grace period, so every one
// this test expects to be found is backdated.
const put = (p, body = "{}") => {
fs.mkdirSync(path.dirname(p), { recursive: true });
fs.writeFileSync(p, body);
return p;
};
const stray = (p, body) => {
put(p, body);
backdate(p);
return p;
};
const session = (sid, stale) => {
const state = put(path.join(consoleDir, "sessions", sid, "state.json"));
if (stale) backdate(state);
return path.dirname(state);
};
const old = session("20250801-101010-aaaaaa", true);
const current = session("20250801-101010-bbbbbb", true);
const fresh = session("20260920-101010-cccccc", false);
// A month-old state.json, but a draft saved today: still in use.
const drafted = session("20250801-101010-dddddd", true);
put(path.join(drafted, "draft.json"));
const kept = [
...["looks.json", "workspaces.json", "console-dir", "update-check.json"].map((n) => put(path.join(consoleDir, n))),
put(path.join(plan2code, "launcher.json")),
put(path.join(plan2code, "models.json")),
put(path.join(plan2code, "bin", "plan2code.js"), "x"),
current,
fresh,
drafted,
];
stray(path.join(consoleDir, "p1.json"), "12345");
put(path.join(consoleDir, "runtime", "x.json"));
backdate(put(path.join(plan2code, "console-dev", "sessions", "x.txt"), "abc"));
backdate(path.join(plan2code, "console-dev"));
// An old folder with a file rewritten just now: the folder's own mtime
// never moves for that, so only its contents show it is in use.
const busy = put(path.join(plan2code, "busy", "log.txt"));
backdate(path.join(plan2code, "busy"));
kept.push(busy);
stray(path.join(plan2code, "notes.txt"));
// In use right now: a held lock and a temp between its write and rename.
const live = [put(path.join(consoleDir, "workspaces.json.lock"), ""), put(path.join(plan2code, "models.json.123.tmp"))];
kept.push(...live);
stray(path.join(consoleDir, "looks.json.456.tmp"));
const opts = { consoleDir, plan2codeDir: plan2code, skipSid: "20250801-101010-bbbbbb" };
const { items, bytes } = await cleanupFindings(opts);
assert.deepEqual(items.map((i) => i.id).sort(), [
"console:looks.json.456.tmp",
"console:p1.json",
"root:console-dev",
"root:notes.txt",
"session:20250801-101010-aaaaaa",
]);
assert.equal(STRAY_GRACE_MS, 60 * 60 * 1000);
assert.equal(items.find((i) => i.id === "console:p1.json").bytes, 5);
assert.equal(items.find((i) => i.id === "root:console-dev").kind, "folder");
assert.equal(bytes, items.reduce((n, i) => n + i.bytes, 0));
// A console running from another home never reaches the folder above it.
const elsewhere = await cleanupFindings({ ...opts, plan2codeDir: path.join(plan2code, "other") });
assert.deepEqual(elsewhere.items.map((i) => i.where).sort(), ["console", "console", "session"]);
// Only ids a fresh scan still finds are removed; anything else is ignored.
const done = await removeCleanup(
["console:p1.json", "session:20250801-101010-aaaaaa", "session:20250801-101010-dddddd", "root:busy", "root:console-dev", "console:looks.json", "root:bin", "session:20250801-101010-bbbbbb", "console:workspaces.json.lock", "root:models.json.123.tmp", "console:../escape", 7],
opts
);
assert.deepEqual(done.removed.sort(), ["console:p1.json", "root:console-dev", "session:20250801-101010-aaaaaa"]);
assert.deepEqual(done.failed, []);
assert.equal(done.bytes, 5 + 3 + 2);
assert.equal(fs.existsSync(old), false);
assert.equal(fs.existsSync(path.join(plan2code, "console-dev")), false);
assert.ok(fs.existsSync(path.join(plan2code, "notes.txt")), "not asked for, so not removed");
for (const p of kept) assert.ok(fs.existsSync(p), p);
assert.ok(fs.existsSync(path.join(consoleDir, "runtime", "x.json")));
} finally {
fs.rmSync(plan2code, { recursive: true, force: true });
}
});
// A temp project with specs/a (overview) and specs/b (no overview), and a
// file outside the root for escapes to aim at.
function overviewProject() {
@@ -5618,6 +5778,7 @@ test("only open leaves the console-dir pointer; status, help and a bad command d
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-pointer-"));
const env = { PLAN2CODE_CONSOLE_HOME: home, PLAN2CODE_MODELS_DIR: path.join(home, "plan2code") };
const pointer = path.join(home, "console-dir");
fs.writeFileSync(path.join(home, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest: null }));
try {
cli(["status"], { env });
cli(["help"], { env });
@@ -5898,3 +6059,173 @@ test("unansweredChat lists delivered Quick questions that still have no reply",
assert.deepEqual(unansweredChat(dir, {}), [2]);
assert.deepEqual(unansweredChat(dir, { chat: { replies: [{ id: "r2", re: 2, conversation: 1, md: "done" }] } }), []);
});
/* ------------------------------------------------------- update check */
const REPO_VERSION = JSON.parse(fs.readFileSync(path.join(ROOT, "version.json"), "utf8")).version;
test("update check: compareVersions orders X.Y.Z numerically and refuses anything else", () => {
assert.equal(compareVersions("2.4.3", "2.4.3"), 0);
assert.equal(compareVersions("2.4.3", "2.5.0"), -1);
assert.equal(compareVersions("3.0.0", "2.99.99"), 1);
assert.equal(compareVersions("2.10.0", "2.9.9"), 1, "numeric, not string, order");
for (const bad of ["2.4", "v2.4.3", "", undefined, "2.4.3-rc1"]) {
assert.equal(compareVersions(bad, "2.4.3"), null, String(bad));
assert.equal(compareVersions("2.4.3", bad), null, String(bad));
}
});
test("update check: latestTag picks the highest vX.Y.Z, skipping peeled and non-release tags", () => {
const out = [
"aaa\trefs/tags/v2.4.3",
"bbb\trefs/tags/v2.4.3^{}",
"ccc\trefs/tags/v2.10.0",
"ddd\trefs/tags/v2.10.0^{}",
"eee\trefs/tags/v2.9.9",
"fff\trefs/tags/v3.0.0-rc1",
"ggg\trefs/tags/release-4",
"hhh\trefs/tags/v9.0.0^{}",
].join("\n");
assert.equal(latestTag(out), "2.10.0");
assert.equal(latestTag(out.replace(/\n/g, "\r\n")), "2.10.0", "CRLF output");
assert.equal(latestTag("fff\trefs/tags/v3.0.0-rc1\nggg\trefs/tags/release-4"), null);
assert.equal(latestTag(""), null);
assert.equal(latestTag(null), null);
assert.equal(latestTag(42), null);
});
test("update check: the cache is reused for an hour, failures included, and rebuilt when stale or corrupt", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-update-"));
const cacheFile = path.join(dir, "nested", "update-check.json");
const now = 1_800_000_000_000;
let calls = 0;
const tags = (v) => async () => {
calls++;
return `abc\trefs/tags/v${v}\n`;
};
const read = () => JSON.parse(fs.readFileSync(cacheFile, "utf8"));
try {
// No cache: asks, and writes what it found.
assert.deepEqual(await checkForUpdate({ installed: "2.4.3", cacheFile, now, run: tags("2.5.0") }), {
installed: "2.4.3",
latest: "2.5.0",
updateAvailable: true,
});
assert.equal(calls, 1);
assert.deepEqual(read(), { checkedAt: now, latest: "2.5.0" });
// Fresh: the runner is not called.
const fresh = await checkForUpdate({ installed: "2.4.3", cacheFile, now: now + CACHE_MS - 1, run: tags("9.9.9") });
assert.equal(fresh.latest, "2.5.0");
assert.equal(calls, 1);
// Equal or newer installed: no update.
assert.equal((await checkForUpdate({ installed: "2.5.0", cacheFile, now, run: tags("9.9.9") })).updateAvailable, false);
assert.equal((await checkForUpdate({ installed: "2.6.0", cacheFile, now, run: tags("9.9.9") })).updateAvailable, false);
assert.equal(calls, 1);
// Stale: asks again and rewrites.
const stale = await checkForUpdate({ installed: "2.4.3", cacheFile, now: now + CACHE_MS, run: tags("2.6.0") });
assert.equal(stale.latest, "2.6.0");
assert.equal(calls, 2);
assert.equal(read().checkedAt, now + CACHE_MS);
// Corrupt: treated as stale.
fs.writeFileSync(cacheFile, "{not json");
assert.equal((await checkForUpdate({ installed: "2.4.3", cacheFile, now, run: tags("2.7.0") })).latest, "2.7.0");
assert.equal(calls, 3);
// A failed lookup is cached as null, and not retried within the hour.
fs.rmSync(cacheFile);
const failed = async () => {
calls++;
return null;
};
assert.equal(await checkForUpdate({ installed: "2.4.3", cacheFile, now, run: failed }), null);
assert.equal(calls, 4);
assert.deepEqual(read(), { checkedAt: now, latest: null });
assert.equal(await checkForUpdate({ installed: "2.4.3", cacheFile, now: now + 1000, run: tags("9.9.9") }), null);
assert.equal(calls, 4, "the cached failure is reused");
// A runner that throws, or an unknown installed version, is null, never a throw.
fs.rmSync(cacheFile);
const boom = async () => {
throw new Error("boom");
};
assert.equal(await checkForUpdate({ installed: "2.4.3", cacheFile, now, run: boom }), null);
assert.equal(await checkForUpdate({ installed: "dev", cacheFile, now: now + CACHE_MS * 2, run: tags("2.5.0") }), null);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
test("update check: the repo and Releases URLs are the plan2code repo's", () => {
assert.equal(REPO_URL, "https://github.com/jparkerweb/plan2code.git");
assert.equal(RELEASES_URL, "https://github.com/jparkerweb/plan2code/releases/");
});
test("update check: the frame carries update only when a newer release is cached, and /version names latest", async () => {
const newer = `${Number(REPO_VERSION.split(".")[0]) + 1}.0.0`;
for (const [latest, expectUpdate] of [
[newer, true],
[REPO_VERSION, false],
]) {
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-update-frame-"));
const env = { PLAN2CODE_CONSOLE_HOME: home, PLAN2CODE_MODELS_DIR: path.join(home, "plan2code") };
fs.writeFileSync(path.join(home, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest }));
const res = cli(["open", "--no-open", "--workflow", "dashboard"], { env });
const s = sessionUrl(res.json.url);
const get = async (pathname) =>
(await fetch(`${s.base}${pathname}`, { headers: { cookie: s.cookie, connection: "close" } })).json();
try {
// The check answers just after boot; give it a moment either way.
let frame;
for (let i = 0; i < 20; i++) {
frame = await get("/state");
if (frame.update) break;
await new Promise((r) => setTimeout(r, 100));
}
if (expectUpdate) {
assert.deepEqual(frame.update, { installed: REPO_VERSION, latest: newer });
} else {
assert.equal("update" in frame, false, "no update key when the installed version is current");
}
assert.deepEqual(await get("/version"), { version: REPO_VERSION, latest });
} finally {
cli(["stop", "--session", res.json.sid], { env });
fs.rmSync(home, { recursive: true, force: true });
}
}
});
test("update banner: the modal is in the page, with the exact command and no inline styles or scripts", () => {
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
const dialog = html.match(/<dialog class="modal" id="update-modal" aria-labelledby="update-title">([\s\S]*?)<\/dialog>/);
assert.ok(dialog, "index.html has the update modal");
assert.doesNotMatch(dialog[1], /\sstyle=/);
assert.doesNotMatch(dialog[1], /<script/i);
const panel = helpTemplate().match(/<section class="help-panel" data-tab="dashboard">([\s\S]*?)<\/section>/);
assert.ok(panel, "the help has a dashboard topic");
assert.match(panel[1], /UPDATE AVAILABLE/, "the dashboard topic explains the banner");
assert.doesNotMatch(panel[1], /\sstyle=/);
assert.doesNotMatch(panel[1], /<script/i);
assert.ok(app.includes('"npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git"'), "app.js copies the exact command");
});
test("update banner: built only on the dashboard, dismissed per session, and Help's version links to Releases", () => {
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
const start = app.indexOf("function renderDashboard(main) {");
assert.ok(start >= 0, "app.js has renderDashboard");
const end = app.indexOf("\n}\n", start);
const body = app.slice(start, end);
assert.match(body, /"dash-nudge update-banner"/, "renderDashboard builds the banner");
const outside = app.slice(0, start) + app.slice(end);
assert.doesNotMatch(outside, /update-banner/, "no other code builds it");
assert.match(app, /"p2c-update-dismissed:" \+ S\.sid/, "the dismissal is keyed by the session id");
assert.match(app, /const RELEASES_URL = "https:\/\/github\.com\/jparkerweb\/plan2code\/releases\/";/);
assert.match(app, /\.rel = "noopener noreferrer";/);
const help = app.match(/async function renderHelpVersion\(\) \{([\s\S]*?)\n\}/);
assert.ok(help, "app.js has renderHelpVersion");
assert.match(help[1], /releasesLink\(/, "the help version is a Releases link");
});
@@ -243,7 +243,7 @@ summarise it back.
Then, in ONE `post`, do all of:
- mark each answered item `"status": "answered"` and record its `answer`
- add your replies to any comment threads
- reply to every note in that item's `thread` (shape below)
- answer any Quick questions that came with it, in `chat.replies` (see Quick
questions)
- publish the next batch of questions
@@ -251,6 +251,26 @@ Then, in ONE `post`, do all of:
One post is one atomic update, so the page never shows a half-changed state.
### Replying to a note
A `comment` is the person talking to you about that card, often asking
something. It shows in the card's **Notes on this** panel, and so does your
answer:
```jsonc
{ "items": [{ "id": "p4", "thread": [
{ "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." }
] }] }
```
- Every entry is `{ "who": "agent", "text": "<markdown>" }`. `text`, not
`md`: the page reads nothing else. An entry with no `text` is rejected.
- The server writes their note into the thread as it arrives. Do not repeat
it, and send only your new entries: `thread` appends.
- Answer what they asked, in the thread, even when you also change a doc or
re-ask the question. "I've updated the doc" alone leaves the question in the
panel with no answer under it.
### Recording the answer
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
@@ -661,9 +681,17 @@ finish are dropped, so you start on a blank page and post your own. A skill
run inline from another (a quick task's review) keeps the page it was
handed. A
fresh `open` would strand the page the person is watching on the dashboard's
session while your questions went to a page nobody has open. Then run the
skill normally: its Interface question was already answered by being
launched, so start where its real work starts.
session while your questions went to a page nobody has open.
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
> own file-read tool and follow it from the top instead.** Every Plan2Code
> skill below the dashboard ships `disable-model-invocation: true` on
> purpose — it exists to be read and followed inline, not launched as a
> sub-skill — and calling one through a skill-invocation tool errors out and
> strands the hand-off mid-launch.
Its Interface step is already answered by having been launched, so start
where its real work starts.
The menu itself is the page's own list — you never send it. The page knows
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
@@ -829,6 +857,12 @@ know:
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
Post `activity` as each step starts, before its doc or question lands — reading
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
implementation — the same way Review does. A step with no card of its own
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
Finalize".
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
Stopping mid-finalize loses nothing
— the specs are untouched until Step 3's summary write — so a stop's finish
@@ -859,7 +893,7 @@ question or doc lands:
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
merge by `id` (an unknown id is added), and `thread` / `comments` append. Send only
merge by `id` (an unknown id is added), and `thread` appends. Send only
what changed. A whole-file rewrite would put the entire session back into your
context on every turn.
@@ -1239,7 +1273,7 @@ answers were submitted but never picked up.
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` and `comments` **append**: leave out any thread entry you already sent, or the person sees your reply twice. |
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
@@ -48,6 +48,10 @@ export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
// so every session within the hour reuses one lookup.
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
// test run (or a second sandboxed instance) shares one handle directory with
// the real thing, and `stop --all` reaches outside its own world and kills a
@@ -487,9 +491,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks, the folders remembered per project and spec, and the pointer to
// this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
// looks, the folders remembered per project and spec, the pointer to this
// console's directory, and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir", "update-check.json"]);
function isScratchName(name) {
return (
@@ -536,6 +540,148 @@ export async function removeScratch(consoleDir, names) {
return removed;
}
/* ------------------------------------------------------------- cleanup */
// What User Preferences -> Cleanup never removes. The console folder keeps its
// protected files, its sessions dir (old sessions go one by one, by age) and,
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
// console, the launcher (bin/, launcher.json) and the models the person added.
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
// A stray must sit untouched this long before Cleanup lists it. The same
// folders hold files that live for milliseconds -- a held
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
// rename -- and removing one mid-write loses another session's change.
export const STRAY_GRACE_MS = 60 * 60 * 1000;
// Bytes under `p`, never following a symlink: a link counts as itself.
async function diskBytes(p) {
let st;
try {
st = await fs.promises.lstat(p);
} catch {
return 0;
}
if (!st.isDirectory()) return st.size;
let entries;
try {
entries = await fs.promises.readdir(p);
} catch {
return 0;
}
let total = 0;
for (const name of entries) total += await diskBytes(path.join(p, name));
return total;
}
// The newest mtime of anything under `p`, never following a symlink. A folder
// counts by its files, since rewriting a file never touches its folder's
// mtime; an empty folder counts by its own. Anything unreadable on the way
// down answers Infinity, so it reads as just touched and stays.
function newestMtime(p) {
let st;
try {
st = fs.lstatSync(p);
} catch {
return Infinity;
}
if (!st.isDirectory()) return st.mtimeMs;
let entries;
try {
entries = fs.readdirSync(p);
} catch {
return Infinity;
}
if (!entries.length) return st.mtimeMs;
let newest = 0;
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
return newest;
}
function entryKind(entry) {
if (entry.isSymbolicLink()) return "link";
return entry.isDirectory() ? "folder" : "file";
}
function strayEntries(dir, kept, where, now) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return [];
}
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
return entries
.filter((e) => !kept.has(e.name))
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
.filter((e) => settled(e.path));
}
/**
* Everything Cleanup would remove, worked out on the server and never taken
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
* `open` sweeps by, plus every file in the folder that old, so a resumed
* session or a saved draft keeps it), anything at the top of the console folder that is
* not kept, and -- only when the console runs from its default home inside
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
* touched within `STRAY_GRACE_MS` are left for a later scan. A
* console running from another home (tests, dev) never reaches ~/.plan2code.
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
*/
export async function cleanupFindings({
consoleDir = HOME_DIR,
plan2codeDir = PLAN2CODE_DIR,
now = Date.now(),
maxAgeMs = SESSION_MAX_AGE_MS,
skipSid,
} = {}) {
const found = [];
const sessionsDir = path.join(consoleDir, "sessions");
for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) {
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
}
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
}
const items = [];
let bytes = 0;
for (const f of found) {
const size = await diskBytes(f.path);
bytes += size;
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
}
return { items, bytes };
}
/**
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
* worked out afresh first and only ids on it are touched, so a name from the
* page is never a path, and anything that stopped qualifying since the scan
* (a session touched again) stays. A link is unlinked, never followed.
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
*/
export async function removeCleanup(ids, opts = {}) {
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
const { items } = await cleanupFindings(opts);
const removed = [];
const failed = [];
let bytes = 0;
for (const item of items) {
if (!wanted.has(item.id)) continue;
try {
if (item.kind === "link") await fs.promises.unlink(item.path);
else await fs.promises.rm(item.path, { recursive: true, force: true });
removed.push(item.id);
bytes += item.bytes;
} catch {
failed.push(item.id);
}
}
return { removed, bytes, failed };
}
/**
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
* the file's realpath must sit inside the root's, so `../`, an absolute path
@@ -871,7 +1017,7 @@ export function handOff(child, pre) {
/* ----------------------------------------------------------- patch merge */
const APPEND_KEYS = new Set(["thread", "comments"]);
const APPEND_KEYS = new Set(["thread"]);
function isPlainObject(v) {
return v !== null && typeof v === "object" && !Array.isArray(v);
@@ -896,7 +1042,7 @@ function mergeOne(target, patch, where) {
}
// Merge a keyed collection: a known id merges one level, an unknown id appends.
// Named fields are replaced whole; thread/comments append.
// Named fields are replaced whole; thread appends.
function mergeKeyed(current, patchList, idKey, defaults, where) {
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
for (const entry of patchList) {
@@ -955,6 +1101,42 @@ function dropStaleSubmissions(currentItems, before, patchList) {
return merged;
}
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
// borrow the shape of the replies and doc blocks they also write, so `from` /
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
// at all is refused. The person's own notes are recorded by the server when
// they send, so an agent that echoes one back is not shown it twice.
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
function normalizeThreads(patchList, currentItems) {
return patchList.map((entry) => {
if (!isPlainObject(entry) || entry.thread == null) return entry;
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
const said = new Set(
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
);
const thread = [];
for (const m of entry.thread) {
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
guard(m, "thread");
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
if (!key) {
throw new Error(
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
);
}
const { from, role, md, body, content, ...rest } = m;
const who = (m.who || from || role) === "user" ? "user" : "agent";
const text = m[key];
if (who === "user" && said.has(text.trim())) continue;
thread.push({ ...rest, who, text });
}
return { ...entry, thread };
});
}
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
@@ -996,7 +1178,7 @@ export function applyPatch(state, patch) {
break;
case "items":
if (!Array.isArray(v)) throw new Error('"items" must be an array');
next.items = dropStaleSubmissions(next.items, state.items, v);
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
break;
case "topics":
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
@@ -1048,15 +1230,11 @@ function stampTimes(before, next) {
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
}
for (const list of [next.items, next.docs]) {
if (!Array.isArray(list)) continue;
for (const entry of list) {
if (Array.isArray(next.items)) {
for (const entry of next.items) {
if (Array.isArray(entry.thread)) {
for (const m of entry.thread) if (!m.at) m.at = now;
}
if (Array.isArray(entry.comments)) {
for (const m of entry.comments) if (!m.at) m.at = now;
}
}
}
if (Array.isArray(next.docs)) {
@@ -1289,7 +1467,10 @@ 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, sentNote, ...rest }) => rest);
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
...rest,
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
}));
const prose =
JSON.stringify(authored) +
JSON.stringify(state.docs || []) +
@@ -65,7 +65,7 @@ export function submittedAwaiting(item) {
if (!s || typeof s !== "object") return null;
if (item.answer && typeof item.answer === "object") return null;
const thread = Array.isArray(item.thread) ? item.thread : [];
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
return replied ? null : s;
}
@@ -74,17 +74,33 @@ export function submittedAwaiting(item) {
* 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.
* Any agent message from the send onwards, or one with no clock to compare,
* means it has been picked up. The person's own entries never count: the
* server writes their note into the thread as it arrives.
*/
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));
const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at));
return picked ? null : n;
}
/**
* Who said a thread entry and what they said. The contract is `{ who, text }`
* and the server lifts anything else into it, but sessions written before that
* hold `{ from, md }` replies, which would otherwise draw as empty bubbles.
*/
export function threadWho(m) {
return m && (m.who || m.from || m.role) === "user" ? "user" : "agent";
}
export function threadText(m) {
if (!m) return "";
for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k];
return "";
}
/* -------------------------------------------------------------- labels */
export function optionLabel(item, k) {
@@ -23,6 +23,9 @@
--warn-soft: #fbe7e3;
--focus: #1f6feb;
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
/* A soft accent halo for the things that want noticing: the update banner
and an enabled Send. Built from --accent, so a picked accent glows too. */
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
@@ -61,6 +64,7 @@
--warn-soft: #34201d;
--focus: #6aa3ff;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
}
}
@@ -85,6 +89,7 @@
--warn-soft: #34201d;
--focus: #6aa3ff;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
}
* { box-sizing: border-box; }
@@ -1097,10 +1102,11 @@ h1 {
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
the tiny ring, left of the label. */
.view-tab .tab-spin {
the tiny ring, left of the label. The extra .spinner is for specificity:
.spinner.tiny comes later and zeroes the margin otherwise. */
.view-tab .spinner.tab-spin {
display: inline-block;
margin-right: 6px;
margin-right: 7px;
vertical-align: -1px;
}
@@ -1657,11 +1663,13 @@ input[type="text"].invalid { border-color: var(--warn); }
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
/* Send breathes while there is something to send: a soft accent ring that
spreads and fades. Off under reduced motion, below. */
/* Send glows and breathes while there is something to send: the steady
--glow, plus a soft accent ring that spreads and fades. The ring is off
under reduced motion, below; the glow stays. */
#btn-send:not(:disabled) { box-shadow: var(--glow); }
@keyframes send-pulse {
0% { box-shadow: 0 0 0 0 var(--accent-line); }
100% { box-shadow: 0 0 0 6px transparent; }
0% { box-shadow: var(--glow), 0 0 0 0 var(--accent-line); }
100% { box-shadow: var(--glow), 0 0 0 6px transparent; }
}
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
@@ -2219,6 +2227,7 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
.modal.help[open] { display: flex; }
.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-version a { color: inherit; }
.help-layout {
display: grid;
@@ -2668,6 +2677,74 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
border-left-width: 4px;
color: var(--ink);
}
/* A newer release: the same slot, in the accent, with the label as the way
into the update modal and a small × that hides it for this session. */
.dash-nudge.update-banner {
position: relative;
padding-left: 40px;
padding-right: 40px;
border-left-width: 4px;
border-left-color: var(--accent-line);
color: var(--ink);
box-shadow: var(--glow);
}
.update-banner-open {
flex: 1 1 16em;
padding: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
font-weight: 600;
letter-spacing: 0.02em;
text-align: center;
cursor: pointer;
}
.update-banner-open:hover { text-decoration: underline; }
/* Pinned to the right edge, out of the flow, so the label centres on the
whole banner rather than on what the × leaves of it. */
.update-banner-dismiss {
position: absolute;
top: 50%;
right: 10px;
transform: translateY(-50%);
padding: 0 6px;
border: 0;
border-radius: var(--radius);
background: none;
color: inherit;
font: inherit;
font-size: 16px;
line-height: 1;
cursor: pointer;
}
.update-banner-dismiss:hover { background: var(--accent-line); }
/* Wide enough that the update command sits on one line beside Copy; a
narrow window still wraps it rather than overflowing. */
#update-modal { max-width: 720px; }
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
.update-steps li { margin: 4px 0; }
/* The hand-off copy row, in the modal's first step: the command and its Copy
side by side. */
.update-command {
margin: 6px 0 4px;
display: flex;
align-items: stretch;
gap: 10px;
flex-wrap: wrap;
}
.update-command code {
flex: 1 1 260px;
min-width: 0;
font: 13px/1.5 var(--mono);
color: var(--ink);
background: var(--panel);
border: 1px solid var(--rule-2);
border-radius: 8px;
padding: 10px 12px;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
.dash-working {
@@ -3394,6 +3471,18 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.models-actions .help.error { color: var(--danger, #d64545); }
/* User Preferences: Cleanup's list of what would go, shown before anything
is deleted. */
.cleanup-list { display: grid; gap: 4px; max-height: 200px; overflow: auto; font-size: 0.88em; }
.cleanup-list:empty { display: none; }
.cleanup-summary { margin: 0 0 2px; font-weight: 600; }
.cleanup-row { display: flex; justify-content: space-between; gap: 12px; }
.cleanup-row span:first-child { min-width: 0; overflow-wrap: anywhere; font-family: var(--mono); }
.cleanup-size { flex: none; color: var(--ink-3); }
.cleanup-more { display: grid; gap: 4px; }
.cleanup-more summary { cursor: pointer; color: var(--ink-2); }
#cleanup-delete[hidden] { display: none; }
/* 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 {
@@ -66,6 +66,8 @@ import {
submittedAwaiting,
noteAwaiting,
suggestionFrom,
threadText,
threadWho,
THUMB_EDGE,
turnGate,
verdictText,
@@ -446,6 +448,10 @@ document.addEventListener("click", (e) => {
const GONE_AFTER_MS = 8000;
// Named so a reconnect can clear only THIS banner: a bare banner(null) would
// wipe an unrelated warning that landed while the page was gone (an upload
// failure, a refused send).
const GONE_BANNER = "Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.";
const WORKING_GRACE_MS = 5 * 60 * 1000;
// Two minutes with the agent mid-turn, three when it is merely meant to be
// listening. The difference is the cost of being wrong: a working agent that
@@ -521,6 +527,9 @@ let chatFrame = null;
// sends them.
let wsFrame = null;
let meterFrame = null;
// The frame's update ({ installed, latest }), present only when a newer
// release is out; null otherwise.
let updateFrame = null;
let chatDot = false;
let chatSending = false;
let chatResetting = false;
@@ -566,7 +575,6 @@ function fresh() {
drafts: {},
images: {},
sent: {},
sentAt: null,
stopping: null,
afterBuild: null,
homeward: null,
@@ -870,10 +878,12 @@ function adopt(body) {
chatFrame = body.chat || null;
if (body.workspace) wsFrame = body.workspace;
if (body.meter) meterFrame = body.meter;
// Always replaced: an absent key means no update.
updateFrame = body.update || null;
lastContact = Date.now();
if (gone) {
gone = false;
banner(null);
if ($("banner").textContent === GONE_BANNER) banner(null);
}
if (firstLoad) {
load();
@@ -1016,7 +1026,9 @@ function adopt(body) {
render();
if ($("workspace-modal").open) renderWorkspace();
tellFolderIssues();
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow) loadOverview();
// The Overview tab's file changes under a build, so a tab you are watching
// refetches on every new frame too, not only on the click that opened it.
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow || view === "overview") loadOverview();
if (announce) showArrival(announce);
// New entries land at the bottom of the rail. Gliding down to them beats
// leaving the list parked where it was while it grew underneath.
@@ -1149,15 +1161,12 @@ function markGone() {
// of the server means there, and a banner promising a reconnect would
// argue with it.
if (!finish() && !stopInProgress()) {
banner(
"Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.",
"warn"
);
banner(GONE_BANNER, "warn");
}
render();
} else if (!bad && gone) {
gone = false;
banner(null);
if ($("banner").textContent === GONE_BANNER) banner(null);
render();
}
}
@@ -1182,7 +1191,6 @@ function connect() {
} catch {}
});
es.addEventListener("submitted", (e) => {
local.sentAt = Date.now();
// Drop only what was actually sent.
//
// This event fires for a send from ANY tab of this session, which is why it
@@ -1799,14 +1807,19 @@ async function sendBrief() {
reply: briefPhrase(choice.range),
}),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
$("brief-modal").close();
banner("Asked for a brief. It will appear as a tab when it is written.", "good");
setTimeout(() => banner(null), 5000);
pendingResult = true;
render();
} catch {
why.textContent = "That did not go through. Try again in a moment.";
} catch (err) {
if (err && err.pending) pendingResult = true;
why.textContent =
err && err.pending
? "Your last answers are still being picked up. Try again in a moment."
: "That did not go through. Try again in a moment.";
} finally {
go.disabled = false;
go.textContent = "Write the brief";
@@ -2515,6 +2528,51 @@ function roleNudge() {
return nudge;
}
// × on the update banner hides it for this console session only, and only
// for the release it named. Blocked storage means "not dismissed".
function updateDismissKey() {
try {
return "p2c-update-dismissed:" + S.sid;
} catch {
return "p2c-update-dismissed:";
}
}
function updateDismissed() {
try {
return sessionStorage.getItem(updateDismissKey()) === updateFrame.latest;
} catch {
return false;
}
}
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
const UPDATE_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
function releasesLink(text) {
const a = el("a", null, text);
a.href = RELEASES_URL;
a.target = "_blank";
a.rel = "noopener noreferrer";
return a;
}
function openUpdateModal() {
if (!updateFrame) return;
const versions = $("update-versions");
versions.replaceChildren(
document.createTextNode("Version "),
releasesLink("v" + updateFrame.latest),
document.createTextNode(" is out — you have "),
el("code", null, updateFrame.installed),
document.createTextNode(".")
);
const row = $("update-command");
const code = el("code", null, UPDATE_COMMAND);
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
$("update-modal").showModal();
}
function renderDashboard(main) {
maybeWake();
const menu = (S && S.menu) || {};
@@ -2526,6 +2584,25 @@ function renderDashboard(main) {
warn.setAttribute("role", "status");
wrap.appendChild(warn);
}
// Built here only, so no other workflow's page ever shows it.
if (updateFrame && !updateDismissed()) {
const notice = el("div", "dash-nudge update-banner");
notice.setAttribute("role", "status");
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + updateFrame.latest);
open.type = "button";
open.addEventListener("click", openUpdateModal);
const dismiss = el("button", "update-banner-dismiss", "×");
dismiss.type = "button";
dismiss.setAttribute("aria-label", "Dismiss until next time");
dismiss.addEventListener("click", () => {
try {
sessionStorage.setItem(updateDismissKey(), updateFrame.latest);
} catch {}
render();
});
notice.append(open, dismiss);
wrap.appendChild(notice);
}
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
if (typeof menu.note === "string" && menu.note.trim()) {
@@ -3223,7 +3300,11 @@ document.addEventListener("keydown", cancelSkipMove, true);
function skipAndMoveOn(id) {
cancelSkipMove();
local.skipFlash = id;
stage(id, { type: "skip", skipped: true });
// A note already typed goes along: skipping the question is not retracting
// the comment. Dropping it would leave the text in the box but out of the
// send, which looks kept and is not.
const cur = local.staged[id];
stage(id, { type: "skip", skipped: true, ...(cur && cur.text ? { text: cur.text } : {}) });
skipTimer = setTimeout(() => {
skipTimer = null;
local.skipFlash = null;
@@ -3340,19 +3421,24 @@ function renderWaiting(main) {
}
pane.appendChild(title);
pane.appendChild(el("p", null, doing));
const ask = "If Plan2Code needs you, the question appears here on its own.";
if (!docs().length) {
pane.appendChild(el("p", null, "If Plan2Code needs you, the question appears here on its own."));
pane.appendChild(el("p", null, ask));
return;
}
// "Task" and the tasks tab's own name both open that tab, so the pointer is
// one click from what it points at. A build posts it as `phase` ("Phase N
// tasks"), a quick task as `tasks`; with neither the words stay plain.
// tasks"), a quick task as `tasks`. A skill with no task list (Document,
// Plan) has nothing live to follow, so it gets no pointer at all.
const list =
docs().find((d) => d.id === "phase") ||
docs().find((d) => d.id === "tasks") ||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
if (!list) {
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
return;
}
const jump = (word) => {
if (!list) return el("strong", "waiting-jump", word);
const b = el("button", "waiting-jump", word);
b.type = "button";
b.addEventListener("click", () => {
@@ -3366,8 +3452,8 @@ function renderWaiting(main) {
"The tabs above fill in as it goes. You can follow along with live ",
jump("Task"),
" updates in the ",
jump((list && list.title) || "Phase tasks"),
" tab. If Plan2Code needs you, the question appears here on its own."
jump(list.title || "Phase tasks"),
" tab. " + ask
);
pane.appendChild(p);
}
@@ -3505,8 +3591,8 @@ function renderSettled(card, item) {
// would misreport which of the two was the answer.
let prose = text;
if (!prose && !lines.length) {
const mine = (item.thread || []).filter((m) => m.who === "user");
if (mine.length) prose = String(mine[mine.length - 1].text || "").trim();
const mine = (item.thread || []).filter((m) => threadWho(m) === "user");
if (mine.length) prose = threadText(mine[mine.length - 1]).trim();
}
const nothing = !lines.length && !prose;
@@ -4322,6 +4408,10 @@ function buildChecklist(card, item, staged) {
const commitList = (change) => {
const cur = local.staged[item.id];
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
// A tick or a state IS the answer, so it ends a skip staged earlier:
// left in place, `skipped` would collapse the reply to "skip" while the
// card showed ticked steps on their way.
delete next.skipped;
const empty = !(next.done && next.done.length) && !next.state && !next.text;
stage(item.id, empty ? null : next);
};
@@ -4371,7 +4461,7 @@ function buildChecklist(card, item, staged) {
function buildMenu(card, item, staged) {
const list = el("ul", "options");
const name = "menu-" + item.id;
for (const o of item.options || []) {
for (const [i, o] of (item.options || []).entries()) {
const picked = staged && staged.k === o.k;
const li = el("li", "option" + (picked ? " is-picked" : ""));
const label = el("label");
@@ -4379,7 +4469,13 @@ function buildMenu(card, item, staged) {
const radio = el("input");
radio.type = "radio";
radio.name = name;
// The same id buildChoice gives its radios: withFocus finds the focused
// input by id after the render this change() sets off, and without one a
// keyboard user arrowing through the menu lands on <body> every time.
radio.id = optionId(item, o, i);
radio.value = o.k;
radio.checked = Boolean(picked);
radio.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
const body = el("div", "option-body");
const head = el("div", "option-label");
@@ -5276,20 +5372,30 @@ function renderAside() {
)
);
}
// A note that has been sent but not yet picked up: marked as waiting, so the
// send is seen to have gone, until the agent replies. The server writes the
// note into the thread as it arrives; a session from before that has only
// `sentNote`, which gets a box of its own below.
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
let waitingShown = false;
for (const m of thread) {
const box = el("div", "msg " + (m.who === "user" ? "you" : ""));
const mine = threadWho(m) === "user";
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
if (pending) waitingShown = true;
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
const who = el("div", "msg-who");
who.appendChild(el("span", null, m.who === "user" ? "You" : "Plan2Code"));
if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
box.appendChild(who);
box.appendChild(md(m.text, "md"));
const text = threadText(m);
if (text) box.appendChild(md(text, "md"));
const tray = mine ? sentAttachments(m) : null;
if (tray) box.appendChild(tray);
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) {
if (waiting && !waitingShown) {
const box = el("div", "msg you pending");
const who = el("div", "msg-who");
who.appendChild(el("span", null, "You"));
@@ -5589,7 +5695,10 @@ async function attachFiles(itemId, files) {
const taken = wanted.slice(0, room);
// One banner at a time, so every refusal goes into it, each by name.
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
if (taken.length < wanted.length) said.push(chat ? "Up to 5 attachments per question." : "Up to 5 attachments per note.");
if (taken.length < wanted.length)
said.push(
chat ? `Up to ${CHAT_MAX_ATTACHMENTS} attachments per question.` : `Up to ${MAX_ATTACHMENTS} attachments per note.`
);
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
await Promise.all(
taken.map(async (file) => {
@@ -6439,6 +6548,10 @@ async function goHome() {
$("home-modal").close();
} catch (err) {
$("home-modal").close();
// The server is holding an uncollected result: Send, Home and Stop all
// need to read as busy until the frame or the ping says otherwise, same
// as send() and sendAfterBuild() do on a 409.
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
@@ -6499,6 +6612,7 @@ async function stopSession() {
stoppingHidden = false;
} catch (err) {
$("stop-modal").close();
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
@@ -6653,7 +6767,6 @@ function markSent({ sentIds, sentNotes = {}, summaries, values }) {
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
}
local.staged = {};
local.sentAt = Date.now();
save();
}
@@ -6706,7 +6819,7 @@ const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", d
// something the agent never hears.
function tokenFor(item, v) {
const map = item.token || {};
if (v.skipped) return "skip";
if (v.skipped) return v.text ? `skip; ${v.text}` : "skip";
const parts = [];
if (v.k) parts.push(map[v.k] || v.k);
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
@@ -6938,14 +7051,14 @@ function renderAbout() {
let helpBuilt = false;
async function renderHelpVersion() {
const el = $("help-version");
const slot = $("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;
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
slot.hidden = !version;
} catch {
el.hidden = true;
slot.hidden = true;
}
}
@@ -7053,6 +7166,7 @@ function openHelpOn(id) {
}
$("btn-home").addEventListener("click", openHomeConfirm);
$("update-done").addEventListener("click", () => $("update-modal").close());
$("home-cancel").addEventListener("click", () => $("home-modal").close());
$("home-go").addEventListener("click", goHome);
$("btn-stop").addEventListener("click", openStopConfirm);
@@ -7132,6 +7246,7 @@ $("btn-looks").addEventListener("click", () => {
});
$("looks-done").addEventListener("click", () => $("looks-modal").close());
$("looks-modal").addEventListener("close", () => {
resetCleanup();
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
});
$("looks-reset").addEventListener("click", () => {
@@ -7278,6 +7393,111 @@ $("models-reset").addEventListener("click", () => {
renderModels();
});
// Cleanup: the server works out what in ~/.plan2code is not needed and
// shows it first; Delete these sends back only the ids it was shown, and the
// server re-checks every one before removing it.
let cleanupFound = null;
// Bumped by every scan, delete and reset: a response from an older one is
// dropped, so a scan still in flight when Preferences closes cannot refill it.
let cleanupGen = 0;
const CLEANUP_SHOWN = 8;
function setCleanupStatus(text, isError) {
const status = $("cleanup-status");
status.textContent = text;
status.classList.toggle("error", Boolean(isError));
}
function cleanupLabel(item) {
if (item.where === "session") return "Session " + item.name;
const where = item.where === "root" ? "~/.plan2code/" : "~/.plan2code/console/";
return where + item.name + (item.kind === "folder" ? "/" : "");
}
function cleanupSummary(items, bytes) {
const sessions = items.filter((i) => i.where === "session").length;
const strays = items.length - sessions;
const parts = [];
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
return parts.join(", ") + " · " + formatBytes(bytes);
}
function resetCleanup() {
cleanupGen++;
cleanupFound = null;
$("cleanup-list").replaceChildren();
$("cleanup-delete").hidden = true;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
setCleanupStatus("", false);
}
function renderCleanup() {
const list = $("cleanup-list");
list.replaceChildren();
const items = (cleanupFound && cleanupFound.items) || [];
$("cleanup-delete").hidden = !items.length;
if (!items.length) return;
const rows = (some) => some.map((item) => {
const row = el("div", "cleanup-row");
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", formatBytes(item.bytes)));
return row;
});
list.append(el("p", "cleanup-summary", cleanupSummary(items, cleanupFound.bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
if (items.length > CLEANUP_SHOWN) {
const more = el("details", "cleanup-more");
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
list.appendChild(more);
}
}
async function scanCleanup() {
const gen = ++cleanupGen;
$("cleanup-scan").disabled = true;
$("cleanup-delete").disabled = true;
setCleanupStatus("Looking…", false);
const { status, body } = await postJson("/cleanup", { scan: true });
if (gen !== cleanupGen) return;
$("cleanup-scan").disabled = false;
$("cleanup-delete").disabled = false;
if (status !== 200 || !body.ok) {
cleanupFound = null;
renderCleanup();
return setCleanupStatus(status ? body.error || "Could not look." : "Plan2Code isn't reachable.", true);
}
cleanupFound = { items: body.items || [], bytes: body.bytes || 0 };
renderCleanup();
// Left in the status line, not cleared: it is the live region, so this is
// what a screen reader hears when the scan finishes.
const found = cleanupFound.items.length;
setCleanupStatus(found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.", false);
}
async function deleteCleanup() {
if (!cleanupFound || !cleanupFound.items.length) return;
const gen = ++cleanupGen;
$("cleanup-delete").disabled = true;
$("cleanup-scan").disabled = true;
setCleanupStatus("Deleting…", false);
const { status, body } = await postJson("/cleanup", { delete: cleanupFound.items.map((i) => i.id) });
if (gen !== cleanupGen) return;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
if (status !== 200 || !body.ok) {
return setCleanupStatus(status ? body.error || "Could not delete." : "Plan2Code isn't reachable.", true);
}
const removed = (body.removed || []).length;
const failed = (body.failed || []).length;
cleanupFound = null;
renderCleanup();
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
setCleanupStatus(failed ? done + " " + failed + " could not be removed." : done, Boolean(failed));
}
$("cleanup-scan").addEventListener("click", scanCleanup);
$("cleanup-delete").addEventListener("click", deleteCleanup);
$("btn-brief").addEventListener("click", openBrief);
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
$("brief-go").addEventListener("click", sendBrief);
@@ -1291,6 +1291,14 @@
come back, and you can change your role any time from the swatch
button.
</p>
<h4>When an update is out</h4>
<p>
When a newer Plan2Code release is out, the dashboard shows
<strong>UPDATE AVAILABLE</strong> at the top. Click it for the command
to run in your terminal; × hides it until the next
<code>/plan2code</code>. The version at the bottom of Help links to
the Releases page.
</p>
<h4>The cards</h4>
<p>They come in three groups.</p>
<p><strong>First, the project</strong></p>
@@ -1845,6 +1853,15 @@
joining the strip. Keep only the ones you want; ticking a box plays
its sound.
</li>
<li>
<strong>Cleanup</strong>: <strong>Find files to clean up</strong>
lists what Plan2Code doesn't need in your
<code>~/.plan2code</code> folder: sessions nobody has opened for
30 days, and files or folders that ended up there by mistake. It
shows each one with its size, and <strong>Delete these</strong>
removes exactly that list. Your preferences, saved folders, models,
the launcher and the session you are in always stay.
</li>
<li>
<strong>Back to default</strong> puts everything back as it was, and
sets Role back to Not set.
@@ -1983,6 +2000,16 @@
</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-cleanup">
<legend>Cleanup</legend>
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
<div class="models-actions">
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
<button type="button" class="btn small danger" id="cleanup-delete" hidden>Delete these</button>
<span class="help" id="cleanup-status" role="status"></span>
</div>
</fieldset>
<fieldset class="modal-ranges looks-models">
<legend>Models</legend>
<div class="models-tabs" role="group" aria-label="Which agent">
@@ -2181,6 +2208,24 @@
</div>
</dialog>
<!-- Opened from the dashboard's UPDATE AVAILABLE banner. The versions and
the copy row are filled by app.js; the update itself runs in a
terminal, never from this page. -->
<dialog class="modal" id="update-modal" aria-labelledby="update-title">
<h2 id="update-title">A new Plan2Code is available</h2>
<p class="modal-blurb" id="update-versions"></p>
<ol class="update-steps">
<li>
Run this in your terminal (not in this page or your agent):
<div class="update-command" id="update-command"></div>
</li>
<li>When it finishes, close this console and start <code>plan2code</code> again.</li>
</ol>
<div class="modal-actions">
<button type="button" class="btn primary" id="update-done">Close</button>
</div>
</dialog>
<footer class="footer">
<div class="footer-summary" id="footer-summary" aria-live="polite">
Nothing to send yet.
@@ -5,7 +5,10 @@
// popover; this file owns the rules. No DOM access at module scope and no
// imports: the page and `node --test` both import this file.
const NAME_CHAR = /[a-z0-9-]/;
// Uppercase too: "@Repo" must still name @repo — names are forced lowercase
// by the workspace rules, and a query typed with a capital otherwise matches
// nothing and opens no suggestions at all.
const NAME_CHAR = /[a-z0-9-]/i;
const MAX_MATCHES = 6;
/**
@@ -23,11 +26,13 @@ export function mentionAt(text, caret) {
}
// Names starting with the query first, then names containing it, in the
// order given, at most six.
// order given, at most six. Case-folded: folder names are lowercase by rule,
// and "@Repo" should still find @repo rather than claim nothing matches.
export function matchNames(names, query) {
const q = String(query || "");
const prefix = names.filter((n) => n.startsWith(q));
const inside = names.filter((n) => !n.startsWith(q) && n.includes(q));
const q = String(query || "").toLowerCase();
const fold = (n) => String(n).toLowerCase();
const prefix = names.filter((n) => fold(n).startsWith(q));
const inside = names.filter((n) => !fold(n).startsWith(q) && fold(n).includes(q));
return [...prefix, ...inside].slice(0, MAX_MATCHES);
}
@@ -25,12 +25,14 @@ import {
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
UPDATE_CHECK_FILE,
USER_MODELS_FILE,
WORKSPACE_FILE,
appendChat,
appendEvent,
chatForFrame,
checkDocument,
cleanupFindings,
currentConversation,
ensureDir,
fileStamp,
@@ -47,6 +49,7 @@ import {
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
removeCleanup,
remoteWarning,
specKey,
typedCount,
@@ -59,6 +62,7 @@ import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
import { meterView } from "./public/meter.js";
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
import { checkForUpdate } from "./update-check.mjs";
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
const args = parseArgs(process.argv.slice(2));
@@ -611,6 +615,7 @@ function stateFrame(state) {
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
workspace: workspaceView(),
meter: meterView(ledgerEntries()),
...(updateInfo ? { update: updateInfo } : {}),
have: haveKey(),
};
}
@@ -623,7 +628,7 @@ function haveKey() {
ledgerEntries();
return (
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}`
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}`
);
}
@@ -648,6 +653,12 @@ function recordSubmitted(state, actions) {
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) };
// The person's side of the Notes thread. Left to the agent it was never
// written, so a question asked in a note vanished once it was picked up
// and the reply under it answered nothing on the page.
if (item.sentNote.text.trim() || item.sentNote.images.length || item.sentNote.files.length) {
item.thread = [...(Array.isArray(item.thread) ? item.thread : []), { who: "user", ...item.sentNote }];
}
continue;
}
const { i, type, ...rest } = action;
@@ -933,6 +944,38 @@ function pushState() {
if (stateNow) broadcast("state", stateFrame(stateNow));
}
/* --------------------------------------------------------- update check */
// The version this console was installed as: install.js writes version.json
// beside console.mjs; a dev checkout falls back to the repo root's.
function installedVersion() {
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 version;
}
return null;
}
// Filled in once the boot-time check answers; until then, and whenever it
// fails, the frame carries no `update` and the page shows no banner.
let updateInfo = null;
let updateLatest = null;
// Started at boot and never awaited: git may take up to its 10 s limit, and
// nothing the person sees waits on it. The catch is not optional: a throw in
// pushState() would otherwise be an unhandled rejection, which ends the server.
function startUpdateCheck() {
const installed = installedVersion();
if (!installed) return;
checkForUpdate({ installed, cacheFile: UPDATE_CHECK_FILE })
.then((result) => {
updateLatest = result?.latest ?? null;
updateInfo = result?.updateAvailable ? { installed: result.installed, latest: result.latest } : null;
if (updateInfo) pushState();
})
.catch(() => {});
}
let agentSeenAt = Date.now();
function agentLastSeen() {
return new Date(agentSeenAt).toISOString();
@@ -1039,10 +1082,8 @@ const server = http.createServer((req, res) => {
}
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 });
}
const version = installedVersion();
if (version) return json(res, 200, { version, latest: updateLatest });
return json(res, 404, { error: "no version" });
}
@@ -1090,7 +1131,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/draft" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
// Debounced client-side; this is just the durable mirror. Twenty minutes
// of someone's structured answers must not die with a closed tab.
try {
@@ -1115,7 +1156,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/looks" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
// `set` carries only the keys one tab changed, merged onto what is on
// disk, so a tab holding stale settings cannot undo another tab's change.
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
@@ -1141,7 +1182,7 @@ const server = http.createServer((req, res) => {
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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
const { models, error } = cleanModels(body && body.models);
if (error) return json(res, 400, { error });
try {
@@ -1154,6 +1195,24 @@ const server = http.createServer((req, res) => {
});
}
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
// ~/.plan2code; `{ delete: [id] }` removes those of the ids a fresh scan
// still finds. Never this session, never a path the page sent.
if (pathname === "/cleanup" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
if (body && Array.isArray(body.delete)) {
return removeCleanup(body.delete, { skipSid: SID })
.then((done) => json(res, 200, { ok: true, ...done }))
.catch((e) => json(res, 500, { error: String(e.message) }));
}
return cleanupFindings({ skipSid: SID })
.then(({ items, bytes }) => json(res, 200, { ok: true, bytes, items: items.map(({ path: _p, ...item }) => item) }))
.catch((e) => json(res, 500, { error: String(e.message) }));
});
}
if (pathname === "/upload" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
const contentType = String(req.headers["content-type"] || "");
@@ -1260,7 +1319,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/submit" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
if (!body || !Array.isArray(body.actions) || body.actions.length === 0) {
return json(res, 400, { error: "actions must be a non-empty array" });
}
@@ -1361,6 +1420,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/chat" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const state = readState() || {};
const current = currentConversation(chatEntries()).conversation;
@@ -1424,6 +1484,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/chat/decision" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
if (body.decision !== "approve" && body.decision !== "decline") return json(res, 400, { error: "bad" });
if (body.text !== undefined && typeof body.text !== "string") return json(res, 400, { error: "bad" });
@@ -1472,6 +1533,7 @@ const server = http.createServer((req, res) => {
if (Object.hasOwn(workspaceRoutes, pathname) && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
let answer;
try {
@@ -1489,6 +1551,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/workspace/scope" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const spec = typeof body.spec === "string" ? body.spec : "";
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
@@ -1589,15 +1652,19 @@ function readBody(req, cb) {
let tooBig = false;
req.on("data", (c) => {
size += c.length;
// Drain past the cap rather than destroy, exactly like readRaw: a
// destroyed request emits 'close', never 'end' or 'error', so cb would
// never run and the page would see a reset instead of the 413 that names
// the problem.
if (size > MAX_BODY) {
tooBig = true;
req.destroy();
chunks.length = 0;
return;
}
chunks.push(c);
});
req.on("end", () => {
if (tooBig) return cb(new Error("too large"));
if (tooBig) return cb(Object.assign(new Error("too large"), { tooBig: true }));
try {
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
} catch (e) {
@@ -1834,6 +1901,9 @@ function onListening(port) {
bootWorkspace();
} catch {}
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
try {
startUpdateCheck();
} catch {}
try {
process.send?.({ type: "listening", port });
} catch {}
@@ -0,0 +1,138 @@
// Plan2Code Web Console - is a newer Plan2Code release out?
//
// `git ls-remote --tags` needs no API token and no rate-limited REST call,
// rides on the person's own git and proxy setup, and the newest `vX.Y.Z`
// release tag is "latest". The server
// starts this at boot and never waits on it; the answer, failures included, is
// cached for an hour so a burst of sessions asks GitHub once.
//
// Nothing here reads, stores or sends a credential: git authenticates itself,
// with every prompt turned off so a missing login fails fast instead of
// opening a window nobody asked for.
//
// Node built-ins only.
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
export const REPO_URL = "https://github.com/jparkerweb/plan2code.git";
export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
export const CACHE_MS = 60 * 60 * 1000;
const SEMVER = /^\d+\.\d+\.\d+$/;
const TAG_REF = /refs\/tags\/v(\d+\.\d+\.\d+)$/;
/** -1, 0 or 1 comparing two plain X.Y.Z versions numerically; null unless both are X.Y.Z. */
export function compareVersions(a, b) {
if (typeof a !== "string" || typeof b !== "string" || !SEMVER.test(a) || !SEMVER.test(b)) return null;
const x = a.split(".").map(Number);
const y = b.split(".").map(Number);
for (let i = 0; i < 3; i++) {
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
}
return 0;
}
/**
* The highest `vX.Y.Z` tag in `git ls-remote --tags` output, without the `v`.
* Peeled lines (`^{}`) never match, so an annotated tag counts once, and
* pre-releases or other tag names are ignored. Null when nothing matches.
*/
export function latestTag(text) {
if (typeof text !== "string") return null;
let best = null;
for (const line of text.split(/\r?\n/)) {
const m = TAG_REF.exec(line.trim());
if (m && (best === null || compareVersions(m[1], best) > 0)) best = m[1];
}
return best;
}
function readCache(cacheFile, now) {
try {
const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
if (!cached || typeof cached.checkedAt !== "number" || now - cached.checkedAt >= CACHE_MS) return undefined;
return typeof cached.latest === "string" ? cached.latest : null;
} catch {
return undefined;
}
}
function writeCache(cacheFile, data) {
const tmp = cacheFile + "." + process.pid + ".tmp";
try {
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
fs.renameSync(tmp, cacheFile);
} catch {
try {
fs.rmSync(tmp, { force: true });
} catch {}
}
}
/**
* `git ls-remote --tags` against the repo: resolves its stdout, or null when
* git is missing, fails, or is still going after `timeoutMs`. No shell, no
* window, no prompt.
*/
export function runLsRemote({ timeoutMs = 10000 } = {}) {
return new Promise((resolve) => {
let settled = false;
const done = (value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(value);
};
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
if (!process.env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
let child;
try {
child = spawn("git", ["ls-remote", "--tags", REPO_URL], {
shell: false,
windowsHide: true,
stdio: ["ignore", "pipe", "ignore"],
env,
});
} catch {
return resolve(null);
}
const timer = setTimeout(() => {
try {
child.kill();
} catch {}
done(null);
}, timeoutMs);
timer.unref?.();
let out = "";
child.stdout.setEncoding("utf8");
child.stdout.on("data", (chunk) => {
out += chunk;
});
child.on("error", () => done(null));
child.on("close", (code) => done(code === 0 ? out : null));
});
}
/**
* Whether `installed` is behind the newest release: `{ installed, latest,
* updateAvailable }`, or null when either version is unknown. Reuses a cache
* under an hour old, and caches a failed lookup as `latest: null` so it is
* not retried until the hour is up. Never throws.
*/
export async function checkForUpdate({ installed, cacheFile, now = Date.now(), run = runLsRemote }) {
try {
let latest = readCache(cacheFile, now);
if (latest === undefined) {
latest = latestTag(await run());
writeCache(cacheFile, { checkedAt: now, latest });
}
const order = compareVersions(installed, latest);
if (latest === null || order === null) return null;
return { installed, latest, updateAvailable: order < 0 };
} catch {
return null;
}
}
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -243,7 +243,7 @@ summarise it back.
Then, in ONE `post`, do all of:
- mark each answered item `"status": "answered"` and record its `answer`
- add your replies to any comment threads
- reply to every note in that item's `thread` (shape below)
- answer any Quick questions that came with it, in `chat.replies` (see Quick
questions)
- publish the next batch of questions
@@ -251,6 +251,26 @@ Then, in ONE `post`, do all of:
One post is one atomic update, so the page never shows a half-changed state.
### Replying to a note
A `comment` is the person talking to you about that card, often asking
something. It shows in the card's **Notes on this** panel, and so does your
answer:
```jsonc
{ "items": [{ "id": "p4", "thread": [
{ "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." }
] }] }
```
- Every entry is `{ "who": "agent", "text": "<markdown>" }`. `text`, not
`md`: the page reads nothing else. An entry with no `text` is rejected.
- The server writes their note into the thread as it arrives. Do not repeat
it, and send only your new entries: `thread` appends.
- Answer what they asked, in the thread, even when you also change a doc or
re-ask the question. "I've updated the doc" alone leaves the question in the
panel with no answer under it.
### Recording the answer
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
@@ -661,9 +681,17 @@ finish are dropped, so you start on a blank page and post your own. A skill
run inline from another (a quick task's review) keeps the page it was
handed. A
fresh `open` would strand the page the person is watching on the dashboard's
session while your questions went to a page nobody has open. Then run the
skill normally: its Interface question was already answered by being
launched, so start where its real work starts.
session while your questions went to a page nobody has open.
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
> own file-read tool and follow it from the top instead.** Every Plan2Code
> skill below the dashboard ships `disable-model-invocation: true` on
> purpose — it exists to be read and followed inline, not launched as a
> sub-skill — and calling one through a skill-invocation tool errors out and
> strands the hand-off mid-launch.
Its Interface step is already answered by having been launched, so start
where its real work starts.
The menu itself is the page's own list — you never send it. The page knows
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
@@ -829,6 +857,12 @@ know:
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
Post `activity` as each step starts, before its doc or question lands — reading
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
implementation — the same way Review does. A step with no card of its own
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
Finalize".
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
Stopping mid-finalize loses nothing
— the specs are untouched until Step 3's summary write — so a stop's finish
@@ -859,7 +893,7 @@ question or doc lands:
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
merge by `id` (an unknown id is added), and `thread` / `comments` append. Send only
merge by `id` (an unknown id is added), and `thread` appends. Send only
what changed. A whole-file rewrite would put the entire session back into your
context on every turn.
@@ -1239,7 +1273,7 @@ answers were submitted but never picked up.
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` and `comments` **append**: leave out any thread entry you already sent, or the person sees your reply twice. |
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
@@ -48,6 +48,10 @@ export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
// so every session within the hour reuses one lookup.
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
// test run (or a second sandboxed instance) shares one handle directory with
// the real thing, and `stop --all` reaches outside its own world and kills a
@@ -487,9 +491,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks, the folders remembered per project and spec, and the pointer to
// this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
// looks, the folders remembered per project and spec, the pointer to this
// console's directory, and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir", "update-check.json"]);
function isScratchName(name) {
return (
@@ -536,6 +540,148 @@ export async function removeScratch(consoleDir, names) {
return removed;
}
/* ------------------------------------------------------------- cleanup */
// What User Preferences -> Cleanup never removes. The console folder keeps its
// protected files, its sessions dir (old sessions go one by one, by age) and,
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
// console, the launcher (bin/, launcher.json) and the models the person added.
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
// A stray must sit untouched this long before Cleanup lists it. The same
// folders hold files that live for milliseconds -- a held
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
// rename -- and removing one mid-write loses another session's change.
export const STRAY_GRACE_MS = 60 * 60 * 1000;
// Bytes under `p`, never following a symlink: a link counts as itself.
async function diskBytes(p) {
let st;
try {
st = await fs.promises.lstat(p);
} catch {
return 0;
}
if (!st.isDirectory()) return st.size;
let entries;
try {
entries = await fs.promises.readdir(p);
} catch {
return 0;
}
let total = 0;
for (const name of entries) total += await diskBytes(path.join(p, name));
return total;
}
// The newest mtime of anything under `p`, never following a symlink. A folder
// counts by its files, since rewriting a file never touches its folder's
// mtime; an empty folder counts by its own. Anything unreadable on the way
// down answers Infinity, so it reads as just touched and stays.
function newestMtime(p) {
let st;
try {
st = fs.lstatSync(p);
} catch {
return Infinity;
}
if (!st.isDirectory()) return st.mtimeMs;
let entries;
try {
entries = fs.readdirSync(p);
} catch {
return Infinity;
}
if (!entries.length) return st.mtimeMs;
let newest = 0;
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
return newest;
}
function entryKind(entry) {
if (entry.isSymbolicLink()) return "link";
return entry.isDirectory() ? "folder" : "file";
}
function strayEntries(dir, kept, where, now) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return [];
}
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
return entries
.filter((e) => !kept.has(e.name))
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
.filter((e) => settled(e.path));
}
/**
* Everything Cleanup would remove, worked out on the server and never taken
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
* `open` sweeps by, plus every file in the folder that old, so a resumed
* session or a saved draft keeps it), anything at the top of the console folder that is
* not kept, and -- only when the console runs from its default home inside
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
* touched within `STRAY_GRACE_MS` are left for a later scan. A
* console running from another home (tests, dev) never reaches ~/.plan2code.
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
*/
export async function cleanupFindings({
consoleDir = HOME_DIR,
plan2codeDir = PLAN2CODE_DIR,
now = Date.now(),
maxAgeMs = SESSION_MAX_AGE_MS,
skipSid,
} = {}) {
const found = [];
const sessionsDir = path.join(consoleDir, "sessions");
for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) {
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
}
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
}
const items = [];
let bytes = 0;
for (const f of found) {
const size = await diskBytes(f.path);
bytes += size;
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
}
return { items, bytes };
}
/**
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
* worked out afresh first and only ids on it are touched, so a name from the
* page is never a path, and anything that stopped qualifying since the scan
* (a session touched again) stays. A link is unlinked, never followed.
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
*/
export async function removeCleanup(ids, opts = {}) {
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
const { items } = await cleanupFindings(opts);
const removed = [];
const failed = [];
let bytes = 0;
for (const item of items) {
if (!wanted.has(item.id)) continue;
try {
if (item.kind === "link") await fs.promises.unlink(item.path);
else await fs.promises.rm(item.path, { recursive: true, force: true });
removed.push(item.id);
bytes += item.bytes;
} catch {
failed.push(item.id);
}
}
return { removed, bytes, failed };
}
/**
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
* the file's realpath must sit inside the root's, so `../`, an absolute path
@@ -871,7 +1017,7 @@ export function handOff(child, pre) {
/* ----------------------------------------------------------- patch merge */
const APPEND_KEYS = new Set(["thread", "comments"]);
const APPEND_KEYS = new Set(["thread"]);
function isPlainObject(v) {
return v !== null && typeof v === "object" && !Array.isArray(v);
@@ -896,7 +1042,7 @@ function mergeOne(target, patch, where) {
}
// Merge a keyed collection: a known id merges one level, an unknown id appends.
// Named fields are replaced whole; thread/comments append.
// Named fields are replaced whole; thread appends.
function mergeKeyed(current, patchList, idKey, defaults, where) {
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
for (const entry of patchList) {
@@ -955,6 +1101,42 @@ function dropStaleSubmissions(currentItems, before, patchList) {
return merged;
}
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
// borrow the shape of the replies and doc blocks they also write, so `from` /
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
// at all is refused. The person's own notes are recorded by the server when
// they send, so an agent that echoes one back is not shown it twice.
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
function normalizeThreads(patchList, currentItems) {
return patchList.map((entry) => {
if (!isPlainObject(entry) || entry.thread == null) return entry;
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
const said = new Set(
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
);
const thread = [];
for (const m of entry.thread) {
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
guard(m, "thread");
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
if (!key) {
throw new Error(
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
);
}
const { from, role, md, body, content, ...rest } = m;
const who = (m.who || from || role) === "user" ? "user" : "agent";
const text = m[key];
if (who === "user" && said.has(text.trim())) continue;
thread.push({ ...rest, who, text });
}
return { ...entry, thread };
});
}
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
@@ -996,7 +1178,7 @@ export function applyPatch(state, patch) {
break;
case "items":
if (!Array.isArray(v)) throw new Error('"items" must be an array');
next.items = dropStaleSubmissions(next.items, state.items, v);
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
break;
case "topics":
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
@@ -1048,15 +1230,11 @@ function stampTimes(before, next) {
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
}
for (const list of [next.items, next.docs]) {
if (!Array.isArray(list)) continue;
for (const entry of list) {
if (Array.isArray(next.items)) {
for (const entry of next.items) {
if (Array.isArray(entry.thread)) {
for (const m of entry.thread) if (!m.at) m.at = now;
}
if (Array.isArray(entry.comments)) {
for (const m of entry.comments) if (!m.at) m.at = now;
}
}
}
if (Array.isArray(next.docs)) {
@@ -1289,7 +1467,10 @@ 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, sentNote, ...rest }) => rest);
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
...rest,
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
}));
const prose =
JSON.stringify(authored) +
JSON.stringify(state.docs || []) +
@@ -65,7 +65,7 @@ export function submittedAwaiting(item) {
if (!s || typeof s !== "object") return null;
if (item.answer && typeof item.answer === "object") return null;
const thread = Array.isArray(item.thread) ? item.thread : [];
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
return replied ? null : s;
}
@@ -74,17 +74,33 @@ export function submittedAwaiting(item) {
* 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.
* Any agent message from the send onwards, or one with no clock to compare,
* means it has been picked up. The person's own entries never count: the
* server writes their note into the thread as it arrives.
*/
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));
const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at));
return picked ? null : n;
}
/**
* Who said a thread entry and what they said. The contract is `{ who, text }`
* and the server lifts anything else into it, but sessions written before that
* hold `{ from, md }` replies, which would otherwise draw as empty bubbles.
*/
export function threadWho(m) {
return m && (m.who || m.from || m.role) === "user" ? "user" : "agent";
}
export function threadText(m) {
if (!m) return "";
for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k];
return "";
}
/* -------------------------------------------------------------- labels */
export function optionLabel(item, k) {
@@ -23,6 +23,9 @@
--warn-soft: #fbe7e3;
--focus: #1f6feb;
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
/* A soft accent halo for the things that want noticing: the update banner
and an enabled Send. Built from --accent, so a picked accent glows too. */
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
@@ -61,6 +64,7 @@
--warn-soft: #34201d;
--focus: #6aa3ff;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
}
}
@@ -85,6 +89,7 @@
--warn-soft: #34201d;
--focus: #6aa3ff;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
}
* { box-sizing: border-box; }
@@ -1097,10 +1102,11 @@ h1 {
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
the tiny ring, left of the label. */
.view-tab .tab-spin {
the tiny ring, left of the label. The extra .spinner is for specificity:
.spinner.tiny comes later and zeroes the margin otherwise. */
.view-tab .spinner.tab-spin {
display: inline-block;
margin-right: 6px;
margin-right: 7px;
vertical-align: -1px;
}
@@ -1657,11 +1663,13 @@ input[type="text"].invalid { border-color: var(--warn); }
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
/* Send breathes while there is something to send: a soft accent ring that
spreads and fades. Off under reduced motion, below. */
/* Send glows and breathes while there is something to send: the steady
--glow, plus a soft accent ring that spreads and fades. The ring is off
under reduced motion, below; the glow stays. */
#btn-send:not(:disabled) { box-shadow: var(--glow); }
@keyframes send-pulse {
0% { box-shadow: 0 0 0 0 var(--accent-line); }
100% { box-shadow: 0 0 0 6px transparent; }
0% { box-shadow: var(--glow), 0 0 0 0 var(--accent-line); }
100% { box-shadow: var(--glow), 0 0 0 6px transparent; }
}
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
@@ -2219,6 +2227,7 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
.modal.help[open] { display: flex; }
.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-version a { color: inherit; }
.help-layout {
display: grid;
@@ -2668,6 +2677,74 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
border-left-width: 4px;
color: var(--ink);
}
/* A newer release: the same slot, in the accent, with the label as the way
into the update modal and a small × that hides it for this session. */
.dash-nudge.update-banner {
position: relative;
padding-left: 40px;
padding-right: 40px;
border-left-width: 4px;
border-left-color: var(--accent-line);
color: var(--ink);
box-shadow: var(--glow);
}
.update-banner-open {
flex: 1 1 16em;
padding: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
font-weight: 600;
letter-spacing: 0.02em;
text-align: center;
cursor: pointer;
}
.update-banner-open:hover { text-decoration: underline; }
/* Pinned to the right edge, out of the flow, so the label centres on the
whole banner rather than on what the × leaves of it. */
.update-banner-dismiss {
position: absolute;
top: 50%;
right: 10px;
transform: translateY(-50%);
padding: 0 6px;
border: 0;
border-radius: var(--radius);
background: none;
color: inherit;
font: inherit;
font-size: 16px;
line-height: 1;
cursor: pointer;
}
.update-banner-dismiss:hover { background: var(--accent-line); }
/* Wide enough that the update command sits on one line beside Copy; a
narrow window still wraps it rather than overflowing. */
#update-modal { max-width: 720px; }
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
.update-steps li { margin: 4px 0; }
/* The hand-off copy row, in the modal's first step: the command and its Copy
side by side. */
.update-command {
margin: 6px 0 4px;
display: flex;
align-items: stretch;
gap: 10px;
flex-wrap: wrap;
}
.update-command code {
flex: 1 1 260px;
min-width: 0;
font: 13px/1.5 var(--mono);
color: var(--ink);
background: var(--panel);
border: 1px solid var(--rule-2);
border-radius: 8px;
padding: 10px 12px;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
.dash-working {
@@ -3394,6 +3471,18 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.models-actions .help.error { color: var(--danger, #d64545); }
/* User Preferences: Cleanup's list of what would go, shown before anything
is deleted. */
.cleanup-list { display: grid; gap: 4px; max-height: 200px; overflow: auto; font-size: 0.88em; }
.cleanup-list:empty { display: none; }
.cleanup-summary { margin: 0 0 2px; font-weight: 600; }
.cleanup-row { display: flex; justify-content: space-between; gap: 12px; }
.cleanup-row span:first-child { min-width: 0; overflow-wrap: anywhere; font-family: var(--mono); }
.cleanup-size { flex: none; color: var(--ink-3); }
.cleanup-more { display: grid; gap: 4px; }
.cleanup-more summary { cursor: pointer; color: var(--ink-2); }
#cleanup-delete[hidden] { display: none; }
/* 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 {
@@ -66,6 +66,8 @@ import {
submittedAwaiting,
noteAwaiting,
suggestionFrom,
threadText,
threadWho,
THUMB_EDGE,
turnGate,
verdictText,
@@ -446,6 +448,10 @@ document.addEventListener("click", (e) => {
const GONE_AFTER_MS = 8000;
// Named so a reconnect can clear only THIS banner: a bare banner(null) would
// wipe an unrelated warning that landed while the page was gone (an upload
// failure, a refused send).
const GONE_BANNER = "Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.";
const WORKING_GRACE_MS = 5 * 60 * 1000;
// Two minutes with the agent mid-turn, three when it is merely meant to be
// listening. The difference is the cost of being wrong: a working agent that
@@ -521,6 +527,9 @@ let chatFrame = null;
// sends them.
let wsFrame = null;
let meterFrame = null;
// The frame's update ({ installed, latest }), present only when a newer
// release is out; null otherwise.
let updateFrame = null;
let chatDot = false;
let chatSending = false;
let chatResetting = false;
@@ -566,7 +575,6 @@ function fresh() {
drafts: {},
images: {},
sent: {},
sentAt: null,
stopping: null,
afterBuild: null,
homeward: null,
@@ -870,10 +878,12 @@ function adopt(body) {
chatFrame = body.chat || null;
if (body.workspace) wsFrame = body.workspace;
if (body.meter) meterFrame = body.meter;
// Always replaced: an absent key means no update.
updateFrame = body.update || null;
lastContact = Date.now();
if (gone) {
gone = false;
banner(null);
if ($("banner").textContent === GONE_BANNER) banner(null);
}
if (firstLoad) {
load();
@@ -1016,7 +1026,9 @@ function adopt(body) {
render();
if ($("workspace-modal").open) renderWorkspace();
tellFolderIssues();
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow) loadOverview();
// The Overview tab's file changes under a build, so a tab you are watching
// refetches on every new frame too, not only on the click that opened it.
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow || view === "overview") loadOverview();
if (announce) showArrival(announce);
// New entries land at the bottom of the rail. Gliding down to them beats
// leaving the list parked where it was while it grew underneath.
@@ -1149,15 +1161,12 @@ function markGone() {
// of the server means there, and a banner promising a reconnect would
// argue with it.
if (!finish() && !stopInProgress()) {
banner(
"Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.",
"warn"
);
banner(GONE_BANNER, "warn");
}
render();
} else if (!bad && gone) {
gone = false;
banner(null);
if ($("banner").textContent === GONE_BANNER) banner(null);
render();
}
}
@@ -1182,7 +1191,6 @@ function connect() {
} catch {}
});
es.addEventListener("submitted", (e) => {
local.sentAt = Date.now();
// Drop only what was actually sent.
//
// This event fires for a send from ANY tab of this session, which is why it
@@ -1799,14 +1807,19 @@ async function sendBrief() {
reply: briefPhrase(choice.range),
}),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
$("brief-modal").close();
banner("Asked for a brief. It will appear as a tab when it is written.", "good");
setTimeout(() => banner(null), 5000);
pendingResult = true;
render();
} catch {
why.textContent = "That did not go through. Try again in a moment.";
} catch (err) {
if (err && err.pending) pendingResult = true;
why.textContent =
err && err.pending
? "Your last answers are still being picked up. Try again in a moment."
: "That did not go through. Try again in a moment.";
} finally {
go.disabled = false;
go.textContent = "Write the brief";
@@ -2515,6 +2528,51 @@ function roleNudge() {
return nudge;
}
// × on the update banner hides it for this console session only, and only
// for the release it named. Blocked storage means "not dismissed".
function updateDismissKey() {
try {
return "p2c-update-dismissed:" + S.sid;
} catch {
return "p2c-update-dismissed:";
}
}
function updateDismissed() {
try {
return sessionStorage.getItem(updateDismissKey()) === updateFrame.latest;
} catch {
return false;
}
}
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
const UPDATE_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
function releasesLink(text) {
const a = el("a", null, text);
a.href = RELEASES_URL;
a.target = "_blank";
a.rel = "noopener noreferrer";
return a;
}
function openUpdateModal() {
if (!updateFrame) return;
const versions = $("update-versions");
versions.replaceChildren(
document.createTextNode("Version "),
releasesLink("v" + updateFrame.latest),
document.createTextNode(" is out — you have "),
el("code", null, updateFrame.installed),
document.createTextNode(".")
);
const row = $("update-command");
const code = el("code", null, UPDATE_COMMAND);
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
$("update-modal").showModal();
}
function renderDashboard(main) {
maybeWake();
const menu = (S && S.menu) || {};
@@ -2526,6 +2584,25 @@ function renderDashboard(main) {
warn.setAttribute("role", "status");
wrap.appendChild(warn);
}
// Built here only, so no other workflow's page ever shows it.
if (updateFrame && !updateDismissed()) {
const notice = el("div", "dash-nudge update-banner");
notice.setAttribute("role", "status");
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + updateFrame.latest);
open.type = "button";
open.addEventListener("click", openUpdateModal);
const dismiss = el("button", "update-banner-dismiss", "×");
dismiss.type = "button";
dismiss.setAttribute("aria-label", "Dismiss until next time");
dismiss.addEventListener("click", () => {
try {
sessionStorage.setItem(updateDismissKey(), updateFrame.latest);
} catch {}
render();
});
notice.append(open, dismiss);
wrap.appendChild(notice);
}
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
if (typeof menu.note === "string" && menu.note.trim()) {
@@ -3223,7 +3300,11 @@ document.addEventListener("keydown", cancelSkipMove, true);
function skipAndMoveOn(id) {
cancelSkipMove();
local.skipFlash = id;
stage(id, { type: "skip", skipped: true });
// A note already typed goes along: skipping the question is not retracting
// the comment. Dropping it would leave the text in the box but out of the
// send, which looks kept and is not.
const cur = local.staged[id];
stage(id, { type: "skip", skipped: true, ...(cur && cur.text ? { text: cur.text } : {}) });
skipTimer = setTimeout(() => {
skipTimer = null;
local.skipFlash = null;
@@ -3340,19 +3421,24 @@ function renderWaiting(main) {
}
pane.appendChild(title);
pane.appendChild(el("p", null, doing));
const ask = "If Plan2Code needs you, the question appears here on its own.";
if (!docs().length) {
pane.appendChild(el("p", null, "If Plan2Code needs you, the question appears here on its own."));
pane.appendChild(el("p", null, ask));
return;
}
// "Task" and the tasks tab's own name both open that tab, so the pointer is
// one click from what it points at. A build posts it as `phase` ("Phase N
// tasks"), a quick task as `tasks`; with neither the words stay plain.
// tasks"), a quick task as `tasks`. A skill with no task list (Document,
// Plan) has nothing live to follow, so it gets no pointer at all.
const list =
docs().find((d) => d.id === "phase") ||
docs().find((d) => d.id === "tasks") ||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
if (!list) {
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
return;
}
const jump = (word) => {
if (!list) return el("strong", "waiting-jump", word);
const b = el("button", "waiting-jump", word);
b.type = "button";
b.addEventListener("click", () => {
@@ -3366,8 +3452,8 @@ function renderWaiting(main) {
"The tabs above fill in as it goes. You can follow along with live ",
jump("Task"),
" updates in the ",
jump((list && list.title) || "Phase tasks"),
" tab. If Plan2Code needs you, the question appears here on its own."
jump(list.title || "Phase tasks"),
" tab. " + ask
);
pane.appendChild(p);
}
@@ -3505,8 +3591,8 @@ function renderSettled(card, item) {
// would misreport which of the two was the answer.
let prose = text;
if (!prose && !lines.length) {
const mine = (item.thread || []).filter((m) => m.who === "user");
if (mine.length) prose = String(mine[mine.length - 1].text || "").trim();
const mine = (item.thread || []).filter((m) => threadWho(m) === "user");
if (mine.length) prose = threadText(mine[mine.length - 1]).trim();
}
const nothing = !lines.length && !prose;
@@ -4322,6 +4408,10 @@ function buildChecklist(card, item, staged) {
const commitList = (change) => {
const cur = local.staged[item.id];
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
// A tick or a state IS the answer, so it ends a skip staged earlier:
// left in place, `skipped` would collapse the reply to "skip" while the
// card showed ticked steps on their way.
delete next.skipped;
const empty = !(next.done && next.done.length) && !next.state && !next.text;
stage(item.id, empty ? null : next);
};
@@ -4371,7 +4461,7 @@ function buildChecklist(card, item, staged) {
function buildMenu(card, item, staged) {
const list = el("ul", "options");
const name = "menu-" + item.id;
for (const o of item.options || []) {
for (const [i, o] of (item.options || []).entries()) {
const picked = staged && staged.k === o.k;
const li = el("li", "option" + (picked ? " is-picked" : ""));
const label = el("label");
@@ -4379,7 +4469,13 @@ function buildMenu(card, item, staged) {
const radio = el("input");
radio.type = "radio";
radio.name = name;
// The same id buildChoice gives its radios: withFocus finds the focused
// input by id after the render this change() sets off, and without one a
// keyboard user arrowing through the menu lands on <body> every time.
radio.id = optionId(item, o, i);
radio.value = o.k;
radio.checked = Boolean(picked);
radio.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
const body = el("div", "option-body");
const head = el("div", "option-label");
@@ -5276,20 +5372,30 @@ function renderAside() {
)
);
}
// A note that has been sent but not yet picked up: marked as waiting, so the
// send is seen to have gone, until the agent replies. The server writes the
// note into the thread as it arrives; a session from before that has only
// `sentNote`, which gets a box of its own below.
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
let waitingShown = false;
for (const m of thread) {
const box = el("div", "msg " + (m.who === "user" ? "you" : ""));
const mine = threadWho(m) === "user";
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
if (pending) waitingShown = true;
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
const who = el("div", "msg-who");
who.appendChild(el("span", null, m.who === "user" ? "You" : "Plan2Code"));
if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
box.appendChild(who);
box.appendChild(md(m.text, "md"));
const text = threadText(m);
if (text) box.appendChild(md(text, "md"));
const tray = mine ? sentAttachments(m) : null;
if (tray) box.appendChild(tray);
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) {
if (waiting && !waitingShown) {
const box = el("div", "msg you pending");
const who = el("div", "msg-who");
who.appendChild(el("span", null, "You"));
@@ -5589,7 +5695,10 @@ async function attachFiles(itemId, files) {
const taken = wanted.slice(0, room);
// One banner at a time, so every refusal goes into it, each by name.
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
if (taken.length < wanted.length) said.push(chat ? "Up to 5 attachments per question." : "Up to 5 attachments per note.");
if (taken.length < wanted.length)
said.push(
chat ? `Up to ${CHAT_MAX_ATTACHMENTS} attachments per question.` : `Up to ${MAX_ATTACHMENTS} attachments per note.`
);
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
await Promise.all(
taken.map(async (file) => {
@@ -6439,6 +6548,10 @@ async function goHome() {
$("home-modal").close();
} catch (err) {
$("home-modal").close();
// The server is holding an uncollected result: Send, Home and Stop all
// need to read as busy until the frame or the ping says otherwise, same
// as send() and sendAfterBuild() do on a 409.
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
@@ -6499,6 +6612,7 @@ async function stopSession() {
stoppingHidden = false;
} catch (err) {
$("stop-modal").close();
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
@@ -6653,7 +6767,6 @@ function markSent({ sentIds, sentNotes = {}, summaries, values }) {
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
}
local.staged = {};
local.sentAt = Date.now();
save();
}
@@ -6706,7 +6819,7 @@ const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", d
// something the agent never hears.
function tokenFor(item, v) {
const map = item.token || {};
if (v.skipped) return "skip";
if (v.skipped) return v.text ? `skip; ${v.text}` : "skip";
const parts = [];
if (v.k) parts.push(map[v.k] || v.k);
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
@@ -6938,14 +7051,14 @@ function renderAbout() {
let helpBuilt = false;
async function renderHelpVersion() {
const el = $("help-version");
const slot = $("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;
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
slot.hidden = !version;
} catch {
el.hidden = true;
slot.hidden = true;
}
}
@@ -7053,6 +7166,7 @@ function openHelpOn(id) {
}
$("btn-home").addEventListener("click", openHomeConfirm);
$("update-done").addEventListener("click", () => $("update-modal").close());
$("home-cancel").addEventListener("click", () => $("home-modal").close());
$("home-go").addEventListener("click", goHome);
$("btn-stop").addEventListener("click", openStopConfirm);
@@ -7132,6 +7246,7 @@ $("btn-looks").addEventListener("click", () => {
});
$("looks-done").addEventListener("click", () => $("looks-modal").close());
$("looks-modal").addEventListener("close", () => {
resetCleanup();
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
});
$("looks-reset").addEventListener("click", () => {
@@ -7278,6 +7393,111 @@ $("models-reset").addEventListener("click", () => {
renderModels();
});
// Cleanup: the server works out what in ~/.plan2code is not needed and
// shows it first; Delete these sends back only the ids it was shown, and the
// server re-checks every one before removing it.
let cleanupFound = null;
// Bumped by every scan, delete and reset: a response from an older one is
// dropped, so a scan still in flight when Preferences closes cannot refill it.
let cleanupGen = 0;
const CLEANUP_SHOWN = 8;
function setCleanupStatus(text, isError) {
const status = $("cleanup-status");
status.textContent = text;
status.classList.toggle("error", Boolean(isError));
}
function cleanupLabel(item) {
if (item.where === "session") return "Session " + item.name;
const where = item.where === "root" ? "~/.plan2code/" : "~/.plan2code/console/";
return where + item.name + (item.kind === "folder" ? "/" : "");
}
function cleanupSummary(items, bytes) {
const sessions = items.filter((i) => i.where === "session").length;
const strays = items.length - sessions;
const parts = [];
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
return parts.join(", ") + " · " + formatBytes(bytes);
}
function resetCleanup() {
cleanupGen++;
cleanupFound = null;
$("cleanup-list").replaceChildren();
$("cleanup-delete").hidden = true;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
setCleanupStatus("", false);
}
function renderCleanup() {
const list = $("cleanup-list");
list.replaceChildren();
const items = (cleanupFound && cleanupFound.items) || [];
$("cleanup-delete").hidden = !items.length;
if (!items.length) return;
const rows = (some) => some.map((item) => {
const row = el("div", "cleanup-row");
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", formatBytes(item.bytes)));
return row;
});
list.append(el("p", "cleanup-summary", cleanupSummary(items, cleanupFound.bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
if (items.length > CLEANUP_SHOWN) {
const more = el("details", "cleanup-more");
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
list.appendChild(more);
}
}
async function scanCleanup() {
const gen = ++cleanupGen;
$("cleanup-scan").disabled = true;
$("cleanup-delete").disabled = true;
setCleanupStatus("Looking…", false);
const { status, body } = await postJson("/cleanup", { scan: true });
if (gen !== cleanupGen) return;
$("cleanup-scan").disabled = false;
$("cleanup-delete").disabled = false;
if (status !== 200 || !body.ok) {
cleanupFound = null;
renderCleanup();
return setCleanupStatus(status ? body.error || "Could not look." : "Plan2Code isn't reachable.", true);
}
cleanupFound = { items: body.items || [], bytes: body.bytes || 0 };
renderCleanup();
// Left in the status line, not cleared: it is the live region, so this is
// what a screen reader hears when the scan finishes.
const found = cleanupFound.items.length;
setCleanupStatus(found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.", false);
}
async function deleteCleanup() {
if (!cleanupFound || !cleanupFound.items.length) return;
const gen = ++cleanupGen;
$("cleanup-delete").disabled = true;
$("cleanup-scan").disabled = true;
setCleanupStatus("Deleting…", false);
const { status, body } = await postJson("/cleanup", { delete: cleanupFound.items.map((i) => i.id) });
if (gen !== cleanupGen) return;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
if (status !== 200 || !body.ok) {
return setCleanupStatus(status ? body.error || "Could not delete." : "Plan2Code isn't reachable.", true);
}
const removed = (body.removed || []).length;
const failed = (body.failed || []).length;
cleanupFound = null;
renderCleanup();
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
setCleanupStatus(failed ? done + " " + failed + " could not be removed." : done, Boolean(failed));
}
$("cleanup-scan").addEventListener("click", scanCleanup);
$("cleanup-delete").addEventListener("click", deleteCleanup);
$("btn-brief").addEventListener("click", openBrief);
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
$("brief-go").addEventListener("click", sendBrief);
@@ -1291,6 +1291,14 @@
come back, and you can change your role any time from the swatch
button.
</p>
<h4>When an update is out</h4>
<p>
When a newer Plan2Code release is out, the dashboard shows
<strong>UPDATE AVAILABLE</strong> at the top. Click it for the command
to run in your terminal; × hides it until the next
<code>/plan2code</code>. The version at the bottom of Help links to
the Releases page.
</p>
<h4>The cards</h4>
<p>They come in three groups.</p>
<p><strong>First, the project</strong></p>
@@ -1845,6 +1853,15 @@
joining the strip. Keep only the ones you want; ticking a box plays
its sound.
</li>
<li>
<strong>Cleanup</strong>: <strong>Find files to clean up</strong>
lists what Plan2Code doesn't need in your
<code>~/.plan2code</code> folder: sessions nobody has opened for
30 days, and files or folders that ended up there by mistake. It
shows each one with its size, and <strong>Delete these</strong>
removes exactly that list. Your preferences, saved folders, models,
the launcher and the session you are in always stay.
</li>
<li>
<strong>Back to default</strong> puts everything back as it was, and
sets Role back to Not set.
@@ -1983,6 +2000,16 @@
</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-cleanup">
<legend>Cleanup</legend>
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
<div class="models-actions">
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
<button type="button" class="btn small danger" id="cleanup-delete" hidden>Delete these</button>
<span class="help" id="cleanup-status" role="status"></span>
</div>
</fieldset>
<fieldset class="modal-ranges looks-models">
<legend>Models</legend>
<div class="models-tabs" role="group" aria-label="Which agent">
@@ -2181,6 +2208,24 @@
</div>
</dialog>
<!-- Opened from the dashboard's UPDATE AVAILABLE banner. The versions and
the copy row are filled by app.js; the update itself runs in a
terminal, never from this page. -->
<dialog class="modal" id="update-modal" aria-labelledby="update-title">
<h2 id="update-title">A new Plan2Code is available</h2>
<p class="modal-blurb" id="update-versions"></p>
<ol class="update-steps">
<li>
Run this in your terminal (not in this page or your agent):
<div class="update-command" id="update-command"></div>
</li>
<li>When it finishes, close this console and start <code>plan2code</code> again.</li>
</ol>
<div class="modal-actions">
<button type="button" class="btn primary" id="update-done">Close</button>
</div>
</dialog>
<footer class="footer">
<div class="footer-summary" id="footer-summary" aria-live="polite">
Nothing to send yet.
@@ -5,7 +5,10 @@
// popover; this file owns the rules. No DOM access at module scope and no
// imports: the page and `node --test` both import this file.
const NAME_CHAR = /[a-z0-9-]/;
// Uppercase too: "@Repo" must still name @repo — names are forced lowercase
// by the workspace rules, and a query typed with a capital otherwise matches
// nothing and opens no suggestions at all.
const NAME_CHAR = /[a-z0-9-]/i;
const MAX_MATCHES = 6;
/**
@@ -23,11 +26,13 @@ export function mentionAt(text, caret) {
}
// Names starting with the query first, then names containing it, in the
// order given, at most six.
// order given, at most six. Case-folded: folder names are lowercase by rule,
// and "@Repo" should still find @repo rather than claim nothing matches.
export function matchNames(names, query) {
const q = String(query || "");
const prefix = names.filter((n) => n.startsWith(q));
const inside = names.filter((n) => !n.startsWith(q) && n.includes(q));
const q = String(query || "").toLowerCase();
const fold = (n) => String(n).toLowerCase();
const prefix = names.filter((n) => fold(n).startsWith(q));
const inside = names.filter((n) => !fold(n).startsWith(q) && fold(n).includes(q));
return [...prefix, ...inside].slice(0, MAX_MATCHES);
}
@@ -25,12 +25,14 @@ import {
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
UPDATE_CHECK_FILE,
USER_MODELS_FILE,
WORKSPACE_FILE,
appendChat,
appendEvent,
chatForFrame,
checkDocument,
cleanupFindings,
currentConversation,
ensureDir,
fileStamp,
@@ -47,6 +49,7 @@ import {
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
removeCleanup,
remoteWarning,
specKey,
typedCount,
@@ -59,6 +62,7 @@ import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
import { meterView } from "./public/meter.js";
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
import { checkForUpdate } from "./update-check.mjs";
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
const args = parseArgs(process.argv.slice(2));
@@ -611,6 +615,7 @@ function stateFrame(state) {
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
workspace: workspaceView(),
meter: meterView(ledgerEntries()),
...(updateInfo ? { update: updateInfo } : {}),
have: haveKey(),
};
}
@@ -623,7 +628,7 @@ function haveKey() {
ledgerEntries();
return (
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}`
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}`
);
}
@@ -648,6 +653,12 @@ function recordSubmitted(state, actions) {
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) };
// The person's side of the Notes thread. Left to the agent it was never
// written, so a question asked in a note vanished once it was picked up
// and the reply under it answered nothing on the page.
if (item.sentNote.text.trim() || item.sentNote.images.length || item.sentNote.files.length) {
item.thread = [...(Array.isArray(item.thread) ? item.thread : []), { who: "user", ...item.sentNote }];
}
continue;
}
const { i, type, ...rest } = action;
@@ -933,6 +944,38 @@ function pushState() {
if (stateNow) broadcast("state", stateFrame(stateNow));
}
/* --------------------------------------------------------- update check */
// The version this console was installed as: install.js writes version.json
// beside console.mjs; a dev checkout falls back to the repo root's.
function installedVersion() {
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 version;
}
return null;
}
// Filled in once the boot-time check answers; until then, and whenever it
// fails, the frame carries no `update` and the page shows no banner.
let updateInfo = null;
let updateLatest = null;
// Started at boot and never awaited: git may take up to its 10 s limit, and
// nothing the person sees waits on it. The catch is not optional: a throw in
// pushState() would otherwise be an unhandled rejection, which ends the server.
function startUpdateCheck() {
const installed = installedVersion();
if (!installed) return;
checkForUpdate({ installed, cacheFile: UPDATE_CHECK_FILE })
.then((result) => {
updateLatest = result?.latest ?? null;
updateInfo = result?.updateAvailable ? { installed: result.installed, latest: result.latest } : null;
if (updateInfo) pushState();
})
.catch(() => {});
}
let agentSeenAt = Date.now();
function agentLastSeen() {
return new Date(agentSeenAt).toISOString();
@@ -1039,10 +1082,8 @@ const server = http.createServer((req, res) => {
}
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 });
}
const version = installedVersion();
if (version) return json(res, 200, { version, latest: updateLatest });
return json(res, 404, { error: "no version" });
}
@@ -1090,7 +1131,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/draft" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
// Debounced client-side; this is just the durable mirror. Twenty minutes
// of someone's structured answers must not die with a closed tab.
try {
@@ -1115,7 +1156,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/looks" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
// `set` carries only the keys one tab changed, merged onto what is on
// disk, so a tab holding stale settings cannot undo another tab's change.
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
@@ -1141,7 +1182,7 @@ const server = http.createServer((req, res) => {
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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
const { models, error } = cleanModels(body && body.models);
if (error) return json(res, 400, { error });
try {
@@ -1154,6 +1195,24 @@ const server = http.createServer((req, res) => {
});
}
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
// ~/.plan2code; `{ delete: [id] }` removes those of the ids a fresh scan
// still finds. Never this session, never a path the page sent.
if (pathname === "/cleanup" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
if (body && Array.isArray(body.delete)) {
return removeCleanup(body.delete, { skipSid: SID })
.then((done) => json(res, 200, { ok: true, ...done }))
.catch((e) => json(res, 500, { error: String(e.message) }));
}
return cleanupFindings({ skipSid: SID })
.then(({ items, bytes }) => json(res, 200, { ok: true, bytes, items: items.map(({ path: _p, ...item }) => item) }))
.catch((e) => json(res, 500, { error: String(e.message) }));
});
}
if (pathname === "/upload" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
const contentType = String(req.headers["content-type"] || "");
@@ -1260,7 +1319,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/submit" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
if (!body || !Array.isArray(body.actions) || body.actions.length === 0) {
return json(res, 400, { error: "actions must be a non-empty array" });
}
@@ -1361,6 +1420,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/chat" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const state = readState() || {};
const current = currentConversation(chatEntries()).conversation;
@@ -1424,6 +1484,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/chat/decision" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
if (body.decision !== "approve" && body.decision !== "decline") return json(res, 400, { error: "bad" });
if (body.text !== undefined && typeof body.text !== "string") return json(res, 400, { error: "bad" });
@@ -1472,6 +1533,7 @@ const server = http.createServer((req, res) => {
if (Object.hasOwn(workspaceRoutes, pathname) && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
let answer;
try {
@@ -1489,6 +1551,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/workspace/scope" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const spec = typeof body.spec === "string" ? body.spec : "";
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
@@ -1589,15 +1652,19 @@ function readBody(req, cb) {
let tooBig = false;
req.on("data", (c) => {
size += c.length;
// Drain past the cap rather than destroy, exactly like readRaw: a
// destroyed request emits 'close', never 'end' or 'error', so cb would
// never run and the page would see a reset instead of the 413 that names
// the problem.
if (size > MAX_BODY) {
tooBig = true;
req.destroy();
chunks.length = 0;
return;
}
chunks.push(c);
});
req.on("end", () => {
if (tooBig) return cb(new Error("too large"));
if (tooBig) return cb(Object.assign(new Error("too large"), { tooBig: true }));
try {
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
} catch (e) {
@@ -1834,6 +1901,9 @@ function onListening(port) {
bootWorkspace();
} catch {}
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
try {
startUpdateCheck();
} catch {}
try {
process.send?.({ type: "listening", port });
} catch {}
@@ -0,0 +1,138 @@
// Plan2Code Web Console - is a newer Plan2Code release out?
//
// `git ls-remote --tags` needs no API token and no rate-limited REST call,
// rides on the person's own git and proxy setup, and the newest `vX.Y.Z`
// release tag is "latest". The server
// starts this at boot and never waits on it; the answer, failures included, is
// cached for an hour so a burst of sessions asks GitHub once.
//
// Nothing here reads, stores or sends a credential: git authenticates itself,
// with every prompt turned off so a missing login fails fast instead of
// opening a window nobody asked for.
//
// Node built-ins only.
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
export const REPO_URL = "https://github.com/jparkerweb/plan2code.git";
export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
export const CACHE_MS = 60 * 60 * 1000;
const SEMVER = /^\d+\.\d+\.\d+$/;
const TAG_REF = /refs\/tags\/v(\d+\.\d+\.\d+)$/;
/** -1, 0 or 1 comparing two plain X.Y.Z versions numerically; null unless both are X.Y.Z. */
export function compareVersions(a, b) {
if (typeof a !== "string" || typeof b !== "string" || !SEMVER.test(a) || !SEMVER.test(b)) return null;
const x = a.split(".").map(Number);
const y = b.split(".").map(Number);
for (let i = 0; i < 3; i++) {
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
}
return 0;
}
/**
* The highest `vX.Y.Z` tag in `git ls-remote --tags` output, without the `v`.
* Peeled lines (`^{}`) never match, so an annotated tag counts once, and
* pre-releases or other tag names are ignored. Null when nothing matches.
*/
export function latestTag(text) {
if (typeof text !== "string") return null;
let best = null;
for (const line of text.split(/\r?\n/)) {
const m = TAG_REF.exec(line.trim());
if (m && (best === null || compareVersions(m[1], best) > 0)) best = m[1];
}
return best;
}
function readCache(cacheFile, now) {
try {
const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
if (!cached || typeof cached.checkedAt !== "number" || now - cached.checkedAt >= CACHE_MS) return undefined;
return typeof cached.latest === "string" ? cached.latest : null;
} catch {
return undefined;
}
}
function writeCache(cacheFile, data) {
const tmp = cacheFile + "." + process.pid + ".tmp";
try {
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
fs.renameSync(tmp, cacheFile);
} catch {
try {
fs.rmSync(tmp, { force: true });
} catch {}
}
}
/**
* `git ls-remote --tags` against the repo: resolves its stdout, or null when
* git is missing, fails, or is still going after `timeoutMs`. No shell, no
* window, no prompt.
*/
export function runLsRemote({ timeoutMs = 10000 } = {}) {
return new Promise((resolve) => {
let settled = false;
const done = (value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(value);
};
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
if (!process.env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
let child;
try {
child = spawn("git", ["ls-remote", "--tags", REPO_URL], {
shell: false,
windowsHide: true,
stdio: ["ignore", "pipe", "ignore"],
env,
});
} catch {
return resolve(null);
}
const timer = setTimeout(() => {
try {
child.kill();
} catch {}
done(null);
}, timeoutMs);
timer.unref?.();
let out = "";
child.stdout.setEncoding("utf8");
child.stdout.on("data", (chunk) => {
out += chunk;
});
child.on("error", () => done(null));
child.on("close", (code) => done(code === 0 ? out : null));
});
}
/**
* Whether `installed` is behind the newest release: `{ installed, latest,
* updateAvailable }`, or null when either version is unknown. Reuses a cache
* under an hour old, and caches a failed lookup as `latest: null` so it is
* not retried until the hour is up. Never throws.
*/
export async function checkForUpdate({ installed, cacheFile, now = Date.now(), run = runLsRemote }) {
try {
let latest = readCache(cacheFile, now);
if (latest === undefined) {
latest = latestTag(await run());
writeCache(cacheFile, { checkedAt: now, latest });
}
const order = compareVersions(installed, latest);
if (latest === null || order === null) return null;
return { installed, latest, updateAvailable: order < 0 };
} catch {
return null;
}
}
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"releaseDate": "2026-10-05",
"mode": "utility"
}
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -243,7 +243,7 @@ summarise it back.
Then, in ONE `post`, do all of:
- mark each answered item `"status": "answered"` and record its `answer`
- add your replies to any comment threads
- reply to every note in that item's `thread` (shape below)
- answer any Quick questions that came with it, in `chat.replies` (see Quick
questions)
- publish the next batch of questions
@@ -251,6 +251,26 @@ Then, in ONE `post`, do all of:
One post is one atomic update, so the page never shows a half-changed state.
### Replying to a note
A `comment` is the person talking to you about that card, often asking
something. It shows in the card's **Notes on this** panel, and so does your
answer:
```jsonc
{ "items": [{ "id": "p4", "thread": [
{ "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." }
] }] }
```
- Every entry is `{ "who": "agent", "text": "<markdown>" }`. `text`, not
`md`: the page reads nothing else. An entry with no `text` is rejected.
- The server writes their note into the thread as it arrives. Do not repeat
it, and send only your new entries: `thread` appends.
- Answer what they asked, in the thread, even when you also change a doc or
re-ask the question. "I've updated the doc" alone leaves the question in the
panel with no answer under it.
### Recording the answer
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
@@ -661,9 +681,17 @@ finish are dropped, so you start on a blank page and post your own. A skill
run inline from another (a quick task's review) keeps the page it was
handed. A
fresh `open` would strand the page the person is watching on the dashboard's
session while your questions went to a page nobody has open. Then run the
skill normally: its Interface question was already answered by being
launched, so start where its real work starts.
session while your questions went to a page nobody has open.
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
> own file-read tool and follow it from the top instead.** Every Plan2Code
> skill below the dashboard ships `disable-model-invocation: true` on
> purpose — it exists to be read and followed inline, not launched as a
> sub-skill — and calling one through a skill-invocation tool errors out and
> strands the hand-off mid-launch.
Its Interface step is already answered by having been launched, so start
where its real work starts.
The menu itself is the page's own list — you never send it. The page knows
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
@@ -829,6 +857,12 @@ know:
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
Post `activity` as each step starts, before its doc or question lands — reading
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
implementation — the same way Review does. A step with no card of its own
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
Finalize".
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
Stopping mid-finalize loses nothing
— the specs are untouched until Step 3's summary write — so a stop's finish
@@ -859,7 +893,7 @@ question or doc lands:
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
merge by `id` (an unknown id is added), and `thread` / `comments` append. Send only
merge by `id` (an unknown id is added), and `thread` appends. Send only
what changed. A whole-file rewrite would put the entire session back into your
context on every turn.
@@ -1239,7 +1273,7 @@ answers were submitted but never picked up.
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` and `comments` **append**: leave out any thread entry you already sent, or the person sees your reply twice. |
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
@@ -48,6 +48,10 @@ export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
// so every session within the hour reuses one lookup.
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
// test run (or a second sandboxed instance) shares one handle directory with
// the real thing, and `stop --all` reaches outside its own world and kills a
@@ -487,9 +491,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks, the folders remembered per project and spec, and the pointer to
// this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
// looks, the folders remembered per project and spec, the pointer to this
// console's directory, and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir", "update-check.json"]);
function isScratchName(name) {
return (
@@ -536,6 +540,148 @@ export async function removeScratch(consoleDir, names) {
return removed;
}
/* ------------------------------------------------------------- cleanup */
// What User Preferences -> Cleanup never removes. The console folder keeps its
// protected files, its sessions dir (old sessions go one by one, by age) and,
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
// console, the launcher (bin/, launcher.json) and the models the person added.
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
// A stray must sit untouched this long before Cleanup lists it. The same
// folders hold files that live for milliseconds -- a held
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
// rename -- and removing one mid-write loses another session's change.
export const STRAY_GRACE_MS = 60 * 60 * 1000;
// Bytes under `p`, never following a symlink: a link counts as itself.
async function diskBytes(p) {
let st;
try {
st = await fs.promises.lstat(p);
} catch {
return 0;
}
if (!st.isDirectory()) return st.size;
let entries;
try {
entries = await fs.promises.readdir(p);
} catch {
return 0;
}
let total = 0;
for (const name of entries) total += await diskBytes(path.join(p, name));
return total;
}
// The newest mtime of anything under `p`, never following a symlink. A folder
// counts by its files, since rewriting a file never touches its folder's
// mtime; an empty folder counts by its own. Anything unreadable on the way
// down answers Infinity, so it reads as just touched and stays.
function newestMtime(p) {
let st;
try {
st = fs.lstatSync(p);
} catch {
return Infinity;
}
if (!st.isDirectory()) return st.mtimeMs;
let entries;
try {
entries = fs.readdirSync(p);
} catch {
return Infinity;
}
if (!entries.length) return st.mtimeMs;
let newest = 0;
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
return newest;
}
function entryKind(entry) {
if (entry.isSymbolicLink()) return "link";
return entry.isDirectory() ? "folder" : "file";
}
function strayEntries(dir, kept, where, now) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return [];
}
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
return entries
.filter((e) => !kept.has(e.name))
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
.filter((e) => settled(e.path));
}
/**
* Everything Cleanup would remove, worked out on the server and never taken
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
* `open` sweeps by, plus every file in the folder that old, so a resumed
* session or a saved draft keeps it), anything at the top of the console folder that is
* not kept, and -- only when the console runs from its default home inside
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
* touched within `STRAY_GRACE_MS` are left for a later scan. A
* console running from another home (tests, dev) never reaches ~/.plan2code.
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
*/
export async function cleanupFindings({
consoleDir = HOME_DIR,
plan2codeDir = PLAN2CODE_DIR,
now = Date.now(),
maxAgeMs = SESSION_MAX_AGE_MS,
skipSid,
} = {}) {
const found = [];
const sessionsDir = path.join(consoleDir, "sessions");
for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) {
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
}
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
}
const items = [];
let bytes = 0;
for (const f of found) {
const size = await diskBytes(f.path);
bytes += size;
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
}
return { items, bytes };
}
/**
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
* worked out afresh first and only ids on it are touched, so a name from the
* page is never a path, and anything that stopped qualifying since the scan
* (a session touched again) stays. A link is unlinked, never followed.
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
*/
export async function removeCleanup(ids, opts = {}) {
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
const { items } = await cleanupFindings(opts);
const removed = [];
const failed = [];
let bytes = 0;
for (const item of items) {
if (!wanted.has(item.id)) continue;
try {
if (item.kind === "link") await fs.promises.unlink(item.path);
else await fs.promises.rm(item.path, { recursive: true, force: true });
removed.push(item.id);
bytes += item.bytes;
} catch {
failed.push(item.id);
}
}
return { removed, bytes, failed };
}
/**
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
* the file's realpath must sit inside the root's, so `../`, an absolute path
@@ -871,7 +1017,7 @@ export function handOff(child, pre) {
/* ----------------------------------------------------------- patch merge */
const APPEND_KEYS = new Set(["thread", "comments"]);
const APPEND_KEYS = new Set(["thread"]);
function isPlainObject(v) {
return v !== null && typeof v === "object" && !Array.isArray(v);
@@ -896,7 +1042,7 @@ function mergeOne(target, patch, where) {
}
// Merge a keyed collection: a known id merges one level, an unknown id appends.
// Named fields are replaced whole; thread/comments append.
// Named fields are replaced whole; thread appends.
function mergeKeyed(current, patchList, idKey, defaults, where) {
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
for (const entry of patchList) {
@@ -955,6 +1101,42 @@ function dropStaleSubmissions(currentItems, before, patchList) {
return merged;
}
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
// borrow the shape of the replies and doc blocks they also write, so `from` /
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
// at all is refused. The person's own notes are recorded by the server when
// they send, so an agent that echoes one back is not shown it twice.
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
function normalizeThreads(patchList, currentItems) {
return patchList.map((entry) => {
if (!isPlainObject(entry) || entry.thread == null) return entry;
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
const said = new Set(
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
);
const thread = [];
for (const m of entry.thread) {
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
guard(m, "thread");
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
if (!key) {
throw new Error(
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
);
}
const { from, role, md, body, content, ...rest } = m;
const who = (m.who || from || role) === "user" ? "user" : "agent";
const text = m[key];
if (who === "user" && said.has(text.trim())) continue;
thread.push({ ...rest, who, text });
}
return { ...entry, thread };
});
}
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
@@ -996,7 +1178,7 @@ export function applyPatch(state, patch) {
break;
case "items":
if (!Array.isArray(v)) throw new Error('"items" must be an array');
next.items = dropStaleSubmissions(next.items, state.items, v);
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
break;
case "topics":
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
@@ -1048,15 +1230,11 @@ function stampTimes(before, next) {
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
}
for (const list of [next.items, next.docs]) {
if (!Array.isArray(list)) continue;
for (const entry of list) {
if (Array.isArray(next.items)) {
for (const entry of next.items) {
if (Array.isArray(entry.thread)) {
for (const m of entry.thread) if (!m.at) m.at = now;
}
if (Array.isArray(entry.comments)) {
for (const m of entry.comments) if (!m.at) m.at = now;
}
}
}
if (Array.isArray(next.docs)) {
@@ -1289,7 +1467,10 @@ 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, sentNote, ...rest }) => rest);
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
...rest,
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
}));
const prose =
JSON.stringify(authored) +
JSON.stringify(state.docs || []) +
@@ -65,7 +65,7 @@ export function submittedAwaiting(item) {
if (!s || typeof s !== "object") return null;
if (item.answer && typeof item.answer === "object") return null;
const thread = Array.isArray(item.thread) ? item.thread : [];
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
return replied ? null : s;
}
@@ -74,17 +74,33 @@ export function submittedAwaiting(item) {
* 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.
* Any agent message from the send onwards, or one with no clock to compare,
* means it has been picked up. The person's own entries never count: the
* server writes their note into the thread as it arrives.
*/
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));
const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at));
return picked ? null : n;
}
/**
* Who said a thread entry and what they said. The contract is `{ who, text }`
* and the server lifts anything else into it, but sessions written before that
* hold `{ from, md }` replies, which would otherwise draw as empty bubbles.
*/
export function threadWho(m) {
return m && (m.who || m.from || m.role) === "user" ? "user" : "agent";
}
export function threadText(m) {
if (!m) return "";
for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k];
return "";
}
/* -------------------------------------------------------------- labels */
export function optionLabel(item, k) {
@@ -23,6 +23,9 @@
--warn-soft: #fbe7e3;
--focus: #1f6feb;
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
/* A soft accent halo for the things that want noticing: the update banner
and an enabled Send. Built from --accent, so a picked accent glows too. */
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
@@ -61,6 +64,7 @@
--warn-soft: #34201d;
--focus: #6aa3ff;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
}
}
@@ -85,6 +89,7 @@
--warn-soft: #34201d;
--focus: #6aa3ff;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
}
* { box-sizing: border-box; }
@@ -1097,10 +1102,11 @@ h1 {
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
the tiny ring, left of the label. */
.view-tab .tab-spin {
the tiny ring, left of the label. The extra .spinner is for specificity:
.spinner.tiny comes later and zeroes the margin otherwise. */
.view-tab .spinner.tab-spin {
display: inline-block;
margin-right: 6px;
margin-right: 7px;
vertical-align: -1px;
}
@@ -1657,11 +1663,13 @@ input[type="text"].invalid { border-color: var(--warn); }
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
/* Send breathes while there is something to send: a soft accent ring that
spreads and fades. Off under reduced motion, below. */
/* Send glows and breathes while there is something to send: the steady
--glow, plus a soft accent ring that spreads and fades. The ring is off
under reduced motion, below; the glow stays. */
#btn-send:not(:disabled) { box-shadow: var(--glow); }
@keyframes send-pulse {
0% { box-shadow: 0 0 0 0 var(--accent-line); }
100% { box-shadow: 0 0 0 6px transparent; }
0% { box-shadow: var(--glow), 0 0 0 0 var(--accent-line); }
100% { box-shadow: var(--glow), 0 0 0 6px transparent; }
}
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
@@ -2219,6 +2227,7 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
.modal.help[open] { display: flex; }
.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-version a { color: inherit; }
.help-layout {
display: grid;
@@ -2668,6 +2677,74 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
border-left-width: 4px;
color: var(--ink);
}
/* A newer release: the same slot, in the accent, with the label as the way
into the update modal and a small × that hides it for this session. */
.dash-nudge.update-banner {
position: relative;
padding-left: 40px;
padding-right: 40px;
border-left-width: 4px;
border-left-color: var(--accent-line);
color: var(--ink);
box-shadow: var(--glow);
}
.update-banner-open {
flex: 1 1 16em;
padding: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
font-weight: 600;
letter-spacing: 0.02em;
text-align: center;
cursor: pointer;
}
.update-banner-open:hover { text-decoration: underline; }
/* Pinned to the right edge, out of the flow, so the label centres on the
whole banner rather than on what the × leaves of it. */
.update-banner-dismiss {
position: absolute;
top: 50%;
right: 10px;
transform: translateY(-50%);
padding: 0 6px;
border: 0;
border-radius: var(--radius);
background: none;
color: inherit;
font: inherit;
font-size: 16px;
line-height: 1;
cursor: pointer;
}
.update-banner-dismiss:hover { background: var(--accent-line); }
/* Wide enough that the update command sits on one line beside Copy; a
narrow window still wraps it rather than overflowing. */
#update-modal { max-width: 720px; }
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
.update-steps li { margin: 4px 0; }
/* The hand-off copy row, in the modal's first step: the command and its Copy
side by side. */
.update-command {
margin: 6px 0 4px;
display: flex;
align-items: stretch;
gap: 10px;
flex-wrap: wrap;
}
.update-command code {
flex: 1 1 260px;
min-width: 0;
font: 13px/1.5 var(--mono);
color: var(--ink);
background: var(--panel);
border: 1px solid var(--rule-2);
border-radius: 8px;
padding: 10px 12px;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
.dash-working {
@@ -3394,6 +3471,18 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.models-actions .help.error { color: var(--danger, #d64545); }
/* User Preferences: Cleanup's list of what would go, shown before anything
is deleted. */
.cleanup-list { display: grid; gap: 4px; max-height: 200px; overflow: auto; font-size: 0.88em; }
.cleanup-list:empty { display: none; }
.cleanup-summary { margin: 0 0 2px; font-weight: 600; }
.cleanup-row { display: flex; justify-content: space-between; gap: 12px; }
.cleanup-row span:first-child { min-width: 0; overflow-wrap: anywhere; font-family: var(--mono); }
.cleanup-size { flex: none; color: var(--ink-3); }
.cleanup-more { display: grid; gap: 4px; }
.cleanup-more summary { cursor: pointer; color: var(--ink-2); }
#cleanup-delete[hidden] { display: none; }
/* 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 {
@@ -66,6 +66,8 @@ import {
submittedAwaiting,
noteAwaiting,
suggestionFrom,
threadText,
threadWho,
THUMB_EDGE,
turnGate,
verdictText,
@@ -446,6 +448,10 @@ document.addEventListener("click", (e) => {
const GONE_AFTER_MS = 8000;
// Named so a reconnect can clear only THIS banner: a bare banner(null) would
// wipe an unrelated warning that landed while the page was gone (an upload
// failure, a refused send).
const GONE_BANNER = "Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.";
const WORKING_GRACE_MS = 5 * 60 * 1000;
// Two minutes with the agent mid-turn, three when it is merely meant to be
// listening. The difference is the cost of being wrong: a working agent that
@@ -521,6 +527,9 @@ let chatFrame = null;
// sends them.
let wsFrame = null;
let meterFrame = null;
// The frame's update ({ installed, latest }), present only when a newer
// release is out; null otherwise.
let updateFrame = null;
let chatDot = false;
let chatSending = false;
let chatResetting = false;
@@ -566,7 +575,6 @@ function fresh() {
drafts: {},
images: {},
sent: {},
sentAt: null,
stopping: null,
afterBuild: null,
homeward: null,
@@ -870,10 +878,12 @@ function adopt(body) {
chatFrame = body.chat || null;
if (body.workspace) wsFrame = body.workspace;
if (body.meter) meterFrame = body.meter;
// Always replaced: an absent key means no update.
updateFrame = body.update || null;
lastContact = Date.now();
if (gone) {
gone = false;
banner(null);
if ($("banner").textContent === GONE_BANNER) banner(null);
}
if (firstLoad) {
load();
@@ -1016,7 +1026,9 @@ function adopt(body) {
render();
if ($("workspace-modal").open) renderWorkspace();
tellFolderIssues();
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow) loadOverview();
// The Overview tab's file changes under a build, so a tab you are watching
// refetches on every new frame too, not only on the click that opened it.
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow || view === "overview") loadOverview();
if (announce) showArrival(announce);
// New entries land at the bottom of the rail. Gliding down to them beats
// leaving the list parked where it was while it grew underneath.
@@ -1149,15 +1161,12 @@ function markGone() {
// of the server means there, and a banner promising a reconnect would
// argue with it.
if (!finish() && !stopInProgress()) {
banner(
"Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.",
"warn"
);
banner(GONE_BANNER, "warn");
}
render();
} else if (!bad && gone) {
gone = false;
banner(null);
if ($("banner").textContent === GONE_BANNER) banner(null);
render();
}
}
@@ -1182,7 +1191,6 @@ function connect() {
} catch {}
});
es.addEventListener("submitted", (e) => {
local.sentAt = Date.now();
// Drop only what was actually sent.
//
// This event fires for a send from ANY tab of this session, which is why it
@@ -1799,14 +1807,19 @@ async function sendBrief() {
reply: briefPhrase(choice.range),
}),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
$("brief-modal").close();
banner("Asked for a brief. It will appear as a tab when it is written.", "good");
setTimeout(() => banner(null), 5000);
pendingResult = true;
render();
} catch {
why.textContent = "That did not go through. Try again in a moment.";
} catch (err) {
if (err && err.pending) pendingResult = true;
why.textContent =
err && err.pending
? "Your last answers are still being picked up. Try again in a moment."
: "That did not go through. Try again in a moment.";
} finally {
go.disabled = false;
go.textContent = "Write the brief";
@@ -2515,6 +2528,51 @@ function roleNudge() {
return nudge;
}
// × on the update banner hides it for this console session only, and only
// for the release it named. Blocked storage means "not dismissed".
function updateDismissKey() {
try {
return "p2c-update-dismissed:" + S.sid;
} catch {
return "p2c-update-dismissed:";
}
}
function updateDismissed() {
try {
return sessionStorage.getItem(updateDismissKey()) === updateFrame.latest;
} catch {
return false;
}
}
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
const UPDATE_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
function releasesLink(text) {
const a = el("a", null, text);
a.href = RELEASES_URL;
a.target = "_blank";
a.rel = "noopener noreferrer";
return a;
}
function openUpdateModal() {
if (!updateFrame) return;
const versions = $("update-versions");
versions.replaceChildren(
document.createTextNode("Version "),
releasesLink("v" + updateFrame.latest),
document.createTextNode(" is out — you have "),
el("code", null, updateFrame.installed),
document.createTextNode(".")
);
const row = $("update-command");
const code = el("code", null, UPDATE_COMMAND);
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
$("update-modal").showModal();
}
function renderDashboard(main) {
maybeWake();
const menu = (S && S.menu) || {};
@@ -2526,6 +2584,25 @@ function renderDashboard(main) {
warn.setAttribute("role", "status");
wrap.appendChild(warn);
}
// Built here only, so no other workflow's page ever shows it.
if (updateFrame && !updateDismissed()) {
const notice = el("div", "dash-nudge update-banner");
notice.setAttribute("role", "status");
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + updateFrame.latest);
open.type = "button";
open.addEventListener("click", openUpdateModal);
const dismiss = el("button", "update-banner-dismiss", "×");
dismiss.type = "button";
dismiss.setAttribute("aria-label", "Dismiss until next time");
dismiss.addEventListener("click", () => {
try {
sessionStorage.setItem(updateDismissKey(), updateFrame.latest);
} catch {}
render();
});
notice.append(open, dismiss);
wrap.appendChild(notice);
}
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
if (typeof menu.note === "string" && menu.note.trim()) {
@@ -3223,7 +3300,11 @@ document.addEventListener("keydown", cancelSkipMove, true);
function skipAndMoveOn(id) {
cancelSkipMove();
local.skipFlash = id;
stage(id, { type: "skip", skipped: true });
// A note already typed goes along: skipping the question is not retracting
// the comment. Dropping it would leave the text in the box but out of the
// send, which looks kept and is not.
const cur = local.staged[id];
stage(id, { type: "skip", skipped: true, ...(cur && cur.text ? { text: cur.text } : {}) });
skipTimer = setTimeout(() => {
skipTimer = null;
local.skipFlash = null;
@@ -3340,19 +3421,24 @@ function renderWaiting(main) {
}
pane.appendChild(title);
pane.appendChild(el("p", null, doing));
const ask = "If Plan2Code needs you, the question appears here on its own.";
if (!docs().length) {
pane.appendChild(el("p", null, "If Plan2Code needs you, the question appears here on its own."));
pane.appendChild(el("p", null, ask));
return;
}
// "Task" and the tasks tab's own name both open that tab, so the pointer is
// one click from what it points at. A build posts it as `phase` ("Phase N
// tasks"), a quick task as `tasks`; with neither the words stay plain.
// tasks"), a quick task as `tasks`. A skill with no task list (Document,
// Plan) has nothing live to follow, so it gets no pointer at all.
const list =
docs().find((d) => d.id === "phase") ||
docs().find((d) => d.id === "tasks") ||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
if (!list) {
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
return;
}
const jump = (word) => {
if (!list) return el("strong", "waiting-jump", word);
const b = el("button", "waiting-jump", word);
b.type = "button";
b.addEventListener("click", () => {
@@ -3366,8 +3452,8 @@ function renderWaiting(main) {
"The tabs above fill in as it goes. You can follow along with live ",
jump("Task"),
" updates in the ",
jump((list && list.title) || "Phase tasks"),
" tab. If Plan2Code needs you, the question appears here on its own."
jump(list.title || "Phase tasks"),
" tab. " + ask
);
pane.appendChild(p);
}
@@ -3505,8 +3591,8 @@ function renderSettled(card, item) {
// would misreport which of the two was the answer.
let prose = text;
if (!prose && !lines.length) {
const mine = (item.thread || []).filter((m) => m.who === "user");
if (mine.length) prose = String(mine[mine.length - 1].text || "").trim();
const mine = (item.thread || []).filter((m) => threadWho(m) === "user");
if (mine.length) prose = threadText(mine[mine.length - 1]).trim();
}
const nothing = !lines.length && !prose;
@@ -4322,6 +4408,10 @@ function buildChecklist(card, item, staged) {
const commitList = (change) => {
const cur = local.staged[item.id];
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
// A tick or a state IS the answer, so it ends a skip staged earlier:
// left in place, `skipped` would collapse the reply to "skip" while the
// card showed ticked steps on their way.
delete next.skipped;
const empty = !(next.done && next.done.length) && !next.state && !next.text;
stage(item.id, empty ? null : next);
};
@@ -4371,7 +4461,7 @@ function buildChecklist(card, item, staged) {
function buildMenu(card, item, staged) {
const list = el("ul", "options");
const name = "menu-" + item.id;
for (const o of item.options || []) {
for (const [i, o] of (item.options || []).entries()) {
const picked = staged && staged.k === o.k;
const li = el("li", "option" + (picked ? " is-picked" : ""));
const label = el("label");
@@ -4379,7 +4469,13 @@ function buildMenu(card, item, staged) {
const radio = el("input");
radio.type = "radio";
radio.name = name;
// The same id buildChoice gives its radios: withFocus finds the focused
// input by id after the render this change() sets off, and without one a
// keyboard user arrowing through the menu lands on <body> every time.
radio.id = optionId(item, o, i);
radio.value = o.k;
radio.checked = Boolean(picked);
radio.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
const body = el("div", "option-body");
const head = el("div", "option-label");
@@ -5276,20 +5372,30 @@ function renderAside() {
)
);
}
// A note that has been sent but not yet picked up: marked as waiting, so the
// send is seen to have gone, until the agent replies. The server writes the
// note into the thread as it arrives; a session from before that has only
// `sentNote`, which gets a box of its own below.
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
let waitingShown = false;
for (const m of thread) {
const box = el("div", "msg " + (m.who === "user" ? "you" : ""));
const mine = threadWho(m) === "user";
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
if (pending) waitingShown = true;
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
const who = el("div", "msg-who");
who.appendChild(el("span", null, m.who === "user" ? "You" : "Plan2Code"));
if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
box.appendChild(who);
box.appendChild(md(m.text, "md"));
const text = threadText(m);
if (text) box.appendChild(md(text, "md"));
const tray = mine ? sentAttachments(m) : null;
if (tray) box.appendChild(tray);
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) {
if (waiting && !waitingShown) {
const box = el("div", "msg you pending");
const who = el("div", "msg-who");
who.appendChild(el("span", null, "You"));
@@ -5589,7 +5695,10 @@ async function attachFiles(itemId, files) {
const taken = wanted.slice(0, room);
// One banner at a time, so every refusal goes into it, each by name.
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
if (taken.length < wanted.length) said.push(chat ? "Up to 5 attachments per question." : "Up to 5 attachments per note.");
if (taken.length < wanted.length)
said.push(
chat ? `Up to ${CHAT_MAX_ATTACHMENTS} attachments per question.` : `Up to ${MAX_ATTACHMENTS} attachments per note.`
);
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
await Promise.all(
taken.map(async (file) => {
@@ -6439,6 +6548,10 @@ async function goHome() {
$("home-modal").close();
} catch (err) {
$("home-modal").close();
// The server is holding an uncollected result: Send, Home and Stop all
// need to read as busy until the frame or the ping says otherwise, same
// as send() and sendAfterBuild() do on a 409.
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
@@ -6499,6 +6612,7 @@ async function stopSession() {
stoppingHidden = false;
} catch (err) {
$("stop-modal").close();
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
@@ -6653,7 +6767,6 @@ function markSent({ sentIds, sentNotes = {}, summaries, values }) {
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
}
local.staged = {};
local.sentAt = Date.now();
save();
}
@@ -6706,7 +6819,7 @@ const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", d
// something the agent never hears.
function tokenFor(item, v) {
const map = item.token || {};
if (v.skipped) return "skip";
if (v.skipped) return v.text ? `skip; ${v.text}` : "skip";
const parts = [];
if (v.k) parts.push(map[v.k] || v.k);
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
@@ -6938,14 +7051,14 @@ function renderAbout() {
let helpBuilt = false;
async function renderHelpVersion() {
const el = $("help-version");
const slot = $("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;
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
slot.hidden = !version;
} catch {
el.hidden = true;
slot.hidden = true;
}
}
@@ -7053,6 +7166,7 @@ function openHelpOn(id) {
}
$("btn-home").addEventListener("click", openHomeConfirm);
$("update-done").addEventListener("click", () => $("update-modal").close());
$("home-cancel").addEventListener("click", () => $("home-modal").close());
$("home-go").addEventListener("click", goHome);
$("btn-stop").addEventListener("click", openStopConfirm);
@@ -7132,6 +7246,7 @@ $("btn-looks").addEventListener("click", () => {
});
$("looks-done").addEventListener("click", () => $("looks-modal").close());
$("looks-modal").addEventListener("close", () => {
resetCleanup();
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
});
$("looks-reset").addEventListener("click", () => {
@@ -7278,6 +7393,111 @@ $("models-reset").addEventListener("click", () => {
renderModels();
});
// Cleanup: the server works out what in ~/.plan2code is not needed and
// shows it first; Delete these sends back only the ids it was shown, and the
// server re-checks every one before removing it.
let cleanupFound = null;
// Bumped by every scan, delete and reset: a response from an older one is
// dropped, so a scan still in flight when Preferences closes cannot refill it.
let cleanupGen = 0;
const CLEANUP_SHOWN = 8;
function setCleanupStatus(text, isError) {
const status = $("cleanup-status");
status.textContent = text;
status.classList.toggle("error", Boolean(isError));
}
function cleanupLabel(item) {
if (item.where === "session") return "Session " + item.name;
const where = item.where === "root" ? "~/.plan2code/" : "~/.plan2code/console/";
return where + item.name + (item.kind === "folder" ? "/" : "");
}
function cleanupSummary(items, bytes) {
const sessions = items.filter((i) => i.where === "session").length;
const strays = items.length - sessions;
const parts = [];
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
return parts.join(", ") + " · " + formatBytes(bytes);
}
function resetCleanup() {
cleanupGen++;
cleanupFound = null;
$("cleanup-list").replaceChildren();
$("cleanup-delete").hidden = true;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
setCleanupStatus("", false);
}
function renderCleanup() {
const list = $("cleanup-list");
list.replaceChildren();
const items = (cleanupFound && cleanupFound.items) || [];
$("cleanup-delete").hidden = !items.length;
if (!items.length) return;
const rows = (some) => some.map((item) => {
const row = el("div", "cleanup-row");
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", formatBytes(item.bytes)));
return row;
});
list.append(el("p", "cleanup-summary", cleanupSummary(items, cleanupFound.bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
if (items.length > CLEANUP_SHOWN) {
const more = el("details", "cleanup-more");
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
list.appendChild(more);
}
}
async function scanCleanup() {
const gen = ++cleanupGen;
$("cleanup-scan").disabled = true;
$("cleanup-delete").disabled = true;
setCleanupStatus("Looking…", false);
const { status, body } = await postJson("/cleanup", { scan: true });
if (gen !== cleanupGen) return;
$("cleanup-scan").disabled = false;
$("cleanup-delete").disabled = false;
if (status !== 200 || !body.ok) {
cleanupFound = null;
renderCleanup();
return setCleanupStatus(status ? body.error || "Could not look." : "Plan2Code isn't reachable.", true);
}
cleanupFound = { items: body.items || [], bytes: body.bytes || 0 };
renderCleanup();
// Left in the status line, not cleared: it is the live region, so this is
// what a screen reader hears when the scan finishes.
const found = cleanupFound.items.length;
setCleanupStatus(found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.", false);
}
async function deleteCleanup() {
if (!cleanupFound || !cleanupFound.items.length) return;
const gen = ++cleanupGen;
$("cleanup-delete").disabled = true;
$("cleanup-scan").disabled = true;
setCleanupStatus("Deleting…", false);
const { status, body } = await postJson("/cleanup", { delete: cleanupFound.items.map((i) => i.id) });
if (gen !== cleanupGen) return;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
if (status !== 200 || !body.ok) {
return setCleanupStatus(status ? body.error || "Could not delete." : "Plan2Code isn't reachable.", true);
}
const removed = (body.removed || []).length;
const failed = (body.failed || []).length;
cleanupFound = null;
renderCleanup();
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
setCleanupStatus(failed ? done + " " + failed + " could not be removed." : done, Boolean(failed));
}
$("cleanup-scan").addEventListener("click", scanCleanup);
$("cleanup-delete").addEventListener("click", deleteCleanup);
$("btn-brief").addEventListener("click", openBrief);
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
$("brief-go").addEventListener("click", sendBrief);
@@ -1291,6 +1291,14 @@
come back, and you can change your role any time from the swatch
button.
</p>
<h4>When an update is out</h4>
<p>
When a newer Plan2Code release is out, the dashboard shows
<strong>UPDATE AVAILABLE</strong> at the top. Click it for the command
to run in your terminal; × hides it until the next
<code>/plan2code</code>. The version at the bottom of Help links to
the Releases page.
</p>
<h4>The cards</h4>
<p>They come in three groups.</p>
<p><strong>First, the project</strong></p>
@@ -1845,6 +1853,15 @@
joining the strip. Keep only the ones you want; ticking a box plays
its sound.
</li>
<li>
<strong>Cleanup</strong>: <strong>Find files to clean up</strong>
lists what Plan2Code doesn't need in your
<code>~/.plan2code</code> folder: sessions nobody has opened for
30 days, and files or folders that ended up there by mistake. It
shows each one with its size, and <strong>Delete these</strong>
removes exactly that list. Your preferences, saved folders, models,
the launcher and the session you are in always stay.
</li>
<li>
<strong>Back to default</strong> puts everything back as it was, and
sets Role back to Not set.
@@ -1983,6 +2000,16 @@
</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-cleanup">
<legend>Cleanup</legend>
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
<div class="models-actions">
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
<button type="button" class="btn small danger" id="cleanup-delete" hidden>Delete these</button>
<span class="help" id="cleanup-status" role="status"></span>
</div>
</fieldset>
<fieldset class="modal-ranges looks-models">
<legend>Models</legend>
<div class="models-tabs" role="group" aria-label="Which agent">
@@ -2181,6 +2208,24 @@
</div>
</dialog>
<!-- Opened from the dashboard's UPDATE AVAILABLE banner. The versions and
the copy row are filled by app.js; the update itself runs in a
terminal, never from this page. -->
<dialog class="modal" id="update-modal" aria-labelledby="update-title">
<h2 id="update-title">A new Plan2Code is available</h2>
<p class="modal-blurb" id="update-versions"></p>
<ol class="update-steps">
<li>
Run this in your terminal (not in this page or your agent):
<div class="update-command" id="update-command"></div>
</li>
<li>When it finishes, close this console and start <code>plan2code</code> again.</li>
</ol>
<div class="modal-actions">
<button type="button" class="btn primary" id="update-done">Close</button>
</div>
</dialog>
<footer class="footer">
<div class="footer-summary" id="footer-summary" aria-live="polite">
Nothing to send yet.
@@ -5,7 +5,10 @@
// popover; this file owns the rules. No DOM access at module scope and no
// imports: the page and `node --test` both import this file.
const NAME_CHAR = /[a-z0-9-]/;
// Uppercase too: "@Repo" must still name @repo — names are forced lowercase
// by the workspace rules, and a query typed with a capital otherwise matches
// nothing and opens no suggestions at all.
const NAME_CHAR = /[a-z0-9-]/i;
const MAX_MATCHES = 6;
/**
@@ -23,11 +26,13 @@ export function mentionAt(text, caret) {
}
// Names starting with the query first, then names containing it, in the
// order given, at most six.
// order given, at most six. Case-folded: folder names are lowercase by rule,
// and "@Repo" should still find @repo rather than claim nothing matches.
export function matchNames(names, query) {
const q = String(query || "");
const prefix = names.filter((n) => n.startsWith(q));
const inside = names.filter((n) => !n.startsWith(q) && n.includes(q));
const q = String(query || "").toLowerCase();
const fold = (n) => String(n).toLowerCase();
const prefix = names.filter((n) => fold(n).startsWith(q));
const inside = names.filter((n) => !fold(n).startsWith(q) && fold(n).includes(q));
return [...prefix, ...inside].slice(0, MAX_MATCHES);
}
@@ -25,12 +25,14 @@ import {
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
UPDATE_CHECK_FILE,
USER_MODELS_FILE,
WORKSPACE_FILE,
appendChat,
appendEvent,
chatForFrame,
checkDocument,
cleanupFindings,
currentConversation,
ensureDir,
fileStamp,
@@ -47,6 +49,7 @@ import {
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
removeCleanup,
remoteWarning,
specKey,
typedCount,
@@ -59,6 +62,7 @@ import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
import { meterView } from "./public/meter.js";
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
import { checkForUpdate } from "./update-check.mjs";
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
const args = parseArgs(process.argv.slice(2));
@@ -611,6 +615,7 @@ function stateFrame(state) {
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
workspace: workspaceView(),
meter: meterView(ledgerEntries()),
...(updateInfo ? { update: updateInfo } : {}),
have: haveKey(),
};
}
@@ -623,7 +628,7 @@ function haveKey() {
ledgerEntries();
return (
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}`
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}`
);
}
@@ -648,6 +653,12 @@ function recordSubmitted(state, actions) {
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) };
// The person's side of the Notes thread. Left to the agent it was never
// written, so a question asked in a note vanished once it was picked up
// and the reply under it answered nothing on the page.
if (item.sentNote.text.trim() || item.sentNote.images.length || item.sentNote.files.length) {
item.thread = [...(Array.isArray(item.thread) ? item.thread : []), { who: "user", ...item.sentNote }];
}
continue;
}
const { i, type, ...rest } = action;
@@ -933,6 +944,38 @@ function pushState() {
if (stateNow) broadcast("state", stateFrame(stateNow));
}
/* --------------------------------------------------------- update check */
// The version this console was installed as: install.js writes version.json
// beside console.mjs; a dev checkout falls back to the repo root's.
function installedVersion() {
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 version;
}
return null;
}
// Filled in once the boot-time check answers; until then, and whenever it
// fails, the frame carries no `update` and the page shows no banner.
let updateInfo = null;
let updateLatest = null;
// Started at boot and never awaited: git may take up to its 10 s limit, and
// nothing the person sees waits on it. The catch is not optional: a throw in
// pushState() would otherwise be an unhandled rejection, which ends the server.
function startUpdateCheck() {
const installed = installedVersion();
if (!installed) return;
checkForUpdate({ installed, cacheFile: UPDATE_CHECK_FILE })
.then((result) => {
updateLatest = result?.latest ?? null;
updateInfo = result?.updateAvailable ? { installed: result.installed, latest: result.latest } : null;
if (updateInfo) pushState();
})
.catch(() => {});
}
let agentSeenAt = Date.now();
function agentLastSeen() {
return new Date(agentSeenAt).toISOString();
@@ -1039,10 +1082,8 @@ const server = http.createServer((req, res) => {
}
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 });
}
const version = installedVersion();
if (version) return json(res, 200, { version, latest: updateLatest });
return json(res, 404, { error: "no version" });
}
@@ -1090,7 +1131,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/draft" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
// Debounced client-side; this is just the durable mirror. Twenty minutes
// of someone's structured answers must not die with a closed tab.
try {
@@ -1115,7 +1156,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/looks" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
// `set` carries only the keys one tab changed, merged onto what is on
// disk, so a tab holding stale settings cannot undo another tab's change.
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
@@ -1141,7 +1182,7 @@ const server = http.createServer((req, res) => {
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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
const { models, error } = cleanModels(body && body.models);
if (error) return json(res, 400, { error });
try {
@@ -1154,6 +1195,24 @@ const server = http.createServer((req, res) => {
});
}
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
// ~/.plan2code; `{ delete: [id] }` removes those of the ids a fresh scan
// still finds. Never this session, never a path the page sent.
if (pathname === "/cleanup" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
if (body && Array.isArray(body.delete)) {
return removeCleanup(body.delete, { skipSid: SID })
.then((done) => json(res, 200, { ok: true, ...done }))
.catch((e) => json(res, 500, { error: String(e.message) }));
}
return cleanupFindings({ skipSid: SID })
.then(({ items, bytes }) => json(res, 200, { ok: true, bytes, items: items.map(({ path: _p, ...item }) => item) }))
.catch((e) => json(res, 500, { error: String(e.message) }));
});
}
if (pathname === "/upload" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
const contentType = String(req.headers["content-type"] || "");
@@ -1260,7 +1319,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/submit" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
if (!body || !Array.isArray(body.actions) || body.actions.length === 0) {
return json(res, 400, { error: "actions must be a non-empty array" });
}
@@ -1361,6 +1420,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/chat" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const state = readState() || {};
const current = currentConversation(chatEntries()).conversation;
@@ -1424,6 +1484,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/chat/decision" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
if (body.decision !== "approve" && body.decision !== "decline") return json(res, 400, { error: "bad" });
if (body.text !== undefined && typeof body.text !== "string") return json(res, 400, { error: "bad" });
@@ -1472,6 +1533,7 @@ const server = http.createServer((req, res) => {
if (Object.hasOwn(workspaceRoutes, pathname) && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
let answer;
try {
@@ -1489,6 +1551,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/workspace/scope" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const spec = typeof body.spec === "string" ? body.spec : "";
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
@@ -1589,15 +1652,19 @@ function readBody(req, cb) {
let tooBig = false;
req.on("data", (c) => {
size += c.length;
// Drain past the cap rather than destroy, exactly like readRaw: a
// destroyed request emits 'close', never 'end' or 'error', so cb would
// never run and the page would see a reset instead of the 413 that names
// the problem.
if (size > MAX_BODY) {
tooBig = true;
req.destroy();
chunks.length = 0;
return;
}
chunks.push(c);
});
req.on("end", () => {
if (tooBig) return cb(new Error("too large"));
if (tooBig) return cb(Object.assign(new Error("too large"), { tooBig: true }));
try {
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
} catch (e) {
@@ -1834,6 +1901,9 @@ function onListening(port) {
bootWorkspace();
} catch {}
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
try {
startUpdateCheck();
} catch {}
try {
process.send?.({ type: "listening", port });
} catch {}
@@ -0,0 +1,138 @@
// Plan2Code Web Console - is a newer Plan2Code release out?
//
// `git ls-remote --tags` needs no API token and no rate-limited REST call,
// rides on the person's own git and proxy setup, and the newest `vX.Y.Z`
// release tag is "latest". The server
// starts this at boot and never waits on it; the answer, failures included, is
// cached for an hour so a burst of sessions asks GitHub once.
//
// Nothing here reads, stores or sends a credential: git authenticates itself,
// with every prompt turned off so a missing login fails fast instead of
// opening a window nobody asked for.
//
// Node built-ins only.
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
export const REPO_URL = "https://github.com/jparkerweb/plan2code.git";
export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
export const CACHE_MS = 60 * 60 * 1000;
const SEMVER = /^\d+\.\d+\.\d+$/;
const TAG_REF = /refs\/tags\/v(\d+\.\d+\.\d+)$/;
/** -1, 0 or 1 comparing two plain X.Y.Z versions numerically; null unless both are X.Y.Z. */
export function compareVersions(a, b) {
if (typeof a !== "string" || typeof b !== "string" || !SEMVER.test(a) || !SEMVER.test(b)) return null;
const x = a.split(".").map(Number);
const y = b.split(".").map(Number);
for (let i = 0; i < 3; i++) {
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
}
return 0;
}
/**
* The highest `vX.Y.Z` tag in `git ls-remote --tags` output, without the `v`.
* Peeled lines (`^{}`) never match, so an annotated tag counts once, and
* pre-releases or other tag names are ignored. Null when nothing matches.
*/
export function latestTag(text) {
if (typeof text !== "string") return null;
let best = null;
for (const line of text.split(/\r?\n/)) {
const m = TAG_REF.exec(line.trim());
if (m && (best === null || compareVersions(m[1], best) > 0)) best = m[1];
}
return best;
}
function readCache(cacheFile, now) {
try {
const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
if (!cached || typeof cached.checkedAt !== "number" || now - cached.checkedAt >= CACHE_MS) return undefined;
return typeof cached.latest === "string" ? cached.latest : null;
} catch {
return undefined;
}
}
function writeCache(cacheFile, data) {
const tmp = cacheFile + "." + process.pid + ".tmp";
try {
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
fs.renameSync(tmp, cacheFile);
} catch {
try {
fs.rmSync(tmp, { force: true });
} catch {}
}
}
/**
* `git ls-remote --tags` against the repo: resolves its stdout, or null when
* git is missing, fails, or is still going after `timeoutMs`. No shell, no
* window, no prompt.
*/
export function runLsRemote({ timeoutMs = 10000 } = {}) {
return new Promise((resolve) => {
let settled = false;
const done = (value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(value);
};
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
if (!process.env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
let child;
try {
child = spawn("git", ["ls-remote", "--tags", REPO_URL], {
shell: false,
windowsHide: true,
stdio: ["ignore", "pipe", "ignore"],
env,
});
} catch {
return resolve(null);
}
const timer = setTimeout(() => {
try {
child.kill();
} catch {}
done(null);
}, timeoutMs);
timer.unref?.();
let out = "";
child.stdout.setEncoding("utf8");
child.stdout.on("data", (chunk) => {
out += chunk;
});
child.on("error", () => done(null));
child.on("close", (code) => done(code === 0 ? out : null));
});
}
/**
* Whether `installed` is behind the newest release: `{ installed, latest,
* updateAvailable }`, or null when either version is unknown. Reuses a cache
* under an hour old, and caches a failed lookup as `latest: null` so it is
* not retried until the hour is up. Never throws.
*/
export async function checkForUpdate({ installed, cacheFile, now = Date.now(), run = runLsRemote }) {
try {
let latest = readCache(cacheFile, now);
if (latest === undefined) {
latest = latestTag(await run());
writeCache(cacheFile, { checkedAt: now, latest });
}
const order = compareVersions(installed, latest);
if (latest === null || order === null) return null;
return { installed, latest, updateAvailable: order < 0 };
} catch {
return null;
}
}
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -243,7 +243,7 @@ summarise it back.
Then, in ONE `post`, do all of:
- mark each answered item `"status": "answered"` and record its `answer`
- add your replies to any comment threads
- reply to every note in that item's `thread` (shape below)
- answer any Quick questions that came with it, in `chat.replies` (see Quick
questions)
- publish the next batch of questions
@@ -251,6 +251,26 @@ Then, in ONE `post`, do all of:
One post is one atomic update, so the page never shows a half-changed state.
### Replying to a note
A `comment` is the person talking to you about that card, often asking
something. It shows in the card's **Notes on this** panel, and so does your
answer:
```jsonc
{ "items": [{ "id": "p4", "thread": [
{ "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." }
] }] }
```
- Every entry is `{ "who": "agent", "text": "<markdown>" }`. `text`, not
`md`: the page reads nothing else. An entry with no `text` is rejected.
- The server writes their note into the thread as it arrives. Do not repeat
it, and send only your new entries: `thread` appends.
- Answer what they asked, in the thread, even when you also change a doc or
re-ask the question. "I've updated the doc" alone leaves the question in the
panel with no answer under it.
### Recording the answer
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
@@ -661,9 +681,17 @@ finish are dropped, so you start on a blank page and post your own. A skill
run inline from another (a quick task's review) keeps the page it was
handed. A
fresh `open` would strand the page the person is watching on the dashboard's
session while your questions went to a page nobody has open. Then run the
skill normally: its Interface question was already answered by being
launched, so start where its real work starts.
session while your questions went to a page nobody has open.
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
> own file-read tool and follow it from the top instead.** Every Plan2Code
> skill below the dashboard ships `disable-model-invocation: true` on
> purpose — it exists to be read and followed inline, not launched as a
> sub-skill — and calling one through a skill-invocation tool errors out and
> strands the hand-off mid-launch.
Its Interface step is already answered by having been launched, so start
where its real work starts.
The menu itself is the page's own list — you never send it. The page knows
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
@@ -829,6 +857,12 @@ know:
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
Post `activity` as each step starts, before its doc or question lands — reading
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
implementation — the same way Review does. A step with no card of its own
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
Finalize".
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
Stopping mid-finalize loses nothing
— the specs are untouched until Step 3's summary write — so a stop's finish
@@ -859,7 +893,7 @@ question or doc lands:
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
merge by `id` (an unknown id is added), and `thread` / `comments` append. Send only
merge by `id` (an unknown id is added), and `thread` appends. Send only
what changed. A whole-file rewrite would put the entire session back into your
context on every turn.
@@ -1239,7 +1273,7 @@ answers were submitted but never picked up.
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` and `comments` **append**: leave out any thread entry you already sent, or the person sees your reply twice. |
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
@@ -48,6 +48,10 @@ export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
// so every session within the hour reuses one lookup.
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
// test run (or a second sandboxed instance) shares one handle directory with
// the real thing, and `stop --all` reaches outside its own world and kills a
@@ -487,9 +491,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks, the folders remembered per project and spec, and the pointer to
// this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
// looks, the folders remembered per project and spec, the pointer to this
// console's directory, and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir", "update-check.json"]);
function isScratchName(name) {
return (
@@ -536,6 +540,148 @@ export async function removeScratch(consoleDir, names) {
return removed;
}
/* ------------------------------------------------------------- cleanup */
// What User Preferences -> Cleanup never removes. The console folder keeps its
// protected files, its sessions dir (old sessions go one by one, by age) and,
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
// console, the launcher (bin/, launcher.json) and the models the person added.
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
// A stray must sit untouched this long before Cleanup lists it. The same
// folders hold files that live for milliseconds -- a held
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
// rename -- and removing one mid-write loses another session's change.
export const STRAY_GRACE_MS = 60 * 60 * 1000;
// Bytes under `p`, never following a symlink: a link counts as itself.
async function diskBytes(p) {
let st;
try {
st = await fs.promises.lstat(p);
} catch {
return 0;
}
if (!st.isDirectory()) return st.size;
let entries;
try {
entries = await fs.promises.readdir(p);
} catch {
return 0;
}
let total = 0;
for (const name of entries) total += await diskBytes(path.join(p, name));
return total;
}
// The newest mtime of anything under `p`, never following a symlink. A folder
// counts by its files, since rewriting a file never touches its folder's
// mtime; an empty folder counts by its own. Anything unreadable on the way
// down answers Infinity, so it reads as just touched and stays.
function newestMtime(p) {
let st;
try {
st = fs.lstatSync(p);
} catch {
return Infinity;
}
if (!st.isDirectory()) return st.mtimeMs;
let entries;
try {
entries = fs.readdirSync(p);
} catch {
return Infinity;
}
if (!entries.length) return st.mtimeMs;
let newest = 0;
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
return newest;
}
function entryKind(entry) {
if (entry.isSymbolicLink()) return "link";
return entry.isDirectory() ? "folder" : "file";
}
function strayEntries(dir, kept, where, now) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return [];
}
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
return entries
.filter((e) => !kept.has(e.name))
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
.filter((e) => settled(e.path));
}
/**
* Everything Cleanup would remove, worked out on the server and never taken
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
* `open` sweeps by, plus every file in the folder that old, so a resumed
* session or a saved draft keeps it), anything at the top of the console folder that is
* not kept, and -- only when the console runs from its default home inside
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
* touched within `STRAY_GRACE_MS` are left for a later scan. A
* console running from another home (tests, dev) never reaches ~/.plan2code.
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
*/
export async function cleanupFindings({
consoleDir = HOME_DIR,
plan2codeDir = PLAN2CODE_DIR,
now = Date.now(),
maxAgeMs = SESSION_MAX_AGE_MS,
skipSid,
} = {}) {
const found = [];
const sessionsDir = path.join(consoleDir, "sessions");
for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) {
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
}
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
}
const items = [];
let bytes = 0;
for (const f of found) {
const size = await diskBytes(f.path);
bytes += size;
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
}
return { items, bytes };
}
/**
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
* worked out afresh first and only ids on it are touched, so a name from the
* page is never a path, and anything that stopped qualifying since the scan
* (a session touched again) stays. A link is unlinked, never followed.
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
*/
export async function removeCleanup(ids, opts = {}) {
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
const { items } = await cleanupFindings(opts);
const removed = [];
const failed = [];
let bytes = 0;
for (const item of items) {
if (!wanted.has(item.id)) continue;
try {
if (item.kind === "link") await fs.promises.unlink(item.path);
else await fs.promises.rm(item.path, { recursive: true, force: true });
removed.push(item.id);
bytes += item.bytes;
} catch {
failed.push(item.id);
}
}
return { removed, bytes, failed };
}
/**
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
* the file's realpath must sit inside the root's, so `../`, an absolute path
@@ -871,7 +1017,7 @@ export function handOff(child, pre) {
/* ----------------------------------------------------------- patch merge */
const APPEND_KEYS = new Set(["thread", "comments"]);
const APPEND_KEYS = new Set(["thread"]);
function isPlainObject(v) {
return v !== null && typeof v === "object" && !Array.isArray(v);
@@ -896,7 +1042,7 @@ function mergeOne(target, patch, where) {
}
// Merge a keyed collection: a known id merges one level, an unknown id appends.
// Named fields are replaced whole; thread/comments append.
// Named fields are replaced whole; thread appends.
function mergeKeyed(current, patchList, idKey, defaults, where) {
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
for (const entry of patchList) {
@@ -955,6 +1101,42 @@ function dropStaleSubmissions(currentItems, before, patchList) {
return merged;
}
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
// borrow the shape of the replies and doc blocks they also write, so `from` /
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
// at all is refused. The person's own notes are recorded by the server when
// they send, so an agent that echoes one back is not shown it twice.
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
function normalizeThreads(patchList, currentItems) {
return patchList.map((entry) => {
if (!isPlainObject(entry) || entry.thread == null) return entry;
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
const said = new Set(
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
);
const thread = [];
for (const m of entry.thread) {
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
guard(m, "thread");
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
if (!key) {
throw new Error(
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
);
}
const { from, role, md, body, content, ...rest } = m;
const who = (m.who || from || role) === "user" ? "user" : "agent";
const text = m[key];
if (who === "user" && said.has(text.trim())) continue;
thread.push({ ...rest, who, text });
}
return { ...entry, thread };
});
}
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
@@ -996,7 +1178,7 @@ export function applyPatch(state, patch) {
break;
case "items":
if (!Array.isArray(v)) throw new Error('"items" must be an array');
next.items = dropStaleSubmissions(next.items, state.items, v);
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
break;
case "topics":
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
@@ -1048,15 +1230,11 @@ function stampTimes(before, next) {
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
}
for (const list of [next.items, next.docs]) {
if (!Array.isArray(list)) continue;
for (const entry of list) {
if (Array.isArray(next.items)) {
for (const entry of next.items) {
if (Array.isArray(entry.thread)) {
for (const m of entry.thread) if (!m.at) m.at = now;
}
if (Array.isArray(entry.comments)) {
for (const m of entry.comments) if (!m.at) m.at = now;
}
}
}
if (Array.isArray(next.docs)) {
@@ -1289,7 +1467,10 @@ 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, sentNote, ...rest }) => rest);
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
...rest,
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
}));
const prose =
JSON.stringify(authored) +
JSON.stringify(state.docs || []) +
@@ -65,7 +65,7 @@ export function submittedAwaiting(item) {
if (!s || typeof s !== "object") return null;
if (item.answer && typeof item.answer === "object") return null;
const thread = Array.isArray(item.thread) ? item.thread : [];
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
return replied ? null : s;
}
@@ -74,17 +74,33 @@ export function submittedAwaiting(item) {
* 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.
* Any agent message from the send onwards, or one with no clock to compare,
* means it has been picked up. The person's own entries never count: the
* server writes their note into the thread as it arrives.
*/
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));
const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at));
return picked ? null : n;
}
/**
* Who said a thread entry and what they said. The contract is `{ who, text }`
* and the server lifts anything else into it, but sessions written before that
* hold `{ from, md }` replies, which would otherwise draw as empty bubbles.
*/
export function threadWho(m) {
return m && (m.who || m.from || m.role) === "user" ? "user" : "agent";
}
export function threadText(m) {
if (!m) return "";
for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k];
return "";
}
/* -------------------------------------------------------------- labels */
export function optionLabel(item, k) {
@@ -23,6 +23,9 @@
--warn-soft: #fbe7e3;
--focus: #1f6feb;
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
/* A soft accent halo for the things that want noticing: the update banner
and an enabled Send. Built from --accent, so a picked accent glows too. */
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
@@ -61,6 +64,7 @@
--warn-soft: #34201d;
--focus: #6aa3ff;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
}
}
@@ -85,6 +89,7 @@
--warn-soft: #34201d;
--focus: #6aa3ff;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
}
* { box-sizing: border-box; }
@@ -1097,10 +1102,11 @@ h1 {
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
the tiny ring, left of the label. */
.view-tab .tab-spin {
the tiny ring, left of the label. The extra .spinner is for specificity:
.spinner.tiny comes later and zeroes the margin otherwise. */
.view-tab .spinner.tab-spin {
display: inline-block;
margin-right: 6px;
margin-right: 7px;
vertical-align: -1px;
}
@@ -1657,11 +1663,13 @@ input[type="text"].invalid { border-color: var(--warn); }
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
/* Send breathes while there is something to send: a soft accent ring that
spreads and fades. Off under reduced motion, below. */
/* Send glows and breathes while there is something to send: the steady
--glow, plus a soft accent ring that spreads and fades. The ring is off
under reduced motion, below; the glow stays. */
#btn-send:not(:disabled) { box-shadow: var(--glow); }
@keyframes send-pulse {
0% { box-shadow: 0 0 0 0 var(--accent-line); }
100% { box-shadow: 0 0 0 6px transparent; }
0% { box-shadow: var(--glow), 0 0 0 0 var(--accent-line); }
100% { box-shadow: var(--glow), 0 0 0 6px transparent; }
}
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
@@ -2219,6 +2227,7 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
.modal.help[open] { display: flex; }
.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-version a { color: inherit; }
.help-layout {
display: grid;
@@ -2668,6 +2677,74 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
border-left-width: 4px;
color: var(--ink);
}
/* A newer release: the same slot, in the accent, with the label as the way
into the update modal and a small × that hides it for this session. */
.dash-nudge.update-banner {
position: relative;
padding-left: 40px;
padding-right: 40px;
border-left-width: 4px;
border-left-color: var(--accent-line);
color: var(--ink);
box-shadow: var(--glow);
}
.update-banner-open {
flex: 1 1 16em;
padding: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
font-weight: 600;
letter-spacing: 0.02em;
text-align: center;
cursor: pointer;
}
.update-banner-open:hover { text-decoration: underline; }
/* Pinned to the right edge, out of the flow, so the label centres on the
whole banner rather than on what the × leaves of it. */
.update-banner-dismiss {
position: absolute;
top: 50%;
right: 10px;
transform: translateY(-50%);
padding: 0 6px;
border: 0;
border-radius: var(--radius);
background: none;
color: inherit;
font: inherit;
font-size: 16px;
line-height: 1;
cursor: pointer;
}
.update-banner-dismiss:hover { background: var(--accent-line); }
/* Wide enough that the update command sits on one line beside Copy; a
narrow window still wraps it rather than overflowing. */
#update-modal { max-width: 720px; }
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
.update-steps li { margin: 4px 0; }
/* The hand-off copy row, in the modal's first step: the command and its Copy
side by side. */
.update-command {
margin: 6px 0 4px;
display: flex;
align-items: stretch;
gap: 10px;
flex-wrap: wrap;
}
.update-command code {
flex: 1 1 260px;
min-width: 0;
font: 13px/1.5 var(--mono);
color: var(--ink);
background: var(--panel);
border: 1px solid var(--rule-2);
border-radius: 8px;
padding: 10px 12px;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
.dash-working {
@@ -3394,6 +3471,18 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.models-actions .help.error { color: var(--danger, #d64545); }
/* User Preferences: Cleanup's list of what would go, shown before anything
is deleted. */
.cleanup-list { display: grid; gap: 4px; max-height: 200px; overflow: auto; font-size: 0.88em; }
.cleanup-list:empty { display: none; }
.cleanup-summary { margin: 0 0 2px; font-weight: 600; }
.cleanup-row { display: flex; justify-content: space-between; gap: 12px; }
.cleanup-row span:first-child { min-width: 0; overflow-wrap: anywhere; font-family: var(--mono); }
.cleanup-size { flex: none; color: var(--ink-3); }
.cleanup-more { display: grid; gap: 4px; }
.cleanup-more summary { cursor: pointer; color: var(--ink-2); }
#cleanup-delete[hidden] { display: none; }
/* 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 {
@@ -66,6 +66,8 @@ import {
submittedAwaiting,
noteAwaiting,
suggestionFrom,
threadText,
threadWho,
THUMB_EDGE,
turnGate,
verdictText,
@@ -446,6 +448,10 @@ document.addEventListener("click", (e) => {
const GONE_AFTER_MS = 8000;
// Named so a reconnect can clear only THIS banner: a bare banner(null) would
// wipe an unrelated warning that landed while the page was gone (an upload
// failure, a refused send).
const GONE_BANNER = "Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.";
const WORKING_GRACE_MS = 5 * 60 * 1000;
// Two minutes with the agent mid-turn, three when it is merely meant to be
// listening. The difference is the cost of being wrong: a working agent that
@@ -521,6 +527,9 @@ let chatFrame = null;
// sends them.
let wsFrame = null;
let meterFrame = null;
// The frame's update ({ installed, latest }), present only when a newer
// release is out; null otherwise.
let updateFrame = null;
let chatDot = false;
let chatSending = false;
let chatResetting = false;
@@ -566,7 +575,6 @@ function fresh() {
drafts: {},
images: {},
sent: {},
sentAt: null,
stopping: null,
afterBuild: null,
homeward: null,
@@ -870,10 +878,12 @@ function adopt(body) {
chatFrame = body.chat || null;
if (body.workspace) wsFrame = body.workspace;
if (body.meter) meterFrame = body.meter;
// Always replaced: an absent key means no update.
updateFrame = body.update || null;
lastContact = Date.now();
if (gone) {
gone = false;
banner(null);
if ($("banner").textContent === GONE_BANNER) banner(null);
}
if (firstLoad) {
load();
@@ -1016,7 +1026,9 @@ function adopt(body) {
render();
if ($("workspace-modal").open) renderWorkspace();
tellFolderIssues();
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow) loadOverview();
// The Overview tab's file changes under a build, so a tab you are watching
// refetches on every new frame too, not only on the click that opened it.
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow || view === "overview") loadOverview();
if (announce) showArrival(announce);
// New entries land at the bottom of the rail. Gliding down to them beats
// leaving the list parked where it was while it grew underneath.
@@ -1149,15 +1161,12 @@ function markGone() {
// of the server means there, and a banner promising a reconnect would
// argue with it.
if (!finish() && !stopInProgress()) {
banner(
"Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.",
"warn"
);
banner(GONE_BANNER, "warn");
}
render();
} else if (!bad && gone) {
gone = false;
banner(null);
if ($("banner").textContent === GONE_BANNER) banner(null);
render();
}
}
@@ -1182,7 +1191,6 @@ function connect() {
} catch {}
});
es.addEventListener("submitted", (e) => {
local.sentAt = Date.now();
// Drop only what was actually sent.
//
// This event fires for a send from ANY tab of this session, which is why it
@@ -1799,14 +1807,19 @@ async function sendBrief() {
reply: briefPhrase(choice.range),
}),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
$("brief-modal").close();
banner("Asked for a brief. It will appear as a tab when it is written.", "good");
setTimeout(() => banner(null), 5000);
pendingResult = true;
render();
} catch {
why.textContent = "That did not go through. Try again in a moment.";
} catch (err) {
if (err && err.pending) pendingResult = true;
why.textContent =
err && err.pending
? "Your last answers are still being picked up. Try again in a moment."
: "That did not go through. Try again in a moment.";
} finally {
go.disabled = false;
go.textContent = "Write the brief";
@@ -2515,6 +2528,51 @@ function roleNudge() {
return nudge;
}
// × on the update banner hides it for this console session only, and only
// for the release it named. Blocked storage means "not dismissed".
function updateDismissKey() {
try {
return "p2c-update-dismissed:" + S.sid;
} catch {
return "p2c-update-dismissed:";
}
}
function updateDismissed() {
try {
return sessionStorage.getItem(updateDismissKey()) === updateFrame.latest;
} catch {
return false;
}
}
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
const UPDATE_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
function releasesLink(text) {
const a = el("a", null, text);
a.href = RELEASES_URL;
a.target = "_blank";
a.rel = "noopener noreferrer";
return a;
}
function openUpdateModal() {
if (!updateFrame) return;
const versions = $("update-versions");
versions.replaceChildren(
document.createTextNode("Version "),
releasesLink("v" + updateFrame.latest),
document.createTextNode(" is out — you have "),
el("code", null, updateFrame.installed),
document.createTextNode(".")
);
const row = $("update-command");
const code = el("code", null, UPDATE_COMMAND);
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
$("update-modal").showModal();
}
function renderDashboard(main) {
maybeWake();
const menu = (S && S.menu) || {};
@@ -2526,6 +2584,25 @@ function renderDashboard(main) {
warn.setAttribute("role", "status");
wrap.appendChild(warn);
}
// Built here only, so no other workflow's page ever shows it.
if (updateFrame && !updateDismissed()) {
const notice = el("div", "dash-nudge update-banner");
notice.setAttribute("role", "status");
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + updateFrame.latest);
open.type = "button";
open.addEventListener("click", openUpdateModal);
const dismiss = el("button", "update-banner-dismiss", "×");
dismiss.type = "button";
dismiss.setAttribute("aria-label", "Dismiss until next time");
dismiss.addEventListener("click", () => {
try {
sessionStorage.setItem(updateDismissKey(), updateFrame.latest);
} catch {}
render();
});
notice.append(open, dismiss);
wrap.appendChild(notice);
}
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
if (typeof menu.note === "string" && menu.note.trim()) {
@@ -3223,7 +3300,11 @@ document.addEventListener("keydown", cancelSkipMove, true);
function skipAndMoveOn(id) {
cancelSkipMove();
local.skipFlash = id;
stage(id, { type: "skip", skipped: true });
// A note already typed goes along: skipping the question is not retracting
// the comment. Dropping it would leave the text in the box but out of the
// send, which looks kept and is not.
const cur = local.staged[id];
stage(id, { type: "skip", skipped: true, ...(cur && cur.text ? { text: cur.text } : {}) });
skipTimer = setTimeout(() => {
skipTimer = null;
local.skipFlash = null;
@@ -3340,19 +3421,24 @@ function renderWaiting(main) {
}
pane.appendChild(title);
pane.appendChild(el("p", null, doing));
const ask = "If Plan2Code needs you, the question appears here on its own.";
if (!docs().length) {
pane.appendChild(el("p", null, "If Plan2Code needs you, the question appears here on its own."));
pane.appendChild(el("p", null, ask));
return;
}
// "Task" and the tasks tab's own name both open that tab, so the pointer is
// one click from what it points at. A build posts it as `phase` ("Phase N
// tasks"), a quick task as `tasks`; with neither the words stay plain.
// tasks"), a quick task as `tasks`. A skill with no task list (Document,
// Plan) has nothing live to follow, so it gets no pointer at all.
const list =
docs().find((d) => d.id === "phase") ||
docs().find((d) => d.id === "tasks") ||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
if (!list) {
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
return;
}
const jump = (word) => {
if (!list) return el("strong", "waiting-jump", word);
const b = el("button", "waiting-jump", word);
b.type = "button";
b.addEventListener("click", () => {
@@ -3366,8 +3452,8 @@ function renderWaiting(main) {
"The tabs above fill in as it goes. You can follow along with live ",
jump("Task"),
" updates in the ",
jump((list && list.title) || "Phase tasks"),
" tab. If Plan2Code needs you, the question appears here on its own."
jump(list.title || "Phase tasks"),
" tab. " + ask
);
pane.appendChild(p);
}
@@ -3505,8 +3591,8 @@ function renderSettled(card, item) {
// would misreport which of the two was the answer.
let prose = text;
if (!prose && !lines.length) {
const mine = (item.thread || []).filter((m) => m.who === "user");
if (mine.length) prose = String(mine[mine.length - 1].text || "").trim();
const mine = (item.thread || []).filter((m) => threadWho(m) === "user");
if (mine.length) prose = threadText(mine[mine.length - 1]).trim();
}
const nothing = !lines.length && !prose;
@@ -4322,6 +4408,10 @@ function buildChecklist(card, item, staged) {
const commitList = (change) => {
const cur = local.staged[item.id];
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
// A tick or a state IS the answer, so it ends a skip staged earlier:
// left in place, `skipped` would collapse the reply to "skip" while the
// card showed ticked steps on their way.
delete next.skipped;
const empty = !(next.done && next.done.length) && !next.state && !next.text;
stage(item.id, empty ? null : next);
};
@@ -4371,7 +4461,7 @@ function buildChecklist(card, item, staged) {
function buildMenu(card, item, staged) {
const list = el("ul", "options");
const name = "menu-" + item.id;
for (const o of item.options || []) {
for (const [i, o] of (item.options || []).entries()) {
const picked = staged && staged.k === o.k;
const li = el("li", "option" + (picked ? " is-picked" : ""));
const label = el("label");
@@ -4379,7 +4469,13 @@ function buildMenu(card, item, staged) {
const radio = el("input");
radio.type = "radio";
radio.name = name;
// The same id buildChoice gives its radios: withFocus finds the focused
// input by id after the render this change() sets off, and without one a
// keyboard user arrowing through the menu lands on <body> every time.
radio.id = optionId(item, o, i);
radio.value = o.k;
radio.checked = Boolean(picked);
radio.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
const body = el("div", "option-body");
const head = el("div", "option-label");
@@ -5276,20 +5372,30 @@ function renderAside() {
)
);
}
// A note that has been sent but not yet picked up: marked as waiting, so the
// send is seen to have gone, until the agent replies. The server writes the
// note into the thread as it arrives; a session from before that has only
// `sentNote`, which gets a box of its own below.
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
let waitingShown = false;
for (const m of thread) {
const box = el("div", "msg " + (m.who === "user" ? "you" : ""));
const mine = threadWho(m) === "user";
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
if (pending) waitingShown = true;
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
const who = el("div", "msg-who");
who.appendChild(el("span", null, m.who === "user" ? "You" : "Plan2Code"));
if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
box.appendChild(who);
box.appendChild(md(m.text, "md"));
const text = threadText(m);
if (text) box.appendChild(md(text, "md"));
const tray = mine ? sentAttachments(m) : null;
if (tray) box.appendChild(tray);
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) {
if (waiting && !waitingShown) {
const box = el("div", "msg you pending");
const who = el("div", "msg-who");
who.appendChild(el("span", null, "You"));
@@ -5589,7 +5695,10 @@ async function attachFiles(itemId, files) {
const taken = wanted.slice(0, room);
// One banner at a time, so every refusal goes into it, each by name.
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
if (taken.length < wanted.length) said.push(chat ? "Up to 5 attachments per question." : "Up to 5 attachments per note.");
if (taken.length < wanted.length)
said.push(
chat ? `Up to ${CHAT_MAX_ATTACHMENTS} attachments per question.` : `Up to ${MAX_ATTACHMENTS} attachments per note.`
);
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
await Promise.all(
taken.map(async (file) => {
@@ -6439,6 +6548,10 @@ async function goHome() {
$("home-modal").close();
} catch (err) {
$("home-modal").close();
// The server is holding an uncollected result: Send, Home and Stop all
// need to read as busy until the frame or the ping says otherwise, same
// as send() and sendAfterBuild() do on a 409.
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
@@ -6499,6 +6612,7 @@ async function stopSession() {
stoppingHidden = false;
} catch (err) {
$("stop-modal").close();
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
@@ -6653,7 +6767,6 @@ function markSent({ sentIds, sentNotes = {}, summaries, values }) {
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
}
local.staged = {};
local.sentAt = Date.now();
save();
}
@@ -6706,7 +6819,7 @@ const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", d
// something the agent never hears.
function tokenFor(item, v) {
const map = item.token || {};
if (v.skipped) return "skip";
if (v.skipped) return v.text ? `skip; ${v.text}` : "skip";
const parts = [];
if (v.k) parts.push(map[v.k] || v.k);
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
@@ -6938,14 +7051,14 @@ function renderAbout() {
let helpBuilt = false;
async function renderHelpVersion() {
const el = $("help-version");
const slot = $("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;
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
slot.hidden = !version;
} catch {
el.hidden = true;
slot.hidden = true;
}
}
@@ -7053,6 +7166,7 @@ function openHelpOn(id) {
}
$("btn-home").addEventListener("click", openHomeConfirm);
$("update-done").addEventListener("click", () => $("update-modal").close());
$("home-cancel").addEventListener("click", () => $("home-modal").close());
$("home-go").addEventListener("click", goHome);
$("btn-stop").addEventListener("click", openStopConfirm);
@@ -7132,6 +7246,7 @@ $("btn-looks").addEventListener("click", () => {
});
$("looks-done").addEventListener("click", () => $("looks-modal").close());
$("looks-modal").addEventListener("close", () => {
resetCleanup();
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
});
$("looks-reset").addEventListener("click", () => {
@@ -7278,6 +7393,111 @@ $("models-reset").addEventListener("click", () => {
renderModels();
});
// Cleanup: the server works out what in ~/.plan2code is not needed and
// shows it first; Delete these sends back only the ids it was shown, and the
// server re-checks every one before removing it.
let cleanupFound = null;
// Bumped by every scan, delete and reset: a response from an older one is
// dropped, so a scan still in flight when Preferences closes cannot refill it.
let cleanupGen = 0;
const CLEANUP_SHOWN = 8;
function setCleanupStatus(text, isError) {
const status = $("cleanup-status");
status.textContent = text;
status.classList.toggle("error", Boolean(isError));
}
function cleanupLabel(item) {
if (item.where === "session") return "Session " + item.name;
const where = item.where === "root" ? "~/.plan2code/" : "~/.plan2code/console/";
return where + item.name + (item.kind === "folder" ? "/" : "");
}
function cleanupSummary(items, bytes) {
const sessions = items.filter((i) => i.where === "session").length;
const strays = items.length - sessions;
const parts = [];
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
return parts.join(", ") + " · " + formatBytes(bytes);
}
function resetCleanup() {
cleanupGen++;
cleanupFound = null;
$("cleanup-list").replaceChildren();
$("cleanup-delete").hidden = true;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
setCleanupStatus("", false);
}
function renderCleanup() {
const list = $("cleanup-list");
list.replaceChildren();
const items = (cleanupFound && cleanupFound.items) || [];
$("cleanup-delete").hidden = !items.length;
if (!items.length) return;
const rows = (some) => some.map((item) => {
const row = el("div", "cleanup-row");
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", formatBytes(item.bytes)));
return row;
});
list.append(el("p", "cleanup-summary", cleanupSummary(items, cleanupFound.bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
if (items.length > CLEANUP_SHOWN) {
const more = el("details", "cleanup-more");
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
list.appendChild(more);
}
}
async function scanCleanup() {
const gen = ++cleanupGen;
$("cleanup-scan").disabled = true;
$("cleanup-delete").disabled = true;
setCleanupStatus("Looking…", false);
const { status, body } = await postJson("/cleanup", { scan: true });
if (gen !== cleanupGen) return;
$("cleanup-scan").disabled = false;
$("cleanup-delete").disabled = false;
if (status !== 200 || !body.ok) {
cleanupFound = null;
renderCleanup();
return setCleanupStatus(status ? body.error || "Could not look." : "Plan2Code isn't reachable.", true);
}
cleanupFound = { items: body.items || [], bytes: body.bytes || 0 };
renderCleanup();
// Left in the status line, not cleared: it is the live region, so this is
// what a screen reader hears when the scan finishes.
const found = cleanupFound.items.length;
setCleanupStatus(found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.", false);
}
async function deleteCleanup() {
if (!cleanupFound || !cleanupFound.items.length) return;
const gen = ++cleanupGen;
$("cleanup-delete").disabled = true;
$("cleanup-scan").disabled = true;
setCleanupStatus("Deleting…", false);
const { status, body } = await postJson("/cleanup", { delete: cleanupFound.items.map((i) => i.id) });
if (gen !== cleanupGen) return;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
if (status !== 200 || !body.ok) {
return setCleanupStatus(status ? body.error || "Could not delete." : "Plan2Code isn't reachable.", true);
}
const removed = (body.removed || []).length;
const failed = (body.failed || []).length;
cleanupFound = null;
renderCleanup();
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
setCleanupStatus(failed ? done + " " + failed + " could not be removed." : done, Boolean(failed));
}
$("cleanup-scan").addEventListener("click", scanCleanup);
$("cleanup-delete").addEventListener("click", deleteCleanup);
$("btn-brief").addEventListener("click", openBrief);
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
$("brief-go").addEventListener("click", sendBrief);
@@ -1291,6 +1291,14 @@
come back, and you can change your role any time from the swatch
button.
</p>
<h4>When an update is out</h4>
<p>
When a newer Plan2Code release is out, the dashboard shows
<strong>UPDATE AVAILABLE</strong> at the top. Click it for the command
to run in your terminal; × hides it until the next
<code>/plan2code</code>. The version at the bottom of Help links to
the Releases page.
</p>
<h4>The cards</h4>
<p>They come in three groups.</p>
<p><strong>First, the project</strong></p>
@@ -1845,6 +1853,15 @@
joining the strip. Keep only the ones you want; ticking a box plays
its sound.
</li>
<li>
<strong>Cleanup</strong>: <strong>Find files to clean up</strong>
lists what Plan2Code doesn't need in your
<code>~/.plan2code</code> folder: sessions nobody has opened for
30 days, and files or folders that ended up there by mistake. It
shows each one with its size, and <strong>Delete these</strong>
removes exactly that list. Your preferences, saved folders, models,
the launcher and the session you are in always stay.
</li>
<li>
<strong>Back to default</strong> puts everything back as it was, and
sets Role back to Not set.
@@ -1983,6 +2000,16 @@
</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-cleanup">
<legend>Cleanup</legend>
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
<div class="models-actions">
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
<button type="button" class="btn small danger" id="cleanup-delete" hidden>Delete these</button>
<span class="help" id="cleanup-status" role="status"></span>
</div>
</fieldset>
<fieldset class="modal-ranges looks-models">
<legend>Models</legend>
<div class="models-tabs" role="group" aria-label="Which agent">
@@ -2181,6 +2208,24 @@
</div>
</dialog>
<!-- Opened from the dashboard's UPDATE AVAILABLE banner. The versions and
the copy row are filled by app.js; the update itself runs in a
terminal, never from this page. -->
<dialog class="modal" id="update-modal" aria-labelledby="update-title">
<h2 id="update-title">A new Plan2Code is available</h2>
<p class="modal-blurb" id="update-versions"></p>
<ol class="update-steps">
<li>
Run this in your terminal (not in this page or your agent):
<div class="update-command" id="update-command"></div>
</li>
<li>When it finishes, close this console and start <code>plan2code</code> again.</li>
</ol>
<div class="modal-actions">
<button type="button" class="btn primary" id="update-done">Close</button>
</div>
</dialog>
<footer class="footer">
<div class="footer-summary" id="footer-summary" aria-live="polite">
Nothing to send yet.
@@ -5,7 +5,10 @@
// popover; this file owns the rules. No DOM access at module scope and no
// imports: the page and `node --test` both import this file.
const NAME_CHAR = /[a-z0-9-]/;
// Uppercase too: "@Repo" must still name @repo — names are forced lowercase
// by the workspace rules, and a query typed with a capital otherwise matches
// nothing and opens no suggestions at all.
const NAME_CHAR = /[a-z0-9-]/i;
const MAX_MATCHES = 6;
/**
@@ -23,11 +26,13 @@ export function mentionAt(text, caret) {
}
// Names starting with the query first, then names containing it, in the
// order given, at most six.
// order given, at most six. Case-folded: folder names are lowercase by rule,
// and "@Repo" should still find @repo rather than claim nothing matches.
export function matchNames(names, query) {
const q = String(query || "");
const prefix = names.filter((n) => n.startsWith(q));
const inside = names.filter((n) => !n.startsWith(q) && n.includes(q));
const q = String(query || "").toLowerCase();
const fold = (n) => String(n).toLowerCase();
const prefix = names.filter((n) => fold(n).startsWith(q));
const inside = names.filter((n) => !fold(n).startsWith(q) && fold(n).includes(q));
return [...prefix, ...inside].slice(0, MAX_MATCHES);
}
@@ -25,12 +25,14 @@ import {
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
UPDATE_CHECK_FILE,
USER_MODELS_FILE,
WORKSPACE_FILE,
appendChat,
appendEvent,
chatForFrame,
checkDocument,
cleanupFindings,
currentConversation,
ensureDir,
fileStamp,
@@ -47,6 +49,7 @@ import {
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
removeCleanup,
remoteWarning,
specKey,
typedCount,
@@ -59,6 +62,7 @@ import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
import { meterView } from "./public/meter.js";
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
import { checkForUpdate } from "./update-check.mjs";
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
const args = parseArgs(process.argv.slice(2));
@@ -611,6 +615,7 @@ function stateFrame(state) {
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
workspace: workspaceView(),
meter: meterView(ledgerEntries()),
...(updateInfo ? { update: updateInfo } : {}),
have: haveKey(),
};
}
@@ -623,7 +628,7 @@ function haveKey() {
ledgerEntries();
return (
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}`
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}`
);
}
@@ -648,6 +653,12 @@ function recordSubmitted(state, actions) {
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) };
// The person's side of the Notes thread. Left to the agent it was never
// written, so a question asked in a note vanished once it was picked up
// and the reply under it answered nothing on the page.
if (item.sentNote.text.trim() || item.sentNote.images.length || item.sentNote.files.length) {
item.thread = [...(Array.isArray(item.thread) ? item.thread : []), { who: "user", ...item.sentNote }];
}
continue;
}
const { i, type, ...rest } = action;
@@ -933,6 +944,38 @@ function pushState() {
if (stateNow) broadcast("state", stateFrame(stateNow));
}
/* --------------------------------------------------------- update check */
// The version this console was installed as: install.js writes version.json
// beside console.mjs; a dev checkout falls back to the repo root's.
function installedVersion() {
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 version;
}
return null;
}
// Filled in once the boot-time check answers; until then, and whenever it
// fails, the frame carries no `update` and the page shows no banner.
let updateInfo = null;
let updateLatest = null;
// Started at boot and never awaited: git may take up to its 10 s limit, and
// nothing the person sees waits on it. The catch is not optional: a throw in
// pushState() would otherwise be an unhandled rejection, which ends the server.
function startUpdateCheck() {
const installed = installedVersion();
if (!installed) return;
checkForUpdate({ installed, cacheFile: UPDATE_CHECK_FILE })
.then((result) => {
updateLatest = result?.latest ?? null;
updateInfo = result?.updateAvailable ? { installed: result.installed, latest: result.latest } : null;
if (updateInfo) pushState();
})
.catch(() => {});
}
let agentSeenAt = Date.now();
function agentLastSeen() {
return new Date(agentSeenAt).toISOString();
@@ -1039,10 +1082,8 @@ const server = http.createServer((req, res) => {
}
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 });
}
const version = installedVersion();
if (version) return json(res, 200, { version, latest: updateLatest });
return json(res, 404, { error: "no version" });
}
@@ -1090,7 +1131,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/draft" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
// Debounced client-side; this is just the durable mirror. Twenty minutes
// of someone's structured answers must not die with a closed tab.
try {
@@ -1115,7 +1156,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/looks" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
// `set` carries only the keys one tab changed, merged onto what is on
// disk, so a tab holding stale settings cannot undo another tab's change.
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
@@ -1141,7 +1182,7 @@ const server = http.createServer((req, res) => {
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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
const { models, error } = cleanModels(body && body.models);
if (error) return json(res, 400, { error });
try {
@@ -1154,6 +1195,24 @@ const server = http.createServer((req, res) => {
});
}
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
// ~/.plan2code; `{ delete: [id] }` removes those of the ids a fresh scan
// still finds. Never this session, never a path the page sent.
if (pathname === "/cleanup" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
if (body && Array.isArray(body.delete)) {
return removeCleanup(body.delete, { skipSid: SID })
.then((done) => json(res, 200, { ok: true, ...done }))
.catch((e) => json(res, 500, { error: String(e.message) }));
}
return cleanupFindings({ skipSid: SID })
.then(({ items, bytes }) => json(res, 200, { ok: true, bytes, items: items.map(({ path: _p, ...item }) => item) }))
.catch((e) => json(res, 500, { error: String(e.message) }));
});
}
if (pathname === "/upload" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
const contentType = String(req.headers["content-type"] || "");
@@ -1260,7 +1319,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/submit" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
if (!body || !Array.isArray(body.actions) || body.actions.length === 0) {
return json(res, 400, { error: "actions must be a non-empty array" });
}
@@ -1361,6 +1420,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/chat" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const state = readState() || {};
const current = currentConversation(chatEntries()).conversation;
@@ -1424,6 +1484,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/chat/decision" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
if (body.decision !== "approve" && body.decision !== "decline") return json(res, 400, { error: "bad" });
if (body.text !== undefined && typeof body.text !== "string") return json(res, 400, { error: "bad" });
@@ -1472,6 +1533,7 @@ const server = http.createServer((req, res) => {
if (Object.hasOwn(workspaceRoutes, pathname) && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
let answer;
try {
@@ -1489,6 +1551,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/workspace/scope" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const spec = typeof body.spec === "string" ? body.spec : "";
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
@@ -1589,15 +1652,19 @@ function readBody(req, cb) {
let tooBig = false;
req.on("data", (c) => {
size += c.length;
// Drain past the cap rather than destroy, exactly like readRaw: a
// destroyed request emits 'close', never 'end' or 'error', so cb would
// never run and the page would see a reset instead of the 413 that names
// the problem.
if (size > MAX_BODY) {
tooBig = true;
req.destroy();
chunks.length = 0;
return;
}
chunks.push(c);
});
req.on("end", () => {
if (tooBig) return cb(new Error("too large"));
if (tooBig) return cb(Object.assign(new Error("too large"), { tooBig: true }));
try {
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
} catch (e) {
@@ -1834,6 +1901,9 @@ function onListening(port) {
bootWorkspace();
} catch {}
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
try {
startUpdateCheck();
} catch {}
try {
process.send?.({ type: "listening", port });
} catch {}
@@ -0,0 +1,138 @@
// Plan2Code Web Console - is a newer Plan2Code release out?
//
// `git ls-remote --tags` needs no API token and no rate-limited REST call,
// rides on the person's own git and proxy setup, and the newest `vX.Y.Z`
// release tag is "latest". The server
// starts this at boot and never waits on it; the answer, failures included, is
// cached for an hour so a burst of sessions asks GitHub once.
//
// Nothing here reads, stores or sends a credential: git authenticates itself,
// with every prompt turned off so a missing login fails fast instead of
// opening a window nobody asked for.
//
// Node built-ins only.
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
export const REPO_URL = "https://github.com/jparkerweb/plan2code.git";
export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
export const CACHE_MS = 60 * 60 * 1000;
const SEMVER = /^\d+\.\d+\.\d+$/;
const TAG_REF = /refs\/tags\/v(\d+\.\d+\.\d+)$/;
/** -1, 0 or 1 comparing two plain X.Y.Z versions numerically; null unless both are X.Y.Z. */
export function compareVersions(a, b) {
if (typeof a !== "string" || typeof b !== "string" || !SEMVER.test(a) || !SEMVER.test(b)) return null;
const x = a.split(".").map(Number);
const y = b.split(".").map(Number);
for (let i = 0; i < 3; i++) {
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
}
return 0;
}
/**
* The highest `vX.Y.Z` tag in `git ls-remote --tags` output, without the `v`.
* Peeled lines (`^{}`) never match, so an annotated tag counts once, and
* pre-releases or other tag names are ignored. Null when nothing matches.
*/
export function latestTag(text) {
if (typeof text !== "string") return null;
let best = null;
for (const line of text.split(/\r?\n/)) {
const m = TAG_REF.exec(line.trim());
if (m && (best === null || compareVersions(m[1], best) > 0)) best = m[1];
}
return best;
}
function readCache(cacheFile, now) {
try {
const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
if (!cached || typeof cached.checkedAt !== "number" || now - cached.checkedAt >= CACHE_MS) return undefined;
return typeof cached.latest === "string" ? cached.latest : null;
} catch {
return undefined;
}
}
function writeCache(cacheFile, data) {
const tmp = cacheFile + "." + process.pid + ".tmp";
try {
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
fs.renameSync(tmp, cacheFile);
} catch {
try {
fs.rmSync(tmp, { force: true });
} catch {}
}
}
/**
* `git ls-remote --tags` against the repo: resolves its stdout, or null when
* git is missing, fails, or is still going after `timeoutMs`. No shell, no
* window, no prompt.
*/
export function runLsRemote({ timeoutMs = 10000 } = {}) {
return new Promise((resolve) => {
let settled = false;
const done = (value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(value);
};
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
if (!process.env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
let child;
try {
child = spawn("git", ["ls-remote", "--tags", REPO_URL], {
shell: false,
windowsHide: true,
stdio: ["ignore", "pipe", "ignore"],
env,
});
} catch {
return resolve(null);
}
const timer = setTimeout(() => {
try {
child.kill();
} catch {}
done(null);
}, timeoutMs);
timer.unref?.();
let out = "";
child.stdout.setEncoding("utf8");
child.stdout.on("data", (chunk) => {
out += chunk;
});
child.on("error", () => done(null));
child.on("close", (code) => done(code === 0 ? out : null));
});
}
/**
* Whether `installed` is behind the newest release: `{ installed, latest,
* updateAvailable }`, or null when either version is unknown. Reuses a cache
* under an hour old, and caches a failed lookup as `latest: null` so it is
* not retried until the hour is up. Never throws.
*/
export async function checkForUpdate({ installed, cacheFile, now = Date.now(), run = runLsRemote }) {
try {
let latest = readCache(cacheFile, now);
if (latest === undefined) {
latest = latestTag(await run());
writeCache(cacheFile, { checkedAt: now, latest });
}
const order = compareVersions(installed, latest);
if (latest === null || order === null) return null;
return { installed, latest, updateAvailable: order < 0 };
} catch {
return null;
}
}
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -57,7 +57,7 @@ Run against EVERY finding. If any question raises doubt, re-investigate or drop.
**Finding survives (real bug):** Reviewer finds `processItems()` at line 47 accesses `items[0].id` with no empty-array check. Re-reads source — confirmed no guard. Traces callers — `orchestrator.js:82` can pass empty array. Adversarial check passes (correctness issue, additive fix). Presented at High.
**Finding dropped (pcweb-jira false positive):** Reviewer recommends removing `jira-api-catalog.md` from consumer loading to "reduce context." Adversarial check: "Does my fix remove something the system depends on?" YES — agents Read these files at runtime to construct valid API calls. Four of five checks fail. Dropped.
**Finding dropped (jira skill false positive):** Reviewer recommends removing `jira-api-catalog.md` from consumer loading to "reduce context." Adversarial check: "Does my fix remove something the system depends on?" YES — agents Read these files at runtime to construct valid API calls. Four of five checks fail. Dropped.
**Finding dropped (false consolidation):** Reviewer flags per-platform config files as "duplicates." Adversarial check: "Am I optimizing for the wrong metric?" YES — platforms have distinct values and will diverge further. Separation is a design choice. Dropped.
@@ -243,7 +243,7 @@ summarise it back.
Then, in ONE `post`, do all of:
- mark each answered item `"status": "answered"` and record its `answer`
- add your replies to any comment threads
- reply to every note in that item's `thread` (shape below)
- answer any Quick questions that came with it, in `chat.replies` (see Quick
questions)
- publish the next batch of questions
@@ -251,6 +251,26 @@ Then, in ONE `post`, do all of:
One post is one atomic update, so the page never shows a half-changed state.
### Replying to a note
A `comment` is the person talking to you about that card, often asking
something. It shows in the card's **Notes on this** panel, and so does your
answer:
```jsonc
{ "items": [{ "id": "p4", "thread": [
{ "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." }
] }] }
```
- Every entry is `{ "who": "agent", "text": "<markdown>" }`. `text`, not
`md`: the page reads nothing else. An entry with no `text` is rejected.
- The server writes their note into the thread as it arrives. Do not repeat
it, and send only your new entries: `thread` appends.
- Answer what they asked, in the thread, even when you also change a doc or
re-ask the question. "I've updated the doc" alone leaves the question in the
panel with no answer under it.
### Recording the answer
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
@@ -661,9 +681,17 @@ finish are dropped, so you start on a blank page and post your own. A skill
run inline from another (a quick task's review) keeps the page it was
handed. A
fresh `open` would strand the page the person is watching on the dashboard's
session while your questions went to a page nobody has open. Then run the
skill normally: its Interface question was already answered by being
launched, so start where its real work starts.
session while your questions went to a page nobody has open.
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
> own file-read tool and follow it from the top instead.** Every Plan2Code
> skill below the dashboard ships `disable-model-invocation: true` on
> purpose — it exists to be read and followed inline, not launched as a
> sub-skill — and calling one through a skill-invocation tool errors out and
> strands the hand-off mid-launch.
Its Interface step is already answered by having been launched, so start
where its real work starts.
The menu itself is the page's own list — you never send it. The page knows
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
@@ -829,6 +857,12 @@ know:
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
Post `activity` as each step starts, before its doc or question lands — reading
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
implementation — the same way Review does. A step with no card of its own
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
Finalize".
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
Stopping mid-finalize loses nothing
— the specs are untouched until Step 3's summary write — so a stop's finish
@@ -859,7 +893,7 @@ question or doc lands:
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
merge by `id` (an unknown id is added), and `thread` / `comments` append. Send only
merge by `id` (an unknown id is added), and `thread` appends. Send only
what changed. A whole-file rewrite would put the entire session back into your
context on every turn.
@@ -1239,7 +1273,7 @@ answers were submitted but never picked up.
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` and `comments` **append**: leave out any thread entry you already sent, or the person sees your reply twice. |
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
@@ -48,6 +48,10 @@ export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
// so every session within the hour reuses one lookup.
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
// test run (or a second sandboxed instance) shares one handle directory with
// the real thing, and `stop --all` reaches outside its own world and kills a
@@ -487,9 +491,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks, the folders remembered per project and spec, and the pointer to
// this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
// looks, the folders remembered per project and spec, the pointer to this
// console's directory, and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir", "update-check.json"]);
function isScratchName(name) {
return (
@@ -536,6 +540,148 @@ export async function removeScratch(consoleDir, names) {
return removed;
}
/* ------------------------------------------------------------- cleanup */
// What User Preferences -> Cleanup never removes. The console folder keeps its
// protected files, its sessions dir (old sessions go one by one, by age) and,
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
// console, the launcher (bin/, launcher.json) and the models the person added.
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
// A stray must sit untouched this long before Cleanup lists it. The same
// folders hold files that live for milliseconds -- a held
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
// rename -- and removing one mid-write loses another session's change.
export const STRAY_GRACE_MS = 60 * 60 * 1000;
// Bytes under `p`, never following a symlink: a link counts as itself.
async function diskBytes(p) {
let st;
try {
st = await fs.promises.lstat(p);
} catch {
return 0;
}
if (!st.isDirectory()) return st.size;
let entries;
try {
entries = await fs.promises.readdir(p);
} catch {
return 0;
}
let total = 0;
for (const name of entries) total += await diskBytes(path.join(p, name));
return total;
}
// The newest mtime of anything under `p`, never following a symlink. A folder
// counts by its files, since rewriting a file never touches its folder's
// mtime; an empty folder counts by its own. Anything unreadable on the way
// down answers Infinity, so it reads as just touched and stays.
function newestMtime(p) {
let st;
try {
st = fs.lstatSync(p);
} catch {
return Infinity;
}
if (!st.isDirectory()) return st.mtimeMs;
let entries;
try {
entries = fs.readdirSync(p);
} catch {
return Infinity;
}
if (!entries.length) return st.mtimeMs;
let newest = 0;
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
return newest;
}
function entryKind(entry) {
if (entry.isSymbolicLink()) return "link";
return entry.isDirectory() ? "folder" : "file";
}
function strayEntries(dir, kept, where, now) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return [];
}
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
return entries
.filter((e) => !kept.has(e.name))
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
.filter((e) => settled(e.path));
}
/**
* Everything Cleanup would remove, worked out on the server and never taken
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
* `open` sweeps by, plus every file in the folder that old, so a resumed
* session or a saved draft keeps it), anything at the top of the console folder that is
* not kept, and -- only when the console runs from its default home inside
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
* touched within `STRAY_GRACE_MS` are left for a later scan. A
* console running from another home (tests, dev) never reaches ~/.plan2code.
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
*/
export async function cleanupFindings({
consoleDir = HOME_DIR,
plan2codeDir = PLAN2CODE_DIR,
now = Date.now(),
maxAgeMs = SESSION_MAX_AGE_MS,
skipSid,
} = {}) {
const found = [];
const sessionsDir = path.join(consoleDir, "sessions");
for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) {
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
}
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
}
const items = [];
let bytes = 0;
for (const f of found) {
const size = await diskBytes(f.path);
bytes += size;
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
}
return { items, bytes };
}
/**
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
* worked out afresh first and only ids on it are touched, so a name from the
* page is never a path, and anything that stopped qualifying since the scan
* (a session touched again) stays. A link is unlinked, never followed.
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
*/
export async function removeCleanup(ids, opts = {}) {
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
const { items } = await cleanupFindings(opts);
const removed = [];
const failed = [];
let bytes = 0;
for (const item of items) {
if (!wanted.has(item.id)) continue;
try {
if (item.kind === "link") await fs.promises.unlink(item.path);
else await fs.promises.rm(item.path, { recursive: true, force: true });
removed.push(item.id);
bytes += item.bytes;
} catch {
failed.push(item.id);
}
}
return { removed, bytes, failed };
}
/**
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
* the file's realpath must sit inside the root's, so `../`, an absolute path
@@ -871,7 +1017,7 @@ export function handOff(child, pre) {
/* ----------------------------------------------------------- patch merge */
const APPEND_KEYS = new Set(["thread", "comments"]);
const APPEND_KEYS = new Set(["thread"]);
function isPlainObject(v) {
return v !== null && typeof v === "object" && !Array.isArray(v);
@@ -896,7 +1042,7 @@ function mergeOne(target, patch, where) {
}
// Merge a keyed collection: a known id merges one level, an unknown id appends.
// Named fields are replaced whole; thread/comments append.
// Named fields are replaced whole; thread appends.
function mergeKeyed(current, patchList, idKey, defaults, where) {
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
for (const entry of patchList) {
@@ -955,6 +1101,42 @@ function dropStaleSubmissions(currentItems, before, patchList) {
return merged;
}
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
// borrow the shape of the replies and doc blocks they also write, so `from` /
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
// at all is refused. The person's own notes are recorded by the server when
// they send, so an agent that echoes one back is not shown it twice.
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
function normalizeThreads(patchList, currentItems) {
return patchList.map((entry) => {
if (!isPlainObject(entry) || entry.thread == null) return entry;
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
const said = new Set(
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
);
const thread = [];
for (const m of entry.thread) {
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
guard(m, "thread");
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
if (!key) {
throw new Error(
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
);
}
const { from, role, md, body, content, ...rest } = m;
const who = (m.who || from || role) === "user" ? "user" : "agent";
const text = m[key];
if (who === "user" && said.has(text.trim())) continue;
thread.push({ ...rest, who, text });
}
return { ...entry, thread };
});
}
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
@@ -996,7 +1178,7 @@ export function applyPatch(state, patch) {
break;
case "items":
if (!Array.isArray(v)) throw new Error('"items" must be an array');
next.items = dropStaleSubmissions(next.items, state.items, v);
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
break;
case "topics":
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
@@ -1048,15 +1230,11 @@ function stampTimes(before, next) {
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
}
for (const list of [next.items, next.docs]) {
if (!Array.isArray(list)) continue;
for (const entry of list) {
if (Array.isArray(next.items)) {
for (const entry of next.items) {
if (Array.isArray(entry.thread)) {
for (const m of entry.thread) if (!m.at) m.at = now;
}
if (Array.isArray(entry.comments)) {
for (const m of entry.comments) if (!m.at) m.at = now;
}
}
}
if (Array.isArray(next.docs)) {
@@ -1289,7 +1467,10 @@ 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, sentNote, ...rest }) => rest);
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
...rest,
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
}));
const prose =
JSON.stringify(authored) +
JSON.stringify(state.docs || []) +
@@ -65,7 +65,7 @@ export function submittedAwaiting(item) {
if (!s || typeof s !== "object") return null;
if (item.answer && typeof item.answer === "object") return null;
const thread = Array.isArray(item.thread) ? item.thread : [];
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
return replied ? null : s;
}
@@ -74,17 +74,33 @@ export function submittedAwaiting(item) {
* 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.
* Any agent message from the send onwards, or one with no clock to compare,
* means it has been picked up. The person's own entries never count: the
* server writes their note into the thread as it arrives.
*/
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));
const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at));
return picked ? null : n;
}
/**
* Who said a thread entry and what they said. The contract is `{ who, text }`
* and the server lifts anything else into it, but sessions written before that
* hold `{ from, md }` replies, which would otherwise draw as empty bubbles.
*/
export function threadWho(m) {
return m && (m.who || m.from || m.role) === "user" ? "user" : "agent";
}
export function threadText(m) {
if (!m) return "";
for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k];
return "";
}
/* -------------------------------------------------------------- labels */
export function optionLabel(item, k) {
@@ -23,6 +23,9 @@
--warn-soft: #fbe7e3;
--focus: #1f6feb;
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
/* A soft accent halo for the things that want noticing: the update banner
and an enabled Send. Built from --accent, so a picked accent glows too. */
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
@@ -61,6 +64,7 @@
--warn-soft: #34201d;
--focus: #6aa3ff;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
}
}
@@ -85,6 +89,7 @@
--warn-soft: #34201d;
--focus: #6aa3ff;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
}
* { box-sizing: border-box; }
@@ -1097,10 +1102,11 @@ h1 {
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
the tiny ring, left of the label. */
.view-tab .tab-spin {
the tiny ring, left of the label. The extra .spinner is for specificity:
.spinner.tiny comes later and zeroes the margin otherwise. */
.view-tab .spinner.tab-spin {
display: inline-block;
margin-right: 6px;
margin-right: 7px;
vertical-align: -1px;
}
@@ -1657,11 +1663,13 @@ input[type="text"].invalid { border-color: var(--warn); }
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
/* Send breathes while there is something to send: a soft accent ring that
spreads and fades. Off under reduced motion, below. */
/* Send glows and breathes while there is something to send: the steady
--glow, plus a soft accent ring that spreads and fades. The ring is off
under reduced motion, below; the glow stays. */
#btn-send:not(:disabled) { box-shadow: var(--glow); }
@keyframes send-pulse {
0% { box-shadow: 0 0 0 0 var(--accent-line); }
100% { box-shadow: 0 0 0 6px transparent; }
0% { box-shadow: var(--glow), 0 0 0 0 var(--accent-line); }
100% { box-shadow: var(--glow), 0 0 0 6px transparent; }
}
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
@@ -2219,6 +2227,7 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
.modal.help[open] { display: flex; }
.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-version a { color: inherit; }
.help-layout {
display: grid;
@@ -2668,6 +2677,74 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
border-left-width: 4px;
color: var(--ink);
}
/* A newer release: the same slot, in the accent, with the label as the way
into the update modal and a small × that hides it for this session. */
.dash-nudge.update-banner {
position: relative;
padding-left: 40px;
padding-right: 40px;
border-left-width: 4px;
border-left-color: var(--accent-line);
color: var(--ink);
box-shadow: var(--glow);
}
.update-banner-open {
flex: 1 1 16em;
padding: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
font-weight: 600;
letter-spacing: 0.02em;
text-align: center;
cursor: pointer;
}
.update-banner-open:hover { text-decoration: underline; }
/* Pinned to the right edge, out of the flow, so the label centres on the
whole banner rather than on what the × leaves of it. */
.update-banner-dismiss {
position: absolute;
top: 50%;
right: 10px;
transform: translateY(-50%);
padding: 0 6px;
border: 0;
border-radius: var(--radius);
background: none;
color: inherit;
font: inherit;
font-size: 16px;
line-height: 1;
cursor: pointer;
}
.update-banner-dismiss:hover { background: var(--accent-line); }
/* Wide enough that the update command sits on one line beside Copy; a
narrow window still wraps it rather than overflowing. */
#update-modal { max-width: 720px; }
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
.update-steps li { margin: 4px 0; }
/* The hand-off copy row, in the modal's first step: the command and its Copy
side by side. */
.update-command {
margin: 6px 0 4px;
display: flex;
align-items: stretch;
gap: 10px;
flex-wrap: wrap;
}
.update-command code {
flex: 1 1 260px;
min-width: 0;
font: 13px/1.5 var(--mono);
color: var(--ink);
background: var(--panel);
border: 1px solid var(--rule-2);
border-radius: 8px;
padding: 10px 12px;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
.dash-working {
@@ -3394,6 +3471,18 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.models-actions .help.error { color: var(--danger, #d64545); }
/* User Preferences: Cleanup's list of what would go, shown before anything
is deleted. */
.cleanup-list { display: grid; gap: 4px; max-height: 200px; overflow: auto; font-size: 0.88em; }
.cleanup-list:empty { display: none; }
.cleanup-summary { margin: 0 0 2px; font-weight: 600; }
.cleanup-row { display: flex; justify-content: space-between; gap: 12px; }
.cleanup-row span:first-child { min-width: 0; overflow-wrap: anywhere; font-family: var(--mono); }
.cleanup-size { flex: none; color: var(--ink-3); }
.cleanup-more { display: grid; gap: 4px; }
.cleanup-more summary { cursor: pointer; color: var(--ink-2); }
#cleanup-delete[hidden] { display: none; }
/* 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 {
@@ -66,6 +66,8 @@ import {
submittedAwaiting,
noteAwaiting,
suggestionFrom,
threadText,
threadWho,
THUMB_EDGE,
turnGate,
verdictText,
@@ -446,6 +448,10 @@ document.addEventListener("click", (e) => {
const GONE_AFTER_MS = 8000;
// Named so a reconnect can clear only THIS banner: a bare banner(null) would
// wipe an unrelated warning that landed while the page was gone (an upload
// failure, a refused send).
const GONE_BANNER = "Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.";
const WORKING_GRACE_MS = 5 * 60 * 1000;
// Two minutes with the agent mid-turn, three when it is merely meant to be
// listening. The difference is the cost of being wrong: a working agent that
@@ -521,6 +527,9 @@ let chatFrame = null;
// sends them.
let wsFrame = null;
let meterFrame = null;
// The frame's update ({ installed, latest }), present only when a newer
// release is out; null otherwise.
let updateFrame = null;
let chatDot = false;
let chatSending = false;
let chatResetting = false;
@@ -566,7 +575,6 @@ function fresh() {
drafts: {},
images: {},
sent: {},
sentAt: null,
stopping: null,
afterBuild: null,
homeward: null,
@@ -870,10 +878,12 @@ function adopt(body) {
chatFrame = body.chat || null;
if (body.workspace) wsFrame = body.workspace;
if (body.meter) meterFrame = body.meter;
// Always replaced: an absent key means no update.
updateFrame = body.update || null;
lastContact = Date.now();
if (gone) {
gone = false;
banner(null);
if ($("banner").textContent === GONE_BANNER) banner(null);
}
if (firstLoad) {
load();
@@ -1016,7 +1026,9 @@ function adopt(body) {
render();
if ($("workspace-modal").open) renderWorkspace();
tellFolderIssues();
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow) loadOverview();
// The Overview tab's file changes under a build, so a tab you are watching
// refetches on every new frame too, not only on the click that opened it.
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow || view === "overview") loadOverview();
if (announce) showArrival(announce);
// New entries land at the bottom of the rail. Gliding down to them beats
// leaving the list parked where it was while it grew underneath.
@@ -1149,15 +1161,12 @@ function markGone() {
// of the server means there, and a banner promising a reconnect would
// argue with it.
if (!finish() && !stopInProgress()) {
banner(
"Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.",
"warn"
);
banner(GONE_BANNER, "warn");
}
render();
} else if (!bad && gone) {
gone = false;
banner(null);
if ($("banner").textContent === GONE_BANNER) banner(null);
render();
}
}
@@ -1182,7 +1191,6 @@ function connect() {
} catch {}
});
es.addEventListener("submitted", (e) => {
local.sentAt = Date.now();
// Drop only what was actually sent.
//
// This event fires for a send from ANY tab of this session, which is why it
@@ -1799,14 +1807,19 @@ async function sendBrief() {
reply: briefPhrase(choice.range),
}),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
$("brief-modal").close();
banner("Asked for a brief. It will appear as a tab when it is written.", "good");
setTimeout(() => banner(null), 5000);
pendingResult = true;
render();
} catch {
why.textContent = "That did not go through. Try again in a moment.";
} catch (err) {
if (err && err.pending) pendingResult = true;
why.textContent =
err && err.pending
? "Your last answers are still being picked up. Try again in a moment."
: "That did not go through. Try again in a moment.";
} finally {
go.disabled = false;
go.textContent = "Write the brief";
@@ -2515,6 +2528,51 @@ function roleNudge() {
return nudge;
}
// × on the update banner hides it for this console session only, and only
// for the release it named. Blocked storage means "not dismissed".
function updateDismissKey() {
try {
return "p2c-update-dismissed:" + S.sid;
} catch {
return "p2c-update-dismissed:";
}
}
function updateDismissed() {
try {
return sessionStorage.getItem(updateDismissKey()) === updateFrame.latest;
} catch {
return false;
}
}
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
const UPDATE_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
function releasesLink(text) {
const a = el("a", null, text);
a.href = RELEASES_URL;
a.target = "_blank";
a.rel = "noopener noreferrer";
return a;
}
function openUpdateModal() {
if (!updateFrame) return;
const versions = $("update-versions");
versions.replaceChildren(
document.createTextNode("Version "),
releasesLink("v" + updateFrame.latest),
document.createTextNode(" is out — you have "),
el("code", null, updateFrame.installed),
document.createTextNode(".")
);
const row = $("update-command");
const code = el("code", null, UPDATE_COMMAND);
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
$("update-modal").showModal();
}
function renderDashboard(main) {
maybeWake();
const menu = (S && S.menu) || {};
@@ -2526,6 +2584,25 @@ function renderDashboard(main) {
warn.setAttribute("role", "status");
wrap.appendChild(warn);
}
// Built here only, so no other workflow's page ever shows it.
if (updateFrame && !updateDismissed()) {
const notice = el("div", "dash-nudge update-banner");
notice.setAttribute("role", "status");
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + updateFrame.latest);
open.type = "button";
open.addEventListener("click", openUpdateModal);
const dismiss = el("button", "update-banner-dismiss", "×");
dismiss.type = "button";
dismiss.setAttribute("aria-label", "Dismiss until next time");
dismiss.addEventListener("click", () => {
try {
sessionStorage.setItem(updateDismissKey(), updateFrame.latest);
} catch {}
render();
});
notice.append(open, dismiss);
wrap.appendChild(notice);
}
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
if (typeof menu.note === "string" && menu.note.trim()) {
@@ -3223,7 +3300,11 @@ document.addEventListener("keydown", cancelSkipMove, true);
function skipAndMoveOn(id) {
cancelSkipMove();
local.skipFlash = id;
stage(id, { type: "skip", skipped: true });
// A note already typed goes along: skipping the question is not retracting
// the comment. Dropping it would leave the text in the box but out of the
// send, which looks kept and is not.
const cur = local.staged[id];
stage(id, { type: "skip", skipped: true, ...(cur && cur.text ? { text: cur.text } : {}) });
skipTimer = setTimeout(() => {
skipTimer = null;
local.skipFlash = null;
@@ -3340,19 +3421,24 @@ function renderWaiting(main) {
}
pane.appendChild(title);
pane.appendChild(el("p", null, doing));
const ask = "If Plan2Code needs you, the question appears here on its own.";
if (!docs().length) {
pane.appendChild(el("p", null, "If Plan2Code needs you, the question appears here on its own."));
pane.appendChild(el("p", null, ask));
return;
}
// "Task" and the tasks tab's own name both open that tab, so the pointer is
// one click from what it points at. A build posts it as `phase` ("Phase N
// tasks"), a quick task as `tasks`; with neither the words stay plain.
// tasks"), a quick task as `tasks`. A skill with no task list (Document,
// Plan) has nothing live to follow, so it gets no pointer at all.
const list =
docs().find((d) => d.id === "phase") ||
docs().find((d) => d.id === "tasks") ||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
if (!list) {
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
return;
}
const jump = (word) => {
if (!list) return el("strong", "waiting-jump", word);
const b = el("button", "waiting-jump", word);
b.type = "button";
b.addEventListener("click", () => {
@@ -3366,8 +3452,8 @@ function renderWaiting(main) {
"The tabs above fill in as it goes. You can follow along with live ",
jump("Task"),
" updates in the ",
jump((list && list.title) || "Phase tasks"),
" tab. If Plan2Code needs you, the question appears here on its own."
jump(list.title || "Phase tasks"),
" tab. " + ask
);
pane.appendChild(p);
}
@@ -3505,8 +3591,8 @@ function renderSettled(card, item) {
// would misreport which of the two was the answer.
let prose = text;
if (!prose && !lines.length) {
const mine = (item.thread || []).filter((m) => m.who === "user");
if (mine.length) prose = String(mine[mine.length - 1].text || "").trim();
const mine = (item.thread || []).filter((m) => threadWho(m) === "user");
if (mine.length) prose = threadText(mine[mine.length - 1]).trim();
}
const nothing = !lines.length && !prose;
@@ -4322,6 +4408,10 @@ function buildChecklist(card, item, staged) {
const commitList = (change) => {
const cur = local.staged[item.id];
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
// A tick or a state IS the answer, so it ends a skip staged earlier:
// left in place, `skipped` would collapse the reply to "skip" while the
// card showed ticked steps on their way.
delete next.skipped;
const empty = !(next.done && next.done.length) && !next.state && !next.text;
stage(item.id, empty ? null : next);
};
@@ -4371,7 +4461,7 @@ function buildChecklist(card, item, staged) {
function buildMenu(card, item, staged) {
const list = el("ul", "options");
const name = "menu-" + item.id;
for (const o of item.options || []) {
for (const [i, o] of (item.options || []).entries()) {
const picked = staged && staged.k === o.k;
const li = el("li", "option" + (picked ? " is-picked" : ""));
const label = el("label");
@@ -4379,7 +4469,13 @@ function buildMenu(card, item, staged) {
const radio = el("input");
radio.type = "radio";
radio.name = name;
// The same id buildChoice gives its radios: withFocus finds the focused
// input by id after the render this change() sets off, and without one a
// keyboard user arrowing through the menu lands on <body> every time.
radio.id = optionId(item, o, i);
radio.value = o.k;
radio.checked = Boolean(picked);
radio.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
const body = el("div", "option-body");
const head = el("div", "option-label");
@@ -5276,20 +5372,30 @@ function renderAside() {
)
);
}
// A note that has been sent but not yet picked up: marked as waiting, so the
// send is seen to have gone, until the agent replies. The server writes the
// note into the thread as it arrives; a session from before that has only
// `sentNote`, which gets a box of its own below.
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
let waitingShown = false;
for (const m of thread) {
const box = el("div", "msg " + (m.who === "user" ? "you" : ""));
const mine = threadWho(m) === "user";
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
if (pending) waitingShown = true;
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
const who = el("div", "msg-who");
who.appendChild(el("span", null, m.who === "user" ? "You" : "Plan2Code"));
if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
box.appendChild(who);
box.appendChild(md(m.text, "md"));
const text = threadText(m);
if (text) box.appendChild(md(text, "md"));
const tray = mine ? sentAttachments(m) : null;
if (tray) box.appendChild(tray);
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) {
if (waiting && !waitingShown) {
const box = el("div", "msg you pending");
const who = el("div", "msg-who");
who.appendChild(el("span", null, "You"));
@@ -5589,7 +5695,10 @@ async function attachFiles(itemId, files) {
const taken = wanted.slice(0, room);
// One banner at a time, so every refusal goes into it, each by name.
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
if (taken.length < wanted.length) said.push(chat ? "Up to 5 attachments per question." : "Up to 5 attachments per note.");
if (taken.length < wanted.length)
said.push(
chat ? `Up to ${CHAT_MAX_ATTACHMENTS} attachments per question.` : `Up to ${MAX_ATTACHMENTS} attachments per note.`
);
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
await Promise.all(
taken.map(async (file) => {
@@ -6439,6 +6548,10 @@ async function goHome() {
$("home-modal").close();
} catch (err) {
$("home-modal").close();
// The server is holding an uncollected result: Send, Home and Stop all
// need to read as busy until the frame or the ping says otherwise, same
// as send() and sendAfterBuild() do on a 409.
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
@@ -6499,6 +6612,7 @@ async function stopSession() {
stoppingHidden = false;
} catch (err) {
$("stop-modal").close();
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
@@ -6653,7 +6767,6 @@ function markSent({ sentIds, sentNotes = {}, summaries, values }) {
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
}
local.staged = {};
local.sentAt = Date.now();
save();
}
@@ -6706,7 +6819,7 @@ const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", d
// something the agent never hears.
function tokenFor(item, v) {
const map = item.token || {};
if (v.skipped) return "skip";
if (v.skipped) return v.text ? `skip; ${v.text}` : "skip";
const parts = [];
if (v.k) parts.push(map[v.k] || v.k);
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
@@ -6938,14 +7051,14 @@ function renderAbout() {
let helpBuilt = false;
async function renderHelpVersion() {
const el = $("help-version");
const slot = $("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;
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
slot.hidden = !version;
} catch {
el.hidden = true;
slot.hidden = true;
}
}
@@ -7053,6 +7166,7 @@ function openHelpOn(id) {
}
$("btn-home").addEventListener("click", openHomeConfirm);
$("update-done").addEventListener("click", () => $("update-modal").close());
$("home-cancel").addEventListener("click", () => $("home-modal").close());
$("home-go").addEventListener("click", goHome);
$("btn-stop").addEventListener("click", openStopConfirm);
@@ -7132,6 +7246,7 @@ $("btn-looks").addEventListener("click", () => {
});
$("looks-done").addEventListener("click", () => $("looks-modal").close());
$("looks-modal").addEventListener("close", () => {
resetCleanup();
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
});
$("looks-reset").addEventListener("click", () => {
@@ -7278,6 +7393,111 @@ $("models-reset").addEventListener("click", () => {
renderModels();
});
// Cleanup: the server works out what in ~/.plan2code is not needed and
// shows it first; Delete these sends back only the ids it was shown, and the
// server re-checks every one before removing it.
let cleanupFound = null;
// Bumped by every scan, delete and reset: a response from an older one is
// dropped, so a scan still in flight when Preferences closes cannot refill it.
let cleanupGen = 0;
const CLEANUP_SHOWN = 8;
function setCleanupStatus(text, isError) {
const status = $("cleanup-status");
status.textContent = text;
status.classList.toggle("error", Boolean(isError));
}
function cleanupLabel(item) {
if (item.where === "session") return "Session " + item.name;
const where = item.where === "root" ? "~/.plan2code/" : "~/.plan2code/console/";
return where + item.name + (item.kind === "folder" ? "/" : "");
}
function cleanupSummary(items, bytes) {
const sessions = items.filter((i) => i.where === "session").length;
const strays = items.length - sessions;
const parts = [];
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
return parts.join(", ") + " · " + formatBytes(bytes);
}
function resetCleanup() {
cleanupGen++;
cleanupFound = null;
$("cleanup-list").replaceChildren();
$("cleanup-delete").hidden = true;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
setCleanupStatus("", false);
}
function renderCleanup() {
const list = $("cleanup-list");
list.replaceChildren();
const items = (cleanupFound && cleanupFound.items) || [];
$("cleanup-delete").hidden = !items.length;
if (!items.length) return;
const rows = (some) => some.map((item) => {
const row = el("div", "cleanup-row");
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", formatBytes(item.bytes)));
return row;
});
list.append(el("p", "cleanup-summary", cleanupSummary(items, cleanupFound.bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
if (items.length > CLEANUP_SHOWN) {
const more = el("details", "cleanup-more");
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
list.appendChild(more);
}
}
async function scanCleanup() {
const gen = ++cleanupGen;
$("cleanup-scan").disabled = true;
$("cleanup-delete").disabled = true;
setCleanupStatus("Looking…", false);
const { status, body } = await postJson("/cleanup", { scan: true });
if (gen !== cleanupGen) return;
$("cleanup-scan").disabled = false;
$("cleanup-delete").disabled = false;
if (status !== 200 || !body.ok) {
cleanupFound = null;
renderCleanup();
return setCleanupStatus(status ? body.error || "Could not look." : "Plan2Code isn't reachable.", true);
}
cleanupFound = { items: body.items || [], bytes: body.bytes || 0 };
renderCleanup();
// Left in the status line, not cleared: it is the live region, so this is
// what a screen reader hears when the scan finishes.
const found = cleanupFound.items.length;
setCleanupStatus(found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.", false);
}
async function deleteCleanup() {
if (!cleanupFound || !cleanupFound.items.length) return;
const gen = ++cleanupGen;
$("cleanup-delete").disabled = true;
$("cleanup-scan").disabled = true;
setCleanupStatus("Deleting…", false);
const { status, body } = await postJson("/cleanup", { delete: cleanupFound.items.map((i) => i.id) });
if (gen !== cleanupGen) return;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
if (status !== 200 || !body.ok) {
return setCleanupStatus(status ? body.error || "Could not delete." : "Plan2Code isn't reachable.", true);
}
const removed = (body.removed || []).length;
const failed = (body.failed || []).length;
cleanupFound = null;
renderCleanup();
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
setCleanupStatus(failed ? done + " " + failed + " could not be removed." : done, Boolean(failed));
}
$("cleanup-scan").addEventListener("click", scanCleanup);
$("cleanup-delete").addEventListener("click", deleteCleanup);
$("btn-brief").addEventListener("click", openBrief);
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
$("brief-go").addEventListener("click", sendBrief);
@@ -1291,6 +1291,14 @@
come back, and you can change your role any time from the swatch
button.
</p>
<h4>When an update is out</h4>
<p>
When a newer Plan2Code release is out, the dashboard shows
<strong>UPDATE AVAILABLE</strong> at the top. Click it for the command
to run in your terminal; × hides it until the next
<code>/plan2code</code>. The version at the bottom of Help links to
the Releases page.
</p>
<h4>The cards</h4>
<p>They come in three groups.</p>
<p><strong>First, the project</strong></p>
@@ -1845,6 +1853,15 @@
joining the strip. Keep only the ones you want; ticking a box plays
its sound.
</li>
<li>
<strong>Cleanup</strong>: <strong>Find files to clean up</strong>
lists what Plan2Code doesn't need in your
<code>~/.plan2code</code> folder: sessions nobody has opened for
30 days, and files or folders that ended up there by mistake. It
shows each one with its size, and <strong>Delete these</strong>
removes exactly that list. Your preferences, saved folders, models,
the launcher and the session you are in always stay.
</li>
<li>
<strong>Back to default</strong> puts everything back as it was, and
sets Role back to Not set.
@@ -1983,6 +2000,16 @@
</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-cleanup">
<legend>Cleanup</legend>
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
<div class="models-actions">
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
<button type="button" class="btn small danger" id="cleanup-delete" hidden>Delete these</button>
<span class="help" id="cleanup-status" role="status"></span>
</div>
</fieldset>
<fieldset class="modal-ranges looks-models">
<legend>Models</legend>
<div class="models-tabs" role="group" aria-label="Which agent">
@@ -2181,6 +2208,24 @@
</div>
</dialog>
<!-- Opened from the dashboard's UPDATE AVAILABLE banner. The versions and
the copy row are filled by app.js; the update itself runs in a
terminal, never from this page. -->
<dialog class="modal" id="update-modal" aria-labelledby="update-title">
<h2 id="update-title">A new Plan2Code is available</h2>
<p class="modal-blurb" id="update-versions"></p>
<ol class="update-steps">
<li>
Run this in your terminal (not in this page or your agent):
<div class="update-command" id="update-command"></div>
</li>
<li>When it finishes, close this console and start <code>plan2code</code> again.</li>
</ol>
<div class="modal-actions">
<button type="button" class="btn primary" id="update-done">Close</button>
</div>
</dialog>
<footer class="footer">
<div class="footer-summary" id="footer-summary" aria-live="polite">
Nothing to send yet.
@@ -5,7 +5,10 @@
// popover; this file owns the rules. No DOM access at module scope and no
// imports: the page and `node --test` both import this file.
const NAME_CHAR = /[a-z0-9-]/;
// Uppercase too: "@Repo" must still name @repo — names are forced lowercase
// by the workspace rules, and a query typed with a capital otherwise matches
// nothing and opens no suggestions at all.
const NAME_CHAR = /[a-z0-9-]/i;
const MAX_MATCHES = 6;
/**
@@ -23,11 +26,13 @@ export function mentionAt(text, caret) {
}
// Names starting with the query first, then names containing it, in the
// order given, at most six.
// order given, at most six. Case-folded: folder names are lowercase by rule,
// and "@Repo" should still find @repo rather than claim nothing matches.
export function matchNames(names, query) {
const q = String(query || "");
const prefix = names.filter((n) => n.startsWith(q));
const inside = names.filter((n) => !n.startsWith(q) && n.includes(q));
const q = String(query || "").toLowerCase();
const fold = (n) => String(n).toLowerCase();
const prefix = names.filter((n) => fold(n).startsWith(q));
const inside = names.filter((n) => !fold(n).startsWith(q) && fold(n).includes(q));
return [...prefix, ...inside].slice(0, MAX_MATCHES);
}
@@ -25,12 +25,14 @@ import {
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
UPDATE_CHECK_FILE,
USER_MODELS_FILE,
WORKSPACE_FILE,
appendChat,
appendEvent,
chatForFrame,
checkDocument,
cleanupFindings,
currentConversation,
ensureDir,
fileStamp,
@@ -47,6 +49,7 @@ import {
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
removeCleanup,
remoteWarning,
specKey,
typedCount,
@@ -59,6 +62,7 @@ import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
import { meterView } from "./public/meter.js";
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
import { checkForUpdate } from "./update-check.mjs";
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
const args = parseArgs(process.argv.slice(2));
@@ -611,6 +615,7 @@ function stateFrame(state) {
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
workspace: workspaceView(),
meter: meterView(ledgerEntries()),
...(updateInfo ? { update: updateInfo } : {}),
have: haveKey(),
};
}
@@ -623,7 +628,7 @@ function haveKey() {
ledgerEntries();
return (
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}`
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}`
);
}
@@ -648,6 +653,12 @@ function recordSubmitted(state, actions) {
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) };
// The person's side of the Notes thread. Left to the agent it was never
// written, so a question asked in a note vanished once it was picked up
// and the reply under it answered nothing on the page.
if (item.sentNote.text.trim() || item.sentNote.images.length || item.sentNote.files.length) {
item.thread = [...(Array.isArray(item.thread) ? item.thread : []), { who: "user", ...item.sentNote }];
}
continue;
}
const { i, type, ...rest } = action;
@@ -933,6 +944,38 @@ function pushState() {
if (stateNow) broadcast("state", stateFrame(stateNow));
}
/* --------------------------------------------------------- update check */
// The version this console was installed as: install.js writes version.json
// beside console.mjs; a dev checkout falls back to the repo root's.
function installedVersion() {
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 version;
}
return null;
}
// Filled in once the boot-time check answers; until then, and whenever it
// fails, the frame carries no `update` and the page shows no banner.
let updateInfo = null;
let updateLatest = null;
// Started at boot and never awaited: git may take up to its 10 s limit, and
// nothing the person sees waits on it. The catch is not optional: a throw in
// pushState() would otherwise be an unhandled rejection, which ends the server.
function startUpdateCheck() {
const installed = installedVersion();
if (!installed) return;
checkForUpdate({ installed, cacheFile: UPDATE_CHECK_FILE })
.then((result) => {
updateLatest = result?.latest ?? null;
updateInfo = result?.updateAvailable ? { installed: result.installed, latest: result.latest } : null;
if (updateInfo) pushState();
})
.catch(() => {});
}
let agentSeenAt = Date.now();
function agentLastSeen() {
return new Date(agentSeenAt).toISOString();
@@ -1039,10 +1082,8 @@ const server = http.createServer((req, res) => {
}
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 });
}
const version = installedVersion();
if (version) return json(res, 200, { version, latest: updateLatest });
return json(res, 404, { error: "no version" });
}
@@ -1090,7 +1131,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/draft" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
// Debounced client-side; this is just the durable mirror. Twenty minutes
// of someone's structured answers must not die with a closed tab.
try {
@@ -1115,7 +1156,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/looks" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
// `set` carries only the keys one tab changed, merged onto what is on
// disk, so a tab holding stale settings cannot undo another tab's change.
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
@@ -1141,7 +1182,7 @@ const server = http.createServer((req, res) => {
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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
const { models, error } = cleanModels(body && body.models);
if (error) return json(res, 400, { error });
try {
@@ -1154,6 +1195,24 @@ const server = http.createServer((req, res) => {
});
}
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
// ~/.plan2code; `{ delete: [id] }` removes those of the ids a fresh scan
// still finds. Never this session, never a path the page sent.
if (pathname === "/cleanup" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
if (body && Array.isArray(body.delete)) {
return removeCleanup(body.delete, { skipSid: SID })
.then((done) => json(res, 200, { ok: true, ...done }))
.catch((e) => json(res, 500, { error: String(e.message) }));
}
return cleanupFindings({ skipSid: SID })
.then(({ items, bytes }) => json(res, 200, { ok: true, bytes, items: items.map(({ path: _p, ...item }) => item) }))
.catch((e) => json(res, 500, { error: String(e.message) }));
});
}
if (pathname === "/upload" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
const contentType = String(req.headers["content-type"] || "");
@@ -1260,7 +1319,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/submit" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
if (!body || !Array.isArray(body.actions) || body.actions.length === 0) {
return json(res, 400, { error: "actions must be a non-empty array" });
}
@@ -1361,6 +1420,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/chat" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const state = readState() || {};
const current = currentConversation(chatEntries()).conversation;
@@ -1424,6 +1484,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/chat/decision" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
if (body.decision !== "approve" && body.decision !== "decline") return json(res, 400, { error: "bad" });
if (body.text !== undefined && typeof body.text !== "string") return json(res, 400, { error: "bad" });
@@ -1472,6 +1533,7 @@ const server = http.createServer((req, res) => {
if (Object.hasOwn(workspaceRoutes, pathname) && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
let answer;
try {
@@ -1489,6 +1551,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/workspace/scope" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const spec = typeof body.spec === "string" ? body.spec : "";
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
@@ -1589,15 +1652,19 @@ function readBody(req, cb) {
let tooBig = false;
req.on("data", (c) => {
size += c.length;
// Drain past the cap rather than destroy, exactly like readRaw: a
// destroyed request emits 'close', never 'end' or 'error', so cb would
// never run and the page would see a reset instead of the 413 that names
// the problem.
if (size > MAX_BODY) {
tooBig = true;
req.destroy();
chunks.length = 0;
return;
}
chunks.push(c);
});
req.on("end", () => {
if (tooBig) return cb(new Error("too large"));
if (tooBig) return cb(Object.assign(new Error("too large"), { tooBig: true }));
try {
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
} catch (e) {
@@ -1834,6 +1901,9 @@ function onListening(port) {
bootWorkspace();
} catch {}
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
try {
startUpdateCheck();
} catch {}
try {
process.send?.({ type: "listening", port });
} catch {}
@@ -0,0 +1,138 @@
// Plan2Code Web Console - is a newer Plan2Code release out?
//
// `git ls-remote --tags` needs no API token and no rate-limited REST call,
// rides on the person's own git and proxy setup, and the newest `vX.Y.Z`
// release tag is "latest". The server
// starts this at boot and never waits on it; the answer, failures included, is
// cached for an hour so a burst of sessions asks GitHub once.
//
// Nothing here reads, stores or sends a credential: git authenticates itself,
// with every prompt turned off so a missing login fails fast instead of
// opening a window nobody asked for.
//
// Node built-ins only.
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
export const REPO_URL = "https://github.com/jparkerweb/plan2code.git";
export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
export const CACHE_MS = 60 * 60 * 1000;
const SEMVER = /^\d+\.\d+\.\d+$/;
const TAG_REF = /refs\/tags\/v(\d+\.\d+\.\d+)$/;
/** -1, 0 or 1 comparing two plain X.Y.Z versions numerically; null unless both are X.Y.Z. */
export function compareVersions(a, b) {
if (typeof a !== "string" || typeof b !== "string" || !SEMVER.test(a) || !SEMVER.test(b)) return null;
const x = a.split(".").map(Number);
const y = b.split(".").map(Number);
for (let i = 0; i < 3; i++) {
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
}
return 0;
}
/**
* The highest `vX.Y.Z` tag in `git ls-remote --tags` output, without the `v`.
* Peeled lines (`^{}`) never match, so an annotated tag counts once, and
* pre-releases or other tag names are ignored. Null when nothing matches.
*/
export function latestTag(text) {
if (typeof text !== "string") return null;
let best = null;
for (const line of text.split(/\r?\n/)) {
const m = TAG_REF.exec(line.trim());
if (m && (best === null || compareVersions(m[1], best) > 0)) best = m[1];
}
return best;
}
function readCache(cacheFile, now) {
try {
const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
if (!cached || typeof cached.checkedAt !== "number" || now - cached.checkedAt >= CACHE_MS) return undefined;
return typeof cached.latest === "string" ? cached.latest : null;
} catch {
return undefined;
}
}
function writeCache(cacheFile, data) {
const tmp = cacheFile + "." + process.pid + ".tmp";
try {
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
fs.renameSync(tmp, cacheFile);
} catch {
try {
fs.rmSync(tmp, { force: true });
} catch {}
}
}
/**
* `git ls-remote --tags` against the repo: resolves its stdout, or null when
* git is missing, fails, or is still going after `timeoutMs`. No shell, no
* window, no prompt.
*/
export function runLsRemote({ timeoutMs = 10000 } = {}) {
return new Promise((resolve) => {
let settled = false;
const done = (value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(value);
};
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
if (!process.env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
let child;
try {
child = spawn("git", ["ls-remote", "--tags", REPO_URL], {
shell: false,
windowsHide: true,
stdio: ["ignore", "pipe", "ignore"],
env,
});
} catch {
return resolve(null);
}
const timer = setTimeout(() => {
try {
child.kill();
} catch {}
done(null);
}, timeoutMs);
timer.unref?.();
let out = "";
child.stdout.setEncoding("utf8");
child.stdout.on("data", (chunk) => {
out += chunk;
});
child.on("error", () => done(null));
child.on("close", (code) => done(code === 0 ? out : null));
});
}
/**
* Whether `installed` is behind the newest release: `{ installed, latest,
* updateAvailable }`, or null when either version is unknown. Reuses a cache
* under an hour old, and caches a failed lookup as `latest: null` so it is
* not retried until the hour is up. Never throws.
*/
export async function checkForUpdate({ installed, cacheFile, now = Date.now(), run = runLsRemote }) {
try {
let latest = readCache(cacheFile, now);
if (latest === undefined) {
latest = latestTag(await run());
writeCache(cacheFile, { checkedAt: now, latest });
}
const order = compareVersions(installed, latest);
if (latest === null || order === null) return null;
return { installed, latest, updateAvailable: order < 0 };
} catch {
return null;
}
}
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -10,7 +10,7 @@
//
// and derives the ticket from a branch named <prefix>/<TICKET-ID>-description,
// where the ticket is an uppercase project key, a hyphen and an integer
// (PCWEB-10968). This script reads the branch, extracts the ticket and prints
// (ABC-10968). This script reads the branch, extracts the ticket and prints
// the exact command, so no prompt re-implements the rule by eye.
import { execFileSync } from "node:child_process";
@@ -96,7 +96,7 @@ run(USAGE, async (argv) => {
let branch = null;
let ticket = args.ticket ? args.ticket.trim() : null;
if (ticket && !/^[A-Z][A-Z0-9]*-\d+$/.test(ticket)) fail(EXIT.INVALID, "bad-ticket", `"${ticket}" is not an uppercase KEY-123 ticket ID.`, "Pass a ticket like PCWEB-10968.");
if (ticket && !/^[A-Z][A-Z0-9]*-\d+$/.test(ticket)) fail(EXIT.INVALID, "bad-ticket", `"${ticket}" is not an uppercase KEY-123 ticket ID.`, "Pass a ticket like ABC-10968.");
if (!ticket) {
branch = currentBranch();
ticket = ticketFromBranch(branch);
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -57,7 +57,7 @@ Run against EVERY finding. If any question raises doubt, re-investigate or drop.
**Finding survives (real bug):** Reviewer finds `processItems()` at line 47 accesses `items[0].id` with no empty-array check. Re-reads source — confirmed no guard. Traces callers — `orchestrator.js:82` can pass empty array. Adversarial check passes (correctness issue, additive fix). Presented at High.
**Finding dropped (pcweb-jira false positive):** Reviewer recommends removing `jira-api-catalog.md` from consumer loading to "reduce context." Adversarial check: "Does my fix remove something the system depends on?" YES — agents Read these files at runtime to construct valid API calls. Four of five checks fail. Dropped.
**Finding dropped (jira skill false positive):** Reviewer recommends removing `jira-api-catalog.md` from consumer loading to "reduce context." Adversarial check: "Does my fix remove something the system depends on?" YES — agents Read these files at runtime to construct valid API calls. Four of five checks fail. Dropped.
**Finding dropped (false consolidation):** Reviewer flags per-platform config files as "duplicates." Adversarial check: "Am I optimizing for the wrong metric?" YES — platforms have distinct values and will diverge further. Separation is a design choice. Dropped.
@@ -243,7 +243,7 @@ summarise it back.
Then, in ONE `post`, do all of:
- mark each answered item `"status": "answered"` and record its `answer`
- add your replies to any comment threads
- reply to every note in that item's `thread` (shape below)
- answer any Quick questions that came with it, in `chat.replies` (see Quick
questions)
- publish the next batch of questions
@@ -251,6 +251,26 @@ Then, in ONE `post`, do all of:
One post is one atomic update, so the page never shows a half-changed state.
### Replying to a note
A `comment` is the person talking to you about that card, often asking
something. It shows in the card's **Notes on this** panel, and so does your
answer:
```jsonc
{ "items": [{ "id": "p4", "thread": [
{ "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." }
] }] }
```
- Every entry is `{ "who": "agent", "text": "<markdown>" }`. `text`, not
`md`: the page reads nothing else. An entry with no `text` is rejected.
- The server writes their note into the thread as it arrives. Do not repeat
it, and send only your new entries: `thread` appends.
- Answer what they asked, in the thread, even when you also change a doc or
re-ask the question. "I've updated the doc" alone leaves the question in the
panel with no answer under it.
### Recording the answer
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
@@ -661,9 +681,17 @@ finish are dropped, so you start on a blank page and post your own. A skill
run inline from another (a quick task's review) keeps the page it was
handed. A
fresh `open` would strand the page the person is watching on the dashboard's
session while your questions went to a page nobody has open. Then run the
skill normally: its Interface question was already answered by being
launched, so start where its real work starts.
session while your questions went to a page nobody has open.
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
> own file-read tool and follow it from the top instead.** Every Plan2Code
> skill below the dashboard ships `disable-model-invocation: true` on
> purpose — it exists to be read and followed inline, not launched as a
> sub-skill — and calling one through a skill-invocation tool errors out and
> strands the hand-off mid-launch.
Its Interface step is already answered by having been launched, so start
where its real work starts.
The menu itself is the page's own list — you never send it. The page knows
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
@@ -829,6 +857,12 @@ know:
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
Post `activity` as each step starts, before its doc or question lands — reading
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
implementation — the same way Review does. A step with no card of its own
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
Finalize".
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
Stopping mid-finalize loses nothing
— the specs are untouched until Step 3's summary write — so a stop's finish
@@ -859,7 +893,7 @@ question or doc lands:
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
merge by `id` (an unknown id is added), and `thread` / `comments` append. Send only
merge by `id` (an unknown id is added), and `thread` appends. Send only
what changed. A whole-file rewrite would put the entire session back into your
context on every turn.
@@ -1239,7 +1273,7 @@ answers were submitted but never picked up.
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` and `comments` **append**: leave out any thread entry you already sent, or the person sees your reply twice. |
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
@@ -48,6 +48,10 @@ export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
// so every session within the hour reuses one lookup.
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
// test run (or a second sandboxed instance) shares one handle directory with
// the real thing, and `stop --all` reaches outside its own world and kills a
@@ -487,9 +491,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks, the folders remembered per project and spec, and the pointer to
// this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
// looks, the folders remembered per project and spec, the pointer to this
// console's directory, and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir", "update-check.json"]);
function isScratchName(name) {
return (
@@ -536,6 +540,148 @@ export async function removeScratch(consoleDir, names) {
return removed;
}
/* ------------------------------------------------------------- cleanup */
// What User Preferences -> Cleanup never removes. The console folder keeps its
// protected files, its sessions dir (old sessions go one by one, by age) and,
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
// console, the launcher (bin/, launcher.json) and the models the person added.
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
// A stray must sit untouched this long before Cleanup lists it. The same
// folders hold files that live for milliseconds -- a held
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
// rename -- and removing one mid-write loses another session's change.
export const STRAY_GRACE_MS = 60 * 60 * 1000;
// Bytes under `p`, never following a symlink: a link counts as itself.
async function diskBytes(p) {
let st;
try {
st = await fs.promises.lstat(p);
} catch {
return 0;
}
if (!st.isDirectory()) return st.size;
let entries;
try {
entries = await fs.promises.readdir(p);
} catch {
return 0;
}
let total = 0;
for (const name of entries) total += await diskBytes(path.join(p, name));
return total;
}
// The newest mtime of anything under `p`, never following a symlink. A folder
// counts by its files, since rewriting a file never touches its folder's
// mtime; an empty folder counts by its own. Anything unreadable on the way
// down answers Infinity, so it reads as just touched and stays.
function newestMtime(p) {
let st;
try {
st = fs.lstatSync(p);
} catch {
return Infinity;
}
if (!st.isDirectory()) return st.mtimeMs;
let entries;
try {
entries = fs.readdirSync(p);
} catch {
return Infinity;
}
if (!entries.length) return st.mtimeMs;
let newest = 0;
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
return newest;
}
function entryKind(entry) {
if (entry.isSymbolicLink()) return "link";
return entry.isDirectory() ? "folder" : "file";
}
function strayEntries(dir, kept, where, now) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return [];
}
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
return entries
.filter((e) => !kept.has(e.name))
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
.filter((e) => settled(e.path));
}
/**
* Everything Cleanup would remove, worked out on the server and never taken
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
* `open` sweeps by, plus every file in the folder that old, so a resumed
* session or a saved draft keeps it), anything at the top of the console folder that is
* not kept, and -- only when the console runs from its default home inside
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
* touched within `STRAY_GRACE_MS` are left for a later scan. A
* console running from another home (tests, dev) never reaches ~/.plan2code.
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
*/
export async function cleanupFindings({
consoleDir = HOME_DIR,
plan2codeDir = PLAN2CODE_DIR,
now = Date.now(),
maxAgeMs = SESSION_MAX_AGE_MS,
skipSid,
} = {}) {
const found = [];
const sessionsDir = path.join(consoleDir, "sessions");
for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) {
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
}
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
}
const items = [];
let bytes = 0;
for (const f of found) {
const size = await diskBytes(f.path);
bytes += size;
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
}
return { items, bytes };
}
/**
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
* worked out afresh first and only ids on it are touched, so a name from the
* page is never a path, and anything that stopped qualifying since the scan
* (a session touched again) stays. A link is unlinked, never followed.
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
*/
export async function removeCleanup(ids, opts = {}) {
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
const { items } = await cleanupFindings(opts);
const removed = [];
const failed = [];
let bytes = 0;
for (const item of items) {
if (!wanted.has(item.id)) continue;
try {
if (item.kind === "link") await fs.promises.unlink(item.path);
else await fs.promises.rm(item.path, { recursive: true, force: true });
removed.push(item.id);
bytes += item.bytes;
} catch {
failed.push(item.id);
}
}
return { removed, bytes, failed };
}
/**
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
* the file's realpath must sit inside the root's, so `../`, an absolute path
@@ -871,7 +1017,7 @@ export function handOff(child, pre) {
/* ----------------------------------------------------------- patch merge */
const APPEND_KEYS = new Set(["thread", "comments"]);
const APPEND_KEYS = new Set(["thread"]);
function isPlainObject(v) {
return v !== null && typeof v === "object" && !Array.isArray(v);
@@ -896,7 +1042,7 @@ function mergeOne(target, patch, where) {
}
// Merge a keyed collection: a known id merges one level, an unknown id appends.
// Named fields are replaced whole; thread/comments append.
// Named fields are replaced whole; thread appends.
function mergeKeyed(current, patchList, idKey, defaults, where) {
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
for (const entry of patchList) {
@@ -955,6 +1101,42 @@ function dropStaleSubmissions(currentItems, before, patchList) {
return merged;
}
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
// borrow the shape of the replies and doc blocks they also write, so `from` /
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
// at all is refused. The person's own notes are recorded by the server when
// they send, so an agent that echoes one back is not shown it twice.
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
function normalizeThreads(patchList, currentItems) {
return patchList.map((entry) => {
if (!isPlainObject(entry) || entry.thread == null) return entry;
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
const said = new Set(
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
);
const thread = [];
for (const m of entry.thread) {
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
guard(m, "thread");
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
if (!key) {
throw new Error(
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
);
}
const { from, role, md, body, content, ...rest } = m;
const who = (m.who || from || role) === "user" ? "user" : "agent";
const text = m[key];
if (who === "user" && said.has(text.trim())) continue;
thread.push({ ...rest, who, text });
}
return { ...entry, thread };
});
}
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
@@ -996,7 +1178,7 @@ export function applyPatch(state, patch) {
break;
case "items":
if (!Array.isArray(v)) throw new Error('"items" must be an array');
next.items = dropStaleSubmissions(next.items, state.items, v);
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
break;
case "topics":
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
@@ -1048,15 +1230,11 @@ function stampTimes(before, next) {
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
}
for (const list of [next.items, next.docs]) {
if (!Array.isArray(list)) continue;
for (const entry of list) {
if (Array.isArray(next.items)) {
for (const entry of next.items) {
if (Array.isArray(entry.thread)) {
for (const m of entry.thread) if (!m.at) m.at = now;
}
if (Array.isArray(entry.comments)) {
for (const m of entry.comments) if (!m.at) m.at = now;
}
}
}
if (Array.isArray(next.docs)) {
@@ -1289,7 +1467,10 @@ 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, sentNote, ...rest }) => rest);
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
...rest,
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
}));
const prose =
JSON.stringify(authored) +
JSON.stringify(state.docs || []) +
@@ -65,7 +65,7 @@ export function submittedAwaiting(item) {
if (!s || typeof s !== "object") return null;
if (item.answer && typeof item.answer === "object") return null;
const thread = Array.isArray(item.thread) ? item.thread : [];
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
return replied ? null : s;
}
@@ -74,17 +74,33 @@ export function submittedAwaiting(item) {
* 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.
* Any agent message from the send onwards, or one with no clock to compare,
* means it has been picked up. The person's own entries never count: the
* server writes their note into the thread as it arrives.
*/
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));
const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at));
return picked ? null : n;
}
/**
* Who said a thread entry and what they said. The contract is `{ who, text }`
* and the server lifts anything else into it, but sessions written before that
* hold `{ from, md }` replies, which would otherwise draw as empty bubbles.
*/
export function threadWho(m) {
return m && (m.who || m.from || m.role) === "user" ? "user" : "agent";
}
export function threadText(m) {
if (!m) return "";
for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k];
return "";
}
/* -------------------------------------------------------------- labels */
export function optionLabel(item, k) {
@@ -23,6 +23,9 @@
--warn-soft: #fbe7e3;
--focus: #1f6feb;
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
/* A soft accent halo for the things that want noticing: the update banner
and an enabled Send. Built from --accent, so a picked accent glows too. */
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
@@ -61,6 +64,7 @@
--warn-soft: #34201d;
--focus: #6aa3ff;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
}
}
@@ -85,6 +89,7 @@
--warn-soft: #34201d;
--focus: #6aa3ff;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
}
* { box-sizing: border-box; }
@@ -1097,10 +1102,11 @@ h1 {
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
the tiny ring, left of the label. */
.view-tab .tab-spin {
the tiny ring, left of the label. The extra .spinner is for specificity:
.spinner.tiny comes later and zeroes the margin otherwise. */
.view-tab .spinner.tab-spin {
display: inline-block;
margin-right: 6px;
margin-right: 7px;
vertical-align: -1px;
}
@@ -1657,11 +1663,13 @@ input[type="text"].invalid { border-color: var(--warn); }
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
/* Send breathes while there is something to send: a soft accent ring that
spreads and fades. Off under reduced motion, below. */
/* Send glows and breathes while there is something to send: the steady
--glow, plus a soft accent ring that spreads and fades. The ring is off
under reduced motion, below; the glow stays. */
#btn-send:not(:disabled) { box-shadow: var(--glow); }
@keyframes send-pulse {
0% { box-shadow: 0 0 0 0 var(--accent-line); }
100% { box-shadow: 0 0 0 6px transparent; }
0% { box-shadow: var(--glow), 0 0 0 0 var(--accent-line); }
100% { box-shadow: var(--glow), 0 0 0 6px transparent; }
}
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
@@ -2219,6 +2227,7 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
.modal.help[open] { display: flex; }
.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-version a { color: inherit; }
.help-layout {
display: grid;
@@ -2668,6 +2677,74 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
border-left-width: 4px;
color: var(--ink);
}
/* A newer release: the same slot, in the accent, with the label as the way
into the update modal and a small × that hides it for this session. */
.dash-nudge.update-banner {
position: relative;
padding-left: 40px;
padding-right: 40px;
border-left-width: 4px;
border-left-color: var(--accent-line);
color: var(--ink);
box-shadow: var(--glow);
}
.update-banner-open {
flex: 1 1 16em;
padding: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
font-weight: 600;
letter-spacing: 0.02em;
text-align: center;
cursor: pointer;
}
.update-banner-open:hover { text-decoration: underline; }
/* Pinned to the right edge, out of the flow, so the label centres on the
whole banner rather than on what the × leaves of it. */
.update-banner-dismiss {
position: absolute;
top: 50%;
right: 10px;
transform: translateY(-50%);
padding: 0 6px;
border: 0;
border-radius: var(--radius);
background: none;
color: inherit;
font: inherit;
font-size: 16px;
line-height: 1;
cursor: pointer;
}
.update-banner-dismiss:hover { background: var(--accent-line); }
/* Wide enough that the update command sits on one line beside Copy; a
narrow window still wraps it rather than overflowing. */
#update-modal { max-width: 720px; }
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
.update-steps li { margin: 4px 0; }
/* The hand-off copy row, in the modal's first step: the command and its Copy
side by side. */
.update-command {
margin: 6px 0 4px;
display: flex;
align-items: stretch;
gap: 10px;
flex-wrap: wrap;
}
.update-command code {
flex: 1 1 260px;
min-width: 0;
font: 13px/1.5 var(--mono);
color: var(--ink);
background: var(--panel);
border: 1px solid var(--rule-2);
border-radius: 8px;
padding: 10px 12px;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
.dash-working {
@@ -3394,6 +3471,18 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.models-actions .help.error { color: var(--danger, #d64545); }
/* User Preferences: Cleanup's list of what would go, shown before anything
is deleted. */
.cleanup-list { display: grid; gap: 4px; max-height: 200px; overflow: auto; font-size: 0.88em; }
.cleanup-list:empty { display: none; }
.cleanup-summary { margin: 0 0 2px; font-weight: 600; }
.cleanup-row { display: flex; justify-content: space-between; gap: 12px; }
.cleanup-row span:first-child { min-width: 0; overflow-wrap: anywhere; font-family: var(--mono); }
.cleanup-size { flex: none; color: var(--ink-3); }
.cleanup-more { display: grid; gap: 4px; }
.cleanup-more summary { cursor: pointer; color: var(--ink-2); }
#cleanup-delete[hidden] { display: none; }
/* 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 {
@@ -66,6 +66,8 @@ import {
submittedAwaiting,
noteAwaiting,
suggestionFrom,
threadText,
threadWho,
THUMB_EDGE,
turnGate,
verdictText,
@@ -446,6 +448,10 @@ document.addEventListener("click", (e) => {
const GONE_AFTER_MS = 8000;
// Named so a reconnect can clear only THIS banner: a bare banner(null) would
// wipe an unrelated warning that landed while the page was gone (an upload
// failure, a refused send).
const GONE_BANNER = "Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.";
const WORKING_GRACE_MS = 5 * 60 * 1000;
// Two minutes with the agent mid-turn, three when it is merely meant to be
// listening. The difference is the cost of being wrong: a working agent that
@@ -521,6 +527,9 @@ let chatFrame = null;
// sends them.
let wsFrame = null;
let meterFrame = null;
// The frame's update ({ installed, latest }), present only when a newer
// release is out; null otherwise.
let updateFrame = null;
let chatDot = false;
let chatSending = false;
let chatResetting = false;
@@ -566,7 +575,6 @@ function fresh() {
drafts: {},
images: {},
sent: {},
sentAt: null,
stopping: null,
afterBuild: null,
homeward: null,
@@ -870,10 +878,12 @@ function adopt(body) {
chatFrame = body.chat || null;
if (body.workspace) wsFrame = body.workspace;
if (body.meter) meterFrame = body.meter;
// Always replaced: an absent key means no update.
updateFrame = body.update || null;
lastContact = Date.now();
if (gone) {
gone = false;
banner(null);
if ($("banner").textContent === GONE_BANNER) banner(null);
}
if (firstLoad) {
load();
@@ -1016,7 +1026,9 @@ function adopt(body) {
render();
if ($("workspace-modal").open) renderWorkspace();
tellFolderIssues();
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow) loadOverview();
// The Overview tab's file changes under a build, so a tab you are watching
// refetches on every new frame too, not only on the click that opened it.
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow || view === "overview") loadOverview();
if (announce) showArrival(announce);
// New entries land at the bottom of the rail. Gliding down to them beats
// leaving the list parked where it was while it grew underneath.
@@ -1149,15 +1161,12 @@ function markGone() {
// of the server means there, and a banner promising a reconnect would
// argue with it.
if (!finish() && !stopInProgress()) {
banner(
"Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.",
"warn"
);
banner(GONE_BANNER, "warn");
}
render();
} else if (!bad && gone) {
gone = false;
banner(null);
if ($("banner").textContent === GONE_BANNER) banner(null);
render();
}
}
@@ -1182,7 +1191,6 @@ function connect() {
} catch {}
});
es.addEventListener("submitted", (e) => {
local.sentAt = Date.now();
// Drop only what was actually sent.
//
// This event fires for a send from ANY tab of this session, which is why it
@@ -1799,14 +1807,19 @@ async function sendBrief() {
reply: briefPhrase(choice.range),
}),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
$("brief-modal").close();
banner("Asked for a brief. It will appear as a tab when it is written.", "good");
setTimeout(() => banner(null), 5000);
pendingResult = true;
render();
} catch {
why.textContent = "That did not go through. Try again in a moment.";
} catch (err) {
if (err && err.pending) pendingResult = true;
why.textContent =
err && err.pending
? "Your last answers are still being picked up. Try again in a moment."
: "That did not go through. Try again in a moment.";
} finally {
go.disabled = false;
go.textContent = "Write the brief";
@@ -2515,6 +2528,51 @@ function roleNudge() {
return nudge;
}
// × on the update banner hides it for this console session only, and only
// for the release it named. Blocked storage means "not dismissed".
function updateDismissKey() {
try {
return "p2c-update-dismissed:" + S.sid;
} catch {
return "p2c-update-dismissed:";
}
}
function updateDismissed() {
try {
return sessionStorage.getItem(updateDismissKey()) === updateFrame.latest;
} catch {
return false;
}
}
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
const UPDATE_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
function releasesLink(text) {
const a = el("a", null, text);
a.href = RELEASES_URL;
a.target = "_blank";
a.rel = "noopener noreferrer";
return a;
}
function openUpdateModal() {
if (!updateFrame) return;
const versions = $("update-versions");
versions.replaceChildren(
document.createTextNode("Version "),
releasesLink("v" + updateFrame.latest),
document.createTextNode(" is out — you have "),
el("code", null, updateFrame.installed),
document.createTextNode(".")
);
const row = $("update-command");
const code = el("code", null, UPDATE_COMMAND);
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
$("update-modal").showModal();
}
function renderDashboard(main) {
maybeWake();
const menu = (S && S.menu) || {};
@@ -2526,6 +2584,25 @@ function renderDashboard(main) {
warn.setAttribute("role", "status");
wrap.appendChild(warn);
}
// Built here only, so no other workflow's page ever shows it.
if (updateFrame && !updateDismissed()) {
const notice = el("div", "dash-nudge update-banner");
notice.setAttribute("role", "status");
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + updateFrame.latest);
open.type = "button";
open.addEventListener("click", openUpdateModal);
const dismiss = el("button", "update-banner-dismiss", "×");
dismiss.type = "button";
dismiss.setAttribute("aria-label", "Dismiss until next time");
dismiss.addEventListener("click", () => {
try {
sessionStorage.setItem(updateDismissKey(), updateFrame.latest);
} catch {}
render();
});
notice.append(open, dismiss);
wrap.appendChild(notice);
}
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
if (typeof menu.note === "string" && menu.note.trim()) {
@@ -3223,7 +3300,11 @@ document.addEventListener("keydown", cancelSkipMove, true);
function skipAndMoveOn(id) {
cancelSkipMove();
local.skipFlash = id;
stage(id, { type: "skip", skipped: true });
// A note already typed goes along: skipping the question is not retracting
// the comment. Dropping it would leave the text in the box but out of the
// send, which looks kept and is not.
const cur = local.staged[id];
stage(id, { type: "skip", skipped: true, ...(cur && cur.text ? { text: cur.text } : {}) });
skipTimer = setTimeout(() => {
skipTimer = null;
local.skipFlash = null;
@@ -3340,19 +3421,24 @@ function renderWaiting(main) {
}
pane.appendChild(title);
pane.appendChild(el("p", null, doing));
const ask = "If Plan2Code needs you, the question appears here on its own.";
if (!docs().length) {
pane.appendChild(el("p", null, "If Plan2Code needs you, the question appears here on its own."));
pane.appendChild(el("p", null, ask));
return;
}
// "Task" and the tasks tab's own name both open that tab, so the pointer is
// one click from what it points at. A build posts it as `phase` ("Phase N
// tasks"), a quick task as `tasks`; with neither the words stay plain.
// tasks"), a quick task as `tasks`. A skill with no task list (Document,
// Plan) has nothing live to follow, so it gets no pointer at all.
const list =
docs().find((d) => d.id === "phase") ||
docs().find((d) => d.id === "tasks") ||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
if (!list) {
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
return;
}
const jump = (word) => {
if (!list) return el("strong", "waiting-jump", word);
const b = el("button", "waiting-jump", word);
b.type = "button";
b.addEventListener("click", () => {
@@ -3366,8 +3452,8 @@ function renderWaiting(main) {
"The tabs above fill in as it goes. You can follow along with live ",
jump("Task"),
" updates in the ",
jump((list && list.title) || "Phase tasks"),
" tab. If Plan2Code needs you, the question appears here on its own."
jump(list.title || "Phase tasks"),
" tab. " + ask
);
pane.appendChild(p);
}
@@ -3505,8 +3591,8 @@ function renderSettled(card, item) {
// would misreport which of the two was the answer.
let prose = text;
if (!prose && !lines.length) {
const mine = (item.thread || []).filter((m) => m.who === "user");
if (mine.length) prose = String(mine[mine.length - 1].text || "").trim();
const mine = (item.thread || []).filter((m) => threadWho(m) === "user");
if (mine.length) prose = threadText(mine[mine.length - 1]).trim();
}
const nothing = !lines.length && !prose;
@@ -4322,6 +4408,10 @@ function buildChecklist(card, item, staged) {
const commitList = (change) => {
const cur = local.staged[item.id];
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
// A tick or a state IS the answer, so it ends a skip staged earlier:
// left in place, `skipped` would collapse the reply to "skip" while the
// card showed ticked steps on their way.
delete next.skipped;
const empty = !(next.done && next.done.length) && !next.state && !next.text;
stage(item.id, empty ? null : next);
};
@@ -4371,7 +4461,7 @@ function buildChecklist(card, item, staged) {
function buildMenu(card, item, staged) {
const list = el("ul", "options");
const name = "menu-" + item.id;
for (const o of item.options || []) {
for (const [i, o] of (item.options || []).entries()) {
const picked = staged && staged.k === o.k;
const li = el("li", "option" + (picked ? " is-picked" : ""));
const label = el("label");
@@ -4379,7 +4469,13 @@ function buildMenu(card, item, staged) {
const radio = el("input");
radio.type = "radio";
radio.name = name;
// The same id buildChoice gives its radios: withFocus finds the focused
// input by id after the render this change() sets off, and without one a
// keyboard user arrowing through the menu lands on <body> every time.
radio.id = optionId(item, o, i);
radio.value = o.k;
radio.checked = Boolean(picked);
radio.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
const body = el("div", "option-body");
const head = el("div", "option-label");
@@ -5276,20 +5372,30 @@ function renderAside() {
)
);
}
// A note that has been sent but not yet picked up: marked as waiting, so the
// send is seen to have gone, until the agent replies. The server writes the
// note into the thread as it arrives; a session from before that has only
// `sentNote`, which gets a box of its own below.
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
let waitingShown = false;
for (const m of thread) {
const box = el("div", "msg " + (m.who === "user" ? "you" : ""));
const mine = threadWho(m) === "user";
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
if (pending) waitingShown = true;
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
const who = el("div", "msg-who");
who.appendChild(el("span", null, m.who === "user" ? "You" : "Plan2Code"));
if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
box.appendChild(who);
box.appendChild(md(m.text, "md"));
const text = threadText(m);
if (text) box.appendChild(md(text, "md"));
const tray = mine ? sentAttachments(m) : null;
if (tray) box.appendChild(tray);
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) {
if (waiting && !waitingShown) {
const box = el("div", "msg you pending");
const who = el("div", "msg-who");
who.appendChild(el("span", null, "You"));
@@ -5589,7 +5695,10 @@ async function attachFiles(itemId, files) {
const taken = wanted.slice(0, room);
// One banner at a time, so every refusal goes into it, each by name.
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
if (taken.length < wanted.length) said.push(chat ? "Up to 5 attachments per question." : "Up to 5 attachments per note.");
if (taken.length < wanted.length)
said.push(
chat ? `Up to ${CHAT_MAX_ATTACHMENTS} attachments per question.` : `Up to ${MAX_ATTACHMENTS} attachments per note.`
);
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
await Promise.all(
taken.map(async (file) => {
@@ -6439,6 +6548,10 @@ async function goHome() {
$("home-modal").close();
} catch (err) {
$("home-modal").close();
// The server is holding an uncollected result: Send, Home and Stop all
// need to read as busy until the frame or the ping says otherwise, same
// as send() and sendAfterBuild() do on a 409.
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
@@ -6499,6 +6612,7 @@ async function stopSession() {
stoppingHidden = false;
} catch (err) {
$("stop-modal").close();
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
@@ -6653,7 +6767,6 @@ function markSent({ sentIds, sentNotes = {}, summaries, values }) {
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
}
local.staged = {};
local.sentAt = Date.now();
save();
}
@@ -6706,7 +6819,7 @@ const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", d
// something the agent never hears.
function tokenFor(item, v) {
const map = item.token || {};
if (v.skipped) return "skip";
if (v.skipped) return v.text ? `skip; ${v.text}` : "skip";
const parts = [];
if (v.k) parts.push(map[v.k] || v.k);
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
@@ -6938,14 +7051,14 @@ function renderAbout() {
let helpBuilt = false;
async function renderHelpVersion() {
const el = $("help-version");
const slot = $("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;
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
slot.hidden = !version;
} catch {
el.hidden = true;
slot.hidden = true;
}
}
@@ -7053,6 +7166,7 @@ function openHelpOn(id) {
}
$("btn-home").addEventListener("click", openHomeConfirm);
$("update-done").addEventListener("click", () => $("update-modal").close());
$("home-cancel").addEventListener("click", () => $("home-modal").close());
$("home-go").addEventListener("click", goHome);
$("btn-stop").addEventListener("click", openStopConfirm);
@@ -7132,6 +7246,7 @@ $("btn-looks").addEventListener("click", () => {
});
$("looks-done").addEventListener("click", () => $("looks-modal").close());
$("looks-modal").addEventListener("close", () => {
resetCleanup();
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
});
$("looks-reset").addEventListener("click", () => {
@@ -7278,6 +7393,111 @@ $("models-reset").addEventListener("click", () => {
renderModels();
});
// Cleanup: the server works out what in ~/.plan2code is not needed and
// shows it first; Delete these sends back only the ids it was shown, and the
// server re-checks every one before removing it.
let cleanupFound = null;
// Bumped by every scan, delete and reset: a response from an older one is
// dropped, so a scan still in flight when Preferences closes cannot refill it.
let cleanupGen = 0;
const CLEANUP_SHOWN = 8;
function setCleanupStatus(text, isError) {
const status = $("cleanup-status");
status.textContent = text;
status.classList.toggle("error", Boolean(isError));
}
function cleanupLabel(item) {
if (item.where === "session") return "Session " + item.name;
const where = item.where === "root" ? "~/.plan2code/" : "~/.plan2code/console/";
return where + item.name + (item.kind === "folder" ? "/" : "");
}
function cleanupSummary(items, bytes) {
const sessions = items.filter((i) => i.where === "session").length;
const strays = items.length - sessions;
const parts = [];
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
return parts.join(", ") + " · " + formatBytes(bytes);
}
function resetCleanup() {
cleanupGen++;
cleanupFound = null;
$("cleanup-list").replaceChildren();
$("cleanup-delete").hidden = true;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
setCleanupStatus("", false);
}
function renderCleanup() {
const list = $("cleanup-list");
list.replaceChildren();
const items = (cleanupFound && cleanupFound.items) || [];
$("cleanup-delete").hidden = !items.length;
if (!items.length) return;
const rows = (some) => some.map((item) => {
const row = el("div", "cleanup-row");
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", formatBytes(item.bytes)));
return row;
});
list.append(el("p", "cleanup-summary", cleanupSummary(items, cleanupFound.bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
if (items.length > CLEANUP_SHOWN) {
const more = el("details", "cleanup-more");
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
list.appendChild(more);
}
}
async function scanCleanup() {
const gen = ++cleanupGen;
$("cleanup-scan").disabled = true;
$("cleanup-delete").disabled = true;
setCleanupStatus("Looking…", false);
const { status, body } = await postJson("/cleanup", { scan: true });
if (gen !== cleanupGen) return;
$("cleanup-scan").disabled = false;
$("cleanup-delete").disabled = false;
if (status !== 200 || !body.ok) {
cleanupFound = null;
renderCleanup();
return setCleanupStatus(status ? body.error || "Could not look." : "Plan2Code isn't reachable.", true);
}
cleanupFound = { items: body.items || [], bytes: body.bytes || 0 };
renderCleanup();
// Left in the status line, not cleared: it is the live region, so this is
// what a screen reader hears when the scan finishes.
const found = cleanupFound.items.length;
setCleanupStatus(found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.", false);
}
async function deleteCleanup() {
if (!cleanupFound || !cleanupFound.items.length) return;
const gen = ++cleanupGen;
$("cleanup-delete").disabled = true;
$("cleanup-scan").disabled = true;
setCleanupStatus("Deleting…", false);
const { status, body } = await postJson("/cleanup", { delete: cleanupFound.items.map((i) => i.id) });
if (gen !== cleanupGen) return;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
if (status !== 200 || !body.ok) {
return setCleanupStatus(status ? body.error || "Could not delete." : "Plan2Code isn't reachable.", true);
}
const removed = (body.removed || []).length;
const failed = (body.failed || []).length;
cleanupFound = null;
renderCleanup();
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
setCleanupStatus(failed ? done + " " + failed + " could not be removed." : done, Boolean(failed));
}
$("cleanup-scan").addEventListener("click", scanCleanup);
$("cleanup-delete").addEventListener("click", deleteCleanup);
$("btn-brief").addEventListener("click", openBrief);
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
$("brief-go").addEventListener("click", sendBrief);
@@ -1291,6 +1291,14 @@
come back, and you can change your role any time from the swatch
button.
</p>
<h4>When an update is out</h4>
<p>
When a newer Plan2Code release is out, the dashboard shows
<strong>UPDATE AVAILABLE</strong> at the top. Click it for the command
to run in your terminal; × hides it until the next
<code>/plan2code</code>. The version at the bottom of Help links to
the Releases page.
</p>
<h4>The cards</h4>
<p>They come in three groups.</p>
<p><strong>First, the project</strong></p>
@@ -1845,6 +1853,15 @@
joining the strip. Keep only the ones you want; ticking a box plays
its sound.
</li>
<li>
<strong>Cleanup</strong>: <strong>Find files to clean up</strong>
lists what Plan2Code doesn't need in your
<code>~/.plan2code</code> folder: sessions nobody has opened for
30 days, and files or folders that ended up there by mistake. It
shows each one with its size, and <strong>Delete these</strong>
removes exactly that list. Your preferences, saved folders, models,
the launcher and the session you are in always stay.
</li>
<li>
<strong>Back to default</strong> puts everything back as it was, and
sets Role back to Not set.
@@ -1983,6 +2000,16 @@
</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-cleanup">
<legend>Cleanup</legend>
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
<div class="models-actions">
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
<button type="button" class="btn small danger" id="cleanup-delete" hidden>Delete these</button>
<span class="help" id="cleanup-status" role="status"></span>
</div>
</fieldset>
<fieldset class="modal-ranges looks-models">
<legend>Models</legend>
<div class="models-tabs" role="group" aria-label="Which agent">
@@ -2181,6 +2208,24 @@
</div>
</dialog>
<!-- Opened from the dashboard's UPDATE AVAILABLE banner. The versions and
the copy row are filled by app.js; the update itself runs in a
terminal, never from this page. -->
<dialog class="modal" id="update-modal" aria-labelledby="update-title">
<h2 id="update-title">A new Plan2Code is available</h2>
<p class="modal-blurb" id="update-versions"></p>
<ol class="update-steps">
<li>
Run this in your terminal (not in this page or your agent):
<div class="update-command" id="update-command"></div>
</li>
<li>When it finishes, close this console and start <code>plan2code</code> again.</li>
</ol>
<div class="modal-actions">
<button type="button" class="btn primary" id="update-done">Close</button>
</div>
</dialog>
<footer class="footer">
<div class="footer-summary" id="footer-summary" aria-live="polite">
Nothing to send yet.
@@ -5,7 +5,10 @@
// popover; this file owns the rules. No DOM access at module scope and no
// imports: the page and `node --test` both import this file.
const NAME_CHAR = /[a-z0-9-]/;
// Uppercase too: "@Repo" must still name @repo — names are forced lowercase
// by the workspace rules, and a query typed with a capital otherwise matches
// nothing and opens no suggestions at all.
const NAME_CHAR = /[a-z0-9-]/i;
const MAX_MATCHES = 6;
/**
@@ -23,11 +26,13 @@ export function mentionAt(text, caret) {
}
// Names starting with the query first, then names containing it, in the
// order given, at most six.
// order given, at most six. Case-folded: folder names are lowercase by rule,
// and "@Repo" should still find @repo rather than claim nothing matches.
export function matchNames(names, query) {
const q = String(query || "");
const prefix = names.filter((n) => n.startsWith(q));
const inside = names.filter((n) => !n.startsWith(q) && n.includes(q));
const q = String(query || "").toLowerCase();
const fold = (n) => String(n).toLowerCase();
const prefix = names.filter((n) => fold(n).startsWith(q));
const inside = names.filter((n) => !fold(n).startsWith(q) && fold(n).includes(q));
return [...prefix, ...inside].slice(0, MAX_MATCHES);
}
@@ -25,12 +25,14 @@ import {
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
UPDATE_CHECK_FILE,
USER_MODELS_FILE,
WORKSPACE_FILE,
appendChat,
appendEvent,
chatForFrame,
checkDocument,
cleanupFindings,
currentConversation,
ensureDir,
fileStamp,
@@ -47,6 +49,7 @@ import {
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
removeCleanup,
remoteWarning,
specKey,
typedCount,
@@ -59,6 +62,7 @@ import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
import { meterView } from "./public/meter.js";
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
import { checkForUpdate } from "./update-check.mjs";
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
const args = parseArgs(process.argv.slice(2));
@@ -611,6 +615,7 @@ function stateFrame(state) {
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
workspace: workspaceView(),
meter: meterView(ledgerEntries()),
...(updateInfo ? { update: updateInfo } : {}),
have: haveKey(),
};
}
@@ -623,7 +628,7 @@ function haveKey() {
ledgerEntries();
return (
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}`
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}`
);
}
@@ -648,6 +653,12 @@ function recordSubmitted(state, actions) {
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) };
// The person's side of the Notes thread. Left to the agent it was never
// written, so a question asked in a note vanished once it was picked up
// and the reply under it answered nothing on the page.
if (item.sentNote.text.trim() || item.sentNote.images.length || item.sentNote.files.length) {
item.thread = [...(Array.isArray(item.thread) ? item.thread : []), { who: "user", ...item.sentNote }];
}
continue;
}
const { i, type, ...rest } = action;
@@ -933,6 +944,38 @@ function pushState() {
if (stateNow) broadcast("state", stateFrame(stateNow));
}
/* --------------------------------------------------------- update check */
// The version this console was installed as: install.js writes version.json
// beside console.mjs; a dev checkout falls back to the repo root's.
function installedVersion() {
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 version;
}
return null;
}
// Filled in once the boot-time check answers; until then, and whenever it
// fails, the frame carries no `update` and the page shows no banner.
let updateInfo = null;
let updateLatest = null;
// Started at boot and never awaited: git may take up to its 10 s limit, and
// nothing the person sees waits on it. The catch is not optional: a throw in
// pushState() would otherwise be an unhandled rejection, which ends the server.
function startUpdateCheck() {
const installed = installedVersion();
if (!installed) return;
checkForUpdate({ installed, cacheFile: UPDATE_CHECK_FILE })
.then((result) => {
updateLatest = result?.latest ?? null;
updateInfo = result?.updateAvailable ? { installed: result.installed, latest: result.latest } : null;
if (updateInfo) pushState();
})
.catch(() => {});
}
let agentSeenAt = Date.now();
function agentLastSeen() {
return new Date(agentSeenAt).toISOString();
@@ -1039,10 +1082,8 @@ const server = http.createServer((req, res) => {
}
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 });
}
const version = installedVersion();
if (version) return json(res, 200, { version, latest: updateLatest });
return json(res, 404, { error: "no version" });
}
@@ -1090,7 +1131,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/draft" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
// Debounced client-side; this is just the durable mirror. Twenty minutes
// of someone's structured answers must not die with a closed tab.
try {
@@ -1115,7 +1156,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/looks" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
// `set` carries only the keys one tab changed, merged onto what is on
// disk, so a tab holding stale settings cannot undo another tab's change.
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
@@ -1141,7 +1182,7 @@ const server = http.createServer((req, res) => {
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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
const { models, error } = cleanModels(body && body.models);
if (error) return json(res, 400, { error });
try {
@@ -1154,6 +1195,24 @@ const server = http.createServer((req, res) => {
});
}
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
// ~/.plan2code; `{ delete: [id] }` removes those of the ids a fresh scan
// still finds. Never this session, never a path the page sent.
if (pathname === "/cleanup" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
if (body && Array.isArray(body.delete)) {
return removeCleanup(body.delete, { skipSid: SID })
.then((done) => json(res, 200, { ok: true, ...done }))
.catch((e) => json(res, 500, { error: String(e.message) }));
}
return cleanupFindings({ skipSid: SID })
.then(({ items, bytes }) => json(res, 200, { ok: true, bytes, items: items.map(({ path: _p, ...item }) => item) }))
.catch((e) => json(res, 500, { error: String(e.message) }));
});
}
if (pathname === "/upload" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
const contentType = String(req.headers["content-type"] || "");
@@ -1260,7 +1319,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/submit" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
if (!body || !Array.isArray(body.actions) || body.actions.length === 0) {
return json(res, 400, { error: "actions must be a non-empty array" });
}
@@ -1361,6 +1420,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/chat" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const state = readState() || {};
const current = currentConversation(chatEntries()).conversation;
@@ -1424,6 +1484,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/chat/decision" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
if (body.decision !== "approve" && body.decision !== "decline") return json(res, 400, { error: "bad" });
if (body.text !== undefined && typeof body.text !== "string") return json(res, 400, { error: "bad" });
@@ -1472,6 +1533,7 @@ const server = http.createServer((req, res) => {
if (Object.hasOwn(workspaceRoutes, pathname) && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
let answer;
try {
@@ -1489,6 +1551,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/workspace/scope" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const spec = typeof body.spec === "string" ? body.spec : "";
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
@@ -1589,15 +1652,19 @@ function readBody(req, cb) {
let tooBig = false;
req.on("data", (c) => {
size += c.length;
// Drain past the cap rather than destroy, exactly like readRaw: a
// destroyed request emits 'close', never 'end' or 'error', so cb would
// never run and the page would see a reset instead of the 413 that names
// the problem.
if (size > MAX_BODY) {
tooBig = true;
req.destroy();
chunks.length = 0;
return;
}
chunks.push(c);
});
req.on("end", () => {
if (tooBig) return cb(new Error("too large"));
if (tooBig) return cb(Object.assign(new Error("too large"), { tooBig: true }));
try {
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
} catch (e) {
@@ -1834,6 +1901,9 @@ function onListening(port) {
bootWorkspace();
} catch {}
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
try {
startUpdateCheck();
} catch {}
try {
process.send?.({ type: "listening", port });
} catch {}
@@ -0,0 +1,138 @@
// Plan2Code Web Console - is a newer Plan2Code release out?
//
// `git ls-remote --tags` needs no API token and no rate-limited REST call,
// rides on the person's own git and proxy setup, and the newest `vX.Y.Z`
// release tag is "latest". The server
// starts this at boot and never waits on it; the answer, failures included, is
// cached for an hour so a burst of sessions asks GitHub once.
//
// Nothing here reads, stores or sends a credential: git authenticates itself,
// with every prompt turned off so a missing login fails fast instead of
// opening a window nobody asked for.
//
// Node built-ins only.
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
export const REPO_URL = "https://github.com/jparkerweb/plan2code.git";
export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
export const CACHE_MS = 60 * 60 * 1000;
const SEMVER = /^\d+\.\d+\.\d+$/;
const TAG_REF = /refs\/tags\/v(\d+\.\d+\.\d+)$/;
/** -1, 0 or 1 comparing two plain X.Y.Z versions numerically; null unless both are X.Y.Z. */
export function compareVersions(a, b) {
if (typeof a !== "string" || typeof b !== "string" || !SEMVER.test(a) || !SEMVER.test(b)) return null;
const x = a.split(".").map(Number);
const y = b.split(".").map(Number);
for (let i = 0; i < 3; i++) {
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
}
return 0;
}
/**
* The highest `vX.Y.Z` tag in `git ls-remote --tags` output, without the `v`.
* Peeled lines (`^{}`) never match, so an annotated tag counts once, and
* pre-releases or other tag names are ignored. Null when nothing matches.
*/
export function latestTag(text) {
if (typeof text !== "string") return null;
let best = null;
for (const line of text.split(/\r?\n/)) {
const m = TAG_REF.exec(line.trim());
if (m && (best === null || compareVersions(m[1], best) > 0)) best = m[1];
}
return best;
}
function readCache(cacheFile, now) {
try {
const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
if (!cached || typeof cached.checkedAt !== "number" || now - cached.checkedAt >= CACHE_MS) return undefined;
return typeof cached.latest === "string" ? cached.latest : null;
} catch {
return undefined;
}
}
function writeCache(cacheFile, data) {
const tmp = cacheFile + "." + process.pid + ".tmp";
try {
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
fs.renameSync(tmp, cacheFile);
} catch {
try {
fs.rmSync(tmp, { force: true });
} catch {}
}
}
/**
* `git ls-remote --tags` against the repo: resolves its stdout, or null when
* git is missing, fails, or is still going after `timeoutMs`. No shell, no
* window, no prompt.
*/
export function runLsRemote({ timeoutMs = 10000 } = {}) {
return new Promise((resolve) => {
let settled = false;
const done = (value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(value);
};
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
if (!process.env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
let child;
try {
child = spawn("git", ["ls-remote", "--tags", REPO_URL], {
shell: false,
windowsHide: true,
stdio: ["ignore", "pipe", "ignore"],
env,
});
} catch {
return resolve(null);
}
const timer = setTimeout(() => {
try {
child.kill();
} catch {}
done(null);
}, timeoutMs);
timer.unref?.();
let out = "";
child.stdout.setEncoding("utf8");
child.stdout.on("data", (chunk) => {
out += chunk;
});
child.on("error", () => done(null));
child.on("close", (code) => done(code === 0 ? out : null));
});
}
/**
* Whether `installed` is behind the newest release: `{ installed, latest,
* updateAvailable }`, or null when either version is unknown. Reuses a cache
* under an hour old, and caches a failed lookup as `latest: null` so it is
* not retried until the hour is up. Never throws.
*/
export async function checkForUpdate({ installed, cacheFile, now = Date.now(), run = runLsRemote }) {
try {
let latest = readCache(cacheFile, now);
if (latest === undefined) {
latest = latestTag(await run());
writeCache(cacheFile, { checkedAt: now, latest });
}
const order = compareVersions(installed, latest);
if (latest === null || order === null) return null;
return { installed, latest, updateAvailable: order < 0 };
} catch {
return null;
}
}
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -10,7 +10,7 @@
//
// and derives the ticket from a branch named <prefix>/<TICKET-ID>-description,
// where the ticket is an uppercase project key, a hyphen and an integer
// (PCWEB-10968). This script reads the branch, extracts the ticket and prints
// (ABC-10968). This script reads the branch, extracts the ticket and prints
// the exact command, so no prompt re-implements the rule by eye.
import { execFileSync } from "node:child_process";
@@ -96,7 +96,7 @@ run(USAGE, async (argv) => {
let branch = null;
let ticket = args.ticket ? args.ticket.trim() : null;
if (ticket && !/^[A-Z][A-Z0-9]*-\d+$/.test(ticket)) fail(EXIT.INVALID, "bad-ticket", `"${ticket}" is not an uppercase KEY-123 ticket ID.`, "Pass a ticket like PCWEB-10968.");
if (ticket && !/^[A-Z][A-Z0-9]*-\d+$/.test(ticket)) fail(EXIT.INVALID, "bad-ticket", `"${ticket}" is not an uppercase KEY-123 ticket ID.`, "Pass a ticket like ABC-10968.");
if (!ticket) {
branch = currentBranch();
ticket = ticketFromBranch(branch);
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -243,7 +243,7 @@ summarise it back.
Then, in ONE `post`, do all of:
- mark each answered item `"status": "answered"` and record its `answer`
- add your replies to any comment threads
- reply to every note in that item's `thread` (shape below)
- answer any Quick questions that came with it, in `chat.replies` (see Quick
questions)
- publish the next batch of questions
@@ -251,6 +251,26 @@ Then, in ONE `post`, do all of:
One post is one atomic update, so the page never shows a half-changed state.
### Replying to a note
A `comment` is the person talking to you about that card, often asking
something. It shows in the card's **Notes on this** panel, and so does your
answer:
```jsonc
{ "items": [{ "id": "p4", "thread": [
{ "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." }
] }] }
```
- Every entry is `{ "who": "agent", "text": "<markdown>" }`. `text`, not
`md`: the page reads nothing else. An entry with no `text` is rejected.
- The server writes their note into the thread as it arrives. Do not repeat
it, and send only your new entries: `thread` appends.
- Answer what they asked, in the thread, even when you also change a doc or
re-ask the question. "I've updated the doc" alone leaves the question in the
panel with no answer under it.
### Recording the answer
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
@@ -661,9 +681,17 @@ finish are dropped, so you start on a blank page and post your own. A skill
run inline from another (a quick task's review) keeps the page it was
handed. A
fresh `open` would strand the page the person is watching on the dashboard's
session while your questions went to a page nobody has open. Then run the
skill normally: its Interface question was already answered by being
launched, so start where its real work starts.
session while your questions went to a page nobody has open.
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
> own file-read tool and follow it from the top instead.** Every Plan2Code
> skill below the dashboard ships `disable-model-invocation: true` on
> purpose — it exists to be read and followed inline, not launched as a
> sub-skill — and calling one through a skill-invocation tool errors out and
> strands the hand-off mid-launch.
Its Interface step is already answered by having been launched, so start
where its real work starts.
The menu itself is the page's own list — you never send it. The page knows
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
@@ -829,6 +857,12 @@ know:
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
Post `activity` as each step starts, before its doc or question lands — reading
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
implementation — the same way Review does. A step with no card of its own
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
Finalize".
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
Stopping mid-finalize loses nothing
— the specs are untouched until Step 3's summary write — so a stop's finish
@@ -859,7 +893,7 @@ question or doc lands:
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
merge by `id` (an unknown id is added), and `thread` / `comments` append. Send only
merge by `id` (an unknown id is added), and `thread` appends. Send only
what changed. A whole-file rewrite would put the entire session back into your
context on every turn.
@@ -1239,7 +1273,7 @@ answers were submitted but never picked up.
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` and `comments` **append**: leave out any thread entry you already sent, or the person sees your reply twice. |
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
@@ -48,6 +48,10 @@ export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
// so every session within the hour reuses one lookup.
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
// test run (or a second sandboxed instance) shares one handle directory with
// the real thing, and `stop --all` reaches outside its own world and kills a
@@ -487,9 +491,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks, the folders remembered per project and spec, and the pointer to
// this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
// looks, the folders remembered per project and spec, the pointer to this
// console's directory, and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir", "update-check.json"]);
function isScratchName(name) {
return (
@@ -536,6 +540,148 @@ export async function removeScratch(consoleDir, names) {
return removed;
}
/* ------------------------------------------------------------- cleanup */
// What User Preferences -> Cleanup never removes. The console folder keeps its
// protected files, its sessions dir (old sessions go one by one, by age) and,
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
// console, the launcher (bin/, launcher.json) and the models the person added.
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
// A stray must sit untouched this long before Cleanup lists it. The same
// folders hold files that live for milliseconds -- a held
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
// rename -- and removing one mid-write loses another session's change.
export const STRAY_GRACE_MS = 60 * 60 * 1000;
// Bytes under `p`, never following a symlink: a link counts as itself.
async function diskBytes(p) {
let st;
try {
st = await fs.promises.lstat(p);
} catch {
return 0;
}
if (!st.isDirectory()) return st.size;
let entries;
try {
entries = await fs.promises.readdir(p);
} catch {
return 0;
}
let total = 0;
for (const name of entries) total += await diskBytes(path.join(p, name));
return total;
}
// The newest mtime of anything under `p`, never following a symlink. A folder
// counts by its files, since rewriting a file never touches its folder's
// mtime; an empty folder counts by its own. Anything unreadable on the way
// down answers Infinity, so it reads as just touched and stays.
function newestMtime(p) {
let st;
try {
st = fs.lstatSync(p);
} catch {
return Infinity;
}
if (!st.isDirectory()) return st.mtimeMs;
let entries;
try {
entries = fs.readdirSync(p);
} catch {
return Infinity;
}
if (!entries.length) return st.mtimeMs;
let newest = 0;
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
return newest;
}
function entryKind(entry) {
if (entry.isSymbolicLink()) return "link";
return entry.isDirectory() ? "folder" : "file";
}
function strayEntries(dir, kept, where, now) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return [];
}
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
return entries
.filter((e) => !kept.has(e.name))
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
.filter((e) => settled(e.path));
}
/**
* Everything Cleanup would remove, worked out on the server and never taken
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
* `open` sweeps by, plus every file in the folder that old, so a resumed
* session or a saved draft keeps it), anything at the top of the console folder that is
* not kept, and -- only when the console runs from its default home inside
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
* touched within `STRAY_GRACE_MS` are left for a later scan. A
* console running from another home (tests, dev) never reaches ~/.plan2code.
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
*/
export async function cleanupFindings({
consoleDir = HOME_DIR,
plan2codeDir = PLAN2CODE_DIR,
now = Date.now(),
maxAgeMs = SESSION_MAX_AGE_MS,
skipSid,
} = {}) {
const found = [];
const sessionsDir = path.join(consoleDir, "sessions");
for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) {
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
}
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
}
const items = [];
let bytes = 0;
for (const f of found) {
const size = await diskBytes(f.path);
bytes += size;
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
}
return { items, bytes };
}
/**
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
* worked out afresh first and only ids on it are touched, so a name from the
* page is never a path, and anything that stopped qualifying since the scan
* (a session touched again) stays. A link is unlinked, never followed.
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
*/
export async function removeCleanup(ids, opts = {}) {
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
const { items } = await cleanupFindings(opts);
const removed = [];
const failed = [];
let bytes = 0;
for (const item of items) {
if (!wanted.has(item.id)) continue;
try {
if (item.kind === "link") await fs.promises.unlink(item.path);
else await fs.promises.rm(item.path, { recursive: true, force: true });
removed.push(item.id);
bytes += item.bytes;
} catch {
failed.push(item.id);
}
}
return { removed, bytes, failed };
}
/**
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
* the file's realpath must sit inside the root's, so `../`, an absolute path
@@ -871,7 +1017,7 @@ export function handOff(child, pre) {
/* ----------------------------------------------------------- patch merge */
const APPEND_KEYS = new Set(["thread", "comments"]);
const APPEND_KEYS = new Set(["thread"]);
function isPlainObject(v) {
return v !== null && typeof v === "object" && !Array.isArray(v);
@@ -896,7 +1042,7 @@ function mergeOne(target, patch, where) {
}
// Merge a keyed collection: a known id merges one level, an unknown id appends.
// Named fields are replaced whole; thread/comments append.
// Named fields are replaced whole; thread appends.
function mergeKeyed(current, patchList, idKey, defaults, where) {
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
for (const entry of patchList) {
@@ -955,6 +1101,42 @@ function dropStaleSubmissions(currentItems, before, patchList) {
return merged;
}
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
// borrow the shape of the replies and doc blocks they also write, so `from` /
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
// at all is refused. The person's own notes are recorded by the server when
// they send, so an agent that echoes one back is not shown it twice.
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
function normalizeThreads(patchList, currentItems) {
return patchList.map((entry) => {
if (!isPlainObject(entry) || entry.thread == null) return entry;
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
const said = new Set(
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
);
const thread = [];
for (const m of entry.thread) {
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
guard(m, "thread");
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
if (!key) {
throw new Error(
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
);
}
const { from, role, md, body, content, ...rest } = m;
const who = (m.who || from || role) === "user" ? "user" : "agent";
const text = m[key];
if (who === "user" && said.has(text.trim())) continue;
thread.push({ ...rest, who, text });
}
return { ...entry, thread };
});
}
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
@@ -996,7 +1178,7 @@ export function applyPatch(state, patch) {
break;
case "items":
if (!Array.isArray(v)) throw new Error('"items" must be an array');
next.items = dropStaleSubmissions(next.items, state.items, v);
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
break;
case "topics":
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
@@ -1048,15 +1230,11 @@ function stampTimes(before, next) {
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
}
for (const list of [next.items, next.docs]) {
if (!Array.isArray(list)) continue;
for (const entry of list) {
if (Array.isArray(next.items)) {
for (const entry of next.items) {
if (Array.isArray(entry.thread)) {
for (const m of entry.thread) if (!m.at) m.at = now;
}
if (Array.isArray(entry.comments)) {
for (const m of entry.comments) if (!m.at) m.at = now;
}
}
}
if (Array.isArray(next.docs)) {
@@ -1289,7 +1467,10 @@ 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, sentNote, ...rest }) => rest);
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
...rest,
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
}));
const prose =
JSON.stringify(authored) +
JSON.stringify(state.docs || []) +
@@ -65,7 +65,7 @@ export function submittedAwaiting(item) {
if (!s || typeof s !== "object") return null;
if (item.answer && typeof item.answer === "object") return null;
const thread = Array.isArray(item.thread) ? item.thread : [];
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
return replied ? null : s;
}
@@ -74,17 +74,33 @@ export function submittedAwaiting(item) {
* 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.
* Any agent message from the send onwards, or one with no clock to compare,
* means it has been picked up. The person's own entries never count: the
* server writes their note into the thread as it arrives.
*/
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));
const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at));
return picked ? null : n;
}
/**
* Who said a thread entry and what they said. The contract is `{ who, text }`
* and the server lifts anything else into it, but sessions written before that
* hold `{ from, md }` replies, which would otherwise draw as empty bubbles.
*/
export function threadWho(m) {
return m && (m.who || m.from || m.role) === "user" ? "user" : "agent";
}
export function threadText(m) {
if (!m) return "";
for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k];
return "";
}
/* -------------------------------------------------------------- labels */
export function optionLabel(item, k) {
@@ -23,6 +23,9 @@
--warn-soft: #fbe7e3;
--focus: #1f6feb;
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
/* A soft accent halo for the things that want noticing: the update banner
and an enabled Send. Built from --accent, so a picked accent glows too. */
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
@@ -61,6 +64,7 @@
--warn-soft: #34201d;
--focus: #6aa3ff;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
}
}
@@ -85,6 +89,7 @@
--warn-soft: #34201d;
--focus: #6aa3ff;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
}
* { box-sizing: border-box; }
@@ -1097,10 +1102,11 @@ h1 {
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
the tiny ring, left of the label. */
.view-tab .tab-spin {
the tiny ring, left of the label. The extra .spinner is for specificity:
.spinner.tiny comes later and zeroes the margin otherwise. */
.view-tab .spinner.tab-spin {
display: inline-block;
margin-right: 6px;
margin-right: 7px;
vertical-align: -1px;
}
@@ -1657,11 +1663,13 @@ input[type="text"].invalid { border-color: var(--warn); }
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
/* Send breathes while there is something to send: a soft accent ring that
spreads and fades. Off under reduced motion, below. */
/* Send glows and breathes while there is something to send: the steady
--glow, plus a soft accent ring that spreads and fades. The ring is off
under reduced motion, below; the glow stays. */
#btn-send:not(:disabled) { box-shadow: var(--glow); }
@keyframes send-pulse {
0% { box-shadow: 0 0 0 0 var(--accent-line); }
100% { box-shadow: 0 0 0 6px transparent; }
0% { box-shadow: var(--glow), 0 0 0 0 var(--accent-line); }
100% { box-shadow: var(--glow), 0 0 0 6px transparent; }
}
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
@@ -2219,6 +2227,7 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
.modal.help[open] { display: flex; }
.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-version a { color: inherit; }
.help-layout {
display: grid;
@@ -2668,6 +2677,74 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
border-left-width: 4px;
color: var(--ink);
}
/* A newer release: the same slot, in the accent, with the label as the way
into the update modal and a small × that hides it for this session. */
.dash-nudge.update-banner {
position: relative;
padding-left: 40px;
padding-right: 40px;
border-left-width: 4px;
border-left-color: var(--accent-line);
color: var(--ink);
box-shadow: var(--glow);
}
.update-banner-open {
flex: 1 1 16em;
padding: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
font-weight: 600;
letter-spacing: 0.02em;
text-align: center;
cursor: pointer;
}
.update-banner-open:hover { text-decoration: underline; }
/* Pinned to the right edge, out of the flow, so the label centres on the
whole banner rather than on what the × leaves of it. */
.update-banner-dismiss {
position: absolute;
top: 50%;
right: 10px;
transform: translateY(-50%);
padding: 0 6px;
border: 0;
border-radius: var(--radius);
background: none;
color: inherit;
font: inherit;
font-size: 16px;
line-height: 1;
cursor: pointer;
}
.update-banner-dismiss:hover { background: var(--accent-line); }
/* Wide enough that the update command sits on one line beside Copy; a
narrow window still wraps it rather than overflowing. */
#update-modal { max-width: 720px; }
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
.update-steps li { margin: 4px 0; }
/* The hand-off copy row, in the modal's first step: the command and its Copy
side by side. */
.update-command {
margin: 6px 0 4px;
display: flex;
align-items: stretch;
gap: 10px;
flex-wrap: wrap;
}
.update-command code {
flex: 1 1 260px;
min-width: 0;
font: 13px/1.5 var(--mono);
color: var(--ink);
background: var(--panel);
border: 1px solid var(--rule-2);
border-radius: 8px;
padding: 10px 12px;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
.dash-working {
@@ -3394,6 +3471,18 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.models-actions .help.error { color: var(--danger, #d64545); }
/* User Preferences: Cleanup's list of what would go, shown before anything
is deleted. */
.cleanup-list { display: grid; gap: 4px; max-height: 200px; overflow: auto; font-size: 0.88em; }
.cleanup-list:empty { display: none; }
.cleanup-summary { margin: 0 0 2px; font-weight: 600; }
.cleanup-row { display: flex; justify-content: space-between; gap: 12px; }
.cleanup-row span:first-child { min-width: 0; overflow-wrap: anywhere; font-family: var(--mono); }
.cleanup-size { flex: none; color: var(--ink-3); }
.cleanup-more { display: grid; gap: 4px; }
.cleanup-more summary { cursor: pointer; color: var(--ink-2); }
#cleanup-delete[hidden] { display: none; }
/* 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 {
@@ -66,6 +66,8 @@ import {
submittedAwaiting,
noteAwaiting,
suggestionFrom,
threadText,
threadWho,
THUMB_EDGE,
turnGate,
verdictText,
@@ -446,6 +448,10 @@ document.addEventListener("click", (e) => {
const GONE_AFTER_MS = 8000;
// Named so a reconnect can clear only THIS banner: a bare banner(null) would
// wipe an unrelated warning that landed while the page was gone (an upload
// failure, a refused send).
const GONE_BANNER = "Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.";
const WORKING_GRACE_MS = 5 * 60 * 1000;
// Two minutes with the agent mid-turn, three when it is merely meant to be
// listening. The difference is the cost of being wrong: a working agent that
@@ -521,6 +527,9 @@ let chatFrame = null;
// sends them.
let wsFrame = null;
let meterFrame = null;
// The frame's update ({ installed, latest }), present only when a newer
// release is out; null otherwise.
let updateFrame = null;
let chatDot = false;
let chatSending = false;
let chatResetting = false;
@@ -566,7 +575,6 @@ function fresh() {
drafts: {},
images: {},
sent: {},
sentAt: null,
stopping: null,
afterBuild: null,
homeward: null,
@@ -870,10 +878,12 @@ function adopt(body) {
chatFrame = body.chat || null;
if (body.workspace) wsFrame = body.workspace;
if (body.meter) meterFrame = body.meter;
// Always replaced: an absent key means no update.
updateFrame = body.update || null;
lastContact = Date.now();
if (gone) {
gone = false;
banner(null);
if ($("banner").textContent === GONE_BANNER) banner(null);
}
if (firstLoad) {
load();
@@ -1016,7 +1026,9 @@ function adopt(body) {
render();
if ($("workspace-modal").open) renderWorkspace();
tellFolderIssues();
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow) loadOverview();
// The Overview tab's file changes under a build, so a tab you are watching
// refetches on every new frame too, not only on the click that opened it.
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow || view === "overview") loadOverview();
if (announce) showArrival(announce);
// New entries land at the bottom of the rail. Gliding down to them beats
// leaving the list parked where it was while it grew underneath.
@@ -1149,15 +1161,12 @@ function markGone() {
// of the server means there, and a banner promising a reconnect would
// argue with it.
if (!finish() && !stopInProgress()) {
banner(
"Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.",
"warn"
);
banner(GONE_BANNER, "warn");
}
render();
} else if (!bad && gone) {
gone = false;
banner(null);
if ($("banner").textContent === GONE_BANNER) banner(null);
render();
}
}
@@ -1182,7 +1191,6 @@ function connect() {
} catch {}
});
es.addEventListener("submitted", (e) => {
local.sentAt = Date.now();
// Drop only what was actually sent.
//
// This event fires for a send from ANY tab of this session, which is why it
@@ -1799,14 +1807,19 @@ async function sendBrief() {
reply: briefPhrase(choice.range),
}),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
$("brief-modal").close();
banner("Asked for a brief. It will appear as a tab when it is written.", "good");
setTimeout(() => banner(null), 5000);
pendingResult = true;
render();
} catch {
why.textContent = "That did not go through. Try again in a moment.";
} catch (err) {
if (err && err.pending) pendingResult = true;
why.textContent =
err && err.pending
? "Your last answers are still being picked up. Try again in a moment."
: "That did not go through. Try again in a moment.";
} finally {
go.disabled = false;
go.textContent = "Write the brief";
@@ -2515,6 +2528,51 @@ function roleNudge() {
return nudge;
}
// × on the update banner hides it for this console session only, and only
// for the release it named. Blocked storage means "not dismissed".
function updateDismissKey() {
try {
return "p2c-update-dismissed:" + S.sid;
} catch {
return "p2c-update-dismissed:";
}
}
function updateDismissed() {
try {
return sessionStorage.getItem(updateDismissKey()) === updateFrame.latest;
} catch {
return false;
}
}
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
const UPDATE_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
function releasesLink(text) {
const a = el("a", null, text);
a.href = RELEASES_URL;
a.target = "_blank";
a.rel = "noopener noreferrer";
return a;
}
function openUpdateModal() {
if (!updateFrame) return;
const versions = $("update-versions");
versions.replaceChildren(
document.createTextNode("Version "),
releasesLink("v" + updateFrame.latest),
document.createTextNode(" is out — you have "),
el("code", null, updateFrame.installed),
document.createTextNode(".")
);
const row = $("update-command");
const code = el("code", null, UPDATE_COMMAND);
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
$("update-modal").showModal();
}
function renderDashboard(main) {
maybeWake();
const menu = (S && S.menu) || {};
@@ -2526,6 +2584,25 @@ function renderDashboard(main) {
warn.setAttribute("role", "status");
wrap.appendChild(warn);
}
// Built here only, so no other workflow's page ever shows it.
if (updateFrame && !updateDismissed()) {
const notice = el("div", "dash-nudge update-banner");
notice.setAttribute("role", "status");
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + updateFrame.latest);
open.type = "button";
open.addEventListener("click", openUpdateModal);
const dismiss = el("button", "update-banner-dismiss", "×");
dismiss.type = "button";
dismiss.setAttribute("aria-label", "Dismiss until next time");
dismiss.addEventListener("click", () => {
try {
sessionStorage.setItem(updateDismissKey(), updateFrame.latest);
} catch {}
render();
});
notice.append(open, dismiss);
wrap.appendChild(notice);
}
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
if (typeof menu.note === "string" && menu.note.trim()) {
@@ -3223,7 +3300,11 @@ document.addEventListener("keydown", cancelSkipMove, true);
function skipAndMoveOn(id) {
cancelSkipMove();
local.skipFlash = id;
stage(id, { type: "skip", skipped: true });
// A note already typed goes along: skipping the question is not retracting
// the comment. Dropping it would leave the text in the box but out of the
// send, which looks kept and is not.
const cur = local.staged[id];
stage(id, { type: "skip", skipped: true, ...(cur && cur.text ? { text: cur.text } : {}) });
skipTimer = setTimeout(() => {
skipTimer = null;
local.skipFlash = null;
@@ -3340,19 +3421,24 @@ function renderWaiting(main) {
}
pane.appendChild(title);
pane.appendChild(el("p", null, doing));
const ask = "If Plan2Code needs you, the question appears here on its own.";
if (!docs().length) {
pane.appendChild(el("p", null, "If Plan2Code needs you, the question appears here on its own."));
pane.appendChild(el("p", null, ask));
return;
}
// "Task" and the tasks tab's own name both open that tab, so the pointer is
// one click from what it points at. A build posts it as `phase` ("Phase N
// tasks"), a quick task as `tasks`; with neither the words stay plain.
// tasks"), a quick task as `tasks`. A skill with no task list (Document,
// Plan) has nothing live to follow, so it gets no pointer at all.
const list =
docs().find((d) => d.id === "phase") ||
docs().find((d) => d.id === "tasks") ||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
if (!list) {
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
return;
}
const jump = (word) => {
if (!list) return el("strong", "waiting-jump", word);
const b = el("button", "waiting-jump", word);
b.type = "button";
b.addEventListener("click", () => {
@@ -3366,8 +3452,8 @@ function renderWaiting(main) {
"The tabs above fill in as it goes. You can follow along with live ",
jump("Task"),
" updates in the ",
jump((list && list.title) || "Phase tasks"),
" tab. If Plan2Code needs you, the question appears here on its own."
jump(list.title || "Phase tasks"),
" tab. " + ask
);
pane.appendChild(p);
}
@@ -3505,8 +3591,8 @@ function renderSettled(card, item) {
// would misreport which of the two was the answer.
let prose = text;
if (!prose && !lines.length) {
const mine = (item.thread || []).filter((m) => m.who === "user");
if (mine.length) prose = String(mine[mine.length - 1].text || "").trim();
const mine = (item.thread || []).filter((m) => threadWho(m) === "user");
if (mine.length) prose = threadText(mine[mine.length - 1]).trim();
}
const nothing = !lines.length && !prose;
@@ -4322,6 +4408,10 @@ function buildChecklist(card, item, staged) {
const commitList = (change) => {
const cur = local.staged[item.id];
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
// A tick or a state IS the answer, so it ends a skip staged earlier:
// left in place, `skipped` would collapse the reply to "skip" while the
// card showed ticked steps on their way.
delete next.skipped;
const empty = !(next.done && next.done.length) && !next.state && !next.text;
stage(item.id, empty ? null : next);
};
@@ -4371,7 +4461,7 @@ function buildChecklist(card, item, staged) {
function buildMenu(card, item, staged) {
const list = el("ul", "options");
const name = "menu-" + item.id;
for (const o of item.options || []) {
for (const [i, o] of (item.options || []).entries()) {
const picked = staged && staged.k === o.k;
const li = el("li", "option" + (picked ? " is-picked" : ""));
const label = el("label");
@@ -4379,7 +4469,13 @@ function buildMenu(card, item, staged) {
const radio = el("input");
radio.type = "radio";
radio.name = name;
// The same id buildChoice gives its radios: withFocus finds the focused
// input by id after the render this change() sets off, and without one a
// keyboard user arrowing through the menu lands on <body> every time.
radio.id = optionId(item, o, i);
radio.value = o.k;
radio.checked = Boolean(picked);
radio.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
const body = el("div", "option-body");
const head = el("div", "option-label");
@@ -5276,20 +5372,30 @@ function renderAside() {
)
);
}
// A note that has been sent but not yet picked up: marked as waiting, so the
// send is seen to have gone, until the agent replies. The server writes the
// note into the thread as it arrives; a session from before that has only
// `sentNote`, which gets a box of its own below.
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
let waitingShown = false;
for (const m of thread) {
const box = el("div", "msg " + (m.who === "user" ? "you" : ""));
const mine = threadWho(m) === "user";
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
if (pending) waitingShown = true;
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
const who = el("div", "msg-who");
who.appendChild(el("span", null, m.who === "user" ? "You" : "Plan2Code"));
if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
box.appendChild(who);
box.appendChild(md(m.text, "md"));
const text = threadText(m);
if (text) box.appendChild(md(text, "md"));
const tray = mine ? sentAttachments(m) : null;
if (tray) box.appendChild(tray);
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) {
if (waiting && !waitingShown) {
const box = el("div", "msg you pending");
const who = el("div", "msg-who");
who.appendChild(el("span", null, "You"));
@@ -5589,7 +5695,10 @@ async function attachFiles(itemId, files) {
const taken = wanted.slice(0, room);
// One banner at a time, so every refusal goes into it, each by name.
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
if (taken.length < wanted.length) said.push(chat ? "Up to 5 attachments per question." : "Up to 5 attachments per note.");
if (taken.length < wanted.length)
said.push(
chat ? `Up to ${CHAT_MAX_ATTACHMENTS} attachments per question.` : `Up to ${MAX_ATTACHMENTS} attachments per note.`
);
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
await Promise.all(
taken.map(async (file) => {
@@ -6439,6 +6548,10 @@ async function goHome() {
$("home-modal").close();
} catch (err) {
$("home-modal").close();
// The server is holding an uncollected result: Send, Home and Stop all
// need to read as busy until the frame or the ping says otherwise, same
// as send() and sendAfterBuild() do on a 409.
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
@@ -6499,6 +6612,7 @@ async function stopSession() {
stoppingHidden = false;
} catch (err) {
$("stop-modal").close();
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
@@ -6653,7 +6767,6 @@ function markSent({ sentIds, sentNotes = {}, summaries, values }) {
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
}
local.staged = {};
local.sentAt = Date.now();
save();
}
@@ -6706,7 +6819,7 @@ const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", d
// something the agent never hears.
function tokenFor(item, v) {
const map = item.token || {};
if (v.skipped) return "skip";
if (v.skipped) return v.text ? `skip; ${v.text}` : "skip";
const parts = [];
if (v.k) parts.push(map[v.k] || v.k);
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
@@ -6938,14 +7051,14 @@ function renderAbout() {
let helpBuilt = false;
async function renderHelpVersion() {
const el = $("help-version");
const slot = $("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;
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
slot.hidden = !version;
} catch {
el.hidden = true;
slot.hidden = true;
}
}
@@ -7053,6 +7166,7 @@ function openHelpOn(id) {
}
$("btn-home").addEventListener("click", openHomeConfirm);
$("update-done").addEventListener("click", () => $("update-modal").close());
$("home-cancel").addEventListener("click", () => $("home-modal").close());
$("home-go").addEventListener("click", goHome);
$("btn-stop").addEventListener("click", openStopConfirm);
@@ -7132,6 +7246,7 @@ $("btn-looks").addEventListener("click", () => {
});
$("looks-done").addEventListener("click", () => $("looks-modal").close());
$("looks-modal").addEventListener("close", () => {
resetCleanup();
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
});
$("looks-reset").addEventListener("click", () => {
@@ -7278,6 +7393,111 @@ $("models-reset").addEventListener("click", () => {
renderModels();
});
// Cleanup: the server works out what in ~/.plan2code is not needed and
// shows it first; Delete these sends back only the ids it was shown, and the
// server re-checks every one before removing it.
let cleanupFound = null;
// Bumped by every scan, delete and reset: a response from an older one is
// dropped, so a scan still in flight when Preferences closes cannot refill it.
let cleanupGen = 0;
const CLEANUP_SHOWN = 8;
function setCleanupStatus(text, isError) {
const status = $("cleanup-status");
status.textContent = text;
status.classList.toggle("error", Boolean(isError));
}
function cleanupLabel(item) {
if (item.where === "session") return "Session " + item.name;
const where = item.where === "root" ? "~/.plan2code/" : "~/.plan2code/console/";
return where + item.name + (item.kind === "folder" ? "/" : "");
}
function cleanupSummary(items, bytes) {
const sessions = items.filter((i) => i.where === "session").length;
const strays = items.length - sessions;
const parts = [];
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
return parts.join(", ") + " · " + formatBytes(bytes);
}
function resetCleanup() {
cleanupGen++;
cleanupFound = null;
$("cleanup-list").replaceChildren();
$("cleanup-delete").hidden = true;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
setCleanupStatus("", false);
}
function renderCleanup() {
const list = $("cleanup-list");
list.replaceChildren();
const items = (cleanupFound && cleanupFound.items) || [];
$("cleanup-delete").hidden = !items.length;
if (!items.length) return;
const rows = (some) => some.map((item) => {
const row = el("div", "cleanup-row");
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", formatBytes(item.bytes)));
return row;
});
list.append(el("p", "cleanup-summary", cleanupSummary(items, cleanupFound.bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
if (items.length > CLEANUP_SHOWN) {
const more = el("details", "cleanup-more");
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
list.appendChild(more);
}
}
async function scanCleanup() {
const gen = ++cleanupGen;
$("cleanup-scan").disabled = true;
$("cleanup-delete").disabled = true;
setCleanupStatus("Looking…", false);
const { status, body } = await postJson("/cleanup", { scan: true });
if (gen !== cleanupGen) return;
$("cleanup-scan").disabled = false;
$("cleanup-delete").disabled = false;
if (status !== 200 || !body.ok) {
cleanupFound = null;
renderCleanup();
return setCleanupStatus(status ? body.error || "Could not look." : "Plan2Code isn't reachable.", true);
}
cleanupFound = { items: body.items || [], bytes: body.bytes || 0 };
renderCleanup();
// Left in the status line, not cleared: it is the live region, so this is
// what a screen reader hears when the scan finishes.
const found = cleanupFound.items.length;
setCleanupStatus(found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.", false);
}
async function deleteCleanup() {
if (!cleanupFound || !cleanupFound.items.length) return;
const gen = ++cleanupGen;
$("cleanup-delete").disabled = true;
$("cleanup-scan").disabled = true;
setCleanupStatus("Deleting…", false);
const { status, body } = await postJson("/cleanup", { delete: cleanupFound.items.map((i) => i.id) });
if (gen !== cleanupGen) return;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
if (status !== 200 || !body.ok) {
return setCleanupStatus(status ? body.error || "Could not delete." : "Plan2Code isn't reachable.", true);
}
const removed = (body.removed || []).length;
const failed = (body.failed || []).length;
cleanupFound = null;
renderCleanup();
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
setCleanupStatus(failed ? done + " " + failed + " could not be removed." : done, Boolean(failed));
}
$("cleanup-scan").addEventListener("click", scanCleanup);
$("cleanup-delete").addEventListener("click", deleteCleanup);
$("btn-brief").addEventListener("click", openBrief);
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
$("brief-go").addEventListener("click", sendBrief);
@@ -1291,6 +1291,14 @@
come back, and you can change your role any time from the swatch
button.
</p>
<h4>When an update is out</h4>
<p>
When a newer Plan2Code release is out, the dashboard shows
<strong>UPDATE AVAILABLE</strong> at the top. Click it for the command
to run in your terminal; × hides it until the next
<code>/plan2code</code>. The version at the bottom of Help links to
the Releases page.
</p>
<h4>The cards</h4>
<p>They come in three groups.</p>
<p><strong>First, the project</strong></p>
@@ -1845,6 +1853,15 @@
joining the strip. Keep only the ones you want; ticking a box plays
its sound.
</li>
<li>
<strong>Cleanup</strong>: <strong>Find files to clean up</strong>
lists what Plan2Code doesn't need in your
<code>~/.plan2code</code> folder: sessions nobody has opened for
30 days, and files or folders that ended up there by mistake. It
shows each one with its size, and <strong>Delete these</strong>
removes exactly that list. Your preferences, saved folders, models,
the launcher and the session you are in always stay.
</li>
<li>
<strong>Back to default</strong> puts everything back as it was, and
sets Role back to Not set.
@@ -1983,6 +2000,16 @@
</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-cleanup">
<legend>Cleanup</legend>
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
<div class="models-actions">
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
<button type="button" class="btn small danger" id="cleanup-delete" hidden>Delete these</button>
<span class="help" id="cleanup-status" role="status"></span>
</div>
</fieldset>
<fieldset class="modal-ranges looks-models">
<legend>Models</legend>
<div class="models-tabs" role="group" aria-label="Which agent">
@@ -2181,6 +2208,24 @@
</div>
</dialog>
<!-- Opened from the dashboard's UPDATE AVAILABLE banner. The versions and
the copy row are filled by app.js; the update itself runs in a
terminal, never from this page. -->
<dialog class="modal" id="update-modal" aria-labelledby="update-title">
<h2 id="update-title">A new Plan2Code is available</h2>
<p class="modal-blurb" id="update-versions"></p>
<ol class="update-steps">
<li>
Run this in your terminal (not in this page or your agent):
<div class="update-command" id="update-command"></div>
</li>
<li>When it finishes, close this console and start <code>plan2code</code> again.</li>
</ol>
<div class="modal-actions">
<button type="button" class="btn primary" id="update-done">Close</button>
</div>
</dialog>
<footer class="footer">
<div class="footer-summary" id="footer-summary" aria-live="polite">
Nothing to send yet.
@@ -5,7 +5,10 @@
// popover; this file owns the rules. No DOM access at module scope and no
// imports: the page and `node --test` both import this file.
const NAME_CHAR = /[a-z0-9-]/;
// Uppercase too: "@Repo" must still name @repo — names are forced lowercase
// by the workspace rules, and a query typed with a capital otherwise matches
// nothing and opens no suggestions at all.
const NAME_CHAR = /[a-z0-9-]/i;
const MAX_MATCHES = 6;
/**
@@ -23,11 +26,13 @@ export function mentionAt(text, caret) {
}
// Names starting with the query first, then names containing it, in the
// order given, at most six.
// order given, at most six. Case-folded: folder names are lowercase by rule,
// and "@Repo" should still find @repo rather than claim nothing matches.
export function matchNames(names, query) {
const q = String(query || "");
const prefix = names.filter((n) => n.startsWith(q));
const inside = names.filter((n) => !n.startsWith(q) && n.includes(q));
const q = String(query || "").toLowerCase();
const fold = (n) => String(n).toLowerCase();
const prefix = names.filter((n) => fold(n).startsWith(q));
const inside = names.filter((n) => !fold(n).startsWith(q) && fold(n).includes(q));
return [...prefix, ...inside].slice(0, MAX_MATCHES);
}
@@ -25,12 +25,14 @@ import {
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_MODELS_FILE,
UPDATE_CHECK_FILE,
USER_MODELS_FILE,
WORKSPACE_FILE,
appendChat,
appendEvent,
chatForFrame,
checkDocument,
cleanupFindings,
currentConversation,
ensureDir,
fileStamp,
@@ -47,6 +49,7 @@ import {
readWorkspace,
rememberWorkspace,
rememberedWorkspace,
removeCleanup,
remoteWarning,
specKey,
typedCount,
@@ -59,6 +62,7 @@ import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
import { meterView } from "./public/meter.js";
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
import { checkForUpdate } from "./update-check.mjs";
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
const args = parseArgs(process.argv.slice(2));
@@ -611,6 +615,7 @@ function stateFrame(state) {
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
workspace: workspaceView(),
meter: meterView(ledgerEntries()),
...(updateInfo ? { update: updateInfo } : {}),
have: haveKey(),
};
}
@@ -623,7 +628,7 @@ function haveKey() {
ledgerEntries();
return (
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}`
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}`
);
}
@@ -648,6 +653,12 @@ function recordSubmitted(state, actions) {
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) };
// The person's side of the Notes thread. Left to the agent it was never
// written, so a question asked in a note vanished once it was picked up
// and the reply under it answered nothing on the page.
if (item.sentNote.text.trim() || item.sentNote.images.length || item.sentNote.files.length) {
item.thread = [...(Array.isArray(item.thread) ? item.thread : []), { who: "user", ...item.sentNote }];
}
continue;
}
const { i, type, ...rest } = action;
@@ -933,6 +944,38 @@ function pushState() {
if (stateNow) broadcast("state", stateFrame(stateNow));
}
/* --------------------------------------------------------- update check */
// The version this console was installed as: install.js writes version.json
// beside console.mjs; a dev checkout falls back to the repo root's.
function installedVersion() {
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 version;
}
return null;
}
// Filled in once the boot-time check answers; until then, and whenever it
// fails, the frame carries no `update` and the page shows no banner.
let updateInfo = null;
let updateLatest = null;
// Started at boot and never awaited: git may take up to its 10 s limit, and
// nothing the person sees waits on it. The catch is not optional: a throw in
// pushState() would otherwise be an unhandled rejection, which ends the server.
function startUpdateCheck() {
const installed = installedVersion();
if (!installed) return;
checkForUpdate({ installed, cacheFile: UPDATE_CHECK_FILE })
.then((result) => {
updateLatest = result?.latest ?? null;
updateInfo = result?.updateAvailable ? { installed: result.installed, latest: result.latest } : null;
if (updateInfo) pushState();
})
.catch(() => {});
}
let agentSeenAt = Date.now();
function agentLastSeen() {
return new Date(agentSeenAt).toISOString();
@@ -1039,10 +1082,8 @@ const server = http.createServer((req, res) => {
}
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 });
}
const version = installedVersion();
if (version) return json(res, 200, { version, latest: updateLatest });
return json(res, 404, { error: "no version" });
}
@@ -1090,7 +1131,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/draft" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
// Debounced client-side; this is just the durable mirror. Twenty minutes
// of someone's structured answers must not die with a closed tab.
try {
@@ -1115,7 +1156,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/looks" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
// `set` carries only the keys one tab changed, merged onto what is on
// disk, so a tab holding stale settings cannot undo another tab's change.
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
@@ -1141,7 +1182,7 @@ const server = http.createServer((req, res) => {
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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
const { models, error } = cleanModels(body && body.models);
if (error) return json(res, 400, { error });
try {
@@ -1154,6 +1195,24 @@ const server = http.createServer((req, res) => {
});
}
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
// ~/.plan2code; `{ delete: [id] }` removes those of the ids a fresh scan
// still finds. Never this session, never a path the page sent.
if (pathname === "/cleanup" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
if (body && Array.isArray(body.delete)) {
return removeCleanup(body.delete, { skipSid: SID })
.then((done) => json(res, 200, { ok: true, ...done }))
.catch((e) => json(res, 500, { error: String(e.message) }));
}
return cleanupFindings({ skipSid: SID })
.then(({ items, bytes }) => json(res, 200, { ok: true, bytes, items: items.map(({ path: _p, ...item }) => item) }))
.catch((e) => json(res, 500, { error: String(e.message) }));
});
}
if (pathname === "/upload" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
const contentType = String(req.headers["content-type"] || "");
@@ -1260,7 +1319,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/submit" && 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" });
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
if (!body || !Array.isArray(body.actions) || body.actions.length === 0) {
return json(res, 400, { error: "actions must be a non-empty array" });
}
@@ -1361,6 +1420,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/chat" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const state = readState() || {};
const current = currentConversation(chatEntries()).conversation;
@@ -1424,6 +1484,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/chat/decision" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
if (body.decision !== "approve" && body.decision !== "decline") return json(res, 400, { error: "bad" });
if (body.text !== undefined && typeof body.text !== "string") return json(res, 400, { error: "bad" });
@@ -1472,6 +1533,7 @@ const server = http.createServer((req, res) => {
if (Object.hasOwn(workspaceRoutes, pathname) && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
let answer;
try {
@@ -1489,6 +1551,7 @@ const server = http.createServer((req, res) => {
if (pathname === "/workspace/scope" && req.method === "POST") {
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
return readBody(req, (err, body) => {
if (err && err.tooBig) return json(res, 413, { error: "too large" });
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
const spec = typeof body.spec === "string" ? body.spec : "";
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
@@ -1589,15 +1652,19 @@ function readBody(req, cb) {
let tooBig = false;
req.on("data", (c) => {
size += c.length;
// Drain past the cap rather than destroy, exactly like readRaw: a
// destroyed request emits 'close', never 'end' or 'error', so cb would
// never run and the page would see a reset instead of the 413 that names
// the problem.
if (size > MAX_BODY) {
tooBig = true;
req.destroy();
chunks.length = 0;
return;
}
chunks.push(c);
});
req.on("end", () => {
if (tooBig) return cb(new Error("too large"));
if (tooBig) return cb(Object.assign(new Error("too large"), { tooBig: true }));
try {
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
} catch (e) {
@@ -1834,6 +1901,9 @@ function onListening(port) {
bootWorkspace();
} catch {}
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
try {
startUpdateCheck();
} catch {}
try {
process.send?.({ type: "listening", port });
} catch {}
@@ -0,0 +1,138 @@
// Plan2Code Web Console - is a newer Plan2Code release out?
//
// `git ls-remote --tags` needs no API token and no rate-limited REST call,
// rides on the person's own git and proxy setup, and the newest `vX.Y.Z`
// release tag is "latest". The server
// starts this at boot and never waits on it; the answer, failures included, is
// cached for an hour so a burst of sessions asks GitHub once.
//
// Nothing here reads, stores or sends a credential: git authenticates itself,
// with every prompt turned off so a missing login fails fast instead of
// opening a window nobody asked for.
//
// Node built-ins only.
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
export const REPO_URL = "https://github.com/jparkerweb/plan2code.git";
export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
export const CACHE_MS = 60 * 60 * 1000;
const SEMVER = /^\d+\.\d+\.\d+$/;
const TAG_REF = /refs\/tags\/v(\d+\.\d+\.\d+)$/;
/** -1, 0 or 1 comparing two plain X.Y.Z versions numerically; null unless both are X.Y.Z. */
export function compareVersions(a, b) {
if (typeof a !== "string" || typeof b !== "string" || !SEMVER.test(a) || !SEMVER.test(b)) return null;
const x = a.split(".").map(Number);
const y = b.split(".").map(Number);
for (let i = 0; i < 3; i++) {
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
}
return 0;
}
/**
* The highest `vX.Y.Z` tag in `git ls-remote --tags` output, without the `v`.
* Peeled lines (`^{}`) never match, so an annotated tag counts once, and
* pre-releases or other tag names are ignored. Null when nothing matches.
*/
export function latestTag(text) {
if (typeof text !== "string") return null;
let best = null;
for (const line of text.split(/\r?\n/)) {
const m = TAG_REF.exec(line.trim());
if (m && (best === null || compareVersions(m[1], best) > 0)) best = m[1];
}
return best;
}
function readCache(cacheFile, now) {
try {
const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
if (!cached || typeof cached.checkedAt !== "number" || now - cached.checkedAt >= CACHE_MS) return undefined;
return typeof cached.latest === "string" ? cached.latest : null;
} catch {
return undefined;
}
}
function writeCache(cacheFile, data) {
const tmp = cacheFile + "." + process.pid + ".tmp";
try {
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
fs.renameSync(tmp, cacheFile);
} catch {
try {
fs.rmSync(tmp, { force: true });
} catch {}
}
}
/**
* `git ls-remote --tags` against the repo: resolves its stdout, or null when
* git is missing, fails, or is still going after `timeoutMs`. No shell, no
* window, no prompt.
*/
export function runLsRemote({ timeoutMs = 10000 } = {}) {
return new Promise((resolve) => {
let settled = false;
const done = (value) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(value);
};
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
if (!process.env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
let child;
try {
child = spawn("git", ["ls-remote", "--tags", REPO_URL], {
shell: false,
windowsHide: true,
stdio: ["ignore", "pipe", "ignore"],
env,
});
} catch {
return resolve(null);
}
const timer = setTimeout(() => {
try {
child.kill();
} catch {}
done(null);
}, timeoutMs);
timer.unref?.();
let out = "";
child.stdout.setEncoding("utf8");
child.stdout.on("data", (chunk) => {
out += chunk;
});
child.on("error", () => done(null));
child.on("close", (code) => done(code === 0 ? out : null));
});
}
/**
* Whether `installed` is behind the newest release: `{ installed, latest,
* updateAvailable }`, or null when either version is unknown. Reuses a cache
* under an hour old, and caches a failed lookup as `latest: null` so it is
* not retried until the hour is up. Never throws.
*/
export async function checkForUpdate({ installed, cacheFile, now = Date.now(), run = runLsRemote }) {
try {
let latest = readCache(cacheFile, now);
if (latest === undefined) {
latest = latestTag(await run());
writeCache(cacheFile, { checkedAt: now, latest });
}
const order = compareVersions(installed, latest);
if (latest === null || order === null) return null;
return { installed, latest, updateAvailable: order < 0 };
} catch {
return null;
}
}
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -10,7 +10,7 @@
//
// and derives the ticket from a branch named <prefix>/<TICKET-ID>-description,
// where the ticket is an uppercase project key, a hyphen and an integer
// (PCWEB-10968). This script reads the branch, extracts the ticket and prints
// (ABC-10968). This script reads the branch, extracts the ticket and prints
// the exact command, so no prompt re-implements the rule by eye.
import { execFileSync } from "node:child_process";
@@ -96,7 +96,7 @@ run(USAGE, async (argv) => {
let branch = null;
let ticket = args.ticket ? args.ticket.trim() : null;
if (ticket && !/^[A-Z][A-Z0-9]*-\d+$/.test(ticket)) fail(EXIT.INVALID, "bad-ticket", `"${ticket}" is not an uppercase KEY-123 ticket ID.`, "Pass a ticket like PCWEB-10968.");
if (ticket && !/^[A-Z][A-Z0-9]*-\d+$/.test(ticket)) fail(EXIT.INVALID, "bad-ticket", `"${ticket}" is not an uppercase KEY-123 ticket ID.`, "Pass a ticket like ABC-10968.");
if (!ticket) {
branch = currentBranch();
ticket = ticketFromBranch(branch);
@@ -1,6 +1,6 @@
{
"name": "Plan2Code",
"version": "2.4.1",
"version": "2.4.2",
"description": "A structured 4-step workflow methodology for AI-assisted software development",
"keywords": [
"ai",
@@ -17,6 +17,6 @@
"url": "https://github.com/jparkerweb/plan2code"
},
"homepage": "https://github.com/jparkerweb/plan2code",
"releaseDate": "2026-10-04",
"releaseDate": "2026-10-05",
"mode": "utility"
}
@@ -243,7 +243,7 @@ summarise it back.
Then, in ONE `post`, do all of:
- mark each answered item `"status": "answered"` and record its `answer`
- add your replies to any comment threads
- reply to every note in that item's `thread` (shape below)
- answer any Quick questions that came with it, in `chat.replies` (see Quick
questions)
- publish the next batch of questions
@@ -251,6 +251,26 @@ Then, in ONE `post`, do all of:
One post is one atomic update, so the page never shows a half-changed state.
### Replying to a note
A `comment` is the person talking to you about that card, often asking
something. It shows in the card's **Notes on this** panel, and so does your
answer:
```jsonc
{ "items": [{ "id": "p4", "thread": [
{ "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." }
] }] }
```
- Every entry is `{ "who": "agent", "text": "<markdown>" }`. `text`, not
`md`: the page reads nothing else. An entry with no `text` is rejected.
- The server writes their note into the thread as it arrives. Do not repeat
it, and send only your new entries: `thread` appends.
- Answer what they asked, in the thread, even when you also change a doc or
re-ask the question. "I've updated the doc" alone leaves the question in the
panel with no answer under it.
### Recording the answer
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
@@ -661,9 +681,17 @@ finish are dropped, so you start on a blank page and post your own. A skill
run inline from another (a quick task's review) keeps the page it was
handed. A
fresh `open` would strand the page the person is watching on the dashboard's
session while your questions went to a page nobody has open. Then run the
skill normally: its Interface question was already answered by being
launched, so start where its real work starts.
session while your questions went to a page nobody has open.
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
> own file-read tool and follow it from the top instead.** Every Plan2Code
> skill below the dashboard ships `disable-model-invocation: true` on
> purpose — it exists to be read and followed inline, not launched as a
> sub-skill — and calling one through a skill-invocation tool errors out and
> strands the hand-off mid-launch.
Its Interface step is already answered by having been launched, so start
where its real work starts.
The menu itself is the page's own list — you never send it. The page knows
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
@@ -829,6 +857,12 @@ know:
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
Post `activity` as each step starts, before its doc or question lands — reading
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
implementation — the same way Review does. A step with no card of its own
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
Finalize".
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
Stopping mid-finalize loses nothing
— the specs are untouched until Step 3's summary write — so a stop's finish
@@ -859,7 +893,7 @@ question or doc lands:
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
merge by `id` (an unknown id is added), and `thread` / `comments` append. Send only
merge by `id` (an unknown id is added), and `thread` appends. Send only
what changed. A whole-file rewrite would put the entire session back into your
context on every turn.
@@ -1239,7 +1273,7 @@ answers were submitted but never picked up.
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` and `comments` **append**: leave out any thread entry you already sent, or the person sees your reply twice. |
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
@@ -48,6 +48,10 @@ export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
// so every session within the hour reuses one lookup.
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
// test run (or a second sandboxed instance) shares one handle directory with
// the real thing, and `stop --all` reaches outside its own world and kills a
@@ -487,9 +491,9 @@ export async function removeSessions(sessionsDir, sids) {
}
// The console folder's own files that no sweep may ever remove: the person's
// looks, the folders remembered per project and spec, and the pointer to
// this console's directory.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
// looks, the folders remembered per project and spec, the pointer to this
// console's directory, and the cached release check.
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir", "update-check.json"]);
function isScratchName(name) {
return (
@@ -536,6 +540,148 @@ export async function removeScratch(consoleDir, names) {
return removed;
}
/* ------------------------------------------------------------- cleanup */
// What User Preferences -> Cleanup never removes. The console folder keeps its
// protected files, its sessions dir (old sessions go one by one, by age) and,
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
// console, the launcher (bin/, launcher.json) and the models the person added.
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
// A stray must sit untouched this long before Cleanup lists it. The same
// folders hold files that live for milliseconds -- a held
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
// rename -- and removing one mid-write loses another session's change.
export const STRAY_GRACE_MS = 60 * 60 * 1000;
// Bytes under `p`, never following a symlink: a link counts as itself.
async function diskBytes(p) {
let st;
try {
st = await fs.promises.lstat(p);
} catch {
return 0;
}
if (!st.isDirectory()) return st.size;
let entries;
try {
entries = await fs.promises.readdir(p);
} catch {
return 0;
}
let total = 0;
for (const name of entries) total += await diskBytes(path.join(p, name));
return total;
}
// The newest mtime of anything under `p`, never following a symlink. A folder
// counts by its files, since rewriting a file never touches its folder's
// mtime; an empty folder counts by its own. Anything unreadable on the way
// down answers Infinity, so it reads as just touched and stays.
function newestMtime(p) {
let st;
try {
st = fs.lstatSync(p);
} catch {
return Infinity;
}
if (!st.isDirectory()) return st.mtimeMs;
let entries;
try {
entries = fs.readdirSync(p);
} catch {
return Infinity;
}
if (!entries.length) return st.mtimeMs;
let newest = 0;
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
return newest;
}
function entryKind(entry) {
if (entry.isSymbolicLink()) return "link";
return entry.isDirectory() ? "folder" : "file";
}
function strayEntries(dir, kept, where, now) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch {
return [];
}
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
return entries
.filter((e) => !kept.has(e.name))
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
.filter((e) => settled(e.path));
}
/**
* Everything Cleanup would remove, worked out on the server and never taken
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
* `open` sweeps by, plus every file in the folder that old, so a resumed
* session or a saved draft keeps it), anything at the top of the console folder that is
* not kept, and -- only when the console runs from its default home inside
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
* touched within `STRAY_GRACE_MS` are left for a later scan. A
* console running from another home (tests, dev) never reaches ~/.plan2code.
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
*/
export async function cleanupFindings({
consoleDir = HOME_DIR,
plan2codeDir = PLAN2CODE_DIR,
now = Date.now(),
maxAgeMs = SESSION_MAX_AGE_MS,
skipSid,
} = {}) {
const found = [];
const sessionsDir = path.join(consoleDir, "sessions");
for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) {
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
}
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
}
const items = [];
let bytes = 0;
for (const f of found) {
const size = await diskBytes(f.path);
bytes += size;
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
}
return { items, bytes };
}
/**
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
* worked out afresh first and only ids on it are touched, so a name from the
* page is never a path, and anything that stopped qualifying since the scan
* (a session touched again) stays. A link is unlinked, never followed.
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
*/
export async function removeCleanup(ids, opts = {}) {
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
const { items } = await cleanupFindings(opts);
const removed = [];
const failed = [];
let bytes = 0;
for (const item of items) {
if (!wanted.has(item.id)) continue;
try {
if (item.kind === "link") await fs.promises.unlink(item.path);
else await fs.promises.rm(item.path, { recursive: true, force: true });
removed.push(item.id);
bytes += item.bytes;
} catch {
failed.push(item.id);
}
}
return { removed, bytes, failed };
}
/**
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
* the file's realpath must sit inside the root's, so `../`, an absolute path
@@ -871,7 +1017,7 @@ export function handOff(child, pre) {
/* ----------------------------------------------------------- patch merge */
const APPEND_KEYS = new Set(["thread", "comments"]);
const APPEND_KEYS = new Set(["thread"]);
function isPlainObject(v) {
return v !== null && typeof v === "object" && !Array.isArray(v);
@@ -896,7 +1042,7 @@ function mergeOne(target, patch, where) {
}
// Merge a keyed collection: a known id merges one level, an unknown id appends.
// Named fields are replaced whole; thread/comments append.
// Named fields are replaced whole; thread appends.
function mergeKeyed(current, patchList, idKey, defaults, where) {
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
for (const entry of patchList) {
@@ -955,6 +1101,42 @@ function dropStaleSubmissions(currentItems, before, patchList) {
return merged;
}
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
// borrow the shape of the replies and doc blocks they also write, so `from` /
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
// at all is refused. The person's own notes are recorded by the server when
// they send, so an agent that echoes one back is not shown it twice.
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
function normalizeThreads(patchList, currentItems) {
return patchList.map((entry) => {
if (!isPlainObject(entry) || entry.thread == null) return entry;
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
const said = new Set(
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
);
const thread = [];
for (const m of entry.thread) {
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
guard(m, "thread");
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
if (!key) {
throw new Error(
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
);
}
const { from, role, md, body, content, ...rest } = m;
const who = (m.who || from || role) === "user" ? "user" : "agent";
const text = m[key];
if (who === "user" && said.has(text.trim())) continue;
thread.push({ ...rest, who, text });
}
return { ...entry, thread };
});
}
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
// Blocks merge by id like docs do, so a patch that only settles a block's
@@ -996,7 +1178,7 @@ export function applyPatch(state, patch) {
break;
case "items":
if (!Array.isArray(v)) throw new Error('"items" must be an array');
next.items = dropStaleSubmissions(next.items, state.items, v);
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
break;
case "topics":
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
@@ -1048,15 +1230,11 @@ function stampTimes(before, next) {
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
}
for (const list of [next.items, next.docs]) {
if (!Array.isArray(list)) continue;
for (const entry of list) {
if (Array.isArray(next.items)) {
for (const entry of next.items) {
if (Array.isArray(entry.thread)) {
for (const m of entry.thread) if (!m.at) m.at = now;
}
if (Array.isArray(entry.comments)) {
for (const m of entry.comments) if (!m.at) m.at = now;
}
}
}
if (Array.isArray(next.docs)) {
@@ -1289,7 +1467,10 @@ 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, sentNote, ...rest }) => rest);
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
...rest,
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
}));
const prose =
JSON.stringify(authored) +
JSON.stringify(state.docs || []) +
@@ -65,7 +65,7 @@ export function submittedAwaiting(item) {
if (!s || typeof s !== "object") return null;
if (item.answer && typeof item.answer === "object") return null;
const thread = Array.isArray(item.thread) ? item.thread : [];
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
return replied ? null : s;
}
@@ -74,17 +74,33 @@ export function submittedAwaiting(item) {
* 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.
* Any agent message from the send onwards, or one with no clock to compare,
* means it has been picked up. The person's own entries never count: the
* server writes their note into the thread as it arrives.
*/
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));
const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at));
return picked ? null : n;
}
/**
* Who said a thread entry and what they said. The contract is `{ who, text }`
* and the server lifts anything else into it, but sessions written before that
* hold `{ from, md }` replies, which would otherwise draw as empty bubbles.
*/
export function threadWho(m) {
return m && (m.who || m.from || m.role) === "user" ? "user" : "agent";
}
export function threadText(m) {
if (!m) return "";
for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k];
return "";
}
/* -------------------------------------------------------------- labels */
export function optionLabel(item, k) {
@@ -23,6 +23,9 @@
--warn-soft: #fbe7e3;
--focus: #1f6feb;
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
/* A soft accent halo for the things that want noticing: the update banner
and an enabled Send. Built from --accent, so a picked accent glows too. */
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
@@ -61,6 +64,7 @@
--warn-soft: #34201d;
--focus: #6aa3ff;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
}
}
@@ -85,6 +89,7 @@
--warn-soft: #34201d;
--focus: #6aa3ff;
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
}
* { box-sizing: border-box; }
@@ -1097,10 +1102,11 @@ h1 {
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
the tiny ring, left of the label. */
.view-tab .tab-spin {
the tiny ring, left of the label. The extra .spinner is for specificity:
.spinner.tiny comes later and zeroes the margin otherwise. */
.view-tab .spinner.tab-spin {
display: inline-block;
margin-right: 6px;
margin-right: 7px;
vertical-align: -1px;
}
@@ -1657,11 +1663,13 @@ input[type="text"].invalid { border-color: var(--warn); }
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
/* Send breathes while there is something to send: a soft accent ring that
spreads and fades. Off under reduced motion, below. */
/* Send glows and breathes while there is something to send: the steady
--glow, plus a soft accent ring that spreads and fades. The ring is off
under reduced motion, below; the glow stays. */
#btn-send:not(:disabled) { box-shadow: var(--glow); }
@keyframes send-pulse {
0% { box-shadow: 0 0 0 0 var(--accent-line); }
100% { box-shadow: 0 0 0 6px transparent; }
0% { box-shadow: var(--glow), 0 0 0 0 var(--accent-line); }
100% { box-shadow: var(--glow), 0 0 0 6px transparent; }
}
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
@@ -2219,6 +2227,7 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
.modal.help[open] { display: flex; }
.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-version a { color: inherit; }
.help-layout {
display: grid;
@@ -2668,6 +2677,74 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
border-left-width: 4px;
color: var(--ink);
}
/* A newer release: the same slot, in the accent, with the label as the way
into the update modal and a small × that hides it for this session. */
.dash-nudge.update-banner {
position: relative;
padding-left: 40px;
padding-right: 40px;
border-left-width: 4px;
border-left-color: var(--accent-line);
color: var(--ink);
box-shadow: var(--glow);
}
.update-banner-open {
flex: 1 1 16em;
padding: 0;
border: 0;
background: none;
color: inherit;
font: inherit;
font-weight: 600;
letter-spacing: 0.02em;
text-align: center;
cursor: pointer;
}
.update-banner-open:hover { text-decoration: underline; }
/* Pinned to the right edge, out of the flow, so the label centres on the
whole banner rather than on what the × leaves of it. */
.update-banner-dismiss {
position: absolute;
top: 50%;
right: 10px;
transform: translateY(-50%);
padding: 0 6px;
border: 0;
border-radius: var(--radius);
background: none;
color: inherit;
font: inherit;
font-size: 16px;
line-height: 1;
cursor: pointer;
}
.update-banner-dismiss:hover { background: var(--accent-line); }
/* Wide enough that the update command sits on one line beside Copy; a
narrow window still wraps it rather than overflowing. */
#update-modal { max-width: 720px; }
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
.update-steps li { margin: 4px 0; }
/* The hand-off copy row, in the modal's first step: the command and its Copy
side by side. */
.update-command {
margin: 6px 0 4px;
display: flex;
align-items: stretch;
gap: 10px;
flex-wrap: wrap;
}
.update-command code {
flex: 1 1 260px;
min-width: 0;
font: 13px/1.5 var(--mono);
color: var(--ink);
background: var(--panel);
border: 1px solid var(--rule-2);
border-radius: 8px;
padding: 10px 12px;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
.dash-working {
@@ -3394,6 +3471,18 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.models-actions .help.error { color: var(--danger, #d64545); }
/* User Preferences: Cleanup's list of what would go, shown before anything
is deleted. */
.cleanup-list { display: grid; gap: 4px; max-height: 200px; overflow: auto; font-size: 0.88em; }
.cleanup-list:empty { display: none; }
.cleanup-summary { margin: 0 0 2px; font-weight: 600; }
.cleanup-row { display: flex; justify-content: space-between; gap: 12px; }
.cleanup-row span:first-child { min-width: 0; overflow-wrap: anywhere; font-family: var(--mono); }
.cleanup-size { flex: none; color: var(--ink-3); }
.cleanup-more { display: grid; gap: 4px; }
.cleanup-more summary { cursor: pointer; color: var(--ink-2); }
#cleanup-delete[hidden] { display: none; }
/* 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 {
@@ -66,6 +66,8 @@ import {
submittedAwaiting,
noteAwaiting,
suggestionFrom,
threadText,
threadWho,
THUMB_EDGE,
turnGate,
verdictText,
@@ -446,6 +448,10 @@ document.addEventListener("click", (e) => {
const GONE_AFTER_MS = 8000;
// Named so a reconnect can clear only THIS banner: a bare banner(null) would
// wipe an unrelated warning that landed while the page was gone (an upload
// failure, a refused send).
const GONE_BANNER = "Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.";
const WORKING_GRACE_MS = 5 * 60 * 1000;
// Two minutes with the agent mid-turn, three when it is merely meant to be
// listening. The difference is the cost of being wrong: a working agent that
@@ -521,6 +527,9 @@ let chatFrame = null;
// sends them.
let wsFrame = null;
let meterFrame = null;
// The frame's update ({ installed, latest }), present only when a newer
// release is out; null otherwise.
let updateFrame = null;
let chatDot = false;
let chatSending = false;
let chatResetting = false;
@@ -566,7 +575,6 @@ function fresh() {
drafts: {},
images: {},
sent: {},
sentAt: null,
stopping: null,
afterBuild: null,
homeward: null,
@@ -870,10 +878,12 @@ function adopt(body) {
chatFrame = body.chat || null;
if (body.workspace) wsFrame = body.workspace;
if (body.meter) meterFrame = body.meter;
// Always replaced: an absent key means no update.
updateFrame = body.update || null;
lastContact = Date.now();
if (gone) {
gone = false;
banner(null);
if ($("banner").textContent === GONE_BANNER) banner(null);
}
if (firstLoad) {
load();
@@ -1016,7 +1026,9 @@ function adopt(body) {
render();
if ($("workspace-modal").open) renderWorkspace();
tellFolderIssues();
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow) loadOverview();
// The Overview tab's file changes under a build, so a tab you are watching
// refetches on every new frame too, not only on the click that opened it.
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow || view === "overview") loadOverview();
if (announce) showArrival(announce);
// New entries land at the bottom of the rail. Gliding down to them beats
// leaving the list parked where it was while it grew underneath.
@@ -1149,15 +1161,12 @@ function markGone() {
// of the server means there, and a banner promising a reconnect would
// argue with it.
if (!finish() && !stopInProgress()) {
banner(
"Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.",
"warn"
);
banner(GONE_BANNER, "warn");
}
render();
} else if (!bad && gone) {
gone = false;
banner(null);
if ($("banner").textContent === GONE_BANNER) banner(null);
render();
}
}
@@ -1182,7 +1191,6 @@ function connect() {
} catch {}
});
es.addEventListener("submitted", (e) => {
local.sentAt = Date.now();
// Drop only what was actually sent.
//
// This event fires for a send from ANY tab of this session, which is why it
@@ -1799,14 +1807,19 @@ async function sendBrief() {
reply: briefPhrase(choice.range),
}),
});
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
if (!res.ok) throw new Error(String(res.status));
$("brief-modal").close();
banner("Asked for a brief. It will appear as a tab when it is written.", "good");
setTimeout(() => banner(null), 5000);
pendingResult = true;
render();
} catch {
why.textContent = "That did not go through. Try again in a moment.";
} catch (err) {
if (err && err.pending) pendingResult = true;
why.textContent =
err && err.pending
? "Your last answers are still being picked up. Try again in a moment."
: "That did not go through. Try again in a moment.";
} finally {
go.disabled = false;
go.textContent = "Write the brief";
@@ -2515,6 +2528,51 @@ function roleNudge() {
return nudge;
}
// × on the update banner hides it for this console session only, and only
// for the release it named. Blocked storage means "not dismissed".
function updateDismissKey() {
try {
return "p2c-update-dismissed:" + S.sid;
} catch {
return "p2c-update-dismissed:";
}
}
function updateDismissed() {
try {
return sessionStorage.getItem(updateDismissKey()) === updateFrame.latest;
} catch {
return false;
}
}
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
const UPDATE_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
function releasesLink(text) {
const a = el("a", null, text);
a.href = RELEASES_URL;
a.target = "_blank";
a.rel = "noopener noreferrer";
return a;
}
function openUpdateModal() {
if (!updateFrame) return;
const versions = $("update-versions");
versions.replaceChildren(
document.createTextNode("Version "),
releasesLink("v" + updateFrame.latest),
document.createTextNode(" is out — you have "),
el("code", null, updateFrame.installed),
document.createTextNode(".")
);
const row = $("update-command");
const code = el("code", null, UPDATE_COMMAND);
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
$("update-modal").showModal();
}
function renderDashboard(main) {
maybeWake();
const menu = (S && S.menu) || {};
@@ -2526,6 +2584,25 @@ function renderDashboard(main) {
warn.setAttribute("role", "status");
wrap.appendChild(warn);
}
// Built here only, so no other workflow's page ever shows it.
if (updateFrame && !updateDismissed()) {
const notice = el("div", "dash-nudge update-banner");
notice.setAttribute("role", "status");
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + updateFrame.latest);
open.type = "button";
open.addEventListener("click", openUpdateModal);
const dismiss = el("button", "update-banner-dismiss", "×");
dismiss.type = "button";
dismiss.setAttribute("aria-label", "Dismiss until next time");
dismiss.addEventListener("click", () => {
try {
sessionStorage.setItem(updateDismissKey(), updateFrame.latest);
} catch {}
render();
});
notice.append(open, dismiss);
wrap.appendChild(notice);
}
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
if (typeof menu.note === "string" && menu.note.trim()) {
@@ -3223,7 +3300,11 @@ document.addEventListener("keydown", cancelSkipMove, true);
function skipAndMoveOn(id) {
cancelSkipMove();
local.skipFlash = id;
stage(id, { type: "skip", skipped: true });
// A note already typed goes along: skipping the question is not retracting
// the comment. Dropping it would leave the text in the box but out of the
// send, which looks kept and is not.
const cur = local.staged[id];
stage(id, { type: "skip", skipped: true, ...(cur && cur.text ? { text: cur.text } : {}) });
skipTimer = setTimeout(() => {
skipTimer = null;
local.skipFlash = null;
@@ -3340,19 +3421,24 @@ function renderWaiting(main) {
}
pane.appendChild(title);
pane.appendChild(el("p", null, doing));
const ask = "If Plan2Code needs you, the question appears here on its own.";
if (!docs().length) {
pane.appendChild(el("p", null, "If Plan2Code needs you, the question appears here on its own."));
pane.appendChild(el("p", null, ask));
return;
}
// "Task" and the tasks tab's own name both open that tab, so the pointer is
// one click from what it points at. A build posts it as `phase` ("Phase N
// tasks"), a quick task as `tasks`; with neither the words stay plain.
// tasks"), a quick task as `tasks`. A skill with no task list (Document,
// Plan) has nothing live to follow, so it gets no pointer at all.
const list =
docs().find((d) => d.id === "phase") ||
docs().find((d) => d.id === "tasks") ||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
if (!list) {
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
return;
}
const jump = (word) => {
if (!list) return el("strong", "waiting-jump", word);
const b = el("button", "waiting-jump", word);
b.type = "button";
b.addEventListener("click", () => {
@@ -3366,8 +3452,8 @@ function renderWaiting(main) {
"The tabs above fill in as it goes. You can follow along with live ",
jump("Task"),
" updates in the ",
jump((list && list.title) || "Phase tasks"),
" tab. If Plan2Code needs you, the question appears here on its own."
jump(list.title || "Phase tasks"),
" tab. " + ask
);
pane.appendChild(p);
}
@@ -3505,8 +3591,8 @@ function renderSettled(card, item) {
// would misreport which of the two was the answer.
let prose = text;
if (!prose && !lines.length) {
const mine = (item.thread || []).filter((m) => m.who === "user");
if (mine.length) prose = String(mine[mine.length - 1].text || "").trim();
const mine = (item.thread || []).filter((m) => threadWho(m) === "user");
if (mine.length) prose = threadText(mine[mine.length - 1]).trim();
}
const nothing = !lines.length && !prose;
@@ -4322,6 +4408,10 @@ function buildChecklist(card, item, staged) {
const commitList = (change) => {
const cur = local.staged[item.id];
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
// A tick or a state IS the answer, so it ends a skip staged earlier:
// left in place, `skipped` would collapse the reply to "skip" while the
// card showed ticked steps on their way.
delete next.skipped;
const empty = !(next.done && next.done.length) && !next.state && !next.text;
stage(item.id, empty ? null : next);
};
@@ -4371,7 +4461,7 @@ function buildChecklist(card, item, staged) {
function buildMenu(card, item, staged) {
const list = el("ul", "options");
const name = "menu-" + item.id;
for (const o of item.options || []) {
for (const [i, o] of (item.options || []).entries()) {
const picked = staged && staged.k === o.k;
const li = el("li", "option" + (picked ? " is-picked" : ""));
const label = el("label");
@@ -4379,7 +4469,13 @@ function buildMenu(card, item, staged) {
const radio = el("input");
radio.type = "radio";
radio.name = name;
// The same id buildChoice gives its radios: withFocus finds the focused
// input by id after the render this change() sets off, and without one a
// keyboard user arrowing through the menu lands on <body> every time.
radio.id = optionId(item, o, i);
radio.value = o.k;
radio.checked = Boolean(picked);
radio.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
const body = el("div", "option-body");
const head = el("div", "option-label");
@@ -5276,20 +5372,30 @@ function renderAside() {
)
);
}
// A note that has been sent but not yet picked up: marked as waiting, so the
// send is seen to have gone, until the agent replies. The server writes the
// note into the thread as it arrives; a session from before that has only
// `sentNote`, which gets a box of its own below.
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
let waitingShown = false;
for (const m of thread) {
const box = el("div", "msg " + (m.who === "user" ? "you" : ""));
const mine = threadWho(m) === "user";
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
if (pending) waitingShown = true;
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
const who = el("div", "msg-who");
who.appendChild(el("span", null, m.who === "user" ? "You" : "Plan2Code"));
if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
box.appendChild(who);
box.appendChild(md(m.text, "md"));
const text = threadText(m);
if (text) box.appendChild(md(text, "md"));
const tray = mine ? sentAttachments(m) : null;
if (tray) box.appendChild(tray);
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) {
if (waiting && !waitingShown) {
const box = el("div", "msg you pending");
const who = el("div", "msg-who");
who.appendChild(el("span", null, "You"));
@@ -5589,7 +5695,10 @@ async function attachFiles(itemId, files) {
const taken = wanted.slice(0, room);
// One banner at a time, so every refusal goes into it, each by name.
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
if (taken.length < wanted.length) said.push(chat ? "Up to 5 attachments per question." : "Up to 5 attachments per note.");
if (taken.length < wanted.length)
said.push(
chat ? `Up to ${CHAT_MAX_ATTACHMENTS} attachments per question.` : `Up to ${MAX_ATTACHMENTS} attachments per note.`
);
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
await Promise.all(
taken.map(async (file) => {
@@ -6439,6 +6548,10 @@ async function goHome() {
$("home-modal").close();
} catch (err) {
$("home-modal").close();
// The server is holding an uncollected result: Send, Home and Stop all
// need to read as busy until the frame or the ping says otherwise, same
// as send() and sendAfterBuild() do on a 409.
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
@@ -6499,6 +6612,7 @@ async function stopSession() {
stoppingHidden = false;
} catch (err) {
$("stop-modal").close();
if (err && err.pending) pendingResult = true;
banner(
err && err.pending
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
@@ -6653,7 +6767,6 @@ function markSent({ sentIds, sentNotes = {}, summaries, values }) {
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
}
local.staged = {};
local.sentAt = Date.now();
save();
}
@@ -6706,7 +6819,7 @@ const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", d
// something the agent never hears.
function tokenFor(item, v) {
const map = item.token || {};
if (v.skipped) return "skip";
if (v.skipped) return v.text ? `skip; ${v.text}` : "skip";
const parts = [];
if (v.k) parts.push(map[v.k] || v.k);
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
@@ -6938,14 +7051,14 @@ function renderAbout() {
let helpBuilt = false;
async function renderHelpVersion() {
const el = $("help-version");
const slot = $("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;
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
slot.hidden = !version;
} catch {
el.hidden = true;
slot.hidden = true;
}
}
@@ -7053,6 +7166,7 @@ function openHelpOn(id) {
}
$("btn-home").addEventListener("click", openHomeConfirm);
$("update-done").addEventListener("click", () => $("update-modal").close());
$("home-cancel").addEventListener("click", () => $("home-modal").close());
$("home-go").addEventListener("click", goHome);
$("btn-stop").addEventListener("click", openStopConfirm);
@@ -7132,6 +7246,7 @@ $("btn-looks").addEventListener("click", () => {
});
$("looks-done").addEventListener("click", () => $("looks-modal").close());
$("looks-modal").addEventListener("close", () => {
resetCleanup();
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
});
$("looks-reset").addEventListener("click", () => {
@@ -7278,6 +7393,111 @@ $("models-reset").addEventListener("click", () => {
renderModels();
});
// Cleanup: the server works out what in ~/.plan2code is not needed and
// shows it first; Delete these sends back only the ids it was shown, and the
// server re-checks every one before removing it.
let cleanupFound = null;
// Bumped by every scan, delete and reset: a response from an older one is
// dropped, so a scan still in flight when Preferences closes cannot refill it.
let cleanupGen = 0;
const CLEANUP_SHOWN = 8;
function setCleanupStatus(text, isError) {
const status = $("cleanup-status");
status.textContent = text;
status.classList.toggle("error", Boolean(isError));
}
function cleanupLabel(item) {
if (item.where === "session") return "Session " + item.name;
const where = item.where === "root" ? "~/.plan2code/" : "~/.plan2code/console/";
return where + item.name + (item.kind === "folder" ? "/" : "");
}
function cleanupSummary(items, bytes) {
const sessions = items.filter((i) => i.where === "session").length;
const strays = items.length - sessions;
const parts = [];
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
return parts.join(", ") + " · " + formatBytes(bytes);
}
function resetCleanup() {
cleanupGen++;
cleanupFound = null;
$("cleanup-list").replaceChildren();
$("cleanup-delete").hidden = true;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
setCleanupStatus("", false);
}
function renderCleanup() {
const list = $("cleanup-list");
list.replaceChildren();
const items = (cleanupFound && cleanupFound.items) || [];
$("cleanup-delete").hidden = !items.length;
if (!items.length) return;
const rows = (some) => some.map((item) => {
const row = el("div", "cleanup-row");
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", formatBytes(item.bytes)));
return row;
});
list.append(el("p", "cleanup-summary", cleanupSummary(items, cleanupFound.bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
if (items.length > CLEANUP_SHOWN) {
const more = el("details", "cleanup-more");
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
list.appendChild(more);
}
}
async function scanCleanup() {
const gen = ++cleanupGen;
$("cleanup-scan").disabled = true;
$("cleanup-delete").disabled = true;
setCleanupStatus("Looking…", false);
const { status, body } = await postJson("/cleanup", { scan: true });
if (gen !== cleanupGen) return;
$("cleanup-scan").disabled = false;
$("cleanup-delete").disabled = false;
if (status !== 200 || !body.ok) {
cleanupFound = null;
renderCleanup();
return setCleanupStatus(status ? body.error || "Could not look." : "Plan2Code isn't reachable.", true);
}
cleanupFound = { items: body.items || [], bytes: body.bytes || 0 };
renderCleanup();
// Left in the status line, not cleared: it is the live region, so this is
// what a screen reader hears when the scan finishes.
const found = cleanupFound.items.length;
setCleanupStatus(found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.", false);
}
async function deleteCleanup() {
if (!cleanupFound || !cleanupFound.items.length) return;
const gen = ++cleanupGen;
$("cleanup-delete").disabled = true;
$("cleanup-scan").disabled = true;
setCleanupStatus("Deleting…", false);
const { status, body } = await postJson("/cleanup", { delete: cleanupFound.items.map((i) => i.id) });
if (gen !== cleanupGen) return;
$("cleanup-delete").disabled = false;
$("cleanup-scan").disabled = false;
if (status !== 200 || !body.ok) {
return setCleanupStatus(status ? body.error || "Could not delete." : "Plan2Code isn't reachable.", true);
}
const removed = (body.removed || []).length;
const failed = (body.failed || []).length;
cleanupFound = null;
renderCleanup();
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
setCleanupStatus(failed ? done + " " + failed + " could not be removed." : done, Boolean(failed));
}
$("cleanup-scan").addEventListener("click", scanCleanup);
$("cleanup-delete").addEventListener("click", deleteCleanup);
$("btn-brief").addEventListener("click", openBrief);
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
$("brief-go").addEventListener("click", sendBrief);
Loaded 100 of 180 files, more files were not shown because too many files have changed in this diff. Show more