Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

24.8 KB
Raw Blame
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { createServer } from 'node:http';
import path from 'node:path';
import { after, before, test } from 'node:test';
import { fileURLToPath } from 'node:url';

import { webkit } from 'playwright';

const docsRoot = fileURLToPath(new URL('..', import.meta.url));
const dist = path.join(docsRoot, 'dist');
const mobileWidths = [320, 393];
const mimeTypes = new Map([
  ['.css', 'text/css'],
  ['.gif', 'image/gif'],
  ['.html', 'text/html'],
  ['.js', 'text/javascript'],
  ['.json', 'application/json'],
  ['.svg', 'image/svg+xml'],
  ['.webp', 'image/webp'],
]);

let server;
let baseUrl;

before(async () => {
  server = createServer(async (request, response) => {
    const url = new URL(request.url, 'http://127.0.0.1');
    const relative = decodeURIComponent(url.pathname).replace(/^\/+/, '');
    const file = path.join(dist, relative, url.pathname.endsWith('/') ? 'index.html' : '');
    try {
      const body = await readFile(file);
      response.writeHead(200, { 'content-type': mimeTypes.get(path.extname(file)) ?? 'application/octet-stream' });
      response.end(body);
    } catch {
      response.writeHead(404);
      response.end('Not found');
    }
  });
  await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
  baseUrl = `http://127.0.0.1:${server.address().port}`;
});

after(async () => {
  await new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve())));
});

async function sitemapRoutes() {
  const sitemap = await readFile(path.join(dist, 'sitemap-0.xml'), 'utf8');
  return [...sitemap.matchAll(/<loc>([^<]+)<\/loc>/gu)]
    .map((match) => new URL(match[1]).pathname);
}

// Layout checks measure the page as set in its web fonts. The stylesheet loads
// them with `display=swap`, so at DOMContentLoaded text can still be in a wider
// fallback face, and a terminal sized to the column overflows it.
async function openPage(page, url) {
  await page.goto(url, { waitUntil: 'load' });
  await page.evaluate(() => document.fonts.ready);
}

// Every page header carries the shields.io GitHub-stars badge, the one
// third-party resource besides the web fonts. Serve a stand-in at the badge's
// declared size so `load` waits only on the local server and the fonts.
const starsBadge = '<svg xmlns="http://www.w3.org/2000/svg" width="90" height="20"></svg>';

async function newPage(browser, options) {
  const page = await browser.newPage(options);
  await page.route('https://img.shields.io/**', (route) => route.fulfill({
    contentType: 'image/svg+xml',
    body: starsBadge,
  }));
  return page;
}

function rgbChannels(value) {
  const channels = value.match(/[\d.]+/gu).slice(0, 3).map(Number);
  return value.startsWith('color(srgb')
    ? channels.map((channel) => channel * 255)
    : channels;
}

function relativeLuminance(value) {
  const linear = rgbChannels(value).map((channel) => {
    const normalized = channel / 255;
    return normalized <= 0.04045
      ? normalized / 12.92
      : ((normalized + 0.055) / 1.055) ** 2.4;
  });
  return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2];
}

function contrastRatio(foreground, background) {
  const foregroundLuminance = relativeLuminance(foreground);
  const backgroundLuminance = relativeLuminance(background);
  return (Math.max(foregroundLuminance, backgroundLuminance) + 0.05)
    / (Math.min(foregroundLuminance, backgroundLuminance) + 0.05);
}

test('mobile pages stay viewport-bound while code remains readable', { timeout: 120_000 }, async () => {
  const browser = await webkit.launch();
  const publicRoutes = await sitemapRoutes();
  let sawScrollableTerminal = false;
  try {
    for (const theme of ['light', 'dark']) {
      for (const width of mobileWidths) {
        const page = await newPage(browser, { viewport: { width, height: 844 }, colorScheme: theme });
        for (const route of publicRoutes) {
          await openPage(page, `${baseUrl}${route}`);
          await page.evaluate((selectedTheme) => {
            document.documentElement.dataset.theme = selectedTheme;
          }, theme);

          const layout = await page.evaluate(() => {
            const rgb = (value) => {
              const channels = value.match(/[\d.]+/gu).slice(0, 3).map(Number);
              return value.startsWith('color(srgb')
                ? channels.map((channel) => channel * 255)
                : channels;
            };
            const luminance = (color) => {
              const linear = color.map((channel) => {
                const normalized = channel / 255;
                return normalized <= 0.04045
                  ? normalized / 12.92
                  : ((normalized + 0.055) / 1.055) ** 2.4;
              });
              return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2];
            };
            const contrast = (foreground, background) => {
              const lighter = Math.max(luminance(foreground), luminance(background));
              const darker = Math.min(luminance(foreground), luminance(background));
              return (lighter + 0.05) / (darker + 0.05);
            };
            const dimContrasts = [...document.querySelectorAll('.wt-terminal-dim')].map((span) => {
              const style = getComputedStyle(span);
              const foreground = rgb(style.color);
              const background = rgb(getComputedStyle(span.closest('pre')).backgroundColor);
              const opacity = Number(style.opacity);
              const effective = foreground.map((channel, index) => (
                opacity * channel + (1 - opacity) * background[index]
              ));
              return contrast(effective, background);
            });
            const fixedTerminal = [...document.querySelectorAll('.expressive-code .frame')]
              .filter((frame) => frame.querySelector('.wt-output'))
              .map((frame) => frame.querySelector('pre'))
              .find((pre) => pre.scrollWidth > pre.clientWidth + 1);
            if (fixedTerminal) fixedTerminal.scrollLeft = fixedTerminal.scrollWidth;
            return {
              viewportWidth: document.documentElement.clientWidth,
              documentWidth: document.documentElement.scrollWidth,
              dimContrasts,
              fixedTerminalScrollLeft: fixedTerminal?.scrollLeft ?? 0,
              frames: [...document.querySelectorAll('.expressive-code .frame')].map((frame) => {
                const pre = frame.querySelector('pre');
                return {
                  hasOutput: Boolean(frame.querySelector('.wt-output')),
                  frameLeft: frame.getBoundingClientRect().left,
                  frameRight: frame.getBoundingClientRect().right,
                  preClientWidth: pre?.clientWidth ?? 0,
                  preScrollWidth: pre?.scrollWidth ?? 0,
                };
              }),
            };
          });

          assert.equal(
            layout.documentWidth,
            layout.viewportWidth,
            `${theme} ${width}px ${route} widens the document`,
          );
          for (const ratio of layout.dimContrasts) {
            assert.ok(
              ratio >= 4.5,
              `${theme} ${width}px ${route} dim text contrast is ${ratio.toFixed(2)}:1`,
            );
          }
          for (const frame of layout.frames) {
            assert.ok(frame.frameLeft >= -1, `${theme} ${width}px ${route} code starts offscreen`);
            assert.ok(
              frame.frameRight <= layout.viewportWidth + 1,
              `${theme} ${width}px ${route} code ends offscreen`,
            );
            if (!frame.hasOutput) {
              assert.ok(
                frame.preScrollWidth <= frame.preClientWidth + 1,
                `${theme} ${width}px ${route} wrappable code still scrolls horizontally`,
              );
            }
          }

          if (layout.fixedTerminalScrollLeft > 0) sawScrollableTerminal = true;

          await page.evaluate(() => window.scrollTo({ left: 100, top: 0 }));
          assert.equal(await page.evaluate(() => window.scrollX), 0, `${theme} ${width}px ${route} pans sideways`);
        }
        await page.close();
      }
    }
    assert.ok(sawScrollableTerminal, 'expected a fixed terminal table to retain internal scrolling');
  } finally {
    await browser.close();
  }
});

// 1920px leaves the content panel wider than the capped content column, so a
// code frame sized off the panel instead of the column shows up there.
test('desktop code examples fit the content column', { timeout: 60_000 }, async () => {
  const browser = await webkit.launch();
  try {
    for (const width of [1152, 1376, 1401, 1920]) {
      const page = await newPage(browser, { viewport: { width, height: 900 } });
      for (const route of await sitemapRoutes()) {
        await openPage(page, `${baseUrl}${route}`);
        const { column, blocks, terminals } = await page.evaluate(() => {
          const { left, right } = document.querySelector('.sl-markdown-content').getBoundingClientRect();
          return {
            column: { left, right },
            blocks: [...document.querySelectorAll('.sl-markdown-content .expressive-code')].map((block) => {
              const rect = block.getBoundingClientRect();
              return { left: rect.left, right: rect.right, text: block.textContent.trim().slice(0, 60) };
            }),
            terminals: [...document.querySelectorAll('.expressive-code .frame')]
              .filter((frame) => frame.querySelector('.wt-output'))
              .map((frame) => {
                const pre = frame.querySelector('pre');
                return {
                  command: frame.querySelector('.wt-command')?.textContent.trim(),
                  clientWidth: pre.clientWidth,
                  scrollWidth: pre.scrollWidth,
                };
              }),
          };
        });
        for (const block of blocks) {
          assert.ok(
            block.left >= column.left - 1 && block.right <= column.right + 1,
            `${route} "${block.text}" leaves the content column at ${width}px`,
          );
        }
        for (const terminal of terminals) {
          assert.ok(
            terminal.scrollWidth <= terminal.clientWidth + 1,
            `${route} ${terminal.command} scrolls horizontally at ${width}px`,
          );
        }
      }
      await page.close();
    }

    const page = await newPage(browser, { viewport: { width: 1920, height: 900 } });
    await openPage(page, baseUrl + '/');
    const rail = await page.evaluate(() => {
      const frame = [...document.querySelectorAll('.expressive-code .frame')]
        .find((candidate) => candidate.querySelector('.wt-command')?.textContent.trim() === 'wt list');
      const pre = frame.querySelector('pre').getBoundingClientRect();
      const textBounds = [...frame.querySelectorAll('.ec-line')].map((line) => {
        const walker = document.createTreeWalker(line, NodeFilter.SHOW_TEXT);
        let node;
        let first;
        let last;
        while ((node = walker.nextNode())) {
          if (!node.textContent) continue;
          first ??= node;
          last = node;
        }
        if (!first) return null;
        const firstRange = document.createRange();
        const lastRange = document.createRange();
        firstRange.selectNodeContents(first);
        lastRange.selectNodeContents(last);
        return {
          left: firstRange.getBoundingClientRect().left,
          right: lastRange.getBoundingClientRect().right,
          columns: line.textContent.length,
        };
      }).filter(Boolean);
      const widest = textBounds.reduce((current, candidate) => (
        candidate.right - candidate.left > current.right - current.left ? candidate : current
      ));
      const padEnd = parseFloat(
        getComputedStyle(frame.querySelector('.ec-line.wt-output .code')).paddingInlineEnd,
      );
      return {
        spare: pre.right - widest.right - padEnd,
        column: (widest.right - widest.left) / widest.columns,
      };
    });
    assert.ok(
      rail.spare >= 0 && rail.spare < rail.column,
      `99-column terminal leaves ${rail.spare.toFixed(1)}px spare beside ${rail.column.toFixed(1)}px columns`,
    );
    await page.close();
  } finally {
    await browser.close();
  }
});

test('copy buttons sit in view on the line they copy without overlapping', { timeout: 60_000 }, async () => {
  const browser = await webkit.launch();
  try {
    for (const { width, touch } of [{ width: 393, touch: true }, { width: 1376, touch: false }]) {
      const page = await newPage(browser, {
        viewport: { width, height: 900 },
        hasTouch: touch,
        isMobile: touch,
      });
      for (const route of await sitemapRoutes()) {
        await openPage(page, `${baseUrl}${route}`);
        const frames = await page.evaluate(() => {
          for (const details of document.querySelectorAll('.sl-markdown-content details')) details.open = true;
          return [...document.querySelectorAll('.expressive-code .frame')].map((frame) => {
            const code = frame.querySelector('pre').getBoundingClientRect();
            return {
              text: frame.textContent.trim().slice(0, 60),
              codeLeft: code.left,
              codeRight: code.right,
              buttons: [...frame.querySelectorAll('.copy button')].map((button) => {
                // A block's control belongs on its first line.
                const line = (button.closest('.ec-line') ?? frame.querySelector('.ec-line'))
                  .getBoundingClientRect();
                const { top, bottom, left, right } = button.getBoundingClientRect();
                return { top, bottom, left, right, lineTop: line.top, lineBottom: line.bottom };
              }),
            };
          });
        });
        const label = (frame) => `${route} "${frame.text}" at ${width}px`;
        for (const frame of frames) {
          for (const [index, button] of frame.buttons.entries()) {
            const center = (button.top + button.bottom) / 2;
            assert.ok(
              center >= button.lineTop && center <= button.lineBottom,
              `${label(frame)}: copy button is off its line`,
            );
            assert.ok(
              button.left >= frame.codeLeft - 1 && button.right <= frame.codeRight + 1,
              `${label(frame)}: copy button is scrolled out of sight`,
            );
            assert.ok(
              frame.buttons.slice(index + 1)
                .every((other) => other.top >= button.bottom - 0.5 || other.bottom <= button.top + 0.5),
              `${label(frame)}: copy buttons overlap`,
            );
          }
        }
      }
      await page.close();
    }
  } finally {
    await browser.close();
  }
});

test('code artifacts keep their visual hierarchy in both themes', async () => {
  const browser = await webkit.launch();
  try {
    for (const theme of ['light', 'dark']) {
      const page = await newPage(browser, { viewport: { width: 1280, height: 900 }, colorScheme: theme });

      await openPage(page, `${baseUrl}/claude-code/`);
      await page.evaluate((selectedTheme) => {
        document.documentElement.dataset.theme = selectedTheme;
      }, theme);
      const commandStyles = await page.evaluate(() => {
        const frame = [...document.querySelectorAll('.expressive-code .frame')]
          .find((candidate) => candidate.textContent.includes(
            'codex plugin marketplace add max-sixty/worktrunk',
          ));
        return {
          background: getComputedStyle(frame.querySelector('pre')).backgroundColor,
          tokens: [...frame.querySelectorAll('.code span')]
            .filter((span) => span.textContent.trim())
            .map((span) => ({
              text: span.textContent,
              color: getComputedStyle(span).color,
            })),
        };
      });
      assert.notEqual(
        commandStyles.tokens.find(({ text }) => text === 'codex').color,
        commandStyles.tokens.find(({ text }) => text === 'plugin').color,
        `${theme} shell command flattens the executable and arguments to one color`,
      );
      for (const { text, color } of commandStyles.tokens) {
        const ratio = contrastRatio(color, commandStyles.background);
        assert.ok(ratio >= 4.5, `${theme} shell token ${text} contrast is ${ratio.toFixed(2)}:1`);
      }

      await openPage(page, baseUrl + '/');
      await page.evaluate((selectedTheme) => {
        document.documentElement.dataset.theme = selectedTheme;
      }, theme);
      const homepageTerminalStyles = await page.evaluate(() => {
        const frames = [...document.querySelectorAll('.expressive-code .frame')];
        const agentFrame = frames.find((candidate) => candidate.textContent.includes(
          "wt switch -x claude -c feature-a -- 'Add user authentication'",
        ));
        const mergeFrame = frames.find((candidate) => candidate.textContent.includes(
          'Merging 1 commit to main',
        ));
        const token = (text) => [...agentFrame.querySelectorAll('.code span')]
          .find((candidate) => candidate.textContent === text);
        const outputLines = [...mergeFrame.querySelectorAll('.ec-line.wt-output')];
        const gutters = outputLines.map((line, index) => ({
          index,
          gutter: line.querySelector('.wt-terminal-gutter'),
        })).filter(({ gutter }) => gutter);
        const joins = gutters.slice(1).flatMap((current, index) => (
          current.index === gutters[index].index + 1
            ? [current.gutter.getBoundingClientRect().top
              - gutters[index].gutter.getBoundingClientRect().bottom]
            : []
        ));
        const pre = agentFrame.querySelector('pre');
        return {
          argument: getComputedStyle(token('feature-a')).color,
          background: getComputedStyle(pre).backgroundColor,
          gutterIndexes: gutters.map(({ index }) => index),
          joins,
          lineHeights: outputLines.map((line) => line.getBoundingClientRect().height),
          quoted: getComputedStyle(token("'Add user authentication'")).color,
        };
      });
      assert.notEqual(
        homepageTerminalStyles.argument,
        homepageTerminalStyles.quoted,
        `${theme} quoted shell string uses the argument color`,
      );
      assert.ok(
        contrastRatio(homepageTerminalStyles.quoted, homepageTerminalStyles.background) >= 4.5,
        `${theme} quoted shell string falls below 4.5:1 contrast`,
      );
      assert.deepEqual(
        homepageTerminalStyles.gutterIndexes,
        [1, 4, 5, 6, 7],
        `${theme} merge gutter rows moved — regenerate from quickstart_merge.snap`,
      );
      assert.equal(
        homepageTerminalStyles.joins.length,
        3,
        `${theme} merge gutter run is no longer three adjacent joins`,
      );
      assert.ok(
        homepageTerminalStyles.joins.every((gap) => Math.abs(gap) < 0.5),
        `${theme} merge gutter does not sit flush between rows`,
      );
      assert.equal(
        new Set(homepageTerminalStyles.lineHeights).size,
        1,
        `${theme} gutter padding changes terminal line height`,
      );
      const comparisonStyles = await page.evaluate(() => {
        const table = document.querySelector('.cmd-compare');
        return {
          text: table.textContent,
          tokens: [...table.querySelectorAll('[class^="wt-shell-"]')].map((span) => {
            const cell = span.closest('td');
            return {
              role: [...span.classList].find((name) => name.startsWith('wt-shell-'))
                .replace('wt-shell-', ''),
              color: getComputedStyle(span).color,
              background: getComputedStyle(cell).backgroundColor,
            };
          }),
        };
      });
      assert.match(comparisonStyles.text, /wt switch -c -x claude feat/);
      assert.match(comparisonStyles.text, /git worktree add -b feat \.\.\/repo\.feat/);
      const roleColors = new Map(comparisonStyles.tokens.map(({ role, color }) => [role, color]));
      assert.equal(roleColors.size, 3, `${theme} comparison is missing a syntax role`);
      assert.equal(
        new Set(roleColors.values()).size,
        roleColors.size,
        theme + ' comparison syntax roles collapse to the same color',
      );
      for (const { role, color, background } of comparisonStyles.tokens) {
        const ratio = contrastRatio(color, background);
        assert.ok(
          ratio >= 4.5,
          theme + ' comparison ' + role + ' contrast is ' + ratio.toFixed(2) + ':1',
        );
      }

      await openPage(page, `${baseUrl}/list/`);
      await page.evaluate((selectedTheme) => {
        document.documentElement.dataset.theme = selectedTheme;
      }, theme);
      const listStyles = await page.evaluate(() => {
        const frame = [...document.querySelectorAll('.expressive-code .frame')]
          .find((candidate) => candidate.textContent.includes('feature-api'));
        const normal = frame.querySelector('.wt-output .code');
        const dim = frame.querySelector('.wt-terminal-dim:not(.wt-terminal-red)');
        return {
          normal: getComputedStyle(normal).color,
          dim: getComputedStyle(dim).color,
          dimOpacity: getComputedStyle(dim).opacity,
          commandColors: new Set(
            [...frame.querySelectorAll('.wt-command .code span')]
              .filter((span) => span.textContent.trim())
              .map((span) => getComputedStyle(span).color),
          ).size,
        };
      });
      assert.notEqual(listStyles.normal, listStyles.dim, `${theme} wt list dim text is not distinct`);
      assert.equal(listStyles.dimOpacity, '1', `${theme} wt list dim text relies on opacity`);
      assert.ok(listStyles.commandColors >= 2, `${theme} console command loses Bash syntax colors`);

      const referenceStyles = await page.evaluate(() => {
        const frame = document.querySelector('.frame.wt-command-reference');
        const roles = ['heading', 'command', 'option', 'value', 'meta'];
        return {
          present: Boolean(frame),
          background: getComputedStyle(frame.querySelector('pre')).backgroundColor,
          colors: roles.map((role) => getComputedStyle(
            frame.querySelector(`.wt-help-${role}`),
          ).color),
        };
      });
      assert.equal(referenceStyles.present, true, `${theme} command reference is not classified`);
      assert.equal(
        new Set(referenceStyles.colors).size,
        referenceStyles.colors.length,
        `${theme} command reference syntax roles collapse to the same color`,
      );
      for (const color of referenceStyles.colors) {
        const ratio = contrastRatio(color, referenceStyles.background);
        assert.ok(ratio >= 4.5, `${theme} help-role contrast is ${ratio.toFixed(2)}:1`);
      }

      await openPage(page, `${baseUrl}/config/`);
      await page.evaluate((selectedTheme) => {
        document.documentElement.dataset.theme = selectedTheme;
      }, theme);
      const fileFrame = await page.evaluate(() => {
        const frame = [...document.querySelectorAll('.frame.has-title')]
          .find((candidate) => candidate.textContent.includes('~/.config/worktrunk/config.toml'));
        const title = frame.querySelector('.title');
        const pre = frame.querySelector('pre');
        return {
          title: title.textContent,
          titleBottom: title.getBoundingClientRect().bottom,
          codeTop: pre.getBoundingClientRect().top,
          titleLeft: title.getBoundingClientRect().left,
          codeLeft: pre.getBoundingClientRect().left,
          titleFont: getComputedStyle(title).fontFamily,
          titleColor: getComputedStyle(title).color,
          titleBackground: getComputedStyle(title).backgroundColor,
          codeBackground: getComputedStyle(pre).backgroundColor,
          accentWidth: getComputedStyle(pre).borderInlineStartWidth,
          stringColor: getComputedStyle([...frame.querySelectorAll('.code span')]
            .find((span) => span.textContent === '".worktrees/{{ branch | sanitize }}"')).color,
        };
      });
      assert.equal(fileFrame.title, '~/.config/worktrunk/config.toml');
      assert.ok(fileFrame.titleFont.includes('JetBrains Mono'), `${theme} file label is not monospaced`);
      assert.ok(
        Math.abs(fileFrame.titleBottom - fileFrame.codeTop) < 1,
        `${theme} file label is detached from its code`,
      );
      assert.ok(
        Math.abs(fileFrame.titleLeft - fileFrame.codeLeft) < 1,
        `${theme} file label is inset from its code`,
      );
      assert.notEqual(
        fileFrame.titleBackground,
        fileFrame.codeBackground,
        `${theme} file label does not read separately from its code`,
      );
      const titleContrast = contrastRatio(fileFrame.titleColor, fileFrame.titleBackground);
      assert.ok(titleContrast >= 4.5, `${theme} file-label contrast is ${titleContrast.toFixed(2)}:1`);
      assert.notEqual(
        fileFrame.stringColor,
        homepageTerminalStyles.quoted,
        `${theme} shell quote color leaks into TOML strings`,
      );
      assert.equal(fileFrame.accentWidth, '3px');
      await page.close();
    }
  } finally {
    await browser.close();
  }
});