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/notes/A1a.md b/app/notes/A1a.md new file mode 100644 index 00000000..c25715f9 --- /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. +- **Not committed.** The stage instruction forbids commit/push/deploy, so the + candidate is uncommitted in the working tree. The Land stage commits the + reviewed candidate. 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'); + }); + }); +}