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.
This commit is contained in:
2026-10-16 13:35:43 +01:00
parent 0e6fbcc062
commit f3e0593f4d
23 changed files with 916 additions and 74 deletions
+102
View File
@@ -11,6 +11,7 @@ import (
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/runinspect"
"git.a-wan.net/alan/pipelines/internal/stage"
"git.a-wan.net/alan/pipelines/internal/summarise"
"net/http/httptest"
"os"
"path/filepath"
@@ -143,3 +144,104 @@ func TestCLIHeadlessRunInspectionCancellationAndRPC(t *testing.T) {
t.Fatal("wait lost terminal state", output)
}
}
// TestCLIRunTitlesExplicitDerivedAndRename is the end-to-end title check: it
// drives the real CLI against the real websocket server and store, starts one
// run with --title and one without, and verifies the title is visible in the
// human `runs` list, in `inspect`, and after a `title` rename. Stage execution is
// stubbed because the environment must not call a model, so the without-flag run
// exercises the server-side prompt fallback rather than the shared summariser.
func TestCLIRunTitlesExplicitDerivedAndRename(t *testing.T) {
t.Setenv("PIPELINES_HARNESS_CONFIG", filepath.Join(t.TempDir(), "harnesses.json"))
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "cli-titles.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if _, err := store.Submit(ctx, "workflow", pipeline.Template([]string{"worker"}, true)); err != nil {
t.Fatal(err)
}
handler := Handler(ctx, store)
r := handler.(*runHandler).runner
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
return stage.Result{Outcome: "success", Output: stage.Values{"summary": "done"}}, nil
}
http := httptest.NewServer(handler)
defer http.Close()
defer func() { cancel(); WaitRuns(handler) }()
url := "ws" + strings.TrimPrefix(http.URL, "http") + "/connect"
run := func(args ...string) (string, error) {
var out bytes.Buffer
app := cli.App{Out: &out, Err: &out, In: strings.NewReader("")}
err := app.Run(ctx, append([]string{"--url", url}, args...))
return out.String(), err
}
output, err := run("run", "workflow", "first prompt line\nmore detail", "--title", "Operator chosen title", "--yes", "--json", "--wait")
if err != nil {
t.Fatal(err)
}
var started protocol.Message
if err := json.Unmarshal([]byte(output), &started); err != nil {
t.Fatal(err)
}
explicitID := started.RunDetail.ID
if started.RunDetail.Title != "Operator chosen title" || started.RunDetail.TitleSource != summarise.SourceExplicit {
t.Fatalf("explicit --title = %+v", started.RunDetail)
}
output, err = run("run", "workflow", "Derived title from prompt\nsecond line", "--yes", "--json", "--wait")
if err != nil {
t.Fatal(err)
}
if err := json.Unmarshal([]byte(output), &started); err != nil {
t.Fatal(err)
}
if started.RunDetail.Title != "Derived title from prompt" || started.RunDetail.TitleSource != summarise.SourceFallback {
t.Fatalf("derived title = %+v", started.RunDetail)
}
output, err = run("runs")
if err != nil {
t.Fatal(err)
}
t.Logf("pipelines runs:\n%s", output)
for _, want := range []string{
fmt.Sprintf("%d\t%s\t%s\tv1\t%s\n", explicitID, "Operator chosen title", "workflow", "succeeded"),
fmt.Sprintf("%d\t%s\t%s\tv1\t%s\n", started.RunDetail.ID, "Derived title from prompt", "workflow", "succeeded"),
} {
if !strings.Contains(output, want) {
t.Fatalf("runs output missing %q:\n%s", want, output)
}
}
output, err = run("inspect", fmt.Sprint(explicitID), "--json")
if err != nil {
t.Fatal(err)
}
var detail protocol.RunDetail
if err := json.Unmarshal([]byte(output), &detail); err != nil {
t.Fatal(err)
}
if detail.Title != "Operator chosen title" || detail.Name != "workflow" || detail.Version != 1 {
t.Fatalf("inspect omitted title/name/version: %+v", detail)
}
output, err = run("title", fmt.Sprint(explicitID), "Renamed after the fact")
if err != nil {
t.Fatal(err)
}
t.Logf("pipelines title: %s", strings.TrimSpace(output))
output, err = run("inspect", fmt.Sprint(explicitID), "--json")
if err != nil {
t.Fatal(err)
}
if err := json.Unmarshal([]byte(output), &detail); err != nil {
t.Fatal(err)
}
if detail.Title != "Renamed after the fact" || detail.TitleSource != summarise.SourceExplicit {
t.Fatalf("rename not visible in inspect: %+v", detail)
}
}
+76 -18
View File
@@ -18,6 +18,7 @@ import (
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
"git.a-wan.net/alan/pipelines/internal/summarise"
)
// activeRun records one in-flight run's cancellation seam and the resolved
@@ -35,8 +36,12 @@ type runner struct {
mu sync.Mutex
active map[int64]activeRun
execute func(context.Context, stage.Definition, stage.Values) (stage.Result, error)
wg sync.WaitGroup
schedulerWG sync.WaitGroup
// title generates the operator-facing run title from the run prompt. When nil
// the store derives a fallback from the prompt with no model call, so tests
// and unconfigured servers stay deterministic.
title func(context.Context, string) summarise.Title
wg sync.WaitGroup
schedulerWG sync.WaitGroup
}
func newRunner(ctx context.Context, s *pipeline.Store) (*runner, error) {
@@ -158,13 +163,19 @@ func (r *runner) start(request protocol.Message, retryOf ...int64) (*protocol.Ru
}
}
}
// Decide admission and idempotency under the lock, but generate the title
// only for a request that will actually start a run: a rejected or replayed
// request must not pay for a bounded model generation, and a live one must
// not hold the lock (stalling listings and cancellation) while a model is
// called. An unavailable or slow model falls back to the prompt's first line.
r.mu.Lock()
defer r.mu.Unlock()
if r.ctx.Err() != nil {
r.mu.Unlock()
return nil, r.ctx.Err()
}
owners, err := r.store.ActiveSessionOwners(r.ctx)
if err != nil {
r.mu.Unlock()
return nil, err
}
// Refuse only an orphaned session: one whose owning run is not active now.
@@ -172,28 +183,49 @@ func (r *runner) start(request protocol.Message, retryOf ...int64) (*protocol.Ru
// workspace) must not block new work.
for _, owner := range owners {
if _, ok := r.active[owner.RunID]; !ok {
r.mu.Unlock()
return nil, fmt.Errorf("an agent may still be active; restart recovery must interrupt it before new work")
}
}
// Idempotent repeats are accepted even while the original run is active.
if len(r.active) > 0 {
existing, err := r.store.RunByKey(r.ctx, request.RequestKey)
if err != nil {
// Idempotent repeats are accepted even while the original run is active, and
// a replay reuses the stored title instead of generating a new one.
existing, err := r.store.RunByKey(r.ctx, request.RequestKey)
if err != nil {
r.mu.Unlock()
return nil, err
}
if existing == 0 {
if err := r.checkWorkspaceFree(workspace); err != nil {
r.mu.Unlock()
return nil, err
}
if existing == 0 {
// The workspace is the only scope a run reserves: refuse a second
// run only when an active run is already changing this exact
// resolved directory. One active run per workspace keeps this scan
// finding at most one match, so the message is deterministic.
for id, entry := range r.active {
if entry.workspace == workspace {
return nil, fmt.Errorf("run %d is already active in workspace %s; wait for it to finish or start this run in a different workspace (for example another checkout of the repository)", id, workspace)
}
}
}
r.mu.Unlock()
var runTitle summarise.Title
if existing == 0 {
// An explicit operator title skips the model call; otherwise the
// configured generator names the run, falling back to the prompt's
// first line when it is unavailable or slow.
if explicit, ok := summarise.ExplicitTitle(request.Title); ok {
runTitle = explicit
} else if r.title != nil {
prompt, _ := request.Input["prompt"].(string)
runTitle = r.title(r.ctx, prompt)
}
}
id, created, err := r.store.CreateRun(r.ctx, d, request.RequestKey, workspace, request.AllowTools, request.WritePaths, request.Input, retryOf...)
r.mu.Lock()
defer r.mu.Unlock()
// Another run may have reserved this workspace while the title was
// generated, so re-check before reserving it; a race on the request key is
// handled by the store's idempotent insert.
if existing == 0 {
if err := r.checkWorkspaceFree(workspace); err != nil {
return nil, err
}
}
id, created, err := r.store.CreateRunTitled(r.ctx, d, request.RequestKey, workspace, request.AllowTools, request.WritePaths, request.Input, runTitle, retryOf...)
if err != nil {
return nil, err
}
@@ -215,6 +247,19 @@ func (r *runner) start(request protocol.Message, retryOf ...int64) (*protocol.Ru
return detail, err
}
// checkWorkspaceFree refuses a run when an active run is already changing the
// same resolved workspace. The workspace is the only scope a run reserves, and
// one active run per workspace keeps this scan finding at most one match, so the
// message is deterministic. Callers must hold r.mu.
func (r *runner) checkWorkspaceFree(workspace string) error {
for id, entry := range r.active {
if entry.workspace == workspace {
return fmt.Errorf("run %d is already active in workspace %s; wait for it to finish or start this run in a different workspace (for example another checkout of the repository)", id, workspace)
}
}
return nil
}
func (r *runner) getRun(id int64) (*protocol.RunDetail, error) {
r.mu.Lock()
defer r.mu.Unlock()
@@ -279,6 +324,19 @@ func (r *runner) cancel(id int64) error {
return nil
}
// setTitle renames a run: it replaces the stored operator-facing title without
// touching the run's input, steps or execution, then returns the updated detail.
func (r *runner) setTitle(id int64, title string) (*protocol.RunDetail, error) {
explicit, ok := summarise.ExplicitTitle(title)
if !ok {
return nil, fmt.Errorf("a title with usable text is required")
}
if err := r.store.SetRunTitle(r.ctx, id, explicit); err != nil {
return nil, err
}
return r.getRun(id)
}
func (r *runner) run(ctx context.Context, id int64, d *protocol.PipelineDetail, workspace string, request protocol.Message) {
input := stage.Values(request.Input)
key := d.Graph.Stages[0].Key
+186
View File
@@ -11,8 +11,194 @@ import (
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/stage"
"git.a-wan.net/alan/pipelines/internal/summarise"
)
// TestRunTitleGeneratedPersistedAndFallback proves the insert path stores a
// generated title with its provenance in list and detail responses, and falls
// back to a derived bounded title when no generator is wired, without failing
// run creation.
func TestRunTitleGeneratedPersistedAndFallback(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "titles.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if _, err := store.Submit(ctx, "titled", pipeline.Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
return stage.Result{Outcome: "success", Output: stage.Values{}}, nil
}
r.title = func(context.Context, string) summarise.Title {
return summarise.Title{Text: "Fix the flaky login test", Source: summarise.SourceModel, Model: "openai/gpt"}
}
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "model-title", Workspace: t.TempDir(), Input: map[string]any{"prompt": "prompt body"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, err := store.GetRun(ctx, run.ID)
if err != nil {
t.Fatal(err)
}
if detail.Title != "Fix the flaky login test" || detail.TitleSource != summarise.SourceModel || detail.TitleModel != "openai/gpt" {
t.Fatalf("model title not stored with provenance: %+v", detail)
}
list, err := store.ListRuns(ctx)
if err != nil || len(list) != 1 || list[0].Title != "Fix the flaky login test" {
t.Fatalf("run list omitted the title: %v %v", list, err)
}
// No generator: the fallback is derived from the prompt's first line and run
// creation still succeeds.
r.title = nil
fallback, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "fallback-title", Workspace: t.TempDir(), Input: map[string]any{"prompt": "Fix the widget\nand more detail"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
detail, err = store.GetRun(ctx, fallback.ID)
if err != nil {
t.Fatal(err)
}
if detail.Title != "Fix the widget" || detail.TitleSource != summarise.SourceFallback || detail.TitleModel != "" {
t.Fatalf("fallback title = %+v, want the prompt's first line", detail)
}
}
// TestRunTitleGeneratorSkippedForReplayAndRejection proves the bounded
// generation runs only for a request that starts a run: an idempotent replay and
// a request refused for an already-reserved workspace must not pay for it.
func TestRunTitleGeneratorSkippedForReplayAndRejection(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "skip.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if _, err := store.Submit(ctx, "skip", pipeline.Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
release := make(chan struct{})
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
<-release
return stage.Result{Outcome: "success", Output: stage.Values{}}, nil
}
calls := 0
r.title = func(context.Context, string) summarise.Title {
calls++
return summarise.Title{Text: "Generated", Source: summarise.SourceModel}
}
workspace := t.TempDir()
first, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "skip-key", Workspace: workspace, Input: map[string]any{"prompt": "first"}})
if err != nil {
t.Fatal(err)
}
if calls != 1 {
t.Fatalf("first start generated %d titles, want 1", calls)
}
// A replay while the first run is active reuses the stored title.
replay, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "skip-key", Workspace: workspace, Input: map[string]any{"prompt": "first"}})
if err != nil || replay.ID != first.ID {
t.Fatalf("replay = %+v, %v; want run %d", replay, err, first.ID)
}
// A new key in the already-reserved workspace is refused.
if _, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "skip-other", Workspace: workspace, Input: map[string]any{"prompt": "second"}}); err == nil {
t.Fatal("workspace conflict was not refused")
}
if calls != 1 {
t.Fatalf("replay/rejection generated %d titles, want 1", calls)
}
close(release)
r.wg.Wait()
}
func TestHandlerWiresRunTitleGenerator(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
store, err := pipeline.Open(filepath.Join(t.TempDir(), "wire.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
configured := HandlerWithOptions(ctx, Options{RunTitles: summarise.GenerateTitle}, store).(*runHandler)
bare := HandlerWithOptions(ctx, Options{}, store).(*runHandler)
defer func() { cancel(); WaitRuns(configured); WaitRuns(bare) }()
if configured.runner.title == nil {
t.Fatal("configured RunTitles was not applied to the runner")
}
if bare.runner.title != nil {
t.Fatal("unconfigured RunTitles must keep deterministic fallback title generation")
}
}
// TestRunnerExplicitTitleSkipsGeneratorAndRenames proves an explicit --title is
// stored verbatim and skips the model generator, and that setTitle later
// replaces it with an explicit provenance without touching the run's input.
func TestRunnerExplicitTitleSkipsGeneratorAndRenames(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
store, err := pipeline.Open(filepath.Join(t.TempDir(), "explicit.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if _, err := store.Submit(ctx, "explicit", pipeline.Template([]string{"one"}, true)); err != nil {
t.Fatal(err)
}
items, _ := store.List(ctx)
r, err := newRunner(ctx, store)
if err != nil {
t.Fatal(err)
}
r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) {
return stage.Result{Outcome: "success", Output: stage.Values{}}, nil
}
generated := 0
r.title = func(context.Context, string) summarise.Title {
generated++
return summarise.Title{Text: "Generated", Source: summarise.SourceModel}
}
run, err := r.start(protocol.Message{PipelineID: items[0].ID, Version: 1, RequestKey: "explicit-key", Workspace: t.TempDir(), Title: "Operator chosen title", Input: map[string]any{"prompt": "prompt body"}})
if err != nil {
t.Fatal(err)
}
r.wg.Wait()
if generated != 0 {
t.Fatalf("explicit title still called the generator %d times", generated)
}
if run.Title != "Operator chosen title" || run.TitleSource != summarise.SourceExplicit || run.TitleModel != "" {
t.Fatalf("explicit title = %+v", run)
}
renamed, err := r.setTitle(run.ID, " Renamed after the fact ")
if err != nil {
t.Fatal(err)
}
if renamed.Title != "Renamed after the fact" || renamed.TitleSource != summarise.SourceExplicit || renamed.Input["prompt"] != "prompt body" {
t.Fatalf("rename = %+v", renamed)
}
if _, err := r.setTitle(run.ID, " "); err == nil {
t.Fatal("blank rename was accepted")
}
if _, err := r.setTitle(run.ID+999, "ghost"); err == nil {
t.Fatal("renaming an unknown run was accepted")
}
}
func TestRunnerRoutingPersistenceAndIdempotency(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
+12 -1
View File
@@ -15,6 +15,7 @@ import (
"git.a-wan.net/alan/pipelines/internal/buildinfo"
"git.a-wan.net/alan/pipelines/internal/pipeline"
"git.a-wan.net/alan/pipelines/internal/protocol"
"git.a-wan.net/alan/pipelines/internal/summarise"
)
// Options configures the HTTP handler.
@@ -31,6 +32,10 @@ type Options struct {
// it from the first store; when neither is available chat_sessions returns an
// empty list rather than the endpoint's whole session list.
OwnedSessions func(context.Context) ([]pipeline.SessionOwner, error)
// RunTitles generates the operator-facing title stored with each new run.
// When nil, run creation stores the prompt-derived fallback without a model
// call, which keeps tests and unconfigured servers deterministic.
RunTitles func(context.Context, string) summarise.Title
}
// Handler serves the persistent connection with default options. Canceling ctx
@@ -53,6 +58,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
if runErr == nil && options.ArtifactsRoot != "" {
runs.artifactsRoot = options.ArtifactsRoot
}
if runErr == nil && options.RunTitles != nil {
runs.title = options.RunTitles
}
if runErr == nil {
runs.schedulerWG.Add(1)
go runs.scheduleLoop()
@@ -192,7 +200,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
} else {
response.Pipelines = items
}
} else if runs != nil && (request.Type == protocol.RunPipeline || request.Type == protocol.RetryRun || request.Type == protocol.ListRuns || request.Type == protocol.GetRun || request.Type == protocol.CancelRun || request.Type == protocol.GetRunEvidence) {
} else if runs != nil && (request.Type == protocol.RunPipeline || request.Type == protocol.RetryRun || request.Type == protocol.ListRuns || request.Type == protocol.GetRun || request.Type == protocol.CancelRun || request.Type == protocol.SetRunTitle || request.Type == protocol.GetRunEvidence) {
var err error
switch request.Type {
case protocol.GetRunEvidence:
@@ -204,6 +212,9 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin
case protocol.RetryRun:
response.Type = protocol.RunStarted
response.RunDetail, err = runs.retry(request)
case protocol.SetRunTitle:
response.Type = protocol.Run
response.RunDetail, err = runs.setTitle(request.RunID, request.Title)
case protocol.ListRuns:
response.Type = protocol.Runs
response.Runs, err = runs.listRuns()