diff --git a/internal/channels/telegram/interactive.go b/internal/channels/telegram/interactive.go new file mode 100644 index 000000000..e22956e4b --- /dev/null +++ b/internal/channels/telegram/interactive.go @@ -0,0 +1,217 @@ +package telegram + +import ( + "context" + "fmt" + "strings" + "time" + + "github.com/go-telegram/bot" + "github.com/go-telegram/bot/models" + + "github.com/samcharles93/archie-core/internal/domain/messaging" +) + +// interactiveReplyTimeout bounds how long one clarify or picker request waits +// for the human's reply. It matches the approval window so the two blocking +// interactions expire together and neither can wedge a turn indefinitely. +const interactiveReplyTimeout = messaging.ToolApprovalTimeout + +// pendingReplyKey identifies the chat a blocked clarify/picker prompt belongs +// to, so only the addressed human's next text is consumed as the answer. +type pendingReplyKey struct { + chatID int64 + threadID int + recipient int64 +} + +// pendingReply is one clarify/picker prompt waiting on the human's next text. +// It is the text-reply analogue of pendingApproval, kept separate so the +// button (callback) and message (text) models cannot entangle. +type pendingReply struct { + resultCh chan replyResult + expiresAt time.Time +} + +// replyResult carries the human's typed answer (or the wait's error) back to +// the blocked interaction. +type replyResult struct { + text string + err error +} + +// telegramInteractor carries clarify and picker interactions for one chat on +// the channel's shared text fallback. Telegram renders no generic question or +// single-choice widget in the agent-turn path, so both interactions appear as +// text the human answers by replying; reporting the Clarify and Picker +// capabilities is therefore honest, because the adapter can carry the +// interaction even though it costs a typed answer. +type telegramInteractor struct { + gw *Gateway + bot *bot.Bot + chatID int64 + threadID int + recipient int64 +} + +// Compile-time guards: the adapter carries both interactions and reports them +// through the capability contract, so ClarifierOf/PickerOf resolve it. +var ( + _ messaging.ClarifyRequester = (*telegramInteractor)(nil) + _ messaging.PickerRequester = (*telegramInteractor)(nil) + _ messaging.CapabilityReporter = (*telegramInteractor)(nil) +) + +// Capabilities reports that this adapter can carry a clarify question and a +// single-choice picker. Both go through the shared text fallback rather than a +// native widget, and the capability is about carrying the interaction, not +// about the widget, so claiming them is what keeps a question from being +// silently dropped. +func (i *telegramInteractor) Capabilities() messaging.AdapterCapabilities { + return messaging.AdapterCapabilities{Clarify: true, Picker: true} +} + +// NewInteractor returns the channel's clarify/picker adapter for one chat, +// already resolved to the requesters its capability report advertises. The +// gateway turn stores it with WithInteractive so its question tool can reach +// the human. +func (g *Gateway) NewInteractor(b *bot.Bot, chatID int64, threadID int, recipient int64) messaging.Interactive { + i := &telegramInteractor{ + gw: g, + bot: b, + chatID: chatID, + threadID: threadID, + recipient: recipient, + } + return messaging.InteractiveOf(i) +} + +// RequestClarification poses the question as text and blocks for the reply. +func (i *telegramInteractor) RequestClarification(ctx context.Context, req messaging.ClarifyRequest) (string, error) { + ctx, cancel := context.WithTimeout(ctx, interactiveReplyTimeout) + defer cancel() + fallback := i.fallback() + return fallback.RequestClarification(ctx, req) +} + +// RequestChoice poses the options as numbered text and matches the typed +// reply. The domain's text fallback owns the rendering and matching, so the +// degrade is one implementation rather than a second parser here. +func (i *telegramInteractor) RequestChoice(ctx context.Context, req messaging.PickerRequest) (messaging.InteractiveChoice, error) { + ctx, cancel := context.WithTimeout(ctx, interactiveReplyTimeout) + defer cancel() + fallback := i.fallback() + return fallback.RequestChoice(ctx, req) +} + +// fallback builds a fresh text fallback for one interaction. Registering the +// pending reply inside Send, before the prompt is delivered, closes the race +// where a fast reply arrives before the blocked call is listening. +func (i *telegramInteractor) fallback() messaging.TextFallback { + key := pendingReplyKey{chatID: i.chatID, threadID: i.threadID, recipient: i.recipient} + ch := make(chan replyResult, 1) + return messaging.TextFallback{ + Send: func(ctx context.Context, text string) error { + i.gw.registerPendingReply(key, pendingReply{ + resultCh: ch, + expiresAt: time.Now().Add(interactiveReplyTimeout), + }) + if err := i.send(ctx, text); err != nil { + i.gw.removePendingReply(key) + return err + } + return nil + }, + Reply: func(ctx context.Context) (string, error) { + select { + case res := <-ch: + return res.text, res.err + case <-ctx.Done(): + i.gw.removePendingReply(key) + return "", ctx.Err() + } + }, + } +} + +// send delivers one prompt. ForceReply makes the reply affordance explicit in +// a chat with other traffic, so the human answers the question rather than +// sending a message the turn cannot tell apart from a new request. +func (i *telegramInteractor) send(ctx context.Context, text string) error { + params := &bot.SendMessageParams{ + ChatID: i.chatID, + Text: text, + ReplyMarkup: &models.ForceReply{ForceReply: true, Selective: true}, + } + if i.threadID != 0 { + params.MessageThreadID = i.threadID + } + if _, err := i.bot.SendMessage(ctx, params); err != nil { + return fmt.Errorf("send interactive prompt: %w", err) + } + return nil +} + +// registerPendingReply stores a pending interaction, pruning any that have +// already expired. +func (g *Gateway) registerPendingReply(key pendingReplyKey, pr pendingReply) { + g.interactiveMu.Lock() + defer g.interactiveMu.Unlock() + now := time.Now() + for existing, pending := range g.pendingReplies { + if !pending.expiresAt.After(now) { + delete(g.pendingReplies, existing) + } + } + g.pendingReplies[key] = &pr +} + +// removePendingReply drops a pending interaction, if present. +func (g *Gateway) removePendingReply(key pendingReplyKey) { + g.interactiveMu.Lock() + defer g.interactiveMu.Unlock() + delete(g.pendingReplies, key) +} + +// consumePendingReply atomically claims the pending interaction for the chat +// and delivers the typed answer. It rejects expired entries and reports +// whether the text was consumed as an answer. +func (g *Gateway) consumePendingReply(key pendingReplyKey, text string) bool { + g.interactiveMu.Lock() + pr, found := g.pendingReplies[key] + expired := !found || !pr.expiresAt.After(time.Now()) + if !expired { + delete(g.pendingReplies, key) + } + g.interactiveMu.Unlock() + if expired { + return false + } + select { + case pr.resultCh <- replyResult{text: text}: + return true + default: + // The channel already has a result (the wait timed out between the + // expiry check and now); do not report a reply that was not taken. + return false + } +} + +// deliverInteractiveReply routes a text reply to a blocked clarify/picker +// request when one is pending for this chat and sender, and reports whether +// the message was consumed. A consumed reply is not dispatched as a new turn; +// a command is never consumed, so /stop still cancels the blocked turn. +func (g *Gateway) deliverInteractiveReply(msg *models.Message) bool { + if msg == nil || msg.From == nil { + return false + } + text := strings.TrimSpace(msg.Text) + if text == "" || strings.HasPrefix(text, "/") { + return false + } + return g.consumePendingReply(pendingReplyKey{ + chatID: msg.Chat.ID, + threadID: msg.MessageThreadID, + recipient: msg.From.ID, + }, text) +} diff --git a/internal/channels/telegram/interactive_test.go b/internal/channels/telegram/interactive_test.go new file mode 100644 index 000000000..79d9c5ead --- /dev/null +++ b/internal/channels/telegram/interactive_test.go @@ -0,0 +1,168 @@ +package telegram + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/go-telegram/bot/models" + + "github.com/samcharles93/archie-core/internal/domain/messaging" +) + +// waitForPendingReply polls the gateway's pending-reply map until a blocked +// interaction has registered itself. Polling the guarded map is race-free: +// the register happens-before the requester blocks, and the map is guarded by +// interactiveMu. +func waitForPendingReply(t *testing.T, g *Gateway) { + t.Helper() + deadline := time.Now().Add(2 * time.Second) + for time.Now().Before(deadline) { + g.interactiveMu.Lock() + n := len(g.pendingReplies) + g.interactiveMu.Unlock() + if n > 0 { + return + } + time.Sleep(5 * time.Millisecond) + } + t.Fatal("no pending interactive reply was registered") +} + +func interactiveReplyMessage(chatID, recipient int64, text string) *models.Message { + return &models.Message{ + From: &models.User{ID: recipient}, + Chat: models.Chat{ID: chatID, Type: models.ChatTypePrivate}, + Text: text, + } +} + +// sentPrompt returns the text of the first sendMessage whose body contains +// want, so a test can assert what the adapter actually rendered. +func sentPrompt(requests []telegramRequest, want string) string { + for _, request := range requests { + if request.method == "sendMessage" && strings.Contains(request.form["text"], want) { + return request.form["text"] + } + } + return "" +} + +func TestInteractorReportsClarifyAndPicker(t *testing.T) { + g, b, _ := newApprovalTestGateway(t) + interactor := g.NewInteractor(b, approvalTestChatID, 0, approvalTestRecipient) + if interactor.Clarifier == nil { + t.Error("interactor does not report the Clarify capability") + } + if interactor.Picker == nil { + t.Error("interactor does not report the Picker capability") + } +} + +// TestInteractivePickUsesTextFallback is the acceptance test for step 4 at the +// adapter: Telegram has no generic picker widget in the turn path, so the +// choice must be rendered as numbered text and matched from the human's typed +// reply rather than failing or being dropped. +func TestInteractivePickUsesTextFallback(t *testing.T) { + g, b, requests := newApprovalTestGateway(t) + interactor := g.NewInteractor(b, approvalTestChatID, 0, approvalTestRecipient) + + type outcome struct { + choice messaging.InteractiveChoice + err error + } + done := make(chan outcome, 1) + go func() { + choice, err := interactor.Picker.RequestChoice(context.Background(), messaging.PickerRequest{ + Prompt: "Which branch?", + Options: []messaging.InteractiveChoice{ + {ID: "main", Label: "main"}, + {ID: "release", Label: "release"}, + }, + }) + done <- outcome{choice: choice, err: err} + }() + + waitForPendingReply(t, g) + if !g.deliverInteractiveReply(interactiveReplyMessage(approvalTestChatID, approvalTestRecipient, "2")) { + t.Fatal("deliverInteractiveReply did not consume the typed reply") + } + + select { + case got := <-done: + if got.err != nil { + t.Fatalf("RequestChoice error = %v", got.err) + } + if got.choice.ID != "release" { + t.Errorf("choice = %+v, want release", got.choice) + } + case <-time.After(2 * time.Second): + t.Fatal("RequestChoice did not return after the reply was delivered") + } + + if prompt := sentPrompt(*requests, "Which branch?"); !strings.Contains(prompt, "1) main") || !strings.Contains(prompt, "2) release") { + t.Errorf("picker prompt was not rendered as numbered text: %q", prompt) + } +} + +func TestInteractiveClarifyReturnsTypedAnswer(t *testing.T) { + g, b, _ := newApprovalTestGateway(t) + interactor := g.NewInteractor(b, approvalTestChatID, 0, approvalTestRecipient) + + type outcome struct { + answer string + err error + } + done := make(chan outcome, 1) + go func() { + answer, err := interactor.Clarifier.RequestClarification(context.Background(), messaging.ClarifyRequest{Question: "Which environment?"}) + done <- outcome{answer: answer, err: err} + }() + + waitForPendingReply(t, g) + if !g.deliverInteractiveReply(interactiveReplyMessage(approvalTestChatID, approvalTestRecipient, " staging ")) { + t.Fatal("deliverInteractiveReply did not consume the typed reply") + } + + select { + case got := <-done: + if got.err != nil { + t.Fatalf("RequestClarification error = %v", got.err) + } + if got.answer != "staging" { + t.Errorf("answer = %q, want staging (trimmed)", got.answer) + } + case <-time.After(2 * time.Second): + t.Fatal("RequestClarification did not return after the reply was delivered") + } +} + +// A command typed while a prompt is pending must reach the command handler, not +// be swallowed as the answer: /stop is how the human cancels the blocked turn. +func TestDeliverInteractiveReplyIgnoresCommands(t *testing.T) { + g, b, _ := newApprovalTestGateway(t) + interactor := g.NewInteractor(b, approvalTestChatID, 0, approvalTestRecipient) + + ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) + defer cancel() + done := make(chan error, 1) + go func() { + _, err := interactor.Clarifier.RequestClarification(ctx, messaging.ClarifyRequest{Question: "Which environment?"}) + done <- err + }() + + waitForPendingReply(t, g) + if g.deliverInteractiveReply(interactiveReplyMessage(approvalTestChatID, approvalTestRecipient, "/stop")) { + t.Error("deliverInteractiveReply consumed a command as the answer") + } + + select { + case err := <-done: + if err == nil { + t.Error("RequestClarification returned nil error after its context expired") + } + case <-time.After(2 * time.Second): + t.Fatal("RequestClarification did not return after its context expired") + } +} diff --git a/internal/channels/telegram/telegram.go b/internal/channels/telegram/telegram.go index 0feb98cb7..3cad3a89c 100644 --- a/internal/channels/telegram/telegram.go +++ b/internal/channels/telegram/telegram.go @@ -107,6 +107,13 @@ type Gateway struct { approvalMu sync.Mutex pendingApprovals map[string]*pendingApproval + // interactive state (gateway clarify/picker). A blocked clarify or + // picker waits on one entry here, keyed by the chat it was posed to, so + // the next text from that human is consumed as the answer rather than + // dispatched as a new turn. + interactiveMu sync.Mutex + pendingReplies map[pendingReplyKey]*pendingReply + // turns serialises chat turns per session off the update worker and // makes the running one cancellable by /stop. Rebuilt on every launch // so a restart abandons in-flight turns with the old bot instance. @@ -178,6 +185,7 @@ func New(token string, allowedUserIDs []int64, log *slog.Logger) *Gateway { dangerousActions: make(map[string]dangerousAction), permanentApprovals: nil, pendingApprovals: make(map[string]*pendingApproval), + pendingReplies: make(map[pendingReplyKey]*pendingReply), log: log.With("component", "gateway-telegram"), } g.newEphemeralSender = func() *channels.EphemeralSender { @@ -546,6 +554,11 @@ func (g *Gateway) defaultHandler(client messaging.ChatContract) bot.HandlerFunc if !ok { return } + // A text reply to a pending clarify/picker prompt is consumed here so + // it answers the blocked interaction instead of starting a new turn. + if g.deliverInteractiveReply(msg) { + return + } // Media messages arrive before the text gates: a photo has no text, // so checking it first is what keeps attachments from being dropped. if _, isMedia := extractInboundMedia(msg); isMedia { @@ -665,6 +678,10 @@ func (g *Gateway) submitTurn(ctx context.Context, b *bot.Bot, msg *models.Messag approver := g.NewApprover(b, chatID, threadID, msg.From.ID) turnCtx = messaging.WithApprovalRequester(turnCtx, approver) + // A clarify or picker prompt blocks the turn on this adapter; when the + // channel cannot carry one the question tool is simply not offered. + turnCtx = messaging.WithInteractive(turnCtx, g.NewInteractor(b, chatID, threadID, msg.From.ID)) + // reply appears as it is written; the typing indicator covers the // gap before the first token and any non-streaming path. stopTyping := g.startTyping(turnCtx, b, chatID, threadID)