Something went wrong. Try again.
small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257// Fixtures the shot gallery and the benchmarks render the screens with.package tui
import ( "context" "encoding/json" "errors" "io" "net" "net/http" "net/http/httptest" "slices" "strings" "testing" "time"
tea "charm.land/bubbletea/v2"
"albedo/cli/internal/config" "albedo/cli/internal/daemon" "albedo/cli/internal/testwire")
func commandTestConnection(t *testing.T, handler http.HandlerFunc) *daemon.Connection { t.Helper() server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path == "/server" { _, _ = w.Write([]byte(testwire.Server)) return } handler(w, r) })) t.Cleanup(server.Close) conn, err := daemon.Attach(t.Context(), daemon.ConnectionSnapshot{Port: server.Listener.Addr().(*net.TCPAddr).Port, Token: "token"}, nil) if err != nil { t.Fatal(err) } t.Cleanup(conn.HTTPClient().CloseIdleConnections) return conn}
// fakeFolders answers the picker the way the daemon does for one local// folder and one remote host.type fakeFolders struct { lists map[string]daemon.FolderList hosts []daemon.KnownHost probe daemon.HostStatus warmed []string}
func (f *fakeFolders) List(_ context.Context, p string) (daemon.FolderList, error) { if l, ok := f.lists[p]; ok { return l, nil } return daemon.FolderList{}, errors.New("no such folder")}func (f *fakeFolders) Repo(_ context.Context, _ string) (*daemon.Repo, error) { return nil, nil }func (f *fakeFolders) Preview(_ context.Context, p string) (daemon.FolderPreview, error) { return daemon.FolderPreview{Path: p}, nil}func (f *fakeFolders) Sessions(_ context.Context) ([]daemon.Session, error) { label := "chernobog" return []daemon.Session{ {ID: "a", Workspace: "/Users/dawn/proj/albedo"}, {ID: "b", Workspace: "mayer@chernobog:/home/mayer/proj/albedo", Location: &daemon.Location{Label: &label}}, }, nil}func (f *fakeFolders) Move(_ context.Context, id, workspace string) (daemon.Session, error) { return daemon.Session{ID: id, Workspace: workspace}, nil}func (f *fakeFolders) Hosts(_ context.Context) ([]daemon.KnownHost, error) { return f.hosts, nil }func (f *fakeFolders) Host(_ context.Context, _ string) (daemon.HostStatus, error) { return f.probe, nil}func (f *fakeFolders) Warm(_ context.Context, h string) (daemon.HostStatus, error) { f.warmed = append(f.warmed, h) return f.probe, nil}func (f *fakeFolders) Local() bool { return true }
// settle runs the picker's commands until it waits on nothing but timers,// which it drops: previews and polls are not what these tests are about.func settle(t *testing.T, m FolderPicker, cmd tea.Cmd) FolderPicker { t.Helper() return drainPicker(m, cmd)}
// drainPicker is settle for the gallery, which has no test to report to.func drainPicker(m FolderPicker, cmd tea.Cmd) FolderPicker { 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(100 * time.Millisecond): continue // a tick } if batch, ok := msg.(tea.BatchMsg); ok { queue = append(queue, batch...) continue } if msg == nil { continue } var more tea.Cmd m, more = m.Update(msg) queue = append(queue, more) } return m}
// typeText types text one key at a time, settling after each.func typeText(m FolderPicker, text string) FolderPicker { for _, r := range text { var cmd tea.Cmd m, cmd = m.Update(tea.KeyPressMsg{Code: r, Text: string(r)}) m = drainPicker(m, cmd) } return m}
func remoteFolders(state, detail string) *fakeFolders { return &fakeFolders{ lists: map[string]daemon.FolderList{ "chernobog:~": {Path: "mayer@chernobog:/home/mayer", Home: "mayer@chernobog:/home/mayer", Entries: []daemon.FolderEntry{{Name: "proj"}, {Name: "notes"}}}, "chernobog:~/proj": {Path: "mayer@chernobog:/home/mayer/proj", Home: "mayer@chernobog:/home/mayer", Entries: []daemon.FolderEntry{{Name: "albedo", VCS: "jj"}}}, }, hosts: []daemon.KnownHost{{Host: "mayer@chernobog", Label: "chernobog", Source: "recent"}, {Host: "devbox", Label: "devbox", Source: "config"}}, probe: daemon.HostStatus{Host: "mayer@chernobog", State: state, Detail: detail, Home: "/home/mayer", OS: "Linux", Arch: "aarch64"}, }}
// focusLoginRow puts the cursor on the row keyed id, so a test can read what// that row says and offers.func focusLoginRow(m *LoginModel, id string) { if i := slices.IndexFunc(m.ChoosePicker.shown, func(s listShown) bool { return m.ChoosePicker.rows[s.row].key == id }); i >= 0 { m.ChoosePicker.Cursor = i }}
// providerPatch is one PATCH /settings?group=providers the fake daemon saw.type providerPatch struct { query, ifMatch string body map[string]any}
// loginWithDaemon is the fixture login screen talking to a fake daemon that// records every providers patch and refuses it, so a test reads what was sent.func loginWithDaemon(t *testing.T) (LoginModel, <-chan providerPatch) { t.Helper() patches := make(chan providerPatch, 4) conn := commandTestConnection(t, func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodPut && strings.HasPrefix(r.URL.Path, "/auth/keys/") { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) _, _ = io.WriteString(w, `{"id":"key-test","provider":"openai","label":"test","detail":"ollama.com","kind":"key","source":"saved","endpoint":"https://ollama.com/v1","limited_until":null,"selected_by_profiles":[],"rotated_by_profiles":[]}`) return } if r.Method == http.MethodPatch && r.URL.Path == "/settings" { data, _ := io.ReadAll(r.Body) var body map[string]any if err := json.Unmarshal(data, &body); err != nil { t.Errorf("patch body is not JSON: %s", data) } patches <- providerPatch{query: r.URL.RawQuery, ifMatch: r.Header.Get("If-Match"), body: body} w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusConflict) _, _ = w.Write([]byte(`{"code":"profile_exists","message":"refused by the test"}`)) return } w.WriteHeader(http.StatusNotFound) }) m := loginModel(120, 30) m.Conn = conn m.Profiles.ETag = `"providers-1"` return m, patches}
func pressCtrl(m LoginModel, r rune) (LoginModel, tea.Cmd) { return m.Update(tea.KeyPressMsg{Code: r, Mod: tea.ModCtrl})}
var pickerProfiles = config.Profiles{ Active: "work", Providers: map[string]config.Settings{ "work": {Extension: "openai", BaseURL: "https://work.example/v1", Model: "gpt-5", Protocol: "responses"}, "codex": {Extension: "codex", Model: "gpt-5-codex", Protocol: "responses"}, },}
var reasoning = []string{"low", "medium", "high"}
func typed(s string) tea.KeyPressMsg { return tea.KeyPressMsg{Code: tea.KeyExtended, Text: s} }
func chosen(t *testing.T, m ModelPickerModel) ModelPickerSelectMsg { t.Helper() _, cmd := m.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) if cmd == nil { t.Fatal("enter chose nothing") } msg, ok := cmd().(ModelPickerSelectMsg) if !ok { t.Fatalf("enter sent %T", cmd()) } return msg}
// savedCaps presses a key that saves a cap change and returns the change it// asked for, with the picker waiting on the daemon.func savedCaps(t *testing.T, m ModelPickerModel, key tea.KeyPressMsg) (ModelPickerModel, daemon.ModelCapsRequest) { t.Helper() m, cmd := m.Update(key) if cmd == nil { t.Fatal("the key saved nothing") } ask, ok := cmd().(ModelPickerCapsMsg) if !ok || m.saving == nil { t.Fatalf("the key sent %T, saving %v", cmd(), m.saving) } return m, ask.Caps}
// answered is the picker once the daemon has saved what it asked.func answered(m ModelPickerModel) ModelPickerModel { m, _ = m.Update(modelCapsSavedMsg{Generation: m.Generation, ETag: "saved"}) return m}
const generationA = testwire.GenerationA
func viewerAt(now time.Time) SessionViewer { m := NewSessionViewer("/work/current") m.now = func() time.Time { return now } return m}
var webhookSessions = []daemon.Session{ {ID: "s", Title: "infra bot", Workspace: "/srv/infra"}, {ID: "t", Title: "release notes", Workspace: "/srv/docs"},}
func newTestChatModel(t *testing.T, session *daemon.Session) ChatModel { t.Helper() conn := daemon.NewConnection(daemon.ConnectionSnapshot{Port: 1}, nil) client := daemon.NewChatClient(conn, session.ID) model := NewChatModel(session, client) t.Cleanup(model.Close) return model}