package tui import ( "fmt" "strings" "albedo/cli/internal/daemon" tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) // cdPhase is where the /cd question box is: asking while the preflight is // out or answered, then moving, attaching or failed once yes was chosen. A // move that reaches its checklist waits there until it is finished. type cdPhase int const ( cdAsking cdPhase = iota cdMoving cdChecklist cdFinishing cdAttaching cdFailed ) // The one question a /cd to another host's folder asks, worded as ana // decided it. const ( cdQuestionText = "Copy memory and move the agent to this machine's daemon?" cdQuestionNote = "No runs only the model's python kernel remotely while its agent loop stays on this machine." ) // cdQuestion is the box /cd opens over the screen for a folder on another // host: yes moves the whole session to that host's daemon, no moves only // its kernel there, as /cd always did. A session the target can only run on // another of its profiles lists them under yes, to pick one. ↑↓ moves // between the lines, enter does the highlighted one, esc changes nothing. type cdQuestion struct { retry *WorkspaceRetry preflight *daemon.TransferPreflight // profiles is the target profile picked for each session that can't // run there on its own, sent with the move. profiles map[string]string sessionID string target string transferID string // failure is why the move failed, or why the preflight could not say. failure string move daemon.Move gen int64 frame int phase cdPhase // option, from 1, is a highlighted line of pickOptions; at 0 yes is the // highlight, or no. touched says a key moved it before the preflight // answered, so the answer leaves it where it is. option int yes, touched bool // hidden is a box put away with esc while the daemon goes on moving. hidden bool // later is the checklist's highlight on its second line. later bool // listed is a box on a move that reached its checklist, or reopened on // one: it shows the checklist, and a retry reads the move again rather // than starting it. listed bool } func newCDQuestion(sessionID, target string, retry *WorkspaceRetry) *cdQuestion { return &cdQuestion{sessionID: sessionID, target: target, retry: retry, gen: int64(nextPageGeneration())} } // host is the target's host as the session's place shows it. func (q *cdQuestion) host() string { if q.preflight != nil && q.preflight.Host != "" { return q.preflight.Host } host, _ := daemon.SplitLocation(q.target) return host } func (q *cdQuestion) checking() bool { return q.preflight == nil && q.failure == "" } // canMove says yes is a choice: the target's daemon answered and can take it. func (q *cdQuestion) canMove() bool { return q.preflight != nil && q.preflight.Available } // checked takes the preflight's answer. The highlight goes to yes when the // move is possible, unless a key already moved it. func (q *cdQuestion) checked(preflight daemon.TransferPreflight, err error) { if err != nil { q.failure = err.Error() q.yes = false return } q.preflight = &preflight q.yes = preflight.Available && (q.yes || !q.touched) q.option = 0 q.profiles = nil for _, r := range q.picks() { if q.profiles == nil { q.profiles = map[string]string{} } q.profiles[r.SessionID] = r.Alternatives[0] } } // picks are the moving sessions that run on the target only on another of // its profiles, each to pick one for. func (q *cdQuestion) picks() []daemon.RunsThere { if !q.canMove() { return nil } var picks []daemon.RunsThere for _, r := range q.preflight.RunsThere { if !r.OK && len(r.Alternatives) > 0 { picks = append(picks, r) } } return picks } // cdOption is one profile line under yes: session runs there on profile. type cdOption struct{ session, profile string } // pickOptions are the lines of every pick, in the order the box shows them. func (q *cdQuestion) pickOptions() []cdOption { var options []cdOption for _, r := range q.picks() { for _, profile := range r.Alternatives { options = append(options, cdOption{r.SessionID, profile}) } } return options } // step moves the highlight by delta through yes, the profile lines and no, // wrapping round. It stays on no while yes is unavailable. func (q *cdQuestion) step(delta int) { if !q.canMove() { return } n := len(q.pickOptions()) + 2 at := n - 1 // no switch { case q.option > 0: at = q.option case q.yes: at = 0 } at = (at + delta + n) % n q.yes, q.option = at == 0, 0 if at > 0 && at < n-1 { q.option = at } } // cdChoice is what a key on the box asks for. type cdChoice int const ( cdNothing cdChoice = iota cdClose cdHide cdChooseYes cdChooseNo cdFinish cdLater ) // key settles a key press on a visible box. Every key is the box's: the // ones it does not use are ignored, like a confirm. func (q *cdQuestion) key(msg tea.KeyPressMsg) cdChoice { switch q.phase { case cdChecklist: return q.checklistKey(msg) case cdMoving, cdFinishing, cdAttaching: if msg.String() == "esc" { return cdHide } return cdNothing case cdFailed: switch msg.String() { case "enter": return cdChooseYes case "esc", "ctrl+c": return cdClose } return cdNothing } switch msg.String() { case "down", "ctrl+n", "tab": q.touched = true q.step(1) case "up", "ctrl+p", "shift+tab": q.touched = true q.step(-1) case "enter": if q.option > 0 { o := q.pickOptions()[q.option-1] q.profiles[o.session] = o.profile return cdNothing } if q.yes && q.canMove() { return cdChooseYes } return cdChooseNo case "esc", "ctrl+c": return cdClose } return cdNothing } // cdBoxWidth is the box's width on a screen width columns wide: 60, or the // screen less two under 64 columns. func cdBoxWidth(width int) int { if width < 64 { return max(20, width-2) } return 60 } // cdTightest is the most a box gives up to fit a short screen. const cdTightest = 3 // view draws the box, width columns wide and height rows tall at most: a box // that does not fit drops the note, then the gaps between picks, then the // facts past their first line and its outer gaps. func (q *cdQuestion) view(width, height int) []string { if q.listed { return q.checklistView(width, height) } for tight := 0; ; tight++ { if box := q.draw(width, tight); len(box) <= height || tight == cdTightest { return box } } } // draw is the box with tight steps of view's dropped. func (q *cdQuestion) draw(width, tight int) []string { outer := cdBoxWidth(width) inner := outer - 6 // a border and two spaces each side var body []string wrap := func(style func(string) string, text string) { for line := range strings.SplitSeq(ansi.Wrap(text, inner, " "), "\n") { body = append(body, style(line)) } } plain := func(s string) string { return s } faint := func(s string) string { return DefaultStyles.Faint.Render(s) } host := q.host() face := connectingFace(host, q.frame) if tight < cdTightest { body = append(body, "") } wrap(func(s string) string { return DefaultStyles.Muted.Render(s) }, q.target) wrap(plain, cdQuestionText) if tight < 1 { wrap(faint, cdQuestionNote) } body = append(body, "") var keys []hint switch q.phase { case cdAsking: body = append(body, q.choices(inner, tight)...) verb := "cd" switch { case q.option > 0: verb = "pick" case q.yes: verb = "move" } keys = []hint{{"esc", "cancel"}, {"enter", verb}} case cdMoving: body = append(body, DefaultStyles.Muted.Render("moving to "+host)+" "+DefaultStyles.Agent.Render(face)) wrap(faint, q.progress()) keys = []hint{{"esc", "hide · the move goes on"}} case cdAttaching: body = append(body, DefaultStyles.Success.Render("moved")+DefaultStyles.Muted.Render(" · opening it on "+host)+" "+DefaultStyles.Agent.Render(face)) keys = []hint{{"esc", "hide"}} case cdFailed: wrap(func(s string) string { return DefaultStyles.Error.Render(s) }, q.failure) wrap(faint, "the session stays here, as it was.") keys = []hint{{"esc", "close"}, {"enter", "retry"}} } body = append(body, "") hints := cdKeys(keys) body = append(body, strings.Repeat(" ", max(0, inner-ansi.StringWidth(hints)))+hints) if tight < cdTightest { body = append(body, "") } return cdFrame("/cd", body, outer) } // choices are the yes and no lines, the highlighted one marked, each with // the facts that decide it under it, as tight as view asks. func (q *cdQuestion) choices(inner, tight int) []string { host := q.host() var rows []string line := func(selected bool, label, aside string) string { switch { case selected: return DefaultStyles.Prompt.Render("› " + label) case aside != "": return DefaultStyles.Faint.Render(" "+label) + " " + aside } return DefaultStyles.Muted.Render(" " + label) } detail := func(text string) { for l := range strings.SplitSeq(ansi.Wrap(text, inner-4, " "), "\n") { rows = append(rows, " "+DefaultStyles.Faint.Render(l)) } } switch { case q.checking(): rows = append(rows, line(false, "yes", DefaultStyles.Faint.Render("checking "+host+" ")+DefaultStyles.Agent.Render(connectingFace(host, q.frame)))) case !q.canMove(): rows = append(rows, line(false, "yes", DefaultStyles.Muted.Render("unavailable"))) reason := q.failure if q.preflight != nil { reason = q.preflight.Reason } if reason == "" { reason = "no albedo daemon answered on " + host } detail(reason) default: rows = append(rows, line(q.yes, "yes", "")) if tight < cdTightest { detail(q.facts()) } else { rows = append(rows, " "+DefaultStyles.Faint.Render(ansi.Truncate(q.facts(), inner-4, "…"))) } rows = append(rows, q.pickRows(inner, tight >= 2)...) } rows = append(rows, line(!q.yes && q.option == 0, "no", "")) return rows } // pickRows are, for each session that needs a pick, why it can't run on // its own profile there and the target's profiles it can run on, the // picked one filled in; gapless leaves out the blank lines around each. func (q *cdQuestion) pickRows(inner int, gapless bool) []string { var rows []string n := 0 for _, r := range q.picks() { if !gapless { rows = append(rows, "") } rows = append(rows, " "+DefaultStyles.Muted.Render(r.Name+" · "+r.Model)) for l := range strings.SplitSeq(ansi.Wrap(r.Reason+"; run it there on", inner-4, " "), "\n") { rows = append(rows, " "+DefaultStyles.Faint.Render(l)) } for _, profile := range r.Alternatives { n++ mark := "○ " if q.profiles[r.SessionID] == profile { mark = "● " } switch { case q.option == n: rows = append(rows, " "+DefaultStyles.Prompt.Render("› "+mark+profile)) case mark == "● ": rows = append(rows, " "+DefaultStyles.Muted.Render(" "+mark+profile)) default: rows = append(rows, " "+DefaultStyles.Faint.Render(" "+mark+profile)) } } } if len(rows) > 0 && !gapless { rows = append(rows, "") } return rows } // facts say what yes moves: the sessions, the bytes, and where it lands. func (q *cdQuestion) facts() string { p := q.preflight parts := []string{counted(max(1, len(p.Sessions)), "session")} if p.Bytes != nil { parts = append(parts, sizeText(*p.Bytes)) } text := strings.Join(parts, ", ") + " with memory and work items move to " + q.host() + "'s daemon" if p.Home != "" { text += " (" + p.Home + ")" } return text + "; this machine keeps a read-only record." } func (q *cdQuestion) progress() string { m := q.move state := m.State switch state { case "", "checking": state = "checking" case "copying": if m.BytesTotal > 0 { state = fmt.Sprintf("copying %s of %s", sizeText(m.BytesDone), sizeText(m.BytesTotal)) } } if m.Reason != "" { state += " · " + m.Reason } return state } // statusText is the move as one line, for the status line under a hidden // box. func (q *cdQuestion) statusText() string { switch q.phase { case cdMoving: return "moving to " + q.host() + " · " + q.progress() case cdFinishing: return "finishing the move to " + q.host() case cdAttaching: return "moved · opening it on " + q.host() } return "" } func cdKeys(keys []hint) string { parts := make([]string, len(keys)) for i, k := range keys { parts[i] = DefaultStyles.Muted.Render(k.key) + " " + DefaultStyles.Faint.Render(k.does) } return strings.Join(parts, " ") } // cdFrame draws body in a rounded box outer columns wide, title in its top // edge. func cdFrame(title string, body []string, outer int) []string { inner := outer - 2 decor := DefaultStyles.Decor.Render head := "─ " + title + " " top := decor("╭─ ") + DefaultStyles.Bold.Render(title) + decor(" "+strings.Repeat("─", max(0, inner-ansi.StringWidth(head)))+"╮") rows := []string{top} for _, line := range body { line = ansi.Truncate(line, inner-4, "…") rows = append(rows, decor("│")+" "+line+strings.Repeat(" ", max(0, inner-4-ansi.StringWidth(line)))+" "+decor("│")) } return append(rows, decor("╰"+strings.Repeat("─", inner)+"╯")) } // overlay lays box centred over the screen, which steps back to the faint // ink under it. func overlay(screen string, box []string, width, height int) string { lines := strings.Split(screen, "\n") for len(lines) < height { lines = append(lines, "") } boxWidth := 0 for _, b := range box { boxWidth = max(boxWidth, ansi.StringWidth(b)) } left := max(0, (width-boxWidth)/2) top := max(0, (height-len(box))/2) for i, line := range lines { plain := ansi.Strip(line) if i < top || i >= top+len(box) { lines[i] = DefaultStyles.Decor.Render(plain) continue } before := ansi.Truncate(plain, left, "") before += strings.Repeat(" ", left-ansi.StringWidth(before)) after := ansi.TruncateLeft(plain, left+boxWidth, "") lines[i] = DefaultStyles.Decor.Render(before) + box[i-top] + DefaultStyles.Decor.Render(after) } return strings.Join(lines, "\n") } // sizeText is a byte count as a person reads it. func sizeText(n int64) string { const unit = 1024 if n < unit { return fmt.Sprintf("%d B", n) } value, suffix := float64(n)/unit, "KiB" for _, next := range []string{"MiB", "GiB", "TiB"} { if value < unit { break } value, suffix = value/unit, next } return fmt.Sprintf("%.1f %s", value, suffix) }