Add the plan2code-app desktop app, its CI workflows and docs

AI Assisted
This commit is contained in:
jparkerweb committed 2026-10-23 10:09:18 -07:00
1 parent 681c4a4b85
commit a5a3a81c5f
55 files changed
+13277

No files matched your search

+78
View File
@@ -0,0 +1,78 @@
// Checks that every file carrying the product's version agrees, the desktop app's included:
// version.json, package.json, CHANGELOG.md's top heading, and the app's tauri.conf.json,
// package.json and Cargo.toml. The release-app workflow runs it before building, with
// --tag <the release tag>, so a release cannot ship an app that names another version.
//
// node scripts/check-versions.mjs [--tag v3.0.0]
//
// Exit 0 when they agree, 1 when they do not (each file and its version is printed).
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const readJson = (file) => JSON.parse(fs.readFileSync(file, "utf8")).version;
const CARGO_VERSION = /^\s*version\s*=\s*"([^"]+)"/m;
const CHANGELOG_HEADING = /^##\s+v?(\d+\.\d+\.\d+)\b/m;
/** Each file that carries the version, with how to read it. Paths are relative to the repo root. */
const SOURCES = [
{ file: "version.json", read: readJson },
{ file: "package.json", read: readJson },
{ file: "CHANGELOG.md", read: (file) => fs.readFileSync(file, "utf8").match(CHANGELOG_HEADING)?.[1] },
{ file: "plan2code-app/src-tauri/tauri.conf.json", read: readJson },
{ file: "plan2code-app/package.json", read: readJson },
{
file: "plan2code-app/src-tauri/Cargo.toml",
// The first `version =` line is the [package] one; dependencies come after it.
read: (file) => fs.readFileSync(file, "utf8").match(CARGO_VERSION)?.[1],
},
];
/**
* `{ ok, versions: [{ file, version }], problems: [string] }` for the tree at `root`. A file that
* is missing or has no readable version is a problem, as is any disagreement, and a `tag`
* (`v3.0.0` or `3.0.0`) that names another version.
*/
export function checkVersions(root = ROOT, { tag } = {}) {
const versions = [];
const problems = [];
for (const { file, read } of SOURCES) {
let version;
try {
version = read(path.join(root, file));
} catch (error) {
problems.push(`${file}: cannot be read (${error.code || error.message})`);
continue;
}
if (!version) {
problems.push(`${file}: no version found`);
continue;
}
versions.push({ file, version });
}
const expected = versions.find((v) => v.file === "version.json")?.version;
for (const { file, version } of versions) {
if (expected && version !== expected) problems.push(`${file} says ${version}, version.json says ${expected}`);
}
if (tag && expected && tag.replace(/^v/, "") !== expected) {
problems.push(`the release tag ${tag} names ${tag.replace(/^v/, "")}, version.json says ${expected}`);
}
return { ok: problems.length === 0, versions, problems };
}
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const args = process.argv.slice(2);
const tagAt = args.indexOf("--tag");
const tag = tagAt >= 0 ? args[tagAt + 1] : undefined;
if (tagAt >= 0 && !tag) {
console.error("Usage: node scripts/check-versions.mjs [--tag v3.0.0]");
process.exit(2);
}
const { ok, versions, problems } = checkVersions(ROOT, { tag });
for (const { file, version } of versions) console.log(`${version.padEnd(10)} ${file}`);
for (const problem of problems) console.error(`MISMATCH: ${problem}`);
process.exit(ok ? 0 : 1);
}
+26
View File
@@ -0,0 +1,26 @@
// Tests for plan2code-app/ui/meter.js. Run with: node --test scripts/test-app-meter.mjs
//
// app.js itself cannot be imported here (it touches `document` and
// `window.__TAURI__` at module scope), which is why the nudge decision lives
// in its own pure module.
import test from "node:test";
import assert from "node:assert/strict";
import { nudgeDue } from "../plan2code-app/ui/meter.js";
test("meter: a real reading at or past the threshold nudges", () => {
assert.equal(nudgeDue({ kind: "real", percent: 70 }, 70), true);
assert.equal(nudgeDue({ kind: "real", percent: 69 }, 70), false);
});
test("meter: a best-effort reading nudges the same as a real one", () => {
assert.equal(nudgeDue({ kind: "besteffort", percent: 80 }, 70), true);
});
test("meter: an estimate never nudges, however high its percent", () => {
assert.equal(nudgeDue({ kind: "estimate", percent: 99 }, 70), false);
});
test("meter: unknown never nudges", () => {
assert.equal(nudgeDue({ kind: "unknown" }, 70), false);
});
+88
View File
@@ -0,0 +1,88 @@
// Tests for scripts/check-versions.mjs. Run with: node --test scripts/test-check-versions.mjs
//
// Each test builds a small tree in a temp folder holding the six files that carry the version,
// so the check is exercised without depending on what the real repo says today.
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 { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
import { checkVersions } from "./check-versions.mjs";
const SCRIPT = path.join(path.dirname(fileURLToPath(import.meta.url)), "check-versions.mjs");
/** A tree with every version file at `version`, each overridable by its path in `over`. */
function tree(t, version = "3.0.0", over = {}) {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-versions-"));
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
const files = {
"version.json": JSON.stringify({ name: "Plan2Code", version }),
"package.json": JSON.stringify({ name: "plan2code", version }),
"CHANGELOG.md": `# Changelog\n\n## v${version}\n\n### Added\n\n- something\n\n## v0.0.1\n`,
"plan2code-app/src-tauri/tauri.conf.json": JSON.stringify({ productName: "Plan2Code", version }),
"plan2code-app/package.json": JSON.stringify({ name: "plan2code-app", version }),
"plan2code-app/src-tauri/Cargo.toml": `[package]\nname = "plan2code-app"\nversion = "${version}"\n\n[dependencies]\nserde = { version = "1" }\n`,
...over,
};
for (const [file, content] of Object.entries(files)) {
if (content === null) continue;
fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true });
fs.writeFileSync(path.join(root, file), content);
}
return root;
}
test("versions: six files at one version pass, and each is listed", (t) => {
const result = checkVersions(tree(t));
assert.equal(result.ok, true, result.problems.join("; "));
assert.equal(result.versions.length, 6);
assert.ok(result.versions.every((v) => v.version === "3.0.0"));
});
test("versions: the app's tauri.conf.json disagreeing is named", (t) => {
const root = tree(t, "3.0.0", {
"plan2code-app/src-tauri/tauri.conf.json": JSON.stringify({ version: "2.11.0" }),
});
const result = checkVersions(root);
assert.equal(result.ok, false);
assert.deepEqual(result.problems, ["plan2code-app/src-tauri/tauri.conf.json says 2.11.0, version.json says 3.0.0"]);
});
test("versions: Cargo.toml's package version counts, a dependency's does not", (t) => {
const root = tree(t, "3.0.0", {
"plan2code-app/src-tauri/Cargo.toml": '[package]\nname = "x"\nversion = "3.1.0"\n',
});
assert.match(checkVersions(root).problems[0], /Cargo\.toml says 3\.1\.0/);
});
test("versions: the changelog's top heading is the one read", (t) => {
const root = tree(t, "3.0.0", { "CHANGELOG.md": "# Changelog\n\n## v3.1.0\n\n## v3.0.0\n" });
assert.match(checkVersions(root).problems[0], /CHANGELOG\.md says 3\.1\.0/);
});
test("versions: a missing file or an unreadable version is a problem, not a throw", (t) => {
const root = tree(t, "3.0.0", { "plan2code-app/package.json": null, "CHANGELOG.md": "# Changelog\n" });
const problems = checkVersions(root).problems;
assert.ok(problems.some((p) => p.startsWith("plan2code-app/package.json: cannot be read")), problems.join("; "));
assert.ok(problems.includes("CHANGELOG.md: no version found"), problems.join("; "));
});
test("versions: a release tag must name the same version, with or without the v", (t) => {
const root = tree(t);
assert.equal(checkVersions(root, { tag: "v3.0.0" }).ok, true);
assert.equal(checkVersions(root, { tag: "3.0.0" }).ok, true);
const bad = checkVersions(root, { tag: "v3.0.1" });
assert.equal(bad.ok, false);
assert.match(bad.problems[0], /release tag v3\.0\.1 names 3\.0\.1/);
});
test("versions: the command exits 0 on agreement and 1 on a mismatch", () => {
// The real tree: the exit code and the output agree with each other, whatever it says today.
const real = spawnSync(process.execPath, [SCRIPT], { encoding: "utf8" });
assert.equal(real.status, real.stderr.includes("MISMATCH") ? 1 : 0);
const noTag = spawnSync(process.execPath, [SCRIPT, "--tag"], { encoding: "utf8" });
assert.equal(noTag.status, 2);
});
+48
View File
@@ -0,0 +1,48 @@
// Standalone check: with PLAN2CODE_EMBED_ORIGIN unset the console page's
// Content-Security-Policy is byte for byte the value it always was. Guards
// the embed opt-in from ever narrowing or widening the default header.
// Shared setup: ./web-console-test-helpers.mjs.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
import { cookieFor, ENV, HOME, ROOT } from "./web-console-test-helpers.mjs";
const SERVER_JS = path.join(ROOT, "src", "web-console", "server.mjs");
const EXPECTED_CSP =
"default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; " +
"font-src 'self'; connect-src 'self'; media-src 'self'; " +
"base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
test("with PLAN2CODE_EMBED_ORIGIN unset the page CSP is the pre-embed string byte for byte", async () => {
const dir = fs.mkdtempSync(path.join(HOME, "standalone-"));
fs.writeFileSync(path.join(dir, "state.json"), JSON.stringify({ sid: path.basename(dir), phase: "collecting" }));
const env = { ...ENV };
delete env.PLAN2CODE_EMBED_ORIGIN;
const child = spawn(process.execPath, [SERVER_JS, `--session=${dir}`, "--token=t", `--project=${dir}`], {
env,
stdio: ["ignore", "pipe", "ignore"],
windowsHide: true,
});
try {
const ready = await new Promise((resolve, reject) => {
let buf = "";
child.stdout.on("data", (c) => {
buf += c;
const line = buf.split("\n").find((l) => l.includes('"ready"'));
if (line) resolve(JSON.parse(line));
});
child.on("exit", () => reject(new Error("server exited before it was ready")));
});
const base = `http://127.0.0.1:${ready.port}`;
const res = await fetch(base + "/", { headers: { cookie: cookieFor(base, "t"), connection: "close" } });
assert.equal(res.status, 200);
await res.arrayBuffer();
assert.equal(res.headers.get("content-security-policy"), EXPECTED_CSP);
} finally {
child.kill();
}
});
+105
View File
@@ -0,0 +1,105 @@
// Web console tests: PLAN2CODE_EMBED_ORIGIN opt-in embed mode. With the
// variable unset the page's CSP keeps frame-ancestors 'none'; set to exactly
// one allowed origin it names that origin; set to anything else it is ignored
// and 'none' stands. Each case boots its own server with the variable in its
// environment. Shared setup: ./web-console-test-helpers.mjs.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
import { cookieFor, ENV, HOME, ROOT } from "./web-console-test-helpers.mjs";
const SERVER_JS = path.join(ROOT, "src", "web-console", "server.mjs");
// Boot a session server whose environment carries PLAN2CODE_EMBED_ORIGIN set
// to `origin` (or does not carry it at all when origin is undefined). Returns
// the child and its base URL; the caller always kills the child.
async function bootServer(origin) {
const dir = fs.mkdtempSync(path.join(HOME, "embed-"));
fs.writeFileSync(path.join(dir, "state.json"), JSON.stringify({ sid: path.basename(dir), phase: "collecting" }));
const env = { ...ENV };
if (origin === undefined) delete env.PLAN2CODE_EMBED_ORIGIN;
else env.PLAN2CODE_EMBED_ORIGIN = origin;
const child = spawn(process.execPath, [SERVER_JS, `--session=${dir}`, "--token=t", `--project=${dir}`], {
env,
stdio: ["ignore", "pipe", "ignore"],
windowsHide: true,
});
const ready = await new Promise((resolve, reject) => {
let buf = "";
child.stdout.on("data", (c) => {
buf += c;
const line = buf.split("\n").find((l) => l.includes('"ready"'));
if (line) resolve(JSON.parse(line));
});
child.on("exit", () => reject(new Error("server exited before it was ready")));
});
return { child, base: `http://127.0.0.1:${ready.port}` };
}
// Fetch the session page with its token cookie and resolve to the page's
// content-security-policy header.
async function cspWith(origin) {
const { child, base } = await bootServer(origin);
try {
const res = await fetch(base + "/", { headers: { cookie: cookieFor(base, "t"), connection: "close" } });
assert.equal(res.status, 200);
await res.arrayBuffer();
return res.headers.get("content-security-policy");
} finally {
child.kill();
}
}
// Fetch the sign-in redirect and resolve to its set-cookie header.
async function cookieWith(origin) {
const { child, base } = await bootServer(origin);
try {
const res = await fetch(`${base}/s/t/`, { redirect: "manual" });
assert.equal(res.status, 302);
await res.arrayBuffer();
return res.headers.get("set-cookie");
} finally {
child.kill();
}
}
test("with PLAN2CODE_EMBED_ORIGIN unset the header keeps frame-ancestors 'none'", async () => {
const csp = await cspWith(undefined);
assert.match(csp, /frame-ancestors 'none'$/);
});
test("each allowed origin is named in frame-ancestors", async () => {
for (const origin of ["http://127.0.0.1:5173", "http://localhost:8080", "http://tauri.localhost", "https://tauri.localhost", "tauri://localhost"]) {
const csp = await cspWith(origin);
assert.ok(csp.endsWith(`frame-ancestors ${origin}`), `${origin}: ${csp}`);
}
});
test("the session cookie is Strict standalone and None; Secure under embed", async () => {
const plain = await cookieWith(undefined);
assert.match(plain, /SameSite=Strict/);
assert.doesNotMatch(plain, /SameSite=None/);
const embedded = await cookieWith("http://tauri.localhost");
assert.match(embedded, /SameSite=None; Secure/);
});
test("anything but exactly one allowed origin keeps frame-ancestors 'none'", async () => {
const rejected = [
"https://example.com",
"",
"http://127.0.0.1:5173 https://example.com",
"http://127.0.0.1:5173;evil",
"http://127.0.0.1:0",
"http://127.0.0.1:99999",
"http://127.0.0.1",
"https://127.0.0.1:443",
"*",
];
for (const origin of rejected) {
const csp = await cspWith(origin);
assert.match(csp, /frame-ancestors 'none'$/, `${JSON.stringify(origin)}: ${csp}`);
}
});
+270
View File
@@ -0,0 +1,270 @@
// Web console tests: the desktop app's in-app signal for `open`. Under the app
// (PLAN2CODE_IN_APP=1) `open` never launches a browser, reuses the app's
// session and tells the app's announce URL which page to show; with the
// variable unset it behaves as it always did. Shared setup:
// ./web-console-test-helpers.mjs.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
import { spawn } from "node:child_process";
import { CONSOLE_CLI, ENV, HOME, cli } from "./web-console-test-helpers.mjs";
import { announcePage, inAppSignal } from "../src/web-console/in-app.mjs";
// A stand-in for the app's announce endpoint: records every POST it accepts.
// `current` is the session the window shows now: what `GET /session` answers.
async function announceServer(token, current = null) {
const seen = [];
const server = http.createServer((req, res) => {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", () => {
if (req.headers["x-plan2code-token"] !== token) {
res.writeHead(403).end();
return;
}
if (req.method === "GET" && req.url === "/session") {
res.writeHead(200, { "content-type": "application/json" }).end(JSON.stringify(current));
return;
}
seen.push(JSON.parse(body));
res.writeHead(204).end();
});
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
return { seen, url: `http://127.0.0.1:${server.address().port}/page`, close: () => server.close() };
}
// `open` run asynchronously (the announce server lives in this process, so a
// blocking spawn would deadlock). Resolves { status, json }.
function openAsync(args, { cwd, env }) {
return new Promise((resolve) => {
const child = spawn(process.execPath, [CONSOLE_CLI, ...args], { cwd, env: { ...ENV, ...env }, windowsHide: true });
let out = "";
child.stdout.on("data", (c) => (out += c));
child.on("close", (status) => {
const line = out.trim().split("\n").filter((l) => l.startsWith("{")).pop();
resolve({ status, json: line ? JSON.parse(line) : null });
});
});
}
function project(name) {
const dir = fs.mkdtempSync(path.join(HOME, `${name}-`));
return dir;
}
// A browser stand-in: PLAN2CODE_BROWSER runs this with the link appended.
function browserRecorder() {
const log = path.join(HOME, `browser-${Date.now()}-${Math.random().toString(16).slice(2)}.log`);
const script = path.join(HOME, `record-${path.basename(log)}.mjs`);
fs.writeFileSync(script, `import fs from "node:fs"; fs.appendFileSync(${JSON.stringify(log)}, process.argv[2] + "\\n");`);
const command = `"${process.execPath}" "${script}"`;
return { command, calls: () => (fs.existsSync(log) ? fs.readFileSync(log, "utf8").trim().split("\n") : []) };
}
const withBrowser = (recorder) => {
const env = { PLAN2CODE_BROWSER: recorder.command, PLAN2CODE_NO_BROWSER: "" };
return env;
};
test("inAppSignal is null unless PLAN2CODE_IN_APP is 1", () => {
assert.equal(inAppSignal({}), null);
assert.equal(inAppSignal({ PLAN2CODE_IN_APP: "0" }), null);
assert.deepEqual(
inAppSignal({ PLAN2CODE_IN_APP: "1", PLAN2CODE_CONSOLE_SID: "s", PLAN2CODE_APP_ANNOUNCE: "http://127.0.0.1:1/x", PLAN2CODE_APP_TOKEN: "t" }),
{ sid: "s", announce: "http://127.0.0.1:1/x", token: "t" }
);
});
test("announcePage sends the token, and fails quietly on a wrong token, a dead port and a non-loopback host", async () => {
const app = await announceServer("good");
try {
assert.equal(await announcePage({ announce: app.url, token: "good" }, { url: "u" }), true);
assert.deepEqual(app.seen, [{ url: "u" }]);
assert.equal(await announcePage({ announce: app.url, token: "bad" }, { url: "u" }), false);
assert.equal(await announcePage({ announce: "http://127.0.0.1:1/x", token: "t" }, { url: "u" }), false);
assert.equal(await announcePage({ announce: "http://example.com/x", token: "t" }, { url: "u" }), false);
assert.equal(await announcePage({ announce: "not a url", token: "t" }, { url: "u" }), false);
} finally {
app.close();
}
});
test("under the app, open reuses the app's session, announces the page and launches no browser", async () => {
const cwd = project("inapp");
const first = cli(["open", "--workflow", "dashboard", "--no-open"], { cwd });
const appSid = first.json.sid;
const app = await announceServer("tok", { sid: appSid, url: first.json.url, workflow: "dashboard" });
const browser = browserRecorder();
try {
const res = await openAsync(["open", "--workflow", "dashboard"], {
cwd,
env: {
...withBrowser(browser),
PLAN2CODE_IN_APP: "1",
PLAN2CODE_APP_ANNOUNCE: app.url,
PLAN2CODE_APP_TOKEN: "tok",
},
});
assert.equal(res.status, 0);
assert.equal(res.json.sid, appSid, "the window's own session is reused, not a second console");
assert.equal(res.json.reused, true);
assert.equal(res.json.inApp, true);
assert.equal(res.json.announced, true);
assert.equal(app.seen.length, 1);
assert.equal(app.seen[0].sid, appSid);
assert.equal(app.seen[0].url, first.json.url);
assert.equal(app.seen[0].workflow, "dashboard");
await new Promise((r) => setTimeout(r, 700));
assert.deepEqual(browser.calls(), [], "no browser is launched under the app");
} finally {
app.close();
cli(["stop", "--session", appSid], { cwd, expectFail: true });
}
});
test("under the app, a hop on the app's session keeps the same url and reports the new workflow", async () => {
const cwd = project("inapp-hop");
const first = cli(["open", "--workflow", "dashboard", "--no-open"], { cwd });
const app = await announceServer("tok", { sid: first.json.sid, url: first.json.url, workflow: "dashboard" });
try {
const res = await openAsync(["open", "--workflow", "pathfinder"], {
cwd,
env: { PLAN2CODE_IN_APP: "1", PLAN2CODE_APP_ANNOUNCE: app.url, PLAN2CODE_APP_TOKEN: "tok" },
});
assert.equal(res.json.url, first.json.url);
assert.equal(app.seen[0].workflow, "pathfinder");
} finally {
app.close();
cli(["stop", "--session", first.json.sid], { cwd, expectFail: true });
}
});
test("under the app, a wrong token is reported and the page is not sent to a browser", async () => {
const cwd = project("inapp-bad");
const first = cli(["open", "--workflow", "dashboard", "--no-open"], { cwd });
const app = await announceServer("right");
const browser = browserRecorder();
try {
const res = await openAsync(["open", "--workflow", "dashboard"], {
cwd,
env: {
...withBrowser(browser),
PLAN2CODE_IN_APP: "1",
PLAN2CODE_CONSOLE_SID: first.json.sid,
PLAN2CODE_APP_ANNOUNCE: app.url,
PLAN2CODE_APP_TOKEN: "wrong",
},
});
assert.equal(res.json.inApp, true);
assert.equal(res.json.announced, false);
assert.equal(app.seen.length, 0);
await new Promise((r) => setTimeout(r, 700));
assert.deepEqual(browser.calls(), []);
} finally {
app.close();
cli(["stop", "--session", first.json.sid], { cwd, expectFail: true });
}
});
test("under the app, a session that is gone gets a fresh one and its address announced", async () => {
const cwd = project("inapp-gone");
const app = await announceServer("tok");
try {
const res = await openAsync(["open", "--workflow", "dashboard"], {
cwd,
env: { PLAN2CODE_IN_APP: "1", PLAN2CODE_CONSOLE_SID: "20200101-000000-nothere", PLAN2CODE_APP_ANNOUNCE: app.url, PLAN2CODE_APP_TOKEN: "tok" },
});
assert.equal(res.status, 0);
assert.notEqual(res.json.sid, "20200101-000000-nothere");
assert.equal(app.seen[0].url, res.json.url);
cli(["stop", "--session", res.json.sid], { cwd, expectFail: true });
} finally {
app.close();
}
});
test("two app windows never receive each other's pages", async () => {
const cwdA = project("win-a");
const cwdB = project("win-b");
const a = cli(["open", "--workflow", "dashboard", "--no-open"], { cwd: cwdA });
const b = cli(["open", "--workflow", "dashboard", "--no-open"], { cwd: cwdB });
const appA = await announceServer("ta", { sid: a.json.sid, url: a.json.url, workflow: "dashboard" });
const appB = await announceServer("tb", { sid: b.json.sid, url: b.json.url, workflow: "dashboard" });
try {
const envFor = (r, app, token) => ({ PLAN2CODE_IN_APP: "1", PLAN2CODE_APP_ANNOUNCE: app.url, PLAN2CODE_APP_TOKEN: token });
await openAsync(["open", "--workflow", "plan"], { cwd: cwdA, env: envFor(a, appA, "ta") });
await openAsync(["open", "--workflow", "quick-task"], { cwd: cwdB, env: envFor(b, appB, "tb") });
assert.deepEqual(appA.seen.map((p) => [p.sid, p.workflow]), [[a.json.sid, "plan"]]);
assert.deepEqual(appB.seen.map((p) => [p.sid, p.workflow]), [[b.json.sid, "quick-task"]]);
} finally {
appA.close();
appB.close();
cli(["stop", "--session", a.json.sid], { cwd: cwdA, expectFail: true });
cli(["stop", "--session", b.json.sid], { cwd: cwdB, expectFail: true });
}
});
test("without the signal, open still launches the browser and reports nothing about an app", async () => {
const cwd = project("bare");
const browser = browserRecorder();
const res = await openAsync(["open", "--workflow", "dashboard"], { cwd, env: withBrowser(browser) });
try {
assert.equal(res.status, 0);
assert.equal(res.json.inApp, undefined);
assert.equal(res.json.announced, undefined);
let calls = [];
for (let i = 0; i < 30 && calls.length === 0; i++) {
await new Promise((r) => setTimeout(r, 100));
calls = browser.calls();
}
assert.ok(calls.length >= 1, "the browser command ran");
assert.match(calls[0], /^http:\/\/127\.0\.0\.1:\d+\/s\//);
} finally {
cli(["stop", "--session", res.json.sid], { cwd, expectFail: true });
}
});
test("the window's session, not the environment's, decides what open resumes", async () => {
const cwd = project("inapp-ask");
const stale = cli(["open", "--workflow", "dashboard", "--no-open"], { cwd });
const live = cli(["open", "--workflow", "dashboard", "--no-open"], { cwd });
const app = await announceServer("tok", { sid: live.json.sid, url: live.json.url, workflow: "dashboard" });
try {
const res = await openAsync(["open", "--workflow", "plan"], {
cwd,
env: { PLAN2CODE_IN_APP: "1", PLAN2CODE_CONSOLE_SID: stale.json.sid, PLAN2CODE_APP_ANNOUNCE: app.url, PLAN2CODE_APP_TOKEN: "tok" },
});
assert.equal(res.json.sid, live.json.sid);
assert.equal(app.seen[0].sid, live.json.sid);
} finally {
app.close();
cli(["stop", "--session", stale.json.sid], { cwd, expectFail: true });
cli(["stop", "--session", live.json.sid], { cwd, expectFail: true });
}
});
test("with nothing shown in the window yet, open makes the first session and announces it", async () => {
const cwd = project("inapp-first");
const app = await announceServer("tok", null);
const browser = browserRecorder();
try {
const res = await openAsync(["open", "--workflow", "dashboard"], {
cwd,
env: { ...withBrowser(browser), PLAN2CODE_IN_APP: "1", PLAN2CODE_APP_ANNOUNCE: app.url, PLAN2CODE_APP_TOKEN: "tok" },
});
assert.equal(res.status, 0);
assert.equal(res.json.announced, true);
assert.equal(app.seen.length, 1);
assert.equal(app.seen[0].sid, res.json.sid);
assert.equal(app.seen[0].url, res.json.url);
await new Promise((r) => setTimeout(r, 700));
assert.deepEqual(browser.calls(), [], "the first page goes to the app too, not a browser");
cli(["stop", "--session", res.json.sid], { cwd, expectFail: true });
} finally {
app.close();
}
});