package tui import ( "albedo/cli/internal/daemon" "context" "slices" "strings" "time" tea "charm.land/bubbletea/v2" "github.com/charmbracelet/x/ansi" ) // queuedEdit is the queued message the composer is editing. The message stays // held while it is edited; stash is the draft the composer held before. type queuedEdit struct { id string loaded string stash editDraft lease time.Duration saving bool } // editDraft is a composer's text with the attachments its markers name. type editDraft struct { text string images promptImages pastes promptPastes } // ChatQueueHeldMsg answers a hold, or a renewal of the hold on the message // being edited. type ChatQueueHeldMsg struct { Err error SessionID string ID string LeaseMs int64 Generation int64 Renew bool } // ChatQueueRenewMsg fires when the hold on the message being edited is due to // be renewed. type ChatQueueRenewMsg struct { SessionID string ID string Generation int64 } // ChatQueueEditedMsg answers saving an edit to a queued message. type ChatQueueEditedMsg struct { Err error SessionID string ID string Text string Images []daemon.ImageAttachment Pastes []string Generation int64 } // ChatQueueDroppedMsg answers cancelling a queued message from the composer. type ChatQueueDroppedMsg struct { Err error SessionID string ID string Generation int64 } // handleQueueEdit applies the answers to the edit of a queued message. func (m *ChatModel) handleQueueEdit(msg tea.Msg) (tea.Cmd, bool) { switch msg := msg.(type) { case ChatQueueHeldMsg: if msg.SessionID != m.SessionID || msg.Generation != m.Generation { return nil, true } return m.queueHeld(msg), true case ChatQueueRenewMsg: if msg.SessionID != m.SessionID || msg.Generation != m.Generation { return nil, true } if m.editing == nil || m.editing.id != msg.ID || m.editing.saving { return nil, true } return m.holdQueued(msg.ID, true), true case ChatQueueEditedMsg: if msg.SessionID != m.SessionID || msg.Generation != m.Generation { return nil, true } return m.queueEdited(msg), true case ChatQueueDroppedMsg: if msg.SessionID != m.SessionID || msg.Generation != m.Generation { return nil, true } return m.queueDropped(msg), true } return nil, false } // queueHeld loads a held message into the composer, or, while already editing, // steps to the one before it. A renewal keeps the lease running. func (m *ChatModel) queueHeld(msg ChatQueueHeldMsg) tea.Cmd { if !msg.Renew { m.queueHold = false } if msg.Renew { if m.editing == nil || m.editing.id != msg.ID { return nil } if msg.Err != nil { if daemon.IsAPICode(msg.Err, "input_not_waiting") { return m.readUnderEdit() } m.AddError("Could not keep the queued message on hold: " + msg.Err.Error()) return m.renewLater(msg.ID, m.editing.lease) } m.editing.lease = time.Duration(msg.LeaseMs) * time.Millisecond return m.renewLater(msg.ID, m.editing.lease) } if msg.Err != nil { if daemon.IsAPICode(msg.Err, "input_not_waiting") { m.AddNotice("The agent already read that message, so it goes as it was sent.") } else { m.AddError("Could not edit the queued message: " + msg.Err.Error()) } return nil } index := slices.IndexFunc(m.pendingUsers, func(p PendingUserTurn) bool { return p.OperationID == msg.ID }) if index < 0 { return m.releaseQueued(msg.ID) } var cmd tea.Cmd if m.editing != nil { cmd = m.releaseQueued(m.editing.id) } else { m.editing = &queuedEdit{stash: m.currentDraft()} } m.editing.id = msg.ID m.editing.lease = time.Duration(msg.LeaseMs) * time.Millisecond m.loadEditing(m.pendingUsers[index]) m.refreshViewportContent() return tea.Batch(cmd, m.renewLater(msg.ID, m.editing.lease)) } // queueEdited applies a saved edit to the local copy of the message, then // restores the draft the composer held before the edit. func (m *ChatModel) queueEdited(msg ChatQueueEditedMsg) tea.Cmd { if m.editing == nil || m.editing.id != msg.ID { return nil } m.editing.saving = false if msg.Err != nil { if daemon.IsAPICode(msg.Err, "input_not_waiting") { return m.readUnderEdit() } m.AddError("Could not save the edit: " + msg.Err.Error()) return nil } if index := slices.IndexFunc(m.pendingUsers, func(p PendingUserTurn) bool { return p.OperationID == msg.ID }); index >= 0 { m.pendingUsers[index].Text = msg.Text m.pendingUsers[index].Images = msg.Images m.pendingUsers[index].Pastes = msg.Pastes } m.leaveEdit(m.editing.stash) return nil } // queueDropped removes the cancelled message. One the turn already read keeps // its place, so the draft comes back with a note. func (m *ChatModel) queueDropped(msg ChatQueueDroppedMsg) tea.Cmd { if m.editing == nil || m.editing.id != msg.ID { return nil } m.editing.saving = false if msg.Err != nil && !daemon.IsAPICode(msg.Err, "queue_item_not_found") { m.AddError("Could not cancel the queued message: " + msg.Err.Error()) return nil } if msg.Err != nil { m.AddNotice("The agent already read that message.") } m.pendingUsers = slices.DeleteFunc(m.pendingUsers, func(p PendingUserTurn) bool { return p.OperationID == msg.ID }) m.leaveEdit(m.editing.stash) return nil } // startQueueEdit holds the latest queued message, or with after set the one // queued before it. It does nothing when no such message waits. func (m *ChatModel) startQueueEdit(after string) tea.Cmd { end := len(m.pendingUsers) if after != "" { end = slices.IndexFunc(m.pendingUsers, func(p PendingUserTurn) bool { return p.OperationID == after }) if end < 0 { return nil } } if m.queueHold { return nil } for i := end - 1; i >= 0; i-- { if p := m.pendingUsers[i]; p.Queued && !p.Expired && p.OperationID != "" { m.queueHold = true return m.holdQueued(p.OperationID, false) } } return nil } // submitQueueEdit saves the composer as the edit, or cancels the message when // the composer is empty. func (m *ChatModel) submitQueueEdit() tea.Cmd { if m.editing.saving { return nil } m.editing.saving = true if strings.TrimSpace(m.TextArea.Value()) == "" { return m.dropQueued(m.editing.id) } text, pasted := m.Images.resolve(m.TextArea.Value()) var images []daemon.ImageAttachment for _, image := range pasted { images = append(images, image.ImageAttachment) } text, pastes := m.Pastes.resolve(text) client, session, gen, id := m.client, m.SessionID, m.Generation, m.editing.id return func() tea.Msg { err := client.EditQueuedInput(context.Background(), id, text, images, pastes) return ChatQueueEditedMsg{SessionID: session, Generation: gen, ID: id, Text: text, Images: images, Pastes: pastes, Err: err} } } // cancelEdit releases the hold and restores the composer's draft; the message // goes as it was. func (m *ChatModel) cancelEdit() tea.Cmd { cmd := m.releaseQueued(m.editing.id) m.leaveEdit(m.editing.stash) return cmd } // readUnderEdit keeps what was typed as a draft when the turn read the message // before the edit could land. func (m *ChatModel) readUnderEdit() tea.Cmd { m.AddNotice("The agent already read that message; what you typed stays in the composer.") m.leaveEdit(joinDrafts(m.editing.stash, m.currentDraft())) return nil } // leaveEdit ends the edit and shows draft in the composer. func (m *ChatModel) leaveEdit(draft editDraft) { m.editing = nil m.TextArea.SetValue(draft.text) m.Images, m.Pastes = draft.images, draft.pastes m.syncLayout() m.refreshViewportContent() } func (m *ChatModel) currentDraft() editDraft { return editDraft{text: m.TextArea.Value(), images: m.Images, pastes: m.Pastes} } // loadEditing puts a queued message's text and attachments in the composer, // numbered from one. func (m *ChatModel) loadEditing(p PendingUserTurn) { m.Images, m.Pastes = promptImages{}, promptPastes{} text := m.Images.adopt(p.Text, unseen(p.Images)) text = m.Pastes.adopt(text, p.Pastes) m.TextArea.SetValue(text) m.editing.loaded = m.TextArea.Value() m.syncLayout() } // joinDrafts puts two drafts one after the other, a paragraph apart, with // their attachments numbered once. func joinDrafts(first, second editDraft) editDraft { var joined editDraft var parts []string for _, draft := range []editDraft{first, second} { if draft.text == "" { continue } text, images := draft.images.resolve(draft.text) text, pastes := draft.pastes.resolve(text) text = joined.images.adopt(text, images) parts = append(parts, joined.pastes.adopt(text, pastes)) } joined.text = strings.Join(parts, "\n\n") return joined } // holdQueued holds a queued message; a renewal extends the hold on the one // being edited. func (m *ChatModel) holdQueued(id string, renew bool) tea.Cmd { client, session, gen := m.client, m.SessionID, m.Generation return func() tea.Msg { lease, err := client.HoldQueuedInput(context.Background(), id) return ChatQueueHeldMsg{SessionID: session, Generation: gen, ID: id, LeaseMs: lease, Err: err, Renew: renew} } } // releaseQueued lets a held message be read. A release that fails needs no // report: the lease lapses on its own. func (m *ChatModel) releaseQueued(id string) tea.Cmd { client := m.client return func() tea.Msg { _ = client.ReleaseQueuedInput(context.Background(), id) return nil } } // dropQueued cancels a queued message without touching the running turn. func (m *ChatModel) dropQueued(id string) tea.Cmd { client, session, gen := m.client, m.SessionID, m.Generation return func() tea.Msg { err := client.CancelQueuedInput(context.Background(), id) return ChatQueueDroppedMsg{SessionID: session, Generation: gen, ID: id, Err: err} } } // editRows names the queued message being edited, above the composer. func (m ChatModel) editRows(width int) []string { if m.editing == nil { return nil } line := "editing a queued message · send it empty to remove it" if m.editing.saving { line = "saving the edit…" } return []string{DefaultStyles.Warning.Render(ansi.Truncate(line, width, "…"))} } // renewLater renews the hold a third of its lease from now. func (m *ChatModel) renewLater(id string, lease time.Duration) tea.Cmd { session, gen := m.SessionID, m.Generation return tea.Tick(lease/3, func(time.Time) tea.Msg { return ChatQueueRenewMsg{SessionID: session, ID: id, Generation: gen} }) }