diff --git a/tests/e2e/journeys/toolkit-command.spec.js b/tests/e2e/journeys/toolkit-command.spec.js new file mode 100644 index 00000000..4f195219 --- /dev/null +++ b/tests/e2e/journeys/toolkit-command.spec.js @@ -0,0 +1,282 @@ +/** + * The `toolkit` command (#764): a tool outside the window asking the app that + * is open what sites it has, and what one of them logged and mailed. + * + * 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, addPullRequestToOrigin, advanceOrigin, currentBranch, read, LOGIN } = 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 ) { + return toolkitIn( undefined, session, ...args ); +} + +// The same, run in a folder, as a tool working in a checkout runs it. +function toolkitIn( cwd, session, ...args ) { + const shim = shimOf( session ); + const result = WINDOWS + ? spawnSync( 'cmd.exe', [ '/d', '/s', '/c', `""${ shim }" ${ args.join( ' ' ) }"` ], { cwd, encoding: 'utf8', windowsVerbatimArguments: true, windowsHide: true } ) + : spawnSync( shim, args, { cwd, encoding: 'utf8' } ); + return { status: result.status, stdout: result.stdout, stderr: result.stderr }; +} + +test( 'the toolkit command lists the open app\'s sites and reads one\'s log and mail, 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 — run inside the checkout with no site named, the command is + // about that site: it prints the end of the debug.log WordPress wrote + // there. The folder is one the test's own process and the app may know by + // two names (`/var` and `/private/var` on macOS), which is the case a tool + // in a real checkout behind a symlink is in. + const logDir = path.join( site.dir, 'build', 'wp-content' ); + fs.mkdirSync( logDir, { recursive: true } ); + fs.writeFileSync( path.join( logDir, 'debug.log' ), '[13-Nov-2026 09:00:00 UTC] PHP Notice: first\n[13-Nov-2026 09:00:01 UTC] PHP Warning: second\n' ); + const log = toolkitIn( path.join( site.dir, 'src' ), session, 'log', '--lines', '1' ); + expect( log.stderr ).toBe( '' ); + expect( log.status ).toBe( 0 ); + expect( log.stdout.trim() ).toBe( '[13-Nov-2026 09:00:01 UTC] PHP Warning: second' ); + + // INVARIANT — run in a folder that is no site's, it is refused, by name. + const elsewhere = toolkitIn( session.userDataDir, session, 'log', '--json' ); + expect( elsewhere.status ).toBe( 1 ); + expect( JSON.parse( elsewhere.stdout ) ).toMatchObject( { ok: false, code: 'unknown-site' } ); + + // INVARIANT — a site that has sent nothing has no mail, and says so. + const mail = toolkit( session, 'mail', 'listed-site', '--json' ); + expect( mail.status ).toBe( 0 ); + expect( JSON.parse( mail.stdout ) ).toEqual( { ok: true, site: site.dir, total: 0, emails: [] } ); + + // 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' } ); +} ); + +/** + * A tool changing a site: the dev server, started and stopped. + * + * What only a launch can show is the whole road: the command, the socket, + * main's gate, the window asked, the row pressing its own button, the page's + * state read back, and the answer on stdout. And the two things a person + * does first: find the command, and turn the switch on. + * + * Nothing is run, as in dev-server.spec.js, which says what that leaves out: + * the handlers that start and stop a server, start a script and open a page + * in the browser are answered by stubs. The stub that starts the server says + * its address itself, on the channel the real one says it on, and answers at + * once; the real one answers only once the server is up. + */ +test( 'a tool can start and stop a site\'s server only once the settings allow it, and the window shows what it did', async ( { session } ) => { + const URL = 'http://127.0.0.1:9400/'; + const site = await makeSite( session, { label: 'served-site' } ); + const { app, page } = await session.start( site.settings ); + await expect( ui.siteHeading( page, 'served-site' ) ).toBeVisible( { timeout: 30_000 } ); + await expect.poll( () => fs.existsSync( shimOf( session ) ), { timeout: 15_000 } ).toBe( true ); + await app.evaluate( ( { ipcMain }, url ) => { + const asked = { starts: [], stops: [], opened: [] }; + global.__e2eToolkit = asked; + const replace = ( channel, handler ) => { + ipcMain.removeHandler( channel ); + ipcMain.handle( channel, handler ); + }; + replace( 'playground:start', ( event, dir ) => { + asked.starts.push( dir ); + event.sender.send( 'playground:url', { sitePath: dir, url } ); + return { ok: true, url }; + } ); + replace( 'playground:stop', ( event, dir ) => { + asked.stops.push( dir ); + return { ok: true }; + } ); + replace( 'npm:run-script', () => ( { runId: 'e2e-watch' } ) ); + replace( 'npm:kill', () => ( { ok: true } ) ); + replace( 'url:open', ( event, opened ) => { + asked.opened.push( opened ); + return true; + } ); + }, URL ); + const asked = () => app.evaluate( () => global.__e2eToolkit ); + const startButton = page.getByRole( 'button', { name: 'Start development server', exact: true } ); + await expect( startButton.first() ).toBeVisible( { timeout: 30_000 } ); + + // INVARIANT — with the switch as the app ships it, off, a tool is refused + // and told where the switch is, and no server is asked for. + const refused = toolkit( session, 'server', 'start', 'served-site', '--json' ); + expect( refused.status ).toBe( 1 ); + expect( JSON.parse( refused.stdout ) ).toMatchObject( { ok: false, code: 'tools-not-allowed' } ); + expect( ( await asked() ).starts ).toEqual( [] ); + + // INVARIANT — the settings say where the command is, as a shell takes it, + // and hold the switch. + await ui.settingsButton( page ).click(); + const dialog = ui.settingsDialog( page ); + await ui.settingsTab( page, 'Tools' ).click(); + await expect( dialog.getByText( `"${ shimOf( session ) }"`, { exact: true } ) ).toBeVisible(); + const allow = dialog.getByRole( 'switch', { name: 'Let tools on this computer change my sites', exact: true } ); + await expect( allow ).not.toBeChecked(); + await allow.click(); + await expect( allow ).toBeChecked(); + await ui.closeDialogButton( dialog ).click(); + + // INVARIANT — turned on, the command starts the site's server, once, and + // answers with its address; and the page says the server is up, as it + // would had the button been pressed. + const started = toolkit( session, 'server', 'start', 'served-site', '--json' ); + expect( started.stderr ).toBe( '' ); + expect( JSON.parse( started.stdout ) ).toEqual( { ok: true, site: site.dir, url: URL, started: true } ); + expect( ( await asked() ).starts ).toEqual( [ site.dir ] ); + await expect( page.getByRole( 'link', { name: 'View site', exact: true } ).first() ).toBeVisible(); + + // INVARIANT — asked again, it starts nothing and says the address it has. + const again = toolkit( session, 'server', 'start', 'served-site' ); + expect( again.stdout ).toBe( `The server was already running at ${ URL }\n` ); + expect( ( await asked() ).starts ).toEqual( [ site.dir ] ); + + // INVARIANT — stop stops that server, and the page offers the start again. + const stopped = toolkit( session, 'server', 'stop', 'served-site', '--json' ); + expect( JSON.parse( stopped.stdout ) ).toEqual( { ok: true, site: site.dir, stopped: true } ); + expect( ( await asked() ).stops ).toEqual( [ site.dir ] ); + await expect( startButton.first() ).toBeVisible(); +} ); + +/** + * A tool doing a contributor's round on a ticket: link it, build, check out + * the pull request on it, leave it, unlink, and update trunk. + * + * Every one of these is the page's own flow, started from outside, so what + * this asserts is the two things only a launch shows: that the page's + * function was reached with what the tool sent, and that the command was + * answered when the flow had ended and not before. The checkout is read + * from the repository after each answer, which is what "ended" means. + * + * Git is real, against an origin on disk, and so is `npm run build`, which + * in the fixture does nothing and exits 0. What is stubbed is what would + * leave the machine: the ticket's pull requests and attachments, and the + * GitHub account, as in pr-checkout.spec.js. + */ +test( 'a tool links a ticket, builds, checks out and leaves a pull request, unlinks, and updates trunk', async ( { session } ) => { + test.setTimeout( 240_000 ); + const PR = 7; + const site = await makeSite( session, { label: 'worked-site', origin: true } ); + addPullRequestToOrigin( site.origin, PR, { [ LOGIN ]: ' fs.existsSync( shimOf( session ) ), { timeout: 15_000 } ).toBe( true ); + await app.evaluate( ( { ipcMain } ) => { + const replace = ( channel, handler ) => { + ipcMain.removeHandler( channel ); + ipcMain.handle( channel, handler ); + }; + replace( 'git:list-ticket-patches', () => ( { ok: true, prs: { status: 'ok', items: [] } } ) ); + replace( 'trac:list-attachments', () => ( { ok: true, status: 'ok', items: [] } ) ); + replace( 'github:account', () => ( { ok: true, login: 'janedoe', configured: true, testMode: null } ) ); + } ); + const json = ( ...args ) => { + const result = toolkit( session, ...args, 'worked-site', '--json' ); + return { status: result.status, ...JSON.parse( result.stdout ) }; + }; + + // INVARIANT — linked, the site is on the ticket's branch by the time the + // command answers, and the page names the ticket. + const linked = json( 'ticket', 'link', '60001' ); + expect( linked ).toMatchObject( { status: 0, ok: true, ticket: 60001 } ); + expect( currentBranch( site.dir ) ).toBe( linked.branch ); + expect( linked.branch ).not.toBe( 'trunk' ); + await expect( ui.workItemNumber( page, '60001' ).first() ).toBeVisible(); + + // INVARIANT — a script on the terminal's list runs to its end and its + // exit is the answer; one that is a watch, or is not on the list, is + // refused and runs nothing. + expect( json( 'run', 'build' ) ).toMatchObject( { status: 0, ok: true, command: 'npm run build', code: 0 } ); + expect( json( 'run', 'watch' ) ).toMatchObject( { status: 1, ok: false, code: 'unsupported-script' } ); + expect( json( 'run', 'postinstall' ) ).toMatchObject( { status: 1, ok: false, code: 'unsupported-script' } ); + + // INVARIANT — the pull request is checked out, its file is on disk, and + // the build after it has ended, by the time the command answers. + expect( json( 'pr', 'checkout', String( PR ) ) ).toMatchObject( { status: 0, ok: true, pullRequest: PR, checkedOut: true } ); + expect( currentBranch( site.dir ) ).toBe( `pr/${ PR }` ); + expect( read( site.dir, LOGIN ) ).toBe( ' { io.out += s; }, + err: (s) => { io.err += s; }, + send: async (endpoint, request, options) => { + io.sent.push({ endpoint, request, timeoutMs: options.timeoutMs }); + return replies ? replies.shift() : reply; + }, + cwd: CWD, + launch: (app) => io.launched.push(app), + readFile: () => '', + sleep: async () => {}, + ...extra + }); + return { code, ...io }; +} + +const sent = (argv) => { const args = parseArgs(argv); return args.usageError ? args : requestFor(args, CWD); }; + +test('each command sends its action, with what it takes and the site it is about', () => { + assert.deepEqual(sent(['sites']), { action: 'sites.list' }); + assert.deepEqual(sent(['log', 'My site', '--lines', '20']), { action: 'site.log', params: { site: 'My site', lines: 20 } }); + assert.deepEqual(sent(['mail']), { action: 'site.mail', params: { site: CWD } }); + assert.deepEqual(sent(['server', 'start', 'My site']), { action: 'site.server.start', params: { site: 'My site' } }); + assert.deepEqual(sent(['server', 'stop']), { action: 'site.server.stop', params: { site: CWD } }); + assert.deepEqual(sent(['run', 'build']), { action: 'site.script.run', params: { script: 'build', site: CWD } }); + assert.deepEqual(sent(['run', 'test', 'My site']), { action: 'site.script.run', params: { script: 'test', site: 'My site' } }); + assert.deepEqual(sent(['install']), { action: 'site.script.run', params: { script: 'install', site: CWD } }); + assert.deepEqual(sent(['ticket', 'link', '62281', 'My site', '--carry']), { action: 'site.ticket.link', params: { ref: '62281', site: 'My site', carry: true } }); + assert.deepEqual(sent(['ticket', 'link', 'https://core.trac.wordpress.org/ticket/62281']), { action: 'site.ticket.link', params: { ref: 'https://core.trac.wordpress.org/ticket/62281', site: CWD } }); + assert.deepEqual(sent(['ticket', 'unlink']), { action: 'site.ticket.unlink', params: { site: CWD } }); + assert.deepEqual(sent(['patch', 'apply']), { action: 'site.patch.apply-latest', params: { site: CWD } }); + assert.deepEqual(sent(['pr', 'checkout', '9000']), { action: 'site.pr.checkout', params: { number: 9000, site: CWD } }); + assert.deepEqual(sent(['pr', 'leave']), { action: 'site.pr.leave', params: { site: CWD } }); + assert.deepEqual(sent(['update']), { action: 'site.trunk.update', params: { site: CWD } }); + assert.deepEqual(sent(['create', 'Demo site', '--project', 'gutenberg']), { action: 'sites.create', params: { name: 'Demo site', project: 'gutenberg' } }); +}); + +test('a folder written relative to where the command was run is sent whole', () => { + // Only this process knows what `.` is relative to. A name is sent as it is. + assert.equal(sent(['mail', '..']).params.site, path.resolve(CWD, '..')); + assert.equal(sent(['log', './src']).params.site, path.resolve(CWD, 'src')); + assert.equal(sent(['log', 'src']).params.site, 'src'); + assert.equal(sent(['create', 'Demo', '--folder', 'sites']).params.folder, path.resolve(CWD, 'sites')); +}); + +test('the options and the command can come in any order, and help needs no app', async () => { + assert.deepEqual(sent(['--json', 'log', '--lines', '5', 'wp']), { action: 'site.log', params: { site: 'wp', lines: 5 } }); + assert.equal(parseArgs(['--json', 'sites', '--endpoint', ENDPOINT]).json, true); + assert.equal(parseArgs(['--json', 'sites', '--endpoint', ENDPOINT]).endpoint, ENDPOINT); + for (const argv of [[], ['-h'], ['--endpoint', ENDPOINT], ['help']]) assert.equal(parseArgs(argv).command, 'help'); + + const result = await runWith([], { ok: true, result: {} }); + assert.equal(result.code, EXIT.OK); + assert.equal(result.out, USAGE); + assert.deepEqual(result.sent, []); + // Every command there is, is in what help prints. + for (const name of Object.keys(COMMANDS)) assert.ok(USAGE.includes(`\n ${name}`), name); +}); + +test('what is not a command, or does not go with one, is a usage error and not a request', async () => { + const error = (argv) => parseArgs(argv).usageError || ''; + assert.match(error(['delete']), /Unknown command: delete/); + assert.match(error(['constructor']), /Unknown command/); + assert.match(error(['server']), /Unknown command: server/); + assert.match(error(['server', 'restart']), /Unknown command: server restart/); + assert.match(error(['sites', '--force']), /Unknown option: --force/); + assert.match(error(['sites', 'extra']), /Unexpected argument: extra/); + assert.match(error(['log', 'one', 'two']), /Unexpected argument: two/); + assert.match(error(['run']), /run takes a script/); + assert.match(error(['ticket', 'link']), /ticket link takes a ref/); + assert.match(error(['create']), /create takes a name/); + for (const lines of ['0', '1.5', 'many']) assert.match(error(['log', '--lines', lines]), /--lines takes a whole number/, lines); + assert.match(error(['log', '--lines']), /--lines takes a value/); + assert.match(error(['mail', '--lines', '5']), /--lines does not go with mail/); + assert.match(error(['sites', '--carry']), /--carry does not go with sites/); + for (const number of ['x', '0', '1.5']) assert.match(error(['pr', 'checkout', number]), /takes a pull request's number/, number); + + 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('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 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.equal(result.sent[0].endpoint, ENDPOINT); + 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('a log that is not there, or is empty, says so and says where it is', () => { + const file = '/sites/wp/build/wp-content/debug.log'; + assert.match(formatLog({ exists: false, path: file, lines: [] }), /has not written a debug\.log.*\n.*\/sites\/wp\/build\/wp-content\/debug\.log/); + assert.match(formatLog({ exists: true, path: file, lines: [] }), /is empty: \/sites\/wp/); + assert.equal(formatLog({ exists: true, path: file, lines: ['one', 'two'] }), 'one\ntwo\n'); +}); + +test('mail is printed with its text, says when a text was cut, and when there is more than was answered', () => { + const out = formatMail({ total: 2, emails: [ + { sentAt: '2026-11-13T09:00:00.000Z', from: 'wordpress@example.test', to: 'admin@example.test', subject: 'Password Reset', text: 'Someone asked.\nhttp://127.0.0.1:9400/wp-login.php?action=rp\n', textTruncated: false }, + { sentAt: null, from: '', to: '', subject: '', text: 'long', textTruncated: true } + ] }); + assert.equal(out, [ + 'Password Reset', + ' Sent: 2026-11-13T09:00:00.000Z', + ' From: wordpress@example.test', + ' To: admin@example.test', + '', + ' Someone asked.', + ' http://127.0.0.1:9400/wp-login.php?action=rp', + '', + '(no subject)', + ' Sent: unknown', + ' From: ', + ' To: ', + '', + ' long', + ' […]', + '' + ].join('\n')); + assert.match(formatMail({ total: 0, emails: [] }), /No mail from this site has been caught yet/); + assert.match(formatMail({ total: 120, emails: [{ sentAt: null, from: '', to: '', subject: 'One', text: '', textTruncated: false }] }), /The newest 1 of 120 mails\./); +}); + +test('--json prints the answer as one JSON document on stdout, a failure included', async () => { + const good = await runWith(['--endpoint', ENDPOINT, 'sites', '--json'], { ok: true, result: { sites: [SITE] } }); + assert.equal(good.code, EXIT.OK); + assert.deepEqual(JSON.parse(good.out), { ok: true, sites: [SITE] }); + assert.equal(good.err, ''); + + const failure = { ok: false, code: 'unknown-site', error: 'No such site.' }; + const bad = await runWith(['--endpoint', ENDPOINT, 'log', '--json'], failure); + assert.equal(bad.code, EXIT.FAILED); + assert.deepEqual(JSON.parse(bad.out), failure); + assert.equal(bad.err, ''); +}); + +test('without --json a failure is a sentence on stderr, under the output of a command that failed', async () => { + const off = await runWith(['--endpoint', ENDPOINT, 'server', 'start'], { ok: false, code: 'tools-not-allowed', error: 'Changing a site from a tool is turned off.' }); + assert.equal(off.code, EXIT.FAILED); + assert.equal(off.out, ''); + assert.equal(off.err, 'Changing a site from a tool is turned off.\n'); + + const failed = await runWith(['--endpoint', ENDPOINT, 'run', 'build'], { ok: false, code: 'script-failed', error: 'npm run build exited with code 1.', output: 'Error: Cannot find module' }); + assert.equal(failed.err, 'Error: Cannot find module\nnpm run build exited with code 1.\n'); +}); + +test('a change says what was done, in a sentence', async () => { + const says = async (argv, result) => (await runWith(['--endpoint', ENDPOINT, ...argv], { ok: true, result })).out; + + assert.equal(await says(['server', 'start'], { url: 'http://127.0.0.1:9400', started: true }), 'The server is running at http://127.0.0.1:9400\n'); + assert.equal(await says(['server', 'start'], { url: 'http://127.0.0.1:9400', started: false }), 'The server was already running at http://127.0.0.1:9400\n'); + assert.equal(await says(['server', 'stop'], { stopped: true }), 'The server is stopped.\n'); + assert.equal(await says(['server', 'stop'], { stopped: false }), 'The server was not running.\n'); + assert.equal(await says(['ticket', 'link', '62281'], { ticket: 62281, branch: 'ticket/62281' }), 'Linked #62281, on branch ticket/62281.\n'); + assert.equal(await says(['ticket', 'unlink'], { ticket: null }), 'No ticket is linked. The site is on trunk.\n'); + assert.equal(await says(['pr', 'checkout', '9000'], { pullRequest: 9000, checkedOut: true }), 'Checked out pull request #9000.\n'); + assert.equal(await says(['pr', 'checkout', '9000'], { pullRequest: 9000, checkedOut: false }), 'Pull request #9000 was already checked out.\n'); + assert.equal(await says(['pr', 'leave'], { left: true }), 'Left the pull request.\n'); + assert.equal(await says(['patch', 'apply'], { appliedPatch: '62281.2.diff' }), 'Applied 62281.2.diff.\n'); + assert.equal(await says(['patch', 'apply'], { pullRequest: 9000, checkedOut: true }), 'Checked out pull request #9000.\n'); + assert.equal(await says(['update'], { updated: true }), 'Updated to the latest trunk.\n'); + assert.equal(await says(['update'], { updated: false }), 'Already up to date with trunk.\n'); + assert.equal(await says(['run', 'build'], { command: 'npm run build', code: 0, output: 'Done.' }), 'Done.\nnpm run build finished.\n'); + assert.equal(await says(['create', 'Demo'], { site: '/sites/demo', name: 'Demo', project: 'core' }), 'Created Demo at /sites/demo. It is installed and built.\n'); + // What went less than well without failing is said under the answer. + assert.equal(await says(['pr', 'checkout', '9000'], { pullRequest: 9000, checkedOut: true, warning: 'The change was made, but the build failed after it.' }), 'Checked out pull request #9000.\nThe change was made, but the build failed after it.\n'); +}); + +test('a change is given far longer to answer than a read, and a new site longer still', async () => { + const waits = async (argv) => (await runWith(['--endpoint', ENDPOINT, ...argv], { ok: false, code: 'x', error: 'x' })).sent[0].timeoutMs; + const read = await waits(['sites']); + const change = await waits(['server', 'start']); + const create = await waits(['create', 'Demo']); + assert.ok(change > read * 10); + assert.ok(create > change); +}); + +test('with the app closed, an installed app is opened and asked again where it then listens', async () => { + const notRunning = { ok: false, code: 'not-running', error: 'The WordPress Contributor Toolkit is not running. Open it and try again.' }; + const installed = ['--endpoint', '\\\\.\\pipe\\wpct-control-old', '--shim', 'C:\\profile\\bin\\toolkit.cmd', '--app', 'C:\\Program Files\\Toolkit\\Toolkit.exe']; + + // The address is new at every start on Windows: it is read again off the + // shim the app rewrites. + const opened = await runWith([...installed, 'sites'], [notRunning, notRunning, { ok: true, result: { sites: [] } }], { + readFile: () => '"C:\\app\\cli.cjs" "--endpoint" "\\\\.\\pipe\\wpct-control-new" "--shim" "C:\\profile\\bin\\toolkit.cmd" %*' + }); + assert.equal(opened.code, EXIT.OK); + assert.deepEqual(opened.launched, ['C:\\Program Files\\Toolkit\\Toolkit.exe']); + assert.deepEqual(opened.sent.map((s) => s.endpoint), ['\\\\.\\pipe\\wpct-control-old', '\\\\.\\pipe\\wpct-control-new', '\\\\.\\pipe\\wpct-control-new']); + assert.match(opened.err, /Opening the WordPress Contributor Toolkit/); + + // From source, or under a test's profile, the shim names no app: the + // command says the app is closed and starts nothing. + const source = await runWith(['--endpoint', ENDPOINT, 'sites'], notRunning); + assert.equal(source.code, EXIT.FAILED); + assert.deepEqual(source.launched, []); + assert.equal(source.sent.length, 1); + + // Any other failure is not a closed app, and opens nothing. + const refused = await runWith([...installed, 'log'], { ok: false, code: 'unknown-site', error: 'No such site.' }); + assert.deepEqual(refused.launched, []); + + // An app that never starts answering is given up on. + let clock = 0; + const never = await runWith([...installed, 'sites'], notRunning, { now: () => { clock += 20000; return clock; } }); + assert.equal(never.code, EXIT.FAILED); + assert.equal(never.launched.length, 1); + assert.match(never.err, /did not start answering/); + + // An app that could not be started at all is said at once, with why, + // and is not waited a minute for. + const unopened = await runWith([...installed, 'sites'], notRunning, { launch: () => ({ error: new Error('spawn EACCES') }) }); + assert.equal(unopened.code, EXIT.FAILED); + assert.equal(unopened.sent.length, 1); + assert.match(unopened.err, /could not be opened: spawn EACCES/); +}); + +test('the address is read off a shim of either platform, and not off one without it', () => { + assert.equal(endpointInShim('ELECTRON_RUN_AS_NODE=1 "/app/Helper" "/app/cli.cjs" "--endpoint" "/Users/dev/Library/Application Support/Toolkit/control.sock" "$@"\n'), '/Users/dev/Library/Application Support/Toolkit/control.sock'); + assert.equal(endpointInShim('"C:\\app\\cli.cjs" "--endpoint" "\\\\.\\pipe\\wpct-control-abc" %*\r\n'), '\\\\.\\pipe\\wpct-control-abc'); + // And off the shims the app itself writes, with what an installed app adds. + const { cliShim } = require('../../src/node-shims.cjs'); + for (const [platform, endpoint] of [['darwin', '/Users/dev/Library/Application Support/Toolkit/control.sock'], ['win32', '\\\\.\\pipe\\wpct-control-abc']]) { + const shim = cliShim({ execPath: '/app/Helper', compatPath: null, cliPath: '/app/cli.cjs', cliArgs: ['--endpoint', endpoint, '--shim', '/profile/bin/toolkit', '--app', '/app/Toolkit'], platform }); + assert.equal(endpointInShim(shim), endpoint, platform); + } + // What bash would expand is escaped in its shim, and read back as it was. + const odd = '/tmp/profile-$USER/a`b\\c"d/control.sock'; + assert.equal(endpointInShim(cliShim({ execPath: '/app/Helper', compatPath: null, cliPath: '/app/cli.cjs', cliArgs: ['--endpoint', odd], platform: 'linux' })), odd); + assert.equal(endpointInShim(''), null); + assert.equal(endpointInShim(undefined), null); +}); diff --git a/tests/unit/control-channel.integration.test.cjs b/tests/unit/control-channel.integration.test.cjs new file mode 100644 index 00000000..fa9c74dd --- /dev/null +++ b/tests/unit/control-channel.integration.test.cjs @@ -0,0 +1,195 @@ +'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, + ControlRefusal, + 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), options = {}) { + const endpoint = controlEndpoint({ userData }); + const server = await startControlServer({ endpoint, actions, ...options }); + 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 nobody can name ahead of the app', () => { + assert.equal( + controlEndpoint({ userData: '/Users/dev/Library/Application Support/Toolkit', platform: 'darwin' }), + '/Users/dev/Library/Application Support/Toolkit/control.sock' + ); + + // A pipe's name is shared by every account on the machine. One derived + // from the profile path could be taken first by another account, which + // would then answer the command; so no two starts have the same name. + const userData = 'C:\\Users\\dev\\AppData\\Roaming\\Toolkit'; + const first = controlEndpoint({ userData, platform: 'win32' }); + const second = controlEndpoint({ userData, platform: 'win32' }); + assert.match(first, /^\\\\\.\\pipe\\wpct-control-[0-9a-f]{32}$/); + assert.notEqual(first, second); + assert.equal(controlEndpoint({ userData, platform: 'win32', nonce: 'abc' }), '\\\\.\\pipe\\wpct-control-abc'); +}); + +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, with its own code when it refused, and the next request is still served', async (t) => { + const { endpoint } = await serve(t, { + broken: async () => { throw new Error('settings.json is not JSON'); }, + missing: async () => { throw Object.assign(new Error('no such file'), { code: 'ENOENT' }); }, + refuses: async () => { throw new ControlRefusal('unknown-site', 'No such site.'); }, + detailed: async () => { throw Object.assign(new ControlRefusal('script-failed', 'npm run build exited with code 1.'), { detail: { output: 'Error: boom', ok: true, code: 'ok' } }); }, + 'sites.list': async () => ({ sites: [] }) + }); + + assert.deepEqual(await ask(endpoint, { action: 'broken' }), { ok: false, code: REFUSAL_CODES.FAILED, error: 'settings.json is not JSON' }); + // A code on any other error is not the action's refusal: a failed read + // carries `ENOENT`, and that is not something to hand a tool as a reason. + assert.equal((await ask(endpoint, { action: 'missing' })).code, REFUSAL_CODES.FAILED); + assert.deepEqual(await ask(endpoint, { action: 'refuses' }), { ok: false, code: 'unknown-site', error: 'No such site.' }); + // What a refusal carries beside its sentence travels with it, and cannot + // replace the three fields every refusal has. + assert.deepEqual(await ask(endpoint, { action: 'detailed' }), { output: 'Error: boom', ok: false, code: 'script-failed', error: 'npm run build exited with code 1.' }); + 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'); +}); + +// The limit on a client is on how long it takes to ask, not on how long the +// app takes to answer: an action slower than that limit is still answered. +test('a client that says nothing is let go, and one that asked is answered however long that takes', async (t) => { + const { endpoint } = await serve(t, { + slow: () => new Promise((resolve) => setTimeout(() => resolve({ done: true }), 150)) + }, profile(t), { requestTimeoutMs: 40 }); + + assert.deepEqual(await ask(endpoint, { action: 'slow' }), { ok: true, result: { done: true } }); + // Connected, and never sent a line: the server hangs up with no reply. + assert.equal(await sendRaw(endpoint, ''), ''); +}); + +// 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); +}); diff --git a/tests/unit/control-requests.test.cjs b/tests/unit/control-requests.test.cjs new file mode 100644 index 00000000..0ca03bf5 --- /dev/null +++ b/tests/unit/control-requests.test.cjs @@ -0,0 +1,718 @@ +'use strict'; + +// What the window does with a request from the `toolkit` command (#764): +// which row, what to press, and how the end is read. The row here is a +// stand-in with the same two things index.jsx hands over: its state after +// each render, and its own functions. + +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const { + APP_ACTIONS, + SITE_ACTIONS, + SETTLED, + MAX_OUTPUT, + rowActivity, + createControlRegistry, + createOutcomeWaiters, + serverStartPlan, + serverStartOutcome, + serverStopPlan, + serverStopOutcome, + scriptRefusal, + tailOfOutput, + waitForSetup, + performSiteControl, + performAppControl +} = require('../../src/renderer/control-requests.cjs'); +const { pickLatest } = require('../../src/latest-patch.cjs'); + +const URL = 'http://127.0.0.1:9400'; +const CORE_SCRIPTS = ['build', 'build:dev', 'dev', 'test', 'watch', 'grunt']; + +// A row's state: a built site with nothing running, unless said otherwise. +function row(changes = {}) { + const base = { + loading: false, + held: false, + busy: false, + canServe: true, + scripts: CORE_SCRIPTS, + server: { running: false, starting: false, url: '', failure: '' }, + ticket: { blocked: null }, + apply: { fetching: null, preview: null, error: '', conflict: '' }, + patches: { isTrac: true, prs: [], prsStatus: 'ok', prRankComplete: true, prsLoading: false, attachments: [], attachmentsStatus: null, attachmentsLoading: false }, + update: { state: 'idle', dirtyOpen: false, failed: false, summary: null } + }; + const next = { ...base, ...changes }; + for (const key of ['server', 'ticket', 'apply', 'patches', 'update']) next[key] = { ...base[key], ...(changes[key] || {}) }; + return next; +} + +// What main says of the site, which the actions ask for before and after. +const status = (changes = {}) => ({ tracTicket: null, pullRequest: null, appliedPatch: null, buildFailed: false, installFailed: false, updateIncomplete: false, ...changes }); + +// A row as index.jsx wires one. `presses` are recorded and can be given a +// result; `render` is what a render does, handing the new state over. +function mountedRow({ initial = row(), results = {}, statuses = [status()] } = {}) { + const pressed = []; + const waiters = createOutcomeWaiters(); + const state = { snapshot: initial }; + // A mounted row has rendered once, and handed its state over. + waiters.settle(initial); + const remaining = [...statuses]; + const press = (name) => (...args) => { + pressed.push(args.length ? { name, args } : name); + return typeof results[name] === 'function' ? results[name](...args) : results[name]; + }; + const presses = { + readStatus: async () => (remaining.length > 1 ? remaining.shift() : remaining[0]) + }; + for (const name of ['toggleDevServer', 'runTerminalCommand', 'linkRef', 'unlinkTicket', 'previewPullRequest', 'previewAttachment', 'loadTracAttachments', 'loadTicketPatches', 'applyPreview', 'leavePullRequest', 'startTrunkUpdate']) presses[name] = press(name); + return { + pressed, + perform: (action, params = {}) => performSiteControl(action, params, { latest: () => ({ snapshot: state.snapshot, presses }), waiters, deps: { pickLatest } }), + render(next) { + state.snapshot = next; + waiters.settle(next); + }, + waiters + }; +} + +// Lets the awaits inside an action run up to its next wait on the page. +const turn = async () => { for (let i = 0; i < 6; i += 1) await new Promise((resolve) => setImmediate(resolve)); }; + +test('a request goes to the row of the site it names, and a site with no row is refused', async () => { + const registry = createControlRegistry(); + const asked = []; + const unregister = registry.register('/sites/wp', async (action, params) => { asked.push({ action, params }); return { ok: true, result: { url: URL } }; }); + + assert.deepEqual(await registry.handle({ id: '1', action: 'site.server.start', sitePath: '/sites/wp' }), { ok: true, result: { url: URL } }); + assert.deepEqual(asked, [{ action: 'site.server.start', params: {} }]); + + for (const request of [{ action: 'site.server.start', sitePath: '/sites/other' }, null, undefined]) { + assert.equal((await registry.handle(request)).code, 'site-not-open'); + } + unregister(); + assert.equal((await registry.handle({ action: 'site.server.start', sitePath: '/sites/wp' })).code, 'site-not-open'); +}); + +test('a request about no site goes to the window itself, and to no row', async () => { + const registry = createControlRegistry(); + registry.register('/sites/wp', async () => ({ ok: true, result: { from: 'row' } })); + assert.equal((await registry.handle({ action: 'sites.create', sitePath: null, params: { name: 'Demo' } })).code, 'site-not-open'); + + const unregister = registry.registerApp(async (action, params) => ({ ok: true, result: { from: 'app', action, params } })); + assert.deepEqual(await registry.handle({ action: 'sites.create', sitePath: null, params: { name: 'Demo' } }), { ok: true, result: { from: 'app', action: 'sites.create', params: { name: 'Demo' } } }); + assert.deepEqual(await registry.handle({ action: 'x', sitePath: '/sites/wp' }), { ok: true, result: { from: 'row' } }); + unregister(); + assert.equal((await registry.handle({ action: 'sites.create' })).code, 'site-not-open'); +}); + +test('an action nothing has, and a row that throws, are answers', async () => { + const registry = createControlRegistry(); + registry.register('/sites/wp', (action) => { + if (action === 'breaks') throw new Error('the row broke'); + return null; + }); + assert.equal((await registry.handle({ action: 'site.delete', sitePath: '/sites/wp' })).code, 'unknown-action'); + assert.deepEqual(await registry.handle({ action: 'breaks', sitePath: '/sites/wp' }), { ok: false, code: 'failed', error: 'the row broke' }); + assert.equal(await mountedRow().perform('site.delete'), null); + assert.equal(performAppControl('sites.delete', {}, { latest: () => ({}) }), null); +}); + +test('a row that is replaced is not taken out by the one it replaced', async () => { + const registry = createControlRegistry(); + const unregisterOld = registry.register('/sites/wp', async () => ({ ok: true, result: { from: 'old' } })); + registry.register('/sites/wp', async () => ({ ok: true, result: { from: 'new' } })); + unregisterOld(); + assert.deepEqual(await registry.handle({ action: 'x', sitePath: '/sites/wp' }), { ok: true, result: { from: 'new' } }); +}); + +test('the actions the window has are the ones a tool was allowed, and none that loses work', () => { + // A new action here is a new thing a tool can make the window do: main's + // `controlActions` has to offer it, and the settings have to name it. + assert.deepEqual(Object.keys(SITE_ACTIONS), ['site.server.start', 'site.server.stop', 'site.script.run', 'site.ticket.link', 'site.ticket.unlink', 'site.pr.checkout', 'site.pr.leave', 'site.patch.apply-latest', 'site.trunk.update']); + assert.deepEqual(Object.keys(APP_ACTIONS), ['sites.create']); + for (const name of [...Object.keys(SITE_ACTIONS), ...Object.keys(APP_ACTIONS)]) assert.doesNotMatch(name, /delete|discard|revert|submit|open-pr/); +}); + +// --- the server ------------------------------------------------------------ + +test('start presses the button on a built site with no server, and nothing else', () => { + assert.deepEqual(serverStartPlan(row()), { press: true }); + assert.deepEqual(serverStartPlan(row({ server: { running: true, url: URL } })), { done: { ok: true, result: { url: URL, started: false } } }); + // On its way already: the request waits for that start, and does not + // press, which would be a second one. + assert.deepEqual(serverStartPlan(row({ server: { starting: true } })), { wait: true }); + assert.equal(serverStartPlan(row({ canServe: false })).refuse.code, 'not-built'); + assert.equal(serverStartPlan(row({ held: true })).refuse.code, 'busy'); + assert.equal(serverStartPlan(row({ held: true, server: { running: true, url: URL } })).done.result.url, URL); +}); + +test('a start has ended when the server has an address, or when the page stopped starting without one', () => { + const outcome = serverStartOutcome(); + // Before the press has reached the page, a failure it still shows is an + // earlier start's. + assert.equal(outcome(row({ server: { failure: 'The last start timed out.' } })), null); + assert.equal(outcome(row({ server: { starting: true } })), null); + assert.deepEqual(outcome(row({ server: { running: true, url: URL } })), { ok: true, result: { url: URL, started: true } }); + + const failed = serverStartOutcome(); + failed(row({ server: { starting: true } })); + assert.deepEqual(failed(row({ server: { failure: 'Timed out starting the server.' } })), { ok: false, code: 'server-failed', error: 'Timed out starting the server.' }); + // Joined a start already on its way: its end is this one's too. + assert.equal(serverStartOutcome({ begun: true })(row()).code, 'server-failed'); +}); + +test('stop presses the button on a running server, and has ended when nothing is running', () => { + assert.deepEqual(serverStopPlan(row({ server: { running: true, url: URL } })), { press: true }); + assert.deepEqual(serverStopPlan(row()), { done: { ok: true, result: { stopped: false } } }); + assert.equal(serverStopPlan(row({ server: { starting: true } })).refuse.code, 'busy'); + const outcome = serverStopOutcome(); + assert.equal(outcome(row({ server: { running: true, url: URL } })), null); + assert.deepEqual(outcome(row()), { ok: true, result: { stopped: true } }); +}); + +test('a start request presses once, a second one joins it, and both hear the address', async () => { + const site = mountedRow(); + const first = site.perform('site.server.start'); + await turn(); + site.render(row({ server: { starting: true } })); + const second = site.perform('site.server.start'); + await turn(); + assert.deepEqual(site.pressed, ['toggleDevServer']); + + site.render(row({ server: { running: true, url: URL } })); + assert.equal((await first).result.url, URL); + assert.equal((await second).result.url, URL); +}); + +test('a row that goes away answers what it owed, and one that never ends is given up on', async () => { + const site = mountedRow(); + const reply = site.perform('site.server.start'); + await turn(); + site.waiters.abandon(); + assert.equal((await reply).code, 'site-not-open'); + + const waiters = createOutcomeWaiters(); + assert.equal((await waiters.wait(() => null, 20)).code, 'timed-out'); + let answers = 0; + const once = waiters.wait(() => { answers += 1; return { ok: true, result: {} }; }); + waiters.settle(row()); + waiters.settle(row()); + await once; + assert.equal(answers, 1, 'an answer given is given once'); +}); + +// --- scripts --------------------------------------------------------------- + +test('a tool can run what the terminal\'s list has, except the watches that never end', () => { + assert.equal(scriptRefusal('build', CORE_SCRIPTS), null); + assert.equal(scriptRefusal('install', CORE_SCRIPTS), null); + for (const script of ['start', 'postinstall', 'build && rm -rf ~', '', undefined, 7, ['build']]) { + assert.equal(scriptRefusal(script, CORE_SCRIPTS).code, 'unsupported-script', String(script)); + } + for (const script of ['watch', 'dev']) assert.match(scriptRefusal(script, CORE_SCRIPTS).error, /does not end/); + // The list offered is the one that can be run. + assert.match(scriptRefusal('nope', CORE_SCRIPTS).error, /install, build, build:dev, test, grunt\./); +}); + +test('a script is typed into the site\'s terminal, and its exit code and the end of its output are the answer', async () => { + const built = mountedRow({ results: { runTerminalCommand: async () => ({ code: 0, output: 'Done.\n' }) } }); + assert.deepEqual(await built.perform('site.script.run', { script: 'build' }), { ok: true, result: { command: 'npm run build', code: 0, output: 'Done.\n' } }); + assert.deepEqual(built.pressed, [{ name: 'runTerminalCommand', args: ['npm run build'] }]); + + const installed = mountedRow({ results: { runTerminalCommand: async () => ({ code: 0, output: '' }) } }); + await installed.perform('site.script.run', { script: 'install' }); + assert.deepEqual(installed.pressed, [{ name: 'runTerminalCommand', args: ['npm install'] }]); + + const failed = mountedRow({ results: { runTerminalCommand: async () => ({ code: 1, output: 'Error: boom' }) } }); + assert.deepEqual(await failed.perform('site.script.run', { script: 'build' }), { ok: false, code: 'script-failed', error: 'npm run build exited with code 1.', output: 'Error: boom' }); + + // Refused before the terminal is touched, and by the terminal's own lock. + const refused = mountedRow({ initial: row({ busy: true }) }); + assert.equal((await refused.perform('site.script.run', { script: 'build' })).code, 'busy'); + assert.equal((await mountedRow().perform('site.script.run', { script: 'watch' })).code, 'unsupported-script'); + assert.deepEqual(refused.pressed, []); + const locked = mountedRow({ results: { runTerminalCommand: async () => ({ refused: 'busy', output: '' }) } }); + assert.equal((await locked.perform('site.script.run', { script: 'build' })).code, 'busy'); + + assert.equal(tailOfOutput('x'.repeat(MAX_OUTPUT + 50)).length, MAX_OUTPUT); + assert.equal(tailOfOutput('abcdef', 3), 'def'); +}); + +// --- tickets --------------------------------------------------------------- + +test('linking a ticket is the card\'s own link, and its answer is the page\'s', async () => { + const linked = mountedRow({ results: { linkRef: async () => ({ ok: true, ticket: 62281, branch: 'ticket/62281', rebuilding: false }) } }); + assert.deepEqual(await linked.perform('site.ticket.link', { ref: 62281 }), { ok: true, result: { ticket: 62281, branch: 'ticket/62281', rebuilt: false } }); + assert.deepEqual(linked.pressed, [{ name: 'linkRef', args: ['62281', undefined] }]); + + const carried = mountedRow({ results: { linkRef: async () => ({ ok: true, ticket: 62281, branch: 'ticket/62281', rebuilding: false }) } }); + await carried.perform('site.ticket.link', { ref: ' 62281 ', carry: true }); + assert.deepEqual(carried.pressed, [{ name: 'linkRef', args: ['62281', { carryTrunkWork: true }] }]); + + for (const ref of [undefined, '', ' ', {}, ['62281']]) { + assert.equal((await mountedRow().perform('site.ticket.link', { ref })).code, 'invalid-request'); + } + assert.equal((await mountedRow({ initial: row({ busy: true }) }).perform('site.ticket.link', { ref: '62281' })).code, 'busy'); +}); + +test('a link the page refused says why, and edits on trunk are a question for the window or for --carry', async () => { + const refusing = (result) => mountedRow({ results: { linkRef: async () => result } }).perform('site.ticket.link', { ref: '62281' }); + + const dirty = await refusing({ ok: false, code: 'dirty-trunk', canCarry: true, files: 3 }); + assert.equal(dirty.code, 'dirty-trunk'); + assert.match(dirty.error, /3 edited file\(s\).*--carry/); + assert.doesNotMatch((await refusing({ ok: false, code: 'dirty-trunk', canCarry: false, files: null })).error, /--carry/); + + assert.deepEqual(await refusing({ ok: false, code: 'is-pull-request', error: '#70123 is a pull request.' }), { ok: false, code: 'is-pull-request', error: '#70123 is a pull request.' }); + assert.equal((await refusing({ ok: false, code: 'legacy-site', error: 'This site was made by an older version.' })).code, 'legacy-site'); + assert.equal((await refusing({ ok: false, code: 'busy' })).code, 'busy'); + // A press the page turned away before it began answers nothing. + assert.equal((await refusing(undefined)).code, 'failed'); +}); + +test('a switch that puts a pull request back is not over until its rebuild is, and says if that failed', async () => { + const site = mountedRow({ + initial: row({ busy: true }), + results: { linkRef: async () => ({ ok: true, ticket: 62281, branch: 'pr/9000', rebuilding: true }) }, + statuses: [status({ tracTicket: 62281, buildFailed: true })] + }); + // The row was idle when asked; the switch took the lock. + const reply = performSiteControl('site.ticket.link', { ref: '62281' }, { + latest: (() => { let asked = 0; return () => ({ snapshot: asked++ === 0 ? row() : row({ busy: true }), presses: { linkRef: async () => ({ ok: true, ticket: 62281, branch: 'pr/9000', rebuilding: true }), readStatus: async () => status({ tracTicket: 62281, buildFailed: true }) } }); })(), + waiters: site.waiters + }); + let answered = false; + reply.then(() => { answered = true; }); + await turn(); + assert.equal(answered, false, 'still rebuilding'); + site.waiters.settle(row()); + const result = await reply; + assert.equal(result.result.rebuilt, true); + assert.match(result.result.warning, /build failed/); +}); + +test('a switch whose rebuild did not end is answered with why, and not as done', async () => { + const site = mountedRow({ initial: row({ busy: true }) }); + const reply = performSiteControl('site.ticket.link', { ref: '62281' }, { + latest: (() => { let asked = 0; return () => ({ snapshot: asked++ === 0 ? row() : row({ busy: true }), presses: { linkRef: async () => ({ ok: true, ticket: 62281, branch: 'pr/9000', rebuilding: true }), readStatus: async () => status({ tracTicket: 62281 }) } }); })(), + waiters: site.waiters + }); + await turn(); + // The site was closed in the app while it rebuilt. + site.waiters.abandon(); + assert.equal((await reply).code, 'site-not-open'); +}); + +// A discard or a delete is confirmed for the site as it was when asked. +test('a site whose page is asking a question starts nothing a tool asks for', async () => { + const requests = [['site.ticket.link', { ref: '62281' }], ['site.pr.checkout', { number: 9000 }], ['site.pr.leave', {}], ['site.patch.apply-latest', {}], ['site.trunk.update', {}], ['site.script.run', { script: 'build' }]]; + for (const [action, params] of requests) { + const site = mountedRow({ initial: row({ asking: true }), statuses: [status({ tracTicket: 62281, pullRequest: { number: 1 } })] }); + const reply = await site.perform(action, params); + assert.equal(reply.code, 'busy', action); + assert.match(reply.error, /asking a question/, action); + assert.deepEqual(site.pressed, [], action); + } +}); + +test('unlinking a site with nothing linked presses nothing', async () => { + const none = mountedRow(); + assert.deepEqual(await none.perform('site.ticket.unlink'), { ok: true, result: { ticket: null, branch: null, rebuilt: false } }); + assert.deepEqual(none.pressed, []); + + const linked = mountedRow({ statuses: [status({ tracTicket: 62281 }), status()], results: { unlinkTicket: async () => ({ ok: true, ticket: null, branch: 'trunk', rebuilding: false }) } }); + assert.deepEqual(await linked.perform('site.ticket.unlink'), { ok: true, result: { ticket: null, branch: 'trunk', rebuilt: false } }); + assert.deepEqual(linked.pressed, ['unlinkTicket']); +}); + +// --- pull requests --------------------------------------------------------- + +const PR_PREVIEW = { kind: 'pr', number: 9000, label: 'PR #9000' }; + +test('a pull request is previewed, then checked out by the preview\'s own button, and main says it is', async () => { + const site = mountedRow({ statuses: [status(), status({ pullRequest: { number: 9000 } })] }); + const reply = site.perform('site.pr.checkout', { number: 9000 }); + await turn(); + assert.deepEqual(site.pressed, [{ name: 'previewPullRequest', args: [9000] }]); + + site.render(row({ apply: { fetching: 9000 } })); + site.render(row({ apply: { preview: PR_PREVIEW } })); + await turn(); + assert.deepEqual(site.pressed.slice(1), ['applyPreview']); + + site.render(row({ busy: true, apply: { preview: PR_PREVIEW } })); + site.render(row()); + assert.deepEqual(await reply, { ok: true, result: { pullRequest: 9000, checkedOut: true } }); +}); + +test('a pull request that cannot be previewed, or is refused at checkout, is said in the page\'s words', async () => { + const unfetched = mountedRow(); + const noPreview = unfetched.perform('site.pr.checkout', { number: 9000 }); + await turn(); + unfetched.render(row({ apply: { fetching: 9000 } })); + unfetched.render(row({ apply: { error: 'Pull request #9000 could not be fetched.' } })); + assert.deepEqual(await noPreview, { ok: false, code: 'preview-failed', error: 'Pull request #9000 could not be fetched.' }); + assert.deepEqual(unfetched.pressed, [{ name: 'previewPullRequest', args: [9000] }], 'nothing is applied'); + + const dirty = mountedRow(); + const blocked = dirty.perform('site.pr.checkout', { number: 9000 }); + await turn(); + dirty.render(row({ apply: { fetching: 9000 } })); + dirty.render(row({ apply: { preview: PR_PREVIEW } })); + await turn(); + dirty.render(row({ busy: true })); + dirty.render(row({ ticket: { blocked: { files: 2 } }, apply: { preview: PR_PREVIEW } })); + const refused = await blocked; + assert.equal(refused.code, 'dirty-trunk'); + assert.match(refused.error, /2 edited file\(s\)/); + + // The page went idle with nothing said, and main says it is not checked out. + const silent = mountedRow(); + const nothing = silent.perform('site.pr.checkout', { number: 9000 }); + await turn(); + silent.render(row({ apply: { fetching: 9000 } })); + silent.render(row({ apply: { preview: PR_PREVIEW } })); + await turn(); + silent.render(row({ busy: true })); + silent.render(row()); + assert.equal((await nothing).code, 'apply-failed'); +}); + +test('a pull request already checked out, a bad number and a busy site press nothing', async () => { + const already = mountedRow({ statuses: [status({ pullRequest: { number: 9000 } })] }); + assert.deepEqual(await already.perform('site.pr.checkout', { number: 9000 }), { ok: true, result: { pullRequest: 9000, checkedOut: false } }); + for (const number of [undefined, 0, -1, 1.5, 'abc']) assert.equal((await mountedRow().perform('site.pr.checkout', { number })).code, 'invalid-request', String(number)); + const busy = mountedRow({ initial: row({ busy: true }) }); + assert.equal((await busy.perform('site.pr.checkout', { number: 9000 })).code, 'busy'); + assert.deepEqual([...already.pressed, ...busy.pressed], []); +}); + +test('leaving a pull request presses its button, and is nothing to do with none checked out', async () => { + const none = mountedRow(); + assert.deepEqual(await none.perform('site.pr.leave'), { ok: true, result: { pullRequest: null, left: false } }); + assert.deepEqual(none.pressed, []); + + const on = mountedRow({ statuses: [status({ pullRequest: { number: 9000 } }), status({ tracTicket: 62281 })] }); + const reply = on.perform('site.pr.leave'); + await turn(); + assert.deepEqual(on.pressed, ['leavePullRequest']); + on.render(row({ busy: true })); + on.render(row()); + assert.deepEqual(await reply, { ok: true, result: { pullRequest: null, left: true, ticket: 62281 } }); +}); + +// --- the latest patch ------------------------------------------------------ + +const ATTACHMENT = { filename: '62281.2.diff', url: 'https://core.trac.wordpress.org/raw-attachment/ticket/62281/62281.2.diff', applyable: true, dateText: '11/10/2026 10:00:00 AM' }; + +test('the latest patch needs a ticket, and no patch applied already', async () => { + assert.equal((await mountedRow().perform('site.patch.apply-latest')).code, 'no-ticket'); + const applied = mountedRow({ statuses: [status({ tracTicket: 62281, appliedPatch: { label: '62281.diff' } })] }); + const refused = await applied.perform('site.patch.apply-latest'); + assert.equal(refused.code, 'already-applied'); + assert.match(refused.error, /62281\.diff/); + assert.deepEqual(applied.pressed, []); +}); + +test('with nothing on the ticket, or a read of Trac that failed, nothing is applied', async () => { + const empty = mountedRow({ statuses: [status({ tracTicket: 62281 })] }); + const none = empty.perform('site.patch.apply-latest'); + await turn(); + assert.deepEqual(empty.pressed, ['loadTicketPatches', 'loadTracAttachments']); + empty.render(row({ patches: { attachmentsLoading: true } })); + empty.render(row({ patches: { attachmentsStatus: 'ok' } })); + assert.equal((await none).code, 'no-latest-patch'); + + const down = mountedRow({ statuses: [status({ tracTicket: 62281 })] }); + const failed = down.perform('site.patch.apply-latest'); + await turn(); + down.render(row({ patches: { attachmentsLoading: true } })); + down.render(row({ patches: { attachmentsStatus: 'error' } })); + assert.equal((await failed).code, 'trac-failed'); + assert.deepEqual(down.pressed, ['loadTicketPatches', 'loadTracAttachments']); +}); + +test('the latest patch on a Trac ticket is read from Trac, previewed, applied by the preview\'s own button, and named by main', async () => { + const older = { ...ATTACHMENT, filename: '62281.diff', url: `${ATTACHMENT.url}.old`, dateText: '11/01/2026 10:00:00 AM' }; + const screenshot = { filename: 'before.png', url: 'https://core.trac.wordpress.org/raw-attachment/ticket/62281/before.png', applyable: false, dateText: '11/12/2026 10:00:00 AM' }; + const site = mountedRow({ statuses: [status({ tracTicket: 62281 }), status({ tracTicket: 62281, appliedPatch: { label: '62281.2.diff' } })] }); + const reply = site.perform('site.patch.apply-latest'); + await turn(); + site.render(row({ patches: { attachmentsLoading: true } })); + site.render(row({ patches: { attachmentsStatus: 'ok', attachments: [older, screenshot, ATTACHMENT] } })); + await turn(); + // The newest that can be applied: not the older diff, not the screenshot. + assert.deepEqual(site.pressed, ['loadTicketPatches', 'loadTracAttachments', { name: 'previewAttachment', args: [ATTACHMENT] }]); + + site.render(row({ apply: { fetching: ATTACHMENT.url } })); + site.render(row({ apply: { preview: { kind: 'patch', number: null, label: '62281.2.diff' } } })); + await turn(); + assert.equal(site.pressed[3], 'applyPreview'); + site.render(row({ busy: true })); + site.render(row()); + assert.deepEqual(await reply, { ok: true, result: { appliedPatch: '62281.2.diff' } }); +}); + +test('a patch that does not apply is refused in the page\'s words, and nothing is said to be applied', async () => { + const site = mountedRow({ statuses: [status({ tracTicket: 62281 })] }); + const reply = site.perform('site.patch.apply-latest'); + await turn(); + site.render(row({ patches: { attachmentsLoading: true } })); + site.render(row({ patches: { attachmentsStatus: 'ok', attachments: [ATTACHMENT] } })); + await turn(); + site.render(row({ apply: { fetching: ATTACHMENT.url } })); + site.render(row({ apply: { preview: { kind: 'patch', number: null, label: '62281.2.diff' } } })); + await turn(); + site.render(row({ busy: true })); + site.render(row({ apply: { error: 'The patch could not be applied.' } })); + assert.deepEqual(await reply, { ok: false, code: 'apply-failed', error: 'The patch could not be applied.' }); +}); + +test('the latest patch on a GitHub site is its newest pull request, read for this request, with no visit to Trac', async () => { + const pr = { number: 9000, url: 'https://github.com/WordPress/gutenberg/pull/9000', commitDate: '2026-11-12T10:00:00Z' }; + assert.deepEqual(pickLatest({ prs: [pr], attachments: [], prRankComplete: true })?.key, 9000, 'this app\'s own ranking names it'); + // A row that is not the one on screen has never read the list. + const site = mountedRow({ + initial: row({ patches: { isTrac: false, prs: [], prsStatus: null } }), + statuses: [status({ tracTicket: 70123 }), status({ tracTicket: 70123 }), status({ tracTicket: 70123, pullRequest: { number: 9000 } })] + }); + const reply = site.perform('site.patch.apply-latest'); + await turn(); + assert.deepEqual(site.pressed, ['loadTicketPatches']); + site.render(row({ patches: { isTrac: false, prsLoading: true } })); + site.render(row({ patches: { isTrac: false, prs: [pr], prsStatus: 'ok' } })); + await turn(); + assert.deepEqual(site.pressed[1], { name: 'previewPullRequest', args: [9000] }); + site.render(row({ apply: { fetching: 9000 } })); + site.render(row({ apply: { preview: PR_PREVIEW } })); + await turn(); + site.render(row({ busy: true })); + site.render(row()); + assert.deepEqual(await reply, { ok: true, result: { pullRequest: 9000, checkedOut: true } }); +}); + +test('a pull request list that could not be read is not taken for an empty one', async () => { + const site = mountedRow({ statuses: [status({ tracTicket: 62281 })] }); + const reply = site.perform('site.patch.apply-latest'); + await turn(); + site.render(row({ patches: { prsLoading: true, attachmentsLoading: true } })); + site.render(row({ patches: { prsStatus: 'error', attachmentsStatus: 'ok', attachments: [ATTACHMENT] } })); + assert.equal((await reply).code, 'patches-failed'); + assert.deepEqual(site.pressed, ['loadTicketPatches', 'loadTracAttachments'], 'nothing is previewed or applied'); +}); + +// --- trunk ----------------------------------------------------------------- + +test('an update presses the update button and answers when the page and main say it is over', async () => { + const site = mountedRow(); + const reply = site.perform('site.trunk.update'); + await turn(); + assert.deepEqual(site.pressed, ['startTrunkUpdate']); + site.render(row({ busy: true, update: { state: 'fetching' } })); + site.render(row({ busy: true, update: { state: 'building' } })); + site.render(row({ update: { summary: { lockfileChanged: false } } })); + assert.deepEqual(await reply, { ok: true, result: { updated: true, upToDate: false } }); + + const current = mountedRow(); + const nothing = current.perform('site.trunk.update'); + await turn(); + current.render(row({ busy: true, update: { state: 'fetching' } })); + current.render(row()); + assert.deepEqual(await nothing, { ok: true, result: { updated: false, upToDate: true } }); +}); + +test('an update that would reset edits, could not fetch, or did not build is not reported as done', async () => { + const dirty = mountedRow(); + const asked = dirty.perform('site.trunk.update'); + await turn(); + dirty.render(row({ update: { dirtyOpen: true } })); + assert.equal((await asked).code, 'dirty'); + + const offline = mountedRow(); + const failed = offline.perform('site.trunk.update'); + await turn(); + offline.render(row({ busy: true, update: { state: 'fetching' } })); + offline.render(row({ update: { failed: true } })); + assert.equal((await failed).code, 'update-failed'); + + const unbuilt = mountedRow({ statuses: [status({ updateIncomplete: true })] }); + const half = unbuilt.perform('site.trunk.update'); + await turn(); + unbuilt.render(row({ busy: true, update: { state: 'building' } })); + unbuilt.render(row()); + const refused = await half; + assert.equal(refused.code, 'update-failed'); + assert.match(refused.error, /not usable yet/); + + const busy = mountedRow({ initial: row({ busy: true }) }); + assert.equal((await busy.perform('site.trunk.update')).code, 'busy'); + assert.deepEqual(busy.pressed, []); +}); + +// --- a new site ------------------------------------------------------------ + +function app({ creating = false, defaultFolder = '/Users/dev/sites', created = { ok: true, path: '/Users/dev/sites/demo' }, statuses = [{ hasNodeModules: true, hasBuilt: true }] } = {}) { + const asked = []; + const remaining = [...statuses]; + return { + asked, + perform: (params) => performAppControl('sites.create', params, { + latest: () => ({ + snapshot: { creating, defaultFolder }, + presses: { + startSiteSetup: async (options) => { asked.push(options); return created; }, + readStatus: async () => (remaining.length > 1 ? remaining.shift() : remaining[0]), + whenSettled: async () => ({ ok: true, result: {} }) + } + }), + deps: { sleep: async () => {} } + }) + }; +} + +test('a site is made by the dialog\'s own function, in the folder named or the one the settings hold', async () => { + const window = app(); + assert.deepEqual(await window.perform({ name: ' Demo ' }), { ok: true, result: { site: '/Users/dev/sites/demo', project: 'core', name: 'Demo' } }); + assert.deepEqual(window.asked, [{ name: 'Demo', dir: '/Users/dev/sites', projectType: 'core' }]); + + const elsewhere = app(); + await elsewhere.perform({ name: 'Demo', project: 'gutenberg', folder: '/tmp/sites' }); + assert.deepEqual(elsewhere.asked, [{ name: 'Demo', dir: '/tmp/sites', projectType: 'gutenberg' }]); +}); + +test('a site with no name, no folder, an unknown project, or asked for during another setup is not started', async () => { + const refused = async (window, params) => { const reply = await window.perform(params); assert.deepEqual(window.asked, []); return reply.code; }; + assert.equal(await refused(app(), { name: ' ' }), 'invalid-request'); + assert.equal(await refused(app(), {}), 'invalid-request'); + assert.equal(await refused(app(), { name: 'Demo', project: 'drupal' }), 'invalid-request'); + assert.equal(await refused(app({ defaultFolder: null }), { name: 'Demo' }), 'no-folder'); + assert.equal(await refused(app({ creating: true }), { name: 'Demo' }), 'busy'); +}); + +test('a new site is ready when it is installed and built, and a setup that failed says which step', async () => { + const slow = app({ statuses: [{}, { hasNodeModules: true }, { hasNodeModules: true, hasBuilt: true }] }); + assert.equal((await slow.perform({ name: 'Demo' })).ok, true); + + const clone = await app({ created: { ok: false, error: 'The folder already exists.' } }).perform({ name: 'Demo' }); + assert.deepEqual(clone, { ok: false, code: 'setup-failed', error: 'The folder already exists.' }); + + const install = await app({ statuses: [{}, { installFailed: true }] }).perform({ name: 'Demo' }); + assert.equal(install.code, 'setup-failed'); + assert.match(install.error, /npm install failed/); + // The site exists all the same, and the answer says where. + assert.equal(install.site, '/Users/dev/sites/demo'); + + const build = await app({ statuses: [{ hasNodeModules: true, buildFailed: true }] }).perform({ name: 'Demo' }); + assert.match(build.error, /first build failed/); + + // The built folder is there before its build has ended: one that failed + // after is only seen once the row has settled. + const late = await app({ statuses: [{ hasNodeModules: true, hasBuilt: true }, { hasNodeModules: true, hasBuilt: true, buildFailed: true }] }).perform({ name: 'Demo' }); + assert.equal(late.code, 'setup-failed'); + assert.match(late.error, /first build failed/); + assert.equal(late.site, '/Users/dev/sites/demo'); + + let clock = 0; + const never = await waitForSetup('/sites/demo', { readStatus: async () => ({}), sleep: async () => {}, now: () => { clock += 1000; return clock; }, timeoutMs: 5000 }); + assert.equal(never.code, 'timed-out'); +}); + +// --- what the review of this found ------------------------------------------ + +test('what a row is in the middle of is read from the flags its page is drawn from', () => { + const idle = { statusLoading: false, isPending: false, isDeleting: false, isUpdating: false, setupChainState: 'idle', terminalRunning: false, isApplying: false, installing: false, building: false, ticketSaving: false }; + assert.deepEqual(rowActivity(idle), { loading: false, held: false, busy: false }); + assert.deepEqual(rowActivity({ ...idle, statusLoading: true }), { loading: true, held: false, busy: false }); + for (const flag of ['isPending', 'isDeleting']) assert.deepEqual(rowActivity({ ...idle, [flag]: true }), { loading: false, held: true, busy: false }, flag); + assert.deepEqual(rowActivity({ ...idle, setupChainState: 'installing' }), { loading: false, held: true, busy: false }); + for (const flag of ['terminalRunning', 'isApplying', 'installing', 'building', 'ticketSaving']) assert.deepEqual(rowActivity({ ...idle, [flag]: true }), { loading: false, held: false, busy: true }, flag); + // An update holds the site and is work that ends: both. + assert.deepEqual(rowActivity({ ...idle, isUpdating: true }), { loading: false, held: true, busy: true }); +}); + +test('a request for a site whose row is still being mounted waits for it, and is refused only if none comes', async () => { + const registry = createControlRegistry({ rowWaitMs: 40 }); + // The window has only just opened: no row yet. + const early = registry.handle({ action: 'site.server.start', sitePath: '/sites/wp' }); + registry.register('/sites/wp', async () => ({ ok: true, result: { url: URL } })); + assert.deepEqual(await early, { ok: true, result: { url: URL } }); + + assert.equal((await registry.handle({ action: 'site.server.start', sitePath: '/sites/never' })).code, 'site-not-open'); +}); + +test('a request waits for a row that is still reading its site\'s status, and acts on what it then reads', async () => { + const site = mountedRow({ initial: row({ loading: true, canServe: false }) }); + const reply = site.perform('site.server.start'); + await turn(); + assert.deepEqual(site.pressed, [], 'nothing is decided from a status not yet read'); + site.render(row()); + await turn(); + assert.deepEqual(site.pressed, ['toggleDevServer']); + site.render(row({ server: { starting: true } })); + site.render(row({ server: { running: true, url: URL } })); + assert.equal((await reply).result.url, URL); +}); + +test('a press the page turned away without a word is answered as busy, not waited on for half an hour', async () => { + // The terminal was taken between the check and the press: the page says + // so in the terminal, and nothing an answer is read from ever changes. + const waiters = createOutcomeWaiters({ startGraceMs: 30 }); + waiters.settle(row()); + const presses = { startTrunkUpdate: () => {}, readStatus: async () => status() }; + const reply = await performSiteControl('site.trunk.update', {}, { latest: () => ({ snapshot: row(), presses }), waiters }); + assert.equal(reply.code, 'busy'); + + // One that did begin is not cut short by the same clock. + const began = createOutcomeWaiters({ startGraceMs: 30 }); + began.settle(row()); + const running = performSiteControl('site.trunk.update', {}, { latest: () => ({ snapshot: row(), presses }), waiters: began }); + await turn(); + began.settle(row({ busy: true, update: { state: 'fetching' } })); + await new Promise((resolve) => setTimeout(resolve, 60)); + began.settle(row({ update: { summary: {} } })); + assert.deepEqual(await running, { ok: true, result: { updated: true, upToDate: false } }); +}); + +test('a new site is not called ready while its row still has its first build running', async () => { + // The folder that says "built" appears before the build has ended. + let settledAsked = 0; + let release; + const stillBuilding = new Promise((resolve) => { release = resolve; }); + const reply = performAppControl('sites.create', { name: 'Demo' }, { + latest: () => ({ + snapshot: { creating: false, defaultFolder: '/Users/dev/sites' }, + presses: { + startSiteSetup: async () => ({ ok: true, path: '/Users/dev/sites/demo' }), + readStatus: async () => ({ hasNodeModules: true, hasBuilt: true }), + whenSettled: async (sitePath) => { settledAsked += 1; assert.equal(sitePath, '/Users/dev/sites/demo'); await stillBuilding; return { ok: true, result: {} }; } + } + }), + deps: { sleep: async () => {} } + }); + let answered = false; + reply.then(() => { answered = true; }); + await turn(); + assert.equal(settledAsked, 1); + assert.equal(answered, false); + release(); + assert.equal((await reply).ok, true); +}); + +test('the window\'s own question to a row is answered once nothing is running there, and is not an action a tool has', async () => { + assert.equal(Object.hasOwn(SITE_ACTIONS, SETTLED), false); + const site = mountedRow({ initial: row({ held: true }) }); + const settled = site.perform(SETTLED); + let answered = false; + settled.then(() => { answered = true; }); + site.render(row({ busy: true })); + await turn(); + assert.equal(answered, false); + site.render(row()); + assert.deepEqual(await settled, { ok: true, result: {} }); +}); diff --git a/tests/unit/control-sites.test.cjs b/tests/unit/control-sites.test.cjs new file mode 100644 index 00000000..ce5a7e21 --- /dev/null +++ b/tests/unit/control-sites.test.cjs @@ -0,0 +1,134 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const { LOG_LINES, MAX_MAIL_TEXT, describeSite, resolveSite, logLineCount, lastLines, describeEmail } = 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 }); +}); + +// One registry in each platform's spelling, so the folder rule is tested for +// Windows from macOS and the other way round. +const POSIX_SITES = ['/Users/dev/sites/wp', '/Users/dev/sites/wp/nested', '/Users/dev/sites/gb']; +const WIN_SITES = ['C:\\Users\\dev\\sites\\wp']; +const META = { '/Users/dev/sites/wp': { label: 'Login fix' }, '/Users/dev/sites/gb': { label: 'Editor' } }; + +test('a site is named by its path, by a folder inside it, or by its name', () => { + const find = (ref, options = {}) => resolveSite(ref, { sites: POSIX_SITES, siteMeta: META, platform: 'darwin', ...options }); + + assert.deepEqual(find('/Users/dev/sites/wp'), { ok: true, sitePath: '/Users/dev/sites/wp' }); + assert.deepEqual(find('/Users/dev/sites/wp/'), { ok: true, sitePath: '/Users/dev/sites/wp' }); + assert.deepEqual(find('/Users/dev/sites/gb/packages/block-editor'), { ok: true, sitePath: '/Users/dev/sites/gb' }); + // The site the folder is most closely in. + assert.deepEqual(find('/Users/dev/sites/wp/nested/src'), { ok: true, sitePath: '/Users/dev/sites/wp/nested' }); + assert.deepEqual(find('login FIX'), { ok: true, sitePath: '/Users/dev/sites/wp' }); + // A site with no name of its own goes by its folder's. + assert.deepEqual(find('nested'), { ok: true, sitePath: '/Users/dev/sites/wp/nested' }); + + // macOS and Windows do not tell the case of a folder apart; Linux does. + assert.equal(find('/users/DEV/sites/wp/src').ok, true); + assert.equal(find('/users/DEV/sites/wp/src', { platform: 'linux' }).ok, false); + assert.deepEqual( + resolveSite('c:\\users\\dev\\sites\\wp\\src\\wp-admin', { sites: WIN_SITES, platform: 'win32' }), + { ok: true, sitePath: 'C:\\Users\\dev\\sites\\wp' } + ); +}); + +// A backslash is a character of a folder's name anywhere but on Windows. +test('off Windows a backslash in a path does not separate folders', () => { + const sites = ['/sites/a/b', '/sites/a\\b']; + for (const platform of ['darwin', 'linux']) { + assert.deepEqual(resolveSite('/sites/a\\b/src', { sites, platform }), { ok: true, sitePath: '/sites/a\\b' }, platform); + assert.deepEqual(resolveSite('/sites/a/b/src', { sites, platform }), { ok: true, sitePath: '/sites/a/b' }, platform); + } +}); + +test('what names no site, or more than one, is refused with a code, and the answer is never the string sent', () => { + const find = (ref, sites = POSIX_SITES) => resolveSite(ref, { sites, siteMeta: META, platform: 'darwin' }); + + for (const ref of [undefined, null, 7, '', ' ', ['/Users/dev/sites/wp']]) { + assert.equal(find(ref).code, 'unknown-site', String(ref)); + } + // A folder beside a site, one above it, and one whose name only starts + // the same way. + for (const ref of ['/Users/dev/sites', '/Users/dev/sites/wp-other', '/Users/dev/sites/wp/../../.ssh', '/etc']) { + const found = find(ref); + assert.ok(!found.ok || POSIX_SITES.includes(found.sitePath), ref); + } + assert.equal(find('/Users/dev/sites/wp-other').code, 'unknown-site'); + // `..` is resolved before the folder is compared: this one is not in wp. + assert.equal(find('/Users/dev/sites/wp/../../.ssh').code, 'unknown-site'); + assert.deepEqual(find('/Users/dev/sites/wp/../gb/src'), { ok: true, sitePath: '/Users/dev/sites/gb' }); + assert.equal(find('/etc').code, 'unknown-site'); + + assert.equal(find('wp', ['/a/wp', '/b/wp']).code, 'ambiguous-site'); + assert.equal(find('anything', []).code, 'unknown-site'); + assert.equal(resolveSite('wp', { sites: undefined }).code, 'unknown-site'); +}); + +test('the number of log lines is what was asked for, within the limits', () => { + assert.equal(logLineCount(undefined), LOG_LINES.fallback); + assert.equal(logLineCount(20), 20); + assert.equal(logLineCount('20'), 20); + assert.equal(logLineCount(LOG_LINES.max + 1), LOG_LINES.max); + for (const asked of [0, -1, 1.5, 'all', null, {}]) assert.equal(logLineCount(asked), LOG_LINES.fallback, String(asked)); +}); + +test('the end of a log is its last lines, without the half line a read from mid-file begins with', () => { + assert.deepEqual(lastLines('one\ntwo\nthree\n', 2), ['two', 'three']); + assert.deepEqual(lastLines('one\r\ntwo\r\n', 5), ['one', 'two']); + assert.deepEqual(lastLines('', 5), []); + // No newline at the end: the last line is still a line. + assert.deepEqual(lastLines('one\ntwo', 5), ['one', 'two']); + assert.deepEqual(lastLines('f of a line\ntwo\nthree\n', 5, { partialFirst: true }), ['two', 'three']); + // One line longer than the read: what there is of it, not an empty log. + assert.deepEqual(lastLines('the end of one very long line', 5, { partialFirst: true }), ['the end of one very long line']); +}); + +test('a mail is answered with who, what and its text, and a long text is cut and said to be', () => { + assert.deepEqual( + describeEmail({ id: '1', sentAt: '2026-11-13T09:00:00.000Z', from: 'a@example.test', to: 'b@example.test', cc: '', subject: 'Hello', text: 'Body', html: '
Body
', raw: 'x' }), + { sentAt: '2026-11-13T09:00:00.000Z', from: 'a@example.test', to: 'b@example.test', subject: 'Hello', text: 'Body', textTruncated: false } + ); + const long = describeEmail({ text: 'x'.repeat(MAX_MAIL_TEXT + 1) }); + assert.equal(long.text.length, MAX_MAIL_TEXT); + assert.equal(long.textTruncated, true); + assert.deepEqual(describeEmail({}), { sentAt: null, from: '', to: '', subject: '', text: '', textTruncated: false }); +}); diff --git a/tests/unit/control-window.test.cjs b/tests/unit/control-window.test.cjs new file mode 100644 index 00000000..ae294215 --- /dev/null +++ b/tests/unit/control-window.test.cjs @@ -0,0 +1,113 @@ +'use strict'; + +// The waiting between main and the window for what a tool asked the window +// to do (#764). The window itself is a recording `send` here. + +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const { REFUSALS, createWindowRequests } = require('../../src/control-window.cjs'); + +function harness({ sendThrows = false } = {}) { + const sent = []; + let n = 0; + const requests = createWindowRequests({ + send: (request) => { + if (sendThrows) throw new Error('no window'); + sent.push(request); + }, + newId: () => `id-${n += 1}` + }); + return { sent, requests }; +} + +const turn = () => new Promise((resolve) => setImmediate(resolve)); + +test('a request goes to a page that is listening, and its answer comes back by its id', async () => { + const { sent, requests } = harness(); + requests.markReady(); + + const first = requests.ask({ action: 'site.server.start', sitePath: '/sites/wp', params: {} }); + const second = requests.ask({ action: 'site.server.stop', sitePath: '/sites/gb', params: {} }); + await turn(); + assert.deepEqual(sent, [ + { id: 'id-1', action: 'site.server.start', sitePath: '/sites/wp', params: {} }, + { id: 'id-2', action: 'site.server.stop', sitePath: '/sites/gb', params: {} } + ]); + + // Answered out of order: each answer is its own request's. + assert.equal(requests.answer('id-2', { ok: true, result: { stopped: true } }), true); + assert.equal(requests.answer('id-1', { ok: false, code: 'not-built', error: 'Not built.' }), true); + assert.deepEqual(await second, { ok: true, result: { stopped: true } }); + assert.deepEqual(await first, { ok: false, code: 'not-built', error: 'Not built.' }); + assert.equal(requests.pending(), 0); +}); + +test('an answer to nothing, or a second answer, changes nothing', async () => { + const { requests } = harness(); + requests.markReady(); + const asked = requests.ask({ action: 'site.server.start', sitePath: '/sites/wp' }); + await turn(); + + assert.equal(requests.answer('id-9', { ok: true, result: {} }), false); + assert.equal(requests.answer('id-1', { ok: true, result: { url: 'http://127.0.0.1:9400' } }), true); + assert.equal(requests.answer('id-1', { ok: true, result: { url: 'http://evil.example' } }), false); + assert.deepEqual(await asked, { ok: true, result: { url: 'http://127.0.0.1:9400' } }); +}); + +test('an answer that is not one is read as a refusal, not passed on', async () => { + for (const reply of [undefined, null, 'ok', 7, {}, { ok: 'yes' }, { ok: false }, { ok: false, code: 7 }]) { + const { requests } = harness(); + requests.markReady(); + const asked = requests.ask({ action: 'site.server.start', sitePath: '/sites/wp' }); + await turn(); + requests.answer('id-1', reply); + assert.deepEqual(await asked, REFUSALS.UNREADABLE, JSON.stringify(reply)); + } +}); + +test('a request waits for a page that is still loading, and is refused if none comes', async () => { + const { sent, requests } = harness(); + + const waited = requests.ask({ action: 'site.server.start', sitePath: '/sites/wp' }); + await turn(); + assert.deepEqual(sent, [], 'nothing is sent into a page that has not subscribed'); + requests.markReady(); + await turn(); + assert.equal(sent.length, 1); + requests.answer('id-1', { ok: true, result: {} }); + assert.deepEqual(await waited, { ok: true, result: {} }); + + const none = harness(); + assert.deepEqual(await none.requests.ask({ action: 'site.server.start', sitePath: '/sites/wp' }, { readyTimeoutMs: 20 }), REFUSALS.NOT_READY); + assert.deepEqual(none.sent, []); +}); + +test('a page that reloads or a window that closes answers everything it was asked, as gone', async () => { + const { sent, requests } = harness(); + requests.markReady(); + const asked = requests.ask({ action: 'site.server.start', sitePath: '/sites/wp' }); + await turn(); + + requests.reset(); + assert.deepEqual(await asked, REFUSALS.GONE); + // The old page's answer, arriving late, is not the new page's. + assert.equal(requests.answer('id-1', { ok: true, result: {} }), false); + + // The page that follows has to say it is listening before it is asked. + const next = requests.ask({ action: 'site.server.stop', sitePath: '/sites/wp' }); + await turn(); + assert.equal(sent.length, 1); + requests.markReady(); + await turn(); + assert.equal(sent.length, 2); + requests.answer('id-2', { ok: true, result: {} }); + await next; +}); + +test('a window that went away between the check and the send is answered as gone', async () => { + const { requests } = harness({ sendThrows: true }); + requests.markReady(); + assert.deepEqual(await requests.ask({ action: 'site.server.start', sitePath: '/sites/wp' }), REFUSALS.GONE); + assert.equal(requests.pending(), 0); +}); diff --git a/tests/unit/ipc-wiring.test.cjs b/tests/unit/ipc-wiring.test.cjs index a6fe79df..b0aec7d6 100644 --- a/tests/unit/ipc-wiring.test.cjs +++ b/tests/unit/ipc-wiring.test.cjs @@ -9299,3 +9299,311 @@ 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. + // Waited for by the clock and not by a count of turns: the command is + // written with real file calls, which on a loaded Windows runner outlast + // any number of turns that would be reasonable to name. + const started = () => logEvent.calls.some(([scope]) => scope === 'control'); + for (const deadline = Date.now() + 10000; Date.now() < deadline && !started();) { + await new Promise((resolve) => setTimeout(resolve, 5)); + } + 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', 'site.log', 'site.mail', 'site.server.start', 'site.server.stop', 'site.script.run', 'site.ticket.link', 'site.ticket.unlink', 'site.pr.checkout', 'site.pr.leave', 'site.patch.apply-latest', 'site.trunk.update', 'sites.create']); + // Nothing that loses work, and nothing that sends it anywhere. + for (const name of Object.keys(actions)) assert.doesNotMatch(name, /delete|discard|revert|submit|open-pr/); + + 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'); + } + + // The settings are told where it is, to show it and copy it. + assert.deepEqual(await main.invoke('control:command'), { ok: true, path: shimPath }); + + assert.equal(close.calls.length, 0); + await main.emitAppEvent('before-quit'); + assert.equal(close.calls.length, 1); +}); + +test('the settings are told there is no toolkit command while the app is not answering tools', async () => { + // The default load: a control channel that never finishes starting. + const main = loadMain({ stubs: { ...silentLogging(), ...fakeSettingsStore().stubs } }); + assert.deepEqual(await main.invoke('control:command'), { ok: false }); +}); + +test('site.log answers the end of the debug.log of the site named, and only of a site the app has', async (t) => { + const site = tempDir(t, 'ipc-wiring-control-log-'); + const logDir = path.join(site, 'build', 'wp-content'); + const logPath = path.join(logDir, 'debug.log'); + const settings = fakeSettingsStore({ sites: [site], siteMeta: { [site]: { label: 'Login fix' } } }); + const { actions } = await controlWiring(t, settings); + + // Nothing has logged yet: the usual state, and not a failure. + assert.deepEqual(await actions['site.log']({ site }), { site, path: logPath, exists: false, lines: [] }); + + fs.mkdirSync(logDir, { recursive: true }); + fs.writeFileSync(logPath, ''); + assert.deepEqual(await actions['site.log']({ site }), { site, path: logPath, exists: true, lines: [] }); + + fs.writeFileSync(logPath, ['one', 'two', 'three', 'four'].map((n) => `[13-Nov-2026 09:00:00 UTC] PHP Notice: ${n}`).join('\n') + '\n'); + const byName = await actions['site.log']({ site: 'login fix', lines: 2 }); + assert.deepEqual(byName.lines, ['[13-Nov-2026 09:00:00 UTC] PHP Notice: three', '[13-Nov-2026 09:00:00 UTC] PHP Notice: four']); + // A folder inside the site, which is what a tool working there sends. + assert.equal((await actions['site.log']({ site: path.join(site, 'src', 'wp-includes') })).lines.length, 4); + + // A folder that is not a site's is refused before anything is read, with + // a code a tool can branch on. The log is found from the registry's own + // path, so there is no path of the tool's to read from. + const outside = tempDir(t, 'ipc-wiring-control-outside-'); + fs.mkdirSync(path.join(outside, 'build', 'wp-content'), { recursive: true }); + fs.writeFileSync(path.join(outside, 'build', 'wp-content', 'debug.log'), 'not yours\n'); + for (const ref of [outside, path.dirname(site), undefined, '']) { + await assert.rejects(actions['site.log']({ site: ref }), (e) => e.code === 'unknown-site', String(ref)); + } +}); + +test('site.log reads a bounded end of a long log, and drops the half line it begins with', async (t) => { + const { MAX_INITIAL_READ } = require('../../src/log-tail'); + const site = tempDir(t, 'ipc-wiring-control-longlog-'); + const logDir = path.join(site, 'build', 'wp-content'); + fs.mkdirSync(logDir, { recursive: true }); + // Lines of a known length, long enough that fewer fit in one read than + // a tool may ask for: the answer is then every line the read holds, its + // first included, which is the one a read from mid-file cuts in half. + const line = (n) => `line ${String(n).padStart(8, '0')} ${'x'.repeat(1500)}`; + const length = line(0).length + 1; + assert.ok(MAX_INITIAL_READ % length !== 0, 'the read begins inside a line'); + const count = Math.ceil((MAX_INITIAL_READ * 3) / length); + fs.writeFileSync(path.join(logDir, 'debug.log'), Array.from({ length: count }, (_, n) => line(n)).join('\n') + '\n'); + const { actions } = await controlWiring(t, fakeSettingsStore({ sites: [site] })); + + const { lines } = await actions['site.log']({ site, lines: 1000 }); + // Whole lines only, and only as many as one read holds: reading the + // whole file would answer more, and keeping the half line one more. + assert.equal(lines.length, Math.floor(MAX_INITIAL_READ / length)); + assert.equal(lines[lines.length - 1], line(count - 1)); + for (const read of lines) assert.equal(read.length, line(0).length, 'every line answered is a whole one'); +}); + +test('site.log finds a site by the name the OS has for a folder the app knows by another', async (t) => { + const site = tempDir(t, 'ipc-wiring-control-real-'); + const link = path.join(tempDir(t, 'ipc-wiring-control-link-'), 'site'); + // A junction on Windows, which needs no privilege; a symlink elsewhere. + fs.symlinkSync(site, link, 'junction'); + fs.mkdirSync(path.join(site, 'src')); + // The app has the site under the link's name; the tool is in the real folder. + const { actions } = await controlWiring(t, fakeSettingsStore({ sites: [link] })); + + assert.equal((await actions['site.log']({ site: path.join(fs.realpathSync(site), 'src') })).site, link); +}); + +test('site.mail answers the mail caught for the site named, newest first, without its HTML', async (t) => { + const site = tempDir(t, 'ipc-wiring-control-mail-'); + const settings = fakeSettingsStore({ + sites: [site], + [`siteMail:${site}`]: [ + { id: '1', sentAt: '2026-11-13T09:00:00.000Z', from: 'wordpress@example.test', to: 'admin@example.test', subject: 'Older', text: 'first', html: 'first
' }, + { id: '2', sentAt: '2026-11-13T10:00:00.000Z', from: 'wordpress@example.test', to: 'admin@example.test', subject: 'Newer', text: 'second', html: 'second
' } + ], + // Another site's mail is not this one's. + 'siteMail:/sites/other': [{ id: '3', sentAt: '2026-11-13T11:00:00.000Z', subject: 'Not yours', text: 'third' }] + }); + const before = structuredClone(settings.values); + const { actions } = await controlWiring(t, settings); + + assert.deepEqual(await actions['site.mail']({ site }), { + site, + total: 2, + emails: [ + { sentAt: '2026-11-13T10:00:00.000Z', from: 'wordpress@example.test', to: 'admin@example.test', subject: 'Newer', text: 'second', textTruncated: false }, + { sentAt: '2026-11-13T09:00:00.000Z', from: 'wordpress@example.test', to: 'admin@example.test', subject: 'Older', text: 'first', textTruncated: false } + ] + }); + await assert.rejects(actions['site.mail']({ site: '/sites/other' }), (e) => e.code === 'unknown-site'); + assert.deepEqual(settings.values, before, 'reading the mail writes nothing'); +}); + +test('site.mail answers the newest few of a site that has sent a great many, and says how many there are', async (t) => { + const { MAX_MAILS } = require('../../src/control-sites.cjs'); + const site = tempDir(t, 'ipc-wiring-control-manymail-'); + const sent = Array.from({ length: MAX_MAILS + 25 }, (_, n) => ({ id: String(n), sentAt: new Date(Date.UTC(2026, 10, 13, 0, 0, n)).toISOString(), subject: `Mail ${n}`, text: 'x' })); + const { actions } = await controlWiring(t, fakeSettingsStore({ sites: [site], [`siteMail:${site}`]: sent })); + + const answer = await actions['site.mail']({ site }); + assert.equal(answer.total, MAX_MAILS + 25); + assert.equal(answer.emails.length, MAX_MAILS); + assert.equal(answer.emails[0].subject, `Mail ${MAX_MAILS + 24}`, 'the newest is first'); +}); + +// A window's page, as far as main is concerned: it says it is listening, is +// sent requests, and answers them by id. +const controlRequests = (win) => win.sent.filter(({ channel }) => channel === 'control:request').map(({ payload }) => payload); + +test('an action that changes a site is refused until the person turns it on, and nothing reaches the window', async (t) => { + const site = tempDir(t, 'ipc-wiring-control-off-'); + const settings = fakeSettingsStore({ sites: [site] }); + const { main, actions } = await controlWiring(t, settings); + const [win] = main.windows; + await main.invoke('control:ready'); + + // Every action but the three reads. + const changes = Object.keys(actions).filter((name) => !['sites.list', 'site.log', 'site.mail'].includes(name)); + assert.equal(changes.length, 10); + for (const action of changes) { + await assert.rejects(actions[action]({ site, name: 'Demo' }), (e) => e.code === 'tools-not-allowed' && /Settings/.test(e.message), action); + } + // Only a real `true` turns it on. + settings.values.preferences = { toolAccess: 'true' }; + await assert.rejects(actions['site.server.start']({ site }), (e) => e.code === 'tools-not-allowed'); + assert.deepEqual(controlRequests(win), []); +}); + +test('turned on, an action is handed to the window for a site the app has, and the window\'s answer is the action\'s', async (t) => { + const site = tempDir(t, 'ipc-wiring-control-on-'); + const settings = fakeSettingsStore({ sites: [site], siteMeta: { [site]: { label: 'Login fix' } }, preferences: { toolAccess: true } }); + const { main, actions } = await controlWiring(t, settings); + const [win] = main.windows; + await main.invoke('control:ready'); + + // A site the app does not have is refused before the window is asked. + await assert.rejects(actions['site.server.start']({ site: '/sites/unknown' }), (e) => e.code === 'unknown-site'); + assert.deepEqual(controlRequests(win), []); + + // The window is told the registry's path, whatever the tool called the + // site, and nothing of what the tool sent as the site. + const started = actions['site.server.start']({ site: 'login fix' }); + for (let waited = 0; waited < 50 && controlRequests(win).length === 0; waited++) await new Promise((resolve) => setImmediate(resolve)); + const [request] = controlRequests(win); + assert.deepEqual({ ...request, id: null }, { id: null, action: 'site.server.start', sitePath: site, params: {} }); + assert.equal(await main.invoke('control:reply', request.id, { ok: true, result: { url: 'http://127.0.0.1:9400', started: true } }), true); + assert.deepEqual(await started, { site, url: 'http://127.0.0.1:9400', started: true }); + + // The window's refusal is the action's, with its code. + const stopped = actions['site.server.stop']({ site }); + for (let waited = 0; waited < 50 && controlRequests(win).length === 1; waited++) await new Promise((resolve) => setImmediate(resolve)); + await main.invoke('control:reply', controlRequests(win)[1].id, { ok: false, code: 'busy', error: 'The server is still starting.' }); + await assert.rejects(stopped, (e) => e.code === 'busy' && e.message === 'The server is still starting.'); + + // A page that reloads while it is asked answers nothing: the request is + // ended, and not left for a tool to wait on. + const interrupted = actions['site.server.start']({ site }); + for (let waited = 0; waited < 50 && controlRequests(win).length === 2; waited++) await new Promise((resolve) => setImmediate(resolve)); + win.emitNavigation('did-start-loading', win.url); + await assert.rejects(interrupted, (e) => e.code === 'window-closed'); +}); + +test('what an action was sent beside the site reaches the window, and what a refusal carries beside its sentence reaches the tool', async (t) => { + const site = tempDir(t, 'ipc-wiring-control-params-'); + const settings = fakeSettingsStore({ sites: [site], preferences: { toolAccess: true } }); + const { main, actions } = await controlWiring(t, settings); + const [win] = main.windows; + await main.invoke('control:ready'); + const next = async (count) => { + for (let waited = 0; waited < 50 && controlRequests(win).length < count; waited++) await new Promise((resolve) => setImmediate(resolve)); + return controlRequests(win)[count - 1]; + }; + + const ran = actions['site.script.run']({ site, script: 'build' }); + const request = await next(1); + assert.deepEqual({ ...request, id: null }, { id: null, action: 'site.script.run', sitePath: site, params: { script: 'build' } }); + await main.invoke('control:reply', request.id, { ok: false, code: 'script-failed', error: 'npm run build exited with code 1.', output: 'Error: boom' }); + await assert.rejects(ran, (e) => e.code === 'script-failed' && e.detail.output === 'Error: boom'); + + // A new site is about no site: the window is asked with none, and the + // answer names the one it made. + const made = actions['sites.create']({ name: 'Demo', project: 'gutenberg', folder: path.join(os.tmpdir(), 'sites') }); + const creation = await next(2); + assert.deepEqual({ ...creation, id: null }, { id: null, action: 'sites.create', sitePath: null, params: { name: 'Demo', project: 'gutenberg', folder: path.join(os.tmpdir(), 'sites') } }); + await main.invoke('control:reply', creation.id, { ok: true, result: { site: '/sites/demo', name: 'Demo', project: 'gutenberg' } }); + assert.deepEqual(await made, { site: '/sites/demo', name: 'Demo', project: 'gutenberg' }); + + // A folder that is not a full path is refused before the window is asked. + for (const folder of ['sites', '', 7, null]) { + await assert.rejects(actions['sites.create']({ name: 'Demo', folder }), (e) => e.code === 'invalid-request', String(folder)); + } + assert.equal(controlRequests(win).length, 2); +}); diff --git a/tests/unit/node-shims.test.cjs b/tests/unit/node-shims.test.cjs index 1744add3..5277c218 100644 --- a/tests/unit/node-shims.test.cjs +++ b/tests/unit/node-shims.test.cjs @@ -69,6 +69,39 @@ 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' + }); + // Run from a person's own cmd.exe, the shim must not leave Electron's + // run-as-Node switch set in that window once it has finished. + assert.ok(win.includes('setlocal') && win.indexOf('setlocal') < win.indexOf('set ELECTRON_RUN_AS_NODE=1')); + 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', () => { @@ -258,3 +291,61 @@ test('a Helper path with spaces survives into a working shim', () => { assert.ok(shim.includes(`--require "${COMPAT.darwin}"`)); assert.ok(shim.includes('ELECTRON_RUN_AS_NODE=1')); }); + +// The `toolkit` shim's arguments name the profile's folder, which is the +// person's to choose (#764). Inside double quotes bash still expands `$` and +// a backtick, and a batch file expands `%`. +test('what a shell would expand in a CLI shim\'s arguments reaches the CLI as written', { skip: process.platform === 'win32' && 'runs a bash shim' }, () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wptk-shim-')); + try { + const cli = path.join(dir, 'cli.js'); + fs.writeFileSync(cli, 'process.stdout.write(JSON.stringify(process.argv.slice(2)));'); + const odd = '/tmp/pro file-$USER/`whoami`/a\\b"c/control.sock'; + const shim = path.join(dir, 'toolkit'); + fs.writeFileSync(shim, cliShim({ execPath: process.execPath, compatPath: null, cliPath: cli, cliArgs: ['--endpoint', odd], platform: 'linux' }), { mode: 0o755 }); + const ran = spawnSync(shim, ['sites'], { encoding: 'utf8' }); + assert.deepEqual(JSON.parse(ran.stdout), ['--endpoint', odd, 'sites']); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test('a percent sign in a Windows CLI shim\'s arguments is doubled, which a batch file reads as one', () => { + const win = cliShim({ execPath: EXEC.win32, compatPath: null, cliPath: 'C:\\app\\src\\cli.cjs', cliArgs: ['--shim', 'C:\\Users\\100%\\bin\\toolkit.cmd'], platform: 'win32' }); + assert.ok(win.includes('"--shim" "C:\\Users\\100%%\\bin\\toolkit.cmd" %*')); +}); + +// An AppImage's mount, and the binary in it, are gone once the app quits +// (#764): the shim is all that is left, and it answers for a closed app. +test('a CLI shim told its binary can go says the app is closed when it has, as JSON when asked', { skip: process.platform === 'win32' && 'runs a bash shim' }, () => { + const message = 'The WordPress Contributor Toolkit is not running. Open it and try again.'; + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wptk-shim-')); + try { + const write = (name, execPath, cliPath) => { + const file = path.join(dir, name); + fs.writeFileSync(file, cliShim({ execPath, compatPath: null, cliPath, cliArgs: [], platform: 'linux', goneMessage: message }), { mode: 0o755 }); + return file; + }; + const gone = write('gone', path.join(dir, 'mount', 'toolkit'), path.join(dir, 'mount', 'cli.cjs')); + const plain = spawnSync(gone, ['sites'], { encoding: 'utf8' }); + assert.equal(plain.status, 1); + assert.equal(plain.stdout, ''); + assert.equal(plain.stderr, `${message}\n`); + const json = spawnSync(gone, ['sites', '--json'], { encoding: 'utf8' }); + assert.equal(json.status, 1); + assert.deepEqual(JSON.parse(json.stdout), { ok: false, code: 'not-running', error: message }); + assert.equal(json.stderr, ''); + + // With the binary there, the shim runs it as any other does. + const cli = path.join(dir, 'cli.js'); + fs.writeFileSync(cli, 'process.stdout.write(JSON.stringify(process.argv.slice(2)));'); + const here = spawnSync(write('here', process.execPath, cli), ['sites', '--json'], { encoding: 'utf8' }); + assert.deepEqual(JSON.parse(here.stdout), ['sites', '--json']); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } + + // A shim not told so has no such check, and neither has a Windows one. + assert.ok(!cliShim({ execPath: EXEC.darwin, compatPath: null, cliPath: '/app/src/cli.cjs', platform: 'darwin' }).includes('not-running')); + assert.ok(!cliShim({ execPath: EXEC.win32, compatPath: null, cliPath: 'C:\\app\\src\\cli.cjs', platform: 'win32', goneMessage: message }).includes('not-running')); +}); diff --git a/tests/unit/settings-view.test.cjs b/tests/unit/settings-view.test.cjs index 60e7a36e..9525d825 100644 --- a/tests/unit/settings-view.test.cjs +++ b/tests/unit/settings-view.test.cjs @@ -3,7 +3,7 @@ const test = require('node:test'); const assert = require('node:assert/strict'); -const { editorItems, editorGone, editorName, editorValue, ASK_FOR_EDITOR, githubAccountLine, newSiteLocationNote, languageItems, languageValue, languageChanged, phpVersionChoice, quitItems, themeItems, colorFieldDraft, pickerValue, resumeFor, SYSTEM_LANGUAGE } = require('../../src/renderer/settings-view.cjs'); +const { toolkitCommandLine, editorItems, editorGone, editorName, editorValue, ASK_FOR_EDITOR, githubAccountLine, newSiteLocationNote, languageItems, languageValue, languageChanged, phpVersionChoice, quitItems, themeItems, colorFieldDraft, pickerValue, resumeFor, SYSTEM_LANGUAGE } = require('../../src/renderer/settings-view.cjs'); test('the GitHub line says the account is still being read, and offers no sign-out, until it is', () => { assert.deepEqual(githubAccountLine(null), { text: 'Reading…', canSignOut: false }); @@ -139,3 +139,17 @@ test('asking each time is kept as no choice, and an editor as its id (#738)', () assert.equal(editorValue(ASK_FOR_EDITOR), null); assert.equal(editorValue('cursor'), 'cursor'); }); + +test('the Tools tab shows the toolkit command quoted, as a shell needs a path with a space in it, and copies the same', () => { + assert.deepEqual(toolkitCommandLine(null), { text: 'Reading…', copy: null }); + + const mac = '/Users/jane/Library/Application Support/WordPress Contributor Toolkit/bin/toolkit'; + assert.deepEqual(toolkitCommandLine({ ok: true, path: mac }), { text: `"${mac}"`, copy: `"${mac}"` }); + + // The app could not start answering tools: nothing to copy, and why. + for (const none of [{ ok: false }, { ok: true }, { ok: true, path: '' }]) { + const line = toolkitCommandLine(none); + assert.equal(line.copy, null); + assert.match(line.text, /not available/); + } +});