mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-17 20:51:19 -08:00
Add Update and restart, a remembered window and safer copy and paste to the desktop app
AI Assisted
This commit is contained in:
1 parent
c07e679105
commit
710c751c2f
24 files changed
+4347
-422
No files matched your search
+780
-32
@@ -11,13 +11,14 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { helloRetryAction, retryLabel, RETRY_AFTER_SECONDS, attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, folderPickerRows, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopRunText, loopLocks, loopStopLabels, loopWindowTitle, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS, NEW_RELEASE_COMMAND } from "../plan2code-app/ui/meter.js";
|
||||
import { looksFromMessage, terminalFontStep, TERMINAL_FONT_DEFAULT, TERMINAL_FONT_MIN, TERMINAL_FONT_MAX, splitterFraction, splitterAria, terminalTitle, barFit, terminalAnsi, TERMINAL_ANSI, hexToRgba, helloRetryAction, retryLabel, RETRY_AFTER_SECONDS, attentionSignal, commandSegments, plainCommandText, menuStep, pageNotShownView, pageDetailsLine, redactSessionUrl, barNextSteps, continueKeys, defaultRightFraction, folderName, folderPickerRows, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopRunText, loopLocks, loopStopLabels, loopWindowTitle, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS, NEW_RELEASE_COMMAND, STILL_WAITING_MS, STILL_WAITING_TEXT, waitingView, friendlyError, endedView, confirmButtons, trapTab, SHORTCUTS, shortcutAction, shortcutLabel, tipWithShortcut, shortcutFromMessage, clipboardAction, releaseAfterCheck, releaseNotesUrl, reasonSentence, UPDATE_RECHECK_MS } from "../plan2code-app/ui/meter.js";
|
||||
import { findBrowser, launchBrowser } from "./browser.mjs";
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const INDEX_HTML_PATH = path.join(HERE, "../plan2code-app/ui/index.html");
|
||||
const APP_JS = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/app.js"), "utf8");
|
||||
const INDEX_HTML = fs.readFileSync(INDEX_HTML_PATH, "utf8");
|
||||
const METER_JS = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/meter.js"), "utf8");
|
||||
|
||||
test("barNextSteps offers nothing while the console runs and the versions agree", () => {
|
||||
assert.deepEqual(barNextSteps(), []);
|
||||
@@ -38,32 +39,77 @@ test("only one control for reconnecting the console is ever offered: after an up
|
||||
assert.deepEqual(steps.map((step) => step.action), ["restart-console"], "the plain reconnect steps aside for the one that stops the old console first");
|
||||
});
|
||||
|
||||
test("a newer GitHub release is offered last, with the command to copy; a mismatch or a stopped console comes first", () => {
|
||||
test("a newer GitHub release is offered last, as Update and restart with a What's new link; a mismatch or a stopped console comes first", () => {
|
||||
const newRelease = { latest: "3.0.1" };
|
||||
const ids = (input) => barNextSteps(input).map((step) => step.id);
|
||||
assert.deepEqual(ids({ newRelease }), ["new-release"]);
|
||||
assert.deepEqual(ids({ consoleDead: true, version: { kind: "mismatch", skills: "3.0.0", app: "3.1.0" }, newRelease }), ["console-dead", "mismatch", "new-release"]);
|
||||
const [step] = barNextSteps({ newRelease });
|
||||
assert.equal(step.text, "Update available: v3.0.1");
|
||||
assert.equal(step.label, "Copy update command");
|
||||
assert.equal(step.action, "copy-update");
|
||||
assert.equal(NEW_RELEASE_COMMAND, "plan2code update");
|
||||
assert.equal(step.label, "Update and restart");
|
||||
assert.equal(step.action, "update-restart");
|
||||
assert.deepEqual(step.link, { label: "What's new", url: "https://github.com/jparkerweb/plan2code/releases/tag/v3.0.1" });
|
||||
assert.equal(releaseNotesUrl("v3.0.1"), step.link.url, "a leading v is not doubled");
|
||||
assert.equal(NEW_RELEASE_COMMAND, "plan2code update", "still the fallback command a failed update names");
|
||||
assert.deepEqual(barNextSteps({ newRelease: null }), [], "nothing newer, nothing shown");
|
||||
});
|
||||
|
||||
test("after the copy the bar says what to do next; if the clipboard was refused it spells the command out", () => {
|
||||
const [copied] = barNextSteps({ newRelease: { latest: "3.0.1", copied: true } });
|
||||
assert.match(copied.text, /^Copied: run `plan2code update` in a terminal/);
|
||||
assert.equal(copied.action, null);
|
||||
const [manual] = barNextSteps({ newRelease: { latest: "3.0.1", manual: true } });
|
||||
assert.match(manual.text, /^Run `plan2code update` in a terminal/);
|
||||
assert.equal(manual.action, null);
|
||||
test("the update states: running shows its line and no button, a failure keeps the app up and says why, an installed one offers the restart", () => {
|
||||
const [running] = barNextSteps({ newRelease: { latest: "3.2.0", updating: "Installing skills (4 of 9)" } });
|
||||
assert.deepEqual([running.text, running.busy, running.action, running.link ?? null], ["Installing skills (4 of 9)", true, null, null]);
|
||||
const [starting] = barNextSteps({ newRelease: { latest: "3.2.0", updating: "" } });
|
||||
assert.equal(starting.text, "Updating to v3.2.0...", "a first line before the installer says anything");
|
||||
const [failed] = barNextSteps({ newRelease: { latest: "3.2.0", failed: "The update did not finish: npm exited with code 1." } });
|
||||
assert.deepEqual([failed.text, failed.tone, failed.action, failed.label], ["Update failed", "err", "update-restart", "Update and restart"], "it can be tried again");
|
||||
assert.match(failed.title, /^The update did not finish: npm exited with code 1\. Plan2Code is still running as it was\./, "the reason, in full, for the tooltip and the list");
|
||||
assert.match(failed.title, /run `plan2code update` in a terminal/, "the old way stays as the fallback");
|
||||
const [restart] = barNextSteps({ newRelease: { latest: "3.2.0", restartNeeded: true } });
|
||||
assert.deepEqual([restart.text, restart.action, restart.label, restart.tone], ["Updated to v3.2.0", "restart-app", "Restart Plan2Code", "ok"]);
|
||||
const [problem] = barNextSteps({ newRelease: { problem: "Could not check for updates: git was not found on PATH." } });
|
||||
assert.deepEqual([problem.id, problem.text, problem.action], ["update-check", "Could not check for updates", null], "a missing git is said, not silent");
|
||||
assert.match(problem.title, /git was not found/);
|
||||
const [same] = barNextSteps({ notReplaced: "3.1.0" });
|
||||
assert.deepEqual([same.id, same.text, same.tone, same.action], ["not-replaced", "App not replaced", "warn", null], "the same version after a restart is not 'Updated to'");
|
||||
assert.match(same.title, /no desktop app for this system yet, so Plan2Code is still on v3\.1\.0\./);
|
||||
const [after] = barNextSteps({ updatedTo: "3.2.0" });
|
||||
assert.deepEqual([after.id, after.text, after.tone, after.action], ["updated-to", "Updated to v3.2.0", "ok", null]);
|
||||
});
|
||||
|
||||
test("the app asks once at start for a newer release, and the bar is wired to the copy action", () => {
|
||||
test("releaseAfterCheck: a recheck never replaces a running or finished update, finds a version, reports a problem and clears an old one", () => {
|
||||
assert.deepEqual(releaseAfterCheck(null, { latest: "3.2.0", problem: null }), { latest: "3.2.0" });
|
||||
assert.deepEqual(releaseAfterCheck(null, { latest: null, problem: "Could not check for updates: git was not found on PATH." }), { problem: "Could not check for updates: git was not found on PATH." });
|
||||
assert.equal(releaseAfterCheck({ latest: "3.2.0" }, { latest: null, problem: null }), null, "current now: the old notice goes");
|
||||
assert.equal(releaseAfterCheck({ problem: "x" }, { latest: null, problem: null }), null);
|
||||
const running = { latest: "3.2.0", updating: "Installing" };
|
||||
assert.equal(releaseAfterCheck(running, { latest: "3.2.0" }), running, "an update that runs is left alone");
|
||||
const waiting = { latest: "3.2.0", restartNeeded: true };
|
||||
assert.equal(releaseAfterCheck(waiting, { latest: "3.3.0" }), waiting, "so is one waiting for its restart");
|
||||
assert.equal(releaseAfterCheck(null, null), null, "no answer, nothing to show");
|
||||
assert.equal(UPDATE_RECHECK_MS, 4 * 60 * 60 * 1000, "every few hours, not once per launch");
|
||||
});
|
||||
|
||||
test("reasonSentence keeps the installer's reason readable: a capital and a full stop", () => {
|
||||
assert.equal(reasonSentence("the update did not finish: npm exited with code 1"), "The update did not finish: npm exited with code 1.");
|
||||
assert.equal(reasonSentence("Already a sentence."), "Already a sentence.");
|
||||
assert.equal(reasonSentence(" two spaces "), "Two spaces.");
|
||||
assert.equal(reasonSentence(""), "The update did not finish.");
|
||||
});
|
||||
|
||||
test("the app asks at start and every few hours for a newer release, and the bar is wired to Update and restart", () => {
|
||||
assert.match(APP_JS, /invoke\('check_new_release'\)/);
|
||||
assert.match(APP_JS, /'copy-update': copyUpdateCommand/);
|
||||
assert.match(APP_JS, /barNextSteps\(\{ consoleDead, version: versionState, newRelease \}\)/);
|
||||
assert.match(APP_JS, /setInterval\(checkNewRelease, UPDATE_RECHECK_MS\)/);
|
||||
assert.match(APP_JS, /'update-restart': \(\) => updateAndRestart\(\)/);
|
||||
assert.match(APP_JS, /'restart-app': \(\) => restartApp\(\)/);
|
||||
assert.doesNotMatch(APP_JS, /copyUpdateCommand|'copy-update'/, "the copy-the-command flow is gone");
|
||||
const update = APP_JS.slice(APP_JS.indexOf("async function updateAndRestart"), APP_JS.indexOf("async function restartApp"));
|
||||
assert.match(update, /invoke\('update_to_newest', \{ progress \}\)/, "the unpinned update, through the progress channel");
|
||||
assert.match(update, /setNewRelease\(\{ latest, failed: reasonSentence\(error\) \}\);\s*\n\s*return;/, "a failure returns before any restart");
|
||||
const restart = APP_JS.slice(APP_JS.indexOf("async function restartApp"), APP_JS.indexOf("async function showUpdatedTo"));
|
||||
assert.match(restart, /invoke\('restart_app', \{ confirmed: false \}\)/, "the quit check guards the respawn");
|
||||
assert.match(APP_JS, /if \(state\.updatedFrom\) void showUpdatedTo\(\);/, "Updated to vX once after the restart");
|
||||
const noted = APP_JS.slice(APP_JS.indexOf("async function showUpdatedTo"), APP_JS.indexOf("// The About dialog"));
|
||||
assert.match(noted, /now === appState\.updatedFrom[\s\S]*?notReplaced = now;/, "an unchanged version is said so, never 'Updated to' it");
|
||||
assert.match(APP_JS, /barNextSteps\(\{ consoleDead, version: versionState, newRelease, updatedTo, notReplaced \}\)/);
|
||||
});
|
||||
|
||||
test("each version state reads and acts as the old version bar did", () => {
|
||||
@@ -91,7 +137,7 @@ test("every control that reconnects the console carries the same label, never 'R
|
||||
});
|
||||
|
||||
test("app.js draws the bar's right end through barNextSteps, not a hand-rolled copy of its order", () => {
|
||||
assert.match(APP_JS, /const steps = barNextSteps\(\{ consoleDead, version: versionState, newRelease \}\);/);
|
||||
assert.match(APP_JS, /const steps = barNextSteps\(\{ consoleDead, version: versionState, newRelease, updatedTo, notReplaced \}\);/);
|
||||
for (const gone of ["console-again", "version-update", "permissions-note", "console-status", "project-dir"]) {
|
||||
assert.ok(!INDEX_HTML.includes(`id="${gone}"`), `index.html still has #${gone}`);
|
||||
}
|
||||
@@ -196,12 +242,15 @@ test("app.js never sets statePlannyEl.hidden directly: SVGElement does not refle
|
||||
assert.match(APP_JS, /statePlannyEl\.toggleAttribute\('hidden', !tired\)/);
|
||||
});
|
||||
|
||||
test("the Restart confirmation no longer claims unsaved work, and offers New Session with the tired Planny", () => {
|
||||
const confirmRestart = APP_JS.slice(APP_JS.indexOf("function confirmRestart"), APP_JS.indexOf("function confirmRestart") + 600);
|
||||
assert.doesNotMatch(confirmRestart, /not saved/, "not always true, so it is gone from this dialog specifically");
|
||||
assert.match(confirmRestart, /'Restart the agent on a fresh context window\?',\s*\n\s*'New Session',/);
|
||||
assert.match(confirmRestart, /\{ tired: true \}/, "the confirm dialog asks for the tired Planny");
|
||||
assert.match(INDEX_HTML, /<svg id="dashboard-state-planny"[^>]*hidden>/, "the tired Planny starts hidden in the markup");
|
||||
test("the Restart confirmation is the shell modal, with New Session as its danger verb and Cancel first", () => {
|
||||
const confirmRestart = APP_JS.slice(APP_JS.indexOf("async function confirmRestart"), APP_JS.indexOf("function showTerminal"));
|
||||
assert.match(confirmRestart, /await confirmModal\(\{\s*title: 'Restart the agent on a fresh context window\?'/);
|
||||
assert.match(confirmRestart, /primary: 'New Session',\s*\n\s*danger: true,/);
|
||||
assert.doesNotMatch(confirmRestart, /showState\(\s*'Restart the agent/, "no longer drawn over the dashboard pane");
|
||||
// The first frame is "Starting Plan2Code" with a plain Planny (no mug); showState hides or restyles it from then on.
|
||||
assert.match(INDEX_HTML, /<svg id="dashboard-state-planny" class="is-plain"[^>]*>/, "the plain Planny is in the markup, visible");
|
||||
assert.doesNotMatch(INDEX_HTML, /<svg id="dashboard-state-planny"[^>]*hidden>/);
|
||||
assert.match(INDEX_HTML, /<div id="dashboard-state">\s*[\s\S]*?<p id="dashboard-state-text">Starting Plan2Code<\/p>/, "visible from the first frame, saying so");
|
||||
});
|
||||
|
||||
test("defaultRightFraction gives the terminal a roomy width when the window has space for it, down to the floor when it does not", () => {
|
||||
@@ -228,7 +277,7 @@ test("with nothing saved yet, app.js starts the terminal docked right via defaul
|
||||
// Docked right and collapsed, the terminal panel is a 28px-wide strip: the
|
||||
// collapse button's text used to run horizontally off the edge of it
|
||||
// (visible, unreadable). It now reads top-to-bottom instead.
|
||||
test("docked right and collapsed, the terminal panel's View Agent Terminal button fits the strip instead of overflowing it", async (t) => {
|
||||
test("docked right and collapsed, the terminal panel's pill and expand button fit the strip instead of overflowing it", async (t) => {
|
||||
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
|
||||
const browser = await launchBrowser();
|
||||
try {
|
||||
@@ -238,19 +287,23 @@ test("docked right and collapsed, the terminal panel's View Agent Terminal butto
|
||||
await page.evaluate(() => {
|
||||
document.getElementById("workspace").classList.add("dock-right");
|
||||
document.getElementById("term-panel").classList.add("collapsed");
|
||||
document.getElementById("term-collapse").textContent = "View Agent Terminal";
|
||||
document.getElementById("term-collapse").setAttribute("aria-pressed", "true");
|
||||
document.getElementById("term-badge").hidden = false;
|
||||
});
|
||||
const fit = await page.evaluate(() => {
|
||||
const el = document.getElementById("term-collapse");
|
||||
return {
|
||||
writingMode: getComputedStyle(el).writingMode,
|
||||
overflowsWidth: el.scrollWidth > el.clientWidth,
|
||||
overflowsPanel: el.getBoundingClientRect().right > document.getElementById("term-panel").getBoundingClientRect().right,
|
||||
const panel = document.getElementById("term-panel").getBoundingClientRect();
|
||||
const measure = (id) => {
|
||||
const el = document.getElementById(id);
|
||||
const box = el.getBoundingClientRect();
|
||||
return { writingMode: getComputedStyle(el).writingMode, overflowsWidth: el.scrollWidth > el.clientWidth, spills: box.right > panel.right + 0.5 || box.left < panel.left - 0.5 };
|
||||
};
|
||||
return { pill: measure("term-badge"), expand: measure("term-collapse"), titleShown: getComputedStyle(document.getElementById("term-title")).display !== "none" };
|
||||
});
|
||||
assert.equal(fit.writingMode, "vertical-rl", "the label is set to run top-to-bottom, not sideways");
|
||||
assert.equal(fit.overflowsWidth, false, "the label text does not overflow its own box");
|
||||
assert.equal(fit.overflowsPanel, false, "the button does not spill past the collapsed panel's edge");
|
||||
assert.equal(fit.pill.writingMode, "vertical-rl", "the pill's label runs top-to-bottom, not sideways");
|
||||
assert.equal(fit.pill.overflowsWidth, false, "the pill's text does not overflow its own box");
|
||||
assert.equal(fit.pill.spills, false, "the pill does not spill past the collapsed panel's edge");
|
||||
assert.equal(fit.expand.spills, false, "the expand button does not spill past the collapsed panel's edge");
|
||||
assert.equal(fit.titleShown, false, "the title has no room in the strip");
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
@@ -549,3 +602,698 @@ test("main.rs guards the window's agent and project commands, and registers loop
|
||||
assert.ok(!body("agent_input").includes("refuse_while_looping"), "typing stays open for a trust or login prompt");
|
||||
assert.match(rust, /generate_handler!\[[\s\S]*?loop_stop_now,\s*loop_state,/);
|
||||
});
|
||||
|
||||
// The string literals of a JavaScript source (quoted and template text), with
|
||||
// comments and regular expressions skipped: enough of a tokenizer for the
|
||||
// shell's own files, which the test below holds to the em dash rule (the same
|
||||
// rule quit_prompt.rs's tests hold its strings to).
|
||||
function stringLiterals(source) {
|
||||
const out = [];
|
||||
const braces = []; // one entry per open `${`, holding the brace depth inside it
|
||||
let i = 0;
|
||||
let last = ""; // the last significant code character, to tell a regex from a division
|
||||
const regexCanStart = () => last === "" || "(,=:[!&|?{};+-*%<>~^".includes(last) || /\b(return|typeof|case|in|of)$/.test(source.slice(Math.max(0, i - 7), i));
|
||||
const readTemplate = () => {
|
||||
let text = "";
|
||||
while (i < source.length) {
|
||||
const c = source[i];
|
||||
if (c === "\\") {
|
||||
text += source.slice(i, i + 2);
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (c === "`") {
|
||||
i += 1;
|
||||
out.push(text);
|
||||
return;
|
||||
}
|
||||
if (c === "$" && source[i + 1] === "{") {
|
||||
i += 2;
|
||||
out.push(text);
|
||||
braces.push(0);
|
||||
return;
|
||||
}
|
||||
text += c;
|
||||
i += 1;
|
||||
}
|
||||
};
|
||||
while (i < source.length) {
|
||||
const c = source[i];
|
||||
const next = source[i + 1];
|
||||
if (/\s/.test(c)) {
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (c === "/" && next === "/") {
|
||||
i = source.indexOf("\n", i);
|
||||
if (i < 0) break;
|
||||
continue;
|
||||
}
|
||||
if (c === "/" && next === "*") {
|
||||
i = source.indexOf("*/", i + 2) + 2;
|
||||
continue;
|
||||
}
|
||||
if (c === "'" || c === '"') {
|
||||
let j = i + 1;
|
||||
let text = "";
|
||||
while (j < source.length && source[j] !== c) {
|
||||
if (source[j] === "\\") {
|
||||
text += source.slice(j, j + 2);
|
||||
j += 2;
|
||||
} else {
|
||||
text += source[j];
|
||||
j += 1;
|
||||
}
|
||||
}
|
||||
out.push(text);
|
||||
i = j + 1;
|
||||
last = c;
|
||||
continue;
|
||||
}
|
||||
if (c === "`") {
|
||||
i += 1;
|
||||
readTemplate();
|
||||
last = "`";
|
||||
continue;
|
||||
}
|
||||
if (c === "/" && regexCanStart()) {
|
||||
let j = i + 1;
|
||||
let inClass = false;
|
||||
while (j < source.length && (inClass || source[j] !== "/")) {
|
||||
if (source[j] === "\\") j += 1;
|
||||
else if (source[j] === "[") inClass = true;
|
||||
else if (source[j] === "]") inClass = false;
|
||||
j += 1;
|
||||
}
|
||||
i = j + 1;
|
||||
while (/[a-z]/i.test(source[i] || "")) i += 1;
|
||||
last = "/";
|
||||
continue;
|
||||
}
|
||||
if (braces.length && c === "{") braces[braces.length - 1] += 1;
|
||||
if (braces.length && c === "}") {
|
||||
if (braces[braces.length - 1] === 0) {
|
||||
braces.pop();
|
||||
i += 1;
|
||||
readTemplate();
|
||||
last = "`";
|
||||
continue;
|
||||
}
|
||||
braces[braces.length - 1] -= 1;
|
||||
}
|
||||
last = c;
|
||||
i += 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
test("stringLiterals finds the strings and skips comments and regular expressions", () => {
|
||||
const sample = [
|
||||
"// a comment \u2014 here",
|
||||
"const a = 'one'; /* \u2014 */ const b = \"two\";",
|
||||
"const re = /'not a string'/g;",
|
||||
"const t = `x ${a ? 'in' : `deep ${b}`} y`;",
|
||||
"const half = 4 / 2; const c = 'after / division';",
|
||||
].join("\n");
|
||||
assert.deepEqual(stringLiterals(sample), ["one", "two", "x ", "in", "deep ", "", " y", "after / division"]);
|
||||
assert.ok(stringLiterals("const s = 'bad \u2014 dash';").some((text) => text.includes("\u2014")), "a dash inside a string is seen");
|
||||
assert.ok(stringLiterals("const s = `bad ${x} \u2014 dash`;").some((text) => text.includes("\u2014")), "and inside template text after a placeholder");
|
||||
});
|
||||
|
||||
test("no string in the shell's meter.js or app.js holds an em dash (U+2014)", () => {
|
||||
for (const [name, source, probe] of [["meter.js", METER_JS, "Reload the page"], ["app.js", APP_JS, "Reloading the page..."]]) {
|
||||
const strings = stringLiterals(source);
|
||||
assert.ok(strings.length > 50, `${name}: the tokenizer read its strings (${strings.length})`);
|
||||
assert.ok(strings.includes(probe), `${name}: the scan reaches the messages it guards`);
|
||||
for (const text of strings) assert.ok(!text.includes("\u2014"), `${name}: ${text}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("the first-run checklist's Node row joins version and path with a colon", () => {
|
||||
assert.match(APP_JS, /const nodeDetail = `\$\{state\.nodeVersion \|\| 'found'\} \(18 or newer\)\$\{state\.nodeBinary \? `: \$\{state\.nodeBinary\}` : ''\}`;/);
|
||||
});
|
||||
|
||||
test("commandSegments puts each backticked command in its own piece, and plainCommandText quotes it for a tooltip", () => {
|
||||
assert.deepEqual(commandSegments("not found; run `plan2code update`"), [
|
||||
{ text: "not found; run ", code: false },
|
||||
{ text: "plan2code update", code: true },
|
||||
]);
|
||||
assert.deepEqual(commandSegments("Run `a` then `b`."), [
|
||||
{ text: "Run ", code: false },
|
||||
{ text: "a", code: true },
|
||||
{ text: " then ", code: false },
|
||||
{ text: "b", code: true },
|
||||
{ text: ".", code: false },
|
||||
]);
|
||||
assert.deepEqual(commandSegments("plain"), [{ text: "plain", code: false }]);
|
||||
assert.deepEqual(commandSegments("a stray ` stays"), [{ text: "a stray ` stays", code: false }]);
|
||||
assert.deepEqual(commandSegments(""), []);
|
||||
assert.deepEqual(commandSegments(null), []);
|
||||
assert.equal(plainCommandText("Run `plan2code update` in a terminal."), 'Run "plan2code update" in a terminal.');
|
||||
const [failed] = barNextSteps({ newRelease: { latest: "3.0.1", failed: "The update did not finish." } });
|
||||
assert.ok(commandSegments(failed.title).some((part) => part.code && part.text === NEW_RELEASE_COMMAND), "a failed update names the command it falls back to, marked as one");
|
||||
});
|
||||
|
||||
test("app.js draws commands in <code> for the bar's next step, the agent status line and the checklist, never as literal backticks", () => {
|
||||
assert.match(APP_JS, /function commandNodes\(text\) \{[\s\S]*?document\.createElement\('code'\)[\s\S]*?code\.textContent = part\.text;/, "built as nodes, not parsed markup");
|
||||
assert.match(APP_JS, /nextStepTextEl\.replaceChildren\(\.\.\.commandNodes\(/);
|
||||
assert.match(APP_JS, /nextStepTextEl\.title = first \? plainCommandText\(first\.title\)/);
|
||||
assert.match(APP_JS, /agentStatusEl\.replaceChildren\(\.\.\.commandNodes\(text\)\)/);
|
||||
assert.match(APP_JS, /agentStatusEl\.title = plainCommandText\(text\)/);
|
||||
assert.match(APP_JS, /if \(typeof detail === 'string'\) detailEl\.append\(\.\.\.commandNodes\(detail\)\)/);
|
||||
assert.doesNotMatch(APP_JS, /nextStepTextEl\.textContent =|agentStatusEl\.textContent = text/, "no plain-text path left beside them");
|
||||
});
|
||||
|
||||
test("menuStep moves through a menu's items: Up and Down wrap, Home and End go to the ends", () => {
|
||||
assert.equal(menuStep("ArrowDown", -1, 3), 0, "from outside the items, Down takes the first");
|
||||
assert.equal(menuStep("ArrowUp", -1, 3), 2, "and Up the last");
|
||||
assert.equal(menuStep("ArrowDown", 0, 3), 1);
|
||||
assert.equal(menuStep("ArrowDown", 2, 3), 0, "Down wraps");
|
||||
assert.equal(menuStep("ArrowUp", 0, 3), 2, "Up wraps");
|
||||
assert.equal(menuStep("Home", 2, 3), 0);
|
||||
assert.equal(menuStep("End", 0, 3), 2);
|
||||
assert.equal(menuStep("ArrowDown", 0, 1), 0, "one item stays put");
|
||||
assert.equal(menuStep("ArrowDown", -1, 0), null, "nothing to move to");
|
||||
assert.equal(menuStep("a", 0, 3), null, "any other key is left alone");
|
||||
assert.equal(menuStep("Enter", 0, 3), null);
|
||||
});
|
||||
|
||||
test("opening a bar menu focuses its first item, and Up, Down, Home and End move between items", () => {
|
||||
const toggle = APP_JS.slice(APP_JS.indexOf("function toggleBarMenu"), APP_JS.indexOf("projectMenuBtn.onclick"));
|
||||
assert.match(toggle, /const \[first\] = barMenuItems\(menu\);\s*\(first \|\| menu\)\.focus\(\);/, "the first item, or the menu itself when none can take focus");
|
||||
assert.match(APP_JS, /function barMenuItems\(menu\) \{[\s\S]*?\[role="menuitem"\][\s\S]*?!item\.hidden && !item\.disabled/);
|
||||
assert.match(APP_JS, /menuStep\(event\.key, items\.indexOf\(document\.activeElement\), items\.length\)/);
|
||||
assert.match(APP_JS, /projectMenu\.addEventListener\('keydown', onBarMenuKey\);/);
|
||||
assert.match(APP_JS, /agentMenu\.addEventListener\('keydown', onBarMenuKey\);/);
|
||||
for (const id of ["project-menu", "agent-menu"]) {
|
||||
assert.match(INDEX_HTML, new RegExp(`<div id="${id}"[^>]*role="menu"[^>]*tabindex="-1"`), `#${id} can hold focus when every item is off`);
|
||||
}
|
||||
});
|
||||
|
||||
test("the checklist's marks and the quiet dot are named for a screen reader", () => {
|
||||
const row = APP_JS.slice(APP_JS.indexOf("function firstRunRow"), APP_JS.indexOf("function renderFirstRun"));
|
||||
assert.match(row, /mark\.setAttribute\('role', 'img'\);/);
|
||||
assert.match(row, /mark\.setAttribute\('aria-label', pass \? 'Ready' : 'Needs attention'\);/);
|
||||
// The quiet mark is a labeled pill in words, a button that opens the terminal.
|
||||
assert.match(INDEX_HTML, /<button id="term-badge" type="button"[^>]*>Agent may need you<\/button>/);
|
||||
});
|
||||
|
||||
test("the shell has one :focus-visible ring, from the tokens", () => {
|
||||
const rings = INDEX_HTML.match(/[^{}\n]*:focus-visible[^{]*\{[^}]*outline[^}]*\}/g) || [];
|
||||
assert.equal(rings.length, 1, rings.join("\n"));
|
||||
assert.match(rings[0], /outline: 2px solid var\(--focus-ring, var\(--accent\)\)/);
|
||||
assert.match(rings[0], /\[role="separator"\]/, "the splitter wears the same ring, not the global blue one");
|
||||
assert.match(INDEX_HTML, /#loop-banner \{[^}]*--focus-ring: var\(--banner-color\)/, "the loop banner keeps its own ring color through the token");
|
||||
});
|
||||
|
||||
test("every confirm goes through the shell modal: New Session, Stop now and Change project, with nothing drawn over the dashboard", () => {
|
||||
assert.doesNotMatch(APP_JS, /leaveConfirm|shownStateNow/, "the in-page confirm's put-it-back code is gone with the confirm");
|
||||
const stop = APP_JS.slice(APP_JS.indexOf("loopStopNowBtn.onclick"), APP_JS.indexOf("function renderNextStep"));
|
||||
assert.match(stop, /await confirmModal\(\{\s*title: 'End the agent now\?'/);
|
||||
assert.match(stop, /primary: 'Stop now',\s*\n\s*danger: true,/);
|
||||
const change = APP_JS.slice(APP_JS.indexOf("async function changeProject"), APP_JS.indexOf("changeProjectBtn.onclick"));
|
||||
assert.match(change, /await confirmModal\(\{\s*title: 'Stop the running agent and switch to a different project\?'/);
|
||||
assert.match(change, /if \(!yes\) return;/, "Cancel changes nothing");
|
||||
assert.doesNotMatch(APP_JS, /showState\('No dashboard has loaded yet\./, "no bare-line state is left to land in");
|
||||
const show = APP_JS.slice(APP_JS.indexOf("function showState"), APP_JS.indexOf("function showErrorState"));
|
||||
assert.match(show, /shownState = \{ text, buttonLabel, onButton, onCancel, options \};/);
|
||||
assert.match(APP_JS, /function hideState\(\) \{[^}]*shownState = null;/);
|
||||
});
|
||||
|
||||
test("pageNotShownView: Reload the page first, then 'still did not load' with Reconnect the console first", () => {
|
||||
const first = pageNotShownView(1);
|
||||
assert.equal(first.text, "The console is running but its page did not show in this window.");
|
||||
assert.deepEqual(first.primary, { action: "reload", label: "Reload the page" });
|
||||
assert.equal(first.secondary, null);
|
||||
for (const n of [2, 3, 7]) {
|
||||
const again = pageNotShownView(n);
|
||||
assert.equal(again.text, "The page still did not load.");
|
||||
assert.deepEqual(again.primary, { action: "reconnect", label: "Reconnect the console" });
|
||||
assert.deepEqual(again.secondary, { action: "reload", label: "Reload the page" });
|
||||
}
|
||||
assert.equal(pageNotShownView(2).primary.label, NEXT_STEP_LABELS.reconnect, "the same label as every other reconnect");
|
||||
});
|
||||
|
||||
test("pageDetailsLine carries the session URL with its key hidden and the last health check", () => {
|
||||
assert.equal(redactSessionUrl("http://127.0.0.1:51234/s/AbC_123-xyz"), "http://127.0.0.1:51234/s/...");
|
||||
assert.equal(redactSessionUrl("http://127.0.0.1:51234/s/AbC/?x=1"), "http://127.0.0.1:51234/s/.../?x=1");
|
||||
assert.equal(redactSessionUrl("http://127.0.0.1:51234/"), "http://127.0.0.1:51234/");
|
||||
assert.equal(redactSessionUrl(null), "");
|
||||
assert.equal(pageDetailsLine({ url: "http://127.0.0.1:5000/s/secret", health: "running" }), "Details: session http://127.0.0.1:5000/s/...; health check: running");
|
||||
assert.equal(pageDetailsLine({ url: null, health: null }), "Details: session none; health check: no answer");
|
||||
});
|
||||
|
||||
test("app.js counts page failures in a row, offers stop-then-start, and shows the Details line", () => {
|
||||
const noHello = APP_JS.slice(APP_JS.indexOf("async function onNoHello"), APP_JS.indexOf("function showState"));
|
||||
assert.match(noHello, /pageFailures \+= 1;\s*const view = pageNotShownView\(pageFailures\);/);
|
||||
assert.match(noHello, /const actions = \{ reload: reloadPage, reconnect: stopAndReconnect \};/);
|
||||
assert.match(noHello, /pageDetailsLine\(\{ url: currentUrl \|\| status\.url, health: status\.state \}\)/);
|
||||
assert.match(noHello, /showState\(view\.text, view\.primary\.label, actions\[view\.primary\.action\], undefined, \{ secondary, details \}\)/);
|
||||
assert.match(noHello, /async function stopAndReconnect\(\) \{[\s\S]*?invoke\('console_stop'\)[\s\S]*?await reconnectConsole\(\);/, "stop, then start");
|
||||
assert.match(APP_JS, /kind === 'console-ready'\) \{\s*frameReady = true;\s*pageFailures = 0;/, "a hello ends the run of failures");
|
||||
const announced = APP_JS.slice(APP_JS.indexOf("function showAnnounced"), APP_JS.indexOf("window.__TAURI__.event.listen('console-page'"));
|
||||
assert.match(announced, /pageFailures = 0;/, "a new page starts over");
|
||||
assert.match(INDEX_HTML, /<button id="dashboard-state-secondary" hidden><\/button>/);
|
||||
assert.match(INDEX_HTML, /<p id="dashboard-state-details" hidden><\/p>/);
|
||||
assert.match(INDEX_HTML, /#dashboard-state-details \{[^}]*color: var\(--ink-3\)/, "muted");
|
||||
});
|
||||
|
||||
// ---- Phase 9: the shell shares the console's tokens and theme ----
|
||||
|
||||
const SHADES_LIGHT = ["#206cc3", "#ecf2f9", "#ffffff", "#9ab4d3"];
|
||||
const SHADES_DARK = ["#619fe5", "#1a2533", "#0c1117", "#3d5978"];
|
||||
|
||||
test("looksFromMessage takes the resolved theme with both shade sets, and nothing that does not match their shapes", () => {
|
||||
assert.deepEqual(looksFromMessage({ plan2code: "looks", accent: SHADES_DARK, theme: "light", light: SHADES_LIGHT, dark: SHADES_DARK }), { theme: "light", light: SHADES_LIGHT, dark: SHADES_DARK });
|
||||
assert.deepEqual(looksFromMessage({ theme: "dark", light: SHADES_LIGHT, dark: SHADES_DARK }).theme, "dark");
|
||||
assert.deepEqual(looksFromMessage({ accent: SHADES_DARK }), { theme: "dark", light: null, dark: SHADES_DARK }, "a page that predates the theme keeps the shell dark in its highlight");
|
||||
for (const bad of [
|
||||
null, undefined, "dark", 7, [], {},
|
||||
{ theme: "system", light: SHADES_LIGHT, dark: SHADES_DARK },
|
||||
{ theme: "dark", light: SHADES_LIGHT },
|
||||
{ theme: "dark", dark: SHADES_DARK },
|
||||
{ theme: "dark", light: SHADES_LIGHT, dark: ["#619fe5", "#1a2533", "#0c1117"] },
|
||||
{ theme: "dark", light: SHADES_LIGHT, dark: ["#619fe5", "#1a2533", "#0c1117", "red"] },
|
||||
{ theme: "dark", light: SHADES_LIGHT, dark: ["#619fe5", "#1a2533", "#0c1117", "#3d5978; x:y"] },
|
||||
{ theme: "dark", light: SHADES_LIGHT, dark: ["#619fe5", "#1a2533", "#0c1117", 5] },
|
||||
{ accent: ["#619fe5", "red", "#0c1117", "#3d5978"] },
|
||||
]) assert.equal(looksFromMessage(bad), null, JSON.stringify(bad));
|
||||
});
|
||||
|
||||
test("the shell applies the looks message through meter.js and keeps the theme beside the accent for the next launch", () => {
|
||||
assert.match(APP_JS, /const looks = looksFromMessage\(event\.data\);\s+if \(looks\) applyLooks\(looks, \{ save: true \}\);/);
|
||||
assert.match(APP_JS, /root\.setAttribute\('data-theme', theme\);/);
|
||||
assert.match(APP_JS, /localStorage\.setItem\(THEME_KEY, theme\);\s+localStorage\.setItem\(ACCENT_KEY, JSON\.stringify\(\{ light, dark \}\)\);/);
|
||||
assert.match(APP_JS, /terminal\.applyTheme\(\);\s+setWindowTheme\(theme\);/, "the terminal and the OS title bar follow every change");
|
||||
assert.match(APP_JS, /getCurrentWindow\(\)\.setTheme\(theme\)/);
|
||||
assert.doesNotMatch(APP_JS, /applyAccent/, "the dark-only accent path is gone");
|
||||
const early = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/theme-early.js"), "utf8");
|
||||
assert.match(early, /p2c-app:theme/);
|
||||
assert.match(early, /p2c-app:accent/);
|
||||
assert.match(INDEX_HTML, /<script src="theme-early\.js"><\/script>/, "a classic script in the head, so it runs before the first paint");
|
||||
assert.ok(INDEX_HTML.indexOf("theme-early.js") < INDEX_HTML.indexOf("<style>"));
|
||||
assert.match(APP_JS, /getCurrentWindow\(\)\.show\(\)/, "the window opens hidden and is shown on the first paint");
|
||||
const conf = JSON.parse(fs.readFileSync(path.join(HERE, "../plan2code-app/src-tauri/tauri.conf.json"), "utf8"));
|
||||
const win = conf.app.windows[0];
|
||||
assert.equal(win.visible, false);
|
||||
assert.equal(win.maximized, undefined, "maximizing is left to the first run in main.rs");
|
||||
assert.ok(win.minWidth >= 900 && win.minHeight >= 500);
|
||||
assert.match(win.backgroundColor, /^#[0-9a-f]{6}$/i);
|
||||
});
|
||||
|
||||
test("the console's looks message carries the resolved theme and both shade sets", () => {
|
||||
const looksJs = fs.readFileSync(path.join(HERE, "../src/web-console/public/looks.js"), "utf8");
|
||||
assert.match(looksJs, /tellApp\("looks", \{ accent: ACCENTS\[looks\.accent\]\.dark, theme: effectiveTheme\(\), light: ACCENTS\[looks\.accent\]\.light, dark: ACCENTS\[looks\.accent\]\.dark \}\);/);
|
||||
const screen = fs.readFileSync(path.join(HERE, "../src/web-console/public/screens/looks.js"), "utf8");
|
||||
assert.match(screen, /matchMedia\("\(prefers-color-scheme: dark\)"\)\.addEventListener\("change", \(\) => \{\s+if \(looks\.theme === "system"\) \{\s+applyLooks\(\);/, "a system theme flip re-runs applyLooks, which tells the shell; looks.js adds no second listener");
|
||||
assert.doesNotMatch(looksJs, /addEventListener\("change"/);
|
||||
});
|
||||
|
||||
test("the shell takes its colors from the console's tokens.css, copied by vendor.mjs, and holds no literal color", () => {
|
||||
const vendor = fs.readFileSync(path.join(HERE, "../plan2code-app/scripts/vendor.mjs"), "utf8");
|
||||
assert.match(vendor, /'\.\.\/src\/web-console\/public\/styles\/tokens\.css', 'tokens\.css'/);
|
||||
const link = INDEX_HTML.indexOf('href="vendor/tokens.css"');
|
||||
assert.ok(link > 0 && link < INDEX_HTML.indexOf("<style>"), "linked before the shell's own styles");
|
||||
const css = INDEX_HTML.slice(INDEX_HTML.indexOf("<style>"), INDEX_HTML.indexOf("</style>")).replace(/\/\*[\s\S]*?\*\//g, "");
|
||||
assert.doesNotMatch(css, /#[0-9a-fA-F]{3,8}\b/, "no hex color left in the styles");
|
||||
assert.doesNotMatch(css, /\brgba?\(/, "no rgb color left in the styles");
|
||||
assert.doesNotMatch(css, /:root\s*\{[^}]*--(panel|ink|accent)\b/, "the dark token block is gone");
|
||||
});
|
||||
|
||||
test("the terminal's font steps stay inside the saved range and the keys reach nothing else", () => {
|
||||
assert.equal(TERMINAL_FONT_DEFAULT, 13);
|
||||
assert.equal(terminalFontStep("+", 13), 14);
|
||||
assert.equal(terminalFontStep("=", 13), 14);
|
||||
assert.equal(terminalFontStep("-", 13), 12);
|
||||
assert.equal(terminalFontStep("0", 20), 13);
|
||||
assert.equal(terminalFontStep("+", TERMINAL_FONT_MAX), TERMINAL_FONT_MAX);
|
||||
assert.equal(terminalFontStep("-", TERMINAL_FONT_MIN), TERMINAL_FONT_MIN);
|
||||
assert.equal(terminalFontStep("a", 13), null);
|
||||
assert.equal(terminalFontStep("_", 13), null, "Ctrl+Shift+minus is a readline undo, left to the agent");
|
||||
assert.equal(terminalFontStep("ArrowUp", 13), null);
|
||||
assert.equal(terminalFontStep("+", NaN), 14, "no size yet steps from the default");
|
||||
const term = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/terminal.js"), "utf8");
|
||||
assert.match(term, /\(event\.ctrlKey \|\| event\.metaKey\) && !event\.altKey/);
|
||||
assert.match(term, /terminalFontStep\(event\.key, term\.options\.fontSize\)/);
|
||||
assert.match(APP_JS, /invoke\('save_terminal_font_size', \{ size \}\)/);
|
||||
assert.match(APP_JS, /terminal\.setFontSize\(Number\.isInteger\(state\.terminalFontSize\)/);
|
||||
});
|
||||
|
||||
// WCAG contrast of one #rrggbb against another.
|
||||
function luminance(hex) {
|
||||
const [r, g, b] = [1, 3, 5].map((i) => parseInt(hex.slice(i, i + 2), 16) / 255).map((c) => (c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4));
|
||||
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
|
||||
}
|
||||
const contrast = (a, b) => {
|
||||
const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
|
||||
return (hi + 0.05) / (lo + 0.05);
|
||||
};
|
||||
|
||||
test("the terminal's two ANSI palettes hold sixteen colors each and stay readable on the panel they sit on", () => {
|
||||
const names = ["black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", "brightBlack", "brightRed", "brightGreen", "brightYellow", "brightBlue", "brightMagenta", "brightCyan", "brightWhite"];
|
||||
const tokens = fs.readFileSync(path.join(HERE, "../src/web-console/public/styles/tokens.css"), "utf8");
|
||||
const panels = { light: /:root \{[\s\S]*?--panel: (#[0-9a-f]{6})/.exec(tokens)[1], dark: /@media \(prefers-color-scheme: dark\) \{[\s\S]*?--panel: (#[0-9a-f]{6})/.exec(tokens)[1] };
|
||||
for (const theme of ["light", "dark"]) {
|
||||
const palette = terminalAnsi(theme);
|
||||
assert.deepEqual(Object.keys(palette), names, theme);
|
||||
for (const name of names) {
|
||||
assert.match(palette[name], /^#[0-9a-f]{6}$/i);
|
||||
// ANSI black on a dark screen is a background shade by nature.
|
||||
if (theme === "dark" && name === "black") continue;
|
||||
const ratio = contrast(palette[name], panels[theme]);
|
||||
assert.ok(ratio >= (name === "brightBlack" ? 4.4 : 3), `${theme} ${name} ${palette[name]} on ${panels[theme]} is only ${ratio.toFixed(2)}:1`);
|
||||
}
|
||||
}
|
||||
assert.equal(terminalAnsi("system"), TERMINAL_ANSI.dark, "anything but light is dark");
|
||||
assert.equal(hexToRgba("#619fe5", 0.35), "rgba(97, 159, 229, 0.35)");
|
||||
assert.equal(hexToRgba("nope", 0.5), "rgba(128, 128, 128, 0.5)");
|
||||
const term = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/terminal.js"), "utf8");
|
||||
assert.match(term, /fontFamily: token\('--mono'/, "the console's mono stack");
|
||||
assert.match(term, /term\.options\.theme = buildTheme\(\)/, "reapplied on every looks message");
|
||||
assert.match(term, /cursor: accent/);
|
||||
});
|
||||
|
||||
test("the splitter steps by 2% along the dock, clamps, and Home and End go to the ends", () => {
|
||||
const opts = { min: 0.1, max: 0.6 };
|
||||
const near = (a, b) => assert.ok(Math.abs(a - b) < 1e-9, `${a} vs ${b}`);
|
||||
near(splitterFraction("ArrowUp", 0.25, "bottom", opts), 0.27);
|
||||
near(splitterFraction("ArrowDown", 0.25, "bottom", opts), 0.23);
|
||||
near(splitterFraction("ArrowLeft", 0.25, "right", opts), 0.27);
|
||||
near(splitterFraction("ArrowRight", 0.25, "right", opts), 0.23);
|
||||
assert.equal(splitterFraction("ArrowLeft", 0.25, "bottom", opts), null, "the other axis is not its key");
|
||||
assert.equal(splitterFraction("ArrowUp", 0.25, "right", opts), null);
|
||||
assert.equal(splitterFraction("Home", 0.25, "bottom", opts), 0.1);
|
||||
assert.equal(splitterFraction("End", 0.25, "right", opts), 0.6);
|
||||
assert.equal(splitterFraction("ArrowUp", 0.6, "bottom", opts), 0.6);
|
||||
assert.equal(splitterFraction("ArrowDown", 0.1, "bottom", opts), 0.1);
|
||||
assert.equal(splitterFraction("a", 0.25, "bottom", opts), null);
|
||||
assert.deepEqual(splitterAria(0.254, opts), { now: 25, min: 10, max: 60 });
|
||||
});
|
||||
|
||||
test("the splitter is a keyboard-usable separator with a 6px hit area and a 1px line", () => {
|
||||
assert.match(INDEX_HTML, /<div id="term-handle" role="separator" aria-orientation="horizontal"[^>]*aria-valuenow="25"[^>]*tabindex="0"/);
|
||||
assert.match(INDEX_HTML, /#workspace:not\(\.dock-right\) #term-handle \{ height: 6px;/);
|
||||
assert.match(INDEX_HTML, /#workspace\.dock-right #term-handle \{ width: 6px;/);
|
||||
assert.match(INDEX_HTML, /#term-handle::after \{[^}]*background: var\(--rule\)/);
|
||||
assert.match(INDEX_HTML, /#term-handle:hover::after, #term-handle:focus-visible::after, #term-handle\.is-dragging::after \{ background: var\(--accent\); \}/);
|
||||
assert.match(APP_JS, /termHandle\.addEventListener\('keydown'[\s\S]*?splitterFraction\(event\.key,/);
|
||||
assert.match(APP_JS, /termHandle\.addEventListener\('dblclick', \(\) => \{\s+paneFraction = defaultPaneFraction\(\);/);
|
||||
assert.match(APP_JS, /termHandle\.setAttribute\('aria-orientation', paneDock === 'right' \? 'vertical' : 'horizontal'\);/);
|
||||
});
|
||||
|
||||
test("the terminal toolbar has a title, labeled icon buttons and a labeled pill that opens the terminal", () => {
|
||||
assert.equal(terminalTitle("Claude Code"), "Terminal \u00b7 Claude Code");
|
||||
assert.equal(terminalTitle(""), "Terminal");
|
||||
assert.equal(terminalTitle(), "Terminal");
|
||||
assert.match(INDEX_HTML, /<span id="term-title">Terminal<\/span>/);
|
||||
for (const id of ["term-dock", "term-maximize", "term-collapse"]) {
|
||||
const tag = new RegExp(`<button id="${id}" class="term-icon"[^>]*aria-label="[^"]+"[^>]*title="[^"]+"`);
|
||||
assert.match(INDEX_HTML, tag, `#${id} is an icon button that names itself`);
|
||||
}
|
||||
assert.doesNotMatch(APP_JS, /term(Dock|Maximize|Collapse)Btn\.textContent/, "no changing text on the three buttons");
|
||||
assert.match(APP_JS, /termTitleEl\.textContent = terminalTitle\(/);
|
||||
assert.match(APP_JS, /termBadgeEl\.onclick = \(\) => \{\s+if \(paneCollapsed\) \{[^}]*?termCollapseBtn\.click\(\);\s+terminal\.focus\(\);\s+return;\s+\}/, "a collapsed terminal expands, then takes the focus once its layout is back");
|
||||
assert.match(APP_JS, /terminal\.focus\(\);\s+\};/);
|
||||
});
|
||||
|
||||
test("a small pane docked right keeps its whole toolbar inside it when the pill shows", async (t) => {
|
||||
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
|
||||
const browser = await launchBrowser();
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 1280, height: 700 } });
|
||||
page.on("pageerror", () => {});
|
||||
await page.goto(pathToFileURL(INDEX_HTML_PATH).href);
|
||||
await page.evaluate(() => {
|
||||
document.getElementById("workspace").classList.add("dock-right");
|
||||
document.getElementById("term-panel").style.width = "192px";
|
||||
document.getElementById("term-badge").hidden = false;
|
||||
document.getElementById("term-title").textContent = "Terminal \u00b7 Claude Code";
|
||||
});
|
||||
const spill = await page.evaluate(() => {
|
||||
const panel = document.getElementById("term-panel").getBoundingClientRect();
|
||||
return ["term-dock", "term-maximize", "term-collapse", "term-badge"].map((id) => ({ id, past: document.getElementById(id).getBoundingClientRect().right - panel.right }));
|
||||
});
|
||||
for (const { id, past } of spill) assert.ok(past <= 0.5, `#${id} spills ${past}px past the panel's edge`);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("barFit drops the model text first, then the status line, and only when the row is too narrow", () => {
|
||||
assert.deepEqual(barFit({ available: 900, needed: 800, model: 200, status: 150 }), { model: true, status: true });
|
||||
assert.deepEqual(barFit({ available: 800, needed: 800, model: 200, status: 150 }), { model: true, status: true }, "exactly fitting is fitting");
|
||||
assert.deepEqual(barFit({ available: 700, needed: 800, model: 200, status: 150 }), { model: false, status: true });
|
||||
assert.deepEqual(barFit({ available: 500, needed: 800, model: 200, status: 150 }), { model: false, status: false });
|
||||
assert.deepEqual(barFit({ available: 500, needed: 800 }), { model: false, status: false }, "no parts measured, none claimed");
|
||||
});
|
||||
|
||||
test("the top bar collapses instead of scrolling, and +N more is a button that lists the other steps", () => {
|
||||
assert.doesNotMatch(INDEX_HTML, /#bar-row \{[^}]*overflow-x: auto/, "no sideways scrolling row");
|
||||
assert.match(INDEX_HTML, /#bar-row\.no-model #agent-model, #bar-row\.no-status #agent-status \{ display: none; \}/);
|
||||
assert.match(APP_JS, /new ResizeObserver\(scheduleFitBar\)\.observe\(barRowEl\);/);
|
||||
assert.match(APP_JS, /barFit\(\{ available: barRowEl\.clientWidth, needed: barRowEl\.scrollWidth, model, status \}\)/);
|
||||
assert.doesNotMatch(APP_JS, /barRowEl\.addEventListener\('scroll'/);
|
||||
assert.match(INDEX_HTML, /<button id="next-step-more" type="button" aria-haspopup="menu" aria-expanded="false" aria-controls="more-menu" hidden><\/button>/);
|
||||
assert.match(INDEX_HTML, /<div id="more-menu" class="bar-dropdown" role="menu"[^>]*tabindex="-1" hidden><\/div>/);
|
||||
assert.match(APP_JS, /nextStepMoreEl\.onclick = \(\) => toggleBarMenu\(nextStepMoreEl, moreMenu\);/);
|
||||
const more = APP_JS.slice(APP_JS.indexOf("function renderMoreMenu"), APP_JS.indexOf("function setVersionState"));
|
||||
assert.match(more, /commandNodes\(step\.title\)/, "the full sentence, a failed update's last line included");
|
||||
assert.match(more, /NEXT_STEP_ACTIONS\[step\.action\]/, "each step's own action");
|
||||
assert.doesNotMatch(APP_JS, /nextStepMoreEl\.title =/, "no longer only in a tooltip");
|
||||
});
|
||||
|
||||
test("the Node.js check's result reaches the page after the window opens, and the first-run checklist waits for it", () => {
|
||||
assert.match(APP_JS, /async function awaitNodeStatus\(state\) \{\s+if \(state\.nodeChecked\) return;/);
|
||||
assert.match(APP_JS, /event\.listen\('node-status', \(event\) => finish\(event\.payload\)\)/);
|
||||
assert.match(APP_JS, /if \(!state\.firstRunDone\) await awaitNodeStatus\(state\);\s+afterProjectKnown\(\);/);
|
||||
const main = fs.readFileSync(path.join(HERE, "../plan2code-app/src-tauri/src/main.rs"), "utf8");
|
||||
assert.match(main, /spawn_node_check\(app\.handle\(\)\.clone\(\)\)/, "the check runs off the main thread");
|
||||
assert.match(main, /app\.emit\("node-status"/);
|
||||
});
|
||||
|
||||
// ---- Phase 10: waits, friendly errors, the confirm modal, shortcuts, links and the clipboard ----
|
||||
|
||||
test("waitingView: quiet for 12 s, then says where to look; an ended agent says so at once with Change agent", () => {
|
||||
assert.equal(STILL_WAITING_MS, 12000);
|
||||
assert.deepEqual(waitingView({ waitedMs: 0, agentState: "running" }), { still: false, text: null, showTerminal: false, changeAgent: false });
|
||||
assert.equal(waitingView({ waitedMs: STILL_WAITING_MS - 1, agentState: "running" }).still, false);
|
||||
const late = waitingView({ waitedMs: STILL_WAITING_MS, agentState: "running" });
|
||||
assert.deepEqual(late, { still: true, text: STILL_WAITING_TEXT, showTerminal: true, changeAgent: false });
|
||||
assert.equal(STILL_WAITING_TEXT, "Still waiting. The agent may be asking you something in its terminal.");
|
||||
const ended = waitingView({ waitedMs: 500, agentState: "ended" });
|
||||
assert.deepEqual([ended.still, ended.showTerminal, ended.changeAgent], [true, true, true], "no need to wait 12 s for an agent that is gone");
|
||||
});
|
||||
|
||||
test("friendlyError maps each known raw message to a sentence with a next step and keeps the raw text for Details", () => {
|
||||
const cases = [
|
||||
["console open printed no JSON: Error: spawn", /did not start properly.*Reconnect the console/],
|
||||
["console open failed: node: command not found", /could not be opened/],
|
||||
["console stop failed: busy", /did not stop cleanly/],
|
||||
["the web console is not installed (looked in $PLAN2CODE_CONSOLE_DIR, a and b)", /skills are missing.*plan2code update/],
|
||||
["The installed Plan2Code console is too old to show inside the app. Press Update skills, then try again.", /too old for this app.*Update skills/],
|
||||
["no agent has been started", /no agent to restart yet/],
|
||||
["no project folder chosen", /Choose a project folder first/],
|
||||
["an agent is already running for this project", /already running.*New Session/],
|
||||
["could not start the agent: spawn ENOENT", /could not start.*installed/],
|
||||
["Could not do that: no agent has been started", /no agent to restart yet/],
|
||||
["busy", /console is busy/],
|
||||
];
|
||||
for (const [raw, pattern] of cases) {
|
||||
const out = friendlyError(raw);
|
||||
assert.match(out.text, pattern, raw);
|
||||
assert.equal(out.details, raw, `the raw text is kept behind Details: ${raw}`);
|
||||
assert.match(out.text, /[.]$/, "a sentence");
|
||||
assert.doesNotMatch(out.text, /^[a-z]/, "no lowercase raw text as the headline");
|
||||
}
|
||||
});
|
||||
|
||||
test("friendlyError words an unknown error by what was being done, and an empty one as nothing", () => {
|
||||
assert.deepEqual(friendlyError("EPERM: operation not permitted", "start the agent"), { text: "Could not start the agent. Try again.", details: "EPERM: operation not permitted" });
|
||||
assert.deepEqual(friendlyError("weird", ""), { text: "That did not work. Try again.", details: "weird" });
|
||||
assert.deepEqual(friendlyError("", "x"), { text: "", details: "" });
|
||||
assert.deepEqual(friendlyError(null), { text: "", details: "" });
|
||||
assert.deepEqual(friendlyError(new Error("boom"), "do that"), { text: "Could not do that. Try again.", details: "Error: boom" });
|
||||
});
|
||||
|
||||
test("endedView: exit code 0 is 'closed normally' and the bar no longer says 'ended' for it", () => {
|
||||
assert.deepEqual(endedView("exited with code 0"), { bar: "closed", sentence: "closed normally", normal: true });
|
||||
assert.deepEqual(endedView("exited with code 2"), { bar: "ended", sentence: "stopped with an error (exit code 2)", normal: false });
|
||||
assert.equal(endedView("was ended by a signal (SIGKILL)").sentence, "was ended from outside the app (SIGKILL)");
|
||||
assert.equal(endedView("stopped: pty gone").sentence, "ended: stopped: pty gone");
|
||||
assert.equal(endedView("").sentence, "ended");
|
||||
assert.match(APP_JS, /endedView\(agent\.reason\)/, "the bar, the menu and the terminal line all read the same words");
|
||||
assert.doesNotMatch(APP_JS, /ended: \$\{agent\.reason\}/, "no raw reason pasted into the terminal line or the menu");
|
||||
});
|
||||
|
||||
test("app.js shows raw errors through friendlyError, never as 'Could not ...: ${error}' text", () => {
|
||||
assert.doesNotMatch(APP_JS, /Could not (?:start the agent|open the install page|open the setup page|type continue|switch project|read the app state): \$\{/, "the old raw-text sites are gone");
|
||||
assert.doesNotMatch(APP_JS, /The console could not be reached: \$\{/);
|
||||
assert.doesNotMatch(APP_JS, /Could not (?:read the recent folders|open the folder picker|open \$\{row\.dir\}): \$\{/, "the folder picker's errors are in plain words too");
|
||||
assert.match(APP_JS, /setFolderPickerError\(error, 'read the recent folders'\)/);
|
||||
assert.doesNotMatch(APP_JS, /Could not do that: \$\{/);
|
||||
assert.match(APP_JS, /function showErrorState\(raw, action, buttonLabel, onButton, onCancel\) \{\s*const friendly = friendlyError\(raw, action\);/);
|
||||
assert.match(APP_JS, /showErrorState\(error, 'reach the console', 'Retry', reconnectConsole\)/);
|
||||
assert.match(APP_JS, /setAgentError\(error, 'start the agent'\)/);
|
||||
assert.match(INDEX_HTML, /<button id="dashboard-state-toggle"[^>]*>Details<\/button>/, "the raw text sits behind Details");
|
||||
assert.match(APP_JS, /agentStatusEl\.addEventListener\('click', openStatusDetails\)/, "a press on the bar's error opens it in full");
|
||||
});
|
||||
|
||||
test("one busy style for every wait, and the wait timer: waits start through beginWait and end when the page arrives", () => {
|
||||
assert.match(APP_JS, /const busy = options\.busy !== undefined \? options\.busy : !buttonLabel && !onCancel;/);
|
||||
assert.match(APP_JS, /beginWait\('Waiting for the agent to open the dashboard\.\.\.'\)/);
|
||||
assert.match(APP_JS, /beginWait\('Starting the agent\.\.\.'\)/);
|
||||
assert.match(APP_JS, /function showAnnounced\(notice\) \{\s*endWait\(\);/);
|
||||
const tick = APP_JS.slice(APP_JS.indexOf("function tickWait"), APP_JS.indexOf("function hideState"));
|
||||
assert.match(tick, /waitingView\(\{ waitedMs: Date\.now\(\) - waitStartedAt, agentState: agent\.state \}\)/);
|
||||
assert.match(tick, /'Show the terminal', showTerminal/);
|
||||
assert.match(tick, /label: 'Change agent'/);
|
||||
for (const line of ["Reconnecting to the console...", "Opening the page...", "Reloading the page...", "Opening the dashboard...", "The console stopped. Reconnecting..."]) {
|
||||
assert.ok(APP_JS.includes(`'${line}'`), `progress line shares the ellipsis: ${line}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("confirmButtons puts the safe button first with focus and the danger verb last; trapTab wraps in both directions", () => {
|
||||
assert.deepEqual(confirmButtons(), { order: ["cancel", "primary"], focus: "cancel" });
|
||||
assert.deepEqual(confirmButtons({ safeFirst: true }), { order: ["cancel", "primary"], focus: "cancel" });
|
||||
assert.deepEqual(confirmButtons({ safeFirst: false }), { order: ["primary", "cancel"], focus: "primary" });
|
||||
assert.equal(trapTab(false, 0, 2), 1);
|
||||
assert.equal(trapTab(false, 1, 2), 0, "forward from the last wraps to the first");
|
||||
assert.equal(trapTab(true, 0, 2), 1, "back from the first wraps to the last");
|
||||
assert.equal(trapTab(false, -1, 2), 0, "focus outside comes in at the first");
|
||||
assert.equal(trapTab(true, -1, 2), 1);
|
||||
assert.equal(trapTab(false, 0, 0), null);
|
||||
});
|
||||
|
||||
test("the confirm modal is an alertdialog in the shell, outside the frame, with the rest of the shell inert while it asks", () => {
|
||||
assert.match(INDEX_HTML, /<div id="confirm-modal" hidden>\s*<div id="confirm-panel" role="alertdialog" aria-modal="true" aria-labelledby="confirm-title" aria-describedby="confirm-body" tabindex="-1">/);
|
||||
assert.ok(INDEX_HTML.indexOf('id="confirm-modal"') > INDEX_HTML.indexOf('<section id="term-panel"'), "a sibling after the workspace (and its frame), never inside either");
|
||||
const modal = APP_JS.slice(APP_JS.indexOf("function confirmModal"), APP_JS.indexOf("// The Rust side asks for a confirm too"));
|
||||
assert.match(modal, /for \(const part of shellParts\(\)\) part\.inert = true;/);
|
||||
assert.match(modal, /for \(const part of shellParts\(\)\) part\.inert = false;/);
|
||||
assert.match(modal, /event\.key !== 'Escape' \|\| confirmModalEl\.hidden[\s\S]*?stopImmediatePropagation\(\);\s*closeConfirm\(false\)/, "Escape cancels, heard on the document in the capture phase so a scrim click does not lose it");
|
||||
assert.match(APP_JS, /if \(event\.defaultPrevented \|\| event\.key !== 'Escape' \|\| folderPickerEl\.hidden\) return;/, "and a handled Escape never closes the folder picker behind it");
|
||||
assert.match(APP_JS, /listen\('confirm-cancel'/, "the Rust side can take a request back");
|
||||
assert.match(modal, /confirmButtons\(\{ safeFirst: primary \? safeFirst : true \}\)/);
|
||||
assert.match(modal, /\(layout\.focus === 'cancel' \? confirmCancelBtn : confirmPrimaryBtn\)\.focus\(\)/, "focus goes to the safe button");
|
||||
assert.match(modal, /\{ kind: 'callout'|item\.kind === 'callout'/, "an amber callout line is allowed");
|
||||
assert.match(modal, /document\.createElement\('pre'\)/, "and a code block");
|
||||
assert.match(INDEX_HTML, /#confirm-body \.confirm-callout \{[^}]*--stage/, "the callout is amber");
|
||||
assert.match(APP_JS, /listen\('confirm-request'/, "Rust's own confirms (loop start, the quit check) arrive as requests");
|
||||
assert.match(APP_JS, /invoke\('confirm_answer', \{ id: req\.id, yes \}\)/);
|
||||
});
|
||||
|
||||
test("shortcutAction: Ctrl or Cmd with the table's keys, never with Alt, and the other platform's modifier is no chord", () => {
|
||||
const key = (k, mods = {}) => ({ key: k, ctrlKey: false, metaKey: false, shiftKey: false, altKey: false, ...mods });
|
||||
assert.deepEqual(SHORTCUTS.map((s) => s.id), ["toggle-terminal", "focus-console", "focus-terminal", "new-session", "change-project", "preferences"]);
|
||||
for (const [k, id, mods] of [["`", "toggle-terminal", {}], ["1", "focus-console", {}], ["2", "focus-terminal", {}], ["N", "new-session", { shiftKey: true }], ["o", "change-project", {}], [",", "preferences", {}]]) {
|
||||
assert.equal(shortcutAction(key(k, { ctrlKey: true, ...mods })), id, `Ctrl+${k}`);
|
||||
assert.equal(shortcutAction(key(k, { metaKey: true, ...mods }), { mac: true }), id, `Cmd+${k}`);
|
||||
assert.equal(shortcutAction(key(k, { metaKey: true, ...mods })), null, `Cmd is no chord on Windows or Linux: ${k}`);
|
||||
assert.equal(shortcutAction(key(k, { ctrlKey: true, ...mods }), { mac: true }), null, `Ctrl is no chord on a Mac: ${k}`);
|
||||
assert.equal(shortcutAction(key(k, { ctrlKey: true, altKey: true, ...mods })), null, `Alt cancels it: ${k}`);
|
||||
}
|
||||
assert.equal(shortcutAction(key("n", { ctrlKey: true })), null, "New Session needs Shift (plain Ctrl+N is not taken)");
|
||||
assert.equal(shortcutAction(key("`", { ctrlKey: true, shiftKey: true })), null);
|
||||
assert.equal(shortcutAction(key("w", { ctrlKey: true })), null);
|
||||
assert.equal(shortcutAction(null), null);
|
||||
});
|
||||
|
||||
test("Ctrl+O in the terminal on Windows and Linux stays the agent's own (Claude Code's transcript); a Mac and the page still get Change project", () => {
|
||||
const ctrlO = { key: "o", ctrlKey: true, metaKey: false, shiftKey: false, altKey: false };
|
||||
assert.equal(shortcutAction(ctrlO, { inTerminal: true }), null);
|
||||
assert.equal(shortcutAction(ctrlO, { inTerminal: false }), "change-project");
|
||||
assert.equal(shortcutAction({ ...ctrlO, ctrlKey: false, metaKey: true }, { mac: true, inTerminal: true }), "change-project");
|
||||
assert.equal(shortcutAction({ ...ctrlO, key: "`" }, { inTerminal: true }), "toggle-terminal", "every other chord works from the terminal");
|
||||
});
|
||||
|
||||
test("shortcut tooltips name the chord for the platform, and the page can only ask for an id in the table", () => {
|
||||
assert.equal(shortcutLabel("new-session"), "Ctrl+Shift+N");
|
||||
assert.equal(shortcutLabel("new-session", true), "Cmd+Shift+N");
|
||||
assert.equal(shortcutLabel("toggle-terminal"), "Ctrl+`");
|
||||
assert.equal(shortcutLabel("preferences", true), "Cmd+,");
|
||||
assert.equal(shortcutLabel("nope"), "");
|
||||
assert.equal(tipWithShortcut("Change project", "change-project"), "Change project (Ctrl+O)");
|
||||
assert.equal(tipWithShortcut("x", "nope"), "x");
|
||||
assert.equal(shortcutFromMessage({ plan2code: "shortcut", id: "new-session" }), "new-session");
|
||||
for (const bad of [{ id: "rm -rf" }, { id: 3 }, {}, null, undefined]) assert.equal(shortcutFromMessage(bad), null);
|
||||
});
|
||||
|
||||
test("the console page's forwarded keys are the shell's table: the same ids, keys and Shift", async () => {
|
||||
const bridge = await import(pathToFileURL(path.join(HERE, "../src/web-console/public/app-bridge.js")).href);
|
||||
assert.deepEqual(
|
||||
bridge.SHORTCUT_KEYS.map(({ id, key, shift }) => ({ id, key, shift })),
|
||||
SHORTCUTS.map(({ id, key, shift }) => ({ id, key, shift }))
|
||||
);
|
||||
assert.equal(bridge.shortcutIdFor({ key: "2", ctrlKey: true, metaKey: false, shiftKey: false, altKey: false }, false), "focus-terminal");
|
||||
assert.equal(bridge.shortcutIdFor({ key: "2", ctrlKey: true, metaKey: false, shiftKey: false, altKey: false }, true), null);
|
||||
const core = fs.readFileSync(path.join(HERE, "../src/web-console/public/screens/core.js"), "utf8");
|
||||
assert.match(core, /tellApp\("shortcut", \{ id \}\)/);
|
||||
assert.match(core, /onAppMessage\("open-preferences"/);
|
||||
assert.match(core, /onAppMessage\("open-help"/);
|
||||
assert.match(APP_JS, /kind === 'shortcut'/);
|
||||
assert.match(APP_JS, /postMessage\(\{ plan2code: 'open-preferences' \}/);
|
||||
});
|
||||
|
||||
test("app.js routes the shortcuts from every focus position: the terminal's key handler, the shell's document and the page's message", () => {
|
||||
assert.match(APP_JS, /onShortcut: \(event\) => \{\s*const id = shortcutAction\(event, \{ mac: IS_MAC, inTerminal: true \}\);/);
|
||||
assert.match(APP_JS, /document\.addEventListener\('keydown', \(event\) => \{\s*if \(event\.defaultPrevented\) return;[\s\S]*?shortcutAction\(event, \{ mac: IS_MAC, inTerminal \}\)/);
|
||||
const term = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/terminal.js"), "utf8");
|
||||
assert.match(term, /if \(onShortcut && onShortcut\(event\)\) \{\s*event\.preventDefault\(\);\s*return false;/, "the terminal never types a shell shortcut to the agent");
|
||||
assert.match(APP_JS, /if \(!changeProjectBtn\.disabled && folderPickerEl\.hidden\) changeProjectBtn\.click\(\);/, "Change project is not run over the bare start's own picker");
|
||||
assert.match(APP_JS, /tipWithShortcut\(paneCollapsed \? 'Show the terminal' : 'Collapse', 'toggle-terminal', IS_MAC\)/, "shown in tooltips");
|
||||
});
|
||||
|
||||
test("the '...' menu: About, Check for updates, Help and Quit, in the bar's menu pattern", () => {
|
||||
assert.match(INDEX_HTML, /<button id="app-menu-button" class="bar-menu"[^>]*aria-haspopup="menu"[^>]*aria-controls="app-menu"/);
|
||||
const menu = INDEX_HTML.slice(INDEX_HTML.indexOf('id="app-menu"'), INDEX_HTML.indexOf('id="more-menu"'));
|
||||
assert.deepEqual([...menu.matchAll(/role="menuitem">([^<]+)</g)].map((m) => m[1]), ["About Plan2Code", "Check for updates", "Help", "Quit"]);
|
||||
assert.match(APP_JS, /\[appMenuBtn, appMenu\]/, "it opens, closes and takes focus like the other bar menus");
|
||||
assert.match(APP_JS, /invoke\('request_quit'\)/);
|
||||
assert.match(APP_JS, /openLink\(releaseNotesUrl\(status\.app\)\)/, "release notes through the opener");
|
||||
});
|
||||
|
||||
test("links open through the opener plugin, http and https only; the terminal's links and What's new use it", () => {
|
||||
const open = APP_JS.slice(APP_JS.indexOf("function openLink"), APP_JS.indexOf("function openLink") + 400);
|
||||
assert.match(open, /\^https\?:/, "anything else is refused before it is sent");
|
||||
assert.match(open, /invoke\('plugin:opener\|open_url', \{ url \}\)/);
|
||||
assert.match(APP_JS, /onLink: \(uri\) => openLink\(uri\)/);
|
||||
assert.match(INDEX_HTML, /<script src="vendor\/addon-web-links\.js"><\/script>/);
|
||||
const term = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/terminal.js"), "utf8");
|
||||
assert.match(term, /new window\.WebLinksAddon\.WebLinksAddon\(\(event, uri\) => \{\s*event\.preventDefault\(\);\s*onLink\(uri\);/);
|
||||
const caps = JSON.parse(fs.readFileSync(path.join(HERE, "../plan2code-app/src-tauri/capabilities/default.json"), "utf8"));
|
||||
const opener = caps.permissions.find((p) => p && p.identifier === "opener:allow-open-url");
|
||||
assert.deepEqual(opener.allow.map((a) => a.url).sort(), ["http://*", "https://*"], "scoped to web links");
|
||||
assert.ok(!caps.permissions.includes("opener:default"), "not the default set (mailto, tel, reveal in folder)");
|
||||
});
|
||||
|
||||
test("clipboardAction: Ctrl+C copies only with a selection (else it is the interrupt), Ctrl+Shift+C and Cmd+C always copy, Ctrl/Cmd+V pastes", () => {
|
||||
const ev = (key, mods = {}) => ({ key, ctrlKey: false, metaKey: false, shiftKey: false, altKey: false, ...mods });
|
||||
assert.equal(clipboardAction(ev("c", { ctrlKey: true }), true), "copy");
|
||||
assert.equal(clipboardAction(ev("c", { ctrlKey: true }), false), null, "no selection: the interrupt goes to the agent");
|
||||
assert.equal(clipboardAction(ev("C", { ctrlKey: true, shiftKey: true }), false), "copy");
|
||||
assert.equal(clipboardAction(ev("c", { metaKey: true }), false), "copy");
|
||||
assert.equal(clipboardAction(ev("v", { ctrlKey: true }), false), "paste");
|
||||
assert.equal(clipboardAction(ev("V", { ctrlKey: true, shiftKey: true }), false), "paste");
|
||||
assert.equal(clipboardAction(ev("v", { metaKey: true }), false), "paste");
|
||||
assert.equal(clipboardAction(ev("c", { ctrlKey: true, altKey: true }), true), null);
|
||||
assert.equal(clipboardAction(ev("c"), true), null);
|
||||
assert.equal(clipboardAction(ev("x", { ctrlKey: true }), true), null);
|
||||
// On a Mac, Ctrl+C is always the interrupt, selection or not; Cmd+C and Ctrl+Shift+C still copy.
|
||||
assert.equal(clipboardAction(ev("c", { ctrlKey: true }), true, { mac: true }), null);
|
||||
assert.equal(clipboardAction(ev("c", { metaKey: true }), true, { mac: true }), "copy");
|
||||
assert.equal(clipboardAction(ev("C", { ctrlKey: true, shiftKey: true }), true, { mac: true }), "copy");
|
||||
assert.equal(clipboardAction(null, true), null);
|
||||
});
|
||||
|
||||
test("the terminal pastes once and in brackets, copies on select only by preference, and has a Copy / Paste / Clear menu", () => {
|
||||
const term = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/terminal.js"), "utf8");
|
||||
assert.match(term, /term\.paste\(text\)/, "bracketed paste, not onInput(text)");
|
||||
assert.doesNotMatch(term, /if \(text\) onInput\(text\)/, "the old unbracketed paste is gone");
|
||||
assert.match(term, /if \(action === 'paste'\) \{\s*event\.preventDefault\(\);/, "the browser's own paste event is stopped, so it cannot land a second time");
|
||||
assert.match(term, /if \(event\.ctrlKey && !event\.shiftKey\) term\.clearSelection\(\);/, "a plain Ctrl+C that copied clears the selection, so the next one is the interrupt");
|
||||
assert.match(term, /if \(!copyOnSelectOn\) return;/, "no unconditional clipboard write on every selection");
|
||||
assert.match(term, /\['Copy', actions\.hasSelection\(\), actions\.copy\],\s*\['Paste', true, actions\.paste\],\s*\['Clear', true, actions\.clear\]/);
|
||||
assert.match(INDEX_HTML, /<div id="term-menu" role="menu"/);
|
||||
assert.match(APP_JS, /terminal\.setCopyOnSelect\(Boolean\(state\.copyOnSelect\)\)/);
|
||||
assert.match(APP_JS, /invoke\('save_copy_on_select', \{ on \}\)|invoke\('set_copy_on_select', \{ on \}\)/);
|
||||
});
|
||||
Reference in new issue
Block a user