Let people define custom agent CLIs and start them from the app and the launcher

AI Assisted
This commit is contained in:
jparkerweb committed 2026-10-25 21:26:08 -07:00
1 parent 3e22d53bf5
commit 94063fc0a9
27 files changed
+4025 -95

No files matched your search

File diff suppressed because it is too large. Load diff
+132
View File
@@ -0,0 +1,132 @@
// The rules of ~/.plan2code/agents.json, console side (src/web-console/agents.mjs),
// against the shared cases every reader's tests load (scripts/fixtures/agents-cases.json),
// plus what only the console does: finding a command and checking a save.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { MAX_AGENTS, buildArgs, makeId, normalizeAgents, resolveCommand, validateForSave } from "../src/web-console/agents.mjs";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const CASES = JSON.parse(fs.readFileSync(path.join(ROOT, "scripts", "fixtures", "agents-cases.json"), "utf8"));
const WINDOWS = process.platform === "win32";
for (const c of CASES.files) {
test(`agents file: ${c.name}`, () => {
const { agents, warnings } = normalizeAgents(c.raw);
assert.deepEqual(agents, c.agents);
if (!c.warnings.length) assert.deepEqual(warnings, []);
for (const part of c.warnings) {
assert.ok(warnings.some((w) => w.includes(part)), `a warning names "${part}": ${JSON.stringify(warnings)}`);
}
});
}
for (const c of CASES.buildArgs) {
test(`buildArgs: ${c.name}`, () => {
assert.deepEqual(buildArgs(c.entry, c.options), c.args);
});
}
for (const c of CASES.ids) {
test(`makeId: ${c.name}`, () => {
assert.equal(makeId(c.input, c.taken), c.id);
});
}
test("normalizeAgents takes the parsed file too, and never throws on odd input", () => {
assert.deepEqual(normalizeAgents({ schema: 1, agents: [{ id: "goose", name: "Goose", command: "goose" }] }).agents.map((a) => a.id), ["goose"]);
for (const odd of [0, true, "null", "42", "\"text\"", [], () => {}]) {
assert.deepEqual(normalizeAgents(odd).agents, [], String(odd));
}
});
test("the fixture covers every rule it promises", () => {
assert.ok(CASES.files.length >= 20 && CASES.buildArgs.length >= 10 && CASES.ids.length >= 8);
const many = CASES.files.find((c) => c.name.startsWith("51 entries"));
assert.equal(many.agents.length, MAX_AGENTS);
});
/* ------------------------------------------------------- resolveCommand */
function fakePath(t) {
const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-agents-"));
t.after(() => fs.rmSync(base, { recursive: true, force: true }));
const bin = path.join(base, "bin");
const spaced = path.join(base, "with space");
fs.mkdirSync(bin);
fs.mkdirSync(spaced);
return { base, bin, spaced };
}
test("resolveCommand finds a bare name on PATH, a full path, and misses what is not there", (t) => {
const { bin, spaced } = fakePath(t);
const name = WINDOWS ? "goose.exe" : "goose";
fs.writeFileSync(path.join(bin, name), "");
const opts = { path: [spaced, `"${bin}"`].join(path.delimiter), pathext: ".EXE;.CMD" };
assert.equal(resolveCommand("goose", opts)?.toLowerCase(), path.join(bin, name).toLowerCase(), "a bare name, PATH entry quoted");
assert.equal(resolveCommand(path.join(bin, name), opts), path.join(bin, name), "a full path");
assert.equal(resolveCommand(` "${path.join(bin, name)}" `, opts), path.join(bin, name), "a quoted, padded full path");
assert.equal(resolveCommand("nowhere", opts), null);
assert.equal(resolveCommand(path.join(bin, "nowhere"), opts), null);
assert.equal(resolveCommand(bin, opts), null, "a folder is not a command");
assert.equal(resolveCommand("", opts), null);
assert.equal(resolveCommand("goose", { path: "", pathext: ".EXE" }), null, "an empty PATH finds nothing");
});
test("resolveCommand on Windows tries PATHEXT, also in a folder with a space and for a full path", { skip: !WINDOWS && "Windows only" }, (t) => {
const { spaced } = fakePath(t);
const cmd = path.join(spaced, "aider.cmd");
fs.writeFileSync(cmd, "@echo off");
const opts = { path: spaced, pathext: ".EXE;.CMD;.BAT" };
assert.equal(resolveCommand("aider", opts)?.toLowerCase(), cmd.toLowerCase(), "found through PATHEXT");
assert.equal(resolveCommand("aider.cmd", opts), cmd, "a name that already has its extension");
assert.equal(resolveCommand(path.join(spaced, "aider"), opts)?.toLowerCase(), cmd.toLowerCase(), "a full path without its extension");
assert.equal(resolveCommand("aider", { path: spaced, pathext: ".EXE" }), null, "only the listed extensions");
});
/* ------------------------------------------------------- validateForSave */
test("validateForSave fills ids from names and every default", () => {
const { agents, error } = validateForSave([
{ id: "goose", name: "Goose", command: "goose" },
{ name: "My Agent", command: " my-agent " },
{ name: "goose!", command: "goose2" },
]);
assert.equal(error, undefined);
assert.deepEqual(agents.map((a) => a.id), ["goose", "my-agent", "goose-2"]);
assert.equal(agents[1].command, "my-agent");
assert.deepEqual(agents[1].modelArgs, ["--model", "{model}"]);
assert.equal(agents[1].prompt, "/plan2code");
});
test("validateForSave names the entry and field of the first failure", () => {
const cases = [
[[{ name: "Goose", command: "goose" }, { name: "GOOSE", command: "x" }], 1, "name"],
[[{ name: "Goose", command: " " }], 0, "command"],
[[{ name: "", command: "x" }], 0, "name"],
[[{ id: "claude", name: "Mine", command: "claude" }], 0, "id"],
[[{ id: "Bad Id", name: "Mine", command: "x" }], 0, "id"],
[[{ id: "a", name: "A", command: "a" }, { id: "a", name: "B", command: "b" }], 1, "id"],
[[{ name: "A", command: "a", args: ["--x", 1] }], 0, "args"],
[[{ name: "A", command: "a", models: [{ label: "no id" }] }], 0, "models"],
[[{ name: "A", command: "a" }, "text"], 1, ""],
];
for (const [list, index, field] of cases) {
const out = validateForSave(list);
assert.ok(out.error, JSON.stringify(list));
assert.equal(out.index, index, JSON.stringify(list));
assert.equal(out.field, field, JSON.stringify(list));
}
assert.equal(validateForSave({}).field, "agents");
assert.equal(validateForSave(Array.from({ length: MAX_AGENTS + 1 }, (_, i) => ({ name: `A${i}`, command: "a" }))).field, "agents");
});
test("an id the form already carries is never handed to a new entry", () => {
const { agents } = validateForSave([{ name: "Goose", command: "a" }, { id: "goose", name: "Other", command: "b" }]);
assert.deepEqual(agents.map((a) => a.id), ["goose-2", "goose"]);
});
+27 -1
View File
@@ -11,7 +11,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { barNextSteps, continueKeys, defaultRightFraction, folderName, windowTitleFor, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js";
import { barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, windowTitleFor, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js";
import { findBrowser, launchBrowser } from "./browser.mjs";
const HERE = path.dirname(fileURLToPath(import.meta.url));
@@ -232,3 +232,29 @@ test("toggling the tired Planny <svg>'s hidden attribute the way app.js does act
await browser.close();
}
});
test("continueKeys gives a custom agent id the plain word and Enter", () => {
assert.deepEqual(continueKeys("my-aider"), ["continue", "\r"]);
});
const AVAIL = (spec) =>
spec.map(([id, installed, custom = false]) => ({ id, label: id, installed, custom }));
test("pickDefaultAgent keeps the remembered agent when it is installed, custom ones included", () => {
const list = AVAIL([["claude", true], ["devin", true], ["codex", true], ["mine", true, true]]);
assert.equal(pickDefaultAgent(list, "codex"), "codex");
assert.equal(pickDefaultAgent(list, "mine"), "mine");
});
test("pickDefaultAgent falls back to the first installed built-in, then the first installed custom agent", () => {
assert.equal(pickDefaultAgent(AVAIL([["claude", false], ["devin", false], ["codex", true]]), null), "codex");
assert.equal(pickDefaultAgent(AVAIL([["claude", false], ["devin", true], ["codex", true]]), "claude"), "devin");
assert.equal(pickDefaultAgent(AVAIL([["claude", false], ["devin", false], ["codex", false], ["mine", true, true]]), "claude"), "mine");
});
test("pickDefaultAgent with nothing installed returns the remembered id, else the first entry, else null", () => {
const none = AVAIL([["claude", false], ["devin", false], ["codex", false]]);
assert.equal(pickDefaultAgent(none, "devin"), "devin");
assert.equal(pickDefaultAgent(none, null), "claude");
assert.equal(pickDefaultAgent([], null), null);
});
+176 -4
View File
@@ -307,14 +307,25 @@ test("launcher: the shipped models.json is curated Devin at low/medium/high only
}
});
test("launcher: with no CLI installed it exits 127 and says how to run the skill from an agent", (t) => {
test("launcher: with no CLI installed it exits 127 and explains how to get one and how to run the skill from an agent", (t) => {
const box = sandbox([]);
t.after(box.cleanup);
const result = box.run([]);
assert.equal(result.status, 127);
assert.match(result.stderr, /none of `claude`, `devin` or `codex` was found/);
assert.ok(result.stderr.includes("type /plan2code"));
assert.ok(result.stderr.includes("$plan2code (Codex)"));
assert.match(result.stderr, /Plan2Code runs inside an AI coding agent CLI, and none was found/);
// Every built-in's label, install command and official page.
for (const part of [
"Claude Code: npm i -g @anthropic-ai/claude-code",
"https://code.claude.com/docs/en/setup",
"Codex: npm i -g @openai/codex",
"https://github.com/openai/codex",
"Devin: https://devin.ai",
"https://docs.devin.ai/work-with-devin/devin-cli",
]) {
assert.ok(result.stderr.includes(part), part);
}
assert.ok(result.stderr.includes("Add it in User Preferences (web console) under Agents, then run `plan2code` again."));
assert.ok(result.stderr.includes("type /plan2code ($plan2code in Codex)"));
assert.match(result.stderr, /cd into the project/);
});
@@ -607,3 +618,164 @@ test("launcher app: an AGENTS.md marks the folder as a project, so the agent sta
assert.doesNotMatch(result.stderr, /doesn't look like a project/);
assert.notEqual(box.argsOf("claude"), null);
});
// Custom agents (~/.plan2code/agents.json). The shared fixture is the contract the console and
// the desktop app read too; the rest starts real stand-ins from a temp home.
const CASES = JSON.parse(fs.readFileSync(path.join(ROOT, "scripts", "fixtures", "agents-cases.json"), "utf8"));
const GOOSE = {
id: "goose",
name: "Goose",
command: "goose",
args: ["--yes", "{prompt}"],
bypassArgs: ["--bypass"],
models: [{ id: "m1", label: "Model one" }, { id: "m2" }],
};
/** Write ~/.plan2code/agents.json (an object is stringified; a string goes in as it is). */
function writeAgents(box, file) {
const target = path.join(box.home, ".plan2code", "agents.json");
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, typeof file === "string" ? file : JSON.stringify(file));
return target;
}
const goose = (extra = {}) => ({ schema: 1, agents: [{ ...GOOSE, ...extra }] });
for (const c of CASES.files) {
test(`launcher agents file: ${c.name}`, () => {
const { normalizeAgents } = require(LAUNCHER);
const { agents, warnings } = normalizeAgents(c.raw);
assert.deepEqual(agents, c.agents);
if (!c.warnings.length) assert.deepEqual(warnings, []);
for (const part of c.warnings) {
assert.ok(warnings.some((w) => w.includes(part)), `a warning names "${part}": ${JSON.stringify(warnings)}`);
}
});
}
for (const c of CASES.buildArgs) {
test(`launcher buildArgs: ${c.name}`, () => {
const { buildArgs } = require(LAUNCHER);
assert.deepEqual(buildArgs(c.entry, c.options), c.args);
});
}
test("launcher agents: --cli <custom id> starts it with args, the model through modelArgs, then bypassArgs and the forwarded args", (t) => {
const box = sandbox(["claude", "goose"]);
t.after(box.cleanup);
writeAgents(box, goose());
const result = box.run(["--cli", "goose", "--model", "m1", "--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("goose"), ["--yes", "/plan2code", "--model", "m1", "--bypass", "--verbose"]);
assert.equal(box.argsOf("claude"), null);
assert.equal(JSON.parse(fs.readFileSync(box.stateFile, "utf8")).lastCli, "goose");
// No model chosen and no models flag: the model arguments are left out.
assert.equal(box.run(["--cli=goose"]).status, 0);
assert.deepEqual(box.argsOf("goose"), ["--yes", "/plan2code", "--bypass"]);
});
test("launcher agents: the last pick can be a custom id, and the --cli error names custom ids", (t) => {
const box = sandbox(["claude", "goose"]);
t.after(box.cleanup);
writeAgents(box, goose());
fs.mkdirSync(path.dirname(box.stateFile), { recursive: true });
fs.writeFileSync(box.stateFile, JSON.stringify({ lastCli: "goose" }));
assert.equal(box.run([]).status, 0);
assert.notEqual(box.argsOf("goose"), null);
assert.equal(box.argsOf("claude"), null);
const bad = box.run(["--cli", "bogus"]);
assert.equal(bad.status, 2);
assert.match(bad.stderr, /--cli takes claude, devin, codex or goose, not "bogus"/);
});
test("launcher agents: the model menu is the agent's own models, with no shipped list or user models.json", (t) => {
const box = sandbox([]);
t.after(box.cleanup);
fs.mkdirSync(path.join(box.home, ".plan2code"), { recursive: true });
const file = writeAgents(box, goose());
const { customClis, listModels, hasModelFlag } = require(LAUNCHER);
const [cli] = customClis(file, false);
assert.deepEqual(listModels(cli), [{ id: "m1", label: "Model one" }, { id: "m2", label: "" }]);
assert.deepEqual(listModels(customClis(writeAgents(box, goose({ models: [] })), false)[0]), []);
// Only --model counts for a custom agent: Codex's -m does not.
assert.equal(hasModelFlag(["--model", "x"], "goose"), true);
assert.equal(hasModelFlag(["-m", "x"], "goose"), false);
// A model given on the command line goes through modelArgs, once.
assert.deepEqual(cli.args(["--model=m2", "-x"]), ["--yes", "/plan2code", "--model", "m2", "--bypass", "-x"]);
});
test("launcher agents: a custom agent whose command is not found is left out and named when nothing can run", (t) => {
const box = sandbox(["claude"]);
t.after(box.cleanup);
writeAgents(box, { schema: 1, agents: [{ id: "ghost", name: "Ghost", command: "ghost-cmd" }] });
// Left out of the way: claude still starts.
assert.equal(box.run([]).status, 0);
assert.notEqual(box.argsOf("claude"), null);
const asked = box.run(["--cli", "ghost"]);
assert.equal(asked.status, 127);
assert.match(asked.stderr, /Custom agent Ghost: ghost-cmd not found/);
const none = sandbox([]);
t.after(none.cleanup);
writeAgents(none, { schema: 1, agents: [{ id: "ghost", name: "Ghost", command: "ghost-cmd" }] });
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("User Preferences"));
});
test("launcher agents: a malformed agents.json warns on a terminal, never crashes, and gives no agents", (t) => {
const box = sandbox(["claude"]);
t.after(box.cleanup);
const file = writeAgents(box, "{ not json");
const { customClis } = require(LAUNCHER);
const lines = [];
const realError = console.error;
console.error = (line) => lines.push(String(line));
try {
assert.deepEqual(customClis(file, true), []);
assert.deepEqual(customClis(path.join(box.home, "missing.json"), true), []);
} finally {
console.error = realError;
}
assert.equal(lines.length, 1);
assert.match(lines[0], /plan2code: agents\.json: agents\.json is not valid JSON/);
// A piped run prints no warning, and the built-ins carry on.
const result = box.run([]);
assert.equal(result.status, 0, result.stderr);
assert.equal(result.stderr, "");
assert.notEqual(box.argsOf("claude"), null);
});
test("launcher agents: the app hand-over passes a custom id and its model unchanged", (t) => {
const box = sandbox(["goose"]);
t.after(box.cleanup);
writeAgents(box, goose());
const display = process.platform === "linux" ? { DISPLAY: ":0" } : {};
const result = box.run(["--cli", "goose", "--model", "m2"], { PLAN2CODE_APP: box.appFile, ...display });
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.appArgs().slice(2), ["--agent", "goose", "--model", "m2"]);
assert.equal(box.argsOf("goose"), null);
assert.equal(JSON.parse(fs.readFileSync(box.stateFile, "utf8")).lastCli, "goose");
});
test("launcher agents: a full-path command starts, and on Windows a .cmd in a folder with a space too", (t) => {
const box = sandbox([]);
t.after(box.cleanup);
const spaced = path.join(box.dir, "with space");
fs.mkdirSync(spaced);
const recorder = path.join(box.dir, "bin", "record.js");
let file;
if (IS_WINDOWS) {
file = path.join(spaced, "spaced.cmd");
fs.writeFileSync(file, `@"${process.execPath}" "${recorder}" spaced %*\r\n`);
} else {
file = path.join(spaced, "spaced");
fs.writeFileSync(file, `#!/bin/sh\nexec "${process.execPath}" "${recorder}" spaced "$@"\n`);
fs.chmodSync(file, 0o755);
}
writeAgents(box, { schema: 1, agents: [{ id: "spaced", name: "Spaced", command: file, args: ["{prompt}"] }] });
const result = box.run(["--cli", "spaced", "--note", "a b"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("spaced"), ["/plan2code", "--note", "a b"]);
});
+2
View File
@@ -392,6 +392,8 @@ test("every state-changing route refuses a foreign Origin, and nothing changes",
["POST", "/draft", { staged: { q1: { k: "B" } } }],
["POST", "/looks", { looks: { theme: "light" } }],
["POST", "/models", { models: { devin: [{ id: "x" }] } }],
["POST", "/agents", { agents: [{ name: "X", command: "x" }] }],
["POST", "/agents/test", { command: "node" }],
["POST", "/workspace/add", { path: picked }],
["POST", "/workspace/edit", { id: "f0", name: "renamed" }],
["POST", "/workspace/remove", { id: "f0" }],
+77
View File
@@ -484,6 +484,83 @@ test("models: the user's additions round-trip, XHigh and Max are refused, and th
assert.deepEqual((await get()).user, { claude: [], devin: [], codex: [] });
});
test("agents: no file is an empty list, a save is written whole and keeps unknown keys, and a bad save names its entry and field", async (t) => {
const file = path.join(MODELS_DIR, "agents.json");
t.after(() => fs.rmSync(file, { force: true }));
fs.rmSync(file, { force: true });
const get = async () => (await fetch(baseUrl + "/agents", { headers: { cookie: cookieFor(baseUrl, token) } })).json();
assert.deepEqual(await get(), { agents: [], warnings: [] }, "no file");
fs.mkdirSync(MODELS_DIR, { recursive: true });
fs.writeFileSync(file, "{ \"schema\": 1, \"agents\": [");
const broken = await get();
assert.deepEqual(broken.agents, [], "a half-written file is no agents");
assert.match(broken.warnings.join(" "), /not valid JSON/, "and says why");
fs.writeFileSync(file, JSON.stringify({ schema: 1, theme: "kept", agents: [] }));
const saved = await post("/agents", { agents: [{ name: "My Agent", command: " my-agent ", note: "mine" }] });
assert.equal(saved.status, 200);
const body = await saved.json();
assert.equal(body.ok, true);
assert.equal(body.agents[0].id, "my-agent", "an id is made from the name");
const written = JSON.parse(fs.readFileSync(file, "utf8"));
assert.equal(written.schema, 1);
assert.equal(written.theme, "kept", "a top-level key the file had survives the rewrite");
assert.deepEqual(written.agents, [
{ name: "My Agent", command: "my-agent", note: "mine", id: "my-agent", args: [], bypassArgs: [], modelArgs: ["--model", "{model}"], prompt: "/plan2code", models: [] },
]);
assert.deepEqual(fs.readdirSync(MODELS_DIR).filter((n) => n.startsWith("agents.json.")), [], "no temp file left behind");
assert.deepEqual((await get()).agents.map((a) => a.id), ["my-agent"]);
const before = fs.readFileSync(file, "utf8");
const dup = await post("/agents", { agents: [{ id: "my-agent", name: "My Agent", command: "my-agent" }, { name: "MY AGENT", command: "x" }] });
assert.equal(dup.status, 400);
assert.deepEqual(await dup.json(), { error: 'name "MY AGENT" is already used', index: 1, field: "name" });
for (const agents of [[{ name: "A", command: " " }], [{ id: "codex", name: "A", command: "a" }], "nope"]) {
assert.equal((await post("/agents", { agents })).status, 400, JSON.stringify(agents));
}
assert.equal((await raw("POST", "/agents", "not json")).status, 400);
assert.equal(fs.readFileSync(file, "utf8"), before, "a refused save writes nothing");
});
test("agents: a file with entries the page could not read is not overwritten unless the save says replace", async (t) => {
const file = path.join(MODELS_DIR, "agents.json");
t.after(() => fs.rmSync(file, { force: true }));
fs.mkdirSync(MODELS_DIR, { recursive: true });
const mine = { agents: [{ name: "Mine", command: "mine" }] };
for (const text of [
JSON.stringify({ schema: 2, agents: [{ id: "future", name: "Future", command: "future" }] }),
JSON.stringify({ schema: 1, agents: [{ id: "Hand", name: "Hand", command: "hand" }] }),
"{ \"schema\": 1, \"agents\": [",
]) {
fs.writeFileSync(file, text);
const refused = await post("/agents", mine);
assert.equal(refused.status, 409, text);
const body = await refused.json();
assert.match(body.error, /could not read/);
assert.ok(body.warnings.length > 0, "the warnings come back with it");
assert.equal(fs.readFileSync(file, "utf8"), text, "nothing is written");
}
const replaced = await post("/agents", { ...mine, replace: true });
assert.equal(replaced.status, 200, "replace: true writes anyway");
const written = JSON.parse(fs.readFileSync(file, "utf8"));
assert.equal(written.schema, 1);
assert.deepEqual(written.agents.map((a) => a.id), ["mine"]);
assert.equal((await post("/agents", mine)).status, 200, "a file the page reads whole saves as usual");
});
test("agents/test: finds a command on PATH or says it is not there, and never runs it", async () => {
const found = await (await post("/agents/test", { command: "node" })).json();
assert.equal(found.found, true);
assert.ok(fs.statSync(found.path).isFile(), found.path);
assert.deepEqual(await (await post("/agents/test", { command: "p2c-no-such-agent-cli" })).json(), { found: false });
for (const command of ["", " ", 7, "x".repeat(1025)]) {
assert.equal((await post("/agents/test", { command })).status, 400, String(command).slice(0, 20));
}
});
test("cleanup over HTTP: a scan lists strays in the console home, and a delete removes only what the scan found", async () => {
const stray = path.join(HOME, "stray-cleanup.json");
fs.writeFileSync(stray, "{}");
+111
View File
@@ -117,6 +117,117 @@ test("the launcher's model menus have Claude, Devin and Codex tabs, and a model
assert.equal(await s.page.locator("#models-user").getByRole("textbox", { name: "Model id" }).inputValue(), "gpt-test-codex-1");
});
test("Agents: a person adds an agent, tests its command, sees it saved after a reload, and deletes it", async (t) => {
noSavedLooks(t);
const file = path.join(MODELS_DIR, "agents.json");
fs.rmSync(file, { force: true });
t.after(() => fs.rmSync(file, { force: true }));
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.page.click("#btn-looks");
const list = s.page.locator("#agents-list");
assert.equal(await list.locator(".agent-card").count(), 0, "no agents before one is added");
await s.page.click("#agents-add");
const card = list.locator(".agent-card").last();
await card.getByRole("textbox", { name: "Name", exact: true }).fill("Test Agent");
await card.getByRole("textbox", { name: "Command", exact: true }).fill("node");
await card.getByRole("textbox", { name: "Command", exact: true }).press("Tab");
await s.page.locator("#agents-status").filter({ hasText: /^Saved./ }).waitFor();
await card.getByRole("button", { name: "Test", exact: true }).click();
await card.locator(".agent-test-result").filter({ hasText: /^Found at / }).waitFor();
const saved = JSON.parse(fs.readFileSync(file, "utf8"));
assert.equal(saved.schema, 1);
assert.deepEqual(saved.agents.map((a) => [a.id, a.name, a.command, a.prompt]), [["test-agent", "Test Agent", "node", "/plan2code"]]);
// A second agent with the same name is refused on its own card and field.
await s.page.click("#agents-add");
const second = list.locator(".agent-card").nth(1);
await second.getByRole("textbox", { name: "Command", exact: true }).fill("x");
await second.getByRole("textbox", { name: "Name", exact: true }).fill("TEST AGENT");
await second.getByRole("textbox", { name: "Name", exact: true }).press("Tab");
await list.locator(".agent-card").nth(1).locator(".agent-error").filter({ hasText: /already used/ }).waitFor();
assert.equal(await list.locator(".agent-card").nth(1).locator('input.invalid[data-field="name"]').count(), 1, "the name field is marked");
assert.equal(JSON.parse(fs.readFileSync(file, "utf8")).agents.length, 1, "a refused save writes nothing");
await s.page.reload({ waitUntil: "domcontentloaded" });
await drawn(s.page);
await s.page.click("#btn-looks");
await list.locator(".agent-card").first().waitFor();
assert.equal(await list.locator(".agent-card").count(), 1);
assert.equal(await list.locator(".agent-card").first().getByRole("textbox", { name: "Name", exact: true }).inputValue(), "Test Agent");
await list.locator(".agent-card").first().getByRole("button", { name: "Delete", exact: true }).click();
await list.locator(".agent-card").first().getByRole("button", { name: "Yes, delete" }).click();
await s.page.waitForFunction(() => document.querySelectorAll("#agents-list .agent-card").length === 0);
await s.page.locator("#agents-status").filter({ hasText: /^Saved./ }).waitFor();
assert.deepEqual(JSON.parse(fs.readFileSync(file, "utf8")).agents, []);
});
test("Agents: a new card's first field is not saved alone, and a redraw keeps focus and what was typed", async (t) => {
noSavedLooks(t);
const file = path.join(MODELS_DIR, "agents.json");
fs.rmSync(file, { force: true });
t.after(() => fs.rmSync(file, { force: true }));
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.page.click("#btn-looks");
const list = s.page.locator("#agents-list");
await s.page.click("#agents-add");
const card = list.locator(".agent-card").last();
const name = card.getByRole("textbox", { name: "Name", exact: true });
const command = card.getByRole("textbox", { name: "Command", exact: true });
await name.fill("Focus Agent");
await name.press("Tab");
await s.page.waitForTimeout(300);
assert.equal(await list.locator(".agent-error").count(), 0, "a name alone is not sent, so nothing is refused");
assert.equal(fs.existsSync(file), false, "and nothing is written");
assert.equal(await command.evaluate((el) => el === document.activeElement), true, "Tab lands on Command");
// The first good save assigns an id and redraws every card: focus stays where Tab put it.
await command.fill("node");
await command.press("Tab");
await s.page.locator("#agents-status").filter({ hasText: /^Saved./ }).waitFor();
assert.equal(JSON.parse(fs.readFileSync(file, "utf8")).agents[0].id, "focus-agent");
assert.equal(await s.page.evaluate(() => document.activeElement?.textContent), "Add an argument", "focus survives the redraw");
// A refused save redraws too: the field being typed in keeps its text, and leaving it saves it.
const prompt = list.locator(".agent-card").last().getByRole("textbox", { name: "Start prompt", exact: true });
await name.fill("");
await prompt.click();
await prompt.fill("/plan2code hi");
await list.locator(".agent-error").filter({ hasText: /name is missing/ }).waitFor();
assert.equal(await s.page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Start prompt");
assert.equal(await s.page.evaluate(() => document.activeElement?.value), "/plan2code hi");
});
test("Agents: a file holding entries the page could not read is only replaced after Save anyway", async (t) => {
noSavedLooks(t);
const file = path.join(MODELS_DIR, "agents.json");
fs.mkdirSync(MODELS_DIR, { recursive: true });
const text = JSON.stringify({ schema: 2, agents: [{ id: "future", name: "Future", command: "future" }] });
fs.writeFileSync(file, text);
t.after(() => fs.rmSync(file, { force: true }));
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.page.click("#btn-looks");
await s.page.locator("#agents-status").filter({ hasText: /schema 2/ }).waitFor();
assert.equal(await s.page.locator("#agents-replace").isVisible(), false, "no Save anyway before a save is tried");
await s.page.click("#agents-add");
const card = s.page.locator("#agents-list .agent-card").last();
await card.getByRole("textbox", { name: "Name", exact: true }).fill("Mine");
await card.getByRole("textbox", { name: "Command", exact: true }).fill("node");
await card.getByRole("textbox", { name: "Command", exact: true }).press("Tab");
await s.page.locator("#agents-status").filter({ hasText: /could not read/ }).waitFor();
assert.equal(fs.readFileSync(file, "utf8"), text, "the refused save writes nothing");
await s.page.locator("#agents-replace").click();
await s.page.locator("#agents-status").filter({ hasText: /^Saved./ }).waitFor();
assert.equal(await s.page.locator("#agents-replace").isVisible(), false);
assert.deepEqual(JSON.parse(fs.readFileSync(file, "utf8")).agents.map((a) => a.id), ["mine"]);
});
test("Cleanup scans the console home and lists an old session folder with its size", async (t) => {
noSavedLooks(t);
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
+2 -1
View File
@@ -447,6 +447,7 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
backdate(put(path.join(plan2code, "app", "plan2code-app"), "x"));
backdate(path.join(plan2code, "app"));
backdate(put(path.join(plan2code, "app.json")));
backdate(put(path.join(plan2code, "agents.json")));
// In use right now: a held lock and a temp between its write and rename.
const live = [put(path.join(consoleDir, "workspaces.json.lock"), ""), put(path.join(plan2code, "models.json.123.tmp"))];
kept.push(...live);
@@ -462,7 +463,7 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
"session:20250801-101010-aaaaaa",
]);
assert.equal(items.some((i) => i.id === "root:handoffs"), false, "the handoffs folder is never a stray");
for (const id of ["root:app", "root:app.json"]) assert.equal(items.some((i) => i.id === id), false, `${id} is never a stray`);
for (const id of ["root:app", "root:app.json", "root:agents.json"]) assert.equal(items.some((i) => i.id === id), false, `${id} is never a stray`);
assert.equal(STRAY_GRACE_MS, 60 * 60 * 1000);
assert.equal(items.find((i) => i.id === "console:p1.json").bytes, 5);
assert.equal(items.find((i) => i.id === "root:console-dev").kind, "folder");
+1 -1
View File
@@ -185,7 +185,7 @@ test("shape: no page module sets a style attribute from script", () => {
// no routes of its own: its buttons are sends (`__git`), through /submit.
const ROUTE_ORDER = [
"/health", "/s/", "/", "SERVABLE", "/overview", "/handoff", "/version", "/state", "/events", "/draft",
"/looks", "/looks", "/subagents", "/pr-host", "/models", "/models", "/cleanup", "/upload",
"/looks", "/looks", "/subagents", "/pr-host", "/models", "/models", "/agents", "/agents", "/agents/test", "/cleanup", "/upload",
"/notepad", "/notepad/text", "/notepad/image", "/notepad/thumb", "/notepad/image/delete", "/notepad/tab",
"/notepad/tab/rename", "/notepad/tab/delete", "/notepad/tab/order", "/notepad/tab/last", "/notepad/images/",
"/attachments/", "/shots/", "/uploads/", "/submit", "/open-link", "/chat", "/chat/decision", "/workspace",