package tui import ( "cmp" "slices" ) // The order and folding of an agent's siblings, the same rule as the web // client's agents menu and tree (web/src/lib/agentTree.ts); robot-docs/agents.md // "the order of agents" describes it once for both. // agentRank is where an agent goes among its siblings, lowest first: working, // then idle, then closed, and within each the latest turn (its start or end) // first. type agentRank struct { state int activity int64 } func (a agentRank) compare(b agentRank) int { return cmp.Or(cmp.Compare(a.state, b.state), cmp.Compare(b.activity, a.activity)) } func rankOf(n *agentNode) agentRank { state := 1 switch { case n.closed: state = 2 case n.running: state = 0 } return agentRank{state: state, activity: cmp.Or(n.activityAt, n.createdAt)} } func millis(at *int64) int64 { if at == nil { return 0 } return *at } // oldestFirst orders agents by when they were made, then by id. func oldestFirst(a, b *agentNode) int { return cmp.Or(cmp.Compare(a.createdAt, b.createdAt), cmp.Compare(a.id, b.id)) } // rankChildren sorts each parent's children by rank, a branch ranked by the // lowest in it so a working agent's parents come up with it, oldest first // among equals. ranks holds every agent's rank. func rankChildren(children map[string][]*agentNode, ranks map[string]agentRank) { best := map[string]agentRank{} var branch func(n *agentNode) agentRank branch = func(n *agentNode) agentRank { if low, ok := best[n.id]; ok { return low } low := ranks[n.id] for _, child := range children[n.id] { if r := branch(child); r.compare(low) < 0 { low = r } } best[n.id] = low return low } for _, list := range children { slices.SortFunc(list, oldestFirst) } for _, list := range children { slices.SortStableFunc(list, func(a, b *agentNode) int { return branch(a).compare(branch(b)) }) } } // closedLeaves splits a parent's ranked children into the ones shown as // themselves and the closed ones with no agents below them, which fold into // one row once there are two or more. func closedLeaves(kids []*agentNode, children map[string][]*agentNode) (shown, folded []*agentNode) { for _, kid := range kids { if kid.closed && len(children[kid.id]) == 0 { folded = append(folded, kid) } else { shown = append(shown, kid) } } if len(folded) == 1 { return append(shown, folded...), nil } return shown, folded }