cli: add wait <run-id> to block until runs finish, then report them

The harness resumes a session when a background command finishes, so "tell me
when this run is done" needs one command that blocks and exits rather than a
polling script.

- `pipelines wait <run-id> [run-id ...]` resolves every id up front (an unknown
  run is a fast client error), then polls each run to a terminal status -
  `succeeded`, `failed`, `canceled` or `interrupted`, blocking through a run
  parked on a human decision - and prints one line per run as it finishes with
  id, status and outcome, stage and duration.
- A finished-but-unsuccessful run is still a finished run: it is reported and
  the command exits 0. The exit is non-zero only for a client-side failure: an
  unknown id, a connection that cannot be established, or `--timeout` expiring
  while a run is still active. A timeout reports the still-active runs,
  changes nothing, and is never treated as a run's outcome.
- Reuses the existing `run --wait` polling machinery: the per-second `get_run`
  reattachment is factored into `awaitRuns`, used by `finishRun` too. No
  subscription or new protocol message. `--url`/`--timeout` follow the existing
  client conventions; `--timeout` is the overall client limit (default 0).
- Read-only: sends only `get_run`, resolves no workspace, is not refused by the
  workspace guard and writes nothing. `--json` prints the final run envelope
  (one envelope for one id, an array for several).
- `commands.go` and `help.go` add it to the usage inventory and EXECUTE help.

Tests: `wait_test.go` (line format, batch reporting, wait-until-terminal,
unknown id, timeout leaves the run active, `--json` shape) and
`wait_command_test.go` (real CLI against the real websocket server and store).

Packaged assets checked: no packaged template changes. No authoring skill
reference file is added, so `internal/author/install.go`'s managed inventory
needs no change. `internal/author/skill/references/operations.md` (the
"inspect results first" run-operations list) and `docs/cli.md` (the scripted-runs
`--wait` paragraph and the CLI/TUI capability-map row) are now stale and are
recorded - not edited - in `docs/notes/wait-command.md` for the `docs-fold`
writer. `SKILL.md` stays a task-directed index; no shared document is edited
here.

No protocol, server, store, TUI or Android change; no new dependency; no run
started. Committed locally only, not pushed or deployed.
This commit is contained in:
2026-10-18 01:11:26 +01:00
parent 78725e92f0
commit b7c2ba7d56
6 changed files with 668 additions and 17 deletions
+210 -17
View File
@@ -90,7 +90,14 @@ func (a App) flags(command string) (*flag.FlagSet, *options) {
f.SetOutput(a.Err)
f.StringVar(&o.url, "url", envOr("PIPELINES_URL", "ws://127.0.0.1:8080/connect"), "Pipeline server WebSocket URL")
f.BoolVar(&o.json, "json", false, "Machine-readable JSON; no interactive picker/editor")
f.DurationVar(&o.timeout, "timeout", 30*time.Second, "Timeout per server request")
if command == "wait" {
// A wait blocks until the runs reach a terminal status, so its --timeout
// is the overall client limit (0 is the default and waits until they
// finish), not a per-request transport timeout.
f.DurationVar(&o.timeout, "timeout", 0, "Give up after this long while a run is still active (0 waits until it finishes)")
} else {
f.DurationVar(&o.timeout, "timeout", 30*time.Second, "Timeout per server request")
}
switch command {
case "provider-check":
f.StringVar(&o.harness, "harness", "opencode", "Provider-check harness: opencode or configured pi")
@@ -314,7 +321,7 @@ func (a App) Run(ctx context.Context, args []string) error {
}
return err
}
if o.timeout <= 0 || o.waitTimeout < 0 || o.version < 0 || o.expected < 0 {
if o.timeout < 0 || (o.timeout == 0 && command != "wait") || o.waitTimeout < 0 || o.version < 0 || o.expected < 0 {
return fmt.Errorf("timeout must be positive, wait-timeout nonnegative, and versions nonnegative")
}
pos := f.Args()
@@ -449,7 +456,13 @@ func (a App) Run(ctx context.Context, args []string) error {
return nil
}
// Connect only for server operations. Keep each RPC bounded, not the interactive session.
dialCtx, cancel := context.WithTimeout(ctx, o.timeout)
// `wait` uses --timeout as its overall wait limit, so its per-request transport
// timeout falls back to the usual bound.
requestTimeout := o.timeout
if requestTimeout <= 0 {
requestTimeout = 30 * time.Second
}
dialCtx, cancel := context.WithTimeout(ctx, requestTimeout)
c, err := client.Open(dialCtx, o.url)
cancel()
if err != nil {
@@ -475,7 +488,7 @@ func (a App) Run(ctx context.Context, args []string) error {
}
})
call := func(request protocol.Message) (protocol.Message, error) {
requestCtx, cancel := context.WithTimeout(ctx, o.timeout)
requestCtx, cancel := context.WithTimeout(ctx, requestTimeout)
defer cancel()
return c.Call(requestCtx, request)
}
@@ -1020,6 +1033,8 @@ func (a App) Run(ctx context.Context, args []string) error {
return a.output(r)
case "run":
return a.run(ctx, pos, o, call, resolve)
case "wait":
return a.wait(ctx, pos, o, call)
}
return nil
}
@@ -1296,22 +1311,19 @@ func (a App) finishRun(ctx context.Context, r protocol.Message, o *options, call
defer timer.Stop()
deadline = timer.C
}
for r.RunDetail.Status == "running" || r.RunDetail.Status == "queued" {
select {
case <-ctx.Done():
return ctx.Err()
case <-deadline:
final := r
err = a.awaitRuns(ctx, []protocol.Message{r}, deadline, call, runInProgress, func(terminal protocol.Message) error {
final = terminal
return nil
})
if err != nil {
var limit *waitLimitError
if errors.As(err, &limit) {
return fmt.Errorf("client wait limit reached for run %d; it remains active and was not canceled; inspect it read-only with pipelines inspect %d --json, and to keep waiting rerun with --wait reusing the original --request-key instead of starting a duplicate run", r.RunDetail.ID, r.RunDetail.ID)
case <-time.After(time.Second):
}
r, err = call(protocol.Message{Type: protocol.GetRun, RunID: r.RunDetail.ID})
if err != nil {
return err
}
if r.RunDetail == nil {
return fmt.Errorf("missing run detail")
}
return err
}
r = final
}
if err = a.output(r); err != nil {
return err
@@ -1322,6 +1334,187 @@ func (a App) finishRun(ctx context.Context, r protocol.Message, o *options, call
return nil
}
// wait polls every named run to a terminal status and reports each as it
// finishes, reusing the run --wait reattachment (GetRun) rather than a second
// mechanism. It is read-only: it resolves no workspace, never cancels, retries
// or otherwise changes a run, and a timeout is never treated as a run's
// outcome.
func (a App) wait(ctx context.Context, pos []string, o *options, call callFunc) error {
if len(pos) == 0 {
return fmt.Errorf("wait requires at least one run ID; use pipelines help wait")
}
// Resolve every id up front so an unknown run is a fast client error rather
// than something a wait would discover only after the others finish.
initial := make([]protocol.Message, 0, len(pos))
for _, value := range pos {
id, err := strconv.ParseInt(value, 10, 64)
if err != nil || id <= 0 {
return fmt.Errorf("run ID must be positive: %q", value)
}
r, err := call(protocol.Message{Type: protocol.GetRun, RunID: id})
if err != nil {
return err
}
if r.RunDetail == nil {
return fmt.Errorf("server did not return run detail for %d", id)
}
initial = append(initial, r)
}
// --timeout bounds the whole wait; 0 (the default) waits until every run
// finishes. Reaching the limit reports the still-active runs and changes
// nothing.
var deadline <-chan time.Time
if o.timeout > 0 {
timer := time.NewTimer(o.timeout)
defer timer.Stop()
deadline = timer.C
}
terminal := make([]protocol.Message, 0, len(initial))
err := a.awaitRuns(ctx, initial, deadline, call, runUnfinished, func(r protocol.Message) error {
terminal = append(terminal, r)
if o.json {
return nil
}
_, writeErr := fmt.Fprintln(a.Out, waitLine(r.RunDetail))
return writeErr
})
if err != nil {
var limit *waitLimitError
if errors.As(err, &limit) {
return fmt.Errorf("wait limit reached; %s still active and not canceled - nothing was changed; rerun pipelines wait to keep waiting", limit.Runs())
}
return err
}
if o.json {
if len(terminal) == 1 {
return a.output(terminal[0])
}
return a.output(terminal)
}
return nil
}
// awaitRuns polls every run that active reports as unfinished until each is
// terminal, using the same GetRun reattachment the run --wait path uses, and
// calls onTerminal for each as it finishes (including runs already terminal at
// entry, in the order supplied). A deadline that passes first returns a
// *waitLimitError naming the runs still active; ctx ending first returns
// ctx.Err(). It never cancels, retries or otherwise changes a run.
func (a App) awaitRuns(ctx context.Context, runs []protocol.Message, deadline <-chan time.Time, call callFunc, active func(string) bool, onTerminal func(protocol.Message) error) error {
remaining := make([]protocol.Message, 0, len(runs))
for _, r := range runs {
if active(r.RunDetail.Status) {
remaining = append(remaining, r)
continue
}
if err := onTerminal(r); err != nil {
return err
}
}
for len(remaining) > 0 {
select {
case <-ctx.Done():
return ctx.Err()
case <-deadline:
return &waitLimitError{IDs: runIDs(remaining)}
case <-time.After(time.Second):
}
next := remaining[:0]
for _, r := range remaining {
refreshed, err := call(protocol.Message{Type: protocol.GetRun, RunID: r.RunDetail.ID})
if err != nil {
return err
}
if refreshed.RunDetail == nil {
return fmt.Errorf("server did not return run detail for %d", r.RunDetail.ID)
}
if active(refreshed.RunDetail.Status) {
next = append(next, refreshed)
continue
}
if err := onTerminal(refreshed); err != nil {
return err
}
}
remaining = next
}
return nil
}
// runInProgress is the active set the run --wait path stops at: a run is still
// being worked on while it is queued or running.
func runInProgress(status string) bool {
return status == protocol.RunStatusQueued || status == protocol.RunStatusRunning
}
// runUnfinished is the active set `pipelines wait` blocks on: the same as
// runInProgress plus a run parked on a human decision (waiting), which has not
// finished either.
func runUnfinished(status string) bool {
return runInProgress(status) || status == protocol.RunStatusWaiting
}
// runIDs extracts the ids of the runs still active when a wait limit passed.
func runIDs(runs []protocol.Message) []int64 {
ids := make([]int64, 0, len(runs))
for _, r := range runs {
ids = append(ids, r.RunDetail.ID)
}
return ids
}
// waitLimitError reports that the client's wait limit was reached while the
// named runs were still active. The runs are untouched: a wait never cancels,
// retries or changes a run, and a timeout is never treated as its outcome.
type waitLimitError struct{ IDs []int64 }
func (e *waitLimitError) Error() string {
return "wait limit reached while run(s) " + e.Runs() + " were still active"
}
// Runs renders the still-active run ids for display.
func (e *waitLimitError) Runs() string {
parts := make([]string, 0, len(e.IDs))
for _, id := range e.IDs {
parts = append(parts, "run "+strconv.FormatInt(id, 10))
}
return strings.Join(parts, ", ")
}
// waitLine is the one-line terminal report `pipelines wait` prints: the run id,
// its status and outcome, its stage and how long it took.
func waitLine(d *protocol.RunDetail) string {
line := fmt.Sprintf("run %d · %s", d.ID, d.Status)
if outcome := strings.TrimSpace(d.Outcome); outcome != "" {
line += " (" + outcome + ")"
}
if stage := strings.TrimSpace(d.CurrentStage); stage != "" {
line += " · " + stage
}
if elapsed := runElapsed(d.CreatedAt, d.FinishedAt); elapsed != "" {
line += " · " + elapsed
}
return line
}
// runElapsed renders a run's wall-clock duration from its stored timestamps. An
// unparseable or missing start yields "" so the line omits the duration rather
// than inventing one; an empty finish uses the current time.
func runElapsed(start, end string) string {
first, err := time.Parse(time.RFC3339, start)
if err != nil {
return ""
}
last, err := time.Parse(time.RFC3339, end)
if err != nil {
if end != "" {
return ""
}
last = time.Now()
}
return max(time.Duration(0), last.Sub(first)).Round(time.Second).String()
}
// providerCheckDocker runs the provider check inside the profile's existing
// Compose service so a Docker-linked profile never falls back to a host harness.
// It streams the child's stdout/stderr and returns its exact exit code.