SIGN IN SIGN UP

AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.

0 0 73 Python

fix(backend/copilot-bot): recover deleted chat sessions instead of erroring (#13197)

### Why / What / How

**Why:** Deleting a Copilot chat session on the web app permanently
bricks the corresponding Discord thread/DM. The bot caches the
`session_id` in Redis under its own key
(`copilot-bot:session:<platform>:<target_id>`). When the session is
deleted on the web, `delete_chat_session` destroys the DB row and clears
the *copilot* session cache — but it has no knowledge of the bot's
mapping key, so that key keeps pointing at the dead session. The next
message resolves the stale ID, `start_chat_turn` raises
`NotFoundError("Session not found.")`, and since nothing ever clears the
stale key, **every subsequent message fails identically**. Reported by
Abhi during bot testing.

**What:** `start_chat_turn` now treats an unresolved `session_id` as
"start fresh" instead of erroring — the conversation self-heals.

**How:** When the provided `session_id` doesn't resolve to a session
(deleted, expired, or otherwise gone), fall back to
`create_chat_session(...)` rather than raising. The handle then carries
the new session ID, and the existing `on_session_id` callback
(`bot_backend.stream_chat` → `handler._on_session_id`) writes it back
into the bot's Redis cache — so the thread recovers automatically on the
next message. This also covers session deletion by *any* cause, not just
the web app. `start_chat_turn` is bot-only (sole caller is the
`PlatformLinkingManager` RPC wrapper), and the `source_platform` value
introduced in #13175 is preserved.

### Changes 🏗️

- `platform_linking/chat.py` — `start_chat_turn` falls back to a fresh
session when a provided `session_id` no longer resolves, instead of
raising `NotFoundError`.
- `platform_linking/chat_test.py` — replaced
`test_existing_session_id_wrong_user_raises_not_found` with
`test_stale_session_id_falls_back_to_fresh_session`, which reproduces
the bug and verifies the recovery.

### Checklist 📋

#### For code changes:
- [x] I have clearly listed my changes in the PR description
- [x] I have made a test plan
- [x] I have tested my changes according to the test plan:
- [x] `test_stale_session_id_falls_back_to_fresh_session` fails against
the pre-fix code (reproduces the bricked thread) and passes after the
fix
- [x] Full `platform_linking/chat_test.py` suite green (4 passed),
`black` + `ruff` + `pyright` clean
B
Bently committed
b5ab847840d03a0b4853ee39aff41d9b8eaf862f
Parent: 8cc3072
Committed by GitHub <noreply@github.com> on 5/27/2026, 1:02:51 PM