From 339489712f921074f4301391fa7909c5803cb75a Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 03:08:18 -0300 Subject: [PATCH 01/28] feat(telegram): send messages and read bot replies Add the write side of the Telegram provider over the existing MTProto session: advertise a bot's commands, send text as the signed-in user, wait for the reply or the next audio document, press an inline button, re-read a message, resolve a username, and ask an inline bot for results. The provider keeps the same concrete session and peer cache as the read side. Chat ids are provider playlist ids, so a bot chat can be a playlist without a second connection. Tests use a fake write API and cover commands, send, reply waiting, callbacks, message parsing, username resolution and inline results. --- external/telegram/provider.go | 2 + external/telegram/write.go | 657 ++++++++++++++++++++++++++++++++ external/telegram/write_test.go | 337 ++++++++++++++++ provider/interfaces.go | 65 ++++ 4 files changed, 1061 insertions(+) create mode 100644 external/telegram/write.go create mode 100644 external/telegram/write_test.go diff --git a/external/telegram/provider.go b/external/telegram/provider.go index c20a5929a..70147ec2f 100644 --- a/external/telegram/provider.go +++ b/external/telegram/provider.go @@ -32,6 +32,7 @@ var ( _ provider.CustomStreamer = (*Provider)(nil) _ provider.TrackPager = (*Provider)(nil) _ provider.CodeAuthenticator = (*Provider)(nil) + _ provider.ChatCommander = (*Provider)(nil) ) const ( @@ -77,6 +78,7 @@ type Provider struct { cfg config.TelegramConfig client *tgclient.Client api *tg.Client + write writeAPI // tests inject a fake; production uses api authReq chan authRequest mu sync.Mutex // guards state and connectErr state provState diff --git a/external/telegram/write.go b/external/telegram/write.go new file mode 100644 index 000000000..32dab743a --- /dev/null +++ b/external/telegram/write.go @@ -0,0 +1,657 @@ +package telegram + +import ( + "context" + "crypto/rand" + "encoding/binary" + "errors" + "fmt" + "strings" + "time" + "unicode/utf8" + + "github.com/bjarneo/cliamp/playlist" + "github.com/bjarneo/cliamp/provider" + "github.com/gotd/td/tg" +) + +// writeAPI is the part of *tg.Client that the write side uses. Tests inject a +// fake so the provider never needs a real account. +type writeAPI interface { + MessagesSendMessage(ctx context.Context, request *tg.MessagesSendMessageRequest) (tg.UpdatesClass, error) + MessagesGetHistory(ctx context.Context, request *tg.MessagesGetHistoryRequest) (tg.MessagesMessagesClass, error) + UsersGetFullUser(ctx context.Context, id tg.InputUserClass) (*tg.UsersUserFull, error) + MessagesGetBotCallbackAnswer(ctx context.Context, request *tg.MessagesGetBotCallbackAnswerRequest) (*tg.MessagesBotCallbackAnswer, error) + MessagesGetInlineBotResults(ctx context.Context, request *tg.MessagesGetInlineBotResultsRequest) (*tg.MessagesBotResults, error) + MessagesSendInlineBotResult(ctx context.Context, request *tg.MessagesSendInlineBotResultRequest) (tg.UpdatesClass, error) +} + +// resolveChatID accepts a peer id or a username and returns the input peer +// plus the canonical peer id. The canonical id goes into track paths, so a +// profile that names a bot by username still produces a playable URI. +func (p *Provider) resolveChatID(ctx context.Context, chat string) (tg.InputPeerClass, string, error) { + if peer, err := parsePeerID(chat); err == nil { + return peer, chat, nil + } + info, err := p.resolveChatCached(ctx, chat) + if err != nil { + return nil, "", err + } + peer, err := parsePeerID(info.ID) + if err != nil { + return nil, "", err + } + return peer, info.ID, nil +} + +// writer returns the API the write side calls. Production leaves write nil and +// uses the connected client; tests set write to a fake. +func (p *Provider) writer() writeAPI { + if p.write != nil { + return p.write + } + return p.api +} + +// BotCommands returns the commands the bot of a user chat advertises. Groups, +// channels and users that are not bots return none. +func (p *Provider) BotCommands(ctx context.Context, chatID string) ([]provider.BotCommand, error) { + if err := p.wait(); err != nil { + return nil, err + } + peer, _, err := p.resolveChatID(ctx, chatID) + if err != nil { + return nil, err + } + user, ok := peer.(*tg.InputPeerUser) + if !ok { + return nil, nil + } + full, err := p.writer().UsersGetFullUser(ctx, &tg.InputUser{ + UserID: user.UserID, + AccessHash: user.AccessHash, + }) + if err != nil { + return nil, fmt.Errorf("telegram: commands of %q: %w", chatID, err) + } + info, ok := full.FullUser.GetBotInfo() + if !ok { + return nil, nil + } + out := make([]provider.BotCommand, 0, len(info.Commands)) + for _, command := range info.Commands { + name := strings.TrimSpace(command.Command) + if name == "" { + continue + } + if !strings.HasPrefix(name, "/") { + name = "/" + name + } + out = append(out, provider.BotCommand{Command: name, Description: command.Description}) + } + return out, nil +} + +// SendCommand sends text to chatID as the signed-in user and returns the id +// of the message Telegram created. +func (p *Provider) SendCommand(ctx context.Context, chatID, text string) (int, error) { + if err := p.wait(); err != nil { + return 0, err + } + text = strings.TrimSpace(text) + if text == "" { + return 0, errors.New("telegram: empty message") + } + peer, _, err := p.resolveChatID(ctx, chatID) + if err != nil { + return 0, err + } + randomID, err := randomMessageID() + if err != nil { + return 0, err + } + updates, err := p.writer().MessagesSendMessage(ctx, &tg.MessagesSendMessageRequest{ + Peer: peer, + Message: text, + RandomID: randomID, + NoWebpage: true, + }) + if err != nil { + return 0, fmt.Errorf("telegram: send to %q: %w", chatID, err) + } + id := sentMessageID(updates) + if id == 0 { + return 0, errors.New("telegram: send returned no message id") + } + return id, nil +} + +// BotCallback presses an inline button on a bot message. +func (p *Provider) BotCallback(ctx context.Context, chatID string, messageID int, data []byte) error { + if err := p.wait(); err != nil { + return err + } + peer, _, err := p.resolveChatID(ctx, chatID) + if err != nil { + return err + } + _, err = p.writer().MessagesGetBotCallbackAnswer(ctx, &tg.MessagesGetBotCallbackAnswerRequest{ + Peer: peer, + MsgID: messageID, + Data: data, + }) + if err != nil { + // DeezLoad starts the download after the callback and can take longer + // than Telegram's callback answer window. The button was pressed, so + // the caller waits for the audio instead of reporting a failure. + if strings.Contains(err.Error(), "BOT_RESPONSE_TIMEOUT") { + return nil + } + return fmt.Errorf("telegram: callback on %q: %w", chatID, err) + } + return nil +} + +// Message reads one message by id. It is used after a callback that edits a +// menu in place: the id stays the same, so WaitReply cannot see the change. +func (p *Provider) Message(ctx context.Context, chatID string, messageID int) (provider.ChatReply, error) { + if err := p.wait(); err != nil { + return provider.ChatReply{}, err + } + peer, canonicalID, err := p.resolveChatID(ctx, chatID) + if err != nil { + return provider.ChatReply{}, err + } + history, err := p.writer().MessagesGetHistory(ctx, &tg.MessagesGetHistoryRequest{ + Peer: peer, + MinID: messageID - 1, + MaxID: messageID + 1, + Limit: 1, + }) + if err != nil { + return provider.ChatReply{}, fmt.Errorf("telegram: message %d of %q: %w", messageID, chatID, err) + } + for _, entity := range messagesOf(history) { + msg, ok := entity.(*tg.Message) + if !ok || msg.ID != messageID { + continue + } + if reply, ok := replyFromMessage(canonicalID, msg); ok { + return reply, nil + } + } + return provider.ChatReply{Kind: "none"}, nil +} + +// replyFromMessage turns one message into a ChatReply. +func replyFromMessage(chatID string, msg *tg.Message) (provider.ChatReply, bool) { + if media, ok := msg.Media.(*tg.MessageMediaDocument); ok { + if doc, ok := media.Document.(*tg.Document); ok { + if info, ok := audioInfo(doc); ok { + track := playlist.Track{ + Path: fmt.Sprintf("%s%s:%d", uriPrefix, chatID, msg.ID), + Title: info.title, + Artist: info.performer, + DurationSecs: info.duration, + ProviderMeta: map[string]string{"telegram.id": fmt.Sprint(msg.ID)}, + } + return provider.ChatReply{ + Kind: "audio", + Track: track, + From: senderOf(msg), + MessageID: msg.ID, + }, true + } + } + } + buttons := buttonsOf(msg) + if text := strings.TrimSpace(msg.Message); text != "" || len(buttons) > 0 { + return provider.ChatReply{ + Kind: "text", + Text: text, + From: senderOf(msg), + MessageID: msg.ID, + Buttons: buttons, + Links: linksOf(msg), + }, true + } + return provider.ChatReply{}, false +} + +// WaitReply polls chatID until an audio message newer than afterID arrives or a +// text reply sits unanswered for replyGrace. It returns Kind "none" when the +// timeout ends with nothing new. The caller owns the timeout. +func (p *Provider) WaitReply(ctx context.Context, chatID string, afterID int, timeout time.Duration) (provider.ChatReply, error) { + return p.waitReply(ctx, chatID, afterID, timeout, false) +} + +// WaitAudio is WaitReply for a bot that first sends text and then downloads +// the audio. It ignores text and keyboards until an audio arrives or the +// timeout ends. +func (p *Provider) WaitAudio(ctx context.Context, chatID string, afterID int, timeout time.Duration) (provider.ChatReply, error) { + return p.waitReply(ctx, chatID, afterID, timeout, true) +} + +func (p *Provider) waitReply(ctx context.Context, chatID string, afterID int, timeout time.Duration, audioOnly bool) (provider.ChatReply, error) { + if err := p.wait(); err != nil { + return provider.ChatReply{}, err + } + peer, canonicalID, err := p.resolveChatID(ctx, chatID) + if err != nil { + return provider.ChatReply{}, err + } + if timeout <= 0 { + timeout = 20 * time.Second + } + deadline := time.Now().Add(timeout) + const replyGrace = 3 * time.Second + var ( + pending provider.ChatReply + hasPending bool + textUntil time.Time + ) + for { + history, err := p.writer().MessagesGetHistory(ctx, &tg.MessagesGetHistoryRequest{ + Peer: peer, + MinID: afterID, + Limit: 20, + }) + if err != nil { + return provider.ChatReply{}, fmt.Errorf("telegram: reply of %q: %w", chatID, err) + } + if audio, ok := audioReply(canonicalID, afterID, messagesOf(history)); ok { + return audio, nil + } + if !audioOnly { + if keyboard, ok := keyboardReply(afterID, messagesOf(history)); ok { + return keyboard, nil + } + if !hasPending { + if value, ok := textReply(afterID, messagesOf(history)); ok { + pending, hasPending = value, true + textUntil = time.Now().Add(replyGrace) + } + } + } else if !hasPending { + // Keep the newest text as a fallback when the timeout ends, but + // never return it while the bot may still send the audio. + if value, ok := textReply(afterID, messagesOf(history)); ok { + pending, hasPending = value, true + } + } + now := time.Now() + if !audioOnly && hasPending && now.After(textUntil) { + return pending, nil + } + if now.After(deadline) { + if hasPending { + return pending, nil + } + return provider.ChatReply{Kind: "none"}, nil + } + wait := time.Until(deadline) + if !audioOnly && hasPending { + wait = min(wait, time.Until(textUntil)) + } + wait = min(wait, time.Second) + if wait < 50*time.Millisecond { + wait = 50 * time.Millisecond + } + select { + case <-ctx.Done(): + return provider.ChatReply{}, ctx.Err() + case <-time.After(wait): + } + } +} + +// audioReply returns the newest audio message newer than afterID. Telegram +// returns history newest first, so the first match is the newest. +func audioReply(chatID string, afterID int, messages []tg.MessageClass) (provider.ChatReply, bool) { + for _, entity := range messages { + msg, ok := entity.(*tg.Message) + if !ok || msg.ID <= afterID || msg.Out { + continue + } + media, ok := msg.Media.(*tg.MessageMediaDocument) + if !ok { + continue + } + doc, ok := media.Document.(*tg.Document) + if !ok { + continue + } + info, ok := audioInfo(doc) + if !ok { + continue + } + track := playlist.Track{ + Path: fmt.Sprintf("%s%s:%d", uriPrefix, chatID, msg.ID), + Title: info.title, + Artist: info.performer, + DurationSecs: info.duration, + ProviderMeta: map[string]string{"telegram.id": fmt.Sprint(msg.ID)}, + } + return provider.ChatReply{Kind: "audio", Track: track, From: senderOf(msg), MessageID: msg.ID}, true + } + return provider.ChatReply{}, false +} + +// keyboardReply returns the newest message with an inline or reply keyboard, +// even when it carries no text. Bots often send the options as a keyboard on +// a separate message. +func keyboardReply(afterID int, messages []tg.MessageClass) (provider.ChatReply, bool) { + for _, entity := range messages { + msg, ok := entity.(*tg.Message) + if !ok || msg.ID <= afterID || msg.Out { + continue + } + buttons := buttonsOf(msg) + if len(buttons) == 0 { + continue + } + return provider.ChatReply{ + Kind: "text", + Text: strings.TrimSpace(msg.Message), + From: senderOf(msg), + MessageID: msg.ID, + Buttons: buttons, + Links: linksOf(msg), + }, true + } + return provider.ChatReply{}, false +} + +// textReply returns the newest text message newer than afterID, with the +// inline buttons attached to it. +func textReply(afterID int, messages []tg.MessageClass) (provider.ChatReply, bool) { + for _, entity := range messages { + msg, ok := entity.(*tg.Message) + if !ok || msg.ID <= afterID || msg.Out { + continue + } + if text := strings.TrimSpace(msg.Message); text != "" { + return provider.ChatReply{ + Kind: "text", + Text: text, + From: senderOf(msg), + MessageID: msg.ID, + Buttons: buttonsOf(msg), + Links: linksOf(msg), + }, true + } + } + return provider.ChatReply{}, false +} + +// linksOf returns the URLs the message text points to, both explicit text +// links and bare URLs. +func linksOf(msg *tg.Message) []string { + if len(msg.Entities) == 0 { + return nil + } + runes := []rune(msg.Message) + var out []string + for _, entity := range msg.Entities { + switch value := entity.(type) { + case *tg.MessageEntityTextURL: + if value.URL != "" { + out = append(out, value.URL) + } + case *tg.MessageEntityURL: + start, end := value.Offset, value.Offset+value.Length + if start >= 0 && end <= len(runes) && start < end { + out = append(out, string(runes[start:end])) + } + } + } + return out +} + +// buttonsOf reads the inline keyboard of a message. Link buttons carry a URL; +// callback buttons carry the data the bot expects back. +func buttonsOf(msg *tg.Message) []provider.ChatButton { + switch markup := msg.ReplyMarkup.(type) { + case *tg.ReplyInlineMarkup: + var out []provider.ChatButton + for _, row := range markup.Rows { + for _, button := range row.Buttons { + item := provider.ChatButton{Text: button.Text} + switch kind := button.Type.(type) { + case *tg.InlineButtonTypeCallback: + item.Kind = "callback" + item.Data = kind.Data + if utf8.Valid(kind.Data) { + item.DataText = string(kind.Data) + } + case *tg.InlineButtonTypeURL: + item.Kind = "url" + item.URL = kind.URL + case *tg.InlineButtonTypeWebView: + item.Kind = "url" + item.URL = kind.URL + case *tg.InlineButtonTypeDisabled: + item.Kind = "disabled" + case *tg.InlineButtonTypeSwitchInline: + item.Kind = "switch_inline" + item.Query = kind.Query + case *tg.InlineButtonTypeCopy: + item.Kind = "copy" + default: + item.Kind = strings.TrimPrefix(fmt.Sprintf("%T", button.Type), "*tg.") + } + out = append(out, item) + } + } + return out + case *tg.ReplyKeyboardMarkup: + var out []provider.ChatButton + for _, row := range markup.Rows { + for _, button := range row.Buttons { + out = append(out, provider.ChatButton{Text: button.Text, Kind: "text", SendText: true}) + } + } + return out + default: + return nil + } +} + +// senderOf describes who sent a message, when Telegram reports it. +func senderOf(msg *tg.Message) string { + switch peer := msg.FromID.(type) { + case *tg.PeerUser: + return fmt.Sprintf("u:%d", peer.UserID) + case *tg.PeerChat: + return fmt.Sprintf("c:%d", peer.ChatID) + case *tg.PeerChannel: + return fmt.Sprintf("ch:%d", peer.ChannelID) + default: + return "" + } +} + +// sentMessageID walks the updates Telegram returns for a send. The id may come +// as updateMessageID, updateNewMessage, updateNewChannelMessage or, for a +// short update, on the update itself. +func sentMessageID(updates tg.UpdatesClass) int { + switch value := updates.(type) { + case *tg.Updates: + return idInUpdates(value.Updates) + case *tg.UpdatesCombined: + return idInUpdates(value.Updates) + case *tg.UpdateShortSentMessage: + return value.ID + default: + return 0 + } +} + +func idInUpdates(updates []tg.UpdateClass) int { + for _, entity := range updates { + switch value := entity.(type) { + case *tg.UpdateMessageID: + return value.ID + case *tg.UpdateNewMessage: + return value.Message.GetID() + case *tg.UpdateNewChannelMessage: + return value.Message.GetID() + } + } + return 0 +} + +func randomMessageID() (int64, error) { + var buf [8]byte + if _, err := rand.Read(buf[:]); err != nil { + return 0, fmt.Errorf("telegram: random id: %w", err) + } + id := int64(binary.LittleEndian.Uint64(buf[:]) & (1<<63 - 1)) + if id == 0 { + id = 1 + } + return id, nil +} + +// ResolveChat resolves a username or t.me link into the playlist description +// the dialog list uses. It also creates the peer without sending a message. +func (p *Provider) ResolveChat(ctx context.Context, username string) (playlist.PlaylistInfo, error) { + if err := p.wait(); err != nil { + return playlist.PlaylistInfo{}, err + } + return p.resolveChatCached(ctx, username) +} + +// InlineResults asks a bot for the inline results of query. This is the flow +// behind a switch_inline button: the user picks one result, and +// SendInlineResult sends it as a normal message. +func (p *Provider) InlineResults(ctx context.Context, chatID, botID, query, offset string) (provider.InlineResults, error) { + if err := p.wait(); err != nil { + return provider.InlineResults{}, err + } + peer, _, err := p.resolveChatID(ctx, chatID) + if err != nil { + return provider.InlineResults{}, err + } + botPeer, _, err := p.resolveChatID(ctx, botID) + if err != nil { + return provider.InlineResults{}, err + } + botUser, ok := botPeer.(*tg.InputPeerUser) + if !ok { + return provider.InlineResults{}, fmt.Errorf("telegram: %q is not a bot", botID) + } + response, err := p.writer().MessagesGetInlineBotResults(ctx, &tg.MessagesGetInlineBotResultsRequest{ + Bot: &tg.InputUser{ + UserID: botUser.UserID, + AccessHash: botUser.AccessHash, + }, + Peer: peer, + Query: query, + Offset: offset, + }) + if err != nil { + return provider.InlineResults{}, fmt.Errorf("telegram: inline results of %q: %w", botID, err) + } + out := provider.InlineResults{ + QueryID: response.QueryID, + NextOffset: response.NextOffset, + } + for _, entity := range response.Results { + switch result := entity.(type) { + case *tg.BotInlineResult: + out.Results = append(out.Results, provider.InlineResult{ + ID: result.ID, + Type: result.Type, + Kind: inlineMessageKind(result.SendMessage), + Title: result.Title, + Description: result.Description, + URL: result.URL, + ThumbURL: webDocumentURL(result.Thumb), + }) + case *tg.BotInlineMediaResult: + kind := inlineMessageKind(result.SendMessage) + if doc, ok := result.Document.(*tg.Document); ok { + if _, audio := audioInfo(doc); audio { + kind = "audio" + } + } + out.Results = append(out.Results, provider.InlineResult{ + ID: result.ID, + Type: result.Type, + Kind: kind, + Title: result.Title, + Description: result.Description, + }) + } + } + return out, nil +} + +// webDocumentURL returns the public URL of an inline result thumbnail. +func webDocumentURL(document tg.WebDocumentClass) string { + switch value := document.(type) { + case *tg.WebDocument: + return value.URL + case *tg.WebDocumentNoProxy: + return value.URL + default: + return "" + } +} + +// inlineMessageKind says what sending the result creates. A media auto +// message is usually an audio or a document; the plugin can prefer it over an +// article. +func inlineMessageKind(message tg.BotInlineMessageClass) string { + switch value := message.(type) { + case *tg.BotInlineMessageMediaAuto: + if value.Message != "" { + return "media" + } + return "media" + case *tg.BotInlineMessageText: + return "text" + case *tg.BotInlineMessageMediaContact: + return "contact" + case *tg.BotInlineMessageMediaGeo, *tg.BotInlineMessageMediaVenue: + return "geo" + case *tg.BotInlineMessageMediaWebPage: + return "webpage" + default: + return "text" + } +} + +// SendInlineResult sends one result of an inline query to the chat. +func (p *Provider) SendInlineResult(ctx context.Context, chatID, botID string, queryID int64, resultID string) (int, error) { + if err := p.wait(); err != nil { + return 0, err + } + peer, _, err := p.resolveChatID(ctx, chatID) + if err != nil { + return 0, err + } + // Resolve the bot so a bad id fails before Telegram creates the message. + if _, _, err := p.resolveChatID(ctx, botID); err != nil { + return 0, err + } + randomID, err := randomMessageID() + if err != nil { + return 0, err + } + updates, err := p.writer().MessagesSendInlineBotResult(ctx, &tg.MessagesSendInlineBotResultRequest{ + Peer: peer, + QueryID: queryID, + ID: resultID, + RandomID: randomID, + }) + if err != nil { + return 0, fmt.Errorf("telegram: send inline result: %w", err) + } + id := sentMessageID(updates) + if id == 0 { + return 0, errors.New("telegram: send inline result returned no message id") + } + return id, nil +} diff --git a/external/telegram/write_test.go b/external/telegram/write_test.go new file mode 100644 index 000000000..e9eb8fbcc --- /dev/null +++ b/external/telegram/write_test.go @@ -0,0 +1,337 @@ +package telegram + +import ( + "context" + "errors" + "testing" + "time" + + "github.com/gotd/td/tg" +) + +type fakeWriteAPI struct { + sent *tg.MessagesSendMessageRequest + sendResp tg.UpdatesClass + sendErr error + + history []tg.MessagesMessagesClass + histErr error + histReqs []*tg.MessagesGetHistoryRequest + + full *tg.UsersUserFull + fullErr error + fullID tg.InputUserClass + + callback *tg.MessagesGetBotCallbackAnswerRequest + callbackErr error + + inline *tg.MessagesBotResults + inlineErr error + inlineReq *tg.MessagesGetInlineBotResultsRequest + sendInline *tg.MessagesSendInlineBotResultRequest + sendInlineResp tg.UpdatesClass + sendInlineErr error +} + +func (f *fakeWriteAPI) MessagesSendMessage(_ context.Context, request *tg.MessagesSendMessageRequest) (tg.UpdatesClass, error) { + f.sent = request + return f.sendResp, f.sendErr +} + +func (f *fakeWriteAPI) MessagesGetHistory(_ context.Context, request *tg.MessagesGetHistoryRequest) (tg.MessagesMessagesClass, error) { + f.histReqs = append(f.histReqs, request) + if f.histErr != nil { + return nil, f.histErr + } + if len(f.history) == 0 { + return &tg.MessagesMessages{}, nil + } + next := f.history[0] + if len(f.history) > 1 { + f.history = f.history[1:] + } + return next, nil +} + +func (f *fakeWriteAPI) UsersGetFullUser(_ context.Context, id tg.InputUserClass) (*tg.UsersUserFull, error) { + f.fullID = id + return f.full, f.fullErr +} + +func (f *fakeWriteAPI) MessagesGetBotCallbackAnswer(_ context.Context, request *tg.MessagesGetBotCallbackAnswerRequest) (*tg.MessagesBotCallbackAnswer, error) { + f.callback = request + return &tg.MessagesBotCallbackAnswer{}, f.callbackErr +} + +func (f *fakeWriteAPI) MessagesGetInlineBotResults(_ context.Context, request *tg.MessagesGetInlineBotResultsRequest) (*tg.MessagesBotResults, error) { + f.inlineReq = request + return f.inline, f.inlineErr +} + +func (f *fakeWriteAPI) MessagesSendInlineBotResult(_ context.Context, request *tg.MessagesSendInlineBotResultRequest) (tg.UpdatesClass, error) { + f.sendInline = request + return f.sendInlineResp, f.sendInlineErr +} + +func readyProvider(api writeAPI) *Provider { + p := &Provider{write: api} + p.state = provReady + return p +} + +func TestSendCommand(t *testing.T) { + api := &fakeWriteAPI{sendResp: &tg.Updates{Updates: []tg.UpdateClass{&tg.UpdateMessageID{ID: 42}}}} + p := readyProvider(api) + + id, err := p.SendCommand(context.Background(), "u:100:200", " /start ") + if err != nil { + t.Fatalf("SendCommand: %v", err) + } + if id != 42 { + t.Fatalf("id = %d, want 42", id) + } + if api.sent == nil { + t.Fatal("no message sent") + } + if api.sent.Message != "/start" { + t.Errorf("message = %q, want %q", api.sent.Message, "/start") + } + if api.sent.RandomID == 0 { + t.Error("RandomID = 0") + } + peer, ok := api.sent.Peer.(*tg.InputPeerUser) + if !ok || peer.UserID != 100 || peer.AccessHash != 200 { + t.Errorf("peer = %#v, want user 100/200", api.sent.Peer) + } +} + +func TestSendCommandShortUpdate(t *testing.T) { + api := &fakeWriteAPI{sendResp: &tg.UpdateShortSentMessage{ID: 7}} + p := readyProvider(api) + + id, err := p.SendCommand(context.Background(), "ch:1:2", "/play") + if err != nil { + t.Fatalf("SendCommand: %v", err) + } + if id != 7 { + t.Fatalf("id = %d, want 7", id) + } +} + +func TestSendCommandRejectsEmpty(t *testing.T) { + p := readyProvider(&fakeWriteAPI{}) + if _, err := p.SendCommand(context.Background(), "u:1:2", " "); err == nil { + t.Fatal("expected an error for an empty message") + } +} + +func TestSendCommandPropagatesError(t *testing.T) { + api := &fakeWriteAPI{sendErr: errors.New("FLOOD_WAIT_30")} + p := readyProvider(api) + if _, err := p.SendCommand(context.Background(), "u:1:2", "/start"); err == nil { + t.Fatal("expected the send error") + } +} + +func TestBotCommands(t *testing.T) { + full := &tg.UserFull{} + full.SetBotInfo(tg.BotInfo{Commands: []tg.BotCommand{ + {Command: "search", Description: "Find a track"}, + {Command: "/start", Description: "Start"}, + {Command: "", Description: "ignored"}, + }}) + api := &fakeWriteAPI{full: &tg.UsersUserFull{FullUser: *full}} + p := readyProvider(api) + + commands, err := p.BotCommands(context.Background(), "u:100:200") + if err != nil { + t.Fatalf("BotCommands: %v", err) + } + if len(commands) != 2 { + t.Fatalf("commands = %#v, want 2", commands) + } + if commands[0].Command != "/search" || commands[0].Description != "Find a track" { + t.Errorf("command 0 = %#v", commands[0]) + } + if commands[1].Command != "/start" { + t.Errorf("command 1 = %#v", commands[1]) + } + user, ok := api.fullID.(*tg.InputUser) + if !ok || user.UserID != 100 || user.AccessHash != 200 { + t.Errorf("full user id = %#v", api.fullID) + } +} + +func TestBotCommandsGroupIsEmpty(t *testing.T) { + p := readyProvider(&fakeWriteAPI{}) + commands, err := p.BotCommands(context.Background(), "c:123") + if err != nil { + t.Fatalf("BotCommands: %v", err) + } + if len(commands) != 0 { + t.Fatalf("commands = %#v, want none", commands) + } +} + +func TestWaitReplyAudio(t *testing.T) { + msg := &tg.Message{ + ID: 10, + Media: &tg.MessageMediaDocument{Document: &tg.Document{ + MimeType: "audio/flac", + Attributes: []tg.DocumentAttributeClass{ + &tg.DocumentAttributeAudio{Title: "Walk", Performer: "Foo Fighters", Duration: 260}, + }, + }}, + } + api := &fakeWriteAPI{history: []tg.MessagesMessagesClass{ + &tg.MessagesMessages{Messages: []tg.MessageClass{msg}}, + }} + p := readyProvider(api) + + reply, err := p.WaitReply(context.Background(), "u:1:2", 5, time.Second) + if err != nil { + t.Fatalf("WaitReply: %v", err) + } + if reply.Kind != "audio" { + t.Fatalf("kind = %q, want audio", reply.Kind) + } + if reply.Track.Title != "Walk" || reply.Track.Artist != "Foo Fighters" { + t.Errorf("track = %#v", reply.Track) + } + if reply.Track.Path != "telegram:u:1:2:10" { + t.Errorf("path = %q", reply.Track.Path) + } + if len(api.histReqs) != 1 || api.histReqs[0].MinID != 5 { + t.Errorf("history requests = %#v", api.histReqs) + } +} + +func TestWaitReplyText(t *testing.T) { + msg := &tg.Message{ID: 8, Message: "Track not found"} + api := &fakeWriteAPI{history: []tg.MessagesMessagesClass{ + &tg.MessagesMessages{Messages: []tg.MessageClass{msg}}, + }} + p := readyProvider(api) + + reply, err := p.WaitReply(context.Background(), "u:1:2", 5, 100*time.Millisecond) + if err != nil { + t.Fatalf("WaitReply: %v", err) + } + if reply.Kind != "text" || reply.Text != "Track not found" { + t.Fatalf("reply = %#v", reply) + } +} + +func TestWaitReplyNone(t *testing.T) { + p := readyProvider(&fakeWriteAPI{}) + reply, err := p.WaitReply(context.Background(), "u:1:2", 5, 50*time.Millisecond) + if err != nil { + t.Fatalf("WaitReply: %v", err) + } + if reply.Kind != "none" { + t.Fatalf("reply = %#v, want none", reply) + } +} + +func TestWaitReplyIgnoresOldAndOutgoing(t *testing.T) { + api := &fakeWriteAPI{history: []tg.MessagesMessagesClass{ + &tg.MessagesMessages{Messages: []tg.MessageClass{ + &tg.Message{ID: 4, Message: "old"}, + &tg.Message{ID: 6, Out: true, Message: "mine"}, + }}, + }} + p := readyProvider(api) + reply, err := p.WaitReply(context.Background(), "u:1:2", 5, 50*time.Millisecond) + if err != nil { + t.Fatalf("WaitReply: %v", err) + } + if reply.Kind != "none" { + t.Fatalf("reply = %#v, want none", reply) + } +} + +func TestBotCallback(t *testing.T) { + api := &fakeWriteAPI{} + p := readyProvider(api) + if err := p.BotCallback(context.Background(), "u:1:2", 77, []byte("data")); err != nil { + t.Fatalf("BotCallback: %v", err) + } + if api.callback == nil || api.callback.MsgID != 77 || string(api.callback.Data) != "data" { + t.Fatalf("callback = %#v", api.callback) + } +} + +func TestInlineResults(t *testing.T) { + api := &fakeWriteAPI{inline: &tg.MessagesBotResults{ + QueryID: 9, + Results: []tg.BotInlineResultClass{ + &tg.BotInlineResult{ID: "1", Type: "audio", Title: "Get Lucky", Description: "Daft Punk"}, + }, + }} + p := readyProvider(api) + results, err := p.InlineResults(context.Background(), "u:1:2", "u:1:2", "get lucky", "") + if err != nil { + t.Fatalf("InlineResults: %v", err) + } + if results.QueryID != 9 || len(results.Results) != 1 { + t.Fatalf("results = %#v", results) + } + if results.Results[0].Title != "Get Lucky" || results.Results[0].Description != "Daft Punk" { + t.Errorf("result = %#v", results.Results[0]) + } + if api.inlineReq == nil || api.inlineReq.Query != "get lucky" { + t.Errorf("request = %#v", api.inlineReq) + } +} + +func TestSendInlineResult(t *testing.T) { + api := &fakeWriteAPI{sendInlineResp: &tg.Updates{Updates: []tg.UpdateClass{&tg.UpdateMessageID{ID: 88}}}} + p := readyProvider(api) + id, err := p.SendInlineResult(context.Background(), "u:1:2", "u:1:2", 9, "1") + if err != nil { + t.Fatalf("SendInlineResult: %v", err) + } + if id != 88 { + t.Fatalf("id = %d", id) + } + if api.sendInline == nil || api.sendInline.QueryID != 9 || api.sendInline.ID != "1" { + t.Errorf("request = %#v", api.sendInline) + } +} + +func TestSentMessageIDFromNewMessage(t *testing.T) { + updates := &tg.Updates{Updates: []tg.UpdateClass{ + &tg.UpdateNewMessage{Message: &tg.Message{ID: 33}}, + }} + if got := sentMessageID(updates); got != 33 { + t.Fatalf("sentMessageID = %d, want 33", got) + } +} + +func TestMessageReadsEditedMenu(t *testing.T) { + msg := &tg.Message{ + ID: 7, + Message: "Settings", + ReplyMarkup: &tg.ReplyInlineMarkup{Rows: []tg.KeyboardInlineButtonRow{{ + Buttons: []tg.KeyboardInlineButton{{ + Text: "FLAC", + Type: &tg.InlineButtonTypeCallback{Data: []byte("flac")}, + }}, + }}}, + } + api := &fakeWriteAPI{history: []tg.MessagesMessagesClass{ + &tg.MessagesMessages{Messages: []tg.MessageClass{msg}}, + }} + p := readyProvider(api) + + reply, err := p.Message(context.Background(), "u:1:2", 7) + if err != nil { + t.Fatalf("Message: %v", err) + } + if reply.Kind != "text" || reply.Text != "Settings" { + t.Fatalf("reply = %#v", reply) + } + if len(reply.Buttons) != 1 || reply.Buttons[0].Text != "FLAC" || string(reply.Buttons[0].Data) != "flac" { + t.Fatalf("buttons = %#v", reply.Buttons) + } +} diff --git a/provider/interfaces.go b/provider/interfaces.go index 38b9e85ab..55802101b 100644 --- a/provider/interfaces.go +++ b/provider/interfaces.go @@ -468,3 +468,68 @@ type ChatFilter interface { Chats() []string SetChats(chats []string) error } + +// BotCommand is one command a chat bot advertises. +type BotCommand struct { + Command string // includes the leading slash, e.g. "/search" + Description string +} + +// ChatButton is one inline button attached to a bot message. Data is the +// callback payload; URL is set for link buttons. A button has one or the +// other. +type ChatButton struct { + Text string + Data []byte + DataText string // Data as text when it is valid UTF-8, e.g. a Deezer URL + URL string + Query string // switch_inline: the inline query the button opens + Kind string // "callback", "url", "text", "switch_inline", ... + SendText bool // reply keyboard: sending Text is the button press +} + +// InlineResult is one result an inline bot returns for a query. +type InlineResult struct { + ID string + Type string + Kind string // "audio", "media", "photo", "text" + Title string + Description string + URL string + ThumbURL string +} + +// InlineResults is the answer to an inline query. QueryID must be sent back +// with the chosen result. +type InlineResults struct { + QueryID int64 + NextOffset string + Results []InlineResult +} + +// ChatReply is what arrived in a chat after a command. Kind is "audio", +// "text" or "none". MessageID is the reply message, so a callback can target +// its inline keyboard. +type ChatReply struct { + Kind string + Track playlist.Track + Text string + From string + MessageID int + Buttons []ChatButton + Links []string +} + +// ChatCommander is implemented by providers that can write into a chat as the +// signed-in user and read the reply. The chat id is a provider playlist id. +type ChatCommander interface { + BotCommands(ctx context.Context, chatID string) ([]BotCommand, error) + SendCommand(ctx context.Context, chatID, text string) (int, error) + WaitReply(ctx context.Context, chatID string, afterID int, timeout time.Duration) (ChatReply, error) + WaitAudio(ctx context.Context, chatID string, afterID int, timeout time.Duration) (ChatReply, error) + BotCallback(ctx context.Context, chatID string, messageID int, data []byte) error + Message(ctx context.Context, chatID string, messageID int) (ChatReply, error) + ResolveChat(ctx context.Context, username string) (playlist.PlaylistInfo, error) + InlineResults(ctx context.Context, chatID, botID, query, offset string) (InlineResults, error) + SendInlineResult(ctx context.Context, chatID, botID string, queryID int64, resultID string) (int, error) +} From 176f9306eb9ab0688db76f343bc0806001341fa8 Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 03:22:55 -0300 Subject: [PATCH 02/28] fix(telegram): collapse the duplicate inline media branch --- external/telegram/write.go | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/external/telegram/write.go b/external/telegram/write.go index 32dab743a..9121339bd 100644 --- a/external/telegram/write.go +++ b/external/telegram/write.go @@ -604,11 +604,8 @@ func webDocumentURL(document tg.WebDocumentClass) string { // message is usually an audio or a document; the plugin can prefer it over an // article. func inlineMessageKind(message tg.BotInlineMessageClass) string { - switch value := message.(type) { + switch message.(type) { case *tg.BotInlineMessageMediaAuto: - if value.Message != "" { - return "media" - } return "media" case *tg.BotInlineMessageText: return "text" From 7f9bbc8a272b0b7e3712f21f42c0749b649e374b Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 03:26:23 -0300 Subject: [PATCH 03/28] fix(telegram): address the write transport review Wait for the provider with the caller's context, keep the inline keyboard and caption on audio replies, bound the history poll by the reply deadline, keep the newest pending text, and decode URL entities through UTF-16 offsets. --- external/telegram/provider.go | 18 ++++++++- external/telegram/write.go | 69 +++++++++++++++++++++------------ external/telegram/write_test.go | 51 ++++++++++++++++++++++++ 3 files changed, 113 insertions(+), 25 deletions(-) diff --git a/external/telegram/provider.go b/external/telegram/provider.go index 70147ec2f..b7d3fcfd3 100644 --- a/external/telegram/provider.go +++ b/external/telegram/provider.go @@ -261,7 +261,19 @@ func (p *Provider) currentState() provState { // wait returns once the connection is usable. playlist.ErrNeedsAuth means the // pane must collect the login code; other errors keep the call retryable. func (p *Provider) wait() error { + return p.waitContext(context.Background()) +} + +// waitContext is wait with a caller that can give up. The provider can spend +// up to connectWait settling, and a canceled UI action should not stay blocked +// in the polling loop until that deadline. +func (p *Provider) waitContext(ctx context.Context) error { + if ctx == nil { + ctx = context.Background() + } deadline := time.Now().Add(connectWait) + ticker := time.NewTicker(100 * time.Millisecond) + defer ticker.Stop() for { switch p.currentState() { case provReady: @@ -277,7 +289,11 @@ func (p *Provider) wait() error { if time.Now().After(deadline) { return errors.New("telegram: still connecting, try again") } - time.Sleep(100 * time.Millisecond) + select { + case <-ctx.Done(): + return ctx.Err() + case <-ticker.C: + } } } diff --git a/external/telegram/write.go b/external/telegram/write.go index 9121339bd..585203513 100644 --- a/external/telegram/write.go +++ b/external/telegram/write.go @@ -8,6 +8,7 @@ import ( "fmt" "strings" "time" + "unicode/utf16" "unicode/utf8" "github.com/bjarneo/cliamp/playlist" @@ -56,7 +57,7 @@ func (p *Provider) writer() writeAPI { // BotCommands returns the commands the bot of a user chat advertises. Groups, // channels and users that are not bots return none. func (p *Provider) BotCommands(ctx context.Context, chatID string) ([]provider.BotCommand, error) { - if err := p.wait(); err != nil { + if err := p.waitContext(ctx); err != nil { return nil, err } peer, _, err := p.resolveChatID(ctx, chatID) @@ -95,7 +96,7 @@ func (p *Provider) BotCommands(ctx context.Context, chatID string) ([]provider.B // SendCommand sends text to chatID as the signed-in user and returns the id // of the message Telegram created. func (p *Provider) SendCommand(ctx context.Context, chatID, text string) (int, error) { - if err := p.wait(); err != nil { + if err := p.waitContext(ctx); err != nil { return 0, err } text = strings.TrimSpace(text) @@ -128,7 +129,7 @@ func (p *Provider) SendCommand(ctx context.Context, chatID, text string) (int, e // BotCallback presses an inline button on a bot message. func (p *Provider) BotCallback(ctx context.Context, chatID string, messageID int, data []byte) error { - if err := p.wait(); err != nil { + if err := p.waitContext(ctx); err != nil { return err } peer, _, err := p.resolveChatID(ctx, chatID) @@ -155,7 +156,7 @@ func (p *Provider) BotCallback(ctx context.Context, chatID string, messageID int // Message reads one message by id. It is used after a callback that edits a // menu in place: the id stays the same, so WaitReply cannot see the change. func (p *Provider) Message(ctx context.Context, chatID string, messageID int) (provider.ChatReply, error) { - if err := p.wait(); err != nil { + if err := p.waitContext(ctx); err != nil { return provider.ChatReply{}, err } peer, canonicalID, err := p.resolveChatID(ctx, chatID) @@ -198,8 +199,11 @@ func replyFromMessage(chatID string, msg *tg.Message) (provider.ChatReply, bool) return provider.ChatReply{ Kind: "audio", Track: track, + Text: strings.TrimSpace(msg.Message), From: senderOf(msg), MessageID: msg.ID, + Buttons: buttonsOf(msg), + Links: linksOf(msg), }, true } } @@ -233,7 +237,7 @@ func (p *Provider) WaitAudio(ctx context.Context, chatID string, afterID int, ti } func (p *Provider) waitReply(ctx context.Context, chatID string, afterID int, timeout time.Duration, audioOnly bool) (provider.ChatReply, error) { - if err := p.wait(); err != nil { + if err := p.waitContext(ctx); err != nil { return provider.ChatReply{}, err } peer, canonicalID, err := p.resolveChatID(ctx, chatID) @@ -244,6 +248,8 @@ func (p *Provider) waitReply(ctx context.Context, chatID string, afterID int, ti timeout = 20 * time.Second } deadline := time.Now().Add(timeout) + pollCtx, cancel := context.WithDeadline(ctx, deadline) + defer cancel() const replyGrace = 3 * time.Second var ( pending provider.ChatReply @@ -251,12 +257,21 @@ func (p *Provider) waitReply(ctx context.Context, chatID string, afterID int, ti textUntil time.Time ) for { - history, err := p.writer().MessagesGetHistory(ctx, &tg.MessagesGetHistoryRequest{ + history, err := p.writer().MessagesGetHistory(pollCtx, &tg.MessagesGetHistoryRequest{ Peer: peer, MinID: afterID, Limit: 20, }) if err != nil { + if ctx.Err() != nil { + return provider.ChatReply{}, ctx.Err() + } + if pollCtx.Err() != nil { + if hasPending { + return pending, nil + } + return provider.ChatReply{Kind: "none"}, nil + } return provider.ChatReply{}, fmt.Errorf("telegram: reply of %q: %w", chatID, err) } if audio, ok := audioReply(canonicalID, afterID, messagesOf(history)); ok { @@ -266,17 +281,12 @@ func (p *Provider) waitReply(ctx context.Context, chatID string, afterID int, ti if keyboard, ok := keyboardReply(afterID, messagesOf(history)); ok { return keyboard, nil } - if !hasPending { - if value, ok := textReply(afterID, messagesOf(history)); ok { - pending, hasPending = value, true - textUntil = time.Now().Add(replyGrace) - } - } - } else if !hasPending { - // Keep the newest text as a fallback when the timeout ends, but - // never return it while the bot may still send the audio. - if value, ok := textReply(afterID, messagesOf(history)); ok { - pending, hasPending = value, true + } + if value, ok := textReply(afterID, messagesOf(history)); ok { + changed := !hasPending || value.Text != pending.Text + pending, hasPending = value, true + if !audioOnly && changed { + textUntil = time.Now().Add(replyGrace) } } now := time.Now() @@ -332,7 +342,15 @@ func audioReply(chatID string, afterID int, messages []tg.MessageClass) (provide DurationSecs: info.duration, ProviderMeta: map[string]string{"telegram.id": fmt.Sprint(msg.ID)}, } - return provider.ChatReply{Kind: "audio", Track: track, From: senderOf(msg), MessageID: msg.ID}, true + return provider.ChatReply{ + Kind: "audio", + Track: track, + Text: strings.TrimSpace(msg.Message), + From: senderOf(msg), + MessageID: msg.ID, + Buttons: buttonsOf(msg), + Links: linksOf(msg), + }, true } return provider.ChatReply{}, false } @@ -390,7 +408,10 @@ func linksOf(msg *tg.Message) []string { if len(msg.Entities) == 0 { return nil } - runes := []rune(msg.Message) + // Telegram entity offsets and lengths count UTF-16 code units. A rune + // slice counts code points, so an emoji before a URL would make the end + // index too large and drop the link. + units := utf16.Encode([]rune(msg.Message)) var out []string for _, entity := range msg.Entities { switch value := entity.(type) { @@ -400,8 +421,8 @@ func linksOf(msg *tg.Message) []string { } case *tg.MessageEntityURL: start, end := value.Offset, value.Offset+value.Length - if start >= 0 && end <= len(runes) && start < end { - out = append(out, string(runes[start:end])) + if start >= 0 && end <= len(units) && start < end { + out = append(out, string(utf16.Decode(units[start:end]))) } } } @@ -516,7 +537,7 @@ func randomMessageID() (int64, error) { // ResolveChat resolves a username or t.me link into the playlist description // the dialog list uses. It also creates the peer without sending a message. func (p *Provider) ResolveChat(ctx context.Context, username string) (playlist.PlaylistInfo, error) { - if err := p.wait(); err != nil { + if err := p.waitContext(ctx); err != nil { return playlist.PlaylistInfo{}, err } return p.resolveChatCached(ctx, username) @@ -526,7 +547,7 @@ func (p *Provider) ResolveChat(ctx context.Context, username string) (playlist.P // behind a switch_inline button: the user picks one result, and // SendInlineResult sends it as a normal message. func (p *Provider) InlineResults(ctx context.Context, chatID, botID, query, offset string) (provider.InlineResults, error) { - if err := p.wait(); err != nil { + if err := p.waitContext(ctx); err != nil { return provider.InlineResults{}, err } peer, _, err := p.resolveChatID(ctx, chatID) @@ -622,7 +643,7 @@ func inlineMessageKind(message tg.BotInlineMessageClass) string { // SendInlineResult sends one result of an inline query to the chat. func (p *Provider) SendInlineResult(ctx context.Context, chatID, botID string, queryID int64, resultID string) (int, error) { - if err := p.wait(); err != nil { + if err := p.waitContext(ctx); err != nil { return 0, err } peer, _, err := p.resolveChatID(ctx, chatID) diff --git a/external/telegram/write_test.go b/external/telegram/write_test.go index e9eb8fbcc..eb3a3b0a5 100644 --- a/external/telegram/write_test.go +++ b/external/telegram/write_test.go @@ -335,3 +335,54 @@ func TestMessageReadsEditedMenu(t *testing.T) { t.Fatalf("buttons = %#v", reply.Buttons) } } + +func TestLinksOfUsesUTF16Offsets(t *testing.T) { + msg := &tg.Message{ + Message: "šŸ˜€ https://example.com", + Entities: []tg.MessageEntityClass{ + &tg.MessageEntityURL{Offset: 3, Length: 19}, + }, + } + links := linksOf(msg) + if len(links) != 1 || links[0] != "https://example.com" { + t.Fatalf("links = %#v, want the URL after the emoji", links) + } +} + +func TestAudioReplyKeepsButtonsAndCaption(t *testing.T) { + msg := &tg.Message{ + ID: 9, + Message: "Here is the track", + Media: &tg.MessageMediaDocument{Document: &tg.Document{ + MimeType: "audio/flac", + Attributes: []tg.DocumentAttributeClass{ + &tg.DocumentAttributeAudio{Title: "Walk", Performer: "Foo Fighters", Duration: 260}, + }, + }}, + ReplyMarkup: &tg.ReplyInlineMarkup{Rows: []tg.KeyboardInlineButtonRow{{ + Buttons: []tg.KeyboardInlineButton{{ + Text: "FLAC", + Type: &tg.InlineButtonTypeCallback{Data: []byte("flac")}, + }}, + }}}, + } + reply, ok := replyFromMessage("u:1:2", msg) + if !ok { + t.Fatal("replyFromMessage returned false") + } + if reply.Kind != "audio" || reply.Text != "Here is the track" { + t.Fatalf("reply = %#v", reply) + } + if len(reply.Buttons) != 1 || reply.Buttons[0].Text != "FLAC" { + t.Fatalf("buttons = %#v", reply.Buttons) + } +} + +func TestWaitContextHonorsCancellation(t *testing.T) { + p := &Provider{} + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if err := p.waitContext(ctx); !errors.Is(err, context.Canceled) { + t.Fatalf("waitContext = %v, want context.Canceled", err) + } +} From 935a4d50bb9d20c6d77dd5a398474f53728344e7 Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 03:30:43 -0300 Subject: [PATCH 04/28] test(telegram): keep the latest bot text while waiting for audio --- external/telegram/write_test.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/external/telegram/write_test.go b/external/telegram/write_test.go index eb3a3b0a5..e1fcf7b08 100644 --- a/external/telegram/write_test.go +++ b/external/telegram/write_test.go @@ -386,3 +386,21 @@ func TestWaitContextHonorsCancellation(t *testing.T) { t.Fatalf("waitContext = %v, want context.Canceled", err) } } + +func TestWaitAudioKeepsTheLatestText(t *testing.T) { + first := &tg.Message{ID: 6, Message: "Searching"} + second := &tg.Message{ID: 7, Message: "Track not found"} + api := &fakeWriteAPI{history: []tg.MessagesMessagesClass{ + &tg.MessagesMessages{Messages: []tg.MessageClass{first}}, + &tg.MessagesMessages{Messages: []tg.MessageClass{second}}, + }} + p := readyProvider(api) + + reply, err := p.WaitAudio(context.Background(), "u:1:2", 5, 1300*time.Millisecond) + if err != nil { + t.Fatalf("WaitAudio: %v", err) + } + if reply.Kind != "text" || reply.Text != "Track not found" { + t.Fatalf("reply = %#v, want the latest text", reply) + } +} From fbd8d93e5ffd578bac3cb5578912f047eb344083 Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 03:49:25 -0300 Subject: [PATCH 05/28] fix(telegram): start the message window at the requested id --- external/telegram/write.go | 9 +++++---- external/telegram/write_test.go | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/external/telegram/write.go b/external/telegram/write.go index 585203513..7a85082af 100644 --- a/external/telegram/write.go +++ b/external/telegram/write.go @@ -164,10 +164,11 @@ func (p *Provider) Message(ctx context.Context, chatID string, messageID int) (p return provider.ChatReply{}, err } history, err := p.writer().MessagesGetHistory(ctx, &tg.MessagesGetHistoryRequest{ - Peer: peer, - MinID: messageID - 1, - MaxID: messageID + 1, - Limit: 1, + Peer: peer, + OffsetID: messageID + 1, + MinID: messageID - 1, + MaxID: messageID + 1, + Limit: 1, }) if err != nil { return provider.ChatReply{}, fmt.Errorf("telegram: message %d of %q: %w", messageID, chatID, err) diff --git a/external/telegram/write_test.go b/external/telegram/write_test.go index e1fcf7b08..75bbca5f3 100644 --- a/external/telegram/write_test.go +++ b/external/telegram/write_test.go @@ -404,3 +404,21 @@ func TestWaitAudioKeepsTheLatestText(t *testing.T) { t.Fatalf("reply = %#v, want the latest text", reply) } } + +func TestMessageWindowStartsAtTheRequestedID(t *testing.T) { + msg := &tg.Message{ID: 7, Message: "Settings"} + api := &fakeWriteAPI{history: []tg.MessagesMessagesClass{ + &tg.MessagesMessages{Messages: []tg.MessageClass{msg}}, + }} + p := readyProvider(api) + + if _, err := p.Message(context.Background(), "u:1:2", 7); err != nil { + t.Fatalf("Message: %v", err) + } + if len(api.histReqs) != 1 { + t.Fatalf("history requests = %d, want 1", len(api.histReqs)) + } + if got := api.histReqs[0].OffsetID; got != 8 { + t.Fatalf("OffsetID = %d, want 8", got) + } +} From 8f7e27d03967ca5305ebcbe8629df1024078e9b6 Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 05:37:17 -0300 Subject: [PATCH 06/28] fix(telegram): restart the reply grace for a new message --- external/telegram/write.go | 2 +- external/telegram/write_test.go | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/external/telegram/write.go b/external/telegram/write.go index 7a85082af..c28514c1d 100644 --- a/external/telegram/write.go +++ b/external/telegram/write.go @@ -284,7 +284,7 @@ func (p *Provider) waitReply(ctx context.Context, chatID string, afterID int, ti } } if value, ok := textReply(afterID, messagesOf(history)); ok { - changed := !hasPending || value.Text != pending.Text + changed := !hasPending || value.Text != pending.Text || value.MessageID != pending.MessageID pending, hasPending = value, true if !audioOnly && changed { textUntil = time.Now().Add(replyGrace) diff --git a/external/telegram/write_test.go b/external/telegram/write_test.go index 75bbca5f3..995c44cd0 100644 --- a/external/telegram/write_test.go +++ b/external/telegram/write_test.go @@ -422,3 +422,21 @@ func TestMessageWindowStartsAtTheRequestedID(t *testing.T) { t.Fatalf("OffsetID = %d, want 8", got) } } + +func TestWaitReplyRestartsGraceForANewMessageWithTheSameText(t *testing.T) { + first := &tg.Message{ID: 6, Message: "Searching"} + second := &tg.Message{ID: 7, Message: "Searching"} + api := &fakeWriteAPI{history: []tg.MessagesMessagesClass{ + &tg.MessagesMessages{Messages: []tg.MessageClass{first}}, + &tg.MessagesMessages{Messages: []tg.MessageClass{second}}, + }} + p := readyProvider(api) + + reply, err := p.WaitReply(context.Background(), "u:1:2", 5, 1300*time.Millisecond) + if err != nil { + t.Fatalf("WaitReply: %v", err) + } + if reply.MessageID != 7 { + t.Fatalf("message id = %d, want the newer message", reply.MessageID) + } +} From 0568a1c7a986e73b0ff7033b517ff9b27f8744fd Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 05:56:34 -0300 Subject: [PATCH 07/28] test(telegram): prove the grace period restarts for a newer message --- external/telegram/write.go | 5 ++++- external/telegram/write_test.go | 20 ++++++++++++++++---- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/external/telegram/write.go b/external/telegram/write.go index c28514c1d..ed50844b3 100644 --- a/external/telegram/write.go +++ b/external/telegram/write.go @@ -237,6 +237,10 @@ func (p *Provider) WaitAudio(ctx context.Context, chatID string, afterID int, ti return p.waitReply(ctx, chatID, afterID, timeout, true) } +// replyGrace is how long a text reply waits for a newer message before it is +// returned as the final answer. It is a var so tests can shorten it. +var replyGrace = 3 * time.Second + func (p *Provider) waitReply(ctx context.Context, chatID string, afterID int, timeout time.Duration, audioOnly bool) (provider.ChatReply, error) { if err := p.waitContext(ctx); err != nil { return provider.ChatReply{}, err @@ -251,7 +255,6 @@ func (p *Provider) waitReply(ctx context.Context, chatID string, afterID int, ti deadline := time.Now().Add(timeout) pollCtx, cancel := context.WithDeadline(ctx, deadline) defer cancel() - const replyGrace = 3 * time.Second var ( pending provider.ChatReply hasPending bool diff --git a/external/telegram/write_test.go b/external/telegram/write_test.go index 995c44cd0..093d05214 100644 --- a/external/telegram/write_test.go +++ b/external/telegram/write_test.go @@ -14,9 +14,10 @@ type fakeWriteAPI struct { sendResp tg.UpdatesClass sendErr error - history []tg.MessagesMessagesClass - histErr error - histReqs []*tg.MessagesGetHistoryRequest + history []tg.MessagesMessagesClass + histErr error + histReqs []*tg.MessagesGetHistoryRequest + histTimes []time.Time full *tg.UsersUserFull fullErr error @@ -40,6 +41,7 @@ func (f *fakeWriteAPI) MessagesSendMessage(_ context.Context, request *tg.Messag func (f *fakeWriteAPI) MessagesGetHistory(_ context.Context, request *tg.MessagesGetHistoryRequest) (tg.MessagesMessagesClass, error) { f.histReqs = append(f.histReqs, request) + f.histTimes = append(f.histTimes, time.Now()) if f.histErr != nil { return nil, f.histErr } @@ -424,6 +426,10 @@ func TestMessageWindowStartsAtTheRequestedID(t *testing.T) { } func TestWaitReplyRestartsGraceForANewMessageWithTheSameText(t *testing.T) { + oldGrace := replyGrace + replyGrace = 50 * time.Millisecond + t.Cleanup(func() { replyGrace = oldGrace }) + first := &tg.Message{ID: 6, Message: "Searching"} second := &tg.Message{ID: 7, Message: "Searching"} api := &fakeWriteAPI{history: []tg.MessagesMessagesClass{ @@ -432,11 +438,17 @@ func TestWaitReplyRestartsGraceForANewMessageWithTheSameText(t *testing.T) { }} p := readyProvider(api) - reply, err := p.WaitReply(context.Background(), "u:1:2", 5, 1300*time.Millisecond) + reply, err := p.WaitReply(context.Background(), "u:1:2", 5, 500*time.Millisecond) if err != nil { t.Fatalf("WaitReply: %v", err) } if reply.MessageID != 7 { t.Fatalf("message id = %d, want the newer message", reply.MessageID) } + if len(api.histTimes) < 2 { + t.Fatalf("history calls = %d, want at least 2", len(api.histTimes)) + } + if since := time.Since(api.histTimes[1]); since < 40*time.Millisecond { + t.Fatalf("returned %v after the newer message, want a restarted grace period", since) + } } From 60d4a0f9fe0570cd964815a93ad732d28d07e44f Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 03:10:20 -0300 Subject: [PATCH 08/28] feat(plugins): add provider actions and the action pane Plugins can register p:action entries under "!", read the active provider and playlist context, call provider chat actions with a blocking call or an on_reply callback, and insert a track at a queue index without replacing the playlist. Add the basic ui.input primitive and the bundled telegram-bot.lua example, which sends a command to the chat open in the Telegram pane and adds the audio reply to the queue. Document the action pane, the provider API, queue.insert and the input primitive; name ! in the keybindings and describe bot chats in the Telegram provider docs. --- docs/keybindings.md | 1 + docs/plugins.md | 90 +++++++++++++++- docs/telegram.md | 14 +++ lua_wiring.go | 168 +++++++++++++++++++++++++++++ luaplugin/api_action.go | 140 ++++++++++++++++++++++++ luaplugin/api_action_test.go | 18 ++++ luaplugin/api_provider.go | 148 +++++++++++++++++++++++++ luaplugin/api_provider_test.go | 143 +++++++++++++++++++++++++ luaplugin/api_queue.go | 25 +++++ luaplugin/api_ui.go | 36 +++++++ luaplugin/hooks.go | 14 +-- luaplugin/luaplugin.go | 34 ++++-- luaplugin/metadata.go | 2 +- main.go | 1 + playlist/playlist.go | 51 +++++++++ playlist/playlist_test.go | 56 ++++++++++ plugins/telegram-bot.lua | 129 ++++++++++++++++++++++ ui/model/action_pane.go | 190 +++++++++++++++++++++++++++++++++ ui/model/action_pane_test.go | 116 ++++++++++++++++++++ ui/model/command_registry.go | 1 + ui/model/keymap_test.go | 4 +- ui/model/keys.go | 12 +++ ui/model/lua_input.go | 101 ++++++++++++++++++ ui/model/model.go | 2 + ui/model/plugin_queue.go | 6 ++ ui/model/plugin_state.go | 25 +++++ ui/model/update.go | 7 ++ ui/model/view.go | 6 ++ 28 files changed, 1521 insertions(+), 19 deletions(-) create mode 100644 luaplugin/api_action.go create mode 100644 luaplugin/api_action_test.go create mode 100644 luaplugin/api_provider.go create mode 100644 luaplugin/api_provider_test.go create mode 100644 plugins/telegram-bot.lua create mode 100644 ui/model/action_pane.go create mode 100644 ui/model/action_pane_test.go create mode 100644 ui/model/lua_input.go diff --git a/docs/keybindings.md b/docs/keybindings.md index 5c492df2b..4b1364b99 100644 --- a/docs/keybindings.md +++ b/docs/keybindings.md @@ -44,6 +44,7 @@ entries, a status message tells you which key to press. | `Ctrl+Z` | Undo the last playlist or queue change | | `o` | Open file browser | | `b` `Esc` | Back to provider | +| `!` | Plugin actions for the active provider | In full and compact playback layouts, the first `Tab` from the playlist focuses Source (`SRC`); `Shift+Tab` starts at Speed when it is visible. Source is skipped diff --git a/docs/plugins.md b/docs/plugins.md index 07f38674e..c386b5e1e 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -291,6 +291,30 @@ The callback can return a string. The CLI client prints it. Invoke commands from List registered commands with `cliamp plugins commands`. A command can run for up to 5 minutes before it times out. cliamp also stops a command when its IPC job is canceled and when cliamp quits. +### `p:action{...}` - plugin action pane (requires `permissions = {"ui"}`) + +The `!` key opens a pane with the actions the loaded plugins registered for the +active provider. An action can run immediately or ask for one line of text +first. `provider` limits it to a provider, by name. + +```lua +p:action{ + key = "!", -- optional, default "!" + id = "send", -- unique per plugin + label = "Send message", + description = "Ask the bot for a track", + provider = "Telegram", -- optional + prompt = "Message", -- optional: ask for text first + on_submit = function(text) ... end, +} +``` + +Actions are namespaced by plugin, so two plugins can use the same `id`. +`p:action` returns `true`, or `false, reason` when the UI permission is missing +or the id is already registered. The action pane filters by provider and by the +text typed in the pane. An action with `prompt` runs `on_submit` with the text; +without it, `on_submit` gets an empty string. + ## Lua API All APIs are in the global `cliamp` table. @@ -358,13 +382,14 @@ cliamp.queue.has_next() --> true when a playable track follows in play order -- mutate (requires "control") cliamp.queue.add(path) -- resolve a file/dir/URL and append +cliamp.queue.insert(index, track) --> true | nil, err -- insert at index cliamp.queue.add(track) --> true | nil, err -- append a track table as given cliamp.queue.jump(index) -- make index current and play it cliamp.queue.remove(index) -- remove the track at index cliamp.queue.move(from, to) -- swap the tracks at from and to ``` -`add`, `remove`, and `move` follow the rules of the `Shift+Up`, `Shift+Down`, +`add`, `insert`, `remove`, and `move` follow the rules of the `Shift+Up`, `Shift+Down`, and `x` keys and of IPC: - While shuffle is on, `move` changes nothing. @@ -372,7 +397,7 @@ and `x` keys and of IPC: that playlist. `remove` removes the track from it too. When that save fails, the edit changes nothing. Favorites is not a playlist file, so an edit of a loaded Favorites list changes only the queue. -- `add`, `move`, and `remove` record no undo. After one of them, `Ctrl+Z` does +- `add`, `insert`, `move`, and `remove` record no undo. After one of them, `Ctrl+Z` does not undo the last TUI edit, because that undo would drop the new change. - While the queue mirrors a saved local playlist, `remove` does not remove a track that a directory source of that playlist supplies. A removal of the @@ -405,6 +430,53 @@ It returns `true`, or `nil` and an error message when the table is invalid (for example, a missing path or a title that is not a string) or when the plugin lacks the `control` permission. An HTTP URL is always marked as a stream. +### cliamp.provider (requires permissions) + +`cliamp.provider.current()` returns the provider and the playlist context: + +```lua +{ + name = "Telegram", + playlist_id = "u:1:2", playlist_name = "DeezLoad", + selection_id = "u:1:2", selection_name = "DeezLoad", +} +``` + +`playlist_id` is the playlist open in the pane; `selection_id` is the row under +the cursor. Either can be empty. `name` is the same string the provider uses in +the UI. + +`cliamp.provider.call(action, params[, options])` calls a provider action. +Reads need `permissions = {"provider"}`; actions that change the remote account +need `permissions = {"provider-send"}`. The provider must implement +`provider.ChatCommander`; a provider without it returns an error. + +```lua +-- block until the bot replies, or return the error +local reply, err = cliamp.provider.call("telegram.ask", { + chat = chat, + text = "/search daft punk", + timeout = 60, +}) + +-- keep the UI responsive while a bot takes its time +cliamp.provider.call("telegram.ask", {chat = chat, text = text}, { + on_reply = function(reply, err) ... end, + timeout = 90, +}) +``` + +Options are `on_reply = function(result, err)` and `timeout = seconds` (default +60). With `on_reply` the call runs off the UI goroutine and delivers the result +to the callback; use it for calls that wait for a bot. Without it the call +blocks the Lua hook and returns the result. A key binding has a five-second +budget, so a waiting call from a key binding needs `on_reply`. + +Telegram actions at this layer are `telegram.commands` (the commands a bot +advertises), `telegram.send` (send text and return the message id), +`telegram.ask` (send and wait for the reply), `telegram.reply` (wait for the +next message after an id), and `telegram.callback` (press an inline button). + ### cliamp.http ```lua @@ -681,6 +753,20 @@ Returns true when the request was accepted. With no interactive UI (headless mode) it returns an error. Closing the selector calls `on_cancel` when given, or `on_select(-1)` otherwise. +```lua +cliamp.ui.input{ + title = "Message", + placeholder = "/search ...", + value = "", -- optional + on_submit = function(text) ... end, + on_cancel = function() ... end, -- optional, Esc +} +``` + +`ui.input` asks for one line of text. `Enter` calls `on_submit` with the text; +`Esc` calls `on_cancel` when given. It returns true when the request was +accepted; headless mode returns an error. + ### cliamp.vis ```lua diff --git a/docs/telegram.md b/docs/telegram.md index ca6182095..e10d574c0 100644 --- a/docs/telegram.md +++ b/docs/telegram.md @@ -107,6 +107,20 @@ screen, desktop widgets) as a `data:` URL. | `buffer_mb` | no | Megabytes buffered before playback (default 1) | | `session_file` | no | Session path (default `~/.local/share/cliamp/telegram.session`) | +## Bot chats + +A chat with a bot is a normal playlist: the provider lists its audio documents +and plays them. A plugin can also write into that chat: send a command as the +signed-in user, wait for the bot's reply, or press an inline button. The write +actions live in the plugin API (`cliamp.provider.call`), not in a fixed key, so +the plugin decides the prompt and how to show the reply. See +[Plugins](plugins.md) and the bundled `telegram-bot.lua`. + +Writes use the same MTProto session as reads and act as the signed-in user. A +bot sees a normal message from you; a command sent to a group is visible to +every member. Keep the session file private: it can send messages and press +buttons on your behalf. + ## Limits - One account: the provider browses the dialogs of the signed-in user. diff --git a/lua_wiring.go b/lua_wiring.go index c9474ebf6..896062605 100644 --- a/lua_wiring.go +++ b/lua_wiring.go @@ -1,6 +1,10 @@ package main import ( + "context" + "encoding/base64" + "fmt" + "strings" "sync" "time" @@ -9,6 +13,7 @@ import ( "github.com/bjarneo/cliamp/internal/playback" "github.com/bjarneo/cliamp/luaplugin" "github.com/bjarneo/cliamp/playlist" + "github.com/bjarneo/cliamp/provider" "github.com/bjarneo/cliamp/ui/model" ) @@ -84,6 +89,13 @@ func luaControlProvider(send func(tea.Msg)) luaplugin.ControlProvider { QueueMove: func(from, to int) { send(model.PluginQueueMsg{Op: "move", Index: from, To: to}) }, + QueueInsert: func(index int, t luaplugin.Track) { + send(model.PluginQueueMsg{Op: "insert", Index: index, Track: playlist.Track{ + Path: t.Path, Title: t.Title, Artist: t.Artist, Album: t.Album, + Genre: t.Genre, Year: t.Year, DurationSecs: t.Duration, Stream: t.Stream, + AlbumArtURL: t.ArtURL, + }}) + }, } } @@ -137,6 +149,7 @@ func luaUIProvider(send func(tea.Msg), headless bool) luaplugin.UIProvider { send(model.ShowStatusMsg{Text: text, Duration: duration}) }, ShowSelect: showSelectFor(send, headless), + ShowInput: showInputFor(send, headless), SetVis: func(name string) { send(model.SetVisMsg{Name: name}) }, @@ -146,6 +159,15 @@ func luaUIProvider(send func(tea.Msg), headless bool) luaplugin.UIProvider { // showSelectFor returns nil in headless mode: there is no UI to answer a // selector, and the API reports it as unavailable instead of accepting a // request nobody can complete. +func showInputFor(send func(tea.Msg), headless bool) func(string, string, string, func(string), func()) { + if headless { + return nil + } + return func(title, placeholder, value string, onSubmit func(string), onCancel func()) { + send(model.LuaInputMsg{Title: title, Placeholder: placeholder, Value: value, OnSubmit: onSubmit, OnCancel: onCancel}) + } +} + func showSelectFor(send func(tea.Msg), headless bool) func(string, []string, int, func(int), func()) { if headless { return nil @@ -154,3 +176,149 @@ func showSelectFor(send func(tea.Msg), headless bool) func(string, []string, int send(model.LuaSelectMsg{Title: title, Options: options, Cursor: cursor, OnDone: onDone, OnCancel: onCancel}) } } + +// luaProviderProvider exposes the provider context and the chat actions a +// provider supports. The dispatcher keeps the Lua API generic: a plugin asks +// for "telegram.send" and the provider that implements ChatCommander runs it. +// The provider call runs on the caller's goroutine, so a blocking reply never +// holds the UI. +func luaProviderProvider(entries []provider.Entry, load func() model.PluginState) luaplugin.ProviderProvider { + return luaplugin.ProviderProvider{ + Current: func() luaplugin.ProviderInfo { return load().Provider }, + Call: func(ctx context.Context, action string, params map[string]any) (map[string]any, error) { + name, verb, ok := strings.Cut(action, ".") + if !ok || name == "" || verb == "" { + return nil, fmt.Errorf("unknown provider action %q", action) + } + var prov playlist.Provider + for _, entry := range entries { + if strings.EqualFold(entry.Name, name) || strings.EqualFold(entry.Key, name) { + prov = entry.Provider + break + } + } + if prov == nil { + return nil, fmt.Errorf("provider %q is not available", name) + } + chat, _ := params["chat"].(string) + if chat == "" { + return nil, fmt.Errorf("%s: chat is required", action) + } + commander, ok := prov.(provider.ChatCommander) + if !ok { + return nil, fmt.Errorf("provider %q does not support chat actions", name) + } + switch verb { + case "commands": + commands, err := commander.BotCommands(ctx, chat) + if err != nil { + return nil, err + } + rows := make([]any, 0, len(commands)) + for _, command := range commands { + rows = append(rows, map[string]any{ + "command": command.Command, + "description": command.Description, + }) + } + return map[string]any{"commands": rows}, nil + case "send": + text, _ := params["text"].(string) + id, err := commander.SendCommand(ctx, chat, text) + if err != nil { + return nil, err + } + return map[string]any{"id": id}, nil + case "ask": + text, _ := params["text"].(string) + id, err := commander.SendCommand(ctx, chat, text) + if err != nil { + return nil, err + } + return waitReplyResult(ctx, commander, chat, id, params) + case "reply": + return waitReplyResult(ctx, commander, chat, intParam(params, "after"), params) + case "callback": + data, err := base64.StdEncoding.DecodeString(stringParam(params, "data_b64")) + if err != nil { + return nil, fmt.Errorf("%s: data_b64: %w", action, err) + } + if err := commander.BotCallback(ctx, chat, intParam(params, "message_id"), data); err != nil { + return nil, err + } + return map[string]any{"ok": true}, nil + default: + return nil, fmt.Errorf("unknown provider action %q", action) + } + }, + } +} + +func waitReplyResult(ctx context.Context, commander provider.ChatCommander, chat string, after int, params map[string]any) (map[string]any, error) { + timeout := 20 * time.Second + if seconds, ok := params["timeout"].(float64); ok && seconds > 0 { + timeout = time.Duration(seconds * float64(time.Second)) + } + reply, err := commander.WaitReply(ctx, chat, after, timeout) + if err != nil { + return nil, err + } + out := map[string]any{ + "id": after, + "kind": reply.Kind, + "text": reply.Text, + "from": reply.From, + "message_id": reply.MessageID, + } + if reply.Kind == "audio" { + out["track"] = luaplugin.TrackData(pluginTrackFromPlaylist(reply.Track)) + } + if len(reply.Buttons) > 0 { + buttons := make([]any, 0, len(reply.Buttons)) + for _, button := range reply.Buttons { + row := map[string]any{"text": button.Text, "kind": button.Kind} + if len(button.Data) > 0 { + row["data_b64"] = base64.StdEncoding.EncodeToString(button.Data) + } + if button.URL != "" { + row["url"] = button.URL + } + if button.SendText { + row["send_text"] = true + } + buttons = append(buttons, row) + } + out["buttons"] = buttons + } + return out, nil +} + +func pluginTrackFromPlaylist(track playlist.Track) luaplugin.Track { + return luaplugin.Track{ + Title: track.Title, + Artist: track.Artist, + Album: track.Album, + Genre: track.Genre, + Path: track.Path, + Year: track.Year, + Number: track.TrackNumber, + Duration: track.DurationSecs, + Stream: track.Stream, + ArtURL: track.AlbumArtURL, + } +} + +func stringParam(params map[string]any, key string) string { + value, _ := params[key].(string) + return value +} + +func intParam(params map[string]any, key string) int { + switch value := params[key].(type) { + case float64: + return int(value) + case int: + return value + } + return 0 +} diff --git a/luaplugin/api_action.go b/luaplugin/api_action.go new file mode 100644 index 000000000..8028383e2 --- /dev/null +++ b/luaplugin/api_action.go @@ -0,0 +1,140 @@ +package luaplugin + +import ( + "errors" + "strings" + + lua "github.com/yuin/gopher-lua" +) + +// errActionExists is returned when a plugin registers the same action id +// twice. +var errActionExists = errors.New("p:action: id already registered") + +// Action is one entry a plugin contributes to the "!" action pane. Prompt is +// the label of the text input; when it is empty the action runs without +// asking for text. Run calls the plugin callback with the typed text. +type Action struct { + ID string + Plugin string + Label string + Description string + Provider string + Key string + Prompt string + + run func(text string) +} + +// Run invokes the action callback. It is safe to call from the UI goroutine: +// the manager queues the Lua call. +func (a Action) Run(text string) { + if a.run != nil { + a.run(text) + } +} + +// registerActionAPI adds p:action() to the plugin object. +func (m *Manager) registerActionAPI(L *lua.LState, obj *lua.LTable, p *Plugin) { + L.SetField(obj, "action", L.NewFunction(func(L *lua.LState) int { + if !p.permitted(PermUI, "p:action") { + L.Push(lua.LFalse) + L.Push(lua.LString("ui permission required")) + return 2 + } + // p:action{...} passes the plugin object first. + opts, ok := L.Get(2).(*lua.LTable) + if !ok { + L.Push(lua.LFalse) + L.Push(lua.LString("p:action: options table required")) + return 2 + } + id := strings.TrimSpace(rawString(L, opts, "id")) + label := strings.TrimSpace(rawString(L, opts, "label")) + fn, ok := opts.RawGetString("on_submit").(*lua.LFunction) + if !ok { + L.Push(lua.LFalse) + L.Push(lua.LString("p:action: on_submit is required")) + return 2 + } + if id == "" { + id = label + } + if id == "" { + L.Push(lua.LFalse) + L.Push(lua.LString("p:action: id or label is required")) + return 2 + } + if label == "" { + label = id + } + key := strings.TrimSpace(rawString(L, opts, "key")) + if key == "" { + key = "!" + } + action := Action{ + ID: id, + Plugin: p.installName, + Label: label, + Description: strings.TrimSpace(rawString(L, opts, "description")), + Provider: strings.TrimSpace(rawString(L, opts, "provider")), + Key: key, + Prompt: strings.TrimSpace(rawString(L, opts, "prompt")), + run: func(text string) { + label := "action " + id + m.enqueue(p, label, func() { + m.call(p, label, hookTimeout, 0, fixedArgs(fn, lua.LString(text))) + }) + }, + } + if err := m.addAction(action); err != nil { + L.Push(lua.LFalse) + L.Push(lua.LString(err.Error())) + return 2 + } + L.Push(lua.LTrue) + return 1 + })) +} + +// addAction stores an action. The plugin install name namespaces the ID so two +// plugins can use the same local id. +func (m *Manager) addAction(action Action) error { + m.mu.Lock() + defer m.mu.Unlock() + key := action.Plugin + "\x00" + action.ID + if m.actions == nil { + m.actions = make(map[string]Action) + } + if _, exists := m.actions[key]; exists { + return errActionExists + } + m.actions[key] = action + return nil +} + +// Actions returns the actions registered for key, in load order. The slice is +// a copy; the caller can sort or filter it. +func (m *Manager) Actions(key string) []Action { + m.mu.RLock() + defer m.mu.RUnlock() + out := make([]Action, 0, len(m.actions)) + for _, action := range m.actions { + if key == "" || action.Key == key { + out = append(out, action) + } + } + return out +} + +// removeActions drops every action of a plugin. It runs when a plugin is +// closed, so the pane never shows a callback into a dead VM. +func (m *Manager) removeActions(installName string) { + m.mu.Lock() + defer m.mu.Unlock() + for key, action := range m.actions { + if action.Plugin == installName { + delete(m.actions, key) + } + } +} diff --git a/luaplugin/api_action_test.go b/luaplugin/api_action_test.go new file mode 100644 index 000000000..599f22c42 --- /dev/null +++ b/luaplugin/api_action_test.go @@ -0,0 +1,18 @@ +package luaplugin + +import "testing" + +func TestActionRegisters(t *testing.T) { + m := newTestManager() + loadTestPlugin(t, m, "action-test", ` + local p = plugin.register({name = "action-test", type = "hook", permissions = {"ui"}}) + p:action{key = "!", id = "say", label = "Say", prompt = "Message", on_submit = function(text) end} + `) + actions := m.Actions("!") + if len(actions) != 1 { + t.Fatalf("actions = %#v", actions) + } + if actions[0].ID != "say" || actions[0].Label != "Say" || actions[0].Prompt != "Message" { + t.Fatalf("action = %#v", actions[0]) + } +} diff --git a/luaplugin/api_provider.go b/luaplugin/api_provider.go new file mode 100644 index 000000000..891616f2a --- /dev/null +++ b/luaplugin/api_provider.go @@ -0,0 +1,148 @@ +package luaplugin + +import ( + "context" + "strings" + "time" + + lua "github.com/yuin/gopher-lua" +) + +// ProviderInfo is the provider and playlist context a plugin sees. The +// playlist is the one open in the provider pane; selection is the row under +// the cursor in the provider list. Either id may be empty. +type ProviderInfo struct { + Name string + PlaylistID string + PlaylistName string + SelectionID string + SelectionName string +} + +// ProviderProvider exposes the active provider context and the chat actions a +// provider supports. Call returns a JSON-compatible map. +type ProviderProvider struct { + Current func() ProviderInfo + Call func(ctx context.Context, action string, params map[string]any) (map[string]any, error) +} + +// providerWrites reports whether an action changes the remote account. Write +// actions need permissions = {"provider-send"}; reads need "provider". +func providerWrites(action string) bool { + switch action { + case "telegram.send", "telegram.ask", "telegram.reply", "telegram.callback": + return true + } + return false +} + +// registerProviderAPI adds cliamp.provider.* to the cliamp table. +// +// cliamp.provider.current() -> {name, playlist_id, playlist_name, +// selection_id, selection_name} +// cliamp.provider.call(action, params[, {on_reply = fn, timeout = secs}]) +func (m *Manager) registerProviderAPI(L *lua.LState, cliamp *lua.LTable, p *Plugin) { + tbl := L.NewTable() + + L.SetField(tbl, "current", L.NewFunction(func(L *lua.LState) int { + if !p.permitted(PermProvider, "cliamp.provider.current") { + return pushErr(L, "provider permission required") + } + pp := m.provider.Load() + if pp == nil || pp.Current == nil { + return pushErr(L, "provider: not available") + } + info := pp.Current() + L.Push(dataToTable(L, map[string]any{ + "name": info.Name, + "playlist_id": info.PlaylistID, + "playlist_name": info.PlaylistName, + "selection_id": info.SelectionID, + "selection_name": info.SelectionName, + })) + return 1 + })) + + L.SetField(tbl, "call", L.NewFunction(func(L *lua.LState) int { + action := strings.TrimSpace(L.CheckString(1)) + if action == "" { + return pushErr(L, "cliamp.provider.call: action is required") + } + if providerWrites(action) { + if !p.permitted(PermProviderSend, "cliamp.provider.call") { + return pushErr(L, "provider-send permission required") + } + } else if !p.permitted(PermProvider, "cliamp.provider.call") { + return pushErr(L, "provider permission required") + } + params := map[string]any{} + if value := L.Get(2); value != lua.LNil { + table, ok := value.(*lua.LTable) + if !ok { + return pushErr(L, "cliamp.provider.call: params must be a table") + } + if converted, ok := luaToGo(table).(map[string]any); ok { + params = converted + } + } + pp := m.provider.Load() + if pp == nil || pp.Call == nil { + return pushErr(L, "provider: not available") + } + + var opts *lua.LTable + if value := L.Get(3); value != lua.LNil { + opts, _ = value.(*lua.LTable) + } + var onReply *lua.LFunction + timeout := 60 * time.Second + if opts != nil { + onReply, _ = opts.RawGetString("on_reply").(*lua.LFunction) + if seconds := optFloatField(L, opts, "timeout"); seconds > 0 { + timeout = time.Duration(seconds * float64(time.Second)) + } + } + + if onReply != nil { + go m.runProviderCall(p, pp.Call, action, params, timeout, onReply) + L.Push(lua.LTrue) + return 1 + } + + ctx := callContext(L) + result, err := pp.Call(ctx, action, params) + if err != nil { + return pushErr(L, err.Error()) + } + L.Push(dataToTable(L, result)) + return 1 + })) + + L.SetField(cliamp, "provider", tbl) +} + +// runProviderCall runs a provider action off the Lua VM and delivers the +// result to the plugin callback. A key bind has a five-second hook budget, so +// a plugin that waits for a bot must use on_reply instead of blocking. +func (m *Manager) runProviderCall(p *Plugin, call func(context.Context, string, map[string]any) (map[string]any, error), action string, params map[string]any, timeout time.Duration, fn *lua.LFunction) { + ctx, cancel := context.WithTimeout(m.ctx, timeout) + defer cancel() + result, err := call(ctx, action, params) + label := "provider.call " + action + m.enqueue(p, label, func() { + m.call(p, label, hookTimeout, 0, func(L *lua.LState) (*lua.LFunction, []lua.LValue) { + if err != nil { + return fn, []lua.LValue{lua.LNil, lua.LString(err.Error())} + } + return fn, []lua.LValue{dataToTable(L, result)} + }) + }) +} + +// optFloatField reads a number field from a Lua options table. +func optFloatField(L *lua.LState, table *lua.LTable, key string) float64 { + if value, ok := table.RawGetString(key).(lua.LNumber); ok { + return float64(value) + } + return 0 +} diff --git a/luaplugin/api_provider_test.go b/luaplugin/api_provider_test.go new file mode 100644 index 000000000..c532d1f91 --- /dev/null +++ b/luaplugin/api_provider_test.go @@ -0,0 +1,143 @@ +package luaplugin + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + lua "github.com/yuin/gopher-lua" +) + +func TestProviderCurrent(t *testing.T) { + m := newTestManager() + m.SetProviderProvider(ProviderProvider{ + Current: func() ProviderInfo { + return ProviderInfo{ + Name: "Telegram", + PlaylistID: "u:1:2", + PlaylistName: "DeezLoad", + SelectionID: "u:3:4", + SelectionName: "Other", + } + }, + }) + loadTestPlugin(t, m, "provider-current", ` + local p = plugin.register({name = "provider-current", type = "hook", permissions = {"provider"}}) + local c = cliamp.provider.current() + _G.name = c.name + _G.playlist = c.playlist_name + _G.selection = c.selection_name + `) + + p := m.plugins[0] + if got := p.L.GetGlobal("name").String(); got != "Telegram" { + t.Errorf("name = %q", got) + } + if got := p.L.GetGlobal("playlist").String(); got != "DeezLoad" { + t.Errorf("playlist = %q", got) + } + if got := p.L.GetGlobal("selection").String(); got != "Other" { + t.Errorf("selection = %q", got) + } +} + +func TestProviderCallRead(t *testing.T) { + m := newTestManager() + var gotAction string + m.SetProviderProvider(ProviderProvider{ + Current: func() ProviderInfo { return ProviderInfo{Name: "Telegram"} }, + Call: func(_ context.Context, action string, params map[string]any) (map[string]any, error) { + gotAction = action + if params["chat"] != "u:1:2" { + t.Errorf("chat = %v", params["chat"]) + } + return map[string]any{"commands": []any{ + map[string]any{"command": "/search", "description": "Find"}, + }}, nil + }, + }) + loadTestPlugin(t, m, "provider-read", ` + local p = plugin.register({name = "provider-read", type = "hook", permissions = {"provider"}}) + local res = cliamp.provider.call("telegram.commands", {chat = "u:1:2"}) + _G.command = res.commands[1].command + _G.description = res.commands[1].description + `) + if gotAction != "telegram.commands" { + t.Errorf("action = %q", gotAction) + } + p := m.plugins[0] + if got := p.L.GetGlobal("command").String(); got != "/search" { + t.Errorf("command = %q", got) + } + if got := p.L.GetGlobal("description").String(); got != "Find" { + t.Errorf("description = %q", got) + } +} + +func TestProviderCallWriteNeedsPermission(t *testing.T) { + m := newTestManager() + m.SetProviderProvider(ProviderProvider{ + Call: func(context.Context, string, map[string]any) (map[string]any, error) { + t.Fatal("the call should not run without provider-send") + return nil, nil + }, + }) + loadTestPlugin(t, m, "provider-denied", ` + local p = plugin.register({name = "provider-denied", type = "hook", permissions = {"provider"}}) + local ok, err = cliamp.provider.call("telegram.send", {chat = "u:1:2", text = "/start"}) + _G.ok = ok + _G.err = err + `) + p := m.plugins[0] + if p.L.GetGlobal("ok") != lua.LNil { + t.Error("call should return nil") + } + if got := p.L.GetGlobal("err").String(); !strings.Contains(got, "provider-send") { + t.Errorf("err = %q", got) + } +} + +func TestProviderCallAsyncReply(t *testing.T) { + m := newTestManager() + messages := make(chan string, 1) + m.SetUIProvider(UIProvider{ + ShowMessage: func(text string, _ time.Duration) { messages <- text }, + }) + m.SetProviderProvider(ProviderProvider{ + Call: func(ctx context.Context, action string, params map[string]any) (map[string]any, error) { + if action != "telegram.ask" { + return nil, errors.New("unexpected action " + action) + } + select { + case <-ctx.Done(): + return nil, ctx.Err() + case <-time.After(30 * time.Millisecond): + } + return map[string]any{ + "id": 10, + "kind": "audio", + "track": map[string]any{ + "title": "Walk", "artist": "Foo Fighters", "path": "telegram:u:1:2:10", + }, + }, nil + }, + }) + loadTestPlugin(t, m, "provider-async", ` + local p = plugin.register({name = "provider-async", type = "hook", permissions = {"provider", "provider-send"}}) + cliamp.provider.call("telegram.ask", {chat = "u:1:2", text = "/search walk"}, { + on_reply = function(reply) + cliamp.message(reply.kind .. ":" .. reply.track.title) + end, + }) + `) + select { + case got := <-messages: + if got != "audio:Walk" { + t.Fatalf("message = %q", got) + } + case <-time.After(2 * time.Second): + t.Fatal("the on_reply callback never ran") + } +} diff --git a/luaplugin/api_queue.go b/luaplugin/api_queue.go index 88f9d2023..2243eee32 100644 --- a/luaplugin/api_queue.go +++ b/luaplugin/api_queue.go @@ -120,6 +120,31 @@ func registerQueueAPI(L *lua.LState, cliamp *lua.LTable, loadState func() *State return 0 })) + // cliamp.queue.insert(index, track) -> true | nil, err — insert a track at + // index. The core remaps the play order, the play-next queue and the + // current position. + L.SetField(tbl, "insert", L.NewFunction(func(L *lua.LState) int { + ctrl := loadCtrl() + index := L.CheckInt(1) + table, ok := L.Get(2).(*lua.LTable) + if !ok { + return pushErr(L, "queue.insert: track table required") + } + if !guard("insert") { + return pushErr(L, "queue.insert: requires permissions = {\"control\"}") + } + if ctrl.QueueInsert == nil { + return pushErr(L, "queue.insert: unavailable") + } + track, err := trackFromTable(table) + if err != nil { + return pushErr(L, "queue.insert: "+err.Error()) + } + ctrl.QueueInsert(index, track) + L.Push(lua.LTrue) + return 1 + })) + // cliamp.queue.move(from, to) — reorder a track. L.SetField(tbl, "move", L.NewFunction(func(L *lua.LState) int { ctrl := loadCtrl() diff --git a/luaplugin/api_ui.go b/luaplugin/api_ui.go index c0fd7e574..f6910b379 100644 --- a/luaplugin/api_ui.go +++ b/luaplugin/api_ui.go @@ -62,6 +62,42 @@ func registerUIAPI(L *lua.LState, cliamp *lua.LTable, p *Plugin, m *Manager) { return 1 })) + // cliamp.ui.input{title = "...", placeholder = "...", value = "...", + // on_submit = fn, on_cancel = fn} + L.SetField(tbl, "input", L.NewFunction(func(L *lua.LState) int { + if !p.permitted(PermUI, "cliamp.ui.input") { + return pushErr(L, "ui permission required") + } + opts := L.CheckTable(1) + fn, ok := opts.RawGetString("on_submit").(*lua.LFunction) + if !ok { + return pushErr(L, "cliamp.ui.input: on_submit is required") + } + up := m.ui.Load() + if up == nil || up.ShowInput == nil { + return pushErr(L, "ui: not available") + } + title := strings.TrimSpace(rawString(L, opts, "title")) + placeholder := strings.TrimSpace(rawString(L, opts, "placeholder")) + value := rawString(L, opts, "value") + cancelFn, _ := opts.RawGetString("on_cancel").(*lua.LFunction) + onCancel := func() {} + if cancelFn != nil { + onCancel = func() { + m.enqueue(p, "ui.input cancel", func() { + m.call(p, "ui.input cancel", hookTimeout, 0, fixedArgs(cancelFn)) + }) + } + } + up.ShowInput(title, placeholder, value, func(text string) { + m.enqueue(p, "ui.input", func() { + m.call(p, "ui.input", hookTimeout, 0, fixedArgs(fn, lua.LString(text))) + }) + }, onCancel) + L.Push(lua.LTrue) + return 1 + })) + vis := L.NewTable() // cliamp.vis.set("Scatter") L.SetField(vis, "set", L.NewFunction(func(L *lua.LState) int { diff --git a/luaplugin/hooks.go b/luaplugin/hooks.go index 8ccbf7b8e..98129e9e2 100644 --- a/luaplugin/hooks.go +++ b/luaplugin/hooks.go @@ -43,12 +43,14 @@ const ( // Permission strings declared via plugin.register({ permissions = {...} }). // Kept as named constants so the guard call sites and docs don't drift. const ( - PermControl = "control" - PermExec = "exec" - PermImage = "image" - PermLayout = "layout" - PermUI = "ui" - PermKeymap = "keymap" + PermControl = "control" + PermExec = "exec" + PermImage = "image" + PermLayout = "layout" + PermUI = "ui" + PermKeymap = "keymap" + PermProvider = "provider" + PermProviderSend = "provider-send" ) // luaHook is a single event callback registered by a plugin. diff --git a/luaplugin/luaplugin.go b/luaplugin/luaplugin.go index 72150d9e7..8ed7752aa 100644 --- a/luaplugin/luaplugin.go +++ b/luaplugin/luaplugin.go @@ -117,11 +117,12 @@ type ControlProvider struct { SetEQPreset func(name string, bands *[10]float64) Next func() Prev func() - QueueAdd func(path string) // resolve path/URL and append - QueueAddTrack func(track Track) // append a track table as given, without resolving its path - QueueJump func(index int) // make index current and play it - QueueRemove func(index int) // remove track at index - QueueMove func(from, to int) // reorder + QueueAdd func(path string) // resolve path/URL and append + QueueAddTrack func(track Track) // append a track table as given, without resolving its path + QueueJump func(index int) // make index current and play it + QueueRemove func(index int) // remove track at index + QueueMove func(from, to int) // reorder + QueueInsert func(index int, track Track) // insert a track at index } // UIProvider supplies callbacks that surface plugin output in the TUI. @@ -133,6 +134,10 @@ type UIProvider struct { // index, or -1 when the user cancels. It must return at once; onDone runs on // the UI goroutine and the manager turns it into a plugin callback. ShowSelect func(title string, options []string, cursor int, onDone func(index int), onCancel func()) + // ShowInput opens a text input. It must return at once; onSubmit and + // onCancel run on the UI goroutine and the manager turns them into plugin + // callbacks. + ShowInput func(title, placeholder, value string, onSubmit func(text string), onCancel func()) // SetVis switches the active visualizer by name. It must return at once: the // UI applies the change on its own goroutine. SetVis func(name string) @@ -152,14 +157,16 @@ type Manager struct { keyBindDescs map[string]KeyBinding // key string -> UI overlay entry (only for binds that supplied a description) reservedKeys map[string]bool // core-reserved keys; plugins may not bind these commands map[string]map[string]*luaHook // plugin name -> command name -> handler + actions map[string]Action // plugin name + id -> action pane entry visPlugs []*luaVis // Lua visualizers in registration order visMap map[string]*luaVis // name -> Lua visualizer namespaces map[string]string // event namespace -> owning plugin name layoutProvider LayoutProvider - names map[string]*Plugin // display name -> plugin that registered it - state atomic.Pointer[StateProvider] // see SetStateProvider - control atomic.Pointer[ControlProvider] // see SetControlProvider - ui atomic.Pointer[UIProvider] // see SetUIProvider + names map[string]*Plugin // display name -> plugin that registered it + state atomic.Pointer[StateProvider] // see SetStateProvider + control atomic.Pointer[ControlProvider] // see SetControlProvider + ui atomic.Pointer[UIProvider] // see SetUIProvider + provider atomic.Pointer[ProviderProvider] // see SetProviderProvider publisher EventPublisher timers *timerManager execs *execManager @@ -511,6 +518,7 @@ func (m *Manager) registerPluginAPI(L *lua.LState, p *Plugin) { m.registerPublishAPI(L, obj, p) m.registerKeymapAPI(L, obj, p) m.registerCommandAPI(L, obj, p) + m.registerActionAPI(L, obj, p) // For visualizer plugins, add init/render registration. if p.Type == "visualizer" { @@ -535,6 +543,7 @@ func (m *Manager) registerCliampAPI(L *lua.LState, p *Plugin) { registerImageAPI(L, cliamp, p) registerLayoutAPI(L, cliamp, p, m) registerUIAPI(L, cliamp, p, m) + m.registerProviderAPI(L, cliamp, p) registerHTTPAPI(L, cliamp) loadState, loadCtrl := loadProvider(&m.state), loadProvider(&m.control) registerPlayerAPI(L, cliamp, loadState) @@ -654,6 +663,12 @@ func (m *Manager) SetStateProvider(sp StateProvider) { m.state.Store(&sp) } +// SetProviderProvider sets the active provider context and the chat actions +// that cliamp.provider.call exposes. It is safe to call while plugins run. +func (m *Manager) SetProviderProvider(pp ProviderProvider) { + m.provider.Store(&pp) +} + // SetControlProvider sets the function pointers for player control. // Only plugins with permissions = {"control"} can use these. It is safe to // call while plugins run. @@ -727,6 +742,7 @@ func (m *Manager) Close() { // Close each VM under its lock. A timer or exec callback that runs now // finishes first, and each later call sees closed and returns errClosed. for _, p := range m.plugins { + m.removeActions(p.installName) p.mu.Lock() p.closed = true p.L.Close() diff --git a/luaplugin/metadata.go b/luaplugin/metadata.go index 8a50d0e60..75e27e585 100644 --- a/luaplugin/metadata.go +++ b/luaplugin/metadata.go @@ -24,7 +24,7 @@ type Metadata struct { // knownPermissions holds the names that plugin.register() accepts in // permissions. -var knownPermissions = map[string]bool{PermControl: true, PermExec: true, PermImage: true, PermLayout: true, PermUI: true, PermKeymap: true} +var knownPermissions = map[string]bool{PermControl: true, PermExec: true, PermImage: true, PermLayout: true, PermUI: true, PermKeymap: true, PermProvider: true, PermProviderSend: true} // errRegisteredTwice is the error of a second plugin.register() call. A // later call could otherwise replace the permissions that install and trust diff --git a/main.go b/main.go index bc9397391..10b36a631 100644 --- a/main.go +++ b/main.go @@ -185,6 +185,7 @@ func run(overrides config.Overrides, positional []string, headless, visualizer60 m.SetIPCBroker(pluginBroker) if luaMgr != nil { luaMgr.SetStateProvider(luaStateProvider(p, m.PluginStateLoader())) + luaMgr.SetProviderProvider(luaProviderProvider(providers.entries, m.PluginStateLoader())) if names := luaMgr.Visualizers(); len(names) > 0 { m.RegisterLuaVisualizers(names, luaMgr) } diff --git a/playlist/playlist.go b/playlist/playlist.go index bdbc0baca..068512be2 100644 --- a/playlist/playlist.go +++ b/playlist/playlist.go @@ -210,6 +210,57 @@ func (p *Playlist) Add(tracks ...Track) { p.revision++ } +// Insert puts track at index in the list. Every index in the play order, +// the play-next queue and the current position moves with its track. In +// shuffle mode the new track plays next; otherwise it keeps the list +// position. +func (p *Playlist) Insert(index int, track Track) { + p.mu.Lock() + defer p.mu.Unlock() + if index < 0 { + index = 0 + } + if index > len(p.tracks) { + index = len(p.tracks) + } + track = cloneTrack(track) + p.tracks = append(p.tracks, Track{}) + copy(p.tracks[index+1:], p.tracks[index:]) + p.tracks[index] = track + + for i, idx := range p.order { + if idx >= index { + p.order[i] = idx + 1 + } + } + insertAt := index + if p.shuffle { + insertAt = p.pos + 1 + if insertAt < 0 { + insertAt = 0 + } + if insertAt > len(p.order) { + insertAt = len(p.order) + } + } + p.order = append(p.order, 0) + copy(p.order[insertAt+1:], p.order[insertAt:]) + p.order[insertAt] = index + if !p.shuffle && index <= p.pos { + p.pos++ + } + for i, idx := range p.queue { + if idx >= index { + p.queue[i] = idx + 1 + } + } + if p.queuedIdx >= index { + p.queuedIdx++ + } + p.rebuildQueuePositions() + p.revision++ +} + // Len returns the number of tracks. func (p *Playlist) Len() int { p.mu.Lock() diff --git a/playlist/playlist_test.go b/playlist/playlist_test.go index 546ce3b95..b198b68f0 100644 --- a/playlist/playlist_test.go +++ b/playlist/playlist_test.go @@ -787,3 +787,59 @@ func TestReverseShuffledKeepsPlayOrder(t *testing.T) { t.Errorf("pos = %d, want %d", p.pos, pos) } } + +func TestInsertAtTopKeepsTheCurrentTrack(t *testing.T) { + p := makePlaylist(3, false) // A B C + p.SetIndex(1) // B + + p.Insert(0, Track{Title: "X"}) + + if got, want := titles(p), []string{"X", "A", "B", "C"}; !sliceEq(got, want) { + t.Fatalf("titles = %v, want %v", got, want) + } + current, index := p.Current() + if current.Title != "B" || index != 2 { + t.Fatalf("current = %q index %d, want B index 2", current.Title, index) + } +} + +func TestInsertAtMiddleKeepsOrder(t *testing.T) { + p := makePlaylist(3, false) // A B C + + p.Insert(1, Track{Title: "X"}) + + if got, want := titles(p), []string{"A", "X", "B", "C"}; !sliceEq(got, want) { + t.Fatalf("titles = %v, want %v", got, want) + } + current, index := p.Current() + if current.Title != "A" || index != 0 { + t.Fatalf("current = %q index %d, want A index 0", current.Title, index) + } +} + +func TestInsertShufflePlaysNext(t *testing.T) { + p := makePlaylist(3, true) + p.pos = 0 + + p.Insert(0, Track{Title: "X"}) + + next, ok := p.Next() + if !ok || next.Title != "X" { + t.Fatalf("next = %q, %v; want X", next.Title, ok) + } +} + +func TestInsertRemapsThePlayNextQueue(t *testing.T) { + p := makePlaylist(3, false) // A B C + p.Queue(2) // C + + p.Insert(0, Track{Title: "X"}) + + entries := p.QueueEntries() + if len(entries) != 1 { + t.Fatalf("queue = %#v", entries) + } + if entries[0].Track.Title != "C" || entries[0].TrackIndex != 3 { + t.Fatalf("queue entry = %#v, want C at 3", entries[0]) + } +} diff --git a/plugins/telegram-bot.lua b/plugins/telegram-bot.lua new file mode 100644 index 000000000..264bd8651 --- /dev/null +++ b/plugins/telegram-bot.lua @@ -0,0 +1,129 @@ +-- telegram-bot.lua — send a message to the Telegram chat you are browsing +-- and add the audio the bot replies with to the current playlist. +-- +-- The core owns the MTProto session and the send/reply calls. This plugin +-- only draws the prompt and decides what to do with the reply, so any bot +-- that answers a text command with an audio document works without code +-- changes. +-- +-- The action appears under "!" when the Telegram provider is open. The +-- p:command("ask") form is for scripts and the MCP: +-- +-- cliamp plugins call telegram-bot ask /search daft punk + +local p = plugin.register({ + name = "telegram-bot", + type = "hook", + version = "0.1.0", + description = "Send a message to a Telegram bot and add its audio to the playlist", + permissions = {"ui", "provider", "provider-send", "control"}, +}) + +local function current_chat() + local ctx = cliamp.provider.current() + if ctx.name ~= "Telegram" then + return nil, nil + end + local chat = ctx.playlist_id + local name = ctx.playlist_name + if chat == "" then + chat = ctx.selection_id + name = ctx.selection_name + end + if chat == "" then + return nil, nil + end + return chat, name +end + +local function add_reply(reply, err) + if not reply then + cliamp.message("Telegram: " .. tostring(err or "no reply"), 8) + return + end + if reply.kind == "audio" and reply.track then + cliamp.queue.insert(0, reply.track) + cliamp.message("Added: " .. reply.track.title, 5) + return + end + if reply.kind == "text" then + cliamp.message(reply.text, 8) + return + end + cliamp.message("No reply yet. Ctrl+R to reload.", 5) +end + +p:action{ + key = "!", + id = "send", + label = "Send message to this chat", + description = "Ask the bot for a track", + provider = "Telegram", + on_submit = function() + local chat, name = current_chat() + if not chat then + cliamp.message("Open a Telegram chat first.", 3) + return + end + cliamp.ui.input{ + title = "Message → " .. (name or chat), + placeholder = "/search ...", + on_submit = function(text) + cliamp.message("Sent. Waiting for the bot…", 3) + local ok, err = cliamp.provider.call("telegram.ask", { + chat = chat, + text = text, + timeout = 60, + }, { + on_reply = add_reply, + timeout = 90, + }) + if not ok then + cliamp.message("Send failed: " .. tostring(err), 8) + end + end, + } + end, +} + +p:command("commands", function(args) + local chat = args[1] + if not chat or chat == "" then + return "usage: commands " + end + local res, err = cliamp.provider.call("telegram.commands", {chat = chat}) + if not res then + return "error: " .. tostring(err) + end + local out = {} + for _, command in ipairs(res.commands) do + out[#out+1] = command.command .. " — " .. command.description + end + return table.concat(out, "\n") +end) + +p:command("ask", function(args) + local chat = args[1] + local text = table.concat(args, " ", 2) + if not chat or chat == "" or text == "" then + return "usage: ask " + end + local reply, err = cliamp.provider.call("telegram.ask", { + chat = chat, + text = text, + timeout = 60, + }) + if not reply then + return "error: " .. tostring(err) + end + if reply.kind == "audio" and reply.track then + return "audio: " .. reply.track.title + end + local out = {reply.kind .. ": " .. tostring(reply.text)} + if reply.buttons then + for i, button in ipairs(reply.buttons) do + out[#out+1] = string.format(" %d. %s kind=%s data=%s", i, button.text, tostring(button.kind), tostring(button.data_b64 or button.url)) + end + end + return table.concat(out, "\n") +end) diff --git a/ui/model/action_pane.go b/ui/model/action_pane.go new file mode 100644 index 000000000..c3dec0c92 --- /dev/null +++ b/ui/model/action_pane.go @@ -0,0 +1,190 @@ +package model + +import ( + "fmt" + "sort" + "strings" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" + + "github.com/bjarneo/cliamp/luaplugin" +) + +// actionPaneState is the "!" pane: every plugin action registered for this +// key, filtered by the text the user types. +type actionPaneState struct { + visible bool + entries []luaplugin.Action + filtered []luaplugin.Action + cursor int + scroll int + query string +} + +// openActionPane collects the actions registered for "!" and shows them. +func (m *Model) openActionPane() { + if m.luaMgr == nil { + m.status.Warning("No plugin actions. Install a plugin that registers p:action.", statusTTLDefault) + return + } + entries := m.luaMgr.Actions("!") + providerName := "" + if m.provider != nil { + providerName = m.provider.Name() + } + available := entries[:0] + for _, action := range entries { + if action.Provider == "" || strings.EqualFold(action.Provider, providerName) { + available = append(available, action) + } + } + entries = available + if len(entries) == 0 { + m.status.Warning("No plugin actions for !. Install a plugin that registers p:action.", statusTTLDefault) + return + } + sort.SliceStable(entries, func(i, j int) bool { + if entries[i].Plugin != entries[j].Plugin { + return entries[i].Plugin < entries[j].Plugin + } + return entries[i].Label < entries[j].Label + }) + m.actionPane = actionPaneState{ + visible: true, + entries: entries, + filtered: entries, + } +} + +// handleActionPaneKey owns the keys while the action pane is open. +func (m *Model) handleActionPaneKey(msg tea.KeyPressMsg) tea.Cmd { + pane := &m.actionPane + switch msg.String() { + case "esc": + m.actionPane = actionPaneState{} + return nil + case "up", "k": + if pane.cursor > 0 { + pane.cursor-- + } else { + pane.cursor = max(0, len(pane.filtered)-1) + } + pane.adjustScroll() + return nil + case "down", "j": + if pane.cursor < len(pane.filtered)-1 { + pane.cursor++ + } else { + pane.cursor = 0 + } + pane.adjustScroll() + return nil + case "enter": + if len(pane.filtered) == 0 { + return nil + } + action := pane.filtered[pane.cursor] + m.actionPane = actionPaneState{} + if action.Prompt != "" { + m.openLuaInput(action.Prompt, "", "", func(text string) { + action.Run(text) + }, nil) + return nil + } + action.Run("") + return nil + default: + if m.editText("action-pane", &pane.query, msg) { + m.filterActions() + } + } + return nil +} + +func (p *actionPaneState) adjustScroll() { + visible := max(1, p.visibleRows()) + if p.cursor < p.scroll { + p.scroll = p.cursor + } + if p.cursor >= p.scroll+visible { + p.scroll = p.cursor - visible + 1 + } +} + +func (p *actionPaneState) visibleRows() int { + return 10 +} + +// filterActions keeps the actions whose label, description or plugin contains +// the query. +func (m *Model) filterActions() { + pane := &m.actionPane + query := strings.ToLower(strings.TrimSpace(pane.query)) + if query == "" { + pane.filtered = pane.entries + } else { + pane.filtered = pane.filtered[:0] + for _, action := range pane.entries { + text := strings.ToLower(action.Label + " " + action.Description + " " + action.Plugin) + if strings.Contains(text, query) { + pane.filtered = append(pane.filtered, action) + } + } + } + pane.cursor = 0 + pane.scroll = 0 +} + +// renderActionPane draws the action list as a centered box. +func (m Model) renderActionPane() string { + pane := m.actionPane + if !pane.visible { + return "" + } + width := max(40, m.layout.frameWidth/2) + width = min(width, max(28, m.layout.frameWidth-4)) + + var b strings.Builder + b.WriteString("Actions") + b.WriteString("\n\n") + b.WriteString("> " + truncate(pane.query, width-4)) + b.WriteString("\n\n") + if len(pane.filtered) == 0 { + b.WriteString(dimStyle.Render(" no matches")) + } else { + visible := min(m.actionPane.visibleRows(), len(pane.filtered)) + start := pane.scroll + if start > len(pane.filtered)-visible { + start = max(0, len(pane.filtered)-visible) + } + end := min(start+visible, len(pane.filtered)) + for i := start; i < end; i++ { + action := pane.filtered[i] + prefix := " " + if i == pane.cursor { + prefix = "ā–ø " + } + line := prefix + action.Label + if action.Plugin != "" && action.Plugin != action.Label { + line += dimStyle.Render(" " + action.Plugin) + } + b.WriteString(truncate(line, width-4)) + if i < end-1 { + b.WriteString("\n") + } + } + if end < len(pane.filtered) { + b.WriteString("\n" + dimStyle.Render(fmt.Sprintf(" ↓ %d more", len(pane.filtered)-end))) + } + } + b.WriteString("\n\n") + b.WriteString(dimStyle.Render(" type to filter enter run esc cancel")) + + return lipgloss.NewStyle(). + Border(lipgloss.RoundedBorder()). + BorderForeground(lipgloss.Color("240")). + Padding(0, 1). + Width(width). + Render(b.String()) +} diff --git a/ui/model/action_pane_test.go b/ui/model/action_pane_test.go new file mode 100644 index 000000000..9433fa2df --- /dev/null +++ b/ui/model/action_pane_test.go @@ -0,0 +1,116 @@ +package model + +import ( + "os" + "path/filepath" + "sync" + "testing" + "time" + + tea "charm.land/bubbletea/v2" + + "github.com/bjarneo/cliamp/internal/plugintrust" + "github.com/bjarneo/cliamp/luaplugin" +) + +func TestActionPaneRunsPluginActionWithInput(t *testing.T) { + configDir := t.TempDir() + t.Setenv("CLIAMP_CONFIG_DIR", configDir) + pluginDir := filepath.Join(configDir, "plugins") + if err := os.MkdirAll(pluginDir, 0o755); err != nil { + t.Fatal(err) + } + pluginPath := filepath.Join(pluginDir, "action-spy.lua") + script := ` +local p = plugin.register({ + name = "action-spy", + type = "hook", + permissions = {"ui"}, +}) +p:action{ + key = "!", + id = "say", + label = "Say something", + prompt = "Message", + on_submit = function(text) + cliamp.message("got:" .. text) + end, +} +` + if err := os.WriteFile(pluginPath, []byte(script), 0o644); err != nil { + t.Fatal(err) + } + if _, err := plugintrust.Approve(pluginDir, "action-spy", pluginPath); err != nil { + t.Fatal(err) + } + mgr, err := luaplugin.New(nil, nil, ReservedKeys()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(sync.OnceFunc(mgr.Close)) + + messages := make(chan string, 1) + mgr.SetUIProvider(luaplugin.UIProvider{ + ShowMessage: func(text string, _ time.Duration) { messages <- text }, + }) + + t.Logf("actions: %#v", mgr.Actions("!")) + m := Model{luaMgr: mgr} + m.openActionPane() + if !m.actionPane.visible || len(m.actionPane.filtered) != 1 { + t.Fatalf("pane = %#v", m.actionPane) + } + m.handleActionPaneKey(tea.KeyPressMsg{Code: tea.KeyEnter}) + if m.luaInput == nil { + t.Fatal("enter did not open the prompt") + } + m.luaInput.value = "hello" + m.handleLuaInputKey(tea.KeyPressMsg{Code: tea.KeyEnter}) + + select { + case got := <-messages: + if got != "got:hello" { + t.Fatalf("message = %q", got) + } + case <-time.After(2 * time.Second): + t.Fatal("the action callback never ran") + } +} + +func TestActionPaneFiltersByLabel(t *testing.T) { + configDir := t.TempDir() + t.Setenv("CLIAMP_CONFIG_DIR", configDir) + pluginDir := filepath.Join(configDir, "plugins") + if err := os.MkdirAll(pluginDir, 0o755); err != nil { + t.Fatal(err) + } + pluginPath := filepath.Join(pluginDir, "action-list.lua") + script := ` +local p = plugin.register({name = "action-list", type = "hook", permissions = {"ui"}}) +for _, label in ipairs({"DeezLoad", "Other bot"}) do + p:action{key = "!", label = label, on_submit = function() end} +end +` + if err := os.WriteFile(pluginPath, []byte(script), 0o644); err != nil { + t.Fatal(err) + } + if _, err := plugintrust.Approve(pluginDir, "action-list", pluginPath); err != nil { + t.Fatal(err) + } + mgr, err := luaplugin.New(nil, nil, ReservedKeys()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(sync.OnceFunc(mgr.Close)) + + m := Model{luaMgr: mgr} + m.openActionPane() + if got := len(m.actionPane.filtered); got != 2 { + t.Fatalf("filtered = %d, want 2", got) + } + m.actionPane.query = "deez" + m.filterActions() + if got := len(m.actionPane.filtered); got != 1 || m.actionPane.filtered[0].Label != "DeezLoad" { + t.Fatalf("filtered = %#v", m.actionPane.filtered) + } +} diff --git a/ui/model/command_registry.go b/ui/model/command_registry.go index ab6ffae32..c80f5fb95 100644 --- a/ui/model/command_registry.go +++ b/ui/model/command_registry.go @@ -200,6 +200,7 @@ var commandRegistry = []commandSpec{ {Mode: commandModeMain, Keys: []string{"/"}, KeyLabel: "/", Label: "Filter/search list", Keymap: true, ContextHelp: true}, {Mode: commandModeMain, Keys: []string{"ctrl+f"}, KeyLabel: "Ctrl+F", Label: "Search active provider or YouTube", Keymap: true, ContextHelp: true}, {Mode: commandModeMain, Keys: []string{"u"}, KeyLabel: "u", Label: "Load URL (stream/playlist)", Keymap: true}, + {Mode: commandModeMain | commandModeProvider, Keys: []string{"!"}, KeyLabel: "!", Label: "Plugin actions", Keymap: true, ContextHelp: true}, {Mode: commandModeMain, Keys: []string{"d"}, KeyLabel: "d", Label: "Audio device picker", Keymap: true}, {Mode: commandModeMain, Keys: []string{"y"}, KeyLabel: "y", Label: "Show lyrics", Keymap: true}, {Mode: commandModeMain | commandModeProvider | commandModeProviderPill | commandModeVolume | commandModeEQ | commandModeShuffle | commandModeRepeat | commandModeSpeed, Keys: []string{"tab", "shift+tab"}, KeyLabel: "Tab/Shift+Tab", Label: "Focus", Keymap: true, ContextHelp: true}, diff --git a/ui/model/keymap_test.go b/ui/model/keymap_test.go index ba37bffd4..6ae400dcd 100644 --- a/ui/model/keymap_test.go +++ b/ui/model/keymap_test.go @@ -19,7 +19,9 @@ var mainKeyPath = []string{"handleKey", "handleGlobalKey", "handleMainKey"} // modalKeyHandlers own the keys while their modal is open. They are not part of // a command mode, so the registry drift guard does not apply to them. var modalKeyHandlers = map[string]bool{ - "handleLuaSelectKey": true, + "handleLuaSelectKey": true, + "handleLuaInputKey": true, + "handleActionPaneKey": true, } // focusKeyHandlers maps the handlers that handleKey calls for a focused area diff --git a/ui/model/keys.go b/ui/model/keys.go index e5db50e94..c4f3c28be 100644 --- a/ui/model/keys.go +++ b/ui/model/keys.go @@ -190,6 +190,13 @@ func normalizeShiftedLetter(msg tea.KeyPressMsg) tea.KeyPressMsg { func (m *Model) handleKey(msg tea.KeyPressMsg) tea.Cmd { msg = normalizeShiftedLetter(msg) + if m.luaInput != nil { + m.handleLuaInputKey(msg) + return nil + } + if m.actionPane.visible { + return m.handleActionPaneKey(msg) + } if m.luaSelect != nil { m.handleLuaSelectKey(msg) return nil @@ -418,6 +425,8 @@ func (m *Model) handleProviderPaneKey(msg tea.KeyPressMsg) tea.Cmd { if _, ok := m.provider.(provider.ChatFilter); ok { return m.startChatPicker() } + case "!": + m.openActionPane() } return nil } @@ -834,6 +843,9 @@ func (m *Model) handleMainKey(msg tea.KeyPressMsg) tea.Cmd { case "?": m.openKeymap() + case "!": + m.openActionPane() + default: if m.luaMgr != nil { m.luaMgr.EmitKey(msg.String()) diff --git a/ui/model/lua_input.go b/ui/model/lua_input.go new file mode 100644 index 000000000..5e41f05d9 --- /dev/null +++ b/ui/model/lua_input.go @@ -0,0 +1,101 @@ +package model + +import ( + "strings" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" +) + +// LuaInputMsg asks the UI to show a text input requested by a plugin. +// OnSubmit runs with the text the user typed; OnCancel runs on Esc. +type LuaInputMsg struct { + Title string + Placeholder string + Value string + OnSubmit func(text string) + OnCancel func() +} + +// luaInputState is the open plugin input. +type luaInputState struct { + title string + placeholder string + value string + cursor int + onSubmit func(string) + onCancel func() +} + +func (m *Model) openLuaInput(title, placeholder, value string, onSubmit func(string), onCancel func()) { + m.luaInput = &luaInputState{ + title: title, + placeholder: placeholder, + value: value, + cursor: len(value), + onSubmit: onSubmit, + onCancel: onCancel, + } +} + +// handleLuaInputKey drives the open input. It returns true when the key was +// consumed. +func (m *Model) handleLuaInputKey(msg tea.KeyPressMsg) bool { + input := m.luaInput + if input == nil { + return false + } + switch msg.String() { + case "esc": + m.luaInput = nil + if input.onCancel != nil { + input.onCancel() + } + case "enter": + text := strings.TrimSpace(input.value) + if text == "" { + return true + } + m.luaInput = nil + if input.onSubmit != nil { + input.onSubmit(text) + } + default: + if m.editText("lua-input", &input.value, msg) { + input.cursor = m.textInput.cursor + } + } + return true +} + +// renderLuaInput draws the input as a centered box over the frame. +func (m Model) renderLuaInput() string { + input := m.luaInput + if input == nil { + return "" + } + width := max(36, lipgloss.Width(input.title)+4) + width = min(width, max(20, m.layout.frameWidth-4)) + + shown := input.value + if input.cursor >= 0 && input.cursor <= len(shown) { + shown = shown[:input.cursor] + "ā–" + shown[input.cursor:] + } + if strings.TrimSpace(input.value) == "" && input.placeholder != "" { + shown = dimStyle.Render(input.placeholder) + } + + var b strings.Builder + b.WriteString(truncate(input.title, width-2)) + b.WriteString("\n\n") + b.WriteString("> " + truncate(shown, width-4)) + b.WriteString("\n\n") + b.WriteString(dimStyle.Render(" enter submit esc cancel")) + + return lipgloss.NewStyle(). + Border(lipgloss.RoundedBorder()). + BorderForeground(lipgloss.Color("240")). + Padding(0, 1). + Width(width). + Render(b.String()) +} diff --git a/ui/model/model.go b/ui/model/model.go index ef254a628..5db050051 100644 --- a/ui/model/model.go +++ b/ui/model/model.go @@ -319,6 +319,8 @@ type Model struct { panes *ui.PaneSet paneCache *paneCache luaSelect *luaSelectState + luaInput *luaInputState + actionPane actionPaneState artRef *artRef slotVis *slotVisualizers downloadsDirectory string diff --git a/ui/model/plugin_queue.go b/ui/model/plugin_queue.go index f98da95cd..cfae5346e 100644 --- a/ui/model/plugin_queue.go +++ b/ui/model/plugin_queue.go @@ -49,6 +49,12 @@ func (m *Model) handlePluginQueue(msg PluginQueueMsg) tea.Cmd { case "move": cmd, _ := m.moveTrack(msg.Index, msg.To) return cmd + + case "insert": + m.playlist.Insert(msg.Index, msg.Track) + m.normalizeQueueOverlay() + m.adjustScroll() + return m.rearmStalePreload() } return nil } diff --git a/ui/model/plugin_state.go b/ui/model/plugin_state.go index 4c0f05d1b..7d613c163 100644 --- a/ui/model/plugin_state.go +++ b/ui/model/plugin_state.go @@ -31,6 +31,8 @@ type PluginState struct { // the rows until the playlist changes, so a caller must not change // them. A state from PluginStateLoader always has a Queue. Queue func() []luaplugin.QueueEntry + // Provider is the provider and playlist context for cliamp.provider.current. + Provider luaplugin.ProviderInfo revision uint64 // the playlist revision at publish } @@ -51,6 +53,28 @@ func (m *Model) PluginStateLoader() func() PluginState { } } +// providerInfo describes the provider the user is browsing and the row under +// the cursor. The playlist is the one open in the provider pane, not the track +// that happens to play. +func (m *Model) providerInfo() luaplugin.ProviderInfo { + info := luaplugin.ProviderInfo{PlaylistID: m.activeProviderPlaylistID} + if m.provider != nil { + info.Name = m.provider.Name() + } + for _, row := range m.provPane.lists { + if row.ID == info.PlaylistID { + info.PlaylistName = row.Name + break + } + } + if m.provPane.cursor >= 0 && m.provPane.cursor < len(m.provPane.lists) { + row := m.provPane.lists[m.provPane.cursor] + info.SelectionID = row.ID + info.SelectionName = row.Name + } + return info +} + // publishPluginState stores the state that Lua plugins read. It makes a new // Queue only when the playlist revision changed. func (m *Model) publishPluginState() { @@ -70,6 +94,7 @@ func (m *Model) publishPluginState() { Count: m.playlist.Len(), Index: m.playlist.Index(), HasNext: m.playlist.HasNext(), + Provider: m.providerInfo(), revision: m.playlist.Revision(), } state.Track.Artist, state.Track.Title = m.resolveTrackDisplay(track) diff --git a/ui/model/update.go b/ui/model/update.go index d6e1ecacf..737af2610 100644 --- a/ui/model/update.go +++ b/ui/model/update.go @@ -113,6 +113,13 @@ func (m Model) update(msg tea.Msg) (tea.Model, tea.Cmd) { } return m, nil + case LuaInputMsg: + if prev := m.luaInput; prev != nil && prev.onCancel != nil { + prev.onCancel() + } + m.openLuaInput(msg.Title, msg.Placeholder, msg.Value, msg.OnSubmit, msg.OnCancel) + return m, nil + case tea.WindowSizeMsg: m.width = msg.Width m.height = msg.Height diff --git a/ui/model/view.go b/ui/model/view.go index bed74e09f..d7ee8ca12 100644 --- a/ui/model/view.go +++ b/ui/model/view.go @@ -268,6 +268,12 @@ func (m Model) View() tea.View { rendered := m.centerFrame(m.layout.frameStyle().Render(content)) rendered = ui.FitRect(rendered, m.layout.frameWidth, max(1, m.height)) + if box := m.renderActionPane(); box != "" { + rendered = overlayCentered(rendered, box, m.layout.frameWidth, m.height) + } + if box := m.renderLuaInput(); box != "" { + rendered = overlayCentered(rendered, box, m.layout.frameWidth, m.height) + } if box := m.renderLuaSelect(); box != "" { rendered = overlayCentered(rendered, box, m.layout.frameWidth, m.height) } From c3e296d78f5384192fa6657d9ac3f4eeded46065 Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 03:32:54 -0300 Subject: [PATCH 09/28] fix(plugins): keep action order unspecified and reject non-object params --- luaplugin/api_action.go | 4 ++-- luaplugin/api_provider.go | 6 ++++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/luaplugin/api_action.go b/luaplugin/api_action.go index 8028383e2..ee194e0d2 100644 --- a/luaplugin/api_action.go +++ b/luaplugin/api_action.go @@ -113,8 +113,8 @@ func (m *Manager) addAction(action Action) error { return nil } -// Actions returns the actions registered for key, in load order. The slice is -// a copy; the caller can sort or filter it. +// Actions returns the actions registered for key. The slice is a copy and the +// order is unspecified; the caller sorts or filters it. func (m *Manager) Actions(key string) []Action { m.mu.RLock() defer m.mu.RUnlock() diff --git a/luaplugin/api_provider.go b/luaplugin/api_provider.go index 891616f2a..6b2dd2f93 100644 --- a/luaplugin/api_provider.go +++ b/luaplugin/api_provider.go @@ -81,9 +81,11 @@ func (m *Manager) registerProviderAPI(L *lua.LState, cliamp *lua.LTable, p *Plug if !ok { return pushErr(L, "cliamp.provider.call: params must be a table") } - if converted, ok := luaToGo(table).(map[string]any); ok { - params = converted + converted, ok := luaToGo(table).(map[string]any) + if !ok { + return pushErr(L, "cliamp.provider.call: params must be a table with string keys") } + params = converted } pp := m.provider.Load() if pp == nil || pp.Call == nil { From a55e874a512dbc04c174fd84c72f192440a9f016 Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 03:51:05 -0300 Subject: [PATCH 10/28] fix(plugins): close the action pane review gaps Classify provider writes by verb so mixed-case provider names cannot skip provider-send, drop provider completions once shutdown starts, keep the playlist position when the first track is inserted, and remove actions left by a plugin that fails to load. Keep entries intact while filtering the action pane, let j and k be typed in its filter, and normalize URL tracks inserted by a plugin. The generic bot plugin now serializes requests per chat and keeps waiting for audio after an interim text reply. Add regression tests for the empty insert, the filter, the stream flag, the mixed-case permission check and the failed-load cleanup. --- luaplugin/api_action_test.go | 12 +++++++ luaplugin/api_provider.go | 17 +++++++-- luaplugin/api_provider_test.go | 23 +++++++++++++ luaplugin/luaplugin.go | 5 +++ playlist/playlist.go | 2 +- playlist/playlist_test.go | 9 +++++ plugins/telegram-bot.lua | 63 +++++++++++++++++++++++++++++++--- ui/model/action_pane.go | 11 +++--- ui/model/action_pane_test.go | 22 ++++++++++++ ui/model/plugin_queue.go | 1 + ui/model/plugin_queue_test.go | 10 ++++++ 11 files changed, 161 insertions(+), 14 deletions(-) diff --git a/luaplugin/api_action_test.go b/luaplugin/api_action_test.go index 599f22c42..6c40a1b60 100644 --- a/luaplugin/api_action_test.go +++ b/luaplugin/api_action_test.go @@ -16,3 +16,15 @@ func TestActionRegisters(t *testing.T) { t.Fatalf("action = %#v", actions[0]) } } + +func TestFailedPluginActionsRemoved(t *testing.T) { + m := newTestManager() + loadTestPluginExpectError(t, m, "bad-action", ` + local p = plugin.register({name = "bad-action", type = "hook", permissions = {"ui"}}) + p:action{key = "!", id = "ghost", label = "Ghost", on_submit = function() end} + error("boom") + `) + if got := m.Actions("!"); len(got) != 0 { + t.Fatalf("actions = %#v, want none after a failed load", got) + } +} diff --git a/luaplugin/api_provider.go b/luaplugin/api_provider.go index 6b2dd2f93..6ac981eea 100644 --- a/luaplugin/api_provider.go +++ b/luaplugin/api_provider.go @@ -27,10 +27,16 @@ type ProviderProvider struct { } // providerWrites reports whether an action changes the remote account. Write -// actions need permissions = {"provider-send"}; reads need "provider". +// actions need permissions = {"provider-send"}; reads need "provider". The +// check looks at the verb, so "Telegram.send" and "telegram.SEND" cannot +// bypass the permission by changing the provider or verb case. func providerWrites(action string) bool { - switch action { - case "telegram.send", "telegram.ask", "telegram.reply", "telegram.callback": + _, verb, ok := strings.Cut(action, ".") + if !ok { + return false + } + switch strings.ToLower(verb) { + case "send", "ask", "reply", "callback", "send_inline", "add_chat": return true } return false @@ -131,6 +137,11 @@ func (m *Manager) runProviderCall(p *Plugin, call func(context.Context, string, defer cancel() result, err := call(ctx, action, params) label := "provider.call " + action + m.mu.RLock() + defer m.mu.RUnlock() + if m.closing { + return + } m.enqueue(p, label, func() { m.call(p, label, hookTimeout, 0, func(L *lua.LState) (*lua.LFunction, []lua.LValue) { if err != nil { diff --git a/luaplugin/api_provider_test.go b/luaplugin/api_provider_test.go index c532d1f91..8977290c0 100644 --- a/luaplugin/api_provider_test.go +++ b/luaplugin/api_provider_test.go @@ -141,3 +141,26 @@ func TestProviderCallAsyncReply(t *testing.T) { t.Fatal("the on_reply callback never ran") } } + +func TestProviderCallWriteRejectsMixedCaseAction(t *testing.T) { + m := newTestManager() + m.SetProviderProvider(ProviderProvider{ + Call: func(context.Context, string, map[string]any) (map[string]any, error) { + t.Fatal("the call should not run without provider-send") + return nil, nil + }, + }) + loadTestPlugin(t, m, "provider-mixed", ` + local p = plugin.register({name = "provider-mixed", type = "hook", permissions = {"provider"}}) + local ok, err = cliamp.provider.call("Telegram.send", {chat = "u:1:2", text = "/start"}) + _G.ok = ok + _G.err = err + `) + p := m.plugins[0] + if p.L.GetGlobal("ok") != lua.LNil { + t.Error("call should return nil") + } + if got := p.L.GetGlobal("err").String(); !strings.Contains(got, "provider-send") { + t.Errorf("err = %q", got) + } +} diff --git a/luaplugin/luaplugin.go b/luaplugin/luaplugin.go index 8ed7752aa..3288d99cd 100644 --- a/luaplugin/luaplugin.go +++ b/luaplugin/luaplugin.go @@ -400,6 +400,11 @@ func (m *Manager) cleanupPlugin(p *Plugin) { delete(m.names, name) } } + for key, action := range m.actions { + if action.Plugin == p.installName { + delete(m.actions, key) + } + } for event, hooks := range m.hooks { m.hooks[event] = filterOutPlugin(hooks, p) } diff --git a/playlist/playlist.go b/playlist/playlist.go index 068512be2..7eccb4521 100644 --- a/playlist/playlist.go +++ b/playlist/playlist.go @@ -246,7 +246,7 @@ func (p *Playlist) Insert(index int, track Track) { p.order = append(p.order, 0) copy(p.order[insertAt+1:], p.order[insertAt:]) p.order[insertAt] = index - if !p.shuffle && index <= p.pos { + if !p.shuffle && len(p.tracks) > 1 && index <= p.pos { p.pos++ } for i, idx := range p.queue { diff --git a/playlist/playlist_test.go b/playlist/playlist_test.go index b198b68f0..b863ff81c 100644 --- a/playlist/playlist_test.go +++ b/playlist/playlist_test.go @@ -843,3 +843,12 @@ func TestInsertRemapsThePlayNextQueue(t *testing.T) { t.Fatalf("queue entry = %#v, want C at 3", entries[0]) } } + +func TestInsertIntoEmptyPlaylistKeepsCurrentAtZero(t *testing.T) { + p := New() + p.ReplaceAt(nil, 0) + p.Insert(0, Track{Title: "A"}) + if _, idx := p.Current(); idx != 0 { + t.Fatalf("current index = %d, want 0", idx) + } +} diff --git a/plugins/telegram-bot.lua b/plugins/telegram-bot.lua index 264bd8651..3a1ac8279 100644 --- a/plugins/telegram-bot.lua +++ b/plugins/telegram-bot.lua @@ -36,21 +36,65 @@ local function current_chat() return chat, name end -local function add_reply(reply, err) +local busy = {} + +local function finish(chat) + busy[chat] = nil +end + +local function insert_audio(reply) + if reply and reply.kind == "audio" and reply.track then + cliamp.queue.insert(0, reply.track) + cliamp.message("Added: " .. reply.track.title, 5) + return true + end + return false +end + +local function wait_audio(chat, afterID) + cliamp.provider.call("telegram.reply", { + chat = chat, + after = afterID, + timeout = 20, + audio_only = true, + }, { + on_reply = function(reply, err) + if not insert_audio(reply) then + if err then + cliamp.message("Telegram: " .. tostring(err), 8) + else + cliamp.message("No audio yet. Ctrl+R to reload.", 5) + end + end + finish(chat) + end, + timeout = 30, + }) +end + +local function add_reply(chat, reply, err, waitForAudio) if not reply then cliamp.message("Telegram: " .. tostring(err or "no reply"), 8) + finish(chat) return end - if reply.kind == "audio" and reply.track then - cliamp.queue.insert(0, reply.track) - cliamp.message("Added: " .. reply.track.title, 5) + if insert_audio(reply) then + finish(chat) return end if reply.kind == "text" then cliamp.message(reply.text, 8) + if waitForAudio and reply.message_id and reply.message_id > 0 then + -- The bot often sends "Downloading..." first and the audio after + -- WaitReply's grace period. Keep waiting for the audio. + wait_audio(chat, reply.message_id) + else + finish(chat) + end return end cliamp.message("No reply yet. Ctrl+R to reload.", 5) + finish(chat) end p:action{ @@ -69,16 +113,25 @@ p:action{ title = "Message → " .. (name or chat), placeholder = "/search ...", on_submit = function(text) + if busy[chat] then + cliamp.message("Wait for the bot to finish this chat first.", 6) + return + end + busy[chat] = true cliamp.message("Sent. Waiting for the bot…", 3) + local waitForAudio = text:sub(1, 1) ~= "/" local ok, err = cliamp.provider.call("telegram.ask", { chat = chat, text = text, timeout = 60, }, { - on_reply = add_reply, + on_reply = function(reply, replyErr) + add_reply(chat, reply, replyErr, waitForAudio) + end, timeout = 90, }) if not ok then + finish(chat) cliamp.message("Send failed: " .. tostring(err), 8) end end, diff --git a/ui/model/action_pane.go b/ui/model/action_pane.go index c3dec0c92..ec53b7698 100644 --- a/ui/model/action_pane.go +++ b/ui/model/action_pane.go @@ -33,7 +33,7 @@ func (m *Model) openActionPane() { if m.provider != nil { providerName = m.provider.Name() } - available := entries[:0] + available := make([]luaplugin.Action, 0, len(entries)) for _, action := range entries { if action.Provider == "" || strings.EqualFold(action.Provider, providerName) { available = append(available, action) @@ -64,7 +64,7 @@ func (m *Model) handleActionPaneKey(msg tea.KeyPressMsg) tea.Cmd { case "esc": m.actionPane = actionPaneState{} return nil - case "up", "k": + case "up": if pane.cursor > 0 { pane.cursor-- } else { @@ -72,7 +72,7 @@ func (m *Model) handleActionPaneKey(msg tea.KeyPressMsg) tea.Cmd { } pane.adjustScroll() return nil - case "down", "j": + case "down": if pane.cursor < len(pane.filtered)-1 { pane.cursor++ } else { @@ -124,13 +124,14 @@ func (m *Model) filterActions() { if query == "" { pane.filtered = pane.entries } else { - pane.filtered = pane.filtered[:0] + filtered := make([]luaplugin.Action, 0, len(pane.entries)) for _, action := range pane.entries { text := strings.ToLower(action.Label + " " + action.Description + " " + action.Plugin) if strings.Contains(text, query) { - pane.filtered = append(pane.filtered, action) + filtered = append(filtered, action) } } + pane.filtered = filtered } pane.cursor = 0 pane.scroll = 0 diff --git a/ui/model/action_pane_test.go b/ui/model/action_pane_test.go index 9433fa2df..9287ac628 100644 --- a/ui/model/action_pane_test.go +++ b/ui/model/action_pane_test.go @@ -114,3 +114,25 @@ end t.Fatalf("filtered = %#v", m.actionPane.filtered) } } + +func TestActionPaneFilterKeepsEntries(t *testing.T) { + m := Model{} + m.actionPane = actionPaneState{ + entries: []luaplugin.Action{ + {Label: "Alpha"}, + {Label: "Beta"}, + {Label: "Gamma"}, + }, + } + m.actionPane.filtered = m.actionPane.entries + m.actionPane.query = "beta" + m.filterActions() + if len(m.actionPane.filtered) != 1 || m.actionPane.filtered[0].Label != "Beta" { + t.Fatalf("filtered = %#v", m.actionPane.filtered) + } + m.actionPane.query = "" + m.filterActions() + if len(m.actionPane.filtered) != 3 || m.actionPane.filtered[0].Label != "Alpha" { + t.Fatalf("cleared filter = %#v", m.actionPane.filtered) + } +} diff --git a/ui/model/plugin_queue.go b/ui/model/plugin_queue.go index cfae5346e..afe73600d 100644 --- a/ui/model/plugin_queue.go +++ b/ui/model/plugin_queue.go @@ -51,6 +51,7 @@ func (m *Model) handlePluginQueue(msg PluginQueueMsg) tea.Cmd { return cmd case "insert": + msg.Track.Stream = msg.Track.Stream || playlist.IsURL(msg.Track.Path) m.playlist.Insert(msg.Index, msg.Track) m.normalizeQueueOverlay() m.adjustScroll() diff --git a/ui/model/plugin_queue_test.go b/ui/model/plugin_queue_test.go index e32782910..1de619992 100644 --- a/ui/model/plugin_queue_test.go +++ b/ui/model/plugin_queue_test.go @@ -94,3 +94,13 @@ func TestAppendsCountAlbumHeaders(t *testing.T) { }) } } + +func TestPluginQueueInsertNormalizesStream(t *testing.T) { + p := playlist.New() + m := Model{player: &playbackFakeEngine{}, playlist: p} + m.Update(PluginQueueMsg{Op: "insert", Index: 0, Track: playlist.Track{Path: "https://example.com/live"}}) + tracks := p.Tracks() + if len(tracks) != 1 || !tracks[0].Stream { + t.Fatalf("tracks = %#v, want one stream track", tracks) + } +} From e2017bf76c7bc95b595c18defea121f2d1d48b8f Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 03:59:00 -0300 Subject: [PATCH 11/28] fix(plugin): show the latest text when the audio wait ends --- plugins/telegram-bot.lua | 2 ++ 1 file changed, 2 insertions(+) diff --git a/plugins/telegram-bot.lua b/plugins/telegram-bot.lua index 3a1ac8279..781e14846 100644 --- a/plugins/telegram-bot.lua +++ b/plugins/telegram-bot.lua @@ -62,6 +62,8 @@ local function wait_audio(chat, afterID) if not insert_audio(reply) then if err then cliamp.message("Telegram: " .. tostring(err), 8) + elseif reply and reply.kind == "text" and reply.text and reply.text ~= "" then + cliamp.message(reply.text, 8) else cliamp.message("No audio yet. Ctrl+R to reload.", 5) end From b862c580200ef94442fa37102bb1316e5c6c6eb4 Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 04:20:20 -0300 Subject: [PATCH 12/28] fix(plugins): finish the action-layer review Guard action dispatch and provider completions against shutdown, retain completions when the plugin queue is full, and apply the documented timeout to synchronous provider calls. The bot plugin now guards the ask command with the same per-chat busy state and documents that slash commands do not wait for delayed audio. Size the action pane from the terminal height, give the selector priority over the action pane, keep the playlist cursor and album-header state after an insert, and add regression tests for these paths. --- luaplugin/api_action.go | 5 +++++ luaplugin/api_provider.go | 10 +++------- luaplugin/api_provider_test.go | 19 +++++++++++++++++++ luaplugin/hooks.go | 28 ++++++++++++++++++++++++++++ luaplugin/hooks_test.go | 15 +++++++++++++++ plugins/telegram-bot.lua | 14 ++++++++++++-- ui/model/action_pane.go | 8 +++++++- ui/model/action_pane_test.go | 10 ++++++++++ ui/model/keys.go | 6 +++--- ui/model/plugin_queue.go | 4 ++++ ui/model/plugin_queue_test.go | 14 ++++++++++++++ ui/model/view.go | 4 ++-- 12 files changed, 122 insertions(+), 15 deletions(-) create mode 100644 luaplugin/hooks_test.go diff --git a/luaplugin/api_action.go b/luaplugin/api_action.go index ee194e0d2..ca1d83302 100644 --- a/luaplugin/api_action.go +++ b/luaplugin/api_action.go @@ -82,6 +82,11 @@ func (m *Manager) registerActionAPI(L *lua.LState, obj *lua.LTable, p *Plugin) { Prompt: strings.TrimSpace(rawString(L, opts, "prompt")), run: func(text string) { label := "action " + id + m.mu.RLock() + defer m.mu.RUnlock() + if m.closing { + return + } m.enqueue(p, label, func() { m.call(p, label, hookTimeout, 0, fixedArgs(fn, lua.LString(text))) }) diff --git a/luaplugin/api_provider.go b/luaplugin/api_provider.go index 6ac981eea..dd0eb20bc 100644 --- a/luaplugin/api_provider.go +++ b/luaplugin/api_provider.go @@ -117,7 +117,8 @@ func (m *Manager) registerProviderAPI(L *lua.LState, cliamp *lua.LTable, p *Plug return 1 } - ctx := callContext(L) + ctx, cancel := context.WithTimeout(callContext(L), timeout) + defer cancel() result, err := pp.Call(ctx, action, params) if err != nil { return pushErr(L, err.Error()) @@ -137,12 +138,7 @@ func (m *Manager) runProviderCall(p *Plugin, call func(context.Context, string, defer cancel() result, err := call(ctx, action, params) label := "provider.call " + action - m.mu.RLock() - defer m.mu.RUnlock() - if m.closing { - return - } - m.enqueue(p, label, func() { + m.enqueueCompletion(p, label, func() { m.call(p, label, hookTimeout, 0, func(L *lua.LState) (*lua.LFunction, []lua.LValue) { if err != nil { return fn, []lua.LValue{lua.LNil, lua.LString(err.Error())} diff --git a/luaplugin/api_provider_test.go b/luaplugin/api_provider_test.go index 8977290c0..e213942c7 100644 --- a/luaplugin/api_provider_test.go +++ b/luaplugin/api_provider_test.go @@ -164,3 +164,22 @@ func TestProviderCallWriteRejectsMixedCaseAction(t *testing.T) { t.Errorf("err = %q", got) } } + +func TestProviderCallSyncUsesTimeout(t *testing.T) { + m := newTestManager() + m.SetProviderProvider(ProviderProvider{ + Call: func(ctx context.Context, action string, params map[string]any) (map[string]any, error) { + <-ctx.Done() + return nil, ctx.Err() + }, + }) + loadTestPlugin(t, m, "provider-timeout", ` + local p = plugin.register({name = "provider-timeout", type = "hook", permissions = {"provider"}}) + local res, err = cliamp.provider.call("telegram.commands", {chat = "u:1:2"}, {timeout = 0.05}) + _G.err = err + `) + p := m.plugins[0] + if got := p.L.GetGlobal("err").String(); !strings.Contains(got, "deadline exceeded") { + t.Errorf("err = %q", got) + } +} diff --git a/luaplugin/hooks.go b/luaplugin/hooks.go index 98129e9e2..545b26fb8 100644 --- a/luaplugin/hooks.go +++ b/luaplugin/hooks.go @@ -204,6 +204,34 @@ func (m *Manager) enqueue(p *Plugin, label string, fn func()) bool { } } +// enqueueCompletion delivers an asynchronous provider completion without +// dropping it when the plugin queue is full. It holds m.mu only for the +// non-blocking send, so Close cannot close the queue underneath the send. The +// caller already returned true to Lua, so losing the completion would leave a +// plugin waiting forever. +func (m *Manager) enqueueCompletion(p *Plugin, label string, fn func()) bool { + for { + m.mu.RLock() + if m.closing { + m.mu.RUnlock() + return false + } + select { + case p.queue <- fn: + p.dropping.Store(false) + m.mu.RUnlock() + return true + default: + m.mu.RUnlock() + } + select { + case <-m.ctx.Done(): + return false + case <-time.After(50 * time.Millisecond): + } + } +} + // runQueue runs the queued calls of p one at a time until Close closes the // queue. Thus the events and key presses of one plugin keep their order. When // Close sets dropQueued, it drops the calls that still wait. diff --git a/luaplugin/hooks_test.go b/luaplugin/hooks_test.go new file mode 100644 index 000000000..f4094ca40 --- /dev/null +++ b/luaplugin/hooks_test.go @@ -0,0 +1,15 @@ +package luaplugin + +import "testing" + +func TestEnqueueCompletionWaitsForQueueSpace(t *testing.T) { + m := newTestManager() + p := &Plugin{installName: "completion", queue: make(chan func(), 1)} + p.queue <- func() {} + done := make(chan bool, 1) + go func() { done <- m.enqueueCompletion(p, "completion", func() {}) }() + <-p.queue + if !<-done { + t.Fatal("enqueueCompletion did not deliver the completion") + } +} diff --git a/plugins/telegram-bot.lua b/plugins/telegram-bot.lua index 781e14846..14ee18a10 100644 --- a/plugins/telegram-bot.lua +++ b/plugins/telegram-bot.lua @@ -6,8 +6,13 @@ -- that answers a text command with an audio document works without code -- changes. -- --- The action appears under "!" when the Telegram provider is open. The --- p:command("ask") form is for scripts and the MCP: +-- The action appears under "!" when the Telegram provider is open. +-- A plain text query keeps waiting for the audio after an interim +-- "downloading" reply. Slash commands are treated as menu commands and do not +-- wait for delayed audio; use a plain query if the bot sends the audio after a +-- slash-command reply. +-- +-- The p:command("ask") form is for scripts and the MCP: -- -- cliamp plugins call telegram-bot ask /search daft punk @@ -163,11 +168,16 @@ p:command("ask", function(args) if not chat or chat == "" or text == "" then return "usage: ask " end + if busy[chat] then + return "busy: wait for the bot to finish this chat" + end + busy[chat] = true local reply, err = cliamp.provider.call("telegram.ask", { chat = chat, text = text, timeout = 60, }) + busy[chat] = nil if not reply then return "error: " .. tostring(err) end diff --git a/ui/model/action_pane.go b/ui/model/action_pane.go index ec53b7698..71bcdf65e 100644 --- a/ui/model/action_pane.go +++ b/ui/model/action_pane.go @@ -20,6 +20,7 @@ type actionPaneState struct { cursor int scroll int query string + height int } // openActionPane collects the actions registered for "!" and shows them. @@ -54,6 +55,7 @@ func (m *Model) openActionPane() { visible: true, entries: entries, filtered: entries, + height: m.height, } } @@ -113,7 +115,11 @@ func (p *actionPaneState) adjustScroll() { } func (p *actionPaneState) visibleRows() int { - return 10 + if p.height <= 0 { + return 10 + } + const chrome = 9 // heading, query, footer, blanks and borders + return max(1, min(10, p.height-chrome)) } // filterActions keeps the actions whose label, description or plugin contains diff --git a/ui/model/action_pane_test.go b/ui/model/action_pane_test.go index 9287ac628..ad236141a 100644 --- a/ui/model/action_pane_test.go +++ b/ui/model/action_pane_test.go @@ -136,3 +136,13 @@ func TestActionPaneFilterKeepsEntries(t *testing.T) { t.Fatalf("cleared filter = %#v", m.actionPane.filtered) } } + +func TestActionPaneVisibleRowsFitsHeight(t *testing.T) { + cases := map[int]int{0: 10, 10: 1, 15: 6, 55: 10} + for height, want := range cases { + pane := actionPaneState{height: height} + if got := pane.visibleRows(); got != want { + t.Fatalf("height %d: visibleRows = %d, want %d", height, got, want) + } + } +} diff --git a/ui/model/keys.go b/ui/model/keys.go index c4f3c28be..2fdf05533 100644 --- a/ui/model/keys.go +++ b/ui/model/keys.go @@ -194,13 +194,13 @@ func (m *Model) handleKey(msg tea.KeyPressMsg) tea.Cmd { m.handleLuaInputKey(msg) return nil } - if m.actionPane.visible { - return m.handleActionPaneKey(msg) - } if m.luaSelect != nil { m.handleLuaSelectKey(msg) return nil } + if m.actionPane.visible { + return m.handleActionPaneKey(msg) + } if cmd, ok := m.handleGlobalKey(msg); ok { return cmd diff --git a/ui/model/plugin_queue.go b/ui/model/plugin_queue.go index afe73600d..1599435ba 100644 --- a/ui/model/plugin_queue.go +++ b/ui/model/plugin_queue.go @@ -52,7 +52,11 @@ func (m *Model) handlePluginQueue(msg PluginQueueMsg) tea.Cmd { case "insert": msg.Track.Stream = msg.Track.Stream || playlist.IsURL(msg.Track.Path) + if m.plCursor >= 0 && msg.Index <= m.plCursor && m.plCursor < m.playlist.Len() { + m.plCursor++ + } m.playlist.Insert(msg.Index, msg.Track) + m.recountHeaderState(m.playlist.Tracks()) m.normalizeQueueOverlay() m.adjustScroll() return m.rearmStalePreload() diff --git a/ui/model/plugin_queue_test.go b/ui/model/plugin_queue_test.go index 1de619992..ad8208fed 100644 --- a/ui/model/plugin_queue_test.go +++ b/ui/model/plugin_queue_test.go @@ -104,3 +104,17 @@ func TestPluginQueueInsertNormalizesStream(t *testing.T) { t.Fatalf("tracks = %#v, want one stream track", tracks) } } + +func TestPluginQueueInsertKeepsSelectionAndHeaderState(t *testing.T) { + p := playlist.New() + p.Replace([]playlist.Track{{Title: "A", Path: "a.mp3"}, {Title: "B", Path: "b.mp3"}}) + m := Model{player: &playbackFakeEngine{}, playlist: p, plCursor: 1} + next, _ := m.Update(PluginQueueMsg{Op: "insert", Index: 0, Track: playlist.Track{Title: "X", Path: "x.mp3"}}) + got := next.(Model) + if got.plCursor != 2 { + t.Fatalf("plCursor = %d, want 2", got.plCursor) + } + if got.headerTracks != 3 { + t.Fatalf("headerTracks = %d, want 3", got.headerTracks) + } +} diff --git a/ui/model/view.go b/ui/model/view.go index d7ee8ca12..ab646ec00 100644 --- a/ui/model/view.go +++ b/ui/model/view.go @@ -271,10 +271,10 @@ func (m Model) View() tea.View { if box := m.renderActionPane(); box != "" { rendered = overlayCentered(rendered, box, m.layout.frameWidth, m.height) } - if box := m.renderLuaInput(); box != "" { + if box := m.renderLuaSelect(); box != "" { rendered = overlayCentered(rendered, box, m.layout.frameWidth, m.height) } - if box := m.renderLuaSelect(); box != "" { + if box := m.renderLuaInput(); box != "" { rendered = overlayCentered(rendered, box, m.layout.frameWidth, m.height) } view := tea.NewView(rendered) From 3cf26d97e000ca15d50f2dde0ceaf127d41e95b0 Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 04:24:11 -0300 Subject: [PATCH 13/28] fix(providers): let the reply wait honor audio_only --- lua_wiring.go | 10 +++++++++- lua_wiring_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/lua_wiring.go b/lua_wiring.go index 896062605..6f131113a 100644 --- a/lua_wiring.go +++ b/lua_wiring.go @@ -259,7 +259,15 @@ func waitReplyResult(ctx context.Context, commander provider.ChatCommander, chat if seconds, ok := params["timeout"].(float64); ok && seconds > 0 { timeout = time.Duration(seconds * float64(time.Second)) } - reply, err := commander.WaitReply(ctx, chat, after, timeout) + var ( + reply provider.ChatReply + err error + ) + if audioOnly, _ := params["audio_only"].(bool); audioOnly { + reply, err = commander.WaitAudio(ctx, chat, after, timeout) + } else { + reply, err = commander.WaitReply(ctx, chat, after, timeout) + } if err != nil { return nil, err } diff --git a/lua_wiring_test.go b/lua_wiring_test.go index 887149142..6999b3f14 100644 --- a/lua_wiring_test.go +++ b/lua_wiring_test.go @@ -1,6 +1,7 @@ package main import ( + "context" "reflect" "testing" "time" @@ -10,6 +11,7 @@ import ( "github.com/bjarneo/cliamp/internal/playback" "github.com/bjarneo/cliamp/luaplugin" "github.com/bjarneo/cliamp/playlist" + "github.com/bjarneo/cliamp/provider" "github.com/bjarneo/cliamp/ui/model" ) @@ -194,3 +196,33 @@ func TestLuaStateProviderReadsPublishedState(t *testing.T) { t.Errorf("queue of a state with no Queue = %#v, want nil", got) } } + +type fakeChatCommander struct { + provider.ChatCommander + replyCalled bool + audioCalled bool +} + +func (f *fakeChatCommander) WaitReply(context.Context, string, int, time.Duration) (provider.ChatReply, error) { + f.replyCalled = true + return provider.ChatReply{Kind: "text"}, nil +} + +func (f *fakeChatCommander) WaitAudio(context.Context, string, int, time.Duration) (provider.ChatReply, error) { + f.audioCalled = true + return provider.ChatReply{Kind: "audio"}, nil +} + +func TestWaitReplyResultHonorsAudioOnly(t *testing.T) { + f := &fakeChatCommander{} + out, err := waitReplyResult(context.Background(), f, "u:1:2", 5, map[string]any{"audio_only": true}) + if err != nil { + t.Fatalf("waitReplyResult: %v", err) + } + if f.replyCalled || !f.audioCalled { + t.Fatalf("reply=%v audio=%v, want only WaitAudio", f.replyCalled, f.audioCalled) + } + if out["kind"] != "audio" { + t.Fatalf("kind = %v", out["kind"]) + } +} From 46362acc736f9fd93a167853333f2072997f1659 Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 04:53:13 -0300 Subject: [PATCH 14/28] fix(plugins): harden the action review follow-ups Make the full-queue completion test deterministic, expire per-chat busy state so a canceled command cannot block the chat forever, and route Ctrl+C to the quit handler before the plugin modal handlers. --- luaplugin/hooks_test.go | 21 ++++++++++++++++++--- plugins/telegram-bot.lua | 26 ++++++++++++++++++++++---- ui/model/keys.go | 3 +++ 3 files changed, 43 insertions(+), 7 deletions(-) diff --git a/luaplugin/hooks_test.go b/luaplugin/hooks_test.go index f4094ca40..3185db174 100644 --- a/luaplugin/hooks_test.go +++ b/luaplugin/hooks_test.go @@ -1,6 +1,9 @@ package luaplugin -import "testing" +import ( + "testing" + "time" +) func TestEnqueueCompletionWaitsForQueueSpace(t *testing.T) { m := newTestManager() @@ -8,8 +11,20 @@ func TestEnqueueCompletionWaitsForQueueSpace(t *testing.T) { p.queue <- func() {} done := make(chan bool, 1) go func() { done <- m.enqueueCompletion(p, "completion", func() {}) }() + + select { + case <-done: + t.Fatal("enqueueCompletion delivered while the queue was full") + case <-time.After(100 * time.Millisecond): + } + <-p.queue - if !<-done { - t.Fatal("enqueueCompletion did not deliver the completion") + select { + case ok := <-done: + if !ok { + t.Fatal("enqueueCompletion did not deliver the completion") + } + case <-time.After(time.Second): + t.Fatal("enqueueCompletion did not retry after the queue had space") } } diff --git a/plugins/telegram-bot.lua b/plugins/telegram-bot.lua index 14ee18a10..907318fff 100644 --- a/plugins/telegram-bot.lua +++ b/plugins/telegram-bot.lua @@ -43,6 +43,24 @@ end local busy = {} +local function is_busy(chat) + local untilTime = busy[chat] + if not untilTime then + return false + end + if untilTime <= os.time() then + busy[chat] = nil + return false + end + return true +end + +local function set_busy(chat) + -- Longer than the 60s ask plus the 30s audio follow-up. A canceled + -- command cannot run its cleanup, so the deadline is the safety net. + busy[chat] = os.time() + 180 +end + local function finish(chat) busy[chat] = nil end @@ -120,11 +138,11 @@ p:action{ title = "Message → " .. (name or chat), placeholder = "/search ...", on_submit = function(text) - if busy[chat] then + if is_busy(chat) then cliamp.message("Wait for the bot to finish this chat first.", 6) return end - busy[chat] = true + set_busy(chat) cliamp.message("Sent. Waiting for the bot…", 3) local waitForAudio = text:sub(1, 1) ~= "/" local ok, err = cliamp.provider.call("telegram.ask", { @@ -168,10 +186,10 @@ p:command("ask", function(args) if not chat or chat == "" or text == "" then return "usage: ask " end - if busy[chat] then + if is_busy(chat) then return "busy: wait for the bot to finish this chat" end - busy[chat] = true + set_busy(chat) local reply, err = cliamp.provider.call("telegram.ask", { chat = chat, text = text, diff --git a/ui/model/keys.go b/ui/model/keys.go index 2fdf05533..7174d9ad9 100644 --- a/ui/model/keys.go +++ b/ui/model/keys.go @@ -190,6 +190,9 @@ func normalizeShiftedLetter(msg tea.KeyPressMsg) tea.KeyPressMsg { func (m *Model) handleKey(msg tea.KeyPressMsg) tea.Cmd { msg = normalizeShiftedLetter(msg) + if msg.String() == "ctrl+c" { + return m.quit() + } if m.luaInput != nil { m.handleLuaInputKey(msg) return nil From a7b53ad979386417c31762dbed4acfed9811dc0f Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 05:19:18 -0300 Subject: [PATCH 15/28] fix(plugins): refresh action-pane height on resize and token the busy state Resizing the terminal now updates the action pane's row budget and clamps its scroll before layout. Each chat reservation carries a request token, so a canceled or stale completion cannot clear a newer reservation. --- plugins/telegram-bot.lua | 55 ++++++++++++++++++++++-------------- ui/model/action_pane_test.go | 19 +++++++++++++ ui/model/update.go | 4 +++ 3 files changed, 57 insertions(+), 21 deletions(-) diff --git a/plugins/telegram-bot.lua b/plugins/telegram-bot.lua index 907318fff..3782d905d 100644 --- a/plugins/telegram-bot.lua +++ b/plugins/telegram-bot.lua @@ -42,26 +42,39 @@ local function current_chat() end local busy = {} +local requestSeq = 0 local function is_busy(chat) - local untilTime = busy[chat] - if not untilTime then + local entry = busy[chat] + if not entry then return false end - if untilTime <= os.time() then + if entry.untilTime <= os.time() then busy[chat] = nil return false end return true end -local function set_busy(chat) +local function reserve(chat) + if is_busy(chat) then + return nil + end + requestSeq = requestSeq + 1 -- Longer than the 60s ask plus the 30s audio follow-up. A canceled -- command cannot run its cleanup, so the deadline is the safety net. - busy[chat] = os.time() + 180 + busy[chat] = {token = requestSeq, untilTime = os.time() + 180} + return requestSeq end -local function finish(chat) +local function finish(chat, token) + local entry = busy[chat] + if not entry then + return + end + if token and entry.token ~= token then + return + end busy[chat] = nil end @@ -74,7 +87,7 @@ local function insert_audio(reply) return false end -local function wait_audio(chat, afterID) +local function wait_audio(chat, afterID, token) cliamp.provider.call("telegram.reply", { chat = chat, after = afterID, @@ -91,20 +104,20 @@ local function wait_audio(chat, afterID) cliamp.message("No audio yet. Ctrl+R to reload.", 5) end end - finish(chat) + finish(chat, token) end, timeout = 30, }) end -local function add_reply(chat, reply, err, waitForAudio) +local function add_reply(chat, reply, err, waitForAudio, token) if not reply then cliamp.message("Telegram: " .. tostring(err or "no reply"), 8) - finish(chat) + finish(chat, token) return end if insert_audio(reply) then - finish(chat) + finish(chat, token) return end if reply.kind == "text" then @@ -112,14 +125,14 @@ local function add_reply(chat, reply, err, waitForAudio) if waitForAudio and reply.message_id and reply.message_id > 0 then -- The bot often sends "Downloading..." first and the audio after -- WaitReply's grace period. Keep waiting for the audio. - wait_audio(chat, reply.message_id) + wait_audio(chat, reply.message_id, token) else - finish(chat) + finish(chat, token) end return end cliamp.message("No reply yet. Ctrl+R to reload.", 5) - finish(chat) + finish(chat, token) end p:action{ @@ -138,11 +151,11 @@ p:action{ title = "Message → " .. (name or chat), placeholder = "/search ...", on_submit = function(text) - if is_busy(chat) then + local token = reserve(chat) + if not token then cliamp.message("Wait for the bot to finish this chat first.", 6) return end - set_busy(chat) cliamp.message("Sent. Waiting for the bot…", 3) local waitForAudio = text:sub(1, 1) ~= "/" local ok, err = cliamp.provider.call("telegram.ask", { @@ -151,12 +164,12 @@ p:action{ timeout = 60, }, { on_reply = function(reply, replyErr) - add_reply(chat, reply, replyErr, waitForAudio) + add_reply(chat, reply, replyErr, waitForAudio, token) end, timeout = 90, }) if not ok then - finish(chat) + finish(chat, token) cliamp.message("Send failed: " .. tostring(err), 8) end end, @@ -186,16 +199,16 @@ p:command("ask", function(args) if not chat or chat == "" or text == "" then return "usage: ask " end - if is_busy(chat) then + local token = reserve(chat) + if not token then return "busy: wait for the bot to finish this chat" end - set_busy(chat) local reply, err = cliamp.provider.call("telegram.ask", { chat = chat, text = text, timeout = 60, }) - busy[chat] = nil + finish(chat, token) if not reply then return "error: " .. tostring(err) end diff --git a/ui/model/action_pane_test.go b/ui/model/action_pane_test.go index ad236141a..1240326ef 100644 --- a/ui/model/action_pane_test.go +++ b/ui/model/action_pane_test.go @@ -146,3 +146,22 @@ func TestActionPaneVisibleRowsFitsHeight(t *testing.T) { } } } + +func TestActionPaneResizeClampsScroll(t *testing.T) { + m := Model{} + m.actionPane = actionPaneState{ + visible: true, + entries: []luaplugin.Action{{Label: "One"}, {Label: "Two"}, {Label: "Three"}}, + filtered: []luaplugin.Action{{Label: "One"}, {Label: "Two"}, {Label: "Three"}}, + cursor: 2, + height: 55, + } + next, _ := m.Update(tea.WindowSizeMsg{Width: 80, Height: 10}) + got := next.(Model) + if got.actionPane.height != 10 { + t.Fatalf("height = %d, want 10", got.actionPane.height) + } + if got.actionPane.scroll != 2 { + t.Fatalf("scroll = %d, want 2", got.actionPane.scroll) + } +} diff --git a/ui/model/update.go b/ui/model/update.go index 737af2610..67431b49f 100644 --- a/ui/model/update.go +++ b/ui/model/update.go @@ -123,6 +123,10 @@ func (m Model) update(msg tea.Msg) (tea.Model, tea.Cmd) { case tea.WindowSizeMsg: m.width = msg.Width m.height = msg.Height + if m.actionPane.visible { + m.actionPane.height = msg.Height + m.actionPane.adjustScroll() + } m.recomputeLayout() m.normalizeMainFocus() m.clampActiveScrollState() From 3871d9d0f71bdfc84c009bd07459a98cde4582fe Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 03:12:22 -0300 Subject: [PATCH 16/28] feat(plugins): add live inputs, rich selectors and text panels Add ui.suggestions, table rows with subtitles and images to select and input, on_change and on_select callbacks, and ui.text. The input can become a live search or a command palette without closing; selectors can show a body and covers. Wire the Telegram inline and message actions through the provider API, keep long option lists scrollable, and add tests for the new UI messages. Document the richer UI API and the new Telegram actions. --- docs/plugins.md | 46 ++++++-- docs/telegram.md | 9 +- lua_wiring.go | 152 +++++++++++++++++++++----- luaplugin/api_ui.go | 120 +++++++++++++++++++-- luaplugin/api_ui_test.go | 98 +++++++++++++++++ luaplugin/luaplugin.go | 21 +++- ui/model/action_pane.go | 4 +- ui/model/image_pulse.go | 16 +++ ui/model/keymap_test.go | 1 + ui/model/keys.go | 4 + ui/model/lua_input.go | 216 +++++++++++++++++++++++++++++++++++-- ui/model/lua_input_test.go | 87 +++++++++++++++ ui/model/lua_modal.go | 120 +++++++++++++++------ ui/model/lua_text.go | 140 ++++++++++++++++++++++++ ui/model/lua_text_test.go | 32 ++++++ ui/model/model.go | 1 + ui/model/update.go | 19 +++- ui/model/view.go | 7 ++ 18 files changed, 1005 insertions(+), 88 deletions(-) create mode 100644 luaplugin/api_ui_test.go create mode 100644 ui/model/image_pulse.go create mode 100644 ui/model/lua_input_test.go create mode 100644 ui/model/lua_text.go create mode 100644 ui/model/lua_text_test.go diff --git a/docs/plugins.md b/docs/plugins.md index c386b5e1e..108b7ebe7 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -475,7 +475,9 @@ budget, so a waiting call from a key binding needs `on_reply`. Telegram actions at this layer are `telegram.commands` (the commands a bot advertises), `telegram.send` (send text and return the message id), `telegram.ask` (send and wait for the reply), `telegram.reply` (wait for the -next message after an id), and `telegram.callback` (press an inline button). +next message after an id), `telegram.callback` (press an inline button), +`telegram.message` (re-read one message), `telegram.inline` (ask an inline bot +for results) and `telegram.send_inline` (send one of those results). ### cliamp.http @@ -741,8 +743,13 @@ panes. ```lua cliamp.ui.select{ - title = "Which visualizer?", - options = { "Bars", "Scatter", "None" }, + title = "Track", + body = "2:34 Ā· 7 options", -- optional text above the list + options = { + "Bars", -- title only + {title = "Get Lucky", subtitle = "Daft Punk", description = "3:09", + image = "/tmp/cover.png"}, -- optional image path or URL + }, cursor = 2, -- optional, 1-based on_select = function(index) ... end, on_cancel = function() ... end, -- optional, Esc @@ -751,21 +758,46 @@ cliamp.ui.select{ Returns true when the request was accepted. With no interactive UI (headless mode) it returns an error. Closing the selector calls `on_cancel` when given, or -`on_select(-1)` otherwise. +`on_select(-1)` otherwise. A table row can carry `title`, `subtitle`, +`description` and `image`; the image is rendered with the terminal's image +protocol when it supports one, and ignored otherwise. ```lua cliamp.ui.input{ title = "Message", - placeholder = "/search ...", + placeholder = "song, artist or link", value = "", -- optional + suggestions = { -- optional, same row shape as select + {title = "/start", description = "Start the bot"}, + }, + on_change = function(text) ... end, -- optional, every edit + on_select = function(index) ... end, -- optional, Enter on a live row on_submit = function(text) ... end, on_cancel = function() ... end, -- optional, Esc } ``` `ui.input` asks for one line of text. `Enter` calls `on_submit` with the text; -`Esc` calls `on_cancel` when given. It returns true when the request was -accepted; headless mode returns an error. +`Esc` calls `on_cancel` when given. `on_change` runs on every edit and +`on_select` runs when `Enter` picks a live suggestion. It returns true when the +request was accepted; headless mode returns an error. + +While an input is open, `cliamp.ui.suggestions(options, {live = true})` replaces +the list under it. This is how a plugin turns the input into a live search or a +command palette. `live = true` (the default) marks the rows as results: `Enter` +selects one and calls `on_select` instead of submitting the typed text. +`live = false` makes them plain suggestions again, so `Enter` submits the text. + +```lua +cliamp.ui.text{ + title = "Bot reply", + text = "long text ...", + on_close = function() ... end, -- optional +} +``` + +`ui.text` opens a scrollable read-only panel. `↑`/`↓`, `PageUp`/`PageDown`, +`Home`/`End` scroll it; `Esc` or `q` closes it and calls `on_close`. ### cliamp.vis diff --git a/docs/telegram.md b/docs/telegram.md index e10d574c0..10a99a5ca 100644 --- a/docs/telegram.md +++ b/docs/telegram.md @@ -111,10 +111,11 @@ screen, desktop widgets) as a `data:` URL. A chat with a bot is a normal playlist: the provider lists its audio documents and plays them. A plugin can also write into that chat: send a command as the -signed-in user, wait for the bot's reply, or press an inline button. The write -actions live in the plugin API (`cliamp.provider.call`), not in a fixed key, so -the plugin decides the prompt and how to show the reply. See -[Plugins](plugins.md) and the bundled `telegram-bot.lua`. +signed-in user, wait for the bot's reply, press an inline button, or ask an +inline bot for results and send one. The write actions live in the plugin API +(`cliamp.provider.call`), not in a fixed key, so the plugin decides the prompt +and how to show the reply. See [Plugins](plugins.md) and the bundled +`telegram-bot.lua`. Writes use the same MTProto session as reads and act as the signed-in user. A bot sees a normal message from you; a command sent to a group is visible to diff --git a/lua_wiring.go b/lua_wiring.go index 6f131113a..cb68f9637 100644 --- a/lua_wiring.go +++ b/lua_wiring.go @@ -148,8 +148,10 @@ func luaUIProvider(send func(tea.Msg), headless bool) luaplugin.UIProvider { ShowMessage: func(text string, duration time.Duration) { send(model.ShowStatusMsg{Text: text, Duration: duration}) }, - ShowSelect: showSelectFor(send, headless), - ShowInput: showInputFor(send, headless), + ShowSelect: showSelectFor(send, headless), + ShowInput: showInputFor(send, headless), + UpdateInput: updateInputFor(send, headless), + ShowText: showTextFor(send, headless), SetVis: func(name string) { send(model.SetVisMsg{Name: name}) }, @@ -159,21 +161,48 @@ func luaUIProvider(send func(tea.Msg), headless bool) luaplugin.UIProvider { // showSelectFor returns nil in headless mode: there is no UI to answer a // selector, and the API reports it as unavailable instead of accepting a // request nobody can complete. -func showInputFor(send func(tea.Msg), headless bool) func(string, string, string, func(string), func()) { +func showTextFor(send func(tea.Msg), headless bool) func(string, string, func()) { if headless { return nil } - return func(title, placeholder, value string, onSubmit func(string), onCancel func()) { - send(model.LuaInputMsg{Title: title, Placeholder: placeholder, Value: value, OnSubmit: onSubmit, OnCancel: onCancel}) + return func(title, text string, onClose func()) { + send(model.LuaTextMsg{Title: title, Text: text, OnClose: onClose}) } } -func showSelectFor(send func(tea.Msg), headless bool) func(string, []string, int, func(int), func()) { +func showInputFor(send func(tea.Msg), headless bool) func(string, string, string, []luaplugin.SelectOption, func(string), func(string), func(int), func()) { if headless { return nil } - return func(title string, options []string, cursor int, onDone func(index int), onCancel func()) { - send(model.LuaSelectMsg{Title: title, Options: options, Cursor: cursor, OnDone: onDone, OnCancel: onCancel}) + return func(title, placeholder, value string, suggestions []luaplugin.SelectOption, onChange, onSubmit func(string), onSelect func(int), onCancel func()) { + send(model.LuaInputMsg{ + Title: title, + Placeholder: placeholder, + Value: value, + Suggestions: suggestions, + OnChange: onChange, + OnSubmit: onSubmit, + OnSelect: onSelect, + OnCancel: onCancel, + }) + } +} + +func updateInputFor(send func(tea.Msg), headless bool) func([]luaplugin.SelectOption, bool) { + if headless { + return nil + } + return func(options []luaplugin.SelectOption, live bool) { + send(model.LuaInputSuggestionsMsg{Options: options, Live: live}) + } +} + +func showSelectFor(send func(tea.Msg), headless bool) func(string, string, []luaplugin.SelectOption, int, func(int), func()) { + if headless { + return nil + } + return func(title, body string, options []luaplugin.SelectOption, cursor int, onDone func(index int), onCancel func()) { + send(model.LuaSelectMsg{Title: title, Body: body, Options: options, Cursor: cursor, OnDone: onDone, OnCancel: onCancel}) } } @@ -238,6 +267,50 @@ func luaProviderProvider(entries []provider.Entry, load func() model.PluginState return waitReplyResult(ctx, commander, chat, id, params) case "reply": return waitReplyResult(ctx, commander, chat, intParam(params, "after"), params) + case "inline": + bot := stringParam(params, "bot") + if bot == "" { + bot = chat + } + inline, err := commander.InlineResults(ctx, chat, bot, stringParam(params, "query"), stringParam(params, "offset")) + if err != nil { + return nil, err + } + rows := make([]any, 0, len(inline.Results)) + for _, result := range inline.Results { + rows = append(rows, map[string]any{ + "id": result.ID, + "type": result.Type, + "kind": result.Kind, + "title": result.Title, + "description": result.Description, + "url": result.URL, + "thumb_url": result.ThumbURL, + }) + } + return map[string]any{ + // Lua 5.1 numbers are float64 and cannot hold a 64-bit + // query id exactly. Keep it a string across the boundary. + "query_id": fmt.Sprintf("%d", inline.QueryID), + "next_offset": inline.NextOffset, + "results": rows, + }, nil + case "send_inline": + bot := stringParam(params, "bot") + if bot == "" { + bot = chat + } + id, err := commander.SendInlineResult(ctx, chat, bot, int64Param(params, "query_id"), stringParam(params, "result_id")) + if err != nil { + return nil, err + } + return map[string]any{"id": id}, nil + case "message": + reply, err := commander.Message(ctx, chat, intParam(params, "message_id")) + if err != nil { + return nil, err + } + return replyResult(reply), nil case "callback": data, err := base64.StdEncoding.DecodeString(stringParam(params, "data_b64")) if err != nil { @@ -254,25 +327,8 @@ func luaProviderProvider(entries []provider.Entry, load func() model.PluginState } } -func waitReplyResult(ctx context.Context, commander provider.ChatCommander, chat string, after int, params map[string]any) (map[string]any, error) { - timeout := 20 * time.Second - if seconds, ok := params["timeout"].(float64); ok && seconds > 0 { - timeout = time.Duration(seconds * float64(time.Second)) - } - var ( - reply provider.ChatReply - err error - ) - if audioOnly, _ := params["audio_only"].(bool); audioOnly { - reply, err = commander.WaitAudio(ctx, chat, after, timeout) - } else { - reply, err = commander.WaitReply(ctx, chat, after, timeout) - } - if err != nil { - return nil, err - } +func replyResult(reply provider.ChatReply) map[string]any { out := map[string]any{ - "id": after, "kind": reply.Kind, "text": reply.Text, "from": reply.From, @@ -281,6 +337,9 @@ func waitReplyResult(ctx context.Context, commander provider.ChatCommander, chat if reply.Kind == "audio" { out["track"] = luaplugin.TrackData(pluginTrackFromPlaylist(reply.Track)) } + if len(reply.Links) > 0 { + out["links"] = reply.Links + } if len(reply.Buttons) > 0 { buttons := make([]any, 0, len(reply.Buttons)) for _, button := range reply.Buttons { @@ -288,6 +347,9 @@ func waitReplyResult(ctx context.Context, commander provider.ChatCommander, chat if len(button.Data) > 0 { row["data_b64"] = base64.StdEncoding.EncodeToString(button.Data) } + if button.DataText != "" { + row["data_text"] = button.DataText + } if button.URL != "" { row["url"] = button.URL } @@ -298,6 +360,28 @@ func waitReplyResult(ctx context.Context, commander provider.ChatCommander, chat } out["buttons"] = buttons } + return out +} + +func waitReplyResult(ctx context.Context, commander provider.ChatCommander, chat string, after int, params map[string]any) (map[string]any, error) { + timeout := 20 * time.Second + if seconds, ok := params["timeout"].(float64); ok && seconds > 0 { + timeout = time.Duration(seconds * float64(time.Second)) + } + var ( + reply provider.ChatReply + err error + ) + if audioOnly, _ := params["audio_only"].(bool); audioOnly { + reply, err = commander.WaitAudio(ctx, chat, after, timeout) + } else { + reply, err = commander.WaitReply(ctx, chat, after, timeout) + } + if err != nil { + return nil, err + } + out := replyResult(reply) + out["id"] = after return out, nil } @@ -321,6 +405,22 @@ func stringParam(params map[string]any, key string) string { return value } +func int64Param(params map[string]any, key string) int64 { + switch value := params[key].(type) { + case float64: + return int64(value) + case int64: + return value + case int: + return int64(value) + case string: + var out int64 + fmt.Sscan(value, &out) + return out + } + return 0 +} + func intParam(params map[string]any, key string) int { switch value := params[key].(type) { case float64: diff --git a/luaplugin/api_ui.go b/luaplugin/api_ui.go index f6910b379..4125a1108 100644 --- a/luaplugin/api_ui.go +++ b/luaplugin/api_ui.go @@ -7,6 +7,42 @@ import ( lua "github.com/yuin/gopher-lua" ) +// parseSelectOptions reads a list of select rows. A row is a string (title +// only) or a table with title, subtitle and description. The same shape works +// for select options and input suggestions. +func parseSelectOptions(L *lua.LState, value lua.LValue) []SelectOption { + list, ok := value.(*lua.LTable) + if !ok { + return nil + } + var out []SelectOption + list.ForEach(func(_, value lua.LValue) { + switch item := value.(type) { + case lua.LString: + if text := strings.TrimSpace(string(item)); text != "" { + out = append(out, SelectOption{Title: text}) + } + case *lua.LTable: + title := strings.TrimSpace(rawString(L, item, "title")) + if title == "" { + title = strings.TrimSpace(rawString(L, item, "label")) + } + if title == "" { + title = strings.TrimSpace(rawString(L, item, "value")) + } + if title != "" { + out = append(out, SelectOption{ + Title: title, + Subtitle: strings.TrimSpace(rawString(L, item, "subtitle")), + Description: strings.TrimSpace(rawString(L, item, "description")), + Image: rawString(L, item, "image"), + }) + } + } + }) + return out +} + // registerUIAPI adds cliamp.ui.select. It lets a plugin ask the user to pick // one of several strings, which is the piece a plugin needs to build its own // settings menu: choose a visualizer, a weight, a layout pane, and so on. @@ -25,12 +61,7 @@ func registerUIAPI(L *lua.LState, cliamp *lua.LTable, p *Plugin, m *Manager) { if !ok { return pushErr(L, "cliamp.ui.select: on_select is required") } - var options []string - if list, ok := opts.RawGetString("options").(*lua.LTable); ok { - list.ForEach(func(_, value lua.LValue) { - options = append(options, value.String()) - }) - } + options := parseSelectOptions(L, opts.RawGetString("options")) if len(options) == 0 { return pushErr(L, "cliamp.ui.select: options is empty") } @@ -48,7 +79,8 @@ func registerUIAPI(L *lua.LState, cliamp *lua.LTable, p *Plugin, m *Manager) { }) } } - up.ShowSelect(title, options, cursor, func(index int) { + body := rawString(L, opts, "body") + up.ShowSelect(title, body, options, cursor, func(index int) { if index < 0 { return } @@ -80,6 +112,7 @@ func registerUIAPI(L *lua.LState, cliamp *lua.LTable, p *Plugin, m *Manager) { title := strings.TrimSpace(rawString(L, opts, "title")) placeholder := strings.TrimSpace(rawString(L, opts, "placeholder")) value := rawString(L, opts, "value") + suggestions := parseSelectOptions(L, opts.RawGetString("suggestions")) cancelFn, _ := opts.RawGetString("on_cancel").(*lua.LFunction) onCancel := func() {} if cancelFn != nil { @@ -89,11 +122,80 @@ func registerUIAPI(L *lua.LState, cliamp *lua.LTable, p *Plugin, m *Manager) { }) } } - up.ShowInput(title, placeholder, value, func(text string) { + onChangeFn, _ := opts.RawGetString("on_change").(*lua.LFunction) + onChange := func(text string) {} + if onChangeFn != nil { + onChange = func(text string) { + m.enqueue(p, "ui.input change", func() { + m.call(p, "ui.input change", hookTimeout, 0, fixedArgs(onChangeFn, lua.LString(text))) + }) + } + } + onSelectFn, _ := opts.RawGetString("on_select").(*lua.LFunction) + onSelect := func(index int) {} + if onSelectFn != nil { + onSelect = func(index int) { + m.enqueue(p, "ui.input select", func() { + m.call(p, "ui.input select", hookTimeout, 0, fixedArgs(onSelectFn, lua.LNumber(index+1))) + }) + } + } + up.ShowInput(title, placeholder, value, suggestions, onChange, func(text string) { m.enqueue(p, "ui.input", func() { m.call(p, "ui.input", hookTimeout, 0, fixedArgs(fn, lua.LString(text))) }) - }, onCancel) + }, onSelect, onCancel) + L.Push(lua.LTrue) + return 1 + })) + + // cliamp.ui.suggestions(options, {live = true}) replaces the list under the + // open input. live rows are results: Enter selects one instead of + // submitting the text. + L.SetField(tbl, "suggestions", L.NewFunction(func(L *lua.LState) int { + if !p.permitted(PermUI, "cliamp.ui.suggestions") { + return pushErr(L, "ui permission required") + } + options := parseSelectOptions(L, L.Get(1)) + live := true + if opts, ok := L.Get(2).(*lua.LTable); ok { + if value, ok := opts.RawGetString("live").(lua.LBool); ok { + live = bool(value) + } + } + up := m.ui.Load() + if up == nil || up.UpdateInput == nil { + return pushErr(L, "ui: not available") + } + up.UpdateInput(options, live) + L.Push(lua.LTrue) + return 1 + })) + + // cliamp.ui.text{title = "...", text = "...", on_close = fn} + L.SetField(tbl, "text", L.NewFunction(func(L *lua.LState) int { + if !p.permitted(PermUI, "cliamp.ui.text") { + return pushErr(L, "ui permission required") + } + opts := L.CheckTable(1) + text := rawString(L, opts, "text") + if strings.TrimSpace(text) == "" { + return pushErr(L, "cliamp.ui.text: text is required") + } + up := m.ui.Load() + if up == nil || up.ShowText == nil { + return pushErr(L, "ui: not available") + } + closeFn, _ := opts.RawGetString("on_close").(*lua.LFunction) + onClose := func() {} + if closeFn != nil { + onClose = func() { + m.enqueue(p, "ui.text close", func() { + m.call(p, "ui.text close", hookTimeout, 0, fixedArgs(closeFn)) + }) + } + } + up.ShowText(strings.TrimSpace(rawString(L, opts, "title")), text, onClose) L.Push(lua.LTrue) return 1 })) diff --git a/luaplugin/api_ui_test.go b/luaplugin/api_ui_test.go new file mode 100644 index 000000000..80c045060 --- /dev/null +++ b/luaplugin/api_ui_test.go @@ -0,0 +1,98 @@ +package luaplugin + +import "testing" + +func TestUIInputPassesSuggestions(t *testing.T) { + m := newTestManager() + var got []SelectOption + m.SetUIProvider(UIProvider{ + ShowInput: func(_ string, _, _ string, suggestions []SelectOption, _ func(string), onSubmit func(string), _ func(int), _ func()) { + got = suggestions + onSubmit("x") + }, + }) + loadTestPlugin(t, m, "input-suggestions", ` + local p = plugin.register({name = "input-suggestions", type = "hook", permissions = {"ui"}}) + cliamp.ui.input{ + title = "Message", + suggestions = {"/start", {value = "/help", description = "How to use"}}, + on_submit = function(text) end, + } + `) + if len(got) != 2 { + t.Fatalf("suggestions = %#v", got) + } + if got[0].Title != "/start" || got[0].Description != "" { + t.Errorf("suggestion 0 = %#v", got[0]) + } + if got[1].Title != "/help" || got[1].Description != "How to use" { + t.Errorf("suggestion 1 = %#v", got[1]) + } +} + +func TestUITextPassesBody(t *testing.T) { + m := newTestManager() + var gotTitle, gotText string + m.SetUIProvider(UIProvider{ + ShowText: func(title, text string, _ func()) { + gotTitle, gotText = title, text + }, + }) + loadTestPlugin(t, m, "ui-text", ` + local p = plugin.register({name = "ui-text", type = "hook", permissions = {"ui"}}) + cliamp.ui.text{title = "Reply", text = "line one\nline two"} + `) + if gotTitle != "Reply" || gotText != "line one\nline two" { + t.Fatalf("title = %q text = %q", gotTitle, gotText) + } +} + +func TestUISelectPassesStructuredOptions(t *testing.T) { + m := newTestManager() + var got []SelectOption + m.SetUIProvider(UIProvider{ + ShowSelect: func(_, _ string, options []SelectOption, _ int, onDone func(int), _ func()) { + got = options + onDone(0) + }, + }) + loadTestPlugin(t, m, "ui-select", ` + local p = plugin.register({name = "ui-select", type = "hook", permissions = {"ui"}}) + cliamp.ui.select{ + title = "Results", + options = { + "/start", + {title = "Get Lucky", subtitle = "Artist: Daft Punk", description = "Album: Random Access Memories"}, + }, + on_select = function(index) end, + } + `) + if len(got) != 2 { + t.Fatalf("options = %#v", got) + } + if got[0].Title != "/start" { + t.Errorf("option 0 = %#v", got[0]) + } + if got[1].Title != "Get Lucky" || got[1].Subtitle != "Artist: Daft Punk" || got[1].Description != "Album: Random Access Memories" { + t.Errorf("option 1 = %#v", got[1]) + } +} + +func TestUISuggestionsPassesImage(t *testing.T) { + m := newTestManager() + var got []SelectOption + m.SetUIProvider(UIProvider{ + UpdateInput: func(options []SelectOption, live bool) { + got = options + }, + }) + loadTestPlugin(t, m, "ui-suggestions", ` + local p = plugin.register({name = "ui-suggestions", type = "hook", permissions = {"ui"}}) + cliamp.ui.suggestions({ + {title = "Get Lucky", subtitle = "Artist: Daft Punk", image = "IMAGE"}, + }, {live = true}) + `) + if len(got) != 1 || got[0].Image != "IMAGE" { + t.Fatalf("options = %#v", got) + } +} diff --git a/luaplugin/luaplugin.go b/luaplugin/luaplugin.go index 3288d99cd..3674cc92b 100644 --- a/luaplugin/luaplugin.go +++ b/luaplugin/luaplugin.go @@ -125,6 +125,18 @@ type ControlProvider struct { QueueInsert func(index int, track Track) // insert a track at index } +// SelectOption is one row of cliamp.ui.select. A plain string option uses +// Title only; a table can add the subtitle and description lines Telegram uses +// for a track: title, artist and album. +type SelectOption struct { + Title string + Subtitle string + Description string + // Image is a pre-rendered ANSI block, one image line per row. The plugin + // downloads and converts it; the core only lays it out. + Image string +} + // UIProvider supplies callbacks that surface plugin output in the TUI. // Not permission-gated — these are low-risk, output-only operations. Like // the ControlProvider funcs, ShowMessage must return at once. @@ -133,11 +145,16 @@ type UIProvider struct { // ShowSelect opens a selector with options and calls onDone with the chosen // index, or -1 when the user cancels. It must return at once; onDone runs on // the UI goroutine and the manager turns it into a plugin callback. - ShowSelect func(title string, options []string, cursor int, onDone func(index int), onCancel func()) + ShowSelect func(title, body string, options []SelectOption, cursor int, onDone func(index int), onCancel func()) // ShowInput opens a text input. It must return at once; onSubmit and // onCancel run on the UI goroutine and the manager turns them into plugin // callbacks. - ShowInput func(title, placeholder, value string, onSubmit func(text string), onCancel func()) + ShowInput func(title, placeholder, value string, suggestions []SelectOption, onChange func(text string), onSubmit func(text string), onSelect func(index int), onCancel func()) + // UpdateInput replaces the suggestions of the open input. live means the + // rows are search results that Enter selects, not command completions. + UpdateInput func(options []SelectOption, live bool) + // ShowText opens a scrollable text panel. It must return at once. + ShowText func(title, text string, onClose func()) // SetVis switches the active visualizer by name. It must return at once: the // UI applies the change on its own goroutine. SetVis func(name string) diff --git a/ui/model/action_pane.go b/ui/model/action_pane.go index 71bcdf65e..b536e0e81 100644 --- a/ui/model/action_pane.go +++ b/ui/model/action_pane.go @@ -89,9 +89,9 @@ func (m *Model) handleActionPaneKey(msg tea.KeyPressMsg) tea.Cmd { action := pane.filtered[pane.cursor] m.actionPane = actionPaneState{} if action.Prompt != "" { - m.openLuaInput(action.Prompt, "", "", func(text string) { + m.openLuaInput(action.Prompt, "", "", nil, nil, func(text string) { action.Run(text) - }, nil) + }, nil, nil) return nil } action.Run("") diff --git a/ui/model/image_pulse.go b/ui/model/image_pulse.go new file mode 100644 index 000000000..1f750f44c --- /dev/null +++ b/ui/model/image_pulse.go @@ -0,0 +1,16 @@ +package model + +// imagePulse alternates the invisible reset at the end of an image +// placeholder line. Bubble Tea redraws only the lines whose bytes changed; +// a static kitty placeholder would stop being re-emitted and the terminal +// would drop the image. The plugin panes solve this inside cliamp.image.block; +// the selector receives a pre-rendered block, so the core has to keep it +// alive on each frame. +var imagePulse bool + +func imageResetSuffix() string { + if imagePulse { + return "\x1b[0m" + } + return "\x1b[0;0m" +} diff --git a/ui/model/keymap_test.go b/ui/model/keymap_test.go index 6ae400dcd..622a968bd 100644 --- a/ui/model/keymap_test.go +++ b/ui/model/keymap_test.go @@ -21,6 +21,7 @@ var mainKeyPath = []string{"handleKey", "handleGlobalKey", "handleMainKey"} var modalKeyHandlers = map[string]bool{ "handleLuaSelectKey": true, "handleLuaInputKey": true, + "handleLuaTextKey": true, "handleActionPaneKey": true, } diff --git a/ui/model/keys.go b/ui/model/keys.go index 7174d9ad9..7abd1031a 100644 --- a/ui/model/keys.go +++ b/ui/model/keys.go @@ -193,6 +193,10 @@ func (m *Model) handleKey(msg tea.KeyPressMsg) tea.Cmd { if msg.String() == "ctrl+c" { return m.quit() } + if m.luaText != nil { + m.handleLuaTextKey(msg) + return nil + } if m.luaInput != nil { m.handleLuaInputKey(msg) return nil diff --git a/ui/model/lua_input.go b/ui/model/lua_input.go index 5e41f05d9..9b16c5aed 100644 --- a/ui/model/lua_input.go +++ b/ui/model/lua_input.go @@ -5,37 +5,89 @@ import ( tea "charm.land/bubbletea/v2" "charm.land/lipgloss/v2" + + "github.com/bjarneo/cliamp/luaplugin" ) // LuaInputMsg asks the UI to show a text input requested by a plugin. -// OnSubmit runs with the text the user typed; OnCancel runs on Esc. +// OnSubmit runs with the text the user typed; OnSelect runs with the 0-based +// index of a live result; OnCancel runs on Esc. type LuaInputMsg struct { Title string Placeholder string Value string + Suggestions []luaplugin.SelectOption + OnChange func(text string) OnSubmit func(text string) + OnSelect func(index int) OnCancel func() } +// LuaInputSuggestionsMsg replaces the suggestions under the open input. +// Live rows are search results: Enter selects one instead of submitting the +// text. +type LuaInputSuggestionsMsg struct { + Options []luaplugin.SelectOption + Live bool +} + // luaInputState is the open plugin input. type luaInputState struct { title string placeholder string value string cursor int + suggestions []luaplugin.SelectOption + filtered []luaplugin.SelectOption + live bool + choice int + onChange func(string) onSubmit func(string) + onSelect func(int) onCancel func() } -func (m *Model) openLuaInput(title, placeholder, value string, onSubmit func(string), onCancel func()) { +func (m *Model) openLuaInput(title, placeholder, value string, suggestions []luaplugin.SelectOption, onChange, onSubmit func(string), onSelect func(int), onCancel func()) { m.luaInput = &luaInputState{ title: title, placeholder: placeholder, value: value, cursor: len(value), + suggestions: suggestions, + onChange: onChange, onSubmit: onSubmit, + onSelect: onSelect, onCancel: onCancel, } + m.luaInput.filter() +} + +// filter keeps command suggestions that match a prefix. Live search results +// are already for the current text, so they are never filtered locally. +func (input *luaInputState) filter() { + if input.live { + input.filtered = input.suggestions + } else { + value := strings.TrimSpace(input.value) + input.filtered = nil + switch { + case value == "": + input.filtered = input.suggestions + case strings.HasPrefix(value, "/") && !strings.ContainsAny(value, " \t"): + prefix := strings.ToLower(value) + for _, suggestion := range input.suggestions { + if strings.HasPrefix(strings.ToLower(suggestion.Title), prefix) { + input.filtered = append(input.filtered, suggestion) + } + } + } + } + if input.choice >= len(input.filtered) { + input.choice = max(0, len(input.filtered)-1) + } + if input.choice < 0 { + input.choice = 0 + } } // handleLuaInputKey drives the open input. It returns true when the key was @@ -51,8 +103,36 @@ func (m *Model) handleLuaInputKey(msg tea.KeyPressMsg) bool { if input.onCancel != nil { input.onCancel() } + case "up": + if len(input.filtered) > 0 { + input.choice = (input.choice - 1 + len(input.filtered)) % len(input.filtered) + } + case "down": + if len(input.filtered) > 0 { + input.choice = (input.choice + 1) % len(input.filtered) + } + case "tab": + if !input.live && len(input.filtered) > 0 { + input.value = input.filtered[input.choice].Title + if strings.HasPrefix(input.value, "/") && !strings.HasSuffix(input.value, " ") { + input.value += " " + } + input.cursor = len(input.value) + input.filter() + } case "enter": + if input.live && len(input.filtered) > 0 { + index := input.choice + m.luaInput = nil + if input.onSelect != nil { + input.onSelect(index) + } + return true + } text := strings.TrimSpace(input.value) + if text == "" && len(input.filtered) > 0 { + text = input.filtered[input.choice].Title + } if text == "" { return true } @@ -63,18 +143,60 @@ func (m *Model) handleLuaInputKey(msg tea.KeyPressMsg) bool { default: if m.editText("lua-input", &input.value, msg) { input.cursor = m.textInput.cursor + // A live result belongs to the previous text. Clear it until the + // plugin sends the results for this query. + if input.live { + input.live = false + input.suggestions = nil + input.filtered = nil + input.choice = 0 + } else { + input.filter() + } + if input.onChange != nil { + input.onChange(input.value) + } } } return true } -// renderLuaInput draws the input as a centered box over the frame. +// inputRows is the number of lines one option needs in the input. +func imageLines(image string) []string { + if strings.TrimSpace(image) == "" { + return nil + } + return strings.Split(strings.TrimRight(image, "\n"), "\n") +} + +func inputRows(option luaplugin.SelectOption) int { + rows := len(imageLines(option.Image)) + 1 + if option.Subtitle != "" { + rows++ + } + if option.Description != "" { + rows++ + } + return rows +} + +// renderLuaInput draws the input and its command menu or live results as a +// centered box. func (m Model) renderLuaInput() string { input := m.luaInput if input == nil { return "" } - width := max(36, lipgloss.Width(input.title)+4) + width := max(40, lipgloss.Width(input.title)+4) + width = max(width, lipgloss.Width(input.placeholder)+8) + for _, suggestion := range input.filtered { + width = max(width, lipgloss.Width(suggestion.Title)+6) + width = max(width, lipgloss.Width(suggestion.Subtitle)+6) + width = max(width, lipgloss.Width(suggestion.Description)+6) + for _, line := range imageLines(suggestion.Image) { + width = max(width, lipgloss.Width(line)+4) + } + } width = min(width, max(20, m.layout.frameWidth-4)) shown := input.value @@ -82,15 +204,46 @@ func (m Model) renderLuaInput() string { shown = shown[:input.cursor] + "ā–" + shown[input.cursor:] } if strings.TrimSpace(input.value) == "" && input.placeholder != "" { - shown = dimStyle.Render(input.placeholder) + shown = dimStyle.Render(truncate(input.placeholder, width-4)) } var b strings.Builder b.WriteString(truncate(input.title, width-2)) b.WriteString("\n\n") b.WriteString("> " + truncate(shown, width-4)) + if len(input.filtered) > 0 { + b.WriteString("\n") + if input.live { + m.renderLiveInputRows(&b, input, width) + } else { + visible := min(5, len(input.filtered)) + start := 0 + if input.choice >= visible { + start = input.choice - visible + 1 + } + for i := start; i < start+visible; i++ { + suggestion := input.filtered[i] + prefix := " " + if i == input.choice { + prefix = "ā–ø " + } + line := prefix + suggestion.Title + if suggestion.Description != "" { + line += " " + dimStyle.Render(suggestion.Description) + } + b.WriteString("\n" + truncate(line, width-4)) + } + if start+visible < len(input.filtered) { + b.WriteString("\n" + dimStyle.Render(" ↓ more")) + } + } + } b.WriteString("\n\n") - b.WriteString(dimStyle.Render(" enter submit esc cancel")) + if input.live { + b.WriteString(dimStyle.Render(truncate(" enter select esc cancel", width-4))) + } else { + b.WriteString(dimStyle.Render(truncate(" tab complete enter esc", width-4))) + } return lipgloss.NewStyle(). Border(lipgloss.RoundedBorder()). @@ -99,3 +252,54 @@ func (m Model) renderLuaInput() string { Width(width). Render(b.String()) } + +// renderLiveInputRows writes the search rows under the input. The window +// keeps the selected row visible and counts the lines each row occupies. +func (m Model) renderLiveInputRows(b *strings.Builder, input *luaInputState, width int) { + maxRows := max(3, m.height-14) + start := max(0, min(input.choice, len(input.filtered)-1)) + rows := inputRows(input.filtered[start]) + for start > 0 && rows+inputRows(input.filtered[start-1]) <= maxRows { + start-- + rows += inputRows(input.filtered[start]) + } + end := start + rows = 0 + for end < len(input.filtered) && rows+inputRows(input.filtered[end]) <= maxRows { + rows += inputRows(input.filtered[end]) + end++ + } + if end <= input.choice { + end = min(len(input.filtered), input.choice+1) + if start > input.choice { + start = input.choice + } + } + if start > 0 { + b.WriteString(dimStyle.Render(" ↑ more")) + b.WriteString("\n") + } + for i := start; i < end; i++ { + option := input.filtered[i] + if i > start { + b.WriteString("\n") + } + for _, line := range imageLines(option.Image) { + b.WriteString(" " + line + imageResetSuffix() + "\n") + } + marker := " " + if i == input.choice { + marker = "ā–ø " + } + b.WriteString(marker + truncate(option.Title, width-6)) + if option.Subtitle != "" { + b.WriteString("\n " + dimStyle.Render(truncate(option.Subtitle, width-6))) + } + if option.Description != "" { + b.WriteString("\n " + dimStyle.Render(truncate(option.Description, width-6))) + } + } + if end < len(input.filtered) { + b.WriteString("\n" + dimStyle.Render(" ↓ more")) + } +} diff --git a/ui/model/lua_input_test.go b/ui/model/lua_input_test.go new file mode 100644 index 000000000..fc4b7479e --- /dev/null +++ b/ui/model/lua_input_test.go @@ -0,0 +1,87 @@ +package model + +import ( + "strings" + "testing" + + tea "charm.land/bubbletea/v2" + + "github.com/bjarneo/cliamp/luaplugin" +) + +func TestLuaInputFiltersAndCompletesCommands(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "", []luaplugin.SelectOption{ + {Title: "/start", Description: "Start"}, + {Title: "/settings", Description: "Settings"}, + {Title: "/help", Description: "Help"}, + }, nil, nil, nil, nil) + + if got := len(m.luaInput.filtered); got != 3 { + t.Fatalf("filtered = %d, want 3", got) + } + m.luaInput.value = "/s" + m.luaInput.filter() + if got := len(m.luaInput.filtered); got != 2 { + t.Fatalf("filtered for /s = %d, want 2", got) + } + m.luaInput.choice = 1 + m.handleLuaInputKey(tea.KeyPressMsg{Code: tea.KeyTab}) + if got := m.luaInput.value; got != "/settings " { + t.Fatalf("value after Tab = %q, want %q", got, "/settings ") + } +} + +func TestLuaInputHidesMenuForPlainText(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "", []luaplugin.SelectOption{{Title: "/start"}}, nil, nil, nil, nil) + m.luaInput.value = "get lucky" + m.luaInput.filter() + if got := len(m.luaInput.filtered); got != 0 { + t.Fatalf("filtered = %d, want 0", got) + } +} + +func TestLuaInputSelectsLiveResult(t *testing.T) { + m := Model{} + selected := -1 + m.openLuaInput("Message", "", "", nil, nil, nil, func(index int) { selected = index }, nil) + m.luaInput.suggestions = []luaplugin.SelectOption{ + {Title: "Get Lucky", Subtitle: "Artist: Daft Punk", Description: "Album: Random Access Memories"}, + } + m.luaInput.live = true + m.luaInput.filter() + m.handleLuaInputKey(tea.KeyPressMsg{Code: tea.KeyEnter}) + if selected != 0 { + t.Fatalf("selected = %d, want 0", selected) + } +} + +func TestLuaInputRendersImageLines(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "", nil, nil, nil, nil, nil) + m.luaInput.live = true + m.luaInput.suggestions = []luaplugin.SelectOption{{Title: "Get Lucky", Image: "IMG\nART"}} + m.luaInput.filter() + box := m.renderLuaInput() + if !strings.Contains(box, "IMG") || !strings.Contains(box, "ART") { + t.Fatalf("box does not contain the image lines:\n%s", box) + } +} + +func TestLuaInputSuggestionsKeepImage(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "", nil, nil, nil, nil, nil) + next, _ := m.Update(LuaInputSuggestionsMsg{ + Options: []luaplugin.SelectOption{{Title: "Get Lucky", Image: "IMG\nART"}}, + Live: true, + }) + got := next.(Model) + if len(got.luaInput.filtered) != 1 || got.luaInput.filtered[0].Image != "IMG\nART" { + t.Fatalf("input = %#v", got.luaInput) + } + box := got.renderLuaInput() + if !strings.Contains(box, "IMG") || !strings.Contains(box, "ART") { + t.Fatalf("box does not contain the image lines:\n%s", box) + } +} diff --git a/ui/model/lua_modal.go b/ui/model/lua_modal.go index d5e72b569..54167e794 100644 --- a/ui/model/lua_modal.go +++ b/ui/model/lua_modal.go @@ -7,13 +7,16 @@ import ( tea "charm.land/bubbletea/v2" "charm.land/lipgloss/v2" + + "github.com/bjarneo/cliamp/luaplugin" ) // LuaSelectMsg asks the UI to show a selector requested by a plugin. OnDone // runs with the chosen index, or -1 when the user cancels. type LuaSelectMsg struct { Title string - Options []string + Body string + Options []luaplugin.SelectOption // Cursor is the 1-based option to start on; 0 starts at the first one. Cursor int OnDone func(index int) @@ -29,7 +32,8 @@ type SetVisMsg struct { // luaSelectState is the open plugin selector. type luaSelectState struct { title string - options []string + body string + options []luaplugin.SelectOption cursor int onDone func(index int) onCancel func() @@ -66,60 +70,102 @@ func (m *Model) handleLuaSelectKey(msg tea.KeyPressMsg) bool { return true } -// renderLuaSelect draws the selector as a centered box over the frame. +// renderLuaSelect draws the selector as a centered box over the frame. An +// option can be one line or three: title, subtitle and description. func (m Model) renderLuaSelect() string { sel := m.luaSelect - if sel == nil { + if sel == nil || len(sel.options) == 0 { return "" } width := 0 for _, option := range sel.options { - width = max(width, lipgloss.Width(option)) + width = max(width, lipgloss.Width(oneLine(option.Title))) + width = max(width, lipgloss.Width(oneLine(option.Subtitle))) + width = max(width, lipgloss.Width(oneLine(option.Description))) + for _, line := range imageLines(option.Image) { + width = max(width, lipgloss.Width(line)+4) + } + } + for _, line := range wrapBlock(sel.body, 40) { + width = max(width, lipgloss.Width(line)) } - width = min(max(width+6, 24), max(20, m.layout.frameWidth-4)) + width = min(max(width+8, 40), max(20, m.layout.frameWidth-4)) title := truncate(sel.title, width-2) - // The list can be longer than the screen (the visualizer picker lists every - // mode). Show a window around the cursor so the selected option is always - // visible, with markers when there is more above or below. - // Title, blank line, options, up to two "more" indicators, blank line, - // footer and the box borders: keep the whole box inside the terminal. - visible := len(sel.options) - if maxRows := max(1, m.height-8); visible > maxRows { - visible = maxRows - } - start := 0 - if sel.cursor >= visible { - start = sel.cursor - visible + 1 - } - if end := start + visible; end > len(sel.options) { - start = max(0, len(sel.options)-visible) - } - end := min(start+visible, len(sel.options)) + bodyLines := wrapBlock(sel.body, width-4) + if maxBody := max(1, (m.height-10)/2); len(bodyLines) > maxBody { + bodyLines = append(bodyLines[:maxBody], "…") + } + + linesOf := func(option luaplugin.SelectOption) int { + lines := len(imageLines(option.Image)) + 1 + if option.Subtitle != "" { + lines++ + } + if option.Description != "" { + lines++ + } + return lines + } + maxRows := max(3, m.height-8-len(bodyLines)) + start := max(0, min(sel.cursor, len(sel.options)-1)) + rows := linesOf(sel.options[start]) + for start > 0 && rows+linesOf(sel.options[start-1]) <= maxRows { + start-- + rows += linesOf(sel.options[start]) + } + end := start + rows = 0 + for end < len(sel.options) && rows+linesOf(sel.options[end]) <= maxRows { + rows += linesOf(sel.options[end]) + end++ + } + if end <= sel.cursor { + end = min(len(sel.options), sel.cursor+1) + if start > sel.cursor { + start = sel.cursor + } + } var b strings.Builder b.WriteString(title) b.WriteString("\n\n") + for _, line := range bodyLines { + b.WriteString(truncate(line, width-4)) + b.WriteString("\n") + } + if len(bodyLines) > 0 { + b.WriteString("\n") + } if start > 0 { b.WriteString(dimStyle.Render(" ↑ ") + truncate(fmt.Sprintf("%d more", start), width-6)) b.WriteString("\n") } for i := start; i < end; i++ { - option := truncate(sel.options[i], width-4) - line := " " + option + option := sel.options[i] + if i > start { + b.WriteString("\n") + } + for _, line := range imageLines(option.Image) { + b.WriteString(" " + line + imageResetSuffix() + "\n") + } + marker := " " if i == sel.cursor { - line = "ā–ø " + option + marker = "ā–ø " } - b.WriteString(line) - if i < end-1 || end < len(sel.options) { - b.WriteString("\n") + b.WriteString(marker + truncate(oneLine(option.Title), width-6)) + if option.Subtitle != "" { + b.WriteString("\n " + dimStyle.Render(truncate(oneLine(option.Subtitle), width-6))) + } + if option.Description != "" { + b.WriteString("\n " + dimStyle.Render(truncate(oneLine(option.Description), width-6))) } } if end < len(sel.options) { - b.WriteString(dimStyle.Render(" ↓ ") + truncate(fmt.Sprintf("%d more", len(sel.options)-end), width-6)) + b.WriteString("\n" + dimStyle.Render(" ↓ ") + truncate(fmt.Sprintf("%d more", len(sel.options)-end), width-6)) } b.WriteString("\n\n") - b.WriteString(dimStyle.Render(" ↑/↓ move enter select esc cancel")) + b.WriteString(dimStyle.Render(" ↑/↓ move enter esc")) box := lipgloss.NewStyle(). Border(lipgloss.RoundedBorder()). @@ -130,6 +176,18 @@ func (m Model) renderLuaSelect() string { return box } +// oneLine folds the line breaks a plugin may put in an option. A selector +// counts options, not rendered lines, so an embedded newline would make the +// box taller than the terminal and hide the rows below. +func oneLine(s string) string { + return strings.Map(func(r rune) rune { + if r == '\n' || r == '\r' || r == '\t' { + return ' ' + } + return r + }, s) +} + // overlayCentered places box over frame, centered. Whole frame lines are // replaced inside the box's band, so the underlay styling cannot leak into it. func overlayCentered(frame, box string, width, height int) string { diff --git a/ui/model/lua_text.go b/ui/model/lua_text.go new file mode 100644 index 000000000..bd6ab6e79 --- /dev/null +++ b/ui/model/lua_text.go @@ -0,0 +1,140 @@ +package model + +import ( + "fmt" + "strings" + + tea "charm.land/bubbletea/v2" + "charm.land/lipgloss/v2" +) + +// LuaTextMsg asks the UI to show a scrollable text block requested by a +// plugin. OnClose runs when the user dismisses it with Esc. +type LuaTextMsg struct { + Title string + Text string + OnClose func() +} + +// luaTextState is the open text panel. +type luaTextState struct { + title string + lines []string + scroll int + onClose func() +} + +func (m *Model) openLuaText(title, text string, onClose func()) { + width := m.luaTextWidth() + m.luaText = &luaTextState{ + title: title, + lines: wrapBlock(strings.TrimSpace(text), width-4), + onClose: onClose, + } +} + +// wrapBlock wraps each source line separately, so the lists and paragraphs a +// bot sends keep their shape. +func wrapBlock(text string, width int) []string { + if strings.TrimSpace(text) == "" { + return nil + } + var out []string + for _, line := range strings.Split(strings.ReplaceAll(text, "\r\n", "\n"), "\n") { + if strings.TrimSpace(line) == "" { + out = append(out, "") + continue + } + out = append(out, wrapText(line, width)...) + } + return out +} + +func (m Model) luaTextWidth() int { + width := max(40, m.layout.frameWidth-8) + return min(width, max(20, m.layout.frameWidth-4)) +} + +func (m Model) luaTextVisible() int { + if m.luaText == nil { + return 0 + } + return min(len(m.luaText.lines), max(3, m.height-10)) +} + +// handleLuaTextKey drives the open text panel. It returns true when the key +// was consumed. +func (m *Model) handleLuaTextKey(msg tea.KeyPressMsg) bool { + text := m.luaText + if text == nil { + return false + } + visible := m.luaTextVisible() + maxScroll := max(0, len(text.lines)-visible) + page := max(1, visible-1) + switch msg.String() { + case "esc", "q": + m.luaText = nil + if text.onClose != nil { + text.onClose() + } + case "up", "k": + text.scroll = max(0, text.scroll-1) + case "down", "j": + text.scroll = min(maxScroll, text.scroll+1) + case "pgup", "ctrl+u": + text.scroll = max(0, text.scroll-page) + case "pgdown", "ctrl+d": + text.scroll = min(maxScroll, text.scroll+page) + case "home", "g": + text.scroll = 0 + case "end", "G": + text.scroll = maxScroll + } + return true +} + +// renderLuaText draws the text panel as a centered box. +func (m Model) renderLuaText() string { + text := m.luaText + if text == nil { + return "" + } + width := m.luaTextWidth() + visible := m.luaTextVisible() + start := min(text.scroll, max(0, len(text.lines)-visible)) + end := min(start+visible, len(text.lines)) + + var b strings.Builder + b.WriteString(truncate(text.title, width-2)) + b.WriteString("\n\n") + for i := start; i < end; i++ { + b.WriteString(truncate(text.lines[i], width-4)) + if i < end-1 { + b.WriteString("\n") + } + } + if len(text.lines) > visible { + b.WriteString("\n") + if start > 0 { + b.WriteString(dimStyle.Render(" ↑ more")) + } + if end < len(text.lines) { + if start > 0 { + b.WriteString(" ") + } else { + b.WriteString(" ") + } + b.WriteString(dimStyle.Render(fmt.Sprintf("↓ %d more", len(text.lines)-end))) + } + } + b.WriteString("\n\n") + b.WriteString(dimStyle.Render(truncate(" ↑/↓ scroll esc close", width-4))) + + return lipgloss.NewStyle(). + Border(lipgloss.RoundedBorder()). + BorderForeground(lipgloss.Color("240")). + Padding(0, 1). + Width(width). + Render(b.String()) +} diff --git a/ui/model/lua_text_test.go b/ui/model/lua_text_test.go new file mode 100644 index 000000000..7a638fbcd --- /dev/null +++ b/ui/model/lua_text_test.go @@ -0,0 +1,32 @@ +package model + +import ( + "strings" + "testing" + + tea "charm.land/bubbletea/v2" +) + +func TestLuaTextKeepsLinesAndScrolls(t *testing.T) { + m := Model{height: 12} + m.openLuaText("Reply", "line one\nline two\nline three\nline four\nline five", nil) + if got := m.luaText.lines[0]; got != "line one" { + t.Fatalf("first line = %q", got) + } + m.handleLuaTextKey(tea.KeyPressMsg{Code: tea.KeyDown}) + m.handleLuaTextKey(tea.KeyPressMsg{Code: tea.KeyDown}) + if m.luaText.scroll != 2 { + t.Fatalf("scroll = %d, want 2", m.luaText.scroll) + } + m.handleLuaTextKey(tea.KeyPressMsg{Code: tea.KeyEscape}) + if m.luaText != nil { + t.Fatal("esc did not close the panel") + } +} + +func TestWrapBlockKeepsBlankLines(t *testing.T) { + lines := wrapBlock("one\n\ntwo", 20) + if strings.Join(lines, "|") != "one||two" { + t.Fatalf("lines = %#v", lines) + } +} diff --git a/ui/model/model.go b/ui/model/model.go index 5db050051..f5c2de865 100644 --- a/ui/model/model.go +++ b/ui/model/model.go @@ -320,6 +320,7 @@ type Model struct { paneCache *paneCache luaSelect *luaSelectState luaInput *luaInputState + luaText *luaTextState actionPane actionPaneState artRef *artRef slotVis *slotVisualizers diff --git a/ui/model/update.go b/ui/model/update.go index 67431b49f..1caadf8e5 100644 --- a/ui/model/update.go +++ b/ui/model/update.go @@ -106,6 +106,7 @@ func (m Model) update(msg tea.Msg) (tea.Model, tea.Cmd) { } m.luaSelect = &luaSelectState{ title: msg.Title, + body: msg.Body, options: msg.Options, cursor: cursor, onDone: msg.OnDone, @@ -113,11 +114,27 @@ func (m Model) update(msg tea.Msg) (tea.Model, tea.Cmd) { } return m, nil + case LuaTextMsg: + m.openLuaText(msg.Title, msg.Text, msg.OnClose) + return m, nil + case LuaInputMsg: if prev := m.luaInput; prev != nil && prev.onCancel != nil { prev.onCancel() } - m.openLuaInput(msg.Title, msg.Placeholder, msg.Value, msg.OnSubmit, msg.OnCancel) + m.openLuaInput(msg.Title, msg.Placeholder, msg.Value, msg.Suggestions, msg.OnChange, msg.OnSubmit, msg.OnSelect, msg.OnCancel) + return m, nil + + case LuaInputSuggestionsMsg: + if m.luaInput == nil { + return m, nil + } + if len(msg.Options) != len(m.luaInput.suggestions) { + m.luaInput.choice = 0 + } + m.luaInput.suggestions = msg.Options + m.luaInput.live = msg.Live + m.luaInput.filter() return m, nil case tea.WindowSizeMsg: diff --git a/ui/model/view.go b/ui/model/view.go index ab646ec00..944936b47 100644 --- a/ui/model/view.go +++ b/ui/model/view.go @@ -263,6 +263,10 @@ func (m Model) View() tea.View { content = strings.Join(m.mainSections(body, true, contentFirst), "\n") } + // Keep image placeholder lines changing every frame so the terminal + // re-emits them and kitty does not drop the images. + imagePulse = !imagePulse + // Every screen now renders within the main frame, so frame and center // uniformly. rendered := m.centerFrame(m.layout.frameStyle().Render(content)) @@ -277,6 +281,9 @@ func (m Model) View() tea.View { if box := m.renderLuaInput(); box != "" { rendered = overlayCentered(rendered, box, m.layout.frameWidth, m.height) } + if box := m.renderLuaText(); box != "" { + rendered = overlayCentered(rendered, box, m.layout.frameWidth, m.height) + } view := tea.NewView(rendered) view.BackgroundColor = ui.ColorBackground if ui.ColorBackground != nil { From a693ce2b1bb6896f9d5feaf3fd4fd8979a7c0398 Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 03:54:33 -0300 Subject: [PATCH 17/28] fix(plugins): align modal input order and route pasted text Render the plugin input above the selector so the topmost modal is also the one that owns the keyboard. Paste into the open plugin input instead of dropping the text or leaking it into the provider search, and share the post-edit behavior between typing and paste. --- ui/model/keys.go | 6 ++++++ ui/model/lua_input.go | 32 +++++++++++++++++++------------- ui/model/lua_input_test.go | 9 +++++++++ 3 files changed, 34 insertions(+), 13 deletions(-) diff --git a/ui/model/keys.go b/ui/model/keys.go index 7abd1031a..6afbe4f7d 100644 --- a/ui/model/keys.go +++ b/ui/model/keys.go @@ -1047,6 +1047,12 @@ func (m *Model) handlePaste(content string) tea.Cmd { if content == "" { return nil } + if m.luaInput != nil { + m.insertText("lua-input", &m.luaInput.value, content) + m.luaInput.cursor = m.textInput.cursor + m.luaInput.afterEdit() + return nil + } if spec, ok := m.topOverlay(); ok { if spec.paste != nil { spec.paste(m, content) diff --git a/ui/model/lua_input.go b/ui/model/lua_input.go index 9b16c5aed..b43065f81 100644 --- a/ui/model/lua_input.go +++ b/ui/model/lua_input.go @@ -143,24 +143,30 @@ func (m *Model) handleLuaInputKey(msg tea.KeyPressMsg) bool { default: if m.editText("lua-input", &input.value, msg) { input.cursor = m.textInput.cursor - // A live result belongs to the previous text. Clear it until the - // plugin sends the results for this query. - if input.live { - input.live = false - input.suggestions = nil - input.filtered = nil - input.choice = 0 - } else { - input.filter() - } - if input.onChange != nil { - input.onChange(input.value) - } + input.afterEdit() } } return true } +// afterEdit applies the state changes that every edit shares, whether it came +// from a key or a paste. +func (input *luaInputState) afterEdit() { + // A live result belongs to the previous text. Clear it until the plugin + // sends the results for this query. + if input.live { + input.live = false + input.suggestions = nil + input.filtered = nil + input.choice = 0 + } else { + input.filter() + } + if input.onChange != nil { + input.onChange(input.value) + } +} + // inputRows is the number of lines one option needs in the input. func imageLines(image string) []string { if strings.TrimSpace(image) == "" { diff --git a/ui/model/lua_input_test.go b/ui/model/lua_input_test.go index fc4b7479e..277017454 100644 --- a/ui/model/lua_input_test.go +++ b/ui/model/lua_input_test.go @@ -85,3 +85,12 @@ func TestLuaInputSuggestionsKeepImage(t *testing.T) { t.Fatalf("box does not contain the image lines:\n%s", box) } } + +func TestPasteGoesToOpenLuaInput(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "", nil, nil, nil, nil, nil) + m.handlePaste("daft punk") + if m.luaInput == nil || m.luaInput.value != "daft punk" { + t.Fatalf("input = %#v, want pasted text", m.luaInput) + } +} From f0bf4ce5ece680c9d6326eacd04a468df21e149f Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 04:21:51 -0300 Subject: [PATCH 18/28] fix(plugins): finish the rich-ui review Run only the WaitReply or WaitAudio selected by audio_only, keep the shared editor cursor in step with tab completion and prefilled inputs, normalize multiline live rows before measuring and rendering them, and ignore paste while a text panel owns the display. --- ui/model/keys.go | 3 +++ ui/model/lua_input.go | 16 ++++++++------ ui/model/lua_input_test.go | 44 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 57 insertions(+), 6 deletions(-) diff --git a/ui/model/keys.go b/ui/model/keys.go index 6afbe4f7d..010061fab 100644 --- a/ui/model/keys.go +++ b/ui/model/keys.go @@ -1047,6 +1047,9 @@ func (m *Model) handlePaste(content string) tea.Cmd { if content == "" { return nil } + if m.luaText != nil { + return nil + } if m.luaInput != nil { m.insertText("lua-input", &m.luaInput.value, content) m.luaInput.cursor = m.textInput.cursor diff --git a/ui/model/lua_input.go b/ui/model/lua_input.go index b43065f81..54bae1f28 100644 --- a/ui/model/lua_input.go +++ b/ui/model/lua_input.go @@ -60,6 +60,8 @@ func (m *Model) openLuaInput(title, placeholder, value string, suggestions []lua onCancel: onCancel, } m.luaInput.filter() + m.textInput.begin("lua-input", value) + m.textInput.cursor = len(value) } // filter keeps command suggestions that match a prefix. Live search results @@ -118,6 +120,8 @@ func (m *Model) handleLuaInputKey(msg tea.KeyPressMsg) bool { input.value += " " } input.cursor = len(input.value) + m.textInput.begin("lua-input", input.value) + m.textInput.cursor = input.cursor input.filter() } case "enter": @@ -196,9 +200,9 @@ func (m Model) renderLuaInput() string { width := max(40, lipgloss.Width(input.title)+4) width = max(width, lipgloss.Width(input.placeholder)+8) for _, suggestion := range input.filtered { - width = max(width, lipgloss.Width(suggestion.Title)+6) - width = max(width, lipgloss.Width(suggestion.Subtitle)+6) - width = max(width, lipgloss.Width(suggestion.Description)+6) + width = max(width, lipgloss.Width(oneLine(suggestion.Title))+6) + width = max(width, lipgloss.Width(oneLine(suggestion.Subtitle))+6) + width = max(width, lipgloss.Width(oneLine(suggestion.Description))+6) for _, line := range imageLines(suggestion.Image) { width = max(width, lipgloss.Width(line)+4) } @@ -297,12 +301,12 @@ func (m Model) renderLiveInputRows(b *strings.Builder, input *luaInputState, wid if i == input.choice { marker = "ā–ø " } - b.WriteString(marker + truncate(option.Title, width-6)) + b.WriteString(marker + truncate(oneLine(option.Title), width-6)) if option.Subtitle != "" { - b.WriteString("\n " + dimStyle.Render(truncate(option.Subtitle, width-6))) + b.WriteString("\n " + dimStyle.Render(truncate(oneLine(option.Subtitle), width-6))) } if option.Description != "" { - b.WriteString("\n " + dimStyle.Render(truncate(option.Description, width-6))) + b.WriteString("\n " + dimStyle.Render(truncate(oneLine(option.Description), width-6))) } } if end < len(input.filtered) { diff --git a/ui/model/lua_input_test.go b/ui/model/lua_input_test.go index 277017454..f53c22156 100644 --- a/ui/model/lua_input_test.go +++ b/ui/model/lua_input_test.go @@ -94,3 +94,47 @@ func TestPasteGoesToOpenLuaInput(t *testing.T) { t.Fatalf("input = %#v, want pasted text", m.luaInput) } } + +func TestLuaInputCursorAfterTab(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "", []luaplugin.SelectOption{{Title: "/help", Description: "Help"}}, nil, nil, nil, nil) + m.luaInput.value = "/h" + m.luaInput.filter() + m.luaInput.choice = 0 + m.handleLuaInputKey(tea.KeyPressMsg{Code: tea.KeyTab}) + m.handleLuaInputKey(tea.KeyPressMsg{Code: 'x', Text: "x"}) + if got := m.luaInput.value; got != "/help x" { + t.Fatalf("value = %q, want %q", got, "/help x") + } +} + +func TestLuaInputCursorOnPrefilledValue(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "abc", nil, nil, nil, nil, nil) + m.handleLuaInputKey(tea.KeyPressMsg{Code: 'd', Text: "d"}) + if got := m.luaInput.value; got != "abcd" { + t.Fatalf("value = %q, want %q", got, "abcd") + } +} + +func TestPasteIgnoredUnderTextPanel(t *testing.T) { + m := Model{} + m.openLuaText("Reply", "body", nil) + m.openLuaInput("Message", "", "", nil, nil, nil, nil, nil) + m.handlePaste("hidden") + if got := m.luaInput.value; got != "" { + t.Fatalf("value = %q, want empty", got) + } +} + +func TestLuaInputLiveRowsAreOneLine(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "", nil, nil, nil, nil, nil) + m.luaInput.live = true + m.luaInput.suggestions = []luaplugin.SelectOption{{Title: "one\ntwo"}} + m.luaInput.filter() + box := m.renderLuaInput() + if strings.Contains(box, "one\ntwo") { + t.Fatalf("live row kept a newline:\n%s", box) + } +} From ecb554287df4e73c2d4bf712ec42c94803cdac81 Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 04:54:40 -0300 Subject: [PATCH 19/28] fix(plugins): notify onChange on completion and cap tall images Route tab completion through the shared edit path so onChange sees the completed value, and cap a live row's image to the rows left after its title, subtitle and description. --- ui/model/lua_input.go | 8 ++++++-- ui/model/lua_input_test.go | 36 ++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 2 deletions(-) diff --git a/ui/model/lua_input.go b/ui/model/lua_input.go index 54bae1f28..4aebc309d 100644 --- a/ui/model/lua_input.go +++ b/ui/model/lua_input.go @@ -122,7 +122,7 @@ func (m *Model) handleLuaInputKey(msg tea.KeyPressMsg) bool { input.cursor = len(input.value) m.textInput.begin("lua-input", input.value) m.textInput.cursor = input.cursor - input.filter() + input.afterEdit() } case "enter": if input.live && len(input.filtered) > 0 { @@ -294,7 +294,11 @@ func (m Model) renderLiveInputRows(b *strings.Builder, input *luaInputState, wid if i > start { b.WriteString("\n") } - for _, line := range imageLines(option.Image) { + lines := imageLines(option.Image) + if budget := maxRows - (inputRows(option) - len(lines)); len(lines) > budget { + lines = lines[:max(0, budget)] + } + for _, line := range lines { b.WriteString(" " + line + imageResetSuffix() + "\n") } marker := " " diff --git a/ui/model/lua_input_test.go b/ui/model/lua_input_test.go index f53c22156..42ad11622 100644 --- a/ui/model/lua_input_test.go +++ b/ui/model/lua_input_test.go @@ -138,3 +138,39 @@ func TestLuaInputLiveRowsAreOneLine(t *testing.T) { t.Fatalf("live row kept a newline:\n%s", box) } } + +func TestLuaInputTabNotifiesChange(t *testing.T) { + var got string + m := Model{} + m.openLuaInput("Message", "", "", []luaplugin.SelectOption{{Title: "/help", Description: "Help"}}, func(text string) { + got = text + }, nil, nil, nil) + m.luaInput.value = "/h" + m.luaInput.filter() + m.luaInput.choice = 0 + m.handleLuaInputKey(tea.KeyPressMsg{Code: tea.KeyTab}) + if got != "/help " { + t.Fatalf("onChange = %q, want %q", got, "/help ") + } +} + +func TestLuaInputCapsTallResultImage(t *testing.T) { + m := Model{height: 24} + m.openLuaInput("Message", "", "", nil, nil, nil, nil, nil) + lines := make([]string, 20) + for i := range lines { + lines[i] = "IMG" + } + m.luaInput.live = true + m.luaInput.suggestions = []luaplugin.SelectOption{{Title: "Title", Image: strings.Join(lines, "\n")}} + m.luaInput.filter() + var b strings.Builder + m.renderLiveInputRows(&b, m.luaInput, 40) + out := b.String() + if strings.Count(out, "IMG") > 9 { + t.Fatalf("image was not capped:\n%s", out) + } + if !strings.Contains(out, "Title") { + t.Fatalf("selected title missing:\n%s", out) + } +} From b0b403e136e92061f4d1b4ab4700ef09bc9c79a2 Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 05:06:11 -0300 Subject: [PATCH 20/28] fix(plugins): keep live results on cursor moves and scroll the input Only run the edit transition when the text changed, so Left, Right, Home and End do not clear live results or fire onChange. Render the input around the cursor so a value longer than the box stays editable. --- ui/model/lua_input.go | 38 +++++++++++++++++++++++++++++++++----- ui/model/lua_input_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 5 deletions(-) diff --git a/ui/model/lua_input.go b/ui/model/lua_input.go index 4aebc309d..025242b9c 100644 --- a/ui/model/lua_input.go +++ b/ui/model/lua_input.go @@ -2,6 +2,7 @@ package model import ( "strings" + "unicode/utf8" tea "charm.land/bubbletea/v2" "charm.land/lipgloss/v2" @@ -145,9 +146,12 @@ func (m *Model) handleLuaInputKey(msg tea.KeyPressMsg) bool { input.onSubmit(text) } default: + before := input.value if m.editText("lua-input", &input.value, msg) { input.cursor = m.textInput.cursor - input.afterEdit() + if input.value != before { + input.afterEdit() + } } } return true @@ -171,6 +175,33 @@ func (input *luaInputState) afterEdit() { } } +// inputWindow shows the part of value around cursor that fits in width cells. +// The cursor marker takes one cell, so the text budget is width-1. +func inputWindow(value string, cursor, width int) string { + if width < 1 { + width = 1 + } + runes := []rune(value) + cursorRune := utf8.RuneCountInString(value[:min(cursor, len(value))]) + if cursorRune > len(runes) { + cursorRune = len(runes) + } + budget := width - 1 + start := 0 + for start < cursorRune && lipgloss.Width(string(runes[start:cursorRune])) >= budget { + start++ + } + end := len(runes) + for end > cursorRune && lipgloss.Width(string(runes[start:end])) > budget { + end-- + } + var b strings.Builder + b.WriteString(string(runes[start:cursorRune])) + b.WriteString("ā–") + b.WriteString(string(runes[cursorRune:end])) + return b.String() +} + // inputRows is the number of lines one option needs in the input. func imageLines(image string) []string { if strings.TrimSpace(image) == "" { @@ -209,10 +240,7 @@ func (m Model) renderLuaInput() string { } width = min(width, max(20, m.layout.frameWidth-4)) - shown := input.value - if input.cursor >= 0 && input.cursor <= len(shown) { - shown = shown[:input.cursor] + "ā–" + shown[input.cursor:] - } + shown := inputWindow(input.value, input.cursor, width-4) if strings.TrimSpace(input.value) == "" && input.placeholder != "" { shown = dimStyle.Render(truncate(input.placeholder, width-4)) } diff --git a/ui/model/lua_input_test.go b/ui/model/lua_input_test.go index 42ad11622..452103fe7 100644 --- a/ui/model/lua_input_test.go +++ b/ui/model/lua_input_test.go @@ -174,3 +174,29 @@ func TestLuaInputCapsTallResultImage(t *testing.T) { t.Fatalf("selected title missing:\n%s", out) } } + +func TestLuaInputCursorMoveKeepsLiveResults(t *testing.T) { + changed := 0 + m := Model{} + m.openLuaInput("Message", "", "abc", nil, func(string) { changed++ }, nil, nil, nil) + m.luaInput.live = true + m.luaInput.suggestions = []luaplugin.SelectOption{{Title: "Get Lucky"}} + m.luaInput.filter() + m.handleLuaInputKey(tea.KeyPressMsg{Code: tea.KeyLeft}) + if changed != 0 { + t.Fatalf("onChange ran %d times on a cursor move", changed) + } + if len(m.luaInput.filtered) != 1 { + t.Fatalf("live results cleared on a cursor move: %#v", m.luaInput.filtered) + } +} + +func TestLuaInputWindowFollowsCursor(t *testing.T) { + m := Model{width: 80} + value := strings.Repeat("a", 80) + "z" + m.openLuaInput("Message", "", value, nil, nil, nil, nil, nil) + box := m.renderLuaInput() + if !strings.Contains(box, "zā–") { + t.Fatalf("cursor is not visible at the end of a long value:\n%s", box) + } +} From 3a1efeb686ecec9b0868b13109475905ed85ab0d Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 05:21:25 -0300 Subject: [PATCH 21/28] perf(plugins): find the visible input window in one pass --- ui/model/lua_input.go | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/ui/model/lua_input.go b/ui/model/lua_input.go index 025242b9c..a355dd5b8 100644 --- a/ui/model/lua_input.go +++ b/ui/model/lua_input.go @@ -187,13 +187,23 @@ func inputWindow(value string, cursor, width int) string { cursorRune = len(runes) } budget := width - 1 - start := 0 - for start < cursorRune && lipgloss.Width(string(runes[start:cursorRune])) >= budget { - start++ + start, used := cursorRune, 0 + for start > 0 { + w := lipgloss.Width(string(runes[start-1])) + if used+w > budget { + break + } + start-- + used += w } - end := len(runes) - for end > cursorRune && lipgloss.Width(string(runes[start:end])) > budget { - end-- + end := cursorRune + for end < len(runes) { + w := lipgloss.Width(string(runes[end])) + if used+w > budget { + break + } + end++ + used += w } var b strings.Builder b.WriteString(string(runes[start:cursorRune])) From 0c85233e8aaca24da203f5e5e138cd31063e0c17 Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 03:38:12 -0300 Subject: [PATCH 22/28] feat(plugins): expose provider context and open resolved playlists provider.current() now carries the section of the open playlist and of the selected row. A plugin can use telegram.resolve to turn a username into a playlist, telegram.add_chat to add it to the chats filter, and cliamp.provider.open to load it without asking the user for Ctrl+R. p:action gains a context filter, so an action can appear only in the provider list or only with a playlist open. Ctrl+C now quits over the action pane, input, text panel and selector instead of leaving the key to their handlers. Document the new context fields, the open call and the resolve/add_chat actions, and list the DeezLoad plugin in the community plugins page. --- docs/community-plugins.md | 1 + docs/plugins.md | 22 ++++++++++-- docs/telegram.md | 5 +-- lua_wiring.go | 51 +++++++++++++++++++++++++-- luaplugin/api_action.go | 2 ++ luaplugin/api_provider.go | 56 ++++++++++++++++++++++++------ main.go | 2 +- ui/model/action_pane.go | 16 +++++++-- ui/model/action_pane_test.go | 39 +++++++++++++++++++++ ui/model/keys.go | 3 ++ ui/model/plugin_modal_quit_test.go | 33 ++++++++++++++++++ ui/model/plugin_open.go | 41 ++++++++++++++++++++++ ui/model/plugin_queue.go | 7 ++++ ui/model/plugin_state.go | 2 ++ ui/model/update.go | 3 ++ 15 files changed, 263 insertions(+), 20 deletions(-) create mode 100644 ui/model/plugin_modal_quit_test.go create mode 100644 ui/model/plugin_open.go diff --git a/docs/community-plugins.md b/docs/community-plugins.md index b68b24805..64d7f8594 100644 --- a/docs/community-plugins.md +++ b/docs/community-plugins.md @@ -20,3 +20,4 @@ These plugins are maintained by the community. To add a plugin, open a PR. | [cliamp-plugin-save-song](https://github.com/dorobica/cliamp-plugin-save-song) | One key saves the playing song, including the live title on radio streams, to a dated list you can search and replay | [@dorobica](https://github.com/dorobica) | | [cliamp-plugin-mac-notify](https://github.com/dbarrerap/cliamp-plugin-mac-notify) | macOS Now Playing desktop notifications with local cover art and YouTube thumbnails | [@dbarrerap](https://github.com/dbarrerap) | | [cliamp-plugin-hanami](https://github.com/niteover/cliamp-plugin-hanami) | Pixel cherry blossom visualizer: petals pile up in drifts that glow with the spectrum and jump on the beat | [@niteover](https://github.com/niteover) | +| [cliamp-plugin-deezload](https://github.com/cartudev/cliamp-plugin-deezload) | DeezLoad music bot for the Telegram provider: command palette, inline search, covers and reply history | [@cartudev](https://github.com/cartudev) | diff --git a/docs/plugins.md b/docs/plugins.md index 108b7ebe7..865d08609 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -304,6 +304,7 @@ p:action{ label = "Send message", description = "Ask the bot for a track", provider = "Telegram", -- optional + context = "chat", -- optional: "chat" or "chats" prompt = "Message", -- optional: ask for text first on_submit = function(text) ... end, } @@ -315,6 +316,10 @@ or the id is already registered. The action pane filters by provider and by the text typed in the pane. An action with `prompt` runs `on_submit` with the text; without it, `on_submit` gets an empty string. +`context` narrows the action to the provider list or to open content: +`"chats"` shows it only while the provider list has no open playlist, and +`"chat"` only while one is open. Leave it out to show the action in both. + ## Lua API All APIs are in the global `cliamp` table. @@ -438,13 +443,16 @@ lacks the `control` permission. An HTTP URL is always marked as a stream. { name = "Telegram", playlist_id = "u:1:2", playlist_name = "DeezLoad", + playlist_section = "Bots", selection_id = "u:1:2", selection_name = "DeezLoad", + selection_section = "Bots", } ``` `playlist_id` is the playlist open in the pane; `selection_id` is the row under -the cursor. Either can be empty. `name` is the same string the provider uses in -the UI. +the cursor. Either can be empty. `playlist_section` and `selection_section` are +the headings the provider uses, such as `Bots` or `Groups`. `name` is the same +string the provider uses in the UI. `cliamp.provider.call(action, params[, options])` calls a provider action. Reads need `permissions = {"provider"}`; actions that change the remote account @@ -477,7 +485,15 @@ advertises), `telegram.send` (send text and return the message id), `telegram.ask` (send and wait for the reply), `telegram.reply` (wait for the next message after an id), `telegram.callback` (press an inline button), `telegram.message` (re-read one message), `telegram.inline` (ask an inline bot -for results) and `telegram.send_inline` (send one of those results). +for results), `telegram.send_inline` (send one of those results), +`telegram.resolve` (turn a username or `t.me` link into a playlist id) and +`telegram.add_chat` (add a chat to the provider's `chats` filter when one is +set). + +`cliamp.provider.open{provider, playlist_id, playlist_name, playlist_section}` +asks the UI to load a playlist that the plugin resolved, such as a bot chat it +just created. It returns true, or an error when the provider is not active or +the UI is not available. ### cliamp.http diff --git a/docs/telegram.md b/docs/telegram.md index 10a99a5ca..705b5459a 100644 --- a/docs/telegram.md +++ b/docs/telegram.md @@ -114,8 +114,9 @@ and plays them. A plugin can also write into that chat: send a command as the signed-in user, wait for the bot's reply, press an inline button, or ask an inline bot for results and send one. The write actions live in the plugin API (`cliamp.provider.call`), not in a fixed key, so the plugin decides the prompt -and how to show the reply. See [Plugins](plugins.md) and the bundled -`telegram-bot.lua`. +and how to show the reply. A plugin can also resolve a bot username, add the +chat to the `chats` filter, and ask the UI to open it. See [Plugins](plugins.md) +and the bundled `telegram-bot.lua`. Writes use the same MTProto session as reads and act as the signed-in user. A bot sees a normal message from you; a command sent to a group is visible to diff --git a/lua_wiring.go b/lua_wiring.go index cb68f9637..3a3aae169 100644 --- a/lua_wiring.go +++ b/lua_wiring.go @@ -211,9 +211,23 @@ func showSelectFor(send func(tea.Msg), headless bool) func(string, string, []lua // for "telegram.send" and the provider that implements ChatCommander runs it. // The provider call runs on the caller's goroutine, so a blocking reply never // holds the UI. -func luaProviderProvider(entries []provider.Entry, load func() model.PluginState) luaplugin.ProviderProvider { +func luaProviderProvider(entries []provider.Entry, load func() model.PluginState, send func(tea.Msg)) luaplugin.ProviderProvider { return luaplugin.ProviderProvider{ Current: func() luaplugin.ProviderInfo { return load().Provider }, + Open: func(info luaplugin.ProviderInfo) error { + if send == nil { + return fmt.Errorf("ui: not available") + } + send(model.PluginOpenProviderMsg{ + ProviderName: info.Name, + Playlist: playlist.PlaylistInfo{ + ID: info.PlaylistID, + Name: info.PlaylistName, + Section: info.PlaylistSection, + }, + }) + return nil + }, Call: func(ctx context.Context, action string, params map[string]any) (map[string]any, error) { name, verb, ok := strings.Cut(action, ".") if !ok || name == "" || verb == "" { @@ -230,7 +244,7 @@ func luaProviderProvider(entries []provider.Entry, load func() model.PluginState return nil, fmt.Errorf("provider %q is not available", name) } chat, _ := params["chat"].(string) - if chat == "" { + if chat == "" && verb != "resolve" { return nil, fmt.Errorf("%s: chat is required", action) } commander, ok := prov.(provider.ChatCommander) @@ -267,6 +281,39 @@ func luaProviderProvider(entries []provider.Entry, load func() model.PluginState return waitReplyResult(ctx, commander, chat, id, params) case "reply": return waitReplyResult(ctx, commander, chat, intParam(params, "after"), params) + case "resolve": + info, err := commander.ResolveChat(ctx, stringParam(params, "username")) + if err != nil { + return nil, err + } + return map[string]any{ + "id": info.ID, + "name": info.Name, + "section": info.Section, + }, nil + case "add_chat": + filter, ok := prov.(provider.ChatFilter) + if !ok { + return nil, fmt.Errorf("provider %q has no chat filter", name) + } + chat := stringParam(params, "chat") + chats := filter.Chats() + found := false + for _, existing := range chats { + if existing == chat { + found = true + break + } + } + added := false + if !found && len(chats) > 0 { + chats = append(chats, chat) + if err := filter.SetChats(chats); err != nil { + return nil, err + } + added = true + } + return map[string]any{"added": added, "filtered": len(chats) > 0}, nil case "inline": bot := stringParam(params, "bot") if bot == "" { diff --git a/luaplugin/api_action.go b/luaplugin/api_action.go index ca1d83302..bdb5fe30e 100644 --- a/luaplugin/api_action.go +++ b/luaplugin/api_action.go @@ -22,6 +22,7 @@ type Action struct { Provider string Key string Prompt string + Context string // "chat", "chats" or empty for both run func(text string) } @@ -80,6 +81,7 @@ func (m *Manager) registerActionAPI(L *lua.LState, obj *lua.LTable, p *Plugin) { Provider: strings.TrimSpace(rawString(L, opts, "provider")), Key: key, Prompt: strings.TrimSpace(rawString(L, opts, "prompt")), + Context: strings.TrimSpace(rawString(L, opts, "context")), run: func(text string) { label := "action " + id m.mu.RLock() diff --git a/luaplugin/api_provider.go b/luaplugin/api_provider.go index dd0eb20bc..bba442f91 100644 --- a/luaplugin/api_provider.go +++ b/luaplugin/api_provider.go @@ -12,11 +12,13 @@ import ( // playlist is the one open in the provider pane; selection is the row under // the cursor in the provider list. Either id may be empty. type ProviderInfo struct { - Name string - PlaylistID string - PlaylistName string - SelectionID string - SelectionName string + Name string + PlaylistID string + PlaylistName string + PlaylistSection string + SelectionID string + SelectionName string + SelectionSection string } // ProviderProvider exposes the active provider context and the chat actions a @@ -24,6 +26,9 @@ type ProviderInfo struct { type ProviderProvider struct { Current func() ProviderInfo Call func(ctx context.Context, action string, params map[string]any) (map[string]any, error) + // Open asks the UI to load a playlist the plugin resolved, such as a bot + // chat that was just created. + Open func(info ProviderInfo) error } // providerWrites reports whether an action changes the remote account. Write @@ -60,15 +65,46 @@ func (m *Manager) registerProviderAPI(L *lua.LState, cliamp *lua.LTable, p *Plug } info := pp.Current() L.Push(dataToTable(L, map[string]any{ - "name": info.Name, - "playlist_id": info.PlaylistID, - "playlist_name": info.PlaylistName, - "selection_id": info.SelectionID, - "selection_name": info.SelectionName, + "name": info.Name, + "playlist_id": info.PlaylistID, + "playlist_name": info.PlaylistName, + "playlist_section": info.PlaylistSection, + "selection_id": info.SelectionID, + "selection_name": info.SelectionName, + "selection_section": info.SelectionSection, })) return 1 })) + // cliamp.provider.open{provider, playlist_id, playlist_name, playlist_section} + L.SetField(tbl, "open", L.NewFunction(func(L *lua.LState) int { + if !p.permitted(PermProvider, "cliamp.provider.open") { + return pushErr(L, "provider permission required") + } + opts := L.CheckTable(1) + info := ProviderInfo{ + Name: strings.TrimSpace(rawString(L, opts, "provider")), + PlaylistID: strings.TrimSpace(rawString(L, opts, "playlist_id")), + PlaylistName: strings.TrimSpace(rawString(L, opts, "playlist_name")), + PlaylistSection: strings.TrimSpace(rawString(L, opts, "playlist_section")), + } + pp := m.provider.Load() + if pp == nil || pp.Open == nil { + return pushErr(L, "provider: not available") + } + if info.Name == "" && pp.Current != nil { + info.Name = pp.Current().Name + } + if info.PlaylistID == "" { + return pushErr(L, "cliamp.provider.open: playlist_id is required") + } + if err := pp.Open(info); err != nil { + return pushErr(L, err.Error()) + } + L.Push(lua.LTrue) + return 1 + })) + L.SetField(tbl, "call", L.NewFunction(func(L *lua.LState) int { action := strings.TrimSpace(L.CheckString(1)) if action == "" { diff --git a/main.go b/main.go index 10b36a631..e14a3260d 100644 --- a/main.go +++ b/main.go @@ -185,7 +185,6 @@ func run(overrides config.Overrides, positional []string, headless, visualizer60 m.SetIPCBroker(pluginBroker) if luaMgr != nil { luaMgr.SetStateProvider(luaStateProvider(p, m.PluginStateLoader())) - luaMgr.SetProviderProvider(luaProviderProvider(providers.entries, m.PluginStateLoader())) if names := luaMgr.Visualizers(); len(names) > 0 { m.RegisterLuaVisualizers(names, luaMgr) } @@ -231,6 +230,7 @@ func run(overrides config.Overrides, positional []string, headless, visualizer60 defer stopLuaSend() luaMgr.SetControlProvider(luaControlProvider(luaSend)) luaMgr.SetUIProvider(luaUIProvider(luaSend, headless)) + luaMgr.SetProviderProvider(luaProviderProvider(providers.entries, m.PluginStateLoader(), luaSend)) } stopIPC, err := startIPC(prog.Send, pluginBroker, luaMgr, headless) diff --git a/ui/model/action_pane.go b/ui/model/action_pane.go index b536e0e81..081f45205 100644 --- a/ui/model/action_pane.go +++ b/ui/model/action_pane.go @@ -34,11 +34,23 @@ func (m *Model) openActionPane() { if m.provider != nil { providerName = m.provider.Name() } + chatOpen := m.activeProviderPlaylistID != "" available := make([]luaplugin.Action, 0, len(entries)) for _, action := range entries { - if action.Provider == "" || strings.EqualFold(action.Provider, providerName) { - available = append(available, action) + if action.Provider != "" && !strings.EqualFold(action.Provider, providerName) { + continue } + switch action.Context { + case "chat": + if !chatOpen { + continue + } + case "chats": + if chatOpen { + continue + } + } + available = append(available, action) } entries = available if len(entries) == 0 { diff --git a/ui/model/action_pane_test.go b/ui/model/action_pane_test.go index 1240326ef..341b51f16 100644 --- a/ui/model/action_pane_test.go +++ b/ui/model/action_pane_test.go @@ -165,3 +165,42 @@ func TestActionPaneResizeClampsScroll(t *testing.T) { t.Fatalf("scroll = %d, want 2", got.actionPane.scroll) } } + +func TestActionPaneFiltersByChatContext(t *testing.T) { + configDir := t.TempDir() + t.Setenv("CLIAMP_CONFIG_DIR", configDir) + pluginDir := filepath.Join(configDir, "plugins") + if err := os.MkdirAll(pluginDir, 0o755); err != nil { + t.Fatal(err) + } + pluginPath := filepath.Join(pluginDir, "action-context.lua") + script := ` +local p = plugin.register({name = "action-context", type = "hook", permissions = {"ui"}}) +p:action{key = "!", id = "chat", label = "Chat action", context = "chat", on_submit = function() end} +p:action{key = "!", id = "chats", label = "Chats action", context = "chats", on_submit = function() end} +` + if err := os.WriteFile(pluginPath, []byte(script), 0o644); err != nil { + t.Fatal(err) + } + if _, err := plugintrust.Approve(pluginDir, "action-context", pluginPath); err != nil { + t.Fatal(err) + } + mgr, err := luaplugin.New(nil, nil, ReservedKeys()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(sync.OnceFunc(mgr.Close)) + + m := Model{luaMgr: mgr} + m.openActionPane() + if len(m.actionPane.filtered) != 1 || m.actionPane.filtered[0].Label != "Chats action" { + t.Fatalf("chats pane = %#v", m.actionPane.filtered) + } + + m.actionPane = actionPaneState{} + m.activeProviderPlaylistID = "u:1:2" + m.openActionPane() + if len(m.actionPane.filtered) != 1 || m.actionPane.filtered[0].Label != "Chat action" { + t.Fatalf("chat pane = %#v", m.actionPane.filtered) + } +} diff --git a/ui/model/keys.go b/ui/model/keys.go index 010061fab..ffdd2c2ab 100644 --- a/ui/model/keys.go +++ b/ui/model/keys.go @@ -190,9 +190,12 @@ func normalizeShiftedLetter(msg tea.KeyPressMsg) tea.KeyPressMsg { func (m *Model) handleKey(msg tea.KeyPressMsg) tea.Cmd { msg = normalizeShiftedLetter(msg) + // Ctrl+C quits over every plugin modal too. The modal handlers below own + // the keyboard, so the global handler never sees the key otherwise. if msg.String() == "ctrl+c" { return m.quit() } + if m.luaText != nil { m.handleLuaTextKey(msg) return nil diff --git a/ui/model/plugin_modal_quit_test.go b/ui/model/plugin_modal_quit_test.go new file mode 100644 index 000000000..38ac371ed --- /dev/null +++ b/ui/model/plugin_modal_quit_test.go @@ -0,0 +1,33 @@ +package model + +import ( + "testing" + + tea "charm.land/bubbletea/v2" + + "github.com/bjarneo/cliamp/luaplugin" + "github.com/bjarneo/cliamp/playlist" +) + +func TestCtrlCQuitsOverPluginModals(t *testing.T) { + cases := []struct { + name string + open func(*Model) + }{ + {"action pane", func(m *Model) { m.actionPane.visible = true }}, + {"lua text", func(m *Model) { m.openLuaText("Reply", "body", nil) }}, + {"lua input", func(m *Model) { m.openLuaInput("Message", "", "", nil, nil, nil, nil, nil) }}, + {"lua select", func(m *Model) { + m.luaSelect = &luaSelectState{title: "Pick", options: []luaplugin.SelectOption{{Title: "One"}}} + }}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + m := Model{player: &playbackFakeEngine{}, playlist: playlist.New()} + tc.open(&m) + if cmd := m.handleKey(tea.KeyPressMsg{Code: 'c', Mod: tea.ModCtrl}); cmd == nil || !m.quitting { + t.Fatal("Ctrl+C did not quit") + } + }) + } +} diff --git a/ui/model/plugin_open.go b/ui/model/plugin_open.go new file mode 100644 index 000000000..9a57e0f3e --- /dev/null +++ b/ui/model/plugin_open.go @@ -0,0 +1,41 @@ +package model + +import ( + "strings" + + tea "charm.land/bubbletea/v2" +) + +// handlePluginOpenProvider loads a playlist that a plugin resolved, such as a +// bot chat created from the chat list. The provider pane may not contain the +// row yet, so the row is added before the tracks are fetched. +func (m *Model) handlePluginOpenProvider(msg PluginOpenProviderMsg) tea.Cmd { + if m.provider == nil || msg.Playlist.ID == "" { + return nil + } + if msg.ProviderName != "" && !strings.EqualFold(m.provider.Name(), msg.ProviderName) { + m.status.Warningf(statusTTLDefault, "Switch to %s first.", msg.ProviderName) + return nil + } + found := false + for i, row := range m.provPane.lists { + if row.ID == msg.Playlist.ID { + m.provPane.lists[i] = msg.Playlist + m.provPane.cursor = i + found = true + break + } + } + if !found { + m.provPane.lists = append(m.provPane.lists, msg.Playlist) + m.provPane.cursor = len(m.provPane.lists) - 1 + } + m.provPane.loading = true + m.activeProviderPlaylistID = msg.Playlist.ID + m.focus = focusPlaylist + m.applyHeightMode() + m.adjustScroll() + m.recomputeLayout() + m.status.Activityf(statusTTLShort, "Loading %s…", msg.Playlist.Name) + return m.fetchProviderTracks(msg.Playlist.ID) +} diff --git a/ui/model/plugin_queue.go b/ui/model/plugin_queue.go index 1599435ba..0a0d41e1b 100644 --- a/ui/model/plugin_queue.go +++ b/ui/model/plugin_queue.go @@ -11,6 +11,13 @@ import ( // Mutations are routed through the Update loop rather than applied directly // from the plugin goroutine so the model's derived state (cursor, current // index, playback) stays consistent. Indices are 0-based. +// PluginOpenProviderMsg asks the UI to load a provider playlist the plugin +// resolved, such as a bot chat that was just created. +type PluginOpenProviderMsg struct { + ProviderName string + Playlist playlist.PlaylistInfo +} + type PluginQueueMsg struct { Op string // "add" | "add_track" | "jump" | "remove" | "move" Path string // add diff --git a/ui/model/plugin_state.go b/ui/model/plugin_state.go index 7d613c163..d35ce3053 100644 --- a/ui/model/plugin_state.go +++ b/ui/model/plugin_state.go @@ -64,6 +64,7 @@ func (m *Model) providerInfo() luaplugin.ProviderInfo { for _, row := range m.provPane.lists { if row.ID == info.PlaylistID { info.PlaylistName = row.Name + info.PlaylistSection = row.Section break } } @@ -71,6 +72,7 @@ func (m *Model) providerInfo() luaplugin.ProviderInfo { row := m.provPane.lists[m.provPane.cursor] info.SelectionID = row.ID info.SelectionName = row.Name + info.SelectionSection = row.Section } return info } diff --git a/ui/model/update.go b/ui/model/update.go index 1caadf8e5..a0e6b1578 100644 --- a/ui/model/update.go +++ b/ui/model/update.go @@ -396,6 +396,9 @@ func (m Model) update(msg tea.Msg) (tea.Model, tea.Cmd) { m.setCustomEQBand(msg.Band, msg.Gain) return m, nil + case PluginOpenProviderMsg: + return m, m.handlePluginOpenProvider(msg) + case PluginQueueMsg: cmd := m.handlePluginQueue(msg) return m, cmd From 2d3758a2e12b3b61e1a9a55162faeb52c150803f Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 03:43:47 -0300 Subject: [PATCH 23/28] docs(plugin): scope the generic bot action to an open chat --- plugins/telegram-bot.lua | 1 + 1 file changed, 1 insertion(+) diff --git a/plugins/telegram-bot.lua b/plugins/telegram-bot.lua index 3782d905d..a40430864 100644 --- a/plugins/telegram-bot.lua +++ b/plugins/telegram-bot.lua @@ -141,6 +141,7 @@ p:action{ label = "Send message to this chat", description = "Ask the bot for a track", provider = "Telegram", + context = "chat", on_submit = function() local chat, name = current_chat() if not chat then From bda9908ca122fc26c99670a4f20acab1d26cb0fc Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 04:31:24 -0300 Subject: [PATCH 24/28] test(plugins): cover the provider section fields --- luaplugin/api_provider_test.go | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/luaplugin/api_provider_test.go b/luaplugin/api_provider_test.go index e213942c7..6f6c85ff9 100644 --- a/luaplugin/api_provider_test.go +++ b/luaplugin/api_provider_test.go @@ -15,11 +15,13 @@ func TestProviderCurrent(t *testing.T) { m.SetProviderProvider(ProviderProvider{ Current: func() ProviderInfo { return ProviderInfo{ - Name: "Telegram", - PlaylistID: "u:1:2", - PlaylistName: "DeezLoad", - SelectionID: "u:3:4", - SelectionName: "Other", + Name: "Telegram", + PlaylistID: "u:1:2", + PlaylistName: "DeezLoad", + PlaylistSection: "Bots", + SelectionID: "u:3:4", + SelectionName: "Other", + SelectionSection: "Chats", } }, }) @@ -28,7 +30,9 @@ func TestProviderCurrent(t *testing.T) { local c = cliamp.provider.current() _G.name = c.name _G.playlist = c.playlist_name + _G.playlist_section = c.playlist_section _G.selection = c.selection_name + _G.selection_section = c.selection_section `) p := m.plugins[0] @@ -41,6 +45,12 @@ func TestProviderCurrent(t *testing.T) { if got := p.L.GetGlobal("selection").String(); got != "Other" { t.Errorf("selection = %q", got) } + if got := p.L.GetGlobal("playlist_section").String(); got != "Bots" { + t.Errorf("playlist_section = %q", got) + } + if got := p.L.GetGlobal("selection_section").String(); got != "Chats" { + t.Errorf("selection_section = %q", got) + } } func TestProviderCallRead(t *testing.T) { From f75eb9a00fd05f34290c500b86dbf42d48e9d139 Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 05:02:42 -0300 Subject: [PATCH 25/28] fix(plugins): close the provider-context review Validate the target provider before accepting provider.open, use the call deadline when no explicit timeout is given, and prefer a newer text reply over an older keyboard. Treat telegram.reply as a read, scope chat actions by the visible provider list, restore the previous playlist context when a load fails, canonicalize chat ids for the busy guard, and cap oversized images in the selector. Add regression tests for the newer-text reply, the read permission, the context deadline and the visible-list action scope. --- external/telegram/write.go | 21 ++++++++++++-------- external/telegram/write_test.go | 26 ++++++++++++++++++++++++ lua_wiring.go | 8 ++++++++ lua_wiring_test.go | 19 ++++++++++++++++-- luaplugin/api_provider.go | 2 +- luaplugin/api_provider_test.go | 22 +++++++++++++++++++++ plugins/telegram-bot.lua | 12 +++++++++++ ui/model/action_pane.go | 2 +- ui/model/action_pane_test.go | 35 +++++++++++++++++++++++++++++++++ ui/model/lua_modal.go | 6 +++++- ui/model/model.go | 5 +++++ ui/model/plugin_open.go | 2 ++ ui/model/providers.go | 3 +++ ui/model/update_provider.go | 7 +++++++ 14 files changed, 157 insertions(+), 13 deletions(-) diff --git a/external/telegram/write.go b/external/telegram/write.go index ed50844b3..3d043742d 100644 --- a/external/telegram/write.go +++ b/external/telegram/write.go @@ -282,8 +282,8 @@ func (p *Provider) waitReply(ctx context.Context, chatID string, afterID int, ti return audio, nil } if !audioOnly { - if keyboard, ok := keyboardReply(afterID, messagesOf(history)); ok { - return keyboard, nil + if newest, ok := newestReplyWithButtons(afterID, messagesOf(history)); ok { + return newest, nil } } if value, ok := textReply(afterID, messagesOf(history)); ok { @@ -359,22 +359,27 @@ func audioReply(chatID string, afterID int, messages []tg.MessageClass) (provide return provider.ChatReply{}, false } -// keyboardReply returns the newest message with an inline or reply keyboard, -// even when it carries no text. Bots often send the options as a keyboard on -// a separate message. -func keyboardReply(afterID int, messages []tg.MessageClass) (provider.ChatReply, bool) { +// newestReplyWithButtons returns the newest text/keyboard message only when +// it carries buttons. A newer text reply without a keyboard supersedes an +// older menu, so WaitReply reports the newer failure instead of the stale +// options. +func newestReplyWithButtons(afterID int, messages []tg.MessageClass) (provider.ChatReply, bool) { for _, entity := range messages { msg, ok := entity.(*tg.Message) if !ok || msg.ID <= afterID || msg.Out { continue } buttons := buttonsOf(msg) - if len(buttons) == 0 { + text := strings.TrimSpace(msg.Message) + if text == "" && len(buttons) == 0 { continue } + if len(buttons) == 0 { + return provider.ChatReply{}, false + } return provider.ChatReply{ Kind: "text", - Text: strings.TrimSpace(msg.Message), + Text: text, From: senderOf(msg), MessageID: msg.ID, Buttons: buttons, diff --git a/external/telegram/write_test.go b/external/telegram/write_test.go index 093d05214..e6e5e23a8 100644 --- a/external/telegram/write_test.go +++ b/external/telegram/write_test.go @@ -452,3 +452,29 @@ func TestWaitReplyRestartsGraceForANewMessageWithTheSameText(t *testing.T) { t.Fatalf("returned %v after the newer message, want a restarted grace period", since) } } + +func TestWaitReplyPrefersNewerTextOverOlderKeyboard(t *testing.T) { + keyboard := &tg.Message{ + ID: 7, + Message: "Menu", + ReplyMarkup: &tg.ReplyInlineMarkup{Rows: []tg.KeyboardInlineButtonRow{{ + Buttons: []tg.KeyboardInlineButton{{ + Text: "FLAC", + Type: &tg.InlineButtonTypeCallback{Data: []byte("flac")}, + }}, + }}}, + } + text := &tg.Message{ID: 8, Message: "Track not found"} + api := &fakeWriteAPI{history: []tg.MessagesMessagesClass{ + &tg.MessagesMessages{Messages: []tg.MessageClass{text, keyboard}}, + }} + p := readyProvider(api) + + reply, err := p.WaitReply(context.Background(), "u:1:2", 5, 100*time.Millisecond) + if err != nil { + t.Fatalf("WaitReply: %v", err) + } + if reply.Kind != "text" || reply.Text != "Track not found" { + t.Fatalf("reply = %#v, want the newer text", reply) + } +} diff --git a/lua_wiring.go b/lua_wiring.go index 3a3aae169..53460ab1c 100644 --- a/lua_wiring.go +++ b/lua_wiring.go @@ -218,6 +218,9 @@ func luaProviderProvider(entries []provider.Entry, load func() model.PluginState if send == nil { return fmt.Errorf("ui: not available") } + if current := load().Provider.Name; current != "" && info.Name != "" && !strings.EqualFold(current, info.Name) { + return fmt.Errorf("provider.open: switch to %s first", info.Name) + } send(model.PluginOpenProviderMsg{ ProviderName: info.Name, Playlist: playlist.PlaylistInfo{ @@ -414,6 +417,11 @@ func waitReplyResult(ctx context.Context, commander provider.ChatCommander, chat timeout := 20 * time.Second if seconds, ok := params["timeout"].(float64); ok && seconds > 0 { timeout = time.Duration(seconds * float64(time.Second)) + } else if deadline, ok := ctx.Deadline(); ok { + timeout = time.Until(deadline) + if timeout <= 0 { + timeout = time.Millisecond + } } var ( reply provider.ChatReply diff --git a/lua_wiring_test.go b/lua_wiring_test.go index 6999b3f14..b87a99a43 100644 --- a/lua_wiring_test.go +++ b/lua_wiring_test.go @@ -201,15 +201,18 @@ type fakeChatCommander struct { provider.ChatCommander replyCalled bool audioCalled bool + timeout time.Duration } -func (f *fakeChatCommander) WaitReply(context.Context, string, int, time.Duration) (provider.ChatReply, error) { +func (f *fakeChatCommander) WaitReply(_ context.Context, _ string, _ int, timeout time.Duration) (provider.ChatReply, error) { f.replyCalled = true + f.timeout = timeout return provider.ChatReply{Kind: "text"}, nil } -func (f *fakeChatCommander) WaitAudio(context.Context, string, int, time.Duration) (provider.ChatReply, error) { +func (f *fakeChatCommander) WaitAudio(_ context.Context, _ string, _ int, timeout time.Duration) (provider.ChatReply, error) { f.audioCalled = true + f.timeout = timeout return provider.ChatReply{Kind: "audio"}, nil } @@ -226,3 +229,15 @@ func TestWaitReplyResultHonorsAudioOnly(t *testing.T) { t.Fatalf("kind = %v", out["kind"]) } } + +func TestWaitReplyResultUsesContextDeadline(t *testing.T) { + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) + defer cancel() + f := &fakeChatCommander{} + if _, err := waitReplyResult(ctx, f, "u:1:2", 5, nil); err != nil { + t.Fatalf("waitReplyResult: %v", err) + } + if f.timeout < time.Second || f.timeout > 2*time.Second { + t.Fatalf("timeout = %v, want the remaining context deadline", f.timeout) + } +} diff --git a/luaplugin/api_provider.go b/luaplugin/api_provider.go index bba442f91..2456dc524 100644 --- a/luaplugin/api_provider.go +++ b/luaplugin/api_provider.go @@ -41,7 +41,7 @@ func providerWrites(action string) bool { return false } switch strings.ToLower(verb) { - case "send", "ask", "reply", "callback", "send_inline", "add_chat": + case "send", "ask", "callback", "send_inline", "add_chat": return true } return false diff --git a/luaplugin/api_provider_test.go b/luaplugin/api_provider_test.go index 6f6c85ff9..cca8b07d4 100644 --- a/luaplugin/api_provider_test.go +++ b/luaplugin/api_provider_test.go @@ -193,3 +193,25 @@ func TestProviderCallSyncUsesTimeout(t *testing.T) { t.Errorf("err = %q", got) } } + +func TestProviderCallReplyIsRead(t *testing.T) { + m := newTestManager() + called := false + m.SetProviderProvider(ProviderProvider{ + Call: func(context.Context, string, map[string]any) (map[string]any, error) { + called = true + return map[string]any{"kind": "text"}, nil + }, + }) + loadTestPlugin(t, m, "provider-reply", ` + local p = plugin.register({name = "provider-reply", type = "hook", permissions = {"provider"}}) + local res = cliamp.provider.call("telegram.reply", {chat = "u:1:2", after = 5}) + _G.kind = res.kind + `) + if !called { + t.Fatal("telegram.reply should be callable with only the provider permission") + } + if got := m.plugins[0].L.GetGlobal("kind").String(); got != "text" { + t.Errorf("kind = %q", got) + } +} diff --git a/plugins/telegram-bot.lua b/plugins/telegram-bot.lua index a40430864..3405badb4 100644 --- a/plugins/telegram-bot.lua +++ b/plugins/telegram-bot.lua @@ -194,12 +194,24 @@ p:command("commands", function(args) return table.concat(out, "\n") end) +local function canonical_chat(chat) + if chat:match("^u:") or chat:match("^c:") or chat:match("^ch:") then + return chat + end + local info = cliamp.provider.call("telegram.resolve", {username = chat}) + if info and info.id and info.id ~= "" then + return info.id + end + return chat +end + p:command("ask", function(args) local chat = args[1] local text = table.concat(args, " ", 2) if not chat or chat == "" or text == "" then return "usage: ask " end + chat = canonical_chat(chat) local token = reserve(chat) if not token then return "busy: wait for the bot to finish this chat" diff --git a/ui/model/action_pane.go b/ui/model/action_pane.go index 081f45205..5a2f5679d 100644 --- a/ui/model/action_pane.go +++ b/ui/model/action_pane.go @@ -34,7 +34,7 @@ func (m *Model) openActionPane() { if m.provider != nil { providerName = m.provider.Name() } - chatOpen := m.activeProviderPlaylistID != "" + chatOpen := m.activeProviderPlaylistID != "" && m.focus != focusProvider available := make([]luaplugin.Action, 0, len(entries)) for _, action := range entries { if action.Provider != "" && !strings.EqualFold(action.Provider, providerName) { diff --git a/ui/model/action_pane_test.go b/ui/model/action_pane_test.go index 341b51f16..4b370edb4 100644 --- a/ui/model/action_pane_test.go +++ b/ui/model/action_pane_test.go @@ -204,3 +204,38 @@ p:action{key = "!", id = "chats", label = "Chats action", context = "chats", on_ t.Fatalf("chat pane = %#v", m.actionPane.filtered) } } + +func TestActionPaneUsesVisibleProviderListForContext(t *testing.T) { + m := Model{luaMgr: nil} + // Use a manager so the pane has actions to filter. + configDir := t.TempDir() + t.Setenv("CLIAMP_CONFIG_DIR", configDir) + pluginDir := filepath.Join(configDir, "plugins") + if err := os.MkdirAll(pluginDir, 0o755); err != nil { + t.Fatal(err) + } + pluginPath := filepath.Join(pluginDir, "action-visible.lua") + script := ` +local p = plugin.register({name = "action-visible", type = "hook", permissions = {"ui"}}) +p:action{key = "!", id = "chat", label = "Chat action", context = "chat", on_submit = function() end} +p:action{key = "!", id = "chats", label = "Chats action", context = "chats", on_submit = function() end} +` + if err := os.WriteFile(pluginPath, []byte(script), 0o644); err != nil { + t.Fatal(err) + } + if _, err := plugintrust.Approve(pluginDir, "action-visible", pluginPath); err != nil { + t.Fatal(err) + } + mgr, err := luaplugin.New(nil, nil, ReservedKeys()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(sync.OnceFunc(mgr.Close)) + m.luaMgr = mgr + m.activeProviderPlaylistID = "u:1:2" + m.focus = focusProvider + m.openActionPane() + if len(m.actionPane.filtered) != 1 || m.actionPane.filtered[0].Label != "Chats action" { + t.Fatalf("provider list pane = %#v", m.actionPane.filtered) + } +} diff --git a/ui/model/lua_modal.go b/ui/model/lua_modal.go index 54167e794..86c127b31 100644 --- a/ui/model/lua_modal.go +++ b/ui/model/lua_modal.go @@ -146,7 +146,11 @@ func (m Model) renderLuaSelect() string { if i > start { b.WriteString("\n") } - for _, line := range imageLines(option.Image) { + lines := imageLines(option.Image) + if budget := maxRows - (linesOf(option) - len(lines)); len(lines) > budget { + lines = lines[:max(0, budget)] + } + for _, line := range lines { b.WriteString(" " + line + imageResetSuffix() + "\n") } marker := " " diff --git a/ui/model/model.go b/ui/model/model.go index f5c2de865..6d8059dc9 100644 --- a/ui/model/model.go +++ b/ui/model/model.go @@ -463,6 +463,11 @@ type Model struct { // from a non-local provider (Spotify, Navidrome, …). Used to highlight that // row in the provider browser. Empty when no provider playlist is active. activeProviderPlaylistID string + // providerOpenPrevID is the playlist that was open before a provider row + // started loading. It restores the highlight and action context when the + // load fails. + providerOpenPrevID string + providerOpenPrevSet bool // radioListeners holds live listener counts per cliamp radio channel slug. // Nil means unknown: the fetch never ran or failed, and rows show no diff --git a/ui/model/plugin_open.go b/ui/model/plugin_open.go index 9a57e0f3e..5b2eebd96 100644 --- a/ui/model/plugin_open.go +++ b/ui/model/plugin_open.go @@ -31,6 +31,8 @@ func (m *Model) handlePluginOpenProvider(msg PluginOpenProviderMsg) tea.Cmd { m.provPane.cursor = len(m.provPane.lists) - 1 } m.provPane.loading = true + m.providerOpenPrevID = m.activeProviderPlaylistID + m.providerOpenPrevSet = true m.activeProviderPlaylistID = msg.Playlist.ID m.focus = focusPlaylist m.applyHeightMode() diff --git a/ui/model/providers.go b/ui/model/providers.go index 1b257303c..349cea696 100644 --- a/ui/model/providers.go +++ b/ui/model/providers.go @@ -639,6 +639,7 @@ func (m *Model) openProviderList(index int) tea.Cmd { } if entry, ok := providerBrowseEntryForID(m.provider, item.ID); ok { m.activeProviderPlaylistID = "" + m.providerOpenPrevSet = false cmd := m.openNavBrowserEntry(m.provider, entry) if m.navBrowser.visible { m.navBrowser.fromProvList = true @@ -646,6 +647,8 @@ func (m *Model) openProviderList(index int) tea.Cmd { return cmd } m.provPane.loading = true + m.providerOpenPrevID = m.activeProviderPlaylistID + m.providerOpenPrevSet = true m.activeProviderPlaylistID = item.ID cmd := m.fetchProviderTracks(item.ID) if _, ok := m.provider.(*radio.ChannelProvider); ok { diff --git a/ui/model/update_provider.go b/ui/model/update_provider.go index aa966579c..f71da4aaf 100644 --- a/ui/model/update_provider.go +++ b/ui/model/update_provider.go @@ -75,6 +75,10 @@ func (m *Model) handleTracksLoaded(msg tracksLoadedMsg) tea.Cmd { m.provPane.loading = false m.tracksPaging = msg.err == nil && msg.next > 0 if msg.err != nil { + if msg.offset == 0 && m.providerOpenPrevSet { + m.activeProviderPlaylistID = m.providerOpenPrevID + m.providerOpenPrevSet = false + } if errors.Is(msg.err, playlist.ErrNeedsAuth) { m.provPane.signIn = true m.err = nil @@ -91,6 +95,9 @@ func (m *Model) handleTracksLoaded(msg tracksLoadedMsg) tea.Cmd { m.err = withRetryHint(msg.err) return nil } + if msg.offset == 0 { + m.providerOpenPrevSet = false + } if msg.offset > 0 { m.playlist.Add(msg.tracks...) m.normalizeQueueOverlay() From 2ae58838f2c9026b04e90466751dfade944695dd Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 05:39:34 -0300 Subject: [PATCH 26/28] fix(plugins): close the last provider-context review Serialize the chats-filter read-modify-write, include switch_inline queries in button payloads, tag input suggestions with the query they belong to, and keep the first rollback id when provider opens overlap. The reply grace already restarts for a new message with the same text. --- lua_wiring.go | 26 ++++++++++++++++++++------ lua_wiring_test.go | 16 ++++++++++++++++ ui/model/lua_input.go | 3 +++ ui/model/lua_input_test.go | 21 +++++++++++++++++++++ ui/model/plugin_open.go | 6 ++++-- ui/model/providers.go | 6 ++++-- ui/model/update.go | 2 +- 7 files changed, 69 insertions(+), 11 deletions(-) diff --git a/lua_wiring.go b/lua_wiring.go index 53460ab1c..01b8c801d 100644 --- a/lua_wiring.go +++ b/lua_wiring.go @@ -144,13 +144,14 @@ func newOrderedSender(send func(tea.Msg)) (queue func(tea.Msg), stop func()) { // luaUIProvider lets Lua plugins show a status message. func luaUIProvider(send func(tea.Msg), headless bool) luaplugin.UIProvider { + var inputQuery string return luaplugin.UIProvider{ ShowMessage: func(text string, duration time.Duration) { send(model.ShowStatusMsg{Text: text, Duration: duration}) }, ShowSelect: showSelectFor(send, headless), - ShowInput: showInputFor(send, headless), - UpdateInput: updateInputFor(send, headless), + ShowInput: showInputFor(send, headless, &inputQuery), + UpdateInput: updateInputFor(send, headless, &inputQuery), ShowText: showTextFor(send, headless), SetVis: func(name string) { send(model.SetVisMsg{Name: name}) @@ -170,17 +171,24 @@ func showTextFor(send func(tea.Msg), headless bool) func(string, string, func()) } } -func showInputFor(send func(tea.Msg), headless bool) func(string, string, string, []luaplugin.SelectOption, func(string), func(string), func(int), func()) { +func showInputFor(send func(tea.Msg), headless bool, current *string) func(string, string, string, []luaplugin.SelectOption, func(string), func(string), func(int), func()) { if headless { return nil } return func(title, placeholder, value string, suggestions []luaplugin.SelectOption, onChange, onSubmit func(string), onSelect func(int), onCancel func()) { + *current = value + update := func(text string) { + *current = text + if onChange != nil { + onChange(text) + } + } send(model.LuaInputMsg{ Title: title, Placeholder: placeholder, Value: value, Suggestions: suggestions, - OnChange: onChange, + OnChange: update, OnSubmit: onSubmit, OnSelect: onSelect, OnCancel: onCancel, @@ -188,12 +196,12 @@ func showInputFor(send func(tea.Msg), headless bool) func(string, string, string } } -func updateInputFor(send func(tea.Msg), headless bool) func([]luaplugin.SelectOption, bool) { +func updateInputFor(send func(tea.Msg), headless bool, current *string) func([]luaplugin.SelectOption, bool) { if headless { return nil } return func(options []luaplugin.SelectOption, live bool) { - send(model.LuaInputSuggestionsMsg{Options: options, Live: live}) + send(model.LuaInputSuggestionsMsg{Options: options, Live: live, Query: *current}) } } @@ -212,6 +220,7 @@ func showSelectFor(send func(tea.Msg), headless bool) func(string, string, []lua // The provider call runs on the caller's goroutine, so a blocking reply never // holds the UI. func luaProviderProvider(entries []provider.Entry, load func() model.PluginState, send func(tea.Msg)) luaplugin.ProviderProvider { + var addChatMu sync.Mutex return luaplugin.ProviderProvider{ Current: func() luaplugin.ProviderInfo { return load().Provider }, Open: func(info luaplugin.ProviderInfo) error { @@ -295,6 +304,8 @@ func luaProviderProvider(entries []provider.Entry, load func() model.PluginState "section": info.Section, }, nil case "add_chat": + addChatMu.Lock() + defer addChatMu.Unlock() filter, ok := prov.(provider.ChatFilter) if !ok { return nil, fmt.Errorf("provider %q has no chat filter", name) @@ -406,6 +417,9 @@ func replyResult(reply provider.ChatReply) map[string]any { if button.SendText { row["send_text"] = true } + if button.Query != "" { + row["query"] = button.Query + } buttons = append(buttons, row) } out["buttons"] = buttons diff --git a/lua_wiring_test.go b/lua_wiring_test.go index b87a99a43..c5e797210 100644 --- a/lua_wiring_test.go +++ b/lua_wiring_test.go @@ -241,3 +241,19 @@ func TestWaitReplyResultUsesContextDeadline(t *testing.T) { t.Fatalf("timeout = %v, want the remaining context deadline", f.timeout) } } + +func TestReplyResultIncludesButtonQuery(t *testing.T) { + out := replyResult(provider.ChatReply{Buttons: []provider.ChatButton{{ + Text: "Switch", + Kind: "switch_inline", + Query: "daft punk", + }}}) + buttons, ok := out["buttons"].([]any) + if !ok || len(buttons) != 1 { + t.Fatalf("buttons = %#v", out["buttons"]) + } + row, ok := buttons[0].(map[string]any) + if !ok || row["query"] != "daft punk" { + t.Fatalf("row = %#v, want query", buttons[0]) + } +} diff --git a/ui/model/lua_input.go b/ui/model/lua_input.go index a355dd5b8..454711099 100644 --- a/ui/model/lua_input.go +++ b/ui/model/lua_input.go @@ -30,6 +30,9 @@ type LuaInputMsg struct { type LuaInputSuggestionsMsg struct { Options []luaplugin.SelectOption Live bool + // Query is the text the results belong to. A message for an older query + // is ignored after the input changed. + Query string } // luaInputState is the open plugin input. diff --git a/ui/model/lua_input_test.go b/ui/model/lua_input_test.go index 452103fe7..73f62f905 100644 --- a/ui/model/lua_input_test.go +++ b/ui/model/lua_input_test.go @@ -200,3 +200,24 @@ func TestLuaInputWindowFollowsCursor(t *testing.T) { t.Fatalf("cursor is not visible at the end of a long value:\n%s", box) } } + +func TestLuaInputIgnoresSuggestionsForAnOldQuery(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "new", nil, nil, nil, nil, nil) + m.Update(LuaInputSuggestionsMsg{ + Query: "old", + Options: []luaplugin.SelectOption{{Title: "Stale"}}, + Live: true, + }) + if len(m.luaInput.suggestions) != 0 { + t.Fatalf("stale suggestions were installed: %#v", m.luaInput.suggestions) + } + m.Update(LuaInputSuggestionsMsg{ + Query: "new", + Options: []luaplugin.SelectOption{{Title: "Fresh"}}, + Live: true, + }) + if len(m.luaInput.suggestions) != 1 || m.luaInput.suggestions[0].Title != "Fresh" { + t.Fatalf("fresh suggestions were not installed: %#v", m.luaInput.suggestions) + } +} diff --git a/ui/model/plugin_open.go b/ui/model/plugin_open.go index 5b2eebd96..4a0385051 100644 --- a/ui/model/plugin_open.go +++ b/ui/model/plugin_open.go @@ -31,8 +31,10 @@ func (m *Model) handlePluginOpenProvider(msg PluginOpenProviderMsg) tea.Cmd { m.provPane.cursor = len(m.provPane.lists) - 1 } m.provPane.loading = true - m.providerOpenPrevID = m.activeProviderPlaylistID - m.providerOpenPrevSet = true + if !m.providerOpenPrevSet { + m.providerOpenPrevID = m.activeProviderPlaylistID + m.providerOpenPrevSet = true + } m.activeProviderPlaylistID = msg.Playlist.ID m.focus = focusPlaylist m.applyHeightMode() diff --git a/ui/model/providers.go b/ui/model/providers.go index 349cea696..413a79250 100644 --- a/ui/model/providers.go +++ b/ui/model/providers.go @@ -647,8 +647,10 @@ func (m *Model) openProviderList(index int) tea.Cmd { return cmd } m.provPane.loading = true - m.providerOpenPrevID = m.activeProviderPlaylistID - m.providerOpenPrevSet = true + if !m.providerOpenPrevSet { + m.providerOpenPrevID = m.activeProviderPlaylistID + m.providerOpenPrevSet = true + } m.activeProviderPlaylistID = item.ID cmd := m.fetchProviderTracks(item.ID) if _, ok := m.provider.(*radio.ChannelProvider); ok { diff --git a/ui/model/update.go b/ui/model/update.go index a0e6b1578..bd32016c2 100644 --- a/ui/model/update.go +++ b/ui/model/update.go @@ -126,7 +126,7 @@ func (m Model) update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil case LuaInputSuggestionsMsg: - if m.luaInput == nil { + if m.luaInput == nil || msg.Query != m.luaInput.value { return m, nil } if len(msg.Options) != len(m.luaInput.suggestions) { From 8d3ec28eba5af4d784db5b7c037da1278c1e078f Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 05:56:04 -0300 Subject: [PATCH 27/28] fix(plugins): carry the query with suggestions and surface queue errors Pass the query that produced suggestions through the Lua UI API, drop stale results, serialize the chats filter, include switch_inline queries, keep the first rollback id across overlapping opens, clear it on provider switch, and report queue insertion failures in the generic bot plugin. A plain-query ask now keeps its busy reservation until the audio follow-up finishes; slash commands keep the menu behavior. --- docs/plugins.md | 3 +++ lua_wiring.go | 22 +++++++--------------- luaplugin/api_ui.go | 4 +++- luaplugin/api_ui_test.go | 2 +- luaplugin/luaplugin.go | 3 ++- plugins/telegram-bot.lua | 38 ++++++++++++++++++++++++++++---------- ui/model/providers.go | 1 + ui/model/update.go | 2 +- 8 files changed, 46 insertions(+), 29 deletions(-) diff --git a/docs/plugins.md b/docs/plugins.md index 865d08609..dbd0146e2 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -803,6 +803,9 @@ the list under it. This is how a plugin turns the input into a live search or a command palette. `live = true` (the default) marks the rows as results: `Enter` selects one and calls `on_select` instead of submitting the typed text. `live = false` makes them plain suggestions again, so `Enter` submits the text. +Pass `query = "..."` with the text the results belong to; cliamp drops a result +for a query the input has already left. Without `query`, newer results apply to +the current input. ```lua cliamp.ui.text{ diff --git a/lua_wiring.go b/lua_wiring.go index 01b8c801d..47e4a8bf6 100644 --- a/lua_wiring.go +++ b/lua_wiring.go @@ -144,14 +144,13 @@ func newOrderedSender(send func(tea.Msg)) (queue func(tea.Msg), stop func()) { // luaUIProvider lets Lua plugins show a status message. func luaUIProvider(send func(tea.Msg), headless bool) luaplugin.UIProvider { - var inputQuery string return luaplugin.UIProvider{ ShowMessage: func(text string, duration time.Duration) { send(model.ShowStatusMsg{Text: text, Duration: duration}) }, ShowSelect: showSelectFor(send, headless), - ShowInput: showInputFor(send, headless, &inputQuery), - UpdateInput: updateInputFor(send, headless, &inputQuery), + ShowInput: showInputFor(send, headless), + UpdateInput: updateInputFor(send, headless), ShowText: showTextFor(send, headless), SetVis: func(name string) { send(model.SetVisMsg{Name: name}) @@ -171,24 +170,17 @@ func showTextFor(send func(tea.Msg), headless bool) func(string, string, func()) } } -func showInputFor(send func(tea.Msg), headless bool, current *string) func(string, string, string, []luaplugin.SelectOption, func(string), func(string), func(int), func()) { +func showInputFor(send func(tea.Msg), headless bool) func(string, string, string, []luaplugin.SelectOption, func(string), func(string), func(int), func()) { if headless { return nil } return func(title, placeholder, value string, suggestions []luaplugin.SelectOption, onChange, onSubmit func(string), onSelect func(int), onCancel func()) { - *current = value - update := func(text string) { - *current = text - if onChange != nil { - onChange(text) - } - } send(model.LuaInputMsg{ Title: title, Placeholder: placeholder, Value: value, Suggestions: suggestions, - OnChange: update, + OnChange: onChange, OnSubmit: onSubmit, OnSelect: onSelect, OnCancel: onCancel, @@ -196,12 +188,12 @@ func showInputFor(send func(tea.Msg), headless bool, current *string) func(strin } } -func updateInputFor(send func(tea.Msg), headless bool, current *string) func([]luaplugin.SelectOption, bool) { +func updateInputFor(send func(tea.Msg), headless bool) func([]luaplugin.SelectOption, bool, string) { if headless { return nil } - return func(options []luaplugin.SelectOption, live bool) { - send(model.LuaInputSuggestionsMsg{Options: options, Live: live, Query: *current}) + return func(options []luaplugin.SelectOption, live bool, query string) { + send(model.LuaInputSuggestionsMsg{Options: options, Live: live, Query: query}) } } diff --git a/luaplugin/api_ui.go b/luaplugin/api_ui.go index 4125a1108..db28ad0b6 100644 --- a/luaplugin/api_ui.go +++ b/luaplugin/api_ui.go @@ -158,16 +158,18 @@ func registerUIAPI(L *lua.LState, cliamp *lua.LTable, p *Plugin, m *Manager) { } options := parseSelectOptions(L, L.Get(1)) live := true + query := "" if opts, ok := L.Get(2).(*lua.LTable); ok { if value, ok := opts.RawGetString("live").(lua.LBool); ok { live = bool(value) } + query = rawString(L, opts, "query") } up := m.ui.Load() if up == nil || up.UpdateInput == nil { return pushErr(L, "ui: not available") } - up.UpdateInput(options, live) + up.UpdateInput(options, live, query) L.Push(lua.LTrue) return 1 })) diff --git a/luaplugin/api_ui_test.go b/luaplugin/api_ui_test.go index 80c045060..8a425d677 100644 --- a/luaplugin/api_ui_test.go +++ b/luaplugin/api_ui_test.go @@ -82,7 +82,7 @@ func TestUISuggestionsPassesImage(t *testing.T) { m := newTestManager() var got []SelectOption m.SetUIProvider(UIProvider{ - UpdateInput: func(options []SelectOption, live bool) { + UpdateInput: func(options []SelectOption, live bool, query string) { got = options }, }) diff --git a/luaplugin/luaplugin.go b/luaplugin/luaplugin.go index 3674cc92b..abb3c81fe 100644 --- a/luaplugin/luaplugin.go +++ b/luaplugin/luaplugin.go @@ -152,7 +152,8 @@ type UIProvider struct { ShowInput func(title, placeholder, value string, suggestions []SelectOption, onChange func(text string), onSubmit func(text string), onSelect func(index int), onCancel func()) // UpdateInput replaces the suggestions of the open input. live means the // rows are search results that Enter selects, not command completions. - UpdateInput func(options []SelectOption, live bool) + // query is the text the results belong to, when the plugin reports it. + UpdateInput func(options []SelectOption, live bool, query string) // ShowText opens a scrollable text panel. It must return at once. ShowText func(title, text string, onClose func()) // SetVis switches the active visualizer by name. It must return at once: the diff --git a/plugins/telegram-bot.lua b/plugins/telegram-bot.lua index 3405badb4..db2f51d2c 100644 --- a/plugins/telegram-bot.lua +++ b/plugins/telegram-bot.lua @@ -80,7 +80,11 @@ end local function insert_audio(reply) if reply and reply.kind == "audio" and reply.track then - cliamp.queue.insert(0, reply.track) + local ok, err = cliamp.queue.insert(0, reply.track) + if not ok then + cliamp.message("Telegram: " .. tostring(err or "could not queue the track"), 8) + return false + end cliamp.message("Added: " .. reply.track.title, 5) return true end @@ -95,14 +99,14 @@ local function wait_audio(chat, afterID, token) audio_only = true, }, { on_reply = function(reply, err) - if not insert_audio(reply) then - if err then - cliamp.message("Telegram: " .. tostring(err), 8) - elseif reply and reply.kind == "text" and reply.text and reply.text ~= "" then - cliamp.message(reply.text, 8) - else - cliamp.message("No audio yet. Ctrl+R to reload.", 5) - end + if reply and reply.kind == "audio" then + insert_audio(reply) + elseif err then + cliamp.message("Telegram: " .. tostring(err), 8) + elseif reply and reply.kind == "text" and reply.text and reply.text ~= "" then + cliamp.message(reply.text, 8) + else + cliamp.message("No audio yet. Ctrl+R to reload.", 5) end finish(chat, token) end, @@ -116,7 +120,8 @@ local function add_reply(chat, reply, err, waitForAudio, token) finish(chat, token) return end - if insert_audio(reply) then + if reply.kind == "audio" then + insert_audio(reply) finish(chat, token) return end @@ -221,6 +226,19 @@ p:command("ask", function(args) text = text, timeout = 60, }) + if reply and reply.kind == "text" and text:sub(1, 1) ~= "/" and reply.message_id and reply.message_id > 0 then + -- A plain query can return "Downloading..." before the audio. Keep + -- the reservation until the audio arrives or the follow-up times out. + local audio = cliamp.provider.call("telegram.reply", { + chat = chat, + after = reply.message_id, + timeout = 20, + audio_only = true, + }) + if audio and audio.kind == "audio" then + reply = audio + end + end finish(chat, token) if not reply then return "error: " .. tostring(err) diff --git a/ui/model/providers.go b/ui/model/providers.go index 413a79250..0ab8c8fdb 100644 --- a/ui/model/providers.go +++ b/ui/model/providers.go @@ -60,6 +60,7 @@ func (m *Model) switchProvider(idx int) tea.Cmd { m.provPane.signIn = false m.catalogBatch = catalogBatchState{} m.activeProviderPlaylistID = "" + m.providerOpenPrevSet = false m.resetProviderNav() m.focus = focusProvider // The Local source shows the playlist manager instead of the old diff --git a/ui/model/update.go b/ui/model/update.go index bd32016c2..f9b256091 100644 --- a/ui/model/update.go +++ b/ui/model/update.go @@ -126,7 +126,7 @@ func (m Model) update(msg tea.Msg) (tea.Model, tea.Cmd) { return m, nil case LuaInputSuggestionsMsg: - if m.luaInput == nil || msg.Query != m.luaInput.value { + if m.luaInput == nil || (msg.Query != "" && msg.Query != m.luaInput.value) { return m, nil } if len(msg.Options) != len(m.luaInput.suggestions) { From a101252c1b66550321474845ab0e1387348e40b0 Mon Sep 17 00:00:00 2001 From: Charlyls Date: Mon, 16 Nov 2026 08:12:22 -0300 Subject: [PATCH 28/28] fix(plugins): bind suggestions to the input token and query presence Return a token from ui.input, carry it through ui.suggestions, and reject rows for another input even when the query is omitted. Track whether query was provided so an explicit empty query is compared too. Update the live-search plugin to pass its token and query, and document both. --- docs/plugins.md | 13 ++++++----- lua_wiring.go | 23 ++++++++++++++----- luaplugin/api_ui.go | 18 +++++++++++---- luaplugin/api_ui_test.go | 5 +++-- luaplugin/luaplugin.go | 4 ++-- ui/model/lua_input.go | 10 ++++++--- ui/model/lua_input_test.go | 46 ++++++++++++++++++++++++++++++++++---- ui/model/update.go | 6 ++++- 8 files changed, 98 insertions(+), 27 deletions(-) diff --git a/docs/plugins.md b/docs/plugins.md index dbd0146e2..0ef29a5a1 100644 --- a/docs/plugins.md +++ b/docs/plugins.md @@ -795,17 +795,20 @@ cliamp.ui.input{ `ui.input` asks for one line of text. `Enter` calls `on_submit` with the text; `Esc` calls `on_cancel` when given. `on_change` runs on every edit and -`on_select` runs when `Enter` picks a live suggestion. It returns true when the -request was accepted; headless mode returns an error. +`on_select` runs when `Enter` picks a live suggestion. It returns `true, token` +when the request was accepted; keep that token for `cliamp.ui.suggestions`. +Headless mode returns an error. While an input is open, `cliamp.ui.suggestions(options, {live = true})` replaces the list under it. This is how a plugin turns the input into a live search or a command palette. `live = true` (the default) marks the rows as results: `Enter` selects one and calls `on_select` instead of submitting the typed text. `live = false` makes them plain suggestions again, so `Enter` submits the text. -Pass `query = "..."` with the text the results belong to; cliamp drops a result -for a query the input has already left. Without `query`, newer results apply to -the current input. +Pass `query = "..."` with the text the results belong to and `token` from the +matching `ui.input` call; cliamp drops a result for a query or input that has +already been replaced. An empty `query` is compared too: only omit it when the +results are not tied to the text. Without `token`, newer results apply to the +most recent input from that plugin. ```lua cliamp.ui.text{ diff --git a/lua_wiring.go b/lua_wiring.go index 47e4a8bf6..d7a88a889 100644 --- a/lua_wiring.go +++ b/lua_wiring.go @@ -6,6 +6,7 @@ import ( "fmt" "strings" "sync" + "sync/atomic" "time" tea "charm.land/bubbletea/v2" @@ -144,12 +145,13 @@ func newOrderedSender(send func(tea.Msg)) (queue func(tea.Msg), stop func()) { // luaUIProvider lets Lua plugins show a status message. func luaUIProvider(send func(tea.Msg), headless bool) luaplugin.UIProvider { + var inputSeq atomic.Uint64 return luaplugin.UIProvider{ ShowMessage: func(text string, duration time.Duration) { send(model.ShowStatusMsg{Text: text, Duration: duration}) }, ShowSelect: showSelectFor(send, headless), - ShowInput: showInputFor(send, headless), + ShowInput: showInputFor(send, headless, &inputSeq), UpdateInput: updateInputFor(send, headless), ShowText: showTextFor(send, headless), SetVis: func(name string) { @@ -170,12 +172,14 @@ func showTextFor(send func(tea.Msg), headless bool) func(string, string, func()) } } -func showInputFor(send func(tea.Msg), headless bool) func(string, string, string, []luaplugin.SelectOption, func(string), func(string), func(int), func()) { +func showInputFor(send func(tea.Msg), headless bool, seq *atomic.Uint64) func(string, string, string, []luaplugin.SelectOption, func(string), func(string), func(int), func()) uint64 { if headless { return nil } - return func(title, placeholder, value string, suggestions []luaplugin.SelectOption, onChange, onSubmit func(string), onSelect func(int), onCancel func()) { + return func(title, placeholder, value string, suggestions []luaplugin.SelectOption, onChange, onSubmit func(string), onSelect func(int), onCancel func()) uint64 { + token := seq.Add(1) send(model.LuaInputMsg{ + Token: token, Title: title, Placeholder: placeholder, Value: value, @@ -185,15 +189,22 @@ func showInputFor(send func(tea.Msg), headless bool) func(string, string, string OnSelect: onSelect, OnCancel: onCancel, }) + return token } } -func updateInputFor(send func(tea.Msg), headless bool) func([]luaplugin.SelectOption, bool, string) { +func updateInputFor(send func(tea.Msg), headless bool) func([]luaplugin.SelectOption, bool, string, bool, uint64) { if headless { return nil } - return func(options []luaplugin.SelectOption, live bool, query string) { - send(model.LuaInputSuggestionsMsg{Options: options, Live: live, Query: query}) + return func(options []luaplugin.SelectOption, live bool, query string, querySet bool, token uint64) { + send(model.LuaInputSuggestionsMsg{ + Token: token, + Options: options, + Live: live, + Query: query, + QuerySet: querySet, + }) } } diff --git a/luaplugin/api_ui.go b/luaplugin/api_ui.go index db28ad0b6..7304ce29a 100644 --- a/luaplugin/api_ui.go +++ b/luaplugin/api_ui.go @@ -49,6 +49,7 @@ func parseSelectOptions(L *lua.LState, value lua.LValue) []SelectOption { // Gated on permissions = {"ui"}. func registerUIAPI(L *lua.LState, cliamp *lua.LTable, p *Plugin, m *Manager) { tbl := L.NewTable() + var inputToken uint64 // cliamp.ui.select{title = "...", options = {"a", "b"}, on_select = fn} L.SetField(tbl, "select", L.NewFunction(func(L *lua.LState) int { @@ -140,13 +141,14 @@ func registerUIAPI(L *lua.LState, cliamp *lua.LTable, p *Plugin, m *Manager) { }) } } - up.ShowInput(title, placeholder, value, suggestions, onChange, func(text string) { + inputToken = up.ShowInput(title, placeholder, value, suggestions, onChange, func(text string) { m.enqueue(p, "ui.input", func() { m.call(p, "ui.input", hookTimeout, 0, fixedArgs(fn, lua.LString(text))) }) }, onSelect, onCancel) L.Push(lua.LTrue) - return 1 + L.Push(lua.LNumber(inputToken)) + return 2 })) // cliamp.ui.suggestions(options, {live = true}) replaces the list under the @@ -159,17 +161,25 @@ func registerUIAPI(L *lua.LState, cliamp *lua.LTable, p *Plugin, m *Manager) { options := parseSelectOptions(L, L.Get(1)) live := true query := "" + querySet := false + token := inputToken if opts, ok := L.Get(2).(*lua.LTable); ok { if value, ok := opts.RawGetString("live").(lua.LBool); ok { live = bool(value) } - query = rawString(L, opts, "query") + if value := opts.RawGetString("query"); value != lua.LNil { + querySet = true + query = strings.TrimSpace(value.String()) + } + if value, ok := opts.RawGetString("token").(lua.LNumber); ok { + token = uint64(value) + } } up := m.ui.Load() if up == nil || up.UpdateInput == nil { return pushErr(L, "ui: not available") } - up.UpdateInput(options, live, query) + up.UpdateInput(options, live, query, querySet, token) L.Push(lua.LTrue) return 1 })) diff --git a/luaplugin/api_ui_test.go b/luaplugin/api_ui_test.go index 8a425d677..af1456218 100644 --- a/luaplugin/api_ui_test.go +++ b/luaplugin/api_ui_test.go @@ -6,9 +6,10 @@ func TestUIInputPassesSuggestions(t *testing.T) { m := newTestManager() var got []SelectOption m.SetUIProvider(UIProvider{ - ShowInput: func(_ string, _, _ string, suggestions []SelectOption, _ func(string), onSubmit func(string), _ func(int), _ func()) { + ShowInput: func(_ string, _, _ string, suggestions []SelectOption, _ func(string), onSubmit func(string), _ func(int), _ func()) uint64 { got = suggestions onSubmit("x") + return 1 }, }) loadTestPlugin(t, m, "input-suggestions", ` @@ -82,7 +83,7 @@ func TestUISuggestionsPassesImage(t *testing.T) { m := newTestManager() var got []SelectOption m.SetUIProvider(UIProvider{ - UpdateInput: func(options []SelectOption, live bool, query string) { + UpdateInput: func(options []SelectOption, live bool, query string, querySet bool, token uint64) { got = options }, }) diff --git a/luaplugin/luaplugin.go b/luaplugin/luaplugin.go index abb3c81fe..a3934246f 100644 --- a/luaplugin/luaplugin.go +++ b/luaplugin/luaplugin.go @@ -149,11 +149,11 @@ type UIProvider struct { // ShowInput opens a text input. It must return at once; onSubmit and // onCancel run on the UI goroutine and the manager turns them into plugin // callbacks. - ShowInput func(title, placeholder, value string, suggestions []SelectOption, onChange func(text string), onSubmit func(text string), onSelect func(index int), onCancel func()) + ShowInput func(title, placeholder, value string, suggestions []SelectOption, onChange func(text string), onSubmit func(text string), onSelect func(index int), onCancel func()) uint64 // UpdateInput replaces the suggestions of the open input. live means the // rows are search results that Enter selects, not command completions. // query is the text the results belong to, when the plugin reports it. - UpdateInput func(options []SelectOption, live bool, query string) + UpdateInput func(options []SelectOption, live bool, query string, querySet bool, token uint64) // ShowText opens a scrollable text panel. It must return at once. ShowText func(title, text string, onClose func()) // SetVis switches the active visualizer by name. It must return at once: the diff --git a/ui/model/lua_input.go b/ui/model/lua_input.go index 454711099..24c53a527 100644 --- a/ui/model/lua_input.go +++ b/ui/model/lua_input.go @@ -14,6 +14,7 @@ import ( // OnSubmit runs with the text the user typed; OnSelect runs with the 0-based // index of a live result; OnCancel runs on Esc. type LuaInputMsg struct { + Token uint64 Title string Placeholder string Value string @@ -28,15 +29,18 @@ type LuaInputMsg struct { // Live rows are search results: Enter selects one instead of submitting the // text. type LuaInputSuggestionsMsg struct { + Token uint64 Options []luaplugin.SelectOption Live bool - // Query is the text the results belong to. A message for an older query - // is ignored after the input changed. - Query string + // Query is the text the results belong to. QuerySet distinguishes an + // omitted query from an explicitly empty one. + Query string + QuerySet bool } // luaInputState is the open plugin input. type luaInputState struct { + token uint64 title string placeholder string value string diff --git a/ui/model/lua_input_test.go b/ui/model/lua_input_test.go index 73f62f905..4dc8113d2 100644 --- a/ui/model/lua_input_test.go +++ b/ui/model/lua_input_test.go @@ -205,19 +205,57 @@ func TestLuaInputIgnoresSuggestionsForAnOldQuery(t *testing.T) { m := Model{} m.openLuaInput("Message", "", "new", nil, nil, nil, nil, nil) m.Update(LuaInputSuggestionsMsg{ - Query: "old", + Query: "old", + QuerySet: true, + Options: []luaplugin.SelectOption{{Title: "Stale"}}, + Live: true, + }) + if len(m.luaInput.suggestions) != 0 { + t.Fatalf("stale suggestions were installed: %#v", m.luaInput.suggestions) + } + m.Update(LuaInputSuggestionsMsg{ + Query: "new", + QuerySet: true, + Options: []luaplugin.SelectOption{{Title: "Fresh"}}, + Live: true, + }) + if len(m.luaInput.suggestions) != 1 || m.luaInput.suggestions[0].Title != "Fresh" { + t.Fatalf("fresh suggestions were not installed: %#v", m.luaInput.suggestions) + } +} + +func TestLuaInputIgnoresSuggestionsForAnOldToken(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "new", nil, nil, nil, nil, nil) + m.luaInput.token = 2 + m.Update(LuaInputSuggestionsMsg{ + Token: 1, Options: []luaplugin.SelectOption{{Title: "Stale"}}, Live: true, }) if len(m.luaInput.suggestions) != 0 { - t.Fatalf("stale suggestions were installed: %#v", m.luaInput.suggestions) + t.Fatalf("suggestions from an old input were installed: %#v", m.luaInput.suggestions) } m.Update(LuaInputSuggestionsMsg{ - Query: "new", + Token: 2, Options: []luaplugin.SelectOption{{Title: "Fresh"}}, Live: true, }) if len(m.luaInput.suggestions) != 1 || m.luaInput.suggestions[0].Title != "Fresh" { - t.Fatalf("fresh suggestions were not installed: %#v", m.luaInput.suggestions) + t.Fatalf("suggestions = %#v", m.luaInput.suggestions) + } +} + +func TestLuaInputExplicitEmptyQueryRejectsStaleResults(t *testing.T) { + m := Model{} + m.openLuaInput("Message", "", "new", nil, nil, nil, nil, nil) + m.Update(LuaInputSuggestionsMsg{ + Query: "", + QuerySet: true, + Options: []luaplugin.SelectOption{{Title: "Stale"}}, + Live: true, + }) + if len(m.luaInput.suggestions) != 0 { + t.Fatalf("explicit empty query was treated as omitted: %#v", m.luaInput.suggestions) } } diff --git a/ui/model/update.go b/ui/model/update.go index f9b256091..5d7a47268 100644 --- a/ui/model/update.go +++ b/ui/model/update.go @@ -123,10 +123,14 @@ func (m Model) update(msg tea.Msg) (tea.Model, tea.Cmd) { prev.onCancel() } m.openLuaInput(msg.Title, msg.Placeholder, msg.Value, msg.Suggestions, msg.OnChange, msg.OnSubmit, msg.OnSelect, msg.OnCancel) + m.luaInput.token = msg.Token return m, nil case LuaInputSuggestionsMsg: - if m.luaInput == nil || (msg.Query != "" && msg.Query != m.luaInput.value) { + if m.luaInput == nil || msg.Token != m.luaInput.token { + return m, nil + } + if msg.QuerySet && msg.Query != m.luaInput.value { return m, nil } if len(msg.Options) != len(m.luaInput.suggestions) {