Skip to content

Turn any idea, plan, or codebase into a beautiful interactive diagram. An agent skill for Claude Code, Codex, and more.

24.4 KB
Raw Blame
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const skillRoot = path.resolve(__dirname, '..', 'archify');

function render(mode, doc) {
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-port-spread-'));
  const input = path.join(tmp, 'input.json');
  const output = path.join(tmp, 'output.html');
  const renderDoc = structuredClone(doc);
  renderDoc.meta = { ...renderDoc.meta, output: `${mode}-automatic-port-spread.html` };
  fs.writeFileSync(input, JSON.stringify(renderDoc));
  try {
    execFileSync('node', [
      path.join(skillRoot, `renderers/${mode}/render-${mode}.mjs`),
      input,
      output,
    ], { stdio: ['ignore', 'ignore', 'pipe'] });
    return fs.readFileSync(output, 'utf8');
  } finally {
    fs.rmSync(tmp, { recursive: true, force: true });
  }
}

function connectionPoints(html, id) {
  const pattern = new RegExp(`data-edge-id="${id}"[^>]+data-composition-points="([^"]+)"`);
  const match = html.match(pattern);
  assert.ok(match, `missing rendered connection ${id}`);
  return match[1].split(';').map((point) => point.split(',').map(Number));
}

function connectionLabelPoint(html, id) {
  const match = html.match(new RegExp(`data-detail="context"[^>]+data-edge-id="${id}"[^>]*>\\s*<rect[^>]*>\\s*<text x="([^"]+)" y="([^"]+)"`));
  assert.ok(match, `missing rendered connection label ${id}`);
  return [Number(match[1]), Number(match[2])];
}

function fanOutArchitecture(connections) {
  return {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Automatic port spread' },
    components: [
      { id: 'hub', type: 'backend', label: 'Hub', pos: [100, 280], size: [120, 60] },
      { id: 'upper', type: 'external', label: 'Upper', pos: [500, 100], size: [120, 60] },
      { id: 'middle', type: 'database', label: 'Middle', pos: [500, 280], size: [120, 60] },
      { id: 'lower', type: 'cloud', label: 'Lower', pos: [500, 460], size: [120, 60] },
    ],
    connections,
  };
}

function reciprocalArchitecture(connections, transpose = false) {
  const position = ([x, y]) => transpose ? [y, x] : [x, y];
  const size = ([width, height]) => transpose ? [height, width] : [width, height];
  return {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Reciprocal automatic channels' },
    components: [
      { id: 'sender', type: 'backend', label: 'Sender', pos: position([125, 250]), size: size([192, 76]) },
      { id: 'receiver', type: 'backend', label: 'Receiver', pos: position([445, 250]), size: size([182, 76]) },
      { id: 'store', type: 'database', label: 'Store', pos: position([445, 435]), size: size([182, 76]) },
    ],
    connections,
  };
}

test('architecture: reciprocal automatic relationships with a third inferred port use separate straight channels', () => {
  for (const transpose of [false, true]) {
    const connections = [
      { id: 'send', from: 'sender', to: 'receiver', ...(!transpose ? { label: 'request' } : {}) },
      { id: 'reply', from: 'receiver', to: 'sender', ...(!transpose ? { label: 'response' } : {}) },
      { id: 'persist', from: 'sender', to: 'store', ...(!transpose ? { label: 'persist' } : {}) },
    ];
    for (const ordered of [connections, [...connections].reverse()]) {
      const html = render('architecture', reciprocalArchitecture(ordered, transpose));
      const send = connectionPoints(html, 'send');
      const reply = connectionPoints(html, 'reply');
      const persist = connectionPoints(html, 'persist');
      assert.equal(send.length, 2, JSON.stringify({ transpose, send, reply }));
      assert.equal(reply.length, 2, JSON.stringify({ transpose, send, reply }));
      const axis = transpose ? 0 : 1;
      assert.equal(send[0][axis], send[1][axis]);
      assert.equal(reply[0][axis], reply[1][axis]);
      assert.notEqual(send[0][axis], reply[0][axis]);
      assert.notDeepEqual(send[0], reply[1]);
      assert.notDeepEqual(send[1], reply[0]);
      const travel = transpose ? 1 : 0;
      assert.ok(send[0][travel] < send[1][travel], 'forward arrow still points to receiver');
      assert.ok(reply[0][travel] > reply[1][travel], 'reverse arrow still points to sender');
      assert.notDeepEqual(persist[0], send[0]);
      assert.notDeepEqual(persist[0], reply.at(-1));
      if (persist[0][travel] === send[0][travel]) {
        assert.ok(Math.abs(persist[0][axis] - send[0][axis]) >= 14);
        assert.ok(Math.abs(persist[0][axis] - reply.at(-1)[axis]) >= 14);
      }
    }
  }
});

test('architecture: reciprocal repair preserves an authored side and via geometry', () => {
  const connections = [
    { id: 'send', from: 'sender', to: 'receiver', fromSide: 'right', toSide: 'left' },
    { id: 'reply', from: 'receiver', to: 'sender', via: [[400, 230], [355, 230]] },
    { id: 'persist', from: 'sender', to: 'store' },
  ];
  const html = render('architecture', reciprocalArchitecture(connections));
  const send = connectionPoints(html, 'send');
  const reply = connectionPoints(html, 'reply');
  assert.deepEqual(send[0][0], 317);
  assert.deepEqual(send.at(-1)[0], 445);
  assert.deepEqual(reply.slice(1, -1), [[400, 230], [355, 230]]);

  const preset = render('architecture', reciprocalArchitecture([
    { id: 'send', from: 'sender', to: 'receiver' },
    { id: 'reply', from: 'receiver', to: 'sender', route: 'orthogonal-h' },
    { id: 'persist', from: 'sender', to: 'store' },
  ]));
  const presetReply = connectionPoints(preset, 'reply');
  assert.ok(presetReply.length > 2, 'authored route preset keeps its bend');
  assert.deepEqual(presetReply[1], [381, 288]);
});

test('architecture: reciprocal repair preserves explicit relationship label placement controls', () => {
  for (const placement of [
    { labelSegment: 1, labelDy: -30 },
    { labelDx: 0 },
    { labelDy: 0 },
  ]) {
    const connections = [
      { id: 'send', from: 'sender', to: 'receiver', label: 'request', ...placement },
      { id: 'reply', from: 'receiver', to: 'sender', label: 'response' },
      { id: 'persist', from: 'sender', to: 'store', label: 'persist' },
    ];
    const html = render('architecture', reciprocalArchitecture(connections));
    assert.ok(connectionPoints(html, 'send').length > 2,
      `explicit ${JSON.stringify(placement)} keeps its authored label segment meaningful`);
    if (placement.labelSegment !== undefined) {
      assert.deepEqual(connectionLabelPoint(html, 'send'), [341, 259.5],
        'labelSegment: 1 remains on the second segment with the authored vertical offset');
    }
  }
});

test('architecture: automatic fan-out uses distinct ports with corner clearance and outward normals', () => {
  const html = render('architecture', fanOutArchitecture([
    { id: 'to-upper', from: 'hub', to: 'upper' },
    { id: 'to-middle', from: 'hub', to: 'middle' },
    { id: 'to-lower', from: 'hub', to: 'lower' },
  ]));

  const routes = ['to-upper', 'to-middle', 'to-lower'].map(id => connectionPoints(html, id));
  assert.equal(new Set(routes.map(points => JSON.stringify(points[0]))).size, 3);
  for (const [[x, y], [nx, ny]] of routes) {
    assert.ok(
      (x === 220 && y >= 294 && y <= 326 && nx > x && ny === y)
      || (x === 100 && y >= 294 && y <= 326 && nx < x && ny === y)
      || (y === 280 && x >= 114 && x <= 206 && ny < y && nx === x)
      || (y === 340 && x >= 114 && x <= 206 && ny > y && nx === x),
      `port ${x},${y} must leave the hub normally with at least 14px corner clearance`,
    );
  }
});

test('architecture: automatic port assignment is stable when relationship input order changes', () => {
  const connections = [
    { id: 'to-upper', from: 'hub', to: 'upper' },
    { id: 'to-middle', from: 'hub', to: 'middle' },
    { id: 'to-lower', from: 'hub', to: 'lower' },
  ];
  const forward = render('architecture', fanOutArchitecture(connections));
  const reversed = render('architecture', fanOutArchitecture([...connections].reverse()));

  for (const connection of connections) {
    assert.deepEqual(
      connectionPoints(forward, connection.id),
      connectionPoints(reversed, connection.id),
      `${connection.id} moved after input reordering`,
    );
  }
});

test('architecture: a singly spread near-aligned vertical relationship keeps one direct axis', () => {
  const html = render('architecture', {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Near-aligned fan-out' },
    components: [
      { id: 'api', type: 'backend', label: 'API', pos: [675, 300], size: [120, 60] },
      { id: 'auth', type: 'security', label: 'Auth', pos: [570, 120], size: [100, 60] },
      { id: 'cache', type: 'database', label: 'Cache', pos: [685, 120], size: [100, 60] },
    ],
    connections: [
      { id: 'verify', from: 'api', to: 'auth', fromSide: 'top', toSide: 'bottom' },
      { id: 'read', from: 'api', to: 'cache', fromSide: 'top', toSide: 'bottom' },
    ],
  });

  assert.deepEqual(connectionPoints(html, 'read'), [[742, 300], [742, 180]]);
  assert.notDeepEqual(connectionPoints(html, 'verify')[0], connectionPoints(html, 'read')[0]);
});

test('architecture: a singly spread near-aligned horizontal relationship keeps one direct axis', () => {
  const html = render('architecture', {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Near-aligned horizontal fan-out' },
    components: [
      { id: 'hub', type: 'backend', label: 'Hub', pos: [100, 100], size: [120, 60] },
      { id: 'direct', type: 'database', label: 'Direct', pos: [500, 107], size: [120, 60] },
      { id: 'branch', type: 'cloud', label: 'Branch', pos: [500, 300], size: [120, 60] },
    ],
    connections: [
      { id: 'hub-direct', from: 'hub', to: 'direct', fromSide: 'right', toSide: 'left' },
      { id: 'hub-branch', from: 'hub', to: 'branch', fromSide: 'right', toSide: 'left' },
    ],
  });

  assert.deepEqual(connectionPoints(html, 'hub-direct'), [[220, 123], [500, 123]]);
  assert.notDeepEqual(connectionPoints(html, 'hub-branch')[0], connectionPoints(html, 'hub-direct')[0]);
});

test('architecture: a shared bottom port keeps its aligned child relationship straight', () => {
  const doc = {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Vertical child relationship' },
    components: [
      { id: 'parent', type: 'backend', label: 'Parent Session', pos: [300, 100], size: [200, 60] },
      { id: 'terminal', type: 'backend', label: 'Background terminal', pos: [300, 300], size: [200, 60] },
      { id: 'workflow', type: 'backend', label: 'Workflow', pos: [560, 300], size: [180, 60] },
    ],
    connections: [
      { id: 'parent-terminal', from: 'parent', to: 'terminal', fromSide: 'bottom', toSide: 'top' },
      { id: 'parent-workflow', from: 'parent', to: 'workflow', fromSide: 'bottom', toSide: 'top' },
    ],
  };
  const forward = render('architecture', doc);
  const reversed = render('architecture', {
    ...doc,
    connections: [...doc.connections].reverse(),
  });

  assert.deepEqual(connectionPoints(forward, 'parent-terminal'), [[393, 160], [393, 300]]);
  assert.notDeepEqual(
    connectionPoints(forward, 'parent-workflow')[0],
    connectionPoints(forward, 'parent-terminal')[0],
  );
  for (const connection of doc.connections) {
    assert.deepEqual(
      connectionPoints(forward, connection.id),
      connectionPoints(reversed, connection.id),
      `${connection.id} moved after input reordering`,
    );
  }
});

test('architecture: incoming and outgoing relationships keep distinct bottom ports while the direct child stays straight', () => {
  const html = render('architecture', {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Shared incoming and outgoing side' },
    components: [
      { id: 'workflow', type: 'backend', label: 'Workflow', pos: [80, 320], size: [180, 60] },
      { id: 'child', type: 'security', label: 'Child boundary', pos: [300, 100], size: [200, 60] },
      { id: 'footer', type: 'frontend', label: 'Footer', pos: [300, 320], size: [200, 60] },
    ],
    connections: [
      { id: 'workflow-child', from: 'workflow', to: 'child', fromSide: 'right', toSide: 'bottom' },
      { id: 'child-footer', from: 'child', to: 'footer', fromSide: 'bottom', toSide: 'top' },
    ],
  });

  assert.deepEqual(connectionPoints(html, 'child-footer'), [[407, 160], [407, 320]]);
  assert.notDeepEqual(
    connectionPoints(html, 'workflow-child').at(-1),
    connectionPoints(html, 'child-footer')[0],
  );
});

test('architecture: a near-aligned relationship keeps the outside bridge when both endpoints are spread', () => {
  const html = render('architecture', {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Two-sided port competition' },
    components: [
      { id: 'source', type: 'backend', label: 'Source', pos: [300, 320], size: [160, 60] },
      { id: 'source-peer', type: 'backend', label: 'Source peer', pos: [80, 320], size: [160, 60] },
      { id: 'target', type: 'database', label: 'Target', pos: [300, 100], size: [160, 60] },
      { id: 'target-peer', type: 'database', label: 'Target peer', pos: [560, 100], size: [160, 60] },
    ],
    connections: [
      { id: 'source-target', from: 'source', to: 'target', fromSide: 'top', toSide: 'bottom' },
      { id: 'source-peer-target', from: 'source-peer', to: 'target', fromSide: 'top', toSide: 'bottom' },
      { id: 'source-target-peer', from: 'source', to: 'target-peer', fromSide: 'top', toSide: 'bottom' },
    ],
  });

  const points = connectionPoints(html, 'source-target');
  assert.ok(points.length > 2);
  assert.notEqual(points[0][0], points.at(-1)[0]);
});

test('architecture: a singly spread near-aligned relationship keeps the bridge when its direct axis is blocked', () => {
  const html = render('architecture', {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Blocked vertical axis' },
    components: [
      { id: 'parent', type: 'backend', label: 'Parent', pos: [300, 100], size: [200, 60] },
      { id: 'terminal', type: 'backend', label: 'Terminal', pos: [300, 400], size: [200, 60] },
      { id: 'workflow', type: 'backend', label: 'Workflow', pos: [560, 400], size: [180, 60] },
      { id: 'obstacle', type: 'external', label: 'X', pos: [382, 245], size: [26, 60] },
    ],
    connections: [
      { id: 'parent-terminal', from: 'parent', to: 'terminal', fromSide: 'bottom', toSide: 'top' },
      { id: 'parent-workflow', from: 'parent', to: 'workflow', fromSide: 'bottom', toSide: 'top' },
    ],
  });

  const points = connectionPoints(html, 'parent-terminal');
  assert.ok(points.length > 2);
  assert.notEqual(points[0][0], points.at(-1)[0]);
});

test('architecture: single and explicitly positioned relationships keep legacy anchors', () => {
  const doc = fanOutArchitecture([
    { id: 'single', from: 'hub', to: 'middle' },
    { id: 'via', from: 'hub', to: 'upper', via: [[300, 310], [300, 130]] },
    { id: 'fixed-route', from: 'hub', to: 'lower', route: 'orthogonal-h' },
    { id: 'fixed-label', from: 'hub', to: 'upper', label: 'contract', labelAt: [360, 200] },
  ]);
  const html = render('architecture', doc);

  assert.deepEqual(connectionPoints(html, 'single'), [[220, 310], [500, 310]]);
  assert.deepEqual(connectionPoints(html, 'via'), [[220, 310], [300, 310], [300, 130], [500, 130]]);
  assert.deepEqual(connectionPoints(html, 'fixed-route'), [[220, 310], [360, 310], [360, 490], [500, 490]]);
  assert.deepEqual(connectionPoints(html, 'fixed-label'), [[220, 310], [360, 310], [360, 130], [500, 130]]);
});

test('architecture: an unspread near-aligned connection shares one horizontal axis', () => {
  const html = render('architecture', {
    schema_version: 1,
    diagram_type: 'architecture',
    meta: { title: 'Near-aligned single connection' },
    components: [
      { id: 'console', type: 'frontend', label: 'Console', pos: [260, 300], size: [170, 64] },
      { id: 'controlplane', type: 'backend', label: 'Control plane', pos: [500, 300], size: [190, 72] },
    ],
    connections: [
      { id: 'console-controlplane', from: 'console', to: 'controlplane', label: 'REST /api', variant: 'emphasis', labelDy: -36 },
    ],
  });

  assert.deepEqual(connectionPoints(html, 'console-controlplane'), [[430, 332], [500, 332]]);
});

test('workflow: automatic cross-lane fan-out selects distinct perpendicular source sides', () => {
  const html = render('workflow', {
    schema_version: 1,
    diagram_type: 'workflow',
    meta: { title: 'Workflow port spread' },
    lanes: [
      { id: 'upper-lane', label: 'Upper' },
      { id: 'hub-lane', label: 'Hub' },
      { id: 'lower-lane', label: 'Lower' },
    ],
    nodes: [
      { id: 'hub', lane: 'hub-lane', col: 0, type: 'backend', label: 'Hub' },
      { id: 'upper', lane: 'upper-lane', col: 3, type: 'external', label: 'Upper' },
      { id: 'middle', lane: 'hub-lane', col: 3, type: 'database', label: 'Middle' },
      { id: 'lower', lane: 'lower-lane', col: 3, type: 'cloud', label: 'Lower' },
    ],
    edges: [
      { id: 'to-upper', from: 'hub', to: 'upper' },
      { id: 'to-middle', from: 'hub', to: 'middle' },
      { id: 'to-lower', from: 'hub', to: 'lower' },
    ],
  });

  assert.deepEqual(connectionPoints(html, 'to-upper')[0], [88, 217]);
  assert.deepEqual(connectionPoints(html, 'to-middle')[0], [134, 243]);
  assert.deepEqual(connectionPoints(html, 'to-lower')[0], [88, 269]);
});

test('dataflow: automatic fan-out spreads flows without changing their authored topology', () => {
  const html = render('dataflow', {
    schema_version: 1,
    diagram_type: 'dataflow',
    meta: { title: 'Data-flow port spread' },
    stages: [{ label: 'Source' }, { label: 'Transform' }, { label: 'Sinks' }],
    nodes: [
      { id: 'hub', type: 'backend', label: 'Hub', stage: 0, row: 2 },
      { id: 'upper', type: 'external', label: 'Upper', stage: 2, row: 0 },
      { id: 'middle', type: 'database', label: 'Middle', stage: 2, row: 2 },
      { id: 'lower', type: 'cloud', label: 'Lower', stage: 2, row: 4 },
    ],
    flows: [
      { id: 'to-upper', from: 'hub', to: 'upper', label: 'upper feed' },
      { id: 'to-middle', from: 'hub', to: 'middle', label: 'middle feed' },
      { id: 'to-lower', from: 'hub', to: 'lower', label: 'lower feed' },
    ],
  });

  assert.deepEqual(connectionPoints(html, 'to-upper')[0], [156, 372]);
  assert.deepEqual(connectionPoints(html, 'to-middle')[0], [156, 385]);
  assert.deepEqual(connectionPoints(html, 'to-lower')[0], [156, 398]);
});

test('dataflow: aligned automatic branches stay straight without collapsing their shared ports', () => {
  const diagram = {
    schema_version: 1, diagram_type: 'dataflow',
    meta: { title: 'Aligned branch', quality_profile: 'showcase' },
    stages: [{ label: 'Input' }, { label: 'Output' }],
    nodes: [
      { id: 'hub', type: 'backend', label: 'Hub', stage: 0, row: 0 },
      { id: 'peer', type: 'backend', label: 'Peer', stage: 1, row: 0 },
      { id: 'lower', type: 'database', label: 'Archive', stage: 1, row: 2 },
    ],
    flows: [
      { id: 'direct', from: 'hub', to: 'peer', label: 'feed' },
      { id: 'branch', from: 'hub', to: 'lower', label: 'archive' },
    ],
  };
  for (const reverse of [false, true]) {
    const input = structuredClone(diagram);
    if (reverse) for (const flow of input.flows) [flow.from, flow.to] = [flow.to, flow.from];
    const html = render('dataflow', input);
    const direct = connectionPoints(html, 'direct');
    const branch = connectionPoints(html, 'branch');
    assert.equal(direct.length, 2, 'a free facing endpoint should align instead of adding four turns');
    assert.equal(direct[0][1], direct[1][1], 'the aligned route must remain orthogonal');
    const index = reverse ? -1 : 0;
    assert.ok(Math.abs(direct.at(index)[1] - branch.at(index)[1]) >= 14,
      'the branch still needs a distinct port');
  }
});

test('authoring defaults point to the bounded automatic port rules and READMEs describe the default', () => {
  const defaults = fs.readFileSync(path.join(skillRoot, 'references/authoring-defaults.md'), 'utf8');
  assert.match(defaults, /Start with automatic routes and endpoint sides/);
  assert.match(defaults, /Geometry reference.*measured spacing, port, canvas, and route rules/);
  const authoringContract = fs.readFileSync(path.join(skillRoot, 'references/authoring-contract.md'), 'utf8');
  assert.match(authoringContract, /Automatic Port Spread is a default renderer behavior/);
  assert.match(authoringContract, /single relationships/);
  assert.match(authoringContract, /explicit `via`, `channelX`, `channelY`, `labelAt`/);
  assert.match(authoringContract, /unobstructed facing ports.*may share one horizontal or vertical axis/);

  const repoRoot = path.resolve(skillRoot, '..');
  for (const file of ['README.md', 'README_EN.md']) {
    assert.match(fs.readFileSync(path.join(repoRoot, file), 'utf8'), /shared automatic endpoints spread deterministically/);
  }
  assert.match(fs.readFileSync(path.join(repoRoot, 'README_ZH.md'), 'utf8'), /共享的自动端点会确定性展开/);
  assert.match(fs.readFileSync(path.join(repoRoot, 'README_JA.md'), 'utf8'), /共有される自動接続点は決定論的に分散/);
});

function settledDetourDataflow() {
  // Anonymous reduction of a settled outer detour sharing three source slots.
  return {
    schema_version: 1, diagram_type: 'dataflow',
    meta: { title: 'Shared ports around an outer detour', quality_profile: 'showcase' },
    stages: [{ label: '文文文文文文文'}, { label: '文文文文文文文'}, { label: '文文文文'}, { label: '文文文文文文'}, { label: '文文文文文文文'}],
    nodes: [
      {id: 'input', type: 'frontend', label: '文文/文文文文', sublabel: 'xxxx · xxxx', stage: 0, row: 0},
      {id: 'options', type: 'frontend', label: '文文文文文文', sublabel: '文文、文文、文文文文', stage: 0, row: 3},
      {id: 'template', type: 'database', label: 'xxxx 文文', sublabel: 'xxxxxx_ / xxxxx_ / xxxxx_', stage: 0, row: 2},
      {id: 'script', type: 'backend', label: '文文文文', sublabel: '文文文 xxx;文文文文文文', stage: 1, row: 0},
      {id: 'title', type: 'backend', label: '文文文', sublabel: '文文文文文;文文文文文', stage: 1, row: 1},
      {id: 'story', type: 'backend', label: '文文文文文文文', sublabel: '文文:文文、文文、文文文', stage: 1, row: 3},
      {id: 'render', type: 'backend', label: '文文文文文文', sublabel: '文文+文文+文文+文文文文', stage: 2, row: 2},
      {id: 'segment', type: 'backend', label: '文文文文文文', sublabel: '文文/文文;文文文文文', stage: 2, row: 3},
      {id: 'audio', type: 'database', label: '文文文文文文', sublabel: 'xxxxxx/xx_xxxxx.xx1', stage: 3, row: 0},
      {id: 'result', type: 'backend', label: '文文文文文文文文文', sublabel: '文文文文文文;xxxx 文文文文', stage: 4, row: 2},
    ],
    flows: [
      {id: 'e1', to: 'script', label: '文文文文文', from: 'input'},
      {id: 'e2', to: 'title', label: '文文文文文', from: 'input'},
      {id: 'e3', to: 'title', label: '文文文文', from: 'options'},
      {id: 'e8', to: 'story', label: '文文', from: 'title'},
      {id: 'e18', to: 'render', label: '文文文文', from: 'template'},
      {id: 'e23', to: 'segment', label: '文文文文', from: 'audio'},
      {id: 'e32', to: 'result', label: '文文文文', from: 'input'},
    ],
  };
}

test('dataflow: settled detours reorder shared slots so the aligned branch is straight', () => {
  const doc = settledDetourDataflow();
  const html = render('dataflow', doc);
  const direct = connectionPoints(html, 'e1');
  assert.equal(direct.length, 2, 'same-row flow needs no bridge after assigning the outward return its top slot');
  assert.equal(direct[0][1], direct[1][1]);
  assert.ok(direct[0][0] < direct[1][0], 'the arrow still points at its target');
  const slots = ['e1', 'e2', 'e32'].map(id => connectionPoints(html, id)[0][1]).sort((a, b) => a - b);
  assert.ok(slots[1] - slots[0] >= 12 && slots[2] - slots[1] >= 12, 'all three branches keep separate ports');
  for (const flow of doc.flows) {
    assert.ok(connectionPoints(html, flow.id).length >= 2, `preserve ${flow.id}`);
  }
});

test('dataflow: invalid placement retains a useful diagnostic during shared port ordering', () => {
  const doc = settledDetourDataflow();
  doc.nodes.find(node => node.id === 'result').row = 6;
  assert.throws(() => render('dataflow', doc), error => {
    assert.match(error.stderr.toString(), /Node "result" uses invalid row 6/);
    assert.doesNotMatch(error.stderr.toString(), /TypeError|Cannot read properties/);
    return true;
  });
});