From 7539fc82b64afd66f90db3e47c07547ef8c2abc3 Mon Sep 17 00:00:00 2001 From: adamsilverstein Date: Fri, 13 Nov 2026 08:52:33 -0800 Subject: [PATCH 01/22] Add a local control channel and the toolkit command that asks through it A tool outside the window had no way to ask the app anything (#764). The channel is a Unix socket in the profile directory, or a named pipe on Windows, and not a loopback port, so a web page cannot reach it. The command is a thin client with no dependencies, so it can run on the Node inside the app. Claude-Session: https://claude.ai/code/session_018vwYjUEX6a9RXfZ6jHr6FN --- src/cli.cjs | 180 +++++++++++++++++ src/control-channel.cjs | 189 ++++++++++++++++++ tests/unit/cli.test.cjs | 121 +++++++++++ .../unit/control-channel.integration.test.cjs | 169 ++++++++++++++++ 4 files changed, 659 insertions(+) create mode 100644 src/cli.cjs create mode 100644 src/control-channel.cjs create mode 100644 tests/unit/cli.test.cjs create mode 100644 tests/unit/control-channel.integration.test.cjs diff --git a/src/cli.cjs b/src/cli.cjs new file mode 100644 index 00000000..fb695974 --- /dev/null +++ b/src/cli.cjs @@ -0,0 +1,180 @@ +'use strict'; + +// The `toolkit` command (#764): how a script, a facilitator or an AI tool with +// a terminal asks the running app a question. +// +// It is a thin front for the control channel in control-channel.cjs and holds +// no logic of the app's own: it sends one request to the app that is already +// open and prints the answer. It runs on Electron's Node through the shim the +// app writes at startup, the same way the app's `npm` does, so it needs no +// Node on the machine. Only Node built-ins are required here, and nothing from +// Electron. +// +// The strings are English and are not translated: the output is read by tools +// first, and `--json` is the form they should ask for. + +const net = require('net'); + +const USAGE = `Usage: toolkit [--json] + +Commands: + sites List the sites in the WordPress Contributor Toolkit and what each one is doing + help Show this message + +Options: + --json Print the answer as JSON + +The WordPress Contributor Toolkit has to be open: this command asks the running app. +`; + +// What each command asks the app for. +const COMMANDS = { + sites: 'sites.list' +}; + +const EXIT = { OK: 0, FAILED: 1, USAGE: 2 }; + +// How long the app gets to answer. A listing reads one branch name per site. +const ANSWER_TIMEOUT_MS = 30000; + +/** + * @param {string[]} argv The arguments after the script. + * @return {{command: string, json: boolean, endpoint: string|null}|{usageError: string}} + */ +function parseArgs(argv) { + let command = null; + let json = false; + let endpoint = null; + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (arg === '--json') json = true; + else if (arg === '--help' || arg === '-h') command = command || 'help'; + // Written by the shim, which knows which profile's app it belongs to. + else if (arg === '--endpoint') endpoint = argv[i += 1] || null; + else if (arg.startsWith('-')) return { usageError: `Unknown option: ${arg}` }; + else if (command) return { usageError: `Unexpected argument: ${arg}` }; + else command = arg; + } + if (!command) command = 'help'; + if (command !== 'help' && !Object.hasOwn(COMMANDS, command)) return { usageError: `Unknown command: ${command}` }; + return { command, json, endpoint }; +} + +/** + * Sends one request and resolves with the app's reply. Never rejects: an app + * that is not there is a reply too, with a code of its own. + * + * @param {string} endpoint + * @param {Object} request + * @param {Object} [options] + * @param {number} [options.timeoutMs] + * @return {Promise} The reply, `{ok: true, result}` or `{ok: false, code, error}`. + */ +function ask(endpoint, request, { timeoutMs = ANSWER_TIMEOUT_MS } = {}) { + return new Promise((resolve) => { + let received = ''; + let settled = false; + const settle = (reply) => { + if (settled) return; + settled = true; + clearTimeout(timer); + socket.destroy(); + resolve(reply); + }; + const socket = net.createConnection(endpoint); + const timer = setTimeout(() => settle({ ok: false, code: 'timeout', error: 'The WordPress Contributor Toolkit did not answer in time.' }), timeoutMs); + socket.setEncoding('utf8'); + socket.on('connect', () => socket.write(`${JSON.stringify(request)}\n`)); + socket.on('data', (chunk) => { received += chunk; }); + socket.on('error', (e) => { + // No socket file, or one nobody is listening on: the app is closed. + if (e.code === 'ENOENT' || e.code === 'ECONNREFUSED') { + settle({ ok: false, code: 'not-running', error: 'The WordPress Contributor Toolkit is not running. Open it and try again.' }); + } else { + settle({ ok: false, code: 'connection-failed', error: `Could not reach the WordPress Contributor Toolkit: ${e.message}` }); + } + }); + socket.on('end', () => { + try { + settle(JSON.parse(received)); + } catch { + settle({ ok: false, code: 'invalid-reply', error: 'The WordPress Contributor Toolkit sent an answer this command could not read.' }); + } + }); + }); +} + +const PROJECT_NAMES = { core: 'WordPress Core', gutenberg: 'Gutenberg' }; + +function describeWork(site) { + if (site.pullRequest !== null) return `pull request #${site.pullRequest} (branch ${site.branch})`; + if (!site.workItem) return `none (branch ${site.branch})`; + const kind = site.workItem.provider === 'trac' ? 'Trac ticket' : 'GitHub issue'; + return `${kind} #${site.workItem.id} (branch ${site.branch})`; +} + +function describeServer(site) { + if (!site.server.running) return 'stopped'; + return site.server.url ? `running at ${site.server.url}` : 'starting'; +} + +/** + * The listing as a person reads it. + * + * @param {Object[]} sites The `sites` of a `sites.list` answer. + * @return {string} + */ +function formatSites(sites) { + if (sites.length === 0) return 'No sites yet. Create one in the WordPress Contributor Toolkit.\n'; + return sites.map((site) => [ + `${site.label} (${PROJECT_NAMES[site.project] || site.project})`, + ` Path: ${site.path}`, + ` Work: ${describeWork(site)}`, + ` Server: ${describeServer(site)}`, + ...(site.initialized ? [] : [' Setup: not finished']) + ].join('\n')).join('\n\n') + '\n'; +} + +/** + * @param {string[]} argv + * @param {Object} [io] + * @param {Function} [io.out] Writes to stdout. + * @param {Function} [io.err] Writes to stderr. + * @param {Function} [io.send] `ask`, replaced in tests. + * @return {Promise} The exit code. + */ +async function run(argv, { out = (s) => process.stdout.write(s), err = (s) => process.stderr.write(s), send = ask } = {}) { + const args = parseArgs(argv); + if (args.usageError) { + err(`${args.usageError}\n\n${USAGE}`); + return EXIT.USAGE; + } + if (args.command === 'help') { + out(USAGE); + return EXIT.OK; + } + if (!args.endpoint) { + err('This command has to be run through the `toolkit` file the WordPress Contributor Toolkit writes when it starts.\n'); + return EXIT.USAGE; + } + + const reply = await send(args.endpoint, { action: COMMANDS[args.command] }); + if (args.json) { + // The whole answer, failure included, on stdout: a tool that asked + // for JSON reads one stream. + out(`${JSON.stringify(reply.ok ? { ok: true, ...reply.result } : reply, null, 2)}\n`); + return reply.ok ? EXIT.OK : EXIT.FAILED; + } + if (!reply.ok) { + err(`${reply.error}\n`); + return EXIT.FAILED; + } + out(formatSites(reply.result.sites)); + return EXIT.OK; +} + +if (require.main === module) { + run(process.argv.slice(2)).then((code) => { process.exitCode = code; }); +} + +module.exports = { parseArgs, ask, formatSites, run, EXIT, USAGE }; diff --git a/src/control-channel.cjs b/src/control-channel.cjs new file mode 100644 index 00000000..2594d5e2 --- /dev/null +++ b/src/control-channel.cjs @@ -0,0 +1,189 @@ +'use strict'; + +// The door a tool outside the window asks the app through (#764). +// +// A local socket: a Unix domain socket in the app's own profile directory on +// macOS and Linux, a named pipe on Windows. Not a TCP port, on purpose. A port +// on loopback is reachable from any page the contributor has open, which is +// the same exposure `wpct://` has and the reason deep-link.cjs keeps that +// scheme to one verb. A socket file and a named pipe can only be opened by a +// process running as the same user, which can already read the settings file +// beside them. +// +// One request per connection: a line of JSON in, a line of JSON out, and the +// connection ends. The actions are handed in by main.js, so this module has no +// Electron import and both sides of every refusal are testable with a real +// socket in a temporary directory. + +const crypto = require('crypto'); +const fs = require('fs'); +const net = require('net'); +const path = require('path'); + +// A request is an action name and a few short parameters. Anything longer is +// not a request this app answers, and is not kept in memory to find out. +const MAX_REQUEST_BYTES = 64 * 1024; + +// How long a client that connected has to say what it wants. +const REQUEST_TIMEOUT_MS = 5000; + +// Every `code` a refusal can carry, for the CLI and for tests. +const REFUSAL_CODES = { + INVALID_REQUEST: 'invalid-request', + TOO_LARGE: 'request-too-large', + UNKNOWN_ACTION: 'unknown-action', + FAILED: 'failed' +}; + +/** + * Where the app listens, derived from the profile directory alone so a client + * told that directory, or handed this address by the shim the app writes, + * needs no file to look it up in. + * + * A named pipe has no directory of its own, so on Windows the profile is + * hashed into the name: two profiles (the installed app and `npm start`, or + * two e2e journeys) must not answer each other's clients. + * + * @param {Object} root0 + * @param {string} root0.userData What `app.getPath('userData')` answered. + * @param {string} [root0.platform] `process.platform`. + * @return {string} A socket path, or a pipe name on Windows. + */ +function controlEndpoint({ userData, platform = process.platform }) { + if (platform === 'win32') { + const id = crypto.createHash('sha256').update(userData).digest('hex').slice(0, 16); + return `\\\\.\\pipe\\wpct-control-${id}`; + } + // path.posix, like nodeExecPath in node-shims.cjs: the platform is + // injected, so the suite runs this branch on Windows too. + return path.posix.join(userData, 'control.sock'); +} + +/** + * The file the `toolkit` command is written to, inside the profile directory. + * + * @param {Object} root0 + * @param {string} root0.userData + * @param {string} [root0.platform] + * @return {string} + */ +function cliShimPath({ userData, platform = process.platform }) { + const join = platform === 'win32' ? path.win32.join : path.posix.join; + return join(userData, 'bin', platform === 'win32' ? 'toolkit.cmd' : 'toolkit'); +} + +function refusal(code, error) { + return { ok: false, code, error }; +} + +/** + * Answers one request line. Never throws: whatever goes wrong is the reply. + * + * @param {string} line The request, without its newline. + * @param {Object Promise>} actions The actions main.js offers, by name. + * @return {Promise<{ok: true, result: *}|{ok: false, code: string, error: string}>} + */ +async function answerRequest(line, actions) { + let request; + try { + request = JSON.parse(line); + } catch { + return refusal(REFUSAL_CODES.INVALID_REQUEST, 'The request is not JSON.'); + } + if (typeof request !== 'object' || request === null || Array.isArray(request) || typeof request.action !== 'string') { + return refusal(REFUSAL_CODES.INVALID_REQUEST, 'The request names no action.'); + } + // Own properties only: `constructor` and `toString` are not actions. + if (!Object.hasOwn(actions, request.action)) { + return refusal(REFUSAL_CODES.UNKNOWN_ACTION, `Unknown action: ${request.action.slice(0, 80)}`); + } + const { params } = request; + if (params !== undefined && (typeof params !== 'object' || params === null || Array.isArray(params))) { + return refusal(REFUSAL_CODES.INVALID_REQUEST, 'The parameters are not an object.'); + } + try { + return { ok: true, result: await actions[request.action](params || {}) }; + } catch (e) { + return refusal(REFUSAL_CODES.FAILED, String(e && e.message ? e.message : e)); + } +} + +function serveConnection(socket, actions) { + let buffered = ''; + let answered = false; + + const reply = (payload) => { + answered = true; + clearTimeout(timer); + socket.end(`${JSON.stringify(payload)}\n`); + }; + // A client that connects and says nothing is let go, not kept. + const timer = setTimeout(() => socket.destroy(), REQUEST_TIMEOUT_MS); + + socket.setEncoding('utf8'); + // A client that went away mid-reply has nobody left to tell. + socket.on('error', () => clearTimeout(timer)); + socket.on('close', () => clearTimeout(timer)); + socket.on('data', (chunk) => { + // One request per connection: what follows the first line is not read. + if (answered) return; + buffered += chunk; + const end = buffered.indexOf('\n'); + if (end === -1) { + if (Buffer.byteLength(buffered) > MAX_REQUEST_BYTES) { + reply(refusal(REFUSAL_CODES.TOO_LARGE, 'The request is too large.')); + } + return; + } + answered = true; + answerRequest(buffered.slice(0, end), actions).then(reply); + }); +} + +/** + * Starts listening at `endpoint`. + * + * On macOS and Linux a socket file left by a run that did not end cleanly + * would refuse the listen, so it is removed first. That is only safe for a + * caller that knows no other copy of the app is serving it: main.js calls this + * after it has taken the single-instance lock, which is keyed on the same + * profile directory the socket is in. + * + * @param {Object} root0 + * @param {string} root0.endpoint From `controlEndpoint`. + * @param {Object} root0.actions The actions offered, by name. + * @param {string} [root0.platform] + * @param {(error: Error) => void} [root0.onError] A failure after the listen began. + * @return {Promise<{close: () => Promise}>} Rejects when the listen fails. + */ +async function startControlServer({ endpoint, actions, platform = process.platform, onError = () => {} }) { + const posix = platform !== 'win32'; + if (posix) await fs.promises.rm(endpoint, { force: true }); + + const server = net.createServer((socket) => serveConnection(socket, actions)); + await new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(endpoint, () => { + server.off('error', reject); + server.on('error', onError); + resolve(); + }); + }); + // The profile directory is the user's own already; this says it of the + // socket itself, wherever the directory's mode was left. + if (posix) await fs.promises.chmod(endpoint, 0o600); + + return { + // Closing a server removes its socket file. + close: () => new Promise((resolve) => server.close(() => resolve())) + }; +} + +module.exports = { + MAX_REQUEST_BYTES, + REFUSAL_CODES, + controlEndpoint, + cliShimPath, + answerRequest, + startControlServer +}; diff --git a/tests/unit/cli.test.cjs b/tests/unit/cli.test.cjs new file mode 100644 index 00000000..3984d6c7 --- /dev/null +++ b/tests/unit/cli.test.cjs @@ -0,0 +1,121 @@ +'use strict'; + +// The `toolkit` command (#764) without an app: what it reads off its +// arguments, what it prints, and what it exits with. The socket itself is +// tests/unit/control-channel.integration.test.cjs. + +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const { parseArgs, formatSites, run, EXIT, USAGE } = require('../../src/cli.cjs'); + +const ENDPOINT = '/profile/control.sock'; + +const SITE = { + path: '/sites/wp', + label: 'wp', + project: 'core', + workItem: { provider: 'trac', id: 62281 }, + branch: 'ticket/62281', + pullRequest: null, + initialized: true, + server: { running: true, url: 'http://127.0.0.1:9400' } +}; + +// Runs the command with its output kept and the app replaced by `reply`. +async function runWith(argv, reply) { + const io = { out: '', err: '', sent: [] }; + const code = await run(argv, { + out: (s) => { io.out += s; }, + err: (s) => { io.err += s; }, + send: async (endpoint, request) => { io.sent.push({ endpoint, request }); return reply; } + }); + return { code, ...io }; +} + +test('the arguments name one command, in any order with its options', () => { + assert.deepEqual(parseArgs(['sites']), { command: 'sites', json: false, endpoint: null }); + assert.deepEqual(parseArgs(['--endpoint', ENDPOINT, 'sites', '--json']), { command: 'sites', json: true, endpoint: ENDPOINT }); + assert.deepEqual(parseArgs(['--json', 'sites', '--endpoint', ENDPOINT]), { command: 'sites', json: true, endpoint: ENDPOINT }); + assert.equal(parseArgs([]).command, 'help'); + assert.equal(parseArgs(['--endpoint', ENDPOINT]).command, 'help'); + assert.equal(parseArgs(['sites', '--help']).command, 'sites'); + assert.equal(parseArgs(['-h']).command, 'help'); +}); + +test('what is not a command or an option is a usage error, not a request', async () => { + assert.match(parseArgs(['delete']).usageError, /Unknown command: delete/); + assert.match(parseArgs(['constructor']).usageError, /Unknown command/); + assert.match(parseArgs(['sites', '--force']).usageError, /Unknown option: --force/); + assert.match(parseArgs(['sites', 'extra']).usageError, /Unexpected argument: extra/); + + const result = await runWith(['--endpoint', ENDPOINT, 'delete'], { ok: true, result: {} }); + assert.equal(result.code, EXIT.USAGE); + assert.match(result.err, /Unknown command: delete/); + assert.deepEqual(result.sent, []); +}); + +test('help is printed without asking the app', async () => { + const result = await runWith([], { ok: true, result: {} }); + assert.equal(result.code, EXIT.OK); + assert.equal(result.out, USAGE); + assert.deepEqual(result.sent, []); +}); + +test('run without the address the shim passes, the command says how it is meant to be run', async () => { + const result = await runWith(['sites'], { ok: true, result: {} }); + assert.equal(result.code, EXIT.USAGE); + assert.match(result.err, /`toolkit` file/); + assert.deepEqual(result.sent, []); +}); + +test('sites asks the app for its list and prints one block per site', async () => { + const second = { ...SITE, path: '/sites/gb', label: 'Gutenberg', project: 'gutenberg', workItem: null, branch: 'trunk', initialized: false, server: { running: false, url: null } }; + const result = await runWith(['--endpoint', ENDPOINT, 'sites'], { ok: true, result: { sites: [SITE, second] } }); + + assert.equal(result.code, EXIT.OK); + assert.deepEqual(result.sent, [{ endpoint: ENDPOINT, request: { action: 'sites.list' } }]); + assert.equal(result.out, [ + 'wp (WordPress Core)', + ' Path: /sites/wp', + ' Work: Trac ticket #62281 (branch ticket/62281)', + ' Server: running at http://127.0.0.1:9400', + '', + 'Gutenberg (Gutenberg)', + ' Path: /sites/gb', + ' Work: none (branch trunk)', + ' Server: stopped', + ' Setup: not finished', + '' + ].join('\n')); + assert.equal(result.err, ''); +}); + +test('the listing names an issue, a pull request and a server that has no address yet', () => { + assert.match(formatSites([{ ...SITE, project: 'gutenberg', workItem: { provider: 'github-issue', id: 70123 }, branch: 'issue/70123' }]), /Work: {4}GitHub issue #70123 \(branch issue\/70123\)/); + assert.match(formatSites([{ ...SITE, branch: 'pr/9000', pullRequest: 9000 }]), /Work: {4}pull request #9000 \(branch pr\/9000\)/); + assert.match(formatSites([{ ...SITE, server: { running: true, url: null } }]), /Server: {2}starting/); + assert.match(formatSites([]), /No sites yet/); +}); + +test('--json prints the answer as one JSON document on stdout', async () => { + const result = await runWith(['--endpoint', ENDPOINT, 'sites', '--json'], { ok: true, result: { sites: [SITE] } }); + + assert.equal(result.code, EXIT.OK); + assert.deepEqual(JSON.parse(result.out), { ok: true, sites: [SITE] }); + assert.equal(result.err, ''); +}); + +test('a failure exits non-zero: on stderr as a sentence, and with --json on stdout with its code', async () => { + const failure = { ok: false, code: 'not-running', error: 'The WordPress Contributor Toolkit is not running. Open it and try again.' }; + + const text = await runWith(['--endpoint', ENDPOINT, 'sites'], failure); + assert.equal(text.code, EXIT.FAILED); + assert.equal(text.out, ''); + assert.equal(text.err, `${failure.error}\n`); + + const json = await runWith(['--endpoint', ENDPOINT, 'sites', '--json'], failure); + assert.equal(json.code, EXIT.FAILED); + assert.deepEqual(JSON.parse(json.out), failure); + assert.equal(json.err, ''); +}); diff --git a/tests/unit/control-channel.integration.test.cjs b/tests/unit/control-channel.integration.test.cjs new file mode 100644 index 00000000..0401659c --- /dev/null +++ b/tests/unit/control-channel.integration.test.cjs @@ -0,0 +1,169 @@ +'use strict'; + +// The control channel (#764) over a real socket: the server from +// src/control-channel.cjs and the client the `toolkit` command uses, `ask` in +// src/cli.cjs, talking to each other in a temporary directory. A named pipe on +// Windows, a socket file elsewhere, which is the endpoint `controlEndpoint` +// answers for the machine the suite runs on. + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const net = require('node:net'); +const os = require('node:os'); +const path = require('node:path'); + +const { + MAX_REQUEST_BYTES, + REFUSAL_CODES, + controlEndpoint, + cliShimPath, + startControlServer +} = require('../../src/control-channel.cjs'); +const { ask } = require('../../src/cli.cjs'); + +const POSIX = process.platform !== 'win32'; + +function profile(t) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wpct-control-')); + t.after(() => fs.rmSync(dir, { recursive: true, force: true })); + return dir; +} + +async function serve(t, actions, userData = profile(t)) { + const endpoint = controlEndpoint({ userData }); + const server = await startControlServer({ endpoint, actions }); + t.after(() => server.close()); + return { endpoint, server }; +} + +// What a client that is not the CLI can send: bytes of its choosing. +function sendRaw(endpoint, bytes) { + return new Promise((resolve) => { + let received = ''; + const socket = net.createConnection(endpoint, () => socket.write(bytes)); + socket.setEncoding('utf8'); + socket.on('data', (chunk) => { received += chunk; }); + // A server that answers and hangs up while this is still writing is + // one of the cases under test; what it said is the result either way. + socket.on('error', () => {}); + socket.on('close', () => resolve(received)); + }); +} + +test('the endpoint is a socket in the profile, and on Windows a pipe named after it', () => { + assert.equal( + controlEndpoint({ userData: '/Users/dev/Library/Application Support/Toolkit', platform: 'darwin' }), + '/Users/dev/Library/Application Support/Toolkit/control.sock' + ); + + const installed = controlEndpoint({ userData: 'C:\\Users\\dev\\AppData\\Roaming\\Toolkit', platform: 'win32' }); + const fromSource = controlEndpoint({ userData: 'C:\\Users\\dev\\AppData\\Roaming\\toolkit-dev', platform: 'win32' }); + assert.match(installed, /^\\\\\.\\pipe\\wpct-control-[0-9a-f]{16}$/); + // Two profiles must not answer each other's clients. + assert.notEqual(installed, fromSource); + assert.equal(installed, controlEndpoint({ userData: 'C:\\Users\\dev\\AppData\\Roaming\\Toolkit', platform: 'win32' })); +}); + +test('the command is written into the profile, with the extension Windows needs', () => { + assert.equal(cliShimPath({ userData: '/Users/dev/Toolkit', platform: 'darwin' }), '/Users/dev/Toolkit/bin/toolkit'); + assert.equal(cliShimPath({ userData: 'C:\\Users\\dev\\Toolkit', platform: 'win32' }), 'C:\\Users\\dev\\Toolkit\\bin\\toolkit.cmd'); +}); + +test('a request is answered by the action it names, with the parameters it sent', async (t) => { + const asked = []; + const { endpoint } = await serve(t, { + 'sites.list': async (params) => { asked.push(params); return { sites: [{ path: '/sites/wp' }] }; } + }); + + assert.deepEqual(await ask(endpoint, { action: 'sites.list' }), { ok: true, result: { sites: [{ path: '/sites/wp' }] } }); + assert.deepEqual(await ask(endpoint, { action: 'sites.list', params: { a: 1 } }), { ok: true, result: { sites: [{ path: '/sites/wp' }] } }); + assert.deepEqual(asked, [{}, { a: 1 }]); +}); + +test('a name that is not an action is refused, and so is one the object only inherits', async (t) => { + const { endpoint } = await serve(t, { 'sites.list': async () => ({}) }); + + for (const action of ['sites.delete', 'constructor', 'toString', '__proto__']) { + const reply = await ask(endpoint, { action }); + assert.equal(reply.ok, false, action); + assert.equal(reply.code, REFUSAL_CODES.UNKNOWN_ACTION, action); + } +}); + +test('a request that is not one is refused without reaching an action', async (t) => { + let reached = 0; + const { endpoint } = await serve(t, { 'sites.list': async () => { reached += 1; return {}; } }); + + const refused = async (bytes) => JSON.parse(await sendRaw(endpoint, bytes)); + assert.equal((await refused('not json\n')).code, REFUSAL_CODES.INVALID_REQUEST); + assert.equal((await refused('["sites.list"]\n')).code, REFUSAL_CODES.INVALID_REQUEST); + assert.equal((await refused('{"action":7}\n')).code, REFUSAL_CODES.INVALID_REQUEST); + assert.equal((await refused('{"action":"sites.list","params":"all"}\n')).code, REFUSAL_CODES.INVALID_REQUEST); + assert.equal(reached, 0); +}); + +test('a request with no end is refused once it is too long to be one', async (t) => { + const { endpoint } = await serve(t, { 'sites.list': async () => ({}) }); + + const reply = JSON.parse(await sendRaw(endpoint, 'x'.repeat(MAX_REQUEST_BYTES + 1))); + assert.deepEqual({ ok: reply.ok, code: reply.code }, { ok: false, code: REFUSAL_CODES.TOO_LARGE }); +}); + +test('only the first request on a connection is answered', async (t) => { + let reached = 0; + const { endpoint } = await serve(t, { 'sites.list': async () => { reached += 1; return {}; } }); + + const received = await sendRaw(endpoint, '{"action":"sites.list"}\n{"action":"sites.list"}\n'); + assert.equal(received.trim().split('\n').length, 1); + assert.equal(reached, 1); +}); + +test('an action that throws is an answer, and the next request is still served', async (t) => { + const { endpoint } = await serve(t, { + broken: async () => { throw new Error('settings.json is not JSON'); }, + 'sites.list': async () => ({ sites: [] }) + }); + + assert.deepEqual(await ask(endpoint, { action: 'broken' }), { ok: false, code: REFUSAL_CODES.FAILED, error: 'settings.json is not JSON' }); + assert.equal((await ask(endpoint, { action: 'sites.list' })).ok, true); +}); + +test('with no app listening, the client says the app is not running', async (t) => { + const userData = profile(t); + const endpoint = controlEndpoint({ userData }); + assert.equal((await ask(endpoint, { action: 'sites.list' })).code, 'not-running'); + + // And again once an app that was listening has closed. + const server = await startControlServer({ endpoint, actions: { 'sites.list': async () => ({}) } }); + assert.equal((await ask(endpoint, { action: 'sites.list' })).ok, true); + await server.close(); + assert.equal((await ask(endpoint, { action: 'sites.list' })).code, 'not-running'); +}); + +test('a client is told when the app takes too long to answer', async (t) => { + const { endpoint } = await serve(t, { slow: () => new Promise(() => {}) }); + + assert.equal((await ask(endpoint, { action: 'slow' }, { timeoutMs: 50 })).code, 'timeout'); +}); + +// A named pipe leaves no file behind and has no mode to set, so these two are +// about the socket file only. +test('a socket file left by a run that did not end cleanly does not refuse the next one', { skip: !POSIX && 'named pipes leave no file' }, async (t) => { + const userData = profile(t); + fs.writeFileSync(controlEndpoint({ userData }), ''); + + const { endpoint } = await serve(t, { 'sites.list': async () => ({ sites: [] }) }, userData); + assert.equal((await ask(endpoint, { action: 'sites.list' })).ok, true); +}); + +test('the socket file is the user\'s alone, and is gone once the server closes', { skip: !POSIX && 'named pipes have no mode' }, async (t) => { + const userData = profile(t); + const endpoint = controlEndpoint({ userData }); + const server = await startControlServer({ endpoint, actions: {} }); + + // The permission bits, without the file type above them. + assert.equal(fs.statSync(endpoint).mode % 0o1000, 0o600); + await server.close(); + assert.equal(fs.existsSync(endpoint), false); +}); From f17f7e0f7954b68f348b28d553eba937f3190362 Mon Sep 17 00:00:00 2001 From: adamsilverstein Date: Fri, 13 Nov 2026 08:52:33 -0800 Subject: [PATCH 02/22] Answer sites.list from the running app and write the toolkit shim Start the channel once the app is ready and offer one read: the sites, where each is, what is checked out and whether its server runs. The shim is written into the profile at every start, on Electron's Node, so the command needs nothing installed on the host. Claude-Session: https://claude.ai/code/session_018vwYjUEX6a9RXfZ6jHr6FN --- src/control-sites.cjs | 40 +++++++++++ src/main.js | 61 +++++++++++++++++ src/node-shims.cjs | 19 ++++-- tests/unit/control-sites.test.cjs | 45 +++++++++++++ tests/unit/ipc-wiring.test.cjs | 108 +++++++++++++++++++++++++++++- tests/unit/node-shims.test.cjs | 30 +++++++++ 6 files changed, 296 insertions(+), 7 deletions(-) create mode 100644 src/control-sites.cjs create mode 100644 tests/unit/control-sites.test.cjs diff --git a/src/control-sites.cjs b/src/control-sites.cjs new file mode 100644 index 00000000..29d33f5a --- /dev/null +++ b/src/control-sites.cjs @@ -0,0 +1,40 @@ +'use strict'; + +// What the control channel (#764) says of a site: the facts a tool needs to +// work in the checkout the app already made, and nothing it would have to +// interpret. Kept out of main.js so the shape has a test of its own. + +const { projectTypeForSite } = require('./project-type.cjs'); +const { pathBasename } = require('./renderer/path-basename.cjs'); + +/** + * @param {Object} root0 + * @param {string} root0.sitePath + * @param {Object} [root0.meta] The site's record in the store. + * @param {string} root0.branch The branch checked out. + * @param {number|null} [root0.pullRequest] The pull request that branch is, if it is one. + * @param {Object} [root0.server] The entry in main.js's `playgroundServers`. + * @return {Object} One entry of `sites.list`. + */ +function describeSite({ sitePath, meta = {}, branch, pullRequest = null, server = null }) { + const project = projectTypeForSite(meta); + return { + path: sitePath, + label: meta.label || pathBasename(sitePath), + project: project.id, + // The stored key is `tracTicket` for both providers (see the note + // above `sites:set-ticket` in main.js); the provider is what tells a + // Trac ticket from a GitHub issue. + workItem: meta.tracTicket ? { provider: project.workItem.provider, id: meta.tracTicket } : null, + branch, + pullRequest, + initialized: Boolean(meta.initialized), + server: { + running: Boolean(server && server.child), + // A server that is still starting has a process and no address yet. + url: (server && server.child && server.url) || null + } + }; +} + +module.exports = { describeSite }; diff --git a/src/main.js b/src/main.js index d88c2c98..431adb4a 100644 --- a/src/main.js +++ b/src/main.js @@ -64,6 +64,8 @@ const { prSubmissionRefusal, prCheckoutRefusal } = require('./renderer/pr-checko const { createProgressThrottle, describeSwitchProgress } = require('./switch-progress.cjs'); const { getStore, peekStore } = require('./settings-store'); const { sitesToResume, readResume } = require('./resume-sites.cjs'); +const { controlEndpoint, cliShimPath, startControlServer } = require('./control-channel.cjs'); +const { describeSite } = require('./control-sites.cjs'); // One name for the send-only progress channel (#173), shared with preload.js // through the tests rather than by import — the renderer bundle and the main @@ -3032,6 +3034,8 @@ app.whenReady().then(async () => { // renderer output into the log file, which only applies to windows created // afterwards. initLogging(); + // Not awaited: the window does not wait for a tool that may never ask. + startControlChannel(); // Before the window: it is made in the theme, and kept in it when the // system's theme changes under 'system'. nativeTheme.on('updated', paintWindowForTheme); @@ -3123,8 +3127,65 @@ app.on('before-quit', () => { ...(playgroundWebServer?.child ? [playgroundWebServer.child] : []) ]; for (const child of children) killChildTree(child); + // Closing it removes the socket file. Not awaited, like the sweep above. + if (controlServer) controlServer.close(); }); +// What a tool outside the window may ask for (#764), by name. This map is the +// whole of it: the channel in control-channel.cjs refuses any name that is not +// a key here. Reads only, so far. Each one answers what the settings file in +// the same directory already says to anything that can open the socket, plus +// what is checked out and what is running. An action that changes a site is a +// different decision from a read: it wants the gates the IPC handler for the +// same change has (`legacySiteBlock`, `mergeInProgressBlock`), and an answer +// to whether the person is asked first. +const controlActions = { + 'sites.list': async () => { + const s = await getStore(); + const siteMeta = s.get('siteMeta') || {}; + // One branch read per site, at once: this runs when a tool asks, not + // on a timer or a render. + const sites = await Promise.all((s.get('sites') || []).map(async (sitePath) => { + const meta = siteMeta[sitePath] || {}; + // Git says what is checked out; the stored name is only for a + // checkout Git cannot read, the rule `activeBranch` follows. + let branch = null; + try { branch = await currentBranchName(sitePath); } catch {} + if (!branch) branch = meta.currentBranch || TRUNK; + return describeSite({ sitePath, meta, branch, pullRequest: prNumberFromRef(branch), server: playgroundServers[sitePath] }); + })); + return { sites }; + } +}; + +let controlServer = null; + +// Starts answering tools outside the window, and writes the `toolkit` command +// they ask through. Both live in the profile directory, so the installed app, +// `npm start` and each e2e journey have their own. A failure costs the command +// and nothing else: it is logged and the app opens as it always did. +async function startControlChannel() { + try { + const userData = app.getPath('userData'); + const endpoint = controlEndpoint({ userData }); + controlServer = await startControlServer({ + endpoint, + actions: controlActions, + onError: (e) => logError('control', `the control channel failed: ${String(e && e.message ? e.message : e)}`) + }); + // Written at every start: an update moves the app, and with it the + // two paths the shim names. The CLI is run from where it ships, like + // the npm CLI the other shims name. + const shimPath = cliShimPath({ userData }); + const shim = cliShim({ execPath: nodeExecPath(), compatPath: null, cliPath: path.join(__dirname, 'cli.cjs'), cliArgs: ['--endpoint', endpoint] }); + await fs.promises.mkdir(path.dirname(shimPath), { recursive: true }); + await fs.promises.writeFile(shimPath, shim, { mode: 0o755 }); + logEvent('control', `answering at ${endpoint}; the command is ${shimPath}`); + } catch (e) { + logError('control', `could not start the control channel: ${String(e && e.message ? e.message : e)}`); + } +} + ipcMain.handle('sites:get', async () => { const s = await getStore(); return s.get('sites'); diff --git a/src/node-shims.cjs b/src/node-shims.cjs index 8159d39b..377ea2dc 100644 --- a/src/node-shims.cjs +++ b/src/node-shims.cjs @@ -40,6 +40,13 @@ function requireArgs(compatPath) { return compatPath ? `--require "${compatPath}" ` : ''; } +// Arguments the app itself puts between a CLI and the caller's own, each one +// quoted the way the paths beside it are. The `toolkit` shim (#764) is the one +// user: it tells the CLI where this profile's app listens. +function quotedArgs(args) { + return args.map((arg) => `"${arg}" `).join(''); +} + // On macOS, a signed Electron removes NODE_OPTIONS from a process that // something outside the app started, and every shim is a bash script: a build // that sets `NODE_OPTIONS=--import=…` for a child lost it, and the child failed @@ -82,9 +89,9 @@ const NODE_OPTIONS_ARGS = [ // POSIX shims are bash scripts. The compat path is interpolated into a quoted // argument, so spaces are safe; unlike NODE_OPTIONS, nothing re-tokenises it. -function posixShim({ execPath, compatPath, cliPath = null, forwardNodeOptions = false }) { +function posixShim({ execPath, compatPath, cliPath = null, cliArgs = [], forwardNodeOptions = false }) { const flag = compatPath ? `${COMPAT_FLAG}=1 ` : ''; - const cli = cliPath ? `"${cliPath}" ` : ''; + const cli = cliPath ? `"${cliPath}" ${quotedArgs(cliArgs)}` : ''; const prelude = forwardNodeOptions ? NODE_OPTIONS_ARGS : ''; // Guarded, since bash before 4.4 calls an empty array unbound under `set -u`. const options = forwardNodeOptions ? '${wptk_opts[@]+"${wptk_opts[@]}"} ' : ''; @@ -94,9 +101,9 @@ function posixShim({ execPath, compatPath, cliPath = null, forwardNodeOptions = // Windows shims are .cmd/.bat. Backslashes inside a quoted command-line argument // are literal — the escaping problem that forces forward slashes in NODE_OPTIONS // does not exist here, so the path goes in as the OS spells it. -function windowsShim({ execPath, compatPath, cliPath = null }) { +function windowsShim({ execPath, compatPath, cliPath = null, cliArgs = [] }) { const flag = compatPath ? `set ${COMPAT_FLAG}=1\r\n` : ''; - const cli = cliPath ? `"${cliPath}" ` : ''; + const cli = cliPath ? `"${cliPath}" ${quotedArgs(cliArgs)}` : ''; return `@echo off\r\nset ELECTRON_RUN_AS_NODE=1\r\n${flag}"${execPath}" ${requireArgs(compatPath)}${cli}%*\r\n`; } @@ -150,9 +157,9 @@ function nodeShim({ execPath, compatPath, platform = process.platform }) { return build({ execPath, compatPath, forwardNodeOptions: platform === 'darwin' }); } -function cliShim({ execPath, compatPath, cliPath, platform = process.platform }) { +function cliShim({ execPath, compatPath, cliPath, cliArgs = [], platform = process.platform }) { const build = platform === 'win32' ? windowsShim : posixShim; - return build({ execPath, compatPath, cliPath, forwardNodeOptions: platform === 'darwin' }); + return build({ execPath, compatPath, cliPath, cliArgs, forwardNodeOptions: platform === 'darwin' }); } module.exports = { nodeShim, cliShim, nodeExecPath, COMPAT_FLAG }; diff --git a/tests/unit/control-sites.test.cjs b/tests/unit/control-sites.test.cjs new file mode 100644 index 00000000..2f5fa101 --- /dev/null +++ b/tests/unit/control-sites.test.cjs @@ -0,0 +1,45 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const { describeSite } = require('../../src/control-sites.cjs'); + +test('a site with nothing linked is described by its folder, its project and its branch', () => { + assert.deepEqual(describeSite({ sitePath: 'C:\\Users\\dev\\sites\\wp one', branch: 'trunk' }), { + path: 'C:\\Users\\dev\\sites\\wp one', + label: 'wp one', + // A record that predates project types is a Core site. + project: 'core', + workItem: null, + branch: 'trunk', + pullRequest: null, + initialized: false, + server: { running: false, url: null } + }); +}); + +test('the work item carries its provider, so a Trac ticket and a GitHub issue are told apart', () => { + const core = describeSite({ sitePath: '/sites/wp', meta: { label: 'My site', tracTicket: 62281, initialized: true }, branch: 'ticket/62281' }); + assert.equal(core.label, 'My site'); + assert.equal(core.initialized, true); + assert.deepEqual(core.workItem, { provider: 'trac', id: 62281 }); + + const gutenberg = describeSite({ sitePath: '/sites/gb', meta: { projectType: 'gutenberg', tracTicket: 70123 }, branch: 'issue/70123' }); + assert.equal(gutenberg.project, 'gutenberg'); + assert.deepEqual(gutenberg.workItem, { provider: 'github-issue', id: 70123 }); +}); + +test('a pull request that is checked out is named', () => { + assert.equal(describeSite({ sitePath: '/sites/wp', branch: 'pr/9000', pullRequest: 9000 }).pullRequest, 9000); +}); + +test('a server is running once it has a process, and has an address once it has said one', () => { + const site = (server) => describeSite({ sitePath: '/sites/wp', branch: 'trunk', server }).server; + + assert.deepEqual(site({ child: {} }), { running: true, url: null }); + assert.deepEqual(site({ child: {}, url: 'http://127.0.0.1:9400' }), { running: true, url: 'http://127.0.0.1:9400' }); + // An entry whose process is gone is not a running server, whatever + // address it still holds. + assert.deepEqual(site({ child: null, url: 'http://127.0.0.1:9400' }), { running: false, url: null }); +}); diff --git a/tests/unit/ipc-wiring.test.cjs b/tests/unit/ipc-wiring.test.cjs index c4a2cb96..831a5edd 100644 --- a/tests/unit/ipc-wiring.test.cjs +++ b/tests/unit/ipc-wiring.test.cjs @@ -379,7 +379,12 @@ function loadMain({ stubs = {}, ready = false } = {}) { try { // Inside the hook, deliberately: building the stubs requires the real // modules, and src/logging.js requires `electron`. - resolveStubs(stubs, stubbed); + // The control channel (#764) starts with the app, and a `ready` load + // would otherwise listen on a real socket in the temporary directory + // the electron stub answers `getPath` with, and write a command beside + // it. A start that never settles does neither; the tests about the + // channel pass their own. + resolveStubs({ './control-channel.cjs': { startControlServer: () => new Promise(() => {}) }, ...stubs }, stubbed); require(MAIN_PATH); } finally { Module._load = originalLoad; @@ -9092,3 +9097,104 @@ test('linking a new ticket from a PR measures trunk before the new branch exists assert.equal(result.branch, 'ticket/60003'); assert.equal(result.prTransition, true); }); + +// --- the control channel (#764) ------------------------------------------- +// +// Not an IPC channel, and the same question: what something other than the +// app's own page can ask the main process for. The socket and its refusals +// are control-channel.integration.test.cjs; this is main.js's half, which is +// the list of actions it hands the channel and what each one answers. + +// Loads main.js through its ready path with the channel recorded in place of +// listening: the actions main.js offered, and the command it wrote. +async function controlWiring(t, settings) { + const profile = tempDir(t, 'ipc-wiring-control-'); + const shimPath = path.join(profile, 'bin', process.platform === 'win32' ? 'toolkit.cmd' : 'toolkit'); + const close = spy(async () => {}); + const startControlServer = spy(async () => ({ close })); + const logEvent = spy(); + const main = loadMain({ + ready: true, + stubs: { + './logging': { ...silentLogging()['./logging'], logEvent }, + ...settings.stubs, + './i18n.cjs': { resolveCatalog: async () => null }, + './control-channel.cjs': { controlEndpoint: () => '/profile/control.sock', cliShimPath: () => shimPath, startControlServer } + } + }); + // The start is not awaited by the ready path; its last step is the log + // line that names the command. + const started = () => logEvent.calls.some(([scope]) => scope === 'control'); + for (let waited = 0; waited < 200 && !started(); waited++) { + await new Promise((resolve) => setImmediate(resolve)); + } + assert.ok(started(), 'the ready path started the control channel'); + return { main, shimPath, close, actions: startControlServer.calls[0][0].actions, endpoint: startControlServer.calls[0][0].endpoint }; +} + +test('the control channel offers reads only, and sites.list answers from the store and from Git', async (t) => { + // One site Git can read, on a branch the store does not name, and one + // whose folder is gone, where the stored branch is all there is. + const onTicket = initRepo(tempDir(t, 'ipc-wiring-control-site-'), { branch: 'ticket/62281' }); + const gone = path.join(os.tmpdir(), 'ipc-wiring-control-gone', 'gb'); + const settings = fakeSettingsStore({ + sites: [onTicket, gone], + siteMeta: { + [onTicket]: { label: 'Login fix', tracTicket: 62281, currentBranch: 'trunk', initialized: true }, + [gone]: { projectType: 'gutenberg', currentBranch: 'pr/7' }, + // A record with no entry in `sites` is not a site. + '/sites/forgotten': { label: 'Forgotten' } + } + }); + const before = structuredClone(settings.values); + const { actions } = await controlWiring(t, settings); + + // The whole door. A second action is a second thing a process other than + // the app can ask for, and belongs in the review of the change that adds + // it rather than arriving unnoticed. + assert.deepEqual(Object.keys(actions), ['sites.list']); + + assert.deepEqual(await actions['sites.list']({}), { + sites: [ + { + path: onTicket, + label: 'Login fix', + project: 'core', + workItem: { provider: 'trac', id: 62281 }, + branch: 'ticket/62281', + pullRequest: null, + initialized: true, + server: { running: false, url: null } + }, + { + path: gone, + label: 'gb', + project: 'gutenberg', + workItem: null, + branch: 'pr/7', + pullRequest: 7, + initialized: false, + server: { running: false, url: null } + } + ] + }); + assert.deepEqual(settings.values, before, 'a listing writes nothing'); +}); + +test('the app writes the toolkit command for its own profile, and stops answering when it quits', async (t) => { + const { main, shimPath, close, endpoint } = await controlWiring(t, fakeSettingsStore()); + + assert.equal(endpoint, '/profile/control.sock'); + const shim = fs.readFileSync(shimPath, 'utf8'); + // Electron's own Node, the app's own CLI, and this profile's address: + // nothing on the host is asked for. + assert.ok(shim.includes('ELECTRON_RUN_AS_NODE=1')); + assert.ok(shim.includes(`"${path.join(SRC_DIR, 'cli.cjs')}" "--endpoint" "/profile/control.sock" `)); + if (process.platform !== 'win32') { + assert.doesNotThrow(() => fs.accessSync(shimPath, fs.constants.X_OK), 'the command can be run'); + } + + assert.equal(close.calls.length, 0); + await main.emitAppEvent('before-quit'); + assert.equal(close.calls.length, 1); +}); diff --git a/tests/unit/node-shims.test.cjs b/tests/unit/node-shims.test.cjs index 1744add3..d2afddb6 100644 --- a/tests/unit/node-shims.test.cjs +++ b/tests/unit/node-shims.test.cjs @@ -69,6 +69,36 @@ test('a CLI shim keeps the preload, the CLI and the arguments in order', () => { assert.ok(npm.indexOf('npm-cli.js') < npm.indexOf('"$@"')); }); +// The `toolkit` shim (#764) tells its CLI where the app listens. Those +// arguments are the app's, so they sit after the CLI, which reads them, and +// before the caller's, and are quoted: a profile path has a space in it on +// macOS ("Application Support"). +test('a CLI shim puts the app\'s own arguments between the CLI and the caller\'s, quoted', () => { + const posix = cliShim({ + execPath: EXEC.darwin, + compatPath: null, + cliPath: '/app/src/cli.cjs', + cliArgs: ['--endpoint', '/Users/dev/Library/Application Support/Toolkit/control.sock'], + platform: 'darwin' + }); + assert.ok(posix.includes('"/app/src/cli.cjs" "--endpoint" "/Users/dev/Library/Application Support/Toolkit/control.sock" "$@"')); + assert.ok(posix.includes('ELECTRON_RUN_AS_NODE=1')); + assert.ok(!posix.includes('--require'), 'the CLI is the app\'s own and needs no compat preload'); + + const win = cliShim({ + execPath: EXEC.win32, + compatPath: null, + cliPath: 'C:\\app\\src\\cli.cjs', + cliArgs: ['--endpoint', '\\\\.\\pipe\\wpct-control-0123456789abcdef'], + platform: 'win32' + }); + assert.ok(win.includes('"C:\\app\\src\\cli.cjs" "--endpoint" "\\\\.\\pipe\\wpct-control-0123456789abcdef" %*')); + + // A shim given none is byte for byte what it was. + const npm = cliShim({ execPath: EXEC.darwin, compatPath: COMPAT.darwin, cliPath: 'npm-cli.js', platform: 'darwin' }); + assert.ok(npm.includes('"npm-cli.js" "$@"')); +}); + // Paths are interpolated into quoted arguments, so a space must not split them. // This is the failure mode that would only ever appear on someone else's machine. test('a path with spaces stays one argument', () => { From 3ad154b3407ccd8836740b6f0ac98570ed5b2303 Mon Sep 17 00:00:00 2001 From: adamsilverstein Date: Fri, 13 Nov 2026 08:52:33 -0800 Subject: [PATCH 03/22] Cover the toolkit command with a journey The unit suite cannot see the app, the shim and the socket working together from a process the app did not start, on a pipe or a socket. Claude-Session: https://claude.ai/code/session_018vwYjUEX6a9RXfZ6jHr6FN --- tests/e2e/journeys/toolkit-command.spec.js | 89 ++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 tests/e2e/journeys/toolkit-command.spec.js diff --git a/tests/e2e/journeys/toolkit-command.spec.js b/tests/e2e/journeys/toolkit-command.spec.js new file mode 100644 index 00000000..87c351d0 --- /dev/null +++ b/tests/e2e/journeys/toolkit-command.spec.js @@ -0,0 +1,89 @@ +/** + * The `toolkit` command (#764): a tool outside the window asking the app that + * is open what sites it has. + * + * The unit suite proves each half: the socket and its refusals, the command's + * arguments and output, the list main.js answers with. What it cannot see is + * the whole of it on a real machine: that the app, started the way it starts, + * listens where the command it wrote looks; that the command runs on + * Electron's own Node, with no Node of the host's, from a process the app did + * not start; and that the pipe on Windows and the socket file elsewhere both + * carry it. So the command is run here the way a terminal runs it, as the file + * in the profile directory, and only its output is read. + * + * What this leaves out: a server that is running, since a journey starts none + * (dev-server.spec.js says why), so `server` is only ever read as stopped; and + * a packaged app, where the command names a CLI inside `app.asar` and a signed + * Helper binary. + * + * Assertions are marked INVARIANT or CHARACTERISATION; see + * ticket-branches.spec.js for why. + */ + +const { spawnSync } = require( 'node:child_process' ); +const fs = require( 'node:fs' ); +const path = require( 'node:path' ); +const { test, expect } = require( '../helpers/app.cjs' ); +const ui = require( '../helpers/ui.cjs' ); +const { makeSite } = require( '../helpers/git-site.cjs' ); + +// Runs the command the app wrote, as a shell would. A `.cmd` cannot be +// spawned directly, so on Windows it goes through cmd.exe, which is also what +// a terminal there does with it. +const WINDOWS = process.platform === 'win32'; +const shimOf = ( session ) => path.join( session.userDataDir, 'bin', WINDOWS ? 'toolkit.cmd' : 'toolkit' ); + +function toolkit( session, ...args ) { + const shim = shimOf( session ); + const result = WINDOWS + ? spawnSync( 'cmd.exe', [ '/d', '/s', '/c', `""${ shim }" ${ args.join( ' ' ) }"` ], { encoding: 'utf8', windowsVerbatimArguments: true, windowsHide: true } ) + : spawnSync( shim, args, { encoding: 'utf8' } ); + return { status: result.status, stdout: result.stdout, stderr: result.stderr }; +} + +test( 'the toolkit command lists the open app\'s sites, and says so when the app is closed', async ( { session } ) => { + const site = await makeSite( session, { label: 'listed-site' } ); + const { page } = await session.start( site.settings ); + await expect( ui.siteHeading( page, 'listed-site' ) ).toBeVisible( { timeout: 30_000 } ); + + // CHARACTERISATION — the command is a file in the profile directory, + // written once the app is listening, which the window does not wait for. + await expect.poll( () => fs.existsSync( shimOf( session ) ), { timeout: 15_000 } ).toBe( true ); + + // INVARIANT — asked for JSON, the command prints the site the app has, + // where it is and what is checked out there, and nothing else on stdout. + const listing = toolkit( session, 'sites', '--json' ); + expect( listing.stderr ).toBe( '' ); + expect( listing.status ).toBe( 0 ); + expect( JSON.parse( listing.stdout ) ).toEqual( { + ok: true, + sites: [ { + path: site.dir, + label: 'listed-site', + project: 'core', + workItem: null, + branch: 'trunk', + pullRequest: null, + initialized: true, + server: { running: false, url: null }, + } ], + } ); + + // INVARIANT — without the flag the same answer is sentences a person reads. + const text = toolkit( session, 'sites' ); + expect( text.status ).toBe( 0 ); + expect( text.stdout ).toContain( 'listed-site (WordPress Core)' ); + expect( text.stdout ).toContain( `Path: ${ site.dir }` ); + expect( text.stdout ).toContain( 'Work: none (branch trunk)' ); + expect( text.stdout ).toContain( 'Server: stopped' ); + + // INVARIANT — asking changed nothing: the site is still the one on screen. + await expect( ui.siteHeading( page, 'listed-site' ) ).toBeVisible(); + + // INVARIANT — with the app closed the command fails, and says why in words + // a tool can pass on, with a code it can branch on. + await session.close(); + const closed = toolkit( session, 'sites', '--json' ); + expect( closed.status ).toBe( 1 ); + expect( JSON.parse( closed.stdout ) ).toMatchObject( { ok: false, code: 'not-running' } ); +} ); From ce946458e616720352ee5ac22b937cc18ee0bd93 Mon Sep 17 00:00:00 2001 From: adamsilverstein Date: Fri, 13 Nov 2026 08:52:33 -0800 Subject: [PATCH 04/22] Document the toolkit command and the control channel Claude-Session: https://claude.ai/code/session_018vwYjUEX6a9RXfZ6jHr6FN --- AGENTS.md | 1 + docs/.vitepress/config.mjs | 1 + docs/guide/toolkit-command.md | 74 +++++++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+) create mode 100644 docs/guide/toolkit-command.md diff --git a/AGENTS.md b/AGENTS.md index cf4a30a8..426d90b2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -127,6 +127,7 @@ When asked to add an existing pull request to an existing stack, preserve its co - **Child processes run on Electron's own Node, not the system Node.** `npm install`, `npm run