package tui import ( "cmp" "context" "fmt" "strings" "time" "albedo/cli/internal/attach" "albedo/cli/internal/daemon" tea "charm.land/bubbletea/v2" ) // cdAskMsg asks the /cd question for a folder picked on another host. type cdAskMsg struct { Retry *WorkspaceRetry Target string } // cdPreflightMsg is the daemon's answer to whether the session can move to // target, the folder as the daemon named it. type cdPreflightMsg struct { Err error Target string Preflight daemon.TransferPreflight Gen int64 } type cdTickMsg struct{ Gen int64 } type cdPollMsg struct{ Gen int64 } // cdMoveMsg is the move as the daemon last reported it. type cdMoveMsg struct { Err error Move daemon.Move Gen int64 } // cdFinishedMsg is the move after an attempt to finish it. type cdFinishedMsg struct { Err error Move daemon.Move Gen int64 } // attachedMsg is an attach to a moved session's new daemon, opened or not. type attachedMsg struct { Err error Attachment *attach.Attachment Settings daemon.Settings Draft string Home string Host string Session daemon.Session Sessions []daemon.Session } // detachMsg leaves the attached view for this daemon's session list. type detachMsg struct{} // attachedApp is a session's new daemon, shown in place of this one's // screens until it quits. type attachedApp struct { app *Workspace attachment *attach.Attachment } const ( // cdPollEvery is how often a move in flight is read again. cdPollEvery = 500 * time.Millisecond // attachDeadline bounds the whole attach: ssh, forward and first reads. attachDeadline = 60 * time.Second ) // cdTarget is the /cd question's target for typed input, and whether there // is one: a folder on another host. A local folder moves as it always did. func cdTarget(workspace, input string) (string, bool) { target := folderRequest(workspace, input) _, _, remote := splitHost(target) return target, remote } // askCD opens the /cd question for target and asks the daemon whether the // session can move there, naming the folder first when it was typed under // the host's home. func (m *Workspace) askCD(target string, retry *WorkspaceRetry) tea.Cmd { if m.ActiveSession == nil { return nil } q := newCDQuestion(m.ActiveSession.ID, target, retry) m.cd = q conn, id, gen := m.Conn, q.sessionID, q.gen return tea.Batch(func() tea.Msg { ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() resolved := target if host, path := daemon.SplitLocation(target); host == "" || !strings.HasPrefix(path, "/") { list, err := daemon.ListFolders(ctx, conn, target) if err != nil { return cdPreflightMsg{Gen: gen, Target: target, Err: err} } resolved = list.Path if h, _ := daemon.SplitLocation(resolved); h == "" { h, _, _ = splitHost(target) resolved = h + ":" + list.Path } } preflight, err := daemon.PreflightTransfer(ctx, conn, id, resolved) return cdPreflightMsg{Gen: gen, Target: resolved, Preflight: preflight, Err: err} }, m.cdTick(gen)) } func (m *Workspace) cdTick(gen int64) tea.Cmd { return tea.Tick(faceInterval, func(time.Time) tea.Msg { return cdTickMsg{Gen: gen} }) } // handleCD takes the /cd question's messages and its keys while it shows. func (m *Workspace) handleCD(msg tea.Msg) (tea.Cmd, bool) { switch msg := msg.(type) { case cdAskMsg: return m.askCD(msg.Target, msg.Retry), true case ChatAttachMsg: return m.attachMoved(msg), true case ChatChecklistMsg: return m.reopenChecklist(msg.SessionID), true case attachedMsg: return m.attached(msg), true } q := m.cd if q == nil { return nil, false } switch msg := msg.(type) { case cdPreflightMsg: if msg.Gen == q.gen { if msg.Err != nil { msg.Err = fmt.Errorf("could not check %s: %w", q.host(), msg.Err) } q.target = cmp.Or(msg.Target, q.target) q.checked(msg.Preflight, msg.Err) } return nil, true case cdTickMsg: if msg.Gen != q.gen || !q.checking() && q.phase != cdMoving && q.phase != cdFinishing && q.phase != cdAttaching { return nil, true } q.frame++ return m.cdTick(q.gen), true case cdPollMsg: if msg.Gen != q.gen || q.phase != cdMoving { return nil, true } return m.readMove(), true case cdMoveMsg: if msg.Gen != q.gen || q.phase != cdMoving { return nil, true } return m.moveProgressed(msg), true case cdFinishedMsg: if msg.Gen != q.gen || q.phase != cdFinishing { return nil, true } return m.finished(msg), true case tea.KeyPressMsg: if q.hidden { return nil, false } return m.cdKey(q.key(msg)), true case tea.PasteMsg: return nil, !q.hidden } return nil, false } // cdKey does what a key on the question chose. func (m *Workspace) cdKey(choice cdChoice) tea.Cmd { q := m.cd switch choice { case cdClose, cdLater: m.cd = nil case cdHide: q.hidden = true if m.State == AppStateFolderPicker { m.FolderPicker.Close() m.State = m.folderReturn } case cdChooseNo: m.cd = nil if m.State == AppStateFolderPicker { m.FolderPicker.moving = true } return moveCmd(daemonFolders{conn: m.Conn, condition: m.sessionCondition}, q.sessionID, m.ActiveSession.Workspace, q.target, q.retry) case cdChooseYes: return m.startMove() case cdFinish: return m.finishMove() } m.syncMoveStatus() return nil } // startMove asks the daemon to move the session and follows it. A retry // after a move that failed takes a new transfer id; after a request that // failed it asks again under the same one, which joins the move if it went // on. func (m *Workspace) startMove() tea.Cmd { q := m.cd if q.listed && q.move.State != "failed" { q.phase, q.failure = cdMoving, "" return tea.Batch(m.readMove(), m.cdTick(q.gen)) } if q.transferID == "" || q.move.State == "failed" { id, err := daemon.NewTransferID() if err != nil { q.phase, q.failure = cdFailed, err.Error() return nil } q.transferID, q.move = id, daemon.Move{} } q.phase, q.failure = cdMoving, "" conn, session, target, gen, id, profiles := m.Conn, q.sessionID, q.target, q.gen, q.transferID, q.profiles return tea.Batch(func() tea.Msg { move, err := daemon.MoveToDaemon(context.Background(), conn, session, id, target, profiles) return cdMoveMsg{Gen: gen, Move: move, Err: err} }, m.cdTick(gen)) } // moveProgressed takes the move's latest state: a settled move fails in the // box or opens the session where it went; otherwise it is read again. func (m *Workspace) moveProgressed(msg cdMoveMsg) tea.Cmd { q := m.cd defer m.syncMoveStatus() if msg.Err != nil { q.phase, q.hidden, q.failure = cdFailed, false, "could not move this session: "+msg.Err.Error() if q.listed { q.failure = "could not read the move to " + q.host() + ": " + msg.Err.Error() } return nil } q.move, q.target = msg.Move, cmp.Or(msg.Move.Target, q.target) switch msg.Move.State { case "checklist": q.phase, q.hidden, q.listed = cdChecklist, false, true m.markMove(q.sessionID, nil, &daemon.SessionMovePending{TransferID: q.transferID, Host: q.host()}) return nil case "failed": q.phase, q.hidden = cdFailed, false q.failure = cmp.Or(msg.Move.Error, msg.Move.ErrorCode, "the move failed") return nil case "active": q.phase = cdAttaching return m.movedAway(msg.Move) } gen := q.gen return tea.Tick(cdPollEvery, func(time.Time) tea.Msg { return cdPollMsg{Gen: gen} }) } // movedAway marks the session moved here and opens it on the daemon it // went to, with what was typed or waiting to be sent. func (m *Workspace) movedAway(move daemon.Move) tea.Cmd { q := m.cd host, _ := daemon.SplitLocation(q.target) m.markMove(q.sessionID, &daemon.SessionMoved{Host: q.host(), Workspace: q.target, TransferID: q.transferID, At: time.Now()}, nil) draft := m.Chat.TextArea.Value() if draft == "" && q.retry != nil { draft = q.retry.Prompt } home := move.TargetHome if home == "" && q.preflight != nil { home = q.preflight.Home } return m.attachCmd(host, home, cmp.Or(move.TargetSessionID, q.sessionID), "", draft) } // attachMoved opens the chat's moved session where it went. func (m *Workspace) attachMoved(msg ChatAttachMsg) tea.Cmd { moved := m.Chat.moved if moved == nil || msg.SessionID != m.Chat.SessionID { return nil } host, _ := daemon.SplitLocation(moved.Workspace) m.Chat.attaching("opening it on "+moved.Host+"…", false) return m.attachCmd(cmp.Or(host, moved.Host), "", msg.SessionID, moved.TransferID, msg.Draft) } // attachCmd forwards a port to host's daemon and reads what the attached // view opens with. home is that daemon's albedo home there, read from the // transfer when it is not known. func (m *Workspace) attachCmd(host, home, sessionID, transferID, draft string) tea.Cmd { conn, open := m.Conn, m.openAttachment if open == nil { open = func(ctx context.Context, host, home string) (*attach.Attachment, error) { return attach.Open(ctx, host, home, attach.Options{}) } } return func() tea.Msg { ctx, cancel := context.WithTimeout(context.Background(), attachDeadline) defer cancel() if home == "" && transferID != "" { if move, err := daemon.GetTransfer(ctx, conn, transferID); err == nil { home, sessionID = move.TargetHome, cmp.Or(move.TargetSessionID, sessionID) } } result := attachedMsg{Host: host, Home: home, Draft: draft} a, err := open(ctx, host, home) if err != nil { result.Err = err return result } result.Session, err = daemon.GetSession(ctx, a.Conn, sessionID) if err == nil { result.Sessions, err = daemon.ListSessions(ctx, a.Conn) } if err == nil { result.Settings, err = daemon.GetSettings(ctx, a.Conn) } if err != nil { a.Close() result.Err = fmt.Errorf("the daemon on %s answered, but: %w", host, err) return result } result.Attachment = a return result } } // attached shows the session on its new daemon, or why it could not be // reached in the moved session's banner. func (m *Workspace) attached(msg attachedMsg) tea.Cmd { var lost []string if m.cd != nil { lost = m.cd.move.Lost } m.cd = nil m.syncMoveStatus() if msg.Err != nil || m.attachedTo != nil { if msg.Attachment != nil { msg.Attachment.Close() } if msg.Err != nil { where := msg.Host if msg.Home != "" { where += " (albedo home " + msg.Home + ")" } m.Chat.attaching("could not open it on "+where+": "+msg.Err.Error(), true) } if m.State == AppStateFolderPicker { m.FolderPicker.Close() m.State = m.folderReturn } return nil } m.FolderPicker.Close() m.Chat.attaching("", false) // this daemon's view of the session stops here; the session list is // what the attached view returns to m.Chat.Close() m.State = AppStateSessionPicker session := msg.Session child := NewWorkspace(msg.Attachment.Conn, Bootstrap{Sessions: msg.Sessions, Settings: msg.Settings}, &session, session.Workspace, false, m.openBrowser) child.nested, child.Tick, child.Graphemes = true, m.Tick, m.Graphemes if msg.Draft != "" { child.Chat.TextArea.SetValue(msg.Draft) } if len(lost) > 0 { child.AddNotice("moved here; not restored: " + strings.Join(lost, ", ")) } m.attachedTo = &attachedApp{app: child, attachment: msg.Attachment} w, h := m.Width, m.Height return tea.Batch(child.Client.Init(), func() tea.Msg { return tea.WindowSizeMsg{Width: w, Height: h} }) } // updateAttached hands msg to the attached view; it returns false while // nothing is attached. func (m *Workspace) updateAttached(msg tea.Msg) (tea.Cmd, bool) { if m.attachedTo == nil { return nil, false } switch msg := msg.(type) { case detachMsg: return m.detach(), true case tea.WindowSizeMsg: m.Width, m.Height = msg.Width, msg.Height } return m.attachedTo.app.Client.Dispatch(msg), true } // detach closes the attached view and its forward, and shows this daemon's // session list. func (m *Workspace) detach() tea.Cmd { attached := m.attachedTo m.attachedTo = nil cleanup := attached.app.Close() w, h := m.Width, m.Height return tea.Batch(cleanup, func() tea.Msg { attached.attachment.Close() return nil }, func() tea.Msg { return tea.WindowSizeMsg{Width: w, Height: h} }, m.openSessions()) } // quit ends the program, or, attached under another view, returns to it. func (m *Workspace) quit() tea.Cmd { if m.nested { return func() tea.Msg { return detachMsg{} } } return tea.Quit } // syncMoveStatus puts a hidden box's move in the chat's status line. func (m *Workspace) syncMoveStatus() { m.Chat.moveStatus = "" if m.cd != nil && m.cd.hidden { m.Chat.moveStatus = m.cd.statusText() } } // readMove reads the box's move again. func (m *Workspace) readMove() tea.Cmd { conn, id, gen := m.Conn, m.cd.transferID, m.cd.gen return func() tea.Msg { move, err := daemon.GetTransfer(context.Background(), conn, id) return cdMoveMsg{Gen: gen, Move: move, Err: err} } } // reopenChecklist opens the box on the session's move waiting in its // checklist, read afresh from the daemon. func (m *Workspace) reopenChecklist(sessionID string) tea.Cmd { s, ok := m.session(sessionID) if !ok || s.MovePending == nil { return nil } q := newCDQuestion(sessionID, "", nil) // the host names the move until it is read q.preflight = &daemon.TransferPreflight{Host: s.MovePending.Host} q.transferID, q.phase, q.listed = s.MovePending.TransferID, cdMoving, true m.cd = q return tea.Batch(m.readMove(), m.cdTick(q.gen)) } // finishMove asks the daemon to disarm the checklist and finish the move. func (m *Workspace) finishMove() tea.Cmd { q := m.cd q.phase, q.failure = cdFinishing, "" conn, id, gen := m.Conn, q.transferID, q.gen return tea.Batch(func() tea.Msg { move, err := daemon.FinishTransfer(context.Background(), conn, id) return cdFinishedMsg{Gen: gen, Move: move, Err: err} }, m.cdTick(gen)) } // finished takes a finish's outcome: a finished move opens the session where // it went; one still in checklist shows each binding's status, to retry. func (m *Workspace) finished(msg cdFinishedMsg) tea.Cmd { q := m.cd defer m.syncMoveStatus() if msg.Err != nil { q.phase, q.hidden, q.failure = cdChecklist, false, "could not finish the move: "+msg.Err.Error() return nil } q.phase = cdMoving return m.moveProgressed(cdMoveMsg{Gen: q.gen, Move: msg.Move}) } // markMove records where session id stands in its move, here and in its chat. func (m *Workspace) markMove(id string, moved *daemon.SessionMoved, pending *daemon.SessionMovePending) { if s, ok := m.session(id); ok { s.Moved, s.MovePending = moved, pending m.updateSession(s) } if m.Chat.SessionID == id { m.Chat.moved, m.Chat.movePending = moved, pending m.Chat.syncLayout() } }