mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-17 20:51:19 -08:00
Install and update from release tags so people never get unfinished work from main
AI Assisted
This commit is contained in:
1 parent
347831475d
commit
c07e679105
12 files changed
+2400
-519
No files matched your search
@@ -19,11 +19,12 @@ function read(file) {
|
||||
// or the end of its container (HTML).
|
||||
function blockOf(file) {
|
||||
const text = read(file);
|
||||
const start = text.search(/^#{2,3} Before you start$|<h3>Before you start<\/h3>/m);
|
||||
const start = text.search(/^#{2,3} Before you start$|<h3>Before you start<\/h3>|<summary>Before you start<\/summary>/m);
|
||||
assert.ok(start >= 0, `${file} has no "Before you start" block`);
|
||||
const rest = text.slice(start);
|
||||
const body = rest.indexOf('\n') + 1;
|
||||
const next = file.endsWith('.html') ? rest.indexOf('</div>') : rest.slice(body).search(/^#{1,3} /m);
|
||||
const closers = ['</details>', '</div>'].map((tag) => rest.indexOf(tag)).filter((i) => i > 0);
|
||||
const next = file.endsWith('.html') ? Math.min(...closers) : rest.slice(body).search(/^#{1,3} /m);
|
||||
const end = file.endsWith('.html') ? next : next < 0 ? -1 : body + next;
|
||||
return end > 0 ? rest.slice(0, end) : rest;
|
||||
}
|
||||
@@ -40,11 +41,30 @@ for (const file of DOCS) {
|
||||
});
|
||||
|
||||
if (!WITH_INSTALL.has(file)) continue;
|
||||
test(`${file} puts the guidance before the install command`, () => {
|
||||
// The command leads (README's "See it" picture, the site's hero); the guidance follows in a
|
||||
// block of its own, and the line beside the command names the two requirements.
|
||||
test(`${file} leads with the install command and names what it needs`, () => {
|
||||
const text = read(file);
|
||||
const guide = text.indexOf('Before you start');
|
||||
const install = text.indexOf('npx --allow-git');
|
||||
assert.ok(guide >= 0 && install >= 0 && guide < install, `${file}: "Before you start" must come before the npx line`);
|
||||
assert.ok(install >= 0 && text.includes('Before you start'), `${file} is missing the install command or "Before you start"`);
|
||||
if (file === 'README.md') {
|
||||
const first = text.split('\n').slice(0, 60).join('\n');
|
||||
assert.ok(first.includes('**Plan it. Approve it. Let it build.**'), 'README.md: the tagline must open it');
|
||||
assert.ok(first.includes('npx --allow-git'), 'README.md: the install command must be in its first 60 lines, under "See it"');
|
||||
assert.ok(first.indexOf('## See it') >= 0 && first.indexOf('## See it') < first.indexOf('npx --allow-git'), 'README.md: the install command must sit under "See it"');
|
||||
assert.ok(first.includes('Needs Node.js 18+ and Git'), 'README.md: the first lines must name Node.js and Git');
|
||||
}
|
||||
if (file === 'docs/index.html') {
|
||||
assert.ok(install < text.indexOf('id="install"'), 'docs/index.html: the command must also be in the hero, before #install');
|
||||
assert.ok(text.includes('Needs Node 18+ and Git'), 'docs/index.html: #install must say what it needs in one line');
|
||||
}
|
||||
});
|
||||
|
||||
test(`${file} installs from the release branch, never from main`, () => {
|
||||
const text = read(file);
|
||||
const commands = text.match(/npx --allow-git=all git\+https:\/\/github\.com\/jparkerweb\/plan2code\.git\S*/g) || [];
|
||||
assert.ok(commands.length > 0, `${file} has no install command`);
|
||||
for (const command of commands) assert.match(command, /\.git#release(?![\w.-])/, `${file}: ${command} must end in #release`);
|
||||
});
|
||||
|
||||
test(`${file} says what a silent install means and how to see why`, () => {
|
||||
|
||||
+674
-21
@@ -104,11 +104,12 @@ test("update: with no record it says so and updates the skills and the plan2code
|
||||
const fake = fakeSteps();
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 0, out);
|
||||
assert.match(out, new RegExp(`No install record found \\(installed before v${VERSION.replace(/\./g, "\\.")}\\); updating the skills and the plan2code command\\.`));
|
||||
assert.match(out, /No install record found; updating the skills and the plan2code command\./);
|
||||
assert.doesNotMatch(out, /installed before v/);
|
||||
// install() covers the command with the skills, so the launcher step does not run again.
|
||||
assert.deepEqual(fake.ran(), ["skills"]);
|
||||
assert.match(out, /skills: updated/);
|
||||
assert.match(out, /launcher: updated/);
|
||||
assert.match(out, /Skills: updated/);
|
||||
assert.match(out, /plan2code command: updated/);
|
||||
});
|
||||
|
||||
test("update: a partial record runs only the listed pieces, in order, unattended", async () => {
|
||||
@@ -119,7 +120,7 @@ test("update: a partial record runs only the listed pieces, in order, unattended
|
||||
assert.deepEqual(fake.ran(), ["statusline", "bot"]);
|
||||
for (const call of fake.calls) assert.equal(call.options.unattended, true, call.piece);
|
||||
assert.doesNotMatch(out, /No install record/);
|
||||
assert.doesNotMatch(out, /skills:/);
|
||||
assert.doesNotMatch(out, /Skills:/);
|
||||
});
|
||||
|
||||
test("update: a failing piece exits 1 naming it, and the others still run", async () => {
|
||||
@@ -128,10 +129,10 @@ test("update: a failing piece exits 1 naming it, and the others still run", asyn
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 1, out);
|
||||
assert.deepEqual(fake.ran(), ["skills", "statusline", "metrics", "bot"]);
|
||||
assert.match(out, /statusline: failed: /);
|
||||
assert.match(out, /metrics: failed: npm exploded/);
|
||||
assert.match(out, /bot: updated/);
|
||||
assert.match(out, /Update failed for: statusline, metrics/);
|
||||
assert.match(out, /Status line: failed: /);
|
||||
assert.match(out, /Metrics: failed: npm exploded/);
|
||||
assert.match(out, /Bot: updated/);
|
||||
assert.match(out, /Update failed for: Status line, Metrics/);
|
||||
});
|
||||
|
||||
test("update: when the skills install leaves the command out, the launcher step runs on its own", async () => {
|
||||
@@ -141,8 +142,8 @@ test("update: when the skills install leaves the command out, the launcher step
|
||||
assert.equal(code, 0, out);
|
||||
assert.deepEqual(fake.ran(), ["skills", "launcher"]);
|
||||
// install() returned 1 for the command alone: the skills still read as updated.
|
||||
assert.match(out, /skills: updated/);
|
||||
assert.match(out, /launcher: updated/);
|
||||
assert.match(out, /Skills: updated/);
|
||||
assert.match(out, /plan2code command: updated/);
|
||||
});
|
||||
|
||||
test("update: a command that fails on the retry is the only piece named", async () => {
|
||||
@@ -150,8 +151,165 @@ test("update: a command that fails on the retry is the only piece named", async
|
||||
const fake = fakeSteps({ launcherWithSkills: false, codes: { launcher: 1 } });
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 1, out);
|
||||
assert.match(out, /skills: updated/);
|
||||
assert.match(out, /Update failed for: launcher\b/);
|
||||
assert.match(out, /Skills: updated/);
|
||||
assert.match(out, /Update failed for: plan2code command\b/);
|
||||
// A failed update says how to go back (the record's old version here).
|
||||
assert.match(out, /To go back to a release, run: plan2code update --tag v1\.0\.0/);
|
||||
});
|
||||
|
||||
test("update: prints the version change, one line per piece by name, the release notes link and the restart hint", async () => {
|
||||
writeRecord(["skills", "launcher", "app", "statusline"]);
|
||||
const fake = fakeSteps();
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 0, out);
|
||||
assert.match(out, new RegExp(`^Updating 1\\.0\\.0 -> ${VERSION.replace(/\./g, "\\.")}$`, "m"));
|
||||
// The compact summary: human names only, never the internal piece names.
|
||||
assert.match(out, /Skills: updated/);
|
||||
assert.match(out, /plan2code command: updated/);
|
||||
assert.match(out, /Desktop app: updated/);
|
||||
assert.match(out, /Status line: updated/);
|
||||
assert.doesNotMatch(out, /[✓✗] (skills|launcher|statusline|app|metrics|bot): /);
|
||||
assert.equal((out.match(/Update summary/g) || []).length, 1, "one summary");
|
||||
assert.match(out, new RegExp(`^What's new: https://github\\.com/jparkerweb/plan2code/releases/tag/v${VERSION.replace(/\./g, "\\.")}$`, "m"));
|
||||
assert.match(out, /Close any open Plan2Code console or app and start `plan2code` again\./);
|
||||
assert.doesNotMatch(out, /Happy coding|PARAMETERS|To go back to a release/);
|
||||
});
|
||||
|
||||
test("update: already on the new version it says so and stops, until --force", async () => {
|
||||
fs.mkdirSync(path.dirname(RECORD), { recursive: true });
|
||||
fs.writeFileSync(RECORD, JSON.stringify({ version: VERSION, scope: "global", pieces: ["skills", "launcher"] }));
|
||||
const idle = fakeSteps();
|
||||
const stopped = await runUpdate(idle.steps);
|
||||
assert.equal(stopped.code, 0, stopped.out);
|
||||
assert.match(stopped.out, new RegExp(`Already on ${VERSION.replace(/\./g, "\\.")}`));
|
||||
assert.match(stopped.out, /plan2code update --force/);
|
||||
assert.deepEqual(idle.ran(), [], "nothing was reinstalled");
|
||||
assert.doesNotMatch(stopped.out, /Update summary/);
|
||||
|
||||
const forced = fakeSteps();
|
||||
const lines = [];
|
||||
const log = console.log;
|
||||
console.log = (...args) => lines.push(args.join(" "));
|
||||
let code;
|
||||
try {
|
||||
code = await installer.update({ steps: forced.steps, cleanShims: () => {}, force: true });
|
||||
} finally {
|
||||
console.log = log;
|
||||
}
|
||||
const out = lines.join("\n").replace(/\x1b\[[0-9;]*m/g, "");
|
||||
assert.equal(code, 0, out);
|
||||
assert.deepEqual(forced.ran(), ["skills"]);
|
||||
assert.match(out, new RegExp(`Updating ${VERSION.replace(/\./g, "\\.")} -> ${VERSION.replace(/\./g, "\\.")}`));
|
||||
});
|
||||
|
||||
test("update: a step's own output stays out of the summary, except its warnings and its failures", async () => {
|
||||
writeRecord(["skills", "statusline", "bot"]);
|
||||
const fake = fakeSteps();
|
||||
fake.steps.skills = async (options) => {
|
||||
console.log("Installing skills");
|
||||
console.log(" ✓ Built 23 skills from src/");
|
||||
console.log(" ! heads up from the skills step");
|
||||
options.outcome.skills = true;
|
||||
options.outcome.launcher = true;
|
||||
return 0;
|
||||
};
|
||||
fake.steps.statusline = async () => {
|
||||
console.log(" ✗ could not write settings.json");
|
||||
return 1;
|
||||
};
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 1, out);
|
||||
assert.doesNotMatch(out, /Installing skills|Built 23 skills/);
|
||||
assert.match(out, /! heads up from the skills step/);
|
||||
assert.match(out, /✗ could not write settings\.json/);
|
||||
});
|
||||
|
||||
test("update: a failed update puts the old version back in the record, so a retry runs instead of stopping at Already on", async () => {
|
||||
writeRecord(["skills", "launcher"]);
|
||||
const fake = fakeSteps({ codes: { skills: 1 } });
|
||||
// As the real launcher step: it works, and recording it stamps the version being installed.
|
||||
fake.steps.launcher = async () => {
|
||||
installer.recordInstalled("launcher");
|
||||
return 0;
|
||||
};
|
||||
const failed = await runUpdate(fake.steps);
|
||||
assert.equal(failed.code, 1, failed.out);
|
||||
assert.match(failed.out, /To try again, run: plan2code update/);
|
||||
assert.match(failed.out, /To go back to a release, run: plan2code update --tag v1\.0\.0/);
|
||||
assert.equal(installer.readInstallRecord().version, "1.0.0", "the record stays on the old version");
|
||||
assert.deepEqual(installer.readInstallRecord().pieces, ["launcher", "skills"], "and keeps every piece");
|
||||
|
||||
const retry = await runUpdate(fakeSteps().steps);
|
||||
assert.equal(retry.code, 0, retry.out);
|
||||
assert.doesNotMatch(retry.out, /Already on/);
|
||||
assert.match(retry.out, /Plan2Code is up to date/);
|
||||
});
|
||||
|
||||
test("update: an app kept because the release has no app file yet leaves the old version on the record, so the next update fetches it", async () => {
|
||||
writeRecord(["skills", "launcher", "app"]);
|
||||
const fake = fakeSteps();
|
||||
fake.steps.app = async (options) => {
|
||||
installer.recordInstalled("app");
|
||||
options.outcome.appMissing = true;
|
||||
return 0;
|
||||
};
|
||||
const kept = await runUpdate(fake.steps);
|
||||
assert.equal(kept.code, 0, kept.out);
|
||||
assert.match(kept.out, /Desktop app: kept \(no new desktop app file yet\)/);
|
||||
assert.equal(installer.readInstallRecord().version, "1.0.0", "the record stays on the old version");
|
||||
|
||||
const next = await runUpdate(fakeSteps().steps);
|
||||
assert.equal(next.code, 0, next.out);
|
||||
assert.doesNotMatch(next.out, /Already on/);
|
||||
assert.match(next.out, /Desktop app: updated/);
|
||||
});
|
||||
|
||||
test("update: a failed desktop app install inside the skills step is shown, and does not fail the update", async () => {
|
||||
writeRecord(["skills", "launcher"]);
|
||||
const fake = fakeSteps();
|
||||
fake.steps.skills = async (options) => {
|
||||
console.log(" Built 23 skills from src/");
|
||||
console.log(" ✗ The desktop app was not installed: the download did not match its checksum.");
|
||||
options.outcome.skills = true;
|
||||
options.outcome.launcher = true;
|
||||
options.outcome.app = false;
|
||||
return 0;
|
||||
};
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 0, out);
|
||||
assert.match(out, /✗ The desktop app was not installed: the download did not match its checksum\./);
|
||||
assert.doesNotMatch(out, /Built 23 skills/);
|
||||
});
|
||||
|
||||
test("update: the app's size is in its summary line when the skills step brought it in", async () => {
|
||||
writeRecord(["skills", "launcher"]);
|
||||
const fake = fakeSteps();
|
||||
fake.steps.skills = async (options) => {
|
||||
options.outcome.skills = true;
|
||||
options.outcome.launcher = true;
|
||||
options.outcome.app = true;
|
||||
options.outcome.appSize = 3 * 1024 * 1024;
|
||||
return 0;
|
||||
};
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 0, out);
|
||||
assert.match(out, /Desktop app: updated \(3\.0 MB\)/);
|
||||
});
|
||||
|
||||
test("uninstall: printKeptData names the folder and lists each entry with its size", async () => {
|
||||
const data = path.join(HOME, ".plan2code");
|
||||
fs.mkdirSync(path.join(data, "handoffs"), { recursive: true });
|
||||
fs.writeFileSync(path.join(data, "handoffs", "h.md"), "y".repeat(3000));
|
||||
const { out } = await captured(() => installer.printKeptData());
|
||||
assert.match(out, /Your data in .* was kept/);
|
||||
assert.match(out, /Handoffs: 3 KB/);
|
||||
fs.rmSync(path.join(data, "handoffs"), { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("install.js --update: an option other than --force is refused", () => {
|
||||
const refused = spawnSync(process.execPath, [INSTALL, "--update", "--nope"], { encoding: "utf8", env: { ...process.env, HOME, USERPROFILE: HOME } });
|
||||
assert.equal(refused.status, 1);
|
||||
assert.match(refused.stderr, /Unknown option\(s\): --update --nope/);
|
||||
});
|
||||
|
||||
test("update: the real status line step keeps a custom statusLine without asking", async () => {
|
||||
@@ -186,7 +344,7 @@ test("update: every step is an install function, never an uninstall", () => {
|
||||
test("install.js: --update and --uninstall are in the usage line, and an unknown option still exits 1", () => {
|
||||
const result = spawnSync(process.execPath, [INSTALL, "--bogus"], { encoding: "utf8" });
|
||||
assert.equal(result.status, 1);
|
||||
assert.ok(result.stderr.includes("Usage: node install.js [--build-skills | --verify-skills | --update | --uninstall [--yes] [--purge]]"), result.stderr);
|
||||
assert.ok(result.stderr.includes("Usage: node install.js [--build-skills | --verify-skills | --update [--force] | --uninstall [--yes] [--purge]]"), result.stderr);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
@@ -207,7 +365,8 @@ async function releaseServer(files) {
|
||||
const name = decodeURIComponent(req.url.slice(1));
|
||||
hits.push(name);
|
||||
if (name in files) {
|
||||
res.writeHead(200);
|
||||
// As GitHub does, the size is sent, so the download can show it.
|
||||
res.writeHead(200, { "Content-Length": Buffer.byteLength(files[name]) });
|
||||
res.end(files[name]);
|
||||
} else {
|
||||
res.writeHead(404);
|
||||
@@ -282,7 +441,10 @@ test("app installed: the file is downloaded, verified, placed and recorded", { s
|
||||
assert.deepEqual(fs.readFileSync(installer.APP_DEST), bytes);
|
||||
assert.deepEqual(installer.readInstallRecord().pieces, ["app", "launcher", "skills"]);
|
||||
assert.deepEqual(fs.readdirSync(APP_DIR), [path.basename(installer.APP_DEST)], "no temp or .old file is left");
|
||||
assert.match(out, /unsigned/);
|
||||
assert.match(out, /Downloading the desktop app \(1 KB\)\.\.\./, "piped: the size, on one plain line");
|
||||
assert.match(out, /not code-signed/);
|
||||
assert.ok(out.includes(`Installed: ${installer.APP_DEST}`), out);
|
||||
assert.ok(out.includes(installer.APP_GUIDE_URL), out);
|
||||
assert.deepEqual(server.hits, [`release/${SUMS}`, `release/${ASSET}`]);
|
||||
} finally {
|
||||
server.close();
|
||||
@@ -353,7 +515,7 @@ test("app update: plan2code update replaces an older app and reports it", { skip
|
||||
// The real app step, in the real update loop; the record lists only the app.
|
||||
const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS, cleanShims: () => {} }));
|
||||
assert.equal(result, 0, out);
|
||||
assert.match(out, /app: updated/);
|
||||
assert.match(out, /Desktop app: updated/);
|
||||
assert.deepEqual(fs.readFileSync(installer.APP_DEST), bytes);
|
||||
assert.deepEqual(fs.readdirSync(APP_DIR), [path.basename(installer.APP_DEST)]);
|
||||
} finally {
|
||||
@@ -368,7 +530,7 @@ test("app update: a checksum mismatch fails the update naming the app, nothing e
|
||||
try {
|
||||
const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS, cleanShims: () => {} }));
|
||||
assert.equal(result, 1);
|
||||
assert.match(out, /Update failed for: app/);
|
||||
assert.match(out, /Update failed for: Desktop app/);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
@@ -384,7 +546,7 @@ test("app update: a release with no app file yet keeps the installed app and doe
|
||||
try {
|
||||
const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS, cleanShims: () => {} }));
|
||||
assert.equal(result, 0, out);
|
||||
assert.match(out, /app: kept/);
|
||||
assert.match(out, /Desktop app: kept/);
|
||||
assert.doesNotMatch(out, /Update failed/);
|
||||
assert.equal(fs.readFileSync(installer.APP_DEST, "utf8"), "the installed app");
|
||||
} finally {
|
||||
@@ -621,6 +783,8 @@ async function runUninstall(options, answers = []) {
|
||||
},
|
||||
remove: () => (calls.push("remove"), 0),
|
||||
purgeIt: () => (calls.push("purge"), 0),
|
||||
purgeWebview: () => (calls.push("webview"), 0),
|
||||
running: () => false,
|
||||
...options,
|
||||
});
|
||||
return { code, asked, calls, out: lines.join("\n").replace(/\x1b\[[0-9;]*m/g, "") };
|
||||
@@ -648,7 +812,7 @@ test("uninstall: a yes removes everything, then asks about the data and keeps it
|
||||
|
||||
test("uninstall: a yes to the data question purges it", async () => {
|
||||
const r = await runUninstall({}, [true, true]);
|
||||
assert.deepEqual(r.calls, ["remove", "purge"]);
|
||||
assert.deepEqual(r.calls, ["remove", "purge", "webview"]);
|
||||
});
|
||||
|
||||
test("uninstall: --yes skips both questions and keeps the data", async () => {
|
||||
@@ -660,13 +824,13 @@ test("uninstall: --yes skips both questions and keeps the data", async () => {
|
||||
test("uninstall: --yes --purge deletes the data without a question", async () => {
|
||||
const r = await runUninstall({ yes: true, purge: true });
|
||||
assert.deepEqual(r.asked, []);
|
||||
assert.deepEqual(r.calls, ["remove", "purge"]);
|
||||
assert.deepEqual(r.calls, ["remove", "purge", "webview"]);
|
||||
});
|
||||
|
||||
test("uninstall: --purge alone still confirms the uninstall but never asks about the data", async () => {
|
||||
const r = await runUninstall({ purge: true }, [true]);
|
||||
assert.equal(r.asked.length, 1);
|
||||
assert.deepEqual(r.calls, ["remove", "purge"]);
|
||||
assert.deepEqual(r.calls, ["remove", "purge", "webview"]);
|
||||
});
|
||||
|
||||
test("uninstall: a failing removal or purge makes the exit code non-zero", async () => {
|
||||
@@ -702,3 +866,492 @@ test("install.js --uninstall: with no terminal and no --yes it explains, exits 1
|
||||
assert.match(r.stdout, /Run plan2code uninstall --yes/);
|
||||
assert.ok(fs.existsSync(path.join(HOME, ".plan2code")));
|
||||
});
|
||||
|
||||
test("install: the Node guard names the version on Node older than 18", () => {
|
||||
assert.equal(installer.nodeVersionProblem("16.20.2"), "Plan2Code needs Node.js 18 or newer; you have v16.20.2. Get it from nodejs.org");
|
||||
assert.equal(installer.nodeVersionProblem("17.9.1").startsWith("Plan2Code needs Node.js 18 or newer"), true);
|
||||
assert.equal(installer.nodeVersionProblem("18.0.0"), null);
|
||||
assert.equal(installer.nodeVersionProblem("26.1.0"), null);
|
||||
});
|
||||
|
||||
test("install: an old Node fails fast with the guard's sentence before installing anything", () => {
|
||||
const code = `Object.defineProperty(process.versions, "node", { value: "16.20.2" }); require(${JSON.stringify(INSTALL)});`;
|
||||
const result = spawnSync(process.execPath, ["-e", code], { encoding: "utf8", env: { ...process.env, HOME, USERPROFILE: HOME } });
|
||||
assert.equal(result.status, 1);
|
||||
assert.match(result.stderr, /Plan2Code needs Node\.js 18 or newer; you have v16\.20\.2\. Get it from nodejs\.org/);
|
||||
});
|
||||
|
||||
test("uninstall: --purge also removes the app's webview data, and a failure there is non-zero", async () => {
|
||||
assert.equal((await runUninstall({ yes: true, purge: true, purgeWebview: () => 1 })).code, 1);
|
||||
const kept = await runUninstall({ yes: true });
|
||||
assert.deepEqual(kept.calls, ["remove"]);
|
||||
});
|
||||
|
||||
test("uninstall: a running app is named before anything is removed", async () => {
|
||||
const r = await runUninstall({ yes: true, running: () => true });
|
||||
assert.match(r.out, /Plan2Code is running: close it first/);
|
||||
const quiet = await runUninstall({ yes: true });
|
||||
assert.doesNotMatch(quiet.out, /is running/);
|
||||
});
|
||||
|
||||
test("appWebviewDirs: the webview data folder for com.plan2code.desktop on each OS", () => {
|
||||
const home = path.join(path.sep, "h");
|
||||
// The last folder on each OS is the app's config folder, where the window-state file lives.
|
||||
assert.deepEqual(installer.appWebviewDirs({ platform: "win32", home, env: { LOCALAPPDATA: path.join(home, "Local"), APPDATA: path.join(home, "Roaming") } }), [
|
||||
path.join(home, "Local", "com.plan2code.desktop"),
|
||||
path.join(home, "Roaming", "com.plan2code.desktop"),
|
||||
]);
|
||||
assert.deepEqual(installer.appWebviewDirs({ platform: "win32", home, env: {} }), [
|
||||
path.join(home, "AppData", "Local", "com.plan2code.desktop"),
|
||||
path.join(home, "AppData", "Roaming", "com.plan2code.desktop"),
|
||||
]);
|
||||
assert.deepEqual(installer.appWebviewDirs({ platform: "linux", home, env: {} }), [
|
||||
path.join(home, ".local", "share", "com.plan2code.desktop"),
|
||||
path.join(home, ".cache", "com.plan2code.desktop"),
|
||||
path.join(home, ".config", "com.plan2code.desktop"),
|
||||
]);
|
||||
assert.deepEqual(installer.appWebviewDirs({ platform: "linux", home, env: { XDG_DATA_HOME: path.join(home, "d"), XDG_CACHE_HOME: path.join(home, "c"), XDG_CONFIG_HOME: path.join(home, "g") } }), [
|
||||
path.join(home, "d", "com.plan2code.desktop"),
|
||||
path.join(home, "c", "com.plan2code.desktop"),
|
||||
path.join(home, "g", "com.plan2code.desktop"),
|
||||
]);
|
||||
assert.deepEqual(installer.appWebviewDirs({ platform: "darwin", home, env: {} }), [
|
||||
path.join(home, "Library", "WebKit", "com.plan2code.desktop"),
|
||||
path.join(home, "Library", "WebKit", "plan2code-app"),
|
||||
path.join(home, "Library", "Caches", "com.plan2code.desktop"),
|
||||
path.join(home, "Library", "Caches", "plan2code-app"),
|
||||
path.join(home, "Library", "Application Support", "com.plan2code.desktop"),
|
||||
]);
|
||||
});
|
||||
|
||||
test("purgeAppWebview: removes the folders that exist and skips the rest", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-webview-"));
|
||||
const there = path.join(dir, "com.plan2code.desktop");
|
||||
fs.mkdirSync(path.join(there, "EBWebView"), { recursive: true });
|
||||
const log = console.log;
|
||||
console.log = () => {};
|
||||
try {
|
||||
assert.equal(installer.purgeAppWebview([there, path.join(dir, "missing")]), 0);
|
||||
assert.equal(fs.existsSync(there), false);
|
||||
} finally {
|
||||
console.log = log;
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("appRunning: asks tasklist on Windows and pgrep elsewhere by the program's name", () => {
|
||||
const seen = [];
|
||||
const run = (cmd, args) => (seen.push([cmd, ...args]), { status: 0, stdout: cmd === "tasklist" ? "plan2code-app.exe 1234 Console" : "" });
|
||||
assert.equal(installer.appRunning({ platform: "win32", run }), true);
|
||||
assert.equal(installer.appRunning({ platform: "win32", run: () => ({ status: 0, stdout: "INFO: No tasks are running" }) }), false);
|
||||
assert.equal(installer.appRunning({ platform: "linux", run }), true);
|
||||
assert.equal(installer.appRunning({ platform: "darwin", run: () => ({ status: 1 }) }), false);
|
||||
assert.equal(installer.appRunning({ platform: "linux", run: () => { throw new Error("no pgrep"); } }), false);
|
||||
assert.deepEqual(seen[1], ["pgrep", "-x", "plan2code-app"]);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The next steps after an install: on or off PATH, with or without the desktop app.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/** printGettingStarted's output with colors stripped. */
|
||||
async function gettingStarted(options) {
|
||||
const { out } = await captured(() => installer.printGettingStarted({ commandInstalled: true, agents: { found: ["Claude Code"], builtins: [] }, ...options }));
|
||||
return out;
|
||||
}
|
||||
|
||||
const POSIX_BIN = "/home/me/.local/bin";
|
||||
|
||||
test("next steps: on PATH without the app, plan2code opens the agent and no PATH line is printed", async () => {
|
||||
const out = await gettingStarted({ pathMissing: false, appInstalled: false, platform: "linux" });
|
||||
assert.match(out, /plan2code\s+opens your AI agent on the Plan2Code dashboard/);
|
||||
assert.match(out, /page that opens in your browser/);
|
||||
assert.doesNotMatch(out, /not on your PATH|export PATH|open a new terminal/);
|
||||
});
|
||||
|
||||
test("next steps: on PATH with the app, steps 2 and 3 name the Plan2Code app", async () => {
|
||||
const out = await gettingStarted({ pathMissing: false, appInstalled: true, platform: "linux" });
|
||||
assert.match(out, /plan2code\s+opens the Plan2Code app/);
|
||||
assert.match(out, /3\. Pick a card on the dashboard: plan2code opens the Plan2Code app/);
|
||||
assert.doesNotMatch(out, /page that opens in your browser|export PATH/);
|
||||
});
|
||||
|
||||
test("next steps: off PATH without the app, the shell's PATH line, a new terminal and the full path", async () => {
|
||||
const out = await gettingStarted({ pathMissing: true, binDir: POSIX_BIN, appInstalled: false, platform: "linux", shell: "/bin/zsh" });
|
||||
assert.match(out, /export PATH="[^"]*\.local\/bin:\$PATH"' >> ~\/\.zshrc/);
|
||||
assert.match(out, /open a new terminal/);
|
||||
assert.ok(out.includes(`"${POSIX_BIN}/plan2code"`), out);
|
||||
assert.match(out, /opens your AI agent on the Plan2Code dashboard/);
|
||||
});
|
||||
|
||||
test("next steps: off PATH with the app on Windows, the PowerShell line, a new terminal, the .cmd path and the app", async () => {
|
||||
const bin = "C:\\Users\\me\\AppData\\Roaming\\npm";
|
||||
const out = await gettingStarted({ pathMissing: true, binDir: bin, appInstalled: true, platform: "win32" });
|
||||
assert.ok(out.includes(`[Environment]::SetEnvironmentVariable('Path', [Environment]::GetEnvironmentVariable('Path', 'User') + ';${bin}', 'User')`), out);
|
||||
assert.match(out, /open a new terminal/);
|
||||
assert.ok(out.includes(`& "${bin}\\plan2code.cmd"`), out);
|
||||
assert.match(out, /opens the Plan2Code app/);
|
||||
});
|
||||
|
||||
test("pathFixLine: bash and other shells get ~/.bashrc, a folder under home is written with $HOME", () => {
|
||||
const fix = installer.pathFixLine("/home/me/.local/bin", { platform: "linux", shell: "/bin/bash", home: "/home/me" });
|
||||
assert.equal(fix.file, "~/.bashrc");
|
||||
assert.equal(fix.line, `echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc`);
|
||||
assert.equal(installer.pathFixLine("/home/me/.local/bin", { platform: "darwin", shell: "/bin/zsh", home: "/home/me" }).file, "~/.zshrc");
|
||||
assert.equal(installer.pathFixLine("/opt/bin", { platform: "linux", shell: "/bin/bash", home: "/home/me" }).line, `echo 'export PATH="/opt/bin:$PATH"' >> ~/.bashrc`);
|
||||
});
|
||||
|
||||
test("next steps: with no agent found, plan2code's setup page is the lead and custom agents go to User Preferences", async () => {
|
||||
const builtins = [{ name: "Claude Code", installUrl: "https://example.test/claude", install: { linux: [{ run: "curl -fsSL https://example.test/install.sh | bash" }] } }];
|
||||
const out = await gettingStarted({ agents: { found: [], builtins }, platform: "linux" });
|
||||
assert.match(out, /No agent yet\? Just run plan2code: its setup page installs one with you\./);
|
||||
assert.ok(out.includes("curl -fsSL https://example.test/install.sh | bash (https://example.test/claude)"), out);
|
||||
assert.match(out, /User Preferences, Agents & models/);
|
||||
assert.doesNotMatch(out, /NO AI AGENT FOUND|agents\.json/);
|
||||
});
|
||||
|
||||
test("detectAgents: reads the shipped list and lookup, and finds a custom agent by its command", async () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-agents-"));
|
||||
try {
|
||||
const userFile = path.join(dir, "user-agents.json");
|
||||
fs.writeFileSync(userFile, JSON.stringify({ schema: 1, agents: [{ id: "mine", name: "Mine", command: process.execPath }] }));
|
||||
const nowhere = { path: "", savedPath: "", npmBin: "", home: dir, vars: {} };
|
||||
const result = await installer.detectAgents({ binDir: dir, userAgentsFile: userFile, env: nowhere });
|
||||
assert.ok(result.builtins.some((entry) => entry.id === "claude"), "falls back to src/ when nothing is installed");
|
||||
assert.deepEqual(result.found, ["Mine"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("desktopAppState: installed, failed, or skipped when declined, not offered or not built yet", () => {
|
||||
assert.equal(installer.desktopAppState({ app: true }), "installed");
|
||||
assert.equal(installer.desktopAppState({ app: false }), "failed");
|
||||
assert.equal(installer.desktopAppState({ app: false, appMissing: "no file yet" }), "skipped");
|
||||
assert.equal(installer.desktopAppState({}), "skipped");
|
||||
});
|
||||
|
||||
test("launcher shim: a plan2code without the launcher marker is saved as .bak, ours is replaced in place", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-shim-"));
|
||||
const foreign = "#!/bin/sh\necho another tool\n";
|
||||
try {
|
||||
const file = path.join(dir, "plan2code");
|
||||
const shim = { file, content: `#!/bin/sh\n# ${installer.LAUNCHER_MARKER}\nexit 0\n` };
|
||||
fs.writeFileSync(file, foreign);
|
||||
assert.equal(installer.isOurLauncherShim(file), false);
|
||||
assert.deepEqual(installer.writeLauncherShim(shim), { backup: `${file}.bak` });
|
||||
assert.equal(fs.readFileSync(`${file}.bak`, "utf8"), foreign);
|
||||
assert.equal(installer.isOurLauncherShim(file), true);
|
||||
assert.deepEqual(installer.writeLauncherShim(shim), { backup: null }, "our own shim is never backed up");
|
||||
assert.equal(fs.readFileSync(`${file}.bak`, "utf8"), foreign);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("install.js: with no terminal the menu is not shown; it says how to install and exits 1", () => {
|
||||
const r = spawnSync(process.execPath, [INSTALL], { encoding: "utf8", input: "", env: { ...process.env, HOME, USERPROFILE: HOME } });
|
||||
assert.equal(r.status, 1, r.stdout + r.stderr);
|
||||
assert.equal(r.stdout.trim(), installer.NO_TERMINAL_MESSAGE);
|
||||
assert.equal(installer.NO_TERMINAL_MESSAGE, "Run this in a terminal, or use `--update` for an unattended install.");
|
||||
});
|
||||
|
||||
test("install.js: piped output carries no escape codes and no boxes", () => {
|
||||
const code = `require(${JSON.stringify(INSTALL)}).printGettingStarted({ commandInstalled: true, agents: { found: [], builtins: [] } })`;
|
||||
const piped = spawnSync(process.execPath, ["-e", code], { encoding: "utf8", env: { ...process.env, HOME, USERPROFILE: HOME } });
|
||||
assert.equal(piped.status, 0, piped.stderr);
|
||||
assert.match(piped.stdout, /How to use Plan2Code/);
|
||||
assert.doesNotMatch(piped.stdout, /\x1b\[|╭|╰/);
|
||||
});
|
||||
|
||||
test("createSpinner: piped, it prints its label once as a plain line and draws nothing", () => {
|
||||
const writes = [];
|
||||
const lines = [];
|
||||
const log = console.log;
|
||||
console.log = (...args) => lines.push(args.join(" "));
|
||||
try {
|
||||
const spinner = installer.createSpinner("Running skills add...", { stream: { isTTY: false, write: (s) => writes.push(s) } }).start();
|
||||
spinner.stop();
|
||||
} finally {
|
||||
console.log = log;
|
||||
}
|
||||
assert.deepEqual(lines, [" Running skills add..."]);
|
||||
assert.deepEqual(writes, []);
|
||||
});
|
||||
|
||||
test("createSpinner: on a terminal it redraws one line with the seconds and clears it on stop", () => {
|
||||
const writes = [];
|
||||
const spinner = installer.createSpinner("Running skills add...", { stream: { isTTY: true, write: (s) => writes.push(s) } }).start();
|
||||
spinner.stop();
|
||||
assert.match(writes[0], /^\r {2}\S+ Running skills add\.\.\. 0s/);
|
||||
assert.equal(writes.at(-1), "\r\x1b[K");
|
||||
});
|
||||
|
||||
test("detectAgents: an agent only in npm's folder or an install folder off PATH is not present, as the launcher sees it", async () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-agents-off-"));
|
||||
try {
|
||||
for (const name of ["claude", "claude.cmd"]) fs.writeFileSync(path.join(dir, name), "");
|
||||
if (process.platform !== "win32") fs.chmodSync(path.join(dir, "claude"), 0o755);
|
||||
const none = path.join(dir, "none.json");
|
||||
const off = { path: "", savedPath: "", npmBin: dir, home: dir, pathext: ".CMD", vars: {} };
|
||||
assert.deepEqual((await installer.detectAgents({ binDir: dir, userAgentsFile: none, env: off })).found, []);
|
||||
const on = { ...off, npmBin: "", path: dir };
|
||||
assert.deepEqual((await installer.detectAgents({ binDir: dir, userAgentsFile: none, env: on })).found, ["Claude Code"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("detectAgents: a custom agents file with the wrong schema is ignored, as the launcher ignores it", async () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-agents-schema-"));
|
||||
try {
|
||||
const userFile = path.join(dir, "user-agents.json");
|
||||
fs.writeFileSync(userFile, JSON.stringify({ schema: 99, agents: [{ id: "mine", name: "Mine", command: process.execPath }] }));
|
||||
const nowhere = { path: "", savedPath: "", npmBin: "", home: dir, vars: {} };
|
||||
assert.deepEqual((await installer.detectAgents({ binDir: dir, userAgentsFile: userFile, env: nowhere })).found, []);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("next steps: without the plan2code command, no line tells the person to run it", async () => {
|
||||
const { out } = await captured(() => installer.printGettingStarted({ commandInstalled: false, agents: { found: [], builtins: [] }, platform: "linux" }));
|
||||
assert.doesNotMatch(out, /run plan2code|Just run plan2code/);
|
||||
assert.match(out, /type \/plan2code/);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Uninstall: works without the skills CLI, prints only what was installed, removes the console,
|
||||
// lists what stays, and always ends with the Removed / Could not remove / To finish block.
|
||||
// Everything runs against the temp HOME above; the steps that would reach the real machine (the
|
||||
// npm global bin, the desktop folder) are replaced.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
const CLAUDE_DIR = path.join(HOME, ".claude");
|
||||
const SKILL_STORE = path.join(HOME, ".agents", "skills");
|
||||
|
||||
/** The legacy sweep reads %APPDATA% and %LOCALAPPDATA% on Windows: point them into the temp HOME while `fn` runs. */
|
||||
function withAppData(fn) {
|
||||
const saved = { APPDATA: process.env.APPDATA, LOCALAPPDATA: process.env.LOCALAPPDATA };
|
||||
process.env.APPDATA = path.join(HOME, "AppData", "Roaming");
|
||||
process.env.LOCALAPPDATA = path.join(HOME, "AppData", "Local");
|
||||
try {
|
||||
return fn();
|
||||
} finally {
|
||||
for (const [key, value] of Object.entries(saved)) {
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function makeSkill(name) {
|
||||
fs.mkdirSync(path.join(SKILL_STORE, name), { recursive: true });
|
||||
fs.writeFileSync(path.join(SKILL_STORE, name, "SKILL.md"), "---\nname: x\n---\n");
|
||||
}
|
||||
|
||||
test("uninstall without the skills CLI: the plan2code skill folders go directly, others stay, and the block says links may remain", () => {
|
||||
fs.rmSync(SKILL_STORE, { recursive: true, force: true });
|
||||
for (const name of ["plan2code", "plan2code-plan", "plan2code-3-implement", "someone-elses-skill"]) makeSkill(name);
|
||||
const report = installer.newUninstallReport();
|
||||
const result = withAppData(() => installer.uninstallSkillsPiece(report, { cli: { ensure: () => false, remove: () => assert.fail("the CLI is unreachable") } }));
|
||||
assert.equal(result.removed, 3);
|
||||
assert.deepEqual(result.failed, []);
|
||||
assert.deepEqual(fs.readdirSync(SKILL_STORE), ["someone-elses-skill"]);
|
||||
assert.equal(report.finish.length, 1);
|
||||
assert.match(report.finish[0], /could not be reached/);
|
||||
assert.match(report.finish[0], /may remain/);
|
||||
assert.deepEqual(installer.removeSkillsDirectly(SKILL_STORE), { removed: [], failed: [] }, "nothing left to remove, no error");
|
||||
});
|
||||
|
||||
test("uninstall with the skills CLI: it does the removing and no folder is touched by hand", () => {
|
||||
fs.rmSync(SKILL_STORE, { recursive: true, force: true });
|
||||
makeSkill("plan2code");
|
||||
const calls = [];
|
||||
const report = installer.newUninstallReport();
|
||||
const result = withAppData(() =>
|
||||
installer.uninstallSkillsPiece(report, {
|
||||
cli: { ensure: () => true, remove: (scope, options) => (calls.push([scope, options.quiet]), 1) },
|
||||
})
|
||||
);
|
||||
assert.deepEqual(calls, [["global", true]]);
|
||||
assert.equal(result.removed, 1);
|
||||
assert.deepEqual(report.finish, [], "nothing is left to do");
|
||||
assert.ok(fs.existsSync(path.join(SKILL_STORE, "plan2code")), "the stand-in CLI removed nothing, and nothing else did");
|
||||
fs.rmSync(SKILL_STORE, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
/** uninstallAll() with every step replaced by one that records itself; `results` says what each reports. */
|
||||
function uninstallWith({ pieces, results = {}, probes = {} }) {
|
||||
if (pieces) writeRecord(pieces);
|
||||
else clearRecord();
|
||||
const ran = [];
|
||||
const steps = {};
|
||||
for (const piece of installer.INSTALL_PIECES) {
|
||||
steps[piece] = () => (ran.push(piece), results[piece] || { removed: 1, failed: [] });
|
||||
}
|
||||
const report = installer.newUninstallReport();
|
||||
const lines = [];
|
||||
const log = console.log;
|
||||
console.log = (...args) => lines.push(args.join(" "));
|
||||
let code;
|
||||
try {
|
||||
code = installer.uninstallAll({ report, steps, probes, removeConsole: () => {} });
|
||||
} finally {
|
||||
console.log = log;
|
||||
}
|
||||
return { code, ran, report, out: lines.join("\n").replace(/\x1b\[[0-9;]*m/g, "") };
|
||||
}
|
||||
|
||||
const NO_STRAYS = { skills: () => false, launcher: () => false, app: () => false, statusline: () => false };
|
||||
|
||||
test("uninstall: only the recorded pieces are removed and named, never ones that were not installed", () => {
|
||||
const r = uninstallWith({ pieces: ["skills", "launcher"], probes: NO_STRAYS, results: { skills: { removed: 23, failed: [], detail: "23" } } });
|
||||
assert.equal(r.code, 0, r.out);
|
||||
assert.deepEqual(r.ran, ["skills", "launcher"]);
|
||||
assert.match(r.out, /Removed Skills \(23\)/);
|
||||
assert.match(r.out, /Removed plan2code command/);
|
||||
assert.doesNotMatch(r.out, /Status line|Metrics|Bot|Desktop app|UNINSTALL|plan2code-metrics|plan2code-bot/);
|
||||
assert.deepEqual(r.report.removed, ["Skills (23)", "plan2code command"]);
|
||||
});
|
||||
|
||||
test("uninstall: a piece missing from the record but found on disk is removed, and a piece found nowhere is not run", () => {
|
||||
const r = uninstallWith({ pieces: null, probes: { ...NO_STRAYS, statusline: () => true } });
|
||||
assert.deepEqual(r.ran, ["statusline"]);
|
||||
assert.match(r.out, /Removed Status line/);
|
||||
});
|
||||
|
||||
test("uninstall: the real probes look at the temp HOME and find nothing there", () => {
|
||||
fs.rmSync(path.join(CLAUDE_DIR, "plan2code-statusline.js"), { force: true });
|
||||
fs.rmSync(SKILL_STORE, { recursive: true, force: true });
|
||||
fs.rmSync(installer.APP_DEST, { force: true });
|
||||
assert.equal(installer.UNINSTALL_PROBES.skills(), false);
|
||||
assert.equal(installer.UNINSTALL_PROBES.app(), false);
|
||||
assert.equal(installer.UNINSTALL_PROBES.statusline(), false);
|
||||
fs.mkdirSync(CLAUDE_DIR, { recursive: true });
|
||||
fs.writeFileSync(path.join(CLAUDE_DIR, "plan2code-statusline.js"), "// ours");
|
||||
assert.equal(installer.UNINSTALL_PROBES.statusline(), true);
|
||||
fs.rmSync(path.join(CLAUDE_DIR, "plan2code-statusline.js"), { force: true });
|
||||
});
|
||||
|
||||
test("uninstall: the status line says it kept statusline-config.json only when that file exists", async () => {
|
||||
fs.mkdirSync(CLAUDE_DIR, { recursive: true });
|
||||
fs.rmSync(path.join(CLAUDE_DIR, "statusline-config.json"), { force: true });
|
||||
const quiet = (await captured(() => installer.uninstallStatusLine())).out;
|
||||
assert.doesNotMatch(quiet, /Preserved: statusline-config\.json/);
|
||||
fs.writeFileSync(path.join(CLAUDE_DIR, "statusline-config.json"), "{}");
|
||||
const kept = (await captured(() => installer.uninstallStatusLine())).out;
|
||||
assert.match(kept, /Preserved: statusline-config\.json/);
|
||||
fs.rmSync(path.join(CLAUDE_DIR, "statusline-config.json"), { force: true });
|
||||
});
|
||||
|
||||
test("uninstall: a piece that fails is named, makes the exit code 1, and the others still run", () => {
|
||||
const r = uninstallWith({ pieces: ["skills", "launcher", "app"], probes: NO_STRAYS, results: { launcher: { removed: 0, failed: ["EBUSY: file in use"] } } });
|
||||
assert.equal(r.code, 1, r.out);
|
||||
assert.deepEqual(r.ran, ["skills", "launcher", "app"]);
|
||||
assert.deepEqual(r.report.failed, ["plan2code command: EBUSY: file in use"]);
|
||||
assert.match(r.out, /plan2code command: EBUSY: file in use/);
|
||||
});
|
||||
|
||||
test("uninstall: the console's version folders and pointer are removed, a running console is stopped first, and sessions stay", () => {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-console-home-"));
|
||||
process.env.PLAN2CODE_CONSOLE_HOME = home;
|
||||
try {
|
||||
for (const version of ["3.0.2", "3.1.0"]) {
|
||||
fs.mkdirSync(path.join(home, version, "public"), { recursive: true });
|
||||
fs.writeFileSync(path.join(home, version, "console.mjs"), "// console");
|
||||
}
|
||||
fs.writeFileSync(path.join(home, "console-dir"), path.join(home, "3.1.0"));
|
||||
fs.mkdirSync(path.join(home, "sessions", "s1"), { recursive: true });
|
||||
fs.writeFileSync(path.join(home, "looks.json"), "{}");
|
||||
const stopped = [];
|
||||
const report = installer.newUninstallReport();
|
||||
const lines = [];
|
||||
const log = console.log;
|
||||
console.log = (...args) => lines.push(args.join(" "));
|
||||
try {
|
||||
installer.removeConsoleFolders(report, { stop: (dir) => (stopped.push(dir), 1) });
|
||||
} finally {
|
||||
console.log = log;
|
||||
}
|
||||
const out = lines.join("\n").replace(/\x1b\[[0-9;]*m/g, "");
|
||||
assert.deepEqual(stopped, [home]);
|
||||
assert.match(out, /Stopped 1 running Plan2Code console first/);
|
||||
assert.deepEqual(fs.readdirSync(home).sort(), ["looks.json", "sessions"]);
|
||||
assert.deepEqual(report.removed, ["Console files"]);
|
||||
assert.deepEqual(report.failed, []);
|
||||
} finally {
|
||||
delete process.env.PLAN2CODE_CONSOLE_HOME;
|
||||
fs.rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("uninstall: a console folder that cannot be removed is reported with what to do, and a missing console home is fine", () => {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-console-busy-"));
|
||||
process.env.PLAN2CODE_CONSOLE_HOME = home;
|
||||
const realRm = fs.rmSync;
|
||||
try {
|
||||
fs.mkdirSync(path.join(home, "3.0.2"), { recursive: true });
|
||||
fs.mkdirSync(path.join(home, "3.1.0"), { recursive: true });
|
||||
fs.rmSync = (target, options) => {
|
||||
if (String(target).endsWith("3.0.2")) throw new Error("EBUSY: resource busy");
|
||||
return realRm(target, options);
|
||||
};
|
||||
const report = installer.newUninstallReport();
|
||||
const log = console.log;
|
||||
console.log = () => {};
|
||||
try {
|
||||
installer.removeConsoleFolders(report, { stop: () => 0 });
|
||||
} finally {
|
||||
console.log = log;
|
||||
fs.rmSync = realRm;
|
||||
}
|
||||
assert.deepEqual(report.failed, ["Console files 3.0.2: EBUSY: resource busy"]);
|
||||
assert.deepEqual(report.finish, ["Close any open Plan2Code console or app, then run plan2code uninstall again."]);
|
||||
assert.deepEqual(report.removed, ["Console files"]);
|
||||
assert.ok(fs.existsSync(path.join(home, "3.0.2")) && !fs.existsSync(path.join(home, "3.1.0")));
|
||||
process.env.PLAN2CODE_CONSOLE_HOME = path.join(home, "nowhere");
|
||||
assert.doesNotThrow(() => installer.removeConsoleFolders(installer.newUninstallReport(), { stop: () => 0 }));
|
||||
} finally {
|
||||
fs.rmSync = realRm;
|
||||
delete process.env.PLAN2CODE_CONSOLE_HOME;
|
||||
realRm(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("uninstall: what stays in the data folder is listed by name with its size, and the closing block always prints", async () => {
|
||||
const data = path.join(HOME, ".plan2code");
|
||||
fs.rmSync(path.join(data, "notepads"), { recursive: true, force: true });
|
||||
fs.mkdirSync(path.join(data, "notepads"), { recursive: true });
|
||||
fs.writeFileSync(path.join(data, "notepads", "a.json"), "x".repeat(2048));
|
||||
fs.mkdirSync(path.join(data, "handoffs"), { recursive: true });
|
||||
const listed = installer.listKeptData(data);
|
||||
const notebooks = listed.find((item) => item.name === "notepads");
|
||||
assert.equal(notebooks.label, "Notebooks");
|
||||
assert.equal(notebooks.bytes, 2048);
|
||||
assert.ok(listed.some((item) => item.name === "handoffs" && item.label === "Handoffs"));
|
||||
|
||||
const kept = await runUninstall({ yes: true });
|
||||
assert.equal(kept.code, 0);
|
||||
assert.match(kept.out, /Your data in .* was kept/);
|
||||
assert.match(kept.out, /Notebooks: 2 KB/);
|
||||
assert.match(kept.out, /Removed: nothing/);
|
||||
assert.match(kept.out, /Could not remove: nothing/);
|
||||
assert.match(kept.out, /To finish: nothing, you are done/);
|
||||
assert.match(kept.out, /Plan2Code is uninstalled/);
|
||||
|
||||
// A failed run still ends on the block, says that something failed, and leaves no cheerful closing line.
|
||||
const failed = await runUninstall({ yes: true, remove: () => 1 });
|
||||
assert.equal(failed.code, 1);
|
||||
assert.match(failed.out, /Removed: nothing/);
|
||||
assert.match(failed.out, /Could not remove:\n\s+✗ One or more pieces/);
|
||||
assert.match(failed.out, /To finish:/);
|
||||
assert.doesNotMatch(failed.out, /Plan2Code is uninstalled/);
|
||||
|
||||
// With the data deleted there is nothing to list, and the block names the data as removed.
|
||||
const purged = await runUninstall({ yes: true, purge: true });
|
||||
assert.doesNotMatch(purged.out, /Notebooks:/);
|
||||
assert.match(purged.out, /Removed: Your Plan2Code data/);
|
||||
fs.rmSync(path.join(data, "notepads"), { recursive: true, force: true });
|
||||
fs.rmSync(path.join(data, "handoffs"), { recursive: true, force: true });
|
||||
});
|
||||
+367
-15
@@ -10,7 +10,7 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
@@ -19,6 +19,9 @@ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const LAUNCHER = path.join(ROOT, "src", "launcher", "plan2code.js");
|
||||
const IS_WINDOWS = process.platform === "win32";
|
||||
const NOTICE = "will use the model you last used in it";
|
||||
// The no-agent pointer to custom agents, word for word as install.js prints it (Task 2.10/2.11).
|
||||
const NO_AGENT_POINTER =
|
||||
"Already use another agent CLI? Add it in User Preferences, Agents & models (the gear on the Plan2Code page), then run `plan2code` again.";
|
||||
|
||||
/**
|
||||
* A temp home and a bin dir holding stand-ins for `clis`; each writes its args to <bin>/<cli>.json.
|
||||
@@ -86,9 +89,12 @@ function sandbox(clis, { installed, project = true, lookup = true, agents } = {}
|
||||
fs.writeFileSync(crashFile, "#!/bin/sh\nexit 3\n");
|
||||
fs.chmodSync(crashFile, 0o755);
|
||||
}
|
||||
const envFor = (env = {}) => ({ ...process.env, PATH: bin, PLAN2CODE_NO_SAVED_PATH: "1", HOME: home, USERPROFILE: home, PLAN2CODE_CONSOLE_HOME: consoleHome, ...env });
|
||||
return {
|
||||
dir,
|
||||
home,
|
||||
launcher,
|
||||
envFor,
|
||||
appFile,
|
||||
crashFile,
|
||||
stateFile: path.join(home, ".plan2code", "launcher.json"),
|
||||
@@ -98,7 +104,7 @@ function sandbox(clis, { installed, project = true, lookup = true, agents } = {}
|
||||
cwd: dir,
|
||||
input: "",
|
||||
encoding: "utf8",
|
||||
env: { ...process.env, PATH: bin, PLAN2CODE_NO_SAVED_PATH: "1", HOME: home, USERPROFILE: home, PLAN2CODE_CONSOLE_HOME: consoleHome, ...env },
|
||||
env: envFor(env),
|
||||
}),
|
||||
argsOf: (cli) => {
|
||||
const file = path.join(bin, `${cli}.json`);
|
||||
@@ -255,7 +261,12 @@ test("launcher: the shipped models.json lists every CLI, and every entry has an
|
||||
const shipped = JSON.parse(fs.readFileSync(path.join(path.dirname(LAUNCHER), "models.json"), "utf8"));
|
||||
for (const cli of ["claude", "devin", "codex"]) {
|
||||
assert.ok(Array.isArray(shipped[cli]), cli);
|
||||
for (const { id, label } of shipped[cli]) assert.ok(id && label, cli);
|
||||
for (const { id, label } of shipped[cli]) {
|
||||
assert.ok(id && label, cli);
|
||||
// A label is the description only: the launcher prints the id beside it, so no label
|
||||
// repeats a name ahead of a gloss ("Sonnet, latest Sonnet" or the same with a dash).
|
||||
assert.doesNotMatch(label, /\u2014|^[^\s,]+, /, `${cli} ${id}: ${label}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -446,8 +457,9 @@ test("launcher: with no CLI installed it exits 127 and explains how to get one a
|
||||
]) {
|
||||
assert.ok(result.stderr.includes(part), part);
|
||||
}
|
||||
assert.ok(result.stderr.includes("Add it by editing `~/.plan2code/agents.json`, then run `plan2code` again."));
|
||||
assert.doesNotMatch(result.stderr, /User Preferences/);
|
||||
// The same pointer install.js prints for custom agents; no hand-editing of agents.json.
|
||||
assert.ok(result.stderr.includes(NO_AGENT_POINTER));
|
||||
assert.doesNotMatch(result.stderr, /editing/);
|
||||
assert.ok(result.stderr.includes("type /plan2code ($plan2code in Codex)"));
|
||||
assert.match(result.stderr, /cd into the project/);
|
||||
});
|
||||
@@ -468,42 +480,136 @@ 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: update runs the npx install and starts no agent", (t) => {
|
||||
/** A `git ls-remote --tags` answer for `tags`, written to a file the launcher reads in git's place. */
|
||||
function lsRemoteStub(box, tags) {
|
||||
const file = path.join(box.dir, "ls-remote.txt");
|
||||
const lines = tags.map((tag, i) => `${String(i + 1).repeat(40).slice(0, 40)}\trefs/tags/${tag}`);
|
||||
fs.writeFileSync(file, lines.join("\n") + "\n");
|
||||
return { PLAN2CODE_LS_REMOTE_FILE: file };
|
||||
}
|
||||
|
||||
const REPO = "git+https://github.com/jparkerweb/plan2code.git";
|
||||
|
||||
test("launcher: update installs the newest release tag, by version and not by name or order", (t) => {
|
||||
const box = sandbox(["npx", "claude"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run(["update"]);
|
||||
// v3.10.0 beats v3.9.0 numerically; a pre-release, a peeled line and a non-release tag never count.
|
||||
const env = lsRemoteStub(box, ["v3.9.0", "v3.10.0", "v3.10.1-rc1", "v3.10.0^{}", "nightly", "v3.2.0"]);
|
||||
const result = box.run(["update"], env);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /Updating Plan2Code\.\.\./);
|
||||
assert.match(result.stdout, /Updating Plan2Code to v3\.10\.0\.\.\./);
|
||||
const args = box.argsOf("npx");
|
||||
assert.ok(args, "npx was not run");
|
||||
assert.ok(args.includes("--update"), args.join(" "));
|
||||
assert.ok(args.includes("git+https://github.com/jparkerweb/plan2code.git"), args.join(" "));
|
||||
assert.ok(args.includes(`${REPO}#v3.10.0`), args.join(" "));
|
||||
assert.ok(!args.includes("--force"), args.join(" "));
|
||||
assert.equal(box.argsOf("claude"), null);
|
||||
});
|
||||
|
||||
test("launcher: update --main installs the tip of main, as it always did", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run(["update", "--main"], lsRemoteStub(box, ["v9.9.9"]));
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /Updating Plan2Code to the newest work on main\.\.\./);
|
||||
const args = box.argsOf("npx");
|
||||
assert.ok(args.includes(REPO), args.join(" "));
|
||||
assert.ok(!args.some((arg) => arg.includes("#")), args.join(" "));
|
||||
// Unreleased work on main carries the last release's version, so the installer's "Already on"
|
||||
// check would stop it: --main always reinstalls.
|
||||
assert.ok(args.includes("--force"), args.join(" "));
|
||||
});
|
||||
|
||||
test("launcher: update --tag reinstalls for a branch, and not for a release tag", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
assert.equal(box.run(["update", "--tag", "release"]).status, 0);
|
||||
let args = box.argsOf("npx");
|
||||
assert.ok(args.includes(`${REPO}#release`) && args.includes("--force"), args.join(" "));
|
||||
assert.equal(box.run(["update", "--tag", "v3.0.2"]).status, 0);
|
||||
args = box.argsOf("npx");
|
||||
assert.ok(args.includes(`${REPO}#v3.0.2`) && !args.includes("--force"), args.join(" "));
|
||||
});
|
||||
|
||||
test("launcher: update --tag installs that ref without asking for the release list", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
// No tag list is available at all: --tag must not need one.
|
||||
const result = box.run(["update", "--tag", "v3.0.2"], { PLAN2CODE_LS_REMOTE_FILE: path.join(box.dir, "missing.txt") });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /Updating Plan2Code to v3\.0\.2\.\.\./);
|
||||
assert.ok(box.argsOf("npx").includes(`${REPO}#v3.0.2`), box.argsOf("npx").join(" "));
|
||||
});
|
||||
|
||||
test("launcher: update --force reaches the installer", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
assert.equal(box.run(["update", "--force"], lsRemoteStub(box, ["v3.1.0"])).status, 0);
|
||||
const args = box.argsOf("npx");
|
||||
assert.ok(args.includes("--update") && args.includes("--force"), args.join(" "));
|
||||
assert.ok(args.includes(`${REPO}#v3.1.0`), args.join(" "));
|
||||
});
|
||||
|
||||
test("launcher: update with no release list says so and installs nothing", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run(["update"], lsRemoteStub(box, ["nightly", "v1.0"]));
|
||||
assert.equal(result.status, 1);
|
||||
assert.match(result.stderr, /could not find the newest Plan2Code release/);
|
||||
assert.match(result.stderr, /--main/);
|
||||
assert.match(result.stderr, /--tag v3\.0\.2/);
|
||||
assert.equal(box.argsOf("npx"), null);
|
||||
});
|
||||
|
||||
test("launcher: update refuses a --tag with no value, both --main and --tag, and an unknown option", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
for (const [args, message] of [
|
||||
[["update", "--tag"], /--tag needs a release or branch/],
|
||||
[["update", "--main", "--tag", "v3.0.2"], /use --main or --tag, not both/],
|
||||
[["update", "--nope"], /unknown option for update: --nope/],
|
||||
]) {
|
||||
const result = box.run(args);
|
||||
assert.equal(result.status, 2, args.join(" "));
|
||||
assert.match(result.stderr, message);
|
||||
assert.equal(box.argsOf("npx"), null);
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher: update passes npx's exit code through", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
assert.equal(box.run(["update"], { P2C_TEST_EXIT: "3" }).status, 3);
|
||||
assert.equal(box.run(["update", "--main"], { P2C_TEST_EXIT: "3" }).status, 3);
|
||||
});
|
||||
|
||||
test("launcher: uninstall runs the npx install with --uninstall and starts no agent", (t) => {
|
||||
const box = sandbox(["npx", "claude"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run(["uninstall", "--yes", "--purge"]);
|
||||
const result = box.run(["uninstall", "--yes", "--purge"], lsRemoteStub(box, ["v3.1.0", "v3.0.2"]));
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /Uninstalling Plan2Code\.\.\./);
|
||||
const args = box.argsOf("npx");
|
||||
assert.ok(args, "npx was not run");
|
||||
assert.ok(args.includes("--uninstall") && args.includes("--yes") && args.includes("--purge"), args.join(" "));
|
||||
assert.ok(!args.includes("--update"), args.join(" "));
|
||||
// The newest release's installer, never unreleased work on main.
|
||||
assert.ok(args.includes(`${REPO}#v3.1.0`), args.join(" "));
|
||||
assert.equal(box.argsOf("claude"), null);
|
||||
});
|
||||
|
||||
test("launcher: uninstall falls back to main when the newest release cannot be found", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run(["uninstall", "--yes"], lsRemoteStub(box, ["nightly"]));
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
const args = box.argsOf("npx");
|
||||
assert.ok(args.includes(REPO) && !args.some((arg) => arg.includes("#")), args.join(" "));
|
||||
});
|
||||
|
||||
test("launcher: uninstall passes npx's exit code through", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
assert.equal(box.run(["uninstall"], { P2C_TEST_EXIT: "4" }).status, 4);
|
||||
assert.equal(box.run(["uninstall"], { P2C_TEST_EXIT: "4", ...lsRemoteStub(box, ["v3.1.0"]) }).status, 4);
|
||||
});
|
||||
|
||||
test("launcher: uninstall refuses an unknown option without running npx", (t) => {
|
||||
@@ -948,7 +1054,8 @@ test("launcher agents: a custom agent whose command is not found is left out and
|
||||
const result = none.run([]);
|
||||
assert.equal(result.status, 127);
|
||||
assert.match(result.stderr, /Custom agent Ghost: ghost-cmd not found/);
|
||||
assert.ok(result.stderr.includes("agents.json"));
|
||||
// Custom agents are fixed where they are added: User Preferences, Agents & models.
|
||||
assert.ok(result.stderr.includes(NO_AGENT_POINTER));
|
||||
});
|
||||
|
||||
test("launcher agents: a malformed agents.json warns on a terminal, never crashes, and gives no agents", (t) => {
|
||||
@@ -1045,8 +1152,8 @@ test("launcher list: with no agent and no terminal it prints this OS's install s
|
||||
assert.ok(result.stderr.includes(leadRun(id)), `${id}: ${leadRun(id)}`);
|
||||
assert.ok(result.stderr.includes(builtin(id).installUrl), id);
|
||||
}
|
||||
assert.ok(result.stderr.includes("add another agent by editing `~/.plan2code/agents.json`, then run `plan2code` again") || result.stderr.includes("Add it by editing `~/.plan2code/agents.json`, then run `plan2code` again."));
|
||||
assert.doesNotMatch(result.stderr, /User Preferences/);
|
||||
assert.ok(result.stderr.includes(NO_AGENT_POINTER));
|
||||
assert.doesNotMatch(result.stderr, /agents\.json/);
|
||||
});
|
||||
|
||||
test("launcher list: --cli for a missing built-in prints its lead install line and exits 127", (t) => {
|
||||
@@ -1464,3 +1571,248 @@ test("launcher folder menu: a folder that fails the project check is not recorde
|
||||
assert.equal(box.argsOf("claude"), null);
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(box.stateFile, "utf8")), state);
|
||||
});
|
||||
|
||||
// --help, --version and the Node guard: none of them shows a prompt or starts an agent.
|
||||
const PROMPT_TEXT = /Which|\(Y\/n\)|\(y\/N\)|Choose|Pick/;
|
||||
|
||||
for (const flag of ["--help", "-h", "help"]) {
|
||||
test(`launcher help: ${flag} prints the usage and exits 0 with no prompt`, (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run([flag]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /^Usage: plan2code/m);
|
||||
for (const word of ["update", "uninstall", "--tag", "--main", "--force", "Go back to a release", "plan2code update --tag v3.0.2", "--cli", "--classic", "--keep-permissions", "--bypass-permissions", "--pick-folder"]) {
|
||||
assert.ok(result.stdout.includes(word), `the usage names ${word}`);
|
||||
}
|
||||
assert.match(result.stdout, /plan2code -- --help shows your agent's own help/);
|
||||
assert.doesNotMatch(result.stdout, PROMPT_TEXT);
|
||||
assert.equal(box.argsOf("claude"), null, "no agent started");
|
||||
});
|
||||
}
|
||||
|
||||
for (const flag of ["--version", "-v"]) {
|
||||
test(`launcher version: ${flag} prints the installed version and exits 0 with no prompt`, (t) => {
|
||||
const box = sandbox(["claude"], { installed: "9.8.7" });
|
||||
t.after(box.cleanup);
|
||||
const result = box.run([flag]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(result.stdout.trim(), "Plan2Code v9.8.7");
|
||||
assert.equal(box.argsOf("claude"), null, "no agent started");
|
||||
});
|
||||
}
|
||||
|
||||
test("launcher help: --help after -- goes to the agent, without the separator", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run(["--", "--help"]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.doesNotMatch(result.stdout, /^Usage: plan2code/m);
|
||||
assert.deepEqual(box.argsOf("claude"), [...CLASSIC_ARGS, "--help"]);
|
||||
});
|
||||
|
||||
test("launcher app: arguments the app does not take are named in one line", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const display = process.platform === "linux" ? { DISPLAY: ":0" } : {};
|
||||
const result = box.run(["--model", "opus", "--verbose"], { PLAN2CODE_APP: box.appFile, ...display });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.deepEqual(box.appArgs().slice(2), ["--agent", "claude", "--model", "opus"]);
|
||||
assert.match(result.stdout, /not passed on: --verbose$/m);
|
||||
});
|
||||
|
||||
test("launcher app: no dropped-argument line when nothing is dropped", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const display = process.platform === "linux" ? { DISPLAY: ":0" } : {};
|
||||
const result = box.run(["--model", "opus"], { PLAN2CODE_APP: box.appFile, ...display });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.doesNotMatch(result.stdout, /not passed on/);
|
||||
});
|
||||
|
||||
test("launcher: droppedForApp keeps every argument but the model flag's forms", () => {
|
||||
const { droppedForApp } = require(LAUNCHER);
|
||||
assert.deepEqual(droppedForApp(["--model", "x", "--verbose"], "claude"), ["--verbose"]);
|
||||
assert.deepEqual(droppedForApp(["--model=x", "-p"], "claude"), ["-p"]);
|
||||
assert.deepEqual(droppedForApp(["-m", "x", "-mfoo", "--y"], "codex"), ["--y"]);
|
||||
assert.deepEqual(droppedForApp(["-m", "x"], "claude"), ["-m", "x"]);
|
||||
assert.deepEqual(droppedForApp([], "claude"), []);
|
||||
});
|
||||
|
||||
test("launcher: the Node guard names the version on Node older than 18", () => {
|
||||
const { nodeVersionProblem } = require(LAUNCHER);
|
||||
assert.equal(nodeVersionProblem("16.20.2"), "Plan2Code needs Node.js 18 or newer; you have v16.20.2. Get it from nodejs.org");
|
||||
assert.equal(nodeVersionProblem("18.0.0"), null);
|
||||
assert.equal(nodeVersionProblem("26.1.0"), null);
|
||||
});
|
||||
|
||||
test("launcher: an old Node fails fast with the guard's sentence", () => {
|
||||
// The guard runs before anything else, so a stubbed process.versions.node stops the load.
|
||||
const code = `Object.defineProperty(process.versions, "node", { value: "16.20.2" }); require(${JSON.stringify(LAUNCHER)});`;
|
||||
const result = spawnSync(process.execPath, ["-e", code], { encoding: "utf8" });
|
||||
assert.equal(result.status, 1);
|
||||
assert.match(result.stderr, /Plan2Code needs Node\.js 18 or newer; you have v16\.20\.2\. Get it from nodejs\.org/);
|
||||
});
|
||||
|
||||
test("launcher app: arguments after -- keep the run in this terminal even with the app installed", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const display = process.platform === "linux" ? { DISPLAY: ":0" } : {};
|
||||
const result = box.run(["--", "--help"], { PLAN2CODE_APP: box.appFile, ...display });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(box.appExists(), false, "the app was not started");
|
||||
assert.deepEqual(box.argsOf("claude"), [...CLASSIC_ARGS, "--help"]);
|
||||
assert.doesNotMatch(result.stdout, /not passed on/);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Prompts at a "terminal". A preload marks stdin as a TTY, so the launcher asks its questions;
|
||||
// stdin stays a pipe. Each prompt opens its own readline, and a readline takes everything
|
||||
// waiting on the pipe, so answers piped in all at once reach the first prompt only: each
|
||||
// answer is written once its prompt shows on stdout, after a short pause.
|
||||
|
||||
/**
|
||||
* Run the launcher with `steps` ([{ when: RegExp, send }]) answered in order, each `when`
|
||||
* matched against the stdout printed since the last answer. Resolves { status, stdout, stderr,
|
||||
* sent } once it exits (killed after 20s, so a prompt nobody answers fails the test, not hangs).
|
||||
*/
|
||||
function runAtTerminal(box, args, steps, { env = {}, cwd = box.dir } = {}) {
|
||||
const shim = path.join(box.dir, "tty-shim.cjs");
|
||||
fs.writeFileSync(shim, 'Object.defineProperty(process.stdin, "isTTY", { value: true, configurable: true });\n');
|
||||
return new Promise((resolve) => {
|
||||
const child = spawn(process.execPath, ["-r", shim, box.launcher, ...args], { cwd, env: box.envFor(env) });
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let from = 0;
|
||||
let sent = 0;
|
||||
let writing = false;
|
||||
const next = () => {
|
||||
if (writing || sent >= steps.length) return;
|
||||
if (!steps[sent].when.test(stdout.slice(from))) return;
|
||||
writing = true;
|
||||
from = stdout.length;
|
||||
setTimeout(() => {
|
||||
child.stdin.write(steps[sent].send);
|
||||
sent++;
|
||||
writing = false;
|
||||
next();
|
||||
}, 80);
|
||||
};
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stderr.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk) => {
|
||||
stdout += chunk;
|
||||
next();
|
||||
});
|
||||
child.stderr.on("data", (chunk) => (stderr += chunk));
|
||||
const timer = setTimeout(() => child.kill(), 20000);
|
||||
child.on("close", (status) => {
|
||||
clearTimeout(timer);
|
||||
resolve({ status, stdout, stderr, sent });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const NOT_A_PROJECT = /doesn't look like a project/;
|
||||
const NOTHING_OPENED = "Nothing opened. cd into your project (or run `git init` here) and run `plan2code` again.";
|
||||
|
||||
test("launcher: isEmptyFolder ignores OS litter and calls an unreadable folder not empty", () => {
|
||||
const { isEmptyFolder } = require(LAUNCHER);
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-empty-"));
|
||||
try {
|
||||
assert.equal(isEmptyFolder(dir), true);
|
||||
fs.writeFileSync(path.join(dir, ".DS_Store"), "");
|
||||
fs.writeFileSync(path.join(dir, "Thumbs.db"), "");
|
||||
assert.equal(isEmptyFolder(dir), true, "OS litter only");
|
||||
fs.writeFileSync(path.join(dir, "notes.txt"), "");
|
||||
assert.equal(isEmptyFolder(dir), false);
|
||||
assert.equal(isEmptyFolder(path.join(dir, "missing")), false);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher project check: an empty folder defaults to Yes, so Enter opens it", async (t) => {
|
||||
const box = sandbox(["claude"], { project: false });
|
||||
t.after(box.cleanup);
|
||||
const empty = path.join(box.dir, "new-project");
|
||||
fs.mkdirSync(empty);
|
||||
const result = await runAtTerminal(box, ["--bypass-permissions", "--model", "opus"], [{ when: /anyway\? \[Y\/n\]: $/, send: "\n" }], { cwd: empty });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(result.sent, 1, result.stdout);
|
||||
assert.match(result.stdout, NOT_A_PROJECT);
|
||||
assert.ok(!result.stdout.includes(NOTHING_OPENED));
|
||||
assert.ok(box.argsOf("claude"), "the agent started");
|
||||
});
|
||||
|
||||
test("launcher project check: an empty folder answered n opens nothing and says what to do", async (t) => {
|
||||
const box = sandbox(["claude"], { project: false });
|
||||
t.after(box.cleanup);
|
||||
const empty = path.join(box.dir, "new-project");
|
||||
fs.mkdirSync(empty);
|
||||
const result = await runAtTerminal(box, ["--bypass-permissions", "--model", "opus"], [{ when: /\[Y\/n\]: $/, send: "n\n" }], { cwd: empty });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.ok(result.stdout.includes(NOTHING_OPENED), result.stdout);
|
||||
assert.equal(box.argsOf("claude"), null);
|
||||
});
|
||||
|
||||
test("launcher project check: a folder with files that is not a project keeps No as the default", async (t) => {
|
||||
// The sandbox folder holds home/, bin/ and app/, and no git repo, AGENTS.md or specs/.
|
||||
const box = sandbox(["claude"], { project: false });
|
||||
t.after(box.cleanup);
|
||||
const declined = await runAtTerminal(box, ["--bypass-permissions", "--model", "opus"], [{ when: /anyway\? \[y\/N\]: $/, send: "\n" }]);
|
||||
assert.equal(declined.status, 0, declined.stderr);
|
||||
assert.equal(declined.sent, 1, declined.stdout);
|
||||
assert.ok(declined.stdout.includes(NOTHING_OPENED), declined.stdout);
|
||||
assert.equal(box.argsOf("claude"), null);
|
||||
|
||||
const confirmed = await runAtTerminal(box, ["--bypass-permissions", "--model", "opus"], [{ when: /\[y\/N\]: $/, send: "y\n" }]);
|
||||
assert.equal(confirmed.status, 0, confirmed.stderr);
|
||||
assert.ok(!confirmed.stdout.includes(NOTHING_OPENED));
|
||||
assert.ok(box.argsOf("claude"), "a typed y opens it");
|
||||
});
|
||||
|
||||
test("launcher menus: the agent tip shows once, and the model menu prints ids in a column beside each description", async (t) => {
|
||||
const box = sandbox(["claude", "devin"]);
|
||||
t.after(box.cleanup);
|
||||
// Agent menu, keyboard question, then model menu: three prompts, each answered in turn.
|
||||
const steps = (modelAnswer) => [
|
||||
{ when: /Choice \[1\]: $/, send: "1\n" },
|
||||
{ when: /\[Y\/n\]: $/, send: "\n" },
|
||||
{ when: /Choice \[(agent default|\d+)\]: $/, send: modelAnswer },
|
||||
];
|
||||
const first = await runAtTerminal(box, ["--classic"], steps("latest opus\n"));
|
||||
assert.equal(first.status, 0, first.stderr);
|
||||
assert.equal(first.sent, 3, first.stdout);
|
||||
assert.match(first.stdout, /skip this launcher and run `\/plan2code`/);
|
||||
assert.doesNotMatch(first.stdout, /That runs outside the desktop app/, "no app installed, so no line about it");
|
||||
// ids padded to the longest (opusplan), then the description; the first run's Enter is the agent's.
|
||||
assert.match(first.stdout, /^ {2}1\) default {3}your account setting$/m);
|
||||
assert.match(first.stdout, /^ {2}2\) sonnet {4}latest Sonnet$/m);
|
||||
assert.match(first.stdout, /^ {2}5\) opusplan {2}Opus in plan mode, Sonnet otherwise$/m);
|
||||
assert.match(first.stdout, /Choice \[agent default\]: /);
|
||||
assert.ok(box.argsOf("claude").includes("opus"), "a typed description picks its model");
|
||||
const state = JSON.parse(fs.readFileSync(box.stateFile, "utf8"));
|
||||
assert.equal(state.agentTipSeen, true);
|
||||
assert.equal(state.lastModels.claude, "opus");
|
||||
|
||||
// Second run: no tip, and Enter runs the model marked (last used).
|
||||
const second = await runAtTerminal(box, ["--classic"], steps("\n"));
|
||||
assert.equal(second.status, 0, second.stderr);
|
||||
assert.equal(second.sent, 3, second.stdout);
|
||||
assert.doesNotMatch(second.stdout, /skip this launcher/);
|
||||
assert.match(second.stdout, /^ {2}3\) opus {6}latest Opus \(last used\)$/m);
|
||||
assert.match(second.stdout, /Choice \[3\]: /);
|
||||
assert.ok(box.argsOf("claude").includes("opus"));
|
||||
});
|
||||
|
||||
test("launcher menus: with the desktop app installed the tip also says it runs outside the app", async (t) => {
|
||||
const box = sandbox(["claude", "devin"]);
|
||||
t.after(box.cleanup);
|
||||
const result = await runAtTerminal(box, ["--classic", "--bypass-permissions", "--model", "opus"], [{ when: /Choice \[1\]: $/, send: "\n" }], {
|
||||
env: { PLAN2CODE_APP: box.appFile },
|
||||
});
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /skip this launcher[^\n]*\n[^\n]*That runs outside the desktop app/);
|
||||
assert.equal(box.appExists(), false, "--classic kept the run in this terminal");
|
||||
});
|
||||
Reference in new issue
Block a user