Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.
TypeScript agent-teamagentic-aiai-agentsai-assistantclaude-codecodexcursorelectrongrokgrok-bot-alternativelinuxlocal-firstmacosmcpmulti-agentopenclaw-alternativeopencodewindows
Send a routine's whole reply to Telegram instead of cutting it at 140 characters (#84)
Cleiton Salvagni25e371428594
diff --git a/docs/spec-mvp.md b/docs/spec-mvp.mdindex 6134db1..74ba2c8 100644--- a/docs/spec-mvp.md+++ b/docs/spec-mvp.md@@ -272,7 +272,7 @@ Receitas que os agentes seguem pra um tipo de tarefa ("como rodar os testes do C- Um bot do próprio usuário (criado no @BotFather): o token vai em Configurações, conferido com o Telegram e guardado no cofre do Mac. O app busca as mensagens do bot (long polling), então nada precisa chegar no Mac.- **Pareamento:** o app mostra um código; só o chat que mandar `/start <código>` fica com o bot. Mensagens e toques de outros chats são ignorados.- **O que chega:** cada aprovação, com Aprovar/Recusar (alto risco pede um segundo toque); cada pergunta de agente (`ask_user`), que eu respondo respondendo à mensagem, e a resposta entra na conversa como se eu tivesse escrito; o fim das rotinas e os avisos de limite.-- O Telegram recebe o texto das aprovações e perguntas (ferramenta, argumentos, motivo), e a tela diz isso. Desligado até eu colar um token.+- O Telegram recebe o texto das aprovações e perguntas (ferramenta, argumentos, motivo) e as respostas das rotinas, e a tela diz isso. Desligado até eu colar um token.### 20. Boletim e custo por tarefa (M12)diff --git a/src/core/index.ts b/src/core/index.tsindex b7d51ff..5c34961 100644--- a/src/core/index.ts+++ b/src/core/index.ts@@ -243,9 +243,9 @@ function toPhone(e: CoreEvent): void {}// Desktop notification, and the same on the phone.-const notifyAll = (title: string, body: string, conversationId?: string): void => {- toMain({ type: 'notify', title, body, conversationId, sound: settings().sounds !== false })- void telegram?.notice(title, body)+const notifyAll = (title: string, shortText: string, conversationId?: string, fullText?: string): void => {+ toMain({ type: 'notify', title, body: shortText, conversationId, sound: settings().sounds !== false })+ void telegram?.notice(title, fullText ?? shortText)}// Asks the main process to do what only it can: open the browser or a folder, show a notification.diff --git a/src/core/routines.ts b/src/core/routines.tsindex f09bcdf..ea01524 100644--- a/src/core/routines.ts+++ b/src/core/routines.ts@@ -85,7 +85,7 @@ export interface RoutineDeps {connectors?: { call(id: string, tool: string, args: Record<string, unknown>): Promise<CallToolResult>; list(): Connector[] }blocked?: () => boolean // paused, or quiet hours: nothing is due until it ends (then it runs late)emit: (e: CoreEvent) => void- notify?: (title: string, body: string, conversationId: string) => void+ notify?: (title: string, shortText: string, conversationId: string, fullText?: string) => voidnow?: () => numberwait?: (ms: number) => Promise<void> // between tries (tests skip it)}@@ -348,7 +348,9 @@ export class Routines {if (!reply) returnconst latest = this.deps.db.routine(id)if (latest) this.store({ ...latest, lastAt: this.now(), lastMessageId: reply.id })- this.deps.notify?.(`${agentName(this.deps.db, r.agentId)} · ${r.name}`, outcome(reply), r.conversationId)+ const title = `${agentName(this.deps.db, r.agentId)} · ${r.name}`+ const fullText = reply.run?.status === 'done' ? reply.text.trim() : ''+ this.deps.notify?.(title, outcome(reply), r.conversationId, fullText || undefined)}).catch((e: unknown) => console.error('[routines]', e)).finally(() => {diff --git a/src/core/telegram.ts b/src/core/telegram.tsindex 65b32bf..38245a7 100644--- a/src/core/telegram.ts+++ b/src/core/telegram.ts@@ -226,7 +226,7 @@ export class Telegram {}async notice(title: string, body: string): Promise<void> {- await this.send(`${title}\n\n${body}`)+ for (const chunk of splitIntoChunks(`${title}\n\n${body}`, MAX_TEXT)) await this.send(chunk)}}@@ -236,3 +236,21 @@ function approvalText(ap: Approval): string {}const clip = (s: string): string => (s.length > MAX_TEXT ? `${s.slice(0, MAX_TEXT)}…` : s)++// Cuts at the last line break that fits, and drops it; a line longer than maxLength is cut at maxLength.+export function splitIntoChunks(text: string, maxLength: number): string[] {+ const chunks: string[] = []+ let remaining = text++ while (remaining.length > maxLength) {+ const lineBreak = remaining.lastIndexOf('\n', maxLength)+ const endsAtLineBreak = lineBreak > 0+ const end = endsAtLineBreak ? lineBreak : maxLength++ chunks.push(remaining.slice(0, end))+ remaining = remaining.slice(endsAtLineBreak ? end + 1 : end)+ }++ chunks.push(remaining)+ return chunks+}diff --git a/src/renderer/src/components/Pages.tsx b/src/renderer/src/components/Pages.tsxindex d66c5c4..b921200 100644--- a/src/renderer/src/components/Pages.tsx+++ b/src/renderer/src/components/Pages.tsx@@ -1688,7 +1688,7 @@ function PhoneCard({ info }: { info?: TelegramInfo }): ReactNode {)}{(error || info?.error) && <p className="note note--error">{error || L(`O Telegram não está respondendo: ${info?.error}`, `Telegram isn't responding: ${info?.error}`)}</p>}<p className="hint">- <Icon name="shield" size={13} /> {L('O Telegram recebe o texto das aprovações e perguntas (ferramenta, argumentos, motivo). O token fica no cofre do sistema. Uma ação de alto risco pede dois toques.', 'Telegram receives the text of approvals and questions (tool, arguments, reason). The token stays in the system’s vault. A high-risk action takes two taps.')}+ <Icon name="shield" size={13} /> {L('O Telegram recebe o texto das aprovações e perguntas (ferramenta, argumentos, motivo) e as respostas das rotinas. O token fica no cofre do sistema. Uma ação de alto risco pede dois toques.', 'Telegram receives the text of approvals and questions (tool, arguments, reason) and the routines’ replies. The token stays in the system’s vault. A high-risk action takes two taps.')}</p></Card>)diff --git a/test/routines.test.ts b/test/routines.test.tsindex 207591f..4a69551 100644--- a/test/routines.test.ts+++ b/test/routines.test.ts@@ -294,6 +294,8 @@ describe('routine retries', () => {let turns: numberlet waits: number[]let notes: string[]+ let fullTexts: (string | undefined)[]+ let doneText: stringlet onWait: () => voidbeforeEach(async () => {@@ -304,13 +306,15 @@ describe('routine retries', () => {turns = 0waits = []notes = []+ fullTexts = []+ doneText = 'Feito.'onWait = () => {}const flaky: Engine = {id: 'claude',async *run() {turns++if (turns <= failures) yield { type: 'error', message: `o provedor caiu (${turns})` }- else yield { type: 'done', text: 'Feito.', usage: { inputTokens: 1, cacheReadTokens: 0, outputTokens: 1 } }+ else yield { type: 'done', text: doneText, usage: { inputTokens: 1, cacheReadTokens: 0, outputTokens: 1 } }}}const engines: Record<EngineId, Engine> = { claude: flaky, codex: fakeEngine('codex'), opencode: fakeEngine('opencode'), pi: fakeEngine('pi'), gemini: fakeEngine('gemini'), cursor: fakeEngine('cursor') }@@ -322,7 +326,7 @@ describe('routine retries', () => {emit: () => {},now: () => clock,wait: async (ms) => (waits.push(ms), onWait()),- notify: (_title, body) => notes.push(body)+ notify: (_title, shortText, _conversationId, fullText) => (notes.push(shortText), fullTexts.push(fullText))})runner = new Runner({ db, engines, settings: async () => settings, emit: () => {}, workDir: mkdtempSync(join(tmpdir(), 'ad-retry-w-')), gateway, routines })})@@ -351,6 +355,21 @@ describe('routine retries', () => {expect(notes).toEqual(['Feito.'])})+ it('a long result: the notification stays short, and the whole reply goes along for the phone', async () => {+ failures = 0+ doneText = `## Notícias de hoje\n\n${Array.from({ length: 5 }, (_, i) => `- Item ${i + 1}: ${'texto '.repeat(20).trim()}`).join('\n')}`+ await fire()+ expect(notes).toHaveLength(1)+ expect(notes[0]!.length).toBeLessThanOrEqual(140)+ expect(fullTexts).toEqual([doneText])+ })++ it('a failed routine sends only the short outcome to the phone', async () => {+ failures = 99+ await fire()+ expect(fullTexts).toEqual([undefined])+ })+it('after the third failure it stops, says it tried three times, and notifies once', async () => {failures = 99await fire()diff --git a/test/telegram.test.ts b/test/telegram.test.tsindex 510c9d9..ef26f30 100644--- a/test/telegram.test.ts+++ b/test/telegram.test.ts@@ -1,6 +1,6 @@import { afterEach, beforeEach, describe, expect, it } from 'vitest'import type { Approval, Message } from '../src/shared/types'-import { Telegram } from '../src/core/telegram'+import { splitIntoChunks, Telegram } from '../src/core/telegram'// A stand-in for Telegram's Bot API: updates are queued by the test; what the bot sends is recorded.function botApi() {@@ -128,4 +128,26 @@ describe('Telegram', () => {await settle()expect(answered).toEqual([['c1', 'Sexta que vem']])})++ it("a long notice arrives whole, in as many messages as it takes, split between lines", async () => {+ await pair()+ const lines = Array.from({ length: 120 }, (_, i) => `- Item ${i + 1}: ${'texto '.repeat(8).trim()}`)+ await tg.notice('Lia · Bom dia', lines.join('\n'))+ const texts = api.sent.slice(1).filter((s) => s.method === 'sendMessage').map((s) => String(s.body['text']))+ expect(texts.length).toBeGreaterThan(1)+ for (const t of texts) expect(t.length).toBeLessThanOrEqual(4096)+ expect(texts[0]!.startsWith('Lia · Bom dia\n\n- Item 1:')).toBe(true)+ expect(texts.join('\n')).toBe(`Lia · Bom dia\n\n${lines.join('\n')}`)+ })++ it('a line longer than a message is cut at the limit', () => {+ expect(splitIntoChunks('abcdefghij', 4)).toEqual(['abcd', 'efgh', 'ij'])+ expect(splitIntoChunks('ab\ncdefgh', 4)).toEqual(['ab', 'cdef', 'gh'])+ })++ it('a short notice is one message', async () => {+ await pair()+ await tg.notice('Lia · Bom dia', 'Linha 1\nLinha 2')+ expect(api.sent.at(-1)!.body['text']).toBe('Lia · Bom dia\n\nLinha 1\nLinha 2')+ })})