1package telegram
2
3import (
4 "context"
5 "fmt"
6 "strings"
7 "sync"
8 "time"
9
10 "github.com/patriceckhart/zot/internal/provider"
11)
12
13// Host is the small interface the Bridge calls back into the TUI
14// through. Decouples bridge plumbing from the Interactive type.
15type Host interface {
16 // SubmitOrQueue feeds a user prompt into the running agent.
17 // Runs now if the agent is idle, queues behind any in-flight
18 // turn otherwise.
19 SubmitOrQueue(prompt string, images []provider.ImageBlock)
20
21 // CancelTurn aborts the active turn (if any). Called when the
22 // paired Telegram user sends /stop.
23 CancelTurn()
24
25 // Notify pushes a one-shot status line into the chat. Used to
26 // surface bridge events ("connected as @bot", "paired with
27 // user X", etc.) in the user's local transcript.
28 Notify(level, message string)
29}
30
31// Bridge polls Telegram for updates and forwards them into the
32// Host's running agent, then mirrors the agent's final assistant
33// text back to the paired Telegram user. One bridge per Interactive
34// instance; created on /telegram connect, stopped on /telegram
35// disconnect or zot exit.
36type Bridge struct {
37 Client *Client
38 Config Config
39 Save func(Config) error
40 Host Host
41
42 mu sync.Mutex
43 running bool
44 cancel context.CancelFunc
45 me *User
46 chatID int64 // populated after first DM from the paired user
47 replyBuf strings.Builder
48
49 // nextReplyFromTelegram is set when the next assistant reply
50 // should be sent bare (no "zot: " prefix) because the turn was
51 // initiated by a Telegram DM. The flag clears as soon as the
52 // reply is flushed. TUI-originated turns leave the flag false
53 // so the reply is tagged "zot: " for clarity on the two-sided
54 // transcript.
55 nextReplyFromTelegram bool
56}
57
58// State is the snapshot /telegram status reports.
59type State struct {
60 Running bool
61 Username string // bot username, e.g. "zotbot"
62 PairedID int64 // 0 when no user has claimed the bot yet
63}
64
65// Active reports whether the bridge is currently polling.
66func (b *Bridge) Active() bool {
67 if b == nil {
68 return false
69 }
70 b.mu.Lock()
71 defer b.mu.Unlock()
72 return b.running
73}
74
75// State returns a snapshot of the bridge for /telegram status.
76func (b *Bridge) State() State {
77 if b == nil {
78 return State{}
79 }
80 b.mu.Lock()
81 defer b.mu.Unlock()
82 s := State{Running: b.running, PairedID: b.Config.AllowedUserID}
83 if b.me != nil {
84 s.Username = b.me.Username
85 }
86 return s
87}
88
89// Start kicks off the polling loop. Idempotent: calling twice
90// returns nil the second time and leaves the existing loop alone.
91// Verifies the bot token with GetMe before starting the loop so
92// obvious configuration errors surface immediately.
93func (b *Bridge) Start(parent context.Context) error {
94 b.mu.Lock()
95 if b.running {
96 b.mu.Unlock()
97 return nil
98 }
99 if b.Config.BotToken == "" {
100 b.mu.Unlock()
101 return fmt.Errorf("no bot token configured; run `zot telegram-bot setup` first")
102 }
103 b.mu.Unlock()
104
105 ctx, cancel := context.WithCancel(parent)
106 // Quick handshake before committing the loop.
107 me, err := b.Client.GetMe(ctx)
108 if err != nil {
109 cancel()
110 return fmt.Errorf("getMe: %w", err)
111 }
112
113 b.mu.Lock()
114 b.running = true
115 b.cancel = cancel
116 b.me = me
117 // Telegram private-chat ids are the same as the user id, so if
118 // we've already paired in a previous session we can send to the
119 // user immediately without waiting for them to DM first.
120 if b.Config.AllowedUserID != 0 && b.chatID == 0 {
121 b.chatID = b.Config.AllowedUserID
122 }
123 if b.Config.BotID != me.ID || b.Config.BotUsername != me.Username {
124 b.Config.BotID = me.ID
125 b.Config.BotUsername = me.Username
126 _ = b.Save(b.Config)
127 }
128 b.mu.Unlock()
129
130 go b.pollLoop(ctx)
131 return nil
132}
133
134// Stop halts the polling loop. Safe to call when not running.
135func (b *Bridge) Stop() {
136 b.mu.Lock()
137 cancel := b.cancel
138 b.running = false
139 b.cancel = nil
140 b.mu.Unlock()
141 if cancel != nil {
142 cancel()
143 }
144}
145
146// OnAssistantText should be called by the TUI with the assistant's
147// final visible text for each turn. The bridge forwards it to the
148// paired chat in message-sized chunks. Prefix depends on which
149// side initiated the turn: TUI-originated turns get "zot: " so the
150// two-sided transcript reads naturally ("you: ..." / "zot: ..."),
151// while Telegram-originated turns send bare text (the user's own
152// bubble is already on-screen, a "zot: " prefix would just add
153// visual noise to a plain back-and-forth).
154func (b *Bridge) OnAssistantText(text string) {
155 b.mu.Lock()
156 // prefix := "zot: "
157 prefix := ""
158 if b.nextReplyFromTelegram {
159 prefix = ""
160 b.nextReplyFromTelegram = false
161 }
162 b.mu.Unlock()
163 b.sendToPaired(text, prefix)
164}
165
166// OnUserTyped mirrors a message the user typed in the zot TUI into
167// the paired Telegram chat, tagged "you:" so the Telegram thread
168// stays a complete record of the conversation (both TUI-originated
169// and Telegram-originated turns). Messages sent from Telegram
170// itself aren't mirrored back (they already appear as the user's
171// own bubble), only TUI-originated prompts flow through here.
172func (b *Bridge) OnUserTyped(text string) {
173 b.sendToPaired(text, "you: ")
174}
175
176// sendToPaired writes text (with an optional prefix, chunked to
177// Telegram's 4096-char cap) to the paired chat. No-op when the
178// bridge is stopped or before the paired chat id is known.
179func (b *Bridge) sendToPaired(text, prefix string) {
180 b.mu.Lock()
181 chatID := b.chatID
182 running := b.running
183 b.mu.Unlock()
184 if !running || chatID == 0 {
185 return
186 }
187 text = strings.TrimSpace(text)
188 if text == "" {
189 return
190 }
191 if prefix != "" {
192 text = prefix + text
193 }
194 for _, chunk := range chunkMessage(text, 4000) {
195 if err := b.Client.SendMessage(context.Background(), chatID, chunk, 0); err != nil {
196 fmt.Fprintln(stderr(), "telegram bridge: sendMessage:", err)
197 return
198 }
199 }
200}
201
202// SendImage uploads path to the paired Telegram chat as an inline
203// photo. Returns an error if the bridge is not running, no user has
204// paired yet, or the upload itself fails. Used by the
205// telegram_send_image tool so a Telegram-originated turn can yield
206// a real image instead of a textual description.
207func (b *Bridge) SendImage(ctx context.Context, path, caption string) error {
208 b.mu.Lock()
209 chatID := b.chatID
210 running := b.running
211 b.mu.Unlock()
212 if !running {
213 return fmt.Errorf("telegram bridge is not running")
214 }
215 if chatID == 0 {
216 return fmt.Errorf("telegram bridge has no paired chat yet")
217 }
218 return b.Client.SendPhoto(ctx, chatID, path, caption)
219}
220
221// SendDocument uploads path to the paired Telegram chat as a raw
222// document attachment (no compression). Counterpart of SendImage for
223// the telegram_send_file tool.
224func (b *Bridge) SendDocument(ctx context.Context, path, caption string) error {
225 b.mu.Lock()
226 chatID := b.chatID
227 running := b.running
228 b.mu.Unlock()
229 if !running {
230 return fmt.Errorf("telegram bridge is not running")
231 }
232 if chatID == 0 {
233 return fmt.Errorf("telegram bridge has no paired chat yet")
234 }
235 return b.Client.SendDocument(ctx, chatID, path, caption)
236}
237
238// pollLoop long-polls Telegram and dispatches each update. Runs
239// until ctx cancels.
240func (b *Bridge) pollLoop(ctx context.Context) {
241 backoff := time.Second
242 for {
243 if err := ctx.Err(); err != nil {
244 return
245 }
246 updates, err := b.Client.GetUpdates(ctx, b.Config.LastUpdateID+1, 30)
247 if err != nil {
248 if ctx.Err() != nil {
249 return
250 }
251 b.Host.Notify("warn", fmt.Sprintf("telegram: getUpdates: %v", err))
252 select {
253 case <-ctx.Done():
254 return
255 case <-time.After(backoff):
256 }
257 if backoff < 30*time.Second {
258 backoff *= 2
259 }
260 continue
261 }
262 backoff = time.Second
263 for _, u := range updates {
264 b.handleUpdate(ctx, u)
265 b.mu.Lock()
266 b.Config.LastUpdateID = u.UpdateID
267 _ = b.Save(b.Config)
268 b.mu.Unlock()
269 }
270 }
271}
272
273// handleUpdate applies pairing, gates on the allowed user, decodes
274// the interesting bits (text, caption, image attachments), and
275// forwards them to the Host. Built-in slash commands (/start,
276// /help, /status, /stop) are handled inline without touching the
277// agent.
278func (b *Bridge) handleUpdate(ctx context.Context, u Update) {
279 msg := u.Message
280 if msg == nil {
281 msg = u.Edited
282 }
283 if msg == nil || msg.From == nil || msg.From.IsBot {
284 return
285 }
286 if msg.Chat.Type != "private" {
287 return
288 }
289
290 text := strings.TrimSpace(msg.Text)
291
292 // Pairing: first user who sends /start claims the bridge.
293 b.mu.Lock()
294 paired := b.Config.AllowedUserID
295 b.mu.Unlock()
296 if paired == 0 {
297 if strings.HasPrefix(text, "/start") {
298 b.mu.Lock()
299 b.Config.AllowedUserID = msg.From.ID
300 b.chatID = msg.Chat.ID
301 _ = b.Save(b.Config)
302 b.mu.Unlock()
303 _ = b.Client.SendMessage(ctx, msg.Chat.ID,
304 fmt.Sprintf("paired with @%s. messages you send here now mirror into the zot tui.", msg.From.Username),
305 msg.MessageID)
306 b.Host.Notify("success", fmt.Sprintf("telegram paired with user %d (@%s)", msg.From.ID, msg.From.Username))
307 return
308 }
309 _ = b.Client.SendMessage(ctx, msg.Chat.ID,
310 "this bot isn't paired yet. send /start to claim it.",
311 msg.MessageID)
312 return
313 }
314
315 if msg.From.ID != paired {
316 _ = b.Client.SendMessage(ctx, msg.Chat.ID,
317 "this bot is paired with a different user.",
318 msg.MessageID)
319 return
320 }
321
322 // Remember the chat id so replies can go out without waiting
323 // for another update round-trip.
324 b.mu.Lock()
325 b.chatID = msg.Chat.ID
326 b.mu.Unlock()
327
328 // Built-in commands that bypass the agent.
329 switch text {
330 case "/start", "/help":
331 _ = b.Client.SendMessage(ctx, msg.Chat.ID,
332 "mirror is active. send me a message and it'll be forwarded to the zot tui. commands: /status, /stop.",
333 msg.MessageID)
334 return
335 case "/status":
336 _ = b.Client.SendMessage(ctx, msg.Chat.ID,
337 fmt.Sprintf("mirror active. paired user: %d.", paired),
338 msg.MessageID)
339 return
340 case "/stop":
341 b.Host.CancelTurn()
342 _ = b.Client.SendMessage(ctx, msg.Chat.ID,
343 "cancelled the current turn.", msg.MessageID)
344 return
345 }
346
347 // Build the prompt: text + caption; download image attachments.
348 prompt := strings.TrimSpace(msg.Text)
349 if msg.Caption != "" {
350 if prompt != "" {
351 prompt += "\n"
352 }
353 prompt += msg.Caption
354 }
355
356 var images []provider.ImageBlock
357 if len(msg.Photo) > 0 {
358 largest := msg.Photo[len(msg.Photo)-1]
359 if data, mime, err := b.download(ctx, largest.FileID, ""); err == nil {
360 images = append(images, provider.ImageBlock{MimeType: mime, Data: data})
361 }
362 }
363 if msg.Document != nil && isImageMIME(msg.Document.MimeType) {
364 if data, mime, err := b.download(ctx, msg.Document.FileID, msg.Document.MimeType); err == nil {
365 images = append(images, provider.ImageBlock{MimeType: mime, Data: data})
366 }
367 }
368
369 if prompt == "" && len(images) == 0 {
370 return
371 }
372
373 b.mu.Lock()
374 b.nextReplyFromTelegram = true
375 b.mu.Unlock()
376 b.Host.SubmitOrQueue(prompt, images)
377}
378
379// download fetches the file referenced by fileID and returns its
380// bytes + mime type. Mime overrides the detected value when non-empty.
381func (b *Bridge) download(ctx context.Context, fileID, mimeOverride string) ([]byte, string, error) {
382 f, err := b.Client.GetFile(ctx, fileID)
383 if err != nil {
384 return nil, "", err
385 }
386 data, err := b.Client.DownloadFile(ctx, f.FilePath)
387 if err != nil {
388 return nil, "", err
389 }
390 mime := mimeOverride
391 if mime == "" {
392 mime = guessImageMIME(f.FilePath)
393 }
394 return data, mime, nil
395}