diff --git a/CHANGELOG.md b/CHANGELOG.md index a7b3ab6..bca78bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -50,6 +50,7 @@ All notable changes to Plan2Code will be documented in this file. ### šŸ› Fixed +- **custom agents**: on Windows, a custom agent whose installer added its folder to the user PATH is now offered by `plan2code` and the desktop app every time, not only from a terminal opened after the install. Both read the saved PATH as well as the one they inherited, and the agent starts with it too. - **web console**: on the dashboard, canceling one spec's Delete and quickly opening another's no longer leaves **Delete it** doing nothing; the first dialog's late close cleared the second dialog's spec. - **web console**: a handoff's **Copy** button keeps showing **Copied** (or **Copy was refused**) when the dashboard redraws while the clipboard answers, instead of the word landing on a button that was already replaced. - **web console**: a finished screen's press (**Commit it now**, **Update CHANGELOG first**, **Back to the dashboard**, **Continue here**, a review) that nothing picks up, because the agent's turn ended while the screen waited, no longer says "Opening Changelog…" forever. After a minute of silence the line beside Planny says Plan2Code is not running and the choice is saved, with **continue** to type in the terminal (a button that types it there, under the app). diff --git a/plan2code-app/src-tauri/src/node_check.rs b/plan2code-app/src-tauri/src/node_check.rs index 289acfe..403d5cf 100644 --- a/plan2code-app/src-tauri/src/node_check.rs +++ b/plan2code-app/src-tauri/src/node_check.rs @@ -113,17 +113,26 @@ fn build_path(fresh: bool) -> String { if let Some(login) = login_shell_path() { parts.push(login); } - // At start this process's PATH already is the saved one; only a refresh - // needs to read it again. + // This process's PATH is whatever its parent had, which is stale when + // that parent (a terminal, the launcher) started before an installer + // added a folder: a custom agent was then offered only some of the time. + // A refresh puts the saved PATH first; at start it only fills in after + // the inherited one, so that keeps its order. + #[cfg(windows)] + let saved = saved_windows_path(); #[cfg(windows)] if fresh { - parts.extend(saved_windows_path()); + parts.extend(saved.clone()); } #[cfg(not(windows))] let _ = fresh; if !inherited.is_empty() { parts.push(inherited); } + #[cfg(windows)] + if !fresh { + parts.extend(saved); + } parts.join(if cfg!(windows) { ";" } else { ":" }) } diff --git a/scripts/test-launcher.mjs b/scripts/test-launcher.mjs index fe2d4ca..d552427 100644 --- a/scripts/test-launcher.mjs +++ b/scripts/test-launcher.mjs @@ -92,7 +92,7 @@ function sandbox(clis, { installed, project = true } = {}) { cwd: dir, input: "", encoding: "utf8", - env: { ...process.env, PATH: bin, HOME: home, USERPROFILE: home, PLAN2CODE_CONSOLE_HOME: consoleHome, ...env }, + env: { ...process.env, PATH: bin, PLAN2CODE_NO_SAVED_PATH: "1", HOME: home, USERPROFILE: home, PLAN2CODE_CONSOLE_HOME: consoleHome, ...env }, }), argsOf: (cli) => { const file = path.join(bin, `${cli}.json`); @@ -419,6 +419,41 @@ test("launcher: compareVersions orders X.Y.Z numerically and refuses anything el assert.equal(compareVersions("v1.0.0", "1.0.0"), null); }); +test("launcher: parseRegQueryValue reads REG_SZ and REG_EXPAND_SZ, and expandPercentVars fills in names", () => { + const { parseRegQueryValue, expandPercentVars } = require(LAUNCHER); + const out = "\r\nHKEY_CURRENT_USER\\Environment\r\n Path REG_EXPAND_SZ %USERPROFILE%\\.pi\\agent\\bin;C:\\Tools\r\n\r\n"; + assert.equal(parseRegQueryValue(out), "%USERPROFILE%\\.pi\\agent\\bin;C:\\Tools"); + assert.equal(parseRegQueryValue(" Path REG_SZ C:\\A\r\n"), "C:\\A"); + assert.equal(parseRegQueryValue("ERROR: The system was unable to find the specified registry key or value.\r\n"), null); + assert.equal(expandPercentVars("%userprofile%\\x;%NOPE%\\y", { USERPROFILE: "C:\\Users\\me" }), "C:\\Users\\me\\x;%NOPE%\\y"); +}); + +// A terminal opened before an agent's installer added its folder keeps the old PATH: the +// launcher reads the saved one too, so a custom agent is offered in every terminal. +test("launcher: on Windows the saved user PATH fills in folders the inherited PATH lacks", { skip: !IS_WINDOWS }, (t) => { + const { addSavedWindowsPath, parseRegQueryValue, expandPercentVars } = require(LAUNCHER); + const reg = spawnSync(path.join(process.env.SystemRoot, "System32", "reg.exe"), ["query", "HKCU\\Environment", "/v", "Path"], { encoding: "utf8" }); + const saved = parseRegQueryValue(reg.stdout); + if (!saved) return t.skip("no user PATH saved in the registry"); + const first = expandPercentVars(saved).split(";").find(Boolean); + const pathKey = Object.keys(process.env).find((key) => key.toUpperCase() === "PATH"); + const before = { PATH: process.env[pathKey], NO: process.env.PLAN2CODE_NO_SAVED_PATH }; + t.after(() => { + process.env[pathKey] = before.PATH; + if (before.NO === undefined) delete process.env.PLAN2CODE_NO_SAVED_PATH; + else process.env.PLAN2CODE_NO_SAVED_PATH = before.NO; + }); + delete process.env.PLAN2CODE_NO_SAVED_PATH; + process.env[pathKey] = "C:\\stale-terminal-path"; + addSavedWindowsPath(); + const dirs = process.env[pathKey].split(";"); + assert.equal(dirs[0], "C:\\stale-terminal-path", "the inherited PATH keeps its place in front"); + assert.ok(dirs.includes(first), `${first} is added from the saved PATH`); + const length = dirs.length; + addSavedWindowsPath(); + assert.equal(process.env[pathKey].split(";").length, length, "a second call adds nothing twice"); +}); + test("launcher: renderBanner draws Planny and the name, colored only through paint", () => { const { renderBanner, paint } = require(LAUNCHER); const plain = renderBanner(paint(false)); diff --git a/src/launcher/plan2code.js b/src/launcher/plan2code.js index 83d0e95..00f1940 100644 --- a/src/launcher/plan2code.js +++ b/src/launcher/plan2code.js @@ -547,6 +547,60 @@ public static class Plan2CodeFolderPicker { } `; +/** + * The value from `reg query /v ` output: the text after the REG_SZ or + * REG_EXPAND_SZ column on its line, or null. + */ +function parseRegQueryValue(output) { + for (const line of String(output || '').split(/\r?\n/)) { + const match = /\sREG_(?:EXPAND_)?SZ\s+(.*)$/.exec(line); + if (match && match[1].trim()) return match[1].trim(); + } + return null; +} + +/** `%NAME%` replaced from `env` (case-insensitive, as Windows reads it); an unknown name stays as written. */ +function expandPercentVars(text, env = process.env) { + const lookup = (name) => { + const key = Object.keys(env).find((k) => k.toUpperCase() === name.toUpperCase()); + return key === undefined ? undefined : env[key]; + }; + return text.replace(/%([^%]+)%/g, (whole, name) => lookup(name) ?? whole); +} + +/** + * Windows only: add to this process's PATH the folders of the system then the user PATH as saved + * in the registry (what a newly opened terminal gets) that it does not have yet. A terminal opened + * before an agent's installer added its folder keeps the old PATH, so the agent was offered in + * some terminals and not others. Changing process.env also hands the folders to the agent. + */ +function addSavedWindowsPath() { + // The launcher tests run with a PATH of stand-ins only, which the saved PATH must not widen. + if (!IS_WINDOWS || process.env.PLAN2CODE_NO_SAVED_PATH) return; + const reg = path.join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'reg.exe'); + const pathKey = Object.keys(process.env).find((key) => key.toUpperCase() === 'PATH') || 'PATH'; + const dirs = (process.env[pathKey] || '').split(path.delimiter).filter(Boolean); + const known = new Set(dirs.map((dir) => path.resolve(dir.replace(/^"|"$/g, '')).toLowerCase())); + const added = []; + for (const key of ['HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment', 'HKCU\\Environment']) { + let out; + try { + out = spawnSync(reg, ['query', key, '/v', 'Path'], { encoding: 'utf8', windowsHide: true, timeout: 5000 }); + } catch { + continue; + } + const value = parseRegQueryValue(out && out.stdout); + if (!value) continue; + for (const dir of expandPercentVars(value).split(path.delimiter).filter(Boolean)) { + const id = path.resolve(dir.replace(/^"|"$/g, '')).toLowerCase(); + if (known.has(id)) continue; + known.add(id); + added.push(dir); + } + } + if (added.length) process.env[pathKey] = [...dirs, ...added].join(path.delimiter); +} + /** * Resolve a command on PATH the way the shell would, including PATHEXT on Windows. * Returns the full path, or null when it is not installed. @@ -670,6 +724,7 @@ function runnableClis(customs) { * exit code) after printing why none can be used. */ async function chooseCli(requested) { + addSavedWindowsPath(); const customs = customClis(); const all = [...CLIS, ...customs]; const { installed, missing } = runnableClis(customs); @@ -1222,4 +1277,4 @@ async function launch() { // Run only when invoked directly; requiring the file (the tests do) is load-only. if (require.main === module) launch(); -module.exports = { normalizeAgents, buildArgs, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject }; +module.exports = { normalizeAgents, buildArgs, parseRegQueryValue, expandPercentVars, addSavedWindowsPath, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject };