Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8977 feat(telegram): show what the agent is doing while it works (#10314)
pseudoyu33137e6f6bf0
diff --git a/.env.example b/.env.exampleindex dd0f25358a..224ca2d2fc 100644--- a/.env.example+++ b/.env.example@@ -684,6 +684,10 @@ MULTICA_SLACK_SECRET_KEY=# stable: losing or rotating it makes stored Bot tokens unreadable.# Generate one with: openssl rand -base64 32MULTICA_TELEGRAM_SECRET_KEY=+# Tool steps shown in the streamed reply while the agent works. auto+# (default): each step with what it is working on in private chats, the kind of+# work only in groups. off, summary or detail apply one level everywhere.+MULTICA_TELEGRAM_TOOL_PROGRESS=# Frontend# Leave empty — auto-derived from page origin in browser, set by Makefile for local dev.diff --git a/apps/docs/content/docs/environment-variables.fr.mdx b/apps/docs/content/docs/environment-variables.fr.mdxindex a5457cd778..f780e56dec 100644--- a/apps/docs/content/docs/environment-variables.fr.mdx+++ b/apps/docs/content/docs/environment-variables.fr.mdx@@ -190,6 +190,7 @@ Les limites de débit d'authentification nécessitent `REDIS_URL` ; sans cette v| Lark | `MULTICA_LARK_SECRET_KEY` | Clé de chiffrement des identifiants de 32 octets, encodée en Base64 || Slack | `MULTICA_SLACK_SECRET_KEY` | Clé de chiffrement des jetons de 32 octets, encodée en Base64 || Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | Clé de chiffrement du jeton du bot de 32 octets, encodée en Base64 |+| Telegram | `MULTICA_TELEGRAM_TOOL_PROGRESS` | Étapes d'outils affichées dans la réponse diffusée : `auto` (par défaut : détails en conversation privée, type de travail dans les groupes), `off`, `summary` ou `detail` || Composio | `COMPOSIO_API_KEY` | Active les connexions d'outils Composio || Composio | `COMPOSIO_CALLBACK_BASE_URL` | URL de l'API de rappel ; peut se rabattre sur `MULTICA_PUBLIC_URL` || Composio | `COMPOSIO_STATE_SECRET` | Secret de signature de l'état OAuth ; peut être dérivé de `JWT_SECRET` |diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdxindex dc9e3d9e8a..7e071e3a39 100644--- a/apps/docs/content/docs/environment-variables.ja.mdx+++ b/apps/docs/content/docs/environment-variables.ja.mdx@@ -190,6 +190,7 @@ allowlist の正確な判定順序は[ログインとサインアップ](/auth-s| Lark | `MULTICA_LARK_SECRET_KEY` | base64 エンコードされた 32 バイトの資格情報暗号化キー || Slack | `MULTICA_SLACK_SECRET_KEY` | base64 エンコードされた 32 バイトの token 暗号化キー || Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | base64 エンコードされた 32 バイトの Bot token 暗号化キー |+| Telegram | `MULTICA_TELEGRAM_TOOL_PROGRESS` | ストリーミング返信に表示するツールのステップ。`auto`(既定。DM では詳細、グループでは作業の種類のみ)、`off`、`summary`、`detail` || Composio | `COMPOSIO_API_KEY` | Composio ツール接続を有効化 || Composio | `COMPOSIO_CALLBACK_BASE_URL` | コールバック API アドレス。`MULTICA_PUBLIC_URL` にフォールバック可能 || Composio | `COMPOSIO_STATE_SECRET` | OAuth state の署名シークレット。`JWT_SECRET` から派生可能 |diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdxindex ae2db23dc7..972eab32cc 100644--- a/apps/docs/content/docs/environment-variables.ko.mdx+++ b/apps/docs/content/docs/environment-variables.ko.mdx@@ -190,6 +190,7 @@ reverse proxy 뒤에 배포한다면 실제 proxy 네트워크를 입력해야| Feishu | `MULTICA_LARK_SECRET_KEY` | base64로 인코딩한 32바이트 자격 증명 암호화 키 || Slack | `MULTICA_SLACK_SECRET_KEY` | base64로 인코딩한 32바이트 token 암호화 키 || Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | base64로 인코딩한 32바이트 Bot token 암호화 키 |+| Telegram | `MULTICA_TELEGRAM_TOOL_PROGRESS` | 스트리밍 응답에 표시할 도구 단계. `auto`(기본값: 개인 채팅은 상세, 그룹은 작업 종류만), `off`, `summary`, `detail` || Composio | `COMPOSIO_API_KEY` | Composio 도구 연결 활성화 || Composio | `COMPOSIO_CALLBACK_BASE_URL` | callback API 주소. `MULTICA_PUBLIC_URL`로 fallback 가능 || Composio | `COMPOSIO_STATE_SECRET` | OAuth state 서명 키. `JWT_SECRET`에서 파생 가능 |diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdxindex 9303c5ee66..473c56e8a9 100644--- a/apps/docs/content/docs/environment-variables.mdx+++ b/apps/docs/content/docs/environment-variables.mdx@@ -190,6 +190,7 @@ The auth rate limits require `REDIS_URL`; without it, the startup log notes that| Lark | `MULTICA_LARK_SECRET_KEY` | Base64-encoded 32-byte credential encryption key || Slack | `MULTICA_SLACK_SECRET_KEY` | Base64-encoded 32-byte token encryption key || Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | Base64-encoded 32-byte Bot token encryption key |+| Telegram | `MULTICA_TELEGRAM_TOOL_PROGRESS` | Tool steps shown in the streamed reply: `auto` (default: details in private chats, kind of work in groups), `off`, `summary` or `detail` || Composio | `COMPOSIO_API_KEY` | Enables Composio tool connections || Composio | `COMPOSIO_CALLBACK_BASE_URL` | Callback API URL; can fall back to `MULTICA_PUBLIC_URL` || Composio | `COMPOSIO_STATE_SECRET` | OAuth state signing secret; can be derived from `JWT_SECRET` |diff --git a/apps/docs/content/docs/environment-variables.zh-Hant.mdx b/apps/docs/content/docs/environment-variables.zh-Hant.mdxindex edfb847a26..e3376a169e 100644--- a/apps/docs/content/docs/environment-variables.zh-Hant.mdx+++ b/apps/docs/content/docs/environment-variables.zh-Hant.mdx@@ -186,6 +186,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com| 飛書 | `MULTICA_LARK_SECRET_KEY` | base64 編碼的 32 位元組憑據加密金鑰 || Slack | `MULTICA_SLACK_SECRET_KEY` | base64 編碼的 32 位元組 token 加密金鑰 || Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | base64 編碼的 32 位元組 Bot token 加密金鑰 |+| Telegram | `MULTICA_TELEGRAM_TOOL_PROGRESS` | 流式回覆中展示的工具步驟:`auto`(預設,私聊顯示細節,群聊只顯示工作型別)、`off`、`summary` 或 `detail` || Composio | `COMPOSIO_API_KEY` | 啟用 Composio 工具連線 || Composio | `COMPOSIO_CALLBACK_BASE_URL` | 回撥 API 地址;可回退到 `MULTICA_PUBLIC_URL` || Composio | `COMPOSIO_STATE_SECRET` | OAuth state 簽名金鑰;可從 `JWT_SECRET` 派生 |diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdxindex 84c046536e..f7e7aecf7d 100644--- a/apps/docs/content/docs/environment-variables.zh.mdx+++ b/apps/docs/content/docs/environment-variables.zh.mdx@@ -190,6 +190,7 @@ MULTICA_PUBLIC_URL=https://api.multica.example.com| 飞书 | `MULTICA_LARK_SECRET_KEY` | base64 编码的 32 字节凭据加密密钥 || Slack | `MULTICA_SLACK_SECRET_KEY` | base64 编码的 32 字节 token 加密密钥 || Telegram | `MULTICA_TELEGRAM_SECRET_KEY` | base64 编码的 32 字节 Bot token 加密密钥 |+| Telegram | `MULTICA_TELEGRAM_TOOL_PROGRESS` | 流式回复中展示的工具步骤:`auto`(默认,私聊显示细节,群聊只显示工作类型)、`off`、`summary` 或 `detail` || Composio | `COMPOSIO_API_KEY` | 启用 Composio 工具连接 || Composio | `COMPOSIO_CALLBACK_BASE_URL` | 回调 API 地址;可回退到 `MULTICA_PUBLIC_URL` || Composio | `COMPOSIO_STATE_SECRET` | OAuth state 签名密钥;可从 `JWT_SECRET` 派生 |diff --git a/apps/docs/content/docs/telegram-bot-integration.fr.mdx b/apps/docs/content/docs/telegram-bot-integration.fr.mdxindex b5da2c5cb1..3dad48bcb3 100644--- a/apps/docs/content/docs/telegram-bot-integration.fr.mdx+++ b/apps/docs/content/docs/telegram-bot-integration.fr.mdx@@ -100,7 +100,7 @@ Lorsqu'une réponse adressée au bot cite un message contenant une photo ou un f### Réponses et contenus pris en charge-Le bot diffuse le texte en continu en publiant puis en modifiant un message Telegram, cite le message déclencheur, respecte les sujets de forum et découpe les longues réponses pour rester sous la limite de taille des messages Telegram.+Le bot diffuse le texte en continu en publiant puis en modifiant un message Telegram, cite le message déclencheur, respecte les sujets de forum et découpe les longues réponses pour rester sous la limite de taille des messages Telegram. Pendant que l'agent travaille, le même message liste ses étapes en cours, comme l'exécution d'une commande ou la lecture d'un fichier, avec le temps écoulé. Une conversation privée montre sur quoi porte chaque étape ; un groupe ne montre que le type de travail. Définissez `MULTICA_TELEGRAM_TOOL_PROGRESS` sur `off`, `summary` ou `detail` pour changer ce comportement.Les photos, fichiers, vidéos, messages vocaux et audio parviennent à l'agent sous forme de pièces jointes dans la même conversation, la légende servant de texte du message ; les fichiers produits par l'agent sont renvoyés dans la conversation après sa réponse. Dans les deux sens, le serveur doit disposer d'un stockage objet (voir la section Configuration en auto-hébergement ci-dessous).diff --git a/apps/docs/content/docs/telegram-bot-integration.ja.mdx b/apps/docs/content/docs/telegram-bot-integration.ja.mdxindex 127f521c74..ff5ba5dc6e 100644--- a/apps/docs/content/docs/telegram-bot-integration.ja.mdx+++ b/apps/docs/content/docs/telegram-bot-integration.ja.mdx@@ -100,7 +100,7 @@ Bot 宛ての返信が引用するメッセージに画像やファイルが含### 返信と対応する内容-Bot は Telegram メッセージを送信・編集してテキストをストリーミング表示し、元メッセージを引用して forum topic を維持します。長い返信は Telegram の文字数制限に合わせて自動分割されます。+Bot は Telegram メッセージを送信・編集してテキストをストリーミング表示し、元メッセージを引用して forum topic を維持します。長い返信は Telegram の文字数制限に合わせて自動分割されます。エージェントの作業中は、同じメッセージに現在のステップ(コマンドの実行、ファイルの読み取りなど)と経過時間も表示されます。DM では各ステップの対象まで、グループでは作業の種類だけを表示します。`MULTICA_TELEGRAM_TOOL_PROGRESS`(`off`、`summary`、`detail`)で変更できます。画像、ファイル、動画、ボイス、音声メッセージは、キャプションをメッセージ本文として、同じ会話の添付ファイルとしてエージェントに届きます。エージェントが生成したファイルは返信の後にチャットへ送り返されます。どちらの方向もサーバー側にオブジェクトストレージが必要です(後述のセルフホスト設定を参照)。diff --git a/apps/docs/content/docs/telegram-bot-integration.ko.mdx b/apps/docs/content/docs/telegram-bot-integration.ko.mdxindex f406c3e2b9..f19cfc6dfd 100644--- a/apps/docs/content/docs/telegram-bot-integration.ko.mdx+++ b/apps/docs/content/docs/telegram-bot-integration.ko.mdx@@ -100,7 +100,7 @@ Bot에게 보낸 답장이 인용한 메시지에 이미지나 파일이 있으### 응답과 지원되는 내용-Bot은 Telegram 메시지를 보내고 편집해 텍스트 응답을 스트리밍하며, 원래 메시지를 인용하고 forum topic을 유지합니다. 긴 응답은 Telegram 길이 제한에 맞춰 자동으로 나뉩니다.+Bot은 Telegram 메시지를 보내고 편집해 텍스트 응답을 스트리밍하며, 원래 메시지를 인용하고 forum topic을 유지합니다. 긴 응답은 Telegram 길이 제한에 맞춰 자동으로 나뉩니다. 에이전트가 작업하는 동안에는 같은 메시지에 현재 단계(명령 실행, 파일 읽기 등)와 경과 시간도 표시됩니다. 개인 채팅에서는 각 단계의 대상까지, 그룹에서는 작업 종류만 보여 줍니다. `MULTICA_TELEGRAM_TOOL_PROGRESS`(`off`, `summary`, `detail`)로 바꿀 수 있습니다.이미지, 파일, 영상, 음성 메시지, 오디오는 caption을 메시지 본문으로 하여 같은 대화의 첨부 파일로 에이전트에 전달됩니다. 에이전트가 만든 파일은 응답 뒤에 채팅으로 다시 전송됩니다. 두 방향 모두 서버에 객체 스토리지가 필요합니다(아래 자체 호스팅 설정 참고).diff --git a/apps/docs/content/docs/telegram-bot-integration.mdx b/apps/docs/content/docs/telegram-bot-integration.mdxindex 1b3cd76e99..6d32a1983c 100644--- a/apps/docs/content/docs/telegram-bot-integration.mdx+++ b/apps/docs/content/docs/telegram-bot-integration.mdx@@ -100,7 +100,7 @@ When a reply that addresses the Bot quotes a message carrying a photo or file, t### Replies and supported content-The Bot streams text by posting and editing a Telegram message, quotes the triggering message, preserves forum topics, and splits long replies under Telegram's message limit.+The Bot streams text by posting and editing a Telegram message, quotes the triggering message, preserves forum topics, and splits long replies under Telegram's message limit. While the agent works, the same message lists its current steps, such as running a command or reading a file, with the time elapsed. A private chat shows what each step is working on; a group shows only the kind of work. Set `MULTICA_TELEGRAM_TOOL_PROGRESS` to `off`, `summary` or `detail` to change this.Photos, files, video, voice, and audio messages reach the agent as attachments on the same conversation, with the caption as the message text, and files the agent produces are sent back into the chat after its reply. Both directions need object storage on the server (see the self-hosting section below).diff --git a/apps/docs/content/docs/telegram-bot-integration.zh-Hant.mdx b/apps/docs/content/docs/telegram-bot-integration.zh-Hant.mdxindex d1c97a46b2..be4513e5a5 100644--- a/apps/docs/content/docs/telegram-bot-integration.zh-Hant.mdx+++ b/apps/docs/content/docs/telegram-bot-integration.zh-Hant.mdx@@ -100,7 +100,7 @@ Multica 會實時請求 Telegram 驗證 Bot,檢查是否存在與長輪詢衝### 回覆與內容範圍-Bot 透過傳送並編輯 Telegram 訊息來流式展示文字回覆,引用觸發訊息、保留 forum topic,並按 Telegram 長度限制自動分段。+Bot 透過傳送並編輯 Telegram 訊息來流式展示文字回覆,引用觸發訊息、保留 forum topic,並按 Telegram 長度限制自動分段。AI 代理工作時,同一則訊息下方會列出它目前的步驟(如執行命令、讀取檔案)和已用時間:私聊顯示每一步的具體物件,群聊只顯示工作型別。可用 `MULTICA_TELEGRAM_TOOL_PROGRESS`(`off`、`summary`、`detail`)調整。圖片、檔案、影片、語音和音訊訊息會作為同一對話的附件交給 AI 代理,caption 作為訊息正文;AI 代理生成的檔案會在回覆之後發回聊天。這兩個方向都需要服務端配置物件儲存(見下文自託管部分)。diff --git a/apps/docs/content/docs/telegram-bot-integration.zh.mdx b/apps/docs/content/docs/telegram-bot-integration.zh.mdxindex b79a0820ef..d860117ad7 100644--- a/apps/docs/content/docs/telegram-bot-integration.zh.mdx+++ b/apps/docs/content/docs/telegram-bot-integration.zh.mdx@@ -100,7 +100,7 @@ Multica 会实时请求 Telegram 验证 Bot,检查是否存在与长轮询冲### 回复与内容范围-Bot 通过发送并编辑 Telegram 消息来流式展示文字回复,引用触发消息、保留 forum topic,并按 Telegram 长度限制自动分段。+Bot 通过发送并编辑 Telegram 消息来流式展示文字回复,引用触发消息、保留 forum topic,并按 Telegram 长度限制自动分段。智能体工作时,同一条消息下方会列出它当前的步骤(如执行命令、读取文件)和已用时间:私聊显示每一步的具体对象,群聊只显示工作类型。可用 `MULTICA_TELEGRAM_TOOL_PROGRESS`(`off`、`summary`、`detail`)调整。图片、文件、视频、语音和音频消息会作为同一对话的附件交给智能体,caption 作为消息正文;智能体生成的文件会在回复之后发回聊天。这两个方向都需要服务端配置对象存储(见下文自托管部分)。diff --git a/docker-compose.selfhost.yml b/docker-compose.selfhost.ymlindex 9b89bac181..8d8985449c 100644--- a/docker-compose.selfhost.yml+++ b/docker-compose.selfhost.yml@@ -229,6 +229,9 @@ services:# (bot_token_encrypted), so this single deployment-wide key is all# the operator needs to set here.MULTICA_TELEGRAM_SECRET_KEY: ${MULTICA_TELEGRAM_SECRET_KEY:-}+ # Tool steps shown in the streamed reply: auto (default; details in+ # private chats, kind of work in groups), off, summary or detail.+ MULTICA_TELEGRAM_TOOL_PROGRESS: ${MULTICA_TELEGRAM_TOOL_PROGRESS:-}restart: unless-stoppedfrontend:diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex d1912fff2e..8835a58a71 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1274,6 +1274,14 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// as WeCom above).var telegramMedia engine.MediaResolvertelegramOutbound := telegram.NewOutbound(queries, box.Open, "", nil, slog.Default())+ // How much of a run's tool calls the streamed reply shows: auto+ // (default), off, summary or detail.+ progressMode, known := telegram.ParseProgressMode(os.Getenv("MULTICA_TELEGRAM_TOOL_PROGRESS"))+ if !known {+ slog.Warn("telegram: unknown MULTICA_TELEGRAM_TOOL_PROGRESS; using auto",+ "value", os.Getenv("MULTICA_TELEGRAM_TOOL_PROGRESS"))+ }+ telegramOutbound.SetProgressMode(progressMode)if store != nil {telegramMedia = telegram.NewMediaResolver(box.Open, store, engine.NewDBMediaIntentLedger(queries), "", nil, slog.Default())telegramOutbound.EnableFileDelivery(store)diff --git a/server/internal/integrations/telegram/api.go b/server/internal/integrations/telegram/api.goindex 8c4bd31ad2..673521664e 100644--- a/server/internal/integrations/telegram/api.go+++ b/server/internal/integrations/telegram/api.go@@ -419,6 +419,15 @@ func (a *botAPI) EditMessageText(ctx context.Context, p editMessageTextParams) ereturn a.call(ctx, "editMessageText", p, nil)}+// DeleteMessage removes a message the bot sent. A bot may delete its own+// messages for 48 hours.+func (a *botAPI) DeleteMessage(ctx context.Context, chatID, messageID int64) error {+ return a.call(ctx, "deleteMessage", struct {+ ChatID int64 `json:"chat_id"`+ MessageID int64 `json:"message_id"`+ }{ChatID: chatID, MessageID: messageID}, nil)+}+// SendChatAction shows the native "typing…" indicator for ~5s in the same// forum topic as the triggering message, when applicable.func (a *botAPI) SendChatAction(ctx context.Context, chatID, messageThreadID int64) error {diff --git a/server/internal/integrations/telegram/outbound.go b/server/internal/integrations/telegram/outbound.goindex 00ec25c992..842a2ab3e3 100644--- a/server/internal/integrations/telegram/outbound.go+++ b/server/internal/integrations/telegram/outbound.go@@ -17,6 +17,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/integrations/channel""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated""github.com/multica-ai/multica/server/pkg/protocol"@@ -29,8 +30,9 @@ import (// Streaming: Telegram has no stream-update protocol, so the "stream 帧" UX is// simulated with the platform's canonical pattern — post one placeholder// message on the first partial, then throttled editMessageText calls as the-// agent's transcript grows (EventTaskMessage text frames), and a final edit /-// send on EventChatDone. Edits are throttled per chat to stay inside+// agent's transcript grows (EventTaskMessage text frames, with the tool calls+// in between shown as steps under the text — outbound_progress.go), and a+// final edit / send on EventChatDone. Edits are throttled per chat to stay inside// Telegram's editMessageText rate budget; on a 429 the streamer backs off and// the final content always lands via the EventChatDone path.type Outbound struct {@@ -52,6 +54,18 @@ type Outbound struct {now func() time.Timewait func(context.Context, time.Duration) error+ // progress is how much of a run's tool calls a chat is shown. Set before+ // Register and not changed after.+ progress ProgressMode+ // heartbeat is how long to wait before moving the clock under a list of+ // steps. A field so a test need not wait out the real cadence.+ heartbeat func(chatID int64, quiet time.Duration) time.Duration++ // flushCtx is the worker context from Start. Deferred pushes of held-back+ // stream text run on it; nil until Start, and then nothing is deferred.+ // Protected by mu.+ flushCtx context.Context+terminalMu sync.MutexterminalSessions map[string]*terminalSessionterminalReady []string@@ -79,6 +93,7 @@ type Outbound struct {type outboundQueries interface {GetChannelTaskDelivery(ctx context.Context, taskID pgtype.UUID) (db.ChannelTaskDelivery, error)GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)+ ListTaskReplyFragments(ctx context.Context, taskID pgtype.UUID) ([]db.ListTaskReplyFragmentsRow, error)// ListAttachmentsByChatMessage is the files the agent bound to its reply,// read by the attachment hop (outbound_media.go).ListAttachmentsByChatMessage(ctx context.Context, arg db.ListAttachmentsByChatMessageParams) ([]db.Attachment, error)@@ -115,6 +130,26 @@ type streamState struct {lastFrameAt time.Timeaccumulated stringschedule *chatSchedule+ // target is where the reply goes, resolved by the frame that opened the+ // stream and reused by every later one.+ target *replyTarget+ // steps is what the agent is doing right now, shown under the text.+ steps stepFeed+ // startedAt is when this process first saw the run; the clock under the+ // steps counts from it.+ startedAt time.Time+ // lastPushed is the body the chat shows, so a push that would change+ // nothing is not sent.+ lastPushed string+ // ended is set when the run is over and the stream is released, for a+ // request that was with Telegram at that moment.+ ended bool+ // flushAt is when the stream's deferred push is due; zero when none is+ // armed. One per stream: held-back frames and the clock share it.+ // flushGen names the timer that is current.+ flushAt time.Time+ flushTimer *time.Timer+ flushGen uint64}// chatSchedule serializes Telegram delivery and owns rate-limit state shared@@ -155,11 +190,13 @@ type terminalReply struct {fallbackFreshSend boolplainTextFallback boolplainTextEdit bool- kind terminalKind- settleReason string- turn replyTurn- turnResolved bool- lease *deliveryLease+ kind terminalKind+ settleReason string+ turn replyTurn+ turnResolved bool+ lease *deliveryLease+ // remnant is the steps a turn that ends without an answer left on screen.+ remnant *streamRemnantacquireAttempts inteditAttempts intcleanupOnce sync.Once@@ -210,11 +247,26 @@ func (h *terminalRetryHeap) Pop() any {return x}-// editInterval is the minimum spacing between editMessageText calls per chat.-// Telegram tolerates roughly one edit per second per chat, with a much-// stricter per-group budget (~20 messages/min); 2.5s keeps a long generation-// well inside both without feeling static.-const editInterval = 2500 * time.Millisecond+// The minimum spacing between two requests to one chat, edits included:+// Telegram counts an editMessageText against the same allowance as a+// sendMessage. It allows a chat about one message a second and a group 20 a+// minute, so each kind of chat is paced at its own limit. One spacing for both+// either stalls a group on a 429 or makes a private chat update in jumps.+const (+ privateEditInterval = time.Second+ groupEditInterval = 3 * time.Second+)++// editIntervalFor picks the spacing from the chat id: Telegram gives users+// positive ids and groups, supergroups and channels negative ones.+func editIntervalFor(chatID int64) time.Duration {+ if chatID < 0 {+ return groupEditInterval+ }+ return privateEditInterval+}++func (s *chatSchedule) editInterval() time.Duration { return editIntervalFor(s.key.chatID) }// placeholderSettleRetry re-checks a stream whose placeholder sendMessage is// still in flight. A check costs one map lookup — the delivery target is@@ -289,6 +341,8 @@ func NewOutbound(q outboundQueries, decrypt Decrypter, apiBase string, client *hbotFallbackBackoff: make(map[string]time.Time),now: time.Now,wait: waitForOutbound,+ progress: ProgressAuto,+ heartbeat: heartbeatInterval,terminalSessions: make(map[string]*terminalSession),terminalWake: make(chan struct{}, 1),terminalWork: make(chan terminalWork, terminalWorkerCount),@@ -301,6 +355,9 @@ func NewOutbound(q outboundQueries, decrypt Decrypter, apiBase string, client *h// Register subscribes to the transcript / completion / failure events.func (o *Outbound) Register(bus *events.Bus) {bus.Subscribe(protocol.EventTaskMessage, o.handleTaskMessage)+ if o.progress != ProgressOff {+ bus.Subscribe(protocol.EventTaskProgress, o.handleTaskProgress)+ }bus.Subscribe(protocol.EventChatDone, o.enqueueTerminalReply)bus.Subscribe(protocol.EventTaskFailed, o.handleTaskFailed)bus.Subscribe(protocol.EventTaskCancelled, o.handleTaskCancelled)@@ -311,6 +368,9 @@ func (o *Outbound) Register(bus *events.Bus) {// Telegram rate limits and network latency must never delay realtime fanout.func (o *Outbound) Start(ctx context.Context) {o.workerOnce.Do(func() {+ o.mu.Lock()+ o.flushCtx = ctx+ o.mu.Unlock()o.workerWG.Add(2)go o.runStreamSweeper(ctx)o.terminalWorkerWG.Add(terminalWorkerCount)@@ -338,38 +398,95 @@ func (o *Outbound) WaitWithTimeout(timeout time.Duration) bool {}}-// handleTaskMessage streams a partial: on each agent text frame, update the-// placeholder message (throttled). Bus delivery is synchronous, so all work-// runs under a tight timeout and never propagates errors.+// handleTaskMessage streams a partial: each agent text frame grows the reply,+// and each tool call or error is a step shown under it. Bus delivery is+// synchronous, so all work runs under a tight timeout and never propagates+// errors.func (o *Outbound) handleTaskMessage(e events.Event) {payload, ok := e.Payload.(protocol.TaskMessagePayload)- if !ok || payload.Type != "text" || payload.Content == "" {+ if !ok {+ return+ }+ switch payload.Type {+ case "text":+ if payload.Content == "" {+ return+ }+ case "tool_use", "error":+ if o.progress == ProgressOff {+ return+ }+ default:+ // A tool's output above all: it is most of the event's volume and none+ // of it belongs in the chat.return}ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)defer cancel()+ target, turn, ok := o.streamTarget(ctx, e)+ if !ok {+ return+ }+ frame := streamFrame{text: payload.Content}+ if payload.Type != "text" {+ step, ok := o.stepFor(target, payload)+ if !ok {+ return+ }+ frame = streamFrame{step: &step}+ }+ o.advanceStream(ctx, target, turn, frame)+}++// streamTarget is where a frame's reply goes and which turn it belongs to.+// Both are fixed for a run, so a reply already streaming answers from memory:+// frames arrive several a second on the synchronous bus, and resolving each+// one cost two database reads.+func (o *Outbound) streamTarget(ctx context.Context, e events.Event) (*replyTarget, replyTurn, bool) {+ if taskID, ok := eventTaskID(e); ok {+ o.mu.Lock()+ st := o.streams[util.UUIDToString(taskID)]+ o.mu.Unlock()+ if st != nil && st.target != nil {+ return st.target, st.turn, true+ }+ }target, err := o.resolveTarget(ctx, e, true)if err != nil || target == nil {- return+ return nil, replyTurn{}, false+ }+ turn, err := o.turnFor(ctx, target.taskID)+ if err != nil {+ // Treating the task as its own turn here would open a second reply+ // beside the one a previous attempt is still holding.+ o.logger.WarnContext(ctx, "telegram outbound: skipping stream frame; reply turn unresolved", "error", err)+ return nil, replyTurn{}, false}+ return target, turn, true+}+// advanceStream adds a frame to the task's streamed reply and pushes the+// result to Telegram. An empty frame is the deferred push: it sends what an+// earlier frame left behind, or moves the clock, and never opens a stream.+func (o *Outbound) advanceStream(ctx context.Context, target *replyTarget, turn replyTurn, frame streamFrame) {+ // Keep the frame before asking for the turn. The deferred push holds the+ // turn while it talks to Telegram, and a frame that arrives meanwhile must+ // not leave a hole in what the next push shows.o.mu.Lock()- st, exists := o.streams[target.streamKey]- turn := replyTurn{}- if exists {- turn = st.turn- }- o.mu.Unlock()- if !turn.id.Valid {- resolved, err := o.turnFor(ctx, target.taskID)- if err != nil {- // Treating the task as its own turn here would open a second reply- // beside the one a previous attempt is still holding.- o.logger.WarnContext(ctx, "telegram outbound: skipping stream frame; reply turn unresolved", "error", err)+ st := o.streams[target.streamKey]+ if st != nil && !frame.empty() {+ now := o.now()+ st.absorb(frame, now)+ frame = streamFrame{}+ if !st.flushAt.IsZero() && st.flushAt.Sub(now) <= st.schedule.editInterval() {+ // A push is already waiting for the chat's next slot and carries+ // this frame with it. A burst of tool calls costs one edit and no+ // database round trip per call.+ o.mu.Unlock()return}- turn = resolved}+ o.mu.Unlock()// Hold the turn for as long as this frame is talking to Telegram. A frame// that checked the state and then sent would still race the final answer@@ -385,12 +502,16 @@ func (o *Outbound) handleTaskMessage(e events.Event) {// reach into this process to tidy up. Release the local stream and its// chat-scheduler reference here, or they are held for good and the// schedule table eventually refuses new chats.- o.clearStream(e)+ o.clearStreamKey(target.streamKey)return}if status != deliveryAcquired {// Another path owns the turn right now. A stream frame is decoration —- // the answer still lands — so it steps aside.+ // the answer still lands — so it steps aside. What it has already kept+ // is pushed once the turn is free again.+ if st != nil {+ o.armFlush(target, st, o.now().Add(deliveryBusyRetry))+ }return}defer o.releaseDelivery(ctx, lease)@@ -400,8 +521,13 @@ func (o *Outbound) handleTaskMessage(e events.Event) {}o.mu.Lock()- st, exists = o.streams[target.streamKey]+ st, exists := o.streams[target.streamKey]+ now := o.now()if !exists {+ if frame.empty() {+ o.mu.Unlock()+ return+ }schedule := o.retainChatLocked(target.botKey, target.chatID)if schedule == nil {o.mu.Unlock()@@ -409,11 +535,10 @@ func (o *Outbound) handleTaskMessage(e events.Event) {}st = &streamState{chatID: target.chatID, threadID: target.threadID, replyTo: target.replyTo,- turn: turn, schedule: schedule,+ target: target, turn: turn, schedule: schedule, startedAt: now, lastFrameAt: now,}o.streams[target.streamKey] = st}- st.lastFrameAt = o.now()// A reply this process did not start — the placeholder came from another// replica, or from the attempt this automatic retry inherited — still// edits that message instead of opening a second one. Its text is whatever@@ -421,41 +546,143 @@ func (o *Outbound) handleTaskMessage(e events.Event) {if msgID := lease.messageID(); msgID != 0 {st.messageID = msgID}- st.accumulated += payload.Content- snapshot := st.accumulated- msgID := st.messageID+ st.absorb(frame, now)+ body := st.render(now)+ unchanged := st.messageID != 0 && body == st.lastPushed+ o.mu.Unlock()++ if unchanged {+ // The chat already shows exactly this. Not asking Telegram to confirm+ // it keeps the request for an edit that changes something.+ o.armHeartbeat(target, st)+ return+ }+ pushed, retryAt := o.pushPartial(ctx, target, st, lease, body)+ if pushed {+ o.mu.Lock()+ var remnant *streamRemnant+ if st.ended {+ // The run was cancelled while this request was with Telegram, so+ // what it put in the chat was not there to be tidied. This frame+ // still holds the turn: tidy it now.+ remnant = o.remnantLocked(st)+ }+ o.mu.Unlock()+ if remnant != nil {+ o.tidyRemnant(ctx, remnant)+ return+ }+ }+ switch {+ case !retryAt.IsZero():+ o.armFlush(target, st, retryAt)+ case pushed:+ o.armHeartbeat(target, st)+ }+}++// armFlush arms the stream's one deferred push, for what a frame could not+// send yet. Without it that waits for the next frame, and an agent that writes+// a sentence and then works in tools for minutes sends none: the chat shows+// the first word until the final answer.+//+// A push already armed for an earlier moment stands; a later one gives way.+// It needs the worker context from Start, so the timer ends with the process.+func (o *Outbound) armFlush(target *replyTarget, st *streamState, at time.Time) {+ o.mu.Lock()+ defer o.mu.Unlock()+ if o.flushCtx == nil || o.streams[target.streamKey] != st {+ return+ }+ if !st.flushAt.IsZero() && !st.flushAt.After(at) {+ return+ }+ if st.flushTimer != nil {+ st.flushTimer.Stop()+ }+ st.flushGen+++ gen := st.flushGen+ st.flushAt = at+ st.flushTimer = time.AfterFunc(max(at.Sub(o.now()), 0), func() { o.flushStream(target, st, gen) })+}++// armHeartbeat keeps the clock under a list of steps moving while the agent+// is quiet. A tool can run for minutes without a frame, and a message that+// does not change for that long is indistinguishable from a run that hung.+func (o *Outbound) armHeartbeat(target *replyTarget, st *streamState) {+ o.mu.Lock()+ now := o.now()+ wait := time.Duration(0)+ if len(st.steps.lines) > 0 {+ wait = o.heartbeat(st.chatID, now.Sub(st.lastFrameAt))+ }o.mu.Unlock()+ if wait > 0 {+ o.armFlush(target, st, now.Add(wait))+ }+}- o.pushPartial(ctx, target, st, lease, msgID, snapshot)+// flushStream is the deferred push. The stream may be gone by now — finished,+// cancelled, or taken over by the final answer — and then there is nothing to+// do. gen tells a timer that was replaced after it fired from the current one.+func (o *Outbound) flushStream(target *replyTarget, st *streamState, gen uint64) {+ o.mu.Lock()+ if st.flushGen != gen {+ o.mu.Unlock()+ return+ }+ st.flushAt = time.Time{}+ st.flushTimer = nil+ live := o.streams[target.streamKey] == st+ turn := st.turn+ flushCtx := o.flushCtx+ o.mu.Unlock()+ if !live || flushCtx.Err() != nil {+ return+ }+ ctx, cancel := context.WithTimeout(flushCtx, 10*time.Second)+ defer cancel()+ o.advanceStream(ctx, target, turn, streamFrame{})}-// pushPartial sends the placeholder on the first flush and edits it after. It+// pushPartial sends the placeholder on the first push and edits it after. It// runs under the turn's lease, so the final answer cannot take the reply over// between the decision made here and the call that acts on it.-func (o *Outbound) pushPartial(ctx context.Context, target *replyTarget, st *streamState, lease *deliveryLease, msgID int64, snapshot string) {+//+// It reports whether the chat now shows body. A non-zero time is when the+// chat can next take an edit: body was held back, and the caller arranges for+// the stream to be pushed then.+func (o *Outbound) pushPartial(ctx context.Context, target *replyTarget, st *streamState, lease *deliveryLease, body string) (bool, time.Time) {if !st.schedule.mu.TryLock() {- return+ // A request to this chat is in flight, so its next slot is one+ // interval away.+ return false, o.now().Add(st.schedule.editInterval())}defer st.schedule.mu.Unlock()now := o.now()- if o.terminalAvailableAt(st.schedule, target.botKey, now).After(now) {- return+ if available := o.terminalAvailableAt(st.schedule, target.botKey, now); available.After(now) {+ return false, available}- api := newBotAPI(o.apiBase, target.botToken, o.client)- text := snapshot- if utf16Units(text) > maxMessageUnits {- // Mid-stream overflow: freeze the streamed message at the cap; the full- // reply is delivered in chunks by the final EventChatDone send.- text = chunkMessage(text, maxMessageUnits)[0]- }o.mu.Lock()if o.streams[target.streamKey] != st {o.mu.Unlock()- return+ return false, time.Time{}}- msgID = st.messageID+ msgID := st.messageIDo.mu.Unlock()+ // Routing is immutable, but installation status and credentials are not.+ // Revalidate at the actual send slot, including deferred/heartbeat pushes.+ token, err := o.activeBotToken(ctx, target.installationID)+ if err != nil {+ o.logger.WarnContext(ctx, "telegram outbound: cannot revalidate stream installation", "error", err)+ return false, time.Time{}+ }+ if token == "" {+ o.clearStreamKey(target.streamKey)+ return false, time.Time{}+ }+ api := newBotAPI(o.apiBase, token, o.client)if msgID != 0 {// Re-prove the turn immediately before the edit. Acquiring it and then@@ -463,29 +690,31 @@ func (o *Outbound) pushPartial(ctx context.Context, target *replyTarget, st *str// lease, and an edit made afterwards overwrites whatever the process// that took over has already published as the final answer.if !o.renewDelivery(ctx, lease) {- return+ return false, time.Time{}}ctx, cancel := o.callContext(ctx)defer cancel()err := api.EditMessageText(ctx, editMessageTextParams{ChatID: st.chatID,MessageID: msgID,- Text: formatHTML(text),+ Text: body,ParseMode: "HTML",})if err != nil && !isNotModified(err) {- o.noteEditFailure(st.schedule, err)- return+ return false, o.noteEditFailure(st.schedule, err)}st.schedule.lastEdit = o.now()- return+ o.mu.Lock()+ st.lastPushed = body+ o.mu.Unlock()+ return true, time.Time{}}// Exactly one placeholder per turn, published before the call goes out so// that any other process reads "a send is outstanding" rather than// "nothing has been sent".if !o.claimSend(ctx, lease) {- return+ return false, time.Time{}}ctx, cancel := o.callContext(ctx)defer cancel()@@ -495,32 +724,36 @@ func (o *Outbound) pushPartial(ctx context.Context, target *replyTarget, st *str}m, err := api.SendMessage(ctx, sendMessageParams{ChatID: st.chatID,- Text: firstNonEmpty(formatHTML(text), streamPlaceholder),+ Text: firstNonEmpty(body, streamPlaceholder),ParseMode: "HTML",MessageThreadID: st.threadID,ReplyParameters: reply,})if o.recordSend(ctx, lease, true, m.MessageID, 0, err) != deliveryAccepted {if err != nil {- o.noteEditFailure(st.schedule, err)+ return false, o.noteEditFailure(st.schedule, err)}- return+ return false, time.Time{}}st.schedule.lastEdit = o.now()o.mu.Lock()st.messageID = m.MessageID+ st.lastPushed = bodyo.mu.Unlock()+ return true, time.Time{}}-// noteEditFailure applies the 429-mandated backoff to the stream; other-// failures are logged and the stream simply stops editing (the final content-// still lands via EventChatDone).-func (o *Outbound) noteEditFailure(schedule *chatSchedule, err error) {+// noteEditFailure applies the 429-mandated backoff to the stream and returns+// when it ends; other failures are logged and the stream simply stops editing+// (the final content still lands via EventChatDone).+func (o *Outbound) noteEditFailure(schedule *chatSchedule, err error) time.Time {if wait, ok := retryAfter(err); ok {- schedule.setBackoffTill(o.now().Add(wait))- return+ till := o.now().Add(wait)+ schedule.setBackoffTill(till)+ return till}o.logger.Warn("telegram outbound: stream edit failed", "error", err)+ return time.Time{}}// enqueueTerminalReply only appends to a bounded keyed FIFO. events.Bus is synchronous;@@ -533,17 +766,18 @@ func (o *Outbound) enqueueTerminalReply(e events.Event) {// close itself is a database write and belongs on a worker, not on the// synchronous bus.if settleOnly := chatDoneContent(e.Payload) == ""; settleOnly {- o.clearStream(e)- o.enqueueTerminal(e, terminalKindClose, "empty_reply")+ o.enqueueTerminal(e, terminalKindClose, "empty_reply", o.takeStream(e))return}- o.enqueueTerminal(e, terminalKindAnswer, "")+ o.enqueueTerminal(e, terminalKindAnswer, "", nil)}// enqueueTerminal appends to a bounded keyed FIFO. events.Bus is synchronous,// so nothing here may touch Telegram or the database — that work belongs to// the terminal workers.-func (o *Outbound) enqueueTerminal(e events.Event, kind terminalKind, settleReason string) {+//+// remnant is what a turn ending without an answer left in the chat to tidy.+func (o *Outbound) enqueueTerminal(e events.Event, kind terminalKind, settleReason string, remnant *streamRemnant) {_, hasTaskID := eventTaskID(e)sessionID, sessionErr := util.ParseUUID(e.ChatSessionID)if !hasTaskID || sessionErr != nil || !sessionID.Valid {@@ -584,7 +818,7 @@ func (o *Outbound) enqueueTerminal(e events.Event, kind terminalKind, settleReasreturn}session.queue = append(session.queue, &terminalReply{- event: e, byteSize: replyBytes, kind: kind, settleReason: settleReason,+ event: e, byteSize: replyBytes, kind: kind, settleReason: settleReason, remnant: remnant,})o.queuedTerminalReplyCount++o.queuedTerminalReplyBytes += replyBytes@@ -848,6 +1082,14 @@ func (o *Outbound) initializeTerminalReply(ctx context.Context, reply *terminalR// automatic retry has superseded, finds the turn closed already.o.deliverAttachments(ctx, reply)}+ remnant, err := o.recoverStreamRemnant(ctx, target, reply.turn, reply.settleReason, reply.remnant)+ if err != nil {+ if retryAt, ok := o.retryDeliveryAcquire(reply, maxDeliveryClaimErrorAttempts); ok {+ return terminalRequestResult{retryAt: retryAt}+ }+ return terminalRequestResult{done: true, err: err}+ }+ o.tidyRemnant(ctx, remnant)return terminalRequestResult{done: true}}@@ -902,6 +1144,9 @@ func (o *Outbound) initializeTerminalReply(ctx context.Context, reply *terminalRreturn terminalRequestResult{retryAt: o.now().Add(chatCapacityRetry)}}}+ if st := o.streams[target.streamKey]; st != nil && st.flushTimer != nil {+ st.flushTimer.Stop()+ }delete(o.streams, target.streamKey)o.mu.Unlock()@@ -1001,7 +1246,7 @@ func (o *Outbound) editStreamedReply(ctx context.Context, api *botAPI, reply *teo.deliverAttachments(ctx, reply)return terminalRequestResult{done: true}}- return terminalRequestResult{retryAt: schedule.lastEdit.Add(editInterval)}+ return terminalRequestResult{retryAt: schedule.lastEdit.Add(schedule.editInterval())}}// sendReplyChunk posts one part of the final answer. The send is published@@ -1058,7 +1303,7 @@ func (o *Outbound) sendReplyChunk(ctx context.Context, api *botAPI, reply *termio.deliverAttachments(ctx, reply)return terminalRequestResult{done: true}}- return terminalRequestResult{retryAt: schedule.lastEdit.Add(editInterval)}+ return terminalRequestResult{retryAt: schedule.lastEdit.Add(schedule.editInterval())}}func (o *Outbound) cleanupTerminalReply(reply *terminalReply) {@@ -1090,7 +1335,7 @@ func (o *Outbound) handleTaskFailed(e events.Event) {o.clearStream(e)return}- o.enqueueTerminal(e, terminalKindNotice, "failure_notice")+ o.enqueueTerminal(e, terminalKindNotice, "failure_notice", nil)}// deliverFailureNotice posts the run-failed notice, one Telegram call per@@ -1196,8 +1441,7 @@ func (o *Outbound) editNoticeOntoPlaceholder(ctx context.Context, api *botAPI, r// synthetic notice is worse than keeping it — but closes the reply so a text// frame still in flight cannot open a second message beside it.func (o *Outbound) handleTaskCancelled(e events.Event) {- o.clearStream(e)- o.enqueueTerminal(e, terminalKindClose, "cancelled")+ o.enqueueTerminal(e, terminalKindClose, "cancelled", o.takeStream(e))}func taskFailureRetryPending(payload any) bool {@@ -1214,11 +1458,17 @@ func (o *Outbound) clearStream(e events.Event) {if !ok {return}- key := util.UUIDToString(taskID)+ o.clearStreamKey(util.UUIDToString(taskID))+}++func (o *Outbound) clearStreamKey(key string) {o.mu.Lock()st := o.streams[key]delete(o.streams, key)if st != nil {+ if st.flushTimer != nil {+ st.flushTimer.Stop()+ }o.releaseChatLocked(st.schedule, st.chatID)}o.mu.Unlock()@@ -1302,6 +1552,9 @@ func (o *Outbound) sweepSettledStreams(ctx context.Context) {// Re-check under the lock: a frame may have arrived while we were// asking, which both revives the stream and makes the answer stale.if current, ok := o.streams[c.key]; ok && current == c.stream && current.lastFrameAt.Equal(c.seenAt) {+ if current.flushTimer != nil {+ current.flushTimer.Stop()+ }delete(o.streams, c.key)o.releaseChatLocked(current.schedule, current.chatID)o.logger.Info("telegram outbound: released local state for a turn that ended elsewhere",@@ -1351,7 +1604,7 @@ func (o *Outbound) makeChatScheduleRoomLocked(now time.Time) bool {var inactive *chatSchedulefor key, schedule := range o.chats {if schedule.refs != 0 || schedule.idleSince.IsZero() ||- now.Sub(schedule.idleSince) < editInterval || schedule.hasActiveBackoff(now) {+ now.Sub(schedule.idleSince) < schedule.editInterval() || schedule.hasActiveBackoff(now) {continue}if inactive == nil || schedule.idleSince.Before(inactive.idleSince) {@@ -1367,7 +1620,7 @@ func (o *Outbound) makeChatScheduleRoomLocked(now time.Time) bool {var active *chatSchedulefor key, schedule := range o.chats {if schedule.refs != 0 || schedule.idleSince.IsZero() ||- now.Sub(schedule.idleSince) < editInterval || !schedule.hasActiveBackoff(now) {+ now.Sub(schedule.idleSince) < schedule.editInterval() || !schedule.hasActiveBackoff(now) {continue}if !o.canMergeBotFallbackLocked(schedule.key.botKey, now) {@@ -1417,7 +1670,7 @@ func (o *Outbound) botFallbackTill(botKey string, now time.Time) time.Time {func (o *Outbound) terminalAvailableAt(schedule *chatSchedule, botKey string, now time.Time) time.Time {available := schedule.backoffTill- if editAvailable := schedule.lastEdit.Add(editInterval); editAvailable.After(available) {+ if editAvailable := schedule.lastEdit.Add(schedule.editInterval()); editAvailable.After(available) {available = editAvailable}if fallback := o.botFallbackTill(botKey, now); fallback.After(available) {@@ -1491,6 +1744,8 @@ type replyTarget struct {threadID int64replyTo int64botToken string+ // private is a one-to-one chat with the person the run belongs to.+ private bool// Identity of the reply this target belongs to, for the ownership row.taskID pgtype.UUID@@ -1519,35 +1774,46 @@ func (o *Outbound) resolveTarget(ctx context.Context, e events.Event, _ bool) (*return nil, nil}binding := telegramBindingFromTaskDelivery(delivery)- inst, err := o.q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{- ID: binding.InstallationID,- ChannelType: string(TypeTelegram),- })+ token, err := o.activeBotToken(ctx, binding.InstallationID)if err != nil {- return nil, fmt.Errorf("load telegram installation: %w", err)+ return nil, err}- if inst.Status != "active" {+ if token == "" {return nil, nil // revoked between trigger and reply}- creds, err := decodeCredentials(inst.Config, o.decrypt)- if err != nil {- return nil, fmt.Errorf("decode telegram credentials: %w", err)- }chatID, threadID, replyTo := outboundTarget(binding)return &replyTarget{streamKey: util.UUIDToString(taskID),- botKey: util.UUIDToString(inst.ID),+ botKey: util.UUIDToString(binding.InstallationID),chatID: chatID,threadID: threadID,replyTo: replyTo,- botToken: creds.BotToken,+ botToken: token,+ private: delivery.ChatType == string(channel.ChatTypeP2P),taskID: taskID,bindingID: delivery.BindingID,- installationID: inst.ID,+ installationID: binding.InstallationID,channelChatID: delivery.ChannelChatID,}, nil}+func (o *Outbound) activeBotToken(ctx context.Context, installationID pgtype.UUID) (string, error) {+ inst, err := o.q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{+ ID: installationID, ChannelType: string(TypeTelegram),+ })+ if err != nil {+ return "", fmt.Errorf("load telegram installation: %w", err)+ }+ if inst.Status != "active" {+ return "", nil+ }+ creds, err := decodeCredentials(inst.Config, o.decrypt)+ if err != nil {+ return "", fmt.Errorf("decode telegram credentials: %w", err)+ }+ return creds.BotToken, nil+}+func telegramBindingFromTaskDelivery(delivery db.ChannelTaskDelivery) db.ChannelChatSessionBinding {return db.ChannelChatSessionBinding{ID: delivery.BindingID, InstallationID: delivery.InstallationID,diff --git a/server/internal/integrations/telegram/outbound_delivery_boundaries_test.go b/server/internal/integrations/telegram/outbound_delivery_boundaries_test.goindex bbc0cc3ce6..0737b4169e 100644--- a/server/internal/integrations/telegram/outbound_delivery_boundaries_test.go+++ b/server/internal/integrations/telegram/outbound_delivery_boundaries_test.go@@ -202,7 +202,7 @@ func TestReview8545PostgresRetryDoesNotAdoptUnrelatedTurn(t *testing.T) {o, _, c, e := review8545Setup(t, bot)o.handleTaskMessage(telegramPartialEvent(e.TaskID, "first request"))o.handleTaskFailed(events.Event{TaskID: e.TaskID, Payload: map[string]any{"retry_pending": true}})- c.advance(editInterval + time.Millisecond)+ c.advance(privateEditInterval + time.Millisecond)// Different ordinary task on the same binding; no retry relationship.otherID := util.UUIDToString(review8545ID())o.handleTaskMessage(telegramPartialEvent(otherID, "unrelated second request"))@@ -214,11 +214,11 @@ func TestReview8545PostgresOldAttemptCannotReopenAfterAdoption(t *testing.T) {o, _, c, e := review8545Setup(t, bot)o.handleTaskMessage(telegramPartialEvent(e.TaskID, "first attempt"))o.handleTaskFailed(events.Event{TaskID: e.TaskID, Payload: map[string]any{"retry_pending": true}})- c.advance(editInterval + time.Millisecond)+ c.advance(privateEditInterval + time.Millisecond)retryTask := util.UUIDToString(review8545ID())seedRetryChain(t, e.TaskID, retryTask)o.handleTaskMessage(telegramPartialEvent(retryTask, "retry attempt"))- c.advance(editInterval + time.Millisecond)+ c.advance(privateEditInterval + time.Millisecond)o.handleTaskMessage(telegramPartialEvent(e.TaskID, "late old attempt"))review8545MessageCount(t, bot, 1)}@@ -310,7 +310,7 @@ func TestReview8545PostgresStaleStreamCannotOverwriteSettledAnswer(t *testing.T)bot := &auditBot{}a, base, c, e := review8545Setup(t, bot)a.handleTaskMessage(telegramPartialEvent(e.TaskID, chatDoneContent(e.Payload)))- c.advance(editInterval + time.Millisecond)+ c.advance(privateEditInterval + time.Millisecond)q := &review8545PauseStreamRead{review8545Queries: base, entered: make(chan struct{}), release: make(chan struct{})}q.pause.Store(true)a.q = q@@ -398,9 +398,9 @@ func TestReview8545PostgresSupersededAttemptCannotRewriteReply(t *testing.T) {seedRetryChain(t, e.TaskID, retryTask)o.handleTaskMessage(telegramPartialEvent(e.TaskID, "first attempt"))- c.advance(editInterval + time.Millisecond)+ c.advance(privateEditInterval + time.Millisecond)o.handleTaskMessage(telegramPartialEvent(retryTask, "retry attempt"))- c.advance(editInterval + time.Millisecond)+ c.advance(privateEditInterval + time.Millisecond)o.handleTaskMessage(telegramPartialEvent(e.TaskID, " stale tail from the old attempt"))review8545MessageCount(t, bot, 1)@@ -428,7 +428,7 @@ func TestReview8545PostgresSettledElsewhereReleasesLocalState(t *testing.T) {if held != 1 {t.Fatalf("setup expected one local stream, found %d", held)}- c.advance(editInterval + time.Millisecond)+ c.advance(privateEditInterval + time.Millisecond)a.handleTaskMessage(telegramPartialEvent(e.TaskID, " late tail"))a.mu.Lock()diff --git a/server/internal/integrations/telegram/outbound_delivery_contract_test.go b/server/internal/integrations/telegram/outbound_delivery_contract_test.goindex 9e44aee26c..5c32fa39d4 100644--- a/server/internal/integrations/telegram/outbound_delivery_contract_test.go+++ b/server/internal/integrations/telegram/outbound_delivery_contract_test.go@@ -204,7 +204,7 @@ func TestAuditLatePartialAfterCompletion(t *testing.T) {e := telegramTestEvent()o.enqueueTerminalReply(e)auditDrain(t, o, c, e.ChatSessionID)- c.advance(editInterval + time.Millisecond)+ c.advance(privateEditInterval + time.Millisecond)o.handleTaskMessage(auditPartial(e))bot.wantOne(t)}@@ -281,7 +281,7 @@ func TestAuditLatePartialAfterCancellationOrEmptyCompletion(t *testing.T) {empty.Payload = protocol.ChatDonePayload{TaskID: e.TaskID, ChatSessionID: e.ChatSessionID}o.enqueueTerminalReply(empty)}- c.advance(editInterval + time.Millisecond)+ c.advance(privateEditInterval + time.Millisecond)o.handleTaskMessage(auditPartial(e))bot.wantOne(t)})@@ -319,7 +319,7 @@ func TestAuditPartialResolutionOverlapsCompletion(t *testing.T) {<-q.enteredo.enqueueTerminalReply(e)auditDrain(t, o, c, e.ChatSessionID)- c.advance(editInterval + time.Millisecond)+ c.advance(privateEditInterval + time.Millisecond)q.release <- struct{}{}<-finishedbot.wantOne(t)@@ -334,7 +334,7 @@ func TestAuditAutomaticRetryPreservesSingleReply(t *testing.T) {o.handleTaskMessage(auditPartial(first))o.handleTaskFailed(events.Event{TaskID: first.TaskID, Type: protocol.EventTaskFailed,Payload: map[string]any{"retry_pending": true}})- c.advance(editInterval + time.Millisecond)+ c.advance(privateEditInterval + time.Millisecond)retry := telegramTestEventFor(3, 5, chatDoneContent(first.Payload))_ = retryTasko.handleTaskMessage(auditPartial(retry))diff --git a/server/internal/integrations/telegram/outbound_progress.go b/server/internal/integrations/telegram/outbound_progress.gonew file mode 100644index 0000000000..f4147ff22f--- /dev/null+++ b/server/internal/integrations/telegram/outbound_progress.go@@ -0,0 +1,498 @@+package telegram++import (+ "context"+ "errors"+ "fmt"+ "html"+ "net/http"+ "regexp"+ "strconv"+ "strings"+ "time"++ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/integrations/wecom"+ "github.com/multica-ai/multica/server/internal/util"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// outbound_progress.go — what the agent is doing, shown while it does it.+//+// An agent writes a sentence and then works in tools for minutes, or starts+// with a tool call and writes nothing until the end. Streaming only its text+// leaves the chat showing one line, or nothing, for the whole run. So the tool+// calls go into the streamed reply as well: a short list of steps in a quote+// block under the text, edited in place as the run moves on, with a clock that+// keeps ticking between steps. When the agent writes again the list gives way+// to the text, and the final answer replaces the whole message.+//+// What a tool call is and which of its arguments may be shown is the WeCom+// adapter's vocabulary (wecom/progress_export.go): one tool table and one+// redactor for both channels.++// ProgressMode is how much of a run's tool calls a chat is shown.+type ProgressMode string++const (+ // ProgressAuto shows a private chat each step with its argument, and a+ // group the kind of work only: a group is read by people the run does not+ // belong to.+ ProgressAuto ProgressMode = "auto"+ // ProgressOff streams the agent's text and nothing else.+ ProgressOff ProgressMode = "off"+ // ProgressSummary shows the kind of work everywhere.+ ProgressSummary ProgressMode = "summary"+ // ProgressDetail shows each step with its argument everywhere.+ ProgressDetail ProgressMode = "detail"+)++// ParseProgressMode reads a configured mode. Empty is the default; an unknown+// value is the default too, and reported as such.+func ParseProgressMode(raw string) (ProgressMode, bool) {+ switch mode := ProgressMode(strings.ToLower(strings.TrimSpace(raw))); mode {+ case "":+ return ProgressAuto, true+ case ProgressAuto, ProgressOff, ProgressSummary, ProgressDetail:+ return mode, true+ }+ return ProgressAuto, false+}++// SetProgressMode chooses how much of a run's tool calls chats are shown. Call+// it before Register.+func (o *Outbound) SetProgressMode(mode ProgressMode) { o.progress = mode }++const (+ // maxStepLines is how many steps stay on screen. The list is where the run+ // is now, not its history.+ maxStepLines = 6+ // maxStepRunes keeps a step on one or two lines of a phone.+ maxStepRunes = 96+)++var stepIcons = map[wecom.StepKind]string{+ wecom.StepStarting: "⏳",+ wecom.StepRead: "📖",+ wecom.StepEdit: "✏️",+ wecom.StepCommand: "💻",+ wecom.StepSearch: "🔎",+ wecom.StepWeb: "🌐",+ wecom.StepSubtask: "🤖",+ wecom.StepPlan: "📝",+ wecom.StepService: "🔌",+ wecom.StepSkill: "🧩",+ wecom.StepTool: "🛠",+ wecom.StepError: "⚠️",+}++// stepLine is one line of the list.+type stepLine struct {+ icon string+ text string+ // count is how many times in a row the step was taken.+ count int+ // transient marks a line that stands in until the first real step.+ transient bool+}++// stepFeed is the list under the text: the newest steps, and how many the run+// has taken in all.+type stepFeed struct {+ lines []stepLine+ total int+}++func (f *stepFeed) add(line stepLine) {+ if n := len(f.lines); n > 0 && f.lines[n-1].transient {+ f.lines = f.lines[:n-1]+ }+ if !line.transient {+ f.total+++ }+ if n := len(f.lines); n > 0 && f.lines[n-1].icon == line.icon && f.lines[n-1].text == line.text {+ // An agent polling a build repeats one call many times over. One line+ // that counts says so; six identical lines push everything else out.+ f.lines[n-1].count+++ return+ }+ line.count = 1+ f.lines = append(f.lines, line)+ if len(f.lines) > maxStepLines {+ f.lines = append(f.lines[:0], f.lines[len(f.lines)-maxStepLines:]...)+ }+}++// render is the quote block, or nothing when no step is showing. elapsed is+// how long the run has taken; it goes on the last line once there is a second+// to show, so the block changes while a step runs.+func (f *stepFeed) render(elapsed time.Duration) string {+ if len(f.lines) == 0 {+ return ""+ }+ var b strings.Builder+ b.WriteString("<blockquote>")+ for i, line := range f.lines {+ if i > 0 {+ b.WriteString("\n")+ }+ b.WriteString(line.icon)+ b.WriteString(" ")+ b.WriteString(html.EscapeString(line.text))+ if line.count > 1 {+ b.WriteString(" ×")+ b.WriteString(strconv.Itoa(line.count))+ }+ }+ if elapsed >= time.Second {+ b.WriteString("\n⏱ ")+ b.WriteString(wecom.FormatElapsed(elapsed))+ switch {+ case f.total == 1:+ b.WriteString(" · 1 step")+ case f.total > 1:+ b.WriteString(" · ")+ b.WriteString(strconv.Itoa(f.total))+ b.WriteString(" steps")+ }+ }+ b.WriteString("</blockquote>")+ return b.String()+}++// streamFrame is one thing a run adds to its reply: text, a step, or neither —+// the deferred push, which only sends what is already kept.+type streamFrame struct {+ text string+ step *stepLine+}++func (f streamFrame) empty() bool { return f.text == "" && f.step == nil }++// absorb keeps a frame in the stream. Caller holds Outbound.mu.+func (st *streamState) absorb(frame streamFrame, now time.Time) {+ if frame.empty() {+ return+ }+ st.lastFrameAt = now+ if frame.text != "" {+ if len(st.steps.lines) > 0 {+ // The agent is writing again: what it was doing is over. Text on+ // either side of a tool call is two separate remarks, which the+ // agent sends without anything between them.+ st.steps.lines = nil+ if st.accumulated != "" && !strings.HasSuffix(st.accumulated, "\n") && !strings.HasPrefix(frame.text, "\n") {+ st.accumulated += "\n\n"+ }+ }+ st.accumulated += frame.text+ }+ if frame.step != nil {+ st.steps.add(*frame.step)+ }+}++// render is the message body for what the stream holds now: the text, then the+// steps. Empty when there is neither. Caller holds Outbound.mu.+func (st *streamState) render(now time.Time) string {+ block := st.steps.render(now.Sub(st.startedAt))+ budget := maxMessageUnits+ if block != "" {+ budget -= utf16Units(block) + 2+ }+ text := st.accumulated+ if utf16Units(text) > budget {+ // Mid-stream overflow: freeze the streamed message at the cap; the full+ // reply is delivered in chunks by the final EventChatDone send.+ text = chunkMessage(text, budget)[0]+ }+ body := formatHTML(text)+ switch {+ case block == "":+ return body+ case body == "":+ return block+ }+ return body + "\n\n" + block+}++// stepFor words a tool call or an error as a line of the list, for the chat it+// is going to.+func (o *Outbound) stepFor(target *replyTarget, payload protocol.TaskMessagePayload) (stepLine, bool) {+ detail := o.progress == ProgressDetail || (o.progress == ProgressAuto && target.private)+ if detail {+ payload.Input = unwrapShellCommand(payload.Input)+ }+ step, ok := wecom.DescribeStep(payload, wecom.LocaleEn, detail)+ if !ok {+ return stepLine{}, false+ }+ return stepLine{icon: stepIcons[step.Kind], text: clipMiddle(step.Text, maxStepRunes)}, true+}++// shellWrapper matches a command handed to a shell to run: `bash -lc "…"`,+// `/bin/zsh -c '…'`.+var shellWrapper = regexp.MustCompile(`(?s)^\s*(?:\S*/)?(?:ba|z|da|k)?sh\s+-[a-z]*c\s+(.+?)\s*$`)++// unwrapShellCommand returns the input with the wrapper shell taken off its+// command. Half of all commands arrive as `/bin/bash -lc "git status"`, and+// the wrapper is the same every time: shown as it is, it fills the line and+// pushes the part that says what is running off the end. The input is copied;+// other subscribers read the same map.+func unwrapShellCommand(input map[string]any) map[string]any {+ for _, key := range []string{"command", "cmd"} {+ var inner string+ switch v := input[key].(type) {+ case string:+ inner = scriptHead(unwrapShell(v))+ if inner == v {+ return input+ }+ case []any:+ // The argv form: ["bash", "-lc", "git status"].+ parts := make([]string, 0, len(v))+ for _, part := range v {+ s, ok := part.(string)+ if !ok {+ return input+ }+ parts = append(parts, s)+ }+ if len(parts) == 0 {+ return input+ }+ inner = strings.Join(parts, " ")+ if len(parts) == 3 && shellWrapper.MatchString(parts[0]+" "+parts[1]+" x") {+ inner = parts[2]+ }+ inner = scriptHead(inner)+ default:+ continue+ }+ out := make(map[string]any, len(input))+ for k, v := range input {+ out[k] = v+ }+ out[key] = inner+ return out+ }+ return input+}++func unwrapShell(command string) string {+ m := shellWrapper.FindStringSubmatch(command)+ if m == nil {+ return command+ }+ inner := m[1]+ if len(inner) < 2 {+ return inner+ }+ switch quote := inner[0]; {+ case quote == '"' && inner[len(inner)-1] == '"':+ inner = inner[1 : len(inner)-1]+ inner = shellEscapes.Replace(inner)+ case quote == '\'' && inner[len(inner)-1] == '\'':+ inner = strings.ReplaceAll(inner[1:len(inner)-1], `'\''`, `'`)+ }+ return inner+}++// scriptHead reduces a script to its first line. An agent often sends several+// commands, or a patch in a here-document, as one command: the first line says+// where it starts, and the rest would put file contents into the chat.+func scriptHead(command string) string {+ lines := strings.Split(strings.TrimSpace(command), "\n")+ head := strings.TrimSpace(lines[0])+ if len(lines) == 1 {+ return head+ }+ return head + " …"+}++// shellEscapes are the characters a backslash protects inside double quotes.+var shellEscapes = strings.NewReplacer(`\"`, `"`, `\\`, `\`, `\$`, `$`, "\\`", "`")++// clipMiddle shortens a line by cutting its middle. A command's start says+// what it is and its end says what it is aimed at; the middle is flags.+func clipMiddle(s string, limit int) string {+ runes := []rune(s)+ if len(runes) <= limit {+ return s+ }+ head := limit * 2 / 3+ tail := limit - head - 1+ return strings.TrimRight(string(runes[:head]), " ") + "…" + strings.TrimLeft(string(runes[len(runes)-tail:]), " ")+}++// heartbeatInterval is how long to wait before moving the clock under a list+// of steps, given how long the run has been quiet. A private chat takes an+// edit a second and a group twenty a minute, so the clock moves often at first+// and slows for a step that turns out to be long; a run quiet for hours is+// left alone, since the final answer does not need the clock to arrive.+func heartbeatInterval(chatID int64, quiet time.Duration) time.Duration {+ switch {+ case quiet >= 3*time.Hour:+ return 0+ case quiet >= 10*time.Minute:+ return time.Minute+ case chatID < 0:+ if quiet >= 2*time.Minute {+ return 20 * time.Second+ }+ return 10 * time.Second+ case quiet >= 2*time.Minute:+ return 10 * time.Second+ }+ return 3 * time.Second+}++// handleTaskProgress opens the reply the moment the agent is launched. The+// first frame of a run can be many seconds away — the CLI starting, the model+// thinking — and until then the chat would show nothing at all.+func (o *Outbound) handleTaskProgress(e events.Event) {+ payload, ok := e.Payload.(protocol.TaskProgressPayload)+ if !ok || payload.Step != 1 {+ // The daemon's other milestone is the run finishing, and the answer is+ // already on its way then.+ return+ }+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cancel()+ target, turn, ok := o.streamTarget(ctx, e)+ if !ok {+ return+ }+ starting := wecom.StartingStep(wecom.LocaleEn)+ o.advanceStream(ctx, target, turn, streamFrame{step: &stepLine{+ icon: stepIcons[starting.Kind], text: starting.Text, transient: true,+ }})+}++// streamRemnant is what a stream left in the chat when its run ended without+// an answer to replace it.+type streamRemnant struct {+ chatID int64+ messageID int64+ installationID pgtype.UUID+ // body is the message without its steps; empty when steps were all it had.+ body string+}++// takeStream ends the task's stream and reports what has to be tidied in the+// chat: a list of steps that no answer is going to replace would say "running"+// for good.+func (o *Outbound) takeStream(e events.Event) *streamRemnant {+ taskID, ok := eventTaskID(e)+ if !ok {+ return nil+ }+ key := util.UUIDToString(taskID)+ var remnant *streamRemnant+ o.mu.Lock()+ if st := o.streams[key]; st != nil {+ // A request already on its way to Telegram finds this when it lands.+ st.ended = true+ remnant = o.remnantLocked(st)+ }+ o.mu.Unlock()+ o.clearStreamKey(key)+ return remnant+}++// remnantLocked keeps the accumulated prose without steps, including text+// waiting for its edit slot. The caller holds o.mu.+func (o *Outbound) remnantLocked(st *streamState) *streamRemnant {+ if st.messageID == 0 || st.target == nil {+ return nil+ }+ st.steps.lines = nil+ return &streamRemnant{+ chatID: st.chatID, messageID: st.messageID, installationID: st.target.installationID,+ body: st.render(o.now()),+ }+}++// recoverStreamRemnant uses the shared delivery and persisted transcript when+// the closing replica never saw the stream. The settled reason/depth check also+// prevents a late cancellation from replacing a final answer or a newer retry.+func (o *Outbound) recoverStreamRemnant(ctx context.Context, target *replyTarget, turn replyTurn, reason string, local *streamRemnant) (*streamRemnant, error) {+ row, err := o.q.GetChannelReplyDelivery(ctx, turn.id)+ if err != nil {+ return nil, fmt.Errorf("load telegram reply for cleanup: %w", err)+ }+ messageID := (&deliveryLease{row: row}).messageID()+ if row.Phase != deliveryPhaseSettled || row.SettledReason != reason ||+ turn.depth < row.AttemptDepth || row.ChunksSent != 0 || messageID == 0 {+ return nil, nil+ }+ fragments, err := o.q.ListTaskReplyFragments(ctx, row.TaskID)+ if err != nil {+ return nil, fmt.Errorf("load telegram reply text for cleanup: %w", err)+ }+ if len(fragments) == 0 && local != nil && local.messageID == messageID {+ return local, nil+ }+ var text streamState+ for _, fragment := range fragments {+ if fragment.Type == "text" {+ text.absorb(streamFrame{text: fragment.Content}, o.now())+ } else if o.progress != ProgressOff {+ text.absorb(streamFrame{step: &stepLine{}}, o.now())+ }+ }+ text.steps.lines = nil+ return &streamRemnant{+ chatID: target.chatID, messageID: messageID, installationID: target.installationID,+ body: text.render(o.now()),+ }, nil+}++// tidyRemnant takes the steps off a message whose run is over: the text stays+// as the agent left it, and a message that was only steps is removed. The turn+// is closed by now, so nothing else writes to the message.+func (o *Outbound) tidyRemnant(ctx context.Context, remnant *streamRemnant) {+ if remnant == nil {+ return+ }+ call := func() error {+ ctx, cancel := o.callContext(ctx)+ defer cancel()+ token, err := o.activeBotToken(ctx, remnant.installationID)+ if err != nil || token == "" {+ return err+ }+ api := newBotAPI(o.apiBase, token, o.client)+ if remnant.body == "" {+ return api.DeleteMessage(ctx, remnant.chatID, remnant.messageID)+ }+ return api.EditMessageText(ctx, editMessageTextParams{+ ChatID: remnant.chatID, MessageID: remnant.messageID, Text: remnant.body, ParseMode: "HTML",+ })+ }+ err := call()+ if retry, ok := retryAfter(err); ok && retry <= remnantRetryLimit {+ if o.wait(ctx, retry) != nil {+ return+ }+ err = call()+ }+ if err != nil && !isNotModified(err) && !isMessageGone(err) {+ o.logger.WarnContext(ctx, "telegram outbound: could not take the steps off a finished reply", "error", err)+ }+}++// remnantRetryLimit is the longest retry_after worth waiting out to tidy a+// message; past it the steps stay, which is untidy and nothing worse.+const remnantRetryLimit = 5 * time.Second++// isMessageGone reports that the message to tidy is not there any more — the+// user deleted it, which leaves nothing to tidy.+func isMessageGone(err error) bool {+ var ae *apiError+ return errors.As(err, &ae) && ae.Code == http.StatusBadRequest &&+ (containsFold(ae.Description, "message to edit not found") ||+ containsFold(ae.Description, "message to delete not found"))+}diff --git a/server/internal/integrations/telegram/outbound_progress_recovery_test.go b/server/internal/integrations/telegram/outbound_progress_recovery_test.gonew file mode 100644index 0000000000..f019dc49e9--- /dev/null+++ b/server/internal/integrations/telegram/outbound_progress_recovery_test.go@@ -0,0 +1,176 @@+package telegram++import (+ "context"+ "errors"+ "fmt"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/integrations/channel"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func TestOutboundRemoteCancellationTidiesProgress(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P)+ h.launch()+ h.last(1)+ other := review8545Second(h.o)+ e := events.Event{TaskID: h.taskID, ChatSessionID: telegramTestEvent().ChatSessionID, Type: protocol.EventTaskCancelled}+ reply := &terminalReply{event: e, kind: terminalKindClose, settleReason: "cancelled", remnant: other.takeStream(e)}+ result := other.initializeTerminalReply(context.Background(), reply)+ if !result.done || result.err != nil {+ t.Fatalf("cancel did not settle: %+v", result)+ }+ if got := h.last(2); got.method != "deleteMessage" {+ t.Fatalf("cancelled turn left progress in Telegram: %+v", h.sent())+ }+}++func seedReplyFragments(t *testing.T, h *progressHarness) {+ t.Helper()+ fx := testutil.New(testPool, "", "")+ unique := time.Now().UnixNano()+ fx.UserID = fx.User(t, "telegram-progress", fmt.Sprintf("progress-%[email protected]", unique))+ fx.WorkspaceID = fx.Workspace(t, "telegram-progress", fmt.Sprintf("progress-%d", unique))+ agent := fx.Agent(t, "telegram-progress", "")+ fx.Task(t, agent, testutil.Cols{"id": h.taskID, "status": "completed", "completed_at": testutil.Raw("now()")})+ for i, fragment := range []struct{ kind, content string }{+ {"text", "我"}, {"text", "会检查这些文件。"},+ {"tool_use", "PRIVATE_TOOL_INPUT"}, {"tool_result", "PRIVATE_TOOL_OUTPUT"},+ {"thinking", "PRIVATE_REASONING"}, {"error", "PRIVATE_ERROR"},+ {"text", "检查完成。"}, {"tool_use", "PRIVATE_TOOL_INPUT"},+ } {+ fx.Insert(t, "task_message", testutil.Cols{+ "task_id": h.taskID, "seq": i + 1, "type": fragment.kind, "content": fragment.content,+ })+ }+}++func TestOutboundRemoteClosePreservesPersistedProse(t *testing.T) {+ for _, reason := range []string{"cancelled", "empty_reply"} {+ t.Run(reason, func(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P)+ seedReplyFragments(t, h)+ h.text("我会检查这些文件。")+ h.tool("Read", map[string]any{"file_path": "private.txt"})+ h.text("检查完成。")+ h.tool("Bash", map[string]any{"command": "true"})+ other := review8545Second(h.o)+ e := telegramTestEvent()+ reply := &terminalReply{event: e, kind: terminalKindClose, settleReason: reason}+ result := other.initializeTerminalReply(context.Background(), reply)+ if !result.done || result.err != nil {+ t.Fatalf("close did not settle: %+v", result)+ }+ got := h.last(5)+ if got.method != "editMessageText" || got.text != "我会检查这些文件。\n\n检查完成。" {+ t.Fatalf("cleanup = %+v", got)+ }+ })+ }+}++func TestOutboundRemoteEmptyReplyDeletesStepsOnlyMessage(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P)+ h.launch()+ other := review8545Second(h.o)+ reply := &terminalReply{event: telegramTestEvent(), kind: terminalKindClose, settleReason: "empty_reply"}+ result := other.initializeTerminalReply(context.Background(), reply)+ if !result.done || result.err != nil {+ t.Fatalf("empty completion did not settle: %+v", result)+ }+ if got := h.last(2); got.method != "deleteMessage" {+ t.Fatalf("cleanup = %+v", got)+ }+}++func TestOutboundCloseUsesProseReportedToOtherReplicas(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P)+ seedReplyFragments(t, h)+ h.text("我")+ h.tool("Read", map[string]any{"file_path": "private.txt"})+ e := telegramTestEvent()+ reply := &terminalReply{event: e, kind: terminalKindClose, settleReason: "cancelled", remnant: h.o.takeStream(e)}+ result := h.o.initializeTerminalReply(context.Background(), reply)+ if !result.done || result.err != nil {+ t.Fatalf("cancel did not settle: %+v", result)+ }+ if got := h.last(3); got.text != "我会检查这些文件。\n\n检查完成。" {+ t.Fatalf("cleanup lost text reported to another replica: %+v", got)+ }+}++func TestOutboundLateCancellationDoesNotReplaceFinalAnswer(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P)+ h.launch()+ other := review8545Second(h.o)+ e := telegramTestEvent()+ if err := sendTerminalReplySynchronouslyForTest(context.Background(), other, e); err != nil {+ t.Fatal(err)+ }+ reply := &terminalReply{event: e, kind: terminalKindClose, settleReason: "cancelled", remnant: h.o.takeStream(e)}+ result := h.o.initializeTerminalReply(context.Background(), reply)+ if !result.done || result.err != nil {+ t.Fatalf("late cancel did not settle: %+v", result)+ }+ if got := h.sent(); len(got) != 2 || got[1].text != chatDoneContent(e.Payload) {+ t.Fatalf("late cancellation changed the answer: %+v", got)+ }+}++func TestOutboundLateCancellationDoesNotReplaceNewerAttempt(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P)+ h.launch()+ retryID := "00000000-0000-0000-0000-000000000005"+ seedRetryChain(t, h.taskID, retryID)+ other := review8545Second(h.o)+ other.handleTaskMessage(telegramPartialEvent(retryID, "Newer attempt."))+ e := telegramTestEvent()+ reply := &terminalReply{event: e, kind: terminalKindClose, settleReason: "cancelled", remnant: h.o.takeStream(e)}+ result := h.o.initializeTerminalReply(context.Background(), reply)+ if !result.done || result.err != nil {+ t.Fatalf("late cancel did not settle: %+v", result)+ }+ if got := h.sent(); len(got) != 2 || got[1].text != "Newer attempt." {+ t.Fatalf("late cancellation changed the retry: %+v", got)+ }+}++type retryReplyFragments struct {+ outboundQueries+ failed bool+}++func (q *retryReplyFragments) ListTaskReplyFragments(ctx context.Context, taskID pgtype.UUID) ([]db.ListTaskReplyFragmentsRow, error) {+ if !q.failed {+ q.failed = true+ return nil, errors.New("transient transcript read failure")+ }+ return q.outboundQueries.ListTaskReplyFragments(ctx, taskID)+}++func TestOutboundRemoteCleanupCanRetryAfterTurnIsClosed(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P)+ seedReplyFragments(t, h)+ h.launch()+ other := review8545Second(h.o)+ other.q = &retryReplyFragments{outboundQueries: other.q}+ reply := &terminalReply{event: telegramTestEvent(), kind: terminalKindClose, settleReason: "cancelled"}+ first := other.initializeTerminalReply(context.Background(), reply)+ if first.done || first.retryAt.IsZero() {+ t.Fatalf("transient read was not retried: %+v", first)+ }+ second := other.initializeTerminalReply(context.Background(), reply)+ if !second.done || second.err != nil {+ t.Fatalf("cleanup retry failed: %+v", second)+ }+ if got := h.last(2); got.text != "我会检查这些文件。\n\n检查完成。" {+ t.Fatalf("cleanup = %+v", got)+ }+}diff --git a/server/internal/integrations/telegram/outbound_progress_test.go b/server/internal/integrations/telegram/outbound_progress_test.gonew file mode 100644index 0000000000..6fa8b0fc74--- /dev/null+++ b/server/internal/integrations/telegram/outbound_progress_test.go@@ -0,0 +1,498 @@+package telegram++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "regexp"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/integrations/channel"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// progressHarness is an Outbound wired to a Bot API that records every call.+type progressHarness struct {+ t *testing.T+ o *Outbound+ taskID string+ // skew moves the Outbound's clock ahead of the wall clock, so a test can+ // let a minute of a run pass without waiting for it.+ skew atomic.Int64++ mu sync.Mutex+ requests []progressRequest+ // hold, when set, keeps every sendMessage unanswered until it is closed.+ hold chan struct{}+}++type progressRequest struct {+ method string+ text string+}++// newProgressHarness starts an Outbound for one chat. The clock under the+// steps stands still unless configure gives it a cadence, so a slow test run+// does not pick up edits of its own.+func newProgressHarness(t *testing.T, chatType channel.ChatType, configure ...func(*Outbound)) *progressHarness {+ t.Helper()+ h := &progressHarness{t: t, taskID: telegramTestEvent().TaskID}+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ text, _ := body["text"].(string)+ h.mu.Lock()+ h.requests = append(h.requests, progressRequest{+ method: r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:], text: text,+ })+ hold := h.hold+ h.mu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ if strings.HasSuffix(r.URL.Path, "/sendMessage") {+ if hold != nil {+ <-hold+ }+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":99,"chat":{"id":42,"type":"private"},"date":0,"text":"x"}}`))+ return+ }+ _, _ = w.Write([]byte(`{"ok":true,"result":true}`))+ }))+ t.Cleanup(api.Close)++ q := newTelegramOutboundQueries(t)+ q.channelOrigin = true+ q.binding.ChatType = string(chatType)+ h.o = NewOutbound(q, nil, api.URL, api.Client(), nil)+ h.o.now = func() time.Time { return time.Now().Add(time.Duration(h.skew.Load())) }+ h.o.heartbeat = func(int64, time.Duration) time.Duration { return 0 }+ for _, fn := range configure {+ fn(h.o)+ }+ ctx, cancel := context.WithCancel(context.Background())+ h.o.Start(ctx)+ t.Cleanup(func() {+ cancel()+ if !h.o.WaitWithTimeout(time.Second) {+ t.Error("outbound workers did not stop")+ }+ })+ return h+}++func (h *progressHarness) sent() []progressRequest {+ h.mu.Lock()+ defer h.mu.Unlock()+ return append([]progressRequest(nil), h.requests...)+}++// last returns the newest request once there are n of them.+func (h *progressHarness) last(n int) progressRequest {+ h.t.Helper()+ deadline := time.Now().Add(3 * time.Second)+ for len(h.sent()) < n && time.Now().Before(deadline) {+ time.Sleep(10 * time.Millisecond)+ }+ got := h.sent()+ if len(got) != n {+ h.t.Fatalf("requests = %+v, want %d", got, n)+ }+ return got[n-1]+}++// openEditSlot ends the chat's edit interval, so the next frame goes out at+// once instead of waiting for it.+func (h *progressHarness) openEditSlot() {+ h.o.mu.Lock()+ st := h.o.streams[h.taskID]+ h.o.mu.Unlock()+ if st == nil {+ return+ }+ st.schedule.mu.Lock()+ st.schedule.lastEdit = time.Now().Add(-time.Hour)+ st.schedule.mu.Unlock()+}++func (h *progressHarness) text(content string) {+ h.openEditSlot()+ h.o.handleTaskMessage(events.Event{+ TaskID: h.taskID, Type: protocol.EventTaskMessage,+ Payload: protocol.TaskMessagePayload{TaskID: h.taskID, Type: "text", Content: content},+ })+}++func (h *progressHarness) tool(tool string, input map[string]any) {+ h.openEditSlot()+ h.o.handleTaskMessage(toolFrame(h.taskID, tool, input))+}++func (h *progressHarness) launch() {+ h.o.handleTaskProgress(events.Event{+ TaskID: h.taskID, Type: protocol.EventTaskProgress,+ Payload: protocol.TaskProgressPayload{TaskID: h.taskID, Summary: "Launching codex", Step: 1, Total: 2},+ })+}++func toolFrame(taskID, tool string, input map[string]any) events.Event {+ return events.Event{+ TaskID: taskID, Type: protocol.EventTaskMessage,+ Payload: protocol.TaskMessagePayload{TaskID: taskID, Type: "tool_use", Tool: tool, Input: input},+ }+}++func toolCall(tool string, input map[string]any) protocol.TaskMessagePayload {+ return protocol.TaskMessagePayload{Type: "tool_use", Tool: tool, Input: input}+}++var clockLine = regexp.MustCompile(`\n⏱ [^<\n]*`)++// clockless drops the clock from a body. It appears once a run is a second+// old, which a loaded machine reaches in the middle of a test.+func clockless(text string) string { return clockLine.ReplaceAllString(text, "") }++// An agent that says one sentence and then works in tools for minutes left the+// chat showing that sentence and nothing else. The steps go under it, in the+// same message, and give way when the agent speaks again.+func TestOutboundShowsToolStepsUnderTheStreamedText(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P)++ h.text("I will check the repositories.")+ if got := h.last(1); got.method != "sendMessage" || got.text != "I will check the repositories." {+ t.Fatalf("opening frame = %+v", got)+ }++ // The wrapper shell the command arrives in is not part of the step.+ h.tool("exec_command", map[string]any{"command": `/bin/bash -lc "git status --short"`})+ want := "I will check the repositories.\n\n<blockquote>💻 Running git status --short</blockquote>"+ if got := h.last(2); got.method != "editMessageText" || clockless(got.text) != want {+ t.Fatalf("first step = %+v\nwant text %q", got, want)+ }++ // The same call again is the same line, counted.+ h.tool("exec_command", map[string]any{"command": `/bin/bash -lc "git status --short"`})+ h.tool("Read", map[string]any{"file_path": "server/main.go"})+ want = "I will check the repositories.\n\n<blockquote>💻 Running git status --short ×2\n📖 Reading server/main.go</blockquote>"+ if got := h.last(4); clockless(got.text) != want {+ t.Fatalf("later steps = %q\nwant %q", got.text, want)+ }++ // A tool's output is not a step and costs no edit.+ h.openEditSlot()+ h.o.handleTaskMessage(events.Event{+ TaskID: h.taskID, Type: protocol.EventTaskMessage,+ Payload: protocol.TaskMessagePayload{TaskID: h.taskID, Type: "tool_result", Tool: "Read", Output: "package main"},+ })++ // The agent is writing again: what it was doing is over, and what it says+ // now is a new paragraph.+ h.text("Everything is clean.")+ if got := h.last(5); got.text != "I will check the repositories.\n\nEverything is clean." {+ t.Fatalf("text after the steps = %q", got.text)+ }+}++// Many agents start with a tool call and write nothing until the end. The+// first step opens the reply, so the chat is not empty for the whole run.+func TestOutboundOpensTheReplyOnTheFirstToolStep(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P)++ h.tool("Grep", map[string]any{"pattern": "TODO <fix>"})+ got := h.last(1)+ // The fragment's markup characters were already replaced on the way in.+ if got.method != "sendMessage" || clockless(got.text) != "<blockquote>🔎 Searching for TODO fix</blockquote>" {+ t.Fatalf("opening step = %+v", got)+ }+}++// The agent's CLI takes seconds to start and the model more to answer. The+// reply opens when the run is launched, and the first real step takes the+// stand-in's place.+func TestOutboundOpensTheReplyWhenTheAgentIsLaunched(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P)++ h.launch()+ if got := h.last(1); got.method != "sendMessage" || clockless(got.text) != "<blockquote>⏳ Starting the agent</blockquote>" {+ t.Fatalf("launch = %+v", got)+ }++ // The daemon's other milestone is the run finishing: nothing to show.+ h.o.handleTaskProgress(events.Event{+ TaskID: h.taskID, Type: protocol.EventTaskProgress,+ Payload: protocol.TaskProgressPayload{TaskID: h.taskID, Summary: "Finishing task", Step: 2, Total: 2},+ })++ h.tool("Read", map[string]any{"file_path": "go.mod"})+ if got := h.last(2); clockless(got.text) != "<blockquote>📖 Reading go.mod</blockquote>" {+ t.Fatalf("first step after launch = %q", got.text)+ }++ h.text("Go 1.26.")+ if got := h.last(3); got.text != "Go 1.26." {+ t.Fatalf("text after launch = %q", got.text)+ }+}++// A group is read by people the run does not belong to. They see what kind of+// work is going on, and none of the paths, commands or search terms.+func TestOutboundKeepsStepArgumentsOutOfGroups(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeGroup)++ h.tool("exec_command", map[string]any{"command": "cat /srv/acme/.env"})+ h.tool("exec_command", map[string]any{"command": "ls /srv/acme"})+ got := h.last(2)+ if clockless(got.text) != "<blockquote>💻 Running a command ×2</blockquote>" {+ t.Fatalf("group steps = %q", got.text)+ }+}++// Steps that arrive while an edit is already waiting for its slot ride along+// with it: one edit carries all of them.+func TestOutboundCarriesABurstOfStepsInOneEdit(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P)++ h.text("Looking.")+ h.last(1)++ // Leave 150ms of the edit interval and send the burst inside it.+ st := func() *streamState {+ h.o.mu.Lock()+ defer h.o.mu.Unlock()+ return h.o.streams[h.taskID]+ }()+ st.schedule.mu.Lock()+ st.schedule.lastEdit = time.Now().Add(150*time.Millisecond - privateEditInterval)+ st.schedule.mu.Unlock()+ for _, file := range []string{"a.go", "b.go", "c.go"} {+ h.o.handleTaskMessage(toolFrame(h.taskID, "Read", map[string]any{"file_path": file}))+ }+ if got := h.sent(); len(got) != 1 {+ t.Fatalf("steps inside the edit interval sent %d requests, want them held back", len(got)-1)+ }++ want := "Looking.\n\n<blockquote>📖 Reading a.go\n📖 Reading b.go\n📖 Reading c.go</blockquote>"+ if got := h.last(2); clockless(got.text) != want {+ t.Fatalf("burst = %q\nwant %q", got.text, want)+ }+ time.Sleep(300 * time.Millisecond)+ if got := h.sent(); len(got) != 2 {+ t.Fatalf("requests after the burst = %d, want 2", len(got))+ }+}++// A build can run for minutes without a frame. The clock under the steps keeps+// moving meanwhile, or the message looks exactly like a run that hung.+func TestOutboundKeepsTheClockMovingDuringALongStep(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P, func(o *Outbound) {+ o.heartbeat = func(int64, time.Duration) time.Duration { return 40 * time.Millisecond }+ })++ h.tool("exec_command", map[string]any{"command": "make test"})+ if got := h.last(1); clockless(got.text) != "<blockquote>💻 Running make test</blockquote>" {+ t.Fatalf("opening step = %+v", got)+ }++ // 75 seconds pass with nothing from the agent.+ h.skew.Add(int64(75 * time.Second))+ want := "<blockquote>💻 Running make test\n⏱ 1m 15s · 1 step</blockquote>"+ if got := h.last(2); got.method != "editMessageText" || got.text != want {+ t.Fatalf("clock = %+v\nwant text %q", got, want)+ }++ // The clock has not moved since: nothing new to show, so nothing is sent.+ time.Sleep(200 * time.Millisecond)+ if got := h.sent(); len(got) != 2 {+ t.Fatalf("requests with the clock standing still = %+v, want 2", got)+ }+}++// With the switch off the reply is the agent's text and nothing else.+func TestOutboundShowsNoStepsWhenProgressIsOff(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P, func(o *Outbound) { o.SetProgressMode(ProgressOff) })++ h.tool("exec_command", map[string]any{"command": "make test"})+ h.text("Done.")+ if got := h.last(1); got.method != "sendMessage" || got.text != "Done." {+ t.Fatalf("reply = %+v", got)+ }+}++// A cancelled run has no answer to take the steps' place. The text stays as+// the agent left it and the steps go; they would say "running" for good.+func TestOutboundTakesTheStepsOffACancelledReply(t *testing.T) {+ cancelled := func(h *progressHarness) {+ h.o.handleTaskCancelled(events.Event{+ TaskID: h.taskID, ChatSessionID: telegramTestEvent().ChatSessionID, Type: protocol.EventTaskCancelled,+ })+ }++ t.Run("text stays", func(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P)+ h.text("Checking the build.")+ h.tool("exec_command", map[string]any{"command": "make test"})+ h.last(2)+ cancelled(h)+ if got := h.last(3); got.method != "editMessageText" || got.text != "Checking the build." {+ t.Fatalf("after cancel = %+v", got)+ }+ })++ t.Run("a message of steps alone is removed", func(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P)+ h.tool("exec_command", map[string]any{"command": "make test"})+ h.last(1)+ cancelled(h)+ if got := h.last(2); got.method != "deleteMessage" {+ t.Fatalf("after cancel = %+v", got)+ }+ })++ // Text that is waiting for the chat's next edit has already taken the+ // steps' place in memory, but the chat still shows them.+ t.Run("steps go when text was waiting to replace them", func(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P)+ h.text("Checking the build.")+ h.tool("exec_command", map[string]any{"command": "make test"})+ h.last(2)+ // Inside the edit interval: kept, not sent.+ h.o.handleTaskMessage(events.Event{+ TaskID: h.taskID, Type: protocol.EventTaskMessage,+ Payload: protocol.TaskMessagePayload{TaskID: h.taskID, Type: "text", Content: "It fails."},+ })+ cancelled(h)+ if got := h.last(3); got.method != "editMessageText" || got.text != "Checking the build.\n\nIt fails." {+ t.Fatalf("after cancel = %+v", got)+ }+ })++ // The cancel can arrive while the message that opens the reply is still+ // on its way to Telegram. Nothing would ever edit it again.+ t.Run("a message still on its way is removed when it lands", func(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P)+ hold := make(chan struct{})+ h.mu.Lock()+ h.hold = hold+ h.mu.Unlock()+ sent := make(chan struct{})+ go func() {+ defer close(sent)+ h.launch()+ }()+ h.last(1)+ cancelled(h)+ close(hold)+ <-sent+ if got := h.last(2); got.method != "deleteMessage" {+ t.Fatalf("after cancel = %+v", got)+ }+ })+}++// Who sees a step's argument is the mode's decision and the chat's.+func TestStepForShowsArgumentsByModeAndChat(t *testing.T) {+ call := toolCall("Bash", map[string]any{"command": "cat notes.txt"})+ cases := []struct {+ mode ProgressMode+ private bool+ want string+ }{+ {ProgressAuto, true, "Running cat notes.txt"},+ {ProgressAuto, false, "Running a command"},+ {ProgressSummary, true, "Running a command"},+ {ProgressDetail, false, "Running cat notes.txt"},+ }+ for _, tc := range cases {+ o := &Outbound{progress: tc.mode}+ step, ok := o.stepFor(&replyTarget{private: tc.private}, call)+ if !ok || step.icon != "💻" || step.text != tc.want {+ t.Errorf("mode %s private %v: step = %+v, %v; want %q", tc.mode, tc.private, step, ok, tc.want)+ }+ }+}++// A long command keeps both ends: what it is, and what it is aimed at.+func TestStepForClipsALongCommandInTheMiddle(t *testing.T) {+ command := "go test -race -count=1 " + strings.Repeat("-tags=integration ", 5) + "./internal/integrations/telegram/..."+ o := &Outbound{progress: ProgressDetail}+ step, _ := o.stepFor(&replyTarget{}, toolCall("Bash", map[string]any{"command": command}))+ if n := len([]rune(step.text)); n > maxStepRunes {+ t.Fatalf("step is %d runes, want at most %d: %q", n, maxStepRunes, step.text)+ }+ if !strings.HasPrefix(step.text, "Running go test -race") || !strings.HasSuffix(step.text, "telegram/...") || !strings.Contains(step.text, "…") {+ t.Fatalf("step = %q", step.text)+ }+}++func TestUnwrapShellCommand(t *testing.T) {+ cases := []struct {+ name string+ input map[string]any+ want string+ }{+ {"double quotes", map[string]any{"command": `/bin/bash -lc "rg \"TODO\" server"`}, `rg "TODO" server`},+ {"single quotes", map[string]any{"command": `zsh -c 'echo '\''hi'\'''`}, `echo 'hi'`},+ {"bare", map[string]any{"command": "sh -c ls"}, "ls"},+ {"no wrapper", map[string]any{"command": "git status"}, "git status"},+ {"argv", map[string]any{"cmd": []any{"bash", "-lc", "go build ./..."}}, "go build ./..."},+ {"argv without a shell", map[string]any{"command": []any{"git", "status"}}, "git status"},+ // An agent often sends a whole script as one command. Its first line+ // says where it starts; the rest would be a patch body in the chat.+ {"script in a wrapper", map[string]any{"command": "/bin/zsh -lc \"mkdir run-b\napply_patch <<'PATCH'\n*** Begin Patch\n+First line.\nPATCH\""}, "mkdir run-b …"},+ {"script without a wrapper", map[string]any{"command": "\nset -e\nmake test\n"}, "set -e …"},+ {"argv script", map[string]any{"cmd": []any{"bash", "-lc", "cd server\ngo build ./..."}}, "cd server …"},+ {"one line with a trailing newline", map[string]any{"command": "bash -lc 'git status\n'"}, "git status"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ original := tc.input["command"]+ out := unwrapShellCommand(tc.input)+ got, _ := out["command"].(string)+ if got == "" {+ got, _ = out["cmd"].(string)+ }+ if got != tc.want {+ t.Fatalf("command = %q, want %q", got, tc.want)+ }+ // Other subscribers read the same payload.+ if s, ok := original.(string); ok && tc.input["command"] != s {+ t.Fatalf("the event's own input was changed to %v", tc.input["command"])+ }+ })+ }+}++// The list is where the run is now: the newest steps, with a count of all of+// them.+func TestStepFeedKeepsTheNewestSteps(t *testing.T) {+ var feed stepFeed+ feed.add(stepLine{icon: "⏳", text: "Starting the agent", transient: true})+ for _, file := range []string{"a", "b", "c", "d", "e", "f", "g", "h"} {+ feed.add(stepLine{icon: "📖", text: "Reading " + file})+ }+ feed.add(stepLine{icon: "📖", text: "Reading h"})+ want := "<blockquote>📖 Reading c\n📖 Reading d\n📖 Reading e\n📖 Reading f\n📖 Reading g\n📖 Reading h ×2\n⏱ 2m · 9 steps</blockquote>"+ if got := feed.render(2 * time.Minute); got != want {+ t.Fatalf("feed = %q\nwant %q", got, want)+ }+ if got := (&stepFeed{}).render(time.Minute); got != "" {+ t.Fatalf("empty feed = %q", got)+ }+}++func TestParseProgressMode(t *testing.T) {+ for raw, want := range map[string]ProgressMode{+ "": ProgressAuto, "auto": ProgressAuto, " Off ": ProgressOff, "summary": ProgressSummary, "DETAIL": ProgressDetail,+ } {+ if got, ok := ParseProgressMode(raw); !ok || got != want {+ t.Errorf("ParseProgressMode(%q) = %s, %v; want %s", raw, got, ok, want)+ }+ }+ if got, ok := ParseProgressMode("verbose"); ok || got != ProgressAuto {+ t.Errorf("unknown mode = %s, %v; want auto reported as unknown", got, ok)+ }+}diff --git a/server/internal/integrations/telegram/outbound_revocation_test.go b/server/internal/integrations/telegram/outbound_revocation_test.gonew file mode 100644index 0000000000..b566c5d69e--- /dev/null+++ b/server/internal/integrations/telegram/outbound_revocation_test.go@@ -0,0 +1,93 @@+package telegram++import (+ "context"+ "errors"+ "strings"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/integrations/channel"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func TestOutboundRevocationStopsExistingStream(t *testing.T) {+ bot := &auditBot{}+ o, q, clock, e := review8545Setup(t, bot)+ o.handleTaskMessage(telegramPartialEvent(e.TaskID, "Checking."))+ q.routing.installation.Status = "revoked"+ clock.advance(4 * time.Second)+ o.handleTaskMessage(telegramPartialEvent(e.TaskID, " PRIVATE_AFTER_REVOKE"))+ bot.mu.Lock()+ defer bot.mu.Unlock()+ for _, body := range bot.messages {+ if strings.Contains(body, "PRIVATE_AFTER_REVOKE") {+ t.Fatalf("revoked installation received streamed content: %q; calls=%v", body, bot.methods)+ }+ }+}++func TestOutboundRevocationStopsHeartbeat(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P)+ h.launch()+ h.o.q.(*fakeTelegramOutboundQueries).installation.Status = "revoked"+ h.skew.Add(int64(75 * time.Second))+ h.openEditSlot()+ h.o.mu.Lock()+ st := h.o.streams[h.taskID]+ gen := st.flushGen+ h.o.mu.Unlock()+ h.o.flushStream(st.target, st, gen)+ if got := h.sent(); len(got) != 1 {+ t.Fatalf("heartbeat sent after revocation: %+v", got)+ }+ h.o.mu.Lock()+ defer h.o.mu.Unlock()+ if len(h.o.streams) != 0 {+ t.Fatal("revoked stream still holds its scheduler and timers")+ }+}++func TestOutboundRevocationStopsDeferredText(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P)+ h.text("我")+ h.o.handleTaskMessage(events.Event{+ TaskID: h.taskID, Type: protocol.EventTaskMessage,+ Payload: protocol.TaskMessagePayload{Type: "text", Content: "会检查这些文件。"},+ })+ h.o.q.(*fakeTelegramOutboundQueries).installation.Status = "revoked"+ deadline := time.Now().Add(3 * time.Second)+ for {+ h.o.mu.Lock()+ st := h.o.streams[h.taskID]+ h.o.mu.Unlock()+ if st == nil {+ break+ }+ if time.Now().After(deadline) {+ t.Fatal("deferred push did not stop the revoked stream")+ }+ time.Sleep(10 * time.Millisecond)+ }+ if got := h.sent(); len(got) != 1 {+ t.Fatalf("deferred text sent after revocation: %+v", got)+ }+}++type unavailableStreamInstallation struct{ outboundQueries }++func (q unavailableStreamInstallation) GetChannelInstallation(context.Context, db.GetChannelInstallationParams) (db.ChannelInstallation, error) {+ return db.ChannelInstallation{}, errors.New("installation lookup unavailable")+}++func TestOutboundStreamFailsClosedWhenInstallationCannotBeChecked(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P)+ h.text("Checking.")+ h.o.q = unavailableStreamInstallation{h.o.q}+ h.tool("Read", map[string]any{"file_path": "private.txt"})+ if got := h.sent(); len(got) != 1 {+ t.Fatalf("stream used cached credentials after lookup failed: %+v", got)+ }+}diff --git a/server/internal/integrations/telegram/outbound_stream_flush_test.go b/server/internal/integrations/telegram/outbound_stream_flush_test.gonew file mode 100644index 0000000000..06a5250dec--- /dev/null+++ b/server/internal/integrations/telegram/outbound_stream_flush_test.go@@ -0,0 +1,106 @@+package telegram++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// An agent often writes one short sentence and then works in tools for+// minutes. The sentence's first chunk opens the message; the rest arrives+// inside the edit interval. Dropping it there left the chat showing a single+// word until the final answer, because no later frame came to carry it.+func TestOutboundFlushesTextAThrottledFrameLeftBehind(t *testing.T) {+ type request struct {+ method string+ body map[string]any+ }+ var mu sync.Mutex+ var requests []request+ snapshot := func() []request {+ mu.Lock()+ defer mu.Unlock()+ return append([]request(nil), requests...)+ }+ api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var body map[string]any+ _ = json.NewDecoder(r.Body).Decode(&body)+ method := r.URL.Path[strings.LastIndex(r.URL.Path, "/")+1:]+ mu.Lock()+ requests = append(requests, request{method: method, body: body})+ mu.Unlock()+ w.Header().Set("Content-Type", "application/json")+ if method == "sendMessage" {+ _, _ = w.Write([]byte(`{"ok":true,"result":{"message_id":99,"chat":{"id":42,"type":"private"},"date":0,"text":"I"}}`))+ return+ }+ _, _ = w.Write([]byte(`{"ok":true,"result":true}`))+ }))+ defer api.Close()++ q := newTelegramOutboundQueries(t)+ q.channelOrigin = true+ o := NewOutbound(q, nil, api.URL, api.Client(), nil)+ ctx, cancel := context.WithCancel(context.Background())+ o.Start(ctx)+ defer func() {+ cancel()+ if !o.WaitWithTimeout(time.Second) {+ t.Error("outbound workers did not stop")+ }+ }()++ taskID := telegramTestEvent().TaskID+ frame := func(content string) events.Event {+ return events.Event{+ TaskID: taskID, Type: protocol.EventTaskMessage,+ Payload: protocol.TaskMessagePayload{TaskID: taskID, Type: "text", Content: content},+ }+ }++ o.handleTaskMessage(frame("I"))+ if got := snapshot(); len(got) != 1 || got[0].method != "sendMessage" {+ t.Fatalf("first frame requests = %+v, want one sendMessage", got)+ }++ // Leave 150ms of the edit interval, so the test does not wait out all of it.+ o.mu.Lock()+ schedule := o.streams[taskID].schedule+ o.mu.Unlock()+ schedule.mu.Lock()+ schedule.lastEdit = time.Now().Add(150*time.Millisecond - privateEditInterval)+ schedule.mu.Unlock()++ o.handleTaskMessage(frame(" will check the open pull requests"))+ if got := snapshot(); len(got) != 1 {+ t.Fatalf("frame inside the edit interval sent %d requests, want it held back", len(got)-1)+ }++ // No further frame arrives: the agent is in a tool call.+ deadline := time.Now().Add(3 * time.Second)+ for len(snapshot()) < 2 && time.Now().Before(deadline) {+ time.Sleep(20 * time.Millisecond)+ }+ got := snapshot()+ if len(got) != 2 {+ t.Fatalf("held-back text never reached Telegram: requests = %+v", got)+ }+ if got[1].method != "editMessageText" || got[1].body["message_id"] != float64(99) ||+ got[1].body["text"] != "I will check the open pull requests" {+ t.Fatalf("flush request = %+v, want an edit of message 99 with the whole text", got[1])+ }++ // One flush per held-back text, not a timer that keeps firing.+ time.Sleep(300 * time.Millisecond)+ if got := snapshot(); len(got) != 2 {+ t.Fatalf("requests after the flush = %d, want 2", len(got))+ }+}diff --git a/server/internal/integrations/telegram/outbound_test.go b/server/internal/integrations/telegram/outbound_test.goindex 7a37be012c..8f2ccf0d5e 100644--- a/server/internal/integrations/telegram/outbound_test.go+++ b/server/internal/integrations/telegram/outbound_test.go@@ -490,7 +490,7 @@ func TestOutboundCapacityPruningPreservesActiveBackoff(t *testing.T) {protected.mu.Lock()protected.setBackoffTill(current.Add(time.Hour))protected.mu.Unlock()- current = current.Add(editInterval)+ current = current.Add(privateEditInterval)o.mu.Lock()for chatID := int64(maxChatSchedules + 1); chatID <= maxChatSchedules+20; chatID++ {@@ -520,9 +520,9 @@ func TestOutboundCapacityEvictionPreservesRecentChatCooldown(t *testing.T) {backoffFor time.DurationwantRoom bool}{- {name: "cooldown without retry after", idleFor: editInterval - time.Millisecond},- {name: "retry after shorter than cooldown", idleFor: time.Second, backoffFor: time.Second},- {name: "cooldown elapsed", idleFor: editInterval, backoffFor: time.Second, wantRoom: true},+ {name: "cooldown without retry after", idleFor: privateEditInterval - time.Millisecond},+ {name: "retry after shorter than cooldown", idleFor: privateEditInterval / 2, backoffFor: privateEditInterval / 4},+ {name: "cooldown elapsed", idleFor: privateEditInterval, backoffFor: time.Second, wantRoom: true},}for _, tt := range tests {@@ -573,7 +573,7 @@ func TestOutboundManyActiveBackoffsKeepTotalScheduleCacheBounded(t *testing.T) {o.mu.Lock()o.releaseChatLocked(schedule, chatID)o.mu.Unlock()- current = current.Add(editInterval)+ current = current.Add(privateEditInterval)}o.mu.Lock()got := len(o.chats)@@ -604,7 +604,7 @@ func TestOutboundCompressedChatInheritsBotFallback(t *testing.T) {o.mu.Lock()o.releaseChatLocked(schedule, chatID)o.mu.Unlock()- current = current.Add(editInterval)+ current = current.Add(privateEditInterval)}o.mu.Lock()newSchedule := o.retainChatLocked("bot-a", maxChatSchedules+1)diff --git a/server/internal/integrations/wecom/progress_export.go b/server/internal/integrations/wecom/progress_export.gonew file mode 100644index 0000000000..cc2efe9a93--- /dev/null+++ b/server/internal/integrations/wecom/progress_export.go@@ -0,0 +1,115 @@+package wecom++import (+ "regexp"+ "strings"+ "time"+)++// progress_export.go — the step vocabulary for adapters that show a run's+// steps somewhere other than a WeCom bubble.+//+// What a tool call is, which of its arguments names the work, and what has to+// be cut or masked before a chat may show it are all decided in+// progress_render.go and progress_secrets.go. Another adapter that worded steps+// itself would have to keep its own copy of the tool table and the redactor in+// step with these, so it asks here instead.++// StepKind is what sort of work a step is, for an adapter that marks each+// sort its own way.+type StepKind string++const (+ StepStarting StepKind = "starting"+ StepRead StepKind = "read"+ StepEdit StepKind = "edit"+ StepCommand StepKind = "command"+ StepSearch StepKind = "search"+ StepWeb StepKind = "web"+ StepSubtask StepKind = "subtask"+ StepPlan StepKind = "plan"+ StepService StepKind = "service"+ StepSkill StepKind = "skill"+ StepTool StepKind = "tool"+ StepError StepKind = "error"+)++// Step is one step of a run, worded and safe to show.+type Step struct {+ Kind StepKind+ Text string+}++// DescribeStep words one task:message as a step of the run, in the given+// locale. It reports false for a message that is not a step: prose, a tool's+// output, reasoning.+//+// withArgument false leaves out everything the agent composed — the path, the+// command line, the search term, an error's text — and keeps the kind of work+// and the identifiers the workspace configured, for a reader who is not the+// one the run belongs to.+func DescribeStep(payload any, l Locale, withArgument bool) (Step, bool) {+ msg := taskMessageFields(payload)+ if msg.msgType != "tool_use" && msg.msgType != "error" {+ return Step{}, false+ }+ step, ok := stepFromMessage(msg)+ if !ok {+ return Step{}, false+ }+ if !withArgument {+ step.args = ""+ named := step.kind == progressService ||+ (step.kind == progressTool && toolIdentifier.MatchString(step.arg))+ if !named {+ step.arg = ""+ }+ }+ text := strings.TrimSpace(step.line(copyFor(l), progressLevelDetail))+ if text == "" {+ return Step{}, false+ }+ return Step{Kind: exportedKind(step.kind), Text: text}, true+}++// toolIdentifier is a tool's own name: `frobnicate`, `web.run`. Some agent+// backends pass a call's title as its name instead, and the agent composed the+// title: "Delete /srv/acme/customers.csv".+var toolIdentifier = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,48}$`)++// StartingStep is the run getting under way, before its first tool call.+func StartingStep(l Locale) Step {+ return Step{Kind: StepStarting, Text: copyFor(l).Progress.Starting}+}++// FormatElapsed renders how long a run has taken, the way the bubble and the+// web chat's status pill do.+func FormatElapsed(d time.Duration) string { return formatElapsed(d) }++func exportedKind(k progressKind) StepKind {+ switch k {+ case progressStarting:+ return StepStarting+ case progressRead:+ return StepRead+ case progressEdit:+ return StepEdit+ case progressCommand:+ return StepCommand+ case progressSearch:+ return StepSearch+ case progressWeb:+ return StepWeb+ case progressSubtask:+ return StepSubtask+ case progressPlan:+ return StepPlan+ case progressService:+ return StepService+ case progressSkill:+ return StepSkill+ case progressError:+ return StepError+ }+ return StepTool+}diff --git a/server/internal/integrations/wecom/progress_export_test.go b/server/internal/integrations/wecom/progress_export_test.gonew file mode 100644index 0000000000..f01274369e--- /dev/null+++ b/server/internal/integrations/wecom/progress_export_test.go@@ -0,0 +1,64 @@+package wecom++import (+ "strings"+ "testing"++ "github.com/multica-ai/multica/server/pkg/protocol"+)++// TestDescribeStepWordsAStepForAnotherAdapter — a tool call and an error are+// steps; prose, a tool's output and reasoning are not.+func TestDescribeStepWordsAStepForAnotherAdapter(t *testing.T) {+ step, ok := DescribeStep(toolUse("exec_command", map[string]any{"command": "git status --short"}), LocaleEn, true)+ if !ok || step.Kind != StepCommand || step.Text != "Running git status --short" {+ t.Fatalf("command step = %+v, %v", step, ok)+ }++ for _, msg := range []protocol.TaskMessagePayload{+ {Type: "text", Content: "I will check the repository."},+ {Type: "tool_result", Tool: "exec_command", Output: "M server/main.go"},+ {Type: "thinking", Content: "The user wants a status."},+ } {+ if step, ok := DescribeStep(msg, LocaleEn, true); ok {+ t.Errorf("%s message became the step %+v", msg.Type, step)+ }+ }+}++// TestDescribeStepWithoutArgumentKeepsOnlyTheKindOfWork — a reader the run+// does not belong to sees what sort of work it is and nothing the agent+// composed.+func TestDescribeStepWithoutArgumentKeepsOnlyTheKindOfWork(t *testing.T) {+ cases := []struct {+ name string+ msg protocol.TaskMessagePayload+ kind StepKind+ want string+ hide string+ }{+ {"a command", toolUse("Bash", map[string]any{"command": "cat /srv/acme/.env"}), StepCommand, "Running a command", "acme"},+ {"a file", toolUse("Read", map[string]any{"file_path": "/srv/acme/handler.go"}), StepRead, "Reading a file", "acme"},+ {"a search", toolUse("Grep", map[string]any{"pattern": "customer_name"}), StepSearch, "Searching the code", "customer_name"},+ {"an error", protocol.TaskMessagePayload{Type: "error", Content: "open /srv/acme/key: denied"}, StepError, "That step errored — carrying on", "acme"},+ {"an MCP call", toolUse("mcp__calendar__list_events", map[string]any{"owner": "[email protected]"}), StepService, "Calling calendar · list_events", "ada"},+ {"an unknown tool", toolUse("frobnicate", map[string]any{"target": "acme-prod"}), StepTool, "Using frobnicate", "acme"},+ // Some agent backends pass the call's title as the tool's name, and+ // the agent composed the title.+ {"a tool named by its title", toolUse("Delete /srv/acme/customers.csv", nil), StepTool, "Working", "acme"},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ step, ok := DescribeStep(tc.msg, LocaleEn, false)+ if !ok || step.Kind != tc.kind || step.Text != tc.want {+ t.Fatalf("step = %+v, %v; want %s %q", step, ok, tc.kind, tc.want)+ }+ // The same call does name its argument for the run's owner, so the+ // absence above is the flag's doing.+ detailed, _ := DescribeStep(tc.msg, LocaleEn, true)+ if !strings.Contains(detailed.Text, tc.hide) {+ t.Fatalf("detailed step %q does not carry %q", detailed.Text, tc.hide)+ }+ })+ }+}diff --git a/server/pkg/db/generated/task_message.sql.go b/server/pkg/db/generated/task_message.sql.goindex d91794ceba..96e75f3c44 100644--- a/server/pkg/db/generated/task_message.sql.go+++ b/server/pkg/db/generated/task_message.sql.go@@ -358,3 +358,38 @@ func (q *Queries) ListTaskProgressSince(ctx context.Context, arg ListTaskProgres}return items, nil}++const listTaskReplyFragments = `-- name: ListTaskReplyFragments :many+SELECT type, COALESCE(CASE WHEN type = 'text' THEN content END, '')::text AS content+FROM task_message+WHERE task_id = $1 AND type IN ('text', 'tool_use', 'error')+ORDER BY seq ASC+`++type ListTaskReplyFragmentsRow struct {+ Type string `json:"type"`+ Content string `json:"content"`+}++// Rebuild a Telegram placeholder without its progress when another replica+// handles cancellation. Only prose leaves this query; tool/error rows mark+// paragraph boundaries without loading arguments, results, or reasoning.+func (q *Queries) ListTaskReplyFragments(ctx context.Context, taskID pgtype.UUID) ([]ListTaskReplyFragmentsRow, error) {+ rows, err := q.db.Query(ctx, listTaskReplyFragments, taskID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListTaskReplyFragmentsRow{}+ for rows.Next() {+ var i ListTaskReplyFragmentsRow+ if err := rows.Scan(&i.Type, &i.Content); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}diff --git a/server/pkg/db/queries/task_message.sql b/server/pkg/db/queries/task_message.sqlindex 5bcda16837..5d01eb321e 100644--- a/server/pkg/db/queries/task_message.sql+++ b/server/pkg/db/queries/task_message.sql@@ -111,3 +111,12 @@ ORDER BY seq ASC;-- name: DeleteTaskMessages :execDELETE FROM task_messageWHERE task_id = $1;++-- name: ListTaskReplyFragments :many+-- Rebuild a Telegram placeholder without its progress when another replica+-- handles cancellation. Only prose leaves this query; tool/error rows mark+-- paragraph boundaries without loading arguments, results, or reasoning.+SELECT type, COALESCE(CASE WHEN type = 'text' THEN content END, '')::text AS content+FROM task_message+WHERE task_id = $1 AND type IN ('text', 'tool_use', 'error')+ORDER BY seq ASC;