Skip to content

fix: disconnect old session on Telegram /attach switch - #29

Merged
saucam merged 1 commit into
mainfrom
fix/telegram-session-switch-leak
Jun 24, 2026
Merged

fix: disconnect old session on Telegram /attach switch#29
saucam merged 1 commit into
mainfrom
fix/telegram-session-switch-leak

Conversation

@saucam

@saucam saucam commented Jun 24, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Root cause: #handleAttach never called disconnectClient before attaching to a new session. Since every Telegram user has a fixed clientId (telegram:<userId>), switching sessions left the old session's client registration intact — causing it to keep streaming into the same chat. With 7 sessions cycled through, multiple old sessions accumulated as registered clients simultaneously.
  • #handleAttach: Calls disconnectClient, clears the streaming buffer, and deletes the dangling ⏹ Stop button before attaching to a different session (the Stop button normally gets deleted by the old session's idle status_change, which won't arrive after we disconnect).
  • #handleDetach: Consistently clears streaming buffer and stop-button state (previously only nulled attachedSessionId/attachedSessionName).

Test plan

  • src/tests/session-client-tracking.test.ts — 14 tests using real Session objects (no SDK); covers the regression shape (both sessions hold the client without detach), the fix (detach-then-attach routes only to new session), scrollback replay going to the correct send function, and the disconnectClient sweep across N sessions
  • src/tests/telegram-session-switch.test.ts — 17 tests mirroring the UserState state machine offline (no Grammy); covers first-attach, same-session re-attach, cross-session switch, streaming buffer isolation, stop-button deletion, and cycling through 7 sessions
  • Full suite: bun test src/tests src/daemon — 494 pass, 0 fail

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Improved Telegram session switching and detaching so chat state is cleaned up correctly.
    • Old session connections are now disconnected when switching sessions, and leftover streaming content is cleared.
    • The “⏹ Stop” control message is removed when no longer needed, preventing stale controls from staying in chat.

When a user ran /attach <new-session> without first /detaching, the old
session kept its client registration in the daemon and continued streaming
into the same Telegram chat. With 7 sessions and cycling between them,
multiple old sessions accumulated as registered clients simultaneously —
causing interleaved output and stale streaming/stop-button state.

Fix: #handleAttach now calls disconnectClient + clears streaming state
before attaching to a different session. Also deletes the ⏹ Stop button
for the old session (its idle status_change won't arrive after disconnect).
#handleDetach gets the same streaming + stop-button cleanup for consistency.

Tests:
- session-client-tracking.test.ts — real Session objects; covers the
  regression shape (both sessions hold the client without detach), the fix
  (detach-then-attach routes only to the new session), and the
  disconnectClient sweep pattern across N sessions.
- telegram-session-switch.test.ts — mirrors UserState state machine;
  covers all switch/detach state transitions offline (no Grammy dep).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jun 24, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Extends Telegram attach and detach handlers to clean up streaming buffer content and delete any active stop-control message when switching or leaving sessions. Two new test files are added: one for Session client-tracking invariants and one for the Telegram-specific attach/detach/switch state logic using offline helpers.

Changes

Telegram session attach/detach cleanup

Layer / File(s) Summary
Attach/detach cleanup in Telegram frontend
src/frontends/telegram/index.ts
On /attach to a different session, disconnects the prior client, clears session ids, empties the streaming buffer, and deletes any active stop-control message. On /detach, also clears the streaming buffer and deletes the stop-control message in addition to existing disconnect logic.
Session client-tracking unit tests
src/tests/session-client-tracking.test.ts
Tests Session.attach/detach count invariants, same-clientId replacement, scrollback replay delivery, and the detach-then-attach session-switch regression with cross-session sweep behavior.
Telegram session-switch and detach logic tests
src/tests/telegram-session-switch.test.ts
Offline UserState types and performSwitch/performDetach helpers drive test cases for first-time attach, same-session reattach, stop-message deletion, multi-session cycling, and streaming buffer isolation across switches.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly reflects the main change: disconnecting the old Telegram session when /attach switches sessions.
Docstring Coverage ✅ Passed Docstring coverage is 85.71% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/telegram-session-switch-leak

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install failed. For unrecoverable errors, disable the tool in CodeRabbit configuration.


Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Jun 24, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 58.34%. Comparing base (f5f46e9) to head (7471ee7).
⚠️ Report is 4 commits behind head on main.
✅ All tests successful. No failed tests found.

Additional details and impacted files
@@             Coverage Diff             @@
##             main      #29       +/-   ##
===========================================
- Coverage   80.61%   58.34%   -22.27%     
===========================================
  Files          45       46        +1     
  Lines        4782     6943     +2161     
===========================================
+ Hits         3855     4051      +196     
- Misses        927     2892     +1965     
Flag Coverage Δ
daemon 58.34% <ø> (-22.27%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.
see 2 files with indirect coverage changes

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai 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.

🧹 Nitpick comments (1)
src/tests/telegram-session-switch.test.ts (1)

24-112: 📐 Maintainability & Code Quality | 🔵 Trivial | 🏗️ Heavy lift

Avoid testing a duplicated state machine copy.

performSwitch/performDetach mirror production behavior, so tests can still pass when real handler logic drifts. Extract the cleanup/switch logic into shared pure helpers and import them here to test the real contract.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/tests/telegram-session-switch.test.ts` around lines 24 - 112, The tests
are exercising a duplicated copy of the session switch/detach state machine
instead of the real contract, so drift in `#handleAttach` and `#handleDetach` can go
unnoticed. Extract the cleanup/switch behavior into shared pure helpers used by
TelegramFrontend, then update the test to import and verify those helpers
directly rather than maintaining local mirrors like performSwitch and
performDetach.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/tests/telegram-session-switch.test.ts`:
- Around line 24-112: The tests are exercising a duplicated copy of the session
switch/detach state machine instead of the real contract, so drift in
`#handleAttach` and `#handleDetach` can go unnoticed. Extract the cleanup/switch
behavior into shared pure helpers used by TelegramFrontend, then update the test
to import and verify those helpers directly rather than maintaining local
mirrors like performSwitch and performDetach.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: a5a8c6da-0788-4ef8-9344-a703e66bf236

📥 Commits

Reviewing files that changed from the base of the PR and between 721bc09 and 7471ee7.

📒 Files selected for processing (3)
  • src/frontends/telegram/index.ts
  • src/tests/session-client-tracking.test.ts
  • src/tests/telegram-session-switch.test.ts

@saucam
saucam merged commit 1f0f6d7 into main Jun 24, 2026
5 checks passed
@saucam saucam mentioned this pull request Jun 28, 2026
saucam added a commit that referenced this pull request Jun 28, 2026
Patch release rolling up six fixes/doc changes since v0.1.1:

- file explorer switches workdir on session change (#37)
- interrupted tool calls marked cancelled, not failed (#35)
- writeBatch guarded against in-flight streams; no TUI double-print (#33)
- TUI reconnects + re-mints token on JWT expiry (#34)
- Telegram /attach disconnects old session before switching (#29)
- richer README badges (#27)

Bumps package.json to 0.1.2 so the release.yml tag check passes, and
backfills the previously-undocumented 0.1.1 entry in the CHANGELOG.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
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.

1 participant