diff --git a/docs/notes/stage-turns.md b/docs/notes/stage-turns.md new file mode 100644 index 00000000..e8b34c63 --- /dev/null +++ b/docs/notes/stage-turns.md @@ -0,0 +1,47 @@ +# Stage turns + +Stage turns are file-based. Each visit gets its own directory under the run: + +``` +/stages/01-implementer/input.md +/stages/01-implementer/memory.md +/stages/01-implementer/output.md +/stages/01-implementer/private/ +/public/ +``` + +`internal/turn.Layout` derives those paths deterministically (the sequence is +zero-padded to two digits). `Paths.Ensure` creates the turn, private and public +directories idempotently; it never deletes or rewrites existing files. + +The first turn's `input.md` is the run prompt. A later turn's input is the +previous turn's output under a `# Previous turn output` heading. Memory is +plain markdown: one `## · visit ` section per completed turn, with +that turn's output verbatim followed by a system-written list of files added to +`public/`. List entries are relative to the run directory, sorted, and unique. +Input, memory and output are stored per turn, and private artifacts stay in the +turn's `private/` directory while shared artifacts go to the run-level +`public/` directory. + +## Outcome-only output contract + +A turn's `output.md` must contain exactly one outcome section and may contain any +markdown after it. The outcome section is an ATX heading named `outcome` (any +level) followed by the first non-blank line, which must be exactly one of the +stage's allowed outcome words: + +```md +## outcome +success + +# Result + +The rest of the output is the body, preserved verbatim. +``` + +Matching trims whitespace and compares case-insensitively, returning the +canonical allowed spelling. Text before the heading is ignored. Headings and +words inside fenced code blocks (triple backticks or tildes) are ignored, so a +diff or code sample cannot add a false outcome. Missing, duplicate, empty, or unknown +outcomes are explicit errors; the parser never guesses, repairs the text, or +looks for any other section. diff --git a/internal/turn/layout.go b/internal/turn/layout.go new file mode 100644 index 00000000..18bb82f7 --- /dev/null +++ b/internal/turn/layout.go @@ -0,0 +1,52 @@ +// Package turn owns the file layout and markdown contracts for file-based +// stage turns. It deliberately has no dependency on the server, protocol or +// stage packages: callers persist and execute turns, while this package keeps +// their paths and plain-markdown shapes deterministic. +package turn + +import ( + "fmt" + "os" + "path/filepath" +) + +// Paths is the complete on-disk layout for one stage visit. +type Paths struct { + RunDir string + Sequence int + StageKey string + TurnDir string + InputPath string + MemoryPath string + OutputPath string + PrivateDir string + PublicDir string +} + +// Layout returns the deterministic paths for a stage turn. The sequence is +// zero-padded to two digits; longer sequences keep all of their digits. +func Layout(runDir string, sequence int, stageKey string) Paths { + turnDir := filepath.Join(runDir, "stages", fmt.Sprintf("%02d-%s", sequence, stageKey)) + return Paths{ + RunDir: runDir, + Sequence: sequence, + StageKey: stageKey, + TurnDir: turnDir, + InputPath: filepath.Join(turnDir, "input.md"), + MemoryPath: filepath.Join(turnDir, "memory.md"), + OutputPath: filepath.Join(turnDir, "output.md"), + PrivateDir: filepath.Join(turnDir, "private"), + PublicDir: filepath.Join(runDir, "public"), + } +} + +// Ensure creates the turn, private and run-level public directories. It is +// idempotent and never removes or rewrites anything already present. +func (p Paths) Ensure() error { + for _, dir := range []string{p.TurnDir, p.PrivateDir, p.PublicDir} { + if err := os.MkdirAll(dir, 0o700); err != nil { + return fmt.Errorf("turn: create %s: %w", dir, err) + } + } + return nil +} diff --git a/internal/turn/layout_test.go b/internal/turn/layout_test.go new file mode 100644 index 00000000..2fcfe8f6 --- /dev/null +++ b/internal/turn/layout_test.go @@ -0,0 +1,70 @@ +package turn + +import ( + "os" + "path/filepath" + "testing" +) + +func TestLayoutIsDeterministic(t *testing.T) { + runDir := filepath.Join(t.TempDir(), "run") + want := Paths{ + RunDir: runDir, + Sequence: 2, + StageKey: "implementer", + TurnDir: filepath.Join(runDir, "stages", "02-implementer"), + InputPath: filepath.Join(runDir, "stages", "02-implementer", "input.md"), + MemoryPath: filepath.Join(runDir, "stages", "02-implementer", "memory.md"), + OutputPath: filepath.Join(runDir, "stages", "02-implementer", "output.md"), + PrivateDir: filepath.Join(runDir, "stages", "02-implementer", "private"), + PublicDir: filepath.Join(runDir, "public"), + } + got := Layout(runDir, 2, "implementer") + if got != want { + t.Fatalf("Layout() = %#v, want %#v", got, want) + } + if again := Layout(runDir, 2, "implementer"); again != got { + t.Fatalf("Layout() is not deterministic: %#v then %#v", got, again) + } +} + +func TestLayoutSupportsLongSequences(t *testing.T) { + got := Layout("/runs/one", 123, "review") + want := filepath.Join("/runs/one", "stages", "123-review") + if got.TurnDir != want { + t.Fatalf("TurnDir = %q, want %q", got.TurnDir, want) + } +} + +func TestPathsEnsureIsIdempotentAndPreservesFiles(t *testing.T) { + paths := Layout(t.TempDir(), 1, "build") + if err := paths.Ensure(); err != nil { + t.Fatalf("Ensure() error: %v", err) + } + for _, dir := range []string{paths.TurnDir, paths.PrivateDir, paths.PublicDir} { + info, err := os.Stat(dir) + if err != nil { + t.Fatalf("stat %s: %v", dir, err) + } + if !info.IsDir() { + t.Fatalf("%s is not a directory", dir) + } + } + kept := filepath.Join(paths.PrivateDir, "keep.txt") + if err := os.WriteFile(kept, []byte("preserve me"), 0o600); err != nil { + t.Fatal(err) + } + if err := paths.Ensure(); err != nil { + t.Fatalf("second Ensure() error: %v", err) + } + body, err := os.ReadFile(kept) + if err != nil { + t.Fatalf("read preserved file: %v", err) + } + if string(body) != "preserve me" { + t.Fatalf("preserved file = %q", body) + } + if _, err := os.Stat(paths.InputPath); !os.IsNotExist(err) { + t.Fatalf("Ensure() should not create the input file, stat error = %v", err) + } +} diff --git a/internal/turn/output.go b/internal/turn/output.go new file mode 100644 index 00000000..dc9dd6db --- /dev/null +++ b/internal/turn/output.go @@ -0,0 +1,170 @@ +package turn + +import ( + "errors" + "fmt" + "strings" +) + +var ( + // ErrEmptyOutput means the turn produced no markdown at all. + ErrEmptyOutput = errors.New("turn output: empty") + // ErrMissingOutcome means no outcome heading and value were found. + ErrMissingOutcome = errors.New("turn output: missing outcome") + // ErrDuplicateOutcome means more than one outcome heading was found. + ErrDuplicateOutcome = errors.New("turn output: duplicate outcome") + // ErrOutcomeNotAllowed means the value was not one of the declared words. + ErrOutcomeNotAllowed = errors.New("turn output: outcome not allowed") +) + +// ParseOutput extracts the single outcome section from a turn's markdown. +// +// A heading whose text is "outcome" (any ATX level) is followed by the first +// non-blank line, which must contain exactly one allowed word. Matching is +// trim-and-lower-case, and the canonical spelling from allowedOutcomes is +// returned. Everything after that value line is the body, preserved byte for +// byte. Text before the outcome heading is ignored. Headings and values inside +// fenced code blocks are never considered. +func ParseOutput(markdown string, allowedOutcomes []string) (Outcome string, Body string, err error) { + if strings.TrimSpace(markdown) == "" { + return "", "", ErrEmptyOutput + } + lines := markdownLines(markdown) + var headings []int + var fence fenceState + for i, line := range lines { + if fence.open() { + if fence.closes(line.text) { + fence = fenceState{} + } + continue + } + if marker, ok := openingFence(line.text); ok { + fence = marker + continue + } + if isOutcomeHeading(line.text) { + headings = append(headings, i) + } + } + switch len(headings) { + case 0: + return "", "", ErrMissingOutcome + case 1: + default: + return "", "", fmt.Errorf("%w: found %d outcome headings", ErrDuplicateOutcome, len(headings)) + } + + heading := headings[0] + value := heading + 1 + for value < len(lines) && strings.TrimSpace(lines[value].text) == "" { + value++ + } + if value == len(lines) { + return "", "", fmt.Errorf("%w: outcome heading has no value", ErrMissingOutcome) + } + word := strings.TrimSpace(lines[value].text) + canonical, ok := allowedOutcome(word, allowedOutcomes) + if !ok { + return "", "", fmt.Errorf("%w: %q", ErrOutcomeNotAllowed, word) + } + return canonical, markdown[lines[value].next:], nil +} + +func allowedOutcome(word string, outcomes []string) (string, bool) { + key := strings.ToLower(word) + for _, outcome := range outcomes { + outcome = strings.TrimSpace(outcome) + if outcome != "" && strings.ToLower(outcome) == key { + return outcome, true + } + } + return "", false +} + +type markdownLine struct { + text string + next int +} + +// markdownLines records each line's content without its line ending and the +// byte position immediately after that line ending. Body slices therefore keep +// CRLF and every other byte exactly as supplied. +func markdownLines(markdown string) []markdownLine { + lines := make([]markdownLine, 0, strings.Count(markdown, "\n")+1) + for start := 0; start < len(markdown); { + next := len(markdown) + text := markdown[start:] + if relative := strings.IndexByte(markdown[start:], '\n'); relative >= 0 { + next = start + relative + 1 + text = markdown[start : start+relative] + } + lines = append(lines, markdownLine{ + text: strings.TrimSuffix(text, "\r"), + next: next, + }) + if next == len(markdown) { + break + } + start = next + } + return lines +} + +func isOutcomeHeading(text string) bool { + text = strings.TrimSpace(text) + hashes := 0 + for hashes < len(text) && text[hashes] == '#' { + hashes++ + } + if hashes == 0 || hashes == len(text) { + return false + } + // Markdown ATX headings require whitespace between the marker and text. + if text[hashes] != ' ' && text[hashes] != '\t' { + return false + } + return strings.EqualFold(strings.TrimSpace(text[hashes:]), "outcome") +} + +type fenceState struct { + char byte + length int +} + +func (f fenceState) open() bool { + return f.length > 0 +} + +func (f fenceState) closes(text string) bool { + char, length, ok := fenceMarker(text) + if !ok || char != f.char || length < f.length { + return false + } + trimmed := strings.TrimLeft(text, " \t") + return strings.TrimSpace(trimmed[length:]) == "" +} + +func openingFence(text string) (fenceState, bool) { + char, length, ok := fenceMarker(text) + if !ok { + return fenceState{}, false + } + return fenceState{char: char, length: length}, true +} + +func fenceMarker(text string) (byte, int, bool) { + trimmed := strings.TrimLeft(text, " \t") + if len(trimmed) < 3 || (trimmed[0] != '`' && trimmed[0] != '~') { + return 0, 0, false + } + char := trimmed[0] + length := 0 + for length < len(trimmed) && trimmed[length] == char { + length++ + } + if length < 3 { + return 0, 0, false + } + return char, length, true +} diff --git a/internal/turn/output_test.go b/internal/turn/output_test.go new file mode 100644 index 00000000..bfe84766 --- /dev/null +++ b/internal/turn/output_test.go @@ -0,0 +1,137 @@ +package turn + +import ( + "errors" + "testing" +) + +func TestParseOutput(t *testing.T) { + allowed := []string{"success", "blocked", "rejected"} + tests := []struct { + name string + input string + outcome string + body string + err error + }{ + { + name: "leading commentary is ignored and trailing section is body", + input: "Checking the work first.\n\n## outcome\nsuccess\n\n# Result\n\nThe work is complete.\n", + outcome: "success", + body: "\n# Result\n\nThe work is complete.\n", + }, + { + name: "diff embedding an outcome line cannot confuse the parser", + input: "# outcome\nblocked\n\n```diff\n+# outcome success\n+unrelated change\n```\n", + outcome: "blocked", + body: "\n```diff\n+# outcome success\n+unrelated change\n```\n", + }, + { + name: "fenced headings before the real outcome are ignored", + input: "```md\n# outcome\nfailed\n```\n\n~~~\n## outcome\nrejected\n~~~\n\n# outcome\nSUCCESS\n\nbody", + outcome: "success", + body: "\nbody", + }, + { + name: "CRLF line endings", + input: "leading\r\n\r\n## outcome\r\n\r\nsuccess\r\n\r\nbody\r\n", + outcome: "success", + body: "\r\nbody\r\n", + }, + { + name: "arbitrary markdown body is preserved exactly", + input: "# outcome\nsuccess\n\n## Heading\n\n- item\n\n```go\nfmt.Println(\"hi\")\n```\n\n# outcome is discussed here\n", + outcome: "success", + body: "\n## Heading\n\n- item\n\n```go\nfmt.Println(\"hi\")\n```\n\n# outcome is discussed here\n", + }, + { + name: "duplicate outcome", + input: "# outcome\nsuccess\n\n# outcome\nblocked\n", + err: ErrDuplicateOutcome, + }, + { + name: "duplicate inside a fence is ignored", + input: "```\n# outcome\nsuccess\n```\n\n# outcome\nblocked\n", + outcome: "blocked", + }, + { + name: "unknown outcome word", + input: "# outcome\nmaybe\n", + err: ErrOutcomeNotAllowed, + }, + { + name: "extra text on the outcome line", + input: "# outcome\nsuccess please\n", + err: ErrOutcomeNotAllowed, + }, + { + name: "value inside a fence is not an outcome value", + input: "# outcome\n```\nsuccess\n```\n", + err: ErrOutcomeNotAllowed, + }, + { + name: "empty output", + input: "", + err: ErrEmptyOutput, + }, + { + name: "whitespace-only output", + input: " \r\n\t\n", + err: ErrEmptyOutput, + }, + { + name: "missing outcome heading", + input: "# Result\nsuccess\n", + err: ErrMissingOutcome, + }, + { + name: "outcome heading without a value", + input: "# outcome\n\n", + err: ErrMissingOutcome, + }, + { + name: "fenced outcome is not a real outcome", + input: "```\n# outcome\nsuccess\n```\n", + err: ErrMissingOutcome, + }, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + outcome, body, err := ParseOutput(test.input, allowed) + if test.err != nil { + if !errors.Is(err, test.err) { + t.Fatalf("error = %v, want %v", err, test.err) + } + if outcome != "" || body != "" { + t.Fatalf("error result = (%q, %q), want empty", outcome, body) + } + return + } + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if outcome != test.outcome || body != test.body { + t.Fatalf("ParseOutput() = (%q, %q), want (%q, %q)", outcome, body, test.outcome, test.body) + } + }) + } +} + +func TestParseOutputReturnsCanonicalOutcome(t *testing.T) { + outcome, body, err := ParseOutput("#### Outcome\n\n Success \n\nrest", []string{" success ", "blocked"}) + if err != nil { + t.Fatalf("ParseOutput() error: %v", err) + } + if outcome != "success" { + t.Fatalf("outcome = %q, want canonical %q", outcome, "success") + } + if body != "\nrest" { + t.Fatalf("body = %q, want %q", body, "\nrest") + } +} + +func TestParseOutputRequiresWhitespaceAfterHeadingMarker(t *testing.T) { + if _, _, err := ParseOutput("#outcome\nsuccess\n", []string{"success"}); !errors.Is(err, ErrMissingOutcome) { + t.Fatalf("error = %v, want missing outcome", err) + } +} diff --git a/internal/turn/render.go b/internal/turn/render.go new file mode 100644 index 00000000..c63fcda9 --- /dev/null +++ b/internal/turn/render.go @@ -0,0 +1,74 @@ +package turn + +import ( + "fmt" + "sort" + "strings" +) + +// RenderInput renders the markdown a turn receives. The first turn receives the +// run prompt as-is. Later turns receive the previous turn's output verbatim +// under a heading; prompt is not repeated. +func RenderInput(prompt string, previousOutput string) string { + if strings.TrimSpace(previousOutput) == "" { + return prompt + } + return "# Previous turn output\n\n" + previousOutput +} + +// MemoryEntry is one completed turn in a later turn's memory file. Output is +// the turn's markdown body, without the outcome section. PublicFiles are paths +// relative to the run directory, so the public prefix is retained. +type MemoryEntry struct { + Stage string + Visit int + Output string + PublicFiles []string +} + +// RenderMemory renders completed turns in the order supplied. Each turn's output +// is embedded verbatim; the file list is system-written from PublicFiles and is +// sorted and deduplicated so the result is deterministic. +func RenderMemory(entries []MemoryEntry) string { + var b strings.Builder + for i, entry := range entries { + if i > 0 { + b.WriteString("\n") + } + fmt.Fprintf(&b, "## %s · visit %d\n\n", entry.Stage, entry.Visit) + if entry.Output != "" { + b.WriteString(entry.Output) + if !strings.HasSuffix(entry.Output, "\n") { + b.WriteString("\n") + } + b.WriteString("\n") + } + b.WriteString("Files added to public/:\n") + files := sortedUnique(entry.PublicFiles) + if len(files) == 0 { + b.WriteString("- _(none)_\n") + continue + } + for _, file := range files { + b.WriteString("- ") + b.WriteString(file) + b.WriteString("\n") + } + } + return b.String() +} + +func sortedUnique(values []string) []string { + if len(values) == 0 { + return nil + } + sorted := append([]string(nil), values...) + sort.Strings(sorted) + unique := sorted[:0] + for _, value := range sorted { + if len(unique) == 0 || unique[len(unique)-1] != value { + unique = append(unique, value) + } + } + return unique +} diff --git a/internal/turn/render_test.go b/internal/turn/render_test.go new file mode 100644 index 00000000..99e20412 --- /dev/null +++ b/internal/turn/render_test.go @@ -0,0 +1,74 @@ +package turn + +import ( + "strings" + "testing" +) + +func TestRenderInputFirstTurnIsTheRunPrompt(t *testing.T) { + prompt := "# Task\n\nImplement the thing.\n" + if got := RenderInput(prompt, ""); got != prompt { + t.Fatalf("first turn input = %q, want prompt verbatim", got) + } + if got := RenderInput(prompt, " \r\n\t"); got != prompt { + t.Fatalf("blank previous output should behave as the first turn, got %q", got) + } +} + +func TestRenderInputLaterTurnShowsOnlyPreviousOutput(t *testing.T) { + previous := "## Result\n\n- changed `internal/turn`\n\n```diff\n+new line\n```\n" + got := RenderInput("the original prompt", previous) + want := "# Previous turn output\n\n" + previous + if got != want { + t.Fatalf("later turn input = %q, want %q", got, want) + } + if strings.Contains(got, "the original prompt") { + t.Fatal("later turn input repeated the run prompt") + } +} + +func TestRenderMemory(t *testing.T) { + entries := []MemoryEntry{ + { + Stage: "planner", + Visit: 1, + Output: "# Plan\n\nDo the work.", + PublicFiles: []string{"public/b.md", "public/a.md", "public/a.md"}, + }, + { + Stage: "reviewer", + Visit: 2, + Output: "No public files.\n", + }, + } + want := "## planner · visit 1\n\n" + + "# Plan\n\nDo the work.\n\n" + + "Files added to public/:\n- public/a.md\n- public/b.md\n\n" + + "## reviewer · visit 2\n\n" + + "No public files.\n\n" + + "Files added to public/:\n- _(none)_\n" + if got := RenderMemory(entries); got != want { + t.Fatalf("RenderMemory() = %q, want %q", got, want) + } + if again := RenderMemory(entries); again != want { + t.Fatalf("RenderMemory() is not deterministic: %q", again) + } +} + +func TestRenderMemoryEmbedsOutputVerbatim(t *testing.T) { + output := "## Notes\n\n```md\n# outcome success\n```\n\nlast line without newline" + entries := []MemoryEntry{{Stage: "build", Visit: 3, Output: output, PublicFiles: []string{"public/report.md"}}} + got := RenderMemory(entries) + if !strings.Contains(got, output) { + t.Fatalf("output was not embedded verbatim:\n%s", got) + } + if !strings.Contains(got, "- public/report.md\n") { + t.Fatalf("public file list missing:\n%s", got) + } +} + +func TestRenderMemoryEmpty(t *testing.T) { + if got := RenderMemory(nil); got != "" { + t.Fatalf("RenderMemory(nil) = %q, want empty", got) + } +} diff --git a/web/AGENTS.md b/web/AGENTS.md index 4d1468f1..9c5e1a4f 100644 --- a/web/AGENTS.md +++ b/web/AGENTS.md @@ -28,13 +28,14 @@ not this one, decides whether a feature is done. | `src/serverUrl.js` | `data/transport/ServerUrl.kt` | `validateServerUrl`, `resolveArtifactUrl` | | `src/client.js` | `data/transport/PipelinesClient.kt` | one reused socket, id matching, timeout, backoff. **DOM-free** | | `src/repository.js` | `data/PipelinesRepository.kt` | typed request builders | -| `src/app.js` | `ui/**` | page shell: boot, state, client wiring, connection/banner, navigation/routes, render dispatch, header | +| `src/app.js` | `ui/**` | page shell: boot, state, client wiring, navigation/routes, render dispatch, persistent rail/workspace/dock | +| `src/shell.js` | `ui/WindowSize.kt`, `ui/components/DetailTabs.kt` | pure shell model: destinations, view/route mapping, roving-tabindex arithmetic, status words | | `src/dom.js` | — | `h()`, shared DOM helpers and clipboard/share actions | | `src/format.js` | `ui/Format.kt` (DOM-facing bits) | status tone and error-text helpers | | `src/views/*.js` | `ui/**` | one module per destination/dialog surface: attention, settings, pipelines, templates, runs, runDetail, chat, search, dialogs | | `index.html`, `*.css` | — | shell + area styles linked in a fixed order | | `serve.mjs` | — | static server + `/connect` proxy | -| `test/*.test.mjs` | `app/src/test/**` | `node --test`, no server needed | +| `test/*.test.mjs` | `app/src/test/**` | `node --test`, no server needed (including the shell/tab helpers) | | `test/smoke.mjs` | — | protocol smoke against a live server | | `test/browser.mjs` | — | zero-dep Chrome DevTools driver | | `test/ui-smoke.mjs` | UI review captures | live browser check + screenshots | diff --git a/web/PARITY.md b/web/PARITY.md index e694b66e..f3fafcb2 100644 --- a/web/PARITY.md +++ b/web/PARITY.md @@ -13,9 +13,9 @@ Status legend: `todo` · `partial` (some of it works) · `done` (working + captu | --- | --- | --- | --- | | T1 | Server-URL entry + validation rules (`data/transport/ServerUrl.kt`) | — | done | | T2 | One reused socket, id matching, request timeout, not-connected guard (`PipelinesClient.kt`) | — | done | -| T3 | Connect / disconnect / manual reconnect | `ping` | done — connect/disconnect captured (`captures/28-connected-banner.png`, the header control reading `Disconnect` while connected); the `Reconnect` control appears beside the URL field while idle/disconnected with a configured endpoint and calls `client.connect`, which resets the attempt/backoff for an immediate re-open (`captures/29-disconnected-banner.png`). `Disconnect` stays available while connected | -| T4 | Backoff recovery + foreground reconnect after sleep/blur (`ConnectionRecovery.kt`, `ForegroundReconnector.kt`) | — | done — the client's capped backoff is surfaced honestly rather than rewritten: `captures/29-disconnected-banner.png` shows the banner `Disconnected: Connection closed (1006) · retrying with backoff` and the header state badge `disconnected — Connection closed (1006) (attempt N, retrying)`. The attempt number is deliberately **not** in the banner text — `ConnectionBanner.kt`'s own disconnected copy omits it (Android names the attempt only while Connecting) — so the page's badge carries it instead of diverging from the Android wording. The foreground-reconnect **decision** (`foregroundAction`) is unit-tested in `test/connection.test.mjs` (Idle→LeaveAlone; Connecting/Disconnected→Reconnect; Connected→`confirmedAlive ? LeaveAlone : Reconnect`); the **rendered recovery** is captured in `captures/30-reconnect-recovered.png`, where the page (asserted still `Disconnected:`) is pointed back at the live server and the browser's own `online` event drives it to a green Connected. The browser uses its `online`/`visibilitychange` event as the liveness signal, so a still-Connected socket is left alone (no in-page positive ping probe is needed; a documented deviation from `ForegroundReconnector`'s positive ping) | -| T5 | Connection banner + live badge; build/protocol mismatch warning | `pong` build/protocol | done — a persistent banner in normal document flow under the header (never overlaying content): green `Connected` + `Server build …` (`captures/28-connected-banner.png`) and `Disconnected: … · retrying with backoff` (`captures/29-disconnected-banner.png`); a minimal dot+word live badge in the runs list/detail (`live` / `reconnecting` / `not live`, per `LiveBadge.kt`/`RunStream.kt`, `captures/28-connected-banner.png`). The build line comes from the `pong` in `SettingsScreen.kt`'s own shape, `Server build {version} ({commit})`; a dirty tree is already marked in `version` by `internal/buildinfo` (`-dirty`), so no duplicate `+dirty` marker is added. The protocol-mismatch warning (shown only when both values are present and differ, naming both) is unit-tested (`protocolMismatch`) and not captured because the live server reports `protocol` 1, matching `PROTOCOL_VERSION` | +| T3 | Connect / disconnect / manual reconnect | `ping` | done — connection now lives only in the Settings Connection section (L2–L4 moved it out of the chrome). `Connect` is connect-only, `Disconnect` closes the shared socket, and `Reconnect` re-opens the validated endpoint immediately, resetting the client's attempt/backoff; all three drive the page's one client. Captured 2026-10-19: `captures/84-shell-settings-connection-1440x900.png` (the connected status card and the Disconnect/Connect pair) and `captures/L1-settings-idle.png` (idle: Connect + Reconnect). The shell's rail/dock dot+word control mirrors the state and is a Settings shortcut (`captures/85-shell-status-indicator-1440x900.png`); the old header URL field, Connect/Disconnect button and state badge are gone | +| T4 | Backoff recovery + foreground reconnect after sleep/blur (`ConnectionRecovery.kt`, `ForegroundReconnector.kt`) | — | done — the client's capped backoff is surfaced honestly rather than rewritten: `captures/29-disconnected-banner.png` shows the Settings status card `Disconnected` / `Connection closed (1006)` / `Retrying with backoff…`, while the shell's compact indicator reads `Disconnected`. The attempt number is named only while Connecting (`Connecting (attempt N)…`), matching `ConnectionBanner.kt`; the disconnected card deliberately omits it rather than diverging from Android's wording. The foreground-reconnect **decision** (`foregroundAction`) is unit-tested in `test/connection.test.mjs` (Idle→LeaveAlone; Connecting/Disconnected→Reconnect; Connected→`confirmedAlive ? LeaveAlone : Reconnect`); the **rendered recovery** is captured in `captures/30-reconnect-recovered.png`, where the page (asserted still `Disconnected`) is pointed back at the live server and the browser's own `online` event drives it to a green Connected. The browser uses its `online`/`visibilitychange` event as the liveness signal, so a still-Connected socket is left alone (no in-page positive ping probe is needed; a documented deviation from `ForegroundReconnector`'s positive ping) | +| T5 | Connection status + live badge; build/protocol mismatch warning | `pong` build/protocol | done — the full status card lives in Settings (never overlaying content): green `Connected` + `Server build …` + `Server time …` (`captures/84-shell-settings-connection-1440x900.png`), `Disconnected` + the server's message + `Retrying with backoff…` (`captures/L1-settings-disconnected.png`), `Connecting (attempt N)…` (`captures/L1-settings-connecting.png`) and idle `Not connected` (`captures/L1-settings-idle.png`). The shell keeps only a compact dot+word indicator (connected / connecting / disconnected / not connected / not configured) in the rail footer and the narrow bar; it is never colour-only. The protocol-mismatch warning is rendered in the same Settings Connection section (and remains unit-tested via `protocolMismatch`); no live mismatch is expected because the server reports protocol 1. A minimal dot+word live badge still marks the run stream in the runs list/detail (`live` / `reconnecting` / `not live`, per `LiveBadge.kt`/`RunStream.kt`). The build line comes from the `pong` in `SettingsScreen.kt`'s own shape, `Server build {version} ({commit})`; a dirty tree is already marked in `version` by `internal/buildinfo` (`-dirty`), so no duplicate `+dirty` marker is added | | T6 | Artifact URL resolution against the configured server (`resolveArtifactUrl`) | `GET /artifacts/…` | done (URL only) | ## Pipelines @@ -45,7 +45,7 @@ Status legend: `todo` · `partial` (some of it works) · `done` (working + captu | R12 | Cancel run | `cancel_run` | done — `src/actions.js` `canCancel` offers a `Cancel run` action only while the run is `executing`; the confirm dialog is the Android copy verbatim (title `Cancel run {id}?`, `This asks the server to stop the active run.`, confirm `Cancel run`, dismiss `Keep`), and the request is exactly `{type:'cancel_run',run_id}` followed by a silent `get_run` refresh (unit-tested in `test/repository.test.mjs`). Captured `captures/40-run-459-cancel-confirm.png` on the executing run present at capture time. **Shown, not executed**: the only candidate was another live pipeline's executing run, so the dialog was shown and dismissed with `Keep` — no `cancel_run` was sent (a real cancel is only safe against a run started in a scratch workspace, which this stage did not do) | | R13 | Retry failed stage (resume) / restart from start | `retry_run` | done — `canRetry` is true only for a loaded, non-executing, `failed` run; the Retry confirm is the Android copy verbatim (title `Retry run {id}?`, `Only failed runs can be retried. The server starts a new run from the same input.`, confirm `Retry`, dismiss `Keep`) and the default send carries only `run_id` + a fresh `request_key` (**no** `retry_mode`, so the server's `resume` default applies exactly like the Android client's mode-less call; unit-tested). Captured `captures/35-run-440-run-actions.png` (failed run 440 offers Retry and no Cancel) and `captures/36-run-440-retry-confirm.png`. **Divergence from the Android UI, stated here**: Android exposes resume only while the protocol has both modes, so the browser adds a clearly-labelled secondary `Restart from start` confirm that states it `replays the whole pipeline from the start instead of resuming the failed stage` and sends `retry_mode:"restart"` (`captures/37-run-440-restart-confirm.png`). Both dialogs were shown and dismissed with `Keep`; no run was started | | R14 | Rename a run | `set_run_title` | done — an inline field on the Summary title row (pre-filled with the current title, `Rename` / `Save` / `Cancel`) sending exactly `{type:'set_run_title',run_id,title}` and then refreshing the run and the runs-list row (unit-tested). Captured `captures/38-run-440-rename-field.png`. The one shared `Action failed` dialog was exercised by a real refused rename: `captures/39-run-440-action-failed.png` shows the live server's exact reason `a title with usable text is required` (a blank title mutates nothing). **Divergence from the Android UI, stated here**: Android does not surface `set_run_title` at all (its README records the deliberate omission), so this control is browser-only | -| R15 | Attention / "Needs you" surface: counts, open, individual dismiss, clear all | derived from `list_runs` + run events | done — the pure `src/attention.js` model mirrors `ui/Attention.kt` and feeds a bell action in the top bar (badge only when non-empty; accessible name `Notifications` / `Notifications, {n} needing attention`) and a bottom sheet titled `Needs you` in `src/app.js`. Only a `waiting` run (kind Decision, rank 0) and a `failed` run (kind Failed, rank 1) qualify; order is kind rank, then recency descending (`finished_at` else `created_at`), then run id descending. Rows carry a status icon, the trimmed-title-else-pipeline label, the exact `{pipeline} · {detail}` line (`Waiting for your decision`, or the trimmed diagnostic else `Run failed`) and a trailing `Dismiss`; tapping a row opens the run, dismissing a Failed row first while a Decision row is left for its answer. Clear all acts only on the snapshot taken when the sheet opened; dismissals persist as one JSON array of `{runId}:{kind}` identities under `pipelines.web.attention.v1` with no expiry (blank/unreadable storage decodes to empty and never throws). Entries are derived from `list_runs` here; R10 will feed the same pure model the pushed `run_event` summaries, with no wording or ordering change. Captured 2026-10-19: `captures/35-attention-bell.png` (bell + badge on the Runs list), `captures/36-attention-sheet.png` (the open sheet), `captures/37-attention-dismissed.png` (one entry individually dismissed, badge 171→170), `captures/38-attention-cleared.png` (Clear all: the empty copy, no Clear all, badge gone). No run was parked in `waiting` on the live server at capture time, so the sheet is exercised with real failed runs and the decision-open path is unit-tested | +| R15 | Attention / "Needs you" surface: counts, open, individual dismiss, clear all | derived from `list_runs` + run events | done — the pure `src/attention.js` model mirrors `ui/Attention.kt` and feeds a bell action in the Runs list heading (badge only when non-empty; accessible name `Notifications` / `Notifications, {n} needing attention`) and a bottom sheet titled `Needs you` in `src/app.js`. Because the shell has no global top bar, the same count is mirrored as a badge on the Runs destination in the rail/dock, so an operator on Pipelines, Chat or Settings can still see that something needs attention without opening Runs; the bell itself stays the Runs-local entry point. Only a `waiting` run (kind Decision, rank 0) and a `failed` run (kind Failed, rank 1) qualify; order is kind rank, then recency descending (`finished_at` else `created_at`), then run id descending. Rows carry a status icon, the trimmed-title-else-pipeline label, the exact `{pipeline} · {detail}` line (`Waiting for your decision`, or the trimmed diagnostic else `Run failed`) and a trailing `Dismiss`; tapping a row opens the run, dismissing a Failed row first while a Decision row is left for its answer. Clear all acts only on the snapshot taken when the sheet opened; dismissals persist as one JSON array of `{runId}:{kind}` identities under `pipelines.web.attention.v1` with no expiry (blank/unreadable storage decodes to empty and never throws). Entries are derived from `list_runs` here; R10 will feed the same pure model the pushed `run_event` summaries, with no wording or ordering change. Captured 2026-10-19: `captures/35-attention-bell.png` (bell + badge on the Runs list), `captures/36-attention-sheet.png` (the open sheet), `captures/37-attention-dismissed.png` (one entry individually dismissed, badge 171→170), `captures/38-attention-cleared.png` (Clear all: the empty copy, no Clear all, badge gone). No run was parked in `waiting` on the live server at capture time, so the sheet is exercised with real failed runs and the decision-open path is unit-tested | Two wording decisions in R3's stage pane, recorded here as the app-authoritative choice: the visit's exported session is titled **Session** (the item text said @@ -76,7 +76,7 @@ rename's exact server reason and, under `--decide`, the full live decision flow. ## Search | # | Feature | Protocol | Status | | --- | --- | --- | --- | -| S1 | Omni-search across pipelines, versions, runs, steps, fields, artifacts | `search` | done — the top bar's `Search` control opens a full-width panel under it (field autofocused, placeholder `Search pipelines, runs and artifacts`, a `Close search` control; opening and closing leave the current view, selection and loaded data untouched, and Escape closes the field). One flat result list with no kind grouping, over a controls row: the kind select (`All kinds`/`Pipelines`/`Runs`/`Steps`/`Fields`/`Artifacts`/`Versions`), the sort select (`Relevance`/`Newest first`/`Name`), the one-line `{Kind} · {Sort}` summary and a `Clear filter` reset. The request is exactly `{type:"search",search:{query,kind,limit:0}}` — the server's own default cap, never above `SearchMaxLimit` 200 — debounced 250 ms after the last keystroke with Enter sending at once; a blank query clears locally with no request; the previous results stay visible (a thin progress bar above them) while a newer query loads and a stale reply is dropped by token; the first load shows the spinner and `Searching…`; an error takes precedence over the results. Failure copy is `AppViewModel`'s: a rejection naming an unknown command, or an older server's reply without `search_results`, reads `This server does not support search. Update the Pipelines server, then try again.` and any other failure carries the server's own text. Row text and blank fallbacks mirror `OmniSearchResults.searchRow` (a field hit's snippet emphasises the first case-insensitive query occurrence, never via `innerHTML`) and the empty state keeps Android's `No matches for "{query}".` / `No {kind} match "{query}".`. Captured 2026-10-19: `captures/01-search-results.png` (flat mixed list for the query `plan`, the controls row and summary `All kinds · Relevance`), `captures/02-search-kind-filter.png` (the `Pipelines` filter narrowing the list and the summary to `Pipelines · Relevance`) | +| S1 | Omni-search across pipelines, versions, runs, steps, fields, artifacts | `search` | done — the shell's `Search` control (rail on wide, dock on narrow) opens a full-width panel in the workspace flow (field autofocused, placeholder `Search pipelines, runs and artifacts`, a `Close search` control; opening and closing leave the current view, selection and loaded data untouched, Escape closes the field and returns focus to the Search control). One flat result list with no kind grouping, over a controls row: the kind select (`All kinds`/`Pipelines`/`Runs`/`Steps`/`Fields`/`Artifacts`/`Versions`), the sort select (`Relevance`/`Newest first`/`Name`), the one-line `{Kind} · {Sort}` summary and a `Clear filter` reset. The request is exactly `{type:"search",search:{query,kind,limit:0}}` — the server's own default cap, never above `SearchMaxLimit` 200 — debounced 250 ms after the last keystroke with Enter sending at once; a blank query clears locally with no request; the previous results stay visible (a thin progress bar above them) while a newer query loads and a stale reply is dropped by token; the first load shows the spinner and `Searching…`; an error takes precedence over the results. Failure copy is `AppViewModel`'s: a rejection naming an unknown command, or an older server's reply without `search_results`, reads `This server does not support search. Update the Pipelines server, then try again.` and any other failure carries the server's own text. Row text and blank fallbacks mirror `OmniSearchResults.searchRow` (a field hit's snippet emphasises the first case-insensitive query occurrence, never via `innerHTML`) and the empty state keeps Android's `No matches for "{query}".` / `No {kind} match "{query}".`. Captured 2026-10-19: `captures/01-search-results.png` (flat mixed list for the query `plan`, the controls row and summary `All kinds · Relevance`), `captures/02-search-kind-filter.png` (the `Pipelines` filter narrowing the list and the summary to `Pipelines · Relevance`) | | S2 | Result routing (open the pipeline, run, stage, artifact) | — | done — every selection closes and clears the search first, then routes through the page's existing navigation: a pipeline/version hit opens the pipeline detail at the result version (version 0 = latest); a run hit opens the run detail; a text hit opens the run-detail tab holding the match, resolved from the hit's `matched_field` (`input` → Input, `output` → Output, else Summary — the browser item's deliberate rule, not the recorded field name); a step or artifact hit opens the recorded visit's stage pane (the zero-based visit index within the stage, falling back to the plain run detail when the visit cannot be located); an unknown/absent payload is read-only and never navigates. Captured 2026-10-19, each with the routed destination asserted in the smoke run: `captures/03-search-route-pipeline.png` (`pipeline:24:v5` → `Plan and land` detail), `captures/04-search-route-run.png` (`run:457` → Runs detail), `captures/05-search-route-field.png` (`run:458:3`, `matched_field input` → the Input tab active), `captures/06-search-route-step.png` (`run:457:1` → the `planner` visit stage pane), `captures/07-search-route-artifact.png` (`/artifacts/355/2/…` → the `implementer` visit pane), `captures/08-search-route-version.png` (`pipeline:22:v6` → the `Server` detail) | Two wording decisions in Search, recorded here as the app-authoritative choices: @@ -97,7 +97,7 @@ the pipeline list already carries — rather than a pluralised verb. | C7 | Markdown rendering + code blocks | — | done — captured 2026-10-19: `captures/45-chat-transcript-newest.png` (opened at the newest content: bold, bullet lists, a `|` table with its `---` delimiter row and inline code spans from the live assistant answer), `captures/47b-chat-markdown-code.png` (a rendered fenced code block — label `js`, the pre body `const answer = 42;` — drawn in the live browser by the page's own `renderMarkdown`, the same function that renders the answer) and `captures/47-chat-reasoning-code.png`. The subset is exactly `Markdown.kt`: paragraphs, `#`–`######` headings, fenced code (```/~~~, the language label else `code`), block quotes, bullet/ordered lists, `|` tables with a `---` delimiter row, thematic rules, inline code, bold, italic (underscore only at word boundaries, so `snake_case` stays plain), `[label](url)` links and bare http(s) autolinks; HTML entities are decoded first in one pass, and HTML, reference links, strikethrough and nested lists render as plain text and are never dropped. **Code-block caveat, stated plainly**: the live assistant answer carries **no** fenced block — its four fences live in the reasoning transcript, which the app draws as plain text, not as markdown (`captures/47-chat-reasoning-code.png` shows one such fence as muted plain text; that is C6 material, not the markdown path). So the rendered `
` code block is captured from a labelled sample through the page's real renderer (`47b`), and the same path plus its `code`-else-language label is unit-tested in `test/markdown.test.mjs`. Only `http(s)` link targets become clickable — the transcript is untrusted model output, so a `javascript:`/`data:` target renders as its label, never as a live link |
 | C8 | Composer: send, stop, attachments, draft | `chat_prompt`, `chat_interrupt` | done — the composer at the foot of an open conversation: a growing 1–6-row `