Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

quickshell/nuguland/test-fixtures/ui/niri-integration.mjs

Raw
import assert from 'node:assert/strict';
import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { rootEntry } from '../sources.js';

// Registry features whose production service this fixture proves natively:
// their doubles are not overlaid here, and niri-integration.qml binds the
// registry inputs these services need.
export const nativeFeatures = Object.freeze(['clipboard']);

// Verify a kernel-owned direct child, never a process-name search or parent PID.
export function assertSubscription(pid, qmlPid, status, command) {
    assert(Number.isSafeInteger(pid) && pid > 1 && Number.isSafeInteger(qmlPid) && qmlPid > 1);
    assert.equal(Number(status.match(/^PPid:\s+(\d+)$/m)?.[1]), qmlPid, 'subscription must be a direct QML child');
    assert.deepEqual(command.split('\0').filter(Boolean), ['/usr/bin/niri', 'msg', '--json', 'event-stream']);
}

export async function prepareNiriIntegration({ run, start, waitFor, runtime, nativeNiri, nativeSocket }) {
    writeFileSync('/project/Niri.qml', nativeNiri);
    writeFileSync('/project/niri-integration-ui-test.qml', rootEntry(readFileSync('/project/test-fixtures/ui/niri-integration.qml', 'utf8'), 2));
    const protocol = '/usr/share/wayland-protocols/stable/xdg-shell/xdg-shell.xml';
    run('wayland-scanner', ['client-header', protocol, '/tmp/niri-integration-xdg.h']);
    run('wayland-scanner', ['private-code', protocol, '/tmp/niri-integration-xdg.c']);
    run('cc', ['-Wall', '-Wextra', '-Werror', '-I/tmp', '/project/test-fixtures/ui/niri-integration-client.c', '/tmp/niri-integration-xdg.c', '-lwayland-client', '-o', '/tmp/niri-integration-client']);
    const socket = join(runtime, 'niri.integration.sock');
    const modeFile = join(runtime, 'niri-integration-outputs.json');
    writeFileSync(modeFile, 'null');
    start('node', ['/project/test-fixtures/ui/niri-integration-proxy.mjs', socket, nativeSocket, modeFile], 'niri-integration-proxy');
    await waitFor('output fixture socket', () => existsSync(socket));
    return { socket, modeFile };
}

export async function runNiriIntegration({ run, start, check, snapshot, ipc, screenshot, click, input, key, compositorKey, stop, evidence, runtime, modeFile }) {
    const action = (...args) => run('niri', ['msg', 'action', ...args.map(String)]);
    const query = name => JSON.parse(run('niri', ['msg', '--json', name]));
    async function closeClient(client) {
        action('close-window', '--id', client.id);
        let timeout;
        try {
            if (client.child.exitCode === null) await new Promise((resolve, reject) => {
                timeout = setTimeout(() => reject(new Error('native client did not acknowledge close')), 3000);
                client.child.once('exit', resolve);
            });
            assert.equal(client.child.exitCode, 0, 'xdg close must exit normally');
            assert.equal(client.child.signalCode, null);
            await stop(client.child);
        } finally {
            clearTimeout(timeout);
        }
    }
    let state = await check('real stream initial state and actual Bar pills', s => s.niri.ready && s.niri.outputCount === 1 && s.niri.windowCount === 0 && s.pills.length === 1 && s.pills[0].active);
    const firstWorkspace = state.niri.workspaces.find(row => row.is_focused).idx;
    async function client(name, title, app) {
        const fifo = join(runtime, `niri-integration-${name}.fifo`);
        run('mkfifo', [fifo]);
        const child = start('/tmp/niri-integration-client', [fifo, title, app], `niri-client-${name}`);
        await check(`native xdg window opens: ${name}`, s => s.niri.focusedTitle === title && s.niri.focusedAppId === app);
        return { child, fifo, id: snapshot().niri.focusedWindow };
    }
    const alpha = await client('alpha', 'alpha initial', 'synthetic.alpha');
    writeFileSync(alpha.fifo, 'title alpha renamed\n');
    await check('focused title delta replaces existing record', s => s.niri.windowCount === 1 && s.niri.focusedTitle === 'alpha renamed' && s.text.includes('focus: alpha renamed · synthetic.alpha'));
    writeFileSync(alpha.fifo, 'app synthetic.changed\n');
    state = await check('focused app-id delta reaches visible context', s => s.niri.focusedAppId === 'synthetic.changed');
    // The real SurfaceManager emits the registry entry's opening; the registry hands
    // the vault double the native focused app. Each opening is closed again by its chip.
    async function openVault(name, opens, app) {
        click(snapshot().vault.rect);
        const opened = await check(name, s => s.vault.open && s.vault.opens === opens && s.vault.app === app && s.vault.opened === 'vault');
        click(opened.vault.rect);
        await check(`vault chip closes opening ${opens}`, s => !s.vault.open && s.vault.opens === opens);
    }
    await openVault('actual Bar opening forwards focused app to the vault', 1, 'synthetic.changed');
    const beta = await client('beta', 'beta window', 'synthetic.beta');
    action('move-window-to-workspace', '2');
    state = await check('workspace deltas add populated second pill', s => s.pills.length === 2 && s.niri.workspaces.some(row => row.idx === 2 && row.active_window_id === beta.id));
    click(state.pills.find(row => row.index === String(firstWorkspace)).rect);
    state = await check('actual Bar pill focuses first workspace and alpha', s => s.niri.focusedWindow === alpha.id && s.pills.find(row => row.index === String(firstWorkspace))?.active);
    await openVault('vault context updates on each opening after external focus', 2, 'synthetic.changed');
    action('focus-window', '--id', beta.id);
    state = await check('external focus reaches second workspace and beta', s => s.niri.focusedWindow === beta.id && s.pills.find(row => row.index === '2')?.active);
    await openVault('vault receives changed focused app, not retained prior context', 3, 'synthetic.beta');
    await screenshot('niri-bar-two-workspaces');
    action('toggle-overview');
    await check('native overview opens through stream', s => s.niri.overviewState === 'open');
    await compositorKey('Escape');
    await check('keyboard closes native overview', s => s.niri.overviewState === 'closed');

    // Only the subscription dies. Mutate a client before the bounded retry fires.
    state = snapshot();
    const pid = state.subscriptionPid;
    assertSubscription(pid, state.qmlPid, readFileSync(`/proc/${pid}/status`, 'utf8'), readFileSync(`/proc/${pid}/cmdline`, 'utf8'));
    const transitionCount = state.readiness.length;
    const originalQmlPid = state.qmlPid;
    writeFileSync(join(evidence, 'niri-subscription.json'), JSON.stringify({ pid, qmlPid: state.qmlPid, command: ['/usr/bin/niri', 'msg', '--json', 'event-stream'] }, null, 2));
    process.kill(pid, 'SIGTERM');
    writeFileSync(beta.fifo, 'title beta during disconnect\n');
    state = await check('subscription disconnect clears readiness and reconnects with fresh state', s => s.readiness.slice(transitionCount).some(row => !row.ready) && s.niri.ready && s.subscriptionPid !== pid && s.niri.focusedTitle === 'beta during disconnect');
    assert.equal(state.qmlPid, originalQmlPid);
    assert(state.readiness.slice(transitionCount).find(row => !row.ready).windows === 0);

    const original = query('outputs');
    const outputName = Object.keys(original)[0];
    run('niri', ['msg', 'output', outputName, 'position', 'set', '400', '120']);
    const repositioned = query('outputs');
    writeFileSync(join(evidence, 'niri-reposition.json'), JSON.stringify({ original, repositioned }, null, 2));
    assert.equal(repositioned[outputName].logical.x, 400);
    assert.equal(repositioned[outputName].logical.y, 120);
    await check('real output reposition reaches outputs-only poll', s => s.niri.outputs[outputName].logical.x === 400 && s.niri.outputs[outputName].logical.y === 120);
    run('niri', ['msg', 'output', outputName, 'position', 'set', '0', '0']);
    const stable = snapshot().niri;
    const extra = { ...original[outputName], name: 'fixture-hotplug', logical: { ...original[outputName].logical, x: -1280 } };
    assert.equal(ipc('fixtureOutputs', 'true'), 'true');
    // The proxy reads this file on every fast output poll; replace it atomically.
    const setMode = text => { writeFileSync(`${modeFile}.next`, text); renameSync(`${modeFile}.next`, modeFile); };
    setMode(JSON.stringify({ Ok: { Outputs: { ...original, 'fixture-hotplug': extra } } }));
    await check('fixture hotplug enters production outputs query without resetting stream', s => s.niri.outputCount === 2 && s.niri.outputs['fixture-hotplug'].logical.x === -1280 && s.niri.focusedTitle === stable.focusedTitle && s.niri.windowCount === stable.windowCount);
    setMode(JSON.stringify({ Err: 'controlled output query rejection' }));
    await check('rejected outputs query preserves last inventory and stream readiness', s => s.niri.outputError.length > 0 && s.niri.outputCount === 2 && s.niri.ready);
    setMode('null');
    await check('fixture unplug restores real inventory through periodic polling', s => s.niri.outputCount === 1 && s.niri.outputError === '' && !s.niri.outputs['fixture-hotplug']);

    assert.equal(ipc('fixtureOutputs', 'false'), 'true');

    await closeClient(beta);
    await check('native close removes beta from the streamed window inventory', s => !s.niri.windows.some(row => row.id === beta.id) && s.niri.windowCount === 1);
    action('focus-window', '--id', alpha.id);
    await check('remaining window regains focus', s => s.niri.focusedWindow === alpha.id);
    await closeClient(alpha);
    await check('closing last native window clears title/app and retains one active pill', s => s.niri.windowCount === 0 && s.niri.focusedTitle === '' && s.niri.focusedAppId === '' && s.pills.length === 1);
    ipc('pasteFixture');
    state = await check('synthetic paste destination gains native focus', s => s.niri.focusedTitle === 'paste destination' && s.paste.destinationFocused && s.paste.destinationEmpty);
    const destinationId = state.niri.focusedWindow;
    click(state.paste.chip);
    state = await check('clipboard search owns popup focus before paste', s => s.paste.open && s.paste.searchFocused && s.paste.target === destinationId && s.paste.button);
    input('type', 'focus-safe');
    state = await check('clipboard destination search is retained', s => s.paste.queryPreserved && s.paste.destinationEmpty);
    click(state.paste.button);
    await check('pointer paste releases popup and types exactly once into destination', s => !s.paste.open && !s.paste.pending && s.paste.destinationMatches && s.paste.queryPreserved && s.niri.focusedWindow === destinationId && s.paste.error === '');
    await screenshot('clipboard-paste-pointer');
    key('ctrl+a');
    key('BackSpace');
    state = await check('destination editor remains keyboard operable after paste', s => s.paste.destinationEmpty);
    click(state.paste.chip);
    state = await check('clipboard reopen restores search before keyboard paste', s => s.paste.open && s.paste.searchFocused && s.paste.queryPreserved);
    key('Return');
    await check('keyboard paste returns focus and inserts exactly once', s => !s.paste.open && !s.paste.pending && s.paste.destinationMatches && s.paste.queryPreserved && s.niri.focusedWindow === destinationId && s.paste.error === '');
    await screenshot('clipboard-paste-keyboard');
    console.log('niri interaction assertions completed; complete runtime-log gate remains mandatory');
}