Skip to content

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

Merge latest dev and preserve wrapped Sequence note contracts

tt-a1i1287d1d940e3
diff --cc archify.zip
index acf9599d,0664adc6..5a3b9f76
Binary files differ
diff --cc archify/renderers/sequence/render-sequence.mjs
index cfb52e8b,6020ff8e..72f9d864
--- a/archify/renderers/sequence/render-sequence.mjs
+++ b/archify/renderers/sequence/render-sequence.mjs
@@@ -64,14 -110,23 +99,13 @@@ function automaticCanvasWidth()
textUnits(participant.label) * 6.8 - 6,
participant.sublabel ? minimumNodeTextWidth(participant.sublabel, participantTextFit.sublabelPreferred) + 86 - availableNodeTextWidth(86) : 0,
)));
- const count = Math.max(1, asArray(sequence.participants).length);
return Math.min(readableCanvasWidth, Math.max(920, Math.ceil((Math.min(190, needed) + 25) * count + 124)));
}
-// A renderer-sized canvas grows to keep the legend clear of late messages and
-// shrinks when the timeline is short: the old 760px floor left ~600px of empty
-// lifeline under typical 4–8 message drafts. Keep a readable minimum band
-// (lifelineTop 142 + 120px timeline + 65px footer = 327) so short diagrams stay
-// usable; an authored viewBox is honored and validated below.
-const SEQUENCE_MIN_AUTO_HEIGHT = 327;
const automaticWidth = sequence.meta?.viewBox ? null : automaticCanvasWidth();
-// Timeline clearance is independent of legend visibility. Messages need 18px
-// before the lifeline bottom; notes, activations and frames need their footer.
-const timelineRequiredHeight = Math.max(contentBottom + 65,
- ...asArray(sequence.messages).map((message) => message.y + 18 + 65));
-const automaticHeight = Math.max(SEQUENCE_MIN_AUTO_HEIGHT, timelineRequiredHeight, legendRequiredHeight(automaticWidth));
-const viewBox = sequence.meta?.viewBox || [automaticWidth, automaticHeight];
-// The timeline scales with viewBox height: a taller viewBox gains message room,
-// a shorter one shrinks the readable band (validated below) instead of clipping.
+
+// Column geometry depends only on the canvas width, which is known before the
+// automatic height is: notes wrap inside lane gaps, and their wrapped height
+// feeds that automatic height.
// `column_fit: "spread"` widens the lanes with the viewBox instead of keeping
// the fixed 108px gap, so a wide canvas gains column distance and label room
// rather than dead space on the right. Spread is the default on both automatic
@@@ -80,150 -134,18 +114,158 @@@ const canvasWidth = sequence.meta?.view
const columnFit = sequence.meta?.column_fit || 'spread';
const participantCount = Math.max(1, asArray(sequence.participants).length);
const preferredSideMargin = 62;
- const participantW = columnFit === 'spread' ? spreadParticipantWidth(canvasWidth) : 86;
-const spreadGeometry = spreadColumnGeometry(viewBox[0]);
++const spreadGeometry = spreadColumnGeometry(canvasWidth);
+ const participantW = columnFit === 'spread' ? spreadGeometry.width : 86;
// Narrow feasible frames can reduce the left margin, while ordinary frames
// keep 62px. Compute card width first so this does not change its sizing rule.
- const minimumParticipantSpan = participantCount * participantW + (participantCount - 1) * 16;
const sideMargin = columnFit === 'spread'
- ? Math.max(40, Math.min(preferredSideMargin, canvasWidth - 40 - minimumParticipantSpan))
+ ? spreadGeometry.margin
: preferredSideMargin;
// Fit the authored width when feasible, preserving a real 16px card gutter.
// Infeasible frames retain that minimum and fail the capacity check below.
const colGap = columnFit === 'spread' && participantCount > 1
- ? Math.max(participantW + 16, (canvasWidth - 40 - sideMargin - participantW) / (participantCount - 1))
+ ? spreadGeometry.gap
: 108;
+const leftX = columnFit === 'spread' ? sideMargin + participantW / 2 : sideMargin;
+const participantIndexById = new Map(asArray(sequence.participants).map((participant, index) => [participant.id, index]));
+
+function participantX(index) {
+ return leftX + index * colGap;
+}
+
+// A note wraps inside one gap between neighbouring lifelines, so it never
+// crosses an unrelated lifeline or activation bar (#676). Every character
+// stays visible, including in image exports: long unbroken text (a URL or
+// path) breaks after its punctuation, otherwise at any character.
+const NOTE_FONT_SIZE = 7;
+const NOTE_LINE_HEIGHT = NOTE_FONT_SIZE + 4;
+// The first line keeps its original position: 12px past the arrow start,
+// which sits 7px from the lifeline.
+const NOTE_ARROW_INSET = 7;
+const NOTE_TEXT_INSET = 12;
+// Activation bars reach 5px past a lifeline; keep 6px of air beyond them.
+const NOTE_LIFELINE_CLEARANCE = 11;
+// Spread columns share one computed gap, but subtracting floating-point column
+// centres can differ in the last digits; such gaps still count as equal.
+const NOTE_GAP_TOLERANCE = 0.5;
+const NOTE_BREAK_AFTER = new Set(['/', '.', '-', '?', '&', '=', '#', '_']);
+const noteSegmenter = new Intl.Segmenter(undefined, { granularity: 'grapheme' });
+const noteLayouts = new Map();
+
+function noteTextWidth(text) {
+ return minimumNodeTextWidth(text, NOTE_FONT_SIZE);
+}
+
+// Index after the last punctuation break in `piece`, or its full length.
+function noteBreakIndex(piece) {
+ for (let index = piece.length - 1; index > 0; index -= 1) {
+ if (NOTE_BREAK_AFTER.has(piece[index - 1])) return index;
+ }
+ return piece.length;
+}
+
+function wrapNoteText(text, width) {
+ const lines = [];
+ let line = '';
+ const flush = () => {
+ const trimmed = line.trimEnd();
+ if (trimmed) lines.push(trimmed);
+ line = '';
+ };
+ for (const word of String(text).match(/\s+|\S+/gu) || []) {
+ if (/^\s+$/u.test(word)) {
+ if (line) line += ' ';
+ continue;
+ }
+ if (noteTextWidth(line + word) <= width) {
+ line += word;
+ continue;
+ }
+ flush();
+ let piece = '';
+ for (const { segment } of noteSegmenter.segment(word)) {
+ while (piece && noteTextWidth(piece + segment) > width) {
+ const cut = noteBreakIndex(piece);
+ lines.push(piece.slice(0, cut));
+ piece = piece.slice(cut);
+ }
+ piece += segment;
+ }
+ line = piece;
+ }
+ flush();
+ return lines;
+}
+
+// The widest gap the message spans; equal gaps resolve to the left-most one,
+// where a note has always started, so notes keep their original position.
+function noteGapIndex(fromIndex, toIndex) {
+ const low = Math.min(fromIndex, toIndex);
+ const high = Math.max(fromIndex, toIndex);
+ let best = null;
+ for (let gap = low; gap < high; gap += 1) {
+ const width = participantX(gap + 1) - participantX(gap);
+ if (!best || width > best.width + NOTE_GAP_TOLERANCE) best = { gap, width };
+ }
+ return best?.gap ?? null;
+}
+
+function noteRect(message) {
+ const note = noteLayout(message);
+ return note && { x: note.x, y: note.top, width: note.width, height: note.bottom - note.top };
+}
+
+function noteLayout(message) {
+ if (noteLayouts.has(message)) return noteLayouts.get(message);
+ let result = null;
+ const fromIndex = participantIndexById.get(message.from);
+ const toIndex = participantIndexById.get(message.to);
+ if (message.note && typeof message.y === 'number' && fromIndex !== undefined && toIndex !== undefined && fromIndex !== toIndex) {
+ const gap = noteGapIndex(fromIndex, toIndex);
+ const x = participantX(gap) + NOTE_ARROW_INSET + NOTE_TEXT_INSET;
+ const maxWidth = Math.max(1, participantX(gap + 1) - NOTE_LIFELINE_CLEARANCE - x);
+ const lines = noteTextWidth(message.note) <= maxWidth ? [message.note] : wrapNoteText(message.note, maxWidth);
+ const baseline = message.y + 18;
+ result = {
+ x,
+ baseline,
+ lines,
+ width: Math.max(...lines.map(noteTextWidth)),
- top: baseline - NOTE_FONT_SIZE,
++ // Include fallback-font ascent in the same bounds used for title clearance.
++ top: baseline - NOTE_FONT_SIZE * 1.2,
+ bottom: message.y + 22 + (lines.length - 1) * NOTE_LINE_HEIGHT,
+ };
+ }
+ noteLayouts.set(message, result);
+ return result;
+}
+
+const contentBottom = Math.max(
+ 0,
+ ...asArray(sequence.messages).map((message) => (message.note
+ ? noteLayout(message)?.bottom ?? message.y + 22
+ : message.y + 6)),
+ ...asArray(sequence.activations).map((activation) => activation.to),
+ ...asArray(sequence.segments).map((segment) => segment.to),
+);
+function legendRequiredHeight(width) {
+ const entries = legendEntries();
+ if (!entries.length) return 0;
+ return Math.ceil(contentBottom + LEGEND_CONTENT_GAP + LEGEND_BLOCK_HEIGHT
+ + legendFootprint(entries, { width: width - 80 }).extraHeight);
+}
- // A renderer-sized canvas grows to keep the legend clear of late messages;
- // an authored viewBox is honored and validated below.
- const viewBox = sequence.meta?.viewBox || [automaticWidth, Math.max(760, legendRequiredHeight(automaticWidth))];
++// A renderer-sized canvas grows to keep the legend clear of late messages and
++// shrinks when the timeline is short. Keep a readable minimum band (lifelineTop
++// 142 + 120px timeline + 65px footer = 327); honor authored canvases below.
++const SEQUENCE_MIN_AUTO_HEIGHT = 327;
++// Timeline clearance is independent of legend visibility. Messages need 18px
++// before the lifeline bottom; notes, activations and frames need their footer.
++const timelineRequiredHeight = Math.max(contentBottom + 65,
++ ...asArray(sequence.messages).map((message) => message.y + 18 + 65));
++const automaticHeight = Math.max(SEQUENCE_MIN_AUTO_HEIGHT, timelineRequiredHeight, legendRequiredHeight(automaticWidth));
++const viewBox = sequence.meta?.viewBox || [automaticWidth, automaticHeight];
+// The timeline scales with viewBox height: a taller viewBox gains message room,
+// a shorter one shrinks the readable band (validated below) instead of clipping.
// Showcase is the fast-authoring default; standard retains legacy label geometry.
const readableMessages = sequence.meta?.quality_profile === 'showcase';
@@@ -240,9 -162,11 +282,9 @@@ const layout =
lifelineTop: 142,
lifelineBottom: viewBox[1] - 65,
legendY: viewBox[1] - 54,
- leftX: columnFit === 'spread' ? sideMargin + participantW / 2 : sideMargin,
+ leftX,
colGap,
- labelH: readableMessages ? 18 : 16
+ labelH: readableMessages ? 18 : 16,
- noteFontSize: 7,
- noteBaselineOffset: 18,
};
// Automatic showcase spread can guarantee a readable fit within its bounded
@@@ -327,44 -262,42 +369,73 @@@ function segmentLabelOccupants()
function segmentLabelBox(segment) {
const labelW = Math.max(42, textUnits(segment.label) * 5.2 + 14);
- const occupied = asArray(sequence.messages)
- .flatMap((message) => [messageLabelBox(message), messageRouteBox(message), messageNoteBox(message)])
- .filter(Boolean);
+ const occupied = segmentLabelOccupants();
const label = { x: 56, y: segment.from - 22, width: labelW, height: 18 };
for (let attempt = 0; attempt < 4; attempt += 1) {
- if (!occupied.some((rect) => rectsOverlap(label, rect, 2))) break;
+ if (!occupied.some(({ rect }) => rectsOverlap(label, rect, 2))) break;
label.y -= 22;
}
+ if (!segmentLabelMisplaced(label, segment)) return label;
+ // Abutting segments can leave no room on the border: the badge climbed
+ // behind the participant headers or into the previous segment, where it
+ // names the wrong phase. Its own frame's top-left corner, clear of messages,
+ // names the right one.
+ // Another segment's title normally sits on that segment's own top border,
+ // so its strip is taken too.
+ const otherTitles = asArray(sequence.segments).filter((other) => other !== segment)
+ .map((other) => ({ x: 56, y: other.from - 22, width: Math.max(42, textUnits(other.label) * 5.2 + 14), height: 18 }));
+ const inside = { x: 56, y: segment.from + 4, width: labelW, height: 18 };
+ for (let attempt = 0; attempt < 4 && inside.y + inside.height <= segment.to - 2; attempt += 1) {
- if (![...occupied, ...otherTitles, ...participants.values()].some((rect) => rectsOverlap(inside, rect, 2))) return inside;
++ if (!segmentLabelMisplaced(inside, segment)
++ && ![...occupied.map(({ rect }) => rect), ...otherTitles, ...participants.values()].some((rect) => rectsOverlap(inside, rect, 2))) return inside;
+ inside.y += 22;
+ }
return label;
}
+// Whether moving one message to `y` keeps it readable: inside the timeline,
+// 28px from messages sharing its horizontal span, and clear of every other
+// label, route and note. Used to offer only repairs that hold.
+function messageFitsAt(messageIndex, y) {
+ const messages = asArray(sequence.messages);
- if (y < layout.lifelineTop + 18 || y > layout.lifelineBottom - 18) return false;
++ if (y < layout.lifelineTop + 18) return false;
++ // An automatic canvas recalculates its height after this edit; an authored
++ // canvas must still fit the suggested position without a second repair.
++ if (sequence.meta?.viewBox && y > layout.lifelineBottom - 18) return false;
+ const span = (message) => {
+ const from = participants.get(message.from)?.cx;
+ const to = participants.get(message.to)?.cx;
+ return [Math.min(from, to), Math.max(from, to)];
+ };
+ const moved = { ...messages[messageIndex], y };
+ const [left, right] = span(moved);
+ const movedRects = [messageLabelBox(moved), messageRouteBox(moved), noteRect(moved)].filter(Boolean);
+ return messages.every((other, otherIndex) => {
+ if (otherIndex === messageIndex || typeof other.y !== 'number') return true;
+ const [otherLeft, otherRight] = span(other);
+ if (Math.abs(other.y - y) < 28 && left < otherRight && otherLeft < right) return false;
+ const otherRects = [messageLabelBox(other), messageRouteBox(other), noteRect(other)].filter(Boolean);
+ return !movedRects.some((rect) => otherRects.some((otherRect) => rectsOverlap(rect, otherRect, 2)));
+ });
+}
+
+// The first occupant the segment label still covers after its upward steps.
+function segmentLabelBlocker(segment) {
+ const label = segmentLabelBox(segment);
+ return segmentLabelOccupants().find(({ rect }) => rectsOverlap(label, rect, 2)) || null;
+}
+
+ // A badge on its frame's top border is the intended title. It stops naming
+ // that frame once it hides mostly behind the participant headers, or once
+ // message labels pushed it up into another segment.
+ function segmentLabelMisplaced(label, segment) {
+ const half = label.height / 2;
+ if (layout.topY + layout.participantH - label.y > half) return true;
+ if (label.y >= segment.from - 22) return false;
+ return asArray(sequence.segments).some((other) => other !== segment
+ && Math.min(label.y + label.height, other.to) - Math.max(label.y, other.from) > half);
+ }
+
const compositionFrames = asArray(sequence.segments).map((segment, index) => ({
id: index,
label: segment.label,
diff --cc scripts/browser-test-inventory.mjs
index 00000000,63dcc530..d0f7dda6
mode 000000,100644..100644
--- a/scripts/browser-test-inventory.mjs
+++ b/scripts/browser-test-inventory.mjs
@@@ -1,0 -1,36 +1,37 @@@
+ // Shared by PR CI and tag releases. WebM decoding stays in test:webm.
+ // Adjacent heavy suites use opposite indices for CI's two modulo shards.
+ export const browserTestFiles = [
+ 'finalize-browser.test.mjs',
+ 'desktop-reader-browser.test.mjs',
+ 'reader-readability-maintained-browser.test.mjs',
+ 'reader-layout-browser.test.mjs',
+ 'reader-layout-settle-browser.test.mjs',
+ 'reader-cards-overflow-browser.test.mjs',
+ 'joint-layout-browser.test.mjs',
+ 'sequence-header-clearance.test.mjs',
+ 'sequence-width-default-browser.test.mjs',
+ 'compact-header-clearance.test.mjs',
+ 'architecture-reading-size-browser.test.mjs',
+ 'export-cleanup-browser.test.mjs',
+ 'i18n.test.mjs',
+ 'offline-font-browser.test.mjs',
+ 'viewer-chrome-layout.test.mjs',
+ 'semantic-radar.test.mjs',
+ 'viewer-camera-browser.test.mjs',
+ 'motion-governor-browser.test.mjs',
+ 'finder-browser.test.mjs',
+ 'intent-trace-browser.test.mjs',
+ 'semantic-lens-browser.test.mjs',
+ 'route-probe-browser.test.mjs',
+ 'focus-browser.test.mjs',
+ 'crossover-state-browser.test.mjs',
+ 'semantic-passport-move-browser.test.mjs',
+ 'export-browser.test.mjs',
++ 'sequence-note-export-browser.test.mjs',
+ 'viewer-identifiers-browser.test.mjs',
+ 'repository-evidence.test.mjs',
+ 'repository-evidence-types-browser.test.mjs',
+ 'tree-branches-browser.test.mjs',
+ 'class-motion-browser.test.mjs',
+ 'dataflow-label-visibility-browser.test.mjs',
+ ];
diff --cc test/reader-layout-browser.test.mjs
index 0e983059,2537dbf5..9f67d6ae
--- a/test/reader-layout-browser.test.mjs
+++ b/test/reader-layout-browser.test.mjs
@@@ -604,6 -631,178 +631,181 @@@ test('Reader Layout preserves final-art
assert.ok(await evaluate("document.querySelector('.diagram-container > svg').clientWidth > 456 * 1.5"),
'an authored canvas retains its previous enlargement behavior');
});
+ await t.test('compact automatic Sequence fits the initial desktop stage without shrinking source text', async () => {
+ const compact = JSON.parse(fs.readFileSync(path.resolve(skillRoot,
+ '../test/fixtures/reader-readability/compact-roundtrip.sequence.json'), 'utf8'));
++ // Wrapped notes need 6px more room before the Accepted label. Preserve
++ // all annotations and the remaining timeline while exercising Reader fit.
++ compact.messages.find(message => message.id === 'accepted').y = 236;
+ function renderSequence(name, doc) {
+ const input = path.join(scratch, `${name}.json`);
+ const output = path.join(scratch, `${name}.html`);
+ fs.writeFileSync(input, JSON.stringify(doc));
+ execFileSync(process.execPath, [path.join(skillRoot, 'bin/archify.mjs'), 'render', 'sequence', input, output]);
+ return output;
+ }
+ async function stage(label) {
+ const value = await evaluate(`(function () {
+ var svg = document.querySelector('.diagram-container > svg');
+ function bounds(element) {
+ var rect = element.getBoundingClientRect();
+ return { top: rect.top, bottom: rect.bottom, left: rect.left, right: rect.right };
+ }
+ var textScales = Array.from(svg.querySelectorAll('text')).map(function (text) {
+ var matrix = text.getScreenCTM();
+ return Math.hypot(matrix.a, matrix.b);
+ });
+ var legend = svg.querySelector('[data-legend]');
+ var legendRect = legend.getBoundingClientRect();
+ var containerRect = svg.parentElement.getBoundingClientRect();
+ var containerStyle = getComputedStyle(svg.parentElement);
+ var navRect = document.querySelector('.diagram-nav').getBoundingClientRect();
+ return { svg: bounds(svg), stage: bounds(svg.parentElement),
+ controls: bounds(document.querySelector('.diagram-nav')),
+ legend: { corner: legend.hasAttribute('data-reader-legend-corner'),
+ bounds: bounds(legend),
+ originalSvg: legend.ownerSVGElement === svg, count: document.querySelectorAll('[data-legend]').length,
+ leftGap: legendRect.left - containerRect.left - parseFloat(containerStyle.borderLeftWidth) - parseFloat(containerStyle.paddingLeft),
+ bottomGap: containerRect.bottom - parseFloat(containerStyle.borderBottomWidth) - parseFloat(containerStyle.paddingBottom) - legendRect.bottom,
+ navOverlap: Math.max(0, Math.min(navRect.right, legendRect.right) - Math.max(navRect.left, legendRect.left)) *
+ Math.max(0, Math.min(navRect.bottom, legendRect.bottom) - Math.max(navRect.top, legendRect.top)) },
+ width: svg.clientWidth, sourceWidth: svg.viewBox.baseVal.width,
+ minimumTextScale: Math.min.apply(Math, textScales),
+ viewportWidth: innerWidth, viewportHeight: innerHeight,
+ geometry: ['viewBox', 'width', 'height'].map(function (name) { return svg.getAttribute(name); }) };
+ })()`);
+ records.push({ label, ...value });
+ return value;
+ }
+ function fits(value) {
+ for (const region of [value.svg, value.stage, value.controls]) {
+ assert.ok(region.top >= -1 && region.bottom <= value.viewportHeight + 1 &&
+ region.left >= -1 && region.right <= value.viewportWidth + 1, JSON.stringify(value));
+ }
+ assert.ok(value.minimumTextScale >= 1 - 0.01, 'initial fitting must retain source text size: ' + JSON.stringify(value));
+ assert.ok(value.width <= value.sourceWidth * 1.5 + 1, 'automatic enlargement remains capped: ' + JSON.stringify(value));
+ }
+ function legendPlacement(value, corner) {
+ assert.equal(value.legend.corner, corner, JSON.stringify(value));
+ assert.equal(value.legend.originalSvg, true, 'legend remains in the original SVG');
+ assert.equal(value.legend.count, 1, 'legend is never duplicated');
+ if (corner) {
+ assert.ok(Math.abs(value.legend.leftGap) <= 1 && Math.abs(value.legend.bottomGap) <= 1,
+ 'legend sits in the outer stage padding corner: ' + JSON.stringify(value));
+ assert.equal(value.legend.navOverlap, 0, 'legend must not overlap navigation');
+ }
+ }
+ async function exportedLegend() {
+ return evaluate(`(async function () {
+ var svg = document.querySelector('.diagram-container > svg');
+ var before = svg.outerHTML, original = URL.createObjectURL, captured;
+ URL.createObjectURL = function (blob) {
+ if (blob.type.indexOf('image/svg+xml') === 0) captured = blob;
+ return original.call(URL, blob);
+ };
+ try {
+ await Archify.exportMenu.run('svg');
+ var text = await captured.text();
+ var clone = new DOMParser().parseFromString(text, 'image/svg+xml').documentElement;
+ return { legend: clone.querySelector('[data-legend]').outerHTML.replace(' style=""', ''),
+ geometry: ['viewBox', 'width', 'height'].map(function (name) { return clone.getAttribute(name); }),
+ count: clone.querySelectorAll('[data-legend]').length, liveUnchanged: before === svg.outerHTML,
+ runtime: Boolean(clone.querySelector('[data-reader-legend-corner]')) || text.includes('--archify-reader-legend-transform') };
+ } finally { URL.createObjectURL = original; }
+ })()`, true);
+ }
+ const file = renderSequence('compact-roundtrip', compact);
+ await load(file, { width: 1396, height: 540 });
+ const canonical = await exportedLegend();
+ assert.equal(canonical.count, 1);
+ assert.equal(canonical.liveUnchanged, true);
+ assert.equal(canonical.runtime, false);
+ await load(file, { width: 1396, height: 830 });
+ const initial = await stage('compact-sequence-initial');
+ fits(initial);
+ legendPlacement(initial, true);
+ if (evidence) {
+ assert.equal(await evaluate('scrollY'), 0, 'initial screenshot uses the top of the document');
+ assert.equal(await evaluate('Archify.view.state().scale'), 1);
+ const capture = await send('Page.captureScreenshot', { format: 'png' });
+ fs.writeFileSync(path.join(evidence, 'compact-sequence-initial.png'), Buffer.from(capture.data, 'base64'));
+ }
+ assert.deepEqual(await exportedLegend(), canonical, 'initial fitting exports canonical geometry and legend placement');
+ assert.ok((await snapshot('compact-sequence-shell')).shellWidth >= 960, 'height fitting preserves the desktop shell');
+ await evaluate('Archify.view.zoomIn(); Archify.view.zoomIn()');
+ await stable();
+ const zoomed = await stage('compact-sequence-legend-150');
+ assert.equal(await evaluate('Archify.view.state().scale'), 1.5);
+ legendPlacement(zoomed, false);
+ assert.deepEqual(zoomed.geometry, initial.geometry);
+ assert.deepEqual(await exportedLegend(), canonical, 'zoom exports canonical legend placement without changing live SVG');
+ await evaluate('Archify.view.reset()');
+ await stable();
+ const reset = await stage('compact-sequence-legend-reset');
+ fits(reset);
+ legendPlacement(reset, true);
+ assert.deepEqual(reset.geometry, initial.geometry);
+ await viewport(1396, 540);
+ await stable();
+ const short = await stage('compact-sequence-short-window');
+ assert.ok(short.stage.bottom > short.viewportHeight, 'insufficient height retains page scrolling');
+ assert.ok(short.minimumTextScale >= 1 - 0.01, 'short windows do not shrink source text');
+ assert.ok(short.width >= initial.width, 'short windows recover reading width');
+ await viewport(1396, 830);
+ await stable();
+ const resizedBack = await stage('compact-sequence-resized-back');
+ fits(resizedBack);
+ legendPlacement(resizedBack, true);
+ await evaluate('Archify.presentation.enter()');
+ await stable();
+ const presented = await stage('compact-sequence-presentation');
+ legendPlacement(presented, false);
+ assert.deepEqual(presented.geometry, initial.geometry);
+ assert.deepEqual(await exportedLegend(), canonical, 'presentation exports canonical legend placement');
+ assert.ok(presented.svg.top >= -1 && presented.svg.bottom <= presented.viewportHeight + 1, JSON.stringify(presented));
+ await evaluate('Archify.presentation.exit()');
+ await stable();
+ const returned = await stage('compact-sequence-return');
+ fits(returned);
+ legendPlacement(returned, true);
+ assert.deepEqual(returned.geometry, initial.geometry, 'fitting never rewrites authored SVG geometry');
+ await media('dark', false, true);
+ await stable();
+ const printed = await stage('compact-sequence-print');
+ legendPlacement(printed, false);
+ assert.deepEqual(printed.geometry, initial.geometry);
+ assert.deepEqual(await exportedLegend(), canonical, 'print exports canonical legend placement');
+ await media();
+ await stable();
+ legendPlacement(await stage('compact-sequence-print-return'), true);
+
+ const wide = { ...compact, segments: [], cards: [],
+ messages: [{ from: 'client', to: 'worker', y: 160, label: 'Check status' }] };
+ await load(renderSequence('short-wide-sequence', wide), { width: 1396, height: 480 });
+ const shortWide = await stage('short-wide-sequence');
+ assert.ok(shortWide.sourceWidth < 960 && shortWide.sourceWidth /
+ Number(shortWide.geometry[0].split(/\s+/)[3]) >= 1.55, 'exercise a small wide canvas');
+ fits(shortWide);
+
+ const long = { ...compact, segments: [], cards: [], messages: Array.from({ length: 20 }, (_, index) => ({
+ from: index % 2 ? 'service' : 'client', to: index % 2 ? 'client' : 'service',
+ y: 160 + index * 100, label: `Message ${index + 1}`,
+ })) };
+ await load(renderSequence('long-automatic-sequence', long), { width: 1396, height: 830 });
+ const reading = await stage('long-automatic-sequence');
+ assert.ok(reading.stage.bottom > reading.viewportHeight, 'long automatic Sequence retains page scrolling');
+ assert.ok(reading.minimumTextScale >= 1 - 0.01, 'long Sequence preserves readable text');
+ assert.ok(reading.width >= reading.sourceWidth * 1.4, 'long Sequence retains reading-width enlargement');
+
+ const explicit = structuredClone(compact);
+ explicit.meta.viewBox = initial.geometry[0].split(/\s+/).slice(2).map(Number);
+ await load(renderSequence('explicit-roundtrip', explicit), { width: 1396, height: 830 });
+ const authored = await stage('explicit-roundtrip');
+ assert.deepEqual(authored.geometry, initial.geometry);
+ assert.equal((await snapshot('explicit-sequence')).readerFit, null, 'explicit canvases retain their previous eligibility');
+ assert.ok(authored.stage.bottom > authored.viewportHeight, 'explicit geometry retains its original desktop layout');
+ });
+
await t.test('public renderers declare automatic reading width while undeclared canvases retain their fit', async () => {
const sequence = { schema_version: 1, diagram_type: 'sequence', meta: { title: 'Reader sequence', output: 'reader-sequence.html' },
participants: [{ id: 'a', type: 'external', label: 'Client' }, { id: 'b', type: 'backend', label: 'Server' }],
diff --cc test/sequence-note-export-browser.test.mjs
index 97b3c493,00000000..7948153d
mode 100644,000000..100644
--- a/test/sequence-note-export-browser.test.mjs
+++ b/test/sequence-note-export-browser.test.mjs
@@@ -1,100 -1,0 +1,101 @@@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { execFileSync } from 'node:child_process';
+import { fileURLToPath, pathToFileURL } from 'node:url';
+import { ChromeVisualBrowser, findChrome } from '../archify/bin/visual-check.mjs';
+
+// Wrapped sequence notes are fine-detail text, hidden at the default zoom, so
+// exports must still carry every line (#676).
+const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'archify');
+const chrome = process.env.ARCHIFY_CHROME ? findChrome() : null;
+const LONG_NOTE = 'this note explains the whole retry and backoff policy in a lot of detail so it is very long';
+
+test('SVG and PNG exports keep every line of a wrapped sequence note', {
+ skip: chrome ? false : 'Set ARCHIFY_CHROME to run real-browser export checks.',
+}, async (t) => {
+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-note-export-'));
+ t.after(() => fs.rmSync(scratch, { recursive: true, force: true }));
+ const input = path.join(scratch, 'note.json');
+ const file = path.join(scratch, 'note.html');
+ fs.writeFileSync(input, JSON.stringify({
+ schema_version: 1,
+ diagram_type: 'sequence',
+ meta: { title: 'Note export', output: 'note.html', quality_profile: 'showcase', column_fit: 'spread' },
+ participants: [
+ { id: 'client', type: 'external', label: 'Client' },
+ { id: 'api', type: 'backend', label: 'API' },
+ { id: 'db', type: 'database', label: 'DB' },
+ ],
+ messages: [
+ { id: 'request', from: 'client', to: 'api', y: 200, label: 'request', note: LONG_NOTE },
+ { id: 'reply', from: 'api', to: 'client', y: 300, label: 'reply', variant: 'return' },
+ ],
+ }));
+ execFileSync(process.execPath, [path.join(skillRoot, 'renderers/sequence/render-sequence.mjs'), input, file]);
+ const lines = [...fs.readFileSync(file, 'utf8').matchAll(/<tspan x="[\d.]+" dy="[\d.]+">([^<]*)<\/tspan>/g)].map((match) => match[1]);
+ assert.ok(lines.length > 1, 'the fixture note wraps');
+
+ const browser = new ChromeVisualBrowser(chrome);
+ t.after(() => browser.close());
+ const session = await browser.sessionPromise;
+ const send = (method, params = {}) => browser.cdp.send(method, params, session);
+ await browser.cdp.send('Browser.setDownloadBehavior', { behavior: 'deny' });
+ async function run(expression) {
+ const result = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
+ assert.equal(result.exceptionDetails, undefined, result.exceptionDetails?.exception?.description);
+ return result.result?.value;
+ }
+ // Capture downloads at the anchor boundary; serialization, drawing and
+ // encoding remain production code.
+ await send('Page.addScriptToEvaluateOnNewDocument', { source: `
+ window.noteDownloads=[];
+ const create=URL.createObjectURL.bind(URL),blobs=new Map();
+ URL.createObjectURL=blob=>{const url=create(blob);blobs.set(url,blob);return url;};
+ const click=HTMLAnchorElement.prototype.click;
+ HTMLAnchorElement.prototype.click=function(){if(this.download){noteDownloads.push(blobs.get(this.href));return;}return click.call(this);};
+ window.noteExport=async format=>{const count=noteDownloads.length;await Archify.exportMenu.run(format);
+ const start=performance.now();while(noteDownloads.length===count){if(performance.now()-start>15000)throw new Error('export timed out');await new Promise(r=>setTimeout(r,20));}
+ return noteDownloads[noteDownloads.length-1];};
+ window.notePixels=async blob=>{const bitmap=await createImageBitmap(blob);const canvas=document.createElement('canvas');canvas.width=bitmap.width;canvas.height=bitmap.height;
+ const context=canvas.getContext('2d');context.drawImage(bitmap,0,0);return context.getImageData(0,0,bitmap.width,bitmap.height);};
+ ` });
+ await send('Emulation.setDeviceMetricsOverride', { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false });
+ const loaded = browser.cdp.waitFor('Page.loadEventFired', session);
+ await send('Page.navigate', { url: pathToFileURL(file).href });
+ await loaded;
+ await run('document.fonts.ready');
+ await run('Archify.readerLayout.whenStable()');
+
+ // The default zoom hides fine detail; the export must not.
+ assert.equal(await run(`getComputedStyle(document.querySelector('text[data-detail="fine"]')).opacity`), '0');
+ const svg = await run(`noteExport('svg').then(blob=>blob.text())`);
+ for (const line of lines) assert.ok(svg.includes(`>${line}</tspan>`), `SVG export keeps "${line}"`);
+ assert.doesNotMatch(svg, /data-detail="fine"/, 'SVG export removes the zoom-only marker');
+
+ // Compare PNG exports with and without the note text: the difference is the
+ // note itself, and it must be as tall as its wrapped lines.
+ const diff = await run(`(async()=>{
+ const withNote=await notePixels(await noteExport('png'));
+ const note=document.querySelector('text[data-detail="fine"]');const saved=note.innerHTML;note.innerHTML='';
+ const withoutNote=await notePixels(await noteExport('png'));note.innerHTML=saved;
+ if(withNote.width!==withoutNote.width||withNote.height!==withoutNote.height)return {sameSize:false};
+ let top=Infinity,bottom=-1,left=Infinity,right=-1;
+ for(let y=0;y<withNote.height;y+=1)for(let x=0;x<withNote.width;x+=1){const i=(y*withNote.width+x)*4;
+ if(Math.abs(withNote.data[i]-withoutNote.data[i])+Math.abs(withNote.data[i+1]-withoutNote.data[i+1])+Math.abs(withNote.data[i+2]-withoutNote.data[i+2])>24){
+ top=Math.min(top,y);bottom=Math.max(bottom,y);left=Math.min(left,x);right=Math.max(right,x);}}
+ return {sameSize:true,width:withNote.width,top,bottom,left,right};
+ })()`);
+ assert.equal(diff.sameSize, true);
+ assert.ok(diff.bottom >= 0, 'the PNG export draws the note');
- const scale = diff.width / 920;
++ const exportedWidth = Number(svg.match(/viewBox="[\d.]+ [\d.]+ ([\d.]+) [\d.]+"/)[1]);
++ const scale = diff.width / exportedWidth;
+ assert.ok(diff.bottom - diff.top >= (lines.length - 1) * 11 * scale * 0.8, `the PNG note spans its ${lines.length} lines (${diff.bottom - diff.top}px at scale ${scale.toFixed(2)})`);
+
+ if (process.env.ARCHIFY_NOTE_EXPORT_EVIDENCE) {
+ const png = await run(`noteExport('png').then(blob=>new Promise((resolve,reject)=>{const reader=new FileReader();reader.onload=()=>resolve(String(reader.result).split(',')[1]);reader.onerror=reject;reader.readAsDataURL(blob);}))`);
+ fs.writeFileSync(process.env.ARCHIFY_NOTE_EXPORT_EVIDENCE, Buffer.from(png, 'base64'));
+ }
+});
diff --cc test/sequence-note-wrap.test.mjs
index f8530723,00000000..6b8ee5fc
mode 100644,000000..100644
--- a/test/sequence-note-wrap.test.mjs
+++ b/test/sequence-note-wrap.test.mjs
@@@ -1,325 -1,0 +1,338 @@@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { spawnSync } from 'node:child_process';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { minimumNodeTextWidth } from '../archify/renderers/shared/text-fit.mjs';
+
+// Sequence message notes wrap inside one gap between neighbouring lifelines and
+// keep every character (#676).
+const skillRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'archify');
+const cli = path.join(skillRoot, 'bin/archify.mjs');
+const LONG_NOTE = 'this note explains the whole retry and backoff policy in a lot of detail so it is very long';
+const URL_NOTE = 'see https://api.example.com/v2/users/profile/settings/notifications/email-preferences';
+
+function sequence({ messages, participants = ['client', 'api', 'db'], quality = 'showcase', activations } = {}) {
+ return {
+ schema_version: 1,
+ diagram_type: 'sequence',
+ meta: { title: 'Note wrap', output: 'note.html', quality_profile: quality, column_fit: 'spread' },
+ participants: participants.map((id) => ({ id, type: 'backend', label: id.toUpperCase() })),
+ messages,
+ ...(activations ? { activations } : {}),
+ };
+}
+
+function run(t, command, spec) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-sequence-note-'));
+ t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
+ const input = path.join(dir, 'candidate.json');
+ const output = path.join(dir, 'note.html');
+ fs.writeFileSync(input, JSON.stringify(spec));
+ const args = command === 'render'
+ ? [cli, 'render', 'sequence', input, output]
+ : [cli, 'validate', 'sequence', input, '--json'];
+ const result = spawnSync(process.execPath, args, { cwd: skillRoot, encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 });
+ return { result, html: command === 'render' && result.status === 0 ? fs.readFileSync(output, 'utf8') : '' };
+}
+
+function render(t, spec) {
+ const { result, html } = run(t, 'render', spec);
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ return html;
+}
+
+function lifelines(html) {
+ return [...html.matchAll(/<path d="M ([\d.]+) 142 L \1 [\d.]+" class="a-default" stroke-width="0.8" stroke-dasharray="3,7"\/>/g)]
+ .map((match) => Number(match[1]));
+}
+
+function notes(html) {
+ return [...html.matchAll(/<text data-detail="fine" x="([\d.]+)" y="([\d.]+)" class="t-dim" font-size="7">([\s\S]*?)<\/text>/g)]
+ .map((match) => {
+ const tspans = [...match[3].matchAll(/<tspan x="([\d.]+)" dy="([\d.]+)">([^<]*)<\/tspan>/g)];
+ return {
+ x: Number(match[1]),
+ y: Number(match[2]),
+ raw: match[3],
+ lines: tspans.length ? tspans.map((line) => line[3]) : [match[3]],
+ tspanX: tspans.map((line) => Number(line[1])),
+ dy: tspans.map((line) => Number(line[2])),
+ };
+ });
+}
+
+function decode(text) {
+ return text.replaceAll('&amp;', '&');
+}
+
+test('the reported long note wraps inside its own lane and keeps every word', (t) => {
+ const html = render(t, sequence({
+ messages: [
+ { id: 'request', from: 'client', to: 'api', y: 200, label: 'request', note: LONG_NOTE },
+ { id: 'reply', from: 'api', to: 'client', y: 380, label: 'reply', variant: 'return' },
+ ],
+ activations: [{ participant: 'api', from: 190, to: 390 }],
+ }));
+ const [client, api] = lifelines(html);
+ const [note] = notes(html);
+ assert.ok(note.lines.length > 1, 'the long note wraps');
+ assert.equal(note.lines.join(' '), LONG_NOTE, 'no word is dropped or shortened');
+ assert.equal(note.x, client + 19, 'the first line keeps its original position');
+ assert.deepEqual(note.dy, note.lines.map((_, index) => (index ? 11 : 0)));
+ for (const line of note.lines) {
+ assert.ok(note.x + minimumNodeTextWidth(line, 7) <= api - 11, `"${line}" stays clear of the API activation bar`);
+ }
+});
+
+test('long unbroken text breaks after URL punctuation and keeps every character', (t) => {
+ const html = render(t, sequence({
+ participants: ['client', 'api', 'db', 'cache', 'queue'],
+ messages: [{ id: 'link', from: 'client', to: 'api', y: 200, label: 'docs', note: URL_NOTE }],
+ }));
+ const [client, api] = lifelines(html);
+ const [note] = notes(html);
+ assert.ok(note.lines.length > 2, 'the address spans several lines');
+ assert.equal(note.lines[0], 'see');
+ assert.equal(note.lines.slice(1).join(''), URL_NOTE.slice('see '.length), 'every character of the address is kept');
+ for (const line of note.lines.slice(1, -1)) {
+ assert.match(line, /[/.\-?&=#_]$/, `"${line}" breaks after punctuation`);
+ }
+ for (const line of note.lines) {
+ assert.ok(client + 19 + minimumNodeTextWidth(line, 7) <= api - 11, `"${line}" fits its lane`);
+ }
+});
+
+test('text without any punctuation breaks at a character boundary', (t) => {
+ const token = 'x'.repeat(160);
+ const html = render(t, sequence({ messages: [{ from: 'client', to: 'api', y: 200, label: 'token', note: token }] }));
+ const [note] = notes(html);
+ assert.ok(note.lines.length > 1);
+ assert.equal(note.lines.join(''), token);
+});
+
+test('a short note keeps its original single-line markup', (t) => {
+ const html = render(t, sequence({ messages: [{ from: 'api', to: 'client', y: 200, label: 'reply', note: 'cached for 5 minutes' }] }));
+ const [client] = lifelines(html);
+ assert.match(html, new RegExp(`<text data-detail="fine" x="${client + 19}" y="218" class="t-dim" font-size="7">cached for 5 minutes</text>`));
+ assert.doesNotMatch(html, /<tspan/);
+});
+
+test('a note on a message that skips participants stays in the left-most gap, in either direction', (t) => {
+ for (const [from, to] of [['client', 'db'], ['db', 'client']]) {
+ const html = render(t, sequence({ messages: [{ from, to, y: 200, label: 'lookup', note: LONG_NOTE }] }));
+ const [client, api] = lifelines(html);
+ const [note] = notes(html);
+ assert.equal(note.x, client + 19, `${from} → ${to} starts where notes always started`);
+ for (const line of note.lines) {
+ assert.ok(note.x + minimumNodeTextWidth(line, 7) <= api - 11, `${from} → ${to}: "${line}" stays clear of the skipped API lifeline`);
+ }
+ }
+});
+
+test('a short note on a reverse message that skips a participant keeps its original position', (t) => {
+ const html = render(t, sequence({ messages: [{ from: 'db', to: 'client', y: 200, label: 'result', note: 'from replica' }] }));
+ const [client] = lifelines(html);
+ assert.match(html, new RegExp(`<text data-detail="fine" x="${client + 19}" y="218" class="t-dim" font-size="7">from replica</text>`));
+});
+
+test('equal spread gaps that differ only by floating-point rounding keep the left-most gap', (t) => {
+ // Six and seven spread columns produce middle gaps such as 141.80000000000007.
+ for (const count of [6, 7]) {
+ const ids = Array.from({ length: count }, (_, index) => `p${index}`);
+ for (const [from, to] of [[ids.at(-1), ids[0]], [ids[0], ids.at(-1)]]) {
+ const html = render(t, sequence({ participants: ids, messages: [{ from, to, y: 200, label: 'reply', note: 'ok' }] }));
+ const [first] = lifelines(html);
+ const [note] = notes(html);
+ assert.ok(Math.abs(note.x - (first + 19)) < 1e-9, `${count} participants, ${from} → ${to}: note at ${note.x}, expected ${first + 19}`);
+ }
+ }
+});
+
+// Fixed columns keep the first note beside the segment label column at x=56.
+test('a segment label steps up clear of a wrapped note', (t) => {
+ const spec = sequence({
+ messages: [{ from: 'client', to: 'api', y: 200, label: 'request', note: 'retries with backoff when the cache misses' }],
+ });
+ spec.meta.column_fit = 'fixed';
+ spec.segments = [{ label: 'Fallback', from: 260, to: 360 }];
+ const { result } = run(t, 'validate', spec);
+ assert.equal(result.status, 0, result.stdout);
+ const html = render(t, spec);
+ const [note] = notes(html);
+ const labelY = Number(html.match(/<rect x="56" y="(-?[\d.]+)" width="[\d.]+" height="18"/)[1]);
+ const noteTop = note.y - 7;
+ assert.ok(labelY + 18 + 2 <= noteTop || labelY >= note.y + (note.lines.length - 1) * 11 + 4,
+ `segment label at y=${labelY} clears the note from ${noteTop}`);
+});
+
+// Read one structured diagnostic from `validate --json` and apply its single
+// supported fix ("set /json/pointer to value") to a copy of the input.
+function failure(t, spec, code) {
+ const { result } = run(t, 'validate', spec);
+ assert.notEqual(result.status, 0, 'validate must fail');
+ const diagnostic = JSON.parse(result.stdout).diagnostics.find((entry) => entry.code === code);
+ assert.ok(diagnostic, `expected ${code} in ${result.stdout}`);
+ assert.equal(diagnostic.severity, 'error');
+ return diagnostic;
+}
+
+function applyFix(spec, fix) {
+ const [, pointer, value] = fix.match(/^set (\/\S+) to (.+)$/);
+ const copy = structuredClone(spec);
+ const keys = pointer.slice(1).split('/');
+ const parent = keys.slice(0, -1).reduce((node, key) => {
+ node[key] ??= {};
+ return node[key];
+ }, copy);
+ parent[keys.at(-1)] = JSON.parse(value);
+ return copy;
+}
+
+test('a segment label left covering a message label reports it with a verified fix', (t) => {
+ // The reviewer's case: the wrapped note pushes the label up onto "request".
+ const spec = sequence({ messages: [{ from: 'client', to: 'api', y: 200, label: 'request', note: LONG_NOTE }] });
+ spec.meta.column_fit = 'fixed';
+ spec.segments = [{ label: 'Fallback', from: 280, to: 360 }];
+ const diagnostic = failure(t, spec, 'sequence/segment-label-overlap');
+ assert.deepEqual(diagnostic.subject, { diagramType: 'sequence', segment: 'Fallback', path: '/segments/0/from' });
+ assert.equal(diagnostic.evidence.attempts, 4);
+ assert.equal(diagnostic.evidence.covered.kind, 'message label');
+ assert.equal(diagnostic.evidence.covered.path, '/messages/0/label');
+ assert.equal(diagnostic.evidence.covered.message, 'request');
+ assert.equal(diagnostic.supportedFixes.length, 1);
+ assert.match(diagnostic.supportedFixes[0], /^set \/segments\/0\/from to \d+$/);
+ const repaired = run(t, 'validate', applyFix(spec, diagnostic.supportedFixes[0])).result;
+ assert.equal(repaired.status, 0, repaired.stdout);
+});
+
+test('a segment label with no clear position names the note it would cover', (t) => {
+ const spec = sequence({
+ messages: [
+ { from: 'client', to: 'api', y: 160, label: 'open' },
+ { from: 'client', to: 'api', y: 200, label: 'request', note: LONG_NOTE.repeat(3) },
+ ],
+ });
+ spec.meta.column_fit = 'fixed';
+ spec.segments = [{ label: 'Fallback', from: 360, to: 400 }];
+ const diagnostic = failure(t, spec, 'sequence/segment-label-overlap');
+ assert.equal(diagnostic.evidence.covered.kind, 'note');
+ assert.equal(diagnostic.evidence.covered.path, '/messages/1/note');
+ for (const fix of diagnostic.supportedFixes) {
+ assert.equal(run(t, 'validate', applyFix(spec, fix)).result.status, 0, `${fix} must hold`);
+ }
+});
+
+test('a wrapped note below an authored canvas reports the height it needs', (t) => {
+ const spec = (height) => ({
+ ...sequence({ messages: [{ id: 'late', from: 'client', to: 'api', y: 660, label: 'late', note: LONG_NOTE.repeat(3) }] }),
+ meta: { title: 'Fixed canvas', output: 'note.html', quality_profile: 'showcase', column_fit: 'spread', viewBox: [920, height], legend: { mode: 'hidden' } },
+ });
+ const diagnostic = failure(t, spec(760), 'sequence/note-canvas-limit');
+ assert.equal(diagnostic.subject.path, '/messages/0/note');
+ assert.equal(diagnostic.subject.message, 'late');
+ assert.equal(diagnostic.evidence.viewBoxHeight, 760);
+ assert.equal(diagnostic.evidence.canvasLimitY, 760 - 65 + 20);
+ assert.ok(diagnostic.evidence.note.y + diagnostic.evidence.note.height > diagnostic.evidence.canvasLimitY);
+ const required = diagnostic.evidence.requiredViewBoxHeight;
+ assert.deepEqual(diagnostic.supportedFixes, [`set /meta/viewBox/1 to ${required}`]);
+ const repaired = run(t, 'validate', applyFix(spec(760), diagnostic.supportedFixes[0])).result;
+ assert.equal(repaired.status, 0, repaired.stdout);
+ const standard = spec(760);
+ standard.meta.quality_profile = 'standard';
+ assert.equal(run(t, 'validate', standard).result.status, 0, 'standard keeps accepting the authored canvas');
+});
+
+test('a wrapped note that reaches the next message names the message and the y it needs', (t) => {
+ const crowded = (replyY) => sequence({
+ participants: ['client', 'api', 'db', 'cache', 'queue'],
+ messages: [
+ { id: 'request', from: 'client', to: 'api', y: 200, label: 'request', note: LONG_NOTE },
+ { id: 'reply', from: 'api', to: 'client', y: replyY, label: 'reply', variant: 'return' },
+ ],
+ });
+ const diagnostic = failure(t, crowded(230), 'sequence/note-overlap');
+ assert.match(diagnostic.message, /Note on message "request" wraps to \d+ lines/);
+ assert.deepEqual(diagnostic.subject, { diagramType: 'sequence', message: 'request', path: '/messages/0/note', from: 'client', to: 'api' });
+ assert.equal(diagnostic.evidence.blocker.path, '/messages/1/y');
+ assert.equal(diagnostic.evidence.blocker.message, 'reply');
+ assert.equal(diagnostic.evidence.blocker.y, 230);
+ assert.ok(diagnostic.evidence.lines > 1);
+ const requiredY = diagnostic.evidence.requiredY;
+ assert.ok(requiredY > 230);
+ assert.deepEqual(diagnostic.supportedFixes, [`set /messages/1/y to ${requiredY}`]);
+
+ const repaired = run(t, 'validate', applyFix(crowded(230), diagnostic.supportedFixes[0])).result;
+ assert.equal(repaired.status, 0, repaired.stdout);
++ // An automatic canvas grows after the move. An authored canvas of the same
++ // original height cannot promise that one-field repair. Place this case later
++ // in the timeline so its automatic height is also schema-valid when authored.
++ const constrainedSpec = crowded(230);
++ for (const message of constrainedSpec.messages) message.y += 140;
++ const automatic = failure(t, constrainedSpec, 'sequence/note-overlap');
++ const compactHeight = Number(render(t, { ...constrainedSpec, meta: { ...constrainedSpec.meta, quality_profile: 'standard' } })
++ .match(/<svg viewBox="0 0 920 (\d+)"/)[1]);
++ constrainedSpec.meta.viewBox = [920, compactHeight];
++ const constrained = failure(t, constrainedSpec, 'sequence/note-overlap');
++ assert.ok(automatic.evidence.requiredY > compactHeight - 65 - 18, 'repair needs more timeline room than the authored canvas');
++ assert.equal(automatic.supportedFixes.length, 1, 'automatic height grows for the move');
++ assert.deepEqual(constrained.supportedFixes, [], 'authored height remains binding');
+ const html = render(t, crowded(requiredY));
+ assert.equal(decode(notes(html)[0].lines.join(' ')), LONG_NOTE);
+});
+
+test('standard keeps accepting a crowded note', (t) => {
+ const spec = sequence({
+ quality: 'standard',
+ messages: [
+ { from: 'client', to: 'api', y: 200, label: 'request', note: LONG_NOTE },
+ { from: 'api', to: 'client', y: 230, label: 'reply', variant: 'return' },
+ ],
+ });
+ assert.equal(run(t, 'validate', spec).result.status, 0);
+});
+
+test('an automatic canvas grows to hold a wrapped note on the last message', (t) => {
+ const html = render(t, sequence({
+ participants: ['client', 'api', 'db', 'cache', 'queue'],
+ messages: [{ from: 'client', to: 'api', y: 700, label: 'late', note: LONG_NOTE.repeat(2) }],
+ }));
+ const height = Number(html.match(/<svg viewBox="0 0 920 (\d+)"/)[1]);
+ const [note] = notes(html);
+ const lastBaseline = note.y + (note.lines.length - 1) * 11;
+ const legendTitle = Number(html.match(/<text x="[\d.]+" y="([\d.]+)"[^>]*>Legend<\/text>/)[1]);
+ assert.ok(lastBaseline + 2 < legendTitle - 12, `last note line ${lastBaseline} stays above the legend title ${legendTitle}`);
+ assert.ok(height > 760);
+});
+
+test('a widened automatic canvas wraps a late note using its final lane geometry', (t) => {
+ const ids = Array.from({ length: 8 }, (_, index) => `p${index}`);
+ const token = 'x'.repeat(160);
+ const spec = sequence({
+ participants: ids,
+ messages: [{ from: 'p1', to: 'p2', y: 700, label: 'late', note: token }],
+ });
+ // This dev-supported label widens the automatic canvas beyond 920px.
+ spec.participants[4].label = 'Team operations';
+ const html = render(t, spec);
+ const [, widthText, heightText] = html.match(/<svg viewBox="0 0 (\d+) (\d+)"/);
+ const width = Number(widthText);
+ const height = Number(heightText);
+ assert.ok(width > 920 && width <= 1085, `automatic width ${width} stays within the readable bound`);
+ const lanes = lifelines(html);
+ const [note] = notes(html);
+ assert.equal(note.x, lanes[1] + 19, 'note starts in the final sender lane');
+ assert.ok(note.lines.length > 1);
+ assert.equal(note.lines.join(''), token);
+ for (const line of note.lines) {
+ assert.ok(note.x + minimumNodeTextWidth(line, 7) <= lanes[2] - 11, `${line} clears the final next lifeline`);
+ }
+ const lastBaseline = note.y + (note.lines.length - 1) * 11;
+ const legendTitle = Number(html.match(/<text x="[\d.]+" y="([\d.]+)"[^>]*>Legend<\/text>/)[1]);
+ assert.ok(lastBaseline + 2 < legendTitle - 12, 'automatic height includes the wrapped note');
+ const authored = render(t, { ...spec, meta: { ...spec.meta, viewBox: [width, height] } });
+ assert.deepEqual(lifelines(authored), lanes, 'authored and computed canvas widths give the same lanes');
+ assert.deepEqual(notes(authored), notes(html), 'note wrapping uses the final width before automatic height');
+});
diff --cc test/sequence-segment-labels.test.mjs
index 00000000,5cee661c..634f211c
mode 000000,100644..100644
--- a/test/sequence-segment-labels.test.mjs
+++ b/test/sequence-segment-labels.test.mjs
@@@ -1,0 -1,150 +1,180 @@@
+ import { test } from 'node:test';
+ import assert from 'node:assert/strict';
+ import { spawnSync } 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 renderer = path.resolve(__dirname, '..', 'archify', 'renderers', 'sequence', 'render-sequence.mjs');
+ const cli = path.resolve(__dirname, '..', 'archify', 'bin', 'archify.mjs');
+ // An unedited first draft with two abutting segments (140-300, 300-520). On
+ // dev the first label climbed behind the participant headers and the second
+ // climbed into the first segment, where it named the wrong phase.
+ const fixture = path.join(__dirname, 'fixtures', 'sequence-first-draft', 'scan-to-pay.sequence.json');
+ const PARTICIPANT_BOTTOM = 72 + 60;
+
++// The draft's note at y320 touches the reply label at y352. Title-placement
++// cases retain the annotation and give that reply plus later messages 12px
++// more room; the unedited draft is tested separately as a diagnostic failure.
++function spacedScanToPay() {
++ const diagram = JSON.parse(fs.readFileSync(fixture, 'utf8'));
++ for (const message of diagram.messages) if (message.y >= 352) message.y += 12;
++ diagram.segments.at(-1).to += 12;
++ return diagram;
++}
++
+ function render(diagram, publicCli = false) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'archify-sequence-segments-'));
+ const input = path.join(directory, 'candidate.json');
+ const output = path.join(directory, 'candidate.html');
+ fs.writeFileSync(input, JSON.stringify(diagram));
+ const args = publicCli ? [cli, 'render', 'sequence', input, output] : [renderer, input, output];
+ const result = spawnSync(process.execPath, args, { cwd: directory, encoding: 'utf8' });
+ return { ...result, input, html: result.status === 0 ? fs.readFileSync(output, 'utf8') : '' };
+ }
+
+ const labels = (html) => [...html.matchAll(/data-segment-id="(\d+)">\s*<rect x="([\d.]+)" y="([\d.-]+)" width="([\d.]+)" height="([\d.]+)"/g)]
+ .map((match) => ({ index: +match[1], x: +match[2], y: +match[3], width: +match[4], height: +match[5] }));
+
+ test('abutting segment labels stay in their own phase and clear of the participant headers', () => {
- const diagram = JSON.parse(fs.readFileSync(fixture, 'utf8'));
++ const diagram = spacedScanToPay();
+ const result = render(diagram);
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ const placed = labels(result.html);
+ assert.equal(placed.length, diagram.segments.length);
+ for (const label of placed) {
+ const own = diagram.segments[label.index];
+ assert.ok(label.y >= PARTICIPANT_BOTTOM, `segment ${label.index} label is behind the participant headers`);
+ for (const [index, other] of diagram.segments.entries()) {
+ if (index === label.index) continue;
+ const inside = Math.min(label.y + label.height, other.to) - Math.max(label.y, other.from);
+ assert.ok(inside <= label.height / 2, `segment ${label.index} label sits in segment ${index}`);
+ }
+ assert.ok(label.y + label.height > own.from - 24 && label.y < own.to, `segment ${label.index} label is detached from its frame`);
+ }
+ });
+
+ test('a label that fits above a spaced frame keeps its place above it', () => {
- const diagram = JSON.parse(fs.readFileSync(fixture, 'utf8'));
++ const diagram = spacedScanToPay();
+ diagram.segments = [{ from: 330, to: 520, label: 'pay' }];
+ for (const message of diagram.messages) message.y += message.y >= 300 ? 40 : 0;
+ diagram.segments[0].from = 340;
+ diagram.segments[0].to = 560;
+ const result = render(diagram);
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ const [label] = labels(result.html);
+ assert.ok(label.y + label.height <= 340, `label at ${label.y} should stay above the frame`);
+ });
+
+ // A three-phase upload whose middle phase is packed with messages: its title
+ // cannot sit on its own top border, and the next phase's title owns the strip
+ // above that phase's border.
+ const upload = path.join(__dirname, 'fixtures', 'sequence-first-draft', 'resumable-upload.sequence.json');
+
+ test('a title pushed inside its packed frame keeps clear of the next segment title', () => {
+ const diagram = JSON.parse(fs.readFileSync(upload, 'utf8'));
+ // The first draft's spacing, where the middle title used to land on "Finalize".
+ const ys = { PATCH: 300, UploadPart: 320, HEAD: 332, Complete: 364, scan: 404, clean: 436, insert: 468, 204: 500 };
+ for (const message of diagram.messages) {
+ const key = Object.keys(ys).find((prefix) => message.label.startsWith(prefix));
+ if (key) message.y = ys[key];
+ }
+ diagram.segments = [{ from: 140, to: 280, label: 'Create' }, { from: 286, to: 384, label: 'Transfer + resume' }, { from: 390, to: 540, label: 'Finalize' }];
+ const result = render(diagram);
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ const placed = labels(result.html);
+ for (let i = 0; i < placed.length; i += 1) {
+ for (let j = i + 1; j < placed.length; j += 1) {
+ const overlap = Math.min(placed[i].y + placed[i].height, placed[j].y + placed[j].height) - Math.max(placed[i].y, placed[j].y);
+ assert.ok(overlap <= 0, `segment titles ${placed[i].index} and ${placed[j].index} overlap by ${overlap}px`);
+ }
+ }
+ });
+
+ test('a segment edge running along a message arrow is reported with the move that clears it', () => {
+ const diagram = JSON.parse(fs.readFileSync(upload, 'utf8'));
+ diagram.segments[0].to = 298;
+ diagram.segments[1].from = 302;
+ const result = render(diagram);
+ assert.notEqual(result.status, 0);
+ assert.match(result.stderr + result.stdout, /Segment "Create" bottom edge at y 298 runs along message "PATCH chunk 1\.\.n" \(arrow at y 300\) — move the edge to at least 304/);
+ });
+
+ test('inside title candidates stay below low participant headers', () => {
- const diagram = JSON.parse(fs.readFileSync(fixture, 'utf8'));
++ const diagram = spacedScanToPay();
+ diagram.segments = [{ from: 120, to: 300, label: 'Phase' }];
+ const result = render(diagram);
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ assert.ok(labels(result.html)[0].y >= PARTICIPANT_BOTTOM);
+ });
+
+ test('inside segment title clears a message note after avoiding participant headers', () => {
+ const diagram = {
+ schema_version: 1, diagram_type: 'sequence',
+ meta: { title: 'Annotated phase', output: 'phase.html', quality_profile: 'showcase', viewBox: [920, 760] },
+ participants: [{ id: 'client', type: 'external', label: 'Client' }, { id: 'api', type: 'backend', label: 'API' }],
+ messages: [{ from: 'client', to: 'api', y: 160, label: 'ping', note: 'diagnostic annotation' }],
+ segments: [{ from: 120, to: 300, label: 'Processing phase title covering the annotation' }],
+ };
+ const result = render(diagram, true);
+ assert.equal(result.status, 0, result.stdout + result.stderr);
+ const [title] = labels(result.html);
+ const note = result.html.match(/<text data-detail="fine" x="([\d.]+)" y="([\d.]+)" class="t-dim" font-size="([\d.]+)">diagnostic annotation<\/text>/);
+ assert.ok(note, 'the full authored annotation remains visible');
+ assert.deepEqual(note.slice(1).map(Number), [176, 178, 7], 'note position and font remain authored geometry');
+ assert.ok(title.y >= PARTICIPANT_BOTTOM, 'title clears the participant headers');
+ assert.ok(title.x <= Number(note[1]) && title.x + title.width > Number(note[1]), 'fixture shares horizontal space with the note');
+ const baseline = Number(note[2]);
+ const font = Number(note[3]);
+ assert.ok(title.y + title.height <= baseline - font * 1.2 || title.y >= baseline + font * 0.3,
+ `title at y${title.y}..${title.y + title.height} must clear the annotation around baseline ${baseline}`);
+ });
+
+ for (const profile of ['standard', 'showcase']) {
+ test(`near-border message preserves ${profile} acceptance policy`, () => {
+ const diagram = {
+ schema_version: 1, diagram_type: 'sequence',
+ meta: { title: 'Phase boundary', output: 'phase.html', quality_profile: profile, viewBox: [920, 760] },
+ participants: [{ id: 'client', type: 'external', label: 'Client' }, { id: 'api', type: 'backend', label: 'API' }],
+ messages: [{ from: 'client', to: 'api', y: 200, label: 'ping' }],
+ segments: [{ from: 140, to: 202, label: 'Phase' }],
+ };
+ const result = render(diagram);
+ if (profile === 'standard') assert.equal(result.status, 0, result.stdout + result.stderr);
+ else {
+ assert.notEqual(result.status, 0);
+ assert.match(result.stdout + result.stderr, /bottom edge at y 202 runs along message "ping"/);
+ const validated = spawnSync(process.execPath, [cli, 'validate', 'sequence', result.input, '--json'], { encoding: 'utf8' });
+ const diagnostic = JSON.parse(validated.stdout).diagnostics.find(entry => entry.code === 'sequence/segment-message-border-run');
+ assert.equal(diagnostic.subject.path, '/segments/0/to');
+ assert.equal(diagnostic.evidence.borderY, 202);
+ assert.equal(diagnostic.evidence.messageY, 200);
+ assert.deepEqual(diagnostic.supportedFixes, [
+ 'set /segments/0/to to at least 204 to leave the message above it',
+ 'set /segments/0/to to at most 196 to leave the message below it',
+ ]);
+ }
+ });
+ }
++
++
++test('the unedited payment draft reports its note overlap with a valid spacing repair', () => {
++ const diagram = JSON.parse(fs.readFileSync(fixture, 'utf8'));
++ const rejected = render(diagram, true);
++ assert.notEqual(rejected.status, 0);
++ const validated = spawnSync(process.execPath, [cli, 'validate', 'sequence', rejected.input, '--json'], { encoding: 'utf8' });
++ const diagnostic = JSON.parse(validated.stdout).diagnostics.find(entry => entry.code === 'sequence/note-overlap');
++ assert.ok(diagnostic, validated.stdout);
++ assert.equal(diagnostic.subject.path, '/messages/5/note');
++ assert.equal(diagnostic.evidence.blocker.path, '/messages/6/y');
++ assert.equal(diagnostic.evidence.requiredY, 364);
++ assert.deepEqual(diagnostic.supportedFixes, [], 'moving only the reply would crowd the following message');
++ const repaired = render(spacedScanToPay(), true);
++ assert.equal(repaired.status, 0, repaired.stdout + repaired.stderr);
++ assert.match(repaired.html, /需验签,并按订单号幂等处理/, 'repair preserves the authored annotation');
++ diagram.meta.quality_profile = 'standard';
++ const compatible = render(diagram, true);
++ assert.equal(compatible.status, 0, compatible.stdout + compatible.stderr);
++});