Commit graph

16236 commits

Author SHA1 Message Date
brooklyn!
7db2decbea
Merge pull request #67302 from NousResearch/bb/salvage-66870-focus-tab-hijack
fix(desktop): don't hijack the active tab on reactive pane unhide (supersedes #66870)
2026-07-19 00:03:55 -04:00
brooklyn!
360b07794b
docs(desktop): document the desktop plugin SDK (@hermes/plugin-sdk) (#67301)
Add an end-to-end developer guide for extending the native Hermes Desktop
app introduced in #60638: the HermesPlugin contract, PluginContext, every
contribution area (panes, routes, sidebar nav, status/title bar, palette,
keybinds, themes, composer, mount-scoped Contribute), the host API, the
React Query + nanostores data layer, the UI kit + theme variables, the
scoped ctx.rest/ctx.socket backend (plugin_api.py under /api/plugins/<id>)
and its separate enable gate, Settings/defaultEnabled/storage, bundled
plugins, the security model, pitfalls, and a full reference.

- Register the page in the sidebar under Extending -> Plugins.
- Disambiguate from the unrelated web-dashboard plugin SDK from both
  directions, and add a map-table row + a desktop user-guide pointer.
- Fill the gaps in the agent-facing hermes-desktop-plugins skill
  (ctx.rest/socket + backend, React Query, defaultEnabled, Contribute)
  and point it at the new reference so agents know the SDK when writing
  addons.
2026-07-19 04:02:17 +00:00
Austin Pickett
43776f109b
fix(desktop): prevent session rotation from stealing focus (#67118)
# Conflicts:
#	apps/desktop/src/app/session/hooks/use-session-state-cache.ts

Co-authored-by: UnathiCodex <theunathi@gmail.com>
2026-07-19 00:00:40 -04:00
Brooklyn Nicholson
fbb867f54f fix(desktop): don't hijack the active tab on reactive pane unhide
In the Focus layout `files` shares one tab group with `workspace`, so when the
first reply adopts a cwd the reactive files unhide fronted files and yanked the
active tab off the new session (~1s after the reply). #65375 fixed the sibling
"reactive unhide reopens a collapsed side" bug but frontPaneInGroup still stole
the active slot unconditionally.

Only take the active slot when the group's current active pane isn't itself
showable, so a reactive unhide can't steal focus from a pane the user is
viewing while still fronting a valid tab when nothing is shown.

Carries forward linfeng961's diagnosis + fix from #66870, reworked onto the
frontPaneInGroup path introduced by #65375.

Co-authored-by: linfeng961 <133505766+linfeng961@users.noreply.github.com>
2026-07-18 23:58:42 -04:00
brooklyn!
a5396765a2
Merge pull request #67298 from NousResearch/bb/salvage-66109-action-menu-tooltip
fix(desktop): restore tooltip-wrapped action-menu + dialog trigger clicks (supersedes #66109)
2026-07-18 23:58:35 -04:00
nousbot-eng
78f38e79cf
fmt(js): npm run fix on merge (#67297)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-07-19 03:57:22 +00:00
AmAzing129
84db32484f 🐛 fix(desktop): restore tooltip-wrapped trigger behavior 2026-07-18 23:52:42 -04:00
brooklyn!
667b98b5cf
Merge pull request #67296 from NousResearch/bb/composer-model-removed-fallback
fix(desktop): reseed composer when a sticky manual pick was removed from the catalog
2026-07-18 23:50:01 -04:00
David Metcalfe
4cdfcf568d
fix(desktop): don't auto-expand user-collapsed side on reactive unhide (#65375)
* fix(desktop): don't auto-expand user-collapsed side on reactive unhide

When `setTreePaneHidden(paneId, false)` was called for a workspace-gated
pane like `files` (bound to $hasWorkspace), it auto-called
`revealTreePane(paneId)` — which expanded the parent column even when
the user had explicitly collapsed it via Cmd+J.

That meant every session create / resume — anything that flipped
$currentCwd from empty to non-empty — silently re-opened the right
sidebar and persisted that open state to localStorage, so the original
session also showed the sidebar as open on return.

`setTreePaneHidden` is a state primitive; user-intent semantics (open
the side, front the tab) belong to `revealTreePane`. Drop the auto-call
and replace it with a narrower `frontPaneInGroup` helper that only
makes the pane the active tab in its group — visible the next time the
column is opened, without forcing it open now.

* fix(desktop): preserve explicit review reveal

---------

Co-authored-by: David Metcalfe <80915+DavidMetcalfe@users.noreply.github.com>
2026-07-18 23:49:37 -04:00
brooklyn!
4f4a4f0d43
Merge pull request #67236 from NousResearch/bb/tui-incremental-markdown
perf(tui): render streamed markdown incrementally per block
2026-07-18 23:47:15 -04:00
brooklyn!
e99a0f6a97
Merge pull request #67283 from NousResearch/bb/salvage-60980-apiserver-offload
fix(api_server): offload synchronous SessionDB calls off the event loop (supersedes #60980)
2026-07-18 23:47:03 -04:00
Brooklyn Nicholson
d5decee5ac fix(desktop): reseed composer when a sticky manual pick was removed
A manual composer pick stays sticky across new chats (intended), but if that
model later disappears from the provider/config, every new chat kept trying the
dead model and 404'd. Fall back to the profile default in that one case only.

refreshCurrentModel now consults the model-options cache the composer already
populates (no extra fetch): a manual pick is preserved unless manualPickRemoved()
proves it's gone — provider present, non-empty catalog, model absent. An
unknown/absent provider, an empty (re-auth/unconfigured) list, or a not-yet-loaded
catalog all preserve the pick, so a still-valid selection is never clobbered.
2026-07-18 23:44:40 -04:00
Brooklyn Nicholson
24b44d56a3 refactor(tui): tighten StreamingMd comments and fence folding
Condense the header rationale to the load-bearing invariants and inline
the single-line math-fence guards. No behavior change; scanner logic and
public surface (createScanState / advanceScan / findStableBoundary)
unchanged.
2026-07-18 23:42:10 -04:00
kshitijk4poor
9ef66ea8c1 test: expect restored human anchor after user-role summary compaction
_is_real_user_message no longer accepts a user-role compaction summary as
the human anchor, so _compress_context restores the original user turn
after the summary; update the lifecycle-status test's expectation.
2026-07-19 08:55:08 +05:30
kshitijk4poor
c03c247e7c fix(compression): keep anchor restoration alternation-safe and grounding scaffolding-proof
Follow-up hardening on top of the salvaged #66637 commits:

- _insert_real_user_anchor could place the restored human turn directly
  next to user-role scaffolding (index-0 insert before a leading synthetic
  user turn, or a scaffolding-only transcript), breaking the strict
  alternation contract (#55677). Restoration now merges into trailing
  scaffolding (anchor text leads, synthetic flags cleared) and appends
  after a user-role compaction summary instead of inserting adjacent.
- _is_real_user_message now also rejects user-role compaction summaries
  (the compressor pins the summary to role=user when the tail opens with
  an assistant turn), so a summary can no longer satisfy the human-anchor
  check and skip restoration.
- _latest_user_task_snapshot reuses the same real-user predicate, so the
  deterministic task snapshot can no longer anchor on todo snapshots,
  truncation notices, or background-process reports.
- The Historical Task Snapshot rewrite keeps the section terminated with
  a blank line; the previous replacement consumed the boundary newlines,
  gluing the next '## ' heading mid-line and deleting all later sections
  on the next iterative compaction.
- Drop _length_continuation_synthetic (no producer anywhere).
- AUTHOR_MAP entry for enzo-adami.
2026-07-19 08:55:08 +05:30
Enzo Adami
d511ce0602 test: assert durable compression rotation 2026-07-19 08:55:08 +05:30
Enzo Adami
2f824ec5d2 test: align string summaries with grounded task snapshot 2026-07-19 08:55:08 +05:30
Enzo Adami
761a0b124e fix: ground compression task snapshot 2026-07-19 08:55:08 +05:30
Enzo Adami
960abf73a0 fix(compression): preserve human intent and durable handoffs 2026-07-19 08:55:08 +05:30
brooklyn!
d015500d45
Merge pull request #67287 from NousResearch/bb/salvage-38614-resume-cwd
fix(cli): restore session cwd on mid-chat /resume and /sessions (supersedes #38614)
2026-07-18 23:25:02 -04:00
nousbot-eng
73fea7b2b0
fmt(js): npm run fix on merge (#67284)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-07-19 03:21:18 +00:00
Brooklyn Nicholson
3700ca4a54 fix(cli): restore session cwd on mid-chat /resume (transplant to mixin)
Dusk1e's fix wired _restore_session_cwd into _handle_resume_command, but that
handler was extracted from cli.py into hermes_cli/cli_commands_mixin.py
(094aa85c3) after the PR's base, so the original cli.py hunk no longer applied
(a naive cherry-pick fuzzily misplaced it inside new_session(), where
session_meta is undefined). Transplanted the call to the end of the handler in
its current home; /sessions <id> delegates here so both command forms are
covered. Dusk1e's regression tests carry over unchanged.

Co-authored-by: Dusk1e <yusufalweshdemir@gmail.com>
2026-07-18 23:20:32 -04:00
Dusk1e
228d8de19c fix(cli): restore session cwd on mid-chat /resume and /sessions 2026-07-18 23:20:19 -04:00
Brooklyn Nicholson
d2cb318509 fix(api_server): reconcile SessionDB offload with per-profile DB routing
Rebased onto current main, where _ensure_session_db grew a per-profile
cache (get_hermes_home()-keyed) for /p/<profile>/ multiplex — after this
PR's base. The PR's async rewrite assumed the old single-self._session_db
model, so on current main `session_db=self._session_db` in _create_agent
would pass None in production (the real DB lives in the per-home cache).

Split the concern: keep a SYNC _ensure_session_db (per-profile, used by
_create_agent + the many sync-patching create_agent tests) and add an
async _ensure_session_db_async that captures the profile home on the loop
thread then offloads only the SQLite open via to_thread (single-flight).
Both share _open_and_cache_session_db. Request handlers use the async
variant; _create_agent reverts to the sync call. Updated the first-request
test's FakeDB to accept db_path to match main's SessionDB(db_path=...).

Co-authored-by: necoweb3 <sswdarius@gmail.com>
2026-07-18 23:14:57 -04:00
brooklyn!
f099b469de
Merge pull request #67282 from NousResearch/bb/unify-project-status
feat: unify active-project identity in chat status (supersedes #64721)
2026-07-18 23:13:52 -04:00
Brooklyn Nicholson
66a7825ebb feat: unify active-project identity in chat status (supersedes #64721)
Surface the session's first-class Project in both chat surfaces: the
Desktop status bar (project name as the workspace label, full cwd in the
tooltip) and the TUI status label + /status output.

One source of truth. The per-profile projects.db is the authority, read
in tui_gateway via _project_info_for_cwd (backed by
projects_db.project_for_path) and threaded through every session.info
emission path the TUI consumes. The Desktop already caches that truth in
$projectTree, so it DERIVES the label from it (projectNameForCwd) instead
of carrying a second per-session $currentProject atom fed from
session.info.

That drops the parallel state #64721 introduced and the entire
reset/reconciliation surface it required (resume, agentless cwd.set,
gateway-switch, fresh-draft): the label is purely derived, so it stays
correct whenever the cwd or the project tree changes. Only explicit,
named projects resolve on both surfaces, so an auto-discovered repo root
keeps the cwd-leaf label everywhere.

Excludes the unrelated markdown shell-fence change bundled in #64721.
2026-07-18 23:08:13 -04:00
dsad
5529175084 fix: TOCTOU race in session create + offload SessionDB init
- Make create sequence (check + insert + title) atomic via single
  _execute_write call with BEGIN IMMEDIATE, closing the TOCTOU window
  where two concurrent same-ID creates could both return 201.

- Offload _ensure_session_db() to asyncio.to_thread with single-flight
  lock so first-request SQLite init doesn't block the event loop.

- Add concurrent same-ID create test (one 201, one 409) and
  first-request path test covering the initialization.
2026-07-18 23:07:29 -04:00
dsad
7ba944d054 fix(api_server): offload synchronous SessionDB calls off the event loop 2026-07-18 23:06:17 -04:00
kshitijk4poor
c7035ef252 fix: add api_content to _CONVERSATION_ROW_COLUMNS for get_resume_conversations
The PR added api_content to get_messages_as_conversation's inline SELECT
but missed the shared _CONVERSATION_ROW_COLUMNS constant used by
get_resume_conversations — _rows_to_conversation references
row["api_content"] but the column wasn't in the SELECT, causing
IndexError on resume-session tests.

Co-authored-by: Soju06 <qlskssk@gmail.com>
2026-07-19 08:25:35 +05:30
kshitijk4poor
39efad89a8 refactor: shared helpers for api_content sidecar pop/drop/extract
Deduplicates the sidecar handling across 9 sites:
- substitute_api_content(): 2 API-bound pop+substitute sites
  (chat_completion_helpers, transport — conversation_loop keeps its
  inline pop because the current-turn compose fallback needs the value)
- drop_stale_api_content(): 4 rewrite-drop sites
  (context_compressor x2, replay_cleanup, agent_runtime_helpers)
- extract_api_content_sidecar(): 3 gateway forwarding sites
  (gateway/session, gateway/slash_commands, cli_commands_mixin)

Also: restore the eager _pending_cli_user_message clear on the early
row-creation try (was lost when the crash-persist moved after prefetch —
a crash in compression between the two tries would leave a stale staged
input), and fix a comment indentation nit in run_agent.py.

Co-authored-by: Soju06 <qlskssk@gmail.com>
2026-07-19 08:25:35 +05:30
Soju06
7b3dcee928 feat(cache): persist the exact bytes sent to the API in an api_content sidecar
The first LLM call of every gateway turn gets ~0% provider prompt-cache
hit rate (in-turn calls: 97-99%) because the bytes sent for a turn's
user message are not the bytes replayed next turn: memory-prefetch and
pre_llm_call context are injected into the API copy only, the #48677
persist override writes cleaned content to the DB row, and
get_messages_as_conversation sanitize/strips user and assistant content
on load. Any of these diverges the request prefix at that message and
re-prefills everything after it — measured 27.9s for the first call vs
2.4-5.8s cached at a median ~156k-token context.

Persist what you send: a nullable messages.api_content column stores the
exact content string sent to the API when it differs from the clean
stored content, and replay substitutes it verbatim (no sanitize, no
strip). The injection composition lives in one helper
(turn_context.compose_user_api_content); the turn prologue stamps its
output onto the live user message, the api_messages build sends the
stamped bytes, and every outgoing copy pops the field so it never
reaches a provider. The crash-resilience user-turn persist moves after
prefetch/pre_llm_call so the user row is written once with its final
sidecar; _ensure_db_session stays before preflight compression (session
rotation needs the parent row under PRAGMA foreign_keys=ON). The
current-turn index trackers are re-anchored after compaction rebuilds
the message list, in-place preflight compaction backfills the stamp onto
the already-inserted row, and gateway replay forwards the sidecar only
when the replay pipeline did not rewrite the content. Rewrite paths that
would leave stale bytes (historical image strip, merge-summary-into-
tail, consecutive-user repair merge, stale-confirmation redaction) drop
the sidecar; the chat-completions transport and the max-iterations
summary path strip it defensively. codex_app_server and MoA turns are
excluded from stamping because their wire bytes differ from the
composition. A missing or dropped sidecar degrades to today's behavior
(one cache-boundary miss), never to wrong content.
2026-07-19 08:25:35 +05:30
brooklyn!
e53f87fe69
Merge pull request #67238 from NousResearch/bb/anthropic-owner-thread-abort
fix(agent): request-local Anthropic clients so the stale/interrupt watchdog never corrupts SQLite (#67142, supersedes #51688)
2026-07-18 22:37:40 -04:00
nousbot-eng
19bf16c4da
fmt(js): npm run fix on merge (#67258)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-07-19 02:27:32 +00:00
brooklyn!
8e9c176117
Merge pull request #67245 from NousResearch/bb/desktop-sidebar-batch
perf(desktop): batch sidebar session slices into one profile-DB pass
2026-07-18 22:21:12 -04:00
brooklyn!
ea1cc1dd4b
Merge pull request #67247 from NousResearch/bb/desktop-resume-single-read
perf(gateway): serve session.resume model + display history from one SELECT
2026-07-18 22:18:39 -04:00
Brooklyn Nicholson
fbabdfbe15 bench(tui): add per-append timing series mode to streaming-md bench 2026-07-18 22:16:23 -04:00
kshitijk4poor
66ed9d63fe refactor: extract 6 copy-paste voice interrupt blocks into one helper
The busy/priority/monitor/backup×2/drain paths each had near-identical
try/except blocks for transcribe+echo with only log_context, adapter,
and metadata varying. Extract into _transcribe_and_echo_pending_voice
which handles the cache lookup, echo dedup, and exception logging in
one place.

Uses a _UNSET sentinel to distinguish 'caller did not pass metadata'
(use the rich _thread_metadata_for_source fallback) from 'caller
explicitly passed None' (monitor/backup/drain paths that use the
simpler thread_id-only dict).

~120 lines of copy-paste collapsed into one 30-line helper.
2026-07-19 07:27:29 +05:30
kshitijk4poor
bca886c844 fix(gateway): invalidate pending STT cache when media merges into event
merge_pending_message_event extends the existing event's media_urls in
place when two media-bearing messages arrive in quick succession (photo
bursts, consecutive voice messages).  The gateway runner caches STT
transcripts on the event via _gateway_pending_stt_text; if the cached
event gains new media after the cache was populated, the stale transcript
was returned instead of transcribing the merged attachments.

Add _invalidate_pending_stt_cache() and call it from both media-merge
branches in merge_pending_message_event so the next transcription call
re-runs against the full merged media list.

Closes the merge-race edge case identified during review of PR #61519.
2026-07-19 07:27:29 +05:30
kshitijk4poor
5920b305f4 refactor: delete dead _dequeue_pending_with_transcription
The function was introduced in d55304c39 but never had a single caller —
verified via git log -S and search_files across the whole repo. The
drain path at _stream_confirmed_final_delivery inlines its logic directly.
Keeping a dead function around that duplicates live logic is a maintenance
hazard: future changes to the live path won't propagate to the dead one.
2026-07-19 07:27:29 +05:30
yu-xin-c
6a135142cc test(gateway): use compression helper in voice regression 2026-07-19 07:27:29 +05:30
yu-xin-c
7b330b1d22 fix(gateway): preserve pending voice media semantics 2026-07-19 07:27:29 +05:30
yu-xin-c
f5d493aebf fix(gateway): dedupe pending voice transcript echoes 2026-07-19 07:27:29 +05:30
kshitijk4poor
71157cbf66 refactor(turn_finalizer): extract _is_pure_tool_call_tail, fix SQLite durability
Extract the inline pure-tool-call tail check to a named helper using
flatten_message_text (canonical content extraction). Fix a SQLite
durability regression: the incremental tool-call persist
(conversation_loop.py:4990) stamps _DB_PERSISTED_MARKER on the assistant
row, so the next _persist_session flush skips it — the filled content
reaches the in-memory transcript but NOT the durable store, and /resume
reloads content="". Pop the marker so the next flush re-writes the row.

Tests pass, ruff clean.
2026-07-19 07:27:10 +05:30
Frowtek
56ac96976b fix(agent): persist the delivered response when the turn tail is a tool-call row
`finalize_turn` guarantees the invariant "delivered final_response =>
assistant row in transcript" (#43849 / #44100) for recovery paths that
return a response without appending a closing assistant message. It
enforces it by checking only the tail's ROLE:

    if _tail_role != "assistant":
        messages.append({"role": "assistant", "content": final_response})

A tail that is a *pure tool-call turn* — `assistant(tool_calls=[...])`
with no text of its own — satisfies that check while carrying none of the
delivered answer. The append is skipped and the response is never
persisted, so the durable transcript ends at an assistant row the user
never saw as the reply. On the next turn the model replays the user
backlog and re-answers it: exactly the symptom the block was added to
prevent, just reached through a different tail shape.

Observed with the real finalizer: with messages ending
`user -> assistant(content="", tool_calls=[t1])` and
`final_response="Here is your answer."`, the persisted transcript keeps
`content=""` and the answer is absent.

Fill that row's empty content instead of appending. This keeps the
invariant without disturbing the tool-call structure and without creating
an assistant->assistant pair. A tail tool-call row that already carries
model text is left untouched, so no model output is ever overwritten.

Adds regression tests for both: the empty tool-call tail is filled, and a
tool-call tail with existing text is not clobbered.
2026-07-19 07:27:10 +05:30
Brooklyn Nicholson
206953fb66 perf(gateway): serve session.resume's model + display history from one SELECT
session.resume built two projections of the same lineage with two separate
get_messages_as_conversation calls — the model-fed copy (tip rows, alternation-
repaired) and the display copy (full lineage, verbatim). The display fetch
already reads a superset of the model fetch (the tip rows are part of the
lineage), so the second call re-scanned the same messages.

Add SessionDB.get_resume_conversations(): one lineage SELECT, split into the tip
(model) and full (display) projections in memory via the extracted
_rows_to_conversation helper. Byte-identical to the two separate reads
(test_get_resume_conversations_matches_separate_reads covers a lineage with a
dangling tool-call tail so repair diverges the two lengths, a single session,
and replayed-user dedup). Both session.resume build paths (deferred + eager) now
use it; the subagent single-read path is unchanged.

From the Desktop performance audit (P1: "Remove repeated resume transcript
work") — the gateway half. The renderer's concurrent REST prefetch is left as-is
(the audit flags dropping it as measure-first).
2026-07-18 21:50:26 -04:00
brooklyn!
7235592ad2
Merge pull request #67241 from NousResearch/bb/telegram-reconnect-watchdog
fix(telegram): cause-agnostic wedged-recovery watchdog + bounded drain so the reconnect ladder can't freeze silently (#66377, supersedes #66492)
2026-07-18 21:48:19 -04:00
Brooklyn Nicholson
40160e2a04 perf(desktop): batch sidebar session slices into one profile-DB pass
The sidebar refresh fired three /api/profiles/sessions calls (recents, cron,
messaging), and each one reopened every selected profile's state.db and re-ran
list_sessions_rich + session_count — ~3N DB opens/counts per refresh, on every
turn/broadcast/reconnect.

Add GET /api/profiles/sessions/sidebar: one pass that opens each profile DB
once and runs the three source-scoped queries together (recents scoped to the
active profile; cron + messaging cross-profile), returning the three windows in
one payload. Same read-only projection, 300s active heuristic, and caller-
supplied source taxonomy (recents_exclude / messaging_exclude / source=cron) as
the per-slice endpoint.

Renderer refreshSessions now makes one listSidebarSessions call and distributes
recents/cron/messaging to their stores (cron *jobs* stay a separate getCronJobs
API). Electron splices remote profiles per slice via fetchProfilesSessionSlice
(reusing the proven per-slice merge) so remote correctness is preserved; the
no-remote common case gets the single-open fast path.

From the Desktop performance audit (P1: "Batch sidebar session slices").
2026-07-18 21:45:18 -04:00
Brooklyn Nicholson
23d2fd5d78 chore(contributors): map mkoduri73@gmail.com -> MaheshBhushan
Attribution mapping for the salvaged #66492 commit (#66377).
2026-07-18 21:38:20 -04:00
Brooklyn Nicholson
c2cb37532c fix(telegram): add cause-agnostic wedged-recovery watchdog so the reconnect ladder can't freeze silently (#66377)
The Telegram gateway could go silently deaf for hours: the reconnect ladder
stalled mid-way (e.g. "attempt 4/10, reconnecting in 40s" then nothing) while
the process stayed active(running), so Restart=always never fired.

Root class: every recovery path — the ladder's re-entry
(_schedule_polling_recovery), the pending-update probe (_probe_pending_updates),
and PTB's error callback — gates new recovery on _polling_error_task.done(). If
that single task wedges on any hung await, all recovery returns early forever
and nothing retries.

The heartbeat loop is a separate task, so make it an independent, cause-agnostic
watchdog: if the same recovery task stays in-flight past
_POLLING_ERROR_TASK_STUCK_TIMEOUT (300s — well beyond a healthy ladder attempt's
bounded stop+drain+start+backoff), force a retryable-fatal so the background
reconnector rebuilds the adapter instead of relying on the frozen ladder. This
guarantees progress regardless of *where* the stall is (issue direction #1),
tracked locally so no task-assignment site needs to change.

Also salvages @koduri-mahesh-bhushan-chowdary's #66492 (drain-await timeout),
which closes the one concrete wedge vector documented in the incident
(_drain_polling_connections' unbounded shutdown()/initialize() on a wedged
CLOSE-WAIT pool). The watchdog covers the rest of the class.

Co-authored-by: Koduri Mahesh Bhushan Chowdary <mkoduri73@gmail.com>
2026-07-18 21:31:15 -04:00
Koduri Mahesh Bhushan Chowdary
3391e639f6 fix(telegram): bound polling drain so wedged pool close can't stall reconnect ladder (#66377)
_drain_polling_connections() awaited polling_req.shutdown() and
.initialize() without a timeout. When the getUpdates httpx connection is
wedged on a stale CLOSE-WAIT socket, that close can block forever, hanging
_handle_polling_network_error (the tracked _polling_error_task). The task
never completes, so every escalation path — _schedule_polling_recovery,
_probe_pending_updates, the heartbeat verifier — stays gated behind its
in-flight guard, the ladder freezes mid-way, _set_fatal_error is never
reached, and Restart=always never fires: the gateway is alive but silently
dead.

Wrap both drain awaits in asyncio.wait_for with a new module-level
_DRAIN_TIMEOUT (15.0s, matching _UPDATER_STOP_TIMEOUT), mirroring the
existing bounded stop()/start_polling() sites. On timeout the drain logs and
continues, so the handler task completes and the ladder always advances
toward the fatal-restart escalation.

Adds test_reconnect_continues_if_drain_hangs, which wedges the drain and
asserts the handler still reaches start_polling within a hard bound.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-18 21:23:11 -04:00