Merge branch 'worktree-agent-a3cb3553b5c91a345'
This commit is contained in:
@@ -0,0 +1,97 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// RunShownMap returns the graph and per-stage progress a chat's run card
|
||||
// draws (protocol.ChatShownRunMap). It is nil, without an error, when the
|
||||
// graph has more than protocol.ChatShownRunMapStages stages. Only routing and
|
||||
// lifecycle facts are read: no step inputs, outputs or transcripts.
|
||||
func (s *Store) RunShownMap(ctx context.Context, id int64) (*protocol.ChatShownRunMap, error) {
|
||||
tx, err := s.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
var graphJSON string
|
||||
if err := tx.QueryRowContext(ctx, `SELECT v.graph_json FROM pipeline_runs r
|
||||
JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version WHERE r.id=?`, id).Scan(&graphJSON); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var graph protocol.Graph
|
||||
if err := json.Unmarshal([]byte(graphJSON), &graph); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(graph.Stages) > protocol.ChatShownRunMapStages {
|
||||
return nil, nil
|
||||
}
|
||||
rows, err := tx.QueryContext(ctx, `SELECT sequence,stage_key,status,outcome,target,
|
||||
COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ',started_at),''),COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ',finished_at),'')
|
||||
FROM run_steps WHERE run_id=? ORDER BY sequence`, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
result := &protocol.ChatShownRunMap{Stages: []protocol.ChatShownRunStage{}, Visits: []protocol.RunGraphVisit{}}
|
||||
index := map[string]int{}
|
||||
for _, stage := range graph.Stages {
|
||||
if _, seen := index[stage.Key]; seen || stage.Key == "" {
|
||||
continue
|
||||
}
|
||||
index[stage.Key] = len(result.Stages)
|
||||
result.Stages = append(result.Stages, protocol.ChatShownRunStage{
|
||||
Key: stage.Key, Type: stage.Type, Edges: stage.Edges, FallbackError: stage.FallbackError,
|
||||
})
|
||||
}
|
||||
latestStage := map[string]protocol.RunGraphVisit{}
|
||||
latestRoute := map[[3]string]protocol.RunGraphVisit{}
|
||||
for rows.Next() {
|
||||
var visit protocol.RunGraphVisit
|
||||
var started, finished string
|
||||
if err := rows.Scan(&visit.Sequence, &visit.Stage, &visit.Status, &visit.Outcome, &visit.Target, &started, &finished); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
latestStage[visit.Stage] = visit
|
||||
if visit.Outcome != "" && visit.Target != "" {
|
||||
latestRoute[[3]string{visit.Stage, visit.Outcome, visit.Target}] = visit
|
||||
}
|
||||
i, declared := index[visit.Stage]
|
||||
if !declared {
|
||||
continue
|
||||
}
|
||||
stage := &result.Stages[i]
|
||||
stage.Visits++
|
||||
stage.Status = visit.Status
|
||||
stage.RunningSince = 0
|
||||
start, startErr := time.Parse(time.RFC3339, started)
|
||||
end, endErr := time.Parse(time.RFC3339, finished)
|
||||
switch {
|
||||
case startErr == nil && endErr == nil && !end.Before(start):
|
||||
stage.Seconds += int64(end.Sub(start) / time.Second)
|
||||
case startErr == nil && finished == "" && visit.Status == "running":
|
||||
stage.RunningSince = start.UnixMilli()
|
||||
}
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
seen := map[int]bool{}
|
||||
for _, visit := range latestStage {
|
||||
seen[visit.Sequence] = true
|
||||
result.Visits = append(result.Visits, visit)
|
||||
}
|
||||
for _, visit := range latestRoute {
|
||||
if !seen[visit.Sequence] {
|
||||
seen[visit.Sequence] = true
|
||||
result.Visits = append(result.Visits, visit)
|
||||
}
|
||||
}
|
||||
sort.Slice(result.Visits, func(a, b int) bool { return result.Visits[a].Sequence < result.Visits[b].Sequence })
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package pipeline
|
||||
|
||||
import (
|
||||
"context"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRunShownMapCompactsVisitsAndTotalsStages(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, err := Open(filepath.Join(t.TempDir(), "map.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer store.Close()
|
||||
if _, err := store.Submit(ctx, "graph", Template([]string{"a", "b", "c"}, true)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pipelines, _ := store.List(ctx)
|
||||
definition, _ := store.Get(ctx, pipelines[0].ID, 1)
|
||||
id, _, err := store.CreateRun(ctx, definition, "map", "workspace", false, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// a → b loops back to a 20 times, then b → c, and c is still running.
|
||||
type step struct{ stage, status, outcome, target, started, finished string }
|
||||
var steps []step
|
||||
for i := 0; i < 20; i++ {
|
||||
steps = append(steps,
|
||||
step{"a", "completed", "success", "b", "2026-12-01 10:00:00", "2026-12-01 10:00:10"},
|
||||
step{"b", "completed", "retry", "a", "2026-12-01 10:00:10", "2026-12-01 10:00:15"})
|
||||
}
|
||||
steps = append(steps,
|
||||
step{"a", "completed", "success", "b", "2026-12-01 10:00:00", "2026-12-01 10:00:10"},
|
||||
step{"b", "completed", "success", "c", "2026-12-01 10:00:10", "2026-12-01 10:00:15"},
|
||||
step{"c", "running", "", "", "2026-12-01 10:05:00", ""})
|
||||
tx, err := store.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for i, s := range steps {
|
||||
var finished any
|
||||
if s.finished != "" {
|
||||
finished = s.finished
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, `INSERT INTO run_steps(run_id,sequence,stage_key,status,outcome,target,input_json,output_json,diagnostic,transcript,started_at,finished_at)
|
||||
VALUES(?,?,?,?,?,?,'{}','{}','PRIVATE','PRIVATE',?,?)`, id, i+1, s.stage, s.status, s.outcome, s.target, s.started, finished); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := store.RunShownMap(ctx, id)
|
||||
if err != nil || got == nil {
|
||||
t.Fatalf("map = %+v, %v", got, err)
|
||||
}
|
||||
if len(got.Stages) != 3 || got.Stages[0].Key != "a" || got.Stages[0].Edges["success"] != "b" {
|
||||
t.Fatalf("stages = %+v", got.Stages)
|
||||
}
|
||||
a, b, c := got.Stages[0], got.Stages[1], got.Stages[2]
|
||||
if a.Visits != 21 || a.Seconds != 210 || a.Status != "completed" || a.RunningSince != 0 {
|
||||
t.Fatalf("stage a = %+v", a)
|
||||
}
|
||||
if b.Visits != 21 || b.Seconds != 105 {
|
||||
t.Fatalf("stage b = %+v", b)
|
||||
}
|
||||
if c.Visits != 1 || c.Status != "running" || c.Seconds != 0 || c.RunningSince == 0 {
|
||||
t.Fatalf("stage c = %+v", c)
|
||||
}
|
||||
// Bounded by the graph: the latest visit of each stage and of each route.
|
||||
var routes []string
|
||||
for _, visit := range got.Visits {
|
||||
routes = append(routes, visit.Stage+">"+visit.Outcome+">"+visit.Target)
|
||||
}
|
||||
if want := "b>retry>a a>success>b b>success>c c>>"; strings.Join(routes, " ") != want {
|
||||
t.Fatalf("visits = %q, want %q", strings.Join(routes, " "), want)
|
||||
}
|
||||
}
|
||||
@@ -97,6 +97,37 @@ type ChatShownRunBody struct {
|
||||
Workspace string `json:"workspace,omitempty"`
|
||||
StartedAt int64 `json:"started_at,omitempty"`
|
||||
FinishedAt int64 `json:"finished_at,omitempty"`
|
||||
// Map is the run's graph and per-stage progress for the card's mini-map
|
||||
// and stage strip; nil when the server could not read it or the graph has
|
||||
// more than ChatShownRunMapStages stages.
|
||||
Map *ChatShownRunMap `json:"map,omitempty"`
|
||||
}
|
||||
|
||||
// ChatShownRunMapStages bounds the graph a run card carries.
|
||||
const ChatShownRunMapStages = 48
|
||||
|
||||
// ChatShownRunMap is a run's graph reduced to what a card draws: each
|
||||
// declared stage's routes and progress, and the compact route evidence (the
|
||||
// latest visit of every stage and of every taken route, in sequence order,
|
||||
// as RunGraphEvidence). Its size is bounded by the graph, not by the run's
|
||||
// length, so a long loop does not grow it.
|
||||
type ChatShownRunMap struct {
|
||||
Stages []ChatShownRunStage `json:"stages"`
|
||||
Visits []RunGraphVisit `json:"visits"`
|
||||
}
|
||||
|
||||
// ChatShownRunStage is one declared stage with its progress in the run.
|
||||
// Seconds totals its finished visits; RunningSince (epoch milliseconds) is the
|
||||
// start of a visit still running, so a client can add the live part.
|
||||
type ChatShownRunStage struct {
|
||||
Key string `json:"key"`
|
||||
Type string `json:"type,omitempty"`
|
||||
Edges map[string]string `json:"edges,omitempty"`
|
||||
FallbackError bool `json:"fallback_error,omitempty"`
|
||||
Visits int `json:"visits,omitempty"`
|
||||
Status string `json:"status,omitempty"`
|
||||
Seconds int64 `json:"seconds,omitempty"`
|
||||
RunningSince int64 `json:"running_since,omitempty"`
|
||||
}
|
||||
|
||||
// ChatShownDiffBody is one Git comparison a chat's model showed: the work tree
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// mappedShownRuns is a run store that also reads the card's graph map.
|
||||
type mappedShownRuns struct {
|
||||
mu sync.Mutex
|
||||
runs fakeShownRuns
|
||||
maps map[int64]*protocol.ChatShownRunMap
|
||||
}
|
||||
|
||||
func (m *mappedShownRuns) RunSummaryByID(ctx context.Context, id int64) (protocol.RunSummary, bool, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.runs.RunSummaryByID(ctx, id)
|
||||
}
|
||||
|
||||
func (m *mappedShownRuns) RunShownMap(_ context.Context, id int64) (*protocol.ChatShownRunMap, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.maps[id], nil
|
||||
}
|
||||
|
||||
func TestShowRunCarriesTheGraphMapAndRefreshesItsProgress(t *testing.T) {
|
||||
previous := shownRunRefreshDelay
|
||||
shownRunRefreshDelay = 10 * time.Millisecond
|
||||
t.Cleanup(func() { shownRunRefreshDelay = previous })
|
||||
f := newChatToolFixture(t)
|
||||
stages := func(implement string) []protocol.ChatShownRunStage {
|
||||
return []protocol.ChatShownRunStage{
|
||||
{Key: "plan", Edges: map[string]string{"success": "implement"}, Visits: 1, Status: "completed", Seconds: 30},
|
||||
{Key: "implement", Edges: map[string]string{"success": "#"}, Visits: 1, Status: implement},
|
||||
}
|
||||
}
|
||||
store := &mappedShownRuns{
|
||||
runs: fakeShownRuns{7: {ID: 7, Name: "feature", Status: "running", CurrentStage: "implement", CreatedAt: "2026-12-01T10:00:00Z"}},
|
||||
maps: map[int64]*protocol.ChatShownRunMap{7: {Stages: stages("running"), Visits: []protocol.RunGraphVisit{
|
||||
{Sequence: 1, Stage: "plan", Status: "completed", Outcome: "success", Target: "implement"},
|
||||
{Sequence: 2, Stage: "implement", Status: "running"},
|
||||
}}},
|
||||
}
|
||||
f.service.runs = store
|
||||
token := f.token(t, chatToolSessionScope+"ses_m")
|
||||
if r := f.call(token, "show_run", `{"run_id":7}`); r.IsError {
|
||||
t.Fatalf("show_run: %v", r)
|
||||
}
|
||||
item := f.items(t, "ses_m")[0]
|
||||
if item.Run.Map == nil || len(item.Run.Map.Stages) != 2 || item.Run.Map.Stages[1].Status != "running" {
|
||||
t.Fatalf("run map = %+v", item.Run.Map)
|
||||
}
|
||||
|
||||
// Only the stage progress changes: the summary is the same, the card is not.
|
||||
store.mu.Lock()
|
||||
store.maps[7] = &protocol.ChatShownRunMap{Stages: stages("completed"), Visits: store.maps[7].Visits}
|
||||
store.mu.Unlock()
|
||||
f.service.observeRun(protocol.RunEventFrame{RunID: 7, Status: "running"})
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
item = f.items(t, "ses_m")[0]
|
||||
if item.Run.Map != nil && item.Run.Map.Stages[1].Status == "completed" {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("the run map was not refreshed: %+v", item.Run.Map)
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"reflect"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -44,7 +45,7 @@ func (s *chatToolService) runShowRun(ctx context.Context, runID int64, title str
|
||||
if !found {
|
||||
return fail(fmt.Sprintf("there is no run %d.", runID))
|
||||
}
|
||||
body := shownRunBody(summary)
|
||||
body := s.shownRunBody(ctx, summary)
|
||||
item := protocol.ChatShownItem{Kind: protocol.ChatShownRun, Title: title, Run: &body}
|
||||
text := fmt.Sprintf("Shown in the operator's Pipelines chat: run %d of %s, %s", runID, body.Pipeline, body.Status)
|
||||
if body.CurrentStage != "" && !shownRunTerminal(body.Status) {
|
||||
@@ -53,12 +54,26 @@ func (s *chatToolService) runShowRun(ctx context.Context, runID int64, title str
|
||||
return &item, chattools.Result{Text: text + "; the card follows the run live."}
|
||||
}
|
||||
|
||||
func shownRunBody(summary protocol.RunSummary) protocol.ChatShownRunBody {
|
||||
return protocol.ChatShownRunBody{
|
||||
// chatShownRunMapStore reads the graph and stage progress a run card draws
|
||||
// (pipeline.Store). It is optional: without it a card has no mini-map.
|
||||
type chatShownRunMapStore interface {
|
||||
RunShownMap(ctx context.Context, id int64) (*protocol.ChatShownRunMap, error)
|
||||
}
|
||||
|
||||
func (s *chatToolService) shownRunBody(ctx context.Context, summary protocol.RunSummary) protocol.ChatShownRunBody {
|
||||
body := protocol.ChatShownRunBody{
|
||||
ID: summary.ID, Pipeline: summary.Name, Title: summary.Title, Status: summary.Status, Outcome: summary.Outcome,
|
||||
CurrentStage: summary.CurrentStage, Workspace: summary.Workspace,
|
||||
StartedAt: shownRunTime(summary.CreatedAt), FinishedAt: shownRunTime(summary.FinishedAt),
|
||||
}
|
||||
if maps, ok := s.runs.(chatShownRunMapStore); ok {
|
||||
runMap, err := maps.RunShownMap(ctx, summary.ID)
|
||||
if err != nil {
|
||||
log.Printf("chat tools: run %d card map: %v", summary.ID, err)
|
||||
}
|
||||
body.Map = runMap
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
func shownRunTime(value string) int64 {
|
||||
@@ -152,13 +167,13 @@ func (s *chatToolService) refreshRunItem(ctx context.Context, sessionID string,
|
||||
if err != nil || !found {
|
||||
return item
|
||||
}
|
||||
body := shownRunBody(summary)
|
||||
body := s.shownRunBody(ctx, summary)
|
||||
if shownRunTerminal(body.Status) {
|
||||
s.unwatchRun(body.ID, item.ID)
|
||||
} else {
|
||||
s.watchRun(body.ID, sessionID, item.ID)
|
||||
}
|
||||
if body == *item.Run {
|
||||
if reflect.DeepEqual(body, *item.Run) {
|
||||
return item
|
||||
}
|
||||
item.Run = &body
|
||||
|
||||
Reference in New Issue
Block a user