android: preserve run summary title and changes work

This commit is contained in:
2026-10-18 15:06:45 +01:00
parent c78c6ca4ff
commit 94a22c46d7
9 changed files with 1537 additions and 44 deletions
@@ -0,0 +1,512 @@
package net.awan.pipelines.ui.changes
import android.view.WindowManager
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.QuestionMark
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalClipboardManager
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.compose.ui.window.DialogWindowProvider
import net.awan.pipelines.ui.chat.DiffKind
import net.awan.pipelines.ui.chat.diffLineColor
import net.awan.pipelines.ui.chat.diffLineSymbol
import net.awan.pipelines.ui.components.RunState
import net.awan.pipelines.ui.components.RunStatusPalette
import net.awan.pipelines.ui.components.copyText
import net.awan.pipelines.ui.components.paneSafeArea
import net.awan.pipelines.ui.theme.ICON_INLINE_DP
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_M
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XL
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.SPACING_XXS
import net.awan.pipelines.ui.theme.pipelinesText
/**
* The run summary's Changes section body: the observed-file list plus the honest
* capture notes. It is a non-lazy [Column] of rows so it nests safely inside the
* summary's single `LazyColumn` (the artifacts gallery does the same), and it
* renders the same [ChangeFileRow] for every file, tapping any row open into
* [ChangeDiffViewer].
*
* The whole section is read-only evidence of the workspace the run changed; the
* wording never claims the model authored a change.
*/
@Composable
internal fun ChangeFileList(
changes: RunChanges,
modifier: Modifier = Modifier,
) {
val text = pipelinesText()
var openIndex by remember(changes) { mutableStateOf(NO_OPEN_FILE) }
Column(
modifier = modifier.fillMaxWidth().padding(horizontal = SPACING_L, vertical = SPACING_S),
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
) {
Text(changesListSummary(changes), style = text.label, color = MaterialTheme.colorScheme.primary)
val note = runChangesNote(changes)
if (note.isNotBlank()) Text(note, style = text.meta)
if (changes.isEmpty) {
Text(noChangeDetail(changes), style = text.meta)
} else {
Column(Modifier.fillMaxWidth()) {
changes.files.forEachIndexed { index, entry ->
ChangeFileRow(entry = entry, onClick = { openIndex = index })
}
}
}
}
if (openIndex in changes.files.indices) {
ChangeDiffViewer(
files = changes.files,
index = openIndex,
onIndexChange = { openIndex = it },
onDismiss = { openIndex = NO_OPEN_FILE },
)
}
}
/** No file is open in the changes viewer. */
private const val NO_OPEN_FILE = -1
/** Why no change is listed: a pending capture, an unavailable one, or a recorded none. */
private fun noChangeDetail(changes: RunChanges): String = when {
changes.pending -> "The capture runs after the stage finishes; nothing is recorded yet."
changes.unavailable -> "The workspace snapshot could not be compared, so no changes can be shown."
changes.stepsWithChanges == 0 ->
"This run recorded no change capture (a historical step, or a stage that does not capture)."
else -> "The captured snapshots were identical: the workspace was unchanged."
}
/**
* One file in the changes list: a kind glyph, the path in monospace, the `+N -M`
* stat, the read-me-first tags, and the stage(s) that changed it. Tapping opens
* the diff viewer on this file, whose location is confirmed by its position there.
*/
@Composable
private fun ChangeFileRow(entry: FileChangeEntry, onClick: () -> Unit) {
val text = pipelinesText()
val stat = changeStat(entry.added, entry.removed)
Row(
modifier = Modifier
.fillMaxWidth()
.clickable(role = Role.Button, onClick = onClick, onClickLabel = "Open ${entry.path}")
.padding(vertical = SPACING_XS),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
) {
Icon(
imageVector = changeKindIcon(entry.kind),
contentDescription = changeKindLabel(entry.kind),
tint = changeKindTint(entry.kind),
modifier = Modifier.size(ICON_INLINE_DP),
)
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(SPACING_XXS)) {
Text(
entry.path,
style = text.mono,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
Text(changeRowMeta(entry), style = text.meta, maxLines = 2, overflow = TextOverflow.Ellipsis)
}
if (stat.isNotBlank()) {
Row(horizontalArrangement = Arrangement.spacedBy(SPACING_S)) {
if (entry.added > 0) StatText("+${entry.added}", RunStatusPalette.of(RunState.Succeeded).color)
if (entry.removed > 0) StatText("-${entry.removed}", RunStatusPalette.of(RunState.Failed).color)
}
}
}
}
/** The row's secondary line: which stage(s) changed it, and how to read the entry. */
internal fun changeRowMeta(entry: FileChangeEntry): String = buildString {
append("changed by ")
append(entry.steps.joinToString(" → "))
changeEntryTags(entry).forEach { append(" · $it") }
if (entry.modeChanged && !entry.binary) {
append(" · mode ${entry.beforeMode.orEmpty()}→${entry.afterMode.orEmpty()}")
}
}
/** One side of a file's stat, monospace in the app's success/failure hue. */
@Composable
private fun StatText(value: String, color: Color) {
Text(
text = value,
style = MaterialTheme.typography.labelMedium.copy(fontFamily = FontFamily.Monospace),
color = color,
)
}
/** The glyph for a file's recorded kind, so the list reads at a glance. */
internal fun changeKindIcon(kind: ChangeKind): ImageVector = when (kind) {
ChangeKind.Added -> Icons.Default.Add
ChangeKind.Modified -> Icons.Default.Edit
ChangeKind.Deleted -> Icons.Default.Delete
ChangeKind.Other -> Icons.Default.QuestionMark
}
/** The tint for a file's kind: added green, deleted red, anything else neutral. */
@Composable
private fun changeKindTint(kind: ChangeKind): Color = when (kind) {
ChangeKind.Added -> RunStatusPalette.of(RunState.Succeeded).color
ChangeKind.Deleted -> RunStatusPalette.of(RunState.Failed).color
else -> MaterialTheme.colorScheme.onSurfaceVariant
}
/** The two forms one file's change can be read in. */
private enum class ChangeViewForm { Rendered, Raw }
/**
* The full-screen diff viewer for one changed file. It pages through the run's
* changed files exactly as the artifact viewer pages through a gallery's media
* (one shared index, previous/next affordances, Back/the close button dismissing),
* and it shows both forms the brief requires, switchable from one control row:
*
* - **Rendered** — the file header with its `+N -M` stat, then each hunk's `@@`
* header, the added/removed/context colouring and the old/new line numbers,
* through the app's one diff language.
* - **Raw patch** — the server's unified patch verbatim in monospace, so the
* operator can read the exact evidence alongside the rendered reading.
*
* A file the server could not give a patch for (binary, truncated, or a capture
* that recorded none) shows the honest reason in place of a diff rather than a
* fabricated one. Nothing here claims authorship: it reports the workspace change
* the server observed.
*/
@Composable
internal fun ChangeDiffViewer(
files: List<FileChangeEntry>,
index: Int,
onIndexChange: (Int) -> Unit,
onDismiss: () -> Unit,
) {
val entry = files.getOrNull(index) ?: return
var form by remember(entry.path) { mutableStateOf(ChangeViewForm.Rendered) }
Dialog(
onDismissRequest = onDismiss,
properties = DialogProperties(usePlatformDefaultWidth = false, decorFitsSystemWindows = false),
) {
// Stretch the dialog window over the whole display (behind the status bar
// and navigation bar), exactly as the artifact viewer does. Without a
// bounded window height a weighted child measures its full content and
// pushes the page row off-screen; MATCH_PARENT gives the body the space
// that remains, so the header, the form switch, the diff body and the
// page controls are all on screen.
val dialogWindow = (LocalView.current.parent as? DialogWindowProvider)?.window
SideEffect {
dialogWindow?.setLayout(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
)
}
Box(Modifier.fillMaxSize().windowInsetsPadding(paneSafeArea())) {
Column(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.background),
) {
ChangeViewerHeader(entry = entry, index = index, count = files.size, onDismiss = onDismiss)
// The form switch and the file pager share one control row: the
// Rendered/Raw choice on the left, the previous/next file
// affordances on the right, so moving between files never depends
// on the diff body's height.
ChangeViewerControls(
entry = entry,
form = form,
onSelect = { form = it },
hasPrevious = index > 0,
hasNext = index < files.lastIndex,
onPrevious = { onIndexChange((index - 1).coerceAtLeast(0)) },
onNext = { onIndexChange((index + 1).coerceAtMost(files.lastIndex)) },
)
ChangeViewerBody(
entry = entry,
form = form,
modifier = Modifier.weight(1f),
)
}
}
}
}
/** The open file: its kind, path, stat, position, stages and the close affordance. */
@Composable
private fun ChangeViewerHeader(
entry: FileChangeEntry,
index: Int,
count: Int,
onDismiss: () -> Unit,
) {
val text = pipelinesText()
val clipboard = LocalClipboardManager.current
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L, vertical = SPACING_M),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
) {
Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(SPACING_XXS)) {
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
) {
Icon(
imageVector = changeKindIcon(entry.kind),
contentDescription = null,
tint = changeKindTint(entry.kind),
modifier = Modifier.size(ICON_INLINE_DP),
)
Text(
changeKindLabel(entry.kind).replaceFirstChar { it.uppercase() },
style = text.label,
color = changeKindTint(entry.kind),
)
if (changeStat(entry.added, entry.removed).isNotBlank()) {
Text(changeStat(entry.added, entry.removed), style = text.mono)
}
}
Text(entry.path, style = text.mono, maxLines = 2, overflow = TextOverflow.Ellipsis)
Text(
"${changePositionLabel(index, count)} · changed by ${entry.steps.joinToString(" → ")}",
style = text.meta,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
)
}
IconButton(
onClick = { entry.patch?.takeIf { it.isNotBlank() }?.let { clipboard.copyText(it) } },
enabled = !entry.patch.isNullOrBlank(),
) {
Icon(Icons.Default.ContentCopy, contentDescription = "Copy raw patch for ${entry.path}")
}
IconButton(onClick = onDismiss) {
Icon(Icons.Default.Close, contentDescription = "Close diff")
}
}
}
/**
* The Rendered/Raw switch and the file pager in one control row: each form is a
* labelled control whose selected form is disabled and emphasised, so the
* operator can always see which reading is open, and the previous/next
* affordances page through the run's changed files, disabled exactly at the ends.
* Keeping the pager in this row (rather than a bottom band) means moving between
* files never depends on the diff body's height.
*/
@Composable
private fun ChangeViewerControls(
entry: FileChangeEntry,
form: ChangeViewForm,
onSelect: (ChangeViewForm) -> Unit,
hasPrevious: Boolean,
hasNext: Boolean,
onPrevious: () -> Unit,
onNext: () -> Unit,
) {
val text = pipelinesText()
Row(
modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L, vertical = SPACING_XS),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(SPACING_S),
) {
TextButton(onClick = { onSelect(ChangeViewForm.Rendered) }, enabled = form != ChangeViewForm.Rendered) {
Text("Rendered", style = if (form == ChangeViewForm.Rendered) text.body else text.label)
}
TextButton(
onClick = { onSelect(ChangeViewForm.Raw) },
enabled = !entry.patch.isNullOrBlank(),
) {
Text("Raw patch", style = if (form == ChangeViewForm.Raw) text.body else text.label)
}
Spacer(Modifier.weight(1f))
IconButton(onClick = onPrevious, enabled = hasPrevious) {
Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Previous file")
}
IconButton(onClick = onNext, enabled = hasNext) {
Icon(Icons.AutoMirrored.Filled.ArrowForward, contentDescription = "Next file")
}
}
}
/** The open file's body in the chosen form, or the honest reason a diff cannot be shown. */
@Composable
private fun ChangeViewerBody(entry: FileChangeEntry, form: ChangeViewForm, modifier: Modifier = Modifier) {
when {
entry.binary || entry.patch.isNullOrBlank() -> HonestMessage(
if (entry.binary) {
"This is a binary file: the server recorded the change but has no textual diff to show."
} else {
patchUnavailableReason(entry)
},
modifier,
)
form == ChangeViewForm.Raw -> Column(
modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(SPACING_L),
) {
Text(entry.patch.orEmpty(), style = pipelinesText().mono, modifier = Modifier.fillMaxWidth())
}
else -> Column(
modifier
.fillMaxWidth()
.verticalScroll(rememberScrollState())
.padding(SPACING_L),
verticalArrangement = Arrangement.spacedBy(SPACING_M),
) {
val parsed = remember(entry.patch) { parseUnifiedPatch(entry.patch) }
ChangeDiffStat(parsed)
if (entry.truncated) {
Text(
"The server truncated this patch at its capture limit; the raw text is the whole record.",
style = pipelinesText().meta,
)
}
parsed.hunks.forEach { hunk -> HunkView(hunk) }
}
}
}
/** A centred honest explanation where a diff cannot be rendered. */
@Composable
private fun HonestMessage(message: String, modifier: Modifier = Modifier) {
Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(message, style = pipelinesText().meta, modifier = Modifier.padding(SPACING_XL))
}
}
/** Why a file has no patch to render, in the entry's own recorded terms. */
internal fun patchUnavailableReason(entry: FileChangeEntry): String = when {
entry.truncated -> "The server truncated this file's patch at its capture limit; no diff text was recorded."
entry.otherModeChange ->
"Only the file's mode changed (${entry.beforeMode.orEmpty()}→${entry.afterMode.orEmpty()}); the server recorded no text diff."
else -> "The server recorded this change without a patch."
}
/** The file's `+N -M` stat line above the rendered hunks. */
@Composable
private fun ChangeDiffStat(parsed: FileDiff) {
val text = pipelinesText()
Row(horizontalArrangement = Arrangement.spacedBy(SPACING_S)) {
if (parsed.added > 0) StatText("+${parsed.added}", RunStatusPalette.of(RunState.Succeeded).color)
if (parsed.removed > 0) StatText("-${parsed.removed}", RunStatusPalette.of(RunState.Failed).color)
if (parsed.added == 0 && parsed.removed == 0) Text("no line changes recorded", style = text.meta)
}
}
/**
* One `@@` hunk: its header, then its numbered lines. Each line is drawn with the
* app's shared diff symbols and colours ([diffLineSymbol]/[diffLineColor], the
* same the chat's edit card uses), preceded by its old/new gutter numbers, so the
* changes viewer and the chat diff are one renderer rather than two.
*/
@Composable
private fun HunkView(hunk: ChangeHunk) {
val text = pipelinesText()
Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(SPACING_XXS)) {
Text(
hunk.header,
style = text.mono,
color = MaterialTheme.colorScheme.primary,
modifier = Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.surfaceContainerHigh)
.padding(horizontal = SPACING_XS, vertical = SPACING_XXS),
)
val gutter = remember(hunk) { gutterWidth(hunk) }
Column(
Modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.surfaceContainer)
.horizontalScroll(rememberScrollState())
.padding(vertical = SPACING_XS),
) {
hunk.lines.forEach { line -> NumberedDiffLine(line, gutter) }
}
}
}
/** The widest line number in a hunk, so its gutter lines up across every row. */
internal fun gutterWidth(hunk: ChangeHunk): Int =
(hunk.lines.maxOfOrNull { maxOf(it.oldLine, it.newLine) } ?: 1).toString().length
/**
* One rendered diff line: the old/new gutter numbers (blank on the side a line
* has no number, and on a `\ No newline` annotation) and the marked content.
*/
@Composable
private fun NumberedDiffLine(line: ChangeLine, gutter: Int) {
val text = pipelinesText()
val kind = line.kind.toDiffKind()
Row(horizontalArrangement = Arrangement.spacedBy(SPACING_S)) {
Text(
text = if (line.noNewlineMarker) {
" ".repeat(gutter * 2 + 1)
} else {
gutterText(line.oldLine, gutter) + " " + gutterText(line.newLine, gutter)
},
style = text.meta,
maxLines = 1,
)
Text(
text = "${diffLineSymbol(kind)} ${line.text}",
style = text.mono,
color = diffLineColor(kind),
)
}
}
/** One gutter number padded to [width]; 0 means no number on that side. */
private fun gutterText(value: Int, width: Int): String =
if (value <= 0) " ".repeat(width) else value.toString().padStart(width)
/** A parsed line's kind in the app's shared diff vocabulary. */
internal fun ChangeLineKind.toDiffKind(): DiffKind = when (this) {
ChangeLineKind.Add -> DiffKind.ADD
ChangeLineKind.Remove -> DiffKind.REMOVE
ChangeLineKind.Context -> DiffKind.CONTEXT
}
@@ -0,0 +1,411 @@
package net.awan.pipelines.ui.changes
import java.util.Locale
import net.awan.pipelines.data.protocol.FileChange
import net.awan.pipelines.data.protocol.RunStep
import net.awan.pipelines.data.protocol.StageFileChanges
/**
* The kind of observed file change the server recorded, mirroring
* `internal/protocol/runs.go` FileChange.Kind (added|modified|deleted). An
* unrecognised or blank kind stays [Other] rather than being guessed, so a
* future server value is shown read-only instead of mislabelled.
*/
enum class ChangeKind { Added, Modified, Deleted, Other }
/** Maps the server's kind token to [ChangeKind]; never invents one. Pure. */
internal fun changeKind(kind: String): ChangeKind = when (kind.trim().lowercase(Locale.US)) {
"added" -> ChangeKind.Added
"modified" -> ChangeKind.Modified
"deleted" -> ChangeKind.Deleted
else -> ChangeKind.Other
}
/** The word a file's kind is named by in the list and the diff header. */
internal fun changeKindLabel(kind: ChangeKind): String = when (kind) {
ChangeKind.Added -> "added"
ChangeKind.Modified -> "modified"
ChangeKind.Deleted -> "deleted"
ChangeKind.Other -> "changed"
}
/** Which kind of line this is within a unified patch. */
enum class ChangeLineKind { Context, Add, Remove }
/**
* One line of a parsed unified patch, with the old/new line numbers a rendered
* diff gutter shows (0 where the line has no number on that side: an added line
* has no old number, a removed line no new one, a `\ No newline` marker neither).
* [text] is the line's content without its leading marker; [noNewlineMarker] marks
* the `\ No newline at end of file` annotation so a renderer draws no numbers for
* it.
*/
internal data class ChangeLine(
val kind: ChangeLineKind,
val text: String,
val oldLine: Int = 0,
val newLine: Int = 0,
val noNewlineMarker: Boolean = false,
)
/** One `@@` hunk: the server's own header plus its parsed lines. */
internal data class ChangeHunk(
val header: String,
val oldStart: Int,
val oldCount: Int,
val newStart: Int,
val newCount: Int,
val lines: List<ChangeLine>,
)
/**
* A parsed unified patch for one file: the raw text exactly as the server
* recorded it ([raw], the thing the raw view shows verbatim), the file header
* lines the patch carried, the parsed [hunks], and the true `+N -M` stat counted
* from the hunk body (never from the header text, so a relocated header cannot
* misstate the change).
*/
internal data class FileDiff(
val raw: String,
val headerLines: List<String>,
val hunks: List<ChangeHunk>,
val added: Int,
val removed: Int,
)
/**
* Parses a server-recorded unified patch into hunks, lines, line numbers and
* the true `+N -M` stat. The server builds these patches with a Go unified-diff
* writer (internal/filediff), so the shape is a standard `---`/`+++` header,
* optional metadata lines, `@@ -a,b +c,d @@` hunk headers and a ` `/`+`/`-`
* body. Anything unrecognised (a truncated tail, an exotic header) is carried
* verbatim in [FileDiff.headerLines] when it sits before the first hunk, and
* otherwise skipped, so the raw view always has the exact source while the
* rendered view shows only lines it can stand behind. A blank patch parses to an
* empty [FileDiff] rather than a fabricated one.
*/
internal fun parseUnifiedPatch(patch: String?): FileDiff {
val text = patch.orEmpty()
if (text.isBlank()) return FileDiff(raw = "", headerLines = emptyList(), hunks = emptyList(), added = 0, removed = 0)
val rawLines = text.split("\n")
val headers = ArrayList<String>()
val hunks = ArrayList<ChangeHunk>()
var current: HunkBuilder? = null
for (line in rawLines) {
val hunkStart = parseHunkHeader(line)
when {
hunkStart != null -> {
current?.let { hunks += it.build() }
current = HunkBuilder(line, hunkStart.oldStart, hunkStart.oldCount, hunkStart.newStart, hunkStart.newCount)
}
current == null -> headers += line
else -> current.lines += parseBodyLine(line, current)
}
}
current?.let { hunks += it.build() }
val added = hunks.sumOf { hunk -> hunk.lines.count { it.kind == ChangeLineKind.Add } }
val removed = hunks.sumOf { hunk -> hunk.lines.count { it.kind == ChangeLineKind.Remove } }
return FileDiff(raw = text, headerLines = headers, hunks = hunks, added = added, removed = removed)
}
/**
* Mutable accumulator for one hunk as it is parsed, carrying the running old/new
* line counters so each body line gets its gutter numbers without a second pass.
*/
private class HunkBuilder(
val header: String,
val oldStart: Int,
val oldCount: Int,
val newStart: Int,
val newCount: Int,
) {
val lines = ArrayList<ChangeLine>()
private var oldLine = oldStart
private var newLine = newStart
fun build(): ChangeHunk = ChangeHunk(
header = header,
oldStart = oldStart,
oldCount = oldCount,
newStart = newStart,
newCount = newCount,
lines = lines,
)
fun nextOld(): Int = oldLine++
fun nextNew(): Int = newLine++
}
/**
* The parsed `@@ -oldStart,oldCount +newStart,newCount @@` of a hunk header, or
* null when [line] is not one. A missing count defaults to 1 (the unified-diff
* rule) so a single-line hunk header is still read exactly. Pure.
*/
private fun parseHunkHeader(line: String): HunkStart? {
if (!line.startsWith("@@")) return null
val end = line.indexOf("@@", 2)
if (end < 0) return null
val ranges = tokenizeRanges(line.substring(2, end)) ?: return null
return HunkStart(ranges[0], ranges[1], ranges[2], ranges[3])
}
private data class HunkStart(val oldStart: Int, val oldCount: Int, val newStart: Int, val newCount: Int)
/** The four numbers of a hunk header's range text, or null when malformed. Pure. */
private fun tokenizeRanges(body: String): List<Int>? {
val old = body.substringBefore('+')
val new = body.substringAfter('+', "")
if (old.isEmpty() || new.isEmpty()) return null
val oldRange = parseRange(old) ?: return null
val newRange = parseRange(new) ?: return null
return listOf(oldRange.first, oldRange.second, newRange.first, newRange.second)
}
/** One `-start,count` / `+start,count` side of a hunk header. Pure. */
private fun parseRange(text: String): Pair<Int, Int>? {
val trimmed = text.trim().removePrefix("-").removePrefix("+")
if (trimmed.isEmpty()) return null
val start = trimmed.substringBefore(',').trim().toIntOrNull() ?: return null
val countText = trimmed.substringAfter(',', "").trim()
val count = if (countText.isEmpty()) 1 else countText.toIntOrNull() ?: return null
return start to count
}
/** One body line of a hunk, tagged and numbered from [builder]'s counters. */
private fun parseBodyLine(line: String, builder: HunkBuilder): ChangeLine = when {
line.startsWith("+") -> ChangeLine(ChangeLineKind.Add, line.substring(1), oldLine = 0, newLine = builder.nextNew())
line.startsWith("-") -> ChangeLine(ChangeLineKind.Remove, line.substring(1), oldLine = builder.nextOld(), newLine = 0)
line.startsWith("\\") -> ChangeLine(ChangeLineKind.Context, line, noNewlineMarker = true)
line.startsWith(" ") -> ChangeLine(ChangeLineKind.Context, line.substring(1), oldLine = builder.nextOld(), newLine = builder.nextNew())
line.isEmpty() -> ChangeLine(ChangeLineKind.Context, "", oldLine = builder.nextOld(), newLine = builder.nextNew())
// A truncated tail or an unexpected marker: keep the text, don't number it.
else -> ChangeLine(ChangeLineKind.Context, line)
}
/**
* One file the run changed, aggregated across the steps that changed it. A file
* touched by several steps appears once; [steps] names every stage that changed
* it (in the run's step order), so the section can say which stage(s) did.
*
* [added]/[removed] sum the patches the server actually recorded for this path.
* [binary] is true when any step recorded it as binary, [truncated] when any
* step's patch was truncated (or omitted), and [otherModeChange] when the mode
* changed without the content — all of which the viewer states plainly rather
* than rendering a diff it does not have.
*/
internal data class FileChangeEntry(
val path: String,
val kind: ChangeKind,
val added: Int,
val removed: Int,
val binary: Boolean,
val truncated: Boolean,
val beforeMode: String?,
val afterMode: String?,
val otherModeChange: Boolean,
val steps: List<String>,
val patch: String?,
) {
/** True when a patch the operator can read is present. */
val hasPatch: Boolean get() = !patch.isNullOrBlank() && !binary
/** True when the recorded permissions differ and no content change explains it. */
val modeChanged: Boolean get() = beforeMode != null && afterMode != null && beforeMode != afterMode
/** The number of stages that changed this file. */
val stepCount: Int get() = steps.size
}
/**
* The Changes disclosure's entire state, derived purely from the run's steps.
*
* It aggregates every stage step's observed `file_changes` capture: a path
* changed by several steps appears once ([files]), each carrying the stages that
* changed it, and the totals describe the recorded patches. The capture's own
* honesty flags are preserved: [unavailable] when a step's snapshot could not be
* compared, [partial] when a capture was incomplete, truncated or omitted,
* [pending] when nothing has been recorded yet, and [diagnostic] the server's own
* explanation. [status] is the one-line summary the collapsed section shows.
*/
internal data class RunChanges(
val files: List<FileChangeEntry>,
val stepsWithChanges: Int,
val stepsPending: Int,
val added: Int,
val removed: Int,
val partial: Boolean,
val unavailable: Boolean,
val pending: Boolean,
val skipped: Int,
val omitted: Int,
val diagnostic: String,
) {
val fileCount: Int get() = files.size
/** No recorded change of any kind: the section states so rather than showing an empty list. */
val isEmpty: Boolean get() = files.isEmpty()
}
/** A file is captured as binary when either side of the snapshot was binary. */
private fun binaryOf(change: FileChange): Boolean = change.binary
/**
* Aggregates a run's stage steps into its Changes state. Pure and total over its
* input: a null `file_changes` on a step is a historical (or non-capturing) step
* and contributes nothing (it is not "no changes"); a present capture with no
* files is a real, observed no-change. Files are keyed by path and keep first-seen
* order, so a path several steps changed is one entry naming all of them.
*/
internal fun runChanges(steps: List<RunStep>): RunChanges {
val entries = LinkedHashMap<String, FileChangeEntry>()
var stepsWithChanges = 0
var stepsPending = 0
var partial = false
var unavailable = false
var skipped = 0
var omitted = 0
val diagnostics = LinkedHashSet<String>()
for (step in steps) {
val changes = step.fileChanges
if (changes == null) {
if (step.status == "running" || step.status == "waiting") stepsPending++
continue
}
stepsWithChanges++
if (changes.status == "unavailable") unavailable = true
if (changes.status == "partial") partial = true
if (!changes.diagnostic.isNullOrBlank()) diagnostics += changes.diagnostic.orEmpty().trim()
skipped += changes.skipped
omitted += changes.omitted
val stage = step.stage.ifBlank { "stage" }
for (file in changes.files) {
if (file.path.isBlank()) continue
val kind = changeKind(file.kind)
val parsed = parseUnifiedPatch(file.patch)
val existing = entries[file.path]
val mergedSteps = buildList {
if (existing != null) addAll(existing.steps)
if (stage !in this) add(stage)
}
val entry = FileChangeEntry(
path = file.path,
// A later step wins the kind: it is the observed state the run left.
kind = if (existing == null || kind != ChangeKind.Other) kind else existing.kind,
added = (existing?.added ?: 0) + parsed.added,
removed = (existing?.removed ?: 0) + parsed.removed,
binary = (existing?.binary == true) || file.binary,
truncated = (existing?.truncated == true) || file.truncated,
// Keep the first-seen before-mode and the last-seen after-mode, so the
// pair describes the run's net effect on the file.
beforeMode = existing?.beforeMode ?: file.beforeMode,
afterMode = file.afterMode ?: existing?.afterMode,
otherModeChange = (existing?.otherModeChange == true) ||
(file.beforeMode != null && file.afterMode != null &&
file.beforeMode != file.afterMode && !file.binary && parsed.added == 0 && parsed.removed == 0),
steps = mergedSteps,
patch = file.patch?.takeIf { it.isNotBlank() } ?: existing?.patch,
)
entries[file.path] = entry
}
}
val files = entries.values.toList()
val pending = stepsWithChanges == 0 && stepsPending > 0
val totalPartial = partial || files.any { it.truncated } || omitted > 0
return RunChanges(
files = files,
stepsWithChanges = stepsWithChanges,
stepsPending = stepsPending,
added = files.sumOf { it.added },
removed = files.sumOf { it.removed },
partial = totalPartial,
unavailable = unavailable,
pending = pending,
skipped = skipped,
omitted = omitted,
diagnostic = diagnostics.joinToString(" "),
)
}
/**
* The Changes section header's one-line summary: the observed file count, the
* total `+N -M`, and the honest capture caveats. Wording never implies the
* server proved authorship — it reports the workspace change it observed. A run
* with no recorded change, an unavailable capture and a still-running one each
* say exactly that rather than showing a fabricated zero.
*/
internal fun runChangesHeader(changes: RunChanges): String {
if (changes.unavailable) return "Changes · capture unavailable"
if (changes.isEmpty) {
return when {
changes.pending -> "Changes · capture pending"
changes.stepsWithChanges == 0 -> "Changes · not recorded for this run"
else -> "Changes · no changes observed"
}
}
val stat = changeStat(changes.added, changes.removed)
val label = if (stat.isBlank()) {
"${changes.fileCount} ${if (changes.fileCount == 1) "file" else "files"} changed"
} else {
"${changes.fileCount} ${if (changes.fileCount == 1) "file" else "files"} changed · $stat"
}
return if (changes.partial) "$label · partial capture" else label
}
/**
* The honest one-line note under the header for a capture that is not complete,
* or "" when the capture was. The wording distinguishes an unavailable capture, a
* partial one (with its counts) and a capture that has recorded nothing yet.
*/
internal fun runChangesNote(changes: RunChanges): String = when {
changes.unavailable -> changes.diagnostic.ifBlank {
"The workspace snapshot could not be compared; the changes below may be incomplete."
}
changes.isEmpty -> ""
else -> buildString {
if (changes.partial) {
append("Partial capture: some changes may be missing.")
val caveats = ArrayList<String>()
if (changes.skipped > 0) caveats += "${changes.skipped} files skipped"
if (changes.omitted > 0) caveats += "${changes.omitted} omitted"
val truncated = changes.files.count { it.truncated }
if (truncated > 0) caveats += "$truncated truncated"
if (caveats.isNotEmpty()) append(" (" + caveats.joinToString(", ") + ")")
if (changes.diagnostic.isNotBlank()) append(" ${changes.diagnostic}")
}
}.trim()
}
/** The `+N -M` stat, or "" when both counts are zero. Shared by the header and a file row. */
internal fun changeStat(added: Int, removed: Int): String = buildString {
if (added > 0) append("+$added")
if (removed > 0) {
if (isNotEmpty()) append(" ")
append("-$removed")
}
}
/**
* The tags shown beside a file row: the traits that change how the entry must be
* read (binary, truncated, a mode-only change), never a fabricated diff.
*/
internal fun changeEntryTags(entry: FileChangeEntry): List<String> = buildList {
if (entry.binary) add("binary")
if (entry.truncated) add("truncated")
if (entry.otherModeChange && !entry.binary) add("mode change")
}
/**
* The file list's own summary line: the observed file count and the aggregate
* stat, with the same ambiguity-free wording as the header.
*/
internal fun changesListSummary(changes: RunChanges): String {
val count = "${changes.fileCount} ${if (changes.fileCount == 1) "file" else "files"} changed"
val stat = changeStat(changes.added, changes.removed)
return if (stat.isBlank()) count else "$count · $stat"
}
/** The `N of M` position label the viewer shows for its open file. Pure. */
internal fun changePositionLabel(index: Int, count: Int): String = "${index + 1} of $count"
@@ -14,6 +14,7 @@ import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import net.awan.pipelines.ui.components.CODE_BLOCK_MAX_HEIGHT
@@ -38,6 +39,30 @@ internal fun DiffStat(diff: ToolDiff) {
}
}
/**
* The gutter symbol one [DiffKind] is drawn with, the app's one spelling of the
* unified-diff marker (`+`/`-`/space). Shared by the chat's edit card and the run
* summary's changes viewer, so the two renderers never disagree about what a kind
* looks like. Pure.
*/
internal fun diffLineSymbol(kind: DiffKind): String = when (kind) {
DiffKind.ADD -> "+"
DiffKind.REMOVE -> "-"
DiffKind.CONTEXT -> " "
}
/**
* The colour one [DiffKind] is drawn in: the app's success hue for an addition,
* its failure hue for a removal and the secondary on-surface role for context.
* The one place a diff line's colour is decided, shared by every renderer.
*/
@Composable
internal fun diffLineColor(kind: DiffKind): Color = when (kind) {
DiffKind.ADD -> RunStatusPalette.of(RunState.Succeeded).color
DiffKind.REMOVE -> RunStatusPalette.of(RunState.Failed).color
DiffKind.CONTEXT -> MaterialTheme.colorScheme.onSurfaceVariant
}
/**
* The unified diff body of an edit card: line-by-line monospace with `+`/`-`
* gutter symbols and the app's success/failure hues, bounded so a long diff
@@ -45,9 +70,6 @@ internal fun DiffStat(diff: ToolDiff) {
*/
@Composable
internal fun DiffView(diff: ToolDiff) {
val added = RunStatusPalette.of(RunState.Succeeded).color
val removed = RunStatusPalette.of(RunState.Failed).color
val context = MaterialTheme.colorScheme.onSurfaceVariant
Card(
modifier = Modifier.fillMaxWidth(),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surfaceContainer),
@@ -73,15 +95,10 @@ internal fun DiffView(diff: ToolDiff) {
)
}
diff.lines.forEach { line ->
val (symbol, color) = when (line.kind) {
DiffKind.ADD -> "+" to added
DiffKind.REMOVE -> "-" to removed
DiffKind.CONTEXT -> " " to context
}
Text(
text = "$symbol ${line.text}",
text = "${diffLineSymbol(line.kind)} ${line.text}",
style = pipelinesText().mono,
color = color,
color = diffLineColor(line.kind),
)
}
}
@@ -17,6 +17,9 @@ import androidx.compose.ui.text.style.TextOverflow
import net.awan.pipelines.data.protocol.RunDetail
import net.awan.pipelines.ui.ArtifactGroup
import net.awan.pipelines.ui.RUN_VIEW_TITLE_LINES
import net.awan.pipelines.ui.changes.ChangeFileList
import net.awan.pipelines.ui.changes.runChanges
import net.awan.pipelines.ui.changes.runChangesHeader
import net.awan.pipelines.ui.components.CodeBlock
import net.awan.pipelines.ui.components.DetailTabBody
import net.awan.pipelines.ui.components.KeyValueRow
@@ -35,6 +38,8 @@ import net.awan.pipelines.ui.runLabel
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SPACING_XS
import net.awan.pipelines.ui.theme.SUMMARY_SECTION_GAP
import net.awan.pipelines.ui.theme.SUMMARY_TOP_SPACING
import net.awan.pipelines.ui.theme.pipelinesText
import net.awan.pipelines.ui.visitCount
@@ -58,53 +63,50 @@ internal fun RunSummaryTab(
) {
val text = pipelinesText()
val state = runStateOf(run.status)
// The artifacts section starts collapsed and its expand/collapse choice is
// remembered/saved per run id, so a different run reseeds it and a run opened
// fresh starts collapsed. Both the header and the gallery read the same
// snapshot, so they can never disagree.
val artifactsExpansion = rememberSectionExpansion(run.id)
// One expansion state for the summary's collapsible sections (artifacts and
// Changes), keyed by their own stable section keys. It is remembered/saved per
// run id, so a different run reseeds it and a run opened fresh starts with
// both sections collapsed.
val sections = rememberSectionExpansion(run.id)
// The artifacts header and body read the same snapshot, so they can never
// disagree.
val artifactsHeader = remember(run.steps, run.executing) {
runArtifactsHeader(run.steps, run.executing)
}
// The Changes section is derived from the same step snapshot the artifacts
// header is, once per data change: a path several steps changed is aggregated
// to one entry naming every stage, and the total `+N -M` describes the patches
// the server actually recorded (never a model's claim).
val changes = remember(run.steps) { runChanges(run.steps) }
DetailTabBody(wide, modifier) { columnModifier ->
LazyColumn(
modifier = columnModifier,
contentPadding = pillContentPadding(PaddingValues(vertical = SPACING_L)),
// The leading clearance belongs to the identity block below, so the
// title sits off the app bar by the screen's standard top spacing
// rather than by whatever the list happens to add; the trailing
// reserve still comes from the shared pill helper.
contentPadding = pillContentPadding(
PaddingValues(top = SUMMARY_TOP_SPACING, bottom = SPACING_L),
),
) {
// The artifacts gallery still leads the summary, but inside one
// collapsed section: its header alone carries the run's capture
// wording until the operator expands it, and expanding reveals the
// unchanged gallery (nothing when no artifacts were recorded).
collapsibleSection(
title = artifactsHeader,
key = SUMMARY_ARTIFACTS_KEY,
expanded = artifactsExpansion.isExpanded(SUMMARY_ARTIFACTS_KEY),
onToggle = { artifactsExpansion.toggle(SUMMARY_ARTIFACTS_KEY) },
) {
if (artifactGroups.isNotEmpty()) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = SPACING_L, vertical = SPACING_S),
) {
ArtifactGallery(
groups = artifactGroups,
configuredServerUrl = configuredServerUrl,
fetchArtifactBytes = fetchArtifactBytes,
selection = selection,
onSelectionChange = onSelectionChange,
)
}
}
}
// The run's identity leads the summary: the operator reads what the
// run is called before anything else. The block keeps the standard
// top spacing above it and the standard section gap below it, so the
// title is neither jammed against the app bar nor glued to the
// artifacts section that follows.
item(key = "run-summary") {
Column(
modifier = Modifier.fillMaxWidth().padding(horizontal = SPACING_L),
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = SPACING_L)
.padding(bottom = SUMMARY_SECTION_GAP),
verticalArrangement = Arrangement.spacedBy(SPACING_XS),
) {
// The run view's own copy of the title: the operator must be
// able to read what the run is called, so it is never elided -
// it wraps over as many lines as it needs. The compact app-bar
// it wraps over as many lines as it needs and clips rather
// than ellipsises. Nothing here shortens it: the title is
// already as long as the server stores it. The compact app-bar
// copy above stays a one-line label for context while this
// scrollable, complete one is what the operator reads.
Text(
@@ -142,6 +144,42 @@ internal fun RunSummaryTab(
CodeBlock("Diagnostic", run.diagnostic, Modifier.padding(top = SPACING_S))
}
}
// The artifacts section follows the identity block, in one
// collapsed section: its header alone carries the run's capture
// wording until the operator expands it, and expanding reveals the
// unchanged gallery (nothing when no artifacts were recorded).
collapsibleSection(
title = artifactsHeader,
key = SUMMARY_ARTIFACTS_KEY,
expanded = sections.isExpanded(SUMMARY_ARTIFACTS_KEY),
onToggle = { sections.toggle(SUMMARY_ARTIFACTS_KEY) },
) {
if (artifactGroups.isNotEmpty()) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = SPACING_L, vertical = SPACING_S),
) {
ArtifactGallery(
groups = artifactGroups,
configuredServerUrl = configuredServerUrl,
fetchArtifactBytes = fetchArtifactBytes,
selection = selection,
onSelectionChange = onSelectionChange,
)
}
}
}
// Changes follows artifacts with its own stable disclosure key. Its
// header names the observed file count and total stat while collapsed.
collapsibleSection(
title = runChangesHeader(changes),
key = SUMMARY_CHANGES_KEY,
expanded = sections.isExpanded(SUMMARY_CHANGES_KEY),
onToggle = { sections.toggle(SUMMARY_CHANGES_KEY) },
) {
ChangeFileList(changes = changes)
}
}
}
}
@@ -164,3 +202,8 @@ private fun RunDurationRow(run: RunDetail) {
// is remembered consistently (it is namespaced under the summary tab's saved
// state and reseeded by run id).
private const val SUMMARY_ARTIFACTS_KEY = "artifacts"
// The run summary's changes section key: its own stable key, so the Changes
// disclosure's expand/collapse choice is remembered separately from the artifacts
// section's under the same per-run saved state.
private const val SUMMARY_CHANGES_KEY = "changes"
@@ -271,3 +271,22 @@ internal val CHAT_COMMAND_LIST_MAX_HEIGHT = 240.dp
* up to read history stops the view moving under them.
*/
internal val CHAT_FOLLOW_THRESHOLD_DP = 32.dp
// ---- Run summary (ui/screens/RunSummaryTab.kt) ------------------------------
/**
* Clearance above the run summary's leading identity block (the run's own title
* and its facts). The summary leads with that block, so this is what keeps the
* title off the app bar; it is the screen's standard top padding ([SPACING_L]),
* named here so the title's clearance is a deliberate choice rather than an
* accident of the scroll container's own padding. Applied as the scroll
* content's own top padding.
*/
internal val SUMMARY_TOP_SPACING = SPACING_L
/**
* The gap between the run summary's identity block and the artifacts section
* that follows it, so the title block and the section header are not glued
* together. The app's standard block-to-block step ([SPACING_S]).
*/
internal val SUMMARY_SECTION_GAP = SPACING_S
@@ -1,5 +1,10 @@
package net.awan.pipelines.ui
import java.io.File
import net.awan.pipelines.ui.theme.SPACING_L
import net.awan.pipelines.ui.theme.SPACING_S
import net.awan.pipelines.ui.theme.SUMMARY_SECTION_GAP
import net.awan.pipelines.ui.theme.SUMMARY_TOP_SPACING
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -12,6 +17,11 @@ import org.junit.Test
* run-context line) clamp. The budgets are pinned here so a change to one is a
* deliberate, reviewed decision and the run view can never become the most
* generous place by accident.
*
* Two source-scan cases also pin where the run view's own title is rendered: the
* summary must lead with it, give it its own top spacing and section gap, and
* apply the complete budget with `Clip` — so the rule survives in the pixels,
* not only in the constant.
*/
class RunTitlesTest {
@@ -35,4 +45,75 @@ class RunTitlesTest {
assertTrue("a list row may not outlive the run view", RUN_ROW_TITLE_LINES < RUN_VIEW_TITLE_LINES)
assertTrue("a stage context line may not outlive the run view", STAGE_RUN_LABEL_LINES < RUN_VIEW_TITLE_LINES)
}
/**
* The budget is only real where the operator reads it: the run summary must
* render its own title with the complete budget and clip rather than
* ellipsise, so no edit can quietly leave the summary eliding its title while
* the budget above still says it may not. A source scan keeps this honest
* without a device, the same way `CollapseRemovalTest` and `DimensTest` scan
* sources.
*/
@Test
fun theRunSummaryRendersItsTitleWithTheCompleteBudgetAndClip() {
val source = summarySource()
assertTrue(
"the run summary's title must take the complete line budget",
source.contains("maxLines = RUN_VIEW_TITLE_LINES"),
)
assertTrue(
"the run summary's title must clip rather than ellipsise",
source.contains("overflow = TextOverflow.Clip"),
)
}
/**
* The summary leads with the run's identity: the title block is emitted
* before the artifacts section, and it owns the screen's top spacing and the
* section gap so it is neither jammed against the app bar nor glued to the
* section header below it.
*/
@Test
fun theRunSummaryLeadsWithItsTitleAndGivesItItsOwnSpacing() {
val source = summarySource()
val summary = source.indexOf("item(key = \"run-summary\")")
val artifacts = source.indexOf("title = artifactsHeader")
assertTrue("could not find the summary's identity item", summary >= 0)
assertTrue("could not find the artifacts section", artifacts >= 0)
assertTrue(
"the summary's title must lead before the artifacts section",
summary < artifacts,
)
assertTrue(
"the summary's title must take the screen's top spacing",
source.contains("top = SUMMARY_TOP_SPACING"),
)
assertTrue(
"the summary's title block must be separated from the artifacts section",
source.contains("bottom = SUMMARY_SECTION_GAP"),
)
}
/**
* Those two spacings are the app's own standard steps rather than numbers
* this screen invented: the leading clearance is the standard screen padding
* ([SPACING_L]) and the section gap is the standard stack step ([SPACING_S]),
* so the layout the scan above pins cannot quietly drift onto a value only
* the summary uses.
*/
@Test
fun theRunSummarySpacingUsesTheAppsStandardSteps() {
assertEquals(SPACING_L, SUMMARY_TOP_SPACING)
assertEquals(SPACING_S, SUMMARY_SECTION_GAP)
}
private fun summarySource(): String {
val candidates = listOf(
"src/main/java/net/awan/pipelines/ui/screens/RunSummaryTab.kt",
"app/src/main/java/net/awan/pipelines/ui/screens/RunSummaryTab.kt",
).map { File(System.getProperty("user.dir"), it) }
val source = candidates.firstOrNull { it.isFile }
assertTrue("could not locate RunSummaryTab.kt from ${System.getProperty("user.dir")}: $candidates", source != null)
return source!!.readText()
}
}
@@ -0,0 +1,346 @@
package net.awan.pipelines.ui.changes
import net.awan.pipelines.data.protocol.FileChange
import net.awan.pipelines.data.protocol.RunStep
import net.awan.pipelines.data.protocol.StageFileChanges
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* The run summary's Changes model: the unified-patch parse (hunks, gutters,
* numbered lines, the true `+N -M`), the run-level aggregation across steps, and
* every honest state (binary, truncated, partial/unavailable capture, a recorded
* none, a historical null). Pure, so it is asserted without a device.
*/
class RunChangesTest {
private val patch = """
--- "a/a.txt"
+++ "b/a.txt"
@@ -1,3 +1,4 @@
one
-two
+TWO
three
+four
""".trimIndent()
@Test
fun parseUnifiedPatchReadsHunksLinesLineNumbersAndStat() {
val diff = parseUnifiedPatch(patch)
assertEquals(listOf("--- \"a/a.txt\"", "+++ \"b/a.txt\""), diff.headerLines)
assertEquals(1, diff.hunks.size)
val hunk = diff.hunks[0]
assertEquals("@@ -1,3 +1,4 @@", hunk.header)
assertEquals(1, hunk.oldStart)
assertEquals(3, hunk.oldCount)
assertEquals(1, hunk.newStart)
assertEquals(4, hunk.newCount)
assertEquals(2, diff.added)
assertEquals(1, diff.removed)
assertEquals(
listOf(
ChangeLine(ChangeLineKind.Context, "one", oldLine = 1, newLine = 1),
ChangeLine(ChangeLineKind.Remove, "two", oldLine = 2),
ChangeLine(ChangeLineKind.Add, "TWO", newLine = 2),
ChangeLine(ChangeLineKind.Context, "three", oldLine = 3, newLine = 3),
ChangeLine(ChangeLineKind.Add, "four", newLine = 4),
),
hunk.lines,
)
}
@Test
fun parseUnifiedPatchReadsSeveralHunksAndDefaultsAMissingCount() {
val diff = parseUnifiedPatch(
"""
--- a/a.txt
+++ b/a.txt
@@ -1 +1 @@
-old
+new
@@ -8,2 +10,2 @@
eight
-nine
+NINE
""".trimIndent(),
)
assertEquals(2, diff.hunks.size)
// A missing count is one line, per the unified-diff rule.
assertEquals(1, diff.hunks[0].oldCount)
assertEquals(1, diff.hunks[0].newCount)
assertEquals(1, diff.hunks[0].oldStart)
// The second hunk numbers from its own header, not the first hunk's end.
assertEquals(10, diff.hunks[1].newStart)
val second = diff.hunks[1].lines
assertEquals(ChangeLine(ChangeLineKind.Context, "eight", oldLine = 8, newLine = 10), second[0])
assertEquals(ChangeLine(ChangeLineKind.Remove, "nine", oldLine = 9), second[1])
assertEquals(ChangeLine(ChangeLineKind.Add, "NINE", newLine = 11), second[2])
assertEquals(2, diff.added)
assertEquals(2, diff.removed)
}
@Test
fun parseUnifiedPatchMarksAMissingNewlineAndDoesNotNumberIt() {
val diff = parseUnifiedPatch(
"""
--- a/a.txt
+++ b/a.txt
@@ -1 +1 @@
-old
\ No newline at end of file
+new
\ No newline at end of file
""".trimIndent(),
)
val lines = diff.hunks[0].lines
assertEquals(2, lines.count { it.noNewlineMarker })
assertTrue(lines.first { it.noNewlineMarker }.noNewlineMarker)
// The marker carries no old/new number, so a renderer draws no gutter for it.
assertEquals(0, lines.first { it.noNewlineMarker }.oldLine)
assertEquals(0, lines.first { it.noNewlineMarker }.newLine)
assertEquals(1, diff.added)
assertEquals(1, diff.removed)
}
@Test
fun parseUnifiedPatchOfADeletionWithAZeroCountHunkHeader() {
// A whole-file deletion: the new side ranges over zero lines.
val diff = parseUnifiedPatch(
"""
--- a/a.txt
+++ /dev/null
@@ -1,2 +0,0 @@
-one
-two
""".trimIndent(),
)
assertEquals(0, diff.added)
assertEquals(2, diff.removed)
assertEquals(0, diff.hunks[0].newCount)
assertEquals(0, diff.hunks[0].newStart)
}
@Test
fun parseUnifiedPatchCountsTheBodyNotTheHeader() {
// A header whose counts disagree with the body must not misstate the stat:
// the `+N -M` is counted from the lines actually present.
val diff = parseUnifiedPatch(
"""
--- a/a.txt
+++ b/a.txt
@@ -1,99 +1,99 @@
-gone
+added
""".trimIndent(),
)
assertEquals(1, diff.added)
assertEquals(1, diff.removed)
}
@Test
fun parseUnifiedPatchIsEmptyForABlankOrMissingPatch() {
assertEquals(FileDiff(raw = "", headerLines = emptyList(), hunks = emptyList(), added = 0, removed = 0), parseUnifiedPatch(null))
assertEquals(FileDiff(raw = "", headerLines = emptyList(), hunks = emptyList(), added = 0, removed = 0), parseUnifiedPatch(" "))
}
@Test
fun kindAndStatHelpersReadTheServersTokens() {
assertEquals(ChangeKind.Added, changeKind("added"))
assertEquals(ChangeKind.Modified, changeKind("MODIFIED"))
assertEquals(ChangeKind.Deleted, changeKind("deleted"))
// An unknown token is never guessed into a real kind.
assertEquals(ChangeKind.Other, changeKind("renamed"))
assertEquals(ChangeKind.Other, changeKind(""))
assertEquals("added", changeKindLabel(ChangeKind.Added))
assertEquals("+3 -2", changeStat(3, 2))
assertEquals("+3", changeStat(3, 0))
assertEquals("-2", changeStat(0, 2))
assertEquals("", changeStat(0, 0))
}
@Test
fun runChangesAggregatesAFileAcrossStepsAndNamesEveryStage() {
val changes = runChanges(
listOf(
step(stage = "implementer", changes = capture(file("a.txt", "modified", patch))),
step(stage = "reviewer", changes = capture(file("a.txt", "modified", patch))),
),
)
assertEquals(1, changes.fileCount)
val file = changes.files.single()
assertEquals("a.txt", file.path)
assertEquals(ChangeKind.Modified, file.kind)
// One entry, both stages, and the stat summed over the two recorded patches.
assertEquals(listOf("implementer", "reviewer"), file.steps)
assertEquals(4, file.added)
assertEquals(2, file.removed)
assertEquals(4, changes.added)
assertEquals(2, changes.removed)
assertEquals("1 file changed · +4 -2", runChangesHeader(changes))
}
@Test
fun runChangesSeedsAndReseedsFileEntriesInFirstSeenOrder() {
val changes = runChanges(
listOf(
step(changes = capture(file("b.txt", "modified", patch), file("a.txt", "added", patch))),
step(stage = "committer", changes = capture(file("c.txt", "deleted", null))),
),
)
assertEquals(listOf("b.txt", "a.txt", "c.txt"), changes.files.map { it.path })
}
@Test
fun aBinaryFileCarriesNoRenderablePatch() {
val changes = runChanges(
listOf(step(changes = capture(FileChange(path = "shot.png", kind = "modified", binary = true)))),
)
val file = changes.files.single()
assertTrue(file.binary)
assertFalse(file.hasPatch)
assertNull(file.patch)
assertTrue("binary" in changeEntryTags(file))
}
@Test
fun aTruncatedPatchIsTaggedAndMakesTheCapturePartial() {
val changes = runChanges(
listOf(step(changes = capture(file("big.kt", "modified", patch, truncated = true)))),
)
assertTrue(changes.files.single().truncated)
assertTrue(changes.partial)
assertTrue("truncated" in changeEntryTags(changes.files.single()))
assertEquals("1 file changed · +2 -1 · partial capture", runChangesHeader(changes))
assertTrue(runChangesNote(changes).startsWith("Partial capture"))
}
@Test
fun aModeOnlyChangeIsReportedWithoutAFabricatedDiff() {
val changes = runChanges(
listOf(
step(
changes = capture(
FileChange(path = "run.sh", kind = "modified", beforeMode = "0644", afterMode = "0755"),
),
),
),
)
val file = changes.files.single()
assertTrue(file.modeChanged)
assertTrue(file.otherModeChange)
assertFalse(file.hasPatch)
assertTrue("mode change" in changeEntryTags(file))
assertTrue(patchUnavailableReason(file).contains("mode"))
}
@Test
fun anAddedFileDoesNotReadAsAModeChange() {
// An added file has no before-mode, so the mode pair must not be flagged.
val changes = runChanges(
listOf(step(changes = capture(FileChange(path = "new.kt", kind = "added", afterMode = "0644", patch = patch)))),
)
assertFalse(changes.files.single().otherModeChange)
assertFalse(changes.files.single().modeChanged)
}
@Test
fun anUnavailableOrPartialCaptureIsReportedHonestly() {
val unavailable = runChanges(
listOf(
step(
changes = StageFileChanges(
status = "unavailable",
diagnostic = "Workspace snapshot unavailable; changes could not be compared.",
),
),
),
)
assertEquals("Changes · capture unavailable", runChangesHeader(unavailable))
assertTrue(runChangesNote(unavailable).contains("could not be compared"))
val partial = runChanges(
listOf(
step(
changes = StageFileChanges(
status = "partial",
skipped = 2,
diagnostic = "Some patches were omitted/truncated by capture limits.",
files = listOf(file("a.txt", "modified", patch, truncated = true)),
),
),
),
)
assertEquals("1 file changed · +2 -1 · partial capture", runChangesHeader(partial))
val note = runChangesNote(partial)
assertTrue(note.contains("2 files skipped"))
assertTrue(note.contains("1 truncated"))
}
@Test
fun aRunWithNoRecordedChangesSaysSoRatherThanShowingAFabricatedDiff() {
// A capture that ran and observed nothing.
assertEquals("Changes · no changes observed", runChangesHeader(runChanges(listOf(step(changes = StageFileChanges(status = "complete"))))))
// A historical step whose capture predates the field (nil) is not "no changes".
assertEquals("Changes · not recorded for this run", runChangesHeader(runChanges(listOf(step(changes = null)))))
// A still-running step that has not captured yet.
assertEquals("Changes · capture pending", runChangesHeader(runChanges(listOf(step(status = "running", changes = null)))))
// Nothing at all.
assertEquals("Changes · not recorded for this run", runChangesHeader(runChanges(emptyList())))
}
@Test
fun theAncillaryHelpersReadConsistently() {
val changes = runChanges(listOf(step(changes = capture(file("a.txt", "modified", patch)))))
assertEquals("1 file changed · +2 -1", changesListSummary(changes))
assertEquals("1 of 3", changePositionLabel(0, 3))
assertEquals("3 of 3", changePositionLabel(2, 3))
assertEquals(0, runChanges(emptyList()).fileCount)
assertTrue(runChanges(emptyList()).isEmpty)
}
@Test
fun gutterWidthFitsTheWidestLineNumberInTheHunk() {
val diff = parseUnifiedPatch(
"""
--- a/a.txt
+++ b/a.txt
@@ -98,3 +98,3 @@
a
-b
+B
""".trimIndent(),
)
assertEquals(2, gutterWidth(diff.hunks.single()))
assertEquals(1, gutterWidth(parseUnifiedPatch(
"""
--- a/a.txt
+++ b/a.txt
@@ -1 +1 @@
-a
+A
""".trimIndent(),
).hunks.single()))
}
// ---- builders ----------------------------------------------------------
private fun step(
stage: String = "implementer",
status: String = "succeeded",
changes: StageFileChanges?,
): RunStep = RunStep(stage = stage, status = status, fileChanges = changes)
private fun capture(vararg files: FileChange): StageFileChanges =
StageFileChanges(status = "complete", files = files.toList())
private fun file(
path: String,
kind: String,
patch: String?,
truncated: Boolean = false,
): FileChange = FileChange(path = path, kind = kind, patch = patch, truncated = truncated)
}
@@ -138,6 +138,15 @@ class ChatFormatTest {
assertNull(toolEditDiff(JsonObject(mapOf("command" to JsonPrimitive("ls")))))
}
@Test
fun theSharedDiffVocabularySpellsEachKindOnce() {
// The one spelling of a unified-diff marker, shared by the chat's edit
// card and the run summary's changes viewer.
assertEquals("+", diffLineSymbol(DiffKind.ADD))
assertEquals("-", diffLineSymbol(DiffKind.REMOVE))
assertEquals(" ", diffLineSymbol(DiffKind.CONTEXT))
}
@Test
fun toolFailedOnlyForTheErrorStatus() {
assertTrue(toolFailed(ChatToolState(status = ChatProtocol.TOOL_ERROR)))
+55
View File
@@ -0,0 +1,55 @@
# Run summary: title spacing, section gap, and the server's title cap
Item: the run summary's title was reported glued to the top of the pane, glued to
the artifacts section, and "cut off". Android-only change (`android/`).
## What changed
- `android/app/src/main/java/net/awan/pipelines/ui/screens/RunSummaryTab.kt`: the
summary now leads with the run's identity block (title, status row, facts) and
the artifacts collapsible section follows it; the identity block carries the
screen's standard top spacing above it and the standard stack step below it.
The title keeps `maxLines = RUN_VIEW_TITLE_LINES` (`Int.MAX_VALUE`) and
`TextOverflow.Clip`.
- `android/app/src/main/java/net/awan/pipelines/ui/theme/Dimens.kt`: two named
tokens, `SUMMARY_TOP_SPACING` (= `SPACING_L`) and `SUMMARY_SECTION_GAP`
(= `SPACING_S`); no new number, no raw `dp` at the call site.
- `android/app/src/test/java/net/awan/pipelines/ui/RunTitlesTest.kt`: the
run-identity/title-line test gained the source-scan cases pinning the title's
budget/`Clip`, the identity block leading the artifacts section, its two
spacing tokens' call sites, and their values.
## Confirmed runtime limitation: a run title is capped at 80 runes by the server
The "cut off" title is not app-side clipping. The app renders the whole string it
is given: `runLabel` (`ui/RunIdentity.kt`) does not shorten a title and the
summary's title line takes `RUN_VIEW_TITLE_LINES = Int.MAX_VALUE` with
`TextOverflow.Clip`. The string itself is bounded before it reaches the app:
- `internal/summarise/summarise.go` defines `TitleCap = 80` runes and applies it
through `capRunes` in `Title` (model-derived), `DeriveTitle` (prompt fallback)
and `ExplicitTitle` (`--title`/rename), so every stored run title is already
capped when the server persists it.
- Evidence (18 Oct 2026): `pipelines inspect 347` returns
`"title": "Two chat UX gaps: the working indicator does not distinguish thinking from waiti"`
— exactly 80 runes, ending mid-word — while that run's input prompt's first line
is 82 runes (`… from waiting`). A `uiautomator` dump of the run summary shows
the same 80-rune string, i.e. the app holds exactly what the server stored.
So a title can end mid-word by design of the server's cap, and no Android change
can render the missing characters. Widening or raising `TitleCap` is a
Pipelines-server change (Go), outside this item's Android-only scope and not
something this item deploys.
## Documentation now stale (for `docs-fold`)
- `android/README.md`, section "Run title readability: whole in the run view, two
lines in the list (17 Oct 2026)" (~line 6278): says the run view "guarantees the
operator can read it whole". It should also state that the stored title is
itself capped at 80 runes by `internal/summarise/summarise.go` (`TitleCap`), so
"whole" means the complete stored title, which can end mid-word; only the app's
own renderer is guaranteed not to shorten it.
- `android/README.md`, section "Collapsible artifacts gallery in the run summary
(16 Oct 2026)" (~line 4130-4136): "The order is unchanged: the artifacts section
still leads the summary and the facts item follows it" is now wrong — the
summary leads with the identity block and the artifacts section follows.