Skip to content

Telegram: save files and media for the agent, and transcribe voice messages locally - #771

Open
SunnyCapt wants to merge 7 commits into
ClickHouse:mainfrom
SunnyCapt:sunnycapt/telegram-media
Open

SunnyCapt wants to merge 7 commits into
ClickHouse:mainfrom
SunnyCapt:sunnycapt/telegram-media

Conversation

@SunnyCapt

@SunnyCapt SunnyCapt commented Nov 29, 2026 •

Copy link
Copy Markdown

Closes #770.

Two commits, meant to be reviewed one at a time.

1. Telegram: save files and media sent to the bot for the agent

  • The message handler also matches voice messages, audio, videos and video notes; before, they were dropped silently.
  • Every file on the message, on the message it replies to and on each part of an album is saved to <workspace>/.uploads/<session id>/<id>_<name> and recorded in uploaded_files, like a web UI upload, so deleting the session deletes it. The turn names it as [Saved to <path>].
  • Inline reading is unchanged (photos, images, PDFs, text, ZIP) and now reads the saved copy instead of downloading twice. The documents of an album are named and saved, not read inline, so ten PDFs cannot overrun the request.
  • Attachments are handled after reply routing, so a file lands in the session the message goes to, and a refused reply downloads nothing.
  • Sender-given file names cannot leave the upload directory or start a line of the turn of their own.
  • telegram.save_attachments (default true, read per message) turns saving off.

2. Transcribe Telegram voice messages with a local Whisper model

  • nerve/transcription/: host recommends a model from the CPUs and memory the process sees (cgroup limits included), the CPU architecture and the free disk; installer builds an environment of its own under NERVE_HOME/transcription with faster-whisper 1.2.1 and av<19 (PyAV 19 dropped the metadata_errors argument faster-whisper passes), downloads the model and checks it on a second of silence; worker runs in that environment as a child process, CPU only; service runs one transcription at a time with a timeout and keeps the transcript beside the file.
  • Nobody is asked. When the Telegram bot starts, the recommended model is installed in the background, or skipped when none fits. A failed attempt is retried after a day, not at every start; transcription.enabled: false installs nothing; turning it back on with a reload, or naming another transcription.model, retries at once.
  • A voice message or video note sent alone is answered with its transcript by the channel, and the transcript is the message the agent acts on. With a caption, forwarded, or quoted by a reply, it is a [Transcript: …] line beside the file.
  • Messages of one chat reach the router in arrival order, so a text sent right after a voice message does not overtake it while it is transcribed.
  • The installer and the worker get an allowlist of environment variables, not Nerve's credentials. Stopping the bot ends an install in progress.
  • nerve setup-transcription (--model, --disable) installs now in the foreground; on a Docker host it runs inside the container. nerve doctor reports whether voice messages are transcribed and why not. transcription is machine-local, also for nerve migrate.

Behaviour change

With Telegram configured, the first start after this change downloads a model into NERVE_HOME/transcription: 0.15 to 1.6 GB depending on the host (small, the ARM pick, is about 0.5 GB), plus an environment of about 250 MB. transcription.enabled: false opts out. An instance without Telegram downloads nothing.

Measurements

On a 10-core ARM host (Apple Silicon under OrbStack, no GPU), 8.5 s of Russian speech: tiny 3.5 s (rough), small about 6 to 7 s (two words wrong), large-v3-turbo about 19 s (every word right). Hence ARM hosts get small. x86 was not measured; the x86 rule (large-v3-turbo from 8 CPUs and 6 GiB) deserves a check on such a host. faster-whisper's default of 4 threads beat all 10 (small: 6 s against 12.5 s).

Testing

  • pytest tests/: 11466 passed. tests/test_setup_provenance.py::TestCredentialSourcesOnAnInstall::test_every_path_is_reported_and_nothing_is_a_value fails in the container this ran in on main as well.
  • New tests: tests/test_telegram_attachments.py, tests/test_transcription.py; helpers of the existing Telegram tests updated.
  • Run on a live Telegram bot: files saved and opened, voice messages echoed and acted on, the model installed on the bot's first start.
  • No frontend change.

Overlap

#728 (Telegram topics) changes much of nerve/channels/telegram.py; whichever lands second will need a rebase.


Note

Medium Risk
Large changes to Telegram message handling and new subprocess/disk-heavy installs on first bot start; failures degrade to file-only turns rather than blocking the daemon.

Overview
Adds two Telegram inbound capabilities: persistent media for the agent and on-device voice/video-note transcription.

Saved attachments — Voice, audio, video, video notes, documents, photos (including albums) are now accepted by the message handler. With telegram.save_attachments (default on), files land in <workspace>/.uploads/<session id>/, are tracked like web uploads, and the turn includes [Saved to …] so the agent can open them; inline behavior for photos/PDFs/text/ZIPs is preserved while avoiding duplicate downloads. A per-chat _ChatOrder queue keeps messages from reaching the router until earlier ones finish (so transcription does not let a following text overtake a voice message).

Local transcription — New transcription.* config (machine-local) and nerve/transcription/ install faster-whisper in an isolated venv under NERVE_HOME, pick a host-appropriate model, and run one child process per file. The bot starts background install on startup; nerve setup-transcription, nerve doctor, and config reload hook in via reconsider_transcription. Standalone voice/video notes are echoed to the user and become the agent turn text; other cases add [Transcript: …] with cached .transcript.json beside saved files.

Docs, config.example.yaml, migration keys, and session cleanup for transcript sidecars are updated accordingly.

Reviewed by Cursor Bugbot for commit 61f0daa. Bugbot is set up for automated code reviews on this repo. Configure here.

@cla-assistant

cla-assistant Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

Voice messages, audio, videos and video notes matched no message handler
and were dropped without a word, and a document that is not text, an
image, a PDF or a ZIP reached the agent as its name only, so the agent
could not open it.

Now each file an authorized user sends, on the message, on the message it
replies to or on any part of an album, is saved in the landing session's
upload directory (<workspace>/.uploads/<session id>/). It is recorded in
uploaded_files like a web upload, so deleting the session deletes it, and
the turn names it as "[Saved to <path>]". Photos, images, PDFs, text files
and ZIPs are still read inline, now from the saved copy instead of a second
download; the documents of an album are named and saved, not read inline,
so ten PDFs cannot overrun the request. Attachments are handled after
reply routing, so the file goes to the session the message lands in and a
refused reply downloads nothing. A file the session already has is not
fetched again; one over the Bot API's 20 MB limit is named, not saved.

Sender-given file names and titles cannot leave the upload directory or
start a line of the turn: separators, control and invisible characters are
removed and long names are cut to the file name limit.

telegram.save_attachments (default true, read per message) turns saving
off: nothing is written to disk and the turn carries what is read inline.
A voice message reached the agent as an audio file it could not hear. Now
the bot transcribes voice messages and video notes on this machine with
faster-whisper; no audio leaves it, there is no remote service, and nobody
is asked. When the Telegram bot starts, the model recommended for the host
is installed in the background, or skipped when none fits the memory or
the disk; voice messages are files until it is ready.
transcription.enabled: false installs nothing and turns it off, and
transcription.model names another model; turning it back on with a reload,
or naming another model, tries the install again at once.

A voice message sent alone is answered at once with its transcript, sent by
the channel rather than the agent, and the transcript is the message the
agent acts on. With a caption, forwarded (someone else's speech) or on the
message a reply quotes, it is a "[Transcript: ...]" line beside the file.
The transcript is kept beside the saved file, keyed by model and language,
so a reply to the same voice message does not run the model again, and
deleting the session deletes it. Messages of one chat reach the router in
the order they arrived, so a text sent right after a voice message no
longer overtakes it while it is transcribed. A failure of any kind leaves
the voice message a file.

nerve.transcription holds the parts. host recommends from the CPUs and
memory the process sees (cgroup limits included), the CPU architecture and
the free disk space: large-v3-turbo on x86 from 8 CPUs and 6 GiB, small
from 4 CPUs and 3 GiB and on ARM, else base, stepping down when it does not
fit. On a 10-core ARM host (Apple Silicon under OrbStack), 8.5 s of speech
took about 6 s with small and 19 s with large-v3-turbo; x86 was not
measured. The model runs on the CPU: the environment has no CUDA libraries.

installer builds a virtual environment of its own under
NERVE_HOME/transcription with faster-whisper 1.2.1 and PyAV below 19, whose
av.open() no longer takes the metadata_errors argument faster-whisper
passes, then downloads the model and transcribes a second of silence before
calling it ready. CTranslate2 and ONNX Runtime stay out of Nerve's lock. It
runs with an allowlist of environment variables, so Nerve's credentials do
not reach pip or the worker; an environment whose Python is gone is built
again; a failed attempt is retried after a day, not at every start; and
stopping the bot kills an install in progress instead of waiting for it.
service runs worker.py in that environment as a child process, one at a
time, with faster-whisper's 4 threads (every CPU made small twice as slow)
and a timeout of at least three times the audio; audio over 20 minutes is
not transcribed.

"nerve setup-transcription" installs the model now in the foreground
(--model to pin one, --disable to turn it off) and, on a Docker host, runs
inside the container, since an environment built on the host would not run
there. nerve doctor says whether voice messages are transcribed, and why
not. transcription is machine-local, also for nerve migrate.
@SunnyCapt
SunnyCapt force-pushed the sunnycapt/telegram-media branch from fbd0db5 to 6aa2611 Compare November 29, 2026 18:28

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Comment thread nerve/channels/telegram.py Resolved
Comment thread nerve/channels/telegram.py Resolved
@github-actions

github-actions Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

AI review gate — AI review passed

Clean review from: Cursor Bugbot.

@nerveai

nerveai commented Nov 29, 2026 •

Copy link
Copy Markdown

Nerve PR review · ✅ Ready to merge

Updated for 61f0daa: Bugbot's leak finding is fixed. A failed or stopped build removes its envs/<lock>-<id> (installer.py:464-469). Stamp-less leftovers from a crash are swept under the install lock (:477-483). A failed update now waits a day like an install (update-failed.json, :284-306); setup-transcription and re-enabling skip the wait.

Earlier rounds, still holding:

  • Lock: faster-whisper's tree is a hash-locked requirements.txt, installed with --require-hashes --only-binary :all:. Against PyPI, all 25 pins match real files and the closure is complete.
  • Install: each build gets its own directory and is switched atomically under a cross-process lock.
  • Chat order: holds across dropped messages and albums.

The PR stops Telegram from silently dropping voice, audio and video. Files now share a web upload's lifecycle.

Completeness: tests for both halves, the lock, the switch, cleanup and back-off; config, docs, reload, doctor, setup-transcription; no migration.

Worth considering:

Checked: full suite in an offline sandbox at 6243d59 (3 chunks): 11477 passed, 41 skipped, test_slack_integration.py excluded. Installer-only delta to 61f0daa: both test files that reference nerve.transcription, 108 passed. ci.yml waits for maintainer approval (fork PR); Bugbot and the AI gate pass at 61f0daa · automated review by nerveai — mention @nerveai to ask a follow-up.

A message that took its turn in the chat's order but never reached the
router (a stranger's message, an answer to a question card, a message in
the delivery-only sink, a later part of an album) gave the turn up at once.
The chain only waits for the message just before, so a text sent after it
could overtake a voice message still being transcribed. Albums did not
wait at all.

Such a message now passes its turn on only once the one before it did, so
the chain holds across it. Like waiting, this gives up after 30 minutes, so a turn
ahead that never ends cannot hold the chain, or its memory, for good. An album's first part keeps its turn until the
album is delivered, and the album waits for what was sent before it, so a
text sent right after an album no longer overtakes it either.

An album sent as a reply to a voice message also carries the transcript of
that voice message, as a single message does.
Only faster-whisper was pinned. CTranslate2, ONNX Runtime, tokenizers,
huggingface_hub and the rest of its tree installed at whatever version the
package index served that day, outside review, and on every Telegram host
the install starts by itself when the bot starts.

The environment is now installed from nerve/transcription/requirements.txt:
the whole tree at exact versions with sha256 hashes, compiled by uv for every
platform (--universal) from requirements.in, installed with
--require-hashes and --only-binary :all:, so a host gets the reviewed
versions and runs no build code. It was compiled with --exclude-newer a week
back, the same seven days Dependabot waits; the header of the file has the
command. The environment records the digest of the lock it was built from; after
an update ships another lock, the next start of the bot installs the
locked versions again without downloading the model, and if that fails
the environment in place stays in use. A test checks that every
requirement is an exact pin with hashes, that the roots are the pins of
requirements.in and that the lock pins FASTER_WHISPER_VERSION.

The locked tree was installed from scratch with uv and transcribed a voice
message; the files ship in the wheel.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Comment thread nerve/transcription/installer.py Resolved
Bringing an installed environment up to a new lock ran pip inside the
environment that voice messages use, so a worker started meanwhile could
import a half-written package and lose its transcript.

The environment is now built in NERVE_HOME/transcription/envs/<lock>, beside
the one in use, and stamped; then the env file is rewritten atomically to
name it. A worker uses either the whole old tree or the whole new one. The
environment it replaced stays until the next switch, as a worker may still
run from it, and older ones are removed. An environment already built from
the current lock is not built again, so installing another model downloads
only the model. One in the older layout (NERVE_HOME/transcription/venv) stays
in use until the first switch.

@cursor cursor Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

Comment thread nerve/transcription/installer.py Resolved
…ll at a time

When the environment env named was this lock's but broken (its Python gone
after a new base image, say), the installer deleted it and built in that
same directory before switching: once bin/python was back, voice messages
used it while packages were still being written. Two installations at once
(the bot's at start and nerve setup-transcription) could also delete each
other's directory.

Each build now goes to a directory of its own, envs/<lock>-<id>, so nothing
is ever built where env points, and the broken one is removed after the
switch. Installations take NERVE_HOME/transcription/install.lock (flock), so
the bot's and the CLI's run one after the other: the second finds the
environment, or the model, ready and does nothing. Waiting for the lock
ends when the bot stops.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

Fix All in Cursor

Reviewed by Cursor Bugbot for commit c964807. Configure here.

Comment thread nerve/transcription/installer.py Resolved
…led updates

Each build has a directory of its own, but one that failed or was stopped
stayed on disk, and the update to a new lock was tried again at every start
with no pause: a host that kept failing (a full disk) gained an environment
of about 250 MB each time.

A build now removes its directory when it fails or is stopped. Before a
build, directories without their stamp (left by a crash or a kill) are
removed; the stamp is written last, and a whole environment, the one in use
or the one it replaced, is never touched there. A failed update is recorded
in update-failed.json and tried again a day later, like an install, or at
once when forced: nerve setup-transcription, or turning transcription back
on with a reload.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Telegram: files and voice messages do not reach the agent

2 participants