Commit Graph

182 Commits

Author SHA1 Message Date
alan 98bbc2deac Report recorded decision evidence and harden the Pi artifacts env
Refinements on top of the human decision stage (a6aff47):

- `pipelines decide` now reports the feedback the server actually stored for
  the chosen option, so a repeated (idempotent) decision shows the recorded
  evidence instead of the ignored request text. A repeated decision is covered
  by a new assertion that also checks the step output does not change.
- The decision option/feedback output keys are defined once in protocol
  (DecisionOptionKey/DecisionFeedbackKey) with a DecisionEvidence reader, and
  the store and CLI use them instead of bare string literals.
- piEnvironment drops any inherited PIPELINES_ARTIFACTS_DIR before spawning Pi,
  so the artifactsDir argument is authoritative and an ambient directory (for
  example Pipelines' own when a stage runs inside another stage) never leaks
  into a child that was given none. Covered by a test with an ambient value set.
2026-10-16 17:25:48 +01:00
alan 95150c79c5 Render every artifact in the shared gallery, with file-type icons
Standardise the artifacts gallery so the run summary and the stage pane
render one tile per artifact instead of images as a grid and everything
else as a plain list.

- Artifacts.kt: ArtifactTile now covers both shapes - an image/video fills
  the cell with a thumbnail (a video shows its poster frame with a play
  badge), anything else shows its file-type icon with the name and size
  beneath it; the grid, share/copy actions and multi-select are unchanged
  and the capture wording is untouched.
- ArtifactType.kt (new): pure ArtifactKind classification from content
  type plus name extension fallback, and artifactIcon(kind) mapping each
  kind to a distinct glyph.
- ArtifactImage.kt: ArtifactVideoFrame/rememberArtifactVideoFrame extract
  a poster frame via MediaMetadataRetriever over an in-memory
  MediaDataSource; the shared memoized-preview scaffold is factored into
  rememberArtifactPreview.
- ArtifactViewer.kt: full-screen viewer takes a video flag and shows the
  poster frame.
- Format.kt: add isVideoContentType; drop the now-unused artifactMetaLine.
- Dimens.kt: ARTIFACT_TYPE_ICON_DP, ARTIFACT_PLAY_BADGE_DP,
  ARTIFACT_TILE_ACTION_DP tokens.
- Tests: new ArtifactTypeTest (type-to-icon mapping, extension fallback,
  distinct glyphs); FormatTest updated for the removed helper.
- android/README.md documents the pass.

android/ only; no new dependencies beyond material-icons-extended.
2026-10-16 17:13:35 +01:00
alan 12976ba372 Open stage sections as their own pane instead of expanding inline
Expanding a stage section rendered its rows stacked at the top of the section: CollapsibleSectionBody passed the section's several field composables straight into AnimatedVisibility, which measures a single child, so all rows were placed at the section origin and only the last (Memory) was visible. Fix the shared body by laying its content out in one full-width Column, and make every stage section open as its own pane rather than growing the stage screen inline.

- PaneState: add the Section pane level (MAX_PANE_DEPTH = 3), a saved sectionKey primitive, and the matching backStep/popTo/encode/decode handling so one Back or peek pops one level and the open section survives rotation and process death.

- StageDetailPane: the stage screen now keeps a compact collapsed list of sections (Artifacts, Output, Input, This run, Stage definition); tapping one opens it as a full-window screen on a narrow window or a panel to the right of the stage pane on a wide one, with its own title, scroll and top spacing. A shared stageSectionSpecs derives the sections for both the stage screen and the section pane, and the artifacts section keeps the shared ArtifactSelectionScaffold.

- PipelinesApp: wire the Section pane into the stack, its peeks and Back. Section content (Definition, Input, Output, Artifacts) and semantics are unchanged; sections start collapsed and the operator's choice persists.

- Tests: cover the section pane level, backStep, popTo and the shared stageSectionSpecs. Build and forced unit tests pass (262 tests, 0 failures); lint shows only the pre-existing themes.xml NewApi errors.

Android only (7 files); no dependency added, no server/Go/installer/Docker change, no run started from the app. APK published to the run artifacts directory and documented in android/README.md.
2026-10-16 17:12:13 +01:00
alan ee5cd742c2 Prove the always decision through the shared approval reply builder
Extend ChatApprovalTest so once, always and reject each go through the same
ChatProtocol.replyRequest builder plus one encode/decode round trip using the
DECISION_* constants, so no decision is asserted more weakly than another, and
add answeringAlwaysUpdatesTheCardInPlace (settled card, no actions, risk panel
retired, request still visible). Refresh the android/README.md verification
notes: 267 tests, the rebuilt APK's sha256 and byte size, the 147/3 artifact
path and LAN URL, and the emulator/device-lock notes for this pass.
2026-10-16 16:57:57 +01:00
alan a6aff47117 Add a human decision stage that pauses a run for an operator's choice
A new registered stage type `human` (internal/stage/human.go) has no model,
agent, tools or configs: its required `prompt` block carries the operator
instructions and its non-error edges are the selectable options. It parses,
validates, renders, exports and imports like every other type (no parser
special-case, no config keys).

At runtime the runner parks the run instead of executing: the step and the run
persist `waiting` with self-contained {prompt, options} evidence, and the run
returns without starting later stages, capturing file diffs, scanning artifacts,
holding a goroutine/timer or applying a stage timeout. The wait is durable: a
restart leaves the waiting rows untouched (RecoverRuns excludes them) and a
rebuilt runtime over the same database still accepts the decision.

`pipelines decide <run-id> [stage] --option KEY [--feedback TEXT] [--json]` and
the TUI `c` picker resolve the decision from the pinned graph in one store
transaction, record the choice and feedback as the step's evidence and resume
along edges[KEY]. An unknown option is refused with the valid list, a stage that
is not waiting is refused, and a repeated decision for an already-decided visit
does not double-apply. Cancel and retry keep working while waiting and after a
decision; a human stage is never killed by a stage timeout or max_visits, and a
`notify` policy can fire an `on=waiting` event.

Docs: the authoring skill references (format.md, operations.md), docs/cli.md and
README describe the stage, the command and the TUI picker. Tests cover stage
validation, the parsing round-trip, the store transitions, a websocket wait/decide
integration, cancel/retry, waiting notifications and a persistence-layer rebuild
(second Open + newRunner over one database, no process restart).
2026-10-16 16:47:28 +01:00
alan 305714c30f Drive the composer's stop control and IME action from one derivation
While a turn was in flight the trailing composer button became the stop
control, but the text field's keyboard send action still checked only
canSend, so a prompt could be sent from the IME during a run even though
the visible control had become stop.

Add ChatFormat.composerAction(thread) -> ComposerAction.Send/Stop as the
single pure derivation and read it from both the trailing button and the
keyboard action, so the two controls can no longer disagree.
ChatFormatTest.composerControlIsStopWhileARunIsInFlightAndSendOtherwise
covers Send when idle and Stop while running. android/ only; no new
dependency.
2026-10-16 16:26:16 +01:00
alan 609721d53b Show pushed approvals as in-place chat cards
Render a server-pushed chat_permission as an approval card in the
transcript instead of a transient bar above the composer, matching the
reference opencode/Jarvis chat: the requested action, its resources, the
amber RISK REVIEW panel, and once/always/reject actions wired to the
server's chat_reply.

- ChatFormat: a pure approvalCard()/ApprovalCard model and one
  ChatProtocol.replyRequest() builder shared by the card's actions and
  the repository, so the wire frame and the controls cannot drift.
- ChatStore/AppViewModel: answerPermission() settles the card in place
  optimistically and survives a chat switch; a failed reply reopens the
  same request rather than showing an unacknowledged decision.
- ChatPermissionFrame gains optional resolved/decision fields so a
  request the server reports as already settled shows its verdict with
  no stale actions; a new request replaces a settled card.
- Findability: a gold PanTool top-bar action and chat-chip marker jump
  to the pending card; the running indicator stands down while waiting.
- Tests: ChatApprovalTest covers pending/answered/resolved, the reply
  builder's once/reject decisions and the missing-summary fallback;
  ChatProtocolTest covers the server-resolution frame. README records
  the 265-test/assembleDebug evidence and the emulator-5556 captures,
  and .approval_check/chat_stub_approval.py is the test double used.

android/ only; no new dependency beyond material-icons-extended; no
Pipelines server, Go, installer or Docker file touched; no run started
from the app. The live brokered server is not verified (the resolved
frame fields are an additive contract it does not emit yet).
2026-10-16 16:12:22 +01:00
alan c700b28e6a Add cross-system read-only search
One query now finds anything in the system over the wire and from the CLI.

- protocol: add Search/SearchResults message types and a SearchRequest
  (query, optional kind filter, optional limit) / SearchResponse (typed,
  ranked matches plus truncation and scan-bound counters) pair, with typed
  payloads for pipeline, version, run, step/visit, field text and artifact.
- store: add Store.Search, a read-only query over pipelines,
  pipeline_versions, pipeline_runs, run_steps (+step_control) and
  step_artifacts. Ranks exact name (3) > name substring (2) > body text (1),
  breaks ties by recency then a stable kind/target order, and reports the
  matched field. Bounds work with a 50-default/200-max result cap, a 2000-row
  per-kind scan limit and a 2000-step / 1 MiB field-text scan budget.
- terms: a bare status word or lone date expression (today, yesterday, this
  week, YYYY-MM-DD) selects runs; anything else stays free text.
- server: dispatch protocol.Search to stores[0].Search; read-only and
  unconfirmed.
- cli: add `pipelines search QUERY [--type KIND] [--limit N] [--json]`, help
  text and a BROWSE line.
- store: add OpenReadOnly so the live-database check never runs DDL.
- docs: document the grammar, kinds, ranking and bounds in docs/cli.md,
  scope the TUI omnisearch to pipelines in docs/ui-ux-review.md, and add a
  search bullet to the packaged operations reference.
- tests: protocol round trip, store/ranking/term-parsing/limit/scan-bound
  unit tests, a server end-to-end test, and an env-guarded live check.

No new dependencies; go.mod/go.sum unchanged.
2026-10-16 15:43:25 +01:00
alan 78d5bd38fc Route the stop control's interrupt through one tested builder
Extract the single chat_interrupt frame into ChatProtocol.interruptRequest and
have PipelinesRepository.chatInterrupt send it, so production and its unit test
share the one wire shape instead of the repository building it inline.

Add chatInterruptRequestCarriesTheRunningSession, which asserts the frame the
stop control sends is chat_interrupt carrying the running session's id (and no
chat prompt/reply) and that it survives the client's JSON round-trip.
Document the slice and its emulator-5556 evidence in android/README.md.
2026-10-16 15:31:04 +01:00
alan e2f306b8bd Summarise large edit diffs and label the card with file and stat
The chat edit diff card rendered every line of an edit, so the >400-line
fallback flooded the transcript with thousands of Text nodes on a phone;
it also showed only the tool name, not the file, on the expanded panel.

- ChatFormat.toolEditDiff keeps the first MAX_RENDERED_DIFF_LINES (200)
  lines and puts the remainder in the new ToolDiff.omitted, while the
  +N/-M counts continue to describe the whole edit.
- DiffView prints "… N more changed lines not shown" first so the
  truncation is visible without scrolling.
- The expanded panel header now shows the edited file name and the shared
  green/red DiffStat, matching the collapsed chip.
- ChatFormatTest pins omitted = 0 for a small edit and the true counts,
  200-line cap and omitted = 300 for an oversized one.
- android/README.md records the change and its evidence.
2026-10-16 15:15:35 +01:00
alan 1b4674d22c Show the derived stage verdict atop the stage view in the run detail
Move a completed stage visit's derived verdict out of the Progress summary
and into the top of the selected stage's Result section, so the chosen
option, its concise reason and the referenced artifacts are visible where
the stage is inspected.

- Add stageVerdictLines, which renders one line "Verdict: <option> · <reason>"
  (still stating the option when the reason is absent) plus a following
  "Referenced artifacts:" line only when artifacts exist, and returns nil
  for a nil verdict so nothing extra is shown.
- Prepend those lines in runSectionLines after the stage state and before
  the stage output and evidence, without adding a section or changing the
  panel layout.
- Update the TUI test to render through the run-detail view, asserting the
  option, reason and artifact names appear, and that a nil verdict adds
  nothing; document the TUI placement in the debugging skill reference.

Omni-search work already present in the working tree (including the
runDuration→protocol.Duration refactor in run_detail.go) is unrelated to
this change and is left uncommitted.
2026-10-16 15:12:23 +01:00
alan c13dca0f42 Merge branch 'main' into lane-go 2026-10-16 14:18:24 +01:00
alan 291cec2bda Show chat tool calls as expandable INPUT/OUTPUT chips
Render each assistant turn's tool calls the way the reference jarvis chat
does: one compact chip per call showing the tool name, its duration and a
spinner while it runs, with consecutive calls of a turn grouped into one
wrapping row so the transcript stays scannable (ChatScreen AssistantParts /
ToolCalls).

Tapping a chip opens a floating panel over the transcript with INPUT as
pretty-printed JSON and OUTPUT as monospace, plus copy actions. The panel is
dismissible by tapping outside or its Close action and is positioned by
ToolPanelPositionProvider so it never moves the conversation (the transcript
scroll position is untouched while the overlay is open).

A failed call is shown as failed and renders both its diff (when present) and
an ERROR block. ERROR text now comes from the new toolErrorText, which prefers
the server's error message over any partial output, while toolOutputText is the
OUTPUT derivation again; toolFailed identifies the error state.

While a turn streams, the transcript follows the newest content with a hard
jump unless the operator has dragged away, driven by
listState.interactionSource.interactions (DragInteraction.Start/Stop/Cancel)
rather than programmatic scrolls. The running indicator and its live elapsed
time derive from the turn's own start (ChatThread.elapsedMillis, an injectable
clock in ChatStore) so they survive a chat switch.

A reconnecting socket now settles every open chat and re-fetches its history
(ChatStore.streamResumed, AppViewModel.observeConnection), and a server-pushed
stream error with no session id settles the sole/active running turn with the
server's message instead of leaving the indicator spinning.

Tests: ChatFormatTest covers toolErrorText; new ChatStreamTest covers the
streaming/elapsed/reconnect/stream-error guarantees against an injected clock;
new ToolPanelPositionProviderTest covers the panel's below/flip/margin
placement. README's chat section documents the follow-the-stream mechanism.
2026-10-16 14:17:50 +01:00
alan e79ff9585f Derive a plain-language verdict for every completed stage visit
Each completed step now exposes a verdict: the chosen option (outcome -> target),
a bounded one-line reason with model/fallback/absent provenance, and the recorded
artifacts the reason refers to. The store persists only the model-generated line
in a new step_verdicts table and derives the fallback at read time (no backfill);
the server generates the line once at completion, best-effort; the TUI renders it
in the stage progress summary. The packaged debugging reference documents it.
2026-10-16 13:54:48 +01:00
alan f3e0593f4d Let runs carry an operator title shown in the CLI and TUI
Add a bounded, never-empty title to every run. `pipelines run --title "..."`
sets it explicitly and skips model generation; otherwise the server generates
it from the prompt through the shared summariser and falls back to the prompt's
first line, recording title_source (model/fallback/explicit) and title_model.

- protocol/store: RunSummary.Title plus Label(), a set_run_title message, title
  columns with an idempotent migration, CreateRunTitled, and SetRunTitle renames.
- summarise: Title/GenerateTitle/DeriveTitle/ExplicitTitle bounded to TitleCap.
- runner: generate the title outside the admission lock and only for a request
  that starts a run; a replay reuses the stored title and an explicit title
  skips the model entirely.
- CLI: `--title` on run and a `title <run-id> "<title>"` rename command; human
  `runs` and `inspect` show the title beside the pipeline name and version.
- TUI: the run list row, run detail header, Home run cards and last-run line,
  and the pipeline Results line show the title via Label().

Tests cover storage/migration/fallback, explicit-title and rename, the
end-to-end CLI flow, and title rendering; CLI and operations docs updated.
2026-10-16 13:36:48 +01:00
alan dce624b428 Merge lane-go: keep the lane's reviewed work 2026-10-16 13:12:36 +01:00
alan 0e6fbcc062 Merge branch 'main' into lane-go 2026-10-16 13:09:34 +01:00
alan d546bc7a3a Migrate the graph, panes, rail and sheet onto the geometry tokens
Move the workflow-graph package (WorkflowGraph, the StageDetailPane sheet,
Artifacts, ArtifactViewer, ArtifactImage) off its remaining raw dp literals
and onto the geometry tokens, all substitutions value-equal so the visuals
are unchanged.

- ui/theme/Dimens.kt gains the off-scale component and graph-chrome sizes:
  the run legend's GRAPH_LEGEND_PAD_X/PAD_Y/GAP, the collapsed
  GRAPH_PANEL_MIN_HEIGHT (moved off WorkflowGraph.kt, now imported by its
  test), the gallery's ARTIFACT_TILE_DP/THUMB_DP/BADGE_DP/PROGRESS_DP/
  PROGRESS_STROKE_DP, and the stage-type chip's STAGE_CHIP_PAD_H.
- Artifact tile/row and thumbnail corner radii derive from the Material
  shape scale (MaterialTheme.shapes.medium/.small), matching the graph's
  existing node corners.
- DimensTest.kt's allow-list shrinks from 24 to 21 entries: 24.dp, 56.dp and
  96.dp are gone now that their last call sites migrated. The structural
  hairlines/zeros, the not-yet-migrated app shell and Settings literals, and
  the sp type values owned by Typography.kt remain.
- WorkflowGraphTest.kt imports the moved GRAPH_PANEL_MIN_HEIGHT.
- android/README.md documents the change and its verification evidence.

Verified: gradle :app:assembleDebug :app:testDebugUnitTest --rerun-tasks
BUILD SUCCESSFUL, 30 XMLs / 259 tests, 0 failures/errors/skipped; the
enforcement test fails on a deliberately introduced literal and passes once
removed; before/after captures at both window widths differ only on the
status-bar clock and live relative-time text.
2026-10-16 13:08:54 +01:00
alan 9f88e4ff71 Recover malformed model-stage results with a bounded, work-preserving repair
A model stage whose final result was malformed failed the whole run even when
the work and evidence had survived, because the only recovery was an isolated
formatter call on a fixed 30-second deadline that could time out on its own
(run 55, ui_reviewer of pipeline 9 v6).

Add an ordered, deterministic local repair pass (internal/stage/result_repair.go)
that runs before any model call: (a) append missing closing delimiters via the
existing closeJSONContainers; (b) remove one unambiguous trailing comma before a
closing } or ]; (c) insert exactly the single comma/colon the JSON parser reported
at its byte offset. Every candidate must pass losslessSyntaxRepair(original,
candidate) and decodeModelResult before it is accepted, so no field value is
invented, removed, reordered or rewritten. Ambiguous payloads (an unescaped quote
or colon inside a string value, or a stray delimiter with no single completion)
return not-ok and fall through to the bounded model re-emit rather than guessing.
stageResultText still strips surrounding prose and a single code fence first;
model_prompt.go now also strips prose around a single balanced-but-malformed
object span so the deterministic pass sees just the object.

Replace the fixed 30-second formatter deadline with repairDeadline(payloadBytes,
remaining), which grows monotonically with payload size, has a floor, and is
clamped to the attempt's remaining budget minus a safety margin, so the stage
context remains the outer bound and a large result is not guaranteed to time out.
The one-request-per-attempt, 32 KiB bound and the deny-all, retained, new-session
property of RepairFormat are unchanged for OpenCodeClient and PiClient.

Record an explicit recovery status on every terminal path: repaired, partial or
unrecoverable, plus a byte offset. A candidate that is valid JSON but still fails
envelope validation is marked partial and never returned as a completed result;
the unrecoverable path retains the bounded original payload, the precise parse
error (including its byte offset) and surfaces the status in the FINAL RESULT
VALIDATION diagnostic.

safeToReplay is intentionally unchanged. The deterministic local repair and the
fresh deny-all, no-tools, retained formatter session are independent of the
stage's tool set and never re-prompt or replay the admitted agent session, so a
shell-enabled review stage gains malformed-result recovery without any replay of
admitted work. Risk: no change to mutation safety; the only added cost is one
bounded formatter call, already budgeted. Replayability is not extended for shell
stages.

Docs and packaged skill references (docs/model-results.md,
internal/author/skill/references/{format,debugging,verification}.md) describe the
three-tier recovery, the status words and the derived deadline; the safeToReplay
decision and its risk are recorded there alongside the commit.

Tests add mocked, offline coverage for the deterministic and partial paths, a
repairDeadline monotonicity/floor/clamp table, and a shell-stage regression
proving a recoverable malformed result does not fail the run or replay tool work.
2026-10-16 13:02:53 +01:00
alan d7f650032d Render assistant text as markdown in the chat transcript
Add a dependency-free CommonMark-subset parser/renderer (ui/chat/Markdown.kt):
paragraphs, headings, fenced code, block quotes, bullet/ordered lists, tables,
thematic rules and inline code/bold/italic/links/autolinks. The renderer turns
blocks into themed, selectable Compose content: fenced code reuses the shared
CodeBlock (existing whole-block copy action), tables are a bordered grid with a
bold header, links use LinkAnnotation.Url, and inline code/headings use the
shared type roles.

ChatScreen.MessagePart now calls MarkdownText(part.text) for PART_TEXT instead
of a single plain Text; the assistant message stays one SelectionContainer, so
all of it remains selectable and long content stays inside the bubble. Geometry
reuses the chat tokens (CHAT_ITEM_GAP promoted private -> internal).

Add MarkdownTest with 10 unit tests covering fences/language, unterminated
fences, soft-wrap joining, headings/rules, lists, tables, inline spans, bare-URL
autolinks and snake_case non-emphasis. Document the change in android/README.md.
2026-10-16 13:01:39 +01:00
alan 7b3a56398d Merge branch 'main' into lane-go 2026-10-16 12:44:09 +01:00
alan 0718f5ba6f Add the Chat destination and hold several conversations at once
Entry point: the floating destination pill gains a Chat icon between Runs and
Settings; it stays a single non-wrapping Row of 48dp targets using the named
DESTINATION_ITEM_SIZE/DESTINATION_ITEM_GAP tokens, clear of the existing 88dp
reserve, so it stays narrow however many destinations it holds.

Protocol/transport: new data/protocol/Chat.kt mirrors the brokered chat wire
shapes; Message gains the optional chat_* payloads, PipelinesClient forwards
unsolicited frames (chat_event/chat_permission) to a new events flow instead of
dropping them, and PipelinesRepository exposes the typed chat calls (sessions,
create, messages, prompt, interrupt, reply).

State: ui/chat/ChatStore.kt is an Android-free multi-chat holder; every open
chat keeps its own conversation, running flag, composer draft and scroll
position, open/activate report when history must be re-synced so a running
session refreshes on return instead of showing a stale copy, and busy/read-only
sessions refuse writes.

Surface: ui/chat/ChatScreen.kt lists the server's sessions with running/busy/
read-only status and an open-chat strip to switch between conversations (chip X
closes only that chat); the conversation is a bottom-anchored transcript of user
bubbles, reasoning, assistant text and tool-call chips that expand to INPUT
(pretty JSON)/OUTPUT (monospace), edit-family calls render a diff card derived
from oldString/newString, and pending chat_permission frames surface an approval
bar answered via chat_reply. New chat creates and opens a session. The manifest
sets windowSoftInputMode=adjustResize for the composer.

Tests: ChatProtocolTest, ChatFormatTest and MultiChatStateTest cover the wire
shapes, formatting and the multi-chat model (switching preserves each
conversation, a running session re-syncs on return, per-chat drafts/scroll,
busy read-only, background events land on their chat). README documents the
slice and its evidence.
2026-10-16 12:43:37 +01:00
alan 3765fdfdf6 Migrate the list and detail screens onto the geometry tokens
Replace the hardcoded paddings, spacings, sizes and offsets in the four
list/detail screens and the shared components they are built from with
references to the token file from the previous item, via WindowInsets or
layout where those derive the value. Every replacement is value-equal, so
the screens render identically at both window widths.

Name the glyph sizes that cannot derive from layout as four new ICON_*
tokens in ui/theme/Dimens.kt (14/18/20/24dp) and shrink the DimensTest
allow-list from 30 to 24 entries: 14.dp, 18.dp and 20.dp leave because
their last call site migrated, and the already-unused 32.dp, 11.sp and
13.sp entries are dropped. All adb/emulator work targeted emulator-5554
only; android/ only; no new dependency, server/Go/installer/Docker file
touched, and no run started from the app.

Verified: :app:assembleDebug + the full unit suite (30 result XMLs, 259
tests, 0 failures/0 errors/0 skipped), the shrunk allow-list still fails a
forced raw-literal probe, and before/after screenshots of every converted
screen at narrow and wide widths match near-zero.
2026-10-16 12:43:19 +01:00
alan bfef465977 Fix build: define protocol.NormalizeText used by the summariser
internal/summarise called protocol.NormalizeText, which was never defined, so the tree did not compile. Add the shared normalisation helper: drop zero-width formatting runes, turn control characters into spaces and collapse whitespace runs (including the non-breaking space variants) into single spaces. Reuse it in OutputPreview instead of duplicating the mapping logic.

Cover the awkward inputs (newlines, tabs, non-breaking spaces, zero-width runes, surrounding quotes, trailing punctuation) in the protocol and summarise tests. Unrelated working-tree changes are left uncommitted.
2026-10-16 12:28:27 +01:00
alan 8e49a0c6f9 Merge lane-go: keep the lane's reviewed work 2026-10-16 12:07:02 +01:00
alan a8ff49f423 Merge lane-app2: keep both lanes' reviewed work
Compose the parallel lane (lane-app2) with the work already on main,
preserving both intents rather than picking one side:

- lane-app2's modernised run graph (rounded tonal nodes, pill terminals,
  chipped outcome labels, pass/fail emphasis and active-stage/edge motion)
  plus its remembered list filters/sort and last-run badges, and the
  app-owned run-status palette.
- main's cross-fading loading/empty/error states, animated list items and
  the single geometry token file (Dimens.kt + DimensTest).

Conflicts resolved in android/README.md (kept both appended sections),
RunStatus.kt (kept the shared ColoredChip extraction and made it animate
under MotionQuick), PipelineListScreen.kt (filters/sort/badges composed with
the StateCrossfade/load-phase presentation and animateListItem rows),
RunDetailScreen.kt (kept both the artifact-selection and graph-palette
imports) and RunHistoryScreen.kt (the cross-faded load branch now passes
sort/filters through, and both empty branches keep the Clear filters action
with animated items). LoadPhase.Empty now carries an optional recovery
action so the crossfade can still offer Clear filters. The graph's new
geometry literals moved onto Dimens.kt GRAPH_* tokens so DimensTest passes
and its allow-list shrinks as intended.

Verified: :app:assembleDebug and :app:testDebugUnitTest (259 tests,
0 failures) with the offline Gradle 8.11.1 / JDK 17 toolchain.
2026-10-16 12:04:45 +01:00
alan f6b9424894 Add a single geometry token file and a test that enforces it
Introduce ui/theme/Dimens.kt as the one source of truth for app geometry,
alongside Typography.kt for type. It defines the 4dp spacing scale
(SPACING_XXS/XS/S/M/L/XL/XXL) and receives the geometry constants that
already existed, each with a comment tying it to what it is: PEEK_WIDTH_DP
(the collapsed strip), PEEK_BUDGET_DP, MIN_ACTIVE_PANE_WIDTH_DP and
MIN_COVERED_PANE_WIDTH_DP from SlidingPaneStack.kt, DESTINATION_PILL_RESERVE
from PipelinesApp.kt, and WIDE_RAIL_WIDTH_DP and DETAIL_MAX_WIDTH_DP from
DetailTabs.kt. Call sites now import the tokens; every value is unchanged,
so no layout changes.

Add ui/theme/DimensTest.kt, a JVM test that scans the app's Kotlin sources
for raw dp/sp literals and fails with file:line:literal unless the literal
is a token or an explicit, reasoned allow-list entry. The allow-list records
the 34 literals that predate the token file, each with a written reason, and
is expected to shrink as call sites migrate onto the tokens.

Document the change and its verification in android/README.md.
2026-10-16 11:50:26 +01:00
alan e5bde981ee 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.
2026-10-16 11:50:08 +01:00
alan e84b0db728 Merge branch 'main' into lane-go 2026-10-16 11:33:19 +01:00
alan d019213c5b Animate selection and live state changes
Animate selection and status changes across the Android UI using the
existing Motion tokens, leaving every resting state unchanged.

- DestinationPill draws one selection indicator and animates its offset
  between the three slots (animateDpAsState, MotionStandard), with the
  glyph tint cross-fading in step; geometry comes from named
  DESTINATION_ITEM_SIZE/GAP tokens via the unit-tested
  destinationIndicatorOffsetDp helper.
- The shared ListRow fades its tonal container and content colour under
  MotionQuick instead of switching.
- New shared CollapsibleSectionBody wraps section bodies in
  AnimatedVisibility (expand/shrink + fade) under MotionQuick, used by
  both the lazy collapsibleSection and the stage pane's StageSection, so
  body and chevron move together.
- StatusChip eases container and label colour and RunStatusIcon eases its
  glyph tint, so a live run's status transition is visible rather than a
  silent colour swap.

Verified: assembleDebug + testDebugUnitTest BUILD SUCCESSFUL, 186 tests
across 23 classes with 0 failures/errors/skips; frames captured on
emulator-5554 for the travelling pill, section collapse and a live status
change; APK published to the run artifact directory. README documents the
change and its evidence.
2026-10-16 11:24:01 +01:00
alan 5157b3a716 Add bounded one-line summariser using the configured default harness
internal/summarise performs a single tool-free generation through the
configured default harness (its interactive model), reusing the exact
stage.ModelGenerator/OpenCodeClient/PiClient construction provider-check
uses. It bounds input (InputCap), output (one line, OutputCap runes) and
time (DefaultTimeout), returns the NoSummary sentinel on any error/timeout/
unusable reply, never runs tools or writes files, and records the harness,
model and failed flag in one sanitized log line plus at most one
OperationEvidence.

Reuse: stage.TruncateRunes and stage.OperationLog.Record are the exported
forms of the existing rune-safe truncation and bounded evidence recording;
protocol.NormalizeText trims replies to one line. No new dependencies.

Not wired into titles/verdicts yet: protocol.OutputPreview and the
internal/server/notify.go notification summary are the obvious future call
sites.
2026-10-16 10:55:43 +01:00
alan 7f7492a7bd Merge branch 'main' into lane-go 2026-10-16 10:45:56 +01:00
alan b89ad29c41 Cross-fade loading, empty and error states in data-backed panes
A data-backed pane swapped its loading spinner, empty message, error
message and content with a plain `when`, so content flashed from empty to
full and empty/error states popped.

Introduce a shared presentation model in ui/components/States.kt:
- `LoadPhase` (Loading, Error(message), Empty(message), Content), with
  message-carrying phases capturing their text at classification so a
  fading-out branch never recomposes against cleared error/filter state.
- `listLoadPhase(loading, error, hasData, emptyMessage)` and
  `detailLoadPhase(error, hasData)` pure classifiers preserving the
  existing precedence (failed load with no data, then loading, then
  empty, else content; stale data keeps the pane on content).
- `StateCrossfade(phase)` wraps the branch in a `Crossfade` using the
  existing `MotionStandard` token; both branches share one box so the
  resting layout is unchanged and the outgoing phase fades under the
  incoming one.

Apply to PipelineListScreen, RunHistoryScreen, PipelineDetailScreen and
RunDetailScreen. Detail panes render the fading-out branch from the last
non-null item. The Runs pane keeps its inline empty/error line inside the
list, now fading through animateListItem().

Add LoadPhaseTest covering the classifiers and captured messages, and
document the change and evidence in android/README.md.
2026-10-16 10:45:27 +01:00
alan 934994d7f7 Add named motion tokens and animate list item changes
Introduce ui/components/Motion.kt beside the pane dimension tokens: two
named duration+easing tokens, MotionQuick (120ms) for small in-place state
changes and MotionStandard (220ms) for content that moves or swaps, under a
300ms MAX_MOTION_MILLIS cap. Every animation call site now asks a token for
its spec instead of writing a duration: the pane slide and section
Crossfade use MotionStandard, the section chevron uses MotionQuick, and the
pane-pop stagger moves in as MOTION_STAGGER_MILLIS (the old
PANE_SLIDE_* / SECTION_SWAP_MILLIS constants are gone).

Add a single LazyItemScope.animateListItem() helper (ListRow.kt) wrapping
the supported Modifier.animateItem with the tokens: items fade in/out
(MotionQuick) and slide to new positions on refresh, filter or re-sort
(MotionStandard). Pipelines rows, run rows, version rows and evidence rows
use it. Specs are built at composition time (no per-frame allocation) and
the chevron reads its angle inside graphicsLayer so it turns without
recomposing the header; resting layout is unchanged and the standard
animator duration scale still applies, so disabled animations are instant.

Add MotionTest covering token ordering, per-token bands, the cap, monotonic
easings, self-reversal and spec timing; SlidingPaneStackTest now reads the
pane timing from the token. Document the change and its verification in
android/README.md.
2026-10-16 09:55:41 +01:00
alan 8b39c087fd Animate the active stage and executed edges in the run graph
Show what is happening while a run is live. The executing stage now carries a
subtle pulsing halo (replacing the blink) and a live ticking elapsed badge
derived from the run's current visit start. Executed edges carry a directional
flow of light dots along the path; a finished stage settles into its static
colour. A finished run never animates, the animation pauses when the graph is
off screen, and with the system animation setting disabled it falls back to a
static but clearly marked running state.

The per-frame visual state and should-animate decision live in pure functions
(GraphMotion.kt, Format.kt secondsSince; GraphSemantics exposes executing and
currentStageStartedAt) with unit tests and no frame-timing assertions. Adds
GraphMotionTest and extends GraphSemanticsTest and FormatTest.
2026-10-16 09:52:57 +01:00
alan 1818a06d2f Restrict chat_sessions to server-owned sessions
chat_sessions now brokers GET /api/session but filters the global list to
the sessions this server recorded in run_steps, deduped by session id, and
fails closed to an empty list when no ownership source is configured. A
session another client holds (in-server claim, released on stream end or
disconnect) or an active run is marked busy; a second client's chat_prompt
for a held session is rejected before any OpenCode call. chat_create stays
unbrokered.
2026-10-16 09:21:50 +01:00
alan dca72a09ee Merge branch 'main' into lane-go 2026-10-16 09:07:06 +01:00
alan 0b74903a00 Add long-press artifact multi-select with bulk copy and share
Long-pressing any artifact — a gallery tile in the run summary or a row in
the stage pane's per-visit list — now enters artifact selection: the pressed
item is selected with the app's selected treatment and further taps toggle
items instead of opening them. A contextual bar replaces the surface's top
bar while selecting, showing the count plus Copy links, Share and a close;
it carries the same pane safe-area insets as the bar it replaces, uses 48dp
IconButtons and leaves selection mode on Back before the surface's own Back
runs. Selection applies only to artifacts, never the runs or pipelines lists.

The selection is one shared host: ArtifactSelectionScaffold owns the
remembered ArtifactSelection, the resolvedSelection lookup, the bulk
copy/share actions, the SnackbarHostState and the pane-scoped BackHandler,
and both RunDetailScreen (summary grid) and StageDetailPane (per-visit list)
go through it, so neither screen owns its own SnackbarHostState or
BackHandler. The immutable ArtifactSelection (enter/toggle/selectAll/clear)
treats selection mode as "one or more urls selected", so it can never
restore half-applied; rememberArtifactSelection saves it via a listSaver and
reseeds per run/visit.

Copy links resolves every selected url against the configured server through
the existing resolvedArtifactUrl (no hardcoded host), writes one absolute
link per line through the new single Clipboard.copyText path (now also used
by the code blocks, pipeline source, artifact row and viewer), and confirms
the number of lines actually produced in a Snackbar. Share fetches every
selected artifact through the existing client, reuses the single-item
writeSharedArtifact (same bounded cache, FileProvider and prune), and sends
one ACTION_SEND_MULTIPLE typed by bulkShareMimeType (the common type, else
the wildcard) with the count in the chooser title; when any fetch fails the
whole set degrades in the same action to its resolved links shared as text.

Pure helpers and tests: ArtifactSelectionTest covers enter, toggle,
deselect-last, select-all/clear, the restored state, the one-per-line link
formatting and the labels; ArtifactSharingTest gains shareTargets and
bulkShareMimeType cases. Unit tests plus assembleDebug pass (168 tests,
21 classes, 0 failures). android/README.md documents the model, action bar
and the bulk share flow, and the doc-accuracy pass records that the bulk
copy writes links in gallery (candidate) order.

No new dependency (icons come from the declared material-icons-extended).
2026-10-16 08:51:03 +01:00
alan 3ff5cd8838 Poll OpenCode permission requests and forward chat_reply 2026-10-16 08:06:39 +01:00
alan 1e7862e7c9 Make pass/fail edges the loudest lines in the run graph
Treat `success` and `error` as the emphasised outcomes so pass/fail is
obvious at a glance and from a distance. An executed pass/fail edge now
uses PASSFAIL_EDGE_STROKE=7f (was 3f), a same-hue, more saturated stroke
(PASSFAIL_SATURATION=1.6f via the new pure boostSaturation helper) and a
matched PASSFAIL_ARROW_HEAD_SIZE=20f arrowhead. Other executed outcomes
keep EDGE_STROKE=3f and not-executed routes the finer
INACTIVE_EDGE_STROKE=2.5f, so the two decisive outcomes dominate.

All widths, the arrowhead size and the saturation factor are named
tokens chosen by edgeStrokeWidth/edgeArrowHeadSize/edgeStrokeColor; the
old 12f arrowhead literal at the call site is gone (drawArrowHead now
takes the size as a parameter). Outcome hues are unchanged; the boosted
stroke keeps the original hue and value.

The run Graph tab help line notes that executed success and failure
routes are drawn thickest, and the definition-only view gets the same
emphasis since every route counts as executed there. New unit tests cover
the saturation maths (hue/value/alpha preserved, safe and clamped) and the
per-edge width/arrowhead/colour choices.
2026-10-16 08:06:34 +01:00
alan 9d1676df0a Merge branch 'main' into lane-go 2026-10-16 07:21:40 +01:00
alan 9c47527def Make executed vs not-executed unmistakable in the run graph
Carry the two states structurally instead of by fading, so the difference
survives a screenshot, a dim screen and a colour-blind reader.

- Executed edges: solid full-colour stroke plus an arrowhead.
- Not-executed edges: dashed muted stroke (INACTIVE_DASH_EFFECT), no arrowhead.
- Executed nodes: keep their fill and normal border.
- Not-executed nodes: no fill, dashed muted border and a muted but legible label.
- Add a one-line legend (GRAPH_LEGEND / GraphLegendEntry / LegendSwatch) pinned
  TopStart, rendered only when a run is selected.
- Replace the private EdgeLayout.isExecuted/inline visited check with the shared
  edgeIsExecuted/stageIsExecuted predicates and remove the alpha-based dimming.
- Update the KDoc and the run Graph tab help text ("solid ... dashed and outlined").

Tests: executed/inactive predicates over the definition view and a RunGraphState,
the dash pattern as a positive even-length rhythm, and the legend naming both
states with executed first.
2026-10-16 07:04:48 +01:00
alan 1195535852 Add a real share action to every artifact item
Give each gallery image cell and each per-visit file row its own share
control: a 48dp IconButton with an accurate "Share <name>" content
description drawn as a sibling of the item's tap handler, so sharing
never opens the image or the item.

Sharing fetches the artifact through the existing client into a scoped
cache file (cache/shared-artifacts/), exposed via a non-exported
FileProvider declared with the new res/xml/file_paths.xml, and sends it
through ACTION_SEND. When the fetch returns nothing the action falls
back to sharing the resolved link as text. Cache files are named
deterministically per artifact so re-sharing overwrites instead of
growing without bound, and a failed or unreachable fetch cannot crash.

The artifact-to-file naming, mime/extension table and the file-vs-link
fallback decision are factored into ArtifactSharing.kt and covered by
the new ArtifactSharingTest.kt. The existing open and copy-link actions
are unchanged; the viewer's action scrim alpha is shared as
ARTIFACT_ACTION_SCRIM_ALPHA. android/README.md documents the provider
and the share flow. No new dependency is added.
2026-10-16 07:03:18 +01:00
alan b28f88be66 Add tests proving chat_interrupt stops a running chat turn
The chat_interrupt path was already wired end to end (protocol type,
server dispatch through handleChatSimple to broker.Interrupt, and the
adapter POST /api/session/{id}/interrupt), but nothing exercised it
against a live stream. Add the missing coverage:

- internal/opencode/chat_test.go: pin the adapter's outbound call
  exactly (POST /api/session/ses_1/interrupt, empty JSON body, one
  request, nil on 200) plus a non-nil error on HTTP 500.
- internal/server/chat_test.go: drive the real opencode.Chat adapter
  over an httptest SSE fixture that holds the turn open until the
  interrupt arrives, then assert the run ends, the interrupt is
  acknowledged, no error frame is sent, and the prompt/interrupt posts
  and interrupt path match. Also cover invalid-session rejection,
  the unconfigured-broker error, and broker-failure reporting, adding a
  spare interruptErr hook to the scripted fakeChat.

Production code is unchanged: verification found no gap in the existing
interrupt transport. Tests use httptest loopback fixtures only and do
not touch the live OpenCode service.
2026-10-16 06:43:02 +01:00
alan e131c02fa1 Merge branch 'main' into lane-go 2026-10-16 06:35:43 +01:00
alan d339827b5f Open artifact images in a full-screen zoomable viewer
Tapping an image artifact (run summary grid, per-visit list or stage pane,
all rendered through ArtifactGallery) now opens a new scrim-backed
full-screen viewer instead of the former small centred dialog, which is
removed rather than stacked.

- ArtifactViewer.kt renders a full-bleed Dialog (usePlatformDefaultWidth =
  false, decorFitsSystemWindows = false) whose content re-applies
  paneSafeArea() so the dark backdrop reaches the edges while respecting
  status bar, cutout and navigation bar. A top-right row keeps the
  open-in-new and copy-link actions and adds a close button over a
  translucent scrim capsule.
- Gestures: pinch zooms about the centroid, drag pans via the existing
  graph zoomAbout, double-tap toggles fit <-> 2.5x, and a downward swipe at
  fit dismisses; a plain tap does nothing. Zoom clamps to [1x, 5x] and the
  new pure clampImageOffset keeps pan inside the scaled image. Zoom state is
  keyed on the url, so closing the viewer or opening another image resets to
  fit/centred. System Back and the close button dismiss the viewer without
  closing the pane behind it.
- Loading goes through the existing cached, off-main-thread
  rememberArtifactBitmap/ArtifactImageState path with distinct loading and
  error states, drawn in the light inverseSurface role that contrasts with
  the always-black scrim.
- Pure helpers fitImageSize, clampImageOffset and toggleZoomScale are
  covered by the new ArtifactViewerTest. ArtifactImage.kt widens
  rememberArtifactBitmap/ArtifactImageState to internal and Artifacts.kt
  replaces FullSizeArtifactDialog with ArtifactViewer (openArtifact made
  internal).
- android/README.md documents the viewer, its gestures and the evidence
  gathered on emulator-5554.
2026-10-16 06:35:08 +01:00
alan 54af4535d7 Add remembered filters to the runs and pipelines lists
Give each list a filter control, remembered per list across restarts like
the sort, combined with AND. Filters narrow; the (later) omni search will
find, so they are kept distinct.

- ui/screens/ListFilter.kt: RunTimeRange (AnyTime default, Today, Last7Days,
  Last30Days), RunPresence (Any default, HasRuns, NoRuns) and the
  RunFilters/PipelineFilters data classes, with one pure predicate per facet
  (runMatchesStatuses, runMatchesPipeline, runMatchesTimeRange,
  pipelineMatchesPresence, pipelineMatchesLastRunStatus) and the AND-combining
  filterRuns/filterPipelines. A default narrows nothing; an empty status set
  means "any"; the time windows are inclusive calendar days; a blank,
  unparseable or future timestamp never matches a finite window; a runless
  pipeline has no last-run status; fromStorage tolerates stale/unknown/blank
  values; encodeRunStates/decodeRunStates round-trip the status set.
- ui/components/FilterMenu.kt: the shared top-bar control both screens use -
  an IconButton with a numeric active-filter count badge opening the caller's
  sections plus one Clear filters action (disabled when nothing is active),
  the count folded into the icon description, and a menu capped to the window
  and clear of the navigation inset so it stays scrollable rather than
  clipping.
- PipelineListScreen.kt/RunHistoryScreen.kt wire the control and predicates;
  the existing name search on pipelines stays a separate field, and the new
  pipeline facets depend on the run history.
- ui/components/States.kt: EmptyState gains optional actionLabel/onAction so
  both lists distinguish "nothing exists" from "nothing matches the current
  filters" and offer Clear filters only in the latter.
- data/SettingsRepository.kt + ui/AppViewModel.kt: store each facet under its
  own stable key as a StateFlow, exactly like the sort keys; the screens
  resolve the stored strings so the repository stays unaware of the UI enums.

Verified on this tree with :app:testDebugUnitTest, assembleDebug, and
emulator-5556 persistence and captures; recorded in android/README.md.
2026-10-16 06:01:18 +01:00
alan 7b61906e1b Lead the run summary with a width-derived artifact grid
In the run detail summary, artifacts now appear at the top of the page and as a grid rather than a list:

- RunDetailScreen emits the "run-artifacts" LazyColumn item before the "run-summary" item, so the captured screenshots are the first thing the operator sees. The rest of the summary and its collapsed-by-default sections are unchanged.
- ArtifactGallery derives its geometry from the measured width via the new pure artifactGrid(availableWidth, preferred, spacing): it fits as many preferred-shaped cells as the width allows and stretches them to fill the row, instead of the removed fixed ARTIFACT_GRID_COLUMNS count. A host narrower than one preferred cell falls back to a single narrower cell; a non-positive preferred token never divides by zero. Tiles still open the full-size image on tap; non-image artifacts keep their compact list form.
- ArtifactGalleryTest replaces the fixed-column cases with grid cases covering a narrow pane (fewer, larger cells), a wide window (more columns), a very wide window (cells near the preferred shape), the single-cell fallback and degenerate inputs, asserting the row never overflows the host.

Verified with assembleDebug (APK 17,863,337 bytes, sha256 32e9081b28f5caa85f5bfa24f7fe7149eeddb919d4e71cf497e9017b80f54ce7) and the unit tests (140 tests, 0 failures/errors/skipped); captured on emulator-5554 at both window widths.
2026-10-16 05:28:39 +01:00
alan 915016df0b Expose OpenCode conversation history in chat_messages
decodeChatMessages only understood the native-serve {info,parts} envelope,
so records from the V2 HTTP API (GET /api/session/{id}/message) decoded
with an empty role and were silently dropped, leaving chat_messages with
empty history. Teach nativeChatMessage to read the V2 top-level shape
(id/type/agent/model/time, parts under "content", user prompt as a bare
string) while keeping the native {info,parts} path via role/id/model/agent/
created accessors and a contentParts fallback.

Add seeded-session evidence: a decoder table test covering both envelopes
(user + assistant with text, reasoning and a completed tool part carrying
input, content and status) plus handler tests that drive chat_messages
through the broker fallthrough and through the real adapter.
2026-10-16 05:24:00 +01:00
alan 315788b3cb Merge branch 'main' into lane-go 2026-10-16 05:09:16 +01:00