diff --git a/app/lib/features/artifacts/domain/artifact_capture.dart b/app/lib/features/artifacts/domain/artifact_capture.dart new file mode 100644 index 00000000..6f081d16 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_capture.dart @@ -0,0 +1,63 @@ +import '../../../core/api_gateway.dart'; +import 'artifact_record.dart'; + +/// Whether a step actually carried an artifact list. +/// +/// An absent (or null) field means the capture is unavailable: an older step, a +/// running visit, or a reply that did not include the field. It must never be +/// reported as an empty capture. An explicitly recorded empty list is a known, +/// empty capture. +enum ArtifactCaptureAvailability { unavailable, recorded } + +/// The recorded capture facts of one step: availability, files, and how many +/// files the bounded scan excluded or omitted. Pure: it reads the step and adds +/// no server call. +class ArtifactCapture { + const ArtifactCapture._({ + required this.availability, + required this.artifacts, + required this.skipped, + required this.truncated, + }); + + factory ArtifactCapture.fromStep(JsonMap step) { + final value = step['artifacts']; + final available = step.containsKey('artifacts') && value is List; + final artifacts = available + ? [ + for (final item in value) + if (item is Map) + ArtifactRecord.fromJson(Map.from(item)), + ] + : const []; + return ArtifactCapture._( + availability: available + ? ArtifactCaptureAvailability.recorded + : ArtifactCaptureAvailability.unavailable, + artifacts: List.unmodifiable(artifacts), + skipped: _countOf(step['artifacts_skipped']), + truncated: _countOf(step['artifacts_truncated']), + ); + } + + final ArtifactCaptureAvailability availability; + + /// Every recorded file, including utility and retired files. + final List artifacts; + + /// Files excluded from the bounded per-step scan. + final int skipped; + + /// Files omitted by the capture's total budget. + final int truncated; + + bool get isAvailable => availability == ArtifactCaptureAvailability.recorded; + + bool get isPartial => skipped > 0 || truncated > 0; + + static int _countOf(dynamic value) { + if (value is num) return value.toInt(); + if (value is String) return int.tryParse(value.trim()) ?? 0; + return 0; + } +} diff --git a/app/lib/features/artifacts/domain/artifact_groups.dart b/app/lib/features/artifacts/domain/artifact_groups.dart new file mode 100644 index 00000000..bfa0707e --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_groups.dart @@ -0,0 +1,109 @@ +import '../../../core/api_gateway.dart'; +import '../../graph/domain/stage_visits.dart'; +import 'artifact_record.dart'; +import 'artifact_selection.dart'; + +/// One gallery group: the stage-produced artifacts of a recorded stage visit. +class ArtifactGroup { + const ArtifactGroup({ + required this.stageKey, + required this.visit, + required this.artifacts, + }); + + final String stageKey; + + /// The display visit number: `control.visit` when positive, else the position + /// within the stage's ordered visits. Never a synthetic visit. + final int visit; + + final List artifacts; +} + +int _sequenceOf(JsonMap step) { + final sequence = step['sequence']; + return sequence is num ? sequence.toInt() : 0; +} + +/// Sequence order with recorded order as the tie-break, matching the web +/// client's stable sort. +List _orderedBySequence(List steps) { + final indexed = <({int position, JsonMap step})>[ + for (var index = 0; index < steps.length; index += 1) + (position: index, step: steps[index]), + ]; + indexed.sort((a, b) { + final bySequence = _sequenceOf(a.step).compareTo(_sequenceOf(b.step)); + return bySequence != 0 ? bySequence : a.position.compareTo(b.position); + }); + return [for (final entry in indexed) entry.step]; +} + +/// Groups a run's stage artifacts by stage and recorded visit. +/// +/// Stages keep first-appearance order and each stage's visits are ordered by +/// sequence. A shared `public/` file is attributed to the visit that first +/// recorded it, because the server records the whole public directory on every +/// model visit. Only visits with at least one presented stage artifact produce a +/// group, so an unavailable or empty capture never yields an empty group. An +/// artifact-less run yields an empty list rather than a fabricated stage. +List artifactGroups(List steps) { + if (steps.isEmpty) return const []; + + final attributed = >{}; + final seenPublic = {}; + for (final recordedStep in _orderedBySequence(steps)) { + final repairs = repairArtifactNames(recordedStep); + final kept = []; + for (final artifact in stageArtifactsFrom( + artifactsOf(recordedStep), + repairs: repairs, + )) { + if (artifact.isPublicName) { + if (seenPublic.contains(artifact.name)) continue; + seenPublic.add(artifact.name); + } + kept.add(artifact); + } + attributed[recordedStep] = List.unmodifiable(kept); + } + + final groups = []; + for (final entry in visitsByStage(steps).entries) { + final visits = entry.value; + for (var index = 0; index < visits.length; index += 1) { + final artifacts = attributed[visits[index]]; + if (artifacts == null || artifacts.isEmpty) continue; + groups.add( + ArtifactGroup( + stageKey: entry.key, + visit: displayVisit(visits[index], index), + artifacts: artifacts, + ), + ); + } + } + return List.unmodifiable(groups); +} + +/// One visit's stage artifacts, excluding shared public files that an earlier +/// visit already recorded. A repeated non-public name in a later visit stays +/// because it is a different recorded artifact, not the same shared file. +List visitArtifacts(JsonMap step, List runSteps) { + final all = stageArtifacts(step); + if (runSteps.isEmpty) return all; + final seen = {}; + for (final candidate in _orderedBySequence(runSteps)) { + if (identical(candidate, step) || + _sequenceOf(candidate) == _sequenceOf(step)) { + break; + } + for (final artifact in stageArtifacts(candidate)) { + if (artifact.isPublicName) seen.add(artifact.name); + } + } + return [ + for (final artifact in all) + if (!artifact.isPublicName || !seen.contains(artifact.name)) artifact, + ]; +} diff --git a/app/lib/features/artifacts/domain/artifact_kind.dart b/app/lib/features/artifacts/domain/artifact_kind.dart new file mode 100644 index 00000000..7bac7708 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_kind.dart @@ -0,0 +1,225 @@ +/// What an artifact is from the gallery's point of view: the two media kinds it +/// previews and the file kinds it labels with a type word. Mirrors the web +/// client's `ArtifactKind` vocabulary. +enum ArtifactKind { + image, + video, + audio, + pdf, + json, + archive, + spreadsheet, + log, + code, + document, + other, +} + +const Set _archiveExtensions = { + 'zip', + 'tar', + 'gz', + 'tgz', + 'bz2', + 'xz', + 'rar', + '7z', + 'jar', + 'war', +}; + +const Set _archiveMimes = { + 'application/zip', + 'application/gzip', + 'application/x-tar', + 'application/x-7z-compressed', + 'application/x-rar-compressed', + 'application/java-archive', +}; + +const Set _spreadsheetExtensions = { + 'csv', + 'tsv', + 'xls', + 'xlsx', + 'ods', +}; + +const Set _spreadsheetMimes = { + 'text/csv', + 'text/tab-separated-values', + 'application/vnd.ms-excel', + 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', +}; + +const Set _codeExtensions = { + 'kt', + 'kts', + 'java', + 'go', + 'py', + 'rb', + 'php', + 'rs', + 'c', + 'h', + 'cc', + 'cpp', + 'hpp', + 'cs', + 'js', + 'jsx', + 'ts', + 'tsx', + 'mjs', + 'cjs', + 'swift', + 'scala', + 'sh', + 'bash', + 'zsh', + 'fish', + 'ps1', + 'sql', + 'yaml', + 'yml', + 'toml', + 'ini', + 'xml', + 'gradle', + 'properties', + 'proto', +}; + +const Set _codeMimes = { + 'application/xml', + 'application/x-yaml', + 'application/javascript', + 'text/javascript', + 'text/x-python', + 'text/x-java-source', + 'text/x-kotlin', + 'application/x-sh', + 'application/x-httpd-php', + 'application/sql', +}; + +const Set _documentExtensions = { + 'txt', + 'md', + 'markdown', + 'rst', + 'doc', + 'docx', + 'odt', + 'rtf', + 'html', + 'htm', +}; + +const Set _markdownExtensions = {'md', 'markdown', 'txt'}; + +const Set _documentMimes = { + 'application/msword', + 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', + 'application/rtf', +}; + +const Map _kindLabels = { + ArtifactKind.image: 'Image', + ArtifactKind.video: 'Video', + ArtifactKind.audio: 'Audio', + ArtifactKind.pdf: 'PDF', + ArtifactKind.json: 'JSON', + ArtifactKind.archive: 'Archive', + ArtifactKind.spreadsheet: 'Spreadsheet', + ArtifactKind.log: 'Log', + ArtifactKind.code: 'Code', + ArtifactKind.document: 'Document', + ArtifactKind.other: 'File', +}; + +/// Whether a recorded content type is an image the gallery previews. +bool isImageContentType(String contentType) => contentType.startsWith('image/'); + +/// Whether a recorded content type is a video; videos get a poster tile and are +/// never decoded inline or autoplayed. +bool isVideoContentType(String contentType) => contentType.startsWith('video/'); + +/// The lowercased extension of [name], or '' when it carries none. +String _extensionOf(String name) { + final dot = name.lastIndexOf('.'); + return dot == -1 ? '' : name.substring(dot + 1).toLowerCase(); +} + +/// The gallery kind for a recorded content type and name. +/// +/// Image and video come straight from the content type; the other kinds match +/// the normalised MIME first, then the name's extension. Pure and total: an +/// unknown type is [ArtifactKind.other], never a guess that changes an action. +ArtifactKind artifactKind(String contentType, String name) { + if (isImageContentType(contentType)) return ArtifactKind.image; + if (isVideoContentType(contentType)) return ArtifactKind.video; + final mime = contentType.split(';').first.trim().toLowerCase(); + final ext = _extensionOf(name); + if (mime.startsWith('audio/')) return ArtifactKind.audio; + if (mime == 'application/pdf' || ext == 'pdf') return ArtifactKind.pdf; + if (mime.contains('json') || ext == 'json') return ArtifactKind.json; + if (_archiveMimes.contains(mime) || _archiveExtensions.contains(ext)) { + return ArtifactKind.archive; + } + if (_spreadsheetMimes.contains(mime) || + _spreadsheetExtensions.contains(ext)) { + return ArtifactKind.spreadsheet; + } + if (ext == 'log') return ArtifactKind.log; + if (mime == 'text/html') return ArtifactKind.document; + if (_codeMimes.contains(mime) || _codeExtensions.contains(ext)) { + return ArtifactKind.code; + } + if (mime.startsWith('text/') || + _documentMimes.contains(mime) || + _documentExtensions.contains(ext)) { + return ArtifactKind.document; + } + return ArtifactKind.other; +} + +/// The prose word naming [kind], so a type glyph never has to be read alone. +String artifactKindLabel(ArtifactKind kind) => _kindLabels[kind] ?? 'File'; + +/// Whether an artifact is text the viewer can render as markdown: `text/markdown` +/// or `text/plain` (parameters ignored), or an md/markdown/txt name. +bool isMarkdownArtifact(String contentType, String name) { + final mime = contentType.split(';').first.trim().toLowerCase(); + if (mime == 'text/markdown' || mime == 'text/plain') return true; + return _markdownExtensions.contains(_extensionOf(name)); +} + +/// Whether an artifact opens inside the full-screen viewer: images, videos, and +/// markdown/text documents. A `text/plain` log, source file or spreadsheet stays +/// an external file because those are evidence, not prose. +bool isViewerArtifact(String contentType, String name) { + if (isImageContentType(contentType) || isVideoContentType(contentType)) { + return true; + } + return artifactKind(contentType, name) == ArtifactKind.document && + isMarkdownArtifact(contentType, name); +} + +/// Human-readable byte size, matching the web client: whole bytes under 1 KiB, +/// otherwise one decimal with a binary unit (KiB/MiB/GiB/TiB/PiB/EiB). +String humanBytes(num size) { + final value = size.truncate(); + const unit = 1024; + if (value < unit) return '$value B'; + var div = unit; + var exp = 0; + var scaled = value ~/ unit; + while (scaled >= unit) { + div *= unit; + exp++; + scaled ~/= unit; + } + return '${(value / div).toStringAsFixed(1)} ${'KMGTPE'[exp]}iB'; +} diff --git a/app/lib/features/artifacts/domain/artifact_record.dart b/app/lib/features/artifacts/domain/artifact_record.dart new file mode 100644 index 00000000..6c6bc845 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_record.dart @@ -0,0 +1,85 @@ +import '../../../core/api_gateway.dart'; + +/// The retired markdown session export file name. Nothing writes it any more, +/// but a run recorded before the HTML-only change still lists `session.md`: it +/// is dated evidence that is never presented beside `session.html`. +const String legacySessionMarkdownArtifact = 'session.md'; + +/// The files the turn protocol itself writes for every visit. They are audit +/// evidence, not stage output, so the artifact gallery lists stage files first +/// and keeps these for an audit/debug surface. +const List systemArtifactNames = [ + 'input.md', + 'memory.md', + 'output.md', + 'session.html', +]; + +/// One recorded artifact of a stage visit. +/// +/// The server is the authority: [name], [url], [contentType] and [sizeBytes] +/// are read verbatim and every other field is kept in [raw]. A record is never +/// inferred or completed locally; a missing url stays empty rather than being +/// fabricated from the name. Two records with the same name stay distinct +/// because only the recorded url identifies an artifact. +class ArtifactRecord { + const ArtifactRecord({ + required this.name, + required this.url, + required this.contentType, + required this.sizeBytes, + required this.raw, + }); + + factory ArtifactRecord.fromJson(JsonMap json) { + final raw = _frozenMap(json); + return ArtifactRecord( + name: _text(raw['name']), + url: _text(raw['url']), + contentType: _text(raw['content_type']), + sizeBytes: _intOf(raw['size_bytes']), + raw: raw, + ); + } + + /// The recorded file name, including any `public/` prefix. + final String name; + + /// The recorded artifact url exactly as the server sent it. + final String url; + + /// The server-sniffed content type, possibly with parameters. + final String contentType; + + /// The recorded byte size; 0 when the server recorded none. + final int sizeBytes; + + /// Every field the server sent, including fields this slice does not model. + /// Deeply unmodifiable, so a view cannot mutate the server reply. + final JsonMap raw; + + bool get hasUrl => url.trim().isNotEmpty; + bool get isLegacySessionMarkdown => name == legacySessionMarkdownArtifact; + bool get isSystem => isSystemArtifactName(name); + bool get isPublicName => name.startsWith('public/'); + + static String _text(dynamic value) => value == null ? '' : '$value'; + + static int _intOf(dynamic value) { + if (value is num) return value.toInt(); + if (value is String) return int.tryParse(value.trim()) ?? 0; + return 0; + } + + static JsonMap _frozenMap(JsonMap json) => Map.unmodifiable( + json.map((key, value) => MapEntry(key, _frozen(value))), + ); + + static dynamic _frozen(dynamic value) { + if (value is Map) return _frozenMap(Map.from(value)); + if (value is List) return List.unmodifiable(value.map(_frozen)); + return value; + } +} + +bool isSystemArtifactName(String name) => systemArtifactNames.contains(name); diff --git a/app/lib/features/artifacts/domain/artifact_selection.dart b/app/lib/features/artifacts/domain/artifact_selection.dart new file mode 100644 index 00000000..4f976473 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_selection.dart @@ -0,0 +1,67 @@ +import '../../../core/api_gateway.dart'; +import 'artifact_record.dart'; + +/// Parses one step's recorded artifact list. An absent, null or malformed list +/// yields no records; the capture state (and its unavailable wording) is +/// reported by `artifact_capture.dart`, never treated as an empty capture here. +List artifactsOf(JsonMap step) { + final value = step['artifacts']; + if (value is! List) return const []; + return [ + for (final item in value) + if (item is Map) ArtifactRecord.fromJson(Map.from(item)), + ]; +} + +/// The html names a visit's session-export repairs produced. +Set repairArtifactNames(JsonMap step) { + final value = step['session_export_repairs']; + if (value is! List) return const {}; + return { + for (final entry in value) + if (entry is Map && + entry['html'] is String && + '${entry['html']}'.trim().isNotEmpty) + '${entry['html']}', + }; +} + +/// The artifacts of one visit as presented: the recorded files with the retired +/// markdown session export filtered out. Duplicate names are kept because an +/// artifact's identity is its recorded url, not its name. +List presentedArtifacts(Iterable artifacts) { + return [ + for (final artifact in artifacts) + if (!artifact.isLegacySessionMarkdown) artifact, + ]; +} + +/// A visit's stage-produced artifacts: everything except the turn-owned files +/// and repaired session exports. Order is preserved. +List stageArtifactsFrom( + Iterable artifacts, { + Set repairs = const {}, +}) { + return [ + for (final artifact in presentedArtifacts(artifacts)) + if (!artifact.isSystem && !repairs.contains(artifact.name)) artifact, + ]; +} + +/// A visit's system files and repaired exports, in recorded order. +List systemArtifactsFrom( + Iterable artifacts, { + Set repairs = const {}, +}) { + return [ + for (final artifact in presentedArtifacts(artifacts)) + if (artifact.isSystem || repairs.contains(artifact.name)) artifact, + ]; +} + +/// Convenience for callers holding a raw step rather than parsed records. +List stageArtifacts(JsonMap step) => + stageArtifactsFrom(artifactsOf(step), repairs: repairArtifactNames(step)); + +List systemArtifacts(JsonMap step) => + systemArtifactsFrom(artifactsOf(step), repairs: repairArtifactNames(step)); diff --git a/app/lib/features/artifacts/domain/artifact_summary.dart b/app/lib/features/artifacts/domain/artifact_summary.dart new file mode 100644 index 00000000..44161a86 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_summary.dart @@ -0,0 +1,78 @@ +import '../../../core/api_gateway.dart'; +import 'artifact_capture.dart'; +import 'artifact_groups.dart'; +import 'artifact_selection.dart'; + +/// The "capture pending" wording shared by a running visit's summary and the +/// run-level empty state, so the two never spell it differently. +const String artifactCapturePending = 'capture pending'; + +/// The explicit message shown where the run's gallery would be when there are +/// no recorded artifacts. A running run says capture pending; a finished run +/// with available captures says plainly that nothing was recorded. +String artifactsEmptyMessage(bool executing) => executing + ? 'Artifacts · $artifactCapturePending' + : 'No artifacts recorded for this run.'; + +/// The run summary's Artifacts section header. +/// +/// The recorded count is exactly the number of tiles [artifactGroups] yields; +/// the title takes its singular form for one. A run whose capture is unavailable +/// says so instead of claiming that nothing was recorded. Partial capture is +/// flagged when any visit excluded or omitted files. +String artifactsHeader(List steps, {required bool executing}) { + final recorded = artifactGroups( + steps, + ).fold(0, (sum, group) => sum + group.artifacts.length); + if (recorded == 0) { + if (executing) return artifactsEmptyMessage(true); + final unavailable = steps.any( + (step) => !ArtifactCapture.fromStep(step).isAvailable, + ); + return unavailable + ? 'Artifacts · capture unavailable' + : artifactsEmptyMessage(false); + } + final partial = steps.any((step) => ArtifactCapture.fromStep(step).isPartial); + var label = + '${recorded == 1 ? 'Artifact' : 'Artifacts'} · $recorded recorded'; + if (partial) label += ' · partial capture'; + return label; +} + +/// The per-visit artifacts label. +/// +/// A running visit says capture pending. A finished visit whose capture field was +/// absent says capture unavailable rather than "not recorded"; only an explicitly +/// empty capture says "not recorded for this visit". Recorded counts exclude the +/// turn-owned files and the retired session markdown, so the words match tiles. +String artifactsSummary(JsonMap step, {int? count}) { + final capture = ArtifactCapture.fromStep(step); + final recorded = count ?? stageArtifacts(step).length; + if (recorded == 0) { + if (step['status'] == 'running') { + return 'Artifacts · $artifactCapturePending'; + } + if (!capture.isAvailable) return 'Artifacts · capture unavailable'; + return 'Artifacts · not recorded for this visit'; + } + var label = 'Artifacts · $recorded recorded'; + if (capture.isPartial) label += ' · partial capture'; + return label; +} + +/// The partial-capture notes, one line per non-zero count and nothing when the +/// capture was complete or had no presented files. An unavailable capture yields +/// no notes because there is no evidence to quantify. +List artifactCaptureNotes(JsonMap step) { + final notes = []; + if (presentedArtifacts(artifactsOf(step)).isEmpty) return notes; + final capture = ArtifactCapture.fromStep(step); + if (capture.skipped > 0) { + notes.add('${capture.skipped} files excluded from artifact capture.'); + } + if (capture.truncated > 0) { + notes.add('${capture.truncated} files omitted by artifact capture limits.'); + } + return notes; +} diff --git a/app/lib/features/artifacts/domain/artifact_url.dart b/app/lib/features/artifacts/domain/artifact_url.dart new file mode 100644 index 00000000..ea16d505 --- /dev/null +++ b/app/lib/features/artifacts/domain/artifact_url.dart @@ -0,0 +1,78 @@ +import '../../../core/transport/server_url.dart'; + +/// A validated artifact url plus whether it points outside the configured +/// server origin. +class ResolvedArtifactUrl { + const ResolvedArtifactUrl({required this.uri, required this.external}); + + final Uri uri; + + /// True when the url's origin differs from the configured server origin (or + /// the configured origin is unusable). A future authenticated fetch must send + /// no cookies, authorization header or other server credentials for an + /// external url. + final bool external; + + String get url => uri.toString(); +} + +const List _unsafePrefixes = ['//', r'\\', r'\/', '/\\']; + +/// Resolves a recorded artifact url for display and opening. +/// +/// A server-relative path (`/artifacts/...`, or a path without the leading +/// slash) resolves against the configured websocket endpoint's http(s) origin, +/// dropping the endpoint path and query. An absolute http(s) url is preserved, +/// including its encoded path and query. Output is always http(s): protocol- +/// relative (`//host`), hostless, credentialed, malformed and non-http(s) urls +/// are rejected with null. A blank or invalid configured endpoint resolves no +/// relative path; it never invents a host. +ResolvedArtifactUrl? resolveArtifactUrl( + String configuredEndpoint, + String artifactUrl, +) { + final raw = artifactUrl.trim(); + if (raw.isEmpty) return null; + for (final prefix in _unsafePrefixes) { + if (raw.startsWith(prefix)) return null; + } + final parsed = Uri.tryParse(raw); + if (parsed == null) return null; + + final configured = _httpOrigin(configuredEndpoint); + if (parsed.hasScheme) { + final scheme = parsed.scheme.toLowerCase(); + if (scheme != 'http' && scheme != 'https') return null; + if (!parsed.hasAuthority || parsed.host.isEmpty) return null; + if (parsed.userInfo.isNotEmpty) return null; + return ResolvedArtifactUrl( + uri: parsed, + external: configured == null || parsed.origin != configured.origin, + ); + } + + if (configured == null) return null; + final relative = raw.startsWith('/') ? raw : '/$raw'; + final resolved = Uri.tryParse('${configured.origin}$relative'); + if (resolved == null) return null; + final scheme = resolved.scheme.toLowerCase(); + if (scheme != 'http' && scheme != 'https') return null; + if (!resolved.hasAuthority || resolved.host.isEmpty) return null; + if (resolved.userInfo.isNotEmpty) return null; + return ResolvedArtifactUrl(uri: resolved, external: false); +} + +/// The http(s) origin of a configured websocket endpoint, or null when the +/// endpoint is blank, malformed, or not a ws/wss url. +Uri? _httpOrigin(String configuredEndpoint) { + try { + final endpoint = ServerUrl.validate(configuredEndpoint); + final http = Uri.parse(endpoint.httpUrl); + final scheme = http.scheme.toLowerCase(); + if (scheme != 'http' && scheme != 'https') return null; + if (http.host.isEmpty) return null; + return Uri.parse(http.origin); + } on FormatException { + return null; + } +} diff --git a/app/lib/features/artifacts/domain/gallery_navigation.dart b/app/lib/features/artifacts/domain/gallery_navigation.dart new file mode 100644 index 00000000..ca115a73 --- /dev/null +++ b/app/lib/features/artifacts/domain/gallery_navigation.dart @@ -0,0 +1,76 @@ +import 'artifact_groups.dart'; +import 'artifact_kind.dart'; +import 'artifact_record.dart'; + +/// One artifact in the viewer's filtered page list, with the stage visit it +/// belongs to. [identity] is the recorded url when there is one; otherwise it is +/// a visit-scoped key so two url-less records never collapse into one page. +class PagedArtifact { + const PagedArtifact({ + required this.stageKey, + required this.visit, + required this.artifact, + required this.pageIndex, + }); + + final String stageKey; + final int visit; + final ArtifactRecord artifact; + + /// Position in the filtered page list. + final int pageIndex; + + String get identity => artifact.hasUrl + ? artifact.url + : '$stageKey\u0000$visit\u0000$pageIndex\u0000${artifact.name}'; +} + +/// The artifacts the viewer can page through, in gallery order: group by group, +/// each group's images, videos and markdown/text documents in recorded order. +/// Other artifacts open externally and are not part of this list. Pure: it only +/// filters and orders records the gallery already holds. +List pagedArtifacts(List groups) { + final pages = []; + for (final group in groups) { + for (final artifact in group.artifacts) { + if (!isViewerArtifact(artifact.contentType, artifact.name)) continue; + pages.add( + PagedArtifact( + stageKey: group.stageKey, + visit: group.visit, + artifact: artifact, + pageIndex: pages.length, + ), + ); + } + } + return List.unmodifiable(pages); +} + +/// Each page's recorded url mapped to its page index, so a tile and the viewer +/// derive from the same ordered list. The first occurrence of a url wins. A +/// record with no recorded url has no fetchable identity and is omitted. +Map viewerIndexByUrl(List groups) { + final indices = {}; + for (final page in pagedArtifacts(groups)) { + if (!page.artifact.hasUrl) continue; + indices.putIfAbsent(page.artifact.url, () => page.pageIndex); + } + return indices; +} + +/// Paging from [current] by [delta] within `count` pages, clamped at both ends +/// so a page never wraps and an empty list is index 0. +int pagedIndex(int current, int delta, int count) { + if (count <= 0) return 0; + final wanted = current + delta; + if (wanted < 0) return 0; + if (wanted >= count) return count - 1; + return wanted; +} + +/// The viewer's position label, e.g. `2 of 5 · image/png`. +String artifactViewerPositionLabel(int index, int count, String contentType) { + final type = contentType.split(';').first.trim(); + return '${index + 1} of $count · ${type.isEmpty ? 'artifact' : type}'; +} diff --git a/app/lib/features/graph/routing/corridor_plan.dart b/app/lib/features/graph/routing/corridor_plan.dart new file mode 100644 index 00000000..33909013 --- /dev/null +++ b/app/lib/features/graph/routing/corridor_plan.dart @@ -0,0 +1,105 @@ +import 'dart:math' as math; + +import '../layout/layout_models.dart'; +import 'route_geometry.dart'; +import 'route_models.dart'; + +/// One vertical-corridor request from a wrapping route. +/// +/// A route needs a track right of its source and a track beside its target; +/// both gaps are 0-based column gaps (`rankCount` is the right free gap). +class CorridorRequest { + const CorridorRequest({ + required this.edgeId, + required this.sourceGap, + required this.targetGap, + }); + + final int edgeId; + final int sourceGap; + final int targetGap; +} + +/// Assigned x coordinates for every wrapping route's two vertical tracks. +class CorridorPlan { + CorridorPlan({ + required Map sourceX, + required Map targetX, + }) : sourceX = Map.unmodifiable(sourceX), + targetX = Map.unmodifiable(targetX); + + final Map sourceX; + final Map targetX; +} + +/// Spreads corridor requests across the free band of each column gap. +/// +/// Requests keep edge-id order, so equal input yields equal coordinates. Tracks +/// are distinct inside a gap; a narrow gap compresses the spacing instead of +/// pushing a corridor into a node column. +CorridorPlan planCorridors({ + required GraphLayout layout, + required List requests, + required RoutingConfig config, +}) { + final ordered = [...requests] + ..sort((a, b) => a.edgeId.compareTo(b.edgeId)); + final slots = >{}; + for (final request in ordered) { + slots + .putIfAbsent(request.sourceGap, () => <_Slot>[]) + .add(_Slot(request.edgeId, source: true)); + slots + .putIfAbsent(request.targetGap, () => <_Slot>[]) + .add(_Slot(request.edgeId, source: false)); + } + + final gaps = ColumnGaps( + nodes: layout.nodes, + rankCount: layout.rankCount, + layoutWidth: layout.width, + ); + final sourceX = {}; + final targetX = {}; + final gapKeys = slots.keys.toList()..sort(); + for (final gapKey in gapKeys) { + final gapSlots = slots[gapKey]!; + final band = gaps.band(gapKey, config.nodeClearance); + final positions = _trackPositions( + band, + gapSlots.length, + config.corridorSpacing, + ); + for (var index = 0; index < gapSlots.length; index += 1) { + if (gapSlots[index].source) { + sourceX[gapSlots[index].edgeId] = positions[index]; + } else { + targetX[gapSlots[index].edgeId] = positions[index]; + } + } + } + return CorridorPlan(sourceX: sourceX, targetX: targetX); +} + +List _trackPositions(GapBand band, int count, double spacing) { + if (count == 0) return const []; + if (band.open) { + return [ + for (var index = 0; index < count; index += 1) band.lo + spacing * index, + ]; + } + final width = band.hi - band.lo; + if (count == 1) return [(band.lo + band.hi) / 2]; + if (width <= 0) return List.filled(count, band.lo); + final step = math.min(spacing, width / (count - 1)); + return [ + for (var index = 0; index < count; index += 1) band.lo + step * index, + ]; +} + +class _Slot { + const _Slot(this.edgeId, {required this.source}); + + final int edgeId; + final bool source; +} diff --git a/app/lib/features/graph/routing/edge_label_placement.dart b/app/lib/features/graph/routing/edge_label_placement.dart new file mode 100644 index 00000000..75264135 --- /dev/null +++ b/app/lib/features/graph/routing/edge_label_placement.dart @@ -0,0 +1,175 @@ +import 'dart:math' as math; + +import '../layout/layout_models.dart'; +import 'route_geometry.dart'; +import 'route_models.dart'; + +/// Places one measured edge label without overlapping a node or another label. +/// +/// Candidates are tried in a deterministic order: the midpoint of each +/// horizontal run (above, then below), then each vertical run (right, then +/// left), sliding along the run before giving up. A run too narrow for the +/// box pushes the label to a free shelf below the drawing, which expands the +/// routing bounds instead of covering a node. +EdgeLabelBox placeEdgeLabel({ + required EdgeRoute route, + required LabelExtent extent, + required List nodes, + required List placed, + required RoutingConfig config, + required double floorY, +}) { + final width = extent.width; + final height = extent.height; + for (final candidate in _candidates(route, width, height, config.labelGap)) { + final box = EdgeLabelBox( + edgeId: route.id, + x: candidate.x, + y: candidate.y, + width: width, + height: height, + ); + if (_fits(box, nodes, placed, config)) return box; + } + + // The fallback shelf is below every route and every existing label, so it + // cannot cover a node. Growing it down expands the returned bounds. + var top = math.max( + floorY, + placed.fold(0, (bottom, box) => math.max(bottom, box.bottom)), + ); + top += config.labelGap; + final centre = _routeCentreX(route); + final step = math.max(height + config.labelGap, 1.0); + for (var attempt = 0; attempt < 100000; attempt += 1) { + final x = math.max(0.0, centre - width / 2); + final box = EdgeLabelBox( + edgeId: route.id, + x: x, + y: top, + width: width, + height: height, + ); + if (_fits(box, nodes, placed, config)) return box; + top += step; + } + // A zero-sized label cannot collide; this is unreachable for real extents. + return EdgeLabelBox( + edgeId: route.id, + x: math.max(0.0, centre - width / 2), + y: top, + width: width, + height: height, + ); +} + +bool _fits( + EdgeLabelBox box, + List nodes, + List placed, + RoutingConfig config, +) { + if (box.x < 0 || box.y < 0) return false; + for (final node in nodes) { + if (boxIntersectsNode( + x: box.x, + y: box.y, + width: box.width, + height: box.height, + node: node, + gap: config.labelGap, + )) { + return false; + } + } + for (final other in placed) { + if (boxesOverlap( + ax: box.x, + ay: box.y, + aw: box.width, + ah: box.height, + bx: other.x, + by: other.y, + bw: other.width, + bh: other.height, + gap: config.labelGap, + )) { + return false; + } + } + return true; +} + +List<_LabelCandidate> _candidates( + EdgeRoute route, + double width, + double height, + double gap, +) { + const fractions = [0.5, 0.35, 0.65, 0.2, 0.8, 0.08, 0.92]; + final horizontals = <_Run>[]; + final verticals = <_Run>[]; + for (var index = 1; index < route.points.length; index += 1) { + final a = route.points[index - 1]; + final b = route.points[index]; + if (a.y == b.y) { + horizontals.add(_Run(a, b, (b.x - a.x).abs(), index)); + } else if (a.x == b.x) { + verticals.add(_Run(a, b, (b.y - a.y).abs(), index)); + } + } + horizontals.sort((a, b) { + final length = b.length.compareTo(a.length); + return length != 0 ? length : a.order.compareTo(b.order); + }); + verticals.sort((a, b) { + final length = b.length.compareTo(a.length); + return length != 0 ? length : a.order.compareTo(b.order); + }); + + final candidates = <_LabelCandidate>[]; + for (final run in horizontals) { + for (final fraction in fractions) { + final x = run.a.x + (run.b.x - run.a.x) * fraction; + final left = x - width / 2; + candidates.add(_LabelCandidate(left, run.a.y - gap - height)); + candidates.add(_LabelCandidate(left, run.a.y + gap)); + } + } + for (final run in verticals) { + for (final fraction in fractions) { + final y = run.a.y + (run.b.y - run.a.y) * fraction; + final top = y - height / 2; + candidates.add(_LabelCandidate(run.a.x + gap, top)); + candidates.add(_LabelCandidate(run.a.x - gap - width, top)); + } + } + return candidates; +} + +double _routeCentreX(EdgeRoute route) { + if (route.points.isEmpty) return 0; + var lo = route.points.first.x; + var hi = lo; + for (final point in route.points) { + lo = math.min(lo, point.x); + hi = math.max(hi, point.x); + } + return (lo + hi) / 2; +} + +class _Run { + const _Run(this.a, this.b, this.length, this.order); + + final RoutePoint a; + final RoutePoint b; + final double length; + final int order; +} + +class _LabelCandidate { + const _LabelCandidate(this.x, this.y); + + final double x; + final double y; +} diff --git a/app/lib/features/graph/routing/edge_route_planner.dart b/app/lib/features/graph/routing/edge_route_planner.dart new file mode 100644 index 00000000..8b3d6ff4 --- /dev/null +++ b/app/lib/features/graph/routing/edge_route_planner.dart @@ -0,0 +1,265 @@ +import 'dart:math' as math; + +import '../domain/graph_definition.dart'; +import '../layout/layout_models.dart'; +import 'corridor_plan.dart'; +import 'route_geometry.dart'; +import 'route_models.dart'; + +/// One routed edge before labels and bounds are assembled. +/// +/// Internal to the routing library: callers receive the immutable public +/// [EdgeRoute] instead. +class PlannedEdgeRoute { + PlannedEdgeRoute({ + required this.edge, + required this.kind, + required this.straight, + required this.sourcePort, + required this.targetPort, + required List points, + }) : points = List.unmodifiable(points); + + final GraphEdge edge; + final RouteKind kind; + final bool straight; + final RoutePort sourcePort; + final RoutePort targetPort; + final List points; + + EdgeRoute toRoute() => EdgeRoute( + id: edge.id, + source: edge.source, + outcome: edge.outcome, + target: edge.target, + label: edge.label, + fallback: edge.fallback, + kind: kind, + straight: straight, + sourcePort: sourcePort, + targetPort: targetPort, + points: points, + ); +} + +/// Plans orthogonal polylines for every edge whose endpoints have placed boxes. +/// +/// [edges] must already be filtered to known endpoints and sorted by id. The +/// plan is deterministic: forward one-rank routes take a straight horizontal +/// run when the measured boxes and labels leave room, and every other route +/// gets a unique lane below the node grid plus vertical corridors inside the +/// column gaps. Corridors and lanes never enter a node column. +/// +/// All horizontal stubs share one [AxisTrackAllocator], so two different edges +/// cannot occupy the same run in a column gap even when they touch different +/// nodes on the same row. +List planEdgeRoutes({ + required GraphLayout layout, + required List edges, + required double maxLabelHeight, + required RoutingConfig config, +}) { + if (edges.isEmpty) return const []; + final nodes = { + for (final node in layout.nodes) node.key: node, + }; + final kinds = {}; + for (final edge in edges) { + final source = nodes[edge.source]!; + final target = nodes[edge.target]!; + kinds[edge.id] = _kindFor(edge, source, target, layout); + } + + final trackSpacing = math.max( + config.portSpacing, + maxLabelHeight + config.labelGap, + ); + final runs = AxisTrackAllocator(trackSpacing); + final straightY = {}; + for (final edge in edges) { + if (kinds[edge.id] != RouteKind.forward) continue; + final source = nodes[edge.source]!; + final target = nodes[edge.target]!; + if (target.rank != source.rank + 1) continue; + if (target.x <= source.right) continue; + final sourceInset = portInset(source, config.portSpacing); + final targetInset = portInset(target, config.portSpacing); + final lo = math.max(source.y + sourceInset, target.y + targetInset); + final hi = math.min( + source.bottom - sourceInset, + target.bottom - targetInset, + ); + if (hi <= lo) continue; + final y = runs.allocate( + desired: (lo + hi) / 2, + min: lo, + max: hi, + spanLo: source.right, + spanHi: target.x, + ); + if (y != null) straightY[edge.id] = y; + } + + final laneStep = math.max( + config.laneSpacing, + maxLabelHeight + config.labelGap, + ); + final contentBottom = layout.nodes.fold( + 0, + (bottom, node) => math.max(bottom, node.bottom), + ); + final wrapPlans = <_WrapPlan>[]; + final corridorRequests = []; + var laneIndex = 0; + for (final edge in edges) { + if (straightY.containsKey(edge.id)) continue; + final source = nodes[edge.source]!; + final target = nodes[edge.target]!; + final kind = kinds[edge.id]!; + final laneY = + contentBottom + config.nodeClearance + laneStep * (laneIndex + 1); + laneIndex += 1; + final sourceGap = (source.rank + 1).clamp(0, layout.rankCount); + final targetGap = kind == RouteKind.forward + ? target.rank.clamp(0, layout.rankCount) + : (target.rank + 1).clamp(0, layout.rankCount); + corridorRequests.add( + CorridorRequest( + edgeId: edge.id, + sourceGap: sourceGap, + targetGap: targetGap, + ), + ); + wrapPlans.add(_WrapPlan(edge: edge, kind: kind, laneY: laneY)); + } + + final corridors = planCorridors( + layout: layout, + requests: corridorRequests, + config: config, + ); + final sourceTrackX = corridors.sourceX; + final targetTrackX = corridors.targetX; + + final sourcePorts = {}; + final targetPorts = {}; + for (final edge in edges) { + final y = straightY[edge.id]; + if (y == null) continue; + final source = nodes[edge.source]!; + final target = nodes[edge.target]!; + sourcePorts[edge.id] = RoutePort( + side: RoutePortSide.right, + point: RoutePoint(source.right, y), + ); + targetPorts[edge.id] = RoutePort( + side: RoutePortSide.left, + point: RoutePoint(target.x, y), + ); + } + for (final plan in wrapPlans) { + final edge = plan.edge; + final source = nodes[edge.source]!; + final target = nodes[edge.target]!; + final sourceTrack = sourceTrackX[edge.id]!; + final targetTrack = targetTrackX[edge.id]!; + final sourceInset = portInset(source, config.portSpacing); + final targetInset = portInset(target, config.portSpacing); + final sourceY = runs.allocate( + desired: source.y + source.height / 2, + min: source.y + sourceInset, + max: source.bottom - sourceInset, + spanLo: source.right, + spanHi: sourceTrack, + ); + final targetSide = plan.kind == RouteKind.forward + ? RoutePortSide.left + : RoutePortSide.right; + final targetBorder = targetSide == RoutePortSide.left + ? target.x + : target.right; + final targetY = runs.allocate( + desired: target.y + target.height / 2, + min: target.y + targetInset, + max: target.bottom - targetInset, + spanLo: math.min(targetBorder, targetTrack), + spanHi: math.max(targetBorder, targetTrack), + ); + sourcePorts[edge.id] = RoutePort( + side: RoutePortSide.right, + point: RoutePoint(source.right, sourceY ?? source.y + source.height / 2), + ); + targetPorts[edge.id] = RoutePort( + side: targetSide, + point: RoutePoint(targetBorder, targetY ?? target.y + target.height / 2), + ); + } + + final planned = {}; + for (final edge in edges) { + final value = straightY[edge.id]; + if (value != null) { + planned[edge.id] = PlannedEdgeRoute( + edge: edge, + kind: kinds[edge.id]!, + straight: true, + sourcePort: sourcePorts[edge.id]!, + targetPort: targetPorts[edge.id]!, + points: _collapse([ + sourcePorts[edge.id]!.point, + targetPorts[edge.id]!.point, + ]), + ); + } + } + for (final plan in wrapPlans) { + final sourceTrack = sourceTrackX[plan.edge.id]!; + final targetTrack = targetTrackX[plan.edge.id]!; + planned[plan.edge.id] = PlannedEdgeRoute( + edge: plan.edge, + kind: plan.kind, + straight: false, + sourcePort: sourcePorts[plan.edge.id]!, + targetPort: targetPorts[plan.edge.id]!, + points: _collapse([ + sourcePorts[plan.edge.id]!.point, + RoutePoint(sourceTrack, sourcePorts[plan.edge.id]!.point.y), + RoutePoint(sourceTrack, plan.laneY), + RoutePoint(targetTrack, plan.laneY), + RoutePoint(targetTrack, targetPorts[plan.edge.id]!.point.y), + targetPorts[plan.edge.id]!.point, + ]), + ); + } + return [for (final edge in edges) planned[edge.id]!]; +} + +RouteKind _kindFor( + GraphEdge edge, + GraphNodeBox source, + GraphNodeBox target, + GraphLayout layout, +) { + if (edge.source == edge.target) return RouteKind.selfLoop; + final sourceRank = layout.ranks[edge.source] ?? source.rank; + final targetRank = layout.ranks[edge.target] ?? target.rank; + if (targetRank > sourceRank) return RouteKind.forward; + if (targetRank < sourceRank) return RouteKind.back; + return RouteKind.sameRank; +} + +List _collapse(List points) { + final result = []; + for (final point in points) { + if (result.isEmpty || result.last != point) result.add(point); + } + return result; +} + +class _WrapPlan { + _WrapPlan({required this.edge, required this.kind, required this.laneY}); + + final GraphEdge edge; + final RouteKind kind; + final double laneY; +} diff --git a/app/lib/features/graph/routing/graph_edge_routing.dart b/app/lib/features/graph/routing/graph_edge_routing.dart new file mode 100644 index 00000000..33ad9a9a --- /dev/null +++ b/app/lib/features/graph/routing/graph_edge_routing.dart @@ -0,0 +1,135 @@ +import 'dart:math' as math; + +import '../domain/graph_definition.dart'; +import '../layout/layout_models.dart'; +import 'edge_label_placement.dart'; +import 'edge_route_planner.dart'; +import 'route_models.dart'; + +/// Routes every definition edge that has a placed source and target. +/// +/// The node boxes and ranks come from the landed [GraphLayout]; this function +/// never moves them, invents a node or assumes a node size. Callers supply one +/// measured [LabelExtent] for every routed edge, plus the clearances and lane +/// spacing in [RoutingConfig]. +/// +/// Edges with an unknown, empty or missing endpoint are returned in +/// [GraphRouting.skipped] with their definition identity intact. A routed edge +/// keeps its id, source, outcome, target, label and fallback flag. Results are +/// ordered by definition edge id and are stable for repeated input. +GraphRouting routeGraphEdges({ + required GraphLayout layout, + required List edges, + required Map labelExtents, + required RoutingConfig config, +}) { + final ordered = [...edges]..sort((a, b) => a.id.compareTo(b.id)); + final seenIds = {}; + for (final edge in ordered) { + if (!seenIds.add(edge.id)) { + throw ArgumentError.value(edge.id, 'edges', 'duplicate edge id'); + } + } + + final nodes = { + for (final node in layout.nodes) node.key: node, + }; + final routed = []; + final skipped = []; + for (final edge in ordered) { + if (!nodes.containsKey(edge.source)) { + skipped.add( + RouteDiagnostic( + id: edge.id, + source: edge.source, + outcome: edge.outcome, + target: edge.target, + reason: RouteSkipReason.unknownSource, + message: 'source "${edge.source}" has no placed node', + ), + ); + continue; + } + if (!edge.knownTarget || !nodes.containsKey(edge.target)) { + skipped.add( + RouteDiagnostic( + id: edge.id, + source: edge.source, + outcome: edge.outcome, + target: edge.target, + reason: RouteSkipReason.unknownTarget, + message: edge.target.isEmpty + ? 'edge target is empty' + : 'target "${edge.target}" has no placed node', + ), + ); + continue; + } + routed.add(edge); + } + + final missing = [ + for (final edge in routed) + if (!labelExtents.containsKey(edge.id)) edge.id, + ]; + if (missing.isNotEmpty) { + throw ArgumentError.value( + missing, + 'labelExtents', + 'missing measured label extents for routed edges', + ); + } + + var maxLabelHeight = 0.0; + for (final edge in routed) { + maxLabelHeight = math.max(maxLabelHeight, labelExtents[edge.id]!.height); + } + final planned = planEdgeRoutes( + layout: layout, + edges: routed, + maxLabelHeight: maxLabelHeight, + config: config, + ); + final routes = [for (final plan in planned) plan.toRoute()]; + var floorY = layout.height; + for (final route in routes) { + for (final point in route.points) { + floorY = math.max(floorY, point.y); + } + } + + final labels = []; + for (var index = 0; index < routes.length; index += 1) { + labels.add( + placeEdgeLabel( + route: routes[index], + extent: labelExtents[routes[index].id]!, + nodes: layout.nodes, + placed: labels, + config: config, + floorY: floorY, + ), + ); + } + + var width = layout.width; + var height = layout.height; + for (final route in routes) { + for (final point in route.points) { + width = math.max(width, point.x); + height = math.max(height, point.y); + } + } + for (final label in labels) { + width = math.max(width, label.right); + height = math.max(height, label.bottom); + } + + return GraphRouting( + routes: routes, + labels: labels, + skipped: skipped, + width: width + config.boundsPadding, + height: height + config.boundsPadding, + ); +} diff --git a/app/lib/features/graph/routing/route_geometry.dart b/app/lib/features/graph/routing/route_geometry.dart new file mode 100644 index 00000000..aa89c4df --- /dev/null +++ b/app/lib/features/graph/routing/route_geometry.dart @@ -0,0 +1,175 @@ +import 'dart:math' as math; + +import '../layout/layout_models.dart'; + +/// Geometry helpers for deterministic orthogonal routing. +/// +/// Everything here is plain numbers: no Flutter types, no drawing and no +/// assumed metrics. The helpers are internal to the routing library. + +/// Reserves horizontal or vertical tracks without collinear overlap. +/// +/// A track is a position on [axis] plus the interval it spans on the other +/// axis. Two tracks only conflict when both their positions and their spans +/// overlap, so a long cross lane and a short stub may share a coordinate when +/// their runs do not meet. +class AxisTrackAllocator { + AxisTrackAllocator(this.step); + + final double step; + final List<_Track> _placed = <_Track>[]; + + /// The nearest free position to [desired], or null when none is found. + double? allocate({ + required double desired, + required double min, + required double max, + required double spanLo, + required double spanHi, + }) { + if (max < min) return null; + final start = desired.clamp(min, max); + var spacing = step; + while (spacing > 0.0001) { + for (var attempt = 0; attempt <= 512; attempt += 1) { + final candidates = attempt == 0 + ? [start] + : [start + attempt * spacing, start - attempt * spacing]; + for (final candidate in candidates) { + if (candidate < min || candidate > max) continue; + if (_isFree(candidate, spanLo, spanHi, spacing)) { + _placed.add(_Track(candidate, spanLo, spanHi)); + return candidate; + } + } + } + spacing /= 2; + } + return null; + } + + bool _isFree(double position, double spanLo, double spanHi, double spacing) { + for (final track in _placed) { + if ((track.position - position).abs() >= spacing) continue; + final overlaps = track.lo <= spanHi && spanLo <= track.hi; + if (overlaps) return false; + } + return true; + } +} + +class _Track { + const _Track(this.position, this.lo, this.hi); + + final double position; + final double lo; + final double hi; +} + +/// The x band available for vertical corridors in each column gap. +/// +/// Gap `g` sits before rank `g`; gap `rankCount` is the free space right of the +/// last column. Left/right bounds come from the placed boxes themselves, so a +/// corridor never crosses a column, including heterogeneous node widths. +class ColumnGaps { + ColumnGaps({ + required List nodes, + required this.rankCount, + required this.layoutWidth, + }) : _left = List.filled(rankCount + 1, 0), + _right = List.filled(rankCount + 1, layoutWidth) { + final rankRight = List.filled(rankCount, 0); + final rankLeft = List.filled(rankCount, layoutWidth); + for (final node in nodes) { + if (node.rank < 0 || node.rank >= rankCount) continue; + rankRight[node.rank] = math.max(rankRight[node.rank], node.right); + rankLeft[node.rank] = math.min(rankLeft[node.rank], node.x); + } + var left = 0.0; + for (var rank = 0; rank < rankCount; rank += 1) { + _left[rank] = left; + left = math.max(left, rankRight[rank]); + } + _left[rankCount] = left; + var right = layoutWidth; + _right[rankCount] = right; + for (var rank = rankCount - 1; rank >= 0; rank -= 1) { + right = math.min(right, rankLeft[rank]); + _right[rank] = right; + } + } + + final int rankCount; + final double layoutWidth; + final List _left; + final List _right; + + /// The usable band in gap [index], inset by at most [clearance]. + /// + /// The rightmost gap is open-ended because a loop may expand the canvas; + /// every other gap is bounded by the neighbouring columns. + GapBand band(int index, double clearance) { + final gap = index.clamp(0, rankCount); + final left = _left[gap]; + final right = _right[gap]; + if (gap == rankCount) { + return GapBand(lo: left + clearance, hi: double.infinity, open: true); + } + if (gap == 0) { + return GapBand( + lo: double.negativeInfinity, + hi: right - clearance, + open: true, + ); + } + final width = math.max(0.0, right - left); + final inset = math.min(clearance, width / 4); + return GapBand(lo: left + inset, hi: right - inset, open: false); + } +} + +/// One usable corridor band. +class GapBand { + const GapBand({required this.lo, required this.hi, required this.open}); + + final double lo; + final double hi; + final bool open; +} + +/// The inset a port keeps from a node corner. +double portInset(GraphNodeBox node, double portSpacing) => + math.min(portSpacing / 2, node.height / 2); + +/// True when an axis-aligned box overlaps [node], optionally inflated by [gap]. +bool boxIntersectsNode({ + required double x, + required double y, + required double width, + required double height, + required GraphNodeBox node, + double gap = 0, +}) { + return x < node.right + gap && + x + width > node.x - gap && + y < node.bottom + gap && + y + height > node.y - gap; +} + +/// True when two label-sized boxes overlap, optionally inflated by [gap]. +bool boxesOverlap({ + required double ax, + required double ay, + required double aw, + required double ah, + required double bx, + required double by, + required double bw, + required double bh, + double gap = 0, +}) { + return ax < bx + bw + gap && + ax + aw + gap > bx && + ay < by + bh + gap && + ay + ah + gap > by; +} diff --git a/app/lib/features/graph/routing/route_models.dart b/app/lib/features/graph/routing/route_models.dart new file mode 100644 index 00000000..7ce2dc24 --- /dev/null +++ b/app/lib/features/graph/routing/route_models.dart @@ -0,0 +1,261 @@ +/// Pure orthogonal geometry for a workflow graph's edges and labels. +/// +/// The caller owns every measurement: node boxes come from the landed +/// `GraphLayout`, label extents are measured after text layout, and clearances +/// or spacings come from [RoutingConfig]. This library never assumes a font, +/// widget style, device class or CSS value, and it has no Flutter imports. +/// +/// The same result can be built into a painter, native widgets or a test +/// fixture; no drawing decision lives here. +library; + +export 'routing_inputs.dart'; + +/// One point on an orthogonal route, in graph space. +class RoutePoint { + const RoutePoint(this.x, this.y); + + final double x; + final double y; + + @override + bool operator ==(Object other) => + other is RoutePoint && other.x == x && other.y == y; + + @override + int get hashCode => Object.hash(x, y); + + @override + String toString() => 'RoutePoint($x, $y)'; +} + +/// The border an edge leaves or enters through. +enum RoutePortSide { top, right, bottom, left } + +/// A route endpoint on a node's border. +/// +/// [side] is the edge's outward direction: a right port leaves to the right +/// (or enters from the right), a left port leaves to the left, and so on. +class RoutePort { + const RoutePort({required this.side, required this.point}); + + final RoutePortSide side; + final RoutePoint point; + + @override + bool operator ==(Object other) => + other is RoutePort && other.side == side && other.point == point; + + @override + int get hashCode => Object.hash(side, point); + + @override + String toString() => 'RoutePort($side, ${point.x}, ${point.y})'; +} + +/// How an edge relates to the layer it comes from. +enum RouteKind { + /// The target is in a later rank. + forward, + + /// Both endpoints share a rank (a cycle or strongly connected component). + sameRank, + + /// The target is in an earlier rank. Ranks from `assignGraphRanks` only + /// produce this for a caller-supplied layout; it is still routed honestly. + back, + + /// The source and target are the same node. + selfLoop, +} + +/// Why an edge has no route. +enum RouteSkipReason { + /// The source key has no placed node. + unknownSource, + + /// The target key has no placed node, including an empty/unknown target. + unknownTarget, +} + +/// One edge's deterministic orthogonal route. +/// +/// [id], [source], [outcome], [target], [label] and [fallback] are copied from +/// the definition edge unchanged. [points] starts at [sourcePort] and ends at +/// [targetPort]; every consecutive pair shares one coordinate. +class EdgeRoute { + EdgeRoute({ + required this.id, + required this.source, + required this.outcome, + required this.target, + required this.label, + required this.fallback, + required this.kind, + required this.straight, + required this.sourcePort, + required this.targetPort, + required List points, + }) : points = List.unmodifiable(points); + + final int id; + final String source; + final String outcome; + final String target; + final String label; + final bool fallback; + final RouteKind kind; + + /// True when the route is one straight horizontal segment. + final bool straight; + final RoutePort sourcePort; + final RoutePort targetPort; + final List points; + + @override + bool operator ==(Object other) => + other is EdgeRoute && + other.id == id && + other.source == source && + other.outcome == outcome && + other.target == target && + other.label == label && + other.fallback == fallback && + other.kind == kind && + other.straight == straight && + other.sourcePort == sourcePort && + other.targetPort == targetPort && + _samePoints(other.points, points); + + @override + int get hashCode => Object.hash( + id, + source, + outcome, + target, + label, + fallback, + kind, + straight, + sourcePort, + targetPort, + Object.hashAll(points), + ); +} + +/// One measured label box placed clear of node interiors. +class EdgeLabelBox { + const EdgeLabelBox({ + required this.edgeId, + required this.x, + required this.y, + required this.width, + required this.height, + }); + + final int edgeId; + final double x; + final double y; + final double width; + final double height; + + double get right => x + width; + double get bottom => y + height; + + @override + bool operator ==(Object other) => + other is EdgeLabelBox && + other.edgeId == edgeId && + other.x == x && + other.y == y && + other.width == width && + other.height == height; + + @override + int get hashCode => Object.hash(edgeId, x, y, width, height); +} + +/// An edge the router deliberately did not draw. +/// +/// The definition identity is preserved so a caller can present a diagnostic +/// instead of inventing a node, route or visit. +class RouteDiagnostic { + const RouteDiagnostic({ + required this.id, + required this.source, + required this.outcome, + required this.target, + required this.reason, + required this.message, + }); + + final int id; + final String source; + final String outcome; + final String target; + final RouteSkipReason reason; + final String message; + + @override + bool operator ==(Object other) => + other is RouteDiagnostic && + other.id == id && + other.source == source && + other.outcome == outcome && + other.target == target && + other.reason == reason && + other.message == message; + + @override + int get hashCode => Object.hash(id, source, outcome, target, reason, message); +} + +/// The complete immutable routing result. +/// +/// [width] and [height] include every route point and label box as well as the +/// landed layout bounds, so a loop that leaves the node grid expands the +/// returned box instead of being clipped. [routes] and [skipped] are ordered by +/// definition edge id; [labels] follows the same order. +class GraphRouting { + GraphRouting({ + required List routes, + required List labels, + required List skipped, + required this.width, + required this.height, + }) : routes = List.unmodifiable(routes), + labels = List.unmodifiable(labels), + skipped = List.unmodifiable(skipped); + + final List routes; + final List labels; + final List skipped; + final double width; + final double height; + + bool get isEmpty => routes.isEmpty; + + /// The route for [id], or null when that edge was skipped. + EdgeRoute? routeFor(int id) { + for (final route in routes) { + if (route.id == id) return route; + } + return null; + } + + /// The label box for [id], or null when the edge was skipped. + EdgeLabelBox? labelFor(int id) { + for (final label in labels) { + if (label.edgeId == id) return label; + } + return null; + } +} + +bool _samePoints(List a, List b) { + if (a.length != b.length) return false; + for (var index = 0; index < a.length; index += 1) { + if (a[index] != b[index]) return false; + } + return true; +} diff --git a/app/lib/features/graph/routing/routing_inputs.dart b/app/lib/features/graph/routing/routing_inputs.dart new file mode 100644 index 00000000..4fafe115 --- /dev/null +++ b/app/lib/features/graph/routing/routing_inputs.dart @@ -0,0 +1,64 @@ +/// Caller-supplied measurements and clearances for graph-edge routing. +/// +/// No font, widget style, device class or CSS value is assumed: every size is +/// measured or chosen by the caller. +library; + +void _requireFiniteNonNegative(String name, double value) { + if (!value.isFinite || value < 0) { + throw ArgumentError.value(value, name, 'must be finite and non-negative'); + } +} + +void _requireFinitePositive(String name, double value) { + if (!value.isFinite || value <= 0) { + throw ArgumentError.value(value, name, 'must be finite and positive'); + } +} + +/// A caller-measured edge label extent, in logical pixels. +class LabelExtent { + LabelExtent({required this.width, required this.height}) { + _requireFiniteNonNegative('width', width); + _requireFiniteNonNegative('height', height); + } + + final double width; + final double height; +} + +/// Clearances and spacings a caller reserves for edge geometry. +/// +/// [nodeClearance] is the distance a lane or corridor keeps from every node +/// edge. [laneSpacing] separates the horizontal tracks used by wrapping +/// routes, [corridorSpacing] separates vertical tracks inside one column gap, +/// and [portSpacing] separates ports on a node side. [labelGap] keeps a label +/// box off its wire; [boundsPadding] is added to the returned bounds. +/// +/// The router may widen a lane step beyond [laneSpacing] when the measured +/// label heights need the room. Inside a narrow column gap it compresses +/// corridor or port spacing rather than routing a track into a node column. +class RoutingConfig { + RoutingConfig({ + required this.nodeClearance, + required this.laneSpacing, + required this.corridorSpacing, + required this.portSpacing, + required this.labelGap, + this.boundsPadding = 0, + }) { + _requireFiniteNonNegative('nodeClearance', nodeClearance); + _requireFinitePositive('laneSpacing', laneSpacing); + _requireFinitePositive('corridorSpacing', corridorSpacing); + _requireFinitePositive('portSpacing', portSpacing); + _requireFiniteNonNegative('labelGap', labelGap); + _requireFiniteNonNegative('boundsPadding', boundsPadding); + } + + final double nodeClearance; + final double laneSpacing; + final double corridorSpacing; + final double portSpacing; + final double labelGap; + final double boundsPadding; +} diff --git a/app/notes/A1a.md b/app/notes/A1a.md new file mode 100644 index 00000000..2d5802e1 --- /dev/null +++ b/app/notes/A1a.md @@ -0,0 +1,101 @@ +# A1a — artifact records, capture facts, grouping, kinds and safe urls + +## What changed + +New nonvisual `artifacts` domain slice. Every file is new; no existing file was +edited. Nothing under `lib/main.dart`, `lib/shell/`, another feature, `pubspec.*`, +`web/`, the Go server or `android/` was touched. No dependency was added and no +network/transport code was written. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/artifacts/domain/artifact_record.dart` | 85 | One recorded artifact: name, url, content type, size and deeply read-only `raw`; retired `session.md` and system names | +| `lib/features/artifacts/domain/artifact_capture.dart` | 63 | Per-step capture availability (`unavailable`/`recorded`), recorded files, skipped and truncated counts | +| `lib/features/artifacts/domain/artifact_selection.dart` | 67 | Record parsing, retired/system/repair filtering (`presented`, `stage`, `system`) | +| `lib/features/artifacts/domain/artifact_groups.dart` | 109 | Group stage artifacts by stage and recorded visit; shared `public/` attribution; per-visit list | +| `lib/features/artifacts/domain/artifact_kind.dart` | 225 | MIME/extension kind vocabulary, labels, markdown/viewer predicates, `humanBytes` | +| `lib/features/artifacts/domain/artifact_summary.dart` | 78 | Run/visit summary and empty wording, partial-capture flag and notes | +| `lib/features/artifacts/domain/gallery_navigation.dart` | 76 | Filtered viewer page order, stable identities, previous/next clamp, position label | +| `lib/features/artifacts/domain/artifact_url.dart` | 78 | Safe http(s) resolution against the configured endpoint and cross-origin marking | +| `test/features/artifacts/domain/artifact_fixtures.dart` | 44 | Local step/artifact fixtures; no fake gateway or socket | +| `test/features/artifacts/domain/artifact_capture_test.dart` | 241 | Unavailable/null/empty/partial capture facts and exact wording | +| `test/features/artifacts/domain/artifact_groups_test.dart` | 308 | Visits, identity, retired/utility files, public attribution, empty states | +| `test/features/artifacts/domain/artifact_selection_test.dart` | 154 | Field preservation, deep immutability, filtering, duplicates | +| `test/features/artifacts/domain/artifact_kind_test.dart` | 110 | Known/unknown MIME and extension classification, markdown/viewer gates, bytes | +| `test/features/artifacts/domain/gallery_navigation_test.dart` | 197 | Filtered order, duplicate urls/names, url-less identities, paging clamp, label | +| `test/features/artifacts/domain/artifact_url_test.dart` | 148 | Relative/absolute urls, wss/https, IPv6, encoded path/query, schemes, credentials, cross-origin | + +## Behaviour (from `web/src/artifacts.js` and `artifactNavigation.js`) + +- **Record facts are verbatim.** `ArtifactRecord.fromJson` reads `name`, `url`, + `content_type`, `size_bytes` and keeps every other server field in a deep + unmodifiable `raw`. A missing url stays `''`; nothing is derived from the name. + Two records with the same name stay distinct because identity is the recorded + url (or a visit-scoped fallback in the viewer). +- **Capture availability is a recorded fact.** An absent, null or non-list + `artifacts` field is `unavailable`; an explicit empty list is a recorded empty + capture. `artifacts_skipped`/`artifacts_truncated` are preserved as counts and + mark a partial capture. Unavailable capture never degrades to "no artifacts" + or "not recorded": the run header says `Artifacts · capture unavailable` + instead of `No artifacts recorded for this run.`, which is the task's explicit + requirement and the one deliberate wording extension beyond the web client. +- **Grouping and identity.** `artifactGroups` keeps first-appearance stage order, + orders each stage's visits by sequence (recorded order on ties), and uses + `displayVisit` from the existing graph domain (`control.visit` when positive, + else position + 1). A step with no presented stage artifact yields no group, so + unavailable/empty captures and utility-only visits never fabricate a visit. + Shared `public/` files are attributed to the first recorded visit; repeated + non-public names in later visits remain separate artifacts. +- **Retired and utility files.** `session.md` is hidden everywhere; `session.html`, + `input.md`, `memory.md`, `output.md` remain system evidence and are excluded + from stage output. Repaired session exports named by `session_export_repairs` + are system evidence too. +- **Kinds.** Image/video come from the content type; audio, PDF, JSON, archive, + spreadsheet, log, code, document then match normalised MIME or extension; + unknown values are `other`/`File`. `isMarkdownArtifact`/`isViewerArtifact` keep + logs, source, CSV and HTML out of the in-app viewer while images, videos and + md/markdown/txt pages enter it. +- **Navigation.** `pagedArtifacts` filters group by group in recorded order; + `viewerIndexByUrl` maps the first occurrence of each url; url-less pages use a + visit-scoped identity; `pagedIndex` clamps with no wrap; the position label + trims content-type parameters and falls back to `artifact`. +- **Safe urls.** Server-relative paths resolve against the configured endpoint's + http(s) origin (endpoint path/query dropped, `wss` → `https`, IPv6 brackets and + percent-encoding kept). Absolute http(s) urls are preserved. Output is always + http(s): blank, protocol-relative, backslash-relative, hostless, credentialed, + malformed and non-http(s) urls return null. A url whose origin differs from the + configured origin is marked `external`, so a future authenticated fetch can + refuse to send cookies or headers; a same-origin url stays internal. + +## Review and quality fixes in this visit + +- `flutter analyze` reported four infos in this slice; all fixed: block braces in + `artifact_summary.dart` and null-aware map entries (`'key': ?value`) in the + test fixtures. Analyze is now clean for the whole app. +- `dart format` found one unformatted test file; all 15 files are now formatted. +- Semantics were re-read against `web/src/artifacts.js` (`presentedArtifacts`, + `stageArtifacts`, `systemArtifacts`, `artifactKind`, `pagedArtifacts`, + `viewerIndexByUrl`, `pagedIndex`, `displayVisit`) and `artifactNavigation.js`. + No other concrete deviation was found, so no behaviour was rewritten. + +## Checks actually run + +``` +flutter test test/features/artifacts/domain # 60 passed +flutter test test/features/graph/domain # 41 passed (stage_visits reuse) +flutter analyze # No issues found! (0.9s) +dart format lib/features/artifacts test/features/artifacts # clean, 15 files +grep trailing whitespace # none +``` + +## Honest limits + +- No gallery screen, viewer, sharing, fetching or transport helper exists in this + slice, so there is no rendered change and no browser capture. The gallery and + viewer are separate future slices. +- No live server, socket, artifact download or real run data was used; tests are + local fixtures and pure functions only. +- Mobile is unverified: no Android/iOS build, emulator, ADB or device was used. +- **Committed by the Land stage** as `ff0f812` on `flutter/a1-data` and merged + with `main` in `a303368`; the checks above were re-run on the merged candidate. + This stage did not merge into `main`, push or deploy. diff --git a/app/notes/P2c.md b/app/notes/P2c.md new file mode 100644 index 00000000..f8837940 --- /dev/null +++ b/app/notes/P2c.md @@ -0,0 +1,116 @@ +# P2c — deterministic orthogonal edge and label routing + +## What changed + +New app-only, pure-Dart files. No existing file, server, web client, legacy +client, shell, `main.dart`, pubspec, domain, layout, other feature or platform +source was edited. + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/graph/routing/route_models.dart` | 261 | public route, port, label, diagnostic and bounds types | +| `lib/features/graph/routing/routing_inputs.dart` | 64 | measured label extents and caller clearances | +| `lib/features/graph/routing/route_geometry.dart` | 175 | axis track allocator and column-gap bands | +| `lib/features/graph/routing/corridor_plan.dart` | 105 | vertical corridor allocation per column gap | +| `lib/features/graph/routing/edge_route_planner.dart` | 265 | forward/back/same-rank/self-loop polyline planning | +| `lib/features/graph/routing/edge_label_placement.dart` | 175 | measured label boxes clear of nodes and other labels | +| `lib/features/graph/routing/graph_edge_routing.dart` | 135 | validation, skipped diagnostics, labels, total bounds | +| `test/features/graph/routing/routing_fixtures.dart` | 143 | chain/diamond/parallel/cycle/self-loop/disconnected fixtures | +| `test/features/graph/routing/routing_assertions.dart` | 215 | orthogonality, borders, node interiors, corridors, labels, bounds | +| `test/features/graph/routing/graph_edge_routing_test.dart` | 191 | chain, diamond, parallel, cycle, loop, disconnected, expanded text, unknown targets | +| `test/features/graph/routing/graph_routing_geometry_test.dart` | 161 | wide labels, tight gaps, 3-stage SCC, backward layout, loop + forwards | +| `test/features/graph/routing/graph_routing_validation_test.dart` | 222 | empty input, missing measurements, duplicate ids, invalid config, determinism/immutability | + +No painting, widgets, styling, shell wiring or font/CSS/device constants were +added. + +## Public API + +```dart +GraphRouting routeGraphEdges({ + required GraphLayout layout, + required List edges, + required Map labelExtents, + required RoutingConfig config, +}); +``` + +`RoutingConfig` takes `nodeClearance`, `laneSpacing`, `corridorSpacing`, +`portSpacing`, `labelGap` and optional `boundsPadding`. `LabelExtent` is the +caller's measured label width/height. The node boxes and ranks are the landed +`GraphLayout` values; the router never moves or resizes a node. + +`GraphRouting` exposes unmodifiable `routes`, `labels`, `skipped`, `width` and +`height`, plus `routeFor(id)` / `labelFor(id)`. Each `EdgeRoute` keeps the +definition `id`, `source`, `outcome`, `target`, `label` and `fallback` flag, and +returns `sourcePort`, `targetPort`, a `RouteKind` and an orthogonal `points` +list. Each `EdgeLabelBox` carries the measured box for its edge id. + +## Deterministic guarantees (and what is not claimed) + +- **Identity:** routed edges copy the definition identity unchanged; skipped + edges keep it in `RouteDiagnostic` with `unknownSource`/`unknownTarget`. No + node, route or visit is invented for an empty, missing or unknown target. +- **Order and stability:** routes, labels and diagnostics are ordered by edge id + regardless of input order. Equal input produces equal, immutable results. +- **Orthogonality and ports:** every consecutive point pair shares one + coordinate. Endpoints are exactly on the source/target border with the + recorded side: forward routes leave right and enter left; same-rank, backward + and self-loop routes leave/enter the right side. +- **Node avoidance:** a forward one-rank route is a straight horizontal run only + when the boxes share a port band and leave room for label-aware track spacing. + Every other route drops into a unique horizontal lane below the node grid, + travels vertically only inside column gaps (or the free space right of the + last column), and returns to a port through its own stub. Vertical corridors + and lanes never enter a node column, and every horizontal stub stays on a row + that is clear of unrelated node boxes. +- **Distinguishable runs:** vertical tracks are spread across each gap, one + slot per corridor request; horizontal stubs and straight routes share one + interval-aware allocator; every wrapping route owns its own lane. Two edges + cannot share a collinear run in the tested fixtures. +- **Labels:** each routed edge needs a measured `LabelExtent`; a missing one is + an `ArgumentError`. The box is placed at a deterministic route run, clear of + node interiors and earlier labels. If a run is too narrow (for example a wide + label between close columns), the label moves to a free shelf below the + drawing and the returned bounds grow instead of covering a node. +- **Bounds:** `width`/`height` include the landed node layout, all route points + and all label boxes, plus `boundsPadding`. A self loop or an edge into the + right-free gap expands the box; nothing is clipped. +- **Not claimed:** perfect general crossing minimization or minimal bend + counts. Corridors and lanes are deterministic and locally separated, not a + globally optimal routing. + +## Checks actually run + +``` +flutter pub get +dart format lib/features/graph/routing test/features/graph/routing # 0 changed +flutter test test/features/graph/routing # 20 passed +flutter analyze # No issues found! +flutter test # 193 passed +``` + +Focused coverage includes chain, diamond fan-out/fan-in, three outcomes to one +target, a two-stage and a three-stage SCC, a self loop alone and beside forward +routes, disconnected stages, heterogeneous widths, 2.6x expanded text, tight +gaps, wide labels, a caller-supplied backward rank, missing/empty/unknown +targets, immutability, stable ordering and finite bounds. + +## Honest limits + +- **No rendering.** This is a nonvisual geometry slice: no painter, widgets, + native controls, screenshots or browser behavior. Rendered parity belongs to + the next renderer task. +- **Layout is an input.** The router does not widen columns for labels or move + nodes. Very wide labels may sit on the free shelf below the drawing; callers + that want labels beside an edge should reserve enough column gap when laying + out nodes. A zero-width column gap leaves no space for distinct vertical + corridors, so callers should supply a positive gap (the landed layout keeps + whatever gap it is given). +- **No general crossing optimum.** Only deterministic corridor/lane separation + is guaranteed, as described above. +- **No server or device.** Tests use local fixtures only; no run, pipeline, + schedule, service, emulator, ADB, Android/iOS build or live chat was touched. +- **Mobile unverified.** Only web-targeted Flutter test/analyze ran. +- **Uncommitted candidate.** Per this stage's instruction the slice is left in + the worktree; no commit, push or deployment was made. diff --git a/app/test/features/artifacts/domain/artifact_capture_test.dart b/app/test/features/artifacts/domain/artifact_capture_test.dart new file mode 100644 index 00000000..adf2f01a --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_capture_test.dart @@ -0,0 +1,241 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_capture.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_summary.dart'; + +import 'artifact_fixtures.dart'; + +void main() { + group('capture facts', () { + test('an absent or null artifact field is an unavailable capture', () { + final absent = ArtifactCapture.fromStep(step(includeArtifacts: false)); + final explicitNull = ArtifactCapture.fromStep(step(artifacts: null)); + + expect(absent.availability, ArtifactCaptureAvailability.unavailable); + expect(absent.isAvailable, isFalse); + expect(absent.artifacts, isEmpty); + expect(explicitNull.isAvailable, isFalse); + }); + + test('a malformed artifact field is unavailable, not empty', () { + final capture = ArtifactCapture.fromStep({ + 'artifacts': 'not a list', + }); + expect(capture.isAvailable, isFalse); + expect(capture.artifacts, isEmpty); + }); + + test('an explicitly recorded empty list is an available empty capture', () { + final capture = ArtifactCapture.fromStep(step(artifacts: const [])); + expect(capture.availability, ArtifactCaptureAvailability.recorded); + expect(capture.isAvailable, isTrue); + expect(capture.artifacts, isEmpty); + expect(capture.isPartial, isFalse); + }); + + test('records the skipped and truncated counts as capture facts', () { + final capture = ArtifactCapture.fromStep( + step( + artifacts: >[artifact('shot.png')], + skipped: 4, + truncated: 7, + ), + ); + expect(capture.artifacts.length, 1); + expect(capture.skipped, 4); + expect(capture.truncated, 7); + expect(capture.isPartial, isTrue); + expect( + ArtifactCapture.fromStep(step(artifacts: const [])).isPartial, + isFalse, + ); + }); + }); + + group('run and visit wording', () { + test('a running or unavailable capture never claims no artifacts', () { + expect( + artifactsSummary(step(status: 'running', artifacts: null)), + 'Artifacts · capture pending', + ); + expect( + artifactsSummary(step(status: 'running', artifacts: const [])), + 'Artifacts · capture pending', + ); + expect( + artifactsSummary(step(status: 'completed', artifacts: null)), + 'Artifacts · capture unavailable', + ); + expect( + artifactsSummary(step(status: 'completed', includeArtifacts: false)), + 'Artifacts · capture unavailable', + ); + }); + + test( + 'a finished available empty capture says not recorded for this visit', + () { + expect( + artifactsSummary(step(status: 'completed', artifacts: const [])), + 'Artifacts · not recorded for this visit', + ); + }, + ); + + test('counts presented stage artifacts and flags partial capture', () { + final full = step( + artifacts: >[ + artifact('a.png'), + artifact('b.png'), + artifact('input.md'), + artifact('session.md'), + ], + truncated: 1, + ); + expect( + artifactsSummary(full), + 'Artifacts · 2 recorded · partial capture', + ); + expect( + artifactsSummary( + step(artifacts: >[artifact('a.png')]), + ), + 'Artifacts · 1 recorded', + ); + }); + + test( + 'capture notes use the exact web wording and stay silent otherwise', + () { + final partial = step( + artifacts: >[artifact('a.png')], + skipped: 4, + truncated: 7, + ); + expect(artifactCaptureNotes(partial), [ + '4 files excluded from artifact capture.', + '7 files omitted by artifact capture limits.', + ]); + expect( + artifactCaptureNotes( + step( + artifacts: >[artifact('a.png')], + skipped: 2, + ), + ), + ['2 files excluded from artifact capture.'], + ); + expect( + artifactCaptureNotes( + step(artifacts: >[artifact('a.png')]), + ), + isEmpty, + ); + expect( + artifactCaptureNotes(step(artifacts: const [], skipped: 4)), + isEmpty, + ); + expect( + artifactCaptureNotes(step(includeArtifacts: false, skipped: 4)), + isEmpty, + ); + }, + ); + + test('the run empty message keeps the web running wording', () { + expect(artifactsEmptyMessage(true), 'Artifacts · capture pending'); + expect( + artifactsEmptyMessage(false), + 'No artifacts recorded for this run.', + ); + expect( + artifactsHeader(const [], executing: true), + 'Artifacts · capture pending', + ); + }); + + test( + 'an unavailable run capture is not reported as no recorded artifacts', + () { + final steps = >[ + step(stage: 'planner', sequence: 1, artifacts: null), + step(stage: 'build', sequence: 2, artifacts: const []), + ]; + expect( + artifactsHeader(steps, executing: false), + 'Artifacts · capture unavailable', + ); + }, + ); + + test('a fully available empty run says no artifacts were recorded', () { + final steps = >[ + step(stage: 'planner', sequence: 1, artifacts: const []), + step(stage: 'build', sequence: 2, artifacts: const []), + ]; + expect( + artifactsHeader(steps, executing: false), + 'No artifacts recorded for this run.', + ); + }); + + test( + 'the run header counts exactly the gallery tiles, singular for one', + () { + final one = >[ + step(artifacts: >[artifact('one.png')]), + ]; + expect(artifactsHeader(one, executing: false), 'Artifact · 1 recorded'); + + final four = >[ + step( + stage: 'planner', + sequence: 1, + artifacts: >[ + artifact('a.png'), + artifact('session.md'), + ], + ), + step( + stage: 'build', + sequence: 2, + artifacts: >[ + artifact('b.png'), + artifact('c.png'), + artifact('d.png'), + ], + ), + ]; + expect( + artifactsHeader(four, executing: false), + 'Artifacts · 4 recorded', + ); + expect(four, isNotEmpty); + }, + ); + + test('partial capture is flagged on the run header', () { + final steps = >[ + step(artifacts: >[artifact('a.png')], skipped: 2), + ]; + expect( + artifactsHeader(steps, executing: false), + 'Artifact · 1 recorded · partial capture', + ); + }); + + test('a visit that recorded only the retired session.md has no tile', () { + final steps = >[ + step(artifacts: >[artifact('session.md')]), + ]; + expect( + artifactsHeader(steps, executing: false), + 'No artifacts recorded for this run.', + ); + expect( + artifactsSummary(steps.first), + 'Artifacts · not recorded for this visit', + ); + expect(artifactCaptureNotes(steps.first), isEmpty); + }); + }); +} diff --git a/app/test/features/artifacts/domain/artifact_fixtures.dart b/app/test/features/artifacts/domain/artifact_fixtures.dart new file mode 100644 index 00000000..04c26bd5 --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_fixtures.dart @@ -0,0 +1,44 @@ +import 'package:pipelines_app/core/api_gateway.dart'; + +/// A minimal recorded [stage artifact], named so tests read like the web +/// client's fixtures. Every field the server records is present. +JsonMap artifact( + String name, { + String? url, + String contentType = '', + int sizeBytes = 0, + Map extra = const {}, +}) { + return { + 'name': name, + 'url': url ?? '/artifacts/1/1/$name', + 'content_type': contentType, + 'size_bytes': sizeBytes, + ...extra, + }; +} + +/// A minimal recorded step. [includeArtifacts] false omits the field entirely +/// (an unavailable capture); a null [artifacts] records an explicit null. +JsonMap step({ + String stage = 'review', + int sequence = 1, + String status = 'completed', + int visit = 1, + List? artifacts, + bool includeArtifacts = true, + int? skipped, + int? truncated, + List? repairs, +}) { + return { + 'stage': stage, + 'sequence': sequence, + 'status': status, + 'control': {'visit': visit}, + if (includeArtifacts) 'artifacts': artifacts, + 'artifacts_skipped': ?skipped, + 'artifacts_truncated': ?truncated, + 'session_export_repairs': ?repairs, + }; +} diff --git a/app/test/features/artifacts/domain/artifact_groups_test.dart b/app/test/features/artifacts/domain/artifact_groups_test.dart new file mode 100644 index 00000000..cf7173f6 --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_groups_test.dart @@ -0,0 +1,308 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_selection.dart'; + +import 'artifact_fixtures.dart'; + +void main() { + group('grouping', () { + test('groups interleaved steps by stage then recorded visit', () { + final steps = >[ + step( + stage: 'planner', + sequence: 1, + visit: 1, + artifacts: >[artifact('a.png')], + ), + step( + stage: 'build', + sequence: 2, + visit: 1, + artifacts: >[artifact('b.png')], + ), + step( + stage: 'planner', + sequence: 3, + visit: 2, + artifacts: >[artifact('c.png')], + ), + ]; + + final groups = artifactGroups(steps); + expect( + groups.map((group) => '${group.stageKey}/${group.visit}'), + ['planner/1', 'planner/2', 'build/1'], + ); + expect(groups.first.artifacts.map((record) => record.name), [ + 'a.png', + ]); + }); + + test('repeated stage visits stay separate and ordered by sequence', () { + final steps = >[ + step( + stage: 'review', + sequence: 7, + visit: 2, + artifacts: >[artifact('second.md')], + ), + step( + stage: 'review', + sequence: 3, + visit: 1, + artifacts: >[artifact('first.md')], + ), + ]; + + final groups = artifactGroups(steps); + expect(groups.map((group) => group.visit), [1, 2]); + expect(groups.map((group) => group.artifacts.single.name), [ + 'first.md', + 'second.md', + ]); + }); + + test( + 'a display visit is control.visit when positive, else position + 1', + () { + final steps = >[ + step( + stage: 's', + sequence: 1, + visit: 0, + artifacts: >[artifact('a')], + ), + step( + stage: 's', + sequence: 2, + visit: 0, + artifacts: >[artifact('b')], + ), + ]; + expect(artifactGroups(steps).map((group) => group.visit), [1, 2]); + }, + ); + + test('equal sequences keep recorded order', () { + final steps = >[ + step( + stage: 's', + sequence: 1, + visit: 1, + artifacts: >[artifact('first')], + ), + step( + stage: 's', + sequence: 1, + visit: 2, + artifacts: >[artifact('second')], + ), + ]; + expect( + artifactGroups(steps).map((group) => group.artifacts.single.name), + ['first', 'second'], + ); + }); + + test('an absent stage visit is not fabricated', () { + final steps = >[ + step( + stage: 'a', + sequence: 1, + artifacts: >[artifact('a.png')], + ), + ]; + final groups = artifactGroups(steps); + expect(groups.single.stageKey, 'a'); + expect(groups.any((group) => group.stageKey == 'b'), isFalse); + }); + }); + + group('identity', () { + test('the same file name in different visits remains two groups', () { + final steps = >[ + step( + stage: 'implementer', + sequence: 1, + visit: 1, + artifacts: >[ + artifact('report.md', url: '/artifacts/1/1/report.md'), + ], + ), + step( + stage: 'implementer', + sequence: 2, + visit: 2, + artifacts: >[ + artifact('report.md', url: '/artifacts/1/2/report.md'), + ], + ), + ]; + final groups = artifactGroups(steps); + expect(groups.length, 2); + expect(groups.map((group) => group.artifacts.single.url), [ + '/artifacts/1/1/report.md', + '/artifacts/1/2/report.md', + ]); + }); + + test('duplicate names in one visit are kept with their recorded urls', () { + final steps = >[ + step( + stage: 's', + sequence: 1, + artifacts: >[ + artifact('shot.png', url: '/artifacts/1/1/shot-a.png'), + artifact('shot.png', url: '/artifacts/1/1/shot-b.png'), + ], + ), + ]; + final artifacts = artifactGroups(steps).single.artifacts; + expect(artifacts.length, 2); + expect(artifacts.map((record) => record.url), [ + '/artifacts/1/1/shot-a.png', + '/artifacts/1/1/shot-b.png', + ]); + }); + + test('the retired session.md is hidden but session.html is retained', () { + final steps = >[ + step( + stage: 's', + sequence: 1, + artifacts: >[ + artifact('session.md'), + artifact('session.html'), + artifact('report.md'), + ], + ), + ]; + // session.html is retained as system evidence, but neither it nor the + // retired session.md is stage output, so the gallery shows only the report. + expect( + artifactGroups(steps).single.artifacts.map((record) => record.name), + ['report.md'], + ); + expect( + systemArtifacts(steps.single).map((record) => record.name), + ['session.html'], + ); + }); + }); + + group('shared public files', () { + test('a public file is attributed to the visit that first recorded it', () { + final steps = >[ + step( + stage: 'a', + sequence: 1, + artifacts: >[ + artifact('input.md'), + artifact('public/a.txt'), + ], + ), + step( + stage: 'b', + sequence: 2, + artifacts: >[ + artifact('output.md'), + artifact('public/a.txt'), + artifact('public/b.txt'), + ], + ), + ]; + final groups = artifactGroups(steps); + expect( + groups.map( + (group) => group.artifacts.map((record) => record.name).toList(), + ), + >[ + ['public/a.txt'], + ['public/b.txt'], + ], + ); + expect( + visitArtifacts(steps[1], steps).map((record) => record.name), + ['public/b.txt'], + ); + }); + + test( + 'visitArtifacts keeps a repeated non-public name in a later visit', + () { + final steps = >[ + step( + stage: 'a', + sequence: 1, + artifacts: >[ + artifact('report.md', url: '/artifacts/1/1/report.md'), + ], + ), + step( + stage: 'a', + sequence: 2, + artifacts: >[ + artifact('report.md', url: '/artifacts/1/2/report.md'), + ], + ), + ]; + expect( + visitArtifacts(steps[1], steps).map((record) => record.url), + ['/artifacts/1/2/report.md'], + ); + }, + ); + + test('a public file repeated inside one visit is recorded once', () { + final steps = >[ + step( + stage: 'a', + sequence: 1, + artifacts: >[ + artifact('public/a.txt'), + artifact('public/a.txt'), + ], + ), + ]; + expect(artifactGroups(steps).single.artifacts.length, 1); + }); + }); + + group('unavailable and empty captures', () { + test('unavailable, null and empty visits yield no group', () { + final steps = >[ + step(stage: 'a', sequence: 1, includeArtifacts: false), + step(stage: 'a', sequence: 2, artifacts: null), + step(stage: 'a', sequence: 3, artifacts: const []), + step( + stage: 'b', + sequence: 4, + artifacts: >[artifact('only.png')], + ), + ]; + final groups = artifactGroups(steps); + expect(groups.length, 1); + expect(groups.single.stageKey, 'b'); + expect(groups.single.visit, 1); + }); + + test('a visit with only utility or retired files yields no group', () { + final steps = >[ + step( + stage: 'a', + sequence: 1, + artifacts: >[ + artifact('input.md'), + artifact('session.md'), + artifact('session.html'), + ], + ), + ]; + expect(artifactGroups(steps), isEmpty); + }); + + test('an empty run yields no groups', () { + expect(artifactGroups(const []), isEmpty); + }); + }); +} diff --git a/app/test/features/artifacts/domain/artifact_kind_test.dart b/app/test/features/artifacts/domain/artifact_kind_test.dart new file mode 100644 index 00000000..a95ccfab --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_kind_test.dart @@ -0,0 +1,110 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_kind.dart'; + +void main() { + test('classifies images and videos from their recorded content type', () { + expect(artifactKind('image/png', 'shot.png'), ArtifactKind.image); + expect( + artifactKind('image/svg+xml; charset=utf-8', 'plot'), + ArtifactKind.image, + ); + expect(artifactKind('video/mp4', 'clip.mp4'), ArtifactKind.video); + }); + + test('matches the web client file-kind vocabulary by MIME and name', () { + const cases = <(String, String, ArtifactKind)>[ + ('audio/mpeg', 'sound.mp3', ArtifactKind.audio), + ('application/pdf', 'report', ArtifactKind.pdf), + ('application/octet-stream', 'data.pdf', ArtifactKind.pdf), + ('application/json', 'payload', ArtifactKind.json), + ('text/plain', 'config.json', ArtifactKind.json), + ('application/zip', 'bundle', ArtifactKind.archive), + ('text/plain', 'backup.tar.gz', ArtifactKind.archive), + ('text/csv', 'rows', ArtifactKind.spreadsheet), + ('application/octet-stream', 'sheet.xlsx', ArtifactKind.spreadsheet), + ('text/plain', 'run.log', ArtifactKind.log), + ('application/xml', 'layout', ArtifactKind.code), + ('text/plain', 'main.go', ArtifactKind.code), + ('text/html; charset=utf-8', 'session.html', ArtifactKind.document), + ('text/plain', 'notes.txt', ArtifactKind.document), + ('application/octet-stream', 'blob.bin', ArtifactKind.other), + ('', '', ArtifactKind.other), + ('application/x-unknown-thing', 'report.unknownext', ArtifactKind.other), + ]; + for (final (contentType, name, kind) in cases) { + expect( + artifactKind(contentType, name), + kind, + reason: '$contentType $name', + ); + } + }); + + test('names every kind in prose, with File as the unknown fallback', () { + expect(artifactKindLabel(ArtifactKind.image), 'Image'); + expect(artifactKindLabel(ArtifactKind.video), 'Video'); + expect(artifactKindLabel(ArtifactKind.audio), 'Audio'); + expect(artifactKindLabel(ArtifactKind.pdf), 'PDF'); + expect(artifactKindLabel(ArtifactKind.json), 'JSON'); + expect(artifactKindLabel(ArtifactKind.archive), 'Archive'); + expect(artifactKindLabel(ArtifactKind.spreadsheet), 'Spreadsheet'); + expect(artifactKindLabel(ArtifactKind.log), 'Log'); + expect(artifactKindLabel(ArtifactKind.code), 'Code'); + expect(artifactKindLabel(ArtifactKind.document), 'Document'); + expect(artifactKindLabel(ArtifactKind.other), 'File'); + }); + + test('formats recorded bytes like the web client', () { + expect(humanBytes(0), '0 B'); + expect(humanBytes(999), '999 B'); + expect(humanBytes(1024), '1.0 KiB'); + expect(humanBytes(1536), '1.5 KiB'); + expect(humanBytes(2 * 1024 * 1024), '2.0 MiB'); + expect(humanBytes(3 * 1024 * 1024 * 1024), '3.0 GiB'); + }); + + test('markdown and viewer artifacts use the shared classification', () { + const markdown = <(String, String)>[ + ('text/markdown', 'plan'), + ('text/markdown; charset=utf-8', 'plan'), + ('text/plain', 'notes'), + ('application/octet-stream', 'input.md'), + ('', 'memory.markdown'), + ('', 'output.txt'), + ]; + for (final (contentType, name) in markdown) { + expect(isMarkdownArtifact(contentType, name), isTrue, reason: name); + } + for (final (contentType, name) in <(String, String)>[ + ('text/html', 'session.html'), + ('text/csv', 'rows.csv'), + ('application/json', 'payload.json'), + ('text/x-python', 'main.py'), + ('application/xml', 'shot.png.xml'), + ('', ''), + ]) { + expect(isMarkdownArtifact(contentType, name), isFalse, reason: name); + } + + for (final (contentType, name) in <(String, String)>[ + ('image/png', 'shot.png'), + ('video/mp4', 'clip.mp4'), + ('text/markdown', 'input.md'), + ('text/plain', 'memory.txt'), + ('', 'output.md'), + ]) { + expect(isViewerArtifact(contentType, name), isTrue, reason: name); + } + for (final (contentType, name) in <(String, String)>[ + ('text/html', 'session.html'), + ('text/csv', 'rows.csv'), + ('application/json', 'payload.json'), + ('text/x-python', 'main.py'), + ('text/plain', 'run.log'), + ('application/octet-stream', 'blob.bin'), + ('', ''), + ]) { + expect(isViewerArtifact(contentType, name), isFalse, reason: name); + } + }); +} diff --git a/app/test/features/artifacts/domain/artifact_selection_test.dart b/app/test/features/artifacts/domain/artifact_selection_test.dart new file mode 100644 index 00000000..d65bdcb7 --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_selection_test.dart @@ -0,0 +1,154 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_selection.dart'; + +import 'artifact_fixtures.dart'; + +void main() { + group('record preservation', () { + test('keeps size, content type, url and unknown fields verbatim', () { + final recorded = ArtifactRecord.fromJson( + artifact( + 'shot.png', + url: '/artifacts/7/3/shot.png', + contentType: 'image/png', + sizeBytes: 1536, + extra: { + 'sha256': 'abc', + 'capture': {'source': 'stage'}, + }, + ), + ); + + expect(recorded.name, 'shot.png'); + expect(recorded.url, '/artifacts/7/3/shot.png'); + expect(recorded.contentType, 'image/png'); + expect(recorded.sizeBytes, 1536); + expect(recorded.raw['sha256'], 'abc'); + expect((recorded.raw['capture'] as Map)['source'], 'stage'); + }); + + test('never invents a missing name, url, type or size', () { + final recorded = ArtifactRecord.fromJson(const {}); + expect(recorded.name, ''); + expect(recorded.url, ''); + expect(recorded.contentType, ''); + expect(recorded.sizeBytes, 0); + expect(recorded.hasUrl, isFalse); + }); + + test('the raw record is read-only, including nested values', () { + final recorded = ArtifactRecord.fromJson( + artifact( + 'a.txt', + extra: { + 'nested': {'x': 1}, + }, + ), + ); + expect( + () => recorded.raw['nested'] = {}, + throwsUnsupportedError, + ); + expect( + () => (recorded.raw['nested'] as Map)['x'] = 2, + throwsUnsupportedError, + ); + }); + }); + + group('retired and utility files', () { + test( + 'hides session.md from presented artifacts but keeps session.html', + () { + final records = [ + ArtifactRecord.fromJson(artifact('shot.png')), + ArtifactRecord.fromJson(artifact(legacySessionMarkdownArtifact)), + ArtifactRecord.fromJson(artifact('session.html')), + ]; + + expect( + presentedArtifacts(records).map((record) => record.name), + ['shot.png', 'session.html'], + ); + }, + ); + + test('utility files are system evidence, not stage output', () { + expect(systemArtifactNames, [ + 'input.md', + 'memory.md', + 'output.md', + 'session.html', + ]); + for (final name in systemArtifactNames) { + expect(isSystemArtifactName(name), isTrue, reason: name); + } + expect(isSystemArtifactName('public/input.md'), isFalse); + expect(isSystemArtifactName('session.md'), isFalse); + expect(isSystemArtifactName('shot.png'), isFalse); + }); + + test('stage artifacts exclude utility files and repair exports', () { + final recorded = step( + artifacts: [ + artifact('input.md'), + artifact('memory.md'), + artifact('output.md'), + artifact('session.html'), + artifact('repaired.html'), + artifact('public/input.md'), + artifact('shot.png'), + ].cast>(), + repairs: >[ + {'html': 'repaired.html'}, + ], + ); + + expect(stageArtifacts(recorded).map((record) => record.name), [ + 'public/input.md', + 'shot.png', + ]); + expect(systemArtifacts(recorded).map((record) => record.name), [ + 'input.md', + 'memory.md', + 'output.md', + 'session.html', + 'repaired.html', + ]); + }); + + test('a missing or malformed artifact list records no artifacts', () { + expect(artifactsOf(step(includeArtifacts: false)), isEmpty); + expect(artifactsOf(step(artifacts: null)), isEmpty); + expect(artifactsOf(step(artifacts: const [])), isEmpty); + expect( + artifactsOf({'artifacts': 'not a list'}), + isEmpty, + ); + }); + + test('duplicate names are records, not identities to dedupe', () { + final records = [ + ArtifactRecord.fromJson( + artifact('shot.png', url: '/artifacts/1/1/a.png'), + ), + ArtifactRecord.fromJson( + artifact('shot.png', url: '/artifacts/1/1/b.png'), + ), + ]; + expect( + stageArtifacts( + step( + artifacts: >[ + artifact('shot.png', url: '/artifacts/1/1/a.png'), + artifact('shot.png', url: '/artifacts/1/1/b.png'), + ], + ), + ).map((record) => record.url), + ['/artifacts/1/1/a.png', '/artifacts/1/1/b.png'], + ); + expect(records.length, 2); + }); + }); +} diff --git a/app/test/features/artifacts/domain/artifact_url_test.dart b/app/test/features/artifacts/domain/artifact_url_test.dart new file mode 100644 index 00000000..e7d9a961 --- /dev/null +++ b/app/test/features/artifacts/domain/artifact_url_test.dart @@ -0,0 +1,148 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_url.dart'; + +void main() { + group('server-relative paths', () { + test( + 'resolve against the configured endpoint origin, dropping its path', + () { + final resolved = resolveArtifactUrl( + 'ws://example.test:8081/connect?token=x', + '/artifacts/a%20b?download=1', + ); + expect(resolved, isNotNull); + expect( + resolved!.uri.toString(), + 'http://example.test:8081/artifacts/a%20b?download=1', + ); + expect(resolved.external, isFalse); + }, + ); + + test('map wss to https and omit the default port', () { + final resolved = resolveArtifactUrl( + 'wss://example.test/connect', + 'artifacts/shot.png', + ); + expect( + resolved!.uri.toString(), + 'https://example.test/artifacts/shot.png', + ); + expect(resolved.external, isFalse); + }); + + test('keep IPv6 brackets and encoded paths intact', () { + final resolved = resolveArtifactUrl( + 'ws://[::1]:8081/connect', + '/artifacts/a%2Fb?next=%2Fnext', + ); + expect( + resolved!.uri.toString(), + 'http://[::1]:8081/artifacts/a%2Fb?next=%2Fnext', + ); + expect(resolved.uri.host, '::1'); + }); + + test('a blank endpoint leaves a relative artifact unresolved', () { + expect(resolveArtifactUrl('', '/artifacts/a'), isNull); + expect(resolveArtifactUrl('not a url', '/artifacts/a'), isNull); + expect( + resolveArtifactUrl('https://example.test', '/artifacts/a'), + isNull, + ); + }); + }); + + group('absolute http(s) artifacts', () { + test('a same-origin absolute url stays internal', () { + final resolved = resolveArtifactUrl( + 'ws://example.test:8081/connect', + 'http://example.test:8081/artifacts/a%20b?download=1', + ); + expect( + resolved!.uri.toString(), + 'http://example.test:8081/artifacts/a%20b?download=1', + ); + expect(resolved.external, isFalse); + }); + + test('cross-host, cross-port and cross-scheme urls are external', () { + const configured = 'wss://example.test/connect'; + for (final url in [ + 'https://cdn.test/artifacts/a', + 'https://example.test:8443/artifacts/a', + 'http://example.test/artifacts/a', + ]) { + final resolved = resolveArtifactUrl(configured, url); + expect(resolved, isNotNull, reason: url); + expect(resolved!.external, isTrue, reason: url); + } + }); + + test('an absolute url without a usable configured origin is external', () { + final resolved = resolveArtifactUrl('', 'https://cdn.test/a%2Fb?q=1'); + expect(resolved!.uri.toString(), 'https://cdn.test/a%2Fb?q=1'); + expect(resolved.external, isTrue); + }); + }); + + group('unsafe urls', () { + test('rejects blank, protocol-relative and hostless urls', () { + for (final url in [ + '', + ' ', + '//evil.test/artifacts/a', + 'http:///artifacts/a', + 'http://', + 'https://?x=1', + ]) { + expect( + resolveArtifactUrl('ws://example.test:8081', url), + isNull, + reason: url, + ); + } + }); + + test('rejects credentials in any absolute url', () { + for (final url in [ + 'http://user:pass@example.test/artifacts/a', + 'https://user@example.test/artifacts/a', + 'http://example.test:8081@evil.test/artifacts/a', + ]) { + expect( + resolveArtifactUrl('ws://example.test:8081', url), + isNull, + reason: url, + ); + } + }); + + test('rejects unsafe and non-http schemes', () { + for (final url in [ + 'javascript:alert(1)', + 'data:text/html,hello', + 'file:///etc/passwd', + 'ftp://example.test/a', + 'intent://example.test/a#Intent;end', + 'mailto:ops@example.test', + ]) { + expect( + resolveArtifactUrl('ws://example.test:8081', url), + isNull, + reason: url, + ); + } + }); + + test('never produces a non-http(s) output', () { + final resolved = resolveArtifactUrl( + 'ws://example.test:8081/connect', + '/artifacts/a', + ); + expect(resolved!.uri.scheme, 'http'); + expect(resolved.uri.hasAuthority, isTrue); + expect(resolved.uri.userInfo, isEmpty); + }); + }); +} diff --git a/app/test/features/artifacts/domain/gallery_navigation_test.dart b/app/test/features/artifacts/domain/gallery_navigation_test.dart new file mode 100644 index 00000000..af8b72ed --- /dev/null +++ b/app/test/features/artifacts/domain/gallery_navigation_test.dart @@ -0,0 +1,197 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart'; +import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart'; +import 'package:pipelines_app/features/artifacts/domain/gallery_navigation.dart'; + +import 'artifact_fixtures.dart'; + +ArtifactRecord record(String name, {String contentType = '', String? url}) => + ArtifactRecord.fromJson(artifact(name, contentType: contentType, url: url)); + +void main() { + group('filtered gallery order', () { + test('pages viewer artifacts group by group, in recorded order', () { + final groups = [ + ArtifactGroup( + stageKey: 'reviewer', + visit: 1, + artifacts: [ + record('session.html', contentType: 'text/html'), + record('input.md', contentType: 'text/markdown'), + ], + ), + ArtifactGroup( + stageKey: 'implementer', + visit: 2, + artifacts: [ + record('run.log', contentType: 'text/plain'), + record('shot.png', contentType: 'image/png'), + record('main.py', contentType: 'text/x-python'), + record('clip.mp4', contentType: 'video/mp4'), + record('memory.txt', contentType: 'text/plain'), + record('rows.csv', contentType: 'text/csv'), + record('output.md', contentType: 'application/octet-stream'), + ], + ), + ]; + + expect(pagedArtifacts(groups).map((page) => page.artifact.name), [ + 'input.md', + 'shot.png', + 'clip.mp4', + 'memory.txt', + 'output.md', + ]); + expect(pagedArtifacts(const []), isEmpty); + }); + + test('a page keeps the stage visit it belongs to', () { + final groups = artifactGroups(>[ + step( + stage: 'a', + sequence: 1, + visit: 3, + artifacts: >[ + artifact('a.png', contentType: 'image/png'), + ], + ), + step( + stage: 'b', + sequence: 2, + visit: 5, + artifacts: >[ + artifact('b.png', contentType: 'image/png'), + ], + ), + ]); + final pages = pagedArtifacts(groups); + expect(pages.map((page) => '${page.stageKey}/${page.visit}'), [ + 'a/3', + 'b/5', + ]); + expect(pages.map((page) => page.pageIndex), [0, 1]); + }); + }); + + group('identity', () { + test('duplicate names with different urls get distinct viewer indices', () { + final groups = artifactGroups(>[ + step( + stage: 'a', + sequence: 1, + visit: 1, + artifacts: >[ + artifact( + 'shot.png', + url: '/artifacts/1/1/shot.png', + contentType: 'image/png', + ), + ], + ), + step( + stage: 'a', + sequence: 2, + visit: 2, + artifacts: >[ + artifact( + 'shot.png', + url: '/artifacts/1/2/shot.png', + contentType: 'image/png', + ), + ], + ), + ]); + final index = viewerIndexByUrl(groups); + expect(index, { + '/artifacts/1/1/shot.png': 0, + '/artifacts/1/2/shot.png': 1, + }); + expect(pagedArtifacts(groups).map((page) => page.identity), [ + '/artifacts/1/1/shot.png', + '/artifacts/1/2/shot.png', + ]); + }); + + test('a repeated url maps to its first occurrence only', () { + final groups = artifactGroups(>[ + step( + stage: 'a', + sequence: 1, + artifacts: >[ + artifact( + 'a.png', + url: '/artifacts/1/1/a.png', + contentType: 'image/png', + ), + artifact( + 'a.png', + url: '/artifacts/1/1/a.png', + contentType: 'image/png', + ), + ], + ), + ]); + final index = viewerIndexByUrl(groups); + expect(index, {'/artifacts/1/1/a.png': 0}); + expect(pagedArtifacts(groups).length, 2); + }); + + test('artifacts without a url keep distinct fallback identities', () { + final groups = artifactGroups(>[ + step( + stage: 'a', + sequence: 1, + visit: 2, + artifacts: >[ + artifact('shot.png', url: '', contentType: 'image/png'), + artifact('shot.png', url: '', contentType: 'image/png'), + ], + ), + ]); + final pages = pagedArtifacts(groups); + expect(pages.map((page) => page.identity).toSet().length, 2); + expect(viewerIndexByUrl(groups), isEmpty); + }); + + test('non-viewer artifacts never get a viewer identity', () { + final groups = artifactGroups(>[ + step( + stage: 'a', + sequence: 1, + artifacts: >[ + artifact('session.html', contentType: 'text/html'), + artifact('main.py', contentType: 'text/x-python'), + artifact('run.log', contentType: 'text/plain'), + ], + ), + ]); + expect(pagedArtifacts(groups), isEmpty); + expect(viewerIndexByUrl(groups), isEmpty); + }); + }); + + group('paging', () { + test('previous and next clamp at both ends without wrapping', () { + expect(pagedIndex(0, -1, 3), 0); + expect(pagedIndex(1, -1, 3), 0); + expect(pagedIndex(1, 1, 3), 2); + expect(pagedIndex(2, 1, 3), 2); + expect(pagedIndex(0, 0, 0), 0); + expect(pagedIndex(0, 0, 1), 0); + expect(pagedIndex(9, -3, 0), 0); + }); + + test('the position label trims the content type and falls back', () { + expect( + artifactViewerPositionLabel(0, 3, 'image/png'), + '1 of 3 · image/png', + ); + expect( + artifactViewerPositionLabel(1, 3, 'image/png; charset=binary'), + '2 of 3 · image/png', + ); + expect(artifactViewerPositionLabel(4, 5, ''), '5 of 5 · artifact'); + expect(artifactViewerPositionLabel(0, 1, ' '), '1 of 1 · artifact'); + }); + }); +} diff --git a/app/test/features/graph/routing/graph_edge_routing_test.dart b/app/test/features/graph/routing/graph_edge_routing_test.dart new file mode 100644 index 00000000..59ee4922 --- /dev/null +++ b/app/test/features/graph/routing/graph_edge_routing_test.dart @@ -0,0 +1,191 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +import '../layout/layout_fixtures.dart' as layout; +import 'routing_assertions.dart'; +import 'routing_fixtures.dart'; + +void main() { + test('chain routes keep identities and use straight forward runs', () { + final graph = chainGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = labelsFor(edges); + final routing = routeFor(graph, labels: labels); + + expect(routing.skipped, isEmpty); + expect( + routing.routes.map((route) => route.id), + edges.map((edge) => edge.id), + ); + for (var index = 0; index < edges.length; index += 1) { + final edge = edges[index]; + final route = routing.routes[index]; + expect(route.source, edge.source); + expect(route.outcome, edge.outcome); + expect(route.target, edge.target); + expect(route.label, edge.label); + expect(route.fallback, edge.fallback); + expect(route.kind, RouteKind.forward); + expect(route.straight, isTrue); + expect(route.points.length, 2); + expect(route.sourcePort.side, RoutePortSide.right); + expect(route.targetPort.side, RoutePortSide.left); + } + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('diamond fan-out and fan-in avoid every node interior', () { + final graph = diamondGraphFixture(); + final layoutBox = layoutFor(graph); + final labels = labelsFor(graphEdges(graph)); + final routing = routeFor(graph, labels: labels); + + expect(routing.skipped, isEmpty); + expect(routing.routes.length, graphEdges(graph).length); + final fromA = routing.routes.where((route) => route.source == 'a'); + expect(fromA.length, 3); + expect( + fromA.where((route) => route.straight).length, + greaterThanOrEqualTo(1), + ); + final longForward = fromA.singleWhere( + (route) => route.target == failureEnd, + ); + expect(longForward.kind, RouteKind.forward); + expect(longForward.straight, isFalse); + expect(longForward.points.length, greaterThan(4)); + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('parallel outcomes to one target get separate corridors and labels', () { + final graph = parallelOutcomesGraph(); + final layoutBox = layoutFor(graph); + final labels = labelsFor(graphEdges(graph)); + final routing = routeFor(graph, labels: labels); + + final parallel = routing.routes + .where((route) => route.source == 'a' && route.target == 'b') + .toList(); + expect(parallel.length, 3); + final ports = { + for (final route in parallel) + '${route.sourcePort.point.y}/${route.targetPort.point.y}', + }; + expect(ports.length, 3, reason: 'each outcome has its own port pair'); + final labelBoxes = [ + for (final route in parallel) routing.labelFor(route.id)!, + ]; + expect(labelBoxes.map((box) => box.y).toSet().length, greaterThan(1)); + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('a same-rank cycle uses distinct lanes around both members', () { + final graph = cycleGraphFixture(); + final layoutBox = layoutFor(graph); + final labels = labelsFor(graphEdges(graph)); + final routing = routeFor(graph, labels: labels); + + final sameRank = routing.routes + .where((route) => route.kind == RouteKind.sameRank) + .toList(); + expect(sameRank.length, 2); + expect(sameRank.map((route) => route.target).toSet(), {'a', 'b'}); + for (final route in sameRank) { + expect(route.straight, isFalse); + expect(route.sourcePort.side, RoutePortSide.right); + expect(route.targetPort.side, RoutePortSide.right); + expect( + route.points.map((point) => point.y).toSet().length, + greaterThan(2), + ); + } + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('a self loop expands bounds and keeps both ports on its border', () { + final graph = selfLoopOnlyGraph(); + final layoutBox = layoutFor(graph); + final labels = labelsFor(graphEdges(graph)); + final routing = routeFor(graph, labels: labels); + + final route = routing.routes.single; + expect(route.kind, RouteKind.selfLoop); + expect(route.straight, isFalse); + expect(route.points.length, greaterThanOrEqualTo(4)); + expect(route.sourcePort.side, RoutePortSide.right); + expect(route.targetPort.side, RoutePortSide.right); + expect(route.sourcePort.point.y, isNot(route.targetPort.point.y)); + expect(routing.width, greaterThan(layoutBox.width)); + expect(routing.height, greaterThan(layoutBox.height)); + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('disconnected stages route only their declared edges', () { + final graph = disconnectedGraphFixture(); + final layoutBox = layoutFor(graph); + final labels = labelsFor(graphEdges(graph)); + final routing = routeFor(graph, labels: labels); + + expect(routing.skipped, isEmpty); + expect(routing.routes.length, 2); + expect(routing.routes.map((route) => route.source).toSet(), { + 'a', + 'b', + }); + expect(layoutBox.nodeFor('c'), isNotNull); + expect(routing.routes.any((route) => route.source == 'c'), isFalse); + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('heterogeneous and expanded text sizes stay valid and grow bounds', () { + final graph = diamondGraphFixture(); + final baseLayout = layoutFor(graph, extents: layout.heterogeneousExtents()); + final expandedExtents = layout.scaledExtents( + layout.heterogeneousExtents(), + 2.6, + ); + final expandedLayout = layoutFor(graph, extents: expandedExtents); + final edges = graphEdges(graph); + final labels = fixedLabels(edges); + + final base = routeFor( + graph, + extents: layout.heterogeneousExtents(), + labels: labels, + ); + final expanded = routeFor(graph, extents: expandedExtents, labels: labels); + + expectValidRouting(base, baseLayout, extents: labels); + expectValidRouting(expanded, expandedLayout, extents: labels); + expect(expanded.width, greaterThan(base.width)); + expect(expanded.height, greaterThan(base.height)); + }); + + test('unknown and missing targets are skipped with their identity', () { + final graph = incompleteGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = labelsFor(edges); + final routing = routeFor(graph, labels: labels); + + expect(routing.skipped.length, 2); + final skipped = routing.skipped.toList(); + expect(skipped.map((item) => item.reason), [ + RouteSkipReason.unknownTarget, + RouteSkipReason.unknownTarget, + ]); + expect(skipped.map((item) => item.id), [1, 2]); + expect(skipped[0].source, 'a'); + expect(skipped[0].outcome, 'blocked'); + expect(skipped[0].target, ''); + expect(skipped[1].target, 'ghost'); + expect(routing.routes.map((route) => route.id), [3, 4]); + expect(routing.routeFor(1), isNull); + expect(routing.routeFor(2), isNull); + expect(layoutBox.nodeFor('ghost'), isNull); + expectValidRouting(routing, layoutBox, extents: labels); + }); +} diff --git a/app/test/features/graph/routing/graph_routing_geometry_test.dart b/app/test/features/graph/routing/graph_routing_geometry_test.dart new file mode 100644 index 00000000..2fce067a --- /dev/null +++ b/app/test/features/graph/routing/graph_routing_geometry_test.dart @@ -0,0 +1,161 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; +import 'package:pipelines_app/features/graph/routing/graph_edge_routing.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +import 'routing_assertions.dart'; +import 'routing_fixtures.dart'; +import '../layout/layout_fixtures.dart' as layout; + +void main() { + test( + 'wide measured labels move outside the drawing instead of covering it', + () { + final graph = chainGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = fixedLabels(edges, width: 400, height: 40); + final routing = routeFor(graph, labels: labels); + + expect(routing.labels.length, edges.length); + for (final label in routing.labels) { + expect(label.y, greaterThanOrEqualTo(layoutBox.height)); + expect(label.right, lessThanOrEqualTo(routing.width)); + expect(label.bottom, lessThanOrEqualTo(routing.height)); + } + expect(routing.height, greaterThan(layoutBox.height)); + expectValidRouting(routing, layoutBox, extents: labels); + }, + ); + + test('tight gaps and expanded extents keep the same guarantees', () { + for (final gap in [8, 24, 80]) { + for (final scale in [1, 2.6]) { + final extents = layout.scaledExtents( + layout.heterogeneousExtents(), + scale, + ); + final layoutBox = layoutFor( + diamondGraphFixture(), + extents: extents, + config: routingLayoutConfig(columnGap: gap, rowGap: 16), + ); + final edges = graphEdges(diamondGraphFixture()); + final labels = labelsFor(edges); + final routing = routeFor( + diamondGraphFixture(), + extents: extents, + labels: labels, + layoutConfig: routingLayoutConfig(columnGap: gap, rowGap: 16), + ); + expectValidRouting(routing, layoutBox, extents: labels); + } + } + }); + + test('a three-stage cycle keeps every same-rank corridor distinct', () { + final graph = cycleThreeGraph(); + final layoutBox = layoutFor( + graph, + config: routingLayoutConfig(columnGap: 8), + ); + final edges = graphEdges(graph); + final labels = labelsFor(edges); + final routing = routeFor( + graph, + labels: labels, + layoutConfig: routingLayoutConfig(columnGap: 8), + ); + + expect(routing.routes.length, 3); + expect( + routing.routes.every((route) => route.kind == RouteKind.sameRank), + isTrue, + ); + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('a caller-supplied backward rank routes around the target column', () { + final layoutBox = GraphLayout( + nodes: [ + const GraphNodeBox( + key: 'a', + terminal: false, + stageIndex: 0, + rank: 1, + x: 208, + y: 8, + width: 120, + height: 60, + ), + const GraphNodeBox( + key: 'b', + terminal: false, + stageIndex: 1, + rank: 0, + x: 8, + y: 8, + width: 120, + height: 60, + ), + ], + ranks: {'a': 1, 'b': 0}, + rankCount: 2, + width: 336, + height: 76, + ); + final edge = GraphEdge( + id: 1, + source: 'a', + outcome: 'success', + target: 'b', + label: 'success', + fallback: false, + knownTarget: true, + ); + final labels = {1: LabelExtent(width: 52, height: 18)}; + final routing = routeGraphEdges( + layout: layoutBox, + edges: [edge], + labelExtents: labels, + config: routingConfig(), + ); + + final route = routing.routes.single; + expect(route.kind, RouteKind.back); + expect(route.sourcePort.side, RoutePortSide.right); + expect(route.targetPort.side, RoutePortSide.right); + expect(route.straight, isFalse); + expect(route.points.length, greaterThan(4)); + expect(routing.width, greaterThan(layoutBox.width)); + expectValidRouting(routing, layoutBox, extents: labels); + }); + + test('a self loop and forward routes share one valid layout', () { + final graph = selfLoopGraphFixture(); + final layoutBox = layoutFor(graph); + final labels = labelsFor(graphEdges(graph)); + final routing = routeFor(graph, labels: labels); + + expect(routing.routes.length, 4); + expect(routing.routes.map((route) => route.kind).toSet(), { + RouteKind.forward, + RouteKind.selfLoop, + }); + final loop = routing.routes.singleWhere( + (route) => route.kind == RouteKind.selfLoop, + ); + expect(loop.source, 'a'); + expect(loop.target, 'a'); + expect(loop.sourcePort.point.y, isNot(loop.targetPort.point.y)); + expect( + routing.routes + .where((route) => route.target == successEnd) + .every((route) => route.targetPort.side == RoutePortSide.left), + isTrue, + ); + expectValidRouting(routing, layoutBox, extents: labels); + }); +} diff --git a/app/test/features/graph/routing/graph_routing_validation_test.dart b/app/test/features/graph/routing/graph_routing_validation_test.dart new file mode 100644 index 00000000..7d548748 --- /dev/null +++ b/app/test/features/graph/routing/graph_routing_validation_test.dart @@ -0,0 +1,222 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/routing/graph_edge_routing.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +import 'routing_fixtures.dart'; + +GraphEdge _edge({ + int id = 1, + String source = 'a', + String target = 'b', + String outcome = 'success', + bool knownTarget = true, +}) { + return GraphEdge( + id: id, + source: source, + outcome: outcome, + target: target, + label: outcome, + fallback: false, + knownTarget: knownTarget, + ); +} + +void main() { + test('an empty graph has empty routes and the layout bounds', () { + final layoutBox = layoutFor({'stages': []}); + final routing = routeGraphEdges( + layout: layoutBox, + edges: const [], + labelExtents: const {}, + config: routingConfig(), + ); + + expect(routing.isEmpty, isTrue); + expect(routing.routes, isEmpty); + expect(routing.labels, isEmpty); + expect(routing.skipped, isEmpty); + expect(routing.width, layoutBox.width + routingConfig().boundsPadding); + expect(routing.height, layoutBox.height + routingConfig().boundsPadding); + }); + + test('unknown endpoints become diagnostics, never invented nodes', () { + final layoutBox = layoutFor(chainGraphFixture()); + final edges = [ + _edge(id: 1, source: 'missing', target: 's0'), + _edge(id: 2, source: 's0', target: 'ghost'), + _edge(id: 3, source: 's0', target: '', knownTarget: false), + ]; + final routing = routeGraphEdges( + layout: layoutBox, + edges: edges, + labelExtents: const {}, + config: routingConfig(), + ); + + expect(routing.routes, isEmpty); + expect(routing.skipped.map((item) => item.reason), [ + RouteSkipReason.unknownSource, + RouteSkipReason.unknownTarget, + RouteSkipReason.unknownTarget, + ]); + expect(routing.skipped.map((item) => item.id), [1, 2, 3]); + expect(layoutBox.nodeFor('missing'), isNull); + expect(layoutBox.nodeFor('ghost'), isNull); + }); + + test('routed edges require measured label extents', () { + final graph = diamondGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = labelsFor(edges)..remove(edges.first.id); + + expect( + () => routeGraphEdges( + layout: layoutBox, + edges: edges, + labelExtents: labels, + config: routingConfig(), + ), + throwsArgumentError, + ); + }); + + test('extra label extents are ignored and duplicate ids are rejected', () { + final graph = diamondGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = labelsFor(edges)..[999] = LabelExtent(width: 10, height: 10); + final routing = routeGraphEdges( + layout: layoutBox, + edges: edges, + labelExtents: labels, + config: routingConfig(), + ); + expect(routing.routes.length, edges.length); + expect(routing.labelFor(999), isNull); + + expect( + () => routeGraphEdges( + layout: layoutBox, + edges: [edges.first, edges.first], + labelExtents: labelsFor(edges), + config: routingConfig(), + ), + throwsArgumentError, + ); + }); + + test('invalid configuration and label extents are rejected', () { + expect( + () => RoutingConfig( + nodeClearance: -1, + laneSpacing: 10, + corridorSpacing: 10, + portSpacing: 8, + labelGap: 2, + ), + throwsArgumentError, + ); + expect( + () => RoutingConfig( + nodeClearance: 2, + laneSpacing: 0, + corridorSpacing: 10, + portSpacing: 8, + labelGap: 2, + ), + throwsArgumentError, + ); + expect( + () => RoutingConfig( + nodeClearance: 2, + laneSpacing: 10, + corridorSpacing: double.nan, + portSpacing: 8, + labelGap: 2, + ), + throwsArgumentError, + ); + expect( + () => LabelExtent(width: double.infinity, height: 10), + throwsArgumentError, + ); + expect(() => LabelExtent(width: 10, height: -1), throwsArgumentError); + }); + + test('the same input produces equal immutable results', () { + final graph = diamondGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = labelsFor(edges); + final config = routingConfig(); + + final first = routeGraphEdges( + layout: layoutBox, + edges: edges, + labelExtents: labels, + config: config, + ); + final second = routeGraphEdges( + layout: layoutBox, + edges: edges, + labelExtents: labels, + config: config, + ); + + expect(first.routes, second.routes); + expect(first.labels, second.labels); + expect(first.skipped, second.skipped); + expect(first.width, second.width); + expect(first.height, second.height); + expect(() => first.routes.add(first.routes.first), throwsUnsupportedError); + expect( + () => first.routes.first.points.add(const RoutePoint(0, 0)), + throwsUnsupportedError, + ); + expect(() => first.labels.add(first.labels.first), throwsUnsupportedError); + expect( + () => first.skipped.add( + const RouteDiagnostic( + id: 1, + source: 'a', + outcome: 'success', + target: 'b', + reason: RouteSkipReason.unknownTarget, + message: '', + ), + ), + throwsUnsupportedError, + ); + }); + + test('edges are routed in definition id order regardless of input order', () { + final graph = diamondGraphFixture(); + final layoutBox = layoutFor(graph); + final edges = graphEdges(graph); + final labels = labelsFor(edges); + final forward = routeGraphEdges( + layout: layoutBox, + edges: edges, + labelExtents: labels, + config: routingConfig(), + ); + final reversed = routeGraphEdges( + layout: layoutBox, + edges: edges.reversed.toList(), + labelExtents: labels, + config: routingConfig(), + ); + + expect(reversed.routes, forward.routes); + expect(reversed.labels, forward.labels); + expect(reversed.width, forward.width); + expect(reversed.height, forward.height); + expect( + forward.routes.map((route) => route.id), + edges.map((edge) => edge.id), + ); + }); +} diff --git a/app/test/features/graph/routing/routing_assertions.dart b/app/test/features/graph/routing/routing_assertions.dart new file mode 100644 index 00000000..c524fa30 --- /dev/null +++ b/app/test/features/graph/routing/routing_assertions.dart @@ -0,0 +1,215 @@ +import 'dart:math' as math; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +const double _epsilon = 1e-9; + +/// Checks the routing guarantees every fixture must satisfy. +void expectValidRouting( + GraphRouting routing, + GraphLayout layout, { + Map? extents, +}) { + expect(routing.width.isFinite, isTrue); + expect(routing.height.isFinite, isTrue); + expect(routing.width, greaterThan(0)); + expect(routing.height, greaterThan(0)); + + for (final route in routing.routes) { + _expectRoute(route, layout, routing.width, routing.height); + _expectNoNodeInterior(route, layout); + } + expectDistinctCorridors(routing.routes); + + final byId = { + for (final label in routing.labels) label.edgeId: label, + }; + expect(byId.length, routing.labels.length, reason: 'one label per edge'); + for (final route in routing.routes) { + final label = byId[route.id]; + expect(label, isNotNull, reason: 'edge ${route.id} has a label'); + final extent = extents?[route.id]; + if (extent != null) { + expect(label!.width, extent.width); + expect(label.height, extent.height); + } + expect(label!.x, greaterThanOrEqualTo(-_epsilon)); + expect(label.y, greaterThanOrEqualTo(-_epsilon)); + expect(label.right, lessThanOrEqualTo(routing.width + _epsilon)); + expect(label.bottom, lessThanOrEqualTo(routing.height + _epsilon)); + for (final node in layout.nodes) { + expect( + _overlaps( + label.x, + label.y, + label.width, + label.height, + node.x, + node.y, + node.width, + node.height, + ), + isFalse, + reason: 'label for edge ${route.id} overlaps node ${node.key}', + ); + } + } + for (var first = 0; first < routing.labels.length; first += 1) { + for (var second = first + 1; second < routing.labels.length; second += 1) { + final a = routing.labels[first]; + final b = routing.labels[second]; + expect( + _overlaps(a.x, a.y, a.width, a.height, b.x, b.y, b.width, b.height), + isFalse, + reason: 'labels for edges ${a.edgeId} and ${b.edgeId} overlap', + ); + } + } + + for (final skipped in routing.skipped) { + expect(routing.routeFor(skipped.id), isNull); + expect(routing.labelFor(skipped.id), isNull); + } +} + +void expectDistinctCorridors(List routes) { + for (var first = 0; first < routes.length; first += 1) { + for (var second = first + 1; second < routes.length; second += 1) { + final a = routes[first]; + final b = routes[second]; + for (var ai = 1; ai < a.points.length; ai += 1) { + final a0 = a.points[ai - 1]; + final a1 = a.points[ai]; + for (var bi = 1; bi < b.points.length; bi += 1) { + final b0 = b.points[bi - 1]; + final b1 = b.points[bi]; + if (a0.x == a1.x && b0.x == b1.x && a0.x == b0.x) { + final aLo = math.min(a0.y, a1.y); + final aHi = math.max(a0.y, a1.y); + final bLo = math.min(b0.y, b1.y); + final bHi = math.max(b0.y, b1.y); + expect( + aLo < bHi - _epsilon && bLo < aHi - _epsilon, + isFalse, + reason: 'edges ${a.id} and ${b.id} share a vertical corridor', + ); + } + if (a0.y == a1.y && b0.y == b1.y && a0.y == b0.y) { + final aLo = math.min(a0.x, a1.x); + final aHi = math.max(a0.x, a1.x); + final bLo = math.min(b0.x, b1.x); + final bHi = math.max(b0.x, b1.x); + expect( + aLo < bHi - _epsilon && bLo < aHi - _epsilon, + isFalse, + reason: 'edges ${a.id} and ${b.id} share a horizontal run', + ); + } + } + } + } + } +} + +void _expectRoute( + EdgeRoute route, + GraphLayout layout, + double width, + double height, +) { + expect(route.points.length, greaterThanOrEqualTo(2)); + expect(route.points.first, route.sourcePort.point); + expect(route.points.last, route.targetPort.point); + for (var index = 0; index < route.points.length; index += 1) { + final point = route.points[index]; + expect(point.x.isFinite, isTrue); + expect(point.y.isFinite, isTrue); + expect(point.x, greaterThanOrEqualTo(-_epsilon)); + expect(point.y, greaterThanOrEqualTo(-_epsilon)); + expect(point.x, lessThanOrEqualTo(width + _epsilon)); + expect(point.y, lessThanOrEqualTo(height + _epsilon)); + if (index > 0) { + final previous = route.points[index - 1]; + expect( + previous.x == point.x || previous.y == point.y, + isTrue, + reason: 'edge ${route.id} segment ${index - 1} is not orthogonal', + ); + expect(previous, isNot(point), reason: 'zero-length segment'); + } + } + _expectPort(route.sourcePort, layout.nodeFor(route.source)!); + _expectPort(route.targetPort, layout.nodeFor(route.target)!); +} + +void _expectPort(RoutePort port, GraphNodeBox box) { + switch (port.side) { + case RoutePortSide.right: + expect(port.point.x, closeTo(box.right, _epsilon)); + expect(port.point.y, greaterThanOrEqualTo(box.y - _epsilon)); + expect(port.point.y, lessThanOrEqualTo(box.bottom + _epsilon)); + case RoutePortSide.left: + expect(port.point.x, closeTo(box.x, _epsilon)); + expect(port.point.y, greaterThanOrEqualTo(box.y - _epsilon)); + expect(port.point.y, lessThanOrEqualTo(box.bottom + _epsilon)); + case RoutePortSide.top: + expect(port.point.y, closeTo(box.y, _epsilon)); + expect(port.point.x, greaterThanOrEqualTo(box.x - _epsilon)); + expect(port.point.x, lessThanOrEqualTo(box.right + _epsilon)); + case RoutePortSide.bottom: + expect(port.point.y, closeTo(box.bottom, _epsilon)); + expect(port.point.x, greaterThanOrEqualTo(box.x - _epsilon)); + expect(port.point.x, lessThanOrEqualTo(box.right + _epsilon)); + } +} + +void _expectNoNodeInterior(EdgeRoute route, GraphLayout layout) { + for (var index = 1; index < route.points.length; index += 1) { + final a = route.points[index - 1]; + final b = route.points[index]; + for (final node in layout.nodes) { + if (a.y == b.y) { + final left = math.min(a.x, b.x); + final right = math.max(a.x, b.x); + final crosses = + a.y > node.y + _epsilon && + a.y < node.bottom - _epsilon && + right > node.x + _epsilon && + left < node.right - _epsilon; + expect( + crosses, + isFalse, + reason: 'edge ${route.id} crosses node ${node.key} horizontally', + ); + } else { + final top = math.min(a.y, b.y); + final bottom = math.max(a.y, b.y); + final crosses = + a.x > node.x + _epsilon && + a.x < node.right - _epsilon && + bottom > node.y + _epsilon && + top < node.bottom - _epsilon; + expect( + crosses, + isFalse, + reason: 'edge ${route.id} crosses node ${node.key} vertically', + ); + } + } + } +} + +bool _overlaps( + double ax, + double ay, + double aw, + double ah, + double bx, + double by, + double bw, + double bh, +) { + return ax < bx + bw && ax + aw > bx && ay < by + bh && ay + ah > by; +} diff --git a/app/test/features/graph/routing/routing_fixtures.dart b/app/test/features/graph/routing/routing_fixtures.dart new file mode 100644 index 00000000..7a155b03 --- /dev/null +++ b/app/test/features/graph/routing/routing_fixtures.dart @@ -0,0 +1,143 @@ +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; +import 'package:pipelines_app/features/graph/layout/graph_node_layout.dart'; +import 'package:pipelines_app/features/graph/layout/layout_models.dart'; +import 'package:pipelines_app/features/graph/routing/graph_edge_routing.dart'; +import 'package:pipelines_app/features/graph/routing/route_models.dart'; + +import '../layout/layout_fixtures.dart' as layout; +import '../domain/graph_fixtures.dart' as domain; + +/// Definitions, measured extents and configs shared by the routing tests. + +GraphLayoutConfig routingLayoutConfig({ + double columnGap = 80, + double rowGap = 16, + double padding = 8, +}) { + return GraphLayoutConfig( + columnGap: columnGap, + rowGap: rowGap, + padding: padding, + ); +} + +RoutingConfig routingConfig({ + double nodeClearance = 8, + double laneSpacing = 28, + double corridorSpacing = 20, + double portSpacing = 12, + double labelGap = 4, + double boundsPadding = 4, +}) { + return RoutingConfig( + nodeClearance: nodeClearance, + laneSpacing: laneSpacing, + corridorSpacing: corridorSpacing, + portSpacing: portSpacing, + labelGap: labelGap, + boundsPadding: boundsPadding, + ); +} + +GraphLayout layoutFor( + Map graph, { + Map? extents, + GraphLayoutConfig? config, +}) { + final nodes = graphNodes(graph); + return layoutGraphNodes( + nodes: nodes, + edges: graphEdges(graph), + extents: extents ?? layout.uniformExtents(nodes), + config: config ?? routingLayoutConfig(), + ); +} + +/// Measured label boxes sized from their text, as a renderer would supply them. +Map labelsFor( + Iterable edges, { + double charWidth = 7, + double padding = 12, + double height = 18, +}) { + return { + for (final edge in edges) + edge.id: LabelExtent( + width: edge.label.length * charWidth + padding, + height: height, + ), + }; +} + +/// One box per edge at an explicit size, used for wide-label checks. +Map fixedLabels( + Iterable edges, { + double width = 52, + double height = 18, +}) { + return { + for (final edge in edges) + edge.id: LabelExtent(width: width, height: height), + }; +} + +GraphRouting routeFor( + Map graph, { + Map? extents, + Map? labels, + GraphLayoutConfig? layoutConfig, + RoutingConfig? config, +}) { + final layout = layoutFor(graph, extents: extents, config: layoutConfig); + final edges = graphEdges(graph); + return routeGraphEdges( + layout: layout, + edges: edges, + labelExtents: labels ?? labelsFor(edges), + config: config ?? routingConfig(), + ); +} + +/// Three outcomes from `a` to the same target `b`, then `b` to Success. +Map parallelOutcomesGraph() => { + 'stages': [ + domain.stage( + 'a', + edges: { + 'success': 'b', + 'approved': 'b', + 'rejected': 'b', + }, + ), + domain.stage('b', edges: {'success': '#success'}), + ], +}; + +/// A single stage that retries itself and has no terminal pair. +Map selfLoopOnlyGraph() => { + 'stages': [ + domain.stage('a', edges: {'retry': 'a'}), + ], +}; + +Map chainGraphFixture() => layout.chainGraph(4); + +Map diamondGraphFixture() => layout.diamondGraphFixture(); + +Map cycleGraphFixture() => layout.cycleGraph(); + +Map selfLoopGraphFixture() => layout.selfLoopGraphFixture(); + +Map disconnectedGraphFixture() => layout.disconnectedGraph(); + +Map incompleteGraphFixture() => + layout.incompleteGraphFixture(); + +/// Three stages in one strongly connected component with no terminals. +Map cycleThreeGraph() => { + 'stages': [ + domain.stage('a', edges: {'success': 'b'}), + domain.stage('b', edges: {'success': 'c'}), + domain.stage('c', edges: {'success': 'a'}), + ], +};