// The /cd question's keys and the move it drives against a fake daemon. The // e2e suite has no second host to move to; these pin what the box does with // each key, that the highlight follows the preflight only until a key moves // it, and that a target that never answers ends in the banner, not a hang. package tui import ( "cmp" "context" "encoding/json" "errors" "io" "net/http" "strings" "sync" "testing" "time" "albedo/cli/internal/attach" "albedo/cli/internal/daemon" tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) var ( keyEnter = tea.KeyPressMsg{Code: tea.KeyEnter} keyEsc = tea.KeyPressMsg{Code: tea.KeyEscape} keyDown = tea.KeyPressMsg{Code: tea.KeyDown} keyUp = tea.KeyPressMsg{Code: tea.KeyUp} ) func TestCDQuestionHighlightsYesOnlyWhenTheTargetCanTakeIt(t *testing.T) { q := newCDQuestion("a", cdShotTarget, nil) if q.yes || q.key(keyEnter) != cdChooseNo { t.Fatal("while checking, enter must do no") } q.checked(daemon.TransferPreflight{Available: true}, nil) if !q.yes || q.key(keyEnter) != cdChooseYes { t.Fatal("an available target highlights yes") } if q.key(keyDown); q.yes || q.key(keyEnter) != cdChooseNo { t.Fatal("↓ moves to no") } refused := newCDQuestion("a", cdShotTarget, nil) refused.checked(daemon.TransferPreflight{Reason: "protocol mismatch"}, nil) for _, key := range []tea.KeyPressMsg{keyUp, keyDown} { if refused.key(key); refused.yes { t.Fatal("↑↓ must skip an unavailable yes") } } if refused.key(keyEnter) != cdChooseNo { t.Fatal("no still works when yes is unavailable") } } func TestCDQuestionKeepsAHighlightMovedBeforeThePreflightAnswered(t *testing.T) { q := newCDQuestion("a", cdShotTarget, nil) q.key(keyDown) q.checked(daemon.TransferPreflight{Available: true}, nil) if q.yes { t.Fatal("the answer moved the highlight from under a key already pressed") } } func TestCDQuestionIgnoresStrayKeysAndEscChangesNothing(t *testing.T) { q := newCDQuestion("a", cdShotTarget, nil) q.checked(daemon.TransferPreflight{Available: true}, nil) for _, key := range []tea.KeyPressMsg{typed("y"), typed("n"), {Code: tea.KeySpace}} { if q.key(key) != cdNothing || !q.yes { t.Fatalf("%q answered the question", key.String()) } } if q.key(keyEsc) != cdClose { t.Fatal("esc must close") } q.phase = cdMoving if q.key(keyEnter) != cdNothing || q.key(keyEsc) != cdHide { t.Fatal("while moving only esc acts, and it hides") } q.phase = cdFailed if q.key(keyEnter) != cdChooseYes || q.key(keyEsc) != cdClose { t.Fatal("a failure retries on enter and closes on esc") } } func TestCDTypedLocalFolderAsksNothing(t *testing.T) { if _, remote := cdTarget(shotHere, "../other"); remote { t.Fatal("a local folder asked the question") } if target, remote := cdTarget(shotHere, "vassago:fleet"); !remote || target != "vassago:~/fleet" { t.Fatalf("target = %q, %v", target, remote) } } func TestCDQuestionPicksATargetProfileForEachSessionThatNeedsOne(t *testing.T) { q := newCDQuestion("a", cdShotTarget, nil) q.checked(cdShotPicks(1, 2), nil) if !q.yes || q.profiles["a"] != "bedrock" || q.profiles["c"] != "opencode-zen" || len(q.profiles) != 2 { t.Fatalf("each pick must default to its first alternative, on yes: %v", q.profiles) } // yes, bedrock, vertex, opencode-zen, no q.key(keyDown) q.key(keyDown) if q.yes || q.option != 2 || q.key(keyEnter) != cdNothing || q.profiles["a"] != "vertex" { t.Fatalf("enter on a profile line must pick it and do nothing else: option %d, %v", q.option, q.profiles) } q.key(keyDown) if q.key(keyDown); q.option != 0 || q.yes || q.key(keyEnter) != cdChooseNo { t.Fatal("↓ past the last profile line reaches no") } if q.key(keyDown); !q.yes || q.key(keyEnter) != cdChooseYes { t.Fatal("↓ from no wraps to yes") } if q.key(keyUp); q.yes || q.option != 0 { t.Fatal("↑ from yes wraps to no") } if q.key(keyUp); q.option != 3 { t.Fatalf("↑ from no reaches the last profile line, at %d", q.option) } if q.key(keyEsc) != cdClose { t.Fatal("esc must close from a profile line") } } func TestCDQuestionWithPicksFitsAShortScreen(t *testing.T) { q := newCDQuestion("a", cdShotTarget, nil) q.checked(cdShotPicks(1, 2), nil) box := q.view(70, 20) text := ansi.Strip(strings.Join(box, "\n")) for _, want := range []string{"no claude profile: sign in there", "vertex", "opencode-zen", "no", "enter move"} { if !strings.Contains(text, want) { t.Fatalf("a %d-row box lacks %q:\n%s", len(box), want, text) } } if len(box) > 20 { t.Fatalf("the box is %d rows on a 20-row screen:\n%s", len(box), text) } q.key(keyUp) q.key(keyUp) box = q.view(90, 16) text = ansi.Strip(strings.Join(box, "\n")) if len(box) > 16 || !strings.Contains(text, cdShotTarget) || !strings.Contains(text, "› ● opencode-zen") || !strings.Contains(text, "enter pick") { t.Fatalf("the move destination, current profile and keys must fit in 16 rows:\n%s", text) } } func TestCDQuestionWithoutAnAlternativeShowsWhyAndOffersOnlyNo(t *testing.T) { q := newCDQuestion("a", cdShotTarget, nil) reason := "vassago has no claude profile: sign in there first" q.checked(daemon.TransferPreflight{Reason: reason, RunsThere: []daemon.RunsThere{{SessionID: "a", Profile: "claude", Reason: reason}}}, nil) if q.key(keyDown); q.yes || q.option != 0 || q.profiles != nil || q.key(keyEnter) != cdChooseNo { t.Fatal("an unavailable move must offer only no") } if box := ansi.Strip(strings.Join(q.view(120, 30), "\n")); !strings.Contains(box, "sign in there first") { t.Fatalf("the box does not say why:\n%s", box) } } // moveBody is what a move's POST asked for. type moveBody struct { Profiles map[string]string `json:"profiles"` Target string `json:"target"` TransferID string `json:"transfer_id"` } // moveDaemon is a fake source daemon that can move a session; preflight is // its answer, an available move of one session when empty, and polled the // move as a read finds it, active when empty. type moveDaemon struct { preflight string polled string moves []moveBody mu sync.Mutex polls int } func (d *moveDaemon) serve(t *testing.T) *daemon.Connection { return commandTestConnection(t, func(w http.ResponseWriter, r *http.Request) { d.mu.Lock() defer d.mu.Unlock() w.Header().Set("Content-Type", "application/json") switch { case r.URL.Path == "/transfers/preflight": if r.URL.Query().Get("target") != cdShotTarget || r.URL.Query().Get("session_id") != "a" { t.Errorf("preflight asked %s", r.URL.RawQuery) } _, _ = io.WriteString(w, cmp.Or(d.preflight, `{"available":true,"reason":null,"target_daemon":{"host":"vassago","protocol":1,"home":"/home/ana/.albedo"},"bytes":1024,"sessions":["a"],"runs_there":[]}`)) case r.Method == http.MethodPost && r.URL.Path == "/sessions/a/move": var body moveBody if err := json.NewDecoder(r.Body).Decode(&body); err != nil { t.Errorf("move body: %v", err) } d.moves = append(d.moves, body) w.WriteHeader(http.StatusAccepted) _, _ = io.WriteString(w, `{"id":"`+body.TransferID+`","session_id":"a","target":"`+cdShotTarget+`","state":"copying","progress":{"bytes_done":10,"bytes_total":1024},"error":null,"reason":null,"target_session_id":null,"target_home":null,"lost":[],"bindings":[]}`) case strings.HasPrefix(r.URL.Path, "/transfers/"): d.polls++ _, _ = io.WriteString(w, cmp.Or(d.polled, `{"id":"x","session_id":"a","target":"`+cdShotTarget+`","state":"active","progress":{"bytes_done":1024,"bytes_total":1024},"error":null,"reason":null,"target_session_id":"a","target_home":"/home/ana/.albedo","lost":["python namespace"],"bindings":[]}`)) default: w.WriteHeader(http.StatusNotFound) } }) } // settleCD runs cmd and feeds what it returns back into app until nothing is // left but ticks, which it drops. func settleCD(t *testing.T, app *Workspace, cmd tea.Cmd) { t.Helper() queue := []tea.Cmd{cmd} for len(queue) > 0 { next := queue[0] queue = queue[1:] if next == nil { continue } done := make(chan tea.Msg, 1) go func() { done <- next() }() var msg tea.Msg select { case msg = <-done: case <-time.After(30 * time.Second): t.Fatal("a command did not return") } switch msg := msg.(type) { case tea.BatchMsg: queue = append(queue, msg...) continue case cdTickMsg, nil: continue } _, more := app.Client.Update(msg) queue = append(queue, more) } } func TestCDYesMovesThenShowsAnUnreachableTargetInTheBanner(t *testing.T) { fake := &moveDaemon{} session := cdShotSession() app := NewWorkspace(fake.serve(t), Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) defer app.Chat.Close() var opened []string app.openAttachment = func(_ context.Context, host, home string) (*attach.Attachment, error) { opened = append(opened, host+" "+home) return nil, errors.New("connection refused") } app.Client.Update(tea.WindowSizeMsg{Width: 120, Height: 30}) _, cmd := app.Client.Update(ChatExecuteCommandMsg{Name: "/cd", Args: cdShotTarget}) settleCD(t, app, cmd) if app.cd == nil || !app.cd.yes { t.Fatal("the question did not open on yes for an available target") } _, cmd = app.Client.Update(keyEnter) settleCD(t, app, cmd) if len(fake.moves) != 1 || fake.moves[0].Target != cdShotTarget || fake.moves[0].TransferID == "" || fake.moves[0].Profiles != nil { t.Fatalf("moves = %v", fake.moves) } if len(opened) != 1 || opened[0] != "vassago /home/ana/.albedo" { t.Fatalf("attached to %q", opened) } if app.cd != nil || app.ActiveSession.Moved == nil || !app.Chat.movedFailed { t.Fatal("a failed attach must close the box and leave the moved banner with its error") } banner := strings.Join(app.Chat.movedRows(120), "\n") for _, want := range []string{"moved to vassago", "/home/ana/.albedo", "connection refused"} { if !strings.Contains(banner, want) { t.Fatalf("banner lacks %q:\n%s", want, banner) } } } func TestCDYesSendsTheProfilesPicked(t *testing.T) { fake := &moveDaemon{preflight: `{"available":true,"reason":null,"target_daemon":{"host":"vassago","protocol":1,"home":"/home/ana/.albedo"},"bytes":1024,"sessions":["a","b"],"runs_there":[` + `{"session_id":"a","name":"fleet rollout","ok":false,"profile":"claude","model":"claude-opus-5-5","reason":"vassago has no claude profile: sign in there first","alternatives":["bedrock","vertex"]},` + `{"session_id":"b","name":"scout","ok":true,"profile":"codex","model":"gpt-5.6-luna","reason":null,"alternatives":[]}]}`} session := cdShotSession() app := NewWorkspace(fake.serve(t), Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) defer app.Chat.Close() app.openAttachment = func(context.Context, string, string) (*attach.Attachment, error) { return nil, errors.New("connection refused") } app.Client.Update(tea.WindowSizeMsg{Width: 120, Height: 30}) _, cmd := app.Client.Update(ChatExecuteCommandMsg{Name: "/cd", Args: cdShotTarget}) settleCD(t, app, cmd) for _, key := range []tea.KeyPressMsg{keyDown, keyDown, keyEnter, keyUp, keyUp} { app.Client.Update(key) } _, cmd = app.Client.Update(keyEnter) settleCD(t, app, cmd) if len(fake.moves) != 1 || len(fake.moves[0].Profiles) != 1 || fake.moves[0].Profiles["a"] != "vertex" { t.Fatalf("moves = %+v", fake.moves) } } // An older target is refused in the preflight and, should a move start // anyway, at its staging. Both read the code as a target to update and keep // the target's words, which name what it lacks, beneath. func TestCDAnOlderTargetSaysToUpdateItAndKeepsItsWords(t *testing.T) { const lacks = "core/sessions here lacks pending_switch_caller, pending_switch_model" boxed := func(app *Workspace) string { box := strings.ReplaceAll(ansi.Strip(strings.Join(app.cd.view(120, 40), "\n")), "│", "") return strings.Join(strings.Fields(box), " ") } open := func(fake *moveDaemon) *Workspace { session := cdShotSession() app := NewWorkspace(fake.serve(t), Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) t.Cleanup(app.Chat.Close) app.Client.Update(tea.WindowSizeMsg{Width: 120, Height: 40}) _, cmd := app.Client.Update(ChatExecuteCommandMsg{Name: "/cd", Args: cdShotTarget}) settleCD(t, app, cmd) return app } says := func(box string) { t.Helper() for _, want := range []string{"older than this one", "Update albedo on vassago.", lacks} { if !strings.Contains(box, want) { t.Fatalf("the box lacks %q:\n%s", want, box) } } } before := open(&moveDaemon{preflight: `{"available":false,"reason":"` + lacks + `","code":"transfer_target_older","target_daemon":{"host":"vassago","protocol":1,"home":"/home/ana/.albedo"},"bytes":null,"sessions":["a"],"runs_there":[]}`}) if before.cd.canMove() || before.cd.key(keyEnter) != cdChooseNo { t.Fatal("an older target must offer only no") } says(boxed(before)) fake := &moveDaemon{polled: `{"id":"x","session_id":"a","target":"` + cdShotTarget + `","state":"failed","progress":{"bytes_done":0,"bytes_total":0},"error":{"code":"transfer_target_older","detail":"` + lacks + `"},"reason":null,"target_session_id":null,"target_home":null,"lost":[],"bindings":[]}`} during := open(fake) _, cmd := during.Client.Update(keyEnter) settleCD(t, during, cmd) if during.cd == nil || during.cd.phase != cdFailed { t.Fatal("a move refused at staging must fail in the box") } says(boxed(during)) } // An extension that failed to load on the target is no reason to update // albedo there, and a staging refusal from a target that can't tell that // apart from an older build names both causes. Both keep the target's words. func TestCDAMissingExtensionDoesNotAlwaysMeanUpdate(t *testing.T) { const words = "extension discord is built in here but failed to load, so it can't receive discord_bots" for code, want := range map[string][]string{ daemon.TransferExtensionUnavailable: {"isn't available on vassago", "failed to load"}, daemon.TransferUnsupported: {"may be older", "failed to load there"}, } { q := newCDQuestion("a", cdShotTarget, nil) q.checked(daemon.TransferPreflight{Reason: words, Code: code, Host: "vassago"}, nil) failed := newCDQuestion("a", cdShotTarget, nil) failed.move = daemon.Move{State: "failed", ErrorCode: code, Error: words} failed.phase = cdFailed for _, box := range []*cdQuestion{q, failed} { text := strings.ReplaceAll(ansi.Strip(strings.Join(box.view(120, 40), "\n")), "│", "") text = strings.Join(strings.Fields(text), " ") for _, w := range append(want, words) { if !strings.Contains(text, w) { t.Fatalf("%s: the box lacks %q:\n%s", code, w, text) } } if code == daemon.TransferExtensionUnavailable && strings.Contains(text, "Update albedo") { t.Fatalf("a quarantined extension must not ask to update albedo:\n%s", text) } } } } func TestCDNoMovesOnlyTheKernel(t *testing.T) { fake := &moveDaemon{} session := cdShotSession() app := NewWorkspace(fake.serve(t), Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) defer app.Chat.Close() app.cd = newCDQuestion("a", cdShotTarget, nil) app.cd.checked(daemon.TransferPreflight{Available: true}, nil) app.Client.Update(keyDown) _, cmd := app.Client.Update(keyEnter) if app.cd != nil || cmd == nil { t.Fatal("no must close the box and move the session's folder") } if _, ok := cmd().(FolderMovedMsg); !ok { t.Fatal("no did not move the folder") } if len(fake.moves) != 0 { t.Fatal("no moved the session to the other daemon") } } func TestQuittingTheAttachedViewReturnsToTheSessionList(t *testing.T) { conn := daemon.NewConnection(daemon.ConnectionSnapshot{Port: 1}, nil) session := cdShotSession() app := NewWorkspace(conn, Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) child := NewWorkspace(conn, Bootstrap{Sessions: []daemon.Session{session}}, &session, shotHere, false, nil) child.nested = true app.attachedTo = &attachedApp{app: child, attachment: &attach.Attachment{}} _, cmd := app.Client.Update(ChatQuitMsg{}) msg := cmd() if _, ok := msg.(detachMsg); !ok { t.Fatalf("the attached view quit the program: %T", msg) } app.Client.Update(msg) if app.attachedTo != nil || app.State != AppStateSessionPicker { t.Fatal("detaching must return to this daemon's session list") } }