Modernise the workflow graph's visual language

Replace the old terminal-diagram look on the Graph tab with a tonal
surface language, keeping the same information and every outcome hue.

- Nodes: stages are rounded rectangles from MaterialTheme.shapes.medium,
  terminals become pills (height/2). Fills are tonal surfaces via the new
  pure tonalFill(surface, accent, fraction) with a soft outlineVariant
  border instead of a flat fill plus hard outline.
- Type: node names use the cardTitle role and outcome labels the label
  role, with theme line height/letter spacing; the [brackets] and all-caps
  are gone (nodeDisplayLabel renders Success/Failure title-cased in colour).
- Edges: StrokeCap.Round/StrokeJoin.Round, bends rounded by one
  ROUTE_CORNER_RADIUS (cornerCutRadius clamps short segments), filled
  arrowheads scaled as edgeStrokeWidth * ARROW_HEAD_SCALE, and labels on
  a shared DrawScope tonal chip.
- Spacing: named dp tokens instead of ad-hoc literals.

Adds pure-logic unit tests (WorkflowGraphTest, GraphPaletteTest) and
documents the change in android/README.md.

Verified: :app:assembleDebug and :app:testDebugUnitTest both BUILD
SUCCESSFUL (207 tests, 0 failures) with no Kotlin warnings.
This commit is contained in:
2026-10-16 11:50:08 +01:00
parent 8b39c087fd
commit e5bde981ee
4 changed files with 644 additions and 84 deletions
+278 -3
View File
@@ -122,7 +122,17 @@ stops it.
zoom is anchored to the gesture centroid: the pure `zoomAbout` keeps the
content point under the fingers fixed (clamped to `MIN_SCALE`/`MAX_SCALE`) and
the existing pan clamp is applied afterwards, so the content no longer slides
away from the fingers.
away from the fingers. The visual language is a modern surface, not a terminal
diagram: a stage is a rounded rectangle (the theme's `shapes.medium`) and a
terminal a pill, both filled with a tonal surface tinted with the node's
semantic hue behind a soft border (not a flat fill plus hard outline); the node
name and the outcome labels use the app's type scale (`cardTitle`/`label`, no
ad-hoc sizes, no all-caps, terminal `Success`/`Failure` in their own colour);
edges draw with round caps/joins and every right-angle bend is rounded by one
`ROUTE_CORNER_RADIUS` control offset over the unchanged stored polyline, with a
filled arrowhead proportional to its stroke and the outcome label on a rounded
tonal chip rather than raw text over the canvas; node and per-edge-track spacing
are named dp tokens.
- One shared graph-panel height (`collapsedGraphHeight`/`expandedGraphHeight`)
replaces the former 360.dp and 340.dp literals, so both detail screens render
the graph at the same size: about 58% of the window height floored at a height
@@ -1876,8 +1886,10 @@ never installed on or driven).
treats `success` (pass) and `error` (fail) as the emphasised outcomes
(`isPassFailOutcome`). An executed pass/fail edge is drawn at
`PASSFAIL_EDGE_STROKE = 7f` — noticeably heavier than the previous `3f` — with
a stronger, more saturated stroke and a matching `PASSFAIL_ARROW_HEAD_SIZE =
20f` arrowhead, so pass/fail is obvious at a glance and from a distance.
a stronger, more saturated stroke and a filled arrowhead proportional to its
own width (`edgeArrowHeadSize`, i.e. `strokeWidth * ARROW_HEAD_SCALE` with
`ARROW_HEAD_SCALE = 4`: 28f for this 7f pass/fail stroke, 12f for a normal
executed route), so pass/fail is obvious at a glance and from a distance.
- **Other lines stay finer.** Every other executed outcome keeps `EDGE_STROKE =
3f`, and a not-executed edge uses the finer `INACTIVE_EDGE_STROKE = 2.5f`, so
the two emphasised outcomes dominate. No outcome hue changed.
@@ -1952,3 +1964,266 @@ fold (the wide layout was produced with `wm size`/`wm density`); the on-device
captures used the debug build of this source, while the published APK is a clean
rebuild of the same source.
## A modern visual language for the workflow graph (16 Oct 2026)
The graph read like an old terminal diagram (flat fills, hard outlines, sharp
right angles, `[bracketed]` all-caps labels, small arrowheads, raw text over the
canvas). This pass gives it a modern surface language without changing any
information or any hue. `android/` only; no dependency was added (the graph's
corner comes from the theme's own shape scale), no run was started from the app,
and every `adb`/emulator command targeted `emulator-5556` (lane A's
`emulator-5554` was never used; the attached Pixel was never installed on or
driven). The only modified tracked files are the four under `android/` shown in
`git status --short` below; the capture runs also leave untracked scratch
directories at the repo root (`.ui_review*/`), so a bare `git status --short` is
not clean and the "nothing outside `android/` touched" claim is only about the
change itself, not those untracked captures.
- **Nodes are rounded and tonal, terminals are pills.** `WorkflowGraph.kt` reads
`MaterialTheme.shapes.medium` once per composition for a stage's corner and
gives a terminal a full pill (`height/2`), so a terminal is visibly not a stage.
The fill is a *tonal surface*: the new pure `tonalFill(surface, accent,
fraction)` blends a raised `surfaceContainerHigh` with a subtle fraction of the
node's semantic colour (`NEUTRAL_TINT`/`KIND_TINT` for a stage by kind,
`TERMINAL_TINT` for a terminal's success/error hue), and the hard outline is
replaced by a soft `outlineVariant` border (`NODE_BORDER`, strengthened for a
selected stage with `NODE_BORDER_SELECTED`). Every kind's hue survives; the
terminal fill now genuinely tints the outcome hue.
- **Type comes from the app's scale.** The node name uses the app's `cardTitle`
role and the outcome labels its `label` role (no ad-hoc `13.sp`/`11.sp`), with
the theme's own line height and letter spacing; the `[brackets]` and the
all-caps `SUCCESS`/`FAILURE` are gone — the graph shows `Success`/`Failure` in
the terminal's own colour (the new pure `nodeDisplayLabel`; the shared
`GraphSemantics.nodeLabel` the TUI-mirroring panes use is untouched).
- **Edges are smoother, with one control offset and matched arrowheads.** The
stored route is still the axis-aligned polyline (`routePoints`, and its layout
tests, are unchanged), but drawing now rounds every right-angle bend with the
single `ROUTE_CORNER_RADIUS` control offset (the pure `cornerCutRadius` clamps a
short adjacent segment to half its length so two cut-backs can never meet),
uses `StrokeCap.Round`/`StrokeJoin.Round`, and scales the filled arrowhead to
the line with one `ARROW_HEAD_SCALE` (`edgeArrowHeadSize = edgeStrokeWidth *
ARROW_HEAD_SCALE`). Labels sit on a rounded *tonal chip* (`tonalFill` of the
raised surface with the label's own colour) instead of raw text over the canvas.
- **More breathing room, from named tokens.** Node width/height, the horizontal
gap, the graph padding, the per-edge lane spacing and track step, and the
terminal-row gap are now named dp tokens (no inline geometry literals); the
values grew so nodes and the per-edge tracks have visibly more room, and the
collapsed-panel floor grew to `320.dp` to still fit a 4-stage graph with its
terminal row.
- **Nothing semantic changed.** The executed/not-executed structural split (solid
full-colour + arrowhead vs dashed muted + no arrowhead; filled vs hollow/dashed
node), the pass/fail emphasis (heavier, same-hue, more-saturated stroke with the
largest head), the selected-stage invert, ntfy/custom/model kind tints, the
`error*` fallback label, the legend, the active halo/elapsed badge, the flow
dots and the screen-reader description are all kept. `graphColors` and
`outcomeColor` keep their field names, so the Timeline step chips that share
them still agree with the graph.
Verification (macOS, Homebrew JDK 25 `openjdk@25`, Gradle 9.7.1,
`ANDROID_HOME=/Users/alan/Library/Android/sdk`, `--offline`):
- `gradle --offline :app:testDebugUnitTest --rerun-tasks` → `BUILD SUCCESSFUL`;
the test-result XMLs aggregate to **207 tests, 0 failures, 0 errors, 0
skipped** (4 new: `WorkflowGraphTest` for the readable node labels, the
arrowhead proportional to its stroke and the corner-cut clamp, and
`GraphPaletteTest` for `tonalFill`). `compileDebugKotlin` emitted no warnings
(the deprecated `quadraticBezierTo` was replaced by `quadraticTo`).
- `gradle --offline :app:assembleDebug` → `BUILD SUCCESSFUL`; `app-debug.apk` is
**17,928,873 bytes**, sha256
`ba5bcc467989425b69aad2ae70799c0cf4d9eaf54be30243b4631fb7e94916b3`.
- On `emulator-5556` (`FoldB_API_36`, dark mode) against the live server
`ws://10.0.2.2:8080/connect`, driven with `adb shell input` and `uiautomator
dump`. Every capture was written with `android/scripts/capture_png.sh -s
emulator-5556` (validated PNG magic bytes, named display id) into
`~/.local/share/pipelines/data/artifacts/108/1/`. The three cases are a
definition-only graph (pipeline 3 "Plan, implement, review", 4 stages), a
partly executed run (run 94, failed at `committer`: `implementer`/`reviewer`/
`ui_reviewer` and the failed `committer` executed, `Success` not) and its
selected (current) stage. Widths: **wide** 2208x1840 @ density 420 (≈841dp) and **narrow**
1080x1920 @ density 480 (≈360dp); **2x** doubles the pixel size and density
(4416x3680 @840 and 2160x3840 @960), so the same dp layout is rendered at
double the pixels. "Before" is a clean `git archive 8b39c08` tree (never a
working-tree stash) built and installed; "after" is this tree.
- `{before,after}_wide_1x_definition.png`, `{before,after}_wide_2x_definition.png`,
`{before,after}_narrow_1x_definition.png`, `{before,after}_narrow_2x_definition.png`
— the definition graph; before shows `[planner]`/`[FAILURE]` rectangular
nodes with hard 90° routes and raw labels, after shows rounded, tonal nodes,
pill terminals and chipped labels.
- `{before,after}_wide_1x_run.png`, `{before,after}_wide_2x_run.png`,
`{before,after}_narrow_1x_run.png`, `{before,after}_narrow_2x_run.png` — run
94; `implementer`/`reviewer`/`ui_reviewer` were visited and the failed
`committer` was visited too (it was entered and then failed), so all four
stages are filled and the selected `committer` inverts (light `inverseSurface`
fill, solid primary border); the executed `success`/`error` routes are the
boldest lines, and the not-executed `Success` terminal is hollow with a dashed
border (the `Failure` terminal, reached by the executed `error` edge, is
filled). The invert applies only to an *executed* stage; a selected
*not-executed* stage is instead drawn hollow with a dashed primary border
(`drawNodes`' not-executed branch), so selection is legible in either state.
- `{before,after}_{wide,narrow}_{1x,2x}_selected.png` — a 2x crop of the
selected `committer` node (its primary border and rounded shape after vs the
sharper `[committer]` before).
- `compare_wide_1x_definition.png`, `compare_wide_1x_run.png`,
`compare_narrow_1x_definition.png`, `compare_narrow_1x_run.png` — stacked
before/after sheets for the 1x narrow and wide cases.
- `adb -s emulator-5556 logcat -d` contained 0 `FATAL EXCEPTION` and 0 `E
AndroidRuntime` lines after a fresh launch and a Runs/Graph sweep; no run was
started from the app. The emulator's display was reset to its native
2208x1840 @420 afterwards.
- **APK publish.** `app-debug.apk` was copied to
`~/.local/share/pipelines/data/artifacts/108/1/pipelines-debug-wip-8b39c08.apk`
(`8b39c08` = `git rev-parse --short HEAD`); `shasum -a 256` matched. `curl -I
http://10.0.0.249:8080/artifacts/108/1/pipelines-debug-wip-8b39c08.apk` (LAN
address from `ipconfig getifaddr en0`) returned `HTTP/1.1 200 OK`,
`Content-Type: application/vnd.android.package-archive`, `Content-Length:
17928873`, and a streamed `GET | shasum -a 256` returned the same `ba5bcc46…`
as the local file. At 17.1 MiB it exceeds the server's 8 MiB per-file inventory
cap, so it is served by direct URL only.
Not verified in this pass: `:app:lintDebug` (its only reported issues are the two
pre-existing `NewApi` errors for `android:windowLightNavigationBar`); the light
theme; the active/animating halo, elapsed badge and flow dots (the run 94 graph
is a finished run, so it renders settled — those live-run visuals are unchanged
by this pass and are covered by `GraphMotionTest`); a real hardware fold
(narrow/wide were produced with `wm size`/`wm density`); and a greyscale pass (the
executed/not-executed distinction is still structural, but only colour captures
were taken). The crops are derived from the full captures with PIL; the
full-size PNGs above are the primary evidence.
### Review follow-up and re-verification (16 Oct 2026)
A follow-up pass addressed the review findings on the code above. The rendered
surface is unchanged (the token conversion maps the former pixel literals onto the
same device-scaled geometry), and `android/` is still the only modified tree; the
untracked `.ui_review*/` scratch captures at the repo root are not part of it.
- **Duplication.** The two near-identical rounded tonal chips (the edge outcome
labels and the active-stage elapsed badge) are now one
`DrawScope.drawTonalChip(textTopLeft, textSize, color)` helper; both call sites
pass the accent tinted into `labelBackground`, so the chip geometry lives once.
- **Redundant geometry.** `cornerCutRadius` now takes the adjacent segment lengths
the caller has already measured (`cornerCutRadius(inLength, outLength, radius)`),
so `roundedRoutePath` computes each corner's two `hypot`s once instead of twice.
- **Redundant width.** The new pure `arrowHeadSizeFor(strokeWidth)` is the one
arrowhead-from-stroke mapping; `drawEdgePaths` passes the width it has just
computed (`arrowHeadSizeFor(width)`) instead of re-deriving it, and
`edgeArrowHeadSize` delegates to the same function.
- **Geometry tokens.** `ROUTE_CORNER_RADIUS` (`7.dp`) and the chip
`EDGE_CHIP_PAD_X`/`EDGE_CHIP_PAD_Y`/`EDGE_CHIP_CORNER` (`2.dp`/`1.dp`/`2.dp`) are
dp tokens like the rest of the new graph geometry, not raw pixel literals.
Re-run checks (same environment as above):
- `gradle --offline :app:testDebugUnitTest` → `BUILD SUCCESSFUL`; the test-result
XMLs aggregate to **207 tests, 0 failures, 0 errors, 0 skipped** (the
`cornerCutRadius` test now exercises the length-based clamp).
- `gradle --offline :app:compileDebugKotlin --rerun-tasks` → `BUILD SUCCESSFUL`
with no `w:` warnings.
- `gradle --offline :app:assembleDebug --rerun-tasks` → `BUILD SUCCESSFUL`;
`app-debug.apk` is **17,928,873 bytes**, sha256
`ab99e734b0b190294ebfad8d342caf599286cefda23a0faf39f0244496e3af1a`. (A full
`--rerun-tasks` rebuild is byte-reproducible — two consecutive runs produced
this same hash — whereas incremental packaging is not, so the published APK is
the `--rerun-tasks` one.)
- Smoke captures on `emulator-5556` (native 2208x1840 @420) with the rebuilt APK
(`adb -s emulator-5556 install -r app/build/outputs/apk/debug/app-debug.apk`),
written via `android/scripts/capture_png.sh -s emulator-5556`:
`followup_wide_1x_definition.png` (the pipeline 3 definition graph) and
`followup_wide_1x_run106.png` (run 106, all four stages visited) in
`~/.local/share/pipelines/data/artifacts/108/3/`. Both render the rounded tonal
nodes, pill terminals and chipped labels; run 106 shows the executed stages
filled, the selected `committer` inverted (light fill, solid primary border) and
the not-executed `Failure` terminal hollow with a dashed border — the same
structural executed/not-executed split, unchanged. `adb -s emulator-5556 logcat
-d | grep -cE 'FATAL EXCEPTION|E AndroidRuntime'` is `0`; the display was not
resized (still native 2208x1840 @420).
- **APK publish (this pass).** The rebuilt APK was copied to
`~/.local/share/pipelines/data/artifacts/108/3/pipelines-debug-wip-8b39c08.apk`
(`8b39c08` = `git rev-parse --short HEAD`). `curl -I
http://10.0.0.249:8080/artifacts/108/3/pipelines-debug-wip-8b39c08.apk` returned
`HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
`Content-Length: 17928873`, and a streamed `GET | shasum -a 256` returned the
same `ab99e734…` as the local file.
### Second review follow-up (16 Oct 2026)
Two remaining findings on the modernised graph were fixed. The rendered surface is
unchanged — the first is a same-value refactor, the second a doc-only correction —
so the before/after captures above still describe the output.
- **One label colour, not two.** `drawEdgeLabels` declared `accent` and
`textColor` holding the identical value (both `outcomeColor(...)` when the edge
executed, else `colors.labelText`); they are now the single `labelColor`, used for
both the label text and its chip tint. No pixel changes.
- **README cites the live arrowhead token.** The dated "Pass/fail edges" section
cited the removed `PASSFAIL_ARROW_HEAD_SIZE = 20f`; it now describes the current
mapping (`edgeArrowHeadSize` = `strokeWidth * ARROW_HEAD_SCALE`, i.e. 28f
pass/fail and 12f normal), matching `WorkflowGraph.kt`.
Re-verified (Homebrew `openjdk@25`, Gradle 9.7.1,
`ANDROID_HOME=/Users/alan/Library/Android/sdk`, `--offline`):
- `gradle --offline :app:compileDebugKotlin --rerun-tasks` → `BUILD SUCCESSFUL`
with no `w:` warnings.
- `gradle --offline :app:testDebugUnitTest --rerun-tasks` → `BUILD SUCCESSFUL`;
the test-result XMLs aggregate to **207 tests, 0 failures, 0 errors, 0 skipped**.
- `gradle --offline :app:assembleDebug --rerun-tasks` → `BUILD SUCCESSFUL`;
`app-debug.apk` is **17,928,873 bytes**, sha256
`c95fab884d392a2b3df6170ec2e16ccc4fdf6f1fef4e946425f5dcda56c881a7`, reproducibly
(two consecutive `--rerun-tasks` rebuilds matched).
- Smoke captures on `emulator-5556` (native 2208x1840 @420) with this APK, written
via `android/scripts/capture_png.sh -s emulator-5556`:
`followup2_wide_1x_launch.png`, `followup2_wide_1x_definition.png` (pipeline 3)
and `followup2_wide_1x_run.png` (run 109, partly executed) in
`~/.local/share/pipelines/data/artifacts/108/5/`. The definition graph renders
rounded tonal stages, pill terminals (filled `Failure`/`Success`) and chipped
labels; run 109 fills the visited stages, inverts the selected `committer`
(light fill, solid primary border) and leaves the not-executed `Failure` terminal
hollow with a dashed border. `adb -s emulator-5556 logcat -d | grep -cE 'FATAL
EXCEPTION|E AndroidRuntime'` is `0`.
- **APK publish (this pass).** The rebuilt APK was copied to
`~/.local/share/pipelines/data/artifacts/108/5/pipelines-debug-wip-8b39c08.apk`
(`8b39c08` = `git rev-parse --short HEAD`); `curl -I
http://10.0.0.249:8080/artifacts/108/5/pipelines-debug-wip-8b39c08.apk` returned
`HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
`Content-Length: 17928873`.
### Re-verification with a fresh before/after capture set (run 117, 16 Oct 2026)
The source is unchanged from the sections above; this pass re-ran every check on
it and produced a fresh, complete before/after capture set in
`~/.local/share/pipelines/data/artifacts/117/1/`. `android/` remains the only
modified tree (the untracked `.caps117/` scratch captures at the repo root and the
older `.ui_review*/` directories are not part of the change). No run was started
from the app, only `emulator-5556` was ever addressed, and its display was reset to
native 2208x1840 @420 at the end.
- `gradle --offline :app:assembleDebug --rerun-tasks` → `BUILD SUCCESSFUL`;
`app-debug.apk` is **17,928,873 bytes**, sha256
`c95fab884d392a2b3df6170ec2e16ccc4fdf6f1fef4e946425f5dcda56c881a7` (identical to
the "Second review follow-up" build above).
- `gradle --offline :app:testDebugUnitTest --rerun-tasks` → `BUILD SUCCESSFUL`;
the test-result XMLs aggregate to **207 tests, 0 failures, 0 errors, 0 skipped**
(the new `tonalFill`, `nodeDisplayLabel`, `arrowHeadScalesWithTheStrokeItTerminates`
and `cornerCutNeverExceedsHalfTheShorterSegment` tests included).
- **Captures.** The same four display configurations as the first pass
(`wm size`/`wm density`: wide 2208x1840 @420 and its 2x 4416x3680 @840; narrow
1080x1920 @420 and its 2x 2160x3840 @840), each for the pipeline 3
definition-only graph and the partly executed run 109 (the selected `committer`),
written with `android/scripts/capture_png.sh -s emulator-5556`:
`{before,after}_{wide,narrow}_{1x,2x}_{definition,run}.png`, the 2x-upscaled
`{before,after}_{wide,narrow}_{1x,2x}_selected.png` node crops, and the stacked
`compare_{wide,narrow}_1x_{definition,run}.png` sheets. The `before` images were
rebuilt from `HEAD` (the four tracked files stashed, `assembleDebug`, captured,
then the stash popped and the after build reproduced the same sha256); they show
the sharp-cornered flat fills, `[bracketed]` all-caps labels and thin raw-text
routes, while the `after` images show the rounded tonal stages, pill terminals
(`Failure` hollow/dashed when not executed, `Success` filled) and chipped labels.
`adb -s emulator-5556 logcat -d | grep -cE 'FATAL EXCEPTION|E AndroidRuntime'`
is `0`.
- **APK publish (this pass).** Copied to
`~/.local/share/pipelines/data/artifacts/117/1/pipelines-debug-wip-8b39c08.apk`;
`curl -I http://10.0.0.249:8080/artifacts/117/1/pipelines-debug-wip-8b39c08.apk`
returned `HTTP/1.1 200 OK`, `Content-Type: application/vnd.android.package-archive`,
`Content-Length: 17928873`.
@@ -51,6 +51,8 @@ import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.PathEffect
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.TransformOrigin
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
@@ -67,15 +69,12 @@ import androidx.compose.ui.semantics.role
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.TextLayoutResult
import androidx.compose.ui.text.TextMeasurer
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.compose.LocalLifecycleOwner
import androidx.lifecycle.compose.currentStateAsState
@@ -93,6 +92,8 @@ import net.awan.pipelines.data.protocol.RunGraphState
import net.awan.pipelines.data.protocol.edges
import net.awan.pipelines.ui.formatDuration
import net.awan.pipelines.ui.secondsSince
import net.awan.pipelines.ui.theme.PipelinesTextStyles
import net.awan.pipelines.ui.theme.pipelinesText
internal data class NodeLayout(
val key: String,
@@ -196,6 +197,13 @@ fun WorkflowGraph(
val scheme = MaterialTheme.colorScheme
val colors = remember(scheme) { graphColors(scheme) }
// The graph's type roles come from the app's one type scale (never ad-hoc
// sizes), and the corner radius from the app's shape scale rather than a raw
// literal; a terminal overrides it with a full pill in drawNodes.
val text = pipelinesText()
val nodeCornerPx = with(density) { MaterialTheme.shapes.medium.topStart.toPx(Size.Zero, this) }
val nodeBorderPx = with(density) { NODE_BORDER.toPx() }
val nodeBorderSelectedPx = with(density) { NODE_BORDER_SELECTED.toPx() }
// node key -> stage type, derived once per graph (never per frame) so node
// kind/colour and the spoken description share one lookup.
val stageTypeByKey = remember(graph) { graph.stages.associate { it.key to it.type } }
@@ -261,13 +269,13 @@ fun WorkflowGraph(
}
// Measured once per second (never per frame) so the canvas draw adds no
// allocation for the timer.
val elapsedLayout = remember(activeStartedAt, nowMillis, scheme, density) {
val elapsedLayout = remember(activeStartedAt, nowMillis, scheme, density, text) {
secondsSince(activeStartedAt.orEmpty(), nowMillis)
?.let(::formatDuration)
?.let {
textMeasurer.measure(
it,
TextStyle(fontSize = 11.sp, fontWeight = FontWeight.Medium, color = colors.nodeText),
text.label.copy(color = colors.nodeText),
)
}
}
@@ -335,7 +343,7 @@ fun WorkflowGraph(
// Labels are drawn only after every curve so they always sit on
// top of a neighbouring edge instead of being crossed by it.
drawEdgePaths(layout, colors, runState, animate, phase)
drawEdgeLabels(layout, colors, runState, textMeasurer)
drawEdgeLabels(layout, colors, runState, textMeasurer, text)
drawNodes(
layout,
colors,
@@ -343,6 +351,10 @@ fun WorkflowGraph(
selectedStage,
stageTypeByKey,
textMeasurer,
text,
nodeCornerPx,
nodeBorderPx,
nodeBorderSelectedPx,
animate,
phase,
elapsedLayout,
@@ -478,6 +490,7 @@ private fun LegendSwatch(executed: Boolean, colors: GraphColors) {
start = from,
end = to,
strokeWidth = EDGE_STROKE,
cap = StrokeCap.Round,
pathEffect = if (executed) null else INACTIVE_DASH_EFFECT,
)
if (executed) drawArrowHead(listOf(from, to), color, ARROW_HEAD_SIZE)
@@ -508,6 +521,11 @@ internal class GraphColors(
* uses the same palette. The two terminal roles stay scheme roles so their
* meaning is kept; every other outcome uses the one curated, legible
* [GraphPalette] for both a stroke and its label text.
*
* Node and label surfaces are *tonal*: a raised surface tone ([scheme]'s
* `surfaceContainerHigh`/`surfaceContainerHighest`) blended with a subtle tint of
* the node's semantic colour (see [tonalFill]) rather than a flat fill, so a node
* reads as raised card, not a terminal cell.
*/
internal fun graphColors(scheme: ColorScheme): GraphColors = GraphColors(
// The two terminal roles stay scheme roles so their meaning is kept.
@@ -517,23 +535,60 @@ internal fun graphColors(scheme: ColorScheme): GraphColors = GraphColors(
// stroke and its label text, so a curve and its label always agree.
palette = GraphPalette.colors,
// Node fills differ by kind (see [GraphNodeKind]): model (neutral), ntfy
// (amber), other/custom (green), and the two terminals.
nodeFill = scheme.surfaceVariant,
nodeNtfyFill = scheme.tertiaryContainer,
nodeCustomFill = scheme.primaryContainer,
// A selected node inverts (light fill / dark text) plus a 4px border, so
// (amber), other/custom (green), and the two terminals (success/error). Each
// is a tonal surface carrying a subtle tint of that kind's semantic hue.
nodeFill = tonalFill(scheme.surfaceContainerHigh, scheme.onSurfaceVariant, NEUTRAL_TINT),
nodeNtfyFill = tonalFill(scheme.surfaceContainerHigh, scheme.tertiary, KIND_TINT),
nodeCustomFill = tonalFill(scheme.surfaceContainerHigh, scheme.primary, KIND_TINT),
// A selected node inverts (light fill / dark text) plus a stronger border, so
// selection reads in either appearance and never relies on colour.
nodeFillActive = scheme.inverseSurface,
nodeTextActive = scheme.inverseOnSurface,
nodeBorder = scheme.outline,
// The stage border is deliberately soft (a low-contrast outline variant), not
// the hard original outline; terminals carry their outcome hue instead.
nodeBorder = scheme.outlineVariant,
nodeBorderActive = scheme.primary,
nodeText = scheme.onSurface,
terminalFill = scheme.secondaryContainer,
terminalErrorFill = scheme.errorContainer,
labelBackground = scheme.surface,
terminalFill = tonalFill(scheme.surfaceContainerHigh, scheme.tertiary, TERMINAL_TINT),
terminalErrorFill = tonalFill(scheme.surfaceContainerHigh, scheme.error, TERMINAL_TINT),
// Edge outcome labels sit on a tonal chip (drawn as a rounded rect) rather than
// raw text over the canvas.
labelBackground = scheme.surfaceContainerHighest,
labelText = scheme.onSurfaceVariant,
)
/**
* [surface] blended with a [fraction] (0..1) of [accent], so a node/label fill
* carries a subtle tint of its semantic colour while staying a legible surface.
* Pure sRGB per-channel interpolation; a fraction outside `[0, 1]` is clamped so
* callers never overshoot the two colours.
*/
internal fun tonalFill(surface: Color, accent: Color, fraction: Float): Color {
val t = fraction.coerceIn(0f, 1f)
return Color(
red = surface.red + (accent.red - surface.red) * t,
green = surface.green + (accent.green - surface.green) * t,
blue = surface.blue + (accent.blue - surface.blue) * t,
alpha = surface.alpha + (accent.alpha - surface.alpha) * t,
)
}
/**
* The label a node shows in the graph: a stage keeps its declared key, while a
* terminal's all-caps `SUCCESS`/`FAILURE` becomes the readable `Success`/
* `Failure` (the graph type has no unnecessary all-caps). Pure, so the display
* form is unit-tested and the shared [GraphSemantics.nodeLabel] the
* TUI-mirroring panes still use is left untouched.
*/
internal fun nodeDisplayLabel(key: String): String {
val label = GraphSemantics.nodeLabel(key)
return if (Protocol.isTerminal(key)) {
label.lowercase().replaceFirstChar { it.uppercase() }
} else {
label
}
}
/** The accessibility label for one node, naming its type when it is a stage. */
private fun nodeDescription(node: NodeLayout, type: String?): String {
if (node.terminal) return "Terminal ${node.label}, tap for details"
@@ -714,14 +769,14 @@ private fun forwardAdjacent(edge: GraphEdge, rank: Map<String, Int>): Boolean =
internal fun layoutGraph(graph: Graph, density: androidx.compose.ui.unit.Density): GraphLayout {
if (graph.stages.isEmpty()) return GraphLayout(emptyList(), emptyList(), 0f, 0f)
val nodeWidth = with(density) { 132.dp.toPx() }
val portSpacing = with(density) { 12.dp.toPx() }
val hGap = with(density) { 132.dp.toPx() }
val pad = with(density) { 32.dp.toPx() }
val laneSpacing = with(density) { 26.dp.toPx() }
val terminalGap = with(density) { 64.dp.toPx() }
val trackStep = with(density) { 18.dp.toPx() }
val minNodeHeight = with(density) { 56.dp.toPx() }
val nodeWidth = with(density) { NODE_WIDTH.toPx() }
val portSpacing = with(density) { NODE_PORT_SPACING.toPx() }
val hGap = with(density) { NODE_H_GAP.toPx() }
val pad = with(density) { GRAPH_PAD.toPx() }
val laneSpacing = with(density) { EDGE_LANE_SPACING.toPx() }
val terminalGap = with(density) { TERMINAL_ROW_GAP.toPx() }
val trackStep = with(density) { EDGE_TRACK_STEP.toPx() }
val minNodeHeight = with(density) { NODE_MIN_HEIGHT.toPx() }
val ranks = rankStages(graph)
val edges = graph.edges()
@@ -770,7 +825,7 @@ internal fun layoutGraph(graph: Graph, density: androidx.compose.ui.unit.Density
graph.stages.forEachIndexed { index, stage ->
positions[stage.key] = NodeLayout(
key = stage.key,
label = GraphSemantics.nodeLabel(stage.key),
label = nodeDisplayLabel(stage.key),
x = stageX(index),
y = pad,
width = nodeWidth,
@@ -807,7 +862,7 @@ internal fun layoutGraph(graph: Graph, density: androidx.compose.ui.unit.Density
val successX = failureX + failureWidth + hGap
positions[Protocol.FAILURE_END] = NodeLayout(
key = Protocol.FAILURE_END,
label = GraphSemantics.nodeLabel(Protocol.FAILURE_END),
label = nodeDisplayLabel(Protocol.FAILURE_END),
x = failureX,
y = terminalY,
width = failureWidth,
@@ -816,7 +871,7 @@ internal fun layoutGraph(graph: Graph, density: androidx.compose.ui.unit.Density
)
positions[Protocol.SUCCESS_END] = NodeLayout(
key = Protocol.SUCCESS_END,
label = GraphSemantics.nodeLabel(Protocol.SUCCESS_END),
label = nodeDisplayLabel(Protocol.SUCCESS_END),
x = successX,
y = terminalY,
width = successWidth,
@@ -1118,6 +1173,56 @@ internal fun arrowDirection(points: List<Offset>): Offset {
return Offset.Zero
}
/**
* The clamped cut-back used at one bend of an axis-aligned route: the shared
* [radius], floored to half of the shorter adjacent segment ([inLength] into the
* corner, [outLength] out of it) so the two cut-backs can never meet or cross on
* a short run. It takes the lengths the caller already measured, so a bend's
* geometry is computed once. Pure, so the clamp is unit-tested without a Canvas.
*/
internal fun cornerCutRadius(inLength: Float, outLength: Float, radius: Float): Float =
minOf(radius, inLength / 2f, outLength / 2f).coerceAtLeast(0f)
/**
* The path an axis-aligned route [points] is drawn along: each interior right
* angle is replaced by a quadratic curve with the one consistent [radius] control
* offset (clamped per corner by [cornerCutRadius]), so the tracks read as smooth
* curves. The route's own endpoints and its stored polyline are unchanged, so
* hit-testing, the arrowheads and every layout test keep using the same geometry;
* only the rendered bends soften. Each corner's segment lengths are measured once
* and reused for both the clamp and the cut points; a degenerate route falls back
* to straight segments rather than dividing by zero.
*/
private fun roundedRoutePath(points: List<Offset>, radius: Float): Path {
val path = Path()
if (points.isEmpty()) return path
path.moveTo(points.first().x, points.first().y)
for (i in 1 until points.size - 1) {
val previous = points[i - 1]
val corner = points[i]
val next = points[i + 1]
val inLength = hypot(corner.x - previous.x, corner.y - previous.y)
val outLength = hypot(next.x - corner.x, next.y - corner.y)
val cut = cornerCutRadius(inLength, outLength, radius)
if (cut <= 0f) {
path.lineTo(corner.x, corner.y)
continue
}
val start = Offset(
corner.x + (previous.x - corner.x) / inLength * cut,
corner.y + (previous.y - corner.y) / inLength * cut,
)
val end = Offset(
corner.x + (next.x - corner.x) / outLength * cut,
corner.y + (next.y - corner.y) / outLength * cut,
)
path.lineTo(start.x, start.y)
path.quadraticTo(corner.x, corner.y, end.x, end.y)
}
path.lineTo(points.last().x, points.last().y)
return path
}
/**
* Column rank for every stage in declaration order, mirroring
* tui.layoutSingleRowGraph: `graph.Stages` is the source order, so stages keep
@@ -1143,23 +1248,29 @@ private fun DrawScope.drawEdgePaths(
// stored polyline, so there is no per-frame recompute.
val points = if (edge.points.isEmpty()) routePoints(edge) else edge.points
if (points.size < 2) continue
val path = Path()
path.moveTo(points.first().x, points.first().y)
for (i in 1 until points.size) {
path.lineTo(points[i].x, points[i].y)
}
// The stored route stays the axis-aligned polyline (the layout/tests
// contract); drawing only rounds its corners with the one shared
// [ROUTE_CORNER_RADIUS] control offset, so the tracks read as smooth curves
// without changing any routing.
val path = roundedRoutePath(points, ROUTE_CORNER_RADIUS.toPx())
// Executed = solid full-colour stroke plus an arrowhead; not executed =
// dashed muted stroke with no arrowhead. The difference is carried by line
// style and arrowhead presence, never by opacity alone, so it survives a
// screenshot, a dim screen and a colour-blind reader. An executed
// `success`/`error` edge uses the heavier pass/fail width, a stronger
// (same-hue) stroke and a matched arrowhead, so pass/fail dominates.
// (same-hue) stroke and a matching arrowhead, so pass/fail dominates.
val motion = edgeMotion(edge.edge, runState)
if (motion != EdgeMotion.Unvisited) {
val color = edgeStrokeColor(edge.edge, runState, colors)
val width = edgeStrokeWidth(edge.edge, runState)
drawPath(path, color = color, style = Stroke(width = width))
drawArrowHead(points, color, edgeArrowHeadSize(edge.edge, runState))
drawPath(
path,
color = color,
style = Stroke(width = width, cap = StrokeCap.Round, join = StrokeJoin.Round),
)
// Reuse the width just computed for the stroke's own head (never
// re-deriving it), so the head always matches the line it terminates.
drawArrowHead(points, color, arrowHeadSizeFor(width))
// While the run is live, an executed route carries a dot travelling
// source -> target so its direction reads at a glance. A settled or
// off-screen graph draws no dot.
@@ -1172,6 +1283,8 @@ private fun DrawScope.drawEdgePaths(
color = colors.labelText,
style = Stroke(
width = edgeStrokeWidth(edge.edge, runState),
cap = StrokeCap.Round,
join = StrokeJoin.Round,
pathEffect = INACTIVE_DASH_EFFECT,
),
)
@@ -1224,33 +1337,57 @@ private fun pointAlong(points: List<Offset>, distance: Float): Offset? {
return points.lastOrNull()
}
/**
* Draws the rounded tonal chip behind a measured label: the shared chip paddings
* and corner ([EDGE_CHIP_PAD_X]/[EDGE_CHIP_PAD_Y]/[EDGE_CHIP_CORNER], dp tokens so
* they scale with the device), filled with [color]. Both the edge outcome labels
* and the active stage's elapsed badge use it, so the two chip call sites keep one
* geometry instead of repeating the same rounded rect. The caller draws the
* pre-measured text at [textTopLeft] afterwards.
*/
private fun DrawScope.drawTonalChip(textTopLeft: Offset, textSize: IntSize, color: Color) {
val padX = EDGE_CHIP_PAD_X.toPx()
val padY = EDGE_CHIP_PAD_Y.toPx()
val corner = EDGE_CHIP_CORNER.toPx()
drawRoundRect(
color = color,
topLeft = Offset(textTopLeft.x - padX, textTopLeft.y - padY),
size = Size(textSize.width + padX * 2f, textSize.height + padY * 2f),
cornerRadius = CornerRadius(corner, corner),
)
}
/**
* Draws every outcome label in a second pass, after all curves, so a
* neighbouring edge can never be drawn across a label. Each label sits on its
* own edge's stored [EdgeLayout.labelPoint] (the edge's own lane/track), so
* distinct outcomes never overprint. An executed edge's label uses its legible
* outcome colour (see [outcomeColor]); a not-executed edge's label uses a muted
* colour on a near-opaque background, matching its dashed stroke rather than
* inheriting a faded curve alpha, which left the text unreadable.
* distinct outcomes never overprint. The label is drawn on a tonal rounded chip
* (not raw text over the canvas): the chip is the raised surface tone tinted with
* the label's own colour, so an executed edge's label keeps its legible outcome
* colour and a not-executed one stays muted but readable. The text uses the app's
* type scale ([text]'s label role), never an ad-hoc size.
*/
private fun DrawScope.drawEdgeLabels(
layout: GraphLayout,
colors: GraphColors,
runState: RunGraphState?,
textMeasurer: TextMeasurer,
text: PipelinesTextStyles,
) {
for (edge in layout.edges) {
val executed = edgeIsExecuted(edge.edge, runState)
val textColor = if (executed) outcomeColor(edge.edge.outcome, colors) else colors.labelText
val measured = textMeasurer.measure(edge.edge.label, TextStyle(fontSize = 11.sp, color = textColor))
// One colour serves both the label text and its chip tint: the outcome
// hue when the edge executed, otherwise the muted not-executed label tone.
val labelColor = if (executed) outcomeColor(edge.edge.outcome, colors) else colors.labelText
val measured = textMeasurer.measure(edge.edge.label, text.label.copy(color = labelColor))
val labelTopLeft = Offset(
x = edge.labelPoint.x - measured.size.width / 2f,
y = edge.labelPoint.y - measured.size.height - 2f,
)
drawRect(
color = colors.labelBackground.copy(alpha = if (executed) 0.92f else 0.86f),
topLeft = Offset(labelTopLeft.x - 3f, labelTopLeft.y - 1f),
size = Size(measured.size.width + 6f, measured.size.height + 2f),
drawTonalChip(
textTopLeft = labelTopLeft,
textSize = measured.size,
color = tonalFill(colors.labelBackground, labelColor, EDGE_CHIP_TINT),
)
// Draw the pre-measured layout: the string overload re-derives its width
// constraints from this DrawScope and throws when a label sits outside it
@@ -1299,6 +1436,10 @@ private fun DrawScope.drawNodes(
selectedStage: String?,
stageTypeByKey: Map<String, String?>,
textMeasurer: TextMeasurer,
text: PipelinesTextStyles,
nodeCornerPx: Float,
nodeBorderPx: Float,
nodeBorderSelectedPx: Float,
animate: Boolean,
phase: Float,
elapsedLayout: TextLayoutResult?,
@@ -1312,17 +1453,23 @@ private fun DrawScope.drawNodes(
val selected = node.key == selectedStage
val kind = graphNodeKind(node.terminal, node.key, stageTypeByKey[node.key])
val topLeft = Offset(node.x, node.y)
val corner = CornerRadius(NODE_CORNER_RADIUS, NODE_CORNER_RADIUS)
val borderWidth = if (selected && !node.terminal) 4f else 2f
// A stage is a rounded rectangle from the theme's shape scale; a terminal
// is a pill (fully rounded) so it is visibly not a stage.
val corner = if (node.terminal) {
CornerRadius(node.height / 2f, node.height / 2f)
} else {
CornerRadius(nodeCornerPx, nodeCornerPx)
}
val borderWidth = if (selected && !node.terminal) nodeBorderSelectedPx else nodeBorderPx
// The active stage carries a halo behind its fill: a pulse while
// animating, a fixed but clearly visible ring otherwise, so a live run's
// current stage is unmistakable with or without animation.
if (motion == NodeMotion.Active) {
drawActiveHalo(node, colors, animate, phase, corner, haloGapPx, haloStrokePx)
}
val textColor: Color
if (executed) {
// Filled with a normal border, exactly as the definition-only view.
// A tonal surface fill carrying a subtle tint of the node's semantic
// colour, plus a soft border (or the outcome hue for a terminal).
val fill = when {
kind == GraphNodeKind.TerminalFailure -> colors.terminalErrorFill
kind == GraphNodeKind.TerminalSuccess -> colors.terminalFill
@@ -1349,11 +1496,10 @@ private fun DrawScope.drawNodes(
cornerRadius = corner,
style = Stroke(width = borderWidth),
)
textColor = if (!node.terminal && selected) colors.nodeTextActive else colors.nodeText
} else {
// Hollow and outlined: no fill (the surface shows through), a dashed
// muted border and a muted but legible label, so "not executed" is a
// shape and border-style difference rather than a faded node. A
// Hollow and outlined: no fill (the tonal surface shows through), a
// dashed muted border and a muted but legible label, so "not executed"
// is a shape and border-style difference rather than a faded node. A
// selected not-executed node keeps the stronger border colour.
val border = if (selected && !node.terminal) colors.nodeBorderActive else colors.labelText
drawRoundRect(
@@ -1363,13 +1509,17 @@ private fun DrawScope.drawNodes(
cornerRadius = corner,
style = Stroke(width = borderWidth, pathEffect = INACTIVE_DASH_EFFECT),
)
textColor = colors.labelText
}
val label = "[" + node.label + "]"
val measured = textMeasurer.measure(
label,
TextStyle(fontSize = 13.sp, fontWeight = FontWeight.Medium, color = textColor),
)
// A terminal names its state in its own colour; a stage names itself in the
// node text colour (inverted when selected). No all-caps, no brackets.
val textColor: Color = when {
node.terminal && kind == GraphNodeKind.TerminalSuccess -> colors.success
node.terminal && kind == GraphNodeKind.TerminalFailure -> colors.error
selected && !node.terminal -> colors.nodeTextActive
executed -> colors.nodeText
else -> colors.labelText
}
val measured = textMeasurer.measure(node.label, text.cardTitle.copy(color = textColor))
// Pre-measured layout avoids the scope-relative width constraint crash and
// the redundant re-measure of the string overload.
drawText(
@@ -1381,7 +1531,7 @@ private fun DrawScope.drawNodes(
)
// The active stage's live elapsed time, drawn as a badge under its label
// from the pre-measured layout (so the draw pass adds no allocation), on
// a near-opaque surface chip so it stays legible over any node fill (the
// an opaque tonal chip so it stays legible over any node fill (the
// selected active node is filled light in the dark theme). Only the
// active node has one, and only while the run is live.
if (motion == NodeMotion.Active && elapsedLayout != null) {
@@ -1389,10 +1539,10 @@ private fun DrawScope.drawNodes(
x = node.x + (node.width - elapsedLayout.size.width) / 2f,
y = node.y + node.height - elapsedLayout.size.height - elapsedInsetPx,
)
drawRect(
color = colors.labelBackground.copy(alpha = 0.92f),
topLeft = Offset(badgeTopLeft.x - 3f, badgeTopLeft.y - 1f),
size = Size(elapsedLayout.size.width + 6f, elapsedLayout.size.height + 2f),
drawTonalChip(
textTopLeft = badgeTopLeft,
textSize = elapsedLayout.size,
color = tonalFill(colors.labelBackground, colors.nodeText, ELAPSED_CHIP_TINT),
)
drawText(textLayoutResult = elapsedLayout, topLeft = badgeTopLeft)
}
@@ -1489,9 +1639,22 @@ internal fun edgeStrokeWidth(edge: GraphEdge, runState: RunGraphState?): Float =
else -> EDGE_STROKE
}
/** The named arrowhead-size token for [edge], scaled to match [edgeStrokeWidth]. */
/**
* Arrowhead length for a stroke of [strokeWidth]: one [ARROW_HEAD_SCALE] multiple
* of the width. This is the single mapping both an edge and the legend share, and
* drawing passes the width it has just computed rather than re-deriving it, so a
* heavier line always carries a proportionally larger filled head.
*/
internal fun arrowHeadSizeFor(strokeWidth: Float): Float = strokeWidth * ARROW_HEAD_SCALE
/**
* The arrowhead length for [edge]: [arrowHeadSizeFor] of its own
* [edgeStrokeWidth], so a heavier line always carries a proportionally larger
* head and the two can never disagree. The pass/fail width is the heaviest, so
* its head is the largest; a not-executed edge draws no head at all.
*/
internal fun edgeArrowHeadSize(edge: GraphEdge, runState: RunGraphState?): Float =
if (isEmphasizedEdge(edge, runState)) PASSFAIL_ARROW_HEAD_SIZE else ARROW_HEAD_SIZE
arrowHeadSizeFor(edgeStrokeWidth(edge, runState))
/**
* The stroke colour for an executed [edge]: its outcome colour, made more
@@ -1522,7 +1685,7 @@ private fun graphDescription(graph: Graph, runState: RunGraphState?): String {
for (outcome in GraphSemantics.outcomes(stage)) {
val target = Protocol.resolveTarget(outcome, stage.edges[outcome] ?: continue)
val label = GraphSemantics.edgeLabel(stage, outcome)
builder.append("Outcome $label goes to ${GraphSemantics.nodeLabel(target)}. ")
builder.append("Outcome $label goes to ${nodeDisplayLabel(target)}. ")
}
}
builder.append("Stages can be tapped for details.")
@@ -1564,19 +1727,33 @@ private const val PULSE_PERIOD_MILLIS = 1_600
/** The active stage's elapsed time ticks once a second, never per frame. */
private const val ELAPSED_TICK_MILLIS = 1_000L
/** Corner radius of a node rect, shared by the fill/border and the active halo. */
private const val NODE_CORNER_RADIUS = 14f
/**
* The active halo: how far outside the node it sits, how thick its ring is, and
* how much of the pulse strength its soft glow carries. dp tokens (like the node
* layout) so they scale with the device; the raw node border/corner literals are
* pre-existing graph geometry.
* layout) so they scale with the device.
*/
private val ACTIVE_HALO_GAP = 6.dp
private val ACTIVE_HALO_STROKE = 4.dp
private const val ACTIVE_HALO_GLOW = 0.28f
/**
* Node geometry, spacing and border tokens. A node's corner radius comes from the
* app's shape scale (`MaterialTheme.shapes.medium`, read once in [WorkflowGraph]);
* a terminal overrides it with a full pill. Everything else is a named dp token so
* no call site writes a geometry literal, the gaps are deliberately generous so
* the graph breathes, and the values scale with the device.
*/
private val NODE_WIDTH = 150.dp
private val NODE_MIN_HEIGHT = 76.dp
private val NODE_PORT_SPACING = 14.dp
private val NODE_H_GAP = 168.dp
private val GRAPH_PAD = 40.dp
private val EDGE_LANE_SPACING = 34.dp
private val TERMINAL_ROW_GAP = 88.dp
private val EDGE_TRACK_STEP = 26.dp
private val NODE_BORDER = 1.dp
private val NODE_BORDER_SELECTED = 3.dp
/** Bottom inset of the active node's elapsed-time badge inside the node rect. */
private val ELAPSED_INSET = 4.dp
@@ -1591,10 +1768,11 @@ private const val FLOW_DOT_SCALE = 1.2f
* pixels, so the two states differ by shape, not by a faded tint.
*
* The two decisive outcomes (`success`/`error`) use the heavier
* [PASSFAIL_EDGE_STROKE] with the matching [PASSFAIL_ARROW_HEAD_SIZE] and a
* stronger [PASSFAIL_SATURATION] stroke, so pass/fail reads at a glance and from
* a distance, while every other outcome keeps the finer [EDGE_STROKE] and a
* not-executed route the finer still [INACTIVE_EDGE_STROKE].
* [PASSFAIL_EDGE_STROKE] with a proportionally larger arrowhead (see
* [edgeArrowHeadSize]) and a stronger [PASSFAIL_SATURATION] stroke, so pass/fail
* reads at a glance and from a distance, while every other outcome keeps the
* finer [EDGE_STROKE] and a not-executed route the finer still
* [INACTIVE_EDGE_STROKE].
*/
private const val EDGE_STROKE = 3f
@@ -1604,11 +1782,41 @@ private const val PASSFAIL_EDGE_STROKE = 7f
/** Stroke width for a not-executed edge; finer than either executed width. */
private const val INACTIVE_EDGE_STROKE = 2.5f
/** Arrowhead length for a normal executed edge. */
private const val ARROW_HEAD_SIZE = 12f
/**
* A route's corner radius, a dp token like the rest of the graph geometry: the
* one consistent control offset every right-angle bend of an orthogonal route is
* rounded by, so all tracks share a single curve language (and scale with the
* device) without changing the stored routing.
*/
private val ROUTE_CORNER_RADIUS = 7.dp
/** Arrowhead length for an executed pass/fail edge, scaled with its heavier stroke. */
private const val PASSFAIL_ARROW_HEAD_SIZE = 20f
/**
* Arrowhead length as a multiple of the edge's own stroke width, so a heavier line
* always carries a proportionally larger filled head (base `3 * 4 = 12`,
* pass/fail `7 * 4 = 28`). [ARROW_HEAD_SIZE] is the base length, used by the
* legend swatch, which names the generic executed state rather than pass/fail.
*/
private const val ARROW_HEAD_SCALE = 4f
private const val ARROW_HEAD_SIZE = EDGE_STROKE * ARROW_HEAD_SCALE
/**
* Tonal tints: the fraction of a node's/edge's semantic colour blended into the
* raised surface for its fill or chip. Small enough to read as a tint, large
* enough to tell the node kinds and outcome labels apart.
*/
private const val NEUTRAL_TINT = 0.10f
private const val KIND_TINT = 0.22f
private const val TERMINAL_TINT = 0.30f
private const val EDGE_CHIP_TINT = 0.20f
private const val ELAPSED_CHIP_TINT = 0.14f
/**
* The tonal chip's padding and corner, dp tokens like the other graph geometry
* (so a chip scales with the device rather than sitting at a raw pixel size).
*/
private val EDGE_CHIP_PAD_X = 2.dp
private val EDGE_CHIP_PAD_Y = 1.dp
private val EDGE_CHIP_CORNER = 2.dp
/**
* How much more saturated an executed pass/fail stroke is than its outcome
@@ -1634,7 +1842,7 @@ private val LEGEND_SWATCH_HEIGHT = 10.dp
* the former 360.dp / 340.dp literals). ~58% of the window height so the graph
* is a substantial share of the screen, floored at a height that still fits a
* 4-stage layout plus its lower terminal row: pad*2 + node + terminal gap + node
* = 32*2 + 56 + 72 + 56 = 248px at density 1.
* = 40*2 + 76 + 88 + 76 = 320px at density 1.
*/
internal fun collapsedGraphHeight(screenHeightDp: Int): Dp =
(screenHeightDp * 0.58f).dp.coerceAtLeast(GRAPH_PANEL_MIN_HEIGHT)
@@ -1643,4 +1851,4 @@ internal fun collapsedGraphHeight(screenHeightDp: Int): Dp =
internal fun expandedGraphHeight(screenHeightDp: Int): Dp = (screenHeightDp * 0.92f).dp
/** Floor that still fits a 4-stage graph with its terminal row (see above). */
internal val GRAPH_PANEL_MIN_HEIGHT = 260.dp
internal val GRAPH_PANEL_MIN_HEIGHT = 320.dp
@@ -182,6 +182,27 @@ class GraphPaletteTest {
private fun valueOf(color: Color): Float = maxOf(color.red, color.green, color.blue)
/**
* [tonalFill] blends a raised surface toward the accent by the given fraction,
* so a node/label fill carries a subtle tint of its semantic colour while
* staying a surface; the fraction is clamped so a caller never overshoots.
*/
@Test
fun tonalFillBlendsTowardTheAccentAndClampsTheFraction() {
val surface = darkSurface
val accent = Color(0xFFFF0000)
// Both endpoints are reproduced exactly on the channel.
assertEquals(surface.red, tonalFill(surface, accent, 0f).red, 0.0001f)
assertEquals(accent.red, tonalFill(surface, accent, 1f).red, 0.0001f)
// A mid tint sits strictly between the two and keeps the surface's alpha.
val mid = tonalFill(surface, accent, 0.2f)
assertTrue(mid.red > surface.red && mid.red < accent.red)
assertEquals(surface.alpha, mid.alpha, 0.0001f)
// Out-of-range fractions clamp to the endpoints instead of overshooting.
assertEquals(surface.red, tonalFill(surface, accent, -1f).red, 0.0001f)
assertEquals(accent.red, tonalFill(surface, accent, 2f).red, 0.0001f)
}
@Test
fun nodeKindIsDeterministicAndCoversEveryKind() {
assertEquals(GraphNodeKind.Model, graphNodeKind(false, "planner", null))
@@ -592,6 +592,62 @@ class WorkflowGraphTest {
assertEquals(1, GRAPH_LEGEND.count { it.executed })
}
/**
* The node label the graph shows is readable: a terminal's all-caps keyword
* becomes title case (no unnecessary all-caps), while a stage keeps its
* declared key.
*/
@Test
fun nodeDisplayLabelsAreReadableAndKeepStageKeys() {
assertEquals("Success", nodeDisplayLabel(Protocol.SUCCESS_END))
assertEquals("Failure", nodeDisplayLabel(Protocol.FAILURE_END))
assertEquals("ui_reviewer", nodeDisplayLabel("ui_reviewer"))
assertEquals("planner", nodeDisplayLabel("planner"))
}
/**
* A heavier line always carries a proportionally larger filled arrowhead: one
* consistent scale ties the head length to the stroke width, so the pass/fail
* head dominates exactly as its stroke does.
*/
@Test
fun arrowHeadScalesWithTheStrokeItTerminates() {
val graph = sampleGraph()
val success = graph.edges().first { it.outcome == "success" }
val other = graph.edges().first { it.outcome == "blocked" }
val runState = RunGraphState(
visitedStages = setOf(success.source, other.source),
takenRoutes = setOf(
GraphRoute(success.source, success.outcome, success.target),
GraphRoute(other.source, other.outcome, other.target),
),
currentStage = success.source,
)
val successRatio = edgeArrowHeadSize(success, runState) / edgeStrokeWidth(success, runState)
val otherRatio = edgeArrowHeadSize(other, runState) / edgeStrokeWidth(other, runState)
assertEquals(successRatio, otherRatio, 0.001f)
assertTrue(edgeArrowHeadSize(success, runState) > edgeArrowHeadSize(other, runState))
}
/**
* The rounded-corner cut at a route bend is the shared radius, floored to half
* the shorter adjacent segment so two cut-backs can never meet or cross; a
* degenerate adjacent segment yields no cut instead of dividing by zero. It
* works on the already-measured segment lengths, so a bend measures them once.
*/
@Test
fun cornerCutNeverExceedsHalfTheShorterSegment() {
val radius = 18f
// Both adjacent segments are long enough to take the full radius.
assertEquals(radius, cornerCutRadius(100f, 100f, radius), 0.001f)
// A short incoming segment halves the cut.
assertEquals(10f, cornerCutRadius(20f, 100f, radius), 0.001f)
// A short outgoing segment halves the cut.
assertEquals(15f, cornerCutRadius(100f, 30f, radius), 0.001f)
// A degenerate adjacent segment yields no cut.
assertEquals(0f, cornerCutRadius(0f, 100f, radius), 0.001f)
}
private fun assertNoSharedRuns(layout: GraphLayout) {
val edges = layout.edges
for (i in edges.indices) {