opencode-telegram-bot icon indicating copy to clipboard operation
opencode-telegram-bot copied to clipboard

Send images read via the Read tool to Telegram as photos

Open vokasug opened this issue 2 months ago • 3 comments

Problem / use case

When working with the agent through Telegram, a natural request is "send me a screenshot of X" — e.g. a UI the agent is automating, a chart it just generated, or any image file on disk. The agent does read the file, but nothing arrives in the chat: the user gets only the agent's text saying it sent the image. Today the only workaround is the manual /ls file browser → download button, which defeats the point of just asking in plain language.

The bot forwards files to Telegram only for write / edit / apply_patch tool parts: prepareToolFileContext() returns { fileData: null } for every other tool. When the agent uses the read tool on an image (e.g. a screenshot), the image never reaches the chat — the user only sees the agent's text reply.

Proposal

Handle tool === "read" in prepareToolFileContext: if input.filePath looks like an image (png/jpg/jpeg/webp/gif), the file exists and is ≤ 10 MB (Telegram sendPhoto limit), read it from disk and pass it through the existing file pipeline with a new asPhoto: true flag.

In sendFile, send flagged files via sendPhoto (inline preview in the chat), falling back to sendDocument if Telegram rejects the photo. Text reads stay completely silent — no spam from reading source/config files.

The change reuses all existing gates: current-session check (subagent reads are filtered out), compact mode, the sendDiffFileAttachments toggle, and the processedToolStates dedupe. The caption comes from the existing formatToolInfo path (📖 <path>).

Patch (against dist of 0.24.1)

--- a/dist/app/managers/summary-aggregation-manager.js
+++ b/dist/app/managers/summary-aggregation-manager.js
@@ -3,6 +3,12 @@
 import { extractErrorMessage } from "../../utils/opencode-error.js";
 import { isRecord } from "../../utils/type-guards.js";
 import { getCurrentProject } from "../stores/settings-store.js";
+import fs from "node:fs";
+import path from "node:path";
+// Read tool results for images are sent to Telegram as photos. Telegram's
+// sendPhoto accepts JPG/PNG/WEBP/GIF up to 10 MB; anything else is skipped.
+const READ_IMAGE_EXTENSIONS = /\.(png|jpe?g|webp|gif)$/i;
+const READ_IMAGE_MAX_BYTES = 10 * 1024 * 1024;
 function isMessagePartDeltaEvent(event) {
     return event.type === "message.part.delta" && isRecord(event.properties);
 }
@@ -1280,6 +1286,31 @@
         return texts.filter((text) => !isUpstreamEmptyResponseText(text, isFinal)).join("");
     }
     prepareToolFileContext(tool, input, title, metadata) {
+        if (tool === "read" && input) {
+            const filePath = typeof input.filePath === "string" ? input.filePath : "";
+            if (!filePath || !READ_IMAGE_EXTENSIONS.test(filePath)) {
+                return { fileData: null, fileChange: null };
+            }
+            try {
+                const stat = fs.statSync(filePath);
+                if (!stat.isFile() || stat.size <= 0 || stat.size > READ_IMAGE_MAX_BYTES) {
+                    return { fileData: null, fileChange: null };
+                }
+                logger.debug(`[Aggregator] Read tool produced image attachment: ${filePath} (${stat.size} bytes)`);
+                return {
+                    fileData: {
+                        buffer: fs.readFileSync(filePath),
+                        filename: path.basename(filePath),
+                        caption: "",
+                        asPhoto: true,
+                    },
+                    fileChange: null,
+                };
+            }
+            catch {
+                return { fileData: null, fileChange: null };
+            }
+        }
         if (tool === "write" && input) {
             const filePath = typeof input.filePath === "string" ? normalizePathForDisplay(input.filePath) : "";
             const content = typeof input.content === "string" ? input.content : "";
--- a/dist/bot/services/event-subscription-service.js
+++ b/dist/bot/services/event-subscription-service.js
@@ -120,11 +120,21 @@
                     await fs.mkdir(TEMP_DIR, { recursive: true });
                     await fs.writeFile(tempFilePath, fileData.buffer);
                     const keyboard = this.getCurrentReplyKeyboard();
-                    await this.botInstance.api.sendDocument(this.chatIdInstance, new InputFile(tempFilePath), {
+                    const options = {
                         caption: fileData.caption,
                         disable_notification: true,
                         ...(keyboard ? { reply_markup: keyboard } : {}),
-                    });
+                    };
+                    if (fileData.asPhoto) {
+                        try {
+                            await this.botInstance.api.sendPhoto(this.chatIdInstance, new InputFile(tempFilePath), options);
+                            return;
+                        }
+                        catch (err) {
+                            logger.warn(`[Bot] sendPhoto failed for ${fileData.filename}, falling back to document:`, err);
+                        }
+                    }
+                    await this.botInstance.api.sendDocument(this.chatIdInstance, new InputFile(tempFilePath), options);
                 }
                 finally {
                     await fs.unlink(tempFilePath).catch(() => { });

For the TypeScript sources this maps to prepareToolFileContext in src/app/managers/summary-aggregation-manager.ts and sendFile in src/bot/services/event-subscription-service.ts.

Verified

Patched the installed 0.24.1 dist locally and restarted the bot. The agent read a PNG screenshot (823 KB) — it arrived in the Telegram chat as a photo with the 📖 <path> caption. Non-image reads produced no messages, same as before the change.

vokasug avatar Sep 16 '26 09:09 vokasug

You can just use /ls command for this.

grinev avatar Sep 21 '26 10:09 grinev

You can just use /ls command for this.

Opencode v2 has image preview now, in both tui and gui, it's an officially supported tool call. No reason to not wire it up to telegram's image display api

sachahjkl avatar Sep 29 '26 19:09 sachahjkl

🤖 AI-generated report — bot-EVOX2 · LLM: Qwen3.8-Flash-Next-EXL3-4.05bpw @ rulith

Still reproduces on v0.26.6 (2026-11-13): the outbound pipeline in dist/bot/messages/telegram-text.js only calls sendMessage / sendRichMessage / editMessageText / sendMessageDraft — a grep over the whole shipped dist/ finds no sendPhoto / sendDocument at all (only inbound attachment strings in i18n). So when the agent reads an image with its Read tool, the user's chat gets only the text and never the picture.

Workaround used today (worked perfectly): from the agent side I called Telegram's sendPhoto directly with curl.exe -F chat_id=… -F [email protected] -F caption=… using the bot token from the bot's own .env. Two photos landed in the private chat with captions, ok:true. Happy to share the exact shape if useful — it suggests the hard part (auth, chat id) is already at hand in-process.

One pointer for whoever picks this up: the bot already sends audio for TTS replies (#253 lineage), so there is precedent for a media path outside telegram-text.js — image parts of assistant messages could ride a similar lane. The Read-tool image parts carry a local file path + mimeType, so sendPhoto(photo: InputFile(path)) with a caption from the adjacent text part seems like the minimal shape.

Related (not duplicates): #286 (tool-output file uploads, closed), #250 (save unsupported inbound files — inbound direction).

biolau avatar Nov 13 '26 20:11 biolau