diff --git a/.agents-docs/AGENTS-architecture-console.md b/.agents-docs/AGENTS-architecture-console.md index 0f22494..e71c6fd 100644 --- a/.agents-docs/AGENTS-architecture-console.md +++ b/.agents-docs/AGENTS-architecture-console.md @@ -17,6 +17,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web | `in-app.mjs` | the desktop app's signal to `open`: `inAppSignal()` reads `PLAN2CODE_IN_APP`, `PLAN2CODE_CONSOLE_SID`, `PLAN2CODE_APP_ANNOUNCE` and `PLAN2CODE_APP_TOKEN`; `announcePage()` POSTs the page to that window's loopback endpoint. Under the app `open` never starts a browser, resumes the app's session and announces the page; with the variables unset nothing here runs. Imported by `cmd-open.mjs` | | `open-link.mjs` | the desktop app's webview opens no new windows, so the page there sends links off the console (`linkLeavesPage()` in `public/app-bridge.js`: http or https on another origin, caught in `wireChrome()`) to `POST /open-link`. `linkToOpen()` takes http and https only (400 otherwise); `openLink()` starts the default browser with the link as one argument, never through a shell (`rundll32 url.dll,FileProtocolHandler` on Windows, `open` on macOS, `$BROWSER` or `xdg-open` elsewhere) and skips it under `PLAN2CODE_NO_BROWSER`. When that fails the page shows the link with a Copy button to paste into a browser | | `loop-setup.mjs` | the Implementation Loop's setup, remembered per project in `~/.plan2code/console/loop-setup.json` (one entry per folded project folder, schema 1): defaults, validation and the read and write the `/loop-setup` route uses. The app reads the same file itself for the quick check, so the page never carries that command | +| `spec-carry.mjs` | the spec a desktop app's New Session carries to the fresh dashboard: one short-lived `~/.plan2code/console/spec-carry.json` (`{project, spec, at}`), written by `restart_brief::leave_spec` in the app from the old session's `specDir` (or, from a dashboard, its picker's `specSel` in the draft), taken once by `POST /spec-carry` (`takeSpecCarry`: same folded project, under ten minutes old, one folder under `specs/`) and used by `loadSpecCarry()` in `selectors.js` only when the new picker lists that spec | | `cmd-post-wait.mjs` | `post` and `wait`: publish a patch, then collect what the person sent | | `cmd-small.mjs` | the small commands: keep, forget, delete-spec, handoff, delete-handoff, status and stop; `handoff new` refuses an unknown `--workflow` the same way `open` does | | `files.mjs` | where the console's files live, how they are written safely, and the argument parser both command lines share | @@ -43,5 +44,5 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web | `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. The `plan2code` launcher reads the same cache for its terminal release notice (a copy of this module sits in `~/.plan2code/bin/`) | | `console.md` | the core of the agent-facing contract, read once per conversation (every skill ships the same copy, so a dashboard hop never re-reads it): starting, the turn (`post --wait`, the exit codes, handling a send, `settle`), posting, the payload and its kinds, documents (including `file` blocks), the house rules, and an index of the topic files below with the moment each is read. A test caps it at 24,000 characters | | `console-finish.md` · `console-stop.md` · `console-chat.md` · `console-workspace.md` · `console-subagents.md` · `console-launches.md` · `console-meter.md` · `console-attachments.md` · `console-trouble.md` | topic files, each read only when its moment first comes: finishing (the finish and its buttons), stop requests (the way home mid-workflow, `stopWarning`, resuming a pause), Quick questions, the Workspace, standing instructions and helper reports, dashboard launches and the menu payload, the session meter's `run` events (read only when a `run` is refused: the notes inline every `run`), keeping a cited note attachment, and recovery | -| `notes/.md` | per-workflow notes (`init` for both inits, `pathfinder` with Briefs, `plan`, `revise-plan`, `document`, `implement` for both builds, `loop` for a build the desktop app's Implementation Loop runs with `--loop` (where it reports a `loopOutcome` instead of asking for sign-off), `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`, `xray`, `diagnose`, `pr-prep`, `test`). Each skill's Interface line reads `/console.md` and its own notes file right after `open`; a test checks every skill names one that exists | +| `notes/.md` | per-workflow notes (`init` for both inits, `pathfinder` with Briefs, `plan`, `revise-plan`, `document`, `implement` for both builds, `loop` for a build the desktop app's Implementation Loop runs with `--loop` (where it reports a `loopOutcome` instead of asking for sign-off), `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`, `xray`, `diagnose`, `pr-prep`, `test`, `dead-code`). Each skill's Interface line reads `/console.md` and its own notes file right after `open`; a test checks every skill names one that exists | | `building.md` · `building-review.md` | the build half of the contract, for `implement`, `implement-review` and `quick-task`: progress posts (`agent.activity`, `agent.quietMinutes`, `file` blocks re-read with `refresh`), the chat check between tasks, questions mid-build and stop requests; `building-review.md` is the review run on the page (the sign-off's `review` verdict, **Review it now**, Implement + Review's Stage 2, Finalize's Step 2.5), read only when asked for | diff --git a/plan2code-app/src-tauri/src/main.rs b/plan2code-app/src-tauri/src/main.rs index 088d9fb..cd5212e 100644 --- a/plan2code-app/src-tauri/src/main.rs +++ b/plan2code-app/src-tauri/src/main.rs @@ -265,6 +265,9 @@ fn before_fresh_hook(state: &AppState) -> BeforeFresh { .lock() .ok() .and_then(|guard| guard.as_ref().map(|sup| sup.session().sid.clone())); + if let (Some(sid), Some(home)) = (sid.as_deref(), session_reader::console_home()) { + restart_brief::leave_spec(&home, sid, chrono::Utc::now().timestamp_millis()); + } let note = sid.and_then(|sid| restart_brief::note_for_restart(&sid)); if let Ok(guard) = announce.lock() { if let Some(server) = guard.as_ref() { diff --git a/plan2code-app/src-tauri/src/restart_brief.rs b/plan2code-app/src-tauri/src/restart_brief.rs index a191128..04a60c9 100644 --- a/plan2code-app/src-tauri/src/restart_brief.rs +++ b/plan2code-app/src-tauri/src/restart_brief.rs @@ -65,6 +65,39 @@ pub fn leave_brief( handoff::write(handoffs, when, &record, &body).map(Some) } +/// The spec session `sid` was on, if the fresh dashboard's picker can offer +/// it: a skill's `specDir`, or, from the dashboard itself, the spec its picker +/// had selected (the page's draft keeps it as `specSel`). +pub fn spec_in(console_home: &Path, sid: &str) -> Option { + let session = session_reader::load(console_home, sid).ok()?; + let spec = if text(&session.state, "workflow") == Some("dashboard") { + let draft = std::fs::read_to_string(session.dir.join("draft.json")).ok()?; + let draft: Value = serde_json::from_str(&draft).ok()?; + text(&draft, "specSel")?.to_string() + } else { + text(&session.state, "specDir")?.to_string() + }; + valid_spec(&spec).then_some(spec) +} + +/// Leave the spec session `sid` was on for the next dashboard in the same +/// folder (the web console's `spec-carry.mjs` reads and removes it). A hint +/// only: nothing here fails a Restart, a failed write loses the preselection. +pub fn leave_spec(console_home: &Path, sid: &str, now_ms: i64) { + let Some(spec) = spec_in(console_home, sid) else { + return; + }; + let Ok(session) = session_reader::load(console_home, sid) else { + return; + }; + let Some(worktree) = text(&session.state, "worktree") else { + return; + }; + let entry = serde_json::json!({ "project": worktree, "spec": spec, "at": now_ms }); + let _ = std::fs::create_dir_all(console_home); + let _ = std::fs::write(console_home.join("spec-carry.json"), entry.to_string()); +} + /// The bar's line for a Restart on session `sid`, written to the real console /// and handoff folders. `None` when there was nothing to leave. pub fn note_for_restart(sid: &str) -> Option { @@ -199,6 +232,44 @@ mod tests { assert!(doc.contains("Phase 5: Restart brief: 4 of 11 done.")); } + fn carried(home: &Path) -> Option { + let text = fs::read_to_string(home.join("spec-carry.json")).ok()?; + serde_json::from_str(&text).ok() + } + + #[test] + fn a_skill_session_carries_its_spec_to_the_next_dashboard() { + let (home, project, _) = session("carry-skill", "implement", Some("specs/feature")); + leave_spec(&home, "s1", 1234); + let entry = carried(&home).expect("a carry file"); + assert_eq!(entry["spec"], "specs/feature"); + assert_eq!(entry["project"], project.to_string_lossy().as_ref()); + assert_eq!(entry["at"], 1234); + } + + #[test] + fn a_dashboard_session_carries_the_spec_its_picker_had() { + let (home, _, _) = session("carry-dash", "dashboard", None); + let draft = home.join("sessions").join("s1").join("draft.json"); + fs::write(&draft, r#"{"specSel":"specs/other"}"#).unwrap(); + leave_spec(&home, "s1", 1); + assert_eq!(carried(&home).unwrap()["spec"], "specs/other"); + // Start from scratch, a handoff pick and an untouched picker carry nothing. + for body in [r#"{"specSel":null}"#, r#"{"specSel":"handoff:x"}"#, "{}"] { + let _ = fs::remove_file(home.join("spec-carry.json")); + fs::write(&draft, body).unwrap(); + leave_spec(&home, "s1", 1); + assert!(carried(&home).is_none(), "{body}"); + } + } + + #[test] + fn a_session_with_no_spec_carries_nothing() { + let (home, _, _) = session("carry-none", "quick-task", None); + leave_spec(&home, "s1", 1); + assert!(carried(&home).is_none()); + } + #[test] fn a_dashboard_session_leaves_nothing() { let (home, _, handoffs) = session("dashboard", "dashboard", None); diff --git a/scripts/test-spec-carry-page.mjs b/scripts/test-spec-carry-page.mjs new file mode 100644 index 0000000..aa1796a --- /dev/null +++ b/scripts/test-spec-carry-page.mjs @@ -0,0 +1,57 @@ +// The page side of the spec an app's New Session carries: loadSpecCarry() in selectors.js. +import assert from "node:assert/strict"; +import test from "node:test"; + +import { page } from "../src/web-console/public/state.js"; +import { loadSpecCarry } from "../src/web-console/public/selectors.js"; + +const specs = [ + { dir: "specs/a", name: "a", state: "building" }, + { dir: "specs/b", name: "b", state: "planned" }, +]; + +// loadSpecCarry asks once per page, so each case is a fresh module copy. +async function fresh() { + return (await import(`../src/web-console/public/selectors.js?${Math.random()}`)).loadSpecCarry; +} + +function setup({ spec, sel } = {}) { + page.S = { workflow: "dashboard", scan: { specs } }; + page.local = sel === undefined ? {} : { specSel: sel }; + globalThis.localStorage = { setItem() {}, getItem: () => null, removeItem() {} }; + const calls = []; + globalThis.fetch = async (url, init) => { + calls.push([url, init && init.method]); + return { status: 200, json: async () => ({ spec }) }; + }; + return calls; +} + +test("a carried spec the picker lists becomes the pick", async () => { + setup({ spec: "specs/b" }); + await (await fresh())(); + assert.equal(page.local.specSel, "specs/b"); +}); + +test("a carried spec the picker does not list leaves the default", async () => { + setup({ spec: "specs/gone" }); + await (await fresh())(); + assert.equal("specSel" in page.local, false); +}); + +test("a pick the person already made is never replaced, or even asked about", async () => { + const calls = setup({ spec: "specs/b", sel: null }); + await (await fresh())(); + assert.equal(page.local.specSel, null); + assert.equal(calls.length, 0); +}); + +test("it asks once per page", async () => { + const calls = setup({ spec: undefined }); + const load = await fresh(); + await load(); + await load(); + assert.equal(calls.length, 1); + assert.deepEqual(calls[0], ["/spec-carry", "POST"]); + assert.equal(typeof loadSpecCarry, "function"); +}); diff --git a/scripts/test-spec-carry.mjs b/scripts/test-spec-carry.mjs new file mode 100644 index 0000000..d80fe86 --- /dev/null +++ b/scripts/test-spec-carry.mjs @@ -0,0 +1,46 @@ +// The spec an app's New Session carries to the fresh dashboard (spec-carry.mjs). +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import test from "node:test"; + +import { takeSpecCarry, SPEC_CARRY_MAX_AGE_MS } from "../src/web-console/spec-carry.mjs"; + +const dir = fs.mkdtempSync(path.join(os.tmpdir(), "spec-carry-")); +const file = path.join(dir, "spec-carry.json"); +const put = (entry) => fs.writeFileSync(file, JSON.stringify(entry)); +const NOW = 1_000_000_000; + +test("a fresh hint for this folder is taken once", () => { + put({ project: dir, spec: "specs/feature", at: NOW }); + assert.equal(takeSpecCarry(dir, NOW + 1000, file), "specs/feature"); + assert.equal(fs.existsSync(file), false); + assert.equal(takeSpecCarry(dir, NOW + 1000, file), null); +}); + +test("a stale hint is dropped, not used", () => { + put({ project: dir, spec: "specs/feature", at: NOW }); + assert.equal(takeSpecCarry(dir, NOW + SPEC_CARRY_MAX_AGE_MS + 1, file), null); + assert.equal(fs.existsSync(file), false); +}); + +test("another folder's fresh hint stays for its own dashboard", () => { + put({ project: path.join(dir, "elsewhere"), spec: "specs/feature", at: NOW }); + assert.equal(takeSpecCarry(dir, NOW, file), null); + assert.equal(fs.existsSync(file), true); +}); + +test("a spec that is not directly under specs/ is refused", () => { + for (const spec of ["../x", "specs/a/b", "specs/.hidden", "other", 5]) { + put({ project: dir, spec, at: NOW }); + assert.equal(takeSpecCarry(dir, NOW, file), null, String(spec)); + } +}); + +test("no file, or a broken one, is no hint", () => { + fs.rmSync(file, { force: true }); + assert.equal(takeSpecCarry(dir, NOW, file), null); + fs.writeFileSync(file, "{nope"); + assert.equal(takeSpecCarry(dir, NOW, file), null); +}); diff --git a/scripts/test-web-console-server.mjs b/scripts/test-web-console-server.mjs index 0801d02..a74e12c 100644 --- a/scripts/test-web-console-server.mjs +++ b/scripts/test-web-console-server.mjs @@ -365,6 +365,7 @@ test("the scratch sweep removes old patches and helpers, never looks, the pointe file("looks.json"), file("workspaces.json"), file("loop-setup.json"), + file("spec-carry.json"), file("loop-reports.json"), file("subagents.json"), file("pr-hosts.json"), @@ -381,7 +382,7 @@ 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", "loop-setup.json", "loop-reports.json", "subagents.json", "pr-hosts.json", "../p.json", "console-dir", "update-check.json"])).sort(), + (await removeScratch(dir, [...stale, "looks.json", "workspaces.json", "loop-setup.json", "loop-reports.json", "subagents.json", "spec-carry.json", "pr-hosts.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); @@ -392,6 +393,7 @@ test("the scratch sweep removes old patches and helpers, never looks, the pointe "loop-reports.json", "loop-setup.json", "pr-hosts.json", + "spec-carry.json", "subagents.json", "update-check.json", "workspaces.json", diff --git a/scripts/test-web-console-shape.mjs b/scripts/test-web-console-shape.mjs index 50430c7..7db5c49 100644 --- a/scripts/test-web-console-shape.mjs +++ b/scripts/test-web-console-shape.mjs @@ -193,7 +193,7 @@ const ROUTE_ORDER = [ "/notepad", "/notepad/text", "/notepad/image", "/notepad/thumb", "/notepad/image/delete", "/notepad/tab", "/notepad/tab/rename", "/notepad/tab/delete", "/notepad/tab/order", "/notepad/tab/last", "/notepad/tab/sent", "/notepad/images/", "/attachments/", "/shots/", "/uploads/", "/submit", "/open-link", "/chat", "/chat/decision", "/workspace", - "WORKSPACE_EDITS", "/workspace/scope", "/workspace/browse", "/loop-setup", "/loop-setup", "/cancel", "/ping", "/bye", + "WORKSPACE_EDITS", "/workspace/scope", "/workspace/browse", "/loop-setup", "/loop-setup", "/spec-carry", "/cancel", "/ping", "/bye", ]; test("shape: routes.mjs lists every URL the server answers, in order", () => { diff --git a/src/web-console/public/index.html b/src/web-console/public/index.html index 41cfdbf..b6b426e 100644 --- a/src/web-console/public/index.html +++ b/src/web-console/public/index.html @@ -145,6 +145,9 @@ + +
@@ -436,6 +439,13 @@ + + + + + + + @@ -901,6 +911,35 @@ + +